Base: codex-main originale (prima del fork aKode)
This commit is contained in:
6
codex-rs/chatgpt/BUILD.bazel
Normal file
6
codex-rs/chatgpt/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "chatgpt",
|
||||
crate_name = "codex_chatgpt",
|
||||
)
|
||||
37
codex-rs/chatgpt/Cargo.toml
Normal file
37
codex-rs/chatgpt/Cargo.toml
Normal file
@@ -0,0 +1,37 @@
|
||||
[package]
|
||||
name = "codex-chatgpt"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
codex-connectors = { workspace = true }
|
||||
codex-core = { workspace = true }
|
||||
codex-features = { workspace = true }
|
||||
codex-runtime-agent-instance = { workspace = true }
|
||||
codex-git-utils = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-model-provider = { workspace = true }
|
||||
codex-plugin = { workspace = true }
|
||||
codex-utils-cli = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
|
||||
[dev-dependencies]
|
||||
codex-protocol = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
uuid = { workspace = true }
|
||||
wiremock = { workspace = true }
|
||||
codex-utils-cargo-bin = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
5
codex-rs/chatgpt/README.md
Normal file
5
codex-rs/chatgpt/README.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# ChatGPT
|
||||
|
||||
This crate pertains to first party ChatGPT APIs and products such as Codex agent.
|
||||
|
||||
This crate is built and maintained by OpenAI employees. External code contributions are not accepted; please report bugs and request features in the [Codex issue tracker](https://github.com/openai/codex/issues).
|
||||
77
codex-rs/chatgpt/src/apply_command.rs
Normal file
77
codex-rs/chatgpt/src/apply_command.rs
Normal 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(())
|
||||
}
|
||||
242
codex-rs/chatgpt/src/chatgpt_client.rs
Normal file
242
codex-rs/chatgpt/src/chatgpt_client.rs
Normal 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;
|
||||
321
codex-rs/chatgpt/src/chatgpt_client_runtime_auth_tests.rs
Normal file
321
codex-rs/chatgpt/src/chatgpt_client_runtime_auth_tests.rs
Normal 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(_))
|
||||
));
|
||||
}
|
||||
523
codex-rs/chatgpt/src/connectors.rs
Normal file
523
codex-rs/chatgpt/src/connectors.rs
Normal 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)]
|
||||
);
|
||||
}
|
||||
}
|
||||
40
codex-rs/chatgpt/src/get_task.rs
Normal file
40
codex-rs/chatgpt/src/get_task.rs
Normal 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
|
||||
}
|
||||
6
codex-rs/chatgpt/src/lib.rs
Normal file
6
codex-rs/chatgpt/src/lib.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
pub mod apply_command;
|
||||
mod chatgpt_client;
|
||||
pub mod connectors;
|
||||
pub mod get_task;
|
||||
3
codex-rs/chatgpt/tests/all.rs
Normal file
3
codex-rs/chatgpt/tests/all.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
// Single integration test binary that aggregates all test modules.
|
||||
// The submodules live in `tests/suite/`.
|
||||
mod suite;
|
||||
188
codex-rs/chatgpt/tests/suite/apply_command_e2e.rs
Normal file
188
codex-rs/chatgpt/tests/suite/apply_command_e2e.rs
Normal file
@@ -0,0 +1,188 @@
|
||||
use codex_chatgpt::apply_command::apply_diff_from_task;
|
||||
use codex_chatgpt::get_task::GetTaskResponse;
|
||||
use codex_utils_cargo_bin::find_resource;
|
||||
use tempfile::TempDir;
|
||||
use tokio::process::Command;
|
||||
|
||||
/// Creates a temporary git repository with initial commit
|
||||
async fn create_temp_git_repo() -> anyhow::Result<TempDir> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let repo_path = temp_dir.path();
|
||||
let envs = vec![
|
||||
("GIT_CONFIG_GLOBAL", "/dev/null"),
|
||||
("GIT_CONFIG_NOSYSTEM", "1"),
|
||||
];
|
||||
|
||||
let output = Command::new("git")
|
||||
.envs(envs.clone())
|
||||
.args(["init"])
|
||||
.current_dir(repo_path)
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
if !output.status.success() {
|
||||
anyhow::bail!(
|
||||
"Failed to initialize git repo: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
Command::new("git")
|
||||
.envs(envs.clone())
|
||||
.args(["config", "user.email", "test@example.com"])
|
||||
.current_dir(repo_path)
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
Command::new("git")
|
||||
.envs(envs.clone())
|
||||
.args(["config", "user.name", "Test User"])
|
||||
.current_dir(repo_path)
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
std::fs::write(repo_path.join("README.md"), "# Test Repo\n")?;
|
||||
|
||||
Command::new("git")
|
||||
.envs(envs.clone())
|
||||
.args(["add", "README.md"])
|
||||
.current_dir(repo_path)
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
let output = Command::new("git")
|
||||
.envs(envs.clone())
|
||||
.args(["commit", "-m", "Initial commit"])
|
||||
.current_dir(repo_path)
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
if !output.status.success() {
|
||||
anyhow::bail!(
|
||||
"Failed to create initial commit: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
Ok(temp_dir)
|
||||
}
|
||||
|
||||
async fn mock_get_task_with_fixture() -> anyhow::Result<GetTaskResponse> {
|
||||
let fixture_path = find_resource!("tests/task_turn_fixture.json")?;
|
||||
let fixture_content = tokio::fs::read_to_string(fixture_path).await?;
|
||||
let response: GetTaskResponse = serde_json::from_str(&fixture_content)?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_apply_command_creates_fibonacci_file() {
|
||||
let temp_repo = create_temp_git_repo()
|
||||
.await
|
||||
.expect("Failed to create temp git repo");
|
||||
let repo_path = temp_repo.path();
|
||||
|
||||
let task_response = mock_get_task_with_fixture()
|
||||
.await
|
||||
.expect("Failed to load fixture");
|
||||
|
||||
apply_diff_from_task(task_response, Some(repo_path.to_path_buf()))
|
||||
.await
|
||||
.expect("Failed to apply diff from task");
|
||||
|
||||
// Assert that fibonacci.js was created in scripts/ directory
|
||||
let fibonacci_path = repo_path.join("scripts/fibonacci.js");
|
||||
assert!(fibonacci_path.exists(), "fibonacci.js was not created");
|
||||
|
||||
// Verify the file contents match expected
|
||||
let contents = std::fs::read_to_string(&fibonacci_path).expect("Failed to read fibonacci.js");
|
||||
assert!(
|
||||
contents.contains("function fibonacci(n)"),
|
||||
"fibonacci.js doesn't contain expected function"
|
||||
);
|
||||
assert!(
|
||||
contents.contains("#!/usr/bin/env node"),
|
||||
"fibonacci.js doesn't have shebang"
|
||||
);
|
||||
assert!(
|
||||
contents.contains("module.exports = fibonacci;"),
|
||||
"fibonacci.js doesn't export function"
|
||||
);
|
||||
|
||||
// Verify file has correct number of lines (31 as specified in fixture)
|
||||
let line_count = contents.lines().count();
|
||||
assert_eq!(
|
||||
line_count, 31,
|
||||
"fibonacci.js should have 31 lines, got {line_count}",
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_apply_command_with_merge_conflicts() {
|
||||
let temp_repo = create_temp_git_repo()
|
||||
.await
|
||||
.expect("Failed to create temp git repo");
|
||||
let repo_path = temp_repo.path();
|
||||
|
||||
// Create conflicting fibonacci.js file first
|
||||
let scripts_dir = repo_path.join("scripts");
|
||||
std::fs::create_dir_all(&scripts_dir).expect("Failed to create scripts directory");
|
||||
|
||||
let conflicting_content = r#"#!/usr/bin/env node
|
||||
|
||||
// This is a different fibonacci implementation
|
||||
function fib(num) {
|
||||
if (num <= 1) return num;
|
||||
return fib(num - 1) + fib(num - 2);
|
||||
}
|
||||
|
||||
console.log("Running fibonacci...");
|
||||
console.log(fib(10));
|
||||
"#;
|
||||
|
||||
let fibonacci_path = scripts_dir.join("fibonacci.js");
|
||||
std::fs::write(&fibonacci_path, conflicting_content).expect("Failed to write conflicting file");
|
||||
|
||||
Command::new("git")
|
||||
.args(["add", "scripts/fibonacci.js"])
|
||||
.current_dir(repo_path)
|
||||
.output()
|
||||
.await
|
||||
.expect("Failed to add fibonacci.js");
|
||||
|
||||
Command::new("git")
|
||||
.args(["commit", "-m", "Add conflicting fibonacci implementation"])
|
||||
.current_dir(repo_path)
|
||||
.output()
|
||||
.await
|
||||
.expect("Failed to commit conflicting file");
|
||||
|
||||
let original_dir = std::env::current_dir().expect("Failed to get current dir");
|
||||
std::env::set_current_dir(repo_path).expect("Failed to change directory");
|
||||
struct DirGuard(std::path::PathBuf);
|
||||
impl Drop for DirGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::env::set_current_dir(&self.0);
|
||||
}
|
||||
}
|
||||
let _guard = DirGuard(original_dir);
|
||||
|
||||
let task_response = mock_get_task_with_fixture()
|
||||
.await
|
||||
.expect("Failed to load fixture");
|
||||
|
||||
let apply_result = apply_diff_from_task(task_response, Some(repo_path.to_path_buf())).await;
|
||||
|
||||
assert!(
|
||||
apply_result.is_err(),
|
||||
"Expected apply to fail due to merge conflicts"
|
||||
);
|
||||
|
||||
let contents = std::fs::read_to_string(&fibonacci_path).expect("Failed to read fibonacci.js");
|
||||
|
||||
assert!(
|
||||
contents.contains("<<<<<<< HEAD")
|
||||
|| contents.contains("=======")
|
||||
|| contents.contains(">>>>>>> "),
|
||||
"fibonacci.js should contain merge conflict markers, got: {contents}",
|
||||
);
|
||||
}
|
||||
2
codex-rs/chatgpt/tests/suite/mod.rs
Normal file
2
codex-rs/chatgpt/tests/suite/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
// Aggregates all former standalone integration tests as modules.
|
||||
mod apply_command_e2e;
|
||||
65
codex-rs/chatgpt/tests/task_turn_fixture.json
Normal file
65
codex-rs/chatgpt/tests/task_turn_fixture.json
Normal file
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"current_diff_task_turn": {
|
||||
"output_items": [
|
||||
{
|
||||
"type": "pr",
|
||||
"pr_title": "Add fibonacci script",
|
||||
"pr_message": "## Summary\n- add a basic Fibonacci script under `scripts/`\n\n## Testing\n- `node scripts/fibonacci.js 10`\n- `npm run lint` *(fails: next not found)*",
|
||||
"output_diff": {
|
||||
"type": "output_diff",
|
||||
"repo_id": "/workspace/rddit-vercel",
|
||||
"base_commit_sha": "1a2e9baf2ce2fdd0c126b47b1bcfd512de2a9f7b",
|
||||
"diff": "diff --git a/scripts/fibonacci.js b/scripts/fibonacci.js\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..6c9fdfdbf8669b7968936411050525b995d0a9a6\n--- /dev/null\n+++ b/scripts/fibonacci.js\n@@ -0,0 +1,31 @@\n+#!/usr/bin/env node\n+\n+function fibonacci(n) {\n+ if (n < 0) {\n+ throw new Error(\"n must be non-negative\");\n+ }\n+ let a = 0;\n+ let b = 1;\n+ for (let i = 0; i < n; i++) {\n+ const next = a + b;\n+ a = b;\n+ b = next;\n+ }\n+ return a;\n+}\n+\n+function printUsage() {\n+ console.log(\"Usage: node scripts/fibonacci.js <n>\");\n+}\n+\n+if (require.main === module) {\n+ const arg = process.argv[2];\n+ if (arg === undefined || isNaN(Number(arg))) {\n+ printUsage();\n+ process.exit(1);\n+ }\n+ const n = Number(arg);\n+ console.log(fibonacci(n));\n+}\n+\n+module.exports = fibonacci;\n",
|
||||
"external_storage_diff": {
|
||||
"file_id": "file_00000000114c61f786900f8c2130ace7",
|
||||
"ttl": null
|
||||
},
|
||||
"files_modified": 1,
|
||||
"lines_added": 31,
|
||||
"lines_removed": 0,
|
||||
"commit_message": "Add fibonacci script"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{
|
||||
"content_type": "text",
|
||||
"text": "**Summary**\n\n- Created a command-line Fibonacci script that validates input and prints the result when executed with Node"
|
||||
},
|
||||
{
|
||||
"content_type": "repo_file_citation",
|
||||
"path": "scripts/fibonacci.js",
|
||||
"line_range_start": 1,
|
||||
"line_range_end": 31
|
||||
},
|
||||
{
|
||||
"content_type": "text",
|
||||
"text": "\n\n**Testing**\n\n- ❌ `npm run lint` (failed to run `next lint`)"
|
||||
},
|
||||
{
|
||||
"content_type": "terminal_chunk_citation",
|
||||
"terminal_chunk_id": "7dd543",
|
||||
"line_range_start": 1,
|
||||
"line_range_end": 5
|
||||
},
|
||||
{
|
||||
"content_type": "text",
|
||||
"text": "\n- ✅ `node scripts/fibonacci.js 10` produced “55”"
|
||||
},
|
||||
{
|
||||
"content_type": "terminal_chunk_citation",
|
||||
"terminal_chunk_id": "6ee559",
|
||||
"line_range_start": 1,
|
||||
"line_range_end": 3
|
||||
},
|
||||
{
|
||||
"content_type": "text",
|
||||
"text": "\n\nCodex couldn't run certain commands due to environment limitations. Consider configuring a setup script or internet access in your Codex environment to install dependencies."
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user