@zeyos/zx 5.5.0 → 5.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/CHANGELOG.md +210 -0
  2. package/README.md +73 -7
  3. package/bin/zx-css.js +328 -0
  4. package/dist/types/components/account-menu/account-menu.d.ts +4 -2
  5. package/dist/types/components/activity-list/activity-list.d.ts +14 -8
  6. package/dist/types/components/agent-thread/ag-ui.d.ts +340 -0
  7. package/dist/types/components/agent-thread/agent-thread.d.ts +711 -0
  8. package/dist/types/components/agent-thread/ui-message-stream.d.ts +401 -0
  9. package/dist/types/components/app-sidebar/app-sidebar.d.ts +14 -8
  10. package/dist/types/components/approval-card/approval-card.d.ts +596 -0
  11. package/dist/types/components/avatar/avatar.d.ts +91 -4
  12. package/dist/types/components/block-view/block-view.d.ts +205 -0
  13. package/dist/types/components/breadcrumb/breadcrumb.d.ts +3 -3
  14. package/dist/types/components/calendar/calendar-model.d.ts +9 -2
  15. package/dist/types/components/calendar/calendar.d.ts +12 -4
  16. package/dist/types/components/chart/chart.d.ts +25 -13
  17. package/dist/types/components/code-editor/code-editor.d.ts +7 -2
  18. package/dist/types/components/composer/composer.d.ts +938 -0
  19. package/dist/types/components/composer/queue.d.ts +76 -0
  20. package/dist/types/components/copy/copy-button.d.ts +6 -4
  21. package/dist/types/components/copy/copy-input.d.ts +10 -6
  22. package/dist/types/components/datebox/date-range-box.d.ts +33 -0
  23. package/dist/types/components/datebox/placeholder.d.ts +7 -0
  24. package/dist/types/components/dock/dock.d.ts +12 -3
  25. package/dist/types/components/entity-ref/entity-ref.d.ts +5 -3
  26. package/dist/types/components/field-upload/field-upload.d.ts +3 -2
  27. package/dist/types/components/file-item/file-item.d.ts +3 -2
  28. package/dist/types/components/file-list/file-list.d.ts +14 -8
  29. package/dist/types/components/filter/filter-model.d.ts +31 -1
  30. package/dist/types/components/filter/filter.d.ts +20 -2
  31. package/dist/types/components/finder/finder.d.ts +14 -6
  32. package/dist/types/components/flag/flag.d.ts +99 -0
  33. package/dist/types/components/grid/grid.d.ts +1 -1
  34. package/dist/types/components/kanban-view/kanban-view.d.ts +8 -66
  35. package/dist/types/components/launcher/launcher.d.ts +2 -0
  36. package/dist/types/components/multi-value-editor/multi-value-editor.d.ts +3 -2
  37. package/dist/types/components/number-field/number-field.d.ts +17 -6
  38. package/dist/types/components/prompt-starters/prompt-starters.d.ts +107 -0
  39. package/dist/types/components/prose/prose.d.ts +9 -6
  40. package/dist/types/components/questionnaire/conditions.d.ts +270 -0
  41. package/dist/types/components/questionnaire/items.d.ts +52 -30
  42. package/dist/types/components/questionnaire/questionnaire.d.ts +44 -4
  43. package/dist/types/components/rating/rating.d.ts +5 -3
  44. package/dist/types/components/run-status/run-status.d.ts +393 -0
  45. package/dist/types/components/run-trace/run-trace.d.ts +624 -0
  46. package/dist/types/components/select/country.d.ts +106 -0
  47. package/dist/types/components/select/field-adapter.d.ts +2 -1
  48. package/dist/types/components/select/locale.d.ts +102 -0
  49. package/dist/types/components/select/select.d.ts +41 -2
  50. package/dist/types/components/slider/slider.d.ts +1 -0
  51. package/dist/types/components/sort-control/sort-control.d.ts +7 -3
  52. package/dist/types/components/source-list/source-list.d.ts +179 -0
  53. package/dist/types/components/split-view/split-view.d.ts +5 -3
  54. package/dist/types/components/surface/catalog.d.ts +260 -0
  55. package/dist/types/components/surface/elicit.d.ts +81 -0
  56. package/dist/types/components/surface/mcp.d.ts +165 -0
  57. package/dist/types/components/surface/schema.d.ts +314 -0
  58. package/dist/types/components/surface/stream.d.ts +118 -0
  59. package/dist/types/components/surface/surface.d.ts +718 -0
  60. package/dist/types/components/surface/text.d.ts +277 -0
  61. package/dist/types/components/surface/validate.d.ts +339 -0
  62. package/dist/types/components/table/table.d.ts +55 -3
  63. package/dist/types/components/table/window.d.ts +203 -0
  64. package/dist/types/components/toolbar/toolbar.d.ts +10 -6
  65. package/dist/types/components/tooltip/tooltip.d.ts +2 -2
  66. package/dist/types/components/tree/tree.d.ts +20 -13
  67. package/dist/types/core/component.d.ts +10 -0
  68. package/dist/types/core/date.d.ts +8 -1
  69. package/dist/types/core/dom.d.ts +1 -0
  70. package/dist/types/core/http.d.ts +10 -0
  71. package/dist/types/core/i18n.d.ts +38 -0
  72. package/dist/types/core/messages.d.ts +479 -1
  73. package/dist/types/core/storage.d.ts +7 -2
  74. package/dist/types/elements/define.d.ts +21 -46
  75. package/dist/types/elements/definitions.d.ts +147 -0
  76. package/dist/types/elements/kit.d.ts +7 -0
  77. package/dist/types/elements/reflect.d.ts +6 -3
  78. package/dist/types/index.d.ts +18 -1
  79. package/dist/types/internal/agent-model.d.ts +587 -0
  80. package/dist/types/internal/date-locale.d.ts +7 -0
  81. package/dist/types/internal/highlight.d.ts +24 -0
  82. package/dist/types/internal/json-patch.d.ts +146 -0
  83. package/dist/types/internal/presence-loop.d.ts +148 -0
  84. package/dist/types/locales/de.d.ts +13 -0
  85. package/dist/types/locales/en.d.ts +2 -0
  86. package/dist/types/locales/index.d.ts +823 -0
  87. package/dist/types/zeyos/view.d.ts +8 -1
  88. package/dist/zx-zeyos.esm.js +20505 -18748
  89. package/dist/zx-zeyos.esm.min.js +5 -5
  90. package/dist/zx.core.css +1276 -0
  91. package/dist/zx.core.min.css +1 -0
  92. package/dist/zx.css +2424 -134
  93. package/dist/zx.esm.js +46167 -28468
  94. package/dist/zx.esm.min.js +40 -8
  95. package/dist/zx.global.js +46167 -28468
  96. package/dist/zx.global.min.js +40 -8
  97. package/dist/zx.layered.css +17302 -0
  98. package/dist/zx.layered.min.css +1 -0
  99. package/dist/zx.min.css +1 -1
  100. package/docs/agent-catalog.json +12501 -0
  101. package/docs/agent-surfaces.md +340 -0
  102. package/docs/api.json +2057 -166
  103. package/docs/llms.md +1458 -58
  104. package/docs/llms.txt +38 -8
  105. package/package.json +29 -6
  106. package/src/components/account-menu/account-menu.js +6 -3
  107. package/src/components/activity-item/activity-item.js +2 -1
  108. package/src/components/activity-list/activity-list.js +16 -10
  109. package/src/components/agent-thread/ag-ui.js +1439 -0
  110. package/src/components/agent-thread/agent-thread.css +417 -0
  111. package/src/components/agent-thread/agent-thread.js +1670 -0
  112. package/src/components/agent-thread/ui-message-stream.js +1281 -0
  113. package/src/components/app-sidebar/app-sidebar.js +18 -8
  114. package/src/components/approval-card/approval-card.css +289 -0
  115. package/src/components/approval-card/approval-card.js +1378 -0
  116. package/src/components/avatar/avatar.css +56 -1
  117. package/src/components/avatar/avatar.js +148 -26
  118. package/src/components/block-view/block-view.css +300 -0
  119. package/src/components/block-view/block-view.js +524 -0
  120. package/src/components/breadcrumb/breadcrumb.js +8 -5
  121. package/src/components/calendar/calendar-model.js +8 -2
  122. package/src/components/calendar/calendar.js +53 -18
  123. package/src/components/chart/chart.js +54 -23
  124. package/src/components/code-editor/code-editor.js +45 -8
  125. package/src/components/code-editor/field-adapter.js +1 -1
  126. package/src/components/composer/composer.css +482 -0
  127. package/src/components/composer/composer.js +1815 -0
  128. package/src/components/composer/queue.js +78 -0
  129. package/src/components/context-menu/context-menu.js +12 -1
  130. package/src/components/copy/copy-button.js +9 -7
  131. package/src/components/copy/copy-input.js +10 -6
  132. package/src/components/date-picker/date-picker.js +2 -1
  133. package/src/components/date-picker/date-range-picker.js +8 -7
  134. package/src/components/datebox/date-range-box.js +3 -9
  135. package/src/components/datebox/datebox.js +18 -21
  136. package/src/components/datebox/placeholder.js +18 -0
  137. package/src/components/dialog/dialog.js +1 -1
  138. package/src/components/dock/dock.js +34 -13
  139. package/src/components/entity-ref/entity-ref.js +16 -5
  140. package/src/components/field-upload/field-upload.js +81 -38
  141. package/src/components/file-item/file-item.js +70 -40
  142. package/src/components/file-list/file-list.js +15 -9
  143. package/src/components/filter/filter-model.js +46 -8
  144. package/src/components/filter/filter.css +3 -3
  145. package/src/components/filter/filter.js +29 -10
  146. package/src/components/filter-panel/filter-panel.js +13 -5
  147. package/src/components/finder/finder.js +50 -26
  148. package/src/components/flag/flag.css +40 -0
  149. package/src/components/flag/flag.js +177 -0
  150. package/src/components/form/form.js +1 -1
  151. package/src/components/grid/grid.js +22 -8
  152. package/src/components/kanban-view/kanban-view.js +51 -81
  153. package/src/components/launcher/launcher.js +17 -2
  154. package/src/components/list-toolbar/list-toolbar.js +2 -1
  155. package/src/components/master-panel/master-panel.js +1 -1
  156. package/src/components/menu-button/menu-button.js +4 -0
  157. package/src/components/message/message.js +3 -0
  158. package/src/components/multi-value-editor/multi-value-editor.js +10 -9
  159. package/src/components/navigation-bar/navigation-bar.js +3 -3
  160. package/src/components/number-field/number-field.js +29 -13
  161. package/src/components/prompt-starters/prompt-starters.css +91 -0
  162. package/src/components/prompt-starters/prompt-starters.js +206 -0
  163. package/src/components/prose/prose.js +14 -10
  164. package/src/components/questionnaire/conditions.js +666 -0
  165. package/src/components/questionnaire/items.js +150 -41
  166. package/src/components/questionnaire/questionnaire.js +126 -32
  167. package/src/components/rating/rating.js +5 -4
  168. package/src/components/run-status/run-status.css +208 -0
  169. package/src/components/run-status/run-status.js +782 -0
  170. package/src/components/run-trace/run-trace.css +443 -0
  171. package/src/components/run-trace/run-trace.js +1209 -0
  172. package/src/components/select/country.js +136 -0
  173. package/src/components/select/field-adapter.js +7 -2
  174. package/src/components/select/locale.js +219 -0
  175. package/src/components/select/select.css +20 -22
  176. package/src/components/select/select.js +94 -12
  177. package/src/components/sheet/sheet-stack.js +10 -1
  178. package/src/components/slider/slider.js +7 -2
  179. package/src/components/sort-control/sort-control.js +15 -5
  180. package/src/components/source-list/source-list.css +208 -0
  181. package/src/components/source-list/source-list.js +358 -0
  182. package/src/components/split-view/split-view.js +5 -3
  183. package/src/components/surface/catalog.js +1334 -0
  184. package/src/components/surface/elicit.js +107 -0
  185. package/src/components/surface/mcp.js +243 -0
  186. package/src/components/surface/schema.js +644 -0
  187. package/src/components/surface/stream.js +245 -0
  188. package/src/components/surface/surface.css +308 -0
  189. package/src/components/surface/surface.js +2291 -0
  190. package/src/components/surface/text.js +513 -0
  191. package/src/components/surface/validate.js +2218 -0
  192. package/src/components/tabbox/tabbox.js +9 -0
  193. package/src/components/table/table.css +63 -3
  194. package/src/components/table/table.js +167 -28
  195. package/src/components/table/window.js +317 -0
  196. package/src/components/toolbar/toolbar.js +12 -7
  197. package/src/components/tooltip/tooltip.css +2 -3
  198. package/src/components/tooltip/tooltip.js +32 -5
  199. package/src/components/tree/tree.js +53 -23
  200. package/src/core/component.js +25 -1
  201. package/src/core/date.js +62 -16
  202. package/src/core/dom.js +22 -2
  203. package/src/core/format.js +15 -13
  204. package/src/core/http.js +29 -20
  205. package/src/core/i18n.js +83 -10
  206. package/src/core/keyboard.js +79 -8
  207. package/src/core/messages.js +519 -2
  208. package/src/core/overlay-host.js +1 -0
  209. package/src/core/storage.js +59 -6
  210. package/src/elements/define.js +178 -130
  211. package/src/elements/definitions.js +229 -0
  212. package/src/elements/kit.js +444 -0
  213. package/src/elements/reflect.js +8 -3
  214. package/src/index.js +18 -1
  215. package/src/internal/agent-model.js +488 -0
  216. package/src/internal/date-locale.js +11 -0
  217. package/src/internal/highlight.js +104 -0
  218. package/src/internal/json-patch.js +405 -0
  219. package/src/internal/presence-loop.js +343 -0
  220. package/src/locales/de.js +911 -0
  221. package/src/locales/en.js +2 -0
  222. package/src/locales/index.js +7 -0
  223. package/src/zeyos/calendar.js +2 -1
  224. package/src/zeyos/form.js +2 -1
  225. package/src/zeyos/launcher.js +7 -6
  226. package/src/zeyos/module-bar.js +2 -1
  227. package/src/zeyos/schema.js +37 -23
  228. package/src/zeyos/select.js +4 -3
  229. package/src/zeyos/table.js +2 -13
  230. package/src/zeyos/view.js +57 -17
  231. package/styles/core.css +11 -0
  232. package/styles/tokens/semantic.css +1 -0
  233. package/styles/zeyos.css +2 -0
  234. package/styles/zx.css +11 -8
  235. package/styles/zx.layered.css +1 -0
