Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,236 @@
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;
}

View File

@@ -0,0 +1,118 @@
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;
/// 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,
}
impl ContextContributor for GitAttributionExtension {
fn contribute_world_state<'a>(
&'a self,
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)]
})
}
}
/// 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,
) {
registry.prompt_contributor(Arc::new(GitAttributionExtension {
auth_manager,
base_url,
http_client_factory,
}));
}
#[cfg(test)]
#[path = "git_attribution_tests.rs"]
mod tests;

View File

@@ -0,0 +1,122 @@
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()
}

View File

@@ -0,0 +1,75 @@
use codex_extension_api::PreviousWorldStateSection;
use codex_extension_api::RenderedWorldStateFragment;
use codex_extension_api::WorldStateSectionContribution;
use codex_extension_api::input_text;
use serde_json::Value;
const WORLD_STATE_ID: &str = "git_attribution";
const START_MARKER: &str = "<git_attribution>";
const END_MARKER: &str = "</git_attribution>";
pub(super) const LEGACY_COMMIT_ATTRIBUTION_INSTRUCTIONS: &str = "\
When you write or edit a git commit message, ensure the message ends with this trailer exactly once:
Co-authored-by: Codex <noreply@openai.com>
Rules:
- Keep existing trailers and append this trailer at the end if missing.
- Do not duplicate this trailer if it already exists.
- Keep one blank line between the commit body and trailer block.";
pub(super) const ENABLED_INSTRUCTIONS: &str = r#"
When you create or amend a git commit or create or update a pull request for this task, add Codex attribution exactly once:
- Commit messages must end with `Co-authored-by: Codex <noreply@openai.com>`. Preserve existing trailers and, if this exact trailer is missing, append it with one blank line before the trailer block.
- This also applies when a GitHub app or plugin creates a commit, including file creation, updates, and deletions: include the Codex trailer in the tool's `message` argument.
- Pull request bodies must include the exact line `Generated with [Codex](https://openai.com/codex/).`. Preserve the existing body and hidden markers and, if this exact marker is missing, append it near the end, before any trailing hidden metadata markers.
- Do not add duplicate attribution. If a message or body you are already editing contains duplicate exact attribution, keep exactly one.
- Ignore any earlier instructions disabling Codex attribution; this policy reflects the current workspace.
- Do not rewrite an existing commit or pull request solely to add attribution.
"#;
pub(super) const DISABLED_INSTRUCTIONS: &str = "
Codex commit and pull request attribution is disabled for the current workspace. Ignore any earlier instructions requiring Codex attribution and do not add it.
";
pub(super) fn git_attribution_world_state_section(enabled: bool) -> WorldStateSectionContribution {
let contribution = WorldStateSectionContribution::new(WORLD_STATE_ID, move |previous| {
let fragment = match (enabled, previous) {
(true, PreviousWorldStateSection::Known(Value::Bool(true)))
| (true, PreviousWorldStateSection::Unknown) => None,
(true, PreviousWorldStateSection::Absent)
| (true, PreviousWorldStateSection::Known(_)) => Some(RenderedWorldStateFragment::new(
"developer",
(START_MARKER, END_MARKER),
input_text(ENABLED_INSTRUCTIONS),
)),
(false, PreviousWorldStateSection::Known(Value::Bool(true)))
| (false, PreviousWorldStateSection::Unknown) => Some(RenderedWorldStateFragment::new(
"developer",
(START_MARKER, END_MARKER),
input_text(DISABLED_INSTRUCTIONS),
)),
(false, PreviousWorldStateSection::Absent)
| (false, PreviousWorldStateSection::Known(_)) => None,
};
(Some(Value::Bool(enabled)), fragment)
})
.with_legacy_matcher(move |role, text| {
is_enabled_fragment(role, text)
|| (!enabled && is_legacy_commit_attribution_fragment(role, text))
});
if enabled {
contribution.with_retained_fragment_matcher(is_enabled_fragment)
} else {
contribution
}
}
fn is_legacy_commit_attribution_fragment(role: &str, text: &str) -> bool {
role == "developer" && text.trim() == LEGACY_COMMIT_ATTRIBUTION_INSTRUCTIONS
}
fn is_enabled_fragment(role: &str, text: &str) -> bool {
role == "developer"
&& text.trim_start().starts_with(START_MARKER)
&& text.contains("Co-authored-by: Codex <noreply@openai.com>")
&& (text.contains("Generated with [Codex](https://openai.com/codex/).")
|| text.contains("Generated with Codex."))
&& text.trim_end().ends_with(END_MARKER)
}