@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.
- package/dist/cjs/bundle.cjs +3154 -289
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/webAppRuntime.cjs +129 -4
- package/dist/cjs/webAppRuntime.cjs.map +2 -2
- package/dist/esm/api/createProcessor.js +1 -0
- package/dist/esm/exports.js +4 -0
- package/dist/esm/integrations/KnowledgeStore.js +1 -0
- package/dist/esm/integrations/KnowledgeStoreProvider.js +292 -0
- package/dist/esm/integrations/KnowledgeStoreValidation.js +428 -0
- package/dist/esm/integrations/ManagedKnowledgeStore.js +539 -0
- package/dist/esm/model/DataValue.js +22 -2
- package/dist/esm/model/GraphProcessor.js +14 -0
- package/dist/esm/model/Nodes.js +18 -0
- package/dist/esm/model/UiGraph.js +2 -2
- package/dist/esm/model/UiGraphBrowserRuntime.js +112 -1
- package/dist/esm/model/UiGraphRendererStyles.js +111 -9
- package/dist/esm/model/UiGraphRuntimeModel.js +26 -2
- package/dist/esm/model/chat/openAIChatRequest.js +8 -2
- package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +8 -8
- package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -1
- package/dist/esm/model/chat-v2/parallelToolCalls.js +38 -0
- package/dist/esm/model/chat-v2/toolContinuation.js +39 -0
- package/dist/esm/model/nodes/BuildKnowledgeContextNode.js +157 -0
- package/dist/esm/model/nodes/GetKnowledgeSourceStatusNode.js +79 -0
- package/dist/esm/model/nodes/KnowledgeDocumentNode.js +88 -0
- package/dist/esm/model/nodes/KnowledgeSourceNode.js +94 -0
- package/dist/esm/model/nodes/SearchKnowledgeNode.js +127 -0
- package/dist/esm/model/nodes/StoredValueNodeUtils.js +10 -0
- package/dist/esm/model/nodes/SyncKnowledgeSourceNode.js +149 -0
- package/dist/esm/model/nodes/ToolNode.js +14 -0
- package/dist/esm/plugins/pinecone/PineconeKnowledgeStore.js +553 -0
- package/dist/esm/plugins/pinecone/plugin.js +32 -0
- package/dist/esm/utils/coerceType.js +24 -2
- package/dist/esm/utils/getPluginConfig.js +12 -6
- package/dist/esm/utils/serialization/serialization.js +4 -1
- package/dist/esm/utils/serialization/serializationUtils.js +59 -1
- package/dist/esm/webAppRuntime.js +1 -1
- package/dist/types/api/createProcessor.d.ts +2 -0
- package/dist/types/exports.d.ts +4 -0
- package/dist/types/integrations/KnowledgeStore.d.ts +131 -0
- package/dist/types/integrations/KnowledgeStoreProvider.d.ts +46 -0
- package/dist/types/integrations/KnowledgeStoreValidation.d.ts +16 -0
- package/dist/types/integrations/ManagedKnowledgeStore.d.ts +57 -0
- package/dist/types/model/DataValue.d.ts +10 -3
- package/dist/types/model/EditorDefinition.d.ts +7 -1
- package/dist/types/model/GraphProcessor.d.ts +2 -0
- package/dist/types/model/Nodes.d.ts +8 -2
- package/dist/types/model/ProcessContext.d.ts +3 -0
- package/dist/types/model/Project.d.ts +11 -0
- package/dist/types/model/UiGraph.d.ts +3 -1
- package/dist/types/model/UiGraphBrowserRuntime.d.ts +25 -1
- package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
- package/dist/types/model/chat-v2/parallelToolCalls.d.ts +9 -0
- package/dist/types/model/nodes/BuildKnowledgeContextNode.d.ts +23 -0
- package/dist/types/model/nodes/GetKnowledgeSourceStatusNode.d.ts +19 -0
- package/dist/types/model/nodes/KnowledgeDocumentNode.d.ts +26 -0
- package/dist/types/model/nodes/KnowledgeSourceNode.d.ts +25 -0
- package/dist/types/model/nodes/SearchKnowledgeNode.d.ts +25 -0
- package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +1 -1
- package/dist/types/model/nodes/SyncKnowledgeSourceNode.d.ts +27 -0
- package/dist/types/model/nodes/ToolNode.d.ts +2 -0
- package/dist/types/plugins/pinecone/PineconeKnowledgeStore.d.ts +11 -0
- package/dist/types/utils/serialization/serializationUtils.d.ts +4 -0
- package/dist/types/webAppRuntime.d.ts +2 -1
- package/package.json +1 -1
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
import CryptoJS from 'crypto-js';
|
|
2
|
+
import { ManagedKnowledgeStore, normalizeKnowledgeSourceManifest, } from '../../integrations/ManagedKnowledgeStore.js';
|
|
3
|
+
const DEFAULT_API_VERSION = '2026-04';
|
|
4
|
+
const MANIFEST_RECORD_ID = '__rivet_manifest__';
|
|
5
|
+
const RESERVED_PREFIX = 'rivet_';
|
|
6
|
+
const DEFAULT_TEXT_FIELD = 'chunk_text';
|
|
7
|
+
const MANIFEST_VISIBILITY_ATTEMPTS = 12;
|
|
8
|
+
export function createPineconeKnowledgeStore(definition, settings, credentials) {
|
|
9
|
+
const config = readConfig(definition);
|
|
10
|
+
const pluginSettings = settings.pluginSettings?.pinecone;
|
|
11
|
+
const apiKey = firstNonEmptyString(credentials.apiKey, pluginSettings?.pineconeApiKey, settings.pluginEnv?.PINECONE_API_KEY);
|
|
12
|
+
if (!apiKey) {
|
|
13
|
+
throw new Error(`Pinecone credentials are missing for knowledge store "${definition.displayName}". Configure its API key or PINECONE_API_KEY.`);
|
|
14
|
+
}
|
|
15
|
+
return new ManagedKnowledgeStore(new PineconeKnowledgeStoreDriver(config, apiKey));
|
|
16
|
+
}
|
|
17
|
+
export async function testPineconeKnowledgeConnection(definition, credentials, signal, context) {
|
|
18
|
+
const config = readConfig(definition);
|
|
19
|
+
const apiKey = firstNonEmptyString(credentials.apiKey, context.settings.pluginSettings?.pinecone?.pineconeApiKey, context.settings.pluginEnv?.PINECONE_API_KEY);
|
|
20
|
+
if (!apiKey)
|
|
21
|
+
throw new Error('Enter an API key before testing this Pinecone connection.');
|
|
22
|
+
const response = await fetch(`${config.indexHost}/describe_index_stats`, {
|
|
23
|
+
method: 'POST',
|
|
24
|
+
headers: {
|
|
25
|
+
Accept: 'application/json',
|
|
26
|
+
'Content-Type': 'application/json',
|
|
27
|
+
'Api-Key': apiKey,
|
|
28
|
+
'X-Pinecone-Api-Version': config.apiVersion,
|
|
29
|
+
},
|
|
30
|
+
body: '{}',
|
|
31
|
+
signal,
|
|
32
|
+
});
|
|
33
|
+
if (!response.ok) {
|
|
34
|
+
const body = await response.text();
|
|
35
|
+
throw createProviderError(response.status, response.statusText, body);
|
|
36
|
+
}
|
|
37
|
+
const payload = await parseJsonResponse(response, 'testing the knowledge-store connection');
|
|
38
|
+
if (!isRecord(payload))
|
|
39
|
+
throw new Error('Pinecone connection test returned a malformed successful response.');
|
|
40
|
+
}
|
|
41
|
+
class PineconeKnowledgeStoreDriver {
|
|
42
|
+
config;
|
|
43
|
+
apiKey;
|
|
44
|
+
capabilities = {
|
|
45
|
+
supportedFilterOperators: ['eq', 'neq', 'in', 'nin', 'gt', 'gte', 'lt', 'lte', 'exists'],
|
|
46
|
+
supportsProviderReranking: true,
|
|
47
|
+
supportedExecutors: ['nodejs'],
|
|
48
|
+
};
|
|
49
|
+
operationScope;
|
|
50
|
+
constructor(config, apiKey) {
|
|
51
|
+
this.config = config;
|
|
52
|
+
this.apiKey = apiKey;
|
|
53
|
+
this.operationScope = `pinecone:${config.indexHost}`;
|
|
54
|
+
}
|
|
55
|
+
async getManifest(sourceId, context) {
|
|
56
|
+
return (await this.#readManifest(sourceId, context)).manifest;
|
|
57
|
+
}
|
|
58
|
+
async #readManifest(sourceId, context) {
|
|
59
|
+
const namespace = this.#namespace(sourceId);
|
|
60
|
+
const url = `${this.config.indexHost}/vectors/fetch?ids=${encodeURIComponent(MANIFEST_RECORD_ID)}&namespace=${encodeURIComponent(namespace)}`;
|
|
61
|
+
const response = await this.#request(url, { method: 'GET' }, context);
|
|
62
|
+
const indexedLsn = readPineconeLsn(response.headers, 'x-pinecone-max-indexed-lsn');
|
|
63
|
+
const payload = await parseJsonResponse(response, 'fetching the knowledge-source manifest');
|
|
64
|
+
if (!isRecord(payload)) {
|
|
65
|
+
throw new Error('Pinecone returned an invalid manifest fetch response.');
|
|
66
|
+
}
|
|
67
|
+
const vectors = payload.vectors;
|
|
68
|
+
if (!isRecord(vectors)) {
|
|
69
|
+
throw new Error('Pinecone manifest fetch response is missing its vectors map.');
|
|
70
|
+
}
|
|
71
|
+
const manifestRecord = vectors[MANIFEST_RECORD_ID];
|
|
72
|
+
if (manifestRecord != null && !isRecord(manifestRecord)) {
|
|
73
|
+
throw new Error(`Pinecone manifest record for source "${sourceId}" is malformed.`);
|
|
74
|
+
}
|
|
75
|
+
if (!isRecord(manifestRecord))
|
|
76
|
+
return { ...(indexedLsn == null ? {} : { indexedLsn }) };
|
|
77
|
+
const fields = isRecord(manifestRecord.fields)
|
|
78
|
+
? manifestRecord.fields
|
|
79
|
+
: isRecord(manifestRecord.metadata)
|
|
80
|
+
? manifestRecord.metadata
|
|
81
|
+
: {};
|
|
82
|
+
const encodedManifest = fields.rivet_manifest_json;
|
|
83
|
+
if (typeof encodedManifest !== 'string') {
|
|
84
|
+
throw new Error(`Pinecone manifest for source "${sourceId}" is missing Rivet manifest metadata.`);
|
|
85
|
+
}
|
|
86
|
+
let manifest;
|
|
87
|
+
try {
|
|
88
|
+
manifest = JSON.parse(encodedManifest);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
throw new Error(`Pinecone manifest for source "${sourceId}" contains invalid JSON.`);
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
manifest: normalizeKnowledgeSourceManifest(manifest, sourceId),
|
|
95
|
+
...(indexedLsn == null ? {} : { indexedLsn }),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
async upsertChunks(sourceId, version, chunks, context) {
|
|
99
|
+
const namespace = this.#namespace(sourceId);
|
|
100
|
+
const records = chunks.map((chunk) => this.#chunkRecord(sourceId, version, chunk));
|
|
101
|
+
const batches = batchNdjson(records, 32, 1_500_000);
|
|
102
|
+
for (let index = 0; index < batches.length; index += 1) {
|
|
103
|
+
context.reportProgress?.({
|
|
104
|
+
message: `Uploading knowledge batch ${index + 1} of ${batches.length}.`,
|
|
105
|
+
percent: 15 + Math.round(((index + 1) / batches.length) * 70),
|
|
106
|
+
});
|
|
107
|
+
const response = await this.#request(`${this.config.indexHost}/records/namespaces/${encodeURIComponent(namespace)}/upsert`, { method: 'POST', body: batches[index], headers: { 'Content-Type': 'application/x-ndjson' } }, context);
|
|
108
|
+
await response.text();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
async commitManifest(manifest, context) {
|
|
112
|
+
const namespace = this.#namespace(manifest.sourceId);
|
|
113
|
+
const record = {
|
|
114
|
+
_id: MANIFEST_RECORD_ID,
|
|
115
|
+
[this.config.textField]: `Rivet knowledge-source manifest for ${manifest.sourceId}, version ${manifest.activeVersion}.`,
|
|
116
|
+
rivet_record_type: 'manifest',
|
|
117
|
+
rivet_source_id: manifest.sourceId,
|
|
118
|
+
rivet_source_version: manifest.activeVersion,
|
|
119
|
+
rivet_manifest_json: JSON.stringify(manifest),
|
|
120
|
+
};
|
|
121
|
+
validatePineconeRecordMetadataSize(record, this.config.textField, `manifest for source "${manifest.sourceId}"`);
|
|
122
|
+
const response = await this.#request(`${this.config.indexHost}/records/namespaces/${encodeURIComponent(namespace)}/upsert`, { method: 'POST', body: JSON.stringify(record), headers: { 'Content-Type': 'application/x-ndjson' } }, context);
|
|
123
|
+
const writeLsn = readPineconeLsn(response.headers, 'x-pinecone-request-lsn') ??
|
|
124
|
+
readPineconeLsn(response.headers, 'x-pinecone-max-indexed-lsn');
|
|
125
|
+
await response.text();
|
|
126
|
+
// Pinecone is eventually consistent. Once the later manifest write is
|
|
127
|
+
// readable, all earlier chunk upserts in this namespace are readable too.
|
|
128
|
+
for (let attempt = 0; attempt < MANIFEST_VISIBILITY_ATTEMPTS; attempt += 1) {
|
|
129
|
+
const visible = await this.#readManifest(manifest.sourceId, context);
|
|
130
|
+
const indexedWrite = writeLsn == null || visible.indexedLsn == null || visible.indexedLsn >= writeLsn;
|
|
131
|
+
if (visible.manifest && sameManifestCommit(visible.manifest, manifest) && indexedWrite)
|
|
132
|
+
return;
|
|
133
|
+
if (attempt + 1 < MANIFEST_VISIBILITY_ATTEMPTS) {
|
|
134
|
+
await cancellableDelay(Math.min(2_000, 100 * 2 ** attempt), context.signal);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
throw new Error(`Pinecone accepted knowledge source "${manifest.sourceId}", but its committed manifest did not become readable in time.`);
|
|
138
|
+
}
|
|
139
|
+
async search(request, context) {
|
|
140
|
+
const namespace = this.#namespace(request.sourceId);
|
|
141
|
+
const filter = combinePineconeFilters({
|
|
142
|
+
$and: [{ rivet_record_type: { $eq: 'chunk' } }, { rivet_source_version: { $eq: request.version } }],
|
|
143
|
+
}, request.filter ? toPineconeFilter(request.filter) : undefined);
|
|
144
|
+
const body = {
|
|
145
|
+
query: { inputs: { text: request.query }, top_k: request.topK, filter },
|
|
146
|
+
};
|
|
147
|
+
if (request.rerank) {
|
|
148
|
+
const model = this.config.rerankModel;
|
|
149
|
+
if (!model && request.rerank.mode === 'required') {
|
|
150
|
+
throw new Error('Pinecone reranking is required, but this connection has no rerank model configured.');
|
|
151
|
+
}
|
|
152
|
+
if (model) {
|
|
153
|
+
body.rerank = {
|
|
154
|
+
query: request.query,
|
|
155
|
+
model,
|
|
156
|
+
top_n: Math.min(request.topK, request.rerank.topN ?? 7),
|
|
157
|
+
rank_fields: [this.config.textField],
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const response = await this.#request(`${this.config.indexHost}/records/namespaces/${encodeURIComponent(namespace)}/search`, { method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } }, context);
|
|
162
|
+
const payload = await parseJsonResponse(response, 'searching knowledge');
|
|
163
|
+
if (!isRecord(payload) || !isRecord(payload.result) || !Array.isArray(payload.result.hits)) {
|
|
164
|
+
throw new Error('Pinecone returned an invalid knowledge search response.');
|
|
165
|
+
}
|
|
166
|
+
return payload.result.hits.map((hit, index) => {
|
|
167
|
+
if (!isRecord(hit) || !isRecord(hit.fields)) {
|
|
168
|
+
throw new Error(`Pinecone knowledge search hit ${index + 1} is malformed.`);
|
|
169
|
+
}
|
|
170
|
+
const fields = hit.fields;
|
|
171
|
+
const id = recordId(hit);
|
|
172
|
+
const text = fields[this.config.textField];
|
|
173
|
+
const documentId = fields.rivet_document_id;
|
|
174
|
+
if (!id || typeof text !== 'string' || !text.trim() || typeof documentId !== 'string' || !documentId.trim()) {
|
|
175
|
+
throw new Error(`Pinecone knowledge search hit ${index + 1} is missing required Rivet fields.`);
|
|
176
|
+
}
|
|
177
|
+
if (fields.rivet_title != null && typeof fields.rivet_title !== 'string') {
|
|
178
|
+
throw new Error(`Pinecone knowledge search hit ${index + 1} has an invalid title.`);
|
|
179
|
+
}
|
|
180
|
+
if (fields.rivet_chunk_index != null &&
|
|
181
|
+
(!Number.isInteger(fields.rivet_chunk_index) || fields.rivet_chunk_index < 0)) {
|
|
182
|
+
throw new Error(`Pinecone knowledge search hit ${index + 1} has an invalid chunk index.`);
|
|
183
|
+
}
|
|
184
|
+
if (hit._score != null && (typeof hit._score !== 'number' || !Number.isFinite(hit._score))) {
|
|
185
|
+
throw new Error(`Pinecone knowledge search hit ${index + 1} has an invalid relevance score.`);
|
|
186
|
+
}
|
|
187
|
+
const title = typeof fields.rivet_title === 'string' && fields.rivet_title.trim() ? fields.rivet_title : undefined;
|
|
188
|
+
const chunkIndex = fields.rivet_chunk_index;
|
|
189
|
+
const score = hit._score;
|
|
190
|
+
const metadata = extractUserMetadata(fields, this.config.textField);
|
|
191
|
+
return {
|
|
192
|
+
id,
|
|
193
|
+
text,
|
|
194
|
+
documentId,
|
|
195
|
+
source: { connectionId: '', sourceId: request.sourceId, version: request.version },
|
|
196
|
+
...(title ? { title } : {}),
|
|
197
|
+
...(chunkIndex == null ? {} : { chunkIndex }),
|
|
198
|
+
...(score == null ? {} : { relevanceScore: score }),
|
|
199
|
+
...(metadata ? { metadata } : {}),
|
|
200
|
+
};
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
async deleteVersion(sourceId, version, context) {
|
|
204
|
+
const namespace = this.#namespace(sourceId);
|
|
205
|
+
const response = await this.#request(`${this.config.indexHost}/vectors/delete`, {
|
|
206
|
+
method: 'POST',
|
|
207
|
+
headers: { 'Content-Type': 'application/json' },
|
|
208
|
+
body: JSON.stringify({
|
|
209
|
+
namespace,
|
|
210
|
+
filter: {
|
|
211
|
+
$and: [{ rivet_record_type: { $eq: 'chunk' } }, { rivet_source_version: { $eq: version } }],
|
|
212
|
+
},
|
|
213
|
+
}),
|
|
214
|
+
}, context);
|
|
215
|
+
await response.text();
|
|
216
|
+
}
|
|
217
|
+
#chunkRecord(sourceId, version, chunk) {
|
|
218
|
+
const metadata = chunk.metadata ?? {};
|
|
219
|
+
for (const [key, value] of Object.entries(metadata)) {
|
|
220
|
+
validatePineconeFieldName(key, 'Knowledge metadata field');
|
|
221
|
+
if (key.startsWith(RESERVED_PREFIX)) {
|
|
222
|
+
throw new Error(`Knowledge metadata field "${key}" uses the reserved ${RESERVED_PREFIX} prefix.`);
|
|
223
|
+
}
|
|
224
|
+
if (key === this.config.textField) {
|
|
225
|
+
throw new Error(`Knowledge metadata field "${key}" conflicts with the Pinecone integrated embedding text field.`);
|
|
226
|
+
}
|
|
227
|
+
if (value === null || (Array.isArray(value) && !value.every((item) => typeof item === 'string'))) {
|
|
228
|
+
throw new Error(`Pinecone metadata field "${key}" must be a string, finite number, boolean, or array of strings.`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const record = {
|
|
232
|
+
_id: chunk.id,
|
|
233
|
+
[this.config.textField]: chunk.text,
|
|
234
|
+
rivet_record_type: 'chunk',
|
|
235
|
+
rivet_source_id: sourceId,
|
|
236
|
+
rivet_source_version: version,
|
|
237
|
+
rivet_document_id: chunk.documentId,
|
|
238
|
+
rivet_title: chunk.title ?? '',
|
|
239
|
+
rivet_chunk_index: chunk.chunkIndex,
|
|
240
|
+
rivet_chunks_in_document: chunk.chunksInDocument,
|
|
241
|
+
...metadata,
|
|
242
|
+
};
|
|
243
|
+
validatePineconeRecordMetadataSize(record, this.config.textField, `knowledge chunk "${chunk.id}"`);
|
|
244
|
+
return record;
|
|
245
|
+
}
|
|
246
|
+
#namespace(sourceId) {
|
|
247
|
+
const readableSourceId = sourceId
|
|
248
|
+
.replace(/[^a-zA-Z0-9._-]/g, '-')
|
|
249
|
+
.replace(/-+/g, '-')
|
|
250
|
+
.replace(/^-|-$/g, '')
|
|
251
|
+
.slice(0, 120) || 'source';
|
|
252
|
+
const sourceHash = CryptoJS.SHA256(sourceId).toString(CryptoJS.enc.Hex).slice(0, 24);
|
|
253
|
+
const safeSourceId = `${readableSourceId}--${sourceHash}`;
|
|
254
|
+
const namespace = this.config.namespaceTemplate.replaceAll('{sourceId}', safeSourceId).trim();
|
|
255
|
+
if (!namespace)
|
|
256
|
+
throw new Error('Pinecone Namespace Template produced an empty namespace.');
|
|
257
|
+
if (namespace.length > 512)
|
|
258
|
+
throw new Error('Pinecone Namespace Template produced a namespace longer than 512 characters.');
|
|
259
|
+
return namespace;
|
|
260
|
+
}
|
|
261
|
+
async #request(url, init, context) {
|
|
262
|
+
const headers = new Headers(init.headers);
|
|
263
|
+
headers.set('Accept', 'application/json');
|
|
264
|
+
headers.set('Api-Key', this.apiKey);
|
|
265
|
+
headers.set('X-Pinecone-Api-Version', this.config.apiVersion);
|
|
266
|
+
let lastError;
|
|
267
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
268
|
+
if (context.signal.aborted)
|
|
269
|
+
throw context.signal.reason ?? new Error('Pinecone request was cancelled.');
|
|
270
|
+
try {
|
|
271
|
+
const response = await fetch(url, { ...init, headers, signal: context.signal });
|
|
272
|
+
if (response.ok)
|
|
273
|
+
return response;
|
|
274
|
+
const body = await response.text();
|
|
275
|
+
const error = createProviderError(response.status, response.statusText, body);
|
|
276
|
+
if (!isRetryableStatus(response.status) || attempt === 2)
|
|
277
|
+
throw error;
|
|
278
|
+
lastError = error;
|
|
279
|
+
const retryAfter = response.headers.get('retry-after');
|
|
280
|
+
await cancellableDelay(retryDelayMs(retryAfter, attempt), context.signal);
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
if (context.signal.aborted)
|
|
284
|
+
throw context.signal.reason ?? error;
|
|
285
|
+
if (error instanceof PineconeKnowledgeError || attempt === 2)
|
|
286
|
+
throw error;
|
|
287
|
+
lastError = error;
|
|
288
|
+
await cancellableDelay(500 * 2 ** attempt + Math.floor(Math.random() * 150), context.signal);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
throw lastError ?? new Error('Pinecone request failed.');
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
export class PineconeKnowledgeError extends Error {
|
|
295
|
+
status;
|
|
296
|
+
providerBody;
|
|
297
|
+
constructor(message, status, providerBody) {
|
|
298
|
+
super(message);
|
|
299
|
+
this.status = status;
|
|
300
|
+
this.providerBody = providerBody;
|
|
301
|
+
this.name = 'PineconeKnowledgeError';
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
function readConfig(definition) {
|
|
305
|
+
const indexHostRaw = stringConfig(definition.config.indexHost);
|
|
306
|
+
if (!indexHostRaw)
|
|
307
|
+
throw new Error(`Pinecone knowledge store "${definition.displayName}" requires an Index Host.`);
|
|
308
|
+
const indexHost = /^https?:\/\//i.test(indexHostRaw) ? indexHostRaw : `https://${indexHostRaw}`;
|
|
309
|
+
let parsed;
|
|
310
|
+
try {
|
|
311
|
+
parsed = new URL(indexHost);
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
throw new Error(`Pinecone knowledge store "${definition.displayName}" has an invalid Index Host.`);
|
|
315
|
+
}
|
|
316
|
+
if (parsed.protocol !== 'https:') {
|
|
317
|
+
throw new Error(`Pinecone knowledge store "${definition.displayName}" requires an HTTPS Index Host.`);
|
|
318
|
+
}
|
|
319
|
+
const namespaceTemplate = stringConfig(definition.config.namespaceTemplate) || '{sourceId}';
|
|
320
|
+
if (!namespaceTemplate.includes('{sourceId}')) {
|
|
321
|
+
throw new Error('Pinecone Namespace Template must contain {sourceId} so sources remain isolated.');
|
|
322
|
+
}
|
|
323
|
+
const textField = stringConfig(definition.config.textField) || DEFAULT_TEXT_FIELD;
|
|
324
|
+
validatePineconeFieldName(textField, 'Pinecone Text Field');
|
|
325
|
+
if (textField.startsWith(RESERVED_PREFIX))
|
|
326
|
+
throw new Error(`Pinecone Text Field cannot use the reserved ${RESERVED_PREFIX} prefix.`);
|
|
327
|
+
return {
|
|
328
|
+
indexHost: `${parsed.protocol}//${parsed.host}`,
|
|
329
|
+
namespaceTemplate,
|
|
330
|
+
textField,
|
|
331
|
+
apiVersion: stringConfig(definition.config.apiVersion) || DEFAULT_API_VERSION,
|
|
332
|
+
...(stringConfig(definition.config.rerankModel)
|
|
333
|
+
? { rerankModel: stringConfig(definition.config.rerankModel) }
|
|
334
|
+
: {}),
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
function toPineconeFilter(filter) {
|
|
338
|
+
if ('and' in filter)
|
|
339
|
+
return { $and: filter.and.map(toPineconeFilter) };
|
|
340
|
+
if ('or' in filter)
|
|
341
|
+
return { $or: filter.or.map(toPineconeFilter) };
|
|
342
|
+
if ('not' in filter)
|
|
343
|
+
return toNegatedPineconeFilter(filter.not);
|
|
344
|
+
validatePineconeFilterComparison(filter);
|
|
345
|
+
const operatorMap = {
|
|
346
|
+
eq: '$eq',
|
|
347
|
+
neq: '$ne',
|
|
348
|
+
in: '$in',
|
|
349
|
+
nin: '$nin',
|
|
350
|
+
gt: '$gt',
|
|
351
|
+
gte: '$gte',
|
|
352
|
+
lt: '$lt',
|
|
353
|
+
lte: '$lte',
|
|
354
|
+
exists: '$exists',
|
|
355
|
+
};
|
|
356
|
+
return { [filter.field]: { [operatorMap[filter.operator]]: filter.operator === 'exists' ? true : filter.value } };
|
|
357
|
+
}
|
|
358
|
+
function toNegatedPineconeFilter(filter) {
|
|
359
|
+
if ('and' in filter)
|
|
360
|
+
return { $or: filter.and.map(toNegatedPineconeFilter) };
|
|
361
|
+
if ('or' in filter)
|
|
362
|
+
return { $and: filter.or.map(toNegatedPineconeFilter) };
|
|
363
|
+
if ('not' in filter)
|
|
364
|
+
return toPineconeFilter(filter.not);
|
|
365
|
+
validatePineconeFilterComparison(filter);
|
|
366
|
+
const operatorMap = {
|
|
367
|
+
eq: '$ne',
|
|
368
|
+
neq: '$eq',
|
|
369
|
+
in: '$nin',
|
|
370
|
+
nin: '$in',
|
|
371
|
+
gt: '$lte',
|
|
372
|
+
gte: '$lt',
|
|
373
|
+
lt: '$gte',
|
|
374
|
+
lte: '$gt',
|
|
375
|
+
exists: '$exists',
|
|
376
|
+
};
|
|
377
|
+
return { [filter.field]: { [operatorMap[filter.operator]]: filter.operator === 'exists' ? false : filter.value } };
|
|
378
|
+
}
|
|
379
|
+
function combinePineconeFilters(required, optional) {
|
|
380
|
+
if (!optional)
|
|
381
|
+
return required;
|
|
382
|
+
const requiredParts = Array.isArray(required.$and) ? required.$and : [required];
|
|
383
|
+
return { $and: [...requiredParts, optional] };
|
|
384
|
+
}
|
|
385
|
+
function batchNdjson(records, maxRecords, maxBytes) {
|
|
386
|
+
const encoder = new TextEncoder();
|
|
387
|
+
const batches = [];
|
|
388
|
+
let lines = [];
|
|
389
|
+
let bytes = 0;
|
|
390
|
+
for (const record of records) {
|
|
391
|
+
const line = JSON.stringify(record);
|
|
392
|
+
const lineBytes = encoder.encode(line).byteLength + (lines.length ? 1 : 0);
|
|
393
|
+
if (lineBytes > maxBytes)
|
|
394
|
+
throw new Error(`A single Pinecone knowledge record exceeds ${maxBytes} bytes.`);
|
|
395
|
+
if (lines.length && (lines.length >= maxRecords || bytes + lineBytes > maxBytes)) {
|
|
396
|
+
batches.push(lines.join('\n'));
|
|
397
|
+
lines = [];
|
|
398
|
+
bytes = 0;
|
|
399
|
+
}
|
|
400
|
+
lines.push(line);
|
|
401
|
+
bytes += lineBytes;
|
|
402
|
+
}
|
|
403
|
+
if (lines.length)
|
|
404
|
+
batches.push(lines.join('\n'));
|
|
405
|
+
return batches;
|
|
406
|
+
}
|
|
407
|
+
function validatePineconeRecordMetadataSize(record, textField, label) {
|
|
408
|
+
const storedMetadata = Object.fromEntries(Object.entries(record).filter(([key]) => key !== '_id' && key !== textField));
|
|
409
|
+
if (new TextEncoder().encode(JSON.stringify(storedMetadata)).byteLength > 40 * 1024) {
|
|
410
|
+
throw new Error(`Pinecone metadata for ${label} exceeds 40 KB.`);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
async function parseJsonResponse(response, operation) {
|
|
414
|
+
const body = await response.text();
|
|
415
|
+
if (!body.trim())
|
|
416
|
+
return {};
|
|
417
|
+
try {
|
|
418
|
+
return JSON.parse(body);
|
|
419
|
+
}
|
|
420
|
+
catch {
|
|
421
|
+
throw new Error(`Pinecone returned invalid JSON while ${operation}: ${body.slice(0, 1000)}`);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
function createProviderError(status, statusText, body) {
|
|
425
|
+
let providerMessage = body.trim();
|
|
426
|
+
try {
|
|
427
|
+
const parsed = JSON.parse(body);
|
|
428
|
+
if (isRecord(parsed)) {
|
|
429
|
+
const error = isRecord(parsed.error) ? parsed.error : undefined;
|
|
430
|
+
providerMessage =
|
|
431
|
+
stringConfig(error?.message) || stringConfig(parsed.message) || stringConfig(parsed.error) || providerMessage;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
// Preserve non-JSON provider bodies verbatim.
|
|
436
|
+
}
|
|
437
|
+
return new PineconeKnowledgeError(`Pinecone request failed (${status} ${statusText}).${providerMessage ? ` ${providerMessage}` : ''}`, status, body);
|
|
438
|
+
}
|
|
439
|
+
function extractUserMetadata(fields, textField) {
|
|
440
|
+
const metadata = {};
|
|
441
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
442
|
+
if (key === textField || key.startsWith(RESERVED_PREFIX) || key.startsWith('_'))
|
|
443
|
+
continue;
|
|
444
|
+
validatePineconeFieldName(key, 'Pinecone response metadata field');
|
|
445
|
+
if (value === null ||
|
|
446
|
+
(typeof value !== 'string' && typeof value !== 'boolean' && typeof value !== 'number' && !Array.isArray(value)) ||
|
|
447
|
+
(typeof value === 'number' && !Number.isFinite(value)) ||
|
|
448
|
+
(Array.isArray(value) && !value.every((item) => typeof item === 'string'))) {
|
|
449
|
+
throw new Error(`Pinecone response metadata field "${key}" must be a string, finite number, boolean, or array of strings.`);
|
|
450
|
+
}
|
|
451
|
+
metadata[key] = value;
|
|
452
|
+
}
|
|
453
|
+
return Object.keys(metadata).length ? metadata : undefined;
|
|
454
|
+
}
|
|
455
|
+
function recordId(value) {
|
|
456
|
+
if (!isRecord(value))
|
|
457
|
+
return '';
|
|
458
|
+
return stringConfig(value._id) || stringConfig(value.id);
|
|
459
|
+
}
|
|
460
|
+
function stringConfig(value) {
|
|
461
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
462
|
+
}
|
|
463
|
+
function firstNonEmptyString(...values) {
|
|
464
|
+
for (const value of values) {
|
|
465
|
+
const normalized = stringConfig(value);
|
|
466
|
+
if (normalized)
|
|
467
|
+
return normalized;
|
|
468
|
+
}
|
|
469
|
+
return '';
|
|
470
|
+
}
|
|
471
|
+
function sameManifestCommit(left, right) {
|
|
472
|
+
return (left.schemaVersion === right.schemaVersion &&
|
|
473
|
+
left.sourceId === right.sourceId &&
|
|
474
|
+
left.activeVersion === right.activeVersion &&
|
|
475
|
+
(left.commitId ?? '') === (right.commitId ?? '') &&
|
|
476
|
+
left.documentCount === right.documentCount &&
|
|
477
|
+
left.chunkCount === right.chunkCount &&
|
|
478
|
+
left.updatedAt === right.updatedAt);
|
|
479
|
+
}
|
|
480
|
+
function readPineconeLsn(headers, name) {
|
|
481
|
+
const value = headers.get(name)?.trim();
|
|
482
|
+
if (!value || !/^\d+$/.test(value))
|
|
483
|
+
return undefined;
|
|
484
|
+
try {
|
|
485
|
+
return BigInt(value);
|
|
486
|
+
}
|
|
487
|
+
catch {
|
|
488
|
+
return undefined;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
function validatePineconeFieldName(value, label) {
|
|
492
|
+
if (!value || value.startsWith('_') || value.startsWith('$')) {
|
|
493
|
+
throw new Error(`${label} "${value}" must be non-empty and cannot start with _ or $.`);
|
|
494
|
+
}
|
|
495
|
+
if (new TextEncoder().encode(value).byteLength > 64) {
|
|
496
|
+
throw new Error(`${label} "${value}" cannot exceed 64 UTF-8 bytes.`);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
function validatePineconeFilterComparison(filter) {
|
|
500
|
+
validatePineconeFieldName(filter.field, 'Pinecone filter field');
|
|
501
|
+
if (filter.field.startsWith(RESERVED_PREFIX)) {
|
|
502
|
+
throw new Error(`Pinecone filter field "${filter.field}" uses the reserved ${RESERVED_PREFIX} prefix.`);
|
|
503
|
+
}
|
|
504
|
+
if (filter.operator === 'exists')
|
|
505
|
+
return;
|
|
506
|
+
if ((filter.operator === 'gt' || filter.operator === 'gte' || filter.operator === 'lt' || filter.operator === 'lte') &&
|
|
507
|
+
(typeof filter.value !== 'number' || !Number.isFinite(filter.value))) {
|
|
508
|
+
throw new Error(`Pinecone filter operator "${filter.operator}" requires a finite number.`);
|
|
509
|
+
}
|
|
510
|
+
if (filter.value === null || (Array.isArray(filter.value) && filter.operator !== 'in' && filter.operator !== 'nin')) {
|
|
511
|
+
throw new Error(`Pinecone filter operator "${filter.operator}" requires a supported scalar value.`);
|
|
512
|
+
}
|
|
513
|
+
if ((filter.operator === 'in' || filter.operator === 'nin') &&
|
|
514
|
+
(!Array.isArray(filter.value) ||
|
|
515
|
+
!filter.value.every((item) => typeof item === 'string' || typeof item === 'number'))) {
|
|
516
|
+
throw new Error(`Pinecone filter operator "${filter.operator}" requires an array of strings or numbers.`);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
function isRecord(value) {
|
|
520
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
521
|
+
}
|
|
522
|
+
function isRetryableStatus(status) {
|
|
523
|
+
return status === 408 || status === 409 || status === 425 || status === 429 || status >= 500;
|
|
524
|
+
}
|
|
525
|
+
function retryDelayMs(retryAfter, attempt) {
|
|
526
|
+
if (retryAfter) {
|
|
527
|
+
const seconds = Number(retryAfter);
|
|
528
|
+
if (Number.isFinite(seconds) && seconds >= 0)
|
|
529
|
+
return Math.min(30_000, seconds * 1000);
|
|
530
|
+
const date = Date.parse(retryAfter);
|
|
531
|
+
if (Number.isFinite(date))
|
|
532
|
+
return Math.min(30_000, Math.max(0, date - Date.now()));
|
|
533
|
+
}
|
|
534
|
+
return 500 * 2 ** attempt + Math.floor(Math.random() * 150);
|
|
535
|
+
}
|
|
536
|
+
async function cancellableDelay(milliseconds, signal) {
|
|
537
|
+
await new Promise((resolve, reject) => {
|
|
538
|
+
const abort = () => {
|
|
539
|
+
clearTimeout(timer);
|
|
540
|
+
signal.removeEventListener('abort', abort);
|
|
541
|
+
reject(signal.reason ?? new Error('Pinecone request was cancelled.'));
|
|
542
|
+
};
|
|
543
|
+
const finish = () => {
|
|
544
|
+
signal.removeEventListener('abort', abort);
|
|
545
|
+
resolve();
|
|
546
|
+
};
|
|
547
|
+
const timer = setTimeout(finish, milliseconds);
|
|
548
|
+
if (signal.aborted)
|
|
549
|
+
abort();
|
|
550
|
+
else
|
|
551
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
552
|
+
});
|
|
553
|
+
}
|
|
@@ -1,11 +1,43 @@
|
|
|
1
1
|
import {} from '../../index.js';
|
|
2
2
|
import { PineconeVectorDatabase } from './PineconeVectorDatabase.js';
|
|
3
3
|
import { registerIntegration } from '../../integrations/integrations.js';
|
|
4
|
+
import { registerKnowledgeStoreProvider } from '../../integrations/KnowledgeStoreProvider.js';
|
|
5
|
+
import { createPineconeKnowledgeStore, testPineconeKnowledgeConnection } from './PineconeKnowledgeStore.js';
|
|
4
6
|
export const pineconePlugin = {
|
|
5
7
|
id: 'pinecone',
|
|
6
8
|
name: 'Pinecone',
|
|
7
9
|
register: () => {
|
|
8
10
|
registerIntegration('vectorDatabase', 'pinecone', (context) => new PineconeVectorDatabase(context.settings));
|
|
11
|
+
registerKnowledgeStoreProvider({
|
|
12
|
+
id: 'pinecone',
|
|
13
|
+
displayName: 'Pinecone',
|
|
14
|
+
pluginId: 'pinecone',
|
|
15
|
+
supportedExecutors: ['nodejs'],
|
|
16
|
+
connectionConfigSpec: [
|
|
17
|
+
{ key: 'indexHost', label: 'Index Host', type: 'string', required: true },
|
|
18
|
+
{
|
|
19
|
+
key: 'namespaceTemplate',
|
|
20
|
+
label: 'Namespace Template',
|
|
21
|
+
type: 'string',
|
|
22
|
+
required: true,
|
|
23
|
+
default: '{sourceId}',
|
|
24
|
+
description: 'Must contain {sourceId}. For example: book-{sourceId}.',
|
|
25
|
+
},
|
|
26
|
+
{ key: 'textField', label: 'Integrated Embedding Text Field', type: 'string', default: 'chunk_text' },
|
|
27
|
+
{ key: 'apiVersion', label: 'Pinecone API Version', type: 'string', default: '2026-04' },
|
|
28
|
+
{ key: 'rerankModel', label: 'Rerank Model', type: 'string', default: 'bge-reranker-v2-m3' },
|
|
29
|
+
],
|
|
30
|
+
credentialConfigSpec: [
|
|
31
|
+
{
|
|
32
|
+
key: 'apiKey',
|
|
33
|
+
label: 'API Key',
|
|
34
|
+
type: 'secret',
|
|
35
|
+
description: 'Stored locally and never written to the project file. Leave blank to use the plugin default.',
|
|
36
|
+
},
|
|
37
|
+
],
|
|
38
|
+
createStore: (_connectionId, definition, context) => createPineconeKnowledgeStore(definition, context.settings, context.credentials),
|
|
39
|
+
testConnection: testPineconeKnowledgeConnection,
|
|
40
|
+
});
|
|
9
41
|
},
|
|
10
42
|
configSpec: {
|
|
11
43
|
pineconeApiKey: {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { match } from 'ts-pattern';
|
|
2
2
|
import { getScalarTypeOf, isArrayDataType, isArrayDataValue, unwrapDataValue, } from '../model/DataValue.js';
|
|
3
3
|
import { expectTypeOptional } from './expectType.js';
|
|
4
|
+
import { normalizeKnowledgeDocument, normalizeKnowledgeEvidence, normalizeKnowledgeSourceReference, } from '../integrations/KnowledgeStoreValidation.js';
|
|
4
5
|
export function coerceTypeOptional(wrapped, type) {
|
|
5
6
|
const value = wrapped ? unwrapDataValue(wrapped) : undefined;
|
|
6
7
|
// Coerce 'true' to [true] for example
|
|
@@ -27,6 +28,9 @@ export function coerceTypeOptional(wrapped, type) {
|
|
|
27
28
|
.with('object', () => coerceToObject(value))
|
|
28
29
|
.with('binary', () => coerceToBinary(value))
|
|
29
30
|
.with('graph-reference', () => coerceToGraphReference(value))
|
|
31
|
+
.with('knowledge-source', () => coerceKnowledgeValue(value, normalizeKnowledgeSourceReference))
|
|
32
|
+
.with('knowledge-document', () => coerceKnowledgeValue(value, normalizeKnowledgeDocument))
|
|
33
|
+
.with('knowledge-evidence', () => coerceKnowledgeValue(value, normalizeKnowledgeEvidence))
|
|
30
34
|
.otherwise(() => {
|
|
31
35
|
if (!value) {
|
|
32
36
|
return value;
|
|
@@ -295,6 +299,16 @@ function coerceToGraphReference(value) {
|
|
|
295
299
|
}
|
|
296
300
|
return undefined;
|
|
297
301
|
}
|
|
302
|
+
function coerceKnowledgeValue(value, normalize) {
|
|
303
|
+
if (!value || value.value == null || isArrayDataValue(value))
|
|
304
|
+
return undefined;
|
|
305
|
+
try {
|
|
306
|
+
return normalize(value.value);
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
return undefined;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
298
312
|
export function canBeCoercedAny(from, to) {
|
|
299
313
|
for (const fromType of Array.isArray(from) ? from : [from]) {
|
|
300
314
|
for (const toType of Array.isArray(to) ? to : [to]) {
|
|
@@ -322,8 +336,16 @@ export function canBeCoerced(from, to) {
|
|
|
322
336
|
if (to === 'gpt-function') {
|
|
323
337
|
return from === 'object';
|
|
324
338
|
}
|
|
325
|
-
if (to === 'audio' ||
|
|
326
|
-
|
|
339
|
+
if (to === 'audio' ||
|
|
340
|
+
to === 'binary' ||
|
|
341
|
+
to === 'image' ||
|
|
342
|
+
to === 'knowledge-source' ||
|
|
343
|
+
to === 'knowledge-document' ||
|
|
344
|
+
to === 'knowledge-evidence') {
|
|
345
|
+
return from === to || from === 'object';
|
|
346
|
+
}
|
|
347
|
+
if (from === 'knowledge-source' || from === 'knowledge-document' || from === 'knowledge-evidence') {
|
|
348
|
+
return to === 'object' || to === 'string';
|
|
327
349
|
}
|
|
328
350
|
return true;
|
|
329
351
|
}
|