@valerypopoff/rivet2-core 2.1.4 → 2.1.6

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 (107) hide show
  1. package/dist/cjs/bundle.cjs +6651 -1022
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +733 -19
  4. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  5. package/dist/esm/api/createProcessor.js +6 -1
  6. package/dist/esm/exports.js +7 -0
  7. package/dist/esm/integrations/KnowledgeStore.js +1 -0
  8. package/dist/esm/integrations/KnowledgeStoreProvider.js +292 -0
  9. package/dist/esm/integrations/KnowledgeStoreValidation.js +428 -0
  10. package/dist/esm/integrations/ManagedKnowledgeStore.js +539 -0
  11. package/dist/esm/model/DataValue.js +22 -2
  12. package/dist/esm/model/GraphBoundaryEffects.js +13 -0
  13. package/dist/esm/model/GraphProcessor.js +1141 -82
  14. package/dist/esm/model/ManagedAsyncBranches.js +28 -0
  15. package/dist/esm/model/Nodes.js +27 -0
  16. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  17. package/dist/esm/model/RecordingPlayer.js +9 -0
  18. package/dist/esm/model/StoredValueStore.js +226 -0
  19. package/dist/esm/model/SubprocessorBridge.js +50 -19
  20. package/dist/esm/model/ToolCallContinuation.js +1 -0
  21. package/dist/esm/model/UiGraph.js +52 -2
  22. package/dist/esm/model/UiGraphActionProtocol.js +10 -1
  23. package/dist/esm/model/UiGraphBrowserRuntime.js +444 -0
  24. package/dist/esm/model/UiGraphNormalization.js +35 -185
  25. package/dist/esm/model/UiGraphRendererStyles.js +878 -78
  26. package/dist/esm/model/UiGraphRuntimeModel.js +255 -15
  27. package/dist/esm/model/UiGraphSchema.js +91 -0
  28. package/dist/esm/model/UiGraphWebAppStorage.js +1 -0
  29. package/dist/esm/model/chat/chatMessages.js +5 -9
  30. package/dist/esm/model/chat/openAIChatRequest.js +8 -2
  31. package/dist/esm/model/chat-v2/chatV2Errors.js +36 -3
  32. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +8 -8
  33. package/dist/esm/model/chat-v2/index.js +1 -0
  34. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -1
  35. package/dist/esm/model/chat-v2/parallelToolCalls.js +38 -0
  36. package/dist/esm/model/chat-v2/toolContinuation.js +45 -8
  37. package/dist/esm/model/chat-v2/toolContinuationConnection.js +68 -0
  38. package/dist/esm/model/nodes/BuildKnowledgeContextNode.js +157 -0
  39. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
  40. package/dist/esm/model/nodes/GetKnowledgeSourceStatusNode.js +79 -0
  41. package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
  42. package/dist/esm/model/nodes/KnowledgeDocumentNode.js +88 -0
  43. package/dist/esm/model/nodes/KnowledgeSourceNode.js +94 -0
  44. package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
  45. package/dist/esm/model/nodes/MatchNode.js +7 -7
  46. package/dist/esm/model/nodes/SearchKnowledgeNode.js +127 -0
  47. package/dist/esm/model/nodes/SetStoredValueNode.js +84 -0
  48. package/dist/esm/model/nodes/StartBackgroundBranchNode.js +59 -0
  49. package/dist/esm/model/nodes/StoredValueNodeUtils.js +57 -0
  50. package/dist/esm/model/nodes/SyncKnowledgeSourceNode.js +149 -0
  51. package/dist/esm/model/nodes/ToolNode.js +14 -0
  52. package/dist/esm/model/nodes/toolCallDelegation.js +44 -1
  53. package/dist/esm/plugins/pinecone/PineconeKnowledgeStore.js +553 -0
  54. package/dist/esm/plugins/pinecone/plugin.js +32 -0
  55. package/dist/esm/recording/ExecutionRecorder.js +1 -0
  56. package/dist/esm/utils/coerceType.js +27 -2
  57. package/dist/esm/utils/getPluginConfig.js +12 -6
  58. package/dist/esm/utils/serialization/serialization.js +4 -1
  59. package/dist/esm/utils/serialization/serializationUtils.js +59 -1
  60. package/dist/esm/webAppRuntime.js +3 -3
  61. package/dist/types/api/createProcessor.d.ts +6 -0
  62. package/dist/types/exports.d.ts +7 -0
  63. package/dist/types/integrations/KnowledgeStore.d.ts +131 -0
  64. package/dist/types/integrations/KnowledgeStoreProvider.d.ts +46 -0
  65. package/dist/types/integrations/KnowledgeStoreValidation.d.ts +16 -0
  66. package/dist/types/integrations/ManagedKnowledgeStore.d.ts +57 -0
  67. package/dist/types/model/DataValue.d.ts +10 -3
  68. package/dist/types/model/EditorDefinition.d.ts +9 -2
  69. package/dist/types/model/ExecutorProtocol.d.ts +12 -0
  70. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
  71. package/dist/types/model/GraphProcessor.d.ts +21 -2
  72. package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
  73. package/dist/types/model/Nodes.d.ts +11 -2
  74. package/dist/types/model/ProcessContext.d.ts +18 -0
  75. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  76. package/dist/types/model/Project.d.ts +11 -0
  77. package/dist/types/model/StoredValueStore.d.ts +55 -0
  78. package/dist/types/model/SubprocessorBridge.d.ts +4 -2
  79. package/dist/types/model/ToolCallContinuation.d.ts +13 -0
  80. package/dist/types/model/UiGraph.d.ts +24 -1
  81. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  82. package/dist/types/model/UiGraphBrowserRuntime.d.ts +75 -0
  83. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
  84. package/dist/types/model/UiGraphRuntimeModel.d.ts +22 -3
  85. package/dist/types/model/UiGraphSchema.d.ts +113 -0
  86. package/dist/types/model/UiGraphWebAppStorage.d.ts +3 -0
  87. package/dist/types/model/chat-v2/index.d.ts +1 -0
  88. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +9 -0
  89. package/dist/types/model/chat-v2/toolContinuation.d.ts +1 -0
  90. package/dist/types/model/chat-v2/toolContinuationConnection.d.ts +28 -0
  91. package/dist/types/model/nodes/BuildKnowledgeContextNode.d.ts +23 -0
  92. package/dist/types/model/nodes/GetKnowledgeSourceStatusNode.d.ts +19 -0
  93. package/dist/types/model/nodes/GetStoredValueNode.d.ts +25 -0
  94. package/dist/types/model/nodes/KnowledgeDocumentNode.d.ts +26 -0
  95. package/dist/types/model/nodes/KnowledgeSourceNode.d.ts +25 -0
  96. package/dist/types/model/nodes/SearchKnowledgeNode.d.ts +25 -0
  97. package/dist/types/model/nodes/SetStoredValueNode.d.ts +23 -0
  98. package/dist/types/model/nodes/StartBackgroundBranchNode.d.ts +14 -0
  99. package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +5 -0
  100. package/dist/types/model/nodes/SyncKnowledgeSourceNode.d.ts +27 -0
  101. package/dist/types/model/nodes/ToolNode.d.ts +2 -0
  102. package/dist/types/model/nodes/toolCallDelegation.d.ts +4 -0
  103. package/dist/types/plugins/pinecone/PineconeKnowledgeStore.d.ts +11 -0
  104. package/dist/types/recording/RecordedEvents.d.ts +5 -0
  105. package/dist/types/utils/serialization/serializationUtils.d.ts +4 -0
  106. package/dist/types/webAppRuntime.d.ts +5 -4
  107. package/package.json +1 -1
