aKode fase 2b-1 (WIP): rimossi cloud-config, apps MCP ChatGPT, upload file, connectors-extension, rate limits backend; plugin remoti in corso (test non ancora compilanti)
Some checks failed
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
Some checks failed
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
This commit is contained in:
@@ -1,83 +0,0 @@
|
||||
use codex_backend_client::Client as BackendClient;
|
||||
use codex_core::config::Config;
|
||||
use codex_model_provider::ProviderAuthContext;
|
||||
use codex_protocol::protocol::RateLimitSnapshot;
|
||||
use codex_protocol::protocol::RateLimitWindow;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
pub(crate) async fn rate_limits_ok(auth_context: &ProviderAuthContext, config: &Config) -> bool {
|
||||
rate_limits_check(auth_context, config)
|
||||
.await
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
async fn rate_limits_check(auth_context: &ProviderAuthContext, config: &Config) -> Option<bool> {
|
||||
let (auth, captured_factory) = auth_context
|
||||
.credentials
|
||||
.auth_with_http_client_factory()
|
||||
.await?;
|
||||
if !auth.uses_codex_backend() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let factory = config.http_client_factory();
|
||||
let policy = factory
|
||||
.network_policy()
|
||||
.clone()
|
||||
.with_account_binding(captured_factory.network_policy())?;
|
||||
let client = BackendClient::from_auth_with_runtime(
|
||||
config.chatgpt_base_url.clone(),
|
||||
&auth,
|
||||
factory.with_network_policy(policy),
|
||||
auth_context.runtime_auth.as_ref(),
|
||||
/*headers*/ &Default::default(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| warn!(%error, "failed to prepare memory rate-limit authentication"))
|
||||
.ok()?;
|
||||
|
||||
let snapshots = client
|
||||
.get_rate_limits_many()
|
||||
.await
|
||||
.map_err(|err| warn!(%err, "failed to fetch rate limits"))
|
||||
.ok()?;
|
||||
|
||||
let snapshot = snapshots
|
||||
.iter()
|
||||
.find(|s| s.limit_id.as_deref() == Some(crate::guard_limits::CODEX_LIMIT_ID))
|
||||
.or_else(|| snapshots.first())?;
|
||||
|
||||
let min_remaining_percent = config.memories.min_rate_limit_remaining_percent;
|
||||
let allowed = snapshot_allows_startup(snapshot, min_remaining_percent);
|
||||
|
||||
if !allowed {
|
||||
info!(
|
||||
min_remaining_percent,
|
||||
"skipping memories startup because Codex rate limits are below the configured threshold"
|
||||
);
|
||||
}
|
||||
|
||||
Some(allowed)
|
||||
}
|
||||
|
||||
fn snapshot_allows_startup(snapshot: &RateLimitSnapshot, min_remaining_percent: i64) -> bool {
|
||||
if snapshot.rate_limit_reached_type.is_some() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let max_used_percent = 100.0 - min_remaining_percent.clamp(0, 100) as f64;
|
||||
window_allows_startup(snapshot.primary.as_ref(), max_used_percent)
|
||||
&& window_allows_startup(snapshot.secondary.as_ref(), max_used_percent)
|
||||
}
|
||||
|
||||
fn window_allows_startup(window: Option<&RateLimitWindow>, max_used_percent: f64) -> bool {
|
||||
match window {
|
||||
Some(window) => window.used_percent <= max_used_percent,
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "guard_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,81 +0,0 @@
|
||||
use super::*;
|
||||
use codex_protocol::protocol::RateLimitReachedType;
|
||||
|
||||
fn snapshot(
|
||||
primary_used_percent: Option<f64>,
|
||||
secondary_used_percent: Option<f64>,
|
||||
) -> RateLimitSnapshot {
|
||||
RateLimitSnapshot {
|
||||
limit_id: Some(crate::guard_limits::CODEX_LIMIT_ID.to_string()),
|
||||
limit_name: None,
|
||||
normal_model_slug: None,
|
||||
primary: primary_used_percent.map(window),
|
||||
secondary: secondary_used_percent.map(window),
|
||||
credits: None,
|
||||
individual_limit: None,
|
||||
spend_control_reached: None,
|
||||
plan_type: None,
|
||||
rate_limit_reached_type: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn window(used_percent: f64) -> RateLimitWindow {
|
||||
RateLimitWindow {
|
||||
used_percent,
|
||||
window_minutes: None,
|
||||
resets_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_check_uses_configured_remaining_threshold() {
|
||||
let snapshot = snapshot(
|
||||
/*primary_used_percent*/ Some(89.9),
|
||||
/*secondary_used_percent*/ Some(50.0),
|
||||
);
|
||||
|
||||
assert!(snapshot_allows_startup(
|
||||
&snapshot, /*min_remaining_percent*/ 10
|
||||
));
|
||||
assert!(!snapshot_allows_startup(
|
||||
&snapshot, /*min_remaining_percent*/ 11
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_check_skips_when_primary_or_secondary_is_too_low() {
|
||||
assert!(!snapshot_allows_startup(
|
||||
&snapshot(
|
||||
/*primary_used_percent*/ Some(75.1),
|
||||
/*secondary_used_percent*/ Some(10.0),
|
||||
),
|
||||
/*min_remaining_percent*/ 25,
|
||||
));
|
||||
assert!(!snapshot_allows_startup(
|
||||
&snapshot(
|
||||
/*primary_used_percent*/ Some(10.0),
|
||||
/*secondary_used_percent*/ Some(75.1),
|
||||
),
|
||||
/*min_remaining_percent*/ 25,
|
||||
));
|
||||
assert!(snapshot_allows_startup(
|
||||
&snapshot(
|
||||
/*primary_used_percent*/ Some(74.9),
|
||||
/*secondary_used_percent*/ Some(74.9),
|
||||
),
|
||||
/*min_remaining_percent*/ 25,
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_check_skips_when_limit_is_reached() {
|
||||
let mut snapshot = snapshot(
|
||||
/*primary_used_percent*/ Some(10.0),
|
||||
/*secondary_used_percent*/ Some(10.0),
|
||||
);
|
||||
snapshot.rate_limit_reached_type = Some(RateLimitReachedType::RateLimitReached);
|
||||
|
||||
assert!(!snapshot_allows_startup(
|
||||
&snapshot, /*min_remaining_percent*/ 25,
|
||||
));
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
mod control;
|
||||
mod extensions;
|
||||
mod guard;
|
||||
mod metrics;
|
||||
mod phase1;
|
||||
mod phase1_output;
|
||||
@@ -47,10 +46,6 @@ mod extension_resources {
|
||||
pub(super) const RETENTION_DAYS: i64 = 14;
|
||||
}
|
||||
|
||||
mod guard_limits {
|
||||
pub(super) const CODEX_LIMIT_ID: &str = "codex";
|
||||
}
|
||||
|
||||
mod prompt_blocks {
|
||||
pub(super) const EXTENSIONS_FOLDER_STRUCTURE: &str = r#"
|
||||
Memory extensions (under {{ memory_extensions_root }}/):
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
pub(crate) const MEMORY_STARTUP: &str = "codex.memory.startup";
|
||||
pub(crate) const MEMORY_STORAGE_BYTES: &str = "codex.memory.storage_bytes";
|
||||
|
||||
pub(crate) const MEMORY_PHASE_ONE_JOBS: &str = "codex.memory.phase1";
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
use crate::ensure_layout;
|
||||
use crate::extensions::seed_extension_instructions;
|
||||
use crate::guard;
|
||||
use crate::metrics::MEMORY_STARTUP;
|
||||
use crate::phase1;
|
||||
use crate::phase2;
|
||||
use crate::runtime::MemoryStartupContext;
|
||||
@@ -84,15 +82,6 @@ pub fn start_memories_startup_task(
|
||||
// done before the quota check.
|
||||
phase1::prune(context.as_ref(), &config).await;
|
||||
|
||||
if !guard::rate_limits_ok(&auth, &config).await {
|
||||
context.counter(
|
||||
MEMORY_STARTUP,
|
||||
/*inc*/ 1,
|
||||
&[("status", "skipped_rate_limit")],
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Run phase 1.
|
||||
phase1::run(Arc::clone(&context), Arc::clone(&config)).await;
|
||||
// Run phase 2.
|
||||
|
||||
@@ -1642,176 +1642,3 @@ async fn memories_startup_phase2_v2_consolidates_without_a_handbook() -> anyhow:
|
||||
assert_eq!(request.body_json()["service_tier"], "flex");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "aKode: runtime registration with auth.openai.com is disabled"]
|
||||
async fn memories_startup_uses_thread_runtime_and_keeps_custom_destinations_independent()
|
||||
-> anyhow::Result<()> {
|
||||
use base64::Engine;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::ProviderAuthContext;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use core_test_support::runtime_auth::PROBE_SERVER;
|
||||
use core_test_support::runtime_auth::run_harness_through_proxy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(
|
||||
json!({
|
||||
"iss": "https://auth.openai.com/", "session_id": "memory-login",
|
||||
"https://api.openai.com/auth": {"user_id": "actor", "chatgpt_account_id": "account_id"}
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
let token = format!("header.{claims}.signature");
|
||||
if let Ok(server) = std::env::var(PROBE_SERVER) {
|
||||
let credentials =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::from_external_chatgpt_tokens(
|
||||
&token,
|
||||
"account_id",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?);
|
||||
let runtime = Arc::new(RuntimeAuthManager::new(
|
||||
Arc::clone(&credentials),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: uuid::Uuid::nil(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: Some("codex".into()),
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
"https://auth.openai.com/agent/register".parse()?,
|
||||
));
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let auth = ProviderAuthContext {
|
||||
credentials: Arc::clone(&credentials),
|
||||
runtime_auth: Some((Arc::clone(&runtime), mode)),
|
||||
};
|
||||
for base_url in [
|
||||
"https://chatgpt.com/backend-api".to_owned(),
|
||||
format!("{server}/custom/backend-api"),
|
||||
] {
|
||||
let model_server = MockServer::start().await;
|
||||
let home = Arc::new(TempDir::new()?);
|
||||
let mut test = test_codex()
|
||||
.with_home(Arc::clone(&home))
|
||||
.with_auth(CodexAuth::from_api_key("ambient-key"))
|
||||
.with_config(|config| {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::Sqlite)
|
||||
.expect("enable state database");
|
||||
config.memories = startup_test_memories_config();
|
||||
config.memories.version = codex_protocol::MemoryVersion::V1;
|
||||
config.memories.dual_write = false;
|
||||
})
|
||||
.build(&model_server)
|
||||
.await?;
|
||||
test.config.chatgpt_base_url = base_url;
|
||||
test.codex.thread_extension_data().insert(auth.clone());
|
||||
let db = test.codex.state_db().expect("startup state database");
|
||||
seed_stage1_output(
|
||||
db.as_ref(),
|
||||
home.path(),
|
||||
chrono::Utc::now(),
|
||||
"source memory",
|
||||
"source summary",
|
||||
"quota-auth",
|
||||
)
|
||||
.await?;
|
||||
let root = home.path().join("memories");
|
||||
tokio::fs::create_dir_all(&root).await?;
|
||||
seed_required_memory_artifacts(&root).await?;
|
||||
let phase2 = mount_sse_once(
|
||||
&model_server,
|
||||
sse(vec![
|
||||
ev_response_created("quota-consolidation"),
|
||||
ev_assistant_message("quota-result", "memory complete"),
|
||||
ev_completed("quota-consolidation"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
trigger_memories_startup(&test).await;
|
||||
// Consolidation starts only after the startup quota request finishes.
|
||||
wait_for_single_request(&phase2).await;
|
||||
shutdown_test_codex(&test).await?;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/agent/register"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-memory", "agent_host_id": "host",
|
||||
"actor": {"kind": "chatgpt", "user_id": "actor", "account_id": "account_id"}
|
||||
})))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let quota = json!({"plan_type": "plus", "rate_limit": {
|
||||
"allowed": true, "limit_reached": false,
|
||||
"primary_window": {"used_percent": 0, "limit_window_seconds": 300,
|
||||
"reset_after_seconds": 60, "reset_at": 2000000000}
|
||||
}});
|
||||
for url in ["/backend-api/wham/usage", "/custom/backend-api/wham/usage"] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path(url))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(quota.clone()))
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
run_harness_through_proxy(
|
||||
&server,
|
||||
"startup_tests::memories_startup_uses_thread_runtime_and_keeps_custom_destinations_independent",
|
||||
/*realtime_target*/ None,
|
||||
)
|
||||
.await?;
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let quota_requests = requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path() == "/backend-api/wham/usage")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(quota_requests.len(), 2);
|
||||
let mut dual = 0;
|
||||
for request in quota_requests {
|
||||
assert_eq!(request.headers["chatgpt-account-id"], "account_id");
|
||||
let authorization = request.headers["authorization"].to_str()?;
|
||||
let proof = if let Some(proof) = request.headers.get("x-openai-agent-assertion") {
|
||||
dual += 1;
|
||||
assert_eq!(authorization, format!("Bearer {token}"));
|
||||
proof.to_str()?
|
||||
} else {
|
||||
authorization.strip_prefix("AgentAssertion ").unwrap()
|
||||
};
|
||||
let payload: serde_json::Value = serde_json::from_slice(
|
||||
&base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(proof.split('.').nth(/*n*/ 2).unwrap())?,
|
||||
)?;
|
||||
assert_eq!(payload["runtime_agent_instance"], "runtime-memory");
|
||||
}
|
||||
assert_eq!(dual, 1);
|
||||
for request in requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path().starts_with("/custom/"))
|
||||
{
|
||||
assert_eq!(request.headers["authorization"], format!("Bearer {token}"));
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user