Initial public release

This commit is contained in:
Meta Vens 2026-04-24 13:17:00 +01:00
commit 05283b2604
88 changed files with 14882 additions and 0 deletions

View file

@ -0,0 +1,113 @@
import "dotenv/config";
import { resolve } from "node:path";
import { loadConfig } from "@voidbot/config";
import {
createTextEmbedder,
createVectorStores,
FileImportStateRepository,
FileMessageArchiveRepository,
HistoryIngester,
RagPipeline,
importDiscordLogs,
} from "@voidbot/rag";
interface CliOptions {
inputPath?: string;
recursive: boolean;
respectIndexingRules: boolean;
}
async function main(): Promise<void> {
if (!process.env.DISCORD_OWNER_ID) {
process.env.DISCORD_OWNER_ID = "__rag_backfill__";
}
const config = loadConfig();
const options = parseArgs(process.argv.slice(2));
const inputPath = options.inputPath ?? config.discordLogRoot;
if (!inputPath) {
throw new Error(
"Provide --input <path> or set DISCORD_LOG_ROOT before running the log backfill.",
);
}
const archiveRepository = new FileMessageArchiveRepository(config.ragArchivePath);
const embedder = createTextEmbedder({
backend: config.ragEmbeddingBackend,
hashDimensions: config.ragEmbeddingDimensions,
ollamaBaseUrl: config.ragOllamaBaseUrl,
ollamaModel: config.ragOllamaModel,
ollamaTimeoutMs: config.ragOllamaTimeoutMs,
queryInstruction: config.ragQueryInstruction,
});
const vectorStore = createVectorStores({
kind: config.vectorStore.kind,
historyPath: config.vectorStore.path,
sourceRoot: config.sourceVectorStoreRoot,
qdrant: config.qdrant,
historyEmbedder: embedder,
sourceEmbedder: embedder,
}).history;
const historyIngester = new HistoryIngester();
const ragPipeline = new RagPipeline(archiveRepository, historyIngester, vectorStore);
const importStateRepository = new FileImportStateRepository(config.ragImportStatePath);
const previousState = await importStateRepository.read();
const importResult = await importDiscordLogs(resolve(inputPath), {
recursive: options.recursive,
channelIndexing: options.respectIndexingRules ? config.channelIndexing : undefined,
previousState,
});
const ingestResult = await ragPipeline.upsertMessages(importResult.messages);
await importStateRepository.write(importResult.nextState);
console.log(`Input: ${resolve(inputPath)}`);
console.log(`Files scanned: ${importResult.filesScanned}`);
console.log(`Files imported: ${importResult.filesImported}`);
console.log(`Files skipped (unchanged): ${importResult.filesSkipped}`);
console.log(`Messages discovered: ${importResult.messages.length}`);
console.log(`Invalid records: ${importResult.invalidRecords}`);
console.log(
`Archive changes: created=${ingestResult.createdMessages}, updated=${ingestResult.updatedMessages}, unchanged=${ingestResult.unchangedMessages}`,
);
console.log(`Indexed chunks: ${ingestResult.indexedChunks}`);
}
function parseArgs(args: string[]): CliOptions {
const options: CliOptions = {
recursive: true,
respectIndexingRules: true,
};
for (let index = 0; index < args.length; index += 1) {
const argument = args[index];
if (argument === "--input") {
options.inputPath = args[index + 1];
index += 1;
continue;
}
if (argument === "--no-recursive") {
options.recursive = false;
continue;
}
if (argument === "--all-channels") {
options.respectIndexingRules = false;
continue;
}
throw new Error(`Unknown argument: ${argument}`);
}
return options;
}
void main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View file

