mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 09:20:22 +08:00
refactor: extract provider pool abstractions
This commit is contained in:
77
crates/aether-provider-pool/src/providers/antigravity.rs
Normal file
77
crates/aether-provider-pool/src/providers/antigravity.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use aether_data_contracts::repository::provider_catalog::StoredProviderCatalogEndpoint;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::capability::ProviderPoolCapabilities;
|
||||
use crate::provider::{
|
||||
provider_pool_endpoint_format_matches, provider_pool_matching_endpoint, ProviderPoolAdapter,
|
||||
};
|
||||
use crate::quota_refresh::ProviderPoolQuotaRequestSpec;
|
||||
|
||||
pub const ANTIGRAVITY_FETCH_AVAILABLE_MODELS_PATH: &str = "/v1internal:fetchAvailableModels";
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct AntigravityProviderPoolAdapter;
|
||||
|
||||
impl ProviderPoolAdapter for AntigravityProviderPoolAdapter {
|
||||
fn provider_type(&self) -> &'static str {
|
||||
"antigravity"
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> ProviderPoolCapabilities {
|
||||
ProviderPoolCapabilities {
|
||||
quota_refresh: true,
|
||||
..ProviderPoolCapabilities::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn quota_refresh_endpoint(
|
||||
&self,
|
||||
endpoints: &[StoredProviderCatalogEndpoint],
|
||||
include_inactive: bool,
|
||||
) -> Option<StoredProviderCatalogEndpoint> {
|
||||
provider_pool_matching_endpoint(endpoints, include_inactive, |endpoint| {
|
||||
provider_pool_endpoint_format_matches(endpoint, "gemini:generate_content")
|
||||
})
|
||||
}
|
||||
|
||||
fn quota_refresh_missing_endpoint_message(&self) -> String {
|
||||
"找不到有效的 gemini:generate_content 端点".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_antigravity_pool_quota_request(
|
||||
key_id: &str,
|
||||
endpoint_base_url: &str,
|
||||
authorization: (String, String),
|
||||
project_id: &str,
|
||||
mut identity_headers: BTreeMap<String, String>,
|
||||
) -> ProviderPoolQuotaRequestSpec {
|
||||
let mut headers = std::mem::take(&mut identity_headers);
|
||||
headers.insert("authorization".to_string(), authorization.1);
|
||||
headers.insert("content-type".to_string(), "application/json".to_string());
|
||||
headers.insert("accept".to_string(), "application/json".to_string());
|
||||
headers
|
||||
.entry("user-agent".to_string())
|
||||
.or_insert_with(|| "antigravity".to_string());
|
||||
|
||||
ProviderPoolQuotaRequestSpec {
|
||||
request_id: format!("antigravity-quota:{key_id}"),
|
||||
provider_name: "antigravity".to_string(),
|
||||
quota_kind: "antigravity".to_string(),
|
||||
method: "POST".to_string(),
|
||||
url: format!(
|
||||
"{}{}",
|
||||
endpoint_base_url.trim_end_matches('/'),
|
||||
ANTIGRAVITY_FETCH_AVAILABLE_MODELS_PATH
|
||||
),
|
||||
headers,
|
||||
content_type: Some("application/json".to_string()),
|
||||
json_body: Some(json!({ "project": project_id })),
|
||||
client_api_format: "gemini:generate_content".to_string(),
|
||||
provider_api_format: "antigravity:fetch_available_models".to_string(),
|
||||
model_name: Some("fetchAvailableModels".to_string()),
|
||||
accept_invalid_certs: false,
|
||||
}
|
||||
}
|
||||
272
crates/aether-provider-pool/src/providers/chatgpt_web.rs
Normal file
272
crates/aether-provider-pool/src/providers/chatgpt_web.rs
Normal file
@@ -0,0 +1,272 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use aether_data_contracts::repository::provider_catalog::StoredProviderCatalogEndpoint;
|
||||
use serde_json::{json, Map, Value};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::capability::ProviderPoolCapabilities;
|
||||
use crate::provider::{
|
||||
provider_pool_endpoint_format_matches, provider_pool_matching_endpoint, ProviderPoolAdapter,
|
||||
ProviderPoolMemberInput,
|
||||
};
|
||||
use crate::quota::{
|
||||
provider_pool_json_bool, provider_pool_json_f64, provider_pool_metadata_bucket,
|
||||
provider_pool_quota_snapshot_exhausted_decision,
|
||||
};
|
||||
use crate::quota_refresh::ProviderPoolQuotaRequestSpec;
|
||||
|
||||
pub const CHATGPT_WEB_DEFAULT_BASE_URL: &str = "https://chatgpt.com";
|
||||
pub const CHATGPT_WEB_CONVERSATION_INIT_PATH: &str = "/backend-api/conversation/init";
|
||||
|
||||
const CHATGPT_WEB_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0";
|
||||
const CHATGPT_WEB_CLIENT_VERSION: &str = "prod-be885abbfcfe7b1f511e88b3003d9ee44757fbad";
|
||||
const CHATGPT_WEB_BUILD_NUMBER: &str = "5955942";
|
||||
const CHATGPT_WEB_SEC_CH_UA: &str =
|
||||
r#""Microsoft Edge";v="143", "Chromium";v="143", "Not A(Brand";v="24""#;
|
||||
const CHATGPT_WEB_FREE_IMAGE_QUOTA_LIMIT: f64 = 25.0;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ChatGptWebProviderPoolAdapter;
|
||||
|
||||
impl ProviderPoolAdapter for ChatGptWebProviderPoolAdapter {
|
||||
fn provider_type(&self) -> &'static str {
|
||||
"chatgpt_web"
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> ProviderPoolCapabilities {
|
||||
ProviderPoolCapabilities {
|
||||
quota_refresh: true,
|
||||
..ProviderPoolCapabilities::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn quota_exhausted(&self, input: &ProviderPoolMemberInput<'_>) -> bool {
|
||||
if let Some(exhausted) =
|
||||
provider_pool_quota_snapshot_exhausted_decision(input.key, input.provider_type)
|
||||
{
|
||||
return exhausted;
|
||||
}
|
||||
provider_pool_metadata_bucket(input.key.upstream_metadata.as_ref(), input.provider_type)
|
||||
.is_some_and(quota_exhausted_from_bucket)
|
||||
}
|
||||
|
||||
fn quota_refresh_endpoint(
|
||||
&self,
|
||||
endpoints: &[StoredProviderCatalogEndpoint],
|
||||
include_inactive: bool,
|
||||
) -> Option<StoredProviderCatalogEndpoint> {
|
||||
provider_pool_matching_endpoint(endpoints, include_inactive, |endpoint| {
|
||||
provider_pool_endpoint_format_matches(endpoint, "openai:image")
|
||||
})
|
||||
}
|
||||
|
||||
fn quota_refresh_missing_endpoint_message(&self) -> String {
|
||||
"找不到有效的 openai:image 端点".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_chatgpt_web_pool_quota_request(
|
||||
key_id: &str,
|
||||
endpoint_base_url: &str,
|
||||
authorization: (String, String),
|
||||
) -> ProviderPoolQuotaRequestSpec {
|
||||
let base_url = chatgpt_web_base_url(endpoint_base_url);
|
||||
let device_id = Uuid::new_v4().to_string();
|
||||
let session_id = Uuid::new_v4().to_string();
|
||||
let mut headers = BTreeMap::from([
|
||||
("accept".to_string(), "application/json".to_string()),
|
||||
("content-type".to_string(), "application/json".to_string()),
|
||||
("user-agent".to_string(), CHATGPT_WEB_USER_AGENT.to_string()),
|
||||
("origin".to_string(), base_url.clone()),
|
||||
("referer".to_string(), format!("{base_url}/")),
|
||||
(
|
||||
"accept-language".to_string(),
|
||||
"zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7".to_string(),
|
||||
),
|
||||
("cache-control".to_string(), "no-cache".to_string()),
|
||||
("pragma".to_string(), "no-cache".to_string()),
|
||||
("priority".to_string(), "u=1, i".to_string()),
|
||||
("sec-ch-ua".to_string(), CHATGPT_WEB_SEC_CH_UA.to_string()),
|
||||
("sec-ch-ua-arch".to_string(), r#""x86""#.to_string()),
|
||||
("sec-ch-ua-bitness".to_string(), r#""64""#.to_string()),
|
||||
("sec-ch-ua-mobile".to_string(), "?0".to_string()),
|
||||
("sec-ch-ua-model".to_string(), r#""""#.to_string()),
|
||||
("sec-ch-ua-platform".to_string(), r#""Windows""#.to_string()),
|
||||
(
|
||||
"sec-ch-ua-platform-version".to_string(),
|
||||
r#""19.0.0""#.to_string(),
|
||||
),
|
||||
("sec-fetch-dest".to_string(), "empty".to_string()),
|
||||
("sec-fetch-mode".to_string(), "cors".to_string()),
|
||||
("sec-fetch-site".to_string(), "same-origin".to_string()),
|
||||
("oai-device-id".to_string(), device_id),
|
||||
("oai-session-id".to_string(), session_id),
|
||||
("oai-language".to_string(), "zh-CN".to_string()),
|
||||
(
|
||||
"oai-client-version".to_string(),
|
||||
CHATGPT_WEB_CLIENT_VERSION.to_string(),
|
||||
),
|
||||
(
|
||||
"oai-client-build-number".to_string(),
|
||||
CHATGPT_WEB_BUILD_NUMBER.to_string(),
|
||||
),
|
||||
(
|
||||
"x-openai-target-path".to_string(),
|
||||
CHATGPT_WEB_CONVERSATION_INIT_PATH.to_string(),
|
||||
),
|
||||
(
|
||||
"x-openai-target-route".to_string(),
|
||||
CHATGPT_WEB_CONVERSATION_INIT_PATH.to_string(),
|
||||
),
|
||||
]);
|
||||
headers.insert(authorization.0.to_ascii_lowercase(), authorization.1);
|
||||
|
||||
ProviderPoolQuotaRequestSpec {
|
||||
request_id: format!("chatgpt-web-quota:{key_id}"),
|
||||
provider_name: "chatgpt_web".to_string(),
|
||||
quota_kind: "chatgpt_web".to_string(),
|
||||
method: "POST".to_string(),
|
||||
url: format!("{base_url}{CHATGPT_WEB_CONVERSATION_INIT_PATH}"),
|
||||
headers,
|
||||
content_type: Some("application/json".to_string()),
|
||||
json_body: Some(json!({
|
||||
"gizmo_id": Value::Null,
|
||||
"requested_default_model": Value::Null,
|
||||
"conversation_id": Value::Null,
|
||||
"timezone_offset_min": -480,
|
||||
"system_hints": ["picture_v2"],
|
||||
})),
|
||||
client_api_format: "openai:image".to_string(),
|
||||
provider_api_format: "chatgpt_web:conversation_init".to_string(),
|
||||
model_name: Some("chatgpt-web-conversation-init".to_string()),
|
||||
accept_invalid_certs: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn chatgpt_web_base_url(endpoint_base_url: &str) -> String {
|
||||
let base_url = endpoint_base_url.trim().trim_end_matches('/');
|
||||
if base_url.is_empty() {
|
||||
CHATGPT_WEB_DEFAULT_BASE_URL.to_string()
|
||||
} else {
|
||||
base_url.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enrich_chatgpt_web_quota_metadata(metadata: &mut Value, auth_config: Option<&Value>) {
|
||||
let Some(object) = metadata.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
for (target, fields) in [
|
||||
("plan_type", &["plan_type", "tier", "plan"][..]),
|
||||
("email", &["email"][..]),
|
||||
("account_id", &["account_id", "accountId"][..]),
|
||||
("account_user_id", &["account_user_id", "accountUserId"][..]),
|
||||
("user_id", &["user_id", "userId"][..]),
|
||||
] {
|
||||
if object.contains_key(target) {
|
||||
continue;
|
||||
}
|
||||
if let Some(value) = chatgpt_web_auth_config_string(auth_config, fields) {
|
||||
object.insert(target.to_string(), json!(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn normalize_chatgpt_web_image_quota_limit(
|
||||
metadata: &mut Value,
|
||||
upstream_metadata: Option<&Value>,
|
||||
) {
|
||||
let existing_limit = existing_chatgpt_web_image_quota_limit(upstream_metadata);
|
||||
let Some(object) = metadata.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let remaining = provider_pool_json_f64(object.get("image_quota_remaining"));
|
||||
let explicit_limit =
|
||||
provider_pool_json_f64(object.get("image_quota_total")).filter(|value| *value > 0.0);
|
||||
let plan_type = chatgpt_web_json_string(object.get("plan_type"));
|
||||
let is_free_plan = plan_type.is_some_and(|value| value.trim().eq_ignore_ascii_case("free"));
|
||||
let limit = if is_free_plan {
|
||||
Some(CHATGPT_WEB_FREE_IMAGE_QUOTA_LIMIT)
|
||||
} else {
|
||||
explicit_limit
|
||||
.or_else(|| infer_chatgpt_web_image_quota_limit(plan_type, remaining, existing_limit))
|
||||
};
|
||||
|
||||
if let Some(limit) = limit {
|
||||
object.insert("image_quota_total".to_string(), json!(limit));
|
||||
|
||||
if !object.contains_key("image_quota_used") {
|
||||
if let Some(remaining) = remaining {
|
||||
object.insert(
|
||||
"image_quota_used".to_string(),
|
||||
json!((limit - remaining).max(0.0)),
|
||||
);
|
||||
} else if object.get("image_quota_blocked").and_then(Value::as_bool) == Some(true) {
|
||||
object.insert("image_quota_used".to_string(), json!(limit));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn chatgpt_web_auth_config_string(auth_config: Option<&Value>, fields: &[&str]) -> Option<String> {
|
||||
let object = auth_config.and_then(Value::as_object)?;
|
||||
fields.iter().find_map(|field| {
|
||||
object
|
||||
.get(*field)
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
})
|
||||
}
|
||||
|
||||
fn chatgpt_web_json_string(value: Option<&Value>) -> Option<&str> {
|
||||
value
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn existing_chatgpt_web_image_quota_limit(upstream_metadata: Option<&Value>) -> Option<f64> {
|
||||
upstream_metadata
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|metadata| metadata.get("chatgpt_web"))
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|bucket| provider_pool_json_f64(bucket.get("image_quota_total")))
|
||||
.filter(|value| *value > 0.0)
|
||||
}
|
||||
|
||||
fn infer_chatgpt_web_image_quota_limit(
|
||||
plan_type: Option<&str>,
|
||||
remaining: Option<f64>,
|
||||
existing_limit: Option<f64>,
|
||||
) -> Option<f64> {
|
||||
let normalized_plan = plan_type.unwrap_or_default().trim().to_ascii_lowercase();
|
||||
if normalized_plan == "free" {
|
||||
return Some(CHATGPT_WEB_FREE_IMAGE_QUOTA_LIMIT);
|
||||
}
|
||||
|
||||
if let Some(existing_limit) = existing_limit.filter(|value| *value > 0.0) {
|
||||
return Some(existing_limit);
|
||||
}
|
||||
|
||||
remaining.filter(|value| *value > 0.0)
|
||||
}
|
||||
|
||||
pub(crate) fn quota_exhausted_from_bucket(bucket: &Map<String, Value>) -> bool {
|
||||
if provider_pool_json_bool(bucket.get("image_quota_blocked")) == Some(true) {
|
||||
return true;
|
||||
}
|
||||
if provider_pool_json_f64(bucket.get("image_quota_remaining")).is_some_and(|value| value <= 0.0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
match (
|
||||
provider_pool_json_f64(bucket.get("image_quota_total")),
|
||||
provider_pool_json_f64(bucket.get("image_quota_used")),
|
||||
) {
|
||||
(Some(limit), Some(used)) if limit > 0.0 => used >= limit,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
136
crates/aether-provider-pool/src/providers/codex.rs
Normal file
136
crates/aether-provider-pool/src/providers/codex.rs
Normal file
@@ -0,0 +1,136 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use aether_data_contracts::repository::provider_catalog::StoredProviderCatalogEndpoint;
|
||||
use aether_pool_core::PoolSchedulingPreset;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::capability::ProviderPoolCapabilities;
|
||||
use crate::provider::{
|
||||
provider_pool_endpoint_format_matches, provider_pool_matching_endpoint, ProviderPoolAdapter,
|
||||
ProviderPoolMemberInput,
|
||||
};
|
||||
use crate::quota::{
|
||||
provider_pool_json_bool, provider_pool_json_f64, provider_pool_metadata_bucket,
|
||||
provider_pool_quota_snapshot_exhausted_decision,
|
||||
};
|
||||
use crate::quota_refresh::ProviderPoolQuotaRequestSpec;
|
||||
|
||||
pub const CODEX_WHAM_USAGE_URL: &str = "https://chatgpt.com/backend-api/wham/usage";
|
||||
const PLACEHOLDER_API_KEY: &str = "__placeholder__";
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CodexProviderPoolAdapter;
|
||||
|
||||
impl ProviderPoolAdapter for CodexProviderPoolAdapter {
|
||||
fn provider_type(&self) -> &'static str {
|
||||
"codex"
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> ProviderPoolCapabilities {
|
||||
ProviderPoolCapabilities {
|
||||
plan_tier: true,
|
||||
quota_reset: true,
|
||||
quota_refresh: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn default_scheduling_presets(&self) -> Vec<PoolSchedulingPreset> {
|
||||
vec![PoolSchedulingPreset {
|
||||
preset: "recent_refresh".to_string(),
|
||||
enabled: true,
|
||||
mode: None,
|
||||
}]
|
||||
}
|
||||
|
||||
fn quota_exhausted(&self, input: &ProviderPoolMemberInput<'_>) -> bool {
|
||||
if let Some(exhausted) =
|
||||
provider_pool_quota_snapshot_exhausted_decision(input.key, input.provider_type)
|
||||
{
|
||||
return exhausted;
|
||||
}
|
||||
provider_pool_metadata_bucket(input.key.upstream_metadata.as_ref(), input.provider_type)
|
||||
.is_some_and(quota_exhausted_from_bucket)
|
||||
}
|
||||
|
||||
fn quota_refresh_endpoint(
|
||||
&self,
|
||||
endpoints: &[StoredProviderCatalogEndpoint],
|
||||
include_inactive: bool,
|
||||
) -> Option<StoredProviderCatalogEndpoint> {
|
||||
provider_pool_matching_endpoint(endpoints, include_inactive, |endpoint| {
|
||||
provider_pool_endpoint_format_matches(endpoint, "openai:responses")
|
||||
})
|
||||
}
|
||||
|
||||
fn quota_refresh_missing_endpoint_message(&self) -> String {
|
||||
"找不到有效的 openai:responses 端点".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_codex_pool_quota_request(
|
||||
key_id: &str,
|
||||
resolved_oauth_auth: Option<(String, String)>,
|
||||
decrypted_api_key: Option<&str>,
|
||||
auth_config: Option<&Value>,
|
||||
) -> Result<ProviderPoolQuotaRequestSpec, String> {
|
||||
let mut headers = BTreeMap::new();
|
||||
headers.insert("accept".to_string(), "application/json".to_string());
|
||||
|
||||
if let Some((name, value)) = resolved_oauth_auth {
|
||||
headers.insert(name.to_ascii_lowercase(), value);
|
||||
} else {
|
||||
let decrypted_key = decrypted_api_key.unwrap_or_default().trim();
|
||||
if decrypted_key.is_empty() || decrypted_key == PLACEHOLDER_API_KEY {
|
||||
return Err("缺少 OAuth 认证信息,请先授权/刷新 Token".to_string());
|
||||
}
|
||||
headers.insert(
|
||||
"authorization".to_string(),
|
||||
format!("Bearer {decrypted_key}"),
|
||||
);
|
||||
}
|
||||
|
||||
let oauth_plan_type = auth_config
|
||||
.and_then(|value| value.get("plan_type"))
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|value| crate::plan::normalize_provider_plan_tier(value, "codex"));
|
||||
let oauth_account_id = auth_config
|
||||
.and_then(|value| value.get("account_id"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty());
|
||||
if oauth_account_id.is_some() && oauth_plan_type.as_deref() != Some("free") {
|
||||
headers.insert(
|
||||
"chatgpt-account-id".to_string(),
|
||||
oauth_account_id.unwrap_or_default().to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(ProviderPoolQuotaRequestSpec {
|
||||
request_id: format!("codex-quota:{key_id}"),
|
||||
provider_name: "codex".to_string(),
|
||||
quota_kind: "codex".to_string(),
|
||||
method: "GET".to_string(),
|
||||
url: CODEX_WHAM_USAGE_URL.to_string(),
|
||||
headers,
|
||||
content_type: None,
|
||||
json_body: None,
|
||||
client_api_format: "openai:responses".to_string(),
|
||||
provider_api_format: "openai:responses".to_string(),
|
||||
model_name: Some("codex-wham-usage".to_string()),
|
||||
accept_invalid_certs: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn quota_exhausted_from_bucket(bucket: &Map<String, Value>) -> bool {
|
||||
if provider_pool_json_bool(bucket.get("credits_unlimited")) == Some(true) {
|
||||
return false;
|
||||
}
|
||||
let has_window_data = provider_pool_json_f64(bucket.get("primary_used_percent")).is_some()
|
||||
|| provider_pool_json_f64(bucket.get("secondary_used_percent")).is_some();
|
||||
if !has_window_data && provider_pool_json_bool(bucket.get("has_credits")) == Some(false) {
|
||||
return true;
|
||||
}
|
||||
provider_pool_json_f64(bucket.get("primary_used_percent")).is_some_and(|value| value >= 100.0)
|
||||
|| provider_pool_json_f64(bucket.get("secondary_used_percent"))
|
||||
.is_some_and(|value| value >= 100.0)
|
||||
}
|
||||
10
crates/aether-provider-pool/src/providers/default.rs
Normal file
10
crates/aether-provider-pool/src/providers/default.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
use crate::provider::ProviderPoolAdapter;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct DefaultProviderPoolAdapter;
|
||||
|
||||
impl ProviderPoolAdapter for DefaultProviderPoolAdapter {
|
||||
fn provider_type(&self) -> &'static str {
|
||||
"default"
|
||||
}
|
||||
}
|
||||
167
crates/aether-provider-pool/src/providers/kiro.rs
Normal file
167
crates/aether-provider-pool/src/providers/kiro.rs
Normal file
@@ -0,0 +1,167 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use aether_data_contracts::repository::provider_catalog::StoredProviderCatalogEndpoint;
|
||||
use serde_json::{Map, Value};
|
||||
use url::form_urlencoded;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::capability::ProviderPoolCapabilities;
|
||||
use crate::provider::{
|
||||
provider_pool_endpoint_format_matches, provider_pool_matching_endpoint, ProviderPoolAdapter,
|
||||
ProviderPoolMemberInput,
|
||||
};
|
||||
use crate::quota::{
|
||||
provider_pool_json_f64, provider_pool_metadata_bucket,
|
||||
provider_pool_quota_snapshot_exhausted_decision,
|
||||
};
|
||||
use crate::quota_refresh::ProviderPoolQuotaRequestSpec;
|
||||
|
||||
pub const KIRO_USAGE_LIMITS_PATH: &str = "/getUsageLimits";
|
||||
pub const KIRO_USAGE_SDK_VERSION: &str = "1.0.0";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct KiroPoolQuotaAuthInput {
|
||||
pub authorization_value: String,
|
||||
pub api_region: String,
|
||||
pub kiro_version: String,
|
||||
pub machine_id: String,
|
||||
pub profile_arn: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct KiroProviderPoolAdapter;
|
||||
|
||||
impl ProviderPoolAdapter for KiroProviderPoolAdapter {
|
||||
fn provider_type(&self) -> &'static str {
|
||||
"kiro"
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> ProviderPoolCapabilities {
|
||||
ProviderPoolCapabilities {
|
||||
plan_tier: true,
|
||||
quota_reset: true,
|
||||
quota_refresh: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn quota_exhausted(&self, input: &ProviderPoolMemberInput<'_>) -> bool {
|
||||
if let Some(exhausted) =
|
||||
provider_pool_quota_snapshot_exhausted_decision(input.key, input.provider_type)
|
||||
{
|
||||
return exhausted;
|
||||
}
|
||||
provider_pool_metadata_bucket(input.key.upstream_metadata.as_ref(), input.provider_type)
|
||||
.is_some_and(quota_exhausted_from_bucket)
|
||||
}
|
||||
|
||||
fn quota_refresh_endpoint(
|
||||
&self,
|
||||
endpoints: &[StoredProviderCatalogEndpoint],
|
||||
include_inactive: bool,
|
||||
) -> Option<StoredProviderCatalogEndpoint> {
|
||||
provider_pool_matching_endpoint(endpoints, include_inactive, |endpoint| {
|
||||
provider_pool_endpoint_format_matches(endpoint, "claude:messages")
|
||||
})
|
||||
.or_else(|| provider_pool_matching_endpoint(endpoints, include_inactive, |_| true))
|
||||
}
|
||||
|
||||
fn quota_refresh_missing_endpoint_message(&self) -> String {
|
||||
"找不到有效的 Kiro 端点".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_kiro_pool_quota_request(
|
||||
key_id: &str,
|
||||
auth: &KiroPoolQuotaAuthInput,
|
||||
) -> ProviderPoolQuotaRequestSpec {
|
||||
let host = format!("q.{}.amazonaws.com", normalize_region(&auth.api_region));
|
||||
let machine_id = auth.machine_id.trim();
|
||||
let ide_tag = if machine_id.is_empty() {
|
||||
format!("KiroIDE-{}", normalize_kiro_version(&auth.kiro_version))
|
||||
} else {
|
||||
format!(
|
||||
"KiroIDE-{}-{machine_id}",
|
||||
normalize_kiro_version(&auth.kiro_version)
|
||||
)
|
||||
};
|
||||
let mut serializer = form_urlencoded::Serializer::new(String::new());
|
||||
serializer.append_pair("origin", "AI_EDITOR");
|
||||
serializer.append_pair("resourceType", "AGENTIC_REQUEST");
|
||||
serializer.append_pair("isEmailRequired", "true");
|
||||
if let Some(profile_arn) = auth
|
||||
.profile_arn
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
serializer.append_pair("profileArn", profile_arn);
|
||||
}
|
||||
|
||||
ProviderPoolQuotaRequestSpec {
|
||||
request_id: format!("kiro-quota:{key_id}"),
|
||||
provider_name: "kiro".to_string(),
|
||||
quota_kind: "kiro".to_string(),
|
||||
method: "GET".to_string(),
|
||||
url: format!("https://{host}{KIRO_USAGE_LIMITS_PATH}?{}", serializer.finish()),
|
||||
headers: BTreeMap::from([
|
||||
(
|
||||
"x-amz-user-agent".to_string(),
|
||||
format!("aws-sdk-js/{KIRO_USAGE_SDK_VERSION} {ide_tag}"),
|
||||
),
|
||||
(
|
||||
"user-agent".to_string(),
|
||||
format!(
|
||||
"aws-sdk-js/{KIRO_USAGE_SDK_VERSION} ua/2.1 os/other#unknown lang/js md/nodejs#22.21.1 api/codewhispererruntime#1.0.0 m/N,E {ide_tag}"
|
||||
),
|
||||
),
|
||||
("host".to_string(), host),
|
||||
("amz-sdk-invocation-id".to_string(), Uuid::new_v4().to_string()),
|
||||
("amz-sdk-request".to_string(), "attempt=1; max=1".to_string()),
|
||||
(
|
||||
"authorization".to_string(),
|
||||
auth.authorization_value.clone(),
|
||||
),
|
||||
("connection".to_string(), "close".to_string()),
|
||||
]),
|
||||
content_type: None,
|
||||
json_body: None,
|
||||
client_api_format: "claude:messages".to_string(),
|
||||
provider_api_format: "kiro:usage".to_string(),
|
||||
model_name: Some("kiro-usage-limits".to_string()),
|
||||
accept_invalid_certs: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_region(value: &str) -> &str {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
"us-east-1"
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_kiro_version(value: &str) -> &str {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
"0.3.210"
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn quota_exhausted_from_bucket(bucket: &Map<String, Value>) -> bool {
|
||||
if provider_pool_json_f64(bucket.get("remaining")).is_some_and(|value| value <= 0.0) {
|
||||
return true;
|
||||
}
|
||||
if provider_pool_json_f64(bucket.get("usage_percentage")).is_some_and(|value| value >= 100.0) {
|
||||
return true;
|
||||
}
|
||||
match (
|
||||
provider_pool_json_f64(bucket.get("usage_limit")),
|
||||
provider_pool_json_f64(bucket.get("current_usage")),
|
||||
) {
|
||||
(Some(limit), Some(current)) if limit > 0.0 => current >= limit,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
29
crates/aether-provider-pool/src/providers/mod.rs
Normal file
29
crates/aether-provider-pool/src/providers/mod.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
pub mod antigravity;
|
||||
pub mod chatgpt_web;
|
||||
pub mod codex;
|
||||
pub mod default;
|
||||
pub mod kiro;
|
||||
pub mod unsupported;
|
||||
|
||||
pub use antigravity::AntigravityProviderPoolAdapter;
|
||||
pub use antigravity::{
|
||||
build_antigravity_pool_quota_request, ANTIGRAVITY_FETCH_AVAILABLE_MODELS_PATH,
|
||||
};
|
||||
pub use chatgpt_web::ChatGptWebProviderPoolAdapter;
|
||||
pub use chatgpt_web::{
|
||||
build_chatgpt_web_pool_quota_request, enrich_chatgpt_web_quota_metadata,
|
||||
normalize_chatgpt_web_image_quota_limit, CHATGPT_WEB_CONVERSATION_INIT_PATH,
|
||||
CHATGPT_WEB_DEFAULT_BASE_URL,
|
||||
};
|
||||
pub use codex::CodexProviderPoolAdapter;
|
||||
pub use codex::{build_codex_pool_quota_request, CODEX_WHAM_USAGE_URL};
|
||||
pub use default::DefaultProviderPoolAdapter;
|
||||
pub use kiro::KiroProviderPoolAdapter;
|
||||
pub use kiro::{
|
||||
build_kiro_pool_quota_request, KiroPoolQuotaAuthInput, KIRO_USAGE_LIMITS_PATH,
|
||||
KIRO_USAGE_SDK_VERSION,
|
||||
};
|
||||
pub use unsupported::{
|
||||
UnsupportedQuotaProviderPoolAdapter, CLAUDE_CODE_PROVIDER_POOL_ADAPTER,
|
||||
GEMINI_CLI_PROVIDER_POOL_ADAPTER, VERTEX_AI_PROVIDER_POOL_ADAPTER,
|
||||
};
|
||||
47
crates/aether-provider-pool/src/providers/unsupported.rs
Normal file
47
crates/aether-provider-pool/src/providers/unsupported.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use crate::provider::ProviderPoolAdapter;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct UnsupportedQuotaProviderPoolAdapter {
|
||||
provider_type: &'static str,
|
||||
quota_refresh_unsupported_message: &'static str,
|
||||
}
|
||||
|
||||
impl UnsupportedQuotaProviderPoolAdapter {
|
||||
pub const fn new(
|
||||
provider_type: &'static str,
|
||||
quota_refresh_unsupported_message: &'static str,
|
||||
) -> Self {
|
||||
Self {
|
||||
provider_type,
|
||||
quota_refresh_unsupported_message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ProviderPoolAdapter for UnsupportedQuotaProviderPoolAdapter {
|
||||
fn provider_type(&self) -> &'static str {
|
||||
self.provider_type
|
||||
}
|
||||
|
||||
fn quota_refresh_unsupported_message(&self) -> String {
|
||||
self.quota_refresh_unsupported_message.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub const CLAUDE_CODE_PROVIDER_POOL_ADAPTER: UnsupportedQuotaProviderPoolAdapter =
|
||||
UnsupportedQuotaProviderPoolAdapter::new(
|
||||
"claude_code",
|
||||
"Claude Code 暂不支持自动刷新额度:上游没有稳定可用的账号额度查询接口",
|
||||
);
|
||||
|
||||
pub const GEMINI_CLI_PROVIDER_POOL_ADAPTER: UnsupportedQuotaProviderPoolAdapter =
|
||||
UnsupportedQuotaProviderPoolAdapter::new(
|
||||
"gemini_cli",
|
||||
"Gemini CLI 暂不支持自动刷新额度:当前只能通过模型同步/缓存快照展示已知配额信息",
|
||||
);
|
||||
|
||||
pub const VERTEX_AI_PROVIDER_POOL_ADAPTER: UnsupportedQuotaProviderPoolAdapter =
|
||||
UnsupportedQuotaProviderPoolAdapter::new(
|
||||
"vertex_ai",
|
||||
"Vertex AI 暂不支持自动刷新额度:额度属于 Google Cloud 项目/区域配额",
|
||||
);
|
||||
Reference in New Issue
Block a user