@valerypopoff/rivet2-core 2.1.2 → 2.1.4

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 (112) hide show
  1. package/dist/cjs/bundle.cjs +3373 -1208
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +625 -0
  4. package/dist/cjs/webAppRuntime.cjs.map +7 -0
  5. package/dist/esm/api/createProcessor.js +3 -0
  6. package/dist/esm/api/processSettings.js +5 -0
  7. package/dist/esm/api/streaming.js +6 -0
  8. package/dist/esm/exports.js +7 -0
  9. package/dist/esm/integrations/mcp/MCPBase.js +92 -34
  10. package/dist/esm/model/GraphProcessor.js +35 -49
  11. package/dist/esm/model/GraphProgress.js +15 -0
  12. package/dist/esm/model/GraphRunLifecycle.js +67 -0
  13. package/dist/esm/model/MarkdownSanitizationPolicy.js +38 -0
  14. package/dist/esm/model/Nodes.js +3 -0
  15. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  16. package/dist/esm/model/RecordingPlayer.js +10 -0
  17. package/dist/esm/model/SubprocessorBridge.js +1 -0
  18. package/dist/esm/model/UiGraph.js +181 -1
  19. package/dist/esm/model/UiGraphActionProtocol.js +122 -0
  20. package/dist/esm/model/UiGraphBindings.js +530 -0
  21. package/dist/esm/model/UiGraphBrowserRuntime.js +40 -0
  22. package/dist/esm/model/UiGraphNormalization.js +298 -0
  23. package/dist/esm/model/UiGraphRendererStyles.js +456 -6
  24. package/dist/esm/model/UiGraphRuntimeModel.js +371 -0
  25. package/dist/esm/model/UiGraphWebAppStatus.js +19 -0
  26. package/dist/esm/model/chat-v2/aiSdkBridge.js +1 -1
  27. package/dist/esm/model/chat-v2/chatV2EditorCache.js +2 -2
  28. package/dist/esm/model/chat-v2/chatV2Pipeline.js +35 -48
  29. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +98 -0
  30. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +64 -0
  31. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +11 -39
  32. package/dist/esm/model/chat-v2/index.js +2 -0
  33. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
  34. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +31 -11
  35. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +21 -9
  36. package/dist/esm/model/chat-v2/providerOptions.js +9 -35
  37. package/dist/esm/model/nodes/ArrayNode.js +2 -13
  38. package/dist/esm/model/nodes/AssembleMessageNode.js +2 -13
  39. package/dist/esm/model/nodes/AssemblePromptNode.js +2 -13
  40. package/dist/esm/model/nodes/CoalesceNode.js +2 -15
  41. package/dist/esm/model/nodes/DelayNode.js +3 -14
  42. package/dist/esm/model/nodes/DidRunNode.js +2 -13
  43. package/dist/esm/model/nodes/JoinNode.js +2 -13
  44. package/dist/esm/model/nodes/LLMChatV2Node.js +3 -3
  45. package/dist/esm/model/nodes/LoopControllerNode.js +3 -14
  46. package/dist/esm/model/nodes/MCPDiscoveryNode.js +19 -90
  47. package/dist/esm/model/nodes/MCPGetPromptNode.js +11 -97
  48. package/dist/esm/model/nodes/MCPToolCallNode.js +11 -97
  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/variadicPortIndex.js +32 -0
  53. package/dist/esm/plugins/anthropic/anthropic.js +1 -1
  54. package/dist/esm/plugins/autoevals/AutoEvalsNode.js +3 -1
  55. package/dist/esm/plugins/gentrace/gentraceSdk.js +8 -0
  56. package/dist/esm/plugins/gentrace/plugin.js +5 -4
  57. package/dist/esm/plugins/google/google.js +9 -7
  58. package/dist/esm/recording/ExecutionRecorder.js +5 -0
  59. package/dist/esm/utils/fetchEventSource.js +16 -17
  60. package/dist/esm/utils/pQueueCompat.js +1 -1
  61. package/dist/esm/utils/serialization/serialization.js +4 -0
  62. package/dist/esm/utils/serialization/serializationUtils.js +16 -0
  63. package/dist/esm/utils/serialization/serialization_v4.js +5 -4
  64. package/dist/esm/webAppRuntime.js +4 -0
  65. package/dist/types/api/createProcessor.d.ts +1 -1
  66. package/dist/types/api/processSettings.d.ts +3 -4
  67. package/dist/types/api/streaming.d.ts +6 -0
  68. package/dist/types/exports.d.ts +7 -0
  69. package/dist/types/integrations/mcp/MCPBase.d.ts +26 -3
  70. package/dist/types/model/ExecutorProtocol.d.ts +7 -0
  71. package/dist/types/model/GraphProcessor.d.ts +7 -0
  72. package/dist/types/model/GraphProgress.d.ts +6 -0
  73. package/dist/types/model/GraphRunLifecycle.d.ts +22 -0
  74. package/dist/types/model/MarkdownSanitizationPolicy.d.ts +9 -0
  75. package/dist/types/model/Nodes.d.ts +3 -2
  76. package/dist/types/model/ProcessContext.d.ts +5 -2
  77. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  78. package/dist/types/model/Settings.d.ts +1 -0
  79. package/dist/types/model/UiGraph.d.ts +50 -5
  80. package/dist/types/model/UiGraphActionProtocol.d.ts +69 -0
  81. package/dist/types/model/UiGraphBindings.d.ts +45 -0
  82. package/dist/types/model/UiGraphBrowserRuntime.d.ts +4 -0
  83. package/dist/types/model/UiGraphNormalization.d.ts +24 -0
  84. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  85. package/dist/types/model/UiGraphRuntimeModel.d.ts +124 -0
  86. package/dist/types/model/UiGraphWebAppStatus.d.ts +5 -0
  87. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +46 -0
  88. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +42 -0
  89. package/dist/types/model/chat-v2/chatV2Types.d.ts +1 -0
  90. package/dist/types/model/chat-v2/index.d.ts +2 -0
  91. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +1 -0
  92. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +2 -0
  93. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -2
  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/JoinNode.d.ts +0 -1
  100. package/dist/types/model/nodes/LoopControllerNode.d.ts +0 -1
  101. package/dist/types/model/nodes/PassthroughNode.d.ts +0 -1
  102. package/dist/types/model/nodes/RaceInputsNode.d.ts +0 -1
  103. package/dist/types/model/nodes/ReportProgressNode.d.ts +23 -0
  104. package/dist/types/model/nodes/variadicPortIndex.d.ts +4 -0
  105. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +5 -0
  106. package/dist/types/plugins/gentrace/plugin.d.ts +1 -1
  107. package/dist/types/recording/RecordedEvents.d.ts +5 -0
  108. package/dist/types/utils/pQueueCompat.d.ts +1 -1
  109. package/dist/types/webAppRuntime.d.ts +9 -0
  110. package/package.json +15 -9
  111. package/dist/esm/plugins/anthropic/fetchEventSource.js +0 -107
  112. package/dist/types/plugins/anthropic/fetchEventSource.d.ts +0 -11
