diff --git a/docs/docs/configure/providers.md b/docs/docs/configure/providers.md index 3f5ab71b3b..6fc7c32ab2 100644 --- a/docs/docs/configure/providers.md +++ b/docs/docs/configure/providers.md @@ -43,7 +43,7 @@ Managed LLM access with dynamic routing across Sonnet 4.6, Opus 4.6, GPT-5.4, GP For pricing, security, and data handling details, see the [Altimate LLM Gateway guide](https://help.altimate.ai/datamates/user-guide/components/llm-gateway/). -To sign out, run `altimate providers logout altimate-backend` (or `/logout` in the TUI). This deletes `~/.altimate/altimate.json` (`%USERPROFILE%\.altimate\altimate.json` on Windows), removes the auth-store entry, and removes remote MCP servers whose `Authorization` header carries the saved key, such as those added with `datamate add`. It checks the same config files a session started in the current directory loads: the global config, `~/.altimate-code`, and project config from the current directory up to the git root (every parent directory outside git). New sessions stop using the key; restart any session that is already running, or run `/logout` inside it. MCP servers configured in other projects are not removed. If the saved key can't be read, logout fails and keeps the file so you can fix it and run logout again. +To sign out, run `altimate providers logout altimate-backend`, or `/logout` in the TUI while a gateway model is selected. This deletes `~/.altimate/altimate.json` (`%USERPROFILE%\.altimate\altimate.json` on Windows), removes the auth-store entry, and removes remote MCP servers whose `Authorization` header carries the saved key, such as those added with `datamate add`. It checks the same config files a session started in the current directory loads: the global config, `~/.altimate-code`, and project config from the current directory up to the git root (every parent directory outside git). New sessions stop using the key; restart any session that is already running, or run `/logout` inside it. MCP servers configured in other projects are not removed. If the saved key can't be read, logout fails and keeps the file so you can fix it and run logout again. !!! tip "Automatic model selection" When Altimate credentials are configured and no model is explicitly chosen, the Altimate LLM Gateway is selected automatically. You can override this by setting `model` in your config or by restricting the `provider` section to specific providers only. @@ -552,6 +552,25 @@ Set your default model and a smaller model for lightweight tasks: The `small_model` is used for lightweight tasks like summarization and context compaction. +## Signing out of a provider + +In the TUI, `/logout` signs out of the provider behind the model you're using. The command names it and how you signed in, for example "Log out of OpenAI (ChatGPT subscription)" or "Log out of OpenAI (API key)". To sign out of a different provider, switch to one of its models first. + +After you confirm, the saved login is removed and the provider list reloads. If the provider is gone, the session switches to another connected model; if no provider is left, the connect picker opens. + +For the Claude Agent provider, `/logout` shows "Log out of Claude Agent (Claude Code connection)". It disconnects Claude Agent from Altimate Code; your Claude Code sign-in stays as it is. + +Some providers have no saved login to remove: + +- **Set by an environment variable**, such as `OPENAI_API_KEY`: `/logout` names the variable. Unset it and restart to disconnect. +- **Set in your config**: remove the provider from the config file. +- **Free models on the keyless public Zen tier**: they need no login, so `/logout` says there is nothing to log out of. +- **Connected outside Altimate Code**, by another tool: sign out in that tool. + +If a provider has both a saved login and an environment variable or a config entry, `/logout` removes the saved login. The provider stays connected that way, and `/logout` tells you how to remove it. + +From a terminal, `altimate providers logout [provider]` removes any saved login. Without a provider it lists the ones you can choose. + ## Provider Options Reference | Field | Type | Description | diff --git a/packages/opencode/src/plugin/tui/altimate/provider-credentials.tsx b/packages/opencode/src/plugin/tui/altimate/provider-credentials.tsx index dc4d2cf3e7..22281d80c1 100644 --- a/packages/opencode/src/plugin/tui/altimate/provider-credentials.tsx +++ b/packages/opencode/src/plugin/tui/altimate/provider-credentials.tsx @@ -16,6 +16,7 @@ import type { BuiltinTuiPlugin } from "@opencode-ai/tui/builtins" import { createSignal, Show } from "solid-js" import { AltimateApi } from "@/altimate/api/client" import { Telemetry } from "@/altimate/telemetry" +import { FreeTier } from "@/altimate/free/client" // altimate_change — /logout for Altimate Base const id = "altimate:provider-credentials" @@ -101,6 +102,21 @@ async function logout(api: TuiPluginApi) { } // altimate_change end +// altimate_change start — /logout when the current model is Altimate Base. Same steps as +// `altimate auth logout altimate-free`: clear the managed credential, then drop any legacy +// auth-store entry left by builds before the managed store. +async function logoutBase(api: TuiPluginApi) { + try { + await FreeTier.logout() + await api.client.auth.remove({ providerID: FreeTier.PROVIDER_ID }, { throwOnError: true }) + await api.client.instance.dispose() + api.ui.toast({ variant: "success", message: "Logged out of Altimate Base" }) + } catch (err) { + api.ui.toast({ variant: "error", message: err instanceof Error ? err.message : "Logout failed" }) + } +} +// altimate_change end + const tui: TuiPlugin = async (api) => { api.keymap.registerLayer({ commands: [ @@ -123,11 +139,22 @@ const tui: TuiPlugin = async (api) => { void logout(api) }, }, + { + name: "altimate.provider.logout.base", + title: "Log out of Altimate Base", + category: "Altimate", + namespace: "palette", + hidden: true, + run() { + void logoutBase(api) + }, + }, // altimate_change end ], bindings: api.tuiConfig.keybinds.gather("altimate.palette", [ "altimate.provider.connect", "altimate.provider.logout", + "altimate.provider.logout.base", ]), }) } diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index f9c3a72ebf..0f9e9c4626 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -1279,6 +1279,11 @@ export namespace Provider { id: ProviderID.zod, name: z.string(), source: z.enum(["env", "config", "custom", "api"]), + // altimate_change start — the login saved for this provider, if any. `source` can't tell it: a + // config entry or an env key overrides it, and a subscription loads as "custom". The TUI's + // /logout reads this to name and remove the right login. + auth: z.enum(["api", "oauth", "wellknown"]).optional(), + // altimate_change end env: z.string().array(), key: z.string().optional(), options: z.record(z.string(), z.any()), @@ -2028,6 +2033,16 @@ export namespace Provider { mergeProvider(providerID, partial) } + // altimate_change start — record the saved login type; see `auth` on Info. Its own read keeps the + // upstream API-key loop above unchanged. OPENCODE_AUTH_CONTENT is parsed without validation, so + // only a known type is reported. + const savedLogins = await Auth.all() + for (const [id, provider] of Object.entries(providers)) { + const type = savedLogins[id]?.type + if (type === "api" || type === "oauth" || type === "wellknown") provider.auth = type + } + // altimate_change end + for (const [id, provider] of Object.entries(providers)) { const providerID = ProviderID.make(id) if (!isProviderAllowed(providerID)) { diff --git a/packages/opencode/test/provider/provider.test.ts b/packages/opencode/test/provider/provider.test.ts index 50d6df5f36..2e7617eee1 100644 --- a/packages/opencode/test/provider/provider.test.ts +++ b/packages/opencode/test/provider/provider.test.ts @@ -3088,3 +3088,68 @@ test("fromModelsDevProvider survives a catalog with a malformed entry mixed in", expect(database["bad-id"]).toBeUndefined() }) // altimate_change end + +// altimate_change start — `auth` tells clients which login is saved; the TUI's /logout reads it +test("provider reports a saved API key as auth: api even when config also lists it", async () => { + const saved = await Auth.get("openai") + await Auth.set("openai", { type: "api", key: "sk-test-saved" }) + try { + await using tmp = await tmpdir({ config: { provider: { openai: {} } } }) + await provideProviderTestInstance({ + directory: tmp.path, + init: async () => Env.remove("OPENAI_API_KEY"), + fn: async () => { + const providers = await Provider.list() + expect(providers[ProviderID.openai].source).toBe("config") + expect(providers[ProviderID.openai].auth).toBe("api") + }, + }) + } finally { + if (saved) await Auth.set("openai", saved) + else await Auth.remove("openai") + } +}) + +test("provider reports a saved sign-in as auth: oauth", async () => { + const saved = await Auth.get("openai") + await Auth.set("openai", { + type: "oauth", + refresh: "refresh-test", + access: "access-test", + expires: Date.now() + 3_600_000, + }) + try { + await using tmp = await tmpdir({ config: {} }) + await provideProviderTestInstance({ + directory: tmp.path, + init: async () => Env.remove("OPENAI_API_KEY"), + fn: async () => { + const providers = await Provider.list() + expect(providers[ProviderID.openai].auth).toBe("oauth") + }, + }) + } finally { + if (saved) await Auth.set("openai", saved) + else await Auth.remove("openai") + } +}) + +test("provider set only by an environment variable has no saved login", async () => { + const saved = await Auth.get("anthropic") + if (saved) await Auth.remove("anthropic") + try { + await using tmp = await tmpdir({ config: {} }) + await provideProviderTestInstance({ + directory: tmp.path, + init: async () => Env.set("ANTHROPIC_API_KEY", "test-api-key"), + fn: async () => { + const providers = await Provider.list() + expect(providers[ProviderID.anthropic].source).toBe("env") + expect(providers[ProviderID.anthropic].auth).toBeUndefined() + }, + }) + } finally { + if (saved) await Auth.set("anthropic", saved) + } +}) +// altimate_change end diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index 6235aeaa18..4f5b9f9089 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -2218,6 +2218,7 @@ export type Provider = { id: string name: string source: "env" | "config" | "custom" | "api" + auth?: "api" | "oauth" | "wellknown" env: Array key?: string options: { diff --git a/packages/tui/src/app.tsx b/packages/tui/src/app.tsx index 39caae8a1b..c2ff3a377f 100644 --- a/packages/tui/src/app.tsx +++ b/packages/tui/src/app.tsx @@ -85,6 +85,7 @@ import { FrecencyProvider } from "./component/prompt/frecency" import { PromptStashProvider } from "./component/prompt/stash" import { DialogAlert } from "./ui/dialog-alert" import { DialogConfirm } from "./ui/dialog-confirm" +import { logoutTarget, logoutTitle } from "./util/logout-target" // altimate_change — /logout import { ToastProvider, useToast } from "./ui/toast" import { isDefaultTitle } from "./util/session" import { KVProvider, useKV } from "./context/kv" @@ -887,6 +888,87 @@ function App(props: { onSnapshot?: () => Promise; pluginHost: TuiPlugi if (workspace?.type !== "worktree" || !workspace.directory) return return workspace }) + // altimate_change start — /logout: the provider behind the current model, and how to sign out of it + const logoutTargetNow = createMemo(() => logoutTarget(local.model.current(), sync.data.provider)) + + async function logoutCurrentProvider() { + const target = logoutTargetNow() + if (!target) return + if (target.kind === "external") { + toast.show({ variant: "warning", message: target.hint, duration: 6000 }) + return + } + const confirmed = await DialogConfirm.show(dialog, "Log out", `Log out of ${target.label}?`) + if (confirmed !== true) return + const othersConnected = sync.data.provider_next.connected.some((id) => id !== target.providerID) + if (target.kind === "gateway") { + // The gateway and Base sign-outs need opencode-side modules (AltimateApi, FreeTier), so they + // run in packages/opencode/src/plugin/tui/altimate/provider-credentials.tsx. + keymap.dispatchCommand("altimate.provider.logout") + } else if (target.kind === "base") { + keymap.dispatchCommand("altimate.provider.logout.base") + } else { + try { + await sdk.client.auth.remove({ providerID: target.providerID }, { throwOnError: true }) + await sdk.client.instance.dispose(undefined, { throwOnError: true }) + } catch (err) { + toast.show({ variant: "error", message: err instanceof Error ? err.message : "Logout failed" }) + return + } + } + // The instance reload drops the provider from the synced list; the current model then falls + // back to another connected one. Say which, or reopen /connect when nothing is left. + const remaining = () => sync.data.provider.find((item) => item.id === target.providerID) + // A saved login can sit on top of an env key or config entry: once the reload lands, the + // provider is either gone or back without `auth`, and then it is still connected that way. + const settled = await waitFor(() => { + const provider = remaining() + return !provider || (target.kind === "saved" && !provider.auth) + }) + if (!settled) { + // The gateway and Base sign-outs report their own failure; this covers a reload that is slow or lost. + toast.show({ + variant: "warning", + message: `The provider list hasn't reloaded yet. If ${target.label} is still listed, run /logout again or restart.`, + duration: 8000, + }) + return + } + const still = remaining() + if (still) { + const after = logoutTarget({ providerID: still.id }, sync.data.provider) + toast.show({ + variant: "warning", + message: `Removed the saved login. ${after?.kind === "external" ? after.hint : `${still.name} is still connected.`}`, + duration: 8000, + }) + return + } + // Only now is the sign-out known to have landed; with nothing else connected, setup starts over. + if (!othersConnected) resetSetupComplete() + const next = local.model.current() + if (!next || next.providerID === target.providerID) { + dialog.replace(() => ) + return + } + if (target.kind === "saved") { + toast.show({ + variant: "success", + message: `Logged out of ${target.label}. Now using ${local.model.parsed().model}.`, + }) + } + } + + async function waitFor(check: () => boolean, timeoutMs = 10_000) { + const deadline = Date.now() + timeoutMs + while (!check()) { + if (Date.now() > deadline) return false + await new Promise((resolve) => setTimeout(resolve, 100)) + } + return true + } + // altimate_change end + const appCommands = createMemo(() => [ { @@ -1120,8 +1202,7 @@ function App(props: { onSnapshot?: () => Promise; pluginHost: TuiPlugi category: "Provider", }, // altimate_change end - // altimate_change start — /auth: sign in to the Altimate LLM Gateway directly; - // /logout: clear the stored gateway credential and disconnect. + // altimate_change start — /auth: sign in to the Altimate LLM Gateway directly { name: "altimate.auth", title: "Sign in to Altimate LLM Gateway", @@ -1132,16 +1213,16 @@ function App(props: { onSnapshot?: () => Promise; pluginHost: TuiPlugi }, category: "Provider", }, + // altimate_change end + // altimate_change start — /logout signs out of the provider behind the current model; the + // title names it, e.g. "Log out of OpenAI (ChatGPT subscription)". See util/logout-target.ts. { name: "altimate.logout", - title: "Sign out of Altimate LLM Gateway", + title: logoutTitle(logoutTargetNow()), + hidden: !logoutTargetNow(), slashName: "logout", run: () => { - // altimate_change — the credential clear + instance dispose + toast happen - // opencode-side (AltimateApi is unreachable from packages/tui); see - // packages/opencode/src/plugin/tui/altimate/provider-credentials.tsx. - keymap.dispatchCommand("altimate.provider.logout") - resetSetupComplete() + void logoutCurrentProvider() }, category: "Provider", }, diff --git a/packages/tui/src/util/logout-target.ts b/packages/tui/src/util/logout-target.ts new file mode 100644 index 0000000000..dde6a9a51a --- /dev/null +++ b/packages/tui/src/util/logout-target.ts @@ -0,0 +1,87 @@ +// altimate_change start — /logout signs out of the provider behind the current model. This file +// decides what that means for the provider: which login to remove, and what to call it. +import type { Provider } from "@opencode-ai/sdk/v2" + +export const GATEWAY_PROVIDER_ID = "altimate-backend" +export const ALTIMATE_BASE_PROVIDER_ID = "altimate-free" +/** Its saved entry only records that the user chose the Claude Code login; the login itself stays with `claude`. */ +const CLAUDE_AGENT_PROVIDER_ID = "claude-agent" +/** The keyless public Zen tier: its free models load with a public key, so there is no login behind them. */ +const ZEN_PROVIDER_ID = "opencode" + +/** Subscription names for OAuth sign-ins that are a paid plan; any other OAuth login is a generic "sign-in". */ +const SUBSCRIPTION_NAMES: Record = { + openai: "ChatGPT subscription", + "github-copilot": "Copilot subscription", +} + +export type LogoutProvider = Pick + +export type LogoutTarget = + /** The Altimate LLM Gateway: its own sign-out also removes the MCP servers that carry its key. */ + | { kind: "gateway"; providerID: string; label: string } + /** Altimate Base: a managed credential with its own store. */ + | { kind: "base"; providerID: string; label: string } + /** A login saved by altimate-code (API key or sign-in), removed from the auth store. */ + | { kind: "saved"; providerID: string; label: string } + /** Connected from outside altimate-code (environment variable, config, another tool): nothing to remove. */ + | { kind: "external"; providerID: string; label: string; hint: string } + +export function logoutTarget( + model: { providerID: string } | undefined, + providers: readonly LogoutProvider[], +): LogoutTarget | undefined { + if (!model) return + const providerID = model.providerID + if (providerID === GATEWAY_PROVIDER_ID) return { kind: "gateway", providerID, label: "Altimate LLM Gateway" } + if (providerID === ALTIMATE_BASE_PROVIDER_ID) return { kind: "base", providerID, label: "Altimate Base" } + const provider = providers.find((item) => item.id === providerID) + if (!provider) return + if (provider.auth) return { kind: "saved", providerID, label: `${provider.name} (${loginName(provider)})` } + if (provider.source === "env") { + const variable = provider.env.length === 1 ? provider.env[0] : "an environment variable" + return { + kind: "external", + providerID, + label: `${provider.name} is set by ${variable}`, + hint: `${provider.name} is set by ${variable}. Unset it and restart to disconnect.`, + } + } + if (provider.source === "config") { + return { + kind: "external", + providerID, + label: `${provider.name} is set in your config`, + hint: `${provider.name} is set in your config. Remove it there to disconnect.`, + } + } + if (providerID === ZEN_PROVIDER_ID) { + return { + kind: "external", + providerID, + label: "Free models need no login", + hint: "Free models need no login, so there is nothing to log out of.", + } + } + return { + kind: "external", + providerID, + label: `${provider.name} is connected outside Altimate Code`, + hint: `${provider.name} is connected outside Altimate Code, so there is no login here to remove.`, + } +} + +function loginName(provider: LogoutProvider): string { + if (provider.id === CLAUDE_AGENT_PROVIDER_ID) return "Claude Code connection" + if (provider.auth === "api") return "API key" + if (provider.auth === "oauth") return SUBSCRIPTION_NAMES[provider.id] ?? "sign-in" + return "sign-in" +} + +/** The command title: the action for a login we can remove, the explanation for one we can't. */ +export function logoutTitle(target: LogoutTarget | undefined): string { + if (!target) return "Log out" + if (target.kind === "external") return target.label + return `Log out of ${target.label}` +} +// altimate_change end diff --git a/packages/tui/test/util/logout-target.test.ts b/packages/tui/test/util/logout-target.test.ts new file mode 100644 index 0000000000..b7b493e46e --- /dev/null +++ b/packages/tui/test/util/logout-target.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, test } from "bun:test" +import { logoutTarget, logoutTitle, type LogoutProvider } from "../../src/util/logout-target" + +const provider = (overrides: Partial & { id: string }): LogoutProvider => ({ + name: overrides.id, + source: "custom", + env: [], + ...overrides, +}) + +describe("logoutTarget", () => { + test("no current model means nothing to log out of", () => { + expect(logoutTarget(undefined, [])).toBeUndefined() + expect(logoutTitle(undefined)).toBe("Log out") + }) + + test("a current model whose provider is gone from the list has no target", () => { + expect(logoutTarget({ providerID: "openai" }, [])).toBeUndefined() + }) + + test("the gateway keeps its own sign-out and name", () => { + const target = logoutTarget({ providerID: "altimate-backend" }, []) + expect(target?.kind).toBe("gateway") + expect(logoutTitle(target)).toBe("Log out of Altimate LLM Gateway") + }) + + test("Altimate Base uses the managed sign-out", () => { + const target = logoutTarget({ providerID: "altimate-free" }, []) + expect(target?.kind).toBe("base") + expect(logoutTitle(target)).toBe("Log out of Altimate Base") + }) + + test("a ChatGPT sign-in is named as the subscription", () => { + const target = logoutTarget({ providerID: "openai" }, [provider({ id: "openai", name: "OpenAI", auth: "oauth" })]) + expect(target?.kind).toBe("saved") + expect(logoutTitle(target)).toBe("Log out of OpenAI (ChatGPT subscription)") + }) + + test("a saved API key is named as an API key, even when config also lists the provider", () => { + const target = logoutTarget( + { providerID: "openai" }, + [provider({ id: "openai", name: "OpenAI", source: "config", auth: "api" })], + ) + expect(logoutTitle(target)).toBe("Log out of OpenAI (API key)") + }) + + test("an OAuth sign-in for a provider without a known plan is a generic sign-in", () => { + const target = logoutTarget({ providerID: "acme" }, [provider({ id: "acme", name: "Acme", auth: "oauth" })]) + expect(logoutTitle(target)).toBe("Log out of Acme (sign-in)") + }) + + test("a provider set by one environment variable names it and removes nothing", () => { + const target = logoutTarget( + { providerID: "openai" }, + [provider({ id: "openai", name: "OpenAI", source: "env", env: ["OPENAI_API_KEY"] })], + ) + expect(target?.kind).toBe("external") + expect(logoutTitle(target)).toBe("OpenAI is set by OPENAI_API_KEY") + expect(target?.kind === "external" && target.hint).toContain("Unset it") + }) + + test("a provider with several candidate variables does not guess which one is set", () => { + const target = logoutTarget( + { providerID: "google" }, + [provider({ id: "google", name: "Google", source: "env", env: ["GOOGLE_API_KEY", "GEMINI_API_KEY"] })], + ) + expect(logoutTitle(target)).toBe("Google is set by an environment variable") + expect(target?.kind === "external" && target.hint).toBe( + "Google is set by an environment variable. Unset it and restart to disconnect.", + ) + }) + + test("a provider from config without a saved login points at the config", () => { + const target = logoutTarget({ providerID: "local" }, [provider({ id: "local", name: "Local", source: "config" })]) + expect(logoutTitle(target)).toBe("Local is set in your config") + }) + + test("a provider connected by another tool says there is nothing to remove", () => { + const target = logoutTarget({ providerID: "acme" }, [provider({ id: "acme", name: "Acme" })]) + expect(target?.kind).toBe("external") + expect(logoutTitle(target)).toBe("Acme is connected outside Altimate Code") + }) + + test("Claude Agent is named as the Claude Code connection, not an API key", () => { + // `/connect` saves { type: "api", key: "claude-code-login" } for it; the login itself stays with `claude`. + const target = logoutTarget( + { providerID: "claude-agent" }, + [provider({ id: "claude-agent", name: "Claude Agent", auth: "api" })], + ) + expect(target?.kind).toBe("saved") + expect(logoutTitle(target)).toBe("Log out of Claude Agent (Claude Code connection)") + }) + + // The keyless public Zen tier's provider ID. + const zen = "opencode" + + test("the free Zen models say there is no login, not that another tool connected them", () => { + const target = logoutTarget({ providerID: zen }, [provider({ id: zen, name: "Zen" })]) + expect(target?.kind).toBe("external") + expect(logoutTitle(target)).toBe("Free models need no login") + }) + + test("Zen with a saved key is logged out like any saved key", () => { + const target = logoutTarget({ providerID: zen }, [provider({ id: zen, name: "Zen", auth: "api" })]) + expect(logoutTitle(target)).toBe("Log out of Zen (API key)") + }) + + test("with several saved logins, the target is the current model's provider", () => { + const providers = [ + provider({ id: "anthropic", name: "Anthropic", auth: "api" }), + provider({ id: "openai", name: "OpenAI", auth: "oauth" }), + provider({ id: "google", name: "Google", source: "env", env: ["GOOGLE_API_KEY"] }), + ] + const target = logoutTarget({ providerID: "openai" }, providers) + expect(target).toEqual({ kind: "saved", providerID: "openai", label: "OpenAI (ChatGPT subscription)" }) + expect(logoutTarget({ providerID: "google" }, providers)?.kind).toBe("external") + }) +})