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,236 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use tokio::sync::Notify;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
use super::policy::resolve_attribution_policy;
|
||||
|
||||
fn enterprise_auth_manager() -> Arc<AuthManager> {
|
||||
AuthManager::from_auth_for_testing(enterprise_auth("workspace-123"))
|
||||
}
|
||||
|
||||
fn http_client_factory() -> HttpClientFactory {
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
}
|
||||
|
||||
fn enterprise_auth(account_id: &str) -> CodexAuth {
|
||||
CodexAuth::from_external_chatgpt_tokens("e30.e30.c2ln", account_id, Some("enterprise"))
|
||||
.expect("fake ChatGPT auth should parse")
|
||||
}
|
||||
|
||||
struct StaticExternalAuth(CodexAuth);
|
||||
|
||||
impl ExternalAuth for StaticExternalAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
|
||||
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
async fn set_auth(auth_manager: &AuthManager, account_id: &str) {
|
||||
auth_manager
|
||||
.set_external_auth(Arc::new(StaticExternalAuth(enterprise_auth(account_id))))
|
||||
.await
|
||||
.expect("auth refresh should succeed");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn policy_resolution_recovers_after_unauthorized() {
|
||||
let server = MockServer::start().await;
|
||||
let request_count = Arc::new(AtomicUsize::new(0));
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/wham/settings/user"))
|
||||
.respond_with({
|
||||
let request_count = request_count.clone();
|
||||
move |_request: &wiremock::Request| {
|
||||
if request_count.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
ResponseTemplate::new(401)
|
||||
} else {
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_json(serde_json::json!({"commit_attribution_enabled": true}))
|
||||
}
|
||||
}
|
||||
})
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let auth_manager = enterprise_auth_manager();
|
||||
set_auth(auth_manager.as_ref(), "workspace-123").await;
|
||||
|
||||
let policy = resolve_attribution_policy(
|
||||
&auth_manager,
|
||||
&format!("{}/backend-api", server.uri()),
|
||||
&http_client_factory(),
|
||||
/*runtime_auth*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("policy resolution should not time out")
|
||||
.expect("policy should resolve after auth recovery");
|
||||
|
||||
assert!(policy.enabled);
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 2);
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn policy_resolution_retries_after_auth_refresh() {
|
||||
let server = MockServer::start().await;
|
||||
let request_started = Arc::new(Notify::new());
|
||||
let request_count = Arc::new(AtomicUsize::new(0));
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/wham/settings/user"))
|
||||
.respond_with({
|
||||
let request_started = request_started.clone();
|
||||
let request_count = request_count.clone();
|
||||
move |_request: &wiremock::Request| match request_count.fetch_add(1, Ordering::SeqCst) {
|
||||
0 => {
|
||||
request_started.notify_one();
|
||||
ResponseTemplate::new(200)
|
||||
.set_delay(Duration::from_millis(100))
|
||||
.set_body_json(serde_json::json!({
|
||||
"commit_attribution_enabled": true,
|
||||
}))
|
||||
}
|
||||
1 => ResponseTemplate::new(401),
|
||||
_ => ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"commit_attribution_enabled": true,
|
||||
})),
|
||||
}
|
||||
})
|
||||
.expect(3)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let auth_manager = enterprise_auth_manager();
|
||||
let resolve = tokio::spawn({
|
||||
let auth_manager = auth_manager.clone();
|
||||
let base_url = format!("{}/backend-api", server.uri());
|
||||
async move {
|
||||
resolve_attribution_policy(
|
||||
&auth_manager,
|
||||
&base_url,
|
||||
&http_client_factory(),
|
||||
/*runtime_auth*/ None,
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
});
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(5), request_started.notified())
|
||||
.await
|
||||
.expect("first settings request should start");
|
||||
set_auth(auth_manager.as_ref(), "workspace-456").await;
|
||||
|
||||
assert!(
|
||||
resolve
|
||||
.await
|
||||
.expect("policy task should complete")
|
||||
.expect("policy should resolve after refresh")
|
||||
.enabled
|
||||
);
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
struct RotatingExternalAuth(AtomicUsize);
|
||||
|
||||
impl ExternalAuth for RotatingExternalAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async {
|
||||
let generation = self.0.load(Ordering::SeqCst);
|
||||
CodexAuth::from_external_chatgpt_tokens(
|
||||
&format!("e30.e30.signature-{generation}"),
|
||||
"workspace-123",
|
||||
Some("enterprise"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.0.fetch_add(/*val*/ 1, Ordering::SeqCst);
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn world_state_stops_after_rejected_refresh() {
|
||||
use codex_extension_api::ContextContributor;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::PreviousWorldStateSection;
|
||||
use codex_extension_api::WorldStateContributionInput;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/wham/settings/user"))
|
||||
.respond_with(ResponseTemplate::new(401))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let source = Arc::new(RotatingExternalAuth(AtomicUsize::new(/*v*/ 0)));
|
||||
let auth_manager = enterprise_auth_manager();
|
||||
auth_manager
|
||||
.set_external_auth(source.clone())
|
||||
.await
|
||||
.expect("external credentials should load");
|
||||
let extension = super::GitAttributionExtension {
|
||||
auth_manager,
|
||||
base_url: format!("{}/backend-api", server.uri()),
|
||||
http_client_factory: http_client_factory(),
|
||||
};
|
||||
let model_info = serde_json::from_value(serde_json::json!({
|
||||
"slug": "test-model",
|
||||
"display_name": "Test model",
|
||||
"supported_reasoning_levels": [],
|
||||
"shell_type": "shell_command",
|
||||
"visibility": "list",
|
||||
"supported_in_api": true,
|
||||
"priority": 0,
|
||||
"support_verbosity": false,
|
||||
"truncation_policy": {"mode": "bytes", "limit": 10000},
|
||||
"experimental_supported_tools": []
|
||||
}))
|
||||
.expect("model metadata should parse");
|
||||
let store = ExtensionData::new("test");
|
||||
let sections = tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
extension.contribute_world_state(WorldStateContributionInput {
|
||||
thread_id: Default::default(),
|
||||
turn_id: "turn",
|
||||
model_info: &model_info,
|
||||
environments: &[],
|
||||
extension_metrics: None,
|
||||
session_store: &store,
|
||||
thread_store: &store,
|
||||
turn_store: &store,
|
||||
step_store: &store,
|
||||
previous_world_state: None,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect("an optional settings failure must not keep refreshing credentials");
|
||||
assert_eq!(source.0.load(Ordering::SeqCst), 1);
|
||||
assert!(sections.iter().all(|section| {
|
||||
section
|
||||
.render_diff(PreviousWorldStateSection::Absent)
|
||||
.1
|
||||
.is_none()
|
||||
}));
|
||||
server.verify().await;
|
||||
}
|
||||
@@ -1,118 +1,38 @@
|
||||
mod policy;
|
||||
mod world_state;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_extension_api::ContextContributor;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::WorldStateContributionInput;
|
||||
use codex_extension_api::WorldStateSectionContribution;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AuthManager;
|
||||
use codex_model_provider::ProviderAuthContext;
|
||||
|
||||
use crate::policy::GitAttributionPolicy;
|
||||
use crate::policy::GitAttributionRetry;
|
||||
use crate::policy::POLICY_RETRY_DELAY;
|
||||
use crate::policy::auth_generation;
|
||||
use crate::policy::cached_attribution_policy;
|
||||
use crate::policy::resolve_attribution_policy;
|
||||
use crate::policy::retry_deferred;
|
||||
use crate::world_state::git_attribution_world_state_section;
|
||||
|
||||
/// Local default for commit and pull request attribution. aKode never fetches a
|
||||
/// remote workspace policy, so attribution stays disabled.
|
||||
const ATTRIBUTION_ENABLED_BY_DEFAULT: bool = false;
|
||||
|
||||
/// Contributes model instructions for agent-created git commits and pull requests.
|
||||
#[derive(Clone)]
|
||||
struct GitAttributionExtension {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
base_url: String,
|
||||
http_client_factory: HttpClientFactory,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
impl ContextContributor for GitAttributionExtension {
|
||||
fn contribute_world_state<'a>(
|
||||
&'a self,
|
||||
input: WorldStateContributionInput<'a>,
|
||||
_input: WorldStateContributionInput<'a>,
|
||||
) -> ExtensionFuture<'a, Vec<WorldStateSectionContribution>> {
|
||||
Box::pin(async move {
|
||||
let auth_context = input.thread_store.get::<ProviderAuthContext>();
|
||||
let auth_manager = auth_context
|
||||
.as_ref()
|
||||
.map_or(&self.auth_manager, |context| &context.credentials);
|
||||
let runtime_auth = auth_context
|
||||
.as_ref()
|
||||
.and_then(|context| context.runtime_auth.as_ref());
|
||||
let enabled = loop {
|
||||
let current_auth_generation = auth_generation(auth_manager.as_ref());
|
||||
let policy = match cached_attribution_policy(
|
||||
input.thread_store,
|
||||
input.turn_store,
|
||||
current_auth_generation,
|
||||
) {
|
||||
Some(policy) => policy,
|
||||
None if retry_deferred(input.thread_store, current_auth_generation) => {
|
||||
GitAttributionPolicy {
|
||||
auth_generation: current_auth_generation,
|
||||
enabled: false,
|
||||
}
|
||||
}
|
||||
None => {
|
||||
match resolve_attribution_policy(
|
||||
auth_manager,
|
||||
&self.base_url,
|
||||
&self.http_client_factory,
|
||||
runtime_auth,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(policy)) => {
|
||||
input.thread_store.insert(policy.clone());
|
||||
policy
|
||||
}
|
||||
Ok(None) => {
|
||||
input.turn_store.insert(GitAttributionPolicy {
|
||||
auth_generation: current_auth_generation,
|
||||
enabled: false,
|
||||
});
|
||||
break false;
|
||||
}
|
||||
Err(_) => {
|
||||
let auth_generation = auth_generation(auth_manager.as_ref());
|
||||
if auth_generation == current_auth_generation {
|
||||
input.thread_store.insert(GitAttributionRetry {
|
||||
auth_generation,
|
||||
retry_at: Instant::now() + POLICY_RETRY_DELAY,
|
||||
});
|
||||
}
|
||||
break false;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if policy.auth_generation == auth_generation(auth_manager.as_ref()) {
|
||||
break policy.enabled;
|
||||
}
|
||||
};
|
||||
vec![git_attribution_world_state_section(enabled)]
|
||||
})
|
||||
let enabled = self.enabled;
|
||||
Box::pin(async move { vec![git_attribution_world_state_section(enabled)] })
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the git-attribution contributor into the extension registry.
|
||||
pub fn install<C: Sync>(
|
||||
registry: &mut ExtensionRegistryBuilder<C>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
base_url: String,
|
||||
http_client_factory: HttpClientFactory,
|
||||
) {
|
||||
pub fn install<C: Sync>(registry: &mut ExtensionRegistryBuilder<C>) {
|
||||
registry.prompt_contributor(Arc::new(GitAttributionExtension {
|
||||
auth_manager,
|
||||
base_url,
|
||||
http_client_factory,
|
||||
enabled: ATTRIBUTION_ENABLED_BY_DEFAULT,
|
||||
}));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "git_attribution_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_backend_client::Client as BackendClient;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct GitAttributionPolicy {
|
||||
pub(super) auth_generation: u64,
|
||||
pub(super) enabled: bool,
|
||||
}
|
||||
|
||||
pub(super) struct GitAttributionRetry {
|
||||
pub(super) auth_generation: u64,
|
||||
pub(super) retry_at: Instant,
|
||||
}
|
||||
|
||||
pub(super) fn retry_deferred(thread_store: &ExtensionData, auth_generation: u64) -> bool {
|
||||
thread_store
|
||||
.get::<GitAttributionRetry>()
|
||||
.is_some_and(|retry| {
|
||||
retry.auth_generation == auth_generation && retry.retry_at > Instant::now()
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn cached_attribution_policy(
|
||||
thread_store: &ExtensionData,
|
||||
turn_store: &ExtensionData,
|
||||
auth_generation: u64,
|
||||
) -> Option<GitAttributionPolicy> {
|
||||
thread_store
|
||||
.get::<GitAttributionPolicy>()
|
||||
.filter(|policy| policy.auth_generation == auth_generation)
|
||||
.or_else(|| {
|
||||
turn_store
|
||||
.get::<GitAttributionPolicy>()
|
||||
.filter(|policy| policy.auth_generation == auth_generation)
|
||||
})
|
||||
.map(|policy| policy.as_ref().clone())
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
const POLICY_RESOLUTION_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
#[cfg(test)]
|
||||
const POLICY_RESOLUTION_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
pub(super) const POLICY_RETRY_DELAY: Duration = Duration::from_secs(30);
|
||||
|
||||
pub(super) async fn resolve_attribution_policy(
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
base_url: &str,
|
||||
http_client_factory: &HttpClientFactory,
|
||||
runtime_auth: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
) -> Result<Option<GitAttributionPolicy>, tokio::time::error::Elapsed> {
|
||||
timeout(POLICY_RESOLUTION_TIMEOUT, async {
|
||||
let mut recovery_generation = auth_generation(auth_manager);
|
||||
let mut auth_recovery = auth_manager.unauthorized_recovery();
|
||||
loop {
|
||||
let auth_generation_at_start = auth_generation(auth_manager);
|
||||
if auth_generation_at_start != recovery_generation {
|
||||
auth_recovery = auth_manager.unauthorized_recovery();
|
||||
recovery_generation = auth_generation_at_start;
|
||||
}
|
||||
let auth = auth_manager.auth_with_http_client_factory().await;
|
||||
if auth_generation(auth_manager) != auth_generation_at_start {
|
||||
continue;
|
||||
}
|
||||
let enabled = match auth {
|
||||
Some((auth, captured_factory)) if auth.uses_codex_backend() => {
|
||||
let policy = http_client_factory
|
||||
.network_policy()
|
||||
.clone()
|
||||
.with_account_binding(captured_factory.network_policy())?;
|
||||
let client = BackendClient::from_auth_with_runtime(
|
||||
base_url,
|
||||
&auth,
|
||||
http_client_factory.clone().with_network_policy(policy),
|
||||
runtime_auth,
|
||||
/*headers*/ &Default::default(),
|
||||
)
|
||||
.await;
|
||||
if auth_generation(auth_manager) != auth_generation_at_start {
|
||||
continue;
|
||||
}
|
||||
let settings = client.ok()?.get_user_settings().await;
|
||||
if auth_generation(auth_manager) != auth_generation_at_start {
|
||||
continue;
|
||||
}
|
||||
match settings {
|
||||
Ok(settings) => Some(settings.commit_attribution_enabled),
|
||||
Err(err) if err.is_unauthorized() && auth_recovery.has_next() => {
|
||||
if auth_recovery.next().await.is_ok() {
|
||||
recovery_generation = auth_generation(auth_manager);
|
||||
continue;
|
||||
}
|
||||
None
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
Some(_) | None => Some(false),
|
||||
};
|
||||
if auth_generation(auth_manager) != auth_generation_at_start {
|
||||
continue;
|
||||
}
|
||||
return enabled.map(|enabled| GitAttributionPolicy {
|
||||
auth_generation: auth_generation_at_start,
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) fn auth_generation(auth_manager: &AuthManager) -> u64 {
|
||||
*auth_manager.auth_change_receiver().borrow()
|
||||
}
|
||||
Reference in New Issue
Block a user