Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(embeddings): add `ok embeddings set-url` CLI + inline endpoint URL validation (#2593)

mike-inkeep2fd2446df2ab
diff --git a/.changeset/embeddings-endpoint-cli-and-validation.md b/.changeset/embeddings-endpoint-cli-and-validation.md
new file mode 100644
index 000000000..9f4544357
--- /dev/null
+++ b/.changeset/embeddings-endpoint-cli-and-validation.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Add `ok embeddings set-url <url>` / `ok embeddings clear-url` to configure the semantic-search embeddings endpoint from the CLI (for headless / CI users), and validate the endpoint URL inline in **Settings → This project → Search**. Both the CLI and the Settings field now reject a guaranteed-to-fail endpoint at entry — a malformed URL, or a plaintext `http://` host other than localhost — using the same rule the server enforces before it will send the API key, instead of letting a bad value degrade silently to lexical search later.
diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdx
index 0103e050c..0596afece 100644
--- a/docs/content/reference/configuration.mdx
+++ b/docs/content/reference/configuration.mdx
@@ -100,7 +100,7 @@ To turn it on (per machine):
1. Store the provider key in `~/.ok/secrets.yml` (0600, this machine only): `ok embeddings set-key` (reads the key from a hidden prompt or stdin). Check it with `ok embeddings status`; remove it with `ok embeddings clear-key`.
2. Enable it for the project: `ok embeddings enable`, or the **Settings → This project → Search** toggle. Either sets `search.semantic.enabled: true` in project-local config (`<project>/.ok/local/config.yml`), picked up live by a running server; `ok embeddings disable` turns it off.
-3. (Optional) point at a non-OpenAI provider via `search.semantic.baseUrl` / `model` / `dimensions`.
+3. (Optional) point at a non-OpenAI provider (Azure / self-hosted): `ok embeddings set-url <url>` — or set `search.semantic.baseUrl` in project-local config; `ok embeddings clear-url` resets to the default. Tune `model` / `dimensions` in config.
The first semantic search kicks off a background embed of the corpus (cents for a whole vault with `text-embedding-3-small`); vectors are cached incrementally under `.ok/local/` and only changed docs re-embed. If the key is missing, the provider errors, or you're offline, search silently degrades to lexical — it never blocks or errors. Each MCP `search` response reports embedding coverage so an agent knows when vectors are still filling in.
diff --git a/packages/app/src/components/settings/SearchSection.dom.test.tsx b/packages/app/src/components/settings/SearchSection.dom.test.tsx
index 06e2b60bd..f217b26da 100644
--- a/packages/app/src/components/settings/SearchSection.dom.test.tsx
+++ b/packages/app/src/components/settings/SearchSection.dom.test.tsx
@@ -406,4 +406,104 @@ describe('SearchSection', () => {
expect(calls).toEqual([{ search: { semantic: { baseUrl: DEFAULT_EMBEDDINGS_BASE_URL } } }]);
});
+
+ test('a malformed URL is not flagged mid-typing, but errors on commit and blocks the write', async () => {
+ const user = userEvent.setup();
+ const { binding, calls } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithSemantic({ enabled: false });
+
+ render(<SearchSection />);
+
+ const input = screen.getByTestId('settings-search-base-url');
+ await user.clear(input);
+ await user.type(input, 'not-a-url');
+
+ // "Reward early": no error while the user is still typing (untouched).
+ expect(screen.queryByTestId('settings-search-base-url-error')).toBeNull();
+
+ await user.tab(); // blur commit → validate
+
+ expect(screen.getByTestId('settings-search-base-url-error')).toBeDefined();
+ expect(input.getAttribute('aria-invalid')).toBe('true');
+ expect(calls).toEqual([]); // guaranteed-to-fail endpoint is not persisted
+ });
+
+ test('committing an invalid URL via Enter also errors and blocks the write', async () => {
+ const user = userEvent.setup();
+ const { binding, calls } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithSemantic({ enabled: false });
+
+ render(<SearchSection />);
+
+ const input = screen.getByTestId('settings-search-base-url');
+ await user.clear(input);
+ // Enter is the distinct commit path (preventDefault + commitBaseUrlInput).
+ await user.type(input, 'not-a-url{Enter}');
+
+ expect(screen.getByTestId('settings-search-base-url-error')).toBeDefined();
+ expect(input.getAttribute('aria-invalid')).toBe('true');
+ expect(calls).toEqual([]);
+ });
+
+ test('a plaintext non-loopback endpoint errors on commit and blocks the write', async () => {
+ const user = userEvent.setup();
+ const { binding, calls } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithSemantic({ enabled: false });
+
+ render(<SearchSection />);
+
+ const input = screen.getByTestId('settings-search-base-url');
+ await user.clear(input);
+ await user.type(input, 'http://azure.example.com/v1');
+ await user.tab();
+
+ expect(screen.getByTestId('settings-search-base-url-error')).toBeDefined();
+ expect(calls).toEqual([]);
+ });
+
+ test('an http loopback endpoint is accepted (no error) and written', async () => {
+ const user = userEvent.setup();
+ const { binding, calls } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithSemantic({ enabled: false });
+
+ render(<SearchSection />);
+
+ const input = screen.getByTestId('settings-search-base-url');
+ await user.clear(input);
+ await user.type(input, 'http://localhost:11434/v1');
+ await user.tab();
+
+ expect(screen.queryByTestId('settings-search-base-url-error')).toBeNull();
+ expect(calls).toEqual([{ search: { semantic: { baseUrl: 'http://localhost:11434/v1' } } }]);
+ });
+
+ test('after a failed commit, fixing the value clears the error live and writes on re-commit', async () => {
+ const user = userEvent.setup();
+ const { binding, calls } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithSemantic({ enabled: false });
+
+ render(<SearchSection />);
+
+ const input = screen.getByTestId('settings-search-base-url');
+ await user.clear(input);
+ await user.type(input, 'nope');
+ await user.tab(); // commit → error shows, field is now "touched"
+ expect(screen.getByTestId('settings-search-base-url-error')).toBeDefined();
+
+ // "Punish late": once touched, a fix clears the error live (no re-blur needed).
+ await user.clear(input);
+ await user.type(input, 'https://azure.example.com/openai/v1');
+ expect(screen.queryByTestId('settings-search-base-url-error')).toBeNull();
+ expect(input.getAttribute('aria-invalid')).toBe('false');
+
+ await user.tab();
+ expect(calls).toEqual([
+ { search: { semantic: { baseUrl: 'https://azure.example.com/openai/v1' } } },
+ ]);
+ });
});
diff --git a/packages/app/src/components/settings/SearchSection.tsx b/packages/app/src/components/settings/SearchSection.tsx
index 1ccf49abb..d57654164 100644
--- a/packages/app/src/components/settings/SearchSection.tsx
+++ b/packages/app/src/components/settings/SearchSection.tsx
@@ -18,7 +18,11 @@
* Account (stored in `~/.ok/secrets.yml`); this section only points there when a
* key is missing.
*/
-import { DEFAULT_EMBEDDINGS_BASE_URL, humanFormat } from '@inkeep/open-knowledge-core';
+import {
+ checkEmbeddingsBaseUrl,
+ DEFAULT_EMBEDDINGS_BASE_URL,
+ humanFormat,
+} from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
@@ -49,6 +53,10 @@ export function SearchSection() {
const { projectLocalConfig, projectLocalSynced, projectLocalBinding } = useConfigContext();
const { status, refresh } = useSemanticSearchStatus();
const [confirmOpen, setConfirmOpen] = useState(false);
+ const [baseUrlError, setBaseUrlError] = useState<string | null>(null);
+ // Don't nag mid-typing: surface the endpoint error only after the field has
+ // been committed once (blur/Enter), then keep it live so a fix clears it.
+ const [baseUrlTouched, setBaseUrlTouched] = useState(false);
const settleTimersRef = useRef<Array<ReturnType<typeof setTimeout>>>([]);
useEffect(
@@ -61,6 +69,17 @@ export function SearchSection() {
const configuredBaseUrl =
projectLocalConfig?.search?.semantic?.baseUrl ?? DEFAULT_EMBEDDINGS_BASE_URL;
+ // When the persisted endpoint changes externally (e.g. `ok embeddings set-url`
+ // in a terminal while Settings is open), the `key`-based Input remounts with a
+ // fresh value — reset the touched gate + error so it starts clean too. This is
+ // the React "adjust state during render on a changed value" pattern (no effect).
+ const [prevConfiguredBaseUrl, setPrevConfiguredBaseUrl] = useState(configuredBaseUrl);
+ if (configuredBaseUrl !== prevConfiguredBaseUrl) {
+ setPrevConfiguredBaseUrl(configuredBaseUrl);
+ setBaseUrlTouched(false);
+ setBaseUrlError(null);
+ }
+
const enabled = projectLocalConfig?.search?.semantic?.enabled ?? false;
const bindingReady = projectLocalSynced && projectLocalBinding !== null;
@@ -126,7 +145,30 @@ export function SearchSection() {
if (write(true)) setConfirmOpen(false);
}
+ // Mirror the server's pre-flight guard (`checkEmbeddingsBaseUrl`) so a
+ // guaranteed-to-fail endpoint is flagged at entry instead of surfacing later
+ // as a provider-rejected status. Empty resets to the default (always valid).
+ function baseUrlProblemMessage(value: string): string | null {
+ const trimmed = value.trim();
+ if (!trimmed) return null;
+ const problem = checkEmbeddingsBaseUrl(trimmed);
+ if (problem === null) return null;
+ return problem === 'invalid-url'
+ ? t`Enter a valid URL (for example https://api.openai.com/v1).`
+ : t`Use an https:// URL — http:// is only allowed for localhost.`;
+ }
+
+ // Live-validate only after the field has been committed once (touched), so the
+ // error doesn't flash while the user is still typing a URL.
+ function onBaseUrlChange(value: string): void {
+ if (baseUrlTouched) setBaseUrlError(baseUrlProblemMessage(value));
+ }
+
function commitBaseUrlInput(input: HTMLInputElement): void {
+ setBaseUrlTouched(true);
+ const message = baseUrlProblemMessage(input.value);
+ setBaseUrlError(message);
+ if (message !== null) return; // invalid — leave the error shown, don't persist
const normalized = normalizeBaseUrl(input.value);
if (writeBaseUrl(input.value)) input.value = normalized;
}
@@ -218,6 +260,7 @@ export function SearchSection() {
key={configuredBaseUrl}
id="settings-search-base-url"
defaultValue={configuredBaseUrl}
+ onChange={(e) => onBaseUrlChange(e.currentTarget.value)}
onBlur={(e) => commitBaseUrlInput(e.currentTarget)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
@@ -229,11 +272,25 @@ export function SearchSection() {
disabled={!bindingReady}
spellCheck={false}
autoComplete="off"
+ aria-invalid={baseUrlError !== null}
+ aria-describedby="settings-search-base-url-message"
data-testid="settings-search-base-url"
className="h-8 font-mono text-sm"
/>
- <p className="text-muted-foreground text-1sm" data-testid="settings-search-base-url-help">
- <Trans>Clear the field to reset back to the default OpenAI endpoint.</Trans>
+ {/* One persistent live region (not a conditionally-mounted node) so a
+ screen reader reliably announces the error when it appears — swapping
+ in a fresh aria-live element WITH content is often missed. */}
+ <p
+ id="settings-search-base-url-message"
+ aria-live="polite"
+ className={baseUrlError ? 'text-1sm text-destructive' : 'text-muted-foreground text-1sm'}
+ data-testid={
+ baseUrlError ? 'settings-search-base-url-error' : 'settings-search-base-url-help'
+ }
+ >
+ {baseUrlError ?? (
+ <Trans>Clear the field to reset back to the default OpenAI endpoint.</Trans>
+ )}
</p>
</div>
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index bb07546d8..a4727578a 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -123,6 +123,7 @@
"2fkdnR": ["Nothing to undo on this file"],
"2hYmUH": ["[email protected]"],
"2hpdRq": ["Hide panel (", ["panelShortcutLabel"], ")"],
+ "2j1kfc": ["Enter a valid URL (for example https://api.openai.com/v1)."],
"2n3oDU": [
"Project-level pages ordered by inbound link count, up to ",
["FULLSCREEN_HUB_LIMIT"],
@@ -808,6 +809,7 @@
"JL3si7": ["Updating"],
"JLUTgi": ["No tags yet — author `#tagname` in any doc to populate the index."],
"JLzQi_": ["Close ", ["accessibleLabel"]],
+ "JM_aq-": ["Use an https:// URL — http:// is only allowed for localhost."],
"JOcPqH": ["Bring a remote repository onto this machine."],
"JWsZlx": ["Open a project to edit."],
"JZ8cO6": ["Light, dark, or follow the OS."],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 3a36351c7..77a7b7f06 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -2803,6 +2803,10 @@ msgstr "Enter a title for this template."
msgid "Enter a valid branch name (no spaces, no leading dot, no \"..\")."
msgstr "Enter a valid branch name (no spaces, no leading dot, no \"..\")."
+#: src/components/settings/SearchSection.tsx
+msgid "Enter a valid URL (for example https://api.openai.com/v1)."
+msgstr "Enter a valid URL (for example https://api.openai.com/v1)."
+
#: src/components/settings/AiToolsSection.tsx
#: src/components/settings/ProjectAiToolsSection.tsx
msgid "Entry"
@@ -7689,6 +7693,10 @@ msgstr "Use a folder you already have."
msgid "Use a starter pack"
msgstr "Use a starter pack"
+#: src/components/settings/SearchSection.tsx
+msgid "Use an https:// URL — http:// is only allowed for localhost."
+msgstr "Use an https:// URL — http:// is only allowed for localhost."
+
#: src/components/ShareButton.tsx
msgid "Use Cmd/Ctrl+C to copy the link below, or open OK in the desktop app."
msgstr "Use Cmd/Ctrl+C to copy the link below, or open OK in the desktop app."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index db73d0583..295bfc4f9 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -123,6 +123,7 @@
"2fkdnR": ["Ńōţĥĩńĝ ţō ũńďō ōń ţĥĩś ƒĩĺē"],
"2hYmUH": ["ḿŷ@ēḿàĩĺ.ćōḿ"],
"2hpdRq": ["Ĥĩďē ƥàńēĺ (", ["panelShortcutLabel"], ")"],
+ "2j1kfc": ["Ēńţēŕ à vàĺĩď ŨŔĹ (ƒōŕ ēxàḿƥĺē ĥţţƥś://àƥĩ.ōƥēńàĩ.ćōḿ/v1)."],
"2n3oDU": [
"ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ōŕďēŕēď ƀŷ ĩńƀōũńď ĺĩńķ ćōũńţ, ũƥ ţō ",
["FULLSCREEN_HUB_LIMIT"],
@@ -808,6 +809,7 @@
"JL3si7": ["Ũƥďàţĩńĝ"],
"JLUTgi": ["Ńō ţàĝś ŷēţ — àũţĥōŕ `#ţàĝńàḿē` ĩń àńŷ ďōć ţō ƥōƥũĺàţē ţĥē ĩńďēx."],
"JLzQi_": ["Ćĺōśē ", ["accessibleLabel"]],
+ "JM_aq-": ["Ũśē àń ĥţţƥś:// ŨŔĹ — ĥţţƥ:// ĩś ōńĺŷ àĺĺōŵēď ƒōŕ ĺōćàĺĥōśţ."],
"JOcPqH": ["ßŕĩńĝ à ŕēḿōţē ŕēƥōśĩţōŕŷ ōńţō ţĥĩś ḿàćĥĩńē."],
"JWsZlx": ["Ōƥēń à ƥŕōĴēćţ ţō ēďĩţ."],
"JZ8cO6": ["Ĺĩĝĥţ, ďàŕķ, ōŕ ƒōĺĺōŵ ţĥē ŌŚ."],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 5282cb474..727ddc036 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -2798,6 +2798,10 @@ msgstr ""
msgid "Enter a valid branch name (no spaces, no leading dot, no \"..\")."
msgstr ""
+#: src/components/settings/SearchSection.tsx
+msgid "Enter a valid URL (for example https://api.openai.com/v1)."
+msgstr ""
+
#: src/components/settings/AiToolsSection.tsx
#: src/components/settings/ProjectAiToolsSection.tsx
msgid "Entry"
@@ -7684,6 +7688,10 @@ msgstr ""
msgid "Use a starter pack"
msgstr ""
+#: src/components/settings/SearchSection.tsx
+msgid "Use an https:// URL — http:// is only allowed for localhost."
+msgstr ""
+
#: src/components/ShareButton.tsx
msgid "Use Cmd/Ctrl+C to copy the link below, or open OK in the desktop app."
msgstr ""
diff --git a/packages/cli/src/commands/embeddings/index.test.ts b/packages/cli/src/commands/embeddings/index.test.ts
new file mode 100644
index 000000000..d9d5d070a
--- /dev/null
+++ b/packages/cli/src/commands/embeddings/index.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { DEFAULT_EMBEDDINGS_BASE_URL } from '@inkeep/open-knowledge-core';
+import { embeddingsCommand } from './index.ts';
+
+function readLocalConfig(dir: string): string {
+ try {
+ return readFileSync(join(dir, '.ok', 'local', 'config.yml'), 'utf-8');
+ } catch {
+ return '';
+ }
+}
+
+describe('ok embeddings set-url / clear-url', () => {
+ let dir: string;
+ let stderr: string;
+ let restoreWrite: () => void;
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'ok-embeddings-url-'));
+ stderr = '';
+ const orig = process.stderr.write.bind(process.stderr);
+ process.stderr.write = ((chunk: string | Uint8Array) => {
+ stderr += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf-8');
+ return true;
+ }) as typeof process.stderr.write;
+ restoreWrite = () => {
+ process.stderr.write = orig;
+ };
+ // Command actions set `process.exitCode = 1` on failure and leave it on
+ // success. Bun's `process.exitCode = undefined` does NOT clear a prior value,
+ // so reset to 0 ("success") before each test — and again after, so a reject
+ // test's exit code never leaks to the `bun test` process.
+ process.exitCode = 0;
+ });
+
+ afterEach(() => {
+ restoreWrite();
+ process.exitCode = 0;
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ // Build a fresh command each run so commander carries no state between calls.
+ function run(...args: string[]): Promise<unknown> {
+ return embeddingsCommand().parseAsync(args, { from: 'user' });
+ }
+
+ test('set-url writes a valid https endpoint to project-local config', async () => {
+ await run('set-url', 'https://azure.example.com/openai/v1', '--cwd', dir);
+ expect(process.exitCode).toBe(0);
+ expect(readLocalConfig(dir)).toContain('https://azure.example.com/openai/v1');
+ });
+
+ test('set-url trims surrounding whitespace before writing', async () => {
+ await run('set-url', ' https://azure.example.com/openai/v1 ', '--cwd', dir);
+ const cfg = readLocalConfig(dir);
+ expect(cfg).toContain('https://azure.example.com/openai/v1');
+ expect(cfg).not.toContain(' https://');
+ });
+
+ test('set-url rejects a malformed URL without writing (exit 1)', async () => {
+ await run('set-url', 'not-a-url', '--cwd', dir);
+ expect(process.exitCode).toBe(1);
+ expect(stderr).toContain('Not a valid URL');
+ expect(readLocalConfig(dir)).toBe('');
+ });
+
+ test('set-url rejects a plaintext non-loopback endpoint without writing (exit 1)', async () => {
+ await run('set-url', 'http://azure.example.com/v1', '--cwd', dir);
+ expect(process.exitCode).toBe(1);
+ expect(stderr).toContain('insecure endpoint');
+ expect(readLocalConfig(dir)).toBe('');
+ });
+
+ test('set-url allows an http loopback endpoint (local gateway)', async () => {
+ await run('set-url', 'http://localhost:11434/v1', '--cwd', dir);
+ expect(process.exitCode).toBe(0);
+ expect(readLocalConfig(dir)).toContain('http://localhost:11434/v1');
+ });
+
+ test('clear-url resets the endpoint to the default', async () => {
+ await run('set-url', 'https://azure.example.com/openai/v1', '--cwd', dir);
+ await run('clear-url', '--cwd', dir);
+ expect(process.exitCode).toBe(0);
+ expect(readLocalConfig(dir)).toContain(DEFAULT_EMBEDDINGS_BASE_URL);
+ });
+});
diff --git a/packages/cli/src/commands/embeddings/index.ts b/packages/cli/src/commands/embeddings/index.ts
index e1e5f98a5..5af183381 100644
--- a/packages/cli/src/commands/embeddings/index.ts
+++ b/packages/cli/src/commands/embeddings/index.ts
@@ -4,6 +4,7 @@
* Subcommands:
* - `set-key` store the provider API key in `~/.ok/secrets.yml` (0600).
* - `clear-key` remove the stored key.
+ * - `set-url` / `clear-url` set / reset `search.semantic.baseUrl` (project-local).
* - `enable` / `disable` flip `search.semantic.enabled` for the project (project-local).
* - `status` show key presence (machine-global) + enabled/capability/coverage (per-project).
*
@@ -15,7 +16,11 @@
*/
import { resolve } from 'node:path';
-import { humanFormat } from '@inkeep/open-knowledge-core';
+import {
+ checkEmbeddingsBaseUrl,
+ DEFAULT_EMBEDDINGS_BASE_URL,
+ humanFormat,
+} from '@inkeep/open-knowledge-core';
import { writeConfigPatch } from '@inkeep/open-knowledge-core/server';
import {
DEFAULT_EMBEDDINGS_DIMENSIONS,
@@ -117,6 +122,74 @@ function clearKeyCommand(): Command {
});
}
+/**
+ * `set-url` / `clear-url` set / reset `search.semantic.baseUrl` in the
+ * project-local config — the same field + scope the Settings endpoint input
+ * uses, so a running server picks the change up live. `set-url` validates the
+ * URL against the SAME rule the server enforces before sending the key
+ * (`checkEmbeddingsBaseUrl`: https, or http only for loopback) so a
+ * guaranteed-to-fail endpoint is rejected here instead of degrading to lexical
+ * at warm time. `clear-url` writes the default endpoint back (mirrors clearing
+ * the Settings field). Human-run (the field is `agentSettable: false`).
+ */
+function setUrlCommand(): Command {
+ return new Command('set-url')
+ .description('Set the embeddings API endpoint for this project (project-local)')
+ .argument('<url>', 'OpenAI-compatible base URL, e.g. https://api.openai.com/v1')
+ .option('--cwd <path>', 'Project directory (defaults to the current directory)')
+ .action(async (url: string, opts: { cwd?: string }) => {
+ const baseUrl = url.trim();
+ const problem = checkEmbeddingsBaseUrl(baseUrl);
+ if (problem !== null) {
+ process.stderr.write(
+ problem === 'invalid-url'
+ ? `Not a valid URL: ${url}\n`
+ : `Refusing an insecure endpoint: use https:// (http:// is allowed only for localhost). Got: ${url}\n`,
+ );
+ process.exitCode = 1;
+ return;
+ }
+ const projectDir = resolve(opts.cwd ?? process.cwd());
+ const result = await writeConfigPatch({
+ cwd: projectDir,
+ scope: 'project-local',
+ patch: { search: { semantic: { baseUrl } } },
+ });
+ if (!result.ok) {
+ process.stderr.write(
+ `Failed to set the embeddings endpoint — ${humanFormat(result.error)}\n`,
+ );
+ process.exitCode = 1;
+ return;
+ }
+ process.stderr.write(`✓ Embeddings endpoint set to ${baseUrl} for ${projectDir}\n`);
+ });
+}
+
+function clearUrlCommand(): Command {
+ return new Command('clear-url')
+ .description('Reset the embeddings API endpoint to the default OpenAI endpoint (project-local)')
+ .option('--cwd <path>', 'Project directory (defaults to the current directory)')
+ .action(async (opts: { cwd?: string }) => {
+ const projectDir = resolve(opts.cwd ?? process.cwd());
+ const result = await writeConfigPatch({
+ cwd: projectDir,
+ scope: 'project-local',
+ patch: { search: { semantic: { baseUrl: DEFAULT_EMBEDDINGS_BASE_URL } } },
+ });
+ if (!result.ok) {
+ process.stderr.write(
+ `Failed to reset the embeddings endpoint — ${humanFormat(result.error)}\n`,
+ );
+ process.exitCode = 1;
+ return;
+ }
+ process.stderr.write(
+ `✓ Embeddings endpoint reset to ${DEFAULT_EMBEDDINGS_BASE_URL} for ${projectDir}\n`,
+ );
+ });
+}
+
/**
* `enable` / `disable` flip `search.semantic.enabled` in the project-local config
* (`<project>/.ok/local/config.yml`) — the same field + scope the Settings toggle
@@ -230,6 +303,8 @@ export function embeddingsCommand(): Command {
.description('Manage the semantic-search embeddings provider key + status')
.addCommand(setKeyCommand())
.addCommand(clearKeyCommand())
+ .addCommand(setUrlCommand())
+ .addCommand(clearUrlCommand())
.addCommand(toggleEnabledCommand('enable', true))
.addCommand(toggleEnabledCommand('disable', false))
.addCommand(statusCommand());
diff --git a/packages/core/src/config/schema.test.ts b/packages/core/src/config/schema.test.ts
index bc3d1d5bd..065caa43d 100644
--- a/packages/core/src/config/schema.test.ts
+++ b/packages/core/src/config/schema.test.ts
@@ -1,10 +1,41 @@
import { describe, expect, test } from 'bun:test';
import {
ConfigSchema,
+ checkEmbeddingsBaseUrl,
isValidAttachmentFolderPath,
normalizeAttachmentFolderPath,
} from './schema.ts';
+describe('checkEmbeddingsBaseUrl', () => {
+ test('accepts https endpoints', () => {
+ expect(checkEmbeddingsBaseUrl('https://api.openai.com/v1')).toBeNull();
+ expect(checkEmbeddingsBaseUrl('https://azure.example.com/openai/v1/')).toBeNull();
+ expect(checkEmbeddingsBaseUrl('https://api.example.com')).toBeNull();
+ });
+
+ test('accepts http only for loopback hosts (key never leaves the machine)', () => {
+ expect(checkEmbeddingsBaseUrl('http://localhost:11434/v1')).toBeNull();
+ expect(checkEmbeddingsBaseUrl('http://127.0.0.1:8080/v1')).toBeNull();
+ expect(checkEmbeddingsBaseUrl('http://[::1]:1234/v1')).toBeNull();
+ });
+
+ test('rejects plaintext http to a non-loopback host', () => {
+ expect(checkEmbeddingsBaseUrl('http://evil.example/v1')).toBe('insecure-scheme');
+ expect(checkEmbeddingsBaseUrl('http://api.openai.com/v1')).toBe('insecure-scheme');
+ });
+
+ test('rejects non-http(s) schemes', () => {
+ expect(checkEmbeddingsBaseUrl('ftp://api.example.com')).toBe('insecure-scheme');
+ expect(checkEmbeddingsBaseUrl('file:///etc/passwd')).toBe('insecure-scheme');
+ });
+
+ test('rejects unparseable input', () => {
+ expect(checkEmbeddingsBaseUrl('not a url')).toBe('invalid-url');
+ expect(checkEmbeddingsBaseUrl('api.openai.com/v1')).toBe('invalid-url');
+ expect(checkEmbeddingsBaseUrl('')).toBe('invalid-url');
+ });
+});
+
describe('content.attachmentFolderPath', () => {
test('defaults to "./" when absent', () => {
expect(ConfigSchema.parse({}).content.attachmentFolderPath).toBe('./');
diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts
index 485810ddb..4641c28ed 100644
--- a/packages/core/src/config/schema.ts
+++ b/packages/core/src/config/schema.ts
@@ -28,6 +28,34 @@ export const DEFAULT_LOGS_MAX_BYTES = 26_214_400;
export const DEFAULT_EMBEDDINGS_BASE_URL = 'https://api.openai.com/v1';
export const DEFAULT_EMBEDDINGS_MODEL = 'text-embedding-3-small';
+/** Why an embeddings base URL is rejected: unparseable, or a plaintext scheme. */
+export type EmbeddingsBaseUrlProblem = 'invalid-url' | 'insecure-scheme';
+
+/**
+ * Validate an embeddings base URL against the SAME rule the server enforces
+ * before it will send the Bearer API key (`assertSafeEmbeddingsBaseUrl` in the
+ * embedder): a parseable URL that is `https:`, or `http:` only for a loopback
+ * host (a local dev gateway, where the key never leaves the machine). Returns
+ * `null` when acceptable, else the problem. Shared so the app's inline
+ * validation and the `ok embeddings set-url` CLI reject a guaranteed-to-fail
+ * endpoint at entry instead of letting it surface later as a provider-rejected
+ * status. Whitespace is the caller's to trim.
+ */
+export function checkEmbeddingsBaseUrl(baseUrl: string): EmbeddingsBaseUrlProblem | null {
+ let url: URL;
+ try {
+ url = new URL(baseUrl);
+ } catch {
+ return 'invalid-url';
+ }
+ if (url.protocol === 'https:') return null;
+ // `URL.hostname` returns IPv6 hosts bracketed (`[::1]`), never bare `::1`.
+ const host = url.hostname.toLowerCase();
+ const isLoopback = host === 'localhost' || host === '127.0.0.1' || host === '[::1]';
+ if (url.protocol === 'http:' && isLoopback) return null;
+ return 'insecure-scheme';
+}
+
export function normalizeAttachmentFolderPath(value: string): string {
const trimmed = value.trim();
return trimmed === '' ? DEFAULT_ATTACHMENT_FOLDER_PATH : trimmed;
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index aa7647d82..9e51fac12 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -107,6 +107,7 @@ export {
type Config,
type ConfigPatch,
ConfigSchema,
+ checkEmbeddingsBaseUrl,
DEFAULT_EMBEDDINGS_BASE_URL,
DEFAULT_EMBEDDINGS_MODEL,
DEFAULT_LOGS_MAX_BYTES,
diff --git a/packages/server/src/embeddings/embedder.ts b/packages/server/src/embeddings/embedder.ts
index 07004978b..3f500a43b 100644
--- a/packages/server/src/embeddings/embedder.ts
+++ b/packages/server/src/embeddings/embedder.ts
@@ -16,6 +16,7 @@
* zero egress. A null return means "no key → degrade to lexical search".
*/
+import { checkEmbeddingsBaseUrl } from '@inkeep/open-knowledge-core';
import {
type EmbeddingErrorReason,
recordEmbeddingProviderError,
@@ -193,17 +194,15 @@ export function normalizeProviderId(baseUrl: string): string {
* catches it and degrades to lexical, so a misconfig never causes egress.
*/
function assertSafeEmbeddingsBaseUrl(baseUrl: string): void {
- let url: URL;
- try {
- url = new URL(baseUrl);
- } catch {
+ // Rules are shared with the app + CLI via `checkEmbeddingsBaseUrl` so
+ // client-side validation can never diverge from this server-side guard.
+ const problem = checkEmbeddingsBaseUrl(baseUrl);
+ if (problem === null) return;
+ if (problem === 'invalid-url') {
throw new Error(`embeddings baseUrl is not a valid URL: ${baseUrl}`);
}
- if (url.protocol === 'https:') return;
- const host = url.hostname.toLowerCase();
- const isLoopback =
- host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]';
- if (url.protocol === 'http:' && isLoopback) return;
+ // insecure-scheme — re-parse for the host detail (already proven parseable).
+ const url = new URL(baseUrl);
throw new Error(
`refusing to send the embeddings API key to a non-HTTPS endpoint (${url.protocol}//${url.host}); ` +
'use https:// (http:// is allowed only for localhost)',