@@ -0,0 +1,67 @@
1
+ /** Owns run-level state only. Scheduling and event emission remain in GraphProcessor. */
2
+ export class GraphRunLifecycle {
3
+ #phase = 'idle';
4
+ #paused = false;
5
+ #abort;
6
+ #finishClaimed = false;
7
+ get phase() {
8
+ return this.#phase;
9
+ }
10
+ get isRunning() {
11
+ return this.#phase === 'running' || this.#phase === 'aborting';
12
+ }
13
+ get isPaused() {
14
+ return this.#paused;
15
+ }
16
+ get isAborted() {
17
+ return this.#abort != null;
18
+ }
19
+ get abortSuccessful() {
20
+ return this.#abort?.successful ?? false;
21
+ }
22
+ get abortError() {
23
+ return this.#abort?.error;
24
+ }
25
+ begin() {
26
+ if (this.isRunning) {
27
+ throw new Error('Cannot process graph while already processing');
28
+ }
29
+ this.#phase = 'running';
30
+ this.#abort = undefined;
31
+ this.#finishClaimed = false;
32
+ }
33
+ complete() {
34
+ if (this.#phase !== 'idle')
35
+ this.#phase = 'finished';
36
+ }
37
+ requestAbort(successful, error) {
38
+ if (!this.isRunning || this.#abort)
39
+ return undefined;
40
+ this.#phase = 'aborting';
41
+ this.#abort = { successful, error };
42
+ return this.#abort;
43
+ }
44
+ pause() {
45
+ if (this.#paused)
46
+ return false;
47
+ this.#paused = true;
48
+ return true;
49
+ }
50
+ resume() {
51
+ if (!this.#paused)
52
+ return false;
53
+ this.#paused = false;
54
+ return true;
55
+ }
56
+ claimRootFinish(isSubProcessor) {
57
+ if (isSubProcessor || this.#finishClaimed)
58
+ return false;
59
+ this.#finishClaimed = true;
60
+ return true;
61
+ }
62
+ getAbortError() {
63
+ if (typeof this.#abort?.error === 'string')
64
+ return new Error(this.#abort.error);
65
+ return this.#abort?.error ?? new Error('Processing aborted');
66
+ }
67
+ }
@@ -0,0 +1,38 @@
1
+ export const RIVET_MARKDOWN_ALLOWED_TAGS = [
2
+ 'a',
3
+ 'blockquote',
4
+ 'br',
5
+ 'code',
6
+ 'del',
7
+ 'em',
8
+ 'h1',
9
+ 'h2',
10
+ 'h3',
11
+ 'h4',
12
+ 'h5',
13
+ 'h6',
14
+ 'hr',
15
+ 'li',
16
+ 'ol',
17
+ 'p',
18
+ 'pre',
19
+ 'strong',
20
+ 'sub',
21
+ 'sup',
22
+ 'table',
23
+ 'tbody',
24
+ 'td',
25
+ 'th',
26
+ 'thead',
27
+ 'tr',
28
+ 'ul',
29
+ ];
30
+ export const RIVET_MARKDOWN_ALLOWED_ATTRIBUTES = ['class', 'href', 'title'];
31
+ // http(s), mailto, hashes, and ordinary relative links. Protocol-relative and
32
+ // active/unknown schemes are intentionally excluded.
33
+ export const RIVET_MARKDOWN_ALLOWED_URI_REGEXP_SOURCE = '^(?:https?:|mailto:|#|\\?(?:[^/]|$)|/(?!/)|\\.{1,2}/|[a-z0-9._~-]+(?:[/?#]|$))';
34
+ export const RIVET_MARKDOWN_SANITIZER_POLICY = Object.freeze({
35
+ allowedAttributes: RIVET_MARKDOWN_ALLOWED_ATTRIBUTES,
36
+ allowedTags: RIVET_MARKDOWN_ALLOWED_TAGS,
37
+ allowedUriRegExpSource: RIVET_MARKDOWN_ALLOWED_URI_REGEXP_SOURCE,
38
+ });
@@ -54,6 +54,8 @@ import { extractObjectPathNode } from './nodes/ExtractObjectPathNode.js';
54
54
  export * from './nodes/ExtractObjectPathNode.js';
55
55
  import { raiseEventNode } from './nodes/RaiseEventNode.js';
56
56
  export * from './nodes/RaiseEventNode.js';
57
+ import { reportProgressNode } from './nodes/ReportProgressNode.js';
58
+ export * from './nodes/ReportProgressNode.js';
57
59
  import { contextNode } from './nodes/ContextNode.js';
58
60
  export * from './nodes/ContextNode.js';
59
61
  import { coalesceNode } from './nodes/CoalesceNode.js';
@@ -210,6 +212,7 @@ export const registerBuiltInNodes = (registry) => {
210
212
  .register(externalCallNode)
211
213
  .register(extractObjectPathNode)
212
214
  .register(raiseEventNode)
215
+ .register(reportProgressNode)
213
216
  .register(contextNode)
214
217
  .register(coalesceNode)
215
218
  .register(didRunNode)
@@ -1,5 +1,5 @@
1
1
  export function buildNodeProcessContext(options) {
2
- const { attachedData, activeOutputPortIds, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, node, nodeAbortController, onPartialOutputs, processId, requestUserInput, setGlobal, waitEvent, } = options;
2
+ const { attachedData, activeOutputPortIds, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, node, nodeAbortController, onPartialOutputs, processId, requestUserInput, reportProgress, setGlobal, waitEvent, } = options;
3
3
  return {
4
4
  ...base,
5
5
  node,
@@ -15,6 +15,7 @@ export function buildNodeProcessContext(options) {
15
15
  createSubProcessor: createSubProcessor,
16
16
  getPluginConfig,
17
17
  requestUserInput,
18
+ reportProgress,
18
19
  execution,
19
20
  };
20
21
  }
@@ -238,6 +238,16 @@ export async function replayExecutionRecording(options) {
238
238
  });
239
239
  break;
240
240
  }
241
+ case 'progress': {
242
+ const { data } = event;
243
+ emitDetached(emitter, 'progress', {
244
+ node: getNode(data.nodeId),
245
+ processId: data.processId,
246
+ progress: data.progress,
247
+ execution: getExecution(data.execution?.graphId ?? getGraphIdForNode(data.nodeId), data.execution),
248
+ });
249
+ break;
250
+ }
241
251
  case 'userInput': {
242
252
  const { data } = event;
243
253
  const node = getNode(data.nodeId);
@@ -27,6 +27,7 @@ export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
27
27
  processor.on('nodeError', (event) => parentEmitter.emit('nodeError', event));
28
28
  processor.on('nodeFinish', (event) => parentEmitter.emit('nodeFinish', event));
29
29
  processor.on('partialOutput', (event) => parentEmitter.emit('partialOutput', event));
30
+ processor.on('progress', (event) => parentEmitter.emit('progress', event));
30
31
  processor.on('nodeExcluded', (event) => parentEmitter.emit('nodeExcluded', event));
31
32
  processor.on('nodeStart', (event) => parentEmitter.emit('nodeStart', event));
32
33
  processor.on('graphAbort', (event) => parentEmitter.emit('graphAbort', event));
@@ -1,4 +1,52 @@
1
1
  import { newId } from '../utils/newId.js';
2
+ export const UI_GRAPH_GAP_SIZES = ['small', 'medium', 'large'];
3
+ export const UI_GRAPH_OUTPUT_RENDER_MODES = ['text', 'json', 'markdown', 'image'];
4
+ export function hasValidUiGraphComponentIds(uiGraph) {
5
+ const componentIds = new Set();
6
+ for (const component of uiGraph.components) {
7
+ const componentId = typeof component.id === 'string' ? component.id : '';
8
+ if (!componentId.trim() || componentIds.has(componentId)) {
9
+ return false;
10
+ }
11
+ componentIds.add(componentId);
12
+ }
13
+ return true;
14
+ }
15
+ /**
16
+ * Returns an immutable component-ID repair for legacy or externally assembled
17
+ * UI graphs. Full untrusted-data validation belongs to normalizeUiGraph().
18
+ */
19
+ export function normalizeUiGraphComponentIds(uiGraph) {
20
+ if (hasValidUiGraphComponentIds(uiGraph)) {
21
+ return uiGraph;
22
+ }
23
+ const reservedIds = new Set(uiGraph.components
24
+ .map((component) => (typeof component.id === 'string' ? component.id : ''))
25
+ .filter((componentId) => Boolean(componentId.trim())));
26
+ const usedIds = new Set();
27
+ const graphId = typeof uiGraph.id === 'string' && uiGraph.id.trim() ? uiGraph.id : 'ui-graph';
28
+ const components = uiGraph.components.map((component, index) => {
29
+ const componentId = typeof component.id === 'string' ? component.id : '';
30
+ if (componentId.trim() && !usedIds.has(componentId)) {
31
+ usedIds.add(componentId);
32
+ return component;
33
+ }
34
+ const repairedId = getRepairedUiGraphComponentId(graphId, index, reservedIds, usedIds);
35
+ usedIds.add(repairedId);
36
+ return { ...component, id: repairedId };
37
+ });
38
+ return { ...uiGraph, components };
39
+ }
40
+ function getRepairedUiGraphComponentId(graphId, componentIndex, reservedIds, usedIds) {
41
+ const baseId = `${graphId}-component-${componentIndex + 1}`;
42
+ let repairedId = baseId;
43
+ let suffix = 2;
44
+ while (reservedIds.has(repairedId) || usedIds.has(repairedId)) {
45
+ repairedId = `${baseId}-${suffix}`;
46
+ suffix += 1;
47
+ }
48
+ return repairedId;
49
+ }
2
50
  export function createDefaultUiGraph(options = {}) {
3
51
  const promptStateKey = 'input';
4
52
  const resultStateKey = 'result';
@@ -45,11 +93,94 @@ export function getUiGraphInitialState(uiGraph) {
45
93
  if (component.type === 'input' || component.type === 'textarea') {
46
94
  state[component.stateKey] = component.defaultValue ?? '';
47
95
  }
96
+ else if (component.type === 'chat') {
97
+ state[getUiGraphChatDraftStateKey(component.id)] = '';
98
+ state[getUiGraphChatMessagesStateKey(component.id)] = [];
99
+ }
48
100
  }
49
101
  return state;
50
102
  }
51
103
  export function getUiGraphActionComponent(uiGraph, componentId) {
52
- return uiGraph.components.find((component) => component.id === componentId && component.type === 'button');
104
+ return uiGraph.components.find((component) => component.id === componentId && (component.type === 'button' || component.type === 'chat'));
105
+ }
106
+ export function getUiGraphChatDraftStateKey(componentId) {
107
+ return `__rivet_chat_${componentId}_draft`;
108
+ }
109
+ export function getUiGraphChatMessagesStateKey(componentId) {
110
+ return `__rivet_chat_${componentId}_messages`;
111
+ }
112
+ export function getUiGraphChatMessages(componentId, state) {
113
+ const messages = state[getUiGraphChatMessagesStateKey(componentId)];
114
+ return Array.isArray(messages) ? messages.filter(isUiGraphChatMessage) : [];
115
+ }
116
+ export function createUiGraphChatSubmissionStatePatch(componentId, state) {
117
+ const draftStateKey = getUiGraphChatDraftStateKey(componentId);
118
+ const content = `${state[draftStateKey] ?? ''}`.trim();
119
+ if (!content) {
120
+ return undefined;
121
+ }
122
+ return {
123
+ [draftStateKey]: '',
124
+ [getUiGraphChatMessagesStateKey(componentId)]: [
125
+ ...getUiGraphChatMessages(componentId, state),
126
+ { role: 'user', content },
127
+ ],
128
+ };
129
+ }
130
+ export function getUiGraphComponentActionState(component, state) {
131
+ if (component.type === 'button') {
132
+ return getUiGraphActionState(component.action, state);
133
+ }
134
+ const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);
135
+ return {
136
+ ...getUiGraphActionState(component.action, state),
137
+ [messagesStateKey]: getUiGraphChatMessages(component.id, state),
138
+ };
139
+ }
140
+ export function resolveUiGraphComponentActionInputs(component, state) {
141
+ if (component.type === 'button') {
142
+ return resolveUiGraphActionInputs(component.action, state);
143
+ }
144
+ const messages = getUiGraphChatMessages(component.id, state);
145
+ const latestMessage = messages[messages.length - 1];
146
+ const latestUserMessage = latestMessage?.role === 'user' ? latestMessage : undefined;
147
+ const historyMessages = latestUserMessage ? messages.slice(0, -1) : messages;
148
+ const inputs = resolveUiGraphActionInputs(component.action, state);
149
+ if (component.action.userInputId) {
150
+ inputs[component.action.userInputId] = latestUserMessage?.content ?? '';
151
+ }
152
+ if (component.action.historyInputId) {
153
+ inputs[component.action.historyInputId] = {
154
+ type: 'chat-message[]',
155
+ value: historyMessages.map(toRivetChatMessage),
156
+ };
157
+ }
158
+ return inputs;
159
+ }
160
+ export function resolveUiGraphComponentActionOutputStatePatch(component, outputs, state) {
161
+ if (component.type === 'button') {
162
+ return resolveUiGraphActionOutputStatePatch(component.action, outputs);
163
+ }
164
+ const outputId = component.action.responseOutputId;
165
+ if (!outputId || !Object.prototype.hasOwnProperty.call(outputs, outputId)) {
166
+ throw new Error(outputId
167
+ ? `Graph output "${outputId}" was not returned by the target graph.`
168
+ : 'The Chat component has no response graph output.');
169
+ }
170
+ const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);
171
+ return {
172
+ [messagesStateKey]: [
173
+ ...getUiGraphChatMessages(component.id, state),
174
+ { role: 'assistant', content: getUiGraphChatResponseText(outputs[outputId]) },
175
+ ],
176
+ };
177
+ }
178
+ export function getUiGraphComponentActionOutputStateKeys(component) {
179
+ return component.type === 'button'
180
+ ? getUiGraphActionOutputBindings(component.action)
181
+ .map((binding) => binding.stateKey.trim())
182
+ .filter(Boolean)
183
+ : [getUiGraphChatMessagesStateKey(component.id)];
53
184
  }
54
185
  export function resolveUiGraphActionInputs(action, state) {
55
186
  const inputs = {};
@@ -66,6 +197,16 @@ export function resolveUiGraphActionInputs(action, state) {
66
197
  }
67
198
  return inputs;
68
199
  }
200
+ /**
201
+ * Selects the UI state that a button action is explicitly allowed to send.
202
+ * Outputs and unrelated form fields stay local to the rendered web app.
203
+ */
204
+ export function getUiGraphActionState(action, state) {
205
+ return Object.fromEntries([...new Set(getUiGraphActionInputBindings(action).map((binding) => binding.stateKey))]
206
+ .filter(Boolean)
207
+ .filter((stateKey) => Object.prototype.hasOwnProperty.call(state, stateKey))
208
+ .map((stateKey) => [stateKey, state[stateKey]]));
209
+ }
69
210
  export function resolveUiGraphActionOutputStateValue(action, outputs) {
70
211
  if (!action.outputKey) {
71
212
  return outputs;
@@ -111,3 +252,42 @@ function resolveUiGraphOutputBindingValue(binding, outputs) {
111
252
  }
112
253
  return outputs[binding.outputKey]?.value;
113
254
  }
255
+ function isUiGraphChatMessage(value) {
256
+ return (value != null &&
257
+ typeof value === 'object' &&
258
+ (value.role === 'user' || value.role === 'assistant') &&
259
+ typeof value.content === 'string');
260
+ }
261
+ function toRivetChatMessage(message) {
262
+ return message.role === 'user'
263
+ ? { type: 'user', message: message.content }
264
+ : {
265
+ type: 'assistant',
266
+ message: message.content,
267
+ function_call: undefined,
268
+ function_calls: undefined,
269
+ };
270
+ }
271
+ function getUiGraphChatResponseText(output) {
272
+ if (output.type === 'chat-message') {
273
+ const message = output.value.message;
274
+ if (typeof message === 'string') {
275
+ return message;
276
+ }
277
+ return (Array.isArray(message) ? message : [message])
278
+ .flatMap((part) => (typeof part === 'string' ? [part] : []))
279
+ .join('\n');
280
+ }
281
+ if (typeof output.value === 'string') {
282
+ return output.value;
283
+ }
284
+ if (output.value == null) {
285
+ return '';
286
+ }
287
+ try {
288
+ return JSON.stringify(output.value, null, 2);
289
+ }
290
+ catch {
291
+ return String(output.value);
292
+ }
293
+ }
@@ -0,0 +1,122 @@
1
+ import { normalizeGraphProgress } from './GraphProgress.js';
2
+ export const RIVET_WEB_APP_ACTION_PROTOCOL_VERSION = 1;
3
+ export function parseRivetWebAppClientMessage(value) {
4
+ if (!isRecord(value) || typeof value.type !== 'string')
5
+ return undefined;
6
+ switch (value.type) {
7
+ case 'client.hello':
8
+ return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION
9
+ ? { type: value.type, protocolVersion: value.protocolVersion }
10
+ : undefined;
11
+ case 'action.start':
12
+ return isNonEmptyString(value.requestId) &&
13
+ isNonEmptyString(value.componentId) &&
14
+ isRecord(value.state) &&
15
+ (value.revisionKey == null || typeof value.revisionKey === 'string')
16
+ ? {
17
+ type: value.type,
18
+ requestId: value.requestId,
19
+ componentId: value.componentId,
20
+ state: value.state,
21
+ ...(typeof value.revisionKey === 'string' ? { revisionKey: value.revisionKey } : {}),
22
+ }
23
+ : undefined;
24
+ case 'action.cancel':
25
+ return isNonEmptyString(value.runId) ? { type: value.type, runId: value.runId } : undefined;
26
+ case 'run.resume':
27
+ return isNonEmptyString(value.runId) &&
28
+ typeof value.lastSequence === 'number' &&
29
+ Number.isSafeInteger(value.lastSequence) &&
30
+ value.lastSequence >= 0
31
+ ? { type: value.type, runId: value.runId, lastSequence: value.lastSequence }
32
+ : undefined;
33
+ default:
34
+ return undefined;
35
+ }
36
+ }
37
+ export function parseRivetWebAppServerMessage(value) {
38
+ if (!isRecord(value) || typeof value.type !== 'string')
39
+ return undefined;
40
+ if (value.type === 'server.ready') {
41
+ return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION
42
+ ? { type: value.type, protocolVersion: value.protocolVersion }
43
+ : undefined;
44
+ }
45
+ if (value.type === 'server.draining')
46
+ return { type: value.type };
47
+ if (value.type === 'action.rejected') {
48
+ return isNonEmptyString(value.requestId) && isNonEmptyString(value.error)
49
+ ? {
50
+ type: value.type,
51
+ requestId: value.requestId,
52
+ error: value.error,
53
+ ...(typeof value.code === 'string' ? { code: value.code } : {}),
54
+ }
55
+ : undefined;
56
+ }
57
+ if (value.type === 'run.rejected') {
58
+ return isNonEmptyString(value.runId) && isNonEmptyString(value.error)
59
+ ? {
60
+ type: value.type,
61
+ runId: value.runId,
62
+ error: value.error,
63
+ ...(typeof value.code === 'string' ? { code: value.code } : {}),
64
+ }
65
+ : undefined;
66
+ }
67
+ if (!hasRunEventBase(value))
68
+ return undefined;
69
+ const base = {
70
+ requestId: value.requestId,
71
+ runId: value.runId,
72
+ sequence: value.sequence,
73
+ };
74
+ switch (value.type) {
75
+ case 'action.accepted':
76
+ case 'action.cancelled':
77
+ return { type: value.type, ...base };
78
+ case 'action.progress': {
79
+ if (!isRecord(value.progress))
80
+ return undefined;
81
+ const progress = normalizeGraphProgress({
82
+ message: typeof value.progress.message === 'string' ? value.progress.message : undefined,
83
+ percent: typeof value.progress.percent === 'number' ? value.progress.percent : undefined,
84
+ });
85
+ return progress ? { type: value.type, ...base, progress } : undefined;
86
+ }
87
+ case 'action.completed':
88
+ return isRecord(value.statePatch) ? { type: value.type, ...base, statePatch: value.statePatch } : undefined;
89
+ case 'action.failed':
90
+ return isNonEmptyString(value.error)
91
+ ? {
92
+ type: value.type,
93
+ ...base,
94
+ error: value.error,
95
+ ...(typeof value.code === 'string' ? { code: value.code } : {}),
96
+ }
97
+ : undefined;
98
+ case 'action.interrupted':
99
+ return isNonEmptyString(value.error) ? { type: value.type, ...base, error: value.error } : undefined;
100
+ default:
101
+ return undefined;
102
+ }
103
+ }
104
+ export function isRivetWebAppRunTerminalEvent(event) {
105
+ return (event.type === 'action.completed' ||
106
+ event.type === 'action.failed' ||
107
+ event.type === 'action.cancelled' ||
108
+ event.type === 'action.interrupted');
109
+ }
110
+ function hasRunEventBase(value) {
111
+ return (isNonEmptyString(value.requestId) &&
112
+ isNonEmptyString(value.runId) &&
113
+ typeof value.sequence === 'number' &&
114
+ Number.isSafeInteger(value.sequence) &&
115
+ value.sequence > 0);
116
+ }
117
+ function isRecord(value) {
118
+ return typeof value === 'object' && value != null && !Array.isArray(value);
119
+ }
120
+ function isNonEmptyString(value) {
121
+ return typeof value === 'string' && value.length > 0;
122
+ }