@valerypopoff/rivet2-core 2.1.3 → 2.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/dist/cjs/bundle.cjs +10138 -5679
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +1214 -0
  4. package/dist/cjs/webAppRuntime.cjs.map +7 -0
  5. package/dist/esm/api/createProcessor.js +8 -1
  6. package/dist/esm/api/streaming.js +6 -0
  7. package/dist/esm/exports.js +8 -0
  8. package/dist/esm/integrations/mcp/MCPBase.js +92 -34
  9. package/dist/esm/model/GraphBoundaryEffects.js +13 -0
  10. package/dist/esm/model/GraphProcessor.js +1138 -86
  11. package/dist/esm/model/GraphProgress.js +15 -0
  12. package/dist/esm/model/ManagedAsyncBranches.js +28 -0
  13. package/dist/esm/model/Nodes.js +12 -0
  14. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  15. package/dist/esm/model/RecordingPlayer.js +19 -0
  16. package/dist/esm/model/StoredValueStore.js +226 -0
  17. package/dist/esm/model/SubprocessorBridge.js +50 -18
  18. package/dist/esm/model/ToolCallContinuation.js +1 -0
  19. package/dist/esm/model/UiGraph.js +177 -4
  20. package/dist/esm/model/UiGraphActionProtocol.js +131 -0
  21. package/dist/esm/model/UiGraphBindings.js +530 -0
  22. package/dist/esm/model/UiGraphBrowserRuntime.js +373 -0
  23. package/dist/esm/model/UiGraphNormalization.js +148 -0
  24. package/dist/esm/model/UiGraphRendererStyles.js +1108 -42
  25. package/dist/esm/model/UiGraphRuntimeModel.js +518 -2
  26. package/dist/esm/model/UiGraphSchema.js +91 -0
  27. package/dist/esm/model/UiGraphWebAppStatus.js +19 -0
  28. package/dist/esm/model/UiGraphWebAppStorage.js +1 -0
  29. package/dist/esm/model/chat/chatMessages.js +5 -9
  30. package/dist/esm/model/chat-v2/chatV2Errors.js +36 -3
  31. package/dist/esm/model/chat-v2/index.js +1 -0
  32. package/dist/esm/model/chat-v2/toolContinuation.js +6 -8
  33. package/dist/esm/model/chat-v2/toolContinuationConnection.js +68 -0
  34. package/dist/esm/model/nodes/ArrayNode.js +2 -13
  35. package/dist/esm/model/nodes/AssembleMessageNode.js +2 -13
  36. package/dist/esm/model/nodes/AssemblePromptNode.js +2 -13
  37. package/dist/esm/model/nodes/CoalesceNode.js +2 -15
  38. package/dist/esm/model/nodes/DelayNode.js +3 -14
  39. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
  40. package/dist/esm/model/nodes/DidRunNode.js +2 -13
  41. package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
  42. package/dist/esm/model/nodes/JoinNode.js +2 -13
  43. package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
  44. package/dist/esm/model/nodes/LoopControllerNode.js +3 -14
  45. package/dist/esm/model/nodes/MCPDiscoveryNode.js +19 -90
  46. package/dist/esm/model/nodes/MCPGetPromptNode.js +11 -97
  47. package/dist/esm/model/nodes/MCPToolCallNode.js +11 -97
  48. package/dist/esm/model/nodes/MatchNode.js +7 -7
  49. package/dist/esm/model/nodes/PassthroughNode.js +3 -14
  50. package/dist/esm/model/nodes/RaceInputsNode.js +2 -13
  51. package/dist/esm/model/nodes/ReportProgressNode.js +57 -0
  52. package/dist/esm/model/nodes/SetStoredValueNode.js +84 -0
  53. package/dist/esm/model/nodes/StartBackgroundBranchNode.js +59 -0
  54. package/dist/esm/model/nodes/StoredValueNodeUtils.js +47 -0
  55. package/dist/esm/model/nodes/toolCallDelegation.js +44 -1
  56. package/dist/esm/model/nodes/variadicPortIndex.js +32 -0
  57. package/dist/esm/plugins/anthropic/anthropic.js +1 -1
  58. package/dist/esm/recording/ExecutionRecorder.js +6 -0
  59. package/dist/esm/utils/coerceType.js +3 -0
  60. package/dist/esm/utils/fetchEventSource.js +16 -17
  61. package/dist/esm/utils/serialization/serialization.js +4 -0
  62. package/dist/esm/utils/serialization/serializationUtils.js +8 -27
  63. package/dist/esm/utils/serialization/serialization_v4.js +3 -3
  64. package/dist/esm/webAppRuntime.js +4 -2
  65. package/dist/types/api/createProcessor.d.ts +4 -0
  66. package/dist/types/api/streaming.d.ts +6 -0
  67. package/dist/types/exports.d.ts +8 -0
  68. package/dist/types/integrations/mcp/MCPBase.d.ts +26 -3
  69. package/dist/types/model/EditorDefinition.d.ts +2 -1
  70. package/dist/types/model/ExecutorProtocol.d.ts +19 -0
  71. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
  72. package/dist/types/model/GraphProcessor.d.ts +26 -2
  73. package/dist/types/model/GraphProgress.d.ts +6 -0
  74. package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
  75. package/dist/types/model/Nodes.d.ts +6 -2
  76. package/dist/types/model/ProcessContext.d.ts +18 -0
  77. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  78. package/dist/types/model/StoredValueStore.d.ts +55 -0
  79. package/dist/types/model/SubprocessorBridge.d.ts +4 -2
  80. package/dist/types/model/ToolCallContinuation.d.ts +13 -0
  81. package/dist/types/model/UiGraph.d.ts +63 -9
  82. package/dist/types/model/UiGraphActionProtocol.d.ts +71 -0
  83. package/dist/types/model/UiGraphBindings.d.ts +45 -0
  84. package/dist/types/model/UiGraphBrowserRuntime.d.ts +55 -0
  85. package/dist/types/model/UiGraphNormalization.d.ts +24 -0
  86. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
  87. package/dist/types/model/UiGraphRuntimeModel.d.ts +97 -6
  88. package/dist/types/model/UiGraphSchema.d.ts +113 -0
  89. package/dist/types/model/UiGraphWebAppStatus.d.ts +5 -0
  90. package/dist/types/model/UiGraphWebAppStorage.d.ts +3 -0
  91. package/dist/types/model/chat-v2/index.d.ts +1 -0
  92. package/dist/types/model/chat-v2/toolContinuation.d.ts +1 -0
  93. package/dist/types/model/chat-v2/toolContinuationConnection.d.ts +28 -0
  94. package/dist/types/model/nodes/ArrayNode.d.ts +0 -1
  95. package/dist/types/model/nodes/AssembleMessageNode.d.ts +0 -1
  96. package/dist/types/model/nodes/AssemblePromptNode.d.ts +0 -1
  97. package/dist/types/model/nodes/DelayNode.d.ts +0 -1
  98. package/dist/types/model/nodes/DidRunNode.d.ts +0 -1
  99. package/dist/types/model/nodes/GetStoredValueNode.d.ts +25 -0
  100. package/dist/types/model/nodes/JoinNode.d.ts +0 -1
  101. package/dist/types/model/nodes/LoopControllerNode.d.ts +0 -1
  102. package/dist/types/model/nodes/PassthroughNode.d.ts +0 -1
  103. package/dist/types/model/nodes/RaceInputsNode.d.ts +0 -1
  104. package/dist/types/model/nodes/ReportProgressNode.d.ts +23 -0
  105. package/dist/types/model/nodes/SetStoredValueNode.d.ts +23 -0
  106. package/dist/types/model/nodes/StartBackgroundBranchNode.d.ts +14 -0
  107. package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +5 -0
  108. package/dist/types/model/nodes/toolCallDelegation.d.ts +4 -0
  109. package/dist/types/model/nodes/variadicPortIndex.d.ts +4 -0
  110. package/dist/types/recording/RecordedEvents.d.ts +10 -0
  111. package/dist/types/webAppRuntime.d.ts +8 -3
  112. package/package.json +2 -2
  113. package/dist/esm/plugins/anthropic/fetchEventSource.js +0 -107
  114. package/dist/types/plugins/anthropic/fetchEventSource.d.ts +0 -11
