agent-rag-mcp 0.6.0 → 0.8.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.
- package/README.md +20 -2
- package/dist/extensions/agent-rag.mjs +40 -17
- package/dist/src/adapters/image-ocr.mjs +16 -4
- package/dist/src/adapters/pdf.mjs +41 -35
- package/dist/src/pi/cache-status.mjs +18 -0
- package/dist/src/pi/cli-bridge.mjs +40 -0
- package/dist/src/retrieve/find.mjs +16 -10
- package/dist/src/retrieve/read.mjs +38 -31
- package/dist/src/retrieve/semantic.mjs +236 -0
- package/dist/src/server.mjs +18 -6
- package/dist/src/store/backup.mjs +279 -19
- package/dist/src/tools/schema.mjs +24 -2
- package/package.json +3 -1
- package/skills/agent-rag/SKILL.md +12 -0
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
|
-
import * as path from "node:path";
|
|
3
2
|
import { DatabaseSync } from "node:sqlite";
|
|
4
|
-
import { getExtractorForPath } from "../adapters/registry.mjs";
|
|
5
3
|
import { clientDbPath } from "../store/db.mjs";
|
|
6
|
-
import { readObject } from "../store/objects.mjs";
|
|
7
4
|
function failure(namespace, code, message) {
|
|
8
5
|
return { namespace, error: { code, message } };
|
|
9
6
|
}
|
|
@@ -20,6 +17,30 @@ function limitUtf8(text, maxBytes) {
|
|
|
20
17
|
}
|
|
21
18
|
return { text: "", truncated: true };
|
|
22
19
|
}
|
|
20
|
+
function startLineOffset(text, startLine) {
|
|
21
|
+
if (startLine === 0) return 0;
|
|
22
|
+
let line = 0;
|
|
23
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
24
|
+
if (text[index] !== "\r" && text[index] !== "\n") continue;
|
|
25
|
+
if (text[index] === "\r" && text[index + 1] === "\n") index += 1;
|
|
26
|
+
line += 1;
|
|
27
|
+
if (line === startLine) return index + 1;
|
|
28
|
+
}
|
|
29
|
+
return text.length;
|
|
30
|
+
}
|
|
31
|
+
function countLines(text) {
|
|
32
|
+
if (text.length === 0) return 0;
|
|
33
|
+
let lines = 1;
|
|
34
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
35
|
+
if (text[index] === "\r" && text[index + 1] === "\n") {
|
|
36
|
+
lines += 1;
|
|
37
|
+
index += 1;
|
|
38
|
+
} else if (text[index] === "\r" || text[index] === "\n") {
|
|
39
|
+
lines += 1;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return lines;
|
|
43
|
+
}
|
|
23
44
|
function limitLines(text, maxLines) {
|
|
24
45
|
if (text.length === 0) return { text, truncated: false };
|
|
25
46
|
if (maxLines === 0) return { text: "", truncated: true };
|
|
@@ -34,9 +55,9 @@ function limitLines(text, maxLines) {
|
|
|
34
55
|
return { text, truncated: false };
|
|
35
56
|
}
|
|
36
57
|
async function readFromCitation(input) {
|
|
37
|
-
const { root, namespace, docVersionId, chunkOrdinal, maxBytes, maxLines } = input;
|
|
38
|
-
if (!Number.isInteger(maxBytes) || maxBytes < 0 || !Number.isInteger(maxLines) || maxLines < 0) {
|
|
39
|
-
return failure(namespace, "invalid_read_limit", "maxBytes and
|
|
58
|
+
const { root, namespace, docVersionId, chunkOrdinal, maxBytes, maxLines, startLine = 0 } = input;
|
|
59
|
+
if (!Number.isInteger(maxBytes) || maxBytes < 0 || !Number.isInteger(maxLines) || maxLines < 0 || !Number.isInteger(startLine) || startLine < 0) {
|
|
60
|
+
return failure(namespace, "invalid_read_limit", "maxBytes, maxLines, and startLine must be non-negative integers.");
|
|
40
61
|
}
|
|
41
62
|
let db;
|
|
42
63
|
try {
|
|
@@ -45,45 +66,31 @@ async function readFromCitation(input) {
|
|
|
45
66
|
return failure(namespace, "database_not_found", `No database exists for namespace ${namespace.client}/${namespace.project}.`);
|
|
46
67
|
}
|
|
47
68
|
db = new DatabaseSync(dbPath, { readOnly: true });
|
|
48
|
-
const citation = db.prepare(`SELECT
|
|
69
|
+
const citation = db.prepare(`SELECT c.text AS text,
|
|
70
|
+
(SELECT COUNT(*) FROM chunk AS total_chunks WHERE total_chunks.doc_version_id = c.doc_version_id) AS totalChunks
|
|
49
71
|
FROM chunk AS c
|
|
50
72
|
JOIN doc_version AS dv ON dv.doc_version_id = c.doc_version_id
|
|
51
73
|
JOIN document AS d ON d.document_id = dv.document_id
|
|
52
74
|
JOIN project AS p ON p.project_id = d.project_id
|
|
53
75
|
JOIN client AS cl ON cl.client_id = p.client_id
|
|
54
|
-
LEFT JOIN object AS o ON o.sha256 = dv.sha256
|
|
55
76
|
WHERE c.doc_version_id = ? AND c.ordinal = ? AND cl.name = ? AND p.slug = ?`).get(docVersionId, chunkOrdinal, namespace.client, namespace.project);
|
|
56
77
|
if (!citation) return failure(namespace, "citation_not_found", "The citation does not exist in the requested document version and namespace.");
|
|
57
|
-
|
|
58
|
-
let bytes;
|
|
59
|
-
try {
|
|
60
|
-
const objectPath = path.resolve(root, citation.relPath);
|
|
61
|
-
const rootPath = path.resolve(root);
|
|
62
|
-
if (objectPath !== rootPath && !objectPath.startsWith(`${rootPath}${path.sep}`)) {
|
|
63
|
-
return failure(namespace, "object_path_invalid", "The recorded object path escapes the configured root.");
|
|
64
|
-
}
|
|
65
|
-
bytes = await readObject(root, citation.sha256);
|
|
66
|
-
} catch (error) {
|
|
67
|
-
if (error.code === "ENOENT") {
|
|
68
|
-
return failure(namespace, "object_missing", "The citation's recorded object file is missing.");
|
|
69
|
-
}
|
|
70
|
-
throw error;
|
|
71
|
-
}
|
|
72
|
-
const extracted = await getExtractorForPath(citation.label).extract(bytes);
|
|
73
|
-
const chunkText = extracted.sections[chunkOrdinal]?.text;
|
|
74
|
-
if (chunkText === void 0) {
|
|
75
|
-
return failure(namespace, "citation_not_found", "The stored object does not contain the requested extracted section.");
|
|
76
|
-
}
|
|
78
|
+
const chunkText = citation.text.slice(startLineOffset(citation.text, startLine));
|
|
77
79
|
const byteLimited = limitUtf8(chunkText, maxBytes);
|
|
78
80
|
const lineLimited = limitLines(byteLimited.text, maxLines);
|
|
79
|
-
const
|
|
81
|
+
const truncatedBy = byteLimited.truncated ? "bytes" : lineLimited.truncated ? "lines" : null;
|
|
82
|
+
const totalChunks = citation.totalChunks;
|
|
80
83
|
return {
|
|
81
84
|
namespace,
|
|
82
85
|
result: {
|
|
83
86
|
text: lineLimited.text,
|
|
84
|
-
truncated:
|
|
87
|
+
truncated: truncatedBy !== null,
|
|
85
88
|
totalChunks,
|
|
86
|
-
nextChunkOrdinal: chunkOrdinal + 1 < totalChunks ? chunkOrdinal + 1 : null
|
|
89
|
+
nextChunkOrdinal: chunkOrdinal + 1 < totalChunks ? chunkOrdinal + 1 : null,
|
|
90
|
+
chunkBytes: Buffer.byteLength(citation.text, "utf8"),
|
|
91
|
+
returnedBytes: Buffer.byteLength(lineLimited.text, "utf8"),
|
|
92
|
+
returnedLines: countLines(lineLimited.text),
|
|
93
|
+
truncatedBy
|
|
87
94
|
}
|
|
88
95
|
};
|
|
89
96
|
} catch (error) {
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { DatabaseSync } from "node:sqlite";
|
|
5
|
+
import { clientDbPath } from "../store/db.mjs";
|
|
6
|
+
const MAX_CHUNK_CHARS = 8192;
|
|
7
|
+
const TIMEOUT_MS = 3e4;
|
|
8
|
+
const MAX_RANKED_RESULTS = 100;
|
|
9
|
+
async function ollamaEmbed(model, texts, signal) {
|
|
10
|
+
const timeout = AbortSignal.timeout(TIMEOUT_MS);
|
|
11
|
+
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
12
|
+
const response = await fetch("http://127.0.0.1:11434/api/embed", {
|
|
13
|
+
method: "POST",
|
|
14
|
+
headers: { "content-type": "application/json" },
|
|
15
|
+
body: JSON.stringify({ model, input: texts, truncate: false }),
|
|
16
|
+
signal: combined,
|
|
17
|
+
redirect: "error"
|
|
18
|
+
});
|
|
19
|
+
if (!response.ok) throw new Error(`Local embedding service returned HTTP ${response.status}.`);
|
|
20
|
+
const data = await response.json();
|
|
21
|
+
if (!data || typeof data !== "object" || !("embeddings" in data)) throw new Error("Embedding response is invalid.");
|
|
22
|
+
return data.embeddings;
|
|
23
|
+
}
|
|
24
|
+
function azureEmbeddingEndpoint(value) {
|
|
25
|
+
let url;
|
|
26
|
+
try {
|
|
27
|
+
url = new URL(value);
|
|
28
|
+
} catch {
|
|
29
|
+
throw new Error("invalid_azure_endpoint");
|
|
30
|
+
}
|
|
31
|
+
const validHost = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.(?:openai\.azure\.com|services\.ai\.azure\.com|cognitiveservices\.azure\.com)$/i.test(url.hostname);
|
|
32
|
+
const validPath = ["", "/", "/openai/v1", "/openai/v1/"].includes(url.pathname);
|
|
33
|
+
if (url.protocol !== "https:" || !validHost || !validPath || url.username || url.password || url.port || url.search || url.hash) throw new Error("invalid_azure_endpoint");
|
|
34
|
+
return `${url.origin}/openai/v1/embeddings`;
|
|
35
|
+
}
|
|
36
|
+
function createAzureEmbed(endpoint, apiKey) {
|
|
37
|
+
const target = azureEmbeddingEndpoint(endpoint);
|
|
38
|
+
if (!apiKey.trim()) throw new Error("missing_azure_api_key");
|
|
39
|
+
return async (deployment, texts, signal) => {
|
|
40
|
+
const timeout = AbortSignal.timeout(TIMEOUT_MS);
|
|
41
|
+
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
42
|
+
const response = await fetch(target, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
headers: { "content-type": "application/json", "api-key": apiKey },
|
|
45
|
+
body: JSON.stringify({ model: deployment, input: texts, encoding_format: "float" }),
|
|
46
|
+
signal: combined,
|
|
47
|
+
redirect: "error"
|
|
48
|
+
});
|
|
49
|
+
if (!response.ok) throw new Error("Azure embedding request failed.");
|
|
50
|
+
const body = await response.json();
|
|
51
|
+
if (!body || typeof body !== "object" || !("data" in body) || !Array.isArray(body.data) || body.data.length !== texts.length) throw new Error("Invalid Azure embedding response.");
|
|
52
|
+
const vectors = new Array(texts.length);
|
|
53
|
+
for (const entry of body.data) {
|
|
54
|
+
if (!entry || typeof entry !== "object" || !Number.isInteger(entry.index) || entry.index < 0 || entry.index >= texts.length || vectors[entry.index] !== void 0 || !Array.isArray(entry.embedding)) throw new Error("Invalid Azure embedding response.");
|
|
55
|
+
vectors[entry.index] = entry.embedding;
|
|
56
|
+
}
|
|
57
|
+
return vectors;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
async function findConfiguredSemantically(input, env = process.env, signal) {
|
|
61
|
+
const provider = env.RAG_EMBEDDING_PROVIDER ?? "ollama";
|
|
62
|
+
const batchSize = env.RAG_EMBEDDING_BATCH_SIZE === void 0 ? 8 : Number(env.RAG_EMBEDDING_BATCH_SIZE);
|
|
63
|
+
if (!Number.isInteger(batchSize) || batchSize < 1 || batchSize > 32) return { namespace: input.namespace, error: { code: "invalid_embedding_batch_size", message: "RAG_EMBEDDING_BATCH_SIZE must be an integer from 1 to 32." } };
|
|
64
|
+
const maxBatchBytes = env.RAG_EMBEDDING_BATCH_BYTES === void 0 ? 65536 : Number(env.RAG_EMBEDDING_BATCH_BYTES);
|
|
65
|
+
if (!Number.isInteger(maxBatchBytes) || maxBatchBytes < 1024 || maxBatchBytes > 1048576) return { namespace: input.namespace, error: { code: "invalid_embedding_batch_bytes", message: "RAG_EMBEDDING_BATCH_BYTES must be an integer from 1024 to 1048576." } };
|
|
66
|
+
const revision = env.RAG_EMBEDDING_REVISION ?? "";
|
|
67
|
+
if (provider === "ollama") return findSemantically({ ...input, model: env.RAG_EMBEDDING_MODEL ?? "", cacheIdentity: JSON.stringify(["ollama", env.RAG_EMBEDDING_MODEL ?? "", revision]), batchSize, maxBatchBytes }, ollamaEmbed, signal);
|
|
68
|
+
if (provider !== "azure") return { namespace: input.namespace, error: { code: "invalid_embedding_provider", message: "RAG_EMBEDDING_PROVIDER must be ollama or azure." } };
|
|
69
|
+
const endpoint = env.RAG_AZURE_OPENAI_ENDPOINT;
|
|
70
|
+
const key = env.RAG_AZURE_OPENAI_API_KEY;
|
|
71
|
+
const deployment = env.RAG_AZURE_OPENAI_DEPLOYMENT;
|
|
72
|
+
if (!endpoint || !key || !deployment?.trim()) return { namespace: input.namespace, error: { code: "semantic_not_configured", message: "Azure embeddings require endpoint, deployment and API key configuration." } };
|
|
73
|
+
let embed;
|
|
74
|
+
try {
|
|
75
|
+
embed = createAzureEmbed(endpoint, key);
|
|
76
|
+
} catch {
|
|
77
|
+
return { namespace: input.namespace, error: { code: "invalid_azure_endpoint", message: "Azure endpoint must be a supported HTTPS resource URL." } };
|
|
78
|
+
}
|
|
79
|
+
return findSemantically({ ...input, model: deployment, cacheIdentity: JSON.stringify(["azure", azureEmbeddingEndpoint(endpoint), deployment, revision]), batchSize, maxBatchBytes }, embed, signal);
|
|
80
|
+
}
|
|
81
|
+
function cosine(a, b) {
|
|
82
|
+
let dot = 0;
|
|
83
|
+
let aNorm = 0;
|
|
84
|
+
let bNorm = 0;
|
|
85
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
86
|
+
dot += a[i] * b[i];
|
|
87
|
+
aNorm += a[i] ** 2;
|
|
88
|
+
bNorm += b[i] ** 2;
|
|
89
|
+
}
|
|
90
|
+
if (!aNorm || !bNorm || !Number.isFinite(dot) || !Number.isFinite(aNorm) || !Number.isFinite(bNorm)) throw new Error("Embedding vector must be finite and nonzero.");
|
|
91
|
+
return dot / Math.sqrt(aNorm * bNorm);
|
|
92
|
+
}
|
|
93
|
+
async function findSemantically(input, embed = ollamaEmbed, signal) {
|
|
94
|
+
const { root, namespace, query, includeHistorical, excerptLength, model } = input;
|
|
95
|
+
const batchSize = input.batchSize ?? 8;
|
|
96
|
+
const maxBatchBytes = input.maxBatchBytes ?? 65536;
|
|
97
|
+
if (!model.trim()) return { namespace, error: { code: "semantic_not_configured", message: "Configure an embedding model." } };
|
|
98
|
+
if (!Number.isInteger(batchSize) || batchSize < 1 || batchSize > 32) return { namespace, error: { code: "invalid_embedding_batch_size", message: "Embedding batch size must be an integer from 1 to 32." } };
|
|
99
|
+
if (!Number.isInteger(maxBatchBytes) || maxBatchBytes < 1024 || maxBatchBytes > 1048576) return { namespace, error: { code: "invalid_embedding_batch_bytes", message: "Embedding batch bytes must be an integer from 1024 to 1048576." } };
|
|
100
|
+
if (query.length > MAX_CHUNK_CHARS) return { namespace, error: { code: "semantic_query_too_large", message: `Semantic queries must not exceed ${MAX_CHUNK_CHARS} characters.` } };
|
|
101
|
+
let db;
|
|
102
|
+
let cache;
|
|
103
|
+
let phase = "database";
|
|
104
|
+
try {
|
|
105
|
+
const dbPath = clientDbPath(root, namespace.client);
|
|
106
|
+
if (!fs.existsSync(dbPath) || !fs.statSync(dbPath).isFile()) return { namespace, error: { code: "database_not_found", message: "Namespace database was not found." } };
|
|
107
|
+
db = new DatabaseSync(dbPath, { readOnly: true });
|
|
108
|
+
const rows = db.prepare(`SELECT dv.doc_version_id AS docVersionId, d.document_id AS documentId,
|
|
109
|
+
e.entity_key AS entityKey, d.label AS label, dv.version_label AS versionLabel, dv.is_current AS isCurrent,
|
|
110
|
+
s.ordinal AS sectionOrdinal, c.ordinal AS chunkOrdinal, c.char_start AS charStart, c.char_end AS charEnd, c.text AS text
|
|
111
|
+
FROM chunk AS c JOIN doc_version AS dv ON dv.doc_version_id = c.doc_version_id
|
|
112
|
+
JOIN document AS d ON d.document_id = dv.document_id JOIN entity AS e ON e.entity_id = d.entity_id
|
|
113
|
+
JOIN project AS p ON p.project_id = d.project_id JOIN client AS cl ON cl.client_id = p.client_id
|
|
114
|
+
LEFT JOIN section AS s ON s.section_id = c.section_id
|
|
115
|
+
WHERE cl.name = ? AND p.slug = ? AND d.deleted_at IS NULL AND e.deleted_at IS NULL AND (dv.is_current = 1 OR ? = 1)
|
|
116
|
+
ORDER BY dv.doc_version_id COLLATE BINARY, c.ordinal`).iterate(namespace.client, namespace.project, includeHistorical ? 1 : 0);
|
|
117
|
+
const iterator = rows[Symbol.iterator]();
|
|
118
|
+
const first = iterator.next();
|
|
119
|
+
if (first.done) return { namespace, result: { citations: [], total: 0, searchMode: "semantic" } };
|
|
120
|
+
phase = "cache";
|
|
121
|
+
cache = new DatabaseSync(path.join(path.dirname(dbPath), "semantic-cache.sqlite"));
|
|
122
|
+
cache.exec("PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL;");
|
|
123
|
+
cache.exec(`CREATE TABLE IF NOT EXISTS vector_cache (
|
|
124
|
+
project TEXT NOT NULL, identity TEXT NOT NULL, doc_version_id TEXT NOT NULL, ordinal INTEGER NOT NULL,
|
|
125
|
+
text_hash TEXT NOT NULL, dimensions INTEGER NOT NULL, vector BLOB NOT NULL,
|
|
126
|
+
PRIMARY KEY(project, identity, doc_version_id, ordinal)
|
|
127
|
+
) WITHOUT ROWID`);
|
|
128
|
+
cache.exec("CREATE INDEX IF NOT EXISTS idx_vector_content ON vector_cache(project, identity, text_hash)");
|
|
129
|
+
const cacheIdentity = createHash("sha256").update(input.cacheIdentity ?? JSON.stringify(["direct", model])).digest("hex");
|
|
130
|
+
const select = cache.prepare("SELECT dimensions, vector FROM vector_cache WHERE project = ? AND identity = ? AND doc_version_id = ? AND ordinal = ? AND text_hash = ?");
|
|
131
|
+
const selectByContent = cache.prepare("SELECT dimensions, vector FROM vector_cache WHERE project = ? AND identity = ? AND text_hash = ? LIMIT 1");
|
|
132
|
+
const upsert = cache.prepare(`INSERT INTO vector_cache(project, identity, doc_version_id, ordinal, text_hash, dimensions, vector) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
133
|
+
ON CONFLICT(project, identity, doc_version_id, ordinal) DO UPDATE SET text_hash=excluded.text_hash, dimensions=excluded.dimensions, vector=excluded.vector`);
|
|
134
|
+
const validateVectors = (vectors, count, dimensions2) => {
|
|
135
|
+
if (!Array.isArray(vectors) || vectors.length !== count || !Array.isArray(vectors[0])) throw new Error("Invalid vector count.");
|
|
136
|
+
const size = dimensions2 ?? vectors[0].length;
|
|
137
|
+
if (size < 1 || size > 8192 || vectors.some((vector) => !Array.isArray(vector) || vector.length !== size || vector.some((n) => typeof n !== "number" || !Number.isFinite(n)))) throw new Error("Invalid vector dimensions.");
|
|
138
|
+
return size;
|
|
139
|
+
};
|
|
140
|
+
phase = "embedding";
|
|
141
|
+
const queryVectors = await embed(model, [query], signal);
|
|
142
|
+
const dimensions = validateVectors(queryVectors, 1);
|
|
143
|
+
const queryVector = queryVectors[0];
|
|
144
|
+
cosine(queryVector, queryVector);
|
|
145
|
+
const citations = [];
|
|
146
|
+
let total = 0;
|
|
147
|
+
const rank = (row, vector) => {
|
|
148
|
+
citations.push({ docVersionId: row.docVersionId, documentId: row.documentId, entityKey: row.entityKey, label: row.label, versionLabel: row.versionLabel, isCurrent: row.isCurrent === 1, sectionOrdinal: row.sectionOrdinal, chunkOrdinal: row.chunkOrdinal, charStart: row.charStart, charEnd: row.charEnd, matchStart: null, matchEnd: null, score: cosine(queryVector, vector), excerpt: row.text.slice(0, excerptLength) });
|
|
149
|
+
citations.sort((a, b) => b.score - a.score || a.docVersionId.localeCompare(b.docVersionId) || a.chunkOrdinal - b.chunkOrdinal);
|
|
150
|
+
if (citations.length > MAX_RANKED_RESULTS) citations.pop();
|
|
151
|
+
};
|
|
152
|
+
let pending = [];
|
|
153
|
+
let pendingBytes = 0;
|
|
154
|
+
const flush = async () => {
|
|
155
|
+
if (!pending.length) return;
|
|
156
|
+
phase = "embedding";
|
|
157
|
+
const vectors = await embed(model, pending.map((entry) => entry.row.text), signal);
|
|
158
|
+
validateVectors(vectors, pending.length, dimensions);
|
|
159
|
+
if (signal?.aborted) throw new Error("cancelled");
|
|
160
|
+
for (const vector of vectors) cosine(vector, vector);
|
|
161
|
+
phase = "cache";
|
|
162
|
+
cache.exec("BEGIN IMMEDIATE");
|
|
163
|
+
try {
|
|
164
|
+
for (const [index, entry] of pending.entries()) {
|
|
165
|
+
const vector = vectors[index];
|
|
166
|
+
const bytes = Buffer.allocUnsafe(dimensions * 4);
|
|
167
|
+
vector.forEach((value, offset) => {
|
|
168
|
+
if (!Number.isFinite(Math.fround(value))) throw new Error("Embedding value exceeds float32.");
|
|
169
|
+
bytes.writeFloatLE(value, offset * 4);
|
|
170
|
+
});
|
|
171
|
+
upsert.run(namespace.project, cacheIdentity, entry.row.docVersionId, entry.row.chunkOrdinal, entry.hash, dimensions, bytes);
|
|
172
|
+
rank(entry.row, Array.from({ length: dimensions }, (_, i) => bytes.readFloatLE(i * 4)));
|
|
173
|
+
}
|
|
174
|
+
cache.exec("COMMIT");
|
|
175
|
+
} catch (error) {
|
|
176
|
+
cache.exec("ROLLBACK");
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
pending = [];
|
|
180
|
+
pendingBytes = 0;
|
|
181
|
+
};
|
|
182
|
+
for (const row of { *[Symbol.iterator]() {
|
|
183
|
+
yield first.value;
|
|
184
|
+
yield* { [Symbol.iterator]: () => iterator };
|
|
185
|
+
} }) {
|
|
186
|
+
if (signal?.aborted) throw new Error("cancelled");
|
|
187
|
+
if (row.text.length > MAX_CHUNK_CHARS) return { namespace, error: { code: "semantic_chunk_too_large", message: `A chunk exceeds ${MAX_CHUNK_CHARS} characters; semantic search did not finish.` } };
|
|
188
|
+
total += 1;
|
|
189
|
+
const hash = createHash("sha256").update(row.text).digest("hex");
|
|
190
|
+
phase = "cache";
|
|
191
|
+
const cached = select.get(namespace.project, cacheIdentity, row.docVersionId, row.chunkOrdinal, hash) ?? selectByContent.get(namespace.project, cacheIdentity, hash);
|
|
192
|
+
if (cached) {
|
|
193
|
+
if (cached.dimensions !== dimensions || cached.vector.byteLength !== dimensions * 4) return { namespace, error: { code: "embedding_dimension_mismatch", message: "Cached vectors do not match this model. Set a new RAG_EMBEDDING_REVISION before rebuilding." } };
|
|
194
|
+
const bytes = Buffer.from(cached.vector);
|
|
195
|
+
rank(row, Array.from({ length: dimensions }, (_, i) => bytes.readFloatLE(i * 4)));
|
|
196
|
+
} else {
|
|
197
|
+
const textBytes = Buffer.byteLength(row.text, "utf8");
|
|
198
|
+
if (textBytes > maxBatchBytes) return { namespace, error: { code: "semantic_chunk_too_large", message: "A chunk exceeds RAG_EMBEDDING_BATCH_BYTES." } };
|
|
199
|
+
if (pendingBytes + textBytes > maxBatchBytes) await flush();
|
|
200
|
+
pending.push({ row, hash });
|
|
201
|
+
pendingBytes += textBytes;
|
|
202
|
+
if (pending.length >= batchSize) await flush();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
await flush();
|
|
206
|
+
return { namespace, result: { citations, total, searchMode: "semantic" } };
|
|
207
|
+
} catch {
|
|
208
|
+
if (signal?.aborted) return { namespace, error: { code: "cancelled", message: "Search was cancelled." } };
|
|
209
|
+
if (phase === "embedding") return { namespace, error: { code: "embedding_unavailable", message: "Embedding request failed; check the configured provider, model and access." } };
|
|
210
|
+
if (phase === "cache") return { namespace, error: { code: "semantic_cache_unavailable", message: "Semantic cache could not be read or written." } };
|
|
211
|
+
return { namespace, error: { code: "database_unavailable", message: "Could not load namespace chunks." } };
|
|
212
|
+
} finally {
|
|
213
|
+
cache?.close();
|
|
214
|
+
db?.close();
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function combineHybrid(lexical, semantic) {
|
|
218
|
+
const merged = /* @__PURE__ */ new Map();
|
|
219
|
+
for (const list of [lexical, semantic]) {
|
|
220
|
+
list.forEach((citation, index) => {
|
|
221
|
+
const key = JSON.stringify([citation.docVersionId, citation.chunkOrdinal]);
|
|
222
|
+
const current = merged.get(key);
|
|
223
|
+
if (current) current.score += 1 / (60 + index + 1);
|
|
224
|
+
else merged.set(key, { citation, score: 1 / (60 + index + 1) });
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
return [...merged.values()].map(({ citation, score }) => ({ ...citation, score })).sort((a, b) => b.score - a.score || a.docVersionId.localeCompare(b.docVersionId) || a.chunkOrdinal - b.chunkOrdinal);
|
|
228
|
+
}
|
|
229
|
+
export {
|
|
230
|
+
azureEmbeddingEndpoint,
|
|
231
|
+
combineHybrid,
|
|
232
|
+
createAzureEmbed,
|
|
233
|
+
findConfiguredSemantically,
|
|
234
|
+
findSemantically,
|
|
235
|
+
ollamaEmbed
|
|
236
|
+
};
|
package/dist/src/server.mjs
CHANGED
|
@@ -7,9 +7,12 @@ import {
|
|
|
7
7
|
import { discoverConfig } from "./config/discovery.mjs";
|
|
8
8
|
import { findInNamespace } from "./retrieve/find.mjs";
|
|
9
9
|
import { readFromCitation } from "./retrieve/read.mjs";
|
|
10
|
+
import { combineHybrid, findConfiguredSemantically } from "./retrieve/semantic.mjs";
|
|
10
11
|
import {
|
|
11
12
|
RAG_TOOLS,
|
|
12
13
|
parseCapabilities,
|
|
14
|
+
parseNamespaceAllowlist,
|
|
15
|
+
isNamespaceAllowed,
|
|
13
16
|
namespaceFromToolInput,
|
|
14
17
|
validateRagFindInput,
|
|
15
18
|
validateRagReadInput
|
|
@@ -24,12 +27,13 @@ function toolError(namespace, error) {
|
|
|
24
27
|
}
|
|
25
28
|
async function main() {
|
|
26
29
|
const capabilities = parseCapabilities(process.env.RAG_CAPABILITIES);
|
|
30
|
+
const allowlist = parseNamespaceAllowlist(process.env.RAG_ALLOWED_NAMESPACES);
|
|
27
31
|
const discovery = discoverConfig({ cwd: process.cwd(), homeDir: process.cwd(), argv: [], env: process.env });
|
|
28
32
|
const root = discovery.root;
|
|
29
33
|
const tools = RAG_TOOLS.filter((tool) => capabilities.has(tool.name === "rag_find" ? "find" : "read"));
|
|
30
34
|
const server = new Server({ name: "agent-rag", version: "0.1.0" }, { capabilities: { tools: { listChanged: false } } });
|
|
31
35
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
|
|
32
|
-
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
36
|
+
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
33
37
|
try {
|
|
34
38
|
const { name, arguments: args } = request.params;
|
|
35
39
|
if (name !== "rag_find" && name !== "rag_read") {
|
|
@@ -42,15 +46,23 @@ async function main() {
|
|
|
42
46
|
if (name === "rag_find") {
|
|
43
47
|
const check2 = validateRagFindInput(args);
|
|
44
48
|
if (!check2.ok) return toolError(check2.namespace, check2.error);
|
|
45
|
-
const { namespace: namespace2, query, limit, excerptChars } = check2.input;
|
|
46
|
-
|
|
47
|
-
|
|
49
|
+
const { namespace: namespace2, query, limit, excerptChars, includeHistorical, matchMode, searchMode } = check2.input;
|
|
50
|
+
if (!isNamespaceAllowed(allowlist, namespace2)) return toolError(namespace2, { code: "namespace_denied", message: "Namespace is not enabled for this process." });
|
|
51
|
+
const found = searchMode !== "lexical" ? await findConfiguredSemantically({ root, namespace: namespace2, query, excerptLength: excerptChars, includeHistorical }, process.env, extra.signal) : findInNamespace({ root, namespace: namespace2, query, excerptLength: excerptChars, includeHistorical, matchMode, maxResults: limit });
|
|
52
|
+
if ("error" in found && found.error) return toolError(namespace2, found.error);
|
|
53
|
+
if (searchMode === "hybrid") {
|
|
54
|
+
const lexical = findInNamespace({ root, namespace: namespace2, query, excerptLength: excerptChars, includeHistorical, matchMode, maxResults: 100 });
|
|
55
|
+
if ("error" in lexical) return toolError(namespace2, lexical.error);
|
|
56
|
+
const citations = combineHybrid(lexical.result.citations, found.result.citations);
|
|
57
|
+
return toolResult({ namespace: namespace2, result: { citations: citations.slice(0, limit), total: found.result.total, searchMode: "hybrid" } });
|
|
58
|
+
}
|
|
48
59
|
return toolResult({ namespace: namespace2, result: { ...found.result, citations: found.result.citations.slice(0, limit) } });
|
|
49
60
|
}
|
|
50
61
|
const check = validateRagReadInput(args);
|
|
51
62
|
if (!check.ok) return toolError(check.namespace, check.error);
|
|
52
|
-
const { namespace, docVersionId, chunkOrdinal, maxBytes, maxLines } = check.input;
|
|
53
|
-
|
|
63
|
+
const { namespace, docVersionId, chunkOrdinal, maxBytes, maxLines, startLine } = check.input;
|
|
64
|
+
if (!isNamespaceAllowed(allowlist, namespace)) return toolError(namespace, { code: "namespace_denied", message: "Namespace is not enabled for this process." });
|
|
65
|
+
const read = await readFromCitation({ root, namespace, docVersionId, chunkOrdinal, maxBytes, maxLines, startLine });
|
|
54
66
|
if ("error" in read) return toolError(namespace, read.error);
|
|
55
67
|
return toolResult({ namespace, result: read.result });
|
|
56
68
|
} catch (error) {
|