@zeyos/zx 5.6.0 → 5.7.1

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 (227) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/README.md +73 -7
  3. package/bin/zx-css.js +328 -0
  4. package/dist/types/components/account-menu/account-menu.d.ts +4 -2
  5. package/dist/types/components/activity-list/activity-list.d.ts +14 -8
  6. package/dist/types/components/agent-thread/ag-ui.d.ts +340 -0
  7. package/dist/types/components/agent-thread/agent-thread.d.ts +142 -14
  8. package/dist/types/components/agent-thread/ui-message-stream.d.ts +401 -0
  9. package/dist/types/components/app-sidebar/app-sidebar.d.ts +14 -8
  10. package/dist/types/components/breadcrumb/breadcrumb.d.ts +3 -3
  11. package/dist/types/components/calendar/calendar-model.d.ts +9 -2
  12. package/dist/types/components/calendar/calendar.d.ts +12 -4
  13. package/dist/types/components/chart/chart.d.ts +25 -13
  14. package/dist/types/components/checklist/checklist.d.ts +29 -0
  15. package/dist/types/components/code-editor/code-editor.d.ts +7 -2
  16. package/dist/types/components/composer/composer.d.ts +206 -4
  17. package/dist/types/components/composer/queue.d.ts +76 -0
  18. package/dist/types/components/copy/copy-button.d.ts +6 -4
  19. package/dist/types/components/copy/copy-input.d.ts +10 -6
  20. package/dist/types/components/datebox/date-range-box.d.ts +33 -0
  21. package/dist/types/components/datebox/placeholder.d.ts +7 -0
  22. package/dist/types/components/dialog/dialog.d.ts +2 -2
  23. package/dist/types/components/dock/dock.d.ts +12 -3
  24. package/dist/types/components/entity-ref/entity-ref.d.ts +5 -3
  25. package/dist/types/components/field-upload/field-upload.d.ts +3 -2
  26. package/dist/types/components/file-item/file-item.d.ts +3 -2
  27. package/dist/types/components/file-list/file-list.d.ts +14 -8
  28. package/dist/types/components/filter/filter-model.d.ts +31 -1
  29. package/dist/types/components/filter/filter.d.ts +20 -2
  30. package/dist/types/components/finder/finder.d.ts +14 -6
  31. package/dist/types/components/flag/flag.d.ts +99 -0
  32. package/dist/types/components/grid/grid.d.ts +1 -1
  33. package/dist/types/components/kanban-view/kanban-view.d.ts +8 -66
  34. package/dist/types/components/launcher/launcher.d.ts +2 -0
  35. package/dist/types/components/modal/modal.d.ts +34 -8
  36. package/dist/types/components/multi-value-editor/multi-value-editor.d.ts +3 -2
  37. package/dist/types/components/number-field/number-field.d.ts +41 -7
  38. package/dist/types/components/prompt-starters/prompt-starters.d.ts +107 -0
  39. package/dist/types/components/prose/prose.d.ts +9 -6
  40. package/dist/types/components/questionnaire/conditions.d.ts +270 -0
  41. package/dist/types/components/questionnaire/items.d.ts +52 -30
  42. package/dist/types/components/questionnaire/questionnaire.d.ts +44 -4
  43. package/dist/types/components/rating/rating.d.ts +5 -3
  44. package/dist/types/components/select/country.d.ts +106 -0
  45. package/dist/types/components/select/field-adapter.d.ts +2 -1
  46. package/dist/types/components/select/locale.d.ts +102 -0
  47. package/dist/types/components/select/select.d.ts +41 -2
  48. package/dist/types/components/sheet/sheet.d.ts +2 -2
  49. package/dist/types/components/slider/slider.d.ts +1 -0
  50. package/dist/types/components/sort-control/sort-control.d.ts +7 -3
  51. package/dist/types/components/source-list/source-list.d.ts +7 -5
  52. package/dist/types/components/split-view/split-view.d.ts +5 -3
  53. package/dist/types/components/surface/catalog.d.ts +260 -0
  54. package/dist/types/components/surface/elicit.d.ts +81 -0
  55. package/dist/types/components/surface/mcp.d.ts +165 -0
  56. package/dist/types/components/surface/schema.d.ts +314 -0
  57. package/dist/types/components/surface/stream.d.ts +118 -0
  58. package/dist/types/components/surface/surface.d.ts +718 -0
  59. package/dist/types/components/surface/text.d.ts +277 -0
  60. package/dist/types/components/surface/validate.d.ts +339 -0
  61. package/dist/types/components/table/table.d.ts +55 -3
  62. package/dist/types/components/table/window.d.ts +203 -0
  63. package/dist/types/components/toolbar/toolbar.d.ts +10 -6
  64. package/dist/types/components/tooltip/tooltip.d.ts +2 -2
  65. package/dist/types/components/tree/tree.d.ts +20 -13
  66. package/dist/types/core/component.d.ts +10 -0
  67. package/dist/types/core/date.d.ts +8 -1
  68. package/dist/types/core/dom.d.ts +15 -0
  69. package/dist/types/core/http.d.ts +10 -0
  70. package/dist/types/core/i18n.d.ts +38 -0
  71. package/dist/types/core/messages.d.ts +344 -1
  72. package/dist/types/core/storage.d.ts +7 -2
  73. package/dist/types/elements/define.d.ts +21 -46
  74. package/dist/types/elements/definitions.d.ts +147 -0
  75. package/dist/types/elements/kit.d.ts +7 -0
  76. package/dist/types/elements/reflect.d.ts +6 -3
  77. package/dist/types/index.d.ts +10 -1
  78. package/dist/types/internal/date-locale.d.ts +7 -0
  79. package/dist/types/internal/json-patch.d.ts +146 -0
  80. package/dist/types/locales/de.d.ts +13 -0
  81. package/dist/types/locales/en.d.ts +2 -0
  82. package/dist/types/locales/index.d.ts +823 -0
  83. package/dist/types/zeyos/view.d.ts +8 -1
  84. package/dist/zx-zeyos.esm.js +16852 -15131
  85. package/dist/zx-zeyos.esm.min.js +5 -5
  86. package/dist/zx.core.css +1276 -0
  87. package/dist/zx.core.min.css +1 -0
  88. package/dist/zx.css +520 -143
  89. package/dist/zx.esm.js +40940 -29684
  90. package/dist/zx.esm.min.js +36 -23
  91. package/dist/zx.global.js +40940 -29684
  92. package/dist/zx.global.min.js +36 -23
  93. package/dist/zx.layered.css +17315 -0
  94. package/dist/zx.layered.min.css +1 -0
  95. package/dist/zx.min.css +1 -1
  96. package/docs/agent-catalog.json +12501 -0
  97. package/docs/agent-surfaces.md +340 -0
  98. package/docs/api.json +909 -137
  99. package/docs/llms.md +1046 -80
  100. package/docs/llms.txt +30 -9
  101. package/package.json +29 -6
  102. package/src/components/account-menu/account-menu.js +6 -3
  103. package/src/components/activity-item/activity-item.js +2 -1
  104. package/src/components/activity-list/activity-list.js +16 -10
  105. package/src/components/agent-thread/ag-ui.js +1439 -0
  106. package/src/components/agent-thread/agent-thread.js +359 -54
  107. package/src/components/agent-thread/ui-message-stream.js +1281 -0
  108. package/src/components/app-sidebar/app-sidebar.js +18 -8
  109. package/src/components/approval-card/approval-card.js +3 -2
  110. package/src/components/block-view/block-view.js +7 -6
  111. package/src/components/breadcrumb/breadcrumb.js +8 -5
  112. package/src/components/button/button.css +24 -11
  113. package/src/components/calendar/calendar-model.js +8 -2
  114. package/src/components/calendar/calendar.js +53 -18
  115. package/src/components/chart/chart.js +54 -23
  116. package/src/components/checklist/checklist.css +9 -1
  117. package/src/components/checklist/checklist.js +59 -3
  118. package/src/components/checklist/field-adapter.js +2 -11
  119. package/src/components/code-editor/code-editor.js +45 -8
  120. package/src/components/code-editor/field-adapter.js +1 -1
  121. package/src/components/composer/composer.css +80 -1
  122. package/src/components/composer/composer.js +390 -16
  123. package/src/components/composer/queue.js +78 -0
  124. package/src/components/context-menu/context-menu.js +12 -1
  125. package/src/components/copy/copy-button.js +9 -7
  126. package/src/components/copy/copy-input.js +10 -6
  127. package/src/components/date-picker/date-picker.js +2 -1
  128. package/src/components/date-picker/date-range-picker.js +8 -7
  129. package/src/components/datebox/date-range-box.js +3 -9
  130. package/src/components/datebox/datebox.js +18 -21
  131. package/src/components/datebox/placeholder.js +18 -0
  132. package/src/components/dialog/dialog.js +4 -5
  133. package/src/components/dock/dock.js +34 -13
  134. package/src/components/entity-ref/entity-ref.js +16 -5
  135. package/src/components/field-upload/field-upload.js +81 -38
  136. package/src/components/file-item/file-item.js +70 -40
  137. package/src/components/file-list/file-list.js +15 -9
  138. package/src/components/filter/filter-model.js +46 -8
  139. package/src/components/filter/filter.css +3 -3
  140. package/src/components/filter/filter.js +29 -10
  141. package/src/components/filter-panel/filter-panel.js +13 -5
  142. package/src/components/finder/finder.js +50 -26
  143. package/src/components/flag/flag.css +40 -0
  144. package/src/components/flag/flag.js +177 -0
  145. package/src/components/form/form.js +1 -1
  146. package/src/components/grid/grid.js +22 -8
  147. package/src/components/kanban-view/kanban-view.js +51 -81
  148. package/src/components/launcher/launcher.js +17 -2
  149. package/src/components/list-toolbar/list-toolbar.js +2 -1
  150. package/src/components/master-panel/master-panel.js +1 -1
  151. package/src/components/menu-button/menu-button.js +4 -0
  152. package/src/components/message/message.js +3 -0
  153. package/src/components/modal/modal.js +62 -8
  154. package/src/components/multi-value-editor/multi-value-editor.js +10 -9
  155. package/src/components/navigation-bar/navigation-bar.js +3 -3
  156. package/src/components/number-field/number-field.js +98 -29
  157. package/src/components/prompt-starters/prompt-starters.css +91 -0
  158. package/src/components/prompt-starters/prompt-starters.js +206 -0
  159. package/src/components/prose/prose.js +14 -10
  160. package/src/components/questionnaire/conditions.js +666 -0
  161. package/src/components/questionnaire/items.js +150 -41
  162. package/src/components/questionnaire/questionnaire.js +126 -32
  163. package/src/components/rating/rating.js +5 -4
  164. package/src/components/run-status/run-status.js +2 -2
  165. package/src/components/select/country.js +136 -0
  166. package/src/components/select/field-adapter.js +7 -2
  167. package/src/components/select/locale.js +219 -0
  168. package/src/components/select/select.css +20 -22
  169. package/src/components/select/select.js +94 -12
  170. package/src/components/sheet/sheet-stack.js +10 -1
  171. package/src/components/sheet/sheet.js +12 -5
  172. package/src/components/slider/slider.js +7 -2
  173. package/src/components/sort-control/sort-control.js +15 -5
  174. package/src/components/source-list/source-list.js +7 -4
  175. package/src/components/split-view/split-view.js +5 -3
  176. package/src/components/surface/catalog.js +1334 -0
  177. package/src/components/surface/elicit.js +107 -0
  178. package/src/components/surface/mcp.js +243 -0
  179. package/src/components/surface/schema.js +644 -0
  180. package/src/components/surface/stream.js +245 -0
  181. package/src/components/surface/surface.css +308 -0
  182. package/src/components/surface/surface.js +2291 -0
  183. package/src/components/surface/text.js +513 -0
  184. package/src/components/surface/validate.js +2218 -0
  185. package/src/components/tabbox/tabbox.js +9 -0
  186. package/src/components/table/table.css +63 -3
  187. package/src/components/table/table.js +167 -28
  188. package/src/components/table/window.js +317 -0
  189. package/src/components/toolbar/toolbar.js +12 -7
  190. package/src/components/tooltip/tooltip.css +2 -3
  191. package/src/components/tooltip/tooltip.js +32 -5
  192. package/src/components/tree/tree.js +53 -23
  193. package/src/core/component.js +25 -1
  194. package/src/core/date.js +62 -16
  195. package/src/core/dom.js +67 -4
  196. package/src/core/format.js +15 -13
  197. package/src/core/http.js +29 -20
  198. package/src/core/i18n.js +83 -10
  199. package/src/core/icons.js +13 -2
  200. package/src/core/keyboard.js +79 -8
  201. package/src/core/messages.js +376 -2
  202. package/src/core/overlay-host.js +1 -0
  203. package/src/core/position.js +3 -2
  204. package/src/core/storage.js +59 -6
  205. package/src/elements/define.js +178 -130
  206. package/src/elements/definitions.js +229 -0
  207. package/src/elements/kit.js +444 -0
  208. package/src/elements/reflect.js +8 -3
  209. package/src/index.js +10 -1
  210. package/src/internal/date-locale.js +11 -0
  211. package/src/internal/json-patch.js +405 -0
  212. package/src/locales/de.js +911 -0
  213. package/src/locales/en.js +2 -0
  214. package/src/locales/index.js +7 -0
  215. package/src/zeyos/calendar.js +2 -1
  216. package/src/zeyos/form.js +2 -1
  217. package/src/zeyos/launcher.js +7 -6
  218. package/src/zeyos/module-bar.js +2 -1
  219. package/src/zeyos/schema.js +37 -23
  220. package/src/zeyos/select.js +4 -3
  221. package/src/zeyos/table.js +2 -13
  222. package/src/zeyos/view.js +57 -17
  223. package/styles/core.css +11 -0
  224. package/styles/tokens/semantic.css +1 -0
  225. package/styles/zeyos.css +2 -0
  226. package/styles/zx.css +4 -8
  227. package/styles/zx.layered.css +1 -0
