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.

refactor(byok): share endpoint path and protocol helpers in service-kit

LeoXing1e6ecbbae253
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 68ab8554..5cda3e12 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -14,6 +14,7 @@
},
"dependencies": {
"@linger/local-installation": "workspace:*",
+ "@linger/service-kit": "workspace:*",
"@linger/wire-contracts": "workspace:*",
"yazl": "3.3.1",
"zod": "4.4.3"
diff --git a/apps/desktop/src/main/setup-command.ts b/apps/desktop/src/main/setup-command.ts
index 2e0a7825..5495b5c1 100644
--- a/apps/desktop/src/main/setup-command.ts
+++ b/apps/desktop/src/main/setup-command.ts
@@ -1,3 +1,7 @@
+import {
+ BYOK_URL_PATH_PATTERN,
+ MAX_BYOK_URL_PATH,
+} from "@linger/service-kit/byok-endpoint";
import { z } from "zod";
import type { SetupCommand } from "../shared/setup.js";
@@ -13,8 +17,8 @@ const providerKey = z
// only extend the base URL's path.
const byokUrlPath = z
.string()
- .max(256)
- .regex(/^(\/[^/?#\s\\]+)*$/, "Invalid path");
+ .max(MAX_BYOK_URL_PATH)
+ .regex(BYOK_URL_PATH_PATTERN, "Invalid path");
const byokEndpointFields = {
baseUrl: z.string().trim().min(1).max(2048),
diff --git a/apps/desktop/src/shell/setup.html b/apps/desktop/src/shell/setup.html
index bd63a759..cffc0645 100644
--- a/apps/desktop/src/shell/setup.html
+++ b/apps/desktop/src/shell/setup.html
@@ -2530,6 +2530,8 @@
// is sent. The wire format follows the end of that address, else the
// runtime's own, so Bifrost passes the runtime's requests through.
// Nothing probes: Test sends one request to that one address.
+ // Keep these format endings, runtime defaults and path validation in
+ // sync with packages/service-kit/src/byok-endpoint.ts (source of truth).
const BYOK_FORMATS = {
"openai-chat": {
suffix: "/chat/completions",
diff --git a/apps/linger-installer/package.json b/apps/linger-installer/package.json
index fcd2c0bb..939c75f4 100644
--- a/apps/linger-installer/package.json
+++ b/apps/linger-installer/package.json
@@ -12,6 +12,7 @@
},
"dependencies": {
"@linger/local-installation": "workspace:*",
+ "@linger/service-kit": "workspace:*",
"@linger/wire-contracts": "workspace:*",
"react": "19.2.7",
"react-dom": "19.2.7"
diff --git a/apps/linger-installer/src/web/ByokPanel.tsx b/apps/linger-installer/src/web/ByokPanel.tsx
index 64aaf390..f74aca10 100644
--- a/apps/linger-installer/src/web/ByokPanel.tsx
+++ b/apps/linger-installer/src/web/ByokPanel.tsx
@@ -8,6 +8,16 @@ import {
type ReactNode,
type SetStateAction,
} from "react";
+import {
+ BYOK_PROTOCOL_ENDPOINTS,
+ DEFAULT_BYOK_PATH,
+ byokProtocolFor,
+ defaultByokEndpoint,
+ normalizeByokBaseUrl,
+ normalizeByokPath,
+ validByokPath,
+ type ByokRuntime,
+} from "@linger/service-kit/byok-endpoint";
import type { components } from "@linger/wire-contracts/linger-installer/types";
import { request } from "./api.js";
@@ -15,7 +25,6 @@ type ByokProtocol = components["schemas"]["ByokProtocol"];
type ByokEndpoint = components["schemas"]["ByokEndpoint"];
type ByokCheckReport = components["schemas"]["ByokCheckReport"];
type ByokModelReport = components["schemas"]["ByokModelReport"];
-type ByokRuntime = "claude" | "codex" | "pi";
/** What the person typed. A null endpoint follows the runtime's default. */
export interface ByokDraft {
@@ -32,24 +41,22 @@ const RUNTIME_LABELS: Record<ByokRuntime, string> = {
codex: "Codex",
pi: "Pi",
};
-// Each runtime's own wire format, so the gateway forwards its requests untranslated.
-const RUNTIME_PROTOCOL: Record<ByokRuntime, ByokProtocol> = {
- claude: "anthropic",
- codex: "openai-responses",
- pi: "openai-chat",
-};
const FORMATS: Record<ByokProtocol, { ending: string; label: string }> = {
"openai-chat": {
- ending: "/chat/completions",
+ ending: BYOK_PROTOCOL_ENDPOINTS["openai-chat"],
label: "OpenAI Chat Completions",
},
- "openai-responses": { ending: "/responses", label: "OpenAI Responses" },
- anthropic: { ending: "/messages", label: "Anthropic Messages" },
+ "openai-responses": {
+ ending: BYOK_PROTOCOL_ENDPOINTS["openai-responses"],
+ label: "OpenAI Responses",
+ },
+ anthropic: {
+ ending: BYOK_PROTOCOL_ENDPOINTS.anthropic,
+ label: "Anthropic Messages",
+ },
};
-const DEFAULT_PATH = "/v1";
-const URL_PATH = /^(\/[^/?#\s\\]+)*$/;
const PATH_OPTIONS: ComboItem[] = [
- { value: DEFAULT_PATH, label: "Most providers", tag: "Default" },
+ { value: DEFAULT_BYOK_PATH, label: "Most providers", tag: "Default" },
{ value: "/api/paas/v4", label: "Zhipu GLM (base https://open.bigmodel.cn)" },
{ value: "/api/v3", label: "Volcano Engine Ark" },
{ value: "/v1beta/openai", label: "Gemini" },
@@ -59,49 +66,33 @@ const PATH_OPTIONS: ComboItem[] = [
export const emptyByokDraft: ByokDraft = {
runtime: "claude",
baseUrl: "",
- path: DEFAULT_PATH,
+ path: DEFAULT_BYOK_PATH,
endpoint: null,
apiKey: "",
modelId: "",
};
-function normalizePath(value: string): string {
- const trimmed = value.trim().replace(/\/+$/, "");
- return trimmed && !trimmed.startsWith("/") ? `/${trimmed}` : trimmed;
-}
-function defaultEndpoint(runtime: ByokRuntime): string {
- return FORMATS[RUNTIME_PROTOCOL[runtime]].ending;
-}
function requestUrl(endpoint: ByokEndpoint): string {
return endpoint.baseUrl + endpoint.path + endpoint.endpoint;
}
function modelsUrl(endpoint: ByokEndpoint): string {
return `${endpoint.baseUrl}${endpoint.path}/models`;
}
-// The wire format follows the end of the address alone; any other ending uses the runtime's own.
-function formatOf(draft: ByokDraft, url: string) {
- const fromUrl = (Object.keys(FORMATS) as ByokProtocol[]).find((protocol) =>
- url.endsWith(FORMATS[protocol].ending),
- );
- return {
- protocol: fromUrl ?? RUNTIME_PROTOCOL[draft.runtime],
- fromUrl: Boolean(fromUrl),
- };
-}
/** The address and key the draft names, as the installer API takes them. */
export function byokEndpoint(draft: ByokDraft): ByokEndpoint {
- const baseUrl = draft.baseUrl.trim().replace(/\/+$/, "");
- const path = normalizePath(draft.path);
- const endpoint = normalizePath(
- draft.endpoint ?? defaultEndpoint(draft.runtime),
+ const baseUrl = normalizeByokBaseUrl(draft.baseUrl);
+ const path = normalizeByokPath(draft.path);
+ const endpoint = normalizeByokPath(
+ draft.endpoint ?? defaultByokEndpoint(draft.runtime),
);
const apiKey = draft.apiKey.trim();
return {
baseUrl,
path,
endpoint,
- protocol: formatOf(draft, baseUrl + path + endpoint).protocol,
+ protocol: byokProtocolFor(baseUrl + path + endpoint, draft.runtime)
+ .protocol,
...(apiKey ? { apiKey } : {}),
};
}
@@ -111,12 +102,12 @@ export function byokAddressProblem(
draft: ByokDraft,
): { field: "base" | "path" | "endpoint"; message: string } | undefined {
const endpoint = byokEndpoint(draft);
- if (!URL_PATH.test(endpoint.path) || endpoint.path.length > 256)
+ if (!validByokPath(endpoint.path))
return {
field: "path",
message: "Path must be empty or a path such as /v1.",
};
- if (!URL_PATH.test(endpoint.endpoint) || endpoint.endpoint.length > 256)
+ if (!validByokPath(endpoint.endpoint))
return {
field: "endpoint",
message: "Endpoint must be empty or a path such as /chat/completions.",
@@ -167,7 +158,7 @@ export function ByokPanel({
const endpoint = byokEndpoint(draft);
const url = requestUrl(endpoint);
- const format = formatOf(draft, url);
+ const format = byokProtocolFor(url, draft.runtime);
const problem = byokAddressProblem(draft);
const hasBase = endpoint.baseUrl !== "";
const hasModel = draft.modelId.trim() !== "";
@@ -256,7 +247,7 @@ export function ByokPanel({
const checking = check?.state === "checking";
const listingNow = listing?.state === "loading";
- const runtimeDefault = defaultEndpoint(draft.runtime);
+ const runtimeDefault = defaultByokEndpoint(draft.runtime);
const sends = (
<>
{"Sends "}
@@ -354,7 +345,7 @@ export function ByokPanel({
setBaseTouched(true);
onDraftChange((current) => ({
...current,
- baseUrl: current.baseUrl.trim().replace(/\/+$/, ""),
+ baseUrl: normalizeByokBaseUrl(current.baseUrl),
}));
}}
/>
@@ -365,7 +356,7 @@ export function ByokPanel({
fit
heading="Path · optional"
value={draft.path}
- isDefault={draft.path === DEFAULT_PATH}
+ isDefault={draft.path === DEFAULT_BYOK_PATH}
items={PATH_OPTIONS}
open={menu === "path"}
onOpenChange={(open) => setMenu(open ? "path" : undefined)}
@@ -375,7 +366,7 @@ export function ByokPanel({
onCommit={() =>
onDraftChange((current) => ({
...current,
- path: normalizePath(current.path),
+ path: normalizeByokPath(current.path),
}))
}
/>
@@ -405,17 +396,17 @@ export function ByokPanel({
change("check", (current) => ({
...current,
endpoint:
- value === defaultEndpoint(current.runtime) ? null : value,
+ value === defaultByokEndpoint(current.runtime) ? null : value,
}))
}
onCommit={() =>
onDraftChange((current) => {
if (current.endpoint === null) return current;
- const value = normalizePath(current.endpoint);
+ const value = normalizeByokPath(current.endpoint);
return {
...current,
endpoint:
- value === defaultEndpoint(current.runtime) ? null : value,
+ value === defaultByokEndpoint(current.runtime) ? null : value,
};
})
}
diff --git a/apps/node-services/src/agent/executor/http/local-computer-http.ts b/apps/node-services/src/agent/executor/http/local-computer-http.ts
index 1a027bdf..ab647fec 100644
--- a/apps/node-services/src/agent/executor/http/local-computer-http.ts
+++ b/apps/node-services/src/agent/executor/http/local-computer-http.ts
@@ -21,6 +21,10 @@ import {
type LocalModelActionCommand,
} from "../../runner-gateway/runner-local-models.js";
import { isRecord } from "@linger/service-kit";
+import {
+ isByokProtocol,
+ validByokPath,
+} from "@linger/service-kit/byok-endpoint";
type LocalComputerHttpStatus = 400 | 404 | 405 | 409 | 410 | 502 | 503;
@@ -349,19 +353,9 @@ const requireModelSourceManagement = (
};
const BYOK_MODEL_ID_PATTERN = /^[-a-zA-Z0-9_./:@]{1,256}$/u;
-// 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_PATTERN = /^(?:\/[^/?#\s\\]+)*$/u;
const isByokUrlPath = (value: unknown): value is string =>
- typeof value === "string" &&
- value.length <= 256 &&
- BYOK_URL_PATH_PATTERN.test(value);
-
-const isByokProtocol = (value: unknown): value is ByokConfigInput["protocol"] =>
- value === "openai-chat" ||
- value === "openai-responses" ||
- value === "anthropic";
+ typeof value === "string" && validByokPath(value);
interface ByokAddress {
readonly base_url: string;
diff --git a/apps/teamhub/internal/app/handlers_model_source.go b/apps/teamhub/internal/app/handlers_model_source.go
index 17adba7d..15efa211 100644
--- a/apps/teamhub/internal/app/handlers_model_source.go
+++ b/apps/teamhub/internal/app/handlers_model_source.go
@@ -408,6 +408,7 @@ func validModelSourceSwitch(request httpapi.ModelSourceSwitchRequest) bool {
// byokURLPathPattern matches a BYOK path or endpoint: empty, or whole
// segments each led by one slash, so it can only extend the base URL's path.
+// Keep in sync with BYOK_URL_PATH_PATTERN in packages/service-kit/src/byok-endpoint.ts.
var byokURLPathPattern = regexp.MustCompile(`^(/[^/?#\s\\]+)*$`)
func validByokAddress(baseURL, path, endpoint string, protocol httpapi.ByokProtocol) bool {
diff --git a/apps/web/src/features/local-models/byok-endpoint.ts b/apps/web/src/features/local-models/byok-endpoint.ts
index 2a8fef4e..680e46c4 100644
--- a/apps/web/src/features/local-models/byok-endpoint.ts
+++ b/apps/web/src/features/local-models/byok-endpoint.ts
@@ -1,24 +1,11 @@
+import {
+ BYOK_PROTOCOL_ENDPOINTS,
+ DEFAULT_BYOK_PATH,
+} from "@linger/service-kit/byok-endpoint";
import type { components } from "@linger/wire-contracts/teamhub-public/types";
type Schemas = components["schemas"];
type ByokProtocol = Schemas["ByokProtocol"];
-type ModelSourceRuntime = Schemas["ModelSourceRuntime"];
-
-/** Each Runtime's own wire format, which Bifrost forwards untranslated. */
-const runtimeProtocols: Record<ModelSourceRuntime, ByokProtocol> = {
- claude: "anthropic",
- codex: "openai-responses",
- pi: "openai-chat",
-};
-
-const protocolEndpoints: Record<ByokProtocol, string> = {
- anthropic: "/messages",
- "openai-chat": "/chat/completions",
- "openai-responses": "/responses",
-};
-
-/** The path most providers serve their API under. */
-export const DEFAULT_BYOK_PATH = "/v1";
/** Paths some providers document; any other path can be typed. */
export const byokPathSuggestions: readonly { label: string; value: string }[] =
@@ -38,52 +25,15 @@ export const byokEndpointSuggestions: readonly {
protocol?: ByokProtocol;
value: string;
}[] = [
- { protocol: "openai-chat", value: protocolEndpoints["openai-chat"] },
+ { protocol: "openai-chat", value: BYOK_PROTOCOL_ENDPOINTS["openai-chat"] },
{
protocol: "openai-responses",
- value: protocolEndpoints["openai-responses"],
+ value: BYOK_PROTOCOL_ENDPOINTS["openai-responses"],
},
- { protocol: "anthropic", value: protocolEndpoints.anthropic },
+ { protocol: "anthropic", value: BYOK_PROTOCOL_ENDPOINTS.anthropic },
{ value: "" },
];
-/** The endpoint a Runtime's requests go to unless the owner picks another. */
-export function defaultByokEndpoint(runtime: ModelSourceRuntime) {
- return protocolEndpoints[runtimeProtocols[runtime]];
-}
-
-const URL_PATH = /^(?:\/[^/?#\s\\]+)*$/u;
-const MAX_URL_PATH = 256;
-
-/** A typed path as it is sent: trimmed, led by one slash, no trailing slash. */
-export function normalizeByokPath(value: string) {
- const trimmed = value.trim().replace(/\/+$/u, "");
- return trimmed && !trimmed.startsWith("/") ? `/${trimmed}` : trimmed;
-}
-
-/** Whether a normalized path only appends whole segments to the base URL. */
-export function validByokPath(path: string) {
- return path.length <= MAX_URL_PATH && URL_PATH.test(path);
-}
-
-/** A base URL as it is sent: trimmed, without a trailing slash. */
-export function normalizeByokBaseUrl(value: string) {
- return value.trim().replace(/\/+$/u, "");
-}
-
-/**
- * The wire format of a request address: its ending names one, else the
- * Runtime's own format applies. Nothing is probed.
- */
-export function byokProtocolFor(url: string, runtime: ModelSourceRuntime) {
- const named = (Object.keys(protocolEndpoints) as ByokProtocol[]).find(
- (protocol) => url.endsWith(protocolEndpoints[protocol]),
- );
- return named
- ? { fromUrl: true, protocol: named }
- : { fromUrl: false, protocol: runtimeProtocols[runtime] };
-}
-
/** A context window as the BYOK form shows it. */
export function byokContextLabel(tokens: number) {
return tokens < 1024
diff --git a/apps/web/src/features/local-models/byok-panel.tsx b/apps/web/src/features/local-models/byok-panel.tsx
index 3ab7c4cf..4f71017b 100644
--- a/apps/web/src/features/local-models/byok-panel.tsx
+++ b/apps/web/src/features/local-models/byok-panel.tsx
@@ -4,6 +4,14 @@ import {
CheckmarkCircle02Icon,
RefreshIcon,
} from "@hugeicons/core-free-icons";
+import {
+ byokProtocolFor,
+ DEFAULT_BYOK_PATH,
+ defaultByokEndpoint,
+ normalizeByokBaseUrl,
+ normalizeByokPath,
+ validByokPath,
+} from "@linger/service-kit/byok-endpoint";
import { useMutation } from "@tanstack/react-query";
import {
type CSSProperties,
@@ -29,12 +37,6 @@ import {
byokContextLabel,
byokEndpointSuggestions,
byokPathSuggestions,
- byokProtocolFor,
- DEFAULT_BYOK_PATH,
- defaultByokEndpoint,
- normalizeByokBaseUrl,
- normalizeByokPath,
- validByokPath,
} from "./byok-endpoint";
import {
byokFailureCopy,
diff --git a/packages/local-installation/src/byok-source.ts b/packages/local-installation/src/byok-source.ts
index ed1e5825..b0558e39 100644
--- a/packages/local-installation/src/byok-source.ts
+++ b/packages/local-installation/src/byok-source.ts
@@ -1,4 +1,9 @@
import path from "node:path";
+import {
+ isByokProtocol,
+ validByokPath,
+ type ByokProtocol,
+} from "@linger/service-kit/byok-endpoint";
import { readPrivate } from "./instance.js";
import {
localmodelsBaseDirectory,
@@ -12,7 +17,7 @@ import {
} from "./managed-runtimes.js";
import type { InstallOutcome, InstallerEvent } from "./events.js";
-export type ByokProtocol = "openai-chat" | "openai-responses" | "anthropic";
+export type { ByokProtocol };
/**
* Requests go to baseUrl + path + endpoint in protocol, and models are listed
@@ -92,18 +97,6 @@ export function isAllowedByokUrl(raw: string): boolean {
}
}
-// 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[],
@@ -129,11 +122,7 @@ function byokEndpointFields(record: Record<string, unknown>): ByokEndpoint {
["Path", record.path],
["Endpoint", record.endpoint],
] as const)
- if (
- typeof value !== "string" ||
- value.length > 256 ||
- !BYOK_URL_PATH.test(value)
- )
+ if (typeof value !== "string" || !validByokPath(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.");
diff --git a/packages/service-kit/AGENTS.md b/packages/service-kit/AGENTS.md
index 7b41f618..fd5dfb3d 100644
--- a/packages/service-kit/AGENTS.md
+++ b/packages/service-kit/AGENTS.md
@@ -13,7 +13,12 @@ installation core.
`displayText`, `sleep`, fetch test-double text helpers, and `sourceRegion`
/ `orderByRegion`, which order mirrors of one download by the
`SIMPLEX_REGION` contract in `scripts/installs/README.md`). It must not import
- `node:` modules because the Web app bundles it.
+ `node:` modules because the Web app bundles it, and it stays free of relative
+ `.js` imports so raw Node type-stripping can load it directly.
+- `src/byok-endpoint.ts`: isomorphic BYOK address entry (`byokProtocolFor`,
+ `defaultByokEndpoint`, `normalizeByokPath`, `normalizeByokBaseUrl`,
+ `validByokPath`, `isByokProtocol`, and the BYOK path pattern and runtime
+ default constants), exported as `@linger/service-kit/byok-endpoint`.
- `src/node.ts`: Node-only entry (`sha256Hex`, `createJsonLogger`,
`serviceCredential`). `serviceCredential` takes the environment from its
caller and is checked against `contracts/fixtures/service-credentials/vectors.json`.
diff --git a/packages/service-kit/package.json b/packages/service-kit/package.json
index 0eaf2916..62c107a0 100644
--- a/packages/service-kit/package.json
+++ b/packages/service-kit/package.json
@@ -12,6 +12,11 @@
"linger-production": "./dist/index.js",
"default": "./src/index.ts"
},
+ "./byok-endpoint": {
+ "types": "./src/byok-endpoint.ts",
+ "linger-production": "./dist/byok-endpoint.js",
+ "default": "./src/byok-endpoint.ts"
+ },
"./node": {
"types": "./src/node.ts",
"linger-production": "./dist/node.js",
diff --git a/packages/service-kit/src/byok-endpoint.test.ts b/packages/service-kit/src/byok-endpoint.test.ts
new file mode 100644
index 00000000..1233a0ae
--- /dev/null
+++ b/packages/service-kit/src/byok-endpoint.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ BYOK_PROTOCOL_ENDPOINTS,
+ BYOK_URL_PATH_PATTERN,
+ DEFAULT_BYOK_PATH,
+ MAX_BYOK_URL_PATH,
+ byokProtocolFor,
+ defaultByokEndpoint,
+ isByokProtocol,
+ normalizeByokBaseUrl,
+ normalizeByokPath,
+ validByokPath,
+} from "./byok-endpoint.js";
+
+describe("BYOK endpoint helpers", () => {
+ it("recognizes only the three supported BYOK wire formats", () => {
+ expect(isByokProtocol("openai-chat")).toBe(true);
+ expect(isByokProtocol("openai-responses")).toBe(true);
+ expect(isByokProtocol("anthropic")).toBe(true);
+ expect(isByokProtocol("gemini")).toBe(false);
+ expect(isByokProtocol("")).toBe(false);
+ expect(isByokProtocol(null)).toBe(false);
+ });
+
+ it("maps each Runtime to its native default endpoint", () => {
+ expect(DEFAULT_BYOK_PATH).toBe("/v1");
+ expect(defaultByokEndpoint("claude")).toBe(
+ BYOK_PROTOCOL_ENDPOINTS.anthropic,
+ );
+ expect(defaultByokEndpoint("codex")).toBe(
+ BYOK_PROTOCOL_ENDPOINTS["openai-responses"],
+ );
+ expect(defaultByokEndpoint("pi")).toBe(
+ BYOK_PROTOCOL_ENDPOINTS["openai-chat"],
+ );
+ });
+
+ it("normalizes base URLs and path segments", () => {
+ expect(normalizeByokBaseUrl(" https://api.example.com/// ")).toBe(
+ "https://api.example.com",
+ );
+ expect(normalizeByokPath(" v1/ ")).toBe("/v1");
+ expect(normalizeByokPath("/api/paas/v4///")).toBe("/api/paas/v4");
+ expect(normalizeByokPath(" ")).toBe("");
+ expect(normalizeByokPath("/")).toBe("");
+ });
+
+ it("validates path segments against host, query, fragment, whitespace and length bounds", () => {
+ expect(validByokPath("")).toBe(true);
+ expect(validByokPath("/v1")).toBe(true);
+ expect(validByokPath("/api/paas/v4")).toBe(true);
+ expect(validByokPath("/chat/completions")).toBe(true);
+ expect(validByokPath(`/${"a".repeat(MAX_BYOK_URL_PATH - 1)}`)).toBe(true);
+ expect(validByokPath(`/${"a".repeat(MAX_BYOK_URL_PATH)}`)).toBe(false);
+ for (const bad of [
+ "v1",
+ "/v1/",
+ "//evil.example/v1",
+ "/v1?key=1",
+ "/v1#frag",
+ "/v1/has space",
+ "/v1\\win",
+ ]) {
+ expect(validByokPath(bad)).toBe(false);
+ expect(BYOK_URL_PATH_PATTERN.test(bad)).toBe(false);
+ }
+ });
+
+ it("derives the wire format from the URL ending and falls back to the Runtime", () => {
+ expect(
+ byokProtocolFor("https://api.example.com/v1/chat/completions", "claude"),
+ ).toEqual({ fromUrl: true, protocol: "openai-chat" });
+ expect(
+ byokProtocolFor("https://api.example.com/v1/responses", "pi"),
+ ).toEqual({ fromUrl: true, protocol: "openai-responses" });
+ expect(
+ byokProtocolFor("https://api.deepseek.com/anthropic/messages", "codex"),
+ ).toEqual({ fromUrl: true, protocol: "anthropic" });
+ expect(
+ byokProtocolFor("https://gw.example.com/custom-endpoint", "claude"),
+ ).toEqual({ fromUrl: false, protocol: "anthropic" });
+ expect(
+ byokProtocolFor("https://gw.example.com/custom-endpoint", "codex"),
+ ).toEqual({ fromUrl: false, protocol: "openai-responses" });
+ expect(
+ byokProtocolFor("https://gw.example.com/custom-endpoint", "pi"),
+ ).toEqual({ fromUrl: false, protocol: "openai-chat" });
+ });
+});
diff --git a/packages/service-kit/src/byok-endpoint.ts b/packages/service-kit/src/byok-endpoint.ts
new file mode 100644
index 00000000..ecb25298
--- /dev/null
+++ b/packages/service-kit/src/byok-endpoint.ts
@@ -0,0 +1,87 @@
+/** Wire formats supported for bring-your-own-key endpoints. */
+export type ByokProtocol = "openai-chat" | "openai-responses" | "anthropic";
+
+/** Runtimes that can drive a bring-your-own-key endpoint. */
+export type ByokRuntime = "claude" | "codex" | "pi";
+
+/** Wire format resolved from a request address and its Runtime fallback. */
+export interface ByokProtocolResolution {
+ readonly fromUrl: boolean;
+ readonly protocol: ByokProtocol;
+}
+
+/** The path most providers serve their API under. */
+export const DEFAULT_BYOK_PATH = "/v1";
+
+/** Maximum length of a BYOK path or endpoint segment string. */
+export const MAX_BYOK_URL_PATH = 256;
+
+// Empty, or whole segments each led by one slash, so a path or endpoint can
+// only extend the base URL's path.
+export const BYOK_URL_PATH_PATTERN = /^(?:\/[^/?#\s\\]+)*$/u;
+
+/** The endpoint suffix that names each BYOK wire format. */
+export const BYOK_PROTOCOL_ENDPOINTS: Readonly<Record<ByokProtocol, string>> = {
+ "openai-chat": "/chat/completions",
+ "openai-responses": "/responses",
+ anthropic: "/messages",
+};
+
+/** Each Runtime's own wire format, which Bifrost forwards untranslated. */
+export const BYOK_RUNTIME_PROTOCOLS: Readonly<
+ Record<ByokRuntime, ByokProtocol>
+> = {
+ claude: "anthropic",
+ codex: "openai-responses",
+ pi: "openai-chat",
+};
+
+const BYOK_PROTOCOLS: readonly ByokProtocol[] = [
+ "openai-chat",
+ "openai-responses",
+ "anthropic",
+];
+
+/** Whether `value` is one of the supported BYOK wire formats. */
+export function isByokProtocol(value: unknown): value is ByokProtocol {
+ return (
+ typeof value === "string" && BYOK_PROTOCOLS.includes(value as ByokProtocol)
+ );
+}
+
+/** The endpoint a Runtime's requests go to unless the owner picks another. */
+export function defaultByokEndpoint(runtime: ByokRuntime): string {
+ return BYOK_PROTOCOL_ENDPOINTS[BYOK_RUNTIME_PROTOCOLS[runtime]];
+}
+
+/** A typed path as it is sent: trimmed, led by one slash, no trailing slash. */
+export function normalizeByokPath(value: string): string {
+ const trimmed = value.trim().replace(/\/+$/u, "");
+ return trimmed && !trimmed.startsWith("/") ? `/${trimmed}` : trimmed;
+}
+
+/** A base URL as it is sent: trimmed, without a trailing slash. */
+export function normalizeByokBaseUrl(value: string): string {
+ return value.trim().replace(/\/+$/u, "");
+}
+
+/** Whether a path only appends whole segments to the base URL. */
+export function validByokPath(path: string): boolean {
+ return path.length <= MAX_BYOK_URL_PATH && BYOK_URL_PATH_PATTERN.test(path);
+}
+
+/**
+ * The wire format of a request address: its ending names one, else the
+ * Runtime's own format applies. Nothing is probed.
+ */
+export function byokProtocolFor(
+ url: string,
+ runtime: ByokRuntime,
+): ByokProtocolResolution {
+ const named = BYOK_PROTOCOLS.find((protocol) =>
+ url.endsWith(BYOK_PROTOCOL_ENDPOINTS[protocol]),
+ );
+ return named
+ ? { fromUrl: true, protocol: named }
+ : { fromUrl: false, protocol: BYOK_RUNTIME_PROTOCOLS[runtime] };
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b46cebea..542034c5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -147,6 +147,9 @@ importers:
'@linger/local-installation':
specifier: workspace:*
version: link:../../packages/local-installation
+ '@linger/service-kit':
+ specifier: workspace:*
+ version: link:../../packages/service-kit
'@linger/wire-contracts':
specifier: workspace:*
version: link:../../contracts/generated/typescript
@@ -187,6 +190,9 @@ importers:
'@linger/local-installation':
specifier: workspace:*
version: link:../../packages/local-installation
+ '@linger/service-kit':
+ specifier: workspace:*
+ version: link:../../packages/service-kit
'@linger/wire-contracts':
specifier: workspace:*
version: link:../../contracts/generated/typescript