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

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/cli/ai/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
AI_PROVIDER_PRIORITY,
DEFAULT_AI_PROVIDER,
getAiProviderDefinition,
hasInlineWpcomAuth,
type AiProviderId,
} from 'cli/ai/providers';
import { readCliConfig, updateCliConfigWithPartial } from 'cli/lib/cli-config/core';
Expand Down Expand Up @@ -49,6 +50,10 @@ export async function resolveUnavailableAiProvider(
}

export async function resolveInitialAiProvider(): Promise< AiProviderId > {
if ( hasInlineWpcomAuth() ) {
return 'wpcom';
}

const { aiProvider: savedProvider } = await readCliConfig();
if ( savedProvider ) {
const definition = getAiProviderDefinition( savedProvider );
Expand Down
19 changes: 14 additions & 5 deletions apps/cli/ai/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,14 @@ async function hasValidWpcomAuth(): Promise< boolean > {
return token !== null;
}

function readInlineWpcomToken(): string | null {
return process.env.STUDIO_WPCOM_TOKEN?.trim() || null;
}

export function hasInlineWpcomAuth(): boolean {
return readInlineWpcomToken() !== null;
}

function createBaseEnvironment(): Record< string, string > {
const env = { ...( process.env as Record< string, string > ) };

Expand All @@ -88,22 +96,23 @@ const AI_PROVIDER_DEFINITIONS: Record< AiProviderId, AiProviderDefinition > = {
id: 'wpcom',
autoFallbackWhenUnavailable: true,
isVisible: async () => true,
isReady: hasValidWpcomAuth,
isReady: async () => hasInlineWpcomAuth() || ( await hasValidWpcomAuth() ),
prepare: async () => {
if ( await hasValidWpcomAuth() ) {
if ( hasInlineWpcomAuth() || ( await hasValidWpcomAuth() ) ) {
return;
}

throw new LoggerError( __( 'WordPress.com login required. Use /login to authenticate.' ) );
},
resolveEnv: async () => {
const token = await readAuthToken();
if ( ! token ) {
const inlineToken = readInlineWpcomToken();
const accessToken = inlineToken ?? ( await readAuthToken() )?.accessToken;
if ( ! accessToken ) {
throw new LoggerError( __( 'WordPress.com login required. Use /login to authenticate.' ) );
}
const env = createBaseEnvironment();
env.ANTHROPIC_BASE_URL = getWpcomAiGatewayBaseUrl();
env.ANTHROPIC_AUTH_TOKEN = token.accessToken;
env.ANTHROPIC_AUTH_TOKEN = accessToken;
env.ANTHROPIC_CUSTOM_HEADERS = buildAnthropicCustomHeaders( {
'X-WPCOM-AI-Feature': WPCOM_AI_FEATURE_HEADER,
} );
Expand Down
Loading