@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,488 @@
1
+ // @ts-check
2
+ /**
3
+ * The agent data model every agent component reads: a conversation thread as a list of plain JSON
4
+ * items, the blocks an answer is made of, the steps a run took, the sources it cites, and the one
5
+ * mapping from a run or agent state to the glyph, tone, and word that show it.
6
+ *
7
+ * The model holds no functions and no DOM nodes, so an agent can produce it directly and an
8
+ * application can store, send, and replay it. Behaviour comes in through component options and
9
+ * events, never through the model.
10
+ */
11
+ import { formatNumber } from '../core/format.js';
12
+
13
+ /**
14
+ * Where a run, or one step of it, stands.
15
+ * @typedef {'queued'|'running'|'waiting'|'paused'|'blocked'|'done'|'failed'|'stopped'|'skipped'} RunState
16
+ */
17
+
18
+ /**
19
+ * What an agent is doing, shown beside its avatar.
20
+ * @typedef {'idle'|'thinking'|'working'|'needs-you'|'blocked'|'offline'} AgentActivity
21
+ */
22
+
23
+ /**
24
+ * A row of figures: what it is, a muted detail, and the value. The tuple form is shorthand for the
25
+ * object form; `call` names the trace step the value came from.
26
+ * @typedef {[string, string, string]|{label: string, detail?: string, value: string, call?: string}} FigureRow
27
+ */
28
+
29
+ /**
30
+ * One block of an answer. Text runs use the inline grammar of `parseInline()`; nothing in a block
31
+ * is ever read as HTML.
32
+ * @typedef {{type: 'p', text: string}
33
+ * | {type: 'quote', text: string}
34
+ * | {type: 'heading', level?: 2|3, text: string}
35
+ * | {type: 'list', ordered?: boolean, items: string[]}
36
+ * | {type: 'code', language?: string, code: string, lines?: boolean}
37
+ * | {type: 'table', columns: string[], rows: string[][], align?: Array<'start'|'center'|'end'|null>}
38
+ * | {type: 'figures', rows: FigureRow[]}
39
+ * | {type: 'callout', tone?: 'info'|'success'|'warning'|'danger', title?: string, text: string}
40
+ * | {type: 'artifact', id: string, title: string, kind?: 'document'|'code', versions?: number}} Block
41
+ */
42
+
43
+ /**
44
+ * A source an answer draws on. `web` sources may carry an `href`; a `record` names an application
45
+ * record; a `call` names the trace step it came from.
46
+ * @typedef {Object} Source
47
+ * @property {string} id Stable identity.
48
+ * @property {string} title Full title, shown in the source card.
49
+ * @property {'web'|'file'|'record'|'call'} [kind='web'] What the source is.
50
+ * @property {string} [site] Short name shown on the chip: a host, a file name, a record type.
51
+ * @property {string} [snippet] The passage the answer used.
52
+ * @property {string} [href] Address of a `web` source.
53
+ * @property {{entity: string, id: string}} [ref] The application record a `record` source names.
54
+ * @property {string} [call] The trace step the source came from.
55
+ */
56
+
57
+ /**
58
+ * A link from an item or a step to something of the application's own — a task, a file, a
59
+ * record. The application resolves it; the components only draw the label and report the click.
60
+ * @typedef {Object} ItemRef
61
+ * @property {string} id Stable identity, handed back on activation.
62
+ * @property {string} label What the link says.
63
+ * @property {string} [icon] Glyph name.
64
+ * @property {string} [entity] What kind of thing it is, for the application: `task`, `file`, …
65
+ */
66
+
67
+ /**
68
+ * One thing an agent did during a run.
69
+ * @typedef {Object} TraceStep
70
+ * @property {string} id Stable identity.
71
+ * @property {'search'|'read'|'query'|'write'|'run'|'call'|'handoff'|'think'|'task'|'ask'|'decision'} [kind='call']
72
+ * What kind of step it is; sets the glyph and how the summary counts it. `task` is a planned step,
73
+ * `ask` a request a person made, `decision` a person's answer; with `think` and `handoff` they are
74
+ * not tool calls.
75
+ * @property {string} label What was done, in the past tense: "Read the dunning policy".
76
+ * @property {RunState} [status='done'] Where the step stands.
77
+ * @property {string} [doing] The present-tense line shown while it runs: "Reading the policy".
78
+ * @property {string} [detail] A muted detail.
79
+ * @property {number} [ms] How long it took.
80
+ * @property {string} [count] A short result count: "42 rows".
81
+ * @property {number} [sources] How many sources a search looked at.
82
+ * @property {string} [tool] The tool's name, shown in mono.
83
+ * @property {string} [args] The call's arguments, JSON or text.
84
+ * @property {string} [result] What the call returned.
85
+ * @property {string} [error] Why the call failed.
86
+ * @property {string} [retryOf] The id of the step this one repeats.
87
+ * @property {string} [actor] Author key of whoever took the step.
88
+ * @property {string} [to] Author key a `handoff` hands over to.
89
+ * @property {string} [at] Local ISO date-time it started; a running step's clock counts from it.
90
+ * @property {number} [tokens] Tokens the step used.
91
+ * @property {ItemRef[]} [refs] Links to what the step touched — a file it wrote, a record it read.
92
+ */
93
+
94
+ /**
95
+ * Who wrote an item or took a step.
96
+ * @typedef {Object} Author
97
+ * @property {string} name Display name.
98
+ * @property {'person'|'agent'|'model'} [kind='agent'] What the author is.
99
+ * @property {string} [initials] Avatar initials; derived from the name when absent.
100
+ * @property {string} [tone] Categorical avatar tone.
101
+ * @property {AgentActivity|null} [activity] What an agent is doing now.
102
+ * @property {string} [via] The model an agent answers through, shown in the byline.
103
+ * @property {string} [icon] A glyph drawn in a tinted tile instead of initials — a model's mark.
104
+ */
105
+
106
+ /** @typedef {{name: string, size?: number, type?: string}} Attachment */
107
+
108
+ /**
109
+ * One version of a regenerated answer.
110
+ * @typedef {{blocks: Block[], sources?: Source[], steps?: TraceStep[], at?: string, model?: string,
111
+ * stopped?: boolean, rating?: 'up'|'down'|null}} AnswerVersion
112
+ */
113
+
114
+ /**
115
+ * One item in a conversation thread.
116
+ * `refs` on any item draws links to the application's own things after its content; `mentions` on a
117
+ * person's message marks each `@name` in the text; an answer's `steps` show the work it did inline,
118
+ * above its text, and change with its version.
119
+ * @typedef {{id: string, type: 'user', at?: string, author?: string, text: string, files?: Attachment[],
120
+ * mentions?: Array<string|{name: string, tone?: string}>, refs?: ItemRef[]}
121
+ * | {id: string, type: 'text', at?: string, author?: string, text: string, refs?: ItemRef[]}
122
+ * | {id: string, type: 'answer', at?: string, author?: string, blocks: Block[], sources?: Source[],
123
+ * steps?: TraceStep[], stepsOpen?: boolean, streaming?: boolean, stopped?: boolean, versions?: AnswerVersion[],
124
+ * version?: number, rating?: 'up'|'down'|null, refs?: ItemRef[]}
125
+ * | {id: string, type: 'trace', at?: string, author?: string, steps: TraceStep[], open?: boolean,
126
+ * title?: string, refs?: ItemRef[]}
127
+ * | {id: string, type: 'approval', at?: string, author?: string, title: string, description?: string,
128
+ * icon?: string|null, tone?: string,
129
+ * status?: 'pending'|'approved'|'rejected'|'expired', details?: Block[],
130
+ * preview?: {label: string, blocks: Block[]}, fields?: Record<string, Record<string, unknown>>,
131
+ * values?: Record<string, unknown>, confirmText?: string|null, reason?: 'optional'|'required'|'none',
132
+ * edited?: boolean, editedKeys?: string[]|null, rejectReason?: string|null, answeredBy?: string,
133
+ * answeredAt?: string}
134
+ * | {id: string, type: 'notice', at?: string, author?: string, text: string,
135
+ * tone?: 'neutral'|'info'|'success'|'warning'|'danger', action?: {id: string, label: string}}
136
+ * | {id: string, type: string, at?: string, author?: string, [key: string]: unknown}} ThreadItem
137
+ */
138
+
139
+ /** @typedef {'neutral'|'info'|'success'|'warning'|'danger'|'muted'} StateTone */
140
+ /** @typedef {{status: string, tone: StateTone, key: string}} StateEntry */
141
+
142
+ /**
143
+ * How each run or step state is drawn: the `statusIcon()` status, its tone, and the message key of
144
+ * the word beside it. A state is always a glyph and a word; its colour never stands alone.
145
+ * @type {Readonly<Record<RunState, StateEntry>>}
146
+ */
147
+ export const STATUS = Object.freeze({
148
+ queued: { status: 'todo', tone: 'neutral', key: 'agent.status.queued' },
149
+ running: { status: 'in-progress', tone: 'info', key: 'agent.status.running' },
150
+ waiting: { status: 'waiting', tone: 'warning', key: 'agent.status.waiting' },
151
+ paused: { status: 'in-progress', tone: 'muted', key: 'agent.status.paused' },
152
+ blocked: { status: 'waiting', tone: 'danger', key: 'agent.status.blocked' },
153
+ done: { status: 'done', tone: 'success', key: 'agent.status.done' },
154
+ failed: { status: 'canceled', tone: 'danger', key: 'agent.status.failed' },
155
+ stopped: { status: 'canceled', tone: 'muted', key: 'agent.status.stopped' },
156
+ skipped: { status: 'canceled', tone: 'muted', key: 'agent.status.skipped' }
157
+ });
158
+
159
+ /**
160
+ * How each agent activity is drawn beside an avatar: the tone of its dot and the message key of
161
+ * its word.
162
+ * @type {Readonly<Record<AgentActivity, {tone: StateTone, key: string}>>}
163
+ */
164
+ export const ACTIVITY = Object.freeze({
165
+ 'needs-you': { tone: 'warning', key: 'agent.activity.needsYou' },
166
+ blocked: { tone: 'danger', key: 'agent.activity.blocked' },
167
+ working: { tone: 'success', key: 'agent.activity.working' },
168
+ thinking: { tone: 'info', key: 'agent.activity.thinking' },
169
+ idle: { tone: 'neutral', key: 'agent.activity.idle' },
170
+ offline: { tone: 'muted', key: 'agent.activity.offline' }
171
+ });
172
+
173
+ /**
174
+ * The English words for `STATUS` and `ACTIVITY`, for a component's `msg` defaults.
175
+ * @type {Readonly<Record<string, string>>}
176
+ */
177
+ export const AGENT_MESSAGES = Object.freeze({
178
+ 'agent.status.queued': 'Not started',
179
+ 'agent.status.running': 'Running',
180
+ 'agent.status.waiting': 'Waiting for you',
181
+ 'agent.status.paused': 'Paused',
182
+ 'agent.status.blocked': 'Blocked',
183
+ 'agent.status.done': 'Done',
184
+ 'agent.status.failed': 'Failed',
185
+ 'agent.status.stopped': 'Stopped',
186
+ 'agent.status.skipped': 'Skipped',
187
+ 'agent.activity.needsYou': 'Needs you',
188
+ 'agent.activity.blocked': 'Blocked',
189
+ 'agent.activity.working': 'Working',
190
+ 'agent.activity.thinking': 'Thinking',
191
+ 'agent.activity.idle': 'Idle',
192
+ 'agent.activity.offline': 'Offline'
193
+ });
194
+
195
+ /**
196
+ * Reads a state, falling back to `done` for anything the model does not know.
197
+ * @param {unknown} state
198
+ * @returns {RunState}
199
+ */
200
+ export function normalizeRunState(state) {
201
+ return typeof state === 'string' && Object.hasOwn(STATUS, state) ? /** @type {RunState} */ (state) : 'done';
202
+ }
203
+
204
+ /**
205
+ * Reads an activity, or null for none or anything unknown.
206
+ * @param {unknown} activity
207
+ * @returns {AgentActivity|null}
208
+ */
209
+ export function normalizeActivity(activity) {
210
+ return typeof activity === 'string' && Object.hasOwn(ACTIVITY, activity) ? /** @type {AgentActivity} */ (activity) : null;
211
+ }
212
+
213
+ /* ------------------------------------------------------------------ inline grammar -- */
214
+
215
+ /** @typedef {{kind: 'text'|'strong'|'code', text: string}|{kind: 'cite', text: string, n: number}} InlineSegment */
216
+
217
+ /** Characters a backslash makes literal. */
218
+ const ESCAPABLE = '*`[\\';
219
+
220
+ /**
221
+ * Splits a run of model text into plain text, `**bold**`, `` `code` ``, and `[n]` citation
222
+ * segments. That is the whole grammar: there are no links, no HTML, and no nesting. A backslash
223
+ * makes the next `*`, `` ` ``, `[`, or backslash literal; a marker that is never closed stays
224
+ * literal text, which is also what a half-streamed marker looks like until its close arrives.
225
+ * Code spans are verbatim: escapes inside them are not processed.
226
+ * @param {unknown} text
227
+ * @returns {InlineSegment[]}
228
+ */
229
+ export function parseInline(text) {
230
+ const source = text == null ? '' : String(text);
231
+ /** @type {InlineSegment[]} */
232
+ const out = [];
233
+ let buffer = '';
234
+ const flush = () => {
235
+ if (!buffer) return;
236
+ const last = out.at(-1);
237
+ if (last?.kind === 'text') last.text += buffer;
238
+ else out.push({ kind: 'text', text: buffer });
239
+ buffer = '';
240
+ };
241
+ let index = 0;
242
+ while (index < source.length) {
243
+ const char = source[index];
244
+ if (char === '\\' && index + 1 < source.length && ESCAPABLE.includes(source[index + 1])) {
245
+ buffer += source[index + 1];
246
+ index += 2;
247
+ continue;
248
+ }
249
+ if (char === '*' && source[index + 1] === '*') {
250
+ const close = findStrongClose(source, index + 2);
251
+ if (close > index + 2) {
252
+ flush();
253
+ out.push({ kind: 'strong', text: unescapeInline(source.slice(index + 2, close)) });
254
+ index = close + 2;
255
+ continue;
256
+ }
257
+ }
258
+ if (char === '`') {
259
+ const close = source.indexOf('`', index + 1);
260
+ if (close > index + 1) {
261
+ flush();
262
+ out.push({ kind: 'code', text: source.slice(index + 1, close) });
263
+ index = close + 1;
264
+ continue;
265
+ }
266
+ }
267
+ if (char === '[') {
268
+ const match = /^\[(\d{1,3})\]/.exec(source.slice(index, index + 5));
269
+ if (match && Number(match[1]) > 0) {
270
+ flush();
271
+ out.push({ kind: 'cite', text: match[0], n: Number(match[1]) });
272
+ index += match[0].length;
273
+ continue;
274
+ }
275
+ }
276
+ buffer += char;
277
+ index += 1;
278
+ }
279
+ flush();
280
+ return out;
281
+ }
282
+
283
+ /**
284
+ * Finds the `**` that closes a bold run opened just before `from`, skipping escaped asterisks.
285
+ * @param {string} source
286
+ * @param {number} from
287
+ * @returns {number} Index of the closing marker, or -1.
288
+ */
289
+ function findStrongClose(source, from) {
290
+ for (let index = from; index < source.length - 1; index += 1) {
291
+ if (source[index] === '\\') {
292
+ index += 1;
293
+ continue;
294
+ }
295
+ if (source[index] === '*' && source[index + 1] === '*') return index;
296
+ }
297
+ return -1;
298
+ }
299
+
300
+ /** @param {string} text @returns {string} The text with its backslash escapes resolved. */
301
+ function unescapeInline(text) {
302
+ return text.replace(/\\([*`[\\])/g, '$1');
303
+ }
304
+
305
+ /**
306
+ * The visible text of a run of model text: markers dropped, citations kept as `[n]`.
307
+ * @param {unknown} text
308
+ * @returns {string}
309
+ */
310
+ export function inlineText(text) {
311
+ return parseInline(text).map((segment) => segment.text).join('');
312
+ }
313
+
314
+ /* ------------------------------------------------------------------ figures -- */
315
+
316
+ /**
317
+ * Reads a figures row in either form.
318
+ * @param {FigureRow} row
319
+ * @returns {{label: string, detail: string, value: string, call: string|null}}
320
+ */
321
+ export function figureRow(row) {
322
+ if (Array.isArray(row)) return { label: String(row[0] ?? ''), detail: String(row[1] ?? ''), value: String(row[2] ?? ''), call: null };
323
+ return {
324
+ label: String(row?.label ?? ''),
325
+ detail: String(row?.detail ?? ''),
326
+ value: String(row?.value ?? ''),
327
+ call: typeof row?.call === 'string' && row.call ? row.call : null
328
+ };
329
+ }
330
+
331
+ /* ------------------------------------------------------------------ export -- */
332
+
333
+ /**
334
+ * An answer as plain text, for search and screen-reader summaries: markers dropped, one blank line
335
+ * between blocks.
336
+ * @param {Block[]} blocks
337
+ * @returns {string}
338
+ */
339
+ export function blocksToText(blocks) {
340
+ return (Array.isArray(blocks) ? blocks : []).map((block) => {
341
+ switch (block?.type) {
342
+ case 'list': return block.items.map((item) => inlineText(item)).join('\n');
343
+ case 'code': return block.code;
344
+ case 'table': return [block.columns, ...block.rows].map((row) => row.map((cell) => inlineText(cell)).join('\t')).join('\n');
345
+ case 'figures': return block.rows.map((row) => {
346
+ const { label, detail, value } = figureRow(row);
347
+ return [label, detail, value].filter(Boolean).join('\t');
348
+ }).join('\n');
349
+ case 'callout': return [block.title, inlineText(block.text)].filter(Boolean).join('\n');
350
+ case 'artifact': return block.title;
351
+ default: return inlineText(/** @type {{text?: string}} */ (block)?.text ?? '');
352
+ }
353
+ }).filter(Boolean).join('\n\n');
354
+ }
355
+
356
+ /** @param {string} cell @returns {string} A table cell safe inside a Markdown pipe row. */
357
+ function markdownCell(cell) {
358
+ return String(cell ?? '').replaceAll('|', '\\|').replaceAll('\n', ' ');
359
+ }
360
+
361
+ /**
362
+ * An answer as Markdown, for copying and export. Inline markers are already Markdown and pass
363
+ * through as written.
364
+ * @param {Block[]} blocks
365
+ * @returns {string}
366
+ */
367
+ export function blocksToMarkdown(blocks) {
368
+ return (Array.isArray(blocks) ? blocks : []).map((block) => {
369
+ switch (block?.type) {
370
+ case 'heading': return `${'#'.repeat(block.level === 3 ? 3 : 2)} ${block.text}`;
371
+ case 'quote': return block.text.split('\n').map((line) => `> ${line}`).join('\n');
372
+ case 'list': return block.items.map((item, index) => `${block.ordered ? `${index + 1}.` : '-'} ${item}`).join('\n');
373
+ case 'code': return `\`\`\`${block.language ?? ''}\n${block.code}\n\`\`\``;
374
+ case 'table': {
375
+ const rows = [block.columns, block.columns.map(() => '---'), ...block.rows];
376
+ return rows.map((row) => `| ${row.map(markdownCell).join(' | ')} |`).join('\n');
377
+ }
378
+ case 'figures': return block.rows.map((row) => {
379
+ const { label, detail, value } = figureRow(row);
380
+ return `- ${label}${detail ? ` (${detail})` : ''}: **${value}**`;
381
+ }).join('\n');
382
+ case 'callout': return `> ${block.title ? `**${block.title}** ` : ''}${block.text}`;
383
+ case 'artifact': return `**${block.title}**`;
384
+ default: return /** @type {{text?: string}} */ (block)?.text ?? '';
385
+ }
386
+ }).filter(Boolean).join('\n\n');
387
+ }
388
+
389
+ /* ------------------------------------------------------------------ runs -- */
390
+
391
+ /**
392
+ * @typedef {Object} TraceSummary
393
+ * @property {number} steps Steps that are not retries.
394
+ * @property {number} calls Tool calls made, retries included.
395
+ * @property {number} retries Steps that repeat another.
396
+ * @property {number} failed Steps that failed and were not retried successfully.
397
+ * @property {number} sources Sources looked at, across all searches.
398
+ * @property {number} ms Time spent on finished steps.
399
+ * @property {TraceStep|null} running The step running now, if any.
400
+ * @property {TraceStep|null} stopped The step the run was stopped at, if any.
401
+ */
402
+
403
+ /** Step kinds that are not tool calls. */
404
+ const NOT_CALLS = new Set(['think', 'handoff', 'task', 'ask', 'decision']);
405
+
406
+ /**
407
+ * What a run's steps add up to, for the one-line summary its trace folds into.
408
+ * @param {TraceStep[]} steps
409
+ * @returns {TraceSummary}
410
+ */
411
+ export function traceSummary(steps) {
412
+ const list = Array.isArray(steps) ? steps : [];
413
+ const retried = new Set(list.map((step) => step.retryOf).filter(Boolean));
414
+ let calls = 0;
415
+ let retries = 0;
416
+ let failed = 0;
417
+ let sources = 0;
418
+ let ms = 0;
419
+ /** @type {TraceStep|null} */
420
+ let running = null;
421
+ /** @type {TraceStep|null} */
422
+ let stopped = null;
423
+ for (const step of list) {
424
+ const status = normalizeRunState(step.status ?? 'done');
425
+ if (!NOT_CALLS.has(step.kind ?? 'call')) calls += 1;
426
+ if (step.retryOf) retries += 1;
427
+ if (status === 'failed' && !retried.has(step.id)) failed += 1;
428
+ if (typeof step.sources === 'number' && Number.isFinite(step.sources)) sources += step.sources;
429
+ if (status === 'running' && !running) running = step;
430
+ if (status === 'stopped' && !stopped) stopped = step;
431
+ if (status !== 'running' && typeof step.ms === 'number' && Number.isFinite(step.ms)) ms += step.ms;
432
+ }
433
+ return { steps: list.length - retries, calls, retries, failed, sources, ms, running, stopped };
434
+ }
435
+
436
+ /**
437
+ * How long something took, the way a person says it: "0.8 s" below ten seconds, then "12 s",
438
+ * "1 min 42 s", "1 h 5 min".
439
+ * @param {number} ms
440
+ * @param {{locale?: string}} [options]
441
+ * @returns {string}
442
+ */
443
+ export function formatDuration(ms, options = {}) {
444
+ const value = Number(ms);
445
+ if (!Number.isFinite(value) || value < 0) return '';
446
+ if (value < 10_000) return `${formatNumber(value / 1000, { decimals: 1, locale: options.locale })} s`;
447
+ return formatElapsed(value);
448
+ }
449
+
450
+ /**
451
+ * A running clock in whole units: "2 s", "41 s", "1 min 42 s", "1 h 5 min".
452
+ * @param {number} ms
453
+ * @returns {string}
454
+ */
455
+ export function formatElapsed(ms) {
456
+ const value = Number(ms);
457
+ if (!Number.isFinite(value) || value < 0) return '';
458
+ const seconds = Math.floor(value / 1000);
459
+ if (seconds < 60) return `${seconds} s`;
460
+ const minutes = Math.floor(seconds / 60);
461
+ if (minutes < 60) return `${minutes} min ${seconds % 60} s`;
462
+ return `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
463
+ }
464
+
465
+ /**
466
+ * What a run cost, from its token counts and per-token prices.
467
+ * @param {[number, number]|null|undefined} tokens Input and output tokens.
468
+ * @param {{in: number, out: number}} price Price per input and per output token.
469
+ * @returns {number}
470
+ */
471
+ export function runCost(tokens, price) {
472
+ if (!Array.isArray(tokens) || !price) return 0;
473
+ const input = Number(tokens[0]) || 0;
474
+ const output = Number(tokens[1]) || 0;
475
+ return input * (Number(price.in) || 0) + output * (Number(price.out) || 0);
476
+ }
477
+
478
+ /**
479
+ * Initials for an avatar from a name: "Finance agent" → "FA".
480
+ * @param {string} name
481
+ * @returns {string}
482
+ */
483
+ export function initialsOf(name) {
484
+ const words = String(name ?? '').trim().split(/\s+/).filter(Boolean);
485
+ if (words.length === 0) return '?';
486
+ const letters = words.length === 1 ? [...words[0]].slice(0, 2) : [[...words[0]][0], [...words.at(-1) ?? ''][0]];
487
+ return letters.join('').toUpperCase();
488
+ }
@@ -19,7 +19,11 @@ import { Tooltip } from '../components/tooltip/tooltip.js';
19
19
  * @property {AppNavItem[]} [children] Child destinations/actions.
20
20
  * @property {boolean} [section] Makes the item a section: a quiet heading over its `children`, which
21
21
  * render at the same level. A section is never focused, selected, or collapsed, and needs no `id`.
22
- * @property {Node|{toElement: () => Node|null}} [actions] A section's trailing controls, such as an add button.
22
+ * @property {Node|{toElement: () => Node|null}|Array<import('./row-actions.js').RowAction|Node>} [actions]
23
+ * On a section, trailing controls beside its heading, such as an add button, always shown. On a
24
+ * destination of AppSidebar's tree, the row's actions: `{icon, label, onSelect(item), disabled?,
25
+ * danger?}` descriptors or nodes, revealed with the row, in its context menu, and after its
26
+ * control in the Tab order while it holds focus. Minimized flyouts show destinations only.
23
27
  */
24
28
  /**
25
29
  * @typedef {Object} AppRailPresenterOptions
@@ -0,0 +1,104 @@
1
+ // @ts-check
2
+ /**
3
+ * A small syntax tokenizer for code an agent writes into an answer. It recognises comments,
4
+ * strings, numbers, and keywords — enough to make code readable, never enough to be an editor —
5
+ * and returns segments, never markup, so the caller builds text nodes and spans from them.
6
+ */
7
+
8
+ /** @typedef {'comment'|'string'|'number'|'keyword'} TokenKind */
9
+ /** @typedef {{text: string, token: TokenKind|null}} CodeSegment */
10
+
11
+ /** A string in single, double, or back quotes; unterminated while it is still being streamed. */
12
+ const STRING = /'(?:[^'\\\n]|\\.)*'?|"(?:[^"\\\n]|\\.)*"?|`(?:[^`\\]|\\.)*`?/;
13
+ /** A number, digit separators included: `30_000`, `0.5`, `1e3`. */
14
+ const NUMBER = /\b\d[\d_]*(?:\.\d+)?(?:e[+-]?\d+)?\b/;
15
+ /** A name or a keyword. */
16
+ const WORD = /[A-Za-z_$][\w$]*/;
17
+
18
+ /**
19
+ * What the tokenizer recognises in one language. Comments, strings, numbers, and words are
20
+ * matched in that order from left to right, so a quote inside a comment or a digit inside a name
21
+ * never starts a token of its own.
22
+ * @param {RegExp} comment Line or block comment.
23
+ * @param {string} keywords Space-separated, lower case for caseless languages.
24
+ * @param {{caseless?: boolean, string?: RegExp}} [options]
25
+ * @returns {{pattern: RegExp, keywords: Set<string>, caseless: boolean}}
26
+ */
27
+ function grammar(comment, keywords, options = {}) {
28
+ const parts = [['comment', comment], ['string', options.string ?? STRING], ['number', NUMBER], ['word', WORD]];
29
+ return {
30
+ pattern: new RegExp(parts.map(([name, part]) => `(?<${name}>${/** @type {RegExp} */ (part).source})`).join('|'), 'g'),
31
+ keywords: new Set(keywords.split(' ')),
32
+ caseless: Boolean(options.caseless)
33
+ };
34
+ }
35
+
36
+ const SCRIPT_KEYWORDS = 'async await break case catch class const continue debugger default delete do else export '
37
+ + 'extends false finally for from function if import in instanceof let new null of return static super switch '
38
+ + 'this throw true try typeof undefined var void while yield';
39
+
40
+ const GRAMMARS = Object.freeze({
41
+ javascript: grammar(/\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/, SCRIPT_KEYWORDS),
42
+ typescript: grammar(/\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/, `${SCRIPT_KEYWORDS} abstract as declare enum implements interface keyof `
43
+ + 'namespace private protected public readonly type'),
44
+ json: grammar(/(?!)/, 'true false null', { string: /"(?:[^"\\\n]|\\.)*"?/ }),
45
+ sql: grammar(/--[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/, 'and as asc between by case count delete desc distinct else end exists from '
46
+ + 'group having in inner insert interval into is join left limit not null on or order outer right select set sum '
47
+ + 'then union update values when where with', { caseless: true, string: /'(?:[^'\n]|'')*'?/ }),
48
+ python: grammar(/#[^\n]*/, 'and as assert async await break class continue def del elif else except false finally for '
49
+ + 'from global if import in is lambda none nonlocal not or pass raise return true try while with yield', { caseless: false }),
50
+ shell: grammar(/(?<!\S)#[^\n]*/, 'case do done elif else esac export fi for function if in local read return then until while'),
51
+ css: grammar(/\/\*[\s\S]*?(?:\*\/|$)/, 'important inherit initial none unset auto')
52
+ });
53
+
54
+ /** Language names an answer may use, mapped to the grammar that reads them. */
55
+ const ALIASES = Object.freeze({
56
+ js: 'javascript', javascript: 'javascript', mjs: 'javascript', jsx: 'javascript',
57
+ ts: 'typescript', typescript: 'typescript', tsx: 'typescript',
58
+ json: 'json',
59
+ sql: 'sql',
60
+ py: 'python', python: 'python',
61
+ sh: 'shell', bash: 'shell', shell: 'shell', zsh: 'shell',
62
+ css: 'css'
63
+ });
64
+
65
+ /**
66
+ * Whether code in this language is coloured.
67
+ * @param {unknown} language
68
+ * @returns {boolean}
69
+ */
70
+ export function isHighlighted(language) {
71
+ return Object.hasOwn(ALIASES, String(language ?? '').toLowerCase());
72
+ }
73
+
74
+ /**
75
+ * Splits code into plain and coloured segments. An unknown language is one plain segment.
76
+ * Python's `True`/`None` and SQL's upper-case keywords are matched without regard to case.
77
+ * @param {unknown} language
78
+ * @param {unknown} source
79
+ * @returns {CodeSegment[]}
80
+ */
81
+ export function highlight(language, source) {
82
+ const code = source == null ? '' : String(source);
83
+ const name = ALIASES[/** @type {keyof typeof ALIASES} */ (String(language ?? '').toLowerCase())];
84
+ const syntax = name ? GRAMMARS[/** @type {keyof typeof GRAMMARS} */ (name)] : null;
85
+ if (!syntax) return code ? [{ text: code, token: null }] : [];
86
+ const caseless = syntax.caseless || name === 'python';
87
+ /** @type {CodeSegment[]} */
88
+ const out = [];
89
+ let plain = 0;
90
+ for (const match of code.matchAll(syntax.pattern)) {
91
+ if (match[0] === '') continue;
92
+ const groups = /** @type {Record<string, string|undefined>} */ (match.groups);
93
+ /** @type {TokenKind|null} */
94
+ const token = groups.comment ? 'comment' : groups.string ? 'string' : groups.number ? 'number'
95
+ : groups.word && syntax.keywords.has(caseless ? groups.word.toLowerCase() : groups.word) ? 'keyword' : null;
96
+ if (!token) continue;
97
+ const start = Number(match.index);
98
+ if (start > plain) out.push({ text: code.slice(plain, start), token: null });
99
+ out.push({ text: match[0], token });
100
+ plain = start + match[0].length;
101
+ }
102
+ if (plain < code.length) out.push({ text: code.slice(plain), token: null });
103
+ return out;
104
+ }