Skip to content
38 changes: 10 additions & 28 deletions src/cli/doctor-diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@
// agentmemory doctor --all # apply every available fix without prompting (CI)
// agentmemory doctor --dry-run # show what each fix WOULD do; execute nothing

import { detectLlmProviderKind, embeddingOptInHint, LLM_PROVIDER_KEYS, llmOptInHint, parseEnvContent } from "../config.js";
import {
detectLlmProviderKind,
embeddingOptInHint,
isRealProviderKey,
LLM_PROVIDER_KEYS,
llmOptInHint,
parseEnvContent,
} from "../config.js";

export type DiagnosticStatus = {
ok: boolean;
Expand Down Expand Up @@ -91,17 +98,6 @@ export type DiagnosticId = (typeof DIAGNOSTIC_IDS)[number];
// Pure helpers (no I/O) — exported for direct unit testing.
// ---------------------------------------------------------------------------

/** Common placeholder values shipped in .env.example. */
const PLACEHOLDER_VALUES = new Set([
"",
"your-key-here",
"sk-ant-...",
"sk-...",
"changeme",
"todo",
"xxx",
]);

const PROVIDER_KEY_NAMES = [
"ANTHROPIC_API_KEY",
"OPENAI_API_KEY",
Expand All @@ -115,25 +111,12 @@ export const parseEnvFile = parseEnvContent;

/** Returns the list of provider keys that look real (non-placeholder). */
export function realProviderKeys(env: Record<string, string>): string[] {
return PROVIDER_KEY_NAMES.filter((k) => {
const v = (env[k] ?? "").trim();
if (!v) return false;
if (PLACEHOLDER_VALUES.has(v.toLowerCase())) return false;
// Reject values that are just dots/placeholders like "xxxx-xxxx".
if (/^x+$/i.test(v.replace(/[-_]/g, ""))) return false;
return true;
});
return PROVIDER_KEY_NAMES.filter((k) => isRealProviderKey(env, k));
}

/** Returns the list of provider key NAMES that exist but are placeholders. */
export function placeholderProviderKeys(env: Record<string, string>): string[] {
return PROVIDER_KEY_NAMES.filter((k) => {
const v = (env[k] ?? "").trim();
if (!v) return false;
if (PLACEHOLDER_VALUES.has(v.toLowerCase())) return true;
if (/^x+$/i.test(v.replace(/[-_]/g, ""))) return true;
return false;
});
return PROVIDER_KEY_NAMES.filter((k) => (env[k] ?? "").trim() !== "" && !isRealProviderKey(env, k));
}

/**
Expand Down Expand Up @@ -210,7 +193,6 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] {
for (const [k, v] of Object.entries(effects.processEnv())) {
if (v !== undefined) env[k] = v;
}
for (const k of placeholderProviderKeys(env)) delete env[k];
if (detectLlmProviderKind(env) !== "llm") {
const hint = llmOptInHint(env);
if (hint) return { ok: false, detail: hint };
Expand Down
36 changes: 33 additions & 3 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,31 @@ function hasRealValue(v: string | undefined): v is string {
return typeof v === "string" && v.trim().length > 0;
}

const PLACEHOLDER_KEY_VALUES = new Set(["your-key-here", "changeme", "todo"]);

function hasRealKey(value: string | undefined): boolean {
const v = value?.trim().toLowerCase();
return (
!!v &&
!v.endsWith("...") &&
!PLACEHOLDER_KEY_VALUES.has(v) &&
!/^x+$/.test(v.replace(/[-_]/g, ""))
);
}

function hasRealOpenAIKey(env: Record<string, string | undefined>): boolean {
return /^http:\/\//i.test(env["OPENAI_BASE_URL"]?.trim() ?? "")
? !!env["OPENAI_API_KEY"]?.trim()
: hasRealKey(env["OPENAI_API_KEY"]);
}

export function isRealProviderKey(
env: Record<string, string | undefined>,
key: string,
): boolean {
return key === "OPENAI_API_KEY" ? hasRealOpenAIKey(env) : hasRealKey(env[key]);
}

// Hydrate ~/.agentmemory/.env into process.env at boot. loadEnvFile() is
// otherwise only consumed via getMergedEnv(), which the many modules that
// read raw process.env["X"] never call — so .env-only values were silently
Expand Down Expand Up @@ -152,7 +177,7 @@ function selectedLlmProviderValue(env: Record<string, string | undefined>): stri
}

function llmProviderHasKey(env: Record<string, string | undefined>, name: LlmProviderName): boolean {
return LLM_PROVIDER_KEYS[name].some((k) => hasRealValue(env[k]));
return LLM_PROVIDER_KEYS[name].some((k) => isRealProviderKey(env, k));
}

export function envFileLabel(path: string = ENV_FILE): string {
Expand All @@ -174,7 +199,7 @@ export function llmOptInHint(env: Record<string, string | undefined> = getMerged
if (env["AGENTMEMORY_ALLOW_AGENT_SDK"] === "true") return null;
const withKey = LLM_PROVIDER_NAMES.filter((name) => llmProviderHasKey(env, name));
if (withKey.length === 0) return null;
const keys = withKey.flatMap((name) => LLM_PROVIDER_KEYS[name].filter((k) => hasRealValue(env[k])));
const keys = withKey.flatMap((name) => LLM_PROVIDER_KEYS[name].filter((k) => isRealProviderKey(env, k)));
return `Found ${keys.join(", ")}, but agentmemory sends nothing to an LLM provider until you choose one for it. To turn on LLM summaries and compression, add AGENTMEMORY_LLM_PROVIDER=${withKey[0]} to ${envFileLabel()}.`;
}

Expand Down Expand Up @@ -220,7 +245,7 @@ function detectProvider(env: Record<string, string>): ProviderConfig {
baseURL: env["ANTHROPIC_BASE_URL"],
};
case "gemini":
if (!hasRealValue(env["GEMINI_API_KEY"])) {
if (!hasRealKey(env["GEMINI_API_KEY"])) {
process.stderr.write(
"[agentmemory] GOOGLE_API_KEY detected — treating as GEMINI_API_KEY. " +
"Set GEMINI_API_KEY in ~/.agentmemory/.env to silence this warning.\n",
Expand Down Expand Up @@ -317,6 +342,11 @@ export function getEnvVar(key: string): string | undefined {
return getMergedEnv()[key];
}

export function getProviderKey(key: string): string | undefined {
const env = getMergedEnv();
return isRealProviderKey(env, key) ? env[key] : undefined;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

export function isSessionSweepEnabled(): boolean {
return getMergedEnv()["AGENTMEMORY_SESSION_SWEEP_ENABLED"] !== "false";
}
Expand Down
8 changes: 4 additions & 4 deletions src/providers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ import { OpenAIProvider } from "./openai.js";
import { OpenRouterProvider } from "./openrouter.js";
import { ResilientProvider } from "./resilient.js";
import { FallbackChainProvider } from "./fallback-chain.js";
import { getEnvVar } from "../config.js";
import { getEnvVar, getProviderKey } from "../config.js";

export { createEmbeddingProvider, createImageEmbeddingProvider } from "./embedding/index.js";

function requireEnvVar(key: string): string {
const value = getEnvVar(key);
const value = getProviderKey(key);
if (!value) {
throw new Error(
`Missing required environment variable: ${key}. Set it in ~/.agentmemory/.env or as an environment variable.`,
Expand Down Expand Up @@ -95,7 +95,7 @@ function createBaseProvider(config: ProviderConfig): MemoryProvider {
);
case "gemini": {
const geminiKey =
getEnvVar("GEMINI_API_KEY") || getEnvVar("GOOGLE_API_KEY");
getProviderKey("GEMINI_API_KEY") || getProviderKey("GOOGLE_API_KEY");
if (!geminiKey) {
throw new Error(
"GEMINI_API_KEY (or GOOGLE_API_KEY) is required for the gemini provider",
Expand All @@ -116,7 +116,7 @@ function createBaseProvider(config: ProviderConfig): MemoryProvider {
"https://openrouter.ai/api/v1/chat/completions",
);
case "openai": {
const openaiKey = getEnvVar("OPENAI_API_KEY");
const openaiKey = getProviderKey("OPENAI_API_KEY");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (!openaiKey) {
throw new Error(
"OPENAI_API_KEY is required for the openai provider",
Expand Down
17 changes: 16 additions & 1 deletion test/cli-doctor-fixes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ describe("doctor v2 diagnostic catalog", () => {
).toEqual({ ok: true, detail: "agent-sdk fallback, no API key" });
});

it("treats a placeholder exported in the environment as missing, unlike the daemon", async () => {
it("treats a placeholder exported in the environment as missing, like the daemon", async () => {
expect(
(
await statusFor(
Expand All @@ -276,6 +276,21 @@ describe("doctor v2 diagnostic catalog", () => {
).ok,
).toBe(false);
});

it("names a placeholder OpenAI key behind a plain-http base URL, like the daemon", async () => {
expect(
await statusFor(
{ AGENTMEMORY_LLM_PROVIDER: "openai", OPENAI_API_KEY: "xxx" },
{ OPENAI_BASE_URL: "http://localhost:11434/v1" },
),
).toEqual({ ok: true, detail: "found: OPENAI_API_KEY" });
expect(
await statusFor(
{ AGENTMEMORY_LLM_PROVIDER: "openai", OPENAI_API_KEY: "xxx", OPENAI_BASE_URL: "http://localhost:11434/v1" },
{},
),
).toEqual({ ok: true, detail: "found: OPENAI_API_KEY" });
});
});

it("engine-version-mismatch fails when iii reports the wrong version", async () => {
Expand Down
Loading
Loading