feat: update token auth flow

This commit is contained in:
Peter Steinberger
2026-01-09 08:12:48 +01:00
parent a4d6638f89
commit 77d4bb8dfe
7 changed files with 145 additions and 160 deletions

View File

@@ -71,7 +71,7 @@ Tip: `--json` does **not** imply non-interactive mode. Use `--non-interactive` (
2) **Model/Auth**
- **Anthropic OAuth (Claude CLI)**: on macOS the wizard checks Keychain item "Claude Code-credentials" (choose "Always Allow" so launchd starts don't block); on Linux/Windows it reuses `~/.claude/.credentials.json` if present.
- **Anthropic OAuth (recommended)**: browser flow; paste the `code#state`.
- **Anthropic token (paste setup-token)**: run `claude setup-token` in your terminal, then paste the token (you can name it; blank = default).
- **OpenAI Codex OAuth (Codex CLI)**: if `~/.codex/auth.json` exists, the wizard can reuse it.
- **OpenAI Codex OAuth**: browser flow; paste the `code#state`.
- Sets `agent.model` to `openai-codex/gpt-5.2` when model is unset or `openai/*`.

View File

@@ -38,10 +38,9 @@ describe("buildAuthChoiceOptions", () => {
version: 1,
profiles: {
[CLAUDE_CLI_PROFILE_ID]: {
type: "oauth",
type: "token",
provider: "anthropic",
access: "token",
refresh: "refresh",
token: "token",
expires: Date.now() + 60 * 60 * 1000,
},
},

View File

@@ -76,9 +76,9 @@ export function buildAuthChoiceOptions(params: {
}
options.push({
value: "oauth",
label: "Anthropic token (setup-token)",
hint: "Runs `claude setup-token`",
value: "token",
label: "Anthropic token (paste setup-token)",
hint: "Run `claude setup-token`, then paste the token",
});
options.push({
@@ -91,11 +91,7 @@ export function buildAuthChoiceOptions(params: {
});
options.push({ value: "gemini-api-key", label: "Google Gemini API key" });
options.push({ value: "apiKey", label: "Anthropic API key" });
options.push({
value: "token",
label: "Paste token (advanced)",
hint: "Stores as a non-refreshable token profile",
});
// Token flow is currently Anthropic-only; use CLI for advanced providers.
options.push({ value: "minimax", label: "Minimax M2.1 (LM Studio)" });
if (params.includeSkip) {
options.push({ value: "skip", label: "Skip for now" });

View File

@@ -17,10 +17,7 @@ import {
resolveEnvApiKey,
} from "../agents/model-auth.js";
import { loadModelCatalog } from "../agents/model-catalog.js";
import {
normalizeProviderId,
resolveConfiguredModelRef,
} from "../agents/model-selection.js";
import { resolveConfiguredModelRef } from "../agents/model-selection.js";
import { parseDurationMs } from "../cli/parse-duration.js";
import type { ClawdbotConfig } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js";
@@ -29,6 +26,10 @@ import {
isRemoteEnvironment,
loginAntigravityVpsAware,
} from "./antigravity-oauth.js";
import {
buildTokenProfileId,
validateAnthropicSetupToken,
} from "./auth-token.js";
import {
applyGoogleGeminiModelDefault,
GOOGLE_GEMINI_DEFAULT_MODEL,
@@ -136,65 +137,7 @@ export async function applyAuthChoice(params: {
);
};
if (params.authChoice === "oauth") {
await params.prompter.note(
[
"This will run `claude setup-token` to create a long-lived Anthropic token.",
"Requires an interactive TTY and a Claude Pro/Max subscription.",
].join("\n"),
"Anthropic token",
);
if (!process.stdin.isTTY) {
await params.prompter.note(
"`claude setup-token` requires an interactive TTY.",
"Anthropic token",
);
return { config: nextConfig, agentModelOverride };
}
const proceed = await params.prompter.confirm({
message: "Run `claude setup-token` now?",
initialValue: true,
});
if (!proceed) return { config: nextConfig, agentModelOverride };
const res = await (async () => {
const { spawnSync } = await import("node:child_process");
return spawnSync("claude", ["setup-token"], { stdio: "inherit" });
})();
if (res.error) {
await params.prompter.note(
`Failed to run claude: ${String(res.error)}`,
"Anthropic token",
);
return { config: nextConfig, agentModelOverride };
}
if (typeof res.status === "number" && res.status !== 0) {
await params.prompter.note(
`claude setup-token failed (exit ${res.status})`,
"Anthropic token",
);
return { config: nextConfig, agentModelOverride };
}
const store = ensureAuthProfileStore(params.agentDir, {
allowKeychainPrompt: true,
});
if (!store.profiles[CLAUDE_CLI_PROFILE_ID]) {
await params.prompter.note(
`No Claude CLI credentials found after setup-token. Expected ${CLAUDE_CLI_PROFILE_ID}.`,
"Anthropic token",
);
return { config: nextConfig, agentModelOverride };
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: CLAUDE_CLI_PROFILE_ID,
provider: "anthropic",
mode: "token",
});
} else if (params.authChoice === "claude-cli") {
if (params.authChoice === "claude-cli") {
const store = ensureAuthProfileStore(params.agentDir, {
allowKeychainPrompt: false,
});
@@ -266,24 +209,50 @@ export async function applyAuthChoice(params: {
provider: "anthropic",
mode: "token",
});
} else if (params.authChoice === "token") {
const providerRaw = await params.prompter.text({
message: "Token provider id (e.g. anthropic)",
validate: (value) => (value?.trim() ? undefined : "Required"),
} else if (params.authChoice === "token" || params.authChoice === "oauth") {
const profileNameRaw = await params.prompter.text({
message: "Token name (blank = default)",
placeholder: "default",
});
const provider = (await params.prompter.select({
message: "Token provider",
options: [{ value: "anthropic", label: "Anthropic (only supported)" }],
})) as "anthropic";
const profileId = buildTokenProfileId({
provider,
name: String(profileNameRaw ?? ""),
});
const provider = normalizeProviderId(String(providerRaw).trim());
const defaultProfileId = `${provider}:manual`;
const profileIdRaw = await params.prompter.text({
message: "Auth profile id",
initialValue: defaultProfileId,
validate: (value) => (value?.trim() ? undefined : "Required"),
const store = ensureAuthProfileStore(params.agentDir, {
allowKeychainPrompt: false,
});
const profileId = String(profileIdRaw).trim();
const existing = store.profiles[profileId];
if (existing?.type === "token") {
const useExisting = await params.prompter.confirm({
message: `Use existing token "${profileId}"?`,
initialValue: true,
});
if (useExisting) {
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId,
provider,
mode: "token",
});
return { config: nextConfig, agentModelOverride };
}
}
await params.prompter.note(
[
"Run `claude setup-token` in your terminal.",
"Then paste the generated token below.",
].join("\n"),
"Anthropic token",
);
const tokenRaw = await params.prompter.text({
message: `Paste token for ${provider}`,
validate: (value) => (value?.trim() ? undefined : "Required"),
message: "Paste Anthropic setup-token",
validate: (value) => validateAnthropicSetupToken(String(value ?? "")),
});
const token = String(tokenRaw).trim();

View File

@@ -0,0 +1,37 @@
import { normalizeProviderId } from "../agents/model-selection.js";
export const ANTHROPIC_SETUP_TOKEN_PREFIX = "sk-ant-oat01-";
export const ANTHROPIC_SETUP_TOKEN_MIN_LENGTH = 80;
export const DEFAULT_TOKEN_PROFILE_NAME = "default";
export function normalizeTokenProfileName(raw: string): string {
const trimmed = raw.trim();
if (!trimmed) return DEFAULT_TOKEN_PROFILE_NAME;
const slug = trimmed
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "");
return slug || DEFAULT_TOKEN_PROFILE_NAME;
}
export function buildTokenProfileId(params: {
provider: string;
name: string;
}): string {
const provider = normalizeProviderId(params.provider);
const name = normalizeTokenProfileName(params.name);
return `${provider}:${name}`;
}
export function validateAnthropicSetupToken(raw: string): string | undefined {
const trimmed = raw.trim();
if (!trimmed) return "Required";
if (!trimmed.startsWith(ANTHROPIC_SETUP_TOKEN_PREFIX)) {
return `Expected token starting with ${ANTHROPIC_SETUP_TOKEN_PREFIX}`;
}
if (trimmed.length < ANTHROPIC_SETUP_TOKEN_MIN_LENGTH) {
return "Token looks too short; paste the full setup-token";
}
return undefined;
}

View File

@@ -21,7 +21,6 @@ import {
ensureAuthProfileStore,
upsertAuthProfile,
} from "../agents/auth-profiles.js";
import { normalizeProviderId } from "../agents/model-selection.js";
import { parseDurationMs } from "../cli/parse-duration.js";
import { createCliProgress } from "../cli/progress.js";
import type { ClawdbotConfig } from "../config/config.js";
@@ -47,6 +46,10 @@ import {
loginAntigravityVpsAware,
} from "./antigravity-oauth.js";
import { buildAuthChoiceOptions } from "./auth-choice-options.js";
import {
buildTokenProfileId,
validateAnthropicSetupToken,
} from "./auth-token.js";
import {
DEFAULT_GATEWAY_DAEMON_RUNTIME,
GATEWAY_DAEMON_RUNTIME_OPTIONS,
@@ -315,62 +318,7 @@ async function promptAuthConfig(
let next = cfg;
if (authChoice === "oauth") {
note(
[
"This will run `claude setup-token` to create a long-lived Anthropic token.",
"Requires an interactive TTY and a Claude Pro/Max subscription.",
].join("\n"),
"Anthropic token",
);
if (!process.stdin.isTTY) {
note(
"`claude setup-token` requires an interactive TTY.",
"Anthropic token",
);
return next;
}
const proceed = guardCancel(
await confirm({
message: "Run `claude setup-token` now?",
initialValue: true,
}),
runtime,
);
if (!proceed) return next;
const res = await (async () => {
const { spawnSync } = await import("node:child_process");
return spawnSync("claude", ["setup-token"], { stdio: "inherit" });
})();
if (res.error) {
note(`Failed to run claude: ${String(res.error)}`, "Anthropic token");
return next;
}
if (typeof res.status === "number" && res.status !== 0) {
note(`claude setup-token failed (exit ${res.status})`, "Anthropic token");
return next;
}
const store = ensureAuthProfileStore(undefined, {
allowKeychainPrompt: true,
});
if (!store.profiles[CLAUDE_CLI_PROFILE_ID]) {
note(
`No Claude CLI credentials found after setup-token. Expected ${CLAUDE_CLI_PROFILE_ID}.`,
"Anthropic token",
);
return next;
}
next = applyAuthProfileConfig(next, {
profileId: CLAUDE_CLI_PROFILE_ID,
provider: "anthropic",
mode: "token",
});
} else if (authChoice === "claude-cli") {
if (authChoice === "claude-cli") {
const store = ensureAuthProfileStore(undefined, {
allowKeychainPrompt: false,
});
@@ -407,30 +355,66 @@ async function promptAuthConfig(
provider: "anthropic",
mode: "token",
});
} else if (authChoice === "token") {
const providerRaw = guardCancel(
} else if (authChoice === "token" || authChoice === "oauth") {
const profileNameRaw = guardCancel(
await text({
message: "Token provider id (e.g. anthropic)",
validate: (value) => (value?.trim() ? undefined : "Required"),
message: "Token name (blank = default)",
placeholder: "default",
}),
runtime,
);
const provider = normalizeProviderId(String(providerRaw).trim());
const defaultProfileId = `${provider}:manual`;
const profileIdRaw = guardCancel(
await text({
message: "Auth profile id",
initialValue: defaultProfileId,
validate: (value) => (value?.trim() ? undefined : "Required"),
const provider = guardCancel(
await select({
message: "Token provider",
options: [
{
value: "anthropic",
label: "Anthropic (only supported)",
},
],
}),
runtime,
) as "anthropic";
const profileId = buildTokenProfileId({
provider,
name: String(profileNameRaw ?? ""),
});
const store = ensureAuthProfileStore(undefined, {
allowKeychainPrompt: false,
});
const existing = store.profiles[profileId];
if (existing?.type === "token") {
const useExisting = guardCancel(
await confirm({
message: `Use existing token "${profileId}"?`,
initialValue: true,
}),
runtime,
);
if (useExisting) {
next = applyAuthProfileConfig(next, {
profileId,
provider,
mode: "token",
});
return next;
}
}
note(
[
"Run `claude setup-token` in your terminal.",
"Then paste the generated token below.",
].join("\n"),
"Anthropic token",
);
const profileId = String(profileIdRaw).trim();
const tokenRaw = guardCancel(
await text({
message: `Paste token for ${provider}`,
validate: (value) => (value?.trim() ? undefined : "Required"),
message: "Paste Anthropic setup-token",
validate: (value) => validateAnthropicSetupToken(String(value ?? "")),
}),
runtime,
);

View File

@@ -2,13 +2,13 @@ import type { CliDeps } from "../cli/deps.js";
import { withProgress } from "../cli/progress.js";
import { loadConfig } from "../config/config.js";
import { success } from "../globals.js";
import type { OutboundDeliveryResult } from "../infra/outbound/deliver.js";
import { buildOutboundResultEnvelope } from "../infra/outbound/envelope.js";
import {
buildOutboundDeliveryJson,
formatGatewaySummary,
formatOutboundDeliverySummary,
} from "../infra/outbound/format.js";
import type { OutboundDeliveryResult } from "../infra/outbound/deliver.js";
import {
type MessagePollResult,
type MessageSendResult,