@valerypopoff/rivet2-core 2.1.3 → 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 (77) hide show
  1. package/dist/cjs/bundle.cjs +2707 -1012
  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/streaming.js +6 -0
  7. package/dist/esm/exports.js +5 -0
  8. package/dist/esm/integrations/mcp/MCPBase.js +92 -34
  9. package/dist/esm/model/GraphProcessor.js +11 -4
  10. package/dist/esm/model/GraphProgress.js +15 -0
  11. package/dist/esm/model/Nodes.js +3 -0
  12. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  13. package/dist/esm/model/RecordingPlayer.js +10 -0
  14. package/dist/esm/model/SubprocessorBridge.js +1 -0
  15. package/dist/esm/model/UiGraph.js +127 -4
  16. package/dist/esm/model/UiGraphActionProtocol.js +122 -0
  17. package/dist/esm/model/UiGraphBindings.js +530 -0
  18. package/dist/esm/model/UiGraphBrowserRuntime.js +40 -0
  19. package/dist/esm/model/UiGraphNormalization.js +298 -0
  20. package/dist/esm/model/UiGraphRendererStyles.js +374 -6
  21. package/dist/esm/model/UiGraphRuntimeModel.js +300 -0
  22. package/dist/esm/model/UiGraphWebAppStatus.js +19 -0
  23. package/dist/esm/model/nodes/ArrayNode.js +2 -13
  24. package/dist/esm/model/nodes/AssembleMessageNode.js +2 -13
  25. package/dist/esm/model/nodes/AssemblePromptNode.js +2 -13
  26. package/dist/esm/model/nodes/CoalesceNode.js +2 -15
  27. package/dist/esm/model/nodes/DelayNode.js +3 -14
  28. package/dist/esm/model/nodes/DidRunNode.js +2 -13
  29. package/dist/esm/model/nodes/JoinNode.js +2 -13
  30. package/dist/esm/model/nodes/LoopControllerNode.js +3 -14
  31. package/dist/esm/model/nodes/MCPDiscoveryNode.js +19 -90
  32. package/dist/esm/model/nodes/MCPGetPromptNode.js +11 -97
  33. package/dist/esm/model/nodes/MCPToolCallNode.js +11 -97
  34. package/dist/esm/model/nodes/PassthroughNode.js +3 -14
  35. package/dist/esm/model/nodes/RaceInputsNode.js +2 -13
  36. package/dist/esm/model/nodes/ReportProgressNode.js +57 -0
  37. package/dist/esm/model/nodes/variadicPortIndex.js +32 -0
  38. package/dist/esm/plugins/anthropic/anthropic.js +1 -1
  39. package/dist/esm/recording/ExecutionRecorder.js +5 -0
  40. package/dist/esm/utils/fetchEventSource.js +16 -17
  41. package/dist/esm/utils/serialization/serialization.js +4 -0
  42. package/dist/esm/utils/serialization/serializationUtils.js +8 -27
  43. package/dist/esm/utils/serialization/serialization_v4.js +3 -3
  44. package/dist/esm/webAppRuntime.js +4 -2
  45. package/dist/types/api/streaming.d.ts +6 -0
  46. package/dist/types/exports.d.ts +5 -0
  47. package/dist/types/integrations/mcp/MCPBase.d.ts +26 -3
  48. package/dist/types/model/ExecutorProtocol.d.ts +7 -0
  49. package/dist/types/model/GraphProcessor.d.ts +7 -0
  50. package/dist/types/model/GraphProgress.d.ts +6 -0
  51. package/dist/types/model/Nodes.d.ts +3 -2
  52. package/dist/types/model/ProcessContext.d.ts +3 -0
  53. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  54. package/dist/types/model/UiGraph.d.ts +42 -9
  55. package/dist/types/model/UiGraphActionProtocol.d.ts +69 -0
  56. package/dist/types/model/UiGraphBindings.d.ts +45 -0
  57. package/dist/types/model/UiGraphBrowserRuntime.d.ts +4 -0
  58. package/dist/types/model/UiGraphNormalization.d.ts +24 -0
  59. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  60. package/dist/types/model/UiGraphRuntimeModel.d.ts +77 -5
  61. package/dist/types/model/UiGraphWebAppStatus.d.ts +5 -0
  62. package/dist/types/model/nodes/ArrayNode.d.ts +0 -1
  63. package/dist/types/model/nodes/AssembleMessageNode.d.ts +0 -1
  64. package/dist/types/model/nodes/AssemblePromptNode.d.ts +0 -1
  65. package/dist/types/model/nodes/DelayNode.d.ts +0 -1
  66. package/dist/types/model/nodes/DidRunNode.d.ts +0 -1
  67. package/dist/types/model/nodes/JoinNode.d.ts +0 -1
  68. package/dist/types/model/nodes/LoopControllerNode.d.ts +0 -1
  69. package/dist/types/model/nodes/PassthroughNode.d.ts +0 -1
  70. package/dist/types/model/nodes/RaceInputsNode.d.ts +0 -1
  71. package/dist/types/model/nodes/ReportProgressNode.d.ts +23 -0
  72. package/dist/types/model/nodes/variadicPortIndex.d.ts +4 -0
  73. package/dist/types/recording/RecordedEvents.d.ts +5 -0
  74. package/dist/types/webAppRuntime.d.ts +8 -3
  75. package/package.json +2 -2
  76. package/dist/esm/plugins/anthropic/fetchEventSource.js +0 -107
  77. package/dist/types/plugins/anthropic/fetchEventSource.d.ts +0 -11
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/webAppRuntime.ts", "../../src/utils/newId.ts", "../../src/model/UiGraph.ts", "../../src/model/GraphProgress.ts", "../../src/model/UiGraphRuntimeModel.ts", "../../src/model/UiGraphActionProtocol.ts", "../../src/model/UiGraphBrowserRuntime.ts"],
4
+ "sourcesContent": ["export type {\n UiComponentId,\n UiGraph,\n UiGraphActionComponent,\n UiGraphChatMessage,\n UiGraphComponent,\n} from './model/UiGraph.js';\nexport type { UiGraphInteractionSnapshot } from './model/UiGraphRuntimeModel.js';\nexport type {\n RivetWebAppClientMessage,\n RivetWebAppRunEvent,\n RivetWebAppServerMessage,\n} from './model/UiGraphActionProtocol.js';\nexport type { GraphProgress } from './model/GraphProgress.js';\nexport type { RivetMarkdownSanitizerPolicy } from './model/MarkdownSanitizationPolicy.js';\nexport {\n createUiGraphChatSubmissionStatePatch,\n getUiGraphActionState,\n getUiGraphChatDraftStateKey,\n} from './model/UiGraph.js';\nexport {\n applyUiGraphStatePatch,\n createUiGraphActionExecutionController,\n createUiGraphInteractionController,\n getUiGraphComponentRenderModel,\n getUiGraphJsonOutputFilename,\n} from './model/UiGraphRuntimeModel.js';\nexport {\n parseRivetWebAppClientMessage,\n parseRivetWebAppServerMessage,\n RIVET_WEB_APP_ACTION_PROTOCOL_VERSION,\n} from './model/UiGraphActionProtocol.js';\nexport { copyUiGraphText, downloadUiGraphJsonOutput } from './model/UiGraphBrowserRuntime.js';\n", "import { nanoid } from 'nanoid/non-secure';\n\nexport function newId<T extends string>(): T {\n return nanoid() as T;\n}\n", "import type { Opaque } from 'type-fest';\nimport type { GraphId } from './NodeGraph.js';\nimport { newId } from '../utils/newId.js';\nimport type { ChatMessage, DataValue } from './DataValue.js';\n\nexport type UiGraphId = Opaque<string, 'UiGraphId'>;\nexport type UiComponentId = Opaque<string, 'UiComponentId'>;\nexport type UiGraphOutputs = Record<string, DataValue>;\nexport const UI_GRAPH_GAP_SIZES = ['small', 'medium', 'large'] as const;\nexport type UiGraphGapSize = (typeof UI_GRAPH_GAP_SIZES)[number];\nexport const UI_GRAPH_OUTPUT_RENDER_MODES = ['text', 'json', 'markdown', 'image'] as const;\nexport type UiGraphOutputRenderMode = (typeof UI_GRAPH_OUTPUT_RENDER_MODES)[number];\n\nexport type UiGraphValueBinding =\n | {\n type: 'state';\n key: string;\n }\n | {\n type: 'literal';\n value: unknown;\n };\n\nexport type UiGraphRunGraphAction = {\n type: 'runGraph';\n graphId?: GraphId;\n inputMappings?: UiGraphInputBinding[];\n inputs?: Record<string, UiGraphValueBinding>;\n outputs?: UiGraphOutputBinding[];\n outputKey?: string;\n outputStateKey?: string;\n};\n\nexport type UiGraphChatRunGraphAction = {\n type: 'runGraph';\n graphId?: GraphId;\n userInputId?: string;\n historyInputId?: string;\n responseOutputId?: string;\n inputMappings?: UiGraphInputBinding[];\n};\n\nexport type UiGraphChatMessage = {\n role: 'assistant' | 'user';\n content: string;\n};\n\nexport type UiGraphInputBinding = {\n inputKey: string;\n stateKey: string;\n};\n\nexport type UiGraphOutputBinding = {\n outputKey?: string;\n stateKey: string;\n};\n\nexport type UiGraphAction = UiGraphRunGraphAction;\n\nexport type UiGraphComponent =\n | {\n id: UiComponentId;\n type: 'text';\n text: string;\n }\n | {\n id: UiComponentId;\n type: 'markdown';\n markdown: string;\n }\n | {\n id: UiComponentId;\n type: 'gap';\n size: UiGraphGapSize;\n }\n | {\n id: UiComponentId;\n type: 'input';\n label: string;\n stateKey: string;\n placeholder?: string;\n defaultValue?: string;\n }\n | {\n id: UiComponentId;\n type: 'textarea';\n label: string;\n stateKey: string;\n placeholder?: string;\n defaultValue?: string;\n }\n | {\n id: UiComponentId;\n type: 'button';\n label: string;\n action: UiGraphAction;\n }\n | {\n id: UiComponentId;\n type: 'chat';\n action: UiGraphChatRunGraphAction;\n placeholder?: string;\n }\n | {\n id: UiComponentId;\n type: 'output';\n label?: string;\n stateKey: string;\n renderAs?: UiGraphOutputRenderMode;\n };\n\nexport type UiGraph = {\n id: UiGraphId;\n name: string;\n description?: string;\n components: UiGraphComponent[];\n};\n\nexport type UiGraphActionComponent = Extract<UiGraphComponent, { type: 'button' | 'chat' }>;\n\nexport function hasValidUiGraphComponentIds(uiGraph: UiGraph): boolean {\n const componentIds = new Set<string>();\n\n for (const component of uiGraph.components) {\n const componentId = typeof component.id === 'string' ? component.id : '';\n if (!componentId.trim() || componentIds.has(componentId)) {\n return false;\n }\n\n componentIds.add(componentId);\n }\n\n return true;\n}\n\n/**\n * Returns an immutable component-ID repair for legacy or externally assembled\n * UI graphs. Full untrusted-data validation belongs to normalizeUiGraph().\n */\nexport function normalizeUiGraphComponentIds(uiGraph: UiGraph): UiGraph {\n if (hasValidUiGraphComponentIds(uiGraph)) {\n return uiGraph;\n }\n\n const reservedIds = new Set(\n uiGraph.components\n .map((component) => (typeof component.id === 'string' ? component.id : ''))\n .filter((componentId) => Boolean(componentId.trim())),\n );\n const usedIds = new Set<string>();\n const graphId = typeof uiGraph.id === 'string' && uiGraph.id.trim() ? uiGraph.id : 'ui-graph';\n const components = uiGraph.components.map((component, index) => {\n const componentId = typeof component.id === 'string' ? component.id : '';\n if (componentId.trim() && !usedIds.has(componentId)) {\n usedIds.add(componentId);\n return component;\n }\n\n const repairedId = getRepairedUiGraphComponentId(graphId, index, reservedIds, usedIds);\n usedIds.add(repairedId);\n return { ...component, id: repairedId as UiComponentId };\n });\n\n return { ...uiGraph, components };\n}\n\nfunction getRepairedUiGraphComponentId(\n graphId: string,\n componentIndex: number,\n reservedIds: ReadonlySet<string>,\n usedIds: ReadonlySet<string>,\n): string {\n const baseId = `${graphId}-component-${componentIndex + 1}`;\n let repairedId = baseId;\n let suffix = 2;\n\n while (reservedIds.has(repairedId) || usedIds.has(repairedId)) {\n repairedId = `${baseId}-${suffix}`;\n suffix += 1;\n }\n\n return repairedId;\n}\n\nexport function createDefaultUiGraph(options: { graphId?: GraphId; name?: string } = {}): UiGraph {\n const promptStateKey = 'input';\n const resultStateKey = 'result';\n\n return {\n id: newId<UiGraphId>(),\n name: options.name ?? 'Untitled web app',\n components: [\n {\n id: newId<UiComponentId>(),\n type: 'markdown',\n markdown: '## New Rivet web app\\n\\nEnter a value and run a graph.',\n },\n {\n id: newId<UiComponentId>(),\n type: 'textarea',\n label: 'Input',\n stateKey: promptStateKey,\n placeholder: 'Type something...',\n },\n {\n id: newId<UiComponentId>(),\n type: 'button',\n label: 'Run graph',\n action: {\n type: 'runGraph',\n graphId: options.graphId,\n inputMappings: [{ inputKey: 'input', stateKey: promptStateKey }],\n outputs: [{ stateKey: resultStateKey }],\n },\n },\n {\n id: newId<UiComponentId>(),\n type: 'output',\n label: 'Result',\n stateKey: resultStateKey,\n renderAs: 'json',\n },\n ],\n };\n}\n\nexport function getUiGraphInitialState(uiGraph: UiGraph): Record<string, unknown> {\n const state: Record<string, unknown> = {};\n\n for (const component of uiGraph.components) {\n if (component.type === 'input' || component.type === 'textarea') {\n state[component.stateKey] = component.defaultValue ?? '';\n } else if (component.type === 'chat') {\n state[getUiGraphChatDraftStateKey(component.id)] = '';\n state[getUiGraphChatMessagesStateKey(component.id)] = [];\n }\n }\n\n return state;\n}\n\nexport function getUiGraphActionComponent(\n uiGraph: UiGraph,\n componentId: UiComponentId,\n): UiGraphActionComponent | undefined {\n return uiGraph.components.find(\n (component): component is UiGraphActionComponent =>\n component.id === componentId && (component.type === 'button' || component.type === 'chat'),\n );\n}\n\nexport function getUiGraphChatDraftStateKey(componentId: UiComponentId): string {\n return `__rivet_chat_${componentId}_draft`;\n}\n\nexport function getUiGraphChatMessagesStateKey(componentId: UiComponentId): string {\n return `__rivet_chat_${componentId}_messages`;\n}\n\nexport function getUiGraphChatMessages(\n componentId: UiComponentId,\n state: Readonly<Record<string, unknown>>,\n): UiGraphChatMessage[] {\n const messages = state[getUiGraphChatMessagesStateKey(componentId)];\n return Array.isArray(messages) ? messages.filter(isUiGraphChatMessage) : [];\n}\n\nexport function createUiGraphChatSubmissionStatePatch(\n componentId: UiComponentId,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> | undefined {\n const draftStateKey = getUiGraphChatDraftStateKey(componentId);\n const content = `${state[draftStateKey] ?? ''}`.trim();\n if (!content) {\n return undefined;\n }\n\n return {\n [draftStateKey]: '',\n [getUiGraphChatMessagesStateKey(componentId)]: [\n ...getUiGraphChatMessages(componentId, state),\n { role: 'user', content } satisfies UiGraphChatMessage,\n ],\n };\n}\n\nexport function getUiGraphComponentActionState(\n component: UiGraphActionComponent,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n if (component.type === 'button') {\n return getUiGraphActionState(component.action, state);\n }\n\n const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);\n return {\n ...getUiGraphActionState(component.action, state),\n [messagesStateKey]: getUiGraphChatMessages(component.id, state),\n };\n}\n\nexport function resolveUiGraphComponentActionInputs(\n component: UiGraphActionComponent,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n if (component.type === 'button') {\n return resolveUiGraphActionInputs(component.action, state);\n }\n\n const messages = getUiGraphChatMessages(component.id, state);\n const latestMessage = messages[messages.length - 1];\n const latestUserMessage = latestMessage?.role === 'user' ? latestMessage : undefined;\n const historyMessages = latestUserMessage ? messages.slice(0, -1) : messages;\n const inputs = resolveUiGraphActionInputs(component.action, state);\n if (component.action.userInputId) {\n inputs[component.action.userInputId] = latestUserMessage?.content ?? '';\n }\n if (component.action.historyInputId) {\n inputs[component.action.historyInputId] = {\n type: 'chat-message[]',\n value: historyMessages.map(toRivetChatMessage),\n } satisfies DataValue;\n }\n return inputs;\n}\n\nexport function resolveUiGraphComponentActionOutputStatePatch(\n component: UiGraphActionComponent,\n outputs: UiGraphOutputs,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n if (component.type === 'button') {\n return resolveUiGraphActionOutputStatePatch(component.action, outputs);\n }\n\n const outputId = component.action.responseOutputId;\n if (!outputId || !Object.prototype.hasOwnProperty.call(outputs, outputId)) {\n throw new Error(\n outputId\n ? `Graph output \"${outputId}\" was not returned by the target graph.`\n : 'The Chat component has no response graph output.',\n );\n }\n\n const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);\n return {\n [messagesStateKey]: [\n ...getUiGraphChatMessages(component.id, state),\n { role: 'assistant', content: getUiGraphChatResponseText(outputs[outputId]!) } satisfies UiGraphChatMessage,\n ],\n };\n}\n\nexport function getUiGraphComponentActionOutputStateKeys(component: UiGraphActionComponent): string[] {\n return component.type === 'button'\n ? getUiGraphActionOutputBindings(component.action)\n .map((binding) => binding.stateKey.trim())\n .filter(Boolean)\n : [getUiGraphChatMessagesStateKey(component.id)];\n}\n\nexport function resolveUiGraphActionInputs(\n action: UiGraphRunGraphAction,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n const inputs: Record<string, unknown> = {};\n\n if (action.inputMappings) {\n for (const binding of action.inputMappings) {\n if (binding.inputKey) {\n inputs[binding.inputKey] = state[binding.stateKey];\n }\n }\n\n return inputs;\n }\n\n for (const [inputId, binding] of Object.entries(action.inputs ?? {})) {\n inputs[inputId] = binding.type === 'state' ? state[binding.key] : binding.value;\n }\n\n return inputs;\n}\n\n/**\n * Selects the UI state that a button action is explicitly allowed to send.\n * Outputs and unrelated form fields stay local to the rendered web app.\n */\nexport function getUiGraphActionState(\n action: UiGraphRunGraphAction,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n return Object.fromEntries(\n [...new Set(getUiGraphActionInputBindings(action).map((binding) => binding.stateKey))]\n .filter(Boolean)\n .filter((stateKey) => Object.prototype.hasOwnProperty.call(state, stateKey))\n .map((stateKey) => [stateKey, state[stateKey]]),\n );\n}\n\nexport function resolveUiGraphActionOutputStateValue(action: UiGraphRunGraphAction, outputs: UiGraphOutputs): unknown {\n if (!action.outputKey) {\n return outputs;\n }\n\n if (!Object.prototype.hasOwnProperty.call(outputs, action.outputKey)) {\n throw new Error(`Graph output \"${action.outputKey}\" was not returned by the target graph.`);\n }\n\n return outputs[action.outputKey]?.value;\n}\n\nexport function resolveUiGraphActionOutputStatePatch(\n action: UiGraphRunGraphAction,\n outputs: UiGraphOutputs,\n): Record<string, unknown> {\n const bindings = getUiGraphActionOutputBindings(action);\n const statePatch: Record<string, unknown> = {};\n\n for (const binding of bindings) {\n const stateKey = binding.stateKey.trim();\n if (!stateKey) {\n continue;\n }\n\n statePatch[stateKey] = resolveUiGraphOutputBindingValue(binding, outputs);\n }\n\n return statePatch;\n}\n\nexport function getUiGraphActionOutputBindings(action: UiGraphRunGraphAction): UiGraphOutputBinding[] {\n if (action.outputs) {\n return action.outputs;\n }\n\n return action.outputStateKey ? [{ outputKey: action.outputKey, stateKey: action.outputStateKey }] : [];\n}\n\nexport function getUiGraphActionInputBindings(action: UiGraphRunGraphAction): UiGraphInputBinding[] {\n if (action.inputMappings) {\n return action.inputMappings;\n }\n\n return Object.entries(action.inputs ?? {}).map(([inputKey, binding]) => ({\n inputKey,\n stateKey: binding.type === 'state' ? binding.key : '',\n }));\n}\n\nfunction resolveUiGraphOutputBindingValue(binding: UiGraphOutputBinding, outputs: UiGraphOutputs): unknown {\n if (!binding.outputKey) {\n return outputs;\n }\n\n if (!Object.prototype.hasOwnProperty.call(outputs, binding.outputKey)) {\n throw new Error(`Graph output \"${binding.outputKey}\" was not returned by the target graph.`);\n }\n\n return outputs[binding.outputKey]?.value;\n}\n\nfunction isUiGraphChatMessage(value: unknown): value is UiGraphChatMessage {\n return (\n value != null &&\n typeof value === 'object' &&\n ((value as UiGraphChatMessage).role === 'user' || (value as UiGraphChatMessage).role === 'assistant') &&\n typeof (value as UiGraphChatMessage).content === 'string'\n );\n}\n\nfunction toRivetChatMessage(message: UiGraphChatMessage): ChatMessage {\n return message.role === 'user'\n ? { type: 'user', message: message.content }\n : {\n type: 'assistant',\n message: message.content,\n function_call: undefined,\n function_calls: undefined,\n };\n}\n\nfunction getUiGraphChatResponseText(output: DataValue): string {\n if (output.type === 'chat-message') {\n const message = output.value.message;\n if (typeof message === 'string') {\n return message;\n }\n return (Array.isArray(message) ? message : [message])\n .flatMap((part) => (typeof part === 'string' ? [part] : []))\n .join('\\n');\n }\n\n if (typeof output.value === 'string') {\n return output.value;\n }\n if (output.value == null) {\n return '';\n }\n\n try {\n return JSON.stringify(output.value, null, 2);\n } catch {\n return String(output.value);\n }\n}\n", "export type GraphProgress = Readonly<{\n message?: string;\n percent?: number;\n}>;\n\nconst MAX_PROGRESS_MESSAGE_LENGTH = 500;\n\n/** Normalizes public graph progress before it crosses executor or web-app transports. */\nexport function normalizeGraphProgress(progress: GraphProgress): GraphProgress | undefined {\n const message =\n typeof progress.message === 'string' ? progress.message.trim().slice(0, MAX_PROGRESS_MESSAGE_LENGTH) : '';\n const percent =\n typeof progress.percent === 'number' && Number.isFinite(progress.percent)\n ? Math.min(100, Math.max(0, progress.percent))\n : undefined;\n\n if (!message && percent == null) {\n return undefined;\n }\n\n return {\n ...(message ? { message } : {}),\n ...(percent == null ? {} : { percent }),\n };\n}\n", "import {\n getUiGraphChatDraftStateKey,\n getUiGraphChatMessages,\n getUiGraphComponentActionOutputStateKeys,\n getUiGraphComponentActionState,\n getUiGraphInitialState,\n type UiComponentId,\n type UiGraph,\n type UiGraphActionComponent,\n type UiGraphChatMessage,\n type UiGraphComponent,\n type UiGraphGapSize,\n type UiGraphOutputRenderMode,\n} from './UiGraph.js';\nimport { normalizeGraphProgress, type GraphProgress } from './GraphProgress.js';\n\nexport type UiGraphOutputRenderModel = {\n hasValue: boolean;\n imageErrorMessage?: string;\n imageSource?: string;\n jsonDownloadValue?: string;\n renderedValue: string;\n renderAs: UiGraphOutputRenderMode;\n};\n\nconst IMAGE_DATA_URL_PATTERN = /^data:(image\\/(?:avif|bmp|gif|jpe?g|png|webp));base64,([\\s\\S]+)$/i;\nconst IMAGE_URL_PATTERN = /^(?:https?:\\/\\/|blob:|\\/\\/|\\/|\\.\\.?\\/)/i;\nconst RELATIVE_IMAGE_PATH_PATTERN = /\\.(?:avif|bmp|gif|jpe?g|png|webp)(?:[?#].*)?$/i;\nconst BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;\n\nexport type UiGraphComponentRenderModel =\n | {\n component: Extract<UiGraphComponent, { type: 'text' }>;\n text: string;\n type: 'text';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'markdown' }>;\n markdown: string;\n type: 'markdown';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'gap' }>;\n size: UiGraphGapSize;\n type: 'gap';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'input' | 'textarea' }>;\n label: string;\n type: 'input' | 'textarea';\n value: string;\n }\n | {\n component: Extract<UiGraphComponent, { type: 'button' }>;\n label: string;\n type: 'button';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'chat' }>;\n draft: string;\n messages: UiGraphChatMessage[];\n type: 'chat';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'output' }>;\n label: string;\n output: UiGraphOutputRenderModel;\n type: 'output';\n };\n\nexport type UiGraphActionExecution = Readonly<{\n componentId: UiComponentId;\n id: number;\n}>;\n\nexport type UiGraphActionExecutionController = {\n begin(component: UiGraphActionComponent): UiGraphActionExecution | undefined;\n finish(execution: UiGraphActionExecution): boolean;\n isCurrent(execution: UiGraphActionExecution): boolean;\n isRunning(componentId: UiComponentId): boolean;\n noteStateWrite(stateKey: string): void;\n resolveStatePatch(\n execution: UiGraphActionExecution,\n statePatch: Record<string, unknown> | undefined,\n ): Record<string, unknown> | undefined;\n reset(): void;\n};\n\nexport type UiGraphInteractionChange = 'action' | 'graph' | 'state';\n\nexport type UiGraphInteractionSnapshot = Readonly<{\n actionErrors: Readonly<Record<string, string>>;\n actionProgress: Readonly<Record<string, GraphProgress>>;\n runningComponentIds: ReadonlySet<UiComponentId>;\n state: Readonly<Record<string, unknown>>;\n}>;\n\nexport type UiGraphActionRunContext = Readonly<{\n abortOtherActions(): void;\n componentId: UiComponentId;\n reportProgress(progress: GraphProgress): void;\n signal: AbortSignal;\n state: Record<string, unknown>;\n}>;\n\nexport type UiGraphActionRunResult = {\n statePatch?: Record<string, unknown>;\n};\n\nexport type UiGraphActionRunner = (context: UiGraphActionRunContext) => Promise<UiGraphActionRunResult>;\n\nexport type UiGraphInteractionController = {\n abortActions(): void;\n cancelAction(componentId: UiComponentId): void;\n detachActions(): void;\n getSnapshot(): UiGraphInteractionSnapshot;\n runAction(component: UiGraphActionComponent, runner: UiGraphActionRunner): Promise<void>;\n setUiGraph(uiGraph: UiGraph): void;\n subscribe(listener: (change: UiGraphInteractionChange) => void): () => void;\n updateState(stateKey: string, value: unknown): void;\n updateStatePatch(statePatch: Record<string, unknown>): void;\n};\n\nexport type UiGraphInteractionControllerOptions = {\n initialState?: Record<string, unknown>;\n};\n\ntype ActiveUiGraphAction = Readonly<{\n abortController: AbortController;\n execution: UiGraphActionExecution;\n}>;\n\n/**\n * Coordinates independent web-app actions without allowing older completions to\n * clear newer loading states or overwrite newer writes to the same UI state key.\n */\nexport function createUiGraphActionExecutionController(): UiGraphActionExecutionController {\n let nextVersion = 0;\n const activeExecutionByComponent = new Map<UiComponentId, number>();\n const latestWriterByStateKey = new Map<string, number>();\n\n return {\n begin(component) {\n if (activeExecutionByComponent.has(component.id)) {\n return undefined;\n }\n\n const execution = { componentId: component.id, id: ++nextVersion };\n activeExecutionByComponent.set(component.id, execution.id);\n\n for (const stateKey of getUiGraphComponentActionOutputStateKeys(component)) {\n latestWriterByStateKey.set(stateKey, execution.id);\n }\n\n return execution;\n },\n finish(execution) {\n if (activeExecutionByComponent.get(execution.componentId) !== execution.id) {\n return false;\n }\n\n activeExecutionByComponent.delete(execution.componentId);\n return true;\n },\n isCurrent(execution) {\n return activeExecutionByComponent.get(execution.componentId) === execution.id;\n },\n isRunning(componentId) {\n return activeExecutionByComponent.has(componentId);\n },\n noteStateWrite(stateKey) {\n const normalizedStateKey = stateKey.trim();\n if (normalizedStateKey) {\n latestWriterByStateKey.set(normalizedStateKey, ++nextVersion);\n }\n },\n resolveStatePatch(execution, statePatch) {\n if (!statePatch) {\n return undefined;\n }\n\n const applicableEntries = Object.entries(statePatch).filter(\n ([stateKey]) => latestWriterByStateKey.get(stateKey) === execution.id,\n );\n return applicableEntries.length > 0 ? Object.fromEntries(applicableEntries) : undefined;\n },\n reset() {\n activeExecutionByComponent.clear();\n latestWriterByStateKey.clear();\n },\n };\n}\n\n/**\n * Owns mutable web-app interaction state for every renderer. React and direct\n * DOM hosts subscribe to this controller instead of reimplementing action\n * cancellation, loading/error state, and stale state-patch protection.\n */\nexport function createUiGraphInteractionController(\n initialUiGraph: UiGraph,\n options: UiGraphInteractionControllerOptions = {},\n): UiGraphInteractionController {\n let uiGraphId = initialUiGraph.id;\n let state = options.initialState ? { ...options.initialState } : getUiGraphInitialState(initialUiGraph);\n let actionErrors: Record<string, string> = {};\n let actionProgress: Record<string, GraphProgress> = {};\n let snapshot: UiGraphInteractionSnapshot;\n const actionController = createUiGraphActionExecutionController();\n const activeActions = new Map<number, ActiveUiGraphAction>();\n const listeners = new Set<(change: UiGraphInteractionChange) => void>();\n\n const updateSnapshot = (): void => {\n snapshot = {\n actionErrors,\n actionProgress,\n runningComponentIds: new Set([...activeActions.values()].map(({ execution }) => execution.componentId)),\n state,\n };\n };\n const publish = (change: UiGraphInteractionChange): void => {\n updateSnapshot();\n for (const listener of listeners) {\n listener(change);\n }\n };\n const abortMatchingActions = (\n predicate: (activeAction: ActiveUiGraphAction, executionId: number) => boolean,\n notify: boolean,\n ): boolean => {\n let changed = false;\n for (const [executionId, activeAction] of activeActions) {\n if (!predicate(activeAction, executionId)) {\n continue;\n }\n activeAction.abortController.abort();\n activeActions.delete(executionId);\n actionController.finish(activeAction.execution);\n changed = true;\n }\n if (changed && notify) {\n publish('action');\n }\n return changed;\n };\n const abortAllActions = (notify: boolean): void => {\n let changed = abortMatchingActions(() => true, false);\n actionController.reset();\n if (Object.keys(actionProgress).length > 0) {\n actionProgress = {};\n changed = true;\n }\n if (changed && notify) {\n publish('action');\n }\n };\n const removeActionPresentation = (componentId: UiComponentId): void => {\n if (Object.prototype.hasOwnProperty.call(actionErrors, componentId)) {\n actionErrors = { ...actionErrors };\n delete actionErrors[componentId];\n }\n if (Object.prototype.hasOwnProperty.call(actionProgress, componentId)) {\n actionProgress = { ...actionProgress };\n delete actionProgress[componentId];\n }\n };\n\n updateSnapshot();\n\n return {\n abortActions() {\n abortAllActions(true);\n },\n cancelAction(componentId) {\n if (abortMatchingActions(({ execution }) => execution.componentId === componentId, false)) {\n removeActionPresentation(componentId);\n publish('action');\n }\n },\n detachActions() {\n activeActions.clear();\n actionController.reset();\n actionProgress = {};\n updateSnapshot();\n },\n getSnapshot() {\n return snapshot;\n },\n async runAction(component, runner) {\n const execution = actionController.begin(component);\n if (!execution) {\n return;\n }\n\n const abortController = new AbortController();\n activeActions.set(execution.id, { abortController, execution });\n removeActionPresentation(component.id);\n publish('action');\n\n try {\n const result = await runner({\n abortOtherActions: () =>\n abortMatchingActions((_activeAction, executionId) => executionId !== execution.id, true),\n componentId: component.id,\n reportProgress: (progress) => {\n if (!actionController.isCurrent(execution)) return;\n const normalized = normalizeGraphProgress(progress);\n if (!normalized) return;\n actionProgress = { ...actionProgress, [component.id]: normalized };\n publish('action');\n },\n signal: abortController.signal,\n state: getUiGraphComponentActionState(component, state),\n });\n if (!actionController.isCurrent(execution)) {\n return;\n }\n\n const statePatch = actionController.resolveStatePatch(execution, result.statePatch);\n if (statePatch) {\n state = applyUiGraphStatePatch(state, statePatch);\n }\n } catch (error) {\n if (!abortController.signal.aborted && actionController.isCurrent(execution)) {\n actionErrors = {\n ...actionErrors,\n [component.id]: error instanceof Error ? error.message : String(error),\n };\n }\n } finally {\n if (activeActions.delete(execution.id)) {\n actionController.finish(execution);\n if (Object.prototype.hasOwnProperty.call(actionProgress, component.id)) {\n actionProgress = { ...actionProgress };\n delete actionProgress[component.id];\n }\n publish('action');\n }\n }\n },\n setUiGraph(nextUiGraph) {\n if (nextUiGraph.id !== uiGraphId) {\n abortAllActions(false);\n uiGraphId = nextUiGraph.id;\n state = getUiGraphInitialState(nextUiGraph);\n actionErrors = {};\n actionProgress = {};\n publish('graph');\n return;\n }\n\n const actionComponentIds = new Set(\n nextUiGraph.components\n .filter((component) => component.type === 'button' || component.type === 'chat')\n .map((component) => component.id),\n );\n let changed = abortMatchingActions(({ execution }) => !actionComponentIds.has(execution.componentId), false);\n const remainingErrors = Object.fromEntries(\n Object.entries(actionErrors).filter(([componentId]) => actionComponentIds.has(componentId as UiComponentId)),\n );\n const remainingProgress = Object.fromEntries(\n Object.entries(actionProgress).filter(([componentId]) => actionComponentIds.has(componentId as UiComponentId)),\n );\n if (Object.keys(remainingErrors).length !== Object.keys(actionErrors).length) {\n actionErrors = remainingErrors;\n changed = true;\n }\n if (Object.keys(remainingProgress).length !== Object.keys(actionProgress).length) {\n actionProgress = remainingProgress;\n changed = true;\n }\n if (changed) {\n publish('graph');\n }\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n updateState(stateKey, value) {\n actionController.noteStateWrite(stateKey);\n state = { ...state, [stateKey]: value };\n publish('state');\n },\n updateStatePatch(statePatch) {\n for (const stateKey of Object.keys(statePatch)) {\n actionController.noteStateWrite(stateKey);\n }\n state = applyUiGraphStatePatch(state, statePatch);\n publish('state');\n },\n };\n}\n\nexport function getUiGraphComponentRenderModel(\n component: UiGraphComponent,\n state: Readonly<Record<string, unknown>>,\n): UiGraphComponentRenderModel {\n switch (component.type) {\n case 'text':\n return { component, text: component.text, type: 'text' };\n case 'markdown':\n return { component, markdown: component.markdown, type: 'markdown' };\n case 'gap':\n return { component, size: component.size, type: 'gap' };\n case 'input':\n case 'textarea':\n return {\n component,\n label: getUiGraphComponentLabel(component),\n type: component.type,\n value: `${state[component.stateKey] ?? component.defaultValue ?? ''}`,\n };\n case 'button':\n return { component, label: component.label, type: 'button' };\n case 'chat':\n return {\n component,\n draft: `${state[getUiGraphChatDraftStateKey(component.id)] ?? ''}`,\n messages: getUiGraphChatMessages(component.id, state),\n type: 'chat',\n };\n case 'output':\n return {\n component,\n label: getUiGraphComponentLabel(component),\n output: getUiGraphOutputRenderModel(state, component.stateKey, component.renderAs ?? 'text'),\n type: 'output',\n };\n }\n}\n\nexport function getUiGraphComponentLabel(\n component: Extract<UiGraphComponent, { type: 'input' | 'textarea' | 'output' }>,\n): string {\n return component.label || component.stateKey;\n}\n\nexport function getUiGraphOutputRenderModel(\n state: Readonly<Record<string, unknown>>,\n stateKey: string,\n renderAs: UiGraphOutputRenderMode,\n): UiGraphOutputRenderModel {\n const value = state[stateKey];\n const hasValue = hasUiGraphStateValue(state, stateKey);\n const renderedValue = renderUiGraphOutputValue(value, renderAs);\n const imageSource = hasValue && renderAs === 'image' ? getUiGraphImageSource(value) : undefined;\n const imageErrorMessage =\n hasValue && renderAs === 'image' && !imageSource ? 'Expected an image URL or base64 image.' : undefined;\n\n return {\n hasValue,\n ...(imageErrorMessage ? { imageErrorMessage } : {}),\n ...(imageSource ? { imageSource } : {}),\n ...(hasValue && renderAs === 'json' ? { jsonDownloadValue: stringifyUiGraphValue(value) } : {}),\n renderedValue,\n renderAs,\n };\n}\n\nexport function hasUiGraphStateValue(state: Readonly<Record<string, unknown>>, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(state, key) && state[key] !== undefined;\n}\n\nexport function renderUiGraphOutputValue(value: unknown, renderAs: UiGraphOutputRenderMode): string {\n if (renderAs === 'json') {\n return stringifyUiGraphValue(value) ?? '';\n }\n\n return typeof value === 'string' ? value : value == null ? '' : stringifyUiGraphValue(value) ?? '';\n}\n\nexport function getUiGraphImageSource(value: unknown): string | undefined {\n if (typeof value !== 'string') {\n return undefined;\n }\n\n const source = value.trim();\n if (!source) {\n return undefined;\n }\n\n const dataUrl = IMAGE_DATA_URL_PATTERN.exec(source);\n if (dataUrl) {\n const base64 = normalizeBase64(dataUrl[2]!);\n return base64 ? `data:${normalizeImageMediaType(dataUrl[1]!)};base64,${base64}` : undefined;\n }\n\n const base64 = normalizeBase64(source);\n const inferredMediaType = base64 ? inferBase64ImageMediaType(base64) : undefined;\n if (base64 && inferredMediaType) {\n return `data:${inferredMediaType};base64,${base64}`;\n }\n\n if (!IMAGE_URL_PATTERN.test(source) && !RELATIVE_IMAGE_PATH_PATTERN.test(source)) {\n return undefined;\n }\n\n try {\n const protocol = new URL(source, 'https://rivet.invalid').protocol;\n return protocol === 'http:' || protocol === 'https:' || protocol === 'blob:' ? source : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeBase64(value: string): string | undefined {\n const compact = value.replace(/\\s/g, '');\n return compact.length >= 8 && compact.length % 4 !== 1 && BASE64_PATTERN.test(compact) ? compact : undefined;\n}\n\nfunction normalizeImageMediaType(mediaType: string): string {\n const normalized = mediaType.toLowerCase();\n return normalized === 'image/jpg' ? 'image/jpeg' : normalized;\n}\n\nfunction inferBase64ImageMediaType(value: string): string | undefined {\n if (value.startsWith('iVBORw0KGgo')) return 'image/png';\n if (value.startsWith('/9j/')) return 'image/jpeg';\n if (value.startsWith('R0lGODdh') || value.startsWith('R0lGODlh')) return 'image/gif';\n return undefined;\n}\n\nexport function stringifyUiGraphValue(value: unknown): string | undefined {\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return '[Unserializable value]';\n }\n}\n\nexport function getUiGraphJsonOutputFilename(appName: string, date = new Date()): string {\n const safeName = appName\n .trim()\n .replace(/[<>:\"/\\\\|?*\\u0000-\\u001F]/g, '-')\n .replace(/\\s+/g, ' ')\n .slice(0, 80);\n\n return `${safeName || 'Rivet web app'} ${formatUiGraphDownloadDateTime(date)}.json`;\n}\n\nexport function formatUiGraphDownloadDateTime(date: Date): string {\n const pad = (value: number) => `${value}`.padStart(2, '0');\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}-${pad(\n date.getMinutes(),\n )}-${pad(date.getSeconds())}`;\n}\n\nexport function applyUiGraphStatePatch(\n state: Record<string, unknown>,\n statePatch: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n return statePatch ? { ...state, ...statePatch } : state;\n}\n", "import type { UiComponentId } from './UiGraph.js';\nimport { normalizeGraphProgress, type GraphProgress } from './GraphProgress.js';\n\nexport const RIVET_WEB_APP_ACTION_PROTOCOL_VERSION = 1 as const;\n\nexport type RivetWebAppActionStartMessage = {\n type: 'action.start';\n requestId: string;\n componentId: UiComponentId;\n revisionKey?: string;\n state: Record<string, unknown>;\n};\n\nexport type RivetWebAppActionCancelMessage = {\n type: 'action.cancel';\n runId: string;\n};\n\nexport type RivetWebAppRunResumeMessage = {\n type: 'run.resume';\n runId: string;\n lastSequence: number;\n};\n\nexport type RivetWebAppClientHelloMessage = {\n type: 'client.hello';\n protocolVersion: typeof RIVET_WEB_APP_ACTION_PROTOCOL_VERSION;\n};\n\nexport type RivetWebAppClientMessage =\n | RivetWebAppClientHelloMessage\n | RivetWebAppActionStartMessage\n | RivetWebAppActionCancelMessage\n | RivetWebAppRunResumeMessage;\n\ntype RunEventBase = {\n requestId: string;\n runId: string;\n sequence: number;\n};\n\nexport type RivetWebAppServerMessage =\n | {\n type: 'server.ready';\n protocolVersion: typeof RIVET_WEB_APP_ACTION_PROTOCOL_VERSION;\n }\n | ({ type: 'action.accepted' } & RunEventBase)\n | ({ type: 'action.progress'; progress: GraphProgress } & RunEventBase)\n | ({ type: 'action.completed'; statePatch: Record<string, unknown> } & RunEventBase)\n | ({ type: 'action.failed'; error: string; code?: string } & RunEventBase)\n | ({ type: 'action.cancelled' } & RunEventBase)\n | ({ type: 'action.interrupted'; error: string } & RunEventBase)\n | {\n type: 'action.rejected';\n requestId: string;\n error: string;\n code?: string;\n }\n | {\n type: 'run.rejected';\n runId: string;\n error: string;\n code?: string;\n }\n | {\n type: 'server.draining';\n };\n\nexport type RivetWebAppRunEvent = Exclude<\n RivetWebAppServerMessage,\n { type: 'server.ready' | 'action.rejected' | 'run.rejected' | 'server.draining' }\n>;\n\nexport function parseRivetWebAppClientMessage(value: unknown): RivetWebAppClientMessage | undefined {\n if (!isRecord(value) || typeof value.type !== 'string') return undefined;\n\n switch (value.type) {\n case 'client.hello':\n return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION\n ? { type: value.type, protocolVersion: value.protocolVersion }\n : undefined;\n case 'action.start':\n return isNonEmptyString(value.requestId) &&\n isNonEmptyString(value.componentId) &&\n isRecord(value.state) &&\n (value.revisionKey == null || typeof value.revisionKey === 'string')\n ? {\n type: value.type,\n requestId: value.requestId,\n componentId: value.componentId as UiComponentId,\n state: value.state,\n ...(typeof value.revisionKey === 'string' ? { revisionKey: value.revisionKey } : {}),\n }\n : undefined;\n case 'action.cancel':\n return isNonEmptyString(value.runId) ? { type: value.type, runId: value.runId } : undefined;\n case 'run.resume':\n return isNonEmptyString(value.runId) &&\n typeof value.lastSequence === 'number' &&\n Number.isSafeInteger(value.lastSequence) &&\n value.lastSequence >= 0\n ? { type: value.type, runId: value.runId, lastSequence: value.lastSequence }\n : undefined;\n default:\n return undefined;\n }\n}\n\nexport function parseRivetWebAppServerMessage(value: unknown): RivetWebAppServerMessage | undefined {\n if (!isRecord(value) || typeof value.type !== 'string') return undefined;\n\n if (value.type === 'server.ready') {\n return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION\n ? { type: value.type, protocolVersion: value.protocolVersion }\n : undefined;\n }\n if (value.type === 'server.draining') return { type: value.type };\n if (value.type === 'action.rejected') {\n return isNonEmptyString(value.requestId) && isNonEmptyString(value.error)\n ? {\n type: value.type,\n requestId: value.requestId,\n error: value.error,\n ...(typeof value.code === 'string' ? { code: value.code } : {}),\n }\n : undefined;\n }\n if (value.type === 'run.rejected') {\n return isNonEmptyString(value.runId) && isNonEmptyString(value.error)\n ? {\n type: value.type,\n runId: value.runId,\n error: value.error,\n ...(typeof value.code === 'string' ? { code: value.code } : {}),\n }\n : undefined;\n }\n if (!hasRunEventBase(value)) return undefined;\n\n const base = {\n requestId: value.requestId,\n runId: value.runId,\n sequence: value.sequence,\n };\n switch (value.type) {\n case 'action.accepted':\n case 'action.cancelled':\n return { type: value.type, ...base };\n case 'action.progress': {\n if (!isRecord(value.progress)) return undefined;\n const progress = normalizeGraphProgress({\n message: typeof value.progress.message === 'string' ? value.progress.message : undefined,\n percent: typeof value.progress.percent === 'number' ? value.progress.percent : undefined,\n });\n return progress ? { type: value.type, ...base, progress } : undefined;\n }\n case 'action.completed':\n return isRecord(value.statePatch) ? { type: value.type, ...base, statePatch: value.statePatch } : undefined;\n case 'action.failed':\n return isNonEmptyString(value.error)\n ? {\n type: value.type,\n ...base,\n error: value.error,\n ...(typeof value.code === 'string' ? { code: value.code } : {}),\n }\n : undefined;\n case 'action.interrupted':\n return isNonEmptyString(value.error) ? { type: value.type, ...base, error: value.error } : undefined;\n default:\n return undefined;\n }\n}\n\nexport function isRivetWebAppRunTerminalEvent(event: RivetWebAppRunEvent): boolean {\n return (\n event.type === 'action.completed' ||\n event.type === 'action.failed' ||\n event.type === 'action.cancelled' ||\n event.type === 'action.interrupted'\n );\n}\n\nfunction hasRunEventBase(value: Record<string, unknown>): value is Record<string, unknown> & RunEventBase {\n return (\n isNonEmptyString(value.requestId) &&\n isNonEmptyString(value.runId) &&\n typeof value.sequence === 'number' &&\n Number.isSafeInteger(value.sequence) &&\n value.sequence > 0\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value != null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n", "import { getUiGraphJsonOutputFilename } from './UiGraphRuntimeModel.js';\n\n/** Copies rendered web-app output without requiring the modern Clipboard API. */\nexport async function copyUiGraphText(value: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(value);\n return true;\n } catch {\n // Preview hosts and non-secure origins may not expose the Clipboard API.\n }\n\n const textArea = document.createElement('textarea');\n textArea.className = 'rivet-web-app-clipboard-fallback';\n textArea.value = value;\n try {\n document.body.append(textArea);\n textArea.select();\n return document.execCommand?.('copy') ?? false;\n } catch {\n return false;\n } finally {\n textArea.remove();\n }\n}\n\n/** Downloads the exact JSON string rendered by a web-app output component. */\nexport function downloadUiGraphJsonOutput(value: string, appName: string): void {\n const url = URL.createObjectURL(new Blob([value], { type: 'application/json' }));\n try {\n const link = document.createElement('a');\n link.href = url;\n link.download = getUiGraphJsonOutputFilename(appName);\n document.body.append(link);\n link.click();\n link.remove();\n } finally {\n globalThis.setTimeout(() => URL.revokeObjectURL(url), 0);\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,wBAAuB;;;ACkOhB,SAAS,uBAAuB,SAA2C;AAChF,QAAM,QAAiC,CAAC;AAExC,aAAW,aAAa,QAAQ,YAAY;AAC1C,QAAI,UAAU,SAAS,WAAW,UAAU,SAAS,YAAY;AAC/D,YAAM,UAAU,QAAQ,IAAI,UAAU,gBAAgB;AAAA,IACxD,WAAW,UAAU,SAAS,QAAQ;AACpC,YAAM,4BAA4B,UAAU,EAAE,CAAC,IAAI;A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E,QAAM,MAAM,IAAI,gBAAgB,IAAI,KAAK,CAAC,KAAK,GAAG,EAAE,MAAM,mBAAmB,CAAC,CAAC;AAC/E,MAAI;AACF,UAAM,OAAO,SAAS,cAAc,GAAG;AACvC,SAAK,OAAO;AACZ,SAAK,WAAW,6BAA6B,OAAO;AACpD,aAAS,KAAK,OAAO,IAAI;AACzB,SAAK,MAAM;AACX,SAAK,OAAO;AAAA,EACd,UAAE;AACA,eAAW,WAAW,MAAM,IAAI,gBAAgB,GAAG,GAAG,CAAC;AAAA,EACzD;AACF;",
6
+ "names": ["base64"]
7
+ }
@@ -53,6 +53,9 @@ export function coreCreateProcessor(project, options, internalOptions = {}) {
53
53
  if (options.onPartialOutput) {
54
54
  processor.on('partialOutput', options.onPartialOutput);
55
55
  }
56
+ if (options.onProgress) {
57
+ processor.on('progress', options.onProgress);
58
+ }
56
59
  if (options.onUserInput) {
57
60
  processor.on('userInput', options.onUserInput);
58
61
  }
@@ -60,6 +60,12 @@ export async function* getProcessorEvents(processor, spec) {
60
60
  };
61
61
  }
