Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

feat: add bookmark embedding support (#2857)

Mohamed Bassem84ab354de6b1
diff --git a/apps/cli/src/commands/admin.ts b/apps/cli/src/commands/admin.ts
index 9db83dbf..84741bf0 100644
--- a/apps/cli/src/commands/admin.ts
+++ b/apps/cli/src/commands/admin.ts
@@ -139,6 +139,10 @@ bookmarksCmd
"Summarization Status",
debugInfo.summarizationStatus ?? "N/A",
]);
+ basicData.push([
+ "Embedding Status",
+ debugInfo.embeddingStatus ?? "N/A",
+ ]);
if (debugInfo.linkInfo) {
basicData.push(["URL", debugInfo.linkInfo.url]);
@@ -258,6 +262,26 @@ bookmarksCmd
}
});
+bookmarksCmd
+ .command("regenerate-embedding")
+ .description("trigger embedding regeneration for a bookmark")
+ .argument(
+ "<bookmarkId>",
+ "the id of the bookmark to regenerate embeddings for",
+ )
+ .action(async (bookmarkId) => {
+ const api = getAPIClient();
+ try {
+ await api.admin.adminRegenerateBookmarkEmbedding.mutate({ bookmarkId });
+ printStatusMessage(true, "Embedding regeneration queued successfully");
+ } catch (error) {
+ printErrorMessageWithReason(
+ "Failed to queue embedding regeneration",
+ error as object,
+ );
+ }
+ });
+
bookmarksCmd
.command("retag")
.description("trigger AI retagging for a bookmark")
@@ -329,6 +353,12 @@ jobsCmd
"-",
"-",
]);
+ data.push([
+ "Embeddings",
+ stats.embeddingsStats.queued.toString(),
+ stats.embeddingsStats.pending.toString(),
+ stats.embeddingsStats.failed.toString(),
+ ]);
data.push([
"Video Processing",
stats.videoStats.queued.toString(),
@@ -464,6 +494,30 @@ jobsCmd
}
});
+jobsCmd
+ .command("regenerate-embeddings")
+ .description("regenerate embeddings for all bookmarks matching a status")
+ .requiredOption(
+ "--status <status>",
+ "filter by embedding status (failure, pending, all)",
+ )
+ .action(async (opts) => {
+ const api = getAPIClient();
+ const status = opts.status as "failure" | "pending" | "all";
+ try {
+ await api.admin.regenerateAllBookmarkEmbeddings.mutate({ status });
+ printStatusMessage(
+ true,
+ `Embedding regeneration queued for all bookmarks with embedding status: ${status}`,
+ );
+ } catch (error) {
+ printErrorMessageWithReason(
+ "Failed to queue embedding regeneration",
+ error as object,
+ );
+ }
+ });
+
jobsCmd
.command("reprocess-assets")
.description("reprocess all asset bookmarks in fix mode")
diff --git a/apps/web/components/admin/BackgroundJobs.tsx b/apps/web/components/admin/BackgroundJobs.tsx
index 0df34cc4..fada6c2f 100644
--- a/apps/web/components/admin/BackgroundJobs.tsx
+++ b/apps/web/components/admin/BackgroundJobs.tsx
@@ -22,6 +22,7 @@ import {
Globe,
HelpCircle,
Image,
+ Layers,
RefreshCw,
Rss,
Search,
@@ -292,6 +293,25 @@ function useJobActions() {
}),
);
+ const {
+ mutateAsync: regenerateBookmarkEmbeddings,
+ isPending: isRegenerateEmbeddingsPending,
+ } = useMutation(
+ api.admin.regenerateAllBookmarkEmbeddings.mutationOptions({
+ onSuccess: () => {
+ toast({
+ description: "Embedding regeneration enqueued",
+ });
+ },
+ onError: (e) => {
+ toast({
+ variant: "destructive",
+ description: e.message,
+ });
+ },
+ }),
+ );
+
const {
mutateAsync: reprocessAssetsFixMode,
isPending: isReprocessingPending,
@@ -444,6 +464,31 @@ function useJobActions() {
loading: isReindexPending,
},
],
+ embeddingsActions: [
+ {
+ label: t(
+ "admin.background_jobs.actions.regenerate_embeddings_for_pending_bookmarks_only",
+ ),
+ onClick: () => regenerateBookmarkEmbeddings({ status: "pending" }),
+ variant: "secondary" as const,
+ loading: isRegenerateEmbeddingsPending,
+ },
+ {
+ label: t(
+ "admin.background_jobs.actions.regenerate_embeddings_for_failed_bookmarks_only",
+ ),
+ onClick: () => regenerateBookmarkEmbeddings({ status: "failure" }),
+ variant: "secondary" as const,
+ loading: isRegenerateEmbeddingsPending,
+ },
+ {
+ label: t(
+ "admin.background_jobs.actions.regenerate_embeddings_for_all_bookmarks",
+ ),
+ onClick: () => regenerateBookmarkEmbeddings({ status: "all" }),
+ loading: isRegenerateEmbeddingsPending,
+ },
+ ],
assetPreprocessingActions: [
{
label: t("admin.background_jobs.actions.reprocess_assets_fix_mode"),
@@ -528,6 +573,13 @@ export default function BackgroundJobs() {
description: t("admin.background_jobs.jobs.indexing.description"),
actions: actions.indexingActions,
},
+ {
+ title: t("admin.background_jobs.jobs.embeddings.title"),
+ icon: Layers,
+ stats: serverStats.embeddingsStats,
+ description: t("admin.background_jobs.jobs.embeddings.description"),
+ actions: actions.embeddingsActions,
+ },
{
title: t("admin.background_jobs.jobs.asset_preprocessing.title"),
icon: Image,
diff --git a/apps/web/components/admin/BookmarkDebugger.tsx b/apps/web/components/admin/BookmarkDebugger.tsx
index 7e15262f..4d173974 100644
--- a/apps/web/components/admin/BookmarkDebugger.tsx
+++ b/apps/web/components/admin/BookmarkDebugger.tsx
@@ -22,6 +22,7 @@ import {
FileText,
FileType,
Image as ImageIcon,
+ Layers,
Link as LinkIcon,
Loader2,
RefreshCw,
@@ -101,6 +102,21 @@ export default function BookmarkDebugger() {
}),
);
+ const regenerateEmbeddingMutation = useMutation(
+ api.admin.adminRegenerateBookmarkEmbedding.mutationOptions({
+ onSuccess: () => {
+ toast.success(t("admin.admin_tools.action_success"), {
+ description: t("admin.admin_tools.regenerate_embedding_queued"),
+ });
+ },
+ onError: (error) => {
+ toast.error(t("admin.admin_tools.action_failed"), {
+ description: error.message,
+ });
+ },
+ }),
+ );
+
const retagMutation = useMutation(
api.admin.adminRetagBookmark.mutationOptions({
onSuccess: () => {
@@ -143,6 +159,12 @@ export default function BookmarkDebugger() {
}
};
+ const handleRegenerateEmbedding = () => {
+ if (bookmarkId) {
+ regenerateEmbeddingMutation.mutate({ bookmarkId });
+ }
+ };
+
const handleRetag = () => {
if (bookmarkId) {
retagMutation.mutate({ bookmarkId });
@@ -339,6 +361,13 @@ export default function BookmarkDebugger() {
</span>
{getStatusBadge(debugInfo.summarizationStatus)}
</div>
+ <div className="flex items-center justify-between gap-2">
+ <span className="flex items-center gap-1.5 text-muted-foreground">
+ <Layers className="h-3.5 w-3.5" />
+ {t("admin.admin_tools.embedding_status")}
+ </span>
+ {getStatusBadge(debugInfo.embeddingStatus)}
+ </div>
{debugInfo.linkInfo && (
<>
<div className="flex items-center justify-between gap-2">
@@ -622,6 +651,19 @@ export default function BookmarkDebugger() {
)}
{t("admin.admin_tools.reindex")}
</Button>
+ <Button
+ onClick={handleRegenerateEmbedding}
+ disabled={regenerateEmbeddingMutation.isPending}
+ size="sm"
+ variant="outline"
+ >
+ {regenerateEmbeddingMutation.isPending ? (
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ ) : (
+ <Layers className="mr-2 h-4 w-4" />
+ )}
+ {t("admin.admin_tools.regenerate_embedding")}
+ </Button>
<Button
onClick={handleRetag}
disabled={retagMutation.isPending}
diff --git a/apps/web/components/admin/ServiceConnections.tsx b/apps/web/components/admin/ServiceConnections.tsx
index 5cdab46a..574ee789 100644
--- a/apps/web/components/admin/ServiceConnections.tsx
+++ b/apps/web/components/admin/ServiceConnections.tsx
@@ -45,7 +45,7 @@ function ConnectionStatus({
return (
<div
- className={`rounded-lg border ${borderColor} bg-background p-5 shadow-sm transition-all sm:w-1/3`}
+ className={`rounded-lg border ${borderColor} bg-background p-5 shadow-sm transition-all`}
>
<div className="mb-3 flex items-center justify-between">
<div>
@@ -86,11 +86,11 @@ function ConnectionsSkeleton() {
return (
<AdminCard>
<div className="mb-4 h-7 w-40 animate-pulse rounded bg-gray-200 dark:bg-gray-700"></div>
- <div className="flex flex-col gap-4 sm:flex-row">
- {[1, 2, 3].map((i) => (
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
+ {[1, 2, 3, 4].map((i) => (
<div
key={i}
- className="rounded-lg border border-gray-200 bg-background p-5 shadow-sm dark:border-gray-700 sm:w-1/3"
+ className="rounded-lg border border-gray-200 bg-background p-5 shadow-sm dark:border-gray-700"
>
<div className="mb-3 flex items-center justify-between">
<div className="h-5 w-28 animate-pulse rounded bg-gray-200 dark:bg-gray-700"></div>
@@ -127,7 +127,7 @@ export default function ServiceConnections() {
<p className="mb-4 text-sm text-muted-foreground">
{t("admin.service_connections.description")}
</p>
- <div className="flex flex-col gap-4 sm:flex-row">
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
<ConnectionStatus
label={t("admin.service_connections.search_engine")}
configured={connections.searchEngine.configured}
@@ -149,6 +149,13 @@ export default function ServiceConnections() {
pluginName={connections.queue.pluginName}
error={connections.queue.error}
/>
+ <ConnectionStatus
+ label={t("admin.service_connections.vector_store")}
+ configured={connections.vectorStore.configured}
+ connected={connections.vectorStore.connected}
+ pluginName={connections.vectorStore.pluginName}
+ error={connections.vectorStore.error}
+ />
</div>
</AdminCard>
);
diff --git a/apps/web/lib/i18n/locales/en/translation.json b/apps/web/lib/i18n/locales/en/translation.json
index 8a7a605a..62ff23d7 100644
--- a/apps/web/lib/i18n/locales/en/translation.json
+++ b/apps/web/lib/i18n/locales/en/translation.json
@@ -638,6 +638,7 @@
"search_engine": "Search Engine",
"browser": "Browser",
"queue_system": "Queue System",
+ "vector_store": "Vector Store",
"status": {
"not_configured": "Not Configured",
"connected": "Connected",
@@ -658,6 +659,10 @@
"title": "Indexing Jobs",
"description": "Search index updates"
},
+ "embeddings": {
+ "title": "Embedding Jobs",
+ "description": "Bookmark vector embedding generation"
+ },
"asset_preprocessing": {
"title": "Asset Preprocessing Jobs",
"description": "Image and document preprocessing (screenshots, text extraction, etc.)"
@@ -710,6 +715,9 @@
"regenerate_ai_summaries_for_failed_bookmarks_only": "Regenerate AI Summaries for Failed Bookmarks Only",
"regenerate_ai_summaries_for_all_bookmarks": "Regenerate AI Summaries for All Bookmarks",
"reindex_all_bookmarks": "Reindex All Bookmarks",
+ "regenerate_embeddings_for_pending_bookmarks_only": "Regenerate Embeddings for Pending Bookmarks Only",
+ "regenerate_embeddings_for_failed_bookmarks_only": "Regenerate Embeddings for Failed Bookmarks Only",
+ "regenerate_embeddings_for_all_bookmarks": "Regenerate Embeddings for All Bookmarks",
"clean_assets": "Clean Dangling Assets & Re-sync Metadata",
"migrate_large_link_html_content": "Move Large Inline HTML Content to Assets",
"reprocess_assets_fix_mode": "Reprocess Unprocessed Assets"
@@ -747,11 +755,13 @@
"owner_user_id": "Owner User ID",
"tagging_status": "Tagging Status",
"summarization_status": "Summarization Status",
+ "embedding_status": "Embedding Status",
"crawl_status": "Crawl Status",
"crawl_status_code": "HTTP Status Code",
"crawled_at": "Crawled At",
"recrawl": "Re-crawl",
"reindex": "Re-index",
+ "regenerate_embedding": "Regenerate Embedding",
"retag": "Re-tag",
"resummarize": "Re-summarize",
"bookmark_not_found": "Bookmark not found",
@@ -759,6 +769,7 @@
"action_failed": "Action failed",
"recrawl_queued": "Re-crawl job has been queued",
"reindex_queued": "Re-index job has been queued",
+ "regenerate_embedding_queued": "Embedding regeneration job has been queued",
"retag_queued": "Re-tag job has been queued",
"resummarize_queued": "Re-summarize job has been queued",
"view": "View",
diff --git a/apps/web/lib/i18n/locales/en_US/translation.json b/apps/web/lib/i18n/locales/en_US/translation.json
index 5a3f5ed6..7cf3998c 100644
--- a/apps/web/lib/i18n/locales/en_US/translation.json
+++ b/apps/web/lib/i18n/locales/en_US/translation.json
@@ -750,6 +750,10 @@
"title": "Indexing Jobs",
"description": "Search index updates"
},
+ "embeddings": {
+ "title": "Embedding Jobs",
+ "description": "Bookmark vector embedding generation"
+ },
"asset_preprocessing": {
"title": "Asset Preprocessing Jobs",
"description": "Image and document preprocessing (screenshots, text extraction, etc.)"
@@ -802,6 +806,9 @@
"regenerate_ai_summaries_for_failed_bookmarks_only": "Regenerate AI Summaries for Failed Bookmarks Only",
"regenerate_ai_summaries_for_all_bookmarks": "Regenerate AI Summaries for All Bookmarks",
"reindex_all_bookmarks": "Reindex All Bookmarks",
+ "regenerate_embeddings_for_pending_bookmarks_only": "Regenerate Embeddings for Pending Bookmarks Only",
+ "regenerate_embeddings_for_failed_bookmarks_only": "Regenerate Embeddings for Failed Bookmarks Only",
+ "regenerate_embeddings_for_all_bookmarks": "Regenerate Embeddings for All Bookmarks",
"clean_assets": "Clean Dangling Assets & Re-sync Metadata",
"migrate_large_link_html_content": "Move Large Inline HTML Content to Assets",
"reprocess_assets_fix_mode": "Reprocess Unprocessed Assets",
@@ -866,11 +873,13 @@
"owner_user_id": "Owner User ID",
"tagging_status": "Tagging Status",
"summarization_status": "Summarization Status",
+ "embedding_status": "Embedding Status",
"crawl_status": "Crawl Status",
"crawl_status_code": "HTTP Status Code",
"crawled_at": "Crawled At",
"recrawl": "Re-crawl",
"reindex": "Re-index",
+ "regenerate_embedding": "Regenerate Embedding",
"retag": "Re-tag",
"resummarize": "Re-summarize",
"bookmark_not_found": "Bookmark not found",
@@ -878,6 +887,7 @@
"action_failed": "Action failed",
"recrawl_queued": "Re-crawl job has been queued",
"reindex_queued": "Re-index job has been queued",
+ "regenerate_embedding_queued": "Embedding regeneration job has been queued",
"retag_queued": "Re-tag job has been queued",
"resummarize_queued": "Re-summarize job has been queued",
"view": "View",
diff --git a/apps/workers/index.ts b/apps/workers/index.ts
index 7029d43b..5282bfd2 100644
--- a/apps/workers/index.ts
+++ b/apps/workers/index.ts
@@ -6,6 +6,7 @@ import {
AdminMaintenanceQueue,
AssetPreprocessingQueue,
BackupQueue,
+ EmbeddingsQueue,
FeedQueue,
initEventLogger,
initTracing,
@@ -30,6 +31,7 @@ import { AdminMaintenanceWorker } from "./workers/adminMaintenanceWorker";
import { AssetPreprocessingWorker } from "./workers/assetPreprocessingWorker";
import { BackupSchedulingWorker, BackupWorker } from "./workers/backupWorker";
import { CrawlerWorker } from "./workers/crawlerWorker";
+import { EmbeddingsWorker } from "./workers/embeddingsWorker";
import { FeedRefreshingWorker, FeedWorker } from "./workers/feedWorker";
import { ImportWorker } from "./workers/importWorker";
import { OpenAiWorker } from "./workers/inference/inferenceWorker";
@@ -47,6 +49,10 @@ const workerBuilders = {
await LowPriorityCrawlerQueue.ensureInit();
return CrawlerWorker.build(LowPriorityCrawlerQueue);
},
+ embeddings: async () => {
+ await EmbeddingsQueue.ensureInit();
+ return EmbeddingsWorker.build();
+ },
inference: async () => {
await OpenAIQueue.ensureInit();
return OpenAiWorker.build();
diff --git a/apps/workers/workers/assetPreprocessingWorker.ts b/apps/workers/workers/assetPreprocessingWorker.ts
index 312257b3..5b36f23c 100644
--- a/apps/workers/workers/assetPreprocessingWorker.ts
+++ b/apps/workers/workers/assetPreprocessingWorker.ts
@@ -17,6 +17,7 @@ import {
import {
addLogFields,
AssetPreprocessingQueue,
+ EmbeddingsQueue,
OpenAIQueue,
QuotaService,
StorageQuotaError,
@@ -89,6 +90,17 @@ export class AssetPreprocessingWorker {
eq(bookmarks.summarizationStatus, "pending"),
),
);
+ await tx
+ .update(bookmarks)
+ .set({
+ embeddingStatus: null,
+ })
+ .where(
+ and(
+ eq(bookmarks.id, bookmarkId),
+ eq(bookmarks.embeddingStatus, "pending"),
+ ),
+ );
});
}
return Promise.resolve();
@@ -461,13 +473,23 @@ async function run(req: DequeuedJob<AssetPreprocessingRequest>) {
groupId: bookmark.userId,
};
if (!isFixMode || anythingChanged) {
- await OpenAIQueue.enqueue(
- {
- bookmarkId,
- type: "tag",
- },
- enqueueOpts,
- );
+ if (serverConfig.embedding.enableAutoIndexing) {
+ await EmbeddingsQueue.enqueue(
+ {
+ bookmarkId,
+ type: "index",
+ },
+ enqueueOpts,
+ );
+ } else {
+ await OpenAIQueue.enqueue(
+ {
+ bookmarkId,
+ type: "tag",
+ },
+ enqueueOpts,
+ );
+ }
await OpenAIQueue.enqueue(
{
bookmarkId,
diff --git a/apps/workers/workers/crawlerWorker.ts b/apps/workers/workers/crawlerWorker.ts
index 87768507..0a0cb5d9 100644
--- a/apps/workers/workers/crawlerWorker.ts
+++ b/apps/workers/workers/crawlerWorker.ts
@@ -51,6 +51,7 @@ import {
addLogFields,
AssetPreprocessingQueue,
getTracer,
+ EmbeddingsQueue,
OpenAIQueue,
QuotaService,
setSpanAttributes,
@@ -435,6 +436,17 @@ export class CrawlerWorker {
eq(bookmarks.summarizationStatus, "pending"),
),
);
+ await tx
+ .update(bookmarks)
+ .set({
+ embeddingStatus: null,
+ })
+ .where(
+ and(
+ eq(bookmarks.id, bookmarkId),
+ eq(bookmarks.embeddingStatus, "pending"),
+ ),
+ );
});
}
},
@@ -2297,13 +2309,23 @@ async function runCrawler(
// Enqueue openai job (if not set, assume it's true for backward compatibility)
if (job.data.runInference !== false) {
- await OpenAIQueue.enqueue(
- {
- bookmarkId,
- type: "tag",
- },
- enqueueOpts,
- );
+ if (serverConfig.embedding.enableAutoIndexing) {
+ await EmbeddingsQueue.enqueue(
+ {
+ bookmarkId,
+ type: "index",
+ },
+ enqueueOpts,
+ );
+ } else {
+ await OpenAIQueue.enqueue(
+ {
+ bookmarkId,
+ type: "tag",
+ },
+ enqueueOpts,
+ );
+ }
await OpenAIQueue.enqueue(
{
bookmarkId,
diff --git a/apps/workers/workers/embeddingsWorker.ts b/apps/workers/workers/embeddingsWorker.ts
new file mode 100644
index 00000000..9a5bac40
--- /dev/null
+++ b/apps/workers/workers/embeddingsWorker.ts
@@ -0,0 +1,432 @@
+import { eq } from "drizzle-orm";
+import { workerStatsCounter } from "metrics";
+import { withWorkerEventLog, withWorkerTracing } from "workerTracing";
+
+import type { ZEmbeddingsRequest } from "@karakeep/shared-server";
+import { db } from "@karakeep/db";
+import { bookmarks } from "@karakeep/db/schema";
+import {
+ addLogFields,
+ EmbeddingsQueue,
+ OpenAIQueue,
+ zEmbeddingsRequestSchema,
+} from "@karakeep/shared-server";
+import serverConfig from "@karakeep/shared/config";
+import { InferenceClientFactory } from "@karakeep/shared/inference";
+import logger from "@karakeep/shared/logger";
+import {
+ DequeuedJob,
+ DequeuedJobError,
+ EnqueueOptions,
+ getQueueClient,
+} from "@karakeep/shared/queueing";
+import {
+ BookmarkVectorDocument,
+ getVectorStoreClient,
+} from "@karakeep/shared/vectorStore";
+import { Bookmark } from "@karakeep/trpc/models/bookmarks";
+
+const MAX_EMBEDDING_CONTENT_EXCERPT_LENGTH = 3000;
+const MAX_EMBEDDING_METADATA_LENGTH = 800;
+
+export class EmbeddingsWorker {
+ static async build() {
+ logger.info("Starting embeddings worker ...");
+ const worker = (await getQueueClient()).createRunner<ZEmbeddingsRequest>(
+ EmbeddingsQueue,
+ {
+ run: withWorkerTracing(
+ "embeddingsWorker.run",
+ withWorkerEventLog("embeddingsWorker.run", runEmbeddings),
+ ),
+ onComplete: async (job) => {
+ workerStatsCounter.labels("embeddings", "completed").inc();
+ const jobId = job.id;
+ logger.info(`[embeddings][${jobId}] Completed successfully`);
+ await attemptMarkEmbeddingStatus(job.data, "success");
+ if (shouldRunTaggingOnComplete(job.data)) {
+ await enqueueTaggingAfterEmbeddings(job);
+ }
+ },
+ onError: async (job) => {
+ workerStatsCounter.labels("embeddings", "failed").inc();
+ const jobId = job.id;
+ logger.error(
+ `[embeddings][${jobId}] embeddings job failed: ${job.error}\n${job.error.stack}`,
+ );
+ if (job.numRetriesLeft == 0) {
+ workerStatsCounter.labels("embeddings", "failed_permanent").inc();
+ await attemptMarkEmbeddingStatus(job.data, "failure");
+ if (job.data && shouldRunTaggingOnComplete(job.data)) {
+ await enqueueTaggingAfterEmbeddings(job);
+ }
+ }
+ },
+ },
+ {
+ concurrency: serverConfig.embedding.numWorkers,
+ pollIntervalMs: 1000,
+ timeoutSecs: serverConfig.embedding.jobTimeoutSec,
+ validator: zEmbeddingsRequestSchema,
+ },
+ );
+
+ return worker;
+ }
+}
+
+async function attemptMarkEmbeddingStatus(
+ jobData: object | undefined,
+ status: "success" | "failure",
+) {
+ if (!jobData) {
+ return;
+ }
+ try {
+ const request = zEmbeddingsRequestSchema.parse(jobData);
+ if (request.type !== "index") {
+ return;
+ }
+ await db
+ .update(bookmarks)
+ .set({ embeddingStatus: status })
+ .where(eq(bookmarks.id, request.bookmarkId));
+ } catch (e) {
+ logger.error(
+ `Something went wrong when marking the embedding status: ${e}`,
+ );
+ }
+}
+
+function shouldRunTaggingOnComplete(request: ZEmbeddingsRequest) {
+ return request.type !== "delete" && request.runTaggingOnComplete !== false;
+}
+
+async function enqueueTaggingAfterEmbeddings(
+ job: DequeuedJob<ZEmbeddingsRequest> | DequeuedJobError<ZEmbeddingsRequest>,
+) {
+ const bookmarkId = job.data?.bookmarkId;
+ if (!bookmarkId) {
+ return;
+ }
+ const bookmark = await db.query.bookmarks.findFirst({
+ where: eq(bookmarks.id, bookmarkId),
+ columns: {
+ userId: true,
+ },
+ });
+ if (!bookmark) {
+ logger.warn(
+ `[embeddings][${job.id}] Bookmark ${bookmarkId} not found, skipping tag enqueue`,
+ );
+ return;
+ }
+
+ const enqueueOpts: EnqueueOptions = {
+ priority: job.priority,
+ groupId: bookmark.userId,
+ };
+ await OpenAIQueue.enqueue(
+ {
+ bookmarkId,
+ type: "tag",
+ },
+ enqueueOpts,
+ );
+}
+
+async function fetchBookmark(bookmarkId: string) {
+ return await db.query.bookmarks.findFirst({
+ where: eq(bookmarks.id, bookmarkId),
+ with: {
+ link: true,
+ text: true,
+ asset: true,
+ tagsOnBookmarks: {
+ with: {
+ tag: true,
+ },
+ },
+ },
+ });
+}
+
+function normalizeEmbeddingText(text: string | null | undefined) {
+ const normalized = text?.replace(/\s+/g, " ").trim();
+ return normalized && normalized.length > 0 ? normalized : null;
+}
+
+function truncateText(text: string, maxLength: number) {
+ if (text.length <= maxLength) {
+ return text;
+ }
+ return `${text.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;
+}
+
+function hostnameFromUrl(url: string | null | undefined) {
+ if (!url) {
+ return null;
+ }
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return null;
+ }
+}
+
+function urlForEmbedding(url: string | null | undefined) {
+ if (!url) {
+ return null;
+ }
+ try {
+ const parsed = new URL(url);
+ parsed.search = "";
+ parsed.hash = "";
+ return parsed.toString();
+ } catch {
+ return normalizeEmbeddingText(url);
+ }
+}
+
+function metadataForEmbedding(metadata: string | null | undefined) {
+ const normalized = normalizeEmbeddingText(metadata);
+ if (!normalized) {
+ return null;
+ }
+
+ try {
+ const parsed = JSON.parse(normalized) as unknown;
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
+ const fields: string[] = [];
+ for (const [key, value] of Object.entries(parsed)) {
+ if (
+ typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean"
+ ) {
+ fields.push(`${key}: ${value}`);
+ }
+ }
+ if (fields.length > 0) {
+ return truncateText(fields.join("; "), MAX_EMBEDDING_METADATA_LENGTH);
+ }
+ }
+ } catch {
+ // Fall back to the raw metadata string.
+ }
+
+ return truncateText(normalized, MAX_EMBEDDING_METADATA_LENGTH);
+}
+
+function appendProfileField(parts: string[], label: string, value: unknown) {
+ if (value instanceof Date) {
+ parts.push(`${label}: ${value.toISOString().slice(0, 10)}`);
+ return;
+ }
+ if (typeof value !== "string") {
+ return;
+ }
+ const normalized = normalizeEmbeddingText(value);
+ if (normalized) {
+ parts.push(`${label}: ${normalized}`);
+ }
+}
+
+function contentBudget(maxTextLength: number) {
+ return Math.max(
+ 500,
+ Math.min(
+ MAX_EMBEDDING_CONTENT_EXCERPT_LENGTH,
+ Math.floor(maxTextLength * 0.4),
+ ),
+ );
+}
+
+async function buildEmbeddingText(
+ bookmark: NonNullable<Awaited<ReturnType<typeof fetchBookmark>>>,
+): Promise<string | null> {
+ const parts: string[] = [];
+
+ appendProfileField(parts, "Title", bookmark.title);
+ parts.push(`Type: ${bookmark.type}`);
+
+ const tags = bookmark.tagsOnBookmarks.map((t) => t.tag.name).sort();
+ if (tags.length > 0) {
+ parts.push(`Tags: ${tags.join(", ")}`);
+ }
+
+ appendProfileField(parts, "Summary", bookmark.summary);
+ appendProfileField(parts, "Note", bookmark.note);
+
+ let rawContent: string | null = null;
+
+ if (bookmark.link) {
+ appendProfileField(parts, "Domain", hostnameFromUrl(bookmark.link.url));
+ appendProfileField(parts, "URL", urlForEmbedding(bookmark.link.url));
+ if (
+ bookmark.link.title &&
+ normalizeEmbeddingText(bookmark.link.title) !==
+ normalizeEmbeddingText(bookmark.title)
+ ) {
+ appendProfileField(parts, "Page title", bookmark.link.title);
+ }
+ appendProfileField(parts, "Description", bookmark.link.description);
+ appendProfileField(parts, "Author", bookmark.link.author);
+ appendProfileField(parts, "Publisher", bookmark.link.publisher);
+ appendProfileField(parts, "Published", bookmark.link.datePublished);
+ rawContent = await Bookmark.getBookmarkPlainTextContent(
+ bookmark.link,
+ bookmark.userId,
+ );
+ } else if (bookmark.text) {
+ appendProfileField(
+ parts,
+ "Source URL",
+ urlForEmbedding(bookmark.text.sourceUrl),
+ );
+ appendProfileField(
+ parts,
+ "Source domain",
+ hostnameFromUrl(bookmark.text.sourceUrl),
+ );
+ rawContent = bookmark.text.text;
+ } else if (bookmark.asset) {
+ appendProfileField(
+ parts,
+ "Source URL",
+ urlForEmbedding(bookmark.asset.sourceUrl),
+ );
+ appendProfileField(
+ parts,
+ "Source domain",
+ hostnameFromUrl(bookmark.asset.sourceUrl),
+ );
+ appendProfileField(parts, "File name", bookmark.asset.fileName);
+ appendProfileField(parts, "Asset type", bookmark.asset.assetType);
+ appendProfileField(
+ parts,
+ "Metadata",
+ metadataForEmbedding(bookmark.asset.metadata),
+ );
+ rawContent = bookmark.asset.content;
+ }
+
+ const normalizedContent = normalizeEmbeddingText(rawContent);
+ if (normalizedContent) {
+ parts.push(
+ `Content excerpt: ${truncateText(
+ normalizedContent,
+ contentBudget(serverConfig.embedding.contextLength),
+ )}`,
+ );
+ }
+
+ if (parts.length === 0) {
+ return null;
+ }
+
+ const fullText = parts.join("\n\n");
+ const maxTextLength = serverConfig.embedding.contextLength;
+ return fullText.length > maxTextLength
+ ? fullText.substring(0, maxTextLength)
+ : fullText;
+}
+
+async function runEmbeddings(job: DequeuedJob<ZEmbeddingsRequest>) {
+ const jobId = job.id;
+
+ const { bookmarkId, force, type: opType } = job.data;
+ addLogFields<"embeddingsWorker.run">({
+ "bookmark.id": bookmarkId,
+ });
+
+ if (
+ opType === "index" &&
+ !serverConfig.embedding.enableAutoIndexing &&
+ !force
+ ) {
+ logger.debug(
+ `[embeddings][${jobId}] Bookmark embedding indexing is disabled, skipping embedding generation`,
+ );
+ return;
+ }
+
+ const vectorStoreClient = await getVectorStoreClient();
+ if (!vectorStoreClient) {
+ logger.debug(
+ `[embeddings][${jobId}] Vector store is not configured, skipping embedding ${opType}`,
+ );
+ return;
+ }
+
+ if (opType === "delete") {
+ await vectorStoreClient.deleteVectors([bookmarkId]);
+ logger.info(`[embeddings][${jobId}] Deleted embedding for ${bookmarkId}`);
+ return;
+ }
+
+ const bookmark = await fetchBookmark(bookmarkId);
+ if (!bookmark) {
+ logger.warn(
+ `[embeddings][${jobId}] Bookmark ${bookmarkId} not found, it might have been deleted already. Skipping ...`,
+ );
+ return;
+ }
+
+ addLogFields<"embeddingsWorker.run">({
+ "user.id": bookmark.userId,
+ });
+
+ const inferenceClient = InferenceClientFactory.build();
+ if (!inferenceClient) {
+ logger.debug(
+ `[embeddings][${jobId}] No inference client configured, skipping embedding generation`,
+ );
+ return;
+ }
+
+ const embeddingText = await buildEmbeddingText(bookmark);
+ if (!embeddingText) {
+ logger.info(
+ `[embeddings][${jobId}] No content found for bookmark ${bookmarkId}, skipping embedding generation`,
+ );
+ return;
+ }
+
+ addLogFields<"embeddingsWorker.run">({
+ "embedding.text_size": embeddingText.length,
+ });
+ logger.debug(
+ `[embeddings][${jobId}] Embedding text length: ${embeddingText.length} characters`,
+ );
+
+ const embeddingResponse = await inferenceClient.generateEmbeddingFromText([
+ embeddingText,
+ ]);
+
+ if (
+ !embeddingResponse.embeddings ||
+ embeddingResponse.embeddings.length === 0
+ ) {
+ throw new Error(
+ `[embeddings][${jobId}] No embeddings returned from inference client`,
+ );
+ }
+
+ const embedding = embeddingResponse.embeddings[0]!;
+ addLogFields<"embeddingsWorker.run">({
+ "embedding.prompt_tokens": embeddingResponse.promptTokens,
+ "embedding.total_tokens": embeddingResponse.totalTokens,
+ });
+ const document: BookmarkVectorDocument = {
+ id: bookmark.id,
+ userId: bookmark.userId,
+ vector: embedding,
+ };
+
+ await vectorStoreClient.addVectors([document]);
+
+ logger.info(
+ `[embeddings][${jobId}] Indexed embedding for bookmark ${bookmarkId} with ${embedding.length} dimensions using ${embeddingResponse.totalTokens ?? "unknown"} tokens`,
+ );
+}
diff --git a/docs/docs/03-configuration/01-environment-variables.md b/docs/docs/03-configuration/01-environment-variables.md
index b79aef99..bb1cfa7c 100644
--- a/docs/docs/03-configuration/01-environment-variables.md
+++ b/docs/docs/03-configuration/01-environment-variables.md
@@ -102,7 +102,12 @@ Either `OPENAI_API_KEY` or `OLLAMA_BASE_URL` need to be set for automatic taggin
| OLLAMA_KEEP_ALIVE | No | Not set | Controls how long the model will stay loaded into memory following the request (examples: "5m" for 5 minutes, "-1m" to keep the model loaded indefinitely, "0" to unload the model instantly after processing is complete). |
| INFERENCE_TEXT_MODEL | No | gpt-4.1-mini | The model to use for text inference. You'll need to change this to some other model if you're using ollama. |
| INFERENCE_IMAGE_MODEL | No | gpt-4o-mini | The model to use for image inference. You'll need to change this to some other model if you're using ollama and that model needs to support vision APIs (e.g. llava). |
+| EMBEDDING_ENABLE_AUTO_INDEXING | No | false | Whether bookmark embedding generation and vector indexing are enabled. When disabled, bookmark tagging still runs directly without waiting for embeddings. |
| EMBEDDING_TEXT_MODEL | No | text-embedding-3-small | The model to be used for generating embeddings for the text. |
+| EMBEDDING_CONTEXT_LENGTH | No | 8000 | The max number of characters that will be passed to the embedding model. If the bookmark content is larger than this size, it will be truncated before embedding generation. |
+| EMBEDDING_DIMENSIONS | No | 1536 | The embedding vector dimensions expected by the vector store. This must match the embedding model or provider configuration. |
+| EMBEDDING_NUM_WORKERS | No | 1 | Number of concurrent workers for embedding generation and vector indexing tasks. Increase this if you have multiple embedding requests and want to process them in parallel. |
+| EMBEDDING_JOB_TIMEOUT_SEC | No | 60 | How long to wait for an embedding generation and vector indexing job to finish before timing out. Increase this if your embedding provider or vector store is slow. |
| INFERENCE_CONTEXT_LENGTH | No | 2048 | The max number of tokens that we'll pass to the inference model. If your content is larger than this size, it'll be truncated to fit. The larger this value, the more of the content will be used in tag inference, but the more expensive the inference will be (money-wise on openAI and resource-wise on ollama). Check the model you're using for its max supported content size. |
| INFERENCE_MAX_OUTPUT_TOKENS | No | 2048 | The maximum number of tokens that the inference model is allowed to generate in its response. This controls the length of AI-generated content like tags and summaries. Increase this if you need longer responses, but be aware that higher values will increase costs (for OpenAI) and processing time. |
| INFERENCE_USE_MAX_COMPLETION_TOKENS | No | false | \[OpenAI Only\] Whether to use the newer `max_completion_tokens` parameter instead of the deprecated `max_tokens` parameter. Set to `true` if using GPT-5 or o-series models which require this. Will become the default in a future release. |
diff --git a/packages/db/drizzle/0085_add_embedding_status.sql b/packages/db/drizzle/0085_add_embedding_status.sql
new file mode 100644
index 00000000..633e6d97
--- /dev/null
+++ b/packages/db/drizzle/0085_add_embedding_status.sql
@@ -0,0 +1 @@
+ALTER TABLE `bookmarks` ADD `embeddingStatus` text DEFAULT 'pending';
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0085_snapshot.json b/packages/db/drizzle/meta/0085_snapshot.json
new file mode 100644
index 00000000..1ec63a1a
--- /dev/null
+++ b/packages/db/drizzle/meta/0085_snapshot.json
@@ -0,0 +1,3356 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "240f4be9-65f7-4176-9376-fd2daa9b443c",
+ "prevId": "db6cb54e-54fe-44b2-a1a9-954bb9795978",
+ "tables": {
+ "account": {
+ "name": "account",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "providerAccountId": {
+ "name": "providerAccountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_state": {
+ "name": "session_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_userId_user_id_fk": {
+ "name": "account_userId_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "account_provider_providerAccountId_pk": {
+ "columns": [
+ "provider",
+ "providerAccountId"
+ ],
+ "name": "account_provider_providerAccountId_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "apiKey": {
+ "name": "apiKey",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lastUsedAt": {
+ "name": "lastUsedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "keyId": {
+ "name": "keyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyHash": {
+ "name": "keyHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "apiKey_keyId_unique": {
+ "name": "apiKey_keyId_unique",
+ "columns": [
+ "keyId"
+ ],
+ "isUnique": true
+ },
+ "apiKey_name_userId_unique": {
+ "name": "apiKey_name_userId_unique",
+ "columns": [
+ "name",
+ "userId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "apiKey_userId_user_id_fk": {
+ "name": "apiKey_userId_user_id_fk",
+ "tableFrom": "apiKey",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "assets": {
+ "name": "assets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "assetType": {
+ "name": "assetType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "contentType": {
+ "name": "contentType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fileName": {
+ "name": "fileName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "assets_bookmarkId_idx": {
+ "name": "assets_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "assets_assetType_idx": {
+ "name": "assets_assetType_idx",
+ "columns": [
+ "assetType"
+ ],
+ "isUnique": false
+ },
+ "assets_userId_idx": {
+ "name": "assets_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "assets_bookmarkId_bookmarks_id_fk": {
+ "name": "assets_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "assets",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "assets_userId_user_id_fk": {
+ "name": "assets_userId_user_id_fk",
+ "tableFrom": "assets",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "backups": {
+ "name": "backups",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "assetId": {
+ "name": "assetId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bookmarkCount": {
+ "name": "bookmarkCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "errorMessage": {
+ "name": "errorMessage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "backups_userId_idx": {
+ "name": "backups_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "backups_createdAt_idx": {
+ "name": "backups_createdAt_idx",
+ "columns": [
+ "createdAt"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "backups_userId_user_id_fk": {
+ "name": "backups_userId_user_id_fk",
+ "tableFrom": "backups",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "backups_assetId_assets_id_fk": {
+ "name": "backups_assetId_assets_id_fk",
+ "tableFrom": "backups",
+ "tableTo": "assets",
+ "columnsFrom": [
+ "assetId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarkAssets": {
+ "name": "bookmarkAssets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "assetType": {
+ "name": "assetType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "assetId": {
+ "name": "assetId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fileName": {
+ "name": "fileName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sourceUrl": {
+ "name": "sourceUrl",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "bookmarkAssets_id_bookmarks_id_fk": {
+ "name": "bookmarkAssets_id_bookmarks_id_fk",
+ "tableFrom": "bookmarkAssets",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarkLinks": {
+ "name": "bookmarkLinks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author": {
+ "name": "author",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "publisher": {
+ "name": "publisher",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "datePublished": {
+ "name": "datePublished",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dateModified": {
+ "name": "dateModified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "imageUrl": {
+ "name": "imageUrl",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "favicon": {
+ "name": "favicon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "htmlContent": {
+ "name": "htmlContent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "contentAssetId": {
+ "name": "contentAssetId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "crawledAt": {
+ "name": "crawledAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "crawlStatus": {
+ "name": "crawlStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "crawlStatusCode": {
+ "name": "crawlStatusCode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 200
+ }
+ },
+ "indexes": {
+ "bookmarkLinks_url_idx": {
+ "name": "bookmarkLinks_url_idx",
+ "columns": [
+ "url"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bookmarkLinks_id_bookmarks_id_fk": {
+ "name": "bookmarkLinks_id_bookmarks_id_fk",
+ "tableFrom": "bookmarkLinks",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarkLists": {
+ "name": "bookmarkLists",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "query": {
+ "name": "query",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rssToken": {
+ "name": "rssToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "public": {
+ "name": "public",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {
+ "bookmarkLists_userId_idx": {
+ "name": "bookmarkLists_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "bookmarkLists_userId_id_idx": {
+ "name": "bookmarkLists_userId_id_idx",
+ "columns": [
+ "userId",
+ "id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "bookmarkLists_userId_user_id_fk": {
+ "name": "bookmarkLists_userId_user_id_fk",
+ "tableFrom": "bookmarkLists",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bookmarkLists_parentId_bookmarkLists_id_fk": {
+ "name": "bookmarkLists_parentId_bookmarkLists_id_fk",
+ "tableFrom": "bookmarkLists",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "parentId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarkTags": {
+ "name": "bookmarkTags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "normalizedName": {
+ "name": "normalizedName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "generated": {
+ "as": "(lower(replace(replace(replace(\"name\", ' ', ''), '-', ''), '_', '')))",
+ "type": "virtual"
+ }
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "bookmarkTags_name_idx": {
+ "name": "bookmarkTags_name_idx",
+ "columns": [
+ "name"
+ ],
+ "isUnique": false
+ },
+ "bookmarkTags_userId_idx": {
+ "name": "bookmarkTags_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "bookmarkTags_normalizedName_idx": {
+ "name": "bookmarkTags_normalizedName_idx",
+ "columns": [
+ "normalizedName"
+ ],
+ "isUnique": false
+ },
+ "bookmarkTags_userId_name_unique": {
+ "name": "bookmarkTags_userId_name_unique",
+ "columns": [
+ "userId",
+ "name"
+ ],
+ "isUnique": true
+ },
+ "bookmarkTags_userId_id_idx": {
+ "name": "bookmarkTags_userId_id_idx",
+ "columns": [
+ "userId",
+ "id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "bookmarkTags_userId_user_id_fk": {
+ "name": "bookmarkTags_userId_user_id_fk",
+ "tableFrom": "bookmarkTags",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarkTexts": {
+ "name": "bookmarkTexts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sourceUrl": {
+ "name": "sourceUrl",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "bookmarkTexts_id_bookmarks_id_fk": {
+ "name": "bookmarkTexts_id_bookmarks_id_fk",
+ "tableFrom": "bookmarkTexts",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarks": {
+ "name": "bookmarks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "archived": {
+ "name": "archived",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "favourited": {
+ "name": "favourited",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "taggingStatus": {
+ "name": "taggingStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "summarizationStatus": {
+ "name": "summarizationStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "embeddingStatus": {
+ "name": "embeddingStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "bookmarks_userId_idx": {
+ "name": "bookmarks_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "bookmarks_createdAt_idx": {
+ "name": "bookmarks_createdAt_idx",
+ "columns": [
+ "createdAt"
+ ],
+ "isUnique": false
+ },
+ "bookmarks_userId_createdAt_id_idx": {
+ "name": "bookmarks_userId_createdAt_id_idx",
+ "columns": [
+ "userId",
+ "createdAt",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "bookmarks_userId_archived_createdAt_id_idx": {
+ "name": "bookmarks_userId_archived_createdAt_id_idx",
+ "columns": [
+ "userId",
+ "archived",
+ "createdAt",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "bookmarks_userId_favourited_createdAt_id_idx": {
+ "name": "bookmarks_userId_favourited_createdAt_id_idx",
+ "columns": [
+ "userId",
+ "favourited",
+ "createdAt",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bookmarks_userId_user_id_fk": {
+ "name": "bookmarks_userId_user_id_fk",
+ "tableFrom": "bookmarks",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarksInLists": {
+ "name": "bookmarksInLists",
+ "columns": {
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "listId": {
+ "name": "listId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "addedAt": {
+ "name": "addedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "listMembershipId": {
+ "name": "listMembershipId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "bookmarksInLists_bookmarkId_idx": {
+ "name": "bookmarksInLists_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "bookmarksInLists_listId_idx": {
+ "name": "bookmarksInLists_listId_idx",
+ "columns": [
+ "listId"
+ ],
+ "isUnique": false
+ },
+ "bookmarksInLists_listId_bookmarkId_idx": {
+ "name": "bookmarksInLists_listId_bookmarkId_idx",
+ "columns": [
+ "listId",
+ "bookmarkId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bookmarksInLists_bookmarkId_bookmarks_id_fk": {
+ "name": "bookmarksInLists_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "bookmarksInLists",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bookmarksInLists_listId_bookmarkLists_id_fk": {
+ "name": "bookmarksInLists_listId_bookmarkLists_id_fk",
+ "tableFrom": "bookmarksInLists",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "listId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bookmarksInLists_listMembershipId_listCollaborators_id_fk": {
+ "name": "bookmarksInLists_listMembershipId_listCollaborators_id_fk",
+ "tableFrom": "bookmarksInLists",
+ "tableTo": "listCollaborators",
+ "columnsFrom": [
+ "listMembershipId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "bookmarksInLists_bookmarkId_listId_pk": {
+ "columns": [
+ "bookmarkId",
+ "listId"
+ ],
+ "name": "bookmarksInLists_bookmarkId_listId_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "config": {
+ "name": "config",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "customPrompts": {
+ "name": "customPrompts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appliesTo": {
+ "name": "appliesTo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "customPrompts_userId_idx": {
+ "name": "customPrompts_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "customPrompts_userId_user_id_fk": {
+ "name": "customPrompts_userId_user_id_fk",
+ "tableFrom": "customPrompts",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "highlights": {
+ "name": "highlights",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "startOffset": {
+ "name": "startOffset",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endOffset": {
+ "name": "endOffset",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'yellow'"
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "highlights_bookmarkId_idx": {
+ "name": "highlights_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "highlights_userId_idx": {
+ "name": "highlights_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "highlights_bookmarkId_bookmarks_id_fk": {
+ "name": "highlights_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "highlights",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "highlights_userId_user_id_fk": {
+ "name": "highlights_userId_user_id_fk",
+ "tableFrom": "highlights",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "importSessionBookmarks": {
+ "name": "importSessionBookmarks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "importSessionId": {
+ "name": "importSessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "importSessionBookmarks_sessionId_idx": {
+ "name": "importSessionBookmarks_sessionId_idx",
+ "columns": [
+ "importSessionId"
+ ],
+ "isUnique": false
+ },
+ "importSessionBookmarks_bookmarkId_idx": {
+ "name": "importSessionBookmarks_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "importSessionBookmarks_importSessionId_bookmarkId_unique": {
+ "name": "importSessionBookmarks_importSessionId_bookmarkId_unique",
+ "columns": [
+ "importSessionId",
+ "bookmarkId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "importSessionBookmarks_importSessionId_importSessions_id_fk": {
+ "name": "importSessionBookmarks_importSessionId_importSessions_id_fk",
+ "tableFrom": "importSessionBookmarks",
+ "tableTo": "importSessions",
+ "columnsFrom": [
+ "importSessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "importSessionBookmarks_bookmarkId_bookmarks_id_fk": {
+ "name": "importSessionBookmarks_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "importSessionBookmarks",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "importSessions": {
+ "name": "importSessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rootListId": {
+ "name": "rootListId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'staging'"
+ },
+ "lastProcessedAt": {
+ "name": "lastProcessedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "importSessions_userId_idx": {
+ "name": "importSessions_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "importSessions_status_idx": {
+ "name": "importSessions_status_idx",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "importSessions_userId_user_id_fk": {
+ "name": "importSessions_userId_user_id_fk",
+ "tableFrom": "importSessions",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "importSessions_rootListId_bookmarkLists_id_fk": {
+ "name": "importSessions_rootListId_bookmarkLists_id_fk",
+ "tableFrom": "importSessions",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "rootListId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "importStagingBookmarks": {
+ "name": "importStagingBookmarks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "importSessionId": {
+ "name": "importSessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "listIds": {
+ "name": "listIds",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sourceAddedAt": {
+ "name": "sourceAddedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "archived": {
+ "name": "archived",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "processingStartedAt": {
+ "name": "processingStartedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "result": {
+ "name": "result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resultReason": {
+ "name": "resultReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resultBookmarkId": {
+ "name": "resultBookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "completedAt": {
+ "name": "completedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "importStaging_session_status_idx": {
+ "name": "importStaging_session_status_idx",
+ "columns": [
+ "importSessionId",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "importStaging_completedAt_idx": {
+ "name": "importStaging_completedAt_idx",
+ "columns": [
+ "completedAt"
+ ],
+ "isUnique": false
+ },
+ "importStaging_status_idx": {
+ "name": "importStaging_status_idx",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ },
+ "importStaging_status_processingStartedAt_idx": {
+ "name": "importStaging_status_processingStartedAt_idx",
+ "columns": [
+ "status",
+ "processingStartedAt"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "importStagingBookmarks_importSessionId_importSessions_id_fk": {
+ "name": "importStagingBookmarks_importSessionId_importSessions_id_fk",
+ "tableFrom": "importStagingBookmarks",
+ "tableTo": "importSessions",
+ "columnsFrom": [
+ "importSessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "importStagingBookmarks_resultBookmarkId_bookmarks_id_fk": {
+ "name": "importStagingBookmarks_resultBookmarkId_bookmarks_id_fk",
+ "tableFrom": "importStagingBookmarks",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "resultBookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "invites": {
+ "name": "invites",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "usedAt": {
+ "name": "usedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "invitedBy": {
+ "name": "invitedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "invites_token_unique": {
+ "name": "invites_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "invites_invitedBy_user_id_fk": {
+ "name": "invites_invitedBy_user_id_fk",
+ "tableFrom": "invites",
+ "tableTo": "user",
+ "columnsFrom": [
+ "invitedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "listCollaborators": {
+ "name": "listCollaborators",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "listId": {
+ "name": "listId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "addedBy": {
+ "name": "addedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "listCollaborators_listId_idx": {
+ "name": "listCollaborators_listId_idx",
+ "columns": [
+ "listId"
+ ],
+ "isUnique": false
+ },
+ "listCollaborators_userId_idx": {
+ "name": "listCollaborators_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "listCollaborators_listId_userId_unique": {
+ "name": "listCollaborators_listId_userId_unique",
+ "columns": [
+ "listId",
+ "userId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "listCollaborators_listId_bookmarkLists_id_fk": {
+ "name": "listCollaborators_listId_bookmarkLists_id_fk",
+ "tableFrom": "listCollaborators",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "listId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "listCollaborators_userId_user_id_fk": {
+ "name": "listCollaborators_userId_user_id_fk",
+ "tableFrom": "listCollaborators",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "listCollaborators_addedBy_user_id_fk": {
+ "name": "listCollaborators_addedBy_user_id_fk",
+ "tableFrom": "listCollaborators",
+ "tableTo": "user",
+ "columnsFrom": [
+ "addedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "listInvitations": {
+ "name": "listInvitations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "listId": {
+ "name": "listId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "invitedAt": {
+ "name": "invitedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invitedEmail": {
+ "name": "invitedEmail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "invitedBy": {
+ "name": "invitedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "listInvitations_listId_idx": {
+ "name": "listInvitations_listId_idx",
+ "columns": [
+ "listId"
+ ],
+ "isUnique": false
+ },
+ "listInvitations_userId_idx": {
+ "name": "listInvitations_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "listInvitations_status_idx": {
+ "name": "listInvitations_status_idx",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ },
+ "listInvitations_listId_userId_unique": {
+ "name": "listInvitations_listId_userId_unique",
+ "columns": [
+ "listId",
+ "userId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "listInvitations_listId_bookmarkLists_id_fk": {
+ "name": "listInvitations_listId_bookmarkLists_id_fk",
+ "tableFrom": "listInvitations",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "listId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "listInvitations_userId_user_id_fk": {
+ "name": "listInvitations_userId_user_id_fk",
+ "tableFrom": "listInvitations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "listInvitations_invitedBy_user_id_fk": {
+ "name": "listInvitations_invitedBy_user_id_fk",
+ "tableFrom": "listInvitations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "invitedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "passwordResetToken": {
+ "name": "passwordResetToken",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "passwordResetToken_token_unique": {
+ "name": "passwordResetToken_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ },
+ "passwordResetTokens_userId_idx": {
+ "name": "passwordResetTokens_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "passwordResetToken_userId_user_id_fk": {
+ "name": "passwordResetToken_userId_user_id_fk",
+ "tableFrom": "passwordResetToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "rssFeedImports": {
+ "name": "rssFeedImports",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "entryId": {
+ "name": "entryId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rssFeedId": {
+ "name": "rssFeedId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "rssFeedImports_feedIdIdx_idx": {
+ "name": "rssFeedImports_feedIdIdx_idx",
+ "columns": [
+ "rssFeedId"
+ ],
+ "isUnique": false
+ },
+ "rssFeedImports_entryIdIdx_idx": {
+ "name": "rssFeedImports_entryIdIdx_idx",
+ "columns": [
+ "entryId"
+ ],
+ "isUnique": false
+ },
+ "rssFeedImports_rssFeedId_bookmarkId_idx": {
+ "name": "rssFeedImports_rssFeedId_bookmarkId_idx",
+ "columns": [
+ "rssFeedId",
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "rssFeedImports_rssFeedId_entryId_unique": {
+ "name": "rssFeedImports_rssFeedId_entryId_unique",
+ "columns": [
+ "rssFeedId",
+ "entryId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "rssFeedImports_rssFeedId_rssFeeds_id_fk": {
+ "name": "rssFeedImports_rssFeedId_rssFeeds_id_fk",
+ "tableFrom": "rssFeedImports",
+ "tableTo": "rssFeeds",
+ "columnsFrom": [
+ "rssFeedId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rssFeedImports_bookmarkId_bookmarks_id_fk": {
+ "name": "rssFeedImports_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "rssFeedImports",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "rssFeeds": {
+ "name": "rssFeeds",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "importTags": {
+ "name": "importTags",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lastFetchedAt": {
+ "name": "lastFetchedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastSuccessfulFetchAt": {
+ "name": "lastSuccessfulFetchAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastFetchedStatus": {
+ "name": "lastFetchedStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "rssFeeds_userId_idx": {
+ "name": "rssFeeds_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "rssFeeds_userId_user_id_fk": {
+ "name": "rssFeeds_userId_user_id_fk",
+ "tableFrom": "rssFeeds",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ruleEngineActions": {
+ "name": "ruleEngineActions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ruleId": {
+ "name": "ruleId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "listId": {
+ "name": "listId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tagId": {
+ "name": "tagId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ruleEngineActions_userId_idx": {
+ "name": "ruleEngineActions_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "ruleEngineActions_ruleId_idx": {
+ "name": "ruleEngineActions_ruleId_idx",
+ "columns": [
+ "ruleId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "ruleEngineActions_userId_user_id_fk": {
+ "name": "ruleEngineActions_userId_user_id_fk",
+ "tableFrom": "ruleEngineActions",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ruleEngineActions_ruleId_ruleEngineRules_id_fk": {
+ "name": "ruleEngineActions_ruleId_ruleEngineRules_id_fk",
+ "tableFrom": "ruleEngineActions",
+ "tableTo": "ruleEngineRules",
+ "columnsFrom": [
+ "ruleId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ruleEngineActions_userId_tagId_fk": {
+ "name": "ruleEngineActions_userId_tagId_fk",
+ "tableFrom": "ruleEngineActions",
+ "tableTo": "bookmarkTags",
+ "columnsFrom": [
+ "userId",
+ "tagId"
+ ],
+ "columnsTo": [
+ "userId",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ruleEngineActions_userId_listId_fk": {
+ "name": "ruleEngineActions_userId_listId_fk",
+ "tableFrom": "ruleEngineActions",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "userId",
+ "listId"
+ ],
+ "columnsTo": [
+ "userId",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ruleEngineRules": {
+ "name": "ruleEngineRules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "event": {
+ "name": "event",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "condition": {
+ "name": "condition",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tagId": {
+ "name": "tagId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ruleEngine_userId_idx": {
+ "name": "ruleEngine_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "ruleEngineRules_userId_user_id_fk": {
+ "name": "ruleEngineRules_userId_user_id_fk",
+ "tableFrom": "ruleEngineRules",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ruleEngineRules_userId_tagId_fk": {
+ "name": "ruleEngineRules_userId_tagId_fk",
+ "tableFrom": "ruleEngineRules",
+ "tableTo": "bookmarkTags",
+ "columnsFrom": [
+ "userId",
+ "tagId"
+ ],
+ "columnsTo": [
+ "userId",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session": {
+ "name": "session",
+ "columns": {
+ "sessionToken": {
+ "name": "sessionToken",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_userId_user_id_fk": {
+ "name": "session_userId_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscriptions": {
+ "name": "subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tier": {
+ "name": "tier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'free'"
+ },
+ "priceId": {
+ "name": "priceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancelAtPeriodEnd": {
+ "name": "cancelAtPeriodEnd",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "startDate": {
+ "name": "startDate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "endDate": {
+ "name": "endDate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subscriptions_userId_unique": {
+ "name": "subscriptions_userId_unique",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": true
+ },
+ "subscriptions_userId_idx": {
+ "name": "subscriptions_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "subscriptions_stripeCustomerId_idx": {
+ "name": "subscriptions_stripeCustomerId_idx",
+ "columns": [
+ "stripeCustomerId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subscriptions_userId_user_id_fk": {
+ "name": "subscriptions_userId_user_id_fk",
+ "tableFrom": "subscriptions",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tagsOnBookmarks": {
+ "name": "tagsOnBookmarks",
+ "columns": {
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tagId": {
+ "name": "tagId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attachedAt": {
+ "name": "attachedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attachedBy": {
+ "name": "attachedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "tagsOnBookmarks_tagId_idx": {
+ "name": "tagsOnBookmarks_tagId_idx",
+ "columns": [
+ "tagId"
+ ],
+ "isUnique": false
+ },
+ "tagsOnBookmarks_bookmarkId_idx": {
+ "name": "tagsOnBookmarks_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "tagsOnBookmarks_tagId_bookmarkId_idx": {
+ "name": "tagsOnBookmarks_tagId_bookmarkId_idx",
+ "columns": [
+ "tagId",
+ "bookmarkId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "tagsOnBookmarks_bookmarkId_bookmarks_id_fk": {
+ "name": "tagsOnBookmarks_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "tagsOnBookmarks",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tagsOnBookmarks_tagId_bookmarkTags_id_fk": {
+ "name": "tagsOnBookmarks_tagId_bookmarkTags_id_fk",
+ "tableFrom": "tagsOnBookmarks",
+ "tableTo": "bookmarkTags",
+ "columnsFrom": [
+ "tagId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "tagsOnBookmarks_bookmarkId_tagId_pk": {
+ "columns": [
+ "bookmarkId",
+ "tagId"
+ ],
+ "name": "tagsOnBookmarks_bookmarkId_tagId_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "userReadingProgress": {
+ "name": "userReadingProgress",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "readingProgressOffset": {
+ "name": "readingProgressOffset",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "readingProgressAnchor": {
+ "name": "readingProgressAnchor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "readingProgressPercent": {
+ "name": "readingProgressPercent",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "userReadingProgress_bookmarkId_idx": {
+ "name": "userReadingProgress_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "userReadingProgress_userId_idx": {
+ "name": "userReadingProgress_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "userReadingProgress_bookmarkId_userId_unique": {
+ "name": "userReadingProgress_bookmarkId_userId_unique",
+ "columns": [
+ "bookmarkId",
+ "userId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "userReadingProgress_bookmarkId_bookmarks_id_fk": {
+ "name": "userReadingProgress_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "userReadingProgress",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "userReadingProgress_userId_user_id_fk": {
+ "name": "userReadingProgress_userId_user_id_fk",
+ "tableFrom": "userReadingProgress",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user": {
+ "name": "user",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "salt": {
+ "name": "salt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'user'"
+ },
+ "bookmarkQuota": {
+ "name": "bookmarkQuota",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "storageQuota": {
+ "name": "storageQuota",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "browserCrawlingEnabled": {
+ "name": "browserCrawlingEnabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bookmarkClickAction": {
+ "name": "bookmarkClickAction",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'open_original_link'"
+ },
+ "archiveDisplayBehaviour": {
+ "name": "archiveDisplayBehaviour",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'show'"
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'UTC'"
+ },
+ "backupsEnabled": {
+ "name": "backupsEnabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "backupsFrequency": {
+ "name": "backupsFrequency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'weekly'"
+ },
+ "backupsRetentionDays": {
+ "name": "backupsRetentionDays",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 30
+ },
+ "readerFontSize": {
+ "name": "readerFontSize",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "readerLineHeight": {
+ "name": "readerLineHeight",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "readerFontFamily": {
+ "name": "readerFontFamily",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "autoTaggingEnabled": {
+ "name": "autoTaggingEnabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "autoSummarizationEnabled": {
+ "name": "autoSummarizationEnabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tagStyle": {
+ "name": "tagStyle",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'titlecase-spaces'"
+ },
+ "curatedTagIds": {
+ "name": "curatedTagIds",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "inferredTagLang": {
+ "name": "inferredTagLang",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "verificationToken": {
+ "name": "verificationToken",
+ "columns": {
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "verificationToken_identifier_token_pk": {
+ "columns": [
+ "identifier",
+ "token"
+ ],
+ "name": "verificationToken_identifier_token_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "webhooks": {
+ "name": "webhooks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "events": {
+ "name": "events",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "webhooks_userId_idx": {
+ "name": "webhooks_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "webhooks_userId_user_id_fk": {
+ "name": "webhooks_userId_user_id_fk",
+ "tableFrom": "webhooks",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index 887e56c2..7e6ef631 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -596,6 +596,13 @@
"when": 1777464072035,
"tag": "0084_rule_engine_multi_list_support",
"breakpoints": true
+ },
+ {
+ "idx": 85,
+ "version": "6",
+ "when": 1780154803212,
+ "tag": "0085_add_embedding_status",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/schema.ts b/packages/db/schema.ts
index 68a6b9c8..20a5a78c 100644
--- a/packages/db/schema.ts
+++ b/packages/db/schema.ts
@@ -208,6 +208,9 @@ export const bookmarks = sqliteTable(
summarizationStatus: text("summarizationStatus", {
enum: ["pending", "failure", "success"],
}).default("pending"),
+ embeddingStatus: text("embeddingStatus", {
+ enum: ["pending", "failure", "success"],
+ }).default("pending"),
summary: text("summary"),
note: text("note"),
type: text("type", {
diff --git a/packages/e2e_tests/docker-compose.yml b/packages/e2e_tests/docker-compose.yml
index 20283a82..c8bac712 100644
--- a/packages/e2e_tests/docker-compose.yml
+++ b/packages/e2e_tests/docker-compose.yml
@@ -20,10 +20,14 @@ services:
CRAWLER_VIDEO_DOWNLOAD_MAX_SIZE: -1
OPENAI_API_KEY: aimock-test-key
OPENAI_BASE_URL: http://aimock:4010/v1
+ EMBEDDING_DIMENSIONS: 96
+ EMBEDDING_ENABLE_AUTO_INDEXING: "true"
INFERENCE_ENABLE_AUTO_SUMMARIZATION: "true"
meilisearch:
image: getmeili/meilisearch:v1.41.0
restart: unless-stopped
+ ports:
+ - "${MEILI_PORT:-7700}:7700"
environment:
MEILI_NO_ANALYTICS: "true"
MEILI_MASTER_KEY: dummy
diff --git a/packages/e2e_tests/setup/aimock/inference.json b/packages/e2e_tests/setup/aimock/inference.json
index 20651396..d2152218 100644
--- a/packages/e2e_tests/setup/aimock/inference.json
+++ b/packages/e2e_tests/setup/aimock/inference.json
@@ -1,5 +1,398 @@
{
"fixtures": [
+ {
+ "match": {
+ "model": "text-embedding-3-small"
+ },
+ "response": {
+ "embedding": [
+ 0.002604,
+ 0.005208,
+ 0.007813,
+ 0.010417,
+ 0.013021,
+ 0.015625,
+ 0.018229,
+ 0.020833,
+ 0.023438,
+ 0.026042,
+ 0.028646,
+ 0.03125,
+ 0.033854,
+ 0.036458,
+ 0.039063,
+ 0.041667,
+ 0.044271,
+ 0.046875,
+ 0.049479,
+ 0.052083,
+ 0.054688,
+ 0.057292,
+ 0.059896,
+ 0.0625,
+ 0.065104,
+ 0.067708,
+ 0.070313,
+ 0.072917,
+ 0.075521,
+ 0.078125,
+ 0.080729,
+ 0.083333,
+ 0.085938,
+ 0.088542,
+ 0.091146,
+ 0.09375,
+ 0.096354,
+ 0.098958,
+ 0.101563,
+ 0.104167,
+ 0.106771,
+ 0.109375,
+ 0.111979,
+ 0.114583,
+ 0.117188,
+ 0.119792,
+ 0.122396,
+ 0.125,
+ 0.127604,
+ 0.130208,
+ 0.132813,
+ 0.135417,
+ 0.138021,
+ 0.140625,
+ 0.143229,
+ 0.145833,
+ 0.148438,
+ 0.151042,
+ 0.153646,
+ 0.15625,
+ 0.158854,
+ 0.161458,
+ 0.164063,
+ 0.166667,
+ 0.169271,
+ 0.171875,
+ 0.174479,
+ 0.177083,
+ 0.179688,
+ 0.182292,
+ 0.184896,
+ 0.1875,
+ 0.190104,
+ 0.192708,
+ 0.195313,
+ 0.197917,
+ 0.200521,
+ 0.203125,
+ 0.205729,
+ 0.208333,
+ 0.210938,
+ 0.213542,
+ 0.216146,
+ 0.21875,
+ 0.221354,
+ 0.223958,
+ 0.226563,
+ 0.229167,
+ 0.231771,
+ 0.234375,
+ 0.236979,
+ 0.239583,
+ 0.242188,
+ 0.244792,
+ 0.247396,
+ 0.25,
+ 0.252604,
+ 0.255208,
+ 0.257813,
+ 0.260417,
+ 0.263021,
+ 0.265625,
+ 0.268229,
+ 0.270833,
+ 0.273438,
+ 0.276042,
+ 0.278646,
+ 0.28125,
+ 0.283854,
+ 0.286458,
+ 0.289063,
+ 0.291667,
+ 0.294271,
+ 0.296875,
+ 0.299479,
+ 0.302083,
+ 0.304688,
+ 0.307292,
+ 0.309896,
+ 0.3125,
+ 0.315104,
+ 0.317708,
+ 0.320313,
+ 0.322917,
+ 0.325521,
+ 0.328125,
+ 0.330729,
+ 0.333333,
+ 0.335938,
+ 0.338542,
+ 0.341146,
+ 0.34375,
+ 0.346354,
+ 0.348958,
+ 0.351563,
+ 0.354167,
+ 0.356771,
+ 0.359375,
+ 0.361979,
+ 0.364583,
+ 0.367188,
+ 0.369792,
+ 0.372396,
+ 0.375,
+ 0.377604,
+ 0.380208,
+ 0.382813,
+ 0.385417,
+ 0.388021,
+ 0.390625,
+ 0.393229,
+ 0.395833,
+ 0.398438,
+ 0.401042,
+ 0.403646,
+ 0.40625,
+ 0.408854,
+ 0.411458,
+ 0.414063,
+ 0.416667,
+ 0.419271,
+ 0.421875,
+ 0.424479,
+ 0.427083,
+ 0.429688,
+ 0.432292,
+ 0.434896,
+ 0.4375,
+ 0.440104,
+ 0.442708,
+ 0.445313,
+ 0.447917,
+ 0.450521,
+ 0.453125,
+ 0.455729,
+ 0.458333,
+ 0.460938,
+ 0.463542,
+ 0.466146,
+ 0.46875,
+ 0.471354,
+ 0.473958,
+ 0.476563,
+ 0.479167,
+ 0.481771,
+ 0.484375,
+ 0.486979,
+ 0.489583,
+ 0.492188,
+ 0.494792,
+ 0.497396,
+ 0.5,
+ 0.502604,
+ 0.505208,
+ 0.507813,
+ 0.510417,
+ 0.513021,
+ 0.515625,
+ 0.518229,
+ 0.520833,
+ 0.523438,
+ 0.526042,
+ 0.528646,
+ 0.53125,
+ 0.533854,
+ 0.536458,
+ 0.539063,
+ 0.541667,
+ 0.544271,
+ 0.546875,
+ 0.549479,
+ 0.552083,
+ 0.554688,
+ 0.557292,
+ 0.559896,
+ 0.5625,
+ 0.565104,
+ 0.567708,
+ 0.570313,
+ 0.572917,
+ 0.575521,
+ 0.578125,
+ 0.580729,
+ 0.583333,
+ 0.585938,
+ 0.588542,
+ 0.591146,
+ 0.59375,
+ 0.596354,
+ 0.598958,
+ 0.601563,
+ 0.604167,
+ 0.606771,
+ 0.609375,
+ 0.611979,
+ 0.614583,
+ 0.617188,
+ 0.619792,
+ 0.622396,
+ 0.625,
+ 0.627604,
+ 0.630208,
+ 0.632813,
+ 0.635417,
+ 0.638021,
+ 0.640625,
+ 0.643229,
+ 0.645833,
+ 0.648438,
+ 0.651042,
+ 0.653646,
+ 0.65625,
+ 0.658854,
+ 0.661458,
+ 0.664063,
+ 0.666667,
+ 0.669271,
+ 0.671875,
+ 0.674479,
+ 0.677083,
+ 0.679688,
+ 0.682292,
+ 0.684896,
+ 0.6875,
+ 0.690104,
+ 0.692708,
+ 0.695313,
+ 0.697917,
+ 0.700521,
+ 0.703125,
+ 0.705729,
+ 0.708333,
+ 0.710938,
+ 0.713542,
+ 0.716146,
+ 0.71875,
+ 0.721354,
+ 0.723958,
+ 0.726563,
+ 0.729167,
+ 0.731771,
+ 0.734375,
+ 0.736979,
+ 0.739583,
+ 0.742188,
+ 0.744792,
+ 0.747396,
+ 0.75,
+ 0.752604,
+ 0.755208,
+ 0.757813,
+ 0.760417,
+ 0.763021,
+ 0.765625,
+ 0.768229,
+ 0.770833,
+ 0.773438,
+ 0.776042,
+ 0.778646,
+ 0.78125,
+ 0.783854,
+ 0.786458,
+ 0.789063,
+ 0.791667,
+ 0.794271,
+ 0.796875,
+ 0.799479,
+ 0.802083,
+ 0.804688,
+ 0.807292,
+ 0.809896,
+ 0.8125,
+ 0.815104,
+ 0.817708,
+ 0.820313,
+ 0.822917,
+ 0.825521,
+ 0.828125,
+ 0.830729,
+ 0.833333,
+ 0.835938,
+ 0.838542,
+ 0.841146,
+ 0.84375,
+ 0.846354,
+ 0.848958,
+ 0.851563,
+ 0.854167,
+ 0.856771,
+ 0.859375,
+ 0.861979,
+ 0.864583,
+ 0.867188,
+ 0.869792,
+ 0.872396,
+ 0.875,
+ 0.877604,
+ 0.880208,
+ 0.882813,
+ 0.885417,
+ 0.888021,
+ 0.890625,
+ 0.893229,
+ 0.895833,
+ 0.898438,
+ 0.901042,
+ 0.903646,
+ 0.90625,
+ 0.908854,
+ 0.911458,
+ 0.914063,
+ 0.916667,
+ 0.919271,
+ 0.921875,
+ 0.924479,
+ 0.927083,
+ 0.929688,
+ 0.932292,
+ 0.934896,
+ 0.9375,
+ 0.940104,
+ 0.942708,
+ 0.945313,
+ 0.947917,
+ 0.950521,
+ 0.953125,
+ 0.955729,
+ 0.958333,
+ 0.960938,
+ 0.963542,
+ 0.966146,
+ 0.96875,
+ 0.971354,
+ 0.973958,
+ 0.976563,
+ 0.979167,
+ 0.981771,
+ 0.984375,
+ 0.986979,
+ 0.989583,
+ 0.992188,
+ 0.994792,
+ 0.997396,
+ 1
+ ]
+ }
+ },
{
"match": {
"model": "gpt-4.1-mini",
diff --git a/packages/e2e_tests/setup/startContainers.ts b/packages/e2e_tests/setup/startContainers.ts
index 7a8b2b40..9d585b09 100644
--- a/packages/e2e_tests/setup/startContainers.ts
+++ b/packages/e2e_tests/setup/startContainers.ts
@@ -47,11 +47,12 @@ export default async function ({ provide }: GlobalSetupContext) {
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const karakeepPort = await getRandomPort();
const aimockPort = await getRandomPort();
+ const meiliPort = await getRandomPort();
const buildArg = process.env.E2E_TEST_NO_BUILD ? "" : "--build";
console.log(
- `Starting docker compose on ports karakeep=${karakeepPort} aimock=${aimockPort}...`,
+ `Starting docker compose on ports karakeep=${karakeepPort} aimock=${aimockPort} meili=${meiliPort}...`,
);
execSync(`docker compose up ${buildArg} -d`, {
cwd: __dirname,
@@ -60,6 +61,7 @@ export default async function ({ provide }: GlobalSetupContext) {
...process.env,
KARAKEEP_PORT: karakeepPort.toString(),
AIMOCK_PORT: aimockPort.toString(),
+ MEILI_PORT: meiliPort.toString(),
},
});
@@ -74,9 +76,11 @@ export default async function ({ provide }: GlobalSetupContext) {
provide("karakeepPort", karakeepPort);
provide("aimockPort", aimockPort);
+ provide("meiliPort", meiliPort);
process.env.KARAKEEP_PORT = karakeepPort.toString();
process.env.AIMOCK_PORT = aimockPort.toString();
+ process.env.MEILI_PORT = meiliPort.toString();
return async () => {
console.log("Capturing docker logs...");
@@ -122,5 +126,6 @@ declare module "vitest" {
export interface ProvidedContext {
karakeepPort: number;
aimockPort: number;
+ meiliPort: number;
}
}
diff --git a/packages/e2e_tests/tests/workers/embeddings.test.ts b/packages/e2e_tests/tests/workers/embeddings.test.ts
new file mode 100644
index 00000000..e4403fa0
--- /dev/null
+++ b/packages/e2e_tests/tests/workers/embeddings.test.ts
@@ -0,0 +1,105 @@
+import { assert, beforeEach, describe, expect, inject, it } from "vitest";
+
+import { createKarakeepClient } from "@karakeep/sdk";
+
+import { createTestUser } from "../../utils/api";
+import { waitUntil } from "../../utils/general";
+
+interface MeiliVectorDocument {
+ id: string;
+ userId: string;
+}
+
+describe("Embeddings Worker Tests", () => {
+ const karakeepPort = inject("karakeepPort");
+ const meiliPort = inject("meiliPort");
+
+ if (!karakeepPort || !meiliPort) {
+ throw new Error("Missing required environment variables");
+ }
+
+ let client: ReturnType<typeof createKarakeepClient>;
+ let apiKey: string;
+
+ beforeEach(async () => {
+ apiKey = await createTestUser();
+ client = createKarakeepClient({
+ baseUrl: `http://localhost:${karakeepPort}/api/v1/`,
+ headers: {
+ "Content-Type": "application/json",
+ authorization: `Bearer ${apiKey}`,
+ },
+ });
+ });
+
+ it("indexes and deletes bookmark embeddings", async () => {
+ const { data: createdBookmark, error } = await client.POST("/bookmarks", {
+ body: {
+ type: "text",
+ title: "Embedding worker text bookmark",
+ text: "Karakeep should generate and index an embedding for this bookmark.",
+ },
+ });
+
+ if (error) {
+ throw error;
+ }
+ assert(createdBookmark);
+
+ await waitUntil(async () => {
+ const { data: bookmark } = await client.GET("/bookmarks/{bookmarkId}", {
+ params: {
+ path: {
+ bookmarkId: createdBookmark.id,
+ },
+ },
+ });
+ return bookmark?.embeddingStatus === "success";
+ }, "Text bookmark embedding is indexed");
+
+ const { response: deleteResponse } = await client.DELETE(
+ "/bookmarks/{bookmarkId}",
+ {
+ params: {
+ path: {
+ bookmarkId: createdBookmark.id,
+ },
+ },
+ },
+ );
+
+ expect(deleteResponse.status).toBe(204);
+
+ await waitUntil(async () => {
+ const deletedVector = await getVectorDocument(
+ meiliPort,
+ createdBookmark.id,
+ );
+ return deletedVector === null;
+ }, "Text bookmark embedding is deleted");
+ }, 120000);
+});
+
+async function getVectorDocument(
+ meiliPort: number,
+ bookmarkId: string,
+): Promise<MeiliVectorDocument | null> {
+ const response = await fetch(
+ `http://localhost:${meiliPort}/indexes/bookmarks_vectors/documents/${bookmarkId}?fields=id,userId`,
+ {
+ headers: {
+ Authorization: "Bearer dummy",
+ },
+ },
+ );
+
+ if (response.status === 404) {
+ return null;
+ }
+ if (!response.ok) {
+ throw new Error(
+ `Failed to fetch vector document: ${response.status} ${await response.text()}`,
+ );
+ }
+ return (await response.json()) as MeiliVectorDocument;
+}
diff --git a/packages/open-api/karakeep-openapi-spec.json b/packages/open-api/karakeep-openapi-spec.json
index f728d9dc..2eb6e093 100644
--- a/packages/open-api/karakeep-openapi-spec.json
+++ b/packages/open-api/karakeep-openapi-spec.json
@@ -163,6 +163,16 @@
null
]
},
+ "embeddingStatus": {
+ "type": "string",
+ "nullable": true,
+ "enum": [
+ "success",
+ "failure",
+ "pending",
+ null
+ ]
+ },
"note": {
"type": "string",
"nullable": true
@@ -441,6 +451,7 @@
"favourited",
"taggingStatus",
"summarizationStatus",
+ "embeddingStatus",
"userId",
"tags",
"content",
@@ -1477,6 +1488,16 @@
null
]
},
+ "embeddingStatus": {
+ "type": "string",
+ "nullable": true,
+ "enum": [
+ "success",
+ "failure",
+ "pending",
+ null
+ ]
+ },
"note": {
"type": "string",
"nullable": true
@@ -1512,6 +1533,7 @@
"favourited",
"taggingStatus",
"summarizationStatus",
+ "embeddingStatus",
"userId"
]
}
@@ -1610,6 +1632,16 @@
null
]
},
+ "embeddingStatus": {
+ "type": "string",
+ "nullable": true,
+ "enum": [
+ "success",
+ "failure",
+ "pending",
+ null
+ ]
+ },
"note": {
"type": "string",
"nullable": true
@@ -1645,6 +1677,7 @@
"favourited",
"taggingStatus",
"summarizationStatus",
+ "embeddingStatus",
"userId"
]
}
diff --git a/packages/plugins/lib/batchingDocumentQueue.ts b/packages/plugins/lib/batchingDocumentQueue.ts
new file mode 100644
index 00000000..36bd93d3
--- /dev/null
+++ b/packages/plugins/lib/batchingDocumentQueue.ts
@@ -0,0 +1,191 @@
+import type { Index } from "meilisearch";
+import { Mutex } from "async-mutex";
+
+import logger from "@karakeep/shared/logger";
+
+interface MeiliDocument {
+ id: string;
+}
+
+type PendingOperation<TDocument extends MeiliDocument> =
+ | {
+ type: "add";
+ document: TDocument;
+ resolve: () => void;
+ reject: (error: Error) => void;
+ }
+ | {
+ type: "delete";
+ id: string;
+ resolve: () => void;
+ reject: (error: Error) => void;
+ };
+
+export class BatchingDocumentQueue<TDocument extends MeiliDocument> {
+ private pendingOperations: PendingOperation<TDocument>[] = [];
+ private flushTimeout: ReturnType<typeof setTimeout> | null = null;
+ private mutex = new Mutex();
+
+ constructor(
+ private index: Index<TDocument>,
+ private jobTimeoutSec: number,
+ private batchSize: number,
+ private batchTimeoutMs: number,
+ private logPrefix: string,
+ ) {}
+
+ async addDocument(document: TDocument): Promise<void> {
+ return new Promise((resolve, reject) => {
+ this.pendingOperations.push({ type: "add", document, resolve, reject });
+ this.scheduleFlush();
+
+ if (this.pendingOperations.length >= this.batchSize) {
+ void this.flush();
+ }
+ });
+ }
+
+ async deleteDocument(id: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ this.pendingOperations.push({ type: "delete", id, resolve, reject });
+ this.scheduleFlush();
+
+ if (this.pendingOperations.length >= this.batchSize) {
+ void this.flush();
+ }
+ });
+ }
+
+ private scheduleFlush(): void {
+ if (this.flushTimeout === null) {
+ this.flushTimeout = setTimeout(() => {
+ void this.flush();
+ }, this.batchTimeoutMs);
+ }
+ }
+
+ private async flush(): Promise<void> {
+ await this.mutex.runExclusive(async () => {
+ if (this.flushTimeout) {
+ clearTimeout(this.flushTimeout);
+ this.flushTimeout = null;
+ }
+
+ if (this.pendingOperations.length === 0) return;
+
+ const lastOpIndexByDocId = new Map<string, number>();
+ for (let i = 0; i < this.pendingOperations.length; i++) {
+ const op = this.pendingOperations[i]!;
+ const docId = op.type === "add" ? op.document.id : op.id;
+ lastOpIndexByDocId.set(docId, i);
+ }
+
+ const adds: Extract<PendingOperation<TDocument>, { type: "add" }>[] = [];
+ const deletes: Extract<
+ PendingOperation<TDocument>,
+ { type: "delete" }
+ >[] = [];
+ const supersededByDocId = new Map<
+ string,
+ PendingOperation<TDocument>[]
+ >();
+
+ for (let i = 0; i < this.pendingOperations.length; i++) {
+ const op = this.pendingOperations[i]!;
+ const docId = op.type === "add" ? op.document.id : op.id;
+
+ if (lastOpIndexByDocId.get(docId) !== i) {
+ let list = supersededByDocId.get(docId);
+ if (!list) {
+ list = [];
+ supersededByDocId.set(docId, list);
+ }
+ list.push(op);
+ continue;
+ }
+
+ const superseded = supersededByDocId.get(docId) ?? [];
+ const origResolve = op.resolve;
+ const origReject = op.reject;
+ op.resolve = () => {
+ origResolve();
+ superseded.forEach((s) => s.resolve());
+ };
+ op.reject = (error: Error) => {
+ origReject(error);
+ superseded.forEach((s) => s.reject(error));
+ };
+
+ if (op.type === "add") {
+ adds.push(
+ op as Extract<PendingOperation<TDocument>, { type: "add" }>,
+ );
+ } else {
+ deletes.push(
+ op as Extract<PendingOperation<TDocument>, { type: "delete" }>,
+ );
+ }
+ }
+
+ this.pendingOperations = [];
+
+ for (let i = 0; i < deletes.length; i += this.batchSize) {
+ const batch = deletes.slice(i, i + this.batchSize);
+ logger.debug(
+ `[${this.logPrefix}] Flushing delete batch: size=${batch.length}`,
+ );
+ await this.flushDeleteBatch(batch);
+ }
+
+ for (let i = 0; i < adds.length; i += this.batchSize) {
+ const batch = adds.slice(i, i + this.batchSize);
+ logger.debug(
+ `[${this.logPrefix}] Flushing add batch: size=${batch.length}`,
+ );
+ await this.flushAddBatch(batch);
+ }
+ });
+ }
+
+ private async flushAddBatch(
+ batch: Extract<PendingOperation<TDocument>, { type: "add" }>[],
+ ): Promise<void> {
+ if (batch.length === 0) return;
+
+ try {
+ const documents = batch.map((p) => p.document);
+ const task = await this.index.addDocuments(documents, {
+ primaryKey: "id",
+ });
+ await this.ensureTaskSuccess(task.taskUid);
+ batch.forEach((p) => p.resolve());
+ } catch (error) {
+ batch.forEach((p) => p.reject(error as Error));
+ }
+ }
+
+ private async flushDeleteBatch(
+ batch: Extract<PendingOperation<TDocument>, { type: "delete" }>[],
+ ): Promise<void> {
+ if (batch.length === 0) return;
+
+ try {
+ const ids = batch.map((p) => p.id);
+ const task = await this.index.deleteDocuments(ids);
+ await this.ensureTaskSuccess(task.taskUid);
+ batch.forEach((p) => p.resolve());
+ } catch (error) {
+ batch.forEach((p) => p.reject(error as Error));
+ }
+ }
+
+ private async ensureTaskSuccess(taskUid: number): Promise<void> {
+ const task = await this.index.tasks.waitForTask(taskUid, {
+ interval: 200,
+ timeout: this.jobTimeoutSec * 1000 * 0.9,
+ });
+ if (task.error) {
+ throw new Error(`${this.logPrefix} task failed: ${task.error.message}`);
+ }
+ }
+}
diff --git a/packages/plugins/package.json b/packages/plugins/package.json
index aab7ab30..6ff26c8a 100644
--- a/packages/plugins/package.json
+++ b/packages/plugins/package.json
@@ -9,7 +9,8 @@
"./queue-restate": "./queue-restate/index.ts",
"./ratelimit-memory": "./ratelimit-memory/index.ts",
"./ratelimit-redis": "./ratelimit-redis/index.ts",
- "./search-meilisearch": "./search-meilisearch/index.ts"
+ "./search-meilisearch": "./search-meilisearch/index.ts",
+ "./vectorstore-meilisearch": "./vectorstore-meilisearch/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit",
diff --git a/packages/plugins/search-meilisearch/src/index.ts b/packages/plugins/search-meilisearch/src/index.ts
index 5fee747e..e66533b3 100644
--- a/packages/plugins/search-meilisearch/src/index.ts
+++ b/packages/plugins/search-meilisearch/src/index.ts
@@ -1,5 +1,4 @@
import type { Index } from "meilisearch";
-import { Mutex } from "async-mutex";
import { Meilisearch } from "meilisearch";
import type {
@@ -14,7 +13,7 @@ import serverConfig from "@karakeep/shared/config";
import { PluginProvider } from "@karakeep/shared/plugins";
import { envConfig } from "./env";
-import logger from "@karakeep/shared/logger";
+import { BatchingDocumentQueue } from "../../lib/batchingDocumentQueue";
function filterToMeiliSearchFilter(filter: FilterQuery): string {
switch (filter.type) {
@@ -29,185 +28,8 @@ function filterToMeiliSearchFilter(filter: FilterQuery): string {
}
}
-type PendingOperation =
- | {
- type: "add";
- document: BookmarkSearchDocument;
- resolve: () => void;
- reject: (error: Error) => void;
- }
- | {
- type: "delete";
- id: string;
- resolve: () => void;
- reject: (error: Error) => void;
- };
-
-class BatchingDocumentQueue {
- private pendingOperations: PendingOperation[] = [];
- private flushTimeout: ReturnType<typeof setTimeout> | null = null;
- private mutex = new Mutex();
-
- constructor(
- private index: Index<BookmarkSearchDocument>,
- private jobTimeoutSec: number,
- private batchSize: number,
- private batchTimeoutMs: number,
- ) {}
-
- async addDocument(document: BookmarkSearchDocument): Promise<void> {
- return new Promise((resolve, reject) => {
- this.pendingOperations.push({ type: "add", document, resolve, reject });
- this.scheduleFlush();
-
- if (this.pendingOperations.length >= this.batchSize) {
- void this.flush();
- }
- });
- }
-
- async deleteDocument(id: string): Promise<void> {
- return new Promise((resolve, reject) => {
- this.pendingOperations.push({ type: "delete", id, resolve, reject });
- this.scheduleFlush();
-
- if (this.pendingOperations.length >= this.batchSize) {
- void this.flush();
- }
- });
- }
-
- private scheduleFlush(): void {
- if (this.flushTimeout === null) {
- this.flushTimeout = setTimeout(() => {
- void this.flush();
- }, this.batchTimeoutMs);
- }
- }
-
- private async flush(): Promise<void> {
- await this.mutex.runExclusive(async () => {
- if (this.flushTimeout) {
- clearTimeout(this.flushTimeout);
- this.flushTimeout = null;
- }
-
- if (this.pendingOperations.length === 0) return;
-
- // Deduplicate: for each document ID, only the last operation matters.
- // Earlier operations for the same document are resolved immediately since
- // the final state will be achieved by the last operation.
- const lastOpIndexByDocId = new Map<string, number>();
- for (let i = 0; i < this.pendingOperations.length; i++) {
- const op = this.pendingOperations[i];
- const docId = op.type === "add" ? op.document.id : op.id;
- lastOpIndexByDocId.set(docId, i);
- }
-
- const adds: Extract<PendingOperation, { type: "add" }>[] = [];
- const deletes: Extract<PendingOperation, { type: "delete" }>[] = [];
- const supersededByDocId = new Map<string, PendingOperation[]>();
-
- for (let i = 0; i < this.pendingOperations.length; i++) {
- const op = this.pendingOperations[i];
- const docId = op.type === "add" ? op.document.id : op.id;
-
- if (lastOpIndexByDocId.get(docId) !== i) {
- let list = supersededByDocId.get(docId);
- if (!list) {
- list = [];
- supersededByDocId.set(docId, list);
- }
- list.push(op);
- continue;
- }
-
- // Wrap resolve/reject to also settle any superseded operations
- // for the same document, so callers only see success/failure
- // after the actual batch completes.
- const superseded = supersededByDocId.get(docId) ?? [];
- const origResolve = op.resolve;
- const origReject = op.reject;
- op.resolve = () => {
- origResolve();
- superseded.forEach((s) => s.resolve());
- };
- op.reject = (error: Error) => {
- origReject(error);
- superseded.forEach((s) => s.reject(error));
- };
-
- if (op.type === "add") {
- adds.push(op as Extract<PendingOperation, { type: "add" }>);
- } else {
- deletes.push(op as Extract<PendingOperation, { type: "delete" }>);
- }
- }
-
- this.pendingOperations = [];
-
- // Flush all deletes first, then all adds, in batchSize chunks
- for (let i = 0; i < deletes.length; i += this.batchSize) {
- const batch = deletes.slice(i, i + this.batchSize);
- logger.debug(
- `[meilisearch] Flushing delete batch: size=${batch.length}`,
- );
- await this.flushDeleteBatch(batch);
- }
-
- for (let i = 0; i < adds.length; i += this.batchSize) {
- const batch = adds.slice(i, i + this.batchSize);
- logger.debug(`[meilisearch] Flushing add batch: size=${batch.length}`);
- await this.flushAddBatch(batch);
- }
- });
- }
-
- private async flushAddBatch(
- batch: Extract<PendingOperation, { type: "add" }>[],
- ): Promise<void> {
- if (batch.length === 0) return;
-
- try {
- const documents = batch.map((p) => p.document);
- const task = await this.index.addDocuments(documents, {
- primaryKey: "id",
- });
- await this.ensureTaskSuccess(task.taskUid);
- batch.forEach((p) => p.resolve());
- } catch (error) {
- batch.forEach((p) => p.reject(error as Error));
- }
- }
-
- private async flushDeleteBatch(
- batch: Extract<PendingOperation, { type: "delete" }>[],
- ): Promise<void> {
- if (batch.length === 0) return;
-
- try {
- const ids = batch.map((p) => p.id);
- const task = await this.index.deleteDocuments(ids);
- await this.ensureTaskSuccess(task.taskUid);
- batch.forEach((p) => p.resolve());
- } catch (error) {
- batch.forEach((p) => p.reject(error as Error));
- }
- }
-
- private async ensureTaskSuccess(taskUid: number): Promise<void> {
- const task = await this.index.tasks.waitForTask(taskUid, {
- interval: 200,
- timeout: this.jobTimeoutSec * 1000 * 0.9,
- });
- if (task.error) {
- throw new Error(`Search task failed: ${task.error.message}`);
- }
- }
-}
-
class MeiliSearchIndexClient implements SearchIndexClient {
- private batchQueue: BatchingDocumentQueue;
+ private batchQueue: BatchingDocumentQueue<BookmarkSearchDocument>;
private jobTimeoutSec: number;
constructor(
@@ -222,6 +44,7 @@ class MeiliSearchIndexClient implements SearchIndexClient {
jobTimeoutSec,
batchSize,
batchTimeoutMs,
+ "meilisearch",
);
}
diff --git a/packages/plugins/vectorstore-meilisearch/index.ts b/packages/plugins/vectorstore-meilisearch/index.ts
new file mode 100644
index 00000000..ef332f1e
--- /dev/null
+++ b/packages/plugins/vectorstore-meilisearch/index.ts
@@ -0,0 +1,12 @@
+// Auto-register the MeiliSearch Vector provider when this package is imported
+import { PluginManager, PluginType } from "@karakeep/shared/plugins";
+
+import { MeiliSearchVectorProvider } from "./src";
+
+if (MeiliSearchVectorProvider.isConfigured()) {
+ PluginManager.register({
+ type: PluginType.VectorStore,
+ name: "MeiliSearchVector",
+ provider: new MeiliSearchVectorProvider(),
+ });
+}
diff --git a/packages/plugins/vectorstore-meilisearch/src/env.ts b/packages/plugins/vectorstore-meilisearch/src/env.ts
new file mode 100644
index 00000000..50800950
--- /dev/null
+++ b/packages/plugins/vectorstore-meilisearch/src/env.ts
@@ -0,0 +1,10 @@
+import { z } from "zod";
+
+export const envConfig = z
+ .object({
+ MEILI_ADDR: z.string().optional(),
+ MEILI_MASTER_KEY: z.string().default(""),
+ MEILI_BATCH_SIZE: z.coerce.number().int().positive().default(50),
+ MEILI_BATCH_TIMEOUT_MS: z.coerce.number().int().positive().default(500),
+ })
+ .parse(process.env);
diff --git a/packages/plugins/vectorstore-meilisearch/src/index.ts b/packages/plugins/vectorstore-meilisearch/src/index.ts
new file mode 100644
index 00000000..d0587577
--- /dev/null
+++ b/packages/plugins/vectorstore-meilisearch/src/index.ts
@@ -0,0 +1,258 @@
+import type { Index } from "meilisearch";
+import { Meilisearch } from "meilisearch";
+
+import type {
+ BookmarkVectorDocument,
+ VectorFilterQuery,
+ VectorSearchOptions,
+ VectorSearchResponse,
+ VectorStoreClient,
+} from "@karakeep/shared/vectorStore";
+import serverConfig from "@karakeep/shared/config";
+import { PluginProvider } from "@karakeep/shared/plugins";
+
+import { envConfig } from "./env";
+import { BatchingDocumentQueue } from "../../lib/batchingDocumentQueue";
+
+// Meilisearch document type that includes the vector field
+interface MeiliVectorDocument {
+ id: string;
+ userId: string;
+ _vectors: {
+ default: unknown;
+ };
+}
+
+function filterToMeiliSearchFilter(filter: VectorFilterQuery): string {
+ switch (filter.type) {
+ case "eq":
+ return `${filter.field} = ${JSON.stringify(filter.value)}`;
+ case "in":
+ return `${filter.field} IN [${filter.values
+ .map((v) => JSON.stringify(v))
+ .join(",")}]`;
+ default: {
+ const exhaustiveCheck: never = filter;
+ throw new Error(`Unhandled filter type: ${exhaustiveCheck}`);
+ }
+ }
+}
+
+class MeiliSearchVectorClient implements VectorStoreClient {
+ private batchQueue: BatchingDocumentQueue<MeiliVectorDocument>;
+
+ constructor(
+ private index: Index<MeiliVectorDocument>,
+ private client: Meilisearch,
+ jobTimeoutSec: number,
+ batchSize: number,
+ batchTimeoutMs: number,
+ ) {
+ this.batchQueue = new BatchingDocumentQueue(
+ index,
+ jobTimeoutSec,
+ batchSize,
+ batchTimeoutMs,
+ "meilisearch-vector",
+ );
+ }
+
+ async addVectors(documents: BookmarkVectorDocument[]): Promise<void> {
+ const meiliDocs: MeiliVectorDocument[] = documents.map((doc) => ({
+ id: doc.id,
+ userId: doc.userId,
+ _vectors: {
+ default: doc.vector,
+ },
+ }));
+
+ await Promise.all(
+ meiliDocs.map((document) => this.batchQueue.addDocument(document)),
+ );
+ }
+
+ async deleteVectors(ids: string[]): Promise<void> {
+ await Promise.all(ids.map((id) => this.batchQueue.deleteDocument(id)));
+ }
+
+ async search(options: VectorSearchOptions): Promise<VectorSearchResponse> {
+ const result = await this.index.search("", {
+ vector: options.vector,
+ hybrid: {
+ semanticRatio: 1.0, // Pure vector search
+ embedder: "default",
+ },
+ filter: options.filter?.map((f) => filterToMeiliSearchFilter(f)),
+ limit: options.limit ?? 10,
+ attributesToRetrieve: ["id"],
+ showRankingScore: true,
+ });
+
+ return {
+ hits: result.hits.map((hit) => ({
+ id: hit.id,
+ score: hit._rankingScore ?? 0,
+ })),
+ processingTimeMs: result.processingTimeMs,
+ };
+ }
+
+ async clearIndex(): Promise<void> {
+ const task = await this.index.deleteAllDocuments();
+ await this.ensureTaskSuccess(task.taskUid);
+ }
+
+ private async ensureTaskSuccess(taskUid: number): Promise<void> {
+ const task = await this.client.tasks.waitForTask(taskUid, {
+ interval: 200,
+ timeout: serverConfig.embedding.jobTimeoutSec * 1000 * 0.9,
+ });
+ if (task.error) {
+ throw new Error(`Vector store task failed: ${task.error.message}`);
+ }
+ }
+
+ async getHealth(): Promise<boolean> {
+ if (!this.client) {
+ return false;
+ }
+ const health = await this.client.health();
+ return health.status === "available";
+ }
+}
+
+export class MeiliSearchVectorProvider implements PluginProvider<VectorStoreClient> {
+ private client: Meilisearch | undefined;
+ private version: string | undefined;
+ private vectorClient: VectorStoreClient | undefined;
+ private initPromise: Promise<VectorStoreClient | null> | undefined;
+ private readonly indexName = "bookmarks_vectors";
+
+ constructor() {
+ if (MeiliSearchVectorProvider.isConfigured()) {
+ this.client = new Meilisearch({
+ host: envConfig.MEILI_ADDR!,
+ apiKey: envConfig.MEILI_MASTER_KEY,
+ });
+ }
+ }
+
+ static isConfigured(): boolean {
+ return !!envConfig.MEILI_ADDR;
+ }
+
+ async getClient(): Promise<VectorStoreClient | null> {
+ if (this.vectorClient) {
+ return this.vectorClient;
+ }
+
+ if (this.initPromise) {
+ return this.initPromise;
+ }
+
+ this.initPromise = this.initClient();
+ const client = await this.initPromise;
+ this.initPromise = undefined;
+ return client;
+ }
+
+ private async initClient(): Promise<VectorStoreClient | null> {
+ if (!this.client) {
+ return null;
+ }
+
+ this.version = (await this.client.getVersion()).pkgVersion;
+ const versionParts = this.version.split(".");
+ if (Number(versionParts[0]) < 1) {
+ throw new Error(
+ `Meilisearch version ${this.version[0]} is not supported. Please upgrade to v1.x.`,
+ );
+ } else if (Number(versionParts[1]) < 3) {
+ console.warn(
+ `[meilisearch-vector] Meilisearch version before v1.3.0 doesn't support embeddings. Please upgrade to v1.3.0 or later. You are using ${this.version}`,
+ );
+ return null;
+ } else if (Number(versionParts[1]) < 13) {
+ console.warn(
+ `[meilisearch-vector] Meilisearch version before v1.13.0 didn't have the embeddings API stabilizied. Please upgrade to v1.13.0 or later. You are using ${this.version}`,
+ );
+ return null;
+ } else if (Number(versionParts[1]) < 38) {
+ console.warn(
+ `[meilisearch-vector] Meilisearch version v1.38.0 introduced major vector speed improvements. Please upgrade to v1.38.0 or later to take advantage of these improvements. You are using ${this.version}`,
+ );
+ }
+
+ const indices = await this.client.getIndexes();
+ let indexFound = indices.results.find((i) => i.uid === this.indexName);
+
+ if (!indexFound) {
+ const idx = await this.client.createIndex(this.indexName, {
+ primaryKey: "id",
+ });
+ await this.client.tasks.waitForTask(idx.taskUid);
+ indexFound = await this.client.getIndex<MeiliVectorDocument>(
+ this.indexName,
+ );
+ }
+
+ await this.configureIndex(indexFound);
+ this.vectorClient = new MeiliSearchVectorClient(
+ indexFound,
+ this.client,
+ serverConfig.embedding.jobTimeoutSec,
+ envConfig.MEILI_BATCH_SIZE,
+ envConfig.MEILI_BATCH_TIMEOUT_MS,
+ );
+ return this.vectorClient;
+ }
+
+ private async configureIndex(
+ index: Index<MeiliVectorDocument>,
+ ): Promise<void> {
+ const desiredFilterableAttributes = ["id", "userId"].sort();
+
+ const settings = await index.getSettings();
+
+ // Configure filterable attributes
+ if (
+ JSON.stringify(settings.filterableAttributes?.sort()) !==
+ JSON.stringify(desiredFilterableAttributes)
+ ) {
+ console.log(
+ `[meilisearch-vector] Updating filterable attributes to ${desiredFilterableAttributes} from ${settings.filterableAttributes}`,
+ );
+ const taskId = await index.updateFilterableAttributes(
+ desiredFilterableAttributes,
+ );
+ await this.client!.tasks.waitForTask(taskId.taskUid);
+ }
+
+ // Configure embedders for vector search
+ const currentEmbedders = settings.embedders;
+ const desiredDimensions = serverConfig.embedding.dimensions;
+ const currentEmbedder = currentEmbedders?.default;
+ if (
+ !currentEmbedder ||
+ currentEmbedder.source != "userProvided" ||
+ currentEmbedder.dimensions !== desiredDimensions
+ ) {
+ console.log(`[meilisearch-vector] Configuring user-provided embedder`);
+ try {
+ // Use userProvided embedder since we generate embeddings ourselves
+ await index
+ .updateEmbedders({
+ default: {
+ source: "userProvided",
+ dimensions: desiredDimensions,
+ },
+ })
+ .waitTask();
+ } catch (error) {
+ console.warn(
+ `[meilisearch-vector] Failed to configure embedder. Vector search may not work: ${error}`,
+ );
+ }
+ }
+ }
+}
diff --git a/packages/sdk/src/karakeep-api.d.ts b/packages/sdk/src/karakeep-api.d.ts
index f529316d..5d689c5f 100644
--- a/packages/sdk/src/karakeep-api.d.ts
+++ b/packages/sdk/src/karakeep-api.d.ts
@@ -794,6 +794,8 @@ export interface components {
taggingStatus: "success" | "failure" | "pending" | null;
/** @enum {string|null} */
summarizationStatus: "success" | "failure" | "pending" | null;
+ /** @enum {string|null} */
+ embeddingStatus: "success" | "failure" | "pending" | null;
note?: string | null;
summary?: string | null;
/** @enum {string|null} */
@@ -1328,6 +1330,8 @@ export interface operations {
taggingStatus: "success" | "failure" | "pending" | null;
/** @enum {string|null} */
summarizationStatus: "success" | "failure" | "pending" | null;
+ /** @enum {string|null} */
+ embeddingStatus: "success" | "failure" | "pending" | null;
note?: string | null;
summary?: string | null;
/** @enum {string|null} */
@@ -1393,6 +1397,8 @@ export interface operations {
taggingStatus: "success" | "failure" | "pending" | null;
/** @enum {string|null} */
summarizationStatus: "success" | "failure" | "pending" | null;
+ /** @enum {string|null} */
+ embeddingStatus: "success" | "failure" | "pending" | null;
note?: string | null;
summary?: string | null;
/** @enum {string|null} */
diff --git a/packages/shared-server/src/eventLogTypes.ts b/packages/shared-server/src/eventLogTypes.ts
index a7765a94..6ce13353 100644
--- a/packages/shared-server/src/eventLogTypes.ts
+++ b/packages/shared-server/src/eventLogTypes.ts
@@ -77,6 +77,13 @@ type EventLogInternal =
"bookmark.id"?: string;
"search.document_size"?: number;
}
+ | {
+ ["event.name"]: "embeddingsWorker.run";
+ "bookmark.id"?: string;
+ "embedding.text_size"?: number;
+ "embedding.prompt_tokens"?: number;
+ "embedding.total_tokens"?: number;
+ }
| {
["event.name"]: "backupWorker.run";
"backup.id"?: string;
diff --git a/packages/shared-server/src/plugins.ts b/packages/shared-server/src/plugins.ts
index 0975323b..dc9fa547 100644
--- a/packages/shared-server/src/plugins.ts
+++ b/packages/shared-server/src/plugins.ts
@@ -27,6 +27,7 @@ export async function loadAllPlugins() {
await import("@karakeep/plugins/queue-liteque");
await import("@karakeep/plugins/queue-restate");
await import("@karakeep/plugins/search-meilisearch");
+ await import("@karakeep/plugins/vectorstore-meilisearch");
// Rate limiters (order matters - last one wins)
await import("@karakeep/plugins/ratelimit-memory");
await import("@karakeep/plugins/ratelimit-redis");
diff --git a/packages/shared-server/src/queues.ts b/packages/shared-server/src/queues.ts
index 30bbff36..c0456836 100644
--- a/packages/shared-server/src/queues.ts
+++ b/packages/shared-server/src/queues.ts
@@ -130,6 +130,25 @@ export const OpenAIQueue = createDeferredQueue<ZOpenAIRequest>("openai_queue", {
keepFailedJobs: false,
});
+// Embeddings Worker
+export const zEmbeddingsRequestSchema = z.object({
+ bookmarkId: z.string(),
+ type: z.enum(["index", "delete"]).default("index"),
+ force: z.boolean().optional(),
+ runTaggingOnComplete: z.boolean().optional(),
+});
+export type ZEmbeddingsRequest = z.infer<typeof zEmbeddingsRequestSchema>;
+
+export const EmbeddingsQueue = createDeferredQueue<ZEmbeddingsRequest>(
+ "embeddings_queue",
+ {
+ defaultJobArgs: {
+ numRetries: 3,
+ },
+ keepFailedJobs: false,
+ },
+);
+
// Search Indexing Worker
export const zSearchIndexingRequestSchema = z.object({
bookmarkId: z.string(),
diff --git a/packages/shared/config.ts b/packages/shared/config.ts
index 47d8556c..1f81ed11 100644
--- a/packages/shared/config.ts
+++ b/packages/shared/config.ts
@@ -70,7 +70,12 @@ const allEnv = z.object({
INFERENCE_FETCH_TIMEOUT_SEC: z.coerce.number().default(300),
INFERENCE_TEXT_MODEL: z.string().default("gpt-4.1-mini"),
INFERENCE_IMAGE_MODEL: z.string().default("gpt-4o-mini"),
+ EMBEDDING_ENABLE_AUTO_INDEXING: stringBool("false"),
EMBEDDING_TEXT_MODEL: z.string().default("text-embedding-3-small"),
+ EMBEDDING_DIMENSIONS: z.coerce.number().default(1536),
+ EMBEDDING_CONTEXT_LENGTH: z.coerce.number().int().positive().default(8000),
+ EMBEDDING_NUM_WORKERS: z.coerce.number().default(1),
+ EMBEDDING_JOB_TIMEOUT_SEC: z.coerce.number().default(60),
INFERENCE_CONTEXT_LENGTH: z.coerce.number().default(2048),
INFERENCE_MAX_OUTPUT_TOKENS: z.coerce.number().default(2048),
INFERENCE_USE_MAX_COMPLETION_TOKENS: stringBool("false"),
@@ -324,7 +329,12 @@ const serverConfigSchema = allEnv.transform((val, ctx) => {
enableAutoSummarization: val.INFERENCE_ENABLE_AUTO_SUMMARIZATION,
},
embedding: {
+ enableAutoIndexing: val.EMBEDDING_ENABLE_AUTO_INDEXING,
textModel: val.EMBEDDING_TEXT_MODEL,
+ dimensions: val.EMBEDDING_DIMENSIONS,
+ contextLength: val.EMBEDDING_CONTEXT_LENGTH,
+ numWorkers: val.EMBEDDING_NUM_WORKERS,
+ jobTimeoutSec: val.EMBEDDING_JOB_TIMEOUT_SEC,
},
crawler: {
numWorkers: val.CRAWLER_NUM_WORKERS,
diff --git a/packages/shared/inference.ts b/packages/shared/inference.ts
index bb3b2218..d58a49af 100644
--- a/packages/shared/inference.ts
+++ b/packages/shared/inference.ts
@@ -15,6 +15,91 @@ export interface InferenceResponse {
export interface EmbeddingResponse {
embeddings: number[][];
+ totalTokens: number | undefined;
+ promptTokens: number | undefined;
+}
+
+function isNumberArray(value: unknown): value is number[] {
+ return (
+ Array.isArray(value) && value.every((item) => typeof item === "number")
+ );
+}
+
+function isNumberArray2D(value: unknown): value is number[][] {
+ return Array.isArray(value) && value.every(isNumberArray);
+}
+
+function parseEmbeddingResponse(response: unknown): number[][] {
+ if (!response || typeof response !== "object") {
+ throw new Error(`Got invalid embedding response from inference provider`);
+ }
+
+ if ("data" in response && Array.isArray(response.data)) {
+ const embeddings = response.data.map((item) => {
+ if (
+ item &&
+ typeof item === "object" &&
+ "embedding" in item &&
+ isNumberArray(item.embedding)
+ ) {
+ return item.embedding;
+ }
+ throw new Error(
+ `Got embedding response item without a numeric embedding array`,
+ );
+ });
+ return embeddings;
+ }
+
+ if ("embeddings" in response && isNumberArray2D(response.embeddings)) {
+ return response.embeddings;
+ }
+
+ if ("embedding" in response && isNumberArray(response.embedding)) {
+ return [response.embedding];
+ }
+
+ const keys = Object.keys(response).join(", ");
+ throw new Error(
+ `Got embedding response with unsupported shape from inference provider. Keys: ${keys}`,
+ );
+}
+
+function getNumericField(
+ value: Record<string, unknown>,
+ field: string,
+): number | undefined {
+ const raw = value[field];
+ return typeof raw === "number" && Number.isFinite(raw) ? raw : undefined;
+}
+
+function parseEmbeddingUsage(response: unknown): {
+ promptTokens: number | undefined;
+ totalTokens: number | undefined;
+} {
+ if (!response || typeof response !== "object") {
+ return { promptTokens: undefined, totalTokens: undefined };
+ }
+
+ const responseObj = response as Record<string, unknown>;
+ const usage = responseObj.usage;
+ if (usage && typeof usage === "object") {
+ const usageObj = usage as Record<string, unknown>;
+ return {
+ promptTokens: getNumericField(usageObj, "prompt_tokens"),
+ totalTokens: getNumericField(usageObj, "total_tokens"),
+ };
+ }
+
+ const promptTokens =
+ getNumericField(responseObj, "prompt_eval_count") ??
+ getNumericField(responseObj, "prompt_tokens");
+ const totalTokens =
+ getNumericField(responseObj, "total_tokens") ??
+ getNumericField(responseObj, "eval_count") ??
+ promptTokens;
+
+ return { promptTokens, totalTokens };
}
export interface InferenceOptions {
@@ -221,10 +306,9 @@ export class OpenAIInferenceClient implements InferenceClient {
model: model,
input: inputs,
});
- const embedding2D: number[][] = embedResponse.data.map(
- (embedding: OpenAI.Embedding) => embedding.embedding,
- );
- return { embeddings: embedding2D };
+ const embedding2D = parseEmbeddingResponse(embedResponse);
+ const usage = parseEmbeddingUsage(embedResponse);
+ return { embeddings: embedding2D, ...usage };
}
}
@@ -379,6 +463,7 @@ class OllamaInferenceClient implements InferenceClient {
// in the future we want to add a way to split the input into multiple parts.
truncate: true,
});
- return { embeddings: embedding.embeddings };
+ const usage = parseEmbeddingUsage(embedding);
+ return { embeddings: embedding.embeddings, ...usage };
}
}
diff --git a/packages/shared/plugins.ts b/packages/shared/plugins.ts
index 5ceee91c..974b9215 100644
--- a/packages/shared/plugins.ts
+++ b/packages/shared/plugins.ts
@@ -2,6 +2,7 @@
import type { QueueClient } from "./queueing";
import type { RateLimitClient } from "./ratelimiting";
+import type { VectorStoreClient } from "./vectorStore";
import logger from "./logger";
import { SearchIndexClient } from "./search";
@@ -9,12 +10,14 @@ export enum PluginType {
Search = "search",
Queue = "queue",
RateLimit = "ratelimit",
+ VectorStore = "vectorstore",
}
interface PluginTypeMap {
[PluginType.Search]: SearchIndexClient;
[PluginType.Queue]: QueueClient;
[PluginType.RateLimit]: RateLimitClient;
+ [PluginType.VectorStore]: VectorStoreClient;
}
export interface TPlugin<T extends PluginType> {
@@ -37,6 +40,7 @@ function createProviderMap(): ProviderMap {
[PluginType.Search]: [],
[PluginType.Queue]: [],
[PluginType.RateLimit]: [],
+ [PluginType.VectorStore]: [],
};
}
@@ -49,8 +53,13 @@ export class PluginManager {
pluginProvidersKey
] ??= createProviderMap());
+ private static providersFor<T extends PluginType>(type: T): TPlugin<T>[] {
+ PluginManager.providers[type] ??= [] as ProviderMap[T];
+ return PluginManager.providers[type] as TPlugin<T>[];
+ }
+
static register<T extends PluginType>(plugin: TPlugin<T>): void {
- const providers = PluginManager.providers[plugin.type];
+ const providers = PluginManager.providersFor(plugin.type);
const existingProvider = providers.findIndex((p) => p.name === plugin.name);
if (existingProvider >= 0) {
return;
@@ -61,7 +70,7 @@ export class PluginManager {
static async getClient<T extends PluginType>(
type: T,
): Promise<PluginTypeMap[T] | null> {
- const providers: TPlugin<T>[] = PluginManager.providers[type];
+ const providers = PluginManager.providersFor(type);
if (providers.length === 0) {
return null;
}
@@ -69,11 +78,11 @@ export class PluginManager {
}
static isRegistered<T extends PluginType>(type: T): boolean {
- return PluginManager.providers[type].length > 0;
+ return PluginManager.providersFor(type).length > 0;
}
static getPluginName<T extends PluginType>(type: T): string | null {
- const providers: TPlugin<T>[] = PluginManager.providers[type];
+ const providers = PluginManager.providersFor(type);
if (providers.length === 0) {
return null;
}
diff --git a/packages/shared/types/bookmarks.ts b/packages/shared/types/bookmarks.ts
index 00a7bc4b..b5f495ed 100644
--- a/packages/shared/types/bookmarks.ts
+++ b/packages/shared/types/bookmarks.ts
@@ -108,6 +108,7 @@ export const zBareBookmarkSchema = z.object({
favourited: z.boolean(),
taggingStatus: z.enum(["success", "failure", "pending"]).nullable(),
summarizationStatus: z.enum(["success", "failure", "pending"]).nullable(),
+ embeddingStatus: z.enum(["success", "failure", "pending"]).nullable(),
note: z.string().nullish(),
summary: z.string().nullish(),
source: zBookmarkSourceSchema.nullish(),
diff --git a/packages/shared/vectorStore.ts b/packages/shared/vectorStore.ts
new file mode 100644
index 00000000..ed17752d
--- /dev/null
+++ b/packages/shared/vectorStore.ts
@@ -0,0 +1,72 @@
+import { z } from "zod";
+
+import { PluginManager, PluginType } from "./plugins";
+
+export const zBookmarkVectorDocument = z.object({
+ id: z.string(),
+ userId: z.string(),
+ vector: z.array(z.number()),
+});
+
+export type BookmarkVectorDocument = z.infer<typeof zBookmarkVectorDocument>;
+
+export type VectorFilterableAttributes = "userId" | "id";
+export type VectorFilterQuery =
+ | {
+ type: "eq";
+ field: VectorFilterableAttributes;
+ value: string;
+ }
+ | {
+ type: "in";
+ field: VectorFilterableAttributes;
+ values: string[];
+ };
+
+export interface VectorSearchResult {
+ id: string;
+ score: number;
+}
+
+export interface VectorSearchOptions {
+ vector: number[];
+ // Different filters are ANDed together
+ filter?: VectorFilterQuery[];
+ limit?: number;
+}
+
+export interface VectorSearchResponse {
+ hits: VectorSearchResult[];
+ processingTimeMs: number;
+}
+
+export interface VectorStoreClient {
+ /**
+ * Add or update vectors in the vector store
+ */
+ addVectors(documents: BookmarkVectorDocument[]): Promise<void>;
+
+ /**
+ * Delete vectors by their IDs
+ */
+ deleteVectors(ids: string[]): Promise<void>;
+
+ /**
+ * Search for similar vectors
+ */
+ search(options: VectorSearchOptions): Promise<VectorSearchResponse>;
+
+ /**
+ * Clear all vectors from the index
+ */
+ clearIndex(): Promise<void>;
+
+ /**
+ * Get the vector store health
+ */
+ getHealth(): Promise<boolean>;
+}
+
+export async function getVectorStoreClient(): Promise<VectorStoreClient | null> {
+ return PluginManager.getClient(PluginType.VectorStore);
+}
diff --git a/packages/trpc/models/bookmarks.ts b/packages/trpc/models/bookmarks.ts
index e2813343..f546de04 100644
--- a/packages/trpc/models/bookmarks.ts
+++ b/packages/trpc/models/bookmarks.ts
@@ -29,7 +29,7 @@ import {
rssFeedImportsTable,
tagsOnBookmarks,
} from "@karakeep/db/schema";
-import { SearchIndexingQueue } from "@karakeep/shared-server";
+import { EmbeddingsQueue, SearchIndexingQueue } from "@karakeep/shared-server";
import { WebhooksService } from "./webhooks.service";
import { deleteAsset, readAsset } from "@karakeep/shared/assetdb";
@@ -388,6 +388,7 @@ export class Bookmark extends BareBookmark {
summary: bookmark.summary,
taggingStatus: bookmark.taggingStatus,
summarizationStatus: bookmark.summarizationStatus,
+ embeddingStatus: bookmark.embeddingStatus,
userId: bookmark.userId,
linkInfo,
textInfo,
@@ -940,6 +941,15 @@ export class Bookmark extends BareBookmark {
groupId: this.ctx.user.id,
},
);
+ await EmbeddingsQueue.enqueue(
+ {
+ bookmarkId: this.bookmark.id,
+ type: "delete",
+ },
+ {
+ groupId: this.ctx.user.id,
+ },
+ );
const webhookService = new WebhooksService(this.ctx.db);
await webhookService.triggerWebhook(
diff --git a/packages/trpc/routers/admin.ts b/packages/trpc/routers/admin.ts
index f705ec76..8cf1cef5 100644
--- a/packages/trpc/routers/admin.ts
+++ b/packages/trpc/routers/admin.ts
@@ -1,6 +1,6 @@
import * as dns from "dns";
import { TRPCError } from "@trpc/server";
-import { count, eq, or, sum } from "drizzle-orm";
+import { and, asc, count, eq, gt, inArray, or, sum } from "drizzle-orm";
import { z } from "zod";
import { assets, bookmarkLinks, bookmarks, users } from "@karakeep/db/schema";
@@ -8,6 +8,7 @@ import {
AdminMaintenanceQueue,
AssetPreprocessingQueue,
buildCrawlIdempotencyKey,
+ EmbeddingsQueue,
FeedQueue,
LinkCrawlerQueue,
LowPriorityCrawlerQueue,
@@ -29,6 +30,7 @@ import {
zAdminCreateUserSchema,
} from "@karakeep/shared/types/admin";
import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
+import { getVectorStoreClient } from "@karakeep/shared/vectorStore";
import { generatePasswordSalt, hashPassword } from "../auth";
import { createAdminScopedProcedure, router } from "../index";
@@ -76,6 +78,11 @@ export const adminAppRouter = router({
indexingStats: z.object({
queued: z.number(),
}),
+ embeddingsStats: z.object({
+ queued: z.number(),
+ pending: z.number(),
+ failed: z.number(),
+ }),
adminMaintenanceStats: z.object({
queued: z.number(),
}),
@@ -104,6 +111,11 @@ export const adminAppRouter = router({
// Indexing
queuedIndexing,
+ // Embeddings
+ queuedEmbeddings,
+ [{ value: pendingEmbeddings }],
+ [{ value: failedEmbeddings }],
+
// Inference
queuedInferences,
[{ value: pendingInference }],
@@ -139,6 +151,17 @@ export const adminAppRouter = router({
// Indexing
SearchIndexingQueue.stats(),
+ // Embeddings
+ EmbeddingsQueue.stats(),
+ ctx.db
+ .select({ value: count() })
+ .from(bookmarks)
+ .where(eq(bookmarks.embeddingStatus, "pending")),
+ ctx.db
+ .select({ value: count() })
+ .from(bookmarks)
+ .where(eq(bookmarks.embeddingStatus, "failure")),
+
// Inference
OpenAIQueue.stats(),
ctx.db
@@ -194,6 +217,11 @@ export const adminAppRouter = router({
indexingStats: {
queued: queuedIndexing.pending + queuedIndexing.pending_retry,
},
+ embeddingsStats: {
+ queued: queuedEmbeddings.pending + queuedEmbeddings.pending_retry,
+ pending: pendingEmbeddings,
+ failed: failedEmbeddings,
+ },
adminMaintenanceStats: {
queued:
queuedAdminMaintenance.pending +
@@ -262,6 +290,77 @@ export const adminAppRouter = router({
),
);
}),
+ regenerateAllBookmarkEmbeddings: adminBookmarksProcedure
+ .input(
+ z
+ .object({
+ status: z.enum(["failure", "pending", "all"]).default("all"),
+ })
+ .optional(),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const status = input?.status ?? "all";
+
+ const vectorStore = await getVectorStoreClient();
+ if (status === "all") {
+ await vectorStore?.clearIndex();
+ }
+
+ // Stream through the matching bookmarks in keyset-paginated batches so we
+ // never load every id into memory at once. For "all"/"failure" we flip the
+ // page to "pending" before enqueueing (avoids overwriting a worker-set
+ // status), which also consumes the "failure" filter as we advance.
+ const PAGE_SIZE = 1000;
+ let cursor: string | undefined = undefined;
+ for (;;) {
+ const page = await ctx.db
+ .select({ id: bookmarks.id })
+ .from(bookmarks)
+ .where(
+ and(
+ status === "all"
+ ? undefined
+ : eq(bookmarks.embeddingStatus, status),
+ cursor ? gt(bookmarks.id, cursor) : undefined,
+ ),
+ )
+ .orderBy(asc(bookmarks.id))
+ .limit(PAGE_SIZE);
+ if (page.length === 0) {
+ break;
+ }
+
+ const ids = page.map((b) => b.id);
+ if (status !== "pending") {
+ await ctx.db
+ .update(bookmarks)
+ .set({ embeddingStatus: "pending" })
+ .where(inArray(bookmarks.id, ids));
+ }
+
+ await Promise.all(
+ ids.map((id) =>
+ EmbeddingsQueue.enqueue(
+ {
+ bookmarkId: id,
+ type: "index",
+ force: true,
+ runTaggingOnComplete: false,
+ },
+ {
+ priority: QueuePriority.Low,
+ groupId: "admin",
+ },
+ ),
+ ),
+ );
+
+ cursor = ids[ids.length - 1];
+ if (page.length < PAGE_SIZE) {
+ break;
+ }
+ }
+ }),
reprocessAssetsFixMode: adminBookmarksProcedure.mutation(async ({ ctx }) => {
const bookmarkIds = await ctx.db.query.bookmarkAssets.findMany({
columns: {
@@ -480,6 +579,12 @@ export const adminAppRouter = router({
pluginName: z.string().optional(),
error: z.string().optional(),
}),
+ vectorStore: z.object({
+ configured: z.boolean(),
+ connected: z.boolean(),
+ pluginName: z.string().optional(),
+ error: z.string().optional(),
+ }),
}),
)
.query(async () => {
@@ -502,6 +607,13 @@ export const adminAppRouter = router({
error?: string;
} = { configured: true, connected: false };
+ const vectorStoreStatus: {
+ configured: boolean;
+ connected: boolean;
+ pluginName?: string;
+ error?: string;
+ } = { configured: false, connected: false };
+
const searchClient = await getSearchClient();
searchEngineStatus.configured = searchClient !== null;
@@ -519,6 +631,23 @@ export const adminAppRouter = router({
}
}
+ const vectorStoreClient = await getVectorStoreClient();
+ vectorStoreStatus.configured = vectorStoreClient !== null;
+
+ if (vectorStoreClient) {
+ const pluginName = PluginManager.getPluginName(PluginType.VectorStore);
+ if (pluginName) {
+ vectorStoreStatus.pluginName = pluginName;
+ }
+
+ try {
+ vectorStoreStatus.connected = await vectorStoreClient.getHealth();
+ } catch (error) {
+ vectorStoreStatus.error =
+ error instanceof Error ? error.message : "Unknown error";
+ }
+ }
+
browserStatus.configured =
!!serverConfig.crawler.browserWebUrl ||
!!serverConfig.crawler.browserWebSocketUrl;
@@ -572,6 +701,7 @@ export const adminAppRouter = router({
searchEngine: searchEngineStatus,
browser: browserStatus,
queue: queueStatus,
+ vectorStore: vectorStoreStatus,
};
}),
getBookmarkDebugInfo: adminBookmarksProcedure
@@ -604,6 +734,7 @@ export const adminAppRouter = router({
summarizationStatus: z
.enum(["pending", "failure", "success"])
.nullable(),
+ embeddingStatus: z.enum(["pending", "failure", "success"]).nullable(),
userId: z.string(),
linkInfo: z
.object({
@@ -702,6 +833,39 @@ export const adminAppRouter = router({
groupId: "admin",
});
}),
+ adminRegenerateBookmarkEmbedding: adminBookmarksProcedure
+ .input(z.object({ bookmarkId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ // Verify bookmark exists
+ const bookmark = await ctx.db.query.bookmarks.findFirst({
+ where: eq(bookmarks.id, input.bookmarkId),
+ });
+
+ if (!bookmark) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Bookmark not found",
+ });
+ }
+
+ await ctx.db
+ .update(bookmarks)
+ .set({ embeddingStatus: "pending" })
+ .where(eq(bookmarks.id, input.bookmarkId));
+
+ await EmbeddingsQueue.enqueue(
+ {
+ bookmarkId: input.bookmarkId,
+ type: "index",
+ force: true,
+ runTaggingOnComplete: false,
+ },
+ {
+ priority: QueuePriority.Low,
+ groupId: "admin",
+ },
+ );
+ }),
adminRetagBookmark: adminBookmarksProcedure
.input(z.object({ bookmarkId: z.string() }))
.mutation(async ({ input, ctx }) => {
diff --git a/packages/trpc/routers/bookmarks.test.ts b/packages/trpc/routers/bookmarks.test.ts
index 95c5116d..d6f6823b 100644
--- a/packages/trpc/routers/bookmarks.test.ts
+++ b/packages/trpc/routers/bookmarks.test.ts
@@ -24,6 +24,9 @@ vi.mock("@karakeep/shared-server", async (original) => {
OpenAIQueue: {
enqueue: vi.fn(),
},
+ EmbeddingsQueue: {
+ enqueue: vi.fn(),
+ },
SearchIndexingQueue: {
enqueue: vi.fn(),
},
diff --git a/packages/trpc/routers/bookmarks.ts b/packages/trpc/routers/bookmarks.ts
index b0f8d325..24f78f85 100644
--- a/packages/trpc/routers/bookmarks.ts
+++ b/packages/trpc/routers/bookmarks.ts
@@ -2,8 +2,6 @@ import { experimental_trpcMiddleware, TRPCError } from "@trpc/server";
import { and, eq, gt, inArray, like, lt, or } from "drizzle-orm";
import { z } from "zod";
-import type { ZBookmarkContent } from "@karakeep/shared/types/bookmarks";
-import type { ZBookmarkTags } from "@karakeep/shared/types/tags";
import {
assets,
AssetTypes,
@@ -18,12 +16,13 @@ import {
users,
} from "@karakeep/db/schema";
import {
+ addLogFields,
AssetPreprocessingQueue,
buildCrawlIdempotencyKey,
+ EmbeddingsQueue,
LinkCrawlerQueue,
- LowPriorityCrawlerQueue,
- addLogFields,
logEvent,
+ LowPriorityCrawlerQueue,
OpenAIQueue,
QueuePriority,
QuotaService,
@@ -31,13 +30,13 @@ import {
} from "@karakeep/shared-server";
import { SUPPORTED_BOOKMARK_ASSET_TYPES } from "@karakeep/shared/assetdb";
import serverConfig from "@karakeep/shared/config";
-import { bookmarkCreationCounter } from "../stats";
import { InferenceClientFactory } from "@karakeep/shared/inference";
import { buildSummaryPrompt } from "@karakeep/shared/prompts.server";
import { EnqueueOptions } from "@karakeep/shared/queueing";
import { getRateLimitClient } from "@karakeep/shared/ratelimiting";
import { FilterQuery, getSearchClient } from "@karakeep/shared/search";
import { parseSearchQuery } from "@karakeep/shared/searchQueryParser";
+import type { ZBookmarkContent } from "@karakeep/shared/types/bookmarks";
import {
BookmarkTypes,
DEFAULT_NUM_BOOKMARKS_PER_PAGE,
@@ -50,8 +49,10 @@ import {
zSearchBookmarksRequestSchema,
zUpdateBookmarksRequestSchema,
} from "@karakeep/shared/types/bookmarks";
+import type { ZBookmarkTags } from "@karakeep/shared/types/tags";
import { ANCHOR_TEXT_MAX_LENGTH } from "@karakeep/shared/utils/reading-progress-dom";
import { normalizeTagName } from "@karakeep/shared/utils/tag";
+import { bookmarkCreationCounter } from "../stats";
import type { AuthedContext } from "../index";
import {
@@ -407,13 +408,23 @@ export const bookmarksAppRouter = router({
break;
}
case BookmarkTypes.TEXT: {
- await OpenAIQueue.enqueue(
- {
- bookmarkId: bookmark.id,
- type: "tag",
- },
- enqueueOpts,
- );
+ if (serverConfig.embedding.enableAutoIndexing) {
+ await EmbeddingsQueue.enqueue(
+ {
+ bookmarkId: bookmark.id,
+ type: "index",
+ },
+ enqueueOpts,
+ );
+ } else {
+ await OpenAIQueue.enqueue(
+ {
+ bookmarkId: bookmark.id,
+ type: "tag",
+ },
+ enqueueOpts,
+ );
+ }
break;
}
case BookmarkTypes.ASSET: {
diff --git a/packages/trpc/stats.ts b/packages/trpc/stats.ts
index f4d4b19a..1c24ded4 100644
--- a/packages/trpc/stats.ts
+++ b/packages/trpc/stats.ts
@@ -8,6 +8,7 @@ import {
AdminMaintenanceQueue,
AssetPreprocessingQueue,
BackupQueue,
+ EmbeddingsQueue,
FeedQueue,
LinkCrawlerQueue,
LowPriorityCrawlerQueue,
@@ -39,6 +40,7 @@ const queuePendingJobsGauge = getOrCreateMetric(
{ name: "link_crawler", queue: LinkCrawlerQueue },
{ name: "low_priority_crawler", queue: LowPriorityCrawlerQueue },
{ name: "backup", queue: BackupQueue },
+ { name: "embeddings", queue: EmbeddingsQueue },
{ name: "openai", queue: OpenAIQueue },
{ name: "search_indexing", queue: SearchIndexingQueue },
{ name: "admin_maintenance", queue: AdminMaintenanceQueue },
diff --git a/packages/trpc/testUtils.ts b/packages/trpc/testUtils.ts
index 174b8822..be5b9bcb 100644
--- a/packages/trpc/testUtils.ts
+++ b/packages/trpc/testUtils.ts
@@ -111,6 +111,9 @@ export function defaultBeforeEach(seedDB = true) {
OpenAIQueue: {
enqueue: vi.fn(),
},
+ EmbeddingsQueue: {
+ enqueue: vi.fn(),
+ },
SearchIndexingQueue: {
enqueue: vi.fn(),
},