Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 29 additions & 7 deletions packages/opencode/src/altimate/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Blank-field refusal also breaks sign-out for exactly the file state this PR fixes

Once a blank field throws, signOut() (lines 195-209) turns any getCredentials() failure into a hard error. Both sign-out entry points call it — TUI /logout (packages/opencode/src/plugin/tui/altimate/provider-credentials.tsx:90) and altimate-code auth logout -p altimate-backend (packages/opencode/src/cli/cmd/providers.ts:670) — so a user whose altimate.json already holds altimateApiKey: "" (the state behind #1834) cannot sign out: the file is kept, the TUI only shows could not read the saved key ... fix the file and sign out again, and the CLI aborts before authSvc.remove, so the auth-store entry survives as well. On main that file parsed, so signOut cleared it. The stated rationale for refusing ("the file holds the only copy") does not apply when the field is blank: there is no key to match MCP entries by, so clearing is still the right outcome. Suggest catching z.ZodError in signOut and continuing to clearCredentials(), keeping the hard failure only for a file that genuinely cannot be read.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good catch, that was a real regression. fixed in 18874d6: sign-out reads the key itself now, so a file with no key or a blank one gets cleared, and it still refuses when a key might exist but can't be read. tests cover blank, whitespace and empty files.

Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: a blank field now makes the workspace overlay remove the user's own datamate MCP server on every turn.

This was raised by Codex and reproduced live.

  • With altimate.json holding all three fields and altimateApiKey: "", getCredentials() now throws.
  • readLocalBindingScopedStrict passes the throw on, and engine-probes.resolveBinding turns it into failed.
  • engine-overlay.refuseUnreadableLink then calls MCP.remove("datamate") and prints Workspace link could not be read: … on every run.

The test used a stdio MCP server registered as datamate in the global config, with altimate run -m altimate-free/altimate-base "hi":

  • base sends the tools datamate_manager, datamate_stubping
  • this head sends only datamate_manager

This doesn't block. It is edge input: terminal use, plus a datamate entry, plus a file whose fields are present with one blank. Main already removes the entry the same way for {}, a missing field, bad JSON or an unset ${env:…}, and the overlay is off under altimate serve.

A follow-up could treat a file whose fields are blank as "no account" in the workspace-binding read (unbound, as on main) and keep the failed path for files that really can't be read.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: for a blank file, the error text is now a raw ZodError JSON.

altimate workspace list:

  • base: Error: Could not load workspaces: Not authenticated
  • this head: Error: Could not load workspaces: [ { "code": "custom", "path": [ "altimateApiKey" ], "message": "must not be blank" }]

The overlay warning above shows the same JSON. Neither message says to sign in.

This is cosmetic, and R1 covers the substance. Mapping a validation failure from getCredentials() to a short sentence would help, for example "the saved Altimate sign-in is blank; run <SIGN_IN_COMMAND>".


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<typeof AltimateCredentials>
Expand Down Expand Up @@ -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<string | undefined> {
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<Array<{ name: string; path: string }>> {
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}); ` +
Expand All @@ -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
Expand Down
5 changes: 5 additions & 0 deletions packages/opencode/src/altimate/api/sign-in.ts
Original file line number Diff line number Diff line change
@@ -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"'
7 changes: 3 additions & 4 deletions packages/opencode/src/cli/cmd/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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__"
Expand Down
23 changes: 23 additions & 0 deletions packages/opencode/src/provider/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 " +

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: 403 guidance names only the API key, but this repo already maps a gateway 403 to the instance name

AltimateApi.validateCredentials (packages/opencode/src/altimate/api/client.ts:280-287) reads a 401 as "Invalid API key" and a 403 as "Invalid instance name". This branch covers both statuses with a message saying only the key is "missing or no longer valid", so a user whose altimateInstanceName (tenant) is wrong is told to replace a key that is fine, and a repeat sign-in may keep the same wrong value if the flow is not browser-driven. Naming both causes keeps the 403 guidance accurate.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reworded in 18874d6 to say the saved sign-in is missing or no longer valid, so it doesn't point only at the key. on /agents/v1 the 403 comes from the missing bearer, but signing in again fixes either cause.

`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.
Expand Down
9 changes: 7 additions & 2 deletions packages/opencode/src/provider/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}
}
Expand Down Expand Up @@ -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
Expand Down
10 changes: 7 additions & 3 deletions packages/opencode/test/altimate/datamate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
}
Expand Down
42 changes: 42 additions & 0 deletions packages/opencode/test/altimate/sign-out.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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") } })

Expand Down
60 changes: 60 additions & 0 deletions packages/opencode/test/provider/error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number, string> = { 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")
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
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"}')
})
})
Loading
Loading