@ -0,0 +1,267 @@
import { spawn } from "node:child_process";
import { access, mkdir, open, writeFile, readFile } from "node:fs/promises";
import { constants as fsConstants } from "node:fs";
import { join, resolve } from "node:path";
import { config as loadDotenv } from "dotenv";
const args = parseArgs(process.argv.slice(2));
if (!args.repoName) {
console.error("Missing required --repo-name argument.");
process.exit(1);
}
const voidbotRoot = resolve(args.voidbotRoot ?? process.cwd());
loadDotenv({ path: join(voidbotRoot, ".env") });
const storageRoot = resolve(
voidbotRoot,
process.env.STORAGE_ROOT && process.env.STORAGE_ROOT.trim().length > 0
? process.env.STORAGE_ROOT
: ".voidbot",
);
const safeRepoName = encodeURIComponent(args.repoName);
const logDir = join(storageRoot, "logs", "source-hooks");
const statusDir = join(storageRoot, "status", "source-hooks");
const logPath = join(logDir, `${safeRepoName}.log`);
const statusPath = join(statusDir, `${safeRepoName}.json`);
if (args.run) {
await runWorker();
} else {
await launchDetachedWorker();
}
async function launchDetachedWorker() {
await ensureDirectories();
const currentStatus = await readJson(statusPath);
if (typeof currentStatus?.pid === "number" && isProcessRunning(currentStatus.pid)) {
await writeStatus({
...currentStatus,
repoName: args.repoName,
logPath,
lastSkippedAt: new Date().toISOString(),
lastSkipReason: "already_running",
});
return;
}
const logHandle = await open(logPath, "a");
const child = spawn(
process.execPath,
[
join(voidbotRoot, "scripts", "git-post-push-index.mjs"),
"--run",
"--voidbot-root",
voidbotRoot,
"--repo-name",
args.repoName,
],
{
cwd: voidbotRoot,
detached: true,
stdio: ["ignore", logHandle.fd, logHandle.fd],
windowsHide: true,
env: process.env,
},
);
child.unref();
await logHandle.close();
await writeStatus({
state: "running",
repoName: args.repoName,
pid: child.pid,
queuedAt: new Date().toISOString(),
logPath,
});
}
async function runWorker() {
await ensureDirectories();
const sourceRepoRoot = process.env.SOURCE_REPO_ROOT
? resolve(process.env.SOURCE_REPO_ROOT)
: undefined;
const repoPath = sourceRepoRoot ? join(sourceRepoRoot, args.repoName) : undefined;
const startedAt = new Date().toISOString();
await writeStatus({
state: "running",
repoName: args.repoName,
pid: process.pid,
startedAt,
logPath,
repoPath,
});
process.stdout.write(`\n=== source hook run ${startedAt} repo=${args.repoName} ===\n`);
if (!sourceRepoRoot) {
const message = "SOURCE_REPO_ROOT is not configured in VoidBot's .env.";
process.stderr.write(`${message}\n`);
await writeStatus({
state: "failed",
repoName: args.repoName,
pid: process.pid,
startedAt,
completedAt: new Date().toISOString(),
exitCode: 1,
logPath,
error: message,
});
process.exit(1);
}
if (!(await pathExists(repoPath))) {
const message = `Configured repo path does not exist: ${repoPath}`;
process.stderr.write(`${message}\n`);
await writeStatus({
state: "failed",
repoName: args.repoName,
pid: process.pid,
startedAt,
completedAt: new Date().toISOString(),
exitCode: 1,
logPath,
repoPath,
error: message,
});
process.exit(1);
}
try {
const child =
process.platform === "win32"
? spawn(
"cmd.exe",
["/d", "/s", "/c", "npm.cmd", "run", "rag:index-sources", "--", "--repo", args.repoName],
{
cwd: voidbotRoot,
windowsHide: true,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
},
)
: spawn("npm", ["run", "rag:index-sources", "--", "--repo", args.repoName], {
cwd: voidbotRoot,
windowsHide: true,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
child.stdout.on("data", (chunk) => {
process.stdout.write(chunk);
});
child.stderr.on("data", (chunk) => {
process.stderr.write(chunk);
});
const exitCode = await new Promise((resolveExit, reject) => {
child.on("error", reject);
child.on("close", (code) => resolveExit(code ?? 1));
});
await writeStatus({
state: exitCode === 0 ? "completed" : "failed",
repoName: args.repoName,
pid: process.pid,
startedAt,
completedAt: new Date().toISOString(),
exitCode,
logPath,
repoPath,
});
process.exit(exitCode);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`${message}\n`);
await writeStatus({
state: "failed",
repoName: args.repoName,
pid: process.pid,
startedAt,
completedAt: new Date().toISOString(),
exitCode: 1,
logPath,
repoPath,
error: message,
});
process.exit(1);
}
}
async function ensureDirectories() {
await mkdir(logDir, { recursive: true });
await mkdir(statusDir, { recursive: true });
}
async function writeStatus(status) {
await writeFile(statusPath, `${JSON.stringify(status, null, 2)}\n`, "utf8");
}
async function readJson(path) {
try {
const content = await readFile(path, "utf8");
return JSON.parse(content);
} catch {
return undefined;
}
}
function isProcessRunning(pid) {
if (typeof pid !== "number" || !Number.isFinite(pid) || pid <= 0) {
return false;
}
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
async function pathExists(path) {
try {
await access(path, fsConstants.F_OK);
return true;
} catch {
return false;
}
}
function parseArgs(argv) {
const parsed = {
run: false,
voidbotRoot: undefined,
repoName: undefined,
};
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
if (argument === "--run") {
parsed.run = true;
continue;
}
if (argument === "--voidbot-root" && argv[index + 1]) {
parsed.voidbotRoot = argv[index + 1];
index += 1;
continue;
}
if (argument === "--repo-name" && argv[index + 1]) {
parsed.repoName = argv[index + 1];
index += 1;
}
}
return parsed;
}

View file

@ -0,0 +1,140 @@
import "dotenv/config";
import { readdir } from "node:fs/promises";
import { join } from "node:path";
import { loadConfig } from "@voidbot/config";
import {
crawlRepositoryDocuments,
createTextEmbedder,
createVectorStores,
FileSourceDocumentArchiveRepository,
SourceDocumentIngester,
SourceRagPipeline,
} from "@voidbot/rag";
interface ScriptOptions {
repos?: string[];
forceReindex?: boolean;
}
async function main(): Promise<void> {
if (!process.env.DISCORD_OWNER_ID) {
process.env.DISCORD_OWNER_ID = "__source_reindex__";
}
const options = parseArgs(process.argv.slice(2));
const config = loadConfig();
if (!config.sourceRepoRoot) {
throw new Error("SOURCE_REPO_ROOT is not configured.");
}
const repoNames =
options.repos && options.repos.length > 0
? options.repos
: await resolveRepoNames(config.sourceRepoRoot, config.sourceRepoPatterns);
if (repoNames.length === 0) {
throw new Error("No source repositories matched SOURCE_REPO_PATTERNS.");
}
const embedder = createTextEmbedder({
backend: config.ragEmbeddingBackend,
hashDimensions: config.ragEmbeddingDimensions,
ollamaBaseUrl: config.ragOllamaBaseUrl,
ollamaModel: config.ragOllamaModel,
ollamaTimeoutMs: config.ragOllamaTimeoutMs,
queryInstruction: config.ragQueryInstruction,
});
const vectorStore = createVectorStores({
kind: config.vectorStore.kind,
historyPath: config.vectorStore.path,
sourceRoot: config.sourceVectorStoreRoot,
qdrant: config.qdrant,
historyEmbedder: embedder,
sourceEmbedder: embedder,
}).source;
const archiveRepository = new FileSourceDocumentArchiveRepository(config.ragSourceArchivePath);
const sourceIngester = new SourceDocumentIngester();
const pipeline = new SourceRagPipeline(archiveRepository, sourceIngester, vectorStore);
let indexedRepositories = 0;
let totalDocuments = 0;
let totalChunks = 0;
for (const repoName of repoNames) {
const repoPath = join(config.sourceRepoRoot, repoName);
const scan = await crawlRepositoryDocuments(repoPath, repoName, {
includePathPrefixes: config.sourceRepoIncludePrefixes[repoName],
});
const result = await pipeline.syncRepoDocuments(repoName, scan.documents, {
forceReindex: options.forceReindex,
});
indexedRepositories += 1;
totalDocuments += scan.documents.length;
totalChunks += result.indexedChunks;
console.log(
[
`Repo ${repoName}:`,
`documents=${scan.documents.length}`,
`created=${result.createdDocuments}`,
`updated=${result.updatedDocuments}`,
`unchanged=${result.unchangedDocuments}`,
`deleted=${result.deletedDocuments}`,
`indexedChunks=${result.indexedChunks}`,
`skippedFiles=${scan.skippedFiles.length}`,
].join(" "),
);
}
console.log(`Indexed repositories: ${indexedRepositories}`);
console.log(`Indexed documents: ${totalDocuments}`);
console.log(`Indexed chunks: ${totalChunks}`);
}
function parseArgs(argv: string[]): ScriptOptions {
const options: ScriptOptions = {};
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
if ((argument === "--repo" || argument === "--repos") && argv[index + 1]) {
options.repos = argv[index + 1]
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
index += 1;
continue;
}
if (argument === "--force") {
options.forceReindex = true;
}
}
return options;
}
async function resolveRepoNames(root: string, patterns: string[]): Promise<string[]> {
const entries = await readdir(root, { withFileTypes: true });
const repoNames = entries
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.filter((name) => patterns.length === 0 || patterns.some((pattern) => matchesPattern(name, pattern)))
.sort((left, right) => left.localeCompare(right));
return repoNames;
}
function matchesPattern(value: string, pattern: string): boolean {
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
const regex = new RegExp(`^${escaped}$`, "i");
return regex.test(value);
}
void main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View file

