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,77 @@
use std::path::PathBuf;
use clap::Parser;
use codex_core::config::Config;
use codex_git_utils::ApplyGitRequest;
use codex_git_utils::apply_git_patch;
use codex_utils_cli::CliConfigOverrides;
use crate::get_task::GetTaskResponse;
use crate::get_task::OutputItem;
use crate::get_task::PrOutputItem;
use crate::get_task::get_task;
/// Applies the latest diff from a Codex agent task.
#[derive(Debug, Parser)]
pub struct ApplyCommand {
pub task_id: String,
#[clap(flatten)]
pub config_overrides: CliConfigOverrides,
}
pub async fn run_apply_command(
apply_cli: ApplyCommand,
cwd: Option<PathBuf>,
) -> anyhow::Result<()> {
let config = Config::load_with_cli_overrides(
apply_cli
.config_overrides
.parse_overrides()
.map_err(anyhow::Error::msg)?,
)
.await?;
let task_response = get_task(&config, apply_cli.task_id).await?;
apply_diff_from_task(task_response, cwd).await
}
pub async fn apply_diff_from_task(
task_response: GetTaskResponse,
cwd: Option<PathBuf>,
) -> anyhow::Result<()> {
let diff_turn = match task_response.current_diff_task_turn {
Some(turn) => turn,
None => anyhow::bail!("No diff turn found"),
};
let output_diff = diff_turn.output_items.iter().find_map(|item| match item {
OutputItem::Pr(PrOutputItem { output_diff }) => Some(output_diff),
_ => None,
});
match output_diff {
Some(output_diff) => apply_diff(&output_diff.diff, cwd).await,
None => anyhow::bail!("No PR output item found"),
}
}
async fn apply_diff(diff: &str, cwd: Option<PathBuf>) -> anyhow::Result<()> {
let cwd = cwd.unwrap_or(std::env::current_dir().unwrap_or_else(|_| std::env::temp_dir()));
let req = ApplyGitRequest {
cwd,
diff: diff.to_string(),
revert: false,
preflight: false,
};
let res = apply_git_patch(&req)?;
if res.exit_code != 0 {
anyhow::bail!(
"Git apply failed (applied={}, skipped={}, conflicts={})\nstdout:\n{}\nstderr:\n{}",
res.applied_paths.len(),
res.skipped_paths.len(),
res.conflicted_paths.len(),
res.stdout,
res.stderr
);
}
println!("Successfully applied diff");
Ok(())
}

View File

