@zeyos/zx 5.6.0 → 5.7.0

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 (215) hide show
  1. package/CHANGELOG.md +154 -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/code-editor/code-editor.d.ts +7 -2
  15. package/dist/types/components/composer/composer.d.ts +206 -4
  16. package/dist/types/components/composer/queue.d.ts +76 -0
  17. package/dist/types/components/copy/copy-button.d.ts +6 -4
  18. package/dist/types/components/copy/copy-input.d.ts +10 -6
  19. package/dist/types/components/datebox/date-range-box.d.ts +33 -0
  20. package/dist/types/components/datebox/placeholder.d.ts +7 -0
  21. package/dist/types/components/dock/dock.d.ts +12 -3
  22. package/dist/types/components/entity-ref/entity-ref.d.ts +5 -3
  23. package/dist/types/components/field-upload/field-upload.d.ts +3 -2
  24. package/dist/types/components/file-item/file-item.d.ts +3 -2
  25. package/dist/types/components/file-list/file-list.d.ts +14 -8
  26. package/dist/types/components/filter/filter-model.d.ts +31 -1
  27. package/dist/types/components/filter/filter.d.ts +20 -2
  28. package/dist/types/components/finder/finder.d.ts +14 -6
  29. package/dist/types/components/flag/flag.d.ts +99 -0
  30. package/dist/types/components/grid/grid.d.ts +1 -1
  31. package/dist/types/components/kanban-view/kanban-view.d.ts +8 -66
  32. package/dist/types/components/launcher/launcher.d.ts +2 -0
  33. package/dist/types/components/multi-value-editor/multi-value-editor.d.ts +3 -2
  34. package/dist/types/components/number-field/number-field.d.ts +17 -6
  35. package/dist/types/components/prompt-starters/prompt-starters.d.ts +107 -0
  36. package/dist/types/components/prose/prose.d.ts +9 -6
  37. package/dist/types/components/questionnaire/conditions.d.ts +270 -0
  38. package/dist/types/components/questionnaire/items.d.ts +52 -30
  39. package/dist/types/components/questionnaire/questionnaire.d.ts +44 -4
  40. package/dist/types/components/rating/rating.d.ts +5 -3
  41. package/dist/types/components/select/country.d.ts +106 -0
  42. package/dist/types/components/select/field-adapter.d.ts +2 -1
  43. package/dist/types/components/select/locale.d.ts +102 -0
  44. package/dist/types/components/select/select.d.ts +41 -2
  45. package/dist/types/components/slider/slider.d.ts +1 -0
  46. package/dist/types/components/sort-control/sort-control.d.ts +7 -3
  47. package/dist/types/components/source-list/source-list.d.ts +7 -5
  48. package/dist/types/components/split-view/split-view.d.ts +5 -3
  49. package/dist/types/components/surface/catalog.d.ts +260 -0
  50. package/dist/types/components/surface/elicit.d.ts +81 -0
  51. package/dist/types/components/surface/mcp.d.ts +165 -0
  52. package/dist/types/components/surface/schema.d.ts +314 -0
  53. package/dist/types/components/surface/stream.d.ts +118 -0
  54. package/dist/types/components/surface/surface.d.ts +718 -0
  55. package/dist/types/components/surface/text.d.ts +277 -0
  56. package/dist/types/components/surface/validate.d.ts +339 -0
  57. package/dist/types/components/table/table.d.ts +55 -3
  58. package/dist/types/components/table/window.d.ts +203 -0
  59. package/dist/types/components/toolbar/toolbar.d.ts +10 -6
  60. package/dist/types/components/tooltip/tooltip.d.ts +2 -2
  61. package/dist/types/components/tree/tree.d.ts +20 -13
  62. package/dist/types/core/component.d.ts +10 -0
  63. package/dist/types/core/date.d.ts +8 -1
  64. package/dist/types/core/dom.d.ts +1 -0
  65. package/dist/types/core/http.d.ts +10 -0
  66. package/dist/types/core/i18n.d.ts +38 -0
  67. package/dist/types/core/messages.d.ts +344 -1
  68. package/dist/types/core/storage.d.ts +7 -2
  69. package/dist/types/elements/define.d.ts +21 -46
  70. package/dist/types/elements/definitions.d.ts +147 -0
  71. package/dist/types/elements/kit.d.ts +7 -0
  72. package/dist/types/elements/reflect.d.ts +6 -3
  73. package/dist/types/index.d.ts +10 -1
  74. package/dist/types/internal/date-locale.d.ts +7 -0
  75. package/dist/types/internal/json-patch.d.ts +146 -0
  76. package/dist/types/locales/de.d.ts +13 -0
  77. package/dist/types/locales/en.d.ts +2 -0
  78. package/dist/types/locales/index.d.ts +823 -0
  79. package/dist/types/zeyos/view.d.ts +8 -1
  80. package/dist/zx-zeyos.esm.js +16802 -15180
  81. package/dist/zx-zeyos.esm.min.js +5 -5
  82. package/dist/zx.core.css +1276 -0
  83. package/dist/zx.core.min.css +1 -0
  84. package/dist/zx.css +498 -134
  85. package/dist/zx.esm.js +40778 -29654
  86. package/dist/zx.esm.min.js +36 -23
  87. package/dist/zx.global.js +40778 -29654
  88. package/dist/zx.global.min.js +36 -23
  89. package/dist/zx.layered.css +17302 -0
  90. package/dist/zx.layered.min.css +1 -0
  91. package/dist/zx.min.css +1 -1
  92. package/docs/agent-catalog.json +12501 -0
  93. package/docs/agent-surfaces.md +340 -0
  94. package/docs/api.json +851 -121
  95. package/docs/llms.md +1018 -71
  96. package/docs/llms.txt +30 -9
  97. package/package.json +29 -6
  98. package/src/components/account-menu/account-menu.js +6 -3
  99. package/src/components/activity-item/activity-item.js +2 -1
  100. package/src/components/activity-list/activity-list.js +16 -10
  101. package/src/components/agent-thread/ag-ui.js +1439 -0
  102. package/src/components/agent-thread/agent-thread.js +359 -54
  103. package/src/components/agent-thread/ui-message-stream.js +1281 -0
  104. package/src/components/app-sidebar/app-sidebar.js +18 -8
  105. package/src/components/approval-card/approval-card.js +3 -2
  106. package/src/components/block-view/block-view.js +7 -6
  107. package/src/components/breadcrumb/breadcrumb.js +8 -5
  108. package/src/components/calendar/calendar-model.js +8 -2
  109. package/src/components/calendar/calendar.js +53 -18
  110. package/src/components/chart/chart.js +54 -23
  111. package/src/components/code-editor/code-editor.js +45 -8
  112. package/src/components/code-editor/field-adapter.js +1 -1
  113. package/src/components/composer/composer.css +80 -1
  114. package/src/components/composer/composer.js +390 -16
  115. package/src/components/composer/queue.js +78 -0
  116. package/src/components/context-menu/context-menu.js +12 -1
  117. package/src/components/copy/copy-button.js +9 -7
  118. package/src/components/copy/copy-input.js +10 -6
  119. package/src/components/date-picker/date-picker.js +2 -1
  120. package/src/components/date-picker/date-range-picker.js +8 -7
  121. package/src/components/datebox/date-range-box.js +3 -9
  122. package/src/components/datebox/datebox.js +18 -21
  123. package/src/components/datebox/placeholder.js +18 -0
  124. package/src/components/dialog/dialog.js +1 -1
  125. package/src/components/dock/dock.js +34 -13
  126. package/src/components/entity-ref/entity-ref.js +16 -5
  127. package/src/components/field-upload/field-upload.js +81 -38
  128. package/src/components/file-item/file-item.js +70 -40
  129. package/src/components/file-list/file-list.js +15 -9
  130. package/src/components/filter/filter-model.js +46 -8
  131. package/src/components/filter/filter.css +3 -3
  132. package/src/components/filter/filter.js +29 -10
  133. package/src/components/filter-panel/filter-panel.js +13 -5
  134. package/src/components/finder/finder.js +50 -26
  135. package/src/components/flag/flag.css +40 -0
  136. package/src/components/flag/flag.js +177 -0
  137. package/src/components/form/form.js +1 -1
  138. package/src/components/grid/grid.js +22 -8
  139. package/src/components/kanban-view/kanban-view.js +51 -81
  140. package/src/components/launcher/launcher.js +17 -2
  141. package/src/components/list-toolbar/list-toolbar.js +2 -1
  142. package/src/components/master-panel/master-panel.js +1 -1
  143. package/src/components/menu-button/menu-button.js +4 -0
  144. package/src/components/message/message.js +3 -0
  145. package/src/components/multi-value-editor/multi-value-editor.js +10 -9
  146. package/src/components/navigation-bar/navigation-bar.js +3 -3
  147. package/src/components/number-field/number-field.js +29 -13
  148. package/src/components/prompt-starters/prompt-starters.css +91 -0
  149. package/src/components/prompt-starters/prompt-starters.js +206 -0
  150. package/src/components/prose/prose.js +14 -10
  151. package/src/components/questionnaire/conditions.js +666 -0
  152. package/src/components/questionnaire/items.js +150 -41
  153. package/src/components/questionnaire/questionnaire.js +126 -32
  154. package/src/components/rating/rating.js +5 -4
  155. package/src/components/run-status/run-status.js +2 -2
  156. package/src/components/select/country.js +136 -0
  157. package/src/components/select/field-adapter.js +7 -2
  158. package/src/components/select/locale.js +219 -0
  159. package/src/components/select/select.css +20 -22
  160. package/src/components/select/select.js +94 -12
  161. package/src/components/sheet/sheet-stack.js +10 -1
  162. package/src/components/slider/slider.js +7 -2
  163. package/src/components/sort-control/sort-control.js +15 -5
  164. package/src/components/source-list/source-list.js +7 -4
  165. package/src/components/split-view/split-view.js +5 -3
  166. package/src/components/surface/catalog.js +1334 -0
  167. package/src/components/surface/elicit.js +107 -0
  168. package/src/components/surface/mcp.js +243 -0
  169. package/src/components/surface/schema.js +644 -0
  170. package/src/components/surface/stream.js +245 -0
  171. package/src/components/surface/surface.css +308 -0
  172. package/src/components/surface/surface.js +2291 -0
  173. package/src/components/surface/text.js +513 -0
  174. package/src/components/surface/validate.js +2218 -0
  175. package/src/components/tabbox/tabbox.js +9 -0
  176. package/src/components/table/table.css +63 -3
  177. package/src/components/table/table.js +167 -28
  178. package/src/components/table/window.js +317 -0
  179. package/src/components/toolbar/toolbar.js +12 -7
  180. package/src/components/tooltip/tooltip.css +2 -3
  181. package/src/components/tooltip/tooltip.js +32 -5
  182. package/src/components/tree/tree.js +53 -23
  183. package/src/core/component.js +25 -1
  184. package/src/core/date.js +62 -16
  185. package/src/core/dom.js +22 -2
  186. package/src/core/format.js +15 -13
  187. package/src/core/http.js +29 -20
  188. package/src/core/i18n.js +83 -10
  189. package/src/core/keyboard.js +79 -8
  190. package/src/core/messages.js +376 -2
  191. package/src/core/overlay-host.js +1 -0
  192. package/src/core/storage.js +59 -6
  193. package/src/elements/define.js +178 -130
  194. package/src/elements/definitions.js +229 -0
  195. package/src/elements/kit.js +444 -0
  196. package/src/elements/reflect.js +8 -3
  197. package/src/index.js +10 -1
  198. package/src/internal/date-locale.js +11 -0
  199. package/src/internal/json-patch.js +405 -0
  200. package/src/locales/de.js +911 -0
  201. package/src/locales/en.js +2 -0
  202. package/src/locales/index.js +7 -0
  203. package/src/zeyos/calendar.js +2 -1
  204. package/src/zeyos/form.js +2 -1
  205. package/src/zeyos/launcher.js +7 -6
  206. package/src/zeyos/module-bar.js +2 -1
  207. package/src/zeyos/schema.js +37 -23
  208. package/src/zeyos/select.js +4 -3
  209. package/src/zeyos/table.js +2 -13
  210. package/src/zeyos/view.js +57 -17
  211. package/styles/core.css +11 -0
  212. package/styles/tokens/semantic.css +1 -0
  213. package/styles/zeyos.css +2 -0
  214. package/styles/zx.css +4 -8
  215. package/styles/zx.layered.css +1 -0
