Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(installer): list a BYOK endpoint's models and pass check failures through

LeoXinga6a894b20154
diff --git a/apps/linger-installer/src/main.ts b/apps/linger-installer/src/main.ts
index 4c2812be..c749bd17 100644
--- a/apps/linger-installer/src/main.ts
+++ b/apps/linger-installer/src/main.ts
@@ -17,7 +17,7 @@ export function parseInstallerArguments(args: string[]) {
resume?: boolean;
inspect?: boolean;
inspectTarget?: string;
- checkByok?: boolean;
+ byokCommand?: "check" | "models";
userKeys?: boolean;
migrate?: boolean;
stop?: boolean;
@@ -39,8 +39,8 @@ export function parseInstallerArguments(args: string[]) {
options.inspect = true;
continue;
}
- if (flag === "--check-byok") {
- options.checkByok = true;
+ if (flag === "--check-byok" || flag === "--list-byok-models") {
+ options.byokCommand = flag === "--check-byok" ? "check" : "models";
continue;
}
if (flag === "--migrate") {
@@ -94,7 +94,7 @@ export function parseInstallerArguments(args: string[]) {
if (
!options.sourceRepo &&
!options.inspect &&
- !options.checkByok &&
+ !options.byokCommand &&
!options.userKeys &&
!options.migrate &&
!options.stop &&
@@ -253,24 +253,44 @@ async function userKeys(options: ReturnType<typeof parseInstallerArguments>) {
process.exit("error" in outcome ? 1 : 0),
);
}
-async function checkByok(options: ReturnType<typeof parseInstallerArguments>) {
+// Headless BYOK endpoint check or model listing for the desktop setup page:
+// the endpoint and key on stdin, one JSON line on stdout.
+async function byokEndpointCommand(
+ options: ReturnType<typeof parseInstallerArguments>,
+ command: "check" | "models",
+) {
let input = "";
for await (const chunk of process.stdin) input += String(chunk);
- const { checkByokEndpoint, validateByokConfiguration } =
- await import("@linger/local-installation/byok-source");
+ const byok = await import("@linger/local-installation/byok-source");
try {
- const config = validateByokConfiguration(JSON.parse(input));
- const result = await checkByokEndpoint(
- options.home,
- config,
- AbortSignal.timeout(45_000),
- );
+ const value: unknown = JSON.parse(input);
+ const result =
+ command === "check"
+ ? await byok.checkByokEndpoint(
+ options.home,
+ byok.validateByokConfiguration(value),
+ AbortSignal.timeout(45_000),
+ )
+ : await byok.listByokModels(
+ options.home,
+ byok.validateByokEndpoint(value),
+ AbortSignal.timeout(30_000),
+ );
process.stdout.write(`${JSON.stringify(result)}\n`, () => process.exit(0));
} catch (error) {
const message =
- error instanceof Error ? error.message : "Could not check BYOK endpoint.";
- process.stdout.write(`${JSON.stringify({ ok: false, message })}\n`, () =>
- process.exit(1),
+ error instanceof Error
+ ? error.message
+ : "Could not reach the BYOK endpoint.";
+ const code =
+ error instanceof Error &&
+ "code" in error &&
+ typeof error.code === "string"
+ ? error.code
+ : undefined;
+ process.stdout.write(
+ `${JSON.stringify({ ok: false, message, ...(code ? { code } : {}) })}\n`,
+ () => process.exit(1),
);
}
}
@@ -422,7 +442,8 @@ if (
process.exit(0),
);
else if (options?.userKeys) await userKeys(options);
- else if (options?.checkByok) await checkByok(options);
+ else if (options?.byokCommand)
+ await byokEndpointCommand(options, options.byokCommand);
else if (options?.inspect) await inspect(options);
else if (options?.resume) await resume(options);
else if (options) await serve(options).catch(failedToStart);
diff --git a/apps/linger-installer/src/server/server.ts b/apps/linger-installer/src/server/server.ts
index 9822efb7..a8f97940 100644
--- a/apps/linger-installer/src/server/server.ts
+++ b/apps/linger-installer/src/server/server.ts
@@ -18,7 +18,11 @@ import {
validateLocalModelsAuthority,
} from "./validation.js";
import { checkModel, openLocalTarget } from "./platform.js";
-import { checkByokEndpoint } from "@linger/local-installation/byok-source";
+import {
+ checkByokEndpoint,
+ listByokModels,
+ validateByokEndpoint,
+} from "@linger/local-installation/byok-source";
import { checkRuntimeModel } from "@linger/local-installation/managed-codex";
export interface ServerOptions {
home: string;
@@ -412,14 +416,52 @@ export async function startInstallerServer(options: ServerOptions) {
}
return;
}
- if (url.pathname === "/api/byok/check" && method === "POST") {
- const byok = validateByok(await body(req));
- const checked = await checkByokEndpoint(
- options.home,
- byok,
- AbortSignal.timeout(45_000),
- );
- json(res, 200, checked);
+ if (
+ (url.pathname === "/api/byok/check" ||
+ url.pathname === "/api/byok/models") &&
+ method === "POST"
+ ) {
+ const input = await body(req);
+ const check = url.pathname === "/api/byok/check";
+ // Validate before the try, so a malformed body stays a plain 400.
+ const run = check
+ ? (() => {
+ const byok = validateByok(input);
+ return () =>
+ checkByokEndpoint(
+ options.home,
+ byok,
+ AbortSignal.timeout(45_000),
+ );
+ })()
+ : (() => {
+ const endpoint = validateByokEndpoint(input);
+ return () =>
+ listByokModels(
+ options.home,
+ endpoint,
+ AbortSignal.timeout(30_000),
+ );
+ })();
+ try {
+ json(res, 200, await run());
+ } catch (failure) {
+ // localmodels names the address it tried and its HTTP status.
+ const code =
+ failure instanceof Error &&
+ "code" in failure &&
+ typeof failure.code === "string"
+ ? failure.code
+ : "BYOK_CHECK_FAILED";
+ error(
+ res,
+ 400,
+ code,
+ failure instanceof Error
+ ? failure.message
+ : "Could not reach the BYOK endpoint.",
+ );
+ }
return;
}
if (url.pathname === "/api/runtime-login" && method === "DELETE") {
diff --git a/apps/linger-installer/src/server/validation.test.ts b/apps/linger-installer/src/server/validation.test.ts
index a78c7ae7..d1f76483 100644
--- a/apps/linger-installer/src/server/validation.test.ts
+++ b/apps/linger-installer/src/server/validation.test.ts
@@ -58,22 +58,40 @@ test.each([
test("validates BYOK check and installation inputs", () => {
expect(
validateByok({
- baseUrl: "https://api.openai.com/v1/",
+ baseUrl: "https://api.openai.com/",
+ path: "/v1",
+ endpoint: "/responses",
+ protocol: "openai-responses",
apiKey: "sk-test",
modelId: "gpt-5.4",
runtime: "codex",
}),
).toMatchObject({
- baseUrl: "https://api.openai.com/v1",
+ baseUrl: "https://api.openai.com",
+ path: "/v1",
+ endpoint: "/responses",
+ protocol: "openai-responses",
modelId: "gpt-5.4",
runtime: "codex",
});
+ expect(() =>
+ validateByok({
+ baseUrl: "https://api.openai.com",
+ path: "v1",
+ endpoint: "/responses",
+ protocol: "openai-responses",
+ modelId: "gpt-5.4",
+ }),
+ ).toThrow();
expect(
validateInput({
instance: "default",
setupChoice: "claude",
byok: {
baseUrl: "https://api.anthropic.com",
+ path: "/v1",
+ endpoint: "/messages",
+ protocol: "anthropic",
apiKey: "sk-ant-test",
modelId: "claude-sonnet-4-6",
},
@@ -91,7 +109,10 @@ test("validates BYOK check and installation inputs", () => {
instance: "default",
setupChoice: "local-models",
byok: {
- baseUrl: "https://api.openai.com/v1",
+ baseUrl: "https://api.openai.com",
+ path: "/v1",
+ endpoint: "/chat/completions",
+ protocol: "openai-chat",
modelId: "gpt-5.4",
},
}),
diff --git a/contracts/generated/typescript/src/generated/linger-installer/types.ts b/contracts/generated/typescript/src/generated/linger-installer/types.ts
index 61873d2d..8c231d1f 100644
--- a/contracts/generated/typescript/src/generated/linger-installer/types.ts
+++ b/contracts/generated/typescript/src/generated/linger-installer/types.ts
@@ -452,6 +452,11 @@ export interface components {
apiKey?: string;
modelId: string;
contextWindow?: number;
+ /**
+ * @description The Runtime BYOK is mounted for when the job applies it.
+ * @enum {string}
+ */
+ runtime?: "claude" | "codex" | "pi";
};
ByokModelReport: {
url: string;
diff --git a/contracts/openapi/linger-installer/openapi.yaml b/contracts/openapi/linger-installer/openapi.yaml
index e0bffdb0..72d30dd7 100644
--- a/contracts/openapi/linger-installer/openapi.yaml
+++ b/contracts/openapi/linger-installer/openapi.yaml
@@ -736,6 +736,10 @@ components:
type: integer
minimum: 1
maximum: 2147483647
+ runtime:
+ description: The Runtime BYOK is mounted for when the job applies it.
+ type: string
+ enum: [claude, codex, pi]
ByokModelReport:
type: object
additionalProperties: false
diff --git a/packages/local-installation/src/byok-source.test.ts b/packages/local-installation/src/byok-source.test.ts
index df47bc98..9b7be6e0 100644
--- a/packages/local-installation/src/byok-source.test.ts
+++ b/packages/local-installation/src/byok-source.test.ts
@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
checkByokEndpoint,
isAllowedByokUrl,
+ listByokModels,
prepareByokNativeRuntime,
prepareByokRuntime,
applyNativeSource,
@@ -39,10 +40,35 @@ describe("isAllowedByokUrl", () => {
expect(isAllowedByokUrl("http://100.88.1.5:11434/v1")).toBe(true);
expect(
validateByokConfiguration({
- baseUrl: "https://api.openai.com/v1/",
+ baseUrl: "https://api.openai.com/",
+ path: "/v1",
+ endpoint: "/responses",
+ protocol: "openai-responses",
modelId: "gpt-5.4",
}).baseUrl,
- ).toBe("https://api.openai.com/v1");
+ ).toBe("https://api.openai.com");
+ });
+
+ it("accepts an empty path or endpoint and refuses one that could leave the base URL", () => {
+ const base = {
+ baseUrl: "https://gw.example.com/full",
+ path: "",
+ endpoint: "",
+ protocol: "anthropic",
+ modelId: "m",
+ };
+ expect(validateByokConfiguration(base)).toMatchObject({
+ path: "",
+ endpoint: "",
+ });
+ for (const bad of [
+ { path: "v1" },
+ { path: "/v1/" },
+ { endpoint: "//evil.example.com/x" },
+ { endpoint: "/chat?key=1" },
+ { protocol: "gemini" },
+ ])
+ expect(() => validateByokConfiguration({ ...base, ...bad })).toThrow();
});
it("blocks link-local metadata, public HTTP, and URL credentials", () => {
@@ -71,7 +97,7 @@ describe("BYOK localmodels integration", () => {
stdout: JSON.stringify({
ok: true,
protocol: "openai-responses",
- base_url: "https://api.example.com/v1",
+ url: "https://api.example.com/v1/responses",
model_id: "gpt-5.4",
context_window: 200_000,
}),
@@ -82,7 +108,10 @@ describe("BYOK localmodels integration", () => {
const report = await checkByokEndpoint(
home,
{
- baseUrl: "https://api.example.com/v1",
+ baseUrl: "https://api.example.com",
+ path: "/v1",
+ endpoint: "/responses",
+ protocol: "openai-responses",
apiKey: "sk-private-secret",
modelId: "gpt-5.4",
runtime: "codex",
@@ -93,25 +122,106 @@ describe("BYOK localmodels integration", () => {
expect(report).toEqual({
ok: true,
protocol: "openai-responses",
- baseUrl: "https://api.example.com/v1",
+ url: "https://api.example.com/v1/responses",
modelId: "gpt-5.4",
contextWindow: 200_000,
});
expect(calls).toHaveLength(1);
expect(calls[0]!.args.join(" ")).not.toContain("sk-private-secret");
expect(calls[0]!.args).toContain("--config-stdin");
- expect(calls[0]!.args.join(" ")).toContain("--runtime codex");
- expect(JSON.parse(calls[0]!.input!)).toMatchObject({
+ expect(calls[0]!.args).not.toContain("--runtime");
+ expect(JSON.parse(calls[0]!.input!)).toEqual({
+ baseUrl: "https://api.example.com",
+ path: "/v1",
+ endpoint: "/responses",
+ protocol: "openai-responses",
apiKey: "sk-private-secret",
modelId: "gpt-5.4",
});
});
+ it("lists models at the endpoint's model address with the key on stdin", async () => {
+ const calls: { args: string[]; input?: string }[] = [];
+ const listing = await listByokModels(
+ await makeHome(),
+ {
+ baseUrl: "https://open.bigmodel.cn",
+ path: "/api/paas/v4",
+ endpoint: "/chat/completions",
+ protocol: "openai-chat",
+ apiKey: "sk-list-secret",
+ },
+ new AbortController().signal,
+ {
+ localmodels: async (_home, args, options = {}) => {
+ calls.push({ args, input: options.input });
+ return {
+ code: 0,
+ stdout: JSON.stringify({
+ ok: true,
+ url: "https://open.bigmodel.cn/api/paas/v4/models",
+ models: [
+ { id: "glm-4.6", name: "GLM 4.6", context_window: 131_072 },
+ { id: "glm-4.5", name: null, context_window: null },
+ ],
+ }),
+ stderr: "",
+ };
+ },
+ },
+ );
+ expect(listing).toEqual({
+ url: "https://open.bigmodel.cn/api/paas/v4/models",
+ models: [
+ { id: "glm-4.6", name: "GLM 4.6", contextWindow: 131_072 },
+ { id: "glm-4.5" },
+ ],
+ });
+ expect(calls[0]!.args).toEqual([
+ "source",
+ "models",
+ "--config-stdin",
+ "--json",
+ ]);
+ expect(JSON.parse(calls[0]!.input!)).toMatchObject({
+ path: "/api/paas/v4",
+ apiKey: "sk-list-secret",
+ });
+
+ await expect(
+ listByokModels(
+ await makeHome(),
+ {
+ baseUrl: "https://open.bigmodel.cn",
+ path: "/api/paas/v4",
+ endpoint: "/chat/completions",
+ protocol: "openai-chat",
+ },
+ new AbortController().signal,
+ {
+ localmodels: async () => ({
+ code: 1,
+ stdout: JSON.stringify({
+ ok: false,
+ code: "BYOK_NOT_FOUND",
+ message:
+ "https://open.bigmodel.cn/api/paas/v4/models returned HTTP 404.",
+ }),
+ stderr: "",
+ }),
+ },
+ ),
+ ).rejects.toMatchObject({ code: "BYOK_NOT_FOUND" });
+ });
+
it("mounts BYOK on Bifrost even when native runtime lacks vendor OAuth", async () => {
const home = await makeHome();
const outcome = await prepareByokRuntime(
{
baseUrl: "https://api.anthropic.com",
+ path: "/v1",
+ endpoint: "/messages",
+ protocol: "anthropic",
apiKey: "sk-ant-test",
modelId: "claude-sonnet-4-6",
runtime: "claude",
@@ -229,7 +339,10 @@ describe("BYOK localmodels integration", () => {
let rejectApply!: (error: Error) => void;
const promise = prepareByokRuntime(
{
- baseUrl: "https://api.example.com/v1",
+ baseUrl: "https://api.example.com",
+ path: "/v1",
+ endpoint: "/responses",
+ protocol: "openai-responses",
modelId: "gpt-4o",
runtime: "codex",
},
@@ -599,7 +712,10 @@ describe("source apply timeouts and progress", () => {
}));
await prepareByokRuntime(
{
- baseUrl: "https://api.example.com/v1",
+ baseUrl: "https://api.example.com",
+ path: "/v1",
+ endpoint: "/messages",
+ protocol: "anthropic",
apiKey: "sk-test",
modelId: "m",
runtime: "claude",
diff --git a/packages/local-installation/src/byok-source.ts b/packages/local-installation/src/byok-source.ts
index dbfc03db..ed1e5825 100644
--- a/packages/local-installation/src/byok-source.ts
+++ b/packages/local-installation/src/byok-source.ts
@@ -14,9 +14,19 @@ import type { InstallOutcome, InstallerEvent } from "./events.js";
export type ByokProtocol = "openai-chat" | "openai-responses" | "anthropic";
-export interface ByokConfiguration {
+/**
+ * Requests go to baseUrl + path + endpoint in protocol, and models are listed
+ * at baseUrl + path + /models.
+ */
+export interface ByokEndpoint {
baseUrl: string;
+ path: string;
+ endpoint: string;
+ protocol: ByokProtocol;
apiKey?: string;
+}
+
+export interface ByokConfiguration extends ByokEndpoint {
modelId: string;
contextWindow?: number;
runtime?: NativeRuntime;
@@ -25,11 +35,16 @@ export interface ByokConfiguration {
export interface ByokCheckOutcome {
ok: true;
protocol: ByokProtocol;
- baseUrl: string;
+ url: string;
modelId: string;
contextWindow: number;
}
+export interface ByokModelListing {
+ url: string;
+ models: { id: string; name?: string; contextWindow?: number }[];
+}
+
interface StoredModelSource {
schema: "localmodels.model-source/v1";
mode: "local" | "subscription" | "byok";
@@ -77,17 +92,31 @@ export function isAllowedByokUrl(raw: string): boolean {
}
}
-export function validateByokConfiguration(value: unknown): ByokConfiguration {
+// Empty, or whole segments each led by one slash, so a path or endpoint can
+// only extend the base URL's path.
+const BYOK_URL_PATH = /^(?:\/[^/?#\s\\]+)*$/u;
+
+function isByokProtocol(value: unknown): value is ByokProtocol {
+ return (
+ value === "openai-chat" ||
+ value === "openai-responses" ||
+ value === "anthropic"
+ );
+}
+
+function byokRecord(
+ value: unknown,
+ keys: readonly string[],
+): Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value))
throw new Error("Invalid BYOK configuration.");
const record = value as Record<string, unknown>;
for (const key of Object.keys(record))
- if (
- !["baseUrl", "apiKey", "modelId", "contextWindow", "runtime"].includes(
- key,
- )
- )
- throw new Error("Invalid BYOK configuration.");
+ if (!keys.includes(key)) throw new Error("Invalid BYOK configuration.");
+ return record;
+}
+
+function byokEndpointFields(record: Record<string, unknown>): ByokEndpoint {
if (
typeof record.baseUrl !== "string" ||
record.baseUrl.length > 2048 ||
@@ -96,11 +125,18 @@ export function validateByokConfiguration(value: unknown): ByokConfiguration {
throw new Error(
"Endpoint URL must use HTTPS, or HTTP on localhost / a private network.",
);
- if (
- typeof record.modelId !== "string" ||
- !/^[-a-zA-Z0-9_./:@]{1,256}$/.test(record.modelId.trim())
- )
- throw new Error("Model ID is invalid.");
+ for (const [label, value] of [
+ ["Path", record.path],
+ ["Endpoint", record.endpoint],
+ ] as const)
+ if (
+ typeof value !== "string" ||
+ value.length > 256 ||
+ !BYOK_URL_PATH.test(value)
+ )
+ throw new Error(`${label} must be empty or a path such as /v1.`);
+ if (!isByokProtocol(record.protocol))
+ throw new Error("Invalid BYOK wire format.");
const apiKey = record.apiKey;
if (
apiKey !== undefined &&
@@ -109,6 +145,40 @@ export function validateByokConfiguration(value: unknown): ByokConfiguration {
[...apiKey].some((c) => c.charCodeAt(0) <= 32 || c.charCodeAt(0) === 127))
)
throw new Error("API key format is invalid.");
+ return {
+ baseUrl: record.baseUrl.trim().replace(/\/+$/, ""),
+ path: record.path as string,
+ endpoint: record.endpoint as string,
+ protocol: record.protocol,
+ ...(apiKey !== undefined ? { apiKey } : {}),
+ };
+}
+
+const BYOK_ENDPOINT_KEYS = [
+ "baseUrl",
+ "path",
+ "endpoint",
+ "protocol",
+ "apiKey",
+] as const;
+
+export function validateByokEndpoint(value: unknown): ByokEndpoint {
+ return byokEndpointFields(byokRecord(value, BYOK_ENDPOINT_KEYS));
+}
+
+export function validateByokConfiguration(value: unknown): ByokConfiguration {
+ const record = byokRecord(value, [
+ ...BYOK_ENDPOINT_KEYS,
+ "modelId",
+ "contextWindow",
+ "runtime",
+ ]);
+ const endpoint = byokEndpointFields(record);
+ if (
+ typeof record.modelId !== "string" ||
+ !/^[-a-zA-Z0-9_./:@]{1,256}$/.test(record.modelId.trim())
+ )
+ throw new Error("Model ID is invalid.");
const contextWindow = record.contextWindow;
if (
contextWindow !== undefined &&
@@ -126,8 +196,7 @@ export function validateByokConfiguration(value: unknown): ByokConfiguration {
)
throw new Error("Invalid BYOK runtime selection.");
return {
- baseUrl: record.baseUrl.trim().replace(/\/+$/, ""),
- ...(apiKey !== undefined ? { apiKey } : {}),
+ ...endpoint,
modelId: record.modelId.trim(),
...(contextWindow !== undefined
? { contextWindow: Number(contextWindow) }
@@ -136,30 +205,45 @@ export function validateByokConfiguration(value: unknown): ByokConfiguration {
};
}
-// The API key travels on stdin, never in argv.
-function byokStdin(config: ByokConfiguration): string {
+// The API key travels on stdin, never in argv. An empty path or endpoint is
+// sent too: it appends nothing, which localmodels tells apart from a missing
+// field.
+function byokStdin(config: ByokEndpoint & Partial<ByokConfiguration>): string {
return JSON.stringify({
baseUrl: config.baseUrl,
+ path: config.path,
+ endpoint: config.endpoint,
+ protocol: config.protocol,
...(config.apiKey !== undefined ? { apiKey: config.apiKey } : {}),
- modelId: config.modelId,
+ ...(config.modelId !== undefined ? { modelId: config.modelId } : {}),
...(config.contextWindow !== undefined
? { contextWindow: config.contextWindow }
: {}),
});
}
-function isByokProtocol(value: unknown): value is ByokProtocol {
- return (
- value === "openai-chat" ||
- value === "openai-responses" ||
- value === "anthropic"
- );
+function endpointFailure(
+ parsed: Record<string, unknown> | undefined,
+ fallback: string,
+ fallbackCode: string,
+): Error {
+ const message =
+ typeof parsed?.message === "string" && parsed.message
+ ? parsed.message
+ : fallback;
+ const code = typeof parsed?.code === "string" ? parsed.code : fallbackCode;
+ return Object.assign(new Error(message), { code });
}
-/**
- * Verifies the endpoint from this computer and finds the wire format it
- * answers, trying the runtime's own format first.
- */
+function parseToolJson(stdout: string): Record<string, unknown> | undefined {
+ try {
+ return JSON.parse(stdout) as Record<string, unknown>;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Sends one request to the endpoint's address from this computer. */
export async function checkByokEndpoint(
home: string,
config: ByokConfiguration,
@@ -170,40 +254,25 @@ export async function checkByokEndpoint(
signal.throwIfAborted();
const result = await (dependencies.localmodels ?? runLocalmodels)(
home,
- [
- "source",
- "check",
- "--config-stdin",
- "--runtime",
- validated.runtime ?? "claude",
- "--json",
- ],
+ ["source", "check", "--config-stdin", "--json"],
{ signal, timeoutMs: 45_000, input: byokStdin(validated) },
);
- let parsed: Record<string, unknown> | undefined;
- try {
- parsed = JSON.parse(result.stdout) as Record<string, unknown>;
- } catch {
- parsed = undefined;
- }
+ const parsed = parseToolJson(result.stdout);
if (
result.code !== 0 ||
parsed?.ok !== true ||
- !isByokProtocol(parsed.protocol)
- ) {
- const message =
- typeof parsed?.message === "string" && parsed.message
- ? parsed.message
- : "Could not verify the BYOK endpoint. Check the URL, API key, model ID and network.";
- const code =
- typeof parsed?.code === "string" ? parsed.code : "BYOK_CHECK_FAILED";
- throw Object.assign(new Error(message), { code });
- }
+ !isByokProtocol(parsed.protocol) ||
+ typeof parsed.url !== "string"
+ )
+ throw endpointFailure(
+ parsed,
+ "Could not verify the BYOK endpoint. Check the URL, API key, model ID and network.",
+ "BYOK_CHECK_FAILED",
+ );
return {
ok: true,
protocol: parsed.protocol,
- baseUrl:
- typeof parsed.base_url === "string" ? parsed.base_url : validated.baseUrl,
+ url: parsed.url,
modelId:
typeof parsed.model_id === "string" ? parsed.model_id : validated.modelId,
contextWindow:
@@ -213,6 +282,48 @@ export async function checkByokEndpoint(
};
}
+/** Lists the models the endpoint serves at baseUrl + path + /models. */
+export async function listByokModels(
+ home: string,
+ endpoint: ByokEndpoint,
+ signal: AbortSignal,
+ dependencies: { localmodels?: typeof runLocalmodels } = {},
+): Promise<ByokModelListing> {
+ const validated = validateByokEndpoint(endpoint);
+ signal.throwIfAborted();
+ const result = await (dependencies.localmodels ?? runLocalmodels)(
+ home,
+ ["source", "models", "--config-stdin", "--json"],
+ { signal, timeoutMs: 30_000, input: byokStdin(validated) },
+ );
+ const parsed = parseToolJson(result.stdout);
+ if (
+ result.code !== 0 ||
+ parsed?.ok !== true ||
+ typeof parsed.url !== "string" ||
+ !Array.isArray(parsed.models)
+ )
+ throw endpointFailure(
+ parsed,
+ "Could not list the endpoint's models. Check the URL, API key and network.",
+ "BYOK_MODELS_FAILED",
+ );
+ const models: ByokModelListing["models"] = [];
+ for (const row of parsed.models as unknown[]) {
+ if (!row || typeof row !== "object") continue;
+ const { id, name, context_window } = row as Record<string, unknown>;
+ if (typeof id !== "string" || !id) continue;
+ models.push({
+ id,
+ ...(typeof name === "string" && name ? { name } : {}),
+ ...(typeof context_window === "number" && context_window > 0
+ ? { contextWindow: context_window }
+ : {}),
+ });
+ }
+ return { url: parsed.url, models };
+}
+
// The kit's longest silent span is a BYOK apply with Bifrost already
// installed: the endpoint probe (up to about 35 s) and then Bifrost's health
// wait (up to 180 s), with no output between them. A download may run longer
diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.ts
index 59d7e9a9..bbdeadeb 100644
--- a/packages/local-installation/src/native-source-flow.test.ts
+++ b/packages/local-installation/src/native-source-flow.test.ts
@@ -1334,7 +1334,10 @@ test.each(["returned", "thrown"])(
...f,
name: "native-flow",
byok: {
- baseUrl: "https://example.test/v1",
+ baseUrl: "https://example.test",
+ path: "/v1",
+ endpoint: "/chat/completions",
+ protocol: "openai-chat",
modelId: "test",
apiKey: "test-key",
runtime: "pi",