@@ -0,0 +1,1214 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/webAppRuntime.ts
21
+ var webAppRuntime_exports = {};
22
+ __export(webAppRuntime_exports, {
23
+ RIVET_WEB_APP_ACTION_PROTOCOL_VERSION: () => RIVET_WEB_APP_ACTION_PROTOCOL_VERSION,
24
+ applyUiGraphStatePatch: () => applyUiGraphStatePatch,
25
+ applyUiGraphWebAppStorageActionPatch: () => applyUiGraphWebAppStorageActionPatch,
26
+ applyUiGraphWebAppStoragePatch: () => applyUiGraphWebAppStoragePatch,
27
+ clearUiGraphChatSearchMatches: () => clearUiGraphChatSearchMatches,
28
+ copyUiGraphText: () => copyUiGraphText,
29
+ createUiGraphActionExecutionController: () => createUiGraphActionExecutionController,
30
+ createUiGraphChatHistoryFlushStatePatch: () => createUiGraphChatHistoryFlushStatePatch,
31
+ createUiGraphChatPinStatePatch: () => createUiGraphChatPinStatePatch,
32
+ createUiGraphChatSubmissionStatePatch: () => createUiGraphChatSubmissionStatePatch,
33
+ createUiGraphInteractionController: () => createUiGraphInteractionController,
34
+ downloadUiGraphJsonOutput: () => downloadUiGraphJsonOutput,
35
+ getUiGraphActionState: () => getUiGraphActionState,
36
+ getUiGraphChatDraftStateKey: () => getUiGraphChatDraftStateKey,
37
+ getUiGraphChatMessagesStateKey: () => getUiGraphChatMessagesStateKey,
38
+ getUiGraphChatPersistentState: () => getUiGraphChatPersistentState,
39
+ getUiGraphChatStorageKey: () => getUiGraphChatStorageKey,
40
+ getUiGraphComponentRenderModel: () => getUiGraphComponentRenderModel,
41
+ getUiGraphJsonOutputFilename: () => getUiGraphJsonOutputFilename,
42
+ getUiGraphProgressiveJsonOutputChunks: () => getUiGraphProgressiveJsonOutputChunks,
43
+ getUiGraphWebAppStorageKey: () => getUiGraphWebAppStorageKey,
44
+ hasUiGraphChatPersistentStateChanged: () => hasUiGraphChatPersistentStateChanged,
45
+ highlightUiGraphChatSearchMatches: () => highlightUiGraphChatSearchMatches,
46
+ loadUiGraphChatPersistentState: () => loadUiGraphChatPersistentState,
47
+ loadUiGraphWebAppStorage: () => loadUiGraphWebAppStorage,
48
+ observeUiGraphOutputResizeBounds: () => observeUiGraphOutputResizeBounds,
49
+ parseRivetWebAppClientMessage: () => parseRivetWebAppClientMessage,
50
+ parseRivetWebAppServerMessage: () => parseRivetWebAppServerMessage,
51
+ revealUiGraphChatElement: () => revealUiGraphChatElement,
52
+ revealUiGraphChatSearchMatch: () => revealUiGraphChatSearchMatch,
53
+ saveUiGraphChatPersistentState: () => saveUiGraphChatPersistentState
54
+ });
55
+ module.exports = __toCommonJS(webAppRuntime_exports);
56
+
57
+ // src/utils/newId.ts
58
+ var import_non_secure = require("nanoid/non-secure");
59
+
60
+ // src/model/UiGraph.ts
61
+ function getUiGraphInitialState(uiGraph) {
62
+ const state = {};
63
+ for (const component of uiGraph.components) {
64
+ if (component.type === "input" || component.type === "textarea") {
65
+ state[component.stateKey] = component.defaultValue ?? "";
66
+ } else if (component.type === "dropdown") {
67
+ state[component.stateKey] = "";
68
+ } else if (component.type === "chat") {
69
+ state[getUiGraphChatDraftStateKey(component.id)] = "";
70
+ state[getUiGraphChatMessagesStateKey(component.id)] = [];
71
+ state[getUiGraphChatPinsStateKey(component.id)] = [];
72
+ }
73
+ }
74
+ return state;
75
+ }
76
+ function getUiGraphChatDraftStateKey(componentId) {
77
+ return `__rivet_chat_${componentId}_draft`;
78
+ }
79
+ function getUiGraphChatMessagesStateKey(componentId) {
80
+ return `__rivet_chat_${componentId}_messages`;
81
+ }
82
+ function getUiGraphChatPinsStateKey(componentId) {
83
+ return `__rivet_chat_${componentId}_pins`;
84
+ }
85
+ function getUiGraphChatMessages(componentId, state) {
86
+ const messages = state[getUiGraphChatMessagesStateKey(componentId)];
87
+ return Array.isArray(messages) ? messages.filter(isUiGraphChatMessage) : [];
88
+ }
89
+ function getUiGraphChatPins(componentId, state) {
90
+ const messages = getUiGraphChatMessages(componentId, state);
91
+ const storedPins = state[getUiGraphChatPinsStateKey(componentId)];
92
+ const messageIndexes = Array.isArray(storedPins) ? [
93
+ ...new Set(
94
+ storedPins.filter(
95
+ (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0
96
+ )
97
+ )
98
+ ].sort((left, right) => left - right) : [];
99
+ const pinnedIndexes = new Set(messageIndexes);
100
+ const pins = [];
101
+ let prompt;
102
+ let promptMessageIndex;
103
+ messages.forEach((message, messageIndex) => {
104
+ if (message.role === "user") {
105
+ prompt = message;
106
+ promptMessageIndex = messageIndex;
107
+ } else if (pinnedIndexes.has(messageIndex)) {
108
+ pins.push({ messageIndex, prompt, promptMessageIndex, response: message });
109
+ }
110
+ });
111
+ return pins;
112
+ }
113
+ function createUiGraphChatPinStatePatch(componentId, state, messageIndex) {
114
+ var _a;
115
+ const messages = getUiGraphChatMessages(componentId, state);
116
+ if (((_a = messages[messageIndex]) == null ? void 0 : _a.role) !== "assistant") {
117
+ return void 0;
118
+ }
119
+ const pinsStateKey = getUiGraphChatPinsStateKey(componentId);
120
+ const pinnedIndexes = getUiGraphChatPins(componentId, state).map((pin) => pin.messageIndex);
121
+ return {
122
+ [pinsStateKey]: pinnedIndexes.includes(messageIndex) ? pinnedIndexes.filter((index) => index !== messageIndex) : [...pinnedIndexes, messageIndex].sort((left, right) => left - right)
123
+ };
124
+ }
125
+ function createUiGraphChatHistoryFlushStatePatch(componentId) {
126
+ return {
127
+ [getUiGraphChatMessagesStateKey(componentId)]: [],
128
+ [getUiGraphChatPinsStateKey(componentId)]: []
129
+ };
130
+ }
131
+ function createUiGraphChatSubmissionStatePatch(componentId, state) {
132
+ const draftStateKey = getUiGraphChatDraftStateKey(componentId);
133
+ const content = `${state[draftStateKey] ?? ""}`.trim();
134
+ if (!content) {
135
+ return void 0;
136
+ }
137
+ return {
138
+ [draftStateKey]: "",
139
+ [getUiGraphChatMessagesStateKey(componentId)]: [
140
+ ...getUiGraphChatMessages(componentId, state),
141
+ { role: "user", content }
142
+ ]
143
+ };
144
+ }
145
+ function getUiGraphComponentActionState(component, state) {
146
+ if (component.type === "button") {
147
+ return getUiGraphActionState(component.action, state);
148
+ }
149
+ const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);
150
+ return {
151
+ ...getUiGraphActionState(component.action, state),
152
+ [messagesStateKey]: getUiGraphChatMessages(component.id, state)
153
+ };
154
+ }
155
+ function getUiGraphComponentActionOutputStateKeys(component) {
156
+ return component.type === "button" ? getUiGraphActionOutputBindings(component.action).map((binding) => binding.stateKey.trim()).filter(Boolean) : [getUiGraphChatMessagesStateKey(component.id)];
157
+ }
158
+ function getUiGraphActionState(action, state) {
159
+ return Object.fromEntries(
160
+ [...new Set(getUiGraphActionInputBindings(action).map((binding) => binding.stateKey))].filter(Boolean).filter((stateKey) => Object.prototype.hasOwnProperty.call(state, stateKey)).map((stateKey) => [stateKey, state[stateKey]])
161
+ );
162
+ }
163
+ function getUiGraphActionOutputBindings(action) {
164
+ if (action.outputs) {
165
+ return action.outputs;
166
+ }
167
+ return action.outputStateKey ? [{ outputKey: action.outputKey, stateKey: action.outputStateKey }] : [];
168
+ }
169
+ function getUiGraphActionInputBindings(action) {
170
+ if (action.inputMappings) {
171
+ return action.inputMappings;
172
+ }
173
+ return Object.entries(action.inputs ?? {}).map(([inputKey, binding]) => ({
174
+ inputKey,
175
+ stateKey: binding.type === "state" ? binding.key : ""
176
+ }));
177
+ }
178
+ function isUiGraphChatMessage(value) {
179
+ return value != null && typeof value === "object" && (value.role === "user" || value.role === "assistant") && typeof value.content === "string";
180
+ }
181
+
182
+ // src/model/GraphProgress.ts
183
+ var MAX_PROGRESS_MESSAGE_LENGTH = 500;
184
+ function normalizeGraphProgress(progress) {
185
+ const message = typeof progress.message === "string" ? progress.message.trim().slice(0, MAX_PROGRESS_MESSAGE_LENGTH) : "";
186
+ const percent = typeof progress.percent === "number" && Number.isFinite(progress.percent) ? Math.min(100, Math.max(0, progress.percent)) : void 0;
187
+ if (!message && percent == null) {
188
+ return void 0;
189
+ }
190
+ return {
191
+ ...message ? { message } : {},
192
+ ...percent == null ? {} : { percent }
193
+ };
194
+ }
195
+
196
+ // src/model/UiGraphRuntimeModel.ts
197
+ var IMAGE_DATA_URL_PATTERN = /^data:(image\/(?:avif|bmp|gif|jpe?g|png|webp));base64,([\s\S]+)$/i;
198
+ var IMAGE_URL_PATTERN = /^(?:https?:\/\/|blob:|\/\/|\/|\.\.?\/)/i;
199
+ var RELATIVE_IMAGE_PATH_PATTERN = /\.(?:avif|bmp|gif|jpe?g|png|webp)(?:[?#].*)?$/i;
200
+ var BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
201
+ var UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_THRESHOLD = 128 * 1024;
202
+ var UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_INITIAL_CHARS = 16 * 1024;
203
+ var UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_CHUNK_CHARS = 16 * 1024;
204
+ var ACTION_LOADING_DELAY_MS = 300;
205
+ function getUiGraphActionComponentsById(uiGraph) {
206
+ return new Map(
207
+ uiGraph.components.filter(
208
+ (component) => component.type === "button" || component.type === "chat"
209
+ ).map((component) => [component.id, component])
210
+ );
211
+ }
212
+ function areUiGraphActionValuesEqual(left, right) {
213
+ if (Object.is(left, right)) {
214
+ return true;
215
+ }
216
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") {
217
+ return false;
218
+ }
219
+ if (Array.isArray(left) || Array.isArray(right)) {
220
+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => areUiGraphActionValuesEqual(value, right[index]));
221
+ }
222
+ const leftRecord = left;
223
+ const rightRecord = right;
224
+ const leftKeys = Object.keys(leftRecord);
225
+ const rightKeys = Object.keys(rightRecord);
226
+ return leftKeys.length === rightKeys.length && leftKeys.every(
227
+ (key) => Object.prototype.hasOwnProperty.call(rightRecord, key) && areUiGraphActionValuesEqual(leftRecord[key], rightRecord[key])
228
+ );
229
+ }
230
+ function areUiGraphActionComponentsExecutionEquivalent(left, right) {
231
+ return left.type === right.type && areUiGraphActionValuesEqual(left.action, right.action);
232
+ }
233
+ function createUiGraphActionExecutionController() {
234
+ let nextVersion = 0;
235
+ const activeExecutionByComponent = /* @__PURE__ */ new Map();
236
+ const latestWriterByStateKey = /* @__PURE__ */ new Map();
237
+ return {
238
+ begin(component) {
239
+ if (activeExecutionByComponent.has(component.id)) {
240
+ return void 0;
241
+ }
242
+ const execution = { componentId: component.id, id: ++nextVersion };
243
+ activeExecutionByComponent.set(component.id, execution.id);
244
+ for (const stateKey of getUiGraphComponentActionOutputStateKeys(component)) {
245
+ latestWriterByStateKey.set(stateKey, execution.id);
246
+ }
247
+ return execution;
248
+ },
249
+ finish(execution) {
250
+ if (activeExecutionByComponent.get(execution.componentId) !== execution.id) {
251
+ return false;
252
+ }
253
+ activeExecutionByComponent.delete(execution.componentId);
254
+ return true;
255
+ },
256
+ isCurrent(execution) {
257
+ return activeExecutionByComponent.get(execution.componentId) === execution.id;
258
+ },
259
+ isRunning(componentId) {
260
+ return activeExecutionByComponent.has(componentId);
261
+ },
262
+ noteStateWrite(stateKey) {
263
+ const normalizedStateKey = stateKey.trim();
264
+ if (normalizedStateKey) {
265
+ latestWriterByStateKey.set(normalizedStateKey, ++nextVersion);
266
+ }
267
+ },
268
+ resolveStatePatch(execution, statePatch) {
269
+ if (!statePatch) {
270
+ return void 0;
271
+ }
272
+ const applicableEntries = Object.entries(statePatch).filter(
273
+ ([stateKey]) => latestWriterByStateKey.get(stateKey) === execution.id
274
+ );
275
+ return applicableEntries.length > 0 ? Object.fromEntries(applicableEntries) : void 0;
276
+ },
277
+ reset() {
278
+ activeExecutionByComponent.clear();
279
+ latestWriterByStateKey.clear();
280
+ }
281
+ };
282
+ }
283
+ function createUiGraphInteractionController(initialUiGraph, options = {}) {
284
+ let uiGraphId = initialUiGraph.id;
285
+ let actionComponentsById = getUiGraphActionComponentsById(initialUiGraph);
286
+ let outputComponentIds = getUiGraphOutputComponentIds(initialUiGraph);
287
+ let outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(initialUiGraph);
288
+ const initialStateOverride = options.initialState ? { ...options.initialState } : void 0;
289
+ let initialState = normalizeUiGraphDropdownState(
290
+ initialUiGraph,
291
+ initialStateOverride ?? getUiGraphInitialState(initialUiGraph)
292
+ );
293
+ let state = { ...initialState };
294
+ let actionErrors = {};
295
+ let actionProgress = {};
296
+ const collapsedOutputComponentIds = /* @__PURE__ */ new Set();
297
+ let snapshot;
298
+ const actionController = createUiGraphActionExecutionController();
299
+ const activeActions = /* @__PURE__ */ new Map();
300
+ const loadingActionIds = /* @__PURE__ */ new Set();
301
+ const loadingDelayTimers = /* @__PURE__ */ new Map();
302
+ const listeners = /* @__PURE__ */ new Set();
303
+ const updateSnapshot = () => {
304
+ snapshot = {
305
+ actionErrors,
306
+ actionProgress,
307
+ collapsedOutputComponentIds: new Set(collapsedOutputComponentIds),
308
+ loadingComponentIds: new Set(
309
+ [...activeActions].flatMap(
310
+ ([executionId, { execution }]) => loadingActionIds.has(executionId) ? [execution.componentId] : []
311
+ )
312
+ ),
313
+ runningComponentIds: new Set([...activeActions.values()].map(({ execution }) => execution.componentId)),
314
+ state
315
+ };
316
+ };
317
+ const publish = (change) => {
318
+ updateSnapshot();
319
+ for (const listener of listeners) {
320
+ listener(change);
321
+ }
322
+ };
323
+ const clearActionLoadingPresentation = (executionId) => {
324
+ const timer = loadingDelayTimers.get(executionId);
325
+ if (timer != null) {
326
+ clearTimeout(timer);
327
+ loadingDelayTimers.delete(executionId);
328
+ }
329
+ loadingActionIds.delete(executionId);
330
+ };
331
+ const delayActionLoadingPresentation = (execution) => {
332
+ loadingDelayTimers.set(
333
+ execution.id,
334
+ setTimeout(() => {
335
+ loadingDelayTimers.delete(execution.id);
336
+ if (!activeActions.has(execution.id) || !actionController.isCurrent(execution)) return;
337
+ loadingActionIds.add(execution.id);
338
+ publish("action");
339
+ }, ACTION_LOADING_DELAY_MS)
340
+ );
341
+ };
342
+ const abortMatchingActions = (predicate, notify) => {
343
+ let changed = false;
344
+ for (const [executionId, activeAction] of activeActions) {
345
+ if (!predicate(activeAction, executionId)) {
346
+ continue;
347
+ }
348
+ activeAction.abortController.abort();
349
+ activeActions.delete(executionId);
350
+ clearActionLoadingPresentation(executionId);
351
+ actionController.finish(activeAction.execution);
352
+ changed = true;
353
+ }
354
+ if (changed && notify) {
355
+ publish("action");
356
+ }
357
+ return changed;
358
+ };
359
+ const abortAllActions = (notify) => {
360
+ let changed = abortMatchingActions(() => true, false);
361
+ actionController.reset();
362
+ if (Object.keys(actionProgress).length > 0) {
363
+ actionProgress = {};
364
+ changed = true;
365
+ }
366
+ if (changed && notify) {
367
+ publish("action");
368
+ }
369
+ };
370
+ const removeActionPresentation = (componentId) => {
371
+ let changed = false;
372
+ if (Object.prototype.hasOwnProperty.call(actionErrors, componentId)) {
373
+ actionErrors = { ...actionErrors };
374
+ delete actionErrors[componentId];
375
+ changed = true;
376
+ }
377
+ if (Object.prototype.hasOwnProperty.call(actionProgress, componentId)) {
378
+ actionProgress = { ...actionProgress };
379
+ delete actionProgress[componentId];
380
+ changed = true;
381
+ }
382
+ return changed;
383
+ };
384
+ const expandOutputsForUpdatedState = (stateKeys, nextState) => {
385
+ for (const stateKey of stateKeys) {
386
+ for (const component of outputComponentsByStateKey.get(stateKey) ?? []) {
387
+ if (getUiGraphOutputRenderModel(nextState, stateKey, component.renderAs ?? "text").hasValue) {
388
+ collapsedOutputComponentIds.delete(component.id);
389
+ }
390
+ }
391
+ }
392
+ };
393
+ updateSnapshot();
394
+ return {
395
+ abortActions() {
396
+ abortAllActions(true);
397
+ },
398
+ cancelAction(componentId) {
399
+ if (abortMatchingActions(({ execution }) => execution.componentId === componentId, false)) {
400
+ removeActionPresentation(componentId);
401
+ publish("action");
402
+ }
403
+ },
404
+ detachActions() {
405
+ for (const executionId of activeActions.keys()) {
406
+ clearActionLoadingPresentation(executionId);
407
+ }
408
+ activeActions.clear();
409
+ actionController.reset();
410
+ actionProgress = {};
411
+ updateSnapshot();
412
+ },
413
+ getSnapshot() {
414
+ return snapshot;
415
+ },
416
+ reset() {
417
+ abortAllActions(false);
418
+ state = { ...initialState };
419
+ actionErrors = {};
420
+ actionProgress = {};
421
+ collapsedOutputComponentIds.clear();
422
+ publish("state");
423
+ },
424
+ async runAction(component, runner) {
425
+ const execution = actionController.begin(component);
426
+ if (!execution) {
427
+ return;
428
+ }
429
+ const abortController = new AbortController();
430
+ activeActions.set(execution.id, { abortController, execution });
431
+ delayActionLoadingPresentation(execution);
432
+ removeActionPresentation(component.id);
433
+ publish("action");
434
+ try {
435
+ const result = await runner({
436
+ abortOtherActions: () => abortMatchingActions((_activeAction, executionId) => executionId !== execution.id, true),
437
+ componentId: component.id,
438
+ reportProgress: (progress) => {
439
+ if (!actionController.isCurrent(execution)) return;
440
+ const normalized = normalizeGraphProgress(progress);
441
+ if (!normalized) return;
442
+ actionProgress = { ...actionProgress, [component.id]: normalized };
443
+ publish("action");
444
+ },
445
+ signal: abortController.signal,
446
+ state: getUiGraphComponentActionState(component, state)
447
+ });
448
+ if (!actionController.isCurrent(execution)) {
449
+ return;
450
+ }
451
+ const statePatch = actionController.resolveStatePatch(execution, result.statePatch);
452
+ if (statePatch) {
453
+ const nextState = applyUiGraphStatePatch(state, statePatch);
454
+ expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
455
+ state = nextState;
456
+ }
457
+ } catch (error) {
458
+ if (!abortController.signal.aborted && actionController.isCurrent(execution)) {
459
+ actionErrors = {
460
+ ...actionErrors,
461
+ [component.id]: error instanceof Error ? error.message : String(error)
462
+ };
463
+ }
464
+ } finally {
465
+ if (activeActions.delete(execution.id)) {
466
+ clearActionLoadingPresentation(execution.id);
467
+ actionController.finish(execution);
468
+ if (Object.prototype.hasOwnProperty.call(actionProgress, component.id)) {
469
+ actionProgress = { ...actionProgress };
470
+ delete actionProgress[component.id];
471
+ }
472
+ publish("action");
473
+ }
474
+ }
475
+ },
476
+ setUiGraph(nextUiGraph) {
477
+ if (nextUiGraph.id !== uiGraphId) {
478
+ abortAllActions(false);
479
+ uiGraphId = nextUiGraph.id;
480
+ initialState = initialStateOverride ?? getUiGraphInitialState(nextUiGraph);
481
+ state = { ...initialState };
482
+ actionErrors = {};
483
+ actionProgress = {};
484
+ outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);
485
+ outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);
486
+ actionComponentsById = getUiGraphActionComponentsById(nextUiGraph);
487
+ collapsedOutputComponentIds.clear();
488
+ publish("graph");
489
+ return;
490
+ }
491
+ if (!initialStateOverride) {
492
+ initialState = getUiGraphInitialState(nextUiGraph);
493
+ }
494
+ const normalizedState = normalizeUiGraphDropdownState(nextUiGraph, state);
495
+ const stateChanged = normalizedState !== state;
496
+ if (stateChanged) {
497
+ state = normalizedState;
498
+ }
499
+ outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);
500
+ outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);
501
+ const collapsedOutputIdsBeforeCleanup = collapsedOutputComponentIds.size;
502
+ for (const componentId of collapsedOutputComponentIds) {
503
+ if (!outputComponentIds.has(componentId)) {
504
+ collapsedOutputComponentIds.delete(componentId);
505
+ }
506
+ }
507
+ const nextActionComponentsById = getUiGraphActionComponentsById(nextUiGraph);
508
+ const actionComponentIds = new Set(nextActionComponentsById.keys());
509
+ const changedActionComponentIds = new Set(
510
+ [...nextActionComponentsById].flatMap(([componentId, component]) => {
511
+ const previousComponent = actionComponentsById.get(componentId);
512
+ return previousComponent && !areUiGraphActionComponentsExecutionEquivalent(previousComponent, component) ? [componentId] : [];
513
+ })
514
+ );
515
+ let changed = collapsedOutputComponentIds.size !== collapsedOutputIdsBeforeCleanup || stateChanged || abortMatchingActions(
516
+ ({ execution }) => !actionComponentIds.has(execution.componentId) || changedActionComponentIds.has(execution.componentId),
517
+ false
518
+ );
519
+ for (const componentId of changedActionComponentIds) {
520
+ changed = removeActionPresentation(componentId) || changed;
521
+ }
522
+ actionComponentsById = nextActionComponentsById;
523
+ const remainingErrors = Object.fromEntries(
524
+ Object.entries(actionErrors).filter(([componentId]) => actionComponentIds.has(componentId))
525
+ );
526
+ const remainingProgress = Object.fromEntries(
527
+ Object.entries(actionProgress).filter(([componentId]) => actionComponentIds.has(componentId))
528
+ );
529
+ if (Object.keys(remainingErrors).length !== Object.keys(actionErrors).length) {
530
+ actionErrors = remainingErrors;
531
+ changed = true;
532
+ }
533
+ if (Object.keys(remainingProgress).length !== Object.keys(actionProgress).length) {
534
+ actionProgress = remainingProgress;
535
+ changed = true;
536
+ }
537
+ if (changed) {
538
+ publish("graph");
539
+ }
540
+ },
541
+ subscribe(listener) {
542
+ listeners.add(listener);
543
+ return () => listeners.delete(listener);
544
+ },
545
+ toggleOutputCollapsed(componentId) {
546
+ if (!outputComponentIds.has(componentId)) {
547
+ return;
548
+ }
549
+ if (collapsedOutputComponentIds.has(componentId)) {
550
+ collapsedOutputComponentIds.delete(componentId);
551
+ } else {
552
+ collapsedOutputComponentIds.add(componentId);
553
+ }
554
+ publish("presentation");
555
+ },
556
+ updateState(stateKey, value) {
557
+ actionController.noteStateWrite(stateKey);
558
+ const nextState = { ...state, [stateKey]: value };
559
+ expandOutputsForUpdatedState([stateKey], nextState);
560
+ state = nextState;
561
+ publish("state");
562
+ },
563
+ updateStatePatch(statePatch) {
564
+ for (const stateKey of Object.keys(statePatch)) {
565
+ actionController.noteStateWrite(stateKey);
566
+ }
567
+ const nextState = applyUiGraphStatePatch(state, statePatch);
568
+ expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
569
+ state = nextState;
570
+ publish("state");
571
+ }
572
+ };
573
+ }
574
+ function getUiGraphOutputComponentIds(uiGraph) {
575
+ return new Set(
576
+ uiGraph.components.filter((component) => component.type === "output").map((component) => component.id)
577
+ );
578
+ }
579
+ function getUiGraphOutputComponentsByStateKey(uiGraph) {
580
+ const componentsByStateKey = /* @__PURE__ */ new Map();
581
+ for (const component of uiGraph.components) {
582
+ if (component.type !== "output") continue;
583
+ const components = componentsByStateKey.get(component.stateKey) ?? [];
584
+ components.push(component);
585
+ componentsByStateKey.set(component.stateKey, components);
586
+ }
587
+ return componentsByStateKey;
588
+ }
589
+ function normalizeUiGraphDropdownState(uiGraph, state) {
590
+ let normalizedState;
591
+ for (const component of uiGraph.components) {
592
+ if (component.type !== "dropdown") {
593
+ continue;
594
+ }
595
+ const selectedValue = `${state[component.stateKey] ?? ""}`;
596
+ if (selectedValue === "" || component.items.some((item) => item.value === selectedValue)) {
597
+ continue;
598
+ }
599
+ normalizedState ??= { ...state };
600
+ normalizedState[component.stateKey] = "";
601
+ }
602
+ return normalizedState ?? state;
603
+ }
604
+ function getUiGraphComponentRenderModel(component, state) {
605
+ switch (component.type) {
606
+ case "text":
607
+ return { component, text: component.text, type: "text" };
608
+ case "markdown":
609
+ return { component, markdown: component.markdown, type: "markdown" };
610
+ case "gap":
611
+ return { component, size: component.size, type: "gap" };
612
+ case "input":
613
+ case "textarea":
614
+ return {
615
+ component,
616
+ label: getUiGraphComponentLabel(component),
617
+ type: component.type,
618
+ value: `${state[component.stateKey] ?? component.defaultValue ?? ""}`
619
+ };
620
+ case "dropdown": {
621
+ const selectedValue = `${state[component.stateKey] ?? ""}`;
622
+ return {
623
+ component,
624
+ items: component.items,
625
+ label: getUiGraphComponentLabel(component),
626
+ type: "dropdown",
627
+ value: component.items.some((item) => item.value === selectedValue) ? selectedValue : ""
628
+ };
629
+ }
630
+ case "button":
631
+ return { component, label: component.label, type: "button" };
632
+ case "chat":
633
+ return {
634
+ component,
635
+ draft: `${state[getUiGraphChatDraftStateKey(component.id)] ?? ""}`,
636
+ messages: getUiGraphChatMessages(component.id, state),
637
+ pins: getUiGraphChatPins(component.id, state),
638
+ type: "chat"
639
+ };
640
+ case "output":
641
+ return {
642
+ component,
643
+ label: getUiGraphComponentLabel(component),
644
+ output: getUiGraphOutputRenderModel(state, component.stateKey, component.renderAs ?? "text"),
645
+ type: "output"
646
+ };
647
+ }
648
+ }
649
+ function getUiGraphComponentLabel(component) {
650
+ return component.label || component.stateKey;
651
+ }
652
+ function getUiGraphOutputRenderModel(state, stateKey, renderAs) {
653
+ const value = state[stateKey];
654
+ const renderedValue = renderUiGraphOutputValue(value, renderAs);
655
+ const hasStateValue = hasUiGraphStateValue(state, stateKey);
656
+ const hasImageValue = hasStateValue && value != null && value !== "";
657
+ const imageSource = hasImageValue && renderAs === "image" ? getUiGraphImageSource(value) : void 0;
658
+ const imageErrorMessage = hasImageValue && renderAs === "image" && !imageSource ? "Expected an image URL or base64 image." : void 0;
659
+ const hasValue = renderAs === "image" ? imageSource != null || imageErrorMessage != null : renderedValue.trim().length > 0;
660
+ return {
661
+ hasValue,
662
+ ...imageErrorMessage ? { imageErrorMessage } : {},
663
+ ...imageSource ? { imageSource } : {},
664
+ ...hasValue && renderAs === "json" ? { jsonDownloadValue: renderedValue } : {},
665
+ renderedValue,
666
+ renderAs
667
+ };
668
+ }
669
+ function hasUiGraphStateValue(state, key) {
670
+ return Object.prototype.hasOwnProperty.call(state, key) && state[key] !== void 0;
671
+ }
672
+ function renderUiGraphOutputValue(value, renderAs) {
673
+ if (renderAs === "json") {
674
+ return stringifyUiGraphValue(value) ?? "";
675
+ }
676
+ return typeof value === "string" ? value : value == null ? "" : stringifyUiGraphValue(value) ?? "";
677
+ }
678
+ function getUiGraphProgressiveJsonOutputChunks(value) {
679
+ if (value.length < UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_THRESHOLD) {
680
+ return void 0;
681
+ }
682
+ const chunks = [];
683
+ let offset = 0;
684
+ let chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_INITIAL_CHARS;
685
+ while (offset < value.length) {
686
+ let nextOffset = Math.min(value.length, offset + chunkLength);
687
+ if (nextOffset < value.length && isHighSurrogate(value.charCodeAt(nextOffset - 1)) && isLowSurrogate(value.charCodeAt(nextOffset))) {
688
+ nextOffset += 1;
689
+ }
690
+ chunks.push(value.slice(offset, nextOffset));
691
+ offset = nextOffset;
692
+ chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_CHUNK_CHARS;
693
+ }
694
+ return chunks;
695
+ }
696
+ function isHighSurrogate(value) {
697
+ return value >= 55296 && value <= 56319;
698
+ }
699
+ function isLowSurrogate(value) {
700
+ return value >= 56320 && value <= 57343;
701
+ }
702
+ function getUiGraphImageSource(value) {
703
+ if (typeof value !== "string") {
704
+ return void 0;
705
+ }
706
+ const source = value.trim();
707
+ if (!source) {
708
+ return void 0;
709
+ }
710
+ const dataUrl = IMAGE_DATA_URL_PATTERN.exec(source);
711
+ if (dataUrl) {
712
+ const base642 = normalizeBase64(dataUrl[2]);
713
+ return base642 ? `data:${normalizeImageMediaType(dataUrl[1])};base64,${base642}` : void 0;
714
+ }
715
+ const base64 = normalizeBase64(source);
716
+ const inferredMediaType = base64 ? inferBase64ImageMediaType(base64) : void 0;
717
+ if (base64 && inferredMediaType) {
718
+ return `data:${inferredMediaType};base64,${base64}`;
719
+ }
720
+ if (!IMAGE_URL_PATTERN.test(source) && !RELATIVE_IMAGE_PATH_PATTERN.test(source)) {
721
+ return void 0;
722
+ }
723
+ try {
724
+ const protocol = new URL(source, "https://rivet.invalid").protocol;
725
+ return protocol === "http:" || protocol === "https:" || protocol === "blob:" ? source : void 0;
726
+ } catch {
727
+ return void 0;
728
+ }
729
+ }
730
+ function normalizeBase64(value) {
731
+ const compact = value.replace(/\s/g, "");
732
+ return compact.length >= 8 && compact.length % 4 !== 1 && BASE64_PATTERN.test(compact) ? compact : void 0;
733
+ }
734
+ function normalizeImageMediaType(mediaType) {
735
+ const normalized = mediaType.toLowerCase();
736
+ return normalized === "image/jpg" ? "image/jpeg" : normalized;
737
+ }
738
+ function inferBase64ImageMediaType(value) {
739
+ if (value.startsWith("iVBORw0KGgo")) return "image/png";
740
+ if (value.startsWith("/9j/")) return "image/jpeg";
741
+ if (value.startsWith("R0lGODdh") || value.startsWith("R0lGODlh")) return "image/gif";
742
+ return void 0;
743
+ }
744
+ function stringifyUiGraphValue(value) {
745
+ try {
746
+ return JSON.stringify(value, null, 2);
747
+ } catch {
748
+ return "[Unserializable value]";
749
+ }
750
+ }
751
+ function getUiGraphJsonOutputFilename(appName, date = /* @__PURE__ */ new Date()) {
752
+ const safeName = appName.trim().replace(/[<>:"/\\|?*\u0000-\u001F]/g, "-").replace(/\s+/g, " ").slice(0, 80);
753
+ return `${safeName || "Rivet web app"} ${formatUiGraphDownloadDateTime(date)}.json`;
754
+ }
755
+ function formatUiGraphDownloadDateTime(date) {
756
+ const pad = (value) => `${value}`.padStart(2, "0");
757
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}-${pad(
758
+ date.getMinutes()
759
+ )}-${pad(date.getSeconds())}`;
760
+ }
761
+ function applyUiGraphStatePatch(state, statePatch) {
762
+ return statePatch ? { ...state, ...statePatch } : state;
763
+ }
764
+
765
+ // src/model/UiGraphActionProtocol.ts
766
+ var RIVET_WEB_APP_ACTION_PROTOCOL_VERSION = 1;
767
+ function parseRivetWebAppClientMessage(value) {
768
+ if (!isRecord(value) || typeof value.type !== "string") return void 0;
769
+ switch (value.type) {
770
+ case "client.hello":
771
+ return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION ? { type: value.type, protocolVersion: value.protocolVersion } : void 0;
772
+ case "action.start":
773
+ return isNonEmptyString(value.requestId) && isNonEmptyString(value.componentId) && isRecord(value.state) && (value.storage == null || isRecord(value.storage)) && (value.revisionKey == null || typeof value.revisionKey === "string") ? {
774
+ type: value.type,
775
+ requestId: value.requestId,
776
+ componentId: value.componentId,
777
+ state: value.state,
778
+ ...isRecord(value.storage) ? { storage: value.storage } : {},
779
+ ...typeof value.revisionKey === "string" ? { revisionKey: value.revisionKey } : {}
780
+ } : void 0;
781
+ case "action.cancel":
782
+ return isNonEmptyString(value.runId) ? { type: value.type, runId: value.runId } : void 0;
783
+ case "run.resume":
784
+ return isNonEmptyString(value.runId) && typeof value.lastSequence === "number" && Number.isSafeInteger(value.lastSequence) && value.lastSequence >= 0 ? { type: value.type, runId: value.runId, lastSequence: value.lastSequence } : void 0;
785
+ default:
786
+ return void 0;
787
+ }
788
+ }
789
+ function parseRivetWebAppServerMessage(value) {
790
+ if (!isRecord(value) || typeof value.type !== "string") return void 0;
791
+ if (value.type === "server.ready") {
792
+ return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION ? { type: value.type, protocolVersion: value.protocolVersion } : void 0;
793
+ }
794
+ if (value.type === "server.draining") return { type: value.type };
795
+ if (value.type === "action.rejected") {
796
+ return isNonEmptyString(value.requestId) && isNonEmptyString(value.error) ? {
797
+ type: value.type,
798
+ requestId: value.requestId,
799
+ error: value.error,
800
+ ...typeof value.code === "string" ? { code: value.code } : {}
801
+ } : void 0;
802
+ }
803
+ if (value.type === "run.rejected") {
804
+ return isNonEmptyString(value.runId) && isNonEmptyString(value.error) ? {
805
+ type: value.type,
806
+ runId: value.runId,
807
+ error: value.error,
808
+ ...typeof value.code === "string" ? { code: value.code } : {}
809
+ } : void 0;
810
+ }
811
+ if (!hasRunEventBase(value)) return void 0;
812
+ const base = {
813
+ requestId: value.requestId,
814
+ runId: value.runId,
815
+ sequence: value.sequence
816
+ };
817
+ switch (value.type) {
818
+ case "action.accepted":
819
+ case "action.cancelled":
820
+ return { type: value.type, ...base };
821
+ case "action.progress": {
822
+ if (!isRecord(value.progress)) return void 0;
823
+ const progress = normalizeGraphProgress({
824
+ message: typeof value.progress.message === "string" ? value.progress.message : void 0,
825
+ percent: typeof value.progress.percent === "number" ? value.progress.percent : void 0
826
+ });
827
+ return progress ? { type: value.type, ...base, progress } : void 0;
828
+ }
829
+ case "action.completed":
830
+ return isRecord(value.statePatch) && (value.storagePatch == null || isRecord(value.storagePatch)) ? {
831
+ type: value.type,
832
+ ...base,
833
+ statePatch: value.statePatch,
834
+ ...isRecord(value.storagePatch) ? { storagePatch: value.storagePatch } : {}
835
+ } : void 0;
836
+ case "action.failed":
837
+ return isNonEmptyString(value.error) ? {
838
+ type: value.type,
839
+ ...base,
840
+ error: value.error,
841
+ ...typeof value.code === "string" ? { code: value.code } : {}
842
+ } : void 0;
843
+ case "action.interrupted":
844
+ return isNonEmptyString(value.error) ? { type: value.type, ...base, error: value.error } : void 0;
845
+ default:
846
+ return void 0;
847
+ }
848
+ }
849
+ function hasRunEventBase(value) {
850
+ return isNonEmptyString(value.requestId) && isNonEmptyString(value.runId) && typeof value.sequence === "number" && Number.isSafeInteger(value.sequence) && value.sequence > 0;
851
+ }
852
+ function isRecord(value) {
853
+ return typeof value === "object" && value != null && !Array.isArray(value);
854
+ }
855
+ function isNonEmptyString(value) {
856
+ return typeof value === "string" && value.length > 0;
857
+ }
858
+
859
+ // src/model/UiGraphBrowserRuntime.ts
860
+ var OUTPUT_MAX_HEIGHT_PX = 800;
861
+ var OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO = 0.8;
862
+ var OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY = "--rivet-web-app-output-resize-min-height";
863
+ var OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY = "--rivet-web-app-output-resize-max-height";
864
+ var CHAT_SEARCH_MATCH_CLASS = "rivet-web-app-chat-search-match";
865
+ var CHAT_SEARCH_ACTIVE_MATCH_CLASS = "rivet-web-app-chat-search-match-active";
866
+ var UI_GRAPH_CHAT_STORAGE_PREFIX = "rivet-web-app-chat-state:v1";
867
+ var UI_GRAPH_APP_STORAGE_PREFIX = "rivet-web-app-storage:v1";
868
+ var escapeRegularExpression = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
869
+ var getPixelValue = (value, fallback) => {
870
+ const parsed = Number.parseFloat(value);
871
+ return Number.isFinite(parsed) ? parsed : fallback;
872
+ };
873
+ var setStyleProperty = (element, property, value) => {
874
+ if (element.style.getPropertyValue(property) !== value) {
875
+ element.style.setProperty(property, value);
876
+ }
877
+ };
878
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
879
+ var getDefaultUiGraphBrowserStorage = () => {
880
+ var _a;
881
+ try {
882
+ return globalThis.localStorage ?? ((_a = globalThis.window) == null ? void 0 : _a.localStorage);
883
+ } catch {
884
+ return void 0;
885
+ }
886
+ };
887
+ var getDefaultUiGraphStorageLocation = () => {
888
+ var _a;
889
+ try {
890
+ return globalThis.location ?? ((_a = globalThis.window) == null ? void 0 : _a.location);
891
+ } catch {
892
+ return void 0;
893
+ }
894
+ };
895
+ function getUiGraphChatStorageKey(uiGraph, location = getDefaultUiGraphStorageLocation()) {
896
+ if (!(location == null ? void 0 : location.origin)) {
897
+ return void 0;
898
+ }
899
+ const pathname = location.pathname.replace(/\/+$/, "") || "/";
900
+ return [
901
+ UI_GRAPH_CHAT_STORAGE_PREFIX,
902
+ encodeURIComponent(location.origin),
903
+ encodeURIComponent(pathname),
904
+ encodeURIComponent(uiGraph.id)
905
+ ].join(":");
906
+ }
907
+ function getUiGraphWebAppStorageKey(uiGraph, location = getDefaultUiGraphStorageLocation()) {
908
+ if (!(location == null ? void 0 : location.origin)) {
909
+ return void 0;
910
+ }
911
+ const pathname = location.pathname.replace(/\/+$/, "") || "/";
912
+ return [
913
+ UI_GRAPH_APP_STORAGE_PREFIX,
914
+ encodeURIComponent(location.origin),
915
+ encodeURIComponent(pathname),
916
+ encodeURIComponent(uiGraph.id)
917
+ ].join(":");
918
+ }
919
+ function loadUiGraphWebAppStorage(uiGraph, storage = getDefaultUiGraphBrowserStorage(), location) {
920
+ const key = getUiGraphWebAppStorageKey(uiGraph, location);
921
+ if (!key || !storage) return {};
922
+ try {
923
+ const serialized = storage.getItem(key);
924
+ if (!serialized) return {};
925
+ const value = JSON.parse(serialized);
926
+ return isRecord2(value) ? value : {};
927
+ } catch {
928
+ return {};
929
+ }
930
+ }
931
+ function applyUiGraphWebAppStoragePatch(uiGraph, currentStorage, patch, storage = getDefaultUiGraphBrowserStorage(), location) {
932
+ const key = getUiGraphWebAppStorageKey(uiGraph, location);
933
+ if (!key || !storage) {
934
+ throw new Error("Browser storage is unavailable for this web app.");
935
+ }
936
+ const nextStorage = { ...currentStorage, ...patch };
937
+ let serialized;
938
+ try {
939
+ serialized = JSON.stringify(nextStorage);
940
+ storage.setItem(key, serialized);
941
+ } catch (error) {
942
+ throw new Error("Web app storage could not be saved. Browser storage may be unavailable or full.", {
943
+ cause: error
944
+ });
945
+ }
946
+ return nextStorage;
947
+ }
948
+ function applyUiGraphWebAppStorageActionPatch(patch, actionNumber, appliedActionByKey, persist) {
949
+ const applicablePatch = Object.fromEntries(
950
+ Object.entries(patch).filter(([key]) => actionNumber >= (appliedActionByKey.get(key) ?? 0))
951
+ );
952
+ const applicableKeys = Object.keys(applicablePatch);
953
+ if (applicableKeys.length === 0) return applicablePatch;
954
+ persist(applicablePatch);
955
+ for (const key of applicableKeys) appliedActionByKey.set(key, actionNumber);
956
+ return applicablePatch;
957
+ }
958
+ function getUiGraphChatPersistentState(uiGraph, state) {
959
+ const persistentState = {};
960
+ for (const component of uiGraph.components) {
961
+ if (component.type !== "chat") continue;
962
+ const draftStateKey = getUiGraphChatDraftStateKey(component.id);
963
+ const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);
964
+ const pinsStateKey = getUiGraphChatPinsStateKey(component.id);
965
+ const draft = state[draftStateKey];
966
+ const messages = getUiGraphChatMessages(component.id, state);
967
+ const pins = getUiGraphChatPins(component.id, state).map((pin) => pin.messageIndex);
968
+ if (typeof draft === "string" && draft) {
969
+ persistentState[draftStateKey] = draft;
970
+ }
971
+ if (messages.length > 0) {
972
+ persistentState[messagesStateKey] = messages;
973
+ }
974
+ if (pins.length > 0) {
975
+ persistentState[pinsStateKey] = pins;
976
+ }
977
+ }
978
+ return persistentState;
979
+ }
980
+ function hasUiGraphChatPersistentStateChanged(uiGraph, previousState, nextState) {
981
+ return uiGraph.components.some((component) => {
982
+ if (component.type !== "chat") return false;
983
+ return previousState[getUiGraphChatDraftStateKey(component.id)] !== nextState[getUiGraphChatDraftStateKey(component.id)] || previousState[getUiGraphChatMessagesStateKey(component.id)] !== nextState[getUiGraphChatMessagesStateKey(component.id)] || previousState[getUiGraphChatPinsStateKey(component.id)] !== nextState[getUiGraphChatPinsStateKey(component.id)];
984
+ });
985
+ }
986
+ function loadUiGraphChatPersistentState(uiGraph, storage = getDefaultUiGraphBrowserStorage(), location) {
987
+ const key = getUiGraphChatStorageKey(uiGraph, location);
988
+ if (!key || !storage) {
989
+ return {};
990
+ }
991
+ try {
992
+ const serializedState = storage.getItem(key);
993
+ if (!serializedState) {
994
+ return {};
995
+ }
996
+ const storedState = JSON.parse(serializedState);
997
+ return isRecord2(storedState) ? getUiGraphChatPersistentState(uiGraph, storedState) : {};
998
+ } catch {
999
+ return {};
1000
+ }
1001
+ }
1002
+ function saveUiGraphChatPersistentState(uiGraph, state, storage = getDefaultUiGraphBrowserStorage(), location) {
1003
+ const key = getUiGraphChatStorageKey(uiGraph, location);
1004
+ if (!key || !storage) {
1005
+ return;
1006
+ }
1007
+ try {
1008
+ const persistentState = getUiGraphChatPersistentState(uiGraph, state);
1009
+ if (Object.keys(persistentState).length === 0) {
1010
+ storage.removeItem(key);
1011
+ return;
1012
+ }
1013
+ const serializedState = JSON.stringify(persistentState);
1014
+ if (storage.getItem(key) !== serializedState) {
1015
+ storage.setItem(key, serializedState);
1016
+ }
1017
+ } catch {
1018
+ }
1019
+ }
1020
+ function observeUiGraphOutputResizeBounds(output) {
1021
+ const ownerWindow = output.ownerDocument.defaultView;
1022
+ let scheduledFrame;
1023
+ const sync = () => {
1024
+ scheduledFrame = void 0;
1025
+ if (!ownerWindow) return;
1026
+ const header = output.querySelector(".rivet-web-app-output-header");
1027
+ const content = output.querySelector(".rivet-web-app-output-content");
1028
+ const body = output.querySelector(".rivet-web-app-output-content-body");
1029
+ if (!header || !content || !body) {
1030
+ output.classList.remove("rivet-web-app-output-resizable");
1031
+ output.classList.remove("rivet-web-app-output-scrollable");
1032
+ output.style.removeProperty(OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY);
1033
+ output.style.removeProperty(OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY);
1034
+ return;
1035
+ }
1036
+ const bodyStyle = ownerWindow.getComputedStyle(body);
1037
+ const lineHeight = getPixelValue(bodyStyle.lineHeight, getPixelValue(bodyStyle.fontSize, 16) * 1.5);
1038
+ const contentStyle = ownerWindow.getComputedStyle(content);
1039
+ const contentPadding = getPixelValue(contentStyle.paddingTop, 0) + getPixelValue(contentStyle.paddingBottom, 0);
1040
+ const verticalBorder = Math.max(0, output.offsetHeight - output.clientHeight);
1041
+ const minimumHeight = Math.ceil(
1042
+ header.getBoundingClientRect().height + contentPadding + lineHeight + verticalBorder
1043
+ );
1044
+ const naturalHeight = Math.ceil(
1045
+ header.getBoundingClientRect().height + contentPadding + Math.max(body.scrollHeight, lineHeight) + verticalBorder
1046
+ );
1047
+ const viewportHeight = (ownerWindow == null ? void 0 : ownerWindow.innerHeight) ?? OUTPUT_MAX_HEIGHT_PX / OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO;
1048
+ const maximumViewportHeight = Math.min(viewportHeight * OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO, OUTPUT_MAX_HEIGHT_PX);
1049
+ output.classList.toggle("rivet-web-app-output-resizable", naturalHeight > maximumViewportHeight);
1050
+ output.classList.toggle("rivet-web-app-output-scrollable", body.scrollHeight > body.clientHeight);
1051
+ setStyleProperty(output, OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY, `${minimumHeight}px`);
1052
+ setStyleProperty(output, OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY, `${naturalHeight}px`);
1053
+ };
1054
+ const scheduleSync = () => {
1055
+ if (scheduledFrame != null) return;
1056
+ if (ownerWindow == null ? void 0 : ownerWindow.requestAnimationFrame) {
1057
+ scheduledFrame = ownerWindow.requestAnimationFrame(sync);
1058
+ } else {
1059
+ sync();
1060
+ }
1061
+ };
1062
+ const resizeObserver = (ownerWindow == null ? void 0 : ownerWindow.ResizeObserver) ? new ownerWindow.ResizeObserver(scheduleSync) : void 0;
1063
+ resizeObserver == null ? void 0 : resizeObserver.observe(output);
1064
+ const mutationObserver = (ownerWindow == null ? void 0 : ownerWindow.MutationObserver) ? new ownerWindow.MutationObserver(scheduleSync) : void 0;
1065
+ mutationObserver == null ? void 0 : mutationObserver.observe(output, { childList: true, characterData: true, subtree: true });
1066
+ output.addEventListener("load", scheduleSync, true);
1067
+ ownerWindow == null ? void 0 : ownerWindow.addEventListener("resize", scheduleSync);
1068
+ sync();
1069
+ return () => {
1070
+ if (scheduledFrame != null) ownerWindow == null ? void 0 : ownerWindow.cancelAnimationFrame(scheduledFrame);
1071
+ resizeObserver == null ? void 0 : resizeObserver.disconnect();
1072
+ mutationObserver == null ? void 0 : mutationObserver.disconnect();
1073
+ output.removeEventListener("load", scheduleSync, true);
1074
+ ownerWindow == null ? void 0 : ownerWindow.removeEventListener("resize", scheduleSync);
1075
+ };
1076
+ }
1077
+ async function copyUiGraphText(value) {
1078
+ var _a;
1079
+ try {
1080
+ await navigator.clipboard.writeText(value);
1081
+ return true;
1082
+ } catch {
1083
+ }
1084
+ const textArea = document.createElement("textarea");
1085
+ textArea.className = "rivet-web-app-clipboard-fallback";
1086
+ textArea.value = value;
1087
+ try {
1088
+ document.body.append(textArea);
1089
+ textArea.select();
1090
+ return ((_a = document.execCommand) == null ? void 0 : _a.call(document, "copy")) ?? false;
1091
+ } catch {
1092
+ return false;
1093
+ } finally {
1094
+ textArea.remove();
1095
+ }
1096
+ }
1097
+ function downloadUiGraphJsonOutput(value, appName) {
1098
+ const url = URL.createObjectURL(new Blob([value], { type: "application/json" }));
1099
+ try {
1100
+ const link = document.createElement("a");
1101
+ link.href = url;
1102
+ link.download = getUiGraphJsonOutputFilename(appName);
1103
+ document.body.append(link);
1104
+ link.click();
1105
+ link.remove();
1106
+ } finally {
1107
+ globalThis.setTimeout(() => URL.revokeObjectURL(url), 0);
1108
+ }
1109
+ }
1110
+ function highlightUiGraphChatSearchMatches(messagesElement, query, requestedActiveIndex = 0) {
1111
+ var _a, _b;
1112
+ clearUiGraphChatSearchMatches(messagesElement);
1113
+ const searchText = query.trim();
1114
+ if (!searchText) {
1115
+ return { activeIndex: -1, matches: [] };
1116
+ }
1117
+ const document2 = messagesElement.ownerDocument;
1118
+ const textNodes = [];
1119
+ const walker = document2.createTreeWalker(messagesElement, 4);
1120
+ let node = walker.nextNode();
1121
+ while (node) {
1122
+ if ((_a = node.parentElement) == null ? void 0 : _a.closest("script, style, textarea")) {
1123
+ node = walker.nextNode();
1124
+ continue;
1125
+ }
1126
+ textNodes.push(node);
1127
+ node = walker.nextNode();
1128
+ }
1129
+ const matches = [];
1130
+ for (const textNode of textNodes) {
1131
+ const value = textNode.data;
1132
+ const ranges = [];
1133
+ const expression = new RegExp(escapeRegularExpression(searchText), "gi");
1134
+ for (const match of value.matchAll(expression)) {
1135
+ if (match.index != null && match[0]) {
1136
+ ranges.push({ start: match.index, end: match.index + match[0].length });
1137
+ }
1138
+ }
1139
+ if (ranges.length === 0 || !textNode.parentNode) {
1140
+ continue;
1141
+ }
1142
+ const fragment = document2.createDocumentFragment();
1143
+ let cursor = 0;
1144
+ for (const range of ranges) {
1145
+ fragment.append(value.slice(cursor, range.start));
1146
+ const match = document2.createElement("mark");
1147
+ match.className = CHAT_SEARCH_MATCH_CLASS;
1148
+ match.textContent = value.slice(range.start, range.end);
1149
+ fragment.append(match);
1150
+ matches.push(match);
1151
+ cursor = range.end;
1152
+ }
1153
+ fragment.append(value.slice(cursor));
1154
+ textNode.parentNode.replaceChild(fragment, textNode);
1155
+ }
1156
+ if (matches.length === 0) {
1157
+ return { activeIndex: -1, matches };
1158
+ }
1159
+ const activeIndex = (requestedActiveIndex % matches.length + matches.length) % matches.length;
1160
+ (_b = matches[activeIndex]) == null ? void 0 : _b.classList.add(CHAT_SEARCH_ACTIVE_MATCH_CLASS);
1161
+ return { activeIndex, matches };
1162
+ }
1163
+ function clearUiGraphChatSearchMatches(messagesElement) {
1164
+ for (const match of messagesElement.querySelectorAll(`.${CHAT_SEARCH_MATCH_CLASS}`)) {
1165
+ match.replaceWith(messagesElement.ownerDocument.createTextNode(match.textContent ?? ""));
1166
+ }
1167
+ messagesElement.normalize();
1168
+ }
1169
+ function revealUiGraphChatElement(messagesElement, element, alignment = "center") {
1170
+ if (!element || !messagesElement.contains(element)) {
1171
+ return;
1172
+ }
1173
+ const containerRect = messagesElement.getBoundingClientRect();
1174
+ const elementRect = element.getBoundingClientRect();
1175
+ const maxScrollTop = Math.max(0, messagesElement.scrollHeight - messagesElement.clientHeight);
1176
+ const offset = elementRect.top - containerRect.top - (alignment === "center" ? (messagesElement.clientHeight - elementRect.height) / 2 : 0);
1177
+ messagesElement.scrollTop = Math.max(0, Math.min(maxScrollTop, messagesElement.scrollTop + offset));
1178
+ }
1179
+ var revealUiGraphChatSearchMatch = revealUiGraphChatElement;
1180
+ // Annotate the CommonJS export names for ESM import in node:
1181
+ 0 && (module.exports = {
1182
+ RIVET_WEB_APP_ACTION_PROTOCOL_VERSION,
1183
+ applyUiGraphStatePatch,
1184
+ applyUiGraphWebAppStorageActionPatch,
1185
+ applyUiGraphWebAppStoragePatch,
1186
+ clearUiGraphChatSearchMatches,
1187
+ copyUiGraphText,
1188
+ createUiGraphActionExecutionController,
1189
+ createUiGraphChatHistoryFlushStatePatch,
1190
+ createUiGraphChatPinStatePatch,
1191
+ createUiGraphChatSubmissionStatePatch,
1192
+ createUiGraphInteractionController,
1193
+ downloadUiGraphJsonOutput,
1194
+ getUiGraphActionState,
1195
+ getUiGraphChatDraftStateKey,
1196
+ getUiGraphChatMessagesStateKey,
1197
+ getUiGraphChatPersistentState,
1198
+ getUiGraphChatStorageKey,
1199
+ getUiGraphComponentRenderModel,
1200
+ getUiGraphJsonOutputFilename,
1201
+ getUiGraphProgressiveJsonOutputChunks,
1202
+ getUiGraphWebAppStorageKey,
1203
+ hasUiGraphChatPersistentStateChanged,
1204
+ highlightUiGraphChatSearchMatches,
1205
+ loadUiGraphChatPersistentState,
1206
+ loadUiGraphWebAppStorage,
1207
+ observeUiGraphOutputResizeBounds,
1208
+ parseRivetWebAppClientMessage,
1209
+ parseRivetWebAppServerMessage,
1210
+ revealUiGraphChatElement,
1211
+ revealUiGraphChatSearchMatch,
1212
+ saveUiGraphChatPersistentState
1213
+ });
1214
+ //# sourceMappingURL=webAppRuntime.cjs.map