diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index 4c1b153ca1..2c361c698f 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -18,10 +18,14 @@ const DEFAULT_MCP_URL = "https://mcpserver.getaltimate.com/sse" const DEFAULT_ALTIMATE_URL = "https://api.myaltimate.com" // altimate_change end +// A blank field is not a sign-in. Accepted, a blank key loaded the gateway provider as connected, +// so a message went to the gateway with no Authorization header and got 403 "Not authenticated". +const CredentialField = z.string().refine((value) => value.trim() !== "", "must not be blank") + const AltimateCredentials = z.object({ - altimateUrl: z.string(), - altimateInstanceName: z.string(), - altimateApiKey: z.string(), + altimateUrl: CredentialField, + altimateInstanceName: CredentialField, + altimateApiKey: CredentialField, mcpServerUrl: z.string().optional(), }) type AltimateCredentials = z.infer @@ -183,20 +187,38 @@ export namespace AltimateApi { } } + /** The key to match MCP entries by on sign-out, read as written. Unlike `getCredentials()` it accepts + * a file whose fields are blank or missing: such a file holds no key to protect, so sign-out can + * clear it. Undefined when there is no key; throws when one may exist but can't be read. Only the + * key is substituted, so an unset `${env:…}` in another field cannot keep a keyless file. */ + async function savedKeyForSignOut(): Promise { + const scoped = currentCredentials() + if (scoped) return scoped.altimateApiKey + const raw: unknown = JSON.parse(await Filesystem.readText(credentialsPath())) + if (!raw || typeof raw !== "object" || Array.isArray(raw)) + throw new Error("the file does not hold the credentials object.") + const written = (raw as { altimateApiKey?: unknown }).altimateApiKey + if (written === undefined) return undefined + if (typeof written !== "string") throw new Error("altimateApiKey is not a string.") + const key = resolveEnvVars(written) as string + return key.trim() === "" ? undefined : key + } + /** Sign out of the gateway: remove MCP entries that carry the saved key, then delete the credential file. * Standalone `datamate add` writes the key into MCP headers (`buildMcpConfig`); matching the exact key * leaves user-authored entries alone. Searches the global config and every project config a session in * `projectDir` loads. Fails without deleting the file when the key can't be read: the file holds the - * only copy, and without it leftover MCP entries can never be matched. */ + * only copy, and without it leftover MCP entries can never be matched. A file with no key, or a blank + * one, is simply cleared. */ export async function signOut(projectDir: string): Promise> { if (!(await isConfigured())) { await withdrawClaudeSkills(projectDir) await forgetTelemetryIdentity() return [] } - let key: string + let key: string | undefined try { - key = (await getCredentials()).altimateApiKey + key = await savedKeyForSignOut() } catch (err) { throw new Error( `could not read the saved key from ${credentialsPath()} (${err instanceof Error ? err.message : err}); ` + @@ -208,7 +230,7 @@ export namespace AltimateApi { ...(await findGlobalConfigPaths(Global.Path.config)), ] const removed: Array<{ name: string; path: string }> = [] - for (const configPath of configPaths) { + for (const configPath of key ? configPaths : []) { for (const name of await listMcpInConfig(configPath)) { const entry = await readMcpEntryFromDisk(name, configPath) if (entry?.type !== "remote" || entry.headers?.Authorization !== `Bearer ${key}`) continue diff --git a/packages/opencode/src/altimate/api/sign-in.ts b/packages/opencode/src/altimate/api/sign-in.ts new file mode 100644 index 0000000000..a072e1daeb --- /dev/null +++ b/packages/opencode/src/altimate/api/sign-in.ts @@ -0,0 +1,5 @@ +/** The browser sign-in from a plain shell: the Altimate LLM Gateway method of the `altimate-backend` + * provider saves the credentials every workspace command reads. `--method` skips the method picker, + * so the command also works where stdin is not a terminal (an agent's shell, Claude Code's `!`). + * Kept apart from the CLI commands so error messages outside the CLI can name it too. */ +export const SIGN_IN_COMMAND = 'altimate-code auth login -p altimate-backend --method "Altimate LLM Gateway"' diff --git a/packages/opencode/src/cli/cmd/link.ts b/packages/opencode/src/cli/cmd/link.ts index 56fd23ee76..d8dacdc526 100644 --- a/packages/opencode/src/cli/cmd/link.ts +++ b/packages/opencode/src/cli/cmd/link.ts @@ -15,6 +15,7 @@ import { UI } from "../ui" import * as prompts from "@clack/prompts" import open from "open" import { AltimateApi } from "@/altimate/api/client" +import { SIGN_IN_COMMAND } from "@/altimate/api/sign-in" import { WorkspaceApi, ConflictError, @@ -59,10 +60,8 @@ import { // Re-exported: other commands and tests import it from here. export { stripControlChars } -/** The browser sign-in from a plain shell: the Altimate LLM Gateway method of the `altimate-backend` - * provider saves the credentials every workspace command reads. `--method` skips the method picker, - * so the command also works where stdin is not a terminal (an agent's shell, Claude Code's `!`). */ -export const SIGN_IN_COMMAND = 'altimate-code auth login -p altimate-backend --method "Altimate LLM Gateway"' +// Re-exported: other commands and tests import it from here. +export { SIGN_IN_COMMAND } const CREATE_NEW_SENTINEL = "__create_new__" const SET_UP_IN_BROWSER_SENTINEL = "__browser_handoff__" diff --git a/packages/opencode/src/provider/error.ts b/packages/opencode/src/provider/error.ts index 67bb6237cf..7abe7d5b74 100644 --- a/packages/opencode/src/provider/error.ts +++ b/packages/opencode/src/provider/error.ts @@ -4,6 +4,9 @@ import { iife } from "@/util/iife" import type { ProviderID } from "./schema" // altimate_change start — translate managed Altimate Base gateway errors import { FreeTier } from "@/altimate/free/client" +import { SIGN_IN_COMMAND } from "@/altimate/api/sign-in" + +const ALTIMATE_GATEWAY_PROVIDER_ID = "altimate-backend" // altimate_change end export namespace ProviderError { @@ -404,6 +407,26 @@ export namespace ProviderError { } } // altimate_change end + // altimate_change start — the Altimate LLM Gateway refusing the key means the user must sign in + // again. It answers a missing key with 403 "Not authenticated" and a wrong one with 401; credit + // limits are 402. The gateway's own words stay in the message so error counts keep matching. + if ( + String(input.providerID) === ALTIMATE_GATEWAY_PROVIDER_ID && + (input.error.statusCode === 401 || input.error.statusCode === 403) + ) { + return { + type: "api_error", + message: + "Sign in to Altimate again: the Altimate LLM Gateway refused the request because the saved " + + `Altimate sign-in is missing or no longer valid. In a terminal, run \`${SIGN_IN_COMMAND}\`. (${m})`, + statusCode: input.error.statusCode, + isRetryable: false, + responseHeaders: input.error.responseHeaders, + responseBody: capResponseBody(input.error.responseBody), + metadata: input.error.url ? { url: maskInternalHost(input.error.url) } : undefined, + } + } + // altimate_change end // altimate_change start — distinguish the gateway byte cap from context overflow // The gateway's fixed request-byte cap is not a context overflow. Retrying compaction can // never help when system instructions and tool schemas alone exceed it. diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index f9c3a72ebf..f55a6f87d7 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -579,8 +579,9 @@ export namespace Provider { }, } } catch { - // Suppress stale auth so the generic Auth.all() merge doesn't leave an invalid provider - await Auth.remove(ProviderID.make("altimate-backend")).catch(() => {}) + // An unusable file (blank fields, bad JSON, an unset ${env:…}) is not a sign-in. The + // auth-store entry is kept: the generic Auth.all() merge skips this provider, so the + // entry can no longer list it without a URL, and deleting it would lose a saved key. return { autoload: false } } } @@ -1940,6 +1941,10 @@ export namespace Provider { for (const [id, provider] of Object.entries(await Auth.all())) { // altimate_change start — the managed provider is hydrated only from its dedicated credential store if (id === FreeTier.PROVIDER_ID) continue + // The gateway's entry is a `url::instance::key` string that only its custom loader can parse. + // Merged raw it listed the provider with no URL ("undefined/chat/completions") whenever the + // loader declined it, because a provider that already exists keeps its place in the list. + if (id === "altimate-backend") continue // altimate_change end const providerID = ProviderID.make(id) if (disabled.has(providerID)) continue diff --git a/packages/opencode/test/altimate/datamate.test.ts b/packages/opencode/test/altimate/datamate.test.ts index f28e8a413e..3d5e1031f0 100644 --- a/packages/opencode/test/altimate/datamate.test.ts +++ b/packages/opencode/test/altimate/datamate.test.ts @@ -193,7 +193,7 @@ describe("getCredentials", () => { ) }) - test("resolves empty-string env var without throwing", async () => { + test("substitutes an empty-string env var, and the blank field it leaves is not a credential", async () => { const altDir = path.join(testHome, ".altimate") await fsp.mkdir(altDir, { recursive: true }) await fsp.writeFile( @@ -206,8 +206,12 @@ describe("getCredentials", () => { ) process.env.TEST_EMPTY_VAR = "" try { - const creds = await AltimateApi.getCredentials() - expect(creds.altimateInstanceName).toBe("") + // A set-but-empty variable is substituted (only an unset one is "not found"), and a blank + // instance name or key is refused: loaded, it sent gateway requests with no usable credential. + const error = String(await AltimateApi.getCredentials().catch((e) => e)) + expect(error).toContain("altimateInstanceName") + expect(error).toContain("must not be blank") + expect(error).not.toContain("not found") } finally { delete process.env.TEST_EMPTY_VAR } diff --git a/packages/opencode/test/altimate/sign-out.test.ts b/packages/opencode/test/altimate/sign-out.test.ts index 6fb1ad4224..847e4d380d 100644 --- a/packages/opencode/test/altimate/sign-out.test.ts +++ b/packages/opencode/test/altimate/sign-out.test.ts @@ -95,6 +95,48 @@ describe("AltimateApi.signOut", () => { expect(await readJson(rootConfig)).toEqual({ mcp: { "datamate-sales": datamateEntry("gateway-test-key") } }) }) + test.each([ + ["a blank key", { altimateUrl: "https://api.test", altimateInstanceName: "tenant", altimateApiKey: "" }], + ["a whitespace key", { altimateUrl: "https://api.test", altimateInstanceName: "tenant", altimateApiKey: " " }], + ["no fields at all", {}], + ])("clears a credential file with %s, leaving MCP entries alone", async (_, content) => { + // Such a file holds no key to protect, and no MCP entry can carry it. Refusing to clear it + // left people who were never signed in unable to sign out. + await writeJson(AltimateApi.credentialsPath(), content) + await writeJson(rootConfig, { mcp: { "datamate-sales": datamateEntry("gateway-test-key") } }) + + expect(await AltimateApi.signOut(subdir)).toEqual([]) + + expect(await AltimateApi.isConfigured()).toBe(false) + expect(await readJson(rootConfig)).toEqual({ mcp: { "datamate-sales": datamateEntry("gateway-test-key") } }) + }) + + test("clears a keyless file even when another field names an unset env var", async () => { + delete process.env.SIGN_OUT_TEST_UNSET_URL + await writeJson(AltimateApi.credentialsPath(), { + altimateUrl: "${env:SIGN_OUT_TEST_UNSET_URL}", + altimateInstanceName: "tenant", + altimateApiKey: "", + }) + + expect(await AltimateApi.signOut(subdir)).toEqual([]) + expect(await AltimateApi.isConfigured()).toBe(false) + }) + + test("removes entries carrying a readable key even when another field is blank", async () => { + await writeJson(AltimateApi.credentialsPath(), { + altimateUrl: "https://api.test", + altimateInstanceName: "", + altimateApiKey: "gateway-test-key", + }) + await writeJson(rootConfig, { mcp: { "datamate-sales": datamateEntry("gateway-test-key") } }) + + expect(await AltimateApi.signOut(subdir)).toEqual([{ name: "datamate-sales", path: rootConfig }]) + + expect(await AltimateApi.isConfigured()).toBe(false) + expect(await readJson(rootConfig)).toEqual({ mcp: {} }) + }) + test("is a no-op when there is no credential file", async () => { await writeJson(rootConfig, { mcp: { "datamate-sales": datamateEntry("gateway-test-key") } }) diff --git a/packages/opencode/test/provider/error.test.ts b/packages/opencode/test/provider/error.test.ts index 3355539862..caaf3bda88 100644 --- a/packages/opencode/test/provider/error.test.ts +++ b/packages/opencode/test/provider/error.test.ts @@ -636,3 +636,63 @@ describe("ProviderError.parseAPICallError: Altimate Base request-too-large isola }) // altimate_change end }) + +describe("ProviderError.parseAPICallError: Altimate LLM Gateway refusing the key", () => { + const statusText: Record = { 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden" } + const gatewayError = (statusCode: number, detail: string) => + makeAPICallError({ + message: statusText[statusCode], + statusCode, + responseBody: JSON.stringify({ detail }), + url: "https://api.myaltimate.com/agents/v1/chat/completions", + }) + + test("403 Not authenticated (no key sent) asks the user to sign in again", () => { + const result = ProviderError.parseAPICallError({ + providerID: "altimate-backend" as any, + error: gatewayError(403, "Not authenticated"), + }) + expect(result.type).toBe("api_error") + if (result.type !== "api_error") return + expect(result.message).toStartWith("Sign in to Altimate again") + expect(result.message).toContain("altimate-code auth login -p altimate-backend") + // The gateway's own text stays, so counts of this error keep matching after the fix. + expect(result.message).toContain('Forbidden: {"detail":"Not authenticated"}') + expect(result.statusCode).toBe(403) + expect(result.isRetryable).toBe(false) + }) + + test("401 Incorrect auth token (revoked or wrong key) asks the user to sign in again", () => { + const result = ProviderError.parseAPICallError({ + providerID: "altimate-backend" as any, + error: gatewayError(401, "Incorrect auth token"), + }) + expect(result.type).toBe("api_error") + if (result.type !== "api_error") return + expect(result.message).toStartWith("Sign in to Altimate again") + expect(result.message).toContain('Unauthorized: {"detail":"Incorrect auth token"}') + expect(result.statusCode).toBe(401) + }) + + test("402 (out of credits) from the gateway is not a sign-in problem", () => { + const result = ProviderError.parseAPICallError({ + providerID: "altimate-backend" as any, + error: gatewayError(402, "Your free credits are used up"), + }) + expect(result.type).toBe("api_error") + if (result.type !== "api_error") return + expect(result.message).not.toContain("Sign in to Altimate again") + expect(result.message).toContain('Payment Required: {"detail":"Your free credits are used up"}') + }) + + test("a 403 from another provider keeps its own message", () => { + const result = ProviderError.parseAPICallError({ + providerID: "openai" as any, + error: gatewayError(403, "Not authenticated"), + }) + expect(result.type).toBe("api_error") + if (result.type !== "api_error") return + expect(result.message).not.toContain("Sign in to Altimate again") + expect(result.message).toContain('Forbidden: {"detail":"Not authenticated"}') + }) +}) diff --git a/packages/opencode/test/provider/provider.test.ts b/packages/opencode/test/provider/provider.test.ts index 50d6df5f36..21c96c525d 100644 --- a/packages/opencode/test/provider/provider.test.ts +++ b/packages/opencode/test/provider/provider.test.ts @@ -3032,6 +3032,113 @@ test("defaultModel falls through to other providers when altimate is not configu }, }) }) + +// A credentials file that is present but not a sign-in. Listed, the gateway provider became the +// default model and its first request went out with no Authorization header (403 "Not authenticated"). +async function withAltimateFile(content: unknown, fn: (dir: string) => Promise) { + await using tmp = await tmpdir({ + init: async (dir) => { + await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ $schema: "https://altimate.ai/config.json" })) + }, + }) + const originalHome = process.env.OPENCODE_TEST_HOME + process.env.OPENCODE_TEST_HOME = tmp.path + await fs.mkdir(path.join(tmp.path, ".altimate"), { recursive: true }) + await Bun.write(path.join(tmp.path, ".altimate", "altimate.json"), JSON.stringify(content)) + try { + return await fn(tmp.path) + } finally { + if (originalHome === undefined) delete process.env.OPENCODE_TEST_HOME + else process.env.OPENCODE_TEST_HOME = originalHome + } +} + +test.each([ + [ + "a blank key", + { altimateUrl: "https://test.altimate.ai", altimateInstanceName: "test-instance", altimateApiKey: "" }, + ], + [ + "a whitespace key", + { altimateUrl: "https://test.altimate.ai", altimateInstanceName: "test-instance", altimateApiKey: " " }, + ], + [ + "a blank key and instance name", + { altimateUrl: "https://test.altimate.ai", altimateInstanceName: "", altimateApiKey: "" }, + ], + [ + "a blank instance name", + { altimateUrl: "https://test.altimate.ai", altimateInstanceName: "", altimateApiKey: "test-api-key" }, + ], + ["a blank URL", { altimateUrl: "", altimateInstanceName: "test-instance", altimateApiKey: "test-api-key" }], +])("altimate.json with %s does not list altimate-backend or make it the default", async (_, content) => { + await withAltimateFile(content, (dir) => + provideProviderTestInstance({ + directory: dir, + init: async () => { + Env.set("ANTHROPIC_API_KEY", "test-api-key") + }, + fn: async () => { + const providers = await Provider.list() + expect(providers["altimate-backend"]).toBeUndefined() + const model = await Provider.defaultModel() + expect(String(model.providerID)).toBe("anthropic") + }, + }), + ) +}) + +test("an altimate-backend auth entry next to an unusable altimate.json does not list a provider with no URL", async () => { + await withAltimateFile({}, async (dir) => { + await Auth.set("altimate-backend", { type: "api", key: "https://test.altimate.ai::test-instance::test-api-key" }) + try { + await provideProviderTestInstance({ + directory: dir, + init: async () => { + Env.set("ANTHROPIC_API_KEY", "test-api-key") + }, + fn: async () => { + const providers = await Provider.list() + expect(providers["altimate-backend"]).toBeUndefined() + }, + }) + // The unusable file declines the sign-in without deleting the saved key. + expect(await Auth.get("altimate-backend")).toEqual({ + type: "api", + key: "https://test.altimate.ai::test-instance::test-api-key", + }) + } finally { + await Auth.remove("altimate-backend") + } + }) +}) + +test("an altimate-backend auth entry alone still signs in to the gateway with its URL, key and instance", async () => { + await using tmp = await tmpdir({ + init: async (dir) => { + await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ $schema: "https://altimate.ai/config.json" })) + }, + }) + const originalHome = process.env.OPENCODE_TEST_HOME + process.env.OPENCODE_TEST_HOME = tmp.path + await Auth.set("altimate-backend", { type: "api", key: "https://test.altimate.ai::test-instance::test-api-key" }) + try { + await provideProviderTestInstance({ + directory: tmp.path, + fn: async () => { + const provider = (await Provider.list())["altimate-backend"] + expect(provider).toBeDefined() + expect(provider.options.baseURL).toBe("https://test.altimate.ai/agents/v1") + expect(provider.options.apiKey).toBe("test-api-key") + expect(provider.options.headers).toEqual({ "x-tenant": "test-instance" }) + }, + }) + } finally { + await Auth.remove("altimate-backend") + if (originalHome === undefined) delete process.env.OPENCODE_TEST_HOME + else process.env.OPENCODE_TEST_HOME = originalHome + } +}) // altimate_change end // altimate_change start — upstream_fix: `ModelsCatalog.isCatalog` only requires