@zeyos/zx 5.5.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 (235) hide show
  1. package/CHANGELOG.md +210 -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 +711 -0
  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/approval-card/approval-card.d.ts +596 -0
  11. package/dist/types/components/avatar/avatar.d.ts +91 -4
  12. package/dist/types/components/block-view/block-view.d.ts +205 -0
  13. package/dist/types/components/breadcrumb/breadcrumb.d.ts +3 -3
  14. package/dist/types/components/calendar/calendar-model.d.ts +9 -2
  15. package/dist/types/components/calendar/calendar.d.ts +12 -4
  16. package/dist/types/components/chart/chart.d.ts +25 -13
  17. package/dist/types/components/code-editor/code-editor.d.ts +7 -2
  18. package/dist/types/components/composer/composer.d.ts +938 -0
  19. package/dist/types/components/composer/queue.d.ts +76 -0
  20. package/dist/types/components/copy/copy-button.d.ts +6 -4
  21. package/dist/types/components/copy/copy-input.d.ts +10 -6
  22. package/dist/types/components/datebox/date-range-box.d.ts +33 -0
  23. package/dist/types/components/datebox/placeholder.d.ts +7 -0
  24. package/dist/types/components/dock/dock.d.ts +12 -3
  25. package/dist/types/components/entity-ref/entity-ref.d.ts +5 -3
  26. package/dist/types/components/field-upload/field-upload.d.ts +3 -2
  27. package/dist/types/components/file-item/file-item.d.ts +3 -2
  28. package/dist/types/components/file-list/file-list.d.ts +14 -8
  29. package/dist/types/components/filter/filter-model.d.ts +31 -1
  30. package/dist/types/components/filter/filter.d.ts +20 -2
  31. package/dist/types/components/finder/finder.d.ts +14 -6
  32. package/dist/types/components/flag/flag.d.ts +99 -0
  33. package/dist/types/components/grid/grid.d.ts +1 -1
  34. package/dist/types/components/kanban-view/kanban-view.d.ts +8 -66
  35. package/dist/types/components/launcher/launcher.d.ts +2 -0
  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 +17 -6
  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/run-status/run-status.d.ts +393 -0
  45. package/dist/types/components/run-trace/run-trace.d.ts +624 -0
  46. package/dist/types/components/select/country.d.ts +106 -0
  47. package/dist/types/components/select/field-adapter.d.ts +2 -1
  48. package/dist/types/components/select/locale.d.ts +102 -0
  49. package/dist/types/components/select/select.d.ts +41 -2
  50. package/dist/types/components/slider/slider.d.ts +1 -0
  51. package/dist/types/components/sort-control/sort-control.d.ts +7 -3
  52. package/dist/types/components/source-list/source-list.d.ts +179 -0
  53. package/dist/types/components/split-view/split-view.d.ts +5 -3
  54. package/dist/types/components/surface/catalog.d.ts +260 -0
  55. package/dist/types/components/surface/elicit.d.ts +81 -0
  56. package/dist/types/components/surface/mcp.d.ts +165 -0
  57. package/dist/types/components/surface/schema.d.ts +314 -0
  58. package/dist/types/components/surface/stream.d.ts +118 -0
  59. package/dist/types/components/surface/surface.d.ts +718 -0
  60. package/dist/types/components/surface/text.d.ts +277 -0
  61. package/dist/types/components/surface/validate.d.ts +339 -0
  62. package/dist/types/components/table/table.d.ts +55 -3
  63. package/dist/types/components/table/window.d.ts +203 -0
  64. package/dist/types/components/toolbar/toolbar.d.ts +10 -6
  65. package/dist/types/components/tooltip/tooltip.d.ts +2 -2
  66. package/dist/types/components/tree/tree.d.ts +20 -13
  67. package/dist/types/core/component.d.ts +10 -0
  68. package/dist/types/core/date.d.ts +8 -1
  69. package/dist/types/core/dom.d.ts +1 -0
  70. package/dist/types/core/http.d.ts +10 -0
  71. package/dist/types/core/i18n.d.ts +38 -0
  72. package/dist/types/core/messages.d.ts +479 -1
  73. package/dist/types/core/storage.d.ts +7 -2
  74. package/dist/types/elements/define.d.ts +21 -46
  75. package/dist/types/elements/definitions.d.ts +147 -0
  76. package/dist/types/elements/kit.d.ts +7 -0
  77. package/dist/types/elements/reflect.d.ts +6 -3
  78. package/dist/types/index.d.ts +18 -1
  79. package/dist/types/internal/agent-model.d.ts +587 -0
  80. package/dist/types/internal/date-locale.d.ts +7 -0
  81. package/dist/types/internal/highlight.d.ts +24 -0
  82. package/dist/types/internal/json-patch.d.ts +146 -0
  83. package/dist/types/internal/presence-loop.d.ts +148 -0
  84. package/dist/types/locales/de.d.ts +13 -0
  85. package/dist/types/locales/en.d.ts +2 -0
  86. package/dist/types/locales/index.d.ts +823 -0
  87. package/dist/types/zeyos/view.d.ts +8 -1
  88. package/dist/zx-zeyos.esm.js +20505 -18748
  89. package/dist/zx-zeyos.esm.min.js +5 -5
  90. package/dist/zx.core.css +1276 -0
  91. package/dist/zx.core.min.css +1 -0
  92. package/dist/zx.css +2424 -134
  93. package/dist/zx.esm.js +46167 -28468
  94. package/dist/zx.esm.min.js +40 -8
  95. package/dist/zx.global.js +46167 -28468
  96. package/dist/zx.global.min.js +40 -8
  97. package/dist/zx.layered.css +17302 -0
  98. package/dist/zx.layered.min.css +1 -0
  99. package/dist/zx.min.css +1 -1
  100. package/docs/agent-catalog.json +12501 -0
  101. package/docs/agent-surfaces.md +340 -0
  102. package/docs/api.json +2057 -166
  103. package/docs/llms.md +1458 -58
  104. package/docs/llms.txt +38 -8
  105. package/package.json +29 -6
  106. package/src/components/account-menu/account-menu.js +6 -3
  107. package/src/components/activity-item/activity-item.js +2 -1
  108. package/src/components/activity-list/activity-list.js +16 -10
  109. package/src/components/agent-thread/ag-ui.js +1439 -0
  110. package/src/components/agent-thread/agent-thread.css +417 -0
  111. package/src/components/agent-thread/agent-thread.js +1670 -0
  112. package/src/components/agent-thread/ui-message-stream.js +1281 -0
  113. package/src/components/app-sidebar/app-sidebar.js +18 -8
  114. package/src/components/approval-card/approval-card.css +289 -0
  115. package/src/components/approval-card/approval-card.js +1378 -0
  116. package/src/components/avatar/avatar.css +56 -1
  117. package/src/components/avatar/avatar.js +148 -26
  118. package/src/components/block-view/block-view.css +300 -0
  119. package/src/components/block-view/block-view.js +524 -0
  120. package/src/components/breadcrumb/breadcrumb.js +8 -5
  121. package/src/components/calendar/calendar-model.js +8 -2
  122. package/src/components/calendar/calendar.js +53 -18
  123. package/src/components/chart/chart.js +54 -23
  124. package/src/components/code-editor/code-editor.js +45 -8
  125. package/src/components/code-editor/field-adapter.js +1 -1
  126. package/src/components/composer/composer.css +482 -0
  127. package/src/components/composer/composer.js +1815 -0
  128. package/src/components/composer/queue.js +78 -0
  129. package/src/components/context-menu/context-menu.js +12 -1
  130. package/src/components/copy/copy-button.js +9 -7
  131. package/src/components/copy/copy-input.js +10 -6
  132. package/src/components/date-picker/date-picker.js +2 -1
  133. package/src/components/date-picker/date-range-picker.js +8 -7
  134. package/src/components/datebox/date-range-box.js +3 -9
  135. package/src/components/datebox/datebox.js +18 -21
  136. package/src/components/datebox/placeholder.js +18 -0
  137. package/src/components/dialog/dialog.js +1 -1
  138. package/src/components/dock/dock.js +34 -13
  139. package/src/components/entity-ref/entity-ref.js +16 -5
  140. package/src/components/field-upload/field-upload.js +81 -38
  141. package/src/components/file-item/file-item.js +70 -40
  142. package/src/components/file-list/file-list.js +15 -9
  143. package/src/components/filter/filter-model.js +46 -8
  144. package/src/components/filter/filter.css +3 -3
  145. package/src/components/filter/filter.js +29 -10
  146. package/src/components/filter-panel/filter-panel.js +13 -5
  147. package/src/components/finder/finder.js +50 -26
  148. package/src/components/flag/flag.css +40 -0
  149. package/src/components/flag/flag.js +177 -0
  150. package/src/components/form/form.js +1 -1
  151. package/src/components/grid/grid.js +22 -8
  152. package/src/components/kanban-view/kanban-view.js +51 -81
  153. package/src/components/launcher/launcher.js +17 -2
  154. package/src/components/list-toolbar/list-toolbar.js +2 -1
  155. package/src/components/master-panel/master-panel.js +1 -1
  156. package/src/components/menu-button/menu-button.js +4 -0
  157. package/src/components/message/message.js +3 -0
  158. package/src/components/multi-value-editor/multi-value-editor.js +10 -9
  159. package/src/components/navigation-bar/navigation-bar.js +3 -3
  160. package/src/components/number-field/number-field.js +29 -13
  161. package/src/components/prompt-starters/prompt-starters.css +91 -0
  162. package/src/components/prompt-starters/prompt-starters.js +206 -0
  163. package/src/components/prose/prose.js +14 -10
  164. package/src/components/questionnaire/conditions.js +666 -0
  165. package/src/components/questionnaire/items.js +150 -41
  166. package/src/components/questionnaire/questionnaire.js +126 -32
  167. package/src/components/rating/rating.js +5 -4
  168. package/src/components/run-status/run-status.css +208 -0
  169. package/src/components/run-status/run-status.js +782 -0
  170. package/src/components/run-trace/run-trace.css +443 -0
  171. package/src/components/run-trace/run-trace.js +1209 -0
  172. package/src/components/select/country.js +136 -0
  173. package/src/components/select/field-adapter.js +7 -2
  174. package/src/components/select/locale.js +219 -0
  175. package/src/components/select/select.css +20 -22
  176. package/src/components/select/select.js +94 -12
  177. package/src/components/sheet/sheet-stack.js +10 -1
  178. package/src/components/slider/slider.js +7 -2
  179. package/src/components/sort-control/sort-control.js +15 -5
  180. package/src/components/source-list/source-list.css +208 -0
  181. package/src/components/source-list/source-list.js +358 -0
  182. package/src/components/split-view/split-view.js +5 -3
  183. package/src/components/surface/catalog.js +1334 -0
  184. package/src/components/surface/elicit.js +107 -0
  185. package/src/components/surface/mcp.js +243 -0
  186. package/src/components/surface/schema.js +644 -0
  187. package/src/components/surface/stream.js +245 -0
  188. package/src/components/surface/surface.css +308 -0
  189. package/src/components/surface/surface.js +2291 -0
  190. package/src/components/surface/text.js +513 -0
  191. package/src/components/surface/validate.js +2218 -0
  192. package/src/components/tabbox/tabbox.js +9 -0
  193. package/src/components/table/table.css +63 -3
  194. package/src/components/table/table.js +167 -28
  195. package/src/components/table/window.js +317 -0
  196. package/src/components/toolbar/toolbar.js +12 -7
  197. package/src/components/tooltip/tooltip.css +2 -3
  198. package/src/components/tooltip/tooltip.js +32 -5
  199. package/src/components/tree/tree.js +53 -23
  200. package/src/core/component.js +25 -1
  201. package/src/core/date.js +62 -16
  202. package/src/core/dom.js +22 -2
  203. package/src/core/format.js +15 -13
  204. package/src/core/http.js +29 -20
  205. package/src/core/i18n.js +83 -10
  206. package/src/core/keyboard.js +79 -8
  207. package/src/core/messages.js +519 -2
  208. package/src/core/overlay-host.js +1 -0
  209. package/src/core/storage.js +59 -6
  210. package/src/elements/define.js +178 -130
  211. package/src/elements/definitions.js +229 -0
  212. package/src/elements/kit.js +444 -0
  213. package/src/elements/reflect.js +8 -3
  214. package/src/index.js +18 -1
  215. package/src/internal/agent-model.js +488 -0
  216. package/src/internal/date-locale.js +11 -0
  217. package/src/internal/highlight.js +104 -0
  218. package/src/internal/json-patch.js +405 -0
  219. package/src/internal/presence-loop.js +343 -0
  220. package/src/locales/de.js +911 -0
  221. package/src/locales/en.js +2 -0
  222. package/src/locales/index.js +7 -0
  223. package/src/zeyos/calendar.js +2 -1
  224. package/src/zeyos/form.js +2 -1
  225. package/src/zeyos/launcher.js +7 -6
  226. package/src/zeyos/module-bar.js +2 -1
  227. package/src/zeyos/schema.js +37 -23
  228. package/src/zeyos/select.js +4 -3
  229. package/src/zeyos/table.js +2 -13
  230. package/src/zeyos/view.js +57 -17
  231. package/styles/core.css +11 -0
  232. package/styles/tokens/semantic.css +1 -0
  233. package/styles/zeyos.css +2 -0
  234. package/styles/zx.css +11 -8
  235. package/styles/zx.layered.css +1 -0