@@ -3,6 +3,7 @@ import { Component } from '../../core/component.js';
3
3
  import { h, restoreTarget, snapshotTarget } from '../../core/dom.js';
4
4
  import { formatFileSize } from '../../core/format.js';
5
5
  import { icon } from '../../core/icons.js';
6
+ import { isEditableTarget } from '../../core/keyboard.js';
6
7
  import { escapeRegExp, uid } from '../../core/util.js';
7
8
  import { AGENT_MESSAGES, initialsOf } from '../../internal/agent-model.js';
8
9
  import { ApprovalCard } from '../approval-card/approval-card.js';
@@ -10,8 +11,11 @@ import { Avatar } from '../avatar/avatar.js';
10
11
  import { BlockView } from '../block-view/block-view.js';
11
12
  import { copyButton } from '../copy/copy-button.js';
12
13
  import { emptyState } from '../empty-state/empty-state.js';
14
+ import { skeletonText } from '../skeleton/skeleton.js';
13
15
  import { RunTrace } from '../run-trace/run-trace.js';
14
16
  import { SourceList } from '../source-list/source-list.js';
17
+ import { Surface } from '../surface/surface.js';
18
+ import { dateLocale } from '../../internal/date-locale.js';
15
19
 
16
20
  /** @typedef {import('../../internal/agent-model.js').ThreadItem} ThreadItem */