@@ -0,0 +1,242 @@
use codex_core::config::Config;
use codex_features::Feature;
use codex_features::RuntimeAuthMode;
use codex_http_client::HttpClient;
use codex_http_client::HttpClientFactory;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::default_client::RESIDENCY_HEADER_NAME;
use codex_login::default_client::create_client_with_chatgpt_cookies;
use codex_login::default_client::default_headers;
use codex_runtime_agent_instance::RuntimeAuthManager;
use std::sync::Arc;
use anyhow::Context;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::sync::LazyLock;
use std::sync::Mutex;
use std::time::Duration;
const OAI_PRODUCT_SKU_HEADER: &str = "OAI-Product-Sku";
const CODEX_PRODUCT_SKU: &str = "codex";
struct CachedChatGptClient {
factory: HttpClientFactory,
residency: Option<Vec<u8>>,
client: HttpClient,
}
static CHATGPT_CLIENT: LazyLock<Mutex<Option<CachedChatGptClient>>> =
LazyLock::new(|| Mutex::new(None));
/// Reuse the client and cookies without changing the caller's captured account policy.
fn chatgpt_client(factory: HttpClientFactory) -> HttpClient {
let residency = default_headers()
.get(RESIDENCY_HEADER_NAME)
.map(|value| value.as_bytes().to_vec());
let mut cached = CHATGPT_CLIENT
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(cached_client) = cached.as_ref()
&& cached_client.factory == factory
&& cached_client.residency == residency
{
return cached_client.client.clone();
}
let client = create_client_with_chatgpt_cookies(&factory);
*cached = Some(CachedChatGptClient {
factory,
residency,
client: client.clone(),
});
client
}
/// Make a GET request to the ChatGPT backend API.
pub(crate) async fn chatgpt_get_request<T: DeserializeOwned>(
config: &Config,
path: String,
) -> anyhow::Result<T> {
let mut config = config.clone();
let (auth, runtime) = standalone_auth(&mut config).await?;
chatgpt_get_request_with_timeout(
&config,
&auth,
runtime.as_ref(),
path,
/*timeout*/ None,
)
.await
}
pub(crate) async fn standalone_auth(
config: &mut Config,
) -> anyhow::Result<(
CodexAuth,
Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
)> {
// Standalone commands create one owner. Freeze the caller's account policy before loading
// credentials; this temporary manager does not own later account changes.
config.application_network_policy = config
.application_network_policy
.clone()
.for_current_account();
if config.features.enabled(Feature::RuntimeAgentInstances) {
codex_model_provider::validate_runtime_destination(Some(&config.chatgpt_base_url))?;
}
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?;
let runtime = if config.features.enabled(Feature::RuntimeAgentInstances)
&& codex_runtime_agent_instance::is_openai_api_url(&config.chatgpt_base_url)
{
let installation_id = codex_core::resolve_installation_id(&config.codex_home).await?;
codex_core::build_runtime_auth_manager(config, auth_manager.clone(), &installation_id)
.map(|runtime| (runtime, config.runtime_auth_mode))
} else {
None
};
let auth = auth_manager
.auth()
.await
.ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?;
Ok((auth, runtime))
}
pub(crate) async fn chatgpt_get_request_with_timeout<T: DeserializeOwned>(
config: &Config,
auth: &CodexAuth,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
path: String,
timeout: Option<Duration>,
) -> anyhow::Result<T> {
let chatgpt_base_url = &config.chatgpt_base_url;
anyhow::ensure!(
auth.uses_codex_backend(),
"ChatGPT backend requests require Codex backend auth"
);
anyhow::ensure!(
auth.get_account_id().is_some(),
"ChatGPT account ID not available, please re-run `codex login`"
);
let url = format!(
"{}/{}",
chatgpt_base_url.trim_end_matches('/'),
path.trim_start_matches('/')
);
let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?;
let mut request = client
.get(&url)
.headers(default_headers())
.headers(
request_auth
.auth
.apply_auth_headers(Default::default())
.await?,
)
.header(OAI_PRODUCT_SKU_HEADER, CODEX_PRODUCT_SKU)
.header("Content-Type", "application/json");
if let Some(timeout) = timeout {
request = request.timeout(timeout);
}
let response = request.send().await.context("Failed to send request")?;
if response.status().is_success() {
let result: T = response
.json()
.await
.context("Failed to parse JSON response")?;
Ok(result)
} else {
let status = response.status();
let body = response.text().await.unwrap_or_default();
anyhow::bail!("Request failed with status {status}: {body}")
}
}
/// Make a POST request to the ChatGPT backend API with an already-captured auth identity.
///
/// Callers must capture `auth` and `config.application_network_policy` together and preserve
/// that snapshot rather than reacquiring either while the request is in flight.
pub(crate) async fn chatgpt_post_request_with_timeout<
TResponse: DeserializeOwned,
TRequest: Serialize + ?Sized,
>(
config: &Config,
auth: &CodexAuth,
path: String,
body: &TRequest,
timeout: Duration,
product_sku: &str,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
) -> anyhow::Result<TResponse> {
anyhow::ensure!(
auth.uses_codex_backend(),
"ChatGPT backend requests require Codex backend auth"
);
anyhow::ensure!(
auth.get_account_id().is_some(),
"ChatGPT account ID not available, please re-run codex login"
);
let url = format!(
"{}/{}",
config.chatgpt_base_url.trim_end_matches('/'),
path.trim_start_matches('/')
);
let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?;
let response = client
.post(&url)
.headers(default_headers())
.headers(
request_auth
.auth
.apply_auth_headers(Default::default())
.await?,
)
.header(OAI_PRODUCT_SKU_HEADER, product_sku)
.header("Content-Type", "application/json")
.timeout(timeout)
.json(body)
.send()
.await
.context("Failed to send request")?;
if response.status().is_success() {
response
.json()
.await
.context("Failed to parse JSON response")
} else {
let status = response.status();
let body = response.text().await.unwrap_or_default();
anyhow::bail!("Request failed with status {status}: {body}")
}
}
/// Keep request credentials and the transport bound to the same account snapshot.
async fn prepare_client_auth(
config: &Config,
auth: &CodexAuth,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
url: &str,
) -> anyhow::Result<(HttpClient, codex_model_provider::ResolvedProviderAuth)> {
if runtime.is_some() {
codex_model_provider::validate_runtime_destination(Some(url))?;
}
let resolved = codex_model_provider::auth_provider_for_request(
auth,
runtime,
/*headers*/ &Default::default(),
)
.await?;
let factory = resolved.bind_http_client_factory(config.http_client_factory())?;
let client = chatgpt_client(factory);
Ok((client, resolved))
}
#[cfg(test)]
#[path = "chatgpt_client_runtime_auth_tests.rs"]
mod runtime_auth_tests;