@@ -0,0 +1,28 @@
1
+ export class ManagedAsyncBranches {
2
+ #pending = new Set();
3
+ #tailByKey = new Map();
4
+ get hasPending() {
5
+ return this.#pending.size > 0;
6
+ }
7
+ enqueue(key, run, onError) {
8
+ const previous = this.#tailByKey.get(key) ?? Promise.resolve();
9
+ const tracked = previous
10
+ .then(run)
11
+ .catch((error) => {
12
+ onError(error);
13
+ })
14
+ .finally(() => {
15
+ this.#pending.delete(tracked);
16
+ if (this.#tailByKey.get(key) === tracked) {
17
+ this.#tailByKey.delete(key);
18
+ }
19
+ });
20
+ this.#tailByKey.set(key, tracked);
21
+ this.#pending.add(tracked);
22
+ }
23
+ async drain() {
24
+ while (this.#pending.size > 0) {
25
+ await Promise.all([...this.#pending]);
26
+ }
27
+ }
28
+ }
@@ -64,12 +64,18 @@ import { didRunNode } from './nodes/DidRunNode.js';
64
64
  export * from './nodes/DidRunNode.js';
65
65
  import { passthroughNode } from './nodes/PassthroughNode.js';
66
66
  export * from './nodes/PassthroughNode.js';
67
+ import { startBackgroundBranchNode } from './nodes/StartBackgroundBranchNode.js';
68
+ export * from './nodes/StartBackgroundBranchNode.js';
67
69
  import { popNode } from './nodes/PopNode.js';
68
70
  export * from './nodes/PopNode.js';
69
71
  import { setGlobalNode } from './nodes/SetGlobalNode.js';
70
72
  export * from './nodes/SetGlobalNode.js';
71
73
  import { getGlobalNode } from './nodes/GetGlobalNode.js';
72
74
  export * from './nodes/GetGlobalNode.js';
75
+ import { setStoredValueNode } from './nodes/SetStoredValueNode.js';
76
+ export * from './nodes/SetStoredValueNode.js';
77
+ import { getStoredValueNode } from './nodes/GetStoredValueNode.js';
78
+ export * from './nodes/GetStoredValueNode.js';
73
79
  import { waitForEventNode } from './nodes/WaitForEventNode.js';
74
80
  export * from './nodes/WaitForEventNode.js';
75
81
  import { gptFunctionNode } from './nodes/ToolNode.js';
@@ -82,6 +88,18 @@ import { vectorStoreNode } from './nodes/VectorStoreNode.js';
82
88
  export * from './nodes/VectorStoreNode.js';
83
89
  import { vectorNearestNeighborsNode } from './nodes/VectorNearestNeighborsNode.js';
84
90
  export * from './nodes/VectorNearestNeighborsNode.js';
91
+ import { knowledgeSourceNode } from './nodes/KnowledgeSourceNode.js';
92
+ export * from './nodes/KnowledgeSourceNode.js';
93
+ import { knowledgeDocumentNode } from './nodes/KnowledgeDocumentNode.js';
94
+ export * from './nodes/KnowledgeDocumentNode.js';
95
+ import { syncKnowledgeSourceNode } from './nodes/SyncKnowledgeSourceNode.js';
96
+ export * from './nodes/SyncKnowledgeSourceNode.js';
97
+ import { getKnowledgeSourceStatusNode } from './nodes/GetKnowledgeSourceStatusNode.js';
98
+ export * from './nodes/GetKnowledgeSourceStatusNode.js';
99
+ import { searchKnowledgeNode } from './nodes/SearchKnowledgeNode.js';
100
+ export * from './nodes/SearchKnowledgeNode.js';
101
+ import { buildKnowledgeContextNode } from './nodes/BuildKnowledgeContextNode.js';
102
+ export * from './nodes/BuildKnowledgeContextNode.js';
85
103
  import { hashNode } from './nodes/HashNode.js';
86
104
  export * from './nodes/HashNode.js';
87
105
  import { abortGraphNode } from './nodes/AbortGraphNode.js';
@@ -217,14 +235,23 @@ export const registerBuiltInNodes = (registry) => {
217
235
  .register(coalesceNode)
218
236
  .register(didRunNode)
219
237
  .register(passthroughNode)
238
+ .register(startBackgroundBranchNode)
220
239
  .register(popNode)
221
240
  .register(setGlobalNode)
222
241
  .register(getGlobalNode)
242
+ .register(setStoredValueNode)
243
+ .register(getStoredValueNode)
223
244
  .register(waitForEventNode)
224
245
  .register(gptFunctionNode)
225
246
  .register(getEmbeddingNode)
226
247
  .register(vectorStoreNode)
227
248
  .register(vectorNearestNeighborsNode)
249
+ .register(knowledgeSourceNode)
250
+ .register(knowledgeDocumentNode)
251
+ .register(syncKnowledgeSourceNode)
252
+ .register(getKnowledgeSourceStatusNode)
253
+ .register(searchKnowledgeNode)
254
+ .register(buildKnowledgeContextNode)
228
255
  .register(hashNode)
229
256
  .register(abortGraphNode)
230
257
  .register(raceInputsNode)
@@ -1,5 +1,5 @@
1
1
  export function buildNodeProcessContext(options) {
2
- const { attachedData, activeOutputPortIds, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, node, nodeAbortController, onPartialOutputs, processId, requestUserInput, reportProgress, setGlobal, waitEvent, } = options;
2
+ const { attachedData, activeOutputPortIds, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, node, nodeAbortController, onPartialOutputs, processId, requestUserInput, reportProgress, setGlobal, toolCallContinuation, waitEvent, } = options;
3
3
  return {
4
4
  ...base,
5
5
  node,
@@ -16,6 +16,7 @@ export function buildNodeProcessContext(options) {
16
16
  getPluginConfig,
17
17
  requestUserInput,
18
18
  reportProgress,
19
+ toolCallContinuation,
19
20
  execution,
20
21
  };
21
22
  }
@@ -136,6 +136,15 @@ export async function replayExecutionRecording(options) {
136
136
  });
137
137
  break;
138
138
  }
139
+ case 'graphOutputsReady': {
140
+ const { data } = event;
141
+ emitDetached(emitter, 'graphOutputsReady', {
142
+ graph: getGraph(data.graphId),
143
+ outputs: data.outputs,
144
+ execution: getExecution(data.graphId, data.execution),
145
+ });
146
+ break;
147
+ }
139
148
  case 'graphError': {
140
149
  const { data } = event;
141
150
  emitDetached(emitter, 'graphError', {
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Run-scoped read-through/write-through cache used by Stored Value nodes.
3
+ * A GraphProcessor creates one controller per root run and shares it with every subprocessor.
4
+ */
5
+ export class RivetStoredValueController {
6
+ store;
7
+ #cache = new Map();
8
+ #keyOperations = new Map();
9
+ #loadErrors = new Map();
10
+ #waiters = new Map();
11
+ constructor(store) {
12
+ this.store = store;
13
+ }
14
+ async get(key) {
15
+ const normalizedKey = normalizeRivetStoredValueKey(key);
16
+ return await this.#withKeyLock(normalizedKey, async () => cloneReadResult(await this.#getUnlocked(normalizedKey)));
17
+ }
18
+ getCached(key) {
19
+ const normalizedKey = normalizeRivetStoredValueKey(key);
20
+ const cached = this.#cache.get(normalizedKey);
21
+ if (!cached)
22
+ return { loaded: false, found: false };
23
+ return cached.found
24
+ ? { loaded: true, found: true, value: cloneRivetStoredValue(cached.value, 'Stored value') }
25
+ : { loaded: true, found: false };
26
+ }
27
+ async set(key, value) {
28
+ const normalizedKey = normalizeRivetStoredValueKey(key);
29
+ const savedValue = cloneRivetStoredValue(value, 'Stored value');
30
+ return await this.#withKeyLock(normalizedKey, async () => {
31
+ const previous = await this.#getUnlocked(normalizedKey);
32
+ await this.store?.set(normalizedKey, cloneRivetStoredValue(savedValue, 'Stored value'));
33
+ this.#cache.set(normalizedKey, { found: true, value: savedValue });
34
+ this.#resolveWaiters(normalizedKey, savedValue);
35
+ return {
36
+ hadPreviousValue: previous.found,
37
+ previousValue: previous.found ? cloneRivetStoredValue(previous.value, 'Stored value') : undefined,
38
+ savedValue: cloneRivetStoredValue(savedValue, 'Stored value'),
39
+ };
40
+ });
41
+ }
42
+ /** Seeds the run cache without writing to the backing store, used for frozen Set-node replay. */
43
+ async seed(key, value) {
44
+ const normalizedKey = normalizeRivetStoredValueKey(key);
45
+ const savedValue = cloneRivetStoredValue(value, 'Stored value');
46
+ await this.#withKeyLock(normalizedKey, () => {
47
+ this.#cache.set(normalizedKey, { found: true, value: savedValue });
48
+ this.#resolveWaiters(normalizedKey, savedValue);
49
+ });
50
+ }
51
+ async waitForSet(key, signal) {
52
+ const normalizedKey = normalizeRivetStoredValueKey(key);
53
+ let immediateValue;
54
+ let waiterPromise;
55
+ signal?.throwIfAborted();
56
+ await this.#withKeyLock(normalizedKey, async () => {
57
+ signal?.throwIfAborted();
58
+ const current = await this.#getUnlocked(normalizedKey);
59
+ signal?.throwIfAborted();
60
+ if (current.found) {
61
+ immediateValue = cloneRivetStoredValue(current.value, 'Stored value');
62
+ return;
63
+ }
64
+ waiterPromise = new Promise((resolve, reject) => {
65
+ const waiter = { resolve, reject };
66
+ const waiters = this.#waiters.get(normalizedKey) ?? new Set();
67
+ waiters.add(waiter);
68
+ this.#waiters.set(normalizedKey, waiters);
69
+ if (!signal)
70
+ return;
71
+ const onAbort = () => {
72
+ waiters.delete(waiter);
73
+ if (waiters.size === 0)
74
+ this.#waiters.delete(normalizedKey);
75
+ reject(signal.reason ?? new Error('Stored value wait was aborted.'));
76
+ };
77
+ if (signal.aborted) {
78
+ onAbort();
79
+ }
80
+ else {
81
+ signal.addEventListener('abort', onAbort, { once: true });
82
+ const originalResolve = waiter.resolve;
83
+ waiter.resolve = (resolvedValue) => {
84
+ signal.removeEventListener('abort', onAbort);
85
+ originalResolve(resolvedValue);
86
+ };
87
+ }
88
+ });
89
+ });
90
+ signal?.throwIfAborted();
91
+ if (immediateValue !== undefined)
92
+ return immediateValue;
93
+ return await waiterPromise;
94
+ }
95
+ async #getUnlocked(key) {
96
+ const cached = this.#cache.get(key);
97
+ if (cached)
98
+ return cached;
99
+ if (this.#loadErrors.has(key))
100
+ throw this.#loadErrors.get(key);
101
+ try {
102
+ const loaded = await this.store?.get(key);
103
+ const result = loaded === undefined
104
+ ? { found: false }
105
+ : { found: true, value: cloneRivetStoredValue(loaded, 'Stored value returned by the store') };
106
+ this.#cache.set(key, result);
107
+ return result;
108
+ }
109
+ catch (error) {
110
+ this.#loadErrors.set(key, error);
111
+ throw error;
112
+ }
113
+ }
114
+ #resolveWaiters(key, value) {
115
+ const waiters = this.#waiters.get(key);
116
+ if (!waiters)
117
+ return;
118
+ this.#waiters.delete(key);
119
+ for (const waiter of waiters) {
120
+ waiter.resolve(cloneRivetStoredValue(value, 'Stored value'));
121
+ }
122
+ }
123
+ async #withKeyLock(key, operation) {
124
+ const previous = this.#keyOperations.get(key) ?? Promise.resolve();
125
+ let release;
126
+ const gate = new Promise((resolve) => {
127
+ release = resolve;
128
+ });
129
+ const current = previous.catch(() => undefined).then(() => gate);
130
+ this.#keyOperations.set(key, current);
131
+ await previous.catch(() => undefined);
132
+ try {
133
+ return await operation();
134
+ }
135
+ finally {
136
+ release();
137
+ if (this.#keyOperations.get(key) === current)
138
+ this.#keyOperations.delete(key);
139
+ }
140
+ }
141
+ }
142
+ export function createRivetStoredValueSnapshotStore(initialValues = {}) {
143
+ const currentValues = cloneRivetStoredValueRecord(initialValues, 'Stored value snapshot');
144
+ const patch = {};
145
+ return {
146
+ store: {
147
+ get(key) {
148
+ const normalizedKey = normalizeRivetStoredValueKey(key);
149
+ return Object.prototype.hasOwnProperty.call(currentValues, normalizedKey)
150
+ ? cloneRivetStoredValue(currentValues[normalizedKey], 'Stored value')
151
+ : undefined;
152
+ },
153
+ set(key, value) {
154
+ const normalizedKey = normalizeRivetStoredValueKey(key);
155
+ const cloned = cloneRivetStoredValue(value, 'Stored value');
156
+ setStoredValueRecordEntry(currentValues, normalizedKey, cloned);
157
+ setStoredValueRecordEntry(patch, normalizedKey, cloneRivetStoredValue(cloned, 'Stored value'));
158
+ },
159
+ },
160
+ getPatch: () => cloneRivetStoredValueRecord(patch, 'Stored value patch'),
161
+ };
162
+ }
163
+ export function normalizeRivetStoredValueKey(value) {
164
+ if (typeof value !== 'string' || !value.trim()) {
165
+ throw new Error('Stored value key must be a non-empty string.');
166
+ }
167
+ return value;
168
+ }
169
+ function setStoredValueRecordEntry(record, key, value) {
170
+ // Defining an own data property keeps all non-empty JSON string keys safe, including __proto__.
171
+ Object.defineProperty(record, key, { configurable: true, enumerable: true, value, writable: true });
172
+ }
173
+ export function cloneRivetStoredValue(value, label = 'Stored value') {
174
+ return clonePortableValue(value, label, new Set());
175
+ }
176
+ export function cloneRivetStoredValueRecord(value, label = 'Stored value record') {
177
+ const cloned = cloneRivetStoredValue(value, label);
178
+ if (!isPlainRecord(cloned))
179
+ throw new Error(`${label} must be a JSON object.`);
180
+ for (const key of Object.keys(cloned))
181
+ normalizeRivetStoredValueKey(key);
182
+ return cloned;
183
+ }
184
+ function cloneReadResult(result) {
185
+ return result.found ? { found: true, value: cloneRivetStoredValue(result.value, 'Stored value') } : { found: false };
186
+ }
187
+ function clonePortableValue(value, label, ancestors) {
188
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
189
+ return value;
190
+ if (typeof value === 'number') {
191
+ if (!Number.isFinite(value))
192
+ throw new Error(`${label} must contain only finite numbers.`);
193
+ return value;
194
+ }
195
+ if (typeof value !== 'object') {
196
+ throw new Error(`${label} must contain only portable JSON values.`);
197
+ }
198
+ if (ancestors.has(value))
199
+ throw new Error(`${label} must not contain cycles.`);
200
+ ancestors.add(value);
201
+ try {
202
+ if (Array.isArray(value)) {
203
+ const cloned = [];
204
+ for (let index = 0; index < value.length; index += 1) {
205
+ if (!Object.prototype.hasOwnProperty.call(value, index)) {
206
+ throw new Error(`${label} must not contain sparse arrays.`);
207
+ }
208
+ cloned.push(clonePortableValue(value[index], label, ancestors));
209
+ }
210
+ return cloned;
211
+ }
212
+ if (!isPlainRecord(value)) {
213
+ throw new Error(`${label} must contain only plain JSON objects and arrays.`);
214
+ }
215
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clonePortableValue(item, label, ancestors)]));
216
+ }
217
+ finally {
218
+ ancestors.delete(value);
219
+ }
220
+ }
221
+ function isPlainRecord(value) {
222
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
223
+ return false;
224
+ const prototype = Object.getPrototypeOf(value);
225
+ return prototype === Object.prototype || prototype === null;
226
+ }
@@ -24,20 +24,22 @@ export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
24
24
  // graph-level terminal event. Keep passive forwarding alive for the
