@zeyos/zx 5.4.0 → 5.6.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 (145) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/README.md +23 -16
  3. package/dist/types/components/agent-thread/agent-thread.d.ts +583 -0
  4. package/dist/types/components/app-sidebar/app-sidebar.d.ts +33 -0
  5. package/dist/types/components/approval-card/approval-card.d.ts +596 -0
  6. package/dist/types/components/avatar/avatar.d.ts +91 -4
  7. package/dist/types/components/badge/badge.d.ts +5 -4
  8. package/dist/types/components/block-view/block-view.d.ts +205 -0
  9. package/dist/types/components/composer/composer.d.ts +736 -0
  10. package/dist/types/components/datebox/date-range-box.d.ts +15 -2
  11. package/dist/types/components/datebox/datebox.d.ts +37 -3
  12. package/dist/types/components/kbd/kbd.d.ts +41 -0
  13. package/dist/types/components/launcher/launcher.d.ts +4 -2
  14. package/dist/types/components/prose/prose.d.ts +69 -0
  15. package/dist/types/components/questionnaire/questionnaire.d.ts +0 -36
  16. package/dist/types/components/run-status/run-status.d.ts +393 -0
  17. package/dist/types/components/run-trace/run-trace.d.ts +624 -0
  18. package/dist/types/components/source-list/source-list.d.ts +177 -0
  19. package/dist/types/components/stat-tile/stat-tile.d.ts +20 -0
  20. package/dist/types/components/tag-picker/tag-picker.d.ts +11 -5
  21. package/dist/types/components/tree/tree.d.ts +44 -3
  22. package/dist/types/core/icons.d.ts +22 -1
  23. package/dist/types/core/messages.d.ts +135 -0
  24. package/dist/types/index.d.ts +12 -2
  25. package/dist/types/internal/agent-model.d.ts +587 -0
  26. package/dist/types/internal/app-rail.d.ts +10 -3
  27. package/dist/types/internal/highlight.d.ts +24 -0
  28. package/dist/types/internal/presence-loop.d.ts +148 -0
  29. package/dist/types/internal/row-actions.d.ts +151 -0
  30. package/dist/zx-zeyos.esm.js +4852 -4535
  31. package/dist/zx-zeyos.esm.min.js +4 -4
  32. package/dist/zx.css +3152 -434
  33. package/dist/zx.esm.js +13730 -6595
  34. package/dist/zx.esm.min.js +27 -8
  35. package/dist/zx.global.js +13730 -6595
  36. package/dist/zx.global.min.js +27 -8
  37. package/dist/zx.min.css +1 -1
  38. package/docs/api.json +1474 -205
  39. package/docs/llms.md +698 -39
  40. package/docs/llms.txt +12 -1
  41. package/package.json +1 -1
  42. package/src/components/account-menu/account-menu.js +2 -2
  43. package/src/components/agent-thread/agent-thread.css +417 -0
  44. package/src/components/agent-thread/agent-thread.js +1365 -0
  45. package/src/components/app-rail/app-rail.css +11 -11
  46. package/src/components/app-sidebar/app-sidebar.css +90 -17
  47. package/src/components/app-sidebar/app-sidebar.js +120 -12
  48. package/src/components/approval-card/approval-card.css +289 -0
  49. package/src/components/approval-card/approval-card.js +1377 -0
  50. package/src/components/avatar/avatar.css +56 -1
  51. package/src/components/avatar/avatar.js +148 -26
  52. package/src/components/badge/badge.css +33 -20
  53. package/src/components/badge/badge.js +5 -4
  54. package/src/components/block-view/block-view.css +300 -0
  55. package/src/components/block-view/block-view.js +523 -0
  56. package/src/components/breadcrumb/breadcrumb.css +28 -3
  57. package/src/components/breadcrumb/breadcrumb.js +2 -2
  58. package/src/components/button/button.css +24 -13
  59. package/src/components/button/button.js +20 -2
  60. package/src/components/calendar/calendar.css +14 -4
  61. package/src/components/card-view/card-view.js +2 -2
  62. package/src/components/chart/chart.js +20 -5
  63. package/src/components/check-button/check-button.css +11 -3
  64. package/src/components/check-button/check-button.js +3 -3
  65. package/src/components/composer/composer.css +403 -0
  66. package/src/components/composer/composer.js +1441 -0
  67. package/src/components/context-menu/context-menu.css +7 -1
  68. package/src/components/date-picker/date-picker.css +6 -0
  69. package/src/components/date-picker/date-picker.js +5 -5
  70. package/src/components/date-picker/date-range-picker.css +6 -0
  71. package/src/components/date-picker/date-range-picker.js +3 -3
  72. package/src/components/date-picker/month-picker.js +3 -3
  73. package/src/components/date-picker/time-picker.css +6 -0
  74. package/src/components/datebox/date-range-box.js +30 -6
  75. package/src/components/datebox/datebox.js +44 -7
  76. package/src/components/dialog/dialog.css +0 -1
  77. package/src/components/dialog/dialog.js +2 -1
  78. package/src/components/dock/dock.js +2 -2
  79. package/src/components/dropdown/dropdown.css +2 -1
  80. package/src/components/entity-ref/entity-ref.css +8 -1
  81. package/src/components/file-item/file-item.css +1 -1
  82. package/src/components/finder/finder.js +2 -2
  83. package/src/components/groupbox/groupbox.js +2 -2
  84. package/src/components/kanban-view/kanban-view.css +8 -4
  85. package/src/components/kanban-view/kanban-view.js +3 -3
  86. package/src/components/kbd/kbd.css +64 -0
  87. package/src/components/kbd/kbd.js +121 -0
  88. package/src/components/launcher/launcher.css +30 -25
  89. package/src/components/launcher/launcher.js +15 -21
  90. package/src/components/list-toolbar/list-toolbar.css +7 -1
  91. package/src/components/menu-button/menu-button.css +9 -2
  92. package/src/components/message/message.js +2 -2
  93. package/src/components/module-bar/module-bar.css +11 -1
  94. package/src/components/multi-value-editor/multi-value-editor.js +4 -4
  95. package/src/components/navigation-bar/navigation-bar.css +3 -2
  96. package/src/components/pagination/pagination.js +2 -2
  97. package/src/components/panel/panel.js +2 -2
  98. package/src/components/prose/prose.css +53 -0
  99. package/src/components/prose/prose.js +152 -0
  100. package/src/components/questionnaire/questionnaire.css +7 -17
  101. package/src/components/questionnaire/questionnaire.js +16 -1
  102. package/src/components/rating/rating.css +3 -1
  103. package/src/components/run-status/run-status.css +208 -0
  104. package/src/components/run-status/run-status.js +782 -0
  105. package/src/components/run-trace/run-trace.css +443 -0
  106. package/src/components/run-trace/run-trace.js +1209 -0
  107. package/src/components/search/search.js +2 -2
  108. package/src/components/select/glyphs.js +3 -3
  109. package/src/components/select/select.css +35 -7
  110. package/src/components/select/select.js +4 -4
  111. package/src/components/source-list/source-list.css +208 -0
  112. package/src/components/source-list/source-list.js +355 -0
  113. package/src/components/stat-tile/stat-tile.css +56 -2
  114. package/src/components/stat-tile/stat-tile.js +25 -2
  115. package/src/components/stepper/stepper.css +2 -1
  116. package/src/components/stepper/stepper.js +3 -3
  117. package/src/components/tabbox/tabbox.css +2 -2
  118. package/src/components/tabbox/tabbox.js +2 -2
  119. package/src/components/table/table.css +52 -16
  120. package/src/components/table/table.js +7 -5
  121. package/src/components/tag-picker/tag-picker.css +56 -43
  122. package/src/components/tag-picker/tag-picker.js +21 -16
  123. package/src/components/tree/tree.css +44 -0
  124. package/src/components/tree/tree.js +97 -9
  125. package/src/components/value-list/value-list.css +25 -4
  126. package/src/components/value-list/value-list.js +2 -1
  127. package/src/components/view/record-view.js +3 -3
  128. package/src/components/view-settings/view-settings.css +2 -1
  129. package/src/components/workspace-switcher/workspace-switcher.js +3 -3
  130. package/src/core/icons.js +34 -3
  131. package/src/core/messages.js +143 -0
  132. package/src/elements/define.js +1 -0
  133. package/src/index.js +12 -2
  134. package/src/internal/agent-model.js +488 -0
  135. package/src/internal/app-rail.js +5 -1
  136. package/src/internal/highlight.js +104 -0
  137. package/src/internal/presence-loop.js +343 -0
  138. package/src/internal/row-actions.js +203 -0
  139. package/styles/base.css +26 -1
  140. package/styles/prose.css +306 -0
  141. package/styles/tokens/dark.css +97 -120
  142. package/styles/tokens/global.css +24 -9
  143. package/styles/tokens/semantic.css +464 -184
  144. package/styles/tokens/themes.css +9 -0
  145. package/styles/zx.css +10 -0
