@valerypopoff/rivet2-core 2.1.5 → 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 (65) hide show
  1. package/dist/cjs/bundle.cjs +3154 -289
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +129 -4
  4. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  5. package/dist/esm/api/createProcessor.js +1 -0
  6. package/dist/esm/exports.js +4 -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/GraphProcessor.js +14 -0
  13. package/dist/esm/model/Nodes.js +18 -0
  14. package/dist/esm/model/UiGraph.js +2 -2
  15. package/dist/esm/model/UiGraphBrowserRuntime.js +112 -1
  16. package/dist/esm/model/UiGraphRendererStyles.js +111 -9
  17. package/dist/esm/model/UiGraphRuntimeModel.js +26 -2
  18. package/dist/esm/model/chat/openAIChatRequest.js +8 -2
  19. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +8 -8
  20. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -1
  21. package/dist/esm/model/chat-v2/parallelToolCalls.js +38 -0
  22. package/dist/esm/model/chat-v2/toolContinuation.js +39 -0
  23. package/dist/esm/model/nodes/BuildKnowledgeContextNode.js +157 -0
  24. package/dist/esm/model/nodes/GetKnowledgeSourceStatusNode.js +79 -0
  25. package/dist/esm/model/nodes/KnowledgeDocumentNode.js +88 -0
  26. package/dist/esm/model/nodes/KnowledgeSourceNode.js +94 -0
  27. package/dist/esm/model/nodes/SearchKnowledgeNode.js +127 -0
  28. package/dist/esm/model/nodes/StoredValueNodeUtils.js +10 -0
  29. package/dist/esm/model/nodes/SyncKnowledgeSourceNode.js +149 -0
  30. package/dist/esm/model/nodes/ToolNode.js +14 -0
  31. package/dist/esm/plugins/pinecone/PineconeKnowledgeStore.js +553 -0
  32. package/dist/esm/plugins/pinecone/plugin.js +32 -0
  33. package/dist/esm/utils/coerceType.js +24 -2
  34. package/dist/esm/utils/getPluginConfig.js +12 -6
  35. package/dist/esm/utils/serialization/serialization.js +4 -1
  36. package/dist/esm/utils/serialization/serializationUtils.js +59 -1
  37. package/dist/esm/webAppRuntime.js +1 -1
  38. package/dist/types/api/createProcessor.d.ts +2 -0
  39. package/dist/types/exports.d.ts +4 -0
  40. package/dist/types/integrations/KnowledgeStore.d.ts +131 -0
  41. package/dist/types/integrations/KnowledgeStoreProvider.d.ts +46 -0
  42. package/dist/types/integrations/KnowledgeStoreValidation.d.ts +16 -0
  43. package/dist/types/integrations/ManagedKnowledgeStore.d.ts +57 -0
  44. package/dist/types/model/DataValue.d.ts +10 -3
  45. package/dist/types/model/EditorDefinition.d.ts +7 -1
  46. package/dist/types/model/GraphProcessor.d.ts +2 -0
  47. package/dist/types/model/Nodes.d.ts +8 -2
  48. package/dist/types/model/ProcessContext.d.ts +3 -0
  49. package/dist/types/model/Project.d.ts +11 -0
  50. package/dist/types/model/UiGraph.d.ts +3 -1
  51. package/dist/types/model/UiGraphBrowserRuntime.d.ts +25 -1
  52. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  53. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +9 -0
  54. package/dist/types/model/nodes/BuildKnowledgeContextNode.d.ts +23 -0
  55. package/dist/types/model/nodes/GetKnowledgeSourceStatusNode.d.ts +19 -0
  56. package/dist/types/model/nodes/KnowledgeDocumentNode.d.ts +26 -0
  57. package/dist/types/model/nodes/KnowledgeSourceNode.d.ts +25 -0
  58. package/dist/types/model/nodes/SearchKnowledgeNode.d.ts +25 -0
  59. package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +1 -1
  60. package/dist/types/model/nodes/SyncKnowledgeSourceNode.d.ts +27 -0
  61. package/dist/types/model/nodes/ToolNode.d.ts +2 -0
  62. package/dist/types/plugins/pinecone/PineconeKnowledgeStore.d.ts +11 -0
  63. package/dist/types/utils/serialization/serializationUtils.d.ts +4 -0
  64. package/dist/types/webAppRuntime.d.ts +2 -1
  65. package/package.json +1 -1