@@ -0,0 +1,1670 @@
1
+ // @ts-check
2
+ import { Component } from '../../core/component.js';
3
+ import { h, restoreTarget, snapshotTarget } from '../../core/dom.js';
4
+ import { formatFileSize } from '../../core/format.js';
5
+ import { icon } from '../../core/icons.js';
6
+ import { isEditableTarget } from '../../core/keyboard.js';
7
+ import { escapeRegExp, uid } from '../../core/util.js';
8
+ import { AGENT_MESSAGES, initialsOf } from '../../internal/agent-model.js';
9
+ import { ApprovalCard } from '../approval-card/approval-card.js';
10
+ import { Avatar } from '../avatar/avatar.js';
11
+ import { BlockView } from '../block-view/block-view.js';
12
+ import { copyButton } from '../copy/copy-button.js';
13
+ import { emptyState } from '../empty-state/empty-state.js';
14
+ import { skeletonText } from '../skeleton/skeleton.js';
15
+ import { RunTrace } from '../run-trace/run-trace.js';
16
+ import { SourceList } from '../source-list/source-list.js';
17
+ import { Surface } from '../surface/surface.js';
18
+ import { dateLocale } from '../../internal/date-locale.js';
19
+
20
+ /** @typedef {import('../../internal/agent-model.js').ThreadItem} ThreadItem */
21
+ /** @typedef {import('../../internal/agent-model.js').Author} Author */
22
+ /** @typedef {import('../../internal/agent-model.js').Source} Source */
23
+ /** @typedef {import('../../internal/agent-model.js').Block} Block */
24
+ /** @typedef {import('../empty-state/empty-state.js').EmptyStateOptions} EmptyStateOptions */
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
+ */
63
+
64
+ /**
65
+ * What a registered item renderer receives besides the item.
66
+ * @typedef {Object} ThreadRenderContext
67
+ * @property {AgentThread} thread The thread drawing the item.
68
+ * @property {Author|null} author The item's author, resolved from `authors`.
69
+ * @property {<T extends Component>(component: T) => T} own Hands a component to the thread, which
70
+ * destroys it with the item.
71
+ */
72
+
73
+ /**
74
+ * Draws one item of a registered type. It returns the item's content; the thread wraps it in the
75
+ * article, byline included.
76
+ * @typedef {(item: ThreadItem, context: ThreadRenderContext) => Node|null} ThreadItemRenderer
77
+ */
78
+
79
+ /**
80
+ * @typedef {Object} AgentThreadOptions
81
+ * @property {ThreadItem[]} [items=[]] The conversation, oldest first.
82
+ * @property {Record<string, Author>} [authors={}] Who wrote the items and took the steps, by key.
83
+ * An item without an `author` is the person's own (`user`) or the first agent's (anything else).
84
+ * @property {string} [me='me'] Author key of the person reading; their items read as "You".
85
+ * @property {string|null} [label=null] Accessible name of the feed; "Conversation" when null.
86
+ * @property {2|3|4|5} [headingLevel=3] Heading level inside answers and cards.
87
+ * @property {EmptyStateOptions|null} [emptyState=null] Shown while there are no items.
88
+ * @property {boolean} [followOutput=true] Keep the end in view while new output arrives, as long
89
+ * as the reader is at the end; otherwise offer "Jump to latest" and leave them where they are.
90
+ * @property {Element|null} [scroller=null] The element that scrolls; the nearest scrolling
91
+ * ancestor (or the thread itself) when null.
92
+ * @property {AnswerAction[]} [answerActions=['copy','regenerate','branch']] Actions under each
93
+ * finished answer; `regenerate` only under the latest one.
94
+ * @property {Partial<Record<'regenerate'|'branch'|'rateUp'|'rateDown'|'edit', string>>} [icons] Glyph
95
+ * names for the answer and message actions.
96
+ * @property {Array<'edit'|'copy'>} [userActions=[]] Actions on the person's own messages, shown
97
+ * while the message is pointed at or holds focus (always on a touch screen): `edit` asks the
98
+ * application to put the message back in the composer, `copy` copies its text.
99
+ * @property {Record<string, string>} [traceIcons={}] Glyph names for trace step kinds, handed to
100
+ * every `RunTrace` the thread draws.
101
+ * @property {Record<string, string>} [sourceIcons={}] Glyph names for source kinds, handed to every
102
+ * `SourceList` the thread draws.
103
+ * @property {(() => Date)|null} [now=null] The clock "today" is measured against in cards and
104
+ * traces, for an application whose world runs on fixed dates; the real clock when null.
105
+ * @property {((at: string) => string)|null} [formatTime=null] Formats an item's `at`; the local
106
+ * clock time when null.
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.
111
+ * @property {Record<string, string>|Record<string, Record<string, string>>} [msg] Localized messages.
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.
114
+ * @property {(event: CustomEvent<{item: ThreadItem, values: Record<string, unknown>}>) => void} [onapprove] Approval listener.
115
+ * @property {(event: CustomEvent<{item: ThreadItem, values: Record<string, unknown>}>) => void} [onedit] Edit listener.
116
+ * @property {(event: CustomEvent<{item: ThreadItem, reason: string}>) => void} [onreject] Rejection listener.
117
+ * @property {(event: CustomEvent<{item: ThreadItem, n: number, source: Source|null}>) => void} [oncite] Citation listener.
118
+ * @property {(event: CustomEvent<{item: ThreadItem, id: string}>) => void} [onartifact] Artifact listener.
119
+ * @property {(event: CustomEvent<{target: string}>) => void} [onreveal] Reveal listener.
120
+ * @property {(event: CustomEvent<{item: ThreadItem, ref: import('../../internal/agent-model.js').ItemRef}>) => void} [onopen] Link listener.
121
+ */
122
+
123
+ /**
124
+ * @typedef {Object} ThreadEntry
125
+ * @property {ThreadItem} item The item as last given.
126
+ * @property {HTMLElement} article Its article.
127
+ * @property {Component[]} owned Components drawn for it.
128
+ * @property {BlockView|null} view An answer's text.
129
+ * @property {RunTrace|null} trace A trace's steps.
130
+ * @property {SourceList|null} sources An answer's sources.
131
+ * @property {ApprovalCard|null} card An approval.
132
+ * @property {Surface|null} [surface] A surface.
133
+ */
134
+
135
+ const MESSAGES = Object.freeze({
136
+ ...AGENT_MESSAGES,
137
+ 'agentThread.label': 'Conversation',
138
+ 'agentThread.you': 'You',
139
+ 'agentThread.agent': 'Agent',
140
+ 'agentThread.via': 'via %1',
141
+ 'agentThread.latest': 'Jump to latest',
142
+ 'agentThread.copy': 'Copy answer',
143
+ 'agentThread.regenerate': 'Regenerate answer',
144
+ 'agentThread.branch': 'Branch into a new conversation',
145
+ 'agentThread.rateUp': 'Helpful',
146
+ 'agentThread.rateDown': 'Not helpful',
147
+ 'agentThread.previousVersion': 'Previous version',
148
+ 'agentThread.nextVersion': 'Next version',
149
+ 'agentThread.version': 'Version %1 of %2',
150
+ 'agentThread.attachments': 'Attachments',
151
+ 'agentThread.sources': 'Sources',
152
+ 'agentThread.stopped': 'Stopped',
153
+ 'agentThread.writing': '%1 is writing an answer',
154
+ 'agentThread.answered': '%1 answered',
155
+ 'agentThread.working': '%1 is working',
156
+ 'agentThread.needsApproval': '%1 needs your approval',
157
+ 'agentThread.needsAnswer': '%1 needs your answer',
158
+ 'agentThread.stoppedAnnounce': 'Stopped',
159
+ 'agentThread.writingNow': '%1 is writing…',
160
+ 'agentThread.edit': 'Edit message',
161
+ 'agentThread.copyMessage': 'Copy message'
162
+ });
163
+
164
+ const DEFAULT_ICONS = Object.freeze({ regenerate: 'reload', branch: 'columns', rateUp: 'check', rateDown: 'x', edit: 'type' });
165
+
166
+ /** How close to the end, in pixels, still counts as reading the end. */
167
+ const END_SLACK = 48;
168
+
169
+ /**
170
+ * A conversation with one or more agents: the person's messages, the agents' answers as they
171
+ * stream, the steps a run took, the approvals that hold it, and one-line notices — drawn from the
172
+ * plain-JSON items of the agent model. The thread owns no transport and no state beyond what it
173
+ * is given: the application feeds it (`upsert`, `patch`, `appendText`) and acts on what it emits.
174
+ *
175
+ * It follows the APG feed pattern: each item is an article in a `role="feed"`, PageDown and
176
+ * PageUp move between articles, and Ctrl+End / Ctrl+Home leave the feed. Streamed text is never
177
+ * read aloud as it arrives; one polite status says when an agent starts, answers, needs
178
+ * approval, or is stopped.
179
+ *
180
+ * @fires AgentThread#action
181
+ * @fires AgentThread#approve
182
+ * @fires AgentThread#edit
183
+ * @fires AgentThread#reject
184
+ * @fires AgentThread#cite
185
+ * @fires AgentThread#artifact
186
+ * @fires AgentThread#reveal
187
+ * @fires AgentThread#open
188
+ * @fires AgentThread#reply
189
+ * @extends {Component<AgentThreadOptions>}
190
+ */
191
+ export class AgentThread extends Component {
192
+ static cssName = 'agent-thread';
193
+
194
+ /** @type {Readonly<AgentThreadOptions>} */
195
+ static defaults = {
196
+ items: [],
197
+ authors: {},
198
+ me: 'me',
199
+ label: null,
200
+ headingLevel: 3,
201
+ emptyState: null,
202
+ followOutput: true,
203
+ scroller: null,
204
+ answerActions: ['copy', 'regenerate', 'branch'],
205
+ userActions: [],
206
+ icons: {},
207
+ traceIcons: {},
208
+ sourceIcons: {},
209
+ now: null,
210
+ formatTime: null,
211
+ surfaceOptions: {},
212
+ msg: MESSAGES
213
+ };
214
+
215
+ /** @type {Map<string, ThreadItemRenderer>} */
216
+ static #renderers = new Map();
217
+
218
+ /**
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.
222
+ * @param {string} type Item type.
223
+ * @param {ThreadItemRenderer} render Draws the item's content.
224
+ * @returns {typeof AgentThread}
225
+ */
226
+ static register(type, render) {
227
+ const name = String(type ?? '').trim();
228
+ if (!name) throw new TypeError('Thread item type must not be empty');
229
+ if (BUILT_IN.has(name)) throw new TypeError(`Thread item type "${name}" is built in`);
230
+ if (typeof render !== 'function') throw new TypeError('Thread item renderer must be a function');
231
+ AgentThread.#renderers.set(name, render);
232
+ return this;
233
+ }
234
+
235
+ /**
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.
238
+ * @param {string} type
239
+ * @returns {boolean}
240
+ */
241
+ static has(type) {
242
+ return BUILT_IN.has(type) || AgentThread.#renderers.has(type);
243
+ }
244
+
245
+ /** @returns {HTMLElement} */
246
+ render() {
247
+ const created = !this.el;
248
+ const root = /** @type {HTMLElement} */ (this.el ?? h('section'));
249
+ this.el = root;
250
+ this._original = created ? null : snapshotTarget(root);
251
+ if (!created) root.replaceChildren();
252
+ this._id = uid('zx-agent-thread');
253
+ /** @type {Map<string, ThreadEntry>} */
254
+ this._entries = new Map();
255
+ /** @type {string[]} */
256
+ this._order = [];
257
+ this._announceTimer = 0;
258
+ this._askingPerson = false;
259
+ /** @type {Element|null} */
260
+ this._scrollHost = null;
261
+ /** @type {EventTarget|null} */
262
+ this._scrollTarget = null;
263
+ this._onScroll = () => { if (this._atEnd()) this._latestButton.hidden = true; };
264
+ /** @type {string|null} */
265
+ this._latestAnswer = null;
266
+ /** @type {Map<string, {expanded?: boolean|null, controls?: string|null}>} Artifact open states, for answers drawn later. */
267
+ this._artifacts = new Map();
268
+ /** @type {WeakSet<Surface>} Surfaces answered elsewhere, whose going is no reply. */
269
+ this._answeredElsewhere = new WeakSet();
270
+
271
+ this._feed = h('div', {
272
+ class: 'zx-agent-thread__feed', role: 'feed', 'aria-busy': 'false',
273
+ 'aria-label': this.options.label || this.msg('agentThread.label')
274
+ });
275
+ this._empty = h('div', { class: 'zx-agent-thread__empty', hidden: true });
276
+ this._latestButton = /** @type {HTMLButtonElement} */ (h('button', {
277
+ type: 'button', class: 'zx-agent-thread__latest', hidden: true
278
+ }, icon('arrow-down', { size: 14 }), h('span', {}, this.msg('agentThread.latest'))));
279
+ this._status = h('p', { class: 'zx-agent-thread__status', role: 'status' });
280
+ root.append(this._feed, this._empty, this._latestButton, this._status);
281
+
282
+ this.listen(this._feed, 'keydown', (event) => this._onFeedKey(/** @type {KeyboardEvent} */ (event)));
283
+ this.listen(this._latestButton, 'click', () => {
284
+ this.scrollToEnd();
285
+ this._lastArticle()?.focus({ preventScroll: true });
286
+ });
287
+ this.listen(root, 'click', (event) => this._onClick(/** @type {MouseEvent} */ (event)));
288
+
289
+ for (const item of Array.isArray(this.options.items) ? this.options.items : []) this._add(item);
290
+ this._syncPositions();
291
+ this._syncEmpty();
292
+ return root;
293
+ }
294
+
295
+ /* ------------------------------------------------------------------ public API -- */
296
+
297
+ /**
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.
300
+ * @param {ThreadItem[]} items
301
+ * @returns {this}
302
+ */
303
+ setItems(items) {
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)));
313
+ this._syncPositions();
314
+ this._syncEmpty();
315
+ return this;
316
+ }
317
+
318
+ /**
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.
321
+ * @param {ThreadItem} item
322
+ * @param {UpsertOptions} [options]
323
+ * @returns {this}
324
+ */
325
+ upsert(item, options = {}) {
326
+ if (!item || typeof item !== 'object' || item.id == null) return this;
327
+ const id = String(item.id);
328
+ const after = options?.after == null ? null : String(options.after);
329
+ this._follow(() => {
330
+ if (this._entries.has(id)) this._replace(id, item);
331
+ else this._add(item, { announce: true, after });
332
+ this._syncPositions();
333
+ this._syncEmpty();
334
+ });
335
+ return this;
336
+ }
337
+
338
+ /**
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.
343
+ * @param {string} id
344
+ * @param {Record<string, unknown>} partial
345
+ * @returns {this}
346
+ */
347
+ patch(id, partial) {
348
+ const entry = this._entries.get(String(id));
349
+ if (!entry || !partial || typeof partial !== 'object') return this;
350
+ const before = entry.item;
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);
355
+ const keys = Object.keys(partial);
356
+ const only = (/** @type {string[]} */ allowed) => keys.every((key) => allowed.includes(key));
357
+ this._follow(() => {
358
+ if (item.type === 'answer' && entry.view && only(['streaming', 'stopped', 'sources', 'blocks', 'steps'])
359
+ && (!('steps' in partial) || entry.trace)) {
360
+ entry.item = item;
361
+ const answer = /** @type {Extract<ThreadItem, {type: 'answer'}>} */ (item);
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
+ }
368
+ if ('steps' in partial) entry.trace?.setSteps(answer.steps ?? []);
369
+ if (answer.stopped && !(/** @type {any} */ (before)).stopped) {
370
+ entry.view.stop();
371
+ this._announce(this.msg('agentThread.stoppedAnnounce'), true);
372
+ } else if ('streaming' in partial && !answer.streaming && (/** @type {any} */ (before)).streaming) {
373
+ entry.view.end();
374
+ this._announce(this.msg('agentThread.answered', this._authorName(item)));
375
+ }
376
+ if ('sources' in partial) entry.view.setSources(answer.sources ?? []);
377
+ this._redrawAnswerFooter(entry);
378
+ this._syncWriting(entry);
379
+ } else if (item.type === 'trace' && entry.trace && only(['steps', 'open', 'title'])) {
380
+ entry.item = item;
381
+ const trace = /** @type {Extract<ThreadItem, {type: 'trace'}>} */ (item);
382
+ if ('steps' in partial) entry.trace.setSteps(trace.steps ?? []);
383
+ if ('title' in partial) entry.trace.setLabel(trace.title ?? null);
384
+ if ('open' in partial) {
385
+ if (trace.open) entry.trace.expand(null);
386
+ else entry.trace.collapse();
387
+ }
388
+ } else if (item.type === 'approval' && entry.card && only(['status', 'answeredBy', 'answeredAt', 'rejectReason'])) {
389
+ entry.item = item;
390
+ const approval = /** @type {Extract<ThreadItem, {type: 'approval'}>} */ (item);
391
+ entry.card.setStatus(approval.status ?? 'pending', {
392
+ by: approval.answeredBy, at: approval.answeredAt, reason: approval.rejectReason ?? undefined
393
+ });
394
+ } else {
395
+ this._replace(String(id), item);
396
+ }
397
+ this._syncPositions();
398
+ });
399
+ return this;
400
+ }
401
+
402
+ /**
403
+ * Streams text into an answer, creating it when the id is new. Only the answer's last
404
+ * paragraph is redrawn.
405
+ * @param {string} id
406
+ * @param {string} text
407
+ * @returns {this}
408
+ */
409
+ appendText(id, text) {
410
+ const key = String(id);
411
+ let entry = this._entries.get(key);
412
+ if (!entry) {
413
+ this.upsert({ id: key, type: 'answer', blocks: [], streaming: true });
414
+ entry = this._entries.get(key);
415
+ }
416
+ if (!entry?.view) return this;
417
+ const view = entry.view;
418
+ const written = entry;
419
+ this._follow(() => {
420
+ view.appendText(text);
421
+ this._syncWriting(written);
422
+ });
423
+ return this;
424
+ }
425
+
426
+ /**
427
+ * Adds a whole block to an answer — a figures block, a table, code — after what it already
428
+ * shows, without redrawing the rest of the answer. Creates the answer when the id is new.
429
+ * @param {string} id
430
+ * @param {Block} block
431
+ * @returns {this}
432
+ */
433
+ appendBlock(id, block) {
434
+ const key = String(id);
435
+ if (!this._entries.has(key)) this.upsert({ id: key, type: 'answer', blocks: [], streaming: true });
436
+ const entry = this._entries.get(key);
437
+ const view = entry?.view;
438
+ if (entry && view) {
439
+ this._follow(() => {
440
+ view.append(block);
441
+ this._syncWriting(entry);
442
+ });
443
+ }
444
+ return this;
445
+ }
446
+
447
+ /**
448
+ * Says something through the thread's polite status — an outcome the thread cannot see itself,
449
+ * such as "Reminders sent". Said once; the same words said twice are heard twice.
450
+ * @param {string} text
451
+ * @returns {this}
452
+ */
453
+ announce(text) {
454
+ if (text) this._announce(String(text), true);
455
+ return this;
456
+ }
457
+
458
+ /**
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.
461
+ * @param {string} id
462
+ * @returns {this}
463
+ */
464
+ remove(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);
469
+ this._syncPositions();
470
+ this._syncEmpty();
471
+ if (held) this._entries.get(this._order[Math.max(0, index - 1)])?.article.focus({ preventScroll: true });
472
+ return this;
473
+ }
474
+
475
+ /**
476
+ * An item as it stands, an answer's streamed text included.
477
+ * @param {string} id
478
+ * @returns {ThreadItem|null}
479
+ */
480
+ get(id) {
481
+ const entry = this._entries.get(String(id));
482
+ if (!entry) return null;
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
+ }
494
+ if (item.type === 'trace' && entry.trace) /** @type {any} */ (item).steps = entry.trace.getSteps();
495
+ return item;
496
+ }
497
+
498
+ /** @returns {ThreadItem[]} Every item, in order, as it stands. */
499
+ getItems() {
500
+ return this._order.map((id) => /** @type {ThreadItem} */ (this.get(id)));
501
+ }
502
+
503
+ /**
504
+ * The main component drawn for an item: an answer's BlockView, a trace's RunTrace, an
505
+ * approval's ApprovalCard.
506
+ * @param {string} id
507
+ * @returns {Component|null}
508
+ */
509
+ getComponent(id) {
510
+ const entry = this._entries.get(String(id));
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;
522
+ }
523
+
524
+ /**
525
+ * Brings something into view and moves focus to it: `item:<id>` an item, `step:<id>` a trace
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`.
528
+ * @param {string} target
529
+ * @returns {boolean} Whether the target was found.
530
+ */
531
+ reveal(target) {
532
+ const [kind, ...rest] = String(target ?? '').split(':');
533
+ const id = rest.join(':');
534
+ let found = false;
535
+ if (kind === 'item') {
536
+ const entry = this._entries.get(id);
537
+ if (entry) {
538
+ entry.article.scrollIntoView({ block: 'nearest' });
539
+ entry.article.focus({ preventScroll: true });
540
+ found = true;
541
+ }
542
+ } else if (kind === 'step') {
543
+ for (const entryId of [...this._order].reverse()) {
544
+ const trace = this._entries.get(entryId)?.trace;
545
+ if (trace && trace.getSteps().some((step) => step.id === id)) {
546
+ trace.reveal(id);
547
+ found = true;
548
+ break;
549
+ }
550
+ }
551
+ } else if (kind === 'source') {
552
+ const [n, ...answer] = rest;
553
+ for (const entryId of answer.length ? [answer.join(':')] : [...this._order].reverse()) {
554
+ const sources = this._entries.get(entryId)?.sources;
555
+ if (sources) {
556
+ sources.highlight(Number(n));
557
+ found = true;
558
+ break;
559
+ }
560
+ }
561
+ }
562
+ if (found) this.emit('reveal', { target: String(target) });
563
+ return found;
564
+ }
565
+
566
+ /**
567
+ * Reflects whether an artifact is open somewhere — an inspector, a drawer — on every card that
568
+ * names it, in every answer. See `BlockView#setArtifactState()`.
569
+ * @param {string} id Artifact id.
570
+ * @param {{expanded?: boolean|null, controls?: string|null}} state
571
+ * @returns {this}
572
+ */
573
+ setArtifactState(id, state) {
574
+ const key = String(id);
575
+ const merged = { ...(this._artifacts.get(key) ?? {}), ...(state ?? {}) };
576
+ this._artifacts.set(key, merged);
577
+ for (const entry of this._entries.values()) entry.view?.setArtifactState(key, merged);
578
+ return this;
579
+ }
580
+
581
+ /**
582
+ * Scrolls to the end of the conversation.
583
+ * @returns {this}
584
+ */
585
+ scrollToEnd() {
586
+ const scroller = this._scroller();
587
+ if (scroller) scroller.scrollTop = scroller.scrollHeight;
588
+ this._latestButton.hidden = true;
589
+ return this;
590
+ }
591
+
592
+ /** @returns {void} */
593
+ destroy() {
594
+ if (this._destroyed) return;
595
+ this._destroyed = true;
596
+ clearTimeout(this._announceTimer);
597
+ this._scrollTarget?.removeEventListener('scroll', this._onScroll);
598
+ this._scrollTarget = null;
599
+ this._scrollHost = null;
600
+ for (const id of [...this._order]) this._drop(id);
601
+ super.destroy();
602
+ if (this._original) restoreTarget(this.el, this._original);
603
+ }
604
+
605
+ /* ------------------------------------------------------------------ items -- */
606
+
607
+ /**
608
+ * @private
609
+ * @param {ThreadItem} item
610
+ * @param {{announce?: boolean, after?: string|null}} [options]
611
+ * @returns {void}
612
+ */
613
+ _add(item, options = {}) {
614
+ if (this._destroyed || !item || typeof item !== 'object' || item.id == null) return;
615
+ const id = String(item.id);
616
+ if (this._entries.has(id)) {
617
+ this._replace(id, item);
618
+ return;
619
+ }
620
+ const entry = this._build(cloneItem(item));
621
+ this._entries.set(id, entry);
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
+ }
630
+ this._syncContinuation(id);
631
+ this._syncLatest();
632
+ if (options.announce) this._announceItem(entry.item);
633
+ }
634
+
635
+ /**
636
+ * @private
637
+ * @param {string} id
638
+ * @param {ThreadItem} item
639
+ * @returns {void}
640
+ */
641
+ _replace(id, item) {
642
+ const old = this._entries.get(id);
643
+ if (!old) return;
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);
665
+ old.article.replaceWith(entry.article);
666
+ for (const component of old.owned) component.destroy();
667
+ this._entries.set(id, entry);
668
+ this._syncContinuation(id);
669
+ this._syncPositions();
670
+ this._syncLatest();
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();
695
+ }
696
+
697
+ /** @private @param {string} id @returns {void} */
698
+ _drop(id) {
699
+ const entry = this._entries.get(id);
700
+ if (!entry) return;
701
+ for (const component of entry.owned) component.destroy();
702
+ entry.article.remove();
703
+ this._entries.delete(id);
704
+ const index = this._order.indexOf(id);
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]);
708
+ this._syncLatest();
709
+ }
710
+
711
+ /**
712
+ * Regenerate belongs to the latest answer only: when another answer becomes the latest, both
713
+ * answers' actions are redrawn.
714
+ * @private
715
+ * @returns {void}
716
+ */
717
+ _syncLatest() {
718
+ const latest = this._latestAnswerId();
719
+ if (latest === this._latestAnswer) return;
720
+ const previous = this._latestAnswer;
721
+ this._latestAnswer = latest;
722
+ for (const id of [previous, latest]) {
723
+ const entry = id ? this._entries.get(id) : null;
724
+ if (entry) this._redrawActions(entry);
725
+ }
726
+ }
727
+
728
+ /** @private @returns {string|null} The id of the last answer in the thread. */
729
+ _latestAnswerId() {
730
+ for (let index = this._order.length - 1; index >= 0; index -= 1) {
731
+ if (this._entries.get(this._order[index])?.item.type === 'answer') return this._order[index];
732
+ }
733
+ return null;
734
+ }
735
+
736
+ /**
737
+ * Redraws an answer's action row alone, leaving its sources as they are.
738
+ * @private
739
+ * @param {ThreadEntry} entry
740
+ * @returns {void}
741
+ */
742
+ _redrawActions(entry) {
743
+ const footer = entry.article.querySelector('.zx-agent-thread__footer');
744
+ if (!footer || /** @type {any} */ (entry.item).streaming) return;
745
+ footer.querySelector('.zx-agent-thread__actions')?.remove();
746
+ const actions = this._answerActions(entry);
747
+ if (actions) footer.append(actions);
748
+ }
749
+
750
+ /**
751
+ * Draws one item into its article.
752
+ * @private
753
+ * @param {ThreadItem} item
754
+ * @param {Surface|null} [surface=null] A surface to keep rather than draw anew.
755
+ * @returns {ThreadEntry}
756
+ */
757
+ _build(item, surface = null) {
758
+ /** @type {ThreadEntry} */
759
+ const entry = { item, article: h('article'), owned: [], view: null, trace: null, sources: null, card: null, surface: null };
760
+ const own = /** @type {<T extends Component>(component: T) => T} */ ((component) => {
761
+ entry.owned.push(component);
762
+ return component;
763
+ });
764
+ const mine = this._isMine(item);
765
+ const bylineId = uid(`${this._id}-byline`);
766
+ const article = entry.article;
767
+ article.className = 'zx-agent-thread__item';
768
+ article.tabIndex = -1;
769
+ article.dataset.type = item.type;
770
+ article.dataset.id = String(item.id);
771
+ if (mine) article.dataset.mine = 'true';
772
+ article.setAttribute('aria-labelledby', bylineId);
773
+ // A notice is named by what it says, not by an author it may not have.
774
+ if (item.type !== 'notice') {
775
+ const avatar = mine ? null : this._avatar(item, own);
776
+ if (avatar) article.append(avatar);
777
+ article.append(this._byline(item, bylineId));
778
+ }
779
+
780
+ const body = h('div', { class: 'zx-agent-thread__body' });
781
+ article.append(body);
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) {
784
+ case 'user': {
785
+ const user = /** @type {Extract<ThreadItem, {type: 'user'}>} */ (item);
786
+ body.append(h('div', { class: 'zx-agent-thread__bubble' },
787
+ h('p', { class: 'zx-agent-thread__text' }, withMentions(String(user.text ?? ''), user.mentions))));
788
+ if (Array.isArray(user.files) && user.files.length) body.append(this._files(user.files));
789
+ const actions = this._userActions(user);
790
+ if (actions) {
791
+ article.setAttribute('data-zx-reveal-host', '');
792
+ body.append(actions);
793
+ }
794
+ break;
795
+ }
796
+ case 'text':
797
+ body.append(h('p', { class: 'zx-agent-thread__text' }, String(/** @type {any} */ (item).text ?? '')));
798
+ break;
799
+ case 'notice': {
800
+ const notice = /** @type {Extract<ThreadItem, {type: 'notice'}>} */ (item);
801
+ const tone = ['info', 'success', 'warning', 'danger'].includes(String(notice.tone)) ? String(notice.tone) : 'neutral';
802
+ article.dataset.tone = tone;
803
+ body.append(h('p', { class: 'zx-agent-thread__notice' },
804
+ tone === 'neutral' ? null : h('span', { class: 'zx-agent-thread__notice-icon', 'aria-hidden': 'true' },
805
+ icon(tone === 'danger' ? 'error' : tone, { size: 14 })),
806
+ h('span', { id: bylineId }, String(notice.text ?? '')),
807
+ notice.action?.id && notice.action.label ? h('button', {
808
+ type: 'button', class: 'zx-agent-thread__notice-action',
809
+ dataset: { threadAction: 'notice', threadValue: String(notice.action.id) }
810
+ }, String(notice.action.label)) : null));
811
+ break;
812
+ }
813
+ case 'answer':
814
+ this._buildAnswer(entry, body, own);
815
+ break;
816
+ case 'trace': {
817
+ const trace = /** @type {Extract<ThreadItem, {type: 'trace'}>} */ (item);
818
+ entry.trace = own(this._trace(trace.steps ?? [], { open: Boolean(trace.open), label: trace.title ?? null }));
819
+ body.append(entry.trace.toElement());
820
+ break;
821
+ }
822
+ case 'approval':
823
+ this._buildApproval(entry, body, own);
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;
834
+ default: {
835
+ const render = AgentThread.#renderers.get(item.type);
836
+ const content = render ? render(item, { thread: this, author: this._author(item), own }) : null;
837
+ if (content) body.append(content);
838
+ break;
839
+ }
840
+ }
841
+ const refs = this._refs(/** @type {{refs?: unknown}} */ (item).refs);
842
+ if (refs) body.append(refs);
843
+ return entry;
844
+ }
845
+
846
+ /**
847
+ * A RunTrace the thread owns: its authors, glyphs, and clock.
848
+ * @private
849
+ * @param {import('../../internal/agent-model.js').TraceStep[]} steps
850
+ * @param {{open?: boolean, label?: string|null}} [options]
851
+ * @returns {RunTrace}
852
+ */
853
+ _trace(steps, options = {}) {
854
+ const trace = new RunTrace(null, {
855
+ steps,
856
+ open: Boolean(options.open),
857
+ label: options.label ?? null,
858
+ authors: this.options.authors,
859
+ icons: this.options.traceIcons ?? {},
860
+ ticking: true,
861
+ now: this.options.now ?? null,
862
+ formatTime: this.options.formatTime ?? null
863
+ });
864
+ // A link on a step is the item's link too: the application hears it once, from the thread.
865
+ this._contain(trace, ['open']);
866
+ trace.on('open', (event) => {
867
+ const detail = /** @type {CustomEvent<{step: any, ref: any}>} */ (event).detail;
868
+ const article = trace.toElement().closest('.zx-agent-thread__item');
869
+ const id = article instanceof HTMLElement ? article.dataset.id : null;
870
+ if (id) this.emit('open', { item: this.get(id), ref: detail.ref, step: detail.step });
871
+ });
872
+ return trace;
873
+ }
874
+
875
+ /**
876
+ * Keeps a child's bubbling `zx-<type>` events inside the thread for the types the thread
877
+ * re-emits itself, so a listener on the thread's root hears each of them once.
878
+ * @private
879
+ * @param {Component} child
880
+ * @param {string[]} types
881
+ * @returns {void}
882
+ */
883
+ _contain(child, types) {
884
+ for (const type of types) this.listen(child.toElement(), `zx-${type}`, (event) => event.stopPropagation());
885
+ }
886
+
887
+ /**
888
+ * Links from an item to the application's own things, after its content.
889
+ * @private
890
+ * @param {unknown} refs
891
+ * @returns {HTMLElement|null}
892
+ */
893
+ _refs(refs) {
894
+ const list = Array.isArray(refs) ? refs.filter((ref) => ref && ref.id != null && ref.label) : [];
895
+ if (!list.length) return null;
896
+ return h('ul', { class: 'zx-agent-thread__refs' }, list.map((ref) => h('li', {},
897
+ h('button', { type: 'button', class: 'zx-agent-thread__ref', dataset: { threadAction: 'open', threadValue: String(ref.id) } },
898
+ ref.icon ? h('span', { class: 'zx-agent-thread__ref-icon', 'aria-hidden': 'true' }, icon(String(ref.icon), { size: 14 })) : null,
899
+ h('span', {}, String(ref.label))))));
900
+ }
901
+
902
+ /**
903
+ * Edit and copy on the person's own message, shown while it is pointed at or holds focus.
904
+ * @private
905
+ * @param {Extract<ThreadItem, {type: 'user'}>} user
906
+ * @returns {HTMLElement|null}
907
+ */
908
+ _userActions(user) {
909
+ const wanted = new Set(Array.isArray(this.options.userActions) ? this.options.userActions : []);
910
+ if (!wanted.size) return null;
911
+ const icons = { ...DEFAULT_ICONS, ...(this.options.icons ?? {}) };
912
+ /** @type {Node[]} */
913
+ const controls = [];
914
+ if (wanted.has('copy')) controls.push(copyButton({ text: String(user.text ?? ''), title: this.msg('agentThread.copyMessage'), size: 'sm' }));
915
+ if (wanted.has('edit')) controls.push(actionButton(icons.edit, this.msg('agentThread.edit'), { action: 'edit' }));
916
+ return controls.length ? h('div', { class: 'zx-agent-thread__actions', 'data-zx-reveal': '' }, controls) : null;
917
+ }
918
+
919
+ /**
920
+ * @private
921
+ * @param {ThreadEntry} entry
922
+ * @param {HTMLElement} body
923
+ * @param {<T extends Component>(component: T) => T} own
924
+ * @returns {void}
925
+ */
926
+ _buildAnswer(entry, body, own) {
927
+ const answer = /** @type {Extract<ThreadItem, {type: 'answer'}>} */ (entry.item);
928
+ const version = this._version(answer);
929
+ if (version.steps.length) {
930
+ entry.trace = own(this._trace(version.steps, { open: Boolean(answer.stepsOpen) }));
931
+ body.append(entry.trace.toElement());
932
+ }
933
+ body.append(h('p', { class: 'zx-agent-thread__writing', hidden: true }, this.msg('agentThread.writingNow', this._authorName(answer))));
934
+ const view = own(new BlockView(null, {
935
+ blocks: version.blocks,
936
+ sources: version.sources,
937
+ streaming: Boolean(answer.streaming),
938
+ headingLevel: this.options.headingLevel
939
+ }));
940
+ if (version.stopped) view.stop();
941
+ for (const [artifact, state] of this._artifacts) view.setArtifactState(artifact, state);
942
+ this._contain(view, ['cite', 'artifact']);
943
+ view.on('cite', (event) => {
944
+ const detail = /** @type {CustomEvent<{n: number, source: Source|null}>} */ (event).detail;
945
+ const emitted = this.emit('cite', { item: this.get(String(answer.id)), n: detail.n, source: detail.source });
946
+ if (!emitted.defaultPrevented) entry.sources?.highlight(detail.n);
947
+ });
948
+ view.on('artifact', (event) => {
949
+ const detail = /** @type {CustomEvent<{id: string}>} */ (event).detail;
950
+ this.emit('artifact', { item: this.get(String(answer.id)), id: detail.id });
951
+ });
952
+ entry.view = view;
953
+ body.append(view.toElement());
954
+ body.append(h('div', { class: 'zx-agent-thread__footer' }));
955
+ this._redrawAnswerFooter(entry, own);
956
+ this._syncWriting(entry);
957
+ }
958
+
959
+ /**
960
+ * While an answer is on its way and nothing of it has arrived, a quiet line says who is
961
+ * writing; it goes as soon as the first words do.
962
+ * @private
963
+ * @param {ThreadEntry} entry
964
+ * @returns {void}
965
+ */
966
+ _syncWriting(entry) {
967
+ const line = /** @type {HTMLElement|null} */ (entry.article.querySelector('.zx-agent-thread__writing'));
968
+ if (!line || !entry.view) return;
969
+ line.hidden = !(/** @type {any} */ (entry.item).streaming && entry.view.toElement().childElementCount === 0);
970
+ }
971
+
972
+ /**
973
+ * Draws an answer's sources and actions, which show only once it is finished.
974
+ * @private
975
+ * @param {ThreadEntry} entry
976
+ * @param {<T extends Component>(component: T) => T} [own]
977
+ * @returns {void}
978
+ */
979
+ _redrawAnswerFooter(entry, own) {
980
+ const footer = /** @type {HTMLElement|null} */ (entry.article.querySelector('.zx-agent-thread__footer'));
981
+ if (!footer) return;
982
+ const answer = /** @type {Extract<ThreadItem, {type: 'answer'}>} */ (entry.item);
983
+ const adopt = own ?? (/** @type {<T extends Component>(component: T) => T} */ ((component) => {
984
+ entry.owned.push(component);
985
+ return component;
986
+ }));
987
+ if (entry.sources) {
988
+ entry.owned = entry.owned.filter((component) => component !== entry.sources);
989
+ entry.sources.destroy();
990
+ entry.sources = null;
991
+ }
992
+ footer.replaceChildren();
993
+ if (answer.streaming) return;
994
+ const sources = this._version(answer).sources;
995
+ if (sources.length) {
996
+ const list = adopt(new SourceList(null, { sources, label: this.msg('agentThread.sources'), icons: this.options.sourceIcons ?? {} }));
997
+ list.on('select', (event) => {
998
+ const source = /** @type {CustomEvent<{source: Source}>} */ (event).detail.source;
999
+ if (source?.call) {
1000
+ event.preventDefault();
1001
+ this.reveal(`step:${source.call}`);
1002
+ }
1003
+ });
1004
+ entry.sources = list;
1005
+ footer.append(list.toElement());
1006
+ }
1007
+ const actions = this._answerActions(entry);
1008
+ if (actions) footer.append(actions);
1009
+ }
1010
+
1011
+ /**
1012
+ * @private
1013
+ * @param {ThreadEntry} entry
1014
+ * @returns {HTMLElement|null}
1015
+ */
1016
+ _answerActions(entry) {
1017
+ const answer = /** @type {Extract<ThreadItem, {type: 'answer'}>} */ (entry.item);
1018
+ const wanted = new Set(Array.isArray(this.options.answerActions) ? this.options.answerActions : []);
1019
+ const icons = { ...DEFAULT_ICONS, ...(this.options.icons ?? {}) };
1020
+ const id = String(answer.id);
1021
+ /** @type {Array<Node>} */
1022
+ const controls = [];
1023
+ const versions = Array.isArray(answer.versions) ? answer.versions : [];
1024
+ if (versions.length > 1) {
1025
+ const index = this._versionIndex(answer);
1026
+ controls.push(h('span', { class: 'zx-agent-thread__pager' },
1027
+ actionButton('chevron-left', this.msg('agentThread.previousVersion'), { action: 'version', value: String(index - 1), dir: 'previous' }, index === 0),
1028
+ h('span', { class: 'zx-agent-thread__pager-text' }, `${index + 1} / ${versions.length}`,
1029
+ h('span', { class: 'zx-agent-thread__sr' }, ` ${this.msg('agentThread.version', index + 1, versions.length)}`)),
1030
+ actionButton('chevron-right', this.msg('agentThread.nextVersion'), { action: 'version', value: String(index + 1), dir: 'next' }, index === versions.length - 1)));
1031
+ }
1032
+ if (wanted.has('copy')) {
1033
+ controls.push(copyButton({ text: () => entry.view?.toMarkdown() ?? '', title: this.msg('agentThread.copy'), size: 'sm' }));
1034
+ }
1035
+ if (wanted.has('regenerate') && this._latestAnswerId() === id) {
1036
+ controls.push(actionButton(icons.regenerate, this.msg('agentThread.regenerate'), { action: 'regenerate' }));
1037
+ }
1038
+ if (wanted.has('branch')) controls.push(actionButton(icons.branch, this.msg('agentThread.branch'), { action: 'branch' }));
1039
+ if (wanted.has('rate')) {
1040
+ for (const [value, glyph, key] of [['up', icons.rateUp, 'agentThread.rateUp'], ['down', icons.rateDown, 'agentThread.rateDown']]) {
1041
+ const control = actionButton(glyph, this.msg(key), { action: 'rate', value });
1042
+ control.setAttribute('aria-pressed', String(this._version(answer).rating === value));
1043
+ controls.push(control);
1044
+ }
1045
+ }
1046
+ return controls.length ? h('div', { class: 'zx-agent-thread__actions' }, controls) : null;
1047
+ }
1048
+
1049
+ /**
1050
+ * @private
1051
+ * @param {ThreadEntry} entry
1052
+ * @param {HTMLElement} body
1053
+ * @param {<T extends Component>(component: T) => T} own
1054
+ * @returns {void}
1055
+ */
1056
+ _buildApproval(entry, body, own) {
1057
+ const approval = /** @type {Extract<ThreadItem, {type: 'approval'}>} */ (entry.item);
1058
+ const card = own(new ApprovalCard(null, {
1059
+ title: approval.title,
1060
+ description: approval.description,
1061
+ icon: approval.icon ?? null,
1062
+ tone: /** @type {any} */ (approval.tone ?? 'blue'),
1063
+ status: approval.status ?? 'pending',
1064
+ details: approval.details ?? null,
1065
+ preview: approval.preview ? { label: approval.preview.label, content: approval.preview.blocks } : null,
1066
+ fields: approval.fields ?? null,
1067
+ values: approval.values ?? {},
1068
+ confirmText: approval.confirmText ?? null,
1069
+ reason: approval.reason ?? 'optional',
1070
+ edited: Boolean(approval.edited),
1071
+ editedKeys: Array.isArray(approval.editedKeys) ? approval.editedKeys : null,
1072
+ rejectReason: approval.rejectReason ?? null,
1073
+ now: this.options.now ?? null,
1074
+ answeredBy: approval.answeredBy ?? null,
1075
+ answeredAt: approval.answeredAt ?? null,
1076
+ headingLevel: this.options.headingLevel
1077
+ }));
1078
+ this._contain(card, ['approve', 'edit', 'reject']);
1079
+ for (const type of ['approve', 'edit', 'reject']) {
1080
+ card.on(type, (event) => {
1081
+ const detail = /** @type {CustomEvent<Record<string, any>>} */ (event).detail;
1082
+ const emitted = this.emit(type, { item: this.get(String(approval.id)), ...detail });
1083
+ if (emitted.defaultPrevented) {
1084
+ event.preventDefault();
1085
+ return;
1086
+ }
1087
+ // The item follows the card, so get() and a later redraw keep what was decided.
1088
+ const at = (this.options.now?.() ?? new Date()).toISOString();
1089
+ // The card keeps which values were edited across saves; the item stores its answer.
1090
+ if (type === 'edit') {
1091
+ entry.item = /** @type {ThreadItem} */ ({ ...entry.item, values: detail.values, edited: true, editedKeys: detail.editedKeys ?? null });
1092
+ }
1093
+ else if (type === 'approve') entry.item = /** @type {ThreadItem} */ ({ ...entry.item, status: 'approved', values: detail.values, answeredAt: at });
1094
+ else entry.item = /** @type {ThreadItem} */ ({ ...entry.item, status: 'rejected', rejectReason: detail.reason || null, answeredAt: at });
1095
+ });
1096
+ }
1097
+ entry.card = card;
1098
+ body.append(card.toElement());
1099
+ }
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
+
1145
+ /**
1146
+ * The author's avatar, beside the byline and the content. Decorative: the byline names them.
1147
+ * @private
1148
+ * @param {ThreadItem} item
1149
+ * @param {<T extends Component>(component: T) => T} own
1150
+ * @returns {HTMLElement|null}
1151
+ */
1152
+ _avatar(item, own) {
1153
+ const author = this._author(item);
1154
+ if (!author) return null;
1155
+ if (author.icon) {
1156
+ return h('span', { class: 'zx-agent-thread__avatar' },
1157
+ h('span', { class: 'zx-agent-thread__mark', dataset: { tone: author.tone ?? null, kind: author.kind ?? 'agent' }, 'aria-hidden': 'true' },
1158
+ icon(String(author.icon), { size: 14 })));
1159
+ }
1160
+ const avatar = own(new Avatar(null, {
1161
+ name: author.name, initials: author.initials ?? initialsOf(author.name), tone: /** @type {any} */ (author.tone ?? null),
1162
+ size: 'sm', shape: author.kind === 'person' ? 'circle' : 'rounded', activity: author.activity ?? null
1163
+ }));
1164
+ return h('span', { class: 'zx-agent-thread__avatar' }, avatar.toElement());
1165
+ }
1166
+
1167
+ /**
1168
+ * @private
1169
+ * @param {ThreadItem} item
1170
+ * @param {string} id
1171
+ * @returns {HTMLElement}
1172
+ */
1173
+ _byline(item, id) {
1174
+ const author = this._author(item);
1175
+ const name = this._authorName(item);
1176
+ const shown = item.type === 'answer' ? this._version(/** @type {any} */ (item)) : null;
1177
+ const at = shown ? shown.at : item.at;
1178
+ const time = this._time(at);
1179
+ const byline = h('div', { class: 'zx-agent-thread__byline' });
1180
+ byline.append(h('span', { class: 'zx-agent-thread__author', id }, name,
1181
+ time ? h('span', { class: 'zx-agent-thread__sr' }, `, ${time}`) : null));
1182
+ if (author?.via) byline.append(h('span', { class: 'zx-agent-thread__via' }, this.msg('agentThread.via', author.via)));
1183
+ if (time) byline.append(h('time', { class: 'zx-agent-thread__time', dateTime: String(at), 'aria-hidden': 'true' }, time));
1184
+ if (shown?.stopped) {
1185
+ byline.append(h('span', { class: 'zx-agent-thread__flag' }, this.msg('agentThread.stopped')));
1186
+ }
1187
+ return byline;
1188
+ }
1189
+
1190
+ /**
1191
+ * @private
1192
+ * @param {Array<{name: string, size?: number}>} files
1193
+ * @returns {HTMLElement}
1194
+ */
1195
+ _files(files) {
1196
+ return h('ul', { class: 'zx-agent-thread__files', 'aria-label': this.msg('agentThread.attachments') },
1197
+ files.map((file) => h('li', { class: 'zx-agent-thread__file' },
1198
+ h('span', { class: 'zx-agent-thread__file-icon', 'aria-hidden': 'true' }, icon('file', { size: 14 })),
1199
+ h('span', { class: 'zx-agent-thread__file-name' }, String(file.name ?? '')),
1200
+ typeof file.size === 'number' ? h('span', { class: 'zx-agent-thread__file-size' }, formatFileSize(file.size, { decimals: 0, standard: 'si' })) : null)));
1201
+ }
1202
+
1203
+ /* ------------------------------------------------------------------ helpers -- */
1204
+
1205
+ /** @private @param {ThreadItem} item @returns {boolean} */
1206
+ _isMine(item) {
1207
+ return item.author ? item.author === this.options.me : item.type === 'user';
1208
+ }
1209
+
1210
+ /** @private @param {ThreadItem} item @returns {Author|null} */
1211
+ _author(item) {
1212
+ const authors = this.options.authors ?? {};
1213
+ if (item.author && Object.hasOwn(authors, item.author)) return authors[item.author];
1214
+ if (this._isMine(item)) return Object.hasOwn(authors, this.options.me) ? authors[this.options.me] : null;
1215
+ const first = Object.entries(authors).find(([key, author]) => key !== this.options.me && author.kind !== 'person');
1216
+ return first ? first[1] : null;
1217
+ }
1218
+
1219
+ /** @private @param {ThreadItem} item @returns {string} */
1220
+ _authorName(item) {
1221
+ if (this._isMine(item)) return this.msg('agentThread.you');
1222
+ return this._author(item)?.name ?? this.msg('agentThread.agent');
1223
+ }
1224
+
1225
+ /** @private @param {unknown} at @returns {string} */
1226
+ _time(at) {
1227
+ if (typeof at !== 'string' || !at) return '';
1228
+ if (typeof this.options.formatTime === 'function') return String(this.options.formatTime(at) ?? '');
1229
+ const date = new Date(at);
1230
+ if (Number.isNaN(date.getTime())) return '';
1231
+ return new Intl.DateTimeFormat(dateLocale(this.options.locale), { hour: '2-digit', minute: '2-digit' }).format(date);
1232
+ }
1233
+
1234
+ /** @private @param {Extract<ThreadItem, {type: 'answer'}>} answer @returns {number} */
1235
+ _versionIndex(answer) {
1236
+ const versions = Array.isArray(answer.versions) ? answer.versions : [];
1237
+ const index = Number.isInteger(answer.version) ? Number(answer.version) : versions.length - 1;
1238
+ return Math.max(0, Math.min(versions.length - 1, index));
1239
+ }
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
+
1275
+ /**
1276
+ * The blocks, sources, and steps an answer shows: its chosen version's when it has several.
1277
+ * @private
1278
+ * @param {Extract<ThreadItem, {type: 'answer'}>} answer
1279
+ * @returns {{blocks: Block[], sources: Source[], steps: import('../../internal/agent-model.js').TraceStep[],
1280
+ * stopped: boolean, rating: 'up'|'down'|null, at: string|undefined}}
1281
+ */
1282
+ _version(answer) {
1283
+ const versions = Array.isArray(answer.versions) ? answer.versions : [];
1284
+ const version = versions.length > 1 ? versions[this._versionIndex(answer)] : null;
1285
+ if (version) {
1286
+ return {
1287
+ blocks: version.blocks ?? [], sources: version.sources ?? [], steps: version.steps ?? answer.steps ?? [],
1288
+ stopped: version.stopped ?? Boolean(answer.stopped), rating: version.rating !== undefined ? version.rating : answer.rating ?? null,
1289
+ at: version.at ?? answer.at
1290
+ };
1291
+ }
1292
+ return {
1293
+ blocks: answer.blocks ?? [], sources: answer.sources ?? [], steps: answer.steps ?? [],
1294
+ stopped: Boolean(answer.stopped), rating: answer.rating ?? null, at: answer.at
1295
+ };
1296
+ }
1297
+
1298
+ /**
1299
+ * A consecutive item by the same author reads as one turn: its byline is still there for a
1300
+ * screen reader, but not drawn again.
1301
+ * @private
1302
+ * @param {string} id
1303
+ * @returns {void}
1304
+ */
1305
+ _syncContinuation(id) {
1306
+ const index = this._order.indexOf(id);
1307
+ for (const at of [index, index + 1]) {
1308
+ const entry = this._entries.get(this._order[at]);
1309
+ const previous = this._entries.get(this._order[at - 1]);
1310
+ if (!entry) continue;
1311
+ // A notice belongs to no one, so it ends a turn on either side of it.
1312
+ const same = Boolean(previous) && !this._isMine(entry.item) && !this._isMine(/** @type {ThreadEntry} */ (previous).item)
1313
+ && entry.item.type !== 'notice' && /** @type {ThreadEntry} */ (previous).item.type !== 'notice'
1314
+ && this._authorName(entry.item) === this._authorName(/** @type {ThreadEntry} */ (previous).item);
1315
+ if (same) entry.article.dataset.continued = 'true';
1316
+ else delete entry.article.dataset.continued;
1317
+ }
1318
+ }
1319
+
1320
+ /** @private @returns {void} */
1321
+ _syncPositions() {
1322
+ const size = String(this._order.length);
1323
+ this._order.forEach((id, index) => {
1324
+ const article = this._entries.get(id)?.article;
1325
+ if (!article) return;
1326
+ article.setAttribute('aria-posinset', String(index + 1));
1327
+ article.setAttribute('aria-setsize', size);
1328
+ });
1329
+ const streaming = this._order.some((id) => {
1330
+ const item = this._entries.get(id)?.item;
1331
+ return item?.type === 'answer' && Boolean(/** @type {any} */ (item).streaming);
1332
+ });
1333
+ this._feed.setAttribute('aria-busy', String(streaming));
1334
+ }
1335
+
1336
+ /** @private @returns {void} */
1337
+ _syncEmpty() {
1338
+ const empty = this._order.length === 0 && this.options.emptyState;
1339
+ this._empty.hidden = !empty;
1340
+ if (empty && !this._empty.firstChild) this._empty.append(emptyState(/** @type {EmptyStateOptions} */ (this.options.emptyState)));
1341
+ if (!empty) this._empty.replaceChildren();
1342
+ }
1343
+
1344
+ /** @private @param {ThreadItem} item @returns {void} */
1345
+ _announceItem(item) {
1346
+ const name = this._authorName(item);
1347
+ if (item.type === 'answer') {
1348
+ this._announce(this.msg(/** @type {any} */ (item).streaming ? 'agentThread.writing' : 'agentThread.answered', name));
1349
+ } else if (item.type === 'approval' && (/** @type {any} */ (item).status ?? 'pending') === 'pending') {
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);
1353
+ } else if (item.type === 'trace') {
1354
+ this._announce(this.msg('agentThread.working', name));
1355
+ } else if (item.type === 'notice' && ['warning', 'danger'].includes(String(/** @type {any} */ (item).tone))) {
1356
+ this._announce(String(/** @type {any} */ (item).text ?? ''));
1357
+ }
1358
+ }
1359
+
1360
+ /**
1361
+ * Says a milestone once. The region is cleared first so the same words said twice are heard
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.
1364
+ * @private
1365
+ * @param {string} text
1366
+ * @param {boolean} [urgent=false] Whether it must be heard.
1367
+ * @returns {void}
1368
+ */
1369
+ _announce(text, urgent = false) {
1370
+ if (this._askingPerson && !urgent) return;
1371
+ clearTimeout(this._announceTimer);
1372
+ this._askingPerson = urgent;
1373
+ this._status.textContent = '';
1374
+ this._announceTimer = window.setTimeout(() => {
1375
+ this._askingPerson = false;
1376
+ this._status.textContent = text;
1377
+ }, 60);
1378
+ }
1379
+
1380
+ /** @private @returns {Element|null} */
1381
+ _scroller() {
1382
+ /** @type {Element|null} */
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;
1391
+ }
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 });
1398
+ }
1399
+ return this._scrollHost;
1400
+ }
1401
+
1402
+ /** @private @returns {boolean} */
1403
+ _atEnd() {
1404
+ const scroller = this._scroller();
1405
+ if (!scroller) return true;
1406
+ return scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight <= END_SLACK;
1407
+ }
1408
+
1409
+ /**
1410
+ * Runs a change and keeps the end in view if the reader was reading it.
1411
+ * @private
1412
+ * @param {() => void} change
1413
+ * @returns {void}
1414
+ */
1415
+ _follow(change) {
1416
+ const follow = this.options.followOutput && this.el.isConnected && this._atEnd();
1417
+ change();
1418
+ if (!this.options.followOutput || !this.el.isConnected) return;
1419
+ if (follow) this.scrollToEnd();
1420
+ else if (!this._atEnd()) this._latestButton.hidden = false;
1421
+ }
1422
+
1423
+ /** @private @returns {HTMLElement|null} */
1424
+ _lastArticle() {
1425
+ const id = this._order.at(-1);
1426
+ return id ? this._entries.get(id)?.article ?? null : null;
1427
+ }
1428
+
1429
+ /* ------------------------------------------------------------------ events -- */
1430
+
1431
+ /** @private @param {MouseEvent} event @returns {void} */
1432
+ _onClick(event) {
1433
+ const target = event.target instanceof Element ? event.target.closest('[data-thread-action]') : null;
1434
+ if (!target || !this.el.contains(target)) return;
1435
+ const article = target.closest('.zx-agent-thread__item');
1436
+ const id = article instanceof HTMLElement ? article.dataset.id : null;
1437
+ const entry = id ? this._entries.get(id) : null;
1438
+ if (!entry) return;
1439
+ const action = String(/** @type {HTMLElement} */ (target).dataset.threadAction);
1440
+ const raw = /** @type {HTMLElement} */ (target).dataset.threadValue;
1441
+ if (action === 'version') {
1442
+ const value = Number(raw);
1443
+ const dir = /** @type {HTMLElement} */ (target).dataset.threadDir;
1444
+ const emitted = this.emit('action', { item: this.get(String(id)), action, value });
1445
+ if (!emitted.defaultPrevented) {
1446
+ this._replace(String(id), /** @type {ThreadItem} */ ({ ...entry.item, version: value }));
1447
+ // Paging keeps focus on the pager: the same arrow, or the other one at either end.
1448
+ const pager = this._entries.get(String(id))?.article.querySelectorAll('[data-thread-action="version"]');
1449
+ const buttons = /** @type {HTMLButtonElement[]} */ ([...(pager ?? [])]);
1450
+ const same = buttons.find((button) => button.dataset.threadDir === dir && !button.disabled);
1451
+ (same ?? buttons.find((button) => !button.disabled))?.focus();
1452
+ }
1453
+ return;
1454
+ }
1455
+ if (action === 'open') {
1456
+ const ref = (/** @type {any} */ (entry.item).refs ?? []).find((/** @type {any} */ candidate) => String(candidate?.id) === raw);
1457
+ if (ref) this.emit('open', { item: this.get(String(id)), ref: { ...ref } });
1458
+ return;
1459
+ }
1460
+ if (action === 'notice') {
1461
+ this.emit('action', { item: this.get(String(id)), action: String(raw) });
1462
+ return;
1463
+ }
1464
+ if (action === 'rate') {
1465
+ const answer = /** @type {Extract<ThreadItem, {type: 'answer'}>} */ (entry.item);
1466
+ const current = this._version(answer).rating;
1467
+ const value = current === raw ? null : raw;
1468
+ const emitted = this.emit('action', { item: this.get(String(id)), action, value });
1469
+ if (!emitted.defaultPrevented) {
1470
+ // With versions, a rating belongs to the version shown.
1471
+ const versions = Array.isArray(answer.versions) && answer.versions.length > 1
1472
+ ? answer.versions.map((version, index) => (index === this._versionIndex(answer) ? { ...version, rating: /** @type {any} */ (value) } : version))
1473
+ : answer.versions;
1474
+ entry.item = /** @type {ThreadItem} */ ({ ...entry.item, rating: value, versions });
1475
+ for (const control of entry.article.querySelectorAll('[data-thread-action="rate"]')) {
1476
+ control.setAttribute('aria-pressed', String(/** @type {HTMLElement} */ (control).dataset.threadValue === value));
1477
+ }
1478
+ }
1479
+ return;
1480
+ }
1481
+ this.emit('action', { item: this.get(String(id)), action });
1482
+ }
1483
+
1484
+ /**
1485
+ * APG feed keys: PageDown and PageUp move between articles; Ctrl+End and Ctrl+Home move focus
1486
+ * past the end or before the start of the feed. A control inside an item keeps them.
1487
+ * @private
1488
+ * @param {KeyboardEvent} event
1489
+ * @returns {void}
1490
+ */
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;
1494
+ const article = event.target instanceof Element ? event.target.closest('.zx-agent-thread__item') : null;
1495
+ if (!(article instanceof HTMLElement)) return;
1496
+ const articles = this._order.map((id) => this._entries.get(id)?.article).filter(Boolean);
1497
+ const index = articles.indexOf(article);
1498
+ if (event.key === 'PageDown' || event.key === 'PageUp') {
1499
+ const next = articles[index + (event.key === 'PageDown' ? 1 : -1)];
1500
+ if (next) {
1501
+ event.preventDefault();
1502
+ next.focus();
1503
+ }
1504
+ } else if ((event.ctrlKey || event.metaKey) && (event.key === 'End' || event.key === 'Home')) {
1505
+ const outside = focusableOutside(this._feed, event.key === 'End' ? 1 : -1);
1506
+ if (outside) {
1507
+ event.preventDefault();
1508
+ outside.focus();
1509
+ }
1510
+ }
1511
+ }
1512
+ }
1513
+
1514
+ /** Item types the thread draws itself. */
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
+ }
1558
+
1559
+ /**
1560
+ * An icon button the thread's delegated click listener acts on.
1561
+ * @param {string} glyph
1562
+ * @param {string} label
1563
+ * @param {{action: string, value?: string, dir?: string}} data
1564
+ * @param {boolean} [disabled]
1565
+ * @returns {HTMLButtonElement}
1566
+ */
1567
+ function actionButton(glyph, label, data, disabled = false) {
1568
+ return /** @type {HTMLButtonElement} */ (h('button', {
1569
+ type: 'button', class: 'zx-icon-btn zx-agent-thread__action', title: label, 'aria-label': label, disabled,
1570
+ dataset: { size: 'sm', threadAction: data.action, threadValue: data.value ?? null, threadDir: data.dir ?? null }
1571
+ }, icon(glyph, { size: 14 })));
1572
+ }
1573
+
1574
+ /**
1575
+ * The person's text with each `@name` it mentions marked, as text nodes and spans.
1576
+ * @param {string} text
1577
+ * @param {unknown} mentions Names without the `@`, or `{name, tone}` to colour a name in its tone.
1578
+ * @returns {Array<Node|string>}
1579
+ */
1580
+ function withMentions(text, mentions) {
1581
+ /** @type {Map<string, string|null>} Each mentioned name and its tone. */
1582
+ const tones = new Map();
1583
+ for (const mention of Array.isArray(mentions) ? mentions : []) {
1584
+ const name = String(typeof mention === 'object' && mention ? mention.name ?? '' : mention ?? '').trim();
1585
+ if (name) tones.set(name, typeof mention === 'object' && mention?.tone ? String(mention.tone) : null);
1586
+ }
1587
+ const names = [...tones.keys()];
1588
+ if (!names.length) return [text];
1589
+ const escaped = names.sort((a, b) => b.length - a.length).map((name) => escapeRegExp(name));
1590
+ const pattern = new RegExp(`@(?:${escaped.join('|')})(?![\\w])`, 'g');
1591
+ /** @type {Array<Node|string>} */
1592
+ const out = [];
1593
+ let from = 0;
1594
+ for (const match of text.matchAll(pattern)) {
1595
+ const at = Number(match.index);
1596
+ if (at > from) out.push(text.slice(from, at));
1597
+ out.push(h('span', { class: 'zx-agent-thread__mention', dataset: { tone: tones.get(match[0].slice(1)) ?? null } }, match[0]));
1598
+ from = at + match[0].length;
1599
+ }
1600
+ if (from < text.length) out.push(text.slice(from));
1601
+ return out;
1602
+ }
1603
+
1604
+ /** Elements that take focus from the keyboard. */
1605
+ const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), '
1606
+ + 'textarea:not([disabled]), [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';
1607
+
1608
+ /**
1609
+ * The first focusable element after (`1`) or before (`-1`) an element in document order.
1610
+ * @param {Element} element
1611
+ * @param {1|-1} direction
1612
+ * @returns {HTMLElement|null}
1613
+ */
1614
+ function focusableOutside(element, direction) {
1615
+ const all = /** @type {HTMLElement[]} */ ([...document.querySelectorAll(FOCUSABLE)])
1616
+ .filter((candidate) => !element.contains(candidate) && candidate.getClientRects().length > 0);
1617
+ const position = (/** @type {HTMLElement} */ candidate) => element.compareDocumentPosition(candidate);
1618
+ if (direction === 1) return all.find((candidate) => position(candidate) & Node.DOCUMENT_POSITION_FOLLOWING) ?? null;
1619
+ return all.reverse().find((candidate) => position(candidate) & Node.DOCUMENT_POSITION_PRECEDING) ?? null;
1620
+ }
1621
+
1622
+ /**
1623
+ * Action payload: under an answer `copy`, `regenerate`, `branch`, `rate` (`value` up, down, or
1624
+ * null), or `version` (`value` the version index; preventable, like `rate`); on the person's own
1625
+ * message `edit` (copying needs no event); on a notice, the id of its `action`.
1626
+ * @event AgentThread#action
1627
+ * @type {CustomEvent<{item: ThreadItem, action: string, value?: unknown}>}
1628
+ */
1629
+ /**
1630
+ * An approval was approved; preventable, which keeps the card pending.
1631
+ * @event AgentThread#approve
1632
+ * @type {CustomEvent<{item: ThreadItem, values: Record<string, unknown>}>}
1633
+ */
1634
+ /**
1635
+ * An approval's values were edited; preventable.
1636
+ * @event AgentThread#edit
1637
+ * @type {CustomEvent<{item: ThreadItem, values: Record<string, unknown>}>}
1638
+ */
1639
+ /**
1640
+ * An approval was rejected; preventable, which keeps the card pending.
1641
+ * @event AgentThread#reject
1642
+ * @type {CustomEvent<{item: ThreadItem, reason: string}>}
1643
+ */
1644
+ /**
1645
+ * A citation was activated; preventable, which skips highlighting the source.
1646
+ * @event AgentThread#cite
1647
+ * @type {CustomEvent<{item: ThreadItem, n: number, source: Source|null}>}
1648
+ */
1649
+ /**
1650
+ * An artifact card was activated.
1651
+ * @event AgentThread#artifact
1652
+ * @type {CustomEvent<{item: ThreadItem, id: string}>}
1653
+ */
1654
+ /**
1655
+ * Something was brought into view by `reveal()`.
1656
+ * @event AgentThread#reveal
1657
+ * @type {CustomEvent<{target: string}>}
1658
+ */
1659
+ /**
1660
+ * A link was activated: one of an item's `refs`, or of a trace step's (then `step` names it).
1661
+ * @event AgentThread#open
1662
+ * @type {CustomEvent<{item: ThreadItem, ref: import('../../internal/agent-model.js').ItemRef, step?: import('../../internal/agent-model.js').TraceStep}>}
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
+ */