Vendor Codex and land Phase 1 Epiphany state slice
This commit is contained in:
parent
130e074c69
commit
2042687e30
3959 changed files with 953751 additions and 7 deletions
211
vendor/codex/codex-rs/model-provider/src/amazon_bedrock/auth.rs
vendored
Normal file
211
vendor/codex/codex-rs/model-provider/src/amazon_bedrock/auth.rs
vendored
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use codex_api::AuthError;
|
||||
use codex_api::AuthProvider;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_aws_auth::AwsAuthContext;
|
||||
use codex_aws_auth::AwsAuthError;
|
||||
use codex_aws_auth::AwsRequestToSign;
|
||||
use codex_client::Request;
|
||||
use codex_client::RequestBody;
|
||||
use codex_client::RequestCompression;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result;
|
||||
use http::HeaderMap;
|
||||
|
||||
use crate::BearerAuthProvider;
|
||||
|
||||
use super::mantle::aws_auth_config;
|
||||
use super::mantle::region_from_config;
|
||||
|
||||
const AWS_BEARER_TOKEN_BEDROCK_ENV_VAR: &str = "AWS_BEARER_TOKEN_BEDROCK";
|
||||
const LEGACY_SESSION_ID_HEADER: &str = "session_id";
|
||||
|
||||
enum BedrockAuthMethod {
|
||||
EnvBearerToken { token: String, region: String },
|
||||
AwsSdkAuth { context: AwsAuthContext },
|
||||
}
|
||||
|
||||
async fn resolve_auth_method(aws: &ModelProviderAwsAuthInfo) -> Result<BedrockAuthMethod> {
|
||||
if let Some(token) = bearer_token_from_env() {
|
||||
let region = bearer_token_region_from_config(aws)?;
|
||||
return Ok(BedrockAuthMethod::EnvBearerToken { token, region });
|
||||
}
|
||||
|
||||
let config = aws_auth_config(aws);
|
||||
let context = AwsAuthContext::load(config)
|
||||
.await
|
||||
.map_err(aws_auth_error_to_codex_error)?;
|
||||
Ok(BedrockAuthMethod::AwsSdkAuth { context })
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_provider_auth(
|
||||
aws: &ModelProviderAwsAuthInfo,
|
||||
) -> Result<SharedAuthProvider> {
|
||||
match resolve_auth_method(aws).await? {
|
||||
BedrockAuthMethod::EnvBearerToken { token, .. } => Ok(Arc::new(BearerAuthProvider {
|
||||
token: Some(token),
|
||||
account_id: None,
|
||||
is_fedramp_account: false,
|
||||
})),
|
||||
BedrockAuthMethod::AwsSdkAuth { context } => {
|
||||
Ok(Arc::new(BedrockMantleSigV4AuthProvider::new(context)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_region(aws: &ModelProviderAwsAuthInfo) -> Result<String> {
|
||||
match resolve_auth_method(aws).await? {
|
||||
BedrockAuthMethod::EnvBearerToken { region, .. } => Ok(region),
|
||||
BedrockAuthMethod::AwsSdkAuth { context, .. } => Ok(context.region().to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn bearer_token_from_env() -> Option<String> {
|
||||
std::env::var(AWS_BEARER_TOKEN_BEDROCK_ENV_VAR)
|
||||
.ok()
|
||||
.map(|token| token.trim().to_string())
|
||||
.filter(|token| !token.is_empty())
|
||||
}
|
||||
|
||||
fn bearer_token_region_from_config(aws: &ModelProviderAwsAuthInfo) -> Result<String> {
|
||||
region_from_config(aws).ok_or_else(|| {
|
||||
CodexErr::Fatal(
|
||||
"Amazon Bedrock bearer token auth requires \
|
||||
`model_providers.amazon-bedrock.aws.region`"
|
||||
.to_string(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn aws_auth_error_to_codex_error(error: AwsAuthError) -> CodexErr {
|
||||
CodexErr::Fatal(format!("failed to resolve Amazon Bedrock auth: {error}"))
|
||||
}
|
||||
|
||||
fn aws_auth_error_to_auth_error(error: AwsAuthError) -> AuthError {
|
||||
if error.is_retryable() {
|
||||
AuthError::Transient(error.to_string())
|
||||
} else {
|
||||
AuthError::Build(error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_headers_not_preserved_by_bedrock_mantle(headers: &mut HeaderMap) {
|
||||
// The Bedrock Mantle front door does not preserve this legacy OpenAI header
|
||||
// for SigV4 verification. Signing it makes the richer Codex agent request
|
||||
// fail even though raw Responses requests work.
|
||||
headers.remove(LEGACY_SESSION_ID_HEADER);
|
||||
}
|
||||
|
||||
/// AWS SigV4 auth provider for Bedrock Mantle OpenAI-compatible requests.
|
||||
#[derive(Debug)]
|
||||
struct BedrockMantleSigV4AuthProvider {
|
||||
context: AwsAuthContext,
|
||||
}
|
||||
|
||||
impl BedrockMantleSigV4AuthProvider {
|
||||
fn new(context: AwsAuthContext) -> Self {
|
||||
Self { context }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl AuthProvider for BedrockMantleSigV4AuthProvider {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) {}
|
||||
|
||||
async fn apply_auth(&self, request: Request) -> std::result::Result<Request, AuthError> {
|
||||
let mut request = request;
|
||||
remove_headers_not_preserved_by_bedrock_mantle(&mut request.headers);
|
||||
let prepared = request.prepare_body_for_send().map_err(AuthError::Build)?;
|
||||
let signed = self
|
||||
.context
|
||||
.sign(AwsRequestToSign {
|
||||
method: request.method.clone(),
|
||||
url: request.url.clone(),
|
||||
headers: prepared.headers.clone(),
|
||||
body: prepared.body_bytes(),
|
||||
})
|
||||
.await
|
||||
.map_err(aws_auth_error_to_auth_error)?;
|
||||
|
||||
request.url = signed.url;
|
||||
request.headers = signed.headers;
|
||||
request.body = prepared.body.map(RequestBody::Raw);
|
||||
request.compression = RequestCompression::None;
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use codex_api::AuthProvider;
|
||||
use http::HeaderValue;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bedrock_bearer_auth_uses_configured_region_and_header() {
|
||||
let token = "bedrock-api-key-test".to_string();
|
||||
let region = bearer_token_region_from_config(&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some(" us-west-2 ".to_string()),
|
||||
})
|
||||
.expect("configured region should resolve");
|
||||
let provider = BearerAuthProvider {
|
||||
token: Some(token),
|
||||
account_id: None,
|
||||
is_fedramp_account: false,
|
||||
};
|
||||
let mut headers = http::HeaderMap::new();
|
||||
|
||||
provider.add_auth_headers(&mut headers);
|
||||
|
||||
assert_eq!(region, "us-west-2");
|
||||
assert!(
|
||||
headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(|value| value.starts_with("Bearer bedrock-api-key-"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bedrock_bearer_auth_rejects_missing_configured_region() {
|
||||
let err = bearer_token_region_from_config(&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: None,
|
||||
})
|
||||
.expect_err("missing region should fail");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"Fatal error: Amazon Bedrock bearer token auth requires \
|
||||
`model_providers.amazon-bedrock.aws.region`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bedrock_mantle_sigv4_strips_legacy_session_id_header() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
LEGACY_SESSION_ID_HEADER,
|
||||
HeaderValue::from_static("019dae79-15c3-70c3-8736-3219b8602b37"),
|
||||
);
|
||||
headers.insert(
|
||||
"x-client-request-id",
|
||||
HeaderValue::from_static("request-id"),
|
||||
);
|
||||
|
||||
remove_headers_not_preserved_by_bedrock_mantle(&mut headers);
|
||||
|
||||
assert!(!headers.contains_key(LEGACY_SESSION_ID_HEADER));
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("x-client-request-id")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("request-id")
|
||||
);
|
||||
}
|
||||
}
|
||||
101
vendor/codex/codex-rs/model-provider/src/amazon_bedrock/mantle.rs
vendored
Normal file
101
vendor/codex/codex-rs/model-provider/src/amazon_bedrock/mantle.rs
vendored
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
use codex_aws_auth::AwsAuthConfig;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result;
|
||||
|
||||
const BEDROCK_MANTLE_SERVICE_NAME: &str = "bedrock-mantle";
|
||||
const BEDROCK_MANTLE_SUPPORTED_REGIONS: [&str; 12] = [
|
||||
"us-east-2",
|
||||
"us-east-1",
|
||||
"us-west-2",
|
||||
"ap-southeast-3",
|
||||
"ap-south-1",
|
||||
"ap-northeast-1",
|
||||
"eu-central-1",
|
||||
"eu-west-1",
|
||||
"eu-west-2",
|
||||
"eu-south-1",
|
||||
"eu-north-1",
|
||||
"sa-east-1",
|
||||
];
|
||||
|
||||
pub(super) fn aws_auth_config(aws: &ModelProviderAwsAuthInfo) -> AwsAuthConfig {
|
||||
AwsAuthConfig {
|
||||
profile: aws.profile.clone(),
|
||||
region: region_from_config(aws),
|
||||
service: BEDROCK_MANTLE_SERVICE_NAME.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn region_from_config(aws: &ModelProviderAwsAuthInfo) -> Option<String> {
|
||||
aws.region
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|region| !region.is_empty())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
pub(super) fn base_url(region: &str) -> Result<String> {
|
||||
if BEDROCK_MANTLE_SUPPORTED_REGIONS.contains(®ion) {
|
||||
Ok(format!("https://bedrock-mantle.{region}.api.aws/v1"))
|
||||
} else {
|
||||
Err(CodexErr::Fatal(format!(
|
||||
"Amazon Bedrock Mantle does not support region `{region}`"
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn base_url_uses_region_endpoint() {
|
||||
assert_eq!(
|
||||
base_url("ap-northeast-1").expect("supported region"),
|
||||
"https://bedrock-mantle.ap-northeast-1.api.aws/v1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_url_rejects_unsupported_region() {
|
||||
let err = base_url("us-west-1").expect_err("unsupported region");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"Fatal error: Amazon Bedrock Mantle does not support region `us-west-1`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aws_auth_config_uses_profile_and_mantle_service() {
|
||||
assert_eq!(
|
||||
aws_auth_config(&ModelProviderAwsAuthInfo {
|
||||
profile: Some("codex-bedrock".to_string()),
|
||||
region: None,
|
||||
}),
|
||||
AwsAuthConfig {
|
||||
profile: Some("codex-bedrock".to_string()),
|
||||
region: None,
|
||||
service: "bedrock-mantle".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aws_auth_config_uses_configured_region() {
|
||||
assert_eq!(
|
||||
aws_auth_config(&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some(" us-west-2 ".to_string()),
|
||||
}),
|
||||
AwsAuthConfig {
|
||||
profile: None,
|
||||
region: Some("us-west-2".to_string()),
|
||||
service: "bedrock-mantle".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
73
vendor/codex/codex-rs/model-provider/src/amazon_bedrock/mod.rs
vendored
Normal file
73
vendor/codex/codex-rs/model-provider/src/amazon_bedrock/mod.rs
vendored
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
mod auth;
|
||||
mod mantle;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_api::Provider;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::Result;
|
||||
|
||||
use crate::provider::ModelProvider;
|
||||
use auth::resolve_provider_auth;
|
||||
use auth::resolve_region;
|
||||
use mantle::base_url;
|
||||
|
||||
/// Runtime provider for Amazon Bedrock's OpenAI-compatible Mantle endpoint.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct AmazonBedrockModelProvider {
|
||||
pub(crate) info: ModelProviderInfo,
|
||||
pub(crate) aws: ModelProviderAwsAuthInfo,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ModelProvider for AmazonBedrockModelProvider {
|
||||
fn info(&self) -> &ModelProviderInfo {
|
||||
&self.info
|
||||
}
|
||||
|
||||
fn auth_manager(&self) -> Option<Arc<AuthManager>> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn auth(&self) -> Option<CodexAuth> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn api_provider(&self) -> Result<Provider> {
|
||||
let region = resolve_region(&self.aws).await?;
|
||||
let mut api_provider_info = self.info.clone();
|
||||
api_provider_info.base_url = Some(base_url(®ion)?);
|
||||
api_provider_info.to_api_provider(/*auth_mode*/ None)
|
||||
}
|
||||
|
||||
async fn api_auth(&self) -> Result<SharedAuthProvider> {
|
||||
resolve_provider_auth(&self.aws).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn api_provider_for_bedrock_bearer_token_uses_configured_region_endpoint() {
|
||||
let region = "eu-central-1";
|
||||
let mut api_provider_info =
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None);
|
||||
api_provider_info.base_url = Some(base_url(region).expect("supported region"));
|
||||
let api_provider = api_provider_info
|
||||
.to_api_provider(/*auth_mode*/ None)
|
||||
.expect("api provider should build");
|
||||
|
||||
assert_eq!(
|
||||
api_provider.base_url,
|
||||
"https://bedrock-mantle.eu-central-1.api.aws/v1"
|
||||
);
|
||||
}
|
||||
}
|
||||
64
vendor/codex/codex-rs/model-provider/src/auth.rs
vendored
Normal file
64
vendor/codex/codex-rs/model-provider/src/auth.rs
vendored
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
|
||||
use crate::bearer_auth_provider::BearerAuthProvider;
|
||||
|
||||
/// Returns the provider-scoped auth manager when this provider uses command-backed auth.
|
||||
///
|
||||
/// Providers without custom auth continue using the caller-supplied base manager, when present.
|
||||
pub(crate) fn auth_manager_for_provider(
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
provider: &ModelProviderInfo,
|
||||
) -> Option<Arc<AuthManager>> {
|
||||
match provider.auth.clone() {
|
||||
Some(config) => Some(AuthManager::external_bearer_only(config)),
|
||||
None => auth_manager,
|
||||
}
|
||||
}
|
||||
|
||||
fn bearer_auth_provider_from_auth(
|
||||
auth: Option<&CodexAuth>,
|
||||
provider: &ModelProviderInfo,
|
||||
) -> codex_protocol::error::Result<BearerAuthProvider> {
|
||||
if let Some(api_key) = provider.api_key()? {
|
||||
return Ok(BearerAuthProvider {
|
||||
token: Some(api_key),
|
||||
account_id: None,
|
||||
is_fedramp_account: false,
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(token) = provider.experimental_bearer_token.clone() {
|
||||
return Ok(BearerAuthProvider {
|
||||
token: Some(token),
|
||||
account_id: None,
|
||||
is_fedramp_account: false,
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(auth) = auth {
|
||||
let token = auth.get_token()?;
|
||||
Ok(BearerAuthProvider {
|
||||
token: Some(token),
|
||||
account_id: auth.get_account_id(),
|
||||
is_fedramp_account: auth.is_fedramp_account(),
|
||||
})
|
||||
} else {
|
||||
Ok(BearerAuthProvider {
|
||||
token: None,
|
||||
account_id: None,
|
||||
is_fedramp_account: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_provider_auth(
|
||||
auth: Option<&CodexAuth>,
|
||||
provider: &ModelProviderInfo,
|
||||
) -> codex_protocol::error::Result<SharedAuthProvider> {
|
||||
Ok(Arc::new(bearer_auth_provider_from_auth(auth, provider)?))
|
||||
}
|
||||
102
vendor/codex/codex-rs/model-provider/src/bearer_auth_provider.rs
vendored
Normal file
102
vendor/codex/codex-rs/model-provider/src/bearer_auth_provider.rs
vendored
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
use codex_api::AuthProvider;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
|
||||
/// Bearer-token auth provider for OpenAI-compatible model-provider requests.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct BearerAuthProvider {
|
||||
pub token: Option<String>,
|
||||
pub account_id: Option<String>,
|
||||
pub is_fedramp_account: bool,
|
||||
}
|
||||
|
||||
impl BearerAuthProvider {
|
||||
pub fn for_test(token: Option<&str>, account_id: Option<&str>) -> Self {
|
||||
Self {
|
||||
token: token.map(str::to_string),
|
||||
account_id: account_id.map(str::to_string),
|
||||
is_fedramp_account: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthProvider for BearerAuthProvider {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) {
|
||||
if let Some(token) = self.token.as_ref()
|
||||
&& let Ok(header) = HeaderValue::from_str(&format!("Bearer {token}"))
|
||||
{
|
||||
let _ = headers.insert(http::header::AUTHORIZATION, header);
|
||||
}
|
||||
if let Some(account_id) = self.account_id.as_ref()
|
||||
&& let Ok(header) = HeaderValue::from_str(account_id)
|
||||
{
|
||||
let _ = headers.insert("ChatGPT-Account-ID", header);
|
||||
}
|
||||
if self.is_fedramp_account {
|
||||
let _ = headers.insert("X-OpenAI-Fedramp", HeaderValue::from_static("true"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn bearer_auth_provider_reports_when_auth_header_will_attach() {
|
||||
let auth = BearerAuthProvider {
|
||||
token: Some("access-token".to_string()),
|
||||
account_id: None,
|
||||
is_fedramp_account: false,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
codex_api::auth_header_telemetry(&auth),
|
||||
codex_api::AuthHeaderTelemetry {
|
||||
attached: true,
|
||||
name: Some("authorization"),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_auth_provider_adds_auth_headers() {
|
||||
let auth = BearerAuthProvider::for_test(Some("access-token"), Some("workspace-123"));
|
||||
let mut headers = HeaderMap::new();
|
||||
|
||||
auth.add_auth_headers(&mut headers);
|
||||
|
||||
assert_eq!(
|
||||
headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("Bearer access-token")
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("ChatGPT-Account-ID")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("workspace-123")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_auth_provider_adds_fedramp_routing_header_for_fedramp_accounts() {
|
||||
let auth = BearerAuthProvider {
|
||||
token: Some("access-token".to_string()),
|
||||
account_id: Some("workspace-123".to_string()),
|
||||
is_fedramp_account: true,
|
||||
};
|
||||
let mut headers = HeaderMap::new();
|
||||
|
||||
auth.add_auth_headers(&mut headers);
|
||||
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("X-OpenAI-Fedramp")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("true")
|
||||
);
|
||||
}
|
||||
}
|
||||
10
vendor/codex/codex-rs/model-provider/src/lib.rs
vendored
Normal file
10
vendor/codex/codex-rs/model-provider/src/lib.rs
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
mod amazon_bedrock;
|
||||
mod auth;
|
||||
mod bearer_auth_provider;
|
||||
mod provider;
|
||||
|
||||
pub use bearer_auth_provider::BearerAuthProvider;
|
||||
pub use bearer_auth_provider::BearerAuthProvider as CoreAuthProvider;
|
||||
pub use provider::ModelProvider;
|
||||
pub use provider::SharedModelProvider;
|
||||
pub use provider::create_model_provider;
|
||||
158
vendor/codex/codex-rs/model-provider/src/provider.rs
vendored
Normal file
158
vendor/codex/codex-rs/model-provider/src/provider.rs
vendored
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_api::Provider;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
|
||||
use crate::amazon_bedrock::AmazonBedrockModelProvider;
|
||||
use crate::auth::auth_manager_for_provider;
|
||||
use crate::auth::resolve_provider_auth;
|
||||
|
||||
/// Runtime provider abstraction used by model execution.
|
||||
///
|
||||
/// Implementations own provider-specific behavior for a model backend. The
|
||||
/// `ModelProviderInfo` returned by `info` is the serialized/configured provider
|
||||
/// metadata used by the default OpenAI-compatible implementation.
|
||||
#[async_trait::async_trait]
|
||||
pub trait ModelProvider: fmt::Debug + Send + Sync {
|
||||
/// Returns the configured provider metadata.
|
||||
fn info(&self) -> &ModelProviderInfo;
|
||||
|
||||
/// Returns the provider-scoped auth manager, when this provider uses one.
|
||||
///
|
||||
/// TODO(celia-oai): Make auth manager access internal to this crate so callers
|
||||
/// resolve provider-specific auth only through `ModelProvider`. We first need
|
||||
/// to think through whether Codex should have a unified provider-specific auth
|
||||
/// manager throughout the codebase; that is a larger refactor than this change.
|
||||
fn auth_manager(&self) -> Option<Arc<AuthManager>>;
|
||||
|
||||
/// Returns the current provider-scoped auth value, if one is configured.
|
||||
async fn auth(&self) -> Option<CodexAuth>;
|
||||
|
||||
/// Returns provider configuration adapted for the API client.
|
||||
async fn api_provider(&self) -> codex_protocol::error::Result<Provider> {
|
||||
let auth = self.auth().await;
|
||||
self.info()
|
||||
.to_api_provider(auth.as_ref().map(CodexAuth::auth_mode))
|
||||
}
|
||||
|
||||
/// Returns the auth provider used to attach request credentials.
|
||||
async fn api_auth(&self) -> codex_protocol::error::Result<SharedAuthProvider> {
|
||||
let auth = self.auth().await;
|
||||
resolve_provider_auth(auth.as_ref(), self.info())
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared runtime model provider handle.
|
||||
pub type SharedModelProvider = Arc<dyn ModelProvider>;
|
||||
|
||||
/// Creates the default runtime model provider for configured provider metadata.
|
||||
pub fn create_model_provider(
|
||||
provider_info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
) -> SharedModelProvider {
|
||||
if provider_info.is_amazon_bedrock() {
|
||||
let aws = provider_info
|
||||
.aws
|
||||
.clone()
|
||||
.unwrap_or(ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: None,
|
||||
});
|
||||
return Arc::new(AmazonBedrockModelProvider {
|
||||
info: provider_info,
|
||||
aws,
|
||||
});
|
||||
}
|
||||
|
||||
let auth_manager = auth_manager_for_provider(auth_manager, &provider_info);
|
||||
Arc::new(ConfiguredModelProvider {
|
||||
info: provider_info,
|
||||
auth_manager,
|
||||
})
|
||||
}
|
||||
|
||||
/// Runtime model provider backed by configured `ModelProviderInfo`.
|
||||
#[derive(Clone, Debug)]
|
||||
struct ConfiguredModelProvider {
|
||||
info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ModelProvider for ConfiguredModelProvider {
|
||||
fn info(&self) -> &ModelProviderInfo {
|
||||
&self.info
|
||||
}
|
||||
|
||||
fn auth_manager(&self) -> Option<Arc<AuthManager>> {
|
||||
self.auth_manager.clone()
|
||||
}
|
||||
|
||||
async fn auth(&self) -> Option<CodexAuth> {
|
||||
match self.auth_manager.as_ref() {
|
||||
Some(auth_manager) => auth_manager.auth().await,
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::num::NonZeroU64;
|
||||
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn provider_info_with_command_auth() -> ModelProviderInfo {
|
||||
ModelProviderInfo {
|
||||
auth: Some(ModelProviderAuthInfo {
|
||||
command: "print-token".to_string(),
|
||||
args: Vec::new(),
|
||||
timeout_ms: NonZeroU64::new(5_000).expect("timeout should be non-zero"),
|
||||
refresh_interval_ms: 300_000,
|
||||
cwd: std::env::current_dir()
|
||||
.expect("current dir should be available")
|
||||
.try_into()
|
||||
.expect("current dir should be absolute"),
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_model_provider_builds_command_auth_manager_without_base_manager() {
|
||||
let provider = create_model_provider(
|
||||
provider_info_with_command_auth(),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
let auth_manager = provider
|
||||
.auth_manager()
|
||||
.expect("command auth provider should have an auth manager");
|
||||
|
||||
assert!(auth_manager.has_external_auth());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_model_provider_does_not_use_openai_auth_manager_for_amazon_bedrock_provider() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(Some(ModelProviderAwsAuthInfo {
|
||||
profile: Some("codex-bedrock".to_string()),
|
||||
region: None,
|
||||
})),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"openai-api-key",
|
||||
))),
|
||||
);
|
||||
|
||||
assert!(provider.auth_manager().is_none());
|
||||
}
|
||||
}
|
||||
Reference in a new issue