@@ -0,0 +1,539 @@
1
+ import CryptoJS from 'crypto-js';
2
+ import stableStringify from 'safe-stable-stringify';
3
+ import { normalizeKnowledgeDocument, normalizeKnowledgeEvidence, normalizeKnowledgeFilter, normalizeKnowledgeMetadata, normalizeKnowledgeQueries, normalizeKnowledgeSourceReference, } from './KnowledgeStoreValidation.js';
4
+ const MANAGED_SCHEMA_VERSION = '1';
5
+ const CHUNKER_VERSION = '1';
6
+ /**
7
+ * Provides deterministic chunking, immutable version activation, idempotency,
8
+ * same-process source serialization, and multi-query result fusion for drivers.
9
+ */
10
+ export class ManagedKnowledgeStore {
11
+ driver;
12
+ capabilities;
13
+ #sourceOperations = new Map();
14
+ constructor(driver) {
15
+ this.driver = driver;
16
+ this.capabilities = driver.capabilities;
17
+ }
18
+ async getSourceStatus(request, context) {
19
+ const source = normalizeKnowledgeSourceReference(request.source);
20
+ const expectedVersion = request.expectedVersion?.trim()
21
+ ? normalizeKnowledgeSourceReference({ ...source, version: request.expectedVersion }).version
22
+ : source.version;
23
+ const manifest = await this.#getManifest(source.sourceId, context);
24
+ if (!manifest) {
25
+ return {
26
+ exists: false,
27
+ source,
28
+ message: `Knowledge source "${source.sourceId}" has not been synchronized.`,
29
+ ...(expectedVersion ? { matchesExpectedVersion: false } : {}),
30
+ };
31
+ }
32
+ const resolvedSource = { ...source, version: manifest.activeVersion };
33
+ return {
34
+ exists: true,
35
+ source: resolvedSource,
36
+ activeVersion: manifest.activeVersion,
37
+ documentCount: manifest.documentCount,
38
+ chunkCount: manifest.chunkCount,
39
+ updatedAt: manifest.updatedAt,
40
+ metadata: manifest.metadata,
41
+ message: `Knowledge source "${source.sourceId}" is ready.`,
42
+ ...(expectedVersion ? { matchesExpectedVersion: expectedVersion === manifest.activeVersion } : {}),
43
+ };
44
+ }
45
+ async syncSource(request, context) {
46
+ const source = normalizeKnowledgeSourceReference(request.source);
47
+ return this.#serializeSourceOperation(source.sourceId, context.signal, () => this.#syncSource(source, request, context));
48
+ }
49
+ async search(request, context) {
50
+ const source = normalizeKnowledgeSourceReference(request.source);
51
+ const queries = normalizeKnowledgeQueries(request.queries);
52
+ validatePositiveInteger(request.topK, 'Results per query', 1, 100);
53
+ validatePositiveInteger(request.maxConcurrency, 'Search concurrency', 1, 32);
54
+ validatePositiveInteger(request.finalResultCount, 'Final result count', 1, 500);
55
+ validatePositiveInteger(request.rerank?.topN, 'Rerank result count', 1, 100);
56
+ if (request.rerank && request.rerank.mode !== 'connection-default' && request.rerank.mode !== 'required') {
57
+ throw new Error('Provider reranking mode must be connection-default or required.');
58
+ }
59
+ const filter = request.filter == null ? undefined : normalizeKnowledgeFilter(request.filter);
60
+ validateCapabilities(this.capabilities, filter, request.rerank);
61
+ const rerank = this.capabilities.supportsProviderReranking ? request.rerank : undefined;
62
+ const manifest = await this.#getManifest(source.sourceId, context);
63
+ if (!manifest) {
64
+ return {
65
+ sourceFound: false,
66
+ source,
67
+ evidence: [],
68
+ queryResults: [],
69
+ message: `Knowledge source "${source.sourceId}" has not been synchronized.`,
70
+ };
71
+ }
72
+ const requestedVersion = source.version?.trim();
73
+ if (requestedVersion && requestedVersion !== manifest.activeVersion) {
74
+ return {
75
+ sourceFound: false,
76
+ source,
77
+ evidence: [],
78
+ queryResults: [],
79
+ message: `Knowledge source "${source.sourceId}" is active at version "${manifest.activeVersion}", not requested version "${requestedVersion}".`,
80
+ };
81
+ }
82
+ const version = manifest.activeVersion;
83
+ const resolvedSource = { ...source, version };
84
+ const topK = request.topK ?? 10;
85
+ const searchAbortController = new AbortController();
86
+ const abortSearch = () => searchAbortController.abort(context.signal.reason);
87
+ if (context.signal.aborted)
88
+ abortSearch();
89
+ else
90
+ context.signal.addEventListener('abort', abortSearch, { once: true });
91
+ let queryResults;
92
+ try {
93
+ const searchContext = { ...context, signal: searchAbortController.signal };
94
+ queryResults = await mapConcurrent(queries, request.maxConcurrency ?? Math.min(queries.length, 3), async (query) => {
95
+ throwIfAborted(searchContext.signal);
96
+ const evidence = await this.driver.search({ sourceId: source.sourceId, version, query, topK, filter, rerank }, searchContext);
97
+ return {
98
+ query,
99
+ evidence: evidence.map((item) => normalizeKnowledgeEvidence({ ...item, source: resolvedSource })),
100
+ };
101
+ });
102
+ }
103
+ catch (error) {
104
+ searchAbortController.abort(error);
105
+ throw error;
106
+ }
107
+ finally {
108
+ context.signal.removeEventListener('abort', abortSearch);
109
+ }
110
+ const evidence = fuseEvidence(queryResults, request.finalResultCount ?? topK);
111
+ return {
112
+ sourceFound: true,
113
+ source: resolvedSource,
114
+ evidence,
115
+ queryResults,
116
+ message: evidence.length
117
+ ? `Found ${evidence.length} relevant knowledge result${evidence.length === 1 ? '' : 's'}.`
118
+ : 'The source is ready, but no relevant knowledge was found.',
119
+ };
120
+ }
121
+ async #syncSource(source, request, context) {
122
+ if (request.documents.length === 0)
123
+ throw new Error('Sync Knowledge Source requires at least one document.');
124
+ const documents = request.documents.map((document, index) => normalizeKnowledgeDocument(document, index));
125
+ const documentIds = resolveDocumentIds(documents);
126
+ validateUniqueDocumentIds(documentIds);
127
+ const metadata = request.metadata == null ? undefined : normalizeKnowledgeMetadata(request.metadata, 'Source metadata');
128
+ const chunking = normalizeChunkingOptions(request.chunking);
129
+ const version = createSourceVersion(documents, metadata, chunking);
130
+ const existing = await this.#getManifest(source.sourceId, context);
131
+ if (!request.forceRefresh && existing?.activeVersion === version) {
132
+ return {
133
+ source: { ...source, version },
134
+ result: 'unchanged',
135
+ previousVersion: existing.activeVersion,
136
+ documentCount: existing.documentCount,
137
+ chunkCount: existing.chunkCount,
138
+ warnings: [],
139
+ };
140
+ }
141
+ context.reportProgress?.({ message: `Preparing ${documents.length} knowledge document(s).`, percent: 5 });
142
+ const chunks = await chunkDocuments(documents, documentIds, version, chunking, context);
143
+ if (chunks.length === 0)
144
+ throw new Error('Sync Knowledge Source produced no non-empty chunks.');
145
+ context.reportProgress?.({ message: `Uploading ${chunks.length} knowledge chunk(s).`, percent: 15 });
146
+ await this.driver.upsertChunks(source.sourceId, version, chunks, context);
147
+ throwIfAborted(context.signal);
148
+ const manifest = {
149
+ schemaVersion: MANAGED_SCHEMA_VERSION,
150
+ sourceId: source.sourceId,
151
+ activeVersion: version,
152
+ commitId: createManifestCommitId(),
153
+ documentCount: documents.length,
154
+ chunkCount: chunks.length,
155
+ updatedAt: new Date().toISOString(),
156
+ ...(metadata && Object.keys(metadata).length ? { metadata } : {}),
157
+ };
158
+ context.reportProgress?.({ message: 'Committing the new knowledge-source version.', percent: 90 });
159
+ await this.driver.commitManifest(manifest, context);
160
+ const committed = await this.#getManifest(source.sourceId, context);
161
+ if (!sameManifestActivation(committed, manifest)) {
162
+ throw new Error(`Knowledge source "${source.sourceId}" did not retain its activation for version "${version}". Another writer may have updated the source concurrently.`);
163
+ }
164
+ const warnings = [];
165
+ if (existing?.activeVersion && existing.activeVersion !== version) {
166
+ let stillActive;
167
+ let cleanupVerificationFailed = false;
168
+ try {
169
+ stillActive = await this.#getManifest(source.sourceId, context);
170
+ }
171
+ catch (error) {
172
+ throwIfAborted(context.signal);
173
+ cleanupVerificationFailed = true;
174
+ warnings.push(`The new version is active, but cleanup verification failed: ${errorMessage(error)}`);
175
+ }
176
+ if (!cleanupVerificationFailed && !sameManifestActivation(stillActive, manifest)) {
177
+ throw new Error(`Knowledge source "${source.sourceId}" no longer has its activation for version "${version}" active. Another writer updated the source concurrently.`);
178
+ }
179
+ if (stillActive) {
180
+ try {
181
+ await this.driver.deleteVersion(source.sourceId, existing.activeVersion, context);
182
+ }
183
+ catch (error) {
184
+ throwIfAborted(context.signal);
185
+ warnings.push(`The new version is active, but stale-version cleanup failed: ${errorMessage(error)}`);
186
+ }
187
+ }
188
+ }
189
+ context.reportProgress?.({ message: 'Knowledge source is ready.', percent: 100 });
190
+ return {
191
+ source: { ...source, version },
192
+ result: existing ? 'updated' : 'created',
193
+ previousVersion: existing?.activeVersion,
194
+ documentCount: documents.length,
195
+ chunkCount: chunks.length,
196
+ warnings,
197
+ };
198
+ }
199
+ async #serializeSourceOperation(sourceId, signal, operation) {
200
+ const operations = this.driver.operationScope
201
+ ? getSharedSourceOperations(this.driver.operationScope)
202
+ : this.#sourceOperations;
203
+ const previous = operations.get(sourceId) ?? Promise.resolve();
204
+ let release;
205
+ const current = new Promise((resolve) => {
206
+ release = resolve;
207
+ });
208
+ const tail = previous.catch(() => undefined).then(() => current);
209
+ operations.set(sourceId, tail);
210
+ void tail.then(() => {
211
+ if (operations.get(sourceId) === tail) {
212
+ operations.delete(sourceId);
213
+ if (this.driver.operationScope)
214
+ removeEmptySharedSourceOperations(this.driver.operationScope, operations);
215
+ }
216
+ });
217
+ try {
218
+ await waitForPromiseOrAbort(previous.catch(() => undefined), signal);
219
+ return await operation();
220
+ }
221
+ finally {
222
+ release();
223
+ }
224
+ }
225
+ async #getManifest(sourceId, context) {
226
+ const manifest = await this.driver.getManifest(sourceId, context);
227
+ return manifest == null ? undefined : normalizeKnowledgeSourceManifest(manifest, sourceId);
228
+ }
229
+ }
230
+ const sharedSourceOperations = new Map();
231
+ function getSharedSourceOperations(scope) {
232
+ const normalizedScope = scope.trim();
233
+ if (!normalizedScope)
234
+ throw new Error('Managed knowledge-store operation scope cannot be empty.');
235
+ let operations = sharedSourceOperations.get(normalizedScope);
236
+ if (!operations) {
237
+ operations = new Map();
238
+ sharedSourceOperations.set(normalizedScope, operations);
239
+ }
240
+ return operations;
241
+ }
242
+ function removeEmptySharedSourceOperations(scope, operations) {
243
+ if (operations.size === 0 && sharedSourceOperations.get(scope.trim()) === operations) {
244
+ sharedSourceOperations.delete(scope.trim());
245
+ }
246
+ }
247
+ export function normalizeKnowledgeSourceManifest(value, expectedSourceId) {
248
+ if (!isRecord(value))
249
+ throw new Error(`Knowledge manifest for source "${expectedSourceId}" must be an object.`);
250
+ if (value.schemaVersion !== MANAGED_SCHEMA_VERSION) {
251
+ throw new Error(`Knowledge manifest for source "${expectedSourceId}" uses unsupported schema version "${String(value.schemaVersion)}".`);
252
+ }
253
+ if (value.sourceId !== expectedSourceId) {
254
+ throw new Error(`Knowledge manifest for source "${expectedSourceId}" belongs to another source.`);
255
+ }
256
+ const activeVersion = typeof value.activeVersion === 'string' ? value.activeVersion.trim() : '';
257
+ if (!activeVersion)
258
+ throw new Error(`Knowledge manifest for source "${expectedSourceId}" has no active version.`);
259
+ if (activeVersion.length > 512) {
260
+ throw new Error(`Knowledge manifest for source "${expectedSourceId}" has an invalid active version.`);
261
+ }
262
+ const commitId = value.commitId == null ? undefined : typeof value.commitId === 'string' ? value.commitId.trim() : '';
263
+ if (value.commitId != null && (!commitId || commitId.length > 128)) {
264
+ throw new Error(`Knowledge manifest for source "${expectedSourceId}" has an invalid commit ID.`);
265
+ }
266
+ const documentCount = normalizePositiveManifestCount(value.documentCount, 'document', expectedSourceId);
267
+ const chunkCount = normalizePositiveManifestCount(value.chunkCount, 'chunk', expectedSourceId);
268
+ const updatedAt = typeof value.updatedAt === 'string' ? value.updatedAt.trim() : '';
269
+ if (!updatedAt || !Number.isFinite(Date.parse(updatedAt))) {
270
+ throw new Error(`Knowledge manifest for source "${expectedSourceId}" has an invalid update time.`);
271
+ }
272
+ const metadata = value.metadata == null ? undefined : normalizeKnowledgeMetadata(value.metadata, 'Manifest metadata');
273
+ return {
274
+ schemaVersion: MANAGED_SCHEMA_VERSION,
275
+ sourceId: expectedSourceId,
276
+ activeVersion,
277
+ ...(commitId ? { commitId } : {}),
278
+ documentCount,
279
+ chunkCount,
280
+ updatedAt,
281
+ ...(metadata && Object.keys(metadata).length ? { metadata } : {}),
282
+ };
283
+ }
284
+ function normalizePositiveManifestCount(value, label, sourceId) {
285
+ if (!Number.isInteger(value) || value < 1) {
286
+ throw new Error(`Knowledge manifest for source "${sourceId}" has an invalid ${label} count.`);
287
+ }
288
+ return value;
289
+ }
290
+ async function waitForPromiseOrAbort(promise, signal) {
291
+ throwIfAborted(signal);
292
+ await new Promise((resolve, reject) => {
293
+ const abort = () => {
294
+ signal.removeEventListener('abort', abort);
295
+ reject(signal.reason ?? new Error('Knowledge operation was cancelled.'));
296
+ };
297
+ signal.addEventListener('abort', abort, { once: true });
298
+ promise.then(() => {
299
+ signal.removeEventListener('abort', abort);
300
+ resolve();
301
+ }, (error) => {
302
+ signal.removeEventListener('abort', abort);
303
+ reject(error);
304
+ });
305
+ });
306
+ }
307
+ export function createSourceVersion(documents, metadata, chunking) {
308
+ const canonical = stableStringify({
309
+ schemaVersion: MANAGED_SCHEMA_VERSION,
310
+ chunkerVersion: CHUNKER_VERSION,
311
+ documents,
312
+ metadata: metadata ?? {},
313
+ chunking,
314
+ });
315
+ const digest = CryptoJS.SHA256(canonical ?? '').toString(CryptoJS.enc.Hex);
316
+ return `ks${MANAGED_SCHEMA_VERSION}-${digest}`;
317
+ }
318
+ function normalizeChunkingOptions(options) {
319
+ if (options?.unit != null && options.unit !== 'characters' && options.unit !== 'tokens') {
320
+ throw new Error('Chunk size unit must be characters or tokens.');
321
+ }
322
+ if (options?.includeTitle != null && typeof options.includeTitle !== 'boolean') {
323
+ throw new Error('Include Title In Indexed Text must be a boolean.');
324
+ }
325
+ const unit = options?.unit ?? 'characters';
326
+ const targetSize = options?.targetSize ?? (unit === 'tokens' ? 700 : 2600);
327
+ const overlap = options?.overlap ?? (unit === 'tokens' ? 80 : 260);
328
+ const minimumBoundarySize = options?.minimumBoundarySize ?? Math.floor(targetSize * 0.55);
329
+ validatePositiveInteger(targetSize, 'Chunk target size', 100, 100_000);
330
+ validatePositiveInteger(overlap, 'Chunk overlap', 0, targetSize - 1);
331
+ validatePositiveInteger(minimumBoundarySize, 'Minimum boundary size', 1, targetSize);
332
+ return { unit, targetSize, overlap, minimumBoundarySize, includeTitle: options?.includeTitle !== false };
333
+ }
334
+ function createManifestCommitId() {
335
+ return CryptoJS.lib.WordArray.random(16).toString(CryptoJS.enc.Hex);
336
+ }
337
+ async function chunkDocuments(documents, documentIds, version, options, context) {
338
+ const chunks = [];
339
+ for (let documentIndex = 0; documentIndex < documents.length; documentIndex += 1) {
340
+ throwIfAborted(context.signal);
341
+ const document = documents[documentIndex];
342
+ const documentId = documentIds[documentIndex];
343
+ const pieces = options.unit === 'tokens'
344
+ ? await splitByTokens(document.text, options, context)
345
+ : splitByCharacters(document.text, options);
346
+ const safeDocumentId = createShortHash(documentId);
347
+ pieces.forEach((piece, chunkIndex) => {
348
+ const prefix = options.includeTitle && document.title ? `${document.title}\n\n` : '';
349
+ chunks.push({
350
+ id: `${version}-${safeDocumentId}-${String(chunkIndex).padStart(5, '0')}`,
351
+ text: `${prefix}${piece}`,
352
+ documentId,
353
+ ...(document.title ? { title: document.title } : {}),
354
+ chunkIndex,
355
+ chunksInDocument: pieces.length,
356
+ ...(document.metadata ? { metadata: document.metadata } : {}),
357
+ });
358
+ });
359
+ context.reportProgress?.({
360
+ message: `Prepared document ${documentIndex + 1} of ${documents.length}.`,
361
+ percent: 5 + Math.round(((documentIndex + 1) / documents.length) * 10),
362
+ });
363
+ }
364
+ return chunks;
365
+ }
366
+ function resolveDocumentIds(documents) {
367
+ return documents.map((document, documentIndex) => document.id?.trim() || createShortHash(`${documentIndex}:${document.title ?? ''}:${document.text}`));
368
+ }
369
+ function validateUniqueDocumentIds(documentIds) {
370
+ const seen = new Set();
371
+ for (const documentId of documentIds) {
372
+ if (seen.has(documentId)) {
373
+ throw new Error(`Sync Knowledge Source contains duplicate document ID "${documentId}".`);
374
+ }
375
+ seen.add(documentId);
376
+ }
377
+ }
378
+ function splitByCharacters(text, options) {
379
+ const chunks = [];
380
+ let start = 0;
381
+ while (start < text.length) {
382
+ let end = Math.min(text.length, start + options.targetSize);
383
+ if (end < text.length)
384
+ end = findBoundary(text, start, end, options.minimumBoundarySize);
385
+ const chunk = text.slice(start, end).trim();
386
+ if (chunk)
387
+ chunks.push(chunk);
388
+ if (end >= text.length)
389
+ break;
390
+ start = Math.max(start + 1, end - options.overlap);
391
+ }
392
+ return chunks;
393
+ }
394
+ async function splitByTokens(text, options, context) {
395
+ const getTokenCount = context.getTokenCount;
396
+ if (!getTokenCount)
397
+ throw new Error('Token-based knowledge chunking requires a runtime tokenizer.');
398
+ const chunks = [];
399
+ let start = 0;
400
+ while (start < text.length) {
401
+ let low = Math.min(text.length, start + 1);
402
+ let high = text.length;
403
+ let best = low;
404
+ while (low <= high) {
405
+ throwIfAborted(context.signal);
406
+ const middle = Math.floor((low + high) / 2);
407
+ const count = await getTokenCount(text.slice(start, middle));
408
+ if (count <= options.targetSize) {
409
+ best = middle;
410
+ low = middle + 1;
411
+ }
412
+ else {
413
+ high = middle - 1;
414
+ }
415
+ }
416
+ let end = best;
417
+ if (end < text.length) {
418
+ const minCharacters = Math.max(1, Math.floor((end - start) * (options.minimumBoundarySize / options.targetSize)));
419
+ end = findBoundary(text, start, end, minCharacters);
420
+ }
421
+ const chunk = text.slice(start, end).trim();
422
+ if (chunk)
423
+ chunks.push(chunk);
424
+ if (end >= text.length)
425
+ break;
426
+ const overlapStart = options.overlap > 0
427
+ ? await findTokenOverlapStart(text, start, end, options.overlap, getTokenCount, context.signal)
428
+ : end;
429
+ start = Math.max(start + 1, overlapStart);
430
+ }
431
+ return chunks;
432
+ }
433
+ async function findTokenOverlapStart(text, chunkStart, chunkEnd, overlapTokens, getTokenCount, signal) {
434
+ let low = chunkStart;
435
+ let high = chunkEnd;
436
+ let best = chunkEnd;
437
+ while (low <= high) {
438
+ throwIfAborted(signal);
439
+ const middle = Math.floor((low + high) / 2);
440
+ const count = await getTokenCount(text.slice(middle, chunkEnd));
441
+ if (count <= overlapTokens) {
442
+ best = middle;
443
+ high = middle - 1;
444
+ }
445
+ else {
446
+ low = middle + 1;
447
+ }
448
+ }
449
+ return best;
450
+ }
451
+ function findBoundary(text, start, proposedEnd, minimumSize) {
452
+ const minimumEnd = start + minimumSize;
453
+ const candidates = [
454
+ text.lastIndexOf('\n\n', proposedEnd),
455
+ text.lastIndexOf('\n', proposedEnd),
456
+ text.lastIndexOf('. ', proposedEnd),
457
+ text.lastIndexOf('! ', proposedEnd),
458
+ text.lastIndexOf('? ', proposedEnd),
459
+ ];
460
+ const boundary = Math.max(...candidates);
461
+ return boundary >= minimumEnd ? boundary + 1 : proposedEnd;
462
+ }
463
+ function fuseEvidence(queryResults, limit) {
464
+ const byId = new Map();
465
+ let firstSeen = 0;
466
+ for (const result of queryResults) {
467
+ result.evidence.forEach((evidence, rank) => {
468
+ const contribution = 1 / (60 + rank + 1);
469
+ const current = byId.get(evidence.id);
470
+ if (current)
471
+ current.score += contribution;
472
+ else
473
+ byId.set(evidence.id, { evidence, score: contribution, firstSeen: firstSeen++ });
474
+ });
475
+ }
476
+ return [...byId.values()]
477
+ .sort((left, right) => right.score - left.score || left.firstSeen - right.firstSeen)
478
+ .slice(0, limit)
479
+ .map(({ evidence }) => evidence);
480
+ }
481
+ function validateCapabilities(capabilities, filter, rerank) {
482
+ if (rerank?.mode === 'required' && !capabilities.supportsProviderReranking) {
483
+ throw new Error('The selected knowledge store does not support provider-side reranking.');
484
+ }
485
+ if (!filter)
486
+ return;
487
+ const supported = new Set(capabilities.supportedFilterOperators ?? []);
488
+ for (const operator of collectFilterOperators(filter)) {
489
+ if (!supported.has(operator))
490
+ throw new Error(`The selected knowledge store does not support the "${operator}" filter operator.`);
491
+ }
492
+ }
493
+ function collectFilterOperators(filter) {
494
+ if ('operator' in filter)
495
+ return [filter.operator];
496
+ if ('and' in filter)
497
+ return filter.and.flatMap(collectFilterOperators);
498
+ if ('or' in filter)
499
+ return filter.or.flatMap(collectFilterOperators);
500
+ return collectFilterOperators(filter.not);
501
+ }
502
+ async function mapConcurrent(items, concurrency, mapper) {
503
+ const results = new Array(items.length);
504
+ let next = 0;
505
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
506
+ while (next < items.length) {
507
+ const index = next++;
508
+ results[index] = await mapper(items[index]);
509
+ }
510
+ });
511
+ await Promise.all(workers);
512
+ return results;
513
+ }
514
+ function validatePositiveInteger(value, label, minimum, maximum) {
515
+ if (value == null)
516
+ return;
517
+ if (!Number.isInteger(value) || value < minimum || value > maximum) {
518
+ throw new Error(`${label} must be an integer between ${minimum} and ${maximum}.`);
519
+ }
520
+ }
521
+ function createShortHash(value) {
522
+ return CryptoJS.SHA256(value).toString(CryptoJS.enc.Hex).slice(0, 24);
523
+ }
524
+ function sameManifestActivation(actual, expected) {
525
+ return actual?.activeVersion === expected.activeVersion && actual.commitId === expected.commitId;
526
+ }
527
+ function throwIfAborted(signal) {
528
+ if (signal.aborted)
529
+ throw signal.reason ?? new Error('Knowledge operation was cancelled.');
530
+ }
531
+ function errorMessage(error) {
532
+ return error instanceof Error ? error.message : String(error);
533
+ }
534
+ function isRecord(value) {
535
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
536
+ return false;
537
+ const prototype = Object.getPrototypeOf(value);
538
+ return prototype === Object.prototype || prototype === null;
539
+ }
@@ -1,6 +1,6 @@
1
1
  import { exhaustiveTuple } from '../utils/genericUtilFunctions.js';
