@zeyos/zx 5.6.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.
- package/CHANGELOG.md +154 -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/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/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/multi-value-editor/multi-value-editor.d.ts +3 -2
- package/dist/types/components/number-field/number-field.d.ts +17 -6
- 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/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 +1 -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 +16802 -15180
- 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 +498 -134
- package/dist/zx.esm.js +40778 -29654
- package/dist/zx.esm.min.js +36 -23
- package/dist/zx.global.js +40778 -29654
- package/dist/zx.global.min.js +36 -23
- package/dist/zx.layered.css +17302 -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 +851 -121
- package/docs/llms.md +1018 -71
- 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/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/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 +1 -1
- 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/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 +29 -13
- 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/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 +22 -2
- package/src/core/format.js +15 -13
- package/src/core/http.js +29 -20
- package/src/core/i18n.js +83 -10
- 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/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,1439 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* `connectAgUi()`: draws an AG-UI event stream in an AgentThread.
|
|
4
|
+
*
|
|
5
|
+
* AG-UI is an open protocol between an agent and its user interface: a run streams lifecycle,
|
|
6
|
+
* text, tool-call, reasoning, state and custom events, with state changes as JSON Patch. The
|
|
7
|
+
* adapter takes those events already parsed — the application owns the socket or the server-sent
|
|
8
|
+
* events, retries and authentication — and turns each into calls on the thread: answers, trace
|
|
9
|
+
* steps, approvals, the application's own tiles, and surfaces. It sends nothing anywhere; what the
|
|
10
|
+
* person decides comes back to the application through `ontoolresult`.
|
|
11
|
+
*
|
|
12
|
+
* The module imports nothing that needs a DOM; the thread it is given does the drawing.
|
|
13
|
+
*/
|
|
14
|
+
import { formatDuration } from '../../internal/agent-model.js';
|
|
15
|
+
import { applyPatch } from '../../internal/json-patch.js';
|
|
16
|
+
import { assertCatalog, CATALOG } from '../surface/catalog.js';
|
|
17
|
+
import { inlineSplitter } from '../surface/stream.js';
|
|
18
|
+
import { createValidationState, validateDocument, validateOp } from '../surface/validate.js';
|
|
19
|
+
|
|
20
|
+
/** @typedef {import('./agent-thread.js').AgentThread} AgentThread */
|
|
21
|
+
/** @typedef {import('../../internal/agent-model.js').ThreadItem} ThreadItem */
|
|
22
|
+
/** @typedef {import('../../internal/agent-model.js').TraceStep} TraceStep */
|
|
23
|
+
/** @typedef {import('../../internal/agent-model.js').RunState} RunState */
|
|
24
|
+
/** @typedef {import('../../internal/agent-model.js').Author} Author */
|
|
25
|
+
/** @typedef {import('../surface/catalog.js').SurfaceCatalog} SurfaceCatalog */
|
|
26
|
+
/** @typedef {import('../surface/validate.js').SurfaceError} SurfaceError */
|
|
27
|
+
/** @typedef {import('../surface/text.js').SurfaceReply} SurfaceReply */
|
|
28
|
+
|
|
29
|
+
/** The AG-UI protocol version the adapter implements. */
|
|
30
|
+
export const AG_UI_VERSION = '1.0';
|
|
31
|
+
|
|
32
|
+
/** Longest token a surface accepts. */
|
|
33
|
+
const MAX_TOKEN = 512;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* One AG-UI event, parsed: its `type` and the fields the protocol gives that type.
|
|
37
|
+
* @typedef {{type: string, timestamp?: number, [key: string]: unknown}} AgUiEvent
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A tool call as a tile renderer receives it — a copy, so changing it changes nothing.
|
|
42
|
+
* @typedef {Object} ToolCall
|
|
43
|
+
* @property {string} id The call's `toolCallId`.
|
|
44
|
+
* @property {string} name The tool's name.
|
|
45
|
+
* @property {unknown} args The parsed arguments once they are complete; `null` before, and when
|
|
46
|
+
* they are not JSON.
|
|
47
|
+
* @property {string} argsText The arguments as they arrived.
|
|
48
|
+
* @property {unknown} [result] The `content` of the call's result event, unchanged (a string, or a
|
|
49
|
+
* list of content parts); for a surface tool, what `ontoolresult` received.
|
|
50
|
+
* @property {string} [error] Why the call failed.
|
|
51
|
+
* @property {RunState} status `queued` while the arguments arrive, `waiting` for an approval or an
|
|
52
|
+
* answer, `running` until the result, then `done`, `failed`, `skipped` when the approval was
|
|
53
|
+
* rejected, or `stopped` when the run ended without it.
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* What a tile renderer returns: an item of a type registered with `AgentThread.register()`, or
|
|
58
|
+
* `null` to draw nothing yet. Its `id` is the adapter's, `tool:<toolCallId>`, whatever it says.
|
|
59
|
+
* @typedef {(call: ToolCall) => ThreadItem|null} ToolTileRenderer
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* A problem the adapter found and how it dealt with it. Codes are stable:
|
|
64
|
+
* - `invalid-event`: an event without a field its type requires, or a value the adapter cannot
|
|
65
|
+
* read; it is dropped.
|
|
66
|
+
* - `version`: `RUN_STARTED` names a protocol version other than 1.x; the run is drawn anyway.
|
|
67
|
+
* - `no-run`: an event outside a run; it is dropped. A `RUN_ERROR` there still draws its notice and
|
|
68
|
+
* marks the last run failed, and what waits for a person stays open.
|
|
69
|
+
* - `out-of-order`: content, arguments, an end or a result for something that was never started
|
|
70
|
+
* or has already ended; it is dropped, never turned into an item.
|
|
71
|
+
* - `duplicate-start`: a start for an id still open, a settled tool call, or a run already seen; it
|
|
72
|
+
* is ignored.
|
|
73
|
+
* - `unclosed`: a message still open when its run ended; it is ended.
|
|
74
|
+
* - `renderer`: a tile renderer threw or returned something that is not an item; the trace step
|
|
75
|
+
* stays as it was.
|
|
76
|
+
* - `approval-check`: `requiresApproval` threw; the call waits for a person.
|
|
77
|
+
* - `state`: a state delta that does not apply; the state stays as it was.
|
|
78
|
+
* - `invalid-line`: a line in a surface fence that is not JSON; it is dropped.
|
|
79
|
+
* - `unknown-surface`: an operation for a surface that has not begun; it is dropped.
|
|
80
|
+
* - `surface-unavailable`: `thread.surface()` gave nothing, as with an application's own `surface`
|
|
81
|
+
* renderer, or a surface it removed. An operation is dropped, and a surface tool's call is
|
|
82
|
+
* answered at once with `{error: 'surface-unavailable'}`.
|
|
83
|
+
* - `surface-answered`: an operation for a surface that has already replied; it is refused.
|
|
84
|
+
* - `not-allowed`: an operation for a surface another source opened — a fence line for a
|
|
85
|
+
* custom-event or tool surface, a custom event for a surface the model opened — or a message id
|
|
86
|
+
* that uses one of the adapter's own prefixes (`approval:`, `tool:`, `trace:`, `surface:`,
|
|
87
|
+
* `error:`, `think:`); it is refused, never merged.
|
|
88
|
+
* - `unterminated-fence`, `line-too-long`: from splitting answer text; a surface left open by an
|
|
89
|
+
* unterminated fence is cancelled when the run ends.
|
|
90
|
+
* - `unterminated-surface`: a surface reached the end of its run without its `end` operation; it
|
|
91
|
+
* is cancelled, because its actions would stay disabled for good.
|
|
92
|
+
* - `internal`: an event the adapter could not handle at all; it is dropped, and `handle()` does
|
|
93
|
+
* not throw.
|
|
94
|
+
* @typedef {Object} AgUiProblem
|
|
95
|
+
* @property {string} code What went wrong.
|
|
96
|
+
* @property {string} message What went wrong, in English.
|
|
97
|
+
* @property {AgUiEvent} [event] The event it concerns.
|
|
98
|
+
* @property {unknown} [cause] The error thrown, for `renderer`, `approval-check` and `state`.
|
|
99
|
+
* @property {SurfaceError[]} [errors] The surface's problems, for a surface tool's document.
|
|
100
|
+
*/
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* @typedef {Object} AgUiOptions
|
|
104
|
+
* @property {{update: (values: Record<string, unknown>) => unknown}|null} [runStatus=null] A
|
|
105
|
+
* RunStatus the run's lifecycle drives: `running` when it starts, `done`, `waiting` (an
|
|
106
|
+
* interrupt, or calls of the run still without a result), `stopped` (cancelled) or `failed`.
|
|
107
|
+
* @property {Record<string, Author>} [authors={}] The thread's authors. A text message whose
|
|
108
|
+
* `name` is one of their keys is written by that author; every other item by `agent`.
|
|
109
|
+
* @property {string|null} [agent=null] The author key of the agent's output; the thread's first
|
|
110
|
+
* agent when null.
|
|
111
|
+
* @property {((call: ToolCall) => unknown)|null} [requiresApproval=null] Asked once a call's
|
|
112
|
+
* arguments are complete: any truthy answer holds the call at an ApprovalCard until the person
|
|
113
|
+
* decides. Nothing is approved by default: a check that throws holds the call too, and so does a
|
|
114
|
+
* Promise, whatever it resolves to, so an asynchronous check never lets a call through. Not asked
|
|
115
|
+
* for surface tools, whose surface is the person's say.
|
|
116
|
+
* @property {((id: string, result: Record<string, unknown>) => void)|null} [ontoolresult=null] What
|
|
117
|
+
* the person decided, for the application to send back to the agent. An approval answers
|
|
118
|
+
* `{approved: true}` or `{approved: false, reason?}`; a surface tool its reply, with `errors`
|
|
119
|
+
* when the surface had any; a `show` surface with no actions answers at once with
|
|
120
|
+
* `{shown: true, surface, errors?}` and stays on screen; a surface tool whose arguments are not a
|
|
121
|
+
* surface answers at once with `{error: 'invalid-arguments'}`, and one the thread cannot draw
|
|
122
|
+
* with `{error: 'surface-unavailable'}`. It fires once for a call. In AG-UI 1.0 the application turns it into a `resume`
|
|
123
|
+
* entry (`{interruptId, status: 'resolved', payload}`) when the run ended with an interrupt for
|
|
124
|
+
* the call, or into a tool message (`{role: 'tool', toolCallId, content}`) when it ended with
|
|
125
|
+
* the call among its `pendingToolCallIds`; either goes in the next run's input.
|
|
126
|
+
* @property {((state: unknown) => void)|null} [onstate=null] The application state after each
|
|
127
|
+
* snapshot or delta.
|
|
128
|
+
* @property {((event: AgUiEvent) => void)|null} [onunknown=null] Every event the adapter does not
|
|
129
|
+
* draw: unknown types, and known ones without a place in the thread (steps, message snapshots,
|
|
130
|
+
* activities, raw and encrypted values, subagents, custom events of another name).
|
|
131
|
+
* @property {((problem: AgUiProblem) => void)|null} [onerror=null] Problems found in the stream.
|
|
132
|
+
* @property {boolean} [showReasoning=false] Show the reasoning text in its trace step. Without
|
|
133
|
+
* it, reasoning is one collapsed "Thought for 12 s" step.
|
|
134
|
+
* @property {string} [surfaceEvent='zx.surface'] The name of the custom event that carries
|
|
135
|
+
* surface operations: its `value` is one operation, or `{ops: [...], token?}`. The token of the
|
|
136
|
+
* event that opens a surface is kept; later ones are ignored. Give these surfaces ids a model
|
|
137
|
+
* cannot predict: a surface belongs to the source that opened it, and a `begin` for an id the
|
|
138
|
+
* model already took is refused.
|
|
139
|
+
* @property {Record<string, ToolTileRenderer>} [tools={}] The tools whose calls the application
|
|
140
|
+
* draws itself, by name. The renderer is called at each status change of the call, never while
|
|
141
|
+
* its arguments stream; its first item that is not `null` is inserted after the call's step,
|
|
142
|
+
* later ones replace it where it stands, and the step links to it.
|
|
143
|
+
* @property {string[]} [surfaceTools=['show_surface','ask_user']] The tools whose arguments are a
|
|
144
|
+
* whole surface document. The surface is drawn once the arguments are complete, and its reply is
|
|
145
|
+
* the call's result.
|
|
146
|
+
* @property {boolean} [inlineSurfaces=false] Split surface fences out of answer text.
|
|
147
|
+
* @property {SurfaceCatalog} [catalog] A narrowed catalog, given to every surface the adapter
|
|
148
|
+
* creates.
|
|
149
|
+
*/
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* What `connectAgUi()` returns.
|
|
153
|
+
* @typedef {Object} AgUiConnection
|
|
154
|
+
* @property {(event: AgUiEvent) => void} handle Takes the next event, in stream order.
|
|
155
|
+
* @property {() => unknown} state The application state as it stands: a copy of the last
|
|
156
|
+
* snapshot with every delta since applied, `null` before the first.
|
|
157
|
+
* @property {() => void} destroy Ends the connection without leaving anyone waiting: a run still
|
|
158
|
+
* open is closed as stopped, every unanswered surface-tool surface is cancelled (its reply, with
|
|
159
|
+
* `reason: 'stopped'`, still reaches `ontoolresult`), every undecided approval card expires, and
|
|
160
|
+
* then the thread is no longer listened to. Nothing of this is reported through `onerror`. Later
|
|
161
|
+
* events are ignored; the items stay.
|
|
162
|
+
*/
|
|
163
|
+
|
|
164
|
+
/** The fields each event type needs: `id` a non-empty string, `text` any string. */
|
|
165
|
+
const SHAPES = /** @type {Record<string, Record<string, 'id'|'text'|'array'|'content'|'present'>>} */ ({
|
|
166
|
+
RUN_STARTED: { threadId: 'id', runId: 'id' },
|
|
167
|
+
RUN_FINISHED: { threadId: 'id', runId: 'id' },
|
|
168
|
+
RUN_ERROR: { message: 'text' },
|
|
169
|
+
TEXT_MESSAGE_START: { messageId: 'id' },
|
|
170
|
+
TEXT_MESSAGE_CONTENT: { messageId: 'id', delta: 'text' },
|
|
171
|
+
TEXT_MESSAGE_END: { messageId: 'id' },
|
|
172
|
+
TOOL_CALL_START: { toolCallId: 'id', toolCallName: 'id' },
|
|
173
|
+
TOOL_CALL_ARGS: { toolCallId: 'id', delta: 'text' },
|
|
174
|
+
TOOL_CALL_END: { toolCallId: 'id' },
|
|
175
|
+
TOOL_CALL_RESULT: { toolCallId: 'id', messageId: 'id', content: 'content' },
|
|
176
|
+
STATE_SNAPSHOT: { snapshot: 'present' },
|
|
177
|
+
STATE_DELTA: { delta: 'array' },
|
|
178
|
+
CUSTOM: { name: 'id', value: 'present' },
|
|
179
|
+
REASONING_START: { messageId: 'id' },
|
|
180
|
+
REASONING_MESSAGE_START: { messageId: 'id' },
|
|
181
|
+
REASONING_MESSAGE_CONTENT: { messageId: 'id', delta: 'text' },
|
|
182
|
+
REASONING_MESSAGE_END: { messageId: 'id' },
|
|
183
|
+
REASONING_END: { messageId: 'id' }
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
/** Events that leave an open chunk stream open. */
|
|
187
|
+
const PASSING = new Set(['RAW', 'ACTIVITY_SNAPSHOT', 'ACTIVITY_DELTA', 'REASONING_ENCRYPTED_VALUE']);
|
|
188
|
+
|
|
189
|
+
/** Prefixes of the adapter's own item ids, which a message id may not take. */
|
|
190
|
+
const RESERVED = /^(?:approval|tool|trace|surface|error|think):/;
|
|
191
|
+
|
|
192
|
+
/** Step states a run's end still finds open. */
|
|
193
|
+
const OPEN_STATES = new Set(['queued', 'running', 'waiting']);
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* @typedef {Object} Run
|
|
197
|
+
* @property {string} id
|
|
198
|
+
* @property {string|null} traceId The trace its steps go into now.
|
|
199
|
+
* @property {number} traces
|
|
200
|
+
* @property {number} errors
|
|
201
|
+
* @property {Set<string>} surfaces Surface items created in the run.
|
|
202
|
+
* @property {Set<string>} cancelAtEnd Surfaces an unterminated fence left open, already reported.
|
|
203
|
+
*/
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* @typedef {Object} Message
|
|
207
|
+
* @property {string} id
|
|
208
|
+
* @property {Run} run
|
|
209
|
+
* @property {boolean} open
|
|
210
|
+
* @property {boolean} ignored A message of a role the thread does not draw.
|
|
211
|
+
* @property {string|null} author
|
|
212
|
+
* @property {string[]} segments Its answer items: the message id, then `<id>#2`, `<id>#3`…
|
|
213
|
+
* @property {Set<string>} written Segments that received text.
|
|
214
|
+
* @property {boolean} afterFence A fence's lines came since the last prose.
|
|
215
|
+
* @property {Set<string>} pending Surfaces its fences began and did not end.
|
|
216
|
+
* @property {number} surfaces Surfaces its fences began.
|
|
217
|
+
* @property {ReturnType<typeof inlineSplitter>|null} splitter
|
|
218
|
+
*/
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* @typedef {Object} Call
|
|
222
|
+
* @property {ToolCall} call
|
|
223
|
+
* @property {'step'|'tile'|'surface'} kind
|
|
224
|
+
* @property {Run} run
|
|
225
|
+
* @property {string} traceId
|
|
226
|
+
* @property {boolean} open Its arguments are still arriving.
|
|
227
|
+
* @property {{source:boolean, value:number}} startedAt
|
|
228
|
+
* @property {boolean} gated
|
|
229
|
+
* @property {boolean} decided
|
|
230
|
+
* @property {string|null} tileId
|
|
231
|
+
* @property {string|null} placeholder
|
|
232
|
+
* @property {string|null} surfaceId
|
|
233
|
+
* @property {string[]} items The items drawn for the call — its approval, tile, stand-in or
|
|
234
|
+
* surface — in thread order.
|
|
235
|
+
*/
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Connects an AG-UI 1.0 event stream to an AgentThread.
|
|
239
|
+
*
|
|
240
|
+
* - Run start, finish and error drive `runStatus`; an error also adds a `notice`. An error outside
|
|
241
|
+
* an open run closes nothing: an approval or a surface still waiting for a person stays open.
|
|
242
|
+
* - A text message is an `answer` streamed with `appendText()`; with `inlineSurfaces`, its
|
|
243
|
+
* surface fences become surfaces after the prose before them, and the prose after a fence
|
|
244
|
+
* continues in the answer `<messageId>#2` (then `#3`…), by the same author.
|
|
245
|
+
* - A tool call is a trace step: its arguments show once complete, its result fills it. A call in
|
|
246
|
+
* `tools` is also the application's tile `tool:<toolCallId>`; a call in `surfaceTools` is an
|
|
247
|
+
* `ask` step and a surface, a Skeleton while its arguments arrive.
|
|
248
|
+
* - Calls `requiresApproval` holds wait at an ApprovalCard (`approval:<toolCallId>`). AG-UI 1.0
|
|
249
|
+
* asks for approval by ending the run with an `interrupt` outcome, or with the call among the
|
|
250
|
+
* `pendingToolCallIds` of a frontend tool; either way the decision reaches the application
|
|
251
|
+
* through `ontoolresult` for its next run, and a later run's result for the call fills the step.
|
|
252
|
+
* A `tool_call` interrupt for a call `requiresApproval` let through gates it too; the
|
|
253
|
+
* application keeps each `interrupt.id` from the event for its `resume` entry. Every other
|
|
254
|
+
* interrupt is the application's: the event goes to `onunknown`. A result that arrives before
|
|
255
|
+
* the decision is drawn as it is, the card expires, and no decision is sent for that call; a
|
|
256
|
+
* surface still waiting is cancelled the same way.
|
|
257
|
+
* - A message id is the answer's item id. A start for a closed message or call reopens it, in this
|
|
258
|
+
* run or a later one, and its content continues: a reopened call is asked about again once its
|
|
259
|
+
* arguments are complete. A start for an id still open, or for a call already decided or
|
|
260
|
+
* answered, is ignored and reported: `ontoolresult` fires once for a call, and a receipt stays.
|
|
261
|
+
* - A surface is the thread item `surface:<runId>/<surface>`, so a model reusing `s1` in every
|
|
262
|
+
* run gets a new surface each run. Its token is the application's for a custom event, the tool
|
|
263
|
+
* call id for a surface tool, and the run id for an inline surface.
|
|
264
|
+
* - A state snapshot and its deltas keep the application state, reported through `onstate`.
|
|
265
|
+
* - Reasoning is one collapsed "Thought for N s" step, its text shown only with `showReasoning`.
|
|
266
|
+
* - `*_CHUNK` events are expanded into their start, content and end events.
|
|
267
|
+
* - Out of order: content, arguments or an end for something never started is dropped, not
|
|
268
|
+
* drawn; a second start for an open id is ignored. Both are reported through `onerror`.
|
|
269
|
+
*
|
|
270
|
+
* @param {AgentThread} thread The thread to draw in.
|
|
271
|
+
* @param {AgUiOptions} [options]
|
|
272
|
+
* @returns {AgUiConnection}
|
|
273
|
+
*/
|
|
274
|
+
export function connectAgUi(thread, options = {}) {
|
|
275
|
+
if (!thread || typeof thread.upsert !== 'function') throw new TypeError('connectAgUi needs an AgentThread');
|
|
276
|
+
const authors = options.authors && typeof options.authors === 'object' ? options.authors : {};
|
|
277
|
+
const agent = typeof options.agent === 'string' && options.agent ? options.agent : null;
|
|
278
|
+
const showReasoning = options.showReasoning === true;
|
|
279
|
+
const surfaceEvent = typeof options.surfaceEvent === 'string' && options.surfaceEvent ? options.surfaceEvent : 'zx.surface';
|
|
280
|
+
const tools = options.tools && typeof options.tools === 'object' ? options.tools : {};
|
|
281
|
+
const surfaceTools = new Set(Array.isArray(options.surfaceTools) ? options.surfaceTools : ['show_surface', 'ask_user']);
|
|
282
|
+
const inlineSurfaces = options.inlineSurfaces === true;
|
|
283
|
+
const catalog = options.catalog ?? null;
|
|
284
|
+
if (catalog) assertCatalog(catalog);
|
|
285
|
+
const runStatus = options.runStatus && typeof options.runStatus.update === 'function' ? options.runStatus : null;
|
|
286
|
+
|
|
287
|
+
/** @type {Run|null} */
|
|
288
|
+
let active = null;
|
|
289
|
+
/** @type {Run|null} */
|
|
290
|
+
let lastRun = null;
|
|
291
|
+
/** @type {Set<string>} */
|
|
292
|
+
const runIds = new Set();
|
|
293
|
+
/** @type {Map<string, Message>} */
|
|
294
|
+
const messages = new Map();
|
|
295
|
+
/** @type {Map<string, Call>} */
|
|
296
|
+
const calls = new Map();
|
|
297
|
+
/** @type {Map<string, TraceStep[]>} */
|
|
298
|
+
const traces = new Map();
|
|
299
|
+
/** @type {Map<string, {source: 'tool'|'custom'|'inline', ended: boolean}>} */
|
|
300
|
+
const surfaces = new Map();
|
|
301
|
+
/** @type {Map<string, string>} Surface item id → the surface tool call it answers. */
|
|
302
|
+
const surfaceCalls = new Map();
|
|
303
|
+
/** @type {Map<string, string>} Approval item id → its call. */
|
|
304
|
+
const approvals = new Map();
|
|
305
|
+
/** @type {Set<string>} */
|
|
306
|
+
const tileRefs = new Set();
|
|
307
|
+
/** @type {{id: string, start: {source:boolean, value:number}, stepId: string, traceId: string, text: string, open: Set<string>, seen: Set<string>}|null} */
|
|
308
|
+
let reasoning = null;
|
|
309
|
+
/** @type {Set<string>} */
|
|
310
|
+
const spans = new Set();
|
|
311
|
+
/** @type {unknown} */
|
|
312
|
+
let state = null;
|
|
313
|
+
/** @type {string|null} The last item the adapter added. */
|
|
314
|
+
let lastPlaced = null;
|
|
315
|
+
/** @type {{text: {id: string, owned: boolean}|null, tool: {id: string, owned: boolean}|null, reasoning: {id: string, owned: boolean}|null}} */
|
|
316
|
+
const chunk = { text: null, tool: null, reasoning: null };
|
|
317
|
+
let destroyed = false;
|
|
318
|
+
|
|
319
|
+
/* ------------------------------------------------------------------ helpers -- */
|
|
320
|
+
|
|
321
|
+
/** @param {string} code @param {string} message @param {Partial<AgUiProblem>} [extra] */
|
|
322
|
+
const report = (code, message, extra = {}) => {
|
|
323
|
+
// Going away is not a problem in the stream, however much it leaves unfinished.
|
|
324
|
+
if (!destroyed && typeof options.onerror === 'function') options.onerror({ code, message, ...extra });
|
|
325
|
+
};
|
|
326
|
+
/** @param {AgUiEvent} event */
|
|
327
|
+
const unknown = (event) => {
|
|
328
|
+
if (typeof options.onunknown === 'function') options.onunknown(event);
|
|
329
|
+
};
|
|
330
|
+
/** @param {string} id @param {Record<string, unknown>} result */
|
|
331
|
+
const answer = (id, result) => {
|
|
332
|
+
if (typeof options.ontoolresult === 'function') options.ontoolresult(id, result);
|
|
333
|
+
};
|
|
334
|
+
/** @param {Record<string, unknown>} values */
|
|
335
|
+
const status = (values) => {
|
|
336
|
+
runStatus?.update(values);
|
|
337
|
+
};
|
|
338
|
+
/** @param {string|null} [key] @returns {{author?: string}} */
|
|
339
|
+
const by = (key = agent) => (key ? { author: key } : {});
|
|
340
|
+
/** @param {AgUiEvent} event @returns {number} */
|
|
341
|
+
const timeOf = (event) => (typeof event.timestamp === 'number' && Number.isFinite(event.timestamp) ? event.timestamp : Date.now());
|
|
342
|
+
/** @param {AgUiEvent} [event] @returns {{source:boolean, value:number}} */
|
|
343
|
+
const stamp = (event) => {
|
|
344
|
+
const source = typeof event?.timestamp === 'number' && Number.isFinite(event.timestamp);
|
|
345
|
+
return { source, value: source ? event.timestamp : Date.now() };
|
|
346
|
+
};
|
|
347
|
+
/** @param {{source:boolean,value:number}} start @param {{source:boolean,value:number}} end @returns {number|null} */
|
|
348
|
+
const elapsed = (start, end) => start.source === end.source && end.value >= start.value
|
|
349
|
+
? end.value - start.value : null;
|
|
350
|
+
/** @param {string|null|undefined} token @returns {string|null} */
|
|
351
|
+
const tokenOf = (token) => (typeof token === 'string' && token.length <= MAX_TOKEN ? token : null);
|
|
352
|
+
|
|
353
|
+
/** @param {ThreadItem} item */
|
|
354
|
+
const place = (item) => {
|
|
355
|
+
thread.upsert(item);
|
|
356
|
+
lastPlaced = String(item.id);
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* The item a call's next item goes after: the last item drawn for this call or an earlier call
|
|
361
|
+
* of the same trace, else the trace itself.
|
|
362
|
+
* @param {Call} entry @param {string|null} [before] An item of the call to go before.
|
|
363
|
+
* @returns {string}
|
|
364
|
+
*/
|
|
365
|
+
const anchorOf = (entry, before = null) => {
|
|
366
|
+
let anchor = entry.traceId;
|
|
367
|
+
for (const step of traces.get(entry.traceId) ?? []) {
|
|
368
|
+
const other = calls.get(step.id);
|
|
369
|
+
const items = other?.traceId === entry.traceId ? other.items.filter((id) => id !== before) : [];
|
|
370
|
+
if (items.length) anchor = /** @type {string} */ (items.at(-1));
|
|
371
|
+
if (step.id === entry.call.id) break;
|
|
372
|
+
}
|
|
373
|
+
return anchor;
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Inserts an item at its call's place, even when something was drawn after the call's step
|
|
378
|
+
* since.
|
|
379
|
+
* @param {Call} entry @param {ThreadItem} item
|
|
380
|
+
*/
|
|
381
|
+
const placeForCall = (entry, item) => {
|
|
382
|
+
const anchor = anchorOf(entry);
|
|
383
|
+
thread.upsert(item, { after: anchor });
|
|
384
|
+
if (lastPlaced === anchor) lastPlaced = String(item.id);
|
|
385
|
+
entry.items.push(String(item.id));
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Removes an item drawn for a call.
|
|
390
|
+
* @param {Call} entry @param {string} id
|
|
391
|
+
*/
|
|
392
|
+
const unplace = (entry, id) => {
|
|
393
|
+
thread.remove(id);
|
|
394
|
+
entry.items = entry.items.filter((other) => other !== id);
|
|
395
|
+
if (lastPlaced === id) lastPlaced = anchorOf(entry);
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Adds a step to the run's current trace, or to a new trace when something else was drawn
|
|
400
|
+
* since, so every step stands where it happened.
|
|
401
|
+
* @param {Run} run @param {TraceStep} step
|
|
402
|
+
* @returns {string} The trace's id.
|
|
403
|
+
*/
|
|
404
|
+
const addStep = (run, step) => {
|
|
405
|
+
const current = run.traceId;
|
|
406
|
+
if (current && lastPlaced === current && traces.has(current)) {
|
|
407
|
+
const steps = /** @type {TraceStep[]} */ (traces.get(current));
|
|
408
|
+
steps.push(step);
|
|
409
|
+
thread.patch(current, { steps: structuredClone(steps) });
|
|
410
|
+
return current;
|
|
411
|
+
}
|
|
412
|
+
run.traces += 1;
|
|
413
|
+
const id = run.traces === 1 ? `trace:${run.id}` : `trace:${run.id}#${run.traces}`;
|
|
414
|
+
run.traceId = id;
|
|
415
|
+
traces.set(id, [step]);
|
|
416
|
+
place(/** @type {ThreadItem} */ ({ id, type: 'trace', ...by(), steps: [structuredClone(step)] }));
|
|
417
|
+
return id;
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
/** @param {string} traceId @param {string} stepId @param {Record<string, unknown>} changes */
|
|
421
|
+
const updateStep = (traceId, stepId, changes) => {
|
|
422
|
+
const steps = traces.get(traceId);
|
|
423
|
+
const index = steps ? steps.findIndex((step) => step.id === stepId) : -1;
|
|
424
|
+
if (!steps || index < 0) return;
|
|
425
|
+
const next = /** @type {Record<string, unknown>} */ ({ ...steps[index], ...changes });
|
|
426
|
+
for (const key of Object.keys(next)) if (next[key] === undefined) delete next[key];
|
|
427
|
+
steps[index] = /** @type {TraceStep} */ (next);
|
|
428
|
+
thread.patch(traceId, { steps: structuredClone(steps) });
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Moves a call to another status: its step, then its tile.
|
|
433
|
+
* @param {Call} entry @param {RunState} next
|
|
434
|
+
* @param {Partial<ToolCall>} [changes] @param {Record<string, unknown>} [step]
|
|
435
|
+
*/
|
|
436
|
+
const setStatus = (entry, next, changes = {}, step = {}) => {
|
|
437
|
+
const changed = entry.call.status !== next;
|
|
438
|
+
Object.assign(entry.call, changes, { status: next });
|
|
439
|
+
updateStep(entry.traceId, entry.call.id, { status: next, ...step });
|
|
440
|
+
if (entry.kind === 'tile' && changed) renderTile(entry);
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Holds a call at an ApprovalCard.
|
|
445
|
+
* @param {Call} entry
|
|
446
|
+
*/
|
|
447
|
+
const gate = (entry) => {
|
|
448
|
+
entry.gated = true;
|
|
449
|
+
const id = `approval:${entry.call.id}`;
|
|
450
|
+
approvals.set(id, entry.call.id);
|
|
451
|
+
const card = /** @type {ThreadItem} */ ({
|
|
452
|
+
id, type: 'approval', ...by(), title: thread.msg('agUi.approve', entry.call.name), status: 'pending',
|
|
453
|
+
details: [{ type: 'code', language: 'json', code: pretty(entry.call.argsText) }]
|
|
454
|
+
});
|
|
455
|
+
// A tile follows the card, also when the renderer answered before there was one.
|
|
456
|
+
if (entry.tileId) {
|
|
457
|
+
thread.upsert(card, { after: anchorOf(entry, entry.tileId) });
|
|
458
|
+
entry.items.splice(entry.items.indexOf(entry.tileId), 0, id);
|
|
459
|
+
} else {
|
|
460
|
+
placeForCall(entry, card);
|
|
461
|
+
}
|
|
462
|
+
setStatus(entry, 'waiting', {}, { args: entry.call.argsText });
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Expires a call's approval card: the decision can no longer be made.
|
|
467
|
+
* @param {Call} entry
|
|
468
|
+
*/
|
|
469
|
+
const expire = (entry) => {
|
|
470
|
+
if (!entry.gated || entry.decided) return;
|
|
471
|
+
entry.decided = true;
|
|
472
|
+
thread.patch(`approval:${entry.call.id}`, { status: 'expired' });
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Takes a call's surface away. Forgotten first: the reply its removal sends is not the call's
|
|
477
|
+
* answer.
|
|
478
|
+
* @param {Call} entry
|
|
479
|
+
*/
|
|
480
|
+
const forgetSurface = (entry) => {
|
|
481
|
+
const id = /** @type {string} */ (entry.surfaceId);
|
|
482
|
+
surfaces.delete(id);
|
|
483
|
+
surfaceCalls.delete(id);
|
|
484
|
+
entry.run.surfaces.delete(id);
|
|
485
|
+
entry.surfaceId = null;
|
|
486
|
+
unplace(entry, id);
|
|
487
|
+
};
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Whether a call has its answer: a person decided it, or it was answered, by its result or at
|
|
491
|
+
* once. Nothing changes that, so `ontoolresult` never fires twice for one call.
|
|
492
|
+
* @param {Call} entry
|
|
493
|
+
* @returns {boolean}
|
|
494
|
+
*/
|
|
495
|
+
const isSettled = (entry) => entry.decided || Object.hasOwn(entry.call, 'result');
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* A start for a call closed but not settled: its arguments continue, so nothing drawn from them
|
|
499
|
+
* stands any more. Its card and its surface go, and it is asked about again once the arguments
|
|
500
|
+
* are complete, so nobody decides on arguments that have since changed.
|
|
501
|
+
* @param {Call} entry @param {Run} run
|
|
502
|
+
*/
|
|
503
|
+
const reopenCall = (entry, run) => {
|
|
504
|
+
const { call } = entry;
|
|
505
|
+
if (entry.gated) {
|
|
506
|
+
approvals.delete(`approval:${call.id}`);
|
|
507
|
+
unplace(entry, `approval:${call.id}`);
|
|
508
|
+
}
|
|
509
|
+
if (entry.surfaceId) forgetSurface(entry);
|
|
510
|
+
Object.assign(entry, { run, open: true, gated: false });
|
|
511
|
+
call.args = null;
|
|
512
|
+
if (entry.kind === 'surface') standIn(entry);
|
|
513
|
+
setStatus(entry, 'queued', {}, { args: undefined, detail: undefined });
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Draws the Skeleton a surface call stands as while its arguments arrive.
|
|
518
|
+
* @param {Call} entry
|
|
519
|
+
*/
|
|
520
|
+
const standIn = (entry) => {
|
|
521
|
+
entry.placeholder = `tool:${entry.call.id}`;
|
|
522
|
+
placeForCall(entry, /** @type {ThreadItem} */ ({ id: entry.placeholder, type: 'zx-placeholder', ...by(), lines: 4 }));
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
/** @param {Call} entry */
|
|
526
|
+
const renderTile = (entry) => {
|
|
527
|
+
const render = tools[entry.call.name];
|
|
528
|
+
if (typeof render !== 'function' || thread._destroyed) return;
|
|
529
|
+
const id = `tool:${entry.call.id}`;
|
|
530
|
+
try {
|
|
531
|
+
const item = render(structuredClone(entry.call));
|
|
532
|
+
if (item == null) return;
|
|
533
|
+
if (!isObject(item) || typeof item.type !== 'string' || !item.type) {
|
|
534
|
+
report('renderer', `The tile renderer for "${entry.call.name}" returned something that is not an item`, { cause: item });
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
const tile = /** @type {ThreadItem} */ ({ ...by(), ...item, id });
|
|
538
|
+
if (entry.tileId) {
|
|
539
|
+
thread.upsert(tile);
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
placeForCall(entry, tile);
|
|
543
|
+
entry.tileId = id;
|
|
544
|
+
} catch (error) {
|
|
545
|
+
report('renderer', `The tile renderer for "${entry.call.name}" failed: ${messageOf(error)}`, { cause: error });
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
tileRefs.add(id);
|
|
549
|
+
updateStep(entry.traceId, entry.call.id, { refs: [{ id, label: thread.msg('agUi.showTile'), entity: 'tile' }] });
|
|
550
|
+
};
|
|
551
|
+
|
|
552
|
+
/** @param {AgUiEvent} event @returns {Run|null} */
|
|
553
|
+
const inRun = (event) => {
|
|
554
|
+
if (active) return active;
|
|
555
|
+
report('no-run', `${event.type} arrived outside a run and was dropped`, { event });
|
|
556
|
+
return null;
|
|
557
|
+
};
|
|
558
|
+
|
|
559
|
+
/* ------------------------------------------------------------------ surfaces -- */
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* Routes one surface operation into its scoped surface. A surface belongs to the source that
|
|
563
|
+
* opened it; an operation from another source is refused.
|
|
564
|
+
* @param {unknown} op
|
|
565
|
+
* @param {{source: 'custom'|'inline', run: Run, token: string|null, badToken?: boolean, message?: Message, event?: AgUiEvent}} context
|
|
566
|
+
*/
|
|
567
|
+
const routeOp = (op, context) => {
|
|
568
|
+
const invalid = context.source === 'inline' ? 'invalid-line' : 'invalid-event';
|
|
569
|
+
const name = isObject(op) ? op.surface : undefined;
|
|
570
|
+
if (!isObject(op) || typeof name !== 'string' || !name) {
|
|
571
|
+
report(invalid, 'A surface operation names no surface; it was dropped', { event: context.event });
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
const id = `surface:${context.run.id}/${name}`;
|
|
575
|
+
let owner = surfaces.get(id);
|
|
576
|
+
if (owner && owner.source !== context.source) {
|
|
577
|
+
report('not-allowed', `Surface "${name}" belongs to another source; the operation was refused`, { event: context.event });
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
if (!owner) {
|
|
581
|
+
if (op.op !== 'begin') {
|
|
582
|
+
report('unknown-surface', `Surface "${name}" has not begun; the operation was dropped`, { event: context.event });
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
if (context.badToken) {
|
|
586
|
+
report('invalid-event', `A surface token is a string of at most ${MAX_TOKEN} characters; surface "${name}" was not opened`, { event: context.event });
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
const entities = thread.options?.surfaceOptions?.resolve?.entities ?? null;
|
|
590
|
+
const checked = validateOp(op, createValidationState({ entities }), catalog ?? CATALOG);
|
|
591
|
+
if (!checked.op) {
|
|
592
|
+
report(invalid, `Surface "${name}" cannot begin; nothing was drawn`, { event: context.event, errors: checked.errors });
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
owner = { source: context.source, ended: false };
|
|
596
|
+
surfaces.set(id, owner);
|
|
597
|
+
context.run.surfaces.add(id);
|
|
598
|
+
const before = lastPlaced;
|
|
599
|
+
place(/** @type {ThreadItem} */ ({
|
|
600
|
+
id, type: 'surface', ...by(context.message ? context.message.author : agent), document: null,
|
|
601
|
+
token: context.token, ...(catalog ? { catalog } : {})
|
|
602
|
+
}));
|
|
603
|
+
// Nothing can stream into what this thread drew for it: an empty item does not stay.
|
|
604
|
+
if (!thread.surface(id)) {
|
|
605
|
+
thread.remove(id);
|
|
606
|
+
lastPlaced = before;
|
|
607
|
+
}
|
|
608
|
+
if (context.message) {
|
|
609
|
+
context.message.pending.add(id);
|
|
610
|
+
context.message.surfaces += 1;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
const surface = thread.surface(id);
|
|
614
|
+
if (!surface) {
|
|
615
|
+
report('surface-unavailable', `The thread has no surface for "${name}"; the operation was dropped`, { event: context.event });
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (surface.getReply()) {
|
|
619
|
+
report('surface-answered', `Surface "${name}" has already been answered; the operation was refused`, { event: context.event });
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
surface.apply(op);
|
|
623
|
+
if (op.op === 'end') {
|
|
624
|
+
owner.ended = true;
|
|
625
|
+
context.message?.pending.delete(id);
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* A surface tool's arguments are complete: draw the surface, or answer the call at once.
|
|
631
|
+
* @param {Call} entry @param {{ok: boolean, value?: unknown}} parsed
|
|
632
|
+
*/
|
|
633
|
+
const surfaceArguments = (entry, parsed) => {
|
|
634
|
+
const { call, run } = entry;
|
|
635
|
+
const skeleton = entry.placeholder;
|
|
636
|
+
entry.placeholder = null;
|
|
637
|
+
/** @param {{error: string, errors?: SurfaceError[]}} result @param {SurfaceError[]} [errors] */
|
|
638
|
+
const refuse = (result, errors) => {
|
|
639
|
+
if (skeleton) unplace(entry, skeleton);
|
|
640
|
+
entry.decided = true;
|
|
641
|
+
setStatus(entry, 'failed', { error: result.error }, { args: call.argsText, error: result.error });
|
|
642
|
+
if (errors) report('invalid-event', `The arguments of "${call.name}" are not a surface`, { errors });
|
|
643
|
+
answer(call.id, result);
|
|
644
|
+
};
|
|
645
|
+
if (!parsed.ok) {
|
|
646
|
+
refuse({ error: 'invalid-arguments' });
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
call.args = parsed.value;
|
|
650
|
+
const settings = thread.options?.surfaceOptions?.resolve?.entities;
|
|
651
|
+
const { document, errors } = validateDocument(parsed.value, catalog ?? CATALOG, { entities: settings ?? null });
|
|
652
|
+
// Without a valid intent a surface draws no controls, so nobody could ever answer it.
|
|
653
|
+
if (!document?.intent) {
|
|
654
|
+
refuse({ error: 'invalid-arguments', errors }, errors);
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
const id = `surface:${run.id}/${document.surface}`;
|
|
658
|
+
if (surfaces.has(id)) {
|
|
659
|
+
const duplicate = [{ code: /** @type {const} */ ('duplicate-begin'), surface: document.surface,
|
|
660
|
+
message: `Surface "${document.surface}" already exists in this run; use another id` }];
|
|
661
|
+
refuse({ error: 'invalid-arguments', errors: duplicate }, duplicate);
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
surfaces.set(id, { source: 'tool', ended: true });
|
|
665
|
+
surfaceCalls.set(id, call.id);
|
|
666
|
+
run.surfaces.add(id);
|
|
667
|
+
entry.surfaceId = id;
|
|
668
|
+
placeForCall(entry, /** @type {ThreadItem} */ ({
|
|
669
|
+
id, type: 'surface', ...by(), document: parsed.value, token: tokenOf(call.id), ...(catalog ? { catalog } : {})
|
|
670
|
+
}));
|
|
671
|
+
if (!thread.surface(id)) {
|
|
672
|
+
// Nothing in this thread can reply: the item goes, and the call is not left waiting for it.
|
|
673
|
+
forgetSurface(entry);
|
|
674
|
+
report('surface-unavailable', `The thread has no surface for "${document.surface}"; the call of "${call.name}" was answered at once`);
|
|
675
|
+
refuse({ error: 'surface-unavailable' });
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
if (skeleton) unplace(entry, skeleton);
|
|
679
|
+
if (document.intent === 'show' && !document.actions?.length) {
|
|
680
|
+
// Nothing here can be answered: the call is, at once, and the surface stays on screen.
|
|
681
|
+
const problems = thread.surface(id)?.getErrors() ?? errors;
|
|
682
|
+
const result = { shown: true, surface: document.surface, ...(problems.length ? { errors: problems } : {}) };
|
|
683
|
+
entry.decided = true;
|
|
684
|
+
setStatus(entry, 'done', { result }, { args: call.argsText, detail: document.title, result: JSON.stringify(result) });
|
|
685
|
+
answer(call.id, result);
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
setStatus(entry, 'waiting', {}, { args: call.argsText, detail: document.title });
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
/* ------------------------------------------------------------------ text -- */
|
|
692
|
+
|
|
693
|
+
/** @param {Message} message @returns {ReturnType<typeof inlineSplitter>} */
|
|
694
|
+
const splitterFor = (message) => inlineSplitter({
|
|
695
|
+
ontext: (text) => prose(message, text),
|
|
696
|
+
online: (line) => fenceLine(message, line),
|
|
697
|
+
onerror: (error) => {
|
|
698
|
+
report(error.code, error.message);
|
|
699
|
+
if (error.code !== 'unterminated-fence') return;
|
|
700
|
+
for (const surface of message.pending) message.run.cancelAtEnd.add(surface);
|
|
701
|
+
message.pending.clear();
|
|
702
|
+
}
|
|
703
|
+
});
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* A start for a closed message: its content continues where it stands, in this run.
|
|
707
|
+
* @param {Message} message @param {Run} run
|
|
708
|
+
*/
|
|
709
|
+
const reopenMessage = (message, run) => {
|
|
710
|
+
message.open = true;
|
|
711
|
+
message.run = run;
|
|
712
|
+
if (message.ignored) return;
|
|
713
|
+
if (inlineSurfaces) message.splitter = splitterFor(message);
|
|
714
|
+
const last = thread.get(/** @type {string} */ (message.segments.at(-1)));
|
|
715
|
+
if (last) thread.upsert(/** @type {ThreadItem} */ ({ ...last, streaming: true, stopped: false }));
|
|
716
|
+
};
|
|
717
|
+
|
|
718
|
+
/** @param {Message} message @param {string} text */
|
|
719
|
+
const prose = (message, text) => {
|
|
720
|
+
let rest = text;
|
|
721
|
+
if (message.afterFence) {
|
|
722
|
+
rest = rest.replace(/^\s+/, '');
|
|
723
|
+
if (!rest) return;
|
|
724
|
+
message.afterFence = false;
|
|
725
|
+
const id = `${message.id}#${message.segments.length + 1}`;
|
|
726
|
+
message.segments.push(id);
|
|
727
|
+
place(/** @type {ThreadItem} */ ({ id, type: 'answer', ...by(message.author), blocks: [], streaming: true }));
|
|
728
|
+
}
|
|
729
|
+
if (!rest) return;
|
|
730
|
+
const current = /** @type {string} */ (message.segments.at(-1));
|
|
731
|
+
message.written.add(current);
|
|
732
|
+
thread.appendText(current, rest);
|
|
733
|
+
};
|
|
734
|
+
|
|
735
|
+
/** @param {Message} message @param {string} line */
|
|
736
|
+
const fenceLine = (message, line) => {
|
|
737
|
+
if (!line.trim()) return;
|
|
738
|
+
message.afterFence = true;
|
|
739
|
+
let op;
|
|
740
|
+
try {
|
|
741
|
+
op = JSON.parse(line);
|
|
742
|
+
} catch {
|
|
743
|
+
report('invalid-line', 'A line in a surface fence is not JSON; it was dropped');
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
routeOp(op, { source: 'inline', run: message.run, token: tokenOf(message.run.id), message });
|
|
747
|
+
};
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* Ends a message: the splitter, then every answer segment.
|
|
751
|
+
* @param {Message} message @param {boolean} [stopped]
|
|
752
|
+
*/
|
|
753
|
+
const endMessage = (message, stopped = false) => {
|
|
754
|
+
message.open = false;
|
|
755
|
+
if (message.ignored) return;
|
|
756
|
+
message.splitter?.end();
|
|
757
|
+
for (const id of message.segments) {
|
|
758
|
+
if (id === message.id && !message.written.has(id) && message.surfaces > 0) {
|
|
759
|
+
thread.remove(id);
|
|
760
|
+
continue;
|
|
761
|
+
}
|
|
762
|
+
thread.patch(id, stopped ? { streaming: false, stopped: true } : { streaming: false });
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
|
|
766
|
+
/* ------------------------------------------------------------------ runs -- */
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* Ends a run: open reasoning, messages and fences, then the surfaces an unterminated fence left.
|
|
770
|
+
* @param {Run} run @param {'done'|'stopped'|'failed'|null} outcome
|
|
771
|
+
* @param {{source:boolean,value:number}} [at] When the run ended.
|
|
772
|
+
*/
|
|
773
|
+
const closeRun = (run, outcome, at = stamp()) => {
|
|
774
|
+
if (reasoning) endReasoning(at);
|
|
775
|
+
const stopped = outcome === 'stopped' || outcome === 'failed';
|
|
776
|
+
for (const entry of calls.values()) {
|
|
777
|
+
if (entry.run !== run || !entry.open) continue;
|
|
778
|
+
report('unclosed', `The arguments of tool call "${entry.call.id}" were still arriving when its run ended`);
|
|
779
|
+
entry.open = false;
|
|
780
|
+
if (entry.placeholder) unplace(entry, entry.placeholder);
|
|
781
|
+
entry.placeholder = null;
|
|
782
|
+
setStatus(entry, 'stopped');
|
|
783
|
+
}
|
|
784
|
+
for (const message of messages.values()) {
|
|
785
|
+
if (message.run !== run || !message.open) continue;
|
|
786
|
+
if (!message.ignored) report('unclosed', `Message "${message.id}" was still open when its run ended`);
|
|
787
|
+
endMessage(message, stopped);
|
|
788
|
+
}
|
|
789
|
+
for (const id of run.surfaces) {
|
|
790
|
+
const surface = thread.surface(id);
|
|
791
|
+
if (surfaces.get(id)?.ended || !surface || surface.getReply()) continue;
|
|
792
|
+
if (!run.cancelAtEnd.has(id)) report('unterminated-surface', `Surface "${id}" reached the end of its run without its "end"; it was cancelled`);
|
|
793
|
+
surface.cancel('stopped');
|
|
794
|
+
}
|
|
795
|
+
run.cancelAtEnd.clear();
|
|
796
|
+
if (!stopped) return;
|
|
797
|
+
for (const id of run.surfaces) {
|
|
798
|
+
const surface = thread.surface(id);
|
|
799
|
+
if (surface && !surface.getReply()) surface.cancel('stopped');
|
|
800
|
+
}
|
|
801
|
+
for (const entry of calls.values()) {
|
|
802
|
+
if (entry.run !== run || !OPEN_STATES.has(entry.call.status)) continue;
|
|
803
|
+
entry.open = false;
|
|
804
|
+
expire(entry);
|
|
805
|
+
setStatus(entry, 'stopped');
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
|
|
809
|
+
/** @param {{source:boolean,value:number}} at */
|
|
810
|
+
const endReasoning = (at) => {
|
|
811
|
+
const span = /** @type {NonNullable<typeof reasoning>} */ (reasoning);
|
|
812
|
+
const ms = elapsed(span.start, at);
|
|
813
|
+
updateStep(span.traceId, span.stepId, {
|
|
814
|
+
status: 'done', label: ms === null ? thread.msg('agUi.thoughtComplete') : thread.msg('agUi.thought', formatDuration(ms)),
|
|
815
|
+
doing: undefined, ...(ms === null ? {} : { ms }),
|
|
816
|
+
...(showReasoning && span.text ? { detail: span.text } : {})
|
|
817
|
+
});
|
|
818
|
+
reasoning = null;
|
|
819
|
+
};
|
|
820
|
+
|
|
821
|
+
/* ------------------------------------------------------------------ events -- */
|
|
822
|
+
|
|
823
|
+
/** @param {AgUiEvent} event */
|
|
824
|
+
const dispatch = (event) => {
|
|
825
|
+
const shape = SHAPES[event.type];
|
|
826
|
+
if (shape) {
|
|
827
|
+
const missing = Object.entries(shape).find(([key, kind]) => !fits(event[key], kind, Object.hasOwn(event, key)));
|
|
828
|
+
if (missing) {
|
|
829
|
+
report('invalid-event', `${event.type} needs "${missing[0]}"; it was dropped`, { event });
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
switch (event.type) {
|
|
834
|
+
case 'RUN_STARTED': return runStarted(event);
|
|
835
|
+
case 'RUN_FINISHED': return runFinished(event);
|
|
836
|
+
case 'RUN_ERROR': return runError(event);
|
|
837
|
+
case 'TEXT_MESSAGE_START': return textStart(event);
|
|
838
|
+
case 'TEXT_MESSAGE_CONTENT': return textContent(event);
|
|
839
|
+
case 'TEXT_MESSAGE_END': return textEnd(event);
|
|
840
|
+
case 'TOOL_CALL_START': return toolStart(event);
|
|
841
|
+
case 'TOOL_CALL_ARGS': return toolArgs(event);
|
|
842
|
+
case 'TOOL_CALL_END': return toolEnd(event);
|
|
843
|
+
case 'TOOL_CALL_RESULT': return toolResult(event);
|
|
844
|
+
case 'STATE_SNAPSHOT': return stateSnapshot(event);
|
|
845
|
+
case 'STATE_DELTA': return stateDelta(event);
|
|
846
|
+
case 'CUSTOM': return custom(event);
|
|
847
|
+
case 'REASONING_START':
|
|
848
|
+
case 'REASONING_MESSAGE_START':
|
|
849
|
+
case 'REASONING_MESSAGE_CONTENT':
|
|
850
|
+
case 'REASONING_MESSAGE_END':
|
|
851
|
+
case 'REASONING_END':
|
|
852
|
+
return reason(event);
|
|
853
|
+
default:
|
|
854
|
+
unknown(event);
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
|
|
858
|
+
/** @param {AgUiEvent} event */
|
|
859
|
+
const runStarted = (event) => {
|
|
860
|
+
const id = String(event.runId);
|
|
861
|
+
if (active?.id === id || runIds.has(id)) {
|
|
862
|
+
report('duplicate-start', `Run "${id}" has already started; the start was ignored`, { event });
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
if (typeof event.protocolVersion === 'string' && !/^1(?:\.|$)/.test(event.protocolVersion)) {
|
|
866
|
+
report('version', `The run speaks AG-UI ${event.protocolVersion}; this adapter implements ${AG_UI_VERSION}`, { event });
|
|
867
|
+
}
|
|
868
|
+
if (active) {
|
|
869
|
+
report('out-of-order', `Run "${active.id}" never finished before run "${id}" started`, { event });
|
|
870
|
+
closeRun(active, null, stamp(event));
|
|
871
|
+
}
|
|
872
|
+
runIds.add(id);
|
|
873
|
+
active = { id, traceId: null, traces: 0, errors: 0, surfaces: new Set(), cancelAtEnd: new Set() };
|
|
874
|
+
lastRun = active;
|
|
875
|
+
status({ state: 'running', started: new Date(timeOf(event)), finished: null, waitingSince: null });
|
|
876
|
+
};
|
|
877
|
+
|
|
878
|
+
/** @param {AgUiEvent} event */
|
|
879
|
+
const runFinished = (event) => {
|
|
880
|
+
const id = String(event.runId);
|
|
881
|
+
if (!active || active.id !== id) {
|
|
882
|
+
report('out-of-order', `Run "${id}" is not the run in progress; its end was dropped`, { event });
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
const run = active;
|
|
886
|
+
const outcome = isObject(event.outcome) ? event.outcome : { type: 'success' };
|
|
887
|
+
const kind = outcome.type;
|
|
888
|
+
const at = new Date(timeOf(event));
|
|
889
|
+
// An outcome nobody recognises reads as success.
|
|
890
|
+
if (kind !== 'success' && kind !== 'interrupt' && kind !== 'cancelled') {
|
|
891
|
+
report('invalid-event', `RUN_FINISHED has an unknown outcome ${safeText(kind)}`, { event });
|
|
892
|
+
}
|
|
893
|
+
closeRun(run, kind === 'cancelled' ? 'stopped' : 'done', stamp(event));
|
|
894
|
+
active = null;
|
|
895
|
+
if (kind === 'cancelled') {
|
|
896
|
+
status({ state: 'stopped', finished: at });
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
if (kind === 'interrupt') interrupted(event, Array.isArray(outcome.interrupts) ? outcome.interrupts : []);
|
|
900
|
+
// The list only ever adds to what the stream shows: a call of this run with no result is still
|
|
901
|
+
// owed one, whoever owes it.
|
|
902
|
+
const pending = Array.isArray(outcome.pendingToolCallIds) && outcome.pendingToolCallIds.length > 0;
|
|
903
|
+
const waiting = kind === 'interrupt' || pending
|
|
904
|
+
|| [...calls.values()].some((entry) => entry.run === run && OPEN_STATES.has(entry.call.status));
|
|
905
|
+
status(waiting ? { state: 'waiting', waitingSince: at } : { state: 'done', finished: at });
|
|
906
|
+
};
|
|
907
|
+
|
|
908
|
+
/**
|
|
909
|
+
* An interrupt outcome: a `tool_call` interrupt for a known call gates it, if nothing has yet;
|
|
910
|
+
* any other interrupt is the application's.
|
|
911
|
+
* @param {AgUiEvent} event @param {unknown[]} interrupts
|
|
912
|
+
*/
|
|
913
|
+
const interrupted = (event, interrupts) => {
|
|
914
|
+
let other = interrupts.length === 0;
|
|
915
|
+
for (const interrupt of interrupts) {
|
|
916
|
+
const callId = isObject(interrupt) && interrupt.reason === 'tool_call' && typeof interrupt.toolCallId === 'string'
|
|
917
|
+
? interrupt.toolCallId : null;
|
|
918
|
+
const entry = callId ? calls.get(callId) : undefined;
|
|
919
|
+
if (!entry) {
|
|
920
|
+
other = true;
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
923
|
+
if (!entry.gated && !entry.decided && entry.kind !== 'surface' && entry.call.status === 'running') gate(entry);
|
|
924
|
+
}
|
|
925
|
+
if (other) unknown(event);
|
|
926
|
+
};
|
|
927
|
+
|
|
928
|
+
/** @param {AgUiEvent} event */
|
|
929
|
+
const runError = (event) => {
|
|
930
|
+
const run = active ?? lastRun;
|
|
931
|
+
if (active) closeRun(active, 'failed', stamp(event));
|
|
932
|
+
// A run that already ended, or a stream refused before it began: what waits for a person from
|
|
933
|
+
// an earlier run is not this error's to close.
|
|
934
|
+
else report('no-run', 'RUN_ERROR arrived outside a run; the last run reads as failed, and what waits for a person stays open', { event });
|
|
935
|
+
active = null;
|
|
936
|
+
const text = String(event.message ?? '');
|
|
937
|
+
const key = run ? `error:${run.id}` : 'error';
|
|
938
|
+
let id = key;
|
|
939
|
+
if (run) {
|
|
940
|
+
run.errors += 1;
|
|
941
|
+
if (run.errors > 1) id = `${key}#${run.errors}`;
|
|
942
|
+
} else {
|
|
943
|
+
id = `${key}:${timeOf(event)}`;
|
|
944
|
+
}
|
|
945
|
+
place(/** @type {ThreadItem} */ ({
|
|
946
|
+
id, type: 'notice', tone: 'danger',
|
|
947
|
+
text: text ? thread.msg('agUi.runFailedWith', text) : thread.msg('agUi.runFailed')
|
|
948
|
+
}));
|
|
949
|
+
status({ state: 'failed', finished: new Date(timeOf(event)) });
|
|
950
|
+
};
|
|
951
|
+
|
|
952
|
+
/** @param {AgUiEvent} event */
|
|
953
|
+
const textStart = (event) => {
|
|
954
|
+
const run = inRun(event);
|
|
955
|
+
if (!run) return;
|
|
956
|
+
const id = String(event.messageId);
|
|
957
|
+
const known = messages.get(id);
|
|
958
|
+
if (known?.open) {
|
|
959
|
+
report('duplicate-start', `Message "${id}" is already open; the start was ignored`, { event });
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
if (known) {
|
|
963
|
+
reopenMessage(known, run);
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
const reserved = RESERVED.test(id);
|
|
967
|
+
if (reserved) report('not-allowed', `Message id "${id}" uses a prefix the adapter keeps for its own items; the message was dropped`, { event });
|
|
968
|
+
const role = event.role ?? 'assistant';
|
|
969
|
+
const name = typeof event.name === 'string' && Object.hasOwn(authors, event.name) ? event.name : null;
|
|
970
|
+
/** @type {Message} */
|
|
971
|
+
const message = {
|
|
972
|
+
id, run, open: true, ignored: reserved || role !== 'assistant', author: name ?? agent, segments: [id], written: new Set(),
|
|
973
|
+
afterFence: false, pending: new Set(), surfaces: 0, splitter: null
|
|
974
|
+
};
|
|
975
|
+
messages.set(id, message);
|
|
976
|
+
if (message.ignored) {
|
|
977
|
+
if (!reserved) unknown(event);
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
if (inlineSurfaces) message.splitter = splitterFor(message);
|
|
981
|
+
place(/** @type {ThreadItem} */ ({ id, type: 'answer', ...by(message.author), blocks: [], streaming: true }));
|
|
982
|
+
};
|
|
983
|
+
|
|
984
|
+
/** @param {AgUiEvent} event */
|
|
985
|
+
const textContent = (event) => {
|
|
986
|
+
const message = messages.get(String(event.messageId));
|
|
987
|
+
if (!message || !message.open) {
|
|
988
|
+
report('out-of-order', `Content for message "${String(event.messageId)}", which is not open, was dropped`, { event });
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
if (message.ignored) return;
|
|
992
|
+
const delta = String(event.delta);
|
|
993
|
+
if (message.splitter) message.splitter.write(delta);
|
|
994
|
+
else prose(message, delta);
|
|
995
|
+
};
|
|
996
|
+
|
|
997
|
+
/** @param {AgUiEvent} event */
|
|
998
|
+
const textEnd = (event) => {
|
|
999
|
+
const message = messages.get(String(event.messageId));
|
|
1000
|
+
if (!message || !message.open) {
|
|
1001
|
+
report('out-of-order', `The end of message "${String(event.messageId)}", which is not open, was dropped`, { event });
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
endMessage(message);
|
|
1005
|
+
};
|
|
1006
|
+
|
|
1007
|
+
/** @param {AgUiEvent} event */
|
|
1008
|
+
const toolStart = (event) => {
|
|
1009
|
+
const run = inRun(event);
|
|
1010
|
+
if (!run) return;
|
|
1011
|
+
const id = String(event.toolCallId);
|
|
1012
|
+
const known = calls.get(id);
|
|
1013
|
+
if (known?.open || (known && isSettled(known))) {
|
|
1014
|
+
report('duplicate-start', `Tool call "${id}" is ${known.open ? 'already open' : 'settled'}; the start was ignored`, { event });
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
if (known) {
|
|
1018
|
+
reopenCall(known, run);
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
const name = String(event.toolCallName);
|
|
1022
|
+
const kind = typeof tools[name] === 'function' && Object.hasOwn(tools, name) ? 'tile' : surfaceTools.has(name) ? 'surface' : 'step';
|
|
1023
|
+
/** @type {TraceStep} */
|
|
1024
|
+
const step = kind === 'surface'
|
|
1025
|
+
? { id, kind: 'ask', label: thread.msg('agUi.asked'), tool: name, status: 'queued' }
|
|
1026
|
+
: { id, kind: 'call', label: thread.msg('agUi.called', name), doing: thread.msg('agUi.calling', name), tool: name, status: 'queued' };
|
|
1027
|
+
/** @type {Call} */
|
|
1028
|
+
const entry = {
|
|
1029
|
+
call: { id, name, args: null, argsText: '', status: 'queued' }, kind, run, traceId: addStep(run, step), open: true,
|
|
1030
|
+
startedAt: stamp(event), gated: false, decided: false, tileId: null, placeholder: null, surfaceId: null, items: []
|
|
1031
|
+
};
|
|
1032
|
+
calls.set(id, entry);
|
|
1033
|
+
if (kind === 'surface') standIn(entry);
|
|
1034
|
+
else if (kind === 'tile') renderTile(entry);
|
|
1035
|
+
};
|
|
1036
|
+
|
|
1037
|
+
/** @param {AgUiEvent} event */
|
|
1038
|
+
const toolArgs = (event) => {
|
|
1039
|
+
const entry = calls.get(String(event.toolCallId));
|
|
1040
|
+
if (!entry || !entry.open) {
|
|
1041
|
+
report('out-of-order', `Arguments for tool call "${String(event.toolCallId)}", which is not open, were dropped`, { event });
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
entry.call.argsText += String(event.delta);
|
|
1045
|
+
};
|
|
1046
|
+
|
|
1047
|
+
/** @param {AgUiEvent} event */
|
|
1048
|
+
const toolEnd = (event) => {
|
|
1049
|
+
const entry = calls.get(String(event.toolCallId));
|
|
1050
|
+
if (!entry || !entry.open) {
|
|
1051
|
+
report('out-of-order', `The end of tool call "${String(event.toolCallId)}", which is not open, was dropped`, { event });
|
|
1052
|
+
return;
|
|
1053
|
+
}
|
|
1054
|
+
entry.open = false;
|
|
1055
|
+
const { call } = entry;
|
|
1056
|
+
const parsed = parseArguments(call.argsText);
|
|
1057
|
+
if (entry.kind === 'surface') {
|
|
1058
|
+
surfaceArguments(entry, parsed);
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
if (parsed.ok) call.args = parsed.value;
|
|
1062
|
+
let gated = false;
|
|
1063
|
+
if (typeof options.requiresApproval === 'function') {
|
|
1064
|
+
try {
|
|
1065
|
+
gated = Boolean(options.requiresApproval(structuredClone(call)));
|
|
1066
|
+
} catch (error) {
|
|
1067
|
+
gated = true;
|
|
1068
|
+
report('approval-check', `requiresApproval failed for "${call.name}"; the call waits for a person`, { cause: error });
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
if (gated) gate(entry);
|
|
1072
|
+
else setStatus(entry, 'running', {}, { args: call.argsText });
|
|
1073
|
+
};
|
|
1074
|
+
|
|
1075
|
+
/** @param {AgUiEvent} event */
|
|
1076
|
+
const toolResult = (event) => {
|
|
1077
|
+
if (!inRun(event)) return;
|
|
1078
|
+
const entry = calls.get(String(event.toolCallId));
|
|
1079
|
+
if (!entry || entry.open) {
|
|
1080
|
+
report('out-of-order', `A result for tool call "${String(event.toolCallId)}", whose arguments are not complete, was dropped`, { event });
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
const content = event.content;
|
|
1084
|
+
const text = typeof content === 'string' ? content
|
|
1085
|
+
: /** @type {unknown[]} */ (content).filter((part) => isObject(part) && part.type === 'text' && typeof part.text === 'string')
|
|
1086
|
+
.map((part) => String(/** @type {any} */ (part).text)).join('\n');
|
|
1087
|
+
const duration = elapsed(entry.startedAt, stamp(event));
|
|
1088
|
+
const timing = duration === null ? {} : { ms: duration };
|
|
1089
|
+
// A rejected or stopped call keeps its status: the result is only recorded.
|
|
1090
|
+
if (entry.call.status === 'skipped' || entry.call.status === 'stopped') {
|
|
1091
|
+
setStatus(entry, entry.call.status, { result: structuredClone(content) }, { result: text });
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
if (entry.gated && !entry.decided) {
|
|
1095
|
+
report('out-of-order', `Tool call "${entry.call.id}" has a result before the person decided; its approval expired`, { event });
|
|
1096
|
+
expire(entry);
|
|
1097
|
+
}
|
|
1098
|
+
if (entry.surfaceId && !entry.decided) {
|
|
1099
|
+
report('out-of-order', `Tool call "${entry.call.id}" has a result before the person answered; its surface was cancelled`, { event });
|
|
1100
|
+
entry.decided = true;
|
|
1101
|
+
thread.surface(entry.surfaceId)?.cancel('stopped');
|
|
1102
|
+
}
|
|
1103
|
+
setStatus(entry, 'done', { result: structuredClone(content) }, { result: text, ...timing });
|
|
1104
|
+
};
|
|
1105
|
+
|
|
1106
|
+
/** @param {AgUiEvent} event */
|
|
1107
|
+
const stateSnapshot = (event) => {
|
|
1108
|
+
if (!inRun(event)) return;
|
|
1109
|
+
try {
|
|
1110
|
+
state = structuredClone(event.snapshot);
|
|
1111
|
+
} catch (error) {
|
|
1112
|
+
report('state', 'The state snapshot is not plain data', { event, cause: error });
|
|
1113
|
+
return;
|
|
1114
|
+
}
|
|
1115
|
+
if (typeof options.onstate === 'function') options.onstate(structuredClone(state));
|
|
1116
|
+
};
|
|
1117
|
+
|
|
1118
|
+
/** @param {AgUiEvent} event */
|
|
1119
|
+
const stateDelta = (event) => {
|
|
1120
|
+
if (!inRun(event)) return;
|
|
1121
|
+
try {
|
|
1122
|
+
state = applyPatch(state, /** @type {any} */ (event.delta));
|
|
1123
|
+
} catch (error) {
|
|
1124
|
+
report('state', `The state delta does not apply: ${messageOf(error)}`, { event, cause: error });
|
|
1125
|
+
return;
|
|
1126
|
+
}
|
|
1127
|
+
if (typeof options.onstate === 'function') options.onstate(structuredClone(state));
|
|
1128
|
+
};
|
|
1129
|
+
|
|
1130
|
+
/** @param {AgUiEvent} event */
|
|
1131
|
+
const custom = (event) => {
|
|
1132
|
+
if (event.name !== surfaceEvent) {
|
|
1133
|
+
unknown(event);
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
const run = inRun(event);
|
|
1137
|
+
if (!run) return;
|
|
1138
|
+
const value = event.value;
|
|
1139
|
+
/** @type {unknown[]} */
|
|
1140
|
+
let ops;
|
|
1141
|
+
let token = null;
|
|
1142
|
+
let badToken = false;
|
|
1143
|
+
if (isObject(value) && Array.isArray(value.ops)) {
|
|
1144
|
+
ops = value.ops;
|
|
1145
|
+
if (value.token != null) {
|
|
1146
|
+
// Checked only where the event opens a surface; elsewhere the token is ignored.
|
|
1147
|
+
if (typeof value.token === 'string' && value.token.length <= MAX_TOKEN) token = value.token;
|
|
1148
|
+
else badToken = true;
|
|
1149
|
+
}
|
|
1150
|
+
} else if (isObject(value) && typeof value.op === 'string') {
|
|
1151
|
+
ops = [value];
|
|
1152
|
+
} else {
|
|
1153
|
+
report('invalid-event', `The value of "${surfaceEvent}" is neither an operation nor {ops}; it was dropped`, { event });
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1156
|
+
for (const op of ops) routeOp(op, { source: 'custom', run, token, badToken, event });
|
|
1157
|
+
};
|
|
1158
|
+
|
|
1159
|
+
/** @param {AgUiEvent} event */
|
|
1160
|
+
const reason = (event) => {
|
|
1161
|
+
const run = inRun(event);
|
|
1162
|
+
if (!run) return;
|
|
1163
|
+
const id = String(event.messageId);
|
|
1164
|
+
const orphan = (/** @type {string} */ what) => report('out-of-order', `${what} outside an open reasoning span was dropped`, { event });
|
|
1165
|
+
switch (event.type) {
|
|
1166
|
+
case 'REASONING_START': {
|
|
1167
|
+
if (reasoning || spans.has(id)) {
|
|
1168
|
+
report('duplicate-start', `Reasoning "${id}" started while another was open or after it ended; ignored`, { event });
|
|
1169
|
+
return;
|
|
1170
|
+
}
|
|
1171
|
+
spans.add(id);
|
|
1172
|
+
const stepId = `think:${id}`;
|
|
1173
|
+
const traceId = addStep(run, { id: stepId, kind: 'think', label: thread.msg('agUi.thinking'), doing: thread.msg('agUi.thinking'), status: 'running' });
|
|
1174
|
+
reasoning = { id, start: stamp(event), stepId, traceId, text: '', open: new Set(), seen: new Set() };
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
case 'REASONING_MESSAGE_START':
|
|
1178
|
+
if (!reasoning) return orphan('A reasoning message');
|
|
1179
|
+
if (reasoning.seen.has(id)) {
|
|
1180
|
+
report('duplicate-start', `Reasoning message "${id}" has already started; the start was ignored`, { event });
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
reasoning.seen.add(id);
|
|
1184
|
+
reasoning.open.add(id);
|
|
1185
|
+
return;
|
|
1186
|
+
case 'REASONING_MESSAGE_CONTENT':
|
|
1187
|
+
if (!reasoning?.open.has(id)) return orphan('Reasoning content');
|
|
1188
|
+
if (showReasoning) reasoning.text += String(event.delta);
|
|
1189
|
+
return;
|
|
1190
|
+
case 'REASONING_MESSAGE_END':
|
|
1191
|
+
if (!reasoning?.open.has(id)) return orphan('The end of a reasoning message');
|
|
1192
|
+
reasoning.open.delete(id);
|
|
1193
|
+
if (showReasoning) reasoning.text += '\n\n';
|
|
1194
|
+
return;
|
|
1195
|
+
default:
|
|
1196
|
+
if (!reasoning || reasoning.id !== id) return orphan('The end of reasoning');
|
|
1197
|
+
reasoning.text = reasoning.text.trim();
|
|
1198
|
+
endReasoning(stamp(event));
|
|
1199
|
+
}
|
|
1200
|
+
};
|
|
1201
|
+
|
|
1202
|
+
/* ------------------------------------------------------------------ chunks -- */
|
|
1203
|
+
|
|
1204
|
+
/**
|
|
1205
|
+
* Expands chunk events into start, content and end events, and ends an open chunk stream when
|
|
1206
|
+
* another event arrives.
|
|
1207
|
+
* @param {AgUiEvent} event
|
|
1208
|
+
* @returns {AgUiEvent[]}
|
|
1209
|
+
*/
|
|
1210
|
+
const expand = (event) => {
|
|
1211
|
+
/** @type {AgUiEvent[]} */
|
|
1212
|
+
const out = [];
|
|
1213
|
+
const stamp = typeof event.timestamp === 'number' ? { timestamp: event.timestamp } : {};
|
|
1214
|
+
/** @param {'text'|'tool'|'reasoning'} lane */
|
|
1215
|
+
const close = (lane) => {
|
|
1216
|
+
const open = chunk[lane];
|
|
1217
|
+
chunk[lane] = null;
|
|
1218
|
+
if (!open?.owned) return;
|
|
1219
|
+
if (lane === 'text') out.push({ type: 'TEXT_MESSAGE_END', messageId: open.id, ...stamp });
|
|
1220
|
+
else if (lane === 'tool') out.push({ type: 'TOOL_CALL_END', toolCallId: open.id, ...stamp });
|
|
1221
|
+
else out.push({ type: 'REASONING_MESSAGE_END', messageId: open.id, ...stamp });
|
|
1222
|
+
};
|
|
1223
|
+
const lanes = /** @type {const} */ (['text', 'tool', 'reasoning']);
|
|
1224
|
+
const lane = event.type === 'TEXT_MESSAGE_CHUNK' ? 'text' : event.type === 'TOOL_CALL_CHUNK' ? 'tool'
|
|
1225
|
+
: event.type === 'REASONING_MESSAGE_CHUNK' ? 'reasoning' : null;
|
|
1226
|
+
if (!lane) {
|
|
1227
|
+
if (!PASSING.has(event.type)) for (const other of lanes) close(other);
|
|
1228
|
+
out.push(event);
|
|
1229
|
+
return out;
|
|
1230
|
+
}
|
|
1231
|
+
for (const other of lanes) if (other !== lane) close(other);
|
|
1232
|
+
const key = lane === 'tool' ? 'toolCallId' : 'messageId';
|
|
1233
|
+
const id = typeof event[key] === 'string' && event[key] ? String(event[key]) : null;
|
|
1234
|
+
if (id && id !== chunk[lane]?.id) {
|
|
1235
|
+
close(lane);
|
|
1236
|
+
if (lane === 'text') {
|
|
1237
|
+
const known = messages.get(id);
|
|
1238
|
+
const owned = !known?.open;
|
|
1239
|
+
chunk.text = { id, owned };
|
|
1240
|
+
if (owned) {
|
|
1241
|
+
out.push({
|
|
1242
|
+
type: 'TEXT_MESSAGE_START', messageId: id, ...stamp,
|
|
1243
|
+
...(event.role !== undefined ? { role: event.role } : {}), ...(event.name !== undefined ? { name: event.name } : {})
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
1246
|
+
} else if (lane === 'tool') {
|
|
1247
|
+
const owned = !calls.get(id)?.open;
|
|
1248
|
+
if (owned && (typeof event.toolCallName !== 'string' || !event.toolCallName)) {
|
|
1249
|
+
report('invalid-event', 'The first TOOL_CALL_CHUNK of a call needs "toolCallName"; it was dropped', { event });
|
|
1250
|
+
return out;
|
|
1251
|
+
}
|
|
1252
|
+
chunk.tool = { id, owned };
|
|
1253
|
+
if (owned) {
|
|
1254
|
+
out.push({
|
|
1255
|
+
type: 'TOOL_CALL_START', toolCallId: id, toolCallName: event.toolCallName, ...stamp,
|
|
1256
|
+
...(event.parentMessageId !== undefined ? { parentMessageId: event.parentMessageId } : {})
|
|
1257
|
+
});
|
|
1258
|
+
}
|
|
1259
|
+
} else {
|
|
1260
|
+
const owned = !reasoning?.open.has(id);
|
|
1261
|
+
chunk.reasoning = { id, owned };
|
|
1262
|
+
if (owned) out.push({ type: 'REASONING_MESSAGE_START', messageId: id, role: 'reasoning', ...stamp });
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
const current = chunk[lane];
|
|
1266
|
+
if (!current) {
|
|
1267
|
+
report('invalid-event', `The first ${event.type} needs "${key}"; it was dropped`, { event });
|
|
1268
|
+
return out;
|
|
1269
|
+
}
|
|
1270
|
+
if (event.delta !== undefined && typeof event.delta !== 'string') {
|
|
1271
|
+
report('invalid-event', `${event.type} has a "delta" that is not a string; it was dropped`, { event });
|
|
1272
|
+
return out;
|
|
1273
|
+
}
|
|
1274
|
+
if (typeof event.delta === 'string' && event.delta !== '') {
|
|
1275
|
+
if (lane === 'text') out.push({ type: 'TEXT_MESSAGE_CONTENT', messageId: current.id, delta: event.delta, ...stamp });
|
|
1276
|
+
else if (lane === 'tool') out.push({ type: 'TOOL_CALL_ARGS', toolCallId: current.id, delta: event.delta, ...stamp });
|
|
1277
|
+
else out.push({ type: 'REASONING_MESSAGE_CONTENT', messageId: current.id, delta: event.delta, ...stamp });
|
|
1278
|
+
}
|
|
1279
|
+
return out;
|
|
1280
|
+
};
|
|
1281
|
+
|
|
1282
|
+
/* ------------------------------------------------------------------ thread events -- */
|
|
1283
|
+
|
|
1284
|
+
/** @param {Event} event */
|
|
1285
|
+
const onOpen = (event) => {
|
|
1286
|
+
const { ref, step } = /** @type {CustomEvent<{ref?: {id?: unknown}, step?: TraceStep}>} */ (event).detail ?? {};
|
|
1287
|
+
const id = ref ? String(ref.id) : '';
|
|
1288
|
+
if (step && tileRefs.has(id) && id === `tool:${step.id}`) thread.reveal(`item:${id}`);
|
|
1289
|
+
};
|
|
1290
|
+
|
|
1291
|
+
/** @param {Event} event */
|
|
1292
|
+
const onReply = (event) => {
|
|
1293
|
+
const { item, reply } = /** @type {CustomEvent<{item?: ThreadItem, reply: SurfaceReply}>} */ (event).detail ?? {};
|
|
1294
|
+
const callId = item ? surfaceCalls.get(String(item.id)) : undefined;
|
|
1295
|
+
const entry = callId ? calls.get(callId) : undefined;
|
|
1296
|
+
if (!entry || !reply || entry.decided) return;
|
|
1297
|
+
entry.decided = true;
|
|
1298
|
+
const errors = thread.surface(String(item?.id))?.getErrors() ?? [];
|
|
1299
|
+
const result = /** @type {Record<string, unknown>} */ ({ ...structuredClone(reply), ...(errors.length ? { errors } : {}) });
|
|
1300
|
+
setStatus(entry, reply.reason === 'stopped' ? 'stopped' : 'done', { result }, { result: JSON.stringify(reply) });
|
|
1301
|
+
answer(entry.call.id, result);
|
|
1302
|
+
};
|
|
1303
|
+
|
|
1304
|
+
/**
|
|
1305
|
+
* An approval decision, once the thread's own listeners have had their say: a prevented
|
|
1306
|
+
* decision keeps the card pending.
|
|
1307
|
+
* @param {boolean} approved
|
|
1308
|
+
* @returns {(event: Event) => void}
|
|
1309
|
+
*/
|
|
1310
|
+
const onDecision = (approved) => (event) => {
|
|
1311
|
+
const detail = /** @type {CustomEvent<{item?: ThreadItem, values?: Record<string, unknown>, reason?: string}>} */ (event).detail ?? {};
|
|
1312
|
+
const callId = detail.item ? approvals.get(String(detail.item.id)) : undefined;
|
|
1313
|
+
const entry = callId ? calls.get(callId) : undefined;
|
|
1314
|
+
if (!entry || entry.decided || entry.call.status !== 'waiting') return;
|
|
1315
|
+
queueMicrotask(() => {
|
|
1316
|
+
if (event.defaultPrevented || entry.decided || destroyed || entry.call.status !== 'waiting') return;
|
|
1317
|
+
entry.decided = true;
|
|
1318
|
+
if (approved) {
|
|
1319
|
+
const values = isObject(detail.values) && Object.keys(detail.values).length ? { values: structuredClone(detail.values) } : {};
|
|
1320
|
+
setStatus(entry, 'running');
|
|
1321
|
+
answer(entry.call.id, { approved: true, ...values });
|
|
1322
|
+
} else {
|
|
1323
|
+
setStatus(entry, 'skipped');
|
|
1324
|
+
answer(entry.call.id, { approved: false, ...(typeof detail.reason === 'string' && detail.reason ? { reason: detail.reason } : {}) });
|
|
1325
|
+
}
|
|
1326
|
+
});
|
|
1327
|
+
};
|
|
1328
|
+
const onApprove = onDecision(true);
|
|
1329
|
+
const onReject = onDecision(false);
|
|
1330
|
+
|
|
1331
|
+
thread.on('open', onOpen);
|
|
1332
|
+
thread.on('reply', onReply);
|
|
1333
|
+
thread.on('approve', onApprove);
|
|
1334
|
+
thread.on('reject', onReject);
|
|
1335
|
+
|
|
1336
|
+
return {
|
|
1337
|
+
handle(event) {
|
|
1338
|
+
if (destroyed) return;
|
|
1339
|
+
if (!isObject(event) || typeof event.type !== 'string' || !event.type) {
|
|
1340
|
+
report('invalid-event', 'An event must be an object with a "type"; it was dropped');
|
|
1341
|
+
return;
|
|
1342
|
+
}
|
|
1343
|
+
try {
|
|
1344
|
+
for (const expanded of expand(/** @type {AgUiEvent} */ (event))) dispatch(expanded);
|
|
1345
|
+
} catch (error) {
|
|
1346
|
+
report('internal', `${safeText(event.type)} could not be handled and was dropped: ${messageOf(error)}`, { event, cause: error });
|
|
1347
|
+
}
|
|
1348
|
+
},
|
|
1349
|
+
state() {
|
|
1350
|
+
return structuredClone(state);
|
|
1351
|
+
},
|
|
1352
|
+
destroy() {
|
|
1353
|
+
if (destroyed) return;
|
|
1354
|
+
destroyed = true;
|
|
1355
|
+
if (active) {
|
|
1356
|
+
closeRun(active, 'stopped');
|
|
1357
|
+
active = null;
|
|
1358
|
+
status({ state: 'stopped', finished: new Date() });
|
|
1359
|
+
}
|
|
1360
|
+
for (const entry of calls.values()) {
|
|
1361
|
+
if (entry.decided) continue;
|
|
1362
|
+
if (entry.surfaceId) thread.surface(entry.surfaceId)?.cancel('stopped');
|
|
1363
|
+
if (entry.gated && !entry.decided) {
|
|
1364
|
+
expire(entry);
|
|
1365
|
+
setStatus(entry, 'stopped');
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
thread.off('open', onOpen);
|
|
1369
|
+
thread.off('reply', onReply);
|
|
1370
|
+
thread.off('approve', onApprove);
|
|
1371
|
+
thread.off('reject', onReject);
|
|
1372
|
+
}
|
|
1373
|
+
};
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
/* ------------------------------------------------------------------ helpers -- */
|
|
1377
|
+
|
|
1378
|
+
/** @param {unknown} value @returns {value is Record<string, any>} */
|
|
1379
|
+
function isObject(value) {
|
|
1380
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
/**
|
|
1384
|
+
* Whether a field has the shape its event type needs.
|
|
1385
|
+
* @param {unknown} value @param {'id'|'text'|'array'|'content'|'present'} kind @param {boolean} present
|
|
1386
|
+
* @returns {boolean}
|
|
1387
|
+
*/
|
|
1388
|
+
function fits(value, kind, present) {
|
|
1389
|
+
switch (kind) {
|
|
1390
|
+
case 'id': return typeof value === 'string' && value !== '';
|
|
1391
|
+
case 'text': return typeof value === 'string';
|
|
1392
|
+
case 'array': return Array.isArray(value);
|
|
1393
|
+
case 'content': return typeof value === 'string' || Array.isArray(value);
|
|
1394
|
+
default: return present;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
/**
|
|
1399
|
+
* A call's complete arguments. No arguments at all read as an empty object, which is how a tool
|
|
1400
|
+
* without parameters is called.
|
|
1401
|
+
* @param {string} text
|
|
1402
|
+
* @returns {{ok: boolean, value?: unknown}}
|
|
1403
|
+
*/
|
|
1404
|
+
function parseArguments(text) {
|
|
1405
|
+
if (!text.trim()) return { ok: true, value: {} };
|
|
1406
|
+
try {
|
|
1407
|
+
return { ok: true, value: JSON.parse(text) };
|
|
1408
|
+
} catch {
|
|
1409
|
+
return { ok: false };
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
/** @param {string} text @returns {string} The arguments indented, or as they are when not JSON. */
|
|
1414
|
+
function pretty(text) {
|
|
1415
|
+
try {
|
|
1416
|
+
return JSON.stringify(JSON.parse(text), null, 2);
|
|
1417
|
+
} catch {
|
|
1418
|
+
return text;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
/** @param {unknown} error @returns {string} */
|
|
1423
|
+
function messageOf(error) {
|
|
1424
|
+
return error instanceof Error ? error.message : safeText(error);
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
/**
|
|
1428
|
+
* Any value as text for a message, without running code a hostile object carries.
|
|
1429
|
+
* @param {unknown} value
|
|
1430
|
+
* @returns {string}
|
|
1431
|
+
*/
|
|
1432
|
+
function safeText(value) {
|
|
1433
|
+
if (typeof value === 'string') return JSON.stringify(value);
|
|
1434
|
+
try {
|
|
1435
|
+
return JSON.stringify(value) ?? typeof value;
|
|
1436
|
+
} catch {
|
|
1437
|
+
return typeof value;
|
|
1438
|
+
}
|
|
1439
|
+
}
|