Skip to content
Open
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -270,10 +270,12 @@ If you have chatted for a while and still see the message, check that auto-captu

### Web UI

Open `http://127.0.0.1:4747` to browse the memory–prompt timeline, inspect captures, and manage the user profile. The UI has five views: **Project memories** (`/project-memories`), **User profile** (`/user-profile`), **Skill library** (`/skill-library`), **Markdown vault** (`/markdown-vault`) and **Stats** (`/stats`). Change the port with `webServerPort`, or set `webServerEnabled: false` to run without the web UI. If you bind the server beyond loopback, see [Web UI HTTP Basic Auth](#web-ui-http-basic-auth).
Open `http://127.0.0.1:4747` to browse the memory–prompt timeline, inspect captures, and manage the user profile. The UI has six views: **Project memories** (`/project-memories`), **User profile** (`/user-profile`), **Skill library** (`/skill-library`), **Markdown vault** (`/markdown-vault`), **Stats** (`/stats`) and **Model** (`/model-settings`). Change the port with `webServerPort`, or set `webServerEnabled: false` to run without the web UI. If you bind the server beyond loopback, see [Web UI HTTP Basic Auth](#web-ui-http-basic-auth).

The timeline shows each memory and prompt once. If several capture prompts refer to one memory, its current prompt is paired with it when available on the page; earlier prompts remain visible as separate entries.

The tag-migration dialog picks the provider/model used for tagging. Because tag migration has no live session, `opencodeModel: "inherit"` cannot be used there, so the dialog lists OpenCode's connected providers and models, lets you choose one, and writes `opencodeProvider` / `opencodeModel` back to the config file that supplied them (global or project). The running plugin reloads the config in place, so no restart is needed.

## Usage Examples

```typescript
Expand Down
28 changes: 26 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1680,11 +1680,15 @@ export function hasAutoCaptureProviderConfig(config: RuntimeConfig = CONFIG): bo
return getAutoCaptureProviderStatus(config).ready;
}

export function initConfig(directory: string): void {
const projectPaths = [
function projectConfigPaths(directory: string): string[] {
return [
join(directory, ".opencode", "opencode-mem.jsonc"),
join(directory, ".opencode", "opencode-mem.json"),
];
}

export function initConfig(directory: string): void {
const projectPaths = projectConfigPaths(directory);
const globalConfig = loadConfigFromPaths(CONFIG_FILES);
const projectConfig = loadConfigFromPaths(projectPaths);
assertProjectRemoteProviderConfigIsSafe(projectConfig);
Expand All @@ -1698,3 +1702,23 @@ export function initConfig(directory: string): void {
export function isConfigured(): boolean {
return true;
}

/**
* Config file that owns a model override written from the web UI: a project
* config that already sets opencodeProvider/opencodeModel wins (that is where
* the running value comes from), then the first existing global file, then a
* new global .jsonc.
*/
export function resolveModelConfigPath(projectDirectory?: string): string {
if (projectDirectory) {
for (const path of projectConfigPaths(projectDirectory)) {
if (!existsSync(path)) continue;
const config = loadConfigFromPaths([path]);
if (config.opencodeProvider || config.opencodeModel) return path;
}
}
for (const path of CONFIG_FILES) {
if (existsSync(path)) return path;
}
return CONFIG_FILES[0] ?? join(CONFIG_DIR, "opencode-mem.jsonc");
}
47 changes: 46 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { CaptureEvidenceRecorder } from "./services/capture-evidence.js";
import { performUserProfileLearning } from "./services/user-memory-learning.js";
import { userPromptManager } from "./services/user-prompt/user-prompt-manager.js";
import { startWebServer, WebServer } from "./services/web-server.js";
import type { ProviderDirectoryEntry } from "./services/api-handlers.js";
import { ensureTursoReady } from "./services/turso/ready.js";
import { tursoConnectionManager } from "./services/turso/connection-manager.js";
import { retainPluginTurso } from "./services/turso/plugin-refs.js";
Expand Down Expand Up @@ -422,8 +423,18 @@ export const OpenCodeMemPlugin: Plugin = async (ctx: PluginInput) => {
try {
const providerResult = await ctx.client.provider.list();
if (providerResult.data?.connected) {
const { setConnectedProviders } = await loadOpencodeProvider();
const { setConnectedProviders, setProviderCatalog } = await loadOpencodeProvider();
setConnectedProviders(providerResult.data.connected);
setProviderCatalog(
(providerResult.data.all ?? []).map((provider) => ({
id: provider.id,
name: provider.name ?? provider.id,
models: Object.values(provider.models ?? {}).map((model) => ({
id: model.id,
name: model.name ?? model.id,
})),
}))
);
log("opencode providers connected", {
list: providerResult.data.connected,
configured: CONFIG.opencodeProvider || "(not set)",
Expand All @@ -438,6 +449,37 @@ export const OpenCodeMemPlugin: Plugin = async (ctx: PluginInput) => {
}
};

// Fresh provider directory for the web UI: the module-level snapshot can be
// empty when the host registers providers after the last event refresh. The
// V2 host passes its native catalog, because its client only knows which
// provider ids are connected.
// Reload through this module's config instance: a dynamic import inside the
// web handlers can resolve to a second copy of config.js under bundling.
const reloadConfig = () => initConfig(directory);
const loadProviderDirectory =
(ctx as { providerDirectory?: () => Promise<ProviderDirectoryEntry[]> }).providerDirectory ??
(async (): Promise<ProviderDirectoryEntry[]> => {
const providerResult = await ctx.client.provider.list();
const data = (providerResult.data ?? {}) as {
all?: Array<{
id: string;
name?: string;
models?: Record<string, { id: string; name?: string }>;
}>;
connected?: string[];
};
const connected = data.connected ?? [];
return (data.all ?? []).map((provider) => ({
id: provider.id,
name: provider.name ?? provider.id,
connected: connected.includes(provider.id),
models: Object.values(provider.models ?? {}).map((model) => ({
id: model.id,
name: model.name ?? model.id,
})),
}));
});

// Coalesce refresh triggers into one in-flight pass plus trailing drain.
// Event handlers and ensureProviderConnected (gate miss) share this path so
// concurrent list() calls collapse; callers can await the same promise.
Expand Down Expand Up @@ -529,6 +571,9 @@ export const OpenCodeMemPlugin: Plugin = async (ctx: PluginInput) => {
enabled: CONFIG.webServerEnabled,
auth: webAuth,
apiToken: CONFIG.webServerApiToken,
projectDirectory: directory,
loadProviderDirectory,
reloadConfig,
})
.then((server) => {
webServer = server;
Expand Down
17 changes: 17 additions & 0 deletions src/services/ai/opencode-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,23 @@ export function setConnectedProviders(providers: string[]): void {
_connectedProviders = new Set(providers);
}

/** Provider directory snapshot (id, display name, models) for config UIs. */
export type ProviderCatalogEntry = {
id: string;
name: string;
models: Array<{ id: string; name: string }>;
};

let _providerCatalog: ProviderCatalogEntry[] = [];

export function setProviderCatalog(providers: ProviderCatalogEntry[]): void {
_providerCatalog = providers;
}

export function getProviderCatalog(): ProviderCatalogEntry[] {
return _providerCatalog;
}

export function isProviderConnected(providerName: string): boolean {
return _connectedProviders.has(providerName);
}
Expand Down
119 changes: 119 additions & 0 deletions src/services/api-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { formatTagsForEmbedding } from "./turso/vector-utils.js";
import { extractScopeFromContainerTag, tryExtractScopeFromContainerTag } from "./memory-scope.js";
import { log } from "./logger.js";
import { CONFIG } from "../config.js";
import { MODEL_ID_PATTERN, writeModelOverride, type ModelOverride } from "./model-config-writer.js";
import type { MemoryType } from "../types/index.js";
import { userPromptManager } from "./user-prompt/user-prompt-manager.js";
import type { UserProfileData } from "./user-profile/types.js";
Expand Down Expand Up @@ -1708,6 +1709,124 @@ export async function handleGetTagMigrationProgress(): Promise<ApiResponse<Migra
return { success: true, data: migrationProgress };
}

export interface TagMigrationModelStatus {
/** True when the migration path can run without a live session (inherit cannot). */
configured: boolean;
providerID: string | null;
modelID: string | null;
}

export interface TagMigrationModelCatalog extends TagMigrationModelStatus {
/** False when the host provider directory is not available in this process. */
available: boolean;
reason?: string;
providers: Array<{
id: string;
name: string;
connected: boolean;
models: Array<{ id: string; name: string }>;
}>;
}

export type ProviderDirectoryEntry = {
id: string;
name: string;
connected: boolean;
models: Array<{ id: string; name: string }>;
};

export async function handleGetTagMigrationModel(
loadDirectory?: () => Promise<ProviderDirectoryEntry[]>
): Promise<ApiResponse<TagMigrationModelCatalog>> {
const status: TagMigrationModelStatus = {
configured: isOpencodeTagMigrationConfigured(),
providerID: CONFIG.opencodeProvider ?? null,
modelID: CONFIG.opencodeModel ?? null,
};

try {
const { loadOpencodeProvider } = await import("./ai/opencode-provider-loader.js");
const { getProviderCatalog, isProviderConnected } = await loadOpencodeProvider();
let catalog: ProviderDirectoryEntry[] = getProviderCatalog().map((provider) => ({
id: provider.id,
name: provider.name,
connected: isProviderConnected(provider.id),
models: provider.models,
}));
// The snapshot is empty when the host has not refreshed it in this module
// instance yet; ask the host directly in that case.
if (catalog.length === 0 && loadDirectory) {
catalog = await loadDirectory();
}
if (catalog.length === 0) {
return {
success: true,
data: {
...status,
available: false,
reason: "provider directory not loaded",
providers: [],
},
};
}
return {
success: true,
data: { ...status, available: true, providers: catalog },
};
} catch (error) {
return { success: false, error: String(error) };
}
}

export async function handleSetTagMigrationModel(
body: unknown,
projectDirectory?: string,
reloadConfig?: () => void
): Promise<
ApiResponse<{
writtenTo: string;
providerID: string;
modelID: string;
requiresReload: boolean;
}>
> {
const input = (body ?? {}) as Partial<ModelOverride>;
const providerID = typeof input.providerID === "string" ? input.providerID.trim() : "";
const modelID = typeof input.modelID === "string" ? input.modelID.trim() : "";
if (!MODEL_ID_PATTERN.test(providerID) || !MODEL_ID_PATTERN.test(modelID)) {
return {
success: false,
error: "providerID and modelID must be non-empty provider/model identifiers",
};
}

try {
// Loaded lazily so config mocks in the test suite keep working.
const { initConfig, resolveModelConfigPath } = await import("../config.js");
const writtenTo = resolveModelConfigPath(projectDirectory);
writeModelOverride(writtenTo, { providerID, modelID });

// Reload so the running process picks the new values up without a restart.
// The plugin's own reload wins: under bundling the lazily imported config
// module is a second copy, and reloading it would change nothing here.
let requiresReload = true;
if (reloadConfig) {
reloadConfig();
} else if (projectDirectory) {
initConfig(projectDirectory);
}
if (reloadConfig || projectDirectory) {
requiresReload = CONFIG.opencodeProvider !== providerID || CONFIG.opencodeModel !== modelID;
}

log("tag-migration model override saved", { writtenTo, providerID, modelID, requiresReload });
return { success: true, data: { writtenTo, providerID, modelID, requiresReload } };
} catch (error) {
log("tag-migration model override failed", { error: String(error) });
return { success: false, error: String(error) };
}
}

type TagMigrationChannel = "opencode" | "external";

function isOpencodeTagMigrationConfigured(): boolean {
Expand Down
Loading