25
25
  // subprocessor object lifetime so remote-debugger/recorder consumers do not
26
26
  // miss those node terminals.
27
- processor.on('nodeError', (event) => parentEmitter.emit('nodeError', event));
28
- processor.on('nodeFinish', (event) => parentEmitter.emit('nodeFinish', event));
29
- processor.on('partialOutput', (event) => parentEmitter.emit('partialOutput', event));
30
- processor.on('progress', (event) => parentEmitter.emit('progress', event));
31
- processor.on('nodeExcluded', (event) => parentEmitter.emit('nodeExcluded', event));
32
- processor.on('nodeStart', (event) => parentEmitter.emit('nodeStart', event));
33
- processor.on('graphAbort', (event) => parentEmitter.emit('graphAbort', event));
34
- processor.on('graphError', (event) => parentEmitter.emit('graphError', event));
35
- processor.on('userInput', (event) => parentEmitter.emit('userInput', event));
36
- processor.on('graphStart', (event) => parentEmitter.emit('graphStart', event));
37
- processor.on('graphFinish', (event) => parentEmitter.emit('graphFinish', event));
38
- processor.on('nodeOutputsCleared', (event) => parentEmitter.emit('nodeOutputsCleared', event));
39
- processor.on('globalSet', (event) => parentEmitter.emit('globalSet', event));
40
- processor.on('newAbortController', (event) => parentEmitter.emit('newAbortController', event));
27
+ const passiveUnsubscribers = [
28
+ processor.on('nodeError', (event) => parentEmitter.emit('nodeError', event)),
29
+ processor.on('nodeFinish', (event) => parentEmitter.emit('nodeFinish', event)),
30
+ processor.on('partialOutput', (event) => parentEmitter.emit('partialOutput', event)),
31
+ processor.on('progress', (event) => parentEmitter.emit('progress', event)),
32
+ processor.on('nodeExcluded', (event) => parentEmitter.emit('nodeExcluded', event)),
33
+ processor.on('nodeStart', (event) => parentEmitter.emit('nodeStart', event)),
34
+ processor.on('graphAbort', (event) => parentEmitter.emit('graphAbort', event)),
35
+ processor.on('graphError', (event) => parentEmitter.emit('graphError', event)),
36
+ processor.on('userInput', (event) => parentEmitter.emit('userInput', event)),
37
+ processor.on('graphStart', (event) => parentEmitter.emit('graphStart', event)),
38
+ processor.on('graphFinish', (event) => parentEmitter.emit('graphFinish', event)),
39
+ processor.on('nodeOutputsCleared', (event) => parentEmitter.emit('nodeOutputsCleared', event)),
40
+ processor.on('globalSet', (event) => parentEmitter.emit('globalSet', event)),
41
+ processor.on('newAbortController', (event) => parentEmitter.emit('newAbortController', event)),
42
+ ];
41
43
  const controlUnsubscribers = [
42
44
  processor.on('pause', () => {
43
45
  if (!parentState.isPaused()) {
@@ -50,7 +52,7 @@ export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
50
52
  }
51
53
  }),
52
54
  ];