View File

@@ -0,0 +1,321 @@
//! Test captured ChatGPT credentials and runtime proofs on helper requests.
use super::*;
use base64::Engine;
use codex_features::RuntimeAuthMode;
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 pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::HashSet;
use std::sync::Arc;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::path;
#[tokio::test]
async fn helpers_use_captured_auth_and_strip_cross_origin_proofs() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let redirected = MockServer::start().await;
Mock::given(path("/"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
.expect(1)
.mount(&redirected)
.await;
Mock::given(path("/agent/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-chatgpt", "agent_host_id": "host-a",
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "workspace-a"},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(path("/data"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
.expect(2)
.mount(&server)
.await;
Mock::given(path("/redirect"))
.respond_with(ResponseTemplate::new(307).insert_header("location", redirected.uri()))
.expect(1)
.mount(&server)
.await;
Mock::given(path("/ps/apps/batch"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"apps": [{"id": "calendar", "name": "Calendar", "description": "Calendar metadata"}],
})))
.expect(1).mount(&server).await;
let home = tempfile::TempDir::new().unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = server.uri();
let token = actor_token();
let auth = CodexAuth::from_external_chatgpt_tokens(
&token,
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let runtime = (
Arc::new(RuntimeAuthManager::new(
AuthManager::from_auth_for_testing(auth.clone()),
AgentHostAuthorization::InstallationId {
installation_id: uuid::Uuid::nil(),
},
RuntimeRegistrationMetadata {
harness: Some("codex".into()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/agent/register", server.uri()).parse().unwrap(),
)),
mode,
);
// No saved auth exists: these helpers must use the supplied snapshot, not reload auth.
let get: serde_json::Value = chatgpt_get_request_with_timeout(
&config,
&auth,
Some(&runtime),
"data".into(),
/*timeout*/ None,
)
.await
.unwrap();
let post: serde_json::Value = chatgpt_post_request_with_timeout(
&config,
&auth,
"data".into(),
&json!({}),
Duration::from_secs(10),
"codex",
Some(&runtime),
)
.await
.unwrap();
let metadata = crate::connectors::read_connector_metadata(
&config,
&auth,
Some(&runtime),
&["calendar".into()],
/*include_tools*/ false,
)
.await
.unwrap();
assert_eq!(metadata.apps.len(), 1);
assert_eq!(metadata.apps[0].name, "Calendar");
assert!(metadata.missing_app_ids.is_empty());
assert_eq!(get, json!({"ok": true}));
assert_eq!(post, get);
let redirected_result = chatgpt_get_request_with_timeout::<serde_json::Value>(
&config,
&auth,
Some(&runtime),
"redirect".into(),
/*timeout*/ None,
)
.await
.unwrap();
assert_eq!(redirected_result, get);
let forwarded = redirected.received_requests().await.unwrap();
assert_eq!(forwarded.len(), 1);
assert!(!forwarded[0].headers.contains_key("authorization"));
assert!(
!forwarded[0]
.headers
.contains_key("x-openai-agent-assertion")
);
redirected.verify().await;
let requests = server.received_requests().await.unwrap();
let metadata_request = requests
.iter()
.find(|request| request.url.path() == "/ps/apps/batch")
.unwrap();
assert_eq!(
metadata_request.headers["authorization"],
format!("Bearer {token}")
);
assert!(
!metadata_request
.headers
.contains_key("x-openai-agent-assertion")
);
let proofs: HashSet<_> = requests
.iter()
.filter(|r| !matches!(r.url.path(), "/agent/register" | "/ps/apps/batch"))
.map(|r| {
assert_eq!(r.headers["chatgpt-account-id"], "workspace-a");
let authorization = r.headers["authorization"].to_str().unwrap();
match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(authorization, format!("Bearer {token}"));
r.headers["x-openai-agent-assertion"].to_str().unwrap()
}
RuntimeAuthMode::AssertionOnly => {
assert!(!r.headers.contains_key("x-openai-agent-assertion"));
authorization.strip_prefix("AgentAssertion ").unwrap()
}
}
})
.collect();
assert_eq!(proofs.len(), 3);
server.verify().await;
}
}
fn actor_token() -> String {
let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json!({
"iss": "https://auth.openai.com/", "session_id": "login-a",
"https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "workspace-a"},
}).to_string());
format!("header.{claims}.signature")
}
#[tokio::test]
async fn standalone_apply_keeps_custom_backend_auth_when_runtime_feature_is_enabled() {
let server = MockServer::start().await;
let token = actor_token();
Mock::given(path("/task"))
.and(wiremock::matchers::header(
"authorization",
format!("Bearer {token}"),
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
.expect(1)
.mount(&server)
.await;
let home = tempfile::TempDir::new().unwrap();
codex_login::auth::login_with_chatgpt_auth_tokens(
home.path(),
&token,
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = server.uri();
config
.features
.enable(Feature::RuntimeAgentInstances)
.unwrap();
let response: serde_json::Value = chatgpt_get_request(&config, "task".into()).await.unwrap();
assert_eq!(response, json!({"ok": true}));
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 1);
assert!(!requests[0].headers.contains_key("x-openai-agent-assertion"));
server.verify().await;
}
#[tokio::test]
async fn connector_requests_reject_unsupported_openai_destinations() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
for base_url in [
"http://chatgpt.com",
"https://future.openai.com/backend-api",
] {
let home = tempfile::TempDir::new().unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = base_url.to_string();
config.features.enable(Feature::Apps).unwrap();
let auth = CodexAuth::from_external_chatgpt_tokens(
&actor_token(),
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let runtime = (
Arc::new(RuntimeAuthManager::for_chatgpt(
AuthManager::from_auth_for_testing(auth.clone()),
uuid::Uuid::nil().to_string(),
base_url.to_string(),
RuntimeRegistrationMetadata {
harness: Some("codex".to_string()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
)),
mode,
);
// Keep a broken validation path from sending the test credential to the network.
let controller = codex_http_client::NetworkPolicyController::default();
config.application_network_policy = controller.policy();
assert!(controller.publish(
config.application_network_policy.revision(),
codex_http_client::DestinationPolicy::Restricted {
allowed_hosts: Default::default(),
},
));
let directory_error = crate::connectors::list_all_connectors_with_options(
&config,
Some(&auth),
Some(&runtime),
/*force_refetch*/ true,
&[],
)
.await
.expect_err("reject unsupported directory destination");
let metadata_error = crate::connectors::read_connector_metadata(
&config,
&auth,
Some(&runtime),
&["calendar".to_string()],
/*include_tools*/ false,
)
.await
.err()
.expect("reject unsupported metadata destination");
for error in [directory_error, metadata_error] {
assert!(
matches!(
error
.downcast_ref::<codex_protocol::error::CodexErr>()
.map(codex_protocol::error::CodexErr::details),
Some(codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_))
),
"{base_url} ({mode:?}): {error:#}",
);
}
}
}
}
#[tokio::test]
async fn standalone_apply_rejects_unsupported_openai_destination() {
let home = tempfile::TempDir::new().unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = "https://future.openai.com/backend-api".into();
config
.features
.enable(Feature::RuntimeAgentInstances)
.unwrap();
let error = chatgpt_get_request::<serde_json::Value>(&config, "task".into())
.await
.unwrap_err();
assert!(matches!(
error
.downcast_ref::<codex_protocol::error::CodexErr>()
.map(codex_protocol::error::CodexErr::details),
Some(codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_))
));
}

View File

@@ -0,0 +1,523 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::time::Duration;
use crate::chatgpt_client::chatgpt_get_request_with_timeout;
use crate::chatgpt_client::chatgpt_post_request_with_timeout;
use codex_connectors::AppInfo;
use codex_connectors::AppToolPolicyEvaluator;
use codex_connectors::ConnectorDirectoryCacheContext;
use codex_connectors::ConnectorDirectoryCacheKey;
use codex_connectors::ConnectorMetadata;
use codex_connectors::ConnectorMetadataStore;
use codex_connectors::ConnectorToolSummary;
use codex_connectors::DirectoryListResponse;
use codex_connectors::merge::merge_connectors;
use codex_connectors::merge::merge_plugin_connectors;
use codex_core::config::Config;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options_and_status;
pub use codex_core::connectors::list_cached_accessible_connectors_from_mcp_tools;
use codex_features::RuntimeAuthMode;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_plugin::AppConnectorId;
use codex_runtime_agent_instance::RuntimeAuthManager;
use serde::Deserialize;
use serde::Serialize;
use std::sync::Arc;
const DIRECTORY_CONNECTORS_TIMEOUT: Duration = Duration::from_secs(60);
const CONNECTOR_METADATA_TIMEOUT: Duration = Duration::from_secs(60);
const DEFAULT_APPS_PRODUCT_SKU: &str = "codex";
async fn apps_enabled(config: &Config) -> anyhow::Result<bool> {
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?;
let auth = auth_manager.auth().await;
Ok(config
.features
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)))
}
pub async fn list_connectors(config: &Config) -> anyhow::Result<Vec<AppInfo>> {
if !apps_enabled(config).await? {
return Ok(Vec::new());
}
let (connectors_result, accessible_result) = tokio::join!(
list_all_connectors(config),
list_accessible_connectors_from_mcp_tools(config),
);
let connectors = connectors_result?;
let accessible = accessible_result?;
Ok(
AppToolPolicyEvaluator::new(&config.config_layer_stack).apply_app_enabled_state(
merge_connectors_with_accessible(
connectors, accessible, /*all_connectors_loaded*/ true,
),
),
)
}
pub async fn list_all_connectors(config: &Config) -> anyhow::Result<Vec<AppInfo>> {
if !apps_enabled(config).await? {
return Ok(Vec::new());
}
let mut config = config.clone();
let (auth, runtime) = crate::chatgpt_client::standalone_auth(&mut config).await?;
list_all_connectors_with_options(
&config,
Some(&auth),
runtime.as_ref(),
/*force_refetch*/ false,
&[],
)
.await
}
pub fn list_cached_all_connectors(
config: &Config,
auth: Option<&CodexAuth>,
plugin_apps: &[AppConnectorId],
) -> Option<Vec<AppInfo>> {
if !config
.features
.apps_enabled_for_auth(auth.is_some_and(CodexAuth::uses_codex_backend))
{
return Some(Vec::new());
}
let auth = auth?;
let cache_context = connector_directory_cache_context(config, auth);
let connectors = codex_connectors::cached_directory_connectors(&cache_context)?;
Some(merge_directory_and_plugin_connectors(
connectors.to_vec(),
plugin_apps,
))
}
pub async fn list_all_connectors_with_options(
config: &Config,
auth: Option<&CodexAuth>,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
force_refetch: bool,
plugin_apps: &[AppConnectorId],
) -> anyhow::Result<Vec<AppInfo>> {
if !config
.features
.apps_enabled_for_auth(auth.is_some_and(CodexAuth::uses_codex_backend))
{
return Ok(Vec::new());
}
let auth = auth.ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?;
let runtime = codex_model_provider::runtime_auth_for_url(runtime, &config.chatgpt_base_url)?;
let cache_context = connector_directory_cache_context(config, auth);
let connectors = codex_connectors::list_all_connectors_with_options(
cache_context,
auth.is_workspace_account(),
force_refetch,
|path| async move {
chatgpt_get_request_with_timeout::<DirectoryListResponse>(
config,
auth,
runtime,
path,
Some(DIRECTORY_CONNECTORS_TIMEOUT),
)
.await
},
)
.await?;
Ok(merge_directory_and_plugin_connectors(
connectors,
plugin_apps,
))
}
pub struct ConnectorMetadataReadResult {
pub apps: Vec<ConnectorMetadata>,
pub missing_app_ids: Vec<String>,
}
/// Reads display metadata without loading MCP connector tools or runtime state.
///
/// The store is created before awaiting the backend request, so a response that arrives after an
/// account or backend change can only commit to the scope under which it was requested.
/// Capture `auth` and `config.application_network_policy` together using
/// `AuthManager::auth_with_http_client_factory` so the request retains that account's policy.
pub async fn read_connector_metadata(
config: &Config,
auth: &CodexAuth,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
app_ids: &[String],
include_tools: bool,
) -> anyhow::Result<ConnectorMetadataReadResult> {
anyhow::ensure!(
auth.uses_codex_backend(),
"ChatGPT backend requests require Codex backend auth"
);
anyhow::ensure!(
auth.get_account_id().is_some(),
"ChatGPT account ID not available, please re-run codex login"
);
let runtime = codex_model_provider::runtime_auth_for_url(runtime, &config.chatgpt_base_url)?;
let store = ConnectorMetadataStore::new(
config.chatgpt_base_url.clone(),
auth.get_account_id(),
auth.get_chatgpt_user_id(),
auth.is_workspace_account(),
);
let mut metadata_by_id = store.fresh_records(app_ids, include_tools);
let missing_ids = app_ids
.iter()
.filter(|app_id| !metadata_by_id.contains_key(app_id.as_str()))
.cloned()
.collect::<Vec<_>>();
if !missing_ids.is_empty() {
let product_sku = config
.apps_mcp_product_sku
.as_deref()
.unwrap_or(DEFAULT_APPS_PRODUCT_SKU);
let response: GetAppsResponse = chatgpt_post_request_with_timeout(
config,
auth,
"/ps/apps/batch".to_string(),
&GetAppsRequest {
app_ids: &missing_ids,
include_tools,
},
CONNECTOR_METADATA_TIMEOUT,
product_sku,
runtime,
)
.await?;
let mut requested_ids = missing_ids.iter().cloned().collect::<HashSet<_>>();
let fetched = response
.apps
.into_iter()
.map(batch_app_to_metadata)
.filter(|metadata| requested_ids.remove(&metadata.id))
.collect::<Vec<_>>();
store.commit(&fetched);
metadata_by_id.extend(
fetched
.into_iter()
.map(|metadata| (metadata.id.clone(), metadata)),
);
}
let mut apps = Vec::new();
let mut missing_app_ids = Vec::new();
for app_id in app_ids {
if let Some(mut metadata) = metadata_by_id.remove(app_id) {
if !include_tools {
metadata.tool_summaries = None;
}
apps.push(metadata);
} else {
missing_app_ids.push(app_id.clone());
}
}
Ok(ConnectorMetadataReadResult {
apps,
missing_app_ids,
})
}
#[derive(Serialize)]
struct GetAppsRequest<'a> {
app_ids: &'a [String],
include_tools: bool,
}
#[derive(Deserialize)]
struct GetAppsResponse {
apps: Vec<BatchApp>,
}
/// The explicit metadata-only projection of Plugin Service's public app response.
///
/// Serde ignores all other backend fields, including full actions, model descriptions, and
/// runtime state.
#[derive(Deserialize)]
struct BatchApp {
id: String,
name: String,
description: Option<String>,
icon_url: Option<String>,
#[serde(default, rename = "icon_dark_url", alias = "icon_url_dark")]
icon_url_dark: Option<String>,
#[serde(default)]
distribution_channel: Option<String>,
#[serde(default)]
tools: Option<Vec<BatchAppToolSummary>>,
}
#[derive(Deserialize)]
struct BatchAppToolSummary {
name: String,
title: Option<String>,
description: String,
#[serde(default)]
is_enabled: Option<bool>,
#[serde(default)]
disabled_reason: Option<String>,
#[serde(default)]
is_read_only: bool,
}
fn batch_app_to_metadata(app: BatchApp) -> ConnectorMetadata {
let BatchApp {
id,
name,
description,
icon_url,
icon_url_dark,
distribution_channel,
tools,
} = app;
ConnectorMetadata {
id,
name,
description,
icon_url,
icon_url_dark,
distribution_channel,
tool_summaries: tools.map(|tools| {
tools
.into_iter()
.map(|tool| {
let BatchAppToolSummary {
name,
title,
description,
is_enabled,
disabled_reason,
is_read_only,
} = tool;
ConnectorToolSummary {
name,
title,
description,
is_enabled: is_enabled.unwrap_or(true),
disabled_reason,
is_read_only,
}
})
.collect()
}),
}
}
fn connector_directory_cache_context(
config: &Config,
auth: &CodexAuth,
) -> ConnectorDirectoryCacheContext {
ConnectorDirectoryCacheContext::new(
config.codex_home.to_path_buf(),
ConnectorDirectoryCacheKey::new(
config.chatgpt_base_url.clone(),
auth.get_account_id(),
auth.get_chatgpt_user_id(),
auth.is_workspace_account(),
),
)
}
fn merge_directory_and_plugin_connectors(
connectors: Vec<AppInfo>,
plugin_apps: &[AppConnectorId],
) -> Vec<AppInfo> {
merge_plugin_connectors(
connectors,
plugin_apps
.iter()
.map(|connector_id| connector_id.0.clone()),
)
}
pub fn connectors_for_plugin_apps(
connectors: Vec<AppInfo>,
plugin_apps: &[AppConnectorId],
) -> Vec<AppInfo> {
let connectors = merge_plugin_connectors(
connectors,
plugin_apps
.iter()
.map(|connector_id| connector_id.0.clone()),
);
let mut connectors_by_id = connectors
.into_iter()
.map(|connector| (connector.id.clone(), connector))
.collect::<HashMap<_, _>>();
plugin_apps
.iter()
.filter_map(|connector_id| connectors_by_id.remove(connector_id.0.as_str()))
.collect()
}
pub fn merge_connectors_with_accessible(
connectors: Vec<AppInfo>,
accessible_connectors: Vec<AppInfo>,
all_connectors_loaded: bool,
) -> Vec<AppInfo> {
let accessible_connectors = if all_connectors_loaded {
let connector_ids: HashSet<&str> = connectors
.iter()
.map(|connector| connector.id.as_str())
.collect();
accessible_connectors
.into_iter()
.filter(|connector| connector_ids.contains(connector.id.as_str()))
.collect()
} else {
accessible_connectors
};
merge_connectors(connectors, accessible_connectors)
}
#[cfg(test)]
mod tests {
use super::*;
use codex_connectors::metadata::connector_install_url;
use codex_plugin::AppConnectorId;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn batch_app_accepts_missing_optional_metadata() {
let app = serde_json::from_value::<BatchApp>(json!({
"id": "alpha",
"name": "Alpha",
"description": "Alpha description",
"icon_url": null,
"tools": [{
"name": "search",
"title": "Search",
"description": "Search Alpha",
}],
}))
.expect("valid legacy batch app");
assert_eq!(
batch_app_to_metadata(app),
ConnectorMetadata {
id: "alpha".to_string(),
name: "Alpha".to_string(),
description: Some("Alpha description".to_string()),
icon_url: None,
icon_url_dark: None,
distribution_channel: None,
tool_summaries: Some(vec![ConnectorToolSummary {
name: "search".to_string(),
title: Some("Search".to_string()),
description: "Search Alpha".to_string(),
is_enabled: true,
disabled_reason: None,
is_read_only: false,
}]),
}
);
}
fn app(id: &str) -> AppInfo {
AppInfo {
id: id.to_string(),
name: id.to_string(),
description: None,
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: None,
is_accessible: false,
is_enabled: true,
plugin_display_names: Vec::new(),
}
}
fn merged_app(id: &str, is_accessible: bool) -> AppInfo {
AppInfo {
id: id.to_string(),
name: id.to_string(),
description: None,
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: Some(connector_install_url(id, id)),
is_accessible,
is_enabled: true,
plugin_display_names: Vec::new(),
}
}
#[test]
fn excludes_accessible_connectors_not_in_all_when_all_loaded() {
let merged = merge_connectors_with_accessible(
vec![app("alpha")],
vec![app("alpha"), app("beta")],
/*all_connectors_loaded*/ true,
);
assert_eq!(merged, vec![merged_app("alpha", /*is_accessible*/ true)]);
}
#[test]
fn keeps_accessible_connectors_not_in_all_while_all_loading() {
let merged = merge_connectors_with_accessible(
vec![app("alpha")],
vec![app("alpha"), app("beta")],
/*all_connectors_loaded*/ false,
);
assert_eq!(
merged,
vec![
merged_app("alpha", /*is_accessible*/ true),
merged_app("beta", /*is_accessible*/ true)
]
);
}
#[test]
fn connectors_for_plugin_apps_returns_only_requested_plugin_apps() {
let connectors = connectors_for_plugin_apps(
vec![app("alpha"), app("beta")],
&[
AppConnectorId("gmail".to_string()),
AppConnectorId("alpha".to_string()),
AppConnectorId("gmail".to_string()),
],
);
assert_eq!(
connectors,
vec![merged_app("gmail", /*is_accessible*/ false), app("alpha")]
);
}
#[test]
fn connectors_for_plugin_apps_preserves_formerly_disallowed_plugin_apps() {
let connector_id = "asdk_app_6938a94a61d881918ef32cb999ff937c";
let connectors =
connectors_for_plugin_apps(Vec::new(), &[AppConnectorId(connector_id.to_string())]);
assert_eq!(
connectors,
vec![merged_app(connector_id, /*is_accessible*/ false)]
);
}
}

View File

@@ -0,0 +1,40 @@
use codex_core::config::Config;
use serde::Deserialize;
use crate::chatgpt_client::chatgpt_get_request;
#[derive(Debug, Deserialize)]
pub struct GetTaskResponse {
pub current_diff_task_turn: Option<AssistantTurn>,
}
// Only relevant fields for our extraction
#[derive(Debug, Deserialize)]
pub struct AssistantTurn {
pub output_items: Vec<OutputItem>,
}
#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
pub enum OutputItem {
#[serde(rename = "pr")]
Pr(PrOutputItem),
#[serde(other)]
Other,
}
#[derive(Debug, Deserialize)]
pub struct PrOutputItem {
pub output_diff: OutputDiff,
}
#[derive(Debug, Deserialize)]
pub struct OutputDiff {
pub diff: String,
}
pub(crate) async fn get_task(config: &Config, task_id: String) -> anyhow::Result<GetTaskResponse> {
let path = format!("/wham/tasks/{task_id}");
chatgpt_get_request(config, path).await
}

View File

@@ -0,0 +1,6 @@
#![recursion_limit = "256"]
pub mod apply_command;
mod chatgpt_client;
pub mod connectors;
pub mod get_task;