mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
use app-server client name for http originator header
This commit is contained in:
@@ -258,6 +258,7 @@ use codex_config::CloudRequirementsLoadErrorCode;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::loader::project_trust_key;
|
||||
use codex_config::types::McpServerTransportConfig;
|
||||
use codex_core::AppServerClientInfo;
|
||||
use codex_core::CodexThread;
|
||||
use codex_core::CodexThreadTurnContextOverrides;
|
||||
use codex_core::ExternalGoalPreviousStatus;
|
||||
@@ -330,6 +331,7 @@ use codex_login::ServerOptions as LoginServerOptions;
|
||||
use codex_login::ShutdownHandle;
|
||||
use codex_login::auth::login_with_chatgpt_auth_tokens;
|
||||
use codex_login::complete_device_code_login;
|
||||
use codex_login::default_client::ClientIdentity;
|
||||
use codex_login::login_with_api_key;
|
||||
use codex_login::request_device_code;
|
||||
use codex_login::run_login_server;
|
||||
|
||||
@@ -308,6 +308,7 @@ impl ExternalAgentConfigRequestProcessor {
|
||||
initial_history: InitialHistory::Forked(rollout_items),
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
app_server_client_info: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
persist_extended_history: false,
|
||||
metrics_service_name: None,
|
||||
|
||||
@@ -17,6 +17,29 @@ struct ThreadListFilters {
|
||||
use_state_db_only: bool,
|
||||
}
|
||||
|
||||
fn app_server_client_info(
|
||||
name: Option<String>,
|
||||
version: Option<String>,
|
||||
) -> Result<Option<AppServerClientInfo>, JSONRPCErrorError> {
|
||||
match (name, version) {
|
||||
(Some(name), Some(version)) => {
|
||||
let user_agent_suffix = Some(format!("{name}; {version}"));
|
||||
let client_identity = ClientIdentity::explicit(name.clone(), user_agent_suffix)
|
||||
.map_err(|_| {
|
||||
invalid_request(format!(
|
||||
"Invalid clientInfo.name: '{name}'. Must be a valid HTTP header value."
|
||||
))
|
||||
})?;
|
||||
Ok(Some(AppServerClientInfo {
|
||||
name,
|
||||
version,
|
||||
client_identity,
|
||||
}))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_resume_override_mismatches(
|
||||
request: &ThreadResumeParams,
|
||||
config_snapshot: &ThreadConfigSnapshot,
|
||||
@@ -859,6 +882,10 @@ impl ThreadRequestProcessor {
|
||||
let config_manager = self.config_manager.clone();
|
||||
let outgoing = Arc::clone(&listener_task_context.outgoing);
|
||||
let error_request_id = request_id.clone();
|
||||
let client_info = app_server_client_info(
|
||||
app_server_client_name.clone(),
|
||||
app_server_client_version.clone(),
|
||||
)?;
|
||||
let thread_start_task = async move {
|
||||
if let Err(error) = Self::thread_start_task(
|
||||
listener_task_context,
|
||||
@@ -866,6 +893,7 @@ impl ThreadRequestProcessor {
|
||||
request_id,
|
||||
app_server_client_name,
|
||||
app_server_client_version,
|
||||
client_info,
|
||||
config,
|
||||
typesafe_overrides,
|
||||
dynamic_tools,
|
||||
@@ -950,6 +978,7 @@ impl ThreadRequestProcessor {
|
||||
request_id: ConnectionRequestId,
|
||||
app_server_client_name: Option<String>,
|
||||
app_server_client_version: Option<String>,
|
||||
app_server_client_info: Option<AppServerClientInfo>,
|
||||
config_overrides: Option<HashMap<String, serde_json::Value>>,
|
||||
typesafe_overrides: ConfigOverrides,
|
||||
dynamic_tools: Option<Vec<ApiDynamicToolSpec>>,
|
||||
@@ -1073,6 +1102,7 @@ impl ThreadRequestProcessor {
|
||||
},
|
||||
session_source: None,
|
||||
thread_source,
|
||||
app_server_client_info,
|
||||
dynamic_tools: core_dynamic_tools,
|
||||
persist_extended_history: false,
|
||||
metrics_service_name: service_name,
|
||||
@@ -2314,6 +2344,10 @@ impl ThreadRequestProcessor {
|
||||
self.send_persist_extended_history_deprecation_notice(request_id.connection_id)
|
||||
.await;
|
||||
}
|
||||
let client_info = app_server_client_info(
|
||||
app_server_client_name.clone(),
|
||||
app_server_client_version.clone(),
|
||||
)?;
|
||||
let redact_resume_payloads =
|
||||
should_redact_thread_resume_payloads(app_server_client_name.as_deref());
|
||||
|
||||
@@ -2416,17 +2450,30 @@ impl ThreadRequestProcessor {
|
||||
let instruction_sources = Self::instruction_sources_from_config(&config).await;
|
||||
let response_history = thread_history.clone();
|
||||
|
||||
match self
|
||||
.thread_manager
|
||||
.resume_thread_with_history(
|
||||
config.clone(),
|
||||
thread_history,
|
||||
self.auth_manager.clone(),
|
||||
/*persist_extended_history*/ false,
|
||||
self.request_trace_context(&request_id).await,
|
||||
)
|
||||
.await
|
||||
{
|
||||
let resume_result = if let Some(client_info) = client_info {
|
||||
self.thread_manager
|
||||
.resume_thread_with_history_and_app_server_client_info(
|
||||
config.clone(),
|
||||
thread_history,
|
||||
self.auth_manager.clone(),
|
||||
/*persist_extended_history*/ false,
|
||||
self.request_trace_context(&request_id).await,
|
||||
client_info,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
self.thread_manager
|
||||
.resume_thread_with_history(
|
||||
config.clone(),
|
||||
thread_history,
|
||||
self.auth_manager.clone(),
|
||||
/*persist_extended_history*/ false,
|
||||
self.request_trace_context(&request_id).await,
|
||||
)
|
||||
.await
|
||||
};
|
||||
|
||||
match resume_result {
|
||||
Ok(NewThread {
|
||||
thread_id,
|
||||
thread: codex_thread,
|
||||
@@ -3007,6 +3054,10 @@ impl ThreadRequestProcessor {
|
||||
self.send_persist_extended_history_deprecation_notice(request_id.connection_id)
|
||||
.await;
|
||||
}
|
||||
let client_info = app_server_client_info(
|
||||
app_server_client_name.clone(),
|
||||
app_server_client_version.clone(),
|
||||
)?;
|
||||
|
||||
let source_thread = self
|
||||
.read_stored_thread_for_resume(&thread_id, path.as_ref(), /*include_history*/ true)
|
||||
@@ -3068,34 +3119,49 @@ impl ThreadRequestProcessor {
|
||||
|
||||
let fallback_model_provider = config.model_provider_id.clone();
|
||||
let instruction_sources = Self::instruction_sources_from_config(&config).await;
|
||||
let initial_history = InitialHistory::Resumed(ResumedHistory {
|
||||
conversation_id: source_thread_id,
|
||||
history: history_items.clone(),
|
||||
rollout_path: source_thread.rollout_path.clone(),
|
||||
});
|
||||
|
||||
let fork_result = if let Some(client_info) = client_info {
|
||||
self.thread_manager
|
||||
.fork_thread_from_history_and_app_server_client_info(
|
||||
ForkSnapshot::Interrupted,
|
||||
config,
|
||||
initial_history,
|
||||
thread_source.map(Into::into),
|
||||
/*persist_extended_history*/ false,
|
||||
self.request_trace_context(&request_id).await,
|
||||
client_info,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
self.thread_manager
|
||||
.fork_thread_from_history(
|
||||
ForkSnapshot::Interrupted,
|
||||
config,
|
||||
initial_history,
|
||||
thread_source.map(Into::into),
|
||||
/*persist_extended_history*/ false,
|
||||
self.request_trace_context(&request_id).await,
|
||||
)
|
||||
.await
|
||||
};
|
||||
|
||||
let NewThread {
|
||||
thread_id,
|
||||
thread: forked_thread,
|
||||
session_configured,
|
||||
..
|
||||
} = self
|
||||
.thread_manager
|
||||
.fork_thread_from_history(
|
||||
ForkSnapshot::Interrupted,
|
||||
config,
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
conversation_id: source_thread_id,
|
||||
history: history_items.clone(),
|
||||
rollout_path: source_thread.rollout_path.clone(),
|
||||
}),
|
||||
thread_source.map(Into::into),
|
||||
/*persist_extended_history*/ false,
|
||||
self.request_trace_context(&request_id).await,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| match err {
|
||||
CodexErr::Io(_) | CodexErr::Json(_) => {
|
||||
invalid_request(format!("failed to load thread {source_thread_id}: {err}"))
|
||||
}
|
||||
CodexErr::InvalidRequest(message) => invalid_request(message),
|
||||
err => internal_error(format!("error forking thread: {err}")),
|
||||
})?;
|
||||
} = fork_result.map_err(|err| match err {
|
||||
CodexErr::Io(_) | CodexErr::Json(_) => {
|
||||
invalid_request(format!("failed to load thread {source_thread_id}: {err}"))
|
||||
}
|
||||
CodexErr::InvalidRequest(message) => invalid_request(message),
|
||||
err => internal_error(format!("error forking thread: {err}")),
|
||||
})?;
|
||||
|
||||
Self::set_app_server_client_info(
|
||||
forked_thread.as_ref(),
|
||||
|
||||
@@ -126,6 +126,7 @@ async fn get_conversation_summary_by_thread_id_reads_pathless_store_thread() ->
|
||||
forked_from_id: None,
|
||||
source: SessionSource::Cli,
|
||||
thread_source: None,
|
||||
originator: "test_originator".to_string(),
|
||||
base_instructions: BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
|
||||
@@ -18,6 +18,10 @@ use codex_app_server_protocol::ThreadLoadedListParams;
|
||||
use codex_app_server_protocol::ThreadLoadedListResponse;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::TurnStartResponse;
|
||||
use codex_app_server_protocol::UserInput as V2UserInput;
|
||||
use core_test_support::responses;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use hmac::Hmac;
|
||||
@@ -104,6 +108,72 @@ async fn websocket_transport_routes_per_connection_handshake_and_responses() ->
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_thread_requests_use_starting_connection_identity() -> Result<()> {
|
||||
let server = responses::start_mock_server().await;
|
||||
let response_mock = responses::mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-1"),
|
||||
responses::ev_assistant_message("msg-1", "Done"),
|
||||
responses::ev_completed("resp-1"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let codex_home = TempDir::new()?;
|
||||
create_config_toml(codex_home.path(), &server.uri(), "never")?;
|
||||
|
||||
let (mut process, bind_addr) = spawn_websocket_server(codex_home.path()).await?;
|
||||
|
||||
let result = async {
|
||||
let mut ws1 = connect_websocket(bind_addr).await?;
|
||||
let mut ws2 = connect_websocket(bind_addr).await?;
|
||||
|
||||
send_initialize_request(&mut ws1, /*id*/ 1, "ws_client_one").await?;
|
||||
read_response_for_id(&mut ws1, /*id*/ 1).await?;
|
||||
|
||||
send_initialize_request(&mut ws2, /*id*/ 2, "ws_client_two").await?;
|
||||
read_response_for_id(&mut ws2, /*id*/ 2).await?;
|
||||
|
||||
let thread_id = start_thread(&mut ws2, /*id*/ 3).await?;
|
||||
send_request(
|
||||
&mut ws2,
|
||||
"turn/start",
|
||||
/*id*/ 4,
|
||||
Some(serde_json::to_value(TurnStartParams {
|
||||
thread_id,
|
||||
input: vec![V2UserInput::Text {
|
||||
text: "Hello from the second websocket client".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
})?),
|
||||
)
|
||||
.await?;
|
||||
let turn_response = read_response_for_id(&mut ws2, /*id*/ 4).await?;
|
||||
let _: TurnStartResponse = to_response::<TurnStartResponse>(turn_response)?;
|
||||
read_notification_for_method(&mut ws2, "turn/completed").await?;
|
||||
|
||||
let request = response_mock.single_request();
|
||||
assert_eq!(
|
||||
request.header("originator").as_deref(),
|
||||
Some("ws_client_two")
|
||||
);
|
||||
let user_agent = request.header("user-agent").expect("user-agent header");
|
||||
assert!(user_agent.starts_with("ws_client_two/"));
|
||||
assert!(user_agent.ends_with(" (ws_client_two; 0.1.0)"));
|
||||
|
||||
Ok::<(), anyhow::Error>(())
|
||||
}
|
||||
.await;
|
||||
|
||||
process
|
||||
.kill()
|
||||
.await
|
||||
.context("failed to stop websocket app-server process")?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_transport_serves_health_endpoints_on_same_listener() -> Result<()> {
|
||||
let server = create_mock_responses_server_sequence_unchecked(Vec::new()).await;
|
||||
|
||||
@@ -17,6 +17,7 @@ use codex_app_server_protocol::UserInput as V2UserInput;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cargo_bin::cargo_bin;
|
||||
use core_test_support::fs_wait;
|
||||
use core_test_support::responses;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use std::path::Path;
|
||||
@@ -116,6 +117,82 @@ async fn initialize_codex_backend_does_not_override_originator() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn codex_backend_thread_requests_use_connection_identity() -> Result<()> {
|
||||
let server = responses::start_mock_server().await;
|
||||
let response_mock = responses::mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-1"),
|
||||
responses::ev_assistant_message("msg-1", "Done"),
|
||||
responses::ev_completed("resp-1"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let codex_home = TempDir::new()?;
|
||||
create_config_toml(codex_home.path(), &server.uri(), "never")?;
|
||||
let mut mcp = McpProcess::new(codex_home.path()).await?;
|
||||
|
||||
let message = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.initialize_with_client_info(ClientInfo {
|
||||
name: "codex-backend".to_string(),
|
||||
title: Some("Codex Backend".to_string()),
|
||||
version: "0.1.0".to_string(),
|
||||
}),
|
||||
)
|
||||
.await??;
|
||||
|
||||
let JSONRPCMessage::Response(response) = message else {
|
||||
anyhow::bail!("expected initialize response, got {message:?}");
|
||||
};
|
||||
let InitializeResponse { user_agent, .. } = to_response::<InitializeResponse>(response)?;
|
||||
assert!(user_agent.starts_with("codex_cli_rs/"));
|
||||
|
||||
let thread_req = mcp
|
||||
.send_thread_start_request(ThreadStartParams::default())
|
||||
.await?;
|
||||
let thread_resp: JSONRPCResponse = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(thread_req)),
|
||||
)
|
||||
.await??;
|
||||
let ThreadStartResponse { thread, .. } = to_response(thread_resp)?;
|
||||
|
||||
let turn_req = mcp
|
||||
.send_turn_start_request(TurnStartParams {
|
||||
thread_id: thread.id,
|
||||
input: vec![V2UserInput::Text {
|
||||
text: "Hello from codex-backend".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let turn_resp: JSONRPCResponse = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(turn_req)),
|
||||
)
|
||||
.await??;
|
||||
let _: TurnStartResponse = to_response(turn_resp)?;
|
||||
timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_notification_message("turn/completed"),
|
||||
)
|
||||
.await??;
|
||||
|
||||
let request = response_mock.single_request();
|
||||
assert_eq!(
|
||||
request.header("originator").as_deref(),
|
||||
Some("codex-backend")
|
||||
);
|
||||
let user_agent = request.header("user-agent").expect("user-agent header");
|
||||
assert!(user_agent.starts_with("codex-backend/"));
|
||||
assert!(user_agent.ends_with(" (codex-backend; 0.1.0)"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialize_respects_originator_override_env_var() -> Result<()> {
|
||||
let responses = Vec::new();
|
||||
|
||||
@@ -1287,6 +1287,7 @@ async fn seed_pathless_store_thread(
|
||||
forked_from_id: None,
|
||||
source: ProtocolSessionSource::Cli,
|
||||
thread_source: None,
|
||||
originator: "test_originator".to_string(),
|
||||
base_instructions: BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
|
||||
@@ -212,6 +212,7 @@ async fn thread_unarchive_preserves_pathless_store_metadata() -> Result<()> {
|
||||
forked_from_id: Some(parent_thread_id),
|
||||
source: SessionSource::Cli,
|
||||
thread_source: None,
|
||||
originator: "test_originator".to_string(),
|
||||
base_instructions: BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
|
||||
@@ -596,6 +596,7 @@ impl AgentControl {
|
||||
}),
|
||||
agent_control: self.clone(),
|
||||
session_source,
|
||||
app_server_client_info: None,
|
||||
inherited_shell_snapshot,
|
||||
inherited_exec_policy,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
use codex_login::default_client::ClientIdentity;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AppServerClientInfo {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub client_identity: ClientIdentity,
|
||||
}
|
||||
@@ -66,6 +66,7 @@ use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::RefreshTokenError;
|
||||
use codex_login::UnauthorizedRecovery;
|
||||
use codex_login::default_client::ClientIdentity;
|
||||
use codex_login::default_client::build_reqwest_client;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_otel::current_span_w3c_trace_context;
|
||||
@@ -170,6 +171,7 @@ struct ModelClientState {
|
||||
provider: SharedModelProvider,
|
||||
auth_env_telemetry: AuthEnvTelemetry,
|
||||
session_source: SessionSource,
|
||||
client_identity: ClientIdentity,
|
||||
model_verbosity: Option<VerbosityConfig>,
|
||||
enable_request_compression: bool,
|
||||
include_timing_metrics: bool,
|
||||
@@ -316,6 +318,7 @@ impl ModelClient {
|
||||
installation_id: String,
|
||||
provider_info: ModelProviderInfo,
|
||||
session_source: SessionSource,
|
||||
client_identity: ClientIdentity,
|
||||
model_verbosity: Option<VerbosityConfig>,
|
||||
enable_request_compression: bool,
|
||||
include_timing_metrics: bool,
|
||||
@@ -339,6 +342,7 @@ impl ModelClient {
|
||||
provider: model_provider,
|
||||
auth_env_telemetry,
|
||||
session_source,
|
||||
client_identity,
|
||||
model_verbosity,
|
||||
enable_request_compression,
|
||||
include_timing_metrics,
|
||||
@@ -367,6 +371,10 @@ impl ModelClient {
|
||||
self.state.provider.auth_manager()
|
||||
}
|
||||
|
||||
pub(crate) fn client_identity_headers(&self) -> ApiHeaderMap {
|
||||
self.state.client_identity.headers_with_default_residency()
|
||||
}
|
||||
|
||||
pub(crate) fn set_window_generation(&self, window_generation: u64) {
|
||||
self.state
|
||||
.window_generation
|
||||
@@ -526,6 +534,7 @@ impl ModelClient {
|
||||
if let Some(header_value) = self.generate_attestation_header_for().await {
|
||||
extra_headers.insert(X_OAI_ATTESTATION_HEADER, header_value);
|
||||
}
|
||||
extra_headers.extend(self.client_identity_headers());
|
||||
let mut sideband_headers = extra_headers.clone();
|
||||
sideband_headers.extend(sideband_websocket_auth_headers(
|
||||
client_setup.api_auth.as_ref(),
|
||||
@@ -585,8 +594,11 @@ impl ModelClient {
|
||||
}),
|
||||
};
|
||||
|
||||
let mut extra_headers = self.client_identity_headers();
|
||||
extra_headers.extend(self.build_subagent_headers());
|
||||
|
||||
client
|
||||
.summarize_input(&payload, self.build_subagent_headers())
|
||||
.summarize_input(&payload, extra_headers)
|
||||
.await
|
||||
.map_err(map_api_error)
|
||||
}
|
||||
@@ -611,7 +623,8 @@ impl ModelClient {
|
||||
}
|
||||
|
||||
fn build_responses_identity_headers(&self) -> ApiHeaderMap {
|
||||
let mut extra_headers = self.build_subagent_headers();
|
||||
let mut extra_headers = self.client_identity_headers();
|
||||
extra_headers.extend(self.build_subagent_headers());
|
||||
if let Some(parent_thread_id) = parent_thread_id_header_value(&self.state.session_source)
|
||||
&& let Ok(val) = HeaderValue::from_str(&parent_thread_id)
|
||||
{
|
||||
@@ -823,7 +836,7 @@ impl ModelClient {
|
||||
websocket_connect_timeout,
|
||||
ApiWebSocketResponsesClient::new(api_provider, api_auth).connect(
|
||||
headers,
|
||||
codex_login::default_client::default_headers(),
|
||||
self.client_identity_headers(),
|
||||
turn_state,
|
||||
Some(websocket_telemetry),
|
||||
),
|
||||
|
||||
@@ -15,6 +15,7 @@ use codex_api::ResponseEvent;
|
||||
use codex_app_server_protocol::AuthMode;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::ClientIdentity;
|
||||
use codex_model_provider::BearerAuthProvider;
|
||||
use codex_model_provider_info::CHATGPT_CODEX_BASE_URL;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
@@ -61,6 +62,13 @@ use tracing_subscriber::registry::LookupSpan;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
|
||||
fn test_model_client(session_source: SessionSource) -> ModelClient {
|
||||
test_model_client_with_identity(session_source, ClientIdentity::process_default())
|
||||
}
|
||||
|
||||
fn test_model_client_with_identity(
|
||||
session_source: SessionSource,
|
||||
client_identity: ClientIdentity,
|
||||
) -> ModelClient {
|
||||
let provider = create_oss_provider_with_base_url("https://example.com/v1", WireApi::Responses);
|
||||
let thread_id = ThreadId::new();
|
||||
ModelClient::new(
|
||||
@@ -70,6 +78,7 @@ fn test_model_client(session_source: SessionSource) -> ModelClient {
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
provider,
|
||||
session_source,
|
||||
client_identity,
|
||||
/*model_verbosity*/ None,
|
||||
/*enable_request_compression*/ false,
|
||||
/*include_timing_metrics*/ false,
|
||||
@@ -78,6 +87,32 @@ fn test_model_client(session_source: SessionSource) -> ModelClient {
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_client_identity_headers_use_concrete_identity() {
|
||||
let client = test_model_client_with_identity(
|
||||
SessionSource::Exec,
|
||||
ClientIdentity::explicit(
|
||||
"codex_explicit_model_client".to_string(),
|
||||
Some("codex_explicit_model_client; 1.0.0".to_string()),
|
||||
)
|
||||
.expect("explicit identity should be valid"),
|
||||
);
|
||||
|
||||
let headers = client.client_identity_headers();
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("originator")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("codex_explicit_model_client"),
|
||||
);
|
||||
let user_agent = headers
|
||||
.get(http::header::USER_AGENT)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.expect("user-agent header");
|
||||
assert!(user_agent.starts_with("codex_explicit_model_client/"));
|
||||
assert!(user_agent.ends_with(" (codex_explicit_model_client; 1.0.0)"));
|
||||
}
|
||||
|
||||
fn test_model_info() -> ModelInfo {
|
||||
serde_json::from_value(json!({
|
||||
"slug": "gpt-test",
|
||||
@@ -520,6 +555,7 @@ fn model_client_with_counting_attestation(
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
provider,
|
||||
SessionSource::Exec,
|
||||
ClientIdentity::process_default(),
|
||||
/*model_verbosity*/ None,
|
||||
/*enable_request_compression*/ false,
|
||||
/*include_timing_metrics*/ false,
|
||||
|
||||
@@ -87,6 +87,7 @@ pub(crate) async fn run_codex_thread_interactive(
|
||||
conversation_history: initial_history.unwrap_or(InitialHistory::New),
|
||||
session_source: SessionSource::SubAgent(subagent_source.clone()),
|
||||
thread_source: Some(ThreadSource::Subagent),
|
||||
app_server_client_info: None,
|
||||
agent_control: parent_session.services.agent_control.clone(),
|
||||
dynamic_tools: Vec::new(),
|
||||
persist_extended_history: false,
|
||||
|
||||
@@ -130,6 +130,8 @@ pub(crate) mod agents_md;
|
||||
pub use agents_md::AgentsMdManager;
|
||||
pub use agents_md::DEFAULT_AGENTS_MD_FILENAME;
|
||||
pub use agents_md::LOCAL_AGENTS_MD_FILENAME;
|
||||
mod app_server_client_info;
|
||||
pub use app_server_client_info::AppServerClientInfo;
|
||||
mod rollout;
|
||||
pub(crate) mod safety;
|
||||
mod session_rollout_init_error;
|
||||
|
||||
@@ -24,7 +24,6 @@ use codex_app_server_protocol::AuthMode;
|
||||
use codex_config::config_toml::RealtimeWsMode;
|
||||
use codex_config::config_toml::RealtimeWsVersion;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::default_headers;
|
||||
use codex_login::read_openai_api_key_from_env;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::CodexErr;
|
||||
@@ -320,6 +319,7 @@ impl RealtimeConversationManager {
|
||||
session_config,
|
||||
call_id: call.call_id,
|
||||
sideband_headers: call.sideband_headers,
|
||||
default_headers: model_client.client_identity_headers(),
|
||||
input_channels,
|
||||
events_tx,
|
||||
handoff_state: handoff.clone(),
|
||||
@@ -329,11 +329,13 @@ impl RealtimeConversationManager {
|
||||
});
|
||||
(task, Some(call.sdp))
|
||||
} else {
|
||||
let mut extra_headers = extra_headers.unwrap_or_default();
|
||||
extra_headers.extend(model_client.client_identity_headers());
|
||||
let connection = client
|
||||
.connect(
|
||||
session_config,
|
||||
extra_headers.unwrap_or_default(),
|
||||
default_headers(),
|
||||
extra_headers,
|
||||
model_client.client_identity_headers(),
|
||||
)
|
||||
.await
|
||||
.map_err(map_api_error)?;
|
||||
@@ -1022,6 +1024,7 @@ struct RealtimeWebrtcSidebandInputTask {
|
||||
session_config: RealtimeSessionConfig,
|
||||
call_id: String,
|
||||
sideband_headers: HeaderMap,
|
||||
default_headers: HeaderMap,
|
||||
input_channels: RealtimeInputChannels,
|
||||
events_tx: Sender<RealtimeEvent>,
|
||||
handoff_state: RealtimeHandoffState,
|
||||
@@ -1036,6 +1039,7 @@ fn spawn_webrtc_sideband_input_task(input: RealtimeWebrtcSidebandInputTask) -> J
|
||||
session_config,
|
||||
call_id,
|
||||
sideband_headers,
|
||||
default_headers,
|
||||
input_channels,
|
||||
events_tx,
|
||||
handoff_state,
|
||||
@@ -1050,12 +1054,7 @@ fn spawn_webrtc_sideband_input_task(input: RealtimeWebrtcSidebandInputTask) -> J
|
||||
}
|
||||
|
||||
let connection = match client
|
||||
.connect_webrtc_sideband(
|
||||
session_config,
|
||||
&call_id,
|
||||
sideband_headers,
|
||||
default_headers(),
|
||||
)
|
||||
.connect_webrtc_sideband(session_config, &call_id, sideband_headers, default_headers)
|
||||
.await
|
||||
{
|
||||
Ok(connection) => connection,
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::agent::Mailbox;
|
||||
use crate::agent::MailboxReceiver;
|
||||
use crate::agent::agent_status_from_event;
|
||||
use crate::agent::status::is_final;
|
||||
use crate::app_server_client_info::AppServerClientInfo;
|
||||
use crate::attestation::AttestationProvider;
|
||||
use crate::build_available_skills;
|
||||
use crate::compact;
|
||||
@@ -61,7 +62,7 @@ use codex_hooks::HooksConfig;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::auth_env_telemetry::collect_auth_env_telemetry;
|
||||
use codex_login::default_client::originator;
|
||||
use codex_login::default_client::ClientIdentity;
|
||||
use codex_mcp::McpConnectionManager;
|
||||
use codex_mcp::McpRuntimeEnvironment;
|
||||
use codex_mcp::codex_apps_tools_cache_key;
|
||||
@@ -396,6 +397,7 @@ pub(crate) struct CodexSpawnArgs {
|
||||
pub(crate) conversation_history: InitialHistory,
|
||||
pub(crate) session_source: SessionSource,
|
||||
pub(crate) thread_source: Option<ThreadSource>,
|
||||
pub(crate) app_server_client_info: Option<AppServerClientInfo>,
|
||||
pub(crate) agent_control: AgentControl,
|
||||
pub(crate) dynamic_tools: Vec<DynamicToolSpec>,
|
||||
pub(crate) persist_extended_history: bool,
|
||||
@@ -460,6 +462,7 @@ impl Codex {
|
||||
conversation_history,
|
||||
session_source,
|
||||
thread_source,
|
||||
app_server_client_info,
|
||||
agent_control,
|
||||
dynamic_tools,
|
||||
persist_extended_history,
|
||||
@@ -603,6 +606,11 @@ impl Codex {
|
||||
account_plan_type,
|
||||
config.features.enabled(Feature::FastMode),
|
||||
);
|
||||
let (app_server_client_name, app_server_client_version, client_identity) =
|
||||
match app_server_client_info {
|
||||
Some(info) => (Some(info.name), Some(info.version), info.client_identity),
|
||||
None => (None, None, ClientIdentity::process_default()),
|
||||
};
|
||||
let session_configuration = SessionConfiguration {
|
||||
provider: config.model_provider.clone(),
|
||||
collaboration_mode,
|
||||
@@ -624,8 +632,9 @@ impl Codex {
|
||||
environments: environment_selections.to_selections(),
|
||||
original_config_do_not_use: Arc::clone(&config),
|
||||
metrics_service_name,
|
||||
app_server_client_name: None,
|
||||
app_server_client_version: None,
|
||||
app_server_client_name,
|
||||
app_server_client_version,
|
||||
client_identity,
|
||||
session_source,
|
||||
thread_source,
|
||||
dynamic_tools,
|
||||
|
||||
@@ -88,6 +88,7 @@ pub(crate) struct SessionConfiguration {
|
||||
pub(super) metrics_service_name: Option<String>,
|
||||
pub(super) app_server_client_name: Option<String>,
|
||||
pub(super) app_server_client_version: Option<String>,
|
||||
pub(super) client_identity: ClientIdentity,
|
||||
/// Source of the session (cli, vscode, exec, mcp, ...)
|
||||
pub(super) session_source: SessionSource,
|
||||
/// Optional analytics source classification for this thread.
|
||||
@@ -419,6 +420,10 @@ impl Session {
|
||||
forked_from_id,
|
||||
source: session_source,
|
||||
thread_source: session_configuration.thread_source,
|
||||
originator: session_configuration
|
||||
.client_identity
|
||||
.originator_value()
|
||||
.to_string(),
|
||||
base_instructions: BaseInstructions {
|
||||
text: session_configuration.base_instructions.clone(),
|
||||
},
|
||||
@@ -611,7 +616,10 @@ impl Session {
|
||||
let auth_mode = auth.map(CodexAuth::auth_mode).map(TelemetryAuthMode::from);
|
||||
let account_id = auth.and_then(CodexAuth::get_account_id);
|
||||
let account_email = auth.and_then(CodexAuth::get_account_email);
|
||||
let originator = originator().value;
|
||||
let originator = session_configuration
|
||||
.client_identity
|
||||
.originator_value()
|
||||
.to_string();
|
||||
let terminal_type = user_agent();
|
||||
let session_model = session_configuration.collaboration_mode.model().to_string();
|
||||
let auth_env_telemetry = collect_auth_env_telemetry(
|
||||
@@ -876,6 +884,7 @@ impl Session {
|
||||
installation_id.clone(),
|
||||
session_configuration.provider.clone(),
|
||||
session_configuration.session_source.clone(),
|
||||
session_configuration.client_identity.clone(),
|
||||
config.model_verbosity,
|
||||
config.features.enabled(Feature::EnableRequestCompression),
|
||||
config.features.enabled(Feature::RuntimeMetrics),
|
||||
|
||||
@@ -402,6 +402,7 @@ fn test_model_client_session() -> crate::client::ModelClientSession {
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
ModelProviderInfo::create_openai_provider(/* base_url */ /*base_url*/ None),
|
||||
codex_protocol::protocol::SessionSource::Exec,
|
||||
ClientIdentity::process_default(),
|
||||
/*model_verbosity*/ None,
|
||||
/*enable_request_compression*/ false,
|
||||
/*include_timing_metrics*/ false,
|
||||
@@ -2830,6 +2831,7 @@ async fn set_rate_limits_retains_previous_credits() {
|
||||
metrics_service_name: None,
|
||||
app_server_client_name: None,
|
||||
app_server_client_version: None,
|
||||
client_identity: ClientIdentity::process_default(),
|
||||
session_source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
@@ -2934,6 +2936,7 @@ async fn set_rate_limits_updates_plan_type_when_present() {
|
||||
metrics_service_name: None,
|
||||
app_server_client_name: None,
|
||||
app_server_client_version: None,
|
||||
client_identity: ClientIdentity::process_default(),
|
||||
session_source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
@@ -3185,6 +3188,7 @@ async fn attach_thread_persistence(session: &mut Session) -> PathBuf {
|
||||
forked_from_id: None,
|
||||
source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
originator: "test_originator".to_string(),
|
||||
base_instructions: BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
@@ -3407,6 +3411,7 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati
|
||||
metrics_service_name: None,
|
||||
app_server_client_name: None,
|
||||
app_server_client_version: None,
|
||||
client_identity: ClientIdentity::process_default(),
|
||||
session_source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
@@ -3940,6 +3945,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() {
|
||||
metrics_service_name: None,
|
||||
app_server_client_name: None,
|
||||
app_server_client_version: None,
|
||||
client_identity: ClientIdentity::process_default(),
|
||||
session_source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
@@ -4049,6 +4055,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
metrics_service_name: None,
|
||||
app_server_client_name: None,
|
||||
app_server_client_version: None,
|
||||
client_identity: ClientIdentity::process_default(),
|
||||
session_source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
@@ -4139,6 +4146,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
session_configuration.provider.clone(),
|
||||
session_configuration.session_source.clone(),
|
||||
session_configuration.client_identity.clone(),
|
||||
config.model_verbosity,
|
||||
config.features.enabled(Feature::EnableRequestCompression),
|
||||
config.features.enabled(Feature::RuntimeMetrics),
|
||||
@@ -4281,6 +4289,7 @@ async fn make_session_with_config_and_rx(
|
||||
metrics_service_name: None,
|
||||
app_server_client_name: None,
|
||||
app_server_client_version: None,
|
||||
client_identity: ClientIdentity::process_default(),
|
||||
session_source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
@@ -4384,6 +4393,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx(
|
||||
metrics_service_name: None,
|
||||
app_server_client_name: None,
|
||||
app_server_client_version: None,
|
||||
client_identity: ClientIdentity::process_default(),
|
||||
session_source: session_source.clone(),
|
||||
thread_source: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
@@ -5426,6 +5436,7 @@ async fn shutdown_complete_does_not_append_to_thread_store_after_shutdown() {
|
||||
forked_from_id: None,
|
||||
source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
originator: "test_originator".to_string(),
|
||||
base_instructions: BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
@@ -5901,6 +5912,7 @@ where
|
||||
metrics_service_name: None,
|
||||
app_server_client_name: None,
|
||||
app_server_client_version: None,
|
||||
client_identity: ClientIdentity::process_default(),
|
||||
session_source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
dynamic_tools,
|
||||
@@ -5991,6 +6003,7 @@ where
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
session_configuration.provider.clone(),
|
||||
session_configuration.session_source.clone(),
|
||||
session_configuration.client_identity.clone(),
|
||||
config.model_verbosity,
|
||||
config.features.enabled(Feature::EnableRequestCompression),
|
||||
config.features.enabled(Feature::RuntimeMetrics),
|
||||
|
||||
@@ -677,6 +677,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
|
||||
GUARDIAN_REVIEWER_NAME.to_string(),
|
||||
)),
|
||||
thread_source: None,
|
||||
app_server_client_info: None,
|
||||
agent_control: AgentControl::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
persist_extended_history: false,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::SkillsManager;
|
||||
use crate::agent::AgentControl;
|
||||
use crate::app_server_client_info::AppServerClientInfo;
|
||||
use crate::attestation::AttestationProvider;
|
||||
use crate::codex_thread::CodexThread;
|
||||
use crate::config::Config;
|
||||
@@ -113,6 +114,16 @@ pub struct NewThread {
|
||||
pub session_configured: SessionConfiguredEvent,
|
||||
}
|
||||
|
||||
struct ForkThreadWithInitialHistoryOptions {
|
||||
snapshot: ForkSnapshot,
|
||||
config: Config,
|
||||
history: InitialHistory,
|
||||
thread_source: Option<ThreadSource>,
|
||||
persist_extended_history: bool,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
app_server_client_info: Option<AppServerClientInfo>,
|
||||
}
|
||||
|
||||
// TODO(ccunningham): Add an explicit non-interrupting live-turn snapshot once
|
||||
// core can represent sampling boundaries directly instead of relying on
|
||||
// whichever items happened to be persisted mid-turn.
|
||||
@@ -177,6 +188,7 @@ pub struct StartThreadOptions {
|
||||
pub initial_history: InitialHistory,
|
||||
pub session_source: Option<SessionSource>,
|
||||
pub thread_source: Option<ThreadSource>,
|
||||
pub app_server_client_info: Option<AppServerClientInfo>,
|
||||
pub dynamic_tools: Vec<codex_protocol::dynamic_tools::DynamicToolSpec>,
|
||||
pub persist_extended_history: bool,
|
||||
pub metrics_service_name: Option<String>,
|
||||
@@ -189,6 +201,7 @@ pub(crate) struct ResumeThreadWithHistoryOptions {
|
||||
pub(crate) initial_history: InitialHistory,
|
||||
pub(crate) agent_control: AgentControl,
|
||||
pub(crate) session_source: SessionSource,
|
||||
pub(crate) app_server_client_info: Option<AppServerClientInfo>,
|
||||
pub(crate) inherited_shell_snapshot: Option<Arc<ShellSnapshot>>,
|
||||
pub(crate) inherited_exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
|
||||
}
|
||||
@@ -569,6 +582,7 @@ impl ThreadManager {
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
app_server_client_info: None,
|
||||
dynamic_tools,
|
||||
persist_extended_history,
|
||||
metrics_service_name: None,
|
||||
@@ -595,6 +609,7 @@ impl ThreadManager {
|
||||
self.agent_control(),
|
||||
session_source,
|
||||
thread_source,
|
||||
options.app_server_client_info,
|
||||
options.dynamic_tools,
|
||||
options.persist_extended_history,
|
||||
options.metrics_service_name,
|
||||
@@ -662,6 +677,48 @@ impl ThreadManager {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
persist_extended_history: bool,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
) -> CodexResult<NewThread> {
|
||||
self.resume_thread_with_history_inner(
|
||||
config,
|
||||
initial_history,
|
||||
auth_manager,
|
||||
persist_extended_history,
|
||||
parent_trace,
|
||||
/*app_server_client_info*/ None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn resume_thread_with_history_and_app_server_client_info(
|
||||
&self,
|
||||
config: Config,
|
||||
initial_history: InitialHistory,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
persist_extended_history: bool,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
app_server_client_info: AppServerClientInfo,
|
||||
) -> CodexResult<NewThread> {
|
||||
self.resume_thread_with_history_inner(
|
||||
config,
|
||||
initial_history,
|
||||
auth_manager,
|
||||
persist_extended_history,
|
||||
parent_trace,
|
||||
Some(app_server_client_info),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn resume_thread_with_history_inner(
|
||||
&self,
|
||||
config: Config,
|
||||
initial_history: InitialHistory,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
persist_extended_history: bool,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
app_server_client_info: Option<AppServerClientInfo>,
|
||||
) -> CodexResult<NewThread> {
|
||||
let environments = default_thread_environment_selections(
|
||||
self.state.environment_manager.as_ref(),
|
||||
@@ -679,6 +736,7 @@ impl ThreadManager {
|
||||
/*metrics_service_name*/ None,
|
||||
parent_trace,
|
||||
environments,
|
||||
app_server_client_info,
|
||||
/*user_shell_override*/ None,
|
||||
))
|
||||
.await
|
||||
@@ -704,6 +762,7 @@ impl ThreadManager {
|
||||
/*metrics_service_name*/ None,
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*app_server_client_info*/ None,
|
||||
/*user_shell_override*/ Some(user_shell_override),
|
||||
))
|
||||
.await
|
||||
@@ -733,6 +792,7 @@ impl ThreadManager {
|
||||
/*metrics_service_name*/ None,
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*app_server_client_info*/ None,
|
||||
/*user_shell_override*/ Some(user_shell_override),
|
||||
))
|
||||
.await
|
||||
@@ -856,26 +916,57 @@ impl ThreadManager {
|
||||
where
|
||||
S: Into<ForkSnapshot>,
|
||||
{
|
||||
self.fork_thread_with_initial_history(
|
||||
snapshot.into(),
|
||||
self.fork_thread_with_initial_history(ForkThreadWithInitialHistoryOptions {
|
||||
snapshot: snapshot.into(),
|
||||
config,
|
||||
history,
|
||||
thread_source,
|
||||
persist_extended_history,
|
||||
parent_trace,
|
||||
)
|
||||
app_server_client_info: None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn fork_thread_with_initial_history(
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn fork_thread_from_history_and_app_server_client_info<S>(
|
||||
&self,
|
||||
snapshot: ForkSnapshot,
|
||||
snapshot: S,
|
||||
config: Config,
|
||||
history: InitialHistory,
|
||||
thread_source: Option<ThreadSource>,
|
||||
persist_extended_history: bool,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
app_server_client_info: AppServerClientInfo,
|
||||
) -> CodexResult<NewThread>
|
||||
where
|
||||
S: Into<ForkSnapshot>,
|
||||
{
|
||||
self.fork_thread_with_initial_history(ForkThreadWithInitialHistoryOptions {
|
||||
snapshot: snapshot.into(),
|
||||
config,
|
||||
history,
|
||||
thread_source,
|
||||
persist_extended_history,
|
||||
parent_trace,
|
||||
app_server_client_info: Some(app_server_client_info),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn fork_thread_with_initial_history(
|
||||
&self,
|
||||
options: ForkThreadWithInitialHistoryOptions,
|
||||
) -> CodexResult<NewThread> {
|
||||
let ForkThreadWithInitialHistoryOptions {
|
||||
snapshot,
|
||||
config,
|
||||
history,
|
||||
thread_source,
|
||||
persist_extended_history,
|
||||
parent_trace,
|
||||
app_server_client_info,
|
||||
} = options;
|
||||
let interrupted_marker = InterruptedTurnHistoryMarker::from_config(&config);
|
||||
let history = fork_history_from_snapshot(snapshot, history, interrupted_marker);
|
||||
let environments = default_thread_environment_selections(
|
||||
@@ -893,6 +984,7 @@ impl ThreadManager {
|
||||
/*metrics_service_name*/ None,
|
||||
parent_trace,
|
||||
environments,
|
||||
app_server_client_info,
|
||||
/*user_shell_override*/ None,
|
||||
))
|
||||
.await
|
||||
@@ -1032,6 +1124,7 @@ impl ThreadManagerState {
|
||||
agent_control,
|
||||
session_source,
|
||||
thread_source,
|
||||
/*app_server_client_info*/ None,
|
||||
Vec::new(),
|
||||
persist_extended_history,
|
||||
metrics_service_name,
|
||||
@@ -1053,6 +1146,7 @@ impl ThreadManagerState {
|
||||
initial_history,
|
||||
agent_control,
|
||||
session_source,
|
||||
app_server_client_info,
|
||||
inherited_shell_snapshot,
|
||||
inherited_exec_policy,
|
||||
} = options;
|
||||
@@ -1066,6 +1160,7 @@ impl ThreadManagerState {
|
||||
agent_control,
|
||||
session_source,
|
||||
thread_source,
|
||||
app_server_client_info,
|
||||
Vec::new(),
|
||||
/*persist_extended_history*/ false,
|
||||
/*metrics_service_name*/ None,
|
||||
@@ -1101,6 +1196,7 @@ impl ThreadManagerState {
|
||||
agent_control,
|
||||
session_source,
|
||||
thread_source,
|
||||
/*app_server_client_info*/ None,
|
||||
Vec::new(),
|
||||
persist_extended_history,
|
||||
/*metrics_service_name*/ None,
|
||||
@@ -1127,6 +1223,7 @@ impl ThreadManagerState {
|
||||
metrics_service_name: Option<String>,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
environments: Vec<TurnEnvironmentSelection>,
|
||||
app_server_client_info: Option<AppServerClientInfo>,
|
||||
user_shell_override: Option<crate::shell::Shell>,
|
||||
) -> CodexResult<NewThread> {
|
||||
Box::pin(self.spawn_thread_with_source(
|
||||
@@ -1136,6 +1233,7 @@ impl ThreadManagerState {
|
||||
agent_control,
|
||||
self.session_source.clone(),
|
||||
thread_source,
|
||||
app_server_client_info,
|
||||
dynamic_tools,
|
||||
persist_extended_history,
|
||||
metrics_service_name,
|
||||
@@ -1157,6 +1255,7 @@ impl ThreadManagerState {
|
||||
agent_control: AgentControl,
|
||||
session_source: SessionSource,
|
||||
thread_source: Option<ThreadSource>,
|
||||
app_server_client_info: Option<AppServerClientInfo>,
|
||||
dynamic_tools: Vec<codex_protocol::dynamic_tools::DynamicToolSpec>,
|
||||
persist_extended_history: bool,
|
||||
metrics_service_name: Option<String>,
|
||||
@@ -1209,6 +1308,7 @@ impl ThreadManagerState {
|
||||
conversation_history: initial_history,
|
||||
session_source,
|
||||
thread_source,
|
||||
app_server_client_info,
|
||||
agent_control,
|
||||
dynamic_tools,
|
||||
persist_extended_history,
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::tasks::InterruptedTurnHistoryMarker;
|
||||
use crate::tasks::interrupted_turn_history_marker;
|
||||
use codex_extension_api::empty_extension_registry;
|
||||
use codex_features::Feature;
|
||||
use codex_login::default_client::ClientIdentity;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ReasoningItemReasoningSummary;
|
||||
@@ -326,6 +327,7 @@ async fn start_thread_rejects_explicit_local_environment_when_default_provider_i
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
app_server_client_info: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
persist_extended_history: false,
|
||||
metrics_service_name: None,
|
||||
@@ -460,6 +462,7 @@ async fn start_thread_keeps_internal_threads_hidden_from_normal_lookups() {
|
||||
InternalSessionSource::MemoryConsolidation,
|
||||
)),
|
||||
thread_source: None,
|
||||
app_server_client_info: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
persist_extended_history: false,
|
||||
metrics_service_name: None,
|
||||
@@ -481,6 +484,68 @@ async fn start_thread_keeps_internal_threads_hidden_from_normal_lookups() {
|
||||
assert!(manager.list_thread_ids().await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_thread_uses_app_server_client_identity_for_rollout_metadata() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let mut config = test_config().await;
|
||||
config.codex_home = temp_dir.path().join("codex-home").abs();
|
||||
config.cwd = config.codex_home.abs();
|
||||
std::fs::create_dir_all(&config.codex_home).expect("create codex home");
|
||||
|
||||
let manager = ThreadManager::with_models_provider_and_home_for_tests(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
config.model_provider.clone(),
|
||||
config.codex_home.to_path_buf(),
|
||||
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
|
||||
);
|
||||
let thread = manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
app_server_client_info: Some(AppServerClientInfo {
|
||||
name: "codex_test_app".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
client_identity: ClientIdentity::explicit(
|
||||
"codex_test_app".to_string(),
|
||||
Some("codex_test_app; 1.0.0".to_string()),
|
||||
)
|
||||
.expect("explicit identity should be valid"),
|
||||
}),
|
||||
dynamic_tools: Vec::new(),
|
||||
persist_extended_history: false,
|
||||
metrics_service_name: None,
|
||||
parent_trace: None,
|
||||
environments: Vec::new(),
|
||||
})
|
||||
.await
|
||||
.expect("thread should start");
|
||||
|
||||
thread.thread.ensure_rollout_materialized().await;
|
||||
thread.thread.flush_rollout().await.expect("flush rollout");
|
||||
let rollout_path = thread
|
||||
.thread
|
||||
.rollout_path()
|
||||
.expect("rollout path should exist");
|
||||
let history = RolloutRecorder::get_rollout_history(&rollout_path)
|
||||
.await
|
||||
.expect("rollout history");
|
||||
let InitialHistory::Resumed(resumed) = history else {
|
||||
panic!("expected materialized rollout history");
|
||||
};
|
||||
let RolloutItem::SessionMeta(session_meta) = &resumed.history[0] else {
|
||||
panic!("expected session metadata as first rollout item");
|
||||
};
|
||||
|
||||
assert_eq!(session_meta.meta.originator, "codex_test_app");
|
||||
|
||||
let report = manager
|
||||
.shutdown_all_threads_bounded(Duration::from_secs(10))
|
||||
.await;
|
||||
assert_eq!(report.completed, vec![thread.thread_id]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
@@ -516,6 +581,7 @@ async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
app_server_client_info: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
persist_extended_history: false,
|
||||
metrics_service_name: None,
|
||||
@@ -788,6 +854,7 @@ async fn resume_stopped_thread_from_rollout_preserves_thread_source() {
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: Some(ThreadSource::User),
|
||||
app_server_client_info: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
persist_extended_history: false,
|
||||
metrics_service_name: None,
|
||||
|
||||
@@ -5,6 +5,7 @@ use codex_core::ModelClient;
|
||||
use codex_core::Prompt;
|
||||
use codex_core::ResponseEvent;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::ClientIdentity;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_otel::SessionTelemetry;
|
||||
@@ -105,6 +106,7 @@ async fn responses_stream_includes_subagent_header_on_review() {
|
||||
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
|
||||
provider.clone(),
|
||||
session_source,
|
||||
ClientIdentity::process_default(),
|
||||
config.model_verbosity,
|
||||
/*enable_request_compression*/ false,
|
||||
/*include_timing_metrics*/ false,
|
||||
@@ -233,6 +235,7 @@ async fn responses_stream_includes_subagent_header_on_other() {
|
||||
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
|
||||
provider.clone(),
|
||||
session_source,
|
||||
ClientIdentity::process_default(),
|
||||
config.model_verbosity,
|
||||
/*enable_request_compression*/ false,
|
||||
/*include_timing_metrics*/ false,
|
||||
@@ -350,6 +353,7 @@ async fn responses_respects_model_info_overrides_from_config() {
|
||||
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
|
||||
provider.clone(),
|
||||
session_source,
|
||||
ClientIdentity::process_default(),
|
||||
config.model_verbosity,
|
||||
/*enable_request_compression*/ false,
|
||||
/*include_timing_metrics*/ false,
|
||||
|
||||
@@ -11,6 +11,7 @@ use codex_extension_api::empty_extension_registry;
|
||||
use codex_features::Feature;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::ClientIdentity;
|
||||
use codex_login::default_client::originator;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::WireApi;
|
||||
@@ -897,6 +898,7 @@ async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuth
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
provider,
|
||||
SessionSource::Exec,
|
||||
ClientIdentity::process_default(),
|
||||
config.model_verbosity,
|
||||
/*enable_request_compression*/ false,
|
||||
/*include_timing_metrics*/ false,
|
||||
@@ -2313,6 +2315,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
provider.clone(),
|
||||
SessionSource::Exec,
|
||||
ClientIdentity::process_default(),
|
||||
config.model_verbosity,
|
||||
/*enable_request_compression*/ false,
|
||||
/*include_timing_metrics*/ false,
|
||||
|
||||
@@ -8,6 +8,7 @@ use codex_core::ResponseEvent;
|
||||
use codex_core::X_RESPONSESAPI_INCLUDE_TIMING_METRICS_HEADER;
|
||||
use codex_features::Feature;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::ClientIdentity;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_otel::MetricsClient;
|
||||
@@ -2040,6 +2041,7 @@ async fn websocket_harness_with_provider_options(
|
||||
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
|
||||
provider.clone(),
|
||||
SessionSource::Exec,
|
||||
ClientIdentity::process_default(),
|
||||
config.model_verbosity,
|
||||
/*enable_request_compression*/ false,
|
||||
runtime_metrics_enabled,
|
||||
|
||||
@@ -186,6 +186,7 @@ async fn find_locates_rollout_file_written_by_recorder() -> std::io::Result<()>
|
||||
/*forked_from_id*/ None,
|
||||
SessionSource::Exec,
|
||||
/*thread_source*/ None,
|
||||
"test_originator".to_string(),
|
||||
BaseInstructions::default(),
|
||||
Vec::new(),
|
||||
),
|
||||
|
||||
@@ -13,6 +13,7 @@ use codex_terminal_detection::user_agent;
|
||||
use reqwest::header::HeaderMap;
|
||||
use reqwest::header::HeaderValue;
|
||||
use reqwest::header::USER_AGENT;
|
||||
use std::sync::Arc;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::RwLock;
|
||||
@@ -44,6 +45,18 @@ pub struct Originator {
|
||||
pub value: String,
|
||||
pub header_value: HeaderValue,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ClientIdentity {
|
||||
inner: Arc<ClientIdentityInner>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ClientIdentityInner {
|
||||
originator: Originator,
|
||||
user_agent_suffix: Option<String>,
|
||||
}
|
||||
|
||||
static ORIGINATOR: LazyLock<RwLock<Option<Originator>>> = LazyLock::new(|| RwLock::new(None));
|
||||
static REQUIREMENTS_RESIDENCY: LazyLock<RwLock<Option<ResidencyRequirement>>> =
|
||||
LazyLock::new(|| RwLock::new(None));
|
||||
@@ -75,6 +88,98 @@ fn get_originator_value(provided: Option<String>) -> Originator {
|
||||
}
|
||||
}
|
||||
|
||||
fn originator_from_explicit_value(value: String) -> Result<Originator, SetOriginatorError> {
|
||||
match HeaderValue::from_str(&value) {
|
||||
Ok(header_value) => Ok(Originator {
|
||||
value,
|
||||
header_value,
|
||||
}),
|
||||
Err(_) => Err(SetOriginatorError::InvalidHeaderValue),
|
||||
}
|
||||
}
|
||||
|
||||
fn current_user_agent_suffix() -> Option<String> {
|
||||
USER_AGENT_SUFFIX
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|guard| guard.clone())
|
||||
}
|
||||
|
||||
fn build_codex_user_agent(originator_value: &str, suffix: Option<&str>) -> String {
|
||||
let build_version = env!("CARGO_PKG_VERSION");
|
||||
let os_info = os_info::get();
|
||||
let prefix = format!(
|
||||
"{originator_value}/{build_version} ({} {}; {}) {}",
|
||||
os_info.os_type(),
|
||||
os_info.version(),
|
||||
os_info.architecture().unwrap_or("unknown"),
|
||||
user_agent()
|
||||
);
|
||||
let suffix = suffix
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map_or_else(String::new, |value| format!(" ({value})"));
|
||||
|
||||
let candidate = format!("{prefix}{suffix}");
|
||||
sanitize_user_agent(candidate, &prefix)
|
||||
}
|
||||
|
||||
fn headers_for_identity(identity: &ClientIdentity) -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("originator", identity.inner.originator.header_value.clone());
|
||||
if let Ok(user_agent) = HeaderValue::from_str(&identity.user_agent()) {
|
||||
headers.insert(USER_AGENT, user_agent);
|
||||
}
|
||||
if let Ok(guard) = REQUIREMENTS_RESIDENCY.read()
|
||||
&& let Some(requirement) = guard.as_ref()
|
||||
&& !headers.contains_key(RESIDENCY_HEADER_NAME)
|
||||
{
|
||||
let value = match requirement {
|
||||
ResidencyRequirement::Us => HeaderValue::from_static("us"),
|
||||
};
|
||||
headers.insert(RESIDENCY_HEADER_NAME, value);
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
impl ClientIdentity {
|
||||
pub fn explicit(
|
||||
originator: String,
|
||||
user_agent_suffix: Option<String>,
|
||||
) -> Result<Self, SetOriginatorError> {
|
||||
Ok(Self {
|
||||
inner: Arc::new(ClientIdentityInner {
|
||||
originator: originator_from_explicit_value(originator)?,
|
||||
user_agent_suffix,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn process_default() -> Self {
|
||||
Self {
|
||||
inner: Arc::new(ClientIdentityInner {
|
||||
originator: originator(),
|
||||
user_agent_suffix: current_user_agent_suffix(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn originator_value(&self) -> &str {
|
||||
self.inner.originator.value.as_str()
|
||||
}
|
||||
|
||||
pub fn user_agent(&self) -> String {
|
||||
build_codex_user_agent(
|
||||
self.inner.originator.value.as_str(),
|
||||
self.inner.user_agent_suffix.as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn headers_with_default_residency(&self) -> HeaderMap {
|
||||
headers_for_identity(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_default_originator(value: String) -> Result<(), SetOriginatorError> {
|
||||
if HeaderValue::from_str(&value).is_err() {
|
||||
return Err(SetOriginatorError::InvalidHeaderValue);
|
||||
@@ -131,29 +236,7 @@ pub fn is_first_party_chat_originator(originator_value: &str) -> bool {
|
||||
}
|
||||
|
||||
pub fn get_codex_user_agent() -> String {
|
||||
let build_version = env!("CARGO_PKG_VERSION");
|
||||
let os_info = os_info::get();
|
||||
let originator = originator();
|
||||
let prefix = format!(
|
||||
"{}/{build_version} ({} {}; {}) {}",
|
||||
originator.value.as_str(),
|
||||
os_info.os_type(),
|
||||
os_info.version(),
|
||||
os_info.architecture().unwrap_or("unknown"),
|
||||
user_agent()
|
||||
);
|
||||
let suffix = USER_AGENT_SUFFIX
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|guard| guard.clone());
|
||||
let suffix = suffix
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map_or_else(String::new, |value| format!(" ({value})"));
|
||||
|
||||
let candidate = format!("{prefix}{suffix}");
|
||||
sanitize_user_agent(candidate, &prefix)
|
||||
ClientIdentity::process_default().user_agent()
|
||||
}
|
||||
|
||||
/// Sanitize the user agent string.
|
||||
@@ -230,21 +313,7 @@ pub fn try_build_reqwest_client() -> Result<reqwest::Client, BuildCustomCaTransp
|
||||
}
|
||||
|
||||
pub fn default_headers() -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("originator", originator().header_value);
|
||||
if let Ok(user_agent) = HeaderValue::from_str(&get_codex_user_agent()) {
|
||||
headers.insert(USER_AGENT, user_agent);
|
||||
}
|
||||
if let Ok(guard) = REQUIREMENTS_RESIDENCY.read()
|
||||
&& let Some(requirement) = guard.as_ref()
|
||||
&& !headers.contains_key(RESIDENCY_HEADER_NAME)
|
||||
{
|
||||
let value = match requirement {
|
||||
ResidencyRequirement::Us => HeaderValue::from_static("us"),
|
||||
};
|
||||
headers.insert(RESIDENCY_HEADER_NAME, value);
|
||||
}
|
||||
headers
|
||||
ClientIdentity::process_default().headers_with_default_residency()
|
||||
}
|
||||
|
||||
fn is_sandboxed() -> bool {
|
||||
|
||||
@@ -2,6 +2,30 @@ use super::sanitize_user_agent;
|
||||
use super::*;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serial_test::serial;
|
||||
|
||||
static RESIDENCY_TEST_LOCK: std::sync::LazyLock<std::sync::Mutex<()>> =
|
||||
std::sync::LazyLock::new(|| std::sync::Mutex::new(()));
|
||||
|
||||
struct ResidencyGuard {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
}
|
||||
|
||||
impl ResidencyGuard {
|
||||
fn set(enforce_residency: Option<ResidencyRequirement>) -> Self {
|
||||
let lock = RESIDENCY_TEST_LOCK
|
||||
.lock()
|
||||
.expect("residency test lock should not be poisoned");
|
||||
set_default_client_residency_requirement(enforce_residency);
|
||||
Self { _lock: lock }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ResidencyGuard {
|
||||
fn drop(&mut self) {
|
||||
set_default_client_residency_requirement(/*enforce_residency*/ None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_codex_user_agent() {
|
||||
@@ -11,6 +35,119 @@ fn test_get_codex_user_agent() {
|
||||
assert!(user_agent.starts_with(&prefix));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_client_identity_builds_expected_headers() {
|
||||
let _guard = ResidencyGuard::set(Some(ResidencyRequirement::Us));
|
||||
|
||||
let identity = ClientIdentity::explicit(
|
||||
"codex_test_client".to_string(),
|
||||
Some("codex_test_client; 1.2.3".to_string()),
|
||||
)
|
||||
.expect("explicit identity should be valid");
|
||||
let headers = identity.headers_with_default_residency();
|
||||
let user_agent = identity.user_agent();
|
||||
|
||||
assert_eq!(identity.originator_value(), "codex_test_client");
|
||||
assert!(user_agent.starts_with("codex_test_client/"));
|
||||
assert!(user_agent.ends_with(" (codex_test_client; 1.2.3)"));
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("originator")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("codex_test_client"),
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get(reqwest::header::USER_AGENT)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some(user_agent.as_str()),
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get(RESIDENCY_HEADER_NAME)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("us"),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_client_identity_rejects_invalid_originator() {
|
||||
assert!(matches!(
|
||||
ClientIdentity::explicit(
|
||||
"bad\noriginator".to_string(),
|
||||
/*user_agent_suffix*/ None
|
||||
),
|
||||
Err(SetOriginatorError::InvalidHeaderValue)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_default_client_identity_matches_default_headers() {
|
||||
let identity = ClientIdentity::process_default();
|
||||
let identity_headers = identity.headers_with_default_residency();
|
||||
let default_headers = default_headers();
|
||||
|
||||
assert_eq!(identity.user_agent(), get_codex_user_agent());
|
||||
assert_eq!(
|
||||
identity_headers
|
||||
.get("originator")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
default_headers
|
||||
.get("originator")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
);
|
||||
assert_eq!(
|
||||
identity_headers
|
||||
.get(reqwest::header::USER_AGENT)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
default_headers
|
||||
.get(reqwest::header::USER_AGENT)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial(default_client_env)]
|
||||
fn explicit_client_identity_ignores_originator_override_env_var() {
|
||||
struct EnvGuard {
|
||||
key: &'static str,
|
||||
previous: Option<String>,
|
||||
}
|
||||
|
||||
impl Drop for EnvGuard {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: this test is serialized with other tests that mutate this env var.
|
||||
unsafe {
|
||||
match &self.previous {
|
||||
Some(value) => std::env::set_var(self.key, value),
|
||||
None => std::env::remove_var(self.key),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _guard = EnvGuard {
|
||||
key: CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR,
|
||||
previous: std::env::var(CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR).ok(),
|
||||
};
|
||||
// SAFETY: this test is serialized with other tests that mutate this env var.
|
||||
unsafe {
|
||||
std::env::set_var(
|
||||
CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR,
|
||||
"codex_env_override",
|
||||
);
|
||||
}
|
||||
|
||||
let identity = ClientIdentity::explicit(
|
||||
"codex_explicit_client".to_string(),
|
||||
/*user_agent_suffix*/ None,
|
||||
)
|
||||
.expect("explicit identity should be valid");
|
||||
|
||||
assert_eq!(identity.originator_value(), "codex_explicit_client");
|
||||
assert!(identity.user_agent().starts_with("codex_explicit_client/"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_first_party_originator_matches_known_values() {
|
||||
assert_eq!(is_first_party_originator(DEFAULT_ORIGINATOR), true);
|
||||
@@ -36,15 +173,16 @@ fn is_first_party_chat_originator_matches_known_values() {
|
||||
async fn test_create_client_sets_default_headers() {
|
||||
skip_if_no_network!();
|
||||
|
||||
set_default_client_residency_requirement(Some(ResidencyRequirement::Us));
|
||||
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
let client = create_client();
|
||||
let client = {
|
||||
let _guard = ResidencyGuard::set(Some(ResidencyRequirement::Us));
|
||||
create_client()
|
||||
};
|
||||
|
||||
// Spin up a local mock server and capture a request.
|
||||
let server = MockServer::start().await;
|
||||
@@ -85,8 +223,6 @@ async fn test_create_client_sets_default_headers() {
|
||||
.get(RESIDENCY_HEADER_NAME)
|
||||
.expect("residency header missing");
|
||||
assert_eq!(residency_header.to_str().unwrap(), "us");
|
||||
|
||||
set_default_client_residency_requirement(/*enforce_residency*/ None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -12,6 +12,7 @@ use codex_features::Feature;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::auth_env_telemetry::collect_auth_env_telemetry;
|
||||
use codex_login::default_client::ClientIdentity;
|
||||
use codex_login::default_client::originator;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_otel::TelemetryAuthMode;
|
||||
@@ -179,6 +180,7 @@ impl MemoryStartupContext {
|
||||
installation_id,
|
||||
config.model_provider.clone(),
|
||||
session_source,
|
||||
ClientIdentity::process_default(),
|
||||
config.model_verbosity,
|
||||
config.features.enabled(Feature::EnableRequestCompression),
|
||||
config.features.enabled(Feature::RuntimeMetrics),
|
||||
@@ -245,6 +247,7 @@ impl MemoryStartupContext {
|
||||
InternalSessionSource::MemoryConsolidation,
|
||||
)),
|
||||
thread_source: Some(ThreadSource::MemoryConsolidation),
|
||||
app_server_client_info: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
persist_extended_history: false,
|
||||
metrics_service_name: None,
|
||||
|
||||
@@ -13,10 +13,6 @@ pub(crate) mod session_index;
|
||||
mod sqlite_metrics;
|
||||
pub mod state_db;
|
||||
|
||||
pub(crate) mod default_client {
|
||||
pub use codex_login::default_client::*;
|
||||
}
|
||||
|
||||
pub(crate) use codex_protocol::protocol;
|
||||
|
||||
pub const SESSIONS_SUBDIR: &str = "sessions";
|
||||
|
||||
@@ -44,7 +44,6 @@ use super::list::parse_timestamp_uuid_from_filename;
|
||||
use super::metadata;
|
||||
use super::session_index::find_thread_names_by_ids;
|
||||
use crate::config::RolloutConfigView;
|
||||
use crate::default_client::originator;
|
||||
use crate::state_db;
|
||||
use crate::state_db::StateDbHandle;
|
||||
use codex_git_utils::collect_git_info;
|
||||
@@ -83,6 +82,7 @@ pub enum RolloutRecorderParams {
|
||||
forked_from_id: Option<ThreadId>,
|
||||
source: SessionSource,
|
||||
thread_source: Option<ThreadSource>,
|
||||
originator: String,
|
||||
base_instructions: BaseInstructions,
|
||||
dynamic_tools: Vec<DynamicToolSpec>,
|
||||
},
|
||||
@@ -158,6 +158,7 @@ impl RolloutRecorderParams {
|
||||
forked_from_id: Option<ThreadId>,
|
||||
source: SessionSource,
|
||||
thread_source: Option<ThreadSource>,
|
||||
originator: String,
|
||||
base_instructions: BaseInstructions,
|
||||
dynamic_tools: Vec<DynamicToolSpec>,
|
||||
) -> Self {
|
||||
@@ -166,6 +167,7 @@ impl RolloutRecorderParams {
|
||||
forked_from_id,
|
||||
source,
|
||||
thread_source,
|
||||
originator,
|
||||
base_instructions,
|
||||
dynamic_tools,
|
||||
}
|
||||
@@ -654,6 +656,7 @@ impl RolloutRecorder {
|
||||
forked_from_id,
|
||||
source,
|
||||
thread_source,
|
||||
originator,
|
||||
base_instructions,
|
||||
dynamic_tools,
|
||||
} => {
|
||||
@@ -675,7 +678,7 @@ impl RolloutRecorder {
|
||||
forked_from_id,
|
||||
timestamp,
|
||||
cwd: config.cwd().to_path_buf(),
|
||||
originator: originator().value,
|
||||
originator,
|
||||
cli_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
agent_nickname: source.get_nickname(),
|
||||
agent_role: source.get_agent_role(),
|
||||
|
||||
@@ -370,6 +370,7 @@ async fn recorder_materializes_on_flush_with_pending_items() -> std::io::Result<
|
||||
/*forked_from_id*/ None,
|
||||
SessionSource::Exec,
|
||||
/*thread_source*/ None,
|
||||
"test_originator".to_string(),
|
||||
BaseInstructions::default(),
|
||||
Vec::new(),
|
||||
),
|
||||
@@ -419,6 +420,13 @@ async fn recorder_materializes_on_flush_with_pending_items() -> std::io::Result<
|
||||
text.contains("\"type\":\"session_meta\""),
|
||||
"expected session metadata in rollout"
|
||||
);
|
||||
let first_line = text.lines().next().expect("session metadata line");
|
||||
let first_line: RolloutLine =
|
||||
serde_json::from_str(first_line).expect("session metadata should parse");
|
||||
let RolloutItem::SessionMeta(session_meta) = first_line.item else {
|
||||
panic!("expected first rollout item to be session metadata");
|
||||
};
|
||||
assert_eq!(session_meta.meta.originator, "test_originator");
|
||||
let buffered_idx = text
|
||||
.find("buffered-event")
|
||||
.expect("buffered event in rollout");
|
||||
@@ -448,6 +456,7 @@ async fn persist_reports_filesystem_error_and_retries_buffered_items() -> std::i
|
||||
/*forked_from_id*/ None,
|
||||
SessionSource::Exec,
|
||||
/*thread_source*/ None,
|
||||
"test_originator".to_string(),
|
||||
BaseInstructions::default(),
|
||||
Vec::new(),
|
||||
),
|
||||
|
||||
@@ -32,6 +32,7 @@ pub(super) async fn create_thread(
|
||||
params.forked_from_id,
|
||||
params.source,
|
||||
params.thread_source,
|
||||
params.originator,
|
||||
params.base_instructions,
|
||||
params.dynamic_tools,
|
||||
),
|
||||
|
||||
@@ -1015,6 +1015,7 @@ mod tests {
|
||||
forked_from_id: None,
|
||||
source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
originator: "test_originator".to_string(),
|
||||
base_instructions: BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
metadata: thread_metadata(),
|
||||
|
||||
@@ -76,6 +76,8 @@ pub struct CreateThreadParams {
|
||||
pub source: SessionSource,
|
||||
/// Optional analytics source classification for this thread.
|
||||
pub thread_source: Option<ThreadSource>,
|
||||
/// Product/client identity persisted in session metadata.
|
||||
pub originator: String,
|
||||
/// Base instructions persisted in session metadata.
|
||||
pub base_instructions: BaseInstructions,
|
||||
/// Dynamic tools available to the thread at startup.
|
||||
|
||||
Reference in New Issue
Block a user