53
- processor.onAny((event, data) => {
55
+ const unsubscribeAny = processor.onAny((event, data) => {
54
56
  if (event.startsWith('globalSet:')) {
55
57
  void parentEmitter.emit(event, data);
56
58
  }
@@ -63,16 +65,35 @@ export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
63
65
  controlsCleanedUp = true;
64
66
  controlUnsubscribers.forEach((unsubscribe) => unsubscribe());
65
67
  };
66
- controlUnsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanupControls));
68
+ if (parentState.autoCleanup !== false) {
69
+ controlUnsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanupControls));
70
+ }
71
+ return () => {
72
+ cleanupControls();
73
+ passiveUnsubscribers.forEach((unsubscribe) => unsubscribe());
74
+ unsubscribeAny();
75
+ };
67
76
  }
68
77
  export function wireSubprocessorLifecycle(processor, options) {
78
+ let unsubscribePendingAbort;
79
+ const abortProcessor = (successful, error) => {
80
+ if (processor.isRunning) {
81
+ void processor.abort(successful, error);
82
+ return;
83
+ }
84
+ unsubscribePendingAbort ??= processor.on('graphStart', () => {
85
+ unsubscribePendingAbort?.();
86
+ unsubscribePendingAbort = undefined;
87
+ void processor.abort(successful, error);
88
+ });
89
+ };
69
90
  const abortFromSignal = () => {
70
91
  const abortReason = getGraphAbortReasonFromSignal(options.signal);
71
- void processor.abort(abortReason?.successful ?? false, abortReason?.error);
92
+ abortProcessor(abortReason?.successful ?? false, abortReason?.error);
72
93
  };
73
94
  const abortFromParent = () => {
74
95
  const abortReason = getGraphAbortReasonFromSignal(options.parentAbortSignal);
75
- void processor.abort(abortReason?.successful ?? false, abortReason?.error);
96
+ abortProcessor(abortReason?.successful ?? false, abortReason?.error);
76
97
  };
77
98
  const pauseProcessor = () => {
78
99
  void processor.pause();
@@ -85,6 +106,7 @@ export function wireSubprocessorLifecycle(processor, options) {
85
106
  const unsubscribers = [
86
107
  () => options.signal?.removeEventListener('abort', abortFromSignal),
87
108
  () => options.parentAbortSignal.removeEventListener('abort', abortFromParent),
109
+ () => unsubscribePendingAbort?.(),
88
110
  options.onParentPause(pauseProcessor),
89
111
  options.onParentResume(resumeProcessor),
90
112
  ];
@@ -96,5 +118,14 @@ export function wireSubprocessorLifecycle(processor, options) {
96
118
  cleanedUp = true;
97
119
  unsubscribers.forEach((unsubscribe) => unsubscribe());
98
120
  };
99
- unsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanup));
121
+ if (options.autoCleanup !== false) {
122
+ unsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanup));
123
+ }
124
+ if (options.signal?.aborted) {
125
+ abortFromSignal();
126
+ }
127
+ else if (options.parentAbortSignal.aborted) {
128
+ abortFromParent();
129
+ }
130
+ return cleanup;
100
131
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -93,9 +93,13 @@ export function getUiGraphInitialState(uiGraph) {
93
93
  if (component.type === 'input' || component.type === 'textarea') {
94
94
  state[component.stateKey] = component.defaultValue ?? '';
95
95
  }
96
+ else if (component.type === 'dropdown') {
97
+ state[component.stateKey] = '';
98
+ }
96
99
  else if (component.type === 'chat') {
97
100
  state[getUiGraphChatDraftStateKey(component.id)] = '';
98
101
  state[getUiGraphChatMessagesStateKey(component.id)] = [];
102
+ state[getUiGraphChatPinsStateKey(component.id)] = [];
99
103
  }
100
104
  }