17
21
  /** @typedef {import('../../internal/agent-model.js').Author} Author */
@@ -19,6 +23,43 @@ import { SourceList } from '../source-list/source-list.js';
19
23
  /** @typedef {import('../../internal/agent-model.js').Block} Block */
20
24
  /** @typedef {import('../empty-state/empty-state.js').EmptyStateOptions} EmptyStateOptions */
21
25
  /** @typedef {'copy'|'regenerate'|'branch'|'rate'} AnswerAction */
26
+ /** @typedef {import('../surface/surface.js').SurfaceOptions} SurfaceOptions */
27
+ /** @typedef {import('../surface/text.js').SurfaceReply} SurfaceReply */
28
+
29
+ /**
30
+ * Something still on its way — a tool call's arguments, a document being composed — drawn as a
31
+ * Skeleton under its author's byline. It is replaced by the item it stands for, and goes without
32
+ * replying or announcing anything.
33
+ * The type's name is reserved; `placeholder` is free for an application's own items.
34
+ * @typedef {Object} PlaceholderItem
35
+ * @property {string} id
36
+ * @property {'zx-placeholder'} type
37
+ * @property {string} [at]
38
+ * @property {string} [author]
39
+ * @property {number} [lines=2] Skeleton lines.
40
+ */
41
+
42
+ /**
43
+ * Where `upsert()` puts an item it adds.
44
+ * @typedef {Object} UpsertOptions
45
+ * @property {string|null} [after=null] The id of the item to insert the new item right after;
46
+ * the end of the thread when null or unknown. An item already in the thread stays where it is.
47
+ */
48
+
49
+ /**
50
+ * A surface in the conversation: an answer or a question an agent composed. The item comes from
51
+ * the application, never from a model line, so its `token` and `catalog` are the application's.
52
+ * Without a `document` it waits for operations streamed into `thread.surface(id)`.
53
+ * @typedef {Object} SurfaceItem
54
+ * @property {string} id
55
+ * @property {'surface'} type
56
+ * @property {string} [at]
57
+ * @property {string} [author]
58
+ * @property {import('../surface/validate.js').SurfaceDocument|null} [document] The whole surface.
59
+ * @property {string|null} [token] The application's token, copied into the reply.
60
+ * @property {import('../surface/catalog.js').SurfaceCatalog} [catalog] A narrowed catalog.
61
+ * @property {SurfaceReply|null} [reply] The reply it gave; the surface is drawn as its receipt.
62
+ */
22
63
 
23
64
  /**
24
65
  * What a registered item renderer receives besides the item.
@@ -64,8 +105,12 @@ import { SourceList } from '../source-list/source-list.js';
64
105
  * @property {((at: string) => string)|null} [formatTime=null] Formats an item's `at`; the local
65
106
  * clock time when null.
66
107
  * @property {string} [locale] Locale for times.
108
+ * @property {Omit<SurfaceOptions, 'document'|'token'|'catalog'|'reply'>} [surfaceOptions={}] Options
109
+ * handed to every Surface the thread draws: the application's `policy`, `resolve`, `chartAdapter`
110
+ * and `msg`. Its authors, heading level and locale are the thread's unless given here.
67
111
  * @property {Record<string, string>|Record<string, Record<string, string>>} [msg] Localized messages.
68
112
  * @property {(event: CustomEvent<{item: ThreadItem, action: string, value?: unknown}>) => void} [onaction] Answer action listener.
113
+ * @property {(event: CustomEvent<{item: ThreadItem, reply: SurfaceReply}>) => void} [onreply] Surface reply listener.
69
114
  * @property {(event: CustomEvent<{item: ThreadItem, values: Record<string, unknown>}>) => void} [onapprove] Approval listener.
70
115
  * @property {(event: CustomEvent<{item: ThreadItem, values: Record<string, unknown>}>) => void} [onedit] Edit listener.
71
116
  * @property {(event: CustomEvent<{item: ThreadItem, reason: string}>) => void} [onreject] Rejection listener.
@@ -84,6 +129,7 @@ import { SourceList } from '../source-list/source-list.js';
84
129
  * @property {RunTrace|null} trace A trace's steps.
85
130
  * @property {SourceList|null} sources An answer's sources.
86
131
  * @property {ApprovalCard|null} card An approval.
132
+ * @property {Surface|null} [surface] A surface.
87
133
  */
88
134
 