2
- export const dataTypes = exhaustiveTuple()('any', 'any[]', 'boolean', 'boolean[]', 'string', 'string[]', 'number', 'number[]', 'date', 'date[]', 'time', 'time[]', 'datetime', 'datetime[]', 'chat-message', 'chat-message[]', 'control-flow-excluded', 'control-flow-excluded[]', 'object', 'object[]', 'fn<string>', 'fn<number>', 'fn<boolean>', 'fn<date>', 'fn<time>', 'fn<datetime>', 'fn<any>', 'fn<object>', 'fn<chat-message>', 'fn<control-flow-excluded>', 'fn<string[]>', 'fn<number[]>', 'fn<boolean[]>', 'fn<date[]>', 'fn<time[]>', 'fn<datetime[]>', 'fn<any[]>', 'fn<object[]>', 'fn<chat-message[]>', 'fn<control-flow-excluded[]>', 'gpt-function', 'gpt-function[]', 'fn<gpt-function[]>', 'fn<gpt-function>', 'vector', 'vector[]', 'fn<vector>', 'fn<vector[]>', 'image', 'image[]', 'fn<image>', 'fn<image[]>', 'binary', 'binary[]', 'fn<binary>', 'fn<binary[]>', 'audio', 'audio[]', 'fn<audio>', 'fn<audio[]>', 'graph-reference', 'graph-reference[]', 'fn<graph-reference>', 'fn<graph-reference[]>', 'document', 'document[]', 'fn<document>', 'fn<document[]>');
3
- export const scalarTypes = exhaustiveTuple()('any', 'boolean', 'string', 'number', 'date', 'time', 'datetime', 'chat-message', 'control-flow-excluded', 'object', 'gpt-function', 'vector', 'image', 'binary', 'audio', 'graph-reference', 'document');
2
+ export const dataTypes = exhaustiveTuple()('any', 'any[]', 'boolean', 'boolean[]', 'string', 'string[]', 'number', 'number[]', 'date', 'date[]', 'time', 'time[]', 'datetime', 'datetime[]', 'chat-message', 'chat-message[]', 'control-flow-excluded', 'control-flow-excluded[]', 'object', 'object[]', 'fn<string>', 'fn<number>', 'fn<boolean>', 'fn<date>', 'fn<time>', 'fn<datetime>', 'fn<any>', 'fn<object>', 'fn<chat-message>', 'fn<control-flow-excluded>', 'fn<string[]>', 'fn<number[]>', 'fn<boolean[]>', 'fn<date[]>', 'fn<time[]>', 'fn<datetime[]>', 'fn<any[]>', 'fn<object[]>', 'fn<chat-message[]>', 'fn<control-flow-excluded[]>', 'gpt-function', 'gpt-function[]', 'fn<gpt-function[]>', 'fn<gpt-function>', 'vector', 'vector[]', 'fn<vector>', 'fn<vector[]>', 'image', 'image[]', 'fn<image>', 'fn<image[]>', 'binary', 'binary[]', 'fn<binary>', 'fn<binary[]>', 'audio', 'audio[]', 'fn<audio>', 'fn<audio[]>', 'graph-reference', 'graph-reference[]', 'fn<graph-reference>', 'fn<graph-reference[]>', 'knowledge-source', 'knowledge-source[]', 'fn<knowledge-source>', 'fn<knowledge-source[]>', 'knowledge-document', 'knowledge-document[]', 'fn<knowledge-document>', 'fn<knowledge-document[]>', 'knowledge-evidence', 'knowledge-evidence[]', 'fn<knowledge-evidence>', 'fn<knowledge-evidence[]>', 'document', 'document[]', 'fn<document>', 'fn<document[]>');
3
+ export const scalarTypes = exhaustiveTuple()('any', 'boolean', 'string', 'number', 'date', 'time', 'datetime', 'chat-message', 'control-flow-excluded', 'object', 'gpt-function', 'vector', 'image', 'binary', 'audio', 'graph-reference', 'knowledge-source', 'knowledge-document', 'knowledge-evidence', 'document');
4
4
  export const dataTypeDisplayNames = {
5
5
  any: 'Any',
6
6
  'any[]': 'Any Array',
@@ -66,6 +66,18 @@ export const dataTypeDisplayNames = {
66
66
  'graph-reference[]': 'Graph Reference Array',
67
67
  'fn<graph-reference>': 'Function<Graph Reference>',
68
68
  'fn<graph-reference[]>': 'Function<Graph Reference Array>',
69
+ 'knowledge-source': 'Knowledge Source',
70
+ 'knowledge-source[]': 'Knowledge Source Array',
71
+ 'fn<knowledge-source>': 'Function<Knowledge Source>',
72
+ 'fn<knowledge-source[]>': 'Function<Knowledge Source Array>',
73
+ 'knowledge-document': 'Knowledge Document',
74
+ 'knowledge-document[]': 'Knowledge Document Array',
75
+ 'fn<knowledge-document>': 'Function<Knowledge Document>',
76
+ 'fn<knowledge-document[]>': 'Function<Knowledge Document Array>',
77
+ 'knowledge-evidence': 'Knowledge Evidence',
78
+ 'knowledge-evidence[]': 'Knowledge Evidence Array',
79
+ 'fn<knowledge-evidence>': 'Function<Knowledge Evidence>',
80
+ 'fn<knowledge-evidence[]>': 'Function<Knowledge Evidence Array>',
69
81
  document: 'Document',
70
82
  'document[]': 'Document Array',
71
83
  'fn<document>': 'Function<Document>',
@@ -169,6 +181,14 @@ export const scalarDefaults = {
169
181
  binary: new Uint8Array(),
170
182
  audio: { data: new Uint8Array() },
171
183
  'graph-reference': { graphId: '', graphName: '' },
184
+ 'knowledge-source': { connectionId: '', sourceId: '' },
185
+ 'knowledge-document': { text: '' },
186
+ 'knowledge-evidence': {
187
+ id: '',
188
+ text: '',
189
+ source: { connectionId: '', sourceId: '' },
190
+ documentId: '',
191
+ },
172
192
  document: {
173
193
  mediaType: 'text/plain',
174
194
  data: new Uint8Array(),
@@ -26,6 +26,7 @@ import { createExcludedNodeOutputs, getControlFlowExclusionDecision, getMissingR
26
26
  import { DELEGATE_TOOL_CALL_INPUT_ID, resolveToolContinuationConnection, } from './chat-v2/toolContinuationConnection.js';
27
27
  import { buildDelegatedToolCallOutputs, delegateToolCall, isDelegatedToolCallRecord, } from './nodes/toolCallDelegation.js';
28
28
  import { ManagedAsyncBranches } from './ManagedAsyncBranches.js';
29
+ import { KnowledgeStoreController } from '../integrations/KnowledgeStoreProvider.js';
29
30
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
30
31
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
31
32
  const graphProcessorGraphOverride = Symbol('graphProcessorGraphOverride');
@@ -160,6 +161,7 @@ export class GraphProcessor {
160
161
  #captureNodeTimings;
161
162
  #frozenNodeOutputResolver;
162
163
  #storedValueStore;
164
+ #knowledgeStores;
163
165
  #useSeededExecutionPlanOnNextRun = false;
164
166
  id = nanoid();
165
167
  #includeTrace = true;
@@ -194,6 +196,7 @@ export class GraphProcessor {
194
196
  #contextValues = undefined;
195
197
  #globals = undefined;
196
198
  #storedValueController = undefined;
199
+ #knowledgeStoreController = undefined;
197
200
  #attachedNodeData = undefined;
198
201
  #successfulAbortTerminalProcessIds = undefined;
199
202
  #totalCost = 0;
@@ -447,6 +450,12 @@ export class GraphProcessor {
447
450
  }
448
451
  this.#storedValueStore = store;
449
452
  }
453
+ setKnowledgeStores(stores) {
454
+ if (this.#lifecycle.isRunning) {
455
+ throw new Error('Cannot change knowledge stores while the graph is running.');
456
+ }
457
+ this.#knowledgeStores = stores;
458
+ }
450
459
  async abort(successful = false, error) {
451
460
  if (!this.#lifecycle.requestAbort(successful, error)) {
452
461
  return Promise.resolve();
@@ -614,6 +623,7 @@ export class GraphProcessor {
614
623
  this.#globals ??= new Map();
615
624
  if (!this.#isSubProcessor) {
616
625
  this.#storedValueController = new RivetStoredValueController(this.#storedValueStore);
626
+ this.#knowledgeStoreController = new KnowledgeStoreController(this.#knowledgeStores);
617
627
  }
618
628
  this.#ignoreNodes = new Set();
619
629
  this.#nodeProcessContextBase = undefined;
@@ -763,6 +773,7 @@ export class GraphProcessor {
763
773
  getGlobal: (id) => this.#globals.get(id),
764
774
  getCachedStoredValue: (key) => this.#storedValueController.getCached(key),
765
775
  getStoredValue: (key) => this.#storedValueController.get(key),
776
+ getKnowledgeStore: (connectionId) => this.#knowledgeStoreController.resolve(connectionId, this.#nodeProcessContextBase),
766
777
  getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
767
778
  graphInputNodeValues: this.#graphInputNodeValues,
768
779
  graphInputs: this.#graphInputs,
@@ -1407,6 +1418,7 @@ export class GraphProcessor {
1407
1418
  processor.#suppressGraphPartialOutputs = true;
1408
1419
  processor.#globals = this.#globals;
1409
1420
  processor.#storedValueController = this.#storedValueController;
1421
+ processor.#knowledgeStoreController = this.#knowledgeStoreController;
1410
1422
  processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
1411
1423
  processor.#executor = this.#executor;
1412
1424
  processor.#suppressGraphLifecycleEvents = isRootGraphOrigin;
@@ -2091,6 +2103,7 @@ export class GraphProcessor {
2091
2103
  processor.#sameGraphRunOwnerOverride = this.#sameGraphRunOwnerOverride ?? this;
2092
2104
  processor.#globals = this.#globals;
2093
2105
  processor.#storedValueController = this.#storedValueController;
2106
+ processor.#knowledgeStoreController = this.#knowledgeStoreController;
2094
2107
  processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
2095
2108
  processor.#executor = this.#executor;
2096
2109
  processor.#suppressGraphLifecycleEvents = true;
@@ -2598,6 +2611,7 @@ export class GraphProcessor {
2598
2611
  processor.#parent = this;
2599
2612
  processor.#globals = this.#globals;
2600
2613
  processor.#storedValueController = this.#storedValueController;
2614
+ processor.#knowledgeStoreController = this.#knowledgeStoreController;
2601
2615
  processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
2602
2616
  processor.#executor = {
2603
2617
  nodeId: node.id,