@@ -0,0 +1,782 @@
1
+ // @ts-check
2
+ import { Component } from '../../core/component.js';
3
+ import { formatDate, isSameDay } from '../../core/date.js';
4
+ import { h, restoreTarget, snapshotTarget } from '../../core/dom.js';
5
+ import { formatCurrency, formatNumber } from '../../core/format.js';
6
+ import { getLanguage, printf } from '../../core/i18n.js';
7
+ import { AGENT_MESSAGES, STATUS, formatElapsed, normalizeRunState } from '../../internal/agent-model.js';
8
+ import { button } from '../button/button.js';
9
+ import { statusIcon } from '../select/glyphs.js';
10
+
11
+ /** @typedef {import('../../internal/agent-model.js').RunState} RunState */
12
+
13
+ /**
14
+ * A button beside the run's state, for what the reader can do about it now: "Review the request"
15
+ * while it waits, "Renew the consent" when it failed.
16
+ * @typedef {Object} RunStatusAction
17
+ * @property {string} label Visible label.
18
+ * @property {'default'|'primary'|'danger'|'ghost'} [kind='default'] Visual intent.
19
+ * @property {string|null} [icon=null] Icon name.
20
+ * @property {(event: MouseEvent) => void} [onclick] Called on activation, before the `action` event.
21
+ */
22
+
23
+ /**
24
+ * What a run has cost so far, and the budget it may spend.
25
+ * @typedef {Object} RunCost
26
+ * @property {number} amount Spent so far.
27
+ * @property {number|null} [budget] The most it may spend. With a budget the cost is a meter that
28
+ * turns to the warning tone from 80% and to the danger tone at 100%.
29
+ * @property {string} [currency] ISO 4217 code, such as `EUR`.
30
+ */
31
+
32
+ /** @typedef {{done: number, total: number}} RunSteps */
33
+
34
+ /**
35
+ * Tokens a run has used: `[input, output]`, or the total as a single number.
36
+ * @typedef {[number, number]|number} RunTokens
37
+ */
38
+
39
+ /**
40
+ * How the state is drawn on its own: `'word'` is the glyph and the word (`compact: true`), `'icon'`
41
+ * the glyph alone with the word kept for assistive technology and the tooltip.
42
+ * @typedef {'word'|'icon'} RunCompactMode
43
+ */
44
+
45
+ /**
46
+ * The tokens drawn as a meter against their budget.
47
+ * @typedef {Object} RunTokenMeter
48
+ * @property {number} total Tokens used.
49
+ * @property {number} budget The most the run may use.
50
+ * @property {'normal'|'warning'|'danger'} level `warning` from 80%, `danger` at 100%.
51
+ * @property {string} text "22.8K of 60K tokens".
52
+ */
53
+
54
+ /** A local ISO date-time string (`2026-09-29T11:20:04`) or a `Date`. @typedef {string|Date} RunTime */
55
+
56
+ /**
57
+ * @typedef {Object} RunStatusOptions
58
+ * @property {RunState} [state='queued'] Where the run stands. Also the root's `data-state`. A
59
+ * `blocked` run is not over: it shows since when it is blocked, never a finished time.
60
+ * @property {string} [summary=''] One sentence on what is happening: "Step 3 of 6 needs your
61
+ * approval." Text only.
62
+ * @property {RunSteps|null} [steps=null] Steps done out of the total, drawn as a progressbar.
63
+ * @property {RunTime|null} [started=null] When the run started.
64
+ * @property {RunTime|null} [finished=null] When it finished, failed, or was stopped. Shown once
65
+ * the run is over.
66
+ * @property {number|null} [workMs=null] How long the agent has worked, in milliseconds. Waiting
67
+ * for a person is not work. The row shows only when this is a number.
68
+ * @property {RunTime|null} [waitingSince=null] Since when the run has waited for a person, or been
69
+ * blocked. Shown as "Waiting since" while the state is `waiting` and "Blocked since" while it is
70
+ * `blocked`.
71
+ * @property {RunTokens|null} [tokens=null] Input and output tokens as `[in, out]`, or the total as
72
+ * one number.
73
+ * @property {number|null} [tokenBudget=null] The most tokens the run may use. With a budget the
74
+ * tokens are a meter, read in compact figures ("22.8K of 60K tokens"), that turns to the warning
75
+ * tone from 80% and to the danger tone at 100%. Without one they stay text.
76
+ * @property {RunCost|null} [cost=null] What the run has cost, against its budget.
77
+ * @property {string|null} [model=null] The model the agent runs on.
78
+ * @property {RunStatusAction[]} [actions=[]] Buttons under the summary.
79
+ * @property {boolean} [ticking=true] While the state is `running`, the working time counts on
80
+ * once a second from `workMs` and the moment of the last `update()`. One interval, which sleeps
81
+ * while the page is hidden.
82
+ * @property {boolean|'icon'} [compact=false] Draws only the state: `true` as a pill of glyph and
83
+ * word for a narrow header, `'icon'` as the glyph alone, its word visually hidden but still the
84
+ * accessible text, and shown as the pill's tooltip.
85
+ * @property {(() => Date)|null} [now=null] The clock: what decides whether a time is today (a
86
+ * time on another day shows its date too) and what the working time counts against while
87
+ * `ticking`. Null is real time. Fixed at construction.
88
+ * @property {string} [locale] BCP 47 tag for numbers and amounts; defaults to the active language.
89
+ * @property {Record<string, string>|Record<string, Record<string, string>>} [msg] Localized
90
+ * messages: the state words (`agent.status.*`) and the `runStatus.*` labels.
91
+ * @property {(event: CustomEvent<{index: number, action: RunStatusAction}>) => void} [onaction]
92
+ * Action listener.
93
+ */
94
+
95
+ /**
96
+ * The run's values as they stand. `workMs` includes the time counted since the last update.
97
+ * @typedef {Object} RunStatusState
98
+ * @property {RunState} state
99
+ * @property {string} summary
100
+ * @property {RunSteps|null} steps
101
+ * @property {RunTime|null} started
102
+ * @property {RunTime|null} finished
103
+ * @property {number|null} workMs
104
+ * @property {RunTime|null} waitingSince
105
+ * @property {RunTokens|null} tokens
106
+ * @property {number|null} tokenBudget
107
+ * @property {RunCost|null} cost
108
+ * @property {string|null} model
109
+ * @property {RunStatusAction[]} actions
110
+ */
111
+
112
+ const MESSAGES = Object.freeze({
113
+ ...AGENT_MESSAGES,
114
+ 'runStatus.started': 'Started',
115
+ 'runStatus.workingTime': 'Working time',
116
+ 'runStatus.waitingSince': 'Waiting since',
117
+ 'runStatus.blockedSince': 'Blocked since',
118
+ 'runStatus.finished': 'Finished',
119
+ 'runStatus.failedAt': 'Failed at',
120
+ 'runStatus.stoppedAt': 'Stopped at',
121
+ 'runStatus.model': 'Model',
122
+ 'runStatus.tokens': 'Tokens',
123
+ 'runStatus.tokensValue': '%1 in · %2 out',
124
+ 'runStatus.tokenBudget': '%1 of %2 tokens',
125
+ 'runStatus.costLabel': 'Cost',
126
+ 'runStatus.cost': '%1 of %2',
127
+ 'runStatus.stepsLabel': 'Steps done',
128
+ // Step plurals come from the English catalogue so its own cardinal rules select the fallback.
129
+ 'runStatus.timeFormat': '%H:%M',
130
+ 'runStatus.dateTimeFormat': '%e %b, %H:%M'
131
+ });
132
+
133
+ /** The values `update()` merges; everything else is fixed at construction. */
134
+ const VALUE_KEYS = Object.freeze(['state', 'summary', 'steps', 'started', 'finished', 'workMs', 'waitingSince',
135
+ 'tokens', 'tokenBudget', 'cost', 'model', 'actions', 'ticking', 'compact']);
136
+
137
+ /** The label of the "finished" row for each state that ends a run. */
138
+ const FINISHED_KEYS = Object.freeze({
139
+ done: 'runStatus.finished',
140
+ failed: 'runStatus.failedAt',
141
+ stopped: 'runStatus.stoppedAt',
142
+ skipped: 'runStatus.finished'
143
+ });
144
+
145
+ /**
146
+ * The label of the "since" row for each state that holds the run for someone or something. A
147
+ * blocked run is not over: it shows since when it has been blocked, never when it finished.
148
+ */
149
+ const SINCE_KEYS = Object.freeze({
150
+ waiting: 'runStatus.waitingSince',
151
+ blocked: 'runStatus.blockedSince'
152
+ });
153
+
154
+ /** What can take focus inside the panel, in document order. */
155
+ const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), '
156
+ + 'textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
157
+
158
+ /**
159
+ * Where an agent's run stands: its state in a glyph and a word, a sentence on what is happening,
160
+ * its steps as a progressbar, when it started and how long the agent has worked, what it has cost
161
+ * against its budget, and the buttons for what the reader can do about it now. `compact` draws the
162
+ * state alone, for a header.
163
+ *
164
+ * It announces nothing itself: the conversation the run belongs to says when it starts, waits,
165
+ * fails, or finishes.
166
+ *
167
+ * @fires RunStatus#action
168
+ * @extends {Component<RunStatusOptions>}
169
+ */
170
+ export class RunStatus extends Component {
171
+ static cssName = 'run-status';
172
+
173
+ /** @type {Readonly<RunStatusOptions>} */
174
+ static defaults = {
175
+ state: 'queued',
176
+ summary: '',
177
+ steps: null,
178
+ started: null,
179
+ finished: null,
180
+ workMs: null,
181
+ waitingSince: null,
182
+ tokens: null,
183
+ tokenBudget: null,
184
+ cost: null,
185
+ model: null,
186
+ actions: [],
187
+ ticking: true,
188
+ compact: false,
189
+ now: null,
190
+ msg: MESSAGES
191
+ };
192
+
193
+ /** @returns {HTMLElement} */
194
+ render() {
195
+ const created = !this.el;
196
+ const root = /** @type {HTMLElement} */ (this.el ?? h('div'));
197
+ this.el = root;
198
+ this._original = created ? null : snapshotTarget(root);
199
+ if (!created) root.replaceChildren();
200
+ /** @type {Record<string, any>} */
201
+ this._values = {};
202
+ for (const key of VALUE_KEYS) this._values[key] = copyValue(this.options[key]);
203
+ this._workBase = finiteOrNull(this.options.workMs);
204
+ this._workAt = this._clock();
205
+ /** @type {HTMLElement|null} */
206
+ this._elapsed = null;
207
+ /** @type {HTMLElement|null} The action row as drawn, kept across updates that leave it unchanged. */
208
+ this._actionsEl = null;
209
+ this._actionsKey = '';
210
+ /** Whether the root took `tabindex="-1"` to hold focus that had nowhere else to go. */
211
+ this._heldFocus = false;
212
+ /** @type {ReturnType<typeof setInterval>|0} */
213
+ this._interval = 0;
214
+ this._destroyed = false;
215
+ const doc = root.ownerDocument;
216
+ this.listen(root, 'click', (event) => this._onClick(/** @type {MouseEvent} */ (event)));
217
+ this.listen(root, 'blur', () => this._releaseFocus());
218
+ this.listen(doc, 'visibilitychange', () => {
219
+ if (!doc.hidden) this._tick();
220
+ this._syncTicker();
221
+ });
222
+ this._draw();
223
+ return root;
224
+ }
225
+
226
+ /**
227
+ * Merges new values and redraws. The working time carries on from where it stood unless the
228
+ * update brings a new `workMs`. Focus inside the panel stays where it was: an action row that
229
+ * did not change is kept as it is, and otherwise focus moves to the action at the same index (or
230
+ * the nearest one left), or to the panel itself when no action is left.
231
+ * @param {Partial<Omit<RunStatusOptions, 'locale'|'msg'|'onaction'|'now'>>} values
232
+ * @returns {this}
233
+ */
234
+ update(values = {}) {
235
+ if (this._destroyed || !values || typeof values !== 'object') return this;
236
+ const current = this._workTime();
237
+ for (const key of VALUE_KEYS) {
238
+ if (Object.hasOwn(values, key)) this._values[key] = copyValue(/** @type {Record<string, unknown>} */ (values)[key]);
239
+ }
240
+ this._workBase = Object.hasOwn(values, 'workMs') ? finiteOrNull(values.workMs) : current;
241
+ this._workAt = this._clock();
242
+ this._draw();
243
+ return this;
244
+ }
245
+
246
+ /** @returns {RunStatusState} The run's values as they stand, as copies. */
247
+ getState() {
248
+ const values = this._values;
249
+ return {
250
+ state: normalizeRunState(values.state),
251
+ summary: String(values.summary ?? ''),
252
+ steps: copyValue(values.steps) ?? null,
253
+ started: values.started ?? null,
254
+ finished: values.finished ?? null,
255
+ workMs: this._workTime(),
256
+ waitingSince: values.waitingSince ?? null,
257
+ tokens: copyValue(values.tokens) ?? null,
258
+ tokenBudget: finiteOrNull(values.tokenBudget),
259
+ cost: copyValue(values.cost) ?? null,
260
+ model: values.model ?? null,
261
+ actions: Array.isArray(values.actions) ? [...values.actions] : []
262
+ };
263
+ }
264
+
265
+ /** Stops the clock, removes what the component drew, and restores an enhanced target. @returns {void} */
266
+ destroy() {
267
+ if (this._destroyed) return;
268
+ this._destroyed = true;
269
+ this._stopTicker();
270
+ this._releaseFocus();
271
+ super.destroy();
272
+ if (this._original) restoreTarget(this.el, this._original);
273
+ }
274
+
275
+ /** @private @returns {number} Milliseconds on the clock the working time counts against. */
276
+ _clock() {
277
+ return typeof this.options.now === 'function' ? currentTime(this.options.now).getTime() : clock();
278
+ }
279
+
280
+ /** @private @returns {number|null} Milliseconds worked, including the time counted since the last update. */
281
+ _workTime() {
282
+ if (this._workBase === null) return null;
283
+ const counting = this._values.ticking !== false && normalizeRunState(this._values.state) === 'running';
284
+ return this._workBase + (counting ? Math.max(0, this._clock() - this._workAt) : 0);
285
+ }
286
+
287
+ /** @private @returns {void} */
288
+ _draw() {
289
+ const root = /** @type {HTMLElement} */ (this.el);
290
+ const values = this._values;
291
+ const state = normalizeRunState(values.state);
292
+ const mode = compactMode(values.compact);
293
+ const focus = this._focusKey();
294
+ if (root.ownerDocument.activeElement !== root) this._releaseFocus();
295
+ root.dataset.state = state;
296
+ if (mode) root.setAttribute('data-compact', mode === 'icon' ? 'icon' : '');
297
+ else root.removeAttribute('data-compact');
298
+ this._elapsed = null;
299
+ if (mode) {
300
+ this._actionsEl = null;
301
+ this._actionsKey = '';
302
+ const word = this.msg(STATUS[state].key);
303
+ this._place([h('span', { class: 'zx-run-status__pill', title: mode === 'icon' ? word : undefined },
304
+ ...this._stateParts(state))]);
305
+ this._restoreFocus(focus);
306
+ this._syncTicker();
307
+ return;
308
+ }
309
+ const steps = stepProgress(values.steps);
310
+ const summary = values.summary == null ? '' : String(values.summary);
311
+ const rows = this._rows(state);
312
+ this._place([
313
+ h('p', { class: 'zx-run-status__state' }, ...this._stateParts(state)),
314
+ summary ? h('p', { class: 'zx-run-status__summary' }, summary) : null,
315
+ steps ? this._steps(steps) : null,
316
+ this._actions(),
317
+ rows.length ? h('dl', { class: 'zx-run-status__props' }, rows.map(([key, value]) => h('div', { class: 'zx-run-status__prop' },
318
+ h('dt', { class: 'zx-run-status__label' }, this.msg(key)),
319
+ h('dd', { class: 'zx-run-status__value' }, value)))) : null
320
+ ]);
321
+ this._restoreFocus(focus);
322
+ this._syncTicker();
323
+ }
324
+
325
+ /**
326
+ * Puts the drawn parts in the root in order. A part kept from the last draw stays where it is
327
+ * rather than being taken out and put back, so focus inside it survives.
328
+ * @private
329
+ * @param {Array<Node|null>} parts
330
+ * @returns {void}
331
+ */
332
+ _place(parts) {
333
+ const root = /** @type {HTMLElement} */ (this.el);
334
+ const nodes = parts.filter((node) => node !== null);
335
+ const keep = new Set(nodes);
336
+ for (const node of Array.from(root.childNodes)) {
337
+ if (!keep.has(node)) node.remove();
338
+ }
339
+ let next = root.firstChild;
340
+ for (const node of nodes) {
341
+ if (node === next) next = next.nextSibling;
342
+ else root.insertBefore(node, next);
343
+ }
344
+ }
345
+
346
+ /**
347
+ * The action row: the one already drawn when the actions read the same, a new one otherwise.
348
+ * @private
349
+ * @returns {HTMLElement|null}
350
+ */
351
+ _actions() {
352
+ const actions = Array.isArray(this._values.actions) ? this._values.actions : [];
353
+ if (!actions.length) {
354
+ this._actionsEl = null;
355
+ this._actionsKey = '';
356
+ return null;
357
+ }
358
+ const key = JSON.stringify(actions.map((action) => [String(action?.label ?? ''), action?.kind ?? null, action?.icon ?? null]));
359
+ if (this._actionsEl && key === this._actionsKey) return this._actionsEl;
360
+ this._actionsKey = key;
361
+ this._actionsEl = h('div', { class: 'zx-run-status__actions' }, actions.map((action, index) => {
362
+ const element = button({
363
+ label: String(action?.label ?? ''), kind: action?.kind, icon: action?.icon ?? null, size: 'sm'
364
+ });
365
+ element.dataset.runAction = String(index);
366
+ return element;
367
+ }));
368
+ return this._actionsEl;
369
+ }
370
+
371
+ /**
372
+ * Where focus is inside the panel, in terms that survive a redraw: the index of an action, or
373
+ * of a focusable element among all of them.
374
+ * @private
375
+ * @returns {{action: number}|{focusable: number}|null} Null when focus is elsewhere, or on the root.
376
+ */
377
+ _focusKey() {
378
+ const root = /** @type {HTMLElement} */ (this.el);
379
+ const active = root.ownerDocument.activeElement;
380
+ if (!active || active === root || !root.contains(active)) return null;
381
+ const control = /** @type {HTMLElement|null} */ (active.closest('[data-run-action]'));
382
+ if (control && root.contains(control)) return { action: Number(control.dataset.runAction) };
383
+ const index = Array.from(root.querySelectorAll(FOCUSABLE)).indexOf(active);
384
+ return index >= 0 ? { focusable: index } : null;
385
+ }
386
+
387
+ /**
388
+ * Puts focus back after a redraw when the element that had it is gone: on the action at the same
389
+ * index or the nearest one left, else on the focusable at the same index, else on the root.
390
+ * @private
391
+ * @param {{action: number}|{focusable: number}|null} key What `_focusKey()` returned before the draw.
392
+ * @returns {void}
393
+ */
394
+ _restoreFocus(key) {
395
+ if (!key) return;
396
+ const root = /** @type {HTMLElement} */ (this.el);
397
+ const active = root.ownerDocument.activeElement;
398
+ if (active && active !== root.ownerDocument.body && root.contains(active)) return;
399
+ const pick = (/** @type {Element[]} */ list, /** @type {number} */ index) => list[Math.min(index, list.length - 1)] ?? null;
400
+ const target = 'action' in key
401
+ ? pick(Array.from(root.querySelectorAll('[data-run-action]')), key.action)
402
+ ?? pick(Array.from(root.querySelectorAll(FOCUSABLE)), 0)
403
+ : pick(Array.from(root.querySelectorAll(FOCUSABLE)), key.focusable);
404
+ if (target instanceof HTMLElement) {
405
+ target.focus({ preventScroll: true });
406
+ return;
407
+ }
408
+ if (!root.hasAttribute('tabindex')) {
409
+ root.tabIndex = -1;
410
+ this._heldFocus = true;
411
+ }
412
+ root.focus({ preventScroll: true });
413
+ }
414
+
415
+ /** @private Gives back the `tabindex` the root took to hold focus. @returns {void} */
416
+ _releaseFocus() {
417
+ if (!this._heldFocus) return;
418
+ this._heldFocus = false;
419
+ this.el.removeAttribute('tabindex');
420
+ }
421
+
422
+ /** @private @param {RunState} state @returns {Node[]} The state's glyph and its word. */
423
+ _stateParts(state) {
424
+ const entry = STATUS[state];
425
+ return [
426
+ statusIcon(entry.status, { tone: /** @type {import('../select/glyphs.js').StatusTone} */ (entry.tone) }),
427
+ h('span', { class: 'zx-run-status__word' }, this.msg(entry.key))
428
+ ];
429
+ }
430
+
431
+ /** @private @param {{done: number, total: number, percent: number}} steps @returns {HTMLElement} */
432
+ _steps(steps) {
433
+ const locale = this.options.locale;
434
+ const done = formatNumber(steps.done, { locale });
435
+ const total = formatNumber(steps.total, { locale });
436
+ return h('div', { class: 'zx-run-status__steps' },
437
+ h('span', {
438
+ class: 'zx-run-status__bar',
439
+ role: 'progressbar',
440
+ 'aria-label': this.msg('runStatus.stepsLabel'),
441
+ 'aria-valuemin': '0',
442
+ 'aria-valuemax': String(steps.total),
443
+ 'aria-valuenow': String(steps.done),
444
+ 'aria-valuetext': this.msgPlural('runStatus.steps', steps.total, done, total)
445
+ }, h('span', { class: 'zx-run-status__bar-fill', style: { inlineSize: `${steps.percent}%` } })),
446
+ h('span', { class: 'zx-run-status__steps-text', 'aria-hidden': 'true' }, `${done}/${total}`));
447
+ }
448
+
449
+ /**
450
+ * The property rows that apply to the state: started, working time, waiting or blocked since,
451
+ * or finished, then model, tokens, and cost.
452
+ * @private
453
+ * @param {RunState} state
454
+ * @returns {Array<[string, Node|string|Array<Node>]>}
455
+ */
456
+ _rows(state) {
457
+ const values = this._values;
458
+ const locale = this.options.locale;
459
+ const keys = runTimeKeys(state);
460
+ /** @type {Array<[string, Node|string|Array<Node>]>} */
461
+ const rows = [];
462
+ const started = this._time(values.started);
463
+ if (started) rows.push(['runStatus.started', started]);
464
+ const worked = this._workTime();
465
+ if (worked !== null) {
466
+ this._elapsed = h('span', { class: 'zx-run-status__elapsed' }, formatElapsed(worked));
467
+ rows.push(['runStatus.workingTime', this._elapsed]);
468
+ }
469
+ const since = keys.since ? this._time(values.waitingSince) : null;
470
+ if (since && keys.since) rows.push([keys.since, since]);
471
+ const finished = keys.finished ? this._time(values.finished) : null;
472
+ if (finished && keys.finished) rows.push([keys.finished, finished]);
473
+ if (values.model) rows.push(['runStatus.model', String(values.model)]);
474
+ const meter = tokenMeter(values.tokens, values.tokenBudget, { locale, template: this.msg('runStatus.tokenBudget') });
475
+ if (meter) {
476
+ rows.push(['runStatus.tokens', [
477
+ h('span', { class: 'zx-run-status__tokens', 'aria-hidden': 'true' }, meter.text),
478
+ this._meter(this.msg('runStatus.tokens'), meter.total, meter.budget, meter.text)
479
+ ]]);
480
+ } else {
481
+ const tokens = formatTokens(values.tokens, { locale, template: this.msg('runStatus.tokensValue') });
482
+ if (tokens) rows.push(['runStatus.tokens', tokens]);
483
+ }
484
+ const cost = this._cost(values.cost);
485
+ if (cost) rows.push(['runStatus.costLabel', cost]);
486
+ return rows;
487
+ }
488
+
489
+ /** @private @param {unknown} value @returns {HTMLElement|null} A `<time>` with the clock time, and the date when it is not today. */
490
+ _time(value) {
491
+ const date = runDate(value);
492
+ if (!date) return null;
493
+ const format = isSameDay(date, currentTime(this.options.now)) ? 'runStatus.timeFormat' : 'runStatus.dateTimeFormat';
494
+ return h('time', { datetime: formatDate(date, '%Y-%m-%dT%H:%M:%S') }, formatDate(date, this.msg(format)));
495
+ }
496
+
497
+ /** @private @param {unknown} cost @returns {Node[]|null} The cost, and a meter against the budget when there is one. */
498
+ _cost(cost) {
499
+ const text = formatRunCost(cost, { locale: this.options.locale, template: this.msg('runStatus.cost') });
500
+ if (!text) return null;
501
+ const { amount, budget } = /** @type {RunCost} */ (cost);
502
+ const limit = Number(budget);
503
+ if (!(limit > 0)) return [h('span', { class: 'zx-run-status__cost' }, text)];
504
+ return [
505
+ h('span', { class: 'zx-run-status__cost', 'aria-hidden': 'true' }, text),
506
+ this._meter(this.msg('runStatus.costLabel'), Math.max(0, Number(amount) || 0), limit, text)
507
+ ];
508
+ }
509
+
510
+ /**
511
+ * A thin `role="meter"` bar of a value against its limit, toned by how close it is.
512
+ * @private
513
+ * @param {string} label
514
+ * @param {number} value
515
+ * @param {number} limit
516
+ * @param {string} text The value in words, its `aria-valuetext`.
517
+ * @returns {HTMLElement}
518
+ */
519
+ _meter(label, value, limit, text) {
520
+ return h('span', {
521
+ class: 'zx-run-status__meter',
522
+ role: 'meter',
523
+ 'aria-label': label,
524
+ 'aria-valuemin': '0',
525
+ 'aria-valuemax': String(limit),
526
+ 'aria-valuenow': String(Math.min(value, limit)),
527
+ 'aria-valuetext': text,
528
+ dataset: { level: costLevel(value, limit) }
529
+ }, h('span', { class: 'zx-run-status__meter-fill', style: { inlineSize: `${Math.min(100, (value / limit) * 100)}%` } }));
530
+ }
531
+
532
+ /** @private @returns {boolean} Whether the working time should count on screen now. */
533
+ _shouldTick() {
534
+ return !this._destroyed
535
+ && this._values.ticking !== false
536
+ && normalizeRunState(this._values.state) === 'running'
537
+ && this._elapsed !== null
538
+ && !this.el.ownerDocument.hidden;
539
+ }
540
+
541
+ /** @private @returns {void} */
542
+ _syncTicker() {
543
+ if (this._shouldTick()) {
544
+ if (!this._interval) this._interval = setInterval(() => this._tick(), 1000);
545
+ } else {
546
+ this._stopTicker();
547
+ }
548
+ }
549
+
550
+ /** @private @returns {void} */
551
+ _stopTicker() {
552
+ if (this._interval) clearInterval(this._interval);
553
+ this._interval = 0;
554
+ }
555
+
556
+ /** @private @returns {void} */
557
+ _tick() {
558
+ const worked = this._workTime();
559
+ if (this._elapsed && worked !== null) this._elapsed.textContent = formatElapsed(worked);
560
+ }
561
+
562
+ /** @private @param {MouseEvent} event @returns {void} */
563
+ _onClick(event) {
564
+ const target = event.target instanceof Element ? event.target : null;
565
+ const control = /** @type {HTMLElement|null} */ (target?.closest('[data-run-action]') ?? null);
566
+ if (!control || !this.el.contains(control)) return;
567
+ const index = Number(control.dataset.runAction);
568
+ const action = /** @type {RunStatusAction|undefined} */ (this._values.actions?.[index]);
569
+ if (!action) return;
570
+ if (typeof action.onclick === 'function') action.onclick(event);
571
+ this.emit('action', { index, action });
572
+ }
573
+ }
574
+
575
+ /**
576
+ * Fired when one of the run's action buttons is activated.
577
+ * @event RunStatus#action
578
+ * @type {CustomEvent<{index: number, action: RunStatusAction}>}
579
+ */
580
+
581
+ /** @returns {number} A monotonic clock in milliseconds. */
582
+ function clock() {
583
+ return typeof performance === 'object' && typeof performance.now === 'function' ? performance.now() : Date.now();
584
+ }
585
+
586
+ /** @param {unknown} value @returns {number|null} */
587
+ function finiteOrNull(value) {
588
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
589
+ }
590
+
591
+ /**
592
+ * A shallow copy, so the options and later updates are never mutated or shared.
593
+ * @template T
594
+ * @param {T} value
595
+ * @returns {T}
596
+ */
597
+ function copyValue(value) {
598
+ if (Array.isArray(value)) return /** @type {T} */ ([...value]);
599
+ if (value && typeof value === 'object' && !(value instanceof Date)) return /** @type {T} */ ({ ...value });
600
+ return value;
601
+ }
602
+
603
+ /**
604
+ * How close a run's cost is to its budget: `'warning'` from 80%, `'danger'` at 100% and over,
605
+ * `'normal'` below, and without a budget.
606
+ * @param {number} amount
607
+ * @param {number|null|undefined} budget
608
+ * @returns {'normal'|'warning'|'danger'}
609
+ */
610
+ export function costLevel(amount, budget) {
611
+ const limit = Number(budget);
612
+ const spent = Number(amount);
613
+ if (!(limit > 0) || !Number.isFinite(spent)) return 'normal';
614
+ const ratio = spent / limit;
615
+ if (ratio >= 1) return 'danger';
616
+ if (ratio >= 0.8) return 'warning';
617
+ return 'normal';
618
+ }
619
+
620
+ /**
621
+ * Reads a steps count: whole numbers, the done count kept within the total. Null for no steps.
622
+ * @param {unknown} steps `{done, total}`.
623
+ * @returns {{done: number, total: number, percent: number}|null}
624
+ */
625
+ export function stepProgress(steps) {
626
+ if (!steps || typeof steps !== 'object') return null;
627
+ const { done, total } = /** @type {{done?: unknown, total?: unknown}} */ (steps);
628
+ const all = Math.max(0, Math.floor(Number(total) || 0));
629
+ if (all === 0) return null;
630
+ const finished = Math.min(all, Math.max(0, Math.floor(Number(done) || 0)));
631
+ return { done: finished, total: all, percent: Math.round((finished / all) * 100) };
632
+ }
633
+
634
+ /**
635
+ * Token counts in words: "18,420 in · 1,236 out" for a pair, "22,840" for a total. Empty without
636
+ * counts.
637
+ * @param {unknown} tokens `[input, output]`, or the total as one number.
638
+ * @param {{locale?: string, template?: string}} [options={}] `template` takes the two formatted
639
+ * counts of a pair as `%1` and `%2`.
640
+ * @returns {string}
641
+ */
642
+ export function formatTokens(tokens, options = {}) {
643
+ if (typeof tokens === 'number') {
644
+ return Number.isFinite(tokens) ? formatNumber(Math.max(0, tokens), { locale: options.locale }) : '';
645
+ }
646
+ if (!Array.isArray(tokens) || tokens.length < 2) return '';
647
+ const counts = tokens.slice(0, 2).map((count) => Math.max(0, Number(count) || 0));
648
+ return printf(options.template ?? MESSAGES['runStatus.tokensValue'],
649
+ counts.map((count) => formatNumber(count, { locale: options.locale })));
650
+ }
651
+
652
+ /**
653
+ * How many tokens a run has used in all: the number itself, or input and output added up.
654
+ * @param {unknown} tokens `[input, output]`, or the total as one number.
655
+ * @returns {number|null} Null without counts.
656
+ */
657
+ export function tokenTotal(tokens) {
658
+ if (typeof tokens === 'number') return Number.isFinite(tokens) ? Math.max(0, tokens) : null;
659
+ if (!Array.isArray(tokens) || tokens.length < 2) return null;
660
+ return tokens.slice(0, 2).reduce((sum, count) => sum + Math.max(0, Number(count) || 0), 0);
661
+ }
662
+
663
+ /**
664
+ * A count in the locale's compact notation (`Intl.NumberFormat` with `notation: 'compact'`) and at
665
+ * most one decimal: "22.8K", "60K", "1.2M" in English, "22.840" in German, which has no compact
666
+ * form for thousands.
667
+ * @param {number} value
668
+ * @param {{locale?: string}} [options={}]
669
+ * @returns {string} Empty for anything that is not a finite number.
670
+ */
671
+ export function formatCompactNumber(value, options = {}) {
672
+ if (typeof value !== 'number' || !Number.isFinite(value)) return '';
673
+ const number = value;
674
+ /** @type {Intl.NumberFormatOptions} */
675
+ const format = { notation: 'compact', maximumFractionDigits: 1 };
676
+ try {
677
+ return new Intl.NumberFormat(options.locale ?? getLanguage(), format).format(number);
678
+ } catch {
679
+ return new Intl.NumberFormat(undefined, format).format(number);
680
+ }
681
+ }
682
+
683
+ /**
684
+ * The tokens as a meter against their budget: the total, the budget, the level (`warning` from
685
+ * 80%, `danger` at 100%, as for the cost), and the words "22.8K of 60K tokens". Null without
686
+ * counts or without a budget above zero, when the tokens stay text.
687
+ * @param {unknown} tokens `[input, output]`, or the total as one number.
688
+ * @param {unknown} budget The most tokens the run may use.
689
+ * @param {{locale?: string, template?: string}} [options={}] `template` takes the compact total and
690
+ * budget as `%1` and `%2`.
691
+ * @returns {RunTokenMeter|null}
692
+ */
693
+ export function tokenMeter(tokens, budget, options = {}) {
694
+ const total = tokenTotal(tokens);
695
+ const limit = typeof budget === 'number' ? budget : Number.NaN;
696
+ if (total === null || !(limit > 0) || !Number.isFinite(limit)) return null;
697
+ const locale = options.locale;
698
+ return {
699
+ total,
700
+ budget: limit,
701
+ level: costLevel(total, limit),
702
+ text: printf(options.template ?? MESSAGES['runStatus.tokenBudget'],
703
+ [formatCompactNumber(total, { locale }), formatCompactNumber(limit, { locale })])
704
+ };
705
+ }
706
+
707
+ /**
708
+ * Reads the `compact` option: `'icon'` for the glyph alone, `'word'` for any other truthy value
709
+ * (the pill of glyph and word), null for the full panel.
710
+ * @param {unknown} value
711
+ * @returns {RunCompactMode|null}
712
+ */
713
+ export function compactMode(value) {
714
+ if (value === 'icon') return 'icon';
715
+ return value ? 'word' : null;
716
+ }
717
+
718
+ /**
719
+ * The message keys of the time rows a state shows besides "Started": the "since" row while the
720
+ * run is held (`waiting`: "Waiting since", `blocked`: "Blocked since"), and the "finished" row
721
+ * once it is over ("Finished", "Failed at", "Stopped at"). A blocked run is not over, so it never
722
+ * shows a finished row.
723
+ * @param {unknown} state
724
+ * @returns {{since: string|null, finished: string|null}}
725
+ */
726
+ export function runTimeKeys(state) {
727
+ const known = normalizeRunState(state);
728
+ return {
729
+ since: SINCE_KEYS[/** @type {keyof typeof SINCE_KEYS} */ (known)] ?? null,
730
+ finished: FINISHED_KEYS[/** @type {keyof typeof FINISHED_KEYS} */ (known)] ?? null
731
+ };
732
+ }
733
+
734
+ /**
735
+ * Reads the `now` option: the date its function returns (a `Date` or a millisecond timestamp),
736
+ * or the real time when there is no function or it returns nothing usable.
737
+ * @param {unknown} now
738
+ * @returns {Date}
739
+ */
740
+ export function currentTime(now) {
741
+ if (typeof now === 'function') {
742
+ const value = now();
743
+ const date = value instanceof Date ? new Date(value.getTime()) : typeof value === 'number' ? new Date(value) : null;
744
+ if (date && !Number.isNaN(date.getTime())) return date;
745
+ }
746
+ return new Date();
747
+ }
748
+
749
+ /**
750
+ * A run's cost in words: "€0.14 of €2.00" against a budget, "€0.14" without one. Empty without a
751
+ * cost.
752
+ * @param {unknown} cost `{amount, budget?, currency?}`.
753
+ * @param {{locale?: string, template?: string}} [options={}] `template` takes the amount and the
754
+ * budget as `%1` and `%2`.
755
+ * @returns {string}
756
+ */
757
+ export function formatRunCost(cost, options = {}) {
758
+ if (!cost || typeof cost !== 'object') return '';
759
+ const { amount, budget, currency } = /** @type {RunCost} */ (cost);
760
+ if (!Number.isFinite(Number(amount))) return '';
761
+ const spent = formatCurrency(Number(amount), currency, { locale: options.locale });
762
+ const limit = Number(budget);
763
+ if (budget == null || !(limit > 0)) return spent;
764
+ return printf(options.template ?? MESSAGES['runStatus.cost'], [spent, formatCurrency(limit, currency, { locale: options.locale })]);
765
+ }
766
+
767
+ /**
768
+ * Reads a run time: a `Date`, or a local ISO date-time string (`2026-09-29T11:20:04`; a bare date
769
+ * is midnight local time). Null for anything else.
770
+ * @param {unknown} value
771
+ * @returns {Date|null}
772
+ */
773
+ export function runDate(value) {
774
+ /** @type {Date|null} */
775
+ let date = null;
776
+ if (value instanceof Date) date = new Date(value.getTime());
777
+ else if (typeof value === 'string' && value.trim()) {
778
+ const text = value.trim();
779
+ date = new Date(/^\d{4}-\d{2}-\d{2}$/.test(text) ? `${text}T00:00` : text);
780
+ }
781
+ return date && !Number.isNaN(date.getTime()) ? date : null;
782
+ }