@ -0,0 +1,65 @@
import { existsSync } from "node:fs";
import { spawn } from "node:child_process";
import { resolve } from "node:path";
import { config as loadDotenv } from "dotenv";
import { loadConfig } from "../packages/config/src";
import { buildVoidMcpServerConfig } from "../packages/core/src/codex-mcp";
async function main(): Promise<void> {
const workspaceRoot = resolve(process.cwd());
loadDotenv({ path: resolve(workspaceRoot, ".env") });
const config = loadConfig();
const server = buildVoidMcpServerConfig(workspaceRoot);
const entrypoint = server.args[0];
if (!entrypoint || !existsSync(entrypoint)) {
throw new Error(
`Build the project first so the MCP server exists at ${entrypoint ?? "(missing entrypoint)"}.`,
);
}
await runCodex(config.codexExecutable, config.codexExecArgs, ["mcp", "remove", server.name], true);
const addArgs = ["mcp", "add"];
for (const [key, value] of Object.entries(server.env ?? {})) {
addArgs.push("--env", `${key}=${value}`);
}
addArgs.push(server.name, "--", server.command, ...server.args);
await runCodex(config.codexExecutable, config.codexExecArgs, addArgs);
await runCodex(config.codexExecutable, config.codexExecArgs, ["mcp", "get", server.name]);
}
void main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
function runCodex(
executable: string,
executableArgs: string[],
args: string[],
allowFailure = false,
): Promise<void> {
return new Promise((resolvePromise, rejectPromise) => {
const child = spawn(executable, [...executableArgs, ...args], {
cwd: process.cwd(),
env: process.env,
stdio: "inherit",
});
child.on("error", rejectPromise);
child.on("close", (code) => {
if (code === 0 || allowFailure) {
resolvePromise();
return;
}
rejectPromise(new Error(`codex ${args.join(" ")} exited with code ${code ?? "unknown"}`));
});
});
}