101
105
  return state;
@@ -109,11 +113,57 @@ export function getUiGraphChatDraftStateKey(componentId) {
109
113
  export function getUiGraphChatMessagesStateKey(componentId) {
110
114
  return `__rivet_chat_${componentId}_messages`;
111
115
  }
116
+ export function getUiGraphChatPinsStateKey(componentId) {
117
+ return `__rivet_chat_${componentId}_pins`;
118
+ }
112
119
  export function getUiGraphChatMessages(componentId, state) {
113
120
  const messages = state[getUiGraphChatMessagesStateKey(componentId)];
114
121
  return Array.isArray(messages) ? messages.filter(isUiGraphChatMessage) : [];
115
122
  }
116
- export function createUiGraphChatSubmissionStatePatch(componentId, state) {
123
+ export function getUiGraphChatPins(componentId, state) {
124
+ const messages = getUiGraphChatMessages(componentId, state);
125
+ const storedPins = state[getUiGraphChatPinsStateKey(componentId)];
126
+ const messageIndexes = Array.isArray(storedPins)
127
+ ? [
128
+ ...new Set(storedPins.filter((value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0)),
129
+ ].sort((left, right) => left - right)
130
+ : [];
131
+ const pinnedIndexes = new Set(messageIndexes);
132
+ const pins = [];
133
+ let prompt;
134
+ let promptMessageIndex;
135
+ messages.forEach((message, messageIndex) => {
136
+ if (message.role === 'user') {
137
+ prompt = message;
138
+ promptMessageIndex = messageIndex;
139
+ }
140
+ else if (pinnedIndexes.has(messageIndex)) {
141
+ pins.push({ messageIndex, prompt, promptMessageIndex, response: message });
142
+ }
143
+ });
144
+ return pins;
145
+ }
146
+ export function createUiGraphChatPinStatePatch(componentId, state, messageIndex) {
147
+ const messages = getUiGraphChatMessages(componentId, state);
148
+ if (messages[messageIndex]?.role !== 'assistant') {
149
+ return undefined;
150
+ }
151
+ const pinsStateKey = getUiGraphChatPinsStateKey(componentId);
152
+ const pinnedIndexes = getUiGraphChatPins(componentId, state).map((pin) => pin.messageIndex);
153
+ return {
154
+ [pinsStateKey]: pinnedIndexes.includes(messageIndex)
155
+ ? pinnedIndexes.filter((index) => index !== messageIndex)
156
+ : [...pinnedIndexes, messageIndex].sort((left, right) => left - right),
157
+ };
158
+ }
159
+ /** Clears a Chat's conversation and pins without discarding an unsent draft. */
160
+ export function createUiGraphChatHistoryFlushStatePatch(componentId) {
161
+ return {
162
+ [getUiGraphChatMessagesStateKey(componentId)]: [],
163
+ [getUiGraphChatPinsStateKey(componentId)]: [],
164
+ };
165
+ }
166
+ export function createUiGraphChatSubmissionStatePatch(componentId, state, timestamp = new Date().toISOString()) {
117
167
  const draftStateKey = getUiGraphChatDraftStateKey(componentId);
118
168
  const content = `${state[draftStateKey] ?? ''}`.trim();
119
169
  if (!content) {
@@ -123,7 +173,7 @@ export function createUiGraphChatSubmissionStatePatch(componentId, state) {
123
173
  [draftStateKey]: '',
124
174
  [getUiGraphChatMessagesStateKey(componentId)]: [
125
175
  ...getUiGraphChatMessages(componentId, state),
126
- { role: 'user', content },
176
+ { role: 'user', content, timestamp },
127
177
  ],
128
178
  };
129
179
  }
@@ -12,12 +12,14 @@ export function parseRivetWebAppClientMessage(value) {
12
12
  return isNonEmptyString(value.requestId) &&
13
13
  isNonEmptyString(value.componentId) &&
14
14
  isRecord(value.state) &&
15
+ (value.storage == null || isRecord(value.storage)) &&
15
16
  (value.revisionKey == null || typeof value.revisionKey === 'string')
16
17
  ? {
17
18
  type: value.type,
18
19
  requestId: value.requestId,
19
20
  componentId: value.componentId,
20
21
  state: value.state,
22
+ ...(isRecord(value.storage) ? { storage: value.storage } : {}),
21
23
  ...(typeof value.revisionKey === 'string' ? { revisionKey: value.revisionKey } : {}),
22
24
  }
23
25
  : undefined;
@@ -85,7 +87,14 @@ export function parseRivetWebAppServerMessage(value) {
85
87
  return progress ? { type: value.type, ...base, progress } : undefined;
86
88
  }
87
89
  case 'action.completed':
88
- return isRecord(value.statePatch) ? { type: value.type, ...base, statePatch: value.statePatch } : undefined;
90
+ return isRecord(value.statePatch) && (value.storagePatch == null || isRecord(value.storagePatch))
91
+ ? {
92
+ type: value.type,
93
+ ...base,
94
+ statePatch: value.statePatch,
95
+ ...(isRecord(value.storagePatch) ? { storagePatch: value.storagePatch } : {}),
96
+ }
97
+ : undefined;
89
98
  case 'action.failed':
90
99
  return isNonEmptyString(value.error)
91
100
  ? {