Base: codex-main originale (prima del fork aKode)
This commit is contained in:
57
codex-rs/app-server/src/account_notifications.rs
Normal file
57
codex-rs/app-server/src/account_notifications.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
//! Publishes account snapshots only while their authentication owner is current.
|
||||
//! Superseded login attempts still receive a terminal completion notification.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::AccountLoginCompletedNotification;
|
||||
use codex_app_server_protocol::AccountUpdatedNotification;
|
||||
use codex_login::AuthChangeState;
|
||||
use tokio::sync::watch;
|
||||
|
||||
pub(crate) enum AccountNotification {
|
||||
LoginCompleted(AccountLoginCompletedNotification),
|
||||
Updated(AccountUpdatedNotification),
|
||||
}
|
||||
|
||||
impl OutgoingMessageSender {
|
||||
pub(crate) async fn send_account_notification(
|
||||
&self,
|
||||
connection_id: Option<ConnectionId>,
|
||||
auth_changes: &watch::Receiver<AuthChangeState>,
|
||||
owner_generation: u64,
|
||||
notification: AccountNotification,
|
||||
) {
|
||||
let Ok(permit) = self.sender.reserve().await else {
|
||||
return;
|
||||
};
|
||||
// Keep the revision read lock through enqueue; never wait while holding it.
|
||||
let current_auth = auth_changes.borrow();
|
||||
let notification = match notification {
|
||||
AccountNotification::LoginCompleted(mut payload) => {
|
||||
if payload.success && current_auth.owner_generation != owner_generation {
|
||||
payload.success = false;
|
||||
payload.error = Some("account changed before sign-in completed".into());
|
||||
}
|
||||
ServerNotification::AccountLoginCompleted(payload)
|
||||
}
|
||||
AccountNotification::Updated(payload) => {
|
||||
if current_auth.owner_generation != owner_generation {
|
||||
return;
|
||||
}
|
||||
ServerNotification::AccountUpdated(payload)
|
||||
}
|
||||
};
|
||||
let message = timestamped_server_notification(notification);
|
||||
permit.send(match connection_id {
|
||||
Some(connection_id) => OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message,
|
||||
write_complete_tx: None,
|
||||
},
|
||||
None => OutgoingEnvelope::Broadcast { message },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "account_notifications_tests.rs"]
|
||||
mod tests;
|
||||
101
codex-rs/app-server/src/account_notifications_tests.rs
Normal file
101
codex-rs/app-server/src/account_notifications_tests.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
//! Exercises auth changes while notification delivery waits for queue capacity.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use test_case::test_case;
|
||||
|
||||
#[test_case(0; "same_owner_refresh")]
|
||||
#[test_case(1; "owner_change")]
|
||||
#[test_case(2; "coalesced_owner_changes")]
|
||||
#[tokio::test]
|
||||
async fn queued_notifications_follow_auth_owner_changes(owner_generation: u64) {
|
||||
for login in [false, true] {
|
||||
let (tx, mut rx) = mpsc::channel(/*buffer*/ 1);
|
||||
let outgoing = OutgoingMessageSender::new(
|
||||
tx.clone(),
|
||||
codex_analytics::AnalyticsEventsClient::disabled(),
|
||||
);
|
||||
let (changes, auth_changes) = watch::channel(AuthChangeState::default());
|
||||
let updated = AccountUpdatedNotification {
|
||||
auth_mode: None,
|
||||
plan_type: None,
|
||||
};
|
||||
tx.send(OutgoingEnvelope::Broadcast {
|
||||
message: timestamped_server_notification(ServerNotification::AccountUpdated(
|
||||
updated.clone(),
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let payload = AccountLoginCompletedNotification {
|
||||
login_id: Some("queued-login".into()),
|
||||
success: true,
|
||||
error: None,
|
||||
onboarding_entrypoint: None,
|
||||
};
|
||||
let notification = if login {
|
||||
AccountNotification::LoginCompleted(payload.clone())
|
||||
} else {
|
||||
AccountNotification::Updated(updated.clone())
|
||||
};
|
||||
let send = outgoing.send_account_notification(
|
||||
Some(ConnectionId(7)),
|
||||
&auth_changes,
|
||||
/*owner_generation*/ 0,
|
||||
notification,
|
||||
);
|
||||
tokio::pin!(send);
|
||||
// Poll delivery with a full queue before changing authentication.
|
||||
assert!(futures::poll!(&mut send).is_pending());
|
||||
changes.send_replace(AuthChangeState {
|
||||
generation: 2,
|
||||
owner_generation,
|
||||
source_generation: owner_generation,
|
||||
login_generation: owner_generation,
|
||||
});
|
||||
rx.recv().await.unwrap();
|
||||
send.await;
|
||||
if login {
|
||||
let OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message: OutgoingMessage::AppServerNotification(envelope),
|
||||
..
|
||||
} = rx.try_recv().unwrap()
|
||||
else {
|
||||
panic!("expected targeted login completion");
|
||||
};
|
||||
assert_eq!(connection_id, ConnectionId(7));
|
||||
let ServerNotification::AccountLoginCompleted(actual) = envelope.notification else {
|
||||
panic!("expected login completion");
|
||||
};
|
||||
assert_eq!(
|
||||
actual,
|
||||
if owner_generation == 0 {
|
||||
payload
|
||||
} else {
|
||||
AccountLoginCompletedNotification {
|
||||
success: false,
|
||||
error: Some("account changed before sign-in completed".into()),
|
||||
..payload
|
||||
}
|
||||
}
|
||||
);
|
||||
} else if owner_generation == 0 {
|
||||
let OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message: OutgoingMessage::AppServerNotification(envelope),
|
||||
..
|
||||
} = rx.try_recv().unwrap()
|
||||
else {
|
||||
panic!("expected targeted account update");
|
||||
};
|
||||
assert_eq!(connection_id, ConnectionId(7));
|
||||
let ServerNotification::AccountUpdated(actual) = envelope.notification else {
|
||||
panic!("expected account update");
|
||||
};
|
||||
assert_eq!(actual, updated);
|
||||
} else {
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
32
codex-rs/app-server/src/analytics_utils.rs
Normal file
32
codex-rs/app-server/src/analytics_utils.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_core::config::Config;
|
||||
use codex_login::AuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeAuthSlot;
|
||||
|
||||
pub(crate) fn analytics_events_client_from_config(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
config: &Config,
|
||||
runtime_auth_slot: Option<RuntimeAuthSlot>,
|
||||
) -> AnalyticsEventsClient {
|
||||
let api_key_headers =
|
||||
if codex_model_provider::provider_uses_first_party_auth_path(&config.model_provider) {
|
||||
match config.model_provider.build_header_map() {
|
||||
Ok(headers) => headers,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "failed to resolve analytics resource selectors");
|
||||
return AnalyticsEventsClient::disabled();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
AnalyticsEventsClient::new_with_runtime(
|
||||
auth_manager,
|
||||
config.chatgpt_backend_url(),
|
||||
config.analytics_enabled,
|
||||
runtime_auth_slot.map(|slot| (slot, config.runtime_auth_mode)),
|
||||
api_key_headers,
|
||||
)
|
||||
}
|
||||
175
codex-rs/app-server/src/app_info.rs
Normal file
175
codex-rs/app-server/src/app_info.rs
Normal file
@@ -0,0 +1,175 @@
|
||||
use codex_app_server_protocol::AppBranding as ApiAppBranding;
|
||||
use codex_app_server_protocol::AppInfo as ApiAppInfo;
|
||||
use codex_app_server_protocol::AppMetadata as ApiAppMetadata;
|
||||
use codex_app_server_protocol::AppReview as ApiAppReview;
|
||||
use codex_app_server_protocol::AppScreenshot as ApiAppScreenshot;
|
||||
use codex_app_server_protocol::AppToolSummary as ApiAppToolSummary;
|
||||
use codex_app_server_protocol::ConnectorMetadata as ApiConnectorMetadata;
|
||||
use codex_connectors::AppBranding;
|
||||
use codex_connectors::AppInfo;
|
||||
use codex_connectors::AppMetadata;
|
||||
use codex_connectors::AppReview;
|
||||
use codex_connectors::AppScreenshot;
|
||||
use codex_connectors::ConnectorMetadata;
|
||||
use codex_connectors::ConnectorToolSummary;
|
||||
use codex_connectors::metadata::connector_install_url;
|
||||
|
||||
/// Converts connector-domain app metadata owned by `codex-connectors` into the app-server wire
|
||||
/// type owned by `codex-app-server-protocol`.
|
||||
///
|
||||
/// The types stay separate so app-server protocol ownership does not leak into the connector
|
||||
/// domain crate. Because this crate owns neither type, Rust's orphan rules require an explicit
|
||||
/// conversion function instead of a `From` implementation.
|
||||
pub(crate) fn app_info_to_api(app: AppInfo) -> ApiAppInfo {
|
||||
let AppInfo {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
logo_url,
|
||||
logo_url_dark,
|
||||
icon_assets,
|
||||
icon_dark_assets,
|
||||
distribution_channel,
|
||||
branding,
|
||||
app_metadata,
|
||||
labels,
|
||||
install_url,
|
||||
is_accessible,
|
||||
is_enabled,
|
||||
plugin_display_names,
|
||||
} = app;
|
||||
ApiAppInfo {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
logo_url,
|
||||
logo_url_dark,
|
||||
icon_assets,
|
||||
icon_dark_assets,
|
||||
distribution_channel,
|
||||
branding: branding.map(app_branding_to_api),
|
||||
app_metadata: app_metadata.map(app_metadata_to_api),
|
||||
labels,
|
||||
install_url,
|
||||
is_accessible,
|
||||
is_enabled,
|
||||
plugin_display_names,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts metadata-only connector data into the app-server wire type.
|
||||
///
|
||||
/// Keeping this separate from app_info_to_api makes it impossible for app/read to accidentally
|
||||
/// expose full runtime tool state from the broader app/list path.
|
||||
pub(crate) fn connector_metadata_to_api(metadata: ConnectorMetadata) -> ApiConnectorMetadata {
|
||||
let ConnectorMetadata {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
icon_url,
|
||||
icon_url_dark,
|
||||
distribution_channel,
|
||||
tool_summaries,
|
||||
} = metadata;
|
||||
let install_url = Some(connector_install_url(&name, &id));
|
||||
ApiConnectorMetadata {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
icon_url,
|
||||
icon_url_dark,
|
||||
distribution_channel,
|
||||
install_url,
|
||||
plugin_display_names: Vec::new(),
|
||||
tool_summaries: tool_summaries.map(|tools| {
|
||||
tools
|
||||
.into_iter()
|
||||
.map(|tool| {
|
||||
let ConnectorToolSummary {
|
||||
name,
|
||||
title,
|
||||
description,
|
||||
is_enabled,
|
||||
disabled_reason,
|
||||
is_read_only,
|
||||
} = tool;
|
||||
ApiAppToolSummary {
|
||||
name,
|
||||
title,
|
||||
description,
|
||||
is_enabled,
|
||||
disabled_reason,
|
||||
is_read_only,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn app_branding_to_api(branding: AppBranding) -> ApiAppBranding {
|
||||
let AppBranding {
|
||||
category,
|
||||
developer,
|
||||
website,
|
||||
privacy_policy,
|
||||
terms_of_service,
|
||||
is_discoverable_app,
|
||||
} = branding;
|
||||
ApiAppBranding {
|
||||
category,
|
||||
developer,
|
||||
website,
|
||||
privacy_policy,
|
||||
terms_of_service,
|
||||
is_discoverable_app,
|
||||
}
|
||||
}
|
||||
|
||||
fn app_review_to_api(review: AppReview) -> ApiAppReview {
|
||||
let AppReview { status } = review;
|
||||
ApiAppReview { status }
|
||||
}
|
||||
|
||||
fn app_screenshot_to_api(screenshot: AppScreenshot) -> ApiAppScreenshot {
|
||||
let AppScreenshot {
|
||||
url,
|
||||
file_id,
|
||||
user_prompt,
|
||||
} = screenshot;
|
||||
ApiAppScreenshot {
|
||||
url,
|
||||
file_id,
|
||||
user_prompt,
|
||||
}
|
||||
}
|
||||
|
||||
fn app_metadata_to_api(metadata: AppMetadata) -> ApiAppMetadata {
|
||||
let AppMetadata {
|
||||
review,
|
||||
categories,
|
||||
sub_categories,
|
||||
seo_description,
|
||||
screenshots,
|
||||
developer,
|
||||
version,
|
||||
version_id,
|
||||
version_notes,
|
||||
first_party_requires_install,
|
||||
show_in_composer_when_unlinked,
|
||||
} = metadata;
|
||||
ApiAppMetadata {
|
||||
review: review.map(app_review_to_api),
|
||||
categories,
|
||||
sub_categories,
|
||||
seo_description,
|
||||
screenshots: screenshots
|
||||
.map(|screenshots| screenshots.into_iter().map(app_screenshot_to_api).collect()),
|
||||
developer,
|
||||
version,
|
||||
version_id,
|
||||
version_notes,
|
||||
first_party_requires_install,
|
||||
show_in_composer_when_unlinked,
|
||||
}
|
||||
}
|
||||
180
codex-rs/app-server/src/app_server_tracing.rs
Normal file
180
codex-rs/app-server/src/app_server_tracing.rs
Normal file
@@ -0,0 +1,180 @@
|
||||
//! Tracing helpers shared by socket and in-process app-server entry points.
|
||||
//!
|
||||
//! The in-process path intentionally reuses the same span shape as JSON-RPC
|
||||
//! transports so request telemetry stays comparable across stdio, websocket,
|
||||
//! and embedded callers. [`typed_request_span`] is the in-process counterpart
|
||||
//! of [`request_span`] and stamps `rpc.transport` as `"in-process"` while
|
||||
//! deriving client identity from the typed [`ClientRequest`] rather than
|
||||
//! from a parsed JSON envelope.
|
||||
|
||||
use crate::message_processor::ConnectionSessionState;
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::transport::AppServerTransport;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::InitializeParams;
|
||||
use codex_app_server_protocol::JSONRPCRequest;
|
||||
use codex_otel::set_parent_from_context;
|
||||
use codex_otel::set_parent_from_w3c_trace_context;
|
||||
use codex_otel::traceparent_context_from_env;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use tracing::Span;
|
||||
use tracing::field;
|
||||
use tracing::info_span;
|
||||
|
||||
pub(crate) fn request_span(
|
||||
request: &JSONRPCRequest,
|
||||
transport: &AppServerTransport,
|
||||
connection_id: ConnectionId,
|
||||
session: &ConnectionSessionState,
|
||||
) -> Span {
|
||||
let initialize_client_info = initialize_client_info(request);
|
||||
let method = request.method.as_str();
|
||||
let span = app_server_request_span_template(
|
||||
method,
|
||||
transport_name(transport),
|
||||
&request.id,
|
||||
connection_id,
|
||||
);
|
||||
|
||||
record_client_info(
|
||||
&span,
|
||||
client_name(initialize_client_info.as_ref(), session),
|
||||
client_version(initialize_client_info.as_ref(), session),
|
||||
);
|
||||
|
||||
let parent_trace = request.trace.as_ref().and_then(|trace| {
|
||||
trace.traceparent.as_ref()?;
|
||||
Some(W3cTraceContext {
|
||||
traceparent: trace.traceparent.clone(),
|
||||
tracestate: trace.tracestate.clone(),
|
||||
})
|
||||
});
|
||||
attach_parent_context(&span, method, &request.id, parent_trace.as_ref());
|
||||
|
||||
span
|
||||
}
|
||||
|
||||
/// Builds tracing span metadata for typed in-process requests.
|
||||
///
|
||||
/// This mirrors `request_span` semantics while stamping transport as
|
||||
/// `in-process` and deriving client info either from initialize params or
|
||||
/// from existing connection session state.
|
||||
pub(crate) fn typed_request_span(
|
||||
request: &ClientRequest,
|
||||
connection_id: ConnectionId,
|
||||
session: &ConnectionSessionState,
|
||||
) -> Span {
|
||||
let method = request.method_name();
|
||||
let span = app_server_request_span_template(method, "in-process", request.id(), connection_id);
|
||||
|
||||
let client_info = initialize_client_info_from_typed_request(request);
|
||||
record_client_info(
|
||||
&span,
|
||||
client_info
|
||||
.map(|(client_name, _)| client_name)
|
||||
.or(session.app_server_client_name()),
|
||||
client_info
|
||||
.map(|(_, client_version)| client_version)
|
||||
.or(session.client_version()),
|
||||
);
|
||||
|
||||
attach_parent_context(&span, method, request.id(), /*parent_trace*/ None);
|
||||
span
|
||||
}
|
||||
|
||||
fn transport_name(transport: &AppServerTransport) -> &'static str {
|
||||
match transport {
|
||||
AppServerTransport::Stdio => "stdio",
|
||||
AppServerTransport::UnixSocket { .. } => "unix_socket",
|
||||
AppServerTransport::WebSocket { .. } => "websocket",
|
||||
AppServerTransport::Off => "off",
|
||||
}
|
||||
}
|
||||
|
||||
fn app_server_request_span_template(
|
||||
method: &str,
|
||||
transport: &'static str,
|
||||
request_id: &impl std::fmt::Display,
|
||||
connection_id: ConnectionId,
|
||||
) -> Span {
|
||||
info_span!(
|
||||
"app_server.request",
|
||||
otel.kind = "server",
|
||||
otel.name = method,
|
||||
rpc.system = "jsonrpc",
|
||||
rpc.method = method,
|
||||
rpc.transport = transport,
|
||||
rpc.request_id = %request_id,
|
||||
app_server.connection_id = %connection_id,
|
||||
app_server.api_version = "v2",
|
||||
app_server.client_name = field::Empty,
|
||||
app_server.client_version = field::Empty,
|
||||
turn.id = field::Empty,
|
||||
)
|
||||
}
|
||||
|
||||
fn record_client_info(span: &Span, client_name: Option<&str>, client_version: Option<&str>) {
|
||||
if let Some(client_name) = client_name {
|
||||
span.record("app_server.client_name", client_name);
|
||||
}
|
||||
if let Some(client_version) = client_version {
|
||||
span.record("app_server.client_version", client_version);
|
||||
}
|
||||
}
|
||||
|
||||
fn attach_parent_context(
|
||||
span: &Span,
|
||||
method: &str,
|
||||
request_id: &impl std::fmt::Display,
|
||||
parent_trace: Option<&W3cTraceContext>,
|
||||
) {
|
||||
if let Some(trace) = parent_trace {
|
||||
if !set_parent_from_w3c_trace_context(span, trace) {
|
||||
tracing::warn!(
|
||||
rpc_method = method,
|
||||
rpc_request_id = %request_id,
|
||||
"ignoring invalid inbound request trace carrier"
|
||||
);
|
||||
}
|
||||
} else if let Some(context) = traceparent_context_from_env() {
|
||||
set_parent_from_context(span, context);
|
||||
}
|
||||
}
|
||||
|
||||
fn client_name<'a>(
|
||||
initialize_client_info: Option<&'a InitializeParams>,
|
||||
session: &'a ConnectionSessionState,
|
||||
) -> Option<&'a str> {
|
||||
if let Some(params) = initialize_client_info {
|
||||
return Some(params.client_info.name.as_str());
|
||||
}
|
||||
session.app_server_client_name()
|
||||
}
|
||||
|
||||
fn client_version<'a>(
|
||||
initialize_client_info: Option<&'a InitializeParams>,
|
||||
session: &'a ConnectionSessionState,
|
||||
) -> Option<&'a str> {
|
||||
if let Some(params) = initialize_client_info {
|
||||
return Some(params.client_info.version.as_str());
|
||||
}
|
||||
session.client_version()
|
||||
}
|
||||
|
||||
fn initialize_client_info(request: &JSONRPCRequest) -> Option<InitializeParams> {
|
||||
if request.method != "initialize" {
|
||||
return None;
|
||||
}
|
||||
let params = request.params.clone()?;
|
||||
serde_json::from_value(params).ok()
|
||||
}
|
||||
|
||||
fn initialize_client_info_from_typed_request(request: &ClientRequest) -> Option<(&str, &str)> {
|
||||
match request {
|
||||
ClientRequest::Initialize { params, .. } => Some((
|
||||
params.client_info.name.as_str(),
|
||||
params.client_info.version.as_str(),
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
160
codex-rs/app-server/src/application_network.rs
Normal file
160
codex-rs/app-server/src/application_network.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
//! Installs application requirements at startup and explicit config/account reloads.
|
||||
//! Local policy limits cloud bootstrap; config construction rejects superseded policy snapshots.
|
||||
|
||||
use super::ApplicationPolicyLoad;
|
||||
use super::ApplicationPolicySnapshot;
|
||||
use super::ConfigManager;
|
||||
use codex_config::ApplicationRequirementsToml;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::NetworkDomainPermissionToml;
|
||||
use codex_http_client::DestinationPolicy;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) fn destination_policy(
|
||||
application: Option<&ApplicationRequirementsToml>,
|
||||
) -> DestinationPolicy {
|
||||
match application.and_then(|application| application.network.as_ref()) {
|
||||
Some(network) if network.enabled => DestinationPolicy::Restricted {
|
||||
allowed_hosts: network
|
||||
.domains
|
||||
.iter()
|
||||
.filter(|&(_host, permission)| *permission == NetworkDomainPermissionToml::Allow)
|
||||
.map(|(host, _permission)| host.clone())
|
||||
.collect(),
|
||||
},
|
||||
Some(_) | None => DestinationPolicy::Unrestricted,
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigManager {
|
||||
pub(super) async fn refresh_local_network_policy(
|
||||
&self,
|
||||
) -> io::Result<codex_config::loader::LocalApplicationRequirements> {
|
||||
let _reload = self
|
||||
.network_policy_reload
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
self.load_local_network_policy(self.network_policy.policy().revision())
|
||||
.await
|
||||
}
|
||||
|
||||
async fn load_local_network_policy(
|
||||
&self,
|
||||
application_revision: codex_http_client::NetworkPolicyRevision,
|
||||
) -> io::Result<codex_config::loader::LocalApplicationRequirements> {
|
||||
let local_revision = self.local_network_policy.policy().revision();
|
||||
let result = async {
|
||||
let sources = codex_config::loader::load_local_application_requirements(
|
||||
codex_exec_server::LOCAL_FS.as_ref(),
|
||||
&self.loader_overrides,
|
||||
)
|
||||
.await?;
|
||||
let application = sources.compose(Default::default())?;
|
||||
self.local_network_policy
|
||||
.publish(local_revision, destination_policy(application.as_ref()));
|
||||
Ok(sources)
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
self.local_network_policy.unavailable(local_revision);
|
||||
self.fail_application_policy(application_revision)?;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) async fn refresh_application_network_policy(
|
||||
&self,
|
||||
) -> io::Result<ApplicationPolicyLoad> {
|
||||
let _reload = self
|
||||
.network_policy_reload
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let revision = self.network_policy.policy().revision();
|
||||
let local_sources = self.load_local_network_policy(revision).await?;
|
||||
let cloud_config = self.current_managed_config_loader();
|
||||
let result = async {
|
||||
let cloud_snapshot = cloud_config.get_snapshot().await;
|
||||
let cloud = cloud_snapshot.bundle.clone().map_err(io::Error::other)?;
|
||||
let application = local_sources.compose(
|
||||
cloud
|
||||
.as_ref()
|
||||
.map(|bundle| bundle.requirements_toml.clone())
|
||||
.unwrap_or_default(),
|
||||
)?;
|
||||
Ok::<_, io::Error>((
|
||||
destination_policy(application.as_ref()),
|
||||
cloud,
|
||||
cloud_snapshot,
|
||||
))
|
||||
}
|
||||
.await;
|
||||
match result {
|
||||
Ok((policy, cloud, cloud_snapshot)) => {
|
||||
let mut current = self.network_policy_snapshot.write().map_err(|_| {
|
||||
io::Error::other("application network policy snapshot lock poisoned")
|
||||
})?;
|
||||
if !self.network_policy.publish(revision, policy.clone()) {
|
||||
*current = None;
|
||||
return Err(io::Error::other(NetworkPolicyDenied::Revoked));
|
||||
}
|
||||
let next = ApplicationPolicySnapshot {
|
||||
revision,
|
||||
policy,
|
||||
cloud,
|
||||
};
|
||||
// Concurrent config loads may finish together if their actual inputs are unchanged.
|
||||
let snapshot = match current.as_ref() {
|
||||
Some(snapshot) if snapshot.as_ref() == &next => Arc::clone(snapshot),
|
||||
_ => {
|
||||
let snapshot = Arc::new(next);
|
||||
*current = Some(Arc::clone(&snapshot));
|
||||
snapshot
|
||||
}
|
||||
};
|
||||
Ok(ApplicationPolicyLoad {
|
||||
cloud_config: CloudConfigBundleLoader::from_snapshot(cloud_snapshot),
|
||||
snapshot,
|
||||
})
|
||||
}
|
||||
Err(error) => {
|
||||
self.fail_application_policy(revision)?;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn check_application_policy_load(
|
||||
&self,
|
||||
load: &ApplicationPolicyLoad,
|
||||
) -> io::Result<()> {
|
||||
let current = self
|
||||
.network_policy_snapshot
|
||||
.read()
|
||||
.map_err(|_| io::Error::other("application network policy snapshot lock poisoned"))?;
|
||||
if self.network_policy.policy().revision() != load.snapshot.revision
|
||||
|| !current
|
||||
.as_ref()
|
||||
.is_some_and(|snapshot| Arc::ptr_eq(snapshot, &load.snapshot))
|
||||
{
|
||||
return Err(io::Error::other(NetworkPolicyDenied::Revoked));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fail_application_policy(
|
||||
&self,
|
||||
revision: codex_http_client::NetworkPolicyRevision,
|
||||
) -> io::Result<()> {
|
||||
let mut current = self
|
||||
.network_policy_snapshot
|
||||
.write()
|
||||
.map_err(|_| io::Error::other("application network policy snapshot lock poisoned"))?;
|
||||
self.network_policy.unavailable(revision);
|
||||
*current = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
282
codex-rs/app-server/src/application_network_tests.rs
Normal file
282
codex-rs/app-server/src/application_network_tests.rs
Normal file
@@ -0,0 +1,282 @@
|
||||
//! Checks that overlapping policy reloads cannot publish out of order.
|
||||
|
||||
use super::ConfigManager;
|
||||
use anyhow::Result;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use tempfile::tempdir;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[tokio::test]
|
||||
async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() -> Result<()> {
|
||||
use crate::in_process::EmbeddedNetworkPolicy;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let home = tempdir()?;
|
||||
let requirements = home.path().join("requirements.toml");
|
||||
std::fs::write(&requirements, "[application.network]")?;
|
||||
let overrides = LoaderOverrides {
|
||||
system_requirements_path: Some(requirements.clone()),
|
||||
..LoaderOverrides::without_managed_config_for_tests()
|
||||
};
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.loader_overrides(overrides.clone())
|
||||
.build()
|
||||
.await?;
|
||||
config.chatgpt_base_url = server.uri();
|
||||
let cloud_endpoint = format!("{}/api/codex/config/bundle", server.uri());
|
||||
let policy = EmbeddedNetworkPolicy::load(&overrides).await;
|
||||
let bootstrap_auth = policy.bind_bootstrap_auth(config.auth_config());
|
||||
let bootstrap = bootstrap_auth
|
||||
.auth_route_config
|
||||
.http_client_factory()
|
||||
.build_client(&cloud_endpoint, ClientRouteClass::Auth)?;
|
||||
let application = policy
|
||||
.bind(config.http_client_factory())
|
||||
.build_client(&server.uri(), ClientRouteClass::Other)?;
|
||||
assert!(bootstrap.get(&cloud_endpoint).send().await.is_err());
|
||||
assert!(application.get(server.uri()).send().await.is_err());
|
||||
policy.activate(&mut config);
|
||||
let caller_factory = config.http_client_factory();
|
||||
let caller_client = caller_factory.build_client(&server.uri(), ClientRouteClass::Other)?;
|
||||
let worktree_bootstrap = policy.clone().bind_bootstrap_auth(config.auth_config());
|
||||
let worktree_client = worktree_bootstrap
|
||||
.auth_route_config
|
||||
.http_client_factory()
|
||||
.build_client(&cloud_endpoint, ClientRouteClass::Auth)?;
|
||||
assert!(caller_client.get(server.uri()).send().await.is_err());
|
||||
assert!(worktree_client.get(&cloud_endpoint).send().await.is_err());
|
||||
assert!(
|
||||
caller_factory
|
||||
.network_policy()
|
||||
.acquire_for_unsupported_sdk()
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let manager = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
overrides,
|
||||
CloudConfigBundleLoader::default(),
|
||||
)
|
||||
.with_embedded_network_policy(policy);
|
||||
drop(manager.refresh_application_network_policy().await?);
|
||||
assert!(application.get(server.uri()).send().await.is_err());
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
|
||||
std::fs::remove_file(&requirements)?;
|
||||
let unrestricted = manager.refresh_application_network_policy().await?;
|
||||
let unrelated_endpoint = format!("{}/not-the-config-endpoint", server.uri()).parse()?;
|
||||
assert_eq!(
|
||||
bootstrap_auth
|
||||
.auth_route_config
|
||||
.http_client_factory()
|
||||
.network_policy()
|
||||
.acquire(&unrelated_endpoint)
|
||||
.map(|_| ()),
|
||||
Err(NetworkPolicyDenied::Destination),
|
||||
);
|
||||
caller_client.get(server.uri()).send().await?;
|
||||
worktree_client.get(&cloud_endpoint).send().await?;
|
||||
assert!(
|
||||
caller_factory
|
||||
.network_policy()
|
||||
.acquire_for_unsupported_sdk()
|
||||
.is_ok()
|
||||
);
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 2);
|
||||
std::fs::write(&requirements, "[malformed")?;
|
||||
assert!(manager.refresh_application_network_policy().await.is_err());
|
||||
assert!(caller_client.get(server.uri()).send().await.is_err());
|
||||
assert!(worktree_client.get(&cloud_endpoint).send().await.is_err());
|
||||
assert!(
|
||||
caller_factory
|
||||
.network_policy()
|
||||
.acquire_for_unsupported_sdk()
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
manager
|
||||
.check_application_policy_load(&unrestricted)
|
||||
.is_err()
|
||||
);
|
||||
std::fs::remove_file(requirements)?;
|
||||
let recovered = manager.refresh_application_network_policy().await?;
|
||||
manager.check_application_policy_load(&recovered)?;
|
||||
assert!(
|
||||
manager
|
||||
.check_application_policy_load(&unrestricted)
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn embedded_caller_activation_uses_cloud_requirements() -> Result<()> {
|
||||
use crate::in_process::EmbeddedNetworkPolicy;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
|
||||
let home = tempdir()?;
|
||||
let overrides = LoaderOverrides::without_managed_config_for_tests();
|
||||
let policy = EmbeddedNetworkPolicy::load(&overrides).await;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.loader_overrides(overrides)
|
||||
.cloud_config_bundle(
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement("[application.network]"),
|
||||
)
|
||||
.build()
|
||||
.await?;
|
||||
policy.activate(&mut config);
|
||||
let factory = config.http_client_factory();
|
||||
assert!(
|
||||
factory
|
||||
.network_policy()
|
||||
.acquire_for_unsupported_sdk()
|
||||
.is_err()
|
||||
);
|
||||
let url = "https://denied.example".parse()?;
|
||||
assert!(factory.network_policy().acquire(&url).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn overlapping_policy_reloads_publish_in_order() -> Result<()> {
|
||||
let home = tempdir()?;
|
||||
let entered = Arc::new(Semaphore::new(/*permits*/ 0));
|
||||
let release = Arc::new(Semaphore::new(/*permits*/ 0));
|
||||
let calls = Arc::new(AtomicUsize::new(/*v*/ 0));
|
||||
let loader = CloudConfigBundleLoader::from_getter({
|
||||
let (entered, release, calls) = (entered.clone(), release.clone(), calls.clone());
|
||||
move || {
|
||||
let (entered, release, calls) = (entered.clone(), release.clone(), calls.clone());
|
||||
async move {
|
||||
let call = calls.fetch_add(/*val*/ 1, Ordering::SeqCst);
|
||||
let host = if call == 0 {
|
||||
entered.add_permits(/*n*/ 1);
|
||||
release
|
||||
.acquire()
|
||||
.await
|
||||
.expect("release first reload")
|
||||
.forget();
|
||||
"old.example"
|
||||
} else if call == 3 {
|
||||
"old.example"
|
||||
} else {
|
||||
"new.example"
|
||||
};
|
||||
Ok(Some(
|
||||
CloudConfigBundleFixture::enterprise_requirement(format!(
|
||||
"[application.network.domains]\n'{host}' = 'allow'"
|
||||
))
|
||||
.into_bundle(),
|
||||
))
|
||||
}
|
||||
}
|
||||
});
|
||||
let manager = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
loader,
|
||||
);
|
||||
let first = tokio::spawn({
|
||||
let manager = manager.clone();
|
||||
async move { manager.refresh_application_network_policy().await }
|
||||
});
|
||||
entered.acquire().await?.forget();
|
||||
let mut second = tokio::spawn({
|
||||
let manager = manager.clone();
|
||||
async move { manager.refresh_application_network_policy().await }
|
||||
});
|
||||
assert!(
|
||||
timeout(Duration::from_millis(/*millis*/ 100), &mut second)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
release.add_permits(/*n*/ 1);
|
||||
let first_load = first.await??;
|
||||
let second_load = timeout(Duration::from_secs(/*secs*/ 5), second).await???;
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 2);
|
||||
manager.check_application_policy_load(&second_load)?;
|
||||
let stale = manager
|
||||
.check_application_policy_load(&first_load)
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
stale.get_ref().and_then(|error| error.downcast_ref()),
|
||||
Some(&NetworkPolicyDenied::Revoked)
|
||||
);
|
||||
|
||||
let policy = manager.network_policy.policy();
|
||||
assert_eq!(
|
||||
policy.acquire(&"https://old.example".parse()?).map(|_| ()),
|
||||
Err(NetworkPolicyDenied::Destination)
|
||||
);
|
||||
assert_eq!(
|
||||
policy.acquire(&"https://new.example".parse()?).map(|_| ()),
|
||||
Ok(())
|
||||
);
|
||||
let unchanged = manager.refresh_application_network_policy().await?;
|
||||
manager.check_application_policy_load(&second_load)?;
|
||||
manager.check_application_policy_load(&unchanged)?;
|
||||
let restored = manager.refresh_application_network_policy().await?;
|
||||
manager.check_application_policy_load(&restored)?;
|
||||
assert!(manager.check_application_policy_load(&first_load).is_err());
|
||||
assert!(manager.check_application_policy_load(&second_load).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cloud_config_change_supersedes_load_even_when_network_rules_are_unchanged() -> Result<()> {
|
||||
let home = tempdir()?;
|
||||
let calls = AtomicUsize::new(/*v*/ 0);
|
||||
let loader = CloudConfigBundleLoader::from_getter(move || {
|
||||
let model = if calls.fetch_add(/*val*/ 1, Ordering::SeqCst) == 0 {
|
||||
"old"
|
||||
} else {
|
||||
"new"
|
||||
};
|
||||
async move {
|
||||
Ok(Some(
|
||||
CloudConfigBundleFixture::enterprise_config(format!("model = '{model}'"))
|
||||
.into_bundle(),
|
||||
))
|
||||
}
|
||||
});
|
||||
let manager = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
loader,
|
||||
);
|
||||
let first = manager.refresh_application_network_policy().await?;
|
||||
let second = manager.refresh_application_network_policy().await?;
|
||||
manager.check_application_policy_load(&second)?;
|
||||
let stale = manager.check_application_policy_load(&first).unwrap_err();
|
||||
assert_eq!(
|
||||
stale.get_ref().and_then(|error| error.downcast_ref()),
|
||||
Some(&NetworkPolicyDenied::Revoked)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
220
codex-rs/app-server/src/attestation.rs
Normal file
220
codex-rs/app-server/src/attestation.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use axum::http::HeaderValue;
|
||||
use codex_app_server_protocol::AttestationGenerateParams;
|
||||
use codex_app_server_protocol::AttestationGenerateResponse;
|
||||
use codex_app_server_protocol::ServerRequestPayload;
|
||||
use codex_core::AttestationContext;
|
||||
use codex_core::AttestationProvider;
|
||||
use codex_core::GenerateAttestationFuture;
|
||||
use serde::Serialize;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use crate::thread_state::ThreadStateManager;
|
||||
|
||||
const ATTESTATION_GENERATE_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
|
||||
pub(crate) fn app_server_attestation_provider(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
thread_state_manager: ThreadStateManager,
|
||||
) -> Arc<dyn AttestationProvider> {
|
||||
Arc::new(AppServerAttestationProvider {
|
||||
outgoing: Arc::downgrade(&outgoing),
|
||||
thread_state_manager,
|
||||
})
|
||||
}
|
||||
|
||||
struct AppServerAttestationProvider {
|
||||
outgoing: Weak<OutgoingMessageSender>,
|
||||
thread_state_manager: ThreadStateManager,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AppServerAttestationProvider {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("AppServerAttestationProvider")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl AttestationProvider for AppServerAttestationProvider {
|
||||
fn header_for_request(&self, context: AttestationContext) -> GenerateAttestationFuture<'_> {
|
||||
let Some(outgoing) = self.outgoing.upgrade() else {
|
||||
return Box::pin(async { None });
|
||||
};
|
||||
let thread_state_manager = self.thread_state_manager.clone();
|
||||
Box::pin(async move {
|
||||
request_attestation_header_value_with_timeout(
|
||||
outgoing,
|
||||
thread_state_manager,
|
||||
context.thread_id,
|
||||
ATTESTATION_GENERATE_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
.and_then(|value| HeaderValue::from_bytes(value.as_bytes()).ok())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_attestation_header_value_with_timeout(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
thread_state_manager: ThreadStateManager,
|
||||
thread_id: codex_protocol::ThreadId,
|
||||
timeout_duration: Duration,
|
||||
) -> Option<String> {
|
||||
let connection_id = thread_state_manager
|
||||
.first_attestation_capable_connection_for_thread(thread_id)
|
||||
.await?;
|
||||
|
||||
let connection_ids = [connection_id];
|
||||
let (request_id, rx) = outgoing
|
||||
.send_request_to_connections(
|
||||
Some(&connection_ids),
|
||||
ServerRequestPayload::AttestationGenerate(AttestationGenerateParams {}),
|
||||
/*thread_id*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
let result = match timeout(timeout_duration, rx).await {
|
||||
Ok(Ok(Ok(result))) => result,
|
||||
Ok(Ok(Err(err))) => {
|
||||
// Don't log err.message because it may contain a token.
|
||||
warn!(code = err.code, "attestation generation request failed");
|
||||
return app_server_attestation_header_value(
|
||||
AppServerAttestationStatus::RequestFailed,
|
||||
/*token*/ None,
|
||||
);
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
warn!("attestation generation request canceled: {err}");
|
||||
return app_server_attestation_header_value(
|
||||
AppServerAttestationStatus::RequestCanceled,
|
||||
/*token*/ None,
|
||||
);
|
||||
}
|
||||
Err(_) => {
|
||||
let _canceled = outgoing.cancel_request(&request_id).await;
|
||||
warn!(
|
||||
timeout_seconds = timeout_duration.as_secs(),
|
||||
"attestation generation request timed out"
|
||||
);
|
||||
return app_server_attestation_header_value(
|
||||
AppServerAttestationStatus::Timeout,
|
||||
/*token*/ None,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
match serde_json::from_value::<AttestationGenerateResponse>(result) {
|
||||
Ok(response) => app_server_attestation_header_value(
|
||||
AppServerAttestationStatus::Ok,
|
||||
Some(&response.token),
|
||||
),
|
||||
Err(err) => {
|
||||
warn!(
|
||||
error_category = ?err.classify(),
|
||||
"failed to deserialize attestation generation response"
|
||||
);
|
||||
app_server_attestation_header_value(
|
||||
AppServerAttestationStatus::MalformedResponse,
|
||||
/*token*/ None,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum AppServerAttestationStatus {
|
||||
Ok,
|
||||
Timeout,
|
||||
RequestFailed,
|
||||
RequestCanceled,
|
||||
MalformedResponse,
|
||||
}
|
||||
|
||||
impl AppServerAttestationStatus {
|
||||
const fn code(self) -> u8 {
|
||||
match self {
|
||||
Self::Ok => 0,
|
||||
Self::Timeout => 1,
|
||||
Self::RequestFailed => 2,
|
||||
Self::RequestCanceled => 3,
|
||||
Self::MalformedResponse => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct AppServerAttestationEnvelope<'a> {
|
||||
v: u8,
|
||||
s: u8,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
t: Option<&'a str>,
|
||||
}
|
||||
|
||||
fn app_server_attestation_header_value(
|
||||
status: AppServerAttestationStatus,
|
||||
token: Option<&str>,
|
||||
) -> Option<String> {
|
||||
serde_json::to_string(&AppServerAttestationEnvelope {
|
||||
v: 1,
|
||||
s: status.code(),
|
||||
t: token,
|
||||
})
|
||||
.map_err(|err| warn!("failed to serialize app-server attestation envelope: {err}"))
|
||||
.ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::AppServerAttestationStatus;
|
||||
use super::app_server_attestation_header_value;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn app_server_attestation_header_value_wraps_opaque_client_payloads() {
|
||||
assert_eq!(
|
||||
app_server_attestation_header_value(
|
||||
AppServerAttestationStatus::Ok,
|
||||
Some("v1.opaque-client-payload"),
|
||||
),
|
||||
Some(r#"{"v":1,"s":0,"t":"v1.opaque-client-payload"}"#.to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_attestation_header_value_reports_app_server_failures() {
|
||||
assert_eq!(
|
||||
app_server_attestation_header_value(
|
||||
AppServerAttestationStatus::Timeout,
|
||||
/*token*/ None,
|
||||
),
|
||||
Some(r#"{"v":1,"s":1}"#.to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
app_server_attestation_header_value(
|
||||
AppServerAttestationStatus::RequestFailed,
|
||||
/*token*/ None,
|
||||
),
|
||||
Some(r#"{"v":1,"s":2}"#.to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
app_server_attestation_header_value(
|
||||
AppServerAttestationStatus::RequestCanceled,
|
||||
/*token*/ None,
|
||||
),
|
||||
Some(r#"{"v":1,"s":3}"#.to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
app_server_attestation_header_value(
|
||||
AppServerAttestationStatus::MalformedResponse,
|
||||
/*token*/ None
|
||||
),
|
||||
Some(r#"{"v":1,"s":4}"#.to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
21
codex-rs/app-server/src/auth_mode.rs
Normal file
21
codex-rs/app-server/src/auth_mode.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
use codex_app_server_protocol::AuthMode as ApiAuthMode;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
|
||||
/// Converts the domain auth mode owned by `codex-protocol` into the app-server wire type owned by
|
||||
/// `codex-app-server-protocol`.
|
||||
///
|
||||
/// The types stay separate so app-server protocol ownership does not leak into domain crates.
|
||||
/// Because this crate owns neither type, Rust's orphan rules require an explicit conversion
|
||||
/// function instead of a `From` implementation.
|
||||
pub(crate) fn auth_mode_to_api(auth_mode: AuthMode) -> ApiAuthMode {
|
||||
match auth_mode {
|
||||
AuthMode::ApiKey => ApiAuthMode::ApiKey,
|
||||
AuthMode::Chatgpt => ApiAuthMode::Chatgpt,
|
||||
AuthMode::ChatgptAuthTokens => ApiAuthMode::ChatgptAuthTokens,
|
||||
AuthMode::Headers => ApiAuthMode::Headers,
|
||||
AuthMode::AgentIdentity => ApiAuthMode::AgentIdentity,
|
||||
AuthMode::PersonalAccessToken => ApiAuthMode::PersonalAccessToken,
|
||||
AuthMode::BedrockApiKey => ApiAuthMode::BedrockApiKey,
|
||||
AuthMode::BedrockAccessKeys => ApiAuthMode::BedrockAccessKeys,
|
||||
}
|
||||
}
|
||||
4045
codex-rs/app-server/src/bespoke_event_handling.rs
Normal file
4045
codex-rs/app-server/src/bespoke_event_handling.rs
Normal file
File diff suppressed because it is too large
Load Diff
42
codex-rs/app-server/src/bin/exec_server.rs
Normal file
42
codex-rs/app-server/src/bin/exec_server.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
//! Cargo entry point for the minimal exec-server integration-test fixture.
|
||||
//!
|
||||
//! This mirrors `//codex-rs/exec-server/testing:exec-server` so Cargo-backed
|
||||
//! app-server integration tests can receive `CARGO_BIN_EXE_exec-server`. It
|
||||
//! also handles the helper argv modes because exec-server re-execs
|
||||
//! `codex_self_exe` for sandboxed filesystem and process requests.
|
||||
|
||||
use codex_exec_server::ExecServerRuntimeOptions;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use std::ffi::OsStr;
|
||||
|
||||
const CODEX_LINUX_SANDBOX_EXE_ENV_VAR: &str = "CODEX_TEST_LINUX_SANDBOX_EXE";
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
#[cfg(target_os = "linux")]
|
||||
codex_utils_pty::init_spawn_helper(std::env::args_os());
|
||||
let mut args = std::env::args_os();
|
||||
let _ = args.next();
|
||||
let argv1 = args.next();
|
||||
#[cfg(unix)]
|
||||
if argv1.as_deref() == Some(OsStr::new(codex_exec_server::CODEX_ARG0_EXEC_HELPER_ARG1)) {
|
||||
codex_exec_server::run_arg0_exec_helper_main();
|
||||
}
|
||||
if argv1.as_deref() == Some(OsStr::new(codex_exec_server::CODEX_FS_HELPER_ARG1)) {
|
||||
codex_exec_server::run_fs_helper_main();
|
||||
}
|
||||
|
||||
let current_exe = std::env::current_exe()?;
|
||||
let codex_linux_sandbox_exe =
|
||||
std::env::var_os(CODEX_LINUX_SANDBOX_EXE_ENV_VAR).map(std::path::PathBuf::from);
|
||||
let runtime_paths = ExecServerRuntimeOptions::new(current_exe, codex_linux_sandbox_exe)?;
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()?
|
||||
.block_on(codex_exec_server::run_main(
|
||||
"ws://127.0.0.1:0",
|
||||
runtime_paths,
|
||||
// This test-only fixture has no application configuration to resolve HTTP policy.
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
))
|
||||
}
|
||||
44
codex-rs/app-server/src/bin/notify_capture.rs
Normal file
44
codex-rs/app-server/src/bin/notify_capture.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use anyhow::bail;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut args = env::args_os();
|
||||
let _program = args.next();
|
||||
let output_path = PathBuf::from(
|
||||
args.next()
|
||||
.ok_or_else(|| anyhow!("expected output path as first argument"))?,
|
||||
);
|
||||
let payload = args
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("expected payload as final argument"))?;
|
||||
|
||||
if args.next().is_some() {
|
||||
bail!("expected payload as final argument");
|
||||
}
|
||||
|
||||
let payload = payload.to_string_lossy();
|
||||
let temp_path = PathBuf::from(format!("{}.tmp", output_path.display()));
|
||||
let mut file = File::create(&temp_path)
|
||||
.with_context(|| format!("failed to create {}", temp_path.display()))?;
|
||||
file.write_all(payload.as_bytes())
|
||||
.with_context(|| format!("failed to write {}", temp_path.display()))?;
|
||||
file.sync_all()
|
||||
.with_context(|| format!("failed to sync {}", temp_path.display()))?;
|
||||
fs::rename(&temp_path, &output_path).with_context(|| {
|
||||
format!(
|
||||
"failed to move {} into {}",
|
||||
temp_path.display(),
|
||||
output_path.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
23
codex-rs/app-server/src/bin/test_notify_capture.rs
Normal file
23
codex-rs/app-server/src/bin/test_notify_capture.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut args = env::args_os().skip(1);
|
||||
let output_path = PathBuf::from(
|
||||
args.next()
|
||||
.ok_or_else(|| anyhow!("missing output path argument"))?,
|
||||
);
|
||||
let payload = args
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("missing payload argument"))?
|
||||
.into_string()
|
||||
.map_err(|_| anyhow!("payload must be valid UTF-8"))?;
|
||||
|
||||
let temp_path = output_path.with_extension("json.tmp");
|
||||
std::fs::write(&temp_path, payload)?;
|
||||
std::fs::rename(&temp_path, &output_path)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
83
codex-rs/app-server/src/code_mode_host.rs
Normal file
83
codex-rs/app-server/src/code_mode_host.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use std::ffi::OsStr;
|
||||
|
||||
use clap::Args;
|
||||
use clap::builder::TypedValueParser;
|
||||
use clap::error::ErrorKind;
|
||||
use url::Url;
|
||||
|
||||
/// Selects the code-mode host for a single app-server process.
|
||||
#[derive(Args, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AppServerCodeModeHostArgs {
|
||||
/// Connect to a remote code-mode host instead of starting a local host.
|
||||
#[arg(
|
||||
long = "code-mode-host",
|
||||
value_name = "URL",
|
||||
value_parser = RedactedHostUrlParser
|
||||
)]
|
||||
pub code_mode_host: Option<Url>,
|
||||
}
|
||||
|
||||
/// Process-scoped transport used to reach the code-mode host.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub enum CodeModeHostTransport {
|
||||
/// Start and own the default local code-mode host.
|
||||
#[default]
|
||||
Local,
|
||||
/// Share an HTTP/2 gRPC connection to the specified remote code-mode host.
|
||||
Grpc(Url),
|
||||
}
|
||||
|
||||
impl From<AppServerCodeModeHostArgs> for CodeModeHostTransport {
|
||||
fn from(args: AppServerCodeModeHostArgs) -> Self {
|
||||
match args.code_mode_host {
|
||||
Some(url) => Self::Grpc(url),
|
||||
None => Self::Local,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct RedactedHostUrlParser;
|
||||
|
||||
impl TypedValueParser for RedactedHostUrlParser {
|
||||
type Value = Url;
|
||||
|
||||
fn parse_ref(
|
||||
&self,
|
||||
command: &clap::Command,
|
||||
_argument: Option<&clap::Arg>,
|
||||
value: &OsStr,
|
||||
) -> Result<Self::Value, clap::Error> {
|
||||
let value = value.to_str().ok_or_else(|| {
|
||||
clap::Error::raw(
|
||||
ErrorKind::InvalidUtf8,
|
||||
"code-mode host URL must contain valid UTF-8",
|
||||
)
|
||||
.with_cmd(command)
|
||||
})?;
|
||||
|
||||
parse_host_url(value)
|
||||
.map_err(|error| clap::Error::raw(ErrorKind::ValueValidation, error).with_cmd(command))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_host_url(value: &str) -> Result<Url, String> {
|
||||
let url = Url::parse(value).map_err(|error| format!("invalid code-mode host URL: {error}"))?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||
return Err("code-mode host URL must use http:// or https:// with a host".to_string());
|
||||
}
|
||||
if url.fragment().is_some() {
|
||||
return Err("code-mode host URL must not contain a fragment".to_string());
|
||||
}
|
||||
if !url.username().is_empty() || url.password().is_some() {
|
||||
return Err("gRPC code-mode host URL must not contain credentials".to_string());
|
||||
}
|
||||
if url.path() != "/" || url.query().is_some() {
|
||||
return Err("gRPC code-mode host URL must not contain a path or query".to_string());
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "code_mode_host_tests.rs"]
|
||||
mod tests;
|
||||
74
codex-rs/app-server/src/code_mode_host_tests.rs
Normal file
74
codex-rs/app-server/src/code_mode_host_tests.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
use super::AppServerCodeModeHostArgs;
|
||||
use super::CodeModeHostTransport;
|
||||
use super::parse_host_url;
|
||||
use pretty_assertions::assert_eq;
|
||||
use url::Url;
|
||||
|
||||
#[test]
|
||||
fn grpc_host_accepts_local_and_secure_endpoints() {
|
||||
for endpoint in ["http://127.0.0.1:8765", "https://example.test"] {
|
||||
assert_eq!(
|
||||
parse_host_url(endpoint),
|
||||
Ok(Url::parse(endpoint).expect("test endpoint should parse"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grpc_host_rejects_credentials_without_disclosing_them() {
|
||||
for endpoint in [
|
||||
"http://alice:secret@example.test",
|
||||
"https://alice:secret@example.test",
|
||||
"https://alice@example.test",
|
||||
"https://:secret@example.test",
|
||||
] {
|
||||
let error = parse_host_url(endpoint).expect_err("gRPC credentials should be rejected");
|
||||
|
||||
assert!(error.contains("must not contain credentials"));
|
||||
assert!(!error.contains("alice"));
|
||||
assert!(!error.contains("secret"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_mode_host_rejects_invalid_endpoints() {
|
||||
for endpoint in [
|
||||
"ftp://127.0.0.1:8765",
|
||||
"ws://",
|
||||
"ws://127.0.0.1:8765",
|
||||
"wss://example.test/code-mode",
|
||||
"ws://alice:secret@example.test/code-mode",
|
||||
"wss://alice:secret@example.test/code-mode",
|
||||
"wss://example.test/code-mode#fragment",
|
||||
"http://",
|
||||
"not a host endpoint",
|
||||
"https://example.test/code-mode#fragment",
|
||||
"https://example.test/code-mode",
|
||||
"http://example.test/?token=secret",
|
||||
] {
|
||||
assert!(
|
||||
parse_host_url(endpoint).is_err(),
|
||||
"invalid code-mode host endpoint should be rejected: {endpoint}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omitted_host_selects_local_transport() {
|
||||
assert_eq!(
|
||||
CodeModeHostTransport::from(AppServerCodeModeHostArgs::default()),
|
||||
CodeModeHostTransport::Local
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_grpc_host_selects_remote_transport() {
|
||||
let url = Url::parse("https://example.test").expect("test endpoint should parse");
|
||||
|
||||
assert_eq!(
|
||||
CodeModeHostTransport::from(AppServerCodeModeHostArgs {
|
||||
code_mode_host: Some(url.clone()),
|
||||
}),
|
||||
CodeModeHostTransport::Grpc(url)
|
||||
);
|
||||
}
|
||||
115
codex-rs/app-server/src/codex_home_metrics.rs
Normal file
115
codex-rs/app-server/src/codex_home_metrics.rs
Normal file
@@ -0,0 +1,115 @@
|
||||
//! Measures local session storage once at standalone app-server startup.
|
||||
//!
|
||||
//! The background scan only visits sessions and archived_sessions under CODEX_HOME.
|
||||
//! It sums regular-file lengths without reading file contents or following symlinks.
|
||||
//! Incomplete scans emit no samples, and shutdown cancels the scan.
|
||||
//! The compression tag reflects the effective startup config, not compression completion.
|
||||
|
||||
use codex_core::config::Config;
|
||||
use codex_features::Feature;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_rollout::ARCHIVED_SESSIONS_SUBDIR;
|
||||
use codex_rollout::SESSIONS_SUBDIR;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const SIZE_BYTES_METRIC: &str = "codex.app_server.codex_home.size_bytes";
|
||||
// Bucket sizes range from 1 MiB through 1 TiB; larger directories use the overflow bucket.
|
||||
const SIZE_BYTES_BOUNDARIES: &[f64] = &[
|
||||
1_048_576.0,
|
||||
10_485_760.0,
|
||||
104_857_600.0,
|
||||
1_073_741_824.0,
|
||||
10_737_418_240.0,
|
||||
107_374_182_400.0,
|
||||
1_099_511_627_776.0,
|
||||
];
|
||||
|
||||
pub(crate) fn spawn(
|
||||
config: &Config,
|
||||
metrics: MetricsClient,
|
||||
shutdown: CancellationToken,
|
||||
) -> JoinHandle<()> {
|
||||
let codex_home = config.codex_home.to_path_buf();
|
||||
let compression_enabled = config
|
||||
.features
|
||||
.enabled(Feature::LocalThreadStoreCompression)
|
||||
.to_string();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let sizes = match directory_sizes(&codex_home, &shutdown) {
|
||||
Ok(sizes) => sizes,
|
||||
Err(error) => {
|
||||
tracing::debug!(error_kind = ?error.kind(), "Skipping CODEX_HOME size metrics");
|
||||
return;
|
||||
}
|
||||
};
|
||||
for (directory, bytes) in [
|
||||
(SESSIONS_SUBDIR, sizes.sessions),
|
||||
(ARCHIVED_SESSIONS_SUBDIR, sizes.archived_sessions),
|
||||
] {
|
||||
let _ = metrics.histogram_with_boundaries(
|
||||
SIZE_BYTES_METRIC,
|
||||
i64::try_from(bytes).unwrap_or(i64::MAX),
|
||||
SIZE_BYTES_BOUNDARIES,
|
||||
&[
|
||||
("directory", directory),
|
||||
("compression_enabled", compression_enabled.as_str()),
|
||||
],
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
struct DirectorySizes {
|
||||
sessions: u64,
|
||||
archived_sessions: u64,
|
||||
}
|
||||
|
||||
fn directory_sizes(codex_home: &Path, shutdown: &CancellationToken) -> io::Result<DirectorySizes> {
|
||||
let sessions = codex_home.join(SESSIONS_SUBDIR);
|
||||
let archived_sessions = codex_home.join(ARCHIVED_SESSIONS_SUBDIR);
|
||||
let mut sizes = DirectorySizes::default();
|
||||
let mut pending = Vec::new();
|
||||
for directory in [&sessions, &archived_sessions] {
|
||||
if shutdown.is_cancelled() {
|
||||
return Err(io::ErrorKind::Interrupted.into());
|
||||
}
|
||||
// Inspect the roots without following symlinks, just like entries below them.
|
||||
let metadata = match std::fs::symlink_metadata(directory) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if metadata.is_dir() {
|
||||
pending.push(directory.to_path_buf());
|
||||
}
|
||||
}
|
||||
while let Some(directory) = pending.pop() {
|
||||
if shutdown.is_cancelled() {
|
||||
return Err(io::ErrorKind::Interrupted.into());
|
||||
}
|
||||
for entry in std::fs::read_dir(directory)? {
|
||||
if shutdown.is_cancelled() {
|
||||
return Err(io::ErrorKind::Interrupted.into());
|
||||
}
|
||||
let entry = entry?;
|
||||
// DirEntry::metadata does not follow symbolic links.
|
||||
let metadata = entry.metadata()?;
|
||||
let path = entry.path();
|
||||
if metadata.is_dir() {
|
||||
pending.push(path);
|
||||
} else if metadata.is_file() {
|
||||
let bytes = metadata.len();
|
||||
if path.starts_with(&sessions) {
|
||||
sizes.sessions = sizes.sessions.saturating_add(bytes);
|
||||
} else if path.starts_with(&archived_sessions) {
|
||||
sizes.archived_sessions = sizes.archived_sessions.saturating_add(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(sizes)
|
||||
}
|
||||
1079
codex-rs/app-server/src/command_exec.rs
Normal file
1079
codex-rs/app-server/src/command_exec.rs
Normal file
File diff suppressed because it is too large
Load Diff
66
codex-rs/app-server/src/config_layer.rs
Normal file
66
codex-rs/app-server/src/config_layer.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
use codex_app_server_protocol::ConfigLayer as ApiConfigLayer;
|
||||
use codex_app_server_protocol::ConfigLayerMetadata as ApiConfigLayerMetadata;
|
||||
use codex_app_server_protocol::ConfigLayerSource as ApiConfigLayerSource;
|
||||
use codex_config::ConfigLayer;
|
||||
use codex_config::ConfigLayerMetadata;
|
||||
use codex_config::ConfigLayerSource;
|
||||
|
||||
/// Converts a config-layer source owned by `codex-config` into the app-server wire type owned by
|
||||
/// `codex-app-server-protocol`.
|
||||
///
|
||||
/// The types stay separate so app-server protocol ownership does not leak into the config domain
|
||||
/// crate. Because this crate owns neither type, Rust's orphan rules require an explicit conversion
|
||||
/// function instead of a `From` implementation.
|
||||
pub(crate) fn config_layer_source_to_api(source: ConfigLayerSource) -> ApiConfigLayerSource {
|
||||
match source {
|
||||
ConfigLayerSource::PackagedDefaults { file } => {
|
||||
ApiConfigLayerSource::PackagedDefaults { file }
|
||||
}
|
||||
ConfigLayerSource::Mdm { domain, key } => ApiConfigLayerSource::Mdm { domain, key },
|
||||
ConfigLayerSource::System { file } => ApiConfigLayerSource::System { file },
|
||||
ConfigLayerSource::EnterpriseManaged { id, name } => {
|
||||
ApiConfigLayerSource::EnterpriseManaged { id, name }
|
||||
}
|
||||
ConfigLayerSource::User { file, profile } => ApiConfigLayerSource::User { file, profile },
|
||||
ConfigLayerSource::Project { dot_codex_folder } => {
|
||||
ApiConfigLayerSource::Project { dot_codex_folder }
|
||||
}
|
||||
ConfigLayerSource::SessionFlags => ApiConfigLayerSource::SessionFlags,
|
||||
ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => {
|
||||
ApiConfigLayerSource::LegacyManagedConfigTomlFromFile { file }
|
||||
}
|
||||
ConfigLayerSource::LegacyManagedConfigTomlFromMdm => {
|
||||
ApiConfigLayerSource::LegacyManagedConfigTomlFromMdm
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts config-layer metadata owned by `codex-config` into the app-server wire type owned by
|
||||
/// `codex-app-server-protocol`.
|
||||
///
|
||||
/// The types stay separate so app-server protocol ownership does not leak into the config domain
|
||||
/// crate. Because this crate owns neither type, Rust's orphan rules require an explicit conversion
|
||||
/// function instead of a `From` implementation.
|
||||
pub(crate) fn config_layer_metadata_to_api(
|
||||
metadata: ConfigLayerMetadata,
|
||||
) -> ApiConfigLayerMetadata {
|
||||
ApiConfigLayerMetadata {
|
||||
name: config_layer_source_to_api(metadata.name),
|
||||
version: metadata.version,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a config layer owned by `codex-config` into the app-server wire type owned by
|
||||
/// `codex-app-server-protocol`.
|
||||
///
|
||||
/// The types stay separate so app-server protocol ownership does not leak into the config domain
|
||||
/// crate. Because this crate owns neither type, Rust's orphan rules require an explicit conversion
|
||||
/// function instead of a `From` implementation.
|
||||
pub(crate) fn config_layer_to_api(layer: ConfigLayer) -> ApiConfigLayer {
|
||||
ApiConfigLayer {
|
||||
name: config_layer_source_to_api(layer.name),
|
||||
version: layer.version,
|
||||
config: layer.config,
|
||||
disabled_reason: layer.disabled_reason,
|
||||
}
|
||||
}
|
||||
852
codex-rs/app-server/src/config_manager.rs
Normal file
852
codex-rs/app-server/src/config_manager.rs
Normal file
@@ -0,0 +1,852 @@
|
||||
use codex_app_server_protocol::ModelProviderError;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_cloud_config::managed_config_bundle_loader;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::ThreadConfigLoader;
|
||||
use codex_config::apply_default_gcp_auth;
|
||||
use codex_config::loader::load_config_layers_state;
|
||||
use codex_config::loader::load_managed_requirements_state;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_features::feature_for_key;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::default_client::set_default_client_residency_requirement;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_ID;
|
||||
use codex_model_provider_info::GCP_PROVIDER_ID;
|
||||
use codex_model_provider_info::OPENAI_PROVIDER_ID;
|
||||
use codex_model_provider_info::built_in_model_providers;
|
||||
use codex_model_provider_info::merge_configured_model_providers;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_json_to_toml::json_to_toml;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::RwLock;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use toml::Value as TomlValue;
|
||||
use tracing::instrument;
|
||||
use tracing::warn;
|
||||
|
||||
#[path = "application_network.rs"]
|
||||
pub(crate) mod application_network;
|
||||
|
||||
/// Shared app-server entry point for loading effective Codex configuration.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ConfigManager {
|
||||
codex_home: PathBuf,
|
||||
cli_overrides: Arc<RwLock<Vec<(String, TomlValue)>>>,
|
||||
runtime_feature_enablement: Arc<RwLock<BTreeMap<String, bool>>>,
|
||||
loader_overrides: LoaderOverrides,
|
||||
strict_config: bool,
|
||||
cloud_config_bundle: Arc<RwLock<CloudConfigBundleLoader>>,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
thread_config_loader: Arc<dyn ThreadConfigLoader>,
|
||||
network_policy: codex_http_client::NetworkPolicyController,
|
||||
local_network_policy: codex_http_client::NetworkPolicyController,
|
||||
network_policy_reload: Arc<tokio::sync::Semaphore>,
|
||||
network_policy_snapshot: Arc<RwLock<Option<Arc<ApplicationPolicySnapshot>>>>,
|
||||
/// Captured before config loading so a reload also revokes pending startups.
|
||||
mcp_ema_cancellation: Arc<Mutex<EmaCancellationRoots>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct EmaCancellationRoots {
|
||||
startup: CancellationToken,
|
||||
lifetime: CancellationToken,
|
||||
}
|
||||
|
||||
/// Startup configuration, including whether loading had to fall back to defaults.
|
||||
pub(crate) struct StartupConfig {
|
||||
pub(crate) config: Config,
|
||||
pub(crate) used_defaults: bool,
|
||||
}
|
||||
|
||||
/// Local auth authority and the cloud-backed configuration loaded with it.
|
||||
pub(crate) struct CloudStartupConfig {
|
||||
pub(crate) bootstrap: Config,
|
||||
pub(crate) config: std::io::Result<Config>,
|
||||
}
|
||||
|
||||
/// Configuration and policy must finish loading against the same account and cloud snapshot.
|
||||
pub(crate) struct ApplicationPolicyLoad {
|
||||
cloud_config: CloudConfigBundleLoader,
|
||||
snapshot: Arc<ApplicationPolicySnapshot>,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct ApplicationPolicySnapshot {
|
||||
revision: codex_http_client::NetworkPolicyRevision,
|
||||
policy: codex_http_client::DestinationPolicy,
|
||||
cloud: Option<codex_config::CloudConfigBundle>,
|
||||
}
|
||||
|
||||
impl ConfigManager {
|
||||
pub(crate) fn new(
|
||||
codex_home: PathBuf,
|
||||
cli_overrides: Vec<(String, TomlValue)>,
|
||||
loader_overrides: LoaderOverrides,
|
||||
strict_config: bool,
|
||||
cloud_config_bundle: CloudConfigBundleLoader,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
thread_config_loader: Arc<dyn ThreadConfigLoader>,
|
||||
) -> Self {
|
||||
let network_policy = codex_http_client::NetworkPolicyController::default();
|
||||
Self {
|
||||
codex_home,
|
||||
cli_overrides: Arc::new(RwLock::new(cli_overrides)),
|
||||
runtime_feature_enablement: Arc::new(RwLock::new(BTreeMap::new())),
|
||||
loader_overrides,
|
||||
strict_config,
|
||||
cloud_config_bundle: Arc::new(RwLock::new(cloud_config_bundle)),
|
||||
arg0_paths,
|
||||
thread_config_loader,
|
||||
network_policy,
|
||||
local_network_policy: Default::default(),
|
||||
network_policy_reload: Arc::new(tokio::sync::Semaphore::new(/*permits*/ 1)),
|
||||
network_policy_snapshot: Arc::default(),
|
||||
mcp_ema_cancellation: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn codex_home(&self) -> &Path {
|
||||
self.codex_home.as_path()
|
||||
}
|
||||
|
||||
/// Explicit account, policy-owner, and enterprise-login changes revoke cached access.
|
||||
pub(crate) fn revoke_mcp_ema(&self) {
|
||||
let mut current = self
|
||||
.mcp_ema_cancellation
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
current.startup.cancel();
|
||||
current.lifetime.cancel();
|
||||
*current = EmaCancellationRoots::default();
|
||||
}
|
||||
|
||||
/// Published threads are validated individually by the existing refresh loop.
|
||||
pub(crate) fn revoke_mcp_ema_startups(&self) {
|
||||
let mut current = self
|
||||
.mcp_ema_cancellation
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
current.startup.cancel();
|
||||
current.startup = CancellationToken::new();
|
||||
}
|
||||
|
||||
fn capture_mcp_ema_cancellation(&self) -> codex_config::McpEmaCancellation {
|
||||
let current = self
|
||||
.mcp_ema_cancellation
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
codex_config::McpEmaCancellation::pending(current.startup.clone(), current.lifetime.clone())
|
||||
}
|
||||
|
||||
pub(crate) fn with_embedded_network_policy(
|
||||
mut self,
|
||||
policy: crate::in_process::EmbeddedNetworkPolicy,
|
||||
) -> Self {
|
||||
self.network_policy = policy.effective;
|
||||
self.local_network_policy = policy.local;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn user_config_path(&self) -> std::io::Result<AbsolutePathBuf> {
|
||||
self.loader_overrides.user_config_path(self.codex_home())
|
||||
}
|
||||
|
||||
pub(crate) fn loader_overrides(&self) -> &LoaderOverrides {
|
||||
&self.loader_overrides
|
||||
}
|
||||
|
||||
pub(crate) fn current_cli_overrides(&self) -> Vec<(String, TomlValue)> {
|
||||
self.cli_overrides
|
||||
.read()
|
||||
.map(|guard| guard.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn current_managed_config_loader(&self) -> CloudConfigBundleLoader {
|
||||
self.cloud_config_bundle
|
||||
.read()
|
||||
.map(|guard| guard.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn extend_runtime_feature_enablement<I>(&self, enablement: I) -> Result<(), ()>
|
||||
where
|
||||
I: IntoIterator<Item = (String, bool)>,
|
||||
{
|
||||
let mut runtime_feature_enablement =
|
||||
self.runtime_feature_enablement.write().map_err(|_| ())?;
|
||||
runtime_feature_enablement.extend(enablement);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn update_managed_config_loader(
|
||||
&self,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
config: &Config,
|
||||
) {
|
||||
// Keep config-server settings and their refresh worker when only
|
||||
// ChatGPT/API-key credentials change.
|
||||
if self
|
||||
.current_managed_config_loader()
|
||||
.config_server()
|
||||
.is_some()
|
||||
{
|
||||
self.revoke_mcp_ema();
|
||||
return;
|
||||
}
|
||||
let loader = managed_config_bundle_loader(
|
||||
auth_manager,
|
||||
config.chatgpt_base_url.clone(),
|
||||
self.codex_home.clone(),
|
||||
config
|
||||
.http_client_factory()
|
||||
.with_network_policy(self.local_network_policy.policy()),
|
||||
config.config_layer_stack.requirements_toml(),
|
||||
);
|
||||
if let Ok(mut guard) = self.cloud_config_bundle.write() {
|
||||
guard.retire_ema_policy();
|
||||
*guard = loader;
|
||||
} else {
|
||||
warn!("failed to update cloud config bundle loader");
|
||||
}
|
||||
self.revoke_mcp_ema();
|
||||
}
|
||||
|
||||
pub(crate) fn clear_chatgpt_config_loader(&self) {
|
||||
if let Ok(mut guard) = self.cloud_config_bundle.write() {
|
||||
if guard.config_server().is_none() {
|
||||
guard.retire_ema_policy();
|
||||
*guard = CloudConfigBundleLoader::default();
|
||||
}
|
||||
} else {
|
||||
warn!("failed to clear cloud config bundle loader");
|
||||
}
|
||||
self.revoke_mcp_ema();
|
||||
}
|
||||
|
||||
pub(crate) async fn sync_default_client_residency_requirement(&self) {
|
||||
match self.load_latest_config(/*fallback_cwd*/ None).await {
|
||||
Ok(config) => {
|
||||
set_default_client_residency_requirement(config.enforce_residency.value());
|
||||
}
|
||||
Err(err) => warn!(
|
||||
error = %err,
|
||||
"failed to sync default client residency requirement after auth refresh"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn load_latest_config(
|
||||
&self,
|
||||
fallback_cwd: Option<PathBuf>,
|
||||
) -> std::io::Result<Config> {
|
||||
let Some(fallback_cwd) = fallback_cwd else {
|
||||
return self.load_non_project_config().await;
|
||||
};
|
||||
self.load_with_cli_overrides(
|
||||
&self.current_cli_overrides(),
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides::default(),
|
||||
Some(fallback_cwd),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Loads system, user, and runtime settings without discovering a project
|
||||
/// from the app-server process's working directory.
|
||||
pub(crate) async fn load_non_project_config(&self) -> std::io::Result<Config> {
|
||||
let mcp_ema_cancellation = self.capture_mcp_ema_cancellation();
|
||||
let policy_load = self.refresh_application_network_policy().await?;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(self.codex_home.clone())
|
||||
.cli_overrides(self.current_cli_overrides())
|
||||
.loader_overrides(self.loader_overrides.clone())
|
||||
.strict_config(self.strict_config)
|
||||
.fallback_cwd(Some(self.codex_home.clone()))
|
||||
.cloud_config_bundle(policy_load.cloud_config.clone())
|
||||
.thread_config_loader(Arc::clone(&self.thread_config_loader))
|
||||
.without_project_context()
|
||||
.build()
|
||||
.await?;
|
||||
self.check_application_policy_load(&policy_load)?;
|
||||
self.apply_network_policy(&mut config);
|
||||
self.apply_runtime_feature_enablement(&mut config);
|
||||
self.apply_arg0_paths(&mut config);
|
||||
config.config_layer_stack = config
|
||||
.config_layer_stack
|
||||
.with_mcp_ema_cancellation(mcp_ema_cancellation);
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub(crate) async fn load_latest_config_with_session_layers(
|
||||
&self,
|
||||
session_layers: &ConfigLayerStack,
|
||||
cwd: &Path,
|
||||
) -> std::io::Result<Config> {
|
||||
let mcp_ema_cancellation = self.capture_mcp_ema_cancellation();
|
||||
let codex_home = AbsolutePathBuf::from_absolute_path(&self.codex_home)?;
|
||||
let layers = self
|
||||
.load_config_layers_for_cwd(AbsolutePathBuf::from_absolute_path(cwd)?)
|
||||
.await?;
|
||||
let mut config = Config::rebuild_with_session_layers(
|
||||
session_layers,
|
||||
cwd.to_path_buf(),
|
||||
&layers,
|
||||
codex_home,
|
||||
)
|
||||
.await?;
|
||||
self.apply_network_policy(&mut config);
|
||||
self.apply_runtime_feature_enablement(&mut config);
|
||||
self.apply_arg0_paths(&mut config);
|
||||
config.config_layer_stack = config
|
||||
.config_layer_stack
|
||||
.with_mcp_ema_cancellation(mcp_ema_cancellation);
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Refreshes global settings and managed requirements using already fetched session layers.
|
||||
pub(crate) async fn load_retained_session_config(
|
||||
&self,
|
||||
session_layers: &ConfigLayerStack,
|
||||
cwd: &Path,
|
||||
) -> std::io::Result<Config> {
|
||||
let mcp_ema_cancellation = self.capture_mcp_ema_cancellation();
|
||||
let mut manager = self.clone();
|
||||
manager.thread_config_loader = Arc::new(codex_config::NoopThreadConfigLoader);
|
||||
let refreshed_layers = manager
|
||||
.load_config_layers_for_cwd(AbsolutePathBuf::from_absolute_path(cwd)?)
|
||||
.await?;
|
||||
// Merge the retained provider definitions before resolving managed provider selection.
|
||||
let mut config = Config::rebuild_with_session_layers(
|
||||
session_layers,
|
||||
cwd.to_path_buf(),
|
||||
&refreshed_layers,
|
||||
AbsolutePathBuf::from_absolute_path(&self.codex_home)?,
|
||||
)
|
||||
.await?;
|
||||
self.apply_network_policy(&mut config);
|
||||
self.apply_runtime_feature_enablement(&mut config);
|
||||
self.apply_arg0_paths(&mut config);
|
||||
config.config_layer_stack = config
|
||||
.config_layer_stack
|
||||
.with_mcp_ema_cancellation(mcp_ema_cancellation);
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Checks the retained session route against current managed provider requirements.
|
||||
pub(crate) async fn check_thread_model_provider(
|
||||
&self,
|
||||
current: &Config,
|
||||
) -> std::io::Result<()> {
|
||||
let policy_load = self.refresh_application_network_policy().await?;
|
||||
// Existing threads retain their session route; only managed
|
||||
// requirements can invalidate it.
|
||||
let requirements = load_managed_requirements_state(
|
||||
LOCAL_FS.as_ref(),
|
||||
&self.codex_home,
|
||||
codex_config::ConfigLoadOptions {
|
||||
loader_overrides: self.loader_overrides.clone(),
|
||||
strict_config: self.strict_config,
|
||||
cloud_config_bundle: policy_load.cloud_config.clone(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
self.check_application_policy_load(&policy_load)?;
|
||||
let selection_changed = requirements
|
||||
.model_provider
|
||||
.as_ref()
|
||||
.is_some_and(|provider_id| provider_id != ¤t.model_provider_id);
|
||||
let required_provider = requirements
|
||||
.model_providers
|
||||
.as_ref()
|
||||
.and_then(|providers| providers.get(¤t.model_provider_id))
|
||||
.cloned();
|
||||
let required_provider = match required_provider {
|
||||
Some(provider)
|
||||
if matches!(
|
||||
current.model_provider_id.as_str(),
|
||||
AMAZON_BEDROCK_PROVIDER_ID
|
||||
| AMAZON_BEDROCK_RUNTIME_PROVIDER_ID
|
||||
| GCP_PROVIDER_ID
|
||||
| OPENAI_PROVIDER_ID
|
||||
) =>
|
||||
{
|
||||
// Managed overrides must receive the same built-in defaults as startup config.
|
||||
// OpenAI's inference URL belongs to the retained session, not the catalog override.
|
||||
let mut provider = merge_configured_model_providers(
|
||||
built_in_model_providers(current.model_provider.base_url.clone()),
|
||||
HashMap::from([(current.model_provider_id.clone(), provider)]),
|
||||
)
|
||||
.map_err(|message| std::io::Error::new(std::io::ErrorKind::InvalidData, message))?
|
||||
.remove(¤t.model_provider_id);
|
||||
if current.model_provider_id == GCP_PROVIDER_ID
|
||||
&& let Some(provider) = provider.as_mut()
|
||||
{
|
||||
apply_default_gcp_auth(provider, ¤t.cwd);
|
||||
}
|
||||
provider
|
||||
}
|
||||
Some(provider) => Some(provider),
|
||||
None => None,
|
||||
};
|
||||
let definition_changed = required_provider
|
||||
.as_ref()
|
||||
.is_some_and(|provider| provider != ¤t.model_provider);
|
||||
if selection_changed || definition_changed {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
ModelProviderError::ModelProviderPolicyConflict {
|
||||
model_provider: current.model_provider_id.clone(),
|
||||
required_model_provider: requirements
|
||||
.model_provider
|
||||
.unwrap_or_else(|| current.model_provider_id.clone()),
|
||||
},
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Load local policy before auth, then fetch the account's cloud configuration.
|
||||
/// Callers choose their error/recovery policy before initializing any runtimes.
|
||||
pub(crate) async fn load_managed_startup_config(
|
||||
&self,
|
||||
cwd: Option<PathBuf>,
|
||||
) -> std::io::Result<CloudStartupConfig> {
|
||||
let bootstrap = self.load_startup_config(cwd.clone()).await?.config;
|
||||
let auth =
|
||||
AuthManager::shared_from_config(&bootstrap, /*enable_codex_api_key_env*/ false)
|
||||
.await
|
||||
.map_err(std::io::Error::other)?;
|
||||
self.update_managed_config_loader(auth, &bootstrap);
|
||||
let config = self.load_latest_config(cwd).await;
|
||||
Ok(CloudStartupConfig { bootstrap, config })
|
||||
}
|
||||
|
||||
/// Installs local policy before cloud access; failed policy loads block traffic while
|
||||
/// non-strict startup remains available for configuration repair.
|
||||
pub(crate) async fn load_startup_config(
|
||||
&self,
|
||||
fallback_cwd: Option<PathBuf>,
|
||||
) -> std::io::Result<StartupConfig> {
|
||||
match self.load_latest_config(fallback_cwd).await {
|
||||
Ok(config) => Ok(StartupConfig {
|
||||
config,
|
||||
used_defaults: false,
|
||||
}),
|
||||
Err(error)
|
||||
if self.strict_config
|
||||
|| crate::is_unsupported_untrusted_approval_policy_error(&error) =>
|
||||
{
|
||||
Err(error)
|
||||
}
|
||||
Err(error) => {
|
||||
warn!(%error, "configuration is unavailable; using default settings");
|
||||
Ok(StartupConfig {
|
||||
config: self.load_default_config().await?,
|
||||
used_defaults: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn load_default_config(&self) -> std::io::Result<Config> {
|
||||
let mcp_ema_cancellation = self.capture_mcp_ema_cancellation();
|
||||
let mut loader_overrides = self.loader_overrides.clone();
|
||||
loader_overrides.ignore_user_config = true;
|
||||
loader_overrides.ignore_project_config = true;
|
||||
loader_overrides.ignore_managed_requirements |=
|
||||
self.refresh_local_network_policy().await.is_err();
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(self.codex_home.clone())
|
||||
.cli_overrides(self.current_cli_overrides())
|
||||
.loader_overrides(loader_overrides)
|
||||
.fallback_cwd(Some(self.codex_home.clone()))
|
||||
.cloud_config_bundle(CloudConfigBundleLoader::default())
|
||||
.build()
|
||||
.await?;
|
||||
self.apply_network_policy(&mut config);
|
||||
self.apply_runtime_feature_enablement(&mut config);
|
||||
self.apply_arg0_paths(&mut config);
|
||||
config.config_layer_stack = config
|
||||
.config_layer_stack
|
||||
.with_mcp_ema_cancellation(mcp_ema_cancellation);
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub(crate) async fn load_with_overrides(
|
||||
&self,
|
||||
request_overrides: Option<HashMap<String, serde_json::Value>>,
|
||||
typesafe_overrides: ConfigOverrides,
|
||||
) -> std::io::Result<Config> {
|
||||
self.load_with_cli_overrides(
|
||||
&self.current_cli_overrides(),
|
||||
request_overrides,
|
||||
typesafe_overrides,
|
||||
/*fallback_cwd*/ None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn load_for_cwd(
|
||||
&self,
|
||||
request_overrides: Option<HashMap<String, serde_json::Value>>,
|
||||
typesafe_overrides: ConfigOverrides,
|
||||
cwd: Option<PathBuf>,
|
||||
) -> std::io::Result<Config> {
|
||||
self.load_with_cli_overrides(
|
||||
&self.current_cli_overrides(),
|
||||
request_overrides,
|
||||
typesafe_overrides,
|
||||
cwd,
|
||||
)
|
||||
.await
|
||||
.and_then(|config| {
|
||||
config.validate_windows_mxc_requirement()?;
|
||||
Ok(config)
|
||||
})
|
||||
}
|
||||
|
||||
/// Validates saved and requested providers before resume overrides or policy can replace them.
|
||||
pub(crate) async fn load_for_resume(
|
||||
&self,
|
||||
saved_provider: Option<&str>,
|
||||
request_overrides: Option<HashMap<String, serde_json::Value>>,
|
||||
mut typesafe_overrides: ConfigOverrides,
|
||||
cwd: Option<PathBuf>,
|
||||
) -> std::io::Result<Config> {
|
||||
let requested_provider = typesafe_overrides.model_provider.clone().or_else(|| {
|
||||
request_overrides
|
||||
.as_ref()
|
||||
.and_then(|values| values.get("model_provider"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::to_owned)
|
||||
});
|
||||
if let Some(saved) = saved_provider {
|
||||
typesafe_overrides.model_provider = Some(saved.to_owned());
|
||||
}
|
||||
self.load_with_validation(
|
||||
&self.current_cli_overrides(),
|
||||
request_overrides,
|
||||
typesafe_overrides,
|
||||
cwd,
|
||||
|config, _overrides, layers| {
|
||||
let requested_provider = requested_provider
|
||||
.as_deref()
|
||||
.or(saved_provider)
|
||||
.or(config.model_provider.as_deref())
|
||||
.unwrap_or("openai");
|
||||
// Validate the saved route even when a client sends a provider override.
|
||||
for provider in [
|
||||
saved_provider.unwrap_or(requested_provider),
|
||||
requested_provider,
|
||||
] {
|
||||
if let Some(required) = layers.required_model_provider()
|
||||
&& required != provider
|
||||
{
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
ModelProviderError::ModelProviderPolicyConflict {
|
||||
model_provider: provider.to_owned(),
|
||||
required_model_provider: required.to_owned(),
|
||||
},
|
||||
));
|
||||
}
|
||||
if !config.model_providers.contains_key(provider)
|
||||
&& !built_in_model_providers(config.openai_base_url.clone())
|
||||
.contains_key(provider)
|
||||
{
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
ModelProviderError::ModelProviderNotConfigured {
|
||||
model_provider: provider.to_owned(),
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(saved) = saved_provider
|
||||
&& saved != requested_provider
|
||||
{
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
format!("Cannot change this thread's model provider from `{saved}` to `{requested_provider}` on resume."),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.await
|
||||
.and_then(|config| {
|
||||
config.validate_windows_mxc_requirement()?;
|
||||
Ok(config)
|
||||
})
|
||||
}
|
||||
|
||||
/// Reload sources using the task's session flags before materializing config.
|
||||
pub(crate) async fn load_permission_config_for_thread(
|
||||
&self,
|
||||
thread_config: &Config,
|
||||
cwd: AbsolutePathBuf,
|
||||
permission_profile: String,
|
||||
) -> std::io::Result<Config> {
|
||||
let mut session_flags = TomlValue::Table(Default::default());
|
||||
for layer in thread_config.config_layer_stack.layers_low_to_high() {
|
||||
if matches!(layer.name, codex_config::ConfigLayerSource::SessionFlags) {
|
||||
codex_config::merge_toml_values(&mut session_flags, &layer.config);
|
||||
}
|
||||
}
|
||||
let overrides = session_flags
|
||||
.as_table()
|
||||
.ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"session flags must be a table",
|
||||
)
|
||||
})?
|
||||
.iter()
|
||||
.map(|(key, value)| (key.clone(), value.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
self.load_with_cli_overrides(
|
||||
&overrides,
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides {
|
||||
cwd: Some(cwd.to_path_buf()),
|
||||
default_permissions: Some(permission_profile),
|
||||
codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
Some(cwd.to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.and_then(|config| {
|
||||
config.validate_windows_mxc_requirement()?;
|
||||
Ok(config)
|
||||
})
|
||||
}
|
||||
|
||||
#[instrument(level = "trace", skip_all)]
|
||||
pub(crate) async fn load_with_cli_overrides(
|
||||
&self,
|
||||
cli_overrides: &[(String, TomlValue)],
|
||||
request_overrides: Option<HashMap<String, serde_json::Value>>,
|
||||
typesafe_overrides: ConfigOverrides,
|
||||
fallback_cwd: Option<PathBuf>,
|
||||
) -> std::io::Result<Config> {
|
||||
self.load_with_validation(
|
||||
cli_overrides,
|
||||
request_overrides,
|
||||
typesafe_overrides,
|
||||
fallback_cwd,
|
||||
|_, _, _| Ok(()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn load_with_validation(
|
||||
&self,
|
||||
cli_overrides: &[(String, TomlValue)],
|
||||
request_overrides: Option<HashMap<String, serde_json::Value>>,
|
||||
mut typesafe_overrides: ConfigOverrides,
|
||||
fallback_cwd: Option<PathBuf>,
|
||||
validate: impl FnOnce(
|
||||
&codex_config::config_toml::ConfigToml,
|
||||
&ConfigOverrides,
|
||||
&ConfigLayerStack,
|
||||
) -> std::io::Result<()>,
|
||||
) -> std::io::Result<Config> {
|
||||
let mcp_ema_cancellation = self.capture_mcp_ema_cancellation();
|
||||
let policy_load = self.refresh_application_network_policy().await?;
|
||||
let mut request_overrides = request_overrides.unwrap_or_default();
|
||||
if let Some(value) = request_overrides.remove("bypass_hook_trust") {
|
||||
typesafe_overrides.bypass_hook_trust = Some(value.as_bool().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"`bypass_hook_trust` override must be a boolean",
|
||||
)
|
||||
})?);
|
||||
}
|
||||
let merged_cli_overrides = cli_overrides
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(
|
||||
request_overrides
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key, json_to_toml(value))),
|
||||
)
|
||||
.collect::<Vec<_>>();
|
||||
let result = codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(self.codex_home.clone())
|
||||
.cli_overrides(merged_cli_overrides)
|
||||
.loader_overrides(self.loader_overrides.clone())
|
||||
.strict_config(self.strict_config)
|
||||
.harness_overrides(typesafe_overrides)
|
||||
.fallback_cwd(fallback_cwd)
|
||||
.cloud_config_bundle(policy_load.cloud_config.clone())
|
||||
.thread_config_loader(Arc::clone(&self.thread_config_loader))
|
||||
.build_with_validation(validate)
|
||||
.await;
|
||||
let mut config = result?;
|
||||
self.check_application_policy_load(&policy_load)?;
|
||||
self.apply_network_policy(&mut config);
|
||||
self.apply_runtime_feature_enablement(&mut config);
|
||||
self.apply_arg0_paths(&mut config);
|
||||
config.config_layer_stack = config
|
||||
.config_layer_stack
|
||||
.with_mcp_ema_cancellation(mcp_ema_cancellation);
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub(crate) async fn load_config_layers_for_cwd(
|
||||
&self,
|
||||
cwd: AbsolutePathBuf,
|
||||
) -> std::io::Result<ConfigLayerStack> {
|
||||
self.load_config_layers(Some(cwd)).await
|
||||
}
|
||||
|
||||
pub(crate) async fn load_config_layers(
|
||||
&self,
|
||||
cwd: Option<AbsolutePathBuf>,
|
||||
) -> std::io::Result<ConfigLayerStack> {
|
||||
let policy_load = self.refresh_application_network_policy().await?;
|
||||
let result = load_config_layers_state(
|
||||
LOCAL_FS.as_ref(),
|
||||
&self.codex_home,
|
||||
cwd,
|
||||
&self.current_cli_overrides(),
|
||||
codex_config::ConfigLoadOptions {
|
||||
loader_overrides: self.loader_overrides().clone(),
|
||||
strict_config: self.strict_config,
|
||||
cloud_config_bundle: policy_load.cloud_config.clone(),
|
||||
},
|
||||
self.thread_config_loader.as_ref(),
|
||||
)
|
||||
.await;
|
||||
let layers = result?;
|
||||
self.check_application_policy_load(&policy_load)?;
|
||||
Ok(layers)
|
||||
}
|
||||
|
||||
fn apply_runtime_feature_enablement(&self, config: &mut Config) {
|
||||
apply_runtime_feature_enablement(config, &self.current_runtime_feature_enablement());
|
||||
}
|
||||
|
||||
fn current_runtime_feature_enablement(&self) -> BTreeMap<String, bool> {
|
||||
self.runtime_feature_enablement
|
||||
.read()
|
||||
.map(|guard| guard.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn apply_network_policy(&self, config: &mut Config) {
|
||||
config.application_network_policy = self.network_policy.policy();
|
||||
config.application_auth_route_config = Some(
|
||||
codex_login::AuthRouteConfig::from_http_client_factory(
|
||||
config
|
||||
.http_client_factory()
|
||||
.with_network_policy(self.network_policy.policy()),
|
||||
)
|
||||
.with_local_bootstrap_factory(
|
||||
config
|
||||
.http_client_factory()
|
||||
.with_network_policy(self.local_network_policy.policy()),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
fn apply_arg0_paths(&self, config: &mut Config) {
|
||||
config.codex_self_exe = self.arg0_paths.codex_self_exe.clone();
|
||||
config.codex_linux_sandbox_exe = self.arg0_paths.codex_linux_sandbox_exe.clone();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new_for_tests(
|
||||
codex_home: PathBuf,
|
||||
cli_overrides: Vec<(String, TomlValue)>,
|
||||
loader_overrides: LoaderOverrides,
|
||||
cloud_config_bundle: CloudConfigBundleLoader,
|
||||
) -> Self {
|
||||
Self::new(
|
||||
codex_home,
|
||||
cli_overrides,
|
||||
loader_overrides,
|
||||
/*strict_config*/ false,
|
||||
cloud_config_bundle,
|
||||
Arg0DispatchPaths::default(),
|
||||
Arc::new(codex_config::NoopThreadConfigLoader),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn without_managed_config_for_tests(codex_home: PathBuf) -> Self {
|
||||
Self::new_for_tests(
|
||||
codex_home,
|
||||
Vec::new(),
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
CloudConfigBundleLoader::default(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "application_network_tests.rs"]
|
||||
mod application_network_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "config_manager_provider_tests.rs"]
|
||||
mod provider_tests;
|
||||
|
||||
pub(crate) fn protected_feature_keys(config_layer_stack: &ConfigLayerStack) -> BTreeSet<String> {
|
||||
let mut protected_features = config_layer_stack
|
||||
.effective_config()
|
||||
.get("features")
|
||||
.and_then(toml::Value::as_table)
|
||||
.map(|features| features.keys().cloned().collect::<BTreeSet<_>>())
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Some(feature_requirements) = config_layer_stack
|
||||
.requirements_toml()
|
||||
.feature_requirements
|
||||
.as_ref()
|
||||
{
|
||||
protected_features.extend(feature_requirements.entries.keys().cloned());
|
||||
}
|
||||
|
||||
protected_features
|
||||
}
|
||||
|
||||
pub(crate) fn apply_runtime_feature_enablement(
|
||||
config: &mut Config,
|
||||
runtime_feature_enablement: &BTreeMap<String, bool>,
|
||||
) {
|
||||
config.runtime_feature_defaults = runtime_feature_enablement
|
||||
.iter()
|
||||
.filter_map(|(name, enabled)| feature_for_key(name).map(|feature| (feature, *enabled)))
|
||||
.collect();
|
||||
let protected_features = protected_feature_keys(&config.config_layer_stack);
|
||||
for (name, enabled) in runtime_feature_enablement {
|
||||
if protected_features.contains(name) {
|
||||
continue;
|
||||
}
|
||||
let Some(feature) = feature_for_key(name) else {
|
||||
continue;
|
||||
};
|
||||
if let Err(err) = config.features.set_enabled(feature, *enabled) {
|
||||
warn!(
|
||||
feature = name,
|
||||
error = %err,
|
||||
"failed to apply runtime feature enablement"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
263
codex-rs/app-server/src/config_manager_provider_tests.rs
Normal file
263
codex-rs/app-server/src/config_manager_provider_tests.rs
Normal file
@@ -0,0 +1,263 @@
|
||||
//! Checks retained providers against managed policy and the current provider selection.
|
||||
|
||||
use super::*;
|
||||
use anyhow::Result;
|
||||
use codex_config::CloudConfigBundleLoadError;
|
||||
use codex_config::CloudConfigBundleLoadErrorCode;
|
||||
use codex_config::ThreadConfigContext;
|
||||
use codex_config::ThreadConfigLoadError;
|
||||
use codex_config::ThreadConfigLoadErrorCode;
|
||||
use codex_config::ThreadConfigLoaderFuture;
|
||||
use codex_config::ThreadConfigSource;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
use test_case::test_case;
|
||||
|
||||
#[test_case(AMAZON_BEDROCK_PROVIDER_ID, "aws.region = 'us-west-2'", "us-west-2", "us-east-1", None; "bedrock")]
|
||||
#[test_case(AMAZON_BEDROCK_RUNTIME_PROVIDER_ID, "aws.region = 'us-west-2'", "us-west-2", "us-east-1", None; "bedrock_runtime")]
|
||||
#[test_case(GCP_PROVIDER_ID, "project_id = 'example-project'\nlocation = 'us-central1'", "example-project", "other-project", None; "gcp_project")]
|
||||
#[test_case(GCP_PROVIDER_ID, "project_id = 'example-project'\nlocation = 'us-central1'", "us-central1", "us-east4", None; "gcp_location")]
|
||||
#[test_case(GCP_PROVIDER_ID, "project_id = 'example-project'\nauth.command = 'print-token'", "print-token", "other-token", None; "gcp_auth")]
|
||||
#[test_case("openai", "model_catalog_url = 'https://chatgpt.com/backend-api/codex/models'", "https://chatgpt.com/backend-api/codex/models", "https://chatgpt.com/backend-api/codex/other-models", None; "openai_catalog")]
|
||||
#[test_case("openai", "model_catalog_url = 'https://chatgpt.com/backend-api/codex/models'", "https://chatgpt.com/backend-api/codex/models", "https://chatgpt.com/backend-api/codex/other-models", Some("https://us.api.openai.com/v1"); "openai_regional_catalog")]
|
||||
#[tokio::test]
|
||||
async fn provider_requirements_resolve_builtin_overrides(
|
||||
provider_id: &str,
|
||||
provider_config: &str,
|
||||
original: &str,
|
||||
replacement: &str,
|
||||
openai_base_url: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let home = tempdir()?;
|
||||
let workspace = tempdir()?;
|
||||
if let Some(base_url) = openai_base_url {
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!("openai_base_url = '{base_url}'"),
|
||||
)?;
|
||||
}
|
||||
let requirements = format!(
|
||||
"model_provider = '{provider_id}'\n[model_providers.{provider_id}]\n{provider_config}"
|
||||
);
|
||||
let manager = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement(&requirements),
|
||||
);
|
||||
let current = manager
|
||||
.load_latest_config(Some(workspace.path().to_path_buf()))
|
||||
.await?;
|
||||
if provider_id == "openai" {
|
||||
assert_eq!(current.model_provider.base_url.as_deref(), openai_base_url);
|
||||
// Retained threads keep their inference route even if user defaults later change.
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"openai_base_url = 'https://eu.api.openai.com/v1'",
|
||||
)?;
|
||||
}
|
||||
manager.check_thread_model_provider(¤t).await?;
|
||||
|
||||
let changed = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement(
|
||||
requirements.replace(original, replacement),
|
||||
),
|
||||
);
|
||||
assert_eq!(
|
||||
changed
|
||||
.check_thread_model_provider(¤t)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct UnavailableThreadConfig;
|
||||
|
||||
impl ThreadConfigLoader for UnavailableThreadConfig {
|
||||
fn load(
|
||||
&self,
|
||||
_context: ThreadConfigContext,
|
||||
) -> ThreadConfigLoaderFuture<'_, Vec<ThreadConfigSource>> {
|
||||
Box::pin(async {
|
||||
Err(ThreadConfigLoadError::new(
|
||||
ThreadConfigLoadErrorCode::RequestFailed,
|
||||
/*status_code*/ None,
|
||||
"thread config service unavailable",
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_requirements_do_not_reload_thread_config() -> Result<()> {
|
||||
let home = tempdir()?;
|
||||
let mut manager = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf());
|
||||
manager.thread_config_loader = Arc::new(codex_config::StaticThreadConfigLoader::new(vec![
|
||||
ThreadConfigSource::Session(codex_config::SessionThreadConfig {
|
||||
model_provider: Some("retained".into()),
|
||||
model_providers: toml::from_str("[retained]\nname = 'Retained'")?,
|
||||
..Default::default()
|
||||
}),
|
||||
]));
|
||||
let current = manager.load_latest_config(/*fallback_cwd*/ None).await?;
|
||||
manager.thread_config_loader = Arc::new(UnavailableThreadConfig);
|
||||
assert!(
|
||||
manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
manager.check_thread_model_provider(¤t).await?;
|
||||
manager.cloud_config_bundle = Arc::new(RwLock::new(
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement("model_provider = 'retained'"),
|
||||
));
|
||||
let retained = manager
|
||||
.load_retained_session_config(¤t.config_layer_stack, ¤t.cwd)
|
||||
.await?;
|
||||
assert_eq!(retained.model_provider, current.model_provider);
|
||||
let factory = current.http_client_factory();
|
||||
assert_eq!(retained.http_client_factory(), factory);
|
||||
|
||||
manager.cloud_config_bundle = Arc::new(RwLock::new(
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement("model_provider = 'other'"),
|
||||
));
|
||||
assert_eq!(
|
||||
manager
|
||||
.check_thread_model_provider(¤t)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_requirements_ignore_system_defaults_but_reject_requirement_changes() -> Result<()>
|
||||
{
|
||||
let home = tempdir()?;
|
||||
let system_config_path = home.path().join("system-config.toml");
|
||||
let requirements_path = home.path().join("requirements.toml");
|
||||
let managed_config_path = home.path().join("managed-config.toml");
|
||||
let mut overrides = LoaderOverrides::without_managed_config_for_tests();
|
||||
overrides.system_config_path = Some(system_config_path.clone());
|
||||
overrides.system_requirements_path = Some(requirements_path.clone());
|
||||
overrides.managed_config_path = Some(managed_config_path.clone());
|
||||
let manager = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
overrides,
|
||||
CloudConfigBundleLoader::default(),
|
||||
);
|
||||
let current = manager.load_latest_config(/*fallback_cwd*/ None).await?;
|
||||
|
||||
std::fs::write(&system_config_path, "invalid toml !!!")?;
|
||||
manager.check_thread_model_provider(¤t).await?;
|
||||
|
||||
std::fs::write(&requirements_path, "model_provider = 'other'")?;
|
||||
assert_eq!(
|
||||
manager
|
||||
.check_thread_model_provider(¤t)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
);
|
||||
|
||||
std::fs::write(&requirements_path, "invalid toml !!!")?;
|
||||
assert_eq!(
|
||||
manager
|
||||
.check_thread_model_provider(¤t)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
std::io::ErrorKind::InvalidData,
|
||||
);
|
||||
|
||||
std::fs::write(
|
||||
&requirements_path,
|
||||
"[model_providers.gateway]\nbase_url = 'https://example.test'",
|
||||
)?;
|
||||
assert_eq!(
|
||||
manager
|
||||
.check_thread_model_provider(¤t)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
std::io::ErrorKind::InvalidData,
|
||||
);
|
||||
std::fs::remove_file(requirements_path)?;
|
||||
|
||||
std::fs::write(managed_config_path, "invalid toml !!!")?;
|
||||
assert_eq!(
|
||||
manager
|
||||
.check_thread_model_provider(¤t)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
std::io::ErrorKind::InvalidData,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_requirement_load_errors_reject_input() -> Result<()> {
|
||||
let home = tempdir()?;
|
||||
let previous = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf())
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await?;
|
||||
for loader in [
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement("invalid toml !!!"),
|
||||
CloudConfigBundleLoader::new(async {
|
||||
Err(CloudConfigBundleLoadError::new(
|
||||
CloudConfigBundleLoadErrorCode::RequestFailed,
|
||||
/*status_code*/ None,
|
||||
"policy unavailable",
|
||||
))
|
||||
}),
|
||||
] {
|
||||
let manager = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
loader,
|
||||
);
|
||||
assert!(
|
||||
manager
|
||||
.check_thread_model_provider(&previous)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A managed startup selection must disappear when its policy is removed.
|
||||
#[tokio::test]
|
||||
async fn catalog_reload_uses_latest_model_provider() -> Result<()> {
|
||||
let home = tempdir()?;
|
||||
let manager = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement(
|
||||
"model_provider = 'gateway'\n[model_providers.gateway]\nname = 'Gateway'\nbase_url = 'https://example.test'",
|
||||
),
|
||||
);
|
||||
let startup = manager.load_non_project_config().await?;
|
||||
assert_eq!(startup.model_provider_id, "gateway");
|
||||
manager.clear_chatgpt_config_loader();
|
||||
let refreshed = manager
|
||||
.load_startup_config(/*fallback_cwd*/ None)
|
||||
.await?
|
||||
.config;
|
||||
assert_eq!(refreshed.model_provider_id, "openai");
|
||||
Ok(())
|
||||
}
|
||||
1063
codex-rs/app-server/src/config_manager_service.rs
Normal file
1063
codex-rs/app-server/src/config_manager_service.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,295 @@
|
||||
//! Prepare config edits and preserve provider definitions across source remapping in a write batch.
|
||||
//! Explicit replacements and deletions remain ordered; only automatic sibling eviction is
|
||||
//! ignored when retaining definitions for a later source upsert.
|
||||
|
||||
use super::ConfigManagerError;
|
||||
use super::MergeError;
|
||||
use super::apply_merge;
|
||||
use super::shell_environment_policy_representation_switch;
|
||||
use super::sparse_overlay;
|
||||
use super::toml_value_to_item;
|
||||
use super::value_at_path;
|
||||
use codex_app_server_protocol::ConfigWriteErrorCode;
|
||||
use codex_app_server_protocol::MergeStrategy;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::merge_toml_values;
|
||||
use codex_core::config::edit::ConfigEdit;
|
||||
use codex_network_proxy::CredentialProviderConfig;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
const PROVIDERS_PATH: [&str; 3] = ["features", "network_proxy", "credentials"];
|
||||
|
||||
pub(super) struct CredentialProviderEdits {
|
||||
definitions: TomlValue,
|
||||
displaced_provider_ids: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl CredentialProviderEdits {
|
||||
pub(super) fn new(config: &TomlValue) -> Self {
|
||||
Self {
|
||||
definitions: providers(config)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| TomlValue::Table(Default::default())),
|
||||
displaced_provider_ids: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn apply(
|
||||
&mut self,
|
||||
config: &mut TomlValue,
|
||||
segments: &[String],
|
||||
value: Option<&TomlValue>,
|
||||
strategy: MergeStrategy,
|
||||
) -> Result<Option<ConfigEdit>, ConfigManagerError> {
|
||||
let persist_segments = if matches!(strategy, MergeStrategy::Upsert)
|
||||
&& value.is_some_and(|value| {
|
||||
shell_environment_policy_representation_switch(config, segments, value)
|
||||
}) {
|
||||
vec!["shell_environment_policy".to_string()]
|
||||
} else {
|
||||
segments.to_vec()
|
||||
};
|
||||
let original_value = value_at_path(config, &persist_segments).cloned();
|
||||
self.apply_provider_merge(config, segments, value, strategy)
|
||||
.map_err(|err| match err {
|
||||
MergeError::Validation(message) => {
|
||||
ConfigManagerError::write(ConfigWriteErrorCode::ConfigValidationError, message)
|
||||
}
|
||||
})?;
|
||||
if original_value.as_ref() == value_at_path(config, &persist_segments) {
|
||||
Ok(None)
|
||||
} else {
|
||||
config_edit_at_path(config, persist_segments).map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn remapping_edits(
|
||||
&self,
|
||||
config: &TomlValue,
|
||||
) -> Result<Vec<ConfigEdit>, ConfigManagerError> {
|
||||
// Use final definitions so later explicit edits and restored providers retain batch order.
|
||||
self.displaced_provider_ids
|
||||
.iter()
|
||||
.map(|id| {
|
||||
let mut segments = PROVIDERS_PATH.map(str::to_string).to_vec();
|
||||
segments.push(id.clone());
|
||||
config_edit_at_path(config, segments)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn apply_provider_merge(
|
||||
&mut self,
|
||||
config: &mut TomlValue,
|
||||
segments: &[String],
|
||||
value: Option<&TomlValue>,
|
||||
strategy: MergeStrategy,
|
||||
) -> Result<(), MergeError> {
|
||||
if !segments
|
||||
.iter()
|
||||
.zip(PROVIDERS_PATH)
|
||||
.all(|(segment, expected)| segment == expected)
|
||||
{
|
||||
return apply_merge(config, segments, value, strategy).map(|_| ());
|
||||
}
|
||||
|
||||
let previous_ids = providers(config)
|
||||
.and_then(TomlValue::as_table)
|
||||
.filter(|_| matches!(strategy, MergeStrategy::Upsert) && value.is_some())
|
||||
.into_iter()
|
||||
.flat_map(|table| table.keys().cloned())
|
||||
.collect::<BTreeSet<_>>();
|
||||
let mut overlay = value.map(|value| sparse_overlay(segments, value));
|
||||
let restored_ids = overlay
|
||||
.as_ref()
|
||||
.and_then(providers)
|
||||
.and_then(TomlValue::as_table)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|(id, update)| {
|
||||
matches!(strategy, MergeStrategy::Upsert)
|
||||
&& update.get("env").is_some()
|
||||
&& self.definitions.get(id.as_str()).is_some()
|
||||
&& self.definitions.get(id.as_str())
|
||||
!= providers(config).and_then(|current| current.get(id.as_str()))
|
||||
})
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if segments.len() > PROVIDERS_PATH.len() {
|
||||
apply_merge(
|
||||
&mut self.definitions,
|
||||
&segments[PROVIDERS_PATH.len()..],
|
||||
value,
|
||||
strategy.clone(),
|
||||
)?;
|
||||
} else {
|
||||
let update = value.and_then(|value| {
|
||||
PROVIDERS_PATH[segments.len()..]
|
||||
.iter()
|
||||
.try_fold(value, |value, key| value.get(*key))
|
||||
});
|
||||
if let Some(update) = update {
|
||||
if matches!(strategy, MergeStrategy::Upsert) {
|
||||
merge_toml_values(&mut self.definitions, update);
|
||||
} else {
|
||||
self.definitions = update.clone();
|
||||
}
|
||||
} else if value.is_none()
|
||||
|| matches!(strategy, MergeStrategy::Replace)
|
||||
&& !value.is_some_and(TomlValue::is_bool)
|
||||
{
|
||||
self.definitions = TomlValue::Table(Default::default());
|
||||
}
|
||||
}
|
||||
|
||||
if !restored_ids.is_empty()
|
||||
&& let Some(overlay) = overlay.as_mut()
|
||||
&& let Some(updates) = overlay
|
||||
.get_mut("features")
|
||||
.and_then(|features| features.get_mut("network_proxy"))
|
||||
.and_then(|proxy| proxy.get_mut("credentials"))
|
||||
.and_then(TomlValue::as_table_mut)
|
||||
{
|
||||
for id in restored_ids {
|
||||
if let Some(definition) = self.definitions.get(&id) {
|
||||
self.displaced_provider_ids.insert(id.clone());
|
||||
updates.insert(id, definition.clone());
|
||||
}
|
||||
}
|
||||
merge_toml_values(config, overlay);
|
||||
} else {
|
||||
apply_merge(config, segments, value, strategy)?;
|
||||
}
|
||||
self.displaced_provider_ids.extend(
|
||||
previous_ids
|
||||
.into_iter()
|
||||
.filter(|id| providers(config).is_none_or(|table| table.get(id).is_none())),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn validate_remapping(
|
||||
&self,
|
||||
original_user_config: &TomlValue,
|
||||
user_config: &TomlValue,
|
||||
layers: &ConfigLayerStack,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut previous = TomlValue::Table(Default::default());
|
||||
let mut effective = previous.clone();
|
||||
let mut user_reached = false;
|
||||
let mut to_validate = BTreeMap::new();
|
||||
for layer in layers.layers_low_to_high() {
|
||||
let is_user = layers
|
||||
.get_active_user_layer()
|
||||
.is_some_and(|user| std::ptr::eq(layer, user));
|
||||
merge_toml_values(
|
||||
&mut previous,
|
||||
if is_user {
|
||||
original_user_config
|
||||
} else {
|
||||
&layer.config
|
||||
},
|
||||
);
|
||||
merge_toml_values(&mut effective, &layer.config);
|
||||
user_reached |= is_user;
|
||||
if user_reached {
|
||||
for (id, old) in providers(&previous)
|
||||
.and_then(TomlValue::as_table)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
// Deleting an override and continuing an incomplete draft remain allowed.
|
||||
if providers(user_config).is_none_or(|map| map.get(id).is_none()) {
|
||||
continue;
|
||||
}
|
||||
let Some(current) = providers(&effective).and_then(|map| map.get(id)) else {
|
||||
continue;
|
||||
};
|
||||
if current == old {
|
||||
continue;
|
||||
}
|
||||
let Ok(old): Result<CredentialProviderConfig, _> = old.clone().try_into()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if old.validate(id).is_ok() {
|
||||
to_validate.insert(id.clone(), current.clone());
|
||||
}
|
||||
}
|
||||
// Compare final ownership, not temporary source moves within the write batch.
|
||||
for (id, definition) in providers(&effective)
|
||||
.and_then(TomlValue::as_table)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let receives_source = providers(&previous)
|
||||
.and_then(TomlValue::as_table)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|(old_id, old)| {
|
||||
// Retained definitions exclude explicit deletes, not automatic eviction.
|
||||
(self.definitions.get(old_id).is_some()
|
||||
|| self.definitions.get(id).is_some()
|
||||
&& providers(original_user_config).and_then(|map| map.get(id))
|
||||
!= providers(user_config).and_then(|map| map.get(id)))
|
||||
&& sources(old).any(|old_source| {
|
||||
!providers(&effective)
|
||||
.and_then(|map| map.get(old_id))
|
||||
.is_some_and(|current| {
|
||||
sources(current)
|
||||
.any(|source| same_source(source, old_source))
|
||||
})
|
||||
&& sources(definition)
|
||||
.any(|source| same_source(source, old_source))
|
||||
})
|
||||
});
|
||||
if receives_source || to_validate.contains_key(id) {
|
||||
// A higher same-ID layer may complete a fragment; a different ID may not.
|
||||
to_validate.insert(id.clone(), definition.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, definition) in to_validate {
|
||||
let provider: CredentialProviderConfig = definition.try_into()?;
|
||||
provider.validate(&id)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn config_edit_at_path(
|
||||
config: &TomlValue,
|
||||
segments: Vec<String>,
|
||||
) -> Result<ConfigEdit, ConfigManagerError> {
|
||||
match value_at_path(config, &segments) {
|
||||
Some(value) => Ok(ConfigEdit::SetPath {
|
||||
value: toml_value_to_item(value)
|
||||
.map_err(|err| ConfigManagerError::anyhow("failed to build config edits", err))?,
|
||||
segments,
|
||||
}),
|
||||
None => Ok(ConfigEdit::ClearPath { segments }),
|
||||
}
|
||||
}
|
||||
|
||||
fn sources(provider: &TomlValue) -> impl Iterator<Item = &str> {
|
||||
provider
|
||||
.get("env")
|
||||
.and_then(TomlValue::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(TomlValue::as_str)
|
||||
}
|
||||
|
||||
fn same_source(left: &str, right: &str) -> bool {
|
||||
left == right || cfg!(windows) && left.eq_ignore_ascii_case(right)
|
||||
}
|
||||
|
||||
fn providers(config: &TomlValue) -> Option<&TomlValue> {
|
||||
PROVIDERS_PATH
|
||||
.iter()
|
||||
.try_fold(config, |value, key| value.get(*key))
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
//! Projects safe provider summaries and shares field editability policy with provider writes.
|
||||
|
||||
use super::ConfigManager;
|
||||
use super::ConfigManagerError;
|
||||
use super::TomlValue;
|
||||
use codex_app_server_protocol::GatewayAuth;
|
||||
use codex_app_server_protocol::ModelProviderListParams;
|
||||
use codex_app_server_protocol::ModelProviderListResponse;
|
||||
use codex_app_server_protocol::ModelProviderSummary;
|
||||
use codex_app_server_protocol::ProviderSettings;
|
||||
use codex_config::ConfigLayerEntry;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_NAME;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_NAME;
|
||||
use codex_model_provider_info::GCP_PROVIDER_ID;
|
||||
use codex_model_provider_info::GCP_PROVIDER_NAME;
|
||||
use codex_model_provider_info::LMSTUDIO_OSS_PROVIDER_ID;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::OLLAMA_OSS_PROVIDER_ID;
|
||||
use codex_model_provider_info::OPENAI_PROVIDER_ID;
|
||||
use codex_model_provider_info::OPENAI_PROVIDER_NAME;
|
||||
use codex_model_provider_info::built_in_model_providers;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
fn string_field(config: Option<&TomlValue>, key: &str) -> Option<String> {
|
||||
config?.get(key)?.as_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
pub(super) fn has_external_auth(config: &TomlValue) -> bool {
|
||||
config
|
||||
.get("base_url")
|
||||
.and_then(TomlValue::as_str)
|
||||
.and_then(|value| url::Url::parse(value).ok())
|
||||
.is_some_and(|url| {
|
||||
!url.username().is_empty() || url.password().is_some() || url.query().is_some()
|
||||
})
|
||||
|| ["auth", "gateway_oauth", "aws", "experimental_bearer_token"]
|
||||
.iter()
|
||||
.any(|key| config.get(key).is_some())
|
||||
|| config
|
||||
.get("requires_openai_auth")
|
||||
.and_then(TomlValue::as_bool)
|
||||
== Some(true)
|
||||
|| ["http_headers", "env_http_headers", "query_params"]
|
||||
.iter()
|
||||
.filter_map(|key| config.get(key)?.as_table())
|
||||
.any(|headers| !headers.is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn valid_endpoint(value: &str) -> bool {
|
||||
url::Url::parse(value).is_ok_and(|url| {
|
||||
matches!(url.scheme(), "http" | "https")
|
||||
&& url.has_host()
|
||||
&& url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
&& url.query().is_none()
|
||||
&& url.fragment().is_none()
|
||||
})
|
||||
}
|
||||
|
||||
impl ConfigManager {
|
||||
pub(crate) async fn model_provider_list(
|
||||
&self,
|
||||
_params: ModelProviderListParams,
|
||||
) -> Result<ModelProviderListResponse, ConfigManagerError> {
|
||||
let layers = self
|
||||
.load_thread_agnostic_config()
|
||||
.await
|
||||
.map_err(|e| ConfigManagerError::io("failed to read providers", e))?;
|
||||
let effective = layers.effective_config();
|
||||
let builtins = built_in_model_providers(/*openai_base_url*/ None);
|
||||
let writable_user_layer = writable_user_layer(&layers, self.loader_overrides());
|
||||
let configured = effective
|
||||
.get("model_providers")
|
||||
.and_then(TomlValue::as_table);
|
||||
let default_id = layers
|
||||
.required_model_provider()
|
||||
.or_else(|| effective.get("model_provider").and_then(TomlValue::as_str))
|
||||
.unwrap_or(OPENAI_PROVIDER_ID);
|
||||
let selection_layer = layers
|
||||
.layers_high_to_low()
|
||||
.find(|layer| layer.config.get("model_provider").is_some());
|
||||
let can_change_default = layers.required_model_provider().is_none()
|
||||
&& writable_user_layer.is_some_and(|user| {
|
||||
selection_layer
|
||||
.is_none_or(|layer| layer.name.precedence() <= user.name.precedence())
|
||||
});
|
||||
let ids: BTreeSet<_> = configured
|
||||
.into_iter()
|
||||
.flat_map(|table| table.keys().map(String::as_str))
|
||||
// Local OSS built-ins cannot have configured provider tables.
|
||||
.filter(|id| !matches!(*id, OLLAMA_OSS_PROVIDER_ID | LMSTUDIO_OSS_PROVIDER_ID))
|
||||
.chain([OPENAI_PROVIDER_ID])
|
||||
.collect();
|
||||
let data = ids
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
summarize_provider(
|
||||
id,
|
||||
configured.and_then(|table| table.get(id)),
|
||||
builtins.get(id),
|
||||
&effective,
|
||||
&layers,
|
||||
writable_user_layer,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Ok(ModelProviderListResponse {
|
||||
data,
|
||||
default_provider_id: default_id.to_owned(),
|
||||
can_change_default,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn summarize_provider(
|
||||
id: &str,
|
||||
config: Option<&TomlValue>,
|
||||
builtin: Option<&ModelProviderInfo>,
|
||||
effective: &TomlValue,
|
||||
layers: &ConfigLayerStack,
|
||||
writable_user_layer: Option<&ConfigLayerEntry>,
|
||||
) -> ModelProviderSummary {
|
||||
let display_name = match builtin {
|
||||
Some(_) if id == AMAZON_BEDROCK_PROVIDER_ID => "Amazon Bedrock Mantle",
|
||||
Some(provider) => &provider.name,
|
||||
None => config.and_then(|c| c.get("name")?.as_str()).unwrap_or(id),
|
||||
};
|
||||
let builtin_auth = uses_builtin_auth(display_name);
|
||||
let requires_rename = builtin.is_none() && (display_name.trim().is_empty() || builtin_auth);
|
||||
let external_auth = builtin_auth || config.is_some_and(has_external_auth);
|
||||
let base_url = if id == OPENAI_PROVIDER_ID {
|
||||
effective.get("openai_base_url")
|
||||
} else {
|
||||
config.and_then(|config| config.get("base_url"))
|
||||
}
|
||||
.and_then(TomlValue::as_str)
|
||||
.filter(|url| valid_endpoint(url))
|
||||
.map(str::to_owned);
|
||||
let settings = match id {
|
||||
OPENAI_PROVIDER_ID => ProviderSettings::OpenAi,
|
||||
AMAZON_BEDROCK_PROVIDER_ID | AMAZON_BEDROCK_RUNTIME_PROVIDER_ID => {
|
||||
let aws = config.and_then(|provider| provider.get("aws"));
|
||||
ProviderSettings::Bedrock {
|
||||
profile: string_field(aws, "profile"),
|
||||
region: string_field(aws, "region"),
|
||||
}
|
||||
}
|
||||
GCP_PROVIDER_ID => ProviderSettings::Gcp {
|
||||
project_id: string_field(config, "project_id"),
|
||||
location: string_field(config, "location"),
|
||||
credential_file: string_field(config, "credential_file"),
|
||||
},
|
||||
_ => {
|
||||
let env_key = string_field(config, "env_key");
|
||||
let auth = if external_auth {
|
||||
GatewayAuth::ExternallyConfigured { env_key }
|
||||
} else if let Some(env_key) = env_key {
|
||||
GatewayAuth::EnvironmentVariable { env_key }
|
||||
} else {
|
||||
GatewayAuth::None
|
||||
};
|
||||
ProviderSettings::CustomGateway { auth }
|
||||
}
|
||||
};
|
||||
let can_edit = supported_fields(id, config, builtin).iter().any(|&field| {
|
||||
(field == "name" || !requires_rename)
|
||||
&& (field != "env_key" || !external_auth)
|
||||
&& field_is_writable(layers, writable_user_layer, id, field)
|
||||
});
|
||||
ModelProviderSummary {
|
||||
id: id.to_owned(),
|
||||
name: display_name.to_owned(),
|
||||
can_edit,
|
||||
base_url,
|
||||
settings,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn uses_builtin_auth(name: &str) -> bool {
|
||||
matches!(
|
||||
name,
|
||||
OPENAI_PROVIDER_NAME
|
||||
| AMAZON_BEDROCK_PROVIDER_NAME
|
||||
| AMAZON_BEDROCK_RUNTIME_PROVIDER_NAME
|
||||
| GCP_PROVIDER_NAME
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn writable_user_layer<'a>(
|
||||
layers: &'a ConfigLayerStack,
|
||||
overrides: &LoaderOverrides,
|
||||
) -> Option<&'a ConfigLayerEntry> {
|
||||
layers
|
||||
.get_active_user_layer()
|
||||
.filter(|user| !user.is_disabled() && !overrides.ignore_user_config)
|
||||
}
|
||||
|
||||
pub(super) fn supported_fields(
|
||||
id: &str,
|
||||
config: Option<&TomlValue>,
|
||||
builtin: Option<&ModelProviderInfo>,
|
||||
) -> &'static [&'static str] {
|
||||
let aws_config = config.and_then(|config| config.get("aws"));
|
||||
match (builtin, id) {
|
||||
(Some(_), AMAZON_BEDROCK_PROVIDER_ID | AMAZON_BEDROCK_RUNTIME_PROVIDER_ID) => {
|
||||
if config.is_some_and(|config| config.get("auth").is_some()) {
|
||||
&[]
|
||||
} else if aws_config.is_some_and(|aws| aws.get("credential_export").is_some()) {
|
||||
&["aws.region"]
|
||||
} else {
|
||||
&["aws.profile", "aws.region"]
|
||||
}
|
||||
}
|
||||
(Some(_), GCP_PROVIDER_ID) => &["project_id", "location", "credential_file"],
|
||||
(Some(_), _) => &[],
|
||||
(None, _) => &["name", "base_url", "env_key"],
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn field_is_writable(
|
||||
layers: &ConfigLayerStack,
|
||||
writable_user_layer: Option<&ConfigLayerEntry>,
|
||||
id: &str,
|
||||
field: &str,
|
||||
) -> bool {
|
||||
let Some(user) = writable_user_layer else {
|
||||
return false;
|
||||
};
|
||||
if id.is_empty()
|
||||
|| layers
|
||||
.requirements_toml()
|
||||
.model_providers
|
||||
.as_ref()
|
||||
.is_some_and(|providers| providers.contains_key(id))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
!layers.layers_high_to_low().any(|layer| {
|
||||
layer.name.precedence() > user.name.precedence()
|
||||
&& layer
|
||||
.config
|
||||
.get("model_providers")
|
||||
.and_then(|providers| providers.get(id))
|
||||
.and_then(|provider| {
|
||||
field
|
||||
.split('.')
|
||||
.try_fold(provider, |value, key| value.get(key))
|
||||
})
|
||||
.is_some()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Previews the effective provider configuration and captures the user layer version for commit.
|
||||
|
||||
use super::ConfigManagerError;
|
||||
use super::MergeError;
|
||||
use super::PreparedProviderWrite;
|
||||
use super::apply_merge;
|
||||
use super::find_effective_layer;
|
||||
use super::override_message;
|
||||
use super::parse_value;
|
||||
use super::value_at_path;
|
||||
use super::writable_key_path;
|
||||
use codex_app_server_protocol::ConfigEdit;
|
||||
use codex_app_server_protocol::ConfigWriteErrorCode;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::version_for_toml;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
pub(super) fn preview(
|
||||
layers: &ConfigLayerStack,
|
||||
user_path: &AbsolutePathBuf,
|
||||
provider_id: &str,
|
||||
edits: Vec<ConfigEdit>,
|
||||
) -> Result<(PreparedProviderWrite, ModelProviderInfo), ConfigManagerError> {
|
||||
let (mut user_config, expected_version) = match layers.get_active_user_layer() {
|
||||
Some(layer) => (layer.config.clone(), layer.version.clone()),
|
||||
None => {
|
||||
let empty = TomlValue::Table(Default::default());
|
||||
let version = version_for_toml(&empty);
|
||||
(empty, version)
|
||||
}
|
||||
};
|
||||
let mut fields = Vec::with_capacity(edits.len());
|
||||
for edit in &edits {
|
||||
let path = writable_key_path(layers, &edit.key_path)?;
|
||||
let value = parse_value(edit.value.clone())?;
|
||||
apply_merge(
|
||||
&mut user_config,
|
||||
&path,
|
||||
value.as_ref(),
|
||||
edit.merge_strategy.clone(),
|
||||
)
|
||||
.map_err(|MergeError::Validation(message)| {
|
||||
ConfigManagerError::write(ConfigWriteErrorCode::ConfigValidationError, message)
|
||||
})?;
|
||||
fields.push((&edit.key_path, path, value));
|
||||
}
|
||||
|
||||
let preview = layers
|
||||
.with_user_config(user_path, user_config)
|
||||
.map_err(|err| {
|
||||
ConfigManagerError::write(ConfigWriteErrorCode::ConfigValidationError, err.to_string())
|
||||
})?;
|
||||
let effective = preview.effective_config();
|
||||
for (key, path, expected) in fields {
|
||||
if value_at_path(&effective, &path) != expected.as_ref() {
|
||||
let source = find_effective_layer(&preview, &path)
|
||||
.map(|layer| override_message(&layer.name))
|
||||
.unwrap_or_else(|| "Overridden by another configuration layer".to_owned());
|
||||
return Err(ConfigManagerError::write(
|
||||
ConfigWriteErrorCode::ConfigLayerReadonly,
|
||||
format!("Cannot configure `{key}`: {source}"),
|
||||
));
|
||||
}
|
||||
}
|
||||
let provider = effective
|
||||
.get("model_providers")
|
||||
.and_then(|providers| providers.get(provider_id))
|
||||
.cloned()
|
||||
.map(TomlValue::try_into)
|
||||
.transpose()
|
||||
.map_err(|_| {
|
||||
ConfigManagerError::write(
|
||||
ConfigWriteErrorCode::ConfigValidationError,
|
||||
format!("Invalid `{provider_id}` provider configuration."),
|
||||
)
|
||||
})?
|
||||
.unwrap_or_default();
|
||||
Ok((
|
||||
PreparedProviderWrite {
|
||||
edits,
|
||||
expected_version,
|
||||
},
|
||||
provider,
|
||||
))
|
||||
}
|
||||
291
codex-rs/app-server/src/config_manager_service_provider_write.rs
Normal file
291
codex-rs/app-server/src/config_manager_service_provider_write.rs
Normal file
@@ -0,0 +1,291 @@
|
||||
//! Applies provider field patches without selecting a provider or changing hidden credentials.
|
||||
//! RPC writes share the config queue and apply field patches with last-write-wins semantics.
|
||||
|
||||
use super::ApiConfigEdit;
|
||||
use super::ConfigManager;
|
||||
use super::ConfigManagerError;
|
||||
use super::MergeStrategy;
|
||||
use super::TomlValue;
|
||||
use super::model_providers::field_is_writable;
|
||||
use super::model_providers::has_external_auth;
|
||||
use super::model_providers::summarize_provider;
|
||||
use super::model_providers::supported_fields;
|
||||
use super::model_providers::uses_builtin_auth;
|
||||
use super::model_providers::valid_endpoint;
|
||||
use super::model_providers::writable_user_layer;
|
||||
use codex_app_server_protocol::BedrockProviderId;
|
||||
use codex_app_server_protocol::ConfigBatchWriteParams;
|
||||
use codex_app_server_protocol::ConfigWriteErrorCode;
|
||||
use codex_app_server_protocol::CustomGatewaySettingsParams;
|
||||
use codex_app_server_protocol::GcpProviderId;
|
||||
use codex_app_server_protocol::ModelProviderConfigWriteParams;
|
||||
use codex_app_server_protocol::ModelProviderConfigWriteResponse;
|
||||
use codex_app_server_protocol::ProviderSettingsPatch;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_ID;
|
||||
use codex_model_provider_info::GCP_PROVIDER_ID;
|
||||
use codex_model_provider_info::LEGACY_OLLAMA_CHAT_PROVIDER_ID;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::built_in_model_providers;
|
||||
use std::collections::HashMap;
|
||||
|
||||
impl ConfigManager {
|
||||
pub(crate) async fn model_provider_config_write(
|
||||
&self,
|
||||
params: ModelProviderConfigWriteParams,
|
||||
) -> Result<ModelProviderConfigWriteResponse, ConfigManagerError> {
|
||||
let layers = self
|
||||
.load_thread_agnostic_config()
|
||||
.await
|
||||
.map_err(|err| ConfigManagerError::io("failed to read providers", err))?;
|
||||
let builtins = built_in_model_providers(/*openai_base_url*/ None);
|
||||
let (provider_id, edits) =
|
||||
provider_edits(¶ms, &layers, self.loader_overrides(), &builtins)?;
|
||||
let response = self
|
||||
.batch_write(ConfigBatchWriteParams {
|
||||
edits,
|
||||
file_path: None,
|
||||
expected_version: None,
|
||||
reload_user_config: false,
|
||||
})
|
||||
.await?;
|
||||
if let Some(overridden) = response.overridden_metadata {
|
||||
return Err(ConfigManagerError::write(
|
||||
ConfigWriteErrorCode::ConfigLayerReadonly,
|
||||
overridden.message,
|
||||
));
|
||||
}
|
||||
let saved = self
|
||||
.load_thread_agnostic_config()
|
||||
.await
|
||||
.map_err(|err| ConfigManagerError::io("failed to read saved provider", err))?;
|
||||
let effective = saved.effective_config();
|
||||
let provider = summarize_provider(
|
||||
&provider_id,
|
||||
effective
|
||||
.get("model_providers")
|
||||
.and_then(|providers| providers.get(&provider_id)),
|
||||
builtins.get(&provider_id),
|
||||
&effective,
|
||||
&saved,
|
||||
writable_user_layer(&saved, self.loader_overrides()),
|
||||
);
|
||||
Ok(ModelProviderConfigWriteResponse { provider })
|
||||
}
|
||||
}
|
||||
|
||||
fn provider_edits(
|
||||
params: &ModelProviderConfigWriteParams,
|
||||
layers: &ConfigLayerStack,
|
||||
overrides: &LoaderOverrides,
|
||||
builtins: &HashMap<String, ModelProviderInfo>,
|
||||
) -> Result<(String, Vec<ApiConfigEdit>), ConfigManagerError> {
|
||||
let effective = layers.effective_config();
|
||||
let configured = effective.get("model_providers");
|
||||
let (provider_id, mut fields) = match ¶ms.settings {
|
||||
ProviderSettingsPatch::CustomGateway(patch) => {
|
||||
let target = patch.provider_id.as_deref();
|
||||
if target
|
||||
.is_some_and(|id| builtins.contains_key(id) || id == LEGACY_OLLAMA_CHAT_PROVIDER_ID)
|
||||
{
|
||||
return Err(invalid(
|
||||
"A custom provider or gateway cannot use a built-in provider ID.",
|
||||
));
|
||||
}
|
||||
let existing = target.and_then(|id| configured?.get(id));
|
||||
if target.is_some() && existing.is_none() {
|
||||
return Err(ConfigManagerError::write(
|
||||
ConfigWriteErrorCode::ConfigPathNotFound,
|
||||
"Unknown provider ID.",
|
||||
));
|
||||
}
|
||||
let name = validate_custom_patch(patch, existing)?;
|
||||
let id = if let Some(id) = target {
|
||||
id.to_owned()
|
||||
} else {
|
||||
if patch.base_url.as_ref().and_then(Option::as_deref).is_none() {
|
||||
return Err(invalid(
|
||||
"A base URL is required to create a custom provider.",
|
||||
));
|
||||
}
|
||||
let default_id = layers
|
||||
.required_model_provider()
|
||||
.or_else(|| effective.get("model_provider")?.as_str());
|
||||
allocate_custom_id(name, |id| {
|
||||
builtins.contains_key(id)
|
||||
|| configured.is_some_and(|table| table.get(id).is_some())
|
||||
|| default_id == Some(id)
|
||||
})
|
||||
};
|
||||
let mut fields =
|
||||
patch_fields([("base_url", &patch.base_url), ("env_key", &patch.env_key)]);
|
||||
if patch.name.is_some() {
|
||||
fields.push(("name", Some(name)));
|
||||
}
|
||||
(id, fields)
|
||||
}
|
||||
ProviderSettingsPatch::Bedrock(patch) => {
|
||||
let id = match patch.provider_id {
|
||||
BedrockProviderId::AmazonBedrock => AMAZON_BEDROCK_PROVIDER_ID,
|
||||
BedrockProviderId::AmazonBedrockRuntime => AMAZON_BEDROCK_RUNTIME_PROVIDER_ID,
|
||||
};
|
||||
(
|
||||
id.to_owned(),
|
||||
patch_fields([
|
||||
("aws.profile", &patch.profile),
|
||||
("aws.region", &patch.region),
|
||||
]),
|
||||
)
|
||||
}
|
||||
ProviderSettingsPatch::Gcp(patch) => {
|
||||
let GcpProviderId::Gcp = patch.provider_id;
|
||||
(
|
||||
GCP_PROVIDER_ID.to_owned(),
|
||||
patch_fields([
|
||||
("project_id", &patch.project_id),
|
||||
("location", &patch.location),
|
||||
("credential_file", &patch.credential_file),
|
||||
]),
|
||||
)
|
||||
}
|
||||
};
|
||||
if fields.iter().any(|(_, value)| *value == Some("")) {
|
||||
return Err(invalid(
|
||||
"Configuration values must not be empty; use null to clear a field.",
|
||||
));
|
||||
}
|
||||
let existing = configured.and_then(|providers| providers.get(&provider_id));
|
||||
let builtin = builtins.get(&provider_id);
|
||||
let user_layer = writable_user_layer(layers, overrides);
|
||||
let supported = supported_fields(&provider_id, existing, builtin);
|
||||
for (field, _) in &fields {
|
||||
if !supported.contains(field) {
|
||||
return Err(invalid(
|
||||
"A supplied field is not editable for this provider.",
|
||||
));
|
||||
}
|
||||
if !field_is_writable(layers, user_layer, &provider_id, field) {
|
||||
return Err(ConfigManagerError::write(
|
||||
ConfigWriteErrorCode::ConfigLayerReadonly,
|
||||
"This configuration field is read-only.",
|
||||
));
|
||||
}
|
||||
}
|
||||
// Custom override tables require a name, but clearing an absent leaf needs no table.
|
||||
let user_provider =
|
||||
user_layer.and_then(|layer| layer.config.get("model_providers")?.get(&provider_id));
|
||||
if builtin.is_none()
|
||||
&& !fields.is_empty()
|
||||
&& !fields.iter().any(|(field, _)| *field == "name")
|
||||
&& (user_provider.is_some() || fields.iter().any(|(_, value)| value.is_some()))
|
||||
&& user_provider
|
||||
.and_then(|provider| provider.get("name"))
|
||||
.is_none()
|
||||
&& let Some(name) = existing.and_then(|provider| provider.get("name")?.as_str())
|
||||
{
|
||||
fields.push(("name", Some(name)));
|
||||
}
|
||||
if builtin.is_none() && existing.is_none() {
|
||||
fields.push(("wire_api", Some("responses")));
|
||||
}
|
||||
let escaped_id = provider_id.replace('\\', "\\\\").replace('"', "\\\"");
|
||||
let edits = fields
|
||||
.into_iter()
|
||||
.map(|(field, value)| ApiConfigEdit {
|
||||
key_path: format!(r#"model_providers."{escaped_id}".{field}"#),
|
||||
value: value.into(),
|
||||
merge_strategy: MergeStrategy::Replace,
|
||||
})
|
||||
.collect();
|
||||
Ok((provider_id, edits))
|
||||
}
|
||||
|
||||
// Missing fields are excluded. A field with no value clears its TOML key.
|
||||
type PatchField<'a> = (&'static str, Option<&'a str>);
|
||||
|
||||
fn patch_fields<'a, const N: usize>(
|
||||
requested: [(&'static str, &'a Option<Option<String>>); N],
|
||||
) -> Vec<PatchField<'a>> {
|
||||
requested
|
||||
.into_iter()
|
||||
.filter_map(|(field, value)| {
|
||||
value
|
||||
.as_ref()
|
||||
.map(|value| (field, value.as_deref().map(str::trim)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn validate_custom_patch<'a>(
|
||||
patch: &'a CustomGatewaySettingsParams,
|
||||
existing: Option<&'a TomlValue>,
|
||||
) -> Result<&'a str, ConfigManagerError> {
|
||||
if patch
|
||||
.base_url
|
||||
.as_ref()
|
||||
.and_then(Option::as_deref)
|
||||
.is_some_and(|url| !valid_endpoint(url.trim()))
|
||||
{
|
||||
return Err(invalid(
|
||||
"Enter an HTTP(S) base URL without credentials, a query, or a fragment.",
|
||||
));
|
||||
}
|
||||
if let Some(Some(key)) = &patch.env_key {
|
||||
let key = key.trim();
|
||||
if !key.starts_with(|c: char| c == '_' || c.is_ascii_alphabetic())
|
||||
|| !key.bytes().all(|c| c == b'_' || c.is_ascii_alphanumeric())
|
||||
{
|
||||
return Err(invalid("Invalid API key environment variable name."));
|
||||
}
|
||||
}
|
||||
let existing_name = existing.and_then(|config| config.get("name")?.as_str());
|
||||
if patch.env_key.is_some()
|
||||
&& existing.is_some_and(|config| {
|
||||
has_external_auth(config)
|
||||
|| existing_name
|
||||
.or(patch.provider_id.as_deref())
|
||||
.is_some_and(uses_builtin_auth)
|
||||
})
|
||||
{
|
||||
return Err(invalid(
|
||||
"Authentication is configured externally. Omit envKey to preserve it.",
|
||||
));
|
||||
}
|
||||
let name = patch
|
||||
.name
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.or(existing_name)
|
||||
.filter(|name| !name.trim().is_empty())
|
||||
.ok_or_else(|| invalid("Enter a provider name."))?;
|
||||
// Legacy names select built-in authentication even on a custom provider.
|
||||
if uses_builtin_auth(name) {
|
||||
return Err(invalid(
|
||||
"This name is reserved for a built-in provider. Enter a different custom provider name.",
|
||||
));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
fn allocate_custom_id(name: &str, is_taken: impl Fn(&str) -> bool) -> String {
|
||||
let slug = name
|
||||
.split(|c: char| !c.is_ascii_alphanumeric())
|
||||
.filter(|part| !part.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("-")
|
||||
.to_ascii_lowercase();
|
||||
let stem = if slug.is_empty() { "custom" } else { &slug };
|
||||
let mut id = stem.to_owned();
|
||||
let mut suffix = 2;
|
||||
while id == LEGACY_OLLAMA_CHAT_PROVIDER_ID || is_taken(&id) {
|
||||
id = format!("{stem}-{suffix}");
|
||||
suffix += 1;
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
fn invalid(message: &str) -> ConfigManagerError {
|
||||
ConfigManagerError::write(ConfigWriteErrorCode::ConfigValidationError, message)
|
||||
}
|
||||
3675
codex-rs/app-server/src/config_manager_service_tests.rs
Normal file
3675
codex-rs/app-server/src/config_manager_service_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
49
codex-rs/app-server/src/connection_cleanup.rs
Normal file
49
codex-rs/app-server/src/connection_cleanup.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use std::future::Future;
|
||||
use std::future::pending;
|
||||
|
||||
use tokio::task::JoinError;
|
||||
use tokio::task::JoinSet;
|
||||
use tracing::warn;
|
||||
|
||||
pub(crate) struct ConnectionCleanupTasks {
|
||||
tasks: JoinSet<()>,
|
||||
}
|
||||
|
||||
impl ConnectionCleanupTasks {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
tasks: JoinSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn spawn(&mut self, future: impl Future<Output = ()> + Send + 'static) {
|
||||
self.tasks.spawn(future);
|
||||
}
|
||||
|
||||
pub(crate) async fn reap_next(&mut self) {
|
||||
if self.tasks.is_empty() {
|
||||
pending::<()>().await;
|
||||
}
|
||||
if let Some(result) = self.tasks.join_next().await {
|
||||
log_cleanup_result(result);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn drain(&mut self) {
|
||||
while let Some(result) = self.tasks.join_next().await {
|
||||
log_cleanup_result(result);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn abort(&mut self) {
|
||||
self.tasks.abort_all();
|
||||
}
|
||||
}
|
||||
|
||||
fn log_cleanup_result(result: Result<(), JoinError>) {
|
||||
if let Err(err) = result
|
||||
&& !err.is_cancelled()
|
||||
{
|
||||
warn!("connection cleanup task failed: {err}");
|
||||
}
|
||||
}
|
||||
249
codex-rs/app-server/src/connection_rpc_gate.rs
Normal file
249
codex-rs/app-server/src/connection_rpc_gate.rs
Normal file
@@ -0,0 +1,249 @@
|
||||
//! Controls RPC admission and draining for each connection.
|
||||
//! Auth ownership changes reject queued work while started handlers finish cleanup.
|
||||
|
||||
use std::future::Future;
|
||||
|
||||
use codex_app_server_transport::ConnectionAuth;
|
||||
|
||||
use tokio::sync::Mutex;
|
||||
use tokio_util::task::TaskTracker;
|
||||
|
||||
/// Per-connection gate for incoming messages and initialized RPC handler execution.
|
||||
///
|
||||
/// Closing the gate prevents queued handlers from starting while allowing
|
||||
/// handlers that already acquired a token to finish.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ConnectionRpcGate {
|
||||
pub(crate) auth: Option<ConnectionAuth>,
|
||||
accepting: Mutex<bool>,
|
||||
tasks: TaskTracker,
|
||||
}
|
||||
|
||||
impl ConnectionRpcGate {
|
||||
pub(crate) fn new() -> Self {
|
||||
let accepting = true;
|
||||
Self {
|
||||
auth: None,
|
||||
accepting: Mutex::new(accepting),
|
||||
tasks: TaskTracker::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn run<F>(&self, future: F)
|
||||
where
|
||||
F: Future<Output = ()>,
|
||||
{
|
||||
let token = {
|
||||
let accepting = self.accepting.lock().await;
|
||||
if !*accepting || self.is_closed() {
|
||||
return;
|
||||
}
|
||||
self.tasks.token()
|
||||
};
|
||||
|
||||
future.await;
|
||||
drop(token);
|
||||
}
|
||||
|
||||
pub(crate) fn is_closed(&self) -> bool {
|
||||
self.tasks.is_closed() || self.auth.as_ref().is_some_and(|auth| !auth.is_current())
|
||||
}
|
||||
|
||||
pub(crate) async fn close(&self) {
|
||||
let mut accepting = self.accepting.lock().await;
|
||||
*accepting = false;
|
||||
self.tasks.close();
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
self.close().await;
|
||||
self.tasks.wait().await;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
async fn is_accepting(&self) -> bool {
|
||||
*self.accepting.lock().await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn inflight_count(&self) -> usize {
|
||||
self.tasks.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ConnectionRpcGate {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_executes_while_open() {
|
||||
let gate = ConnectionRpcGate::new();
|
||||
let ran = Arc::new(AtomicBool::new(/*v*/ false));
|
||||
let ran_clone = Arc::clone(&ran);
|
||||
|
||||
gate.run(async move {
|
||||
ran_clone.store(/*val*/ true, Ordering::Release);
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(ran.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_drops_future_without_polling_after_close() {
|
||||
let gate = ConnectionRpcGate::new();
|
||||
gate.close().await;
|
||||
let polled = Arc::new(AtomicBool::new(/*v*/ false));
|
||||
let polled_clone = Arc::clone(&polled);
|
||||
|
||||
gate.run(async move {
|
||||
polled_clone.store(/*val*/ true, Ordering::Release);
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(!polled.load(Ordering::Acquire));
|
||||
assert!(!gate.is_accepting().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_returns_while_started_run_remains_active() {
|
||||
let gate = Arc::new(ConnectionRpcGate::new());
|
||||
let (started_tx, started_rx) = oneshot::channel();
|
||||
let (finish_tx, finish_rx) = oneshot::channel();
|
||||
let gate_for_run = Arc::clone(&gate);
|
||||
let run_task = tokio::spawn(async move {
|
||||
gate_for_run
|
||||
.run(async move {
|
||||
started_tx.send(()).expect("receiver should be open");
|
||||
let _ = finish_rx.await;
|
||||
})
|
||||
.await;
|
||||
});
|
||||
|
||||
started_rx.await.expect("run should start");
|
||||
gate.close().await;
|
||||
assert!(!gate.is_accepting().await);
|
||||
assert_eq!(gate.inflight_count(), 1);
|
||||
|
||||
finish_tx
|
||||
.send(())
|
||||
.expect("running future should be waiting");
|
||||
run_task.await.expect("run task should complete");
|
||||
gate.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_waits_for_started_run_to_finish() {
|
||||
let gate = Arc::new(ConnectionRpcGate::new());
|
||||
let (started_tx, started_rx) = oneshot::channel();
|
||||
let (finish_tx, finish_rx) = oneshot::channel();
|
||||
let gate_for_run = Arc::clone(&gate);
|
||||
let run_task = tokio::spawn(async move {
|
||||
gate_for_run
|
||||
.run(async move {
|
||||
started_tx.send(()).expect("receiver should be open");
|
||||
let _ = finish_rx.await;
|
||||
})
|
||||
.await;
|
||||
});
|
||||
|
||||
started_rx.await.expect("run should start");
|
||||
assert_eq!(gate.inflight_count(), 1);
|
||||
|
||||
let gate_for_shutdown = Arc::clone(&gate);
|
||||
let shutdown_task = tokio::spawn(async move {
|
||||
gate_for_shutdown.shutdown().await;
|
||||
});
|
||||
|
||||
timeout(Duration::from_millis(/*millis*/ 50), shutdown_task)
|
||||
.await
|
||||
.expect_err("shutdown should wait for the running future");
|
||||
|
||||
finish_tx
|
||||
.send(())
|
||||
.expect("running future should be waiting");
|
||||
run_task.await.expect("run task should complete");
|
||||
gate.shutdown().await;
|
||||
assert_eq!(gate.inflight_count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_drops_late_runs_while_waiting_for_inflight_work() {
|
||||
let gate = Arc::new(ConnectionRpcGate::new());
|
||||
let (started_tx, started_rx) = oneshot::channel();
|
||||
let (finish_tx, finish_rx) = oneshot::channel();
|
||||
let gate_for_run = Arc::clone(&gate);
|
||||
let run_task = tokio::spawn(async move {
|
||||
gate_for_run
|
||||
.run(async move {
|
||||
started_tx.send(()).expect("receiver should be open");
|
||||
let _ = finish_rx.await;
|
||||
})
|
||||
.await;
|
||||
});
|
||||
|
||||
started_rx.await.expect("run should start");
|
||||
let gate_for_shutdown = Arc::clone(&gate);
|
||||
let shutdown_task = tokio::spawn(async move {
|
||||
gate_for_shutdown.shutdown().await;
|
||||
});
|
||||
|
||||
timeout(Duration::from_millis(/*millis*/ 50), shutdown_task)
|
||||
.await
|
||||
.expect_err("shutdown should wait for the running future");
|
||||
|
||||
let late_polled = Arc::new(AtomicBool::new(/*v*/ false));
|
||||
let late_polled_clone = Arc::clone(&late_polled);
|
||||
gate.run(async move {
|
||||
late_polled_clone.store(/*val*/ true, Ordering::Release);
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(!late_polled.load(Ordering::Acquire));
|
||||
|
||||
finish_tx
|
||||
.send(())
|
||||
.expect("running future should still be waiting");
|
||||
run_task.await.expect("run task should complete");
|
||||
gate.shutdown().await;
|
||||
assert_eq!(gate.inflight_count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_is_counted_before_handler_body_continues() {
|
||||
let gate = Arc::new(ConnectionRpcGate::new());
|
||||
let (entered_tx, entered_rx) = oneshot::channel();
|
||||
let (continue_tx, continue_rx) = oneshot::channel();
|
||||
let gate_for_run = Arc::clone(&gate);
|
||||
let run_task = tokio::spawn(async move {
|
||||
gate_for_run
|
||||
.run(async move {
|
||||
entered_tx.send(()).expect("receiver should be open");
|
||||
let _ = continue_rx.await;
|
||||
})
|
||||
.await;
|
||||
});
|
||||
|
||||
entered_rx.await.expect("handler body should be entered");
|
||||
assert_eq!(gate.inflight_count(), 1);
|
||||
|
||||
continue_tx
|
||||
.send(())
|
||||
.expect("handler body should still be waiting");
|
||||
run_task.await.expect("run task should complete");
|
||||
assert_eq!(gate.inflight_count(), 0);
|
||||
}
|
||||
}
|
||||
177
codex-rs/app-server/src/current_time.rs
Normal file
177
codex-rs/app-server/src/current_time.rs
Normal file
@@ -0,0 +1,177 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use anyhow::bail;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_app_server_protocol::CurrentTimeReadParams;
|
||||
use codex_app_server_protocol::CurrentTimeReadResponse;
|
||||
use codex_app_server_protocol::ServerRequestPayload;
|
||||
use codex_core::SleepFuture;
|
||||
use codex_core::TimeFuture;
|
||||
use codex_core::TimeProvider;
|
||||
use codex_protocol::ThreadId;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::timeout_at;
|
||||
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use crate::thread_state::ThreadStateManager;
|
||||
|
||||
const CURRENT_TIME_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const CURRENT_TIME_POLL_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
pub(crate) fn app_server_time_provider(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
thread_state_manager: ThreadStateManager,
|
||||
) -> Arc<dyn TimeProvider> {
|
||||
Arc::new(AppServerTimeProvider {
|
||||
outgoing: Arc::downgrade(&outgoing),
|
||||
thread_state_manager,
|
||||
})
|
||||
}
|
||||
|
||||
struct AppServerTimeProvider {
|
||||
outgoing: Weak<OutgoingMessageSender>,
|
||||
thread_state_manager: ThreadStateManager,
|
||||
}
|
||||
|
||||
impl TimeProvider for AppServerTimeProvider {
|
||||
fn current_time(&self, thread_id: ThreadId) -> TimeFuture<'_> {
|
||||
let outgoing = self.outgoing.clone();
|
||||
let thread_state_manager = self.thread_state_manager.clone();
|
||||
Box::pin(async move {
|
||||
let outgoing = outgoing
|
||||
.upgrade()
|
||||
.context("app-server current-time provider is unavailable")?;
|
||||
request_current_time(outgoing, thread_state_manager, thread_id).await
|
||||
})
|
||||
}
|
||||
|
||||
fn sleep(&self, thread_id: ThreadId, duration: Duration) -> SleepFuture<'_> {
|
||||
let outgoing = self.outgoing.clone();
|
||||
let thread_state_manager = self.thread_state_manager.clone();
|
||||
Box::pin(async move {
|
||||
let outgoing = outgoing
|
||||
.upgrade()
|
||||
.context("app-server current-time provider is unavailable")?;
|
||||
let started_at =
|
||||
request_current_time(outgoing.clone(), thread_state_manager.clone(), thread_id)
|
||||
.await?;
|
||||
let wake_at = started_at
|
||||
.checked_add_signed(
|
||||
chrono::Duration::from_std(duration)
|
||||
.context("external sleep duration is outside the supported range")?,
|
||||
)
|
||||
.context("external sleep deadline is outside the supported range")?;
|
||||
|
||||
loop {
|
||||
tokio::time::sleep(CURRENT_TIME_POLL_INTERVAL).await;
|
||||
if request_current_time(outgoing.clone(), thread_state_manager.clone(), thread_id)
|
||||
.await?
|
||||
>= wake_at
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_current_time(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
thread_state_manager: ThreadStateManager,
|
||||
thread_id: ThreadId,
|
||||
) -> Result<DateTime<Utc>> {
|
||||
let deadline = Instant::now() + CURRENT_TIME_REQUEST_TIMEOUT;
|
||||
timeout_at(
|
||||
deadline,
|
||||
thread_state_manager.wait_for_thread_subscriber(thread_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
anyhow!(
|
||||
"timed out waiting for a client to subscribe to the thread after {}s",
|
||||
CURRENT_TIME_REQUEST_TIMEOUT.as_secs()
|
||||
)
|
||||
})?;
|
||||
let connection_ids = thread_state_manager
|
||||
.subscribed_connection_ids(thread_id)
|
||||
.await;
|
||||
let connection_id = require_single_current_time_connection(&connection_ids)?;
|
||||
let connection_ids = [connection_id];
|
||||
let (request_id, rx) = outgoing
|
||||
.send_request_to_connections(
|
||||
Some(&connection_ids),
|
||||
ServerRequestPayload::CurrentTimeRead(CurrentTimeReadParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
}),
|
||||
/*thread_id*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
let result = match timeout_at(deadline, rx).await {
|
||||
Ok(Ok(Ok(result))) => result,
|
||||
Ok(Ok(Err(err))) => {
|
||||
bail!(
|
||||
"current-time request failed: code={} message={}",
|
||||
err.code,
|
||||
err.message
|
||||
);
|
||||
}
|
||||
Ok(Err(err)) => bail!("current-time request was canceled: {err}"),
|
||||
Err(_) => {
|
||||
let _canceled = outgoing.cancel_request(&request_id).await;
|
||||
bail!(
|
||||
"current-time request timed out after {}s",
|
||||
CURRENT_TIME_REQUEST_TIMEOUT.as_secs()
|
||||
);
|
||||
}
|
||||
};
|
||||
let response: CurrentTimeReadResponse =
|
||||
serde_json::from_value(result).context("invalid current-time response")?;
|
||||
|
||||
DateTime::from_timestamp(response.current_time_at, 0)
|
||||
.ok_or_else(|| anyhow!("current-time response is outside the supported range"))
|
||||
}
|
||||
|
||||
fn require_single_current_time_connection(connection_ids: &[ConnectionId]) -> Result<ConnectionId> {
|
||||
// External clocks are not interchangeable, so do not choose one silently.
|
||||
match connection_ids {
|
||||
[connection_id] => Ok(*connection_id),
|
||||
_ => bail!(
|
||||
"expected exactly one client subscribed to the thread, found {}",
|
||||
connection_ids.len()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::require_single_current_time_connection;
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
|
||||
#[test]
|
||||
fn current_time_connection_must_be_unambiguous() {
|
||||
assert_eq!(
|
||||
require_single_current_time_connection(&[ConnectionId(7)]).unwrap(),
|
||||
ConnectionId(7)
|
||||
);
|
||||
assert_eq!(
|
||||
require_single_current_time_connection(&[])
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"expected exactly one client subscribed to the thread, found 0"
|
||||
);
|
||||
assert_eq!(
|
||||
require_single_current_time_connection(&[ConnectionId(7), ConnectionId(8)])
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"expected exactly one client subscribed to the thread, found 2"
|
||||
);
|
||||
}
|
||||
}
|
||||
50
codex-rs/app-server/src/daemon_thread_recovery.rs
Normal file
50
codex-rs/app-server/src/daemon_thread_recovery.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
//! Saves persistent root thread IDs and restores them through the shared internal resume path.
|
||||
//! Recovery uses normal cold-resume semantics without delaying readiness for runtime loading.
|
||||
//! Already-loaded runtimes remain owned by their current clients.
|
||||
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_app_server_transport::daemon_recovery;
|
||||
|
||||
pub(crate) async fn snapshot(
|
||||
path: PathBuf,
|
||||
saved: daemon_recovery::RecoverySnapshot,
|
||||
) -> io::Result<()> {
|
||||
// A forced exit must not wait for file I/O in Tokio's blocking pool.
|
||||
let (result_tx, result_rx) = tokio::sync::oneshot::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("daemon-snapshot".into())
|
||||
.spawn(move || {
|
||||
let result = daemon_recovery::write_snapshot(&path, &saved);
|
||||
if result.is_err()
|
||||
&& let Err(err) = std::fs::remove_file(&path)
|
||||
&& err.kind() != io::ErrorKind::NotFound
|
||||
{
|
||||
tracing::warn!("failed to clear stale daemon recovery file: {err}");
|
||||
}
|
||||
let _ = result_tx.send(result);
|
||||
})?;
|
||||
result_rx.await.map_err(io::Error::other)?
|
||||
}
|
||||
|
||||
/// Consume the handoff before serving requests, then restore runtimes in the background.
|
||||
pub(crate) async fn start_recovery(
|
||||
path: PathBuf,
|
||||
processor: std::sync::Arc<crate::message_processor::MessageProcessor>,
|
||||
) -> io::Result<tokio::task::JoinHandle<()>> {
|
||||
let candidates = tokio::task::spawn_blocking(move || {
|
||||
let candidates = daemon_recovery::read_snapshot(&path);
|
||||
// Even malformed or temporarily unreadable snapshots belong to this generation only.
|
||||
match std::fs::remove_file(&path) {
|
||||
Ok(()) => candidates,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => candidates,
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(io::Error::other)??;
|
||||
Ok(tokio::spawn(async move {
|
||||
processor.restore_daemon_threads(candidates).await;
|
||||
}))
|
||||
}
|
||||
111
codex-rs/app-server/src/dynamic_tools.rs
Normal file
111
codex-rs/app-server/src/dynamic_tools.rs
Normal file
@@ -0,0 +1,111 @@
|
||||
use codex_app_server_protocol::DynamicToolCallOutputContentItem;
|
||||
use codex_app_server_protocol::DynamicToolCallResponse;
|
||||
use codex_core::CodexThread;
|
||||
use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem as CoreDynamicToolCallOutputContentItem;
|
||||
use codex_protocol::dynamic_tools::DynamicToolResponse as CoreDynamicToolResponse;
|
||||
use codex_protocol::protocol::Op;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::oneshot;
|
||||
use tracing::error;
|
||||
|
||||
use crate::image_url::REMOTE_IMAGE_URL_ERROR;
|
||||
use crate::image_url::is_remote_image_url;
|
||||
use crate::outgoing_message::ClientRequestResult;
|
||||
use crate::server_request_error::is_turn_transition_server_request_error;
|
||||
|
||||
const INVALID_AUDIO_URL_ERROR: &str = "audio URLs must use an inline data URL";
|
||||
|
||||
pub(crate) async fn on_call_response(
|
||||
call_id: String,
|
||||
receiver: oneshot::Receiver<ClientRequestResult>,
|
||||
conversation: Arc<CodexThread>,
|
||||
) {
|
||||
let response = receiver.await;
|
||||
let (response, _error) = match response {
|
||||
Ok(Ok(value)) => decode_response(value),
|
||||
Ok(Err(err)) if is_turn_transition_server_request_error(&err) => return,
|
||||
Ok(Err(err)) => {
|
||||
error!("request failed with client error: {err:?}");
|
||||
fallback_response("dynamic tool request failed")
|
||||
}
|
||||
Err(err) => {
|
||||
error!("request failed: {err:?}");
|
||||
fallback_response("dynamic tool request failed")
|
||||
}
|
||||
};
|
||||
|
||||
let DynamicToolCallResponse {
|
||||
content_items,
|
||||
success,
|
||||
} = response.clone();
|
||||
let core_response = CoreDynamicToolResponse {
|
||||
content_items: content_items
|
||||
.into_iter()
|
||||
.map(CoreDynamicToolCallOutputContentItem::from)
|
||||
.collect(),
|
||||
success,
|
||||
};
|
||||
if let Err(err) = conversation
|
||||
.submit(Op::DynamicToolResponse {
|
||||
id: call_id.clone(),
|
||||
response: core_response,
|
||||
})
|
||||
.await
|
||||
{
|
||||
error!("failed to submit DynamicToolResponse: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_response(value: serde_json::Value) -> (DynamicToolCallResponse, Option<String>) {
|
||||
match serde_json::from_value::<DynamicToolCallResponse>(value) {
|
||||
Ok(response)
|
||||
if response.content_items.iter().any(|item| {
|
||||
matches!(
|
||||
item,
|
||||
DynamicToolCallOutputContentItem::InputImage { image_url }
|
||||
if is_remote_image_url(image_url)
|
||||
)
|
||||
}) =>
|
||||
{
|
||||
error!(
|
||||
message = REMOTE_IMAGE_URL_ERROR,
|
||||
"dynamic tool response was invalid"
|
||||
);
|
||||
fallback_response(REMOTE_IMAGE_URL_ERROR)
|
||||
}
|
||||
Ok(response)
|
||||
if response.content_items.iter().any(|item| {
|
||||
matches!(
|
||||
item,
|
||||
DynamicToolCallOutputContentItem::InputAudio { audio_url }
|
||||
if !audio_url
|
||||
.get(.."data:".len())
|
||||
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("data:"))
|
||||
)
|
||||
}) =>
|
||||
{
|
||||
error!(
|
||||
message = INVALID_AUDIO_URL_ERROR,
|
||||
"dynamic tool response was invalid"
|
||||
);
|
||||
fallback_response(INVALID_AUDIO_URL_ERROR)
|
||||
}
|
||||
Ok(response) => (response, None),
|
||||
Err(err) => {
|
||||
error!("failed to deserialize DynamicToolCallResponse: {err}");
|
||||
fallback_response("dynamic tool response was invalid")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fallback_response(message: &str) -> (DynamicToolCallResponse, Option<String>) {
|
||||
(
|
||||
DynamicToolCallResponse {
|
||||
content_items: vec![DynamicToolCallOutputContentItem::InputText {
|
||||
text: message.to_string(),
|
||||
}],
|
||||
success: false,
|
||||
},
|
||||
Some(message.to_string()),
|
||||
)
|
||||
}
|
||||
177
codex-rs/app-server/src/effective_plugin_change.rs
Normal file
177
codex-rs/app-server/src/effective_plugin_change.rs
Normal file
@@ -0,0 +1,177 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_app_server_protocol::ConfigBatchWriteParams;
|
||||
use codex_app_server_protocol::ConfigEdit;
|
||||
use codex_app_server_protocol::MergeStrategy;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core_plugins::EffectivePluginsChange;
|
||||
use codex_core_plugins::remote::RemotePluginMaterialization;
|
||||
use codex_core_plugins::remote::RemotePluginScope;
|
||||
use codex_core_plugins::remote::RemotePluginShareDiscoverability;
|
||||
use codex_login::AuthManager;
|
||||
use serde_json::json;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::request_processors::ConfigRequestProcessor;
|
||||
use crate::request_serialization::RequestSerializationAccess;
|
||||
use crate::request_serialization::RequestSerializationQueueKey;
|
||||
use crate::request_serialization::RequestSerializationQueues;
|
||||
|
||||
/// Refresh plugin consumers and trust hooks from newly materialized Workspace + Listed bundles.
|
||||
pub(crate) fn effective_plugins_changed_callback(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config_manager: ConfigManager,
|
||||
config_processor: ConfigRequestProcessor,
|
||||
request_serialization_queues: RequestSerializationQueues,
|
||||
) -> Arc<dyn Fn(EffectivePluginsChange) + Send + Sync> {
|
||||
Arc::new(move |change| {
|
||||
thread_manager.plugins_manager().clear_cache();
|
||||
thread_manager.skills_service().clear_cache();
|
||||
|
||||
let refresh_thread_manager = Arc::clone(&thread_manager);
|
||||
tokio::spawn(async move {
|
||||
refresh_thread_manager.invalidate_mcp_runtimes().await;
|
||||
refresh_thread_manager.refresh_hook_runtimes().await;
|
||||
});
|
||||
|
||||
if change.materialized_remote_plugins.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let trust_auth_manager = Arc::clone(&auth_manager);
|
||||
let trust_thread_manager = Arc::clone(&thread_manager);
|
||||
let trust_config_manager = config_manager.clone();
|
||||
let trust_config_processor = config_processor.clone();
|
||||
let trust_request_serialization_queues = request_serialization_queues.clone();
|
||||
tokio::spawn(async move {
|
||||
trust_request_serialization_queues
|
||||
.enqueue_background(
|
||||
RequestSerializationQueueKey::Global("config"),
|
||||
RequestSerializationAccess::Exclusive,
|
||||
async move {
|
||||
if let Err(err) = trust_materialized_plugin_hooks(
|
||||
change.materialized_remote_plugins,
|
||||
&trust_auth_manager,
|
||||
&trust_thread_manager,
|
||||
&trust_config_manager,
|
||||
&trust_config_processor,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!(error = %err, "failed to trust materialized plugin hooks");
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
fn workspace_listed_plugin_ids(
|
||||
materializations: Vec<RemotePluginMaterialization>,
|
||||
current_account_id: &str,
|
||||
) -> BTreeSet<String> {
|
||||
materializations
|
||||
.into_iter()
|
||||
.filter(|plugin| {
|
||||
plugin.scope == RemotePluginScope::Workspace
|
||||
&& plugin.discoverability == Some(RemotePluginShareDiscoverability::Listed)
|
||||
&& plugin.authenticated_account_id.as_deref() == Some(current_account_id)
|
||||
})
|
||||
.map(|plugin| plugin.plugin_id.as_key())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn hook_trusted_hash_edit(hook_key: &str, current_hash: &str) -> ConfigEdit {
|
||||
let escaped_hook_key = hook_key.replace('\\', "\\\\").replace('"', "\\\"");
|
||||
ConfigEdit {
|
||||
key_path: format!(r#"hooks.state."{escaped_hook_key}".trusted_hash"#),
|
||||
value: json!(current_hash),
|
||||
merge_strategy: MergeStrategy::Replace,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn trust_materialized_plugin_hooks(
|
||||
materializations: Vec<RemotePluginMaterialization>,
|
||||
auth_manager: &AuthManager,
|
||||
thread_manager: &ThreadManager,
|
||||
config_manager: &ConfigManager,
|
||||
config_processor: &ConfigRequestProcessor,
|
||||
) -> Result<(), String> {
|
||||
let Some(current_account_id) = auth_manager
|
||||
.auth_cached()
|
||||
.and_then(|auth| auth.get_account_id())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let plugin_ids = workspace_listed_plugin_ids(materializations, ¤t_account_id);
|
||||
if plugin_ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let config = config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| format!("failed to reload config: {err}"))?;
|
||||
let plugin_outcome = thread_manager
|
||||
.plugins_manager()
|
||||
.plugins_for_config(&config.plugins_config_input())
|
||||
.await;
|
||||
let hooks_config = codex_hooks::HooksConfig {
|
||||
feature_enabled: true,
|
||||
bypass_hook_trust: config.bypass_hook_trust,
|
||||
config_layer_stack: Some(config.config_layer_stack),
|
||||
plugin_hook_sources: plugin_outcome.effective_plugin_hook_sources(),
|
||||
plugin_hook_load_warnings: plugin_outcome.effective_plugin_hook_warnings(),
|
||||
..Default::default()
|
||||
};
|
||||
let hooks = tokio::task::spawn_blocking(move || codex_hooks::list_hooks(hooks_config))
|
||||
.await
|
||||
.map_err(|err| format!("hook discovery task failed: {err}"))?;
|
||||
if !hooks.warnings.is_empty() {
|
||||
warn!(
|
||||
warnings = ?hooks.warnings,
|
||||
"hook discovery reported warnings while trusting materialized plugins"
|
||||
);
|
||||
}
|
||||
let edits = hooks
|
||||
.hooks
|
||||
.into_iter()
|
||||
.filter(|hook| {
|
||||
hook.plugin_id
|
||||
.as_ref()
|
||||
.is_some_and(|plugin_id| plugin_ids.contains(plugin_id))
|
||||
})
|
||||
.map(|hook| hook_trusted_hash_edit(&hook.key, &hook.current_hash))
|
||||
.collect::<Vec<_>>();
|
||||
if edits.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if auth_manager
|
||||
.auth_cached()
|
||||
.and_then(|auth| auth.get_account_id())
|
||||
.as_deref()
|
||||
!= Some(current_account_id.as_str())
|
||||
{
|
||||
warn!("skipping materialized plugin hook trust after account changed");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let params = ConfigBatchWriteParams {
|
||||
edits,
|
||||
file_path: None,
|
||||
expected_version: None,
|
||||
reload_user_config: true,
|
||||
};
|
||||
config_processor
|
||||
.batch_write(params)
|
||||
.await
|
||||
.map_err(|err| format!("failed to write hook trust: {}", err.message))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "effective_plugin_change_tests.rs"]
|
||||
mod tests;
|
||||
63
codex-rs/app-server/src/effective_plugin_change_tests.rs
Normal file
63
codex-rs/app-server/src/effective_plugin_change_tests.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use super::*;
|
||||
use codex_plugin::PluginId;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn only_workspace_listed_materializations_are_eligible() {
|
||||
let materialization =
|
||||
|name: &str,
|
||||
scope: RemotePluginScope,
|
||||
discoverability: Option<RemotePluginShareDiscoverability>| {
|
||||
RemotePluginMaterialization {
|
||||
plugin_id: PluginId::new(name.to_string(), "test".to_string())
|
||||
.expect("valid plugin id"),
|
||||
scope,
|
||||
discoverability,
|
||||
authenticated_account_id: Some("account-123".to_string()),
|
||||
}
|
||||
};
|
||||
|
||||
let mut materializations = vec![
|
||||
materialization(
|
||||
"eligible",
|
||||
RemotePluginScope::Workspace,
|
||||
Some(RemotePluginShareDiscoverability::Listed),
|
||||
),
|
||||
materialization(
|
||||
"unlisted",
|
||||
RemotePluginScope::Workspace,
|
||||
Some(RemotePluginShareDiscoverability::Unlisted),
|
||||
),
|
||||
materialization(
|
||||
"private",
|
||||
RemotePluginScope::Workspace,
|
||||
Some(RemotePluginShareDiscoverability::Private),
|
||||
),
|
||||
materialization("workspace-missing", RemotePluginScope::Workspace, None),
|
||||
materialization("global", RemotePluginScope::Global, None),
|
||||
materialization("user", RemotePluginScope::User, None),
|
||||
];
|
||||
let mut wrong_account = materialization(
|
||||
"wrong-account",
|
||||
RemotePluginScope::Workspace,
|
||||
Some(RemotePluginShareDiscoverability::Listed),
|
||||
);
|
||||
wrong_account.authenticated_account_id = Some("account-456".to_string());
|
||||
materializations.push(wrong_account);
|
||||
|
||||
let plugin_ids = workspace_listed_plugin_ids(materializations, "account-123");
|
||||
|
||||
assert_eq!(plugin_ids, BTreeSet::from(["eligible@test".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hook_trusted_hash_edit_targets_only_escaped_leaf() {
|
||||
assert_eq!(
|
||||
hook_trusted_hash_edit(r#"plugin."quoted"\path"#, "sha256:current"),
|
||||
ConfigEdit {
|
||||
key_path: r#"hooks.state."plugin.\"quoted\"\\path".trusted_hash"#.to_string(),
|
||||
value: serde_json::json!("sha256:current"),
|
||||
merge_strategy: MergeStrategy::Replace,
|
||||
}
|
||||
);
|
||||
}
|
||||
38
codex-rs/app-server/src/error_code.rs
Normal file
38
codex-rs/app-server/src/error_code.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
|
||||
pub(crate) const INVALID_REQUEST_ERROR_CODE: i64 = -32600;
|
||||
pub(crate) const METHOD_NOT_FOUND_ERROR_CODE: i64 = -32601;
|
||||
pub const INVALID_PARAMS_ERROR_CODE: i64 = -32602;
|
||||
pub(crate) const INTERNAL_ERROR_CODE: i64 = -32603;
|
||||
pub(crate) const OVERLOADED_ERROR_CODE: i64 = -32001;
|
||||
pub const INPUT_TOO_LARGE_ERROR_CODE: &str = "input_too_large";
|
||||
|
||||
pub(crate) fn server_draining_error() -> JSONRPCErrorError {
|
||||
let mut error = invalid_request("Server is draining; retry after reconnecting");
|
||||
error.data = Some(serde_json::json!({ "reason": "serverShuttingDown" }));
|
||||
error
|
||||
}
|
||||
|
||||
pub(crate) fn invalid_request(message: impl Into<String>) -> JSONRPCErrorError {
|
||||
error(INVALID_REQUEST_ERROR_CODE, message)
|
||||
}
|
||||
|
||||
pub(crate) fn method_not_found(message: impl Into<String>) -> JSONRPCErrorError {
|
||||
error(METHOD_NOT_FOUND_ERROR_CODE, message)
|
||||
}
|
||||
|
||||
pub(crate) fn invalid_params(message: impl Into<String>) -> JSONRPCErrorError {
|
||||
error(INVALID_PARAMS_ERROR_CODE, message)
|
||||
}
|
||||
|
||||
pub(crate) fn internal_error(message: impl Into<String>) -> JSONRPCErrorError {
|
||||
error(INTERNAL_ERROR_CODE, message)
|
||||
}
|
||||
|
||||
fn error(code: i64, message: impl Into<String>) -> JSONRPCErrorError {
|
||||
JSONRPCErrorError {
|
||||
code,
|
||||
message: message.into(),
|
||||
data: None,
|
||||
}
|
||||
}
|
||||
626
codex-rs/app-server/src/extensions.rs
Normal file
626
codex-rs/app-server/src/extensions.rs
Normal file
@@ -0,0 +1,626 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadGoal;
|
||||
use codex_app_server_protocol::ThreadGoalUpdatedNotification;
|
||||
use codex_app_server_protocol::ThreadQueueChangedNotification;
|
||||
use codex_app_server_protocol::WarningNotification;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_extension_api::ExtensionEventSink;
|
||||
use codex_extension_api::ExtensionRegistry;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::ExtensionWarning;
|
||||
use codex_extension_api::TurnStartAdmission;
|
||||
use codex_goal_extension::GoalExtensionConfig;
|
||||
use codex_goal_extension::GoalService;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AuthManager;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::Event;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_queue_extension::QueuedItemService;
|
||||
use codex_rollout::state_db::StateDbHandle;
|
||||
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use crate::outgoing_message::ThreadScopedOutgoingMessageSender;
|
||||
use crate::thread_state::ThreadListenerCommand;
|
||||
use crate::thread_state::ThreadStateManager;
|
||||
|
||||
pub(crate) struct ThreadExtensionDependencies {
|
||||
pub(crate) sample_responses: Arc<crate::thread_sample::SampleResponseRegistry>,
|
||||
pub(crate) event_sink: Arc<dyn ExtensionEventSink>,
|
||||
pub(crate) auth_manager: Arc<AuthManager>,
|
||||
pub(crate) state_db: Option<StateDbHandle>,
|
||||
pub(crate) analytics_events_client: AnalyticsEventsClient,
|
||||
pub(crate) thread_manager: Weak<ThreadManager>,
|
||||
pub(crate) goal_service: Arc<GoalService>,
|
||||
pub(crate) environment_manager: Arc<EnvironmentManager>,
|
||||
pub(crate) executor_skill_provider: Arc<dyn codex_skills_extension::SkillProvider>,
|
||||
pub(crate) cloud_skill_provider: Option<Arc<dyn codex_skills_extension::SkillProvider>>,
|
||||
pub(crate) git_attribution_base_url: String,
|
||||
pub(crate) http_client_factory: HttpClientFactory,
|
||||
/// Process-scoped queue shared by idle dispatch and app-server requests.
|
||||
pub(crate) queue_service: Option<Arc<QueuedItemService>>,
|
||||
pub(crate) turn_start_admission: Option<Arc<dyn TurnStartAdmission>>,
|
||||
}
|
||||
|
||||
pub(crate) fn thread_extensions(
|
||||
config: &Config,
|
||||
dependencies: ThreadExtensionDependencies,
|
||||
) -> Arc<ExtensionRegistry<Config>> {
|
||||
let ThreadExtensionDependencies {
|
||||
sample_responses,
|
||||
event_sink,
|
||||
auth_manager,
|
||||
state_db,
|
||||
analytics_events_client,
|
||||
thread_manager,
|
||||
goal_service,
|
||||
environment_manager,
|
||||
executor_skill_provider,
|
||||
cloud_skill_provider,
|
||||
git_attribution_base_url,
|
||||
http_client_factory,
|
||||
queue_service,
|
||||
turn_start_admission,
|
||||
} = dependencies;
|
||||
let mut builder = ExtensionRegistryBuilder::<Config>::with_event_sink(Arc::clone(&event_sink));
|
||||
if config
|
||||
.features
|
||||
.enabled(codex_features::Feature::MultiEnvCopyFile)
|
||||
{
|
||||
codex_multi_env_copy_file::install(&mut builder);
|
||||
}
|
||||
if let Some(admission) = turn_start_admission {
|
||||
builder.turn_start_admission(admission);
|
||||
}
|
||||
if let Some(queue_service) = queue_service {
|
||||
codex_queue_extension::install(&mut builder, queue_service);
|
||||
}
|
||||
codex_history_notes_extension::install(&mut builder, auth_manager.clone());
|
||||
crate::install_agent_message_board(&mut builder, thread_manager.clone());
|
||||
if let Some(state_db) = state_db {
|
||||
codex_goal_extension::install_with_backend(
|
||||
&mut builder,
|
||||
state_db,
|
||||
analytics_events_client,
|
||||
codex_otel::global(),
|
||||
thread_manager.clone(),
|
||||
goal_service,
|
||||
|config: &Config| GoalExtensionConfig {
|
||||
enabled: config.features.enabled(codex_features::Feature::Goals),
|
||||
max_goal_token_budget: config.max_goal_token_budget,
|
||||
},
|
||||
);
|
||||
}
|
||||
codex_git_attribution::install(
|
||||
&mut builder,
|
||||
auth_manager.clone(),
|
||||
git_attribution_base_url,
|
||||
http_client_factory,
|
||||
);
|
||||
codex_guardian_v2::install(&mut builder, auth_manager.clone(), thread_manager);
|
||||
codex_memories_extension::install(&mut builder, codex_otel::global());
|
||||
codex_mcp_extension::install(&mut builder);
|
||||
codex_mcp_extension::install_plugins(&mut builder, environment_manager);
|
||||
codex_web_search_extension::install(&mut builder, auth_manager.clone());
|
||||
codex_image_generation_extension::install(&mut builder, auth_manager, |config: &Config| {
|
||||
Some(config.codex_home.clone())
|
||||
});
|
||||
let mut skill_providers = codex_skills_extension::SkillProviders::new()
|
||||
.with_executor_provider(executor_skill_provider)
|
||||
.with_host_provider(Arc::new(codex_skills_extension::HostSkillProvider::new()));
|
||||
if let Some(provider) = cloud_skill_provider {
|
||||
skill_providers = skill_providers.with_cloud_provider(provider);
|
||||
}
|
||||
codex_skills_extension::install_with_providers_and_metrics(
|
||||
&mut builder,
|
||||
skill_providers,
|
||||
codex_otel::global(),
|
||||
|config: &Config| codex_skills_extension::SkillsExtensionConfig {
|
||||
include_instructions: config.include_skill_instructions,
|
||||
catalog_deltas_enabled: config
|
||||
.features
|
||||
.enabled(codex_features::Feature::SkillCatalogDeltas),
|
||||
omit_descriptions: config
|
||||
.features
|
||||
.enabled(codex_features::Feature::OmitSkillDescriptions),
|
||||
max_context_tokens: config.skill_max_context_tokens,
|
||||
bundled_skills_enabled: config.bundled_skills_enabled(),
|
||||
cloud_skill_enabled: config.cloud_skill_enabled,
|
||||
shadow_selection_enabled: config
|
||||
.features
|
||||
.enabled(codex_features::Feature::SkillSearch),
|
||||
},
|
||||
);
|
||||
builder.model_request_contributor(sample_responses);
|
||||
Arc::new(builder.build())
|
||||
}
|
||||
|
||||
pub(crate) fn app_server_extension_event_sink(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
thread_state_manager: ThreadStateManager,
|
||||
) -> Arc<dyn ExtensionEventSink> {
|
||||
Arc::new(AppServerExtensionEventSink {
|
||||
outgoing,
|
||||
thread_state_manager,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn send_thread_warning(
|
||||
outgoing: &Arc<OutgoingMessageSender>,
|
||||
thread_state_manager: &ThreadStateManager,
|
||||
thread_id: ThreadId,
|
||||
message: String,
|
||||
) {
|
||||
let subscribed_connection_ids = thread_state_manager
|
||||
.subscribed_connection_ids(thread_id)
|
||||
.await;
|
||||
let thread_outgoing = ThreadScopedOutgoingMessageSender::new(
|
||||
Arc::clone(outgoing),
|
||||
subscribed_connection_ids,
|
||||
thread_id,
|
||||
);
|
||||
thread_outgoing
|
||||
.send_server_notification(ServerNotification::Warning(WarningNotification {
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
message,
|
||||
}))
|
||||
.await;
|
||||
}
|
||||
|
||||
struct AppServerExtensionEventSink {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
thread_state_manager: ThreadStateManager,
|
||||
}
|
||||
|
||||
const MAX_EXTENSION_WARNING_BYTES: usize = 256;
|
||||
const EXTENSION_WARNING_SUBSCRIBER_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
impl ExtensionEventSink for AppServerExtensionEventSink {
|
||||
fn emit(&self, event: Event) {
|
||||
match event.msg {
|
||||
EventMsg::ThreadQueueChanged(queue_event) => {
|
||||
let thread_id = queue_event.thread_id;
|
||||
if let Some(listener_command_tx) = self
|
||||
.thread_state_manager
|
||||
.current_listener_command_tx(thread_id)
|
||||
{
|
||||
let command = ThreadListenerCommand::EmitThreadQueueChanged;
|
||||
if listener_command_tx.send(command).is_ok() {
|
||||
return;
|
||||
}
|
||||
tracing::warn!(
|
||||
"failed to enqueue extension queue update for {thread_id}: listener command channel is closed"
|
||||
);
|
||||
}
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let thread_state_manager = self.thread_state_manager.clone();
|
||||
tokio::spawn(async move {
|
||||
let subscribed_connection_ids = thread_state_manager
|
||||
.subscribed_connection_ids(thread_id)
|
||||
.await;
|
||||
let outgoing = ThreadScopedOutgoingMessageSender::new(
|
||||
outgoing,
|
||||
subscribed_connection_ids,
|
||||
thread_id,
|
||||
);
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::ThreadQueueChanged(
|
||||
ThreadQueueChangedNotification {
|
||||
thread_id: thread_id.to_string(),
|
||||
},
|
||||
))
|
||||
.await;
|
||||
});
|
||||
}
|
||||
EventMsg::ThreadGoalUpdated(thread_goal_event) => {
|
||||
let thread_id = thread_goal_event.thread_id;
|
||||
let turn_id = thread_goal_event.turn_id;
|
||||
let goal: ThreadGoal = thread_goal_event.goal.into();
|
||||
if let Some(listener_command_tx) = self
|
||||
.thread_state_manager
|
||||
.current_listener_command_tx(thread_id)
|
||||
{
|
||||
let command = ThreadListenerCommand::EmitThreadGoalUpdated {
|
||||
turn_id: turn_id.clone(),
|
||||
goal: goal.clone(),
|
||||
};
|
||||
if listener_command_tx.send(command).is_ok() {
|
||||
return;
|
||||
}
|
||||
tracing::warn!(
|
||||
"failed to enqueue extension goal update for {thread_id}: listener command channel is closed"
|
||||
);
|
||||
}
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
tokio::spawn(async move {
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::ThreadGoalUpdated(
|
||||
ThreadGoalUpdatedNotification {
|
||||
thread_id: thread_id.to_string(),
|
||||
turn_id,
|
||||
goal,
|
||||
},
|
||||
))
|
||||
.await;
|
||||
});
|
||||
}
|
||||
msg => {
|
||||
tracing::debug!(event_id = %event.id, ?msg, "dropping unsupported extension event");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_warning(&self, warning: ExtensionWarning) {
|
||||
let ExtensionWarning {
|
||||
thread_id,
|
||||
turn_id: _,
|
||||
message,
|
||||
} = warning;
|
||||
let Ok(thread_id) = ThreadId::from_string(&thread_id) else {
|
||||
tracing::warn!(
|
||||
%thread_id,
|
||||
"dropping extension warning with invalid thread id"
|
||||
);
|
||||
return;
|
||||
};
|
||||
let mut message = message;
|
||||
if message.len() > MAX_EXTENSION_WARNING_BYTES {
|
||||
let mut truncate_at = MAX_EXTENSION_WARNING_BYTES;
|
||||
while !message.is_char_boundary(truncate_at) {
|
||||
truncate_at -= 1;
|
||||
}
|
||||
message.truncate(truncate_at);
|
||||
}
|
||||
if let Some(listener_command_tx) = self
|
||||
.thread_state_manager
|
||||
.current_listener_command_tx(thread_id)
|
||||
{
|
||||
let command = ThreadListenerCommand::EmitWarning {
|
||||
message: message.clone(),
|
||||
};
|
||||
if listener_command_tx.send(command).is_ok() {
|
||||
return;
|
||||
}
|
||||
tracing::warn!(
|
||||
"failed to enqueue extension warning for {thread_id}: listener command channel is closed"
|
||||
);
|
||||
}
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let thread_state_manager = self.thread_state_manager.clone();
|
||||
tokio::spawn(async move {
|
||||
if tokio::time::timeout(
|
||||
EXTENSION_WARNING_SUBSCRIBER_TIMEOUT,
|
||||
thread_state_manager.wait_for_thread_subscriber(thread_id),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!(
|
||||
%thread_id,
|
||||
timeout_secs = EXTENSION_WARNING_SUBSCRIBER_TIMEOUT.as_secs(),
|
||||
"dropping extension warning after waiting for a thread subscriber"
|
||||
);
|
||||
return;
|
||||
}
|
||||
send_thread_warning(&outgoing, &thread_state_manager, thread_id, message).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use codex_protocol::protocol::ThreadGoal as CoreThreadGoal;
|
||||
use codex_protocol::protocol::ThreadGoalStatus;
|
||||
use codex_protocol::protocol::ThreadGoalUpdatedEvent;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::OutgoingEnvelope;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use crate::thread_state::ConnectionCapabilities;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_server_event_sink_uses_listener_fifo_for_goal_updates_warnings_and_clears() {
|
||||
let (outgoing_tx, _outgoing_rx) = mpsc::channel(4);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
outgoing_tx,
|
||||
AnalyticsEventsClient::disabled(),
|
||||
));
|
||||
let thread_state_manager = ThreadStateManager::new();
|
||||
let thread_id = ThreadId::default();
|
||||
let (listener_command_tx, mut listener_command_rx) = mpsc::unbounded_channel();
|
||||
thread_state_manager.register_listener_command_tx(thread_id, listener_command_tx.clone());
|
||||
let sink = app_server_extension_event_sink(outgoing, thread_state_manager);
|
||||
|
||||
sink.emit(thread_goal_updated_event(thread_id, "turn-1"));
|
||||
sink.emit_warning(ExtensionWarning {
|
||||
thread_id: thread_id.to_string(),
|
||||
turn_id: Some("turn-warning".to_string()),
|
||||
message: "catalog was shortened".to_string(),
|
||||
});
|
||||
sink.emit(thread_goal_updated_event(thread_id, "turn-2"));
|
||||
listener_command_tx
|
||||
.send(ThreadListenerCommand::EmitThreadGoalCleared)
|
||||
.expect("listener command channel should be open");
|
||||
|
||||
let mut observed = Vec::new();
|
||||
for _ in 0..4 {
|
||||
let command = timeout(Duration::from_secs(1), listener_command_rx.recv())
|
||||
.await
|
||||
.expect("timed out waiting for listener command")
|
||||
.expect("listener command channel closed unexpectedly");
|
||||
match command {
|
||||
ThreadListenerCommand::EmitThreadGoalUpdated { turn_id, .. } => {
|
||||
observed.push(turn_id.expect("extension goal updates should include turn ids"));
|
||||
}
|
||||
ThreadListenerCommand::EmitWarning { message } => observed.push(message),
|
||||
ThreadListenerCommand::EmitThreadGoalCleared => {
|
||||
observed.push("cleared".to_string())
|
||||
}
|
||||
_ => panic!("unexpected listener command"),
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
vec![
|
||||
"turn-1".to_string(),
|
||||
"catalog was shortened".to_string(),
|
||||
"turn-2".to_string(),
|
||||
"cleared".to_string()
|
||||
],
|
||||
observed
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_server_event_sink_truncates_warning_before_listener_enqueue() {
|
||||
let (outgoing_tx, _outgoing_rx) = mpsc::channel(4);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
outgoing_tx,
|
||||
AnalyticsEventsClient::disabled(),
|
||||
));
|
||||
let thread_state_manager = ThreadStateManager::new();
|
||||
let thread_id = ThreadId::default();
|
||||
let (listener_command_tx, mut listener_command_rx) = mpsc::unbounded_channel();
|
||||
thread_state_manager.register_listener_command_tx(thread_id, listener_command_tx);
|
||||
let sink = app_server_extension_event_sink(outgoing, thread_state_manager);
|
||||
|
||||
sink.emit_warning(ExtensionWarning {
|
||||
thread_id: thread_id.to_string(),
|
||||
turn_id: Some("turn-warning".to_string()),
|
||||
message: "🙂".repeat(65),
|
||||
});
|
||||
|
||||
let command = timeout(Duration::from_secs(1), listener_command_rx.recv())
|
||||
.await
|
||||
.expect("timed out waiting for listener command")
|
||||
.expect("listener command channel closed unexpectedly");
|
||||
let ThreadListenerCommand::EmitWarning { message } = command else {
|
||||
panic!("expected warning listener command");
|
||||
};
|
||||
assert_eq!(message, "🙂".repeat(64));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_server_event_sink_targets_subscriber_without_listener() {
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(4);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
outgoing_tx,
|
||||
AnalyticsEventsClient::disabled(),
|
||||
));
|
||||
let thread_id = ThreadId::new();
|
||||
let subscribed_connection = ConnectionId(1);
|
||||
let unrelated_connection = ConnectionId(2);
|
||||
let thread_state_manager = ThreadStateManager::new();
|
||||
for connection_id in [subscribed_connection, unrelated_connection] {
|
||||
thread_state_manager
|
||||
.connection_initialized(connection_id, ConnectionCapabilities::default())
|
||||
.await;
|
||||
}
|
||||
assert!(
|
||||
thread_state_manager
|
||||
.try_add_connection_to_thread(thread_id, subscribed_connection)
|
||||
.await,
|
||||
"connection should be subscribed"
|
||||
);
|
||||
let sink = app_server_extension_event_sink(outgoing, thread_state_manager);
|
||||
|
||||
sink.emit_warning(ExtensionWarning {
|
||||
thread_id: thread_id.to_string(),
|
||||
turn_id: Some("turn-1".to_string()),
|
||||
message: "catalog was shortened".to_string(),
|
||||
});
|
||||
|
||||
let envelope = timeout(Duration::from_secs(1), outgoing_rx.recv())
|
||||
.await
|
||||
.expect("timed out waiting for warning notification")
|
||||
.expect("outgoing channel closed unexpectedly");
|
||||
let OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message,
|
||||
write_complete_tx: _,
|
||||
} = envelope
|
||||
else {
|
||||
panic!("expected connection-targeted warning notification");
|
||||
};
|
||||
assert_eq!(connection_id, subscribed_connection);
|
||||
let OutgoingMessage::AppServerNotification(envelope) = message else {
|
||||
panic!("expected app-server warning notification");
|
||||
};
|
||||
let ServerNotification::Warning(notification) = envelope.notification else {
|
||||
panic!("expected warning notification");
|
||||
};
|
||||
assert_eq!(
|
||||
notification,
|
||||
WarningNotification {
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
message: "catalog was shortened".to_string(),
|
||||
}
|
||||
);
|
||||
assert!(outgoing_rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_server_event_sink_waits_for_subscriber_without_listener() {
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(4);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
outgoing_tx,
|
||||
AnalyticsEventsClient::disabled(),
|
||||
));
|
||||
let thread_id = ThreadId::new();
|
||||
let subscribed_connection = ConnectionId(1);
|
||||
let thread_state_manager = ThreadStateManager::new();
|
||||
thread_state_manager
|
||||
.connection_initialized(subscribed_connection, ConnectionCapabilities::default())
|
||||
.await;
|
||||
let sink = app_server_extension_event_sink(outgoing, thread_state_manager.clone());
|
||||
|
||||
sink.emit_warning(ExtensionWarning {
|
||||
thread_id: thread_id.to_string(),
|
||||
turn_id: Some("turn-1".to_string()),
|
||||
message: "catalog was shortened".to_string(),
|
||||
});
|
||||
tokio::task::yield_now().await;
|
||||
assert!(
|
||||
thread_state_manager
|
||||
.try_add_connection_to_thread(thread_id, subscribed_connection)
|
||||
.await,
|
||||
"connection should be subscribed"
|
||||
);
|
||||
|
||||
let envelope = timeout(Duration::from_secs(1), outgoing_rx.recv())
|
||||
.await
|
||||
.expect("timed out waiting for warning notification")
|
||||
.expect("outgoing channel closed unexpectedly");
|
||||
let OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message,
|
||||
write_complete_tx: _,
|
||||
} = envelope
|
||||
else {
|
||||
panic!("expected connection-targeted warning notification");
|
||||
};
|
||||
assert_eq!(connection_id, subscribed_connection);
|
||||
let OutgoingMessage::AppServerNotification(envelope) = message else {
|
||||
panic!("expected app-server warning notification");
|
||||
};
|
||||
let ServerNotification::Warning(notification) = envelope.notification else {
|
||||
panic!("expected warning notification");
|
||||
};
|
||||
assert_eq!(
|
||||
notification,
|
||||
WarningNotification {
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
message: "catalog was shortened".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_server_event_sink_targets_subscriber_after_listener_closes() {
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(4);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
outgoing_tx,
|
||||
AnalyticsEventsClient::disabled(),
|
||||
));
|
||||
let thread_id = ThreadId::new();
|
||||
let subscribed_connection = ConnectionId(1);
|
||||
let thread_state_manager = ThreadStateManager::new();
|
||||
thread_state_manager
|
||||
.connection_initialized(subscribed_connection, ConnectionCapabilities::default())
|
||||
.await;
|
||||
assert!(
|
||||
thread_state_manager
|
||||
.try_add_connection_to_thread(thread_id, subscribed_connection)
|
||||
.await,
|
||||
"connection should be subscribed"
|
||||
);
|
||||
let (listener_command_tx, listener_command_rx) = mpsc::unbounded_channel();
|
||||
drop(listener_command_rx);
|
||||
thread_state_manager.register_listener_command_tx(thread_id, listener_command_tx);
|
||||
let sink = app_server_extension_event_sink(outgoing, thread_state_manager);
|
||||
|
||||
sink.emit_warning(ExtensionWarning {
|
||||
thread_id: thread_id.to_string(),
|
||||
turn_id: Some("turn-1".to_string()),
|
||||
message: "catalog was shortened".to_string(),
|
||||
});
|
||||
|
||||
let envelope = timeout(Duration::from_secs(1), outgoing_rx.recv())
|
||||
.await
|
||||
.expect("timed out waiting for warning notification")
|
||||
.expect("outgoing channel closed unexpectedly");
|
||||
let OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message,
|
||||
write_complete_tx: _,
|
||||
} = envelope
|
||||
else {
|
||||
panic!("expected connection-targeted warning notification");
|
||||
};
|
||||
assert_eq!(connection_id, subscribed_connection);
|
||||
let OutgoingMessage::AppServerNotification(envelope) = message else {
|
||||
panic!("expected app-server warning notification");
|
||||
};
|
||||
let ServerNotification::Warning(notification) = envelope.notification else {
|
||||
panic!("expected warning notification");
|
||||
};
|
||||
assert_eq!(
|
||||
notification,
|
||||
WarningNotification {
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
message: "catalog was shortened".to_string(),
|
||||
}
|
||||
);
|
||||
assert!(outgoing_rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_server_event_sink_drops_warning_with_invalid_thread_id() {
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(4);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
outgoing_tx,
|
||||
AnalyticsEventsClient::disabled(),
|
||||
));
|
||||
let sink = app_server_extension_event_sink(outgoing, ThreadStateManager::new());
|
||||
|
||||
sink.emit_warning(ExtensionWarning {
|
||||
thread_id: "not-a-thread-id".to_string(),
|
||||
turn_id: Some("turn-1".to_string()),
|
||||
message: "catalog was shortened".to_string(),
|
||||
});
|
||||
|
||||
assert!(outgoing_rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
fn thread_goal_updated_event(thread_id: ThreadId, turn_id: &str) -> Event {
|
||||
Event {
|
||||
id: turn_id.to_string(),
|
||||
msg: EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
|
||||
thread_id,
|
||||
turn_id: Some(turn_id.to_string()),
|
||||
goal: CoreThreadGoal {
|
||||
thread_id,
|
||||
objective: "wire extension events".to_string(),
|
||||
status: ThreadGoalStatus::Active,
|
||||
token_budget: Some(123),
|
||||
tokens_used: 45,
|
||||
time_used_seconds: 6,
|
||||
created_at: 7,
|
||||
updated_at: 8,
|
||||
},
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
6
codex-rs/app-server/src/external_agent_migration/mod.rs
Normal file
6
codex-rs/app-server/src/external_agent_migration/mod.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
mod processor;
|
||||
mod protocol;
|
||||
mod session_importer;
|
||||
|
||||
pub(crate) use processor::ExternalAgentConfigRequestProcessor;
|
||||
pub(crate) use processor::ExternalAgentConfigRequestProcessorArgs;
|
||||
795
codex-rs/app-server/src/external_agent_migration/processor.rs
Normal file
795
codex-rs/app-server/src/external_agent_migration/processor.rs
Normal file
@@ -0,0 +1,795 @@
|
||||
use codex_protocol::MemoryVersion;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::outgoing_message::ConnectionRequestId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use crate::request_processors::ConfigRequestProcessor;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::ExternalAgentConfigImportCompletedInput;
|
||||
use codex_analytics::ExternalAgentConfigImportFailureInput;
|
||||
use codex_app_server_protocol::ExternalAgentConfigDetectParams;
|
||||
use codex_app_server_protocol::ExternalAgentConfigDetectResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportHistoriesReadResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportHistoryRecordParams;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportHistoryRecordResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportItemTypeFailure as ProtocolImportFailure;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportItemTypeSuccess as ProtocolImportSuccess;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportParams;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportProgressNotification;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportTypeResult as ProtocolImportTypeResult;
|
||||
use codex_app_server_protocol::ExternalAgentConfigMigrationItem;
|
||||
use codex_app_server_protocol::ExternalAgentConfigMigrationItemType;
|
||||
use codex_app_server_protocol::ExternalAgentImportedConnectorCandidate;
|
||||
use codex_app_server_protocol::ExternalAgentImportedConnectorSource;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_external_agent_migration::DetectedConnectorCandidate;
|
||||
use codex_external_agent_migration::ExternalAgentConfigDetectOptions;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportItemResult as CoreImportItemResult;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportOutcome as CoreImportOutcome;
|
||||
use codex_external_agent_migration::ExternalAgentConfigMigrationItemType as CoreMigrationItemType;
|
||||
use codex_external_agent_migration::ExternalAgentConfigService;
|
||||
use codex_external_agent_migration::ExternalAgentSessionImportLimits;
|
||||
use codex_external_agent_migration::PluginImportOutcome;
|
||||
use codex_external_agent_migration::record_import_error;
|
||||
use codex_external_agent_migration::sessions::ExternalAgentSessionMigration as CoreSessionMigration;
|
||||
use codex_external_agent_migration::sessions::read_imported_connector_candidates;
|
||||
use codex_external_agent_migration::sessions::record_detected_session_connectors;
|
||||
use codex_features::Feature;
|
||||
use codex_rollout::StateDbHandle;
|
||||
use codex_state::ExternalAgentConfigImportFailureRecord;
|
||||
use codex_state::ExternalAgentConfigImportSuccessRecord;
|
||||
use codex_thread_store::ThreadStore;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::protocol::completed_notification;
|
||||
use super::protocol::core_migration_items;
|
||||
use super::protocol::detect_response;
|
||||
use super::protocol::protocol_import_history;
|
||||
use super::protocol::protocol_import_type_result;
|
||||
use super::session_importer::ExternalAgentSessionImporter;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ExternalAgentConfigRequestProcessor {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
migration_service: ExternalAgentConfigService,
|
||||
session_importer: ExternalAgentSessionImporter,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config_manager: ConfigManager,
|
||||
config_processor: ConfigRequestProcessor,
|
||||
state_db: Option<StateDbHandle>,
|
||||
analytics_events_client: AnalyticsEventsClient,
|
||||
}
|
||||
|
||||
pub(crate) struct ExternalAgentConfigRequestProcessorArgs {
|
||||
pub(crate) outgoing: Arc<OutgoingMessageSender>,
|
||||
pub(crate) thread_manager: Arc<ThreadManager>,
|
||||
pub(crate) thread_store: Arc<dyn ThreadStore>,
|
||||
pub(crate) config_manager: ConfigManager,
|
||||
pub(crate) config_processor: ConfigRequestProcessor,
|
||||
pub(crate) state_db: Option<StateDbHandle>,
|
||||
pub(crate) analytics_events_client: AnalyticsEventsClient,
|
||||
pub(crate) arg0_paths: Arg0DispatchPaths,
|
||||
pub(crate) codex_home: PathBuf,
|
||||
}
|
||||
|
||||
impl ExternalAgentConfigRequestProcessor {
|
||||
pub(crate) fn new(args: ExternalAgentConfigRequestProcessorArgs) -> Self {
|
||||
let ExternalAgentConfigRequestProcessorArgs {
|
||||
outgoing,
|
||||
thread_manager,
|
||||
thread_store,
|
||||
config_manager,
|
||||
config_processor,
|
||||
state_db,
|
||||
analytics_events_client,
|
||||
arg0_paths,
|
||||
codex_home,
|
||||
} = args;
|
||||
let migration_service = ExternalAgentConfigService::new(
|
||||
codex_home.clone(),
|
||||
thread_manager.auth_manager(),
|
||||
analytics_events_client.clone(),
|
||||
state_db.clone(),
|
||||
);
|
||||
let session_importer = ExternalAgentSessionImporter::new(
|
||||
codex_home,
|
||||
migration_service.connector_metadata_roots().to_vec(),
|
||||
Arc::clone(&thread_manager),
|
||||
thread_store,
|
||||
config_manager.clone(),
|
||||
arg0_paths,
|
||||
);
|
||||
Self {
|
||||
outgoing,
|
||||
migration_service,
|
||||
session_importer,
|
||||
thread_manager,
|
||||
config_manager,
|
||||
config_processor,
|
||||
state_db,
|
||||
analytics_events_client,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn detect(
|
||||
&self,
|
||||
params: ExternalAgentConfigDetectParams,
|
||||
) -> Result<ExternalAgentConfigDetectResponse, JSONRPCErrorError> {
|
||||
let (include_memory, memory_version) = self.memory_import_settings().await;
|
||||
let migration_service = self
|
||||
.migration_service
|
||||
.with_migration_source(params.migration_source.as_deref())
|
||||
.with_memory_version(memory_version);
|
||||
let default_session_import_limits = ExternalAgentSessionImportLimits::default();
|
||||
let migration_service =
|
||||
migration_service.with_session_import_limits(ExternalAgentSessionImportLimits {
|
||||
max_age: params
|
||||
.max_session_age_days
|
||||
.map(|days| Duration::from_secs(u64::from(days) * 24 * 60 * 60))
|
||||
.unwrap_or(default_session_import_limits.max_age),
|
||||
max_sessions: params
|
||||
.max_sessions
|
||||
.map(|max_sessions| max_sessions as usize)
|
||||
.unwrap_or(default_session_import_limits.max_sessions),
|
||||
});
|
||||
let options = ExternalAgentConfigDetectOptions {
|
||||
include_home: params.include_home,
|
||||
include_memory,
|
||||
cwds: params.cwds,
|
||||
};
|
||||
let items = migration_service
|
||||
.detect(options)
|
||||
.await
|
||||
.map_err(|err| internal_error(err.to_string()))?;
|
||||
let sessions = items
|
||||
.iter()
|
||||
.filter_map(|item| item.details.as_ref())
|
||||
.flat_map(|details| details.sessions.iter().cloned())
|
||||
.collect::<Vec<_>>();
|
||||
let (connector_names_by_source_path, connectors) =
|
||||
detected_session_connectors(&migration_service, &sessions);
|
||||
record_detected_session_connectors(
|
||||
self.migration_service.codex_home(),
|
||||
connector_names_by_source_path,
|
||||
)
|
||||
.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to record detected connector candidates: {err}"
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok(detect_response(items, connectors))
|
||||
}
|
||||
|
||||
pub(crate) async fn import(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ExternalAgentConfigImportParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let (include_memory, memory_version) = self.memory_import_settings().await;
|
||||
if params
|
||||
.migration_items
|
||||
.iter()
|
||||
.any(|item| item.item_type == ExternalAgentConfigMigrationItemType::Memory)
|
||||
&& !include_memory
|
||||
{
|
||||
return Err(invalid_request("external agent memory import is disabled"));
|
||||
}
|
||||
if params.migration_items.iter().any(|item| {
|
||||
item.item_type == ExternalAgentConfigMigrationItemType::Memory
|
||||
&& item
|
||||
.details
|
||||
.as_ref()
|
||||
.is_none_or(|details| details.memory.is_empty())
|
||||
}) {
|
||||
return Err(invalid_request(
|
||||
"memory import requires at least one selected memory",
|
||||
));
|
||||
}
|
||||
let import_id = Uuid::new_v4().to_string();
|
||||
let analytics_source = params.source.clone().unwrap_or_default();
|
||||
let provider_id = params.provider_id.clone();
|
||||
let migration_service = self
|
||||
.migration_service
|
||||
.with_migration_source(params.migration_source.as_deref())
|
||||
.with_memory_version(memory_version);
|
||||
let needs_runtime_refresh = migration_items_need_runtime_refresh(¶ms.migration_items);
|
||||
let has_migration_items = !params.migration_items.is_empty();
|
||||
let has_plugin_imports = params.migration_items.iter().any(|item| {
|
||||
matches!(
|
||||
item.item_type,
|
||||
ExternalAgentConfigMigrationItemType::Plugins
|
||||
)
|
||||
});
|
||||
let (pending_session_imports, session_validation_result) =
|
||||
self.validate_pending_session_imports(¶ms, &migration_service);
|
||||
let import_outcome = self
|
||||
.import_external_agent_config(params, &migration_service)
|
||||
.await;
|
||||
if needs_runtime_refresh {
|
||||
self.config_processor.handle_config_mutation().await;
|
||||
}
|
||||
self.outgoing
|
||||
.send_response(
|
||||
request_id,
|
||||
ExternalAgentConfigImportResponse {
|
||||
import_id: import_id.clone(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
if !has_migration_items {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut completed_item_results = Vec::new();
|
||||
if let Some(session_validation_result) = session_validation_result {
|
||||
send_import_progress(&self.outgoing, &import_id, &session_validation_result).await;
|
||||
completed_item_results.push(session_validation_result);
|
||||
}
|
||||
for item_result in import_outcome.item_results {
|
||||
send_import_progress(&self.outgoing, &import_id, &item_result).await;
|
||||
completed_item_results.push(item_result);
|
||||
}
|
||||
|
||||
let has_background_imports = !import_outcome.pending_plugin_imports.is_empty()
|
||||
|| !pending_session_imports.is_empty();
|
||||
if !has_background_imports {
|
||||
send_completed_import_notification(
|
||||
&self.outgoing,
|
||||
self.state_db.as_ref(),
|
||||
&self.analytics_events_client,
|
||||
import_id,
|
||||
analytics_source,
|
||||
provider_id,
|
||||
&completed_item_results,
|
||||
)
|
||||
.await;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let session_importer = self.session_importer.clone();
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let state_db = self.state_db.clone();
|
||||
let analytics_events_client = self.analytics_events_client.clone();
|
||||
let thread_manager = Arc::clone(&self.thread_manager);
|
||||
let session_metadata_mode = migration_service.session_metadata_mode();
|
||||
let plugin_migration_service = migration_service;
|
||||
let session_import_result = (!pending_session_imports.is_empty()).then(|| {
|
||||
CoreImportItemResult::new(
|
||||
CoreMigrationItemType::Sessions,
|
||||
"Import sessions".to_string(),
|
||||
/*cwd*/ None,
|
||||
)
|
||||
});
|
||||
let pending_plugin_imports = import_outcome.pending_plugin_imports;
|
||||
tokio::spawn(async move {
|
||||
let connector_names_by_source_path =
|
||||
detected_session_connectors(&plugin_migration_service, &pending_session_imports).0;
|
||||
let session_progress_outgoing = Arc::clone(&outgoing);
|
||||
let session_import_id = import_id.clone();
|
||||
let session_imports = async move {
|
||||
let session_import_result = session_import_result?;
|
||||
let item_result = session_importer
|
||||
.import_sessions(
|
||||
pending_session_imports,
|
||||
session_import_result,
|
||||
session_metadata_mode,
|
||||
connector_names_by_source_path,
|
||||
)
|
||||
.await;
|
||||
send_import_progress(&session_progress_outgoing, &session_import_id, &item_result)
|
||||
.await;
|
||||
Some(item_result)
|
||||
};
|
||||
let plugin_progress_outgoing = Arc::clone(&outgoing);
|
||||
let plugin_import_id = import_id.clone();
|
||||
let plugin_imports = async move {
|
||||
let mut item_results = Vec::new();
|
||||
for pending_plugin_import in pending_plugin_imports {
|
||||
let mut item_result = CoreImportItemResult::new(
|
||||
CoreMigrationItemType::Plugins,
|
||||
pending_plugin_import.description.clone(),
|
||||
pending_plugin_import.cwd.clone(),
|
||||
);
|
||||
match plugin_migration_service
|
||||
.import_plugins(
|
||||
pending_plugin_import.cwd.as_deref(),
|
||||
Some(pending_plugin_import.details),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(plugin_outcome) => {
|
||||
apply_plugin_outcome_to_item_result(&mut item_result, plugin_outcome);
|
||||
}
|
||||
Err(error) => {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"plugin_import",
|
||||
/*sub_error_type*/ None,
|
||||
error.to_string(),
|
||||
/*source*/ None,
|
||||
);
|
||||
}
|
||||
}
|
||||
send_import_progress(
|
||||
&plugin_progress_outgoing,
|
||||
&plugin_import_id,
|
||||
&item_result,
|
||||
)
|
||||
.await;
|
||||
item_results.push(item_result);
|
||||
}
|
||||
item_results
|
||||
};
|
||||
let (session_result, plugin_results) = tokio::join!(session_imports, plugin_imports);
|
||||
let mut background_item_results = Vec::new();
|
||||
if let Some(session_result) = session_result {
|
||||
background_item_results.push(session_result);
|
||||
}
|
||||
background_item_results.extend(plugin_results);
|
||||
completed_item_results.extend(background_item_results);
|
||||
if has_plugin_imports {
|
||||
thread_manager.plugins_manager().clear_cache();
|
||||
thread_manager.skills_service().clear_cache();
|
||||
}
|
||||
send_completed_import_notification(
|
||||
&outgoing,
|
||||
state_db.as_ref(),
|
||||
&analytics_events_client,
|
||||
import_id,
|
||||
analytics_source,
|
||||
provider_id,
|
||||
&completed_item_results,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn memory_import_settings(&self) -> (bool, MemoryVersion) {
|
||||
let config = match self
|
||||
.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
{
|
||||
Ok(config) => config,
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
error = %err,
|
||||
"failed to reload config for external agent memory import detection"
|
||||
);
|
||||
return (false, MemoryVersion::V1);
|
||||
}
|
||||
};
|
||||
(
|
||||
config.features.enabled(Feature::ExternalAgentMemoryImport),
|
||||
config.memories.version,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn read_import_histories(
|
||||
&self,
|
||||
) -> Result<ExternalAgentConfigImportHistoriesReadResponse, JSONRPCErrorError> {
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or_else(|| internal_error("state database is unavailable"))?;
|
||||
let histories = state_db
|
||||
.external_agent_config_import_history_records()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to read import histories: {err}")))?;
|
||||
let data = histories
|
||||
.into_iter()
|
||||
.map(protocol_import_history)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let connectors = read_imported_connector_candidates(self.migration_service.codex_home())
|
||||
.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to read imported connector candidates: {err}"
|
||||
))
|
||||
})?
|
||||
.into_iter()
|
||||
.map(|candidate| ExternalAgentImportedConnectorCandidate {
|
||||
name: candidate.name,
|
||||
session_count: candidate.session_count,
|
||||
source: ExternalAgentImportedConnectorSource::RemoteMcpServersConfig,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(ExternalAgentConfigImportHistoriesReadResponse { data, connectors })
|
||||
}
|
||||
|
||||
pub(crate) async fn record_import_history(
|
||||
&self,
|
||||
params: ExternalAgentConfigImportHistoryRecordParams,
|
||||
) -> Result<ExternalAgentConfigImportHistoryRecordResponse, JSONRPCErrorError> {
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or_else(|| internal_error("state database is unavailable"))?;
|
||||
let import_id = Uuid::new_v4().to_string();
|
||||
let item_type_results = params
|
||||
.item_type_results
|
||||
.into_iter()
|
||||
.map(|type_result| ProtocolImportTypeResult {
|
||||
item_type: type_result.item_type,
|
||||
successes: type_result
|
||||
.successes
|
||||
.into_iter()
|
||||
.map(|success| ProtocolImportSuccess {
|
||||
item_type: success.item_type,
|
||||
cwd: success.cwd,
|
||||
source: success.source,
|
||||
target: success.target,
|
||||
title: success.title,
|
||||
})
|
||||
.collect(),
|
||||
failures: type_result.failures,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
record_import_history(
|
||||
state_db,
|
||||
import_id.as_str(),
|
||||
Some(params.provider_id.as_str()),
|
||||
&item_type_results,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to record import history: {err}")))?;
|
||||
|
||||
Ok(ExternalAgentConfigImportHistoryRecordResponse { import_id })
|
||||
}
|
||||
|
||||
fn validate_pending_session_imports(
|
||||
&self,
|
||||
params: &ExternalAgentConfigImportParams,
|
||||
migration_service: &ExternalAgentConfigService,
|
||||
) -> (Vec<CoreSessionMigration>, Option<CoreImportItemResult>) {
|
||||
let sessions = params
|
||||
.migration_items
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
matches!(
|
||||
item.item_type,
|
||||
ExternalAgentConfigMigrationItemType::Sessions
|
||||
)
|
||||
})
|
||||
.filter_map(|item| item.details.as_ref())
|
||||
.flat_map(|details| details.sessions.clone())
|
||||
.map(|session| CoreSessionMigration {
|
||||
path: session.path,
|
||||
cwd: session.cwd,
|
||||
title: session.title,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if sessions.is_empty() {
|
||||
return (Vec::new(), None);
|
||||
}
|
||||
let mut item_result = CoreImportItemResult::new(
|
||||
CoreMigrationItemType::Sessions,
|
||||
"Validate session imports".to_string(),
|
||||
/*cwd*/ None,
|
||||
);
|
||||
let mut selected_session_paths = HashSet::new();
|
||||
let mut selected_sessions = Vec::new();
|
||||
for session in sessions {
|
||||
let canonical_path =
|
||||
match migration_service.external_agent_session_source_path(&session.path) {
|
||||
Ok(Some(canonical_path)) => canonical_path,
|
||||
Ok(None) => {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_missing",
|
||||
Some("session_not_detected"),
|
||||
format!(
|
||||
"external agent session was not detected for import: {}",
|
||||
session.path.display()
|
||||
),
|
||||
Some(session.path.display().to_string()),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Err(err) => {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_source_path",
|
||||
Some("failed_to_resolve_session_source_path"),
|
||||
err.to_string(),
|
||||
Some(session.path.display().to_string()),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if selected_session_paths.insert(canonical_path) {
|
||||
selected_sessions.push(session);
|
||||
}
|
||||
}
|
||||
(selected_sessions, Some(item_result))
|
||||
}
|
||||
|
||||
async fn import_external_agent_config(
|
||||
&self,
|
||||
params: ExternalAgentConfigImportParams,
|
||||
migration_service: &ExternalAgentConfigService,
|
||||
) -> CoreImportOutcome {
|
||||
migration_service
|
||||
.import(core_migration_items(
|
||||
params
|
||||
.migration_items
|
||||
.into_iter()
|
||||
.filter(|item| item.item_type != ExternalAgentConfigMigrationItemType::Sessions)
|
||||
.collect(),
|
||||
))
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_import_progress(
|
||||
outgoing: &OutgoingMessageSender,
|
||||
import_id: &str,
|
||||
item_result: &CoreImportItemResult,
|
||||
) {
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::ExternalAgentConfigImportProgress(
|
||||
ExternalAgentConfigImportProgressNotification {
|
||||
import_id: import_id.to_string(),
|
||||
item_type_results: vec![protocol_import_type_result(item_result)],
|
||||
},
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn send_completed_import_notification(
|
||||
outgoing: &OutgoingMessageSender,
|
||||
state_db: Option<&StateDbHandle>,
|
||||
analytics_events_client: &AnalyticsEventsClient,
|
||||
import_id: String,
|
||||
analytics_source: String,
|
||||
provider_id: Option<String>,
|
||||
item_results: &[CoreImportItemResult],
|
||||
) {
|
||||
let notification = completed_notification(import_id, item_results);
|
||||
log_completed_import_failures(¬ification);
|
||||
track_completed_import_notification(
|
||||
analytics_events_client,
|
||||
&analytics_source,
|
||||
provider_id.as_deref().unwrap_or_default(),
|
||||
¬ification,
|
||||
);
|
||||
if let Some(state_db) = state_db
|
||||
&& let Err(err) =
|
||||
record_completed_import_notification(state_db, provider_id.as_deref(), ¬ification)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
import_id = %notification.import_id,
|
||||
error = %err,
|
||||
"failed to record external agent config import completion"
|
||||
);
|
||||
}
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::ExternalAgentConfigImportCompleted(
|
||||
notification,
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
fn log_completed_import_failures(notification: &ExternalAgentConfigImportCompletedNotification) {
|
||||
for type_result in ¬ification.item_type_results {
|
||||
for failure in &type_result.failures {
|
||||
let error_type = import_failure_error_type(failure);
|
||||
tracing::warn!(
|
||||
import_id = %notification.import_id,
|
||||
item_type = ?failure.item_type,
|
||||
error_type = %error_type,
|
||||
failure_stage = %failure.failure_stage,
|
||||
cwd = ?failure.cwd,
|
||||
source = ?failure.source,
|
||||
error = %failure.message,
|
||||
"external agent config migration item failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn track_completed_import_notification(
|
||||
analytics_events_client: &AnalyticsEventsClient,
|
||||
analytics_source: &str,
|
||||
provider_id: &str,
|
||||
notification: &ExternalAgentConfigImportCompletedNotification,
|
||||
) {
|
||||
for type_result in ¬ification.item_type_results {
|
||||
let item_type = analytics_migration_item_type(type_result.item_type).to_string();
|
||||
analytics_events_client.track_external_agent_config_import_completed(
|
||||
ExternalAgentConfigImportCompletedInput {
|
||||
import_id: notification.import_id.clone(),
|
||||
source: analytics_source.to_string(),
|
||||
provider_id: provider_id.to_string(),
|
||||
item_type: item_type.clone(),
|
||||
success_count: type_result.successes.len(),
|
||||
failed_count: type_result.failures.len(),
|
||||
},
|
||||
);
|
||||
for failure in &type_result.failures {
|
||||
analytics_events_client.track_external_agent_config_import_failure(
|
||||
ExternalAgentConfigImportFailureInput {
|
||||
import_id: notification.import_id.clone(),
|
||||
source: analytics_source.to_string(),
|
||||
provider_id: provider_id.to_string(),
|
||||
item_type: item_type.clone(),
|
||||
failure_stage: failure.failure_stage.clone(),
|
||||
error_type: import_failure_error_type(failure),
|
||||
sub_error_type: failure.sub_error_type.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn import_failure_error_type(failure: &ProtocolImportFailure) -> String {
|
||||
failure
|
||||
.error_type
|
||||
.clone()
|
||||
.unwrap_or_else(|| failure.failure_stage.clone())
|
||||
}
|
||||
|
||||
fn analytics_migration_item_type(item_type: ExternalAgentConfigMigrationItemType) -> &'static str {
|
||||
match item_type {
|
||||
ExternalAgentConfigMigrationItemType::AgentsMd => "AGENTS_MD",
|
||||
ExternalAgentConfigMigrationItemType::Config => "CONFIG",
|
||||
ExternalAgentConfigMigrationItemType::Skills => "SKILLS",
|
||||
ExternalAgentConfigMigrationItemType::Plugins => "PLUGINS",
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig => "MCP_SERVER_CONFIG",
|
||||
ExternalAgentConfigMigrationItemType::Subagents => "SUBAGENTS",
|
||||
ExternalAgentConfigMigrationItemType::Hooks => "HOOKS",
|
||||
ExternalAgentConfigMigrationItemType::Commands => "COMMANDS",
|
||||
ExternalAgentConfigMigrationItemType::Memory => "MEMORY",
|
||||
ExternalAgentConfigMigrationItemType::Sessions => "SESSIONS",
|
||||
}
|
||||
}
|
||||
|
||||
async fn record_completed_import_notification(
|
||||
state_db: &StateDbHandle,
|
||||
provider_id: Option<&str>,
|
||||
notification: &ExternalAgentConfigImportCompletedNotification,
|
||||
) -> anyhow::Result<()> {
|
||||
record_import_history(
|
||||
state_db,
|
||||
notification.import_id.as_str(),
|
||||
provider_id,
|
||||
¬ification.item_type_results,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn record_import_history(
|
||||
state_db: &StateDbHandle,
|
||||
import_id: &str,
|
||||
provider_id: Option<&str>,
|
||||
item_type_results: &[ProtocolImportTypeResult],
|
||||
) -> anyhow::Result<()> {
|
||||
let successes = item_type_results
|
||||
.iter()
|
||||
.flat_map(|type_result| type_result.successes.iter())
|
||||
.map(|success| {
|
||||
Ok(ExternalAgentConfigImportSuccessRecord {
|
||||
item_type: serde_json::from_value(serde_json::to_value(success.item_type)?)?,
|
||||
cwd: success.cwd.clone(),
|
||||
source: success.source.clone(),
|
||||
target: success.target.clone(),
|
||||
title: success.title.clone(),
|
||||
})
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
let failures = item_type_results
|
||||
.iter()
|
||||
.flat_map(|type_result| type_result.failures.iter())
|
||||
.map(|failure| {
|
||||
Ok(ExternalAgentConfigImportFailureRecord {
|
||||
item_type: serde_json::from_value(serde_json::to_value(failure.item_type)?)?,
|
||||
error_type: failure.error_type.clone(),
|
||||
sub_error_type: failure.sub_error_type.clone(),
|
||||
failure_stage: failure.failure_stage.clone(),
|
||||
message: failure.message.clone(),
|
||||
cwd: failure.cwd.clone(),
|
||||
source: failure.source.clone(),
|
||||
})
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
state_db
|
||||
.record_external_agent_config_import_completed(
|
||||
import_id,
|
||||
provider_id,
|
||||
&successes,
|
||||
&failures,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn detected_session_connectors(
|
||||
migration_service: &ExternalAgentConfigService,
|
||||
sessions: &[CoreSessionMigration],
|
||||
) -> (
|
||||
BTreeMap<PathBuf, Vec<String>>,
|
||||
Vec<DetectedConnectorCandidate>,
|
||||
) {
|
||||
let mut connector_names_by_source_path = BTreeMap::new();
|
||||
let mut connectors_by_name = BTreeMap::<String, DetectedConnectorCandidate>::new();
|
||||
let sessions = sessions
|
||||
.iter()
|
||||
.filter(|session| session.path.is_file())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
for (source_path, session_connectors) in
|
||||
migration_service.detect_session_connectors_by_source_path(&sessions)
|
||||
{
|
||||
connector_names_by_source_path.insert(
|
||||
source_path,
|
||||
session_connectors
|
||||
.iter()
|
||||
.map(|candidate| candidate.name.clone())
|
||||
.collect(),
|
||||
);
|
||||
for candidate in session_connectors {
|
||||
let key = candidate.name.to_lowercase();
|
||||
let session_count = candidate.session_count;
|
||||
let connector = connectors_by_name.entry(key).or_insert_with(|| {
|
||||
let mut connector = candidate;
|
||||
connector.session_count = 0;
|
||||
connector
|
||||
});
|
||||
connector.session_count = connector.session_count.saturating_add(session_count);
|
||||
}
|
||||
}
|
||||
(
|
||||
connector_names_by_source_path,
|
||||
connectors_by_name.into_values().collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn apply_plugin_outcome_to_item_result(
|
||||
item_result: &mut CoreImportItemResult,
|
||||
plugin_outcome: PluginImportOutcome,
|
||||
) {
|
||||
for plugin_id in plugin_outcome.succeeded_plugin_ids {
|
||||
item_result.record_success(
|
||||
Some(plugin_id.clone()),
|
||||
Some(plugin_id),
|
||||
/*title*/ None,
|
||||
);
|
||||
}
|
||||
for raw_error in plugin_outcome.raw_errors {
|
||||
item_result.record_error(raw_error);
|
||||
}
|
||||
}
|
||||
|
||||
fn migration_items_need_runtime_refresh(items: &[ExternalAgentConfigMigrationItem]) -> bool {
|
||||
items.iter().any(|item| {
|
||||
matches!(
|
||||
item.item_type,
|
||||
ExternalAgentConfigMigrationItemType::Config
|
||||
| ExternalAgentConfigMigrationItemType::Skills
|
||||
| ExternalAgentConfigMigrationItemType::McpServerConfig
|
||||
| ExternalAgentConfigMigrationItemType::Hooks
|
||||
| ExternalAgentConfigMigrationItemType::Commands
|
||||
| ExternalAgentConfigMigrationItemType::Plugins
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "processor_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,40 @@
|
||||
use super::*;
|
||||
|
||||
fn migration_item(
|
||||
item_type: ExternalAgentConfigMigrationItemType,
|
||||
) -> ExternalAgentConfigMigrationItem {
|
||||
ExternalAgentConfigMigrationItem {
|
||||
item_type,
|
||||
description: String::new(),
|
||||
cwd: None,
|
||||
details: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_items_that_update_runtime_sources_trigger_refresh() {
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Config,
|
||||
)]));
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Skills,
|
||||
)]));
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig,
|
||||
)]));
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Hooks,
|
||||
)]));
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Commands,
|
||||
)]));
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Plugins,
|
||||
)]));
|
||||
assert!(!migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Memory,
|
||||
)]));
|
||||
assert!(!migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Sessions,
|
||||
)]));
|
||||
}
|
||||
366
codex-rs/app-server/src/external_agent_migration/protocol.rs
Normal file
366
codex-rs/app-server/src/external_agent_migration/protocol.rs
Normal file
@@ -0,0 +1,366 @@
|
||||
use crate::error_code::internal_error;
|
||||
use codex_app_server_protocol::CommandMigration;
|
||||
use codex_app_server_protocol::ExternalAgentConfigDetectResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportHistory;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportItemTypeFailure as ProtocolImportFailure;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportItemTypeSuccess as ProtocolImportSuccess;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportTypeResult as ProtocolImportTypeResult;
|
||||
use codex_app_server_protocol::ExternalAgentConfigMigrationItem;
|
||||
use codex_app_server_protocol::ExternalAgentConfigMigrationItemType;
|
||||
use codex_app_server_protocol::ExternalAgentDetectedConnectorCandidate;
|
||||
use codex_app_server_protocol::ExternalAgentDetectedConnectorSource;
|
||||
use codex_app_server_protocol::HookMigration;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::McpServerMigration;
|
||||
use codex_app_server_protocol::MigrationDetails;
|
||||
use codex_app_server_protocol::PluginsMigration;
|
||||
use codex_app_server_protocol::SkillMigration;
|
||||
use codex_app_server_protocol::SubagentMigration;
|
||||
use codex_external_agent_migration::DetectedConnectorCandidate as CoreDetectedConnectorCandidate;
|
||||
use codex_external_agent_migration::DetectedConnectorSource as CoreDetectedConnectorSource;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportItemResult as CoreImportItemResult;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportRawError as CoreImportRawError;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportSuccess;
|
||||
use codex_external_agent_migration::ExternalAgentConfigMigrationItem as CoreMigrationItem;
|
||||
use codex_external_agent_migration::ExternalAgentConfigMigrationItemType as CoreMigrationItemType;
|
||||
use codex_external_agent_migration::MigrationDetails as CoreMigrationDetails;
|
||||
use codex_external_agent_migration::NamedMigration;
|
||||
use codex_external_agent_migration::PluginsMigration as CorePluginsMigration;
|
||||
use codex_external_agent_migration::sessions::ExternalAgentSessionMigration;
|
||||
use codex_state::ExternalAgentConfigImportFailureRecord;
|
||||
use codex_state::ExternalAgentConfigImportSuccessRecord;
|
||||
|
||||
pub(super) fn detect_response(
|
||||
items: Vec<CoreMigrationItem>,
|
||||
connectors: Vec<CoreDetectedConnectorCandidate>,
|
||||
) -> ExternalAgentConfigDetectResponse {
|
||||
ExternalAgentConfigDetectResponse {
|
||||
items: items.into_iter().map(protocol_migration_item).collect(),
|
||||
connectors: connectors
|
||||
.into_iter()
|
||||
.map(|candidate| ExternalAgentDetectedConnectorCandidate {
|
||||
name: candidate.name,
|
||||
session_count: candidate.session_count,
|
||||
source: match candidate.source {
|
||||
CoreDetectedConnectorSource::RemoteMcpServersConfig => {
|
||||
ExternalAgentDetectedConnectorSource::RemoteMcpServersConfig
|
||||
}
|
||||
CoreDetectedConnectorSource::SessionToolUse => {
|
||||
ExternalAgentDetectedConnectorSource::SessionToolUse
|
||||
}
|
||||
},
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_migration_item(item: CoreMigrationItem) -> ExternalAgentConfigMigrationItem {
|
||||
ExternalAgentConfigMigrationItem {
|
||||
item_type: protocol_migration_item_type(item.item_type),
|
||||
description: item.description,
|
||||
cwd: item.cwd,
|
||||
details: item.details.map(protocol_migration_details),
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_migration_details(details: CoreMigrationDetails) -> MigrationDetails {
|
||||
MigrationDetails {
|
||||
plugins: details
|
||||
.plugins
|
||||
.into_iter()
|
||||
.map(|plugin| PluginsMigration {
|
||||
marketplace_name: plugin.marketplace_name,
|
||||
plugin_names: plugin.plugin_names,
|
||||
})
|
||||
.collect(),
|
||||
skills: details
|
||||
.skills
|
||||
.into_iter()
|
||||
.map(|skill| SkillMigration { name: skill.name })
|
||||
.collect(),
|
||||
sessions: details
|
||||
.sessions
|
||||
.into_iter()
|
||||
.map(|session| codex_app_server_protocol::SessionMigration {
|
||||
path: session.path,
|
||||
cwd: session.cwd,
|
||||
title: session.title,
|
||||
})
|
||||
.collect(),
|
||||
mcp_servers: details
|
||||
.mcp_servers
|
||||
.into_iter()
|
||||
.map(|server| McpServerMigration { name: server.name })
|
||||
.collect(),
|
||||
hooks: details
|
||||
.hooks
|
||||
.into_iter()
|
||||
.map(|hook| HookMigration { name: hook.name })
|
||||
.collect(),
|
||||
subagents: details
|
||||
.subagents
|
||||
.into_iter()
|
||||
.map(|subagent| SubagentMigration {
|
||||
name: subagent.name,
|
||||
})
|
||||
.collect(),
|
||||
commands: details
|
||||
.commands
|
||||
.into_iter()
|
||||
.map(|command| CommandMigration { name: command.name })
|
||||
.collect(),
|
||||
memory: details.memory,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn core_migration_items(
|
||||
items: Vec<ExternalAgentConfigMigrationItem>,
|
||||
) -> Vec<CoreMigrationItem> {
|
||||
items
|
||||
.into_iter()
|
||||
.map(|item| CoreMigrationItem {
|
||||
item_type: core_migration_item_type(item.item_type),
|
||||
description: item.description,
|
||||
cwd: item.cwd,
|
||||
details: item.details.map(core_migration_details),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn core_migration_details(details: MigrationDetails) -> CoreMigrationDetails {
|
||||
CoreMigrationDetails {
|
||||
plugins: details
|
||||
.plugins
|
||||
.into_iter()
|
||||
.map(|plugin| CorePluginsMigration {
|
||||
marketplace_name: plugin.marketplace_name,
|
||||
plugin_names: plugin.plugin_names,
|
||||
})
|
||||
.collect(),
|
||||
skills: details
|
||||
.skills
|
||||
.into_iter()
|
||||
.map(|skill| NamedMigration { name: skill.name })
|
||||
.collect(),
|
||||
sessions: details
|
||||
.sessions
|
||||
.into_iter()
|
||||
.map(|session| ExternalAgentSessionMigration {
|
||||
path: session.path,
|
||||
cwd: session.cwd,
|
||||
title: session.title,
|
||||
})
|
||||
.collect(),
|
||||
mcp_servers: details
|
||||
.mcp_servers
|
||||
.into_iter()
|
||||
.map(|server| NamedMigration { name: server.name })
|
||||
.collect(),
|
||||
hooks: details
|
||||
.hooks
|
||||
.into_iter()
|
||||
.map(|hook| NamedMigration { name: hook.name })
|
||||
.collect(),
|
||||
subagents: details
|
||||
.subagents
|
||||
.into_iter()
|
||||
.map(|subagent| NamedMigration {
|
||||
name: subagent.name,
|
||||
})
|
||||
.collect(),
|
||||
commands: details
|
||||
.commands
|
||||
.into_iter()
|
||||
.map(|command| NamedMigration { name: command.name })
|
||||
.collect(),
|
||||
memory: details.memory,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn protocol_migration_item_type(
|
||||
item_type: CoreMigrationItemType,
|
||||
) -> ExternalAgentConfigMigrationItemType {
|
||||
match item_type {
|
||||
CoreMigrationItemType::Config => ExternalAgentConfigMigrationItemType::Config,
|
||||
CoreMigrationItemType::Skills => ExternalAgentConfigMigrationItemType::Skills,
|
||||
CoreMigrationItemType::AgentsMd => ExternalAgentConfigMigrationItemType::AgentsMd,
|
||||
CoreMigrationItemType::Plugins => ExternalAgentConfigMigrationItemType::Plugins,
|
||||
CoreMigrationItemType::McpServerConfig => {
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig
|
||||
}
|
||||
CoreMigrationItemType::Subagents => ExternalAgentConfigMigrationItemType::Subagents,
|
||||
CoreMigrationItemType::Hooks => ExternalAgentConfigMigrationItemType::Hooks,
|
||||
CoreMigrationItemType::Commands => ExternalAgentConfigMigrationItemType::Commands,
|
||||
CoreMigrationItemType::Memory => ExternalAgentConfigMigrationItemType::Memory,
|
||||
CoreMigrationItemType::Sessions => ExternalAgentConfigMigrationItemType::Sessions,
|
||||
}
|
||||
}
|
||||
|
||||
fn core_migration_item_type(
|
||||
item_type: ExternalAgentConfigMigrationItemType,
|
||||
) -> CoreMigrationItemType {
|
||||
match item_type {
|
||||
ExternalAgentConfigMigrationItemType::Config => CoreMigrationItemType::Config,
|
||||
ExternalAgentConfigMigrationItemType::Skills => CoreMigrationItemType::Skills,
|
||||
ExternalAgentConfigMigrationItemType::AgentsMd => CoreMigrationItemType::AgentsMd,
|
||||
ExternalAgentConfigMigrationItemType::Plugins => CoreMigrationItemType::Plugins,
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig => {
|
||||
CoreMigrationItemType::McpServerConfig
|
||||
}
|
||||
ExternalAgentConfigMigrationItemType::Subagents => CoreMigrationItemType::Subagents,
|
||||
ExternalAgentConfigMigrationItemType::Hooks => CoreMigrationItemType::Hooks,
|
||||
ExternalAgentConfigMigrationItemType::Commands => CoreMigrationItemType::Commands,
|
||||
ExternalAgentConfigMigrationItemType::Memory => CoreMigrationItemType::Memory,
|
||||
ExternalAgentConfigMigrationItemType::Sessions => CoreMigrationItemType::Sessions,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn protocol_import_history(
|
||||
record: codex_state::ExternalAgentConfigImportHistoryRecord,
|
||||
) -> Result<ExternalAgentConfigImportHistory, JSONRPCErrorError> {
|
||||
let successes = record
|
||||
.successes
|
||||
.into_iter()
|
||||
.map(protocol_import_success_record)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let failures = record
|
||||
.failures
|
||||
.into_iter()
|
||||
.map(protocol_import_failure_record)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(ExternalAgentConfigImportHistory {
|
||||
import_id: record.import_id,
|
||||
provider_id: record.provider_id,
|
||||
completed_at_ms: record.completed_at_ms,
|
||||
successes,
|
||||
failures,
|
||||
})
|
||||
}
|
||||
|
||||
fn protocol_import_success_record(
|
||||
record: ExternalAgentConfigImportSuccessRecord,
|
||||
) -> Result<ProtocolImportSuccess, JSONRPCErrorError> {
|
||||
Ok(ProtocolImportSuccess {
|
||||
item_type: protocol_import_record_item_type(record.item_type)?,
|
||||
cwd: record.cwd,
|
||||
source: record.source,
|
||||
target: record.target,
|
||||
title: record.title,
|
||||
})
|
||||
}
|
||||
|
||||
fn protocol_import_failure_record(
|
||||
record: ExternalAgentConfigImportFailureRecord,
|
||||
) -> Result<ProtocolImportFailure, JSONRPCErrorError> {
|
||||
Ok(ProtocolImportFailure {
|
||||
item_type: protocol_import_record_item_type(record.item_type)?,
|
||||
error_type: record.error_type,
|
||||
sub_error_type: record.sub_error_type,
|
||||
failure_stage: record.failure_stage,
|
||||
message: record.message,
|
||||
cwd: record.cwd,
|
||||
source: record.source,
|
||||
})
|
||||
}
|
||||
|
||||
fn protocol_import_record_item_type(
|
||||
item_type: String,
|
||||
) -> Result<ExternalAgentConfigMigrationItemType, JSONRPCErrorError> {
|
||||
serde_json::from_value(serde_json::Value::String(item_type.clone())).map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to decode import item type {item_type}: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn completed_notification(
|
||||
import_id: String,
|
||||
item_results: &[CoreImportItemResult],
|
||||
) -> ExternalAgentConfigImportCompletedNotification {
|
||||
let mut protocol_type_results: Vec<ProtocolImportTypeResult> = Vec::new();
|
||||
for item_result in item_results {
|
||||
let item_raw_errors = item_result
|
||||
.raw_errors
|
||||
.iter()
|
||||
.map(protocol_import_raw_error)
|
||||
.collect::<Vec<_>>();
|
||||
let item_successes = item_result
|
||||
.successes
|
||||
.iter()
|
||||
.map(protocol_import_success)
|
||||
.collect::<Vec<_>>();
|
||||
let item_type = protocol_migration_item_type(item_result.item_type);
|
||||
if let Some(type_result) = protocol_type_results
|
||||
.iter_mut()
|
||||
.find(|type_result| type_result.item_type == item_type)
|
||||
{
|
||||
type_result.successes.extend(item_successes);
|
||||
type_result.failures.extend(item_raw_errors);
|
||||
} else {
|
||||
protocol_type_results.push(ProtocolImportTypeResult {
|
||||
item_type,
|
||||
successes: item_successes,
|
||||
failures: item_raw_errors,
|
||||
});
|
||||
}
|
||||
}
|
||||
protocol_type_results.sort_by_key(|type_result| match type_result.item_type {
|
||||
ExternalAgentConfigMigrationItemType::Config => 0,
|
||||
ExternalAgentConfigMigrationItemType::Skills => 1,
|
||||
ExternalAgentConfigMigrationItemType::AgentsMd => 2,
|
||||
ExternalAgentConfigMigrationItemType::Plugins => 3,
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig => 4,
|
||||
ExternalAgentConfigMigrationItemType::Subagents => 5,
|
||||
ExternalAgentConfigMigrationItemType::Hooks => 6,
|
||||
ExternalAgentConfigMigrationItemType::Commands => 7,
|
||||
ExternalAgentConfigMigrationItemType::Sessions => 8,
|
||||
ExternalAgentConfigMigrationItemType::Memory => 9,
|
||||
});
|
||||
|
||||
ExternalAgentConfigImportCompletedNotification {
|
||||
import_id,
|
||||
item_type_results: protocol_type_results,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn protocol_import_type_result(
|
||||
item_result: &CoreImportItemResult,
|
||||
) -> ProtocolImportTypeResult {
|
||||
ProtocolImportTypeResult {
|
||||
item_type: protocol_migration_item_type(item_result.item_type),
|
||||
successes: item_result
|
||||
.successes
|
||||
.iter()
|
||||
.map(protocol_import_success)
|
||||
.collect(),
|
||||
failures: item_result
|
||||
.raw_errors
|
||||
.iter()
|
||||
.map(protocol_import_raw_error)
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_import_success(success: &ExternalAgentConfigImportSuccess) -> ProtocolImportSuccess {
|
||||
ProtocolImportSuccess {
|
||||
item_type: protocol_migration_item_type(success.item_type),
|
||||
cwd: success.cwd.clone(),
|
||||
source: success.source.clone(),
|
||||
target: success.target.clone(),
|
||||
title: success.title.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_import_raw_error(raw_error: &CoreImportRawError) -> ProtocolImportFailure {
|
||||
ProtocolImportFailure {
|
||||
item_type: protocol_migration_item_type(raw_error.item_type),
|
||||
error_type: raw_error.error_type.clone(),
|
||||
sub_error_type: raw_error.sub_error_type.clone(),
|
||||
failure_stage: raw_error.failure_stage.clone(),
|
||||
message: raw_error.message.clone(),
|
||||
cwd: raw_error.cwd.clone(),
|
||||
source: raw_error.source.clone(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,624 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportItemResult;
|
||||
use codex_external_agent_migration::record_import_error;
|
||||
use codex_external_agent_migration::sessions::CompletedExternalAgentSessionImport;
|
||||
use codex_external_agent_migration::sessions::ExistingSessionAppend;
|
||||
use codex_external_agent_migration::sessions::ExternalAgentSessionMigration;
|
||||
use codex_external_agent_migration::sessions::ImportedExternalAgentSession;
|
||||
use codex_external_agent_migration::sessions::ImportedSessionConnectorAttribution;
|
||||
use codex_external_agent_migration::sessions::PendingSessionImport;
|
||||
use codex_external_agent_migration::sessions::SessionImportTarget;
|
||||
use codex_external_agent_migration::sessions::SessionMetadataMode;
|
||||
use codex_external_agent_migration::sessions::append_existing_session;
|
||||
use codex_external_agent_migration::sessions::append_imported_session_connector_names;
|
||||
use codex_external_agent_migration::sessions::detect_imported_cla_session_connectors_by_source_path;
|
||||
use codex_external_agent_migration::sessions::prepare_validated_session_import_with_metadata_mode;
|
||||
use codex_external_agent_migration::sessions::record_completed_session_imports;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_prompts::render_model_instructions;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::BaseInstructions;
|
||||
use codex_protocol::models::BaseInstructionsProvenance;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::into_persisted_rollout_items;
|
||||
use codex_thread_store::AppendThreadItemsParams;
|
||||
use codex_thread_store::CreateThreadParams;
|
||||
use codex_thread_store::PersistContext;
|
||||
use codex_thread_store::ThreadMetadataPatch;
|
||||
use codex_thread_store::ThreadPersistenceMetadata;
|
||||
use codex_thread_store::ThreadStore;
|
||||
use codex_thread_store::UpdateThreadMetadataParams;
|
||||
use futures::StreamExt;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::config_manager::ConfigManager;
|
||||
|
||||
const SESSION_IMPORT_CONCURRENCY: usize = 5;
|
||||
|
||||
struct CompletedSessionImport {
|
||||
cwd: PathBuf,
|
||||
import: CompletedExternalAgentSessionImport,
|
||||
connector_attribution: Option<ImportedSessionConnectorAttribution>,
|
||||
}
|
||||
|
||||
enum SessionImportOutcome {
|
||||
Created(CompletedSessionImport),
|
||||
Appended {
|
||||
cwd: PathBuf,
|
||||
source_path: PathBuf,
|
||||
imported_thread_id: ThreadId,
|
||||
title: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct ExternalAgentSessionImporter {
|
||||
codex_home: PathBuf,
|
||||
connector_metadata_roots: Vec<PathBuf>,
|
||||
permits: Arc<Semaphore>,
|
||||
append_checkpoint_permits: Arc<Semaphore>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
config_manager: ConfigManager,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
}
|
||||
|
||||
impl ExternalAgentSessionImporter {
|
||||
pub(super) fn new(
|
||||
codex_home: PathBuf,
|
||||
connector_metadata_roots: Vec<PathBuf>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
config_manager: ConfigManager,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
) -> Self {
|
||||
Self {
|
||||
codex_home,
|
||||
connector_metadata_roots,
|
||||
permits: Arc::new(Semaphore::new(1)),
|
||||
append_checkpoint_permits: Arc::new(Semaphore::new(1)),
|
||||
thread_manager,
|
||||
thread_store,
|
||||
config_manager,
|
||||
arg0_paths,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn import_sessions(
|
||||
&self,
|
||||
sessions: Vec<ExternalAgentSessionMigration>,
|
||||
mut item_result: ExternalAgentConfigImportItemResult,
|
||||
metadata_mode: SessionMetadataMode,
|
||||
mut connector_names_by_source_path: BTreeMap<PathBuf, Vec<String>>,
|
||||
) -> ExternalAgentConfigImportItemResult {
|
||||
if sessions.is_empty() {
|
||||
return item_result;
|
||||
}
|
||||
let Ok(_permit) = self.permits.acquire().await else {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_permit",
|
||||
Some("failed_to_acquire_import_permit"),
|
||||
"external agent session import permit could not be acquired",
|
||||
/*source*/ None,
|
||||
);
|
||||
return item_result;
|
||||
};
|
||||
let import_results = futures::stream::iter(sessions)
|
||||
.map(|session| {
|
||||
let importer = self.clone();
|
||||
async move {
|
||||
importer
|
||||
.import_requested_session(session, metadata_mode)
|
||||
.await
|
||||
}
|
||||
})
|
||||
.buffer_unordered(SESSION_IMPORT_CONCURRENCY);
|
||||
futures::pin_mut!(import_results);
|
||||
|
||||
let mut completed_imports = Vec::new();
|
||||
let mut appended_connector_names_by_source_path = BTreeMap::new();
|
||||
while let Some(result) = import_results.next().await {
|
||||
match result {
|
||||
Ok(Some(SessionImportOutcome::Created(completed_import))) => {
|
||||
item_result.record_success_with_cwd(
|
||||
Some(completed_import.cwd.clone()),
|
||||
Some(completed_import.import.source_path.display().to_string()),
|
||||
Some(completed_import.import.imported_thread_id.to_string()),
|
||||
completed_import.import.title.clone(),
|
||||
);
|
||||
completed_imports.push(completed_import);
|
||||
}
|
||||
Ok(Some(SessionImportOutcome::Appended {
|
||||
cwd,
|
||||
source_path,
|
||||
imported_thread_id,
|
||||
title,
|
||||
})) => {
|
||||
item_result.record_success_with_cwd(
|
||||
Some(cwd),
|
||||
Some(source_path.display().to_string()),
|
||||
Some(imported_thread_id.to_string()),
|
||||
title,
|
||||
);
|
||||
if let Some(connector_names) =
|
||||
connector_names_by_source_path.remove(&source_path)
|
||||
{
|
||||
appended_connector_names_by_source_path
|
||||
.insert(source_path, connector_names);
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(failure) => {
|
||||
let SessionImportFailure {
|
||||
source_path,
|
||||
message,
|
||||
stage,
|
||||
sub_error_type,
|
||||
} = failure;
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
stage,
|
||||
Some(sub_error_type.as_str()),
|
||||
message,
|
||||
Some(source_path.display().to_string()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(err) = append_imported_session_connector_names(
|
||||
&self.codex_home,
|
||||
appended_connector_names_by_source_path,
|
||||
) {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_ledger_update",
|
||||
Some("failed_to_update_session_connector_metadata"),
|
||||
err.to_string(),
|
||||
/*source*/ None,
|
||||
);
|
||||
}
|
||||
if completed_imports.is_empty() {
|
||||
return item_result;
|
||||
}
|
||||
let connector_attributions_by_source_path = completed_imports
|
||||
.iter()
|
||||
.filter_map(|completed_import| {
|
||||
completed_import
|
||||
.connector_attribution
|
||||
.clone()
|
||||
.map(|attribution| (completed_import.import.source_path.clone(), attribution))
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let connector_metadata_roots = self.connector_metadata_roots.clone();
|
||||
let mut attributed_connector_names_by_source_path =
|
||||
match tokio::task::spawn_blocking(move || {
|
||||
detect_imported_cla_session_connectors_by_source_path(
|
||||
&connector_attributions_by_source_path,
|
||||
&connector_metadata_roots,
|
||||
)
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(connector_names_by_source_path) => connector_names_by_source_path,
|
||||
Err(err) => {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_connector_detection_task",
|
||||
Some("session_connector_detection_task_failed"),
|
||||
err.to_string(),
|
||||
/*source*/ None,
|
||||
);
|
||||
Default::default()
|
||||
}
|
||||
};
|
||||
for completed_import in &mut completed_imports {
|
||||
completed_import.import.connector_names = attributed_connector_names_by_source_path
|
||||
.remove(&completed_import.import.source_path)
|
||||
.unwrap_or_default();
|
||||
}
|
||||
for completed_import in &mut completed_imports {
|
||||
let Some(connector_names) =
|
||||
connector_names_by_source_path.remove(&completed_import.import.source_path)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
completed_import
|
||||
.import
|
||||
.connector_names
|
||||
.extend(connector_names);
|
||||
}
|
||||
let completed_imports = completed_imports
|
||||
.into_iter()
|
||||
.map(|completed_import| completed_import.import)
|
||||
.collect();
|
||||
if let Err(err) = record_completed_session_imports(&self.codex_home, completed_imports) {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_ledger_update",
|
||||
Some("failed_to_update_session_ledger"),
|
||||
err.to_string(),
|
||||
/*source*/ None,
|
||||
);
|
||||
}
|
||||
item_result
|
||||
}
|
||||
|
||||
async fn import_requested_session(
|
||||
&self,
|
||||
session: ExternalAgentSessionMigration,
|
||||
metadata_mode: SessionMetadataMode,
|
||||
) -> Result<Option<SessionImportOutcome>, SessionImportFailure> {
|
||||
let source_path = session.path.clone();
|
||||
let Some(pending_import) = self
|
||||
.prepare_session_import(session, metadata_mode)
|
||||
.await
|
||||
.map_err(|failure| SessionImportFailure {
|
||||
source_path: source_path.clone(),
|
||||
message: failure.message,
|
||||
stage: "session_prepare",
|
||||
sub_error_type: failure.sub_error_type,
|
||||
})?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let PendingSessionImport {
|
||||
source_path,
|
||||
source_content_sha256,
|
||||
target,
|
||||
attributed_mcp_server_ids,
|
||||
session,
|
||||
} = pending_import;
|
||||
match target {
|
||||
SessionImportTarget::New => self
|
||||
.create_session_import(
|
||||
source_path,
|
||||
source_content_sha256,
|
||||
attributed_mcp_server_ids,
|
||||
session,
|
||||
)
|
||||
.await
|
||||
.map(SessionImportOutcome::Created)
|
||||
.map(Some),
|
||||
SessionImportTarget::Existing {
|
||||
thread_id,
|
||||
expected_source_content_sha256,
|
||||
} => {
|
||||
let cwd = session.cwd.clone();
|
||||
let title = session.title.clone();
|
||||
let appended = append_existing_session(
|
||||
&self.codex_home,
|
||||
self.append_checkpoint_permits.as_ref(),
|
||||
self.thread_manager.as_ref(),
|
||||
self.thread_store.as_ref(),
|
||||
ExistingSessionAppend {
|
||||
source_path: &source_path,
|
||||
source_content_sha256: &source_content_sha256,
|
||||
expected_source_content_sha256: &expected_source_content_sha256,
|
||||
thread_id,
|
||||
source_items: &session.rollout_items,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
Ok(appended.then_some(SessionImportOutcome::Appended {
|
||||
cwd,
|
||||
source_path,
|
||||
imported_thread_id: thread_id,
|
||||
title,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_session_import(
|
||||
&self,
|
||||
source_path: PathBuf,
|
||||
source_content_sha256: String,
|
||||
attributed_mcp_server_ids: BTreeSet<String>,
|
||||
session: ImportedExternalAgentSession,
|
||||
) -> Result<CompletedSessionImport, SessionImportFailure> {
|
||||
let connector_attribution = source_path
|
||||
.file_stem()
|
||||
.and_then(|stem| stem.to_str())
|
||||
.map(str::trim)
|
||||
.filter(|session_id| !session_id.is_empty())
|
||||
.map(|session_id| ImportedSessionConnectorAttribution {
|
||||
session_id: session_id.to_string(),
|
||||
server_ids: attributed_mcp_server_ids,
|
||||
});
|
||||
let cwd = session.cwd.clone();
|
||||
let title = session.title.clone();
|
||||
let imported_thread_id =
|
||||
self.persist_session(session)
|
||||
.await
|
||||
.map_err(|failure| SessionImportFailure {
|
||||
source_path: source_path.clone(),
|
||||
message: failure.message,
|
||||
stage: "session_persist",
|
||||
sub_error_type: failure.sub_error_type,
|
||||
})?;
|
||||
Ok(CompletedSessionImport {
|
||||
cwd,
|
||||
import: CompletedExternalAgentSessionImport {
|
||||
source_path,
|
||||
source_content_sha256,
|
||||
imported_thread_id,
|
||||
connector_names: Vec::new(),
|
||||
title,
|
||||
},
|
||||
connector_attribution,
|
||||
})
|
||||
}
|
||||
|
||||
async fn prepare_session_import(
|
||||
&self,
|
||||
session: ExternalAgentSessionMigration,
|
||||
metadata_mode: SessionMetadataMode,
|
||||
) -> Result<Option<PendingSessionImport>, SessionImportStepFailure> {
|
||||
let codex_home = self.codex_home.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
prepare_validated_session_import_with_metadata_mode(&codex_home, session, metadata_mode)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"session_preparation_task_failed",
|
||||
format!("external agent session preparation task failed: {err}"),
|
||||
)
|
||||
})?
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"failed_to_prepare_session",
|
||||
format!("failed to prepare external agent session: {err}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
async fn persist_session(
|
||||
&self,
|
||||
session: ImportedExternalAgentSession,
|
||||
) -> Result<ThreadId, SessionImportStepFailure> {
|
||||
let ImportedExternalAgentSession {
|
||||
cwd,
|
||||
title,
|
||||
first_user_message,
|
||||
mut rollout_items,
|
||||
} = session;
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_with_overrides(
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides {
|
||||
cwd: Some(cwd),
|
||||
codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
let io_kind = match err.kind() {
|
||||
ErrorKind::NotFound => "not_found",
|
||||
ErrorKind::PermissionDenied => "permission_denied",
|
||||
ErrorKind::AlreadyExists => "already_exists",
|
||||
ErrorKind::InvalidInput => "invalid_input",
|
||||
ErrorKind::InvalidData => "invalid_data",
|
||||
ErrorKind::IsADirectory => "is_a_directory",
|
||||
ErrorKind::NotADirectory => "not_a_directory",
|
||||
ErrorKind::TimedOut => "timed_out",
|
||||
ErrorKind::WriteZero => "write_zero",
|
||||
ErrorKind::UnexpectedEof => "unexpected_eof",
|
||||
ErrorKind::StorageFull => "storage_full",
|
||||
ErrorKind::QuotaExceeded => "quota_exceeded",
|
||||
ErrorKind::FileTooLarge => "file_too_large",
|
||||
ErrorKind::ReadOnlyFilesystem => "read_only_filesystem",
|
||||
_ => "other",
|
||||
};
|
||||
SessionImportStepFailure::new(
|
||||
format!("failed_to_load_session_config_{io_kind}"),
|
||||
format!("failed to load imported session config: {err}"),
|
||||
)
|
||||
})?;
|
||||
let models_manager = self.thread_manager.get_models_manager();
|
||||
let model = models_manager
|
||||
.get_default_model(
|
||||
&config.model,
|
||||
/*allow_provider_model_fallback*/ false,
|
||||
RefreshStrategy::Offline,
|
||||
config.http_client_factory(),
|
||||
)
|
||||
.await;
|
||||
let model_info = models_manager
|
||||
.get_model_info(model.as_str(), &config.to_models_manager_config())
|
||||
.await;
|
||||
let thread_id = ThreadId::new();
|
||||
let source = self.thread_manager.session_source();
|
||||
let cwd = config.cwd.to_path_buf();
|
||||
let model_provider = config.model_provider_id.clone();
|
||||
let memory_mode = if config.memories.generate_memories {
|
||||
ThreadMemoryMode::Enabled
|
||||
} else {
|
||||
ThreadMemoryMode::Disabled
|
||||
};
|
||||
let now = Utc::now();
|
||||
let create_params = CreateThreadParams {
|
||||
attached_thread: false,
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
session_id: thread_id.into(),
|
||||
thread_id,
|
||||
extra_config: None,
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
source: source.clone(),
|
||||
thread_source: None,
|
||||
originator: codex_login::default_client::originator().value,
|
||||
base_instructions: BaseInstructions {
|
||||
text: config
|
||||
.base_instructions
|
||||
.clone()
|
||||
.unwrap_or_else(|| render_model_instructions(&model_info)),
|
||||
provenance: Some(config.base_instructions_provenance.clone().unwrap_or_else(
|
||||
|| {
|
||||
if config.base_instructions.is_some() {
|
||||
BaseInstructionsProvenance::Custom
|
||||
} else {
|
||||
BaseInstructionsProvenance::Model {
|
||||
model: model_info.slug.clone(),
|
||||
}
|
||||
}
|
||||
},
|
||||
)),
|
||||
},
|
||||
dynamic_tools: Vec::new(),
|
||||
selected_capability_roots: Vec::new(),
|
||||
runtime_workspace_roots: None,
|
||||
multi_agent_version: Some(MultiAgentVersion::V1),
|
||||
history_mode: ThreadHistoryMode::Legacy,
|
||||
history_base: None,
|
||||
subagent_history_start_ordinal: None,
|
||||
initial_window_id: codex_protocol::ContextWindowId::new_uuid_v7().to_string(),
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: Some(cwd.clone()),
|
||||
model_provider: model_provider.clone(),
|
||||
memory_mode,
|
||||
},
|
||||
};
|
||||
rollout_items = into_persisted_rollout_items(rollout_items, ThreadHistoryMode::Legacy);
|
||||
let (created_at, updated_at) = rollout_items
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(event)) => event.started_at,
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => event.completed_at,
|
||||
_ => None,
|
||||
})
|
||||
.fold(None, |chronology: Option<(i64, i64)>, timestamp| {
|
||||
Some(match chronology {
|
||||
Some((created_at, updated_at)) => {
|
||||
(created_at.min(timestamp), updated_at.max(timestamp))
|
||||
}
|
||||
None => (timestamp, timestamp),
|
||||
})
|
||||
})
|
||||
.and_then(|(created_at, updated_at)| {
|
||||
Some((
|
||||
DateTime::from_timestamp(created_at, /*nsecs*/ 0)?,
|
||||
DateTime::from_timestamp(updated_at, /*nsecs*/ 0)?,
|
||||
))
|
||||
})
|
||||
.unwrap_or((now, now));
|
||||
let title = title
|
||||
.as_deref()
|
||||
.and_then(codex_core::util::normalize_thread_name);
|
||||
let metadata = ThreadMetadataPatch {
|
||||
title,
|
||||
preview: first_user_message.clone(),
|
||||
model_provider: Some(model_provider),
|
||||
created_at: Some(created_at),
|
||||
updated_at: Some(updated_at),
|
||||
advance_recency_at: Some(updated_at),
|
||||
source: Some(source.clone()),
|
||||
thread_source: Some(None),
|
||||
agent_nickname: Some(source.get_nickname()),
|
||||
agent_role: Some(source.get_agent_role()),
|
||||
agent_path: Some(source.get_agent_path().map(Into::into)),
|
||||
cwd: Some(cwd),
|
||||
cli_version: Some(env!("CARGO_PKG_VERSION").to_string()),
|
||||
first_user_message,
|
||||
memory_mode: Some(memory_mode),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
self.thread_store
|
||||
.create_thread(create_params)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"failed_to_create_thread",
|
||||
format!("failed to import session: {err}"),
|
||||
)
|
||||
})?;
|
||||
if !rollout_items.is_empty()
|
||||
&& let Err(err) = self
|
||||
.thread_store
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id,
|
||||
items: rollout_items,
|
||||
})
|
||||
.await
|
||||
{
|
||||
let _ = self.thread_store.discard_thread(thread_id).await;
|
||||
return Err(SessionImportStepFailure::new(
|
||||
"failed_to_append_thread_items",
|
||||
format!("failed to import session: {err}"),
|
||||
));
|
||||
}
|
||||
|
||||
self.thread_store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
patch: metadata,
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"failed_to_update_thread_metadata",
|
||||
format!("failed to update imported session: {err}"),
|
||||
)
|
||||
})?;
|
||||
self.thread_store
|
||||
.persist_thread(thread_id, PersistContext::Standard)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"failed_to_persist_thread",
|
||||
format!("failed to persist imported session: {err}"),
|
||||
)
|
||||
})?;
|
||||
self.thread_store
|
||||
.shutdown_thread(thread_id)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"failed_to_shutdown_thread",
|
||||
format!("failed to shutdown imported session: {err}"),
|
||||
)
|
||||
})?;
|
||||
Ok(thread_id)
|
||||
}
|
||||
}
|
||||
|
||||
struct SessionImportFailure {
|
||||
source_path: PathBuf,
|
||||
message: String,
|
||||
stage: &'static str,
|
||||
sub_error_type: String,
|
||||
}
|
||||
|
||||
struct SessionImportStepFailure {
|
||||
sub_error_type: String,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl SessionImportStepFailure {
|
||||
fn new(sub_error_type: impl Into<String>, message: String) -> Self {
|
||||
Self {
|
||||
sub_error_type: sub_error_type.into(),
|
||||
message,
|
||||
}
|
||||
}
|
||||
}
|
||||
98
codex-rs/app-server/src/external_auth.rs
Normal file
98
codex-rs/app-server/src/external_auth.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use codex_app_server_protocol::ChatgptAuthTokensRefreshParams;
|
||||
use codex_app_server_protocol::ChatgptAuthTokensRefreshReason;
|
||||
use codex_app_server_protocol::ChatgptAuthTokensRefreshResponse;
|
||||
use codex_app_server_protocol::ServerRequestPayload;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::auth::ExternalAuth;
|
||||
use codex_login::auth::ExternalAuthRefreshContext;
|
||||
use codex_login::auth::ExternalAuthRefreshReason;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
|
||||
const EXTERNAL_AUTH_REFRESH_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
pub(crate) struct ExternalAuthBridge {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
auth: RwLock<CodexAuth>,
|
||||
}
|
||||
|
||||
impl ExternalAuthBridge {
|
||||
pub(crate) fn new(outgoing: Arc<OutgoingMessageSender>, auth: CodexAuth) -> Self {
|
||||
Self {
|
||||
outgoing,
|
||||
auth: RwLock::new(auth),
|
||||
}
|
||||
}
|
||||
|
||||
async fn refresh(&self, context: ExternalAuthRefreshContext) -> std::io::Result<CodexAuth> {
|
||||
let reason = match context.reason {
|
||||
ExternalAuthRefreshReason::Unauthorized => ChatgptAuthTokensRefreshReason::Unauthorized,
|
||||
};
|
||||
let params = ChatgptAuthTokensRefreshParams {
|
||||
reason,
|
||||
previous_account_id: context.previous_account_id,
|
||||
};
|
||||
|
||||
let (request_id, rx) = self
|
||||
.outgoing
|
||||
.send_request(ServerRequestPayload::ChatgptAuthTokensRefresh(params))
|
||||
.await;
|
||||
let result = match timeout(EXTERNAL_AUTH_REFRESH_TIMEOUT, rx).await {
|
||||
Ok(result) => {
|
||||
let result = result.map_err(|err| {
|
||||
std::io::Error::other(format!("auth refresh request canceled: {err}"))
|
||||
})?;
|
||||
result.map_err(|err| {
|
||||
// Don't log err.message because it may contain a token.
|
||||
let code = err.code;
|
||||
std::io::Error::other(format!("auth refresh request failed: code={code}"))
|
||||
})?
|
||||
}
|
||||
Err(_) => {
|
||||
let _canceled = self.outgoing.cancel_request(&request_id).await;
|
||||
return Err(std::io::Error::other(format!(
|
||||
"auth refresh request timed out after {}s",
|
||||
EXTERNAL_AUTH_REFRESH_TIMEOUT.as_secs()
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
// Don't propagate parser error messages because they may contain a token.
|
||||
let response: ChatgptAuthTokensRefreshResponse = serde_json::from_value(result)
|
||||
.map_err(|_| std::io::Error::other("invalid auth refresh response"))?;
|
||||
let auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
response.access_token.as_str(),
|
||||
response.chatgpt_account_id.as_str(),
|
||||
response.chatgpt_plan_type.as_deref(),
|
||||
)
|
||||
.map_err(|err| {
|
||||
std::io::Error::new(err.kind(), "auth refresh returned invalid credentials")
|
||||
})?;
|
||||
*self
|
||||
.auth
|
||||
.write()
|
||||
.map_err(|_| std::io::Error::other("external auth lock is poisoned"))? = auth.clone();
|
||||
Ok(auth)
|
||||
}
|
||||
}
|
||||
|
||||
impl ExternalAuth for ExternalAuthBridge {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async {
|
||||
self.auth
|
||||
.read()
|
||||
.map(|auth| auth.clone())
|
||||
.map_err(|_| std::io::Error::other("external auth lock is poisoned"))
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh(&self, context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(ExternalAuthBridge::refresh(self, context))
|
||||
}
|
||||
}
|
||||
158
codex-rs/app-server/src/filters.rs
Normal file
158
codex-rs/app-server/src/filters.rs
Normal file
@@ -0,0 +1,158 @@
|
||||
use codex_app_server_protocol::ThreadSourceKind;
|
||||
use codex_core::INTERACTIVE_SESSION_SOURCES;
|
||||
use codex_protocol::protocol::SessionSource as CoreSessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource as CoreSubAgentSource;
|
||||
|
||||
pub(crate) fn compute_source_filters(
|
||||
source_kinds: Option<Vec<ThreadSourceKind>>,
|
||||
) -> (Vec<CoreSessionSource>, Option<Vec<ThreadSourceKind>>) {
|
||||
let Some(source_kinds) = source_kinds else {
|
||||
return (INTERACTIVE_SESSION_SOURCES.to_vec(), None);
|
||||
};
|
||||
|
||||
if source_kinds.is_empty() {
|
||||
return (INTERACTIVE_SESSION_SOURCES.to_vec(), None);
|
||||
}
|
||||
|
||||
let requires_post_filter = source_kinds.iter().any(|kind| {
|
||||
matches!(
|
||||
kind,
|
||||
ThreadSourceKind::Exec
|
||||
| ThreadSourceKind::AppServer
|
||||
| ThreadSourceKind::SubAgent
|
||||
| ThreadSourceKind::SubAgentReview
|
||||
| ThreadSourceKind::SubAgentCompact
|
||||
| ThreadSourceKind::SubAgentThreadSpawn
|
||||
| ThreadSourceKind::SubAgentOther
|
||||
| ThreadSourceKind::Unknown
|
||||
)
|
||||
});
|
||||
|
||||
if requires_post_filter {
|
||||
(Vec::new(), Some(source_kinds))
|
||||
} else {
|
||||
let interactive_sources = source_kinds
|
||||
.iter()
|
||||
.filter_map(|kind| match kind {
|
||||
ThreadSourceKind::Cli => Some(CoreSessionSource::Cli),
|
||||
ThreadSourceKind::VsCode => Some(CoreSessionSource::VSCode),
|
||||
ThreadSourceKind::Exec
|
||||
| ThreadSourceKind::AppServer
|
||||
| ThreadSourceKind::SubAgent
|
||||
| ThreadSourceKind::SubAgentReview
|
||||
| ThreadSourceKind::SubAgentCompact
|
||||
| ThreadSourceKind::SubAgentThreadSpawn
|
||||
| ThreadSourceKind::SubAgentOther
|
||||
| ThreadSourceKind::Unknown => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
(interactive_sources, Some(source_kinds))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn source_kind_matches(source: &CoreSessionSource, filter: &[ThreadSourceKind]) -> bool {
|
||||
filter.iter().any(|kind| match kind {
|
||||
ThreadSourceKind::Cli => matches!(source, CoreSessionSource::Cli),
|
||||
ThreadSourceKind::VsCode => matches!(source, CoreSessionSource::VSCode),
|
||||
ThreadSourceKind::Exec => matches!(source, CoreSessionSource::Exec),
|
||||
ThreadSourceKind::AppServer => matches!(source, CoreSessionSource::Mcp),
|
||||
ThreadSourceKind::SubAgent => matches!(source, CoreSessionSource::SubAgent(_)),
|
||||
ThreadSourceKind::SubAgentReview => {
|
||||
matches!(
|
||||
source,
|
||||
CoreSessionSource::SubAgent(CoreSubAgentSource::Review)
|
||||
)
|
||||
}
|
||||
ThreadSourceKind::SubAgentCompact => {
|
||||
matches!(
|
||||
source,
|
||||
CoreSessionSource::SubAgent(CoreSubAgentSource::Compact)
|
||||
)
|
||||
}
|
||||
ThreadSourceKind::SubAgentThreadSpawn => matches!(
|
||||
source,
|
||||
CoreSessionSource::SubAgent(CoreSubAgentSource::ThreadSpawn { .. })
|
||||
),
|
||||
ThreadSourceKind::SubAgentOther => matches!(
|
||||
source,
|
||||
CoreSessionSource::SubAgent(CoreSubAgentSource::Other(_))
|
||||
),
|
||||
ThreadSourceKind::Unknown => matches!(source, CoreSessionSource::Unknown),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use codex_protocol::ThreadId;
|
||||
use pretty_assertions::assert_eq;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[test]
|
||||
fn compute_source_filters_defaults_to_interactive_sources() {
|
||||
let (allowed_sources, filter) = compute_source_filters(/*source_kinds*/ None);
|
||||
|
||||
assert_eq!(allowed_sources, INTERACTIVE_SESSION_SOURCES.to_vec());
|
||||
assert_eq!(filter, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_source_filters_empty_means_interactive_sources() {
|
||||
let (allowed_sources, filter) = compute_source_filters(Some(Vec::new()));
|
||||
|
||||
assert_eq!(allowed_sources, INTERACTIVE_SESSION_SOURCES.to_vec());
|
||||
assert_eq!(filter, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_source_filters_interactive_only_skips_post_filtering() {
|
||||
let source_kinds = vec![ThreadSourceKind::Cli, ThreadSourceKind::VsCode];
|
||||
let (allowed_sources, filter) = compute_source_filters(Some(source_kinds.clone()));
|
||||
|
||||
assert_eq!(
|
||||
allowed_sources,
|
||||
vec![CoreSessionSource::Cli, CoreSessionSource::VSCode]
|
||||
);
|
||||
assert_eq!(filter, Some(source_kinds));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_source_filters_subagent_variant_requires_post_filtering() {
|
||||
let source_kinds = vec![ThreadSourceKind::SubAgentReview];
|
||||
let (allowed_sources, filter) = compute_source_filters(Some(source_kinds.clone()));
|
||||
|
||||
assert_eq!(allowed_sources, Vec::new());
|
||||
assert_eq!(filter, Some(source_kinds));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_kind_matches_distinguishes_subagent_variants() {
|
||||
let parent_thread_id =
|
||||
ThreadId::from_string(&Uuid::new_v4().to_string()).expect("valid thread id");
|
||||
let review = CoreSessionSource::SubAgent(CoreSubAgentSource::Review);
|
||||
let spawn = CoreSessionSource::SubAgent(CoreSubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
depth: 1,
|
||||
agent_path: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
});
|
||||
|
||||
assert!(source_kind_matches(
|
||||
&review,
|
||||
&[ThreadSourceKind::SubAgentReview]
|
||||
));
|
||||
assert!(!source_kind_matches(
|
||||
&review,
|
||||
&[ThreadSourceKind::SubAgentThreadSpawn]
|
||||
));
|
||||
assert!(source_kind_matches(
|
||||
&spawn,
|
||||
&[ThreadSourceKind::SubAgentThreadSpawn]
|
||||
));
|
||||
assert!(!source_kind_matches(
|
||||
&spawn,
|
||||
&[ThreadSourceKind::SubAgentReview]
|
||||
));
|
||||
}
|
||||
}
|
||||
377
codex-rs/app-server/src/fs_watch.rs
Normal file
377
codex-rs/app-server/src/fs_watch.rs
Normal file
@@ -0,0 +1,377 @@
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use codex_app_server_protocol::FsChangedNotification;
|
||||
use codex_app_server_protocol::FsUnwatchParams;
|
||||
use codex_app_server_protocol::FsUnwatchResponse;
|
||||
use codex_app_server_protocol::FsWatchParams;
|
||||
use codex_app_server_protocol::FsWatchResponse;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_file_watcher::DebouncedWatchReceiver;
|
||||
use codex_file_watcher::FileWatcher;
|
||||
use codex_file_watcher::FileWatcherSubscriber;
|
||||
use codex_file_watcher::WatchPath;
|
||||
use codex_file_watcher::WatchRegistration;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::hash::Hash;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Mutex as AsyncMutex;
|
||||
#[cfg(test)]
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tracing::warn;
|
||||
|
||||
const FS_CHANGED_NOTIFICATION_DEBOUNCE: Duration = Duration::from_millis(200);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct FsWatchManager {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
file_watcher: Arc<FileWatcher>,
|
||||
state: Arc<AsyncMutex<FsWatchState>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FsWatchState {
|
||||
entries: HashMap<WatchKey, WatchEntry>,
|
||||
}
|
||||
|
||||
struct WatchEntry {
|
||||
terminate_tx: oneshot::Sender<oneshot::Sender<()>>,
|
||||
_subscriber: FileWatcherSubscriber,
|
||||
_registration: WatchRegistration,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
struct WatchKey {
|
||||
connection_id: ConnectionId,
|
||||
watch_id: String,
|
||||
}
|
||||
|
||||
impl FsWatchManager {
|
||||
pub(crate) fn new(outgoing: Arc<OutgoingMessageSender>) -> Self {
|
||||
let file_watcher = match FileWatcher::new() {
|
||||
Ok(file_watcher) => Arc::new(file_watcher),
|
||||
Err(err) => {
|
||||
warn!("filesystem watch manager falling back to noop core watcher: {err}");
|
||||
Arc::new(FileWatcher::noop())
|
||||
}
|
||||
};
|
||||
Self::new_with_file_watcher(outgoing, file_watcher)
|
||||
}
|
||||
|
||||
fn new_with_file_watcher(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
file_watcher: Arc<FileWatcher>,
|
||||
) -> Self {
|
||||
Self {
|
||||
outgoing,
|
||||
file_watcher,
|
||||
state: Arc::new(AsyncMutex::new(FsWatchState::default())),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn watch(
|
||||
&self,
|
||||
connection_id: ConnectionId,
|
||||
params: FsWatchParams,
|
||||
) -> Result<FsWatchResponse, JSONRPCErrorError> {
|
||||
let watch_id = params.watch_id;
|
||||
let watch_key = WatchKey {
|
||||
connection_id,
|
||||
watch_id: watch_id.clone(),
|
||||
};
|
||||
let outgoing = self.outgoing.clone();
|
||||
let (subscriber, rx) = self.file_watcher.add_subscriber();
|
||||
let watch_root = params.path.clone();
|
||||
let registration = subscriber.register_paths(vec![WatchPath {
|
||||
path: params.path.to_path_buf(),
|
||||
recursive: false,
|
||||
}]);
|
||||
let (terminate_tx, terminate_rx) = oneshot::channel();
|
||||
|
||||
match self.state.lock().await.entries.entry(watch_key) {
|
||||
Entry::Occupied(_) => {
|
||||
return Err(invalid_request(format!(
|
||||
"watchId already exists: {watch_id}"
|
||||
)));
|
||||
}
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert(WatchEntry {
|
||||
terminate_tx,
|
||||
_subscriber: subscriber,
|
||||
_registration: registration,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let task_watch_id = watch_id.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut rx = DebouncedWatchReceiver::new(rx, FS_CHANGED_NOTIFICATION_DEBOUNCE);
|
||||
tokio::pin!(terminate_rx);
|
||||
loop {
|
||||
let event = tokio::select! {
|
||||
biased;
|
||||
_ = &mut terminate_rx => break,
|
||||
event = rx.recv() => match event {
|
||||
Some(event) => event,
|
||||
None => break,
|
||||
},
|
||||
};
|
||||
let mut changed_paths = event
|
||||
.paths
|
||||
.into_iter()
|
||||
.map(|path| watch_root.join(path))
|
||||
.collect::<Vec<_>>();
|
||||
changed_paths.sort_by(|left, right| left.as_path().cmp(right.as_path()));
|
||||
if !changed_paths.is_empty() {
|
||||
outgoing
|
||||
.send_server_notification_to_connection_and_wait(
|
||||
connection_id,
|
||||
ServerNotification::FsChanged(FsChangedNotification {
|
||||
watch_id: task_watch_id.clone(),
|
||||
changed_paths,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(FsWatchResponse { path: params.path })
|
||||
}
|
||||
|
||||
pub(crate) async fn unwatch(
|
||||
&self,
|
||||
connection_id: ConnectionId,
|
||||
params: FsUnwatchParams,
|
||||
) -> Result<FsUnwatchResponse, JSONRPCErrorError> {
|
||||
let watch_key = WatchKey {
|
||||
connection_id,
|
||||
watch_id: params.watch_id,
|
||||
};
|
||||
let entry = self.state.lock().await.entries.remove(&watch_key);
|
||||
if let Some(entry) = entry {
|
||||
// Wait for the oneshot to be destroyed by the task to ensure that no notifications
|
||||
// are send after the unwatch response.
|
||||
let (done_tx, done_rx) = oneshot::channel();
|
||||
let _ = entry.terminate_tx.send(done_tx);
|
||||
let _ = done_rx.await;
|
||||
}
|
||||
Ok(FsUnwatchResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn connection_closed(&self, connection_id: ConnectionId) {
|
||||
let mut state = self.state.lock().await;
|
||||
state
|
||||
.entries
|
||||
.extract_if(|key, _| key.connection_id == connection_id)
|
||||
.count();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn absolute_path(path: PathBuf) -> AbsolutePathBuf {
|
||||
assert!(
|
||||
path.is_absolute(),
|
||||
"path must be absolute: {}",
|
||||
path.display()
|
||||
);
|
||||
AbsolutePathBuf::try_from(path).expect("path should be absolute")
|
||||
}
|
||||
|
||||
fn manager_with_noop_watcher() -> FsWatchManager {
|
||||
const OUTGOING_BUFFER: usize = 1;
|
||||
let (tx, _rx) = mpsc::channel(OUTGOING_BUFFER);
|
||||
FsWatchManager::new_with_file_watcher(
|
||||
Arc::new(OutgoingMessageSender::new(
|
||||
tx,
|
||||
codex_analytics::AnalyticsEventsClient::disabled(),
|
||||
)),
|
||||
Arc::new(FileWatcher::noop()),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn watch_uses_client_id_and_tracks_the_owner_scoped_entry() {
|
||||
let temp_dir = TempDir::new().expect("temp dir");
|
||||
let head_path = temp_dir.path().join("HEAD");
|
||||
std::fs::write(&head_path, "ref: refs/heads/main\n").expect("write HEAD");
|
||||
|
||||
let manager = manager_with_noop_watcher();
|
||||
let path = absolute_path(head_path);
|
||||
let watch_id = "watch-head".to_string();
|
||||
let response = manager
|
||||
.watch(
|
||||
ConnectionId(1),
|
||||
FsWatchParams {
|
||||
watch_id: watch_id.clone(),
|
||||
path: path.clone(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("watch should succeed");
|
||||
|
||||
assert_eq!(response.path, path);
|
||||
|
||||
let state = manager.state.lock().await;
|
||||
assert_eq!(
|
||||
state.entries.keys().cloned().collect::<HashSet<_>>(),
|
||||
HashSet::from([WatchKey {
|
||||
connection_id: ConnectionId(1),
|
||||
watch_id,
|
||||
}])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unwatch_is_scoped_to_the_connection_that_created_the_watch() {
|
||||
let temp_dir = TempDir::new().expect("temp dir");
|
||||
let head_path = temp_dir.path().join("HEAD");
|
||||
std::fs::write(&head_path, "ref: refs/heads/main\n").expect("write HEAD");
|
||||
|
||||
let manager = manager_with_noop_watcher();
|
||||
manager
|
||||
.watch(
|
||||
ConnectionId(1),
|
||||
FsWatchParams {
|
||||
watch_id: "watch-head".to_string(),
|
||||
path: absolute_path(head_path),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("watch should succeed");
|
||||
let watch_key = WatchKey {
|
||||
connection_id: ConnectionId(1),
|
||||
watch_id: "watch-head".to_string(),
|
||||
};
|
||||
|
||||
manager
|
||||
.unwatch(
|
||||
ConnectionId(2),
|
||||
FsUnwatchParams {
|
||||
watch_id: "watch-head".to_string(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("foreign unwatch should be a no-op");
|
||||
assert!(manager.state.lock().await.entries.contains_key(&watch_key));
|
||||
|
||||
manager
|
||||
.unwatch(
|
||||
ConnectionId(1),
|
||||
FsUnwatchParams {
|
||||
watch_id: "watch-head".to_string(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("owner unwatch should succeed");
|
||||
assert!(!manager.state.lock().await.entries.contains_key(&watch_key));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn watch_rejects_duplicate_id_for_the_same_connection() {
|
||||
let temp_dir = TempDir::new().expect("temp dir");
|
||||
let head_path = temp_dir.path().join("HEAD");
|
||||
let fetch_head_path = temp_dir.path().join("FETCH_HEAD");
|
||||
std::fs::write(&head_path, "ref: refs/heads/main\n").expect("write HEAD");
|
||||
std::fs::write(&fetch_head_path, "old-fetch\n").expect("write FETCH_HEAD");
|
||||
|
||||
let manager = manager_with_noop_watcher();
|
||||
manager
|
||||
.watch(
|
||||
ConnectionId(1),
|
||||
FsWatchParams {
|
||||
watch_id: "watch-head".to_string(),
|
||||
path: absolute_path(head_path),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("first watch should succeed");
|
||||
|
||||
let error = manager
|
||||
.watch(
|
||||
ConnectionId(1),
|
||||
FsWatchParams {
|
||||
watch_id: "watch-head".to_string(),
|
||||
path: absolute_path(fetch_head_path),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("duplicate watch should fail");
|
||||
|
||||
assert_eq!(error.message, "watchId already exists: watch-head");
|
||||
assert_eq!(manager.state.lock().await.entries.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_closed_removes_only_that_connections_watches() {
|
||||
let temp_dir = TempDir::new().expect("temp dir");
|
||||
let head_path = temp_dir.path().join("HEAD");
|
||||
let fetch_head_path = temp_dir.path().join("FETCH_HEAD");
|
||||
let packed_refs_path = temp_dir.path().join("packed-refs");
|
||||
std::fs::write(&head_path, "ref: refs/heads/main\n").expect("write HEAD");
|
||||
std::fs::write(&fetch_head_path, "old-fetch\n").expect("write FETCH_HEAD");
|
||||
std::fs::write(&packed_refs_path, "refs\n").expect("write packed-refs");
|
||||
|
||||
let manager = manager_with_noop_watcher();
|
||||
let response = manager
|
||||
.watch(
|
||||
ConnectionId(1),
|
||||
FsWatchParams {
|
||||
watch_id: "watch-head".to_string(),
|
||||
path: absolute_path(head_path.clone()),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("first watch should succeed");
|
||||
manager
|
||||
.watch(
|
||||
ConnectionId(1),
|
||||
FsWatchParams {
|
||||
watch_id: "watch-fetch-head".to_string(),
|
||||
path: absolute_path(fetch_head_path),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("second watch should succeed");
|
||||
manager
|
||||
.watch(
|
||||
ConnectionId(2),
|
||||
FsWatchParams {
|
||||
watch_id: "watch-packed-refs".to_string(),
|
||||
path: absolute_path(packed_refs_path),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("third watch should succeed");
|
||||
|
||||
manager.connection_closed(ConnectionId(1)).await;
|
||||
|
||||
assert_eq!(
|
||||
manager
|
||||
.state
|
||||
.lock()
|
||||
.await
|
||||
.entries
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<HashSet<_>>(),
|
||||
HashSet::from([WatchKey {
|
||||
connection_id: ConnectionId(2),
|
||||
watch_id: "watch-packed-refs".to_string(),
|
||||
}])
|
||||
);
|
||||
assert_eq!(response.path, absolute_path(head_path));
|
||||
}
|
||||
}
|
||||
256
codex-rs/app-server/src/fuzzy_file_search.rs
Normal file
256
codex-rs/app-server/src/fuzzy_file_search.rs
Normal file
@@ -0,0 +1,256 @@
|
||||
use std::num::NonZero;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_app_server_protocol::FuzzyFileSearchMatchType;
|
||||
use codex_app_server_protocol::FuzzyFileSearchResult;
|
||||
use codex_app_server_protocol::FuzzyFileSearchSessionCompletedNotification;
|
||||
use codex_app_server_protocol::FuzzyFileSearchSessionUpdatedNotification;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_file_search as file_search;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
|
||||
const MATCH_LIMIT: usize = 50;
|
||||
const MAX_THREADS: usize = 12;
|
||||
|
||||
pub(crate) async fn run_fuzzy_file_search(
|
||||
query: String,
|
||||
roots: Vec<String>,
|
||||
cancellation_flag: Arc<AtomicBool>,
|
||||
) -> Vec<FuzzyFileSearchResult> {
|
||||
if roots.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
#[expect(clippy::expect_used)]
|
||||
let limit = NonZero::new(MATCH_LIMIT).expect("MATCH_LIMIT should be a valid non-zero usize");
|
||||
|
||||
let cores = std::thread::available_parallelism()
|
||||
.map(std::num::NonZero::get)
|
||||
.unwrap_or(1);
|
||||
let threads = cores.min(MAX_THREADS);
|
||||
#[expect(clippy::expect_used)]
|
||||
let threads = NonZero::new(threads.max(1)).expect("threads should be non-zero");
|
||||
let search_dirs: Vec<PathBuf> = roots.iter().map(PathBuf::from).collect();
|
||||
|
||||
let mut files = match tokio::task::spawn_blocking(move || {
|
||||
file_search::run(
|
||||
query.as_str(),
|
||||
search_dirs,
|
||||
file_search::FileSearchOptions {
|
||||
limit,
|
||||
threads,
|
||||
compute_indices: true,
|
||||
..Default::default()
|
||||
},
|
||||
Some(cancellation_flag),
|
||||
)
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(Ok(res)) => res
|
||||
.matches
|
||||
.into_iter()
|
||||
.map(|m| {
|
||||
let file_name = m.path.file_name().unwrap_or_default();
|
||||
FuzzyFileSearchResult {
|
||||
root: m.root.to_string_lossy().to_string(),
|
||||
path: m.path.to_string_lossy().to_string(),
|
||||
match_type: match m.match_type {
|
||||
file_search::MatchType::File => FuzzyFileSearchMatchType::File,
|
||||
file_search::MatchType::Directory => FuzzyFileSearchMatchType::Directory,
|
||||
},
|
||||
file_name: file_name.to_string_lossy().to_string(),
|
||||
score: m.score,
|
||||
indices: m.indices,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
Ok(Err(err)) => {
|
||||
warn!("fuzzy-file-search failed: {err}");
|
||||
Vec::new()
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("fuzzy-file-search join failed: {err}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
|
||||
files.sort_by(file_search::cmp_by_score_desc_then_path_asc::<
|
||||
FuzzyFileSearchResult,
|
||||
_,
|
||||
_,
|
||||
>(|f| f.score, |f| f.path.as_str()));
|
||||
|
||||
files
|
||||
}
|
||||
|
||||
pub(crate) struct FuzzyFileSearchSession {
|
||||
session: file_search::FileSearchSession,
|
||||
shared: Arc<SessionShared>,
|
||||
}
|
||||
|
||||
impl FuzzyFileSearchSession {
|
||||
pub(crate) fn update_query(&self, query: String) {
|
||||
if self.shared.canceled.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
{
|
||||
#[expect(clippy::unwrap_used)]
|
||||
let mut latest_query = self.shared.latest_query.lock().unwrap();
|
||||
*latest_query = query.clone();
|
||||
}
|
||||
self.session.update_query(&query);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FuzzyFileSearchSession {
|
||||
fn drop(&mut self) {
|
||||
self.shared.canceled.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn start_fuzzy_file_search_session(
|
||||
session_id: String,
|
||||
roots: Vec<String>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
) -> anyhow::Result<FuzzyFileSearchSession> {
|
||||
#[expect(clippy::expect_used)]
|
||||
let limit = NonZero::new(MATCH_LIMIT).expect("MATCH_LIMIT should be a valid non-zero usize");
|
||||
let cores = std::thread::available_parallelism()
|
||||
.map(std::num::NonZero::get)
|
||||
.unwrap_or(1);
|
||||
let threads = cores.min(MAX_THREADS);
|
||||
#[expect(clippy::expect_used)]
|
||||
let threads = NonZero::new(threads.max(1)).expect("threads should be non-zero");
|
||||
let search_dirs: Vec<PathBuf> = roots.iter().map(PathBuf::from).collect();
|
||||
let canceled = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let shared = Arc::new(SessionShared {
|
||||
session_id,
|
||||
latest_query: Mutex::new(String::new()),
|
||||
outgoing,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
canceled: canceled.clone(),
|
||||
});
|
||||
|
||||
let reporter = Arc::new(SessionReporterImpl {
|
||||
shared: shared.clone(),
|
||||
});
|
||||
let session = file_search::create_session(
|
||||
search_dirs,
|
||||
file_search::FileSearchOptions {
|
||||
limit,
|
||||
threads,
|
||||
compute_indices: true,
|
||||
..Default::default()
|
||||
},
|
||||
reporter,
|
||||
Some(canceled),
|
||||
)?;
|
||||
|
||||
Ok(FuzzyFileSearchSession { session, shared })
|
||||
}
|
||||
|
||||
struct SessionShared {
|
||||
session_id: String,
|
||||
latest_query: Mutex<String>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
runtime: tokio::runtime::Handle,
|
||||
canceled: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
struct SessionReporterImpl {
|
||||
shared: Arc<SessionShared>,
|
||||
}
|
||||
|
||||
impl SessionReporterImpl {
|
||||
fn send_snapshot(&self, snapshot: &file_search::FileSearchSnapshot) {
|
||||
if self.shared.canceled.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
|
||||
let query = {
|
||||
#[expect(clippy::unwrap_used)]
|
||||
self.shared.latest_query.lock().unwrap().clone()
|
||||
};
|
||||
if snapshot.query != query {
|
||||
return;
|
||||
}
|
||||
|
||||
let files = if query.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
collect_files(snapshot)
|
||||
};
|
||||
|
||||
let notification = ServerNotification::FuzzyFileSearchSessionUpdated(
|
||||
FuzzyFileSearchSessionUpdatedNotification {
|
||||
session_id: self.shared.session_id.clone(),
|
||||
query,
|
||||
files,
|
||||
},
|
||||
);
|
||||
let outgoing = self.shared.outgoing.clone();
|
||||
self.shared.runtime.spawn(async move {
|
||||
outgoing.send_server_notification(notification).await;
|
||||
});
|
||||
}
|
||||
|
||||
fn send_complete(&self) {
|
||||
if self.shared.canceled.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let session_id = self.shared.session_id.clone();
|
||||
let outgoing = self.shared.outgoing.clone();
|
||||
self.shared.runtime.spawn(async move {
|
||||
let notification = ServerNotification::FuzzyFileSearchSessionCompleted(
|
||||
FuzzyFileSearchSessionCompletedNotification { session_id },
|
||||
);
|
||||
outgoing.send_server_notification(notification).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl file_search::SessionReporter for SessionReporterImpl {
|
||||
fn on_update(&self, snapshot: &file_search::FileSearchSnapshot) {
|
||||
self.send_snapshot(snapshot);
|
||||
}
|
||||
|
||||
fn on_complete(&self) {
|
||||
self.send_complete();
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_files(snapshot: &file_search::FileSearchSnapshot) -> Vec<FuzzyFileSearchResult> {
|
||||
let mut files = snapshot
|
||||
.matches
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let file_name = m.path.file_name().unwrap_or_default();
|
||||
FuzzyFileSearchResult {
|
||||
root: m.root.to_string_lossy().to_string(),
|
||||
path: m.path.to_string_lossy().to_string(),
|
||||
match_type: match m.match_type {
|
||||
file_search::MatchType::File => FuzzyFileSearchMatchType::File,
|
||||
file_search::MatchType::Directory => FuzzyFileSearchMatchType::Directory,
|
||||
},
|
||||
file_name: file_name.to_string_lossy().to_string(),
|
||||
score: m.score,
|
||||
indices: m.indices.clone(),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
files.sort_by(file_search::cmp_by_score_desc_then_path_asc::<
|
||||
FuzzyFileSearchResult,
|
||||
_,
|
||||
_,
|
||||
>(|f| f.score, |f| f.path.as_str()));
|
||||
files
|
||||
}
|
||||
68
codex-rs/app-server/src/gateway_oauth_notifications.rs
Normal file
68
codex-rs/app-server/src/gateway_oauth_notifications.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
//! Forward OAuth progress for every configured provider sharing the changed grant.
|
||||
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use codex_app_server_protocol::GatewayOAuthChangedNotification;
|
||||
use codex_app_server_protocol::GatewayOAuthStatus;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::GatewayAuthStatus;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
pub(crate) fn status_fields(status: GatewayAuthStatus) -> (GatewayOAuthStatus, Option<String>) {
|
||||
match status {
|
||||
GatewayAuthStatus::NotReady => (GatewayOAuthStatus::NotReady, None),
|
||||
GatewayAuthStatus::Started => (GatewayOAuthStatus::Started, None),
|
||||
GatewayAuthStatus::Succeeded => (GatewayOAuthStatus::Succeeded, None),
|
||||
GatewayAuthStatus::Failed { message } => (GatewayOAuthStatus::Failed, Some(message)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn spawn(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
config_manager: ConfigManager,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
) -> AbortOnDropHandle<()> {
|
||||
let mut events = codex_login::subscribe_gateway_auth_status(&auth_manager.runtime_config());
|
||||
AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
loop {
|
||||
let change = match events.recv().await {
|
||||
Ok(change) => change,
|
||||
Err(RecvError::Lagged(_)) => continue,
|
||||
Err(RecvError::Closed) => break,
|
||||
};
|
||||
let Ok(config) = config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
for (provider_id, provider) in &config.model_providers {
|
||||
let Ok(Some(manager)) = codex_model_provider::create_model_provider(
|
||||
provider.clone(),
|
||||
Some(Arc::clone(&auth_manager)),
|
||||
)
|
||||
.gateway_auth_manager() else {
|
||||
continue;
|
||||
};
|
||||
if !matches!(manager.oauth_session(), Some(oauth) if oauth.config() == &change.config)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let (status, error) = status_fields(change.status.clone());
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::GatewayOAuthChanged(
|
||||
GatewayOAuthChangedNotification {
|
||||
auth_url: None,
|
||||
provider_id: provider_id.clone(),
|
||||
status,
|
||||
error,
|
||||
},
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
8
codex-rs/app-server/src/image_url.rs
Normal file
8
codex-rs/app-server/src/image_url.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
pub(crate) const REMOTE_IMAGE_URL_ERROR: &str =
|
||||
"remote image URLs are not supported; use an inline data URL instead";
|
||||
|
||||
pub(crate) fn is_remote_image_url(image_url: &str) -> bool {
|
||||
image_url.split_once(':').is_some_and(|(scheme, _)| {
|
||||
scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")
|
||||
})
|
||||
}
|
||||
1451
codex-rs/app-server/src/in_process.rs
Normal file
1451
codex-rs/app-server/src/in_process.rs
Normal file
File diff suppressed because it is too large
Load Diff
177
codex-rs/app-server/src/in_process_bootstrap.rs
Normal file
177
codex-rs/app-server/src/in_process_bootstrap.rs
Normal file
@@ -0,0 +1,177 @@
|
||||
//! Loads embedded application policy and builds serving authentication from effective requirements.
|
||||
//! Workspace policy uses stored auth even when the caller uses an environment API key.
|
||||
//! Caller credential storage remains intact; initialization receives the effective URL and residency.
|
||||
|
||||
use crate::config_manager::ConfigManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_login::AuthManager;
|
||||
use std::io::Error as IoError;
|
||||
use std::io::Result as IoResult;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Policy shared by transports created before and owned by the embedded app-server.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct EmbeddedNetworkPolicy {
|
||||
pub(crate) effective: codex_http_client::NetworkPolicyController,
|
||||
pub(crate) local: codex_http_client::NetworkPolicyController,
|
||||
}
|
||||
|
||||
impl EmbeddedNetworkPolicy {
|
||||
/// Loads the local rules for cloud bootstrap; all other traffic starts unavailable.
|
||||
pub async fn load(overrides: &codex_config::LoaderOverrides) -> Self {
|
||||
let policy = Self::default();
|
||||
let local = async {
|
||||
codex_config::loader::load_local_application_requirements(
|
||||
codex_exec_server::LOCAL_FS.as_ref(),
|
||||
overrides,
|
||||
)
|
||||
.await?
|
||||
.compose(Default::default())
|
||||
}
|
||||
.await;
|
||||
if let Ok(application) = local {
|
||||
policy.local.publish(
|
||||
policy.local.policy().revision(),
|
||||
crate::config_manager::application_network::destination_policy(
|
||||
application.as_ref(),
|
||||
),
|
||||
);
|
||||
}
|
||||
policy
|
||||
}
|
||||
|
||||
/// Attaches the live application policy before an environment can start connecting.
|
||||
pub fn bind(
|
||||
&self,
|
||||
factory: codex_http_client::HttpClientFactory,
|
||||
) -> codex_http_client::HttpClientFactory {
|
||||
factory.with_network_policy(self.effective.policy())
|
||||
}
|
||||
|
||||
/// Publishes successfully loaded requirements before caller-owned clients are created.
|
||||
pub fn activate(&self, config: &mut Config) {
|
||||
let application = config
|
||||
.config_layer_stack
|
||||
.requirements()
|
||||
.application
|
||||
.as_ref()
|
||||
.map(|requirements| &requirements.value);
|
||||
self.effective.publish(
|
||||
self.effective.policy().revision(),
|
||||
crate::config_manager::application_network::destination_policy(application),
|
||||
);
|
||||
self.bind_config(config);
|
||||
}
|
||||
|
||||
/// Keeps a rebuilt caller config on the live policy owned by the running app-server.
|
||||
pub fn bind_config(&self, config: &mut Config) {
|
||||
config.application_network_policy = self.effective.policy();
|
||||
}
|
||||
|
||||
/// Limits cloud discovery and each authentication request to their exact local-policy endpoints.
|
||||
pub fn bind_bootstrap_auth(
|
||||
&self,
|
||||
mut auth: codex_login::AuthConfig,
|
||||
) -> codex_login::AuthConfig {
|
||||
let factory = auth
|
||||
.auth_route_config
|
||||
.http_client_factory()
|
||||
.clone()
|
||||
.with_network_policy(self.local.policy());
|
||||
let endpoint = codex_backend_client::Client::new(
|
||||
auth.chatgpt_base_url
|
||||
.as_deref()
|
||||
.unwrap_or("https://chatgpt.com/backend-api/"),
|
||||
factory.clone(),
|
||||
)
|
||||
.config_bundle_url();
|
||||
auth.auth_route_config = codex_login::AuthRouteConfig::from_http_client_factory(
|
||||
factory.clone().with_network_policy(
|
||||
self.local
|
||||
.policy()
|
||||
.restrict_to_endpoints(endpoint.parse().into_iter().collect()),
|
||||
),
|
||||
)
|
||||
.with_local_bootstrap_factory(factory)
|
||||
.with_application_network_policy(self.effective.policy());
|
||||
auth
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn configure(
|
||||
config_manager: &ConfigManager,
|
||||
config: &mut Arc<Config>,
|
||||
enable_codex_api_key_env: bool,
|
||||
) -> IoResult<Arc<AuthManager>> {
|
||||
let bootstrap_config = config_manager
|
||||
.load_startup_config(Some(config.cwd.to_path_buf()))
|
||||
.await?
|
||||
.config;
|
||||
let caller_auth = config.auth_config();
|
||||
let bootstrap_auth = codex_login::AuthConfig {
|
||||
chatgpt_base_url: Some(bootstrap_config.chatgpt_base_url.clone()),
|
||||
forced_login_method: bootstrap_config.forced_login_method,
|
||||
forced_chatgpt_workspace_id: bootstrap_config.forced_chatgpt_workspace_id.clone(),
|
||||
managed_auth_policy: bootstrap_config
|
||||
.config_layer_stack
|
||||
.requirements()
|
||||
.managed_auth_policy(),
|
||||
auth_route_config: bootstrap_config.auth_route_config(),
|
||||
..caller_auth.clone()
|
||||
};
|
||||
bootstrap_auth.validate()?;
|
||||
let bootstrap_auth_manager = AuthManager::shared_from_auth_config(
|
||||
bootstrap_auth,
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await
|
||||
.map_err(IoError::other)?;
|
||||
config_manager.update_managed_config_loader(bootstrap_auth_manager, &bootstrap_config);
|
||||
let policy_config = config_manager
|
||||
.load_startup_config(Some(config.cwd.to_path_buf()))
|
||||
.await?
|
||||
.config;
|
||||
config.validate_windows_mxc_requirement_from(&policy_config)?;
|
||||
let auth_config = codex_login::AuthConfig {
|
||||
chatgpt_base_url: Some(policy_config.chatgpt_base_url.clone()),
|
||||
forced_login_method: policy_config.forced_login_method,
|
||||
forced_chatgpt_workspace_id: policy_config.forced_chatgpt_workspace_id.clone(),
|
||||
managed_auth_policy: policy_config
|
||||
.config_layer_stack
|
||||
.requirements()
|
||||
.managed_auth_policy(),
|
||||
auth_route_config: policy_config.auth_route_config(),
|
||||
..caller_auth
|
||||
};
|
||||
auth_config.validate()?;
|
||||
let policy_auth_manager = AuthManager::shared_from_auth_config(
|
||||
auth_config.clone(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await
|
||||
.map_err(IoError::other)?;
|
||||
let auth_manager = if enable_codex_api_key_env {
|
||||
AuthManager::shared_from_auth_config(auth_config, /*enable_codex_api_key_env*/ true)
|
||||
.await
|
||||
.map_err(IoError::other)?
|
||||
} else {
|
||||
policy_auth_manager.clone()
|
||||
};
|
||||
let config = Arc::make_mut(config);
|
||||
config.chatgpt_base_url = policy_config.chatgpt_base_url;
|
||||
config.chatgpt_base_url_is_explicit = policy_config.chatgpt_base_url_is_explicit;
|
||||
config.enforce_residency = policy_config.enforce_residency;
|
||||
config.application_network_policy = policy_config.application_network_policy;
|
||||
config.application_auth_route_config = policy_config.application_auth_route_config;
|
||||
config.forced_login_method = policy_config.forced_login_method;
|
||||
config.forced_chatgpt_workspace_id = policy_config.forced_chatgpt_workspace_id;
|
||||
config_manager.update_managed_config_loader(policy_auth_manager, config);
|
||||
codex_login::default_client::set_default_client_residency_requirement(
|
||||
config.enforce_residency.value(),
|
||||
);
|
||||
Ok(auth_manager)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "in_process_bootstrap_tests.rs"]
|
||||
mod tests;
|
||||
234
codex-rs/app-server/src/in_process_bootstrap_tests.rs
Normal file
234
codex-rs/app-server/src/in_process_bootstrap_tests.rs
Normal file
@@ -0,0 +1,234 @@
|
||||
//! Embedded startup preserves caller configuration and bootstrap access across authentication.
|
||||
|
||||
use super::EmbeddedNetworkPolicy;
|
||||
use super::configure;
|
||||
use crate::config_manager::ConfigManager;
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::NoopThreadConfigLoader;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_core::config::set_project_trust_level;
|
||||
use codex_http_client::DestinationPolicy;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::NetworkPermit;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use codex_model_provider::DEFAULT_CHATGPT_BASE_URL;
|
||||
use codex_protocol::config_types::TrustLevel;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct BootstrapExternalAuth(CodexAuth);
|
||||
|
||||
impl ExternalAuth for BootstrapExternalAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
|
||||
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bootstrap_discovery_survives_identity_installation_but_account_access_is_revoked()
|
||||
-> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let overrides = LoaderOverrides::without_managed_config_for_tests();
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.loader_overrides(overrides.clone())
|
||||
.build()
|
||||
.await?;
|
||||
let policy = EmbeddedNetworkPolicy::load(&overrides).await;
|
||||
let auth_config = policy.bind_bootstrap_auth(config.auth_config());
|
||||
let bootstrap = auth_config.auth_route_config.http_client_factory().clone();
|
||||
let bundle_url =
|
||||
codex_backend_client::Client::new(config.chatgpt_base_url.clone(), bootstrap.clone())
|
||||
.config_bundle_url()
|
||||
.parse()?;
|
||||
let content_url = "https://chatgpt.com/backend-api/codex/responses".parse()?;
|
||||
let manager = AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::Ephemeral,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
Some(config.chatgpt_base_url.clone()),
|
||||
AuthKeyringBackendKind::default(),
|
||||
auth_config.auth_route_config,
|
||||
)
|
||||
.await;
|
||||
assert!(manager.auth_cached().is_none());
|
||||
|
||||
bootstrap.network_policy().acquire(&bundle_url)?;
|
||||
let mut previous_access: Option<(HttpClientFactory, NetworkPermit)> = None;
|
||||
for identity in ["bootstrap-account-one", "bootstrap-account-two"] {
|
||||
let token = format!(
|
||||
"e30.{}.signature",
|
||||
URL_SAFE_NO_PAD.encode(serde_json::to_vec(&serde_json::json!({
|
||||
"sub": "bootstrap-user",
|
||||
"https://api.openai.com/auth": {
|
||||
"chatgpt_user_id": "bootstrap-user",
|
||||
"chatgpt_account_id": identity,
|
||||
},
|
||||
}))?),
|
||||
);
|
||||
let auth = CodexAuth::from_external_chatgpt_tokens(&token, identity, Some("enterprise"))?;
|
||||
manager
|
||||
.set_external_auth(Arc::new(BootstrapExternalAuth(auth)))
|
||||
.await?;
|
||||
|
||||
if let Some((client, permit)) = previous_access.take() {
|
||||
assert_eq!(permit.check(), Err(NetworkPolicyDenied::Revoked));
|
||||
assert_eq!(
|
||||
client.network_policy().acquire(&content_url).err(),
|
||||
Some(NetworkPolicyDenied::Revoked)
|
||||
);
|
||||
}
|
||||
|
||||
// Discovery must remain possible after both initial login and a workspace change.
|
||||
bootstrap.network_policy().acquire(&bundle_url)?;
|
||||
assert_eq!(
|
||||
bootstrap.network_policy().acquire(&content_url).err(),
|
||||
Some(NetworkPolicyDenied::Destination)
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.application_network_policy()
|
||||
.acquire(&content_url)
|
||||
.err(),
|
||||
Some(NetworkPolicyDenied::Unavailable)
|
||||
);
|
||||
|
||||
assert!(policy.effective.publish(
|
||||
policy.effective.policy().revision(),
|
||||
DestinationPolicy::Unrestricted,
|
||||
));
|
||||
let client = manager.http_client_factory();
|
||||
let permit = client.network_policy().acquire(&content_url)?;
|
||||
previous_access = Some((client, permit));
|
||||
}
|
||||
|
||||
let (client, permit) = previous_access.expect("the last identity has active account access");
|
||||
manager.clear_external_auth();
|
||||
assert_eq!(permit.check(), Err(NetworkPolicyDenied::Revoked));
|
||||
assert_eq!(
|
||||
client.network_policy().acquire(&content_url).err(),
|
||||
Some(NetworkPolicyDenied::Revoked)
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.application_network_policy()
|
||||
.acquire(&content_url)
|
||||
.err(),
|
||||
Some(NetworkPolicyDenied::Unavailable)
|
||||
);
|
||||
bootstrap.network_policy().acquire(&bundle_url)?;
|
||||
|
||||
// Losing local requirements must still close the bootstrap route.
|
||||
policy.local.unavailable(policy.local.policy().revision());
|
||||
assert_eq!(
|
||||
bootstrap.network_policy().acquire(&bundle_url).err(),
|
||||
Some(NetworkPolicyDenied::Unavailable)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_reloads_the_callers_selected_project() -> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let root = temp.path().canonicalize()?;
|
||||
let home = root.join("home");
|
||||
let selected = root.join("selected");
|
||||
std::fs::create_dir(&home)?;
|
||||
std::fs::create_dir_all(selected.join(".codex"))?;
|
||||
std::fs::create_dir(selected.join(".git"))?;
|
||||
set_project_trust_level(&home, &selected, TrustLevel::Trusted)?;
|
||||
let selected_url = "https://selected.example/backend-api/";
|
||||
let user_config = home.join("config.toml");
|
||||
let trust = std::fs::read_to_string(&user_config)?;
|
||||
std::fs::write(
|
||||
&user_config,
|
||||
format!("chatgpt_base_url = '{selected_url}'\n{trust}"),
|
||||
)?;
|
||||
let project_config = selected.join(".codex/config.toml");
|
||||
std::fs::write(&project_config, "model = 'selected-model'")?;
|
||||
let loader_overrides = LoaderOverrides::without_managed_config_for_tests();
|
||||
let mut config = Arc::new(
|
||||
ConfigBuilder::default()
|
||||
.codex_home(home.clone())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
cwd: Some(selected.clone()),
|
||||
..Default::default()
|
||||
})
|
||||
.loader_overrides(loader_overrides.clone())
|
||||
.build()
|
||||
.await?,
|
||||
);
|
||||
assert_eq!(config.chatgpt_base_url, selected_url);
|
||||
assert_eq!(config.model.as_deref(), Some("selected-model"));
|
||||
let manager = ConfigManager::new(
|
||||
home,
|
||||
Vec::new(),
|
||||
loader_overrides,
|
||||
/*strict_config*/ true,
|
||||
CloudConfigBundleLoader::default(),
|
||||
Arg0DispatchPaths::default(),
|
||||
Arc::new(NoopThreadConfigLoader),
|
||||
);
|
||||
let _auth = configure(
|
||||
&manager,
|
||||
&mut config,
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
config.cwd.as_path().canonicalize()?,
|
||||
selected.canonicalize()?
|
||||
);
|
||||
assert_eq!(config.chatgpt_base_url, selected_url);
|
||||
|
||||
let marked = CodexAuth::from_api_key("sk-proj-fedramp-test-key");
|
||||
for (configured_url, expected_url) in [
|
||||
(None, "https://gov.chatgpt.com/backend-api/"),
|
||||
(Some(DEFAULT_CHATGPT_BASE_URL), DEFAULT_CHATGPT_BASE_URL),
|
||||
] {
|
||||
let setting = configured_url
|
||||
.map(|url| format!("chatgpt_base_url = '{url}'\n"))
|
||||
.unwrap_or_default();
|
||||
std::fs::write(&user_config, format!("{setting}{trust}"))?;
|
||||
let _auth = configure(
|
||||
&manager,
|
||||
&mut config,
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(config.chatgpt_backend_url().resolve(&marked), expected_url);
|
||||
}
|
||||
|
||||
std::fs::write(&project_config, "[malformed")?;
|
||||
let error = configure(
|
||||
&manager,
|
||||
&mut config,
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.ok_or_else(|| anyhow::anyhow!("embedded startup ignored the selected project"))?;
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("Error parsing project config file")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
1595
codex-rs/app-server/src/lib.rs
Normal file
1595
codex-rs/app-server/src/lib.rs
Normal file
File diff suppressed because it is too large
Load Diff
83
codex-rs/app-server/src/lib_tests.rs
Normal file
83
codex-rs/app-server/src/lib_tests.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Unit tests for the crate and its related test suites.
|
||||
|
||||
use super::LogFormat;
|
||||
use super::ShutdownAction;
|
||||
use super::ShutdownSignal;
|
||||
use super::ShutdownState;
|
||||
#[cfg(debug_assertions)]
|
||||
use super::loader_overrides_with_test_user_config_file;
|
||||
use super::turn_admission::TurnAdmission;
|
||||
#[cfg(debug_assertions)]
|
||||
use codex_config::LoaderOverrides;
|
||||
#[cfg(debug_assertions)]
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn shutdown_waits_for_admitted_requests_but_force_remains_available() {
|
||||
let admission = TurnAdmission::default();
|
||||
let active = admission.subscribe_active();
|
||||
let in_flight = admission.admit().expect("request admitted");
|
||||
let mut shutdown = ShutdownState::default();
|
||||
let connection_count = 1;
|
||||
let running_turn_count = 0;
|
||||
shutdown.on_signal(
|
||||
ShutdownSignal::Forceable,
|
||||
connection_count,
|
||||
running_turn_count,
|
||||
&admission,
|
||||
);
|
||||
assert!(matches!(
|
||||
shutdown.update(running_turn_count, *active.borrow(), connection_count),
|
||||
ShutdownAction::Noop
|
||||
));
|
||||
shutdown.on_signal(
|
||||
ShutdownSignal::Forceable,
|
||||
connection_count,
|
||||
running_turn_count,
|
||||
&admission,
|
||||
);
|
||||
assert!(shutdown.forced());
|
||||
assert!(matches!(
|
||||
shutdown.update(running_turn_count, *active.borrow(), connection_count),
|
||||
ShutdownAction::Finish
|
||||
));
|
||||
drop(in_flight);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_format_from_env_value_matches_json_values_case_insensitively() {
|
||||
assert_eq!(LogFormat::from_env_value(Some("json")), LogFormat::Json);
|
||||
assert_eq!(LogFormat::from_env_value(Some("JSON")), LogFormat::Json);
|
||||
assert_eq!(LogFormat::from_env_value(Some(" Json ")), LogFormat::Json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_format_from_env_value_defaults_for_non_json_values() {
|
||||
assert_eq!(
|
||||
LogFormat::from_env_value(/*value*/ None),
|
||||
LogFormat::Default
|
||||
);
|
||||
assert_eq!(LogFormat::from_env_value(Some("")), LogFormat::Default);
|
||||
assert_eq!(LogFormat::from_env_value(Some("text")), LogFormat::Default);
|
||||
assert_eq!(LogFormat::from_env_value(Some("jsonl")), LogFormat::Default);
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
#[test]
|
||||
fn debug_test_user_config_file_overrides_loader_path() {
|
||||
let path = std::env::temp_dir().join("codex-app-server-test-config.toml");
|
||||
let loader_overrides =
|
||||
loader_overrides_with_test_user_config_file(LoaderOverrides::default(), Some(path.clone()))
|
||||
.expect("test config path should be valid");
|
||||
|
||||
assert_eq!(
|
||||
loader_overrides.user_config_path,
|
||||
Some(AbsolutePathBuf::from_absolute_path(path).expect("absolute test path"))
|
||||
);
|
||||
}
|
||||
|
||||
#[path = "stderr_logging_tests.rs"]
|
||||
mod stderr_logging_tests;
|
||||
67
codex-rs/app-server/src/log_write_warning.rs
Normal file
67
codex-rs/app-server/src/log_write_warning.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::WarningNotification;
|
||||
use codex_core::config::Config;
|
||||
use codex_feedback::CodexFeedback;
|
||||
use codex_state::LogWriteFailureReporter;
|
||||
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
|
||||
const LOG_WRITE_WARNING_WITH_FEEDBACK: &str = "Codex couldn't save diagnostic logs to its local database. Use /feedback with logs included before closing Codex, or run `codex doctor` for diagnostics.";
|
||||
const LOG_WRITE_WARNING_WITHOUT_FEEDBACK: &str = "Codex couldn't save diagnostic logs to its local database. Run `codex doctor` for diagnostics.";
|
||||
|
||||
pub(crate) struct LogWriteWarningReporter {
|
||||
feedback: CodexFeedback,
|
||||
outgoing: Weak<OutgoingMessageSender>,
|
||||
/// Permanently set by the first failure; limits warning delivery to one attempt
|
||||
/// for this reporter, even if later SQLite writes succeed.
|
||||
has_failure: AtomicBool,
|
||||
message: &'static str,
|
||||
}
|
||||
|
||||
impl LogWriteWarningReporter {
|
||||
pub(crate) fn new(
|
||||
feedback: CodexFeedback,
|
||||
outgoing: &Arc<OutgoingMessageSender>,
|
||||
config: &Config,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
feedback,
|
||||
outgoing: Arc::downgrade(outgoing),
|
||||
has_failure: AtomicBool::new(false),
|
||||
message: if config.feedback_enabled {
|
||||
LOG_WRITE_WARNING_WITH_FEEDBACK
|
||||
} else {
|
||||
LOG_WRITE_WARNING_WITHOUT_FEEDBACK
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn notify_failure(&self) {
|
||||
if !self.has_failure.swap(true, Ordering::Relaxed)
|
||||
&& let Some(outgoing) = self.outgoing.upgrade()
|
||||
{
|
||||
outgoing.try_send_server_notification(ServerNotification::Warning(
|
||||
WarningNotification {
|
||||
thread_id: None,
|
||||
message: self.message.to_string(),
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LogWriteFailureReporter for LogWriteWarningReporter {
|
||||
fn report_failure(&self, diagnostic: &str) {
|
||||
self.feedback.report_failure(diagnostic);
|
||||
self.notify_failure();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "log_write_warning_tests.rs"]
|
||||
mod tests;
|
||||
171
codex-rs/app-server/src/log_write_warning_tests.rs
Normal file
171
codex-rs/app-server/src/log_write_warning_tests.rs
Normal file
@@ -0,0 +1,171 @@
|
||||
use super::*;
|
||||
use crate::outgoing_message::OutgoingEnvelope;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_feedback::CodexFeedback;
|
||||
use codex_state::LogWriteFailureReporter;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
#[tokio::test]
|
||||
async fn log_write_warning_is_broadcast_once() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await?;
|
||||
for feedback_enabled in [true, false] {
|
||||
config.feedback_enabled = feedback_enabled;
|
||||
let feedback = CodexFeedback::new();
|
||||
let (tx, mut rx) = mpsc::channel(/*buffer*/ 4);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
tx,
|
||||
AnalyticsEventsClient::disabled(),
|
||||
));
|
||||
let reporter = LogWriteWarningReporter::new(feedback.clone(), &outgoing, &config);
|
||||
reporter.report_failure("SQLite flush failed");
|
||||
let OutgoingEnvelope::Broadcast {
|
||||
message: OutgoingMessage::AppServerNotification(envelope),
|
||||
} = rx.try_recv()?
|
||||
else {
|
||||
panic!("expected a broadcast notification");
|
||||
};
|
||||
let expected = if feedback_enabled {
|
||||
"Codex couldn't save diagnostic logs to its local database. Use /feedback with logs included before closing Codex, or run `codex doctor` for diagnostics."
|
||||
} else {
|
||||
"Codex couldn't save diagnostic logs to its local database. Run `codex doctor` for diagnostics."
|
||||
};
|
||||
let ServerNotification::Warning(notification) = envelope.notification else {
|
||||
panic!("expected a warning");
|
||||
};
|
||||
assert_eq!(
|
||||
notification,
|
||||
WarningNotification {
|
||||
thread_id: None,
|
||||
message: expected.to_string(),
|
||||
}
|
||||
);
|
||||
reporter.report_failure("another SQLite flush failed");
|
||||
assert!(rx.try_recv().is_err());
|
||||
assert_eq!(
|
||||
feedback
|
||||
.snapshot(/*session_id*/ None)
|
||||
.log_attachment(/*logs_override*/ None)
|
||||
.buffer,
|
||||
b"SQLite flush failedanother SQLite flush failed"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn log_write_warning_keeps_feedback_when_sender_is_gone() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await?;
|
||||
let feedback = CodexFeedback::new();
|
||||
let (tx, mut rx) = mpsc::channel(/*buffer*/ 4);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
tx,
|
||||
AnalyticsEventsClient::disabled(),
|
||||
));
|
||||
let reporter = LogWriteWarningReporter::new(feedback.clone(), &outgoing, &config);
|
||||
drop(outgoing);
|
||||
reporter.report_failure("SQLite flush failed");
|
||||
assert_eq!(
|
||||
feedback
|
||||
.snapshot(/*session_id*/ None)
|
||||
.log_attachment(/*logs_override*/ None)
|
||||
.buffer,
|
||||
b"SQLite flush failed"
|
||||
);
|
||||
assert!(reporter.outgoing.upgrade().is_none());
|
||||
reporter.report_failure("second failure");
|
||||
assert_eq!(
|
||||
feedback
|
||||
.snapshot(/*session_id*/ None)
|
||||
.log_attachment(/*logs_override*/ None)
|
||||
.buffer,
|
||||
b"SQLite flush failedsecond failure"
|
||||
);
|
||||
assert!(rx.try_recv().is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn log_write_warning_reports_failed_sqlite_flush() -> anyhow::Result<()> {
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
|
||||
for attach_after_failure in [false, true] {
|
||||
let home = tempfile::tempdir()?;
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await?;
|
||||
let feedback = CodexFeedback::new();
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite_config().clone(),
|
||||
"test-provider".to_string(),
|
||||
)
|
||||
.await?;
|
||||
let (tx, mut rx) = mpsc::channel(/*buffer*/ 4);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
tx,
|
||||
AnalyticsEventsClient::disabled(),
|
||||
));
|
||||
let reporter = LogWriteWarningReporter::new(feedback.clone(), &outgoing, &config);
|
||||
let initial_reporter: Arc<dyn LogWriteFailureReporter> = if attach_after_failure {
|
||||
Arc::new(feedback.clone())
|
||||
} else {
|
||||
reporter.clone()
|
||||
};
|
||||
let layer = codex_state::log_db::start(runtime.clone(), initial_reporter);
|
||||
runtime.close().await;
|
||||
tracing::subscriber::with_default(
|
||||
tracing_subscriber::registry().with(layer.clone()),
|
||||
|| {
|
||||
tracing::info!("first failed log write");
|
||||
},
|
||||
);
|
||||
layer.flush().await;
|
||||
assert!(layer.has_write_failure());
|
||||
if attach_after_failure {
|
||||
layer.set_failure_reporter(reporter.clone());
|
||||
if layer.has_write_failure() {
|
||||
reporter.notify_failure();
|
||||
}
|
||||
}
|
||||
|
||||
assert!(matches!(
|
||||
rx.try_recv(),
|
||||
Ok(OutgoingEnvelope::Broadcast {
|
||||
message: OutgoingMessage::AppServerNotification(_),
|
||||
..
|
||||
})
|
||||
));
|
||||
tracing::subscriber::with_default(
|
||||
tracing_subscriber::registry().with(layer.clone()),
|
||||
|| {
|
||||
tracing::info!("second failed log write");
|
||||
},
|
||||
);
|
||||
layer.flush().await;
|
||||
assert!(rx.try_recv().is_err());
|
||||
assert_eq!(
|
||||
String::from_utf8(
|
||||
feedback
|
||||
.snapshot(/*session_id*/ None)
|
||||
.log_attachment(/*logs_override*/ None)
|
||||
.buffer
|
||||
)?
|
||||
.matches("failed to flush logs to SQLite")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
172
codex-rs/app-server/src/main.rs
Normal file
172
codex-rs/app-server/src/main.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
use clap::Parser;
|
||||
use codex_app_server::AppServerCodeModeHostArgs;
|
||||
use codex_app_server::AppServerRuntimeOptions;
|
||||
use codex_app_server::AppServerTransport;
|
||||
use codex_app_server::PluginStartupTasks;
|
||||
use codex_app_server::run_main_with_transport_options;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_arg0::arg0_dispatch_or_else;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use codex_websocket_auth::WebsocketAuthArgs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(all(
|
||||
target_os = "linux",
|
||||
target_env = "musl",
|
||||
any(target_arch = "x86_64", target_arch = "aarch64")
|
||||
))]
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
|
||||
|
||||
// Debug-only test hook: lets integration tests point the server at a temporary
|
||||
// managed config file without writing to /etc.
|
||||
const MANAGED_CONFIG_PATH_ENV_VAR: &str = "CODEX_APP_SERVER_MANAGED_CONFIG_PATH";
|
||||
const DISABLE_MANAGED_CONFIG_ENV_VAR: &str = "CODEX_APP_SERVER_DISABLE_MANAGED_CONFIG";
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(version)]
|
||||
struct AppServerArgs {
|
||||
/// Load frozen cloud skills from a JSON snapshot instead of a live skill service.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
cloud_skills_snapshot: Option<PathBuf>,
|
||||
#[command(flatten)]
|
||||
config_overrides: CliConfigOverrides,
|
||||
|
||||
#[command(flatten)]
|
||||
code_mode_host: AppServerCodeModeHostArgs,
|
||||
|
||||
/// Transport endpoint URL. Supported values: `stdio://` (default),
|
||||
/// `unix://`, `unix://PATH`, `ws://IP:PORT`, `off`.
|
||||
#[arg(
|
||||
long = "listen",
|
||||
value_name = "URL",
|
||||
default_value = AppServerTransport::DEFAULT_LISTEN_URL
|
||||
)]
|
||||
listen: AppServerTransport,
|
||||
|
||||
/// Session source used to derive product restrictions and metadata.
|
||||
#[arg(
|
||||
long = "session-source",
|
||||
value_name = "SOURCE",
|
||||
default_value = "vscode",
|
||||
value_parser = SessionSource::from_startup_arg
|
||||
)]
|
||||
session_source: SessionSource,
|
||||
|
||||
#[command(flatten)]
|
||||
auth: WebsocketAuthArgs,
|
||||
|
||||
/// Fail if config.toml contains unknown configuration fields.
|
||||
#[arg(long = "strict-config", default_value_t = false)]
|
||||
strict_config: bool,
|
||||
|
||||
/// Hidden debug-only test hook used by integration tests that spawn the
|
||||
/// production app-server binary.
|
||||
#[cfg(debug_assertions)]
|
||||
#[arg(long = "disable-plugin-startup-tasks-for-tests", hide = true)]
|
||||
disable_plugin_startup_tasks_for_tests: bool,
|
||||
|
||||
/// Enable remote control for this app-server process without changing persistence.
|
||||
#[arg(long = "remote-control", hide = true)]
|
||||
remote_control: bool,
|
||||
|
||||
/// Save loaded threads during managed daemon shutdown.
|
||||
#[arg(long, hide = true)]
|
||||
managed_daemon: bool,
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let remote_control_disabled = codex_app_server::take_remote_control_disabled_env();
|
||||
arg0_dispatch_or_else(move |arg0_paths: Arg0DispatchPaths| async move {
|
||||
let AppServerArgs {
|
||||
cloud_skills_snapshot,
|
||||
config_overrides,
|
||||
code_mode_host,
|
||||
listen,
|
||||
session_source,
|
||||
auth,
|
||||
strict_config,
|
||||
#[cfg(debug_assertions)]
|
||||
disable_plugin_startup_tasks_for_tests,
|
||||
remote_control,
|
||||
managed_daemon,
|
||||
} = AppServerArgs::parse();
|
||||
let loader_overrides = if disable_managed_config_from_debug_env() {
|
||||
LoaderOverrides::without_managed_config_for_tests()
|
||||
} else {
|
||||
managed_config_path_from_debug_env()
|
||||
.map(LoaderOverrides::with_managed_config_path_for_tests)
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let transport = listen;
|
||||
let auth = auth.try_into_settings()?;
|
||||
let mut runtime_options = AppServerRuntimeOptions {
|
||||
cloud_skills_snapshot,
|
||||
code_mode_host_transport: code_mode_host.into(),
|
||||
managed_daemon,
|
||||
..Default::default()
|
||||
};
|
||||
#[cfg(debug_assertions)]
|
||||
if disable_plugin_startup_tasks_for_tests {
|
||||
runtime_options.plugin_startup_tasks = PluginStartupTasks::Skip;
|
||||
}
|
||||
runtime_options.remote_control_startup_mode =
|
||||
match (remote_control, remote_control_disabled) {
|
||||
(true, _) => codex_app_server::RemoteControlStartupMode::EnabledEphemeral,
|
||||
(false, true) => codex_app_server::RemoteControlStartupMode::DisabledEphemeral,
|
||||
(false, false) => codex_app_server::RemoteControlStartupMode::ResolvePersisted,
|
||||
};
|
||||
|
||||
let exit = run_main_with_transport_options(
|
||||
arg0_paths,
|
||||
config_overrides,
|
||||
loader_overrides,
|
||||
strict_config,
|
||||
/*default_analytics_enabled*/ false,
|
||||
transport,
|
||||
session_source,
|
||||
auth,
|
||||
runtime_options,
|
||||
)
|
||||
.await?;
|
||||
if exit == codex_app_server::AppServerExit::Forced {
|
||||
// Runtime teardown can wait forever for blocked rollout I/O.
|
||||
std::process::exit(0);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn disable_managed_config_from_debug_env() -> bool {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
if let Ok(value) = std::env::var(DISABLE_MANAGED_CONFIG_ENV_VAR) {
|
||||
return matches!(value.as_str(), "1" | "true" | "TRUE" | "yes" | "YES");
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn managed_config_path_from_debug_env() -> Option<PathBuf> {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
if let Ok(value) = std::env::var(MANAGED_CONFIG_PATH_ENV_VAR) {
|
||||
return if value.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(PathBuf::from(value))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "main_tests.rs"]
|
||||
mod tests;
|
||||
85
codex-rs/app-server/src/main_tests.rs
Normal file
85
codex-rs/app-server/src/main_tests.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use super::AppServerArgs;
|
||||
use clap::Parser;
|
||||
use codex_app_server::AppServerTransport;
|
||||
use pretty_assertions::assert_eq;
|
||||
use toml::Value as TomlValue;
|
||||
use url::Url;
|
||||
|
||||
#[test]
|
||||
fn app_server_accepts_cli_config_overrides() {
|
||||
let args = AppServerArgs::try_parse_from([
|
||||
"codex-app-server",
|
||||
"-c",
|
||||
"model=\"gpt-5-codex\"",
|
||||
"--config",
|
||||
"sandbox_mode=\"read-only\"",
|
||||
"--listen",
|
||||
"off",
|
||||
])
|
||||
.expect("parse app-server args");
|
||||
|
||||
let parsed_overrides = args
|
||||
.config_overrides
|
||||
.parse_overrides()
|
||||
.expect("parse config overrides");
|
||||
|
||||
assert_eq!(
|
||||
parsed_overrides,
|
||||
vec![
|
||||
(
|
||||
"model".to_string(),
|
||||
TomlValue::String("gpt-5-codex".to_string()),
|
||||
),
|
||||
(
|
||||
"sandbox_mode".to_string(),
|
||||
TomlValue::String("read-only".to_string()),
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_accepts_process_scoped_grpc_code_mode_host() {
|
||||
let args = AppServerArgs::try_parse_from([
|
||||
"codex-app-server",
|
||||
"--code-mode-host",
|
||||
"https://example.test",
|
||||
"--listen",
|
||||
"off",
|
||||
])
|
||||
.expect("parse gRPC app-server args");
|
||||
|
||||
assert_eq!(
|
||||
args.code_mode_host.code_mode_host,
|
||||
Some(Url::parse("https://example.test").expect("test endpoint should parse"))
|
||||
);
|
||||
assert_eq!(args.listen, AppServerTransport::Off);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_rejects_invalid_code_mode_host() {
|
||||
for endpoint in [
|
||||
"ftp://127.0.0.1:8765",
|
||||
"ws://",
|
||||
"ws://127.0.0.1:8765",
|
||||
"wss://example.test/code-mode",
|
||||
"ws://alice:secret@example.test/code-mode",
|
||||
"wss://alice:secret@example.test/code-mode",
|
||||
"wss://example.test/code-mode#fragment",
|
||||
"http://",
|
||||
"https://example.test/#fragment",
|
||||
"https://example.test/code-mode",
|
||||
"http://alice:secret@example.test",
|
||||
"https://alice:secret@example.test",
|
||||
"http://example.test/?token=secret",
|
||||
] {
|
||||
let error =
|
||||
AppServerArgs::try_parse_from(["codex-app-server", "--code-mode-host", endpoint])
|
||||
.expect_err("invalid code-mode host endpoint should fail startup argument parsing");
|
||||
|
||||
assert_eq!(error.kind(), clap::error::ErrorKind::ValueValidation);
|
||||
let rendered_error = error.to_string();
|
||||
assert!(!rendered_error.contains("alice"));
|
||||
assert!(!rendered_error.contains("secret"));
|
||||
}
|
||||
}
|
||||
26
codex-rs/app-server/src/managed_daemon.rs
Normal file
26
codex-rs/app-server/src/managed_daemon.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
//! Unix process setup specific to a managed app-server daemon.
|
||||
|
||||
use std::io;
|
||||
|
||||
const NOFILE_LIMIT: libc::rlim_t = 4096;
|
||||
|
||||
pub(crate) fn raise_nofile_limit() -> io::Result<()> {
|
||||
let mut limit = libc::rlimit {
|
||||
rlim_cur: 0,
|
||||
rlim_max: 0,
|
||||
};
|
||||
// SAFETY: getrlimit initializes the stack-owned resource-limit structure.
|
||||
if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } == -1 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let target = limit.rlim_cur.max(limit.rlim_max.min(NOFILE_LIMIT));
|
||||
if target == limit.rlim_cur {
|
||||
return Ok(());
|
||||
}
|
||||
limit.rlim_cur = target;
|
||||
// SAFETY: the requested soft limit does not exceed the inherited hard limit.
|
||||
if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) } == -1 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
652
codex-rs/app-server/src/mcp_refresh.rs
Normal file
652
codex-rs/app-server/src/mcp_refresh.rs
Normal file
@@ -0,0 +1,652 @@
|
||||
use crate::config_manager::ConfigManager;
|
||||
use codex_core::CodexThread;
|
||||
use codex_core::ConfigRefreshOutcome;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
use tracing::warn;
|
||||
|
||||
pub(crate) async fn reload_mcp_config(
|
||||
thread_manager: &Arc<ThreadManager>,
|
||||
config_manager: &ConfigManager,
|
||||
) -> io::Result<()> {
|
||||
// Keep the reload state machine out of the request dispatcher's stack frame.
|
||||
Box::pin(reload_mcp_config_with_policy(
|
||||
thread_manager,
|
||||
config_manager,
|
||||
ReloadPolicy::Strict,
|
||||
))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn reload_mcp_config_best_effort(
|
||||
thread_manager: &Arc<ThreadManager>,
|
||||
config_manager: &ConfigManager,
|
||||
) {
|
||||
if let Err(err) = Box::pin(reload_mcp_config_with_policy(
|
||||
thread_manager,
|
||||
config_manager,
|
||||
ReloadPolicy::BestEffort,
|
||||
))
|
||||
.await
|
||||
{
|
||||
warn!(%err, "failed to reload MCP configuration");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ReloadPolicy {
|
||||
Strict,
|
||||
BestEffort,
|
||||
}
|
||||
|
||||
async fn reload_mcp_config_with_policy(
|
||||
thread_manager: &ThreadManager,
|
||||
config_manager: &ConfigManager,
|
||||
policy: ReloadPolicy,
|
||||
) -> io::Result<()> {
|
||||
config_manager.revoke_mcp_ema_startups();
|
||||
let mut rejected = false;
|
||||
let mut load_error = None;
|
||||
let mut completed: Vec<Arc<CodexThread>> = Vec::new();
|
||||
// Bound both discovery and stale-owner retries so concurrent churn cannot
|
||||
// keep the reload request alive indefinitely. Completed publications remain valid.
|
||||
for pass in 0..3 {
|
||||
let host_loaded = match policy {
|
||||
ReloadPolicy::BestEffort => true,
|
||||
ReloadPolicy::Strict => match config_manager.load_config_layers(/*cwd*/ None).await {
|
||||
Ok(_) => true,
|
||||
Err(err) => {
|
||||
load_error.get_or_insert(err);
|
||||
false
|
||||
}
|
||||
},
|
||||
};
|
||||
let mut targets = Vec::new();
|
||||
for thread_id in thread_manager.list_thread_ids().await {
|
||||
match thread_manager.get_thread(thread_id).await {
|
||||
Ok(thread) => {
|
||||
if !completed.iter().any(|done| Arc::ptr_eq(done, &thread)) {
|
||||
targets.push((thread_id, thread));
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(%thread_id, %err, "failed to load thread for MCP configuration refresh");
|
||||
}
|
||||
}
|
||||
}
|
||||
if targets.is_empty() {
|
||||
break;
|
||||
}
|
||||
for (thread_id, target) in targets {
|
||||
for attempt in 0..3 {
|
||||
let current_config = target.config().await;
|
||||
let mut target_load_error = None;
|
||||
let next_config = if host_loaded {
|
||||
match load_refresh_config(¤t_config, config_manager).await {
|
||||
Ok(next_config) => next_config,
|
||||
Err(err) => {
|
||||
if matches!(policy, ReloadPolicy::BestEffort) {
|
||||
warn!(%thread_id, %err, "failed to load session configuration");
|
||||
}
|
||||
target_load_error = Some(err);
|
||||
disabled_enterprise_config(¤t_config)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
disabled_enterprise_config(¤t_config)
|
||||
};
|
||||
match target.refresh_mcp_config(current_config, next_config).await {
|
||||
ConfigRefreshOutcome::Published => {}
|
||||
ConfigRefreshOutcome::Rejected => rejected = true,
|
||||
ConfigRefreshOutcome::Stale => {
|
||||
if attempt == 2 {
|
||||
target.disable_mcp_enterprise_auth().await;
|
||||
rejected = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if matches!(policy, ReloadPolicy::Strict)
|
||||
&& let Some(err) = target_load_error
|
||||
{
|
||||
load_error.get_or_insert(err);
|
||||
}
|
||||
break;
|
||||
}
|
||||
completed.push(target);
|
||||
}
|
||||
if pass == 2 {
|
||||
for thread_id in thread_manager.list_thread_ids().await {
|
||||
if let Ok(thread) = thread_manager.get_thread(thread_id).await
|
||||
&& !completed.iter().any(|done| Arc::ptr_eq(done, &thread))
|
||||
{
|
||||
thread.disable_mcp_enterprise_auth().await;
|
||||
rejected = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Finish publishing every session's fail-closed configuration before reporting failure.
|
||||
if matches!(policy, ReloadPolicy::Strict)
|
||||
&& let Some(err) = load_error
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
if rejected && matches!(policy, ReloadPolicy::Strict) {
|
||||
return Err(io::Error::other(
|
||||
"enterprise MCP configuration was rejected; affected sessions retained their previous configuration with enterprise MCP disabled",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn disabled_enterprise_config(current_config: &Config) -> Config {
|
||||
let mut config = current_config.clone();
|
||||
config.disable_mcp_enterprise_auth();
|
||||
config.config_layer_stack = config
|
||||
.config_layer_stack
|
||||
.with_cloud_config_binding(/*binding*/ None);
|
||||
config
|
||||
}
|
||||
|
||||
async fn load_refresh_config(
|
||||
current_config: &Config,
|
||||
config_manager: &ConfigManager,
|
||||
) -> io::Result<Config> {
|
||||
config_manager
|
||||
.load_latest_config_with_session_layers(
|
||||
¤t_config.config_layer_stack,
|
||||
¤t_config.cwd,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::extensions::ThreadExtensionDependencies;
|
||||
use crate::extensions::thread_extensions;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::ThreadConfigContext;
|
||||
use codex_config::ThreadConfigLoadError;
|
||||
use codex_config::ThreadConfigLoadErrorCode;
|
||||
use codex_config::ThreadConfigLoader;
|
||||
use codex_config::ThreadConfigSource;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_config::types::McpServerConfig;
|
||||
use codex_core::ThreadStoreBuilder;
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_core::init_state_db;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_extension_api::NoopExtensionEventSink;
|
||||
use codex_home::CodexHomeUserInstructionsProvider;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_models_manager::manager::ModelCatalogSettings;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_refresh_stops_after_bounded_attempts() -> anyhow::Result<()> {
|
||||
let (_temp_dir, thread_manager, config_manager, loader) = refresh_test_state().await?;
|
||||
for thread_id in thread_manager.list_thread_ids().await {
|
||||
let thread = thread_manager.get_thread(thread_id).await?;
|
||||
if thread.config().await.cwd.ends_with("good") {
|
||||
*loader.churn_thread.lock().unwrap() = Some(thread);
|
||||
}
|
||||
}
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(10),
|
||||
reload_mcp_config(&thread_manager, &config_manager),
|
||||
)
|
||||
.await
|
||||
.expect("reload must terminate under owner churn")
|
||||
.expect_err("reload failed closed");
|
||||
assert_eq!(loader.good_loads.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(loader.bad_loads.load(Ordering::Relaxed), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_refresh_reports_thread_planning_failures() -> anyhow::Result<()> {
|
||||
let (temp_dir, thread_manager, config_manager, _loader) = refresh_test_state().await?;
|
||||
std::fs::write(
|
||||
temp_dir.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
"[features]\nsecret_auth_storage = true\n",
|
||||
)?;
|
||||
|
||||
let err = reload_mcp_config(&thread_manager, &config_manager)
|
||||
.await
|
||||
.expect_err("strict refresh should fail");
|
||||
|
||||
assert_eq!(err.to_string(), "failed to load refresh config");
|
||||
for thread_id in thread_manager.list_thread_ids().await {
|
||||
let config = thread_manager.get_thread(thread_id).await?.config().await;
|
||||
let failed = config.cwd.ends_with("bad");
|
||||
assert_eq!(
|
||||
config.auth_keyring_backend_kind(),
|
||||
if failed {
|
||||
AuthKeyringBackendKind::Direct
|
||||
} else {
|
||||
AuthKeyringBackendKind::Secrets
|
||||
}
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn best_effort_refresh_updates_healthy_threads() -> anyhow::Result<()> {
|
||||
let (temp_dir, thread_manager, config_manager, loader) = refresh_test_state().await?;
|
||||
std::fs::write(
|
||||
temp_dir.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
"[features]\nsecret_auth_storage = true\n",
|
||||
)?;
|
||||
|
||||
reload_mcp_config_best_effort(&thread_manager, &config_manager).await;
|
||||
|
||||
assert_eq!(loader.good_loads.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(loader.bad_loads.load(Ordering::Relaxed), 1);
|
||||
for thread_id in thread_manager.list_thread_ids().await {
|
||||
let thread = thread_manager.get_thread(thread_id).await?;
|
||||
let config = thread.config().await;
|
||||
let expected = if config.cwd.ends_with("good") {
|
||||
AuthKeyringBackendKind::Secrets
|
||||
} else {
|
||||
AuthKeyringBackendKind::Direct
|
||||
};
|
||||
assert_eq!(config.auth_keyring_backend_kind(), expected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_refresh_preserves_config_when_host_config_cannot_load() -> anyhow::Result<()> {
|
||||
let (temp_dir, thread_manager, config_manager, _loader) = refresh_test_state().await?;
|
||||
std::fs::write(
|
||||
temp_dir.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
"[features",
|
||||
)?;
|
||||
|
||||
assert!(
|
||||
reload_mcp_config(&thread_manager, &config_manager)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
for thread_id in thread_manager.list_thread_ids().await {
|
||||
let config = thread_manager.get_thread(thread_id).await?.config().await;
|
||||
assert_eq!(
|
||||
config.auth_keyring_backend_kind(),
|
||||
AuthKeyringBackendKind::Direct
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalidation_does_not_reload_thread_config() -> anyhow::Result<()> {
|
||||
let (_temp_dir, thread_manager, _config_manager, loader) = refresh_test_state().await?;
|
||||
|
||||
thread_manager.invalidate_mcp_runtimes().await;
|
||||
|
||||
assert_eq!(loader.good_loads.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(loader.bad_loads.load(Ordering::Relaxed), 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_config_reload_only_applies_mcp_inputs() -> anyhow::Result<()> {
|
||||
let (temp_dir, thread_manager, config_manager, _loader) = refresh_test_state().await?;
|
||||
std::fs::write(
|
||||
temp_dir.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
"model = \"unrelated-model-change\"\n[features]\nsecret_auth_storage = true\n",
|
||||
)?;
|
||||
|
||||
let mut good_thread = None;
|
||||
for thread_id in thread_manager.list_thread_ids().await {
|
||||
let thread = thread_manager.get_thread(thread_id).await?;
|
||||
let thread_config = thread.config().await;
|
||||
if thread_config.cwd.ends_with("good") {
|
||||
good_thread = Some(thread);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let thread = good_thread.expect("good test thread should exist");
|
||||
let original_model = thread.config().await.model.clone();
|
||||
|
||||
let current_config = thread.config().await;
|
||||
let refresh_config = load_refresh_config(¤t_config, &config_manager).await?;
|
||||
let _ = thread
|
||||
.refresh_mcp_config(current_config, refresh_config)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
thread.config().await.auth_keyring_backend_kind(),
|
||||
AuthKeyringBackendKind::Secrets
|
||||
);
|
||||
assert_eq!(thread.config().await.model, original_model);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_config_preserves_thread_mcp_overrides() -> anyhow::Result<()> {
|
||||
let (temp_dir, thread_manager, config_manager, _loader) = refresh_test_state().await?;
|
||||
let initial_config_manager =
|
||||
ConfigManager::without_managed_config_for_tests(temp_dir.path().to_path_buf());
|
||||
let thread_config = initial_config_manager
|
||||
.load_for_cwd(
|
||||
Some(HashMap::from([
|
||||
(
|
||||
"mcp_servers.thread.command".to_string(),
|
||||
json!("thread-mcp"),
|
||||
),
|
||||
("mcp_servers.thread.enabled".to_string(), json!(false)),
|
||||
])),
|
||||
ConfigOverrides::default(),
|
||||
Some(temp_dir.path().join("good")),
|
||||
)
|
||||
.await?;
|
||||
let thread = thread_manager
|
||||
.start_thread(codex_core::StartThreadOptions::new(thread_config))
|
||||
.await?
|
||||
.thread;
|
||||
std::fs::write(
|
||||
temp_dir.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
r#"
|
||||
[mcp_servers.global]
|
||||
command = "global-mcp"
|
||||
enabled = false
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let current_config = thread.config().await;
|
||||
let refresh_config = load_refresh_config(¤t_config, &config_manager).await?;
|
||||
let mut actual = refresh_config.mcp_servers.get().clone();
|
||||
actual.remove(codex_mcp::CODEX_APPS_MCP_SERVER_NAME);
|
||||
let expected = serde_json::from_value::<HashMap<String, McpServerConfig>>(json!({
|
||||
"global": {
|
||||
"command": "global-mcp",
|
||||
"enabled": false
|
||||
},
|
||||
"thread": {
|
||||
"command": "thread-mcp",
|
||||
"enabled": false
|
||||
}
|
||||
}))?;
|
||||
|
||||
assert_eq!(actual, expected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_refresh_installs_refreshed_thread_mcp_config() -> anyhow::Result<()> {
|
||||
let (temp_dir, thread_manager, config_manager, _loader) = refresh_test_state().await?;
|
||||
let mut good_thread = None;
|
||||
for thread_id in thread_manager.list_thread_ids().await {
|
||||
let thread = thread_manager.get_thread(thread_id).await?;
|
||||
let thread_config = thread.config().await;
|
||||
if thread_config.cwd.ends_with("good") {
|
||||
good_thread = Some(thread);
|
||||
} else {
|
||||
thread_manager.remove_thread(&thread_id).await;
|
||||
}
|
||||
}
|
||||
let thread = good_thread.expect("good test thread should exist");
|
||||
// Config loading can finish before a startup is visible to ThreadManager.
|
||||
let pending_startup = config_manager
|
||||
.load_for_cwd(
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides::default(),
|
||||
Some(temp_dir.path().join("good")),
|
||||
)
|
||||
.await?;
|
||||
assert!(
|
||||
!pending_startup
|
||||
.config_layer_stack
|
||||
.mcp_ema_cancellation()
|
||||
.is_cancelled()
|
||||
);
|
||||
// Prediction forks inherit a published config and may outlive their parent.
|
||||
let parent = thread_manager
|
||||
.start_thread(codex_core::StartThreadOptions::new(pending_startup.clone()))
|
||||
.await?;
|
||||
let (inherited_fork, _) = thread_manager
|
||||
.fork_options_from_parent(parent.thread_id)
|
||||
.await?;
|
||||
thread_manager.remove_thread(&parent.thread_id).await;
|
||||
std::fs::write(
|
||||
temp_dir.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
r#"
|
||||
[mcp_servers.refreshed]
|
||||
command = "refreshed-mcp"
|
||||
enabled = false
|
||||
"#,
|
||||
)?;
|
||||
|
||||
reload_mcp_config(&thread_manager, &config_manager).await?;
|
||||
|
||||
let fork = thread_manager.start_thread(inherited_fork).await?;
|
||||
assert!(
|
||||
fork.thread
|
||||
.config()
|
||||
.await
|
||||
.config_layer_stack
|
||||
.mcp_ema_cancellation()
|
||||
.is_cancelled()
|
||||
);
|
||||
fork.thread.shutdown_and_wait().await?;
|
||||
parent.thread.shutdown_and_wait().await?;
|
||||
assert!(
|
||||
pending_startup
|
||||
.config_layer_stack
|
||||
.mcp_ema_cancellation()
|
||||
.is_cancelled()
|
||||
);
|
||||
assert!(
|
||||
thread
|
||||
.config()
|
||||
.await
|
||||
.config_layer_stack
|
||||
.mcp_ema_cancellation()
|
||||
.is_cancelled()
|
||||
);
|
||||
let fresh_startup = config_manager
|
||||
.load_for_cwd(
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides::default(),
|
||||
Some(temp_dir.path().join("good")),
|
||||
)
|
||||
.await?;
|
||||
assert!(
|
||||
!fresh_startup
|
||||
.config_layer_stack
|
||||
.mcp_ema_cancellation()
|
||||
.is_cancelled()
|
||||
);
|
||||
|
||||
assert!(
|
||||
thread
|
||||
.config()
|
||||
.await
|
||||
.mcp_servers
|
||||
.get()
|
||||
.contains_key("refreshed")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn refresh_test_state() -> anyhow::Result<(
|
||||
TempDir,
|
||||
Arc<ThreadManager>,
|
||||
ConfigManager,
|
||||
Arc<CountingThreadConfigLoader>,
|
||||
)> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let good_cwd = temp_dir.path().join("good");
|
||||
let bad_cwd = temp_dir.path().join("bad");
|
||||
std::fs::create_dir_all(&good_cwd)?;
|
||||
std::fs::create_dir_all(&bad_cwd)?;
|
||||
std::fs::write(
|
||||
temp_dir.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
"[features]\nsecret_auth_storage = false\n",
|
||||
)?;
|
||||
|
||||
let initial_config_manager =
|
||||
ConfigManager::without_managed_config_for_tests(temp_dir.path().to_path_buf());
|
||||
let good_config = initial_config_manager
|
||||
.load_for_cwd(
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides::default(),
|
||||
Some(good_cwd.clone()),
|
||||
)
|
||||
.await?;
|
||||
let bad_config = initial_config_manager
|
||||
.load_for_cwd(
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides::default(),
|
||||
Some(bad_cwd.clone()),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("dummy"));
|
||||
let state_db = init_state_db(&good_config)
|
||||
.await
|
||||
.expect("refresh tests require state db");
|
||||
let thread_store =
|
||||
ThreadStoreBuilder::from_config(&good_config, Some(state_db.clone())).build();
|
||||
let environment_manager = Arc::new(EnvironmentManager::default_for_tests());
|
||||
let executor_skill_provider: Arc<dyn codex_skills_extension::SkillProvider> = Arc::new(
|
||||
codex_skills_extension::ExecutorSkillProvider::new_with_restriction_product(
|
||||
SessionSource::Exec.restriction_product(),
|
||||
),
|
||||
);
|
||||
let thread_manager = Arc::new_cyclic(|thread_manager| {
|
||||
ThreadManager::new(
|
||||
&good_config,
|
||||
codex_core::build_startup_models(
|
||||
&good_config,
|
||||
auth_manager.clone(),
|
||||
"11111111-1111-4111-8111-111111111111".to_string(),
|
||||
Arc::new(ModelCatalogSettings::disk(
|
||||
good_config.codex_home.to_path_buf(),
|
||||
)),
|
||||
),
|
||||
codex_core::CodexAppsToolsCache::default(),
|
||||
SessionSource::Exec,
|
||||
Arc::clone(&environment_manager),
|
||||
thread_extensions(
|
||||
&good_config,
|
||||
ThreadExtensionDependencies {
|
||||
sample_responses: Arc::new(
|
||||
crate::thread_sample::SampleResponseRegistry::default(),
|
||||
),
|
||||
cloud_skill_provider: None,
|
||||
event_sink: Arc::new(NoopExtensionEventSink),
|
||||
auth_manager: auth_manager.clone(),
|
||||
state_db: Some(state_db.clone()),
|
||||
analytics_events_client: codex_analytics::AnalyticsEventsClient::disabled(),
|
||||
thread_manager: thread_manager.clone(),
|
||||
goal_service: Arc::new(codex_goal_extension::GoalService::new()),
|
||||
environment_manager: Arc::clone(&environment_manager),
|
||||
executor_skill_provider: Arc::clone(&executor_skill_provider),
|
||||
git_attribution_base_url: good_config.chatgpt_base_url.clone(),
|
||||
http_client_factory: good_config.http_client_factory(),
|
||||
queue_service: None,
|
||||
turn_start_admission: None,
|
||||
},
|
||||
),
|
||||
Arc::new(CodexHomeUserInstructionsProvider::new(
|
||||
good_config.codex_home.clone(),
|
||||
)),
|
||||
/*analytics_events_client*/ None,
|
||||
codex_core::passthrough_image_store(),
|
||||
Arc::clone(&thread_store),
|
||||
codex_core::local_agent_graph_store_from_state_db(Some(&state_db)),
|
||||
/*attestation_provider*/ None,
|
||||
/*external_time_provider*/ None,
|
||||
)
|
||||
});
|
||||
thread_manager
|
||||
.start_thread(codex_core::StartThreadOptions::new(good_config))
|
||||
.await?;
|
||||
thread_manager
|
||||
.start_thread(codex_core::StartThreadOptions::new(bad_config))
|
||||
.await?;
|
||||
|
||||
let loader = Arc::new(CountingThreadConfigLoader {
|
||||
good_cwd: AbsolutePathBuf::try_from(good_cwd)?,
|
||||
bad_cwd: AbsolutePathBuf::try_from(bad_cwd)?,
|
||||
good_loads: AtomicUsize::new(0),
|
||||
bad_loads: AtomicUsize::new(0),
|
||||
churn_thread: std::sync::Mutex::new(None),
|
||||
});
|
||||
let config_manager = ConfigManager::new(
|
||||
temp_dir.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
/*strict_config*/ false,
|
||||
CloudConfigBundleLoader::default(),
|
||||
Arg0DispatchPaths::default(),
|
||||
loader.clone(),
|
||||
);
|
||||
|
||||
Ok((temp_dir, thread_manager, config_manager, loader))
|
||||
}
|
||||
|
||||
struct CountingThreadConfigLoader {
|
||||
good_cwd: AbsolutePathBuf,
|
||||
bad_cwd: AbsolutePathBuf,
|
||||
good_loads: AtomicUsize,
|
||||
bad_loads: AtomicUsize,
|
||||
churn_thread: std::sync::Mutex<Option<Arc<CodexThread>>>,
|
||||
}
|
||||
|
||||
impl CountingThreadConfigLoader {
|
||||
async fn load(
|
||||
&self,
|
||||
context: ThreadConfigContext,
|
||||
) -> Result<Vec<ThreadConfigSource>, ThreadConfigLoadError> {
|
||||
if context.cwd.as_ref() == Some(&self.good_cwd) {
|
||||
self.good_loads.fetch_add(1, Ordering::Relaxed);
|
||||
let thread = self.churn_thread.lock().unwrap().clone();
|
||||
if let Some(thread) = thread {
|
||||
let current = thread.config().await;
|
||||
let next = current.as_ref().clone();
|
||||
assert_eq!(
|
||||
thread.refresh_runtime_config(current, next).await,
|
||||
ConfigRefreshOutcome::Published
|
||||
);
|
||||
}
|
||||
}
|
||||
if context.cwd.as_ref() == Some(&self.bad_cwd) {
|
||||
self.bad_loads.fetch_add(1, Ordering::Relaxed);
|
||||
return Err(ThreadConfigLoadError::new(
|
||||
ThreadConfigLoadErrorCode::Internal,
|
||||
/*status_code*/ None,
|
||||
"failed to load refresh config",
|
||||
));
|
||||
}
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadConfigLoader for CountingThreadConfigLoader {
|
||||
fn load(
|
||||
&self,
|
||||
context: ThreadConfigContext,
|
||||
) -> codex_config::ThreadConfigLoaderFuture<'_, Vec<ThreadConfigSource>> {
|
||||
Box::pin(CountingThreadConfigLoader::load(self, context))
|
||||
}
|
||||
}
|
||||
}
|
||||
2070
codex-rs/app-server/src/message_processor.rs
Normal file
2070
codex-rs/app-server/src/message_processor.rs
Normal file
File diff suppressed because it is too large
Load Diff
364
codex-rs/app-server/src/message_processor_gateway_oauth_tests.rs
Normal file
364
codex-rs/app-server/src/message_processor_gateway_oauth_tests.rs
Normal file
@@ -0,0 +1,364 @@
|
||||
//! Exercise gateway sign-in and managed-provider checks through JSON-RPC with a mock keyring.
|
||||
|
||||
use super::ConnectionSessionState;
|
||||
use super::MessageProcessor;
|
||||
use super::message_processor_tracing_tests::TEST_CONNECTION_ID;
|
||||
use super::message_processor_tracing_tests::build_test_processor;
|
||||
use super::message_processor_tracing_tests::read_response;
|
||||
use crate::outgoing_message::OutgoingEnvelope;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use crate::transport::AppServerTransport;
|
||||
use anyhow::Result;
|
||||
use codex_app_server_protocol::GatewayOAuthLoginResponse;
|
||||
use codex_app_server_protocol::GatewayOAuthReadResponse;
|
||||
use codex_app_server_protocol::GatewayOAuthStatus;
|
||||
use codex_app_server_protocol::InitializeResponse;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::test_support::seed_gateway_auth;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
use test_case::test_case;
|
||||
use tokio::time::timeout;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::body_string_contains;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
async fn send_request(
|
||||
processor: &Arc<MessageProcessor>,
|
||||
session: &Arc<ConnectionSessionState>,
|
||||
request: serde_json::Value,
|
||||
) {
|
||||
processor
|
||||
.process_request(
|
||||
TEST_CONNECTION_ID,
|
||||
serde_json::from_value(request).expect("JSON-RPC request"),
|
||||
&AppServerTransport::Stdio,
|
||||
Arc::clone(session),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[test_case(false; "default provider")]
|
||||
#[test_case(true; "explicit non-default provider")]
|
||||
#[tokio::test]
|
||||
async fn gateway_oauth_login_updates_existing_requests(selected: bool) -> Result<()> {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/token"))
|
||||
.and(body_string_contains("grant_type=authorization_code"))
|
||||
.and(body_string_contains("code=accepted"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"access_token": "new-access", "refresh_token": "new-refresh", "expires_in": 3600
|
||||
})))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
r#"
|
||||
model_provider = "gateway"
|
||||
[model_providers.gateway]
|
||||
name = "OpenAI"
|
||||
requires_openai_auth = true
|
||||
base_url = "{url}/v1"
|
||||
wire_api = "responses"
|
||||
[model_providers.gateway.gateway_oauth]
|
||||
authorization_url = "{url}/authorize"
|
||||
token_url = "{url}/token"
|
||||
client_id = "app-server-login-success"
|
||||
delivery = {{ kind = "header", name = "X-Gateway-Authorization" }}
|
||||
"#,
|
||||
url = server.uri()
|
||||
),
|
||||
)?;
|
||||
let config = Arc::new(
|
||||
ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await?,
|
||||
);
|
||||
let auth_manager = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("primary"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let observer = seed_gateway_auth(
|
||||
&config.model_provider,
|
||||
&auth_manager,
|
||||
json!({
|
||||
"access_token": "old-access", "refresh_token": "old-refresh", "expires_at": null,
|
||||
}),
|
||||
);
|
||||
assert_eq!(observer.resolve_access_token().await?, "old-access");
|
||||
let provider = codex_model_provider::create_model_provider(
|
||||
config.model_provider.clone(),
|
||||
Some(Arc::clone(&auth_manager)),
|
||||
);
|
||||
assert_eq!(
|
||||
provider.api_auth().await?.to_auth_headers().unwrap()["x-gateway-authorization"],
|
||||
"Bearer old-access"
|
||||
);
|
||||
let (processor, mut outgoing) = build_test_processor(config, auth_manager).await;
|
||||
let session = Arc::new(ConnectionSessionState::new(
|
||||
crate::transport::ConnectionOrigin::Stdio,
|
||||
));
|
||||
send_request(
|
||||
&processor,
|
||||
&session,
|
||||
json!({
|
||||
"id": 1, "method": "initialize", "params": {
|
||||
"clientInfo": {"name": "gateway-test", "version": "1"}
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let _: InitializeResponse = read_response(&mut outgoing, /*request_id*/ 1).await;
|
||||
// Existing request consumers retain the gateway when the default changes.
|
||||
if selected {
|
||||
let path = home.path().join("config.toml");
|
||||
let text = std::fs::read_to_string(&path)?;
|
||||
std::fs::write(
|
||||
path,
|
||||
text.replace(
|
||||
"model_provider = \"gateway\"",
|
||||
"model_provider = \"openai\"",
|
||||
),
|
||||
)?;
|
||||
}
|
||||
let params = selected.then(|| json!({"modelProvider": "gateway"}));
|
||||
send_request(
|
||||
&processor,
|
||||
&session,
|
||||
json!({"id": 2, "method": "account/gatewayOAuth/login", "params": params}),
|
||||
)
|
||||
.await;
|
||||
let authorization_url = timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
loop {
|
||||
let envelope = outgoing
|
||||
.recv()
|
||||
.await
|
||||
.expect("outgoing channel open during login");
|
||||
if let OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message: OutgoingMessage::AppServerNotification(notification),
|
||||
..
|
||||
} = envelope
|
||||
&& let ServerNotification::GatewayOAuthChanged(changed) = notification.notification
|
||||
&& let Some(url) = changed.auth_url
|
||||
{
|
||||
assert_eq!(connection_id, TEST_CONNECTION_ID);
|
||||
return url;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
let query = url::Url::parse(&authorization_url)?
|
||||
.query_pairs()
|
||||
.into_owned()
|
||||
.collect::<std::collections::HashMap<_, _>>();
|
||||
let mut callback = url::Url::parse(&query["redirect_uri"])?;
|
||||
callback
|
||||
.query_pairs_mut()
|
||||
.append_pair("code", "accepted")
|
||||
.append_pair("state", &query["state"]);
|
||||
codex_login::default_client::create_client_without_request_logging()
|
||||
.get(callback.as_str())
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
let response: GatewayOAuthLoginResponse = read_response(&mut outgoing, /*request_id*/ 2).await;
|
||||
assert_eq!(response, GatewayOAuthLoginResponse {});
|
||||
send_request(
|
||||
&processor,
|
||||
&session,
|
||||
json!({"id": 3, "method": "account/gatewayOAuth/read", "params": params}),
|
||||
)
|
||||
.await;
|
||||
let response: GatewayOAuthReadResponse = read_response(&mut outgoing, /*request_id*/ 3).await;
|
||||
assert_eq!(
|
||||
response,
|
||||
GatewayOAuthReadResponse {
|
||||
provider_id: "gateway".to_string(),
|
||||
provider_name: "OpenAI".to_string(),
|
||||
required: true,
|
||||
status: Some(GatewayOAuthStatus::Succeeded),
|
||||
error: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(observer.resolve_access_token().await?, "new-access");
|
||||
assert_eq!(
|
||||
provider.api_auth().await?.to_auth_headers().unwrap()["x-gateway-authorization"],
|
||||
"Bearer new-access"
|
||||
);
|
||||
processor.shutdown_threads().await;
|
||||
processor.drain_background_tasks().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_oauth_model_list_checks_requirements_before_refreshing_token() -> Result<()> {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/token"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"access_token": "refreshed", "expires_in": 3600,
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let home = TempDir::new()?;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await?;
|
||||
config.model_provider_id = "gateway".into();
|
||||
config.model_provider = toml::from_str(&format!(
|
||||
r#"
|
||||
name = "Gateway"
|
||||
base_url = "{url}/v1"
|
||||
[gateway_oauth]
|
||||
authorization_url = "{url}/authorize"
|
||||
token_url = "{url}/token"
|
||||
client_id = "app-server-requirements-test"
|
||||
delivery = {{ kind = "header", name = "X-Gateway-Authorization" }}
|
||||
"#,
|
||||
url = server.uri(),
|
||||
))?;
|
||||
let auth_manager = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("primary"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let _gateway = seed_gateway_auth(
|
||||
&config.model_provider,
|
||||
&auth_manager,
|
||||
json!({"access_token": "expired", "refresh_token": "old-refresh", "expires_at": 0}),
|
||||
);
|
||||
let (processor, mut outgoing) = build_test_processor(Arc::new(config), auth_manager).await;
|
||||
let session = Arc::new(ConnectionSessionState::new(
|
||||
crate::transport::ConnectionOrigin::Stdio,
|
||||
));
|
||||
send_request(
|
||||
&processor,
|
||||
&session,
|
||||
json!({"id": 1, "method": "initialize", "params": {
|
||||
"clientInfo": {"name": "gateway-test", "version": "1"},
|
||||
"capabilities": {"explicitGatewayOauth": true},
|
||||
}}),
|
||||
)
|
||||
.await;
|
||||
let _: InitializeResponse = read_response(&mut outgoing, /*request_id*/ 1).await;
|
||||
std::fs::write(
|
||||
home.path().join("requirements.toml"),
|
||||
"model_provider = 'openai'",
|
||||
)?;
|
||||
send_request(
|
||||
&processor,
|
||||
&session,
|
||||
json!({"id": 2, "method": "model/list", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
let error = timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
loop {
|
||||
if let OutgoingEnvelope::ToConnection {
|
||||
message: OutgoingMessage::Error(error),
|
||||
..
|
||||
} = outgoing
|
||||
.recv()
|
||||
.await
|
||||
.expect("outgoing channel open during request")
|
||||
{
|
||||
break error.error;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(
|
||||
error,
|
||||
JSONRPCErrorError {
|
||||
code: -32600,
|
||||
message: codex_app_server_protocol::ModelProviderError::ModelProviderPolicyConflict {
|
||||
model_provider: "gateway".into(),
|
||||
required_model_provider: "openai".into(),
|
||||
}
|
||||
.to_string(),
|
||||
data: Some(serde_json::to_value(
|
||||
codex_app_server_protocol::ModelProviderError::ModelProviderPolicyConflict {
|
||||
model_provider: "gateway".into(),
|
||||
required_model_provider: "openai".into(),
|
||||
}
|
||||
)?),
|
||||
}
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
processor.shutdown_threads().await;
|
||||
processor.drain_background_tasks().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checking another provider must not recreate the first provider's readiness state.
|
||||
#[tokio::test]
|
||||
async fn gateway_oauth_read_retains_each_provider_status() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let mut text = String::from("[features]\nsecret_auth_storage = true\n");
|
||||
for id in ["first", "second"] {
|
||||
text.push_str(&format!(
|
||||
r#"
|
||||
[model_providers.{id}]
|
||||
name = "{id}"
|
||||
base_url = "https://{id}.example/v1"
|
||||
wire_api = "responses"
|
||||
[model_providers.{id}.gateway_oauth]
|
||||
authorization_url = "https://{id}.example/authorize"
|
||||
token_url = "https://{id}.example/token"
|
||||
client_id = "{id}"
|
||||
delivery = {{ kind = "header", name = "X-Gateway-Authorization" }}
|
||||
"#
|
||||
));
|
||||
}
|
||||
std::fs::write(home.path().join("config.toml"), text)?;
|
||||
let config = Arc::new(
|
||||
ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await?,
|
||||
);
|
||||
let auth = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("primary"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let mut changes = codex_login::subscribe_gateway_auth_status(&auth.runtime_config());
|
||||
let (processor, _outgoing) = build_test_processor(config, auth).await;
|
||||
for (id, changed) in [("first", true), ("second", true), ("first", false)] {
|
||||
let state = processor
|
||||
.account_processor
|
||||
.gateway_oauth_read(codex_app_server_protocol::GatewayOAuthReadParams {
|
||||
model_provider: Some(id.into()),
|
||||
})
|
||||
.await
|
||||
.map_err(|err| anyhow::anyhow!("{}", err.message))?;
|
||||
assert_eq!(state.provider_id, id);
|
||||
assert_eq!(state.status, Some(GatewayOAuthStatus::NotReady));
|
||||
if changed {
|
||||
assert_eq!(
|
||||
changes.try_recv()?.status,
|
||||
codex_login::GatewayAuthStatus::NotReady
|
||||
);
|
||||
} else {
|
||||
assert!(matches!(
|
||||
changes.try_recv(),
|
||||
Err(tokio::sync::broadcast::error::TryRecvError::Empty)
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,759 @@
|
||||
//! Exercises client attachment, approval routing, and cleanup across thread creation.
|
||||
|
||||
use codex_app_server_protocol::TurnStartResponse;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::protocol::AgentStatus;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::streaming_sse::StreamingSseChunk;
|
||||
use core_test_support::streaming_sse::start_streaming_sse_server;
|
||||
use pretty_assertions::assert_eq;
|
||||
use test_case::test_case;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use super::ConnectionSessionState;
|
||||
use super::MessageProcessor;
|
||||
use super::message_processor_tracing_tests::build_test_processor;
|
||||
use super::message_processor_tracing_tests::read_response_from;
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::OutgoingEnvelope;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use crate::transport::AppServerTransport;
|
||||
use crate::transport::ConnectionOrigin;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use app_test_support::MockResponsesConfig;
|
||||
use app_test_support::create_mock_responses_server_sequence_unchecked;
|
||||
use codex_app_server_protocol::InitializeResponse;
|
||||
use codex_app_server_protocol::JSONRPCError;
|
||||
use codex_app_server_protocol::JSONRPCResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ServerRequest;
|
||||
use codex_app_server_protocol::ThreadClosedNotification;
|
||||
use codex_app_server_protocol::ThreadLoadedListResponse;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_login::AuthManager;
|
||||
use core_test_support::fs_wait::wait_for_path_exists;
|
||||
use core_test_support::process::wait_for_pid_file;
|
||||
use core_test_support::stdio_server_bin;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_unloads_after_requesting_connection_closes_during_mcp_startup() -> Result<()>
|
||||
{
|
||||
let server = create_mock_responses_server_sequence_unchecked(Vec::new()).await;
|
||||
let home = TempDir::new()?;
|
||||
let barrier_file = home.path().join("allow-initialize");
|
||||
let pid_file = home.path().join("mcp.pid");
|
||||
MockResponsesConfig::new(&server.uri())
|
||||
.with_root_config("thread_unload_delay_secs = 1")
|
||||
.with_extra_config(&format!(
|
||||
r#"[mcp_servers.blocked]
|
||||
command = {}
|
||||
required = true
|
||||
startup_timeout_sec = 120
|
||||
|
||||
[mcp_servers.blocked.env]
|
||||
MCP_TEST_INITIALIZE_BARRIER_FILE = {}
|
||||
MCP_TEST_PID_FILE = {}
|
||||
"#,
|
||||
toml::Value::String(stdio_server_bin()?),
|
||||
toml::Value::String(barrier_file.to_string_lossy().into_owned()),
|
||||
toml::Value::String(pid_file.to_string_lossy().into_owned()),
|
||||
))
|
||||
.write(home.path())?;
|
||||
let config = Arc::new(
|
||||
ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await?,
|
||||
);
|
||||
let auth =
|
||||
AuthManager::shared_from_config(config.as_ref(), /*enable_codex_api_key_env*/ false)
|
||||
.await?;
|
||||
let (processor, mut outgoing) = build_test_processor(config, auth).await;
|
||||
let owner_id = ConnectionId(1);
|
||||
let owner = Arc::new(ConnectionSessionState::new(ConnectionOrigin::WebSocket));
|
||||
let result: Result<()> = async {
|
||||
send_request(
|
||||
&processor,
|
||||
owner_id,
|
||||
&owner,
|
||||
json!({"id": 1, "method": "initialize", "params": {
|
||||
"clientInfo": {"name": "startup-owner", "version": "1"},
|
||||
"capabilities": {"experimentalApi": true}
|
||||
}}),
|
||||
)
|
||||
.await;
|
||||
let _: InitializeResponse =
|
||||
read_response_from(&mut outgoing, owner_id, /*request_id*/ 1).await;
|
||||
send_request(
|
||||
&processor,
|
||||
owner_id,
|
||||
&owner,
|
||||
json!({"id": 2, "method": "thread/start", "params": {"ephemeral": true}}),
|
||||
)
|
||||
.await;
|
||||
wait_for_path_exists(&pid_file, Duration::from_secs(/*secs*/ 10)).await?;
|
||||
#[cfg(unix)]
|
||||
let pid = wait_for_pid_file(&pid_file).await?;
|
||||
#[cfg(not(unix))]
|
||||
wait_for_pid_file(&pid_file).await?;
|
||||
#[cfg(unix)]
|
||||
anyhow::ensure!(
|
||||
core_test_support::process::process_is_alive(&pid)?,
|
||||
"MCP process should be running before releasing startup"
|
||||
);
|
||||
|
||||
// Advance only connection cleanup's clock. Startup and idle unloading keep
|
||||
// using the original runtime's real clock while the MCP barrier stays closed.
|
||||
let cleanup = tokio::task::spawn_blocking({
|
||||
let processor = Arc::clone(&processor);
|
||||
let owner = Arc::clone(&owner);
|
||||
move || -> Result<()> {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.start_paused(/*start_paused*/ true)
|
||||
.build()?;
|
||||
runtime.block_on(async {
|
||||
timeout(
|
||||
Duration::from_secs(/*secs*/ 45),
|
||||
processor.connection_closed(owner_id, &owner),
|
||||
)
|
||||
.await
|
||||
.context("connection cleanup did not finish while MCP startup was blocked")
|
||||
})
|
||||
}
|
||||
});
|
||||
cleanup
|
||||
.await
|
||||
.context("connection cleanup task panicked")??;
|
||||
std::fs::write(&barrier_file, "ready")?;
|
||||
|
||||
// The harness receives the completed handler's output even though its transport is gone.
|
||||
// Retain both messages because idle unloading can finish before the response is consumed.
|
||||
let (started, closed) = timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
let mut started: Option<ThreadStartResponse> = None;
|
||||
let mut closed = None;
|
||||
while started.is_none() || closed.is_none() {
|
||||
let envelope = outgoing.recv().await.context("outgoing channel closed")?;
|
||||
match envelope {
|
||||
OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message: OutgoingMessage::Response(response),
|
||||
..
|
||||
} if connection_id == owner_id && response.id == RequestId::Integer(2) => {
|
||||
started = Some(serde_json::from_value(serde_json::to_value(
|
||||
response.result,
|
||||
)?)?);
|
||||
}
|
||||
OutgoingEnvelope::Broadcast {
|
||||
message: OutgoingMessage::AppServerNotification(notification),
|
||||
} => {
|
||||
if let ServerNotification::ThreadClosed(notification) =
|
||||
notification.notification
|
||||
{
|
||||
closed = Some(notification);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
anyhow::Ok((
|
||||
started.context("missing thread/start response")?,
|
||||
closed.context("missing thread/closed notification")?,
|
||||
))
|
||||
})
|
||||
.await
|
||||
.context("thread created after disconnect did not unload")??;
|
||||
anyhow::ensure!(
|
||||
closed
|
||||
== (ThreadClosedNotification {
|
||||
thread_id: started.thread.id
|
||||
}),
|
||||
"unexpected thread/closed notification: {closed:?}"
|
||||
);
|
||||
|
||||
let observer_id = ConnectionId(2);
|
||||
let observer = Arc::new(ConnectionSessionState::new(ConnectionOrigin::WebSocket));
|
||||
send_request(
|
||||
&processor,
|
||||
observer_id,
|
||||
&observer,
|
||||
json!({"id": 3, "method": "initialize", "params": {
|
||||
"clientInfo": {"name": "loaded-thread-observer", "version": "1"}
|
||||
}}),
|
||||
)
|
||||
.await;
|
||||
let _: InitializeResponse =
|
||||
read_response_from(&mut outgoing, observer_id, /*request_id*/ 3).await;
|
||||
send_request(
|
||||
&processor,
|
||||
observer_id,
|
||||
&observer,
|
||||
json!({"id": 4, "method": "thread/loaded/list", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
let loaded: ThreadLoadedListResponse =
|
||||
read_response_from(&mut outgoing, observer_id, /*request_id*/ 4).await;
|
||||
anyhow::ensure!(
|
||||
loaded
|
||||
== (ThreadLoadedListResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
}),
|
||||
"disconnected thread remained loaded: {loaded:?}"
|
||||
);
|
||||
#[cfg(unix)]
|
||||
core_test_support::process::wait_for_process_exit(&pid).await?;
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
|
||||
// Release the startup fixture and reap its runtime even when the regression assertion fails.
|
||||
std::fs::write(&barrier_file, "ready")?;
|
||||
drop(outgoing);
|
||||
let drained = timeout(Duration::from_secs(/*secs*/ 10), owner.rpc_gate.shutdown()).await;
|
||||
processor.clear_runtime_references();
|
||||
processor.shutdown_threads().await;
|
||||
drained.context("thread/start did not finish during test cleanup")?;
|
||||
result?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case(0, false; "v2_zero_delay")]
|
||||
#[test_case(1, false; "v2_one_second_delay")]
|
||||
#[test_case(1, true; "ephemeral_v2_followup_after_idle_deadline")]
|
||||
#[tokio::test]
|
||||
async fn disconnected_v2_child_lifecycle(unload_delay_secs: u64, ephemeral: bool) -> Result<()> {
|
||||
let (release_spawn, spawn_gate) = oneshot::channel();
|
||||
let (release_spawn_completion, spawn_completion_gate) = oneshot::channel();
|
||||
let (release_first_completion, first_completion_gate) = oneshot::channel();
|
||||
let (release_second_completion, second_completion_gate) = oneshot::channel();
|
||||
let done = responses::sse(vec![
|
||||
responses::ev_response_created("done"),
|
||||
responses::ev_assistant_message("done", "Done"),
|
||||
responses::ev_completed("done"),
|
||||
]);
|
||||
let (server, _completions) = start_streaming_sse_server(vec![
|
||||
vec![
|
||||
StreamingSseChunk {
|
||||
gate: Some(spawn_gate),
|
||||
body: responses::sse(vec![
|
||||
responses::ev_response_created("spawn"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
"spawn",
|
||||
"collaboration",
|
||||
"spawn_agent",
|
||||
&json!({"task_name": "child", "message": "Reply done", "fork_turns": "none"})
|
||||
.to_string(),
|
||||
),
|
||||
]),
|
||||
},
|
||||
StreamingSseChunk {
|
||||
gate: Some(spawn_completion_gate),
|
||||
body: responses::sse(vec![responses::ev_completed("spawn")]),
|
||||
},
|
||||
],
|
||||
vec![StreamingSseChunk {
|
||||
gate: Some(first_completion_gate),
|
||||
body: done.clone(),
|
||||
}],
|
||||
vec![StreamingSseChunk {
|
||||
gate: Some(second_completion_gate),
|
||||
body: if ephemeral {
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("followup"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
"followup",
|
||||
"collaboration",
|
||||
"followup_task",
|
||||
&json!({"target": "child", "message": "Recall your previous reply"})
|
||||
.to_string(),
|
||||
),
|
||||
responses::ev_completed("followup"),
|
||||
])
|
||||
} else {
|
||||
done.clone()
|
||||
},
|
||||
}],
|
||||
// Follow-up responses and the child's completion notification.
|
||||
vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
body: done.clone(),
|
||||
}],
|
||||
vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
body: done.clone(),
|
||||
}],
|
||||
vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
body: done,
|
||||
}],
|
||||
])
|
||||
.await;
|
||||
let home = TempDir::new()?;
|
||||
let config = MockResponsesConfig::new(server.uri())
|
||||
.with_root_config(&format!(
|
||||
"thread_unload_delay_secs = {unload_delay_secs}\napprovals_reviewer = \"user\""
|
||||
))
|
||||
.enable_feature(Feature::Collab)
|
||||
.enable_feature(Feature::MultiAgentV2);
|
||||
config.write(home.path())?;
|
||||
let config = Arc::new(
|
||||
ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await?,
|
||||
);
|
||||
let auth =
|
||||
AuthManager::shared_from_config(config.as_ref(), /*enable_codex_api_key_env*/ false)
|
||||
.await?;
|
||||
let (processor, mut outgoing) = build_test_processor(config, auth).await;
|
||||
let mut created = processor.thread_created_receiver();
|
||||
let owner_id = ConnectionId(1);
|
||||
let owner = Arc::new(ConnectionSessionState::new(ConnectionOrigin::WebSocket));
|
||||
let result: Result<()> = async {
|
||||
send_request(
|
||||
&processor,
|
||||
owner_id,
|
||||
&owner,
|
||||
json!({"id": 1, "method": "initialize", "params": {
|
||||
"clientInfo": {"name": "parent-owner", "version": "1"},
|
||||
"capabilities": {"experimentalApi": true}
|
||||
}}),
|
||||
)
|
||||
.await;
|
||||
let _: InitializeResponse =
|
||||
read_response_from(&mut outgoing, owner_id, /*request_id*/ 1).await;
|
||||
processor
|
||||
.connection_initialized(owner_id, owner.request_attestation())
|
||||
.await;
|
||||
send_request(
|
||||
&processor,
|
||||
owner_id,
|
||||
&owner,
|
||||
json!({"id": 2, "method": "thread/start", "params": {"ephemeral": ephemeral}}),
|
||||
)
|
||||
.await;
|
||||
let parent: ThreadStartResponse =
|
||||
read_response_from(&mut outgoing, owner_id, /*request_id*/ 2).await;
|
||||
send_request(
|
||||
&processor,
|
||||
owner_id,
|
||||
&owner,
|
||||
json!({"id": 3, "method": "turn/start", "params": {
|
||||
"threadId": parent.thread.id,
|
||||
"input": [{"type": "text", "text": "Spawn a child and finish"}]
|
||||
}}),
|
||||
)
|
||||
.await;
|
||||
let _: TurnStartResponse =
|
||||
read_response_from(&mut outgoing, owner_id, /*request_id*/ 3).await;
|
||||
timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
server.wait_for_request_count(/*count*/ 1),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Finish connection cleanup before the model can create a child. Dispatch the
|
||||
// core creation event exactly as the app-server does with no initialized clients.
|
||||
processor.connection_closed(owner_id, &owner).await;
|
||||
release_spawn.send(()).expect("parent response is waiting");
|
||||
let child_id = timeout(Duration::from_secs(/*secs*/ 10), created.recv()).await??;
|
||||
let child_runtime = Arc::downgrade(
|
||||
&processor
|
||||
.thread_processor
|
||||
.thread_manager
|
||||
.get_thread(child_id)
|
||||
.await?,
|
||||
);
|
||||
let attach = processor.try_attach_thread_listener(child_id, Vec::new());
|
||||
tokio::pin!(attach);
|
||||
// The old runtime has left core, but its app-server cleanup still owns the ID.
|
||||
let pending = &processor.thread_processor.pending_thread_unloads;
|
||||
pending
|
||||
.lock()
|
||||
.await
|
||||
.insert(child_id, tokio::sync::watch::channel(()).0);
|
||||
assert!(
|
||||
futures::poll!(&mut attach).is_pending(),
|
||||
"attachment must wait for old cleanup"
|
||||
);
|
||||
pending.lock().await.remove(&child_id);
|
||||
attach.await;
|
||||
// Keep the spawn response open until the child's model request arrives, so
|
||||
// the next gated response belongs to the parent regardless of scheduling.
|
||||
timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
server.wait_for_request_count(/*count*/ 2),
|
||||
)
|
||||
.await?;
|
||||
release_spawn_completion
|
||||
.send(())
|
||||
.expect("spawn completion is waiting");
|
||||
timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
server.wait_for_request_count(/*count*/ 3),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Installing an unsubscribed listener must not unload a still-running child.
|
||||
let premature_close = timeout(Duration::from_millis(/*millis*/ 1200), async {
|
||||
loop {
|
||||
if let OutgoingEnvelope::Broadcast {
|
||||
message: OutgoingMessage::AppServerNotification(notification),
|
||||
} = outgoing.recv().await.expect("outgoing channel stays open")
|
||||
&& matches!(
|
||||
notification.notification,
|
||||
ServerNotification::ThreadClosed(_)
|
||||
)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert!(premature_close.is_err(), "running threads must stay loaded");
|
||||
if ephemeral {
|
||||
// Complete the child while the parent's follow-up response remains gated.
|
||||
let child = processor
|
||||
.thread_processor
|
||||
.thread_manager
|
||||
.get_thread(child_id)
|
||||
.await?;
|
||||
release_first_completion
|
||||
.send(())
|
||||
.expect("child completion is waiting");
|
||||
timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
while !matches!(child.agent_status().await, AgentStatus::Completed(_)) {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("child did not complete")?;
|
||||
tokio::time::sleep(Duration::from_secs(unload_delay_secs + 1)).await;
|
||||
release_second_completion
|
||||
.send(())
|
||||
.expect("parent completion is waiting");
|
||||
|
||||
// Exercise the parent's real followup_task call and inspect the child's next
|
||||
// model request: accepting a follow-up must preserve its earlier model context.
|
||||
timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
server.wait_for_request_count(/*count*/ 5),
|
||||
)
|
||||
.await
|
||||
.context("ephemeral child did not receive its follow-up")?;
|
||||
let requests = server.requests().await;
|
||||
let followup = requests[3..]
|
||||
.iter()
|
||||
.map(|request| serde_json::from_slice::<serde_json::Value>(request))
|
||||
.collect::<std::result::Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.find(|request| {
|
||||
request["input"]
|
||||
.to_string()
|
||||
.contains("Recall your previous reply")
|
||||
&& !request["input"].as_array().is_some_and(|input| {
|
||||
input.iter().any(|item| {
|
||||
item["type"] == "function_call_output" && item["call_id"] == "spawn"
|
||||
})
|
||||
})
|
||||
})
|
||||
.context("missing child follow-up request")?;
|
||||
let previous_reply = followup["input"]
|
||||
.as_array()
|
||||
.context("follow-up input")?
|
||||
.iter()
|
||||
.find(|item| item["role"] == "assistant")
|
||||
.context("child's previous reply must survive the idle deadline")?;
|
||||
assert_eq!(
|
||||
previous_reply["content"],
|
||||
json!([{"type": "output_text", "text": "Done"}])
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
release_first_completion
|
||||
.send(())
|
||||
.expect("first completion is waiting");
|
||||
release_second_completion
|
||||
.send(())
|
||||
.expect("second completion is waiting");
|
||||
|
||||
// Check both registry cleanup and runtime release, regardless of the order
|
||||
// in which the parent and child finish unloading.
|
||||
timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
loop {
|
||||
let loaded = processor
|
||||
.thread_processor
|
||||
.thread_manager
|
||||
.list_thread_ids()
|
||||
.await;
|
||||
if loaded.is_empty() && child_runtime.upgrade().is_none() {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("parent and disconnected child still retain their runtimes")?;
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
drop(outgoing);
|
||||
processor.clear_runtime_references();
|
||||
processor.shutdown_threads().await;
|
||||
server.shutdown().await;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn child_human_approval_survives_attachment_and_rejects_unrelated_clients() -> Result<()> {
|
||||
let (release_spawn_completion, spawn_completion_gate) = oneshot::channel();
|
||||
let (server, _completions) = start_streaming_sse_server(vec![
|
||||
vec![
|
||||
StreamingSseChunk {
|
||||
gate: None,
|
||||
body: responses::sse(vec![
|
||||
responses::ev_response_created("spawn"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
"spawn",
|
||||
"collaboration",
|
||||
"spawn_agent",
|
||||
&json!({"task_name": "child", "message": "Run echo", "fork_turns": "none"})
|
||||
.to_string(),
|
||||
),
|
||||
]),
|
||||
},
|
||||
StreamingSseChunk {
|
||||
gate: Some(spawn_completion_gate),
|
||||
body: responses::sse(vec![responses::ev_completed("spawn")]),
|
||||
},
|
||||
],
|
||||
vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
body: responses::sse(vec![
|
||||
responses::ev_response_created("command"),
|
||||
responses::ev_function_call(
|
||||
"child-command",
|
||||
"exec_command",
|
||||
&json!({"cmd": "echo human-approved"}).to_string(),
|
||||
),
|
||||
responses::ev_completed("command"),
|
||||
]),
|
||||
}],
|
||||
])
|
||||
.await;
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("requirements.toml"),
|
||||
r#"
|
||||
[features]
|
||||
unified_exec = false
|
||||
shell_tool = true
|
||||
|
||||
[[rules.prefix_rules]]
|
||||
pattern = [{ token = "echo" }]
|
||||
decision = "prompt-user"
|
||||
"#,
|
||||
)?;
|
||||
MockResponsesConfig::new(server.uri())
|
||||
.with_approval_policy("on-request")
|
||||
.with_sandbox_mode("workspace-write")
|
||||
.with_root_config("approvals_reviewer = \"auto_review\"")
|
||||
.enable_feature(Feature::Collab)
|
||||
.enable_feature(Feature::MultiAgentV2)
|
||||
.write(home.path())?;
|
||||
let config = Arc::new(
|
||||
ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await?,
|
||||
);
|
||||
let auth =
|
||||
AuthManager::shared_from_config(config.as_ref(), /*enable_codex_api_key_env*/ false)
|
||||
.await?;
|
||||
let (processor, mut outgoing) = build_test_processor(config, auth).await;
|
||||
let mut created = processor.thread_created_receiver();
|
||||
let incompatible_id = ConnectionId(1);
|
||||
let capable_id = ConnectionId(2);
|
||||
let unrelated_id = ConnectionId(3);
|
||||
let incompatible = Arc::new(ConnectionSessionState::new(ConnectionOrigin::WebSocket));
|
||||
let capable = Arc::new(ConnectionSessionState::new(ConnectionOrigin::WebSocket));
|
||||
let unrelated = Arc::new(ConnectionSessionState::new(ConnectionOrigin::WebSocket));
|
||||
let result: Result<()> = async {
|
||||
for (id, session, required_human_approval) in [
|
||||
(incompatible_id, &incompatible, false),
|
||||
(capable_id, &capable, true),
|
||||
] {
|
||||
send_request(
|
||||
&processor,
|
||||
id,
|
||||
session,
|
||||
json!({"id": 1, "method": "initialize", "params": {
|
||||
"clientInfo": {"name": "attachment-test", "version": "1"},
|
||||
"capabilities": {
|
||||
"experimentalApi": true,
|
||||
"requiredHumanApproval": required_human_approval
|
||||
}
|
||||
}}),
|
||||
)
|
||||
.await;
|
||||
let _: InitializeResponse =
|
||||
read_response_from(&mut outgoing, id, /*request_id*/ 1).await;
|
||||
processor
|
||||
.connection_initialized(id, session.request_attestation())
|
||||
.await;
|
||||
}
|
||||
send_request(
|
||||
&processor,
|
||||
incompatible_id,
|
||||
&incompatible,
|
||||
json!({"id": 2, "method": "thread/start", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
let parent: ThreadStartResponse =
|
||||
read_response_from(&mut outgoing, incompatible_id, /*request_id*/ 2).await;
|
||||
send_request(
|
||||
&processor,
|
||||
incompatible_id,
|
||||
&incompatible,
|
||||
json!({"id": 3, "method": "turn/start", "params": {
|
||||
"threadId": parent.thread.id,
|
||||
"input": [{"type": "text", "text": "Spawn a child to run echo"}]
|
||||
}}),
|
||||
)
|
||||
.await;
|
||||
let _: TurnStartResponse =
|
||||
read_response_from(&mut outgoing, incompatible_id, /*request_id*/ 3).await;
|
||||
let child_id = timeout(Duration::from_secs(/*secs*/ 10), created.recv()).await??;
|
||||
|
||||
while outgoing.try_recv().is_ok() {}
|
||||
// Attach the initial client set before draining the child's queued approval.
|
||||
processor
|
||||
.try_attach_thread_listener(child_id, vec![incompatible_id, capable_id])
|
||||
.await;
|
||||
let request = timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
loop {
|
||||
if let OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message: OutgoingMessage::Request(request),
|
||||
..
|
||||
} = outgoing.recv().await.context("outgoing channel closed")?
|
||||
{
|
||||
assert_eq!(connection_id, capable_id);
|
||||
break anyhow::Ok(request);
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("capable client did not receive the child's approval during attachment")??;
|
||||
let ServerRequest::CommandExecutionRequestApproval { request_id, params } = &request else {
|
||||
anyhow::bail!("expected human approval, got {request:?}");
|
||||
};
|
||||
assert_eq!(
|
||||
(¶ms.thread_id, params.kind),
|
||||
(
|
||||
&child_id.to_string(),
|
||||
codex_app_server_protocol::CommandExecutionApprovalKind::HumanCommand,
|
||||
),
|
||||
);
|
||||
|
||||
// Initialize a capable client after auto-attachment. Capability alone must not
|
||||
// let it approve or reject this request before it subscribes and receives it.
|
||||
send_request(
|
||||
&processor,
|
||||
unrelated_id,
|
||||
&unrelated,
|
||||
json!({"id": 1, "method": "initialize", "params": {
|
||||
"clientInfo": {"name": "unrelated-client", "version": "1"},
|
||||
"capabilities": {"experimentalApi": true, "requiredHumanApproval": true}
|
||||
}}),
|
||||
)
|
||||
.await;
|
||||
let _: InitializeResponse =
|
||||
read_response_from(&mut outgoing, unrelated_id, /*request_id*/ 1).await;
|
||||
processor
|
||||
.connection_initialized(unrelated_id, unrelated.request_attestation())
|
||||
.await;
|
||||
for connection_id in [incompatible_id, unrelated_id] {
|
||||
processor
|
||||
.process_response(
|
||||
connection_id,
|
||||
JSONRPCResponse {
|
||||
id: request_id.clone(),
|
||||
result: json!({"decision": "accept"}),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
processor
|
||||
.process_error(
|
||||
connection_id,
|
||||
JSONRPCError {
|
||||
id: request_id.clone(),
|
||||
error: crate::error_code::internal_error("unsupported request"),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
processor
|
||||
.outgoing
|
||||
.pending_requests_for_thread(child_id)
|
||||
.await,
|
||||
vec![request.clone()],
|
||||
"unrouted responses and errors must leave the request pending",
|
||||
);
|
||||
}
|
||||
|
||||
// Routing ends at the human decision. Command execution and replay have
|
||||
// their own coverage; declining here needs no Linux sandbox executable.
|
||||
processor
|
||||
.process_response(
|
||||
capable_id,
|
||||
JSONRPCResponse {
|
||||
id: request_id.clone(),
|
||||
result: json!({"decision": "decline"}),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
processor
|
||||
.outgoing
|
||||
.pending_requests_for_thread(child_id)
|
||||
.await
|
||||
.is_empty()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
drop(release_spawn_completion);
|
||||
drop(outgoing);
|
||||
processor.clear_runtime_references();
|
||||
processor.shutdown_threads().await;
|
||||
server.shutdown().await;
|
||||
result
|
||||
}
|
||||
|
||||
async fn send_request(
|
||||
processor: &Arc<MessageProcessor>,
|
||||
connection_id: ConnectionId,
|
||||
session: &Arc<ConnectionSessionState>,
|
||||
request: serde_json::Value,
|
||||
) {
|
||||
processor
|
||||
.process_request(
|
||||
connection_id,
|
||||
serde_json::from_value(request).expect("JSON-RPC request"),
|
||||
&AppServerTransport::WebSocket {
|
||||
bind_address: "127.0.0.1:0".parse().expect("loopback address"),
|
||||
},
|
||||
Arc::clone(session),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
751
codex-rs/app-server/src/message_processor_tracing_tests.rs
Normal file
751
codex-rs/app-server/src/message_processor_tracing_tests.rs
Normal file
@@ -0,0 +1,751 @@
|
||||
use super::ConnectionSessionState;
|
||||
use super::MessageProcessor;
|
||||
use super::MessageProcessorArgs;
|
||||
use crate::analytics_utils::analytics_events_client_from_config;
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use crate::plugin_config_reload::PluginStartupConfig;
|
||||
use crate::transport::AppServerTransport;
|
||||
use anyhow::Result;
|
||||
use app_test_support::create_mock_responses_server_repeating_assistant;
|
||||
use app_test_support::write_mock_responses_config_toml;
|
||||
use codex_analytics::AppServerRpcTransport;
|
||||
use codex_app_server_protocol::ClientInfo;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::InitializeCapabilities;
|
||||
use codex_app_server_protocol::InitializeParams;
|
||||
use codex_app_server_protocol::InitializeResponse;
|
||||
use codex_app_server_protocol::JSONRPCRequest;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
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;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_feedback::CodexFeedback;
|
||||
use codex_login::AuthManager;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use opentelemetry::global;
|
||||
use opentelemetry::trace::SpanId;
|
||||
use opentelemetry::trace::SpanKind;
|
||||
use opentelemetry::trace::TraceId;
|
||||
use opentelemetry::trace::TracerProvider as _;
|
||||
use opentelemetry_sdk::propagation::TraceContextPropagator;
|
||||
use opentelemetry_sdk::trace::InMemorySpanExporter;
|
||||
use opentelemetry_sdk::trace::SdkTracerProvider;
|
||||
use opentelemetry_sdk::trace::SpanData;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serial_test::serial;
|
||||
use std::collections::BTreeMap;
|
||||
use std::future::Future;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use wiremock::MockServer;
|
||||
|
||||
pub(super) const TEST_CONNECTION_ID: ConnectionId = ConnectionId(7);
|
||||
|
||||
struct TestTracing {
|
||||
exporter: InMemorySpanExporter,
|
||||
provider: SdkTracerProvider,
|
||||
}
|
||||
|
||||
struct RemoteTrace {
|
||||
trace_id: TraceId,
|
||||
parent_span_id: SpanId,
|
||||
context: W3cTraceContext,
|
||||
}
|
||||
|
||||
impl RemoteTrace {
|
||||
fn new(trace_id: &str, parent_span_id: &str) -> Self {
|
||||
let trace_id = TraceId::from_hex(trace_id).expect("trace id");
|
||||
let parent_span_id = SpanId::from_hex(parent_span_id).expect("parent span id");
|
||||
let context = W3cTraceContext {
|
||||
traceparent: Some(format!("00-{trace_id}-{parent_span_id}-01")),
|
||||
tracestate: Some("vendor=value".to_string()),
|
||||
};
|
||||
|
||||
Self {
|
||||
trace_id,
|
||||
parent_span_id,
|
||||
context,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn init_test_tracing() -> &'static TestTracing {
|
||||
static TEST_TRACING: OnceLock<TestTracing> = OnceLock::new();
|
||||
TEST_TRACING.get_or_init(|| {
|
||||
let exporter = InMemorySpanExporter::default();
|
||||
let provider = SdkTracerProvider::builder()
|
||||
.with_simple_exporter(exporter.clone())
|
||||
.build();
|
||||
let tracer = provider.tracer("codex-app-server-message-processor-tests");
|
||||
global::set_text_map_propagator(TraceContextPropagator::new());
|
||||
let subscriber =
|
||||
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer));
|
||||
tracing::subscriber::set_global_default(subscriber)
|
||||
.expect("global tracing subscriber should only be installed once");
|
||||
TestTracing { exporter, provider }
|
||||
})
|
||||
}
|
||||
|
||||
fn request_from_client_request(request: ClientRequest) -> JSONRPCRequest {
|
||||
serde_json::from_value(serde_json::to_value(request).expect("serialize client request"))
|
||||
.expect("client request should convert to JSON-RPC")
|
||||
}
|
||||
|
||||
struct TracingHarness {
|
||||
_server: MockServer,
|
||||
_codex_home: TempDir,
|
||||
processor: Arc<MessageProcessor>,
|
||||
outgoing_rx: mpsc::Receiver<crate::outgoing_message::OutgoingEnvelope>,
|
||||
session: Arc<ConnectionSessionState>,
|
||||
tracing: &'static TestTracing,
|
||||
}
|
||||
|
||||
impl TracingHarness {
|
||||
async fn new() -> Result<Self> {
|
||||
let server = create_mock_responses_server_repeating_assistant("Done").await;
|
||||
let codex_home = TempDir::new()?;
|
||||
let config = Arc::new(build_test_config(codex_home.path(), &server.uri()).await?);
|
||||
let auth_manager = AuthManager::shared_from_config(
|
||||
config.as_ref(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await?;
|
||||
let (processor, outgoing_rx) = build_test_processor(config, auth_manager).await;
|
||||
let tracing = init_test_tracing();
|
||||
tracing.exporter.reset();
|
||||
tracing::callsite::rebuild_interest_cache();
|
||||
let mut harness = Self {
|
||||
_server: server,
|
||||
_codex_home: codex_home,
|
||||
processor,
|
||||
outgoing_rx,
|
||||
session: Arc::new(ConnectionSessionState::new(
|
||||
crate::transport::ConnectionOrigin::Stdio,
|
||||
)),
|
||||
tracing,
|
||||
};
|
||||
|
||||
let _: InitializeResponse = harness
|
||||
.request(
|
||||
ClientRequest::Initialize {
|
||||
request_id: RequestId::Integer(1),
|
||||
params: InitializeParams {
|
||||
client_info: ClientInfo {
|
||||
name: "codex-app-server-tests".to_string(),
|
||||
title: None,
|
||||
version: "0.1.0".to_string(),
|
||||
},
|
||||
capabilities: Some(InitializeCapabilities {
|
||||
experimental_api: true,
|
||||
..Default::default()
|
||||
}),
|
||||
},
|
||||
},
|
||||
/*trace*/ None,
|
||||
)
|
||||
.await;
|
||||
assert!(harness.session.initialized());
|
||||
|
||||
Ok(harness)
|
||||
}
|
||||
|
||||
fn reset_tracing(&self) {
|
||||
self.tracing.exporter.reset();
|
||||
}
|
||||
|
||||
async fn shutdown(self) {
|
||||
self.processor.shutdown_threads().await;
|
||||
self.processor.drain_background_tasks().await;
|
||||
}
|
||||
|
||||
async fn request<T>(&mut self, request: ClientRequest, trace: Option<W3cTraceContext>) -> T
|
||||
where
|
||||
T: serde::de::DeserializeOwned,
|
||||
{
|
||||
let request_id = match request.id() {
|
||||
RequestId::Integer(request_id) => *request_id,
|
||||
request_id => panic!("expected integer request id in test harness, got {request_id:?}"),
|
||||
};
|
||||
let mut request = request_from_client_request(request);
|
||||
request.trace = trace;
|
||||
|
||||
self.processor
|
||||
.process_request(
|
||||
TEST_CONNECTION_ID,
|
||||
request,
|
||||
&AppServerTransport::Stdio,
|
||||
Arc::clone(&self.session),
|
||||
)
|
||||
.await;
|
||||
read_response(&mut self.outgoing_rx, request_id).await
|
||||
}
|
||||
|
||||
async fn start_thread(
|
||||
&mut self,
|
||||
request_id: i64,
|
||||
trace: Option<W3cTraceContext>,
|
||||
) -> ThreadStartResponse {
|
||||
let response = self
|
||||
.request(
|
||||
ClientRequest::ThreadStart {
|
||||
request_id: RequestId::Integer(request_id),
|
||||
params: ThreadStartParams {
|
||||
ephemeral: Some(true),
|
||||
..ThreadStartParams::default()
|
||||
},
|
||||
},
|
||||
trace,
|
||||
)
|
||||
.await;
|
||||
read_thread_started_notification(&mut self.outgoing_rx).await;
|
||||
response
|
||||
}
|
||||
}
|
||||
|
||||
async fn build_test_config(codex_home: &Path, server_uri: &str) -> Result<Config> {
|
||||
write_mock_responses_config_toml(
|
||||
codex_home,
|
||||
server_uri,
|
||||
&BTreeMap::new(),
|
||||
/*auto_compact_limit*/ 8_192,
|
||||
Some(false),
|
||||
"mock_provider",
|
||||
"compact",
|
||||
)?;
|
||||
|
||||
Ok(ConfigBuilder::default()
|
||||
.codex_home(codex_home.to_path_buf())
|
||||
.build()
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub(super) async fn build_test_processor(
|
||||
config: Arc<Config>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
) -> (
|
||||
Arc<MessageProcessor>,
|
||||
mpsc::Receiver<crate::outgoing_message::OutgoingEnvelope>,
|
||||
) {
|
||||
let (outgoing_tx, outgoing_rx) = mpsc::channel(16);
|
||||
let config_manager = ConfigManager::new(
|
||||
config.codex_home.to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::with_managed_config_path_for_tests(
|
||||
config.codex_home.join("managed_config.toml").to_path_buf(),
|
||||
),
|
||||
/*strict_config*/ false,
|
||||
CloudConfigBundleLoader::default(),
|
||||
Arg0DispatchPaths::default(),
|
||||
Arc::new(codex_config::NoopThreadConfigLoader),
|
||||
);
|
||||
let analytics_events_client = analytics_events_client_from_config(
|
||||
Arc::clone(&auth_manager),
|
||||
config.as_ref(),
|
||||
/*runtime_auth_slot*/ None,
|
||||
);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
outgoing_tx,
|
||||
analytics_events_client.clone(),
|
||||
));
|
||||
let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs {
|
||||
cloud_skill_provider: None,
|
||||
outgoing,
|
||||
analytics_events_client,
|
||||
arg0_paths: Arg0DispatchPaths::default(),
|
||||
startup_cwd: Some(config.cwd.to_path_buf()),
|
||||
config,
|
||||
config_manager,
|
||||
environment_manager: Arc::new(EnvironmentManager::default_for_tests()),
|
||||
feedback: CodexFeedback::new(),
|
||||
log_db: None,
|
||||
state_db: None,
|
||||
config_warnings: Vec::new(),
|
||||
startup_warnings_tx: mpsc::unbounded_channel().0,
|
||||
session_source: SessionSource::VSCode,
|
||||
user_verification: Arc::new(crate::user_verification::Service::new(Arc::clone(
|
||||
&auth_manager,
|
||||
))),
|
||||
auth_manager,
|
||||
runtime_auth_slot: None,
|
||||
installation_id: "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
code_mode_session_provider: None,
|
||||
rpc_transport: AppServerRpcTransport::Stdio,
|
||||
remote_control_handle: None,
|
||||
plugin_startup_tasks: Some(PluginStartupConfig::Current),
|
||||
}));
|
||||
(processor, outgoing_rx)
|
||||
}
|
||||
|
||||
fn run_current_thread_test_with_stack<F>(name: &str, future: F) -> Result<()>
|
||||
where
|
||||
F: Future<Output = Result<()>> + Send + 'static,
|
||||
{
|
||||
const TEST_STACK_SIZE_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
let handle = std::thread::Builder::new()
|
||||
.name(name.to_string())
|
||||
.stack_size(TEST_STACK_SIZE_BYTES)
|
||||
.spawn(move || -> Result<()> {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
runtime.block_on(Box::pin(future))
|
||||
})?;
|
||||
|
||||
match handle.join() {
|
||||
Ok(result) => result,
|
||||
Err(_) => Err(anyhow::anyhow!("{name} thread panicked")),
|
||||
}
|
||||
}
|
||||
|
||||
fn span_attr<'a>(span: &'a SpanData, key: &str) -> Option<&'a str> {
|
||||
span.attributes
|
||||
.iter()
|
||||
.find(|kv| kv.key.as_str() == key)
|
||||
.and_then(|kv| match &kv.value {
|
||||
opentelemetry::Value::String(value) => Some(value.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn find_rpc_span_with_trace<'a>(
|
||||
spans: &'a [SpanData],
|
||||
kind: SpanKind,
|
||||
method: &str,
|
||||
trace_id: TraceId,
|
||||
) -> &'a SpanData {
|
||||
spans
|
||||
.iter()
|
||||
.find(|span| {
|
||||
span.span_kind == kind
|
||||
&& span_attr(span, "rpc.system") == Some("jsonrpc")
|
||||
&& span_attr(span, "rpc.method") == Some(method)
|
||||
&& span.span_context.trace_id() == trace_id
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
panic!(
|
||||
"missing {kind:?} span for rpc.method={method} trace={trace_id}; exported spans:\n{}",
|
||||
format_spans(spans)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn find_span_with_trace<'a, F>(
|
||||
spans: &'a [SpanData],
|
||||
trace_id: TraceId,
|
||||
description: &str,
|
||||
predicate: F,
|
||||
) -> &'a SpanData
|
||||
where
|
||||
F: Fn(&SpanData) -> bool,
|
||||
{
|
||||
spans
|
||||
.iter()
|
||||
.find(|span| span.span_context.trace_id() == trace_id && predicate(span))
|
||||
.unwrap_or_else(|| {
|
||||
panic!(
|
||||
"missing span matching {description} for trace={trace_id}; exported spans:\n{}",
|
||||
format_spans(spans)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn format_spans(spans: &[SpanData]) -> String {
|
||||
spans
|
||||
.iter()
|
||||
.map(|span| {
|
||||
let rpc_method = span_attr(span, "rpc.method").unwrap_or("-");
|
||||
format!(
|
||||
"name={} span_id={} kind={:?} parent={} trace={} rpc.method={}",
|
||||
span.name,
|
||||
span.span_context.span_id(),
|
||||
span.span_kind,
|
||||
span.parent_span_id,
|
||||
span.span_context.trace_id(),
|
||||
rpc_method
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn span_depth_from_ancestor(
|
||||
spans: &[SpanData],
|
||||
child: &SpanData,
|
||||
ancestor: &SpanData,
|
||||
) -> Option<usize> {
|
||||
let ancestor_span_id = ancestor.span_context.span_id();
|
||||
let mut parent_span_id = child.parent_span_id;
|
||||
let mut depth = 1;
|
||||
while parent_span_id != SpanId::INVALID {
|
||||
if parent_span_id == ancestor_span_id {
|
||||
return Some(depth);
|
||||
}
|
||||
let Some(parent_span) = spans
|
||||
.iter()
|
||||
.find(|span| span.span_context.span_id() == parent_span_id)
|
||||
else {
|
||||
break;
|
||||
};
|
||||
parent_span_id = parent_span.parent_span_id;
|
||||
depth += 1;
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn assert_span_descends_from(spans: &[SpanData], child: &SpanData, ancestor: &SpanData) {
|
||||
if span_depth_from_ancestor(spans, child, ancestor).is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
panic!(
|
||||
"span {} does not descend from {}; exported spans:\n{}",
|
||||
child.name,
|
||||
ancestor.name,
|
||||
format_spans(spans)
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_has_internal_descendant_at_min_depth(
|
||||
spans: &[SpanData],
|
||||
ancestor: &SpanData,
|
||||
min_depth: usize,
|
||||
) {
|
||||
if spans.iter().any(|span| {
|
||||
span.span_kind == SpanKind::Internal
|
||||
&& span.span_context.trace_id() == ancestor.span_context.trace_id()
|
||||
&& span_depth_from_ancestor(spans, span, ancestor)
|
||||
.is_some_and(|depth| depth >= min_depth)
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
|
||||
panic!(
|
||||
"missing internal descendant at depth >= {min_depth} below {}; exported spans:\n{}",
|
||||
ancestor.name,
|
||||
format_spans(spans)
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) async fn read_response<T: serde::de::DeserializeOwned>(
|
||||
outgoing_rx: &mut mpsc::Receiver<crate::outgoing_message::OutgoingEnvelope>,
|
||||
request_id: i64,
|
||||
) -> T {
|
||||
read_response_from(outgoing_rx, TEST_CONNECTION_ID, request_id).await
|
||||
}
|
||||
|
||||
pub(super) async fn read_response_from<T: serde::de::DeserializeOwned>(
|
||||
outgoing_rx: &mut mpsc::Receiver<crate::outgoing_message::OutgoingEnvelope>,
|
||||
expected_connection_id: ConnectionId,
|
||||
request_id: i64,
|
||||
) -> T {
|
||||
loop {
|
||||
let envelope = tokio::time::timeout(Duration::from_secs(/*secs*/ 30), outgoing_rx.recv())
|
||||
.await
|
||||
.expect("timed out waiting for response")
|
||||
.expect("outgoing channel closed");
|
||||
let crate::outgoing_message::OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message,
|
||||
..
|
||||
} = envelope
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if connection_id != expected_connection_id {
|
||||
continue;
|
||||
}
|
||||
let crate::outgoing_message::OutgoingMessage::Response(response) = message else {
|
||||
continue;
|
||||
};
|
||||
if response.id != RequestId::Integer(request_id) {
|
||||
continue;
|
||||
}
|
||||
return serde_json::from_value(
|
||||
serde_json::to_value(response.result).expect("response payload should serialize"),
|
||||
)
|
||||
.expect("response payload should deserialize");
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_thread_started_notification(
|
||||
outgoing_rx: &mut mpsc::Receiver<crate::outgoing_message::OutgoingEnvelope>,
|
||||
) {
|
||||
loop {
|
||||
let envelope = tokio::time::timeout(std::time::Duration::from_secs(5), outgoing_rx.recv())
|
||||
.await
|
||||
.expect("timed out waiting for thread/started notification")
|
||||
.expect("outgoing channel closed");
|
||||
match envelope {
|
||||
crate::outgoing_message::OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message,
|
||||
..
|
||||
} => {
|
||||
if connection_id != TEST_CONNECTION_ID {
|
||||
continue;
|
||||
}
|
||||
let crate::outgoing_message::OutgoingMessage::AppServerNotification(notification) =
|
||||
message
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if matches!(
|
||||
notification.notification,
|
||||
codex_app_server_protocol::ServerNotification::ThreadStarted(_)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
crate::outgoing_message::OutgoingEnvelope::Broadcast { message } => {
|
||||
let crate::outgoing_message::OutgoingMessage::AppServerNotification(notification) =
|
||||
message
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if matches!(
|
||||
notification.notification,
|
||||
codex_app_server_protocol::ServerNotification::ThreadStarted(_)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_exported_spans<F>(tracing: &TestTracing, predicate: F) -> Vec<SpanData>
|
||||
where
|
||||
F: Fn(&[SpanData]) -> bool,
|
||||
{
|
||||
let mut last_spans = Vec::new();
|
||||
for _ in 0..200 {
|
||||
tokio::task::yield_now().await;
|
||||
tracing
|
||||
.provider
|
||||
.force_flush()
|
||||
.expect("force flush should succeed");
|
||||
let spans = tracing.exporter.get_finished_spans().expect("span export");
|
||||
last_spans = spans.clone();
|
||||
if predicate(&spans) {
|
||||
return spans;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
|
||||
panic!(
|
||||
"timed out waiting for expected exported spans:\n{}",
|
||||
format_spans(&last_spans)
|
||||
);
|
||||
}
|
||||
|
||||
async fn wait_for_new_exported_spans<F>(
|
||||
tracing: &TestTracing,
|
||||
baseline_len: usize,
|
||||
predicate: F,
|
||||
) -> Vec<SpanData>
|
||||
where
|
||||
F: Fn(&[SpanData]) -> bool,
|
||||
{
|
||||
let spans = wait_for_exported_spans(tracing, |spans| {
|
||||
spans.len() > baseline_len && predicate(&spans[baseline_len..])
|
||||
})
|
||||
.await;
|
||||
spans.into_iter().skip(baseline_len).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial(app_server_tracing)]
|
||||
fn thread_start_jsonrpc_span_exports_server_span_and_parents_children() -> Result<()> {
|
||||
run_current_thread_test_with_stack(
|
||||
"thread_start_jsonrpc_span_exports_server_span_and_parents_children",
|
||||
async {
|
||||
let mut harness = TracingHarness::new().await?;
|
||||
|
||||
let RemoteTrace {
|
||||
trace_id: remote_trace_id,
|
||||
parent_span_id: remote_parent_span_id,
|
||||
context: remote_trace,
|
||||
..
|
||||
} = RemoteTrace::new("00000000000000000000000000000011", "0000000000000022");
|
||||
|
||||
let _: ThreadStartResponse = harness
|
||||
.start_thread(/*request_id*/ 20_002, /*trace*/ None)
|
||||
.await;
|
||||
let untraced_spans = wait_for_exported_spans(harness.tracing, |spans| {
|
||||
spans.iter().any(|span| {
|
||||
span.span_kind == SpanKind::Server
|
||||
&& span_attr(span, "rpc.method") == Some("thread/start")
|
||||
})
|
||||
})
|
||||
.await;
|
||||
let untraced_server_span = find_rpc_span_with_trace(
|
||||
&untraced_spans,
|
||||
SpanKind::Server,
|
||||
"thread/start",
|
||||
untraced_spans
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|span| {
|
||||
span.span_kind == SpanKind::Server
|
||||
&& span_attr(span, "rpc.system") == Some("jsonrpc")
|
||||
&& span_attr(span, "rpc.method") == Some("thread/start")
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
panic!(
|
||||
"missing latest thread/start server span; exported spans:\n{}",
|
||||
format_spans(&untraced_spans)
|
||||
)
|
||||
})
|
||||
.span_context
|
||||
.trace_id(),
|
||||
);
|
||||
assert_has_internal_descendant_at_min_depth(
|
||||
&untraced_spans,
|
||||
untraced_server_span,
|
||||
/*min_depth*/ 1,
|
||||
);
|
||||
|
||||
let baseline_len = untraced_spans.len();
|
||||
let _: ThreadStartResponse = harness
|
||||
.start_thread(/*request_id*/ 20_003, Some(remote_trace))
|
||||
.await;
|
||||
let spans = wait_for_new_exported_spans(harness.tracing, baseline_len, |spans| {
|
||||
spans.iter().any(|span| {
|
||||
span.span_kind == SpanKind::Server
|
||||
&& span_attr(span, "rpc.method") == Some("thread/start")
|
||||
&& span.span_context.trace_id() == remote_trace_id
|
||||
}) && spans.iter().any(|span| {
|
||||
span.name.as_ref() == "app_server.thread_start.notify_started"
|
||||
&& span.span_context.trace_id() == remote_trace_id
|
||||
})
|
||||
})
|
||||
.await;
|
||||
|
||||
let server_request_span =
|
||||
find_rpc_span_with_trace(&spans, SpanKind::Server, "thread/start", remote_trace_id);
|
||||
assert_eq!(server_request_span.name.as_ref(), "thread/start");
|
||||
assert_eq!(server_request_span.parent_span_id, remote_parent_span_id);
|
||||
assert!(server_request_span.parent_span_is_remote);
|
||||
assert_eq!(server_request_span.span_context.trace_id(), remote_trace_id);
|
||||
assert_ne!(server_request_span.span_context.span_id(), SpanId::INVALID);
|
||||
assert_has_internal_descendant_at_min_depth(
|
||||
&spans,
|
||||
server_request_span,
|
||||
/*min_depth*/ 1,
|
||||
);
|
||||
assert_has_internal_descendant_at_min_depth(
|
||||
&spans,
|
||||
server_request_span,
|
||||
/*min_depth*/ 2,
|
||||
);
|
||||
harness.shutdown().await;
|
||||
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
#[serial(app_server_tracing)]
|
||||
async fn turn_start_jsonrpc_span_parents_core_turn_spans() -> Result<()> {
|
||||
let mut harness = TracingHarness::new().await?;
|
||||
let thread_start_response = harness.start_thread(/*request_id*/ 2, /*trace*/ None).await;
|
||||
let thread_id = thread_start_response.thread.id.clone();
|
||||
|
||||
harness.reset_tracing();
|
||||
|
||||
let RemoteTrace {
|
||||
trace_id: remote_trace_id,
|
||||
parent_span_id: remote_parent_span_id,
|
||||
context: remote_trace,
|
||||
} = RemoteTrace::new("00000000000000000000000000000077", "0000000000000088");
|
||||
let turn_start_response: TurnStartResponse = harness
|
||||
.request(
|
||||
ClientRequest::TurnStart {
|
||||
request_id: RequestId::Integer(3),
|
||||
params: TurnStartParams {
|
||||
disabled_plugin_ids: None,
|
||||
environments: None,
|
||||
thread_id,
|
||||
client_user_message_id: None,
|
||||
input: vec![UserInput::Text {
|
||||
text: "hello".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
turn_trigger: None,
|
||||
parent_turn_id: None,
|
||||
root_turn_id: None,
|
||||
tool_output: None,
|
||||
responsesapi_client_metadata: None,
|
||||
responsesapi_client_metadata_patch: None,
|
||||
additional_context: None,
|
||||
cwd: None,
|
||||
runtime_workspace_roots: None,
|
||||
approval_policy: None,
|
||||
sandbox_policy: None,
|
||||
permissions: None,
|
||||
approvals_reviewer: None,
|
||||
model: None,
|
||||
service_tier: None,
|
||||
service_tier_for_turn: None,
|
||||
effort: None,
|
||||
summary: None,
|
||||
personality: None,
|
||||
output_schema: None,
|
||||
collaboration_mode: None,
|
||||
multi_agent_mode: None,
|
||||
cyber_access_program: None,
|
||||
},
|
||||
},
|
||||
Some(remote_trace),
|
||||
)
|
||||
.await;
|
||||
let spans = wait_for_exported_spans(harness.tracing, |spans| {
|
||||
spans.iter().any(|span| {
|
||||
span.span_kind == SpanKind::Server
|
||||
&& span_attr(span, "rpc.method") == Some("turn/start")
|
||||
&& span.span_context.trace_id() == remote_trace_id
|
||||
}) && spans.iter().any(|span| {
|
||||
span_attr(span, "codex.op") == Some("turn_input")
|
||||
&& span.span_context.trace_id() == remote_trace_id
|
||||
})
|
||||
})
|
||||
.await;
|
||||
|
||||
let server_request_span =
|
||||
find_rpc_span_with_trace(&spans, SpanKind::Server, "turn/start", remote_trace_id);
|
||||
let core_turn_span =
|
||||
find_span_with_trace(&spans, remote_trace_id, "codex.op=turn_input", |span| {
|
||||
span_attr(span, "codex.op") == Some("turn_input")
|
||||
});
|
||||
|
||||
assert_eq!(server_request_span.parent_span_id, remote_parent_span_id);
|
||||
assert!(server_request_span.parent_span_is_remote);
|
||||
assert_eq!(server_request_span.span_context.trace_id(), remote_trace_id);
|
||||
assert_eq!(
|
||||
span_attr(server_request_span, "turn.id"),
|
||||
Some(turn_start_response.turn.id.as_str())
|
||||
);
|
||||
assert_span_descends_from(&spans, core_turn_span, server_request_span);
|
||||
harness.shutdown().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Exercises background routing call sites and explicit account reads through JSON-RPC.
|
||||
|
||||
use super::message_processor_tracing_tests::TEST_CONNECTION_ID;
|
||||
use super::message_processor_tracing_tests::read_response;
|
||||
use super::*;
|
||||
use codex_app_server_protocol::GetAccountResponse;
|
||||
use codex_app_server_protocol::InitializeResponse;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use test_case::test_case;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
#[test_case(None; "signed_out")]
|
||||
#[test_case(Some("dummy"); "api_key")]
|
||||
#[tokio::test]
|
||||
async fn background_routing_call_sites_skip_config(api_key: Option<&str>) -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
if let Some(api_key) = api_key {
|
||||
codex_login::login_with_api_key(
|
||||
home.path(),
|
||||
api_key,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)?;
|
||||
}
|
||||
let config = Arc::new(
|
||||
codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
|
||||
.build()
|
||||
.await?,
|
||||
);
|
||||
let auth_manager = Arc::new(
|
||||
AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
Some(config.chatgpt_base_url.clone()),
|
||||
AuthKeyringBackendKind::default(),
|
||||
config.auth_config().auth_route_config,
|
||||
)
|
||||
.await,
|
||||
);
|
||||
let (loads_tx, mut loads_rx) = mpsc::unbounded_channel();
|
||||
let loader = CloudConfigBundleLoader::from_getter(move || {
|
||||
loads_tx.send(()).expect("config-load observer is alive");
|
||||
async { Ok(None) }
|
||||
});
|
||||
let config_manager = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
loader,
|
||||
);
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*buffer*/ 16);
|
||||
let analytics_events_client = AnalyticsEventsClient::disabled();
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
outgoing_tx,
|
||||
analytics_events_client.clone(),
|
||||
));
|
||||
let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs {
|
||||
cloud_skill_provider: None,
|
||||
outgoing,
|
||||
analytics_events_client,
|
||||
arg0_paths: Arg0DispatchPaths::default(),
|
||||
startup_cwd: Some(config.cwd.to_path_buf()),
|
||||
config,
|
||||
config_manager,
|
||||
environment_manager: Arc::new(EnvironmentManager::default_for_tests()),
|
||||
feedback: CodexFeedback::new(),
|
||||
log_db: None,
|
||||
state_db: None,
|
||||
config_warnings: Vec::new(),
|
||||
startup_warnings_tx: mpsc::unbounded_channel().0,
|
||||
session_source: SessionSource::VSCode,
|
||||
user_verification: Arc::new(crate::user_verification::Service::new(Arc::clone(
|
||||
&auth_manager,
|
||||
))),
|
||||
auth_manager,
|
||||
runtime_auth_slot: None,
|
||||
installation_id: "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
code_mode_session_provider: None,
|
||||
rpc_transport: AppServerRpcTransport::Stdio,
|
||||
remote_control_handle: None,
|
||||
// Isolate routing from unrelated plugin startup configuration loads.
|
||||
plugin_startup_tasks: None,
|
||||
}));
|
||||
// The model catalog has its own legitimate config refresh, outside routing.
|
||||
processor.models_refresh_worker.shutdown();
|
||||
|
||||
// Observe the task scheduled by real processor construction, not the helper.
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 1), loads_rx.recv())
|
||||
.await
|
||||
.is_err(),
|
||||
"startup routing entered configuration loading"
|
||||
);
|
||||
let session = Arc::new(ConnectionSessionState::new(
|
||||
crate::transport::ConnectionOrigin::Stdio,
|
||||
));
|
||||
processor
|
||||
.process_request(
|
||||
TEST_CONNECTION_ID,
|
||||
serde_json::from_value(json!({
|
||||
"id": 1, "method": "initialize", "params": {
|
||||
"clientInfo": {"name": "workspace-routing-test", "version": "1"}
|
||||
}
|
||||
}))?,
|
||||
&crate::transport::AppServerTransport::Stdio,
|
||||
Arc::clone(&session),
|
||||
)
|
||||
.await;
|
||||
let _: InitializeResponse = read_response(&mut outgoing_rx, /*request_id*/ 1).await;
|
||||
// Complete the same post-initialize hook used by the real transports.
|
||||
processor
|
||||
.connection_initialized(TEST_CONNECTION_ID, /*request_attestation*/ false)
|
||||
.await;
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 1), loads_rx.recv())
|
||||
.await
|
||||
.is_err(),
|
||||
"connection initialization routing entered configuration loading"
|
||||
);
|
||||
|
||||
processor
|
||||
.process_request(
|
||||
TEST_CONNECTION_ID,
|
||||
serde_json::from_value(json!({
|
||||
"id": 2, "method": "account/read", "params": {"refreshToken": false}
|
||||
}))?,
|
||||
&crate::transport::AppServerTransport::Stdio,
|
||||
session,
|
||||
)
|
||||
.await;
|
||||
let response: GetAccountResponse = read_response(&mut outgoing_rx, /*request_id*/ 2).await;
|
||||
assert_eq!(
|
||||
response,
|
||||
GetAccountResponse {
|
||||
user_id: None,
|
||||
account: api_key.map(|_| codex_app_server_protocol::Account::ApiKey {}),
|
||||
requires_openai_auth: true,
|
||||
workspace_routing: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
loads_rx.try_recv(),
|
||||
Ok(()),
|
||||
"explicit account/read must reload config"
|
||||
);
|
||||
processor.shutdown_threads().await;
|
||||
Ok(())
|
||||
}
|
||||
151
codex-rs/app-server/src/model_catalog.rs
Normal file
151
codex-rs/app-server/src/model_catalog.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
//! Loads the model catalog for the current effective provider configuration.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_features::Feature;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use codex_protocol::openai_models::ModelPreset;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::config_manager::StartupConfig;
|
||||
|
||||
/// Refreshes catalog routing without changing the routes retained by existing threads.
|
||||
pub(crate) struct ModelCatalog {
|
||||
config_manager: ConfigManager,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
startup_cwd: Option<PathBuf>,
|
||||
state: Mutex<CatalogState>,
|
||||
}
|
||||
|
||||
struct CatalogState {
|
||||
needs_reload: bool,
|
||||
config: Arc<Config>,
|
||||
models_manager: SharedModelsManager,
|
||||
}
|
||||
|
||||
impl ModelCatalog {
|
||||
pub(crate) fn new(
|
||||
config_manager: ConfigManager,
|
||||
startup_cwd: Option<PathBuf>,
|
||||
config: Arc<Config>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
) -> Self {
|
||||
let models_manager = thread_manager.get_models_manager();
|
||||
Self {
|
||||
config_manager,
|
||||
thread_manager,
|
||||
startup_cwd,
|
||||
state: Mutex::new(CatalogState {
|
||||
needs_reload: false,
|
||||
config,
|
||||
models_manager,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the same startup context used to reload the catalog after account setup.
|
||||
pub(crate) async fn load_startup_config_layers(&self) -> std::io::Result<ConfigLayerStack> {
|
||||
let cwd = self
|
||||
.startup_cwd
|
||||
.as_deref()
|
||||
.map(AbsolutePathBuf::from_absolute_path)
|
||||
.transpose()?;
|
||||
self.config_manager.load_config_layers(cwd).await
|
||||
}
|
||||
|
||||
/// Marks catalog configuration stale after an account transition.
|
||||
pub(crate) async fn invalidate(&self) {
|
||||
self.state.lock().await.needs_reload = true;
|
||||
}
|
||||
|
||||
pub(crate) async fn invalidate_if_current_provider(&self, provider_id: &str) {
|
||||
let mut state = self.state.lock().await;
|
||||
if state.config.model_provider_id == provider_id {
|
||||
state.needs_reload = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "catalog reloads are serialized with account invalidation; model fetching holds no lock"
|
||||
)]
|
||||
pub(crate) async fn current(&self) -> std::io::Result<(Arc<Config>, SharedModelsManager)> {
|
||||
let mut state = self.state.lock().await;
|
||||
if state.needs_reload {
|
||||
// Keep the large config-loading future off callers' stacks.
|
||||
let config = Box::pin(
|
||||
self.config_manager
|
||||
.load_startup_config(self.startup_cwd.clone()),
|
||||
)
|
||||
.await?;
|
||||
let StartupConfig {
|
||||
config,
|
||||
used_defaults,
|
||||
} = config;
|
||||
if config.model_provider_id != state.config.model_provider_id
|
||||
|| config.model_provider != state.config.model_provider
|
||||
|| config.model_catalog != state.config.model_catalog
|
||||
|| config.features.enabled(Feature::RuntimeAgentInstances)
|
||||
!= state
|
||||
.config
|
||||
.features
|
||||
.enabled(Feature::RuntimeAgentInstances)
|
||||
|| config.runtime_auth_mode != state.config.runtime_auth_mode
|
||||
{
|
||||
state.models_manager = self.thread_manager.models_manager_for_config(&config);
|
||||
}
|
||||
self.thread_manager.set_api_key_model_discovery_enabled(
|
||||
config.features.enabled(Feature::ApiKeyModelDiscovery),
|
||||
);
|
||||
state.config = Arc::new(config);
|
||||
// Try again on the next access so a temporary fallback cannot pin the provider.
|
||||
state.needs_reload = used_defaults;
|
||||
}
|
||||
Ok((Arc::clone(&state.config), Arc::clone(&state.models_manager)))
|
||||
}
|
||||
|
||||
pub(crate) async fn list_models(
|
||||
&self,
|
||||
refresh_strategy: RefreshStrategy,
|
||||
) -> std::io::Result<Vec<ModelPreset>> {
|
||||
let (config, models_manager) = self.current().await?;
|
||||
let models = self
|
||||
.list_models_from_snapshot(
|
||||
Arc::clone(&config),
|
||||
Arc::clone(&models_manager),
|
||||
refresh_strategy,
|
||||
)
|
||||
.await?;
|
||||
// The periodic worker also refreshes retained Work catalogs. Picker RPCs use
|
||||
// list_models_from_snapshot directly and do not wait on other originators.
|
||||
if refresh_strategy == RefreshStrategy::Online {
|
||||
models_manager
|
||||
.refresh_originator_catalogs(config.http_client_factory())
|
||||
.await;
|
||||
}
|
||||
Ok(models)
|
||||
}
|
||||
|
||||
pub(crate) async fn list_models_from_snapshot(
|
||||
&self,
|
||||
config: Arc<Config>,
|
||||
models_manager: SharedModelsManager,
|
||||
refresh_strategy: RefreshStrategy,
|
||||
) -> std::io::Result<Vec<ModelPreset>> {
|
||||
// Keep the existing policy check even for a warm catalog. A policy
|
||||
// edit alone must not make the retained provider silently permissible.
|
||||
self.config_manager
|
||||
.check_thread_model_provider(&config)
|
||||
.await?;
|
||||
Ok(models_manager
|
||||
.list_models(refresh_strategy, config.http_client_factory())
|
||||
.await)
|
||||
}
|
||||
}
|
||||
69
codex-rs/app-server/src/models.rs
Normal file
69
codex-rs/app-server/src/models.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use codex_app_server_protocol::Model;
|
||||
use codex_app_server_protocol::ModelServiceTier;
|
||||
use codex_app_server_protocol::ModelUpgradeInfo;
|
||||
use codex_app_server_protocol::ReasoningEffortOption;
|
||||
use codex_protocol::openai_models::ModelPreset;
|
||||
use codex_protocol::openai_models::ReasoningEffortPreset;
|
||||
|
||||
pub fn supported_models(models: Vec<ModelPreset>, include_hidden: bool) -> Vec<Model> {
|
||||
models
|
||||
.into_iter()
|
||||
.filter(|preset| include_hidden || preset.show_in_picker)
|
||||
.map(model_from_preset)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn model_from_preset(preset: ModelPreset) -> Model {
|
||||
Model {
|
||||
id: preset.id.to_string(),
|
||||
model: preset.model.to_string(),
|
||||
upgrade: preset.upgrade.as_ref().map(|upgrade| upgrade.id.clone()),
|
||||
upgrade_info: preset.upgrade.as_ref().map(|upgrade| ModelUpgradeInfo {
|
||||
model: upgrade.id.clone(),
|
||||
upgrade_copy: upgrade.upgrade_copy.clone(),
|
||||
model_link: upgrade.model_link.clone(),
|
||||
migration_markdown: upgrade.migration_markdown.clone(),
|
||||
retirement_at: upgrade
|
||||
.retirement_at
|
||||
.as_ref()
|
||||
.map(chrono::DateTime::timestamp),
|
||||
}),
|
||||
availability_nux: preset.availability_nux.map(Into::into),
|
||||
display_name: preset.display_name.to_string(),
|
||||
description: preset.description.to_string(),
|
||||
model_specialty: preset.model_specialty,
|
||||
hidden: !preset.show_in_picker,
|
||||
supported_reasoning_efforts: reasoning_efforts_from_preset(
|
||||
preset.supported_reasoning_efforts,
|
||||
),
|
||||
default_reasoning_effort: preset.default_reasoning_effort,
|
||||
input_modalities: preset.input_modalities,
|
||||
supports_personality: false,
|
||||
multi_agent_version: preset.multi_agent_version.map(Into::into),
|
||||
additional_speed_tiers: preset.additional_speed_tiers,
|
||||
service_tiers: preset
|
||||
.service_tiers
|
||||
.into_iter()
|
||||
.map(|service_tier| ModelServiceTier {
|
||||
id: service_tier.id,
|
||||
name: service_tier.name,
|
||||
description: service_tier.description,
|
||||
})
|
||||
.collect(),
|
||||
default_service_tier: preset.default_service_tier,
|
||||
available_access_programs: preset.available_access_programs.map(Into::into),
|
||||
is_default: preset.is_default,
|
||||
}
|
||||
}
|
||||
|
||||
fn reasoning_efforts_from_preset(
|
||||
efforts: Vec<ReasoningEffortPreset>,
|
||||
) -> Vec<ReasoningEffortOption> {
|
||||
efforts
|
||||
.into_iter()
|
||||
.map(|preset| ReasoningEffortOption {
|
||||
reasoning_effort: preset.effort,
|
||||
description: preset.description,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
69
codex-rs/app-server/src/models_refresh_worker.rs
Normal file
69
codex-rs/app-server/src/models_refresh_worker.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::model_catalog::ModelCatalog;
|
||||
|
||||
const MODELS_REFRESH_INTERVAL: Duration = Duration::from_secs(4 * 60 + 30);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ModelsRefreshWorker {
|
||||
shutdown: CancellationToken,
|
||||
_task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl ModelsRefreshWorker {
|
||||
pub(crate) fn shutdown(&self) {
|
||||
self.shutdown.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ModelsRefreshWorker {
|
||||
fn drop(&mut self) {
|
||||
self.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn spawn(model_catalog: &Arc<ModelCatalog>) -> ModelsRefreshWorker {
|
||||
spawn_with_interval(model_catalog, MODELS_REFRESH_INTERVAL)
|
||||
}
|
||||
|
||||
fn spawn_with_interval(
|
||||
model_catalog: &Arc<ModelCatalog>,
|
||||
refresh_interval: Duration,
|
||||
) -> ModelsRefreshWorker {
|
||||
let model_catalog = Arc::downgrade(model_catalog);
|
||||
let shutdown = CancellationToken::new();
|
||||
let worker_shutdown = shutdown.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
loop {
|
||||
if worker_shutdown.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
let Some(model_catalog) = model_catalog.upgrade() else {
|
||||
break;
|
||||
};
|
||||
if let Err(err) = model_catalog.list_models(RefreshStrategy::Online).await {
|
||||
// Parser diagnostics can include provider credentials from the source TOML.
|
||||
tracing::warn!(error_kind = ?err.kind(), "model catalog refresh blocked by provider requirements");
|
||||
}
|
||||
drop(model_catalog);
|
||||
|
||||
tokio::select! {
|
||||
_ = worker_shutdown.cancelled() => break,
|
||||
_ = tokio::time::sleep(refresh_interval) => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
ModelsRefreshWorker {
|
||||
shutdown,
|
||||
_task: task,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "models_refresh_worker_tests.rs"]
|
||||
mod tests;
|
||||
433
codex-rs/app-server/src/models_refresh_worker_tests.rs
Normal file
433
codex-rs/app-server/src/models_refresh_worker_tests.rs
Normal file
@@ -0,0 +1,433 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_config::CloudConfigBundle;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_feedback::CodexFeedback;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_models_manager::manager::ModelCatalogSettings;
|
||||
use codex_models_manager::manager::ModelsEndpointClient;
|
||||
use codex_models_manager::manager::ModelsEndpointFuture;
|
||||
use codex_models_manager::manager::ModelsEndpointResponse;
|
||||
use codex_models_manager::manager::OpenAiModelsManager;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CoreResult;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn test_thread_manager(
|
||||
config: &codex_core::config::Config,
|
||||
models_manager: Option<SharedModelsManager>,
|
||||
auth_manager: Arc<codex_login::AuthManager>,
|
||||
) -> Arc<codex_core::ThreadManager> {
|
||||
let factory = match models_manager {
|
||||
Some(models) => codex_core::test_support::fixed_model_catalog(models),
|
||||
None => Arc::new(ModelCatalogSettings::disk(config.codex_home.to_path_buf())),
|
||||
};
|
||||
let startup = codex_core::build_startup_models(
|
||||
config,
|
||||
auth_manager,
|
||||
uuid::Uuid::new_v4().to_string(),
|
||||
factory,
|
||||
);
|
||||
Arc::new(codex_core::ThreadManager::new(
|
||||
config,
|
||||
startup,
|
||||
codex_core::CodexAppsToolsCache::default(),
|
||||
codex_protocol::protocol::SessionSource::Exec,
|
||||
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
|
||||
codex_extension_api::empty_extension_registry(),
|
||||
Arc::new(codex_core::test_support::EmptyUserInstructionsProvider),
|
||||
/*analytics_events_client*/ None,
|
||||
codex_core::passthrough_image_store(),
|
||||
codex_core::ThreadStoreBuilder::from_config(config, /*state_db*/ None).build(),
|
||||
/*agent_graph_store*/ None,
|
||||
/*attestation_provider*/ None,
|
||||
/*external_time_provider*/ None,
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TestModelsEndpoint {
|
||||
fetch_count: AtomicUsize,
|
||||
fetched: Notify,
|
||||
release_second_fetch: Notify,
|
||||
originator_endpoint: Option<Arc<TestModelsEndpoint>>,
|
||||
}
|
||||
|
||||
impl TestModelsEndpoint {
|
||||
fn new() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
fetch_count: AtomicUsize::new(0),
|
||||
fetched: Notify::new(),
|
||||
release_second_fetch: Notify::new(),
|
||||
originator_endpoint: None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn wait_for_fetch_count(&self, expected: usize) {
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while self.fetch_count.load(Ordering::SeqCst) < expected {
|
||||
self.fetched.notified().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("expected {expected} model fetches"));
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelsEndpointClient for TestModelsEndpoint {
|
||||
fn for_originator(
|
||||
&self,
|
||||
_originator: codex_models_manager::ModelCatalogOriginator,
|
||||
) -> Option<Arc<dyn ModelsEndpointClient>> {
|
||||
self.originator_endpoint
|
||||
.clone()
|
||||
.map(|endpoint| endpoint as Arc<dyn ModelsEndpointClient>)
|
||||
}
|
||||
|
||||
fn identity(&self) -> Option<String> {
|
||||
Some("test-provider".to_string())
|
||||
}
|
||||
|
||||
fn has_command_auth(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn uses_codex_backend(&self) -> ModelsEndpointFuture<'_, bool> {
|
||||
Box::pin(async { false })
|
||||
}
|
||||
|
||||
fn list_models<'a>(
|
||||
&'a self,
|
||||
_client_version: &'a str,
|
||||
_http_client_factory: HttpClientFactory,
|
||||
) -> ModelsEndpointFuture<'a, CoreResult<ModelsEndpointResponse>> {
|
||||
Box::pin(async move {
|
||||
let fetch_index = self.fetch_count.fetch_add(1, Ordering::SeqCst);
|
||||
self.fetched.notify_one();
|
||||
if fetch_index == 0 {
|
||||
return Err(CodexErr::Io(std::io::Error::other("test failure")));
|
||||
}
|
||||
if fetch_index == 1 {
|
||||
self.release_second_fetch.notified().await;
|
||||
}
|
||||
Ok(ModelsEndpointResponse {
|
||||
models: Vec::new(),
|
||||
etag: None,
|
||||
identity: self.identity().expect("test endpoint identity"),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refreshes_immediately_periodically_and_stops_when_dropped() {
|
||||
let codex_home = tempdir().expect("temp dir");
|
||||
let mut endpoint = TestModelsEndpoint::new();
|
||||
let work_endpoint = TestModelsEndpoint::new();
|
||||
work_endpoint.release_second_fetch.notify_one();
|
||||
Arc::get_mut(&mut endpoint).unwrap().originator_endpoint = Some(work_endpoint.clone());
|
||||
let requirements_path = codex_home.path().join("requirements.toml");
|
||||
std::fs::write(&requirements_path, "model_provider = 'ollama'").unwrap();
|
||||
let config_manager = crate::config_manager::ConfigManager::new_for_tests(
|
||||
codex_home.path().to_path_buf(),
|
||||
vec![("model_provider".to_string(), "ollama".into())],
|
||||
LoaderOverrides::with_managed_config_path_for_tests(
|
||||
codex_home.path().join("managed_config.toml"),
|
||||
),
|
||||
CloudConfigBundleLoader::default(),
|
||||
);
|
||||
// The TUI forwards its typed --oss selection through the raw CLI overrides too.
|
||||
let config = Arc::new(
|
||||
ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
model_provider: Some("ollama".to_string()),
|
||||
..Default::default()
|
||||
})
|
||||
.build()
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
let models_manager: SharedModelsManager = Arc::new(OpenAiModelsManager::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
endpoint.clone(),
|
||||
/*auth_manager*/ None,
|
||||
));
|
||||
let work_manager = models_manager.for_originator("codex_work_desktop").unwrap();
|
||||
let mut work_updates = work_manager.model_catalog_updates().unwrap();
|
||||
let auth_manager = codex_login::AuthManager::shared_from_config(
|
||||
config.as_ref(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("test auth manager");
|
||||
let catalog = Arc::new(ModelCatalog::new(
|
||||
config_manager,
|
||||
Some(config.cwd.to_path_buf()),
|
||||
Arc::clone(&config),
|
||||
test_thread_manager(&config, Some(Arc::clone(&models_manager)), auth_manager),
|
||||
));
|
||||
let worker = spawn_with_interval(&catalog, Duration::from_millis(/*millis*/ 10));
|
||||
|
||||
endpoint.wait_for_fetch_count(/*expected*/ 2).await;
|
||||
drop(worker);
|
||||
endpoint.release_second_fetch.notify_one();
|
||||
work_endpoint.wait_for_fetch_count(/*expected*/ 2).await;
|
||||
work_updates.changed().await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
|
||||
assert_eq!(endpoint.fetch_count.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(work_endpoint.fetch_count.load(Ordering::SeqCst), 2);
|
||||
|
||||
// Reloading after login preserves an embedded caller's typed --oss override.
|
||||
catalog.invalidate().await;
|
||||
assert_eq!(
|
||||
catalog.current().await.unwrap().0.model_provider_id,
|
||||
"ollama"
|
||||
);
|
||||
|
||||
assert!(Arc::ptr_eq(
|
||||
&catalog.current().await.unwrap().1,
|
||||
&models_manager
|
||||
));
|
||||
|
||||
// The catalog follows a new managed route without reusing the old endpoint.
|
||||
std::fs::write(&requirements_path, "model_provider = 'openai'").unwrap();
|
||||
catalog.invalidate().await;
|
||||
catalog.list_models(RefreshStrategy::Offline).await.unwrap();
|
||||
assert_eq!(
|
||||
catalog.current().await.unwrap().0.model_provider_id,
|
||||
"openai"
|
||||
);
|
||||
std::fs::remove_file(&requirements_path).unwrap();
|
||||
catalog.invalidate().await;
|
||||
assert_eq!(
|
||||
catalog.current().await.unwrap().0.model_provider_id,
|
||||
"ollama"
|
||||
);
|
||||
assert_eq!(endpoint.fetch_count.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn background_refresh_blocks_invalid_requirements_then_recovers() -> anyhow::Result<()> {
|
||||
let home = tempdir()?;
|
||||
let config = Arc::new(
|
||||
crate::config_manager::ConfigManager::without_managed_config_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
)
|
||||
.load_non_project_config()
|
||||
.await?,
|
||||
);
|
||||
let (checks_tx, mut checks_rx) = mpsc::unbounded_channel();
|
||||
let loader = CloudConfigBundleLoader::from_getter(move || {
|
||||
let (reply_tx, reply_rx) = oneshot::channel::<Option<CloudConfigBundle>>();
|
||||
checks_tx
|
||||
.send(reply_tx)
|
||||
.expect("requirements check receiver");
|
||||
async move { Ok(reply_rx.await.expect("requirements check response")) }
|
||||
});
|
||||
let config_manager = crate::config_manager::ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
loader,
|
||||
);
|
||||
let endpoint = TestModelsEndpoint::new();
|
||||
let models_manager: SharedModelsManager = Arc::new(OpenAiModelsManager::new(
|
||||
home.path().to_path_buf(),
|
||||
endpoint.clone(),
|
||||
/*auth_manager*/ None,
|
||||
));
|
||||
let auth_manager = codex_login::AuthManager::shared_from_config(
|
||||
config.as_ref(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("test auth manager");
|
||||
let catalog = Arc::new(ModelCatalog::new(
|
||||
config_manager,
|
||||
Some(config.cwd.to_path_buf()),
|
||||
Arc::clone(&config),
|
||||
test_thread_manager(&config, Some(models_manager), auth_manager),
|
||||
));
|
||||
let feedback = CodexFeedback::new();
|
||||
// This test uses Tokio's current-thread runtime, so spawned refreshes share the subscriber.
|
||||
let _subscriber_guard = tracing::subscriber::set_default(
|
||||
tracing_subscriber::registry().with(feedback.logger_layer()),
|
||||
);
|
||||
let worker = spawn_with_interval(&catalog, Duration::from_millis(/*millis*/ 10));
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
for expected in 1..=2 {
|
||||
checks_rx.recv().await.unwrap().send(/*t*/ None).unwrap();
|
||||
endpoint.wait_for_fetch_count(expected).await;
|
||||
}
|
||||
|
||||
// Let the in-flight request finish, then control each refresh's requirements.
|
||||
endpoint.release_second_fetch.notify_one();
|
||||
let mut next_check = checks_rx.recv().await.unwrap();
|
||||
for requirements in [
|
||||
"model_provider = 'other'",
|
||||
"model_provider = []",
|
||||
"[model_providers.gateway]\nexperimental_bearer_token = 'private-provider-token-marker' trailing",
|
||||
] {
|
||||
next_check
|
||||
.send(Some(
|
||||
CloudConfigBundleFixture::enterprise_requirement(requirements).into_bundle(),
|
||||
))
|
||||
.unwrap();
|
||||
// Reaching the next check proves the previous refresh completed. Keep
|
||||
// this check blocked while asserting that the previous one did not fetch.
|
||||
next_check = checks_rx.recv().await.unwrap();
|
||||
assert_eq!(endpoint.fetch_count.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
next_check.send(/*t*/ None).unwrap();
|
||||
endpoint.wait_for_fetch_count(/*expected*/ 3).await;
|
||||
})
|
||||
.await?;
|
||||
drop(worker);
|
||||
let logs = String::from_utf8(
|
||||
feedback
|
||||
.snapshot(/*session_id*/ None)
|
||||
.log_attachment(/*logs_override*/ None)
|
||||
.buffer,
|
||||
)?;
|
||||
assert!(logs.contains("model catalog refresh blocked by provider requirements"));
|
||||
assert!(logs.contains("error_kind=InvalidData"));
|
||||
assert!(!logs.contains("private-provider-token-marker"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A transient cloud failure must not pin the fallback catalog after policy recovers.
|
||||
#[tokio::test]
|
||||
async fn catalog_reload_recovers_after_cloud_failure() -> anyhow::Result<()> {
|
||||
let home = tempdir()?;
|
||||
let failed = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let loader_failed = Arc::clone(&failed);
|
||||
let loader = CloudConfigBundleLoader::from_getter(move || {
|
||||
let failed = Arc::clone(&loader_failed);
|
||||
async move {
|
||||
if failed.load(Ordering::SeqCst) {
|
||||
Err(codex_config::CloudConfigBundleLoadError::new(
|
||||
codex_config::CloudConfigBundleLoadErrorCode::RequestFailed,
|
||||
/*status_code*/ None,
|
||||
"test cloud timeout",
|
||||
))
|
||||
} else {
|
||||
Ok(Some(
|
||||
CloudConfigBundleFixture::enterprise_requirement("model_provider = 'ollama'")
|
||||
.into_bundle(),
|
||||
))
|
||||
}
|
||||
}
|
||||
});
|
||||
let manager = crate::config_manager::ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
loader,
|
||||
);
|
||||
let config = Arc::new(manager.load_non_project_config().await?);
|
||||
let auth = codex_login::AuthManager::shared_from_config(
|
||||
config.as_ref(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await?;
|
||||
let catalog = Arc::new(ModelCatalog::new(
|
||||
manager,
|
||||
/*startup_cwd*/ None,
|
||||
Arc::clone(&config),
|
||||
test_thread_manager(&config, /*models_manager*/ None, auth),
|
||||
));
|
||||
failed.store(true, Ordering::SeqCst);
|
||||
catalog.invalidate().await;
|
||||
assert_eq!(catalog.current().await?.0.model_provider_id, "openai");
|
||||
assert!(catalog.list_models(RefreshStrategy::Offline).await.is_err());
|
||||
failed.store(false, Ordering::SeqCst);
|
||||
// Exercise the same online request used by the periodic background worker.
|
||||
catalog.list_models(RefreshStrategy::Online).await?;
|
||||
assert_eq!(catalog.current().await?.0.model_provider_id, "ollama");
|
||||
assert!(
|
||||
!catalog
|
||||
.list_models(RefreshStrategy::Offline)
|
||||
.await?
|
||||
.is_empty()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Repairing a project config after fallback must restore that project's local model catalog.
|
||||
#[tokio::test]
|
||||
async fn catalog_reload_recovers_original_project_after_startup_fallback() -> anyhow::Result<()> {
|
||||
let home = tempdir()?;
|
||||
let project = tempdir()?;
|
||||
let project_path = AbsolutePathBuf::from_absolute_path(project.path())?
|
||||
.canonicalize()?
|
||||
.to_path_buf();
|
||||
std::fs::create_dir(project_path.join(".codex"))?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
toml::to_string(&serde_json::json!({
|
||||
"projects": {project_path.to_string_lossy(): {"trust_level": "trusted"}}
|
||||
}))?,
|
||||
)?;
|
||||
let project_config = project_path.join(".codex/config.toml");
|
||||
std::fs::write(&project_config, "model_catalog_json = [")?;
|
||||
let manager = crate::config_manager::ConfigManager::without_managed_config_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let startup = manager
|
||||
.load_startup_config(Some(project_path.clone()))
|
||||
.await?;
|
||||
assert!(startup.used_defaults);
|
||||
let config = Arc::new(startup.config);
|
||||
let auth = codex_login::AuthManager::shared_from_config(
|
||||
config.as_ref(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await?;
|
||||
let catalog = ModelCatalog::new(
|
||||
manager,
|
||||
Some(project_path.clone()),
|
||||
Arc::clone(&config),
|
||||
test_thread_manager(&config, /*models_manager*/ None, auth),
|
||||
);
|
||||
let mut model = codex_models_manager::bundled_models_response()?
|
||||
.models
|
||||
.remove(0);
|
||||
model.slug = "project-model".into();
|
||||
std::fs::write(
|
||||
project_path.join(".codex/catalog.json"),
|
||||
serde_json::to_vec(&serde_json::json!({"models": [model]}))?,
|
||||
)?;
|
||||
std::fs::write(&project_config, "model_catalog_json = 'catalog.json'")?;
|
||||
catalog.invalidate().await;
|
||||
let (config, _) = catalog.current().await?;
|
||||
assert_eq!(config.cwd.as_path(), project_path);
|
||||
let models = catalog.list_models(RefreshStrategy::Offline).await?;
|
||||
assert_eq!(
|
||||
models
|
||||
.iter()
|
||||
.map(|model| model.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["project-model"]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
225
codex-rs/app-server/src/notification_media.rs
Normal file
225
codex-rs/app-server/src/notification_media.rs
Normal file
@@ -0,0 +1,225 @@
|
||||
use codex_app_server_protocol::DynamicToolCallOutputContentItem;
|
||||
use codex_app_server_protocol::GeneratedImageRef;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadItemPayload;
|
||||
use codex_app_server_protocol::UserInput;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputBody;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
|
||||
pub(crate) fn without_notification_media(notification: ServerNotification) -> ServerNotification {
|
||||
match notification {
|
||||
ServerNotification::ItemStarted(mut notification) => {
|
||||
notification.item.payload = without_thread_item_media(notification.item.payload);
|
||||
ServerNotification::ItemStarted(notification)
|
||||
}
|
||||
ServerNotification::ItemCompleted(mut notification) => {
|
||||
notification.item.payload = without_thread_item_media(notification.item.payload);
|
||||
ServerNotification::ItemCompleted(notification)
|
||||
}
|
||||
ServerNotification::RawResponseItemCompleted(mut notification) => {
|
||||
match &mut notification.item {
|
||||
ResponseItem::Message { content, .. } => {
|
||||
content.retain(|item| match item {
|
||||
ContentItem::InputImage { .. } | ContentItem::InputAudio { .. } => false,
|
||||
ContentItem::InputText { .. } | ContentItem::OutputText { .. } => true,
|
||||
});
|
||||
}
|
||||
ResponseItem::FunctionCallOutput { output, .. }
|
||||
| ResponseItem::CustomToolCallOutput { output, .. } => {
|
||||
if let Some(items) = output.content_items_mut() {
|
||||
items.retain(|item| match item {
|
||||
FunctionCallOutputContentItem::InputImage { .. }
|
||||
| FunctionCallOutputContentItem::InputAudio { .. } => false,
|
||||
FunctionCallOutputContentItem::InputText { .. }
|
||||
| FunctionCallOutputContentItem::EncryptedContent { .. } => true,
|
||||
});
|
||||
}
|
||||
}
|
||||
ResponseItem::ImageGenerationCall { result, .. } => result.clear(),
|
||||
ResponseItem::AdditionalTools { .. }
|
||||
| ResponseItem::AgentMessage { .. }
|
||||
| ResponseItem::Reasoning { .. }
|
||||
| ResponseItem::LocalShellCall { .. }
|
||||
| ResponseItem::FunctionCall { .. }
|
||||
| ResponseItem::ToolSearchCall { .. }
|
||||
| ResponseItem::CustomToolCall { .. }
|
||||
| ResponseItem::ToolSearchOutput { .. }
|
||||
| ResponseItem::WebSearchCall { .. }
|
||||
| ResponseItem::Compaction { .. }
|
||||
| ResponseItem::ConfigurationUpdate { .. }
|
||||
| ResponseItem::CompactionTrigger { .. }
|
||||
| ResponseItem::ContextCompaction { .. }
|
||||
| ResponseItem::Other => {}
|
||||
}
|
||||
ServerNotification::RawResponseItemCompleted(notification)
|
||||
}
|
||||
ServerNotification::Error(_)
|
||||
| ServerNotification::ThreadStarted(_)
|
||||
| ServerNotification::ThreadStatusChanged(_)
|
||||
| ServerNotification::ThreadReadStateChanged(_)
|
||||
| ServerNotification::ThreadArchived(_)
|
||||
| ServerNotification::ThreadDeleted(_)
|
||||
| ServerNotification::ThreadUnarchived(_)
|
||||
| ServerNotification::ThreadClosed(_)
|
||||
| ServerNotification::ThreadReverted(_)
|
||||
| ServerNotification::SkillsChanged(_)
|
||||
| ServerNotification::ThreadNameUpdated(_)
|
||||
| ServerNotification::ThreadSectionChanged(_)
|
||||
| ServerNotification::ThreadAttachmentUpdated(_)
|
||||
| ServerNotification::ThreadGoalUpdated(_)
|
||||
| ServerNotification::ThreadPredictionUpdated(_)
|
||||
| ServerNotification::ThreadGoalCleared(_)
|
||||
| ServerNotification::ThreadQueueChanged(_)
|
||||
| ServerNotification::ProjectChanged(_)
|
||||
| ServerNotification::ThreadProjectUpdated(_)
|
||||
| ServerNotification::EnvironmentConnected(_)
|
||||
| ServerNotification::EnvironmentDisconnected(_)
|
||||
| ServerNotification::ThreadSettingsUpdated(_)
|
||||
| ServerNotification::ThreadTokenUsageUpdated(_)
|
||||
| ServerNotification::TurnStarted(_)
|
||||
| ServerNotification::HookStarted(_)
|
||||
| ServerNotification::TurnCompleted(_)
|
||||
| ServerNotification::HookCompleted(_)
|
||||
| ServerNotification::TurnDiffUpdated(_)
|
||||
| ServerNotification::TurnPlanUpdated(_)
|
||||
| ServerNotification::ItemGuardianApprovalReviewStarted(_)
|
||||
| ServerNotification::ItemGuardianApprovalReviewCompleted(_)
|
||||
| ServerNotification::StrictReviewRequired(_)
|
||||
| ServerNotification::RawResponseCompleted(_)
|
||||
| ServerNotification::AgentMessageDelta(_)
|
||||
| ServerNotification::PlanDelta(_)
|
||||
| ServerNotification::CommandExecOutputDelta(_)
|
||||
| ServerNotification::ProcessOutputDelta(_)
|
||||
| ServerNotification::ProcessExited(_)
|
||||
| ServerNotification::CommandExecutionOutputDelta(_)
|
||||
| ServerNotification::TerminalInteraction(_)
|
||||
| ServerNotification::FileChangeOutputDelta(_)
|
||||
| ServerNotification::FileChangePatchUpdated(_)
|
||||
| ServerNotification::ServerRequestResolved(_)
|
||||
| ServerNotification::McpToolCallProgress(_)
|
||||
| ServerNotification::McpServerOauthLoginCompleted(_)
|
||||
| ServerNotification::McpServerStatusUpdated(_)
|
||||
| ServerNotification::McpServerEventStream(_)
|
||||
| ServerNotification::AccountUpdated(_)
|
||||
| ServerNotification::AccountRateLimitsUpdated(_)
|
||||
| ServerNotification::AppListUpdated(_)
|
||||
| ServerNotification::RemoteControlStatusChanged(_)
|
||||
| ServerNotification::ExternalAgentConfigImportProgress(_)
|
||||
| ServerNotification::ExternalAgentConfigImportCompleted(_)
|
||||
| ServerNotification::FsChanged(_)
|
||||
| ServerNotification::ReasoningSummaryTextDelta(_)
|
||||
| ServerNotification::ReasoningSummaryPartAdded(_)
|
||||
| ServerNotification::ReasoningTextDelta(_)
|
||||
| ServerNotification::ContextCompacted(_)
|
||||
| ServerNotification::ModelRerouted(_)
|
||||
| ServerNotification::ModelVerification(_)
|
||||
| ServerNotification::AuthRecoveryStarted(_)
|
||||
| ServerNotification::AuthRecoveryCompleted(_)
|
||||
| ServerNotification::TurnModerationMetadata(_)
|
||||
| ServerNotification::ModelSafetyBufferingUpdated(_)
|
||||
| ServerNotification::Warning(_)
|
||||
| ServerNotification::GuardianWarning(_)
|
||||
| ServerNotification::DeprecationNotice(_)
|
||||
| ServerNotification::ConfigWarning(_)
|
||||
| ServerNotification::FuzzyFileSearchSessionUpdated(_)
|
||||
| ServerNotification::FuzzyFileSearchSessionCompleted(_)
|
||||
| ServerNotification::ThreadRealtimeStarted(_)
|
||||
| ServerNotification::ThreadRealtimeItemAdded(_)
|
||||
| ServerNotification::ThreadRealtimeItemStarted(_)
|
||||
| ServerNotification::ThreadRealtimeItemTranscriptDelta(_)
|
||||
| ServerNotification::ThreadRealtimeItemCompleted(_)
|
||||
| ServerNotification::ThreadRealtimeTranscriptDelta(_)
|
||||
| ServerNotification::ThreadRealtimeTranscriptDone(_)
|
||||
| ServerNotification::ThreadRealtimeOutputAudioDelta(_)
|
||||
| ServerNotification::ThreadRealtimeSdp(_)
|
||||
| ServerNotification::ThreadRealtimeError(_)
|
||||
| ServerNotification::ThreadRealtimeClosed(_)
|
||||
| ServerNotification::WindowsWorldWritableWarning(_)
|
||||
| ServerNotification::WindowsSandboxSetupCompleted(_)
|
||||
| ServerNotification::AccountLoginCompleted(_)
|
||||
| ServerNotification::GatewayOAuthChanged(_) => notification,
|
||||
}
|
||||
}
|
||||
|
||||
fn without_thread_item_media(mut item: ThreadItemPayload) -> ThreadItemPayload {
|
||||
match &mut item {
|
||||
ThreadItemPayload::UserMessage { content, .. } => {
|
||||
content.retain(|item| match item {
|
||||
UserInput::Image { .. } | UserInput::Audio { .. } => false,
|
||||
UserInput::Text { .. }
|
||||
| UserInput::LocalImage { .. }
|
||||
| UserInput::LocalAudio { .. }
|
||||
| UserInput::Skill { .. }
|
||||
| UserInput::Mention { .. } => true,
|
||||
});
|
||||
}
|
||||
ThreadItemPayload::DynamicToolCall {
|
||||
content_items: Some(content_items),
|
||||
..
|
||||
} => {
|
||||
content_items.retain(|item| match item {
|
||||
DynamicToolCallOutputContentItem::InputImage { .. }
|
||||
| DynamicToolCallOutputContentItem::InputAudio { .. } => false,
|
||||
DynamicToolCallOutputContentItem::InputText { .. } => true,
|
||||
});
|
||||
}
|
||||
ThreadItemPayload::FunctionCallOutput {
|
||||
output: FunctionCallOutputBody::ContentItems(items),
|
||||
..
|
||||
} => {
|
||||
items.retain(|item| match item {
|
||||
FunctionCallOutputContentItem::InputImage { .. }
|
||||
| FunctionCallOutputContentItem::InputAudio { .. } => false,
|
||||
FunctionCallOutputContentItem::InputText { .. }
|
||||
| FunctionCallOutputContentItem::EncryptedContent { .. } => true,
|
||||
});
|
||||
}
|
||||
ThreadItemPayload::McpToolCall {
|
||||
result: Some(result),
|
||||
..
|
||||
} => {
|
||||
// TODO(ruslan): Handle oversized results that core has already collapsed into a
|
||||
// truncated text preview, which can contain inline media that this filter retains.
|
||||
result.content.retain(|item| {
|
||||
!matches!(
|
||||
item.get("type").and_then(serde_json::Value::as_str),
|
||||
Some("image" | "audio")
|
||||
) && item
|
||||
.get("resource")
|
||||
.and_then(|resource| resource.get("blob"))
|
||||
.is_none()
|
||||
});
|
||||
}
|
||||
ThreadItemPayload::ImageGeneration(item) => {
|
||||
item.image = GeneratedImageRef::Inline {
|
||||
result: String::new(),
|
||||
};
|
||||
}
|
||||
ThreadItemPayload::HookPrompt { .. }
|
||||
| ThreadItemPayload::AgentMessage { .. }
|
||||
| ThreadItemPayload::Plan { .. }
|
||||
| ThreadItemPayload::Reasoning { .. }
|
||||
| ThreadItemPayload::FunctionCallOutput {
|
||||
output: FunctionCallOutputBody::Text(_),
|
||||
..
|
||||
}
|
||||
| ThreadItemPayload::CommandExecution { .. }
|
||||
| ThreadItemPayload::FileChange { .. }
|
||||
| ThreadItemPayload::McpToolCall { result: None, .. }
|
||||
| ThreadItemPayload::DynamicToolCall {
|
||||
content_items: None,
|
||||
..
|
||||
}
|
||||
| ThreadItemPayload::CollabAgentToolCall { .. }
|
||||
| ThreadItemPayload::SubAgentActivity { .. }
|
||||
| ThreadItemPayload::WebSearch(_)
|
||||
| ThreadItemPayload::ImageView { .. }
|
||||
| ThreadItemPayload::Sleep(_)
|
||||
| ThreadItemPayload::EnteredReviewMode { .. }
|
||||
| ThreadItemPayload::ExitedReviewMode { .. }
|
||||
| ThreadItemPayload::ContextCompaction { .. } => {}
|
||||
}
|
||||
item
|
||||
}
|
||||
95
codex-rs/app-server/src/otel_config.rs
Normal file
95
codex-rs/app-server/src/otel_config.rs
Normal file
@@ -0,0 +1,95 @@
|
||||
//! Maps OTEL requirements and masks exporter credentials in app-server responses.
|
||||
|
||||
use codex_app_server_protocol::OtelExporter;
|
||||
use codex_app_server_protocol::OtelHttpProtocol;
|
||||
use codex_app_server_protocol::OtelRequirements;
|
||||
use codex_app_server_protocol::OtelTlsConfig;
|
||||
use codex_app_server_protocol::OtelToolResultLogConfig;
|
||||
use codex_app_server_protocol::SerdeRedactedString;
|
||||
use codex_config::OtelRequirementsToml;
|
||||
use codex_config::types::OtelExporterKind;
|
||||
use codex_config::types::OtelHttpProtocol as CoreOtelHttpProtocol;
|
||||
use codex_config::types::OtelTlsConfig as CoreOtelTlsConfig;
|
||||
use serde_json::Value as JsonValue;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub(crate) fn map_otel_requirements_to_api(otel: OtelRequirementsToml) -> OtelRequirements {
|
||||
OtelRequirements {
|
||||
tool_result: otel.tool_result.map(|value| OtelToolResultLogConfig {
|
||||
max_bytes: value.max_bytes,
|
||||
}),
|
||||
log_sse_deltas: otel.log_sse_deltas,
|
||||
log_user_prompt: otel.log_user_prompt,
|
||||
log_agent_responses: otel.log_agent_responses,
|
||||
log_guardian_assessments: otel.log_guardian_assessments,
|
||||
environment: otel.environment,
|
||||
exporter: otel.exporter.map(map_otel_exporter_to_api),
|
||||
trace_exporter: otel.trace_exporter.map(map_otel_exporter_to_api),
|
||||
metrics_exporter: otel.metrics_exporter.map(map_otel_exporter_to_api),
|
||||
span_attributes: otel.span_attributes,
|
||||
tracestate: otel.tracestate,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_otel_exporter_to_api(exporter: OtelExporterKind) -> OtelExporter {
|
||||
let response_headers = |headers: HashMap<String, _>| {
|
||||
headers
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name, SerdeRedactedString::from(value)))
|
||||
.collect()
|
||||
};
|
||||
match exporter {
|
||||
OtelExporterKind::None => OtelExporter::None,
|
||||
OtelExporterKind::Statsig => OtelExporter::Statsig,
|
||||
OtelExporterKind::OtlpHttp {
|
||||
endpoint,
|
||||
headers,
|
||||
protocol,
|
||||
tls,
|
||||
} => OtelExporter::OtlpHttp {
|
||||
endpoint,
|
||||
headers: response_headers(headers),
|
||||
protocol: match protocol {
|
||||
CoreOtelHttpProtocol::Binary => OtelHttpProtocol::Binary,
|
||||
CoreOtelHttpProtocol::Json => OtelHttpProtocol::Json,
|
||||
},
|
||||
tls: tls.map(map_otel_tls_to_api),
|
||||
},
|
||||
OtelExporterKind::OtlpGrpc {
|
||||
endpoint,
|
||||
headers,
|
||||
tls,
|
||||
} => OtelExporter::OtlpGrpc {
|
||||
endpoint,
|
||||
headers: response_headers(headers),
|
||||
tls: tls.map(map_otel_tls_to_api),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn map_otel_tls_to_api(tls: CoreOtelTlsConfig) -> OtelTlsConfig {
|
||||
OtelTlsConfig {
|
||||
ca_certificate: tls.ca_certificate.map(Into::into),
|
||||
client_certificate: tls.client_certificate.map(Into::into),
|
||||
client_private_key: tls.client_private_key.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
/// Masks exporter header values before OTEL configuration crosses the API boundary.
|
||||
pub(crate) fn redact_otel_exporter_headers(otel: &mut JsonValue) {
|
||||
for field in ["exporter", "trace_exporter", "metrics_exporter"] {
|
||||
let Some(exporter) = otel.get_mut(field).and_then(JsonValue::as_object_mut) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
for config in exporter.values_mut() {
|
||||
let Some(headers) = config.get_mut("headers").and_then(JsonValue::as_object_mut) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
for value in headers.values_mut() {
|
||||
*value = SerdeRedactedString::PLACEHOLDER.into();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
113
codex-rs/app-server/src/otel_reloader.rs
Normal file
113
codex-rs/app-server/src/otel_reloader.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use crate::OTEL_SERVICE_NAME;
|
||||
use crate::config_manager::ConfigManager;
|
||||
use codex_login::AuthManager;
|
||||
use codex_otel::OtelProvider;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::Subscriber;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
use tracing_subscriber::Layer;
|
||||
use tracing_subscriber::registry::LookupSpan;
|
||||
use tracing_subscriber::reload;
|
||||
|
||||
type OtelExportLayer<S> = Option<Box<dyn Layer<S> + Send + Sync + 'static>>;
|
||||
type OtelReloadLayers<S> = (
|
||||
Vec<Box<dyn Layer<S> + Send + Sync + 'static>>,
|
||||
reload::Handle<OtelExportLayer<S>, S>,
|
||||
);
|
||||
|
||||
pub(crate) fn layers<S>(provider: Option<&OtelProvider>) -> OtelReloadLayers<S>
|
||||
where
|
||||
S: Subscriber + for<'span> LookupSpan<'span> + Send + Sync + 'static,
|
||||
{
|
||||
let logger_export_layer: OtelExportLayer<S> = provider
|
||||
.and_then(OtelProvider::logger_export_layer)
|
||||
.map(Layer::boxed);
|
||||
let (logger_layer, logger_handle) = reload::Layer::new(logger_export_layer);
|
||||
|
||||
let layers: Vec<Box<dyn Layer<S> + Send + Sync + 'static>> = vec![
|
||||
logger_layer
|
||||
.with_filter(tracing_subscriber::filter::filter_fn(
|
||||
OtelProvider::log_export_filter,
|
||||
))
|
||||
.boxed(),
|
||||
// The subscriber graph is fixed after startup. Keep the global tracer
|
||||
// bridge installed even when tracing starts disabled so an account
|
||||
// switch can install a trace exporter later.
|
||||
OtelProvider::reloadable_tracing_layer(OTEL_SERVICE_NAME).boxed(),
|
||||
];
|
||||
(layers, logger_handle)
|
||||
}
|
||||
|
||||
pub(crate) fn spawn<S>(
|
||||
mut provider: Option<OtelProvider>,
|
||||
logger_reload_handle: reload::Handle<OtelExportLayer<S>, S>,
|
||||
config_manager: ConfigManager,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
default_analytics_enabled: bool,
|
||||
shutdown_token: CancellationToken,
|
||||
) -> JoinHandle<()>
|
||||
where
|
||||
S: Subscriber + for<'span> LookupSpan<'span> + Send + Sync + 'static,
|
||||
{
|
||||
let mut auth_changes = auth_manager.auth_change_receiver();
|
||||
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown_token.cancelled() => break,
|
||||
changed = auth_changes.changed() => {
|
||||
if changed.is_err() {
|
||||
break;
|
||||
}
|
||||
|
||||
// Account handlers install the new cloud loader after publishing auth changes.
|
||||
tokio::time::sleep(Duration::from_millis(/*millis*/ 50)).await;
|
||||
|
||||
let config = match config_manager.load_latest_config(/*fallback_cwd*/ None).await {
|
||||
Ok(config) => config,
|
||||
Err(error) => {
|
||||
warn!(%error, "failed to reload telemetry config after account change");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let next_provider = match codex_core::otel_init::build_provider(
|
||||
&config,
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
Some(OTEL_SERVICE_NAME),
|
||||
default_analytics_enabled,
|
||||
) {
|
||||
Ok(provider) => provider,
|
||||
Err(error) => {
|
||||
warn!(%error, "failed to rebuild telemetry exporters after account change");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Err(error) = logger_reload_handle.reload(
|
||||
next_provider
|
||||
.as_ref()
|
||||
.and_then(OtelProvider::logger_export_layer)
|
||||
.map(Layer::boxed),
|
||||
) {
|
||||
warn!(%error, "failed to install telemetry exporters after account change");
|
||||
continue;
|
||||
}
|
||||
if let Some(previous_provider) = std::mem::replace(&mut provider, next_provider) {
|
||||
drop(tokio::task::spawn_blocking(move || previous_provider.shutdown()));
|
||||
}
|
||||
info!(
|
||||
event.name = "codex.app_server.otel_reloaded",
|
||||
"reloaded telemetry exporters after account change"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(provider) = provider {
|
||||
let _ = tokio::task::spawn_blocking(move || provider.shutdown()).await;
|
||||
}
|
||||
})
|
||||
}
|
||||
1787
codex-rs/app-server/src/outgoing_message.rs
Normal file
1787
codex-rs/app-server/src/outgoing_message.rs
Normal file
File diff suppressed because it is too large
Load Diff
37
codex-rs/app-server/src/plugin_config_reload.rs
Normal file
37
codex-rs/app-server/src/plugin_config_reload.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
//! Adapts existing config loaders for blocking plugin-upgrade workers.
|
||||
//! Reloads must use the same normal or fallback entry point as the initial load.
|
||||
|
||||
use crate::config_manager::ConfigManager;
|
||||
use codex_core_plugins::ConfigLayerReload;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The config-loading path used to select marketplaces for startup tasks.
|
||||
pub(crate) enum PluginStartupConfig {
|
||||
Current,
|
||||
Defaults,
|
||||
}
|
||||
|
||||
pub(crate) fn for_cwd(manager: ConfigManager, cwd: AbsolutePathBuf) -> ConfigLayerReload {
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
Arc::new(move || runtime.block_on(manager.load_config_layers_for_cwd(cwd.clone())))
|
||||
}
|
||||
|
||||
/// Reloads config without deriving project context from a process cwd.
|
||||
pub(crate) fn global(manager: ConfigManager) -> ConfigLayerReload {
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
Arc::new(move || {
|
||||
runtime
|
||||
.block_on(manager.load_non_project_config())
|
||||
.map(|config| config.config_layer_stack)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn defaults(manager: ConfigManager) -> ConfigLayerReload {
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
Arc::new(move || {
|
||||
runtime
|
||||
.block_on(manager.load_default_config())
|
||||
.map(|config| config.config_layer_stack)
|
||||
})
|
||||
}
|
||||
759
codex-rs/app-server/src/request_processors.rs
Normal file
759
codex-rs/app-server/src/request_processors.rs
Normal file
@@ -0,0 +1,759 @@
|
||||
use crate::bespoke_event_handling::apply_bespoke_event_handling;
|
||||
use crate::command_exec::CommandExecManager;
|
||||
use crate::command_exec::StartCommandExecParams;
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::error_code::INPUT_TOO_LARGE_ERROR_CODE;
|
||||
use crate::error_code::invalid_params;
|
||||
use crate::models::supported_models;
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::ConnectionRequestId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use crate::outgoing_message::RequestContext;
|
||||
use crate::outgoing_message::ThreadScopedOutgoingMessageSender;
|
||||
use crate::skills_watcher::SkillsWatcher;
|
||||
use crate::thread_status::ThreadWatchManager;
|
||||
use crate::thread_status::resolve_thread_status;
|
||||
use chrono::Duration as ChronoDuration;
|
||||
use chrono::SecondsFormat;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::AnalyticsJsonRpcError;
|
||||
use codex_analytics::InputError;
|
||||
use codex_analytics::TurnSteerRequestError;
|
||||
use codex_app_server_protocol::Account;
|
||||
use codex_app_server_protocol::AccountLoginCompletedNotification;
|
||||
use codex_app_server_protocol::AccountTokenUsageDailyBucket;
|
||||
use codex_app_server_protocol::AccountTokenUsageSummary;
|
||||
use codex_app_server_protocol::AccountUpdatedNotification;
|
||||
use codex_app_server_protocol::AddCreditsNudgeCreditType;
|
||||
use codex_app_server_protocol::AddCreditsNudgeEmailStatus;
|
||||
use codex_app_server_protocol::AdditionalContextEntry;
|
||||
use codex_app_server_protocol::AdditionalContextKind;
|
||||
use codex_app_server_protocol::AppListUpdatedNotification;
|
||||
use codex_app_server_protocol::AppSummary;
|
||||
use codex_app_server_protocol::AppTemplateSummary;
|
||||
use codex_app_server_protocol::AppTemplateUnavailableReason;
|
||||
use codex_app_server_protocol::AppsInstalledParams;
|
||||
use codex_app_server_protocol::AppsInstalledResponse;
|
||||
use codex_app_server_protocol::AppsListParams;
|
||||
use codex_app_server_protocol::AppsListResponse;
|
||||
use codex_app_server_protocol::AppsReadParams;
|
||||
use codex_app_server_protocol::AppsReadResponse;
|
||||
use codex_app_server_protocol::AskForApproval;
|
||||
use codex_app_server_protocol::AuthMode;
|
||||
use codex_app_server_protocol::CancelLoginAccountParams;
|
||||
use codex_app_server_protocol::CancelLoginAccountResponse;
|
||||
use codex_app_server_protocol::CancelLoginAccountStatus;
|
||||
use codex_app_server_protocol::ClientInfo;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::ClientResponsePayload;
|
||||
use codex_app_server_protocol::CodexErrorInfo;
|
||||
use codex_app_server_protocol::CollaborationModeListParams;
|
||||
use codex_app_server_protocol::CollaborationModeListResponse;
|
||||
use codex_app_server_protocol::CommandExecParams;
|
||||
use codex_app_server_protocol::CommandExecResizeParams;
|
||||
use codex_app_server_protocol::CommandExecTerminateParams;
|
||||
use codex_app_server_protocol::CommandExecWriteParams;
|
||||
use codex_app_server_protocol::ConfigWarningNotification;
|
||||
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditOutcome;
|
||||
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditParams;
|
||||
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse;
|
||||
use codex_app_server_protocol::ConversationGitInfo;
|
||||
use codex_app_server_protocol::ConversationSummary;
|
||||
use codex_app_server_protocol::DeprecationNoticeNotification;
|
||||
use codex_app_server_protocol::DynamicToolFunctionSpec;
|
||||
use codex_app_server_protocol::DynamicToolNamespaceTool;
|
||||
use codex_app_server_protocol::DynamicToolSpec;
|
||||
use codex_app_server_protocol::EnvironmentAddParams;
|
||||
use codex_app_server_protocol::EnvironmentAddResponse;
|
||||
use codex_app_server_protocol::EnvironmentInfoParams;
|
||||
use codex_app_server_protocol::EnvironmentInfoResponse;
|
||||
use codex_app_server_protocol::EnvironmentShellInfo;
|
||||
use codex_app_server_protocol::EnvironmentStatusKind;
|
||||
use codex_app_server_protocol::EnvironmentStatusParams;
|
||||
use codex_app_server_protocol::EnvironmentStatusResponse;
|
||||
use codex_app_server_protocol::ExperimentalFeature as ApiExperimentalFeature;
|
||||
use codex_app_server_protocol::ExperimentalFeatureListParams;
|
||||
use codex_app_server_protocol::ExperimentalFeatureListResponse;
|
||||
use codex_app_server_protocol::ExperimentalFeatureStage as ApiExperimentalFeatureStage;
|
||||
use codex_app_server_protocol::FeedbackUploadParams;
|
||||
use codex_app_server_protocol::FeedbackUploadResponse;
|
||||
use codex_app_server_protocol::GetAccountParams;
|
||||
use codex_app_server_protocol::GetAccountRateLimitsResponse;
|
||||
use codex_app_server_protocol::GetAccountResponse;
|
||||
use codex_app_server_protocol::GetAccountTokenUsageParams;
|
||||
use codex_app_server_protocol::GetAccountTokenUsageResponse;
|
||||
use codex_app_server_protocol::GetAuthStatusParams;
|
||||
use codex_app_server_protocol::GetAuthStatusResponse;
|
||||
use codex_app_server_protocol::GetConversationSummaryParams;
|
||||
use codex_app_server_protocol::GetConversationSummaryResponse;
|
||||
use codex_app_server_protocol::GetWorkspaceMessagesResponse;
|
||||
use codex_app_server_protocol::GitDiffToRemoteParams;
|
||||
use codex_app_server_protocol::GitDiffToRemoteResponse;
|
||||
use codex_app_server_protocol::GitInfo as ApiGitInfo;
|
||||
use codex_app_server_protocol::HookHandlerMetadata;
|
||||
use codex_app_server_protocol::HookMetadata;
|
||||
use codex_app_server_protocol::HooksListParams;
|
||||
use codex_app_server_protocol::HooksListResponse;
|
||||
use codex_app_server_protocol::InitializeParams;
|
||||
use codex_app_server_protocol::InitializeResponse;
|
||||
use codex_app_server_protocol::InstalledApp;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::ListMcpServerStatusParams;
|
||||
use codex_app_server_protocol::ListMcpServerStatusResponse;
|
||||
use codex_app_server_protocol::LoginAccountParams;
|
||||
use codex_app_server_protocol::LoginAccountResponse;
|
||||
use codex_app_server_protocol::LoginApiKeyParams;
|
||||
use codex_app_server_protocol::LoginAppBrand;
|
||||
use codex_app_server_protocol::LogoutAccountResponse;
|
||||
use codex_app_server_protocol::MarketplaceAddParams;
|
||||
use codex_app_server_protocol::MarketplaceAddResponse;
|
||||
use codex_app_server_protocol::MarketplaceInterface;
|
||||
use codex_app_server_protocol::MarketplaceRemoveParams;
|
||||
use codex_app_server_protocol::MarketplaceRemoveResponse;
|
||||
use codex_app_server_protocol::MarketplaceUpgradeErrorInfo;
|
||||
use codex_app_server_protocol::MarketplaceUpgradeParams;
|
||||
use codex_app_server_protocol::MarketplaceUpgradeResponse;
|
||||
use codex_app_server_protocol::McpResourceReadParams;
|
||||
use codex_app_server_protocol::McpResourceReadResponse;
|
||||
use codex_app_server_protocol::McpServerOauthClientRegistration;
|
||||
use codex_app_server_protocol::McpServerOauthLoginCompletedNotification;
|
||||
use codex_app_server_protocol::McpServerOauthLoginParams;
|
||||
use codex_app_server_protocol::McpServerOauthLoginResponse;
|
||||
use codex_app_server_protocol::McpServerRefreshResponse;
|
||||
use codex_app_server_protocol::McpServerStatus;
|
||||
use codex_app_server_protocol::McpServerStatusDetail;
|
||||
use codex_app_server_protocol::McpServerToolCallParams;
|
||||
use codex_app_server_protocol::McpServerToolCallResponse;
|
||||
use codex_app_server_protocol::MemoryResetResponse;
|
||||
use codex_app_server_protocol::MockExperimentalMethodParams;
|
||||
use codex_app_server_protocol::MockExperimentalMethodResponse;
|
||||
use codex_app_server_protocol::ModelListParams;
|
||||
use codex_app_server_protocol::ModelListResponse;
|
||||
use codex_app_server_protocol::ModelProviderError;
|
||||
use codex_app_server_protocol::PermissionProfileListParams;
|
||||
use codex_app_server_protocol::PermissionProfileListResponse;
|
||||
use codex_app_server_protocol::PermissionProfileSummary;
|
||||
use codex_app_server_protocol::PluginDetail;
|
||||
use codex_app_server_protocol::PluginInstallParams;
|
||||
use codex_app_server_protocol::PluginInstallResponse;
|
||||
use codex_app_server_protocol::PluginInstalledParams;
|
||||
use codex_app_server_protocol::PluginInstalledResponse;
|
||||
use codex_app_server_protocol::PluginInterface;
|
||||
use codex_app_server_protocol::PluginListMarketplaceKind;
|
||||
use codex_app_server_protocol::PluginListParams;
|
||||
use codex_app_server_protocol::PluginListResponse;
|
||||
use codex_app_server_protocol::PluginMarketplaceEntry;
|
||||
use codex_app_server_protocol::PluginReadParams;
|
||||
use codex_app_server_protocol::PluginReadResponse;
|
||||
use codex_app_server_protocol::PluginShareCheckoutParams;
|
||||
use codex_app_server_protocol::PluginShareCheckoutResponse;
|
||||
use codex_app_server_protocol::PluginShareContext;
|
||||
use codex_app_server_protocol::PluginShareDeleteParams;
|
||||
use codex_app_server_protocol::PluginShareDeleteResponse;
|
||||
use codex_app_server_protocol::PluginShareDiscoverability;
|
||||
use codex_app_server_protocol::PluginShareListItem;
|
||||
use codex_app_server_protocol::PluginShareListParams;
|
||||
use codex_app_server_protocol::PluginShareListResponse;
|
||||
use codex_app_server_protocol::PluginSharePrincipal;
|
||||
use codex_app_server_protocol::PluginSharePrincipalType;
|
||||
use codex_app_server_protocol::PluginShareSaveParams;
|
||||
use codex_app_server_protocol::PluginShareSaveResponse;
|
||||
use codex_app_server_protocol::PluginShareTarget;
|
||||
use codex_app_server_protocol::PluginShareUpdateDiscoverability;
|
||||
use codex_app_server_protocol::PluginShareUpdateTargetsParams;
|
||||
use codex_app_server_protocol::PluginShareUpdateTargetsResponse;
|
||||
use codex_app_server_protocol::PluginSkillReadParams;
|
||||
use codex_app_server_protocol::PluginSkillReadResponse;
|
||||
use codex_app_server_protocol::PluginSource;
|
||||
use codex_app_server_protocol::PluginSummary;
|
||||
use codex_app_server_protocol::PluginUninstallParams;
|
||||
use codex_app_server_protocol::PluginUninstallResponse;
|
||||
use codex_app_server_protocol::RateLimitResetCredit;
|
||||
use codex_app_server_protocol::RateLimitResetCreditStatus;
|
||||
use codex_app_server_protocol::RateLimitResetCreditsSummary;
|
||||
use codex_app_server_protocol::RateLimitResetType;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ReviewStartParams;
|
||||
use codex_app_server_protocol::ReviewStartResponse;
|
||||
use codex_app_server_protocol::ReviewTarget as ApiReviewTarget;
|
||||
use codex_app_server_protocol::SandboxMode;
|
||||
use codex_app_server_protocol::SendAddCreditsNudgeEmailParams;
|
||||
use codex_app_server_protocol::SendAddCreditsNudgeEmailResponse;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::SkillSummary;
|
||||
use codex_app_server_protocol::SkillsConfigWriteParams;
|
||||
use codex_app_server_protocol::SkillsConfigWriteResponse;
|
||||
use codex_app_server_protocol::SkillsExtraRootsSetParams;
|
||||
use codex_app_server_protocol::SkillsExtraRootsSetResponse;
|
||||
use codex_app_server_protocol::SkillsListParams;
|
||||
use codex_app_server_protocol::SkillsListResponse;
|
||||
use codex_app_server_protocol::SortDirection;
|
||||
use codex_app_server_protocol::Thread;
|
||||
use codex_app_server_protocol::ThreadApproveGuardianDeniedActionParams;
|
||||
use codex_app_server_protocol::ThreadApproveGuardianDeniedActionResponse;
|
||||
use codex_app_server_protocol::ThreadArchiveParams;
|
||||
use codex_app_server_protocol::ThreadArchiveResponse;
|
||||
use codex_app_server_protocol::ThreadArchivedNotification;
|
||||
use codex_app_server_protocol::ThreadBackgroundTerminal;
|
||||
use codex_app_server_protocol::ThreadBackgroundTerminalsCleanParams;
|
||||
use codex_app_server_protocol::ThreadBackgroundTerminalsCleanResponse;
|
||||
use codex_app_server_protocol::ThreadBackgroundTerminalsListParams;
|
||||
use codex_app_server_protocol::ThreadBackgroundTerminalsListResponse;
|
||||
use codex_app_server_protocol::ThreadBackgroundTerminalsTerminateParams;
|
||||
use codex_app_server_protocol::ThreadBackgroundTerminalsTerminateResponse;
|
||||
use codex_app_server_protocol::ThreadClosedNotification;
|
||||
use codex_app_server_protocol::ThreadCompactStartParams;
|
||||
use codex_app_server_protocol::ThreadCompactStartResponse;
|
||||
use codex_app_server_protocol::ThreadDecrementElicitationParams;
|
||||
use codex_app_server_protocol::ThreadDecrementElicitationResponse;
|
||||
use codex_app_server_protocol::ThreadDeleteParams;
|
||||
use codex_app_server_protocol::ThreadDeleteResponse;
|
||||
use codex_app_server_protocol::ThreadDeletedNotification;
|
||||
use codex_app_server_protocol::ThreadForkParams;
|
||||
use codex_app_server_protocol::ThreadForkResponse;
|
||||
use codex_app_server_protocol::ThreadGoal;
|
||||
use codex_app_server_protocol::ThreadGoalClearParams;
|
||||
use codex_app_server_protocol::ThreadGoalClearResponse;
|
||||
use codex_app_server_protocol::ThreadGoalClearedNotification;
|
||||
use codex_app_server_protocol::ThreadGoalGetParams;
|
||||
use codex_app_server_protocol::ThreadGoalGetResponse;
|
||||
use codex_app_server_protocol::ThreadGoalSetParams;
|
||||
use codex_app_server_protocol::ThreadGoalSetResponse;
|
||||
use codex_app_server_protocol::ThreadGoalStatus;
|
||||
use codex_app_server_protocol::ThreadGoalUpdatedNotification;
|
||||
use codex_app_server_protocol::ThreadHistoryBuilder;
|
||||
#[cfg(test)]
|
||||
use codex_app_server_protocol::ThreadHistoryMode;
|
||||
use codex_app_server_protocol::ThreadIncrementElicitationParams;
|
||||
use codex_app_server_protocol::ThreadIncrementElicitationResponse;
|
||||
use codex_app_server_protocol::ThreadInjectItemsParams;
|
||||
use codex_app_server_protocol::ThreadInjectItemsResponse;
|
||||
use codex_app_server_protocol::ThreadItemEntry;
|
||||
use codex_app_server_protocol::ThreadItemPayload;
|
||||
use codex_app_server_protocol::ThreadItemsListParams;
|
||||
use codex_app_server_protocol::ThreadItemsListResponse;
|
||||
use codex_app_server_protocol::ThreadItemsReadParams;
|
||||
use codex_app_server_protocol::ThreadItemsReadResponse;
|
||||
use codex_app_server_protocol::ThreadListCwdFilter;
|
||||
use codex_app_server_protocol::ThreadListParams;
|
||||
use codex_app_server_protocol::ThreadListResponse;
|
||||
use codex_app_server_protocol::ThreadLoadedListParams;
|
||||
use codex_app_server_protocol::ThreadLoadedListResponse;
|
||||
use codex_app_server_protocol::ThreadMemoryModeSetParams;
|
||||
use codex_app_server_protocol::ThreadMemoryModeSetResponse;
|
||||
use codex_app_server_protocol::ThreadMetadataGitInfoUpdateParams;
|
||||
use codex_app_server_protocol::ThreadMetadataUpdateParams;
|
||||
use codex_app_server_protocol::ThreadMetadataUpdateResponse;
|
||||
use codex_app_server_protocol::ThreadNameUpdatedNotification;
|
||||
use codex_app_server_protocol::ThreadProjectUpdatedNotification;
|
||||
use codex_app_server_protocol::ThreadReadParams;
|
||||
use codex_app_server_protocol::ThreadReadResponse;
|
||||
use codex_app_server_protocol::ThreadRealtimeAppendAudioParams;
|
||||
use codex_app_server_protocol::ThreadRealtimeAppendAudioResponse;
|
||||
use codex_app_server_protocol::ThreadRealtimeAppendSpeechParams;
|
||||
use codex_app_server_protocol::ThreadRealtimeAppendSpeechResponse;
|
||||
use codex_app_server_protocol::ThreadRealtimeAppendTextParams;
|
||||
use codex_app_server_protocol::ThreadRealtimeAppendTextResponse;
|
||||
use codex_app_server_protocol::ThreadRealtimeListVoicesResponse;
|
||||
use codex_app_server_protocol::ThreadRealtimeStartParams;
|
||||
use codex_app_server_protocol::ThreadRealtimeStartResponse;
|
||||
use codex_app_server_protocol::ThreadRealtimeStartTransport;
|
||||
use codex_app_server_protocol::ThreadRealtimeStopParams;
|
||||
use codex_app_server_protocol::ThreadRealtimeStopResponse;
|
||||
use codex_app_server_protocol::ThreadResumeInitialTurnsPageParams;
|
||||
use codex_app_server_protocol::ThreadResumeParams;
|
||||
use codex_app_server_protocol::ThreadResumeResponse;
|
||||
use codex_app_server_protocol::ThreadSearchOccurrence;
|
||||
use codex_app_server_protocol::ThreadSearchOccurrencesParams;
|
||||
use codex_app_server_protocol::ThreadSearchOccurrencesResponse;
|
||||
use codex_app_server_protocol::ThreadSearchParams;
|
||||
use codex_app_server_protocol::ThreadSearchResponse;
|
||||
use codex_app_server_protocol::ThreadSearchResult;
|
||||
use codex_app_server_protocol::ThreadSearchSortKey;
|
||||
use codex_app_server_protocol::ThreadSearchTextRange;
|
||||
use codex_app_server_protocol::ThreadSetNameParams;
|
||||
use codex_app_server_protocol::ThreadSetNameResponse;
|
||||
use codex_app_server_protocol::ThreadSettings;
|
||||
use codex_app_server_protocol::ThreadSettingsUpdateParams;
|
||||
use codex_app_server_protocol::ThreadSettingsUpdateResponse;
|
||||
use codex_app_server_protocol::ThreadShellCommandParams;
|
||||
use codex_app_server_protocol::ThreadShellCommandResponse;
|
||||
use codex_app_server_protocol::ThreadSortKey;
|
||||
use codex_app_server_protocol::ThreadSourceKind;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_app_server_protocol::ThreadStartedNotification;
|
||||
use codex_app_server_protocol::ThreadStatus;
|
||||
use codex_app_server_protocol::ThreadTimelineListParams;
|
||||
use codex_app_server_protocol::ThreadTimelineListResponse;
|
||||
use codex_app_server_protocol::ThreadTurnsListParams;
|
||||
use codex_app_server_protocol::ThreadTurnsListResponse;
|
||||
use codex_app_server_protocol::ThreadUnarchiveParams;
|
||||
use codex_app_server_protocol::ThreadUnarchiveResponse;
|
||||
use codex_app_server_protocol::ThreadUnarchivedNotification;
|
||||
use codex_app_server_protocol::ThreadUnsubscribeParams;
|
||||
use codex_app_server_protocol::ThreadUnsubscribeResponse;
|
||||
use codex_app_server_protocol::ThreadUnsubscribeStatus;
|
||||
use codex_app_server_protocol::Turn;
|
||||
use codex_app_server_protocol::TurnEnvironmentParams;
|
||||
use codex_app_server_protocol::TurnError;
|
||||
use codex_app_server_protocol::TurnInterruptParams;
|
||||
use codex_app_server_protocol::TurnInterruptResponse;
|
||||
use codex_app_server_protocol::TurnItemsView;
|
||||
use codex_app_server_protocol::TurnSettingsUpdateParams;
|
||||
use codex_app_server_protocol::TurnSettingsUpdateResponse;
|
||||
use codex_app_server_protocol::TurnSettingsUpdateStatus;
|
||||
use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::TurnStartResponse;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_app_server_protocol::TurnSteerParams;
|
||||
use codex_app_server_protocol::TurnSteerResponse;
|
||||
use codex_app_server_protocol::UserInput as V2UserInput;
|
||||
use codex_app_server_protocol::WindowsSandboxReadiness;
|
||||
use codex_app_server_protocol::WindowsSandboxReadinessResponse;
|
||||
use codex_app_server_protocol::WindowsSandboxSetupCompletedNotification;
|
||||
use codex_app_server_protocol::WindowsSandboxSetupMode;
|
||||
use codex_app_server_protocol::WindowsSandboxSetupStartParams;
|
||||
use codex_app_server_protocol::WindowsSandboxSetupStartResponse;
|
||||
use codex_app_server_protocol::WorkspaceMessage;
|
||||
use codex_app_server_protocol::WorkspaceMessageType;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_backend_client::AddCreditsNudgeCreditType as BackendAddCreditsNudgeCreditType;
|
||||
use codex_backend_client::Client as BackendClient;
|
||||
use codex_backend_client::CodexWorkspaceMessage as BackendWorkspaceMessage;
|
||||
use codex_backend_client::CodexWorkspaceMessageType as BackendWorkspaceMessageType;
|
||||
use codex_backend_client::CodexWorkspaceMessagesResponse as BackendWorkspaceMessagesResponse;
|
||||
use codex_backend_client::ConsumeRateLimitResetCreditCode as BackendConsumeRateLimitResetCreditCode;
|
||||
use codex_backend_client::RateLimitResetCreditDetails as BackendRateLimitResetCreditDetails;
|
||||
use codex_backend_client::RateLimitResetCreditsDetails as BackendRateLimitResetCreditsDetails;
|
||||
use codex_backend_client::RequestError as BackendRequestError;
|
||||
use codex_backend_client::TokenUsageProfile;
|
||||
use codex_chatgpt::connectors;
|
||||
use codex_config::CloudConfigBundleLoadError;
|
||||
use codex_config::CloudConfigBundleLoadErrorCode;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::loader::project_trust_key;
|
||||
use codex_config::types::McpServerTransportConfig;
|
||||
use codex_connectors::AppInfo;
|
||||
use codex_core::CodexThread;
|
||||
use codex_core::CodexThreadSettingsOverrides;
|
||||
use codex_core::ForkSnapshot;
|
||||
use codex_core::McpManager;
|
||||
use codex_core::NewThread;
|
||||
use codex_core::NotSubmittedReason;
|
||||
#[cfg(test)]
|
||||
use codex_core::SessionMeta;
|
||||
use codex_core::StartThreadOptions;
|
||||
use codex_core::SteerSubmission;
|
||||
use codex_core::ThreadConfigSnapshot;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::TurnInput;
|
||||
use codex_core::TurnInputRequest;
|
||||
use codex_core::TurnInputSubmission;
|
||||
use codex_core::TurnStartOptions;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_core::config::NetworkProxyAuditMetadata;
|
||||
use codex_core::config::edit::ConfigEdit;
|
||||
use codex_core::config::edit::ConfigEditsBuilder;
|
||||
use codex_core::connectors::AccessibleConnectorsStatus;
|
||||
use codex_core::exec::ExecCapturePolicy;
|
||||
use codex_core::exec::ExecExpiration;
|
||||
use codex_core::exec::ExecParams;
|
||||
use codex_core::exec_env::create_env;
|
||||
use codex_core::path_utils;
|
||||
#[cfg(test)]
|
||||
use codex_core::read_head_for_summary;
|
||||
use codex_core::sandboxing::SandboxPermissions;
|
||||
use codex_core::truncate_rollout_after_turn_id;
|
||||
use codex_core::truncate_rollout_before_turn_id;
|
||||
use codex_core::validate_environment_ids_and_cwds;
|
||||
use codex_core::windows_sandbox::WindowsSandboxLevelExt;
|
||||
use codex_core::windows_sandbox::WindowsSandboxSetupMode as CoreWindowsSandboxSetupMode;
|
||||
use codex_core::windows_sandbox::WindowsSandboxSetupRequest;
|
||||
use codex_core::windows_sandbox::sandbox_setup_is_complete;
|
||||
use codex_core_plugins::PluginInstallError as CorePluginInstallError;
|
||||
use codex_core_plugins::PluginInstallRequest;
|
||||
use codex_core_plugins::PluginReadRequest;
|
||||
use codex_core_plugins::PluginUninstallError as CorePluginUninstallError;
|
||||
use codex_core_plugins::PluginsManager;
|
||||
use codex_core_plugins::loader::load_plugin_apps;
|
||||
use codex_core_plugins::manifest::PluginManifestInterface;
|
||||
use codex_core_plugins::marketplace::MarketplaceError;
|
||||
use codex_core_plugins::marketplace::MarketplacePluginSource;
|
||||
use codex_core_plugins::marketplace_add::MarketplaceAddError;
|
||||
use codex_core_plugins::marketplace_add::MarketplaceAddRequest;
|
||||
use codex_core_plugins::marketplace_add::add_marketplace as add_marketplace_to_codex_home;
|
||||
use codex_core_plugins::marketplace_remove::MarketplaceRemoveError;
|
||||
use codex_core_plugins::marketplace_remove::MarketplaceRemoveRequest as CoreMarketplaceRemoveRequest;
|
||||
use codex_core_plugins::marketplace_remove::remove_marketplace;
|
||||
use codex_core_plugins::remote::RemoteMarketplace;
|
||||
use codex_core_plugins::remote::RemoteMarketplaceSource;
|
||||
use codex_core_plugins::remote::RemotePluginCatalogError;
|
||||
use codex_core_plugins::remote::RemotePluginDetail as RemoteCatalogPluginDetail;
|
||||
use codex_core_plugins::remote::RemotePluginServiceConfig;
|
||||
use codex_core_plugins::remote::RemotePluginShareContext as RemoteCatalogPluginShareContext;
|
||||
use codex_core_plugins::remote::RemotePluginShareSummary as RemoteCatalogPluginShareSummary;
|
||||
use codex_core_plugins::remote::RemotePluginSummary as RemoteCatalogPluginSummary;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_exec_server::EnvironmentObservedStatus;
|
||||
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_features::FEATURES;
|
||||
use codex_features::Feature;
|
||||
use codex_features::Stage;
|
||||
use codex_feedback::CodexFeedback;
|
||||
use codex_feedback::FeedbackAttachmentPath;
|
||||
use codex_feedback::FeedbackUploadOptions;
|
||||
use codex_git_utils::git_diff_to_remote;
|
||||
use codex_git_utils::resolve_root_git_project_for_trust;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CODEX_OPEN_APP_URL;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::LoginSuccessPage;
|
||||
use codex_login::LoginSuccessPageBrand;
|
||||
use codex_login::ServerOptions as LoginServerOptions;
|
||||
use codex_login::ShutdownHandle;
|
||||
use codex_login::complete_device_code_login;
|
||||
use codex_login::login_with_api_key;
|
||||
use codex_login::login_with_bedrock_api_key;
|
||||
use codex_login::oauth_client_id;
|
||||
use codex_login::request_device_code;
|
||||
use codex_login::run_login_server;
|
||||
use codex_mcp::McpRuntimeContext;
|
||||
use codex_mcp::McpServerStatusSnapshot;
|
||||
use codex_mcp::McpSnapshotDetail;
|
||||
use codex_mcp::collect_mcp_server_status_snapshot_with_detail;
|
||||
use codex_mcp::discover_supported_scopes;
|
||||
use codex_mcp::read_mcp_resource as read_mcp_resource_without_thread;
|
||||
use codex_mcp::resolve_oauth_scopes;
|
||||
use codex_memories_write::clear_memory_roots_contents;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_models_manager::collaboration_mode_presets::builtin_collaboration_mode_presets;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::CollaborationMode;
|
||||
use codex_protocol::config_types::ForcedLoginMethod;
|
||||
use codex_protocol::config_types::Personality;
|
||||
use codex_protocol::config_types::ReasoningSummary;
|
||||
use codex_protocol::config_types::TrustLevel;
|
||||
use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::AdditionalContextEntry as CoreAdditionalContextEntry;
|
||||
use codex_protocol::protocol::AdditionalContextKind as CoreAdditionalContextKind;
|
||||
use codex_protocol::protocol::AgentStatus;
|
||||
use codex_protocol::protocol::ConversationAudioParams;
|
||||
use codex_protocol::protocol::ConversationSpeechParams;
|
||||
use codex_protocol::protocol::ConversationStartParams;
|
||||
use codex_protocol::protocol::ConversationStartTransport;
|
||||
use codex_protocol::protocol::ConversationTextParams;
|
||||
use codex_protocol::protocol::EnvironmentConfigState;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::protocol::GitInfo as CoreGitInfo;
|
||||
use codex_protocol::protocol::McpAuthStatus as CoreMcpAuthStatus;
|
||||
use codex_protocol::protocol::Op;
|
||||
use codex_protocol::protocol::RealtimeVoicesList;
|
||||
use codex_protocol::protocol::ReviewRequest;
|
||||
use codex_protocol::protocol::ReviewTarget as CoreReviewTarget;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::protocol::SessionMetaLine;
|
||||
use codex_protocol::protocol::TurnEnvironmentRequest;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use codex_protocol::protocol::strip_user_message_prefix;
|
||||
use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS;
|
||||
use codex_protocol::user_input::UserInput as CoreInputItem;
|
||||
use codex_rmcp_client::McpOAuthClientRegistration;
|
||||
use codex_rmcp_client::StreamableHttpRedirectMode;
|
||||
use codex_rmcp_client::perform_oauth_login_return_url;
|
||||
use codex_rollout::InitialHistory;
|
||||
use codex_rollout::ResumedHistory;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::persisted_rollout_item;
|
||||
use codex_rollout::state_db::StateDbHandle;
|
||||
use codex_rollout::state_db::reconcile_rollout;
|
||||
use codex_state::ThreadMetadata;
|
||||
use codex_state::log_db::LogDbLayer;
|
||||
use codex_thread_store::ArchiveThreadParams as StoreArchiveThreadParams;
|
||||
use codex_thread_store::ArchiveThreadsParams as StoreArchiveThreadsParams;
|
||||
use codex_thread_store::ClearableField as StoreClearableField;
|
||||
use codex_thread_store::DeleteThreadsParams as StoreDeleteThreadsParams;
|
||||
use codex_thread_store::GitInfoPatch as StoreGitInfoPatch;
|
||||
use codex_thread_store::ItemSortKey as StoreItemSortKey;
|
||||
use codex_thread_store::ListItemsParams as StoreListItemsParams;
|
||||
use codex_thread_store::ListItemsPosition as StoreListItemsPosition;
|
||||
use codex_thread_store::ListThreadsParams as StoreListThreadsParams;
|
||||
use codex_thread_store::ListTimelineParams as StoreListTimelineParams;
|
||||
use codex_thread_store::ListTurnsParams as StoreListTurnsParams;
|
||||
use codex_thread_store::LoadThreadHistoryParams as StoreLoadThreadHistoryParams;
|
||||
use codex_thread_store::LocalThreadStore;
|
||||
use codex_thread_store::ReadThreadByRolloutPathParams as StoreReadThreadByRolloutPathParams;
|
||||
use codex_thread_store::ReadThreadParams as StoreReadThreadParams;
|
||||
use codex_thread_store::SearchThreadOccurrencesParams as StoreSearchThreadOccurrencesParams;
|
||||
use codex_thread_store::SearchThreadsParams as StoreSearchThreadsParams;
|
||||
use codex_thread_store::SortDirection as StoreSortDirection;
|
||||
use codex_thread_store::StoredThread;
|
||||
use codex_thread_store::StoredTurn;
|
||||
use codex_thread_store::StoredTurnItemsView;
|
||||
use codex_thread_store::StoredTurnStatus;
|
||||
use codex_thread_store::ThreadMetadataPatch as StoreThreadMetadataPatch;
|
||||
use codex_thread_store::ThreadRelationFilter as StoreThreadRelationFilter;
|
||||
use codex_thread_store::ThreadSortKey as StoreThreadSortKey;
|
||||
use codex_thread_store::ThreadStore;
|
||||
use codex_thread_store::ThreadStoreError;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::io::Error as IoError;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::result::Result;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::SemaphorePermit;
|
||||
use tokio::sync::broadcast;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::sync::DropGuard;
|
||||
use tokio_util::task::TaskTracker;
|
||||
use toml::Value as TomlValue;
|
||||
use tracing::Instrument;
|
||||
use tracing::error;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[cfg(test)]
|
||||
use codex_app_server_protocol::ServerRequest;
|
||||
|
||||
pub(crate) mod account_processor;
|
||||
mod apps_processor;
|
||||
mod bedrock_auth;
|
||||
mod catalog_processor;
|
||||
mod command_exec_processor;
|
||||
pub(crate) mod config_processor;
|
||||
#[cfg(test)]
|
||||
#[path = "request_processors/config_reload_tests.rs"]
|
||||
mod config_reload_tests;
|
||||
mod diagnostics;
|
||||
mod environment_processor;
|
||||
mod feedback_doctor_report;
|
||||
mod feedback_processor;
|
||||
mod feedback_rollout_history;
|
||||
mod feedback_thread_index;
|
||||
mod fs_processor;
|
||||
mod git_processor;
|
||||
mod initialize_processor;
|
||||
mod marketplace_processor;
|
||||
mod mcp_event_stream;
|
||||
mod mcp_processor;
|
||||
mod memory_status;
|
||||
mod persisted_resume_settings;
|
||||
mod plugins;
|
||||
mod process_exec_processor;
|
||||
mod projects;
|
||||
mod remote_control_processor;
|
||||
mod rollout;
|
||||
mod search;
|
||||
mod thread_attachments;
|
||||
mod thread_enrichment;
|
||||
mod thread_fork_goal;
|
||||
mod thread_input;
|
||||
mod thread_memory;
|
||||
mod thread_processor;
|
||||
mod thread_queue_processor;
|
||||
mod thread_read_state;
|
||||
mod thread_sections;
|
||||
mod token_usage_replay;
|
||||
mod turn_processor;
|
||||
mod windows_sandbox_processor;
|
||||
|
||||
pub(crate) use account_processor::AccountRequestProcessor;
|
||||
pub(crate) use apps_processor::AppsRequestProcessor;
|
||||
pub(crate) use catalog_processor::CatalogRequestProcessor;
|
||||
pub(crate) use command_exec_processor::CommandExecRequestProcessor;
|
||||
pub(crate) use config_processor::ConfigRequestProcessor;
|
||||
pub(crate) use diagnostics::read_server_diagnostics;
|
||||
pub(crate) use environment_processor::EnvironmentRequestProcessor;
|
||||
pub(crate) use feedback_processor::FeedbackRequestProcessor;
|
||||
pub(crate) use fs_processor::FsRequestProcessor;
|
||||
pub(crate) use git_processor::GitRequestProcessor;
|
||||
pub(crate) use initialize_processor::InitializeRequestProcessor;
|
||||
pub(crate) use marketplace_processor::MarketplaceRequestProcessor;
|
||||
pub(crate) use mcp_event_stream::McpEventStreamReady;
|
||||
pub(crate) use mcp_event_stream::McpEventStreams;
|
||||
pub(crate) use mcp_processor::McpRequestProcessor;
|
||||
pub(crate) use plugins::PluginRequestProcessor;
|
||||
pub(crate) use process_exec_processor::ProcessExecRequestProcessor;
|
||||
pub(crate) use projects::ProjectRequestProcessor;
|
||||
pub(crate) use remote_control_processor::RemoteControlRequestProcessor;
|
||||
pub(crate) use search::SearchRequestProcessor;
|
||||
pub(crate) use thread_goal_processor::ThreadGoalRequestProcessor;
|
||||
pub(crate) use thread_processor::ThreadRequestProcessor;
|
||||
pub(crate) use thread_processor::ThreadResumeTarget;
|
||||
pub(crate) use thread_queue_processor::ThreadQueueRequestProcessor;
|
||||
pub(crate) use turn_processor::TurnRequestProcessor;
|
||||
pub(crate) use windows_sandbox_processor::WindowsSandboxRequestProcessor;
|
||||
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::filters::compute_source_filters;
|
||||
use crate::filters::source_kind_matches;
|
||||
use crate::thread_state::ConnectionCapabilities;
|
||||
use crate::thread_state::PendingThreadUnloads;
|
||||
use crate::thread_state::ThreadListenerCommand;
|
||||
use crate::thread_state::ThreadState;
|
||||
use crate::thread_state::ThreadStateManager;
|
||||
use token_usage_replay::restored_token_usage_turn_id;
|
||||
use token_usage_replay::send_thread_token_usage_update_to_connection;
|
||||
|
||||
pub(crate) fn apply_live_thread_settings(
|
||||
thread: &mut Thread,
|
||||
config_snapshot: &ThreadConfigSnapshot,
|
||||
) {
|
||||
thread.model = Some(config_snapshot.model.clone());
|
||||
thread.reasoning_effort = config_snapshot.reasoning_effort.clone();
|
||||
thread.environments = Some(
|
||||
config_snapshot
|
||||
.environment_selections()
|
||||
.iter()
|
||||
.map(Into::into)
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
|
||||
fn resolve_request_cwd(cwd: Option<PathBuf>) -> Result<Option<AbsolutePathBuf>, JSONRPCErrorError> {
|
||||
cwd.map(|cwd| {
|
||||
AbsolutePathBuf::relative_to_current_dir(path_utils::normalize_for_native_workdir(cwd))
|
||||
.map_err(|err| invalid_request(format!("invalid cwd: {err}")))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn resolve_turn_environment_requests(
|
||||
thread_manager: &ThreadManager,
|
||||
environments: Option<Vec<TurnEnvironmentParams>>,
|
||||
) -> Result<Option<Vec<TurnEnvironmentRequest>>, JSONRPCErrorError> {
|
||||
let Some(environments) = environments else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut requests = Vec::with_capacity(environments.len());
|
||||
for environment in environments {
|
||||
let environment_id = environment.environment_id;
|
||||
let cwd = environment
|
||||
.cwd
|
||||
.to_inferred_path_uri()
|
||||
.ok_or_else(|| {
|
||||
invalid_request(format!(
|
||||
"invalid cwd for environment `{environment_id}`: path `{}` does not use absolute POSIX or Windows path syntax",
|
||||
environment.cwd
|
||||
))
|
||||
})?;
|
||||
let workspace_roots = environment
|
||||
.runtime_workspace_roots
|
||||
.map(|roots| {
|
||||
let mut resolved_roots = Vec::new();
|
||||
for root in roots {
|
||||
let root = root.to_inferred_path_uri().ok_or_else(|| {
|
||||
invalid_request(format!(
|
||||
"invalid runtime workspace root for environment `{environment_id}`: path `{root}` does not use absolute POSIX or Windows path syntax"
|
||||
))
|
||||
})?;
|
||||
if !resolved_roots.contains(&root) {
|
||||
resolved_roots.push(root);
|
||||
}
|
||||
}
|
||||
Ok::<_, JSONRPCErrorError>(resolved_roots)
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or_else(|| vec![cwd.clone()]);
|
||||
requests.push(TurnEnvironmentRequest {
|
||||
environment_id,
|
||||
cwd,
|
||||
workspace_roots,
|
||||
config: EnvironmentConfigState::FromThread,
|
||||
});
|
||||
}
|
||||
validate_environment_ids_and_cwds(
|
||||
&thread_manager.environment_manager(),
|
||||
requests
|
||||
.iter()
|
||||
.map(|request| (request.environment_id.as_str(), &request.cwd)),
|
||||
)
|
||||
.map_err(environment_selection_error)?;
|
||||
Ok(Some(requests))
|
||||
}
|
||||
|
||||
/// Project-local layers cannot define providers, so explicit selectors can use the startup map.
|
||||
fn config_for_provider(
|
||||
startup: &Arc<Config>,
|
||||
provider_id: &str,
|
||||
) -> Result<Arc<Config>, JSONRPCErrorError> {
|
||||
if startup.model_provider_id == provider_id {
|
||||
return Ok(Arc::clone(startup));
|
||||
}
|
||||
let provider = startup.model_providers.get(provider_id).ok_or_else(|| {
|
||||
model_provider_error(&ModelProviderError::ModelProviderNotConfigured {
|
||||
model_provider: provider_id.to_owned(),
|
||||
})
|
||||
})?;
|
||||
let mut config = startup.as_ref().clone();
|
||||
config.model_provider_id = provider_id.to_owned();
|
||||
config.model_provider = provider.clone();
|
||||
Ok(Arc::new(config))
|
||||
}
|
||||
|
||||
fn resolve_runtime_workspace_roots(workspace_roots: Vec<AbsolutePathBuf>) -> Vec<AbsolutePathBuf> {
|
||||
let mut resolved_roots = Vec::new();
|
||||
for root in workspace_roots {
|
||||
if !resolved_roots.iter().any(|existing| existing == &root) {
|
||||
resolved_roots.push(root);
|
||||
}
|
||||
}
|
||||
resolved_roots
|
||||
}
|
||||
|
||||
pub(crate) mod config_errors;
|
||||
mod request_errors;
|
||||
mod thread_delete;
|
||||
mod thread_goal_processor;
|
||||
mod thread_lifecycle;
|
||||
mod thread_resume_redaction;
|
||||
mod thread_summary;
|
||||
|
||||
use self::config_errors::*;
|
||||
use self::request_errors::*;
|
||||
use self::thread_goal_processor::api_thread_goal_from_state;
|
||||
use self::thread_lifecycle::*;
|
||||
use self::thread_resume_redaction::*;
|
||||
use self::thread_summary::*;
|
||||
|
||||
pub(crate) use self::thread_lifecycle::populate_thread_turns_from_history;
|
||||
#[cfg(test)]
|
||||
pub(crate) use self::thread_summary::read_summary_from_rollout;
|
||||
#[cfg(test)]
|
||||
pub(crate) use self::thread_summary::summary_to_thread;
|
||||
pub(crate) use self::thread_summary::thread_settings_from_config_snapshot;
|
||||
|
||||
pub(crate) fn build_legacy_api_turns_from_rollout_items(items: &[RolloutItem]) -> Vec<Turn> {
|
||||
let mut builder = ThreadHistoryBuilder::new();
|
||||
for item in items {
|
||||
if let Some(item) =
|
||||
persisted_rollout_item(item, codex_protocol::protocol::ThreadHistoryMode::Legacy)
|
||||
{
|
||||
builder.handle_rollout_item(item.as_ref());
|
||||
}
|
||||
}
|
||||
builder.finish()
|
||||
}
|
||||
1718
codex-rs/app-server/src/request_processors/account_processor.rs
Normal file
1718
codex-rs/app-server/src/request_processors/account_processor.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,31 @@
|
||||
//! Build account API clients from the latest config and captured account authority.
|
||||
|
||||
use super::*;
|
||||
use futures::future::BoxFuture;
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
// Keep config loading and runtime bootstrap out of request-handler future types.
|
||||
#[inline(never)]
|
||||
pub(super) fn backend_client<'a>(
|
||||
&'a self,
|
||||
auth: &'a CodexAuth,
|
||||
http_client_factory: codex_http_client::HttpClientFactory,
|
||||
) -> BoxFuture<'a, Result<BackendClient, JSONRPCErrorError>> {
|
||||
Box::pin(async move {
|
||||
let config = self.load_latest_config().await;
|
||||
let runtime = self
|
||||
.thread_manager
|
||||
.runtime_auth_for_config(&config)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
BackendClient::from_auth_with_runtime(
|
||||
config.chatgpt_base_url.clone(),
|
||||
auth,
|
||||
http_client_factory,
|
||||
runtime.as_ref(),
|
||||
/*headers*/ &Default::default(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| internal_error(error.to_string()))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Post-login GovCloud checks use current authentication and freshly loaded configuration.
|
||||
//! Official endpoint hostnames take precedence over credential and configured AWS regions.
|
||||
//! Results are advisory; configuration and region resolution failures remain RPC errors.
|
||||
|
||||
use super::AccountRequestProcessor;
|
||||
use crate::error_code::internal_error;
|
||||
use codex_app_server_protocol::BedrockCheckGovCloudRequirementsResponse;
|
||||
use codex_app_server_protocol::ClientResponsePayload;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_config::NetworkDomainPermissionToml;
|
||||
use codex_model_provider::is_amazon_bedrock_gov_cloud_region;
|
||||
use codex_model_provider::resolve_amazon_bedrock_region;
|
||||
use codex_protocol::config_types::ForcedLoginMethod;
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) async fn bedrock_check_gov_cloud_requirements(
|
||||
&self,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to load configuration: {err}")))?;
|
||||
let provider = &config.model_provider;
|
||||
if !provider.is_amazon_bedrock() {
|
||||
return Ok(Some(
|
||||
BedrockCheckGovCloudRequirementsResponse {
|
||||
is_gov_cloud: false,
|
||||
should_warn: false,
|
||||
}
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
|
||||
let endpoint_domain = provider
|
||||
.base_url
|
||||
.as_deref()
|
||||
.map(|base_url| {
|
||||
url::Url::parse(base_url)
|
||||
.ok()
|
||||
.and_then(|url| {
|
||||
url.host_str()
|
||||
.map(|host| host.trim_end_matches('.').to_string())
|
||||
})
|
||||
.ok_or_else(|| internal_error("Amazon Bedrock endpoint has no valid hostname"))
|
||||
})
|
||||
.transpose()?;
|
||||
let endpoint_region = endpoint_domain.as_deref().and_then(|domain| {
|
||||
let (service, rest) = domain.split_once('.')?;
|
||||
let region = match service {
|
||||
"bedrock-mantle" => rest.strip_suffix(".api.aws"),
|
||||
"bedrock-runtime" | "bedrock-runtime-fips" => rest.strip_suffix(".amazonaws.com"),
|
||||
_ => None,
|
||||
}?;
|
||||
// Require a single region label, not a substring in a proxy hostname.
|
||||
(!region.is_empty() && !region.contains('.')).then_some(region)
|
||||
});
|
||||
let region = match endpoint_region {
|
||||
Some(region) => region.to_string(),
|
||||
None => {
|
||||
resolve_amazon_bedrock_region(provider.clone(), Some(self.auth_manager.clone()))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to resolve Amazon Bedrock region: {err}"))
|
||||
})?
|
||||
}
|
||||
};
|
||||
let is_gov_cloud = is_amazon_bedrock_gov_cloud_region(®ion);
|
||||
let mut should_warn = false;
|
||||
if is_gov_cloud {
|
||||
let domain = if let Some(domain) = endpoint_domain {
|
||||
domain
|
||||
} else if provider.is_amazon_bedrock_runtime() {
|
||||
format!("bedrock-runtime.{region}.amazonaws.com")
|
||||
} else {
|
||||
format!("bedrock-mantle.{region}.api.aws")
|
||||
};
|
||||
let requirements = config.config_layer_stack.requirements_toml();
|
||||
let api_only = requirements
|
||||
.allowed_login_methods
|
||||
.as_ref()
|
||||
.is_some_and(|methods| {
|
||||
!methods.is_empty()
|
||||
&& methods
|
||||
.iter()
|
||||
.all(|method| *method == ForcedLoginMethod::Api)
|
||||
});
|
||||
let network_allowed = requirements
|
||||
.application
|
||||
.as_ref()
|
||||
.and_then(|application| application.network.as_ref())
|
||||
.is_some_and(|network| {
|
||||
network.enabled
|
||||
&& network.domains.get(&domain) == Some(&NetworkDomainPermissionToml::Allow)
|
||||
});
|
||||
should_warn = !api_only || !network_allowed;
|
||||
}
|
||||
|
||||
Ok(Some(
|
||||
BedrockCheckGovCloudRequirementsResponse {
|
||||
is_gov_cloud,
|
||||
should_warn,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
use super::super::bedrock_auth::BedrockProviderConfig;
|
||||
use super::super::bedrock_auth::prepare_bedrock_provider;
|
||||
use super::super::config_processor::map_error as map_config_error;
|
||||
use super::AccountRequestProcessor;
|
||||
use super::CloudLoginProvider;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use codex_app_server_protocol::AwsCredentialType;
|
||||
use codex_app_server_protocol::BedrockAwsProfile;
|
||||
use codex_app_server_protocol::BedrockDiscoverParams;
|
||||
use codex_app_server_protocol::BedrockDiscoverResponse;
|
||||
use codex_app_server_protocol::BedrockEnvironmentCredential;
|
||||
use codex_app_server_protocol::BedrockSetupParams;
|
||||
use codex_app_server_protocol::BedrockSetupResponse;
|
||||
use codex_app_server_protocol::ClientResponsePayload;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::is_supported_amazon_bedrock_region;
|
||||
|
||||
const AWS_ACCESS_KEY_ID: &str = "AWS_ACCESS_KEY_ID";
|
||||
const AWS_SECRET_ACCESS_KEY: &str = "AWS_SECRET_ACCESS_KEY";
|
||||
const AWS_BEARER_TOKEN_BEDROCK: &str = "AWS_BEARER_TOKEN_BEDROCK";
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) async fn bedrock_discover(
|
||||
&self,
|
||||
_params: BedrockDiscoverParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.ensure_provider_login_allowed(CloudLoginProvider::AmazonBedrock)?;
|
||||
let profiles = codex_aws_auth::discover_aws_profiles()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to discover AWS profiles: {err}")))?
|
||||
.into_iter()
|
||||
.map(|profile| BedrockAwsProfile {
|
||||
name: profile.name,
|
||||
region: profile.region,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let region = non_empty_env_var("AWS_REGION");
|
||||
let environment_credentials = [
|
||||
(
|
||||
AwsCredentialType::AccessKeys,
|
||||
non_empty_env_var(AWS_ACCESS_KEY_ID).is_some()
|
||||
&& non_empty_env_var(AWS_SECRET_ACCESS_KEY).is_some(),
|
||||
),
|
||||
(
|
||||
AwsCredentialType::BedrockApiKey,
|
||||
non_empty_env_var(AWS_BEARER_TOKEN_BEDROCK).is_some(),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|(_, available)| *available)
|
||||
.map(|(credential_type, _)| BedrockEnvironmentCredential {
|
||||
credential_type,
|
||||
region: region.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Some(
|
||||
BedrockDiscoverResponse {
|
||||
profiles,
|
||||
environment_credentials,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn bedrock_setup(
|
||||
&self,
|
||||
params: BedrockSetupParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.ensure_provider_login_allowed(CloudLoginProvider::AmazonBedrock)?;
|
||||
let (profile, region) = match ¶ms {
|
||||
BedrockSetupParams::Profile { profile, region } => {
|
||||
(Some(profile.trim()), region.trim())
|
||||
}
|
||||
BedrockSetupParams::Environment { region } => (None, region.trim()),
|
||||
};
|
||||
let write = prepare_bedrock_provider(
|
||||
&self.config_manager,
|
||||
BedrockProviderConfig {
|
||||
region: Some(region),
|
||||
profile,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
if profile.is_none()
|
||||
&& matches!(
|
||||
self.auth_manager.auth_cached(),
|
||||
Some(CodexAuth::BedrockApiKey(_) | CodexAuth::BedrockAccessKeys(_))
|
||||
)
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Codex-managed Bedrock credentials are already configured and take priority over AWS environment credentials. Run `codex logout` and try again.",
|
||||
));
|
||||
}
|
||||
|
||||
if !is_supported_amazon_bedrock_region(region) {
|
||||
return Err(invalid_request(format!(
|
||||
"Amazon Bedrock does not support region `{region}`"
|
||||
)));
|
||||
}
|
||||
|
||||
if let Some(profile) = profile {
|
||||
if profile.is_empty() {
|
||||
return Err(invalid_request("AWS profile name must not be empty."));
|
||||
}
|
||||
codex_aws_auth::validate_aws_profile(
|
||||
profile,
|
||||
region,
|
||||
self.config.http_client_factory(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
invalid_request(format!(
|
||||
"failed to load credentials for AWS profile `{profile}`: {err}"
|
||||
))
|
||||
})?;
|
||||
} else {
|
||||
let has_bedrock_api_key = non_empty_env_var(AWS_BEARER_TOKEN_BEDROCK).is_some();
|
||||
let has_access_keys = non_empty_env_var(AWS_ACCESS_KEY_ID).is_some()
|
||||
&& non_empty_env_var(AWS_SECRET_ACCESS_KEY).is_some();
|
||||
if !has_bedrock_api_key && !has_access_keys {
|
||||
return Err(invalid_request(
|
||||
"No AWS credentials found. Please Configure AWS credentials or complete AWS sign-in, then try again.",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Validate the selected credentials against Bedrock ListModels once supported.
|
||||
self.cancel_active_login().await;
|
||||
self.config_manager
|
||||
.commit_provider_config(write)
|
||||
.await
|
||||
.map_err(map_config_error)?;
|
||||
self.model_catalog.invalidate().await;
|
||||
|
||||
Ok(Some(BedrockSetupResponse {}.into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty_env_var(name: &str) -> Option<String> {
|
||||
std::env::var(name)
|
||||
.ok()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
//! Owns one explicit enterprise sign-in attempt for a configured MCP server.
|
||||
//! Start, replacement, cancellation, and local commit admission all pass through this state.
|
||||
//! The credential store separately fences logins invalidated by another process.
|
||||
|
||||
use super::*;
|
||||
use anyhow::Context;
|
||||
use codex_config::McpEmaRegistration;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_mcp::ema_auth_scope;
|
||||
use codex_rmcp_client::EmaErrorDetail;
|
||||
use codex_rmcp_client::EnterpriseOAuthLoginRequest;
|
||||
use codex_rmcp_client::perform_enterprise_oauth_login_return_url;
|
||||
use futures::FutureExt;
|
||||
use tokio::sync::watch;
|
||||
|
||||
pub(crate) struct EnterpriseLoginTarget {
|
||||
pub(crate) thread_id: String,
|
||||
pub(crate) server_name: String,
|
||||
pub(crate) registration: McpEmaRegistration,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
pub(crate) enum EnterpriseLoginCompletion {
|
||||
Pending,
|
||||
Succeeded,
|
||||
Failed(EmaErrorDetail),
|
||||
}
|
||||
|
||||
impl EnterpriseLoginCompletion {
|
||||
pub(crate) fn is_complete(self) -> bool {
|
||||
matches!(self, Self::Succeeded | Self::Failed(_))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct EnterpriseLogin {
|
||||
pub(crate) login_id: String,
|
||||
pub(crate) authorization_url: String,
|
||||
pub(crate) completion: watch::Receiver<EnterpriseLoginCompletion>,
|
||||
}
|
||||
|
||||
pub(crate) struct EnterpriseLoginState {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config_manager: ConfigManager,
|
||||
// Cancellation and commit admission use this same lock. A cancelled attempt cannot commit.
|
||||
active: Mutex<Option<EnterpriseLoginAttempt>>,
|
||||
// Start and cancel hold this through callback shutdown; the worker never acquires it.
|
||||
start_gate: Mutex<()>,
|
||||
// Account changes cancel queued and running setup before waiting for start_gate.
|
||||
setup_cancel: Mutex<CancellationToken>,
|
||||
}
|
||||
|
||||
struct EnterpriseLoginAttempt {
|
||||
login_id: String,
|
||||
cancel: CancellationToken,
|
||||
completion: watch::Receiver<EnterpriseLoginCompletion>,
|
||||
}
|
||||
|
||||
impl Drop for EnterpriseLoginAttempt {
|
||||
fn drop(&mut self) {
|
||||
self.cancel.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
impl EnterpriseLoginState {
|
||||
pub(super) fn new(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config_manager: ConfigManager,
|
||||
) -> Self {
|
||||
Self {
|
||||
auth_manager,
|
||||
thread_manager,
|
||||
config_manager,
|
||||
active: Mutex::new(None),
|
||||
start_gate: Mutex::new(()),
|
||||
setup_cancel: Mutex::new(CancellationToken::new()),
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "serialize start/cancel through callback shutdown; the worker uses a separate state lock"
|
||||
)]
|
||||
pub(super) async fn cancel(&self, login_id: Option<&str>) -> bool {
|
||||
if login_id.is_none() {
|
||||
let mut setup_cancel = self.setup_cancel.lock().await;
|
||||
setup_cancel.cancel();
|
||||
*setup_cancel = CancellationToken::new();
|
||||
}
|
||||
let (login_id, mut completion) = {
|
||||
let active = self.active.lock().await;
|
||||
if login_id.is_some_and(|id| active.as_ref().is_none_or(|a| a.login_id != id)) {
|
||||
return false;
|
||||
}
|
||||
let Some(attempt) = active.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
attempt.cancel.cancel();
|
||||
(attempt.login_id.clone(), attempt.completion.clone())
|
||||
};
|
||||
// A partial callback request can stall the blocking HTTP worker. Cancellation
|
||||
// already fences commit; primary logout must not wait indefinitely for I/O.
|
||||
if tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
let _start = self.start_gate.lock().await;
|
||||
completion.wait_for(|state| state.is_complete()).await
|
||||
})
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
self.clear(&login_id).await;
|
||||
}
|
||||
// Retain a timed-out attempt so a replacement still waits for port cleanup.
|
||||
true
|
||||
}
|
||||
|
||||
async fn clear(&self, login_id: &str) {
|
||||
let mut active = self.active.lock().await;
|
||||
if active
|
||||
.as_ref()
|
||||
.is_some_and(|attempt| attempt.login_id == login_id)
|
||||
{
|
||||
*active = None;
|
||||
}
|
||||
}
|
||||
|
||||
async fn configuration_is_current(
|
||||
&self,
|
||||
target: &EnterpriseLoginTarget,
|
||||
keyring_backend: AuthKeyringBackendKind,
|
||||
) -> bool {
|
||||
let Ok(thread_id) = ThreadId::from_string(&target.thread_id) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(thread) = self.thread_manager.get_thread(thread_id).await else {
|
||||
return false;
|
||||
};
|
||||
let current = thread.config().await;
|
||||
let Ok(config) = self
|
||||
.config_manager
|
||||
.load_latest_config_with_session_layers(¤t.config_layer_stack, ¤t.cwd)
|
||||
.await
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let config = thread.runtime_mcp_config_and_context(&config).await.0;
|
||||
let auth = self.auth_manager.auth_cached();
|
||||
let servers = codex_mcp::effective_mcp_servers(&config, auth.as_ref());
|
||||
config.xaa_enabled
|
||||
&& config.auth_keyring_backend_kind == keyring_backend
|
||||
&& servers.get(&target.server_name).is_some_and(|server| {
|
||||
server.config().enabled
|
||||
&& server.config().ema_registration() == Some(&target.registration)
|
||||
})
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "serialize start/cancel through callback shutdown; the worker uses a separate state lock"
|
||||
)]
|
||||
pub(crate) async fn start(
|
||||
self: &Arc<Self>,
|
||||
request: EnterpriseOAuthLoginRequest<'_>,
|
||||
scope: codex_config::McpEmaAuthScope,
|
||||
target: EnterpriseLoginTarget,
|
||||
) -> Result<EnterpriseLogin, JSONRPCErrorError> {
|
||||
// MCP requests are not in the account request queue. Serialize start and
|
||||
// cancellation here; the separate commit gate stays responsive to the worker.
|
||||
let setup_cancel = self.setup_cancel.lock().await.child_token();
|
||||
let _start = tokio::select! {
|
||||
biased;
|
||||
_ = setup_cancel.cancelled() => return Err(internal_error("enterprise sign-in was cancelled")),
|
||||
guard = self.start_gate.lock() => guard,
|
||||
};
|
||||
let previous = {
|
||||
let active = self.active.lock().await;
|
||||
// Keep the cancelled attempt installed until its callback worker closes.
|
||||
// A cancelled replacement request leaves the next start responsible for waiting.
|
||||
active.as_ref().map(|attempt| {
|
||||
attempt.cancel.cancel();
|
||||
(attempt.login_id.clone(), attempt.completion.clone())
|
||||
})
|
||||
};
|
||||
if let Some((login_id, mut completion)) = previous {
|
||||
// An abandoned setup request drops its flow and closes this channel.
|
||||
let _ = tokio::select! {
|
||||
biased;
|
||||
_ = setup_cancel.cancelled() => return Err(internal_error("enterprise sign-in was cancelled")),
|
||||
result = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(10),
|
||||
completion.wait_for(|state| state.is_complete()),
|
||||
) => result.map_err(|_| internal_error("previous enterprise sign-in did not close"))?,
|
||||
};
|
||||
self.clear(&login_id).await;
|
||||
}
|
||||
let login_generation = self
|
||||
.auth_manager
|
||||
.auth_change_state_receiver()
|
||||
.borrow()
|
||||
.login_generation;
|
||||
let account = self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.filter(|auth| ema_auth_scope(Some(auth)).as_ref() == Some(&scope))
|
||||
.ok_or_else(|| internal_error("Codex account changed during enterprise sign-in"))?;
|
||||
if !self
|
||||
.auth_manager
|
||||
.account_login_is_current(&account)
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(internal_error(
|
||||
"Codex account changed during enterprise sign-in",
|
||||
));
|
||||
}
|
||||
let keyring_backend = request.keyring_backend_kind;
|
||||
// Keep commit cancellation under `active`; cancelling the setup epoch must
|
||||
// not race an already-admitted synchronous credential write.
|
||||
let cancel = CancellationToken::new();
|
||||
let login_id = Uuid::new_v4().to_string();
|
||||
let (completed, completion) = watch::channel(EnterpriseLoginCompletion::Pending);
|
||||
*self.active.lock().await = Some(EnterpriseLoginAttempt {
|
||||
login_id: login_id.clone(),
|
||||
cancel: cancel.clone(),
|
||||
completion: completion.clone(),
|
||||
});
|
||||
let handle = tokio::select! {
|
||||
biased;
|
||||
_ = setup_cancel.cancelled() => Err(internal_error("enterprise sign-in was cancelled")),
|
||||
_ = cancel.cancelled() => Err(internal_error("enterprise sign-in was cancelled")),
|
||||
result = perform_enterprise_oauth_login_return_url(request) =>
|
||||
result.map_err(|error| internal_error(
|
||||
EmaErrorDetail::from_error(
|
||||
&error.context(EmaErrorDetail::new("failed to start enterprise sign-in")),
|
||||
).to_string(),
|
||||
)),
|
||||
};
|
||||
let handle = match handle {
|
||||
Ok(handle) => handle,
|
||||
Err(error) => {
|
||||
self.clear(&login_id).await;
|
||||
completed.send_replace(EnterpriseLoginCompletion::Failed(EmaErrorDetail::new(
|
||||
"failed to start enterprise sign-in",
|
||||
)));
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let callback_closed = handle.callback_closed().shared();
|
||||
let authorization_url = handle.authorization_url();
|
||||
let lifecycle = Arc::clone(self);
|
||||
let completion_id = login_id.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() =>
|
||||
Err(EmaErrorDetail::new("Enterprise sign-in was cancelled.").into()),
|
||||
result = async {
|
||||
let credentials = handle.wait().await.context(EmaErrorDetail::new(
|
||||
"Enterprise sign-in authorization failed.",
|
||||
))?;
|
||||
callback_closed.clone().await;
|
||||
let mut active = credentials.commit_if(|| async {
|
||||
lifecycle.auth_manager.reload().await;
|
||||
let eligible = lifecycle.auth_manager.account_login_is_current(&account).await.unwrap_or(false)
|
||||
&& lifecycle.configuration_is_current(&target, keyring_backend).await;
|
||||
// Reread persisted account authority after acquiring the credential
|
||||
// lock, including changes made by another app-server process.
|
||||
lifecycle.auth_manager.reload().await;
|
||||
if !eligible || !lifecycle.auth_manager.account_login_is_current(&account).await.unwrap_or(false) {
|
||||
return None;
|
||||
}
|
||||
// Keep cancellation responsive during the async checks above.
|
||||
// Once admitted, retain this guard through the synchronous write.
|
||||
let active = lifecycle.active.lock().await;
|
||||
let current = active.as_ref().is_some_and(|attempt| {
|
||||
attempt.login_id == completion_id && !attempt.cancel.is_cancelled()
|
||||
})
|
||||
&& lifecycle.auth_manager.auth_change_state_receiver().borrow().login_generation == login_generation
|
||||
&& ema_auth_scope(lifecycle.auth_manager.auth_cached().as_ref()).as_ref() == Some(&scope);
|
||||
if !current {
|
||||
return None;
|
||||
}
|
||||
// The credential lock is held: revoke cached bearers before replacing
|
||||
// the grant, and let new threads pin only the committed credential.
|
||||
lifecycle.config_manager.revoke_mcp_ema();
|
||||
Some(active)
|
||||
}).await.context(EmaErrorDetail::new(
|
||||
"Enterprise sign-in credential commit failed.",
|
||||
))?;
|
||||
// A successful commit is no longer cancelable. Clear it while
|
||||
// still holding the commit gate.
|
||||
*active = None;
|
||||
Ok(())
|
||||
} => result,
|
||||
};
|
||||
// The canceled wait future has dropped its listener guard. Also wait
|
||||
// for the blocking callback worker before allowing a fixed-port retry.
|
||||
callback_closed.await;
|
||||
if result.is_err() {
|
||||
lifecycle.clear(&completion_id).await;
|
||||
}
|
||||
completed.send_replace(match result {
|
||||
Ok(()) => EnterpriseLoginCompletion::Succeeded,
|
||||
Err(error) => EnterpriseLoginCompletion::Failed(EmaErrorDetail::from_error(&error)),
|
||||
});
|
||||
});
|
||||
Ok(EnterpriseLogin {
|
||||
login_id,
|
||||
authorization_url,
|
||||
completion,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Gateway sign-in RPCs share credentials with inference and bind cancellation to the initiating connection.
|
||||
//! Cancellation is acknowledged only after the active login releases its slot.
|
||||
|
||||
use super::*;
|
||||
use crate::gateway_oauth_notifications::status_fields;
|
||||
use crate::transport::ConnectionId;
|
||||
use codex_app_server_protocol::GatewayOAuthCancelResponse;
|
||||
use codex_app_server_protocol::GatewayOAuthLoginResponse;
|
||||
use codex_app_server_protocol::GatewayOAuthReadResponse;
|
||||
use codex_login::OAuthSessionManager;
|
||||
use codex_model_provider::GatewayAuthManager;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
pub(super) struct ActiveGatewayLogin {
|
||||
owner: ConnectionId,
|
||||
cancel: CancellationToken,
|
||||
finished: CancellationToken,
|
||||
}
|
||||
|
||||
struct LoginGuard(Arc<std::sync::Mutex<Option<ActiveGatewayLogin>>>);
|
||||
|
||||
impl Drop for LoginGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(active) = self.0.lock().unwrap_or_else(PoisonError::into_inner).take() {
|
||||
active.finished.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
async fn gateway_client(
|
||||
&self,
|
||||
model_provider: Option<String>,
|
||||
) -> Result<(Arc<Config>, Option<Arc<OAuthSessionManager>>), JSONRPCErrorError> {
|
||||
let config = match model_provider.as_deref() {
|
||||
Some(provider_id) => {
|
||||
let config = config_for_provider(&self.config, provider_id)?;
|
||||
// Explicit selectors use startup definitions, so validate against current policy.
|
||||
self.config_manager
|
||||
.check_thread_model_provider(&config)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
config
|
||||
}
|
||||
None => Arc::new(
|
||||
self.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?,
|
||||
),
|
||||
};
|
||||
let manager = codex_model_provider::create_model_provider(
|
||||
config.model_provider.clone(),
|
||||
Some(Arc::clone(&self.auth_manager)),
|
||||
)
|
||||
.gateway_auth_manager()
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
let session = manager
|
||||
.as_deref()
|
||||
.and_then(GatewayAuthManager::oauth_session);
|
||||
// Keep sign-in status alive when clients alternate between providers.
|
||||
if let Some(manager) = &manager {
|
||||
self.gateway_clients
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(config.model_provider_id.clone(), Arc::clone(manager));
|
||||
}
|
||||
Ok((config, session))
|
||||
}
|
||||
|
||||
pub(crate) async fn gateway_oauth_read(
|
||||
&self,
|
||||
params: codex_app_server_protocol::GatewayOAuthReadParams,
|
||||
) -> Result<GatewayOAuthReadResponse, JSONRPCErrorError> {
|
||||
let (config, client) = self.gateway_client(params.model_provider).await?;
|
||||
let state = if let Some(client) = client {
|
||||
Some(status_fields(
|
||||
client
|
||||
.status()
|
||||
.await
|
||||
.map_err(|err| internal_error(err.to_string()))?,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(GatewayOAuthReadResponse {
|
||||
provider_id: config.model_provider_id.clone(),
|
||||
provider_name: config.model_provider.name.clone(),
|
||||
required: state.is_some(),
|
||||
status: state.as_ref().map(|state| state.0),
|
||||
error: state.and_then(|state| state.1),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn gateway_oauth_login(
|
||||
&self,
|
||||
params: codex_app_server_protocol::GatewayOAuthLoginParams,
|
||||
owner: ConnectionId,
|
||||
connection_gate: &crate::connection_rpc_gate::ConnectionRpcGate,
|
||||
) -> Result<GatewayOAuthLoginResponse, JSONRPCErrorError> {
|
||||
let cancel = CancellationToken::new();
|
||||
let guard = {
|
||||
let mut active = self
|
||||
.gateway_login
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if connection_gate.is_closed() {
|
||||
return Err(invalid_request("The connection is closed"));
|
||||
}
|
||||
if active.is_some() {
|
||||
return Err(invalid_request("Gateway sign-in is already in progress"));
|
||||
}
|
||||
*active = Some(ActiveGatewayLogin {
|
||||
owner,
|
||||
cancel: cancel.clone(),
|
||||
finished: CancellationToken::new(),
|
||||
});
|
||||
LoginGuard(Arc::clone(&self.gateway_login))
|
||||
};
|
||||
let (config, client) = self.gateway_client(params.model_provider).await?;
|
||||
let client = client
|
||||
.ok_or_else(|| invalid_request("The selected provider does not use gateway OAuth"))?;
|
||||
if config.model_provider.requires_openai_auth
|
||||
&& config.model_provider.env_key.is_none()
|
||||
&& config.model_provider.experimental_bearer_token.is_none()
|
||||
&& config.model_provider.auth.is_none()
|
||||
&& self.auth_manager.auth_cached().is_none()
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Sign in to your primary account before signing in to the gateway",
|
||||
));
|
||||
}
|
||||
let (url_tx, url_rx) = tokio::sync::oneshot::channel();
|
||||
let login = client.login_with_browser(cancel.cancelled(), |url| {
|
||||
let _ = url_tx.send(url.to_string());
|
||||
});
|
||||
tokio::pin!(login);
|
||||
let result = tokio::select! {
|
||||
result = &mut login => result,
|
||||
url = url_rx => {
|
||||
if let Ok(url) = url {
|
||||
self.outgoing.send_server_notification_to_connections(&[owner], ServerNotification::GatewayOAuthChanged(codex_app_server_protocol::GatewayOAuthChangedNotification {
|
||||
auth_url: Some(url), provider_id: config.model_provider_id.clone(),
|
||||
status: codex_app_server_protocol::GatewayOAuthStatus::Started, error: None,
|
||||
})).await;
|
||||
}
|
||||
login.await
|
||||
}
|
||||
};
|
||||
result.map_err(|err| internal_error(err.to_string()))?;
|
||||
drop(guard);
|
||||
Ok(GatewayOAuthLoginResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn gateway_oauth_cancel(
|
||||
&self,
|
||||
owner: ConnectionId,
|
||||
) -> Result<GatewayOAuthCancelResponse, JSONRPCErrorError> {
|
||||
let finished = {
|
||||
let active = self
|
||||
.gateway_login
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
let Some(active) = active.as_ref() else {
|
||||
return Ok(GatewayOAuthCancelResponse {});
|
||||
};
|
||||
if active.owner != owner {
|
||||
return Err(invalid_request(
|
||||
"Gateway sign-in belongs to another connection",
|
||||
));
|
||||
}
|
||||
active.cancel.cancel();
|
||||
active.finished.clone()
|
||||
};
|
||||
finished.cancelled().await;
|
||||
Ok(GatewayOAuthCancelResponse {})
|
||||
}
|
||||
|
||||
pub(crate) fn gateway_connection_closed(&self, owner: ConnectionId) {
|
||||
let active = self
|
||||
.gateway_login
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(active) = active.as_ref()
|
||||
&& active.owner == owner
|
||||
{
|
||||
active.cancel.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cancel_gateway_login(&self) {
|
||||
let active = self
|
||||
.gateway_login
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(active) = active.as_ref() {
|
||||
active.cancel.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Validates and persists GCP setup without changing saved login credentials or existing threads.
|
||||
|
||||
use super::super::config_processor::map_error as map_config_error;
|
||||
use super::AccountRequestProcessor;
|
||||
use super::CloudLoginProvider;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use codex_app_server_protocol::ClientResponsePayload;
|
||||
use codex_app_server_protocol::GcpSetupParams;
|
||||
use codex_app_server_protocol::GcpSetupResponse;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_config::apply_default_gcp_auth;
|
||||
use codex_login::RefreshTokenError;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_model_provider_info::GCP_PROVIDER_ID;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::merge_gcp_provider_overrides;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serialize;
|
||||
use serde::de::MapAccess;
|
||||
use serde::de::Visitor;
|
||||
use serde::de::value::MapAccessDeserializer;
|
||||
use serde_json::json;
|
||||
use std::fmt;
|
||||
use std::io::BufReader;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tokio::fs::File;
|
||||
|
||||
pub(crate) async fn handle_gcp_setup(
|
||||
processor: &AccountRequestProcessor,
|
||||
params: GcpSetupParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
processor.ensure_provider_login_allowed(CloudLoginProvider::Gcp)?;
|
||||
let network_policy = processor
|
||||
.auth_manager
|
||||
.application_network_policy()
|
||||
.for_current_account();
|
||||
let layers = processor
|
||||
.model_catalog
|
||||
.load_startup_config_layers()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to load configuration layers: {err}")))?;
|
||||
let (write, provider) = processor
|
||||
.config_manager
|
||||
.prepare_provider_config(
|
||||
&layers,
|
||||
GCP_PROVIDER_ID,
|
||||
[
|
||||
("project_id", Some(params.project_id.trim())),
|
||||
(
|
||||
"location",
|
||||
Some(params.location.as_deref().unwrap_or("global").trim()),
|
||||
),
|
||||
("credential_file", params.credential_file.as_deref()),
|
||||
],
|
||||
)
|
||||
.map_err(map_config_error)?;
|
||||
if provider.base_url.is_some() {
|
||||
return Err(invalid_request(
|
||||
"Google Cloud has a custom `base_url`. Clear `model_providers.gcp.base_url` before configuring a project and location.",
|
||||
));
|
||||
}
|
||||
// Even checking a Windows UNC credential path can contact the remote host.
|
||||
let permit = network_policy
|
||||
.acquire_for_unsupported_sdk()
|
||||
.map_err(|err| invalid_request(err.to_string()))?;
|
||||
permit
|
||||
.run(verify_credentials(provider, &processor.config.cwd))
|
||||
.await
|
||||
.map_err(|err| invalid_request(err.to_string()))??;
|
||||
|
||||
processor
|
||||
.config_manager
|
||||
.commit_provider_config(write)
|
||||
.await
|
||||
.map_err(map_config_error)?;
|
||||
processor.cancel_active_login().await;
|
||||
processor.model_catalog.invalidate().await;
|
||||
Ok(Some(GcpSetupResponse {}.into()))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
enum AuthErrorReason {
|
||||
GcloudNotInstalled,
|
||||
CredentialFileInvalid,
|
||||
AuthCommandFailed,
|
||||
}
|
||||
|
||||
impl AuthErrorReason {
|
||||
fn error(self, message: impl Into<String>) -> JSONRPCErrorError {
|
||||
let mut error = invalid_request(message);
|
||||
error.data = Some(json!({ "reason": self }));
|
||||
error
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_credential_file(path: &Path) -> std::io::Result<File> {
|
||||
if !tokio::fs::metadata(path).await?.is_file() {
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"expected a regular file",
|
||||
));
|
||||
}
|
||||
File::open(path).await
|
||||
}
|
||||
|
||||
// Require a JSON object. Serde also accepts positional arrays when deserializing a struct.
|
||||
struct AdcObject;
|
||||
|
||||
impl<'de> Visitor<'de> for AdcObject {
|
||||
type Value = ();
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("a Google Cloud credential object")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<(), A::Error> {
|
||||
#[derive(Deserialize)]
|
||||
struct Adc {
|
||||
#[serde(rename = "type")]
|
||||
kind: String,
|
||||
}
|
||||
let adc = Adc::deserialize(MapAccessDeserializer::new(map))?;
|
||||
if adc.kind.trim().is_empty() {
|
||||
return Err(serde::de::Error::custom(
|
||||
"expected a nonempty credential type",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_adc_file(file: File) -> std::io::Result<()> {
|
||||
let file = file.into_std().await;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
// Stream past type-specific fields without retaining the credential contents.
|
||||
let mut json = serde_json::Deserializer::from_reader(BufReader::new(file));
|
||||
json.deserialize_map(AdcObject)?;
|
||||
json.end()?;
|
||||
Ok(())
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn verify_credentials(
|
||||
configured: ModelProviderInfo,
|
||||
cwd: &AbsolutePathBuf,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
configured
|
||||
.validate_gcp_credential_file()
|
||||
.map_err(|err| AuthErrorReason::CredentialFileInvalid.error(err))?;
|
||||
let default_gcloud = configured.auth.is_none();
|
||||
let mut candidate = ModelProviderInfo::create_gcp_provider();
|
||||
merge_gcp_provider_overrides(Some(&mut candidate), configured).map_err(invalid_request)?;
|
||||
apply_default_gcp_auth(&mut candidate, cwd);
|
||||
candidate.validate().map_err(invalid_request)?;
|
||||
let auth_file = candidate.credential_file.clone().or_else(|| {
|
||||
if default_gcloud {
|
||||
std::env::var_os("GOOGLE_APPLICATION_CREDENTIALS").map(PathBuf::from)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
if let Some(path) = auth_file {
|
||||
let path = cwd.as_path().join(path);
|
||||
let file = open_credential_file(&path).await.map_err(|err| {
|
||||
AuthErrorReason::CredentialFileInvalid.error(format!(
|
||||
"Cannot read the Google Cloud credential file: {err}"
|
||||
))
|
||||
})?;
|
||||
if default_gcloud {
|
||||
validate_adc_file(file).await.map_err(|_| AuthErrorReason::CredentialFileInvalid.error(
|
||||
"Expected a Google Cloud credential file containing a JSON object with a nonempty string type.",
|
||||
))?;
|
||||
}
|
||||
}
|
||||
let provider = create_model_provider(candidate, /*auth_manager*/ None);
|
||||
provider
|
||||
.runtime_base_url()
|
||||
.await
|
||||
.map_err(|err| invalid_request(err.to_string()))?;
|
||||
// This fresh provider owns a command-backed manager. A refresh runs that command
|
||||
// once and preserves errors that the inference auth path reduces to missing auth.
|
||||
let auth_manager = provider
|
||||
.auth_manager()
|
||||
.ok_or_else(|| internal_error("Missing GCP auth manager."))?;
|
||||
if let Err(err) = auth_manager.refresh_token().await {
|
||||
if default_gcloud
|
||||
&& let RefreshTokenError::Transient(err) = err
|
||||
&& err.kind() == ErrorKind::NotFound
|
||||
&& cwd.as_path().is_dir()
|
||||
{
|
||||
return Err(AuthErrorReason::GcloudNotInstalled.error(
|
||||
"Cannot find gcloud on the app-server host. Check its installation and PATH.",
|
||||
));
|
||||
}
|
||||
return Err(AuthErrorReason::AuthCommandFailed
|
||||
.error("The Google Cloud auth command could not obtain an access token."));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
use super::*;
|
||||
|
||||
const RATE_LIMIT_RESET_REQUEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
|
||||
const RATE_LIMIT_RESET_DETAILS_REQUEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5);
|
||||
#[cfg(debug_assertions)]
|
||||
const RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR: &str =
|
||||
"CODEX_TEST_RATE_LIMIT_RESET_REQUEST_TIMEOUT_MS";
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(super) async fn detailed_rate_limit_reset_credits(
|
||||
client: &BackendClient,
|
||||
) -> Option<RateLimitResetCreditsSummary> {
|
||||
let details = match tokio::time::timeout(
|
||||
RATE_LIMIT_RESET_DETAILS_REQUEST_TIMEOUT,
|
||||
client.list_rate_limit_reset_credits(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(details)) => details,
|
||||
Ok(Err(err)) => {
|
||||
tracing::warn!(
|
||||
"failed to fetch rate limit reset credit details; falling back to the usage response: {err}"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!(
|
||||
"rate limit reset credit detail request timed out; falling back to the usage response"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
match rate_limit_reset_credits_from_backend(details) {
|
||||
Ok(summary) => Some(summary),
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
"failed to parse rate limit reset credit details; falling back to the usage response: {err}"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn consume_account_rate_limit_reset_credit(
|
||||
&self,
|
||||
params: ConsumeAccountRateLimitResetCreditParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
if params.idempotency_key.is_empty() {
|
||||
return Err(invalid_request("idempotencyKey must not be empty"));
|
||||
}
|
||||
if params.credit_id.as_deref().is_some_and(str::is_empty) {
|
||||
return Err(invalid_request("creditId must not be empty"));
|
||||
}
|
||||
|
||||
let client = self.rate_limit_reset_backend_client().await?;
|
||||
let request_timeout = RATE_LIMIT_RESET_REQUEST_TIMEOUT;
|
||||
#[cfg(debug_assertions)]
|
||||
let request_timeout = std::env::var(RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR)
|
||||
.ok()
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
.map(Duration::from_millis)
|
||||
.unwrap_or(request_timeout);
|
||||
let response = tokio::time::timeout(request_timeout, async {
|
||||
match params.credit_id.as_deref() {
|
||||
Some(credit_id) => {
|
||||
client
|
||||
.consume_rate_limit_reset_credit_by_id(¶ms.idempotency_key, credit_id)
|
||||
.await
|
||||
}
|
||||
None => {
|
||||
client
|
||||
.consume_rate_limit_reset_credit(¶ms.idempotency_key)
|
||||
.await
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| internal_error("rate limit reset consume timed out"))?
|
||||
.map_err(|err| internal_error(format!("failed to consume rate limit reset: {err}")))?;
|
||||
let outcome = match response.code {
|
||||
BackendConsumeRateLimitResetCreditCode::Reset => {
|
||||
ConsumeAccountRateLimitResetCreditOutcome::Reset
|
||||
}
|
||||
BackendConsumeRateLimitResetCreditCode::NothingToReset => {
|
||||
ConsumeAccountRateLimitResetCreditOutcome::NothingToReset
|
||||
}
|
||||
BackendConsumeRateLimitResetCreditCode::NoCredit => {
|
||||
ConsumeAccountRateLimitResetCreditOutcome::NoCredit
|
||||
}
|
||||
BackendConsumeRateLimitResetCreditCode::AlreadyRedeemed => {
|
||||
ConsumeAccountRateLimitResetCreditOutcome::AlreadyRedeemed
|
||||
}
|
||||
};
|
||||
Ok(Some(
|
||||
ConsumeAccountRateLimitResetCreditResponse { outcome }.into(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn rate_limit_reset_backend_client(&self) -> Result<BackendClient, JSONRPCErrorError> {
|
||||
let Some((auth, http_client_factory)) =
|
||||
self.auth_manager.auth_with_http_client_factory().await
|
||||
else {
|
||||
return Err(invalid_request(
|
||||
"codex account authentication required for rate limit reset credits",
|
||||
));
|
||||
};
|
||||
if !auth.uses_codex_backend() {
|
||||
return Err(invalid_request(
|
||||
"chatgpt authentication required for rate limit reset credits",
|
||||
));
|
||||
}
|
||||
|
||||
self.backend_client(&auth, http_client_factory).await
|
||||
}
|
||||
}
|
||||
|
||||
fn rate_limit_reset_credits_from_backend(
|
||||
details: BackendRateLimitResetCreditsDetails,
|
||||
) -> Result<RateLimitResetCreditsSummary, String> {
|
||||
let credits = details
|
||||
.credits
|
||||
.into_iter()
|
||||
.map(rate_limit_reset_credit_from_backend)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(RateLimitResetCreditsSummary {
|
||||
available_count: details.available_count,
|
||||
credits: Some(credits),
|
||||
})
|
||||
}
|
||||
|
||||
fn rate_limit_reset_credit_from_backend(
|
||||
credit: BackendRateLimitResetCreditDetails,
|
||||
) -> Result<RateLimitResetCredit, String> {
|
||||
let reset_type = match credit.reset_type.as_str() {
|
||||
"codex_rate_limits" => RateLimitResetType::CodexRateLimits,
|
||||
_ => RateLimitResetType::Unknown,
|
||||
};
|
||||
let status = match credit.status.as_str() {
|
||||
"available" => RateLimitResetCreditStatus::Available,
|
||||
"redeeming" => RateLimitResetCreditStatus::Redeeming,
|
||||
"redeemed" => RateLimitResetCreditStatus::Redeemed,
|
||||
_ => RateLimitResetCreditStatus::Unknown,
|
||||
};
|
||||
let granted_at = rate_limit_reset_credit_timestamp(&credit.granted_at)
|
||||
.map_err(|err| format!("invalid granted_at for credit `{}`: {err}", credit.id))?;
|
||||
let expires_at = credit
|
||||
.expires_at
|
||||
.as_deref()
|
||||
.map(rate_limit_reset_credit_timestamp)
|
||||
.transpose()
|
||||
.map_err(|err| format!("invalid expires_at for credit `{}`: {err}", credit.id))?;
|
||||
|
||||
Ok(RateLimitResetCredit {
|
||||
id: credit.id,
|
||||
reset_type,
|
||||
status,
|
||||
granted_at,
|
||||
expires_at,
|
||||
title: credit.title,
|
||||
description: credit.description,
|
||||
})
|
||||
}
|
||||
|
||||
fn rate_limit_reset_credit_timestamp(timestamp: &str) -> Result<i64, String> {
|
||||
DateTime::parse_from_rfc3339(timestamp)
|
||||
.map(|timestamp| timestamp.timestamp())
|
||||
.map_err(|err| format!("failed to parse timestamp `{timestamp}`: {err}"))
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Keep optional security reminders on the app-server's existing runtime identity.
|
||||
//! Only saved ChatGPT credentials matching the active login may fetch a notice.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::AccountSecuritySetupAction;
|
||||
use codex_app_server_protocol::AccountSecuritySetupNotice;
|
||||
use codex_app_server_protocol::GetAccountSecuritySetupResponse;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
notice: Option<Notice>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Notice {
|
||||
title: String,
|
||||
description: String,
|
||||
action: AccountSecuritySetupAction,
|
||||
}
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) async fn get_account_security_setup(&self) -> GetAccountSecuritySetupResponse {
|
||||
let notice = tokio::time::timeout(Duration::from_secs(/*secs*/ 3), async {
|
||||
let config = self.load_latest_config().await;
|
||||
let (auth, factory) = self.auth_manager.auth_with_http_client_factory().await?;
|
||||
let source_generation = self
|
||||
.auth_manager
|
||||
.auth_change_state_for(&auth)?
|
||||
.source_generation;
|
||||
let saved = config
|
||||
.auth_config()
|
||||
.load_auth(/*enable_codex_api_key_env*/ false)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()?;
|
||||
if !matches!(saved, CodexAuth::Chatgpt(_)) || saved.is_fedramp_account() {
|
||||
return None;
|
||||
}
|
||||
if auth.auth_mode() != codex_protocol::auth::AuthMode::Chatgpt
|
||||
|| saved.get_token().ok()? != auth.get_token().ok()?
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let account_id = auth.get_account_id()?;
|
||||
let user_id = auth.get_chatgpt_user_id()?;
|
||||
let url = format!(
|
||||
"{}/wham/security-setup",
|
||||
config.chatgpt_base_url.trim_end_matches('/')
|
||||
);
|
||||
let runtime = self
|
||||
.thread_manager
|
||||
.runtime_auth_for_config(&config)
|
||||
.ok()?
|
||||
.filter(|_| codex_runtime_agent_instance::is_openai_api_url(&url));
|
||||
let resolved = codex_model_provider::auth_provider_for_request(
|
||||
&auth,
|
||||
runtime.as_ref(),
|
||||
/*headers*/ &Default::default(),
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
let factory = resolved.bind_http_client_factory(factory).ok()?;
|
||||
let client =
|
||||
RouteAwareClientPool::new_without_redirects(factory, ClientRouteClass::Api);
|
||||
let mut headers = resolved
|
||||
.auth
|
||||
.apply_auth_headers(Default::default())
|
||||
.await
|
||||
.ok()?;
|
||||
headers.insert("chatgpt-account-id", account_id.parse().ok()?);
|
||||
resolved.validate_headers(&headers).ok()?;
|
||||
let response = client
|
||||
.get(&url)
|
||||
.headers(headers)
|
||||
.header(
|
||||
"User-Agent",
|
||||
codex_login::default_client::get_codex_user_agent(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.ok()?;
|
||||
if !response.status().is_success() {
|
||||
return None;
|
||||
}
|
||||
let notice = response.json::<Response>().await.ok()?.notice?;
|
||||
let current = self.auth_manager.auth().await?;
|
||||
if self
|
||||
.auth_manager
|
||||
.auth_change_state_for(&auth)?
|
||||
.source_generation
|
||||
!= source_generation
|
||||
|| current.auth_mode() != codex_protocol::auth::AuthMode::Chatgpt
|
||||
|| current.get_account_id().as_ref() != Some(&account_id)
|
||||
|| current.get_chatgpt_user_id().as_ref() != Some(&user_id)
|
||||
|| current.is_fedramp_account()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(AccountSecuritySetupNotice {
|
||||
account_id,
|
||||
user_id,
|
||||
title: notice.title,
|
||||
description: notice.description,
|
||||
action: notice.action,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
GetAccountSecuritySetupResponse { notice }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,641 @@
|
||||
//! Discovers routing for the selected ChatGPT workspace without crossing auth owners.
|
||||
//! Discovery is coordinated per routing key; a cache miss never proves independence.
|
||||
//! Credential refreshes invalidate the cache, but do not cancel same-owner discovery.
|
||||
//! Model sessions retain their original bootstrap scope across configuration changes.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::AccountRoutingOverride;
|
||||
use codex_backend_client::AccountEntry;
|
||||
use codex_config::ConfigLoadError;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use codex_login::RefreshTokenError;
|
||||
use codex_login::WorkspaceRouting;
|
||||
use codex_login::WorkspaceRoutingRequest;
|
||||
use codex_login::WorkspaceRoutingResolver;
|
||||
use codex_login::auth::RefreshTokenFailedError;
|
||||
use codex_model_provider::ProviderAccount;
|
||||
use codex_model_provider::ProviderAccountError;
|
||||
use codex_model_provider::ProviderAccountState;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Weak;
|
||||
use tokio::sync::Semaphore;
|
||||
use url::Url;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub(super) struct WorkspaceRoutingKey {
|
||||
auth_generation: u64,
|
||||
chatgpt_account_id: String,
|
||||
effective_chatgpt_base_url: String,
|
||||
required_chatgpt_base_url: Option<String>,
|
||||
}
|
||||
|
||||
// Results live through same-key waiters, even if another key replaces the cache.
|
||||
// Weak entries are pruned on the next read after those requests finish.
|
||||
pub(super) type WorkspaceRoutingFetches = HashMap<WorkspaceRoutingKey, Weak<WorkspaceRoutingFetch>>;
|
||||
|
||||
pub(super) struct WorkspaceRoutingFetch {
|
||||
discovery: Semaphore,
|
||||
routing: Mutex<Option<CachedWorkspaceRouting>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct CachedWorkspaceRouting {
|
||||
key: WorkspaceRoutingKey,
|
||||
routing: WorkspaceRouting,
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) struct AccountRead {
|
||||
account_state: ProviderAccountState,
|
||||
user_id: Option<String>,
|
||||
pub(super) workspace_routing: Option<WorkspaceRouting>,
|
||||
workspace_name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub(super) enum AccountReadError {
|
||||
#[error(transparent)]
|
||||
InvalidAccount(#[from] ProviderAccountError),
|
||||
#[error(transparent)]
|
||||
Routing(#[from] WorkspaceRoutingError),
|
||||
}
|
||||
|
||||
/// Routing failures carry no account, URL, or backend data. Config failures retain
|
||||
/// only a location or structured error category, never the raw config error.
|
||||
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub(super) enum WorkspaceRoutingError {
|
||||
#[error("failed to load workspace requirements: {0}")]
|
||||
RequirementsLoad(String),
|
||||
#[error("workspace routing requires a ChatGPT account id")]
|
||||
MissingAccountId,
|
||||
#[error("workspace routing discovery cancelled")]
|
||||
DiscoveryCancelled,
|
||||
#[error("account changed during workspace routing discovery")]
|
||||
AccountChanged,
|
||||
#[error("workspace routing discovery unauthorized (401)")]
|
||||
DiscoveryUnauthorized,
|
||||
#[error(transparent)]
|
||||
RefreshTokenRejected(RefreshTokenFailedError),
|
||||
#[error("workspace routing discovery failed")]
|
||||
DiscoveryFailed,
|
||||
#[error("selected workspace missing from routing discovery")]
|
||||
MissingWorkspace,
|
||||
#[error("duplicate workspace in routing discovery")]
|
||||
DuplicateWorkspace,
|
||||
#[error("failed to reload workspace requirements: {0}")]
|
||||
RequirementsReload(String),
|
||||
#[error("configuration changed during workspace routing discovery; retry account/read")]
|
||||
ConfigurationChanged,
|
||||
#[error("invalid model provider URL")]
|
||||
InvalidProviderUrl,
|
||||
#[error("invalid ChatGPT backend URL")]
|
||||
InvalidBootstrapUrl,
|
||||
#[error("invalid session ChatGPT backend URL")]
|
||||
InvalidSessionBootstrapUrl,
|
||||
#[error("ChatGPT backend changed; start a new thread before sending more content")]
|
||||
SessionBackendChanged,
|
||||
#[error("workspace routing discovery cancelled during shutdown")]
|
||||
Shutdown,
|
||||
#[error("workspace routing discovery timed out")]
|
||||
DiscoveryTimeout,
|
||||
#[error("workspace routing discovery missing backend origin")]
|
||||
MissingBackendOrigin,
|
||||
#[error("workspace routing discovery has invalid account routing override")]
|
||||
InvalidRoutingOverride,
|
||||
#[error("workspace routing discovery must return an origin")]
|
||||
BackendIsNotOrigin,
|
||||
#[error("required ChatGPT backend conflicts with workspace routing")]
|
||||
BackendConflict,
|
||||
#[error("invalid workspace backend URL")]
|
||||
InvalidBackendUrl,
|
||||
#[error("workspace backend must use an HTTPS origin without credentials")]
|
||||
InvalidBackendOrigin,
|
||||
}
|
||||
|
||||
fn workspace_config_load_reason(error: &io::Error) -> String {
|
||||
// Parser messages and cloud bundle errors can quote secrets, even without
|
||||
// their source snippets. Retain only structured diagnostics before these
|
||||
// errors reach JSON-RPC clients, login notifications, or tracing.
|
||||
let mut current = error
|
||||
.get_ref()
|
||||
.map(|source| source as &(dyn std::error::Error + 'static));
|
||||
while let Some(source) = current {
|
||||
if let Some(config) = source.downcast_ref::<ConfigLoadError>() {
|
||||
let config = config.config_error();
|
||||
let start = config.range.start;
|
||||
// Non-file diagnostics store a display name, which can contain
|
||||
// backend-supplied policy names and IDs, in this field.
|
||||
if !config.path.is_absolute() {
|
||||
return format!(
|
||||
"invalid non-file configuration at line {}, column {}",
|
||||
start.line, start.column
|
||||
);
|
||||
}
|
||||
return format!(
|
||||
"invalid configuration at {}:{}:{}",
|
||||
config.path.display(),
|
||||
start.line,
|
||||
start.column
|
||||
);
|
||||
}
|
||||
if let Some(cloud) = source.downcast_ref::<CloudConfigBundleLoadError>() {
|
||||
let reason = match cloud.code() {
|
||||
CloudConfigBundleLoadErrorCode::Timeout => "request timed out",
|
||||
CloudConfigBundleLoadErrorCode::Auth
|
||||
| CloudConfigBundleLoadErrorCode::RequestFailed => {
|
||||
// Cloud loading currently erases the typed denial. Match
|
||||
// only known safe policy messages, never forward raw text.
|
||||
let message = cloud.to_string();
|
||||
if let Some(policy) = [
|
||||
NetworkPolicyDenied::Unavailable,
|
||||
NetworkPolicyDenied::Destination,
|
||||
NetworkPolicyDenied::Revoked,
|
||||
NetworkPolicyDenied::UnsupportedTransport,
|
||||
]
|
||||
.into_iter()
|
||||
.find(|policy| policy.to_string() == message)
|
||||
{
|
||||
return policy.to_string();
|
||||
}
|
||||
if cloud.code() == CloudConfigBundleLoadErrorCode::Auth {
|
||||
"authentication failed"
|
||||
} else {
|
||||
"request failed"
|
||||
}
|
||||
}
|
||||
CloudConfigBundleLoadErrorCode::InvalidBundle => "invalid bundle",
|
||||
CloudConfigBundleLoadErrorCode::Internal => "internal error",
|
||||
};
|
||||
return match cloud.status_code() {
|
||||
Some(status) => format!("cloud config: {reason} (HTTP {status})"),
|
||||
None => format!("cloud config: {reason}"),
|
||||
};
|
||||
}
|
||||
if let Some(policy) = source.downcast_ref::<NetworkPolicyDenied>() {
|
||||
return policy.to_string();
|
||||
}
|
||||
current = source.source();
|
||||
}
|
||||
// Use the OS error or kind, never an untyped error's potentially secret message.
|
||||
match error.raw_os_error() {
|
||||
Some(code) => io::Error::from_raw_os_error(code).to_string(),
|
||||
None => error.kind().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
impl WorkspaceRoutingResolver for AccountRequestProcessor {
|
||||
fn resolve(
|
||||
&self,
|
||||
request: WorkspaceRoutingRequest,
|
||||
) -> Pin<Box<dyn Future<Output = io::Result<Option<WorkspaceRouting>>> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
self.read_account(Some(&request))
|
||||
.await
|
||||
.map(|account| account.workspace_routing)
|
||||
.map_err(|error| match error {
|
||||
AccountReadError::InvalidAccount(error) => io::Error::other(error),
|
||||
AccountReadError::Routing(WorkspaceRoutingError::RefreshTokenRejected(
|
||||
error,
|
||||
)) => io::Error::new(io::ErrorKind::PermissionDenied, error),
|
||||
AccountReadError::Routing(error) => io::Error::new(
|
||||
if error == WorkspaceRoutingError::DiscoveryUnauthorized {
|
||||
io::ErrorKind::PermissionDenied
|
||||
} else {
|
||||
io::ErrorKind::Other
|
||||
},
|
||||
error,
|
||||
),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(super) async fn read_account_for_background_workspace_routing(
|
||||
&self,
|
||||
) -> Result<Option<AccountRead>, AccountReadError> {
|
||||
if !self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.as_ref()
|
||||
.is_some_and(CodexAuth::is_chatgpt_auth)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
self.read_account(/*request*/ None).await.map(Some)
|
||||
}
|
||||
|
||||
pub(crate) fn notify_workspace_routing_to_connection(&self, connection_id: ConnectionId) {
|
||||
let processor = self.clone();
|
||||
let auth_changes = self.auth_manager.auth_change_state_receiver();
|
||||
let owner_generation = auth_changes.borrow().owner_generation;
|
||||
tokio::spawn(async move {
|
||||
if auth_changes.borrow().owner_generation != owner_generation {
|
||||
return;
|
||||
}
|
||||
if let Ok(Some(response)) = processor
|
||||
.read_account_for_background_workspace_routing()
|
||||
.await
|
||||
&& response.workspace_routing.is_some()
|
||||
&& auth_changes.borrow().owner_generation == owner_generation
|
||||
{
|
||||
let notification = processor.current_account_updated_notification();
|
||||
processor
|
||||
.outgoing
|
||||
.send_account_notification(
|
||||
Some(connection_id),
|
||||
&auth_changes,
|
||||
owner_generation,
|
||||
AccountNotification::Updated(notification),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) async fn get_account(
|
||||
&self,
|
||||
params: GetAccountParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.refresh_token_if_requested(params.refresh_token).await;
|
||||
let read = self
|
||||
.read_account(/*request*/ None)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
AccountReadError::InvalidAccount(error) => invalid_request(error.to_string()),
|
||||
AccountReadError::Routing(error) => internal_error(error.to_string()),
|
||||
})?;
|
||||
let mut account = read.account_state.account.map(Account::from);
|
||||
if let Some(Account::Chatgpt { workspace_name, .. }) = &mut account {
|
||||
*workspace_name = read.workspace_name;
|
||||
}
|
||||
Ok(Some(
|
||||
GetAccountResponse {
|
||||
account,
|
||||
user_id: read.user_id,
|
||||
requires_openai_auth: read.account_state.requires_openai_auth,
|
||||
workspace_routing: read.workspace_routing.map(|routing| {
|
||||
codex_app_server_protocol::WorkspaceRouting {
|
||||
chatgpt_account_id: routing.chatgpt_account_id,
|
||||
backend_origin: routing.backend_origin,
|
||||
account_routing_override: match routing.account_routing_override.as_str() {
|
||||
"NO_CONSTRAINT" => AccountRoutingOverride::NoConstraint,
|
||||
"us" => AccountRoutingOverride::Us,
|
||||
"us_cr" => AccountRoutingOverride::UsCr,
|
||||
_ => unreachable!("routing discovery validates the override"),
|
||||
},
|
||||
}
|
||||
}),
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn read_account(
|
||||
&self,
|
||||
request: Option<&WorkspaceRoutingRequest>,
|
||||
) -> Result<AccountRead, AccountReadError> {
|
||||
let mut auth_changes = self.auth_manager.auth_change_state_receiver();
|
||||
let auth_state = *auth_changes.borrow_and_update();
|
||||
let current_auth_changes = auth_changes.clone();
|
||||
let read = Box::pin(async {
|
||||
let load_config = async || {
|
||||
match request.and_then(|request| request.session.as_deref()) {
|
||||
Some(session) => {
|
||||
self.config_manager
|
||||
.load_retained_session_config(&session.config_layer_stack, &session.cwd)
|
||||
.await
|
||||
}
|
||||
None => {
|
||||
self.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
}
|
||||
}
|
||||
};
|
||||
let config = match load_config().await {
|
||||
Ok(config) => config,
|
||||
Err(_)
|
||||
if !self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.as_ref()
|
||||
.is_some_and(CodexAuth::is_chatgpt_auth) =>
|
||||
{
|
||||
self.config.as_ref().clone()
|
||||
}
|
||||
Err(error) => {
|
||||
return Err(WorkspaceRoutingError::RequirementsLoad(
|
||||
workspace_config_load_reason(&error),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
};
|
||||
let auth = self.auth_manager.auth_cached();
|
||||
let provider = create_model_provider(
|
||||
config.model_provider.clone(),
|
||||
Some(self.auth_manager.clone()),
|
||||
);
|
||||
let account_state = provider
|
||||
.account_state()
|
||||
.map_err(AccountReadError::InvalidAccount)?;
|
||||
let user_id = auth
|
||||
.as_ref()
|
||||
.filter(|_| {
|
||||
matches!(
|
||||
&account_state.account,
|
||||
Some(ProviderAccount::Chatgpt { .. })
|
||||
)
|
||||
})
|
||||
.and_then(CodexAuth::get_chatgpt_user_id);
|
||||
let mut workspace_routing = if let Some((auth, account_id)) = auth
|
||||
.as_ref()
|
||||
.filter(|auth| {
|
||||
auth.is_chatgpt_auth()
|
||||
&& (request.is_some()
|
||||
|| matches!(
|
||||
account_state.account,
|
||||
Some(ProviderAccount::Chatgpt { .. })
|
||||
))
|
||||
})
|
||||
.and_then(|auth| auth.get_account_id().map(|account_id| (auth, account_id)))
|
||||
{
|
||||
if account_id.is_empty() {
|
||||
return Err(WorkspaceRoutingError::MissingAccountId.into());
|
||||
}
|
||||
let required_chatgpt_base_url = config
|
||||
.config_layer_stack
|
||||
.requirements_toml()
|
||||
.chatgpt_base_url
|
||||
.clone();
|
||||
let key = WorkspaceRoutingKey {
|
||||
auth_generation: auth_state.generation,
|
||||
chatgpt_account_id: account_id.clone(),
|
||||
effective_chatgpt_base_url: config.chatgpt_base_url.clone(),
|
||||
required_chatgpt_base_url: required_chatgpt_base_url.clone(),
|
||||
};
|
||||
let fetch = {
|
||||
let mut fetches = self.workspace_routing_fetches.lock().await;
|
||||
fetches.retain(|_, fetch| fetch.strong_count() > 0);
|
||||
if let Some(fetch) = fetches.get(&key).and_then(Weak::upgrade) {
|
||||
fetch
|
||||
} else {
|
||||
let fetch = Arc::new(WorkspaceRoutingFetch {
|
||||
discovery: Semaphore::new(/*permits*/ 1),
|
||||
routing: Mutex::new(/*t*/ None),
|
||||
});
|
||||
fetches.insert(key.clone(), Arc::downgrade(&fetch));
|
||||
fetch
|
||||
}
|
||||
};
|
||||
let _permit = fetch
|
||||
.discovery
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|_| WorkspaceRoutingError::DiscoveryCancelled)?;
|
||||
let fetched = fetch.routing.lock().await.clone();
|
||||
let cached = match fetched {
|
||||
Some(routing) => Some(routing),
|
||||
None => self
|
||||
.workspace_routing
|
||||
.lock()
|
||||
.await
|
||||
.as_ref()
|
||||
.filter(|cached| cached.key == key)
|
||||
.cloned(),
|
||||
};
|
||||
let routing = if let Some(cached) = cached {
|
||||
cached
|
||||
} else {
|
||||
let runtime = self
|
||||
.thread_manager
|
||||
.runtime_auth_for_config(&config)
|
||||
.map_err(|_| WorkspaceRoutingError::DiscoveryFailed)?;
|
||||
let mut recovery = self.auth_manager.unauthorized_recovery();
|
||||
let mut discovery_auth = auth.clone();
|
||||
let mut discovery_generation = auth_state.generation;
|
||||
let response = loop {
|
||||
let client = BackendClient::from_auth_with_runtime(
|
||||
&config.chatgpt_base_url,
|
||||
&discovery_auth,
|
||||
config.http_client_factory(),
|
||||
runtime.as_ref(),
|
||||
/*headers*/ &Default::default(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| WorkspaceRoutingError::DiscoveryFailed)?;
|
||||
match client.get_accounts_check().await {
|
||||
Ok(response) => break response,
|
||||
Err(error) => {
|
||||
let unauthorized = error.is_unauthorized();
|
||||
if unauthorized && recovery.has_next() {
|
||||
let result = recovery.next().await;
|
||||
let refreshed = *current_auth_changes.borrow();
|
||||
if refreshed.owner_generation != auth_state.owner_generation {
|
||||
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
if let Err(error) = result
|
||||
&& refreshed.generation == discovery_generation
|
||||
{
|
||||
let cached_failure = self
|
||||
.auth_manager
|
||||
.refresh_failure_for_auth(&discovery_auth);
|
||||
if let RefreshTokenError::Permanent(failed) = error
|
||||
&& !self.auth_manager.has_external_auth()
|
||||
&& cached_failure.as_ref() == Some(&failed)
|
||||
{
|
||||
return Err(
|
||||
WorkspaceRoutingError::RefreshTokenRejected(failed)
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
return Err(
|
||||
WorkspaceRoutingError::DiscoveryUnauthorized.into()
|
||||
);
|
||||
}
|
||||
discovery_generation = refreshed.generation;
|
||||
discovery_auth = self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.ok_or(WorkspaceRoutingError::AccountChanged)?;
|
||||
continue;
|
||||
}
|
||||
return Err(if unauthorized {
|
||||
WorkspaceRoutingError::DiscoveryUnauthorized
|
||||
} else {
|
||||
WorkspaceRoutingError::DiscoveryFailed
|
||||
}
|
||||
.into());
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut accounts = response
|
||||
.accounts
|
||||
.into_iter()
|
||||
.filter(|account| account.id == account_id);
|
||||
let mut entry = accounts
|
||||
.next()
|
||||
.ok_or(WorkspaceRoutingError::MissingWorkspace)?;
|
||||
if accounts.next().is_some() {
|
||||
return Err(WorkspaceRoutingError::DuplicateWorkspace.into());
|
||||
}
|
||||
let latest_config = load_config().await.map_err(|error| {
|
||||
WorkspaceRoutingError::RequirementsReload(workspace_config_load_reason(
|
||||
&error,
|
||||
))
|
||||
})?;
|
||||
if latest_config.chatgpt_base_url != config.chatgpt_base_url
|
||||
|| latest_config.model_provider != config.model_provider
|
||||
|| latest_config
|
||||
.config_layer_stack
|
||||
.requirements_toml()
|
||||
.chatgpt_base_url
|
||||
!= required_chatgpt_base_url
|
||||
{
|
||||
return Err(WorkspaceRoutingError::ConfigurationChanged.into());
|
||||
}
|
||||
let name = entry.name.take();
|
||||
let routing = resolve_routing(
|
||||
entry,
|
||||
required_chatgpt_base_url.as_deref(),
|
||||
&config.chatgpt_base_url,
|
||||
)?;
|
||||
let mut cached = self.workspace_routing.lock().await;
|
||||
if current_auth_changes.borrow().owner_generation != auth_state.owner_generation
|
||||
{
|
||||
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
let routing = CachedWorkspaceRouting {
|
||||
key: WorkspaceRoutingKey {
|
||||
auth_generation: discovery_generation,
|
||||
..key
|
||||
},
|
||||
routing,
|
||||
name,
|
||||
};
|
||||
// Same-owner refresh can complete a newer discovery first.
|
||||
if current_auth_changes.borrow().generation == discovery_generation {
|
||||
*cached = Some(routing.clone());
|
||||
}
|
||||
routing
|
||||
};
|
||||
*fetch.routing.lock().await = Some(routing.clone());
|
||||
Some(routing)
|
||||
} else {
|
||||
*self.workspace_routing.lock().await = None;
|
||||
None
|
||||
};
|
||||
if let Some(request) = request.filter(|_| workspace_routing.is_some()) {
|
||||
let origin = Url::parse(&request.provider_base_url)
|
||||
.map_err(|_| WorkspaceRoutingError::InvalidProviderUrl)?
|
||||
.origin();
|
||||
let bootstrap_origin = Url::parse(&config.chatgpt_base_url)
|
||||
.map_err(|_| WorkspaceRoutingError::InvalidBootstrapUrl)?
|
||||
.origin();
|
||||
let session_bootstrap_origin = Url::parse(&request.chatgpt_base_url)
|
||||
.map_err(|_| WorkspaceRoutingError::InvalidSessionBootstrapUrl)?
|
||||
.origin();
|
||||
let selected_backend = workspace_routing.as_ref().is_some_and(|routing| {
|
||||
routing.routing.backend_origin == origin.ascii_serialization()
|
||||
});
|
||||
let workspace_bound = request.previously_routed
|
||||
|| request.provider_base_url == codex_model_provider::CHATGPT_CODEX_BASE_URL
|
||||
|| origin == session_bootstrap_origin
|
||||
|| (session_bootstrap_origin == bootstrap_origin && selected_backend);
|
||||
if !workspace_bound {
|
||||
workspace_routing = None;
|
||||
} else if session_bootstrap_origin != bootstrap_origin {
|
||||
return Err(WorkspaceRoutingError::SessionBackendChanged.into());
|
||||
}
|
||||
}
|
||||
let (workspace_routing, workspace_name) = workspace_routing
|
||||
.map(|workspace| (Some(workspace.routing), workspace.name))
|
||||
.unwrap_or_default();
|
||||
Ok(AccountRead {
|
||||
account_state,
|
||||
user_id,
|
||||
workspace_routing,
|
||||
workspace_name,
|
||||
})
|
||||
});
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = self.workspace_routing_shutdown.cancelled() => {
|
||||
return Err(WorkspaceRoutingError::Shutdown.into());
|
||||
}
|
||||
_ = auth_changes.wait_for(|state| state.owner_generation != auth_state.owner_generation) => {
|
||||
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
result = tokio::time::timeout(Duration::from_secs(/*secs*/ 15), read) => {
|
||||
result.map_err(|_| WorkspaceRoutingError::DiscoveryTimeout)?
|
||||
}
|
||||
};
|
||||
if auth_changes.borrow().owner_generation != auth_state.owner_generation {
|
||||
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_routing(
|
||||
entry: AccountEntry,
|
||||
required_chatgpt_base_url: Option<&str>,
|
||||
effective_base_url: &str,
|
||||
) -> Result<WorkspaceRouting, AccountReadError> {
|
||||
let backend = entry
|
||||
.workspace_backend_origin
|
||||
.ok_or(WorkspaceRoutingError::MissingBackendOrigin)?;
|
||||
let account_routing_override = match entry.account_routing_override.as_deref() {
|
||||
Some(value @ ("NO_CONSTRAINT" | "us" | "us_cr")) => value.to_owned(),
|
||||
_ => {
|
||||
return Err(WorkspaceRoutingError::InvalidRoutingOverride.into());
|
||||
}
|
||||
};
|
||||
let required = required_chatgpt_base_url
|
||||
.map(parse_backend_url)
|
||||
.transpose()?;
|
||||
let discovered = if backend == "NO_CONSTRAINT" {
|
||||
None
|
||||
} else {
|
||||
let url = parse_backend_url(&backend)?;
|
||||
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
|
||||
return Err(WorkspaceRoutingError::BackendIsNotOrigin.into());
|
||||
}
|
||||
Some(url)
|
||||
};
|
||||
let origin = match (required, discovered) {
|
||||
(Some(required), Some(discovered)) => {
|
||||
if required.origin() != discovered.origin() {
|
||||
return Err(WorkspaceRoutingError::BackendConflict.into());
|
||||
}
|
||||
required.origin()
|
||||
}
|
||||
(Some(url), None) | (None, Some(url)) => url.origin(),
|
||||
(None, None) => parse_backend_url(effective_base_url)?.origin(),
|
||||
};
|
||||
Ok(WorkspaceRouting {
|
||||
chatgpt_account_id: entry.id,
|
||||
backend_origin: origin.ascii_serialization(),
|
||||
account_routing_override,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_backend_url(value: &str) -> Result<Url, AccountReadError> {
|
||||
let url = Url::parse(value).map_err(|_| WorkspaceRoutingError::InvalidBackendUrl)?;
|
||||
if url.scheme() != "https"
|
||||
|| url.host_str().is_none()
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
|| value.trim() != value
|
||||
{
|
||||
return Err(WorkspaceRoutingError::InvalidBackendOrigin.into());
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "workspace_routing_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Origin resolution, strict discovery validation, and background read eligibility.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use test_case::test_case;
|
||||
|
||||
#[test_case(CloudConfigBundleLoadErrorCode::RequestFailed, "cloud config: request failed"; "request")]
|
||||
#[test_case(CloudConfigBundleLoadErrorCode::Auth, "cloud config: authentication failed"; "refresh")]
|
||||
fn cloud_failures_preserve_policy_denials_but_redact_other_messages(
|
||||
code: CloudConfigBundleLoadErrorCode,
|
||||
redacted: &str,
|
||||
) {
|
||||
let denied = NetworkPolicyDenied::Destination.to_string();
|
||||
for (message, expected) in [
|
||||
(denied.clone(), denied),
|
||||
(
|
||||
"destination denied by application network policy: sk-test-private-value".into(),
|
||||
redacted.into(),
|
||||
),
|
||||
] {
|
||||
let error = io::Error::other(CloudConfigBundleLoadError::new(
|
||||
code, /*status_code*/ None, message,
|
||||
));
|
||||
assert_eq!(workspace_config_load_reason(&error), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test_case(None; "signed_out")]
|
||||
#[test_case(Some("dummy"); "api_key")]
|
||||
#[tokio::test]
|
||||
async fn background_routing_skips_config_until_chatgpt_sign_in(
|
||||
api_key: Option<&str>,
|
||||
) -> anyhow::Result<()> {
|
||||
use app_test_support::ChatGptAuthFixture;
|
||||
use app_test_support::write_chatgpt_auth;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let backend = wiremock::MockServer::start().await;
|
||||
app_test_support::mount_workspace_routing(&backend).await;
|
||||
let loads = Arc::new(AtomicUsize::new(/*v*/ 0));
|
||||
let calls = Arc::clone(&loads);
|
||||
let loader = CloudConfigBundleLoader::from_getter(move || {
|
||||
calls.fetch_add(/*val*/ 1, Ordering::SeqCst);
|
||||
async { Ok(None) }
|
||||
});
|
||||
let manager = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
vec![(
|
||||
"chatgpt_base_url".into(),
|
||||
format!("{}/backend-api", backend.uri()).into(),
|
||||
)],
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
loader,
|
||||
);
|
||||
let config = Arc::new(
|
||||
manager
|
||||
.load_latest_config(Some(home.path().to_path_buf()))
|
||||
.await?,
|
||||
);
|
||||
if let Some(api_key) = api_key {
|
||||
codex_login::login_with_api_key(
|
||||
home.path(),
|
||||
api_key,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)?;
|
||||
}
|
||||
let auth_manager = Arc::new(
|
||||
AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
Some(config.chatgpt_base_url.clone()),
|
||||
AuthKeyringBackendKind::default(),
|
||||
config.auth_config().auth_route_config,
|
||||
)
|
||||
.await,
|
||||
);
|
||||
let threads = Arc::new(
|
||||
codex_core::test_support::thread_manager_with_models_provider_and_home(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
config.model_provider.clone(),
|
||||
config.codex_home.to_path_buf(),
|
||||
Arc::new(EnvironmentManager::default_for_tests()),
|
||||
),
|
||||
);
|
||||
let (sender, _receiver) = tokio::sync::mpsc::channel(16);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
sender,
|
||||
codex_analytics::AnalyticsEventsClient::disabled(),
|
||||
));
|
||||
let model_catalog = Arc::new(crate::model_catalog::ModelCatalog::new(
|
||||
manager.clone(),
|
||||
Some(config.cwd.to_path_buf()),
|
||||
Arc::clone(&config),
|
||||
Arc::clone(&threads),
|
||||
));
|
||||
let processor = AccountRequestProcessor::new(
|
||||
Arc::clone(&auth_manager),
|
||||
threads,
|
||||
outgoing,
|
||||
config,
|
||||
manager,
|
||||
model_catalog,
|
||||
);
|
||||
let initial_loads = loads.load(Ordering::SeqCst);
|
||||
for _ in 0..3 {
|
||||
assert!(
|
||||
processor
|
||||
.read_account_for_background_workspace_routing()
|
||||
.await?
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
assert_eq!(loads.load(Ordering::SeqCst), initial_loads);
|
||||
|
||||
processor.read_account(/*request*/ None).await?;
|
||||
assert!(loads.load(Ordering::SeqCst) > initial_loads);
|
||||
|
||||
write_chatgpt_auth(
|
||||
home.path(),
|
||||
ChatGptAuthFixture::new("access-chatgpt").account_id("account-123"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
assert!(auth_manager.reload().await);
|
||||
let initial_loads = loads.load(Ordering::SeqCst);
|
||||
let read = processor
|
||||
.read_account_for_background_workspace_routing()
|
||||
.await?
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
read.workspace_routing,
|
||||
Some(WorkspaceRouting {
|
||||
chatgpt_account_id: "account-123".into(),
|
||||
backend_origin: "https://chatgpt.com".into(),
|
||||
account_routing_override: "NO_CONSTRAINT".into(),
|
||||
})
|
||||
);
|
||||
assert!(loads.load(Ordering::SeqCst) > initial_loads);
|
||||
|
||||
let config_path = home.path().join("config.toml");
|
||||
std::fs::write(&config_path, "invalid = [ 'sk-test-private-value',")?;
|
||||
let Err(error) = processor
|
||||
.read_account_for_background_workspace_routing()
|
||||
.await
|
||||
else {
|
||||
panic!("invalid config must prevent workspace routing");
|
||||
};
|
||||
let message = error.to_string();
|
||||
assert!(
|
||||
message.starts_with(&format!(
|
||||
"failed to load workspace requirements: invalid configuration at {}:1:",
|
||||
config_path.display(),
|
||||
)),
|
||||
"{message}"
|
||||
);
|
||||
assert!(!message.contains("sk-test-private-value"), "{message}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case(Some("https://gov.chatgpt.com/backend-api/"), "NO_CONSTRAINT", "https://gov.chatgpt.com"; "configured_only")]
|
||||
#[test_case(None, "https://gov.chatgpt.com", "https://gov.chatgpt.com"; "discovered_only")]
|
||||
#[test_case(Some("https://GOV.chatgpt.com:443/backend-api/"), "https://gov.chatgpt.com", "https://gov.chatgpt.com"; "matching_effective_port")]
|
||||
#[test_case(Some("https://example.com:8443/backend-api/"), "https://example.com:8443", "https://example.com:8443"; "custom_port")]
|
||||
#[test_case(None, "NO_CONSTRAINT", "https://chatgpt.com"; "existing_default")]
|
||||
fn resolves_origins(required: Option<&str>, discovered: &str, expected: &str) {
|
||||
let entry = serde_json::from_value(serde_json::json!({
|
||||
"id": "workspace", "workspace_backend_origin": discovered,
|
||||
"account_routing_override": "NO_CONSTRAINT",
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
resolve_routing(entry, required, "https://chatgpt.com/backend-api/").unwrap(),
|
||||
WorkspaceRouting {
|
||||
chatgpt_account_id: "workspace".into(),
|
||||
backend_origin: expected.into(),
|
||||
account_routing_override: "NO_CONSTRAINT".into(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test_case("https://other.example/backend-api/", "https://gov.chatgpt.com"; "host_conflict")]
|
||||
#[test_case("http://gov.chatgpt.com/backend-api/", "https://gov.chatgpt.com"; "scheme_conflict")]
|
||||
#[test_case("https://gov.chatgpt.com:444/backend-api/", "https://gov.chatgpt.com"; "port_conflict")]
|
||||
fn rejects_conflicting_origins(required: &str, discovered: &str) {
|
||||
let entry = serde_json::from_value(serde_json::json!({
|
||||
"id": "workspace", "workspace_backend_origin": discovered,
|
||||
"account_routing_override": "us_cr",
|
||||
}))
|
||||
.unwrap();
|
||||
assert!(resolve_routing(entry, Some(required), "https://chatgpt.com").is_err());
|
||||
}
|
||||
|
||||
#[test_case(serde_json::json!(null), serde_json::json!("us_cr"), WorkspaceRoutingError::MissingBackendOrigin; "null_origin")]
|
||||
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(null), WorkspaceRoutingError::InvalidRoutingOverride; "null_routing")]
|
||||
#[test_case(serde_json::json!(""), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendUrl; "empty_origin")]
|
||||
#[test_case(serde_json::json!("https://example.com/backend-api/"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_path")]
|
||||
#[test_case(serde_json::json!("https://example.com?query"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_query")]
|
||||
#[test_case(serde_json::json!("https://example.com#fragment"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_fragment")]
|
||||
#[test_case(serde_json::json!("https://user:pass@example.com"), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendOrigin; "credentials")]
|
||||
#[test_case(serde_json::json!("http://example.com"), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendOrigin; "insecure_origin")]
|
||||
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!("unknown"), WorkspaceRoutingError::InvalidRoutingOverride; "unknown_routing")]
|
||||
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(""), WorkspaceRoutingError::InvalidRoutingOverride; "empty_routing")]
|
||||
fn rejects_invalid_discovery(backend: Value, routing: Value, expected: WorkspaceRoutingError) {
|
||||
let entry = serde_json::from_value(serde_json::json!({
|
||||
"id": "workspace", "workspace_backend_origin": backend, "account_routing_override": routing,
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
resolve_routing(
|
||||
entry,
|
||||
/*required_chatgpt_base_url*/ None,
|
||||
"https://chatgpt.com"
|
||||
),
|
||||
Err(AccountReadError::Routing(expected))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrestricted_discovery_uses_effective_custom_backend() {
|
||||
let entry = serde_json::from_value(serde_json::json!({
|
||||
"id": "workspace", "workspace_backend_origin": "NO_CONSTRAINT", "account_routing_override": "us",
|
||||
})).unwrap();
|
||||
assert_eq!(
|
||||
resolve_routing(
|
||||
entry,
|
||||
/*required_chatgpt_base_url*/ None,
|
||||
"https://custom.example:8443/backend-api/"
|
||||
)
|
||||
.unwrap(),
|
||||
WorkspaceRouting {
|
||||
chatgpt_account_id: "workspace".into(),
|
||||
backend_origin: "https://custom.example:8443".into(),
|
||||
account_routing_override: "us".into(),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//! Lists the active managed login and switches its workspace through the account-session API.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::AccountSession;
|
||||
use codex_app_server_protocol::AccountSessionWorkspace;
|
||||
use codex_app_server_protocol::AccountSessionWorkspaceKind;
|
||||
use codex_app_server_protocol::AccountSessionsListParams;
|
||||
use codex_app_server_protocol::AccountSessionsResponse;
|
||||
use codex_app_server_protocol::AccountSessionsSwitchParams;
|
||||
use codex_app_server_protocol::AccountSessionsSwitchResponse;
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) async fn list_account_sessions(
|
||||
&self,
|
||||
params: AccountSessionsListParams,
|
||||
) -> Result<AccountSessionsResponse, JSONRPCErrorError> {
|
||||
let auth = if params.refresh_workspace_metadata {
|
||||
self.auth_manager.auth().await
|
||||
} else {
|
||||
self.auth_manager.auth_cached()
|
||||
}
|
||||
.filter(|_| !self.auth_manager.has_external_auth());
|
||||
let session_id = auth
|
||||
.as_ref()
|
||||
.and_then(CodexAuth::managed_account_session_id);
|
||||
let (Some(auth), Some(session_id)) = (auth, session_id) else {
|
||||
return Ok(AccountSessionsResponse {
|
||||
active_session_id: None,
|
||||
sessions: vec![],
|
||||
});
|
||||
};
|
||||
let account_id = auth.get_account_id();
|
||||
let mut workspaces = account_id
|
||||
.iter()
|
||||
.map(|id| AccountSessionWorkspace {
|
||||
account_id: id.clone(),
|
||||
name: None,
|
||||
image_url: None,
|
||||
kind: None,
|
||||
})
|
||||
.collect();
|
||||
if params.refresh_workspace_metadata {
|
||||
let accounts = self.workspace_memberships(&auth).await?;
|
||||
workspaces = accounts
|
||||
.accounts
|
||||
.into_iter()
|
||||
.map(|account| AccountSessionWorkspace {
|
||||
account_id: account.id,
|
||||
name: account.name,
|
||||
image_url: account.profile_picture_url,
|
||||
kind: match account.structure.as_str() {
|
||||
"personal" => Some(AccountSessionWorkspaceKind::Personal),
|
||||
"workspace" => Some(AccountSessionWorkspaceKind::Workspace),
|
||||
_ => None,
|
||||
},
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
workspaces.sort_by_key(|workspace| {
|
||||
accounts
|
||||
.account_ordering
|
||||
.iter()
|
||||
.position(|id| id == &workspace.account_id)
|
||||
.unwrap_or(usize::MAX)
|
||||
});
|
||||
let current = self.auth_manager.auth_cached();
|
||||
if self.auth_manager.has_external_auth()
|
||||
|| current
|
||||
.as_ref()
|
||||
.and_then(CodexAuth::managed_account_session_id)
|
||||
.as_deref()
|
||||
!= Some(&session_id)
|
||||
|| current.and_then(|auth| auth.get_account_id()) != account_id
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Authentication changed while listing account sessions",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(AccountSessionsResponse {
|
||||
active_session_id: Some(session_id.clone()),
|
||||
sessions: vec![AccountSession {
|
||||
session_id,
|
||||
email: auth.get_account_email(),
|
||||
user_id: auth.get_chatgpt_user_id(),
|
||||
display_name: None,
|
||||
image_url: None,
|
||||
last_used_at: chrono::Utc::now().timestamp(),
|
||||
is_active: true,
|
||||
selected_workspace_account_id: account_id,
|
||||
workspaces,
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
async fn workspace_memberships(
|
||||
&self,
|
||||
auth: &CodexAuth,
|
||||
) -> Result<codex_backend_client::AccountsCheckResponse, JSONRPCErrorError> {
|
||||
let client = BackendClient::from_auth(
|
||||
self.config.chatgpt_base_url.clone(),
|
||||
auth,
|
||||
self.config.http_client_factory(),
|
||||
);
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 30),
|
||||
client.get_accounts_check(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| internal_error("Workspace metadata request timed out"))?
|
||||
.map_err(|_| internal_error("Failed to fetch workspace metadata"))
|
||||
}
|
||||
|
||||
pub(crate) async fn switch_account_session(
|
||||
&self,
|
||||
params: AccountSessionsSwitchParams,
|
||||
threads: &crate::request_processors::ThreadRequestProcessor,
|
||||
admission: &crate::turn_admission::TurnAdmission,
|
||||
) -> Result<AccountSessionsSwitchResponse, JSONRPCErrorError> {
|
||||
if self.active_login.lock().await.is_some() {
|
||||
return Err(invalid_request(
|
||||
"Finish or cancel the current login before switching workspaces",
|
||||
));
|
||||
}
|
||||
self.auth_manager
|
||||
.validate_workspace_switch(¶ms.session_id, ¶ms.account_id)
|
||||
.map_err(|error| invalid_request(error.to_string()))?;
|
||||
if self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.and_then(|auth| auth.get_account_id())
|
||||
.as_deref()
|
||||
== Some(¶ms.account_id)
|
||||
{
|
||||
return self.account_session_switch_response(¶ms).await;
|
||||
}
|
||||
let auth = self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.ok_or_else(|| invalid_request("Authentication is unavailable"))?;
|
||||
let memberships = self.workspace_memberships(&auth).await?;
|
||||
let mut matches = memberships
|
||||
.accounts
|
||||
.iter()
|
||||
.filter(|account| account.id == params.account_id);
|
||||
let Some(target) = matches.next() else {
|
||||
return Err(invalid_request("The selected workspace is unavailable"));
|
||||
};
|
||||
if matches.next().is_some() || target.is_deactivated {
|
||||
return Err(invalid_request("The selected workspace is unavailable"));
|
||||
}
|
||||
// The exchange strips the FedRAMP hint from the server session's token templates.
|
||||
if auth.is_fedramp_account()
|
||||
|| target.is_fedramp_compliant_workspace
|
||||
|| target.workspace_backend_origin.as_deref() == Some("https://gov.chatgpt.com")
|
||||
{
|
||||
return Err(invalid_request("Sign in to switch government workspaces"));
|
||||
}
|
||||
self.auth_manager
|
||||
.validate_workspace_switch(¶ms.session_id, ¶ms.account_id)
|
||||
.map_err(|error| invalid_request(error.to_string()))?;
|
||||
if target.can_access_with_session == Some(false) {
|
||||
if !params.allow_browser_login {
|
||||
return Err(invalid_request(
|
||||
"The selected workspace requires a new sign-in",
|
||||
));
|
||||
}
|
||||
let mut opts = self
|
||||
.login_chatgpt_common(
|
||||
/*codex_streamlined_login*/ true,
|
||||
LoginSuccessPage::default(),
|
||||
)
|
||||
.await?;
|
||||
opts.workspace_login = Some(
|
||||
auth.workspace_login(
|
||||
¶ms.session_id,
|
||||
params.account_id.clone(),
|
||||
target.sso_connection_name.clone(),
|
||||
)
|
||||
.map_err(|error| invalid_request(error.to_string()))?,
|
||||
);
|
||||
opts.forced_chatgpt_workspace_id = Some(vec![params.account_id]);
|
||||
let pause = admission.pause().await?;
|
||||
threads.unload_for_workspace_switch().await?;
|
||||
let (login_id, auth_url) = self.start_browser_login(opts, Some(pause)).await?;
|
||||
return Ok(AccountSessionsSwitchResponse::BrowserLogin { login_id, auth_url });
|
||||
}
|
||||
let _pause = admission.pause().await?;
|
||||
threads.unload_for_workspace_switch().await?;
|
||||
let switched = self
|
||||
.auth_manager
|
||||
.switch_workspace(¶ms.session_id, ¶ms.account_id)
|
||||
.await
|
||||
.map_err(|error| invalid_request(error.to_string()))?;
|
||||
let auth_changes = self.auth_manager.auth_change_state_receiver();
|
||||
let owner_generation = auth_changes.borrow().owner_generation;
|
||||
self.reload_workspace_config().await;
|
||||
// Routing includes fatal authorization and policy checks. Restore the
|
||||
// previous login on any failure, unless another auth operation replaced it.
|
||||
if let Err(error) = self.read_account(/*request*/ None).await {
|
||||
let rollback = self.auth_manager.rollback_workspace_switch(switched).await;
|
||||
self.reload_workspace_config().await;
|
||||
rollback.map_err(|rollback| internal_error(format!("Workspace validation failed: {error}; could not restore the previous workspace: {rollback}")))?;
|
||||
return Err(internal_error(format!(
|
||||
"Workspace validation failed: {error}"
|
||||
)));
|
||||
}
|
||||
self.thread_manager.invalidate_mcp_runtimes().await;
|
||||
self.model_catalog.invalidate().await;
|
||||
Self::maybe_refresh_plugin_caches_for_current_config(
|
||||
&self.config_manager,
|
||||
&self.thread_manager,
|
||||
self.auth_manager.auth_cached(),
|
||||
)
|
||||
.await;
|
||||
self.outgoing
|
||||
.send_account_notification(
|
||||
/*connection_id*/ None,
|
||||
&auth_changes,
|
||||
owner_generation,
|
||||
AccountNotification::Updated(self.current_account_updated_notification()),
|
||||
)
|
||||
.await;
|
||||
self.account_session_switch_response(¶ms).await
|
||||
}
|
||||
|
||||
async fn reload_workspace_config(&self) {
|
||||
self.config_manager
|
||||
.update_managed_config_loader(self.auth_manager.clone(), &self.config);
|
||||
self.config_manager
|
||||
.sync_default_client_residency_requirement()
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn account_session_switch_response(
|
||||
&self,
|
||||
params: &AccountSessionsSwitchParams,
|
||||
) -> Result<AccountSessionsSwitchResponse, JSONRPCErrorError> {
|
||||
let response = self
|
||||
.list_account_sessions(AccountSessionsListParams {
|
||||
refresh_workspace_metadata: false,
|
||||
})
|
||||
.await?;
|
||||
if response.active_session_id.as_deref() != Some(¶ms.session_id)
|
||||
|| !response.sessions.iter().any(|session| {
|
||||
session.session_id == params.session_id
|
||||
&& session.selected_workspace_account_id.as_deref() == Some(¶ms.account_id)
|
||||
})
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Authentication changed during workspace switching",
|
||||
));
|
||||
}
|
||||
Ok(AccountSessionsSwitchResponse::Switched { sessions: response })
|
||||
}
|
||||
}
|
||||
497
codex-rs/app-server/src/request_processors/apps_processor.rs
Normal file
497
codex-rs/app-server/src/request_processors/apps_processor.rs
Normal file
@@ -0,0 +1,497 @@
|
||||
use super::*;
|
||||
use crate::app_info::app_info_to_api;
|
||||
use codex_connectors::AppToolPolicyEvaluator;
|
||||
|
||||
mod installed;
|
||||
mod read;
|
||||
|
||||
pub(super) use read::APP_READ_MAX_IDS;
|
||||
|
||||
pub(crate) struct AppsRequestProcessor {
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
shutdown_token: CancellationToken,
|
||||
_shutdown_drop_guard: DropGuard,
|
||||
}
|
||||
|
||||
impl AppsRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
shutdown_token: CancellationToken,
|
||||
) -> Self {
|
||||
let shutdown_drop_guard = shutdown_token.clone().drop_guard();
|
||||
Self {
|
||||
thread_manager,
|
||||
outgoing,
|
||||
config_manager,
|
||||
shutdown_token,
|
||||
_shutdown_drop_guard: shutdown_drop_guard,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn apps_list(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: AppsListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.apps_list_inner(request_id, params)
|
||||
.await
|
||||
.map(|response| response.map(Into::into))
|
||||
}
|
||||
|
||||
async fn apps_list_inner(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: AppsListParams,
|
||||
) -> Result<Option<AppsListResponse>, JSONRPCErrorError> {
|
||||
let installed_start = Instant::now();
|
||||
let reload = params.force_refetch;
|
||||
let thread = if let Some(thread_id) = params.thread_id.as_deref() {
|
||||
let (_, loaded_thread) = self.load_thread(thread_id).await?;
|
||||
Some(loaded_thread)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let fallback_cwd = match thread.as_ref() {
|
||||
Some(thread) => Some(thread.config_snapshot().await.cwd().to_path_buf()),
|
||||
None => None,
|
||||
};
|
||||
let mut config = self.load_latest_config(fallback_cwd).await?;
|
||||
|
||||
if let Some(thread) = thread.as_ref() {
|
||||
let _ = config
|
||||
.features
|
||||
.set_enabled(Feature::Apps, thread.enabled(Feature::Apps));
|
||||
}
|
||||
|
||||
let mcp_manager = thread
|
||||
.as_ref()
|
||||
.map(|thread| thread.mcp_manager())
|
||||
.unwrap_or_else(|| self.thread_manager.mcp_manager());
|
||||
self.thread_manager
|
||||
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
let auth_manager = mcp_manager.auth_manager();
|
||||
if params.force_refetch && !auth_manager.has_external_auth() {
|
||||
auth_manager
|
||||
.reload_with_cached_auth()
|
||||
.await
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
}
|
||||
let auth = auth_manager.auth().await;
|
||||
if !config
|
||||
.features
|
||||
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend))
|
||||
{
|
||||
let response = AppsListResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
};
|
||||
record_legacy_apps_installed_duration(installed_start, reload);
|
||||
return Ok(Some(response));
|
||||
}
|
||||
|
||||
let request = request_id.clone();
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let environment_manager = self.thread_manager.environment_manager();
|
||||
let plugins_manager = mcp_manager.plugins_manager();
|
||||
let shutdown_token = self.shutdown_token.child_token();
|
||||
tokio::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = shutdown_token.cancelled() => {}
|
||||
_ = Self::apps_list_task(
|
||||
outgoing,
|
||||
request,
|
||||
params,
|
||||
config,
|
||||
environment_manager,
|
||||
mcp_manager,
|
||||
plugins_manager,
|
||||
installed_start,
|
||||
) => {}
|
||||
}
|
||||
});
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn shutdown(&self) {
|
||||
self.shutdown_token.cancel();
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn apps_list_task(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
request_id: ConnectionRequestId,
|
||||
params: AppsListParams,
|
||||
config: Config,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
mcp_manager: Arc<McpManager>,
|
||||
plugins_manager: Arc<PluginsManager>,
|
||||
installed_start: Instant,
|
||||
) {
|
||||
let reload = params.force_refetch;
|
||||
let retry_params = params.clone();
|
||||
let retry_config = config.clone();
|
||||
let retry_environment_manager = Arc::clone(&environment_manager);
|
||||
let retry_mcp_manager = Arc::clone(&mcp_manager);
|
||||
let retry_plugins_manager = Arc::clone(&plugins_manager);
|
||||
let result = Self::apps_list_response(
|
||||
&outgoing,
|
||||
params,
|
||||
config,
|
||||
environment_manager,
|
||||
mcp_manager,
|
||||
plugins_manager,
|
||||
)
|
||||
.await;
|
||||
if result.is_ok() {
|
||||
record_legacy_apps_installed_duration(installed_start, reload);
|
||||
}
|
||||
let should_retry = result
|
||||
.as_ref()
|
||||
.is_ok_and(|(_, codex_apps_ready)| !codex_apps_ready);
|
||||
outgoing
|
||||
.send_result(request_id, result.map(|(response, _)| response))
|
||||
.await;
|
||||
|
||||
if should_retry && !retry_params.force_refetch {
|
||||
let mut retry_params = retry_params;
|
||||
retry_params.force_refetch = true;
|
||||
if let Err(err) = Self::apps_list_response(
|
||||
&outgoing,
|
||||
retry_params,
|
||||
retry_config,
|
||||
retry_environment_manager,
|
||||
retry_mcp_manager,
|
||||
retry_plugins_manager,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("failed to refresh app list after codex-apps readiness retry: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn apps_list_response(
|
||||
outgoing: &Arc<OutgoingMessageSender>,
|
||||
params: AppsListParams,
|
||||
config: Config,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
mcp_manager: Arc<McpManager>,
|
||||
plugins_manager: Arc<PluginsManager>,
|
||||
) -> Result<(AppsListResponse, bool), JSONRPCErrorError> {
|
||||
let AppsListParams {
|
||||
cursor,
|
||||
limit,
|
||||
thread_id: _,
|
||||
force_refetch,
|
||||
} = params;
|
||||
let start = match cursor {
|
||||
Some(cursor) => match cursor.parse::<usize>() {
|
||||
Ok(idx) => idx,
|
||||
Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))),
|
||||
},
|
||||
None => 0,
|
||||
};
|
||||
|
||||
let loaded_plugins = plugins_manager
|
||||
.plugins_for_config(&config.plugins_config_input())
|
||||
.await;
|
||||
let connector_snapshot =
|
||||
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(
|
||||
loaded_plugins.capability_summaries(),
|
||||
);
|
||||
let plugin_apps = connector_snapshot.connector_ids().to_vec();
|
||||
let mut config = config;
|
||||
let auth = match mcp_manager
|
||||
.auth_manager()
|
||||
.auth_with_http_client_factory()
|
||||
.await
|
||||
{
|
||||
Some((auth, factory)) => {
|
||||
config.application_network_policy = factory.network_policy().clone();
|
||||
Some(auth)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let runtime = mcp_manager
|
||||
.runtime_auth_for_config(&config)
|
||||
.map(|(slot, mode)| {
|
||||
slot.get()
|
||||
.cloned()
|
||||
.map(|runtime| (runtime, mode))
|
||||
.ok_or_else(|| {
|
||||
internal_error("runtime authentication is not initialized".to_string())
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
let mut accessible_connectors =
|
||||
connectors::list_cached_accessible_connectors_from_mcp_tools(&config, auth.as_ref());
|
||||
let mut all_connectors =
|
||||
connectors::list_cached_all_connectors(&config, auth.as_ref(), &plugin_apps);
|
||||
let cached_all_connectors = all_connectors.clone();
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
|
||||
let accessible_config = config.clone();
|
||||
let accessible_tx = tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager(
|
||||
&accessible_config,
|
||||
force_refetch,
|
||||
Arc::clone(&environment_manager),
|
||||
mcp_manager,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| format!("failed to load accessible apps: {err}"));
|
||||
let _ = accessible_tx.send(AppListLoadResult::Accessible(result));
|
||||
});
|
||||
|
||||
let all_config = config.clone();
|
||||
let all_plugin_apps = plugin_apps.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = connectors::list_all_connectors_with_options(
|
||||
&all_config,
|
||||
auth.as_ref(),
|
||||
runtime.as_ref(),
|
||||
force_refetch,
|
||||
&all_plugin_apps,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| format!("failed to list apps: {err}"));
|
||||
let _ = tx.send(AppListLoadResult::Directory(result));
|
||||
});
|
||||
|
||||
let app_list_deadline = tokio::time::Instant::now() + APP_LIST_LOAD_TIMEOUT;
|
||||
let mut accessible_loaded = false;
|
||||
let mut all_loaded = false;
|
||||
let mut codex_apps_ready = true;
|
||||
let mut last_notified_apps = None;
|
||||
let mut sent_app_list_update = false;
|
||||
let app_policy = AppToolPolicyEvaluator::new(&config.config_layer_stack);
|
||||
|
||||
if accessible_connectors.is_some() || all_connectors.is_some() {
|
||||
let merged = app_policy.apply_app_enabled_state(merge_loaded_apps(
|
||||
all_connectors.as_deref(),
|
||||
accessible_connectors.as_deref(),
|
||||
));
|
||||
if !force_refetch {
|
||||
last_notified_apps = Some(merged);
|
||||
} else if should_send_app_list_updated_notification(
|
||||
merged.as_slice(),
|
||||
accessible_loaded,
|
||||
all_loaded,
|
||||
) {
|
||||
send_app_list_updated_notification(outgoing, merged.clone()).await;
|
||||
last_notified_apps = Some(merged);
|
||||
sent_app_list_update = true;
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
let result = match tokio::time::timeout_at(app_list_deadline, rx.recv()).await {
|
||||
Ok(Some(result)) => result,
|
||||
Ok(None) => {
|
||||
return Err(internal_error("failed to load app lists"));
|
||||
}
|
||||
Err(_) => {
|
||||
let timeout_seconds = APP_LIST_LOAD_TIMEOUT.as_secs();
|
||||
return Err(internal_error(format!(
|
||||
"timed out waiting for app lists after {timeout_seconds} seconds"
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
match result {
|
||||
AppListLoadResult::Accessible(Ok(status)) => {
|
||||
accessible_connectors = Some(status.connectors);
|
||||
accessible_loaded = true;
|
||||
codex_apps_ready = status.codex_apps_ready;
|
||||
}
|
||||
AppListLoadResult::Accessible(Err(err)) => {
|
||||
return Err(internal_error(err));
|
||||
}
|
||||
AppListLoadResult::Directory(Ok(connectors)) => {
|
||||
all_connectors = Some(connectors);
|
||||
all_loaded = true;
|
||||
}
|
||||
AppListLoadResult::Directory(Err(err)) => {
|
||||
return Err(internal_error(err));
|
||||
}
|
||||
}
|
||||
|
||||
let showing_interim_force_refetch = force_refetch && !(accessible_loaded && all_loaded);
|
||||
let all_connectors_for_update =
|
||||
if showing_interim_force_refetch && cached_all_connectors.is_some() {
|
||||
cached_all_connectors.as_deref()
|
||||
} else {
|
||||
all_connectors.as_deref()
|
||||
};
|
||||
let accessible_connectors_for_update =
|
||||
if showing_interim_force_refetch && !accessible_loaded {
|
||||
None
|
||||
} else {
|
||||
accessible_connectors.as_deref()
|
||||
};
|
||||
let merged = app_policy.apply_app_enabled_state(merge_loaded_apps(
|
||||
all_connectors_for_update,
|
||||
accessible_connectors_for_update,
|
||||
));
|
||||
if should_send_app_list_updated_notification(
|
||||
merged.as_slice(),
|
||||
accessible_loaded,
|
||||
all_loaded,
|
||||
) && (last_notified_apps.as_ref() != Some(&merged)
|
||||
|| (!force_refetch
|
||||
&& start == 0
|
||||
&& accessible_loaded
|
||||
&& all_loaded
|
||||
&& !sent_app_list_update))
|
||||
{
|
||||
send_app_list_updated_notification(outgoing, merged.clone()).await;
|
||||
last_notified_apps = Some(merged.clone());
|
||||
sent_app_list_update = true;
|
||||
}
|
||||
|
||||
if accessible_loaded && all_loaded {
|
||||
let response = paginate_apps(merged.as_slice(), start, limit)?;
|
||||
return Ok((response, codex_apps_ready));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_thread(
|
||||
&self,
|
||||
thread_id: &str,
|
||||
) -> Result<(ThreadId, Arc<CodexThread>), JSONRPCErrorError> {
|
||||
let thread_id = ThreadId::from_string(thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
|
||||
|
||||
let thread = self
|
||||
.thread_manager
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
|
||||
|
||||
Ok((thread_id, thread))
|
||||
}
|
||||
|
||||
async fn load_latest_config(
|
||||
&self,
|
||||
fallback_cwd: Option<PathBuf>,
|
||||
) -> Result<Config, JSONRPCErrorError> {
|
||||
self.config_manager
|
||||
.load_latest_config(fallback_cwd)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
|
||||
}
|
||||
|
||||
async fn load_apps_config(
|
||||
&self,
|
||||
thread_id: Option<&str>,
|
||||
) -> Result<(Config, Arc<McpManager>), JSONRPCErrorError> {
|
||||
let Some(thread_id) = thread_id else {
|
||||
let config = self.load_latest_config(/*fallback_cwd*/ None).await?;
|
||||
self.thread_manager
|
||||
.runtime_auth_for_config(&config)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
return Ok((config, self.thread_manager.mcp_manager()));
|
||||
};
|
||||
let (_, thread) = self.load_thread(thread_id).await?;
|
||||
let thread_config = thread.config().await;
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_latest_config_with_session_layers(
|
||||
&thread_config.config_layer_stack,
|
||||
&thread_config.cwd,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?;
|
||||
let mcp_manager = thread.mcp_manager();
|
||||
self.thread_manager
|
||||
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
Ok((config, mcp_manager))
|
||||
}
|
||||
}
|
||||
|
||||
const APP_LIST_LOAD_TIMEOUT: Duration = Duration::from_secs(90);
|
||||
// `app/list` is the legacy request-path baseline for the `app/installed` endpoint;
|
||||
// `path=legacy` keeps it separate from the new snapshot-backed implementation in dashboards.
|
||||
const APPS_INSTALLED_DURATION_METRIC: &str = "codex.apps.installed.duration_ms";
|
||||
|
||||
fn record_legacy_apps_installed_duration(started_at: Instant, reload: bool) {
|
||||
let reload = if reload { "true" } else { "false" };
|
||||
if let Some(metrics) = codex_otel::global() {
|
||||
let _ = metrics.record_duration(
|
||||
APPS_INSTALLED_DURATION_METRIC,
|
||||
started_at.elapsed(),
|
||||
&[("path", "legacy"), ("reload", reload)],
|
||||
);
|
||||
}
|
||||
}
|
||||
enum AppListLoadResult {
|
||||
Accessible(Result<AccessibleConnectorsStatus, String>),
|
||||
Directory(Result<Vec<AppInfo>, String>),
|
||||
}
|
||||
|
||||
fn merge_loaded_apps(
|
||||
all_connectors: Option<&[AppInfo]>,
|
||||
accessible_connectors: Option<&[AppInfo]>,
|
||||
) -> Vec<AppInfo> {
|
||||
let all_connectors_loaded = all_connectors.is_some();
|
||||
let all = all_connectors.map_or_else(Vec::new, <[AppInfo]>::to_vec);
|
||||
let accessible = accessible_connectors.map_or_else(Vec::new, <[AppInfo]>::to_vec);
|
||||
connectors::merge_connectors_with_accessible(all, accessible, all_connectors_loaded)
|
||||
}
|
||||
|
||||
fn should_send_app_list_updated_notification(
|
||||
connectors: &[AppInfo],
|
||||
accessible_loaded: bool,
|
||||
all_loaded: bool,
|
||||
) -> bool {
|
||||
connectors.iter().any(|connector| connector.is_accessible) || (accessible_loaded && all_loaded)
|
||||
}
|
||||
|
||||
fn paginate_apps(
|
||||
connectors: &[AppInfo],
|
||||
start: usize,
|
||||
limit: Option<u32>,
|
||||
) -> Result<AppsListResponse, JSONRPCErrorError> {
|
||||
let total = connectors.len();
|
||||
if start > total {
|
||||
return Err(invalid_request(format!(
|
||||
"cursor {start} exceeds total apps {total}"
|
||||
)));
|
||||
}
|
||||
|
||||
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
|
||||
let end = start.saturating_add(effective_limit).min(total);
|
||||
let data = connectors[start..end]
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(app_info_to_api)
|
||||
.collect();
|
||||
let next_cursor = if end < total {
|
||||
Some(end.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(AppsListResponse { data, next_cursor })
|
||||
}
|
||||
|
||||
async fn send_app_list_updated_notification(
|
||||
outgoing: &Arc<OutgoingMessageSender>,
|
||||
data: Vec<AppInfo>,
|
||||
) {
|
||||
let data = data.into_iter().map(app_info_to_api).collect();
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::AppListUpdated(
|
||||
AppListUpdatedNotification { data },
|
||||
))
|
||||
.await;
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
use super::*;
|
||||
|
||||
use codex_connectors::ConnectorRuntimeTool;
|
||||
use codex_connectors::connector_runtime_context_key;
|
||||
use codex_connectors::connector_tool_is_synthetic;
|
||||
use codex_connectors::installed_connector_runtime;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::MCP_TOOL_CODEX_APPS_META_KEY;
|
||||
use codex_mcp::McpRuntime;
|
||||
use codex_mcp::McpRuntimeInput;
|
||||
use codex_mcp::McpStartupPolicy;
|
||||
use codex_mcp::ToolInfo;
|
||||
use codex_mcp::effective_mcp_servers;
|
||||
use codex_mcp::host_owned_codex_apps_enabled;
|
||||
use codex_mcp::tool_is_model_visible;
|
||||
use codex_protocol::mcp::ClientMcpExtensions;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "installed_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
const CONNECTOR_RUNTIME_REFRESH_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const APPS_INSTALLED_SUBMIT_ID: &str = "app-installed";
|
||||
const APPS_INSTALLED_RESPONSE_BYTES_METRIC: &str = "codex.apps.installed.response_bytes";
|
||||
const APPS_INSTALLED_CONNECTOR_COUNT_METRIC: &str = "codex.apps.installed.connector_count";
|
||||
const APPS_INSTALLED_TOOL_COUNT_METRIC: &str = "codex.apps.installed.tool_count";
|
||||
const APPS_SNAPSHOT_AGE_METRIC: &str = "codex.apps.snapshot.age_ms";
|
||||
|
||||
struct AppsInstalledSnapshotMetrics {
|
||||
age: Option<Duration>,
|
||||
tool_count: usize,
|
||||
}
|
||||
|
||||
impl AppsRequestProcessor {
|
||||
pub(crate) async fn apps_installed(
|
||||
&self,
|
||||
params: AppsInstalledParams,
|
||||
) -> Result<AppsInstalledResponse, JSONRPCErrorError> {
|
||||
let started_at = Instant::now();
|
||||
let force_refresh = params.force_refresh;
|
||||
let mut retained_previous_snapshot = false;
|
||||
let mut refresh_disposition = if force_refresh {
|
||||
"not_started"
|
||||
} else {
|
||||
"not_requested"
|
||||
};
|
||||
let mut snapshot_age = None;
|
||||
let mut snapshot_tool_count = 0;
|
||||
let result = async {
|
||||
let (config, thread) = match params.thread_id.as_deref() {
|
||||
Some(thread_id) => {
|
||||
let (_, thread) = self.load_thread(thread_id).await?;
|
||||
let config = thread.config().await;
|
||||
(config.as_ref().clone(), Some(thread))
|
||||
}
|
||||
None => (
|
||||
self.load_latest_config(/*fallback_cwd*/ None).await?,
|
||||
None,
|
||||
),
|
||||
};
|
||||
let mcp_manager = thread.as_ref().map(|thread| thread.mcp_manager())
|
||||
.unwrap_or_else(|| self.thread_manager.mcp_manager());
|
||||
let auth_manager = mcp_manager.auth_manager();
|
||||
let auth = auth_manager.auth().await;
|
||||
let runtime_enabled = config
|
||||
.features
|
||||
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend));
|
||||
|
||||
let cache_key = connector_runtime_context_key(auth.as_ref());
|
||||
let previous_snapshot = mcp_manager
|
||||
.codex_apps_tools_cache()
|
||||
.current_snapshot(config.codex_home.to_path_buf(), cache_key.clone());
|
||||
let mut model_visible_tool_names = None;
|
||||
let tools = if force_refresh && runtime_enabled {
|
||||
let refresh_result = async {
|
||||
if let Some(thread) = thread {
|
||||
let snapshot = thread.refresh_codex_apps_tools().await?;
|
||||
model_visible_tool_names = Some(snapshot.model_visible_tool_names);
|
||||
snapshot_age = Some(Duration::ZERO);
|
||||
return Ok(snapshot.tools);
|
||||
}
|
||||
let mcp_config = mcp_manager.runtime_config(&config).await;
|
||||
let mut mcp_servers = effective_mcp_servers(&mcp_config, auth.as_ref());
|
||||
mcp_servers.retain(|name, _| name == CODEX_APPS_MCP_SERVER_NAME);
|
||||
let mcp_config = Arc::new(mcp_config.for_threadless_operations(&mcp_servers));
|
||||
anyhow::ensure!(
|
||||
!mcp_servers.is_empty(),
|
||||
"host-owned MCP server '{CODEX_APPS_MCP_SERVER_NAME}' is not enabled"
|
||||
);
|
||||
let startup_timeout = mcp_servers
|
||||
.get(CODEX_APPS_MCP_SERVER_NAME)
|
||||
.and_then(|server| server.config().startup_timeout_sec)
|
||||
.unwrap_or(CONNECTOR_RUNTIME_REFRESH_TIMEOUT);
|
||||
let runtime_context = McpRuntimeContext::new(
|
||||
self.thread_manager.environment_manager(),
|
||||
config.cwd.to_path_buf(),
|
||||
);
|
||||
let cancellation_token = CancellationToken::new();
|
||||
let codex_apps_auth_manager =
|
||||
host_owned_codex_apps_enabled(&mcp_config, auth.as_ref())
|
||||
.then(|| Arc::clone(&auth_manager));
|
||||
self.thread_manager.runtime_auth_for_mcp_manager(&config, &mcp_manager)?;
|
||||
let runtime = McpRuntime::new(McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: mcp_manager.runtime_auth_for_config(&config),
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::clone(&mcp_config),
|
||||
plugins_available: false,
|
||||
ready_selected_capability_roots: Vec::new(),
|
||||
mcp_servers,
|
||||
submit_id: APPS_INSTALLED_SUBMIT_ID.to_string(),
|
||||
tx_event: None,
|
||||
startup_cancellation_token: cancellation_token.clone(),
|
||||
runtime_context,
|
||||
codex_apps_tools_cache: mcp_manager.codex_apps_tools_cache(),
|
||||
tool_catalog_cache: mcp_manager.tool_catalog_cache(),
|
||||
codex_apps_tools_cache_key: cache_key.clone(),
|
||||
client_mcp_extensions: ClientMcpExtensions::default(),
|
||||
auth: auth.clone(),
|
||||
auth_manager: codex_apps_auth_manager,
|
||||
elicitation_reviewer: None,
|
||||
elicitation_lifecycle: None,
|
||||
})
|
||||
.await;
|
||||
|
||||
let result = if runtime
|
||||
.latest_wait_for_server_ready(
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
startup_timeout,
|
||||
)
|
||||
.await
|
||||
{
|
||||
mcp_manager
|
||||
.codex_apps_tools_cache()
|
||||
.current_snapshot(config.codex_home.to_path_buf(), cache_key.clone())
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"hosted connector refresh completed without publishing a snapshot"
|
||||
)
|
||||
})
|
||||
} else {
|
||||
Err(anyhow::anyhow!(
|
||||
"failed to refresh tools for MCP server '{CODEX_APPS_MCP_SERVER_NAME}'"
|
||||
))
|
||||
};
|
||||
cancellation_token.cancel();
|
||||
runtime.shutdown().await;
|
||||
result.map(|snapshot| {
|
||||
snapshot_age = Some(snapshot.age());
|
||||
snapshot.tools().to_vec()
|
||||
})
|
||||
}
|
||||
.await;
|
||||
|
||||
match refresh_result {
|
||||
Ok(tools) => {
|
||||
refresh_disposition = "success";
|
||||
tools
|
||||
}
|
||||
Err(err) => {
|
||||
refresh_disposition = "error";
|
||||
retained_previous_snapshot = previous_snapshot.is_some();
|
||||
return Err(internal_error(format!(
|
||||
"failed to refresh installed connector runtime state: {err:#}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if force_refresh {
|
||||
refresh_disposition = "skipped_apps_disabled";
|
||||
retained_previous_snapshot = previous_snapshot.is_some();
|
||||
}
|
||||
previous_snapshot.map_or_else(Vec::new, |snapshot| {
|
||||
snapshot_age = Some(snapshot.age());
|
||||
snapshot.tools().to_vec()
|
||||
})
|
||||
};
|
||||
|
||||
snapshot_tool_count = tools.len();
|
||||
let apps = installed_connector_runtime(
|
||||
&config.config_layer_stack,
|
||||
tools.iter().map(|tool| {
|
||||
let mut runtime_tool = connector_runtime_tool(tool);
|
||||
if let Some(names) = &model_visible_tool_names {
|
||||
runtime_tool.model_visible &= names.contains(tool.tool.name.as_ref());
|
||||
}
|
||||
runtime_tool
|
||||
}),
|
||||
)
|
||||
.into_iter()
|
||||
.map(|app| InstalledApp {
|
||||
id: app.id,
|
||||
runtime_name: app.runtime_name,
|
||||
enabled: runtime_enabled && app.enabled,
|
||||
callable: runtime_enabled && app.callable,
|
||||
})
|
||||
.collect();
|
||||
Ok(AppsInstalledResponse { apps })
|
||||
}
|
||||
.await;
|
||||
|
||||
if let Some(metrics) = codex_otel::global() {
|
||||
record_apps_installed_metrics(
|
||||
&metrics,
|
||||
started_at,
|
||||
force_refresh,
|
||||
retained_previous_snapshot,
|
||||
refresh_disposition,
|
||||
AppsInstalledSnapshotMetrics {
|
||||
age: snapshot_age,
|
||||
tool_count: snapshot_tool_count,
|
||||
},
|
||||
result.as_ref().ok(),
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
fn connector_runtime_tool(tool: &ToolInfo) -> ConnectorRuntimeTool<'_> {
|
||||
let annotations = tool.tool.annotations.as_ref();
|
||||
ConnectorRuntimeTool {
|
||||
connector_id: tool.connector_id.as_deref(),
|
||||
connector_name: tool.connector_name.as_deref(),
|
||||
tool_name: &tool.tool.name,
|
||||
tool_title: tool.tool.title.as_deref(),
|
||||
destructive_hint: annotations.and_then(|annotations| annotations.destructive_hint),
|
||||
open_world_hint: annotations.and_then(|annotations| annotations.open_world_hint),
|
||||
synthetic: connector_tool_is_synthetic(
|
||||
tool.tool
|
||||
.meta
|
||||
.as_deref()
|
||||
.and_then(|meta| meta.get(MCP_TOOL_CODEX_APPS_META_KEY)),
|
||||
),
|
||||
model_visible: tool_is_model_visible(tool),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_apps_installed_metrics(
|
||||
metrics: &codex_otel::MetricsClient,
|
||||
started_at: Instant,
|
||||
force_refresh: bool,
|
||||
retained_previous_snapshot: bool,
|
||||
refresh_disposition: &'static str,
|
||||
snapshot_metrics: AppsInstalledSnapshotMetrics,
|
||||
response: Option<&AppsInstalledResponse>,
|
||||
) {
|
||||
let Some(response) = response else {
|
||||
return;
|
||||
};
|
||||
let force_refresh = if force_refresh { "true" } else { "false" };
|
||||
let retained_previous_snapshot = if retained_previous_snapshot {
|
||||
"true"
|
||||
} else {
|
||||
"false"
|
||||
};
|
||||
let _ = metrics.record_duration(
|
||||
APPS_INSTALLED_DURATION_METRIC,
|
||||
started_at.elapsed(),
|
||||
&[
|
||||
("path", "installed"),
|
||||
("reload", force_refresh),
|
||||
("force_refresh", force_refresh),
|
||||
("refresh", refresh_disposition),
|
||||
("outcome", "success"),
|
||||
("retained_previous_snapshot", retained_previous_snapshot),
|
||||
],
|
||||
);
|
||||
if let Ok(bytes) = serde_json::to_vec(response) {
|
||||
let _ = metrics.histogram(
|
||||
APPS_INSTALLED_RESPONSE_BYTES_METRIC,
|
||||
i64::try_from(bytes.len()).unwrap_or(i64::MAX),
|
||||
&[("path", "new")],
|
||||
);
|
||||
}
|
||||
let _ = metrics.histogram(
|
||||
APPS_INSTALLED_CONNECTOR_COUNT_METRIC,
|
||||
i64::try_from(response.apps.len()).unwrap_or(i64::MAX),
|
||||
&[("path", "new")],
|
||||
);
|
||||
let _ = metrics.histogram(
|
||||
APPS_INSTALLED_TOOL_COUNT_METRIC,
|
||||
i64::try_from(snapshot_metrics.tool_count).unwrap_or(i64::MAX),
|
||||
&[("path", "new")],
|
||||
);
|
||||
if let Some(snapshot_age) = snapshot_metrics.age {
|
||||
let _ = metrics.record_duration(
|
||||
APPS_SNAPSHOT_AGE_METRIC,
|
||||
snapshot_age,
|
||||
&[("path", "new"), ("observation", "installed")],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
use super::APPS_INSTALLED_DURATION_METRIC;
|
||||
use super::AppsInstalledSnapshotMetrics;
|
||||
use super::record_apps_installed_metrics;
|
||||
use anyhow::Result;
|
||||
use codex_app_server_protocol::AppsInstalledResponse;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_otel::MetricsConfig;
|
||||
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use opentelemetry_sdk::metrics::data::ScopeMetrics;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::Instant;
|
||||
|
||||
fn test_metrics() -> Result<MetricsClient> {
|
||||
Ok(MetricsClient::new(
|
||||
MetricsConfig::in_memory(
|
||||
"test",
|
||||
"codex-app-server",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
InMemoryMetricExporter::default(),
|
||||
)
|
||||
.with_runtime_reader(),
|
||||
)?)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_duration_records_one_sample_per_success_with_legacy_comparison_dimensions()
|
||||
-> Result<()> {
|
||||
let metrics = test_metrics()?;
|
||||
let response = AppsInstalledResponse { apps: Vec::new() };
|
||||
|
||||
record_apps_installed_metrics(
|
||||
&metrics,
|
||||
Instant::now(),
|
||||
/*force_refresh*/ false,
|
||||
/*retained_previous_snapshot*/ false,
|
||||
"not_requested",
|
||||
AppsInstalledSnapshotMetrics {
|
||||
age: None,
|
||||
tool_count: 0,
|
||||
},
|
||||
Some(&response),
|
||||
);
|
||||
record_apps_installed_metrics(
|
||||
&metrics,
|
||||
Instant::now(),
|
||||
/*force_refresh*/ true,
|
||||
/*retained_previous_snapshot*/ false,
|
||||
"success",
|
||||
AppsInstalledSnapshotMetrics {
|
||||
age: None,
|
||||
tool_count: 0,
|
||||
},
|
||||
Some(&response),
|
||||
);
|
||||
|
||||
let snapshot = metrics.snapshot()?;
|
||||
let metric = snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(ScopeMetrics::metrics)
|
||||
.find(|metric| metric.name() == APPS_INSTALLED_DURATION_METRIC)
|
||||
.expect("installed duration metric should be recorded");
|
||||
let mut points = match metric.data() {
|
||||
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => histogram
|
||||
.data_points()
|
||||
.map(|point| {
|
||||
let attributes = point
|
||||
.attributes()
|
||||
.map(|attribute| {
|
||||
(
|
||||
attribute.key.as_str().to_string(),
|
||||
attribute.value.as_str().to_string(),
|
||||
)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
(attributes, point.count())
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
_ => panic!("installed duration should be a floating-point histogram"),
|
||||
};
|
||||
points.sort_by(|(left, _), (right, _)| left.cmp(right));
|
||||
|
||||
assert_eq!(
|
||||
points,
|
||||
vec![
|
||||
(
|
||||
BTreeMap::from([
|
||||
("force_refresh".to_string(), "false".to_string()),
|
||||
("outcome".to_string(), "success".to_string()),
|
||||
("path".to_string(), "installed".to_string()),
|
||||
("refresh".to_string(), "not_requested".to_string()),
|
||||
("reload".to_string(), "false".to_string()),
|
||||
(
|
||||
"retained_previous_snapshot".to_string(),
|
||||
"false".to_string()
|
||||
),
|
||||
]),
|
||||
1,
|
||||
),
|
||||
(
|
||||
BTreeMap::from([
|
||||
("force_refresh".to_string(), "true".to_string()),
|
||||
("outcome".to_string(), "success".to_string()),
|
||||
("path".to_string(), "installed".to_string()),
|
||||
("refresh".to_string(), "success".to_string()),
|
||||
("reload".to_string(), "true".to_string()),
|
||||
(
|
||||
"retained_previous_snapshot".to_string(),
|
||||
"false".to_string()
|
||||
),
|
||||
]),
|
||||
1,
|
||||
),
|
||||
]
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_duration_does_not_record_failed_requests() -> Result<()> {
|
||||
let metrics = test_metrics()?;
|
||||
|
||||
record_apps_installed_metrics(
|
||||
&metrics,
|
||||
Instant::now(),
|
||||
/*force_refresh*/ true,
|
||||
/*retained_previous_snapshot*/ true,
|
||||
"error",
|
||||
AppsInstalledSnapshotMetrics {
|
||||
age: None,
|
||||
tool_count: 0,
|
||||
},
|
||||
/*response*/ None,
|
||||
);
|
||||
|
||||
let snapshot = metrics.snapshot()?;
|
||||
assert!(
|
||||
snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(ScopeMetrics::metrics)
|
||||
.all(|metric| metric.name() != APPS_INSTALLED_DURATION_METRIC),
|
||||
"failed installed requests must not record a successful duration sample",
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
use super::*;
|
||||
use crate::app_info::connector_metadata_to_api;
|
||||
|
||||
pub(in crate::request_processors) const APP_READ_MAX_IDS: usize = 100;
|
||||
const APPS_READ_DURATION_METRIC: &str = "codex.apps.read.duration_ms";
|
||||
|
||||
impl AppsRequestProcessor {
|
||||
pub(crate) async fn apps_read(
|
||||
&self,
|
||||
params: AppsReadParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let started_at = Instant::now();
|
||||
let AppsReadParams {
|
||||
app_ids,
|
||||
thread_id,
|
||||
include_tools,
|
||||
} = params;
|
||||
if app_ids.len() > APP_READ_MAX_IDS {
|
||||
return Err(invalid_params(format!(
|
||||
"app/read accepts at most {APP_READ_MAX_IDS} appIds"
|
||||
)));
|
||||
}
|
||||
|
||||
let mut seen_app_ids = HashSet::new();
|
||||
let app_ids = app_ids
|
||||
.into_iter()
|
||||
.filter(|app_id| seen_app_ids.insert(app_id.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
let (mut config, mcp_manager) = self.load_apps_config(thread_id.as_deref()).await?;
|
||||
let auth = match mcp_manager
|
||||
.auth_manager()
|
||||
.auth_with_http_client_factory()
|
||||
.await
|
||||
{
|
||||
Some((auth, factory)) => {
|
||||
config.application_network_policy = factory.network_policy().clone();
|
||||
Some(auth)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let runtime = self
|
||||
.thread_manager
|
||||
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
if !config
|
||||
.features
|
||||
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend))
|
||||
{
|
||||
let response = AppsReadResponse {
|
||||
apps: Vec::new(),
|
||||
missing_app_ids: app_ids,
|
||||
};
|
||||
record_apps_read_duration(started_at, include_tools);
|
||||
return Ok(Some(response.into()));
|
||||
}
|
||||
let auth = auth
|
||||
.as_ref()
|
||||
.ok_or_else(|| internal_error("app/read requires ChatGPT auth".to_string()))?;
|
||||
|
||||
let connectors::ConnectorMetadataReadResult {
|
||||
apps,
|
||||
missing_app_ids,
|
||||
} = connectors::read_connector_metadata(
|
||||
&config,
|
||||
auth,
|
||||
runtime.as_ref(),
|
||||
&app_ids,
|
||||
include_tools,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to read app metadata: {err}")))?;
|
||||
let loaded_plugins = mcp_manager
|
||||
.plugins_manager()
|
||||
.plugins_for_config(&config.plugins_config_input())
|
||||
.await;
|
||||
let connector_snapshot =
|
||||
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(
|
||||
loaded_plugins.capability_summaries(),
|
||||
);
|
||||
let apps = apps
|
||||
.into_iter()
|
||||
.map(|metadata| {
|
||||
let mut app = connector_metadata_to_api(metadata);
|
||||
app.plugin_display_names = connector_snapshot
|
||||
.plugin_display_names_for_connector_id(app.id.as_str())
|
||||
.to_vec();
|
||||
app
|
||||
})
|
||||
.collect();
|
||||
let response = AppsReadResponse {
|
||||
apps,
|
||||
missing_app_ids,
|
||||
};
|
||||
record_apps_read_duration(started_at, include_tools);
|
||||
Ok(Some(response.into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn record_apps_read_duration(started_at: Instant, include_tools: bool) {
|
||||
let include_tools = if include_tools { "true" } else { "false" };
|
||||
if let Some(metrics) = codex_otel::global() {
|
||||
let _ = metrics.record_duration(
|
||||
APPS_READ_DURATION_METRIC,
|
||||
started_at.elapsed(),
|
||||
&[("include_tools", include_tools)],
|
||||
);
|
||||
}
|
||||
}
|
||||
98
codex-rs/app-server/src/request_processors/bedrock_auth.rs
Normal file
98
codex-rs/app-server/src/request_processors/bedrock_auth.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
use super::config_processor::map_error as map_config_error;
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::config_manager_service::PreparedProviderWrite;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use codex_app_server_protocol::ConfigBatchWriteParams;
|
||||
use codex_app_server_protocol::ConfigEdit;
|
||||
use codex_app_server_protocol::ConfigWriteErrorCode;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::MergeStrategy;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::config::edit::ConfigEditsBuilder;
|
||||
use codex_model_provider::AMAZON_BEDROCK_PROVIDER_ID;
|
||||
|
||||
pub(super) struct BedrockProviderConfig<'a> {
|
||||
pub(super) region: Option<&'a str>,
|
||||
pub(super) profile: Option<&'a str>,
|
||||
}
|
||||
|
||||
pub(super) async fn prepare_bedrock_provider(
|
||||
config_manager: &ConfigManager,
|
||||
config: BedrockProviderConfig<'_>,
|
||||
) -> Result<PreparedProviderWrite, JSONRPCErrorError> {
|
||||
let layers = config_manager
|
||||
.load_config_layers(/*cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to load configuration layers: {err}")))?;
|
||||
let mut settings = vec![("aws.profile", config.profile)];
|
||||
if let Some(region) = config.region {
|
||||
settings.push(("aws.region", Some(region)));
|
||||
}
|
||||
let (write, provider) = config_manager
|
||||
.prepare_provider_config(&layers, AMAZON_BEDROCK_PROVIDER_ID, settings)
|
||||
.map_err(map_config_error)?;
|
||||
if provider
|
||||
.aws
|
||||
.is_some_and(|aws| aws.credential_export.is_some())
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Amazon Bedrock is configured to use `aws.credential_export`. Please clear this setting to use another sign-in method.",
|
||||
));
|
||||
}
|
||||
Ok(write)
|
||||
}
|
||||
|
||||
pub(super) async fn clear_user_model_provider_if_bedrock(
|
||||
config_manager: &ConfigManager,
|
||||
config: &Config,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let mut latest_config = None;
|
||||
loop {
|
||||
let config = latest_config.as_ref().unwrap_or(config);
|
||||
let Some(key_paths) = ConfigEditsBuilder::bedrock_provider_config_paths_to_clear(config)
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let expected_version = config
|
||||
.config_layer_stack
|
||||
.get_active_user_layer()
|
||||
.map(|layer| layer.version.clone());
|
||||
|
||||
let result = config_manager
|
||||
.batch_write(ConfigBatchWriteParams {
|
||||
edits: key_paths
|
||||
.into_iter()
|
||||
.map(|segments| ConfigEdit {
|
||||
key_path: segments.join("."),
|
||||
value: serde_json::Value::Null,
|
||||
merge_strategy: MergeStrategy::Replace,
|
||||
})
|
||||
.collect(),
|
||||
file_path: None,
|
||||
expected_version,
|
||||
reload_user_config: false,
|
||||
})
|
||||
.await;
|
||||
if let Err(err) = &result
|
||||
&& latest_config.is_none()
|
||||
&& err.write_error_code() == Some(ConfigWriteErrorCode::ConfigVersionConflict)
|
||||
{
|
||||
tracing::warn!(
|
||||
"configuration changed while clearing Amazon Bedrock settings; retrying once"
|
||||
);
|
||||
latest_config = Some(
|
||||
config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to reload Amazon Bedrock configuration: {err}"
|
||||
))
|
||||
})?,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
return result.map(|_| ()).map_err(map_config_error);
|
||||
}
|
||||
}
|
||||
783
codex-rs/app-server/src/request_processors/catalog_processor.rs
Normal file
783
codex-rs/app-server/src/request_processors/catalog_processor.rs
Normal file
@@ -0,0 +1,783 @@
|
||||
use super::*;
|
||||
use crate::model_catalog::ModelCatalog;
|
||||
use codex_config::ConfigPathContext;
|
||||
use codex_core::config::permission_profile_catalog;
|
||||
use codex_hooks::HookListEntryHandler;
|
||||
use codex_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use futures::StreamExt;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CatalogRequestProcessor {
|
||||
pub(super) outgoing: Arc<OutgoingMessageSender>,
|
||||
pub(super) skills_watcher: Arc<SkillsWatcher>,
|
||||
pub(super) thread_manager: Arc<ThreadManager>,
|
||||
pub(super) config: Arc<Config>,
|
||||
pub(super) config_manager: ConfigManager,
|
||||
model_catalog: Arc<ModelCatalog>,
|
||||
}
|
||||
|
||||
const SKILLS_LIST_CWD_CONCURRENCY: usize = 5;
|
||||
|
||||
fn skills_to_info(
|
||||
skills: &[codex_skills::SkillMetadata],
|
||||
disabled_paths: &HashSet<PathUri>,
|
||||
) -> Vec<codex_app_server_protocol::SkillMetadata> {
|
||||
skills
|
||||
.iter()
|
||||
.map(|skill| {
|
||||
let enabled = !disabled_paths.contains(&skill.path_to_skills_md);
|
||||
codex_app_server_protocol::SkillMetadata {
|
||||
name: skill.name.clone(),
|
||||
description: skill.description.clone(),
|
||||
short_description: skill.short_description.clone(),
|
||||
interface: skill.interface.clone().map(|interface| {
|
||||
codex_app_server_protocol::SkillInterface {
|
||||
display_name: interface.display_name,
|
||||
short_description: interface.short_description,
|
||||
icon_small: interface.icon_small,
|
||||
icon_large: interface.icon_large,
|
||||
icon_small_url: None,
|
||||
icon_large_url: None,
|
||||
brand_color: interface.brand_color,
|
||||
default_prompt: interface.default_prompt,
|
||||
}
|
||||
}),
|
||||
dependencies: skill.dependencies.clone().map(|dependencies| {
|
||||
codex_app_server_protocol::SkillDependencies {
|
||||
tools: dependencies
|
||||
.tools
|
||||
.into_iter()
|
||||
.map(|tool| codex_app_server_protocol::SkillToolDependency {
|
||||
r#type: tool.r#type,
|
||||
value: tool.value,
|
||||
description: tool.description,
|
||||
transport: tool.transport,
|
||||
command: tool.command,
|
||||
url: tool.url,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}),
|
||||
path: skill.path_to_skills_md.clone().into(),
|
||||
scope: skill.scope.into(),
|
||||
enabled,
|
||||
plugin_id: skill.plugin_id.clone(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn hooks_to_info(hooks: &[codex_hooks::HookListEntry]) -> Vec<HookMetadata> {
|
||||
hooks
|
||||
.iter()
|
||||
.filter(|hook| !hook.builtin)
|
||||
.map(|hook| {
|
||||
let handler = match &hook.handler {
|
||||
HookListEntryHandler::Command { command, r#async } => {
|
||||
HookHandlerMetadata::Command {
|
||||
command: command.clone(),
|
||||
r#async: *r#async,
|
||||
}
|
||||
}
|
||||
HookListEntryHandler::McpTool { server, tool } => HookHandlerMetadata::McpTool {
|
||||
server: server.clone(),
|
||||
tool: tool.clone(),
|
||||
},
|
||||
};
|
||||
HookMetadata {
|
||||
key: hook.key.clone(),
|
||||
event_name: hook.event_name.into(),
|
||||
handler,
|
||||
matcher: hook.matcher.clone(),
|
||||
timeout_sec: hook.timeout_sec,
|
||||
status_message: hook.status_message.clone(),
|
||||
additional_context_limit: hook.additional_context_limit,
|
||||
source_path: hook.source_path.clone(),
|
||||
source: hook.source.into(),
|
||||
plugin_id: hook.plugin_id.clone(),
|
||||
environment_id: hook.environment_id.clone(),
|
||||
display_order: hook.display_order,
|
||||
enabled: hook.enabled,
|
||||
is_managed: hook.is_managed,
|
||||
current_hash: hook.current_hash.clone(),
|
||||
trust_status: hook.trust_status.into(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn errors_to_info(
|
||||
errors: &[codex_skills::SkillError],
|
||||
) -> Vec<codex_app_server_protocol::SkillErrorInfo> {
|
||||
errors
|
||||
.iter()
|
||||
.map(|err| codex_app_server_protocol::SkillErrorInfo {
|
||||
path: err.path.to_path_buf(),
|
||||
message: err.message.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl CatalogRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
skills_watcher: Arc<SkillsWatcher>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config: Arc<Config>,
|
||||
config_manager: ConfigManager,
|
||||
model_catalog: Arc<ModelCatalog>,
|
||||
) -> Self {
|
||||
Self {
|
||||
outgoing,
|
||||
skills_watcher,
|
||||
thread_manager,
|
||||
config,
|
||||
config_manager,
|
||||
model_catalog,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn skills_list(
|
||||
&self,
|
||||
params: SkillsListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.skills_list_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn hooks_list(
|
||||
&self,
|
||||
params: HooksListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.hooks_list_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn skills_config_write(
|
||||
&self,
|
||||
params: SkillsConfigWriteParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.skills_config_write_response_inner(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn skills_extra_roots_set(
|
||||
&self,
|
||||
params: SkillsExtraRootsSetParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.skills_extra_roots_set_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn model_list(
|
||||
&self,
|
||||
params: ModelListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let (active_config, active_models_manager) = self
|
||||
.model_catalog
|
||||
.current()
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
let (config, models_manager) = match params.model_provider.as_deref() {
|
||||
None => (active_config, active_models_manager),
|
||||
Some(provider_id) => {
|
||||
let config = config_for_provider(&self.config, provider_id)?;
|
||||
if provider_id == active_config.model_provider_id
|
||||
&& config.model_provider == active_config.model_provider
|
||||
{
|
||||
(active_config, active_models_manager)
|
||||
} else {
|
||||
// Temporary catalogs must not replace the active provider's disk cache.
|
||||
let manager = self.thread_manager.temporary_models_manager_for_config(
|
||||
&config,
|
||||
&codex_models_manager::manager::ModelCatalogSettings::default(),
|
||||
);
|
||||
(config, manager)
|
||||
}
|
||||
}
|
||||
};
|
||||
// Gate the same provider used by the catalog, including when its model cache is warm.
|
||||
// Resolving credentials may refresh them, but explicit host policy prevents browser login.
|
||||
if let Some(gateway) = codex_model_provider::create_model_provider(
|
||||
config.model_provider.clone(),
|
||||
Some(self.thread_manager.auth_manager()),
|
||||
)
|
||||
.gateway_auth_manager()
|
||||
.map_err(|error| internal_error(error.to_string()))?
|
||||
{
|
||||
// Refreshing credentials can contact the gateway before the catalog's own check.
|
||||
self.config_manager
|
||||
.check_thread_model_provider(&config)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
if let Err(error) = gateway.resolve_access_token().await {
|
||||
let current = self
|
||||
.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
// An explicit selection need not match the current default.
|
||||
if current.model_providers.get(&config.model_provider_id)
|
||||
!= Some(&config.model_provider)
|
||||
|| (params.model_provider.is_none()
|
||||
&& current.model_provider_id != config.model_provider_id)
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Model provider settings changed. Restart Codex to apply them, then retry fetching the model list",
|
||||
));
|
||||
}
|
||||
return Err(invalid_request(error.to_string()));
|
||||
}
|
||||
}
|
||||
self.list_models(params, config, models_manager)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn experimental_feature_list(
|
||||
&self,
|
||||
params: ExperimentalFeatureListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.experimental_feature_list_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn permission_profile_list(
|
||||
&self,
|
||||
params: PermissionProfileListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.permission_profile_list_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn collaboration_mode_list(
|
||||
&self,
|
||||
params: CollaborationModeListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
Self::list_collaboration_modes(self.thread_manager.clone(), params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn mock_experimental_method(
|
||||
&self,
|
||||
params: MockExperimentalMethodParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.mock_experimental_method_inner(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
async fn resolve_cwd_config(
|
||||
&self,
|
||||
cwd: &Path,
|
||||
) -> Result<(AbsolutePathBuf, ConfigLayerStack), String> {
|
||||
let cwd_abs =
|
||||
AbsolutePathBuf::relative_to_current_dir(cwd).map_err(|err| err.to_string())?;
|
||||
let config_layer_stack = self
|
||||
.config_manager
|
||||
.load_config_layers_for_cwd(cwd_abs.clone())
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
|
||||
Ok((cwd_abs, config_layer_stack))
|
||||
}
|
||||
|
||||
async fn load_latest_config(
|
||||
&self,
|
||||
fallback_cwd: Option<PathBuf>,
|
||||
) -> Result<Config, JSONRPCErrorError> {
|
||||
self.config_manager
|
||||
.load_latest_config(fallback_cwd)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
|
||||
}
|
||||
|
||||
async fn list_models(
|
||||
&self,
|
||||
params: ModelListParams,
|
||||
config: Arc<Config>,
|
||||
models_manager: codex_models_manager::manager::SharedModelsManager,
|
||||
) -> Result<ModelListResponse, JSONRPCErrorError> {
|
||||
let ModelListParams {
|
||||
limit,
|
||||
cursor,
|
||||
include_hidden,
|
||||
model_provider: _,
|
||||
} = params;
|
||||
let presets = self
|
||||
.model_catalog
|
||||
.list_models_from_snapshot(
|
||||
config,
|
||||
models_manager,
|
||||
codex_models_manager::manager::RefreshStrategy::OnlineIfUncached,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
let models = supported_models(presets, include_hidden.unwrap_or(false));
|
||||
let total = models.len();
|
||||
|
||||
if total == 0 {
|
||||
return Ok(ModelListResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
});
|
||||
}
|
||||
|
||||
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
|
||||
let effective_limit = effective_limit.min(total);
|
||||
let start = match cursor {
|
||||
Some(cursor) => cursor
|
||||
.parse::<usize>()
|
||||
.map_err(|_| invalid_request(format!("invalid cursor: {cursor}")))?,
|
||||
None => 0,
|
||||
};
|
||||
|
||||
if start > total {
|
||||
return Err(invalid_request(format!(
|
||||
"cursor {start} exceeds total models {total}"
|
||||
)));
|
||||
}
|
||||
|
||||
let end = start.saturating_add(effective_limit).min(total);
|
||||
let items = models[start..end].to_vec();
|
||||
let next_cursor = if end < total {
|
||||
Some(end.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(ModelListResponse {
|
||||
data: items,
|
||||
next_cursor,
|
||||
})
|
||||
}
|
||||
|
||||
async fn list_collaboration_modes(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
params: CollaborationModeListParams,
|
||||
) -> Result<CollaborationModeListResponse, JSONRPCErrorError> {
|
||||
let CollaborationModeListParams {} = params;
|
||||
let items = thread_manager
|
||||
.list_collaboration_modes()
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
.collect();
|
||||
let response = CollaborationModeListResponse { data: items };
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn experimental_feature_list_response(
|
||||
&self,
|
||||
params: ExperimentalFeatureListParams,
|
||||
) -> Result<ExperimentalFeatureListResponse, JSONRPCErrorError> {
|
||||
let ExperimentalFeatureListParams {
|
||||
cursor,
|
||||
limit,
|
||||
thread_id,
|
||||
} = params;
|
||||
let config = match thread_id.as_deref() {
|
||||
Some(thread_id) => {
|
||||
let thread_id = ThreadId::from_string(thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
|
||||
let thread = self
|
||||
.thread_manager
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
|
||||
let thread_config = thread.config().await;
|
||||
self.config_manager
|
||||
.load_latest_config_with_session_layers(
|
||||
&thread_config.config_layer_stack,
|
||||
&thread_config.cwd,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?
|
||||
}
|
||||
None => self.load_latest_config(/*fallback_cwd*/ None).await?,
|
||||
};
|
||||
let data = FEATURES
|
||||
.iter()
|
||||
.map(|spec| {
|
||||
let (stage, display_name, description, announcement) = match spec.stage {
|
||||
Stage::Experimental {
|
||||
name,
|
||||
menu_description,
|
||||
announcement,
|
||||
} => (
|
||||
ApiExperimentalFeatureStage::Beta,
|
||||
Some(name.to_string()),
|
||||
Some(menu_description.to_string()),
|
||||
Some(announcement.to_string()),
|
||||
),
|
||||
Stage::UnderDevelopment => (
|
||||
ApiExperimentalFeatureStage::UnderDevelopment,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
Stage::Stable => (ApiExperimentalFeatureStage::Stable, None, None, None),
|
||||
Stage::Deprecated => {
|
||||
(ApiExperimentalFeatureStage::Deprecated, None, None, None)
|
||||
}
|
||||
Stage::Removed => (ApiExperimentalFeatureStage::Removed, None, None, None),
|
||||
};
|
||||
|
||||
ApiExperimentalFeature {
|
||||
name: spec.key.to_string(),
|
||||
stage,
|
||||
display_name,
|
||||
description,
|
||||
announcement,
|
||||
enabled: config.features.enabled(spec.id),
|
||||
default_enabled: spec.default_enabled,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let total = data.len();
|
||||
if total == 0 {
|
||||
return Ok(ExperimentalFeatureListResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
});
|
||||
}
|
||||
|
||||
// Clamp to 1 so limit=0 cannot return a non-advancing page.
|
||||
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
|
||||
let effective_limit = effective_limit.min(total);
|
||||
let start = match cursor {
|
||||
Some(cursor) => match cursor.parse::<usize>() {
|
||||
Ok(idx) => idx,
|
||||
Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))),
|
||||
},
|
||||
None => 0,
|
||||
};
|
||||
|
||||
if start > total {
|
||||
return Err(invalid_request(format!(
|
||||
"cursor {start} exceeds total feature flags {total}"
|
||||
)));
|
||||
}
|
||||
|
||||
let end = start.saturating_add(effective_limit).min(total);
|
||||
let data = data[start..end].to_vec();
|
||||
let next_cursor = if end < total {
|
||||
Some(end.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(ExperimentalFeatureListResponse { data, next_cursor })
|
||||
}
|
||||
|
||||
async fn permission_profile_list_response(
|
||||
&self,
|
||||
params: PermissionProfileListParams,
|
||||
) -> Result<PermissionProfileListResponse, JSONRPCErrorError> {
|
||||
let PermissionProfileListParams { cursor, limit, cwd } = params;
|
||||
let (cwd, config_layer_stack) = match cwd {
|
||||
Some(cwd) => self
|
||||
.resolve_cwd_config(&PathBuf::from(cwd))
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?,
|
||||
None => (
|
||||
self.config.cwd.clone(),
|
||||
self.config_manager
|
||||
.load_config_layers(/*cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?,
|
||||
),
|
||||
};
|
||||
let context = ConfigPathContext::new(
|
||||
PathConvention::native(),
|
||||
Some(PathUri::from_abs_path(&cwd)),
|
||||
AbsolutePathBufGuard::home_directory()
|
||||
.and_then(|home| PathUri::from_host_native_path(home).ok()),
|
||||
);
|
||||
let profiles = permission_profile_catalog(&config_layer_stack, &context)
|
||||
.map_err(|err| internal_error(format!("failed to resolve permission profiles: {err}")))?
|
||||
.into_iter()
|
||||
.map(|profile| PermissionProfileSummary {
|
||||
id: profile.id,
|
||||
description: profile.description,
|
||||
allowed: profile.allowed,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let total = profiles.len();
|
||||
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
|
||||
let effective_limit = effective_limit.min(total);
|
||||
let start = match cursor {
|
||||
Some(cursor) => cursor
|
||||
.parse::<usize>()
|
||||
.map_err(|_| invalid_request(format!("invalid cursor: {cursor}")))?,
|
||||
None => 0,
|
||||
};
|
||||
|
||||
if start > total {
|
||||
return Err(invalid_request(format!(
|
||||
"cursor {start} exceeds total permission profiles {total}"
|
||||
)));
|
||||
}
|
||||
|
||||
let end = start.saturating_add(effective_limit).min(total);
|
||||
let data = profiles[start..end].to_vec();
|
||||
let next_cursor = (end < total).then_some(end.to_string());
|
||||
|
||||
Ok(PermissionProfileListResponse { data, next_cursor })
|
||||
}
|
||||
|
||||
async fn mock_experimental_method_inner(
|
||||
&self,
|
||||
params: MockExperimentalMethodParams,
|
||||
) -> Result<MockExperimentalMethodResponse, JSONRPCErrorError> {
|
||||
let MockExperimentalMethodParams { value } = params;
|
||||
let response = MockExperimentalMethodResponse { echoed: value };
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn skills_list_response(
|
||||
&self,
|
||||
params: SkillsListParams,
|
||||
) -> Result<SkillsListResponse, JSONRPCErrorError> {
|
||||
let SkillsListParams { cwds, force_reload } = params;
|
||||
let cwds = if cwds.is_empty() {
|
||||
vec![self.config.cwd.to_path_buf()]
|
||||
} else {
|
||||
cwds
|
||||
};
|
||||
|
||||
let skills_service = self.thread_manager.skills_service();
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
if force_reload {
|
||||
plugins_manager.clear_cache();
|
||||
skills_service.clear_cache();
|
||||
}
|
||||
let fs = self
|
||||
.thread_manager
|
||||
.environment_manager()
|
||||
.default_environment()
|
||||
.map(|environment| environment.get_filesystem());
|
||||
let skills_request = skills_service.for_request();
|
||||
let mut data = futures::stream::iter(cwds.into_iter().enumerate())
|
||||
.map(|(index, cwd)| {
|
||||
let fs = fs.clone();
|
||||
let skills_request = &skills_request;
|
||||
let plugins_manager = Arc::clone(&plugins_manager);
|
||||
async move {
|
||||
let config = match self.load_latest_config(Some(cwd.clone())).await {
|
||||
Ok(resolved) => resolved,
|
||||
Err(error) => {
|
||||
let error_path = cwd.clone();
|
||||
return (
|
||||
index,
|
||||
codex_app_server_protocol::SkillsListEntry {
|
||||
cwd,
|
||||
skills: Vec::new(),
|
||||
errors: vec![codex_app_server_protocol::SkillErrorInfo {
|
||||
path: error_path,
|
||||
message: error.message,
|
||||
}],
|
||||
},
|
||||
);
|
||||
}
|
||||
};
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let plugins = plugins_manager.plugins_for_config(&plugins_input).await;
|
||||
let plugin_skill_snapshots =
|
||||
plugins_manager.plugin_skill_snapshots_for_config(&plugins_input);
|
||||
let skills_input = codex_skills_extension::HostSkillsLoadInput::new(
|
||||
config.cwd.clone(),
|
||||
plugins.effective_plugin_skill_roots(),
|
||||
config.config_layer_stack,
|
||||
)
|
||||
.with_plugin_skill_snapshots(plugin_skill_snapshots);
|
||||
let skills_input = match self
|
||||
.thread_manager
|
||||
.environment_manager()
|
||||
.default_environment_id()
|
||||
{
|
||||
Some(environment_id) => skills_input.with_environment_id(environment_id),
|
||||
None => skills_input,
|
||||
};
|
||||
let snapshot = skills_request
|
||||
.snapshot_for_cwd(&skills_input, force_reload, fs)
|
||||
.await;
|
||||
let outcome = snapshot.outcome();
|
||||
let errors = errors_to_info(&outcome.errors);
|
||||
let skills = skills_to_info(&outcome.skills, &outcome.disabled_paths);
|
||||
(
|
||||
index,
|
||||
codex_app_server_protocol::SkillsListEntry {
|
||||
cwd,
|
||||
skills,
|
||||
errors,
|
||||
},
|
||||
)
|
||||
}
|
||||
})
|
||||
.buffer_unordered(SKILLS_LIST_CWD_CONCURRENCY)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
data.sort_unstable_by_key(|(index, _)| *index);
|
||||
let data = data.into_iter().map(|(_, entry)| entry).collect();
|
||||
Ok(SkillsListResponse { data })
|
||||
}
|
||||
|
||||
async fn skills_extra_roots_set_response(
|
||||
&self,
|
||||
params: SkillsExtraRootsSetParams,
|
||||
) -> Result<SkillsExtraRootsSetResponse, JSONRPCErrorError> {
|
||||
let SkillsExtraRootsSetParams { extra_roots } = params;
|
||||
self.skills_watcher
|
||||
.register_runtime_extra_roots(&extra_roots);
|
||||
self.thread_manager
|
||||
.skills_service()
|
||||
.set_extra_roots(extra_roots);
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::SkillsChanged(
|
||||
codex_app_server_protocol::SkillsChangedNotification {},
|
||||
))
|
||||
.await;
|
||||
Ok(SkillsExtraRootsSetResponse {})
|
||||
}
|
||||
|
||||
/// Resolve a loaded thread's hook inventory, or inspect configuration for each requested cwd.
|
||||
async fn hooks_list_response(
|
||||
&self,
|
||||
params: HooksListParams,
|
||||
) -> Result<HooksListResponse, JSONRPCErrorError> {
|
||||
let HooksListParams { cwds, thread_id } = params;
|
||||
if let Some(thread_id) = thread_id {
|
||||
if !cwds.is_empty() {
|
||||
return Err(invalid_request("specify either threadId or cwds"));
|
||||
}
|
||||
let thread_id = ThreadId::from_string(&thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
|
||||
let thread = self
|
||||
.thread_manager
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
|
||||
let cwd = thread.config_snapshot().await.cwd().to_path_buf();
|
||||
let hooks = thread.list_hooks();
|
||||
return Ok(HooksListResponse {
|
||||
data: vec![codex_app_server_protocol::HooksListEntry {
|
||||
cwd,
|
||||
hooks: hooks_to_info(&hooks.hooks),
|
||||
warnings: hooks.warnings,
|
||||
errors: Vec::new(),
|
||||
}],
|
||||
});
|
||||
}
|
||||
|
||||
let cwds = if cwds.is_empty() {
|
||||
vec![self.config.cwd.to_path_buf()]
|
||||
} else {
|
||||
cwds
|
||||
};
|
||||
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
let mut data = Vec::new();
|
||||
for cwd in cwds {
|
||||
let config = match self
|
||||
.config_manager
|
||||
.load_for_cwd(
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides::default(),
|
||||
Some(cwd.clone()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(config) => config,
|
||||
Err(err) => {
|
||||
let error_path = cwd.clone();
|
||||
data.push(codex_app_server_protocol::HooksListEntry {
|
||||
cwd,
|
||||
hooks: Vec::new(),
|
||||
warnings: Vec::new(),
|
||||
errors: vec![codex_app_server_protocol::HookErrorInfo {
|
||||
path: error_path,
|
||||
message: err.to_string(),
|
||||
}],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let hooks_enabled = config.features.enabled(Feature::CodexHooks);
|
||||
let plugin_hooks = if hooks_enabled && config.features.enabled(Feature::Plugins) {
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let plugin_outcome = plugins_manager.plugins_for_config(&plugins_input).await;
|
||||
codex_core_plugins::PluginHookLoadOutcome {
|
||||
hook_sources: plugin_outcome.effective_plugin_hook_sources(),
|
||||
hook_load_warnings: plugin_outcome.effective_plugin_hook_warnings(),
|
||||
}
|
||||
} else {
|
||||
codex_core_plugins::PluginHookLoadOutcome::default()
|
||||
};
|
||||
let hooks_config = codex_hooks::HooksConfig {
|
||||
feature_enabled: hooks_enabled,
|
||||
bypass_hook_trust: config.bypass_hook_trust,
|
||||
config_layer_stack: Some(config.config_layer_stack),
|
||||
plugin_hook_sources: plugin_hooks.hook_sources,
|
||||
plugin_hook_load_warnings: plugin_hooks.hook_load_warnings,
|
||||
..Default::default()
|
||||
};
|
||||
let hooks = tokio::task::spawn_blocking(move || codex_hooks::list_hooks(hooks_config))
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("hook discovery task failed: {err}")))?;
|
||||
data.push(codex_app_server_protocol::HooksListEntry {
|
||||
cwd,
|
||||
hooks: hooks_to_info(&hooks.hooks),
|
||||
warnings: hooks.warnings,
|
||||
errors: Vec::new(),
|
||||
});
|
||||
}
|
||||
Ok(HooksListResponse { data })
|
||||
}
|
||||
|
||||
async fn skills_config_write_response_inner(
|
||||
&self,
|
||||
params: SkillsConfigWriteParams,
|
||||
) -> Result<SkillsConfigWriteResponse, JSONRPCErrorError> {
|
||||
let SkillsConfigWriteParams {
|
||||
path,
|
||||
name,
|
||||
enabled,
|
||||
} = params;
|
||||
let edit = match (path, name) {
|
||||
(Some(path), None) => ConfigEdit::SetSkillConfig {
|
||||
path: path.into_path_buf(),
|
||||
enabled,
|
||||
},
|
||||
(None, Some(name)) if !name.trim().is_empty() => {
|
||||
ConfigEdit::SetSkillConfigByName { name, enabled }
|
||||
}
|
||||
_ => {
|
||||
return Err(invalid_params(
|
||||
"skills/config/write requires exactly one of path or name",
|
||||
));
|
||||
}
|
||||
};
|
||||
let edits = vec![edit];
|
||||
ConfigEditsBuilder::new(&self.config.codex_home)
|
||||
.with_edits(edits)
|
||||
.apply()
|
||||
.await
|
||||
.map(|()| {
|
||||
self.thread_manager.plugins_manager().clear_cache();
|
||||
self.thread_manager.skills_service().clear_cache();
|
||||
SkillsConfigWriteResponse {
|
||||
effective_enabled: enabled,
|
||||
}
|
||||
})
|
||||
.map_err(|err| internal_error(format!("failed to update skill settings: {err}")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
use super::*;
|
||||
use codex_core::exec_env::inject_apply_patch_env;
|
||||
use codex_core::windows_sandbox::local_binding_policy_for_sandbox;
|
||||
use codex_core::windows_sandbox::managed_proxy_routing_for_windows_sandbox;
|
||||
use codex_protocol::shell_environment::is_non_inheritable_env_var;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CommandExecRequestProcessor {
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
config: Arc<Config>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
command_exec_manager: CommandExecManager,
|
||||
}
|
||||
|
||||
impl CommandExecRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
config: Arc<Config>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
) -> Self {
|
||||
Self {
|
||||
arg0_paths,
|
||||
config,
|
||||
outgoing,
|
||||
config_manager,
|
||||
environment_manager,
|
||||
command_exec_manager: CommandExecManager::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn one_off_command_exec(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: CommandExecParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.require_local_environment()?;
|
||||
self.exec_one_off_command(request_id, params)
|
||||
.await
|
||||
.map(|()| None)
|
||||
}
|
||||
|
||||
pub(crate) async fn command_exec_write(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: CommandExecWriteParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.command_exec_manager
|
||||
.write(request_id, params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn command_exec_resize(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: CommandExecResizeParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.command_exec_manager
|
||||
.resize(request_id, params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn command_exec_terminate(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: CommandExecTerminateParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.command_exec_manager
|
||||
.terminate(request_id, params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn connection_closed(&self, connection_id: ConnectionId) {
|
||||
self.command_exec_manager
|
||||
.connection_closed(connection_id)
|
||||
.await;
|
||||
}
|
||||
|
||||
fn require_local_environment(&self) -> Result<(), JSONRPCErrorError> {
|
||||
self.environment_manager
|
||||
.try_local_environment()
|
||||
.is_some()
|
||||
.then_some(())
|
||||
.ok_or_else(|| internal_error("local environment is not configured"))
|
||||
}
|
||||
|
||||
async fn exec_one_off_command(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: CommandExecParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
self.exec_one_off_command_inner(request_id.clone(), params)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn exec_one_off_command_inner(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: CommandExecParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
tracing::debug!("ExecOneOffCommand params: {params:?}");
|
||||
|
||||
let request = request_id.clone();
|
||||
|
||||
if params.command.is_empty() {
|
||||
return Err(invalid_request("command must not be empty"));
|
||||
}
|
||||
|
||||
let CommandExecParams {
|
||||
command,
|
||||
process_id,
|
||||
tty,
|
||||
stream_stdin,
|
||||
stream_stdout_stderr,
|
||||
output_bytes_cap,
|
||||
disable_output_cap,
|
||||
disable_timeout,
|
||||
timeout_ms,
|
||||
cwd,
|
||||
env: env_overrides,
|
||||
size,
|
||||
sandbox_policy,
|
||||
permission_profile,
|
||||
} = params;
|
||||
if sandbox_policy.is_some() && permission_profile.is_some() {
|
||||
return Err(invalid_request(
|
||||
"`permissionProfile` cannot be combined with `sandboxPolicy`",
|
||||
));
|
||||
}
|
||||
|
||||
if size.is_some() && !tty {
|
||||
return Err(invalid_params("command/exec size requires tty: true"));
|
||||
}
|
||||
|
||||
if disable_output_cap && output_bytes_cap.is_some() {
|
||||
return Err(invalid_params(
|
||||
"command/exec cannot set both outputBytesCap and disableOutputCap",
|
||||
));
|
||||
}
|
||||
|
||||
if disable_timeout && timeout_ms.is_some() {
|
||||
return Err(invalid_params(
|
||||
"command/exec cannot set both timeoutMs and disableTimeout",
|
||||
));
|
||||
}
|
||||
|
||||
let cwd = cwd.map_or_else(|| self.config.cwd.clone(), |cwd| self.config.cwd.join(cwd));
|
||||
let mut env = create_env(
|
||||
&self.config.permissions.shell_environment_policy,
|
||||
/*thread_id*/ None,
|
||||
);
|
||||
if let Some(env_overrides) = env_overrides {
|
||||
for (key, value) in env_overrides {
|
||||
match value {
|
||||
Some(value) => {
|
||||
env.insert(key, value);
|
||||
}
|
||||
None => {
|
||||
env.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
env.retain(|name, _| !is_non_inheritable_env_var(name));
|
||||
inject_apply_patch_env(&mut env);
|
||||
let timeout_ms = match timeout_ms {
|
||||
Some(timeout_ms) => match u64::try_from(timeout_ms) {
|
||||
Ok(timeout_ms) => Some(timeout_ms),
|
||||
Err(_) => {
|
||||
return Err(invalid_params(format!(
|
||||
"command/exec timeoutMs must be non-negative, got {timeout_ms}"
|
||||
)));
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config);
|
||||
let output_bytes_cap = if disable_output_cap {
|
||||
None
|
||||
} else {
|
||||
Some(output_bytes_cap.unwrap_or(DEFAULT_OUTPUT_BYTES_CAP))
|
||||
};
|
||||
let expiration = if disable_timeout {
|
||||
ExecExpiration::Cancellation(CancellationToken::new())
|
||||
} else {
|
||||
match timeout_ms {
|
||||
Some(timeout_ms) => timeout_ms.into(),
|
||||
None => ExecExpiration::DefaultTimeout,
|
||||
}
|
||||
};
|
||||
let capture_policy = if disable_output_cap {
|
||||
ExecCapturePolicy::FullBuffer
|
||||
} else {
|
||||
ExecCapturePolicy::ShellTool
|
||||
};
|
||||
let sandbox_cwd = if permission_profile.is_some() {
|
||||
cwd.clone()
|
||||
} else {
|
||||
self.config.cwd.clone()
|
||||
};
|
||||
let (
|
||||
effective_permission_profile,
|
||||
network_proxy_spec,
|
||||
network_proxy_permission_profile,
|
||||
managed_network_requirements_enabled,
|
||||
windows_sandbox_workspace_roots,
|
||||
) = if let Some(permission_profile) = permission_profile {
|
||||
let overrides = ConfigOverrides {
|
||||
cwd: Some(cwd.to_path_buf()),
|
||||
default_permissions: Some(permission_profile),
|
||||
..Default::default()
|
||||
};
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_for_cwd(
|
||||
/*request_overrides*/ None,
|
||||
overrides,
|
||||
Some(self.config.cwd.to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| invalid_request(format!("invalid permission profile: {err}")))?;
|
||||
if let Some(warning) = config.startup_warnings.iter().find(|warning| {
|
||||
warning.contains("Configured value for `permission_profile` is disallowed")
|
||||
}) {
|
||||
return Err(invalid_request(format!(
|
||||
"invalid permission profile: {warning}"
|
||||
)));
|
||||
}
|
||||
(
|
||||
config.permissions.effective_permission_profile(),
|
||||
config.permissions.network.clone(),
|
||||
config.permissions.permission_profile().clone(),
|
||||
config.managed_network_requirements_enabled(),
|
||||
config.effective_workspace_roots(),
|
||||
)
|
||||
} else if let Some(policy) = sandbox_policy.map(|policy| policy.to_core()) {
|
||||
let mut permissions = self.config.permissions.clone();
|
||||
permissions
|
||||
.set_legacy_sandbox_policy(policy, &sandbox_cwd)
|
||||
.map_err(|err| invalid_request(format!("invalid sandbox policy: {err}")))?;
|
||||
(
|
||||
permissions.effective_permission_profile(),
|
||||
self.config.permissions.network.clone(),
|
||||
self.config.permissions.permission_profile().clone(),
|
||||
self.config.managed_network_requirements_enabled(),
|
||||
self.config.effective_workspace_roots(),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
self.config.permissions.effective_permission_profile(),
|
||||
self.config.permissions.network.clone(),
|
||||
self.config.permissions.permission_profile().clone(),
|
||||
self.config.managed_network_requirements_enabled(),
|
||||
self.config.effective_workspace_roots(),
|
||||
)
|
||||
};
|
||||
let started_network_proxy = match network_proxy_spec.as_ref() {
|
||||
Some(spec) => match spec
|
||||
.start_proxy(
|
||||
&network_proxy_permission_profile,
|
||||
managed_proxy_routing_for_windows_sandbox(
|
||||
self.config.effective_local_windows_sandbox_type(),
|
||||
),
|
||||
local_binding_policy_for_sandbox(
|
||||
self.config.effective_local_windows_sandbox_type(),
|
||||
Some(std::env::consts::OS),
|
||||
),
|
||||
/*policy_decider*/ None,
|
||||
/*blocked_request_observer*/ None,
|
||||
managed_network_requirements_enabled,
|
||||
NetworkProxyAuditMetadata::default(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(started) => Some(started),
|
||||
Err(err) => {
|
||||
return Err(internal_error(format!(
|
||||
"failed to start managed network proxy: {err}"
|
||||
)));
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let exec_params = ExecParams {
|
||||
command,
|
||||
cwd: cwd.clone(),
|
||||
expiration,
|
||||
capture_policy,
|
||||
env,
|
||||
network: started_network_proxy
|
||||
.as_ref()
|
||||
.map(codex_core::config::StartedNetworkProxy::proxy),
|
||||
network_environment_id: None,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
windows_sandbox_level,
|
||||
justification: None,
|
||||
arg0: None,
|
||||
};
|
||||
|
||||
let codex_linux_sandbox_exe = self.arg0_paths.codex_linux_sandbox_exe.clone();
|
||||
let outgoing = self.outgoing.clone();
|
||||
let request_for_task = request.clone();
|
||||
let started_network_proxy_for_task = started_network_proxy;
|
||||
let use_legacy_landlock = self.config.features.use_legacy_landlock();
|
||||
let size = match size.map(crate::command_exec::terminal_size_from_protocol) {
|
||||
Some(Ok(size)) => Some(size),
|
||||
Some(Err(error)) => return Err(error),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let exec_request = codex_core::exec::build_exec_request(
|
||||
exec_params,
|
||||
&effective_permission_profile,
|
||||
&sandbox_cwd,
|
||||
windows_sandbox_workspace_roots.as_slice(),
|
||||
&codex_linux_sandbox_exe,
|
||||
&self.arg0_paths.codex_self_exe,
|
||||
self.config.effective_local_windows_sandbox_type(),
|
||||
use_legacy_landlock,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("exec failed: {err}")))?;
|
||||
self.command_exec_manager
|
||||
.start(StartCommandExecParams {
|
||||
outgoing,
|
||||
request_id: request_for_task,
|
||||
process_id,
|
||||
exec_request,
|
||||
started_network_proxy: started_network_proxy_for_task,
|
||||
tty,
|
||||
stream_stdin,
|
||||
stream_stdout_stderr,
|
||||
output_bytes_cap,
|
||||
size,
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
50
codex-rs/app-server/src/request_processors/config_errors.rs
Normal file
50
codex-rs/app-server/src/request_processors/config_errors.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use super::*;
|
||||
|
||||
fn cloud_config_bundle_load_error(err: &std::io::Error) -> Option<&CloudConfigBundleLoadError> {
|
||||
let mut current: Option<&(dyn std::error::Error + 'static)> = err
|
||||
.get_ref()
|
||||
.map(|source| source as &(dyn std::error::Error + 'static));
|
||||
while let Some(source) = current {
|
||||
if let Some(cloud_error) = source.downcast_ref::<CloudConfigBundleLoadError>() {
|
||||
return Some(cloud_error);
|
||||
}
|
||||
current = source.source();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(super) fn model_provider_error(provider: &ModelProviderError) -> JSONRPCErrorError {
|
||||
let mut error = invalid_request(provider.to_string());
|
||||
error.data = serde_json::to_value(provider).ok();
|
||||
error
|
||||
}
|
||||
|
||||
pub(crate) fn config_load_error(err: &std::io::Error) -> JSONRPCErrorError {
|
||||
let mut current = err
|
||||
.get_ref()
|
||||
.map(|error| error as &(dyn std::error::Error + 'static));
|
||||
while let Some(source) = current {
|
||||
if let Some(provider_error) = source.downcast_ref::<ModelProviderError>() {
|
||||
return model_provider_error(provider_error);
|
||||
}
|
||||
current = source.source();
|
||||
}
|
||||
let data = cloud_config_bundle_load_error(err).map(|cloud_error| {
|
||||
let mut data = serde_json::json!({
|
||||
"reason": "cloudConfigBundle",
|
||||
"errorCode": format!("{:?}", cloud_error.code()),
|
||||
"detail": cloud_error.to_string(),
|
||||
});
|
||||
if let Some(status_code) = cloud_error.status_code() {
|
||||
data["statusCode"] = serde_json::json!(status_code);
|
||||
}
|
||||
if cloud_error.code() == CloudConfigBundleLoadErrorCode::Auth {
|
||||
data["action"] = serde_json::json!("relogin");
|
||||
}
|
||||
data
|
||||
});
|
||||
|
||||
let mut error = invalid_request(format!("failed to load configuration: {err}"));
|
||||
error.data = data;
|
||||
error
|
||||
}
|
||||
1358
codex-rs/app-server/src/request_processors/config_processor.rs
Normal file
1358
codex-rs/app-server/src/request_processors/config_processor.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,252 @@
|
||||
//! Regressions for reload entry points composing the final thread configuration.
|
||||
|
||||
use super::config_processor::reload_user_config;
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::mcp_refresh::reload_mcp_config;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_login::CodexAuth;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[tokio::test]
|
||||
async fn reloads_accept_a_provider_supplied_by_thread_overrides() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let manager = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf());
|
||||
let initial = manager
|
||||
.load_for_cwd(
|
||||
Some(HashMap::from([
|
||||
("model_provider".to_string(), json!("thread-provider")),
|
||||
(
|
||||
"model_providers.thread-provider".to_string(),
|
||||
json!({"name": "Thread provider", "base_url": "https://provider.example/v1", "wire_api": "responses"}),
|
||||
),
|
||||
])),
|
||||
ConfigOverrides::default(),
|
||||
Some(home.path().to_path_buf()),
|
||||
)
|
||||
.await?;
|
||||
let threads = Arc::new(
|
||||
codex_core::test_support::thread_manager_with_models_provider_and_home(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
initial.model_provider.clone(),
|
||||
initial.codex_home.to_path_buf(),
|
||||
Arc::new(EnvironmentManager::default_for_tests()),
|
||||
),
|
||||
);
|
||||
let thread = threads
|
||||
.start_thread(codex_core::StartThreadOptions::new(initial))
|
||||
.await?
|
||||
.thread;
|
||||
|
||||
for enabled in [true, false] {
|
||||
std::fs::write(
|
||||
home.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
format!(
|
||||
"model_provider = 'missing-provider'\n[features]\nsecret_auth_storage = {enabled}\n"
|
||||
),
|
||||
)?;
|
||||
if enabled {
|
||||
reload_mcp_config(&threads, &manager).await?;
|
||||
} else {
|
||||
reload_user_config(&manager, &threads).await;
|
||||
}
|
||||
let config = thread.config().await;
|
||||
assert_eq!(config.model_provider_id, "thread-provider");
|
||||
assert_eq!(
|
||||
config.auth_keyring_backend_kind(),
|
||||
if enabled {
|
||||
AuthKeyringBackendKind::Secrets
|
||||
} else {
|
||||
AuthKeyringBackendKind::Direct
|
||||
}
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn user_reload_promotes_plugin_and_feature_requirements_without_server_changes()
|
||||
-> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let requirements_path = home.path().join("requirements.toml");
|
||||
std::fs::write(&requirements_path, "")?;
|
||||
std::fs::write(
|
||||
home.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
"[features]\nenable_mcp_apps = true\n",
|
||||
)?;
|
||||
let mut overrides = codex_config::LoaderOverrides::without_managed_config_for_tests();
|
||||
overrides.ignore_managed_requirements = false;
|
||||
overrides.system_requirements_path = Some(requirements_path.clone());
|
||||
let manager = ConfigManager::new(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
overrides,
|
||||
/*strict_config*/ false,
|
||||
codex_config::CloudConfigBundleLoader::default(),
|
||||
codex_arg0::Arg0DispatchPaths::default(),
|
||||
Arc::new(codex_config::NoopThreadConfigLoader),
|
||||
);
|
||||
let initial = manager
|
||||
.load_latest_config(Some(home.path().to_path_buf()))
|
||||
.await?;
|
||||
let threads = Arc::new(
|
||||
codex_core::test_support::thread_manager_with_models_provider_and_home(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
initial.model_provider.clone(),
|
||||
initial.codex_home.to_path_buf(),
|
||||
Arc::new(EnvironmentManager::default_for_tests()),
|
||||
),
|
||||
);
|
||||
assert!(
|
||||
initial
|
||||
.features
|
||||
.enabled(codex_features::Feature::EnableMcpApps)
|
||||
);
|
||||
let original_servers = initial.mcp_servers.get().clone();
|
||||
let thread = threads
|
||||
.start_thread(codex_core::StartThreadOptions::new(initial))
|
||||
.await?
|
||||
.thread;
|
||||
std::fs::write(
|
||||
&requirements_path,
|
||||
"[features]\nenable_mcp_apps = false\n[plugins.example.mcp_servers]\n",
|
||||
)?;
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(10),
|
||||
reload_user_config(&manager, &threads),
|
||||
)
|
||||
.await
|
||||
.expect("policy promotion must terminate");
|
||||
let config = thread.config().await;
|
||||
assert_eq!(config.mcp_servers.get(), &original_servers);
|
||||
assert!(
|
||||
!config
|
||||
.features
|
||||
.enabled(codex_features::Feature::EnableMcpApps)
|
||||
);
|
||||
assert!(
|
||||
config
|
||||
.config_layer_stack
|
||||
.requirements()
|
||||
.plugins
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.value
|
||||
.get("example")
|
||||
.unwrap()
|
||||
.mcp_servers
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
config
|
||||
.config_layer_stack
|
||||
.requirements()
|
||||
.feature_requirements
|
||||
.is_some()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case::test_case(codex_config::CloudConfigBundleBindingStatus::Stale)]
|
||||
#[test_case::test_case(codex_config::CloudConfigBundleBindingStatus::Suspended)]
|
||||
#[tokio::test]
|
||||
async fn mcp_refresh_rejects_superseded_app_server_policy(
|
||||
status: codex_config::CloudConfigBundleBindingStatus,
|
||||
) -> anyhow::Result<()> {
|
||||
use codex_config::CloudConfigBundle;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::CloudConfigBundlePolicy;
|
||||
use codex_config::CloudConfigBundleSnapshot;
|
||||
use codex_core::ConfigRefreshOutcome;
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let policy = CloudConfigBundlePolicy::default();
|
||||
let mut snapshot = CloudConfigBundleSnapshot {
|
||||
config_server: None,
|
||||
bundle: Ok(None),
|
||||
binding: None,
|
||||
};
|
||||
policy.publish_snapshot(&mut snapshot);
|
||||
let loader =
|
||||
CloudConfigBundleLoader::default().with_ema_policy_snapshots(policy.clone(), move || {
|
||||
let snapshot = snapshot.clone();
|
||||
async move { snapshot }
|
||||
});
|
||||
let manager = ConfigManager::new(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
codex_config::LoaderOverrides::without_managed_config_for_tests(),
|
||||
/*strict_config*/ false,
|
||||
loader,
|
||||
codex_arg0::Arg0DispatchPaths::default(),
|
||||
Arc::new(codex_config::NoopThreadConfigLoader),
|
||||
);
|
||||
let initial = manager
|
||||
.load_latest_config(Some(home.path().to_path_buf()))
|
||||
.await?;
|
||||
let threads = codex_core::test_support::thread_manager_with_models_provider_and_home(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
initial.model_provider.clone(),
|
||||
initial.codex_home.to_path_buf(),
|
||||
Arc::new(EnvironmentManager::default_for_tests()),
|
||||
);
|
||||
let thread = threads
|
||||
.start_thread(codex_core::StartThreadOptions::new(initial))
|
||||
.await?
|
||||
.thread;
|
||||
let current = thread.config().await;
|
||||
let next = manager
|
||||
.load_latest_config_with_session_layers(¤t.config_layer_stack, ¤t.cwd)
|
||||
.await?;
|
||||
let mut replacement = CloudConfigBundle::default();
|
||||
replacement
|
||||
.config_toml
|
||||
.enterprise_managed
|
||||
.push(codex_config::CloudConfigFragment {
|
||||
id: "replacement".into(),
|
||||
name: "replacement".into(),
|
||||
contents: "model = 'replacement-model'".into(),
|
||||
});
|
||||
policy.observe_remote_bundle(&replacement);
|
||||
if status == codex_config::CloudConfigBundleBindingStatus::Stale {
|
||||
policy.publish_snapshot(&mut CloudConfigBundleSnapshot {
|
||||
config_server: None,
|
||||
bundle: Ok(Some(replacement)),
|
||||
binding: None,
|
||||
});
|
||||
}
|
||||
assert_eq!(
|
||||
next.config_layer_stack
|
||||
.cloud_config_binding()
|
||||
.expect("app-server must retain the policy binding")
|
||||
.read()
|
||||
.status,
|
||||
status,
|
||||
);
|
||||
let outcome = thread.refresh_mcp_config(Arc::clone(¤t), next).await;
|
||||
let expected = match status {
|
||||
codex_config::CloudConfigBundleBindingStatus::Stale => ConfigRefreshOutcome::Stale,
|
||||
codex_config::CloudConfigBundleBindingStatus::Suspended => ConfigRefreshOutcome::Rejected,
|
||||
codex_config::CloudConfigBundleBindingStatus::Current => unreachable!(),
|
||||
};
|
||||
assert_eq!(outcome, expected);
|
||||
if status == codex_config::CloudConfigBundleBindingStatus::Stale {
|
||||
assert!(Arc::ptr_eq(¤t, &thread.config().await));
|
||||
} else {
|
||||
assert!(
|
||||
thread
|
||||
.config()
|
||||
.await
|
||||
.config_layer_stack
|
||||
.cloud_config_binding()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! Attempts one new continuation turn immediately after daemon thread restoration.
|
||||
//! Completed or superseded work is discarded; recovery never waits for a later idle event.
|
||||
//! Permissions and the saved local executor selection must match the resumed runtime.
|
||||
|
||||
use super::ThreadRequestProcessor;
|
||||
use codex_app_server_protocol::ThreadEnvironment;
|
||||
use codex_app_server_transport::daemon_recovery::InterruptedTurn;
|
||||
use codex_core::TurnInput;
|
||||
use codex_core::TurnInputRequest;
|
||||
use codex_core::TurnInputSubmission;
|
||||
use codex_core::TurnStartOptions;
|
||||
use codex_core::context::ContextualUserFragment;
|
||||
use codex_core::context::InternalContextSource;
|
||||
use codex_core::context::InternalModelContextFragment;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::EnvironmentConfigState;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::TurnAbortReason;
|
||||
use codex_protocol::protocol::TurnAbortedEvent;
|
||||
use codex_rollout::RolloutItem;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
pub(crate) async fn continue_daemon_turn(&self, thread_id: &str, saved: InterruptedTurn) {
|
||||
let Ok(thread_id) = ThreadId::from_string(thread_id) else {
|
||||
return;
|
||||
};
|
||||
let Ok(thread) = self.thread_manager.get_thread(thread_id).await else {
|
||||
return;
|
||||
};
|
||||
let Some(path) = thread.rollout_path() else {
|
||||
return;
|
||||
};
|
||||
let history = match codex_rollout::RolloutRecorder::load_rollout_items(&path).await {
|
||||
Ok((history, _, _)) => history,
|
||||
Err(err) => {
|
||||
tracing::warn!(%thread_id, %err, "failed to read interrupted turn history");
|
||||
return;
|
||||
}
|
||||
};
|
||||
// The snapshot has complete recorded input, but the old process may have
|
||||
// completed or replaced its turn during the shutdown grace period.
|
||||
let Some(start) = history
|
||||
.iter()
|
||||
.rposition(|item| matches!(item, RolloutItem::EventMsg(EventMsg::TurnStarted(_))))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if !matches!(&history[start], RolloutItem::EventMsg(EventMsg::TurnStarted(event))
|
||||
if event.turn_id == saved.turn_id)
|
||||
|| history[start..].iter().any(|item| match item {
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => {
|
||||
event.turn_id == saved.turn_id
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TurnAborted(event)) => event
|
||||
.turn_id
|
||||
.as_ref()
|
||||
.is_none_or(|turn_id| turn_id == &saved.turn_id),
|
||||
_ => false,
|
||||
})
|
||||
{
|
||||
return;
|
||||
}
|
||||
let previous_context = history.iter().rev().find_map(|item| match item {
|
||||
RolloutItem::TurnContext(context)
|
||||
if context.turn_id.as_ref() == Some(&saved.turn_id) =>
|
||||
{
|
||||
Some(context)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let Some(previous_context) = previous_context else {
|
||||
return;
|
||||
};
|
||||
let config = thread.config_snapshot().await;
|
||||
let [environment] = config.environment_selections() else {
|
||||
return;
|
||||
};
|
||||
if environment.environment_id != codex_exec_server::LOCAL_ENVIRONMENT_ID
|
||||
|| environment.config != EnvironmentConfigState::FromThread
|
||||
|| saved.local_environment.as_ref() != Some(&ThreadEnvironment::from(environment))
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Recovery must not override a stricter saved or newly configured policy.
|
||||
if previous_context.permission_profile != config.permission_profile {
|
||||
return;
|
||||
}
|
||||
let continuation = ContextualUserFragment::into(InternalModelContextFragment::new(
|
||||
InternalContextSource::from_static("daemon_recovery"),
|
||||
"The server restarted and interrupted the previous turn. Continue the unfinished work from the saved conversation. Check the current state before repeating actions that may already have completed.",
|
||||
));
|
||||
let request = TurnInputRequest::new(TurnInput::ResponseItem(continuation)).on_start(
|
||||
TurnStartOptions {
|
||||
turn_trigger: Some("daemon_recovery".to_string()),
|
||||
final_output_json_schema: saved.output_schema,
|
||||
service_tier: saved.service_tier,
|
||||
cyber_access_program: saved.cyber_access_program,
|
||||
root_turn_id: previous_context.root_turn_id.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
// Close the old turn in persisted history before exposing a new running turn.
|
||||
if let Err(err) = thread
|
||||
.append_rollout_items(&[RolloutItem::EventMsg(EventMsg::TurnAborted(
|
||||
TurnAbortedEvent {
|
||||
root_turn_id: None,
|
||||
turn_id: Some(saved.turn_id.clone()),
|
||||
reason: TurnAbortReason::Interrupted,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
))])
|
||||
.await
|
||||
{
|
||||
tracing::warn!(%thread_id, %err, "failed to close interrupted turn history");
|
||||
return;
|
||||
}
|
||||
match thread.continue_turn_if_idle(request, saved.turn_id).await {
|
||||
Ok(TurnInputSubmission::Started { .. }) => {
|
||||
crate::extensions::send_thread_warning(
|
||||
&self.outgoing,
|
||||
&self.thread_state_manager,
|
||||
thread_id,
|
||||
"Resuming interrupted work".to_string(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Ok(TurnInputSubmission::NotSubmitted { reason }) => {
|
||||
tracing::debug!(%thread_id, ?reason, "recovery continuation was not started");
|
||||
}
|
||||
Ok(TurnInputSubmission::Steered { .. } | TurnInputSubmission::Accepted) => {
|
||||
// continue_turn_if_idle uses start_if_idle, which cannot steer or
|
||||
// enter the agent-message path that returns Accepted.
|
||||
unreachable!("continuation must start or decline")
|
||||
}
|
||||
Err(err) => tracing::warn!(%thread_id, %err, "recovery continuation failed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//! Selects persistent root threads for managed daemon recovery using normal resume semantics.
|
||||
//! Only threads successfully persisted through the existing thread store become candidates.
|
||||
|
||||
use super::ThreadRequestProcessor;
|
||||
use codex_app_server_transport::daemon_recovery::InterruptedTurn;
|
||||
use codex_app_server_transport::daemon_recovery::RecoverySnapshot;
|
||||
use codex_thread_store::PersistContext;
|
||||
use tracing::warn;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "snapshot selection must be serialized against pending unloads"
|
||||
)]
|
||||
pub(crate) async fn daemon_recovery_snapshot(&self) -> RecoverySnapshot {
|
||||
let mut snapshot = RecoverySnapshot::default();
|
||||
for thread_id in self.thread_manager.list_thread_ids().await {
|
||||
let pending_unloads = self.pending_thread_unloads.lock().await;
|
||||
if pending_unloads.contains_key(&thread_id) {
|
||||
continue;
|
||||
}
|
||||
let Ok(thread) = self.thread_manager.get_thread(thread_id).await else {
|
||||
continue;
|
||||
};
|
||||
let config = thread.config_snapshot().await;
|
||||
if !config.ephemeral
|
||||
&& config.parent_thread_id.is_none()
|
||||
&& !config.session_source.is_non_root_agent()
|
||||
{
|
||||
let interrupted = thread.interrupted_turn().await;
|
||||
if let Err(err) = self
|
||||
.thread_store
|
||||
.persist_thread(thread_id, PersistContext::Standard)
|
||||
.await
|
||||
{
|
||||
warn!(%thread_id, %err, "skipping daemon restore for thread that could not be persisted");
|
||||
continue;
|
||||
}
|
||||
snapshot.loaded.insert(thread_id.to_string());
|
||||
if let Some((turn_id, options, environment)) = interrupted {
|
||||
snapshot.interrupted.insert(
|
||||
thread_id.to_string(),
|
||||
InterruptedTurn {
|
||||
turn_id,
|
||||
output_schema: options.final_output_json_schema,
|
||||
service_tier: options.service_tier,
|
||||
cyber_access_program: options.cyber_access_program,
|
||||
local_environment: Some((&environment).into()),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
}
|
||||
23
codex-rs/app-server/src/request_processors/diagnostics.rs
Normal file
23
codex-rs/app-server/src/request_processors/diagnostics.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use codex_app_server_protocol::ServerDiagnosticsGauge;
|
||||
use codex_app_server_protocol::ServerDiagnosticsProcess;
|
||||
use codex_app_server_protocol::ServerDiagnosticsResponse;
|
||||
|
||||
pub(crate) fn read_server_diagnostics() -> ServerDiagnosticsResponse {
|
||||
let diagnostics = codex_diagnostics::snapshot();
|
||||
|
||||
ServerDiagnosticsResponse {
|
||||
process: ServerDiagnosticsProcess {
|
||||
id: diagnostics.process.id,
|
||||
resident_memory_bytes: diagnostics.process.resident_memory_bytes,
|
||||
physical_footprint_bytes: diagnostics.process.physical_footprint_bytes,
|
||||
},
|
||||
gauges: diagnostics
|
||||
.gauges
|
||||
.into_iter()
|
||||
.map(|gauge| ServerDiagnosticsGauge {
|
||||
name: gauge.name.to_string(),
|
||||
value: gauge.value,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
use super::*;
|
||||
use codex_config::ScopedSkillsConfig;
|
||||
use codex_exec_server::RemoteEnvironmentOptions;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct EnvironmentRequestProcessor {
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
}
|
||||
|
||||
impl EnvironmentRequestProcessor {
|
||||
pub(crate) fn new(environment_manager: Arc<EnvironmentManager>) -> Self {
|
||||
Self {
|
||||
environment_manager,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn environment_add(
|
||||
&self,
|
||||
params: EnvironmentAddParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let skills = ScopedSkillsConfig {
|
||||
required: params
|
||||
.skills
|
||||
.and_then(|skills| skills.required)
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let options = RemoteEnvironmentOptions {
|
||||
exec_server_url: params.exec_server_url,
|
||||
connect_timeout: params.connect_timeout_ms.map(Duration::from_millis),
|
||||
http_headers: params
|
||||
.auth_bearer_token
|
||||
.into_iter()
|
||||
.map(|token| {
|
||||
(
|
||||
"Authorization".to_string(),
|
||||
format!("Bearer {}", token.into_inner()),
|
||||
)
|
||||
})
|
||||
.chain(
|
||||
params
|
||||
.websocket_request_id
|
||||
.map(|request_id| ("X-Request-ID".to_string(), request_id)),
|
||||
)
|
||||
.collect(),
|
||||
};
|
||||
self.environment_manager
|
||||
.upsert_environment_with_options(params.environment_id, options, skills)
|
||||
.map_err(|err| invalid_request(err.to_string()))?;
|
||||
Ok(Some(EnvironmentAddResponse {}.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn environment_info(
|
||||
&self,
|
||||
params: EnvironmentInfoParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let environment_id = params.environment_id;
|
||||
let environment = self
|
||||
.environment_manager
|
||||
.get_environment(&environment_id)
|
||||
.ok_or_else(|| invalid_request(format!("unknown environment id `{environment_id}`")))?;
|
||||
let info = environment.force_info().await.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to get info for environment `{environment_id}`: {err}"
|
||||
))
|
||||
})?;
|
||||
Ok(Some(
|
||||
EnvironmentInfoResponse {
|
||||
shell: EnvironmentShellInfo {
|
||||
name: info.shell.name,
|
||||
path: info.shell.path,
|
||||
},
|
||||
cwd: info.cwd,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn environment_status(
|
||||
&self,
|
||||
params: EnvironmentStatusParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let environment_id = params.environment_id;
|
||||
let (status, error) = match self
|
||||
.environment_manager
|
||||
.get_environment_status(&environment_id)
|
||||
.await
|
||||
{
|
||||
Some(EnvironmentObservedStatus::Ready) => (EnvironmentStatusKind::Ready, None),
|
||||
Some(EnvironmentObservedStatus::Pending) => (EnvironmentStatusKind::Pending, None),
|
||||
Some(EnvironmentObservedStatus::Disconnected { error }) => {
|
||||
(EnvironmentStatusKind::Disconnected, Some(error))
|
||||
}
|
||||
None => (
|
||||
EnvironmentStatusKind::Unknown,
|
||||
Some(format!("unknown environment id `{environment_id}`")),
|
||||
),
|
||||
};
|
||||
Ok(Some(EnvironmentStatusResponse { status, error }.into()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
//! Builds a redacted doctor report attachment for feedback uploads.
|
||||
//!
|
||||
//! Feedback upload should never depend on doctor succeeding. This module runs
|
||||
//! the configured Codex executable as a subprocess, accepts only valid JSON from
|
||||
//! `codex doctor --json --feedback`, derives a small set of Sentry tags, and otherwise
|
||||
//! skips the attachment with a warning. Keeping the report generation out of the
|
||||
//! app-server process avoids sharing doctor internals across crates while still
|
||||
//! using the CLI's JSON report format with bounded database scans.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_core::config::Config;
|
||||
use codex_feedback::DOCTOR_REPORT_ATTACHMENT_FILENAME;
|
||||
use codex_feedback::FeedbackAttachment;
|
||||
use serde_json::Value;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
use tracing::warn;
|
||||
|
||||
// Keep the existing 25-second diagnostic allowance plus the filesystem
|
||||
// probe budget (eight seconds) and a small amount of process overhead.
|
||||
const DOCTOR_FEEDBACK_REPORT_TIMEOUT: Duration = Duration::from_secs(35);
|
||||
const MAX_DOCTOR_TAG_VALUE_LEN: usize = 256;
|
||||
|
||||
/// Redacted doctor report data that can be merged into a feedback upload.
|
||||
pub(crate) struct DoctorFeedbackReport {
|
||||
/// JSON support report to upload as `codex-doctor-report.json`.
|
||||
pub(crate) attachment: FeedbackAttachment,
|
||||
/// Low-cardinality Sentry tags derived from the report status and check ids.
|
||||
pub(crate) tags: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// Runs `codex --cd <workspace> doctor --json --feedback` and returns a best-effort
|
||||
/// feedback attachment.
|
||||
///
|
||||
/// Failure to spawn Codex, finish before the timeout, or parse JSON means the
|
||||
/// feedback upload proceeds without the doctor report. Callers should merge the
|
||||
/// returned tags without overriding explicit client-provided tags.
|
||||
pub(crate) async fn doctor_feedback_report(
|
||||
config: &Config,
|
||||
workspace: &Path,
|
||||
) -> Option<DoctorFeedbackReport> {
|
||||
let executable = config
|
||||
.codex_self_exe
|
||||
.clone()
|
||||
.or_else(|| std::env::current_exe().ok())?;
|
||||
|
||||
let mut command = doctor_command(&executable, workspace, config.codex_home.as_path());
|
||||
command.stdin(Stdio::null());
|
||||
command.kill_on_drop(/*kill_on_drop*/ true);
|
||||
let output = match timeout(DOCTOR_FEEDBACK_REPORT_TIMEOUT, command.output()).await {
|
||||
Ok(Ok(output)) => output,
|
||||
Ok(Err(err)) => {
|
||||
warn!(
|
||||
executable = %executable.display(),
|
||||
error = %err,
|
||||
"failed to run doctor report for feedback; skipping attachment"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Err(_) => {
|
||||
warn!(
|
||||
executable = %executable.display(),
|
||||
"timed out running doctor report for feedback; skipping attachment"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let Some(json_start) = stdout.find('{') else {
|
||||
warn!(
|
||||
executable = %executable.display(),
|
||||
status = %output.status,
|
||||
stderr = %String::from_utf8_lossy(&output.stderr),
|
||||
"doctor report for feedback did not produce JSON; skipping attachment"
|
||||
);
|
||||
return None;
|
||||
};
|
||||
let json = stdout[json_start..].trim();
|
||||
let report: Value = match serde_json::from_str(json) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
executable = %executable.display(),
|
||||
status = %output.status,
|
||||
error = %err,
|
||||
"doctor report for feedback was not valid JSON; skipping attachment"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let pretty = serde_json::to_vec_pretty(&report).unwrap_or_else(|_| json.as_bytes().to_vec());
|
||||
Some(DoctorFeedbackReport {
|
||||
tags: doctor_report_tags(&report),
|
||||
attachment: FeedbackAttachment {
|
||||
filename: DOCTOR_REPORT_ATTACHMENT_FILENAME.to_string(),
|
||||
content_type: Some("application/json".to_string()),
|
||||
buffer: pretty,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn doctor_command(executable: &Path, cwd: &Path, codex_home: &Path) -> Command {
|
||||
let mut command = Command::from(codex_utils_process::background_command(executable));
|
||||
command
|
||||
.arg("--cd")
|
||||
.arg(cwd)
|
||||
.arg("doctor")
|
||||
.arg("--json")
|
||||
.arg("--feedback")
|
||||
.current_dir(codex_home)
|
||||
.env("CODEX_HOME", codex_home);
|
||||
command
|
||||
}
|
||||
|
||||
fn doctor_report_tags(report: &Value) -> BTreeMap<String, String> {
|
||||
let mut tags = BTreeMap::new();
|
||||
if let Some(overall_status) = report.get("overallStatus").and_then(Value::as_str) {
|
||||
tags.insert(
|
||||
"doctor_overall_status".to_string(),
|
||||
truncate_tag_value(overall_status),
|
||||
);
|
||||
}
|
||||
|
||||
let mut ok_count = 0usize;
|
||||
let mut warning_count = 0usize;
|
||||
let mut fail_count = 0usize;
|
||||
let mut failed_checks = Vec::new();
|
||||
let mut warning_checks = Vec::new();
|
||||
if let Some(checks) = report.get("checks") {
|
||||
for check in check_values(checks) {
|
||||
let status = check.get("status").and_then(Value::as_str);
|
||||
let id = check.get("id").and_then(Value::as_str).unwrap_or("unknown");
|
||||
match status {
|
||||
Some("ok") => ok_count += 1,
|
||||
Some("warning") => {
|
||||
warning_count += 1;
|
||||
warning_checks.push(id.to_string());
|
||||
}
|
||||
Some("fail") => {
|
||||
fail_count += 1;
|
||||
failed_checks.push(id.to_string());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
tags.insert("doctor_ok_count".to_string(), ok_count.to_string());
|
||||
tags.insert(
|
||||
"doctor_warning_count".to_string(),
|
||||
warning_count.to_string(),
|
||||
);
|
||||
tags.insert("doctor_fail_count".to_string(), fail_count.to_string());
|
||||
if !failed_checks.is_empty() {
|
||||
tags.insert(
|
||||
"doctor_failed_checks".to_string(),
|
||||
truncate_tag_value(&failed_checks.join(",")),
|
||||
);
|
||||
}
|
||||
if !warning_checks.is_empty() {
|
||||
tags.insert(
|
||||
"doctor_warning_checks".to_string(),
|
||||
truncate_tag_value(&warning_checks.join(",")),
|
||||
);
|
||||
}
|
||||
|
||||
tags
|
||||
}
|
||||
|
||||
/// Iterates checks from both the current keyed JSON shape and older array reports.
|
||||
fn check_values(checks: &Value) -> Box<dyn Iterator<Item = &Value> + '_> {
|
||||
match checks {
|
||||
Value::Array(values) => Box::new(values.iter()),
|
||||
Value::Object(values) => Box::new(values.values()),
|
||||
_ => Box::new(std::iter::empty()),
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate_tag_value(value: &str) -> String {
|
||||
if value.chars().count() <= MAX_DOCTOR_TAG_VALUE_LEN {
|
||||
return value.to_string();
|
||||
}
|
||||
let prefix = value
|
||||
.chars()
|
||||
.take(MAX_DOCTOR_TAG_VALUE_LEN.saturating_sub(3))
|
||||
.collect::<String>();
|
||||
format!("{prefix}...")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn doctor_command_keeps_missing_workspace_out_of_process_cwd() {
|
||||
let codex_home = tempdir().expect("codex home");
|
||||
let workspace = codex_home.path().join("deleted-workspace");
|
||||
|
||||
let command = doctor_command(Path::new("codex"), &workspace, codex_home.path());
|
||||
let command = command.as_std();
|
||||
|
||||
assert_eq!(command.get_current_dir(), Some(codex_home.path()));
|
||||
assert_eq!(
|
||||
command.get_args().collect::<Vec<_>>(),
|
||||
[
|
||||
"--cd".as_ref(),
|
||||
workspace.as_os_str(),
|
||||
"doctor".as_ref(),
|
||||
"--json".as_ref(),
|
||||
"--feedback".as_ref()
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
command.get_envs().collect::<Vec<_>>(),
|
||||
[("CODEX_HOME".as_ref(), Some(codex_home.path().as_os_str()))]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doctor_report_tags_summarize_status_counts() {
|
||||
let report = json!({
|
||||
"overallStatus": "fail",
|
||||
"checks": {
|
||||
"runtime.provenance": {"id": "runtime.provenance", "status": "ok"},
|
||||
"websocket.reachability": {
|
||||
"id": "websocket.reachability",
|
||||
"status": "warning"
|
||||
},
|
||||
"auth.credentials": {"id": "auth.credentials", "status": "fail"}
|
||||
}
|
||||
});
|
||||
|
||||
let tags = doctor_report_tags(&report);
|
||||
|
||||
let expected = BTreeMap::from([
|
||||
("doctor_fail_count".to_string(), "1".to_string()),
|
||||
(
|
||||
"doctor_failed_checks".to_string(),
|
||||
"auth.credentials".to_string(),
|
||||
),
|
||||
("doctor_ok_count".to_string(), "1".to_string()),
|
||||
("doctor_overall_status".to_string(), "fail".to_string()),
|
||||
(
|
||||
"doctor_warning_checks".to_string(),
|
||||
"websocket.reachability".to_string(),
|
||||
),
|
||||
("doctor_warning_count".to_string(), "1".to_string()),
|
||||
]);
|
||||
assert_eq!(tags, expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! Exercises SQLite log collection, legacy storage, and feedback snapshot ordering.
|
||||
use super::*;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_state::SqliteConfig;
|
||||
use codex_state::StateRuntime;
|
||||
use codex_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tracing_subscriber::prelude::*;
|
||||
|
||||
#[derive(PartialEq)]
|
||||
enum Scenario {
|
||||
Healthy,
|
||||
WriteFailure,
|
||||
Corruption,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_includes_flush_and_query_failures_in_the_same_submission() -> anyhow::Result<()> {
|
||||
for scenario in [
|
||||
Scenario::Healthy,
|
||||
Scenario::WriteFailure,
|
||||
Scenario::Corruption,
|
||||
] {
|
||||
let home = tempfile::tempdir()?;
|
||||
let config = core_test_support::load_default_config_for_test(&home).await;
|
||||
let sqlite = &config.sqlite;
|
||||
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
|
||||
let pool = sqlite.open_read_write_pool(&sqlite.logs_db_path()).await?;
|
||||
let feedback = CodexFeedback::new();
|
||||
let writer =
|
||||
codex_state::log_db::start(runtime.clone(), std::sync::Arc::new(feedback.clone()));
|
||||
let _guard = tracing_subscriber::registry()
|
||||
.with(feedback.logger_layer())
|
||||
.with(writer.clone())
|
||||
.set_default();
|
||||
let thread_id = ThreadId::new();
|
||||
tracing::info_span!("thread", thread_id = %thread_id)
|
||||
.in_scope(|| tracing::info!("persisted log"));
|
||||
writer.flush().await;
|
||||
match scenario {
|
||||
Scenario::WriteFailure => {
|
||||
sqlx::query("CREATE TRIGGER fail_log_insert BEFORE INSERT ON logs BEGIN SELECT RAISE(ABORT, 'synthetic-secret'); END").execute(&pool).await?;
|
||||
}
|
||||
Scenario::Corruption => {
|
||||
sqlx::raw_sql("PRAGMA writable_schema = ON; UPDATE sqlite_schema SET rootpage = 2147483647 WHERE name = 'logs'; PRAGMA schema_version = 1000000;").execute(&pool).await?;
|
||||
}
|
||||
Scenario::Healthy => {}
|
||||
}
|
||||
let snapshot = feedback.snapshot(Some(thread_id));
|
||||
tracing::info_span!("thread", thread_id = %thread_id)
|
||||
.in_scope(|| tracing::info!("latest log"));
|
||||
let (snapshot, sqlite_logs, legacy_logs) = collect_feedback_logs(
|
||||
&feedback,
|
||||
Some(&writer),
|
||||
Some(&runtime),
|
||||
&config,
|
||||
snapshot,
|
||||
&[thread_id],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(legacy_logs, None);
|
||||
assert_eq!(sqlite_logs.is_some(), scenario == Scenario::Healthy);
|
||||
let logs = String::from_utf8(snapshot.log_attachment(sqlite_logs).buffer)?;
|
||||
assert!(logs.contains("persisted log"));
|
||||
assert!(logs.contains("latest log"));
|
||||
let expected_error = match scenario {
|
||||
Scenario::Healthy => None,
|
||||
Scenario::WriteFailure => Some("constraint"),
|
||||
Scenario::Corruption => Some("corrupt"),
|
||||
};
|
||||
assert_eq!(
|
||||
logs.matches("failed to flush logs to SQLite").count(),
|
||||
usize::from(expected_error.is_some())
|
||||
);
|
||||
if let Some(error) = expected_error {
|
||||
assert!(logs.contains(&format!("failed to flush logs to SQLite error={error:?}")));
|
||||
}
|
||||
assert_eq!(
|
||||
logs.contains("failed to query feedback logs from sqlite"),
|
||||
scenario == Scenario::Corruption
|
||||
);
|
||||
pool.close().await;
|
||||
runtime.close().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_preserves_legacy_logs_when_the_directory_is_unset_or_current_logs_are_empty()
|
||||
-> anyhow::Result<()> {
|
||||
for configured_log_dir in [false, true] {
|
||||
let home = tempfile::tempdir()?;
|
||||
let sqlite_home = home.path().join("sqlite");
|
||||
let mut overrides = vec![(
|
||||
"sqlite_home".to_string(),
|
||||
toml::Value::String(sqlite_home.to_string_lossy().into_owned()),
|
||||
)];
|
||||
if configured_log_dir {
|
||||
overrides.push((
|
||||
"log_dir".to_string(),
|
||||
toml::Value::String(home.path().join("log").to_string_lossy().into_owned()),
|
||||
));
|
||||
}
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.loader_overrides(codex_config::LoaderOverrides::without_managed_config_for_tests())
|
||||
.cli_overrides(overrides)
|
||||
.build()
|
||||
.await?;
|
||||
let legacy_sqlite = SqliteConfig::new_for_testing(sqlite_home.abs());
|
||||
let legacy = StateRuntime::init(legacy_sqlite.clone(), "test-provider".to_string()).await?;
|
||||
let pool = legacy_sqlite
|
||||
.open_read_write_pool(&legacy_sqlite.logs_db_path())
|
||||
.await?;
|
||||
let thread_id = ThreadId::new();
|
||||
let now = chrono::Utc::now();
|
||||
let timestamp = now.format("%Y-%m-%dT%H:%M:%S.000000Z");
|
||||
for (id, body) in [
|
||||
(thread_id, "legacy history"),
|
||||
(ThreadId::new(), "unrelated history"),
|
||||
] {
|
||||
sqlx::query(
|
||||
"INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body, thread_id)
|
||||
VALUES (?, 0, 'INFO', 'test', ?, ?)",
|
||||
)
|
||||
.bind(now.timestamp())
|
||||
.bind(body)
|
||||
.bind(id.to_string())
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
pool.close().await;
|
||||
legacy.close().await;
|
||||
let legacy_before = std::fs::read(legacy_sqlite.logs_db_path())?;
|
||||
|
||||
let runtime =
|
||||
StateRuntime::init(config.sqlite.clone(), "test-provider".to_string()).await?;
|
||||
let pool = config
|
||||
.sqlite
|
||||
.open_read_write_pool(&config.sqlite.logs_db_path())
|
||||
.await?;
|
||||
let feedback = CodexFeedback::new();
|
||||
for current_has_logs in [false, true] {
|
||||
if current_has_logs {
|
||||
sqlx::query(
|
||||
"INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body, thread_id)
|
||||
VALUES (?, 0, 'INFO', 'test', 'current history', ?)",
|
||||
)
|
||||
.bind(now.timestamp())
|
||||
.bind(thread_id.to_string())
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
let (_, current_logs, legacy_logs) = collect_feedback_logs(
|
||||
&feedback,
|
||||
/*log_db*/ None,
|
||||
Some(&runtime),
|
||||
&config,
|
||||
feedback.snapshot(Some(thread_id)),
|
||||
&[thread_id],
|
||||
)
|
||||
.await;
|
||||
let mut expected_current = String::new();
|
||||
if !configured_log_dir {
|
||||
expected_current.push_str(&format!("{timestamp} INFO legacy history\n"));
|
||||
}
|
||||
if current_has_logs {
|
||||
expected_current.push_str(&format!("{timestamp} INFO current history\n"));
|
||||
}
|
||||
assert_eq!(
|
||||
current_logs,
|
||||
(!expected_current.is_empty()).then(|| expected_current.into_bytes())
|
||||
);
|
||||
assert_eq!(
|
||||
legacy_logs,
|
||||
(configured_log_dir && !current_has_logs)
|
||||
.then(|| format!("{timestamp} INFO legacy history\n").into_bytes())
|
||||
);
|
||||
}
|
||||
if configured_log_dir {
|
||||
assert_eq!(std::fs::read(legacy_sqlite.logs_db_path())?, legacy_before);
|
||||
}
|
||||
pool.close().await;
|
||||
runtime.close().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user