Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(providers): add API key connections with custom endpoints (#176)

Leoaa5c08494e30
diff --git a/apps/mobile/src/features/settings/ProviderConnections.tsx b/apps/mobile/src/features/settings/ProviderConnections.tsx
new file mode 100644
index 000000000..1ddedeabe
--- /dev/null
+++ b/apps/mobile/src/features/settings/ProviderConnections.tsx
@@ -0,0 +1,386 @@
+import { useCallback, useEffect, useState } from "react";
+import { Linking, Pressable, TextInput, View } from "react-native";
+import type {
+ EnvironmentId,
+ SubscriptionAuthLoginProgress,
+ SubscriptionAuthStartResult,
+ SubscriptionProviderId,
+} from "@t3tools/contracts";
+import {
+ apiKeyStartInput,
+ apiKeyValidationError,
+ PROVIDER_CONNECTIONS,
+ providerConnectionLabel,
+ providerUsesApiKey,
+ providerSupportsBaseUrl,
+} from "@t3tools/client-runtime/provider-auth";
+import {
+ squashAtomCommandFailure,
+ type AtomCommandResult,
+} from "@t3tools/client-runtime/state/runtime";
+
+import { AppText as Text } from "../../components/AppText";
+import { useEnvironmentQuery } from "../../state/query";
+import { serverEnvironment } from "../../state/server";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { SettingsSection } from "./components/SettingsSection";
+
+const RETRY_POLL_MS = 5000;
+
+function commandError(result: AtomCommandResult<unknown, unknown>): string {
+ if (result._tag !== "Failure") return "The request failed.";
+ const error = squashAtomCommandFailure(result);
+ return error instanceof Error ? error.message : "The request failed.";
+}
+
+function Action({
+ label,
+ disabled = false,
+ onPress,
+}: {
+ readonly label: string;
+ readonly disabled?: boolean;
+ readonly onPress: () => void;
+}) {
+ return (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityState={{ disabled }}
+ disabled={disabled}
+ onPress={onPress}
+ className={`min-h-11 justify-center rounded-xl bg-subtle px-3 py-2 ${disabled ? "opacity-50" : ""}`}
+ >
+ <Text className="text-sm font-t3-medium text-foreground">{label}</Text>
+ </Pressable>
+ );
+}
+
+export function ProviderConnections({ environmentId }: { readonly environmentId: EnvironmentId }) {
+ const query = useEnvironmentQuery(
+ serverEnvironment.subscriptionAuth({ environmentId, input: {} }),
+ );
+ const start = useAtomCommand(serverEnvironment.startSubscriptionAuth, { reportFailure: false });
+ const complete = useAtomCommand(serverEnvironment.completeSubscriptionAuth, {
+ reportFailure: false,
+ });
+ const poll = useAtomCommand(serverEnvironment.pollSubscriptionAuth, { reportFailure: false });
+ const cancel = useAtomCommand(serverEnvironment.cancelSubscriptionAuth, { reportFailure: false });
+ const logout = useAtomCommand(serverEnvironment.logoutSubscriptionAuth, { reportFailure: false });
+ const test = useAtomCommand(serverEnvironment.testSubscriptionAuth, { reportFailure: false });
+ const [flow, setFlow] = useState<SubscriptionAuthStartResult | null>(null);
+ const [keyProvider, setKeyProvider] = useState<SubscriptionProviderId | null>(null);
+ const [code, setCode] = useState("");
+ const [baseUrl, setBaseUrl] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const settle = useCallback(
+ (progress: SubscriptionAuthLoginProgress) => {
+ if (progress.status === "connected") {
+ setFlow(null);
+ setCode("");
+ query.refresh();
+ return true;
+ }
+ if (progress.status === "failed") setError(progress.error);
+ return progress.status !== "pending";
+ },
+ [query],
+ );
+
+ useEffect(() => {
+ if (!flow || flow.completion !== "poll") return;
+ let cancelled = false;
+ let pollFailed = false;
+ let timer: ReturnType<typeof setTimeout>;
+ const check = async () => {
+ const result = await poll({ environmentId, input: { loginId: flow.loginId } });
+ if (cancelled) return;
+ if (result._tag !== "Success") {
+ // A dropped request must not end the login; the next check picks up the approval.
+ if (result._tag === "Failure") {
+ pollFailed = true;
+ setError(commandError(result));
+ }
+ timer = setTimeout(check, RETRY_POLL_MS);
+ return;
+ }
+ if (pollFailed) {
+ pollFailed = false;
+ setError(null);
+ }
+ if (settle(result.value)) return;
+ if (result.value.status === "pending")
+ timer = setTimeout(check, Math.max(1000, result.value.nextPollMs));
+ };
+ timer = setTimeout(check, 1000);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [flow, environmentId, poll, settle]);
+
+ const openUrl = async (url: string) => {
+ try {
+ await Linking.openURL(url);
+ } catch {
+ setError("Could not open the sign-in page. Try Open sign-in again.");
+ }
+ };
+
+ const openKey = (provider: SubscriptionProviderId) => {
+ setError(null);
+ setCode("");
+ setBaseUrl(
+ providerSupportsBaseUrl(provider)
+ ? (query.data?.providers.find((status) => status.provider === provider)?.baseUrl ?? "")
+ : "",
+ );
+ setKeyProvider(provider);
+ };
+
+ const connect = async (provider: SubscriptionProviderId) => {
+ if (provider === "opencode-go") {
+ openKey(provider);
+ return;
+ }
+ setError(null);
+ setCode("");
+ setBusy(true);
+ const result = await start({ environmentId, input: { provider } });
+ setBusy(false);
+ if (result._tag === "Failure") {
+ setError(commandError(result));
+ return;
+ }
+ if (result._tag !== "Success") return;
+ setFlow(result.value);
+ if (result.value.url) await openUrl(result.value.url);
+ };
+
+ const saveKey = async () => {
+ if (!keyProvider || busy) return;
+ const validation = apiKeyValidationError(code, baseUrl);
+ setError(validation);
+ if (validation) return;
+ setBusy(true);
+ const started = await start({ environmentId, input: apiKeyStartInput(keyProvider, baseUrl) });
+ if (started._tag !== "Success") {
+ setBusy(false);
+ if (started._tag === "Failure") setError(commandError(started));
+ return;
+ }
+ const result = await complete({
+ environmentId,
+ input: { loginId: started.value.loginId, code: code.trim() },
+ });
+ setBusy(false);
+ if (result._tag === "Success" && result.value.status === "connected") {
+ setKeyProvider(null);
+ setCode("");
+ setBaseUrl("");
+ query.refresh();
+ } else {
+ if (result._tag === "Failure") setError(commandError(result));
+ else if (result._tag === "Success")
+ setError(
+ result.value.status === "failed"
+ ? result.value.error
+ : "The key was not saved. Try again.",
+ );
+ await cancel({ environmentId, input: { loginId: started.value.loginId } });
+ }
+ };
+
+ const finish = async () => {
+ if (!flow || busy) return;
+ setError(null);
+ setBusy(true);
+ const result = await complete({ environmentId, input: { loginId: flow.loginId, code } });
+ setBusy(false);
+ if (result._tag === "Success") settle(result.value);
+ else if (result._tag === "Failure") setError(commandError(result));
+ };
+
+ const cancelLogin = async () => {
+ const login = flow;
+ setFlow(null);
+ setKeyProvider(null);
+ setCode("");
+ setBaseUrl("");
+ setError(null);
+ if (login) {
+ const result = await cancel({ environmentId, input: { loginId: login.loginId } });
+ if (result._tag === "Failure") setError(commandError(result));
+ }
+ };
+
+ const runAction = async (provider: SubscriptionProviderId, action: "disconnect" | "test") => {
+ setError(null);
+ setBusy(true);
+ const result = await (action === "disconnect" ? logout : test)({
+ environmentId,
+ input: { provider },
+ });
+ setBusy(false);
+ if (result._tag === "Success") query.refresh();
+ else if (result._tag === "Failure") setError(commandError(result));
+ };
+
+ const activeProvider = keyProvider ?? flow?.provider;
+ const label = PROVIDER_CONNECTIONS.find((provider) => provider.id === activeProvider)?.label;
+ return (
+ <SettingsSection title={activeProvider ? `Connect ${label}` : "Provider connections"} card>
+ <View className="gap-3 p-4">
+ {error || query.error ? (
+ <Text accessibilityRole="alert" className="text-sm text-danger">
+ {error ?? query.error}
+ </Text>
+ ) : null}
+ {keyProvider ? (
+ <>
+ <Text className="text-sm font-t3-medium text-foreground">API key</Text>
+ <TextInput
+ accessibilityLabel="API key"
+ secureTextEntry
+ autoCapitalize="none"
+ autoCorrect={false}
+ autoComplete="off"
+ value={code}
+ editable={!busy}
+ onChangeText={setCode}
+ className="min-h-11 rounded-xl border border-border-subtle px-3 py-2 text-foreground"
+ />
+ {providerSupportsBaseUrl(keyProvider) ? (
+ <>
+ <Text className="text-sm font-t3-medium text-foreground">Base URL (optional)</Text>
+ <TextInput
+ accessibilityLabel="Base URL (optional)"
+ placeholder="Provider default"
+ keyboardType="url"
+ autoCapitalize="none"
+ autoCorrect={false}
+ autoComplete="off"
+ value={baseUrl}
+ editable={!busy}
+ onChangeText={setBaseUrl}
+ className="min-h-11 rounded-xl border border-border-subtle px-3 py-2 text-foreground"
+ />
+ </>
+ ) : null}
+ <Text className="text-sm text-foreground-muted">
+ {providerSupportsBaseUrl(keyProvider)
+ ? "The environment sends this key to the selected endpoint."
+ : "Grok uses its default endpoint."}{" "}
+ API billing can be separate from your subscription.
+ </Text>
+ <View className="flex-row gap-2">
+ <Action
+ label={busy ? "Saving…" : "Save"}
+ disabled={busy || !code.trim()}
+ onPress={() => void saveKey()}
+ />
+ <Action label="Cancel" disabled={busy} onPress={() => void cancelLogin()} />
+ </View>
+ </>
+ ) : flow ? (
+ <>
+ {flow.instructions ? (
+ <Text className="text-sm text-foreground-muted">{flow.instructions}</Text>
+ ) : null}
+ {flow.url ? (
+ <Action label="Open sign-in" onPress={() => void openUrl(flow.url)} />
+ ) : null}
+ {flow.userCode ? (
+ <Text selectable className="text-lg font-t3-medium text-foreground">
+ {flow.userCode}
+ </Text>
+ ) : null}
+ {flow.completion === "paste" ? (
+ <>
+ <TextInput
+ accessibilityLabel="Authorization code"
+ placeholder="Paste the authorization code"
+ autoCapitalize="none"
+ autoCorrect={false}
+ value={code}
+ editable={!busy}
+ onChangeText={setCode}
+ className="min-h-11 rounded-xl border border-border-subtle px-3 py-2 text-foreground"
+ />
+ <Action
+ label="Connect"
+ disabled={busy || !code.trim()}
+ onPress={() => void finish()}
+ />
+ </>
+ ) : !error ? (
+ <Text className="text-sm text-foreground-muted">Waiting for approval…</Text>
+ ) : null}
+ <Action label="Cancel" disabled={busy} onPress={() => void cancelLogin()} />
+ </>
+ ) : (
+ <>
+ {query.isPending ? (
+ <Text className="text-sm text-foreground-muted">Loading connections…</Text>
+ ) : null}
+ {PROVIDER_CONNECTIONS.map((provider) => {
+ const status = query.data?.providers.find((entry) => entry.provider === provider.id);
+ const apiKey = providerUsesApiKey(status);
+ return (
+ <View key={provider.id} className="gap-2 border-b border-border-subtle py-3">
+ <Text className="text-base font-t3-medium text-foreground">{provider.label}</Text>
+ <Text className="text-sm text-foreground-muted">
+ {status ? providerConnectionLabel(status) : "Status unavailable"}
+ </Text>
+ {status?.baseUrl ? (
+ <Text selectable className="text-sm text-foreground-muted">
+ {status.baseUrl}
+ </Text>
+ ) : null}
+ {status?.lastFailedRequest ? (
+ <Text className="text-sm text-danger">{status.lastFailedRequest.message}</Text>
+ ) : null}
+ <View className="flex-row flex-wrap gap-2">
+ <Action
+ label={
+ status?.connected
+ ? apiKey && provider.id !== "opencode-go"
+ ? "Use OAuth"
+ : "Reconnect"
+ : "Connect"
+ }
+ disabled={busy || query.isPending}
+ onPress={() => void connect(provider.id)}
+ />
+ {provider.id !== "opencode-go" ? (
+ <Action
+ label={apiKey ? "Reconnect key" : "API key"}
+ disabled={busy || query.isPending}
+ onPress={() => openKey(provider.id)}
+ />
+ ) : null}
+ {status?.connected ? (
+ <>
+ <Action
+ label={apiKey ? "Check key" : "Check OAuth"}
+ disabled={busy}
+ onPress={() => void runAction(provider.id, "test")}
+ />
+ <Action
+ label="Disconnect"
+ disabled={busy}
+ onPress={() => void runAction(provider.id, "disconnect")}
+ />
+ </>
+ ) : null}
+ </View>
+ </View>
+ );
+ })}
+ </>
+ )}
+ </View>
+ </SettingsSection>
+ );
+}
diff --git a/apps/mobile/src/features/settings/SettingsProviderHealthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProviderHealthRouteScreen.tsx
index 4db483c48..fde98b279 100644
--- a/apps/mobile/src/features/settings/SettingsProviderHealthRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsProviderHealthRouteScreen.tsx
@@ -13,10 +13,11 @@ import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { canResolveInboxItem, settingsInboxView } from "./botInbox.logic";
import { SettingsSection } from "./components/SettingsSection";
+import { ProviderConnections } from "./ProviderConnections";
export type SettingsProviderHealthParams = {
readonly environmentId: EnvironmentId;
- readonly target: "local-execution" | "bot-inbox";
+ readonly target: "local-execution" | "bot-inbox" | "providers";
} & Record<string, unknown>;
function Field(props: { readonly label: string; readonly value: string }) {
@@ -119,7 +120,7 @@ export function SettingsProviderHealthRouteScreen({
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const query = useEnvironmentQuery(
- route.params.target === "local-execution"
+ route.params.target !== "bot-inbox"
? null
: botInboxEnvironment.list({
environmentId: route.params.environmentId,
@@ -151,9 +152,19 @@ export function SettingsProviderHealthRouteScreen({
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4"
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
- refreshControl={<RefreshControl refreshing={query.isPending} onRefresh={query.refresh} />}
+ keyboardShouldPersistTaps="handled"
+ refreshControl={
+ route.params.target === "bot-inbox" ? (
+ <RefreshControl refreshing={query.isPending} onRefresh={query.refresh} />
+ ) : undefined
+ }
>
- {route.params.target === "local-execution" ? (
+ {route.params.target === "providers" ? (
+ <ProviderConnections
+ key={route.params.environmentId}
+ environmentId={route.params.environmentId}
+ />
+ ) : route.params.target === "local-execution" ? (
section
) : inboxView?.kind === "error" ? (
<Text className="py-16 text-center text-sm text-danger">{inboxView.message}</Text>
diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
index c0bf38000..7c2e0220a 100644
--- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
@@ -115,6 +115,8 @@ function LocalSettingsRouteScreen({
/>
</SettingsSection>
+ <ProviderSettingsSection environmentId={settingsEnvironmentId} />
+
<ErrorsSettingsSection environmentId={connections[0]?.environmentId ?? null} />
<GeneralSettingsSection />
@@ -135,6 +137,37 @@ function LocalSettingsRouteScreen({
);
}
+function ProviderSettingsSection({
+ environmentId,
+}: {
+ readonly environmentId: EnvironmentId | null;
+}) {
+ const navigation = useNavigation();
+ return (
+ <SettingsSection title="Providers">
+ {environmentId === null ? (
+ <Text className="text-sm text-foreground-muted">
+ Open Settings from an environment to connect a provider.
+ </Text>
+ ) : (
+ <SettingsRow
+ icon="key"
+ label="Provider connections"
+ onPress={() =>
+ navigation.navigate("SettingsSheet", {
+ screen: "SettingsContent",
+ params: {
+ screen: "SettingsProviderHealth",
+ params: { environmentId, target: "providers" },
+ },
+ })
+ }
+ />
+ )}
+ </SettingsSection>
+ );
+}
+
function ErrorsSettingsSection({
environmentId,
}: {
diff --git a/apps/mobile/src/features/settings/settingsDeepLink.test.ts b/apps/mobile/src/features/settings/settingsDeepLink.test.ts
index 176b968f3..4b6f9b261 100644
--- a/apps/mobile/src/features/settings/settingsDeepLink.test.ts
+++ b/apps/mobile/src/features/settings/settingsDeepLink.test.ts
@@ -3,14 +3,17 @@ import { describe, expect, it } from "vite-plus/test";
import { resolveMobileSettingsHealthTarget } from "./settingsDeepLink";
describe("mobile Settings chat links", () => {
- it.each(["local-execution", "bot-inbox"] as const)("opens the %s target", (target) => {
- expect(resolveMobileSettingsHealthTarget(`grokbot://app/v1/settings?id=${target}`)).toBe(
- target,
- );
- });
+ it.each(["local-execution", "bot-inbox", "providers"] as const)(
+ "opens the %s target",
+ (target) => {
+ expect(resolveMobileSettingsHealthTarget(`grokbot://app/v1/settings?id=${target}`)).toBe(
+ target,
+ );
+ },
+ );
it.each([
- "grokbot://app/v1/settings?id=providers",
+ "grokbot://app/v1/settings?id=providers&id=bot-inbox",
"grokbot://app/v1/settings?id=provider-access",
"grokbot://app/v1/settings?id=provider-access&id=bot-inbox",
"grokbot://app/v1/settings?id=provider-access&from=chat",
diff --git a/apps/mobile/src/features/settings/settingsDeepLink.ts b/apps/mobile/src/features/settings/settingsDeepLink.ts
index 5f33601e7..52ab7b969 100644
--- a/apps/mobile/src/features/settings/settingsDeepLink.ts
+++ b/apps/mobile/src/features/settings/settingsDeepLink.ts
@@ -1,8 +1,8 @@
import { parseSettingsDeepLinkId } from "@t3tools/client-runtime/settings-deep-link";
-export type MobileSettingsHealthTarget = "local-execution" | "bot-inbox";
+export type MobileSettingsHealthTarget = "local-execution" | "bot-inbox" | "providers";
export function resolveMobileSettingsHealthTarget(href: string): MobileSettingsHealthTarget | null {
const id = parseSettingsDeepLinkId(href);
- return id === "local-execution" || id === "bot-inbox" ? id : null;
+ return id === "local-execution" || id === "bot-inbox" || id === "providers" ? id : null;
}
diff --git a/apps/server/src/provider/AkeruKimiProvider.test.ts b/apps/server/src/provider/AkeruKimiProvider.test.ts
index 2c0205119..c863fe343 100644
--- a/apps/server/src/provider/AkeruKimiProvider.test.ts
+++ b/apps/server/src/provider/AkeruKimiProvider.test.ts
@@ -8,6 +8,26 @@ const access = {
};
describe("AkeruKimiProvider", () => {
+ it("uses API keys and custom endpoints without OAuth device headers", async () => {
+ const request = vi.fn(
+ async (_input: string | URL | Request, _init?: RequestInit) => new Response("{}"),
+ );
+ const fetch = buildAkeruKimiFetch(
+ async () => ({ accessToken: "api-key", baseUrl: "https://proxy.example/v1" }),
+ request,
+ );
+ await fetch("https://api.kimi.com/coding/v1/messages?beta=true", {
+ method: "POST",
+ body: "{}",
+ });
+ expect(request).toHaveBeenCalledWith(
+ "https://proxy.example/v1/messages?beta=true",
+ expect.objectContaining({ method: "POST", body: "{}", redirect: "error" }),
+ );
+ const headers = new Headers(request.mock.calls[0]?.[1]?.headers);
+ expect(headers.get("authorization")).toBe("Bearer api-key");
+ expect(headers.get("x-msh-device-id")).toBeNull();
+ });
it("builds the Kimi Anthropic model without changing the saved model", () => {
expect(akeruKimiProvider("k3-256k", async () => access)).toMatchObject({
provider: "anthropic.messages",
diff --git a/apps/server/src/provider/AkeruKimiProvider.ts b/apps/server/src/provider/AkeruKimiProvider.ts
index bf21309d4..859c1c99b 100644
--- a/apps/server/src/provider/AkeruKimiProvider.ts
+++ b/apps/server/src/provider/AkeruKimiProvider.ts
@@ -2,13 +2,15 @@ import { createAnthropic } from "@ai-sdk/anthropic";
import type { MastraModelConfig } from "@mastra/core/llm";
import { getKimiCodingDeviceHeaders } from "../subscription-auth/providers/kimi.ts";
+import { subscriptionRequestUrl } from "../subscription-auth/runtime.ts";
const KIMI_CODING_BASE_URL = "https://api.kimi.com/coding/v1";
type AkeruKimiFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
export interface AkeruKimiAccess {
readonly accessToken: string;
- readonly deviceId: string;
+ readonly deviceId?: string;
+ readonly baseUrl?: string;
}
export function buildAkeruKimiFetch(
@@ -25,10 +27,16 @@ export function buildAkeruKimiFetch(
headers.delete("authorization");
headers.delete("x-api-key");
headers.set("Authorization", `Bearer ${access.accessToken}`);
- for (const [key, value] of Object.entries(getKimiCodingDeviceHeaders(access.deviceId))) {
- headers.set(key, value);
+ if (access.deviceId !== undefined) {
+ for (const [key, value] of Object.entries(getKimiCodingDeviceHeaders(access.deviceId))) {
+ headers.set(key, value);
+ }
}
- return request(input, { ...init, headers });
+ return request(subscriptionRequestUrl(input, KIMI_CODING_BASE_URL, access.baseUrl), {
+ ...init,
+ headers,
+ redirect: "error",
+ });
};
}
diff --git a/apps/server/src/provider/AkeruMastraHarness.test.ts b/apps/server/src/provider/AkeruMastraHarness.test.ts
index 62af4a0e1..1cf8de00b 100644
--- a/apps/server/src/provider/AkeruMastraHarness.test.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.test.ts
@@ -396,6 +396,26 @@ describe("AkeruMastraHarness", () => {
}
});
+ it("routes Codex API keys through OpenAI Responses instead of the OAuth transport", () => {
+ const authStorage = new AuthStorage("/tmp/akeru-unused-api-key-auth.json");
+ const getCredential = vi.fn(() => ({
+ type: "api-key" as const,
+ access: "key",
+ baseUrl: "https://proxy.example/v1",
+ }));
+ expect(
+ resolveAkeruMastraModel(
+ "openai/gpt-5.6",
+ authStorage,
+ undefined,
+ undefined,
+ undefined,
+ getCredential,
+ ),
+ ).toMatchObject({ modelId: "gpt-5.6", provider: "openai.responses" });
+ expect(getCredential).toHaveBeenCalledWith("openai-codex");
+ });
+
it("keeps Kimi model names on the Kimi subscription transport", () => {
const authStorage = new AuthStorage("/tmp/akeru-unused-auth.json");
assert.equal(
diff --git a/apps/server/src/provider/AkeruMastraHarness.ts b/apps/server/src/provider/AkeruMastraHarness.ts
index be129d8f2..dee6b9d0d 100644
--- a/apps/server/src/provider/AkeruMastraHarness.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.ts
@@ -46,6 +46,8 @@ import {
createAkeruAgentInstructions,
createAkeruBotInstructions,
} from "./AkeruAgentInstructions.ts";
+import type { SubscriptionAuthService } from "../subscription-auth/service.ts";
+import { akeruOpenAIProvider } from "./AkeruOpenAIProvider.ts";
import { akeruKimiProvider, type AkeruKimiAccess } from "./AkeruKimiProvider.ts";
import { akeruOpenCodeGoProvider } from "./AkeruOpenCodeGoProvider.ts";
import { createAkeruMastraTools } from "./AkeruMastraTools.ts";
@@ -188,6 +190,7 @@ export interface AkeruMastraHarnessOptions {
readonly authStorage: AuthStorage;
readonly getKimiAccess?: () => Promise<AkeruKimiAccess | undefined>;
readonly getOpenCodeGoApiKey?: () => Promise<string | undefined>;
+ readonly getSubscriptionApiKey?: SubscriptionAuthService["getApiKeyCredential"];
readonly memoryDbPath: string;
readonly startMemoryCall?: (input: {
readonly threadId: string;
@@ -367,7 +370,11 @@ export class AkeruPassiveObservationalMemoryProcessor implements Processor<"obse
export async function createAkeruMastraMemory(
options: Pick<
AkeruMastraHarnessOptions,
- "authStorage" | "getKimiAccess" | "getOpenCodeGoApiKey" | "memoryDbPath"
+ | "authStorage"
+ | "getKimiAccess"
+ | "getOpenCodeGoApiKey"
+ | "getSubscriptionApiKey"
+ | "memoryDbPath"
>,
) {
const storage = new LibSQLStore({
@@ -382,6 +389,8 @@ export async function createAkeruMastraMemory(
options.authStorage,
options.getKimiAccess,
options.getOpenCodeGoApiKey,
+ undefined,
+ options.getSubscriptionApiKey,
);
const memory = new Memory({
storage,
@@ -450,9 +459,15 @@ export function resolveAkeruMastraModel(
getKimiAccess?: () => Promise<AkeruKimiAccess | undefined>,
getOpenCodeGoApiKey?: () => Promise<string | undefined>,
modelOptions?: AkeruMastraState["modelOptions"],
+ getSubscriptionApiKey?: SubscriptionAuthService["getApiKeyCredential"],
) {
const trimmed = modelId.trim();
if (trimmed.startsWith("openai/")) {
+ if (getSubscriptionApiKey?.("openai-codex")) {
+ return akeruOpenAIProvider(trimmed.slice("openai/".length), () =>
+ getSubscriptionApiKey("openai-codex"),
+ );
+ }
const reasoningEffort = modelOptions?.reasoningEffort;
return openaiCodexProvider(trimmed.slice("openai/".length), {
authStorage,
@@ -465,7 +480,11 @@ export function resolveAkeruMastraModel(
}
if (trimmed.startsWith("opencode-go/")) {
if (!getOpenCodeGoApiKey) throw new Error("OpenCode Go subscription access is unavailable.");
- return akeruOpenCodeGoProvider(trimmed.slice("opencode-go/".length), getOpenCodeGoApiKey);
+ return akeruOpenCodeGoProvider(
+ trimmed.slice("opencode-go/".length),
+ getOpenCodeGoApiKey,
+ () => getSubscriptionApiKey?.("opencode-go")?.baseUrl,
+ );
}
throw new Error(`Mastra has no subscription transport for model '${modelId}'.`);
}
@@ -859,6 +878,7 @@ export async function createAkeruMastraHarness(
options.getKimiAccess,
options.getOpenCodeGoApiKey,
controllerModelOptions(requestContext),
+ options.getSubscriptionApiKey,
),
tools: ({ requestContext }) => resolveAkeruTools(requestContext, options),
memory: observationalMemory.memory,
diff --git a/apps/server/src/provider/AkeruOpenAIProvider.test.ts b/apps/server/src/provider/AkeruOpenAIProvider.test.ts
new file mode 100644
index 000000000..4784512f1
--- /dev/null
+++ b/apps/server/src/provider/AkeruOpenAIProvider.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+import type { ApiKeyCredential } from "../subscription-auth/types.ts";
+import { akeruOpenAIProvider, buildAkeruOpenAIFetch } from "./AkeruOpenAIProvider.ts";
+
+describe("Akeru OpenAI API-key transport", () => {
+ it("uses Responses without a ChatGPT account or OAuth token", () => {
+ expect(
+ akeruOpenAIProvider("gpt-5.6", () => ({ type: "api-key", access: "key" })),
+ ).toMatchObject({ modelId: "gpt-5.6", provider: "openai.responses" });
+ });
+
+ it("loads current credentials for every request and stops after logout", async () => {
+ let credential: ApiKeyCredential | undefined = {
+ type: "api-key",
+ access: "first-key",
+ baseUrl: "https://proxy.example/v1",
+ };
+ const request = vi.fn(
+ async (_input: string | URL | Request, _init?: RequestInit) => new Response("{}"),
+ );
+ const fetch = buildAkeruOpenAIFetch(() => credential, request);
+ await fetch("https://api.openai.com/v1/responses", {
+ method: "POST",
+ body: "{}",
+ headers: { "chatgpt-account-id": "stale-account" },
+ });
+ expect(request).toHaveBeenCalledWith(
+ "https://proxy.example/v1/responses",
+ expect.objectContaining({ method: "POST", body: "{}", redirect: "error" }),
+ );
+ expect(new Headers(request.mock.calls[0]?.[1]?.headers).get("authorization")).toBe(
+ "Bearer first-key",
+ );
+ expect(new Headers(request.mock.calls[0]?.[1]?.headers).get("chatgpt-account-id")).toBeNull();
+ credential = { type: "api-key", access: "replacement-key" };
+ await fetch("https://api.openai.com/v1/responses");
+ expect(new Headers(request.mock.calls[1]?.[1]?.headers).get("authorization")).toBe(
+ "Bearer replacement-key",
+ );
+ credential = undefined;
+ await expect(fetch("https://api.openai.com/v1/responses")).rejects.toThrow(
+ "no longer connected",
+ );
+ expect(request).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/server/src/provider/AkeruOpenAIProvider.ts b/apps/server/src/provider/AkeruOpenAIProvider.ts
new file mode 100644
index 000000000..d60f32be8
--- /dev/null
+++ b/apps/server/src/provider/AkeruOpenAIProvider.ts
@@ -0,0 +1,39 @@
+import { createOpenAI } from "@ai-sdk/openai";
+import type { ApiKeyCredential } from "../subscription-auth/types.ts";
+import { subscriptionRequestUrl } from "../subscription-auth/runtime.ts";
+
+type OpenAIFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
+const OPENAI_BASE_URL = "https://api.openai.com/v1";
+
+export function buildAkeruOpenAIFetch(
+ getCredential: () => ApiKeyCredential | undefined,
+ request: OpenAIFetch = globalThis.fetch,
+): OpenAIFetch {
+ return async (input, init) => {
+ const credential = getCredential();
+ if (!credential)
+ throw new Error("The OpenAI API key is no longer connected. Start a new turn.");
+ const headers = new Headers(input instanceof Request ? input.headers : undefined);
+ new Headers(init?.headers).forEach((value, key) => headers.set(key, value));
+ headers.set("Authorization", `Bearer ${credential.access}`);
+ headers.delete("chatgpt-account-id");
+ return request(subscriptionRequestUrl(input, OPENAI_BASE_URL, credential.baseUrl), {
+ ...init,
+ headers,
+ redirect: "error",
+ });
+ };
+}
+
+export function akeruOpenAIProvider(
+ modelId: string,
+ getCredential: () => ApiKeyCredential | undefined,
+) {
+ return createOpenAI({
+ apiKey: "akeru-api-key",
+ baseURL: OPENAI_BASE_URL,
+ fetch: buildAkeruOpenAIFetch(getCredential) as NonNullable<
+ NonNullable<Parameters<typeof createOpenAI>[0]>["fetch"]
+ >,
+ }).responses(modelId);
+}
diff --git a/apps/server/src/provider/AkeruOpenCodeGoProvider.test.ts b/apps/server/src/provider/AkeruOpenCodeGoProvider.test.ts
index 07e3289c7..117613300 100644
--- a/apps/server/src/provider/AkeruOpenCodeGoProvider.test.ts
+++ b/apps/server/src/provider/AkeruOpenCodeGoProvider.test.ts
@@ -7,6 +7,28 @@ import {
} from "./AkeruOpenCodeGoProvider.ts";
describe("AkeruOpenCodeGoProvider", () => {
+ it.each(["responses", "anthropic", "chat-completions"] as const)(
+ "routes %s to the custom endpoint",
+ async (protocol) => {
+ const request = vi.fn(
+ async (_input: string | URL | Request, _init?: RequestInit) => new Response("{}"),
+ );
+ await buildAkeruOpenCodeGoFetch(
+ protocol,
+ async () => "custom-key",
+ request,
+ () => "http://localhost:8080/v1",
+ )("https://opencode.ai/zen/go/v1/messages", { method: "POST", body: "{}" });
+ expect(request).toHaveBeenCalledWith(
+ "http://localhost:8080/v1/messages",
+ expect.objectContaining({ body: "{}", redirect: "error" }),
+ );
+ const headers = new Headers(request.mock.calls[0]?.[1]?.headers);
+ expect(headers.get(protocol === "anthropic" ? "x-api-key" : "authorization")).toBe(
+ protocol === "anthropic" ? "custom-key" : "Bearer custom-key",
+ );
+ },
+ );
it("selects the protocol required by each model family", () => {
expect(openCodeGoProtocol("gpt-5.6-luna")).toBe("responses");
expect(openCodeGoProtocol("muse-spark-1.3-contributor")).toBe("responses");
diff --git a/apps/server/src/provider/AkeruOpenCodeGoProvider.ts b/apps/server/src/provider/AkeruOpenCodeGoProvider.ts
index 1751f8d18..e59d20dd7 100644
--- a/apps/server/src/provider/AkeruOpenCodeGoProvider.ts
+++ b/apps/server/src/provider/AkeruOpenCodeGoProvider.ts
@@ -2,6 +2,7 @@ import { createAnthropic } from "@ai-sdk/anthropic";
import { createOpenAI } from "@ai-sdk/openai";
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import type { MastraModelConfig } from "@mastra/core/llm";
+import { subscriptionRequestUrl } from "../subscription-auth/runtime.ts";
const OPEN_CODE_GO_BASE_URL = "https://opencode.ai/zen/go/v1";
const OPEN_CODE_GO_USER_AGENT = "akeru-bot/0.0.37";
@@ -30,6 +31,7 @@ export function buildAkeruOpenCodeGoFetch(
protocol: OpenCodeGoProtocol,
getApiKey: () => Promise<string | undefined>,
request: AkeruOpenCodeGoFetch = globalThis.fetch,
+ getBaseUrl: () => string | undefined = () => undefined,
): AkeruOpenCodeGoFetch {
return async (input, init) => {
const apiKey = await getApiKey();
@@ -48,18 +50,26 @@ export function buildAkeruOpenCodeGoFetch(
} else {
headers.set("Authorization", `Bearer ${apiKey}`);
}
- return request(input, { ...init, headers });
+ return request(subscriptionRequestUrl(input, OPEN_CODE_GO_BASE_URL, getBaseUrl()), {
+ ...init,
+ headers,
+ redirect: "error",
+ });
};
}
export function akeruOpenCodeGoProvider(
modelId: string,
getApiKey: () => Promise<string | undefined>,
+ getBaseUrl?: () => string | undefined,
): MastraModelConfig {
const protocol = openCodeGoProtocol(modelId);
- const fetch = buildAkeruOpenCodeGoFetch(protocol, getApiKey) as NonNullable<
- NonNullable<Parameters<typeof createOpenAI>[0]>["fetch"]
- >;
+ const fetch = buildAkeruOpenCodeGoFetch(
+ protocol,
+ getApiKey,
+ globalThis.fetch,
+ getBaseUrl,
+ ) as NonNullable<NonNullable<Parameters<typeof createOpenAI>[0]>["fetch"]>;
if (protocol === "responses") {
return createOpenAI({
name: "opencode-go",
diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts
index 0409b7c69..1c626aaff 100644
--- a/apps/server/src/provider/Drivers/ClaudeDriver.ts
+++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts
@@ -43,7 +43,7 @@ import {
type ProviderInstance,
} from "../ProviderDriver.ts";
import type { ServerProviderDraft } from "../providerSnapshot.ts";
-import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
+import { mergeSubscriptionInstanceEnvironment } from "../../subscription-auth/runtime.ts";
import {
enrichProviderSnapshotWithVersionAdvisory,
makePackageManagedProviderMaintenanceResolver,
@@ -123,12 +123,12 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
- const { cwd } = yield* ServerConfig;
+ const { cwd, secretsDir } = yield* ServerConfig;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const modelManifest = yield* ModelManifest.ModelManifest;
- const processEnv = mergeProviderInstanceEnvironment(environment);
+ const processEnv = mergeSubscriptionInstanceEnvironment(environment);
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
instanceId,
@@ -152,7 +152,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
};
const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions);
- const textGeneration = yield* makeClaudeTextGeneration(effectiveConfig, processEnv);
+ const textGeneration = yield* makeClaudeTextGeneration(
+ effectiveConfig,
+ processEnv,
+ secretsDir,
+ );
// Per-instance capabilities cache: keyed on binary + resolved HOME so
// account-specific probes never share auth metadata across instances.
diff --git a/apps/server/src/provider/Drivers/ClaudeHome.test.ts b/apps/server/src/provider/Drivers/ClaudeHome.test.ts
index a7ff41fc8..70d95afa1 100644
--- a/apps/server/src/provider/Drivers/ClaudeHome.test.ts
+++ b/apps/server/src/provider/Drivers/ClaudeHome.test.ts
@@ -1,10 +1,15 @@
+// @effect-diagnostics nodeBuiltinImport:off
+import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Path from "effect/Path";
+import { subscriptionRuntimeEnvironment } from "../../subscription-auth/runtime.ts";
+import { SubscriptionAuthService } from "../../subscription-auth/service.ts";
import {
makeClaudeCapabilitiesCacheKey,
makeClaudeContinuationGroupKey,
@@ -39,6 +44,29 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => {
}),
);
+ it.effect("marks CLAUDE_CONFIG_DIR explicit so saved API keys do not replace the account", () =>
+ Effect.gen(function* () {
+ const secretsDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-claude-home-"));
+ try {
+ const auth = SubscriptionAuthService.forSecretsDir(secretsDir);
+ const login = yield* Effect.promise(() =>
+ auth.startLogin("anthropic", { authMode: "api-key" }),
+ );
+ yield* Effect.promise(() => auth.completeLogin(login.loginId, "provider-wide-key"));
+ const environment = yield* makeClaudeEnvironment(
+ { homePath: "~/.claude-work" },
+ { CLAUDE_CODE_OAUTH_TOKEN: "native-oauth" },
+ );
+ expect(subscriptionRuntimeEnvironment(secretsDir, "anthropic", environment)).toBe(
+ environment,
+ );
+ expect(environment.ANTHROPIC_API_KEY).toBeUndefined();
+ } finally {
+ NodeFS.rmSync(secretsDir, { recursive: true, force: true });
+ }
+ }),
+ );
+
it.effect("separates capability probes by cwd", () =>
Effect.gen(function* () {
const config = { binaryPath: "claude", homePath: "" };
diff --git a/apps/server/src/provider/Drivers/ClaudeHome.ts b/apps/server/src/provider/Drivers/ClaudeHome.ts
index b3ef22b64..aec4a1fc7 100644
--- a/apps/server/src/provider/Drivers/ClaudeHome.ts
+++ b/apps/server/src/provider/Drivers/ClaudeHome.ts
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
import * as Path from "effect/Path";
import { expandHomePath } from "../../pathExpansion.ts";
+import { withExplicitEnvironmentKeys } from "../../subscription-auth/runtime.ts";
export const resolveClaudeHomePath = Effect.fn("resolveClaudeHomePath")(function* (
config: Pick<ClaudeSettings, "homePath">,
@@ -22,16 +23,16 @@ export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function
const homePath = config.homePath.trim();
if (homePath.length === 0) return resolvedBaseEnv;
const resolvedHomePath = yield* resolveClaudeHomePath(config);
- return {
- ...resolvedBaseEnv,
- // Isolate this instance's config via CLAUDE_CONFIG_DIR rather than HOME.
- // Overriding HOME also relocates the macOS login keychain lookup
- // ($HOME/Library/Keychains), so the spawned CLI can't find its stored
- // OAuth credentials and reports "Not logged in". CLAUDE_CONFIG_DIR points
- // Claude Code at its config dir directly while leaving HOME (and the
- // keychain) intact.
- CLAUDE_CONFIG_DIR: resolvedHomePath,
- };
+ // Isolate this instance's config via CLAUDE_CONFIG_DIR rather than HOME.
+ // Overriding HOME also relocates the macOS login keychain lookup
+ // ($HOME/Library/Keychains), so the spawned CLI can't find its stored
+ // OAuth credentials and reports "Not logged in". CLAUDE_CONFIG_DIR points
+ // Claude Code at its config dir directly while leaving HOME (and the
+ // keychain) intact. The key is marked explicit so a saved provider-wide
+ // API key does not replace the account in that directory.
+ return withExplicitEnvironmentKeys({ ...resolvedBaseEnv, CLAUDE_CONFIG_DIR: resolvedHomePath }, [
+ "CLAUDE_CONFIG_DIR",
+ ]);
});
export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationGroupKey")(
diff --git a/apps/server/src/provider/Drivers/GrokDriver.ts b/apps/server/src/provider/Drivers/GrokDriver.ts
index 112f11013..280a24d21 100644
--- a/apps/server/src/provider/Drivers/GrokDriver.ts
+++ b/apps/server/src/provider/Drivers/GrokDriver.ts
@@ -26,7 +26,7 @@ import {
type ProviderInstance,
} from "../ProviderDriver.ts";
import type { ServerProviderDraft } from "../providerSnapshot.ts";
-import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
+import { mergeSubscriptionInstanceEnvironment } from "../../subscription-auth/runtime.ts";
import {
makeManualOnlyProviderMaintenanceCapabilities,
makeStaticProviderMaintenanceResolver,
@@ -88,8 +88,9 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
+ const { secretsDir } = yield* ServerConfig;
const eventLoggers = yield* ProviderEventLoggers;
- const processEnv = mergeProviderInstanceEnvironment(environment);
+ const processEnv = mergeSubscriptionInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
instanceId,
@@ -111,7 +112,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
instanceId,
});
- const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
+ const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv, secretsDir);
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe(
Effect.map(stampIdentity),
diff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.ts
index a01e414f8..586b6acda 100644
--- a/apps/server/src/provider/Drivers/OpenCodeDriver.ts
+++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts
@@ -40,7 +40,7 @@ import {
type ProviderInstance,
} from "../ProviderDriver.ts";
import type { ServerProviderDraft } from "../providerSnapshot.ts";
-import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
+import { mergeSubscriptionInstanceEnvironment } from "../../subscription-auth/runtime.ts";
import {
enrichProviderSnapshotWithVersionAdvisory,
makePackageManagedProviderMaintenanceResolver,
@@ -119,7 +119,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
- const processEnv = mergeProviderInstanceEnvironment(environment);
+ const processEnv = mergeSubscriptionInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
instanceId,
diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.ts
index ad6fc1d7e..5360711e4 100644
--- a/apps/server/src/provider/Layers/AgentController.ts
+++ b/apps/server/src/provider/Layers/AgentController.ts
@@ -713,7 +713,9 @@ const make = (options?: AgentControllerLiveOptions) =>
makeMastraHarness({
authStorage,
getKimiAccess: () => subscriptionAuth.getKimiForCodingAccess(),
- getOpenCodeGoApiKey: () => subscriptionAuth.getAccessToken("opencode-go"),
+ getOpenCodeGoApiKey: async () =>
+ subscriptionAuth.getApiKeyCredential("opencode-go")?.access,
+ getSubscriptionApiKey: (provider) => subscriptionAuth.getApiKeyCredential(provider),
memoryDbPath: NodePath.join(config.stateDir, "mastra-observational-memory.sqlite"),
syncThreadToolApproval: async (threadId, toolName, protectedAction) => {
const active = sessions.get(threadId);
diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts
index 73323a96b..3b9ed57c6 100644
--- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts
+++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts
@@ -34,6 +34,7 @@ import * as TestClock from "effect/testing/TestClock";
import { attachmentRelativePath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
+import { SubscriptionAuthService } from "../../subscription-auth/service.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterProcessError, ProviderAdapterValidationError } from "../Errors.ts";
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
@@ -267,6 +268,34 @@ const THREAD_ID = ThreadId.make("thread-claude-1");
const RESUME_THREAD_ID = ThreadId.make("thread-claude-resume");
describe("ClaudeAdapterLive", () => {
+ it.effect("passes a newly saved API key and endpoint to the Claude SDK", () => {
+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-claude-api-key-"));
+ const harness = makeHarness({ baseDir: directory });
+ return Effect.gen(function* () {
+ const adapter = yield* ClaudeAdapter;
+ const config = yield* ServerConfig;
+ const auth = SubscriptionAuthService.forSecretsDir(config.secretsDir);
+ const login = yield* Effect.promise(() =>
+ auth.startLogin("anthropic", { authMode: "api-key", baseUrl: "https://proxy.example/v1" }),
+ );
+ yield* Effect.promise(() => auth.completeLogin(login.loginId, "sdk-api-key"));
+ yield* adapter.startSession({
+ threadId: THREAD_ID,
+ provider: ProviderDriverKind.make("claudeAgent"),
+ runtimeMode: "full-access",
+ });
+ const environment = harness.getLastCreateQueryInput()?.options.env;
+ assert.equal(environment?.ANTHROPIC_API_KEY, "sdk-api-key");
+ assert.equal(environment?.ANTHROPIC_BASE_URL, "https://proxy.example");
+ assert.isUndefined(environment?.CLAUDE_CODE_OAUTH_TOKEN);
+ assert.isUndefined(environment?.ANTHROPIC_AUTH_TOKEN);
+ }).pipe(
+ Effect.provide(harness.layer),
+ Effect.ensuring(
+ Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true })),
+ ),
+ );
+ });
it.effect("returns validation error for non-claude provider on startSession", () => {
const harness = makeHarness();
return Effect.gen(function* () {
diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts
index 6eb624599..fb7c43570 100644
--- a/apps/server/src/provider/Layers/ClaudeAdapter.ts
+++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts
@@ -78,6 +78,7 @@ import * as Stream from "effect/Stream";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
+import { subscriptionRuntimeEnvironment } from "../../subscription-auth/runtime.ts";
import {
createAkeruAgentInstructions,
createAkeruBotInstructions,
@@ -4346,7 +4347,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
canUseTool,
onUserDialog,
supportedDialogKinds: ["resume_return"],
- env: claudeEnvironment,
+ env: subscriptionRuntimeEnvironment(
+ serverConfig.secretsDir,
+ "anthropic",
+ claudeEnvironment,
+ ),
additionalDirectories,
...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),
...(Object.keys(mcpServers).length > 0 ? { mcpServers } : {}),
diff --git a/apps/server/src/provider/Layers/GrokAdapter.ts b/apps/server/src/provider/Layers/GrokAdapter.ts
index 27283ded5..1747e0f12 100644
--- a/apps/server/src/provider/Layers/GrokAdapter.ts
+++ b/apps/server/src/provider/Layers/GrokAdapter.ts
@@ -34,6 +34,7 @@ import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
+import { subscriptionRuntimeEnvironment } from "../../subscription-auth/runtime.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import { toAcpMcpServers } from "../McpServerConfig.ts";
import {
@@ -591,7 +592,11 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
];
const acp = yield* makeGrokAcpRuntime({
grokSettings,
- ...(options?.environment ? { environment: options.environment } : {}),
+ environment: subscriptionRuntimeEnvironment(
+ serverConfig.secretsDir,
+ "xai",
+ options?.environment,
+ ),
childProcessSpawner,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.ts
index ee3b3f280..2f5421db1 100644
--- a/apps/server/src/provider/Layers/OpenCodeAdapter.ts
+++ b/apps/server/src/provider/Layers/OpenCodeAdapter.ts
@@ -28,6 +28,7 @@ import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
+import { subscriptionRuntimeEnvironment } from "../../subscription-auth/runtime.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import {
@@ -1224,7 +1225,11 @@ export function makeOpenCodeAdapter(
const server = yield* openCodeRuntime.connectToOpenCodeServer({
binaryPath,
serverUrl,
- ...(options?.environment ? { environment: options.environment } : {}),
+ environment: subscriptionRuntimeEnvironment(
+ serverConfig.secretsDir,
+ "opencode-go",
+ options?.environment,
+ ),
});
const client = openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
diff --git a/apps/server/src/subscription-auth/runtime.test.ts b/apps/server/src/subscription-auth/runtime.test.ts
new file mode 100644
index 000000000..07a3f52df
--- /dev/null
+++ b/apps/server/src/subscription-auth/runtime.test.ts
@@ -0,0 +1,227 @@
+// @effect-diagnostics nodeBuiltinImport:off
+import * as NodeFS from "node:fs";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+import { SubscriptionAuthService } from "./service.ts";
+import {
+ mergeSubscriptionInstanceEnvironment,
+ subscriptionRequestUrl,
+ subscriptionRuntimeEnvironment,
+ withExplicitEnvironmentKeys,
+} from "./runtime.ts";
+
+const directories: string[] = [];
+function fixture() {
+ const secretsDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-runtime-auth-"));
+ directories.push(secretsDir);
+ return { secretsDir, auth: SubscriptionAuthService.forSecretsDir(secretsDir) };
+}
+afterEach(() => {
+ for (const directory of directories.splice(0))
+ NodeFS.rmSync(directory, { recursive: true, force: true });
+});
+
+describe("subscription runtime credentials", () => {
+ it.each([
+ ["anthropic", "ANTHROPIC_API_KEY", "instance-key"],
+ ["anthropic", "ANTHROPIC_API_KEY", ""],
+ ["anthropic", "ANTHROPIC_AUTH_TOKEN", "instance-token"],
+ ["anthropic", "CLAUDE_CODE_OAUTH_TOKEN", "instance-oauth"],
+ ["anthropic", "ANTHROPIC_BASE_URL", "https://instance.example"],
+ ["anthropic", "CLAUDE_CONFIG_DIR", "/instance/claude"],
+ ["xai", "XAI_API_KEY", "instance-key"],
+ ["opencode-go", "OPENCODE_API_KEY", "instance-key"],
+ ] as const)(
+ "preserves explicit %s %s settings even when equal to inherited values",
+ async (provider, name, value) => {
+ const { secretsDir, auth } = fixture();
+ const login = await auth.startLogin(provider, { authMode: "api-key" });
+ await auth.completeLogin(login.loginId, "provider-wide-key");
+ const environment = {
+ ...mergeSubscriptionInstanceEnvironment([{ name, value, sensitive: true }], {
+ [name]: value,
+ KEEP: "value",
+ }),
+ };
+ expect(subscriptionRuntimeEnvironment(secretsDir, provider, environment)).toBe(environment);
+ expect(environment[name]).toBe(value);
+ expect(JSON.stringify(environment)).not.toContain("provider-wide-key");
+ },
+ );
+
+ it("keeps a home-isolated Claude instance on its own account", async () => {
+ const { secretsDir, auth } = fixture();
+ const login = await auth.startLogin("anthropic", { authMode: "api-key" });
+ await auth.completeLogin(login.loginId, "provider-wide-key");
+ const merged = mergeSubscriptionInstanceEnvironment(undefined, {
+ CLAUDE_CODE_OAUTH_TOKEN: "native-oauth",
+ });
+ const environment = withExplicitEnvironmentKeys(
+ { ...merged, CLAUDE_CONFIG_DIR: "/instance/claude" },
+ ["CLAUDE_CONFIG_DIR"],
+ );
+ expect(subscriptionRuntimeEnvironment(secretsDir, "anthropic", environment)).toBe(environment);
+ expect(environment.CLAUDE_CODE_OAUTH_TOKEN).toBe("native-oauth");
+ expect(environment.ANTHROPIC_API_KEY).toBeUndefined();
+ });
+
+ it("replaces an inherited Grok key when only unrelated instance variables are explicit", async () => {
+ const { secretsDir, auth } = fixture();
+ const login = await auth.startLogin("xai", { authMode: "api-key" });
+ await auth.completeLogin(login.loginId, "provider-wide-key");
+ const environment = {
+ ...mergeSubscriptionInstanceEnvironment(
+ [{ name: "KEEP", value: "instance-value", sensitive: false }],
+ { XAI_API_KEY: "inherited-key", KEEP: "inherited-value" },
+ ),
+ };
+ expect(subscriptionRuntimeEnvironment(secretsDir, "xai", environment)).toEqual({
+ XAI_API_KEY: "provider-wide-key",
+ KEEP: "instance-value",
+ });
+ });
+
+ it("does not override a directly supplied adapter environment", async () => {
+ const { secretsDir, auth } = fixture();
+ const login = await auth.startLogin("xai", { authMode: "api-key" });
+ await auth.completeLogin(login.loginId, "provider-wide-key");
+ const environment = { XAI_API_KEY: "adapter-key" };
+ expect(subscriptionRuntimeEnvironment(secretsDir, "xai", environment)).toBe(environment);
+ });
+
+ it("distinguishes explicit OpenCode credentials from inherited OpenCode credentials", async () => {
+ const { secretsDir, auth } = fixture();
+ const login = await auth.startLogin("opencode-go", { authMode: "api-key" });
+ await auth.completeLogin(login.loginId, "provider-wide-key");
+ const content = JSON.stringify({
+ provider: {
+ "opencode-go": {
+ options: { apiKey: "instance-key", baseURL: "https://instance.example/v1" },
+ },
+ },
+ });
+ const baseEnv = { OPENCODE_CONFIG_CONTENT: content };
+ const explicit = {
+ ...mergeSubscriptionInstanceEnvironment(
+ [{ name: "OPENCODE_CONFIG_CONTENT", value: content, sensitive: true }],
+ baseEnv,
+ ),
+ };
+ expect(subscriptionRuntimeEnvironment(secretsDir, "opencode-go", explicit)).toBe(explicit);
+ const inherited = { ...mergeSubscriptionInstanceEnvironment(undefined, baseEnv) };
+ const result = subscriptionRuntimeEnvironment(secretsDir, "opencode-go", inherited);
+ expect(JSON.parse(result.OPENCODE_CONFIG_CONTENT!).provider["opencode-go"].options).toEqual({
+ apiKey: "provider-wide-key",
+ baseURL: "https://opencode.ai/zen/go/v1",
+ });
+ });
+
+ it.each([
+ ["https://proxy.example", "https://proxy.example"],
+ ["https://proxy.example/v1", "https://proxy.example"],
+ ["https://proxy.example/v1/", "https://proxy.example"],
+ ["https://proxy.example/gateway/v1/", "https://proxy.example/gateway"],
+ ])("uses the same Claude root for health and SDK requests: %s", async (baseUrl, root) => {
+ const { secretsDir, auth } = fixture();
+ const login = await auth.startLogin("anthropic", { authMode: "api-key", baseUrl });
+ await auth.completeLogin(login.loginId, "claude-key");
+ const environment = subscriptionRuntimeEnvironment(
+ secretsDir,
+ "anthropic",
+ mergeSubscriptionInstanceEnvironment(undefined, {}),
+ );
+ expect(environment.ANTHROPIC_BASE_URL).toBe(root);
+ const request = vi.fn().mockResolvedValue(new Response("{}"));
+ vi.stubGlobal("fetch", request);
+ try {
+ await auth.testHealth("anthropic");
+ expect(request).toHaveBeenCalledWith(
+ `${environment.ANTHROPIC_BASE_URL}/v1/models`,
+ expect.any(Object),
+ );
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+ it("reads Claude keys at process start and leaves the original environment unchanged", async () => {
+ const { secretsDir, auth } = fixture();
+ const environment = {
+ ...mergeSubscriptionInstanceEnvironment(undefined, {
+ CLAUDE_CODE_OAUTH_TOKEN: "native-oauth",
+ ANTHROPIC_AUTH_TOKEN: "native-token",
+ KEEP: "value",
+ }),
+ };
+ expect(subscriptionRuntimeEnvironment(secretsDir, "anthropic", environment)).toBe(environment);
+ const login = await auth.startLogin("anthropic", {
+ authMode: "api-key",
+ baseUrl: "https://proxy.example/v1",
+ });
+ await auth.completeLogin(login.loginId, "new-key");
+ expect(subscriptionRuntimeEnvironment(secretsDir, "anthropic", environment)).toEqual({
+ KEEP: "value",
+ ANTHROPIC_API_KEY: "new-key",
+ ANTHROPIC_BASE_URL: "https://proxy.example",
+ });
+ auth.logout("anthropic");
+ expect(subscriptionRuntimeEnvironment(secretsDir, "anthropic", environment)).toBe(environment);
+ expect(environment.CLAUDE_CODE_OAUTH_TOKEN).toBe("native-oauth");
+ });
+
+ it("passes saved Grok API keys to the ACP authentication environment", async () => {
+ const { secretsDir, auth } = fixture();
+ const login = await auth.startLogin("xai", { authMode: "api-key" });
+ await auth.completeLogin(login.loginId, "grok-key");
+ expect(subscriptionRuntimeEnvironment(secretsDir, "xai", { KEEP: "value" })).toEqual({
+ KEEP: "value",
+ XAI_API_KEY: "grok-key",
+ });
+ });
+
+ it("merges OpenCode Go credentials without deleting other OpenCode providers or options", async () => {
+ const { secretsDir, auth } = fixture();
+ const login = await auth.startLogin("opencode-go", {
+ authMode: "api-key",
+ baseUrl: "https://proxy.example/v1",
+ });
+ await auth.completeLogin(login.loginId, "go-key");
+ const result = subscriptionRuntimeEnvironment(secretsDir, "opencode-go", {
+ OPENCODE_CONFIG_CONTENT: JSON.stringify({
+ theme: "dark",
+ provider: { other: { name: "Other" }, "opencode-go": { options: { timeout: 1000 } } },
+ }),
+ });
+ expect(JSON.parse(result.OPENCODE_CONFIG_CONTENT!)).toEqual({
+ theme: "dark",
+ provider: {
+ other: { name: "Other" },
+ "opencode-go": {
+ options: { timeout: 1000, apiKey: "go-key", baseURL: "https://proxy.example/v1" },
+ },
+ },
+ });
+ });
+
+ it("preserves Request bodies and URL suffixes when changing endpoints", async () => {
+ const request = new Request("https://api.example/v1/messages?beta=true", {
+ method: "POST",
+ body: "request-body",
+ });
+ const rewritten = subscriptionRequestUrl(
+ request,
+ "https://api.example/v1",
+ "http://localhost:8000/api",
+ );
+ expect(rewritten).toBeInstanceOf(Request);
+ expect((rewritten as Request).url).toBe("http://localhost:8000/api/messages?beta=true");
+ expect(await (rewritten as Request).text()).toBe("request-body");
+ expect(() =>
+ subscriptionRequestUrl(
+ "https://elsewhere.example/v1/messages",
+ "https://api.example/v1",
+ "http://localhost:8000/api",
+ ),
+ ).toThrow("does not match");
+ });
+});
diff --git a/apps/server/src/subscription-auth/runtime.ts b/apps/server/src/subscription-auth/runtime.ts
new file mode 100644
index 000000000..e4a89d579
--- /dev/null
+++ b/apps/server/src/subscription-auth/runtime.ts
@@ -0,0 +1,145 @@
+import type { ProviderInstanceConfig, ProviderInstanceEnvironment } from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+
+import { mergeProviderInstanceEnvironment } from "../provider/ProviderInstanceEnvironment.ts";
+import {
+ anthropicApiBaseUrl,
+ SubscriptionAuthService,
+ type SubscriptionProviderId,
+} from "./service.ts";
+
+const explicitEnvironmentKeys = Symbol("subscriptionInstanceEnvironmentKeys");
+type SubscriptionEnvironment = NodeJS.ProcessEnv & {
+ readonly [explicitEnvironmentKeys]?: ReadonlySet<string>;
+};
+
+/** The symbol survives environment spreads without becoming a child-process variable. */
+export function mergeSubscriptionInstanceEnvironment(
+ environment: ProviderInstanceEnvironment | undefined,
+ baseEnv: NodeJS.ProcessEnv = process.env,
+): SubscriptionEnvironment {
+ return {
+ ...mergeProviderInstanceEnvironment(environment, baseEnv),
+ [explicitEnvironmentKeys]: new Set(environment?.map(({ name }) => name)),
+ };
+}
+
+/** Drivers call this after they add their own isolation variables to a merged environment. */
+export function withExplicitEnvironmentKeys(
+ environment: NodeJS.ProcessEnv,
+ keys: Iterable<string>,
+): SubscriptionEnvironment {
+ const existing = (environment as SubscriptionEnvironment)[explicitEnvironmentKeys];
+ return {
+ ...environment,
+ [explicitEnvironmentKeys]: new Set([...(existing ?? []), ...keys]),
+ };
+}
+
+function hasExplicitEnvironmentKey(environment: SubscriptionEnvironment, key: string): boolean {
+ const keys = environment[explicitEnvironmentKeys];
+ return keys ? keys.has(key) : environment !== process.env && Object.hasOwn(environment, key);
+}
+
+const CONNECTION_ENV_KEYS: Partial<Record<SubscriptionProviderId, ReadonlyArray<string>>> = {
+ anthropic: [
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_AUTH_TOKEN",
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ "ANTHROPIC_BASE_URL",
+ "CLAUDE_CONFIG_DIR",
+ ],
+ xai: ["XAI_API_KEY"],
+ "opencode-go": ["OPENCODE_API_KEY"],
+};
+
+/** False when the instance brings its own connection, so a saved provider-wide key does not reach it. */
+export function instanceUsesSavedCredential(
+ provider: SubscriptionProviderId,
+ instance: ProviderInstanceConfig | undefined,
+): boolean {
+ if (!instance) return true;
+ const connectionKeys = CONNECTION_ENV_KEYS[provider] ?? [];
+ if (instance.environment?.some(({ name }) => connectionKeys.includes(name))) return false;
+ if (provider === "anthropic") {
+ const config = instance.config;
+ const homePath =
+ typeof config === "object" && config !== null && "homePath" in config
+ ? config.homePath
+ : undefined;
+ if (typeof homePath === "string" && homePath.trim().length > 0) return false;
+ }
+ return true;
+}
+
+const ConfigRecord = Schema.Record(Schema.String, Schema.Unknown);
+const decodeConfig = Schema.decodeUnknownSync(Schema.fromJsonString(ConfigRecord));
+const decodeRecord = Schema.decodeUnknownSync(ConfigRecord);
+
+/** Read saved API keys at process start, not when the provider registry starts. */
+export function subscriptionRuntimeEnvironment(
+ secretsDir: string,
+ provider: SubscriptionProviderId,
+ environment: SubscriptionEnvironment = process.env,
+): NodeJS.ProcessEnv {
+ const connectionKeys = CONNECTION_ENV_KEYS[provider] ?? [];
+ if (connectionKeys.some((key) => hasExplicitEnvironmentKey(environment, key))) return environment;
+ const credential =
+ SubscriptionAuthService.forSecretsDir(secretsDir).getApiKeyCredential(provider);
+ if (!credential) return environment;
+ const { [explicitEnvironmentKeys]: _explicitKeys, ...env } = environment;
+ switch (provider) {
+ case "anthropic":
+ delete env.CLAUDE_CODE_OAUTH_TOKEN;
+ delete env.ANTHROPIC_AUTH_TOKEN;
+ env.ANTHROPIC_API_KEY = credential.access;
+ if (credential.baseUrl) env.ANTHROPIC_BASE_URL = anthropicApiBaseUrl(credential.baseUrl);
+ else delete env.ANTHROPIC_BASE_URL;
+ break;
+ case "xai":
+ env.XAI_API_KEY = credential.access;
+ break;
+ case "opencode-go": {
+ const config = decodeConfig(env.OPENCODE_CONFIG_CONTENT ?? "{}");
+ const providers = decodeRecord(config.provider ?? {});
+ const providerConfig = decodeRecord(providers["opencode-go"] ?? {});
+ const options = decodeRecord(providerConfig.options ?? {});
+ if (
+ hasExplicitEnvironmentKey(environment, "OPENCODE_CONFIG_CONTENT") &&
+ (Object.hasOwn(options, "apiKey") || Object.hasOwn(options, "baseURL"))
+ )
+ return environment;
+ env.OPENCODE_CONFIG_CONTENT = JSON.stringify({
+ ...config,
+ provider: {
+ ...providers,
+ "opencode-go": {
+ ...providerConfig,
+ options: {
+ ...options,
+ apiKey: credential.access,
+ baseURL: credential.baseUrl ?? "https://opencode.ai/zen/go/v1",
+ },
+ },
+ },
+ });
+ break;
+ }
+ }
+ return env;
+}
+
+/** Keep the SDK's endpoint suffix and request body when changing API origins. */
+export function subscriptionRequestUrl(
+ input: string | URL | Request,
+ defaultBaseUrl: string,
+ baseUrl: string | undefined,
+): string | URL | Request {
+ if (!baseUrl) return input;
+ const url = input instanceof Request ? input.url : String(input);
+ if (!url.startsWith(`${defaultBaseUrl}/`)) {
+ throw new Error("The provider request does not match its API base URL.");
+ }
+ const target = `${baseUrl}${url.slice(defaultBaseUrl.length)}`;
+ return input instanceof Request ? new Request(target, input) : target;
+}
diff --git a/apps/server/src/subscription-auth/service.test.ts b/apps/server/src/subscription-auth/service.test.ts
index 432cb7cc6..ca3f9c5f2 100644
--- a/apps/server/src/subscription-auth/service.test.ts
+++ b/apps/server/src/subscription-auth/service.test.ts
@@ -18,6 +18,284 @@ function fixture() {
}
describe("subscription auth storage", () => {
+ it("keeps API keys away from subscription plan endpoints except default OpenCode Go", async () => {
+ const { authPath } = fixture();
+ const service = new SubscriptionAuthService(authPath);
+ const anthropic = await service.startLogin("anthropic", { authMode: "api-key" });
+ await service.completeLogin(anthropic.loginId, "anthropic-key");
+ expect(await service.getPlanAccessToken("anthropic")).toBeUndefined();
+ const go = await service.startLogin("opencode-go");
+ await service.completeLogin(go.loginId, "go-key");
+ expect(await service.getPlanAccessToken("opencode-go")).toBe("go-key");
+ const custom = await service.startLogin("opencode-go", {
+ authMode: "api-key",
+ baseUrl: "https://proxy.example/v1",
+ });
+ await service.completeLogin(custom.loginId, "custom-key");
+ expect(await service.getPlanAccessToken("opencode-go")).toBeUndefined();
+ });
+ it("switches back to OAuth without retaining the API endpoint or key", async () => {
+ const { authPath } = fixture();
+ const service = new SubscriptionAuthService(authPath);
+ const keyLogin = await service.startLogin("anthropic", {
+ authMode: "api-key",
+ baseUrl: "https://proxy.example/v1",
+ });
+ await service.completeLogin(keyLogin.loginId, "old-api-key");
+ service.recordRequestFailure("anthropic", "Key rejected");
+ const oauth = await service.startLogin("anthropic");
+ const state = new URL(oauth.url).searchParams.get("state");
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ access_token: "oauth-access",
+ refresh_token: "oauth-refresh",
+ expires_in: 3600,
+ }),
+ { headers: { "content-type": "application/json" } },
+ ),
+ ),
+ );
+ try {
+ expect(await service.completeLogin(oauth.loginId, `code#${state}`)).toEqual({
+ status: "connected",
+ });
+ expect(service.statuses()[0]).toMatchObject({ authMode: "oauth", health: "detected" });
+ expect(service.statuses()[0]?.baseUrl).toBeUndefined();
+ expect(service.getApiKeyCredential("anthropic")).toBeUndefined();
+ expect(NodeFS.readFileSync(authPath, "utf-8")).not.toContain("old-api-key");
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it.each(["refresh", "health"] as const)(
+ "does not let an in-flight OAuth %s replace a saved API key",
+ async (operation) => {
+ const { authPath } = fixture();
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({
+ xai: { type: "oauth", access: "old", refresh: "old-refresh", expires: 0 },
+ }),
+ );
+ const service = new SubscriptionAuthService(authPath);
+ let completeRequest!: (response: Response) => void;
+ const response = new Promise<Response>((resolve) => {
+ completeRequest = resolve;
+ });
+ const request = vi.fn(() => response);
+ vi.stubGlobal("fetch", request);
+ try {
+ const refreshing =
+ operation === "refresh" ? service.getAccessToken("xai") : service.testHealth("xai");
+ expect(request).toHaveBeenCalledOnce();
+ const login = await service.startLogin("xai", { authMode: "api-key" });
+ await service.completeLogin(login.loginId, "replacement-key");
+ completeRequest(
+ new Response(JSON.stringify({ access_token: "late-oauth-token", expires_in: 3600 }), {
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ await refreshing;
+ expect(service.getApiKeyCredential("xai")?.access).toBe("replacement-key");
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ },
+ );
+
+ it("does not let an OAuth health check undo logout from another service", async () => {
+ const { authPath } = fixture();
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({
+ xai: { type: "oauth", access: "old-access", refresh: "old-refresh", expires: 0 },
+ }),
+ );
+ const checking = new SubscriptionAuthService(authPath);
+ const other = new SubscriptionAuthService(authPath);
+ let completeRequest!: (response: Response) => void;
+ const request = vi.fn(
+ () =>
+ new Promise<Response>((resolve) => {
+ completeRequest = resolve;
+ }),
+ );
+ vi.stubGlobal("fetch", request);
+ try {
+ const pending = checking.testHealth("xai");
+ expect(request).toHaveBeenCalledOnce();
+ other.logout("xai");
+ completeRequest(
+ new Response(JSON.stringify({ access_token: "late-access", expires_in: 3600 }), {
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ await pending;
+ const status = checking.statuses().find((entry) => entry.provider === "xai");
+ expect(status?.connected).toBe(false);
+ expect(status?.oauthCheck).toBeUndefined();
+ expect(JSON.parse(NodeFS.readFileSync(authPath, "utf-8"))).toEqual({});
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("removes pending API-key logins on logout and reads cancellations from disk", async () => {
+ const { authPath } = fixture();
+ const first = new SubscriptionAuthService(authPath);
+ const login = await first.startLogin("anthropic", { authMode: "api-key" });
+ const second = new SubscriptionAuthService(authPath);
+ first.cancelLogin(login.loginId);
+ expect(await second.completeLogin(login.loginId, "key")).toMatchObject({ status: "failed" });
+ const pending = await first.startLogin("anthropic", { authMode: "api-key" });
+ second.logout("anthropic");
+ expect(await first.completeLogin(pending.loginId, "key")).toMatchObject({ status: "failed" });
+ });
+
+ it("redacts saved API keys from provider failures recorded by an older runtime", async () => {
+ const { authPath } = fixture();
+ const runtime = new SubscriptionAuthService(authPath);
+ const auth = new SubscriptionAuthService(authPath);
+ const login = await auth.startLogin("xai", { authMode: "api-key" });
+ await auth.completeLogin(login.loginId, "private-key");
+ runtime.recordRequestFailure("xai", "Rejected private-key");
+ expect(JSON.stringify(runtime.statuses())).not.toContain("private-key");
+ expect(NodeFS.readFileSync(`${authPath}.health`, "utf-8")).not.toContain("private-key");
+ });
+ it.each(["anthropic", "openai-codex", "xai", "kimi-for-coding", "opencode-go"] as const)(
+ "saves %s API keys through complete and never returns the key",
+ async (provider) => {
+ const { authPath } = fixture();
+ const service = new SubscriptionAuthService(authPath);
+ const options = {
+ authMode: "api-key" as const,
+ ...(provider === "xai" ? {} : { baseUrl: "https://proxy.example/v1/" }),
+ };
+ const started = await service.startLogin(provider, options);
+ expect(started.completion).toBe("paste");
+ expect(NodeFS.readFileSync(`${authPath}.pending`, "utf-8")).not.toContain("test-secret");
+ const restarted = new SubscriptionAuthService(authPath);
+ expect(await restarted.pollLogin(started.loginId)).toMatchObject({ status: "pending" });
+ expect(await restarted.completeLogin(started.loginId, " test-secret ")).toEqual({
+ status: "connected",
+ });
+ expect(await restarted.completeLogin(started.loginId, "replacement")).toMatchObject({
+ status: "failed",
+ });
+ expect(restarted.getApiKeyCredential(provider)).toMatchObject({
+ type: "api-key",
+ access: "test-secret",
+ });
+ expect(restarted.statuses().find((status) => status.provider === provider)).toMatchObject({
+ connected: true,
+ authMode: "api-key",
+ });
+ expect(JSON.stringify(restarted.statuses())).not.toContain("test-secret");
+ expect(NodeFS.statSync(authPath).mode & 0o777).toBe(0o600);
+ },
+ );
+
+ it("rejects invalid keys without replacing OAuth and clears old health on save", async () => {
+ const { authPath } = fixture();
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({
+ anthropic: {
+ type: "oauth",
+ access: "oauth",
+ refresh: "refresh",
+ expires: Date.now() + 60_000,
+ },
+ }),
+ );
+ const service = new SubscriptionAuthService(authPath);
+ service.recordRequestFailure("anthropic", "Old failure");
+ const started = await service.startLogin("anthropic", { authMode: "api-key" });
+ expect(await service.completeLogin(started.loginId, " \n ")).toMatchObject({
+ status: "failed",
+ });
+ expect(await service.getAccessToken("anthropic")).toBe("oauth");
+ expect(await service.completeLogin(started.loginId, "new-key")).toEqual({
+ status: "connected",
+ });
+ expect(service.statuses()[0]).toMatchObject({
+ health: "detected",
+ healthTest: { status: "not-run" },
+ });
+ expect(service.statuses()[0]?.lastFailedRequest).toBeUndefined();
+ const oauth = await service.startLogin("anthropic");
+ expect(oauth.url).toContain("https://");
+ service.cancelLogin(oauth.loginId);
+ expect(await service.getAccessToken("anthropic")).toBe("new-key");
+ service.logout("anthropic");
+ expect(service.statuses()[0]).toMatchObject({ connected: false });
+ expect(service.statuses()[0]?.authMode).toBeUndefined();
+ });
+
+ it("rejects unsupported modes and base URLs before creating pending state", async () => {
+ const { authPath } = fixture();
+ const service = new SubscriptionAuthService(authPath);
+ await expect(service.startLogin("cursor", { authMode: "api-key" })).rejects.toThrow(
+ "not supported",
+ );
+ await expect(
+ service.startLogin("xai", { authMode: "api-key", baseUrl: "https://example.com" }),
+ ).rejects.toThrow("does not support");
+ await expect(
+ service.startLogin("anthropic", { baseUrl: "https://example.com" }),
+ ).rejects.toThrow("require API-key");
+ await expect(
+ service.startLogin("anthropic", {
+ authMode: "api-key",
+ baseUrl: "https://user:[email protected]",
+ }),
+ ).rejects.toThrow();
+ expect(NodeFS.existsSync(`${authPath}.pending`)).toBe(false);
+ });
+
+ it("checks custom API endpoints without exposing network errors or using OAuth refresh", async () => {
+ const { authPath } = fixture();
+ const service = new SubscriptionAuthService(authPath);
+ const started = await service.startLogin("anthropic", {
+ authMode: "api-key",
+ baseUrl: "https://proxy.example/v1",
+ });
+ await service.completeLogin(started.loginId, "private-key");
+ const request = vi.fn().mockRejectedValue(new Error("private-key"));
+ vi.stubGlobal("fetch", request);
+ try {
+ await service.testHealth("anthropic");
+ expect(request).toHaveBeenCalledWith(
+ "https://proxy.example/v1/models",
+ expect.objectContaining({
+ redirect: "error",
+ headers: expect.objectContaining({ "x-api-key": "private-key" }),
+ }),
+ );
+ expect(JSON.stringify(service.statuses())).not.toContain("private-key");
+ expect(service.statuses()[0]?.oauthCheck).toBeUndefined();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("returns API-key Kimi access without an OAuth device identity", async () => {
+ const { authPath } = fixture();
+ const service = new SubscriptionAuthService(authPath);
+ const started = await service.startLogin("kimi-for-coding", {
+ authMode: "api-key",
+ baseUrl: "http://localhost:8888/v1",
+ });
+ await service.completeLogin(started.loginId, "kimi-key");
+ expect(await service.getKimiForCodingAccess()).toEqual({
+ accessToken: "kimi-key",
+ baseUrl: "http://localhost:8888/v1",
+ });
+ });
it("loads provider status without exposing tokens", () => {
const { authPath } = fixture();
NodeFS.writeFileSync(
@@ -37,6 +315,7 @@ describe("subscription auth storage", () => {
expect(anthropic).toEqual({
provider: "anthropic",
connected: true,
+ authMode: "oauth",
expiresAt: 1_800_000_000_000,
health: "detected",
reconnectAction: "Reconnect account",
diff --git a/apps/server/src/subscription-auth/service.ts b/apps/server/src/subscription-auth/service.ts
index ef7760c33..284843967 100644
--- a/apps/server/src/subscription-auth/service.ts
+++ b/apps/server/src/subscription-auth/service.ts
@@ -17,7 +17,12 @@
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeCrypto from "node:crypto";
-import type { BotId } from "@t3tools/contracts";
+import {
+ SubscriptionBaseUrl,
+ type BotId,
+ type SubscriptionAuthStartInput,
+} from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
import {
completeAnthropicLogin,
@@ -49,7 +54,19 @@ import {
startXAIDeviceLogin,
type XAIDeviceLoginPending,
} from "./providers/xai.ts";
-import type { OAuthCredential, OAuthCredentials, SubscriptionAuthData } from "./types.ts";
+import type {
+ ApiKeyCredential,
+ OAuthCredential,
+ OAuthCredentials,
+ SubscriptionAuthData,
+} from "./types.ts";
+
+const decodeBaseUrl = Schema.decodeUnknownSync(SubscriptionBaseUrl);
+
+/** Anthropic endpoints use an API root; a trailing /v1 is accepted for compatibility. */
+export function anthropicApiBaseUrl(baseUrl = "https://api.anthropic.com"): string {
+ return baseUrl.replace(/\/+$/, "").replace(/\/v1$/, "");
+}
const OPENCODE_GO_AUTH_URL = "https://opencode.ai/auth";
const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
@@ -92,6 +109,8 @@ export type LoginPollStatus =
export interface ProviderStatus {
provider: SubscriptionProviderId;
connected: boolean;
+ authMode?: "oauth" | "api-key";
+ baseUrl?: string;
/** ms epoch when the current access token expires; refreshed on demand. */
expiresAt?: number;
health:
@@ -139,6 +158,7 @@ function oauthFailureKind(cause: unknown): "request" | "revoked" {
}
type PendingLogin =
+ | { provider: SubscriptionProviderId; authMode: "api-key"; baseUrl?: string }
| { provider: "anthropic"; verifier: string }
| { provider: "openai-codex"; pending: CodexDeviceLoginPending }
| { provider: "cursor"; pending: CursorLoginPending }
@@ -272,6 +292,10 @@ export class SubscriptionAuthService {
return {
provider,
connected: credential !== undefined,
+ ...(credential ? { authMode: credential.type } : {}),
+ ...(credential?.type === "api-key" && credential.baseUrl
+ ? { baseUrl: credential.baseUrl }
+ : {}),
...(credential?.type === "oauth" ? { expiresAt: credential.expires } : {}),
health: state,
...(health?.lastSuccessfulRequestAt
@@ -280,7 +304,7 @@ export class SubscriptionAuthService {
...(health?.lastFailedRequest ? { lastFailedRequest: health.lastFailedRequest } : {}),
...(health?.nextRetryAt ? { nextRetryAt: health.nextRetryAt } : {}),
reconnectAction:
- provider === "opencode-go"
+ credential?.type === "api-key" || provider === "opencode-go"
? credential
? "Replace API key"
: "Connect API key"
@@ -348,8 +372,16 @@ export class SubscriptionAuthService {
at: string,
failureKind: "request" | "revoked",
): void {
- this.reloadHealth();
+ this.reload();
const { nextRetryAt: _nextRetryAt, ...previous } = this.health[key] ?? {};
+ for (const credential of Object.values(this.data)) {
+ for (const secret of [
+ credential.access,
+ credential.type === "oauth" ? credential.refresh : undefined,
+ ]) {
+ if (secret) message = message.replaceAll(secret, "[redacted]");
+ }
+ }
this.health[key] = {
...previous,
lastFailedRequest: { at, message },
@@ -417,40 +449,61 @@ export class SubscriptionAuthService {
}
async testHealth(provider: SubscriptionProviderId): Promise<void> {
+ this.reload();
const credential = this.data[provider];
if (!credential) {
this.recordOAuthFailure(provider, "No account is connected.");
return;
}
- if (provider === "opencode-go") {
+ if (credential.type === "api-key") {
+ const defaultBaseUrls: Record<SubscriptionProviderId, string> = {
+ anthropic: "https://api.anthropic.com/v1",
+ "openai-codex": "https://api.openai.com/v1",
+ cursor: "https://api.cursor.com",
+ xai: "https://api.x.ai/v1",
+ "kimi-for-coding": "https://api.kimi.com/coding/v1",
+ "opencode-go": "https://opencode.ai/zen/go/v1",
+ };
+ const url =
+ provider === "opencode-go" && !credential.baseUrl
+ ? OPENCODE_GO_USAGE_URL
+ : provider === "anthropic"
+ ? `${anthropicApiBaseUrl(credential.baseUrl)}/v1/models`
+ : `${credential.baseUrl ?? defaultBaseUrls[provider]}/models`;
try {
- const response = await fetch(OPENCODE_GO_USAGE_URL, {
+ const response = await fetch(url, {
+ redirect: "error",
headers: {
- Authorization: `Bearer ${credential.access}`,
+ ...(provider === "anthropic"
+ ? { "x-api-key": credential.access, "anthropic-version": "2023-06-01" }
+ : { Authorization: `Bearer ${credential.access}` }),
"User-Agent": OPENCODE_GO_USER_AGENT,
- "x-opencode-client": "akeru-bot",
+ ...(provider === "opencode-go" ? { "x-opencode-client": "akeru-bot" } : {}),
},
});
if (!response.ok) {
- throw new Error(`OpenCode Go rejected the API key (${response.status}).`);
+ this.recordRequestFailure(
+ provider,
+ `The provider rejected the API-key check (${response.status}).`,
+ undefined,
+ response.status === 401 || response.status === 403 ? "revoked" : "request",
+ );
+ } else {
+ this.recordRequestSuccess(provider);
}
- this.recordRequestSuccess(provider);
- } catch (cause) {
+ } catch {
this.recordRequestFailure(
provider,
- cause instanceof Error ? cause.message : "OpenCode Go rejected the API key.",
- undefined,
- oauthFailureKind(cause),
+ "The API-key check failed. Check the base URL and connection.",
);
}
return;
}
- if (credential.type !== "oauth") {
- this.recordOAuthFailure(provider, "The stored credential has the wrong type.");
- return;
- }
try {
const refreshed = await this.runRefresh(provider, credential);
+ this.reload();
+ const current = this.data[provider];
+ if (current?.type !== "oauth" || current.refresh !== credential.refresh) return;
this.setCredential(provider, refreshed);
// Refresh proves the OAuth grant is usable. It does not prove that the
// subscription can make a model request, so keep access detected until
@@ -492,80 +545,113 @@ export class SubscriptionAuthService {
return this.data[provider] !== undefined;
}
- async startLogin(provider: SubscriptionProviderId): Promise<StartedLogin> {
+ async startLogin(
+ provider: SubscriptionProviderId,
+ options: Omit<SubscriptionAuthStartInput, "provider"> = {},
+ ): Promise<StartedLogin> {
+ this.reload();
+ const authMode = options.authMode ?? (provider === "opencode-go" ? "api-key" : "oauth");
+ if (options.baseUrl !== undefined && authMode !== "api-key") {
+ throw new Error("Custom base URLs require API-key authentication. Select API key first.");
+ }
+ if (authMode === "api-key" && provider === "cursor") {
+ throw new Error("Cursor API-key authentication is not supported. Use OAuth.");
+ }
+ if (options.baseUrl !== undefined && provider === "xai") {
+ throw new Error(
+ "The Grok bridge does not support custom base URLs. Use the default endpoint.",
+ );
+ }
+ if (authMode === "oauth" && provider === "opencode-go") {
+ throw new Error("OpenCode Go requires an API key. Select API key first.");
+ }
+ const baseUrl =
+ options.baseUrl === undefined
+ ? undefined
+ : decodeBaseUrl(options.baseUrl).replace(/\/+$/, "");
const loginId = NodeCrypto.randomUUID();
let started: StartedLogin;
- switch (provider) {
- case "anthropic": {
- const { url, verifier } = await startAnthropicLogin();
- this.pendingLogins.set(loginId, { provider, verifier });
- started = { loginId, provider, url, completion: "paste" };
- break;
- }
- case "openai-codex": {
- const pending = await startCodexDeviceLogin();
- this.pendingLogins.set(loginId, { provider, pending });
- started = {
- loginId,
- provider,
- url: pending.url,
- userCode: pending.userCode,
- instructions: pending.instructions,
- completion: "poll",
- };
- break;
- }
- case "cursor": {
- const pending = await startCursorLogin();
- this.pendingLogins.set(loginId, { provider, pending });
- started = {
- loginId,
- provider,
- url: pending.url,
- instructions: "Approve the Cursor login in your browser.",
- completion: "poll",
- };
- break;
- }
- case "xai": {
- const pending = await startXAIDeviceLogin();
- this.pendingLogins.set(loginId, { provider, pending });
- started = {
- loginId,
- provider,
- url: pending.url,
- userCode: pending.userCode,
- instructions: pending.instructions,
- completion: "poll",
- };
- break;
- }
- case "kimi-for-coding": {
- const pending = await startKimiDeviceLogin();
- this.pendingLogins.set(loginId, { provider, pending });
- started = {
- loginId,
- provider,
- url: pending.url,
- userCode: pending.userCode,
- instructions: pending.instructions,
- completion: "poll",
- };
- break;
- }
- case "opencode-go": {
- this.pendingLogins.set(loginId, { provider });
- started = {
- loginId,
- provider,
- url: OPENCODE_GO_AUTH_URL,
- instructions: "Subscribe to OpenCode Go, copy the API key, then paste it here.",
- completion: "paste",
- };
- break;
+ if (authMode === "api-key") {
+ this.pendingLogins.set(loginId, { provider, authMode, ...(baseUrl ? { baseUrl } : {}) });
+ started = {
+ loginId,
+ provider,
+ url: provider === "opencode-go" ? OPENCODE_GO_AUTH_URL : "",
+ instructions: "Paste the provider API key.",
+ completion: "paste",
+ };
+ } else
+ switch (provider) {
+ case "anthropic": {
+ const { url, verifier } = await startAnthropicLogin();
+ this.pendingLogins.set(loginId, { provider, verifier });
+ started = { loginId, provider, url, completion: "paste" };
+ break;
+ }
+ case "openai-codex": {
+ const pending = await startCodexDeviceLogin();
+ this.pendingLogins.set(loginId, { provider, pending });
+ started = {
+ loginId,
+ provider,
+ url: pending.url,
+ userCode: pending.userCode,
+ instructions: pending.instructions,
+ completion: "poll",
+ };
+ break;
+ }
+ case "cursor": {
+ const pending = await startCursorLogin();
+ this.pendingLogins.set(loginId, { provider, pending });
+ started = {
+ loginId,
+ provider,
+ url: pending.url,
+ instructions: "Approve the Cursor login in your browser.",
+ completion: "poll",
+ };
+ break;
+ }
+ case "xai": {
+ const pending = await startXAIDeviceLogin();
+ this.pendingLogins.set(loginId, { provider, pending });
+ started = {
+ loginId,
+ provider,
+ url: pending.url,
+ userCode: pending.userCode,
+ instructions: pending.instructions,
+ completion: "poll",
+ };
+ break;
+ }
+ case "kimi-for-coding": {
+ const pending = await startKimiDeviceLogin();
+ this.pendingLogins.set(loginId, { provider, pending });
+ started = {
+ loginId,
+ provider,
+ url: pending.url,
+ userCode: pending.userCode,
+ instructions: pending.instructions,
+ completion: "poll",
+ };
+ break;
+ }
+ case "opencode-go": {
+ this.pendingLogins.set(loginId, { provider });
+ started = {
+ loginId,
+ provider,
+ url: OPENCODE_GO_AUTH_URL,
+ instructions: "Subscribe to OpenCode Go, copy the API key, then paste it here.",
+ completion: "paste",
+ };
+ break;
+ }
}
- }
// Drop the oldest abandoned login rather than growing without bound.
if (this.pendingLogins.size > PENDING_LOGIN_CAP) {
@@ -579,11 +665,14 @@ export class SubscriptionAuthService {
/** One upstream poll for a started login. Persists credentials on success. */
async pollLogin(loginId: string): Promise<LoginPollStatus> {
+ this.reload();
const login = this.pendingLogins.get(loginId);
if (!login) {
return { status: "failed", error: "Login expired or already completed. Start again." };
}
+ if ("authMode" in login) return { status: "pending", nextPollMs: 2000 };
+
switch (login.provider) {
case "anthropic":
return { status: "pending", nextPollMs: 2000 };
@@ -631,6 +720,9 @@ export class SubscriptionAuthService {
): LoginPollStatus {
switch (result.status) {
case "complete":
+ this.reload();
+ if (!this.pendingLogins.has(loginId))
+ return { status: "failed", error: "Login cancelled. Start again." };
this.pendingLogins.delete(loginId);
this.savePending();
this.setCredential(provider, result.credentials);
@@ -646,28 +738,41 @@ export class SubscriptionAuthService {
/** Finish a paste-completion login (Anthropic) with the pasted code. */
async completeLogin(loginId: string, code: string): Promise<LoginPollStatus> {
+ this.reload();
const login = this.pendingLogins.get(loginId);
if (!login) {
return { status: "failed", error: "Login expired or already completed. Start again." };
}
- if (login.provider !== "anthropic" && login.provider !== "opencode-go") {
- return { status: "failed", error: "This login completes by polling, not with a code." };
- }
-
- if (login.provider === "opencode-go") {
+ if ("authMode" in login || login.provider === "opencode-go") {
const apiKey = code.trim();
- if (apiKey.length === 0) {
- return { status: "failed", error: "Paste an OpenCode Go API key." };
+ if (apiKey.length === 0 || /[\r\n]/.test(apiKey)) {
+ return { status: "failed", error: "Paste a non-empty API key on one line." };
}
- this.pendingLogins.delete(loginId);
- this.savePending();
- this.data["opencode-go"] = { type: "api-key", access: apiKey };
+ const baseUrl = "baseUrl" in login ? login.baseUrl : undefined;
+ this.reload();
+ this.data[login.provider] = {
+ type: "api-key",
+ access: apiKey,
+ ...(baseUrl ? { baseUrl } : {}),
+ };
+ delete this.health[login.provider];
this.save();
+ this.saveHealth();
+ for (const [id, pending] of this.pendingLogins) {
+ if (pending.provider === login.provider) this.pendingLogins.delete(id);
+ }
+ this.savePending();
return { status: "connected" };
}
+ if (login.provider !== "anthropic") {
+ return { status: "failed", error: "This login completes by polling, not with a code." };
+ }
try {
const credentials = await completeAnthropicLogin(code, login.verifier);
+ this.reload();
+ if (!this.pendingLogins.has(loginId))
+ return { status: "failed", error: "Login cancelled. Start again." };
this.pendingLogins.delete(loginId);
this.savePending();
this.setCredential("anthropic", credentials);
@@ -682,11 +787,17 @@ export class SubscriptionAuthService {
}
cancelLogin(loginId: string): void {
+ this.reload();
this.pendingLogins.delete(loginId);
this.savePending();
}
logout(provider: SubscriptionProviderId): void {
+ this.reload();
+ for (const [loginId, pending] of this.pendingLogins) {
+ if (pending.provider === provider) this.pendingLogins.delete(loginId);
+ }
+ this.savePending();
delete this.data[provider];
this.reloadHealth();
delete this.health[provider];
@@ -695,6 +806,11 @@ export class SubscriptionAuthService {
}
private setCredential(provider: SubscriptionProviderId, credentials: OAuthCredentials): void {
+ if (this.data[provider]?.type === "api-key") {
+ this.reloadHealth();
+ delete this.health[provider];
+ this.saveHealth();
+ }
this.data[provider] = { type: "oauth", ...credentials };
this.save();
}
@@ -724,6 +840,18 @@ export class SubscriptionAuthService {
return refresh;
}
+ async getPlanAccessToken(provider: SubscriptionProviderId): Promise<string | undefined> {
+ const apiKey = this.getApiKeyCredential(provider);
+ if (apiKey && (provider !== "opencode-go" || apiKey.baseUrl)) return undefined;
+ return this.getAccessToken(provider);
+ }
+
+ getApiKeyCredential(provider: SubscriptionProviderId): ApiKeyCredential | undefined {
+ this.reload();
+ const credential = this.data[provider];
+ return credential?.type === "api-key" ? credential : undefined;
+ }
+
async getOpenAICodexAccess(): Promise<
{ readonly accessToken: string; readonly accountId: string } | undefined
> {
@@ -737,11 +865,15 @@ export class SubscriptionAuthService {
}
async getKimiForCodingAccess(): Promise<
- { readonly accessToken: string; readonly deviceId: string } | undefined
+ | { readonly accessToken: string; readonly deviceId?: string; readonly baseUrl?: string }
+ | undefined
> {
this.reload();
const accessToken = await this.getAccessToken("kimi-for-coding");
const credential = this.data["kimi-for-coding"];
+ if (credential?.type === "api-key" && accessToken) {
+ return { accessToken, ...(credential.baseUrl ? { baseUrl: credential.baseUrl } : {}) };
+ }
const deviceId = credential?.type === "oauth" ? credential.deviceId : undefined;
return accessToken && isKimiCodingDeviceId(deviceId) ? { accessToken, deviceId } : undefined;
}
@@ -752,6 +884,11 @@ export class SubscriptionAuthService {
): Promise<string | undefined> {
try {
const refreshed = await this.runRefresh(provider, credential);
+ this.reload();
+ const current = this.data[provider];
+ if (current?.type !== "oauth" || current.refresh !== credential.refresh) {
+ return current?.access;
+ }
this.setCredential(provider, refreshed);
return refreshed.access;
} catch (cause) {
diff --git a/apps/server/src/subscription-auth/sessionReset.test.ts b/apps/server/src/subscription-auth/sessionReset.test.ts
new file mode 100644
index 000000000..3fa5585bd
--- /dev/null
+++ b/apps/server/src/subscription-auth/sessionReset.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, it } from "@effect/vitest";
+import {
+ ProviderDriverKind,
+ ProviderInstanceId,
+ ThreadId,
+ type ProviderInstanceConfig,
+ type ProviderSession,
+} from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+
+import type { SubscriptionProviderId } from "./service.ts";
+import type { ApiKeyCredential } from "./types.ts";
+import { makeApiKeySessionReset } from "./sessionReset.ts";
+
+function session(driver: string, instanceId?: string): ProviderSession {
+ return {
+ provider: ProviderDriverKind.make(driver),
+ ...(instanceId ? { providerInstanceId: ProviderInstanceId.make(instanceId) } : {}),
+ threadId: ThreadId.make(`thread-${instanceId ?? driver}`),
+ status: "ready",
+ runtimeMode: "full-access",
+ createdAt: "2026-09-04T00:00:00Z",
+ updatedAt: "2026-09-04T00:00:00Z",
+ };
+}
+
+function fixture(
+ extraSessions: ReadonlyArray<ProviderSession> = [],
+ instances: Readonly<Record<string, ProviderInstanceConfig>> = {},
+) {
+ const credentials: Partial<Record<SubscriptionProviderId, ApiKeyCredential>> = {};
+ const stopped: string[] = [];
+ const sessions = [
+ ...["claudeAgent", "grok", "opencode", "codex"].map((driver) => session(driver)),
+ ...extraSessions,
+ ];
+ const reset = makeApiKeySessionReset(
+ { getApiKeyCredential: (provider) => credentials[provider] },
+ {
+ listSessions: () => Effect.succeed(sessions),
+ stopSession: ({ threadId }) =>
+ Effect.sync(() => {
+ stopped.push(threadId);
+ }),
+ },
+ Effect.succeed(instances),
+ );
+ return { credentials, stopped, reset };
+}
+
+describe("API-key session reset", () => {
+ it.effect("stops the matching bridge after replacing its key", () =>
+ Effect.gen(function* () {
+ const { credentials, stopped, reset } = fixture();
+ credentials.anthropic = { type: "api-key", access: "old-key" };
+ const result = yield* reset(
+ Effect.sync(() => {
+ credentials.anthropic = { type: "api-key", access: "new-key" };
+ return "connected";
+ }),
+ );
+ expect(result).toBe("connected");
+ expect(stopped).toEqual(["thread-claudeAgent"]);
+ }),
+ );
+
+ it.effect("stops a bridge when its key is disconnected or replaced by OAuth", () =>
+ Effect.gen(function* () {
+ const { credentials, stopped, reset } = fixture();
+ credentials.xai = { type: "api-key", access: "grok-key" };
+ yield* reset(
+ Effect.sync(() => {
+ delete credentials.xai;
+ }),
+ );
+ expect(stopped).toEqual(["thread-grok"]);
+ }),
+ );
+
+ it.effect("stops a bridge when only the endpoint changes", () =>
+ Effect.gen(function* () {
+ const { credentials, stopped, reset } = fixture();
+ credentials["opencode-go"] = {
+ type: "api-key",
+ access: "key",
+ baseUrl: "https://old.example/v1",
+ };
+ yield* reset(
+ Effect.sync(() => {
+ credentials["opencode-go"] = {
+ type: "api-key",
+ access: "key",
+ baseUrl: "https://new.example/v1",
+ };
+ }),
+ );
+ expect(stopped).toEqual(["thread-opencode"]);
+ }),
+ );
+
+ it.effect("keeps sessions for pending and unchanged credentials", () =>
+ Effect.gen(function* () {
+ const { credentials, stopped, reset } = fixture();
+ credentials.anthropic = { type: "api-key", access: "key" };
+ yield* reset(Effect.succeed({ status: "pending" }));
+ yield* reset(
+ Effect.sync(() => {
+ credentials.anthropic = { type: "api-key", access: "key" };
+ }),
+ );
+ expect(stopped).toEqual([]);
+ }),
+ );
+
+ it.effect("keeps sessions for instances that bring their own connection", () =>
+ Effect.gen(function* () {
+ const { credentials, stopped, reset } = fixture(
+ [
+ session("claudeAgent", "claude-work"),
+ session("claudeAgent", "claude-shared"),
+ session("grok", "grok-own-key"),
+ ],
+ {
+ "claude-work": {
+ driver: ProviderDriverKind.make("claudeAgent"),
+ config: { homePath: "~/.claude-work" },
+ },
+ "claude-shared": { driver: ProviderDriverKind.make("claudeAgent"), config: {} },
+ "grok-own-key": {
+ driver: ProviderDriverKind.make("grok"),
+ environment: [{ name: "XAI_API_KEY", value: "own", sensitive: true }],
+ },
+ },
+ );
+ credentials.anthropic = { type: "api-key", access: "old" };
+ credentials.xai = { type: "api-key", access: "old" };
+ yield* reset(
+ Effect.sync(() => {
+ credentials.anthropic = { type: "api-key", access: "new" };
+ credentials.xai = { type: "api-key", access: "new" };
+ }),
+ );
+ expect(stopped).toEqual(["thread-claudeAgent", "thread-grok", "thread-claude-shared"]);
+ }),
+ );
+
+ it.effect("does not stop sessions after a failed login", () =>
+ Effect.gen(function* () {
+ const { stopped, reset } = fixture();
+ const result = yield* reset(Effect.fail("login failed")).pipe(Effect.flip);
+ expect(result).toBe("login failed");
+ expect(stopped).toEqual([]);
+ }),
+ );
+});
diff --git a/apps/server/src/subscription-auth/sessionReset.ts b/apps/server/src/subscription-auth/sessionReset.ts
new file mode 100644
index 000000000..5b19a3df7
--- /dev/null
+++ b/apps/server/src/subscription-auth/sessionReset.ts
@@ -0,0 +1,71 @@
+import * as Effect from "effect/Effect";
+import {
+ defaultInstanceIdForDriver,
+ SubscriptionAuthError,
+ type ProviderInstanceConfig,
+ type ProviderInstanceId,
+ type ProviderSession,
+} from "@t3tools/contracts";
+
+import type { AgentControllerShape } from "../provider/Services/AgentController.ts";
+import { instanceUsesSavedCredential } from "./runtime.ts";
+import type { SubscriptionAuthService, SubscriptionProviderId } from "./service.ts";
+
+const BRIDGE_PROVIDERS = [
+ { provider: "anthropic", driver: "claudeAgent" },
+ { provider: "xai", driver: "grok" },
+ { provider: "opencode-go", driver: "opencode" },
+] as const satisfies ReadonlyArray<{ provider: SubscriptionProviderId; driver: string }>;
+
+type BridgeProvider = (typeof BRIDGE_PROVIDERS)[number];
+
+function sessionInstanceId(session: ProviderSession): ProviderInstanceId {
+ return session.providerInstanceId ?? defaultInstanceIdForDriver(session.provider);
+}
+
+/** Restart bridge processes after their saved API credentials change. */
+export function makeApiKeySessionReset(
+ auth: Pick<SubscriptionAuthService, "getApiKeyCredential">,
+ controller: Pick<AgentControllerShape, "listSessions" | "stopSession">,
+ loadInstances: Effect.Effect<Readonly<Record<string, ProviderInstanceConfig>>>,
+) {
+ const usesChangedCredential = (
+ session: ProviderSession,
+ changed: ReadonlyArray<BridgeProvider>,
+ instances: Readonly<Record<string, ProviderInstanceConfig>>,
+ ) =>
+ changed.some(
+ ({ provider, driver }) =>
+ driver === session.provider &&
+ instanceUsesSavedCredential(provider, instances[sessionInstanceId(session)]),
+ );
+
+ return Effect.fn("subscriptionAuth.resetChangedApiKeySessions")(function* <A, E, R>(
+ operation: Effect.Effect<A, E, R>,
+ ) {
+ const before = BRIDGE_PROVIDERS.map(({ provider }) => auth.getApiKeyCredential(provider));
+ const result = yield* operation;
+ const changed = BRIDGE_PROVIDERS.filter(({ provider }, index) => {
+ const previous = before[index];
+ const current = auth.getApiKeyCredential(provider);
+ return previous?.access !== current?.access || previous?.baseUrl !== current?.baseUrl;
+ });
+ if (changed.length === 0) return result;
+
+ const [sessions, instances] = yield* Effect.all([controller.listSessions(), loadInstances]);
+ yield* Effect.forEach(
+ sessions.filter((session) => usesChangedCredential(session, changed, instances)),
+ (session) => controller.stopSession({ threadId: session.threadId }),
+ { discard: true },
+ ).pipe(
+ Effect.mapError(
+ () =>
+ new SubscriptionAuthError({
+ reason:
+ "The credentials changed, but a provider session could not stop. Stop the affected chat before retrying.",
+ }),
+ ),
+ );
+ return result;
+ });
+}
diff --git a/apps/server/src/subscription-auth/snapshot.test.ts b/apps/server/src/subscription-auth/snapshot.test.ts
index 2ff990bc1..999a5f45d 100644
--- a/apps/server/src/subscription-auth/snapshot.test.ts
+++ b/apps/server/src/subscription-auth/snapshot.test.ts
@@ -52,6 +52,22 @@ function providerFixture(
}
describe("provider access capabilities", () => {
+ it("reports API-key authentication instead of asking for an OAuth check", () => {
+ const capabilities = buildProviderAccessCapabilities(
+ [
+ { ...baseSubscription, provider: "anthropic", authMode: "api-key" },
+ { ...baseSubscription, provider: "xai", authMode: "api-key" },
+ ],
+ [],
+ );
+ expect(capabilities.find((entry) => entry.id === "claude-max")).toMatchObject({
+ accessMethod: "api-key",
+ nextAction: "Check the API key, then send a provider request to verify access.",
+ });
+ expect(capabilities.find((entry) => entry.id === "xai-subscription")?.accessMethod).toBe(
+ "api-key",
+ );
+ });
it("maps Kimi bots to the Kimi subscription", () => {
expect(
subscriptionDependentBots(
diff --git a/apps/server/src/subscription-auth/snapshot.ts b/apps/server/src/subscription-auth/snapshot.ts
index c73d6aaa9..c59457f0a 100644
--- a/apps/server/src/subscription-auth/snapshot.ts
+++ b/apps/server/src/subscription-auth/snapshot.ts
@@ -105,14 +105,17 @@ export function buildProviderAccessCapabilities(
return {
id: entry.id,
label: entry.label,
- accessMethod: "subscription-oauth" as const,
+ accessMethod:
+ status?.authMode === "api-key" ? ("api-key" as const) : ("subscription-oauth" as const),
health: status?.health ?? ("missing" as const),
apiAccess: "separate" as const,
nextAction:
status?.health === "healthy" || status?.health === "recovered"
? "Send a provider request after the provider changes access."
: status?.connected
- ? "Check OAuth, then send a provider request to verify access."
+ ? status.authMode === "api-key"
+ ? "Check the API key, then send a provider request to verify access."
+ : "Check OAuth, then send a provider request to verify access."
: `Connect ${entry.label} in Settings.`,
...(status?.lastSuccessfulRequestAt
? { lastSuccessfulRequestAt: status.lastSuccessfulRequestAt }
@@ -207,7 +210,10 @@ export function buildProviderAccessCapabilities(
{
id: "xai-subscription",
label: "xAI subscription login",
- accessMethod: "subscription-oauth" as const,
+ accessMethod:
+ subscriptionById.get("xai")?.authMode === "api-key"
+ ? ("api-key" as const)
+ : ("subscription-oauth" as const),
health: subscriptionById.get("xai")?.health ?? ("missing" as const),
apiAccess: "separate" as const,
nextAction: "Send a Grok request to verify the shared xAI login.",
diff --git a/apps/server/src/subscription-auth/types.ts b/apps/server/src/subscription-auth/types.ts
index 02d911fbd..044289d02 100644
--- a/apps/server/src/subscription-auth/types.ts
+++ b/apps/server/src/subscription-auth/types.ts
@@ -22,6 +22,7 @@ export type OAuthCredential = {
export interface ApiKeyCredential {
readonly type: "api-key";
readonly access: string;
+ readonly baseUrl?: string;
}
export type SubscriptionCredential = OAuthCredential | ApiKeyCredential;
diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts
index aa3e59e2b..eedb0e0fe 100644
--- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts
+++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts
@@ -44,6 +44,7 @@ import {
resolveClaudeEffort,
} from "../provider/Layers/ClaudeProvider.ts";
import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts";
+import { subscriptionRuntimeEnvironment } from "../subscription-auth/runtime.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -61,6 +62,7 @@ const decodeClaudeOutputEnvelope = Schema.decodeEffect(Schema.fromJsonString(Cla
export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
claudeSettings: ClaudeSettings,
environment?: NodeJS.ProcessEnv,
+ secretsDir?: string,
) {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
@@ -157,6 +159,9 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
: undefined;
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
+ const requestEnvironment = secretsDir
+ ? subscriptionRuntimeEnvironment(secretsDir, "anthropic", claudeEnvironment)
+ : claudeEnvironment;
const spawnCommand = yield* resolveSpawnCommand(
claudeSettings.binaryPath || "claude",
[
@@ -171,10 +176,10 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
...(settingsJson ? ["--settings", settingsJson] : []),
"--dangerously-skip-permissions",
],
- { env: claudeEnvironment },
+ { env: requestEnvironment },
);
const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
- env: claudeEnvironment,
+ env: requestEnvironment,
cwd,
shell: spawnCommand.shell,
stdin: {
diff --git a/apps/server/src/textGeneration/GrokTextGeneration.ts b/apps/server/src/textGeneration/GrokTextGeneration.ts
index 1cf3d13e2..93eaa9667 100644
--- a/apps/server/src/textGeneration/GrokTextGeneration.ts
+++ b/apps/server/src/textGeneration/GrokTextGeneration.ts
@@ -1,3 +1,4 @@
+import { subscriptionRuntimeEnvironment } from "../subscription-auth/runtime.ts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
@@ -37,6 +38,7 @@ const isTextGenerationError = Schema.is(TextGenerationError);
export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(function* (
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
+ secretsDir?: string,
) {
const crypto = yield* Crypto.Crypto;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -63,7 +65,9 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
const outputRef = yield* Ref.make("");
const runtime = yield* makeGrokAcpRuntime({
grokSettings,
- environment,
+ environment: secretsDir
+ ? subscriptionRuntimeEnvironment(secretsDir, "xai", environment)
+ : environment,
childProcessSpawner: commandSpawner,
cwd,
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
diff --git a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts
index a4f953f27..30775e9c7 100644
--- a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts
+++ b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts
@@ -17,6 +17,7 @@ import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { extractJsonObject } from "@t3tools/shared/schemaJson";
import * as ServerConfig from "../config.ts";
+import { subscriptionRuntimeEnvironment } from "../subscription-auth/runtime.ts";
import { resolveAttachmentPath } from "../attachmentStore.ts";
import {
buildBranchNamePrompt,
@@ -301,7 +302,11 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
openCodeRuntime
.startOpenCodeServerProcess({
binaryPath: input.binaryPath,
- environment: resolvedEnvironment,
+ environment: subscriptionRuntimeEnvironment(
+ serverConfig.secretsDir,
+ "opencode-go",
+ resolvedEnvironment,
+ ),
})
.pipe(
Effect.provideService(Scope.Scope, serverScope),
diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts
index 1992c64f7..b4ff8e470 100644
--- a/apps/server/src/usage/UsageService.ts
+++ b/apps/server/src/usage/UsageService.ts
@@ -449,7 +449,7 @@ export const make = Effect.gen(function* () {
const finishedAtMs = yield* Clock.currentTimeMillis;
subscriptionAuth.reload();
const planLimits = yield* Effect.promise(() =>
- readPlanLimits((provider) => subscriptionAuth.getAccessToken(provider)),
+ readPlanLimits((provider) => subscriptionAuth.getPlanAccessToken(provider)),
).pipe(Effect.catchCause(() => Effect.succeed([])));
return {
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 3caab21b4..9f06c3141 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -79,6 +79,8 @@ import {
} from "@t3tools/contracts";
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
import { SubscriptionAuthService } from "./subscription-auth/service.ts";
+import { makeApiKeySessionReset } from "./subscription-auth/sessionReset.ts";
+import { deriveProviderInstanceConfigMap } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
import {
buildProviderAccessCapabilities,
subscriptionDependentBots,
@@ -540,6 +542,14 @@ const makeWsRpcLayer = (
const botInbox = BotInboxService.forSecretsDir(config.secretsDir);
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
const serverSettings = yield* ServerSettings.ServerSettingsService;
+ const resetChangedApiKeySessions = makeApiKeySessionReset(
+ subscriptionAuth,
+ agentController,
+ serverSettings.getSettings.pipe(
+ Effect.map(deriveProviderInstanceConfigMap),
+ Effect.orElseSucceed(() => ({})),
+ ),
+ );
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -2478,11 +2488,11 @@ const makeWsRpcLayer = (
}),
{ "rpc.aggregate": "bot" },
),
- [WS_METHODS.subscriptionAuthStart]: ({ provider }) =>
+ [WS_METHODS.subscriptionAuthStart]: ({ provider, ...options }) =>
observeRpcEffect(
WS_METHODS.subscriptionAuthStart,
Effect.tryPromise({
- try: () => subscriptionAuth.startLogin(provider),
+ try: () => subscriptionAuth.startLogin(provider, options),
catch: (cause) =>
new SubscriptionAuthError({
reason: cause instanceof Error ? cause.message : String(cause),
@@ -2499,7 +2509,7 @@ const makeWsRpcLayer = (
new SubscriptionAuthError({
reason: cause instanceof Error ? cause.message : String(cause),
}),
- }),
+ }).pipe(resetChangedApiKeySessions),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.subscriptionAuthComplete]: ({ loginId, code }) =>
@@ -2511,7 +2521,7 @@ const makeWsRpcLayer = (
new SubscriptionAuthError({
reason: cause instanceof Error ? cause.message : String(cause),
}),
- }),
+ }).pipe(resetChangedApiKeySessions),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.subscriptionAuthCancel]: ({ loginId }) =>
@@ -2528,7 +2538,7 @@ const makeWsRpcLayer = (
WS_METHODS.subscriptionAuthLogout,
Effect.sync(() => {
subscriptionAuth.logout(provider);
- }).pipe(Effect.andThen(getAccessHealthSnapshot())),
+ }).pipe(resetChangedApiKeySessions, Effect.andThen(getAccessHealthSnapshot())),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.subscriptionAuthHealthTest]: ({ provider }) =>
diff --git a/apps/web/src/components/onboarding/DesktopOnboarding.test.tsx b/apps/web/src/components/onboarding/DesktopOnboarding.test.tsx
new file mode 100644
index 000000000..73cdbfbe0
--- /dev/null
+++ b/apps/web/src/components/onboarding/DesktopOnboarding.test.tsx
@@ -0,0 +1,309 @@
+import { EnvironmentId, type SubscriptionProviderId } from "@t3tools/contracts";
+import { act, type ComponentProps } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import type { ProviderApiKeyForm } from "../settings/ProvidersPanel";
+import { DEFAULT_DESKTOP_ONBOARDING_DRAFT } from "./desktopOnboarding.logic";
+
+const mocks = vi.hoisted(() => ({
+ start: vi.fn(),
+ complete: vi.fn(),
+ cancel: vi.fn(),
+ poll: vi.fn(),
+ refresh: vi.fn(),
+ next: vi.fn(),
+ open: vi.fn(),
+ form: null as ComponentProps<typeof ProviderApiKeyForm> | null,
+ input: null as { onChange: (event: { currentTarget: { value: string } }) => void } | null,
+ buttons: new Map<string, { onClick?: () => void; disabled?: boolean }>(),
+ connected: false,
+}));
+
+vi.mock("../../state/server", () => ({
+ serverEnvironment: {
+ subscriptionAuth: () => ({}),
+ startSubscriptionAuth: "start",
+ completeSubscriptionAuth: "complete",
+ cancelSubscriptionAuth: "cancel",
+ pollSubscriptionAuth: "poll",
+ },
+}));
+vi.mock("../../state/query", () => ({
+ useEnvironmentQuery: () => ({
+ data: { providers: [{ provider: "openai-codex", connected: mocks.connected }] },
+ refresh: mocks.refresh,
+ }),
+}));
+vi.mock("../../state/use-atom-command", () => ({
+ useAtomCommand: (command: "start" | "complete" | "cancel" | "poll") => mocks[command],
+}));
+vi.mock("../settings/ProvidersPanel", () => ({
+ ProviderApiKeyForm: (props: ComponentProps<typeof ProviderApiKeyForm>) => {
+ mocks.form = props;
+ return null;
+ },
+}));
+vi.mock("../ui/button", () => ({
+ Button: (props: { children?: unknown; onClick?: () => void; disabled?: boolean }) => {
+ const label = (Array.isArray(props.children) ? props.children : [props.children])
+ .filter((child) => typeof child === "string")
+ .join("");
+ mocks.buttons.set(label, props);
+ return null;
+ },
+}));
+vi.mock("../ui/input", () => ({
+ Input: (props: NonNullable<typeof mocks.input>) => {
+ mocks.input = props;
+ return null;
+ },
+}));
+
+import { SubscriptionStep } from "./DesktopOnboarding";
+
+// Match the minimal ReactDOM host used by PreviewView's unit tests.
+class TestNode {
+ parentNode: TestNode | null = null;
+ childNodes: TestNode[] = [];
+ readonly nodeName: string;
+ readonly tagName: string;
+ readonly namespaceURI = "http://www.w3.org/1999/xhtml";
+ readonly style = {};
+ constructor(
+ name: string,
+ readonly ownerDocument: TestNode | null = null,
+ readonly nodeType = 1,
+ ) {
+ this.nodeName = name.toUpperCase();
+ this.tagName = this.nodeName;
+ }
+ set textContent(_value: string) {
+ this.childNodes = [];
+ }
+ appendChild(child: TestNode) {
+ child.parentNode = this;
+ this.childNodes.push(child);
+ return child;
+ }
+ removeChild(child: TestNode) {
+ this.childNodes.splice(this.childNodes.indexOf(child), 1);
+ child.parentNode = null;
+ return child;
+ }
+ insertBefore(child: TestNode, before: TestNode) {
+ child.parentNode = this;
+ this.childNodes.splice(this.childNodes.indexOf(before), 0, child);
+ return child;
+ }
+ createElement(name: string) {
+ return new TestNode(name, this);
+ }
+ createElementNS(_namespace: string, name: string) {
+ return this.createElement(name);
+ }
+ createTextNode() {
+ return new TestNode("#text", this, 3);
+ }
+ addEventListener() {}
+ removeEventListener() {}
+ setAttribute() {}
+ removeAttribute() {}
+}
+
+let root: Root;
+const environmentId = EnvironmentId.make("onboarding-environment");
+const success = <T,>(value: T) => ({ _tag: "Success" as const, value });
+
+async function render(providerId: SubscriptionProviderId = "openai-codex") {
+ await act(async () =>
+ root.render(
+ <SubscriptionStep
+ environmentId={environmentId}
+ draft={{ ...DEFAULT_DESKTOP_ONBOARDING_DRAFT, providerId }}
+ onChange={vi.fn()}
+ onContinue={mocks.next}
+ />,
+ ),
+ );
+}
+
+async function click(label: string) {
+ const button = mocks.buttons.get(label);
+ expect(button).toBeDefined();
+ expect(button?.disabled).not.toBe(true);
+ await act(async () => button?.onClick?.());
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.buttons.clear();
+ mocks.form = null;
+ mocks.input = null;
+ mocks.connected = false;
+ mocks.start.mockResolvedValue(success({ loginId: "key-login" }));
+ mocks.complete.mockResolvedValue(success({ status: "connected" }));
+ mocks.cancel.mockResolvedValue(success({}));
+ const document = new TestNode("#document", null, 9);
+ vi.stubGlobal("document", document);
+ vi.stubGlobal("window", {
+ document,
+ HTMLIFrameElement: TestNode,
+ location: { search: "" },
+ open: mocks.open,
+ });
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ root = createRoot(document.createElement("div") as unknown as Element);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ vi.unstubAllGlobals();
+});
+
+describe("onboarding API-key connections", () => {
+ it.each(["openai-codex", "anthropic", "kimi-for-coding"] as const)(
+ "saves a %s key and custom endpoint, then continues",
+ async (provider) => {
+ await render(provider);
+ await click("Use an API key");
+ expect(mocks.form?.supportsBaseUrl).toBe(true);
+ await act(async () => {
+ mocks.form?.onKeyChange(" test-key ");
+ mocks.form?.onBaseUrlChange("https://proxy.example/v1");
+ });
+ await act(async () => mocks.form?.onSave());
+ expect(mocks.start).toHaveBeenCalledWith({
+ environmentId,
+ input: {
+ provider,
+ authMode: "api-key",
+ baseUrl: "https://proxy.example/v1",
+ },
+ });
+ expect(mocks.complete).toHaveBeenCalledWith({
+ environmentId,
+ input: {
+ loginId: "key-login",
+ code: "test-key",
+ },
+ });
+ expect(mocks.refresh).toHaveBeenCalled();
+ expect(mocks.next).toHaveBeenCalledOnce();
+ expect(mocks.open).not.toHaveBeenCalled();
+ },
+ );
+
+ it("keeps the form busy and does not continue until the key is saved", async () => {
+ let finish!: (value: ReturnType<typeof success<{ status: "connected" }>>) => void;
+ const completion = new Promise<ReturnType<typeof success<{ status: "connected" }>>>(
+ (resolve) => {
+ finish = resolve;
+ },
+ );
+ mocks.complete.mockReturnValue(completion);
+ await render();
+ await click("Use an API key");
+ await act(async () => mocks.form?.onKeyChange("test-key"));
+ await act(async () => mocks.form?.onSave());
+ expect(mocks.form?.busy).toBe(true);
+ expect(mocks.next).not.toHaveBeenCalled();
+ await act(async () => mocks.form?.onSave());
+ expect(mocks.start).toHaveBeenCalledOnce();
+ await act(async () => finish(success({ status: "connected" })));
+ expect(mocks.next).toHaveBeenCalledOnce();
+ });
+
+ it("keeps failed saves on the key form and cancels the pending login", async () => {
+ mocks.complete.mockResolvedValue(success({ status: "failed", error: "Key rejected" }));
+ await render("anthropic");
+ await click("Use an API key");
+ await act(async () => mocks.form?.onKeyChange("test-key"));
+ await act(async () => mocks.form?.onSave());
+ expect(mocks.form?.error).toBe("Key rejected");
+ expect(mocks.form?.busy).toBe(false);
+ expect(mocks.cancel).toHaveBeenCalledWith({ environmentId, input: { loginId: "key-login" } });
+ expect(mocks.next).not.toHaveBeenCalled();
+ });
+
+ it("rejects invalid endpoints before starting a login", async () => {
+ await render();
+ await click("Use an API key");
+ await act(async () => {
+ mocks.form?.onKeyChange("test-key");
+ mocks.form?.onBaseUrlChange("https://user:[email protected]/v1");
+ });
+ await act(async () => mocks.form?.onSave());
+ expect(mocks.form?.error).toContain("without credentials");
+ expect(mocks.start).not.toHaveBeenCalled();
+ expect(mocks.next).not.toHaveBeenCalled();
+ });
+
+ it("clears the key and endpoint when cancelled", async () => {
+ await render();
+ await click("Use an API key");
+ await act(async () => {
+ mocks.form?.onKeyChange("test-key");
+ mocks.form?.onBaseUrlChange("https://proxy.example/v1");
+ });
+ await act(async () => mocks.form?.onCancel());
+ await click("Use an API key");
+ expect(mocks.form?.apiKey).toBe("");
+ expect(mocks.form?.baseUrl).toBe("");
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+
+ it("keeps Grok on its default endpoint", async () => {
+ await render("xai");
+ await click("Use an API key");
+ expect(mocks.form?.supportsBaseUrl).toBe(false);
+ await act(async () => mocks.form?.onKeyChange("test-key"));
+ await act(async () => mocks.form?.onSave());
+ expect(mocks.start).toHaveBeenCalledWith({
+ environmentId,
+ input: { provider: "xai", authMode: "api-key" },
+ });
+ });
+
+ it("opens the key form directly for OpenCode Go", async () => {
+ await render("opencode-go");
+ await click("Connect OpenCode Go");
+ expect(mocks.form?.supportsBaseUrl).toBe(true);
+ expect(mocks.start).not.toHaveBeenCalled();
+ expect(mocks.open).not.toHaveBeenCalled();
+ });
+
+ it("preserves OAuth and enables Claude paste completion after starting", async () => {
+ mocks.start.mockResolvedValue(
+ success({
+ loginId: "oauth-login",
+ provider: "anthropic",
+ completion: "paste",
+ url: "https://claude.example/login",
+ }),
+ );
+ await render("anthropic");
+ await click("Connect Claude");
+ expect(mocks.start).toHaveBeenCalledWith({ environmentId, input: { provider: "anthropic" } });
+ expect(mocks.open).toHaveBeenCalledWith(
+ "https://claude.example/login",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ expect(mocks.form).toBeNull();
+ await act(async () => mocks.input?.onChange({ currentTarget: { value: "oauth-code" } }));
+ await click("Connect");
+ expect(mocks.complete).toHaveBeenCalledWith({
+ environmentId,
+ input: { loginId: "oauth-login", code: "oauth-code" },
+ });
+ expect(mocks.next).not.toHaveBeenCalled();
+ });
+
+ it("lets an already connected API-only user continue without OAuth", async () => {
+ mocks.connected = true;
+ await render();
+ await click("Continue");
+ expect(mocks.next).toHaveBeenCalledOnce();
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/components/onboarding/DesktopOnboarding.tsx b/apps/web/src/components/onboarding/DesktopOnboarding.tsx
index 7f21f02a5..884305f75 100644
--- a/apps/web/src/components/onboarding/DesktopOnboarding.tsx
+++ b/apps/web/src/components/onboarding/DesktopOnboarding.tsx
@@ -47,6 +47,12 @@ import { DEFAULT_BOT_RUNTIME_MODE } from "../roster/botSandbox";
import { BLOB_COLORS, BLOB_SHAPES } from "../roster/roster.logic";
import { useRosterStore } from "../roster/rosterStore";
import { useBotThreadRuntime } from "../roster/useBotThreadRuntime";
+import {
+ apiKeyStartInput,
+ apiKeyValidationError,
+ providerSupportsBaseUrl,
+} from "@t3tools/client-runtime/provider-auth";
+import { ProviderApiKeyForm } from "../settings/ProvidersPanel";
import { SUBSCRIPTION_PROVIDERS } from "../settings/subscriptionProviders";
import {
DEFAULT_DESKTOP_ONBOARDING_DRAFT,
@@ -94,7 +100,7 @@ interface ActiveLogin {
readonly error: string | null;
}
-function SubscriptionStep({
+export function SubscriptionStep({
environmentId,
draft,
onChange,
@@ -124,6 +130,9 @@ function SubscriptionStep({
const [activeLogin, setActiveLogin] = useState<ActiveLogin | null>(null);
const [busy, setBusy] = useState(false);
const [code, setCode] = useState("");
+ const [keyMode, setKeyMode] = useState(false);
+ const [baseUrl, setBaseUrl] = useState("");
+ const [error, setError] = useState<string | null>(null);
const statusByProvider = useMemo(
() => new Map(statusQuery.data?.providers.map((status) => [status.provider, status]) ?? []),
@@ -178,18 +187,73 @@ function SubscriptionStep({
};
}, [activeLogin, environmentId, pollAuth, settle]);
+ const openKey = () => {
+ setCode("");
+ setError(null);
+ setBaseUrl(statusByProvider.get(draft.providerId)?.baseUrl ?? "");
+ setKeyMode(true);
+ };
+
+ const saveKey = async () => {
+ if (busy) return;
+ const validation = apiKeyValidationError(code, baseUrl);
+ setError(validation);
+ if (validation) return;
+ setBusy(true);
+ const started = await startAuth({
+ environmentId,
+ input: apiKeyStartInput(draft.providerId, baseUrl),
+ });
+ if (started._tag !== "Success") {
+ setBusy(false);
+ if (started._tag === "Failure") setError(commandError(started));
+ return;
+ }
+ const result = await completeAuth({
+ environmentId,
+ input: { loginId: started.value.loginId, code: code.trim() },
+ });
+ if (result._tag === "Success" && result.value.status === "connected") {
+ setCode("");
+ setBaseUrl("");
+ setKeyMode(false);
+ setBusy(false);
+ statusQuery.refresh();
+ onContinue();
+ return;
+ }
+ if (result._tag === "Failure") setError(commandError(result));
+ else if (result._tag === "Success") {
+ setError(
+ result.value.status === "failed" ? result.value.error : "The key was not saved. Try again.",
+ );
+ }
+ await cancelAuth({ environmentId, input: { loginId: started.value.loginId } });
+ setBusy(false);
+ };
+
const connect = async () => {
+ if (draft.providerId === "opencode-go" && !captureMode) {
+ openKey();
+ return;
+ }
if (captureMode) {
onContinue();
return;
}
+ setError(null);
+ setCode("");
setBusy(true);
const result = await startAuth({
environmentId,
input: { provider: draft.providerId },
});
- if (isAtomCommandInterrupted(result)) return;
+ if (isAtomCommandInterrupted(result)) {
+ setBusy(false);
+ return;
+ }
if (result._tag === "Failure") {
+ setError(commandError(result));
setBusy(false);
return;
}
@@ -226,6 +290,32 @@ function SubscriptionStep({
}
};
+ if (keyMode) {
+ return (
+ <div className="space-y-4">
+ <h1 className="text-balance text-[2rem] font-medium leading-[1.08] tracking-[-0.035em]">
+ Connect {selected.label} with an API key
+ </h1>
+ <ProviderApiKeyForm
+ supportsBaseUrl={providerSupportsBaseUrl(draft.providerId)}
+ apiKey={code}
+ baseUrl={baseUrl}
+ busy={busy}
+ error={error}
+ onKeyChange={setCode}
+ onBaseUrlChange={setBaseUrl}
+ onSave={() => void saveKey()}
+ onCancel={() => {
+ setKeyMode(false);
+ setCode("");
+ setBaseUrl("");
+ setError(null);
+ }}
+ />
+ </div>
+ );
+ }
+
if (activeLogin) {
return (
<div className="space-y-4">
@@ -296,13 +386,10 @@ function SubscriptionStep({
<div className="space-y-6">
<div>
<h1 className="text-balance text-[2rem] font-medium leading-[1.08] tracking-[-0.035em]">
- Connect your subscription
+ Connect your provider
</h1>
- <p className="mt-3 text-sm leading-6 text-muted-foreground">
- Use an account you already pay for. Akeru keeps the login on this Mac.
- </p>
</div>
- <div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Subscription">
+ <div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Provider">
{SUBSCRIPTION_PROVIDERS.map((definition) => {
const active = definition.id === draft.providerId;
const ProviderIcon = typeof definition.icon === "string" ? null : definition.icon;
@@ -315,6 +402,7 @@ function SubscriptionStep({
type="button"
role="radio"
aria-checked={active}
+ disabled={busy}
onClick={() => onChange({ ...draft, providerId: definition.id })}
className={`relative flex min-h-24 flex-col items-start rounded-2xl border p-3 text-left transition duration-150 motion-reduce:transition-none ${
active
@@ -348,6 +436,16 @@ function SubscriptionStep({
);
})}
</div>
+ {error ? (
+ <p role="alert" className="text-sm text-destructive">
+ {error}
+ </p>
+ ) : null}
+ {!connected && selected.id !== "opencode-go" ? (
+ <Button className="w-full" variant="outline" disabled={busy} onClick={openKey}>
+ Use an API key
+ </Button>
+ ) : null}
<Button
className="h-10 w-full rounded-xl"
disabled={busy}
diff --git a/apps/web/src/components/settings/ProvidersPanel.test.tsx b/apps/web/src/components/settings/ProvidersPanel.test.tsx
index 1af98e059..5e06feeb1 100644
--- a/apps/web/src/components/settings/ProvidersPanel.test.tsx
+++ b/apps/web/src/components/settings/ProvidersPanel.test.tsx
@@ -2,7 +2,7 @@ import { renderToStaticMarkup } from "react-dom/server";
import type { SubscriptionProviderStatus } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
-import { ProviderLoginCard, SUBSCRIPTION_PROVIDERS } from "./ProvidersPanel";
+import { ProviderApiKeyForm, ProviderLoginCard, SUBSCRIPTION_PROVIDERS } from "./ProvidersPanel";
describe("subscription providers", () => {
it("offers Kimi subscription login without Cursor", () => {
@@ -12,6 +12,113 @@ describe("subscription providers", () => {
expect(providers).not.toContain("cursor");
});
+ it("masks API keys and offers an optional endpoint with save and cancel", () => {
+ const markup = renderToStaticMarkup(
+ <ProviderApiKeyForm
+ apiKey=""
+ baseUrl=""
+ busy={false}
+ error="The key was not saved."
+ onKeyChange={() => undefined}
+ onBaseUrlChange={() => undefined}
+ onSave={() => undefined}
+ onCancel={() => undefined}
+ />,
+ );
+ expect(markup).toContain('type="password"');
+ expect(markup).toContain('autoComplete="off"');
+ expect(markup).toContain("Base URL (optional)");
+ expect(markup).toContain("Save");
+ expect(markup).toContain("Cancel");
+ expect(markup).toContain('role="alert"');
+ expect(markup).toContain("The key was not saved.");
+ expect(markup).toMatch(/type="submit"[^>]*disabled/);
+ });
+
+ it("identifies saved keys and provides both key reconnect and OAuth switching", () => {
+ const markup = renderToStaticMarkup(
+ <ProviderLoginCard
+ definition={SUBSCRIPTION_PROVIDERS[1]!}
+ status={{
+ provider: "anthropic",
+ authMode: "api-key",
+ baseUrl: "https://proxy.example/v1",
+ connected: true,
+ health: "detected",
+ dependentBots: [],
+ dependentRoutines: [],
+ }}
+ busy={false}
+ onConnect={() => undefined}
+ onApiKey={() => undefined}
+ onDisconnect={() => undefined}
+ onTest={() => undefined}
+ />,
+ );
+ expect(markup).toContain("Check key");
+ expect(markup).not.toContain("Check OAuth");
+ expect(markup).toContain("API key saved");
+ expect(markup).toContain("https://proxy.example/v1");
+ expect(markup).toContain("Reconnect key");
+ expect(markup).toContain("Use OAuth");
+ expect(markup).toContain("Disconnect Claude");
+ expect(markup).not.toContain(SUBSCRIPTION_PROVIDERS[1]!.description);
+ });
+
+ it("disables other providers without showing false progress", () => {
+ const markup = renderToStaticMarkup(
+ <ProviderLoginCard
+ definition={SUBSCRIPTION_PROVIDERS[0]!}
+ status={undefined}
+ busy={false}
+ disabled
+ onConnect={() => undefined}
+ onApiKey={() => undefined}
+ onDisconnect={() => undefined}
+ onTest={() => undefined}
+ />,
+ );
+ expect(markup).toContain("disabled");
+ expect(markup).not.toContain("animate-spin");
+ });
+
+ it("does not offer a custom endpoint for Grok", () => {
+ const markup = renderToStaticMarkup(
+ <ProviderApiKeyForm
+ supportsBaseUrl={false}
+ apiKey=""
+ baseUrl=""
+ busy={false}
+ error={null}
+ onKeyChange={() => undefined}
+ onBaseUrlChange={() => undefined}
+ onSave={() => undefined}
+ onCancel={() => undefined}
+ />,
+ );
+ expect(markup).not.toContain("Base URL");
+ expect(markup).toContain("Grok uses its default endpoint.");
+ expect(markup).toContain('type="password"');
+ });
+
+ it("disables both form actions while saving", () => {
+ const markup = renderToStaticMarkup(
+ <ProviderApiKeyForm
+ apiKey="test-key"
+ baseUrl="https://proxy.example"
+ busy
+ error={null}
+ onKeyChange={() => undefined}
+ onBaseUrlChange={() => undefined}
+ onSave={() => undefined}
+ onCancel={() => undefined}
+ />,
+ );
+ expect(markup).toContain("Saving…");
+ expect(markup).toMatch(/type="submit"[^>]*disabled/);
+ expect(markup).toMatch(/type="button"[^>]*disabled/);
+ });
+
it("keeps connected providers compact", () => {
const status: SubscriptionProviderStatus = {
provider: "openai-codex",
diff --git a/apps/web/src/components/settings/ProvidersPanel.tsx b/apps/web/src/components/settings/ProvidersPanel.tsx
index 28f402998..46791badb 100644
--- a/apps/web/src/components/settings/ProvidersPanel.tsx
+++ b/apps/web/src/components/settings/ProvidersPanel.tsx
@@ -1,6 +1,7 @@
import { CopyIcon, ExternalLinkIcon, LoaderIcon, LogOutIcon, RefreshCwIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import type {
+ EnvironmentId,
SubscriptionAuthLoginProgress,
SubscriptionAuthStartResult,
SubscriptionProviderId,
@@ -12,6 +13,13 @@ import {
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
+import {
+ apiKeyStartInput,
+ apiKeyValidationError,
+ providerUsesApiKey,
+ providerSupportsBaseUrl,
+} from "@t3tools/client-runtime/provider-auth";
+
import { useSettingsEnvironmentId } from "../../settingsDialogStore";
import { serverEnvironment } from "../../state/server";
import { useEnvironmentQuery } from "../../state/query";
@@ -70,16 +78,20 @@ export function ProviderLoginCard({
definition,
status,
busy,
+ disabled = false,
onConnect,
onDisconnect,
onTest,
+ onApiKey,
}: {
readonly definition: SubscriptionProviderDefinition;
readonly status: SubscriptionProviderStatus | undefined;
readonly busy: boolean;
+ readonly disabled?: boolean;
readonly onConnect: () => void;
readonly onDisconnect: () => void;
readonly onTest: () => void;
+ readonly onApiKey?: () => void;
}) {
const connected = status?.connected === true;
const ProviderIcon = typeof definition.icon === "string" ? null : definition.icon;
@@ -103,43 +115,138 @@ export function ProviderLoginCard({
</Badge>
</span>
}
- description={definition.description}
- status={definition.subscription}
+ description={providerUsesApiKey(status) ? undefined : definition.description}
+ status={
+ status?.authMode === "api-key"
+ ? `API key saved${status.baseUrl ? ` · ${status.baseUrl}` : ""}`
+ : definition.subscription
+ }
control={
- connected ? (
- <div className="flex items-center gap-1.5">
- <Button size="xs" variant="outline" disabled={busy} onClick={onTest}>
- {busy ? (
- <LoaderIcon className="size-3.5 animate-spin" />
- ) : (
- <RefreshCwIcon className="size-3.5" />
- )}
- {definition.id === "opencode-go" ? "Check key" : "Check OAuth"}
+ <div className="flex flex-wrap items-center gap-1.5">
+ {definition.id !== "opencode-go" && onApiKey ? (
+ <Button size="xs" variant="ghost-muted" disabled={busy || disabled} onClick={onApiKey}>
+ {providerUsesApiKey(status) ? "Reconnect key" : "API key"}
</Button>
- <Button size="xs" variant="ghost-muted" disabled={busy} onClick={onConnect}>
- Reconnect
- </Button>
- <Button
- size="icon-xs"
- variant="ghost-muted"
- aria-label={`Disconnect ${definition.label}`}
- disabled={busy}
- onClick={onDisconnect}
- >
- <LogOutIcon className="size-3.5" />
+ ) : null}
+ {connected ? (
+ <div className="flex items-center gap-1.5">
+ <Button size="xs" variant="outline" disabled={busy || disabled} onClick={onTest}>
+ {busy ? (
+ <LoaderIcon className="size-3.5 animate-spin" />
+ ) : (
+ <RefreshCwIcon className="size-3.5" />
+ )}
+ {providerUsesApiKey(status) ? "Check key" : "Check OAuth"}
+ </Button>
+ <Button
+ size="xs"
+ variant="ghost-muted"
+ disabled={busy || disabled}
+ onClick={onConnect}
+ >
+ {providerUsesApiKey(status) && definition.id !== "opencode-go"
+ ? "Use OAuth"
+ : "Reconnect"}
+ </Button>
+ <Button
+ size="icon-xs"
+ variant="ghost-muted"
+ aria-label={`Disconnect ${definition.label}`}
+ disabled={busy || disabled}
+ onClick={onDisconnect}
+ >
+ <LogOutIcon className="size-3.5" />
+ </Button>
+ </div>
+ ) : (
+ <Button size="xs" variant="outline" disabled={busy || disabled} onClick={onConnect}>
+ {busy ? <LoaderIcon className="size-3.5 animate-spin" /> : null}
+ Connect
</Button>
- </div>
- ) : (
- <Button size="xs" variant="outline" disabled={busy} onClick={onConnect}>
- {busy ? <LoaderIcon className="size-3.5 animate-spin" /> : null}
- Connect
- </Button>
- )
+ )}
+ </div>
}
/>
);
}
+export function ProviderApiKeyForm({
+ supportsBaseUrl = true,
+ apiKey,
+ baseUrl,
+ busy,
+ error,
+ onKeyChange,
+ onBaseUrlChange,
+ onSave,
+ onCancel,
+}: {
+ readonly supportsBaseUrl?: boolean;
+ readonly apiKey: string;
+ readonly baseUrl: string;
+ readonly busy: boolean;
+ readonly error: string | null;
+ readonly onKeyChange: (value: string) => void;
+ readonly onBaseUrlChange: (value: string) => void;
+ readonly onSave: () => void;
+ readonly onCancel: () => void;
+}) {
+ return (
+ <form
+ className="space-y-3 px-3 pb-3 sm:px-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ onSave();
+ }}
+ >
+ <label className="block space-y-1 text-sm">
+ <span>API key</span>
+ <Input
+ type="password"
+ autoComplete="off"
+ spellCheck={false}
+ value={apiKey}
+ disabled={busy}
+ onChange={(event) => onKeyChange(event.currentTarget.value)}
+ />
+ </label>
+ {supportsBaseUrl ? (
+ <label className="block space-y-1 text-sm">
+ <span>Base URL (optional)</span>
+ <Input
+ type="url"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder="Provider default"
+ value={baseUrl}
+ disabled={busy}
+ onChange={(event) => onBaseUrlChange(event.currentTarget.value)}
+ />
+ </label>
+ ) : null}
+ <p className="text-[13px] text-muted-foreground">
+ {supportsBaseUrl
+ ? "The environment sends this key to the selected endpoint."
+ : "Grok uses its default endpoint."}{" "}
+ API billing can be separate from your subscription.
+ </p>
+ {error ? (
+ <p role="alert" className="text-sm text-destructive">
+ {error}
+ </p>
+ ) : null}
+ <div className="flex gap-2">
+ <Button type="submit" size="xs" disabled={busy || !apiKey.trim()}>
+ {busy ? "Saving…" : "Save"}
+ </Button>
+ <Button type="button" size="xs" variant="ghost-muted" disabled={busy} onClick={onCancel}>
+ Cancel
+ </Button>
+ </div>
+ </form>
+ );
+}
+
function ActiveLoginPanel({
login,
pastedCode,
@@ -190,6 +297,8 @@ function ActiveLoginPanel({
{flow.completion === "paste" ? (
<div className="flex gap-2">
<Input
+ type={isApiKey ? "password" : "text"}
+ autoComplete="off"
value={pastedCode}
onChange={(event) => onPastedCodeChange(event.currentTarget.value)}
placeholder={isApiKey ? "Paste the API key" : "Paste the authorization code"}
@@ -205,16 +314,20 @@ function ActiveLoginPanel({
Connect
</Button>
</div>
- ) : (
+ ) : !login.error ? (
<div className="flex items-center gap-2 text-[13px] text-muted-foreground">
<LoaderIcon className="size-3.5 animate-spin" />
Waiting for approval…
</div>
- )}
+ ) : null}
- {login.error ? <p className="text-[13px] text-destructive">{login.error}</p> : null}
+ {login.error ? (
+ <p role="alert" className="text-[13px] text-destructive">
+ {login.error}
+ </p>
+ ) : null}
- <Button size="xs" variant="ghost-muted" onClick={onCancel}>
+ <Button size="xs" variant="ghost-muted" disabled={completing} onClick={onCancel}>
Cancel
</Button>
</div>
@@ -223,6 +336,10 @@ function ActiveLoginPanel({
export function ProvidersPanel() {
const environmentId = useSettingsEnvironmentId();
+ return <ProviderConnections key={environmentId ?? "none"} environmentId={environmentId} />;
+}
+
+function ProviderConnections({ environmentId }: { readonly environmentId: EnvironmentId | null }) {
const statusQuery = useEnvironmentQuery(
environmentId === null
? null
@@ -251,6 +368,9 @@ export function ProvidersPanel() {
const [busyProvider, setBusyProvider] = useState<SubscriptionProviderId | null>(null);
const [pastedCode, setPastedCode] = useState("");
const [completing, setCompleting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [keyProvider, setKeyProvider] = useState<SubscriptionProviderDefinition | null>(null);
+ const [baseUrl, setBaseUrl] = useState("");
const statusByProvider = useMemo(
() => new Map(statusQuery.data?.providers.map((status) => [status.provider, status]) ?? []),
@@ -305,8 +425,62 @@ export function ProvidersPanel() {
};
}, [activeLogin, environmentId, pollAuth, settleLogin]);
+ const openApiKey = (definition: SubscriptionProviderDefinition) => {
+ setError(null);
+ setPastedCode("");
+ setBaseUrl(
+ providerSupportsBaseUrl(definition.id)
+ ? (statusByProvider.get(definition.id)?.baseUrl ?? "")
+ : "",
+ );
+ setKeyProvider(definition);
+ };
+
+ const saveApiKey = async () => {
+ if (environmentId === null || !keyProvider || completing) return;
+ const validationError = apiKeyValidationError(pastedCode, baseUrl);
+ setError(validationError);
+ if (validationError) return;
+ setCompleting(true);
+ const started = await startAuth({
+ environmentId,
+ input: apiKeyStartInput(keyProvider.id, baseUrl),
+ });
+ if (started._tag !== "Success") {
+ setCompleting(false);
+ if (started._tag === "Failure") setError(commandError(started));
+ return;
+ }
+ const result = await completeAuth({
+ environmentId,
+ input: { loginId: started.value.loginId, code: pastedCode.trim() },
+ });
+ setCompleting(false);
+ if (result._tag === "Success" && result.value.status === "connected") {
+ setKeyProvider(null);
+ setPastedCode("");
+ setBaseUrl("");
+ statusQuery.refresh();
+ } else {
+ if (result._tag === "Failure") setError(commandError(result));
+ else if (result._tag === "Success")
+ setError(
+ result.value.status === "failed"
+ ? result.value.error
+ : "The key was not saved. Try again.",
+ );
+ await cancelAuth({ environmentId, input: { loginId: started.value.loginId } });
+ }
+ };
+
const connect = async (definition: SubscriptionProviderDefinition) => {
if (environmentId === null) return;
+ if (definition.id === "opencode-go") {
+ openApiKey(definition);
+ return;
+ }
+ setError(null);
+ setPastedCode("");
setBusyProvider(definition.id);
const result = await startAuth({
environmentId,
@@ -314,6 +488,7 @@ export function ProvidersPanel() {
});
if (isAtomCommandInterrupted(result)) return;
if (result._tag === "Failure") {
+ setError(commandError(result));
setBusyProvider(null);
return;
}
@@ -345,25 +520,63 @@ export function ProvidersPanel() {
setBusyProvider(null);
setPastedCode("");
if (environmentId === null || !login) return;
- await cancelAuth({ environmentId, input: { loginId: login.flow.loginId } });
+ const result = await cancelAuth({ environmentId, input: { loginId: login.flow.loginId } });
+ if (result._tag === "Failure") setError(commandError(result));
};
const disconnect = async (provider: SubscriptionProviderId) => {
if (environmentId === null) return;
+ setError(null);
setBusyProvider(provider);
const result = await logoutAuth({ environmentId, input: { provider } });
setBusyProvider(null);
if (result._tag === "Success") statusQuery.refresh();
+ else if (result._tag === "Failure") setError(commandError(result));
};
const testHealth = async (provider: SubscriptionProviderId) => {
if (environmentId === null) return;
+ setError(null);
setBusyProvider(provider);
const result = await testAuth({ environmentId, input: { provider } });
setBusyProvider(null);
- if (result._tag === "Success") statusQuery.refresh();
+ if (result._tag === "Success") {
+ statusQuery.refresh();
+ const status = result.value.providers.find((entry) => entry.provider === provider);
+ if (status?.oauthCheck?.status === "failed" || status?.healthTest?.status === "failed") {
+ setError(
+ status.lastFailedRequest?.message ??
+ "The provider check failed. Reconnect and try again.",
+ );
+ }
+ } else if (result._tag === "Failure") setError(commandError(result));
};
+ if (keyProvider) {
+ return (
+ <SettingsPageContainer>
+ <SettingsSection title={`Connect ${keyProvider.label} with an API key`}>
+ <ProviderApiKeyForm
+ supportsBaseUrl={providerSupportsBaseUrl(keyProvider.id)}
+ apiKey={pastedCode}
+ baseUrl={baseUrl}
+ busy={completing}
+ error={error}
+ onKeyChange={setPastedCode}
+ onBaseUrlChange={setBaseUrl}
+ onSave={() => void saveApiKey()}
+ onCancel={() => {
+ setKeyProvider(null);
+ setPastedCode("");
+ setBaseUrl("");
+ setError(null);
+ }}
+ />
+ </SettingsSection>
+ </SettingsPageContainer>
+ );
+ }
+
if (activeLogin) {
return (
<SettingsPageContainer>
@@ -383,15 +596,17 @@ export function ProvidersPanel() {
return (
<SettingsPageContainer>
- <SettingsSection title="Subscriptions">
+ <SettingsSection title="Providers">
<div className="px-3 pb-2 text-[13px] leading-[1.45] text-muted-foreground sm:px-4">
- Connect accounts you already pay for. Akeru uses the coding access included with each
- subscription. Tokens stay on this Akeru server.
+ Connect a subscription or API key. Credentials stay on this environment.
</div>
- {statusQuery.error ? (
- <div className="mx-3 rounded-xl border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive sm:mx-4">
- {statusQuery.error}
+ {error || statusQuery.error ? (
+ <div
+ role="alert"
+ className="mx-3 rounded-xl border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive sm:mx-4"
+ >
+ {error ?? statusQuery.error}
</div>
) : null}
@@ -400,7 +615,9 @@ export function ProvidersPanel() {
key={definition.id}
definition={definition}
status={statusByProvider.get(definition.id)}
- busy={busyProvider === definition.id || statusQuery.isPending}
+ busy={busyProvider === definition.id}
+ disabled={busyProvider !== null || statusQuery.isPending}
+ onApiKey={() => openApiKey(definition)}
onConnect={() => void connect(definition)}
onDisconnect={() => void disconnect(definition.id)}
onTest={() => void testHealth(definition.id)}
diff --git a/docs/internals/subscription-auth.md b/docs/internals/subscription-auth.md
index f1ba8cbb2..3890d1bcf 100644
--- a/docs/internals/subscription-auth.md
+++ b/docs/internals/subscription-auth.md
@@ -1,6 +1,6 @@
# Subscription authentication
-Akeru lets a user connect an existing AI subscription. It does not ask for an API key and it does not run a provider CLI to authenticate.
+Akeru lets a user connect an existing AI subscription or supply an API key. The environment server owns both authentication methods. A custom base URL selects an API-compatible endpoint for API-key connections; it does not change subscription OAuth endpoints.
Supported account flows:
@@ -19,7 +19,7 @@ The environment server owns credentials. It writes them to:
<stateDir>/secrets/subscription-auth.json
```
-The directory uses mode `0700`. The file uses mode `0600`. Writes use a temporary file and atomic rename. OAuth access tokens and refresh tokens never cross the WebSocket contract. Clients only receive provider status, an authorization URL, a user code when required, and login progress.
+The directory uses mode `0700`. The file uses mode `0600`. Writes use a temporary file and atomic rename. Clients submit API keys through `subscriptionAuth.complete`; the server never returns saved keys. OAuth access tokens and refresh tokens never cross the WebSocket contract. Status includes the authentication method and custom base URL, but no credentials.
Local desktop, a remote server, and a future hosted control plane use the same boundary. The storage adapter can move from the local file to an encrypted tenant secret store without changing the client contract.
@@ -34,15 +34,15 @@ When a run starts:
3. It passes only that access token to the agent runtime or sandbox for that run.
4. The sandbox loses the token when the run or sandbox ends.
-This keeps a disposable sandbox disposable. A stolen sandbox cannot renew access after its short-lived token expires.
+This limits the lifetime of OAuth access in a sandbox. API keys do not have the same short-lived guarantee. Keep keys in the environment secret store and pass them only to the provider runtime that needs them.
## Remote-ready login
The client drives every login over RPC:
-- `subscriptionAuth.start` creates a pending login and returns the provider URL.
+- `subscriptionAuth.start` creates a pending login. An `authMode` of `api-key` selects key entry and accepts an optional `baseUrl`. OAuth remains the default for subscription providers.
- `subscriptionAuth.poll` performs one upstream poll for a device or browser-poll flow.
-- `subscriptionAuth.complete` exchanges a pasted code for Anthropic.
+- `subscriptionAuth.complete` exchanges a pasted code for Anthropic OAuth or stores a key for an API-key login.
- `subscriptionAuth.cancel` removes abandoned pending state.
- `subscriptionAuth.logout` removes the stored credential.
@@ -52,4 +52,8 @@ Pending login state stays on the environment server. It is bounded and contains
## Runtime integration
-`SubscriptionAuthService.getAccessToken(provider)` is the runtime seam. It returns a valid short-lived access token and serializes concurrent refresh requests. The current provider CLI adapters do not consume this seam yet. The Mastra runtime must call it when subscription-backed model execution replaces the legacy CLI harness.
+`SubscriptionAuthService.getAccessToken(provider)` returns a valid OAuth access token or the saved API key. It serializes concurrent OAuth refresh requests. `getApiKeyCredential(provider)` reloads the server-owned credential and returns its optional base URL for runtime use only.
+
+Codex uses the OpenAI Responses API when an API key is saved and keeps the Codex subscription transport for OAuth. Kimi and OpenCode Go resolve keys and custom endpoints for model requests. Claude, Grok, and OpenCode receive saved API credentials when their adapter starts a provider process. The login, completion, and logout RPC paths stop affected bridge sessions when the API key or endpoint changes. The next turn starts a new process with the current connection. Grok supports API keys at its default endpoint; its current bridge rejects custom base URLs.
+
+Custom endpoints must use the selected provider's protocol. They do not make every model compatible with every driver. Health checks use the selected endpoint and disable HTTP redirects so a redirect cannot forward a key to another host.
diff --git a/docs/user/install.md b/docs/user/install.md
index e14236db7..86a1c733f 100644
--- a/docs/user/install.md
+++ b/docs/user/install.md
@@ -90,7 +90,7 @@ close the terminal.
## Connect a subscription
-Open **Settings > Providers** on any connected client. The **Subscriptions** section supports:
+Open **Settings > Providers**. Mobile lists these options under **Provider connections**:
| Account | Supported access |
| --------------- | --------------------------------------- |
@@ -107,10 +107,32 @@ The environment server owns the connection, so you connect once per environment.
credentials outside the workspace. Web, desktop, and mobile clients only receive connection
status and sign-in progress.
-After sign-in, select **Check OAuth** to test an OAuth login or **Check key** to test OpenCode Go.
+After sign-in, select **Check OAuth** to test an OAuth login or **Check key** to test an API key.
Use **Reconnect** after a revoked or expired login. Akeru cannot verify whether an xAI login includes
SuperGrok or X Premium+.
+### Connect an API key
+
+Web and desktop use **Settings > Providers**. Mobile uses **Settings > Providers > Provider connections**.
+Select an environment first if you have more than one environment.
+
+ChatGPT, Claude, Grok, Kimi For Coding, and OpenCode Go accept API keys. Select **API key** beside a
+provider. For OpenCode Go, select **Connect**.
+
+Enter the key in the password field. Optionally enter a **Base URL** for a compatible endpoint.
+Grok uses its default endpoint and does not show a Base URL field.
+Leave the URL empty to use the provider default. The URL must use HTTP or HTTPS and must not contain
+credentials, a query, or a fragment. The environment sends the key to this endpoint, so use an endpoint
+you trust. API billing can be separate from your subscription.
+
+Select **Save** to store the key on the environment. **Cancel** discards the form. A saved key has not
+necessarily passed a provider request; select **Check key** to check access.
+
+Use **Reconnect key** to replace the key or change the endpoint. OpenCode Go uses **Reconnect**.
+The form shows the saved endpoint but never shows the saved key. Enter the key again when you change
+the endpoint. Use **Use OAuth** to return to subscription login where supported. **Disconnect** removes
+the saved connection from the environment.
+
## What Akeru runs
Codex and Kimi use Akeru's custom Mastra-based runtime. Akeru supplies the workspace, memory,
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 20a20dc31..a950ba4ee 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -39,6 +39,10 @@
"types": "./src/platform/index.ts",
"default": "./src/platform/index.ts"
},
+ "./provider-auth": {
+ "types": "./src/providerAuth.ts",
+ "default": "./src/providerAuth.ts"
+ },
"./providerSkills": {
"types": "./src/providerSkills.ts",
"default": "./src/providerSkills.ts"
diff --git a/packages/client-runtime/src/providerAuth.test.ts b/packages/client-runtime/src/providerAuth.test.ts
new file mode 100644
index 000000000..7d1b99dcb
--- /dev/null
+++ b/packages/client-runtime/src/providerAuth.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { SubscriptionProviderStatus } from "@t3tools/contracts";
+import {
+ apiKeyStartInput,
+ apiKeyValidationError,
+ PROVIDER_CONNECTIONS,
+ providerConnectionLabel,
+ providerUsesApiKey,
+ providerSupportsBaseUrl,
+} from "./providerAuth.ts";
+
+const status: SubscriptionProviderStatus = {
+ provider: "anthropic",
+ connected: true,
+ dependentBots: [],
+ dependentRoutines: [],
+};
+
+describe("provider API key forms", () => {
+ it("only offers providers supported by API-key login", () => {
+ expect(PROVIDER_CONNECTIONS.map((provider) => provider.id)).toEqual([
+ "openai-codex",
+ "anthropic",
+ "xai",
+ "kimi-for-coding",
+ "opencode-go",
+ ]);
+ });
+
+ it("starts key authentication without sending the key in the start request", () => {
+ expect(apiKeyStartInput("anthropic", " https://proxy.example/v1 ")).toEqual({
+ provider: "anthropic",
+ authMode: "api-key",
+ baseUrl: "https://proxy.example/v1",
+ });
+ expect(apiKeyStartInput("anthropic", " ")).toEqual({
+ provider: "anthropic",
+ authMode: "api-key",
+ });
+ });
+
+ it("does not send an unsupported Grok endpoint", () => {
+ expect(providerSupportsBaseUrl("xai")).toBe(false);
+ expect(providerSupportsBaseUrl("cursor")).toBe(false);
+ expect(providerSupportsBaseUrl("anthropic")).toBe(true);
+ expect(apiKeyStartInput("xai", "https://proxy.example/v1")).toEqual({
+ provider: "xai",
+ authMode: "api-key",
+ });
+ });
+
+ it("requires a nonempty key", () => {
+ expect(apiKeyValidationError(" ", "")).toBe("Enter an API key.");
+ expect(apiKeyValidationError("key", "")).toBeNull();
+ });
+
+ it.each([
+ "not a URL",
+ "ftp://example.com",
+ "https://user:[email protected]",
+ "https://example.com?key=secret",
+ "https://example.com#fragment",
+ ])("rejects invalid endpoints: %s", (url) => {
+ expect(apiKeyValidationError("key", url)).toContain("HTTP or HTTPS");
+ });
+
+ it.each(["https://api.example.com/v1", "http://localhost:8080/v1"])(
+ "accepts supported endpoints: %s",
+ (url) => {
+ expect(apiKeyValidationError("key", url)).toBeNull();
+ },
+ );
+
+ it("does not claim a saved key passed a health check", () => {
+ expect(providerConnectionLabel({ ...status, authMode: "api-key", health: "detected" })).toBe(
+ "API key saved · detected",
+ );
+ expect(providerConnectionLabel({ ...status, connected: false })).toBe("Not connected");
+ expect(providerConnectionLabel(status)).toBe("OAuth connected");
+ });
+
+ it("keeps OAuth and legacy OpenCode key status distinct", () => {
+ expect(providerUsesApiKey(status)).toBe(false);
+ expect(providerUsesApiKey({ ...status, authMode: "api-key" })).toBe(true);
+ expect(providerUsesApiKey({ ...status, provider: "opencode-go" })).toBe(true);
+ });
+});
diff --git a/packages/client-runtime/src/providerAuth.ts b/packages/client-runtime/src/providerAuth.ts
new file mode 100644
index 000000000..d37010ad6
--- /dev/null
+++ b/packages/client-runtime/src/providerAuth.ts
@@ -0,0 +1,51 @@
+import {
+ SubscriptionBaseUrl,
+ type SubscriptionAuthStartInput,
+ type SubscriptionProviderId,
+ type SubscriptionProviderStatus,
+} from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+
+export const PROVIDER_CONNECTIONS = [
+ { id: "openai-codex", label: "ChatGPT" },
+ { id: "anthropic", label: "Claude" },
+ { id: "xai", label: "Grok" },
+ { id: "kimi-for-coding", label: "Kimi For Coding" },
+ { id: "opencode-go", label: "OpenCode Go" },
+] as const satisfies ReadonlyArray<{ id: SubscriptionProviderId; label: string }>;
+
+export function providerSupportsBaseUrl(provider: SubscriptionProviderId): boolean {
+ return provider !== "xai" && provider !== "cursor";
+}
+
+export function providerUsesApiKey(status: SubscriptionProviderStatus | undefined): boolean {
+ return status?.authMode === "api-key" || status?.provider === "opencode-go";
+}
+
+const isSubscriptionBaseUrl = Schema.is(SubscriptionBaseUrl);
+
+export function apiKeyValidationError(key: string, baseUrl: string): string | null {
+ if (!key.trim()) return "Enter an API key.";
+ if (baseUrl.trim() && !isSubscriptionBaseUrl(baseUrl.trim())) {
+ return "Use an HTTP or HTTPS base URL without credentials, a query, or a fragment.";
+ }
+ return null;
+}
+
+export function apiKeyStartInput(
+ provider: SubscriptionProviderId,
+ baseUrl: string,
+): SubscriptionAuthStartInput {
+ return {
+ provider,
+ authMode: "api-key",
+ ...(providerSupportsBaseUrl(provider) && baseUrl.trim() ? { baseUrl: baseUrl.trim() } : {}),
+ };
+}
+
+export function providerConnectionLabel(status: SubscriptionProviderStatus): string {
+ if (!status.connected) return "Not connected";
+ const mode = providerUsesApiKey(status) ? "API key saved" : "OAuth connected";
+ const health = status.health?.replaceAll("-", " ");
+ return health ? `${mode} · ${health}` : mode;
+}
diff --git a/packages/contracts/src/subscriptionAuth.test.ts b/packages/contracts/src/subscriptionAuth.test.ts
index 7c1c8f6b6..9f0bc2fd0 100644
--- a/packages/contracts/src/subscriptionAuth.test.ts
+++ b/packages/contracts/src/subscriptionAuth.test.ts
@@ -4,14 +4,60 @@ import * as Schema from "effect/Schema";
import {
SubscriptionAuthLoginProgress,
SubscriptionAuthStartResult,
+ SubscriptionAuthStartInput,
SubscriptionAuthStatuses,
} from "./subscriptionAuth.ts";
+const decodeStartInput = Schema.decodeUnknownSync(SubscriptionAuthStartInput);
const decodeStatuses = Schema.decodeUnknownSync(SubscriptionAuthStatuses);
const decodeStartResult = Schema.decodeUnknownSync(SubscriptionAuthStartResult);
const decodeLoginProgress = Schema.decodeUnknownSync(SubscriptionAuthLoginProgress);
describe("subscription auth contracts", () => {
+ it("accepts API-key setup and preserves the legacy OAuth input", () => {
+ const decode = Schema.decodeUnknownSync(SubscriptionAuthStartInput);
+ expect(decode({ provider: "anthropic" })).toEqual({ provider: "anthropic" });
+ expect(
+ decode({ provider: "anthropic", authMode: "api-key", baseUrl: "https://proxy.example/v1" }),
+ ).toEqual({ provider: "anthropic", authMode: "api-key", baseUrl: "https://proxy.example/v1" });
+ });
+
+ it.each([
+ "file:///tmp/key",
+ "https://user:[email protected]/v1",
+ "https://example.com?key=secret",
+ "https://example.com/#secret",
+ "not-a-url",
+ ])("rejects an unsafe base URL: %s", (baseUrl) => {
+ expect(() =>
+ decodeStartInput({
+ provider: "anthropic",
+ authMode: "api-key",
+ baseUrl,
+ }),
+ ).toThrow();
+ });
+
+ it("exposes API-key metadata but strips secrets from status", () => {
+ const decoded = decodeStatuses({
+ providers: [
+ {
+ provider: "anthropic",
+ connected: true,
+ authMode: "api-key",
+ baseUrl: "http://localhost:8080/v1",
+ access: "secret",
+ apiKey: "secret",
+ refresh: "secret",
+ },
+ ],
+ });
+ expect(decoded.providers[0]).toMatchObject({
+ authMode: "api-key",
+ baseUrl: "http://localhost:8080/v1",
+ });
+ expect(JSON.stringify(decoded)).not.toContain("secret");
+ });
it("decodes provider statuses without any credential fields", () => {
const decoded = decodeStatuses({
providers: [{ provider: "openai-codex", connected: true, expiresAt: 123 }],
diff --git a/packages/contracts/src/subscriptionAuth.ts b/packages/contracts/src/subscriptionAuth.ts
index 1bf9d3ade..e63c86a61 100644
--- a/packages/contracts/src/subscriptionAuth.ts
+++ b/packages/contracts/src/subscriptionAuth.ts
@@ -21,9 +21,34 @@ export const SubscriptionProviderId = Schema.Literals([
]);
export type SubscriptionProviderId = typeof SubscriptionProviderId.Type;
+export const SubscriptionAuthMode = Schema.Literals(["oauth", "api-key"]);
+export type SubscriptionAuthMode = typeof SubscriptionAuthMode.Type;
+
+export const SubscriptionBaseUrl = TrimmedNonEmptyString.check(
+ Schema.makeFilter(
+ (value) => {
+ try {
+ const url = new URL(value);
+ return (
+ (url.protocol === "https:" || url.protocol === "http:") &&
+ !url.username &&
+ !url.password &&
+ !url.search &&
+ !url.hash
+ );
+ } catch {
+ return false;
+ }
+ },
+ { message: "Use an HTTP or HTTPS base URL without credentials, a query, or a fragment." },
+ ),
+);
+
export const SubscriptionProviderStatus = Schema.Struct({
provider: SubscriptionProviderId,
connected: Schema.Boolean,
+ authMode: Schema.optional(SubscriptionAuthMode),
+ baseUrl: Schema.optional(SubscriptionBaseUrl),
/** ms epoch when the current access token expires. Absent when disconnected. */
expiresAt: Schema.optional(Schema.Number),
health: Schema.optional(
@@ -151,6 +176,9 @@ export type SubscriptionAuthHealthTestInput = typeof SubscriptionAuthHealthTestI
export const SubscriptionAuthStartInput = Schema.Struct({
provider: SubscriptionProviderId,
+ authMode: Schema.optional(SubscriptionAuthMode),
+ /** Custom endpoints apply to API-key authentication only. */
+ baseUrl: Schema.optional(SubscriptionBaseUrl),
});
export type SubscriptionAuthStartInput = typeof SubscriptionAuthStartInput.Type;