@contractspec/lib.knowledge 1.57.0 → 1.59.0

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 (74) hide show
  1. package/dist/access/guard.d.ts +13 -17
  2. package/dist/access/guard.d.ts.map +1 -1
  3. package/dist/access/guard.js +60 -49
  4. package/dist/access/index.d.ts +2 -2
  5. package/dist/access/index.d.ts.map +1 -0
  6. package/dist/access/index.js +60 -2
  7. package/dist/index.d.ts +6 -12
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +455 -12
  10. package/dist/ingestion/document-processor.d.ts +18 -20
  11. package/dist/ingestion/document-processor.d.ts.map +1 -1
  12. package/dist/ingestion/document-processor.js +63 -53
  13. package/dist/ingestion/embedding-service.d.ts +7 -11
  14. package/dist/ingestion/embedding-service.d.ts.map +1 -1
  15. package/dist/ingestion/embedding-service.js +26 -25
  16. package/dist/ingestion/gmail-adapter.d.ts +13 -17
  17. package/dist/ingestion/gmail-adapter.d.ts.map +1 -1
  18. package/dist/ingestion/gmail-adapter.js +67 -46
  19. package/dist/ingestion/index.d.ts +6 -6
  20. package/dist/ingestion/index.d.ts.map +1 -0
  21. package/dist/ingestion/index.js +221 -6
  22. package/dist/ingestion/storage-adapter.d.ts +10 -14
  23. package/dist/ingestion/storage-adapter.d.ts.map +1 -1
  24. package/dist/ingestion/storage-adapter.js +31 -26
  25. package/dist/ingestion/vector-indexer.d.ts +11 -15
  26. package/dist/ingestion/vector-indexer.d.ts.map +1 -1
  27. package/dist/ingestion/vector-indexer.js +32 -32
  28. package/dist/node/access/guard.js +60 -0
  29. package/dist/node/access/index.js +60 -0
  30. package/dist/node/index.js +454 -0
  31. package/dist/node/ingestion/document-processor.js +64 -0
  32. package/dist/node/ingestion/embedding-service.js +26 -0
  33. package/dist/node/ingestion/gmail-adapter.js +72 -0
  34. package/dist/node/ingestion/index.js +221 -0
  35. package/dist/node/ingestion/storage-adapter.js +31 -0
  36. package/dist/node/ingestion/vector-indexer.js +32 -0
  37. package/dist/node/query/index.js +79 -0
  38. package/dist/node/query/service.js +79 -0
  39. package/dist/node/retriever/index.js +100 -0
  40. package/dist/node/retriever/interface.js +0 -0
  41. package/dist/node/retriever/static-retriever.js +43 -0
  42. package/dist/node/retriever/vector-retriever.js +58 -0
  43. package/dist/node/types.js +0 -0
  44. package/dist/query/index.d.ts +2 -2
  45. package/dist/query/index.d.ts.map +1 -0
  46. package/dist/query/index.js +79 -2
  47. package/dist/query/service.d.ts +20 -24
  48. package/dist/query/service.d.ts.map +1 -1
  49. package/dist/query/service.js +76 -62
  50. package/dist/retriever/index.d.ts +4 -4
  51. package/dist/retriever/index.d.ts.map +1 -0
  52. package/dist/retriever/index.js +100 -3
  53. package/dist/retriever/interface.d.ts +38 -42
  54. package/dist/retriever/interface.d.ts.map +1 -1
  55. package/dist/retriever/interface.js +1 -0
  56. package/dist/retriever/static-retriever.d.ts +13 -17
  57. package/dist/retriever/static-retriever.d.ts.map +1 -1
  58. package/dist/retriever/static-retriever.js +42 -46
  59. package/dist/retriever/vector-retriever.d.ts +23 -27
  60. package/dist/retriever/vector-retriever.d.ts.map +1 -1
  61. package/dist/retriever/vector-retriever.js +57 -59
  62. package/dist/types.d.ts +34 -38
  63. package/dist/types.d.ts.map +1 -1
  64. package/dist/types.js +1 -0
  65. package/package.json +152 -45
  66. package/dist/access/guard.js.map +0 -1
  67. package/dist/ingestion/document-processor.js.map +0 -1
  68. package/dist/ingestion/embedding-service.js.map +0 -1
  69. package/dist/ingestion/gmail-adapter.js.map +0 -1
  70. package/dist/ingestion/storage-adapter.js.map +0 -1
  71. package/dist/ingestion/vector-indexer.js.map +0 -1
  72. package/dist/query/service.js.map +0 -1
  73. package/dist/retriever/static-retriever.js.map +0 -1
  74. package/dist/retriever/vector-retriever.js.map +0 -1
