@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
@@ -1,9 +1,252 @@
1
+ import { getUiGraphChatDraftStateKey, getUiGraphChatMessages, getUiGraphComponentActionOutputStateKeys, getUiGraphComponentActionState, getUiGraphInitialState, } from './UiGraph.js';
2
+ import { normalizeGraphProgress } from './GraphProgress.js';
3
+ const IMAGE_DATA_URL_PATTERN = /^data:(image\/(?:avif|bmp|gif|jpe?g|png|webp));base64,([\s\S]+)$/i;
4
+ const IMAGE_URL_PATTERN = /^(?:https?:\/\/|blob:|\/\/|\/|\.\.?\/)/i;
5
+ const RELATIVE_IMAGE_PATH_PATTERN = /\.(?:avif|bmp|gif|jpe?g|png|webp)(?:[?#].*)?$/i;
6
+ const BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
7
+ /**
8
+ * Coordinates independent web-app actions without allowing older completions to
9
+ * clear newer loading states or overwrite newer writes to the same UI state key.
10
+ */
11
+ export function createUiGraphActionExecutionController() {
12
+ let nextVersion = 0;
13
+ const activeExecutionByComponent = new Map();
14
+ const latestWriterByStateKey = new Map();
15
+ return {
16
+ begin(component) {
17
+ if (activeExecutionByComponent.has(component.id)) {
18
+ return undefined;
19
+ }
20
+ const execution = { componentId: component.id, id: ++nextVersion };
21
+ activeExecutionByComponent.set(component.id, execution.id);
22
+ for (const stateKey of getUiGraphComponentActionOutputStateKeys(component)) {
23
+ latestWriterByStateKey.set(stateKey, execution.id);
24
+ }
25
+ return execution;
26
+ },
27
+ finish(execution) {
28
+ if (activeExecutionByComponent.get(execution.componentId) !== execution.id) {
29
+ return false;
30
+ }
31
+ activeExecutionByComponent.delete(execution.componentId);
32
+ return true;
33
+ },
34
+ isCurrent(execution) {
35
+ return activeExecutionByComponent.get(execution.componentId) === execution.id;
36
+ },
37
+ isRunning(componentId) {
38
+ return activeExecutionByComponent.has(componentId);
39
+ },
40
+ noteStateWrite(stateKey) {
41
+ const normalizedStateKey = stateKey.trim();
42
+ if (normalizedStateKey) {
43
+ latestWriterByStateKey.set(normalizedStateKey, ++nextVersion);
44
+ }
45
+ },
46
+ resolveStatePatch(execution, statePatch) {
47
+ if (!statePatch) {
48
+ return undefined;
49
+ }
50
+ const applicableEntries = Object.entries(statePatch).filter(([stateKey]) => latestWriterByStateKey.get(stateKey) === execution.id);
51
+ return applicableEntries.length > 0 ? Object.fromEntries(applicableEntries) : undefined;
52
+ },
53
+ reset() {
54
+ activeExecutionByComponent.clear();
55
+ latestWriterByStateKey.clear();
56
+ },
57
+ };
58
+ }
59
+ /**
60
+ * Owns mutable web-app interaction state for every renderer. React and direct
61
+ * DOM hosts subscribe to this controller instead of reimplementing action
62
+ * cancellation, loading/error state, and stale state-patch protection.
63
+ */
64
+ export function createUiGraphInteractionController(initialUiGraph, options = {}) {
65
+ let uiGraphId = initialUiGraph.id;
66
+ let state = options.initialState ? { ...options.initialState } : getUiGraphInitialState(initialUiGraph);
67
+ let actionErrors = {};
68
+ let actionProgress = {};
69
+ let snapshot;
70
+ const actionController = createUiGraphActionExecutionController();
71
+ const activeActions = new Map();
72
+ const listeners = new Set();
73
+ const updateSnapshot = () => {
74
+ snapshot = {
75
+ actionErrors,
76
+ actionProgress,
77
+ runningComponentIds: new Set([...activeActions.values()].map(({ execution }) => execution.componentId)),
78
+ state,
79
+ };
80
+ };
81
+ const publish = (change) => {
82
+ updateSnapshot();
83
+ for (const listener of listeners) {
84
+ listener(change);
85
+ }
86
+ };
87
+ const abortMatchingActions = (predicate, notify) => {
88
+ let changed = false;
89
+ for (const [executionId, activeAction] of activeActions) {
90
+ if (!predicate(activeAction, executionId)) {
91
+ continue;
92
+ }
93
+ activeAction.abortController.abort();
94
+ activeActions.delete(executionId);
95
+ actionController.finish(activeAction.execution);
96
+ changed = true;
97
+ }
98
+ if (changed && notify) {
99
+ publish('action');
100
+ }
101
+ return changed;
102
+ };
103
+ const abortAllActions = (notify) => {
104
+ let changed = abortMatchingActions(() => true, false);
105
+ actionController.reset();
106
+ if (Object.keys(actionProgress).length > 0) {
107
+ actionProgress = {};
108
+ changed = true;
109
+ }
110
+ if (changed && notify) {
111
+ publish('action');
112
+ }
113
+ };
114
+ const removeActionPresentation = (componentId) => {
115
+ if (Object.prototype.hasOwnProperty.call(actionErrors, componentId)) {
116
+ actionErrors = { ...actionErrors };
117
+ delete actionErrors[componentId];
118
+ }
119
+ if (Object.prototype.hasOwnProperty.call(actionProgress, componentId)) {
120
+ actionProgress = { ...actionProgress };
121
+ delete actionProgress[componentId];
122
+ }
123
+ };
124
+ updateSnapshot();
125
+ return {
126
+ abortActions() {
127
+ abortAllActions(true);
128
+ },
129
+ cancelAction(componentId) {
130
+ if (abortMatchingActions(({ execution }) => execution.componentId === componentId, false)) {
131
+ removeActionPresentation(componentId);
132
+ publish('action');
133
+ }
134
+ },
135
+ detachActions() {
136
+ activeActions.clear();
137
+ actionController.reset();
138
+ actionProgress = {};
139
+ updateSnapshot();
140
+ },
141
+ getSnapshot() {
142
+ return snapshot;
143
+ },
144
+ async runAction(component, runner) {
145
+ const execution = actionController.begin(component);
146
+ if (!execution) {
147
+ return;
148
+ }
149
+ const abortController = new AbortController();
150
+ activeActions.set(execution.id, { abortController, execution });
151
+ removeActionPresentation(component.id);
152
+ publish('action');
153
+ try {
154
+ const result = await runner({
155
+ abortOtherActions: () => abortMatchingActions((_activeAction, executionId) => executionId !== execution.id, true),
156
+ componentId: component.id,
157
+ reportProgress: (progress) => {
158
+ if (!actionController.isCurrent(execution))
159
+ return;
160
+ const normalized = normalizeGraphProgress(progress);
161
+ if (!normalized)
162
+ return;
163
+ actionProgress = { ...actionProgress, [component.id]: normalized };
164
+ publish('action');
165
+ },
166
+ signal: abortController.signal,
167
+ state: getUiGraphComponentActionState(component, state),
168
+ });
169
+ if (!actionController.isCurrent(execution)) {
170
+ return;
171
+ }
172
+ const statePatch = actionController.resolveStatePatch(execution, result.statePatch);
173
+ if (statePatch) {
174
+ state = applyUiGraphStatePatch(state, statePatch);
175
+ }
176
+ }
177
+ catch (error) {
178
+ if (!abortController.signal.aborted && actionController.isCurrent(execution)) {
179
+ actionErrors = {
180
+ ...actionErrors,
181
+ [component.id]: error instanceof Error ? error.message : String(error),
182
+ };
183
+ }
184
+ }
185
+ finally {
186
+ if (activeActions.delete(execution.id)) {
187
+ actionController.finish(execution);
188
+ if (Object.prototype.hasOwnProperty.call(actionProgress, component.id)) {
189
+ actionProgress = { ...actionProgress };
190
+ delete actionProgress[component.id];
191
+ }
192
+ publish('action');
193
+ }
194
+ }
195
+ },
196
+ setUiGraph(nextUiGraph) {
197
+ if (nextUiGraph.id !== uiGraphId) {
198
+ abortAllActions(false);
199
+ uiGraphId = nextUiGraph.id;
200
+ state = getUiGraphInitialState(nextUiGraph);
201
+ actionErrors = {};
202
+ actionProgress = {};
203
+ publish('graph');
204
+ return;
205
+ }
206
+ const actionComponentIds = new Set(nextUiGraph.components
207
+ .filter((component) => component.type === 'button' || component.type === 'chat')
208
+ .map((component) => component.id));
209
+ let changed = abortMatchingActions(({ execution }) => !actionComponentIds.has(execution.componentId), false);
210
+ const remainingErrors = Object.fromEntries(Object.entries(actionErrors).filter(([componentId]) => actionComponentIds.has(componentId)));
211
+ const remainingProgress = Object.fromEntries(Object.entries(actionProgress).filter(([componentId]) => actionComponentIds.has(componentId)));
212
+ if (Object.keys(remainingErrors).length !== Object.keys(actionErrors).length) {
213
+ actionErrors = remainingErrors;
214
+ changed = true;
215
+ }
216
+ if (Object.keys(remainingProgress).length !== Object.keys(actionProgress).length) {
217
+ actionProgress = remainingProgress;
218
+ changed = true;
219
+ }
220
+ if (changed) {
221
+ publish('graph');
222
+ }
223
+ },
224
+ subscribe(listener) {
225
+ listeners.add(listener);
226
+ return () => listeners.delete(listener);
227
+ },
228
+ updateState(stateKey, value) {
229
+ actionController.noteStateWrite(stateKey);
230
+ state = { ...state, [stateKey]: value };
231
+ publish('state');
232
+ },
233
+ updateStatePatch(statePatch) {
234
+ for (const stateKey of Object.keys(statePatch)) {
235
+ actionController.noteStateWrite(stateKey);
236
+ }
237
+ state = applyUiGraphStatePatch(state, statePatch);
238
+ publish('state');
239
+ },
240
+ };
241
+ }
1
242
  export function getUiGraphComponentRenderModel(component, state) {
2
243
  switch (component.type) {
3
244
  case 'text':
4
245
  return { component, text: component.text, type: 'text' };
5
246
  case 'markdown':
6
247
  return { component, markdown: component.markdown, type: 'markdown' };
248
+ case 'gap':
249
+ return { component, size: component.size, type: 'gap' };
7
250
  case 'input':
8
251
  case 'textarea':
9
252
  return {
@@ -14,6 +257,13 @@ export function getUiGraphComponentRenderModel(component, state) {
14
257
  };
15
258
  case 'button':
16
259
  return { component, label: component.label, type: 'button' };
260
+ case 'chat':
261
+ return {
262
+ component,
263
+ draft: `${state[getUiGraphChatDraftStateKey(component.id)] ?? ''}`,
264
+ messages: getUiGraphChatMessages(component.id, state),
265
+ type: 'chat',
266
+ };
17
267
  case 'output':
18
268
  return {
19
269
  component,
@@ -30,8 +280,12 @@ export function getUiGraphOutputRenderModel(state, stateKey, renderAs) {
30
280
  const value = state[stateKey];
31
281
  const hasValue = hasUiGraphStateValue(state, stateKey);
32
282
  const renderedValue = renderUiGraphOutputValue(value, renderAs);
283
+ const imageSource = hasValue && renderAs === 'image' ? getUiGraphImageSource(value) : undefined;
284
+ const imageErrorMessage = hasValue && renderAs === 'image' && !imageSource ? 'Expected an image URL or base64 image.' : undefined;
33
285
  return {
34
286
  hasValue,
287
+ ...(imageErrorMessage ? { imageErrorMessage } : {}),
288
+ ...(imageSource ? { imageSource } : {}),
35
289
  ...(hasValue && renderAs === 'json' ? { jsonDownloadValue: stringifyUiGraphValue(value) } : {}),
36
290
  renderedValue,
37
291
  renderAs,
@@ -46,6 +300,52 @@ export function renderUiGraphOutputValue(value, renderAs) {
46
300
  }
47
301
  return typeof value === 'string' ? value : value == null ? '' : stringifyUiGraphValue(value) ?? '';
48
302
  }
303
+ export function getUiGraphImageSource(value) {
304
+ if (typeof value !== 'string') {
305
+ return undefined;
306
+ }
307
+ const source = value.trim();
308
+ if (!source) {
309
+ return undefined;
310
+ }
311
+ const dataUrl = IMAGE_DATA_URL_PATTERN.exec(source);
312
+ if (dataUrl) {
313
+ const base64 = normalizeBase64(dataUrl[2]);
314
+ return base64 ? `data:${normalizeImageMediaType(dataUrl[1])};base64,${base64}` : undefined;
315
+ }
316
+ const base64 = normalizeBase64(source);
317
+ const inferredMediaType = base64 ? inferBase64ImageMediaType(base64) : undefined;
318
+ if (base64 && inferredMediaType) {
319
+ return `data:${inferredMediaType};base64,${base64}`;
320
+ }
321
+ if (!IMAGE_URL_PATTERN.test(source) && !RELATIVE_IMAGE_PATH_PATTERN.test(source)) {
322
+ return undefined;
323
+ }
324
+ try {
325
+ const protocol = new URL(source, 'https://rivet.invalid').protocol;
326
+ return protocol === 'http:' || protocol === 'https:' || protocol === 'blob:' ? source : undefined;
327
+ }
328
+ catch {
329
+ return undefined;
330
+ }
331
+ }
332
+ function normalizeBase64(value) {
333
+ const compact = value.replace(/\s/g, '');
334
+ return compact.length >= 8 && compact.length % 4 !== 1 && BASE64_PATTERN.test(compact) ? compact : undefined;
335
+ }
336
+ function normalizeImageMediaType(mediaType) {
337
+ const normalized = mediaType.toLowerCase();
338
+ return normalized === 'image/jpg' ? 'image/jpeg' : normalized;
339
+ }
340
+ function inferBase64ImageMediaType(value) {
341
+ if (value.startsWith('iVBORw0KGgo'))
342
+ return 'image/png';
343
+ if (value.startsWith('/9j/'))
344
+ return 'image/jpeg';
345
+ if (value.startsWith('R0lGODdh') || value.startsWith('R0lGODlh'))
346
+ return 'image/gif';
347
+ return undefined;
348
+ }
49
349
  export function stringifyUiGraphValue(value) {
50
350
  try {
51
351
  return JSON.stringify(value, null, 2);
@@ -0,0 +1,19 @@
1
+ export const RIVET_WEB_APP_STATUS_FUNCTION_NAME = 'setWebAppStatus';
2
+ /** Built-in External Call function used to report web-app status. */
3
+ export const rivetWebAppStatusExternalFunction = async (context, value) => {
4
+ const message = formatRivetWebAppStatusMessage(value);
5
+ context.reportProgress({ message });
6
+ return { type: 'string', value: message };
7
+ };
8
+ export function formatRivetWebAppStatusMessage(value) {
9
+ if (typeof value === 'string')
10
+ return value;
11
+ if (value == null)
12
+ return '';
13
+ try {
14
+ return JSON.stringify(value) ?? String(value);
15
+ }
16
+ catch {
17
+ return '[Unserializable web app status]';
18
+ }
19
+ }
@@ -7,6 +7,7 @@ import { flattenDeep } from 'lodash-es';
7
7
  import { dedent } from 'ts-dedent';
8
8
  import {} from '../EditorDefinition.js';
9
9
  import { nodeDefinition } from '../NodeDefinition.js';
10
+ import { getNextVariadicPortIndex } from './variadicPortIndex.js';
10
11
  export class ArrayNodeImpl extends NodeImpl {
11
12
  static create() {
12
13
  const chartNode = {
@@ -27,7 +28,7 @@ export class ArrayNodeImpl extends NodeImpl {
27
28
  }
28
29
  getInputDefinitions(connections) {
29
30
  const inputs = [];
30
- const inputCount = this.#getInputPortCount(connections);
31
+ const inputCount = getNextVariadicPortIndex(connections, this.chartNode.id, 'input', 'legacy');
31
32
  for (let i = 1; i <= inputCount; i++) {
32
33
  inputs.push({
33
34
  dataType: 'any',
@@ -70,18 +71,6 @@ export class ArrayNodeImpl extends NodeImpl {
70
71
  },
71
72
  ];
72
73
  }
73
- #getInputPortCount(connections) {
74
- const inputNodeId = this.chartNode.id;
75
- const inputConnections = connections.filter((connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'));
76
- let maxInputNumber = 0;
77
- for (const connection of inputConnections) {
78
- const inputNumber = parseInt(connection.inputId.replace('input', ''));
79
- if (inputNumber > maxInputNumber) {
80
- maxInputNumber = inputNumber;
81
- }
82
- }
83
- return maxInputNumber + 1;
84
- }
85
74
  static getUIData() {
86
75
  return {
87
76
  infoBoxBody: dedent `
@@ -7,6 +7,7 @@ import { orderBy } from 'lodash-es';
7
7
  import { coerceTypeOptional, dedent, getInputOrData } from '../../utils/index.js';
8
8
  import { nodeDefinition } from '../NodeDefinition.js';
9
9
  import { match } from 'ts-pattern';
10
+ import { getNextVariadicPortIndex } from './variadicPortIndex.js';
10
11
  const messageTypeToTitle = {
11
12
  assistant: 'Assistant',
12
13
  function: 'Function Tool Call',
@@ -35,7 +36,7 @@ export class AssembleMessageNodeImpl extends NodeImpl {
35
36
  }
36
37
  getInputDefinitions(connections) {
37
38
  const inputs = [];
38
- const messageCount = this.#getInputPortCount(connections);
39
+ const messageCount = getNextVariadicPortIndex(connections, this.chartNode.id, 'part', 'legacy');
39
40
  if (this.data.useTypeInput) {
40
41
  inputs.push({
41
42
  dataType: 'string',
@@ -96,18 +97,6 @@ export class AssembleMessageNodeImpl extends NodeImpl {
96
97
  },
97
98
  ];
98
99
  }
99
- #getInputPortCount(connections) {
100
- const inputNodeId = this.chartNode.id;
101
- const messageConnections = connections.filter((connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('part'));
102
- let maxMessageNumber = 0;
103
- for (const connection of messageConnections) {
104
- const messageNumber = parseInt(connection.inputId.replace('part', ''));
105
- if (messageNumber > maxMessageNumber) {
106
- maxMessageNumber = messageNumber;
107
- }
108
- }
109
- return maxMessageNumber + 1;
110
- }
111
100
  static getUIData() {
112
101
  return {
113
102
  infoBoxBody: dedent `
@@ -8,6 +8,7 @@ import { orderBy } from 'lodash-es';
8
8
  import { dedent } from 'ts-dedent';
9
9
  import { nodeDefinition } from '../NodeDefinition.js';
10
10
  import { getInputOrData } from '../../utils/inputs.js';
11
+ import { getNextVariadicPortIndex } from './variadicPortIndex.js';
11
12
  export class AssemblePromptNodeImpl extends NodeImpl {
12
13
  static create() {
13
14
  const chartNode = {
@@ -25,7 +26,7 @@ export class AssemblePromptNodeImpl extends NodeImpl {
25
26
  }
26
27
  getInputDefinitions(connections) {
27
28
  const inputs = [];
28
- const messageCount = this.#getMessagePortCount(connections);
29
+ const messageCount = getNextVariadicPortIndex(connections, this.chartNode.id, 'message', 'legacy');
29
30
  if (this.data.useIsLastMessageCacheBreakpointInput) {
30
31
  inputs.push({
31
32
  dataType: 'boolean',
@@ -63,18 +64,6 @@ export class AssemblePromptNodeImpl extends NodeImpl {
63
64
  }
64
65
  return outputs;
65
66
  }
66
- #getMessagePortCount(connections) {
67
- const inputNodeId = this.chartNode.id;
68
- const messageConnections = connections.filter((connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('message'));
69
- let maxMessageNumber = 0;
70
- for (const connection of messageConnections) {
71
- const messageNumber = parseInt(connection.inputId.replace('message', ''));
72
- if (messageNumber > maxMessageNumber) {
73
- maxMessageNumber = messageNumber;
74
- }
75
- }
76
- return maxMessageNumber + 1;
77
- }
78
67
  static getUIData() {
79
68
  return {
80
69
  infoBoxBody: dedent `
@@ -6,6 +6,7 @@ import {} from '../GraphProcessor.js';
6
6
  import { dedent } from 'ts-dedent';
7
7
  import { nodeDefinition } from '../NodeDefinition.js';
8
8
  import {} from '../EditorDefinition.js';
9
+ import { getNextVariadicPortIndex } from './variadicPortIndex.js';
9
10
  const INPUT_PORT_ID_PATTERN = /^input(\d+)$/;
10
11
  const IGNORE_NULL_LABEL = "Ignore 'null'";
11
12
  const IGNORE_UNDEFINED_LABEL = "Ignore 'undefined'";
@@ -29,7 +30,7 @@ export class CoalesceNodeImpl extends NodeImpl {
29
30
  };
30
31
  getInputDefinitions(connections) {
31
32
  const inputs = [];
32
- const inputCount = this.#getInputPortCount(connections);
33
+ const inputCount = getNextVariadicPortIndex(connections, this.chartNode.id, 'input', 'strict-positive');
33
34
  inputs.push({
34
35
  dataType: 'boolean',
35
36
  id: 'conditional',
@@ -89,20 +90,6 @@ export class CoalesceNodeImpl extends NodeImpl {
89
90
  group: ['Logic'],
90
91
  };
91
92
  }
92
- #getInputPortCount(connections) {
93
- const inputNodeId = this.chartNode.id;
94
- let maxInputNumber = 0;
95
- for (const connection of connections) {
96
- if (connection.inputNodeId !== inputNodeId) {
97
- continue;
98
- }
99
- const inputNumber = this.#getInputPortNumber(connection.inputId);
100
- if (inputNumber && inputNumber > maxInputNumber) {
101
- maxInputNumber = inputNumber;
102
- }
103
- }
104
- return maxInputNumber + 1;
105
- }
106
93
  async process(inputData) {
107
94
  const conditional = inputData['conditional'];
108
95
  // This lets the coalesce actually be control-flow-excluded itself, because otherwise
@@ -6,6 +6,7 @@ import {} from '../GraphProcessor.js';
6
6
  import {} from '../../index.js';
7
7
  import { dedent } from 'ts-dedent';
8
8
  import { getInputOrData } from '../../utils/inputs.js';
9
+ import { getNextVariadicPortIndex } from './variadicPortIndex.js';
9
10
  export class DelayNodeImpl extends NodeImpl {
10
11
  static create() {
11
12
  const chartNode = {
@@ -25,7 +26,7 @@ export class DelayNodeImpl extends NodeImpl {
25
26
  }
26
27
  getInputDefinitions(connections) {
27
28
  const inputs = [];
28
- const inputCount = this.#getInputPortCount(connections);
29
+ const inputCount = getNextVariadicPortIndex(connections, this.chartNode.id, 'input', 'decimal');
29
30
  if (this.data.useDelayInput) {
30
31
  inputs.push({
31
32
  dataType: 'number',
@@ -44,7 +45,7 @@ export class DelayNodeImpl extends NodeImpl {
44
45
  }
45
46
  getOutputDefinitions(connections) {
46
47
  const outputs = [];
47
- const inputCount = this.#getInputPortCount(connections);
48
+ const inputCount = getNextVariadicPortIndex(connections, this.chartNode.id, 'input', 'decimal');
48
49
  for (let i = 1; i <= inputCount - 1; i++) {
49
50
  outputs.push({
50
51
  dataType: 'any',
@@ -64,18 +65,6 @@ export class DelayNodeImpl extends NodeImpl {
64
65
  group: ['Logic'],
65
66
  };
66
67
  }
67
- #getInputPortCount(connections) {
68
- const inputNodeId = this.chartNode.id;
69
- const inputConnections = connections.filter((connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'));
70
- let maxInputNumber = 0;
71
- for (const connection of inputConnections) {
72
- const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);
73
- if (messageNumber > maxInputNumber) {
74
- maxInputNumber = messageNumber;
75
- }
76
- }
77
- return maxInputNumber + 1;
78
- }
79
68
  getEditors() {
80
69
  return [
81
70
  {
@@ -4,6 +4,7 @@ import { NodeImpl } from '../NodeImpl.js';
4
4
  import { nodeDefinition } from '../NodeDefinition.js';
5
5
  import {} from '../GraphProcessor.js';
6
6
  import {} from '../EditorDefinition.js';
7
+ import { getNextVariadicPortIndex } from './variadicPortIndex.js';
7
8
  const DID_RUN_EXPLANATION = 'Outputs true when all connected inputs have run. Falsy or empty values still count as having run, so this is useful for adapting "did this branch run at all?" into a boolean If port.';
8
9
  export class DidRunNodeImpl extends NodeImpl {
9
10
  static create() {
@@ -20,7 +21,7 @@ export class DidRunNodeImpl extends NodeImpl {
20
21
  };
21
22
  }
22
23
  getInputDefinitions(connections) {
23
- const inputCount = this.#getInputPortCount(connections);
24
+ const inputCount = getNextVariadicPortIndex(connections, this.chartNode.id, 'input', 'decimal');
24
25
  const inputs = [];
25
26
  for (let i = 1; i <= inputCount; i++) {
26
27
  inputs.push({
@@ -57,18 +58,6 @@ export class DidRunNodeImpl extends NodeImpl {
57
58
  },
58
59
  ];
59
60
  }
60
- #getInputPortCount(connections) {
61
- const inputNodeId = this.chartNode.id;
62
- const inputConnections = connections.filter((connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'));
63
- let maxInputNumber = 0;
64
- for (const connection of inputConnections) {
65
- const inputNumber = parseInt(connection.inputId.replace('input', ''), 10);
66
- if (inputNumber > maxInputNumber) {
67
- maxInputNumber = inputNumber;
68
- }
69
- }
70
- return maxInputNumber + 1;
71
- }
72
61
  async process(inputData) {
73
62
  const hasDynamicInput = Object.keys(inputData).some((key) => key.startsWith('input'));
74
63
  if (!hasDynamicInput) {
@@ -8,6 +8,7 @@ import {} from '../GraphProcessor.js';
8
8
  import { dedent } from 'ts-dedent';
9
9
  import {} from '../EditorDefinition.js';
10
10
  import { handleEscapeCharacters } from '../../utils/index.js';
11
+ import { getNextVariadicPortIndex } from './variadicPortIndex.js';
11
12
  export class JoinNodeImpl extends NodeImpl {
12
13
  static create = () => {
13
14
  const chartNode = {
@@ -28,7 +29,7 @@ export class JoinNodeImpl extends NodeImpl {
28
29
  };
29
30
  getInputDefinitions(connections) {
30
31
  const inputs = [];
31
- const inputCount = this.#getInputPortCount(connections);
32
+ const inputCount = getNextVariadicPortIndex(connections, this.chartNode.id, 'input', 'decimal');
32
33
  if (this.data.useJoinStringInput) {
33
34
  inputs.push({
34
35
  dataType: 'string',
@@ -54,18 +55,6 @@ export class JoinNodeImpl extends NodeImpl {
54
55
  },
55
56
  ];
56
57
  }
57
- #getInputPortCount(connections) {
58
- const inputNodeId = this.chartNode.id;
59
- const inputConnections = connections.filter((connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'));
60
- let maxInputNumber = 0;
61
- for (const connection of inputConnections) {
62
- const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);
63
- if (messageNumber > maxInputNumber) {
64
- maxInputNumber = messageNumber;
65
- }
66
- }
67
- return maxInputNumber + 1;
68
- }
69
58
  getEditors() {
70
59
  return [
71
60
  {
@@ -8,6 +8,7 @@ import {} from '../ProcessContext.js';
8
8
  import { dedent } from 'ts-dedent';
9
9
  import {} from '../../index.js';
10
10
  import { entries } from '../../utils/typeSafety.js';
11
+ import { getHighestVariadicPortIndex } from './variadicPortIndex.js';
11
12
  export class LoopControllerNodeImpl extends NodeImpl {
12
13
  static create() {
13
14
  const chartNode = {
@@ -27,7 +28,7 @@ export class LoopControllerNodeImpl extends NodeImpl {
27
28
  }
28
29
  getInputDefinitions(connections, nodes) {
29
30
  const inputs = [];
30
- const messageCount = this.#getInputPortCount(connections);
31
+ const messageCount = getHighestVariadicPortIndex(connections, this.chartNode.id, 'input', 'legacy');
31
32
  inputs.push({
32
33
  dataType: 'any',
33
34
  id: 'continue',
@@ -59,7 +60,7 @@ export class LoopControllerNodeImpl extends NodeImpl {
59
60
  return inputs;
60
61
  }
61
62
  getOutputDefinitions(connections, nodes) {
62
- const messageCount = this.#getInputPortCount(connections);
63
+ const messageCount = getHighestVariadicPortIndex(connections, this.chartNode.id, 'input', 'legacy');
63
64
  const outputs = [];
64
65
  outputs.push({
65
66
  dataType: 'any',
@@ -123,18 +124,6 @@ export class LoopControllerNodeImpl extends NodeImpl {
123
124
  group: ['Logic'],
124
125
  };
125
126
  }
126
- #getInputPortCount(connections) {
127
- const inputNodeId = this.chartNode.id;
128
- const messageConnections = connections.filter((connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'));
129
- let maxMessageNumber = 0;
130
- for (const connection of messageConnections) {
131
- const messageNumber = parseInt(connection.inputId.replace('input', ''));
132
- if (messageNumber > maxMessageNumber) {
133
- maxMessageNumber = messageNumber;
134
- }
135
- }
136
- return maxMessageNumber;
137
- }
138
127
  async process(inputs, context) {
139
128
  const output = {};
140
129
  let inputCount = 0;