89
135
  const MESSAGES = Object.freeze({
@@ -108,6 +154,7 @@ const MESSAGES = Object.freeze({
108
154
  'agentThread.answered': '%1 answered',
109
155
  'agentThread.working': '%1 is working',
110
156
  'agentThread.needsApproval': '%1 needs your approval',
157
+ 'agentThread.needsAnswer': '%1 needs your answer',
111
158
  'agentThread.stoppedAnnounce': 'Stopped',
112
159
  'agentThread.writingNow': '%1 is writing…',
113
160
  'agentThread.edit': 'Edit message',
@@ -138,6 +185,7 @@ const END_SLACK = 48;
138
185
  * @fires AgentThread#artifact
139
186
  * @fires AgentThread#reveal
140
187
  * @fires AgentThread#open
188
+ * @fires AgentThread#reply
141
189
  * @extends {Component<AgentThreadOptions>}
142
190
  */
143
191
  export class AgentThread extends Component {
@@ -160,6 +208,7 @@ export class AgentThread extends Component {
160
208
  sourceIcons: {},
161
209
  now: null,
162
210
  formatTime: null,
211
+ surfaceOptions: {},
163
212
  msg: MESSAGES
164
213
  };
165
214
 
@@ -167,8 +216,9 @@ export class AgentThread extends Component {
167
216
  static #renderers = new Map();
168
217
 
169
218
  /**
170
- * Registers how items of another type are drawn — an application's own, or a surface. A
171
- * built-in type cannot be replaced.
219
+ * Registers how items of another type are drawn. An application's own renderer for `surface`
220
+ * replaces the library's drawing of that type; the types the library always draws cannot be
221
+ * replaced.
172
222
  * @param {string} type Item type.
173
223
  * @param {ThreadItemRenderer} render Draws the item's content.
174
224
  * @returns {typeof AgentThread}
@@ -183,7 +233,8 @@ export class AgentThread extends Component {
183
233
  }
184
234
 
185
235
  /**
186
- * Reports whether a type has a registered renderer.
236
+ * Reports whether a type has a registered renderer. `surface` answers false until an
237
+ * application registers its own, so a guarded `register()` still takes effect.
187
238
  * @param {string} type
188
239
  * @returns {boolean}
189
240
  */
@@ -204,12 +255,18 @@ export class AgentThread extends Component {
204
255
  /** @type {string[]} */
205
256
  this._order = [];
206
257
  this._announceTimer = 0;
258
+ this._askingPerson = false;
207
259
  /** @type {Element|null} */
208
260
  this._scrollHost = null;
261
+ /** @type {EventTarget|null} */
262
+ this._scrollTarget = null;
263
+ this._onScroll = () => { if (this._atEnd()) this._latestButton.hidden = true; };
209
264
  /** @type {string|null} */
210
265
  this._latestAnswer = null;
211
266
  /** @type {Map<string, {expanded?: boolean|null, controls?: string|null}>} Artifact open states, for answers drawn later. */
212
267
  this._artifacts = new Map();
268
+ /** @type {WeakSet<Surface>} Surfaces answered elsewhere, whose going is no reply. */
269
+ this._answeredElsewhere = new WeakSet();
213
270
 
214
271
  this._feed = h('div', {
215
272
  class: 'zx-agent-thread__feed', role: 'feed', 'aria-busy': 'false',
@@ -238,29 +295,40 @@ export class AgentThread extends Component {
238
295
  /* ------------------------------------------------------------------ public API -- */
239
296
 
240
297
  /**
241
- * Replaces the conversation.
298
+ * Replaces the conversation. Everything is dropped and then drawn anew, except a surface already
299
+ * drawn, which stays so that one still matching keeps answering.
242
300
  * @param {ThreadItem[]} items
243
301
  * @returns {this}
244
302
  */
245
303
  setItems(items) {
246
- for (const id of [...this._order]) this._drop(id);
247
- for (const item of Array.isArray(items) ? items : []) this._add(item);
304
+ const list = (Array.isArray(items) ? items : []).filter((item) => item && typeof item === 'object' && item.id != null);
305
+ const staying = new Set(list.filter((item) => item.type === 'surface' && this._entries.get(String(item.id))?.surface)
306
+ .map((item) => String(item.id)));
307
+ for (const id of [...this._order]) if (!staying.has(id)) this._drop(id);
308
+ for (const item of list) {
309
+ if (item.type === 'surface' && staying.has(String(item.id))) this._replace(String(item.id), item);
310
+ else this._add(item);
311
+ }
312
+ if (staying.size) this._arrange(list.map((item) => String(item.id)));
248
313
  this._syncPositions();
249
314
  this._syncEmpty();
250
315
  return this;
251
316
  }
252
317
 
253
318
  /**
254
- * Adds an item, or replaces the item with the same id where it stands.
319
+ * Adds an item, or replaces the item with the same id where it stands. A new item goes at the
320
+ * end, or right after the item `options.after` names.
255
321
  * @param {ThreadItem} item
322
+ * @param {UpsertOptions} [options]
256
323
  * @returns {this}
257
324
  */
258
- upsert(item) {
325
+ upsert(item, options = {}) {
259
326
  if (!item || typeof item !== 'object' || item.id == null) return this;
260
327
  const id = String(item.id);
328
+ const after = options?.after == null ? null : String(options.after);
261
329
  this._follow(() => {
262
330
  if (this._entries.has(id)) this._replace(id, item);
263
- else this._add(item, { announce: true });
331
+ else this._add(item, { announce: true, after });
264
332
  this._syncPositions();
265
333
  this._syncEmpty();
266
334
  });
@@ -268,9 +336,10 @@ export class AgentThread extends Component {
268
336
  }
269
337
 
270
338
  /**
271
- * Changes part of an item. The common changes are made in place — an answer finishing or
272
- * stopping, a trace's steps, an approval's status — so focus and selection inside the item
273
- * survive; anything else redraws the item.
339
+ * Changes part of an item. The common changes are made in place — an answer finishing, stopping
340
+ * or writing on, a trace's steps, an approval's status — so what the reader opened, and focus and
341
+ * selection where the blocks stay, survive; anything else redraws the item. Metadata patches
342
+ * retain an answer's live blocks; explicit `blocks` or `versions` remain authoritative.
274
343
  * @param {string} id
275
344
  * @param {Record<string, unknown>} partial
276
345
  * @returns {this}
@@ -279,7 +348,10 @@ export class AgentThread extends Component {
279
348
  const entry = this._entries.get(String(id));
280
349
  if (!entry || !partial || typeof partial !== 'object') return this;
281
350
  const before = entry.item;
282
- const item = /** @type {ThreadItem} */ ({ ...before, ...structuredClone(partial), id: before.id, type: before.type });
351
+ // Streamed blocks live in the BlockView until read back. Start a partial update from that
352
+ // snapshot so a redraw for metadata (including version metadata) cannot rewind its text.
353
+ const current = before.type === 'answer' ? this.get(String(id)) ?? before : before;
354
+ const item = this._intoVersion(/** @type {ThreadItem} */ ({ ...current, ...cloneItem({ ...partial, type: before.type }), id: before.id, type: before.type }), partial);
283
355
  const keys = Object.keys(partial);
284
356
  const only = (/** @type {string[]} */ allowed) => keys.every((key) => allowed.includes(key));
285
357
  this._follow(() => {
@@ -287,11 +359,16 @@ export class AgentThread extends Component {
287
359
  && (!('steps' in partial) || entry.trace)) {
288
360
  entry.item = item;
289
361
  const answer = /** @type {Extract<ThreadItem, {type: 'answer'}>} */ (item);
290
- if ('blocks' in partial) entry.view.setBlocks(answer.blocks ?? []);
362
+ // An answer that writes on, or is no longer stopped, takes its view back up where it stands.
363
+ const reopened = Boolean(answer.streaming) && !(/** @type {any} */ (before)).streaming;
364
+ const unstopped = !answer.stopped && Boolean(/** @type {any} */ (before).stopped);
365
+ if ('blocks' in partial || reopened || unstopped) {
366
+ entry.view.setBlocks('blocks' in partial ? answer.blocks ?? [] : entry.view.getBlocks(), reopened ? { streaming: true } : {});
367
+ }
291
368
  if ('steps' in partial) entry.trace?.setSteps(answer.steps ?? []);
292
369
  if (answer.stopped && !(/** @type {any} */ (before)).stopped) {
293
370
  entry.view.stop();
294
- this._announce(this.msg('agentThread.stoppedAnnounce'));
371
+ this._announce(this.msg('agentThread.stoppedAnnounce'), true);
295
372
  } else if ('streaming' in partial && !answer.streaming && (/** @type {any} */ (before)).streaming) {
296
373
  entry.view.end();
297
374
  this._announce(this.msg('agentThread.answered', this._authorName(item)));
@@ -374,19 +451,24 @@ export class AgentThread extends Component {
374
451
  * @returns {this}
375
452
  */
376
453
  announce(text) {
377
- if (text) this._announce(String(text));
454
+ if (text) this._announce(String(text), true);
378
455
  return this;
379
456
  }
380
457
 
381
458
  /**
382
- * Removes an item.
459
+ * Removes an item. Focus inside it moves to the item above, or the one below when it was the
460
+ * first, so that a keyboard user is not thrown back to the top of the page.
383
461
  * @param {string} id
384
462
  * @returns {this}
385
463
  */
386
464
  remove(id) {
387
- this._drop(String(id));
465
+ const key = String(id);
466
+ const index = this._order.indexOf(key);
467
+ const held = this._entries.get(key)?.article.contains(document.activeElement);
468
+ this._drop(key);
388
469
  this._syncPositions();
389
470
  this._syncEmpty();
471
+ if (held) this._entries.get(this._order[Math.max(0, index - 1)])?.article.focus({ preventScroll: true });
390
472
  return this;
391
473
  }
392
474
 
@@ -398,8 +480,17 @@ export class AgentThread extends Component {
398
480
  get(id) {
399
481
  const entry = this._entries.get(String(id));
400
482
  if (!entry) return null;
401
- const item = structuredClone(entry.item);
402
- if (item.type === 'answer' && entry.view) /** @type {any} */ (item).blocks = entry.view.getBlocks();
483
+ const item = cloneItem(entry.item);
484
+ if (item.type === 'surface' && entry.surface) {
485
+ const surface = /** @type {any} */ (item);
486
+ const document = entry.surface.toDocument();
487
+ if (document) surface.document = document;
488
+ surface.reply = entry.surface.getReply();
489
+ }
490
+ if (item.type === 'answer' && entry.view) {
491
+ /** @type {any} */ (item).blocks = entry.view.getBlocks();
492
+ return this._intoVersion(item, { blocks: true });
493
+ }
403
494
  if (item.type === 'trace' && entry.trace) /** @type {any} */ (item).steps = entry.trace.getSteps();
404
495
  return item;
405
496
  }
@@ -417,12 +508,23 @@ export class AgentThread extends Component {
417
508
  */
418
509
  getComponent(id) {
419
510
  const entry = this._entries.get(String(id));
420
- return entry ? entry.view ?? entry.trace ?? entry.card ?? null : null;
511
+ return entry ? entry.view ?? entry.trace ?? entry.card ?? entry.surface ?? null : null;
512
+ }
513
+
514
+ /**
515
+ * The Surface drawn for a `surface` item, to stream its operations into with `apply()` or
516
+ * `write()`.
517
+ * @param {string} id
518
+ * @returns {Surface|null}
519
+ */
520
+ surface(id) {
521
+ return this._entries.get(String(id))?.surface ?? null;
421
522
  }
422
523
 
423
524
  /**
424
525
  * Brings something into view and moves focus to it: `item:<id>` an item, `step:<id>` a trace
425
- * step (in whichever trace holds it), `source:<n>` a source of the latest answer that has one.
526
+ * step (in whichever trace holds it), `source:<n>` a source of the latest answer that has one,
527
+ * `source:<n>:<id>` a source in the list of the answer `id`.
426
528
  * @param {string} target
427
529
  * @returns {boolean} Whether the target was found.
428
530
  */
@@ -447,10 +549,11 @@ export class AgentThread extends Component {
447
549
  }
448
550
  }
449
551
  } else if (kind === 'source') {
450
- for (const entryId of [...this._order].reverse()) {
552
+ const [n, ...answer] = rest;
553
+ for (const entryId of answer.length ? [answer.join(':')] : [...this._order].reverse()) {
451
554
  const sources = this._entries.get(entryId)?.sources;
452
555
  if (sources) {
453
- sources.highlight(Number(id));
556
+ sources.highlight(Number(n));
454
557
  found = true;
455
558
  break;
456
559
  }
@@ -491,6 +594,9 @@ export class AgentThread extends Component {
491
594
  if (this._destroyed) return;
492
595
  this._destroyed = true;
493
596
  clearTimeout(this._announceTimer);
597
+ this._scrollTarget?.removeEventListener('scroll', this._onScroll);
598
+ this._scrollTarget = null;
599
+ this._scrollHost = null;
494
600
  for (const id of [...this._order]) this._drop(id);
495
601
  super.destroy();
496
602
  if (this._original) restoreTarget(this.el, this._original);
@@ -501,20 +607,26 @@ export class AgentThread extends Component {
501
607
  /**
502
608
  * @private
503
609
  * @param {ThreadItem} item
504
- * @param {{announce?: boolean}} [options]
610
+ * @param {{announce?: boolean, after?: string|null}} [options]
505
611
  * @returns {void}
506
612
  */
507
613
  _add(item, options = {}) {
508
- if (!item || typeof item !== 'object' || item.id == null) return;
614
+ if (this._destroyed || !item || typeof item !== 'object' || item.id == null) return;
509
615
  const id = String(item.id);
510
616
  if (this._entries.has(id)) {
511
617
  this._replace(id, item);
512
618
  return;
513
619
  }
514
- const entry = this._build(structuredClone(item));
620
+ const entry = this._build(cloneItem(item));
515
621
  this._entries.set(id, entry);
516
- this._order.push(id);
517
- this._feed.append(entry.article);
622
+ const anchor = options.after != null && options.after !== id ? this._entries.get(options.after) : null;
623
+ if (anchor) {
624
+ this._order.splice(this._order.indexOf(String(options.after)) + 1, 0, id);
625
+ anchor.article.after(entry.article);
626
+ } else {
627
+ this._order.push(id);
628
+ this._feed.append(entry.article);
629
+ }
518
630
  this._syncContinuation(id);
519
631
  this._syncLatest();
520
632
  if (options.announce) this._announceItem(entry.item);
@@ -529,15 +641,57 @@ export class AgentThread extends Component {
529
641
  _replace(id, item) {
530
642
  const old = this._entries.get(id);
531
643
  if (!old) return;
532
- const hadFocus = old.article.contains(document.activeElement);
533
- const entry = this._build(structuredClone({ ...item, id }));
644
+ const focused = /** @type {HTMLElement|null} */ (document.activeElement);
645
+ const hadFocus = old.article.contains(focused);
646
+ // A surface keeps answering where it stands unless the item brings a different surface, which
647
+ // supersedes it: it replies once either way.
648
+ const keep = item.type === 'surface' && old.surface && keepsSurface(old, /** @type {any} */ (item)) ? old.surface : null;
649
+ // An item bringing a reply the surface never gave says it was answered elsewhere: the one reply
650
+ // is out already, and what is drawn now is its receipt.
651
+ const reply = /** @type {any} */ (item).reply;
652
+ const answered = !keep && item.type === 'surface' && reply && old.surface && !old.surface.getReply() ? old.surface : null;
653
+ /** @type {ThreadItem} */
654
+ let next = this._keepStreamed(old, item);
655
+ if (keep) {
656
+ old.owned = old.owned.filter((component) => component !== keep);
657
+ old.surface = null;
658
+ } else if (answered) {
659
+ this._answeredElsewhere.add(answered);
660
+ next = /** @type {ThreadItem} */ ({ ...next, document: /** @type {any} */ (item).document ?? answered.toDocument() });
661
+ } else {
662
+ old.surface?.supersede();
663
+ }
664
+ const entry = this._build(cloneItem({ ...next, id }), keep);
534
665
  old.article.replaceWith(entry.article);
535
666
  for (const component of old.owned) component.destroy();
536
667
  this._entries.set(id, entry);
537
668
  this._syncContinuation(id);
538
669
  this._syncPositions();
539
670
  this._syncLatest();
540
- if (hadFocus) entry.article.focus({ preventScroll: true });
671
+ // A surface carried over took its field with it, and whoever was typing there stays there.
672
+ if (hadFocus) (keep?.toElement().contains(focused) ? /** @type {HTMLElement} */ (focused) : entry.article).focus({ preventScroll: true });
673
+ }
674
+
675
+ /**
676
+ * Puts the feed in the order given, moving only what stands elsewhere. Anything a listener added
677
+ * meanwhile stays, after what was asked for.
678
+ * @private
679
+ * @param {string[]} ids
680
+ * @returns {void}
681
+ */
682
+ _arrange(ids) {
683
+ const focused = /** @type {HTMLElement|null} */ (document.activeElement);
684
+ const listed = new Set(ids);
685
+ this._order = [...[...listed].filter((id) => this._entries.has(id)), ...this._order.filter((id) => !listed.has(id))];
686
+ let next = this._feed.firstElementChild;
687
+ for (const id of this._order) {
688
+ const { article } = /** @type {ThreadEntry} */ (this._entries.get(id));
689
+ if (article === next) next = next.nextElementSibling;
690
+ else this._feed.insertBefore(article, next);
691
+ }
692
+ if (focused !== document.activeElement && this._feed.contains(focused)) focused?.focus({ preventScroll: true });
693
+ for (const id of this._order) this._syncContinuation(id);
694
+ this._syncLatest();
541
695
  }
542
696
 
543
697
  /** @private @param {string} id @returns {void} */
@@ -547,7 +701,10 @@ export class AgentThread extends Component {
547
701
  for (const component of entry.owned) component.destroy();
548
702
  entry.article.remove();
549
703
  this._entries.delete(id);
704
+ const index = this._order.indexOf(id);
550
705
  this._order = this._order.filter((other) => other !== id);
706
+ // The item after it may now start a turn, and needs its byline back.
707
+ if (this._order[index] !== undefined) this._syncContinuation(this._order[index]);
551
708
  this._syncLatest();
552
709
  }
553
710
 
@@ -594,11 +751,12 @@ export class AgentThread extends Component {
594
751
  * Draws one item into its article.
595
752
  * @private
596
753
  * @param {ThreadItem} item
754
+ * @param {Surface|null} [surface=null] A surface to keep rather than draw anew.
597
755
  * @returns {ThreadEntry}
598
756
  */
599
- _build(item) {
757
+ _build(item, surface = null) {
600
758
  /** @type {ThreadEntry} */
601
- const entry = { item, article: h('article'), owned: [], view: null, trace: null, sources: null, card: null };
759
+ const entry = { item, article: h('article'), owned: [], view: null, trace: null, sources: null, card: null, surface: null };
602
760
  const own = /** @type {<T extends Component>(component: T) => T} */ ((component) => {
603
761
  entry.owned.push(component);
604
762
  return component;
@@ -621,7 +779,8 @@ export class AgentThread extends Component {
621
779
 
622
780
  const body = h('div', { class: 'zx-agent-thread__body' });
623
781
  article.append(body);
624
- switch (item.type) {
782
+ // An application's own renderer for `surface` goes the way of every registered type.
783
+ switch (item.type === 'surface' && AgentThread.#renderers.has('surface') ? '' : item.type) {
625
784
  case 'user': {
626
785
  const user = /** @type {Extract<ThreadItem, {type: 'user'}>} */ (item);
627
786
  body.append(h('div', { class: 'zx-agent-thread__bubble' },
@@ -663,6 +822,15 @@ export class AgentThread extends Component {
663
822
  case 'approval':
664
823
  this._buildApproval(entry, body, own);
665
824
  break;
825
+ case 'zx-placeholder': {
826
+ const lines = Number(/** @type {any} */ (item).lines);
827
+ body.setAttribute('aria-busy', 'true');
828
+ body.append(skeletonText({ lines: Number.isInteger(lines) && lines > 0 && lines <= 12 ? lines : 2 }));
829
+ break;
830
+ }
831
+ case 'surface':
832
+ this._buildSurface(entry, body, own, surface);
833
+ break;
666
834
  default: {
667
835
  const render = AgentThread.#renderers.get(item.type);
668
836
  const content = render ? render(item, { thread: this, author: this._author(item), own }) : null;
@@ -930,6 +1098,50 @@ export class AgentThread extends Component {
930
1098
  body.append(card.toElement());
931
1099
  }
932
1100
 
1101
+ /**
1102
+ * A surface item: the Surface, its reply re-emitted as the thread's `reply` and kept on the item.
1103
+ * @private
1104
+ * @param {ThreadEntry} entry
1105
+ * @param {HTMLElement} body
1106
+ * @param {<T extends Component>(component: T) => T} own
1107
+ * @param {Surface|null} kept A surface carried over from the item's earlier drawing.
1108
+ * @returns {void}
1109
+ */
1110
+ _buildSurface(entry, body, own, kept) {
1111
+ const item = /** @type {SurfaceItem} */ (/** @type {unknown} */ (entry.item));
1112
+ const surface = kept ?? new Surface(null, {
1113
+ authors: /** @type {any} */ (this.options.authors),
1114
+ headingLevel: this.options.headingLevel,
1115
+ locale: this.options.locale,
1116
+ ...(this.options.surfaceOptions ?? {}),
1117
+ document: item.document ?? null,
1118
+ token: item.token ?? null,
1119
+ reply: item.reply ?? null,
1120
+ ...(item.catalog ? { catalog: item.catalog } : {})
1121
+ });
1122
+ own(surface);
1123
+ if (!kept) {
1124
+ this._contain(surface, ['reply', 'error', 'change', 'ready', 'end']);
1125
+ // A streamed surface says what it is only once it begins.
1126
+ if (!item.document) {
1127
+ surface.on('ready', () => {
1128
+ if (!surface.getReply() && asksForAnswer(surface.toDocument()?.intent)) {
1129
+ this._announce(this.msg('agentThread.needsAnswer', this._authorName(item)), true);
1130
+ }
1131
+ });
1132
+ }
1133
+ surface.on('reply', (event) => {
1134
+ if (this._answeredElsewhere.has(surface)) return;
1135
+ const { reply } = /** @type {CustomEvent<{reply: SurfaceReply}>} */ (event).detail;
1136
+ const current = this._entries.get(String(item.id));
1137
+ if (current?.surface === surface) current.item = /** @type {ThreadItem} */ ({ ...current.item, reply });
1138
+ this.emit('reply', { item: this.get(String(item.id)) ?? { ...item, reply }, reply });
1139
+ });
1140
+ }
1141
+ entry.surface = surface;
1142
+ body.append(surface.toElement());
1143
+ }
1144
+
933
1145
  /**
934
1146
  * The author's avatar, beside the byline and the content. Decorative: the byline names them.
935
1147
  * @private
@@ -1016,7 +1228,7 @@ export class AgentThread extends Component {
1016
1228
  if (typeof this.options.formatTime === 'function') return String(this.options.formatTime(at) ?? '');
1017
1229
  const date = new Date(at);
1018
1230
  if (Number.isNaN(date.getTime())) return '';
1019
- return new Intl.DateTimeFormat(this.options.locale, { hour: '2-digit', minute: '2-digit' }).format(date);
1231
+ return new Intl.DateTimeFormat(dateLocale(this.options.locale), { hour: '2-digit', minute: '2-digit' }).format(date);
1020
1232
  }
1021
1233
 
1022
1234
  /** @private @param {Extract<ThreadItem, {type: 'answer'}>} answer @returns {number} */
@@ -1026,6 +1238,40 @@ export class AgentThread extends Component {
1026
1238
  return Math.max(0, Math.min(versions.length - 1, index));
1027
1239
  }
1028
1240
 
1241
+ /**
1242
+ * An answer with versions shows its chosen version, so what changes in it belongs there too: the
1243
+ * item's own fields are only what it would show without them.
1244
+ * @private
1245
+ * @template {ThreadItem} T
1246
+ * @param {T} item
1247
+ * @param {Record<string, unknown>} partial What changed.
1248
+ * @returns {T}
1249
+ */
1250
+ _intoVersion(item, partial) {
1251
+ const answer = /** @type {any} */ (item);
1252
+ const versions = Array.isArray(answer.versions) ? answer.versions : [];
1253
+ const changed = ['blocks', 'sources', 'steps'].filter((key) => key in partial);
1254
+ if (item.type !== 'answer' || versions.length < 2 || !changed.length || 'versions' in partial) return item;
1255
+ const index = this._versionIndex(answer);
1256
+ const version = { ...versions[index], ...Object.fromEntries(changed.map((key) => [key, answer[key]])) };
1257
+ return { ...item, versions: versions.map((other, at) => (at === index ? version : other)) };
1258
+ }
1259
+
1260
+ /**
1261
+ * Streamed text lives in the view, so an answer drawn anew from the same versions takes it along
1262
+ * into the version it was streamed into.
1263
+ * @private
1264
+ * @param {ThreadEntry} old
1265
+ * @param {ThreadItem} item
1266
+ * @returns {ThreadItem}
1267
+ */
1268
+ _keepStreamed(old, item) {
1269
+ const versions = /** @type {any} */ (item).versions;
1270
+ if (!old.view || versions === undefined || versions !== /** @type {any} */ (old.item).versions) return item;
1271
+ const shown = this._intoVersion(/** @type {ThreadItem} */ ({ ...old.item, blocks: old.view.getBlocks() }), { blocks: true });
1272
+ return /** @type {ThreadItem} */ ({ ...item, versions: /** @type {any} */ (shown).versions });
1273
+ }
1274
+
1029
1275
  /**
1030
1276
  * The blocks, sources, and steps an answer shows: its chosen version's when it has several.
1031
1277
  * @private
@@ -1101,7 +1347,9 @@ export class AgentThread extends Component {
1101
1347
  if (item.type === 'answer') {
1102
1348
  this._announce(this.msg(/** @type {any} */ (item).streaming ? 'agentThread.writing' : 'agentThread.answered', name));
1103
1349
  } else if (item.type === 'approval' && (/** @type {any} */ (item).status ?? 'pending') === 'pending') {
1104
- this._announce(this.msg('agentThread.needsApproval', name));
1350
+ this._announce(this.msg('agentThread.needsApproval', name), true);
1351
+ } else if (item.type === 'surface' && !AgentThread.#renderers.has('surface') && asksForAnswer(/** @type {any} */ (item).document?.intent) && !(/** @type {any} */ (item).reply)) {
1352
+ this._announce(this.msg('agentThread.needsAnswer', name), true);
1105
1353
  } else if (item.type === 'trace') {
1106
1354
  this._announce(this.msg('agentThread.working', name));
1107
1355
  } else if (item.type === 'notice' && ['warning', 'danger'].includes(String(/** @type {any} */ (item).tone))) {
@@ -1111,36 +1359,42 @@ export class AgentThread extends Component {
1111
1359
 
1112
1360
  /**
1113
1361
  * Says a milestone once. The region is cleared first so the same words said twice are heard
1114
- * twice.
1362
+ * twice. Words still waiting to be said give way only to words that must be heard: what asks
1363
+ * something of the person is not overtaken by what has just finished.
1115
1364
  * @private
1116
1365
  * @param {string} text
1366
+ * @param {boolean} [urgent=false] Whether it must be heard.
1117
1367
  * @returns {void}
1118
1368
  */
1119
- _announce(text) {
1369
+ _announce(text, urgent = false) {
1370
+ if (this._askingPerson && !urgent) return;
1120
1371
  clearTimeout(this._announceTimer);
1372
+ this._askingPerson = urgent;
1121
1373
  this._status.textContent = '';
1122
1374
  this._announceTimer = window.setTimeout(() => {
1375
+ this._askingPerson = false;
1123
1376
  this._status.textContent = text;
1124
1377
  }, 60);
1125
1378
  }
1126
1379
 
1127
1380
  /** @private @returns {Element|null} */
1128
1381
  _scroller() {
1129
- if (this.options.scroller) return this.options.scroller;
1130
- if (this._scrollHost?.isConnected) return this._scrollHost;
1131
1382
  /** @type {Element|null} */
1132
- let node = this.el;
1133
- while (node && node !== document.documentElement) {
1134
- const overflow = getComputedStyle(node).overflowY;
1135
- if (overflow === 'auto' || overflow === 'scroll') break;
1136
- node = node.parentElement;
1383
+ let node = this.options.scroller ?? this.el;
1384
+ if (!this.options.scroller) {
1385
+ while (node && node !== document.documentElement) {
1386
+ const overflow = getComputedStyle(node).overflowY;
1387
+ if (overflow === 'auto' || overflow === 'scroll') break;
1388
+ node = node.parentElement;
1389
+ }
1390
+ node = node ?? document.scrollingElement;
1137
1391
  }
1138
- this._scrollHost = node ?? document.scrollingElement;
1139
- if (this._scrollHost) {
1140
- const host = this._scrollHost === document.documentElement ? window : this._scrollHost;
1141
- this.listen(host, 'scroll', () => {
1142
- if (this._atEnd()) this._latestButton.hidden = true;
1143
- }, { passive: true });
1392
+ const target = node === document.documentElement ? window : node;
1393
+ if (target !== this._scrollTarget) {
1394
+ this._scrollTarget?.removeEventListener('scroll', this._onScroll);
1395
+ this._scrollHost = node;
1396
+ this._scrollTarget = target;
1397
+ if (target) this.listen(target, 'scroll', this._onScroll, { passive: true });
1144
1398
  }
1145
1399
  return this._scrollHost;
1146
1400
  }
@@ -1229,12 +1483,14 @@ export class AgentThread extends Component {
1229
1483
 
1230
1484
  /**
1231
1485
  * APG feed keys: PageDown and PageUp move between articles; Ctrl+End and Ctrl+Home move focus
1232
- * past the end or before the start of the feed.
1486
+ * past the end or before the start of the feed. A control inside an item keeps them.
1233
1487
  * @private
1234
1488
  * @param {KeyboardEvent} event
1235
1489
  * @returns {void}
1236
1490
  */
1237
1491
  _onFeedKey(event) {
1492
+ // A key a control inside an item handled, or one that moves its caret, is the control's.
1493
+ if (event.defaultPrevented || isEditableTarget(/** @type {Element|null} */ (event.target))) return;
1238
1494
  const article = event.target instanceof Element ? event.target.closest('.zx-agent-thread__item') : null;
1239
1495
  if (!(article instanceof HTMLElement)) return;
1240
1496
  const articles = this._order.map((id) => this._entries.get(id)?.article).filter(Boolean);
@@ -1256,7 +1512,49 @@ export class AgentThread extends Component {
1256
1512
  }
1257
1513
 
1258
1514
  /** Item types the thread draws itself. */
1259
- const BUILT_IN = new Set(['user', 'text', 'answer', 'trace', 'approval', 'notice']);
1515
+ const BUILT_IN = new Set(['user', 'text', 'answer', 'trace', 'approval', 'notice', 'zx-placeholder']);
1516
+
1517
+ /**
1518
+ * Whether a surface of this intent waits for the person's answer.
1519
+ * @param {unknown} intent
1520
+ * @returns {boolean}
1521
+ */
1522
+ function asksForAnswer(intent) {
1523
+ return typeof intent === 'string' && intent !== 'show';
1524
+ }
1525
+
1526
+ /**
1527
+ * Copies an item. Only a surface keeps its `catalog` by reference: a catalog is the library's own
1528
+ * frozen object, and a copy of it is refused.
1529
+ * @template {Record<string, any>} T
1530
+ * @param {T} item
1531
+ * @returns {T}
1532
+ */
1533
+ function cloneItem(item) {
1534
+ if (item?.type !== 'surface' || !('catalog' in item)) return structuredClone(item);
1535
+ const { catalog, ...rest } = item;
1536
+ return /** @type {T} */ (/** @type {unknown} */ ({ ...structuredClone(rest), catalog }));
1537
+ }
1538
+
1539
+ /**
1540
+ * Whether a redrawn surface item still describes the surface already drawn: same token and
1541
+ * catalog, no other document, and no reply the surface has not given itself.
1542
+ * @param {ThreadEntry} old
1543
+ * @param {SurfaceItem} item
1544
+ * @returns {boolean}
1545
+ */
1546
+ function keepsSurface(old, item) {
1547
+ const before = /** @type {SurfaceItem} */ (/** @type {unknown} */ (old.item));
1548
+ if (item.reply && !old.surface?.getReply()) return false;
1549
+ if ((item.token ?? null) !== (before.token ?? null) || (item.catalog ?? null) !== (before.catalog ?? null)) return false;
1550
+ if (item.document == null) return true;
1551
+ // The document the item was drawn from, or the one the surface now stands as — what `get()`
1552
+ // hands back — both describe the surface already drawn.
1553
+ const given = JSON.stringify(item.document);
1554
+ if (given === JSON.stringify(before.document ?? null)) return true;
1555
+ const drawn = old.surface?.toDocument();
1556
+ return Boolean(drawn) && given === JSON.stringify(drawn);
1557
+ }
1260
1558
 
1261
1559
  /**
1262
1560
  * An icon button the thread's delegated click listener acts on.
@@ -1363,3 +1661,10 @@ function focusableOutside(element, direction) {
1363
1661
  * @event AgentThread#open
1364
1662
  * @type {CustomEvent<{item: ThreadItem, ref: import('../../internal/agent-model.js').ItemRef, step?: import('../../internal/agent-model.js').TraceStep}>}
1365
1663
  */
1664
+ /**
1665
+ * A surface in the thread replied: its one reply, with the item as it now stands. Also sent when
1666
+ * an unanswered surface is superseded by a new one under the same id, removed, or destroyed with
1667
+ * the thread.
1668
+ * @event AgentThread#reply
1669
+ * @type {CustomEvent<{item: ThreadItem, reply: SurfaceReply}>}
1670
+ */