@zeyos/zx 5.6.0 → 5.7.1
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.
- package/CHANGELOG.md +188 -0
- package/README.md +73 -7
- package/bin/zx-css.js +328 -0
- package/dist/types/components/account-menu/account-menu.d.ts +4 -2
- package/dist/types/components/activity-list/activity-list.d.ts +14 -8
- package/dist/types/components/agent-thread/ag-ui.d.ts +340 -0
- package/dist/types/components/agent-thread/agent-thread.d.ts +142 -14
- package/dist/types/components/agent-thread/ui-message-stream.d.ts +401 -0
- package/dist/types/components/app-sidebar/app-sidebar.d.ts +14 -8
- package/dist/types/components/breadcrumb/breadcrumb.d.ts +3 -3
- package/dist/types/components/calendar/calendar-model.d.ts +9 -2
- package/dist/types/components/calendar/calendar.d.ts +12 -4
- package/dist/types/components/chart/chart.d.ts +25 -13
- package/dist/types/components/checklist/checklist.d.ts +29 -0
- package/dist/types/components/code-editor/code-editor.d.ts +7 -2
- package/dist/types/components/composer/composer.d.ts +206 -4
- package/dist/types/components/composer/queue.d.ts +76 -0
- package/dist/types/components/copy/copy-button.d.ts +6 -4
- package/dist/types/components/copy/copy-input.d.ts +10 -6
- package/dist/types/components/datebox/date-range-box.d.ts +33 -0
- package/dist/types/components/datebox/placeholder.d.ts +7 -0
- package/dist/types/components/dialog/dialog.d.ts +2 -2
- package/dist/types/components/dock/dock.d.ts +12 -3
- package/dist/types/components/entity-ref/entity-ref.d.ts +5 -3
- package/dist/types/components/field-upload/field-upload.d.ts +3 -2
- package/dist/types/components/file-item/file-item.d.ts +3 -2
- package/dist/types/components/file-list/file-list.d.ts +14 -8
- package/dist/types/components/filter/filter-model.d.ts +31 -1
- package/dist/types/components/filter/filter.d.ts +20 -2
- package/dist/types/components/finder/finder.d.ts +14 -6
- package/dist/types/components/flag/flag.d.ts +99 -0
- package/dist/types/components/grid/grid.d.ts +1 -1
- package/dist/types/components/kanban-view/kanban-view.d.ts +8 -66
- package/dist/types/components/launcher/launcher.d.ts +2 -0
- package/dist/types/components/modal/modal.d.ts +34 -8
- package/dist/types/components/multi-value-editor/multi-value-editor.d.ts +3 -2
- package/dist/types/components/number-field/number-field.d.ts +41 -7
- package/dist/types/components/prompt-starters/prompt-starters.d.ts +107 -0
- package/dist/types/components/prose/prose.d.ts +9 -6
- package/dist/types/components/questionnaire/conditions.d.ts +270 -0
- package/dist/types/components/questionnaire/items.d.ts +52 -30
- package/dist/types/components/questionnaire/questionnaire.d.ts +44 -4
- package/dist/types/components/rating/rating.d.ts +5 -3
- package/dist/types/components/select/country.d.ts +106 -0
- package/dist/types/components/select/field-adapter.d.ts +2 -1
- package/dist/types/components/select/locale.d.ts +102 -0
- package/dist/types/components/select/select.d.ts +41 -2
- package/dist/types/components/sheet/sheet.d.ts +2 -2
- package/dist/types/components/slider/slider.d.ts +1 -0
- package/dist/types/components/sort-control/sort-control.d.ts +7 -3
- package/dist/types/components/source-list/source-list.d.ts +7 -5
- package/dist/types/components/split-view/split-view.d.ts +5 -3
- package/dist/types/components/surface/catalog.d.ts +260 -0
- package/dist/types/components/surface/elicit.d.ts +81 -0
- package/dist/types/components/surface/mcp.d.ts +165 -0
- package/dist/types/components/surface/schema.d.ts +314 -0
- package/dist/types/components/surface/stream.d.ts +118 -0
- package/dist/types/components/surface/surface.d.ts +718 -0
- package/dist/types/components/surface/text.d.ts +277 -0
- package/dist/types/components/surface/validate.d.ts +339 -0
- package/dist/types/components/table/table.d.ts +55 -3
- package/dist/types/components/table/window.d.ts +203 -0
- package/dist/types/components/toolbar/toolbar.d.ts +10 -6
- package/dist/types/components/tooltip/tooltip.d.ts +2 -2
- package/dist/types/components/tree/tree.d.ts +20 -13
- package/dist/types/core/component.d.ts +10 -0
- package/dist/types/core/date.d.ts +8 -1
- package/dist/types/core/dom.d.ts +15 -0
- package/dist/types/core/http.d.ts +10 -0
- package/dist/types/core/i18n.d.ts +38 -0
- package/dist/types/core/messages.d.ts +344 -1
- package/dist/types/core/storage.d.ts +7 -2
- package/dist/types/elements/define.d.ts +21 -46
- package/dist/types/elements/definitions.d.ts +147 -0
- package/dist/types/elements/kit.d.ts +7 -0
- package/dist/types/elements/reflect.d.ts +6 -3
- package/dist/types/index.d.ts +10 -1
- package/dist/types/internal/date-locale.d.ts +7 -0
- package/dist/types/internal/json-patch.d.ts +146 -0
- package/dist/types/locales/de.d.ts +13 -0
- package/dist/types/locales/en.d.ts +2 -0
- package/dist/types/locales/index.d.ts +823 -0
- package/dist/types/zeyos/view.d.ts +8 -1
- package/dist/zx-zeyos.esm.js +16852 -15131
- package/dist/zx-zeyos.esm.min.js +5 -5
- package/dist/zx.core.css +1276 -0
- package/dist/zx.core.min.css +1 -0
- package/dist/zx.css +520 -143
- package/dist/zx.esm.js +40940 -29684
- package/dist/zx.esm.min.js +36 -23
- package/dist/zx.global.js +40940 -29684
- package/dist/zx.global.min.js +36 -23
- package/dist/zx.layered.css +17315 -0
- package/dist/zx.layered.min.css +1 -0
- package/dist/zx.min.css +1 -1
- package/docs/agent-catalog.json +12501 -0
- package/docs/agent-surfaces.md +340 -0
- package/docs/api.json +909 -137
- package/docs/llms.md +1046 -80
- package/docs/llms.txt +30 -9
- package/package.json +29 -6
- package/src/components/account-menu/account-menu.js +6 -3
- package/src/components/activity-item/activity-item.js +2 -1
- package/src/components/activity-list/activity-list.js +16 -10
- package/src/components/agent-thread/ag-ui.js +1439 -0
- package/src/components/agent-thread/agent-thread.js +359 -54
- package/src/components/agent-thread/ui-message-stream.js +1281 -0
- package/src/components/app-sidebar/app-sidebar.js +18 -8
- package/src/components/approval-card/approval-card.js +3 -2
- package/src/components/block-view/block-view.js +7 -6
- package/src/components/breadcrumb/breadcrumb.js +8 -5
- package/src/components/button/button.css +24 -11
- package/src/components/calendar/calendar-model.js +8 -2
- package/src/components/calendar/calendar.js +53 -18
- package/src/components/chart/chart.js +54 -23
- package/src/components/checklist/checklist.css +9 -1
- package/src/components/checklist/checklist.js +59 -3
- package/src/components/checklist/field-adapter.js +2 -11
- package/src/components/code-editor/code-editor.js +45 -8
- package/src/components/code-editor/field-adapter.js +1 -1
- package/src/components/composer/composer.css +80 -1
- package/src/components/composer/composer.js +390 -16
- package/src/components/composer/queue.js +78 -0
- package/src/components/context-menu/context-menu.js +12 -1
- package/src/components/copy/copy-button.js +9 -7
- package/src/components/copy/copy-input.js +10 -6
- package/src/components/date-picker/date-picker.js +2 -1
- package/src/components/date-picker/date-range-picker.js +8 -7
- package/src/components/datebox/date-range-box.js +3 -9
- package/src/components/datebox/datebox.js +18 -21
- package/src/components/datebox/placeholder.js +18 -0
- package/src/components/dialog/dialog.js +4 -5
- package/src/components/dock/dock.js +34 -13
- package/src/components/entity-ref/entity-ref.js +16 -5
- package/src/components/field-upload/field-upload.js +81 -38
- package/src/components/file-item/file-item.js +70 -40
- package/src/components/file-list/file-list.js +15 -9
- package/src/components/filter/filter-model.js +46 -8
- package/src/components/filter/filter.css +3 -3
- package/src/components/filter/filter.js +29 -10
- package/src/components/filter-panel/filter-panel.js +13 -5
- package/src/components/finder/finder.js +50 -26
- package/src/components/flag/flag.css +40 -0
- package/src/components/flag/flag.js +177 -0
- package/src/components/form/form.js +1 -1
- package/src/components/grid/grid.js +22 -8
- package/src/components/kanban-view/kanban-view.js +51 -81
- package/src/components/launcher/launcher.js +17 -2
- package/src/components/list-toolbar/list-toolbar.js +2 -1
- package/src/components/master-panel/master-panel.js +1 -1
- package/src/components/menu-button/menu-button.js +4 -0
- package/src/components/message/message.js +3 -0
- package/src/components/modal/modal.js +62 -8
- package/src/components/multi-value-editor/multi-value-editor.js +10 -9
- package/src/components/navigation-bar/navigation-bar.js +3 -3
- package/src/components/number-field/number-field.js +98 -29
- package/src/components/prompt-starters/prompt-starters.css +91 -0
- package/src/components/prompt-starters/prompt-starters.js +206 -0
- package/src/components/prose/prose.js +14 -10
- package/src/components/questionnaire/conditions.js +666 -0
- package/src/components/questionnaire/items.js +150 -41
- package/src/components/questionnaire/questionnaire.js +126 -32
- package/src/components/rating/rating.js +5 -4
- package/src/components/run-status/run-status.js +2 -2
- package/src/components/select/country.js +136 -0
- package/src/components/select/field-adapter.js +7 -2
- package/src/components/select/locale.js +219 -0
- package/src/components/select/select.css +20 -22
- package/src/components/select/select.js +94 -12
- package/src/components/sheet/sheet-stack.js +10 -1
- package/src/components/sheet/sheet.js +12 -5
- package/src/components/slider/slider.js +7 -2
- package/src/components/sort-control/sort-control.js +15 -5
- package/src/components/source-list/source-list.js +7 -4
- package/src/components/split-view/split-view.js +5 -3
- package/src/components/surface/catalog.js +1334 -0
- package/src/components/surface/elicit.js +107 -0
- package/src/components/surface/mcp.js +243 -0
- package/src/components/surface/schema.js +644 -0
- package/src/components/surface/stream.js +245 -0
- package/src/components/surface/surface.css +308 -0
- package/src/components/surface/surface.js +2291 -0
- package/src/components/surface/text.js +513 -0
- package/src/components/surface/validate.js +2218 -0
- package/src/components/tabbox/tabbox.js +9 -0
- package/src/components/table/table.css +63 -3
- package/src/components/table/table.js +167 -28
- package/src/components/table/window.js +317 -0
- package/src/components/toolbar/toolbar.js +12 -7
- package/src/components/tooltip/tooltip.css +2 -3
- package/src/components/tooltip/tooltip.js +32 -5
- package/src/components/tree/tree.js +53 -23
- package/src/core/component.js +25 -1
- package/src/core/date.js +62 -16
- package/src/core/dom.js +67 -4
- package/src/core/format.js +15 -13
- package/src/core/http.js +29 -20
- package/src/core/i18n.js +83 -10
- package/src/core/icons.js +13 -2
- package/src/core/keyboard.js +79 -8
- package/src/core/messages.js +376 -2
- package/src/core/overlay-host.js +1 -0
- package/src/core/position.js +3 -2
- package/src/core/storage.js +59 -6
- package/src/elements/define.js +178 -130
- package/src/elements/definitions.js +229 -0
- package/src/elements/kit.js +444 -0
- package/src/elements/reflect.js +8 -3
- package/src/index.js +10 -1
- package/src/internal/date-locale.js +11 -0
- package/src/internal/json-patch.js +405 -0
- package/src/locales/de.js +911 -0
- package/src/locales/en.js +2 -0
- package/src/locales/index.js +7 -0
- package/src/zeyos/calendar.js +2 -1
- package/src/zeyos/form.js +2 -1
- package/src/zeyos/launcher.js +7 -6
- package/src/zeyos/module-bar.js +2 -1
- package/src/zeyos/schema.js +37 -23
- package/src/zeyos/select.js +4 -3
- package/src/zeyos/table.js +2 -13
- package/src/zeyos/view.js +57 -17
- package/styles/core.css +11 -0
- package/styles/tokens/semantic.css +1 -0
- package/styles/zeyos.css +2 -0
- package/styles/zx.css +4 -8
- package/styles/zx.layered.css +1 -0
|
@@ -0,0 +1,1281 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { uid } from '../../core/util.js';
|
|
3
|
+
import { formatDuration } from '../../internal/agent-model.js';
|
|
4
|
+
import { sourceHost, sourceHref } from '../source-list/source-list.js';
|
|
5
|
+
|
|
6
|
+
/** @typedef {import('./agent-thread.js').AgentThread} AgentThread */
|
|
7
|
+
/** @typedef {import('../block-view/block-view.js').BlockView} BlockView */
|
|
8
|
+
/** @typedef {import('../run-status/run-status.js').RunStatus} RunStatus */
|
|
9
|
+
/** @typedef {import('../../internal/agent-model.js').Author} Author */
|
|
10
|
+
/** @typedef {import('../../internal/agent-model.js').Block} Block */
|
|
11
|
+
/** @typedef {import('../../internal/agent-model.js').RunState} RunState */
|
|
12
|
+
/** @typedef {import('../../internal/agent-model.js').Source} Source */
|
|
13
|
+
/** @typedef {import('../../internal/agent-model.js').ThreadItem} ThreadItem */
|
|
14
|
+
/** @typedef {import('../../internal/agent-model.js').TraceStep} TraceStep */
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The version of the UI message stream this adapter implements: the value of the response header
|
|
18
|
+
* `x-vercel-ai-ui-message-stream`.
|
|
19
|
+
*/
|
|
20
|
+
export const UI_MESSAGE_STREAM_VERSION = 'v1';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* One parsed part of the stream: the JSON of an event, without its `data: ` framing. The `[DONE]`
|
|
24
|
+
* sentinel is the transport's and never reaches the adapter.
|
|
25
|
+
* @typedef {{type: string, [key: string]: any}} UiMessagePart
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A tool call as a tile renderer receives it: a copy, so a renderer changes nothing by holding on
|
|
30
|
+
* to it.
|
|
31
|
+
* @typedef {Object} ToolCall
|
|
32
|
+
* @property {string} id The tool call id.
|
|
33
|
+
* @property {string} name The tool's name.
|
|
34
|
+
* @property {unknown} args The input once it is complete; `null` before.
|
|
35
|
+
* @property {string} argsText The input as text; empty until it is complete when it was not
|
|
36
|
+
* streamed.
|
|
37
|
+
* @property {unknown} [result] What the tool returned.
|
|
38
|
+
* @property {string} [error] Why the call failed.
|
|
39
|
+
* @property {RunState} status `queued` while the input arrives, `waiting` for an approval, `running`
|
|
40
|
+
* until the result, then `done`, `failed`, `skipped` when it was denied, or `stopped`.
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @typedef {Object} UiMessageStreamOptions
|
|
45
|
+
* @property {RunStatus|null} [runStatus=null] A run status to keep up to date.
|
|
46
|
+
* @property {Record<string, Author>} [authors={}] Who writes; its first author who is not a person
|
|
47
|
+
* is the agent when `agent` is not given.
|
|
48
|
+
* @property {string|null} [agent=null] Author key of the assistant's output.
|
|
49
|
+
* @property {Record<string, (call: ToolCall) => ThreadItem|null>} [tools={}] Tiles by tool name: the
|
|
50
|
+
* application's renderer for a tool's calls, called at each status change. Its item joins the
|
|
51
|
+
* thread as `tool:<toolCallId>`, and the call's step links to it.
|
|
52
|
+
* @property {(approvalId: string, approved: boolean, reason?: string) => void} [onapproval] The
|
|
53
|
+
* person decided. The application sends the answer with its next request.
|
|
54
|
+
* @property {(name: string, data: unknown, id?: string) => void} [ondata] A `data-<name>` part. With
|
|
55
|
+
* an `id` it replaces the earlier value of that name and id. What went out here stays with the
|
|
56
|
+
* application: a `reset-step` takes back what was drawn, not what was delivered.
|
|
57
|
+
* @property {(metadata: unknown) => void} [onmetadata] Metadata of the message.
|
|
58
|
+
* @property {(part: UiMessagePart) => void} [onunknown] A part the adapter does not draw.
|
|
59
|
+
* @property {(error: Error) => void} [onerror] A part out of order, or a tile that failed.
|
|
60
|
+
* @property {boolean} [showReasoning=false] Shows the model's reasoning text. Without it the text
|
|
61
|
+
* is not kept, and the reasoning is one step that says how long it took.
|
|
62
|
+
*/
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @typedef {Object} UiMessageStreamConnection
|
|
66
|
+
* @property {(part: UiMessagePart) => void} handle Takes the next part of the stream.
|
|
67
|
+
* @property {(messageId?: string) => void} replay Says that the stream is about to be fed again from
|
|
68
|
+
* the `start` of the response it was reading, after a reconnect that returns the whole response:
|
|
69
|
+
* only the application knows that it reconnected. What that response drew goes, so that the replay
|
|
70
|
+
* rebuilds it, with nothing doubled and nothing reported. What earlier responses of the message drew
|
|
71
|
+
* stays, because a response is all a replay sends, and a decision stands. Without `messageId`, the
|
|
72
|
+
* message being read. A message this connection does not know is left alone.
|
|
73
|
+
* @property {() => void} destroy Stops listening. An answer still open is stopped, a pending
|
|
74
|
+
* approval expires, because no decision could reach the application any more, and a call still
|
|
75
|
+
* going is stopped, because nothing can settle it.
|
|
76
|
+
*/
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* @typedef {Object} MessageState
|
|
80
|
+
* @property {string} id The message id, which is also its first answer item's.
|
|
81
|
+
* @property {string[]} pieces The answer items that hold it, in thread order: the message id, then
|
|
82
|
+
* `<id>#2`, `<id>#3`. What it says next goes to the last.
|
|
83
|
+
* @property {boolean} writing Whether its last piece is streaming.
|
|
84
|
+
* @property {TraceStep[]} steps The message's steps, which its first piece shows.
|
|
85
|
+
* @property {Source[]} sources The message's sources.
|
|
86
|
+
* @property {string} listed The piece that lists them.
|
|
87
|
+
* @property {Set<unknown>} texts Text blocks not ended yet. An ended block's id is free again.
|
|
88
|
+
* @property {unknown} speaking The open block whose words are going out; null when none is.
|
|
89
|
+
* @property {Map<unknown, {text: string, ended: boolean}>} held What other open blocks said
|
|
90
|
+
* meanwhile, by block, in the order they began. Answers can only be written at their end, so blocks
|
|
91
|
+
* that stream side by side go out one after the other.
|
|
92
|
+
* @property {boolean} hasText Whether the last piece ends in text a new block has to be set apart
|
|
93
|
+
* from.
|
|
94
|
+
* @property {boolean} gap Whether the next text starts a new paragraph.
|
|
95
|
+
* @property {boolean} drawn Whether the first piece has steps on screen.
|
|
96
|
+
* @property {boolean} failed Whether the run reported an error.
|
|
97
|
+
* @property {boolean} closed Whether it finished or was stopped.
|
|
98
|
+
* @property {boolean} implied Whether its `start` is still to come: a part created it ahead of its
|
|
99
|
+
* `start`, or a replay is about to send it again.
|
|
100
|
+
* @property {boolean} replaying Whether its latest response is being sent again.
|
|
101
|
+
* @property {boolean} quiet Whether the response that resumed it has written nothing yet.
|
|
102
|
+
* @property {number} writes Counts what it wrote, so that a step can tell it wrote nothing.
|
|
103
|
+
* @property {ThinkingState|null} thinking Its reasoning.
|
|
104
|
+
* @property {CallState[]} calls The calls it began, in order.
|
|
105
|
+
* @property {string[]} notices The error notices drawn while it was open, in order.
|
|
106
|
+
* @property {StepMark} mark Where its current step began.
|
|
107
|
+
* @property {StepMark} response Where its latest response began.
|
|
108
|
+
*/
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* A point in a message that it can go back to: where a step or a response began. Everything added
|
|
112
|
+
* since is what `reset-step` and `replay()` take back. A call belongs to the step that began it, and
|
|
113
|
+
* its tile and card go with it; an earlier call the step only moved on stays, as it does on the
|
|
114
|
+
* protocol's own client.
|
|
115
|
+
* @typedef {Object} StepMark
|
|
116
|
+
* @property {number} at When it was taken, among the connection's marks.
|
|
117
|
+
* @property {number} calls How many calls the message had begun.
|
|
118
|
+
* @property {number} notices How many notices it had drawn.
|
|
119
|
+
* @property {number} pieces How many pieces the message had.
|
|
120
|
+
* @property {Block[]} blocks What its last piece showed.
|
|
121
|
+
* @property {number} sources How many sources it had.
|
|
122
|
+
* @property {{ms: number, text: string}|null} thought Its reasoning so far, if it had any.
|
|
123
|
+
* @property {Pick<MessageState, 'writing'|'hasText'|'gap'|'failed'|'quiet'>} state Where its text
|
|
124
|
+
* stood.
|
|
125
|
+
* @property {number} writes What it had written.
|
|
126
|
+
*/
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* @typedef {Object} ThinkingState
|
|
130
|
+
* @property {TraceStep} step The one step all the message's reasoning shares.
|
|
131
|
+
* @property {Set<unknown>} open Reasoning blocks not ended yet.
|
|
132
|
+
* @property {number|null} since When the running stretch began.
|
|
133
|
+
* @property {number} ms Time spent in finished stretches.
|
|
134
|
+
* @property {string} text The reasoning text; only with `showReasoning`.
|
|
135
|
+
*/
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* @typedef {Object} CallState
|
|
139
|
+
* @property {string} id The tool call id.
|
|
140
|
+
* @property {string} name The tool's name.
|
|
141
|
+
* @property {MessageState} message The message it belongs to, also from a later response.
|
|
142
|
+
* @property {RunState} status Where it stands.
|
|
143
|
+
* @property {unknown} args The complete input.
|
|
144
|
+
* @property {string} argsText The input text so far.
|
|
145
|
+
* @property {unknown} [result] The output.
|
|
146
|
+
* @property {string} [error] The error text.
|
|
147
|
+
* @property {number|null} since When it began running.
|
|
148
|
+
* @property {TraceStep} step Its step.
|
|
149
|
+
* @property {string|null} tile The tile's item id, once drawn.
|
|
150
|
+
*/
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* @typedef {Object} ApprovalState
|
|
154
|
+
* @property {string} id The approval id.
|
|
155
|
+
* @property {CallState} call The call it holds.
|
|
156
|
+
* @property {MessageState|null} by The message being read when it was drawn.
|
|
157
|
+
* @property {number} at How many marks had been taken when it was drawn.
|
|
158
|
+
* @property {boolean} settled Whether nothing can be decided any more.
|
|
159
|
+
*/
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* An answer to an approval, from the person or recorded in the stream.
|
|
163
|
+
* @typedef {Object} Decision
|
|
164
|
+
* @property {boolean} approved Whether it was approved.
|
|
165
|
+
* @property {string} [reason] Why it was rejected.
|
|
166
|
+
* @property {string} [at] When, as the card says it.
|
|
167
|
+
*/
|
|
168
|
+
|
|
169
|
+
/** @param {unknown} value @returns {string} A tool's input or output as text. */
|
|
170
|
+
function asText(value) {
|
|
171
|
+
if (value === undefined) return '';
|
|
172
|
+
return typeof value === 'string' ? value : JSON.stringify(value, null, 2);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* What a card that holds a decision shows.
|
|
177
|
+
* @param {Decision} decision
|
|
178
|
+
* @returns {{status: 'approved'|'rejected', rejectReason?: string, answeredAt?: string}}
|
|
179
|
+
*/
|
|
180
|
+
function cardOf({ approved, reason, at }) {
|
|
181
|
+
return { status: approved ? 'approved' : 'rejected', ...(reason ? { rejectReason: reason } : {}), ...(at ? { answeredAt: at } : {}) };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* The name of a file part: its own, or the last segment of an `http(s)` address. The address is
|
|
186
|
+
* only read, never loaded, and a `data:` address has no name to give.
|
|
187
|
+
* @param {UiMessagePart} part
|
|
188
|
+
* @returns {string}
|
|
189
|
+
*/
|
|
190
|
+
function fileName(part) {
|
|
191
|
+
if (typeof part.filename === 'string' && part.filename.trim()) return part.filename.trim();
|
|
192
|
+
try {
|
|
193
|
+
const url = new URL(String(part.url));
|
|
194
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:') return '';
|
|
195
|
+
return decodeURIComponent(url.pathname.split('/').filter(Boolean).at(-1) ?? '');
|
|
196
|
+
} catch {
|
|
197
|
+
return '';
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The source a `source-url` or `source-document` part stands for. A link is kept only when it is
|
|
203
|
+
* `https:` and passes `safeHref()`; without one the source stays, so `[n]` citations keep counting
|
|
204
|
+
* the same sources, and it opens nothing.
|
|
205
|
+
* @param {UiMessagePart} part
|
|
206
|
+
* @returns {Source}
|
|
207
|
+
*/
|
|
208
|
+
function sourceOf(part) {
|
|
209
|
+
const id = String(part.sourceId);
|
|
210
|
+
const title = typeof part.title === 'string' ? part.title.trim() : '';
|
|
211
|
+
if (part.type === 'source-document') {
|
|
212
|
+
const name = String(part.filename || part.mediaType || '');
|
|
213
|
+
return { id, kind: 'file', title: title || name, site: name };
|
|
214
|
+
}
|
|
215
|
+
const link = { id, title, kind: /** @type {const} */ ('web'), href: part.url };
|
|
216
|
+
const href = sourceHref(link);
|
|
217
|
+
if (!href) return { id, kind: 'web', title: title || String(part.url ?? '') };
|
|
218
|
+
const site = /** @type {string} */ (sourceHost(link));
|
|
219
|
+
return { id, kind: 'web', title: title || site, site, href };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Draws an AI SDK UI message stream in an AgentThread: text, reasoning, tool calls and their
|
|
224
|
+
* approvals, sources, and files. The application owns the request, the event source, retries, and
|
|
225
|
+
* authentication; it strips the `data: ` framing and the `[DONE]` sentinel and hands each parsed
|
|
226
|
+
* part to `handle()`, so the adapter runs with any transport and without a network.
|
|
227
|
+
*
|
|
228
|
+
* Keep one connection for the whole conversation: an approval's answer goes out with the
|
|
229
|
+
* application's next request, and the response to it continues the same message. A `start` for an
|
|
230
|
+
* answer the connection did not draw, restored with the conversation, takes it over, and nothing in
|
|
231
|
+
* the thread is overwritten: a `start` naming any other item opens an answer of its own.
|
|
232
|
+
*
|
|
233
|
+
* The thread stays in stream order. What a message says after a card, a tile, or another item it
|
|
234
|
+
* cannot write above continues in a new answer `<messageId>#<n>`, counting from 2, which the thread
|
|
235
|
+
* draws as the same turn. A `reset-step` takes back what the step drew, whichever answers it reached.
|
|
236
|
+
*
|
|
237
|
+
* Model output is data. Nothing is approved without the person, reasoning text stays out of the
|
|
238
|
+
* page unless asked for, a source only ever links to `https:`, and no address is fetched to draw
|
|
239
|
+
* anything: a file part shows its name and type, never its content.
|
|
240
|
+
*
|
|
241
|
+
* @param {AgentThread} thread The thread to draw in.
|
|
242
|
+
* @param {UiMessageStreamOptions} [options]
|
|
243
|
+
* @returns {UiMessageStreamConnection}
|
|
244
|
+
*/
|
|
245
|
+
export function connectUiMessageStream(thread, options = {}) {
|
|
246
|
+
const runStatus = options.runStatus ?? null;
|
|
247
|
+
const tools = options.tools ?? {};
|
|
248
|
+
const showReasoning = options.showReasoning === true;
|
|
249
|
+
const agent = options.agent
|
|
250
|
+
?? Object.entries(options.authors ?? {}).find(([, author]) => author?.kind !== 'person')?.[0];
|
|
251
|
+
const byline = agent ? { author: agent } : {};
|
|
252
|
+
|
|
253
|
+
/** @type {Map<string, MessageState>} */
|
|
254
|
+
const messages = new Map();
|
|
255
|
+
/** @type {Map<string, CallState>} */
|
|
256
|
+
const calls = new Map();
|
|
257
|
+
/** @type {Map<string, ApprovalState>} By thread item id. */
|
|
258
|
+
const approvals = new Map();
|
|
259
|
+
/** @type {Map<string, Decision>} What was decided, by approval id, for good. */
|
|
260
|
+
const decisions = new Map();
|
|
261
|
+
/** @type {Set<string>} */
|
|
262
|
+
const tiles = new Set();
|
|
263
|
+
/** @type {string[]} Every item the adapter added, in thread order. */
|
|
264
|
+
const added = [];
|
|
265
|
+
/** @type {MessageState|null} */
|
|
266
|
+
let current = null;
|
|
267
|
+
/** @type {MessageState|null} The message read last. */
|
|
268
|
+
let latest = null;
|
|
269
|
+
let marks = 0;
|
|
270
|
+
let destroyed = false;
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* @param {string} message
|
|
274
|
+
* @param {UiMessagePart} part
|
|
275
|
+
* @returns {void}
|
|
276
|
+
*/
|
|
277
|
+
const report = (message, part) => {
|
|
278
|
+
options.onerror?.(Object.assign(new Error(message), { part }));
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
282
|
+
const sendMetadata = (part) => {
|
|
283
|
+
if (part.messageMetadata !== undefined) options.onmetadata?.(part.messageMetadata);
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
/** @returns {boolean} Whether an approval is still waiting for the person. */
|
|
287
|
+
const waitingForPerson = () => [...approvals.values()].some((approval) => !approval.settled);
|
|
288
|
+
|
|
289
|
+
/** @param {ThreadItem} item @returns {void} */
|
|
290
|
+
const add = (item) => {
|
|
291
|
+
added.push(String(item.id));
|
|
292
|
+
thread.upsert(item);
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
/** @param {string} id An item the adapter added. @returns {void} */
|
|
296
|
+
const takeBack = (id) => {
|
|
297
|
+
const at = added.lastIndexOf(id);
|
|
298
|
+
if (at !== -1) added.splice(at, 1);
|
|
299
|
+
thread.remove(id);
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
/** @param {MessageState} message @returns {string} The item its next words go to. */
|
|
303
|
+
const tailOf = (message) => /** @type {string} */ (message.pieces.at(-1));
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* The thread can only add at its end, so a message's last piece stops being a place to write
|
|
307
|
+
* once anything else stands below it.
|
|
308
|
+
* @param {MessageState} message
|
|
309
|
+
* @returns {boolean}
|
|
310
|
+
*/
|
|
311
|
+
const atEnd = (message) => added.at(-1) === tailOf(message);
|
|
312
|
+
|
|
313
|
+
/** @param {string} id @returns {MessageState|undefined} The message an answer is a piece of. */
|
|
314
|
+
const ownerOf = (id) => [...messages.values()].find((message) => message.pieces.includes(id));
|
|
315
|
+
|
|
316
|
+
/* ------------------------------------------------------------------ messages -- */
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Takes over an answer this connection did not draw: restored with the conversation, or drawn by
|
|
320
|
+
* a connection before it. The message goes on from what stands in the thread, with the pieces,
|
|
321
|
+
* sources and steps it has, so that a later part of one of its calls finds that call's step.
|
|
322
|
+
* @param {MessageState} message
|
|
323
|
+
* @param {any} item The answer as it stands.
|
|
324
|
+
* @returns {void}
|
|
325
|
+
*/
|
|
326
|
+
function adopt(message, item) {
|
|
327
|
+
for (let n = 2; /** @type {any} */ (thread.get(`${message.id}#${n}`))?.type === 'answer'; n += 1) {
|
|
328
|
+
message.pieces.push(`${message.id}#${n}`);
|
|
329
|
+
}
|
|
330
|
+
const tail = /** @type {any} */ (thread.get(tailOf(message)));
|
|
331
|
+
message.listed = tailOf(message);
|
|
332
|
+
message.sources = tail.sources ?? [];
|
|
333
|
+
message.hasText = tail.blocks?.at(-1)?.type === 'p';
|
|
334
|
+
message.writing = false;
|
|
335
|
+
message.quiet = true;
|
|
336
|
+
message.steps = item.steps ?? [];
|
|
337
|
+
message.drawn = message.steps.length > 0;
|
|
338
|
+
for (const step of message.steps) {
|
|
339
|
+
if (step.kind === 'think') {
|
|
340
|
+
message.thinking = { step, open: new Set(), since: null, ms: 0, text: step.detail ?? '' };
|
|
341
|
+
} else if (step.kind === 'call' && !calls.has(step.id)) {
|
|
342
|
+
const tile = `tool:${step.id}`;
|
|
343
|
+
const drawn = Boolean(thread.get(tile));
|
|
344
|
+
if (drawn) tiles.add(tile);
|
|
345
|
+
calls.set(step.id, {
|
|
346
|
+
id: step.id, name: step.tool ?? '', message, status: step.status ?? 'done', args: null,
|
|
347
|
+
argsText: step.args ?? '', since: null, step, tile: drawn ? tile : null
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// What already stands in the thread decides where the message goes on, whoever put it there.
|
|
352
|
+
added.splice(0, added.length, ...thread.getItems().map((entry) => String(entry.id)));
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Opens a message under the id asked for. What already holds that id is never overwritten: an
|
|
357
|
+
* answer the adapter did not draw is taken over, and anything else, whether a person's message, a
|
|
358
|
+
* card, or a piece of another message, leaves the message an id of its own.
|
|
359
|
+
* @param {string} requested
|
|
360
|
+
* @param {boolean} [implied]
|
|
361
|
+
* @returns {MessageState}
|
|
362
|
+
*/
|
|
363
|
+
function openMessage(requested, implied = false) {
|
|
364
|
+
const taken = /** @type {any} */ (thread.get(requested));
|
|
365
|
+
const adopted = taken?.type === 'answer' && !ownerOf(requested);
|
|
366
|
+
const id = taken && !adopted ? uid('zx-ui-message') : requested;
|
|
367
|
+
const message = /** @type {MessageState} */ ({
|
|
368
|
+
id, pieces: [id], writing: true, steps: [], sources: [], listed: id, texts: new Set(), hasText: false,
|
|
369
|
+
speaking: null, held: new Map(),
|
|
370
|
+
gap: false, drawn: false, failed: false, closed: false, implied, thinking: null, quiet: false,
|
|
371
|
+
writes: 0, replaying: false, calls: [], notices: []
|
|
372
|
+
});
|
|
373
|
+
messages.set(requested, message);
|
|
374
|
+
current = message;
|
|
375
|
+
latest = message;
|
|
376
|
+
if (adopted) adopt(message, taken);
|
|
377
|
+
else add({ id, type: 'answer', ...byline, blocks: [], streaming: true });
|
|
378
|
+
message.mark = markStep(message);
|
|
379
|
+
message.response = message.mark;
|
|
380
|
+
return message;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* The message a part belongs to. A part that arrives outside any message opens one, so what it
|
|
385
|
+
* carries is still drawn.
|
|
386
|
+
* @param {UiMessagePart} part
|
|
387
|
+
* @returns {MessageState}
|
|
388
|
+
*/
|
|
389
|
+
function activeMessage(part) {
|
|
390
|
+
if (current) return current;
|
|
391
|
+
report(`${part.type} arrived outside a message`, part);
|
|
392
|
+
return openMessage(uid('zx-ui-message'), true);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Hands the thread a message's steps. An answer without steps has no trace to update in place,
|
|
397
|
+
* so its first steps redraw it, and the redraw has to carry the text streamed so far.
|
|
398
|
+
* @param {MessageState} message
|
|
399
|
+
* @returns {void}
|
|
400
|
+
*/
|
|
401
|
+
function drawSteps(message) {
|
|
402
|
+
/** @type {Record<string, unknown>} */
|
|
403
|
+
const partial = { steps: message.steps };
|
|
404
|
+
const redraw = !message.drawn;
|
|
405
|
+
if (redraw) partial.blocks = /** @type {{blocks?: unknown[]}|null} */ (thread.get(message.id))?.blocks ?? [];
|
|
406
|
+
message.drawn = true;
|
|
407
|
+
thread.patch(message.id, partial);
|
|
408
|
+
if (redraw && message.sources.length) drawSources(message);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** @param {MessageState} message @returns {void} */
|
|
412
|
+
function endPiece(message) {
|
|
413
|
+
if (!message.writing) return;
|
|
414
|
+
message.writing = false;
|
|
415
|
+
thread.patch(tailOf(message), { streaming: false });
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Continues a message below what now stands under it, in a new answer of the same author, which
|
|
420
|
+
* the thread draws as the same turn.
|
|
421
|
+
* @param {MessageState} message
|
|
422
|
+
* @returns {void}
|
|
423
|
+
*/
|
|
424
|
+
function continueMessage(message) {
|
|
425
|
+
endPiece(message);
|
|
426
|
+
let n = message.pieces.length + 1;
|
|
427
|
+
while (thread.get(`${message.id}#${n}`)) n += 1;
|
|
428
|
+
const id = `${message.id}#${n}`;
|
|
429
|
+
message.pieces.push(id);
|
|
430
|
+
message.writing = true;
|
|
431
|
+
message.hasText = false;
|
|
432
|
+
message.gap = false;
|
|
433
|
+
add({ id, type: 'answer', ...byline, blocks: [], streaming: true });
|
|
434
|
+
// Only the answer that held the list changes: the ones above it keep what they have.
|
|
435
|
+
if (message.sources.length) drawSources(message, message.pieces.slice(-2, -1));
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* The answer that takes what a message says next. A resumed message's last answer stays as it is
|
|
440
|
+
* until here, so one with nothing to say leaves it closed.
|
|
441
|
+
* @param {MessageState} message
|
|
442
|
+
* @returns {string}
|
|
443
|
+
*/
|
|
444
|
+
function writeTo(message) {
|
|
445
|
+
message.writes += 1;
|
|
446
|
+
message.quiet = false;
|
|
447
|
+
if (!atEnd(message)) continueMessage(message);
|
|
448
|
+
else if (!message.writing) {
|
|
449
|
+
message.writing = true;
|
|
450
|
+
thread.patch(tailOf(message), { streaming: true, stopped: false });
|
|
451
|
+
}
|
|
452
|
+
return tailOf(message);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* @param {MessageState} message
|
|
457
|
+
* @param {boolean} [stopped=false] Whether it was cut off. What a response that wrote nothing cut
|
|
458
|
+
* off is not its last answer, which had already said what it had to say.
|
|
459
|
+
* @returns {void}
|
|
460
|
+
*/
|
|
461
|
+
function closeMessage(message, stopped = false) {
|
|
462
|
+
endThinking(message);
|
|
463
|
+
while (message.held.size) nextBlock(message);
|
|
464
|
+
message.speaking = null;
|
|
465
|
+
message.closed = true;
|
|
466
|
+
message.writing = false;
|
|
467
|
+
message.implied = false;
|
|
468
|
+
message.replaying = false;
|
|
469
|
+
// A response brings its own blocks, so one left open cannot hold its id into the next.
|
|
470
|
+
message.texts.clear();
|
|
471
|
+
if (current === message) current = null;
|
|
472
|
+
thread.patch(tailOf(message), stopped && !message.quiet ? { streaming: false, stopped: true } : { streaming: false });
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** @param {MessageState} message @returns {void} */
|
|
476
|
+
function stopMessage(message) {
|
|
477
|
+
for (const call of calls.values()) {
|
|
478
|
+
if (call.message === message && (call.status === 'queued' || call.status === 'running')) finishCall(call, 'stopped');
|
|
479
|
+
}
|
|
480
|
+
closeMessage(message, true);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* The response to an approval or a tool's output continues the message it belongs to. Its last
|
|
485
|
+
* piece stays as it is: whatever the message says next takes it up again or, with something below
|
|
486
|
+
* it, opens a new one.
|
|
487
|
+
* @param {MessageState} message
|
|
488
|
+
* @returns {void}
|
|
489
|
+
*/
|
|
490
|
+
function resumeMessage(message) {
|
|
491
|
+
message.closed = false;
|
|
492
|
+
message.failed = false;
|
|
493
|
+
message.quiet = true;
|
|
494
|
+
current = message;
|
|
495
|
+
latest = message;
|
|
496
|
+
message.response = markStep(message);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* A `start` for an unknown id opens a message, and one for a message that finished or was stopped
|
|
501
|
+
* resumes it: the response to an approval or a tool's output reuses the id. Only a `start` for a
|
|
502
|
+
* message still open is a duplicate. One without an id during an open message names no other
|
|
503
|
+
* message: streams merged into one each send their own, and the message goes on.
|
|
504
|
+
* @param {UiMessagePart} part
|
|
505
|
+
* @returns {void}
|
|
506
|
+
*/
|
|
507
|
+
function onStart(part) {
|
|
508
|
+
const id = part.messageId == null ? null : String(part.messageId);
|
|
509
|
+
const known = id ? messages.get(id) : undefined;
|
|
510
|
+
if (current?.implied) {
|
|
511
|
+
// The parts that came ahead of this start already opened the answer.
|
|
512
|
+
current.implied = false;
|
|
513
|
+
if (id) messages.set(id, current);
|
|
514
|
+
} else if (!id && current) {
|
|
515
|
+
sendMetadata(part);
|
|
516
|
+
return;
|
|
517
|
+
} else if (known && !known.closed) {
|
|
518
|
+
report(`Duplicate start for message ${id}`, part);
|
|
519
|
+
return;
|
|
520
|
+
} else {
|
|
521
|
+
if (current) {
|
|
522
|
+
report(`start arrived while message ${current.id} was still open`, part);
|
|
523
|
+
stopMessage(current);
|
|
524
|
+
}
|
|
525
|
+
if (known) resumeMessage(known);
|
|
526
|
+
else openMessage(id ?? uid('zx-ui-message'));
|
|
527
|
+
}
|
|
528
|
+
runStatus?.update({ state: 'running', finished: null, waitingSince: null, ...(known || current?.replaying ? {} : { started: new Date() }) });
|
|
529
|
+
sendMetadata(part);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
533
|
+
function onFinish(part) {
|
|
534
|
+
sendMetadata(part);
|
|
535
|
+
let failed = part.finishReason === 'error';
|
|
536
|
+
if (current) {
|
|
537
|
+
failed = failed || current.failed;
|
|
538
|
+
closeMessage(current);
|
|
539
|
+
} else {
|
|
540
|
+
report('finish arrived outside a message', part);
|
|
541
|
+
}
|
|
542
|
+
if (waitingForPerson()) runStatus?.update({ state: 'waiting' });
|
|
543
|
+
else runStatus?.update({ state: failed ? 'failed' : 'done', finished: new Date() });
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/* ------------------------------------------------------------------ steps -- */
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* @param {MessageState} message
|
|
550
|
+
* @returns {StepMark}
|
|
551
|
+
*/
|
|
552
|
+
function markStep(message) {
|
|
553
|
+
const { thinking, writing, hasText, gap, failed, quiet, writes } = message;
|
|
554
|
+
marks += 1;
|
|
555
|
+
return {
|
|
556
|
+
at: marks,
|
|
557
|
+
calls: message.calls.length,
|
|
558
|
+
notices: message.notices.length,
|
|
559
|
+
pieces: message.pieces.length,
|
|
560
|
+
blocks: /** @type {{blocks?: Block[]}|null} */ (thread.get(tailOf(message)))?.blocks ?? [],
|
|
561
|
+
sources: message.sources.length,
|
|
562
|
+
thought: thinking && {
|
|
563
|
+
ms: thinking.ms + (thinking.since === null ? 0 : Date.now() - thinking.since),
|
|
564
|
+
text: thinking.text
|
|
565
|
+
},
|
|
566
|
+
state: { writing, hasText, gap, failed, quiet },
|
|
567
|
+
writes
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Takes a message back to a mark, so that only what the server sends next stands in place of what
|
|
573
|
+
* it added since. The step or response itself stays open: its next parts need no `start-step` of
|
|
574
|
+
* their own. If it added nothing the answer is left alone, with whatever the reader has selected
|
|
575
|
+
* in it, and what stays is changed in place, so that what the reader opened stays open.
|
|
576
|
+
* @param {MessageState} message
|
|
577
|
+
* @param {StepMark} mark
|
|
578
|
+
* @param {boolean} [again=false] Whether the same parts are about to come again, which rebuilds
|
|
579
|
+
* every card drawn since, also one for an earlier call, in its place among the rest.
|
|
580
|
+
* @returns {void}
|
|
581
|
+
*/
|
|
582
|
+
function withdraw(message, mark, again = false) {
|
|
583
|
+
const begun = new Set(message.calls.splice(mark.calls));
|
|
584
|
+
const notices = message.notices.splice(mark.notices);
|
|
585
|
+
const finishedSince = message.response.at > mark.at;
|
|
586
|
+
// No block is open any more, and the retry may name its blocks the same way.
|
|
587
|
+
message.texts.clear();
|
|
588
|
+
message.held.clear();
|
|
589
|
+
message.speaking = null;
|
|
590
|
+
// A mark taken since no longer points at anything. The response falls back with it, and still
|
|
591
|
+
// began when it began: a replay sends no card from before that.
|
|
592
|
+
if (message.mark.at > mark.at) message.mark = mark;
|
|
593
|
+
if (message.response.at > mark.at) message.response = { ...mark, at: message.response.at };
|
|
594
|
+
const cards = [...approvals].filter(([, { call, by, at }]) => begun.has(call) || (again && by === message && at >= mark.at));
|
|
595
|
+
if (!begun.size && !cards.length && !notices.length && message.writes === mark.writes && !message.thinking?.open.size) return;
|
|
596
|
+
for (const [id, approval] of cards) {
|
|
597
|
+
// A decision on its way cannot reach the application any more.
|
|
598
|
+
approval.settled = true;
|
|
599
|
+
approvals.delete(id);
|
|
600
|
+
takeBack(id);
|
|
601
|
+
}
|
|
602
|
+
/** @type {Set<TraceStep>} */
|
|
603
|
+
const steps = new Set();
|
|
604
|
+
for (const call of begun) {
|
|
605
|
+
steps.add(call.step);
|
|
606
|
+
calls.delete(call.id);
|
|
607
|
+
if (!call.tile) continue;
|
|
608
|
+
tiles.delete(call.tile);
|
|
609
|
+
takeBack(call.tile);
|
|
610
|
+
}
|
|
611
|
+
message.steps = message.steps.filter((step) => !steps.has(step));
|
|
612
|
+
for (const id of [...message.pieces.splice(mark.pieces), ...notices]) takeBack(id);
|
|
613
|
+
message.sources.length = mark.sources;
|
|
614
|
+
restoreThinking(message, mark.thought);
|
|
615
|
+
Object.assign(message, mark.state);
|
|
616
|
+
message.writes = mark.writes;
|
|
617
|
+
// An answer that finished since is not left writing above what now stands below it.
|
|
618
|
+
if (finishedSince && !atEnd(message)) message.writing = false;
|
|
619
|
+
|
|
620
|
+
const traced = message.drawn;
|
|
621
|
+
message.drawn = message.steps.length > 0;
|
|
622
|
+
if (message.drawn) thread.patch(message.id, { steps: message.steps });
|
|
623
|
+
else if (traced) thread.upsert({ .../** @type {any} */ (thread.get(message.id)), steps: [] });
|
|
624
|
+
thread.patch(tailOf(message), { blocks: mark.blocks, streaming: message.writing, stopped: false });
|
|
625
|
+
drawSources(message);
|
|
626
|
+
if (waitingForPerson()) runStatus?.update({ state: 'waiting' });
|
|
627
|
+
else runStatus?.update({ state: 'running', waitingSince: null });
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** @returns {void} */
|
|
631
|
+
function onStartStep() {
|
|
632
|
+
if (current) current.mark = markStep(current);
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
636
|
+
function onResetStep(part) {
|
|
637
|
+
if (current) withdraw(current, current.mark);
|
|
638
|
+
else report('reset-step arrived outside a message', part);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/* ------------------------------------------------------------------ text -- */
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* A block's words start going out, in a new paragraph.
|
|
645
|
+
* @param {MessageState} message
|
|
646
|
+
* @param {unknown} id
|
|
647
|
+
* @returns {void}
|
|
648
|
+
*/
|
|
649
|
+
function speak(message, id) {
|
|
650
|
+
message.speaking = id;
|
|
651
|
+
message.gap = message.hasText;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* @param {MessageState} message
|
|
656
|
+
* @param {string} text
|
|
657
|
+
* @returns {void}
|
|
658
|
+
*/
|
|
659
|
+
function writeText(message, text) {
|
|
660
|
+
// A new block is a new paragraph and a new piece a new answer; only text opens either.
|
|
661
|
+
const delta = message.gap || !atEnd(message) ? text.trimStart() : text;
|
|
662
|
+
if (!delta) return;
|
|
663
|
+
const id = writeTo(message);
|
|
664
|
+
thread.appendText(id, message.gap ? `\n\n${delta}` : delta);
|
|
665
|
+
message.gap = false;
|
|
666
|
+
message.hasText = true;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* The block speaking is done: the first one held back goes out, and so on while they have ended.
|
|
671
|
+
* @param {MessageState} message
|
|
672
|
+
* @returns {void}
|
|
673
|
+
*/
|
|
674
|
+
function nextBlock(message) {
|
|
675
|
+
message.speaking = null;
|
|
676
|
+
for (const [id, block] of message.held) {
|
|
677
|
+
message.held.delete(id);
|
|
678
|
+
speak(message, id);
|
|
679
|
+
writeText(message, block.text);
|
|
680
|
+
if (!block.ended) return;
|
|
681
|
+
message.speaking = null;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
686
|
+
function onTextStart(part) {
|
|
687
|
+
const message = activeMessage(part);
|
|
688
|
+
if (message.texts.has(part.id)) report(`Duplicate text-start for block ${part.id}`, part);
|
|
689
|
+
else message.texts.add(part.id);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
693
|
+
function onTextDelta(part) {
|
|
694
|
+
const message = activeMessage(part);
|
|
695
|
+
if (!message.texts.has(part.id)) {
|
|
696
|
+
report(`text-delta arrived before the text-start of block ${part.id}`, part);
|
|
697
|
+
message.texts.add(part.id);
|
|
698
|
+
}
|
|
699
|
+
const delta = String(part.delta ?? '');
|
|
700
|
+
if (message.speaking === null) speak(message, part.id);
|
|
701
|
+
if (message.speaking === part.id) {
|
|
702
|
+
writeText(message, delta);
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
const block = message.held.get(part.id);
|
|
706
|
+
if (block) block.text += delta;
|
|
707
|
+
else message.held.set(part.id, { text: delta, ended: false });
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
711
|
+
function onTextEnd(part) {
|
|
712
|
+
if (!current?.texts.delete(part.id)) {
|
|
713
|
+
report(`text-end arrived before the text-start of block ${part.id}`, part);
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
const block = current.held.get(part.id);
|
|
717
|
+
if (block) block.ended = true;
|
|
718
|
+
else if (current.speaking === part.id) nextBlock(current);
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/* ------------------------------------------------------------------ reasoning -- */
|
|
722
|
+
|
|
723
|
+
/** @param {MessageState} message @returns {ThinkingState} */
|
|
724
|
+
function thinkingOf(message) {
|
|
725
|
+
if (message.thinking) return message.thinking;
|
|
726
|
+
const word = thread.msg('uiMessageStream.thinking');
|
|
727
|
+
message.thinking = {
|
|
728
|
+
step: { id: `think:${message.id}`, kind: 'think', label: word, doing: word, status: 'running' },
|
|
729
|
+
open: new Set(), since: null, ms: 0, text: ''
|
|
730
|
+
};
|
|
731
|
+
message.steps.push(message.thinking.step);
|
|
732
|
+
return message.thinking;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* @param {MessageState} message
|
|
737
|
+
* @param {unknown} id
|
|
738
|
+
* @returns {ThinkingState}
|
|
739
|
+
*/
|
|
740
|
+
function beginThinking(message, id) {
|
|
741
|
+
const thinking = thinkingOf(message);
|
|
742
|
+
message.writes += 1;
|
|
743
|
+
thinking.open.add(id);
|
|
744
|
+
if (thinking.text) thinking.text += '\n\n';
|
|
745
|
+
if (thinking.since === null) {
|
|
746
|
+
thinking.since = Date.now();
|
|
747
|
+
thinking.step.status = 'running';
|
|
748
|
+
drawSteps(message);
|
|
749
|
+
}
|
|
750
|
+
return thinking;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/**
|
|
754
|
+
* The step says how long the reasoning took in its words, so it carries no `ms`: the trace would
|
|
755
|
+
* print that beside them.
|
|
756
|
+
* @param {ThinkingState} thinking
|
|
757
|
+
* @returns {void}
|
|
758
|
+
*/
|
|
759
|
+
function settleThinking(thinking) {
|
|
760
|
+
const { step, ms, text } = thinking;
|
|
761
|
+
thinking.since = null;
|
|
762
|
+
thinking.open.clear();
|
|
763
|
+
step.status = 'done';
|
|
764
|
+
step.label = thread.msg('uiMessageStream.thought', formatDuration(ms, { locale: thread.options.locale }));
|
|
765
|
+
if (text) step.detail = text;
|
|
766
|
+
else delete step.detail;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/** @param {MessageState} message @returns {void} */
|
|
770
|
+
function endThinking(message) {
|
|
771
|
+
const thinking = message.thinking;
|
|
772
|
+
if (!thinking || thinking.since === null) return;
|
|
773
|
+
thinking.ms += Date.now() - thinking.since;
|
|
774
|
+
settleThinking(thinking);
|
|
775
|
+
drawSteps(message);
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* Puts a message's reasoning back where a withdrawn step found it.
|
|
780
|
+
* @param {MessageState} message
|
|
781
|
+
* @param {StepMark['thought']} thought
|
|
782
|
+
* @returns {void}
|
|
783
|
+
*/
|
|
784
|
+
function restoreThinking(message, thought) {
|
|
785
|
+
const { thinking } = message;
|
|
786
|
+
if (!thinking) return;
|
|
787
|
+
if (thought) {
|
|
788
|
+
Object.assign(thinking, thought);
|
|
789
|
+
settleThinking(thinking);
|
|
790
|
+
} else {
|
|
791
|
+
message.steps = message.steps.filter((step) => step !== thinking.step);
|
|
792
|
+
message.thinking = null;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
797
|
+
function onReasoningStart(part) {
|
|
798
|
+
const message = activeMessage(part);
|
|
799
|
+
if (message.thinking?.open.has(part.id)) report(`Duplicate reasoning-start for block ${part.id}`, part);
|
|
800
|
+
else beginThinking(message, part.id);
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
804
|
+
function onReasoningDelta(part) {
|
|
805
|
+
const message = activeMessage(part);
|
|
806
|
+
let thinking = message.thinking;
|
|
807
|
+
if (!thinking?.open.has(part.id)) {
|
|
808
|
+
report(`reasoning-delta arrived before the reasoning-start of block ${part.id}`, part);
|
|
809
|
+
thinking = beginThinking(message, part.id);
|
|
810
|
+
}
|
|
811
|
+
message.writes += 1;
|
|
812
|
+
if (showReasoning) thinking.text += String(part.delta ?? '');
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
816
|
+
function onReasoningEnd(part) {
|
|
817
|
+
const thinking = current?.thinking;
|
|
818
|
+
if (!current || !thinking?.open.has(part.id)) {
|
|
819
|
+
report(`reasoning-end arrived before the reasoning-start of block ${part.id}`, part);
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
current.writes += 1;
|
|
823
|
+
thinking.open.delete(part.id);
|
|
824
|
+
if (thinking.open.size === 0) endThinking(current);
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/* ------------------------------------------------------------------ tool calls -- */
|
|
828
|
+
|
|
829
|
+
/** @param {UiMessagePart} part @returns {CallState} */
|
|
830
|
+
function addCall(part) {
|
|
831
|
+
const message = activeMessage(part);
|
|
832
|
+
const id = String(part.toolCallId);
|
|
833
|
+
const name = typeof part.toolName === 'string' ? part.toolName : '';
|
|
834
|
+
/** @type {CallState} */
|
|
835
|
+
const call = {
|
|
836
|
+
id, name, message, status: 'queued', args: null, argsText: '', since: null, tile: null,
|
|
837
|
+
step: { id, kind: 'call', label: part.title || name || id, status: 'queued' }
|
|
838
|
+
};
|
|
839
|
+
if (name) call.step.tool = name;
|
|
840
|
+
calls.set(id, call);
|
|
841
|
+
message.calls.push(call);
|
|
842
|
+
message.steps.push(call.step);
|
|
843
|
+
drawSteps(message);
|
|
844
|
+
drawTile(call);
|
|
845
|
+
return call;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* The call a part names. Only a call whose input was never streamed may start at `available`;
|
|
850
|
+
* anything else ahead of its start creates the step and is reported.
|
|
851
|
+
* @param {UiMessagePart} part
|
|
852
|
+
* @param {{expected?: boolean}} [options]
|
|
853
|
+
* @returns {CallState}
|
|
854
|
+
*/
|
|
855
|
+
function callOf(part, { expected = false } = {}) {
|
|
856
|
+
const known = calls.get(String(part.toolCallId));
|
|
857
|
+
if (known) return known;
|
|
858
|
+
// A replay may name a call a reset-step of the same stream already took back.
|
|
859
|
+
if (!expected && !current?.replaying) report(`${part.type} arrived before the start of tool call ${part.toolCallId}`, part);
|
|
860
|
+
return addCall(part);
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* Fills in what an input part knows about its call.
|
|
865
|
+
* @param {CallState} call
|
|
866
|
+
* @param {UiMessagePart} part
|
|
867
|
+
* @returns {void}
|
|
868
|
+
*/
|
|
869
|
+
function setInput(call, part) {
|
|
870
|
+
if (!call.name && typeof part.toolName === 'string') {
|
|
871
|
+
call.name = part.toolName;
|
|
872
|
+
call.step.tool = part.toolName;
|
|
873
|
+
call.step.label = part.title || part.toolName;
|
|
874
|
+
}
|
|
875
|
+
call.args = part.input === undefined ? null : part.input;
|
|
876
|
+
call.argsText ||= asText(part.input);
|
|
877
|
+
// The input is shown once it is complete, never as it streams.
|
|
878
|
+
if (call.argsText) call.step.args = call.argsText;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* Moves a call on, and calls its tile's renderer when the status changed.
|
|
883
|
+
* @param {CallState} call
|
|
884
|
+
* @param {RunState} status
|
|
885
|
+
* @returns {void}
|
|
886
|
+
*/
|
|
887
|
+
function moveCall(call, status) {
|
|
888
|
+
const changed = call.status !== status;
|
|
889
|
+
call.status = status;
|
|
890
|
+
call.step.status = status;
|
|
891
|
+
if (status === 'running') call.since = Date.now();
|
|
892
|
+
drawSteps(call.message);
|
|
893
|
+
if (changed) drawTile(call);
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* Ends a call. A card still pending has lost its question: whatever happened happened without
|
|
898
|
+
* it, so it cannot be left inviting a decision.
|
|
899
|
+
* @param {CallState} call
|
|
900
|
+
* @param {RunState} status
|
|
901
|
+
* @returns {void}
|
|
902
|
+
*/
|
|
903
|
+
function finishCall(call, status) {
|
|
904
|
+
for (const [id, approval] of approvals) {
|
|
905
|
+
if (approval.call === call && !approval.settled) expire(id, approval);
|
|
906
|
+
}
|
|
907
|
+
if (call.since !== null) call.step.ms = Date.now() - call.since;
|
|
908
|
+
call.since = null;
|
|
909
|
+
moveCall(call, status);
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/**
|
|
913
|
+
* Draws or updates a call's tile. Whatever the renderer returns is the application's: the
|
|
914
|
+
* adapter only sets the id, so the renderer cannot aim at another item.
|
|
915
|
+
* @param {CallState} call
|
|
916
|
+
* @returns {void}
|
|
917
|
+
*/
|
|
918
|
+
function drawTile(call) {
|
|
919
|
+
const render = call.name && Object.hasOwn(tools, call.name) ? tools[call.name] : null;
|
|
920
|
+
if (typeof render !== 'function') return;
|
|
921
|
+
/** @type {ThreadItem|null} */
|
|
922
|
+
let item;
|
|
923
|
+
try {
|
|
924
|
+
item = render(structuredClone({
|
|
925
|
+
id: call.id, name: call.name, args: call.args, argsText: call.argsText,
|
|
926
|
+
...(call.result === undefined ? {} : { result: call.result }),
|
|
927
|
+
...(call.error === undefined ? {} : { error: call.error }),
|
|
928
|
+
status: call.status
|
|
929
|
+
}));
|
|
930
|
+
} catch (error) {
|
|
931
|
+
options.onerror?.(error instanceof Error ? error : new Error(String(error)));
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
if (item == null) return;
|
|
935
|
+
if (typeof item !== 'object' || typeof item.type !== 'string' || !item.type) {
|
|
936
|
+
report(`The tile of ${call.name} is not a thread item`, { type: 'tile', toolCallId: call.id });
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
const id = `tool:${call.id}`;
|
|
940
|
+
if (call.tile) {
|
|
941
|
+
thread.patch(id, { ...item });
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
call.tile = id;
|
|
945
|
+
tiles.add(id);
|
|
946
|
+
add({ ...byline, ...item, id });
|
|
947
|
+
call.step.refs = [{ id, label: thread.msg('uiMessageStream.showTile', call.step.label), entity: 'tool' }];
|
|
948
|
+
drawSteps(call.message);
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
952
|
+
function onInputStart(part) {
|
|
953
|
+
if (calls.has(String(part.toolCallId))) report(`Duplicate tool-input-start for call ${part.toolCallId}`, part);
|
|
954
|
+
else addCall(part);
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
958
|
+
function onInputDelta(part) {
|
|
959
|
+
const call = callOf(part);
|
|
960
|
+
call.argsText += String(part.inputTextDelta ?? '');
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
964
|
+
function onInputAvailable(part) {
|
|
965
|
+
const call = callOf(part, { expected: true });
|
|
966
|
+
setInput(call, part);
|
|
967
|
+
if (call.status === 'queued') moveCall(call, 'running');
|
|
968
|
+
else drawSteps(call.message);
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
972
|
+
function onInputError(part) {
|
|
973
|
+
const call = callOf(part, { expected: true });
|
|
974
|
+
setInput(call, part);
|
|
975
|
+
call.error = String(part.errorText ?? '');
|
|
976
|
+
call.step.error = call.error;
|
|
977
|
+
finishCall(call, 'failed');
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
981
|
+
function onOutputAvailable(part) {
|
|
982
|
+
// A preliminary output is followed by the final one, which is what finishes the call.
|
|
983
|
+
if (part.preliminary) return;
|
|
984
|
+
const call = callOf(part);
|
|
985
|
+
call.result = part.output;
|
|
986
|
+
call.step.result = asText(part.output);
|
|
987
|
+
finishCall(call, 'done');
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
991
|
+
function onOutputError(part) {
|
|
992
|
+
const call = callOf(part);
|
|
993
|
+
call.error = String(part.errorText ?? '');
|
|
994
|
+
call.step.error = call.error;
|
|
995
|
+
finishCall(call, 'failed');
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
999
|
+
function onOutputDenied(part) {
|
|
1000
|
+
finishCall(callOf(part), 'skipped');
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
/* ------------------------------------------------------------------ approvals -- */
|
|
1004
|
+
|
|
1005
|
+
/**
|
|
1006
|
+
* @param {string} id The approval's item id.
|
|
1007
|
+
* @param {ApprovalState} approval
|
|
1008
|
+
* @returns {void}
|
|
1009
|
+
*/
|
|
1010
|
+
function expire(id, approval) {
|
|
1011
|
+
approval.settled = true;
|
|
1012
|
+
thread.patch(id, { status: 'expired' });
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
1016
|
+
function onApprovalRequest(part) {
|
|
1017
|
+
const approvalId = String(part.approvalId);
|
|
1018
|
+
const id = `approval:${approvalId}`;
|
|
1019
|
+
if (approvals.has(id)) {
|
|
1020
|
+
report(`Duplicate tool-approval-request ${part.approvalId}`, part);
|
|
1021
|
+
return;
|
|
1022
|
+
}
|
|
1023
|
+
const call = callOf(part);
|
|
1024
|
+
// An automatic decision is a record, not a question: nobody is asked, and the outcome follows.
|
|
1025
|
+
if (part.isAutomatic) return;
|
|
1026
|
+
// A request that arrives again was answered once, and that answer stands.
|
|
1027
|
+
const decision = decisions.get(approvalId);
|
|
1028
|
+
approvals.set(id, { id: approvalId, call, by: current, at: marks, settled: Boolean(decision) });
|
|
1029
|
+
const code = call.args === null ? call.argsText : asText(call.args);
|
|
1030
|
+
// The answer ends before the card joins, so the thread's last word is that it needs approval,
|
|
1031
|
+
// not that it answered. A card for an earlier call outlives a reset of this step, and the answer
|
|
1032
|
+
// above it stays ended with it.
|
|
1033
|
+
if (current) {
|
|
1034
|
+
endPiece(current);
|
|
1035
|
+
for (const mark of [current.mark, current.response]) {
|
|
1036
|
+
if (!current.calls.includes(call, mark.calls)) mark.state.writing = false;
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
add({
|
|
1040
|
+
id,
|
|
1041
|
+
type: 'approval',
|
|
1042
|
+
...byline,
|
|
1043
|
+
title: thread.msg('uiMessageStream.approvalTitle', call.step.label),
|
|
1044
|
+
...(typeof part.reason === 'string' && part.reason ? { description: part.reason } : {}),
|
|
1045
|
+
...(code ? { details: [{ type: 'code', ...(typeof call.args === 'string' ? {} : { language: 'json' }), code }] } : {}),
|
|
1046
|
+
...(decision ? cardOf(decision) : { status: 'pending' })
|
|
1047
|
+
});
|
|
1048
|
+
// A tile follows the card that holds its call.
|
|
1049
|
+
if (call.tile) {
|
|
1050
|
+
const tile = thread.get(call.tile);
|
|
1051
|
+
takeBack(call.tile);
|
|
1052
|
+
if (tile) add(tile);
|
|
1053
|
+
}
|
|
1054
|
+
if (decision) {
|
|
1055
|
+
settleCall(call, decision.approved);
|
|
1056
|
+
return;
|
|
1057
|
+
}
|
|
1058
|
+
moveCall(call, 'waiting');
|
|
1059
|
+
runStatus?.update({ state: 'waiting', waitingSince: new Date() });
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
/**
|
|
1063
|
+
* The stream records a decision the person did not make here: on another device, or on the
|
|
1064
|
+
* server's side. It is the application's already, so nothing goes to `onapproval`, and the card
|
|
1065
|
+
* says what was decided rather than inviting another answer.
|
|
1066
|
+
* @param {UiMessagePart} part
|
|
1067
|
+
* @returns {void}
|
|
1068
|
+
*/
|
|
1069
|
+
function onApprovalResponse(part) {
|
|
1070
|
+
const approvalId = String(part.approvalId);
|
|
1071
|
+
const id = `approval:${approvalId}`;
|
|
1072
|
+
const approval = approvals.get(id);
|
|
1073
|
+
if (!approval) {
|
|
1074
|
+
options.onunknown?.(part);
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
if (approval.settled) return;
|
|
1078
|
+
const decision = { approved: part.approved === true, ...(typeof part.reason === 'string' && part.reason ? { reason: part.reason } : {}) };
|
|
1079
|
+
approval.settled = true;
|
|
1080
|
+
decisions.set(approvalId, decision);
|
|
1081
|
+
thread.patch(id, cardOf(decision));
|
|
1082
|
+
settleCall(approval.call, decision.approved);
|
|
1083
|
+
if (!waitingForPerson()) runStatus?.update({ state: 'running', waitingSince: null });
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
/**
|
|
1087
|
+
* Moves on a call whose approval was decided.
|
|
1088
|
+
* @param {CallState} call
|
|
1089
|
+
* @param {boolean} approved
|
|
1090
|
+
* @returns {void}
|
|
1091
|
+
*/
|
|
1092
|
+
function settleCall(call, approved) {
|
|
1093
|
+
if (approved) moveCall(call, 'running');
|
|
1094
|
+
else finishCall(call, 'skipped');
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
/**
|
|
1098
|
+
* Hears the person's answer. It takes effect once every listener has had its say, because a
|
|
1099
|
+
* prevented event keeps the card pending and a card that stays pending decided nothing.
|
|
1100
|
+
* @param {boolean} approved
|
|
1101
|
+
* @returns {(event: Event) => void}
|
|
1102
|
+
*/
|
|
1103
|
+
const onDecision = (approved) => (event) => {
|
|
1104
|
+
const { detail } = /** @type {CustomEvent<{item?: ThreadItem, reason?: string}>} */ (event);
|
|
1105
|
+
const approval = approvals.get(String(detail?.item?.id));
|
|
1106
|
+
if (!approval) return;
|
|
1107
|
+
queueMicrotask(() => {
|
|
1108
|
+
if (destroyed || approval.settled || event.defaultPrevented) return;
|
|
1109
|
+
approval.settled = true;
|
|
1110
|
+
const reason = approved ? undefined : detail.reason || undefined;
|
|
1111
|
+
const at = /** @type {{answeredAt?: string}|null} */ (thread.get(`approval:${approval.id}`))?.answeredAt;
|
|
1112
|
+
decisions.set(approval.id, { approved, ...(reason ? { reason } : {}), ...(at ? { at } : {}) });
|
|
1113
|
+
settleCall(approval.call, approved);
|
|
1114
|
+
if (!waitingForPerson()) runStatus?.update({ state: 'running', waitingSince: null });
|
|
1115
|
+
options.onapproval?.(approval.id, approved, reason);
|
|
1116
|
+
});
|
|
1117
|
+
};
|
|
1118
|
+
const onApprove = onDecision(true);
|
|
1119
|
+
const onReject = onDecision(false);
|
|
1120
|
+
|
|
1121
|
+
/** @param {Event} event @returns {void} */
|
|
1122
|
+
const onOpen = (event) => {
|
|
1123
|
+
const id = /** @type {CustomEvent<{ref?: {id?: string}}>} */ (event).detail?.ref?.id;
|
|
1124
|
+
if (id && tiles.has(id)) thread.reveal(`item:${id}`);
|
|
1125
|
+
};
|
|
1126
|
+
|
|
1127
|
+
/**
|
|
1128
|
+
* A message lists its sources under its last piece, where a citation in an earlier piece cannot
|
|
1129
|
+
* reach them on its own. Like a decision, it waits for every listener: a prevented citation is
|
|
1130
|
+
* the application's to answer.
|
|
1131
|
+
* @param {Event} event
|
|
1132
|
+
* @returns {void}
|
|
1133
|
+
*/
|
|
1134
|
+
const onCite = (event) => {
|
|
1135
|
+
const { detail } = /** @type {CustomEvent<{item?: ThreadItem, n: number}>} */ (event);
|
|
1136
|
+
const id = String(detail?.item?.id);
|
|
1137
|
+
const message = ownerOf(id);
|
|
1138
|
+
if (!message || tailOf(message) === id) return;
|
|
1139
|
+
queueMicrotask(() => {
|
|
1140
|
+
if (!destroyed && !event.defaultPrevented) thread.reveal(`source:${detail.n}:${tailOf(message)}`);
|
|
1141
|
+
});
|
|
1142
|
+
};
|
|
1143
|
+
|
|
1144
|
+
thread.on('approve', onApprove);
|
|
1145
|
+
thread.on('reject', onReject);
|
|
1146
|
+
thread.on('open', onOpen);
|
|
1147
|
+
thread.on('cite', onCite);
|
|
1148
|
+
|
|
1149
|
+
/* ------------------------------------------------------------------ the rest -- */
|
|
1150
|
+
|
|
1151
|
+
/**
|
|
1152
|
+
* Lists a message's sources under its last piece, where its turn ends. A citation counts the
|
|
1153
|
+
* whole message's sources wherever it stands, so the pieces above keep them for their citations,
|
|
1154
|
+
* without a list of their own.
|
|
1155
|
+
* @param {MessageState} message
|
|
1156
|
+
* @param {string[]} [above] The pieces above the last whose citations have to learn of them.
|
|
1157
|
+
* @returns {void}
|
|
1158
|
+
*/
|
|
1159
|
+
function drawSources(message, above = message.pieces.slice(0, -1)) {
|
|
1160
|
+
const tail = tailOf(message);
|
|
1161
|
+
if (message.listed !== tail) thread.patch(message.listed, { sources: [] });
|
|
1162
|
+
message.listed = tail;
|
|
1163
|
+
thread.patch(tail, { sources: message.sources });
|
|
1164
|
+
for (const id of above) /** @type {BlockView|null} */ (thread.getComponent(id))?.setSources(message.sources);
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
1168
|
+
function onSource(part) {
|
|
1169
|
+
const message = activeMessage(part);
|
|
1170
|
+
const source = sourceOf(part);
|
|
1171
|
+
if (message.sources.some((known) => known.id === source.id)) return;
|
|
1172
|
+
message.sources.push(source);
|
|
1173
|
+
message.writes += 1;
|
|
1174
|
+
drawSources(message);
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
1178
|
+
function onFile(part) {
|
|
1179
|
+
const message = activeMessage(part);
|
|
1180
|
+
const label = fileName(part) || thread.msg('uiMessageStream.file');
|
|
1181
|
+
thread.appendBlock(writeTo(message), { type: 'figures', rows: [{ label, value: String(part.mediaType ?? '') }] });
|
|
1182
|
+
message.hasText = false;
|
|
1183
|
+
message.gap = false;
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
/** @param {UiMessagePart} part @returns {void} */
|
|
1187
|
+
function onError(part) {
|
|
1188
|
+
const id = uid('zx-ui-error');
|
|
1189
|
+
if (current) {
|
|
1190
|
+
current.failed = true;
|
|
1191
|
+
current.notices.push(id);
|
|
1192
|
+
}
|
|
1193
|
+
add({ id, type: 'notice', tone: 'danger', text: String(part.errorText ?? '') });
|
|
1194
|
+
runStatus?.update({ state: 'failed' });
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
/** @returns {void} */
|
|
1198
|
+
function onAbort() {
|
|
1199
|
+
if (current) stopMessage(current);
|
|
1200
|
+
runStatus?.update({ state: 'stopped', finished: new Date() });
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
/** @type {Record<string, (part: UiMessagePart) => void>} */
|
|
1204
|
+
const handlers = {
|
|
1205
|
+
start: onStart,
|
|
1206
|
+
finish: onFinish,
|
|
1207
|
+
abort: onAbort,
|
|
1208
|
+
error: onError,
|
|
1209
|
+
'text-start': onTextStart,
|
|
1210
|
+
'text-delta': onTextDelta,
|
|
1211
|
+
'text-end': onTextEnd,
|
|
1212
|
+
'reasoning-start': onReasoningStart,
|
|
1213
|
+
'reasoning-delta': onReasoningDelta,
|
|
1214
|
+
'reasoning-end': onReasoningEnd,
|
|
1215
|
+
'tool-input-start': onInputStart,
|
|
1216
|
+
'tool-input-delta': onInputDelta,
|
|
1217
|
+
'tool-input-available': onInputAvailable,
|
|
1218
|
+
'tool-input-error': onInputError,
|
|
1219
|
+
'tool-output-available': onOutputAvailable,
|
|
1220
|
+
'tool-output-error': onOutputError,
|
|
1221
|
+
'tool-output-denied': onOutputDenied,
|
|
1222
|
+
'tool-approval-request': onApprovalRequest,
|
|
1223
|
+
'tool-approval-response': onApprovalResponse,
|
|
1224
|
+
'source-url': onSource,
|
|
1225
|
+
'source-document': onSource,
|
|
1226
|
+
file: onFile,
|
|
1227
|
+
'message-metadata': sendMetadata,
|
|
1228
|
+
// A file made while reasoning is part of the reasoning, which stays private.
|
|
1229
|
+
'reasoning-file': () => {},
|
|
1230
|
+
// Step boundaries draw nothing of their own, and a step ends with its own parts.
|
|
1231
|
+
'start-step': onStartStep,
|
|
1232
|
+
'finish-step': () => {},
|
|
1233
|
+
'reset-step': onResetStep
|
|
1234
|
+
};
|
|
1235
|
+
|
|
1236
|
+
return {
|
|
1237
|
+
handle(part) {
|
|
1238
|
+
if (destroyed) return;
|
|
1239
|
+
const type = part && typeof part === 'object' ? part.type : null;
|
|
1240
|
+
if (typeof type === 'string' && Object.hasOwn(handlers, type)) handlers[type](part);
|
|
1241
|
+
else if (typeof type === 'string' && type.length > 5 && type.startsWith('data-')) options.ondata?.(type.slice(5), part.data, part.id);
|
|
1242
|
+
else options.onunknown?.(part);
|
|
1243
|
+
},
|
|
1244
|
+
replay(messageId) {
|
|
1245
|
+
if (destroyed) return;
|
|
1246
|
+
const message = messageId == null ? current ?? latest : messages.get(String(messageId));
|
|
1247
|
+
if (!message) return;
|
|
1248
|
+
if (current && current !== message) stopMessage(current);
|
|
1249
|
+
withdraw(message, message.response, true);
|
|
1250
|
+
message.closed = false;
|
|
1251
|
+
message.failed = false;
|
|
1252
|
+
message.implied = true;
|
|
1253
|
+
message.replaying = true;
|
|
1254
|
+
current = message;
|
|
1255
|
+
latest = message;
|
|
1256
|
+
const waiting = waitingForPerson();
|
|
1257
|
+
runStatus?.update({ state: waiting ? 'waiting' : 'running', finished: null, ...(waiting ? {} : { waitingSince: null }) });
|
|
1258
|
+
},
|
|
1259
|
+
destroy() {
|
|
1260
|
+
if (destroyed) return;
|
|
1261
|
+
destroyed = true;
|
|
1262
|
+
thread.off('approve', onApprove);
|
|
1263
|
+
thread.off('reject', onReject);
|
|
1264
|
+
thread.off('open', onOpen);
|
|
1265
|
+
thread.off('cite', onCite);
|
|
1266
|
+
for (const [id, approval] of approvals) {
|
|
1267
|
+
if (approval.settled) continue;
|
|
1268
|
+
expire(id, approval);
|
|
1269
|
+
moveCall(approval.call, 'stopped');
|
|
1270
|
+
}
|
|
1271
|
+
if (current) {
|
|
1272
|
+
stopMessage(current);
|
|
1273
|
+
runStatus?.update({ state: 'stopped', finished: new Date() });
|
|
1274
|
+
}
|
|
1275
|
+
// A call of a finished message may be waiting for the next response, which cannot come now.
|
|
1276
|
+
for (const call of calls.values()) {
|
|
1277
|
+
if (call.status === 'queued' || call.status === 'running') finishCall(call, 'stopped');
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
}
|