Skip to content

Find code by asking what it does. A CLI for coding agents that uses Jev to discover relevant files and source context.

Add a custom provider for TypeSafe-compatible endpoints (#28)

Mohamed Ubaida9993c1b9b75
diff --git a/README.md b/README.md
index 6e25912..0a66981 100644
--- a/README.md
+++ b/README.md
@@ -25,7 +25,7 @@ jg skill
jg "How are telemetry events recorded and sent?" ./my-project
```
-Requires **Node.js 22+**, **macOS or Linux**, and a key for **Vercel AI Gateway, TypeSafe, OpenRouter, or OpenCode Zen**.
+Requires **Node.js 22+**, **macOS or Linux**, and a key for **Vercel AI Gateway, TypeSafe, OpenRouter, OpenCode Zen, or a custom TypeSafe-compatible endpoint**.
No separate Python, Bun, or ripgrep installation is required to use `jg`.
Provider selection requires **0.3.0 or newer**. Upgrade an older installation with
diff --git a/apps/cli/README.md b/apps/cli/README.md
index 3f626a2..8bb7b27 100644
--- a/apps/cli/README.md
+++ b/apps/cli/README.md
@@ -13,9 +13,11 @@ jg doctor
jg "How are telemetry events recorded and sent?" ./my-project
```
-`auth` asks you to choose a provider, then saves its key in an owner-only config file.
-Run `jg --help` for the supported provider names. Searches use that provider until you run auth again.
-`doctor` verifies access with synthetic input and names the selected provider.
+`auth` asks you to choose a provider or a custom endpoint, then saves its key in an
+owner-only config file. Run `jg --help` for the supported provider names. Searches
+use that provider until you run auth again.
+`doctor` verifies access with synthetic input and names the selected provider or
+endpoint host.
When the provider rejects the request, doctor reports the HTTP status and its
error message, when available. A working key can still lack model access or paid
credits; follow the provider’s explanation before replacing the key. Saved keys
@@ -27,7 +29,20 @@ For unattended setup, pipe the key from your secret manager to:
jg auth --provider opencode --stdin
```
-Both options are required for piped setup. Credentials are saved under
+Both options are required for piped setup. To send traffic through your own
+TypeSafe-compatible gateway, choose “Custom endpoint” in `auth` and enter its base
+URL and model ID, or pass both explicitly:
+
+```sh
+jg auth --provider custom --base-url https://gateway.example.com/typesafe/v1 --model gateway/jev-2 --stdin
+```
+
+Custom endpoints must use `https://`; `http://localhost` and `http://127.0.0.1`
+are accepted for a local proxy. Auth and doctor name only the endpoint host, never
+the key. The saved endpoint and model are part of the cache identity, so custom
+answers stay separate from the preset providers’ answers and from other endpoints.
+
+Credentials are saved under
`$XDG_CONFIG_HOME/jevgrep/credentials.json`, or `~/.config/jevgrep/credentials.json`.
Existing saved records without a provider still mean Vercel, without a migration.
API-key, endpoint, and model environment overrides are ignored; users who only
diff --git a/apps/cli/src/args.ts b/apps/cli/src/args.ts
index 1288f35..3908771 100644
--- a/apps/cli/src/args.ts
+++ b/apps/cli/src/args.ts
@@ -1,13 +1,16 @@
import { parseArgs } from "node:util";
import type { SearchInput } from "@repo/core";
-import { providers, isProviderId, type ProviderId } from "@repo/core/providers";
+import { providers, customProviderId, isCredentialProvider } from "@repo/core/providers";
import { CliError } from "./errors";
import { DEFAULT_MAX_SOURCE_BYTES } from "./render";
+import type { AuthOptions } from "./auth";
+
+const credentialProviders = [...Object.keys(providers), customProviderId];
export type Command =
| { kind: "help" | "version" | "doctor" | "cache-clear" }
| { kind: "skill"; agents: string[]; global: boolean; yes: boolean }
- | { kind: "auth"; provider?: ProviderId }
+ | ({ kind: "auth" } & AuthOptions)
| {
kind: "search";
query: string;
@@ -30,6 +33,8 @@ export function parseCommand(args: string[]): Command {
version: { type: "boolean" },
stdin: { type: "boolean" },
provider: { type: "string" },
+ "base-url": { type: "string" },
+ model: { type: "string" },
agent: { type: "string", multiple: true },
global: { type: "boolean" },
yes: { type: "boolean" },
@@ -54,13 +59,28 @@ export function parseCommand(args: string[]): Command {
if (values.help || values.version) throw new CliError("Use --help or --version alone.");
const first = positionals[0];
if (first === "auth") {
- if (positionals.length !== 1 || keys.some((key) => !["stdin", "provider"].includes(key)))
+ if (
+ positionals.length !== 1 ||
+ keys.some((key) => !["stdin", "provider", "base-url", "model"].includes(key))
+ )
throw new CliError("Usage: jg auth OR jg auth --provider NAME --stdin");
if (!keys.length) return { kind: "auth" };
- if (!values.stdin || !isProviderId(values.provider))
+ if (!values.stdin || !isCredentialProvider(values.provider))
throw new CliError(
- `Use auth --provider ${Object.keys(providers).join("|")} --stdin for a piped key.`,
+ `Use auth --provider ${credentialProviders.join("|")} --stdin for a piped key.`,
);
+ if (values.provider === customProviderId) {
+ if (!values["base-url"] || !values.model)
+ throw new CliError("Custom endpoints need --base-url URL and --model ID with --stdin.");
+ return {
+ kind: "auth",
+ provider: customProviderId,
+ baseURL: values["base-url"],
+ model: values.model,
+ };
+ }
+ if (values["base-url"] !== undefined || values.model !== undefined)
+ throw new CliError("--base-url and --model are only valid with --provider custom.");
return { kind: "auth", provider: values.provider };
}
if (first === "skill") {
@@ -87,7 +107,7 @@ export function parseCommand(args: string[]): Command {
!first?.trim() ||
positionals.length > 2 ||
values.stdin ||
- keys.some((key) => ["agent", "global", "yes", "provider"].includes(key))
+ keys.some((key) => ["agent", "global", "yes", "provider", "base-url", "model"].includes(key))
)
throw new CliError('Usage: jg "question" [root]. Run jg --help.');
let concurrency: number | undefined;
@@ -140,15 +160,18 @@ Usage: jg "question" [root]
Root defaults to the current directory; use -- before a root beginning with -.
Commands:
- auth Choose a provider, then save its key (hidden prompt)
+ auth Choose a provider or custom endpoint, then save its key
doctor Verify Jev access using a synthetic question
skill Install the agent skill via npx skills
--help, -h Show usage
--version Show the installed version
Auth automation:
- auth --provider ${Object.keys(providers).join("|")} --stdin
+ auth --provider ${credentialProviders.join("|")} --stdin
+ auth --provider custom --base-url URL --model ID --stdin
Save one provider/key from a pipe. Re-running auth replaces your setup.
+ Custom endpoints must use https://; http:// is allowed only for localhost
+ and 127.0.0.1. Auth and doctor name the endpoint host, never the key.
Saved credentials only; provider key/URL environment variables are ignored.
Skill installation options:
diff --git a/apps/cli/src/auth.ts b/apps/cli/src/auth.ts
index fb86dc9..9937994 100644
--- a/apps/cli/src/auth.ts
+++ b/apps/cli/src/auth.ts
@@ -2,8 +2,18 @@ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"
import { homedir } from "node:os";
import { join } from "node:path";
import { randomUUID } from "node:crypto";
-import { isCancel, password, select } from "@clack/prompts";
-import { providers, isProviderId, type ProviderId } from "@repo/core/providers";
+import { isCancel, password, select, text } from "@clack/prompts";
+import {
+ customProviderId,
+ customProviderLabel,
+ endpointFor,
+ isCredentialProvider,
+ providers,
+ validateBaseURL,
+ validateModel,
+ type CredentialProvider,
+ type ProviderId,
+} from "@repo/core/providers";
import { CliError } from "./errors";
export function configDirectory() {
@@ -18,59 +28,88 @@ function validateKey(raw: string): string {
return key;
}
-export type Credentials = { provider: ProviderId; apiKey: string };
+export type Credentials =
+ | { provider: ProviderId; apiKey: string }
+ | { provider: typeof customProviderId; baseURL: string; model: string; apiKey: string };
-export async function authenticate(provider: ProviderId | undefined, signal: AbortSignal) {
- let key: string;
- if (provider !== undefined) {
- const chunks: Buffer[] = [];
- let bytes = 0;
- const abort = () => process.stdin.destroy(new DOMException("Interrupted", "AbortError"));
- signal.throwIfAborted();
- signal.addEventListener("abort", abort, { once: true });
- try {
- for await (const chunk of process.stdin) {
- bytes += chunk.length;
- if (bytes > 8192) throw new CliError("Auth input exceeds 8 KiB.");
- chunks.push(Buffer.from(chunk));
- }
- key = validateKey(Buffer.concat(chunks).toString("utf8"));
- } finally {
- signal.removeEventListener("abort", abort);
- }
- } else {
- if (!process.stdin.isTTY)
- throw new CliError(
- `Use auth --provider ${Object.keys(providers).join("|")} --stdin to read a piped key.`,
- );
- const selected = await select<ProviderId>({
- message: "Choose your Jev provider",
- options: (Object.keys(providers) as ProviderId[]).map((value) => ({
- value,
- label: providers[value].label,
- })),
- output: process.stdout,
- signal,
- });
- if (isCancel(selected)) throw new DOMException("Interrupted", "AbortError");
- provider = selected;
- const answer = await password({
- message: `Paste your ${providers[provider].label} API key`,
- output: process.stdout,
- signal,
- });
- if (isCancel(answer)) {
- throw new DOMException("Interrupted", "AbortError");
+export type AuthOptions = {
+ provider?: CredentialProvider;
+ baseURL?: string;
+ model?: string;
+};
+
+type CustomEndpoint = { baseURL: string; model: string };
+
+function invalid(error: unknown) {
+ return error instanceof Error ? error.message : "Invalid value.";
+}
+
+function customEndpoint(options: AuthOptions): CustomEndpoint {
+ try {
+ return { baseURL: validateBaseURL(options.baseURL), model: validateModel(options.model) };
+ } catch (error) {
+ throw new CliError(invalid(error));
+ }
+}
+
+async function readKey(signal: AbortSignal): Promise<string> {
+ const chunks: Buffer[] = [];
+ let bytes = 0;
+ const abort = () => process.stdin.destroy(new DOMException("Interrupted", "AbortError"));
+ signal.throwIfAborted();
+ signal.addEventListener("abort", abort, { once: true });
+ try {
+ for await (const chunk of process.stdin) {
+ bytes += chunk.length;
+ if (bytes > 8192) throw new CliError("Auth input exceeds 8 KiB.");
+ chunks.push(Buffer.from(chunk));
}
- key = validateKey(answer);
+ return validateKey(Buffer.concat(chunks).toString("utf8"));
+ } finally {
+ signal.removeEventListener("abort", abort);
}
+}
+
+async function promptEndpoint(signal: AbortSignal): Promise<CustomEndpoint> {
+ const baseURL = await text({
+ message: "Base URL of the custom endpoint",
+ placeholder: "https://gateway.example.com/typesafe/v1",
+ validate: (value) => {
+ try {
+ validateBaseURL(value);
+ } catch (error) {
+ return invalid(error);
+ }
+ },
+ output: process.stdout,
+ signal,
+ });
+ if (isCancel(baseURL)) throw new DOMException("Interrupted", "AbortError");
+ const model = await text({
+ message: "Model ID served by that endpoint",
+ placeholder: "your-gateway/jev",
+ validate: (value) => {
+ try {
+ validateModel(value);
+ } catch (error) {
+ return invalid(error);
+ }
+ },
+ output: process.stdout,
+ signal,
+ });
+ if (isCancel(model)) throw new DOMException("Interrupted", "AbortError");
+ return customEndpoint({ baseURL, model });
+}
+
+async function save(credentials: Credentials, signal: AbortSignal) {
const directory = configDirectory();
signal.throwIfAborted();
await mkdir(directory, { recursive: true, mode: 0o700 });
await chmod(directory, 0o700);
const temporary = join(directory, `.credentials-${randomUUID()}.json`);
try {
- await writeFile(temporary, JSON.stringify({ provider, apiKey: key }) + "\n", {
+ await writeFile(temporary, JSON.stringify(credentials) + "\n", {
mode: 0o600,
flag: "wx",
});
@@ -79,7 +118,61 @@ export async function authenticate(provider: ProviderId | undefined, signal: Abo
} finally {
await rm(temporary, { force: true });
}
- process.stdout.write(`${providers[provider].label} key saved. Run jg doctor to verify access.\n`);
+}
+
+async function readPassword(message: string, signal: AbortSignal): Promise<string> {
+ const answer = await password({ message, output: process.stdout, signal });
+ if (isCancel(answer)) throw new DOMException("Interrupted", "AbortError");
+ return validateKey(answer);
+}
+
+export async function authenticate(options: AuthOptions, signal: AbortSignal) {
+ let credentials: Credentials;
+ if (options.provider !== undefined) {
+ if (options.provider === customProviderId) {
+ const endpoint = customEndpoint(options);
+ credentials = { provider: customProviderId, ...endpoint, apiKey: await readKey(signal) };
+ } else {
+ credentials = { provider: options.provider, apiKey: await readKey(signal) };
+ }
+ } else {
+ if (!process.stdin.isTTY)
+ throw new CliError(
+ `Use auth --provider ${[...Object.keys(providers), customProviderId].join(
+ "|",
+ )} --stdin to read a piped key.`,
+ );
+ const selected = await select<CredentialProvider>({
+ message: "Choose your Jev provider",
+ options: [
+ ...(Object.keys(providers) as ProviderId[]).map((value) => ({
+ value,
+ label: providers[value].label,
+ })),
+ { value: customProviderId, label: customProviderLabel },
+ ],
+ output: process.stdout,
+ signal,
+ });
+ if (isCancel(selected)) throw new DOMException("Interrupted", "AbortError");
+ if (selected === customProviderId) {
+ const endpoint = await promptEndpoint(signal);
+ credentials = {
+ provider: customProviderId,
+ ...endpoint,
+ apiKey: await readPassword("Paste the API key for that endpoint", signal),
+ };
+ } else {
+ credentials = {
+ provider: selected,
+ apiKey: await readPassword(`Paste your ${providers[selected].label} API key`, signal),
+ };
+ }
+ }
+ await save(credentials, signal);
+ process.stdout.write(
+ `${endpointFor(credentials).label} key saved. Run jg doctor to verify access.\n`,
+ );
}
export async function loadCredentials(): Promise<Credentials> {
@@ -91,8 +184,17 @@ export async function loadCredentials(): Promise<Credentials> {
throw new CliError("Invalid credentials. Run jg auth again.");
}
const provider = Object.hasOwn(credentials, "provider") ? credentials.provider : "vercel";
- if (!isProviderId(provider)) throw new CliError("Invalid provider. Run jg auth again.");
- return { provider, apiKey: validateKey(credentials.apiKey) };
+ if (!isCredentialProvider(provider)) throw new CliError("Invalid provider. Run jg auth again.");
+ const apiKey = validateKey(credentials.apiKey);
+ if (provider === customProviderId) {
+ return {
+ provider,
+ baseURL: validateBaseURL(credentials.baseURL),
+ model: validateModel(credentials.model),
+ apiKey,
+ };
+ }
+ return { provider, apiKey };
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
throw new CliError("Run jg auth or use jg auth --provider NAME --stdin.");
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts
index cc8d023..baac4a1 100644
--- a/apps/cli/src/index.ts
+++ b/apps/cli/src/index.ts
@@ -1,6 +1,6 @@
#!/usr/bin/env node
import { authenticate, configDirectory, loadCredentials } from "./auth";
-import { providers } from "@repo/core/providers";
+import { endpointFor } from "@repo/core/providers";
import { help, parseCommand } from "./args";
import { CliError } from "./errors";
import { renderResult } from "./render";
@@ -47,7 +47,7 @@ async function main() {
process.exitCode = await installSkill(command, controller.signal);
return;
case "auth":
- return authenticate(command.provider, controller.signal);
+ return authenticate(command, controller.signal);
case "cache-clear": {
const { createEvaluationCache } = await import("@repo/core");
const cache = createEvaluationCache({ directory: cacheDirectory() });
@@ -58,6 +58,7 @@ async function main() {
}
case "doctor": {
const credentials = await loadCredentials();
+ const endpoint = endpointFor(credentials);
const { createEvaluator, EvaluationFailure } = await import("@repo/core");
const evaluator = createEvaluator({
...credentials,
@@ -75,22 +76,22 @@ async function main() {
});
if (!(answers.relevant! > 0.5))
throw new CliError(
- `${providers[credentials.provider].label} returned an unexpected answer to the connection check.`,
+ `${endpoint.label} returned an unexpected answer to the connection check.`,
);
- await write(`Jev connection verified through ${providers[credentials.provider].label}.\n`);
+ await write(`Jev connection verified through ${endpoint.label}.\n`);
} catch (error) {
if (error instanceof CliError) throw error;
if (error instanceof EvaluationFailure && error.diagnostic) {
const { statusCode, message } = error.diagnostic;
throw new CliError(
- `Jev connection check failed through ${providers[credentials.provider].label} (HTTP ${statusCode}).\n` +
+ `Jev connection check failed through ${endpoint.label} (HTTP ${statusCode}).\n` +
(message
? `Provider: ${message}`
: "Check your saved key, model access, and provider billing."),
);
}
throw new CliError(
- `Jev connection check failed through ${providers[credentials.provider].label}. Check your saved key, model access, and network.`,
+ `Jev connection check failed through ${endpoint.label}. Check your saved key, model access, and network.`,
);
}
return;
diff --git a/apps/cli/test/args.test.ts b/apps/cli/test/args.test.ts
index bb3a2f0..82463bd 100644
--- a/apps/cli/test/args.test.ts
+++ b/apps/cli/test/args.test.ts
@@ -71,6 +71,39 @@ test("auth requires explicit provider for stdin and keeps provider selection out
expect(() => parseCommand(args)).toThrow();
});
+test("custom auth carries an explicit base URL and model while presets reject them", () => {
+ expect(
+ parseCommand([
+ "auth",
+ "--provider",
+ "custom",
+ "--base-url",
+ "https://gateway.example.com/typesafe/v1",
+ "--model",
+ "gateway/jev-2",
+ "--stdin",
+ ]),
+ ).toEqual({
+ kind: "auth",
+ provider: "custom",
+ baseURL: "https://gateway.example.com/typesafe/v1",
+ model: "gateway/jev-2",
+ });
+ for (const args of [
+ ["auth", "--provider", "custom", "--stdin"],
+ ["auth", "--provider", "custom", "--base-url", "https://gateway.example.com/v1", "--stdin"],
+ ["auth", "--provider", "custom", "--model", "gateway/jev-2", "--stdin"],
+ ["auth", "--provider", "vercel", "--base-url", "https://gateway.example.com/v1", "--stdin"],
+ ["auth", "--provider", "vercel", "--model", "gateway/jev-2", "--stdin"],
+ ["auth", "--base-url", "https://gateway.example.com/v1", "--model", "gateway/jev-2", "--stdin"],
+ ["doctor", "--base-url", "https://gateway.example.com/v1"],
+ ["doctor", "--model", "gateway/jev-2"],
+ ["question", "--base-url", "https://gateway.example.com/v1"],
+ ["cache", "clear", "--model", "gateway/jev-2"],
+ ])
+ expect(() => parseCommand(args)).toThrow();
+});
+
test("concurrency is a positive search-only limit and does not change cache policy", () => {
const command = parseCommand(["question", "--concurrency", "2"]);
expect(command).toMatchObject({ kind: "search", concurrency: 2, policy: {} });
diff --git a/apps/cli/test/auth.test.ts b/apps/cli/test/auth.test.ts
index 3419e30..37f35ea 100644
--- a/apps/cli/test/auth.test.ts
+++ b/apps/cli/test/auth.test.ts
@@ -1,5 +1,5 @@
import { expect } from "bun:test";
-import { readFile, stat } from "node:fs/promises";
+import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { testInDocker, withCli } from "./cli";
@@ -31,3 +31,160 @@ testInDocker("installed auth saves privately, bounds stdin, and never echoes key
});
});
});
+
+testInDocker(
+ "custom auth saves the endpoint and doctor verifies it without echoing the key",
+ async () => {
+ const requests: Array<{ path: string; authorization: string; body: Record<string, unknown> }> =
+ [];
+ const server = Bun.serve({
+ port: 0,
+ async fetch(request) {
+ requests.push({
+ path: new URL(request.url).pathname,
+ authorization: request.headers.get("authorization") ?? "",
+ body: (await request.json()) as Record<string, unknown>,
+ });
+ return Response.json({ answers: { relevant: { type: "noul", noul: 0.9 } } });
+ },
+ });
+ try {
+ await withCli(async ({ home, run }) => {
+ const key = "custom-endpoint-secret";
+ const baseURL = `http://127.0.0.1:${server.port}/typesafe/v1`;
+ const auth = await run(
+ [
+ "auth",
+ "--provider",
+ "custom",
+ "--base-url",
+ baseURL,
+ "--model",
+ "gateway/jev-2",
+ "--stdin",
+ ],
+ `${key}\n`,
+ );
+ expect(auth.code).toBe(0);
+ expect(auth.stderr).toBe("");
+ expect(auth.stdout).toContain(`Custom endpoint (127.0.0.1:${server.port})`);
+ expect(auth.stdout).toContain("key saved");
+ expect(auth.stdout).not.toContain(key);
+ const file = join(home, "jevgrep", "credentials.json");
+ expect(JSON.parse(await readFile(file, "utf8"))).toEqual({
+ provider: "custom",
+ baseURL,
+ model: "gateway/jev-2",
+ apiKey: key,
+ });
+ expect((await stat(file)).mode & 0o777).toBe(0o600);
+ expect((await stat(join(home, "jevgrep"))).mode & 0o777).toBe(0o700);
+ expect(requests).toHaveLength(0);
+
+ const doctor = await run(["doctor"]);
+ expect(doctor.code).toBe(0);
+ expect(doctor.stderr).toBe("");
+ expect(doctor.stdout).toContain(`Custom endpoint (127.0.0.1:${server.port})`);
+ expect(doctor.stdout).not.toContain(key);
+ expect(requests).toHaveLength(1);
+ expect(requests[0]!.path).toBe("/typesafe/v1/systemone");
+ expect(requests[0]!.authorization).toBe(`Bearer ${key}`);
+ expect(requests[0]!.body.model).toBe("gateway/jev-2");
+ expect(Object.keys(requests[0]!.body.questions as object)).toEqual(["relevant"]);
+ });
+ } finally {
+ server.stop(true);
+ }
+ },
+);
+
+testInDocker("custom auth rejects insecure or incomplete endpoints before saving", async () => {
+ await withCli(async ({ home, run }) => {
+ const file = join(home, "jevgrep", "credentials.json");
+ for (const [args, expected] of [
+ [
+ [
+ "auth",
+ "--provider",
+ "custom",
+ "--base-url",
+ "http://gateway.example.com/v1",
+ "--model",
+ "jev",
+ "--stdin",
+ ],
+ "https://",
+ ],
+ [
+ [
+ "auth",
+ "--provider",
+ "custom",
+ "--base-url",
+ "ftp://gateway.example.com/v1",
+ "--model",
+ "jev",
+ "--stdin",
+ ],
+ "Base URL",
+ ],
+ [
+ [
+ "auth",
+ "--provider",
+ "custom",
+ "--base-url",
+ "https://gateway.example.com/v1",
+ "--model",
+ "two words",
+ "--stdin",
+ ],
+ "model ID",
+ ],
+ [
+ ["auth", "--provider", "custom", "--base-url", "https://gateway.example.com/v1", "--stdin"],
+ "--model",
+ ],
+ [
+ ["auth", "--provider", "vercel", "--base-url", "https://gateway.example.com/v1", "--stdin"],
+ "custom",
+ ],
+ ] as const) {
+ const result = await run([...args], "rejected-endpoint-secret\n");
+ expect(result.code).toBe(1);
+ expect(result.stderr).toBe("");
+ expect(result.stdout).toContain(expected);
+ expect(result.stdout).not.toContain("rejected-endpoint-secret");
+ }
+ expect(await readFile(file, "utf8").catch(() => null)).toBeNull();
+ const piped = await run(["auth"], "piped-secret\n");
+ expect(piped.code).toBe(1);
+ expect(piped.stdout).toContain("custom");
+ expect(piped.stdout).not.toContain("piped-secret");
+ });
+});
+
+testInDocker(
+ "doctor rejects a persisted custom endpoint that violates the transport rule",
+ async () => {
+ await withCli(async ({ home, run }) => {
+ const directory = join(home, "jevgrep");
+ await mkdir(directory, { recursive: true, mode: 0o700 });
+ await writeFile(
+ join(directory, "credentials.json"),
+ JSON.stringify({
+ provider: "custom",
+ baseURL: "http://gateway.example.com/v1",
+ model: "gateway/jev-2",
+ apiKey: "stored-endpoint-secret",
+ }),
+ );
+ const doctor = await run(["doctor"]);
+ expect(doctor.code).toBe(1);
+ expect(doctor.stderr).toBe("");
+ expect(doctor.stdout).toContain("Could not read valid credentials");
+ expect(doctor.stdout).not.toContain("stored-endpoint-secret");
+ expect(doctor.stdout).not.toContain("gateway.example.com");
+ });
+ },
+);
diff --git a/apps/cli/test/process.test.ts b/apps/cli/test/process.test.ts
index d412095..187c0e9 100644
--- a/apps/cli/test/process.test.ts
+++ b/apps/cli/test/process.test.ts
@@ -42,6 +42,7 @@ testInDocker("interactive auth hides input and exits 130 on interruption", async
await withCli(async ({ home }) => {
for (const mode of [
"save",
+ "custom-save",
"interrupt-provider",
"interrupt-key",
"cancel-provider",
@@ -72,15 +73,24 @@ try:
output += part
wait_for(b"Choose your Jev provider")
mode = sys.argv[2]
- if not mode.endswith("provider"):
- os.write(master, b"\\x1b[B\\x1b[B\\r")
+ if mode == "custom-save":
+ os.write(master, b"\\x1b[B\\x1b[B\\x1b[B\\x1b[B\\r")
+ wait_for(b"Base URL")
+ os.write(master, b"http://127.0.0.1:8080/v1\\r")
+ wait_for(b"Model ID")
+ os.write(master, b"gateway/jev-2\\r")
wait_for(b"API key")
- if mode == "save":
os.write(master, b"pty-fixture-secret\\r")
- elif mode.startswith("cancel"):
- os.write(master, b"\\x03")
else:
- process.send_signal(signal.SIGINT)
+ if not mode.endswith("provider"):
+ os.write(master, b"\\x1b[B\\x1b[B\\r")
+ wait_for(b"API key")
+ if mode == "save":
+ os.write(master, b"pty-fixture-secret\\r")
+ elif mode.startswith("cancel"):
+ os.write(master, b"\\x03")
+ else:
+ process.send_signal(signal.SIGINT)
rest, errors = process.communicate(timeout=5)
output += rest
echo = b""
@@ -103,10 +113,11 @@ finally:
{ env: { ...process.env, HOME: home, XDG_CONFIG_HOME: home } },
);
const result = JSON.parse(stdout);
- expect(result.code).toBe(mode === "save" ? 0 : 130);
+ const saved = mode === "save" || mode === "custom-save";
+ expect(result.code).toBe(saved ? 0 : 130);
expect(result.stderr).toBe("");
expect(result.stdout + result.echo).not.toContain("pty-fixture-secret");
- expect(result.stdout).toContain(mode === "save" ? "key saved" : "Interrupted");
+ expect(result.stdout).toContain(saved ? "key saved" : "Interrupted");
if (mode === "save") {
expect(JSON.parse(await readFile(file, "utf8"))).toEqual({
provider: "openrouter",
@@ -116,6 +127,14 @@ finally:
result.stdout.indexOf("TypeSafe"),
);
expect(result.stdout.indexOf("TypeSafe")).toBeLessThan(result.stdout.indexOf("OpenRouter"));
+ } else if (mode === "custom-save") {
+ expect(JSON.parse(await readFile(file, "utf8"))).toEqual({
+ provider: "custom",
+ baseURL: "http://127.0.0.1:8080/v1",
+ model: "gateway/jev-2",
+ apiKey: "pty-fixture-secret",
+ });
+ expect(result.stdout).toContain("Custom endpoint (127.0.0.1:8080)");
} else expect(await readFile(file, "utf8")).toBe(previous);
expect(await readdir(join(home, "jevgrep"))).toEqual(["credentials.json"]);
}
diff --git a/packages/core/src/evaluator.ts b/packages/core/src/evaluator.ts
index ab76975..cd947b3 100644
--- a/packages/core/src/evaluator.ts
+++ b/packages/core/src/evaluator.ts
@@ -1,6 +1,6 @@
import { APICallError, experimental_evaluate as evaluate } from "ai";
import { createTypeSafeAi } from "@ai-sdk/typesafe-ai";
-import { providers, type ProviderId } from "./providers";
+import { endpointFor, type CredentialProvider } from "./providers";
import { type createEvaluationCache, type CacheInput } from "./cache";
import { setTimeout as delay } from "node:timers/promises";
import { stripVTControlCharacters } from "node:util";
@@ -29,8 +29,10 @@ export class EvaluationFailure extends Error {
}
export function createEvaluator(options: {
- provider: ProviderId;
+ provider: CredentialProvider;
apiKey: string;
+ baseURL?: string;
+ model?: string;
cache?: ReturnType<typeof createEvaluationCache>;
policyVersion?: string;
fetch?: typeof fetch;
@@ -39,7 +41,7 @@ export function createEvaluator(options: {
timeoutMs?: number;
concurrency?: number;
}) {
- const preset = providers[options.provider];
+ const endpoint = endpointFor(options);
const concurrency = options.concurrency ?? 32;
const timeoutMs = options.timeoutMs ?? (options.provider === "typesafe" ? 60_000 : 15_000);
if (!Number.isSafeInteger(concurrency) || concurrency < 1)
@@ -79,7 +81,7 @@ export function createEvaluator(options: {
}
const provider = createTypeSafeAi({
apiKey: options.apiKey,
- baseURL: preset.baseURL,
+ baseURL: endpoint.baseURL,
fetch: async (input, init) => {
assertActive();
if (requests >= (options.requestLimit ?? 50_000))
@@ -119,9 +121,9 @@ export function createEvaluator(options: {
const cacheInput: CacheInput = {
request,
namespace: {
- model: preset.model,
+ model: endpoint.model,
provider: options.provider,
- endpoint: preset.baseURL,
+ endpoint: endpoint.baseURL,
protocol: "typesafe-ai-3.0.8",
policyVersion: options.policyVersion ?? "1",
parserVersion: "cpython-3.11.3-pyodide-0.25.1-ts-5.9.3",
@@ -178,7 +180,7 @@ export function createEvaluator(options: {
const reservation = rateBudget?.reserve(reservedTokens);
try {
const result = await evaluate({
- model: provider.evaluationModel(preset.model),
+ model: provider.evaluationModel(endpoint.model),
...request,
maxRetries: 0,
abortSignal: AbortSignal.any([
diff --git a/packages/core/src/providers.ts b/packages/core/src/providers.ts
index c876321..84188ab 100644
--- a/packages/core/src/providers.ts
+++ b/packages/core/src/providers.ts
@@ -23,6 +23,67 @@ export const providers = {
export type ProviderId = keyof typeof providers;
+/** A custom record points at any TypeSafe-compatible endpoint instead of a fixed preset. */
+export const customProviderId = "custom";
+export const customProviderLabel = "Custom endpoint";
+
+export type CredentialProvider = ProviderId | typeof customProviderId;
+
+export type ProviderEndpoint = { label: string; baseURL: string; model: string };
+
+export type ProviderSelection = {
+ provider: CredentialProvider;
+ baseURL?: string;
+ model?: string;
+};
+
export function isProviderId(value: unknown): value is ProviderId {
return typeof value === "string" && Object.hasOwn(providers, value);
}
+
+export function isCredentialProvider(value: unknown): value is CredentialProvider {
+ return value === customProviderId || isProviderId(value);
+}
+
+const loopbackHosts = new Set(["localhost", "127.0.0.1"]);
+
+export function validateBaseURL(value: unknown): string {
+ if (typeof value !== "string" || !value.trim())
+ throw new Error("Provide a base URL for the custom endpoint.");
+ const baseURL = value.trim();
+ let url: URL;
+ try {
+ url = new URL(baseURL);
+ } catch {
+ throw new Error("Base URL must be an absolute http(s) URL.");
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:")
+ throw new Error("Base URL must be an absolute http(s) URL.");
+ if (url.protocol === "http:" && !loopbackHosts.has(url.hostname))
+ throw new Error(
+ "Base URL must use https:// (http:// is allowed only for localhost or 127.0.0.1).",
+ );
+ return baseURL;
+}
+
+export function validateModel(value: unknown): string {
+ if (typeof value !== "string" || !value.trim() || /\s/.test(value.trim()))
+ throw new Error("Provide one non-empty model ID without whitespace.");
+ return value.trim();
+}
+
+function customEndpoint(selection: ProviderSelection): ProviderEndpoint {
+ const baseURL = validateBaseURL(selection.baseURL);
+ return {
+ label: `${customProviderLabel} (${new URL(baseURL).host})`,
+ baseURL,
+ model: validateModel(selection.model),
+ };
+}
+
+/** Resolve the transport settings for a saved record without exposing its key. */
+export function endpointFor(selection: ProviderSelection): ProviderEndpoint {
+ return selection.provider === customProviderId
+ ? customEndpoint(selection)
+ : providers[selection.provider];
+}
diff --git a/packages/core/test/providers.test.ts b/packages/core/test/providers.test.ts
new file mode 100644
index 0000000..14e151e
--- /dev/null
+++ b/packages/core/test/providers.test.ts
@@ -0,0 +1,61 @@
+import { expect, test } from "bun:test";
+import {
+ customProviderId,
+ endpointFor,
+ isCredentialProvider,
+ providers,
+ validateBaseURL,
+ validateModel,
+} from "../src/providers";
+
+test("preset endpoints keep their existing label, base URL, and model", () => {
+ for (const provider of ["vercel", "typesafe", "openrouter", "opencode"] as const)
+ expect(endpointFor({ provider })).toEqual(providers[provider]);
+});
+
+test("custom endpoints resolve to the saved base URL, model, and visible host", () => {
+ expect(
+ endpointFor({
+ provider: "custom",
+ baseURL: "https://gateway.example.com/typesafe/v1",
+ model: "gateway/jev-2",
+ }),
+ ).toEqual({
+ label: "Custom endpoint (gateway.example.com)",
+ baseURL: "https://gateway.example.com/typesafe/v1",
+ model: "gateway/jev-2",
+ });
+});
+
+test("base URLs require https except for loopback development proxies", () => {
+ expect(validateBaseURL(" https://gateway.example.com/v1 ")).toBe(
+ "https://gateway.example.com/v1",
+ );
+ expect(validateBaseURL("http://localhost:8080/v1")).toBe("http://localhost:8080/v1");
+ expect(validateBaseURL("http://127.0.0.1:8080/v1")).toBe("http://127.0.0.1:8080/v1");
+ for (const value of [
+ "http://gateway.example.com/v1",
+ "http://192.168.1.10:8080/v1",
+ "ftp://gateway.example.com/v1",
+ "gateway.example.com/v1",
+ "",
+ " ",
+ undefined,
+ 7,
+ ])
+ expect(() => validateBaseURL(value)).toThrow();
+});
+
+test("model IDs must be non-empty and free of whitespace", () => {
+ expect(validateModel(" gateway/jev-2 ")).toBe("gateway/jev-2");
+ for (const value of ["", " ", "two words", undefined, 7])
+ expect(() => validateModel(value)).toThrow();
+});
+
+test("custom is a selectable credential provider and unknown names stay invalid", () => {
+ expect(customProviderId).toBe("custom");
+ expect(isCredentialProvider("custom")).toBe(true);
+ expect(isCredentialProvider("vercel")).toBe(true);
+ for (const value of ["unknown", "Custom", "", undefined, 7])
+ expect(isCredentialProvider(value)).toBe(false);
+});
diff --git a/test/evaluator.test.ts b/test/evaluator.test.ts
index 25d830d..f444291 100644
--- a/test/evaluator.test.ts
+++ b/test/evaluator.test.ts
@@ -1,5 +1,9 @@
import { routeProviderFetch } from "./fixtures/provider-route.mjs";
import { expect, test } from "bun:test";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createEvaluationCache } from "../packages/core/src/cache";
import { createEvaluator, EvaluationFailure } from "../packages/core/src/evaluator";
test("Jev uses native state and validated boolean probabilities through real HTTP", async () => {
@@ -435,6 +439,121 @@ for (const kind of ["cancelled", "authentication"] as const)
}
});
+test("a custom provider uses its saved base URL and model through the same protocol", async () => {
+ const observed: Array<{ path: string; authorization: string; body: Record<string, unknown> }> =
+ [];
+ const server = Bun.serve({
+ port: 0,
+ async fetch(request) {
+ observed.push({
+ path: new URL(request.url).pathname,
+ authorization: request.headers.get("authorization") ?? "",
+ body: (await request.json()) as Record<string, unknown>,
+ });
+ return Response.json({ answers: { q: { type: "noul", noul: 0.7 } } });
+ },
+ });
+ try {
+ const evaluator = createEvaluator({
+ apiKey: "fixture-key",
+ provider: "custom",
+ baseURL: `http://127.0.0.1:${server.port}/gateway/v1`,
+ model: "gateway/jev-2",
+ signal: new AbortController().signal,
+ });
+ expect(
+ await evaluator.evaluate({
+ state: "test",
+ questions: { q: { type: "boolean", instructions: "Relevant?" } },
+ }),
+ ).toEqual({ q: 0.7 });
+ expect(observed).toEqual([
+ {
+ path: "/gateway/v1/systemone",
+ authorization: "Bearer fixture-key",
+ body: {
+ model: "gateway/jev-2",
+ state: "test",
+ questions: { q: { type: "noul", instructions: "Relevant?" } },
+ },
+ },
+ ]);
+ } finally {
+ server.stop(true);
+ }
+});
+
+test("custom cache identity keeps endpoints and models separate from presets", async () => {
+ const models: string[] = [];
+ const server = Bun.serve({
+ port: 0,
+ async fetch(request) {
+ const body = (await request.json()) as { model: string };
+ models.push(body.model);
+ return Response.json({ answers: { q: { type: "noul", noul: 0.6 } } });
+ },
+ });
+ const directory = await mkdtemp(join(tmpdir(), "jevgrep-custom-cache-"));
+ try {
+ const request = {
+ state: "test",
+ questions: { q: { type: "boolean" as const, instructions: "Relevant?" } },
+ };
+ const signal = new AbortController().signal;
+ const origin = `http://127.0.0.1:${server.port}`;
+ const evaluator = (options: Record<string, unknown>) =>
+ createEvaluator({
+ apiKey: "fixture-key",
+ signal,
+ cache: createEvaluationCache({ directory }),
+ ...options,
+ } as Parameters<typeof createEvaluator>[0]);
+
+ expect(
+ await evaluator({
+ provider: "vercel",
+ fetch: routeProviderFetch(fetch, origin),
+ }).evaluate(request),
+ ).toEqual({ q: 0.6 });
+ expect(
+ await evaluator({
+ provider: "custom",
+ baseURL: `${origin}/gateway/v1`,
+ model: "gateway/jev-2",
+ }).evaluate(request),
+ ).toEqual({ q: 0.6 });
+ expect(models).toEqual(["typesafe-ai/jev", "gateway/jev-2"]);
+
+ expect(
+ await evaluator({
+ provider: "custom",
+ baseURL: `${origin}/gateway/v1`,
+ model: "gateway/jev-2",
+ }).evaluate(request),
+ ).toEqual({ q: 0.6 });
+ expect(models).toEqual(["typesafe-ai/jev", "gateway/jev-2"]);
+
+ expect(
+ await evaluator({
+ provider: "custom",
+ baseURL: `${origin}/gateway/v1`,
+ model: "gateway/jev-3",
+ }).evaluate(request),
+ ).toEqual({ q: 0.6 });
+ expect(
+ await evaluator({
+ provider: "custom",
+ baseURL: `${origin}/other/v1`,
+ model: "gateway/jev-2",
+ }).evaluate(request),
+ ).toEqual({ q: 0.6 });
+ expect(models).toEqual(["typesafe-ai/jev", "gateway/jev-2", "gateway/jev-3", "gateway/jev-2"]);
+ } finally {
+ server.stop(true);
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
test("native token pacing preserves concurrent small calls and excludes queue time from timeout", async () => {
const arrivals: Array<{ at: number; tokens: number }> = [];
let active = 0;