@@ -0,0 +1,1334 @@
1
+ // @ts-check
2
+ /**
3
+ * The surface catalog: every intent and node a surface may use, and what is generated from it.
4
+ *
5
+ * The catalog is curated by hand. `surfaceSchema()`, `surfaceTools()` and `surfacePrompt()` turn it
6
+ * — or a catalog narrowed by `narrowCatalog()` — into the JSON Schema of the format, function-
7
+ * calling tool definitions and the guide a model reads, so a model is told exactly what will
8
+ * render. The module imports nothing that touches the DOM: a server can import it directly to
9
+ * build the same tools and prompt it hands to its model.
10
+ */
11
+ import { CONDITION_OPS, MAX_CONDITION_DEPTH, RULE_FORMATS } from '../questionnaire/conditions.js';
12
+ import { FIELD_TYPES, MAX_SCHEMA_CHOICES, MAX_SCHEMA_PROPERTIES, SCHEMA_FORMATS } from './schema.js';
13
+
14
+ /** The version a `begin` operation and a document carry. */
15
+ export const SURFACE_VERSION = 'surface/1';
16
+
17
+ /** The version every reply carries. */
18
+ export const REPLY_VERSION = 'reply/1';
19
+
20
+ /** The limits of one surface. Anything over a limit is dropped and reported. */
21
+ export const LIMITS = Object.freeze({
22
+ /** Nodes per surface. */
23
+ nodes: 400,
24
+ /** Depth of the node tree, counting the root's children as 1. */
25
+ depth: 12,
26
+ /** Characters per string. */
27
+ string: 20000,
28
+ /** Rows per table or diff, and entries per list or other array. */
29
+ rows: 1000,
30
+ /** Input schema properties per surface. */
31
+ fields: MAX_SCHEMA_PROPERTIES,
32
+ /** Choices per choice node or schema property. */
33
+ choices: MAX_SCHEMA_CHOICES,
34
+ /** Actions per surface. */
35
+ actions: 8,
36
+ /** Characters of the surface's data, written as JSON. */
37
+ data: 1000000,
38
+ /** Nesting of a `visible`, `when` or `if` condition. */
39
+ condition: MAX_CONDITION_DEPTH,
40
+ /** Nesting of any JSON value inside one operation, counting the operation as 1. */
41
+ value: 32,
42
+ /** Columns per table. */
43
+ columns: 50,
44
+ /** Table cells across all tables of a surface; a `$data` binding counts each time it is used. */
45
+ cells: 100000,
46
+ /** Datasets per chart. */
47
+ datasets: 12,
48
+ /** Steps per questionnaire. */
49
+ steps: 50,
50
+ /** Sources per surface. */
51
+ sources: 50,
52
+ /** Characters of a title, label or other short text. */
53
+ label: 200,
54
+ /** Characters of a description. */
55
+ description: 2000,
56
+ /** Characters of an id, a name, an author or a tool. */
57
+ name: 64,
58
+ /** Characters of a link address. */
59
+ href: 2000
60
+ });
61
+
62
+ /** The six intents, in the order the guide presents them. */
63
+ export const INTENTS = Object.freeze(/** @type {SurfaceIntent[]} */ (['show', 'ask', 'choose', 'confirm', 'review', 'questionnaire']));
64
+
65
+ /** Where a surface asks to be placed. */
66
+ export const PLACEMENTS = Object.freeze(/** @type {SurfacePlacement[]} */ (['inline', 'sheet', 'dialog']));
67
+
68
+ /** Action ids kept for closing a surface. An action of the surface's own cannot use them. */
69
+ export const RESERVED_ACTIONS = Object.freeze(['cancel', 'dismiss']);
70
+
71
+ /** What an id looks like: a node, an action, a row or a surface. Never `constructor` or `prototype`. */
72
+ export const ID_PATTERN = '^(?!(?:constructor|prototype)$)[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$';
73
+
74
+ /**
75
+ * What an input name, a column id, a row key or a step name looks like: it becomes a key of the
76
+ * reply's `values` or of a row, so `__proto__`, `constructor` and `prototype` are excluded.
77
+ */
78
+ export const NAME_PATTERN = '^(?!(?:__proto__|constructor|prototype)$)[A-Za-z_][A-Za-z0-9_.-]{0,63}$';
79
+
80
+ /** Invisible format characters (Unicode `Cf`) in the Basic Multilingual Plane, as a class body. */
81
+ const CF_BMP = '\\u00AD\\u0600-\\u0605\\u061C\\u06DD\\u070F\\u0890\\u0891\\u08E2\\u180E\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u206F\\uFEFF\\uFFF9-\\uFFFB';
82
+
83
+ /** The format characters beyond it, written as surrogate pairs so a pattern reads the same with or without the `u` flag. */
84
+ const CF_ASTRAL = [[0x110BD, 0x110BD], [0x110CD, 0x110CD], [0x13430, 0x1343F], [0x1BCA0, 0x1BCA3], [0x1D173, 0x1D17A], [0xE0001, 0xE0001], [0xE0020, 0xE007F]]
85
+ .flatMap(([from, to]) => Array.from({ length: to - from + 1 }, (_, offset) => {
86
+ const text = String.fromCodePoint(from + offset);
87
+ return [...Array(text.length).keys()].map((index) => `\\u${text.charCodeAt(index).toString(16).toUpperCase().padStart(4, '0')}`).join('');
88
+ }))
89
+ .join('|');
90
+
91
+ /**
92
+ * What a link address looks like: `https://` in lower case, a host without credentials, and no
93
+ * whitespace, control, backslash or invisible format characters anywhere. The validator applies
94
+ * the same pattern, then parses the address.
95
+ */
96
+ export const HREF_PATTERN = `^(?!.*(?:${CF_ASTRAL}))https://[^\\s/?#@\\\\\\u0000-\\u001F\\u007F${CF_BMP}]+(?:[/?#][^\\s\\\\\\u0000-\\u001F\\u007F${CF_BMP}]*)?$`;
97
+
98
+ /** What an icon name looks like. */
99
+ export const ICON_PATTERN = '^[a-z0-9][a-z0-9-]{0,39}$';
100
+
101
+ /** Keys refused anywhere, at any depth. */
102
+ export const FORBIDDEN_KEYS = Object.freeze(['__proto__', 'constructor', 'prototype']);
103
+
104
+ /** @typedef {'show'|'ask'|'choose'|'confirm'|'review'|'questionnaire'} SurfaceIntent */
105
+ /** @typedef {'inline'|'sheet'|'dialog'} SurfacePlacement */
106
+
107
+ /**
108
+ * The value types a catalog property may have. Named types are described by the JSON Schema
109
+ * `$defs` of the same name.
110
+ * @typedef {'string'|'integer'|'number'|'boolean'|'number|string'|'string[]'|'Href'|'Ref'|'Column[]'|'Row[]'|'Figure[]'|'ChartData'|'Choice[]'|'DiffRow[]'|'Schema'|'Step[]'} CatalogType
111
+ */
112
+
113
+ /**
114
+ * One property of a node.
115
+ * @typedef {Object} CatalogProp
116
+ * @property {CatalogType} type What the value is.
117
+ * @property {ReadonlyArray<string|number>} [enum] The values allowed.
118
+ * @property {number} [max] Most characters of a string, or entries of a list.
119
+ * @property {boolean} [required] Whether the node needs it to render.
120
+ * @property {string|null} option The component option the property maps to: an option name, or
121
+ * `<option>[].<member>` for a member of a list option's entries. `null` when the surface itself
122
+ * consumes it (an input's `name`, a link's text and address).
123
+ */
124
+
125
+ /**
126
+ * One node type. `visible` is common to every node and not listed in `props`.
127
+ * @typedef {Object} CatalogNode
128
+ * @property {string} type The node type.
129
+ * @property {string|null} component The component that draws it, as `docs/api.json` names it;
130
+ * `null` for a node the surface draws itself.
131
+ * @property {SurfaceIntent} [intentOnly] The one intent the node may appear in.
132
+ * @property {boolean} children Whether it lays out `children`.
133
+ * @property {boolean} input Whether its value lands in the reply's `values`.
134
+ * @property {Readonly<Record<string, CatalogProp>>} props Its properties.
135
+ */
136
+
137
+ /**
138
+ * One intent: the frame, default actions and reply shape of a surface.
139
+ * @typedef {Object} CatalogIntent
140
+ * @property {SurfaceIntent} intent The intent.
141
+ * @property {ReadonlyArray<string>} requires Node types of which the surface needs at least one;
142
+ * empty when it needs none.
143
+ * @property {ReadonlyArray<string>} actions The default actions, by label.
144
+ * @property {string} reply What the reply's `values` hold.
145
+ */
146
+
147
+ /**
148
+ * The catalog, or a narrowed one.
149
+ * @typedef {Object} SurfaceCatalog
150
+ * @property {string} version The format version, `surface/1`.
151
+ * @property {Readonly<Partial<Record<SurfaceIntent, CatalogIntent>>>} intents The intents.
152
+ * @property {Readonly<Record<string, CatalogNode>>} nodes The node types.
153
+ */
154
+
155
+ /** @param {CatalogType} type @param {Partial<CatalogProp>} [rest] @returns {CatalogProp} */
156
+ const prop = (type, rest = {}) => ({ type, option: null, ...rest });
157
+
158
+ const TONES = ['info', 'success', 'warning', 'danger'];
159
+
160
+ /** @type {Record<string, CatalogNode>} */
161
+ const NODES = {
162
+ text: {
163
+ type: 'text', component: 'BlockView', children: false, input: false,
164
+ props: { text: prop('string', { required: true, max: LIMITS.string, option: 'blocks[].text' }) }
165
+ },
166
+ heading: {
167
+ type: 'heading', component: 'BlockView', children: false, input: false,
168
+ props: {
169
+ text: prop('string', { required: true, max: LIMITS.label, option: 'blocks[].text' }),
170
+ level: prop('integer', { enum: [2, 3], option: 'blocks[].level' })
171
+ }
172
+ },
173
+ list: {
174
+ type: 'list', component: 'BlockView', children: false, input: false,
175
+ props: {
176
+ items: prop('string[]', { required: true, max: LIMITS.rows, option: 'blocks[].items' }),
177
+ ordered: prop('boolean', { option: 'blocks[].ordered' })
178
+ }
179
+ },
180
+ quote: {
181
+ type: 'quote', component: 'BlockView', children: false, input: false,
182
+ props: { text: prop('string', { required: true, max: LIMITS.string, option: 'blocks[].text' }) }
183
+ },
184
+ code: {
185
+ type: 'code', component: 'BlockView', children: false, input: false,
186
+ props: {
187
+ code: prop('string', { required: true, max: LIMITS.string, option: 'blocks[].code' }),
188
+ language: prop('string', { max: 32, option: 'blocks[].language' })
189
+ }
190
+ },
191
+ callout: {
192
+ type: 'callout', component: 'BlockView', children: false, input: false,
193
+ props: {
194
+ text: prop('string', { required: true, max: LIMITS.string, option: 'blocks[].text' }),
195
+ title: prop('string', { max: LIMITS.label, option: 'blocks[].title' }),
196
+ tone: prop('string', { enum: TONES, option: 'blocks[].tone' })
197
+ }
198
+ },
199
+ figures: {
200
+ type: 'figures', component: 'BlockView', children: false, input: false,
201
+ props: { rows: prop('Figure[]', { required: true, max: LIMITS.rows, option: 'blocks[].rows' }) }
202
+ },
203
+ table: {
204
+ type: 'table', component: 'Table', children: false, input: true,
205
+ props: {
206
+ columns: prop('Column[]', { required: true, max: LIMITS.columns, option: 'columns' }),
207
+ rows: prop('Row[]', { required: true, max: LIMITS.rows, option: 'data' }),
208
+ rowId: prop('string', { max: LIMITS.name, option: 'rowId' }),
209
+ selectable: prop('string', { enum: ['single', 'multi'], option: 'selectable' }),
210
+ name: prop('string', { max: LIMITS.name }),
211
+ label: prop('string', { max: LIMITS.label, option: 'label' })
212
+ }
213
+ },
214
+ stat: {
215
+ type: 'stat', component: 'StatTile', children: false, input: false,
216
+ props: {
217
+ label: prop('string', { required: true, max: LIMITS.label, option: 'label' }),
218
+ value: prop('number|string', { required: true, max: LIMITS.label, option: 'value' }),
219
+ format: prop('string', { enum: ['number', 'currency', 'percent'], option: 'format' }),
220
+ currency: prop('string', { max: 3, option: 'currency' }),
221
+ delta: prop('number|string', { max: LIMITS.label, option: 'delta' }),
222
+ caption: prop('string', { max: LIMITS.label, option: 'caption' })
223
+ }
224
+ },
225
+ badge: {
226
+ type: 'badge', component: 'Badge', children: false, input: false,
227
+ props: {
228
+ label: prop('string', { required: true, max: LIMITS.name, option: 'label' }),
229
+ kind: prop('string', { enum: ['neutral', 'accent', 'success', 'warning', 'danger', 'info'], option: 'kind' })
230
+ }
231
+ },
232
+ ref: {
233
+ type: 'ref', component: 'EntityRef', children: false, input: false,
234
+ props: { ref: prop('Ref', { required: true, option: 'id' }) }
235
+ },
236
+ link: {
237
+ type: 'link', component: null, children: false, input: false,
238
+ props: {
239
+ text: prop('string', { required: true, max: LIMITS.label }),
240
+ href: prop('Href', { required: true, max: LIMITS.href })
241
+ }
242
+ },
243
+ chart: {
244
+ type: 'chart', component: 'Chart', children: false, input: false,
245
+ props: {
246
+ kind: prop('string', { required: true, enum: ['bar', 'line', 'pie', 'doughnut'], option: 'type' }),
247
+ data: prop('ChartData', { required: true, option: 'data' }),
248
+ label: prop('string', { required: true, max: LIMITS.label, option: 'label' }),
249
+ description: prop('string', { max: LIMITS.description, option: 'description' })
250
+ }
251
+ },
252
+ empty: {
253
+ type: 'empty', component: 'EmptyState', children: false, input: false,
254
+ props: {
255
+ title: prop('string', { required: true, max: LIMITS.label, option: 'title' }),
256
+ description: prop('string', { max: LIMITS.description, option: 'description' })
257
+ }
258
+ },
259
+ stack: {
260
+ type: 'stack', component: 'Stack', children: true, input: false,
261
+ props: { gap: prop('string', { enum: ['sm', 'md', 'lg'], option: 'gap' }) }
262
+ },
263
+ columns: {
264
+ type: 'columns', component: 'LayoutGrid', children: true, input: false,
265
+ props: { count: prop('integer', { enum: [1, 2, 3], option: 'columns' }) }
266
+ },
267
+ group: {
268
+ type: 'group', component: 'Groupbox', children: true, input: false,
269
+ props: { title: prop('string', { required: true, max: LIMITS.label, option: 'title' }) }
270
+ },
271
+ fields: {
272
+ type: 'fields', component: 'Fieldset', children: false, input: true,
273
+ props: {
274
+ schema: prop('Schema', { required: true, option: 'fields' }),
275
+ title: prop('string', { max: LIMITS.label, option: 'title' })
276
+ }
277
+ },
278
+ choice: {
279
+ type: 'choice', component: 'Questionnaire', children: false, input: true,
280
+ props: {
281
+ name: prop('string', { required: true, max: LIMITS.name }),
282
+ label: prop('string', { required: true, max: LIMITS.label, option: 'items[].prompt' }),
283
+ choices: prop('Choice[]', { required: true, max: LIMITS.choices, option: 'items[].choices' }),
284
+ multiple: prop('boolean', { option: 'items[].multiple' })
285
+ }
286
+ },
287
+ diff: {
288
+ type: 'diff', component: 'Table', intentOnly: 'review', children: false, input: true,
289
+ props: {
290
+ name: prop('string', { required: true, max: LIMITS.name }),
291
+ rows: prop('DiffRow[]', { required: true, max: LIMITS.rows, option: 'data' }),
292
+ label: prop('string', { max: LIMITS.label, option: 'label' })
293
+ }
294
+ },
295
+ questionnaire: {
296
+ type: 'questionnaire', component: 'Questionnaire', intentOnly: 'questionnaire', children: false, input: true,
297
+ props: {
298
+ steps: prop('Step[]', { required: true, max: LIMITS.steps, option: 'items' }),
299
+ review: prop('boolean', { option: 'review' })
300
+ }
301
+ }
302
+ };
303
+
304
+ /** @type {Record<SurfaceIntent, CatalogIntent>} */
305
+ const INTENT_ENTRIES = {
306
+ show: { intent: 'show', requires: [], actions: [], reply: 'No values. Actions are optional; closing the surface replies `dismiss`.' },
307
+ ask: { intent: 'ask', requires: ['fields'], actions: ['Submit', 'Cancel'], reply: 'The values of its inputs, by name.' },
308
+ choose: { intent: 'choose', requires: ['choice'], actions: ['Submit', 'Cancel'], reply: 'The picked value under the choice\'s name; a list when `multiple`.' },
309
+ confirm: { intent: 'confirm', requires: [], actions: ['Confirm', 'Cancel'], reply: '`{}`. The application may ask the person to type a confirmation.' },
310
+ review: { intent: 'review', requires: ['diff', 'table'], actions: ['Approve selected', 'Reject'], reply: 'The ids of the accepted diff rows or selected table rows, under the input\'s name.' },
311
+ questionnaire: { intent: 'questionnaire', requires: ['questionnaire'], actions: ['Cancel'], reply: '`{answers, path}`: the answers by step name and the steps taken.' }
312
+ };
313
+
314
+ /**
315
+ * The full catalog. Frozen; narrow it with `narrowCatalog()`.
316
+ * @type {SurfaceCatalog}
317
+ */
318
+ export const CATALOG = deepFreeze({
319
+ version: SURFACE_VERSION,
320
+ intents: INTENT_ENTRIES,
321
+ nodes: NODES
322
+ });
323
+
324
+ /**
325
+ * Returns a catalog limited to some intents and node types. It can only narrow: a name the
326
+ * catalog does not have is refused, and so is an intent whose required node would be removed
327
+ * (`ask` without `fields`, `choose` without `choice`, `review` without `diff` or `table`,
328
+ * `questionnaire` without `questionnaire`). A node that belongs to one intent leaves with it.
329
+ * @param {SurfaceCatalog} catalog The catalog to narrow: `CATALOG` or an already narrowed one.
330
+ * @param {{intents?: SurfaceIntent[], nodes?: string[]}} [options] What to keep; all when left out.
331
+ * @returns {SurfaceCatalog} A new frozen catalog.
332
+ * @throws {TypeError} For an unknown name, an intent left without its required node, or a
333
+ * catalog that is not the library's.
334
+ */
335
+ export function narrowCatalog(catalog, options = {}) {
336
+ assertCatalog(catalog);
337
+ const intents = options.intents ?? /** @type {SurfaceIntent[]} */ (Object.keys(catalog.intents));
338
+ const nodes = options.nodes ?? Object.keys(catalog.nodes);
339
+ if (!Array.isArray(intents) || !Array.isArray(nodes)) throw new TypeError('"intents" and "nodes" must be lists of names');
340
+ for (const name of intents) {
341
+ if (typeof name !== 'string' || !Object.hasOwn(catalog.intents, name)) throw new TypeError(`Unknown intent: ${String(name)}`);
342
+ }
343
+ for (const name of nodes) {
344
+ if (typeof name !== 'string' || !Object.hasOwn(catalog.nodes, name)) throw new TypeError(`Unknown node type: ${String(name)}`);
345
+ }
346
+ const keptIntents = new Set(intents);
347
+ const keptNodes = nodes.filter((name) => {
348
+ const only = catalog.nodes[name].intentOnly;
349
+ return !only || keptIntents.has(only);
350
+ });
351
+ if (!keptNodes.length) throw new TypeError('A catalog keeps at least one node type');
352
+ if (!intents.length) throw new TypeError('A catalog keeps at least one intent');
353
+ for (const name of intents) {
354
+ const entry = /** @type {CatalogIntent} */ (catalog.intents[name]);
355
+ if (entry.requires.length && !entry.requires.some((type) => keptNodes.includes(type))) {
356
+ throw new TypeError(`The intent "${name}" needs a ${entry.requires.join(' or ')} node`);
357
+ }
358
+ }
359
+ /** @type {Record<string, CatalogIntent>} */
360
+ const keptIntentEntries = {};
361
+ for (const name of INTENTS) if (keptIntents.has(name)) keptIntentEntries[name] = /** @type {CatalogIntent} */ (catalog.intents[name]);
362
+ /** @type {Record<string, CatalogNode>} */
363
+ const keptNodeEntries = {};
364
+ for (const name of Object.keys(CATALOG.nodes)) if (keptNodes.includes(name)) keptNodeEntries[name] = catalog.nodes[name];
365
+ return Object.freeze({
366
+ version: SURFACE_VERSION,
367
+ intents: Object.freeze(keptIntentEntries),
368
+ nodes: Object.freeze(keptNodeEntries)
369
+ });
370
+ }
371
+
372
+ /**
373
+ * Throws unless the catalog is the library's, or narrowed from it: every intent and node entry
374
+ * must be the library's own frozen entry, so a catalog cannot be widened by building one by hand.
375
+ * @param {unknown} catalog
376
+ * @returns {asserts catalog is SurfaceCatalog}
377
+ * @throws {TypeError} When the catalog is not the library's.
378
+ */
379
+ export function assertCatalog(catalog) {
380
+ if (!isObject(catalog) || catalog.version !== SURFACE_VERSION || !isObject(catalog.intents) || !isObject(catalog.nodes)) {
381
+ throw new TypeError('Not a surface catalog');
382
+ }
383
+ for (const [name, entry] of Object.entries(catalog.intents)) {
384
+ if (/** @type {Record<string, unknown>} */ (CATALOG.intents)[name] !== entry) throw new TypeError(`The catalog's intent "${name}" is not the library's`);
385
+ }
386
+ for (const [name, entry] of Object.entries(catalog.nodes)) {
387
+ if (CATALOG.nodes[name] !== entry) throw new TypeError(`The catalog's node "${name}" is not the library's`);
388
+ }
389
+ }
390
+
391
+ /* ------------------------------------------------------------------------------------------------
392
+ * JSON Schema
393
+ * --------------------------------------------------------------------------------------------- */
394
+
395
+ /** The JSON Schema dialect of everything generated here. */
396
+ const DIALECT = 'https://json-schema.org/draft/2020-12/schema';
397
+
398
+ /**
399
+ * Two profiles share one generator. `full` is the format as a validator reads it: limits,
400
+ * patterns, data and bindings. `strict` is what providers' strict structured output accepts:
401
+ * every object closed and every key required (optional ones nullable), no recursion, no length or
402
+ * range constraints, maps written as lists, and no data or bindings.
403
+ * @typedef {'full'|'strict'} Profile
404
+ */
405
+
406
+ /**
407
+ * @typedef {Record<string, any>} JsonSchema
408
+ */
409
+
410
+ /**
411
+ * Builds the `$defs` and node schemas of one profile for a catalog.
412
+ * @param {SurfaceCatalog} catalog @param {Profile} profile
413
+ */
414
+ function schemaKit(catalog, profile) {
415
+ const strict = profile === 'strict';
416
+ /** @type {Record<string, JsonSchema>} */
417
+ const defs = {};
418
+ /** @param {string} name @returns {JsonSchema} */
419
+ const ref = (name) => ({ $ref: `#/$defs/${name}` });
420
+ /** @param {JsonSchema} schema @returns {JsonSchema} */
421
+ const nullable = (schema) => (strict ? { anyOf: [schema, { type: 'null' }] } : schema);
422
+ /**
423
+ * @param {number} [max] @param {string} [pattern]
424
+ * @returns {JsonSchema}
425
+ */
426
+ const string = (max, pattern) => {
427
+ /** @type {JsonSchema} */
428
+ const schema = { type: 'string' };
429
+ if (!strict && pattern) schema.pattern = pattern;
430
+ if (!strict && max) schema.maxLength = max;
431
+ return schema;
432
+ };
433
+ /**
434
+ * @param {JsonSchema} items @param {number} [max] @param {number} [min=0]
435
+ * @returns {JsonSchema}
436
+ */
437
+ const list = (items, max, min = 0) => {
438
+ /** @type {JsonSchema} */
439
+ const schema = { type: 'array', items };
440
+ if (!strict && min) schema.minItems = min;
441
+ if (!strict && max) schema.maxItems = max;
442
+ return schema;
443
+ };
444
+ /**
445
+ * @param {number} [min] @param {number} [max]
446
+ * @returns {JsonSchema}
447
+ */
448
+ const integer = (min, max) => {
449
+ /** @type {JsonSchema} */
450
+ const schema = { type: 'integer' };
451
+ if (!strict && min !== undefined) schema.minimum = min;
452
+ if (!strict && max !== undefined) schema.maximum = max;
453
+ return schema;
454
+ };
455
+ /**
456
+ * A closed object. In the strict profile every key is required and the optional ones accept
457
+ * null.
458
+ * @param {Record<string, JsonSchema>} properties @param {string[]} required
459
+ * @returns {JsonSchema}
460
+ */
461
+ const object = (properties, required) => {
462
+ if (!strict) return { type: 'object', properties, required, additionalProperties: false };
463
+ /** @type {Record<string, JsonSchema>} */
464
+ const all = {};
465
+ for (const [key, schema] of Object.entries(properties)) all[key] = required.includes(key) ? schema : nullable(schema);
466
+ return { type: 'object', properties: all, required: Object.keys(properties), additionalProperties: false };
467
+ };
468
+ const notForbidden = { not: { enum: [...FORBIDDEN_KEYS] } };
469
+ const scalar = { anyOf: [string(LIMITS.string), { type: 'number' }, { type: 'boolean' }, { type: 'null' }] };
470
+
471
+ defs.Id = string(LIMITS.name, ID_PATTERN);
472
+ defs.Name = string(LIMITS.name, NAME_PATTERN);
473
+ defs.Scalar = scalar;
474
+ defs.Ref = object({ $ref: string(LIMITS.name, NAME_PATTERN), id: string(LIMITS.label) }, ['$ref', 'id']);
475
+ defs.Cell = { anyOf: [string(LIMITS.string), { type: 'number' }, { type: 'boolean' }, { type: 'null' }, ref('Ref')] };
476
+
477
+ // Conditions are unrolled to their four levels rather than recursive, which both bounds them
478
+ // and keeps the strict profile free of recursion.
479
+ defs.Condition1 = object({
480
+ field: ref('Name'),
481
+ op: { type: 'string', enum: [...CONDITION_OPS] },
482
+ value: { anyOf: [string(LIMITS.label), { type: 'number' }, { type: 'boolean' }, { type: 'null' }, list(scalar, LIMITS.choices, 1)] }
483
+ }, ['field', 'op']);
484
+ for (let level = 2; level <= MAX_CONDITION_DEPTH; level += 1) {
485
+ const inner = ref(`Condition${level - 1}`);
486
+ defs[`Condition${level}`] = {
487
+ anyOf: [
488
+ ref('Condition1'),
489
+ object({ all: list(inner, 0, 1) }, ['all']),
490
+ object({ any: list(inner, 0, 1) }, ['any']),
491
+ object({ not: inner }, ['not'])
492
+ ]
493
+ };
494
+ }
495
+ defs.Condition = ref(`Condition${MAX_CONDITION_DEPTH}`);
496
+
497
+ defs.Column = object({
498
+ id: ref('Name'),
499
+ label: string(LIMITS.label),
500
+ align: { type: 'string', enum: ['start', 'center', 'end'] },
501
+ format: { type: 'string', enum: ['text', 'number', 'currency', 'percent', 'date'] },
502
+ currency: string(3)
503
+ }, ['id', 'label']);
504
+ defs.Row = strict
505
+ ? list(ref('Cell'), LIMITS.columns)
506
+ : {
507
+ anyOf: [
508
+ { type: 'object', propertyNames: { ...notForbidden, pattern: NAME_PATTERN }, additionalProperties: ref('Cell'), maxProperties: LIMITS.columns },
509
+ list(ref('Cell'), LIMITS.columns)
510
+ ]
511
+ };
512
+ defs.Figure = object({ label: string(LIMITS.label), detail: string(LIMITS.label), value: string(LIMITS.label) }, ['label', 'value']);
513
+ defs.ChartData = object({
514
+ labels: list({ anyOf: [string(LIMITS.label), { type: 'number' }] }, LIMITS.rows),
515
+ datasets: list(object({
516
+ label: string(LIMITS.label),
517
+ data: list({ anyOf: [{ type: 'number' }, { type: 'null' }] }, LIMITS.rows)
518
+ }, ['label', 'data']), LIMITS.datasets, 1)
519
+ }, ['labels', 'datasets']);
520
+ defs.Choice = object({
521
+ value: string(LIMITS.label),
522
+ label: string(LIMITS.label),
523
+ description: string(LIMITS.description),
524
+ icon: string(40, ICON_PATTERN)
525
+ }, ['value', 'label']);
526
+ defs.DiffRow = object({
527
+ id: ref('Id'),
528
+ field: ref('Name'),
529
+ label: string(LIMITS.label),
530
+ before: ref('Scalar'),
531
+ after: ref('Scalar'),
532
+ ref: ref('Ref')
533
+ }, ['id', 'field', 'label', 'before', 'after']);
534
+
535
+ const choiceList = list(object({ const: string(LIMITS.label), title: string(LIMITS.label) }, ['const', 'title']), LIMITS.choices, 1);
536
+ const allFieldTypes = [...new Set(Object.values(FIELD_TYPES).flat())];
537
+ /** @type {Record<string, JsonSchema>} */
538
+ const propertyMembers = {
539
+ type: { type: 'string', enum: ['string', 'number', 'integer', 'boolean', 'array'] },
540
+ title: string(LIMITS.label),
541
+ description: string(LIMITS.description),
542
+ default: { anyOf: [string(LIMITS.string), { type: 'number' }, { type: 'boolean' }, list(string(LIMITS.label), LIMITS.choices)] },
543
+ enum: list(string(LIMITS.label), LIMITS.choices, 1),
544
+ oneOf: choiceList,
545
+ format: { type: 'string', enum: [...SCHEMA_FORMATS] },
546
+ minimum: { type: 'number' },
547
+ maximum: { type: 'number' },
548
+ minLength: integer(0),
549
+ maxLength: integer(0),
550
+ items: object({ type: { type: 'string', enum: ['string'] }, enum: list(string(LIMITS.label), LIMITS.choices, 1), anyOf: choiceList }, []),
551
+ minItems: integer(0),
552
+ maxItems: integer(0),
553
+ 'x-zx': object({ field: { type: 'string', enum: allFieldTypes }, visible: ref('Condition') }, [])
554
+ };
555
+ defs.Property = object(propertyMembers, ['type']);
556
+ defs.NamedProperty = object({ name: ref('Name'), ...propertyMembers }, ['name', 'type']);
557
+ defs.Schema = object({
558
+ type: { type: 'string', enum: ['object'] },
559
+ properties: strict
560
+ ? list(ref('NamedProperty'), MAX_SCHEMA_PROPERTIES)
561
+ : {
562
+ anyOf: [
563
+ { type: 'object', propertyNames: { ...notForbidden, pattern: NAME_PATTERN }, additionalProperties: ref('Property'), maxProperties: MAX_SCHEMA_PROPERTIES },
564
+ list(ref('NamedProperty'), MAX_SCHEMA_PROPERTIES)
565
+ ]
566
+ },
567
+ required: list(ref('Name'), MAX_SCHEMA_PROPERTIES),
568
+ ...(strict ? {} : { $schema: string(LIMITS.label) })
569
+ }, ['type', 'properties']);
570
+
571
+ const message = string(LIMITS.label);
572
+ defs.Rule = {
573
+ anyOf: [
574
+ object({ required: { type: 'boolean' }, message }, ['required']),
575
+ object({ minLength: integer(0), message }, ['minLength']),
576
+ object({ maxLength: integer(0), message }, ['maxLength']),
577
+ object({ minimum: { type: 'number' }, message }, ['minimum']),
578
+ object({ maximum: { type: 'number' }, message }, ['maximum']),
579
+ object({ format: { type: 'string', enum: [...RULE_FORMATS] }, message }, ['format']),
580
+ object({ oneOf: list(scalar, LIMITS.choices, 1), message }, ['oneOf'])
581
+ ]
582
+ };
583
+ defs.Step = object({
584
+ name: ref('Name'),
585
+ prompt: string(LIMITS.label),
586
+ description: string(LIMITS.description),
587
+ section: string(LIMITS.label),
588
+ required: { type: 'boolean' },
589
+ multiple: { type: 'boolean' },
590
+ skippable: { type: 'boolean' },
591
+ choices: list(ref('Choice'), LIMITS.choices),
592
+ input: object({
593
+ label: string(LIMITS.label),
594
+ placeholder: string(LIMITS.label),
595
+ multiline: { type: 'boolean' },
596
+ maxLength: integer(0, LIMITS.string)
597
+ }, []),
598
+ when: ref('Condition'),
599
+ next: { anyOf: [string(LIMITS.name), list(object({ if: ref('Condition'), goto: string(LIMITS.name) }, ['goto']), LIMITS.steps, 1)] },
600
+ validate: list(ref('Rule'), 16)
601
+ }, ['name', 'prompt']);
602
+
603
+ defs.Action = object({
604
+ id: ref('Id'),
605
+ label: string(LIMITS.label),
606
+ kind: { type: 'string', enum: ['primary', 'secondary', 'danger'] },
607
+ tool: string(128),
608
+ description: string(LIMITS.description)
609
+ }, ['id', 'label']);
610
+ defs.Source = object({
611
+ n: integer(1, 999),
612
+ title: string(LIMITS.label),
613
+ call: string(128),
614
+ ref: ref('Ref')
615
+ }, ['n']);
616
+ defs.Href = string(LIMITS.href, HREF_PATTERN);
617
+
618
+ if (!strict) {
619
+ defs.Pointer = { type: 'string', pattern: '^(?:/.*)?$', maxLength: LIMITS.href };
620
+ defs.Binding = object({ $data: ref('Pointer') }, ['$data']);
621
+ // Data is any JSON, unrolled to the value depth so a schema can bound its nesting.
622
+ defs.Json0 = scalar;
623
+ for (let level = 1; level <= LIMITS.value - 2; level += 1) {
624
+ defs[`Json${level}`] = {
625
+ anyOf: [
626
+ ref('Json0'),
627
+ list(ref(`Json${level - 1}`), LIMITS.rows),
628
+ { type: 'object', propertyNames: notForbidden, additionalProperties: ref(`Json${level - 1}`), maxProperties: LIMITS.rows }
629
+ ]
630
+ };
631
+ }
632
+ defs.Json = ref(`Json${LIMITS.value - 2}`);
633
+ }
634
+
635
+ /**
636
+ * The schema of one property's value.
637
+ * @param {string} name @param {CatalogProp} entry @returns {JsonSchema}
638
+ */
639
+ const propSchema = (name, entry) => {
640
+ /** @type {JsonSchema} */
641
+ let schema;
642
+ switch (entry.type) {
643
+ case 'string':
644
+ schema = entry.enum ? { type: 'string', enum: [...entry.enum] } : string(entry.max ?? LIMITS.string, name === 'name' || name === 'rowId' ? NAME_PATTERN : undefined);
645
+ break;
646
+ case 'integer':
647
+ schema = entry.enum ? { type: 'integer', enum: [...entry.enum] } : integer();
648
+ break;
649
+ case 'number':
650
+ schema = { type: 'number' };
651
+ break;
652
+ case 'boolean':
653
+ schema = { type: 'boolean' };
654
+ break;
655
+ case 'number|string':
656
+ schema = { anyOf: [{ type: 'number' }, string(entry.max ?? LIMITS.string)] };
657
+ break;
658
+ case 'string[]':
659
+ schema = list(string(LIMITS.string), entry.max ?? LIMITS.rows);
660
+ break;
661
+ case 'Href':
662
+ case 'Ref':
663
+ case 'ChartData':
664
+ case 'Schema':
665
+ schema = ref(entry.type);
666
+ break;
667
+ default: {
668
+ const item = entry.type.slice(0, -2);
669
+ schema = list(ref(item), entry.max ?? LIMITS.rows);
670
+ }
671
+ }
672
+ if (!strict && name !== 'name') schema = { anyOf: [schema, ref('Binding')] };
673
+ return schema;
674
+ };
675
+
676
+ /**
677
+ * The schema of a node of one type, with `extra` members first (the operation's `op` and
678
+ * `surface`).
679
+ * @param {CatalogNode} entry @param {Record<string, JsonSchema>} extra
680
+ * @returns {JsonSchema}
681
+ */
682
+ const nodeSchema = (entry, extra = {}) => {
683
+ /** @type {Record<string, JsonSchema>} */
684
+ const properties = { ...extra, id: ref('Id'), type: { type: 'string', enum: [entry.type] }, visible: ref('Condition') };
685
+ if (entry.children) properties.children = list(ref('Id'), LIMITS.nodes);
686
+ /** @type {string[]} */
687
+ const required = [...Object.keys(extra), 'id', 'type'];
688
+ for (const [name, member] of Object.entries(entry.props)) {
689
+ properties[name] = propSchema(name, member);
690
+ if (member.required) required.push(name);
691
+ }
692
+ return object(properties, required);
693
+ };
694
+
695
+ for (const entry of Object.values(catalog.nodes)) defs[`node_${entry.type}`] = nodeSchema(entry);
696
+
697
+ /** @type {SurfaceIntent[]} */
698
+ const intents = /** @type {SurfaceIntent[]} */ (Object.keys(catalog.intents));
699
+ return { defs, ref, object, list, string, nullable, nodeSchema, intents, strict };
700
+ }
701
+
702
+ /**
703
+ * Keeps only the `$defs` a schema reaches, so a narrowed catalog's schema names nothing it lacks.
704
+ * @param {JsonSchema} schema @param {Record<string, JsonSchema>} defs
705
+ * @returns {JsonSchema} The schema with `$defs` attached.
706
+ */
707
+ function withDefs(schema, defs) {
708
+ /** @type {Set<string>} */
709
+ const used = new Set();
710
+ /** @param {unknown} value */
711
+ const visit = (value) => {
712
+ if (Array.isArray(value)) {
713
+ value.forEach(visit);
714
+ return;
715
+ }
716
+ if (!isObject(value)) return;
717
+ for (const [key, member] of Object.entries(value)) {
718
+ if (key === '$ref' && typeof member === 'string' && member.startsWith('#/$defs/')) {
719
+ const name = member.slice(8);
720
+ if (!used.has(name)) {
721
+ used.add(name);
722
+ visit(defs[name]);
723
+ }
724
+ } else {
725
+ visit(member);
726
+ }
727
+ }
728
+ };
729
+ visit(schema);
730
+ /** @type {Record<string, JsonSchema>} */
731
+ const kept = {};
732
+ for (const name of Object.keys(defs)) if (used.has(name)) kept[name] = defs[name];
733
+ return { ...schema, $defs: kept };
734
+ }
735
+
736
+ /**
737
+ * The document form of a surface: the whole surface as one object, for the `show_surface` and
738
+ * `ask_user` tools and `Surface({document})`.
739
+ * @param {ReturnType<typeof schemaKit>} kit @param {SurfaceIntent[]} intents @param {string[]} nodeTypes
740
+ * @returns {JsonSchema}
741
+ */
742
+ function documentSchema(kit, intents, nodeTypes) {
743
+ const { ref, object, list, string, strict } = kit;
744
+ /** @type {Record<string, JsonSchema>} */
745
+ const properties = {
746
+ zx: { type: 'string', enum: [SURFACE_VERSION] },
747
+ surface: ref('Id'),
748
+ intent: { type: 'string', enum: intents },
749
+ title: string(LIMITS.label),
750
+ author: string(LIMITS.name, NAME_PATTERN),
751
+ root: list(ref('Id'), LIMITS.nodes),
752
+ placement: { type: 'string', enum: [...PLACEMENTS] },
753
+ description: string(LIMITS.description),
754
+ nodes: list(nodeTypes.length ? { anyOf: nodeTypes.map((type) => ref(`node_${type}`)) } : { not: {} }, LIMITS.nodes),
755
+ actions: list(ref('Action'), LIMITS.actions),
756
+ sources: list(ref('Source'), LIMITS.sources)
757
+ };
758
+ if (!strict) properties.data = { type: 'object', propertyNames: { not: { enum: [...FORBIDDEN_KEYS] } }, additionalProperties: ref('Json') };
759
+ return object(properties, ['zx', 'surface', 'intent', 'title', 'author', 'root', 'nodes']);
760
+ }
761
+
762
+ /**
763
+ * The JSON Schema (2020-12) of the format for a catalog: one operation line, and a whole document.
764
+ * Validation, not the schema, is what decides: the schema cannot see duplicate ids, the order of
765
+ * inputs a condition may name, or the application's entities, and it leaves out the repairs the
766
+ * validator makes.
767
+ * @param {SurfaceCatalog} [catalog=CATALOG]
768
+ * @returns {{line: JsonSchema, document: JsonSchema}}
769
+ */
770
+ export function surfaceSchema(catalog = CATALOG) {
771
+ assertCatalog(catalog);
772
+ const kit = schemaKit(catalog, 'full');
773
+ const { ref, object, list, string, defs } = kit;
774
+ const types = Object.keys(catalog.nodes);
775
+ const head = { op: null, surface: ref('Id') };
776
+ /** @param {string} op @returns {Record<string, JsonSchema>} */
777
+ const opHead = (op) => ({ ...head, op: { type: 'string', enum: [op] } });
778
+
779
+ /** @type {JsonSchema[]} */
780
+ const ops = [
781
+ object({
782
+ zx: { type: 'string', enum: [SURFACE_VERSION] },
783
+ ...opHead('begin'),
784
+ intent: { type: 'string', enum: kit.intents },
785
+ title: string(LIMITS.label),
786
+ author: string(LIMITS.name, NAME_PATTERN),
787
+ root: list(ref('Id'), LIMITS.nodes),
788
+ placement: { type: 'string', enum: [...PLACEMENTS] },
789
+ description: string(LIMITS.description)
790
+ }, ['zx', 'op', 'surface', 'intent', 'title', 'author', 'root']),
791
+ ...types.map((type) => kit.nodeSchema(catalog.nodes[type], opHead('node'))),
792
+ object({
793
+ ...opHead('patch'),
794
+ id: ref('Id'),
795
+ props: { type: 'object', propertyNames: { not: { enum: [...FORBIDDEN_KEYS, 'id', 'type'] } }, additionalProperties: ref('Json') }
796
+ }, ['op', 'surface', 'id', 'props']),
797
+ object({ ...opHead('append'), id: ref('Id'), text: string(LIMITS.string) }, ['op', 'surface', 'id', 'text']),
798
+ object({ ...opHead('remove'), id: ref('Id') }, ['op', 'surface', 'id']),
799
+ object({ ...opHead('data'), path: ref('Pointer'), value: ref('Json') }, ['op', 'surface', 'path', 'value']),
800
+ object({ ...opHead('data'), path: ref('Pointer'), remove: { type: 'boolean', enum: [true] } }, ['op', 'surface', 'path', 'remove']),
801
+ object({ ...opHead('actions'), items: list(ref('Action'), LIMITS.actions) }, ['op', 'surface', 'items']),
802
+ object({ ...opHead('end'), sources: list(ref('Source'), LIMITS.sources) }, ['op', 'surface'])
803
+ ];
804
+ const line = withDefs({
805
+ $schema: DIALECT,
806
+ title: 'Surface operation',
807
+ description: 'One line of a surface stream.',
808
+ anyOf: ops
809
+ }, defs);
810
+ const document = withDefs({
811
+ $schema: DIALECT,
812
+ title: 'Surface document',
813
+ description: 'A whole surface in one object.',
814
+ ...documentSchema(kit, kit.intents, types)
815
+ }, defs);
816
+ return { line, document };
817
+ }
818
+
819
+ /**
820
+ * A function-calling tool definition in the neutral shape providers adapt.
821
+ * @typedef {Object} SurfaceTool
822
+ * @property {string} name The tool's name.
823
+ * @property {string} description What it does, for the model.
824
+ * @property {JsonSchema} parameters The arguments' JSON Schema, usable with strict structured
825
+ * output.
826
+ */
827
+
828
+ /**
829
+ * The tool definitions a model calls to put a surface in front of the person: `show_surface`
830
+ * (any intent, a whole document) and `ask_user` (an `ask` surface; left out when the catalog has
831
+ * no `ask`). The person's reply is each call's result. Arguments follow the strict profile: every
832
+ * key present, `null` for one that does not apply, schema properties and table rows as lists.
833
+ * @param {SurfaceCatalog} [catalog=CATALOG]
834
+ * @returns {SurfaceTool[]}
835
+ */
836
+ export function surfaceTools(catalog = CATALOG) {
837
+ assertCatalog(catalog);
838
+ const kit = schemaKit(catalog, 'strict');
839
+ const types = Object.keys(catalog.nodes);
840
+ /** @type {SurfaceTool[]} */
841
+ const tools = [{
842
+ name: 'show_surface',
843
+ description: showDescription(catalog),
844
+ parameters: withDefs({ ...documentSchema(kit, kit.intents, types) }, kit.defs)
845
+ }];
846
+ if (Object.hasOwn(catalog.intents, 'ask')) {
847
+ const askTypes = types.filter((type) => !catalog.nodes[type].intentOnly || catalog.nodes[type].intentOnly === 'ask');
848
+ tools.push({
849
+ name: 'ask_user',
850
+ description: 'Ask the person for values you need, with a form of one or more fields nodes. Returns their reply: `submit` with the values, or `cancel`.',
851
+ parameters: withDefs({ ...documentSchema(kit, ['ask'], askTypes) }, kit.defs)
852
+ });
853
+ }
854
+ return tools;
855
+ }
856
+
857
+ /** How the `show_surface` description names each intent. */
858
+ const INTENT_WORDS = Object.freeze({
859
+ show: 'a rich answer', ask: 'a form', choose: 'a choice', confirm: 'a confirmation', review: 'a review', questionnaire: 'a questionnaire'
860
+ });
861
+
862
+ /**
863
+ * The `show_surface` description, naming only the catalog's intents.
864
+ * @param {SurfaceCatalog} catalog @returns {string}
865
+ */
866
+ function showDescription(catalog) {
867
+ const words = INTENTS.filter((intent) => Object.hasOwn(catalog.intents, intent)).map((intent) => INTENT_WORDS[intent]);
868
+ const list = words.length > 1 ? `${words.slice(0, -1).join(', ')} or ${words.at(-1)}` : words.join('');
869
+ const inputs = Object.values(catalog.nodes).some((entry) => entry.input) && INTENTS.some((intent) => intent !== 'show' && intent !== 'confirm' && Object.hasOwn(catalog.intents, intent));
870
+ return `Show the person a surface composed from the catalog: ${list}. Returns the person's reply: the action taken${inputs ? ' and the values entered' : ''}.`;
871
+ }
872
+
873
+ /* ------------------------------------------------------------------------------------------------
874
+ * The guide a model reads
875
+ * --------------------------------------------------------------------------------------------- */
876
+
877
+ /** @typedef {{title: string, intro: string, intent: SurfaceIntent, nodes: string[], document: Record<string, any>, lines: Record<string, any>[], before: string, after: string}} WorkedExample */
878
+
879
+ /**
880
+ * The worked examples the guide draws from, in order of preference. The guide shows the first two
881
+ * that fit the catalog. Each is written once as operations; the document form is derived from
882
+ * them, with schema properties and table rows as lists for the strict tools.
883
+ * @returns {WorkedExample[]}
884
+ */
885
+ function examplePool() {
886
+ /** @type {WorkedExample[]} */
887
+ const pool = [];
888
+ pool.push({
889
+ title: 'A review of reminders to send',
890
+ intro: 'Three invoices are overdue. The surface lists them for selection and asks which template to use.',
891
+ intent: 'review',
892
+ nodes: ['text', 'table', 'fields'],
893
+ before: 'Three invoices are more than two weeks overdue. Pick the ones to remind:',
894
+ after: 'I will send the reminders you approve.',
895
+ lines: [
896
+ { zx: SURFACE_VERSION, op: 'begin', surface: 's1', intent: 'review', title: 'Send 3 first reminders?', author: 'finance', root: ['why', 'list', 'opts'] },
897
+ { op: 'node', surface: 's1', id: 'why', type: 'text', text: 'Three invoices are more than **14 days** overdue [1].' },
898
+ { op: 'node', surface: 's1', id: 'list', type: 'table', name: 'invoices', selectable: 'multi', rowId: 'invoice', columns: [{ id: 'invoice', label: 'Invoice' }, { id: 'customer', label: 'Customer' }, { id: 'amount', label: 'Amount', align: 'end', format: 'currency', currency: 'EUR' }], rows: { $data: '/overdue' } },
899
+ { op: 'node', surface: 's1', id: 'opts', type: 'fields', schema: { type: 'object', required: ['template'], properties: { template: { type: 'string', title: 'Template', oneOf: [{ const: 'reminder-1', title: 'First reminder' }, { const: 'reminder-2', title: 'Second reminder, €5.00 fee' }] }, sendOn: { type: 'string', format: 'date', title: 'Send on' } } } },
900
+ { op: 'data', surface: 's1', path: '/overdue', value: [{ invoice: 'RE-2026-0121', customer: 'Helios Energie', amount: 4860 }, { invoice: 'RE-2026-0127', customer: 'Nordlicht Logistik', amount: 1275.5 }, { invoice: 'RE-2026-0130', customer: 'Atelier Brun', amount: 620 }] },
901
+ { op: 'actions', surface: 's1', items: [{ id: 'send', label: 'Send reminders', kind: 'primary', tool: 'mail.send' }, { id: 'later', label: 'Not now' }] },
902
+ { op: 'end', surface: 's1', sources: [{ n: 1, call: 'invoices' }] }
903
+ ],
904
+ document: {}
905
+ });
906
+ pool.push({
907
+ title: 'A payment form with a conditional field',
908
+ intro: 'The IBAN is asked for only when the person pays by transfer.',
909
+ intent: 'ask',
910
+ nodes: ['fields'],
911
+ before: 'I need the payment details to record the order.',
912
+ after: 'Thanks — I will record the payment as soon as you submit.',
913
+ lines: [
914
+ { zx: SURFACE_VERSION, op: 'begin', surface: 'pay', intent: 'ask', title: 'How will the customer pay?', author: 'orders', root: ['form'] },
915
+ { op: 'node', surface: 'pay', id: 'form', type: 'fields', schema: { type: 'object', required: ['method'], properties: { method: { type: 'string', title: 'Payment', oneOf: [{ const: 'card', title: 'Card' }, { const: 'transfer', title: 'Bank transfer' }] }, iban: { type: 'string', title: 'IBAN', maxLength: 34, 'x-zx': { visible: { field: 'method', op: 'eq', value: 'transfer' } } }, note: { type: 'string', title: 'Note for the invoice', 'x-zx': { field: 'textarea' } } } } },
916
+ { op: 'end', surface: 'pay' }
917
+ ],
918
+ document: {}
919
+ });
920
+ pool.push({
921
+ title: 'A choice between plans',
922
+ intro: 'The person picks one of three options; the reply carries the picked value.',
923
+ intent: 'choose',
924
+ nodes: ['choice'],
925
+ before: 'There are three ways to split the shipment.',
926
+ after: 'I will plan the shipment the way you pick.',
927
+ lines: [
928
+ { zx: SURFACE_VERSION, op: 'begin', surface: 'plan', intent: 'choose', title: 'How should the order ship?', author: 'logistics', root: ['pick'] },
929
+ { op: 'node', surface: 'plan', id: 'pick', type: 'choice', name: 'plan', label: 'Shipping plan', choices: [{ value: 'one', label: 'One shipment', description: 'Everything on 14 Nov' }, { value: 'two', label: 'Two shipments', description: 'In stock now, the rest on 14 Nov' }, { value: 'pickup', label: 'Pickup', description: 'From the Lyon depot' }] },
930
+ { op: 'end', surface: 'plan' }
931
+ ],
932
+ document: {}
933
+ });
934
+ pool.push({
935
+ title: 'An answer with figures',
936
+ intro: 'A read-only surface: two figures side by side and a short note.',
937
+ intent: 'show',
938
+ nodes: ['columns', 'stat', 'text'],
939
+ before: 'Here is where the quarter stands.',
940
+ after: '',
941
+ lines: [
942
+ { zx: SURFACE_VERSION, op: 'begin', surface: 'q3', intent: 'show', title: 'Third quarter', author: 'finance', root: ['row', 'note'] },
943
+ { op: 'node', surface: 'q3', id: 'row', type: 'columns', count: 2, children: ['rev', 'open'] },
944
+ { op: 'node', surface: 'q3', id: 'rev', type: 'stat', label: 'Revenue', value: 182400, format: 'currency', currency: 'EUR', delta: 0.08 },
945
+ { op: 'node', surface: 'q3', id: 'open', type: 'stat', label: 'Open invoices', value: 14, caption: 'of 212' },
946
+ { op: 'node', surface: 'q3', id: 'note', type: 'text', text: 'Revenue is up **8 %** on the second quarter.' },
947
+ { op: 'end', surface: 'q3' }
948
+ ],
949
+ document: {}
950
+ });
951
+ pool.push({
952
+ title: 'A confirmation',
953
+ intro: 'Nothing but a question and the default Confirm and Cancel actions.',
954
+ intent: 'confirm',
955
+ nodes: [],
956
+ before: 'The draft is ready to archive.',
957
+ after: '',
958
+ lines: [
959
+ { zx: SURFACE_VERSION, op: 'begin', surface: 'arch', intent: 'confirm', title: 'Archive the three drafts?', author: 'files', root: [], description: 'Archived drafts can be restored for 30 days.' },
960
+ { op: 'end', surface: 'arch' }
961
+ ],
962
+ document: {}
963
+ });
964
+ pool.push({
965
+ title: 'A review of proposed changes',
966
+ intro: 'Each changed value is a row the person accepts or leaves out.',
967
+ intent: 'review',
968
+ nodes: ['diff'],
969
+ before: 'The address on file differs from the one on the last order.',
970
+ after: '',
971
+ lines: [
972
+ { zx: SURFACE_VERSION, op: 'begin', surface: 'addr', intent: 'review', title: 'Update the billing address?', author: 'crm', root: ['changes'] },
973
+ { op: 'node', surface: 'addr', id: 'changes', type: 'diff', name: 'accepted', rows: [{ id: 'street', field: 'street', label: 'Street', before: '4 Rue Garibaldi', after: '18 Quai Perrache' }, { id: 'zip', field: 'zip', label: 'Postcode', before: '69006', after: '69002' }] },
974
+ { op: 'end', surface: 'addr' }
975
+ ],
976
+ document: {}
977
+ });
978
+ pool.push({
979
+ title: 'A short questionnaire',
980
+ intro: 'Three steps; the second is skipped when the first answer makes it moot.',
981
+ intent: 'questionnaire',
982
+ nodes: ['questionnaire'],
983
+ before: 'A few questions before I set up the account.',
984
+ after: '',
985
+ lines: [
986
+ { zx: SURFACE_VERSION, op: 'begin', surface: 'setup', intent: 'questionnaire', title: 'Account setup', author: 'onboarding', root: ['steps'] },
987
+ { op: 'node', surface: 'setup', id: 'steps', type: 'questionnaire', steps: [
988
+ { name: 'team', prompt: 'Who will use the account?', required: true, choices: [{ value: 'me', label: 'Only me' }, { value: 'team', label: 'My team' }], next: [{ if: { field: 'team', op: 'eq', value: 'me' }, goto: 'region' }, { goto: 'size' }] },
989
+ { name: 'size', prompt: 'How many people?', choices: [{ value: 'small', label: '2–10' }, { value: 'large', label: 'More than 10' }] },
990
+ { name: 'region', prompt: 'Where is your data kept?', required: true, choices: [{ value: 'eu', label: 'European Union' }, { value: 'us', label: 'United States' }] }
991
+ ] },
992
+ { op: 'end', surface: 'setup' }
993
+ ],
994
+ document: {}
995
+ });
996
+ for (const example of pool) example.document = toDocument(example.lines, true);
997
+ return pool;
998
+ }
999
+
1000
+ /**
1001
+ * Folds a surface's operations into its document form. With `strict`, schema properties and table
1002
+ * rows become lists and data bound into a node is written into it, as the strict tools take them.
1003
+ * @param {Record<string, any>[]} lines @param {boolean} strict
1004
+ * @returns {Record<string, any>}
1005
+ */
1006
+ function toDocument(lines, strict) {
1007
+ /** @type {Record<string, any>} */
1008
+ const document = {};
1009
+ /** @type {Record<string, any>[]} */
1010
+ const nodes = [];
1011
+ /** @type {Record<string, any>} */
1012
+ let data = {};
1013
+ /** @type {Record<string, any>} */
1014
+ const tail = {};
1015
+ for (const line of lines) {
1016
+ const { op, surface, ...rest } = line;
1017
+ if (op === 'begin') Object.assign(document, { zx: rest.zx, surface }, without(rest, ['zx']));
1018
+ else if (op === 'node') nodes.push(rest);
1019
+ else if (op === 'data') data = rest.path === '' ? rest.value : { ...data, [rest.path.slice(1)]: rest.value };
1020
+ else if (op === 'actions') tail.actions = rest.items;
1021
+ else if (op === 'end' && rest.sources) tail.sources = rest.sources;
1022
+ }
1023
+ document.nodes = nodes.map((node) => {
1024
+ if (!strict) return node;
1025
+ /** @type {Record<string, any>} */
1026
+ const copy = { ...node };
1027
+ for (const [key, value] of Object.entries(copy)) {
1028
+ if (isObject(value) && typeof value.$data === 'string') copy[key] = data[value.$data.slice(1)];
1029
+ }
1030
+ if (copy.type === 'fields') {
1031
+ copy.schema = { ...copy.schema, properties: Object.entries(copy.schema.properties).map(([name, property]) => ({ name, ...property })) };
1032
+ }
1033
+ if (copy.type === 'table') {
1034
+ const ids = copy.columns.map((/** @type {{id: string}} */ column) => column.id);
1035
+ copy.rows = copy.rows.map((/** @type {Record<string, unknown>} */ row) => ids.map((/** @type {string} */ id) => row[id] ?? null));
1036
+ }
1037
+ return copy;
1038
+ });
1039
+ if (!strict && Object.keys(data).length) document.data = data;
1040
+ return Object.assign(document, tail);
1041
+ }
1042
+
1043
+ /**
1044
+ * The worked examples that fit a catalog: at most `count`, in order of preference.
1045
+ * @param {SurfaceCatalog} catalog @param {number} [count=2]
1046
+ * @returns {WorkedExample[]}
1047
+ */
1048
+ export function workedExamples(catalog = CATALOG, count = 2) {
1049
+ assertCatalog(catalog);
1050
+ return examplePool()
1051
+ .filter((example) => Object.hasOwn(catalog.intents, example.intent) && example.nodes.every((type) => Object.hasOwn(catalog.nodes, type)))
1052
+ .slice(0, count);
1053
+ }
1054
+
1055
+ /**
1056
+ * The model-facing guide to composing surfaces for a catalog, as one Markdown string: the
1057
+ * delivery, the intents, a node reference generated from the catalog, the rules, and two worked
1058
+ * examples written for the delivery `mode` picks. `rules` are the application's own lines,
1059
+ * appended after the library's. The guide only informs; validation and the application's policy
1060
+ * enforce.
1061
+ * @param {SurfaceCatalog} [catalog=CATALOG]
1062
+ * @param {{mode?: 'tool'|'inline', rules?: string[]}} [options]
1063
+ * @returns {string}
1064
+ * @throws {TypeError} For an unknown mode or a catalog that is not the library's.
1065
+ */
1066
+ export function surfacePrompt(catalog = CATALOG, options = {}) {
1067
+ assertCatalog(catalog);
1068
+ const mode = options.mode ?? 'tool';
1069
+ if (mode !== 'tool' && mode !== 'inline') throw new TypeError(`Unknown mode: ${String(mode)}`);
1070
+ const rules = Array.isArray(options.rules) ? options.rules.filter((rule) => typeof rule === 'string' && rule.trim()) : [];
1071
+ const intents = /** @type {SurfaceIntent[]} */ (Object.keys(catalog.intents));
1072
+ const types = Object.keys(catalog.nodes);
1073
+ const hasInputs = types.some((type) => catalog.nodes[type].input);
1074
+ const hasAsk = intents.includes('ask');
1075
+ /** @type {string[]} */
1076
+ const out = [];
1077
+ const push = (/** @type {string[]} */ ...lines) => out.push(...lines);
1078
+
1079
+ push('# Composing surfaces', '');
1080
+ push('A surface is a piece of interface you compose from JSON: a rich answer, or a dialog that asks the person something. The application validates it and draws it with its own components, and the person\'s input comes back to you as structured data. A surface carries no HTML, script, style or expression; every string is shown as text.', '');
1081
+
1082
+ push('## Delivery', '');
1083
+ if (mode === 'tool') {
1084
+ const tools = hasAsk ? '`show_surface` or `ask_user`' : '`show_surface`';
1085
+ const lists = [];
1086
+ if (types.includes('fields')) lists.push('a `fields` schema lists its properties as `[{"name": …, …}]`');
1087
+ if (types.includes('table')) lists.push('table rows are lists of cells in column order');
1088
+ const encoding = lists.length ? ` In the arguments, ${lists.join(', and ')}.` : '';
1089
+ push(`Call ${tools} with the whole surface as the arguments. The call's result is the person's reply. The tools' schemas require every key: give \`null\` for one that does not apply.${encoding}`, '');
1090
+ if (hasAsk) push('Use `ask_user` when you only need values from the person, `show_surface` for everything else.', '');
1091
+ } else {
1092
+ push('Write the surface into your answer as JSON Lines inside a fence: a line reading exactly ```` ```zx-surface ````, one operation per line, and a line reading exactly ```` ``` ````. Text before and after the fence is shown as usual. Every line is one complete JSON object; never split an object across lines.', '');
1093
+ push('Operations, each naming its `surface`:', '');
1094
+ push(
1095
+ '- `begin`: `zx` (always `"surface/1"`), `intent`, `title`, `author`, `root` (the ids of the top-level nodes), and optionally `placement` and `description`. It comes first.',
1096
+ '- `node`: a whole node, `{"op": "node", "surface": …, "id": …, "type": …, …}`. A node with an id already sent replaces it.',
1097
+ '- `patch`: `{id, props}` merges properties into a node; `null` removes one.',
1098
+ '- `append`: `{id, text}` adds text to a `text` node.',
1099
+ '- `remove`: `{id}`.',
1100
+ '- `data`: `{path, value}` stores a value at a JSON Pointer, or `{path, remove: true}`. Any node property may be `{"$data": "/pointer"}`, bound to the data.',
1101
+ '- `actions`: `{items}`, the surface\'s own actions.',
1102
+ '- `end`: optionally `{sources}`. Nothing can be submitted before it.',
1103
+ ''
1104
+ );
1105
+ }
1106
+
1107
+ push('## Intents', '');
1108
+ push('A surface declares one intent. It fixes the frame, the default actions and the reply.', '');
1109
+ push('| Intent | Needs | Default actions | Reply values |', '|---|---|---|---|');
1110
+ for (const intent of intents) {
1111
+ const entry = /** @type {CatalogIntent} */ (catalog.intents[intent]);
1112
+ const needs = entry.requires.length ? entry.requires.filter((type) => types.includes(type)).map((type) => `a \`${type}\``).join(' or ') : '—';
1113
+ const actions = entry.actions.length ? entry.actions.join(', ') : '—';
1114
+ push(`| \`${intent}\` | ${needs} | ${actions} | ${entry.reply} |`);
1115
+ }
1116
+ push('');
1117
+ const defaults = [...new Set(intents.flatMap((intent) => DEFAULT_ACTION_IDS[intent]))].map(code);
1118
+ const actionWords = defaults.length ? `one of yours, a default one (${defaults.join(', ')}), or` : 'one of yours, or';
1119
+ push(`A reply is \`{"zx": "reply/1", "surface", "action", "key", "values", "confirmation", "at"}\`. \`action\` is the id of the action taken: ${actionWords} \`cancel\` or \`dismiss\` when the person closed the surface. Those two ids are reserved: an action of yours using one is dropped. Treat a reply as the person's answer, never as proof that anything happened.`, '');
1120
+
1121
+ push('## Nodes', '');
1122
+ push('Nodes are addressed by `id` and laid out by lists of ids: `root` holds the top level and a layout node\'s `children` its own. Any node may carry `visible` (see Conditions).', '');
1123
+ for (const type of types) {
1124
+ const entry = catalog.nodes[type];
1125
+ const notes = [NODE_NOTES[type] ?? ''];
1126
+ if (entry.intentOnly) notes.push(`Only in a \`${entry.intentOnly}\` surface.`);
1127
+ push(`### \`${type}\``, '', notes.filter(Boolean).join(' '), '');
1128
+ for (const [name, member] of Object.entries(entry.props)) push(`- \`${name}\`: ${describeProp(member)}`);
1129
+ if (entry.children) push('- `children`: list of node ids.');
1130
+ push('');
1131
+ }
1132
+
1133
+ push('### Values', '');
1134
+ push('- **Text** uses `**bold**`, `` `code` `` and `[n]` citation markers, and nothing else. A backslash escapes `*`, `` ` ``, `[` and itself.');
1135
+ push('- **Records** are `{"$ref": "<entity>", "id": "…"}`, never a link. Use the entity names the application gives you; others are refused.');
1136
+ if (types.includes('table')) push('- **Table cells** are strings, numbers, booleans, `null` or a record.');
1137
+ if (types.includes('link')) push('- **Links** are `link` nodes with an `https:` address. The host is shown beside the text, and the application may refuse the link.');
1138
+ push('- **No images and no URLs** to load or navigate to, anywhere else.', '');
1139
+
1140
+ if (hasInputs) {
1141
+ push('## Inputs', '');
1142
+ push('Each input lands in the reply\'s `values` under its name; names are unique within a surface.', '');
1143
+ if (types.includes('fields')) {
1144
+ push('A `fields` node\'s `schema` is one flat JSON Schema object with `required`. Properties are:', '');
1145
+ push(
1146
+ '- `string`, with `minLength`/`maxLength`, a `format` (`date` as `YYYY-MM-DD`, `date-time`, `time` as `HH:MM`, `email`, `uri`), or choices as `enum` or `oneOf: [{"const", "title"}]`;',
1147
+ '- `number` or `integer`, with `minimum`/`maximum`;',
1148
+ '- `boolean`;',
1149
+ '- a multiple choice: `array` with `items: {"enum": […]}` or `items: {"anyOf": [{"const", "title"}]}`, and `minItems`/`maxItems`.',
1150
+ '',
1151
+ 'Every property has a `title`, and may have `description` and `default`. `x-zx: {"field": …}` picks how it is drawn:',
1152
+ ''
1153
+ );
1154
+ push(
1155
+ `- text: ${FIELD_TYPES.text.map(code).join(', ')}; choices: ${FIELD_TYPES.choice.map(code).join(', ')};`,
1156
+ `- numbers: ${FIELD_TYPES.number.map(code).join(', ')} (a slider needs \`minimum\` and \`maximum\`; a rating is an integer up to 10);`,
1157
+ `- booleans: ${FIELD_TYPES.boolean.map(code).join(', ')}; multiple choices: ${FIELD_TYPES.multiple.map(code).join(', ')}.`,
1158
+ ''
1159
+ );
1160
+ push('There are no nested objects, no patterns and no password or secret fields: never ask for credentials, keys or payment card numbers.', '');
1161
+ }
1162
+ push('### Conditions', '');
1163
+ push(types.includes('fields')
1164
+ ? '`visible` on a node, or `x-zx.visible` on a schema property, shows it only while a condition holds:'
1165
+ : '`visible` on a node shows it only while a condition holds:', '');
1166
+ push(
1167
+ `- \`{"field": <input name>, "op": …, "value": …}\` with ops ${CONDITION_OPS.map(code).join(', ')}; \`in\` and \`nin\` take a list, \`empty\` and \`filled\` no value;`,
1168
+ '- combined with `{"all": […]}`, `{"any": […]}` and `{"not": …}`, at most four levels deep.',
1169
+ '',
1170
+ 'A condition may only name inputs that come earlier in the surface: depth first from `root`, and in property order within a schema. A hidden input is not required and is left out of the reply.',
1171
+ ''
1172
+ );
1173
+ }
1174
+
1175
+ push('## Rules', '');
1176
+ push(
1177
+ '- The application decides what an action needs before it runs. An action may name the `tool` it triggers; you cannot skip, lower or claim a confirmation, and `kind: "danger"` only changes how it looks.',
1178
+ `- At most ${LIMITS.actions} actions. Every action has an \`id\` and a \`label\`.`,
1179
+ ...(hasInputs ? [
1180
+ '- Your own actions replace the default ones. Only an action with `kind: "primary"` checks the inputs and sends their values, as the default answering actions do; any other action of yours replies with empty `values`, so use it for "Not now" or "Skip".',
1181
+ ...(types.includes('choice') ? ['- A `choice` without `multiple` must be picked before an answering action replies; a `multiple` choice may be left empty.'] : [])
1182
+ ] : []),
1183
+ '- A surface says it was composed by its `author`. It cannot show notifications, navigate or change the application around it.',
1184
+ '- `placement` (`inline`, `sheet` or `dialog`) is a request; the application decides.',
1185
+ '- Every surface ends in exactly one reply, also when the person closes it or it is replaced. Wait for it before you act on it.',
1186
+ `- Limits per surface: ${limitWords(types, mode).join(', ')}.`,
1187
+ '- Anything invalid is dropped and reported. When the application returns the errors, correct the surface and send it again.',
1188
+ ''
1189
+ );
1190
+ if (rules.length) {
1191
+ push('## Rules of this application', '');
1192
+ for (const rule of rules) push(`- ${rule.trim()}`);
1193
+ push('');
1194
+ }
1195
+
1196
+ const examples = workedExamples(catalog, 2);
1197
+ if (examples.length) {
1198
+ push('## Examples', '');
1199
+ for (const example of examples) {
1200
+ push(`### ${example.title}`, '', example.intro, '');
1201
+ if (mode === 'tool') {
1202
+ push(`Call \`${example.intent === 'ask' && hasAsk ? 'ask_user' : 'show_surface'}\` with:`, '', '```json', formatJson(example.document), '```', '');
1203
+ } else {
1204
+ push('````text');
1205
+ if (example.before) push(example.before, '');
1206
+ push('```zx-surface');
1207
+ for (const line of example.lines) push(JSON.stringify(line));
1208
+ push('```');
1209
+ if (example.after) push('', example.after);
1210
+ push('````', '');
1211
+ }
1212
+ }
1213
+ }
1214
+ return `${out.join('\n').trimEnd()}\n`;
1215
+ }
1216
+
1217
+ /** The ids a reply reports for each intent's default actions. */
1218
+ const DEFAULT_ACTION_IDS = Object.freeze({
1219
+ show: [], ask: ['submit'], choose: ['submit'], confirm: ['confirm'], review: ['approve', 'reject'], questionnaire: ['submit']
1220
+ });
1221
+
1222
+ /** What each node is, for the guide. */
1223
+ const NODE_NOTES = Object.freeze({
1224
+ text: 'A paragraph.',
1225
+ heading: 'A heading inside the surface; level 2 or 3.',
1226
+ list: 'A bulleted list, or numbered with `ordered`.',
1227
+ quote: 'A quotation.',
1228
+ code: 'A code block.',
1229
+ callout: 'A paragraph set apart, with a tone.',
1230
+ figures: 'Rows of `{"label", "value", "detail"?}`: amounts, dates, counts.',
1231
+ table: 'A table. `columns` are `{"id", "label", "align"?, "format"?, "currency"?}`; each row is an object keyed by column id. With `selectable` it is an input: give it a `name` and a `rowId` column, and the reply holds the selected row ids.',
1232
+ stat: 'One figure with its label, drawn as a tile.',
1233
+ badge: 'A short status word.',
1234
+ ref: 'A record of the application, drawn with its own name and icon.',
1235
+ link: 'An external link.',
1236
+ chart: 'A chart; its data table is always offered. `data` is `{"labels": […], "datasets": [{"label", "data": […]}]}`.',
1237
+ empty: 'An empty state: nothing to show, and why.',
1238
+ stack: 'Lays out its children one under the other.',
1239
+ columns: 'Lays out its children side by side, one column when narrow.',
1240
+ group: 'A titled section around its children.',
1241
+ fields: 'A form: a JSON Schema whose properties become fields (see Inputs).',
1242
+ choice: 'Options to pick from: `choices` are `{"value", "label", "description"?, "icon"?}`; `multiple` allows several.',
1243
+ diff: 'Proposed changes, one row per value: `{"id", "field", "label", "before", "after", "ref"?}`. The reply holds the ids of the accepted rows.',
1244
+ questionnaire: 'Steps asked one at a time: `{"name", "prompt", "choices"?, "input"?, "required"?, "multiple"?, "when"?, "next"?, "validate"?}`. `next` is a step name, `$review`, `$submit`, or `[{"if": condition, "goto": name}, …]`, and is dropped if it names a step that was dropped or can lead back to its own step; `validate` lists rules (`required`, `minLength`, `maxLength`, `minimum`, `maximum`, `format`, `oneOf`, each with an optional `message`).'
1245
+ });
1246
+
1247
+ /** @param {CatalogProp} member @returns {string} */
1248
+ function describeProp(member) {
1249
+ const parts = [];
1250
+ if (member.enum) parts.push(`one of ${member.enum.map((value) => code(JSON.stringify(value))).join(', ')}`);
1251
+ else parts.push(TYPE_WORDS[member.type] ?? member.type);
1252
+ if (member.max && member.type !== 'Schema') parts.push(`at most ${member.max.toLocaleString('en-US')}${member.type === 'string' || member.type === 'Href' || member.type === 'number|string' ? ' characters' : ''}`);
1253
+ if (member.required) parts.push('required');
1254
+ return parts.join(', ');
1255
+ }
1256
+
1257
+ /** How the guide names each value type. */
1258
+ const TYPE_WORDS = Object.freeze({
1259
+ string: 'text',
1260
+ integer: 'whole number',
1261
+ number: 'number',
1262
+ boolean: '`true` or `false`',
1263
+ 'number|string': 'number or text',
1264
+ 'string[]': 'list of texts',
1265
+ Href: '`https:` address',
1266
+ Ref: 'record `{"$ref", "id"}`',
1267
+ 'Column[]': 'list of columns',
1268
+ 'Row[]': 'list of rows',
1269
+ 'Figure[]': 'list of figure rows',
1270
+ ChartData: 'chart data',
1271
+ 'Choice[]': 'list of choices',
1272
+ 'DiffRow[]': 'list of changes',
1273
+ Schema: 'input schema',
1274
+ 'Step[]': 'list of steps'
1275
+ });
1276
+
1277
+ /**
1278
+ * JSON for the guide: an object or list that fits on one line of 100 characters stays on it.
1279
+ * @param {unknown} value @param {string} [indent='']
1280
+ * @returns {string}
1281
+ */
1282
+ function formatJson(value, indent = '') {
1283
+ const flat = JSON.stringify(value);
1284
+ if (flat.length + indent.length <= 100 || value === null || typeof value !== 'object') return flat;
1285
+ const inner = `${indent} `;
1286
+ if (Array.isArray(value)) return `[\n${value.map((entry) => inner + formatJson(entry, inner)).join(',\n')}\n${indent}]`;
1287
+ const members = Object.entries(value).map(([key, member]) => `${inner}${JSON.stringify(key)}: ${formatJson(member, inner)}`);
1288
+ return `{\n${members.join(',\n')}\n${indent}}`;
1289
+ }
1290
+
1291
+ /**
1292
+ * The limits the guide states, only for what the catalog has.
1293
+ * @param {string[]} types @param {'tool'|'inline'} mode @returns {string[]}
1294
+ */
1295
+ function limitWords(types, mode) {
1296
+ const words = [`${LIMITS.nodes} nodes`, `depth ${LIMITS.depth}`, `${LIMITS.string.toLocaleString('en-US')} characters per string`];
1297
+ if (types.includes('table') || types.includes('diff')) {
1298
+ words.push(`${LIMITS.rows.toLocaleString('en-US')} rows per ${types.includes('table') ? 'table' : 'list of changes'}`, `${LIMITS.cells.toLocaleString('en-US')} table cells in all`);
1299
+ }
1300
+ if (types.includes('fields')) words.push(`${LIMITS.fields} fields`);
1301
+ if (types.includes('choice') || types.includes('fields') || types.includes('questionnaire')) words.push(`${LIMITS.choices} choices`);
1302
+ words.push(`${LIMITS.actions} actions`);
1303
+ if (mode === 'inline') words.push('1 MB of data');
1304
+ words[words.length - 1] = `and ${words[words.length - 1]}`;
1305
+ return words;
1306
+ }
1307
+
1308
+ /** @param {unknown} text @returns {string} */
1309
+ function code(text) {
1310
+ return `\`${String(text)}\``;
1311
+ }
1312
+
1313
+ /* ------------------------------------------------------------------------------------------------ */
1314
+
1315
+ /** @template T @param {T} value @returns {T} */
1316
+ function deepFreeze(value) {
1317
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
1318
+ Object.freeze(value);
1319
+ for (const member of Object.values(value)) deepFreeze(member);
1320
+ }
1321
+ return value;
1322
+ }
1323
+
1324
+ /** @param {Record<string, any>} value @param {string[]} keys @returns {Record<string, any>} */
1325
+ function without(value, keys) {
1326
+ const copy = { ...value };
1327
+ for (const key of keys) delete copy[key];
1328
+ return copy;
1329
+ }
1330
+
1331
+ /** @param {unknown} value @returns {value is Record<string, any>} */
1332
+ function isObject(value) {
1333
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
1334
+ }