Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(meta-muse-code): add muse@ signed by the Muse Code login
Jack Rudenkoa5e67ec026f8
diff --git a/packages/cli/src/auth/credentials/authority.ts b/packages/cli/src/auth/credentials/authority.tsindex b3391c54..42305320 100644--- a/packages/cli/src/auth/credentials/authority.ts+++ b/packages/cli/src/auth/credentials/authority.ts@@ -21,6 +21,7 @@ import { DevinCredentialProvider } from "./devin-credential.js";import { GrokSubscriptionCredentialProvider } from "./grok-credential.js";import { makeKimiCodingCredential, makeKimiCredential } from "./kimi-credential.js";import { LocalCredentialProvider } from "./local-credential.js";+import { MuseCodeCredentialProvider } from "./muse-code-credential.js";import { NativeAnthropicCredentialProvider } from "./native-anthropic-credential.js";import type {CredentialProvider,@@ -254,6 +255,10 @@ export class CredentialAuthority {// "x-ai": that is the METERED XAI_API_KEY provider, and crossing them would// let a pay-per-token key authenticate a flat-rate `SUB` provider.authority.register(new GrokSubscriptionCredentialProvider(), ["grok-subscription"]);+ // Muse Code: a key minted from a Meta `dca:` login, confirmed by the mint's+ // entitlement answer. `apiKeyEnvVar: ""`, so the generic loop skips it; it+ // must NOT alias onto "meta", the METERED META_API_KEY provider.+ authority.register(new MuseCodeCredentialProvider(), ["meta-muse-code"]);authority.register(makeKimiCredential(), ["kimi"]);// kimi-coding is a SEPARATE product with its own endpoint + KIMI_CODING_API_KEY.// It must NOT alias onto the regular Kimi credential, or the coding endpointdiff --git a/packages/cli/src/auth/credentials/muse-code-credential.ts b/packages/cli/src/auth/credentials/muse-code-credential.tsnew file mode 100644index 00000000..851ca7a3--- /dev/null+++ b/packages/cli/src/auth/credentials/muse-code-credential.ts@@ -0,0 +1,79 @@+/**+ * Muse Code subscription credential — a key minted from a Meta `dca:` login.+ *+ * The `meta-muse-code` definition sets `apiKeyEnvVar: ""`, and that is+ * load-bearing: proxy-server's generic key extraction would otherwise cache a+ * short-lived minted key past its life, and the generic loop in+ * `authority.ts` would register an ApiKeyCredentialProvider for it.+ * `META_API_KEY` is NEVER aliased here: it is the METERED `meta` provider's+ * key, and honouring it would let a per-token key sign a provider claudish+ * reports as flat-rate SUB.+ *+ * Every artifact is `arm: "oauth"`. There is no api-key half, so nothing can+ * fall through to an unconfirmed key (CLAUDE.md: absent `arm` ⇒ metered).+ */++import {+ MUSE_NON_INTERACTIVE_MESSAGE,+ ensureMuseCredentialReady,+ isMuseCredentialConfigured,+ museCredentialStatusFromFiles,+ refreshMuseCredentialStatus,+ requestPathMayPrompt,+ resetMuseCredentialState,+} from "../../providers/meta-muse/muse-credentials.js";+import { credentialPromptRole } from "./prompt-role.js";+import type { CredentialProvider, ReadinessResult, RequestAuth } from "./types.js";+import { readinessDetail } from "./types.js";++export class MuseCodeCredentialProvider implements CredentialProvider {+ readonly catalogName = "meta-muse-code";++ /**+ * Present when claudish's own login or its borrowed copy is on disk, or —+ * only in a process that may read the Keychain — when the Muse Code CLI's+ * item exists (attributes only; no dialog). In a `never` process a+ * Keychain-only login is ABSENT: it could not be used here, and a kept+ * candidate would only fail later with the login message.+ */+ async describeReadiness(): Promise<ReadinessResult> {+ try {+ // A `never` process asks no Keychain question at all, not even the+ // attribute-only one: a locked login keychain can answer any `security`+ // call with an unlock dialog, and this process could not use the item.+ const status =+ credentialPromptRole() === "never"+ ? museCredentialStatusFromFiles()+ : await refreshMuseCredentialStatus();+ if (status === "absent" && credentialPromptRole() === "never") {+ return { readiness: "absent", detail: MUSE_NON_INTERACTIVE_MESSAGE };+ }+ if (status === "failed") {+ return {+ readiness: "failed",+ detail: "the macOS Keychain could not be asked about the Muse Code login",+ };+ }+ return { readiness: isMuseCredentialConfigured(status) ? "present" : "absent" };+ } catch (err) {+ return {+ readiness: "failed",+ detail: `Muse Code credential could not be read: ${readinessDetail(err) ?? "unknown error"}`,+ };+ }+ }++ async isAvailable(): Promise<boolean> {+ return (await this.describeReadiness()).readiness === "present";+ }++ /** A confirmed key; the request path may use the Keychain only in an interactive launch. */+ async getRequestAuth(): Promise<RequestAuth> {+ const state = await ensureMuseCredentialReady({ prompt: requestPathMayPrompt() });+ return { headers: { Authorization: `Bearer ${state.key}` }, arm: "oauth" };+ }++ invalidate(): void {+ resetMuseCredentialState();+ }+}diff --git a/packages/cli/src/auth/credentials/source.ts b/packages/cli/src/auth/credentials/source.tsindex e4dbad05..eb39294b 100644--- a/packages/cli/src/auth/credentials/source.ts+++ b/packages/cli/src/auth/credentials/source.ts@@ -42,6 +42,10 @@import { isLocalProviderEnabled } from "../../profile-config.js";import { hasDevinCredentials } from "../../providers/devin/devin-credentials.js";+import {+ isMuseCredentialConfigured,+ museCredentialStatus,+} from "../../providers/meta-muse/muse-credentials.js";import { hasSharedAntigravityToken } from "../antigravity-token.js";import { hasOAuthCredentials } from "../oauth-registry.js";import { peekVertexProjectOrigin } from "../vertex-auth.js";@@ -111,6 +115,14 @@ export interface SourceConfig {*/export function describeSourceSync(p: SourceClassifiable, config: SourceConfig): CredentialSource {if (p.isLocal) return isLocalProviderEnabled(p.catalogName, config) ? "local" : null;+ // Muse Code BEFORE the generic OAuth branch: its login is claudish's own file,+ // the borrowed copy, or the Muse Code CLI's Keychain item, none of which+ // `hasOAuthCredentials` reads. `"oauth"` for the same wire-contract reason as+ // Devin below. Sync: two file checks plus the Keychain PRESENCE memo, which+ // an async caller refreshes (`refreshMuseCredentialStatus`); no dialog.+ if (p.catalogName === "meta-muse-code") {+ return isMuseCredentialConfigured(museCredentialStatus()) ? "oauth" : null;+ }// OAuth wins for OAuth-capable providers when credentials exist.if (p.oauthSlug && hasOAuthCredentials(p.catalogName)) return "oauth";// Antigravity's OAuth token lives in the SHARED keychain store (populated bydiff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsindex 7ca1b5b3..645a2382 100644--- a/packages/cli/src/cli.ts+++ b/packages/cli/src/cli.ts@@ -1750,6 +1750,10 @@ async function probeModelRouting(// --probe exists to prevent.formatAdapterName = "DevinAPIFormat";declaredStreamFormat = "connect-proto";+ } else if (providerName === "meta-muse-code") {+ // `museCodeProfile`: Responses only, so --probe muse@… names that path.+ formatAdapterName = "CodexAPIFormat";+ declaredStreamFormat = "openai-responses-sse";} else {formatAdapterName = "OpenAIAPIFormat";declaredStreamFormat = "openai-sse";diff --git a/packages/cli/src/handlers/shared/remote-provider-types.ts b/packages/cli/src/handlers/shared/remote-provider-types.tsindex 19e5f37c..b537553d 100644--- a/packages/cli/src/handlers/shared/remote-provider-types.ts+++ b/packages/cli/src/handlers/shared/remote-provider-types.ts@@ -218,6 +218,11 @@ export const SUBSCRIPTION_PROVIDERS = new Set([//// Its metered sibling `opencode-zen` deliberately stays OUT."opencode-zen-go",+ // Muse Code is Meta's flat-rate plan. Its ONE credential is a key minted from+ // a Meta login, and the core signs it only after a mint confirmed+ // `is_subs_active && !require_payment` (muse-mint.ts). The metered `meta`+ // provider (META_API_KEY) stays OUT.+ "meta-muse-code",]);/**diff --git a/packages/cli/src/model-selector.ts b/packages/cli/src/model-selector.tsindex 29e0fd01..a12df7f2 100644--- a/packages/cli/src/model-selector.ts+++ b/packages/cli/src/model-selector.ts@@ -1034,6 +1034,7 @@ const PICKER_COPY: Record<string, { name?: string; description?: string }> = {"x-ai": { name: "xAI / Grok", description: "Direct API" },deepseek: { description: "Direct API" },meta: { description: "Direct API" },+ "meta-muse-code": { name: "Muse Code", description: "Meta subscription" },mistralai: { name: "Mistral", description: "Direct API" },sakana: { name: "Sakana Fugu", description: "Direct API" },"sakana-subscription": { name: "Sakana Fugu Subscription", description: "Subscription plan" },@@ -1075,6 +1076,7 @@ const PICKER_ORDER = ["x-ai","deepseek","meta",+ "meta-muse-code","mistralai","sakana","sakana-subscription",diff --git a/packages/cli/src/providers/meta-muse/muse-credentials.ts b/packages/cli/src/providers/meta-muse/muse-credentials.tsnew file mode 100644index 00000000..35edd69b--- /dev/null+++ b/packages/cli/src/providers/meta-muse/muse-credentials.ts@@ -0,0 +1,342 @@+/**+ * The Muse Code credential core: which `dca:` login signs, the minted `LLM|` key,+ * the entitlement it was confirmed with, and how both are renewed.+ *+ * ## Sources, in order (architecture §4.3)+ *+ * 1. claudish's own login, `~/.claudish/meta-muse-oauth.json`.+ * 2. claudish's borrowed copy of the Muse Code CLI's login,+ * `~/.claudish/meta-muse-borrowed.json`.+ * 3. The Muse Code CLI's Keychain item — only when the caller may prompt AND the+ * process's credential prompt role is not `never` (`prompt-role.ts`). A+ * confirmed mint from it writes the borrowed copy, so the next process,+ * including a `team` slot that may never prompt, needs no Keychain at all.+ *+ * Each source's `dca:` token is MINTED (`muse-mint.ts`), and only a mint that+ * confirmed the subscription installs state. A mint that rejects the login+ * (401/403) moves to the next source; a network or transient failure is+ * rethrown unchanged — it never falls to another source and never falls back+ * to an unconfirmed key. Each source switch is logged with the tier name, so a+ * silent account switch between the own login and a borrowed one is visible.+ *+ * ## Renewal+ *+ * - Entitlement TTL: re-mint before the next request once the confirmation is+ * older than 30 minutes (a rule, not a vendor value). It bounds a lapse of the+ * subscription in `claudish serve` and in long sessions to 30 minutes of SUB+ * labelling.+ * - A 401 from `/v1/responses` → {@link forceRefreshMuseApiKey}: the rejected+ * key is marked dead and the token re-minted (single-flight), unless the key+ * in use is already a different one (a stale failure).+ *+ * Every artifact carries `arm: "oauth"`; there is no api-key half. Nothing here+ * writes the Muse Code CLI's own Keychain item.+ */++import { credentialPromptRole } from "../../auth/credentials/prompt-role.js";+import { log } from "../../logger.js";+import {+ MUSE_KEYCHAIN_READ_DEADLINE_MS,+ museKeychainPresence,+ museKeychainPresenceCached,+ withMuseKeychainLogin,+} from "./muse-keychain.js";+import { MuseLoginExpiredError, type MuseMint, mintMuseApiKey } from "./muse-mint.js";+import { defaultMuseStoreDir, readMuseStore, writeBorrowedCopy } from "./muse-store.js";++/** Re-mint once the entitlement confirmation is older than this. */+export const MUSE_ENTITLEMENT_TTL_MS = 30 * 60_000;++export type MuseSource = "claudish-login" | "borrowed-copy" | "keychain";++export interface MuseState {+ source: MuseSource;+ accessToken: string;+ key: string;+ confirmedAt: number;+ subsTierName?: string;+ /** Bumped on every install, so a caller can tell a re-mint happened. */+ generation: number;+}++/** A terminal Muse Code credential failure with a message that names its fix. */+export class MuseCredentialError extends Error {+ readonly terminal = true;+ constructor(message: string) {+ super(message);+ this.name = "MuseCredentialError";+ }+}++export const MUSE_NO_LOGIN_MESSAGE =+ "muse@ needs a Muse Code login: run `claudish login muse` (or, in an interactive terminal, `muse login` and allow Keychain access).";+export const MUSE_NON_INTERACTIVE_MESSAGE =+ "muse@ in a team slot / MCP session needs a claudish login: run `claudish login muse`, or one interactive `claudish --model muse@<model>` and allow Keychain access.";++/** Injectable side effects, so the core is testable with no network and no Keychain. */+export interface MuseCoreDeps {+ mint: (accessToken: string) => Promise<MuseMint>;+ readStore: typeof readMuseStore;+ writeBorrowedCopy: typeof writeBorrowedCopy;+ keychainLogin: typeof withMuseKeychainLogin;+ now: () => number;+ dir: () => string;+}++const defaultDeps: MuseCoreDeps = {+ mint: (token) => mintMuseApiKey(token),+ readStore: readMuseStore,+ writeBorrowedCopy,+ keychainLogin: withMuseKeychainLogin,+ now: () => Date.now(),+ dir: defaultMuseStoreDir,+};++let deps: MuseCoreDeps = defaultDeps;+let state: MuseState | undefined;+let generation = 0;+const deadKeys = new Set<string>();+let inFlightResolve: Promise<MuseState> | null = null;+let lastFailure: string | undefined;++/** Replace the seam (`null` restores it) and forget all state. */+export function setMuseCoreTestDeps(next: Partial<MuseCoreDeps> | null): void {+ deps = next ? { ...defaultDeps, ...next } : defaultDeps;+ resetMuseCredentialState();+}++/** Forget the minted key and every in-flight resolve (after a login or logout). */+export function resetMuseCredentialState(): void {+ state = undefined;+ deadKeys.clear();+ inFlightResolve = null;+ lastFailure = undefined;+}++/** The installed state, if any. Never contains a secret that was not confirmed. */+export function currentMuseState(): MuseState | undefined {+ return state;+}++function install(source: MuseSource, accessToken: string, mint: MuseMint): MuseState {+ if (state && (state.source !== source || state.subsTierName !== mint.subsTierName)) {+ log(+ `[MuseCode] signing source ${state.source} (${state.subsTierName ?? "tier unknown"}) → ` ++ `${source} (${mint.subsTierName ?? "tier unknown"})`+ );+ } else if (!state) {+ log(`[MuseCode] signing with ${source} (${mint.subsTierName ?? "tier unknown"})`);+ }+ state = {+ source,+ accessToken,+ key: mint.apiKey,+ confirmedAt: deps.now(),+ ...(mint.subsTierName ? { subsTierName: mint.subsTierName } : {}),+ generation: ++generation,+ };+ lastFailure = undefined;+ // A mint that confirmed this key revives it: the service may hand back the+ // key it just rejected, and a dead mark on it would re-mint every request.+ deadKeys.delete(mint.apiKey);+ return state;+}++function isLoginRejection(err: unknown): boolean {+ return err instanceof MuseLoginExpiredError;+}++/** Mint from one file source. null when the source is absent or its login was rejected. */+async function tryFileSource(+ source: "claudish-login" | "borrowed-copy"+): Promise<MuseState | null> {+ const record = deps.readStore(+ source === "claudish-login" ? "own-login" : "borrowed-copy",+ deps.dir()+ );+ if (!record) return null;+ try {+ return install(source, record.access_token, await deps.mint(record.access_token));+ } catch (err) {+ if (isLoginRejection(err)) {+ log(`[MuseCode] ${source} login rejected by the key service; trying the next source`);+ return null;+ }+ throw err;+ }+}++async function resolveFromSources(prompt: boolean): Promise<MuseState> {+ const own = await tryFileSource("claudish-login");+ if (own) return own;+ const borrowed = await tryFileSource("borrowed-copy");+ if (borrowed) return borrowed;++ const role = credentialPromptRole();+ if (prompt && role !== "never") {+ const result = await deps.keychainLogin(async (accessToken) => {+ const mint = await deps.mint(accessToken);+ // Confirmed: keep a copy so a process that may never prompt can sign too.+ try {+ deps.writeBorrowedCopy(accessToken, mint.subsTierName, deps.dir());+ } catch (err) {+ log(`[MuseCode] could not write the borrowed copy: ${(err as Error).message}`);+ }+ return { accessToken, mint };+ }, MUSE_KEYCHAIN_READ_DEADLINE_MS);+ if (result.kind === "used") {+ return install(+ result.source === "borrowed-copy" ? "borrowed-copy" : "keychain",+ result.value.accessToken,+ result.value.mint+ );+ }+ if (result.kind === "timeout") {+ throw new MuseCredentialError(+ 'could not read the Muse Code login from the macOS Keychain (no answer to the access dialog); run `claudish login muse`, or retry and click "Always Allow".'+ );+ }+ if (result.kind === "failed") {+ throw new MuseCredentialError(+ `could not read the Muse Code login from the macOS Keychain (${result.detail}); run \`claudish login muse\`, or retry and click "Always Allow".`+ );+ }+ // absent / not-allowed: fall through to the no-login message.+ }+ if (role === "never") throw new MuseCredentialError(MUSE_NON_INTERACTIVE_MESSAGE);+ throw new MuseCredentialError(MUSE_NO_LOGIN_MESSAGE);+}++/**+ * A confirmed, unexpired state — resolving it when needed. Single-flight: every+ * concurrent caller shares one resolve. `prompt` permits the Keychain source+ * (the role must allow it too).+ */+export async function ensureMuseCredentialReady(opts: { prompt: boolean }): Promise<MuseState> {+ if (+ state &&+ !deadKeys.has(state.key) &&+ deps.now() - state.confirmedAt <= MUSE_ENTITLEMENT_TTL_MS+ ) {+ return state;+ }+ if (inFlightResolve) return inFlightResolve;+ const previous = state;+ inFlightResolve = (async () => {+ try {+ // A TTL re-mint first re-confirms the token already in use, so a lapse is+ // caught and a working source is not abandoned for an earlier one.+ if (previous && !deadKeys.has(previous.key)) {+ try {+ return install(+ previous.source,+ previous.accessToken,+ await deps.mint(previous.accessToken)+ );+ } catch (err) {+ if (!isLoginRejection(err)) throw err;+ }+ }+ return await resolveFromSources(opts.prompt);+ } catch (err) {+ lastFailure = (err as Error).message;+ throw err;+ } finally {+ inFlightResolve = null;+ }+ })();+ return inFlightResolve;+}++/**+ * After a 401 on a request signed with `rejectedKey`: mark it dead and re-mint,+ * unless the key in use is already a different, live one (a stale failure).+ * Throws a terminal error naming the login fix when no source works.+ */+export async function forceRefreshMuseApiKey(opts: {+ rejectedKey?: string;+ prompt: boolean;+}): Promise<MuseState> {+ if (opts.rejectedKey) deadKeys.add(opts.rejectedKey);+ if (state && opts.rejectedKey && state.key !== opts.rejectedKey && !deadKeys.has(state.key)) {+ return state;+ }+ if (state) deadKeys.add(state.key);+ try {+ return await ensureMuseCredentialReady({ prompt: opts.prompt });+ } catch (err) {+ if (err instanceof MuseCredentialError || isLoginRejection(err)) {+ throw new MuseCredentialError(+ "Meta rejected a freshly minted Muse Code key (HTTP 401): run `claudish login muse` (or `muse login`)."+ );+ }+ throw err;+ }+}++/** Whether the request path of this process may use the Keychain source. */+export function requestPathMayPrompt(): boolean {+ return credentialPromptRole() === "interactive-launch";+}++/**+ * Run a config-TUI action with the Muse login resolved IN-PROCESS first, so the+ * action's own proxy requests find it in memory and never cause a read. Errors+ * of the resolve are not thrown: the action runs and reports what it finds.+ */+export async function withInteractiveCredential<T>(action: () => Promise<T>): Promise<T> {+ try {+ await ensureMuseCredentialReady({ prompt: credentialPromptRole() !== "never" });+ } catch (err) {+ log(`[MuseCode] login not available for this action: ${(err as Error).message}`);+ }+ return action();+}++/**+ * The one cached Muse Code credential status, for sync readers (Providers tab,+ * `claudish providers --json`, `source.ts`). The two file checks are sync;+ * `keychain` comes from the async presence memo ({@link refreshMuseCredentialStatus}).+ */+export type MuseCredentialStatus =+ | "own-login"+ | "borrowed-copy"+ | "keychain"+ | "absent"+ | "failed"+ | "unknown";++export function museCredentialStatus(dir: string = deps.dir()): MuseCredentialStatus {+ if (deps.readStore("own-login", dir)) return "own-login";+ if (deps.readStore("borrowed-copy", dir)) return "borrowed-copy";+ const presence = museKeychainPresenceCached();+ if (presence === "present") return "keychain";+ if (presence === "failed") return "failed";+ if (presence === "absent") return "absent";+ return "unknown";+}++/** The status from claudish's own two files only: no Keychain question of any kind. */+export function museCredentialStatusFromFiles(dir: string = deps.dir()): MuseCredentialStatus {+ if (deps.readStore("own-login", dir)) return "own-login";+ if (deps.readStore("borrowed-copy", dir)) return "borrowed-copy";+ return "absent";+}++/** Refresh the Keychain presence memo (attributes only, no dialog), then read the status. */+export async function refreshMuseCredentialStatus(): Promise<MuseCredentialStatus> {+ if (!deps.readStore("own-login", deps.dir()) && !deps.readStore("borrowed-copy", deps.dir())) {+ await museKeychainPresence();+ }+ return museCredentialStatus();+}++/** Projection: a status that means a login is there to use. */+export function isMuseCredentialConfigured(status: MuseCredentialStatus): boolean {+ return status === "own-login" || status === "borrowed-copy" || status === "keychain";+}++/** The last resolve failure's message, for diagnostics. */+export function lastMuseCredentialFailure(): string | undefined {+ return lastFailure;+}diff --git a/packages/cli/src/providers/probe-live.ts b/packages/cli/src/providers/probe-live.tsindex f4c854cb..978c42de 100644--- a/packages/cli/src/providers/probe-live.ts+++ b/packages/cli/src/providers/probe-live.ts@@ -88,7 +88,7 @@ export interface ProbeTiming {* token-related failure, we surface a login hint instead of masking the link* as "skipped".*/-const OAUTH_PROVIDERS = new Set(["vertex", "antigravity", "devin"]);+const OAUTH_PROVIDERS = new Set(["vertex", "antigravity", "devin", "meta-muse-code"]);// Ask for a short paragraph so we can sample streaming throughput (tokens/sec).// Capped to keep probes quick while leaving room for reasoning models that// spend hidden reasoning tokens BEFORE any visible text: at 64 tokens, models@@ -335,6 +335,17 @@ function annotateOAuthHint(result: ProbeResult, provider: string, isOAuth: booleif (!isOAuth) return result;if (result.state === "live") return result;+ // Muse Code's entitlement failure: the login works but the account is not+ // subscribed. Logging in again changes nothing, so the hint is the subscribe+ // link the message names — never a login command.+ if (provider === "meta-muse-code") {+ const subscribe = /no active Muse Code subscription[^:]*: subscribe at (\S+?)\.?$/i.exec(+ result.errorMessage || ""+ );+ if (subscribe)+ return { ...result, state: "auth-failed", actionHint: `subscribe at ${subscribe[1]}` };+ }+const loginCommand =provider === "antigravity"? "claudish login antigravity"@@ -345,7 +356,9 @@ function annotateOAuthHint(result: ProbeResult, provider: string, isOAuth: boole// would send the user to a command that does not exist.provider === "devin"? "devin login"- : undefined;+ : provider === "meta-muse-code"+ ? "claudish login muse"+ : undefined;if (!loginCommand) return result;diff --git a/packages/cli/src/providers/provider-definitions.test.ts b/packages/cli/src/providers/provider-definitions.test.tsindex 690917d9..ddc30924 100644--- a/packages/cli/src/providers/provider-definitions.test.ts+++ b/packages/cli/src/providers/provider-definitions.test.ts@@ -615,6 +615,7 @@ describe("billing classification", () => {"glm-coding","grok-subscription","kimi-coding",+ "meta-muse-code","minimax-coding","opencode-zen-go","qwen-coding",diff --git a/packages/cli/src/providers/provider-definitions.ts b/packages/cli/src/providers/provider-definitions.tsindex f3e675d4..9e0ad2a9 100644--- a/packages/cli/src/providers/provider-definitions.ts+++ b/packages/cli/src/providers/provider-definitions.ts@@ -33,6 +33,7 @@ export type TransportType =| "antigravity"| "devin"| "grok-subscription"+ | "meta-muse-code"| "openrouter"| "ollamacloud"| "kimi-coding"@@ -335,6 +336,7 @@ const geminiHandler = lazyHandler((m) => m.geminiProfile);const antigravityHandler = lazyHandler((m) => m.antigravityProfile);const devinHandler = lazyHandler((m) => m.devinProfile);const grokSubscriptionHandler = lazyHandler((m) => m.grokSubscriptionProfile);+const museCodeHandler = lazyHandler((m) => m.museCodeProfile);const openaiHandler = lazyHandler((m) => m.openaiProfile);const openaiCodexHandler = lazyHandler((m) => m.openaiCodexProfile);const anthropicCompatHandler = lazyHandler((m) => m.anthropicCompatProfile);@@ -695,6 +697,37 @@ export const BUILTIN_PROVIDERS: TieredProviderDefinition[] = [description: "Grok on your SuperGrok or X Premium+ plan (gk@)",},+ // ── Muse Code (Meta subscription) ──────────────────────────────────+ // Meta's flat-rate Muse Code plan, signed with an `LLM|` key MINTED from a+ // Meta `dca:` login (claudish's own, its borrowed copy, or — interactive only —+ // the Muse Code CLI's Keychain item). The mint's entitlement answer is what+ // permits SUB billing. Wire: OpenAI Responses, `store: false`. The metered+ // Meta API on META_API_KEY is the separate `meta` provider.+ // Write-up: ai-docs/sessions/…/research/muse-wire.md (§8: mint and login).+ {+ createHandler: museCodeHandler,+ tier: "subscription",+ name: "meta-muse-code",+ displayName: "Muse Code (subscription)",+ transport: "meta-muse-code",+ tokenStrategy: "delta-aware",+ baseUrl: "https://api.meta.ai",+ baseUrlEnvVars: ["MUSE_CODE_BASE_URL"],+ apiPath: "/v1/responses",+ // MUST stay empty, as for gk@/ag@/dv@: a non-empty value makes the generic+ // loop register an api-key provider and lets proxy-server cache a minted+ // key past its life. META_API_KEY is never aliased (metered `meta`).+ apiKeyEnvVar: "",+ apiKeyDescription:+ "Muse Code login (`claudish login muse`, or `muse login` in an interactive session)",+ apiKeyUrl: "https://dev.meta.ai",+ shortcuts: ["muse"],+ shortestPrefix: "muse",+ legacyPrefixes: [],+ isDirectApi: true,+ description: "Muse Code on your Meta subscription (muse@)",+ },+// ── MiniMax (Anthropic-compatible) ─────────────────────────────────{createHandler: anthropicCompatHandler,diff --git a/packages/cli/src/providers/provider-profiles.ts b/packages/cli/src/providers/provider-profiles.tsindex 854e6e64..6b310809 100644--- a/packages/cli/src/providers/provider-profiles.ts+++ b/packages/cli/src/providers/provider-profiles.ts@@ -45,6 +45,7 @@ import { DevinProviderTransport } from "./transport/devin.js";import { GeminiProviderTransport } from "./transport/gemini-apikey.js";import { GrokSubscriptionProviderTransport } from "./transport/grok-subscription.js";import { LiteLLMProviderTransport } from "./transport/litellm.js";+import { MuseCodeTransport } from "./transport/meta-muse-code.js";import { OllamaProviderTransport } from "./transport/ollamacloud.js";import { OpenAICodexTransport } from "./transport/openai-codex.js";import { OpenAIProviderTransport } from "./transport/openai.js";@@ -219,6 +220,27 @@ export const grokSubscriptionProfile: ProviderProfile = {},};+/**+ * Muse Code subscription (`muse@`): OpenAI Responses at api.meta.ai, signed with+ * a key minted from the Muse Code login. Responses ONLY — the one API on which+ * subscription billing was verified (muse-wire.md §2) — so the adapter is the+ * Responses format and the transport adds the CLI's `store: false` body.+ * The empty api key is intentional: `MuseCodeTransport` signs per request.+ */+export const museCodeProfile: ProviderProfile = {+ createHandler(ctx) {+ const transport = new MuseCodeTransport(ctx.provider, ctx.modelName, "");+ const adapter = new CodexAPIFormat(ctx.modelName);+ const handler = new ComposedHandler(transport, ctx.targetModel, ctx.modelName, ctx.port, {+ adapter,+ tokenStrategy: "delta-aware",+ ...ctx.sharedOpts,+ });+ log(`[Proxy] Created Muse Code handler (composed): ${ctx.modelName}`);+ return handler;+ },+};+/*** OpenAI-compatible Chat Completions, for a provider the catalog does not route.* A catalog connection never reaches this profile: `buildWireHandler` builds itdiff --git a/packages/cli/src/providers/routing-hints.ts b/packages/cli/src/providers/routing-hints.tsindex eb4afc94..c4a740e4 100644--- a/packages/cli/src/providers/routing-hints.ts+++ b/packages/cli/src/providers/routing-hints.ts@@ -42,6 +42,11 @@ const PROVIDER_HINT_MAP: Record<string, ProviderHintInfo> = {"glm-coding": { apiKeyEnvVar: "GLM_CODING_API_KEY" },deepseek: { apiKeyEnvVar: "DEEPSEEK_API_KEY" },meta: { apiKeyEnvVar: "META_API_KEY" },+ // No env var: the login is minted from claudish's own Muse login or the Muse+ // Code CLI's. META_API_KEY is the metered `meta` provider and never signs muse@.+ "meta-muse-code": {+ note: "Log in with `claudish login muse`, or `muse login` in an interactive terminal and allow Keychain access",+ },mistralai: { apiKeyEnvVar: "MISTRAL_API_KEY" },sakana: { apiKeyEnvVar: "SAKANA_API_KEY" },"sakana-subscription": { apiKeyEnvVar: "SAKANA_SUBSCRIPTION_API_KEY" },diff --git a/packages/cli/src/providers/transport/meta-muse-code.ts b/packages/cli/src/providers/transport/meta-muse-code.tsnew file mode 100644index 00000000..31d9fe6a--- /dev/null+++ b/packages/cli/src/providers/transport/meta-muse-code.ts@@ -0,0 +1,80 @@+/**+ * Muse Code subscription transport: OpenAI Responses at+ * `https://api.meta.ai/v1/responses`, signed with a key minted from the Muse+ * Code login (`providers/meta-muse/muse-credentials.ts`).+ *+ * Three things differ from the OpenAI base transport:+ *+ * 1. **Auth per request, from the credential authority** (`refreshAuth`, step+ * 5b): the minted key is short-lived and re-minted on a 30-minute+ * entitlement TTL, so it cannot be a constructor argument. A failure+ * throws the core's classified error, which ComposedHandler's one+ * classifier answers (`handlers/shared/auth-failure.ts`).+ * 2. **401 → re-mint once** (`forceRefreshAuth`), with the rejected request's+ * key, so a failure that names an already-replaced key re-mints nothing.+ * 3. **The body the Muse Code CLI sends**: `store: false`, encrypted reasoning+ * included, and `reasoning.summary: "auto"` where reasoning is sent, which+ * is what Claude Code shows as thinking (muse-wire.md §2.3).+ *+ * The served context window comes from the account's dynamic models catalog,+ * memoized, with a 5-minute backoff after a miss.+ */++import { credentials } from "../../auth/credentials/authority.js";+import type { RequestAuth } from "../../auth/credentials/types.js";+import { forceRefreshMuseApiKey, requestPathMayPrompt } from "../meta-muse/muse-credentials.js";+import { discoverContextWindow } from "../model-discovery.js";+import { OpenAIProviderTransport } from "./openai.js";++const WINDOW_RETRY_MS = 5 * 60_000;++/** The bearer token of a header bag, if it carries one. */+function bearerOf(headers?: Record<string, string>): string | undefined {+ if (!headers) return undefined;+ const value = headers.Authorization ?? headers.authorization;+ return value?.startsWith("Bearer ") ? value.slice("Bearer ".length) : undefined;+}++export class MuseCodeTransport extends OpenAIProviderTransport {+ override readonly displayName = "Muse Code";+ private auth?: RequestAuth;+ private window = 0;+ private windowRetryAt = 0;++ async refreshAuth(): Promise<void> {+ this.auth = await credentials.getRequestAuth("meta-muse-code", { model: this.modelName });+ if (!this.window && Date.now() >= this.windowRetryAt) {+ this.window = (await discoverContextWindow("meta-muse-code", this.modelName)) ?? 0;+ if (!this.window) this.windowRetryAt = Date.now() + WINDOW_RETRY_MS;+ }+ }++ async getHeaders(): Promise<Record<string, string>> {+ return { ...(this.auth?.headers ?? {}), ...(this.provider.headers ?? {}) };+ }++ async forceRefreshAuth(ctx?: { rejectedHeaders?: Record<string, string> }): Promise<void> {+ await forceRefreshMuseApiKey({+ rejectedKey: bearerOf(ctx?.rejectedHeaders),+ prompt: requestPathMayPrompt(),+ });+ this.auth = await credentials.getRequestAuth("meta-muse-code", { model: this.modelName });+ }++ getContextWindow(): number {+ return this.window;+ }++ transformPayload(payload: any): any {+ const next: any = {+ ...payload,+ store: false,+ include: Array.from(new Set([...(payload?.include ?? []), "reasoning.encrypted_content"])),+ };+ const reasoning = next.reasoning;+ if (reasoning && typeof reasoning === "object" && reasoning.summary === undefined) {+ next.reasoning = { ...reasoning, summary: "auto" };+ }+ return next;+ }+}diff --git a/packages/cli/src/providers/transport/openai.ts b/packages/cli/src/providers/transport/openai.tsindex 479e46ce..02405833 100644--- a/packages/cli/src/providers/transport/openai.ts+++ b/packages/cli/src/providers/transport/openai.ts@@ -173,6 +173,7 @@ export class OpenAIProviderTransport implements ProviderTransport {if (name === "glm") return "GLM";if (name === "glm-coding") return "GLM Coding";if (name === "openai") return "OpenAI";+ if (name === "meta-muse-code") return "Muse Code";return name.charAt(0).toUpperCase() + name.slice(1);}}diff --git a/packages/cli/src/providers/wire-handler.ts b/packages/cli/src/providers/wire-handler.tsindex f5c885d9..ee6215a5 100644--- a/packages/cli/src/providers/wire-handler.ts+++ b/packages/cli/src/providers/wire-handler.ts@@ -35,6 +35,7 @@ import { getProviderByName } from "./provider-definitions.js";import type { ProfileContext } from "./provider-profiles.js";import { AnthropicProviderTransport } from "./transport/anthropic-compat.js";import { GeminiProviderTransport } from "./transport/gemini-apikey.js";+import { MuseCodeTransport } from "./transport/meta-muse-code.js";import { OpenAICodexTransport } from "./transport/openai-codex.js";import { OpenAIProviderTransport } from "./transport/openai.js";import { OpenCodeZenMessagesTransport, OpenCodeZenTransport } from "./transport/opencode-zen.js";@@ -162,6 +163,12 @@ function transportFor(if (definitionName === "openai-codex") {return new OpenAICodexTransport(ctx.provider, ctx.modelName, ctx.apiKey);}+ // Muse Code signs with a minted key, and only on Responses (the API its+ // subscription billing was verified on); `buildWireHandler` never builds it+ // on another API.+ if (definitionName === "meta-muse-code" && api === "responses") {+ return withEndpoint(new MuseCodeTransport(ctx.provider, ctx.modelName, ""), url);+ }let inner: ProviderTransport;if (api === "anthropic-messages") {const provider: RemoteProvider = OPENCODE.has(definitionName)@@ -313,6 +320,14 @@ export async function buildWireHandler(};}if (wire.status === "unknown") return tryInTurn(ctx, definitionName, connection, "wire unknown");+ if (definitionName === "meta-muse-code" && wire.api !== "responses") {+ return tryInTurn(+ ctx,+ definitionName,+ connection,+ `Muse Code is billed on responses, not ${wire.api}`+ );+ }const handler = buildKnownWireHandler(ctx, definitionName, connection, wire);return handler@@ -327,7 +342,10 @@ function tryInTurn(why: string): WireHandlerOutcome {const label = `${connection.route.routeId}/${connection.route.routeProfileId} · ${connection.externalModelId}`;- const apis = Object.keys(connection.profile.apis) as WireApi[];+ // Muse Code: Responses only, whatever else its host serves (see transportFor).+ const apis = (Object.keys(connection.profile.apis) as WireApi[]).filter(+ (api) => definitionName !== "meta-muse-code" || api === "responses"+ );if (apis.length === 0) {return { kind: "refused", message: `${label}: ${why}, and its route profile publishes no API` };}diff --git a/packages/cli/src/telemetry.ts b/packages/cli/src/telemetry.tsindex 888d74d4..9e81dc22 100644--- a/packages/cli/src/telemetry.ts+++ b/packages/cli/src/telemetry.ts@@ -64,6 +64,7 @@ const PUBLIC_PROVIDERS = new Set(["qwen-coding","qwen-payg","meta",+ "meta-muse-code",]);// ─── Module-Level State ───────────────────────────────────────────────────────diff --git a/packages/cli/src/tui/App.tsx b/packages/cli/src/tui/App.tsxindex 28cc447d..30c94433 100644--- a/packages/cli/src/tui/App.tsx+++ b/packages/cli/src/tui/App.tsx@@ -47,6 +47,7 @@ import {pingLocalProvider,pingLocalProviders,} from "../providers/local-liveness.js";+import { refreshMuseCredentialStatus } from "../providers/meta-muse/muse-credentials.js";// 1Password CONFIG persistence (sync, no SDK). Reads/writes the global +// project config files for the account / imports / environments fields.import {@@ -536,6 +537,22 @@ export function App({ requestLogin }: AppProps = {}) {};}, [keychainSupported, refreshKeychainVars, refreshConfig]);+ // The Muse Code row reads one cached status (`museCredentialStatus`): two+ // file checks plus the Keychain PRESENCE memo. Fill that memo once at mount+ // (attributes only; no item data is read) and re-derive the rows, so a+ // Keychain-only Muse login does not render as unconfigured.+ useEffect(() => {+ let cancelled = false;+ void refreshMuseCredentialStatus()+ .catch(() => undefined)+ .then(() => {+ if (!cancelled) refreshConfig();+ });+ return () => {+ cancelled = true;+ };+ }, [refreshConfig]);+// Drop the cached test badge for one provider (keyed by TUI name, as// runProbeTest stores it). Call on any credential change — save/remove key or// URL, OAuth login — so a stale FAIL / "ready Xms" doesn't outlive thediff --git a/packages/cli/src/tui/providers.ts b/packages/cli/src/tui/providers.tsindex 5ec9c0ad..57f2240c 100644--- a/packages/cli/src/tui/providers.ts+++ b/packages/cli/src/tui/providers.ts@@ -14,6 +14,11 @@ import {} from "../auth/vertex-auth.js";import { hasDevinCredentials } from "../providers/devin/devin-credentials.js";import type { LocalLiveness } from "../providers/local-liveness.js";+import {+ type MuseCredentialStatus,+ isMuseCredentialConfigured,+ museCredentialStatus,+} from "../providers/meta-muse/muse-credentials.js";import { type ProviderDefinition, getAllProviders } from "../providers/provider-definitions.js";export interface ProviderDef {@@ -191,7 +196,13 @@ export function providerAuthCapabilities(// "no auth method available" for a machine that holds a live `ya29…` token is// the wrong statement, and the `l` keybinding stays gated on `oauthSlug` so no// `claudish login vertex` is advertised.- const oauthSupported = !!p.oauthSlug || p.catalogName === "devin" || p.catalogName === "vertex";+ // Muse Code: statically supported, so the login guidance shows before the+ // first login; its presence drives only "set" (architecture §6).+ const oauthSupported =+ !!p.oauthSlug ||+ p.catalogName === "devin" ||+ p.catalogName === "vertex" ||+ p.catalogName === "meta-muse-code";// Antigravity's OAuth token is in the shared keychain, not an oauth-file — so// hasOAuthCredentials can't see it; check the keychain directly (memoized).const oauthSet =@@ -199,7 +210,8 @@ export function providerAuthCapabilities((hasOAuthCredentials(p.catalogName) ||(p.catalogName === "antigravity" && hasSharedAntigravityToken()) ||(p.catalogName === "devin" && hasDevinCredentials()) ||- (p.catalogName === "vertex" && hasVertexAdcCredentials()));+ (p.catalogName === "vertex" && hasVertexAdcCredentials()) ||+ (p.catalogName === "meta-muse-code" && isMuseCredentialConfigured(museCredentialStatus())));return {apiKey: { supported: apiKeySupported, set: apiKeySet },oauth: { supported: oauthSupported, set: oauthSet },@@ -220,7 +232,18 @@ export function providerAuthCapabilities(* Sync and free of subprocesses (see `peekVertexProjectOrigin`), so it is safe* on a render path.*/+/** What the Muse Code row says about its login, by the one cached status. */+const MUSE_STATUS_NOTE: Record<MuseCredentialStatus, string> = {+ "own-login": "Signed in with claudish's own Muse Code login",+ "borrowed-copy": "Using claudish's copy of the Muse Code CLI login",+ keychain: "Muse Code CLI login found in the Keychain — first use asks for access",+ absent: "No Muse Code login — run `claudish login muse`, or `muse login`",+ failed: "The Keychain could not be asked about the Muse Code login",+ unknown: "Checking for a Muse Code login…",+};+export function providerCredentialNote(p: ProviderDef): string | undefined {+ if (p.catalogName === "meta-muse-code") return MUSE_STATUS_NOTE[museCredentialStatus()];if (p.catalogName !== "vertex") return undefined;const origin = peekVertexProjectOrigin();if (!origin) {