View file

@ -0,0 +1,205 @@
import "dotenv/config";
import { readdir, chmod, mkdir, readFile, stat, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { loadConfig } from "@voidbot/config";
const HOOK_MARKER = "# voidbot-source-index-push-hook";
interface ScriptOptions {
repos?: string[];
}
async function main(): Promise<void> {
if (!process.env.DISCORD_OWNER_ID) {
process.env.DISCORD_OWNER_ID = "__source_hook_install__";
}
const config = loadConfig();
if (!config.sourceRepoRoot) {
throw new Error("SOURCE_REPO_ROOT is not configured.");
}
const options = parseArgs(process.argv.slice(2));
const repoNames =
options.repos && options.repos.length > 0
? options.repos
: await resolveRepoNames(config.sourceRepoRoot, config.sourceRepoPatterns);
let installed = 0;
let updated = 0;
let backedUp = 0;
let skipped = 0;
for (const repoName of repoNames) {
const repoPath = join(config.sourceRepoRoot, repoName);
const gitDir = await resolveGitDir(repoPath);
if (!gitDir) {
console.log(`Skipping ${repoName}: no .git directory found.`);
skipped += 1;
continue;
}
const hooksDir = join(gitDir, "hooks");
const hookPath = join(hooksDir, "pre-push");
const backupHookPath = join(hooksDir, "pre-push.voidbot.prev");
await mkdir(hooksDir, { recursive: true });
let existingContent: string | undefined;
try {
existingContent = await readFile(hookPath, "utf8");
} catch {
existingContent = undefined;
}
if (
existingContent &&
!existingContent.includes(HOOK_MARKER) &&
!(await pathExists(backupHookPath))
) {
await writeFile(backupHookPath, existingContent, "utf8");
await chmod(backupHookPath, 0o755);
backedUp += 1;
} else if (
existingContent &&
!existingContent.includes(HOOK_MARKER) &&
(await pathExists(backupHookPath))
) {
console.log(`Skipping ${repoName}: existing pre-push hook already has a Void backup; not clobbering it.`);
skipped += 1;
continue;
}
const hookScript = renderHookScript(process.cwd(), repoName);
await writeFile(hookPath, hookScript, "utf8");
await chmod(hookPath, 0o755);
if (existingContent?.includes(HOOK_MARKER)) {
updated += 1;
console.log(`Updated pre-push hook for ${repoName}.`);
} else {
installed += 1;
console.log(`Installed pre-push hook for ${repoName}.`);
}
}
console.log(
[
`installed=${installed}`,
`updated=${updated}`,
`backedUp=${backedUp}`,
`skipped=${skipped}`,
].join(" "),
);
}
function parseArgs(argv: string[]): ScriptOptions {
const options: ScriptOptions = {};
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
if ((argument === "--repo" || argument === "--repos") && argv[index + 1]) {
options.repos = argv[index + 1]
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
index += 1;
}
}
return options;
}
async function resolveRepoNames(root: string, patterns: string[]): Promise<string[]> {
const entries = await readdir(root, { withFileTypes: true });
return entries
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.filter((name) => patterns.length === 0 || patterns.some((pattern) => matchesPattern(name, pattern)))
.sort((left, right) => left.localeCompare(right));
}
async function resolveGitDir(repoPath: string): Promise<string | undefined> {
const dotGitPath = join(repoPath, ".git");
try {
const dotGitStats = await stat(dotGitPath);
if (dotGitStats.isDirectory()) {
return dotGitPath;
}
if (dotGitStats.isFile()) {
const pointer = await readFile(dotGitPath, "utf8");
const match = pointer.match(/^gitdir:\s*(.+)$/im);
if (match?.[1]) {
return resolve(repoPath, match[1].trim());
}
}
} catch {
return undefined;
}
return undefined;
}
function renderHookScript(voidbotRoot: string, repoName: string): string {
const normalizedRoot = voidbotRoot.replace(/\\/g, "/");
const launcherPath = `${normalizedRoot}/scripts/git-post-push-index.mjs`;
const nodePath = process.execPath.replace(/\\/g, "/");
const quotedNodePath = escapeForDoubleQuotedShell(nodePath);
const quotedLauncherPath = escapeForDoubleQuotedShell(launcherPath);
const quotedRoot = escapeForDoubleQuotedShell(normalizedRoot);
const quotedRepoName = escapeForDoubleQuotedShell(repoName);
return [
"#!/bin/sh",
HOOK_MARKER,
"HOOK_DIR=\"$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)\"",
"PREV_HOOK=\"$HOOK_DIR/pre-push.voidbot.prev\"",
"",
"if [ -x \"$PREV_HOOK\" ]; then",
" \"$PREV_HOOK\" \"$@\"",
" PREV_STATUS=$?",
" if [ \"$PREV_STATUS\" -ne 0 ]; then",
" exit \"$PREV_STATUS\"",
" fi",
"fi",
"",
`\"${quotedNodePath}\" \"${quotedLauncherPath}\" --voidbot-root \"${quotedRoot}\" --repo-name \"${quotedRepoName}\" >/dev/null 2>&1 || true`,
"",
"exit 0",
"",
].join("\n");
}
function escapeForDoubleQuotedShell(value: string): string {
return value.replace(/(["`$\\])/g, "\\$1");
}
function matchesPattern(value: string, pattern: string): boolean {
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
const regex = new RegExp(`^${escaped}$`, "i");
return regex.test(value);
}
async function pathExists(path: string): Promise<boolean> {
try {
await stat(path);
return true;
} catch {
return false;
}
}
void main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View file

@ -0,0 +1,191 @@
import "dotenv/config";
import { access, readdir, readFile } from "node:fs/promises";
import { constants } from "node:fs";
import { join } from "node:path";
import { loadConfig } from "@voidbot/config";
import {
createTextEmbedder,
QdrantVectorStore,
type StoredQdrantChunk,
} from "@voidbot/rag";
interface CliOptions {
wipe: boolean;
}
interface StoredVectorIndex {
chunks?: StoredQdrantChunk[];
}
async function main(): Promise<void> {
if (!process.env.DISCORD_OWNER_ID) {
process.env.DISCORD_OWNER_ID = "__qdrant_migration__";
}
const config = loadConfig();
const options = parseArgs(process.argv.slice(2));
const historyEmbedder = createTextEmbedder({
backend: config.ragEmbeddingBackend,
hashDimensions: config.ragEmbeddingDimensions,
ollamaBaseUrl: config.ragOllamaBaseUrl,
ollamaModel: config.ragOllamaModel,
ollamaTimeoutMs: config.ragOllamaTimeoutMs,
queryInstruction: config.ragQueryInstruction,
});
const sourceEmbedder = createTextEmbedder({
backend: config.ragEmbeddingBackend,
hashDimensions: config.ragEmbeddingDimensions,
ollamaBaseUrl: config.ragOllamaBaseUrl,
ollamaModel: config.ragOllamaModel,
ollamaTimeoutMs: config.ragOllamaTimeoutMs,
queryInstruction: config.ragSourceQueryInstruction,
});
const historyStore = new QdrantVectorStore({
url: config.qdrant.url,
apiKey: config.qdrant.apiKey,
timeoutMs: config.qdrant.timeoutMs,
collectionName: config.qdrant.historyCollection,
corpusKind: "discord_history",
embedder: historyEmbedder,
});
const sourceStore = new QdrantVectorStore({
url: config.qdrant.url,
apiKey: config.qdrant.apiKey,
timeoutMs: config.qdrant.timeoutMs,
collectionName: config.qdrant.sourceCollection,
corpusKind: "repository_source",
embedder: sourceEmbedder,
});
if (options.wipe) {
await historyStore.clear();
await sourceStore.clear();
}
const localVectors = await loadLocalVectors(config.storageRoot, {
historyPath: config.vectorStore.path,
sourceRoot: config.sourceVectorStoreRoot,
});
await historyStore.upsertStoredChunks(localVectors.historyChunks);
await sourceStore.upsertStoredChunks(localVectors.sourceChunks);
console.log(`Qdrant URL: ${config.qdrant.url}`);
console.log(`History collection: ${config.qdrant.historyCollection}`);
console.log(`Source collection: ${config.qdrant.sourceCollection}`);
console.log(`History chunks migrated: ${localVectors.historyChunks.length}`);
console.log(`Source chunks migrated: ${localVectors.sourceChunks.length}`);
console.log(`Source shards discovered locally: ${localVectors.sourceShardFiles}`);
}
function parseArgs(args: string[]): CliOptions {
const options: CliOptions = {
wipe: false,
};
for (const argument of args) {
if (argument === "--wipe") {
options.wipe = true;
continue;
}
throw new Error(`Unknown argument: ${argument}`);
}
return options;
}
async function loadLocalVectors(
storageRoot: string,
options: {
historyPath: string;
sourceRoot: string;
},
): Promise<{
historyChunks: StoredQdrantChunk[];
sourceChunks: StoredQdrantChunk[];
sourceShardFiles: number;
}> {
const historyChunks = await loadChunksFromPath(options.historyPath);
const sourceFiles = await listJsonFiles(options.sourceRoot);
const sourceChunks: StoredQdrantChunk[] = [];
for (const filePath of sourceFiles) {
sourceChunks.push(...(await loadChunksFromPath(filePath)));
}
if (historyChunks.length > 0 || sourceChunks.length > 0) {
return {
historyChunks,
sourceChunks,
sourceShardFiles: sourceFiles.length,
};
}
const legacyPath = join(storageRoot, "vector-store.json");
const legacyChunks = await loadChunksFromPath(legacyPath);
return {
historyChunks: legacyChunks.filter((chunk) => chunk.metadata.corpusKind !== "repository_source"),
sourceChunks: legacyChunks.filter((chunk) => chunk.metadata.corpusKind === "repository_source"),
sourceShardFiles: 0,
};
}
async function loadChunksFromPath(filePath: string): Promise<StoredQdrantChunk[]> {
if (!(await pathExists(filePath))) {
return [];
}
const raw = await readFile(filePath, "utf8");
const store = JSON.parse(raw) as StoredVectorIndex;
return (store.chunks ?? []).filter(isStoredChunk);
}
async function listJsonFiles(directory: string): Promise<string[]> {
if (!(await pathExists(directory))) {
return [];
}
const entries = await readdir(directory, { withFileTypes: true });
return entries
.filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
.map((entry) => join(directory, entry.name))
.sort((left, right) => left.localeCompare(right));
}
async function pathExists(targetPath: string): Promise<boolean> {
try {
await access(targetPath, constants.F_OK);
return true;
} catch {
return false;
}
}
function isStoredChunk(value: unknown): value is StoredQdrantChunk {
if (typeof value !== "object" || value === null) {
return false;
}
const chunk = value as Partial<StoredQdrantChunk>;
return (
typeof chunk.id === "string" &&
typeof chunk.sourceId === "string" &&
(chunk.sourceKind === "discord_message" || chunk.sourceKind === "source_document") &&
typeof chunk.text === "string" &&
Array.isArray(chunk.vector) &&
typeof chunk.indexedAt === "string" &&
typeof chunk.metadata === "object" &&
chunk.metadata !== null
);
}
void main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View file

@ -0,0 +1,107 @@
import "dotenv/config";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { loadConfig } from "@voidbot/config";
interface StoredVectorChunk {
id: string;
sourceId?: string;
sourceMessageId?: string;
sourceKind?: "discord_message" | "source_document";
text: string;
normalizedText: string;
metadata: Record<string, string>;
vector: number[];
indexedAt: string;
}
interface VectorIndexStore {
version: number;
embedderId: string;
dimensions: number;
chunks: StoredVectorChunk[];
}
async function main(): Promise<void> {
if (!process.env.DISCORD_OWNER_ID) {
process.env.DISCORD_OWNER_ID = "__vector_migration__";
}
const config = loadConfig();
const legacyPath = join(config.storageRoot, "vector-store.json");
const raw = await readFile(legacyPath, "utf8");
const legacyStore = JSON.parse(raw) as VectorIndexStore;
const historyChunks: StoredVectorChunk[] = [];
const sourceChunksByRepo = new Map<string, StoredVectorChunk[]>();
for (const chunk of legacyStore.chunks ?? []) {
const sourceId = chunk.sourceId ?? chunk.sourceMessageId;
const sourceKind = chunk.sourceKind ?? (chunk.metadata?.corpusKind === "repository_source" ? "source_document" : "discord_message");
const normalizedChunk: StoredVectorChunk = {
...chunk,
sourceId,
sourceKind,
metadata: {
...chunk.metadata,
sourceId: chunk.metadata?.sourceId ?? sourceId ?? "",
},
};
if (normalizedChunk.metadata.corpusKind === "repository_source") {
const repoName = normalizedChunk.metadata.repoName;
if (!repoName) {
continue;
}
const bucket = sourceChunksByRepo.get(repoName) ?? [];
bucket.push(normalizedChunk);
sourceChunksByRepo.set(repoName, bucket);
continue;
}
historyChunks.push(normalizedChunk);
}
await mkdir(dirname(config.vectorStore.path), { recursive: true });
await writeFile(
config.vectorStore.path,
`${JSON.stringify({
version: 2,
embedderId: legacyStore.embedderId,
dimensions: legacyStore.dimensions,
chunks: historyChunks,
})}\n`,
"utf8",
);
await mkdir(config.sourceVectorStoreRoot, { recursive: true });
for (const [repoName, chunks] of sourceChunksByRepo) {
const shardPath = join(config.sourceVectorStoreRoot, `${encodeURIComponent(repoName)}.json`);
await writeFile(
shardPath,
`${JSON.stringify({
version: 2,
embedderId: legacyStore.embedderId,
dimensions: legacyStore.dimensions,
chunks,
})}\n`,
"utf8",
);
}
console.log(`Legacy mixed store: ${legacyPath}`);
console.log(`History chunks written: ${historyChunks.length}`);
console.log(`Source repos written: ${sourceChunksByRepo.size}`);
console.log(
`Source chunks written: ${[...sourceChunksByRepo.values()].reduce((sum, chunks) => sum + chunks.length, 0)}`,
);
}
void main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View file

@ -0,0 +1,90 @@
import "dotenv/config";
import { loadConfig } from "@voidbot/config";
import {
createTextEmbedder,
FileMessageArchiveRepository,
FileSourceDocumentArchiveRepository,
HistoryIngester,
SourceDocumentIngester,
createVectorStores,
} from "@voidbot/rag";
const REBUILD_CHUNK_BATCH_SIZE = 64;
async function main(): Promise<void> {
if (!process.env.DISCORD_OWNER_ID) {
process.env.DISCORD_OWNER_ID = "__rag_rebuild__";
}
const config = loadConfig();
const archiveRepository = new FileMessageArchiveRepository(config.ragArchivePath);
const sourceArchiveRepository = new FileSourceDocumentArchiveRepository(config.ragSourceArchivePath);
const embedder = createTextEmbedder({
backend: config.ragEmbeddingBackend,
hashDimensions: config.ragEmbeddingDimensions,
ollamaBaseUrl: config.ragOllamaBaseUrl,
ollamaModel: config.ragOllamaModel,
ollamaTimeoutMs: config.ragOllamaTimeoutMs,
queryInstruction: config.ragQueryInstruction,
});
const vectorStores = createVectorStores({
kind: config.vectorStore.kind,
historyPath: config.vectorStore.path,
sourceRoot: config.sourceVectorStoreRoot,
qdrant: config.qdrant,
historyEmbedder: embedder,
sourceEmbedder: embedder,
});
const vectorStore = vectorStores.history;
const sourceVectorStore = vectorStores.source;
const historyIngester = new HistoryIngester();
const sourceIngester = new SourceDocumentIngester();
const activeMessages = await archiveRepository.listAllActive();
const historyChunks = historyIngester.chunkMessages(activeMessages);
const sourceDocuments = await sourceArchiveRepository.listAll();
const sourceChunks = sourceIngester.chunkDocuments(sourceDocuments);
await vectorStore.clear();
await sourceVectorStore.clear();
for (let index = 0; index < historyChunks.length; index += REBUILD_CHUNK_BATCH_SIZE) {
const batch = historyChunks.slice(index, index + REBUILD_CHUNK_BATCH_SIZE);
if (batch.length === 0) {
continue;
}
await vectorStore.upsert(batch);
if ((index / REBUILD_CHUNK_BATCH_SIZE + 1) % 25 === 0 || index + batch.length >= historyChunks.length) {
console.log(`History rebuild progress: ${Math.min(index + batch.length, historyChunks.length)}/${historyChunks.length} chunks`);
}
}
for (let index = 0; index < sourceChunks.length; index += REBUILD_CHUNK_BATCH_SIZE) {
const batch = sourceChunks.slice(index, index + REBUILD_CHUNK_BATCH_SIZE);
if (batch.length === 0) {
continue;
}
await sourceVectorStore.upsert(batch);
if ((index / REBUILD_CHUNK_BATCH_SIZE + 1) % 25 === 0 || index + batch.length >= sourceChunks.length) {
console.log(`Source rebuild progress: ${Math.min(index + batch.length, sourceChunks.length)}/${sourceChunks.length} chunks`);
}
}
console.log(`Embedder: ${embedder.id}`);
console.log(`Archived active messages: ${activeMessages.length}`);
console.log(`Archived source documents: ${sourceDocuments.length}`);
console.log(`History chunks rebuilt: ${historyChunks.length}`);
console.log(`Source chunks rebuilt: ${sourceChunks.length}`);
console.log(`Indexed chunks rebuilt: ${historyChunks.length + sourceChunks.length}`);
}
void main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View file

@ -0,0 +1,38 @@
import { spawn } from "node:child_process";
import { resolve } from "node:path";
import { config as loadDotenv } from "dotenv";
import { loadConfig } from "../packages/config/src";
import { VOID_MCP_SERVER_NAME } from "../packages/core/src/codex-mcp";
void main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
async function main(): Promise<void> {
loadDotenv({ path: resolve(process.cwd(), ".env") });
const config = loadConfig();
await runCodex(config.codexExecutable, config.codexExecArgs, ["mcp", "remove", VOID_MCP_SERVER_NAME]);
}
function runCodex(executable: string, executableArgs: string[], args: string[]): Promise<void> {
return new Promise((resolve, reject) => {
const child = spawn(executable, [...executableArgs, ...args], {
cwd: process.cwd(),
env: process.env,
stdio: "inherit",
});
child.on("error", reject);
child.on("close", (code) => {
if (code === 0) {
resolve();
return;
}
reject(new Error(`codex ${args.join(" ")} exited with code ${code ?? "unknown"}`));
});
});
}

View file

@ -0,0 +1,155 @@
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$dockerDesktopPath = "C:\Program Files\Docker\Docker\Docker Desktop.exe"
$dockerCliDir = "C:\Program Files\Docker\Docker\resources\bin"
$startQdrantScript = Join-Path $PSScriptRoot "start-qdrant.ps1"
$dockerInstallerDownloadDir = Join-Path $env:LOCALAPPDATA "Temp\VoidBot\DockerDesktopInstaller"
$dockerInstallerOverrideUrl = $env:VOIDBOT_DOCKER_DESKTOP_DOWNLOAD_URL
function Test-Administrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]::new($identity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Test-WslInstalled {
try {
& wsl --status *> $null
return $LASTEXITCODE -eq 0
} catch {
return $false
}
}
function Get-DockerInstallerPath {
New-Item -ItemType Directory -Force -Path $dockerInstallerDownloadDir | Out-Null
if ($dockerInstallerOverrideUrl) {
$fileName = [System.IO.Path]::GetFileName(([System.Uri]$dockerInstallerOverrideUrl).AbsolutePath)
if ([string]::IsNullOrWhiteSpace($fileName)) {
throw "VOIDBOT_DOCKER_DESKTOP_DOWNLOAD_URL does not point to a valid installer filename."
}
$overrideInstallerPath = Join-Path $dockerInstallerDownloadDir $fileName
Write-Host "Downloading Docker Desktop installer from override URL..."
& curl.exe -L --fail --silent --show-error --output $overrideInstallerPath $dockerInstallerOverrideUrl
if ($LASTEXITCODE -ne 0 -or -not (Test-Path $overrideInstallerPath)) {
throw "Failed to download Docker Desktop installer from override URL."
}
return $overrideInstallerPath
}
Write-Host "Downloading Docker Desktop installer via winget..."
$downloadOutput = & winget download `
--id Docker.DockerDesktop `
--exact `
--accept-source-agreements `
--accept-package-agreements `
--download-directory $dockerInstallerDownloadDir
if ($downloadOutput) {
$downloadOutput | ForEach-Object { Write-Host $_ }
}
$installer = Get-ChildItem -Path $dockerInstallerDownloadDir -Filter "*.exe" -File -Recurse |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
if ($null -eq $installer) {
throw "winget download completed without leaving a Docker Desktop installer behind."
}
return $installer.FullName
}
if (-not (Test-Administrator)) {
throw "Run this script from an elevated PowerShell window. Docker Desktop and WSL feature installation require administrator privileges."
}
$processor = Get-CimInstance Win32_Processor | Select-Object -First 1
if (-not $processor.VirtualizationFirmwareEnabled) {
throw "Hardware virtualization is disabled in BIOS/UEFI. Enable AMD-V/SVM or Intel VT-x/Virtualization Technology, reboot Windows, then rerun this script."
}
if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
throw "winget is not available on this machine."
}
$restartRequired = $false
if (-not (Test-WslInstalled)) {
Write-Host "Installing WSL..."
try {
& wsl --install --no-distribution
} catch {
Write-Warning "wsl --install --no-distribution failed; retrying with wsl --install."
& wsl --install
}
$restartRequired = $true
}
if (-not (Test-Path $dockerDesktopPath)) {
$dockerInstallerPath = Get-DockerInstallerPath
Write-Host "Installing Docker Desktop from $dockerInstallerPath..."
$installProcess = Start-Process `
-FilePath $dockerInstallerPath `
-ArgumentList @(
"install",
"--accept-license",
"--backend=wsl-2"
) `
-Wait `
-PassThru
if ($installProcess.ExitCode -ne 0) {
throw "Docker Desktop installer exited with code $($installProcess.ExitCode). Check $env:LOCALAPPDATA\Docker\install-log.txt for details."
}
& net.exe localgroup docker-users $env:USERNAME /add *> $null
}
if ($restartRequired) {
Write-Warning "A restart may be required before Docker Desktop and WSL are usable."
Write-Warning "Reboot Windows, open an elevated PowerShell window in this repo, and rerun scripts\\setup-docker-qdrant.ps1."
exit 0
}
if (Test-Path $dockerCliDir) {
$env:Path = "$dockerCliDir;$env:Path"
}
if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {
throw "Docker Desktop appears to be installed, but docker.exe is not on PATH yet. Sign out and back in, or start Docker Desktop once and rerun this script."
}
if (-not (Get-Process -Name "Docker Desktop" -ErrorAction SilentlyContinue)) {
Write-Host "Starting Docker Desktop..."
Start-Process -FilePath $dockerDesktopPath | Out-Null
}
$dockerReady = $false
for ($attempt = 0; $attempt -lt 60; $attempt += 1) {
& docker version *> $null
if ($LASTEXITCODE -eq 0) {
$dockerReady = $true
break
}
Start-Sleep -Seconds 5
}
if (-not $dockerReady) {
throw "Docker Desktop did not become ready in time. Open Docker Desktop, finish any first-run prompts, then rerun this script."
}
& powershell -ExecutionPolicy Bypass -File $startQdrantScript

48
scripts/start-qdrant.ps1 Normal file
View file

@ -0,0 +1,48 @@
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$composeFile = Join-Path $repoRoot "infra\qdrant\docker-compose.yml"
$dockerCliDir = "C:\Program Files\Docker\Docker\resources\bin"
if (Test-Path $dockerCliDir) {
$env:Path = "$dockerCliDir;$env:Path"
}
if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {
throw "Docker CLI is not available on PATH. Install Docker Desktop first, then rerun this script."
}
& docker version *> $null
if ($LASTEXITCODE -ne 0) {
throw "Docker is installed but the daemon is not ready. Start Docker Desktop, finish any first-run prompts, then rerun this script."
}
Write-Host "Starting Qdrant with Docker Compose..."
& docker compose -f $composeFile up -d
if ($LASTEXITCODE -ne 0) {
throw "Docker Compose failed to start Qdrant."
}
$healthy = $false
for ($attempt = 0; $attempt -lt 30; $attempt += 1) {
try {
$response = Invoke-RestMethod -Uri "http://127.0.0.1:6333" -TimeoutSec 5
if ($null -ne $response) {
$healthy = $true
break
}
} catch {
Start-Sleep -Seconds 2
}
}
if (-not $healthy) {
throw "Qdrant container started, but the HTTP API did not become reachable at http://127.0.0.1:6333 in time."
}
Write-Host "Qdrant is up."
Write-Host "API: http://127.0.0.1:6333"
Write-Host "Dashboard: http://127.0.0.1:6333/dashboard"