@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,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,aAA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S,KAAK,OAAO,QAAQ;AAC7B,aAAS,OAAO;AAChB,aAAO,cAAS,gBAAT,kCAAuB,YAAW;AAAA,EAC3C,QAAQ;AACN,WAAO;AAAA,EACT,UAAE;AACA,aAAS,OAAO;AAAA,EAClB;AACF;AAGO,SAAS,0BAA0B,OAAe,SAAuB;AAC9E,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
  }
@@ -1,7 +1,12 @@
1
1
  import { DEFAULT_CHAT_NODE_TIMEOUT } from '../utils/defaults.js';
2
+ function definedRuntimeSettings(settings) {
3
+ return Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== undefined && value !== ''));
4
+ }
2
5
  export function resolveProcessSettings(settings = {}, fallbacks = {}) {
3
6
  const openAiApiKey = settings.openAiApiKey || settings.openAiKey || fallbacks.openAiApiKey || fallbacks.openAiKey || '';
4
7
  return {
8
+ ...fallbacks,
9
+ ...definedRuntimeSettings(settings),
5
10
  openAiApiKey,
6
11
  openAiKey: openAiApiKey,
7
12
  anthropicApiKey: settings.anthropicApiKey || fallbacks.anthropicApiKey || '',
@@ -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,14 @@ 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';
12
+ export * from './model/UiGraphRuntimeModel.js';
13
+ export * from './model/UiGraphWebAppStatus.js';
14
+ export * from './model/UiGraphActionProtocol.js';
15
+ export * from './model/GraphProgress.js';
10
16
  export * from './model/UiGraphRendererStyles.js';
17
+ export * from './model/MarkdownSanitizationPolicy.js';
11
18
  export * from './model/NodeImpl.js';
12
19
  export * from './model/NodeDefinition.js';
13
20
  export * from './model/Nodes.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';
@@ -18,6 +18,9 @@ import { getInputNodesTo, getMissingRequiredInputs, getOutputNodesFrom, getStart
18
18
  import { wireSubprocessorEvents, wireSubprocessorLifecycle } from './SubprocessorBridge.js';
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
+ import { GraphRunLifecycle } from './GraphRunLifecycle.js';
22
+ import { normalizeGraphProgress } from './GraphProgress.js';
23
+ import { RIVET_WEB_APP_STATUS_FUNCTION_NAME, rivetWebAppStatusExternalFunction } from './UiGraphWebAppStatus.js';
21
24
  import { createExcludedNodeOutputs, getControlFlowExclusionDecision, getMissingRequiredInputExclusion, } from './NodeExclusionPolicy.js';
22
25
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
23
26
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
@@ -112,11 +115,10 @@ export class GraphProcessor {
112
115
  #nodeInstances;
113
116
  #connections;
114
117
  #emitter = new Emittery();
115
- #running = false;
118
+ #lifecycle = new GraphRunLifecycle();
116
119
  #isSubProcessor = false;
117
120
  #externalFunctions = {};
118
121
  slowMode = false;
119
- #isPaused = false;
120
122
  #parent;
121
123
  #registry;
122
124
  #concurrency;
@@ -161,9 +163,6 @@ export class GraphProcessor {
161
163
  #contextValues = undefined;
162
164
  #globals = undefined;
163
165
  #attachedNodeData = undefined;
164
- #aborted = false;
165
- #abortSuccessfully = false;
166
- #abortError = undefined;
167
166
  #successfulAbortTerminalProcessIds = undefined;
168
167
  #totalCost = 0;
169
168
  #ignoreNodes = undefined;
@@ -179,10 +178,9 @@ export class GraphProcessor {
179
178
  #graphInputNodeValues = {};
180
179
  /** User input nodes that are pending user input. */
181
180
  #pendingUserInputs = undefined;
182
- #finishEmitted = false;
183
181
  #unsubscribeTokenizerError;
184
182
  get isRunning() {
185
- return this.#running;
183
+ return this.#lifecycle.isRunning;
186
184
  }
187
185
  #startNodeTiming() {
188
186
  return this.#captureNodeTimings ? getMonotonicTimeMs() : undefined;
@@ -246,6 +244,7 @@ export class GraphProcessor {
246
244
  this.#captureNodeTimings = options?.captureNodeTimings ?? false;
247
245
  this.#emitter.bindMethods(this, ['on', 'off', 'once', 'onAny', 'offAny']);
248
246
  this.setExternalFunction('echo', async (value) => ({ type: 'any', value }));
247
+ this.setExternalFunction(RIVET_WEB_APP_STATUS_FUNCTION_NAME, rivetWebAppStatusExternalFunction);
249
248
  this.#emitter.on('globalSet', ({ id, value }) => {
250
249
  emitDetached(this.#emitter, `globalSet:${id}`, value);
251
250
  });
@@ -400,11 +399,9 @@ export class GraphProcessor {
400
399
  this.#externalFunctions[name] = fn;
401
400
  }
402
401
  async abort(successful = false, error) {
403
- if (!this.#running || this.#aborted) {
402
+ if (!this.#lifecycle.requestAbort(successful, error)) {
404
403
  return Promise.resolve();
405
404
  }
406
- this.#abortSuccessfully = successful;
407
- this.#abortError = error;
408
405
  const abortReason = createGraphAbortReason(successful, error);
409
406
  this.#abortController.abort(abortReason);
410
407
  this.#abortActiveNodeControllers(abortReason);
@@ -415,14 +412,12 @@ export class GraphProcessor {
415
412
  await this.#processingQueue.onIdle();
416
413
  }
417
414
  pause() {
418
- if (this.#isPaused === false) {
419
- this.#isPaused = true;
415
+ if (this.#lifecycle.pause()) {
420
416
  emitDetached(this.#emitter, 'pause', void 0);
421
417
  }
422
418
  }
423
419
  resume() {
424
- if (this.#isPaused) {
425
- this.#isPaused = false;
420
+ if (this.#lifecycle.resume()) {
426
421
  emitDetached(this.#emitter, 'resume', void 0);
427
422
  }
428
423
  }
@@ -430,16 +425,16 @@ export class GraphProcessor {
430
425
  this.slowMode = slowMode;
431
426
  }
432
427
  async #waitUntilUnpaused() {
433
- if (!this.#isPaused) {
428
+ if (!this.#lifecycle.isPaused) {
434
429
  return;
435
430
  }
436
431
  if (this.#abortController.signal.aborted) {
437
- throw this.#getAbortError();
432
+ throw this.#lifecycle.getAbortError();
438
433
  }
439
434
  await new Promise((resolve, reject) => {
440
435
  const abortListener = () => {
441
436
  cleanup();
442
- reject(this.#getAbortError());
437
+ reject(this.#lifecycle.getAbortError());
443
438
  };
444
439
  const unsubscribeResume = this.#emitter.on('resume', () => {
445
440
  cleanup();
@@ -452,12 +447,6 @@ export class GraphProcessor {
452
447
  this.#abortController.signal.addEventListener('abort', abortListener, { once: true });
453
448
  });
454
449
  }
455
- #getAbortError() {
456
- if (typeof this.#abortError === 'string') {
457
- return new Error(this.#abortError);
458
- }
459
- return this.#abortError ?? new Error('Processing aborted');
460
- }
461
450
  async *events() {
462
451
  for await (const [event, data] of this.#emitter.anyEvent()) {
463
452
  yield {
@@ -521,7 +510,7 @@ export class GraphProcessor {
521
510
  erroredNodes: this.#erroredNodes,
522
511
  graphInputs: this.#graphInputs,
523
512
  graphOutputs: this.#graphOutputs,
524
- isAborted: () => this.#aborted,
513
+ isAborted: () => this.#lifecycle.isAborted,
525
514
  nodeResults: this.#nodeResults,
526
515
  project: this.#project,
527
516
  recorder,
@@ -536,7 +525,8 @@ export class GraphProcessor {
536
525
  this.#graphOutputs = graphOutputs;
537
526
  },
538
527
  setRunning: (running) => {
539
- this.#running = running;
528
+ if (!running)
529
+ this.#lifecycle.complete();
540
530
  },
541
531
  visitedNodes: this.#visitedNodes,
542
532
  waitUntilUnpaused: () => this.#waitUntilUnpaused(),
@@ -544,8 +534,7 @@ export class GraphProcessor {
544
534
  return this.#graphOutputs;
545
535
  }
546
536
  #initProcessState() {
547
- this.#running = true;
548
- this.#finishEmitted = false;
537
+ this.#lifecycle.begin();
549
538
  if (!this.#hasPreloadedData) {
550
539
  this.#nodeResults = new Map();
551
540
  this.#visitedNodes = new Set();
@@ -553,9 +542,7 @@ export class GraphProcessor {
553
542
  this.#erroredNodes = new Map();
554
543
  this.#currentlyProcessing = new Set();
555
544
  const seededExecutionPlan = this.#seededExecutionPlanForNextRun();
556
- this.#remainingNodes = new Set(seededExecutionPlan
557
- ? seededExecutionPlan.nodeIds
558
- : this.#graph.nodes.map((node) => node.id));
545
+ this.#remainingNodes = new Set(seededExecutionPlan ? seededExecutionPlan.nodeIds : this.#graph.nodes.map((node) => node.id));
559
546
  this.#pendingUserInputs = {};
560
547
  this.#processingQueue = new PQueue({ concurrency: this.#concurrency.nodeConcurrency });
561
548
  this.#graphOutputs = {};
@@ -569,12 +556,6 @@ export class GraphProcessor {
569
556
  this.#nodeProcessContextBase = undefined;
570
557
  this.#runToRelevantNodeIds = undefined;
571
558
  this.#abortController = this.#newAbortController();
572
- this.#abortController.signal.addEventListener('abort', () => {
573
- this.#aborted = true;
574
- });
575
- this.#aborted = false;
576
- this.#abortError = undefined;
577
- this.#abortSuccessfully = false;
578
559
  this.#successfulAbortTerminalProcessIds = new Set();
579
560
  this.#nodeAbortControllers = new Map();
580
561
  this.#loadedProjects =
@@ -595,7 +576,7 @@ export class GraphProcessor {
595
576
  inputs = {},
596
577
  /** Contextual data available to all graphs and subgraphs. Kind of like react context, avoids drilling down data into subgraphs. Be careful when using it. */
597
578
  contextValues = {}) {
598
- if (this.#running) {
579
+ if (this.#lifecycle.isRunning) {
599
580
  throw new Error('Cannot process graph while already processing');
600
581
  }
601
582
  try {
@@ -620,16 +601,15 @@ export class GraphProcessor {
620
601
  return await this.#profileRuntimeAsync('finalizeGraphRun', () => this.#finalizeGraphRun());
621
602
  }
622
603
  finally {
623
- this.#running = false;
604
+ this.#lifecycle.complete();
624
605
  this.#cleanupTokenizerErrorListener();
625
606
  await this.#profileRuntimeAsync('emitFinish', () => this.#emitFinishIfNeeded());
626
607
  }
627
608
  }
628
609
  async #emitFinishIfNeeded() {
629
- if (this.#isSubProcessor || this.#finishEmitted) {
610
+ if (!this.#lifecycle.claimRootFinish(this.#isSubProcessor)) {
630
611
  return;
631
612
  }
632
- this.#finishEmitted = true;
633
613
  await this.#emitter.emit('finish', undefined);
634
614
  }
635
615
  #initializeGraphRun(context, inputs, contextValues) {
@@ -853,8 +833,8 @@ export class GraphProcessor {
853
833
  });
854
834
  }
855
835
  #createGraphError(erroredNodes) {
856
- if (this.#abortError) {
857
- return this.#getAbortError();
836
+ if (this.#lifecycle.abortError) {
837
+ return this.#lifecycle.getAbortError();
858
838
  }
859
839
  const message = `Graph ${this.#graph.metadata.name} (${this.#graph.metadata.id}) failed to process due to errors in nodes:\n${erroredNodes
860
840
  .map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})`)
@@ -867,7 +847,7 @@ export class GraphProcessor {
867
847
  }
868
848
  async #throwIfGraphErrored() {
869
849
  const erroredNodes = this.#getUnhandledErroredNodes();
870
- if (!erroredNodes.length || this.#abortSuccessfully) {
850
+ if (!erroredNodes.length || this.#lifecycle.abortSuccessful) {
871
851
  return;
872
852
  }
873
853
  const error = this.#createGraphError(erroredNodes);
@@ -880,7 +860,7 @@ export class GraphProcessor {
880
860
  async #finalizeGraphRun() {
881
861
  ensureGraphCostOutput(this.#graphOutputs, this.#totalCost);
882
862
  const outputValues = this.#graphOutputs;
883
- this.#running = false;
863
+ this.#lifecycle.complete();
884
864
  await this.#emitter.emit('graphFinish', this.#withExecution({ graph: this.#graph, outputs: outputValues }));
885
865
  if (!this.#isSubProcessor) {
886
866
  await this.#emitter.emit('done', { results: outputValues });
@@ -1227,7 +1207,7 @@ export class GraphProcessor {
1227
1207
  setNodeResults: (nodeId, outputs) => this.#nodeResults.set(nodeId, outputs),
1228
1208
  markNodeVisited: (nodeId) => this.#visitedNodes.add(nodeId),
1229
1209
  nodeErrored: (n, err, pid, durationMs, splitRunDurationMs) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs),
1230
- isAborted: () => this.#aborted,
1210
+ isAborted: () => this.#lifecycle.isAborted,
1231
1211
  getAbortError: () => createGraphAbortErrorFromSignal(this.#abortController.signal),
1232
1212
  emit: (event, data) => {
1233
1213
  if (event === 'partialOutput') {
@@ -1316,8 +1296,8 @@ export class GraphProcessor {
1316
1296
  this.#successfulAbortTerminalProcessIds.add(processId);
1317
1297
  return SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
1318
1298
  }
1319
- if (this.#abortSuccessfully && isAbortLikeError(error)) {
1320
- const exclusionReason = this.#abortError === RACE_LOSER_EXCLUSION_REASON
1299
+ if (this.#lifecycle.abortSuccessful && isAbortLikeError(error)) {
1300
+ const exclusionReason = this.#lifecycle.abortError === RACE_LOSER_EXCLUSION_REASON
1321
1301
  ? RACE_LOSER_EXCLUSION_REASON
1322
1302
  : SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
1323
1303
  if (exclusionReason === SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON) {
@@ -1462,6 +1442,12 @@ export class GraphProcessor {
1462
1442
  },
1463
1443
  processId,
1464
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
+ },
1465
1451
  setGlobal: (id, value) => {
1466
1452
  this.#globals.set(id, value);
1467
1453
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id, value, processId }));
@@ -1577,7 +1563,7 @@ export class GraphProcessor {
1577
1563
  const wireEventsProfileStart = this.#startRuntimeProfile();
1578
1564
  try {
1579
1565
  wireSubprocessorEvents(processor, this.#emitter, {
1580
- isPaused: () => this.#isPaused,
1566
+ isPaused: () => this.#lifecycle.isPaused,
1581
1567
  pause: () => {
1582
1568
  void this.pause();
1583
1569
  },
@@ -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
+ }