@@ -0,0 +1,26 @@
1
+ // src/ingestion/embedding-service.ts
2
+ class EmbeddingService {
3
+ provider;
4
+ batchSize;
5
+ constructor(provider, batchSize = 16) {
6
+ this.provider = provider;
7
+ this.batchSize = batchSize;
8
+ }
9
+ async embedFragments(fragments) {
10
+ const results = [];
11
+ for (let i = 0;i < fragments.length; i += this.batchSize) {
12
+ const slice = fragments.slice(i, i + this.batchSize);
13
+ const documents = slice.map((fragment) => ({
14
+ id: fragment.id,
15
+ text: fragment.text,
16
+ metadata: fragment.metadata
17
+ }));
18
+ const embeddings = await this.provider.embedDocuments(documents);
19
+ results.push(...embeddings);
20
+ }
21
+ return results;
22
+ }
23
+ }
24
+ export {
25
+ EmbeddingService
26
+ };
@@ -0,0 +1,72 @@
1
+ // src/ingestion/gmail-adapter.ts
2
+ class GmailIngestionAdapter {
3
+ gmail;
4
+ processor;
5
+ embeddings;
6
+ indexer;
7
+ constructor(gmail, processor, embeddings, indexer) {
8
+ this.gmail = gmail;
9
+ this.processor = processor;
10
+ this.embeddings = embeddings;
11
+ this.indexer = indexer;
12
+ }
13
+ async syncThreads(query) {
14
+ const threads = await this.gmail.listThreads(query);
15
+ for (const thread of threads) {
16
+ await this.ingestThread(thread);
17
+ }
18
+ }
19
+ async ingestThread(thread) {
20
+ const document = this.toRawDocument(thread);
21
+ const fragments = await this.processor.process(document);
22
+ const embeddings = await this.embeddings.embedFragments(fragments);
23
+ await this.indexer.upsert(fragments, embeddings);
24
+ }
25
+ toRawDocument(thread) {
26
+ const content = composeThreadText(thread);
27
+ return {
28
+ id: thread.id,
29
+ mimeType: "text/plain",
30
+ data: Buffer.from(content, "utf-8"),
31
+ metadata: {
32
+ subject: thread.subject ?? "",
33
+ participants: thread.participants.map((p) => p.email).join(", "),
34
+ updatedAt: thread.updatedAt.toISOString()
35
+ }
36
+ };
37
+ }
38
+ }
39
+ function composeThreadText(thread) {
40
+ const header = [
41
+ `Subject: ${thread.subject ?? ""}`,
42
+ `Snippet: ${thread.snippet ?? ""}`
43
+ ];
44
+ const messageTexts = thread.messages.map((message) => {
45
+ const parts = [
46
+ `From: ${formatAddress(message.from)}`,
47
+ `To: ${message.to.map(formatAddress).join(", ")}`
48
+ ];
49
+ if (message.sentAt) {
50
+ parts.push(`Date: ${message.sentAt.toISOString()}`);
51
+ }
52
+ const body = message.textBody ?? stripHtml(message.htmlBody ?? "");
53
+ return `${parts.join(`
54
+ `)}
55
+
56
+ ${body ?? ""}`;
57
+ });
58
+ return [...header, ...messageTexts].join(`
59
+
60
+ ---
61
+
62
+ `);
63
+ }
64
+ function formatAddress(address) {
65
+ return address.name ? `${address.name} <${address.email}>` : address.email;
66
+ }
67
+ function stripHtml(html) {
68
+ return html.replace(/<[^>]+>/g, " ");
69
+ }
70
+ export {
71
+ GmailIngestionAdapter
72
+ };
@@ -0,0 +1,221 @@
1
+ // src/ingestion/document-processor.ts
2
+ import { Buffer as Buffer2 } from "node:buffer";
3
+
4
+ class DocumentProcessor {
5
+ extractors = new Map;
6
+ constructor() {
7
+ this.registerExtractor("text/plain", this.extractText.bind(this));
8
+ this.registerExtractor("application/json", this.extractJson.bind(this));
9
+ }
10
+ registerExtractor(mimeType, extractor) {
11
+ this.extractors.set(mimeType.toLowerCase(), extractor);
12
+ }
13
+ async process(document) {
14
+ const extractor = this.extractors.get(document.mimeType.toLowerCase()) ?? this.extractors.get("*/*");
15
+ if (!extractor) {
16
+ throw new Error(`No extractor registered for mime type ${document.mimeType}`);
17
+ }
18
+ const fragments = await extractor(document);
19
+ if (fragments.length === 0) {
20
+ return [
21
+ {
22
+ id: `${document.id}:0`,
23
+ documentId: document.id,
24
+ text: "",
25
+ metadata: document.metadata
26
+ }
27
+ ];
28
+ }
29
+ return fragments;
30
+ }
31
+ async extractText(document) {
32
+ const text = Buffer2.from(document.data).toString("utf-8");
33
+ return [
34
+ {
35
+ id: `${document.id}:0`,
36
+ documentId: document.id,
37
+ text,
38
+ metadata: document.metadata
39
+ }
40
+ ];
41
+ }
42
+ async extractJson(document) {
43
+ const text = Buffer2.from(document.data).toString("utf-8");
44
+ try {
45
+ const json = JSON.parse(text);
46
+ return [
47
+ {
48
+ id: `${document.id}:0`,
49
+ documentId: document.id,
50
+ text: JSON.stringify(json, null, 2),
51
+ metadata: {
52
+ ...document.metadata,
53
+ contentType: "application/json"
54
+ }
55
+ }
56
+ ];
57
+ } catch {
58
+ return this.extractText(document);
59
+ }
60
+ }
61
+ }
62
+
63
+ // src/ingestion/embedding-service.ts
64
+ class EmbeddingService {
65
+ provider;
66
+ batchSize;
67
+ constructor(provider, batchSize = 16) {
68
+ this.provider = provider;
69
+ this.batchSize = batchSize;
70
+ }
71
+ async embedFragments(fragments) {
72
+ const results = [];
73
+ for (let i = 0;i < fragments.length; i += this.batchSize) {
74
+ const slice = fragments.slice(i, i + this.batchSize);
75
+ const documents = slice.map((fragment) => ({
76
+ id: fragment.id,
77
+ text: fragment.text,
78
+ metadata: fragment.metadata
79
+ }));
80
+ const embeddings = await this.provider.embedDocuments(documents);
81
+ results.push(...embeddings);
82
+ }
83
+ return results;
84
+ }
85
+ }
86
+
87
+ // src/ingestion/vector-indexer.ts
88
+ class VectorIndexer {
89
+ provider;
90
+ config;
91
+ constructor(provider, config) {
92
+ this.provider = provider;
93
+ this.config = config;
94
+ }
95
+ async upsert(fragments, embeddings) {
96
+ const documents = embeddings.map((embedding) => {
97
+ const fragment = fragments.find((f) => f.id === embedding.id);
98
+ return {
99
+ id: embedding.id,
100
+ vector: embedding.vector,
101
+ payload: {
102
+ ...this.config.metadata,
103
+ ...fragment?.metadata ?? {},
104
+ documentId: fragment?.documentId
105
+ },
106
+ namespace: this.config.namespace
107
+ };
108
+ });
109
+ const request = {
110
+ collection: this.config.collection,
111
+ documents
112
+ };
113
+ await this.provider.upsert(request);
114
+ }
115
+ }
116
+
117
+ // src/ingestion/gmail-adapter.ts
118
+ class GmailIngestionAdapter {
119
+ gmail;
120
+ processor;
121
+ embeddings;
122
+ indexer;
123
+ constructor(gmail, processor, embeddings, indexer) {
124
+ this.gmail = gmail;
125
+ this.processor = processor;
126
+ this.embeddings = embeddings;
127
+ this.indexer = indexer;
128
+ }
129
+ async syncThreads(query) {
130
+ const threads = await this.gmail.listThreads(query);
131
+ for (const thread of threads) {
132
+ await this.ingestThread(thread);
133
+ }
134
+ }
135
+ async ingestThread(thread) {
136
+ const document = this.toRawDocument(thread);
137
+ const fragments = await this.processor.process(document);
138
+ const embeddings = await this.embeddings.embedFragments(fragments);
139
+ await this.indexer.upsert(fragments, embeddings);
140
+ }
141
+ toRawDocument(thread) {
142
+ const content = composeThreadText(thread);
143
+ return {
144
+ id: thread.id,
145
+ mimeType: "text/plain",
146
+ data: Buffer.from(content, "utf-8"),
147
+ metadata: {
148
+ subject: thread.subject ?? "",
149
+ participants: thread.participants.map((p) => p.email).join(", "),
150
+ updatedAt: thread.updatedAt.toISOString()
151
+ }
152
+ };
153
+ }
154
+ }
155
+ function composeThreadText(thread) {
156
+ const header = [
157
+ `Subject: ${thread.subject ?? ""}`,
158
+ `Snippet: ${thread.snippet ?? ""}`
159
+ ];
160
+ const messageTexts = thread.messages.map((message) => {
161
+ const parts = [
162
+ `From: ${formatAddress(message.from)}`,
163
+ `To: ${message.to.map(formatAddress).join(", ")}`
164
+ ];
165
+ if (message.sentAt) {
166
+ parts.push(`Date: ${message.sentAt.toISOString()}`);
167
+ }
168
+ const body = message.textBody ?? stripHtml(message.htmlBody ?? "");
169
+ return `${parts.join(`
170
+ `)}
171
+
172
+ ${body ?? ""}`;
173
+ });
174
+ return [...header, ...messageTexts].join(`
175
+
176
+ ---
177
+
178
+ `);
179
+ }
180
+ function formatAddress(address) {
181
+ return address.name ? `${address.name} <${address.email}>` : address.email;
182
+ }
183
+ function stripHtml(html) {
184
+ return html.replace(/<[^>]+>/g, " ");
185
+ }
186
+
187
+ // src/ingestion/storage-adapter.ts
188
+ class StorageIngestionAdapter {
189
+ processor;
190
+ embeddings;
191
+ indexer;
192
+ constructor(processor, embeddings, indexer) {
193
+ this.processor = processor;
194
+ this.embeddings = embeddings;
195
+ this.indexer = indexer;
196
+ }
197
+ async ingestObject(object) {
198
+ if (!("data" in object) || !object.data) {
199
+ throw new Error("Storage ingestion requires object data");
200
+ }
201
+ const raw = {
202
+ id: object.key,
203
+ mimeType: object.contentType ?? "application/octet-stream",
204
+ data: object.data,
205
+ metadata: {
206
+ bucket: object.bucket,
207
+ checksum: object.checksum ?? ""
208
+ }
209
+ };
210
+ const fragments = await this.processor.process(raw);
211
+ const embeddings = await this.embeddings.embedFragments(fragments);
212
+ await this.indexer.upsert(fragments, embeddings);
213
+ }
214
+ }
215
+ export {
216
+ VectorIndexer,
217
+ StorageIngestionAdapter,
218
+ GmailIngestionAdapter,
219
+ EmbeddingService,
220
+ DocumentProcessor
221
+ };
@@ -0,0 +1,31 @@
1
+ // src/ingestion/storage-adapter.ts
2
+ class StorageIngestionAdapter {
3
+ processor;
4
+ embeddings;
5
+ indexer;
6
+ constructor(processor, embeddings, indexer) {
7
+ this.processor = processor;
8
+ this.embeddings = embeddings;
9
+ this.indexer = indexer;
10
+ }
11
+ async ingestObject(object) {
12
+ if (!("data" in object) || !object.data) {
13
+ throw new Error("Storage ingestion requires object data");
14
+ }
15
+ const raw = {
16
+ id: object.key,
17
+ mimeType: object.contentType ?? "application/octet-stream",
18
+ data: object.data,
19
+ metadata: {
20
+ bucket: object.bucket,
21
+ checksum: object.checksum ?? ""
22
+ }
23
+ };
24
+ const fragments = await this.processor.process(raw);
25
+ const embeddings = await this.embeddings.embedFragments(fragments);
26
+ await this.indexer.upsert(fragments, embeddings);
27
+ }
28
+ }
29
+ export {
30
+ StorageIngestionAdapter
31
+ };
@@ -0,0 +1,32 @@
1
+ // src/ingestion/vector-indexer.ts
2
+ class VectorIndexer {
3
+ provider;
4
+ config;
5
+ constructor(provider, config) {
6
+ this.provider = provider;
7
+ this.config = config;
8
+ }
9
+ async upsert(fragments, embeddings) {
10
+ const documents = embeddings.map((embedding) => {
11
+ const fragment = fragments.find((f) => f.id === embedding.id);
12
+ return {
13
+ id: embedding.id,
14
+ vector: embedding.vector,
15
+ payload: {
16
+ ...this.config.metadata,
17
+ ...fragment?.metadata ?? {},
18
+ documentId: fragment?.documentId
19
+ },
20
+ namespace: this.config.namespace
21
+ };
22
+ });
23
+ const request = {
24
+ collection: this.config.collection,
25
+ documents
26
+ };
27
+ await this.provider.upsert(request);
28
+ }
29
+ }
30
+ export {
31
+ VectorIndexer
32
+ };
@@ -0,0 +1,79 @@
1
+ // src/query/service.ts
2
+ class KnowledgeQueryService {
3
+ embeddings;
4
+ vectorStore;
5
+ llm;
6
+ config;
7
+ constructor(embeddings, vectorStore, llm, config) {
8
+ this.embeddings = embeddings;
9
+ this.vectorStore = vectorStore;
10
+ this.llm = llm;
11
+ this.config = config;
12
+ }
13
+ async query(question) {
14
+ const embedding = await this.embeddings.embedQuery(question);
15
+ const results = await this.vectorStore.search({
16
+ collection: this.config.collection,
17
+ vector: embedding.vector,
18
+ topK: this.config.topK ?? 5,
19
+ namespace: this.config.namespace,
20
+ filter: undefined
21
+ });
22
+ const context = buildContext(results);
23
+ const messages = this.buildMessages(question, context);
24
+ const response = await this.llm.chat(messages);
25
+ return {
26
+ answer: response.message.content.map((part) => ("text" in part) ? part.text : "").join(""),
27
+ references: results.map((result) => ({
28
+ ...result,
29
+ text: extractText(result)
30
+ })),
31
+ usage: response.usage
32
+ };
33
+ }
34
+ buildMessages(question, context) {
35
+ const systemPrompt = this.config.systemPrompt ?? "You are a knowledge assistant that answers questions using the provided context. Cite relevant sources if possible.";
36
+ return [
37
+ {
38
+ role: "system",
39
+ content: [{ type: "text", text: systemPrompt }]
40
+ },
41
+ {
42
+ role: "user",
43
+ content: [
44
+ {
45
+ type: "text",
46
+ text: `Question:
47
+ ${question}
48
+
49
+ Context:
50
+ ${context}`
51
+ }
52
+ ]
53
+ }
54
+ ];
55
+ }
56
+ }
57
+ function buildContext(results) {
58
+ if (results.length === 0) {
59
+ return "No relevant documents found.";
60
+ }
61
+ return results.map((result, index) => {
62
+ const text = extractText(result);
63
+ return `Source ${index + 1} (score: ${result.score.toFixed(3)}):
64
+ ${text}`;
65
+ }).join(`
66
+
67
+ `);
68
+ }
69
+ function extractText(result) {
70
+ const payload = result.payload ?? {};
71
+ if (typeof payload.text === "string")
72
+ return payload.text;
73
+ if (typeof payload.content === "string")
74
+ return payload.content;
75
+ return JSON.stringify(payload);
76
+ }
77
+ export {
78
+ KnowledgeQueryService
79
+ };
@@ -0,0 +1,79 @@
1
+ // src/query/service.ts
2
+ class KnowledgeQueryService {
3
+ embeddings;
4
+ vectorStore;
5
+ llm;
6
+ config;
7
+ constructor(embeddings, vectorStore, llm, config) {
8
+ this.embeddings = embeddings;
9
+ this.vectorStore = vectorStore;
10
+ this.llm = llm;
11
+ this.config = config;
12
+ }
13
+ async query(question) {
14
+ const embedding = await this.embeddings.embedQuery(question);
15
+ const results = await this.vectorStore.search({
16
+ collection: this.config.collection,
17
+ vector: embedding.vector,
18
+ topK: this.config.topK ?? 5,
19
+ namespace: this.config.namespace,
20
+ filter: undefined
21
+ });
22
+ const context = buildContext(results);
23
+ const messages = this.buildMessages(question, context);
24
+ const response = await this.llm.chat(messages);
25
+ return {
26
+ answer: response.message.content.map((part) => ("text" in part) ? part.text : "").join(""),
27
+ references: results.map((result) => ({
28
+ ...result,
29
+ text: extractText(result)
30
+ })),
31
+ usage: response.usage
32
+ };
33
+ }
34
+ buildMessages(question, context) {
35
+ const systemPrompt = this.config.systemPrompt ?? "You are a knowledge assistant that answers questions using the provided context. Cite relevant sources if possible.";
36
+ return [
37
+ {
38
+ role: "system",
39
+ content: [{ type: "text", text: systemPrompt }]
40
+ },
41
+ {
42
+ role: "user",
43
+ content: [
44
+ {
45
+ type: "text",
46
+ text: `Question:
47
+ ${question}
48
+
49
+ Context:
50
+ ${context}`
51
+ }
52
+ ]
53
+ }
54
+ ];
55
+ }
56
+ }
57
+ function buildContext(results) {
58
+ if (results.length === 0) {
59
+ return "No relevant documents found.";
60
+ }
61
+ return results.map((result, index) => {
62
+ const text = extractText(result);
63
+ return `Source ${index + 1} (score: ${result.score.toFixed(3)}):
64
+ ${text}`;
65
+ }).join(`
66
+
67
+ `);
68
+ }
69
+ function extractText(result) {
70
+ const payload = result.payload ?? {};
71
+ if (typeof payload.text === "string")
72
+ return payload.text;
73
+ if (typeof payload.content === "string")
74
+ return payload.content;
75
+ return JSON.stringify(payload);
76
+ }
77
+ export {
78
+ KnowledgeQueryService
79
+ };
@@ -0,0 +1,100 @@
1
+ // src/retriever/static-retriever.ts
2
+ class StaticRetriever {
3
+ content;
4
+ constructor(config) {
5
+ this.content = config.content instanceof Map ? config.content : new Map(Object.entries(config.content));
6
+ }
7
+ async retrieve(query, options) {
8
+ const content = this.content.get(options.spaceKey);
9
+ if (!content)
10
+ return [];
11
+ const queryLower = query.toLowerCase();
12
+ const lines = content.split(`
13
+ `).filter((line) => line.trim());
14
+ const results = [];
15
+ for (const line of lines) {
16
+ if (line.toLowerCase().includes(queryLower)) {
17
+ results.push({
18
+ content: line,
19
+ source: options.spaceKey,
20
+ score: 1,
21
+ metadata: { type: "static" }
22
+ });
23
+ }
24
+ }
25
+ return results.slice(0, options.topK ?? 5);
26
+ }
27
+ async getStatic(spaceKey) {
28
+ return this.content.get(spaceKey) ?? null;
29
+ }
30
+ supportsSpace(spaceKey) {
31
+ return this.content.has(spaceKey);
32
+ }
33
+ listSpaces() {
34
+ return [...this.content.keys()];
35
+ }
36
+ }
37
+ function createStaticRetriever(content) {
38
+ return new StaticRetriever({ content });
39
+ }
40
+
41
+ // src/retriever/vector-retriever.ts
42
+ class VectorRetriever {
43
+ config;
44
+ spaceCollections;
45
+ staticContent;
46
+ constructor(config) {
47
+ this.config = config;
48
+ this.spaceCollections = config.spaceCollections instanceof Map ? config.spaceCollections : new Map(Object.entries(config.spaceCollections));
49
+ this.staticContent = config.staticContent ? config.staticContent instanceof Map ? config.staticContent : new Map(Object.entries(config.staticContent)) : new Map;
50
+ }
51
+ async retrieve(query, options) {
52
+ const collection = this.spaceCollections.get(options.spaceKey);
53
+ if (!collection) {
54
+ return [];
55
+ }
56
+ const embedding = await this.config.embeddings.embedQuery(query);
57
+ const results = await this.config.vectorStore.search({
58
+ collection,
59
+ vector: embedding.vector,
60
+ topK: options.topK ?? this.config.defaultTopK ?? 5,
61
+ namespace: options.tenantId,
62
+ filter: options.filter
63
+ });
64
+ const minScore = options.minScore ?? this.config.defaultMinScore ?? 0;
65
+ const filtered = results.filter((r) => r.score >= minScore);
66
+ return filtered.map((result) => ({
67
+ content: this.extractContent(result.payload),
68
+ source: result.id,
69
+ score: result.score,
70
+ metadata: result.payload
71
+ }));
72
+ }
73
+ async getStatic(spaceKey) {
74
+ return this.staticContent.get(spaceKey) ?? null;
75
+ }
76
+ supportsSpace(spaceKey) {
77
+ return this.spaceCollections.has(spaceKey);
78
+ }
79
+ listSpaces() {
80
+ return [...this.spaceCollections.keys()];
81
+ }
82
+ extractContent(payload) {
83
+ if (!payload)
84
+ return "";
85
+ if (typeof payload.text === "string")
86
+ return payload.text;
87
+ if (typeof payload.content === "string")
88
+ return payload.content;
89
+ return JSON.stringify(payload);
90
+ }
91
+ }
92
+ function createVectorRetriever(config) {
93
+ return new VectorRetriever(config);
94
+ }
95
+ export {
96
+ createVectorRetriever,
97
+ createStaticRetriever,
98
+ VectorRetriever,
99
+ StaticRetriever
100
+ };
File without changes
@@ -0,0 +1,43 @@
1
+ // src/retriever/static-retriever.ts
2
+ class StaticRetriever {
3
+ content;
4
+ constructor(config) {
5
+ this.content = config.content instanceof Map ? config.content : new Map(Object.entries(config.content));
6
+ }
7
+ async retrieve(query, options) {
8
+ const content = this.content.get(options.spaceKey);
9
+ if (!content)
10
+ return [];
11
+ const queryLower = query.toLowerCase();
12
+ const lines = content.split(`
13
+ `).filter((line) => line.trim());
14
+ const results = [];
15
+ for (const line of lines) {
16
+ if (line.toLowerCase().includes(queryLower)) {
17
+ results.push({
18
+ content: line,
19
+ source: options.spaceKey,
20
+ score: 1,
21
+ metadata: { type: "static" }
22
+ });
23
+ }
24
+ }
25
+ return results.slice(0, options.topK ?? 5);
26
+ }
27
+ async getStatic(spaceKey) {
28
+ return this.content.get(spaceKey) ?? null;
29
+ }
30
+ supportsSpace(spaceKey) {
31
+ return this.content.has(spaceKey);
32
+ }
33
+ listSpaces() {
34
+ return [...this.content.keys()];
35
+ }
36
+ }
37
+ function createStaticRetriever(content) {
38
+ return new StaticRetriever({ content });
39
+ }
40
+ export {
41
+ createStaticRetriever,
42
+ StaticRetriever
43
+ };