@@ -0,0 +1,1365 @@
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 { escapeRegExp, uid } from '../../core/util.js';
7
+ import { AGENT_MESSAGES, initialsOf } from '../../internal/agent-model.js';
8
+ import { ApprovalCard } from '../approval-card/approval-card.js';
9
+ import { Avatar } from '../avatar/avatar.js';
10
+ import { BlockView } from '../block-view/block-view.js';
11
+ import { copyButton } from '../copy/copy-button.js';
12
+ import { emptyState } from '../empty-state/empty-state.js';
13
+ import { RunTrace } from '../run-trace/run-trace.js';
14
+ import { SourceList } from '../source-list/source-list.js';
15
+
16
+ /** @typedef {import('../../internal/agent-model.js').ThreadItem} ThreadItem */
17
+ /** @typedef {import('../../internal/agent-model.js').Author} Author */
18
+ /** @typedef {import('../../internal/agent-model.js').Source} Source */
19
+ /** @typedef {import('../../internal/agent-model.js').Block} Block */
20
+ /** @typedef {import('../empty-state/empty-state.js').EmptyStateOptions} EmptyStateOptions */
21
+ /** @typedef {'copy'|'regenerate'|'branch'|'rate'} AnswerAction */
22
+
23
+ /**
24
+ * What a registered item renderer receives besides the item.
25
+ * @typedef {Object} ThreadRenderContext
26
+ * @property {AgentThread} thread The thread drawing the item.
27
+ * @property {Author|null} author The item's author, resolved from `authors`.
28
+ * @property {<T extends Component>(component: T) => T} own Hands a component to the thread, which
29
+ * destroys it with the item.
30
+ */
31
+
32
+ /**
33
+ * Draws one item of a registered type. It returns the item's content; the thread wraps it in the
34
+ * article, byline included.
35
+ * @typedef {(item: ThreadItem, context: ThreadRenderContext) => Node|null} ThreadItemRenderer
36
+ */
37
+
38
+ /**
39
+ * @typedef {Object} AgentThreadOptions
40
+ * @property {ThreadItem[]} [items=[]] The conversation, oldest first.
41
+ * @property {Record<string, Author>} [authors={}] Who wrote the items and took the steps, by key.
42
+ * An item without an `author` is the person's own (`user`) or the first agent's (anything else).
43
+ * @property {string} [me='me'] Author key of the person reading; their items read as "You".
44
+ * @property {string|null} [label=null] Accessible name of the feed; "Conversation" when null.
45
+ * @property {2|3|4|5} [headingLevel=3] Heading level inside answers and cards.
46
+ * @property {EmptyStateOptions|null} [emptyState=null] Shown while there are no items.
47
+ * @property {boolean} [followOutput=true] Keep the end in view while new output arrives, as long
48
+ * as the reader is at the end; otherwise offer "Jump to latest" and leave them where they are.
49
+ * @property {Element|null} [scroller=null] The element that scrolls; the nearest scrolling
50
+ * ancestor (or the thread itself) when null.
51
+ * @property {AnswerAction[]} [answerActions=['copy','regenerate','branch']] Actions under each
52
+ * finished answer; `regenerate` only under the latest one.
53
+ * @property {Partial<Record<'regenerate'|'branch'|'rateUp'|'rateDown'|'edit', string>>} [icons] Glyph
54
+ * names for the answer and message actions.
55
+ * @property {Array<'edit'|'copy'>} [userActions=[]] Actions on the person's own messages, shown
56
+ * while the message is pointed at or holds focus (always on a touch screen): `edit` asks the
57
+ * application to put the message back in the composer, `copy` copies its text.
58
+ * @property {Record<string, string>} [traceIcons={}] Glyph names for trace step kinds, handed to
59
+ * every `RunTrace` the thread draws.
60
+ * @property {Record<string, string>} [sourceIcons={}] Glyph names for source kinds, handed to every
61
+ * `SourceList` the thread draws.
62
+ * @property {(() => Date)|null} [now=null] The clock "today" is measured against in cards and
63
+ * traces, for an application whose world runs on fixed dates; the real clock when null.
64
+ * @property {((at: string) => string)|null} [formatTime=null] Formats an item's `at`; the local
65
+ * clock time when null.
66
+ * @property {string} [locale] Locale for times.
67
+ * @property {Record<string, string>|Record<string, Record<string, string>>} [msg] Localized messages.
68
+ * @property {(event: CustomEvent<{item: ThreadItem, action: string, value?: unknown}>) => void} [onaction] Answer action listener.
69
+ * @property {(event: CustomEvent<{item: ThreadItem, values: Record<string, unknown>}>) => void} [onapprove] Approval listener.
70
+ * @property {(event: CustomEvent<{item: ThreadItem, values: Record<string, unknown>}>) => void} [onedit] Edit listener.
71
+ * @property {(event: CustomEvent<{item: ThreadItem, reason: string}>) => void} [onreject] Rejection listener.
72
+ * @property {(event: CustomEvent<{item: ThreadItem, n: number, source: Source|null}>) => void} [oncite] Citation listener.
73
+ * @property {(event: CustomEvent<{item: ThreadItem, id: string}>) => void} [onartifact] Artifact listener.
74
+ * @property {(event: CustomEvent<{target: string}>) => void} [onreveal] Reveal listener.
75
+ * @property {(event: CustomEvent<{item: ThreadItem, ref: import('../../internal/agent-model.js').ItemRef}>) => void} [onopen] Link listener.
76
+ */
77
+
78
+ /**
79
+ * @typedef {Object} ThreadEntry
80
+ * @property {ThreadItem} item The item as last given.
81
+ * @property {HTMLElement} article Its article.
82
+ * @property {Component[]} owned Components drawn for it.
83
+ * @property {BlockView|null} view An answer's text.
84
+ * @property {RunTrace|null} trace A trace's steps.
85
+ * @property {SourceList|null} sources An answer's sources.
86
+ * @property {ApprovalCard|null} card An approval.
87
+ */
88
+
89
+ const MESSAGES = Object.freeze({
90
+ ...AGENT_MESSAGES,
91
+ 'agentThread.label': 'Conversation',
92
+ 'agentThread.you': 'You',
93
+ 'agentThread.agent': 'Agent',
94
+ 'agentThread.via': 'via %1',
95
+ 'agentThread.latest': 'Jump to latest',
96
+ 'agentThread.copy': 'Copy answer',
97
+ 'agentThread.regenerate': 'Regenerate answer',
98
+ 'agentThread.branch': 'Branch into a new conversation',
99
+ 'agentThread.rateUp': 'Helpful',
100
+ 'agentThread.rateDown': 'Not helpful',
101
+ 'agentThread.previousVersion': 'Previous version',
102
+ 'agentThread.nextVersion': 'Next version',
103
+ 'agentThread.version': 'Version %1 of %2',
104
+ 'agentThread.attachments': 'Attachments',
105
+ 'agentThread.sources': 'Sources',
106
+ 'agentThread.stopped': 'Stopped',
107
+ 'agentThread.writing': '%1 is writing an answer',
108
+ 'agentThread.answered': '%1 answered',
109
+ 'agentThread.working': '%1 is working',
110
+ 'agentThread.needsApproval': '%1 needs your approval',
111
+ 'agentThread.stoppedAnnounce': 'Stopped',
112
+ 'agentThread.writingNow': '%1 is writing…',
113
+ 'agentThread.edit': 'Edit message',
114
+ 'agentThread.copyMessage': 'Copy message'
115
+ });
116
+
117
+ const DEFAULT_ICONS = Object.freeze({ regenerate: 'reload', branch: 'columns', rateUp: 'check', rateDown: 'x', edit: 'type' });
118
+
119
+ /** How close to the end, in pixels, still counts as reading the end. */
120
+ const END_SLACK = 48;
121
+
122
+ /**
123
+ * A conversation with one or more agents: the person's messages, the agents' answers as they
124
+ * stream, the steps a run took, the approvals that hold it, and one-line notices — drawn from the
125
+ * plain-JSON items of the agent model. The thread owns no transport and no state beyond what it
126
+ * is given: the application feeds it (`upsert`, `patch`, `appendText`) and acts on what it emits.
127
+ *
128
+ * It follows the APG feed pattern: each item is an article in a `role="feed"`, PageDown and
129
+ * PageUp move between articles, and Ctrl+End / Ctrl+Home leave the feed. Streamed text is never
130
+ * read aloud as it arrives; one polite status says when an agent starts, answers, needs
131
+ * approval, or is stopped.
132
+ *
133
+ * @fires AgentThread#action
134
+ * @fires AgentThread#approve
135
+ * @fires AgentThread#edit
136
+ * @fires AgentThread#reject
137
+ * @fires AgentThread#cite
138
+ * @fires AgentThread#artifact
139
+ * @fires AgentThread#reveal
140
+ * @fires AgentThread#open
141
+ * @extends {Component<AgentThreadOptions>}
142
+ */
143
+ export class AgentThread extends Component {
144
+ static cssName = 'agent-thread';
145
+
146
+ /** @type {Readonly<AgentThreadOptions>} */
147
+ static defaults = {
148
+ items: [],
149
+ authors: {},
150
+ me: 'me',
151
+ label: null,
152
+ headingLevel: 3,
153
+ emptyState: null,
154
+ followOutput: true,
155
+ scroller: null,
156
+ answerActions: ['copy', 'regenerate', 'branch'],
157
+ userActions: [],
158
+ icons: {},
159
+ traceIcons: {},
160
+ sourceIcons: {},
161
+ now: null,
162
+ formatTime: null,
163
+ msg: MESSAGES
164
+ };
165
+
166
+ /** @type {Map<string, ThreadItemRenderer>} */
167
+ static #renderers = new Map();
168
+
169
+ /**
170
+ * Registers how items of another type are drawn — an application's own, or a surface. A
171
+ * built-in type cannot be replaced.
172
+ * @param {string} type Item type.
173
+ * @param {ThreadItemRenderer} render Draws the item's content.
174
+ * @returns {typeof AgentThread}
175
+ */
176
+ static register(type, render) {
177
+ const name = String(type ?? '').trim();
178
+ if (!name) throw new TypeError('Thread item type must not be empty');
179
+ if (BUILT_IN.has(name)) throw new TypeError(`Thread item type "${name}" is built in`);
180
+ if (typeof render !== 'function') throw new TypeError('Thread item renderer must be a function');
181
+ AgentThread.#renderers.set(name, render);
182
+ return this;
183
+ }
184
+
185
+ /**
186
+ * Reports whether a type has a registered renderer.
187
+ * @param {string} type
188
+ * @returns {boolean}
189
+ */
190
+ static has(type) {
191
+ return BUILT_IN.has(type) || AgentThread.#renderers.has(type);
192
+ }
193
+
194
+ /** @returns {HTMLElement} */
195
+ render() {
196
+ const created = !this.el;
197
+ const root = /** @type {HTMLElement} */ (this.el ?? h('section'));
198
+ this.el = root;
199
+ this._original = created ? null : snapshotTarget(root);
200
+ if (!created) root.replaceChildren();
201
+ this._id = uid('zx-agent-thread');
202
+ /** @type {Map<string, ThreadEntry>} */
203
+ this._entries = new Map();
204
+ /** @type {string[]} */
205
+ this._order = [];
206
+ this._announceTimer = 0;
207
+ /** @type {Element|null} */
208
+ this._scrollHost = null;
209
+ /** @type {string|null} */
210
+ this._latestAnswer = null;
211
+ /** @type {Map<string, {expanded?: boolean|null, controls?: string|null}>} Artifact open states, for answers drawn later. */
212
+ this._artifacts = new Map();
213
+
214
+ this._feed = h('div', {
215
+ class: 'zx-agent-thread__feed', role: 'feed', 'aria-busy': 'false',
216
+ 'aria-label': this.options.label || this.msg('agentThread.label')
217
+ });
218
+ this._empty = h('div', { class: 'zx-agent-thread__empty', hidden: true });
219
+ this._latestButton = /** @type {HTMLButtonElement} */ (h('button', {
220
+ type: 'button', class: 'zx-agent-thread__latest', hidden: true
221
+ }, icon('arrow-down', { size: 14 }), h('span', {}, this.msg('agentThread.latest'))));
222
+ this._status = h('p', { class: 'zx-agent-thread__status', role: 'status' });
223
+ root.append(this._feed, this._empty, this._latestButton, this._status);
224
+
225
+ this.listen(this._feed, 'keydown', (event) => this._onFeedKey(/** @type {KeyboardEvent} */ (event)));
226
+ this.listen(this._latestButton, 'click', () => {
227
+ this.scrollToEnd();
228
+ this._lastArticle()?.focus({ preventScroll: true });
229
+ });
230
+ this.listen(root, 'click', (event) => this._onClick(/** @type {MouseEvent} */ (event)));
231
+
232
+ for (const item of Array.isArray(this.options.items) ? this.options.items : []) this._add(item);
233
+ this._syncPositions();
234
+ this._syncEmpty();
235
+ return root;
236
+ }
237
+
238
+ /* ------------------------------------------------------------------ public API -- */
239
+
240
+ /**
241
+ * Replaces the conversation.
242
+ * @param {ThreadItem[]} items
243
+ * @returns {this}
244
+ */
245
+ setItems(items) {
246
+ for (const id of [...this._order]) this._drop(id);
247
+ for (const item of Array.isArray(items) ? items : []) this._add(item);
248
+ this._syncPositions();
249
+ this._syncEmpty();
250
+ return this;
251
+ }
252
+
253
+ /**
254
+ * Adds an item, or replaces the item with the same id where it stands.
255
+ * @param {ThreadItem} item
256
+ * @returns {this}
257
+ */
258
+ upsert(item) {
259
+ if (!item || typeof item !== 'object' || item.id == null) return this;
260
+ const id = String(item.id);
261
+ this._follow(() => {
262
+ if (this._entries.has(id)) this._replace(id, item);
263
+ else this._add(item, { announce: true });
264
+ this._syncPositions();
265
+ this._syncEmpty();
266
+ });
267
+ return this;
268
+ }
269
+
270
+ /**
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.
274
+ * @param {string} id
275
+ * @param {Record<string, unknown>} partial
276
+ * @returns {this}
277
+ */
278
+ patch(id, partial) {
279
+ const entry = this._entries.get(String(id));
280
+ if (!entry || !partial || typeof partial !== 'object') return this;
281
+ const before = entry.item;
282
+ const item = /** @type {ThreadItem} */ ({ ...before, ...structuredClone(partial), id: before.id, type: before.type });
283
+ const keys = Object.keys(partial);
284
+ const only = (/** @type {string[]} */ allowed) => keys.every((key) => allowed.includes(key));
285
+ this._follow(() => {
286
+ if (item.type === 'answer' && entry.view && only(['streaming', 'stopped', 'sources', 'blocks', 'steps'])
287
+ && (!('steps' in partial) || entry.trace)) {
288
+ entry.item = item;
289
+ const answer = /** @type {Extract<ThreadItem, {type: 'answer'}>} */ (item);
290
+ if ('blocks' in partial) entry.view.setBlocks(answer.blocks ?? []);
291
+ if ('steps' in partial) entry.trace?.setSteps(answer.steps ?? []);
292
+ if (answer.stopped && !(/** @type {any} */ (before)).stopped) {
293
+ entry.view.stop();
294
+ this._announce(this.msg('agentThread.stoppedAnnounce'));
295
+ } else if ('streaming' in partial && !answer.streaming && (/** @type {any} */ (before)).streaming) {
296
+ entry.view.end();
297
+ this._announce(this.msg('agentThread.answered', this._authorName(item)));
298
+ }
299
+ if ('sources' in partial) entry.view.setSources(answer.sources ?? []);
300
+ this._redrawAnswerFooter(entry);
301
+ this._syncWriting(entry);
302
+ } else if (item.type === 'trace' && entry.trace && only(['steps', 'open', 'title'])) {
303
+ entry.item = item;
304
+ const trace = /** @type {Extract<ThreadItem, {type: 'trace'}>} */ (item);
305
+ if ('steps' in partial) entry.trace.setSteps(trace.steps ?? []);
306
+ if ('title' in partial) entry.trace.setLabel(trace.title ?? null);
307
+ if ('open' in partial) {
308
+ if (trace.open) entry.trace.expand(null);
309
+ else entry.trace.collapse();
310
+ }
311
+ } else if (item.type === 'approval' && entry.card && only(['status', 'answeredBy', 'answeredAt', 'rejectReason'])) {
312
+ entry.item = item;
313
+ const approval = /** @type {Extract<ThreadItem, {type: 'approval'}>} */ (item);
314
+ entry.card.setStatus(approval.status ?? 'pending', {
315
+ by: approval.answeredBy, at: approval.answeredAt, reason: approval.rejectReason ?? undefined
316
+ });
317
+ } else {
318
+ this._replace(String(id), item);
319
+ }
320
+ this._syncPositions();
321
+ });
322
+ return this;
323
+ }
324
+
325
+ /**
326
+ * Streams text into an answer, creating it when the id is new. Only the answer's last
327
+ * paragraph is redrawn.
328
+ * @param {string} id
329
+ * @param {string} text
330
+ * @returns {this}
331
+ */
332
+ appendText(id, text) {
333
+ const key = String(id);
334
+ let entry = this._entries.get(key);
335
+ if (!entry) {
336
+ this.upsert({ id: key, type: 'answer', blocks: [], streaming: true });
337
+ entry = this._entries.get(key);
338
+ }
339
+ if (!entry?.view) return this;
340
+ const view = entry.view;
341
+ const written = entry;
342
+ this._follow(() => {
343
+ view.appendText(text);
344
+ this._syncWriting(written);
345
+ });
346
+ return this;
347
+ }
348
+
349
+ /**
350
+ * Adds a whole block to an answer — a figures block, a table, code — after what it already
351
+ * shows, without redrawing the rest of the answer. Creates the answer when the id is new.
352
+ * @param {string} id
353
+ * @param {Block} block
354
+ * @returns {this}
355
+ */
356
+ appendBlock(id, block) {
357
+ const key = String(id);
358
+ if (!this._entries.has(key)) this.upsert({ id: key, type: 'answer', blocks: [], streaming: true });
359
+ const entry = this._entries.get(key);
360
+ const view = entry?.view;
361
+ if (entry && view) {
362
+ this._follow(() => {
363
+ view.append(block);
364
+ this._syncWriting(entry);
365
+ });
366
+ }
367
+ return this;
368
+ }
369
+
370
+ /**
371
+ * Says something through the thread's polite status — an outcome the thread cannot see itself,
372
+ * such as "Reminders sent". Said once; the same words said twice are heard twice.
373
+ * @param {string} text
374
+ * @returns {this}
375
+ */
376
+ announce(text) {
377
+ if (text) this._announce(String(text));
378
+ return this;
379
+ }
380
+
381
+ /**
382
+ * Removes an item.
383
+ * @param {string} id
384
+ * @returns {this}
385
+ */
386
+ remove(id) {
387
+ this._drop(String(id));
388
+ this._syncPositions();
389
+ this._syncEmpty();
390
+ return this;
391
+ }
392
+
393
+ /**
394
+ * An item as it stands, an answer's streamed text included.
395
+ * @param {string} id
396
+ * @returns {ThreadItem|null}
397
+ */
398
+ get(id) {
399
+ const entry = this._entries.get(String(id));
400
+ if (!entry) return null;
401
+ const item = structuredClone(entry.item);
402
+ if (item.type === 'answer' && entry.view) /** @type {any} */ (item).blocks = entry.view.getBlocks();
403
+ if (item.type === 'trace' && entry.trace) /** @type {any} */ (item).steps = entry.trace.getSteps();
404
+ return item;
405
+ }
406
+
407
+ /** @returns {ThreadItem[]} Every item, in order, as it stands. */
408
+ getItems() {
409
+ return this._order.map((id) => /** @type {ThreadItem} */ (this.get(id)));
410
+ }
411
+
412
+ /**
413
+ * The main component drawn for an item: an answer's BlockView, a trace's RunTrace, an
414
+ * approval's ApprovalCard.
415
+ * @param {string} id
416
+ * @returns {Component|null}
417
+ */
418
+ getComponent(id) {
419
+ const entry = this._entries.get(String(id));
420
+ return entry ? entry.view ?? entry.trace ?? entry.card ?? null : null;
421
+ }
422
+
423
+ /**
424
+ * 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.
426
+ * @param {string} target
427
+ * @returns {boolean} Whether the target was found.
428
+ */
429
+ reveal(target) {
430
+ const [kind, ...rest] = String(target ?? '').split(':');
431
+ const id = rest.join(':');
432
+ let found = false;
433
+ if (kind === 'item') {
434
+ const entry = this._entries.get(id);
435
+ if (entry) {
436
+ entry.article.scrollIntoView({ block: 'nearest' });
437
+ entry.article.focus({ preventScroll: true });
438
+ found = true;
439
+ }
440
+ } else if (kind === 'step') {
441
+ for (const entryId of [...this._order].reverse()) {
442
+ const trace = this._entries.get(entryId)?.trace;
443
+ if (trace && trace.getSteps().some((step) => step.id === id)) {
444
+ trace.reveal(id);
445
+ found = true;
446
+ break;
447
+ }
448
+ }
449
+ } else if (kind === 'source') {
450
+ for (const entryId of [...this._order].reverse()) {
451
+ const sources = this._entries.get(entryId)?.sources;
452
+ if (sources) {
453
+ sources.highlight(Number(id));
454
+ found = true;
455
+ break;
456
+ }
457
+ }
458
+ }
459
+ if (found) this.emit('reveal', { target: String(target) });
460
+ return found;
461
+ }
462
+
463
+ /**
464
+ * Reflects whether an artifact is open somewhere — an inspector, a drawer — on every card that
465
+ * names it, in every answer. See `BlockView#setArtifactState()`.
466
+ * @param {string} id Artifact id.
467
+ * @param {{expanded?: boolean|null, controls?: string|null}} state
468
+ * @returns {this}
469
+ */
470
+ setArtifactState(id, state) {
471
+ const key = String(id);
472
+ const merged = { ...(this._artifacts.get(key) ?? {}), ...(state ?? {}) };
473
+ this._artifacts.set(key, merged);
474
+ for (const entry of this._entries.values()) entry.view?.setArtifactState(key, merged);
475
+ return this;
476
+ }
477
+
478
+ /**
479
+ * Scrolls to the end of the conversation.
480
+ * @returns {this}
481
+ */
482
+ scrollToEnd() {
483
+ const scroller = this._scroller();
484
+ if (scroller) scroller.scrollTop = scroller.scrollHeight;
485
+ this._latestButton.hidden = true;
486
+ return this;
487
+ }
488
+
489
+ /** @returns {void} */
490
+ destroy() {
491
+ if (this._destroyed) return;
492
+ this._destroyed = true;
493
+ clearTimeout(this._announceTimer);
494
+ for (const id of [...this._order]) this._drop(id);
495
+ super.destroy();
496
+ if (this._original) restoreTarget(this.el, this._original);
497
+ }
498
+
499
+ /* ------------------------------------------------------------------ items -- */
500
+
501
+ /**
502
+ * @private
503
+ * @param {ThreadItem} item
504
+ * @param {{announce?: boolean}} [options]
505
+ * @returns {void}
506
+ */
507
+ _add(item, options = {}) {
508
+ if (!item || typeof item !== 'object' || item.id == null) return;
509
+ const id = String(item.id);
510
+ if (this._entries.has(id)) {
511
+ this._replace(id, item);
512
+ return;
513
+ }
514
+ const entry = this._build(structuredClone(item));
515
+ this._entries.set(id, entry);
516
+ this._order.push(id);
517
+ this._feed.append(entry.article);
518
+ this._syncContinuation(id);
519
+ this._syncLatest();
520
+ if (options.announce) this._announceItem(entry.item);
521
+ }
522
+
523
+ /**
524
+ * @private
525
+ * @param {string} id
526
+ * @param {ThreadItem} item
527
+ * @returns {void}
528
+ */
529
+ _replace(id, item) {
530
+ const old = this._entries.get(id);
531
+ if (!old) return;
532
+ const hadFocus = old.article.contains(document.activeElement);
533
+ const entry = this._build(structuredClone({ ...item, id }));
534
+ old.article.replaceWith(entry.article);
535
+ for (const component of old.owned) component.destroy();
536
+ this._entries.set(id, entry);
537
+ this._syncContinuation(id);
538
+ this._syncPositions();
539
+ this._syncLatest();
540
+ if (hadFocus) entry.article.focus({ preventScroll: true });
541
+ }
542
+
543
+ /** @private @param {string} id @returns {void} */
544
+ _drop(id) {
545
+ const entry = this._entries.get(id);
546
+ if (!entry) return;
547
+ for (const component of entry.owned) component.destroy();
548
+ entry.article.remove();
549
+ this._entries.delete(id);
550
+ this._order = this._order.filter((other) => other !== id);
551
+ this._syncLatest();
552
+ }
553
+
554
+ /**
555
+ * Regenerate belongs to the latest answer only: when another answer becomes the latest, both
556
+ * answers' actions are redrawn.
557
+ * @private
558
+ * @returns {void}
559
+ */
560
+ _syncLatest() {
561
+ const latest = this._latestAnswerId();
562
+ if (latest === this._latestAnswer) return;
563
+ const previous = this._latestAnswer;
564
+ this._latestAnswer = latest;
565
+ for (const id of [previous, latest]) {
566
+ const entry = id ? this._entries.get(id) : null;
567
+ if (entry) this._redrawActions(entry);
568
+ }
569
+ }
570
+
571
+ /** @private @returns {string|null} The id of the last answer in the thread. */
572
+ _latestAnswerId() {
573
+ for (let index = this._order.length - 1; index >= 0; index -= 1) {
574
+ if (this._entries.get(this._order[index])?.item.type === 'answer') return this._order[index];
575
+ }
576
+ return null;
577
+ }
578
+
579
+ /**
580
+ * Redraws an answer's action row alone, leaving its sources as they are.
581
+ * @private
582
+ * @param {ThreadEntry} entry
583
+ * @returns {void}
584
+ */
585
+ _redrawActions(entry) {
586
+ const footer = entry.article.querySelector('.zx-agent-thread__footer');
587
+ if (!footer || /** @type {any} */ (entry.item).streaming) return;
588
+ footer.querySelector('.zx-agent-thread__actions')?.remove();
589
+ const actions = this._answerActions(entry);
590
+ if (actions) footer.append(actions);
591
+ }
592
+
593
+ /**
594
+ * Draws one item into its article.
595
+ * @private
596
+ * @param {ThreadItem} item
597
+ * @returns {ThreadEntry}
598
+ */
599
+ _build(item) {
600
+ /** @type {ThreadEntry} */
601
+ const entry = { item, article: h('article'), owned: [], view: null, trace: null, sources: null, card: null };
602
+ const own = /** @type {<T extends Component>(component: T) => T} */ ((component) => {
603
+ entry.owned.push(component);
604
+ return component;
605
+ });
606
+ const mine = this._isMine(item);
607
+ const bylineId = uid(`${this._id}-byline`);
608
+ const article = entry.article;
609
+ article.className = 'zx-agent-thread__item';
610
+ article.tabIndex = -1;
611
+ article.dataset.type = item.type;
612
+ article.dataset.id = String(item.id);
613
+ if (mine) article.dataset.mine = 'true';
614
+ article.setAttribute('aria-labelledby', bylineId);
615
+ // A notice is named by what it says, not by an author it may not have.
616
+ if (item.type !== 'notice') {
617
+ const avatar = mine ? null : this._avatar(item, own);
618
+ if (avatar) article.append(avatar);
619
+ article.append(this._byline(item, bylineId));
620
+ }
621
+
622
+ const body = h('div', { class: 'zx-agent-thread__body' });
623
+ article.append(body);
624
+ switch (item.type) {
625
+ case 'user': {
626
+ const user = /** @type {Extract<ThreadItem, {type: 'user'}>} */ (item);
627
+ body.append(h('div', { class: 'zx-agent-thread__bubble' },
628
+ h('p', { class: 'zx-agent-thread__text' }, withMentions(String(user.text ?? ''), user.mentions))));
629
+ if (Array.isArray(user.files) && user.files.length) body.append(this._files(user.files));
630
+ const actions = this._userActions(user);
631
+ if (actions) {
632
+ article.setAttribute('data-zx-reveal-host', '');
633
+ body.append(actions);
634
+ }
635
+ break;
636
+ }
637
+ case 'text':
638
+ body.append(h('p', { class: 'zx-agent-thread__text' }, String(/** @type {any} */ (item).text ?? '')));
639
+ break;
640
+ case 'notice': {
641
+ const notice = /** @type {Extract<ThreadItem, {type: 'notice'}>} */ (item);
642
+ const tone = ['info', 'success', 'warning', 'danger'].includes(String(notice.tone)) ? String(notice.tone) : 'neutral';
643
+ article.dataset.tone = tone;
644
+ body.append(h('p', { class: 'zx-agent-thread__notice' },
645
+ tone === 'neutral' ? null : h('span', { class: 'zx-agent-thread__notice-icon', 'aria-hidden': 'true' },
646
+ icon(tone === 'danger' ? 'error' : tone, { size: 14 })),
647
+ h('span', { id: bylineId }, String(notice.text ?? '')),
648
+ notice.action?.id && notice.action.label ? h('button', {
649
+ type: 'button', class: 'zx-agent-thread__notice-action',
650
+ dataset: { threadAction: 'notice', threadValue: String(notice.action.id) }
651
+ }, String(notice.action.label)) : null));
652
+ break;
653
+ }
654
+ case 'answer':
655
+ this._buildAnswer(entry, body, own);
656
+ break;
657
+ case 'trace': {
658
+ const trace = /** @type {Extract<ThreadItem, {type: 'trace'}>} */ (item);
659
+ entry.trace = own(this._trace(trace.steps ?? [], { open: Boolean(trace.open), label: trace.title ?? null }));
660
+ body.append(entry.trace.toElement());
661
+ break;
662
+ }
663
+ case 'approval':
664
+ this._buildApproval(entry, body, own);
665
+ break;
666
+ default: {
667
+ const render = AgentThread.#renderers.get(item.type);
668
+ const content = render ? render(item, { thread: this, author: this._author(item), own }) : null;
669
+ if (content) body.append(content);
670
+ break;
671
+ }
672
+ }
673
+ const refs = this._refs(/** @type {{refs?: unknown}} */ (item).refs);
674
+ if (refs) body.append(refs);
675
+ return entry;
676
+ }
677
+
678
+ /**
679
+ * A RunTrace the thread owns: its authors, glyphs, and clock.
680
+ * @private
681
+ * @param {import('../../internal/agent-model.js').TraceStep[]} steps
682
+ * @param {{open?: boolean, label?: string|null}} [options]
683
+ * @returns {RunTrace}
684
+ */
685
+ _trace(steps, options = {}) {
686
+ const trace = new RunTrace(null, {
687
+ steps,
688
+ open: Boolean(options.open),
689
+ label: options.label ?? null,
690
+ authors: this.options.authors,
691
+ icons: this.options.traceIcons ?? {},
692
+ ticking: true,
693
+ now: this.options.now ?? null,
694
+ formatTime: this.options.formatTime ?? null
695
+ });
696
+ // A link on a step is the item's link too: the application hears it once, from the thread.
697
+ this._contain(trace, ['open']);
698
+ trace.on('open', (event) => {
699
+ const detail = /** @type {CustomEvent<{step: any, ref: any}>} */ (event).detail;
700
+ const article = trace.toElement().closest('.zx-agent-thread__item');
701
+ const id = article instanceof HTMLElement ? article.dataset.id : null;
702
+ if (id) this.emit('open', { item: this.get(id), ref: detail.ref, step: detail.step });
703
+ });
704
+ return trace;
705
+ }
706
+
707
+ /**
708
+ * Keeps a child's bubbling `zx-<type>` events inside the thread for the types the thread
709
+ * re-emits itself, so a listener on the thread's root hears each of them once.
710
+ * @private
711
+ * @param {Component} child
712
+ * @param {string[]} types
713
+ * @returns {void}
714
+ */
715
+ _contain(child, types) {
716
+ for (const type of types) this.listen(child.toElement(), `zx-${type}`, (event) => event.stopPropagation());
717
+ }
718
+
719
+ /**
720
+ * Links from an item to the application's own things, after its content.
721
+ * @private
722
+ * @param {unknown} refs
723
+ * @returns {HTMLElement|null}
724
+ */
725
+ _refs(refs) {
726
+ const list = Array.isArray(refs) ? refs.filter((ref) => ref && ref.id != null && ref.label) : [];
727
+ if (!list.length) return null;
728
+ return h('ul', { class: 'zx-agent-thread__refs' }, list.map((ref) => h('li', {},
729
+ h('button', { type: 'button', class: 'zx-agent-thread__ref', dataset: { threadAction: 'open', threadValue: String(ref.id) } },
730
+ ref.icon ? h('span', { class: 'zx-agent-thread__ref-icon', 'aria-hidden': 'true' }, icon(String(ref.icon), { size: 14 })) : null,
731
+ h('span', {}, String(ref.label))))));
732
+ }
733
+
734
+ /**
735
+ * Edit and copy on the person's own message, shown while it is pointed at or holds focus.
736
+ * @private
737
+ * @param {Extract<ThreadItem, {type: 'user'}>} user
738
+ * @returns {HTMLElement|null}
739
+ */
740
+ _userActions(user) {
741
+ const wanted = new Set(Array.isArray(this.options.userActions) ? this.options.userActions : []);
742
+ if (!wanted.size) return null;
743
+ const icons = { ...DEFAULT_ICONS, ...(this.options.icons ?? {}) };
744
+ /** @type {Node[]} */
745
+ const controls = [];
746
+ if (wanted.has('copy')) controls.push(copyButton({ text: String(user.text ?? ''), title: this.msg('agentThread.copyMessage'), size: 'sm' }));
747
+ if (wanted.has('edit')) controls.push(actionButton(icons.edit, this.msg('agentThread.edit'), { action: 'edit' }));
748
+ return controls.length ? h('div', { class: 'zx-agent-thread__actions', 'data-zx-reveal': '' }, controls) : null;
749
+ }
750
+
751
+ /**
752
+ * @private
753
+ * @param {ThreadEntry} entry
754
+ * @param {HTMLElement} body
755
+ * @param {<T extends Component>(component: T) => T} own
756
+ * @returns {void}
757
+ */
758
+ _buildAnswer(entry, body, own) {
759
+ const answer = /** @type {Extract<ThreadItem, {type: 'answer'}>} */ (entry.item);
760
+ const version = this._version(answer);
761
+ if (version.steps.length) {
762
+ entry.trace = own(this._trace(version.steps, { open: Boolean(answer.stepsOpen) }));
763
+ body.append(entry.trace.toElement());
764
+ }
765
+ body.append(h('p', { class: 'zx-agent-thread__writing', hidden: true }, this.msg('agentThread.writingNow', this._authorName(answer))));
766
+ const view = own(new BlockView(null, {
767
+ blocks: version.blocks,
768
+ sources: version.sources,
769
+ streaming: Boolean(answer.streaming),
770
+ headingLevel: this.options.headingLevel
771
+ }));
772
+ if (version.stopped) view.stop();
773
+ for (const [artifact, state] of this._artifacts) view.setArtifactState(artifact, state);
774
+ this._contain(view, ['cite', 'artifact']);
775
+ view.on('cite', (event) => {
776
+ const detail = /** @type {CustomEvent<{n: number, source: Source|null}>} */ (event).detail;
777
+ const emitted = this.emit('cite', { item: this.get(String(answer.id)), n: detail.n, source: detail.source });
778
+ if (!emitted.defaultPrevented) entry.sources?.highlight(detail.n);
779
+ });
780
+ view.on('artifact', (event) => {
781
+ const detail = /** @type {CustomEvent<{id: string}>} */ (event).detail;
782
+ this.emit('artifact', { item: this.get(String(answer.id)), id: detail.id });
783
+ });
784
+ entry.view = view;
785
+ body.append(view.toElement());
786
+ body.append(h('div', { class: 'zx-agent-thread__footer' }));
787
+ this._redrawAnswerFooter(entry, own);
788
+ this._syncWriting(entry);
789
+ }
790
+
791
+ /**
792
+ * While an answer is on its way and nothing of it has arrived, a quiet line says who is
793
+ * writing; it goes as soon as the first words do.
794
+ * @private
795
+ * @param {ThreadEntry} entry
796
+ * @returns {void}
797
+ */
798
+ _syncWriting(entry) {
799
+ const line = /** @type {HTMLElement|null} */ (entry.article.querySelector('.zx-agent-thread__writing'));
800
+ if (!line || !entry.view) return;
801
+ line.hidden = !(/** @type {any} */ (entry.item).streaming && entry.view.toElement().childElementCount === 0);
802
+ }
803
+
804
+ /**
805
+ * Draws an answer's sources and actions, which show only once it is finished.
806
+ * @private
807
+ * @param {ThreadEntry} entry
808
+ * @param {<T extends Component>(component: T) => T} [own]
809
+ * @returns {void}
810
+ */
811
+ _redrawAnswerFooter(entry, own) {
812
+ const footer = /** @type {HTMLElement|null} */ (entry.article.querySelector('.zx-agent-thread__footer'));
813
+ if (!footer) return;
814
+ const answer = /** @type {Extract<ThreadItem, {type: 'answer'}>} */ (entry.item);
815
+ const adopt = own ?? (/** @type {<T extends Component>(component: T) => T} */ ((component) => {
816
+ entry.owned.push(component);
817
+ return component;
818
+ }));
819
+ if (entry.sources) {
820
+ entry.owned = entry.owned.filter((component) => component !== entry.sources);
821
+ entry.sources.destroy();
822
+ entry.sources = null;
823
+ }
824
+ footer.replaceChildren();
825
+ if (answer.streaming) return;
826
+ const sources = this._version(answer).sources;
827
+ if (sources.length) {
828
+ const list = adopt(new SourceList(null, { sources, label: this.msg('agentThread.sources'), icons: this.options.sourceIcons ?? {} }));
829
+ list.on('select', (event) => {
830
+ const source = /** @type {CustomEvent<{source: Source}>} */ (event).detail.source;
831
+ if (source?.call) {
832
+ event.preventDefault();
833
+ this.reveal(`step:${source.call}`);
834
+ }
835
+ });
836
+ entry.sources = list;
837
+ footer.append(list.toElement());
838
+ }
839
+ const actions = this._answerActions(entry);
840
+ if (actions) footer.append(actions);
841
+ }
842
+
843
+ /**
844
+ * @private
845
+ * @param {ThreadEntry} entry
846
+ * @returns {HTMLElement|null}
847
+ */
848
+ _answerActions(entry) {
849
+ const answer = /** @type {Extract<ThreadItem, {type: 'answer'}>} */ (entry.item);
850
+ const wanted = new Set(Array.isArray(this.options.answerActions) ? this.options.answerActions : []);
851
+ const icons = { ...DEFAULT_ICONS, ...(this.options.icons ?? {}) };
852
+ const id = String(answer.id);
853
+ /** @type {Array<Node>} */
854
+ const controls = [];
855
+ const versions = Array.isArray(answer.versions) ? answer.versions : [];
856
+ if (versions.length > 1) {
857
+ const index = this._versionIndex(answer);
858
+ controls.push(h('span', { class: 'zx-agent-thread__pager' },
859
+ actionButton('chevron-left', this.msg('agentThread.previousVersion'), { action: 'version', value: String(index - 1), dir: 'previous' }, index === 0),
860
+ h('span', { class: 'zx-agent-thread__pager-text' }, `${index + 1} / ${versions.length}`,
861
+ h('span', { class: 'zx-agent-thread__sr' }, ` ${this.msg('agentThread.version', index + 1, versions.length)}`)),
862
+ actionButton('chevron-right', this.msg('agentThread.nextVersion'), { action: 'version', value: String(index + 1), dir: 'next' }, index === versions.length - 1)));
863
+ }
864
+ if (wanted.has('copy')) {
865
+ controls.push(copyButton({ text: () => entry.view?.toMarkdown() ?? '', title: this.msg('agentThread.copy'), size: 'sm' }));
866
+ }
867
+ if (wanted.has('regenerate') && this._latestAnswerId() === id) {
868
+ controls.push(actionButton(icons.regenerate, this.msg('agentThread.regenerate'), { action: 'regenerate' }));
869
+ }
870
+ if (wanted.has('branch')) controls.push(actionButton(icons.branch, this.msg('agentThread.branch'), { action: 'branch' }));
871
+ if (wanted.has('rate')) {
872
+ for (const [value, glyph, key] of [['up', icons.rateUp, 'agentThread.rateUp'], ['down', icons.rateDown, 'agentThread.rateDown']]) {
873
+ const control = actionButton(glyph, this.msg(key), { action: 'rate', value });
874
+ control.setAttribute('aria-pressed', String(this._version(answer).rating === value));
875
+ controls.push(control);
876
+ }
877
+ }
878
+ return controls.length ? h('div', { class: 'zx-agent-thread__actions' }, controls) : null;
879
+ }
880
+
881
+ /**
882
+ * @private
883
+ * @param {ThreadEntry} entry
884
+ * @param {HTMLElement} body
885
+ * @param {<T extends Component>(component: T) => T} own
886
+ * @returns {void}
887
+ */
888
+ _buildApproval(entry, body, own) {
889
+ const approval = /** @type {Extract<ThreadItem, {type: 'approval'}>} */ (entry.item);
890
+ const card = own(new ApprovalCard(null, {
891
+ title: approval.title,
892
+ description: approval.description,
893
+ icon: approval.icon ?? null,
894
+ tone: /** @type {any} */ (approval.tone ?? 'blue'),
895
+ status: approval.status ?? 'pending',
896
+ details: approval.details ?? null,
897
+ preview: approval.preview ? { label: approval.preview.label, content: approval.preview.blocks } : null,
898
+ fields: approval.fields ?? null,
899
+ values: approval.values ?? {},
900
+ confirmText: approval.confirmText ?? null,
901
+ reason: approval.reason ?? 'optional',
902
+ edited: Boolean(approval.edited),
903
+ editedKeys: Array.isArray(approval.editedKeys) ? approval.editedKeys : null,
904
+ rejectReason: approval.rejectReason ?? null,
905
+ now: this.options.now ?? null,
906
+ answeredBy: approval.answeredBy ?? null,
907
+ answeredAt: approval.answeredAt ?? null,
908
+ headingLevel: this.options.headingLevel
909
+ }));
910
+ this._contain(card, ['approve', 'edit', 'reject']);
911
+ for (const type of ['approve', 'edit', 'reject']) {
912
+ card.on(type, (event) => {
913
+ const detail = /** @type {CustomEvent<Record<string, any>>} */ (event).detail;
914
+ const emitted = this.emit(type, { item: this.get(String(approval.id)), ...detail });
915
+ if (emitted.defaultPrevented) {
916
+ event.preventDefault();
917
+ return;
918
+ }
919
+ // The item follows the card, so get() and a later redraw keep what was decided.
920
+ const at = (this.options.now?.() ?? new Date()).toISOString();
921
+ // The card keeps which values were edited across saves; the item stores its answer.
922
+ if (type === 'edit') {
923
+ entry.item = /** @type {ThreadItem} */ ({ ...entry.item, values: detail.values, edited: true, editedKeys: detail.editedKeys ?? null });
924
+ }
925
+ else if (type === 'approve') entry.item = /** @type {ThreadItem} */ ({ ...entry.item, status: 'approved', values: detail.values, answeredAt: at });
926
+ else entry.item = /** @type {ThreadItem} */ ({ ...entry.item, status: 'rejected', rejectReason: detail.reason || null, answeredAt: at });
927
+ });
928
+ }
929
+ entry.card = card;
930
+ body.append(card.toElement());
931
+ }
932
+
933
+ /**
934
+ * The author's avatar, beside the byline and the content. Decorative: the byline names them.
935
+ * @private
936
+ * @param {ThreadItem} item
937
+ * @param {<T extends Component>(component: T) => T} own
938
+ * @returns {HTMLElement|null}
939
+ */
940
+ _avatar(item, own) {
941
+ const author = this._author(item);
942
+ if (!author) return null;
943
+ if (author.icon) {
944
+ return h('span', { class: 'zx-agent-thread__avatar' },
945
+ h('span', { class: 'zx-agent-thread__mark', dataset: { tone: author.tone ?? null, kind: author.kind ?? 'agent' }, 'aria-hidden': 'true' },
946
+ icon(String(author.icon), { size: 14 })));
947
+ }
948
+ const avatar = own(new Avatar(null, {
949
+ name: author.name, initials: author.initials ?? initialsOf(author.name), tone: /** @type {any} */ (author.tone ?? null),
950
+ size: 'sm', shape: author.kind === 'person' ? 'circle' : 'rounded', activity: author.activity ?? null
951
+ }));
952
+ return h('span', { class: 'zx-agent-thread__avatar' }, avatar.toElement());
953
+ }
954
+
955
+ /**
956
+ * @private
957
+ * @param {ThreadItem} item
958
+ * @param {string} id
959
+ * @returns {HTMLElement}
960
+ */
961
+ _byline(item, id) {
962
+ const author = this._author(item);
963
+ const name = this._authorName(item);
964
+ const shown = item.type === 'answer' ? this._version(/** @type {any} */ (item)) : null;
965
+ const at = shown ? shown.at : item.at;
966
+ const time = this._time(at);
967
+ const byline = h('div', { class: 'zx-agent-thread__byline' });
968
+ byline.append(h('span', { class: 'zx-agent-thread__author', id }, name,
969
+ time ? h('span', { class: 'zx-agent-thread__sr' }, `, ${time}`) : null));
970
+ if (author?.via) byline.append(h('span', { class: 'zx-agent-thread__via' }, this.msg('agentThread.via', author.via)));
971
+ if (time) byline.append(h('time', { class: 'zx-agent-thread__time', dateTime: String(at), 'aria-hidden': 'true' }, time));
972
+ if (shown?.stopped) {
973
+ byline.append(h('span', { class: 'zx-agent-thread__flag' }, this.msg('agentThread.stopped')));
974
+ }
975
+ return byline;
976
+ }
977
+
978
+ /**
979
+ * @private
980
+ * @param {Array<{name: string, size?: number}>} files
981
+ * @returns {HTMLElement}
982
+ */
983
+ _files(files) {
984
+ return h('ul', { class: 'zx-agent-thread__files', 'aria-label': this.msg('agentThread.attachments') },
985
+ files.map((file) => h('li', { class: 'zx-agent-thread__file' },
986
+ h('span', { class: 'zx-agent-thread__file-icon', 'aria-hidden': 'true' }, icon('file', { size: 14 })),
987
+ h('span', { class: 'zx-agent-thread__file-name' }, String(file.name ?? '')),
988
+ typeof file.size === 'number' ? h('span', { class: 'zx-agent-thread__file-size' }, formatFileSize(file.size, { decimals: 0, standard: 'si' })) : null)));
989
+ }
990
+
991
+ /* ------------------------------------------------------------------ helpers -- */
992
+
993
+ /** @private @param {ThreadItem} item @returns {boolean} */
994
+ _isMine(item) {
995
+ return item.author ? item.author === this.options.me : item.type === 'user';
996
+ }
997
+
998
+ /** @private @param {ThreadItem} item @returns {Author|null} */
999
+ _author(item) {
1000
+ const authors = this.options.authors ?? {};
1001
+ if (item.author && Object.hasOwn(authors, item.author)) return authors[item.author];
1002
+ if (this._isMine(item)) return Object.hasOwn(authors, this.options.me) ? authors[this.options.me] : null;
1003
+ const first = Object.entries(authors).find(([key, author]) => key !== this.options.me && author.kind !== 'person');
1004
+ return first ? first[1] : null;
1005
+ }
1006
+
1007
+ /** @private @param {ThreadItem} item @returns {string} */
1008
+ _authorName(item) {
1009
+ if (this._isMine(item)) return this.msg('agentThread.you');
1010
+ return this._author(item)?.name ?? this.msg('agentThread.agent');
1011
+ }
1012
+
1013
+ /** @private @param {unknown} at @returns {string} */
1014
+ _time(at) {
1015
+ if (typeof at !== 'string' || !at) return '';
1016
+ if (typeof this.options.formatTime === 'function') return String(this.options.formatTime(at) ?? '');
1017
+ const date = new Date(at);
1018
+ if (Number.isNaN(date.getTime())) return '';
1019
+ return new Intl.DateTimeFormat(this.options.locale, { hour: '2-digit', minute: '2-digit' }).format(date);
1020
+ }
1021
+
1022
+ /** @private @param {Extract<ThreadItem, {type: 'answer'}>} answer @returns {number} */
1023
+ _versionIndex(answer) {
1024
+ const versions = Array.isArray(answer.versions) ? answer.versions : [];
1025
+ const index = Number.isInteger(answer.version) ? Number(answer.version) : versions.length - 1;
1026
+ return Math.max(0, Math.min(versions.length - 1, index));
1027
+ }
1028
+
1029
+ /**
1030
+ * The blocks, sources, and steps an answer shows: its chosen version's when it has several.
1031
+ * @private
1032
+ * @param {Extract<ThreadItem, {type: 'answer'}>} answer
1033
+ * @returns {{blocks: Block[], sources: Source[], steps: import('../../internal/agent-model.js').TraceStep[],
1034
+ * stopped: boolean, rating: 'up'|'down'|null, at: string|undefined}}
1035
+ */
1036
+ _version(answer) {
1037
+ const versions = Array.isArray(answer.versions) ? answer.versions : [];
1038
+ const version = versions.length > 1 ? versions[this._versionIndex(answer)] : null;
1039
+ if (version) {
1040
+ return {
1041
+ blocks: version.blocks ?? [], sources: version.sources ?? [], steps: version.steps ?? answer.steps ?? [],
1042
+ stopped: version.stopped ?? Boolean(answer.stopped), rating: version.rating !== undefined ? version.rating : answer.rating ?? null,
1043
+ at: version.at ?? answer.at
1044
+ };
1045
+ }
1046
+ return {
1047
+ blocks: answer.blocks ?? [], sources: answer.sources ?? [], steps: answer.steps ?? [],
1048
+ stopped: Boolean(answer.stopped), rating: answer.rating ?? null, at: answer.at
1049
+ };
1050
+ }
1051
+
1052
+ /**
1053
+ * A consecutive item by the same author reads as one turn: its byline is still there for a
1054
+ * screen reader, but not drawn again.
1055
+ * @private
1056
+ * @param {string} id
1057
+ * @returns {void}
1058
+ */
1059
+ _syncContinuation(id) {
1060
+ const index = this._order.indexOf(id);
1061
+ for (const at of [index, index + 1]) {
1062
+ const entry = this._entries.get(this._order[at]);
1063
+ const previous = this._entries.get(this._order[at - 1]);
1064
+ if (!entry) continue;
1065
+ // A notice belongs to no one, so it ends a turn on either side of it.
1066
+ const same = Boolean(previous) && !this._isMine(entry.item) && !this._isMine(/** @type {ThreadEntry} */ (previous).item)
1067
+ && entry.item.type !== 'notice' && /** @type {ThreadEntry} */ (previous).item.type !== 'notice'
1068
+ && this._authorName(entry.item) === this._authorName(/** @type {ThreadEntry} */ (previous).item);
1069
+ if (same) entry.article.dataset.continued = 'true';
1070
+ else delete entry.article.dataset.continued;
1071
+ }
1072
+ }
1073
+
1074
+ /** @private @returns {void} */
1075
+ _syncPositions() {
1076
+ const size = String(this._order.length);
1077
+ this._order.forEach((id, index) => {
1078
+ const article = this._entries.get(id)?.article;
1079
+ if (!article) return;
1080
+ article.setAttribute('aria-posinset', String(index + 1));
1081
+ article.setAttribute('aria-setsize', size);
1082
+ });
1083
+ const streaming = this._order.some((id) => {
1084
+ const item = this._entries.get(id)?.item;
1085
+ return item?.type === 'answer' && Boolean(/** @type {any} */ (item).streaming);
1086
+ });
1087
+ this._feed.setAttribute('aria-busy', String(streaming));
1088
+ }
1089
+
1090
+ /** @private @returns {void} */
1091
+ _syncEmpty() {
1092
+ const empty = this._order.length === 0 && this.options.emptyState;
1093
+ this._empty.hidden = !empty;
1094
+ if (empty && !this._empty.firstChild) this._empty.append(emptyState(/** @type {EmptyStateOptions} */ (this.options.emptyState)));
1095
+ if (!empty) this._empty.replaceChildren();
1096
+ }
1097
+
1098
+ /** @private @param {ThreadItem} item @returns {void} */
1099
+ _announceItem(item) {
1100
+ const name = this._authorName(item);
1101
+ if (item.type === 'answer') {
1102
+ this._announce(this.msg(/** @type {any} */ (item).streaming ? 'agentThread.writing' : 'agentThread.answered', name));
1103
+ } else if (item.type === 'approval' && (/** @type {any} */ (item).status ?? 'pending') === 'pending') {
1104
+ this._announce(this.msg('agentThread.needsApproval', name));
1105
+ } else if (item.type === 'trace') {
1106
+ this._announce(this.msg('agentThread.working', name));
1107
+ } else if (item.type === 'notice' && ['warning', 'danger'].includes(String(/** @type {any} */ (item).tone))) {
1108
+ this._announce(String(/** @type {any} */ (item).text ?? ''));
1109
+ }
1110
+ }
1111
+
1112
+ /**
1113
+ * Says a milestone once. The region is cleared first so the same words said twice are heard
1114
+ * twice.
1115
+ * @private
1116
+ * @param {string} text
1117
+ * @returns {void}
1118
+ */
1119
+ _announce(text) {
1120
+ clearTimeout(this._announceTimer);
1121
+ this._status.textContent = '';
1122
+ this._announceTimer = window.setTimeout(() => {
1123
+ this._status.textContent = text;
1124
+ }, 60);
1125
+ }
1126
+
1127
+ /** @private @returns {Element|null} */
1128
+ _scroller() {
1129
+ if (this.options.scroller) return this.options.scroller;
1130
+ if (this._scrollHost?.isConnected) return this._scrollHost;
1131
+ /** @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;
1137
+ }
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 });
1144
+ }
1145
+ return this._scrollHost;
1146
+ }
1147
+
1148
+ /** @private @returns {boolean} */
1149
+ _atEnd() {
1150
+ const scroller = this._scroller();
1151
+ if (!scroller) return true;
1152
+ return scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight <= END_SLACK;
1153
+ }
1154
+
1155
+ /**
1156
+ * Runs a change and keeps the end in view if the reader was reading it.
1157
+ * @private
1158
+ * @param {() => void} change
1159
+ * @returns {void}
1160
+ */
1161
+ _follow(change) {
1162
+ const follow = this.options.followOutput && this.el.isConnected && this._atEnd();
1163
+ change();
1164
+ if (!this.options.followOutput || !this.el.isConnected) return;
1165
+ if (follow) this.scrollToEnd();
1166
+ else if (!this._atEnd()) this._latestButton.hidden = false;
1167
+ }
1168
+
1169
+ /** @private @returns {HTMLElement|null} */
1170
+ _lastArticle() {
1171
+ const id = this._order.at(-1);
1172
+ return id ? this._entries.get(id)?.article ?? null : null;
1173
+ }
1174
+
1175
+ /* ------------------------------------------------------------------ events -- */
1176
+
1177
+ /** @private @param {MouseEvent} event @returns {void} */
1178
+ _onClick(event) {
1179
+ const target = event.target instanceof Element ? event.target.closest('[data-thread-action]') : null;
1180
+ if (!target || !this.el.contains(target)) return;
1181
+ const article = target.closest('.zx-agent-thread__item');
1182
+ const id = article instanceof HTMLElement ? article.dataset.id : null;
1183
+ const entry = id ? this._entries.get(id) : null;
1184
+ if (!entry) return;
1185
+ const action = String(/** @type {HTMLElement} */ (target).dataset.threadAction);
1186
+ const raw = /** @type {HTMLElement} */ (target).dataset.threadValue;
1187
+ if (action === 'version') {
1188
+ const value = Number(raw);
1189
+ const dir = /** @type {HTMLElement} */ (target).dataset.threadDir;
1190
+ const emitted = this.emit('action', { item: this.get(String(id)), action, value });
1191
+ if (!emitted.defaultPrevented) {
1192
+ this._replace(String(id), /** @type {ThreadItem} */ ({ ...entry.item, version: value }));
1193
+ // Paging keeps focus on the pager: the same arrow, or the other one at either end.
1194
+ const pager = this._entries.get(String(id))?.article.querySelectorAll('[data-thread-action="version"]');
1195
+ const buttons = /** @type {HTMLButtonElement[]} */ ([...(pager ?? [])]);
1196
+ const same = buttons.find((button) => button.dataset.threadDir === dir && !button.disabled);
1197
+ (same ?? buttons.find((button) => !button.disabled))?.focus();
1198
+ }
1199
+ return;
1200
+ }
1201
+ if (action === 'open') {
1202
+ const ref = (/** @type {any} */ (entry.item).refs ?? []).find((/** @type {any} */ candidate) => String(candidate?.id) === raw);
1203
+ if (ref) this.emit('open', { item: this.get(String(id)), ref: { ...ref } });
1204
+ return;
1205
+ }
1206
+ if (action === 'notice') {
1207
+ this.emit('action', { item: this.get(String(id)), action: String(raw) });
1208
+ return;
1209
+ }
1210
+ if (action === 'rate') {
1211
+ const answer = /** @type {Extract<ThreadItem, {type: 'answer'}>} */ (entry.item);
1212
+ const current = this._version(answer).rating;
1213
+ const value = current === raw ? null : raw;
1214
+ const emitted = this.emit('action', { item: this.get(String(id)), action, value });
1215
+ if (!emitted.defaultPrevented) {
1216
+ // With versions, a rating belongs to the version shown.
1217
+ const versions = Array.isArray(answer.versions) && answer.versions.length > 1
1218
+ ? answer.versions.map((version, index) => (index === this._versionIndex(answer) ? { ...version, rating: /** @type {any} */ (value) } : version))
1219
+ : answer.versions;
1220
+ entry.item = /** @type {ThreadItem} */ ({ ...entry.item, rating: value, versions });
1221
+ for (const control of entry.article.querySelectorAll('[data-thread-action="rate"]')) {
1222
+ control.setAttribute('aria-pressed', String(/** @type {HTMLElement} */ (control).dataset.threadValue === value));
1223
+ }
1224
+ }
1225
+ return;
1226
+ }
1227
+ this.emit('action', { item: this.get(String(id)), action });
1228
+ }
1229
+
1230
+ /**
1231
+ * 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.
1233
+ * @private
1234
+ * @param {KeyboardEvent} event
1235
+ * @returns {void}
1236
+ */
1237
+ _onFeedKey(event) {
1238
+ const article = event.target instanceof Element ? event.target.closest('.zx-agent-thread__item') : null;
1239
+ if (!(article instanceof HTMLElement)) return;
1240
+ const articles = this._order.map((id) => this._entries.get(id)?.article).filter(Boolean);
1241
+ const index = articles.indexOf(article);
1242
+ if (event.key === 'PageDown' || event.key === 'PageUp') {
1243
+ const next = articles[index + (event.key === 'PageDown' ? 1 : -1)];
1244
+ if (next) {
1245
+ event.preventDefault();
1246
+ next.focus();
1247
+ }
1248
+ } else if ((event.ctrlKey || event.metaKey) && (event.key === 'End' || event.key === 'Home')) {
1249
+ const outside = focusableOutside(this._feed, event.key === 'End' ? 1 : -1);
1250
+ if (outside) {
1251
+ event.preventDefault();
1252
+ outside.focus();
1253
+ }
1254
+ }
1255
+ }
1256
+ }
1257
+
1258
+ /** Item types the thread draws itself. */
1259
+ const BUILT_IN = new Set(['user', 'text', 'answer', 'trace', 'approval', 'notice']);
1260
+
1261
+ /**
1262
+ * An icon button the thread's delegated click listener acts on.
1263
+ * @param {string} glyph
1264
+ * @param {string} label
1265
+ * @param {{action: string, value?: string, dir?: string}} data
1266
+ * @param {boolean} [disabled]
1267
+ * @returns {HTMLButtonElement}
1268
+ */
1269
+ function actionButton(glyph, label, data, disabled = false) {
1270
+ return /** @type {HTMLButtonElement} */ (h('button', {
1271
+ type: 'button', class: 'zx-icon-btn zx-agent-thread__action', title: label, 'aria-label': label, disabled,
1272
+ dataset: { size: 'sm', threadAction: data.action, threadValue: data.value ?? null, threadDir: data.dir ?? null }
1273
+ }, icon(glyph, { size: 14 })));
1274
+ }
1275
+
1276
+ /**
1277
+ * The person's text with each `@name` it mentions marked, as text nodes and spans.
1278
+ * @param {string} text
1279
+ * @param {unknown} mentions Names without the `@`, or `{name, tone}` to colour a name in its tone.
1280
+ * @returns {Array<Node|string>}
1281
+ */
1282
+ function withMentions(text, mentions) {
1283
+ /** @type {Map<string, string|null>} Each mentioned name and its tone. */
1284
+ const tones = new Map();
1285
+ for (const mention of Array.isArray(mentions) ? mentions : []) {
1286
+ const name = String(typeof mention === 'object' && mention ? mention.name ?? '' : mention ?? '').trim();
1287
+ if (name) tones.set(name, typeof mention === 'object' && mention?.tone ? String(mention.tone) : null);
1288
+ }
1289
+ const names = [...tones.keys()];
1290
+ if (!names.length) return [text];
1291
+ const escaped = names.sort((a, b) => b.length - a.length).map((name) => escapeRegExp(name));
1292
+ const pattern = new RegExp(`@(?:${escaped.join('|')})(?![\\w])`, 'g');
1293
+ /** @type {Array<Node|string>} */
1294
+ const out = [];
1295
+ let from = 0;
1296
+ for (const match of text.matchAll(pattern)) {
1297
+ const at = Number(match.index);
1298
+ if (at > from) out.push(text.slice(from, at));
1299
+ out.push(h('span', { class: 'zx-agent-thread__mention', dataset: { tone: tones.get(match[0].slice(1)) ?? null } }, match[0]));
1300
+ from = at + match[0].length;
1301
+ }
1302
+ if (from < text.length) out.push(text.slice(from));
1303
+ return out;
1304
+ }
1305
+
1306
+ /** Elements that take focus from the keyboard. */
1307
+ const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), '
1308
+ + 'textarea:not([disabled]), [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';
1309
+
1310
+ /**
1311
+ * The first focusable element after (`1`) or before (`-1`) an element in document order.
1312
+ * @param {Element} element
1313
+ * @param {1|-1} direction
1314
+ * @returns {HTMLElement|null}
1315
+ */
1316
+ function focusableOutside(element, direction) {
1317
+ const all = /** @type {HTMLElement[]} */ ([...document.querySelectorAll(FOCUSABLE)])
1318
+ .filter((candidate) => !element.contains(candidate) && candidate.getClientRects().length > 0);
1319
+ const position = (/** @type {HTMLElement} */ candidate) => element.compareDocumentPosition(candidate);
1320
+ if (direction === 1) return all.find((candidate) => position(candidate) & Node.DOCUMENT_POSITION_FOLLOWING) ?? null;
1321
+ return all.reverse().find((candidate) => position(candidate) & Node.DOCUMENT_POSITION_PRECEDING) ?? null;
1322
+ }
1323
+
1324
+ /**
1325
+ * Action payload: under an answer `copy`, `regenerate`, `branch`, `rate` (`value` up, down, or
1326
+ * null), or `version` (`value` the version index; preventable, like `rate`); on the person's own
1327
+ * message `edit` (copying needs no event); on a notice, the id of its `action`.
1328
+ * @event AgentThread#action
1329
+ * @type {CustomEvent<{item: ThreadItem, action: string, value?: unknown}>}
1330
+ */
1331
+ /**
1332
+ * An approval was approved; preventable, which keeps the card pending.
1333
+ * @event AgentThread#approve
1334
+ * @type {CustomEvent<{item: ThreadItem, values: Record<string, unknown>}>}
1335
+ */
1336
+ /**
1337
+ * An approval's values were edited; preventable.
1338
+ * @event AgentThread#edit
1339
+ * @type {CustomEvent<{item: ThreadItem, values: Record<string, unknown>}>}
1340
+ */
1341
+ /**
1342
+ * An approval was rejected; preventable, which keeps the card pending.
1343
+ * @event AgentThread#reject
1344
+ * @type {CustomEvent<{item: ThreadItem, reason: string}>}
1345
+ */
1346
+ /**
1347
+ * A citation was activated; preventable, which skips highlighting the source.
1348
+ * @event AgentThread#cite
1349
+ * @type {CustomEvent<{item: ThreadItem, n: number, source: Source|null}>}
1350
+ */
1351
+ /**
1352
+ * An artifact card was activated.
1353
+ * @event AgentThread#artifact
1354
+ * @type {CustomEvent<{item: ThreadItem, id: string}>}
1355
+ */
1356
+ /**
1357
+ * Something was brought into view by `reveal()`.
1358
+ * @event AgentThread#reveal
1359
+ * @type {CustomEvent<{target: string}>}
1360
+ */
1361
+ /**
1362
+ * A link was activated: one of an item's `refs`, or of a trace step's (then `step` names it).
1363
+ * @event AgentThread#open
1364
+ * @type {CustomEvent<{item: ThreadItem, ref: import('../../internal/agent-model.js').ItemRef, step?: import('../../internal/agent-model.js').TraceStep}>}
1365
+ */