Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ graph TD
EM -->|local| HF[HuggingFace Transformers<br>Xenova/nomic-embed-text-v1]
EM -->|remote| API[OpenAI-compatible API]

WS --> AH[API Handlers<br>src/services/api-handlers.ts]
WS --> AH[API Handlers<br>src/services/handlers/]
AH --> MC
```

Expand Down Expand Up @@ -135,7 +135,7 @@ src/
│ ├── cleanup-service.ts # Old memory and transcript cleanup
│ ├── migration-service.ts # V1→V2 data migration
│ ├── web-server.ts # HTTP server for web UI + REST API
│ ├── api-handlers.ts # REST API endpoint handlers
│ ├── handlers/ # REST API endpoint handlers
│ ├── platform-server.ts # Platform-agnostic HTTP server abstraction
│ ├── logger.ts # Structured logging with level control
│ ├── privacy.ts # Private content stripping (API keys, tokens)
Expand Down
4 changes: 4 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- **Prepared-statement caching is shared, and plugin.ts re-exports OpenCodeMemPlugin directly.**
- **better-sqlite3 is an optional dependency — installs no longer hard-fail on platforms where its native build breaks (bun:sqlite / node:sqlite users unaffected).**
- **Dashboard route handlers are imported directly — the api-handlers.ts re-export layer is gone.**
- **Config types are now derived from the zod schema (z.infer) instead of a hand-maintained duplicate interface.**
- **Startup no longer blocks on embedding warmup or score recalculation** — the plugin loads immediately and warms up in the background.

### Fixed
Expand Down
6 changes: 3 additions & 3 deletions docs/GETTING-STARTED.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,11 @@ After the initial download, subsequent runs are near-instant. Alternatively, use
| `%USERPROFILE%\.config\opencode\opencode-mem0.jsonc` | Global config |
| `%USERPROFILE%\.opencode-mem0\data` | SQLite databases, embedding model cache |

### better-sqlite3 install fails (node-gyp / MSBuild error)
### better-sqlite3 native build fails (node-gyp / MSBuild warning)

**Symptom:** `npm install opencode-mem0` fails with `node-gyp` or `MSBuild` errors (Windows ARM64 or a very new Node version without prebuilt binaries).
**Symptom:** `npm install` warns that optional `better-sqlite3` failed to build (`node-gyp` / `MSBuild`). The install itself succeeds.

**Solution:** Install [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) with the **"Desktop development with C++"** workload + [Python 3](https://www.python.org/downloads/), then retry. One-time setup.
**Solution:** Ignore it on Bun or Node >= 22.5 — `bun:sqlite` / `node:sqlite` cover those runtimes. On Node < 22.5, install [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) with the **"Desktop development with C++"** workload + [Python 3](https://www.python.org/downloads/) and retry so the native fallback can load.

### Auto-capture skips with "LLM provider not configured"

Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,14 @@
"@opencode-ai/plugin": "^1.14.31",
"@opencode-ai/sdk": "^1.14.31",
"ai": "^7.0.4",
"better-sqlite3": "^13.0.2",
"franc-min": "^6.2.0",
"jsonc-parser": "^3.3.1",
"usearch": "^2.25.1",
"zod": "^4.4.1"
},
"optionalDependencies": {
"better-sqlite3": "^13.0.2"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.13",
"@types/bun": "^1.3.13",
Expand Down
109 changes: 2 additions & 107 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,113 +17,6 @@ export const CONFIG_FILES = [

export type VectorBackendConfig = "usearch-first" | "usearch" | "exact-scan";

interface OpenCodeMemConfig {
storagePath?: string;
userEmailOverride?: string;
userNameOverride?: string;
memory?: {
defaultScope?: "project" | "all-projects";
};
embeddingModel?: string;
embeddingDimensions?: number;
embeddingApiUrl?: string;
embeddingApiKey?: string;
similarityThreshold?: number;
maxMemories?: number;
injectProfile?: boolean;
containerTagPrefix?: string;
autoCaptureEnabled?: boolean;
promptTrackingEnabled?: boolean;
profileLearningEnabled?: boolean;
autoCaptureMaxIterations?: number;
autoCaptureMaxRetries?: number;
autoCaptureIterationTimeout?: number;
autoCaptureLanguage?: string;
memoryProvider?: AIProviderType;
memoryModel?: string;
memoryApiUrl?: string;
memoryApiKey?: string;
memoryTemperature?: number | false;
memoryExtraParams?: Record<string, unknown>;
opencodeProvider?: string;
opencodeModel?: string;
vectorBackend?: VectorBackendConfig;
aiSessionRetentionDays?: number;
webServerEnabled?: boolean;
webServerPort?: number;
webServerHost?: string;
webServerApiKey?: string;
maxVectorsPerShard?: number;
autoCleanupEnabled?: boolean;
autoCleanupRetentionDays?: number;
deduplicationEnabled?: boolean;
deduplicationSimilarityThreshold?: number;
deduplicationIngestEnabled?: boolean;
userProfileAnalysisInterval?: number;
userProfileMaxBatchesPerIdle?: number;
userProfileMaxPreferences?: number;
userProfileMaxPatterns?: number;
userProfileMaxWorkflows?: number;
userProfileChangelogRetentionCount?: number;
promptRetentionDays?: number | false;
showAutoCaptureToasts?: boolean;
showUserProfileToasts?: boolean;
showErrorToasts?: boolean;
transcriptStorage?: {
enabled?: boolean;
maxAgeDays?: number;
};
memoryScoring?: {
enabled?: boolean;
recalculationIntervalMinutes?: number;
recalculationBatchSize?: number;
recencyHalfLifeDays?: number;
utilityHalfLifeDays?: number;
};
memoryLifecycle?: {
stmDecayDays?: number;
ltmDecayDays?: number;
promotionThreshold?: number;
archiveThreshold?: number;
archiveAfterDays?: number;
checkIntervalMinutes?: number;
decayBatchSize?: number;
};
compaction?: {
enabled?: boolean;
memoryLimit?: number;
};
chatMessage?: {
enabled?: boolean;
maxMemories?: number;
excludeCurrentSession?: boolean;
maxAgeDays?: number;
injectOn?: "first" | "always";
mode?: "relevant" | "fast";
};
retrieval?: {
maxResults?: number;
diversityThreshold?: number;
contextBoost?: number;
};
injection?: {
tokenBudget?: number;
format?: "plain" | "xml" | "yaml";
relevanceThreshold?: number;
};
contextualDecay?: {
enabled?: boolean;
baseDecayRate?: number;
strengthBoostFactor?: number;
accessBoostFactor?: number;
minDecayRate?: number;
maxDecayRate?: number;
};
logLevel?: "debug" | "info" | "warn" | "error";
warmupTimeoutMs?: number;
rateLimitEnabled?: boolean;
}

export const OpenCodeMemConfigSchema = z.object({
storagePath: z.string().optional(),
userEmailOverride: z.string().optional(),
Expand Down Expand Up @@ -251,6 +144,8 @@ export const OpenCodeMemConfigSchema = z.object({
rateLimitEnabled: z.boolean().optional(),
});

export type OpenCodeMemConfig = z.infer<typeof OpenCodeMemConfigSchema>;

const DEFAULTS: Partial<OpenCodeMemConfig> = {
storagePath: join(DATA_DIR, "data"),
embeddingModel: "Xenova/nomic-embed-text-v1",
Expand Down
9 changes: 1 addition & 8 deletions src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
import type { PluginModule } from "@opencode-ai/plugin";
import pkg from "../package.json" with { type: "json" };

let OpenCodeMemPlugin: (typeof import("./index.js"))["OpenCodeMemPlugin"]; // skipcq JS-E1009
try {
({ OpenCodeMemPlugin } = await import("./index.js"));
} catch (e) {
console.error("Failed to load OpenCodeMemPlugin:", e); // skipcq JS-0002
throw e;
}
import { OpenCodeMemPlugin } from "./index.js";

export const id = pkg.name;
export { OpenCodeMemPlugin };
Expand Down
124 changes: 0 additions & 124 deletions src/services/api-handlers.ts

This file was deleted.

41 changes: 41 additions & 0 deletions src/services/handlers/admin.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { join } from "node:path";
import { embeddingService } from "../embedding.js";
import { shardManager, getAllShards } from "../sqlite/shard-manager.js";
import { vectorSearch } from "../sqlite/vector-search.js";
Expand Down Expand Up @@ -367,3 +368,43 @@ export async function handleRunTagMigrationBatch(
return { success: false, error: "Internal error in handleRunTagMigrationBatch" };
}
}

export function handleEmbeddingCacheStats(): ApiResponse<{
size: number;
maxSize: number;
hits: number;
misses: number;
rate: number;
}> {
try {
const stats = embeddingService.getCacheStats();
return { success: true, data: stats };
} catch (error) {
log("handleEmbeddingCacheStats: error", { error: String(error) });
return { success: false, error: "Internal error in handleEmbeddingCacheStats" };
}
}

export function handleApiStatus(): ApiResponse<{
mode: "full" | "text-only";
warmedUp: boolean;
ready: boolean;
}> {
try {
const mode = embeddingService.embeddingAvailable ? "full" : "text-only";
const warmedUp = embeddingService.isWarmedUp;
let ready = false;
try {
const metadataPath = join(CONFIG.storagePath, "metadata.db");
const db = connectionManager.getConnection(metadataPath);
const row = db.prepare("SELECT COUNT(*) as count FROM shards").get() as { count: number };
ready = row.count > 0;
} catch {
ready = false;
}
return { success: true, data: { mode, warmedUp, ready } };
} catch (error) {
log("handleApiStatus: error", { error: String(error) });
return { success: false, error: "Internal error in handleApiStatus" };
}
}
Loading
Loading