62
62
  }
63
+ else if (event.type === 'progress' && spec.progress) {
64
+ yield {
65
+ type: 'progress',
66
+ ...event.progress,
67
+ };
68
+ }
63
69
  }
64
70
  }
65
71
  /**
@@ -7,7 +7,12 @@ export * from './model/NodeGraph.js';
7
7
  export * from './model/NodePrefabResolver.js';
8
8
  export { getGraphBoundary } from './model/GraphBoundaryCache.js';
9
9
  export * from './model/UiGraph.js';
10
+ export * from './model/UiGraphNormalization.js';
11
+ export * from './model/UiGraphBindings.js';
10
12
  export * from './model/UiGraphRuntimeModel.js';
13
+ export * from './model/UiGraphWebAppStatus.js';
14
+ export * from './model/UiGraphActionProtocol.js';
15
+ export * from './model/GraphProgress.js';
11
16
  export * from './model/UiGraphRendererStyles.js';
12
17
  export * from './model/MarkdownSanitizationPolicy.js';
13
18
  export * from './model/NodeImpl.js';
@@ -1,4 +1,9 @@
1
- import { getServerHelperMessage, getServerOptions } from './MCPUtils.js';
1
+ import { coerceTypeOptional } from '../../utils/coerceType.js';
2
+ import { getInputOrData } from '../../utils/inputs.js';
3
+ import { interpolate } from '../../utils/interpolation.js';
4
+ import { keys } from '../../utils/typeSafety.js';
5
+ import { MCPError, MCPErrorType } from './MCPProvider.js';
6
+ import { getServerHelperMessage, getServerOptions, loadMCPConfiguration } from './MCPUtils.js';
2
7
  export const getMCPBaseInputs = (data) => {
3
8
  const inputs = [];
4
9
  if (data.useNameInput) {
@@ -25,21 +30,8 @@ export const getMCPBaseInputs = (data) => {
25
30
  }
26
31
  return inputs;
27
32
  };
28
- export const getMCPBaseEditors = async (context, data) => {
29
- const editors = [];
30
- editors.push([
31
- {
32
- type: 'toggle',
33
- label: 'Output Tools',
34
- dataKey: 'useToolsOutput',
35
- helperMessage: 'Toggle on if you want to get a Tools output',
36
- },
37
- {
38
- type: 'toggle',
39
- label: 'Output Prompts',
40
- dataKey: 'usePromptsOutput',
41
- helperMessage: 'Toggle on if you want to get a Prompts output',
42
- },
33
+ export function getMCPClientEditors() {
34
+ return [
43
35
  {
44
36
  type: 'string',
45
37
  label: 'Name',
@@ -63,25 +55,91 @@ export const getMCPBaseEditors = async (context, data) => {
63
55
  { label: 'STDIO', value: 'stdio' },
64
56
  ],
65
57
  },
66
- ]);
58
+ ];
59
+ }
60
+ export async function getMCPServerEditors(context, data, options = {}) {
67
61
  if (data.transportType === 'http') {
68
- editors.push({
69
- type: 'string',
70
- label: 'Server URL',
71
- dataKey: 'serverUrl',
72
- useInputToggleDataKey: 'useServerUrlInput',
73
- helperMessage: 'The endpoint URL for the MCP server to connect',
74
- });
62
+ return [
63
+ {
64
+ type: 'string',
65
+ label: 'Server URL',
66
+ dataKey: 'serverUrl',
67
+ useInputToggleDataKey: 'useServerUrlInput',
68
+ helperMessage: options.httpServerUrlHelperMessage ?? 'The endpoint URL for the MCP server to connect',
69
+ },
70
+ ];
75
71
  }
76
- else if (data.transportType === 'stdio') {
72
+ if (data.transportType === 'stdio') {
77
73
  const serverOptions = await getServerOptions(context);
78
- editors.push({
79
- type: 'dropdown',
80
- label: 'Server ID',
81
- dataKey: 'serverId',
82
- helperMessage: getServerHelperMessage(context, serverOptions.length),
83
- options: serverOptions,
84
- });
74
+ return [
75
+ {
76
+ type: 'dropdown',
77
+ label: 'Server ID',
78
+ dataKey: 'serverId',
79
+ helperMessage: getServerHelperMessage(context, serverOptions.length),
80
+ options: serverOptions,
81
+ },
82
+ ];
85
83
  }
86
- return editors;
87
- };
84
+ return [];
85
+ }
86
+ export function getMCPBaseBody(data, context) {
87
+ const server = data.transportType === 'http'
88
+ ? data.useServerUrlInput
89
+ ? '(Using Server URL Input)'
90
+ : data.serverUrl
91
+ : `Server ID: ${data.serverId || '(None)'}`;
92
+ const parts = [`Name: ${data.name}`, `Version: ${data.version}`, server];
93
+ if (context.executor !== 'nodejs') {
94
+ parts.push('(Requires Node Executor)');
95
+ }
96
+ return parts.join('\n');
97
+ }
98
+ export function requireMCPProvider(context) {
99
+ if (!context.mcpProvider) {
100
+ throw new Error('MCP Provider not found');
101
+ }
102
+ return context.mcpProvider;
103
+ }
104
+ export async function resolveMCPServer(data, inputs, context) {
105
+ const clientConfig = {
106
+ name: getInputOrData(data, inputs, 'name', 'string'),
107
+ version: getInputOrData(data, inputs, 'version', 'string'),
108
+ };
109
+ const transportType = getInputOrData(data, inputs, 'transportType', 'string');
110
+ if (transportType === 'http') {
111
+ const serverUrl = getInputOrData(data, inputs, 'serverUrl', 'string');
112
+ if (!serverUrl || serverUrl === '') {
113
+ throw new MCPError(MCPErrorType.SERVER_NOT_FOUND, 'No server URL was provided');
114
+ }
115
+ if (!serverUrl.includes('/mcp')) {
116
+ throw new MCPError(MCPErrorType.SERVER_COMMUNICATION_FAILED, 'Include /mcp in your server URL. For example: http://localhost:8080/mcp');
117
+ }
118
+ return { transportType, clientConfig, serverUrl };
119
+ }
120
+ if (transportType === 'stdio') {
121
+ const serverId = data.serverId ?? '';
122
+ const mcpConfig = await loadMCPConfiguration(context);
123
+ if (!mcpConfig.mcpServers[serverId]) {
124
+ throw new MCPError(MCPErrorType.SERVER_NOT_FOUND, `Server ${serverId} not found in MCP config`);
125
+ }
126
+ return {
127
+ transportType,
128
+ clientConfig,
129
+ serverConfig: {
130
+ config: mcpConfig.mcpServers[serverId],
131
+ serverId,
132
+ },
133
+ };
134
+ }
135
+ return undefined;
136
+ }
137
+ export function interpolateMCPArgumentTemplate(template, inputs) {
138
+ const values = {};
139
+ for (const key of keys(inputs)) {
140
+ if (key.startsWith('input')) {
141
+ values[key.slice('input-'.length)] = coerceTypeOptional(inputs[key], 'string') ?? '';
142
+ }
143
+ }
144
+ return interpolate(template, values);
145
+ }
@@ -8,7 +8,7 @@ import { nanoid } from 'nanoid/non-secure';
8
8
  import { coerceTypeOptional } from '../utils/coerceType.js';
9
9
  import { getPluginConfig } from '../utils/index.js';
10
10
  import { isGraphExecutionPlan, preprocessGraphState, toReusableGraphExecutionPlan, } from './GraphPreprocessor.js';
11
- import { getGraphBoundary, } from './GraphBoundaryCache.js';
11
+ import { getGraphBoundary } from './GraphBoundaryCache.js';
12
12
  import { applyFrozenGraphBoundaryEffects, ensureGraphCostOutput } from './GraphBoundaryEffects.js';
13
13
  import { replayExecutionRecording } from './RecordingPlayer.js';
14
14
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
@@ -19,6 +19,8 @@ import { wireSubprocessorEvents, wireSubprocessorLifecycle } from './Subprocesso
19
19
  import { createGraphAbortError, createGraphAbortErrorFromSignal, createGraphAbortReason, getAbortSignalReason, getGraphAbortReasonFromError, getGraphAbortReasonFromSignal, isAbortLikeError, isRaceLoserGraphAbortReason, isSuccessfulNonRaceGraphAbortReason, RACE_LOSER_EXCLUSION_REASON, SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON, } from './GraphAbortReasons.js';
20
20
  import { emitDetached } from '../utils/emitDetached.js';
21
21
  import { GraphRunLifecycle } from './GraphRunLifecycle.js';
22
+ import { normalizeGraphProgress } from './GraphProgress.js';
23
+ import { RIVET_WEB_APP_STATUS_FUNCTION_NAME, rivetWebAppStatusExternalFunction } from './UiGraphWebAppStatus.js';
22
24
  import { createExcludedNodeOutputs, getControlFlowExclusionDecision, getMissingRequiredInputExclusion, } from './NodeExclusionPolicy.js';
23
25
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
24
26
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
@@ -242,6 +244,7 @@ export class GraphProcessor {
242
244
  this.#captureNodeTimings = options?.captureNodeTimings ?? false;
243
245
  this.#emitter.bindMethods(this, ['on', 'off', 'once', 'onAny', 'offAny']);
244
246
  this.setExternalFunction('echo', async (value) => ({ type: 'any', value }));
247
+ this.setExternalFunction(RIVET_WEB_APP_STATUS_FUNCTION_NAME, rivetWebAppStatusExternalFunction);
245
248
  this.#emitter.on('globalSet', ({ id, value }) => {
246
249
  emitDetached(this.#emitter, `globalSet:${id}`, value);
247
250
  });
@@ -539,9 +542,7 @@ export class GraphProcessor {
539
542
  this.#erroredNodes = new Map();
540
543
  this.#currentlyProcessing = new Set();
541
544
  const seededExecutionPlan = this.#seededExecutionPlanForNextRun();
542
- this.#remainingNodes = new Set(seededExecutionPlan
543
- ? seededExecutionPlan.nodeIds
544
- : this.#graph.nodes.map((node) => node.id));
545
+ this.#remainingNodes = new Set(seededExecutionPlan ? seededExecutionPlan.nodeIds : this.#graph.nodes.map((node) => node.id));
545
546
  this.#pendingUserInputs = {};
546
547
  this.#processingQueue = new PQueue({ concurrency: this.#concurrency.nodeConcurrency });
547
548
  this.#graphOutputs = {};
@@ -1441,6 +1442,12 @@ export class GraphProcessor {
1441
1442
  },
1442
1443
  processId,
1443
1444
  requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId),
1445
+ reportProgress: (progress) => {
1446
+ const normalized = normalizeGraphProgress(progress);
1447
+ if (normalized) {
1448
+ emitDetached(this.#emitter, 'progress', this.#withExecution({ node, processId, progress: normalized }));
1449
+ }
1450
+ },
1444
1451
  setGlobal: (id, value) => {
1445
1452
  this.#globals.set(id, value);
1446
1453
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id, value, processId }));
@@ -0,0 +1,15 @@
1
+ const MAX_PROGRESS_MESSAGE_LENGTH = 500;
2
+ /** Normalizes public graph progress before it crosses executor or web-app transports. */
3
+ export function normalizeGraphProgress(progress) {
4
+ const message = typeof progress.message === 'string' ? progress.message.trim().slice(0, MAX_PROGRESS_MESSAGE_LENGTH) : '';
5
+ const percent = typeof progress.percent === 'number' && Number.isFinite(progress.percent)
6
+ ? Math.min(100, Math.max(0, progress.percent))
7
+ : undefined;
8
+ if (!message && percent == null) {
9
+ return undefined;
10
+ }
11
+ return {
12
+ ...(message ? { message } : {}),
13
+ ...(percent == null ? {} : { percent }),
14
+ };
15
+ }
@@ -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,6 @@
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'];
2
4
  export function hasValidUiGraphComponentIds(uiGraph) {
3
5
  const componentIds = new Set();
4
6
  for (const component of uiGraph.components) {
@@ -11,9 +13,8 @@ export function hasValidUiGraphComponentIds(uiGraph) {
11
13
  return true;
12
14
  }
13
15
  /**
14
- * Returns an immutable repair for legacy or externally assembled UI graphs.
15
- * Repaired IDs are deterministic so separately rendered HTML and action calls agree
16
- * without mutating a host-owned project snapshot.
16
+ * Returns an immutable component-ID repair for legacy or externally assembled
17
+ * UI graphs. Full untrusted-data validation belongs to normalizeUiGraph().
17
18
  */
18
19
  export function normalizeUiGraphComponentIds(uiGraph) {
19
20
  if (hasValidUiGraphComponentIds(uiGraph)) {
@@ -92,11 +93,94 @@ export function getUiGraphInitialState(uiGraph) {
92
93
  if (component.type === 'input' || component.type === 'textarea') {
93
94
  state[component.stateKey] = component.defaultValue ?? '';
94
95
  }
96
+ else if (component.type === 'chat') {
97
+ state[getUiGraphChatDraftStateKey(component.id)] = '';
98
+ state[getUiGraphChatMessagesStateKey(component.id)] = [];
99
+ }
95
100
  }
96
101
  return state;
97
102
  }
98
103
  export function getUiGraphActionComponent(uiGraph, componentId) {
99
- 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)];
100
184
  }
101
185
  export function resolveUiGraphActionInputs(action, state) {
102
186
  const inputs = {};
@@ -168,3 +252,42 @@ function resolveUiGraphOutputBindingValue(binding, outputs) {
168
252
  }
169
253
  return outputs[binding.outputKey]?.value;
170
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
+ }