aKode fase 2b-2: rimosso login ChatGPT e tutti i sottosistemi solo-ChatGPT
- Login: resta solo chiave API (+ header, Bedrock). Rimossi OAuth/browser, device code, refresh/revoke su auth.openai.com, PAT, agent/workload identity, runtime agent instance, backend-client e openapi-models, workspace routing. - Rimossi: generazione immagini (ext + skill imagegen), history notes, plugin remoti (catalogo, sync, share), cyber access program, daybreak, cloud config e requirements (config_server ora fail-closed), attestation, frozen cloud skills, EMA MCP auth, Codex Apps/connettori, ricerca ospitata, header/zstd/ routing/cookie del backend Codex, fallback OPENAI_API_KEY del realtime. - Messaggi d'errore senza link a chatgpt.com. - Chiavi di config legacy accettate e ignorate; feature rimosse = Stage::Removed. - Test: cancellati solo quelli del codice rimosso; test di sicurezza (sandbox estensioni, permessi, redazione, auth storage, requirements) adattati. Restano solo fallimenti d'ambiente (code-mode-host/V8, ~/.agents). - Istruzioni di sistema invariate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -86,7 +86,7 @@ pub type ExtensionFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
/// are frozen for the runtime and do not include lifecycle-contributor state.
|
||||
/// Auto-discovered plugin servers are resolved by the plugin manager. Declare
|
||||
/// executor plugins separately so the host attributes their MCP servers
|
||||
/// and connectors to the same identity as their other capabilities.
|
||||
/// to the same identity as their other capabilities.
|
||||
pub trait McpServerContributor<C: Sync>: Send + Sync {
|
||||
/// Stable identity used for registration provenance and conflict diagnostics.
|
||||
fn id(&self) -> &'static str;
|
||||
@@ -96,12 +96,7 @@ pub trait McpServerContributor<C: Sync>: Send + Sync {
|
||||
context: McpServerContributionContext<'a, C>,
|
||||
) -> ExtensionFuture<'a, Vec<McpServerContribution>>;
|
||||
|
||||
/// Reads canonical hosted-plugin IDs from published state without discovery or MCP I/O.
|
||||
fn hosted_plugin_ids(&self, _context: McpServerContributionContext<'_, C>) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Declares executor plugins, including those without MCP servers or connectors. Each
|
||||
/// Declares executor plugins, including those without MCP servers. Each
|
||||
/// declaration identifies the plugin once; its deferred MCP data cannot change that identity.
|
||||
/// Return plugins in precedence order: across contributors in registration order, the first
|
||||
/// plugin wins if several provide the same server. Use the supplied plugin policy for both
|
||||
|
||||
@@ -183,7 +183,7 @@ pub struct SelectedPluginIdentity {
|
||||
}
|
||||
|
||||
/// An executor plugin and its deferred MCP data. Callers that only need the identity can drop
|
||||
/// `mcp` without loading server or connector configuration. A plugin still owns its skills when
|
||||
/// `mcp` without loading server configuration. A plugin still owns its skills when
|
||||
/// it has no MCP data.
|
||||
pub struct SelectedPlugin<'a> {
|
||||
pub selected_root_id: String,
|
||||
@@ -199,7 +199,6 @@ pub struct SelectedPluginContribution {
|
||||
pub plugin_display_name: String,
|
||||
/// Environment that supplied the plugin, independent of where its MCP servers run.
|
||||
pub source_environment_id: String,
|
||||
pub connector_ids: Vec<String>,
|
||||
pub servers: Vec<(String, McpServerConfig)>,
|
||||
}
|
||||
|
||||
@@ -213,25 +212,12 @@ pub enum McpServerContribution {
|
||||
},
|
||||
/// Adds an ordinary extension-owned server with its own HTTP protocol mode.
|
||||
/// The mode applies only if this registration wins server resolution; it
|
||||
/// does not grant controller-owned Apps cache or environment authority.
|
||||
/// does not grant environment authority.
|
||||
SetWithProtocolMode {
|
||||
name: String,
|
||||
config: Box<McpServerConfig>,
|
||||
protocol_mode: crate::McpProtocolMode,
|
||||
},
|
||||
/// Registers the controller-owned Apps server under its reserved name.
|
||||
HostedApps {
|
||||
config: Box<McpServerConfig>,
|
||||
/// Overrides the HTTP protocol mode, or uses the hosted Apps default when absent.
|
||||
protocol_mode: Option<crate::McpProtocolMode>,
|
||||
},
|
||||
/// Attributes Apps connectors to an account-hosted plugin. Plugins from executor folders must
|
||||
/// use `McpServerContributor::selected_plugins`, even if they only provide Apps connectors.
|
||||
HostedPluginConnectors {
|
||||
plugin_id: String,
|
||||
plugin_display_name: String,
|
||||
connector_ids: Vec<String>,
|
||||
},
|
||||
/// Removes a named MCP server.
|
||||
Remove { name: String },
|
||||
}
|
||||
|
||||
@@ -43,8 +43,6 @@ pub enum ToolCallOutcome {
|
||||
/// Provenance captured from the immutable MCP call selected for one tool invocation.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum McpToolSource {
|
||||
/// A connector routed through the host-owned Codex Apps MCP server.
|
||||
Connector,
|
||||
/// An MCP server whose frozen registration matches the active Codex configuration.
|
||||
Config,
|
||||
/// An MCP server registered by a locally loaded plugin.
|
||||
@@ -78,9 +76,7 @@ impl McpToolContext {
|
||||
) -> Self {
|
||||
let tool = call.tool_info().clone();
|
||||
let registration = call.config().mcp_server_catalog.server(call.server_name());
|
||||
let source = if tool.connector_id.is_some() && call.is_host_owned_apps() {
|
||||
McpToolSource::Connector
|
||||
} else if call.is_selected_plugin_server() {
|
||||
let source = if call.is_selected_plugin_server() {
|
||||
McpToolSource::SelectedPlugin
|
||||
} else if let Some(McpServerSource::Plugin(plugin)) =
|
||||
registration.map(ResolvedMcpServer::source)
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Counts policy denials per turn; the host carries out any requested interruption.
|
||||
|
||||
const MAX_CONSECUTIVE_CYBER_GUARDIAN_DENIALS_PER_TURN: u32 = 1;
|
||||
const MAX_CONSECUTIVE_GUARDIAN_DENIALS_PER_TURN: u32 = 3;
|
||||
const MAX_RECENT_CYBER_AUTO_REVIEW_DENIALS_PER_TURN: u32 = 1;
|
||||
const MAX_RECENT_AUTO_REVIEW_DENIALS_PER_TURN: u32 = 10;
|
||||
pub(crate) const AUTO_REVIEW_DENIAL_WINDOW_SIZE: usize = 50;
|
||||
|
||||
@@ -18,24 +16,6 @@ struct GuardianRejectionCircuitBreakerTurn {
|
||||
interrupt_triggered: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum GuardianRejectionCircuitBreakerPolicy {
|
||||
Standard,
|
||||
CyberModel,
|
||||
}
|
||||
|
||||
impl From<&codex_protocol::openai_models::ModelInfo> for GuardianRejectionCircuitBreakerPolicy {
|
||||
fn from(model: &codex_protocol::openai_models::ModelInfo) -> Self {
|
||||
if model.model_specialty.as_deref()
|
||||
== Some(codex_protocol::openai_models::MODEL_SPECIALTY_CYBER)
|
||||
{
|
||||
Self::CyberModel
|
||||
} else {
|
||||
Self::Standard
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum GuardianRejectionCircuitBreakerAction {
|
||||
Continue,
|
||||
@@ -50,28 +30,14 @@ impl GuardianRejectionCircuitBreaker {
|
||||
self.turns.remove(turn_id);
|
||||
}
|
||||
|
||||
pub(crate) fn record_denial(
|
||||
&mut self,
|
||||
turn_id: &str,
|
||||
policy: GuardianRejectionCircuitBreakerPolicy,
|
||||
) -> GuardianRejectionCircuitBreakerAction {
|
||||
pub(crate) fn record_denial(&mut self, turn_id: &str) -> GuardianRejectionCircuitBreakerAction {
|
||||
let turn = self.turns.entry(turn_id.to_string()).or_default();
|
||||
turn.consecutive_denials = turn.consecutive_denials.saturating_add(1);
|
||||
Self::record_recent_review(turn, /*denied*/ true);
|
||||
let recent_denials = turn.recent_denials.iter().filter(|denied| **denied).count() as u32;
|
||||
let (max_consecutive_denials, max_recent_denials) = match policy {
|
||||
GuardianRejectionCircuitBreakerPolicy::Standard => (
|
||||
MAX_CONSECUTIVE_GUARDIAN_DENIALS_PER_TURN,
|
||||
MAX_RECENT_AUTO_REVIEW_DENIALS_PER_TURN,
|
||||
),
|
||||
GuardianRejectionCircuitBreakerPolicy::CyberModel => (
|
||||
MAX_CONSECUTIVE_CYBER_GUARDIAN_DENIALS_PER_TURN,
|
||||
MAX_RECENT_CYBER_AUTO_REVIEW_DENIALS_PER_TURN,
|
||||
),
|
||||
};
|
||||
if !turn.interrupt_triggered
|
||||
&& (turn.consecutive_denials >= max_consecutive_denials
|
||||
|| recent_denials >= max_recent_denials)
|
||||
&& (turn.consecutive_denials >= MAX_CONSECUTIVE_GUARDIAN_DENIALS_PER_TURN
|
||||
|| recent_denials >= MAX_RECENT_AUTO_REVIEW_DENIALS_PER_TURN)
|
||||
{
|
||||
turn.interrupt_triggered = true;
|
||||
GuardianRejectionCircuitBreakerAction::InterruptTurn {
|
||||
|
||||
@@ -5,38 +5,22 @@ use pretty_assertions::assert_eq;
|
||||
fn guardian_rejection_circuit_breaker_interrupts_after_three_consecutive_denials() {
|
||||
let mut circuit_breaker = GuardianRejectionCircuitBreaker::default();
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::Continue
|
||||
);
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::Continue
|
||||
);
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::InterruptTurn {
|
||||
consecutive_denials: 3,
|
||||
recent_denials: 3,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
GuardianRejectionCircuitBreakerAction::Continue
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guardian_rejection_circuit_breaker_interrupts_cyber_models_after_one_denial() {
|
||||
let mut circuit_breaker = GuardianRejectionCircuitBreaker::default();
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::CyberModel),
|
||||
GuardianRejectionCircuitBreakerAction::InterruptTurn {
|
||||
consecutive_denials: 1,
|
||||
recent_denials: 1,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::CyberModel),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::Continue
|
||||
);
|
||||
}
|
||||
@@ -45,20 +29,20 @@ fn guardian_rejection_circuit_breaker_interrupts_cyber_models_after_one_denial()
|
||||
fn guardian_rejection_circuit_breaker_resets_consecutive_denials_on_non_denial() {
|
||||
let mut circuit_breaker = GuardianRejectionCircuitBreaker::default();
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::Continue
|
||||
);
|
||||
circuit_breaker.record_non_denial("turn-1");
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::Continue
|
||||
);
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::Continue
|
||||
);
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::InterruptTurn {
|
||||
consecutive_denials: 3,
|
||||
recent_denials: 4,
|
||||
@@ -71,14 +55,13 @@ fn auto_review_rejection_circuit_breaker_interrupts_after_ten_recent_denials() {
|
||||
let mut circuit_breaker = GuardianRejectionCircuitBreaker::default();
|
||||
for _ in 0..9 {
|
||||
assert_eq!(
|
||||
circuit_breaker
|
||||
.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::Continue
|
||||
);
|
||||
circuit_breaker.record_non_denial("turn-1");
|
||||
}
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::InterruptTurn {
|
||||
consecutive_denials: 1,
|
||||
recent_denials: 10,
|
||||
@@ -91,8 +74,7 @@ fn auto_review_rejection_circuit_breaker_forgets_denials_outside_recent_review_w
|
||||
let mut circuit_breaker = GuardianRejectionCircuitBreaker::default();
|
||||
for _ in 0..9 {
|
||||
assert_eq!(
|
||||
circuit_breaker
|
||||
.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::Continue
|
||||
);
|
||||
circuit_breaker.record_non_denial("turn-1");
|
||||
@@ -101,7 +83,7 @@ fn auto_review_rejection_circuit_breaker_forgets_denials_outside_recent_review_w
|
||||
circuit_breaker.record_non_denial("turn-1");
|
||||
}
|
||||
assert_eq!(
|
||||
circuit_breaker.record_denial("turn-1", GuardianRejectionCircuitBreakerPolicy::Standard),
|
||||
circuit_breaker.record_denial("turn-1"),
|
||||
GuardianRejectionCircuitBreakerAction::Continue
|
||||
);
|
||||
}
|
||||
|
||||
@@ -83,7 +83,6 @@ pub(crate) use assessment::parse_guardian_assessment;
|
||||
pub(crate) use circuit_breaker::AUTO_REVIEW_DENIAL_WINDOW_SIZE;
|
||||
pub(crate) use circuit_breaker::GuardianRejectionCircuitBreaker;
|
||||
pub(crate) use circuit_breaker::GuardianRejectionCircuitBreakerAction;
|
||||
pub(crate) use circuit_breaker::GuardianRejectionCircuitBreakerPolicy;
|
||||
pub use metrics::token_usage_delta;
|
||||
pub use model::ReviewModel;
|
||||
pub use model::select_review_model;
|
||||
@@ -128,7 +127,6 @@ pub use session::is_basic_session_source;
|
||||
pub use session::prompt_cache_key_override_for_review_session;
|
||||
pub use settings::ReviewerConfig;
|
||||
pub use settings::ReviewerTurn;
|
||||
pub use settings::guardian_cyber_access_program;
|
||||
pub use settings::reviewer_permission_profile;
|
||||
pub use settings::reviewer_tool_policy;
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ use crate::GuardianReviewFailureReason;
|
||||
use crate::GuardianReviewSessionKind;
|
||||
use crate::GuardianReviewTerminalStatus;
|
||||
use crate::GuardianReviewedAction;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_otel::GUARDIAN_REVIEW_COUNT_METRIC;
|
||||
use codex_otel::GUARDIAN_REVIEW_DURATION_METRIC;
|
||||
use codex_otel::GUARDIAN_REVIEW_TOKEN_USAGE_METRIC;
|
||||
@@ -49,18 +48,8 @@ pub(crate) fn emit_guardian_review_metrics(
|
||||
.map(|(key, value)| (*key, value.as_str()))
|
||||
.collect();
|
||||
|
||||
// Custom MCP tool names may contain user data; only attribute tools from the OpenAI Apps server.
|
||||
let mcp_tags = if let GuardianReviewedAction::McpToolCall {
|
||||
server, tool_name, ..
|
||||
} = reviewed_action
|
||||
&& server == CODEX_APPS_MCP_SERVER_NAME
|
||||
{
|
||||
vec![("tool", sanitize_metric_tag_value(tool_name))]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
// Custom MCP tool names may contain user data, so MCP tools are never attributed.
|
||||
let mut counter_tag_refs = tag_refs.clone();
|
||||
counter_tag_refs.extend(mcp_tags.iter().map(|(key, value)| (*key, value.as_str())));
|
||||
counter_tag_refs.push(("context_changed", bool_tag(result.context_changed)));
|
||||
session_telemetry.counter(
|
||||
GUARDIAN_REVIEW_COUNT_METRIC,
|
||||
@@ -439,18 +428,6 @@ mod tests {
|
||||
BTreeMap::new();
|
||||
"network access"
|
||||
)]
|
||||
#[test_case(
|
||||
GuardianReviewedAction::McpToolCall {
|
||||
server: CODEX_APPS_MCP_SERVER_NAME.to_string(),
|
||||
tool_name: "search docs".to_string(),
|
||||
connector_id: None,
|
||||
connector_name: None,
|
||||
tool_title: None,
|
||||
},
|
||||
"mcp_tool_call",
|
||||
BTreeMap::from([("tool".to_string(), "search_docs".to_string())]);
|
||||
"openai apps tool call"
|
||||
)]
|
||||
#[test_case(
|
||||
GuardianReviewedAction::McpToolCall {
|
||||
server: "codex_apps_custom".to_string(),
|
||||
|
||||
@@ -24,7 +24,6 @@ use tokio::sync::Mutex;
|
||||
|
||||
use crate::GuardianRejectionCircuitBreaker;
|
||||
use crate::GuardianRejectionCircuitBreakerAction;
|
||||
use crate::GuardianRejectionCircuitBreakerPolicy;
|
||||
use crate::GuardianReviewOutcome;
|
||||
use crate::ReviewCompletion;
|
||||
|
||||
@@ -144,12 +143,8 @@ impl ReviewDenials {
|
||||
}
|
||||
|
||||
/// Returns a warning exactly once when this turn reaches its denial limit.
|
||||
pub async fn record_denial(&self, turn_id: &str, model: &ModelInfo) -> Option<String> {
|
||||
let action = self
|
||||
.0
|
||||
.lock()
|
||||
.await
|
||||
.record_denial(turn_id, GuardianRejectionCircuitBreakerPolicy::from(model));
|
||||
pub async fn record_denial(&self, turn_id: &str) -> Option<String> {
|
||||
let action = self.0.lock().await.record_denial(turn_id);
|
||||
match action {
|
||||
GuardianRejectionCircuitBreakerAction::Continue => None,
|
||||
GuardianRejectionCircuitBreakerAction::InterruptTurn {
|
||||
|
||||
@@ -13,7 +13,6 @@ use crate::ReviewRequest;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::SynchronousApprovalReviewer;
|
||||
use codex_protocol::approvals::GuardianReviewReason;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::protocol::CodexErrorInfo;
|
||||
use codex_protocol::protocol::ErrorEvent;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
@@ -39,7 +38,7 @@ pub trait ReviewHost: Clone + Send + Sync + 'static {
|
||||
/// Returns the target's rules, or no evidence when they cannot be resolved.
|
||||
fn permissions(&self) -> Option<codex_guardian_context::PermissionContext>;
|
||||
/// Captures the turn currently servicing reviews, which may differ from a yielded cell's origin.
|
||||
fn servicing_turn(&self) -> impl Future<Output = Option<(String, Arc<ModelInfo>)>> + Send;
|
||||
fn servicing_turn(&self) -> impl Future<Output = Option<String>> + Send;
|
||||
/// Returns the owning turn and optional target item after validating the action.
|
||||
fn validate_action(&self) -> Result<(&str, Option<&str>), ReviewDecision>;
|
||||
/// Prepares evidence and accounting, with a client event only for supported actions.
|
||||
@@ -205,10 +204,10 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
|
||||
if cached_approval {
|
||||
return Some(self.cached_approval().await);
|
||||
}
|
||||
if let Some((turn_id, model)) = self.host.servicing_turn().await {
|
||||
if let Some(turn_id) = self.host.servicing_turn().await {
|
||||
let denials = ReviewDenials::for_thread(self.thread_store);
|
||||
if completed.assessment_outcome == Some(GuardianAssessmentOutcome::Deny) {
|
||||
if let Some(message) = denials.record_denial(&turn_id, &model).await {
|
||||
if let Some(message) = denials.record_denial(&turn_id).await {
|
||||
// The denial window returns a warning only once per turn.
|
||||
self.telemetry.counter(
|
||||
"codex.guardian.denial_limit_reached",
|
||||
|
||||
@@ -11,6 +11,7 @@ use codex_protocol::approvals::GuardianAssessmentAction;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::items::ModelInvocationContext;
|
||||
use codex_protocol::openai_models::GuardianScope;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -39,7 +40,7 @@ impl ReviewHost for GatedHost {
|
||||
fn permissions(&self) -> Option<codex_guardian_context::PermissionContext> {
|
||||
None
|
||||
}
|
||||
async fn servicing_turn(&self) -> Option<(String, Arc<ModelInfo>)> {
|
||||
async fn servicing_turn(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn validate_action(&self) -> Result<(&str, Option<&str>), ReviewDecision> {
|
||||
|
||||
@@ -181,7 +181,7 @@ impl<H: ReviewHost> ReviewRequest<'_, H> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
return ReviewDecision::Abort;
|
||||
}
|
||||
if let Some((turn_id, _)) = self.host.servicing_turn().await {
|
||||
if let Some(turn_id) = self.host.servicing_turn().await {
|
||||
ReviewDenials::for_thread(self.thread_store)
|
||||
.record_non_denial(&turn_id)
|
||||
.await;
|
||||
|
||||
@@ -17,7 +17,6 @@ use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::EnvironmentConfigState;
|
||||
use codex_protocol::protocol::ThreadSettingsOverrides;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelections;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
use codex_protocol::turn_input::TurnInputRequest;
|
||||
use codex_protocol::turn_input::TurnStartOptions;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
@@ -28,18 +27,6 @@ use serde_json::Value;
|
||||
/// Keeping it in thread data avoids caching settings that can change between reviews.
|
||||
pub struct ReviewerConfig<C>(pub fn(&C) -> anyhow::Result<C>);
|
||||
|
||||
/// Uses Blue for either Daybreak selection without changing Standard or automatic behavior.
|
||||
pub fn guardian_cyber_access_program(
|
||||
program: Option<CyberAccessProgram>,
|
||||
) -> Option<CyberAccessProgram> {
|
||||
program.map(|program| match program {
|
||||
CyberAccessProgram::Standard => CyberAccessProgram::Standard,
|
||||
CyberAccessProgram::DaybreakBlue | CyberAccessProgram::DaybreakRed => {
|
||||
CyberAccessProgram::DaybreakBlue
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Reviewer tool selection and construction restrictions, enforced by core.
|
||||
pub fn reviewer_tool_policy() -> ToolPolicy {
|
||||
ToolPolicy {
|
||||
@@ -73,8 +60,6 @@ pub struct ReviewerTurn {
|
||||
pub personality: Option<Personality>,
|
||||
pub model: String,
|
||||
pub reasoning_effort: Option<ReasoningEffort>,
|
||||
/// The parent turn's selection; Guardian uses Blue for either Daybreak program.
|
||||
pub cyber_access_program: Option<CyberAccessProgram>,
|
||||
pub parent_response_id: Option<String>,
|
||||
pub schema: Value,
|
||||
pub parent_turn_id: String,
|
||||
@@ -114,7 +99,6 @@ impl ReviewerTurn {
|
||||
)
|
||||
.on_start(TurnStartOptions {
|
||||
turn_trigger: Some("guardian_review".to_owned()),
|
||||
cyber_access_program: guardian_cyber_access_program(self.cyber_access_program),
|
||||
final_output_json_schema: Some(self.schema),
|
||||
parent_turn_id: Some(self.parent_turn_id),
|
||||
root_turn_id: self.root_turn_id,
|
||||
|
||||
@@ -13,8 +13,6 @@ doctest = false
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
codex-agent-identity = { workspace = true }
|
||||
codex-runtime-agent-instance = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
codex-api = { workspace = true }
|
||||
codex-config = { workspace = true }
|
||||
|
||||
@@ -20,7 +20,7 @@ use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_protocol::approvals::GuardianReviewReason;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::mcp::is_node_repl_backed_connector;
|
||||
use codex_protocol::mcp::is_node_repl_backed_server;
|
||||
use codex_protocol::openai_models::GuardianModelPolicy;
|
||||
use codex_protocol::openai_models::GuardianReviewMode;
|
||||
use codex_protocol::openai_models::GuardianScope;
|
||||
@@ -269,14 +269,11 @@ async fn cached_evidence(
|
||||
action.get("tool_name").and_then(serde_json::Value::as_str),
|
||||
Some("js" | "browser_js")
|
||||
)
|
||||
&& is_node_repl_backed_connector(
|
||||
&& is_node_repl_backed_server(
|
||||
action
|
||||
.get("server")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or_default(),
|
||||
action
|
||||
.get("connector_id")
|
||||
.and_then(serde_json::Value::as_str),
|
||||
)
|
||||
&& cached.js_executions == 1
|
||||
{
|
||||
|
||||
@@ -11,7 +11,6 @@ use std::time::SystemTime;
|
||||
use codex_core::CodexThread;
|
||||
use codex_core::GuardianAuthorizationVersion;
|
||||
use codex_core::GuardianRootSnapshot;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::context::ContextualUserFragment;
|
||||
use codex_core::context::GuardianContextMode;
|
||||
@@ -34,7 +33,6 @@ use codex_prompts::ResolvedModelMessages;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::security_risk::SecurityRiskScore;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
|
||||
use super::authorization::ScoreAuthorization;
|
||||
use super::config::GuardianV2Config;
|
||||
@@ -65,9 +63,6 @@ pub(super) struct Classification {
|
||||
pub(super) thread_id: String,
|
||||
pub(super) turn_id: String,
|
||||
pub(super) root_turn_id: Option<String>,
|
||||
pub(super) cyber_access_program: Option<CyberAccessProgram>,
|
||||
pub(super) parent_response_id: Option<String>,
|
||||
pub(super) manager: Arc<ThreadManager>,
|
||||
pub(super) thread: Arc<CodexThread>,
|
||||
pub(super) config: Arc<Config>,
|
||||
pub(super) context_mode: GuardianContextMode,
|
||||
@@ -118,9 +113,6 @@ impl Classification {
|
||||
thread_id,
|
||||
turn_id,
|
||||
root_turn_id,
|
||||
cyber_access_program,
|
||||
parent_response_id,
|
||||
manager,
|
||||
thread,
|
||||
config,
|
||||
context_mode,
|
||||
@@ -149,7 +141,7 @@ impl Classification {
|
||||
metadata = async {
|
||||
let trusted_tool_context = match mcp_tool.as_ref() {
|
||||
Some(tool) => {
|
||||
trusted_tool_context(tool.tool_info(), tool.source(), &manager, &config).await
|
||||
trusted_tool_context(tool.tool_info(), tool.source(), &config).await
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
@@ -291,8 +283,6 @@ impl Classification {
|
||||
let instructions = guardian_config.render_classifier_instructions(policy, extra_policy);
|
||||
let sampling = LunaSamplingRequest {
|
||||
item_id_generator: Arc::clone(thread.item_id_generator()),
|
||||
cyber_access_program,
|
||||
parent_response_id,
|
||||
instructions,
|
||||
#[cfg(test)]
|
||||
input: Vec::new(),
|
||||
|
||||
@@ -39,7 +39,7 @@ async fn allow_messaging_guardian_review(server: &wiremock::MockServer) {
|
||||
.any(|item| {
|
||||
item["text"].as_str().is_some_and(|text| {
|
||||
text.contains("\"tool\": \"mcp_tool_call\"")
|
||||
&& text.contains("\"server\": \"codex_apps\"")
|
||||
&& text.contains("\"server\": \"messaging\"")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -88,7 +88,7 @@ async fn confirmed_root_delivery_invalidates_root_and_worker_cached_approvals()
|
||||
}),
|
||||
"tools/list" => json!({"tools": [{"name": TOOL, "inputSchema": {
|
||||
"type": "object", "properties": {"text": {"type": "string"}}
|
||||
}, "_meta": {"connector_id": "user_message", "connector_name": "user_message"}}]}),
|
||||
}}]}),
|
||||
"tools/call" => {
|
||||
assert_eq!(request["params"]["name"], TOOL);
|
||||
assert_eq!(
|
||||
@@ -123,7 +123,7 @@ async fn confirmed_root_delivery_invalidates_root_and_worker_cached_approvals()
|
||||
MessagingSetup::CodeMode(format!("{}/user-messaging", messaging_server.uri())),
|
||||
)
|
||||
.await?;
|
||||
wait_for_mcp_server(&test.codex, "codex_apps").await?;
|
||||
wait_for_mcp_server(&test.codex, "messaging").await?;
|
||||
allow_messaging_guardian_review(&thread_server).await;
|
||||
let root_store = test.codex.thread_extension_data();
|
||||
let root_progress = root_store.get::<GuardianV2ScoreProgress>().unwrap();
|
||||
@@ -165,7 +165,7 @@ async fn confirmed_root_delivery_invalidates_root_and_worker_cached_approvals()
|
||||
ev_custom_tool_call(
|
||||
"send-message",
|
||||
"exec",
|
||||
"text(await tools.mcp__codex_apps__user_message_send_message({text: 'May I deploy?'}));",
|
||||
"text(await tools.mcp__messaging__user_message_send_message({text: 'May I deploy?'}));",
|
||||
),
|
||||
ev_completed("send-message"),
|
||||
]),
|
||||
|
||||
@@ -59,7 +59,6 @@ use codex_protocol::protocol::TruncationPolicy;
|
||||
use codex_protocol::security_risk::SecurityRiskScore;
|
||||
use codex_protocol_test_support::uuid_v7_item_id_generator_for_test;
|
||||
use core_test_support::ThreadIdle;
|
||||
use core_test_support::apps_test_server::HostedMessagingServer;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::responses::WebSocketConnectionConfig;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
@@ -260,8 +259,7 @@ async fn installed_extension_warms_connections_without_blocking_thread_start() -
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn installed_extension_keeps_parent_program_out_of_websocket_and_http_reviews() -> Result<()>
|
||||
{
|
||||
async fn installed_extension_reviews_over_websocket_and_http_after_auth_refresh() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("original"));
|
||||
@@ -269,19 +267,11 @@ async fn installed_extension_keeps_parent_program_out_of_websocket_and_http_revi
|
||||
.set_external_auth(Arc::new(RefreshableAuth(std::sync::Mutex::new("original"))))
|
||||
.await?;
|
||||
let thread_server = responses::start_mock_server().await;
|
||||
let mut test = test_codex()
|
||||
let test = test_codex()
|
||||
.with_auth_manager(Arc::clone(&auth_manager))
|
||||
.with_config(|config| config.approvals_reviewer = ApprovalsReviewer::AutoReview)
|
||||
.build_with_auto_env(&thread_server)
|
||||
.await?;
|
||||
let mut options = test.start_thread_options().await;
|
||||
options
|
||||
.thread_extension_init
|
||||
.insert(codex_core::RequiredCyberAccessPrograms {
|
||||
allowed: vec![codex_protocol::turn_input::CyberAccessProgram::DaybreakRed],
|
||||
});
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
test.codex = test.thread_manager.start_thread(options).await?.thread;
|
||||
let events = vec![
|
||||
ev_assistant_message("sample", "low"),
|
||||
ev_completed("response-1"),
|
||||
@@ -308,8 +298,6 @@ async fn installed_extension_keeps_parent_program_out_of_websocket_and_http_revi
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session-1");
|
||||
let thread_store = test.codex.thread_extension_data();
|
||||
// An earlier extension cannot erase Core's captured enrollment policy.
|
||||
thread_store.remove::<codex_core::RequiredCyberAccessPrograms>();
|
||||
let mut model = test
|
||||
.thread_manager
|
||||
.get_models_manager()
|
||||
@@ -340,7 +328,6 @@ async fn installed_extension_keeps_parent_program_out_of_websocket_and_http_revi
|
||||
.expect("Guardian v2 should initialize");
|
||||
let turn_store = ExtensionData::new("turn-1");
|
||||
turn_store.insert_arc(thread_store.get::<Config>().expect("captured test config"));
|
||||
turn_store.insert(codex_protocol::turn_input::CyberAccessProgram::DaybreakRed);
|
||||
let tool_name = ToolName::namespaced("mcp__node_repl__", "js");
|
||||
let payload = ToolPayload::Function {
|
||||
arguments: r#"{"path":"README.md"}"#.to_owned(),
|
||||
@@ -410,7 +397,6 @@ async fn installed_extension_keeps_parent_program_out_of_websocket_and_http_revi
|
||||
assert_eq!(requests.len(), 1);
|
||||
requests.push(http_request.body_json());
|
||||
for request in &requests {
|
||||
assert!(request.get("access_programs").is_none());
|
||||
responses::assert_parent_turn(request, Some("turn-1"))?;
|
||||
responses::assert_root_turn(request, /*expected*/ None)?;
|
||||
}
|
||||
@@ -969,19 +955,22 @@ async fn sample_configured_conversation_history_with_delivery(
|
||||
)> {
|
||||
let thread_server = responses::start_mock_server().await;
|
||||
let guardian_policy = guardian_policy.map(str::to_owned);
|
||||
let guardian_config = format!(
|
||||
let mut guardian_config = format!(
|
||||
"{guardian_config}\n[features.guardianv2.review_scope]\ncomputer_use_only = false\n"
|
||||
);
|
||||
if let MessagingSetup::CodeMode(url) = &messaging {
|
||||
// The messaging MCP is an ordinary user-configured server with auto-approved tools.
|
||||
guardian_config.push_str(&format!(
|
||||
"\n[mcp_servers.messaging]\nurl = \"{url}\"\ndefault_tools_approval_mode = \"approve\"\nsupports_parallel_tool_calls = true\n"
|
||||
));
|
||||
}
|
||||
let has_model_defaults = model_defaults.is_some();
|
||||
let code_mode = matches!(&messaging, MessagingSetup::CodeMode(_));
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
extensions.thread_lifecycle_contributor(Arc::new(ThreadIdle));
|
||||
if let MessagingSetup::CodeMode(url) = messaging {
|
||||
extensions.mcp_server_contributor(Arc::new(HostedMessagingServer(url)));
|
||||
}
|
||||
let builder = test_codex()
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_auth(CodexAuth::from_api_key("Test API Key"))
|
||||
.with_model_info_override("codex-auto-review", |model_info| {
|
||||
model_info
|
||||
.model_messages
|
||||
@@ -998,7 +987,6 @@ async fn sample_configured_conversation_history_with_delivery(
|
||||
config.guardian_policy_config = Some("Policy from the live thread.".to_owned());
|
||||
if code_mode {
|
||||
for feature in [
|
||||
Feature::Apps,
|
||||
Feature::CodeMode,
|
||||
Feature::CodeModeInterrupt,
|
||||
Feature::Collab,
|
||||
@@ -1035,7 +1023,8 @@ async fn sample_configured_conversation_history_with_delivery(
|
||||
let catalog = test.config.model_catalog.as_mut().expect("test catalog");
|
||||
for model in &mut catalog.models {
|
||||
let policy = match model.slug.as_str() {
|
||||
"codex-auto-review" => TEST_THREAD_REVIEWER_POLICY,
|
||||
// API-key auth (the only credential aKode supports) prefers the Luna reviewer.
|
||||
"codex-auto-review" | "gpt-5.6-luna" => TEST_THREAD_REVIEWER_POLICY,
|
||||
"gpt-5.5" => "Policy from the captured parent.",
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
@@ -15,11 +15,10 @@ use codex_extension_api::ToolPayload;
|
||||
use codex_extension_api::ToolStartInput;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::mcp::is_node_repl_backed_connector;
|
||||
use codex_protocol::mcp::is_node_repl_backed_server;
|
||||
use codex_protocol::openai_models::GuardianReviewMode;
|
||||
use codex_protocol::openai_models::GuardianScope;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
|
||||
use super::action::ActionRenderError;
|
||||
use super::action::GuardianAction;
|
||||
@@ -66,19 +65,7 @@ impl GuardianV2Extension {
|
||||
};
|
||||
let is_js_execution = input.mcp_tool.is_some_and(|tool| {
|
||||
let info = tool.tool_info();
|
||||
is_node_repl_backed_connector(&info.server_name, info.connector_id.as_deref())
|
||||
&& if info.server_name == "codex_apps" {
|
||||
info.tool
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.get("_codex_apps"))
|
||||
.and_then(|meta| meta.get("resource_uri"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.and_then(|uri| uri.trim_matches('/').rsplit('/').next())
|
||||
== Some("js")
|
||||
} else {
|
||||
info.tool.name == "js"
|
||||
}
|
||||
is_node_repl_backed_server(&info.server_name) && info.tool.name == "js"
|
||||
});
|
||||
// Count execution attempts even when policy disables background scoring.
|
||||
if is_js_execution {
|
||||
@@ -105,7 +92,7 @@ impl GuardianV2Extension {
|
||||
.mcp_tool
|
||||
.map(|tool| {
|
||||
let info = tool.tool_info();
|
||||
GuardianScope::for_mcp_connector(&info.server_name, info.connector_id.as_deref())
|
||||
GuardianScope::for_mcp_server(&info.server_name)
|
||||
})
|
||||
.or_else(|| {
|
||||
if guardian_config.review_multi_agent_calls {
|
||||
@@ -189,14 +176,6 @@ impl GuardianV2Extension {
|
||||
let thread_id = input.thread_store.level_id().to_owned();
|
||||
let turn_id = input.turn_id.to_owned();
|
||||
let root_turn_id = input.root_turn_id.map(str::to_owned);
|
||||
let cyber_access_program = input
|
||||
.turn_store
|
||||
.get::<CyberAccessProgram>()
|
||||
.map(|program| *program);
|
||||
let parent_response_id = input
|
||||
.turn_store
|
||||
.get::<codex_api::ResponseId>()
|
||||
.map(|id| id.0.clone());
|
||||
let thread_context: Result<_, String> = async {
|
||||
let parsed_thread_id =
|
||||
ThreadId::from_string(&thread_id).map_err(|error| error.to_string())?;
|
||||
@@ -208,10 +187,10 @@ impl GuardianV2Extension {
|
||||
.get_thread(parsed_thread_id)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok((manager, thread))
|
||||
Ok(thread)
|
||||
}
|
||||
.await;
|
||||
let (manager, thread) = match thread_context {
|
||||
let thread = match thread_context {
|
||||
Ok(context) => context,
|
||||
Err(error) => {
|
||||
score_progress.invalidate(tool_call_index);
|
||||
@@ -415,9 +394,6 @@ impl GuardianV2Extension {
|
||||
thread_id,
|
||||
turn_id,
|
||||
root_turn_id,
|
||||
cyber_access_program,
|
||||
parent_response_id,
|
||||
manager,
|
||||
thread,
|
||||
config,
|
||||
context_mode,
|
||||
|
||||
@@ -19,19 +19,14 @@ use codex_api::Reasoning;
|
||||
use codex_api::ReasoningContext;
|
||||
use codex_api::ResponsesApiRequest;
|
||||
use codex_context_fragments::RenderedFragment;
|
||||
use codex_core::cyber_access_program::ApiKeyCyberAccessPrograms;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AgentIdentityAuthPolicy;
|
||||
use codex_model_provider::SharedModelProvider;
|
||||
use codex_model_provider::WorkspaceRoutingContext;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
use thiserror::Error;
|
||||
use tokio::sync::oneshot;
|
||||
use uuid::Uuid;
|
||||
@@ -47,18 +42,8 @@ const MAX_CONCURRENT_REQUESTS: usize = 16;
|
||||
pub struct LunaSamplerConfig {
|
||||
/// Provider and credentials selected for the owning thread.
|
||||
pub provider: SharedModelProvider,
|
||||
/// Provider and feature policy shared with ordinary model requests.
|
||||
pub api_key_cyber_access_programs: ApiKeyCyberAccessPrograms,
|
||||
/// False when the parent host confines its explicit program to that thread.
|
||||
pub inherit_parent_cyber_access_program: bool,
|
||||
/// Routing scope and retained configuration layers for the owning thread.
|
||||
pub workspace_routing: WorkspaceRoutingContext,
|
||||
/// Effective proxy, custom-CA, and cookie configuration.
|
||||
pub http_client_factory: HttpClientFactory,
|
||||
/// Agent-identity policy selected for the owning thread.
|
||||
pub agent_identity_policy: AgentIdentityAuthPolicy,
|
||||
/// Host-resolved source used to scope agent-identity authentication.
|
||||
pub session_source: SessionSource,
|
||||
/// Owning runtime session identifier.
|
||||
pub session_id: String,
|
||||
/// Owning thread identifier.
|
||||
@@ -79,10 +64,6 @@ pub struct LunaSamplerConfig {
|
||||
pub struct LunaSamplingRequest {
|
||||
/// Generator selected by the owning session for response items.
|
||||
pub item_id_generator: codex_protocol::ItemIdGenerator,
|
||||
/// Cyber selection captured from the owning turn; Daybreak reviews use Blue.
|
||||
pub cyber_access_program: Option<CyberAccessProgram>,
|
||||
/// ID of the response handling the classified tool.
|
||||
pub parent_response_id: Option<String>,
|
||||
/// Trusted classifier instructions with their role and content attribution.
|
||||
pub instructions: RenderedFragment,
|
||||
/// Composed evidence messages, with roles, annotations and content order intact.
|
||||
@@ -247,21 +228,14 @@ impl LunaSampler {
|
||||
prompt_cache_options: None,
|
||||
text: None,
|
||||
client_metadata: None,
|
||||
access_programs: None,
|
||||
};
|
||||
execution::SamplingExecution {
|
||||
auth_owner,
|
||||
cyber_access_program: codex_guardian_reviewer::guardian_cyber_access_program(
|
||||
request
|
||||
.cyber_access_program
|
||||
.filter(|_| self.config.inherit_parent_cyber_access_program),
|
||||
),
|
||||
config: Arc::clone(&self.config),
|
||||
connections: Arc::clone(&self.connections),
|
||||
request: api_request,
|
||||
// Retries keep the classification's inference turn identity.
|
||||
turn_id: Uuid::now_v7().to_string(),
|
||||
parent_response_id: request.parent_response_id.clone(),
|
||||
parent_turn_id: request.parent_turn_id.clone(),
|
||||
root_turn_id: request.root_turn_id.clone(),
|
||||
}
|
||||
|
||||
@@ -29,14 +29,10 @@ use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::NetworkPolicy;
|
||||
use codex_login::AuthChangeState;
|
||||
use codex_login::AuthOwner;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::ClientRedirectPolicy;
|
||||
use codex_login::default_client::add_originator_header;
|
||||
use codex_login::default_client::create_client_for_route_async;
|
||||
use codex_login::default_client::default_headers;
|
||||
use codex_model_provider::ACCOUNT_ROUTING_HEADER;
|
||||
use codex_model_provider::AgentIdentitySessionFallback;
|
||||
use codex_model_provider::ProviderAuthScope;
|
||||
use codex_model_provider::ResponsesConnectionKey;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_websocket_client::WebSocketConnector;
|
||||
@@ -59,12 +55,6 @@ const MAX_CONCURRENT_OPENS: usize = 4;
|
||||
const REFILL_LOW_WATERMARK: usize = INITIAL_WEBSOCKET_CONNECTIONS / 2;
|
||||
const RESPONSES_WEBSOCKETS_BETA: &str = "responses_websockets=2026-02-06";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum RequestMode {
|
||||
Regular,
|
||||
GuardianClassifier,
|
||||
}
|
||||
|
||||
pub(super) struct ConnectionPool {
|
||||
config: Arc<LunaSamplerConfig>,
|
||||
pub(super) idle_connections: Mutex<Vec<PooledConnection>>,
|
||||
@@ -86,13 +76,11 @@ struct HttpTransport {
|
||||
|
||||
pub(super) struct PooledConnection {
|
||||
connection: ResponsesWebsocketConnection,
|
||||
request_kind: RequestMode,
|
||||
// The bridge routes by thread ID, so each socket needs its own identity.
|
||||
pub(super) thread_id: String,
|
||||
pub(super) expires_at: Instant,
|
||||
auth_changes: Option<tokio::sync::watch::Receiver<AuthChangeState>>,
|
||||
key: ResponsesConnectionKey,
|
||||
runtime_id: Option<String>,
|
||||
auth_owner: Option<AuthOwner>,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
}
|
||||
@@ -101,9 +89,7 @@ pub(super) struct PooledConnection {
|
||||
struct ClientSetup {
|
||||
provider: Provider,
|
||||
http_client_factory: HttpClientFactory,
|
||||
runtime_id: Option<String>,
|
||||
auth_owner: Option<AuthOwner>,
|
||||
request_kind: RequestMode,
|
||||
auth: SharedAuthProvider,
|
||||
redirect_policy: ClientRedirectPolicy,
|
||||
key: ResponsesConnectionKey,
|
||||
@@ -117,7 +103,6 @@ enum Connection {
|
||||
|
||||
pub(super) struct ConnectionLease {
|
||||
pub(super) thread_id: String,
|
||||
pub(super) request_kind: RequestMode,
|
||||
pub(super) auth_owner: Option<AuthOwner>,
|
||||
connection: Connection,
|
||||
pool: Arc<ConnectionPool>,
|
||||
@@ -160,10 +145,6 @@ impl ConnectionPool {
|
||||
}
|
||||
|
||||
fn start_refill(self: &Arc<Self>, guard: OwnedMutexGuard<()>) -> Option<JoinHandle<()>> {
|
||||
// Runtime sources must be reauthenticated when a classification is admitted.
|
||||
if self.config.provider.runtime_auth().is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut retry_after = self
|
||||
.retry_after
|
||||
.lock()
|
||||
@@ -232,48 +213,40 @@ impl ConnectionPool {
|
||||
.map_err(|error| LunaSamplerError::Api(ApiError::Stream(error.to_string())))?;
|
||||
let admitted = Instant::now();
|
||||
let setup = self.client_setup().await?;
|
||||
let fresh_connection = self.runtime_connection(&setup).await?;
|
||||
let ClientSetup {
|
||||
mut provider,
|
||||
auth,
|
||||
http_client_factory,
|
||||
runtime_id,
|
||||
auth_owner,
|
||||
request_kind,
|
||||
redirect_policy,
|
||||
key,
|
||||
auth_changes,
|
||||
} = setup;
|
||||
let setup_finished = Instant::now();
|
||||
let connection = if runtime_id.is_some() {
|
||||
fresh_connection
|
||||
} else {
|
||||
loop {
|
||||
let idle = self
|
||||
.idle_connections
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.pop();
|
||||
match idle {
|
||||
Some(connection)
|
||||
if connection.key == key
|
||||
&& connection.runtime_id == runtime_id
|
||||
&& connection.auth_owner == auth_owner
|
||||
&& connection
|
||||
.auth_changes
|
||||
.as_ref()
|
||||
.is_none_or(|auth| !auth.has_changed().unwrap_or(true))
|
||||
&& Instant::now() < connection.expires_at
|
||||
&& !connection.connection.is_closed().await =>
|
||||
{
|
||||
break Some(connection);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => break None,
|
||||
let connection = loop {
|
||||
let idle = self
|
||||
.idle_connections
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.pop();
|
||||
match idle {
|
||||
Some(connection)
|
||||
if connection.key == key
|
||||
&& connection.auth_owner == auth_owner
|
||||
&& connection
|
||||
.auth_changes
|
||||
.as_ref()
|
||||
.is_none_or(|auth| !auth.has_changed().unwrap_or(true))
|
||||
&& Instant::now() < connection.expires_at
|
||||
&& !connection.connection.is_closed().await =>
|
||||
{
|
||||
break Some(connection);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => break None,
|
||||
}
|
||||
};
|
||||
let (connection, thread_id, request_kind) = match connection {
|
||||
let (connection, thread_id) = match connection {
|
||||
Some(connection) => {
|
||||
if self
|
||||
.idle_connections
|
||||
@@ -285,19 +258,13 @@ impl ConnectionPool {
|
||||
self.replenish();
|
||||
}
|
||||
let thread_id = connection.thread_id.clone();
|
||||
let request_kind = connection.request_kind;
|
||||
(Connection::Websocket(connection), thread_id, request_kind)
|
||||
(Connection::Websocket(connection), thread_id)
|
||||
}
|
||||
None => {
|
||||
self.replenish();
|
||||
// Sampling owns the retry budget across both transports.
|
||||
provider.retry.max_attempts = 0;
|
||||
let url = provider.url_for_path("/responses");
|
||||
let redirect_policy = if provider.headers.contains_key(ACCOUNT_ROUTING_HEADER) {
|
||||
ClientRedirectPolicy::Reject
|
||||
} else {
|
||||
redirect_policy
|
||||
};
|
||||
let transport = {
|
||||
let mut cached = self
|
||||
.http_transport
|
||||
@@ -340,11 +307,7 @@ impl ConnectionPool {
|
||||
.await?
|
||||
.clone();
|
||||
let client = ResponsesClient::new(transport, provider, auth);
|
||||
(
|
||||
Connection::Http(client),
|
||||
ThreadId::new().to_string(),
|
||||
request_kind,
|
||||
)
|
||||
(Connection::Http(client), ThreadId::new().to_string())
|
||||
}
|
||||
};
|
||||
if auth_changes
|
||||
@@ -375,7 +338,6 @@ impl ConnectionPool {
|
||||
Ok(ConnectionLease {
|
||||
auth_owner,
|
||||
thread_id,
|
||||
request_kind,
|
||||
connection,
|
||||
pool: Arc::clone(self),
|
||||
_permit: permit,
|
||||
@@ -385,12 +347,6 @@ impl ConnectionPool {
|
||||
async fn client_setup(&self) -> Result<ClientSetup, LunaSamplerError> {
|
||||
let setup = codex_model_provider::resolve_request(
|
||||
self.config.provider.as_ref(),
|
||||
Some(ProviderAuthScope {
|
||||
agent_identity_policy: self.config.agent_identity_policy,
|
||||
session_source: self.config.session_source.clone(),
|
||||
agent_identity_session_fallback: AgentIdentitySessionFallback::default(),
|
||||
}),
|
||||
Some(&self.config.workspace_routing),
|
||||
self.config.http_client_factory.clone(),
|
||||
)
|
||||
.await
|
||||
@@ -406,32 +362,22 @@ impl ConnectionPool {
|
||||
)));
|
||||
}
|
||||
let key = ResponsesConnectionKey::new(&setup.api_provider, setup.auth_revision);
|
||||
let request_kind = self.responses_request_kind(setup.auth.as_ref());
|
||||
Ok(ClientSetup {
|
||||
provider: setup.api_provider,
|
||||
auth: setup.api_auth,
|
||||
redirect_policy: setup.redirect_policy,
|
||||
http_client_factory: setup.http_client_factory,
|
||||
runtime_id: setup.runtime_id,
|
||||
auth_owner: setup.auth_owner,
|
||||
request_kind,
|
||||
key,
|
||||
auth_changes,
|
||||
})
|
||||
}
|
||||
|
||||
fn headers(
|
||||
&self,
|
||||
thread_id: &str,
|
||||
request_kind: RequestMode,
|
||||
) -> Result<HeaderMap, LunaSamplerError> {
|
||||
fn headers(&self, thread_id: &str) -> Result<HeaderMap, LunaSamplerError> {
|
||||
let mut headers = build_session_headers(
|
||||
Some(self.config.session_id.clone()),
|
||||
Some(thread_id.to_owned()),
|
||||
);
|
||||
if request_kind == RequestMode::GuardianClassifier {
|
||||
headers.insert("x-codex-guardian", HeaderValue::from_static("classifier"));
|
||||
}
|
||||
headers.insert("x-openai-subagent", HeaderValue::from_static("guardian"));
|
||||
headers.insert(
|
||||
"x-codex-window-id",
|
||||
@@ -453,69 +399,6 @@ impl ConnectionPool {
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
fn responses_request_kind(&self, auth: Option<&CodexAuth>) -> RequestMode {
|
||||
let provider = self.config.provider.info();
|
||||
if auth.is_some_and(CodexAuth::uses_codex_backend)
|
||||
&& provider.is_openai()
|
||||
&& provider.requires_openai_auth
|
||||
&& provider.env_key.is_none()
|
||||
&& provider.experimental_bearer_token.is_none()
|
||||
&& provider.auth.is_none()
|
||||
&& provider.aws.is_none()
|
||||
{
|
||||
RequestMode::GuardianClassifier
|
||||
} else {
|
||||
RequestMode::Regular
|
||||
}
|
||||
}
|
||||
|
||||
async fn runtime_connection(
|
||||
&self,
|
||||
setup: &ClientSetup,
|
||||
) -> Result<Option<PooledConnection>, LunaSamplerError> {
|
||||
if setup.runtime_id.is_none() || !self.config.provider.info().supports_websockets {
|
||||
return Ok(None);
|
||||
}
|
||||
if self
|
||||
.retry_after
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.is_some_and(|deadline| Instant::now() < deadline)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let Ok(permit) = Arc::clone(&self.sockets).try_acquire_owned() else {
|
||||
return Ok(None);
|
||||
};
|
||||
match self.open_connection_with_setup(permit, setup.clone()).await {
|
||||
Ok(connection) => Ok(Some(connection)),
|
||||
Err(LunaSamplerError::ConnectionTimeout) => {
|
||||
*self
|
||||
.retry_after
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) =
|
||||
Some(Instant::now() + CONNECT_COOLDOWN);
|
||||
Ok(None)
|
||||
}
|
||||
Err(
|
||||
error @ LunaSamplerError::Api(ApiError::Transport(
|
||||
TransportError::Policy(_) | TransportError::Build(_),
|
||||
)),
|
||||
) => Err(error),
|
||||
Err(
|
||||
error @ LunaSamplerError::Api(ApiError::Transport(TransportError::Http {
|
||||
status:
|
||||
http::StatusCode::UNAUTHORIZED
|
||||
| http::StatusCode::FORBIDDEN
|
||||
| http::StatusCode::TOO_MANY_REQUESTS,
|
||||
..
|
||||
})),
|
||||
) => Err(error),
|
||||
// Unsupported upgrades and connection failures can still use HTTP.
|
||||
Err(_) => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_connection(
|
||||
&self,
|
||||
permit: OwnedSemaphorePermit,
|
||||
@@ -533,15 +416,13 @@ impl ConnectionPool {
|
||||
provider,
|
||||
auth,
|
||||
http_client_factory,
|
||||
runtime_id,
|
||||
auth_owner,
|
||||
request_kind,
|
||||
redirect_policy: _,
|
||||
key,
|
||||
auth_changes,
|
||||
} = setup;
|
||||
let thread_id = ThreadId::new().to_string();
|
||||
let mut headers = self.headers(&thread_id, request_kind)?;
|
||||
let mut headers = self.headers(&thread_id)?;
|
||||
headers.insert(
|
||||
"openai-beta",
|
||||
HeaderValue::from_static(RESPONSES_WEBSOCKETS_BETA),
|
||||
@@ -611,12 +492,10 @@ impl ConnectionPool {
|
||||
|
||||
Ok(PooledConnection {
|
||||
connection,
|
||||
request_kind,
|
||||
thread_id,
|
||||
expires_at: Instant::now() + MAX_WEBSOCKET_AGE,
|
||||
auth_changes,
|
||||
key,
|
||||
runtime_id,
|
||||
auth_owner,
|
||||
_permit: permit,
|
||||
})
|
||||
@@ -650,7 +529,7 @@ impl ConnectionLease {
|
||||
thread_id: Some(self.thread_id.clone()),
|
||||
extra_headers: self
|
||||
.pool
|
||||
.headers(&self.thread_id, self.request_kind)
|
||||
.headers(&self.thread_id)
|
||||
.map_err(|error| ApiError::Stream(error.to_string()))?,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -664,7 +543,6 @@ impl ConnectionLease {
|
||||
|
||||
pub(super) async fn reuse(self) {
|
||||
if let Connection::Websocket(connection) = self.connection
|
||||
&& connection.runtime_id.is_none()
|
||||
&& !connection.connection.is_closed().await
|
||||
{
|
||||
self.pool
|
||||
|
||||
@@ -12,10 +12,7 @@ use anyhow::Result;
|
||||
use codex_guardian_context::TranscriptCursor;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::WorkspaceRouting;
|
||||
use codex_login::WorkspaceRoutingRequest;
|
||||
use codex_login::WorkspaceRoutingResolver;
|
||||
use codex_model_provider::ModelProviderFuture;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use core_test_support::responses;
|
||||
@@ -184,7 +181,7 @@ async fn replenishes_before_last_idle_socket_is_leased() -> Result<()> {
|
||||
#[tokio::test]
|
||||
async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
for uses_codex_backend in [false, true] {
|
||||
for codex_style_base_path in [false, true] {
|
||||
let http = responses::start_mock_server().await;
|
||||
let events = vec![
|
||||
responses::ev_output_text_delta("low"),
|
||||
@@ -196,7 +193,7 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
|
||||
connections.push(vec![events.clone()]);
|
||||
let ws = responses::start_websocket_server(connections).await;
|
||||
let gateway = Gateway::new(&http.uri(), ws.uri()).await?;
|
||||
let base_path = if uses_codex_backend {
|
||||
let base_path = if codex_style_base_path {
|
||||
"/backend-api/codex"
|
||||
} else {
|
||||
"/v1"
|
||||
@@ -205,11 +202,13 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
|
||||
let mut config = sampler_config(base_url.clone());
|
||||
config.provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(base_url)),
|
||||
Some(AuthManager::from_auth_for_testing(if uses_codex_backend {
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing()
|
||||
} else {
|
||||
CodexAuth::from_api_key("test-api-key")
|
||||
})),
|
||||
Some(AuthManager::from_auth_for_testing(
|
||||
if codex_style_base_path {
|
||||
CodexAuth::from_api_key("Test API Key")
|
||||
} else {
|
||||
CodexAuth::from_api_key("test-api-key")
|
||||
},
|
||||
)),
|
||||
);
|
||||
config.service_tier = Some("priority".to_owned());
|
||||
let sampler = LunaSampler::new(config);
|
||||
@@ -220,10 +219,12 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
let mut request = sample_request("parent-turn");
|
||||
request.parent_response_id = Some("resp-parent".to_owned());
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(5), sampler.sample(request)).await??,
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
sampler.sample(sample_request("parent-turn"))
|
||||
)
|
||||
.await??,
|
||||
"low"
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -253,30 +254,17 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
|
||||
|
||||
let requests = http_mock.requests();
|
||||
let first = &requests[0];
|
||||
let expected_path = if uses_codex_backend {
|
||||
let expected_path = if codex_style_base_path {
|
||||
"/backend-api/codex/responses"
|
||||
} else {
|
||||
"/v1/responses"
|
||||
};
|
||||
assert_eq!(first.path(), expected_path);
|
||||
assert_eq!(
|
||||
first.header("x-codex-guardian").as_deref(),
|
||||
uses_codex_backend.then_some("classifier")
|
||||
);
|
||||
assert_eq!(first.header("x-codex-guardian"), None);
|
||||
assert!(first.header("authorization").is_some());
|
||||
let body = first.body_json();
|
||||
assert_eq!(
|
||||
body["service_tier"].as_str(),
|
||||
if uses_codex_backend {
|
||||
None
|
||||
} else {
|
||||
Some("priority")
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
body["client_metadata"]["parent_response_id"].as_str(),
|
||||
uses_codex_backend.then_some("resp-parent")
|
||||
);
|
||||
assert_eq!(body["service_tier"].as_str(), Some("priority"));
|
||||
assert_eq!(body["client_metadata"].get("parent_response_id"), None);
|
||||
|
||||
gateway.allowed_opens.store(usize::MAX, Ordering::SeqCst);
|
||||
tokio::time::pause();
|
||||
@@ -502,17 +490,6 @@ async fn cancellation_closes_http_before_headers_and_while_draining_the_body() -
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct RoutingPolicy(Mutex<Option<WorkspaceRouting>>);
|
||||
|
||||
impl WorkspaceRoutingResolver for RoutingPolicy {
|
||||
fn resolve(
|
||||
&self,
|
||||
_request: WorkspaceRoutingRequest,
|
||||
) -> ModelProviderFuture<'_, std::io::Result<Option<WorkspaceRouting>>> {
|
||||
Box::pin(async { Ok(self.0.lock().unwrap().clone()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sampling_uses_new_credentials_after_logout_and_login() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
@@ -579,13 +556,9 @@ async fn sampling_uses_new_credentials_after_logout_and_login() -> Result<()> {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_cache_preserves_no_constraint_redirect_policy_and_configured_headers() -> Result<()> {
|
||||
async fn http_cache_reuses_transport_with_default_redirect_policy() -> Result<()> {
|
||||
let base_url = "https://localhost:9/backend-api/codex".to_owned();
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let resolver = Arc::new(RoutingPolicy(Mutex::new(None)));
|
||||
let routing_owner: Arc<dyn WorkspaceRoutingResolver> = resolver.clone();
|
||||
auth.set_workspace_routing_resolver(Arc::downgrade(&routing_owner));
|
||||
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key"));
|
||||
let mut config = sampler_config(base_url.clone());
|
||||
config.provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(base_url)),
|
||||
@@ -595,19 +568,9 @@ async fn http_cache_preserves_no_constraint_redirect_policy_and_configured_heade
|
||||
// Exercise HTTP leases without starting a background WebSocket opener.
|
||||
*pool.retry_after.lock().unwrap() = Some(Instant::now() + CONNECT_COOLDOWN);
|
||||
let mut previous: Option<Arc<HttpTransport>> = None;
|
||||
for (routing, expected_policy) in [
|
||||
(None, ClientRedirectPolicy::Default),
|
||||
(Some("NO_CONSTRAINT"), ClientRedirectPolicy::Reject),
|
||||
(Some("NO_CONSTRAINT"), ClientRedirectPolicy::Reject),
|
||||
(None, ClientRedirectPolicy::Default),
|
||||
] {
|
||||
*resolver.0.lock().unwrap() = routing.map(|account_routing_override| WorkspaceRouting {
|
||||
chatgpt_account_id: "account_id".into(),
|
||||
backend_origin: "https://localhost:9".into(),
|
||||
account_routing_override: account_routing_override.into(),
|
||||
});
|
||||
for _ in 0..2 {
|
||||
let setup = pool.client_setup().await?;
|
||||
assert!(!setup.provider.headers.contains_key(ACCOUNT_ROUTING_HEADER));
|
||||
assert_eq!(setup.redirect_policy, ClientRedirectPolicy::Default);
|
||||
let lease = pool.lease().await?;
|
||||
assert!(matches!(lease.connection, Connection::Http(_)));
|
||||
let cached = Arc::clone(pool.http_transport.lock().unwrap().as_ref().unwrap());
|
||||
@@ -615,293 +578,13 @@ async fn http_cache_preserves_no_constraint_redirect_policy_and_configured_heade
|
||||
(cached.url.as_str(), cached.redirect_policy),
|
||||
(
|
||||
"https://localhost:9/backend-api/codex/responses",
|
||||
expected_policy
|
||||
ClientRedirectPolicy::Default
|
||||
),
|
||||
);
|
||||
if let Some(previous) = previous {
|
||||
assert_eq!(
|
||||
Arc::ptr_eq(&previous, &cached),
|
||||
previous.redirect_policy == expected_policy,
|
||||
);
|
||||
assert!(Arc::ptr_eq(&previous, &cached));
|
||||
}
|
||||
previous = Some(cached);
|
||||
}
|
||||
|
||||
let mut config = sampler_config("https://localhost:9/v1".into());
|
||||
let mut info = config.provider.info().clone();
|
||||
info.http_headers = Some(std::collections::HashMap::from([(
|
||||
ACCOUNT_ROUTING_HEADER.into(),
|
||||
"us".into(),
|
||||
)]));
|
||||
config.provider = create_model_provider(info, config.provider.auth_manager());
|
||||
let pool = ConnectionPool::new(Arc::new(config));
|
||||
*pool.retry_after.lock().unwrap() = Some(Instant::now() + CONNECT_COOLDOWN);
|
||||
assert_eq!(
|
||||
pool.client_setup().await?.redirect_policy,
|
||||
ClientRedirectPolicy::Default
|
||||
);
|
||||
let lease = pool.lease().await?;
|
||||
assert!(matches!(lease.connection, Connection::Http(_)));
|
||||
assert_eq!(
|
||||
pool.http_transport
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.redirect_policy,
|
||||
ClientRedirectPolicy::Reject,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_transports_authenticate_each_classification() -> Result<()> {
|
||||
use base64::Engine;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
struct MutableAuth(Mutex<CodexAuth>);
|
||||
impl codex_login::ExternalAuth for MutableAuth {
|
||||
fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.lock().unwrap().clone()) })
|
||||
}
|
||||
|
||||
fn refresh(
|
||||
&self,
|
||||
_context: codex_login::ExternalAuthRefreshContext,
|
||||
) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
skip_if_no_network!(Ok(()));
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
for transport in [
|
||||
"http",
|
||||
"websocket",
|
||||
"upgrade_required",
|
||||
"legacy_endpoint",
|
||||
"changed_auth",
|
||||
"denied",
|
||||
] {
|
||||
let websocket = transport == "websocket";
|
||||
let denied = transport == "denied";
|
||||
let changed_auth = transport == "changed_auth";
|
||||
let source = Arc::new(MutableAuth(Mutex::new(CodexAuth::from_api_key(
|
||||
"guardian-key",
|
||||
))));
|
||||
let registration = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-guardian",
|
||||
"agent_host_id": "host-guardian",
|
||||
"actor": {"kind": "platform", "user_id": "actor", "organization_id": "org", "project_id": null},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(®istration)
|
||||
.await;
|
||||
let response = vec![
|
||||
responses::ev_output_text_delta("low"),
|
||||
responses::ev_completed("score"),
|
||||
];
|
||||
let ws = if websocket {
|
||||
// Each peer leaves another response available, so closure cannot force the retry.
|
||||
Some(
|
||||
responses::start_websocket_server(vec![
|
||||
vec![response.clone(), response.clone()],
|
||||
vec![response.clone(), response.clone()],
|
||||
])
|
||||
.await,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let http = MockServer::start().await;
|
||||
let upgrade_response = if denied {
|
||||
ResponseTemplate::new(403).set_body_json(json!({"error": {
|
||||
"code": "runtime_instance_paused", "type": "runtime_agent_error",
|
||||
"message": "The runtime agent instance is paused."
|
||||
}}))
|
||||
} else if transport == "legacy_endpoint" {
|
||||
ResponseTemplate::new(404)
|
||||
} else {
|
||||
ResponseTemplate::new(426)
|
||||
};
|
||||
let handshake_source = Arc::clone(&source);
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/responses"))
|
||||
.respond_with(move |_request: &wiremock::Request| {
|
||||
if changed_auth {
|
||||
*handshake_source.0.lock().unwrap() =
|
||||
CodexAuth::from_api_key("replacement-key");
|
||||
}
|
||||
upgrade_response.clone()
|
||||
})
|
||||
.expect(match transport {
|
||||
"upgrade_required" | "legacy_endpoint" => 2,
|
||||
"changed_auth" | "denied" => 1,
|
||||
_ => 0,
|
||||
})
|
||||
.mount(&http)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/responses"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.insert_header("content-type", "text/event-stream")
|
||||
.set_body_string(responses::sse(response)),
|
||||
)
|
||||
.expect(if websocket || denied {
|
||||
0
|
||||
} else if changed_auth {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
})
|
||||
.mount(&http)
|
||||
.await;
|
||||
let url = ws.as_ref().map_or_else(
|
||||
|| http.uri(),
|
||||
|ws| ws.uri().replacen("ws://", "http://", /*count*/ 1),
|
||||
);
|
||||
let mut config = sampler_config(url);
|
||||
let credentials =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("guardian-key"));
|
||||
if changed_auth {
|
||||
credentials.set_external_auth(source.clone()).await?;
|
||||
}
|
||||
let runtime = Arc::new(RuntimeAuthManager::new(
|
||||
Arc::clone(&credentials),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: uuid::Uuid::nil(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: Some("codex".into()),
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/register", registration.uri()).parse()?,
|
||||
));
|
||||
let mut info = config.provider.info().clone();
|
||||
info.supports_websockets = transport != "http";
|
||||
config.provider = codex_model_provider::test_support::runtime_model_provider(
|
||||
info,
|
||||
Arc::clone(&credentials),
|
||||
(runtime, mode),
|
||||
);
|
||||
let sampler = LunaSampler::new(config);
|
||||
sampler.prewarm().await;
|
||||
if let Some(ws) = &ws {
|
||||
assert!(
|
||||
ws.handshakes().is_empty(),
|
||||
"prewarming must not admit runtime work"
|
||||
);
|
||||
}
|
||||
if denied {
|
||||
let error = sampler.sample(sample_request("denied")).await.unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
error,
|
||||
LunaSamplerError::Api(ApiError::Transport(TransportError::Http {
|
||||
status: http::StatusCode::FORBIDDEN,
|
||||
..
|
||||
}))
|
||||
),
|
||||
"{error:?}"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(sampler.sample(sample_request("first")).await?, "low");
|
||||
if changed_auth {
|
||||
assert_eq!(
|
||||
credentials.auth().await.unwrap().get_token()?,
|
||||
"replacement-key"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(sampler.sample(sample_request("second")).await?, "low");
|
||||
}
|
||||
}
|
||||
let headers = if let Some(ws) = &ws {
|
||||
assert_eq!(
|
||||
ws.connections().iter().map(Vec::len).collect::<Vec<_>>(),
|
||||
vec![1, 1]
|
||||
);
|
||||
ws.handshakes()
|
||||
.iter()
|
||||
.map(|h| {
|
||||
(
|
||||
h.header("authorization").unwrap(),
|
||||
h.header("x-openai-agent-assertion"),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
http.received_requests()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|request| {
|
||||
(
|
||||
request.headers["authorization"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned(),
|
||||
request
|
||||
.headers
|
||||
.get("x-openai-agent-assertion")
|
||||
.map(|value| value.to_str().unwrap().to_owned()),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let expected_attempts = match transport {
|
||||
"upgrade_required" | "legacy_endpoint" => 4,
|
||||
"denied" => 1,
|
||||
_ => 2,
|
||||
};
|
||||
assert_eq!(headers.len(), expected_attempts);
|
||||
let mut proofs = std::collections::BTreeSet::new();
|
||||
for (authorization, supplemental) in headers {
|
||||
let proof = match mode {
|
||||
RuntimeAuthMode::DualHeader => {
|
||||
assert_eq!(authorization, "Bearer guardian-key");
|
||||
supplemental.unwrap()
|
||||
}
|
||||
RuntimeAuthMode::AssertionOnly => {
|
||||
assert!(supplemental.is_none());
|
||||
authorization
|
||||
.strip_prefix("AgentAssertion ")
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
}
|
||||
};
|
||||
let payload: serde_json::Value = serde_json::from_slice(
|
||||
&base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(proof.split('.').nth(/*n*/ 2).unwrap())?,
|
||||
)?;
|
||||
assert_eq!(payload["runtime_agent_instance"], "runtime-guardian");
|
||||
assert!(
|
||||
proofs.insert(proof),
|
||||
"each attempt must authenticate afresh"
|
||||
);
|
||||
}
|
||||
registration.verify().await;
|
||||
http.verify().await;
|
||||
drop(sampler);
|
||||
if let Some(ws) = ws {
|
||||
ws.shutdown().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ use super::LunaSamplerConfig;
|
||||
use super::LunaSamplerError;
|
||||
use super::MAX_OUTPUT_BYTES;
|
||||
use super::SampledScore;
|
||||
use super::connection_pool::RequestMode;
|
||||
use super::response::PendingResponse;
|
||||
use super::telemetry::SamplingTelemetry;
|
||||
use super::telemetry::record_retry;
|
||||
@@ -18,14 +17,12 @@ use codex_api::ApiError;
|
||||
use codex_api::ResponseEvent;
|
||||
use codex_api::ResponsesApiRequest;
|
||||
use codex_api::TransportError;
|
||||
use codex_core::cyber_access_program;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_login::AuthOwner;
|
||||
use codex_login::UnauthorizedRecovery;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::TokenUsage;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
use http::StatusCode;
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
@@ -39,12 +36,10 @@ const TURN_METADATA_KEY: &str = "x-codex-turn-metadata";
|
||||
|
||||
pub(super) struct SamplingExecution {
|
||||
pub(super) auth_owner: Option<AuthOwner>,
|
||||
pub(super) cyber_access_program: Option<CyberAccessProgram>,
|
||||
pub(super) config: Arc<LunaSamplerConfig>,
|
||||
pub(super) connections: Arc<ConnectionPool>,
|
||||
pub(super) request: ResponsesApiRequest,
|
||||
pub(super) turn_id: String,
|
||||
pub(super) parent_response_id: Option<String>,
|
||||
pub(super) parent_turn_id: String,
|
||||
pub(super) root_turn_id: Option<String>,
|
||||
}
|
||||
@@ -243,29 +238,8 @@ impl SamplingExecution {
|
||||
{
|
||||
return Err(account_changed_error());
|
||||
}
|
||||
// Omitted programs need no auth lookup, which can refresh credentials.
|
||||
self.request.access_programs = match self.cyber_access_program {
|
||||
None => None,
|
||||
Some(program) => {
|
||||
let auth = tokio::select! {
|
||||
biased;
|
||||
_ = &mut owner_changed => return Err(account_changed_error()),
|
||||
auth = self.config.provider.auth() => auth,
|
||||
};
|
||||
cyber_access_program::for_auth(
|
||||
auth.as_ref(),
|
||||
Some(program),
|
||||
self.config.api_key_cyber_access_programs,
|
||||
)
|
||||
.map_err(LunaSamplerError::Provider)?
|
||||
}
|
||||
};
|
||||
ensure_account_owner()?;
|
||||
self.request.service_tier = if lease.request_kind == RequestMode::GuardianClassifier {
|
||||
None
|
||||
} else {
|
||||
self.config.service_tier.clone()
|
||||
};
|
||||
self.request.service_tier = self.config.service_tier.clone();
|
||||
let thread_id = &lease.thread_id;
|
||||
let mut turn_metadata = json!({
|
||||
"session_id": self.config.session_id,
|
||||
@@ -291,11 +265,6 @@ impl SamplingExecution {
|
||||
turn_metadata["root_turn_id"] = json!(root_turn_id);
|
||||
}
|
||||
client_metadata.insert(TURN_METADATA_KEY.to_owned(), turn_metadata.to_string());
|
||||
if lease.request_kind == RequestMode::GuardianClassifier
|
||||
&& let Some(parent_response_id) = &self.parent_response_id
|
||||
{
|
||||
client_metadata.insert("parent_response_id".to_owned(), parent_response_id.clone());
|
||||
}
|
||||
self.request.client_metadata = Some(client_metadata);
|
||||
let stream = match tokio::select! {
|
||||
biased;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Keeps classifier evidence within its owning account and thread routing binding.
|
||||
//! Keeps classifier evidence within the credential owner that started the request.
|
||||
|
||||
use super::connect_sampler;
|
||||
use super::proxy_websocket_servers;
|
||||
@@ -10,66 +10,23 @@ use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use codex_login::WorkspaceRouting;
|
||||
use codex_login::WorkspaceRoutingRequest;
|
||||
use codex_login::WorkspaceRoutingResolver;
|
||||
use codex_model_provider::ModelProviderFuture;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::responses::WebSocketConnectionConfig;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
type RoutingFuture<'a> = ModelProviderFuture<'a, std::io::Result<Option<WorkspaceRouting>>>;
|
||||
|
||||
struct UnavailableRouting;
|
||||
|
||||
impl WorkspaceRoutingResolver for UnavailableRouting {
|
||||
fn resolve(&self, _request: WorkspaceRoutingRequest) -> RoutingFuture<'_> {
|
||||
Box::pin(async { Err(std::io::Error::other("discovery unavailable")) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_routing_blocks_a_prewarmed_classifier_connection() -> Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let response = vec![vec![ev_assistant_message("r1", "low"), ev_completed("r1")]];
|
||||
let server = responses::start_websocket_server(vec![response.clone(), response]).await;
|
||||
let base_url = proxy_websocket_servers(&[&server, &server])
|
||||
.await?
|
||||
.replace("/v1", "/backend-api/codex");
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let mut config = sampler_config(base_url.clone());
|
||||
config.provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(base_url)),
|
||||
Some(auth.clone()),
|
||||
);
|
||||
let sampler = connect_sampler(config).await?;
|
||||
let resolver: Arc<dyn WorkspaceRoutingResolver> = Arc::new(UnavailableRouting);
|
||||
auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
|
||||
let error = sampler.sample(sample_request("turn-1")).await.unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains("discovery unavailable"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(server.connections().iter().all(Vec::is_empty));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct AuthAfterRouting {
|
||||
/// Host-supplied credentials that switch to a different key once `resolved` is set.
|
||||
struct SwitchingAuth {
|
||||
initial: CodexAuth,
|
||||
updated: CodexAuth,
|
||||
resolved: AtomicBool,
|
||||
}
|
||||
|
||||
impl ExternalAuth for AuthAfterRouting {
|
||||
impl ExternalAuth for SwitchingAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async {
|
||||
Ok(if self.resolved.load(Ordering::SeqCst) {
|
||||
@@ -85,152 +42,9 @@ impl ExternalAuth for AuthAfterRouting {
|
||||
}
|
||||
}
|
||||
|
||||
impl WorkspaceRoutingResolver for AuthAfterRouting {
|
||||
fn resolve(&self, _request: WorkspaceRoutingRequest) -> RoutingFuture<'_> {
|
||||
Box::pin(async {
|
||||
self.resolved.store(/*val*/ true, Ordering::SeqCst);
|
||||
Ok(None)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn classification_retries_refreshes_but_never_switches_accounts() -> Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
// Both tokens identify the same user; their signatures differ after refresh.
|
||||
let token =
|
||||
"header.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91c2VyX2lkIjoidXNlci1hIn19";
|
||||
for account in ["workspace-a", "workspace-b"] {
|
||||
let server = responses::start_mock_server().await;
|
||||
let response = responses::mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
ev_assistant_message("score", "low"),
|
||||
ev_completed("score"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let home = tempfile::tempdir()?;
|
||||
let changes = Arc::new(AuthAfterRouting {
|
||||
initial: CodexAuth::from_external_chatgpt_tokens(
|
||||
&format!("{token}.initial"),
|
||||
"workspace-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
updated: CodexAuth::from_external_chatgpt_tokens(
|
||||
&format!("{token}.refreshed"),
|
||||
account,
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
resolved: AtomicBool::new(/*v*/ false),
|
||||
});
|
||||
let auth = AuthManager::from_auth_for_testing_with_home(
|
||||
changes.initial.clone(),
|
||||
home.path().to_owned(),
|
||||
);
|
||||
auth.set_external_auth(changes.clone()).await?;
|
||||
let resolver: Arc<dyn WorkspaceRoutingResolver> = changes;
|
||||
auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
|
||||
let mut config = sampler_config(format!("{}/backend-api/codex", server.uri()));
|
||||
config.provider = create_model_provider(config.provider.info().clone(), Some(auth));
|
||||
let sampler = super::LunaSampler::new(config);
|
||||
let result = sampler.sample(sample_request("turn-1")).await;
|
||||
if account == "workspace-a" {
|
||||
assert_eq!(result?, "low");
|
||||
let request = response.single_request();
|
||||
assert_eq!(
|
||||
(
|
||||
request.header("chatgpt-account-id"),
|
||||
request.header("authorization")
|
||||
),
|
||||
(
|
||||
Some("workspace-a".into()),
|
||||
Some(format!("Bearer {token}.refreshed"))
|
||||
),
|
||||
);
|
||||
} else {
|
||||
assert!(result.unwrap_err().to_string().contains("account changed"));
|
||||
assert!(
|
||||
response.requests().is_empty(),
|
||||
"evidence must not reach the new account"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct ChangedBootstrap(AtomicBool);
|
||||
|
||||
impl WorkspaceRoutingResolver for ChangedBootstrap {
|
||||
fn resolve(&self, request: WorkspaceRoutingRequest) -> RoutingFuture<'_> {
|
||||
Box::pin(async move {
|
||||
if request.previously_routed {
|
||||
Err(std::io::Error::other(
|
||||
"bootstrap changed; start a new thread",
|
||||
))
|
||||
} else if self.0.swap(/*val*/ false, Ordering::SeqCst) {
|
||||
Ok(Some(WorkspaceRouting {
|
||||
chatgpt_account_id: "account_id".into(),
|
||||
backend_origin: "https://gov.chatgpt.com".into(),
|
||||
account_routing_override: "us_cr".into(),
|
||||
}))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn idle_classifier_retains_the_owning_threads_workspace_binding() -> Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let thread_server = responses::start_mock_server().await;
|
||||
let test = core_test_support::test_codex::test_codex()
|
||||
.with_auth_manager(Arc::clone(&auth))
|
||||
.build_with_auto_env(&thread_server)
|
||||
.await?;
|
||||
let server = responses::start_mock_server().await;
|
||||
let resolver: Arc<dyn WorkspaceRoutingResolver> =
|
||||
Arc::new(ChangedBootstrap(AtomicBool::new(/*v*/ true)));
|
||||
auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
|
||||
let mut config = test.config.clone();
|
||||
config.model_provider = ModelProviderInfo::create_openai_provider(Some(format!(
|
||||
"{}/backend-api/codex",
|
||||
server.uri()
|
||||
)));
|
||||
let session_store = codex_extension_api::ExtensionData::new("session-1");
|
||||
let input = codex_extension_api::ThreadStartInput {
|
||||
config: &config,
|
||||
session_source: &codex_protocol::protocol::SessionSource::Exec,
|
||||
persistent_thread_state_available: false,
|
||||
environments: &[],
|
||||
mcp_resource_client: None,
|
||||
extension_metrics: None,
|
||||
session_store: &session_store,
|
||||
thread_store: test.codex.thread_extension_data(),
|
||||
};
|
||||
let owning_context = input
|
||||
.thread_store
|
||||
.get::<codex_model_provider::WorkspaceRoutingContext>()
|
||||
.expect("Core seeds the owning thread's routing context before extensions start");
|
||||
let classifier = crate::async_scorer::startup::sampler_config(&input, /*manager*/ None).await;
|
||||
classifier
|
||||
.provider
|
||||
.responses_api_provider(&owning_context)
|
||||
.await?;
|
||||
let sampler = super::LunaSampler::new(classifier);
|
||||
let error = sampler.sample(sample_request("turn-1")).await.unwrap_err();
|
||||
assert!(error.to_string().contains("start a new thread"), "{error}");
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_switch_cancels_request_opening_and_first_token_waits() -> Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let token = "header.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91c2VyX2lkIjoidXNlci1hIn19.signature";
|
||||
for transport in ["http", "websocket"] {
|
||||
let http = responses::start_mock_server().await;
|
||||
let opening = responses::mount_response_once(
|
||||
@@ -245,17 +59,9 @@ async fn account_switch_cancels_request_opening_and_first_token_waits() -> Resul
|
||||
close_after_requests: false,
|
||||
};
|
||||
let websocket = responses::start_websocket_server_with_headers(vec![stalled; 2]).await;
|
||||
let changes = Arc::new(AuthAfterRouting {
|
||||
initial: CodexAuth::from_external_chatgpt_tokens(
|
||||
token,
|
||||
"workspace-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
updated: CodexAuth::from_external_chatgpt_tokens(
|
||||
token,
|
||||
"workspace-b",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
let changes = Arc::new(SwitchingAuth {
|
||||
initial: CodexAuth::from_api_key("key-a"),
|
||||
updated: CodexAuth::from_api_key("key-b"),
|
||||
resolved: AtomicBool::new(/*v*/ false),
|
||||
});
|
||||
let home = tempfile::tempdir()?;
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
use anyhow::Result;
|
||||
use codex_api::ApiError;
|
||||
use codex_context_fragments::RenderedFragment;
|
||||
use codex_core::cyber_access_program::ApiKeyCyberAccessPrograms;
|
||||
use codex_extension_api::ContextualUserFragment;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_guardian_context::PreviousReviews;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::AgentIdentityAuthPolicy;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
@@ -23,16 +21,14 @@ use codex_protocol::TranscriptFormat;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
use codex_protocol_test_support::uuid_v7_item_id_generator_for_test;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::responses::WebSocketConnectionConfig;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::ev_completed_with_tokens;
|
||||
use core_test_support::responses::ev_model_verification_metadata;
|
||||
use core_test_support::responses::ev_output_text_delta;
|
||||
use core_test_support::responses::ev_response_metadata;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
@@ -241,11 +237,6 @@ pub(in crate::async_scorer) async fn proxy_websocket_servers_with_http(
|
||||
|
||||
pub(in crate::async_scorer) fn sampler_config(base_url: String) -> LunaSamplerConfig {
|
||||
LunaSamplerConfig {
|
||||
api_key_cyber_access_programs: ApiKeyCyberAccessPrograms::Disabled,
|
||||
inherit_parent_cyber_access_program: true,
|
||||
workspace_routing: codex_model_provider::WorkspaceRoutingContext::new(
|
||||
"https://chatgpt.com/backend-api".into(),
|
||||
),
|
||||
provider: create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(base_url)),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
@@ -253,8 +244,6 @@ pub(in crate::async_scorer) fn sampler_config(base_url: String) -> LunaSamplerCo
|
||||
))),
|
||||
),
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
agent_identity_policy: AgentIdentityAuthPolicy::JwtOnly,
|
||||
session_source: SessionSource::Exec,
|
||||
session_id: "session-1".to_owned(),
|
||||
thread_id: "thread-1".to_owned(),
|
||||
originator: Some("guardian-v2-test".to_owned()),
|
||||
@@ -308,8 +297,6 @@ fn assert_classifier_instructions(request: &serde_json::Value) {
|
||||
pub(in crate::async_scorer) fn sample_request(parent_turn_id: &str) -> LunaSamplingRequest {
|
||||
LunaSamplingRequest {
|
||||
item_id_generator: uuid_v7_item_id_generator_for_test(),
|
||||
cyber_access_program: None,
|
||||
parent_response_id: None,
|
||||
instructions: classifier_instructions(),
|
||||
input: vec![responses::user_message_item(
|
||||
"The user requested a README summary.",
|
||||
@@ -322,60 +309,6 @@ pub(in crate::async_scorer) fn sample_request(parent_turn_id: &str) -> LunaSampl
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn classifier_preserves_api_key_cyber_program_policy() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
for policy in [
|
||||
ApiKeyCyberAccessPrograms::Enabled,
|
||||
ApiKeyCyberAccessPrograms::Disabled,
|
||||
ApiKeyCyberAccessPrograms::UnsupportedProvider,
|
||||
] {
|
||||
let server = responses::start_mock_server().await;
|
||||
let response = responses::mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
ev_assistant_message("score", "low"),
|
||||
ev_completed("score"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let mut config = sampler_config(server.uri());
|
||||
config.api_key_cyber_access_programs = policy;
|
||||
let sampler = LunaSampler::new(config);
|
||||
let mut request = sample_request("parent");
|
||||
request.cyber_access_program = Some(CyberAccessProgram::DaybreakRed);
|
||||
let result = sampler.sample(request).await;
|
||||
match policy {
|
||||
ApiKeyCyberAccessPrograms::Disabled => {
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("Cyber access programs are disabled for this API-key session.")
|
||||
);
|
||||
assert!(response.requests().is_empty());
|
||||
}
|
||||
ApiKeyCyberAccessPrograms::Enabled | ApiKeyCyberAccessPrograms::UnsupportedProvider => {
|
||||
assert_eq!(result?, "low");
|
||||
let expected = match policy {
|
||||
ApiKeyCyberAccessPrograms::Enabled => Some(json!({"cyber": "daybreak_blue"})),
|
||||
ApiKeyCyberAccessPrograms::UnsupportedProvider => None,
|
||||
ApiKeyCyberAccessPrograms::Disabled => unreachable!(),
|
||||
};
|
||||
assert_eq!(
|
||||
response
|
||||
.single_request()
|
||||
.body_json()
|
||||
.get("access_programs")
|
||||
.cloned(),
|
||||
expected,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
type RecordedMetric = (String, i64, Vec<(String, String)>);
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -534,40 +467,23 @@ impl ExternalAuth for RefreshableAuth {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn classifier_sends_guardian_header_only_with_codex_backend_auth() -> Result<()> {
|
||||
async fn classifier_never_sends_backend_classifier_header() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
for (auth, base_path, expected_header, expected_service_tier) in [
|
||||
// Every provider and credential uses the regular Responses route: no classifier header,
|
||||
// no routing hint, and the configured service tier is forwarded unchanged.
|
||||
for (auth, base_path) in [
|
||||
(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
CodexAuth::from_api_key("Test API Key"),
|
||||
"/backend-api/codex",
|
||||
Some("classifier"),
|
||||
None,
|
||||
),
|
||||
(
|
||||
CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new())),
|
||||
"/api/codex",
|
||||
Some("classifier"),
|
||||
None,
|
||||
),
|
||||
(
|
||||
CodexAuth::from_api_key("test-api-key"),
|
||||
"/api/codex",
|
||||
None,
|
||||
Some("priority"),
|
||||
),
|
||||
(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
"/v1",
|
||||
Some("classifier"),
|
||||
None,
|
||||
),
|
||||
(
|
||||
CodexAuth::from_api_key("test-api-key"),
|
||||
"/v1",
|
||||
None,
|
||||
Some("priority"),
|
||||
),
|
||||
(CodexAuth::from_api_key("test-api-key"), "/api/codex"),
|
||||
(CodexAuth::from_api_key("Test API Key"), "/v1"),
|
||||
(CodexAuth::from_api_key("test-api-key"), "/v1"),
|
||||
] {
|
||||
let events = vec![
|
||||
ev_assistant_message("classification", "low"),
|
||||
@@ -591,10 +507,7 @@ async fn classifier_sends_guardian_header_only_with_codex_backend_auth() -> Resu
|
||||
assert_eq!(sampler.sample(sample_request("turn-1")).await?, "low");
|
||||
for handshake in server.handshakes() {
|
||||
assert_eq!(handshake.uri(), format!("{base_path}/responses"));
|
||||
assert_eq!(
|
||||
handshake.header("x-codex-guardian").as_deref(),
|
||||
expected_header
|
||||
);
|
||||
assert_eq!(handshake.header("x-codex-guardian"), None);
|
||||
assert_eq!(handshake.header("x-codex-routing-hint"), None);
|
||||
}
|
||||
let request = server
|
||||
@@ -604,7 +517,8 @@ async fn classifier_sends_guardian_header_only_with_codex_backend_auth() -> Resu
|
||||
)
|
||||
.await
|
||||
.body_json();
|
||||
assert_eq!(request["service_tier"].as_str(), expected_service_tier);
|
||||
assert_eq!(request["service_tier"].as_str(), Some("priority"));
|
||||
assert_eq!(request["client_metadata"].get("parent_response_id"), None);
|
||||
|
||||
drop(sampler);
|
||||
server.shutdown().await;
|
||||
@@ -620,7 +534,7 @@ async fn preconnected_sampler_reuses_authenticated_websocket_for_classifications
|
||||
let scripted_requests = vec![
|
||||
vec![
|
||||
ev_output_text_delta("low"),
|
||||
ev_model_verification_metadata("response-1", vec!["trusted_access_for_cyber"]),
|
||||
ev_response_metadata("response-1", json!({"unrelated": ["ignored"]})),
|
||||
ev_assistant_message("sample-1", "low"),
|
||||
ev_completed("response-1"),
|
||||
],
|
||||
@@ -658,15 +572,8 @@ async fn preconnected_sampler_reuses_authenticated_websocket_for_classifications
|
||||
);
|
||||
|
||||
let sampler = connect_sampler(LunaSamplerConfig {
|
||||
api_key_cyber_access_programs: ApiKeyCyberAccessPrograms::Disabled,
|
||||
inherit_parent_cyber_access_program: true,
|
||||
workspace_routing: codex_model_provider::WorkspaceRoutingContext::new(
|
||||
"https://chatgpt.com/backend-api".into(),
|
||||
),
|
||||
provider,
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
agent_identity_policy: AgentIdentityAuthPolicy::JwtOnly,
|
||||
session_source: SessionSource::Exec,
|
||||
session_id: "session-1".to_owned(),
|
||||
thread_id: "thread-1".to_owned(),
|
||||
originator: Some("guardian-v2-test".to_owned()),
|
||||
@@ -707,8 +614,6 @@ async fn preconnected_sampler_reuses_authenticated_websocket_for_classifications
|
||||
let first = sampler
|
||||
.sample(LunaSamplingRequest {
|
||||
item_id_generator: uuid_v7_item_id_generator_for_test(),
|
||||
cyber_access_program: None,
|
||||
parent_response_id: None,
|
||||
instructions: classifier_instructions(),
|
||||
input: vec![ResponseItem::Message {
|
||||
status: None,
|
||||
@@ -754,8 +659,6 @@ async fn preconnected_sampler_reuses_authenticated_websocket_for_classifications
|
||||
let second = sampler
|
||||
.sample(LunaSamplingRequest {
|
||||
item_id_generator: uuid_v7_item_id_generator_for_test(),
|
||||
cyber_access_program: None,
|
||||
parent_response_id: None,
|
||||
instructions: classifier_instructions(),
|
||||
input: vec![responses::user_message_item(
|
||||
"The user requested a source review.",
|
||||
@@ -841,15 +744,8 @@ async fn sampler_returns_classification_token_before_terminal_response_events()
|
||||
))),
|
||||
);
|
||||
let sampler = connect_sampler(LunaSamplerConfig {
|
||||
api_key_cyber_access_programs: ApiKeyCyberAccessPrograms::Disabled,
|
||||
inherit_parent_cyber_access_program: true,
|
||||
workspace_routing: codex_model_provider::WorkspaceRoutingContext::new(
|
||||
"https://chatgpt.com/backend-api".into(),
|
||||
),
|
||||
provider,
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
agent_identity_policy: AgentIdentityAuthPolicy::JwtOnly,
|
||||
session_source: SessionSource::Exec,
|
||||
session_id: "session-1".to_owned(),
|
||||
thread_id: "thread-1".to_owned(),
|
||||
originator: None,
|
||||
@@ -1210,9 +1106,9 @@ async fn sampler_limits_transient_recovery_attempts() -> Result<()> {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn parent_response_id_survives_classifier_transport_retry() -> Result<()> {
|
||||
async fn classifier_transport_retry_sends_no_backend_metadata() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
for uses_codex_backend in [false, true] {
|
||||
for codex_style_base_path in [false, true] {
|
||||
let healthy = responses::start_websocket_server(vec![vec![vec![
|
||||
ev_assistant_message("resp-review", "low"),
|
||||
ev_completed("resp-review"),
|
||||
@@ -1224,15 +1120,15 @@ async fn parent_response_id_survives_classifier_transport_retry() -> Result<()>
|
||||
})]]]).await;
|
||||
let base_url = proxy_websocket_servers(&[&healthy, &expired]).await?;
|
||||
let mut config = sampler_config(base_url.clone());
|
||||
if uses_codex_backend {
|
||||
if codex_style_base_path {
|
||||
config.provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(format!(
|
||||
"{}/backend-api/codex",
|
||||
base_url.trim_end_matches("/v1")
|
||||
))),
|
||||
Some(AuthManager::from_auth_for_testing(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
)),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"Test API Key",
|
||||
))),
|
||||
);
|
||||
}
|
||||
let metrics = Arc::new(RecordingMetrics::default());
|
||||
@@ -1245,10 +1141,7 @@ async fn parent_response_id_survives_classifier_transport_retry() -> Result<()>
|
||||
.lock()
|
||||
.unwrap()
|
||||
.sort_by_key(|connection| connection.thread_id == expired_id);
|
||||
let parent_response_id = "resp-parent";
|
||||
let mut request = sample_request("turn-1");
|
||||
request.parent_response_id = Some(parent_response_id.to_owned());
|
||||
assert_eq!(sampler.sample(request).await?, "low");
|
||||
assert_eq!(sampler.sample(sample_request("turn-1")).await?, "low");
|
||||
metrics.assert_outcome("success", /*attempts*/ 2, "none");
|
||||
for server in [&expired, &healthy] {
|
||||
let requests = server.single_connection();
|
||||
@@ -1256,12 +1149,11 @@ async fn parent_response_id_survives_classifier_transport_retry() -> Result<()>
|
||||
let body = requests[0].body_json();
|
||||
assert_eq!(
|
||||
(
|
||||
body["client_metadata"].get("parent_response_id").cloned(),
|
||||
body["client_metadata"].get("parent_response_id"),
|
||||
body["client_metadata"].get("guardian_credits_requested"),
|
||||
),
|
||||
(uses_codex_backend.then(|| json!(parent_response_id)), None)
|
||||
(None, None)
|
||||
);
|
||||
assert!(!body["input"].to_string().contains(parent_response_id));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,11 +5,8 @@ use std::sync::Arc;
|
||||
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::cyber_access_program::ApiKeyCyberAccessPrograms;
|
||||
use codex_extension_api::ThreadOriginator;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_features::Feature;
|
||||
use codex_login::AgentIdentityAuthPolicy;
|
||||
|
||||
use super::sampler::LunaSamplerConfig;
|
||||
use super::sampler::MODEL;
|
||||
@@ -18,8 +15,6 @@ pub(super) async fn sampler_config(
|
||||
input: &ThreadStartInput<'_, Config>,
|
||||
manager: Option<Arc<ThreadManager>>,
|
||||
) -> LunaSamplerConfig {
|
||||
let inherit_parent_cyber_access_program =
|
||||
codex_core::RequiredCyberAccessPrograms::for_thread(input.thread_store).is_none();
|
||||
let luna_model = if let Some(thread_manager) = manager {
|
||||
let mut model_config = input.config.to_models_manager_config();
|
||||
model_config.model_context_window = None;
|
||||
@@ -47,21 +42,8 @@ pub(super) async fn sampler_config(
|
||||
.get::<codex_model_provider::ProviderAuthContext>()
|
||||
.expect("Core installs provider auth before starting Guardian");
|
||||
LunaSamplerConfig {
|
||||
api_key_cyber_access_programs: ApiKeyCyberAccessPrograms::from_config(input.config),
|
||||
inherit_parent_cyber_access_program,
|
||||
workspace_routing: input
|
||||
.thread_store
|
||||
.get_or_init(|| input.config.workspace_routing_context())
|
||||
.as_ref()
|
||||
.clone(),
|
||||
provider: auth.model_provider(input.config.model_provider.clone()),
|
||||
http_client_factory: input.config.http_client_factory(),
|
||||
agent_identity_policy: if input.config.features.enabled(Feature::UseAgentIdentity) {
|
||||
AgentIdentityAuthPolicy::ChatGptAuth
|
||||
} else {
|
||||
AgentIdentityAuthPolicy::JwtOnly
|
||||
},
|
||||
session_source: input.session_source.clone(),
|
||||
session_id: input.session_store.level_id().to_string(),
|
||||
thread_id: input.thread_store.level_id().to_string(),
|
||||
originator: input
|
||||
|
||||
@@ -3,81 +3,22 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_extension_api::McpToolInfo;
|
||||
use codex_extension_api::McpToolSource;
|
||||
use codex_features::Feature;
|
||||
use codex_guardian_context::TrustedTool;
|
||||
use codex_guardian_context::TrustedToolSource;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum PluginCapability {
|
||||
Connector,
|
||||
Mcp,
|
||||
}
|
||||
|
||||
pub(crate) async fn trusted_tool_context(
|
||||
tool: &McpToolInfo,
|
||||
source: &McpToolSource,
|
||||
manager: &ThreadManager,
|
||||
config: &Config,
|
||||
) -> Option<TrustedTool> {
|
||||
if source == &McpToolSource::Connector
|
||||
&& tool
|
||||
.connector_id
|
||||
.as_deref()
|
||||
.is_some_and(|connector_id| !connector_id.trim().is_empty())
|
||||
&& config
|
||||
.features
|
||||
.enabled(Feature::GuardianTrustOrchestratorConnectors)
|
||||
{
|
||||
return Some(TrustedTool {
|
||||
server: tool.server_name.clone(),
|
||||
connector_id: tool.connector_id.clone(),
|
||||
source: TrustedToolSource::PluginServiceOrchestrator,
|
||||
});
|
||||
}
|
||||
|
||||
let codex_home = config.codex_home.as_path().canonicalize().ok()?;
|
||||
let plugins = match source {
|
||||
McpToolSource::Connector => Some(
|
||||
manager
|
||||
.plugins_manager()
|
||||
.plugins_for_config(&config.plugins_config_input())
|
||||
.await,
|
||||
),
|
||||
McpToolSource::Config | McpToolSource::Plugin { .. } => None,
|
||||
McpToolSource::SelectedPlugin | McpToolSource::Other => return None,
|
||||
};
|
||||
|
||||
let source = match source {
|
||||
McpToolSource::Connector => {
|
||||
let connector_id = tool.connector_id.as_deref()?;
|
||||
if let Some(plugin) = plugins.as_ref()?.plugins().iter().find(|plugin| {
|
||||
plugin.is_active()
|
||||
&& plugin
|
||||
.apps
|
||||
.iter()
|
||||
.any(|app| app.connector_id.0 == connector_id)
|
||||
&& is_home_owned_plugin_capability(
|
||||
plugin.root.as_path(),
|
||||
&codex_home,
|
||||
PluginCapability::Connector,
|
||||
)
|
||||
}) {
|
||||
plugin.root.as_path().display().to_string()
|
||||
} else {
|
||||
trusted_user_config_source(config, "apps", connector_id, &codex_home)?
|
||||
}
|
||||
}
|
||||
McpToolSource::Plugin { root, .. } => {
|
||||
let plugin_root = root.to_abs_path().ok()?;
|
||||
if !is_home_owned_plugin_capability(
|
||||
plugin_root.as_path(),
|
||||
&codex_home,
|
||||
PluginCapability::Mcp,
|
||||
) {
|
||||
if !is_home_owned_plugin_mcp(plugin_root.as_path(), &codex_home) {
|
||||
return None;
|
||||
}
|
||||
plugin_root.as_path().display().to_string()
|
||||
@@ -90,16 +31,12 @@ pub(crate) async fn trusted_tool_context(
|
||||
|
||||
Some(TrustedTool {
|
||||
server: tool.server_name.clone(),
|
||||
connector_id: tool.connector_id.clone(),
|
||||
connector_id: None,
|
||||
source: TrustedToolSource::UserConfiguration(source),
|
||||
})
|
||||
}
|
||||
|
||||
fn is_home_owned_plugin_capability(
|
||||
plugin_root: &Path,
|
||||
codex_home: &Path,
|
||||
capability: PluginCapability,
|
||||
) -> bool {
|
||||
fn is_home_owned_plugin_mcp(plugin_root: &Path, codex_home: &Path) -> bool {
|
||||
if !is_home_owned_path(plugin_root, codex_home) {
|
||||
return false;
|
||||
}
|
||||
@@ -126,21 +63,12 @@ fn is_home_owned_plugin_capability(
|
||||
let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&manifest_contents) else {
|
||||
return false;
|
||||
};
|
||||
let declaration_path = match capability {
|
||||
PluginCapability::Connector => manifest
|
||||
.get("apps")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map_or_else(
|
||||
|| plugin_root.join(".app.json"),
|
||||
|path| plugin_root.join(path),
|
||||
),
|
||||
PluginCapability::Mcp => match manifest.get("mcpServers") {
|
||||
Some(serde_json::Value::Object(_)) => manifest_path,
|
||||
Some(serde_json::Value::String(path)) => plugin_root.join(path),
|
||||
Some(_) => return false,
|
||||
None if manifest_path == root_manifest => plugin_root.join("mcp.json"),
|
||||
None => plugin_root.join(".mcp.json"),
|
||||
},
|
||||
let declaration_path = match manifest.get("mcpServers") {
|
||||
Some(serde_json::Value::Object(_)) => manifest_path,
|
||||
Some(serde_json::Value::String(path)) => plugin_root.join(path),
|
||||
Some(_) => return false,
|
||||
None if manifest_path == root_manifest => plugin_root.join("mcp.json"),
|
||||
None => plugin_root.join(".mcp.json"),
|
||||
};
|
||||
|
||||
is_home_owned_path(&declaration_path, codex_home)
|
||||
|
||||
@@ -3,7 +3,6 @@ use std::path::Path;
|
||||
use anyhow::Result;
|
||||
use codex_extension_api::McpToolInfo;
|
||||
use codex_extension_api::McpToolSource;
|
||||
use codex_features::Feature;
|
||||
use codex_guardian_context::TrustedTool;
|
||||
use codex_guardian_context::TrustedToolSource;
|
||||
use codex_login::CodexAuth;
|
||||
@@ -13,15 +12,13 @@ use core_test_support::test_codex::test_codex;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[cfg(unix)]
|
||||
use super::PluginCapability;
|
||||
#[cfg(unix)]
|
||||
use super::is_home_owned_path;
|
||||
#[cfg(unix)]
|
||||
use super::is_home_owned_plugin_capability;
|
||||
use super::is_home_owned_plugin_mcp;
|
||||
use super::trusted_tool_context;
|
||||
|
||||
fn mcp_tool(server: &str, connector_id: Option<&str>) -> Result<McpToolInfo> {
|
||||
fn mcp_tool(server: &str) -> Result<McpToolInfo> {
|
||||
Ok(serde_json::from_value(json!({
|
||||
"server_name": server,
|
||||
"tool_name": "inspect",
|
||||
@@ -32,8 +29,6 @@ fn mcp_tool(server: &str, connector_id: Option<&str>) -> Result<McpToolInfo> {
|
||||
"description": "Remote tool instructions",
|
||||
"inputSchema": {"type": "object", "properties": {}}
|
||||
},
|
||||
"connector_id": connector_id,
|
||||
"connector_name": connector_id.map(|_| "Remote connector"),
|
||||
"plugin_display_names": []
|
||||
}))?)
|
||||
}
|
||||
@@ -41,7 +36,7 @@ fn mcp_tool(server: &str, connector_id: Option<&str>) -> Result<McpToolInfo> {
|
||||
fn expected_context(tool: &McpToolInfo, source: &Path) -> TrustedTool {
|
||||
TrustedTool {
|
||||
server: tool.server_name.clone(),
|
||||
connector_id: tool.connector_id.clone(),
|
||||
connector_id: None,
|
||||
source: TrustedToolSource::UserConfiguration(source.display().to_string()),
|
||||
}
|
||||
}
|
||||
@@ -55,25 +50,18 @@ async fn trusts_only_tools_configured_in_codex_home() -> Result<()> {
|
||||
.with_pre_build_hook(|home| {
|
||||
std::fs::write(
|
||||
home.join("config.toml"),
|
||||
"[mcp_servers.home_server]\nurl = \"http://127.0.0.1:9/mcp\"\n\n[apps.connector_home]\nenabled = true\n",
|
||||
"[mcp_servers.home_server]\nurl = \"http://127.0.0.1:9/mcp\"\n",
|
||||
)
|
||||
.expect("write user MCP and connector config");
|
||||
.expect("write user MCP config");
|
||||
})
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
for (tool, unrelated, source) in [
|
||||
(
|
||||
mcp_tool("home_server", /*connector_id*/ None)?,
|
||||
mcp_tool("other_server", /*connector_id*/ None)?,
|
||||
McpToolSource::Config,
|
||||
),
|
||||
(
|
||||
mcp_tool("codex_apps", Some("connector_home"))?,
|
||||
mcp_tool("codex_apps", Some("connector_other"))?,
|
||||
McpToolSource::Connector,
|
||||
),
|
||||
] {
|
||||
let context = trusted_tool_context(&tool, &source, &test.thread_manager, &test.config)
|
||||
for (tool, unrelated, source) in [(
|
||||
mcp_tool("home_server")?,
|
||||
mcp_tool("other_server")?,
|
||||
McpToolSource::Config,
|
||||
)] {
|
||||
let context = trusted_tool_context(&tool, &source, &test.config)
|
||||
.await
|
||||
.expect("home-configured tool should be trusted");
|
||||
assert_eq!(
|
||||
@@ -81,7 +69,7 @@ async fn trusts_only_tools_configured_in_codex_home() -> Result<()> {
|
||||
expected_context(&tool, &test.home.path().join("config.toml")),
|
||||
);
|
||||
assert_eq!(
|
||||
trusted_tool_context(&unrelated, &source, &test.thread_manager, &test.config).await,
|
||||
trusted_tool_context(&unrelated, &source, &test.config).await,
|
||||
None,
|
||||
);
|
||||
}
|
||||
@@ -90,39 +78,12 @@ async fn trusts_only_tools_configured_in_codex_home() -> Result<()> {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn rejects_blank_orchestrator_connector_ids() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let test = test_codex().build_with_auto_env(&server).await?;
|
||||
let mut config = test.config.clone();
|
||||
config
|
||||
.features
|
||||
.enable(Feature::GuardianTrustOrchestratorConnectors)?;
|
||||
for connector_id in [Some(""), Some(" \t\n "), None] {
|
||||
let tool = mcp_tool("codex_apps", connector_id)?;
|
||||
assert_eq!(
|
||||
trusted_tool_context(
|
||||
&tool,
|
||||
&McpToolSource::Connector,
|
||||
&test.thread_manager,
|
||||
&config,
|
||||
)
|
||||
.await,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn trusts_connector_declared_by_home_owned_plugin() -> Result<()> {
|
||||
async fn trusts_mcp_server_declared_by_home_owned_plugin() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let test = test_codex()
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_auth(CodexAuth::from_api_key("Test API Key"))
|
||||
.with_pre_build_hook(|home| {
|
||||
let plugin_root = home.join("plugins/cache/test/trusted/local");
|
||||
std::fs::create_dir_all(plugin_root.join(".codex-plugin"))
|
||||
@@ -132,11 +93,6 @@ async fn trusts_connector_declared_by_home_owned_plugin() -> Result<()> {
|
||||
r#"{"name":"trusted","description":"Trusted plugin instructions"}"#,
|
||||
)
|
||||
.expect("write plugin manifest");
|
||||
std::fs::write(
|
||||
plugin_root.join(".app.json"),
|
||||
r#"{"apps":{"calendar":{"id":"connector_calendar"}}}"#,
|
||||
)
|
||||
.expect("write plugin connector declaration");
|
||||
std::fs::write(
|
||||
plugin_root.join(".mcp.json"),
|
||||
r#"{"mcpServers":{"trusted_server":{"url":"http://127.0.0.1:9/mcp"}}}"#,
|
||||
@@ -158,18 +114,7 @@ async fn trusts_connector_declared_by_home_owned_plugin() -> Result<()> {
|
||||
.join("test")
|
||||
.join("trusted")
|
||||
.join("local");
|
||||
let tool = mcp_tool("codex_apps", Some("connector_calendar"))?;
|
||||
let context = trusted_tool_context(
|
||||
&tool,
|
||||
&McpToolSource::Connector,
|
||||
&test.thread_manager,
|
||||
&test.config,
|
||||
)
|
||||
.await
|
||||
.expect("home-owned plugin connector should be trusted");
|
||||
assert_eq!(context, expected_context(&tool, &plugin_root));
|
||||
|
||||
let mcp = mcp_tool("trusted_server", /*connector_id*/ None)?;
|
||||
let mcp = mcp_tool("trusted_server")?;
|
||||
let mcp_context = trusted_tool_context(
|
||||
&mcp,
|
||||
&McpToolSource::Plugin {
|
||||
@@ -180,7 +125,6 @@ async fn trusts_connector_declared_by_home_owned_plugin() -> Result<()> {
|
||||
.join("plugins/cache/test/trusted/local")
|
||||
.into(),
|
||||
},
|
||||
&test.thread_manager,
|
||||
&test.config,
|
||||
)
|
||||
.await
|
||||
@@ -194,20 +138,13 @@ async fn trusts_connector_declared_by_home_owned_plugin() -> Result<()> {
|
||||
id: "trusted@test".to_string(),
|
||||
root: test.config.cwd.clone().into(),
|
||||
},
|
||||
&test.thread_manager,
|
||||
&test.config,
|
||||
)
|
||||
.await,
|
||||
None,
|
||||
);
|
||||
assert_eq!(
|
||||
trusted_tool_context(
|
||||
&mcp,
|
||||
&McpToolSource::SelectedPlugin,
|
||||
&test.thread_manager,
|
||||
&test.config,
|
||||
)
|
||||
.await,
|
||||
trusted_tool_context(&mcp, &McpToolSource::SelectedPlugin, &test.config,).await,
|
||||
None,
|
||||
);
|
||||
|
||||
@@ -233,23 +170,11 @@ async fn rejects_paths_that_escape_codex_home_through_symlinks() -> Result<()> {
|
||||
plugin_root.join(".codex-plugin").join("plugin.json"),
|
||||
r#"{"name":"trusted"}"#,
|
||||
)?;
|
||||
let outside_apps = test.cwd.path().join("outside-app.json");
|
||||
let outside_mcp = test.cwd.path().join("outside-mcp.json");
|
||||
std::fs::write(&outside_apps, r#"{"apps":{}}"#)?;
|
||||
std::fs::write(&outside_mcp, r#"{"mcpServers":{}}"#)?;
|
||||
std::os::unix::fs::symlink(&outside_apps, plugin_root.join(".app.json"))?;
|
||||
std::os::unix::fs::symlink(&outside_mcp, plugin_root.join(".mcp.json"))?;
|
||||
|
||||
assert!(!is_home_owned_plugin_capability(
|
||||
&plugin_root,
|
||||
&canonical_home,
|
||||
PluginCapability::Connector,
|
||||
));
|
||||
assert!(!is_home_owned_plugin_capability(
|
||||
&plugin_root,
|
||||
&canonical_home,
|
||||
PluginCapability::Mcp,
|
||||
));
|
||||
assert!(!is_home_owned_plugin_mcp(&plugin_root, &canonical_home));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
//! Exposes a narrow history capability backed by the parent's live MCP runtime.
|
||||
//! Guardian owns tool exposure and output limits, never a second Apps connection.
|
||||
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use codex_core::CodexThread;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ToolCall;
|
||||
use codex_extension_api::ToolContributor;
|
||||
use codex_extension_api::ToolExecutor;
|
||||
use codex_extension_api::TurnLifecycleContributor;
|
||||
use codex_extension_api::TurnStartInput;
|
||||
use codex_extension_api::TurnStartPhase;
|
||||
|
||||
pub(super) struct ConversationHistoryTools {
|
||||
pub parent: Weak<CodexThread>,
|
||||
}
|
||||
|
||||
struct HistoryTools(Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>>);
|
||||
|
||||
impl TurnLifecycleContributor for ConversationHistoryTools {
|
||||
fn turn_start_phase(&self, _thread_store: &ExtensionData) -> TurnStartPhase {
|
||||
TurnStartPhase::RegularTaskStart
|
||||
}
|
||||
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let tools = match self.parent.upgrade() {
|
||||
Some(parent) => {
|
||||
let max_output_tokens = parent
|
||||
.config()
|
||||
.await
|
||||
.guardian_conversation_history_max_output_tokens
|
||||
.map_or(/*default*/ 4_000, NonZeroUsize::get);
|
||||
codex_core::guardian_review::conversation_history_tools(
|
||||
&parent,
|
||||
max_output_tokens,
|
||||
)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
input.thread_store.insert(HistoryTools(tools));
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolContributor for ConversationHistoryTools {
|
||||
fn tools(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
thread_store
|
||||
.get::<HistoryTools>()
|
||||
.map(|tools| tools.0.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
use super::*;
|
||||
use codex_core::TurnInputRequest;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::Op;
|
||||
use codex_protocol::protocol::TurnAbortReason;
|
||||
@@ -19,14 +18,14 @@ use core_test_support::wait_for_event_match;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::time::Duration;
|
||||
|
||||
struct StaleDenials(ModelInfo);
|
||||
struct StaleDenials;
|
||||
|
||||
impl TurnLifecycleContributor for StaleDenials {
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let denials = ReviewDenials::for_thread(input.thread_store);
|
||||
for _ in 0..2 {
|
||||
assert_eq!(denials.record_denial(input.turn_id, &self.0).await, None);
|
||||
assert_eq!(denials.record_denial(input.turn_id).await, None);
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -34,12 +33,9 @@ impl TurnLifecycleContributor for StaleDenials {
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn terminal_turn_clears_extension_owned_denials() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let config = core_test_support::load_default_config_for_test(&home).await;
|
||||
let model = codex_core::test_support::construct_model_info_offline("gpt-5", &config);
|
||||
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
|
||||
// Seed stale state before the production Guardian contributor runs its start hook.
|
||||
extensions.turn_lifecycle_contributor(Arc::new(StaleDenials(model.clone())));
|
||||
extensions.turn_lifecycle_contributor(Arc::new(StaleDenials));
|
||||
let mut releases = Vec::new();
|
||||
let streams = (0..3)
|
||||
.map(|_| {
|
||||
@@ -86,7 +82,7 @@ async fn terminal_turn_clears_extension_owned_denials() -> anyhow::Result<()> {
|
||||
.await;
|
||||
// An interruption event can precede its cleanup. The next turn starts after it.
|
||||
if let Some(previous) = previous_turn.replace(turn_id.clone()) {
|
||||
assert_eq!(denials.record_denial(&previous, &model).await, None);
|
||||
assert_eq!(denials.record_denial(&previous).await, None);
|
||||
}
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
@@ -95,7 +91,7 @@ async fn terminal_turn_clears_extension_owned_denials() -> anyhow::Result<()> {
|
||||
.await?;
|
||||
// Without start cleanup, these denials reach the three-denial limit.
|
||||
for _ in 0..2 {
|
||||
assert_eq!(denials.record_denial(&turn_id, &model).await, None);
|
||||
assert_eq!(denials.record_denial(&turn_id).await, None);
|
||||
}
|
||||
if index == 1 {
|
||||
test.codex.submit(Op::Interrupt).await?;
|
||||
@@ -116,10 +112,7 @@ async fn terminal_turn_clears_extension_owned_denials() -> anyhow::Result<()> {
|
||||
}
|
||||
}
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
assert_eq!(
|
||||
denials.record_denial(&previous_turn.unwrap(), &model).await,
|
||||
None
|
||||
);
|
||||
assert_eq!(denials.record_denial(&previous_turn.unwrap()).await, None);
|
||||
streaming.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use codex_core::CodexResponsesHeaders;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::config::Constrained;
|
||||
@@ -34,7 +33,6 @@ use codex_protocol::protocol::InternalSessionSource;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadSource;
|
||||
|
||||
mod conversation_history;
|
||||
mod reviewer_config;
|
||||
|
||||
/// Owns reviewer agents through the same thread manager as the parent conversation.
|
||||
@@ -58,7 +56,6 @@ impl ThreadLifecycleContributor<Config> for GuardianExtension {
|
||||
reviewer_config::build_reviewer_config,
|
||||
));
|
||||
let manager = self.thread_manager.clone();
|
||||
let parent_thread_id = input.thread_store.level_id().to_owned();
|
||||
let runtime = input.thread_store.get_or_init(ReviewerTasks::default);
|
||||
input.thread_store.get_or_init(ReviewBlocking::default);
|
||||
input.thread_store.get_or_init(|| {
|
||||
@@ -66,7 +63,6 @@ impl ThreadLifecycleContributor<Config> for GuardianExtension {
|
||||
Arc::clone(&runtime),
|
||||
move |context, key, kind, snapshot, cancel| {
|
||||
let manager = manager.clone();
|
||||
let parent_thread_id = parent_thread_id.clone();
|
||||
let runtime = Arc::clone(&runtime);
|
||||
Box::pin(async move {
|
||||
let history_reset = context.history_reset.clone();
|
||||
@@ -92,52 +88,10 @@ impl ThreadLifecycleContributor<Config> for GuardianExtension {
|
||||
options.session_source =
|
||||
Some(SessionSource::Internal(InternalSessionSource::Guardian));
|
||||
options.thread_source = Some(ThreadSource::GuardianReview);
|
||||
// This is the backend reviewer model, independent of current login.
|
||||
// Core checks the selected model and auth on each request attempt.
|
||||
let provider = codex_model_provider::create_model_provider(
|
||||
options.config.model_provider.clone(),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
options.thread_extension_init.insert(CodexResponsesHeaders {
|
||||
model: provider.approval_review_preferred_model().to_owned(),
|
||||
headers: http::HeaderMap::from_iter([(
|
||||
http::HeaderName::from_static("x-codex-guardian"),
|
||||
http::HeaderValue::from_static("reviewer"),
|
||||
)]),
|
||||
});
|
||||
options
|
||||
.thread_extension_init
|
||||
.insert(SessionIsolation::Isolated);
|
||||
let mut tool_policy = codex_guardian_reviewer::reviewer_tool_policy();
|
||||
if options
|
||||
.config
|
||||
.features
|
||||
.enabled(codex_features::Feature::GuardianConversationHistoryTools)
|
||||
{
|
||||
let parent = manager
|
||||
.get_thread(ThreadId::from_string(&parent_thread_id)?)
|
||||
.await?;
|
||||
let mut extensions = ExtensionRegistryBuilder::<Config>::default();
|
||||
let history_tools =
|
||||
Arc::new(conversation_history::ConversationHistoryTools {
|
||||
parent: Arc::downgrade(&parent),
|
||||
});
|
||||
extensions.tool_contributor(history_tools.clone());
|
||||
extensions.turn_lifecycle_contributor(history_tools);
|
||||
options.thread_extension_init.insert(
|
||||
codex_extension_api::IsolatedSessionExtensions(Arc::new(
|
||||
extensions.build(),
|
||||
)),
|
||||
);
|
||||
tool_policy.allowed_tools.get_or_insert_default().extend(
|
||||
["search_messages", "read_messages"].map(|name| {
|
||||
codex_extension_api::ToolName::namespaced(
|
||||
"user_message",
|
||||
name,
|
||||
)
|
||||
}),
|
||||
);
|
||||
}
|
||||
let tool_policy = codex_guardian_reviewer::reviewer_tool_policy();
|
||||
options.thread_extension_init.insert(tool_policy);
|
||||
let session_cancel = cancel.clone();
|
||||
let until = async move {
|
||||
|
||||
@@ -36,9 +36,6 @@ pub(crate) fn build_reviewer_config(parent_config: &Config) -> anyhow::Result<Co
|
||||
config.mcp_servers.set(HashMap::new()).map_err(|err| {
|
||||
anyhow::anyhow!("guardian review session could not clear MCP servers: {err}")
|
||||
})?;
|
||||
let conversation_history_tools = config
|
||||
.features
|
||||
.enabled(Feature::GuardianConversationHistoryTools);
|
||||
for feature in [
|
||||
Feature::Collab,
|
||||
Feature::MultiAgentV2,
|
||||
@@ -51,9 +48,6 @@ pub(crate) fn build_reviewer_config(parent_config: &Config) -> anyhow::Result<Co
|
||||
Feature::WebSearchRequest,
|
||||
Feature::WebSearchCached,
|
||||
] {
|
||||
if feature == Feature::Apps && conversation_history_tools {
|
||||
continue;
|
||||
}
|
||||
config.features.disable(feature).map_err(|err| {
|
||||
anyhow::anyhow!(
|
||||
"guardian review session could not disable `features.{}`: {err}",
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "history-notes",
|
||||
crate_name = "codex_history_notes_extension",
|
||||
)
|
||||
@@ -1,36 +0,0 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "codex-history-notes-extension"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "codex_history_notes_extension"
|
||||
path = "src/lib.rs"
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
codex-client = { workspace = true }
|
||||
codex-core = { workspace = true }
|
||||
codex-extension-api = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-model-provider = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-tools = { workspace = true }
|
||||
codex-utils-output-truncation = { workspace = true }
|
||||
http = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
codex-config = { workspace = true }
|
||||
codex-model-provider-info = { workspace = true }
|
||||
core_test_support = { workspace = true }
|
||||
insta = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt"] }
|
||||
wiremock = { workspace = true }
|
||||
@@ -1,114 +0,0 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_client::HttpTransport;
|
||||
use codex_client::RequestBody;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::default_client::create_transport_for_routes_async;
|
||||
use codex_model_provider::SharedModelProvider;
|
||||
use codex_utils_output_truncation::TruncationPolicy;
|
||||
use http::HeaderValue;
|
||||
use http::Method;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
const HISTORY_NOTES_BACKEND_TIMEOUT: Duration = Duration::from_secs(35);
|
||||
const ENCRYPTED_TOOL_ARGUMENTS_HEADER: &str = "x-openai-encrypted-tool-arguments";
|
||||
const TOOL_OUTPUT_TRUNCATION_POLICY_HEADER: &str = "x-openai-tool-output-truncation-policy";
|
||||
const OPERATION_ERROR_PREFIX: &str = "Unable to perform operation:";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct HistoryNotesBackend {
|
||||
provider: SharedModelProvider,
|
||||
http_client_factory: HttpClientFactory,
|
||||
}
|
||||
|
||||
impl HistoryNotesBackend {
|
||||
pub(crate) fn new(
|
||||
provider: SharedModelProvider,
|
||||
http_client_factory: HttpClientFactory,
|
||||
) -> Self {
|
||||
Self {
|
||||
provider,
|
||||
http_client_factory,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn call(
|
||||
&self,
|
||||
path: &str,
|
||||
session_id: &str,
|
||||
current_agent_name: &str,
|
||||
mut arguments: Value,
|
||||
truncation_policy: TruncationPolicy,
|
||||
) -> Result<Value, String> {
|
||||
let Some(arguments_object) = arguments.as_object_mut() else {
|
||||
return Err("History tool arguments must be a JSON object".to_string());
|
||||
};
|
||||
arguments_object.insert(
|
||||
"context".to_string(),
|
||||
json!({
|
||||
"session_id": session_id,
|
||||
"current_agent_name": current_agent_name,
|
||||
}),
|
||||
);
|
||||
|
||||
let setup = codex_model_provider::resolve_request(
|
||||
self.provider.as_ref(),
|
||||
/*scope*/ None,
|
||||
/*routing*/ None,
|
||||
self.http_client_factory.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| format!("{OPERATION_ERROR_PREFIX} Could not prepare the backend request."))?;
|
||||
|
||||
let mut request = setup.api_provider.build_request(Method::POST, path);
|
||||
let encoded_truncation_policy =
|
||||
serde_json::to_string(&truncation_policy).map_err(|_| {
|
||||
format!("{OPERATION_ERROR_PREFIX} Could not encode the output truncation policy.")
|
||||
})?;
|
||||
request.headers.insert(
|
||||
TOOL_OUTPUT_TRUNCATION_POLICY_HEADER,
|
||||
HeaderValue::from_str(&encoded_truncation_policy).map_err(|_| {
|
||||
format!(
|
||||
"{OPERATION_ERROR_PREFIX} Could not construct the output truncation policy header."
|
||||
)
|
||||
})?,
|
||||
);
|
||||
if matches!(
|
||||
path,
|
||||
"alpha/history/v2/search_contents"
|
||||
| "alpha/notes/v2/search_contents"
|
||||
| "alpha/notes/v2/append_to_file"
|
||||
| "alpha/notes/v2/write_file"
|
||||
) {
|
||||
request.headers.insert(
|
||||
ENCRYPTED_TOOL_ARGUMENTS_HEADER,
|
||||
HeaderValue::from_static("true"),
|
||||
);
|
||||
}
|
||||
request.body = Some(RequestBody::Json(arguments));
|
||||
request.timeout = Some(HISTORY_NOTES_BACKEND_TIMEOUT);
|
||||
let request = setup.api_auth.apply_auth(request).await.map_err(|_| {
|
||||
format!("{OPERATION_ERROR_PREFIX} Could not apply backend authentication.")
|
||||
})?;
|
||||
let transport = create_transport_for_routes_async(
|
||||
setup.http_client_factory,
|
||||
ClientRouteClass::Api,
|
||||
setup.redirect_policy,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| format!("{OPERATION_ERROR_PREFIX} The backend request failed."))?;
|
||||
let response = transport
|
||||
.execute(request)
|
||||
.await
|
||||
.map_err(|_| format!("{OPERATION_ERROR_PREFIX} The backend request failed."))?;
|
||||
|
||||
serde_json::from_slice(&response.body)
|
||||
.map_err(|_| format!("{OPERATION_ERROR_PREFIX} The backend returned invalid JSON."))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "backend_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,147 +0,0 @@
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_utils_output_truncation::TruncationPolicy;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
use super::ENCRYPTED_TOOL_ARGUMENTS_HEADER;
|
||||
use super::HistoryNotesBackend;
|
||||
|
||||
#[tokio::test]
|
||||
async fn routes_through_codex_backend_and_injects_trusted_session_agent_context() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/backend-api/codex/alpha/notes/v2/read_file"))
|
||||
.and(header("x-openai-actor-authorization", "actor-biscuit"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"encrypted_output": "enc_payload"
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"x-openai-actor-authorization",
|
||||
HeaderValue::from_static("actor-biscuit"),
|
||||
);
|
||||
let auth_manager =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::Headers(AuthHeaders::new(headers)));
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(format!(
|
||||
"{}/backend-api/codex",
|
||||
server.uri()
|
||||
))),
|
||||
Some(auth_manager),
|
||||
);
|
||||
let backend = HistoryNotesBackend::new(
|
||||
provider,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
);
|
||||
|
||||
let response = backend
|
||||
.call(
|
||||
"alpha/notes/v2/read_file",
|
||||
"session-123",
|
||||
"/root/worker",
|
||||
json!({
|
||||
"path": "notes.md",
|
||||
"context": {
|
||||
"session_id": "spoofed-session",
|
||||
"current_agent_name": "/root/spoofed",
|
||||
}
|
||||
}),
|
||||
TruncationPolicy::Bytes(1024),
|
||||
)
|
||||
.await
|
||||
.expect("History request should succeed");
|
||||
|
||||
assert_eq!(response, json!({"encrypted_output": "enc_payload"}));
|
||||
let requests = server.received_requests().await.expect("recorded requests");
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert!(
|
||||
requests[0]
|
||||
.headers
|
||||
.get(ENCRYPTED_TOOL_ARGUMENTS_HEADER)
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(&requests[0].body).expect("JSON body"),
|
||||
json!({
|
||||
"path": "notes.md",
|
||||
"context": {
|
||||
"session_id": "session-123",
|
||||
"current_agent_name": "/root/worker",
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marks_encrypted_history_and_notes_arguments_without_changing_the_json_body() {
|
||||
let server = MockServer::start().await;
|
||||
let cases = [
|
||||
(
|
||||
"history/v2/search_contents",
|
||||
json!({"query": "encrypted-query"}),
|
||||
),
|
||||
(
|
||||
"notes/v2/search_contents",
|
||||
json!({"query": "encrypted-query"}),
|
||||
),
|
||||
(
|
||||
"notes/v2/append_to_file",
|
||||
json!({"path": "notes.md", "text": "encrypted-text"}),
|
||||
),
|
||||
(
|
||||
"notes/v2/write_file",
|
||||
json!({"path": "notes.md", "text": "encrypted-text"}),
|
||||
),
|
||||
];
|
||||
for (route, _) in &cases {
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!("/backend-api/codex/alpha/{route}")))
|
||||
.and(header(ENCRYPTED_TOOL_ARGUMENTS_HEADER, "true"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
|
||||
let auth_manager =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::Headers(AuthHeaders::new(HeaderMap::new())));
|
||||
let backend = HistoryNotesBackend::new(
|
||||
create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(format!(
|
||||
"{}/backend-api/codex",
|
||||
server.uri()
|
||||
))),
|
||||
Some(auth_manager),
|
||||
),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
);
|
||||
|
||||
for (route, arguments) in cases {
|
||||
backend
|
||||
.call(
|
||||
&format!("alpha/{route}"),
|
||||
"session-123",
|
||||
"/root",
|
||||
arguments.clone(),
|
||||
TruncationPolicy::Bytes(1024),
|
||||
)
|
||||
.await
|
||||
.expect("encrypted argument request should succeed");
|
||||
}
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_core::config::Config;
|
||||
use codex_extension_api::ConfigContributor;
|
||||
use codex_extension_api::ContentItemKind;
|
||||
use codex_extension_api::ContextContributor;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::PromptFragment;
|
||||
use codex_extension_api::PromptSlot;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_extension_api::ToolCall;
|
||||
use codex_extension_api::ToolContributor;
|
||||
use codex_extension_api::ToolExecutor;
|
||||
use codex_login::AuthManager;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::openai_models::HistoryToolMessages;
|
||||
use codex_protocol::openai_models::NotesToolMessages;
|
||||
use codex_utils_output_truncation::TruncationPolicy;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::backend::HistoryNotesBackend;
|
||||
use crate::tools::HistoryNotesAction;
|
||||
use crate::tools::HistoryNotesTool;
|
||||
|
||||
// Bound model context even when note paths are unusually long.
|
||||
const MAX_THREAD_HINT_BYTES: usize = 4_000;
|
||||
|
||||
struct HistoryNotesExtension {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
}
|
||||
|
||||
struct HistoryNotesExtensionConfig {
|
||||
backend: HistoryNotesBackend,
|
||||
}
|
||||
|
||||
struct HistoryNotesAgentIdentity {
|
||||
agent_name: String,
|
||||
}
|
||||
|
||||
impl HistoryNotesExtension {
|
||||
fn update_config(&self, thread_store: &ExtensionData, config: &Config) {
|
||||
let auth = thread_store
|
||||
.get::<codex_model_provider::ProviderAuthContext>()
|
||||
.unwrap_or_else(|| {
|
||||
Arc::new(codex_model_provider::ProviderAuthContext {
|
||||
credentials: Arc::clone(&self.auth_manager),
|
||||
runtime_auth: None,
|
||||
})
|
||||
});
|
||||
if config
|
||||
.token_budget
|
||||
.as_ref()
|
||||
.is_some_and(|token_budget| token_budget.use_history_notes_extension)
|
||||
&& config.model_provider.is_openai()
|
||||
&& auth.credentials.current_auth_uses_codex_backend()
|
||||
{
|
||||
thread_store.insert(HistoryNotesExtensionConfig {
|
||||
backend: HistoryNotesBackend::new(
|
||||
auth.model_provider(config.model_provider.clone()),
|
||||
config.http_client_factory(),
|
||||
),
|
||||
});
|
||||
} else {
|
||||
thread_store.remove::<HistoryNotesExtensionConfig>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadLifecycleContributor<Config> for HistoryNotesExtension {
|
||||
fn on_thread_start<'a>(
|
||||
&'a self,
|
||||
input: ThreadStartInput<'a, Config>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let agent_name = input
|
||||
.session_source
|
||||
.get_agent_path()
|
||||
.unwrap_or_else(AgentPath::root)
|
||||
.to_string();
|
||||
input
|
||||
.thread_store
|
||||
.insert(HistoryNotesAgentIdentity { agent_name });
|
||||
self.update_config(input.thread_store, input.config);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigContributor<Config> for HistoryNotesExtension {
|
||||
fn on_config_changed(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
_previous_config: &Config,
|
||||
new_config: &Config,
|
||||
) {
|
||||
self.update_config(thread_store, new_config);
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextContributor for HistoryNotesExtension {
|
||||
fn contribute_thread_context<'a>(
|
||||
&'a self,
|
||||
session_store: &'a ExtensionData,
|
||||
thread_store: &'a ExtensionData,
|
||||
) -> ExtensionFuture<'a, Vec<PromptFragment>> {
|
||||
Box::pin(async move {
|
||||
let Some(config) = thread_store.get::<HistoryNotesExtensionConfig>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(identity) = thread_store.get::<HistoryNotesAgentIdentity>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(result) = config
|
||||
.backend
|
||||
.call(
|
||||
"alpha/notes/v2/thread_hint",
|
||||
session_store.level_id(),
|
||||
&identity.agent_name,
|
||||
json!({}),
|
||||
TruncationPolicy::Bytes(MAX_THREAD_HINT_BYTES),
|
||||
)
|
||||
.await
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(text) = result.get("text").and_then(serde_json::Value::as_str) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if text.len() > MAX_THREAD_HINT_BYTES {
|
||||
return Vec::new();
|
||||
}
|
||||
if text.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![PromptFragment::tool(
|
||||
PromptSlot::ContextWindow,
|
||||
text,
|
||||
ContentItemKind("notes.thread_hint".to_string()),
|
||||
"notes".to_string(),
|
||||
)]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolContributor for HistoryNotesExtension {
|
||||
fn tools(
|
||||
&self,
|
||||
session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
self.tools_with_messages(
|
||||
session_store,
|
||||
thread_store,
|
||||
/*history_messages*/ None,
|
||||
/*notes_messages*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
fn tools_for_step(
|
||||
&self,
|
||||
session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
step_store: &ExtensionData,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
let history_messages = step_store.get::<HistoryToolMessages>();
|
||||
let notes_messages = step_store.get::<NotesToolMessages>();
|
||||
self.tools_with_messages(
|
||||
session_store,
|
||||
thread_store,
|
||||
history_messages.as_deref(),
|
||||
notes_messages.as_deref(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryNotesExtension {
|
||||
fn tools_with_messages(
|
||||
&self,
|
||||
session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
history_messages: Option<&HistoryToolMessages>,
|
||||
notes_messages: Option<&NotesToolMessages>,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
let Some(config) = thread_store.get::<HistoryNotesExtensionConfig>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(identity) = thread_store.get::<HistoryNotesAgentIdentity>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
HistoryNotesAction::ALL
|
||||
.into_iter()
|
||||
.map(|action| {
|
||||
Arc::new(HistoryNotesTool::new(
|
||||
action,
|
||||
config.backend.clone(),
|
||||
session_store.level_id().to_string(),
|
||||
identity.agent_name.clone(),
|
||||
history_messages,
|
||||
notes_messages,
|
||||
)) as Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the standalone history and notes tools backed by the Codex backend.
|
||||
pub fn install(registry: &mut ExtensionRegistryBuilder<Config>, auth_manager: Arc<AuthManager>) {
|
||||
let extension = Arc::new(HistoryNotesExtension { auth_manager });
|
||||
registry.thread_lifecycle_contributor(extension.clone());
|
||||
registry.config_contributor(extension.clone());
|
||||
registry.prompt_contributor(extension.clone());
|
||||
registry.tool_contributor(extension);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
mod backend;
|
||||
mod extension;
|
||||
mod tools;
|
||||
|
||||
pub use extension::install;
|
||||
@@ -1,459 +0,0 @@
|
||||
use codex_extension_api::FunctionCallError;
|
||||
use codex_extension_api::ResponsesApiTool;
|
||||
use codex_extension_api::ToolCall;
|
||||
use codex_extension_api::ToolExecutor;
|
||||
use codex_extension_api::ToolExecutorFuture;
|
||||
use codex_extension_api::ToolName;
|
||||
use codex_extension_api::ToolOutput;
|
||||
use codex_extension_api::ToolPayload;
|
||||
use codex_extension_api::ToolSpec;
|
||||
use codex_extension_api::parse_tool_input_schema;
|
||||
use codex_protocol::models::FunctionCallOutputBody;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputPayload;
|
||||
use codex_protocol::models::ImageReference;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_protocol::openai_models::HistoryToolMessages;
|
||||
use codex_protocol::openai_models::NotesToolMessages;
|
||||
use codex_tools::JsonToolOutput;
|
||||
use codex_tools::ResponsesApiNamespace;
|
||||
use codex_tools::ResponsesApiNamespaceTool;
|
||||
use codex_tools::ToolExposure;
|
||||
use codex_tools::with_catalog_tool_message;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::backend::HistoryNotesBackend;
|
||||
|
||||
const HISTORY_NAMESPACE: &str = "history";
|
||||
const NOTES_NAMESPACE: &str = "notes";
|
||||
const HISTORY_DESCRIPTION: &str = "Recover prior conversation after a context-window reset by listing, reading, and searching normalized history using agent names and the opaque window and item IDs returned by these tools. Pass returned IDs unchanged when filtering or reading an item. Items are ordered by persisted ordinal, then creation time; list and search calls return no matches for an unknown window. Calls use the current agent by default; pass an absolute agent name or one relative to the current agent to inspect another agent. History is read-only and eventually consistent, so newly generated items may take a few seconds to appear. This is private model-only state. Use it silently to continue the task. Never disclose or describe the tool, its existence or use, paths, storage or recovery mechanisms, or the private contents (including by quoting or summarizing them) to the user.";
|
||||
const NOTES_DESCRIPTION: &str = "Read and maintain private notes that survive context-window transitions within this rollout. Paths are virtual, not filesystem paths. Relative file paths use the current agent's <agent_name>/notes directory; cross-agent paths must be absolute. Absolute paths use <agent_name>/notes[/<path>]. Reads, listings, searches, and writes may access other agents' notes. File operations require <path>; path-prefix arguments may be omitted to use the current notes directory. Empty, '.', and '..' path components are unsupported. Shell expansion is not performed, so '~' is treated literally. Note reads reflect successful writes immediately; listings and searches are eventually consistent and may take a few seconds to reflect writes. Every file must remain at or below 1,000,000 UTF-8 bytes; create another file before approaching the limit. This is private model-only state. Use it silently to continue the task. Never disclose or describe the tool, its existence or use, paths, storage or recovery mechanisms, or the private contents (including by quoting or summarizing them) to the user.";
|
||||
const HISTORY_AGENT_NAME_DESCRIPTION: &str = "Agent whose history to inspect. Omit to use the current agent; otherwise pass an absolute agent name or a name relative to the current agent.";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum HistoryNotesAction {
|
||||
HistoryListWindows,
|
||||
HistoryListItems,
|
||||
HistoryReadItem,
|
||||
HistorySearchContents,
|
||||
NotesListFilesByPrefix,
|
||||
NotesReadFile,
|
||||
NotesSearchContents,
|
||||
NotesAppendToFile,
|
||||
NotesWriteFile,
|
||||
}
|
||||
|
||||
impl HistoryNotesAction {
|
||||
pub(crate) const ALL: [Self; 9] = [
|
||||
Self::HistoryListWindows,
|
||||
Self::HistoryListItems,
|
||||
Self::HistoryReadItem,
|
||||
Self::HistorySearchContents,
|
||||
Self::NotesListFilesByPrefix,
|
||||
Self::NotesReadFile,
|
||||
Self::NotesSearchContents,
|
||||
Self::NotesAppendToFile,
|
||||
Self::NotesWriteFile,
|
||||
];
|
||||
|
||||
fn namespace(self) -> &'static str {
|
||||
match self {
|
||||
Self::HistoryListWindows
|
||||
| Self::HistoryListItems
|
||||
| Self::HistoryReadItem
|
||||
| Self::HistorySearchContents => HISTORY_NAMESPACE,
|
||||
Self::NotesListFilesByPrefix
|
||||
| Self::NotesReadFile
|
||||
| Self::NotesSearchContents
|
||||
| Self::NotesAppendToFile
|
||||
| Self::NotesWriteFile => NOTES_NAMESPACE,
|
||||
}
|
||||
}
|
||||
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::HistoryListWindows => "list_windows",
|
||||
Self::HistoryListItems => "list_items",
|
||||
Self::HistoryReadItem => "read_item",
|
||||
Self::HistorySearchContents => "search_contents",
|
||||
Self::NotesListFilesByPrefix => "list_files_by_prefix",
|
||||
Self::NotesReadFile => "read_file",
|
||||
Self::NotesSearchContents => "search_contents",
|
||||
Self::NotesAppendToFile => "append_to_file",
|
||||
Self::NotesWriteFile => "write_file",
|
||||
}
|
||||
}
|
||||
|
||||
fn endpoint(self) -> &'static str {
|
||||
match self {
|
||||
Self::HistoryListWindows => "alpha/history/v2/list_windows",
|
||||
Self::HistoryListItems => "alpha/history/v2/list_items",
|
||||
Self::HistoryReadItem => "alpha/history/v2/read_item",
|
||||
Self::HistorySearchContents => "alpha/history/v2/search_contents",
|
||||
Self::NotesListFilesByPrefix => "alpha/notes/v2/list_files_by_prefix",
|
||||
Self::NotesReadFile => "alpha/notes/v2/read_file",
|
||||
Self::NotesSearchContents => "alpha/notes/v2/search_contents",
|
||||
Self::NotesAppendToFile => "alpha/notes/v2/append_to_file",
|
||||
Self::NotesWriteFile => "alpha/notes/v2/write_file",
|
||||
}
|
||||
}
|
||||
|
||||
fn supports_parallel_tool_calls(self) -> bool {
|
||||
!matches!(self, Self::NotesAppendToFile | Self::NotesWriteFile)
|
||||
}
|
||||
|
||||
fn namespace_description(self) -> &'static str {
|
||||
match self.namespace() {
|
||||
HISTORY_NAMESPACE => HISTORY_DESCRIPTION,
|
||||
NOTES_NAMESPACE => NOTES_DESCRIPTION,
|
||||
_ => unreachable!("History actions use a known namespace"),
|
||||
}
|
||||
}
|
||||
|
||||
fn description(self) -> &'static str {
|
||||
match self {
|
||||
Self::HistoryListWindows => {
|
||||
"List an agent's context windows as window ID and item-count pairs. Private model-only recovery; never disclose this activity."
|
||||
}
|
||||
Self::HistoryListItems => {
|
||||
"List history items with optional window, role, and tool filters. Private model-only recovery; never disclose this activity."
|
||||
}
|
||||
Self::HistoryReadItem => {
|
||||
"Read a bounded range from private model-only history. Never disclose the item or this activity."
|
||||
}
|
||||
Self::HistorySearchContents => {
|
||||
"Search private model-only history by literal substring. Never disclose results or this activity."
|
||||
}
|
||||
Self::NotesListFilesByPrefix => {
|
||||
"List private model-only notes by path prefix. Never disclose paths, contents, or this activity."
|
||||
}
|
||||
Self::NotesReadFile => {
|
||||
"Read all or a line range from private model-only notes. Never disclose paths, contents, or this activity."
|
||||
}
|
||||
Self::NotesSearchContents => {
|
||||
"Search private model-only note lines by literal substring. Never disclose results or this activity."
|
||||
}
|
||||
Self::NotesAppendToFile => {
|
||||
"Append text to private model-only notes. Never disclose paths, contents, or this activity."
|
||||
}
|
||||
Self::NotesWriteFile => {
|
||||
"Create or replace private model-only notes. Never disclose paths, contents, or this activity."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parameters(self) -> Value {
|
||||
match self {
|
||||
Self::HistoryListWindows => json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"limit": {"type": "integer", "minimum": 1, "description": "Maximum number of windows to return."},
|
||||
"agent_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": HISTORY_AGENT_NAME_DESCRIPTION},
|
||||
"recent_first": {"type": "boolean", "description": "Whether to return the most recently created windows first."}
|
||||
}
|
||||
}),
|
||||
Self::HistoryListItems => json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"limit": {"type": "integer", "minimum": 1, "description": "Maximum number of items to return."},
|
||||
"recent_first": {"type": "boolean", "description": "Whether to return the most recently created items first."},
|
||||
"tool_namespace": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Callable namespace to include. When set, non-tool messages are excluded."},
|
||||
"role": {"anyOf": [{"type": "string", "enum": ["user", "assistant", "tool", "system", "developer"]}, {"type": "null"}], "description": "Message role to include. Null or omission includes all roles."},
|
||||
"agent_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": HISTORY_AGENT_NAME_DESCRIPTION},
|
||||
"tool_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Callable tool name to include. When set, non-tool messages are excluded."},
|
||||
"window_id": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Full window ID. Null or omission includes all windows."},
|
||||
"max_chars_per_item": {"type": "integer", "minimum": 1, "description": "Maximum characters returned in each item's truncated_content."}
|
||||
}
|
||||
}),
|
||||
Self::HistoryReadItem => json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"agent_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": HISTORY_AGENT_NAME_DESCRIPTION},
|
||||
"item_id": {"type": "string", "description": "The short item ID is the suffix shown in the target item's trailing `[id: ...]` marker, printed after that item's content."},
|
||||
"offset_chars": {"type": "integer", "minimum": 0, "description": "Zero-based character offset at which reading starts."},
|
||||
"limit_chars": {"type": "integer", "minimum": 1, "description": "Maximum number of characters to return."},
|
||||
"window_id": {"type": "string", "description": "Full window ID containing the item."}
|
||||
},
|
||||
"required": ["item_id", "window_id"]
|
||||
}),
|
||||
Self::HistorySearchContents => json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"limit": {"type": "integer", "minimum": 1, "description": "Maximum number of matching items to return."},
|
||||
"query": {"type": "string", "encrypted": true, "description": "Case-sensitive literal substring to find in item content."},
|
||||
"recent_first": {"type": "boolean", "description": "Whether to return the most recently created matches first."},
|
||||
"tool_namespace": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Callable namespace to include. When set, non-tool messages are excluded."},
|
||||
"role": {"anyOf": [{"type": "string", "enum": ["user", "assistant", "tool", "system", "developer"]}, {"type": "null"}], "description": "Message role to include. Null or omission includes all roles."},
|
||||
"agent_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": HISTORY_AGENT_NAME_DESCRIPTION},
|
||||
"tool_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Callable tool name to include. When set, non-tool messages are excluded."},
|
||||
"window_id": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Full window ID. Null or omission includes all windows."}
|
||||
},
|
||||
"required": ["query"]
|
||||
}),
|
||||
Self::NotesListFilesByPrefix => json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"prefix": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Note path prefix to list."},
|
||||
"max_results": {"type": "integer", "minimum": 1, "description": "Maximum number of files to return."},
|
||||
"file_order_by": {"type": "string", "enum": ["name", "created_at", "updated_at"], "description": "Field used to order files."},
|
||||
"file_order": {"type": "string", "enum": ["ascending", "descending"], "description": "Direction used to order files."}
|
||||
}
|
||||
}),
|
||||
Self::NotesReadFile => json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {"type": "string", "description": "Note file path to read."},
|
||||
"start_line": {"anyOf": [{"type": "integer"}, {"type": "null"}], "description": "First line to return, inclusive and 1-based. Negative values count backward from the final line."},
|
||||
"stop_line": {"anyOf": [{"type": "integer"}, {"type": "null"}], "description": "Last line to return, inclusive and 1-based. Negative values count backward from the final line."}
|
||||
},
|
||||
"required": ["path"]
|
||||
}),
|
||||
Self::NotesSearchContents => json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"max_matches_per_file": {"type": "integer", "minimum": 1, "description": "Maximum number of matching lines returned per file."},
|
||||
"query": {"type": "string", "encrypted": true, "description": "Case-sensitive literal substring to find in note lines."},
|
||||
"recent_file_first": {"type": "boolean", "description": "Whether to order matching files by creation time, newest first."},
|
||||
"max_files": {"type": "integer", "minimum": 1, "description": "Maximum number of matching files returned."},
|
||||
"path_prefix": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Note path prefix to search."}
|
||||
},
|
||||
"required": ["query"]
|
||||
}),
|
||||
Self::NotesAppendToFile => json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"text": {"type": "string", "encrypted": true, "description": "Text appended exactly as provided."},
|
||||
"path": {"type": "string", "description": "Note file path to append to."}
|
||||
},
|
||||
"required": ["text", "path"]
|
||||
}),
|
||||
Self::NotesWriteFile => json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"text": {"type": "string", "encrypted": true, "description": "Complete replacement text for the file."},
|
||||
"path": {"type": "string", "description": "Note file path to create or replace."}
|
||||
},
|
||||
"required": ["text", "path"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn spec(
|
||||
self,
|
||||
history_messages: Option<&HistoryToolMessages>,
|
||||
notes_messages: Option<&NotesToolMessages>,
|
||||
) -> ToolSpec {
|
||||
let (namespace_description, tool_message) = match self {
|
||||
Self::HistoryListWindows => history_messages
|
||||
.map(|messages| (&messages.namespace_description, &messages.list_windows)),
|
||||
Self::HistoryListItems => history_messages
|
||||
.map(|messages| (&messages.namespace_description, &messages.list_items)),
|
||||
Self::HistoryReadItem => history_messages
|
||||
.map(|messages| (&messages.namespace_description, &messages.read_item)),
|
||||
Self::HistorySearchContents => history_messages
|
||||
.map(|messages| (&messages.namespace_description, &messages.search_contents)),
|
||||
Self::NotesListFilesByPrefix => notes_messages.map(|messages| {
|
||||
(
|
||||
&messages.namespace_description,
|
||||
&messages.list_files_by_prefix,
|
||||
)
|
||||
}),
|
||||
Self::NotesReadFile => notes_messages
|
||||
.map(|messages| (&messages.namespace_description, &messages.read_file)),
|
||||
Self::NotesSearchContents => notes_messages
|
||||
.map(|messages| (&messages.namespace_description, &messages.search_contents)),
|
||||
Self::NotesAppendToFile => notes_messages
|
||||
.map(|messages| (&messages.namespace_description, &messages.append_to_file)),
|
||||
Self::NotesWriteFile => notes_messages
|
||||
.map(|messages| (&messages.namespace_description, &messages.write_file)),
|
||||
}
|
||||
.map_or((None, None), |(namespace_description, tool_message)| {
|
||||
(namespace_description.as_deref(), tool_message.as_ref())
|
||||
});
|
||||
let tool = with_catalog_tool_message(
|
||||
ResponsesApiTool {
|
||||
name: self.name().to_string(),
|
||||
description: self.description().to_string(),
|
||||
strict: false,
|
||||
parameters: parse_tool_input_schema(&self.parameters()).unwrap_or_else(|error| {
|
||||
panic!("History tool input schema should parse: {error}")
|
||||
}),
|
||||
output_schema: None,
|
||||
defer_loading: None,
|
||||
},
|
||||
tool_message,
|
||||
);
|
||||
ToolSpec::Namespace(ResponsesApiNamespace {
|
||||
name: self.namespace().to_string(),
|
||||
description: namespace_description
|
||||
.unwrap_or(self.namespace_description())
|
||||
.to_string(),
|
||||
tools: vec![ResponsesApiNamespaceTool::Function(tool)],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct HistoryNotesTool {
|
||||
action: HistoryNotesAction,
|
||||
backend: HistoryNotesBackend,
|
||||
session_id: String,
|
||||
current_agent_name: String,
|
||||
spec: ToolSpec,
|
||||
}
|
||||
|
||||
impl HistoryNotesTool {
|
||||
pub(crate) fn new(
|
||||
action: HistoryNotesAction,
|
||||
backend: HistoryNotesBackend,
|
||||
session_id: String,
|
||||
current_agent_name: String,
|
||||
history_messages: Option<&HistoryToolMessages>,
|
||||
notes_messages: Option<&NotesToolMessages>,
|
||||
) -> Self {
|
||||
Self {
|
||||
action,
|
||||
backend,
|
||||
session_id,
|
||||
current_agent_name,
|
||||
spec: action.spec(history_messages, notes_messages),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_call(
|
||||
&self,
|
||||
call: ToolCall<'_>,
|
||||
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
|
||||
let arguments = call.function_arguments()?;
|
||||
let arguments = if arguments.trim().is_empty() {
|
||||
json!({})
|
||||
} else {
|
||||
serde_json::from_str(arguments)
|
||||
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?
|
||||
};
|
||||
let result = self
|
||||
.backend
|
||||
.call(
|
||||
self.action.endpoint(),
|
||||
&self.session_id,
|
||||
&self.current_agent_name,
|
||||
arguments,
|
||||
call.truncation_policy,
|
||||
)
|
||||
.await
|
||||
.map_err(FunctionCallError::RespondToModel)?;
|
||||
|
||||
Ok(Box::new(HistoryNotesToolOutput::new(result)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'call> ToolExecutor<ToolCall<'call>> for HistoryNotesTool {
|
||||
fn tool_name(&self) -> ToolName {
|
||||
ToolName::namespaced(self.action.namespace(), self.action.name())
|
||||
}
|
||||
|
||||
fn spec(&self) -> ToolSpec {
|
||||
self.spec.clone()
|
||||
}
|
||||
|
||||
fn exposure(&self) -> ToolExposure {
|
||||
ToolExposure::DirectModelOnly
|
||||
}
|
||||
|
||||
fn supports_parallel_tool_calls(&self) -> bool {
|
||||
self.action.supports_parallel_tool_calls()
|
||||
}
|
||||
|
||||
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
|
||||
where
|
||||
'call: 'a,
|
||||
{
|
||||
Box::pin(self.handle_call(call))
|
||||
}
|
||||
}
|
||||
|
||||
struct HistoryNotesToolOutput {
|
||||
result: Value,
|
||||
output: FunctionCallOutputPayload,
|
||||
}
|
||||
|
||||
impl HistoryNotesToolOutput {
|
||||
fn new(mut result: Value) -> Result<Self, FunctionCallError> {
|
||||
// Separate attachments before serializing any text or retaining log output.
|
||||
let images = result.as_object_mut().and_then(|map| map.remove("images"));
|
||||
// The server applies the requested output budget before encryption.
|
||||
let mut output = match result.get("encrypted_output").and_then(Value::as_str) {
|
||||
Some(encrypted_content) => FunctionCallOutputPayload::from_content_items(vec![
|
||||
FunctionCallOutputContentItem::EncryptedContent {
|
||||
encrypted_content: encrypted_content.to_string(),
|
||||
},
|
||||
]),
|
||||
None => FunctionCallOutputPayload::from_text(result.to_string()),
|
||||
};
|
||||
if let Some(images) = images {
|
||||
let invalid_image = || {
|
||||
FunctionCallError::RespondToModel(
|
||||
"History backend returned invalid image content.".to_string(),
|
||||
)
|
||||
};
|
||||
let images = images.as_array().ok_or_else(invalid_image)?;
|
||||
let mut content = match output.body {
|
||||
FunctionCallOutputBody::Text(text) => {
|
||||
vec![FunctionCallOutputContentItem::InputText { text }]
|
||||
}
|
||||
FunctionCallOutputBody::ContentItems(content) => content,
|
||||
};
|
||||
for image in images {
|
||||
let data = image
|
||||
.get("data")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(invalid_image)?;
|
||||
let mime_type = image
|
||||
.get("mime_type")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(invalid_image)?;
|
||||
let detail =
|
||||
serde_json::from_value(image.get("detail").cloned().unwrap_or(Value::Null))
|
||||
.map_err(|_| invalid_image())?;
|
||||
content.push(FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: format!("data:{mime_type};base64,{data}"),
|
||||
},
|
||||
detail,
|
||||
});
|
||||
}
|
||||
output = FunctionCallOutputPayload::from_content_items(content);
|
||||
}
|
||||
Ok(Self { result, output })
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolOutput for HistoryNotesToolOutput {
|
||||
fn log_output(&self) -> String {
|
||||
JsonToolOutput::new(self.result.clone()).log_output()
|
||||
}
|
||||
|
||||
fn success_for_logging(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option<Value> {
|
||||
// Hooks must not receive model-only image attachments.
|
||||
Some(self.result.clone())
|
||||
}
|
||||
|
||||
fn to_response_item(&self, call_id: &str, _payload: &ToolPayload) -> ResponseInputItem {
|
||||
ResponseInputItem::FunctionCallOutput {
|
||||
call_id: call_id.to_string(),
|
||||
output: self.output.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> Value {
|
||||
Value::String("History tools are unavailable in code mode.".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tools_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,181 +0,0 @@
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputPayload;
|
||||
use codex_protocol::models::ImageDetail;
|
||||
use codex_protocol::models::ImageReference;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_tools::ToolOutput;
|
||||
use codex_tools::ToolPayload;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
use super::HistoryNotesToolOutput;
|
||||
|
||||
#[test]
|
||||
fn preserves_encrypted_history_output() {
|
||||
let result = HistoryNotesToolOutput::new(json!({"encrypted_output": "enc_payload"}))
|
||||
.expect("valid output")
|
||||
.to_response_item(
|
||||
"call-1",
|
||||
&ToolPayload::Function {
|
||||
arguments: "{}".to_string(),
|
||||
},
|
||||
);
|
||||
|
||||
let ResponseInputItem::FunctionCallOutput { output, .. } = result else {
|
||||
panic!("expected function-call output");
|
||||
};
|
||||
assert_eq!(
|
||||
output.content_items(),
|
||||
Some(
|
||||
[FunctionCallOutputContentItem::EncryptedContent {
|
||||
encrypted_content: "enc_payload".to_string(),
|
||||
}]
|
||||
.as_slice()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_images_as_separate_output_items_without_logging_bytes() {
|
||||
let output = HistoryNotesToolOutput::new(json!({
|
||||
"encrypted_output": "enc_payload",
|
||||
"images": [
|
||||
{"data": "cG5n", "mime_type": "image/png", "detail": "original"},
|
||||
{"data": "anBlZw==", "mime_type": "image/jpeg", "detail": "low"},
|
||||
{"data": "Z2lm", "mime_type": "image/gif"},
|
||||
{"data": "d2VicA==", "mime_type": "image/webp", "detail": null}
|
||||
]
|
||||
}))
|
||||
.expect("valid image output");
|
||||
assert_eq!(
|
||||
output.log_output(),
|
||||
json!({"encrypted_output": "enc_payload"}).to_string()
|
||||
);
|
||||
assert_eq!(
|
||||
output.post_tool_use_response(
|
||||
"call-1",
|
||||
&ToolPayload::Function {
|
||||
arguments: "{}".to_string()
|
||||
}
|
||||
),
|
||||
Some(json!({"encrypted_output": "enc_payload"}))
|
||||
);
|
||||
assert_eq!(
|
||||
output.to_response_item(
|
||||
"call-1",
|
||||
&ToolPayload::Function {
|
||||
arguments: "{}".to_string()
|
||||
}
|
||||
),
|
||||
ResponseInputItem::FunctionCallOutput {
|
||||
call_id: "call-1".to_string(),
|
||||
output: FunctionCallOutputPayload::from_content_items(vec![
|
||||
FunctionCallOutputContentItem::EncryptedContent {
|
||||
encrypted_content: "enc_payload".to_string()
|
||||
},
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: "data:image/png;base64,cG5n".to_string()
|
||||
},
|
||||
detail: Some(ImageDetail::Original)
|
||||
},
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: "data:image/jpeg;base64,anBlZw==".to_string()
|
||||
},
|
||||
detail: Some(ImageDetail::Low)
|
||||
},
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: "data:image/gif;base64,Z2lm".to_string()
|
||||
},
|
||||
detail: None
|
||||
},
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: "data:image/webp;base64,d2VicA==".to_string()
|
||||
},
|
||||
detail: None
|
||||
},
|
||||
])
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_empty_attachments_and_legacy_plaintext_results() {
|
||||
for (result, expected) in [
|
||||
(
|
||||
json!({"encrypted_output": "enc_payload", "images": []}),
|
||||
FunctionCallOutputPayload::from_content_items(vec![
|
||||
FunctionCallOutputContentItem::EncryptedContent {
|
||||
encrypted_content: "enc_payload".to_string(),
|
||||
},
|
||||
]),
|
||||
),
|
||||
(
|
||||
json!({"text": "legacy result"}),
|
||||
FunctionCallOutputPayload::from_text(json!({"text": "legacy result"}).to_string()),
|
||||
),
|
||||
] {
|
||||
let output = HistoryNotesToolOutput::new(result).expect("valid output");
|
||||
assert_eq!(
|
||||
output.to_response_item(
|
||||
"call-1",
|
||||
&ToolPayload::Function {
|
||||
arguments: "{}".to_string()
|
||||
}
|
||||
),
|
||||
ResponseInputItem::FunctionCallOutput {
|
||||
call_id: "call-1".to_string(),
|
||||
output: expected
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_attachments_instead_of_silently_dropping_them() {
|
||||
for images in [
|
||||
json!(null),
|
||||
json!({}),
|
||||
json!([null]),
|
||||
json!([{"mime_type": "image/png"}]),
|
||||
json!([{"data": "private-image-bytes"}]),
|
||||
json!([{"data": "private-image-bytes", "mime_type": "image/png", "detail": "invalid"}]),
|
||||
] {
|
||||
let result = HistoryNotesToolOutput::new(
|
||||
json!({"encrypted_output": "enc_payload", "images": images}),
|
||||
);
|
||||
let Err(codex_extension_api::FunctionCallError::RespondToModel(message)) = result else {
|
||||
panic!("expected a model-facing image error");
|
||||
};
|
||||
assert_eq!(message, "History backend returned invalid image content.");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_catalog_messages_preserve_defaults_and_explicit_empty_descriptions() {
|
||||
let action = super::HistoryNotesAction::NotesReadFile;
|
||||
let mut expected = action.spec(/*history_messages*/ None, /*notes_messages*/ None);
|
||||
let codex_tools::ToolSpec::Namespace(namespace) = &mut expected else {
|
||||
panic!("expected namespace");
|
||||
};
|
||||
namespace.description.clear();
|
||||
let codex_tools::ResponsesApiNamespaceTool::Function(tool) = &mut namespace.tools[0] else {
|
||||
panic!("expected function");
|
||||
};
|
||||
tool.description.clear();
|
||||
let messages = codex_protocol::openai_models::NotesToolMessages {
|
||||
namespace_description: Some(String::new()),
|
||||
read_file: Some(codex_protocol::openai_models::ToolMessage {
|
||||
description: Some(String::new()),
|
||||
parameters: Some(String::new()),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
action.spec(/*history_messages*/ None, Some(&messages)),
|
||||
expected
|
||||
);
|
||||
}
|
||||
@@ -1,505 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::config::TokenBudgetConfig;
|
||||
use codex_extension_api::ContentItemKind;
|
||||
use codex_extension_api::ConversationHistory;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionRegistry;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::NoopTurnItemEmitter;
|
||||
use codex_extension_api::PromptFragment;
|
||||
use codex_extension_api::PromptSlot;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_extension_api::ToolCall;
|
||||
use codex_extension_api::ToolCallSource;
|
||||
use codex_extension_api::ToolExecutor;
|
||||
use codex_extension_api::ToolName;
|
||||
use codex_extension_api::ToolPayload;
|
||||
use codex_history_notes_extension::install;
|
||||
use codex_http_client::DestinationPolicy;
|
||||
use codex_http_client::NetworkPolicyController;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_protocol::openai_models::NotesToolMessages;
|
||||
use codex_protocol::openai_models::ToolMessage;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_protocol::protocol::TruncationPolicy;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
type TestResult = Result<(), Box<dyn std::error::Error>>;
|
||||
const THREAD_HINT: &str = "Recent notes (up to 5, most-recent first):\n- /root/worker/notes/latest.md (2 lines, 14 UTF-8 bytes)";
|
||||
|
||||
#[tokio::test]
|
||||
async fn installed_extension_exposes_and_invokes_history_notes_tools() -> TestResult {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/backend-api/codex/alpha/notes/v2/read_file"))
|
||||
.and(header("x-openai-actor-authorization", "actor-biscuit"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"encrypted_output": "enc_payload"
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/backend-api/codex/alpha/notes/v2/thread_hint"))
|
||||
.and(header("x-openai-actor-authorization", "actor-biscuit"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"text": THREAD_HINT})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.build()
|
||||
.await?;
|
||||
config.model_provider.base_url = Some(format!("{}/backend-api/codex", server.uri()));
|
||||
config.token_budget = Some(TokenBudgetConfig {
|
||||
use_history_notes_extension: true,
|
||||
..TokenBudgetConfig::default()
|
||||
});
|
||||
let controller = NetworkPolicyController::default();
|
||||
config.application_network_policy = controller.policy();
|
||||
assert!(controller.publish(
|
||||
controller.policy().revision(),
|
||||
DestinationPolicy::Unrestricted
|
||||
));
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"x-openai-actor-authorization",
|
||||
HeaderValue::from_static("actor-biscuit"),
|
||||
);
|
||||
let auth_manager =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::Headers(AuthHeaders::new(headers)));
|
||||
let mut builder = ExtensionRegistryBuilder::<Config>::new();
|
||||
install(&mut builder, auth_manager);
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session-123");
|
||||
let thread_store = ExtensionData::new("thread-123");
|
||||
let session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id: ThreadId::new(),
|
||||
depth: 1,
|
||||
agent_path: Some(AgentPath::root().join("worker").expect("agent path")),
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
});
|
||||
|
||||
for contributor in registry.thread_lifecycle_contributors() {
|
||||
contributor
|
||||
.on_thread_start(ThreadStartInput {
|
||||
config: &config,
|
||||
session_source: &session_source,
|
||||
persistent_thread_state_available: true,
|
||||
environments: &[],
|
||||
mcp_resource_client: None,
|
||||
extension_metrics: None,
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
let tools = exposed_tools(®istry, &session_store, &thread_store);
|
||||
assert_eq!(
|
||||
tools
|
||||
.iter()
|
||||
.map(|tool| tool.tool_name())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
ToolName::namespaced("history", "list_windows"),
|
||||
ToolName::namespaced("history", "list_items"),
|
||||
ToolName::namespaced("history", "read_item"),
|
||||
ToolName::namespaced("history", "search_contents"),
|
||||
ToolName::namespaced("notes", "list_files_by_prefix"),
|
||||
ToolName::namespaced("notes", "read_file"),
|
||||
ToolName::namespaced("notes", "search_contents"),
|
||||
ToolName::namespaced("notes", "append_to_file"),
|
||||
ToolName::namespaced("notes", "write_file"),
|
||||
]
|
||||
);
|
||||
|
||||
// Existing executors retain the catalog snapshot selected for their step.
|
||||
let step_store = ExtensionData::new("step-1");
|
||||
let mut messages = NotesToolMessages {
|
||||
read_file: Some(ToolMessage {
|
||||
description: Some("Catalog read instructions".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
step_store.insert(messages.clone());
|
||||
let catalog_tools =
|
||||
registry.tool_contributors()[0].tools_for_step(&session_store, &thread_store, &step_store);
|
||||
let captured_tool = catalog_tools
|
||||
.iter()
|
||||
.find(|tool| tool.tool_name() == ToolName::namespaced("notes", "read_file"))
|
||||
.expect("notes.read_file should be exposed");
|
||||
let captured_spec = captured_tool.spec();
|
||||
messages.read_file.as_mut().expect("read_file").description = Some(String::new());
|
||||
step_store.insert(messages);
|
||||
let next_tools =
|
||||
registry.tool_contributors()[0].tools_for_step(&session_store, &thread_store, &step_store);
|
||||
assert_ne!(
|
||||
next_tools
|
||||
.iter()
|
||||
.find(|tool| tool.tool_name() == ToolName::namespaced("notes", "read_file"))
|
||||
.expect("notes.read_file should be exposed")
|
||||
.spec(),
|
||||
captured_spec
|
||||
);
|
||||
assert_eq!(captured_tool.spec(), captured_spec);
|
||||
|
||||
let read_file = tools
|
||||
.iter()
|
||||
.find(|tool| tool.tool_name() == ToolName::namespaced("notes", "read_file"))
|
||||
.expect("notes.read_file should be exposed");
|
||||
let call = tool_call(
|
||||
ToolName::namespaced("notes", "read_file"),
|
||||
json!({"path": "notes.md"}),
|
||||
);
|
||||
let output = read_file.handle(call.clone()).await?;
|
||||
let ResponseInputItem::FunctionCallOutput { output, .. } =
|
||||
output.to_response_item(&call.call_id, &call.payload)
|
||||
else {
|
||||
panic!("expected function-call output");
|
||||
};
|
||||
assert_eq!(
|
||||
output.content_items(),
|
||||
Some(
|
||||
[FunctionCallOutputContentItem::EncryptedContent {
|
||||
encrypted_content: "enc_payload".to_string(),
|
||||
}]
|
||||
.as_slice()
|
||||
)
|
||||
);
|
||||
|
||||
let hints = registry.context_contributors()[0]
|
||||
.contribute_thread_context(&session_store, &thread_store)
|
||||
.await;
|
||||
assert_eq!(
|
||||
hints,
|
||||
vec![PromptFragment::tool(
|
||||
PromptSlot::ContextWindow,
|
||||
THREAD_HINT,
|
||||
ContentItemKind("notes.thread_hint".to_string()),
|
||||
"notes".to_string(),
|
||||
)]
|
||||
);
|
||||
|
||||
let requests = server.received_requests().await.expect("recorded requests");
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(&requests[0].body)?,
|
||||
json!({
|
||||
"path": "notes.md",
|
||||
"context": {
|
||||
"session_id": "session-123",
|
||||
"current_agent_name": "/root/worker",
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(&requests[1].body)?,
|
||||
json!({
|
||||
"context": {
|
||||
"session_id": "session-123",
|
||||
"current_agent_name": "/root/worker",
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
for (namespace, name, mut arguments) in [
|
||||
("history", "list_windows", json!({"limit": 101})),
|
||||
("history", "list_items", json!({})),
|
||||
(
|
||||
"history",
|
||||
"list_items",
|
||||
json!({"limit": 21, "max_chars_per_item": 4_000}),
|
||||
),
|
||||
(
|
||||
"history",
|
||||
"read_item",
|
||||
json!({"window_id": "window", "item_id": "item", "limit_chars": 20_001}),
|
||||
),
|
||||
(
|
||||
"history",
|
||||
"search_contents",
|
||||
json!({"query": "x".repeat(1_001), "limit": 21}),
|
||||
),
|
||||
("history", "search_contents", json!({"query": ""})),
|
||||
("notes", "list_files_by_prefix", json!({"max_results": 101})),
|
||||
(
|
||||
"notes",
|
||||
"search_contents",
|
||||
json!({"query": "x".repeat(1_001), "max_files": 21, "max_matches_per_file": 11}),
|
||||
),
|
||||
("notes", "search_contents", json!({"query": ""})),
|
||||
(
|
||||
"notes",
|
||||
"read_file",
|
||||
json!({"path": "notes.md", "start_line": -2}),
|
||||
),
|
||||
(
|
||||
"notes",
|
||||
"append_to_file",
|
||||
json!({"path": "notes.md", "text": "append"}),
|
||||
),
|
||||
(
|
||||
"notes",
|
||||
"write_file",
|
||||
json!({"path": "notes.md", "text": "replace"}),
|
||||
),
|
||||
] {
|
||||
server.reset().await;
|
||||
let mut response = json!({"encrypted_output": "enc_history"});
|
||||
let mut expected_output =
|
||||
vec![json!({"type": "encrypted_content", "encrypted_content": "enc_history"})];
|
||||
if namespace == "history" && name == "read_item" {
|
||||
// Images are not part of the text budget sent to the backend.
|
||||
let data = "cG5n".repeat(1_000);
|
||||
response["images"] = json!([
|
||||
{"data": data, "mime_type": "image/png", "detail": "original"},
|
||||
{"data": "anBlZw==", "mime_type": "image/jpeg", "detail": "high"}
|
||||
]);
|
||||
expected_output.extend([
|
||||
json!({"type": "input_image", "image_url": format!("data:image/png;base64,{data}"), "detail": "original"}),
|
||||
json!({"type": "input_image", "image_url": "data:image/jpeg;base64,anBlZw==", "detail": "high"})
|
||||
]);
|
||||
}
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!(
|
||||
"/backend-api/codex/alpha/{namespace}/v2/{name}"
|
||||
)))
|
||||
.and(header("x-openai-actor-authorization", "actor-biscuit"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(response))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let tool_name = ToolName::namespaced(namespace, name);
|
||||
let tool = tools
|
||||
.iter()
|
||||
.find(|tool| tool.tool_name() == tool_name)
|
||||
.expect("exposed tool");
|
||||
let call = tool_call(tool_name, arguments.clone());
|
||||
let output = tool.handle(call.clone()).await?;
|
||||
assert_eq!(
|
||||
serde_json::to_value(output.to_response_item(&call.call_id, &call.payload))?,
|
||||
json!({"type": "function_call_output", "call_id": call.call_id, "output": expected_output})
|
||||
);
|
||||
arguments["context"] = json!({
|
||||
"session_id": "session-123",
|
||||
"current_agent_name": "/root/worker",
|
||||
});
|
||||
let requests = server.received_requests().await.expect("recorded requests");
|
||||
for request in &requests {
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(
|
||||
request
|
||||
.headers
|
||||
.get("x-openai-tool-output-truncation-policy")
|
||||
.expect("truncation policy header")
|
||||
.to_str()?
|
||||
)?,
|
||||
json!({"mode": "bytes", "limit": 1024})
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
requests
|
||||
.iter()
|
||||
.map(|request| serde_json::from_slice::<serde_json::Value>(&request.body))
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
vec![arguments]
|
||||
);
|
||||
}
|
||||
|
||||
// Plaintext backend responses must keep attachments out of text and logs too.
|
||||
server.reset().await;
|
||||
let text_result = json!({"content": "look: [image 1]", "n_chars": 15, "next_offset_chars": 15});
|
||||
let mut response = text_result.clone();
|
||||
response["images"] = json!([
|
||||
{"data": "cG5n", "mime_type": "image/png", "detail": "original"}
|
||||
]);
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/backend-api/codex/alpha/history/v2/read_item"))
|
||||
.and(header("x-openai-actor-authorization", "actor-biscuit"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(response))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let tool_name = ToolName::namespaced("history", "read_item");
|
||||
let read_item = tools
|
||||
.iter()
|
||||
.find(|tool| tool.tool_name() == tool_name)
|
||||
.expect("history.read_item");
|
||||
let call = tool_call(tool_name, json!({"window_id": "window", "item_id": "item"}));
|
||||
let output = read_item.handle(call.clone()).await?;
|
||||
assert_eq!(output.log_output(), text_result.to_string());
|
||||
assert_eq!(
|
||||
serde_json::to_value(output.to_response_item(&call.call_id, &call.payload))?,
|
||||
json!({
|
||||
"type": "function_call_output",
|
||||
"call_id": call.call_id,
|
||||
"output": [
|
||||
{"type": "input_text", "text": text_result.to_string()},
|
||||
{"type": "input_image", "image_url": "data:image/png;base64,cG5n", "detail": "original"}
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
for result in [
|
||||
json!({"text": ""}),
|
||||
json!({"text": "x".repeat(4_001)}),
|
||||
json!({"encrypted_output": "old-backend-hint"}),
|
||||
] {
|
||||
server.reset().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/backend-api/codex/alpha/notes/v2/thread_hint"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(result))
|
||||
.mount(&server)
|
||||
.await;
|
||||
assert!(
|
||||
registry.context_contributors()[0]
|
||||
.contribute_thread_context(&session_store, &thread_store)
|
||||
.await
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
server.reset().await;
|
||||
assert!(controller.publish(
|
||||
controller.policy().revision(),
|
||||
DestinationPolicy::Restricted {
|
||||
allowed_hosts: Default::default(),
|
||||
},
|
||||
));
|
||||
assert!(
|
||||
registry.context_contributors()[0]
|
||||
.contribute_thread_context(&session_store, &thread_store)
|
||||
.await
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
server
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("recorded requests")
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let mut disabled_config = config.clone();
|
||||
disabled_config.token_budget = None;
|
||||
for contributor in registry.config_contributors() {
|
||||
contributor.on_config_changed(&session_store, &thread_store, &config, &disabled_config);
|
||||
}
|
||||
assert!(exposed_tools(®istry, &session_store, &thread_store).is_empty());
|
||||
assert!(
|
||||
registry.context_contributors()[0]
|
||||
.contribute_thread_context(&session_store, &thread_store)
|
||||
.await
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn history_notes_require_an_openai_provider_and_codex_backend_auth() -> TestResult {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.build()
|
||||
.await?;
|
||||
config.token_budget = Some(TokenBudgetConfig {
|
||||
use_history_notes_extension: true,
|
||||
..TokenBudgetConfig::default()
|
||||
});
|
||||
|
||||
for (provider, auth) in [
|
||||
(
|
||||
config.model_provider.clone(),
|
||||
CodexAuth::from_api_key("test-api-key"),
|
||||
),
|
||||
(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
),
|
||||
] {
|
||||
config.model_provider = provider;
|
||||
let mut builder = ExtensionRegistryBuilder::<Config>::new();
|
||||
install(&mut builder, AuthManager::from_auth_for_testing(auth));
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session-123");
|
||||
let thread_store = ExtensionData::new("thread-123");
|
||||
|
||||
for contributor in registry.thread_lifecycle_contributors() {
|
||||
contributor
|
||||
.on_thread_start(ThreadStartInput {
|
||||
config: &config,
|
||||
session_source: &SessionSource::Cli,
|
||||
persistent_thread_state_available: true,
|
||||
environments: &[],
|
||||
mcp_resource_client: None,
|
||||
extension_metrics: None,
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
assert!(exposed_tools(®istry, &session_store, &thread_store).is_empty());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn exposed_tools(
|
||||
registry: &ExtensionRegistry<Config>,
|
||||
session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
registry
|
||||
.tool_contributors()
|
||||
.iter()
|
||||
.flat_map(|contributor| contributor.tools(session_store, thread_store))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn tool_call(tool_name: ToolName, arguments: serde_json::Value) -> ToolCall<'static> {
|
||||
ToolCall {
|
||||
turn_id: "turn-1".to_string(),
|
||||
call_id: "call-read-file".to_string(),
|
||||
tool_name,
|
||||
model: "gpt-test".to_string(),
|
||||
codex_turn_metadata: None,
|
||||
truncation_policy: TruncationPolicy::Bytes(1024),
|
||||
source: ToolCallSource::Direct,
|
||||
conversation_history: ConversationHistory::default(),
|
||||
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
|
||||
attachment_store: codex_core::passthrough_image_store(),
|
||||
ephemeral: false,
|
||||
environments: Vec::new(),
|
||||
payload: ToolPayload::Function {
|
||||
arguments: arguments.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
//! Verify captured catalog definitions and history attachments reach outgoing model requests.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_core::config::Config;
|
||||
use codex_core::config::TokenBudgetConfig;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_history_notes_extension::install;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use core_test_support::context_snapshot;
|
||||
use core_test_support::context_snapshot::ContextSnapshotOptions;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use http::HeaderMap;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const PNG: &str =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII=";
|
||||
|
||||
const NATIVE_TOOLS: [(&str, &str, &[&str]); 2] = [
|
||||
(
|
||||
"history",
|
||||
"",
|
||||
&["list_windows", "list_items", "read_item", "search_contents"],
|
||||
),
|
||||
(
|
||||
"notes",
|
||||
" ",
|
||||
&[
|
||||
"list_files_by_prefix",
|
||||
"read_file",
|
||||
"search_contents",
|
||||
"append_to_file",
|
||||
"write_file",
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn history_images_reach_the_next_model_request() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let server = responses::start_mock_server().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/alpha/history/v2/read_item"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"encrypted_output": "opaque-history-text",
|
||||
"images": [
|
||||
{"data": PNG, "mime_type": "image/png", "detail": "original"},
|
||||
{"data": PNG, "mime_type": "image/png", "detail": "high"},
|
||||
{"data": PNG, "mime_type": "image/png", "detail": "auto"}
|
||||
]
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let requests = responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
responses::sse(vec![
|
||||
responses::ev_function_call_with_namespace(
|
||||
"read-history",
|
||||
"history",
|
||||
"read_item",
|
||||
&json!({"window_id": "window", "item_id": "item"}).to_string(),
|
||||
),
|
||||
responses::ev_completed("first-response"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("assistant", "done"),
|
||||
responses::ev_completed("second-response"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let auth = CodexAuth::Headers(AuthHeaders::new(HeaderMap::new()));
|
||||
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
|
||||
install(
|
||||
&mut extensions,
|
||||
AuthManager::from_auth_for_testing(auth.clone()),
|
||||
);
|
||||
let parameters = json!({
|
||||
"type": "object", "description": "Catalog read parameters",
|
||||
"properties": {"window_id": {"type": "string"}, "item_id": {"type": "string"}},
|
||||
"required": ["window_id", "item_id"]
|
||||
});
|
||||
let catalog_parameters = parameters.clone();
|
||||
let test = test_codex()
|
||||
.with_auth(auth)
|
||||
.with_model_info_override("gpt-5.5", move |model_info| {
|
||||
model_info.supports_experimental_context = true;
|
||||
let mut messages = json!({});
|
||||
for (namespace, description, names) in NATIVE_TOOLS {
|
||||
messages[namespace] = json!({"namespace_description": description});
|
||||
for name in names {
|
||||
messages[namespace][*name] =
|
||||
json!({"description": format!("Catalog {namespace}.{name}")});
|
||||
}
|
||||
}
|
||||
messages["history"]["read_item"]["parameters"] = json!(catalog_parameters.to_string());
|
||||
model_info.model_messages.get_or_insert_default().tools =
|
||||
Some(serde_json::from_value(messages).expect("native catalog messages"));
|
||||
})
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_config(|config| {
|
||||
config.model_provider.name = "OpenAI".to_string();
|
||||
config.token_budget = Some(TokenBudgetConfig {
|
||||
use_history_notes_extension: true,
|
||||
..TokenBudgetConfig::default()
|
||||
});
|
||||
})
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
test.submit_text_turn("Read the image from history.")
|
||||
.await?;
|
||||
let requests = requests.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
for request in &requests {
|
||||
let body = request.body_json();
|
||||
for (name, description, tool_names) in NATIVE_TOOLS {
|
||||
let namespace = body["tools"]
|
||||
.as_array()
|
||||
.expect("tools")
|
||||
.iter()
|
||||
.find(|tool| tool["name"] == name)
|
||||
.expect("native namespace");
|
||||
assert_eq!(namespace["description"], description);
|
||||
let tools = namespace["tools"].as_array().expect("namespace tools");
|
||||
assert_eq!(
|
||||
tools
|
||||
.iter()
|
||||
.map(|tool| (
|
||||
tool["name"].as_str().unwrap(),
|
||||
tool["description"].as_str().unwrap().to_string(),
|
||||
))
|
||||
.collect::<BTreeMap<_, _>>(),
|
||||
tool_names
|
||||
.iter()
|
||||
.map(|tool| (*tool, format!("Catalog {name}.{tool}")))
|
||||
.collect(),
|
||||
);
|
||||
if name == "history" {
|
||||
assert_eq!(
|
||||
tools
|
||||
.iter()
|
||||
.find(|tool| tool["name"] == "read_item")
|
||||
.unwrap()["parameters"],
|
||||
parameters
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
requests[1].function_call_output("read-history")["output"],
|
||||
json!([
|
||||
{"type": "encrypted_content", "encrypted_content": "opaque-history-text"},
|
||||
{"type": "input_image", "image_url": format!("data:image/png;base64,{PNG}"), "detail": "original"},
|
||||
{"type": "input_image", "image_url": format!("data:image/png;base64,{PNG}"), "detail": "original"},
|
||||
{"type": "input_image", "image_url": format!("data:image/png;base64,{PNG}"), "detail": "original"}
|
||||
])
|
||||
);
|
||||
insta::assert_snapshot!(context_snapshot::format_request_history_snapshot(
|
||||
"History/Notes catalog definitions preserve empty and whitespace namespace descriptions, and history images reach the next model request.",
|
||||
&requests,
|
||||
&ContextSnapshotOptions::default()
|
||||
.rewrite_known_segments()
|
||||
.include_request_settings(),
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
---
|
||||
source: ext/history-notes/tests/image_model_input.rs
|
||||
expression: "context_snapshot::format_request_history_snapshot(\"History/Notes catalog definitions preserve empty and whitespace namespace descriptions, and history images reach the next model request.\",\n&requests,\n&ContextSnapshotOptions::default().rewrite_known_segments().include_request_settings(),)"
|
||||
---
|
||||
Scenario: History/Notes catalog definitions preserve empty and whitespace namespace descriptions, and history images reach the next model request.
|
||||
|
||||
## Window 1
|
||||
Settings:
|
||||
include: ["reasoning.encrypted_content"]
|
||||
model: "gpt-5.5"
|
||||
parallel_tool_calls: true
|
||||
prompt_cache_key: "<PROMPT_CACHE_KEY 1>"
|
||||
reasoning: {"effort":"medium"}
|
||||
store: false
|
||||
stream: true
|
||||
text: {"verbosity":"low"}
|
||||
tool_choice: "auto"
|
||||
tools (9; hash=8ee44dddbc5ba019):
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
- custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- namespace/history; hash=48578cec2ffd3727
|
||||
- function/list_items
|
||||
- function/list_windows
|
||||
- function/read_item
|
||||
- function/search_contents
|
||||
- namespace/notes: ; hash=1984d9e2f2d6c4f0
|
||||
- function/append_to_file
|
||||
- function/list_files_by_prefix
|
||||
- function/read_file
|
||||
- function/search_contents
|
||||
- function/write_file
|
||||
- tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7
|
||||
- web_search; hash=f103e327c6870a46
|
||||
-- request 1 (turn) --
|
||||
00:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
01:message/developer[2]:
|
||||
[01] <PERMISSIONS_INSTRUCTIONS>
|
||||
[02] <tools>
|
||||
Deferred tool namespaces:
|
||||
- multi_agent_v1: Tools for spawning and managing sub-agents.
|
||||
</tools>
|
||||
02:message/user:
|
||||
<ENVIRONMENT_CONTEXT>
|
||||
03:message/user:
|
||||
Read the image from history.
|
||||
-- request 2 (turn) --
|
||||
04:function_call/history.read_item:{"item_id":"item","window_id":"window"}
|
||||
05:function_call_output:<encrypted_content> | <input_image> | <input_image> | <input_image>
|
||||
@@ -1,10 +0,0 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "image-generation",
|
||||
compile_data = [
|
||||
"imagegen_description.md",
|
||||
"imagegen_gif_description.md",
|
||||
],
|
||||
crate_name = "codex_image_generation_extension",
|
||||
)
|
||||
@@ -1,43 +0,0 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "codex-image-generation-extension"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "codex_image_generation_extension"
|
||||
path = "src/lib.rs"
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64 = { workspace = true }
|
||||
codex-api = { workspace = true }
|
||||
codex-attachment-store = { workspace = true }
|
||||
codex-core = { workspace = true }
|
||||
codex-exec-server = { workspace = true }
|
||||
codex-extension-api = { workspace = true }
|
||||
codex-extension-items = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-model-provider = { workspace = true }
|
||||
codex-model-provider-info = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-tools = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
codex-utils-image = { workspace = true }
|
||||
codex-utils-path-uri = { workspace = true }
|
||||
http = { workspace = true }
|
||||
schemars = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
image = { workspace = true, features = ["png"] }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
|
||||
@@ -1,18 +0,0 @@
|
||||
The `image_gen.imagegen` tool enables image generation from descriptions and editing of existing images based on specific instructions. Use it when:
|
||||
|
||||
- The user requests an image based on a scene description, such as a diagram, portrait, comic, meme, or any other visual.
|
||||
- The user wants to modify an attached or previously generated image with specific changes, including adding or removing elements, altering colors, improving quality/resolution, or transforming the style (e.g., cartoon, oil painting).
|
||||
|
||||
Guidelines:
|
||||
- imagegen needs a few minutes to finish. In code-mode, use the first-line @exec directive to give the initial call 120 seconds and the same yield for any waits that follow. Once it finishes, return the image with generatedImage(result).
|
||||
- Avoid printing the full result or its base64 image data with `text()` or `notify()`; print only small metadata when needed.
|
||||
- Set `transparent_background` to true when the request calls for a transparent background, including background removal or a cutout; set it to false otherwise. For edits, preserve existing transparency unless the user asks to change it.
|
||||
- Omit both `referenced_image_paths` and `num_last_images_to_include` when generating a brand new image.
|
||||
- For edits, use `referenced_image_paths` when every target image has a local file path.
|
||||
- If you have not seen a local image yet, use `view_image` to inspect it before editing.
|
||||
- Use `num_last_images_to_include` only when at least one target image has no local file path.
|
||||
- Set `num_last_images_to_include` to the smallest number of recent conversation images that includes every target image, up to 5.
|
||||
- Never provide both `referenced_image_paths` and `num_last_images_to_include`.
|
||||
- If neither mechanism can include every target image, ask the user to attach the missing images again.
|
||||
- Directly generate the image without reconfirmation or clarification unless required images must be attached again.
|
||||
- Always use this tool for image editing unless the user explicitly requests otherwise. Do not use the `python` tool for image editing unless specifically instructed.
|
||||
@@ -1,4 +0,0 @@
|
||||
GIF guidelines:
|
||||
- Use imagegen only for simple GIFs with 2–16 frames. For more complex animations or more than 16 frames, use other tools instead.
|
||||
- Set `gif` to request GIF output. Use `{}` for the defaults (9 frames, 200 ms per frame), or set `frame_count` and `frame_duration_ms`.
|
||||
- To edit a previously generated GIF, first inspect its frames, then create a spritesheet with equal-sized cells in a regular grid. Pass that spritesheet through `referenced_image_paths` and set `gif` to generate the new GIF. Do not pass the GIF itself as an edit input.
|
||||
@@ -1,76 +0,0 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
const GENERATED_IMAGE_ARTIFACTS_DIR: &str = "generated_images";
|
||||
const MAX_IMAGE_GENERATION_OUTPUT_HINT_BYTES: usize = 1024;
|
||||
|
||||
/// Identify GIFs from their encoded header so transport and filenames preserve animation.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum GeneratedImageFormat {
|
||||
Png,
|
||||
Gif,
|
||||
}
|
||||
|
||||
impl GeneratedImageFormat {
|
||||
pub(crate) fn from_base64(result: &str) -> Self {
|
||||
let result = result.trim();
|
||||
if result.starts_with("R0lGODdh") || result.starts_with("R0lGODlh") {
|
||||
Self::Gif
|
||||
} else {
|
||||
Self::Png
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mime_type(self) -> &'static str {
|
||||
match self {
|
||||
Self::Png => "image/png",
|
||||
Self::Gif => "image/gif",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the extension-owned artifact path for a generated image.
|
||||
pub(crate) fn image_generation_artifact_path(
|
||||
save_root: &AbsolutePathBuf,
|
||||
session_id: &str,
|
||||
call_id: &str,
|
||||
format: GeneratedImageFormat,
|
||||
) -> AbsolutePathBuf {
|
||||
let sanitize = |value: &str| {
|
||||
let mut sanitized: String = value
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
ch
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if sanitized.is_empty() {
|
||||
sanitized = "generated_image".to_string();
|
||||
}
|
||||
sanitized
|
||||
};
|
||||
|
||||
let extension = match format {
|
||||
GeneratedImageFormat::Png => "png",
|
||||
GeneratedImageFormat::Gif => "gif",
|
||||
};
|
||||
save_root
|
||||
.join(GENERATED_IMAGE_ARTIFACTS_DIR)
|
||||
.join(sanitize(session_id))
|
||||
.join(format!("{}.{extension}", sanitize(call_id)))
|
||||
}
|
||||
|
||||
/// Returns the model-facing generated-image path hint, or omits it if it is too large.
|
||||
pub(crate) fn image_generation_output_hint(
|
||||
image_output_dir: impl Display,
|
||||
image_output_path: impl Display,
|
||||
) -> Option<String> {
|
||||
let hint = format!(
|
||||
"Generated images are saved to {image_output_dir} as {image_output_path} by default.\nIf you need to use a generated image at another path, copy it and leave the original in place unless the user explicitly asks you to delete it.\nThe generated image is already displayed to the user. There is no need to render it in the final response as a Markdown image or file link."
|
||||
);
|
||||
(hint.len() <= MAX_IMAGE_GENERATION_OUTPUT_HINT_BYTES).then_some(hint)
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
use codex_api::ImageEditRequest;
|
||||
use codex_api::ImageGenerationRequest;
|
||||
use codex_api::ImageRequestError;
|
||||
use codex_api::ImageResponse;
|
||||
use codex_api::ImagesClient;
|
||||
use codex_api::ReqwestTransport;
|
||||
use codex_api::map_api_error;
|
||||
use codex_core::X_CODEX_TURN_METADATA_HEADER;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::default_client::add_originator_header;
|
||||
use codex_login::default_client::create_transport_for_routes_async;
|
||||
use codex_model_provider::SharedModelProvider;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
|
||||
const X_CODEX_IMAGE_TURN_ID_HEADER: &str = "x-codex-image-turn-id";
|
||||
|
||||
pub(crate) struct ImageBackendError {
|
||||
message: String,
|
||||
codex_error: CodexErr,
|
||||
imagegen_request_id: Option<String>,
|
||||
}
|
||||
|
||||
impl ImageBackendError {
|
||||
fn from_image_request(error: ImageRequestError) -> Self {
|
||||
let (error, imagegen_request_id) = error.into_parts();
|
||||
let message = error.to_string();
|
||||
Self {
|
||||
message,
|
||||
codex_error: map_api_error(error),
|
||||
imagegen_request_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_message(message: String) -> Self {
|
||||
Self {
|
||||
codex_error: CodexErr::Stream(message.clone()),
|
||||
message,
|
||||
imagegen_request_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
|
||||
pub(crate) fn codex_error(&self) -> &CodexErr {
|
||||
&self.codex_error
|
||||
}
|
||||
|
||||
pub(crate) fn imagegen_request_id(&self) -> Option<&str> {
|
||||
self.imagegen_request_id.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CodexImagesBackend {
|
||||
provider: SharedModelProvider,
|
||||
http_client_factory: HttpClientFactory,
|
||||
originator: Option<String>,
|
||||
}
|
||||
|
||||
impl CodexImagesBackend {
|
||||
/// Creates a backend that sends image requests through the active model provider.
|
||||
pub(crate) fn new(
|
||||
provider: SharedModelProvider,
|
||||
http_client_factory: HttpClientFactory,
|
||||
originator: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
provider,
|
||||
http_client_factory,
|
||||
originator,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the provider and auth required for the current image API request.
|
||||
async fn client(&self) -> Result<ImagesClient<ReqwestTransport>, ImageBackendError> {
|
||||
let setup = codex_model_provider::resolve_request(
|
||||
self.provider.as_ref(),
|
||||
/*scope*/ None,
|
||||
/*routing*/ None,
|
||||
self.http_client_factory.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ImageBackendError::from_message(err.to_string()))?;
|
||||
let transport = create_transport_for_routes_async(
|
||||
setup.http_client_factory,
|
||||
ClientRouteClass::Api,
|
||||
setup.redirect_policy,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ImageBackendError::from_message(err.to_string()))?;
|
||||
Ok(ImagesClient::new(
|
||||
transport,
|
||||
setup.api_provider,
|
||||
setup.api_auth,
|
||||
))
|
||||
}
|
||||
|
||||
/// Sends a standalone image generation request through the configured Images client.
|
||||
pub(crate) async fn generate(
|
||||
&self,
|
||||
request: ImageGenerationRequest,
|
||||
turn_id: &str,
|
||||
codex_turn_metadata: Option<&str>,
|
||||
) -> Result<(ImageResponse, Option<String>), ImageBackendError> {
|
||||
self.client()
|
||||
.await?
|
||||
.generate(
|
||||
&request,
|
||||
image_request_headers(self.originator.as_deref(), turn_id, codex_turn_metadata),
|
||||
)
|
||||
.await
|
||||
.map_err(ImageBackendError::from_image_request)
|
||||
}
|
||||
|
||||
/// Sends a standalone image edit request through the configured Images client.
|
||||
pub(crate) async fn edit(
|
||||
&self,
|
||||
request: ImageEditRequest,
|
||||
turn_id: &str,
|
||||
codex_turn_metadata: Option<&str>,
|
||||
) -> Result<(ImageResponse, Option<String>), ImageBackendError> {
|
||||
self.client()
|
||||
.await?
|
||||
.edit(
|
||||
&request,
|
||||
image_request_headers(self.originator.as_deref(), turn_id, codex_turn_metadata),
|
||||
)
|
||||
.await
|
||||
.map_err(ImageBackendError::from_image_request)
|
||||
}
|
||||
}
|
||||
|
||||
fn image_request_headers(
|
||||
originator: Option<&str>,
|
||||
turn_id: &str,
|
||||
codex_turn_metadata: Option<&str>,
|
||||
) -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
if let Ok(turn_id) = HeaderValue::from_str(turn_id) {
|
||||
headers.insert(X_CODEX_IMAGE_TURN_ID_HEADER, turn_id);
|
||||
}
|
||||
if let Some(originator) = originator {
|
||||
add_originator_header(&mut headers, originator);
|
||||
}
|
||||
|
||||
if let Some(metadata) = codex_turn_metadata
|
||||
&& let Ok(metadata) = HeaderValue::from_str(metadata)
|
||||
{
|
||||
headers.insert(X_CODEX_TURN_METADATA_HEADER, metadata);
|
||||
}
|
||||
|
||||
headers
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_core::config::Config;
|
||||
use codex_extension_api::ConfigContributor;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadOriginator;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_extension_api::ToolCall;
|
||||
use codex_extension_api::ToolContributor;
|
||||
use codex_extension_api::ToolExecutor;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AuthManager;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
use crate::backend::CodexImagesBackend;
|
||||
use crate::tool::ImageGenerationTool;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ImageGenerationExtension {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
resolve_save_root: Arc<SaveRootResolver>,
|
||||
}
|
||||
|
||||
type SaveRootResolver = dyn Fn(&Config) -> Option<AbsolutePathBuf> + Send + Sync;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ImageGenerationExtensionConfig {
|
||||
available: bool,
|
||||
gif_enabled: bool,
|
||||
http_client_factory: HttpClientFactory,
|
||||
provider: ModelProviderInfo,
|
||||
save_root: Option<AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
impl ImageGenerationExtensionConfig {
|
||||
/// Resolves the image provider and save root for a thread.
|
||||
fn from_config(config: &Config, resolve_save_root: &SaveRootResolver) -> Self {
|
||||
Self {
|
||||
available: config.model_provider.is_openai()
|
||||
|| config.model_provider.requires_openai_auth
|
||||
|| config.model_provider.uses_openai_actor_authorization(),
|
||||
gif_enabled: config.features.image_generation_animation_enabled(),
|
||||
http_client_factory: config.http_client_factory(),
|
||||
provider: config.model_provider.clone(),
|
||||
save_root: resolve_save_root(config),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadLifecycleContributor<Config> for ImageGenerationExtension {
|
||||
/// Seeds image-generation configuration when a thread begins.
|
||||
fn on_thread_start<'a>(
|
||||
&'a self,
|
||||
input: ThreadStartInput<'a, Config>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
input
|
||||
.thread_store
|
||||
.insert(ImageGenerationExtensionConfig::from_config(
|
||||
input.config,
|
||||
self.resolve_save_root.as_ref(),
|
||||
));
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigContributor<Config> for ImageGenerationExtension {
|
||||
/// Refreshes image-generation configuration after thread configuration changes.
|
||||
fn on_config_changed(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
_previous_config: &Config,
|
||||
new_config: &Config,
|
||||
) {
|
||||
thread_store.insert(ImageGenerationExtensionConfig::from_config(
|
||||
new_config,
|
||||
self.resolve_save_root.as_ref(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolContributor for ImageGenerationExtension {
|
||||
/// Creates the image-generation tool exposed by this installed extension.
|
||||
fn tools(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
let Some(config) = thread_store.get::<ImageGenerationExtensionConfig>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !config.available {
|
||||
return Vec::new();
|
||||
}
|
||||
let auth = thread_store
|
||||
.get::<codex_model_provider::ProviderAuthContext>()
|
||||
.unwrap_or_else(|| {
|
||||
Arc::new(codex_model_provider::ProviderAuthContext {
|
||||
credentials: Arc::clone(&self.auth_manager),
|
||||
runtime_auth: None,
|
||||
})
|
||||
});
|
||||
|
||||
vec![Arc::new(ImageGenerationTool::new(
|
||||
CodexImagesBackend::new(
|
||||
auth.model_provider(config.provider.clone()),
|
||||
config.http_client_factory.clone(),
|
||||
thread_store
|
||||
.get::<ThreadOriginator>()
|
||||
.map(|originator| originator.0.clone()),
|
||||
),
|
||||
config.save_root.clone(),
|
||||
thread_store.level_id().to_string(),
|
||||
config.gif_enabled,
|
||||
))]
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the standalone image-generation extension contributors.
|
||||
pub fn install(
|
||||
registry: &mut ExtensionRegistryBuilder<Config>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
resolve_save_root: impl Fn(&Config) -> Option<AbsolutePathBuf> + Send + Sync + 'static,
|
||||
) {
|
||||
let extension = Arc::new(ImageGenerationExtension {
|
||||
auth_manager,
|
||||
resolve_save_root: Arc::new(resolve_save_root),
|
||||
});
|
||||
registry.thread_lifecycle_contributor(extension.clone());
|
||||
registry.config_contributor(extension.clone());
|
||||
registry.tool_contributor(extension);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
mod artifact;
|
||||
mod backend;
|
||||
mod extension;
|
||||
mod tool;
|
||||
|
||||
pub use extension::install;
|
||||
|
||||
pub(crate) const IMAGE_GEN_NAMESPACE: &str = "image_gen";
|
||||
pub(crate) const IMAGEGEN_TOOL_NAME: &str = "imagegen";
|
||||
@@ -1,691 +0,0 @@
|
||||
use base64::Engine;
|
||||
use codex_api::ImageBackground;
|
||||
use codex_api::ImageEditRequest;
|
||||
use codex_api::ImageGenerationRequest;
|
||||
use codex_api::ImageQuality;
|
||||
use codex_exec_server::FileSystemEnvironmentAccessor;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_extension_api::ToolOutput;
|
||||
use codex_extension_api::ToolPayload;
|
||||
use codex_extension_api::ToolSpec;
|
||||
use codex_extension_items::image_generation::ImageGenerationFailure;
|
||||
use codex_extension_items::image_generation::ImageGenerationInputImage;
|
||||
use codex_protocol::ResponseItemId;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::UsageLimitReachedError;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::DEFAULT_IMAGE_DETAIL;
|
||||
use codex_protocol::models::FunctionCallOutputBody;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputPayload;
|
||||
use codex_protocol::models::ImageReference;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_tools::ResponsesApiNamespaceTool;
|
||||
use codex_tools::ToolEnvironment;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
use super::GeneratedImageOutput;
|
||||
use super::ImageRequest;
|
||||
use super::ImagegenArgs;
|
||||
use super::PreparedImageRequest;
|
||||
use super::imagegen_tool_spec;
|
||||
use super::request_for_call_args;
|
||||
use super::usage_limit_failure;
|
||||
use crate::IMAGE_GEN_NAMESPACE;
|
||||
use crate::IMAGEGEN_TOOL_NAME;
|
||||
use crate::artifact::image_generation_artifact_path;
|
||||
use crate::artifact::image_generation_output_hint;
|
||||
|
||||
const RESULT: &str = "cG5n";
|
||||
|
||||
#[test]
|
||||
fn test_usage_limit_failure_without_an_exhausted_window_reset() {
|
||||
for (limit_id, expected) in [
|
||||
(
|
||||
Some("imagegen_premium"),
|
||||
Some(ImageGenerationFailure::UsageLimitExceeded {
|
||||
limit_id: "imagegen_premium".to_string(),
|
||||
resets_at: None,
|
||||
}),
|
||||
),
|
||||
(Some("premium"), None),
|
||||
(None, None),
|
||||
] {
|
||||
let error = CodexErr::UsageLimitReached(UsageLimitReachedError {
|
||||
plan_type: None,
|
||||
resets_at: None,
|
||||
limit_window_minutes: None,
|
||||
rate_limits: Some(Box::new(
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"limit_id": limit_id,
|
||||
"primary": {"used_percent": 100.0},
|
||||
"secondary": {"used_percent": 50.0, "resets_at": 3000}
|
||||
}))
|
||||
.expect("rate limit snapshot"),
|
||||
)),
|
||||
promo_message: None,
|
||||
rate_limit_reached_type: None,
|
||||
});
|
||||
|
||||
assert_eq!(usage_limit_failure(&error), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn referenced_files_record_the_exact_bytes_read_for_each_request() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory");
|
||||
let root = AbsolutePathBuf::from_absolute_path(directory.path()).expect("absolute root");
|
||||
let first = root.join("first.png");
|
||||
let second = root.join("second.png");
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let environment =
|
||||
ToolEnvironment::new("test".to_string(), PathUri::from_abs_path(&root), &access);
|
||||
let args = ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "combine the references".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: Some(vec![second.clone(), first.clone()]),
|
||||
num_last_images_to_include: None,
|
||||
};
|
||||
let png = |color| {
|
||||
let image = image::RgbaImage::from_pixel(1, 1, image::Rgba(color));
|
||||
let mut bytes = std::io::Cursor::new(Vec::new());
|
||||
image
|
||||
.write_to(&mut bytes, image::ImageFormat::Png)
|
||||
.expect("encode PNG");
|
||||
bytes.into_inner()
|
||||
};
|
||||
let second_bytes = png([0, 255, 0, 255]);
|
||||
std::fs::write(second.as_path(), &second_bytes).expect("write second image");
|
||||
std::fs::write(root.join("unused.png").as_path(), png([0, 0, 255, 255]))
|
||||
.expect("write unused image");
|
||||
|
||||
// Reusing a path after replacing its contents must produce a new observation.
|
||||
for first_bytes in [png([255, 0, 0, 255]), png([255, 255, 0, 255])] {
|
||||
std::fs::write(first.as_path(), &first_bytes).expect("write first image");
|
||||
let inputs = [(&second, &second_bytes), (&first, &first_bytes)];
|
||||
let expected = PreparedImageRequest {
|
||||
request: ImageRequest::Edit(ImageEditRequest {
|
||||
output: None,
|
||||
images: inputs
|
||||
.iter()
|
||||
.map(|(_, bytes)| ImageReference::Inline {
|
||||
image_url: format!(
|
||||
"data:image/png;base64,{}",
|
||||
base64::engine::general_purpose::STANDARD.encode(bytes)
|
||||
),
|
||||
})
|
||||
.collect(),
|
||||
prompt: args.prompt.clone(),
|
||||
background: Some(ImageBackground::Opaque),
|
||||
model: "gpt-image-2".to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images: inputs
|
||||
.iter()
|
||||
.map(|(path, bytes)| ImageGenerationInputImage {
|
||||
path: (*path).clone(),
|
||||
sha256: format!("{:x}", Sha256::digest(bytes)),
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
assert_eq!(
|
||||
request_for_call_args(&args, &[], std::slice::from_ref(&environment))
|
||||
.await
|
||||
.expect("edit request"),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn unreadable_or_invalid_reference_does_not_build_an_edit_request() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory");
|
||||
let root = AbsolutePathBuf::from_absolute_path(directory.path()).expect("absolute root");
|
||||
let invalid = root.join("invalid.png");
|
||||
std::fs::write(invalid.as_path(), b"not an image").expect("write invalid image");
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let environment =
|
||||
ToolEnvironment::new("test".to_string(), PathUri::from_abs_path(&root), &access);
|
||||
for path in [root.join("missing.png"), invalid] {
|
||||
let args = ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "edit the reference".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: Some(vec![path]),
|
||||
num_last_images_to_include: None,
|
||||
};
|
||||
assert!(
|
||||
request_for_call_args(&args, &[], std::slice::from_ref(&environment))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artifact_path_sanitizes_session_and_call_ids() {
|
||||
let save_root = AbsolutePathBuf::current_dir().expect("current directory should be absolute");
|
||||
|
||||
assert_eq!(
|
||||
image_generation_artifact_path(
|
||||
&save_root,
|
||||
"../session",
|
||||
"../call",
|
||||
super::GeneratedImageFormat::Png
|
||||
),
|
||||
save_root
|
||||
.join("generated_images")
|
||||
.join("___session")
|
||||
.join("___call.png")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_reserved_image_gen_namespace() {
|
||||
let ToolSpec::Namespace(spec) = imagegen_tool_spec(/*gif_enabled*/ false) else {
|
||||
panic!("imagegen should advertise a namespace tool");
|
||||
};
|
||||
assert_eq!(spec.name, IMAGE_GEN_NAMESPACE);
|
||||
let ResponsesApiNamespaceTool::Function(function) = &spec.tools[0] else {
|
||||
panic!("imagegen should advertise a function tool");
|
||||
};
|
||||
assert_eq!(function.name, IMAGEGEN_TOOL_NAME);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imagegen_code_mode_declaration_describes_generated_image_result() {
|
||||
let spec = imagegen_tool_spec(/*gif_enabled*/ false);
|
||||
let definitions = codex_tools::collect_code_mode_tool_definitions(
|
||||
[&spec],
|
||||
/*code_mode_input_schema_max_bytes*/ None,
|
||||
);
|
||||
let [definition] = definitions.as_slice() else {
|
||||
panic!("imagegen should produce one code-mode declaration");
|
||||
};
|
||||
let (_, return_type) = definition
|
||||
.description
|
||||
.rsplit_once("): Promise<")
|
||||
.expect("imagegen declaration should return a promise");
|
||||
assert_eq!(
|
||||
return_type,
|
||||
"{ image_url: string; output_hint?: string; }>; };\n```"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imagegen_output_schema_does_not_change_direct_api_serialization() {
|
||||
let spec = imagegen_tool_spec(/*gif_enabled*/ false);
|
||||
let mut without_output_schema = spec.clone();
|
||||
let ToolSpec::Namespace(namespace) = &mut without_output_schema else {
|
||||
panic!("imagegen should advertise a namespace tool");
|
||||
};
|
||||
let ResponsesApiNamespaceTool::Function(function) = &mut namespace.tools[0] else {
|
||||
panic!("imagegen should advertise a function tool");
|
||||
};
|
||||
function.output_schema = None;
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(spec).expect("tool spec should serialize"),
|
||||
serde_json::to_value(without_output_schema).expect("tool spec should serialize")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn omitted_references_generate_with_fixed_defaults() {
|
||||
assert_eq!(
|
||||
request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "paint a moonlit lake".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: None,
|
||||
num_last_images_to_include: None,
|
||||
},
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect("generation request should build"),
|
||||
PreparedImageRequest {
|
||||
request: ImageRequest::Generate(ImageGenerationRequest {
|
||||
output: None,
|
||||
prompt: "paint a moonlit lake".to_string(),
|
||||
background: Some(ImageBackground::Opaque),
|
||||
model: "gpt-image-2".to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recent_image_fallback_selects_newest_images_in_chronological_order() {
|
||||
let history = vec![
|
||||
ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
input_image("user-1"),
|
||||
input_image("user-2"),
|
||||
ContentItem::InputText {
|
||||
text: "edit these".to_string(),
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::FunctionCall {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
name: "mcp_image".to_string(),
|
||||
namespace: None,
|
||||
arguments: "{}".to_string(),
|
||||
call_id: "mcp-call".to_string(),
|
||||
encrypted_function_args: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: Some("mcp-call".to_string()),
|
||||
name: None,
|
||||
namespace: None,
|
||||
output: image_output("mcp"),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::CustomToolCall {
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
status: Some("completed".to_string()),
|
||||
call_id: "code-mode-call".to_string(),
|
||||
name: "exec".to_string(),
|
||||
namespace: None,
|
||||
input: String::new(),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::CustomToolCallOutput {
|
||||
id: None,
|
||||
call_id: "code-mode-call".to_string(),
|
||||
name: Some("exec".to_string()),
|
||||
output: image_output("code-mode"),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::ImageGenerationCall {
|
||||
encrypted_content: None,
|
||||
id: Some(ResponseItemId::with_suffix("ig", "generated-call")),
|
||||
status: "completed".to_string(),
|
||||
revised_prompt: None,
|
||||
result: "generated".to_string(),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: None,
|
||||
name: Some("notifications".to_string()),
|
||||
namespace: Some("slack".to_string()),
|
||||
output: image_output("standalone"),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: None,
|
||||
num_last_images_to_include: Some(5),
|
||||
},
|
||||
&history,
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect("history-backed edit request should build"),
|
||||
PreparedImageRequest {
|
||||
request: ImageRequest::Edit(expected_edit_request(
|
||||
"change the lighting",
|
||||
&["user-2", "mcp", "code-mode", "generated", "standalone"],
|
||||
)),
|
||||
input_images: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recent_image_fallback_passes_file_backed_image_to_edit_request() {
|
||||
let request = request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: None,
|
||||
num_last_images_to_include: Some(1),
|
||||
},
|
||||
&[ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
input_image("older-inline-image"),
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::File {
|
||||
file_id: "newer-file-backed-image".to_string(),
|
||||
},
|
||||
detail: None,
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect("a selected file-backed image should be passed through");
|
||||
|
||||
assert_eq!(
|
||||
request,
|
||||
PreparedImageRequest {
|
||||
request: ImageRequest::Edit(ImageEditRequest {
|
||||
output: None,
|
||||
images: vec![ImageReference::File {
|
||||
file_id: "newer-file-backed-image".to_string(),
|
||||
}],
|
||||
prompt: "change the lighting".to_string(),
|
||||
background: Some(ImageBackground::Opaque),
|
||||
model: "gpt-image-2".to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// Tool-output file references must count toward the window instead of exposing an older image.
|
||||
#[tokio::test]
|
||||
async fn recent_image_fallback_passes_file_backed_tool_output_to_edit_request() {
|
||||
let request = request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: None,
|
||||
num_last_images_to_include: Some(1),
|
||||
},
|
||||
&[
|
||||
ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: Some("older-inline-output".to_string()),
|
||||
name: None,
|
||||
namespace: None,
|
||||
output: image_output("older-inline-image"),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::CustomToolCallOutput {
|
||||
id: None,
|
||||
call_id: "newer-file-backed-output".to_string(),
|
||||
name: Some("view_image".to_string()),
|
||||
output: FunctionCallOutputPayload::from_content_items(vec![
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::File {
|
||||
file_id: "newer-file-backed-image".to_string(),
|
||||
},
|
||||
detail: None,
|
||||
},
|
||||
]),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect("a selected file-backed tool output should be passed through");
|
||||
|
||||
assert_eq!(
|
||||
request,
|
||||
PreparedImageRequest {
|
||||
request: ImageRequest::Edit(ImageEditRequest {
|
||||
output: None,
|
||||
images: vec![ImageReference::File {
|
||||
file_id: "newer-file-backed-image".to_string(),
|
||||
}],
|
||||
prompt: "change the lighting".to_string(),
|
||||
background: Some(ImageBackground::Opaque),
|
||||
model: "gpt-image-2".to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn conflicting_image_selectors_return_tool_error() {
|
||||
let error = request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: Some(vec![
|
||||
"/tmp/image.png"
|
||||
.try_into()
|
||||
.expect("test path should be absolute"),
|
||||
]),
|
||||
num_last_images_to_include: Some(1),
|
||||
},
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect_err("conflicting selectors should fail");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"provide only one of `referenced_image_paths` or `num_last_images_to_include`"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn too_many_referenced_image_paths_return_tool_error() {
|
||||
let error = request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: Some(
|
||||
(0..6)
|
||||
.map(|index| {
|
||||
format!("/tmp/image-{index}.png")
|
||||
.try_into()
|
||||
.expect("test path should be absolute")
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
num_last_images_to_include: None,
|
||||
},
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect_err("too many paths should fail before reading files");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"`referenced_image_paths` must contain at most 5 paths"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recent_image_fallback_requires_requested_count() {
|
||||
let error = request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: None,
|
||||
num_last_images_to_include: Some(2),
|
||||
},
|
||||
&[ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![input_image("only-image")],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect_err("history-backed edit should require the requested image count");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"requested the last 2 conversation images, but only 1 were available"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_output_returns_image_input_and_output_hint() {
|
||||
let output_hint =
|
||||
image_generation_output_hint("/tmp", "/tmp/call-1.png").expect("hint should fit");
|
||||
let output = GeneratedImageOutput {
|
||||
result: RESULT.to_string(),
|
||||
output_hint: Some(output_hint.clone()),
|
||||
};
|
||||
|
||||
let ResponseInputItem::FunctionCallOutput {
|
||||
output: response_output,
|
||||
..
|
||||
} = output.to_response_item("call-1", &function_payload())
|
||||
else {
|
||||
panic!("imagegen should return function tool output");
|
||||
};
|
||||
let FunctionCallOutputBody::ContentItems(content_items) = response_output.body else {
|
||||
panic!("imagegen output should contain generated image bytes");
|
||||
};
|
||||
assert_eq!(
|
||||
content_items,
|
||||
vec![
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{RESULT}")
|
||||
},
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputText { text: output_hint },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_output_returns_generated_image_helper_input_in_code_mode() {
|
||||
let output = GeneratedImageOutput {
|
||||
result: RESULT.to_string(),
|
||||
output_hint: Some("generated image save hint".to_string()),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
output.code_mode_result(&function_payload()),
|
||||
serde_json::json!({
|
||||
"image_url": format!("data:image/png;base64,{RESULT}"),
|
||||
"output_hint": "generated image save hint",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_output_omits_oversized_output_hint() {
|
||||
let long_path = "x".repeat(1024);
|
||||
let output = GeneratedImageOutput {
|
||||
result: RESULT.to_string(),
|
||||
output_hint: image_generation_output_hint("/tmp", long_path),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
output.code_mode_result(&function_payload()),
|
||||
serde_json::json!({
|
||||
"image_url": format!("data:image/png;base64,{RESULT}"),
|
||||
})
|
||||
);
|
||||
|
||||
let ResponseInputItem::FunctionCallOutput {
|
||||
output: response_output,
|
||||
..
|
||||
} = output.to_response_item("call-1", &function_payload())
|
||||
else {
|
||||
panic!("imagegen should return function tool output");
|
||||
};
|
||||
let FunctionCallOutputBody::ContentItems(content_items) = response_output.body else {
|
||||
panic!("imagegen output should contain generated image bytes");
|
||||
};
|
||||
assert_eq!(
|
||||
content_items,
|
||||
vec![FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{RESULT}")
|
||||
},
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
fn input_image(image: &str) -> ContentItem {
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{image}"),
|
||||
},
|
||||
detail: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn image_output(image: &str) -> FunctionCallOutputPayload {
|
||||
FunctionCallOutputPayload::from_content_items(vec![FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{image}"),
|
||||
},
|
||||
detail: None,
|
||||
}])
|
||||
}
|
||||
|
||||
fn expected_edit_request(prompt: &str, images: &[&str]) -> ImageEditRequest {
|
||||
ImageEditRequest {
|
||||
output: None,
|
||||
images: images
|
||||
.iter()
|
||||
.map(|image| ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{image}"),
|
||||
})
|
||||
.collect(),
|
||||
prompt: prompt.to_string(),
|
||||
background: Some(ImageBackground::Opaque),
|
||||
model: "gpt-image-2".to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn function_payload() -> ToolPayload {
|
||||
ToolPayload::Function {
|
||||
arguments: "{}".to_string(),
|
||||
}
|
||||
}
|
||||
@@ -1,821 +0,0 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
use codex_api::GifOptions;
|
||||
use codex_api::ImageBackground;
|
||||
use codex_api::ImageEditRequest;
|
||||
use codex_api::ImageGenerationRequest;
|
||||
use codex_api::ImageOutput;
|
||||
use codex_api::ImageQuality;
|
||||
use codex_attachment_store::UploadRequest;
|
||||
use codex_attachment_store::UploadResult;
|
||||
use codex_exec_server::CreateDirectoryOptions;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_extension_api::ExtensionTurnItem;
|
||||
use codex_extension_api::FunctionCallError;
|
||||
use codex_extension_api::ToolCall;
|
||||
use codex_extension_api::ToolEnvironment;
|
||||
use codex_extension_api::ToolExecutor;
|
||||
use codex_extension_api::ToolName;
|
||||
use codex_extension_api::ToolOutput;
|
||||
use codex_extension_api::ToolPayload;
|
||||
use codex_extension_api::ToolSpec;
|
||||
use codex_extension_api::parse_tool_input_schema;
|
||||
use codex_extension_items::ExtensionItem;
|
||||
use codex_extension_items::image_generation::GeneratedImageRef;
|
||||
use codex_extension_items::image_generation::ImageGenerationFailure;
|
||||
use codex_extension_items::image_generation::ImageGenerationInputImage;
|
||||
use codex_extension_items::image_generation::ImageGenerationItem;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::DEFAULT_IMAGE_DETAIL;
|
||||
use codex_protocol::models::FunctionCallOutputBody;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputPayload;
|
||||
use codex_protocol::models::ImageReference;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::ImageGenerationBeginEvent;
|
||||
use codex_protocol::protocol::ImageGenerationEndEvent;
|
||||
use codex_tools::ResponsesApiNamespace;
|
||||
use codex_tools::ResponsesApiNamespaceTool;
|
||||
use codex_tools::ResponsesApiTool;
|
||||
use codex_tools::ToolExposure;
|
||||
use codex_tools::default_namespace_description;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_image::PromptImageMode;
|
||||
use codex_utils_image::load_for_prompt_bytes;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use schemars::JsonSchema;
|
||||
use schemars::r#gen::SchemaSettings;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::IMAGE_GEN_NAMESPACE;
|
||||
use crate::IMAGEGEN_TOOL_NAME;
|
||||
use crate::artifact::GeneratedImageFormat;
|
||||
use crate::artifact::image_generation_artifact_path;
|
||||
use crate::artifact::image_generation_output_hint;
|
||||
use crate::backend::CodexImagesBackend;
|
||||
|
||||
const IMAGE_MODEL: &str = "gpt-image-2";
|
||||
const MAX_EDIT_IMAGES: usize = 5;
|
||||
const MAX_EXECUTOR_GENERATED_IMAGE_BYTES: usize = 32 * 1024 * 1024;
|
||||
const MAX_EXECUTOR_GENERATED_IMAGE_BASE64_BYTES: usize =
|
||||
MAX_EXECUTOR_GENERATED_IMAGE_BYTES.div_ceil(3) * 4;
|
||||
const IMAGEGEN_DESCRIPTION: &str = include_str!("../imagegen_description.md");
|
||||
const IMAGEGEN_GIF_DESCRIPTION: &str = include_str!("../imagegen_gif_description.md");
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ImageGenerationTool {
|
||||
backend: CodexImagesBackend,
|
||||
save_root: Option<AbsolutePathBuf>,
|
||||
thread_id: String,
|
||||
gif_enabled: bool,
|
||||
}
|
||||
|
||||
impl ImageGenerationTool {
|
||||
/// Creates an image-generation tool backed by an image API executor.
|
||||
pub(crate) fn new(
|
||||
backend: CodexImagesBackend,
|
||||
save_root: Option<AbsolutePathBuf>,
|
||||
thread_id: String,
|
||||
gif_enabled: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
backend,
|
||||
save_root,
|
||||
thread_id,
|
||||
gif_enabled,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ImagegenArgs {
|
||||
prompt: String,
|
||||
/// Set this to create a simple looping GIF with 2–16 frames. Use {} for defaults.
|
||||
gif: Option<GifOptions>,
|
||||
/// Whether the output should have a transparent background. Defaults to false.
|
||||
#[serde(default)]
|
||||
transparent_background: bool,
|
||||
#[schemars(length(max = 5))]
|
||||
referenced_image_paths: Option<Vec<AbsolutePathBuf>>,
|
||||
#[schemars(range(min = 1, max = 5))]
|
||||
num_last_images_to_include: Option<usize>,
|
||||
}
|
||||
|
||||
fn legacy_end_event(item: &ImageGenerationItem) -> EventMsg {
|
||||
EventMsg::ImageGenerationEnd(ImageGenerationEndEvent {
|
||||
call_id: item.id.clone(),
|
||||
status: item.status.clone(),
|
||||
revised_prompt: item.revised_prompt.clone(),
|
||||
image: item.image.clone(),
|
||||
transparent_background: item.transparent_background,
|
||||
failure: item.failure.clone(),
|
||||
saved_path: item.saved_path.clone(),
|
||||
input_images: item.input_images.clone(),
|
||||
generation_id: item.generation_id.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn extension_turn_item(item: ImageGenerationItem, legacy_event: EventMsg) -> ExtensionTurnItem {
|
||||
ExtensionTurnItem {
|
||||
item: ExtensionItem::ImageGeneration(item),
|
||||
legacy_events: vec![legacy_event],
|
||||
}
|
||||
}
|
||||
|
||||
impl<'call> ToolExecutor<ToolCall<'call>> for ImageGenerationTool {
|
||||
/// Keeps the tool in the existing image-generation Responses namespace.
|
||||
fn tool_name(&self) -> ToolName {
|
||||
ToolName::namespaced(IMAGE_GEN_NAMESPACE, IMAGEGEN_TOOL_NAME)
|
||||
}
|
||||
|
||||
/// Advertises a rewritten prompt, background choice, and optional edit references.
|
||||
fn spec(&self) -> ToolSpec {
|
||||
imagegen_tool_spec(self.gif_enabled)
|
||||
}
|
||||
|
||||
/// Exposes image generation directly and through the nested code-mode tool surface.
|
||||
fn exposure(&self) -> ToolExposure {
|
||||
ToolExposure::Direct
|
||||
}
|
||||
|
||||
/// Executes the selected image operation and returns the completed image result.
|
||||
fn handle<'a>(&'a self, call: ToolCall<'call>) -> codex_extension_api::ToolExecutorFuture<'a>
|
||||
where
|
||||
'call: 'a,
|
||||
{
|
||||
Box::pin(self.handle_call(call))
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageGenerationTool {
|
||||
async fn handle_call(
|
||||
&self,
|
||||
call: ToolCall<'_>,
|
||||
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
|
||||
let args = parse_args(&call)?;
|
||||
if args.gif.is_some() && !self.gif_enabled {
|
||||
return Err(FunctionCallError::RespondToModel(
|
||||
"GIF output is unavailable in this session.".to_string(),
|
||||
));
|
||||
}
|
||||
let PreparedImageRequest {
|
||||
request,
|
||||
input_images,
|
||||
} = request_for_call_args(&args, call.conversation_history.items(), &call.environments)
|
||||
.await?;
|
||||
call.turn_item_emitter
|
||||
.emit_started(extension_turn_item(
|
||||
ImageGenerationItem {
|
||||
id: call.call_id.clone(),
|
||||
status: "in_progress".to_string(),
|
||||
revised_prompt: None,
|
||||
image: GeneratedImageRef::Inline {
|
||||
result: String::new(),
|
||||
},
|
||||
transparent_background: None,
|
||||
failure: None,
|
||||
saved_path: None,
|
||||
input_images: Vec::new(),
|
||||
imagegen_request_id: None,
|
||||
generation_id: None,
|
||||
},
|
||||
EventMsg::ImageGenerationBegin(ImageGenerationBeginEvent {
|
||||
call_id: call.call_id.clone(),
|
||||
}),
|
||||
))
|
||||
.await;
|
||||
let result = match request {
|
||||
ImageRequest::Generate(request) => {
|
||||
self.backend
|
||||
.generate(request, &call.turn_id, call.codex_turn_metadata.as_deref())
|
||||
.await
|
||||
}
|
||||
ImageRequest::Edit(request) => {
|
||||
self.backend
|
||||
.edit(request, &call.turn_id, call.codex_turn_metadata.as_deref())
|
||||
.await
|
||||
}
|
||||
}
|
||||
.map_err(|error| {
|
||||
(
|
||||
format!("image generation failed: {}", error.message()),
|
||||
usage_limit_failure(error.codex_error()),
|
||||
error.imagegen_request_id().map(str::to_string),
|
||||
)
|
||||
})
|
||||
.and_then(|(response, imagegen_request_id)| {
|
||||
let transparent_background = match response.background {
|
||||
Some(ImageBackground::Transparent) => Some(true),
|
||||
Some(ImageBackground::Opaque) => Some(false),
|
||||
Some(ImageBackground::Auto) | None => None,
|
||||
};
|
||||
match response.data.into_iter().next() {
|
||||
Some(data) => Ok((
|
||||
data.b64_json,
|
||||
transparent_background,
|
||||
imagegen_request_id,
|
||||
data.generation_id,
|
||||
)),
|
||||
None => Err((
|
||||
"image generation returned no image data".to_string(),
|
||||
None,
|
||||
imagegen_request_id,
|
||||
)),
|
||||
}
|
||||
});
|
||||
let (result, transparent_background, imagegen_request_id, generation_id) = match result {
|
||||
Ok(result) => result,
|
||||
Err((message, failure, imagegen_request_id)) => {
|
||||
let item = ImageGenerationItem {
|
||||
id: call.call_id.clone(),
|
||||
status: "failed".to_string(),
|
||||
revised_prompt: Some(args.prompt),
|
||||
image: GeneratedImageRef::Inline {
|
||||
result: String::new(),
|
||||
},
|
||||
transparent_background: None,
|
||||
failure,
|
||||
saved_path: None,
|
||||
input_images: Vec::new(),
|
||||
imagegen_request_id,
|
||||
generation_id: None,
|
||||
};
|
||||
let legacy_event = legacy_end_event(&item);
|
||||
call.turn_item_emitter
|
||||
.emit_completed(extension_turn_item(item, legacy_event))
|
||||
.await;
|
||||
return Err(FunctionCallError::RespondToModel(message));
|
||||
}
|
||||
};
|
||||
// TODO(anp): Migrate image tool path arguments and saved-path events to PathUri so image
|
||||
// operations can use the primary environment even when its paths are foreign to the host.
|
||||
let saved_path = save_image_generation_result(
|
||||
self.save_root.as_ref(),
|
||||
call.environments
|
||||
.iter()
|
||||
.find(|environment| environment.cwd.to_abs_path().is_ok()),
|
||||
&self.thread_id,
|
||||
&call.call_id,
|
||||
&result,
|
||||
)
|
||||
.await;
|
||||
// The UI item retains its attachment-store reference, while the model-facing output keeps
|
||||
// the original image so Core can prepare and upload it separately.
|
||||
let image = match BASE64_STANDARD.decode(result.trim().as_bytes()) {
|
||||
Ok(data) => {
|
||||
let request = UploadRequest {
|
||||
thread_id: self.thread_id.clone(),
|
||||
ephemeral: call.ephemeral,
|
||||
file_name: None,
|
||||
tags: HashMap::from([("usage".to_string(), "image_gen".to_string())]),
|
||||
data,
|
||||
};
|
||||
match call.attachment_store.upload(request).await {
|
||||
Ok(UploadResult::File { file_id }) => GeneratedImageRef::File { file_id },
|
||||
Ok(UploadResult::Inline { bytes }) => GeneratedImageRef::Inline {
|
||||
result: BASE64_STANDARD.encode(bytes),
|
||||
},
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
kind = ?error.kind(),
|
||||
"failed to upload generated image"
|
||||
);
|
||||
GeneratedImageRef::Inline {
|
||||
result: result.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!("failed to decode generated image for upload: {error}");
|
||||
GeneratedImageRef::Inline {
|
||||
result: result.clone(),
|
||||
}
|
||||
}
|
||||
};
|
||||
let item = ImageGenerationItem {
|
||||
id: call.call_id.clone(),
|
||||
status: "completed".to_string(),
|
||||
revised_prompt: Some(args.prompt),
|
||||
image,
|
||||
transparent_background,
|
||||
failure: None,
|
||||
saved_path: saved_path.clone(),
|
||||
input_images,
|
||||
imagegen_request_id,
|
||||
generation_id,
|
||||
};
|
||||
let legacy_event = legacy_end_event(&item);
|
||||
call.turn_item_emitter
|
||||
.emit_completed(extension_turn_item(item, legacy_event))
|
||||
.await;
|
||||
let output_hint = saved_path.as_ref().and_then(|output_path| {
|
||||
let output_dir = output_path.parent()?;
|
||||
image_generation_output_hint(output_dir.display(), output_path.display())
|
||||
});
|
||||
Ok(Box::new(GeneratedImageOutput {
|
||||
result,
|
||||
output_hint,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn usage_limit_failure(error: &CodexErr) -> Option<ImageGenerationFailure> {
|
||||
let CodexErrorDetails::UsageLimitReached(usage_limit) = error.details() else {
|
||||
return None;
|
||||
};
|
||||
let rate_limits = usage_limit.rate_limits.as_deref()?;
|
||||
let limit_id = rate_limits.limit_id.as_deref()?;
|
||||
if !matches!(limit_id, "image_gen" | "imagegen_premium") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let resets_at = if let Some(reset_at) = usage_limit.resets_at.as_ref() {
|
||||
Some(reset_at.timestamp())
|
||||
} else {
|
||||
[rate_limits.primary.as_ref(), rate_limits.secondary.as_ref()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|window| window.used_percent >= 100.0)
|
||||
.filter_map(|window| window.resets_at)
|
||||
.max()
|
||||
};
|
||||
|
||||
Some(ImageGenerationFailure::UsageLimitExceeded {
|
||||
limit_id: limit_id.to_string(),
|
||||
resets_at,
|
||||
})
|
||||
}
|
||||
|
||||
async fn save_image_generation_result(
|
||||
save_root: Option<&AbsolutePathBuf>,
|
||||
environment: Option<&ToolEnvironment<'_>>,
|
||||
session_id: &str,
|
||||
call_id: &str,
|
||||
result: &str,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
let (output_dir, save_result) = match save_root {
|
||||
Some(save_root) => {
|
||||
let path = image_generation_artifact_path(
|
||||
save_root,
|
||||
session_id,
|
||||
call_id,
|
||||
GeneratedImageFormat::from_base64(result),
|
||||
);
|
||||
let output_dir = path.parent().unwrap_or_else(|| save_root.clone());
|
||||
let save_result: io::Result<AbsolutePathBuf> = async {
|
||||
let bytes = BASE64_STANDARD
|
||||
.decode(result.trim().as_bytes())
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
|
||||
if let Some(parent) = path.parent() {
|
||||
LOCAL_FS
|
||||
.create_directory(
|
||||
&PathUri::from_abs_path(&parent),
|
||||
CreateDirectoryOptions {
|
||||
recursive: true,
|
||||
follow_symlinks: true,
|
||||
},
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
LOCAL_FS
|
||||
.write_file(
|
||||
&PathUri::from_abs_path(&path),
|
||||
bytes,
|
||||
Default::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await?;
|
||||
Ok(path)
|
||||
}
|
||||
.await;
|
||||
(output_dir, save_result)
|
||||
}
|
||||
None => {
|
||||
let environment = environment?;
|
||||
let cwd = environment.cwd.to_abs_path().ok()?;
|
||||
let fs = environment.fs();
|
||||
let output_dir = cwd.join("generated_images");
|
||||
let save_result: io::Result<AbsolutePathBuf> = async {
|
||||
let result = result.trim();
|
||||
if result.len() > MAX_EXECUTOR_GENERATED_IMAGE_BASE64_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"generated image exceeds the executor file size limit",
|
||||
));
|
||||
}
|
||||
let bytes = BASE64_STANDARD
|
||||
.decode(result.as_bytes())
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
|
||||
if bytes.len() > MAX_EXECUTOR_GENERATED_IMAGE_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"generated image exceeds the executor file size limit",
|
||||
));
|
||||
}
|
||||
|
||||
let artifact_path = image_generation_artifact_path(
|
||||
&cwd,
|
||||
session_id,
|
||||
call_id,
|
||||
GeneratedImageFormat::from_base64(result),
|
||||
);
|
||||
let path = output_dir.join(artifact_path.as_path().file_name().unwrap_or_default());
|
||||
if let Some(parent) = path.parent() {
|
||||
let parent_uri = PathUri::from_abs_path(&parent);
|
||||
fs.create_directory(
|
||||
&parent_uri,
|
||||
CreateDirectoryOptions {
|
||||
recursive: true,
|
||||
follow_symlinks: true,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Full-access executor contexts do not prevent symlinked output directories.
|
||||
let metadata = fs.get_metadata(&parent_uri, Default::default()).await?;
|
||||
if metadata.is_symlink || !metadata.is_directory {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"generated image directory is not a real directory",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Existing destination hardlinks could otherwise overwrite files outside the workspace.
|
||||
let path_uri = PathUri::from_abs_path(&path);
|
||||
match fs.get_metadata(&path_uri, Default::default()).await {
|
||||
Ok(_) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
"generated image destination already exists",
|
||||
));
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
|
||||
fs.write_file(&path_uri, bytes, Default::default()).await?;
|
||||
Ok(path)
|
||||
}
|
||||
.await;
|
||||
(output_dir, save_result)
|
||||
}
|
||||
};
|
||||
|
||||
match save_result {
|
||||
Ok(path) => Some(path),
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
call_id = %call_id,
|
||||
output_dir = %output_dir.display(),
|
||||
"failed to save generated image: {error}"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum ImageRequest {
|
||||
Generate(ImageGenerationRequest),
|
||||
Edit(ImageEditRequest),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct PreparedImageRequest {
|
||||
request: ImageRequest,
|
||||
input_images: Vec<ImageGenerationInputImage>,
|
||||
}
|
||||
|
||||
struct LoadedInputImage {
|
||||
image: ImageReference,
|
||||
identity: ImageGenerationInputImage,
|
||||
}
|
||||
|
||||
async fn request_for_call_args(
|
||||
args: &ImagegenArgs,
|
||||
history: &[ResponseItem],
|
||||
environments: &[ToolEnvironment<'_>],
|
||||
) -> Result<PreparedImageRequest, FunctionCallError> {
|
||||
let background = if args.transparent_background {
|
||||
ImageBackground::Transparent
|
||||
} else {
|
||||
ImageBackground::Opaque
|
||||
};
|
||||
let paths = args.referenced_image_paths.as_deref().unwrap_or_default();
|
||||
if paths.len() > MAX_EDIT_IMAGES {
|
||||
return Err(FunctionCallError::RespondToModel(format!(
|
||||
"`referenced_image_paths` must contain at most {MAX_EDIT_IMAGES} paths"
|
||||
)));
|
||||
}
|
||||
let mut input_images = Vec::with_capacity(paths.len());
|
||||
let images = match (paths.is_empty(), args.num_last_images_to_include) {
|
||||
(true, None) => {
|
||||
return Ok(PreparedImageRequest {
|
||||
request: ImageRequest::Generate(ImageGenerationRequest {
|
||||
prompt: args.prompt.clone(),
|
||||
output: args.gif.map(ImageOutput::Gif),
|
||||
background: Some(background),
|
||||
model: IMAGE_MODEL.to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images,
|
||||
});
|
||||
}
|
||||
(false, None) => {
|
||||
let Some(environment) = environments
|
||||
.iter()
|
||||
.find(|environment| environment.cwd.to_abs_path().is_ok())
|
||||
else {
|
||||
return Err(FunctionCallError::RespondToModel(
|
||||
"referenced image paths are unavailable in this session".to_string(),
|
||||
));
|
||||
};
|
||||
let mut images = Vec::with_capacity(paths.len());
|
||||
for path in paths {
|
||||
let input = load_input_image(path, environment).await?;
|
||||
images.push(input.image);
|
||||
input_images.push(input.identity);
|
||||
}
|
||||
images
|
||||
}
|
||||
(true, Some(count)) => {
|
||||
if !(1..=MAX_EDIT_IMAGES).contains(&count) {
|
||||
return Err(FunctionCallError::RespondToModel(format!(
|
||||
"`num_last_images_to_include` must be between 1 and {MAX_EDIT_IMAGES}"
|
||||
)));
|
||||
}
|
||||
// Pathless images have no stable reference, so this bounded window may include newer
|
||||
// unrelated images. This remains best-effort until the harness provides stable refs.
|
||||
recent_images(history, count)?
|
||||
}
|
||||
(false, Some(_)) => {
|
||||
return Err(FunctionCallError::RespondToModel(
|
||||
"provide only one of `referenced_image_paths` or \
|
||||
`num_last_images_to_include`"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
Ok(PreparedImageRequest {
|
||||
request: ImageRequest::Edit(ImageEditRequest {
|
||||
images,
|
||||
prompt: args.prompt.clone(),
|
||||
output: args.gif.map(ImageOutput::Gif),
|
||||
background: Some(background),
|
||||
model: IMAGE_MODEL.to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images,
|
||||
})
|
||||
}
|
||||
|
||||
fn recent_images(
|
||||
history: &[ResponseItem],
|
||||
count: usize,
|
||||
) -> Result<Vec<ImageReference>, FunctionCallError> {
|
||||
let mut images = Vec::with_capacity(count);
|
||||
'history: for item in history.iter().rev() {
|
||||
let mut image_references = Vec::new();
|
||||
match item {
|
||||
ResponseItem::Message { content, .. } => {
|
||||
image_references.extend(content.iter().rev().filter_map(|item| match item {
|
||||
ContentItem::InputImage { image, .. } => Some(image.clone()),
|
||||
ContentItem::InputText { .. }
|
||||
| ContentItem::InputAudio { .. }
|
||||
| ContentItem::OutputText { .. } => None,
|
||||
}));
|
||||
}
|
||||
ResponseItem::FunctionCallOutput { output, .. }
|
||||
| ResponseItem::CustomToolCallOutput { output, .. } => {
|
||||
image_references.extend(output_images(output).cloned());
|
||||
}
|
||||
ResponseItem::ImageGenerationCall { result, .. } if !result.is_empty() => {
|
||||
image_references.push(ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{result}"),
|
||||
});
|
||||
}
|
||||
ResponseItem::AdditionalTools { .. }
|
||||
| ResponseItem::Reasoning { .. }
|
||||
| ResponseItem::AgentMessage { .. }
|
||||
| ResponseItem::LocalShellCall { .. }
|
||||
| ResponseItem::FunctionCall { .. }
|
||||
| ResponseItem::ToolSearchCall { .. }
|
||||
| ResponseItem::CustomToolCall { .. }
|
||||
| ResponseItem::ToolSearchOutput { .. }
|
||||
| ResponseItem::WebSearchCall { .. }
|
||||
| ResponseItem::ImageGenerationCall { .. }
|
||||
| ResponseItem::Compaction { .. }
|
||||
| ResponseItem::ConfigurationUpdate { .. }
|
||||
| ResponseItem::CompactionTrigger { .. }
|
||||
| ResponseItem::ContextCompaction { .. }
|
||||
| ResponseItem::Other => {}
|
||||
}
|
||||
for image in image_references {
|
||||
images.push(image);
|
||||
if images.len() == count {
|
||||
break 'history;
|
||||
}
|
||||
}
|
||||
}
|
||||
if images.len() != count {
|
||||
return Err(FunctionCallError::RespondToModel(format!(
|
||||
"requested the last {count} conversation images, but only {} were available",
|
||||
images.len()
|
||||
)));
|
||||
}
|
||||
images.reverse();
|
||||
Ok(images)
|
||||
}
|
||||
|
||||
/// Extracts image references from a tool output in newest-first order.
|
||||
fn output_images(output: &FunctionCallOutputPayload) -> impl Iterator<Item = &ImageReference> + '_ {
|
||||
output
|
||||
.content_items()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.rev()
|
||||
.filter_map(|item| match item {
|
||||
FunctionCallOutputContentItem::InputImage { image, .. } => Some(image),
|
||||
FunctionCallOutputContentItem::InputText { .. }
|
||||
| FunctionCallOutputContentItem::InputAudio { .. }
|
||||
| FunctionCallOutputContentItem::EncryptedContent { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn load_input_image(
|
||||
path: &AbsolutePathBuf,
|
||||
environment: &ToolEnvironment<'_>,
|
||||
) -> Result<LoadedInputImage, FunctionCallError> {
|
||||
let path_uri = PathUri::from_abs_path(path);
|
||||
let bytes = environment
|
||||
.fs()
|
||||
.read_file(&path_uri, Default::default())
|
||||
.await
|
||||
.map_err(|error| {
|
||||
FunctionCallError::RespondToModel(format!(
|
||||
"unable to read referenced image at `{}`: {error}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
let sha256 = format!("{:x}", Sha256::digest(&bytes));
|
||||
let image = load_for_prompt_bytes(path.as_path(), bytes, PromptImageMode::Original).map_err(
|
||||
|error| {
|
||||
FunctionCallError::RespondToModel(format!(
|
||||
"unable to process referenced image at `{}`: {error}",
|
||||
path.display()
|
||||
))
|
||||
},
|
||||
)?;
|
||||
Ok(LoadedInputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: image.into_data_url(),
|
||||
},
|
||||
identity: ImageGenerationInputImage {
|
||||
path: path.clone(),
|
||||
sha256,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses the strict model-facing arguments for an image-generation call.
|
||||
fn parse_args(call: &ToolCall<'_>) -> Result<ImagegenArgs, FunctionCallError> {
|
||||
serde_json::from_str(call.function_arguments()?)
|
||||
.map_err(|err| FunctionCallError::RespondToModel(err.to_string()))
|
||||
}
|
||||
|
||||
/// Builds the namespace function schema exposed to the model.
|
||||
fn imagegen_tool_spec(gif_enabled: bool) -> ToolSpec {
|
||||
let mut schema_value = serde_json::to_value(
|
||||
SchemaSettings::draft2019_09()
|
||||
.with(|settings| settings.inline_subschemas = true)
|
||||
.into_generator()
|
||||
.into_root_schema_for::<ImagegenArgs>(),
|
||||
)
|
||||
.unwrap_or_else(|err| panic!("imagegen schema should serialize: {err}"));
|
||||
let Value::Object(ref mut schema) = schema_value else {
|
||||
unreachable!("imagegen root schema must be an object");
|
||||
};
|
||||
if !gif_enabled && let Some(Value::Object(properties)) = schema.get_mut("properties") {
|
||||
properties.remove("gif");
|
||||
}
|
||||
let mut input_schema = Map::new();
|
||||
for key in ["properties", "required", "type", "additionalProperties"] {
|
||||
if let Some(value) = schema.remove(key) {
|
||||
input_schema.insert(key.to_string(), value);
|
||||
}
|
||||
}
|
||||
ToolSpec::Namespace(ResponsesApiNamespace {
|
||||
name: IMAGE_GEN_NAMESPACE.to_string(),
|
||||
description: default_namespace_description(IMAGE_GEN_NAMESPACE),
|
||||
tools: vec![ResponsesApiNamespaceTool::Function(ResponsesApiTool {
|
||||
name: IMAGEGEN_TOOL_NAME.to_string(),
|
||||
description: if gif_enabled {
|
||||
format!("{IMAGEGEN_DESCRIPTION}\n{IMAGEGEN_GIF_DESCRIPTION}")
|
||||
} else {
|
||||
IMAGEGEN_DESCRIPTION.to_string()
|
||||
},
|
||||
strict: false,
|
||||
parameters: parse_tool_input_schema(&Value::Object(input_schema))
|
||||
.unwrap_or_else(|err| panic!("imagegen input schema should parse: {err}")),
|
||||
output_schema: Some(
|
||||
serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"image_url": { "type": "string" },
|
||||
"output_hint": { "type": "string" }
|
||||
},
|
||||
"required": ["image_url"],
|
||||
"additionalProperties": false
|
||||
})
|
||||
.into(),
|
||||
),
|
||||
defer_loading: None,
|
||||
})],
|
||||
})
|
||||
}
|
||||
|
||||
struct GeneratedImageOutput {
|
||||
result: String,
|
||||
output_hint: Option<String>,
|
||||
}
|
||||
|
||||
impl ToolOutput for GeneratedImageOutput {
|
||||
/// Avoids copying image bytes into tool-call telemetry.
|
||||
fn log_output(&self) -> String {
|
||||
"[generated image]".to_string()
|
||||
}
|
||||
|
||||
/// Reports a completed images request as successful tool execution.
|
||||
fn success_for_logging(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Returns the object consumed by the code-mode `generatedImage()` helper.
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> Value {
|
||||
let mut result = Map::from_iter([(
|
||||
"image_url".to_string(),
|
||||
Value::String(format!(
|
||||
"data:{};base64,{}",
|
||||
GeneratedImageFormat::from_base64(&self.result).mime_type(),
|
||||
self.result
|
||||
)),
|
||||
)]);
|
||||
if let Some(output_hint) = &self.output_hint {
|
||||
result.insert(
|
||||
"output_hint".to_string(),
|
||||
Value::String(output_hint.clone()),
|
||||
);
|
||||
}
|
||||
Value::Object(result)
|
||||
}
|
||||
|
||||
/// Returns generated bytes and persisted-artifact context for model follow-up.
|
||||
fn to_response_item(&self, call_id: &str, _payload: &ToolPayload) -> ResponseInputItem {
|
||||
let mut content = vec![FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: format!(
|
||||
"data:{};base64,{}",
|
||||
GeneratedImageFormat::from_base64(&self.result).mime_type(),
|
||||
self.result
|
||||
),
|
||||
},
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
}];
|
||||
if let Some(output_hint) = &self.output_hint {
|
||||
content.push(FunctionCallOutputContentItem::InputText {
|
||||
text: output_hint.clone(),
|
||||
});
|
||||
}
|
||||
ResponseInputItem::FunctionCallOutput {
|
||||
call_id: call_id.to_string(),
|
||||
output: FunctionCallOutputPayload {
|
||||
body: FunctionCallOutputBody::ContentItems(content),
|
||||
success: Some(true),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests.rs"]
|
||||
mod tests;
|
||||
@@ -17,7 +17,6 @@ anyhow = { workspace = true }
|
||||
codex-core = { workspace = true }
|
||||
codex-core-plugins = { workspace = true }
|
||||
codex-config = { workspace = true }
|
||||
codex-connectors = { workspace = true }
|
||||
codex-exec-server = { workspace = true }
|
||||
codex-extension-api = { workspace = true }
|
||||
codex-features = { workspace = true }
|
||||
|
||||
@@ -1,249 +0,0 @@
|
||||
//! Refreshes cloud plugins each turn and after auth changes.
|
||||
|
||||
use crate::PluginListQuery;
|
||||
use crate::PluginsThreadState;
|
||||
use crate::plugin_contributor::PluginContributor;
|
||||
use codex_core::config::Config;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_extension_api::CatalogRefreshBackoff;
|
||||
use codex_extension_api::CatalogRefreshInput;
|
||||
use codex_extension_api::ConfigContributor;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::McpServerContribution;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_extension_api::TurnLifecycleContributor;
|
||||
use codex_extension_api::TurnStartInput;
|
||||
use codex_extension_api::TurnStartPhase;
|
||||
use codex_features::Feature;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_mcp::McpResourceClientAuthKey;
|
||||
use std::collections::HashSet;
|
||||
|
||||
const MAX_PROJECTED_CLOUD_PLUGINS: usize = 100;
|
||||
pub(crate) const MAX_PLUGIN_DISPLAY_NAME_CHARS: usize = 64;
|
||||
pub(crate) const MAX_CONNECTOR_IDS_PER_PLUGIN: usize = 64;
|
||||
|
||||
/// Auth scope of the latest catalog accepted for this turn.
|
||||
struct LatestCloudPluginAuth(Option<McpResourceClientAuthKey>);
|
||||
|
||||
impl PluginContributor {
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "cloud discovery must remain serialized through fetching and catalog publication"
|
||||
)]
|
||||
async fn refresh_cloud_catalog(&self, input: CatalogRefreshInput<'_>) -> bool {
|
||||
let Some(provider) = &self.providers.cloud else {
|
||||
return false;
|
||||
};
|
||||
let Some(state) = input.thread_store.get::<PluginsThreadState>() else {
|
||||
return false;
|
||||
};
|
||||
// Wait without holding catalog state or the MCP runtime permit, then recheck the cache.
|
||||
let (mut refresh_succeeded, waited) = match state.cloud_refresh_lock.try_lock() {
|
||||
Ok(guard) => (guard, false),
|
||||
Err(_) => (state.cloud_refresh_lock.lock().await, true),
|
||||
};
|
||||
let query = PluginListQuery {
|
||||
thread_id: input.thread_store.level_id().to_string(),
|
||||
turn_id: input.turn_id.to_string(),
|
||||
mcp_resources: input.session_store.get::<McpResourceClient>(),
|
||||
snapshots: Vec::new(),
|
||||
};
|
||||
let (auth_cache_key, resource_cache_key, catalog_cleared) =
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
if !state.plugins_enabled {
|
||||
return false;
|
||||
}
|
||||
let auth = query
|
||||
.mcp_resources
|
||||
.as_ref()
|
||||
.map(|client| client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME));
|
||||
let resource_cache_key = query
|
||||
.mcp_resources
|
||||
.as_ref()
|
||||
.and_then(|client| client.server_cache_key(CODEX_APPS_MCP_SERVER_NAME));
|
||||
if ((waited && *refresh_succeeded)
|
||||
|| input
|
||||
.turn_store
|
||||
.get::<LatestCloudPluginAuth>()
|
||||
.is_some_and(|previous| previous.0 == auth))
|
||||
&& state
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.is_some_and(|generation| generation.auth_cache_key == auth)
|
||||
&& state.cloud_catalog().is_some()
|
||||
{
|
||||
input.turn_store.insert(LatestCloudPluginAuth(auth));
|
||||
return false;
|
||||
}
|
||||
if state.cloud_retry.as_ref().is_some_and(|retry| {
|
||||
retry.is_pending(auth.as_ref(), resource_cache_key.as_ref())
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
// Waiting callers must not reuse a failed or cancelled refresh.
|
||||
*refresh_succeeded = false;
|
||||
input.turn_store.remove::<LatestCloudPluginAuth>();
|
||||
let previous_catalog_auth = state
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.filter(|generation| generation.catalog.is_some())
|
||||
.map(|generation| generation.auth_cache_key.clone());
|
||||
let auth_cache_key =
|
||||
state.prepare_cloud_generation(query.mcp_resources.as_deref().cloned());
|
||||
let catalog_cleared =
|
||||
previous_catalog_auth.is_some_and(|previous| previous != auth_cache_key);
|
||||
(auth_cache_key, resource_cache_key, catalog_cleared)
|
||||
};
|
||||
let result = provider.list(query).await;
|
||||
let mut state = state.contributor_state();
|
||||
let catalog_published = match result {
|
||||
Ok(catalog) => {
|
||||
let published = state.publish_cloud_catalog(auth_cache_key.as_ref(), catalog);
|
||||
if published {
|
||||
state.cloud_retry = None;
|
||||
input
|
||||
.turn_store
|
||||
.insert(LatestCloudPluginAuth(auth_cache_key));
|
||||
*refresh_succeeded = true;
|
||||
} else {
|
||||
tracing::debug!("cloud plugin discovery finished after auth changed");
|
||||
}
|
||||
published
|
||||
}
|
||||
Err(_) => {
|
||||
if state.cloud_generation.as_ref().is_some_and(|generation| {
|
||||
generation.auth_cache_key == auth_cache_key && generation.is_auth_current()
|
||||
}) {
|
||||
state.cloud_retry = Some(CatalogRefreshBackoff::after_failure(
|
||||
auth_cache_key,
|
||||
resource_cache_key,
|
||||
state.cloud_retry.as_ref(),
|
||||
));
|
||||
}
|
||||
tracing::warn!("cloud plugin discovery failed");
|
||||
false
|
||||
}
|
||||
};
|
||||
catalog_cleared || catalog_published
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadLifecycleContributor<Config> for PluginContributor {
|
||||
fn on_thread_start<'a>(
|
||||
&'a self,
|
||||
input: ThreadStartInput<'a, Config>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let state = input.thread_store.get_or_init(PluginsThreadState::default);
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
state.plugins_enabled = input.config.features.enabled(Feature::Plugins);
|
||||
state.extension_metrics = input.extension_metrics;
|
||||
}
|
||||
if let Some(resources) = &input.mcp_resource_client {
|
||||
input.session_store.insert(resources.as_ref().clone());
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigContributor<Config> for PluginContributor {
|
||||
fn on_config_changed(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
_previous_config: &Config,
|
||||
new_config: &Config,
|
||||
) {
|
||||
let plugins_enabled = new_config.features.enabled(Feature::Plugins);
|
||||
let state = thread_store.get_or_init(PluginsThreadState::default);
|
||||
let mut state = state.contributor_state();
|
||||
if state.plugins_enabled != plugins_enabled {
|
||||
state.cloud_retry = None;
|
||||
}
|
||||
state.plugins_enabled = plugins_enabled;
|
||||
if self.providers.cloud.is_none() || !plugins_enabled {
|
||||
state.cloud_generation = None;
|
||||
state.cloud_retry = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TurnLifecycleContributor for PluginContributor {
|
||||
fn turn_start_phase(&self, thread_store: &ExtensionData) -> TurnStartPhase {
|
||||
if self.providers.cloud.is_some()
|
||||
&& thread_store
|
||||
.get::<PluginsThreadState>()
|
||||
.is_some_and(|state| state.contributor_state().plugins_enabled)
|
||||
{
|
||||
TurnStartPhase::RegularTaskStart
|
||||
} else {
|
||||
TurnStartPhase::BeforeTaskRegistration
|
||||
}
|
||||
}
|
||||
|
||||
fn requires_mcp_runtime(&self, thread_store: &ExtensionData) -> bool {
|
||||
self.turn_start_phase(thread_store) == TurnStartPhase::RegularTaskStart
|
||||
}
|
||||
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
input.turn_store.remove::<LatestCloudPluginAuth>();
|
||||
self.refresh_cloud_catalog(CatalogRefreshInput {
|
||||
turn_id: input.turn_id,
|
||||
session_store: input.session_store,
|
||||
thread_store: input.thread_store,
|
||||
turn_store: input.turn_store,
|
||||
})
|
||||
.await;
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh_catalog_for_step<'a>(
|
||||
&'a self,
|
||||
input: CatalogRefreshInput<'a>,
|
||||
) -> ExtensionFuture<'a, bool> {
|
||||
Box::pin(self.refresh_cloud_catalog(input))
|
||||
}
|
||||
}
|
||||
|
||||
/// Cloud packages contribute Apps attribution, never executor MCP declarations.
|
||||
pub(crate) fn hosted_plugin_connectors(catalog: &PluginCatalog) -> Vec<McpServerContribution> {
|
||||
catalog
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|entry| entry.enabled)
|
||||
.filter_map(|entry| {
|
||||
let PluginIdentity::Remote { remote_plugin_id } = &entry.id else {
|
||||
return None;
|
||||
};
|
||||
let mut seen_connector_ids = HashSet::new();
|
||||
Some(McpServerContribution::HostedPluginConnectors {
|
||||
plugin_id: remote_plugin_id.clone(),
|
||||
plugin_display_name: entry
|
||||
.display_name
|
||||
.chars()
|
||||
.take(MAX_PLUGIN_DISPLAY_NAME_CHARS)
|
||||
.collect(),
|
||||
connector_ids: entry
|
||||
.connector_ids
|
||||
.iter()
|
||||
.filter(|connector_id| seen_connector_ids.insert((*connector_id).clone()))
|
||||
.take(MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.cloned()
|
||||
.collect(),
|
||||
})
|
||||
})
|
||||
.take(MAX_PROJECTED_CLOUD_PLUGINS)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "cloud_plugin_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,406 +0,0 @@
|
||||
//! Tests per-turn cloud plugin discovery, auth recovery, tool calls, and plugin policy.
|
||||
|
||||
use super::*;
|
||||
use crate::PluginProvider;
|
||||
use crate::PluginProviderError;
|
||||
use crate::PluginProviderFuture;
|
||||
use crate::PluginProviders;
|
||||
use crate::PluginsThreadState;
|
||||
use crate::install_plugin_providers;
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginCatalogEntry;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::McpServerContributionContext;
|
||||
use codex_extension_api::McpServerContributor;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_protocol::config_types::CollaborationMode;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::config_types::Settings;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
#[tokio::test]
|
||||
async fn cloud_discovery_selects_regular_task_phase() {
|
||||
struct ExistingContributor;
|
||||
impl TurnLifecycleContributor for ExistingContributor {}
|
||||
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
builder.turn_lifecycle_contributor(Arc::new(ExistingContributor));
|
||||
let executor = Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
)));
|
||||
install_plugin_providers(&mut builder, PluginProviders::new(executor.clone()));
|
||||
install_plugin_providers(
|
||||
&mut builder,
|
||||
PluginProviders::new(executor).with_cloud_provider(Arc::new(CloudProvider::default())),
|
||||
);
|
||||
let registry = builder.build();
|
||||
let thread = ExtensionData::new("thread");
|
||||
for plugins_enabled in [false, true] {
|
||||
thread
|
||||
.get_or_init(PluginsThreadState::default)
|
||||
.contributor_state()
|
||||
.plugins_enabled = plugins_enabled;
|
||||
let dependencies = registry
|
||||
.turn_lifecycle_contributors()
|
||||
.iter()
|
||||
.map(|contributor| contributor.requires_mcp_runtime(&thread))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(dependencies, vec![false, false, plugins_enabled]);
|
||||
let phases = registry
|
||||
.turn_lifecycle_contributors()
|
||||
.iter()
|
||||
.map(|contributor| contributor.turn_start_phase(&thread))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
phases,
|
||||
vec![
|
||||
TurnStartPhase::BeforeTaskRegistration,
|
||||
TurnStartPhase::BeforeTaskRegistration,
|
||||
if plugins_enabled {
|
||||
TurnStartPhase::RegularTaskStart
|
||||
} else {
|
||||
TurnStartPhase::BeforeTaskRegistration
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabling_plugins_clears_cloud_catalog_and_skips_discovery() -> anyhow::Result<()> {
|
||||
let config_home = tempfile::tempdir()?;
|
||||
let mut config = codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(config_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(config_home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
let mode = CollaborationMode {
|
||||
mode: ModeKind::Default,
|
||||
settings: Settings {
|
||||
model: "test".to_string(),
|
||||
reasoning_effort: None,
|
||||
developer_instructions: None,
|
||||
},
|
||||
};
|
||||
let provider = Arc::new(CloudProvider::default());
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
let providers = PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
))))
|
||||
.with_cloud_provider(provider.clone());
|
||||
install_plugin_providers(&mut builder, providers);
|
||||
let registry = builder.build();
|
||||
let session = ExtensionData::new("session");
|
||||
let thread = ExtensionData::new("thread");
|
||||
let thread_init = codex_extension_api::ExtensionDataInit::default();
|
||||
for (turn_id, plugins_enabled, reply) in [
|
||||
("off", false, Ok(cloud_catalog())),
|
||||
("on", true, Ok(cloud_catalog())),
|
||||
("plugins-off", false, Ok(cloud_catalog())),
|
||||
(
|
||||
"re-enabled-failed",
|
||||
true,
|
||||
Err("discovery unavailable".to_string()),
|
||||
),
|
||||
("failed-plugins-off", false, Ok(cloud_catalog())),
|
||||
("re-enabled", true, Ok(cloud_catalog())),
|
||||
] {
|
||||
let expected_catalog = if plugins_enabled {
|
||||
reply.clone().ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let previous_discoveries = provider.calls.load(Ordering::SeqCst);
|
||||
provider.set_reply(reply);
|
||||
let previous = config.clone();
|
||||
config
|
||||
.features
|
||||
.set_enabled(Feature::Plugins, plugins_enabled)?;
|
||||
for contributor in registry.config_contributors() {
|
||||
contributor.on_config_changed(&session, &thread, &previous, &config);
|
||||
}
|
||||
if !plugins_enabled && let Some(state) = thread.get::<PluginsThreadState>() {
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
}
|
||||
for contributor in registry.turn_lifecycle_contributors() {
|
||||
contributor
|
||||
.on_turn_start(TurnStartInput {
|
||||
turn_id,
|
||||
collaboration_mode: &mode,
|
||||
token_usage_at_turn_start: None,
|
||||
session_store: &session,
|
||||
thread_store: &thread,
|
||||
turn_store: &ExtensionData::new(turn_id),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
registry.mcp_server_contributors()[0]
|
||||
.contribute(codex_extension_api::McpServerContributionContext::for_step(
|
||||
&config,
|
||||
&thread_init,
|
||||
&thread,
|
||||
"test",
|
||||
&[],
|
||||
/*executor_capability_discovery*/ None,
|
||||
/*executor_capability_discovery_v2*/ None,
|
||||
))
|
||||
.await;
|
||||
if let Some(state) = thread.get::<PluginsThreadState>() {
|
||||
assert_eq!(state.cloud_catalog(), expected_catalog, "turn {turn_id}");
|
||||
}
|
||||
assert_eq!(
|
||||
provider.calls.load(Ordering::SeqCst),
|
||||
previous_discoveries + usize::from(plugins_enabled),
|
||||
"turn {turn_id}",
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_change_clears_hosted_plugins_before_waiting_for_executor() -> anyhow::Result<()> {
|
||||
struct UnreadyExecutor;
|
||||
impl codex_exec_server::NoiseRendezvousConnectProvider for UnreadyExecutor {
|
||||
fn connect_bundle(
|
||||
&self,
|
||||
_: codex_exec_server::NoiseChannelPublicKey,
|
||||
) -> futures::future::BoxFuture<
|
||||
'_,
|
||||
Result<
|
||||
codex_exec_server::NoiseRendezvousConnectBundle,
|
||||
codex_exec_server::ExecServerError,
|
||||
>,
|
||||
> {
|
||||
Box::pin(futures::future::pending())
|
||||
}
|
||||
}
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let mut config = codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.fallback_cwd(Some(home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
config.features.enable(Feature::Plugins)?;
|
||||
let manager = Arc::new(EnvironmentManager::default_for_tests());
|
||||
manager
|
||||
.materialize_pending_noise_environment("unready".to_string(), Arc::new(UnreadyExecutor))?;
|
||||
let contributor = PluginContributor {
|
||||
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(manager)))
|
||||
.with_cloud_provider(Arc::new(CloudProvider::default())),
|
||||
};
|
||||
let thread = ExtensionData::new("thread");
|
||||
let state = thread.get_or_init(PluginsThreadState::default);
|
||||
let old_auth = state
|
||||
.contributor_state()
|
||||
.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
assert!(
|
||||
state
|
||||
.contributor_state()
|
||||
.publish_cloud_catalog(old_auth.as_ref(), cloud_catalog())
|
||||
);
|
||||
let roots = [SelectedCapabilityRoot {
|
||||
id: "plugin".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: "unready".to_string(),
|
||||
path: PathUri::parse("file:///plugins/demo")?,
|
||||
},
|
||||
}];
|
||||
let init = codex_extension_api::ExtensionDataInit::default();
|
||||
let context = McpServerContributionContext::for_step(
|
||||
&config, &init, &thread, "test", &roots, /*executor_capability_discovery*/ None,
|
||||
/*executor_capability_discovery_v2*/ None,
|
||||
)
|
||||
.with_auth_changed(/*auth_changed*/ true);
|
||||
let mut loading = std::pin::pin!(contributor.selected_plugins(context, &config.plugins));
|
||||
assert!(futures::poll!(&mut loading).is_pending());
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn cloud_refresh_serializes_waiters_and_retries() {
|
||||
let new_catalog = PluginCatalog::default();
|
||||
for (reply, cancelled) in [
|
||||
(Ok(cloud_catalog()), false),
|
||||
(Err("discovery failed".to_string()), false),
|
||||
(Ok(cloud_catalog()), true),
|
||||
] {
|
||||
let succeeded = reply.is_ok() && !cancelled;
|
||||
let expected_catalog = if succeeded {
|
||||
cloud_catalog()
|
||||
} else {
|
||||
new_catalog.clone()
|
||||
};
|
||||
let provider = Arc::new(CloudProvider::default());
|
||||
provider.set_reply(reply);
|
||||
let contributor = PluginContributor {
|
||||
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
))))
|
||||
.with_cloud_provider(provider.clone()),
|
||||
};
|
||||
let session = ExtensionData::new("session");
|
||||
let thread = ExtensionData::new("thread");
|
||||
let turn = ExtensionData::new("turn");
|
||||
let prewarm_turn = ExtensionData::new("prewarm");
|
||||
let input = CatalogRefreshInput {
|
||||
turn_id: "turn",
|
||||
session_store: &session,
|
||||
thread_store: &thread,
|
||||
turn_store: &turn,
|
||||
};
|
||||
let state = thread.get_or_init(PluginsThreadState::default);
|
||||
state.contributor_state().plugins_enabled = true;
|
||||
|
||||
// A delayed prewarm waits without superseding the real turn's request.
|
||||
provider.pause_discovery.store(true, Ordering::SeqCst);
|
||||
let mut turn_start = contributor.refresh_catalog_for_step(input);
|
||||
assert!(futures::poll!(&mut turn_start).is_pending());
|
||||
let prewarm_input = CatalogRefreshInput {
|
||||
turn_id: "prewarm",
|
||||
turn_store: &prewarm_turn,
|
||||
..input
|
||||
};
|
||||
let mut prewarm = contributor.refresh_catalog_for_step(prewarm_input);
|
||||
assert!(futures::poll!(&mut prewarm).is_pending());
|
||||
let mut cancelled_waiter = contributor.refresh_catalog_for_step(prewarm_input);
|
||||
assert!(futures::poll!(&mut cancelled_waiter).is_pending());
|
||||
drop(cancelled_waiter);
|
||||
assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
|
||||
|
||||
provider.set_reply(Ok(new_catalog.clone()));
|
||||
if cancelled {
|
||||
drop(turn_start);
|
||||
} else {
|
||||
provider.resume_discovery.notify_one();
|
||||
assert_eq!(turn_start.await, succeeded);
|
||||
}
|
||||
// Waiting turns share failure cooldowns; cancellation still allows immediate retry.
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(5), prewarm)
|
||||
.await
|
||||
.expect("waiting discovery should complete after its predecessor stops"),
|
||||
cancelled,
|
||||
);
|
||||
if !succeeded && !cancelled {
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
assert!(contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
}
|
||||
assert_eq!(state.cloud_catalog(), Some(expected_catalog.clone()));
|
||||
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
assert_eq!(
|
||||
provider.calls.load(Ordering::SeqCst),
|
||||
1 + usize::from(!succeeded),
|
||||
);
|
||||
|
||||
// Retained catalogs do not need MCP rebuilding after failed retries.
|
||||
prewarm_turn.remove::<LatestCloudPluginAuth>();
|
||||
provider.set_reply(Err("discovery failed".to_string()));
|
||||
let previous_calls = provider.calls.load(Ordering::SeqCst);
|
||||
for _ in 0..2 {
|
||||
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
assert_eq!(state.cloud_catalog(), Some(expected_catalog.clone()));
|
||||
}
|
||||
assert_eq!(provider.calls.load(Ordering::SeqCst), previous_calls + 1);
|
||||
|
||||
// Clearing an old auth scope still requires rebuilding, even on failure.
|
||||
session.insert(McpResourceClient::new(Arc::new(
|
||||
codex_mcp::McpRuntime::empty(/*prefix_mcp_tool_names*/ false),
|
||||
)));
|
||||
assert!(contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
provider.set_reply(Ok(new_catalog.clone()));
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
assert!(contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
}
|
||||
}
|
||||
|
||||
struct CloudProvider {
|
||||
reply: Mutex<Result<PluginCatalog, String>>,
|
||||
calls: AtomicUsize,
|
||||
resources: Mutex<Option<Arc<McpResourceClient>>>,
|
||||
pause_discovery: AtomicBool,
|
||||
discovery_started: Notify,
|
||||
resume_discovery: Notify,
|
||||
}
|
||||
|
||||
impl Default for CloudProvider {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
reply: Mutex::new(Ok(PluginCatalog::default())),
|
||||
calls: AtomicUsize::new(0),
|
||||
resources: Mutex::new(None),
|
||||
pause_discovery: AtomicBool::new(false),
|
||||
discovery_started: Notify::new(),
|
||||
resume_discovery: Notify::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CloudProvider {
|
||||
fn set_reply(&self, reply: Result<PluginCatalog, String>) {
|
||||
*self
|
||||
.reply
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = reply;
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginProvider for CloudProvider {
|
||||
fn list(&self, query: PluginListQuery) -> PluginProviderFuture<'_, PluginCatalog> {
|
||||
*self
|
||||
.resources
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = query.mcp_resources;
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
let reply = self
|
||||
.reply
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
let pause = self.pause_discovery.swap(false, Ordering::SeqCst);
|
||||
Box::pin(async move {
|
||||
if pause {
|
||||
self.discovery_started.notify_one();
|
||||
self.resume_discovery.notified().await;
|
||||
}
|
||||
reply.map_err(PluginProviderError::Message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn cloud_catalog() -> PluginCatalog {
|
||||
PluginCatalog {
|
||||
entries: vec![PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: "plugin_remote".to_string(),
|
||||
},
|
||||
display_name: "Cloud Demo".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
mcp_servers: Default::default(),
|
||||
connector_ids: vec!["calendar".to_string()],
|
||||
locations: vec![codex_core_plugins::PluginSourceLocation::Cloud {
|
||||
resource_uri: "plugin://plugin_remote".to_string(),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -1,652 +0,0 @@
|
||||
//! Exercises independent event connections through the real MCP HTTP transport.
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::convert::Infallible;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use axum::Json;
|
||||
use axum::Router;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::response::sse::Event;
|
||||
use axum::response::sse::Sse;
|
||||
use axum::routing::post;
|
||||
use codex_config::McpServerTransportConfig;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::plugins_manager_for_config;
|
||||
use codex_exec_server_test_support::environment_manager_without_environments;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::CodexAppsResourceListParams;
|
||||
use codex_mcp::EffectiveMcpServer;
|
||||
use codex_mcp::McpEventNotification;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_mcp::McpRuntime;
|
||||
use codex_mcp::McpRuntimeContext;
|
||||
use codex_mcp::McpRuntimeInput;
|
||||
use codex_mcp::McpServerRegistration;
|
||||
use codex_mcp::McpStartupPolicy;
|
||||
use codex_mcp::ResolvedMcpCatalog;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(super) const WAIT: Duration = Duration::from_secs(/*secs*/ 5);
|
||||
|
||||
pub(super) struct TestStream {
|
||||
pub request: Value,
|
||||
pub headers: HeaderMap,
|
||||
pub notifications: mpsc::UnboundedSender<Value>,
|
||||
}
|
||||
|
||||
impl TestStream {
|
||||
pub fn notify(&self, method: &str) -> McpEventNotification {
|
||||
let params = json!({
|
||||
"data": {"text": "hello"},
|
||||
"_meta": {"io.modelcontextprotocol/subscriptionId": self.request["id"], "connector": "test"},
|
||||
});
|
||||
self.notifications
|
||||
.send(json!({"jsonrpc": "2.0", "method": method, "params": params}))
|
||||
.unwrap();
|
||||
McpEventNotification {
|
||||
method: method.into(),
|
||||
params: Some(params),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct BlockedTools {
|
||||
started: Notify,
|
||||
release: Notify,
|
||||
handshakes: AtomicUsize,
|
||||
inventories: AtomicUsize,
|
||||
inventory_returned: AtomicBool,
|
||||
inventory_error: Option<&'static str>,
|
||||
stalled_initialize_timeout: Option<Duration>,
|
||||
modern_with_sharing: bool,
|
||||
held_mime_type: Option<&'static str>,
|
||||
session_id: Option<&'static str>,
|
||||
resource_started: Notify,
|
||||
release_resource: Notify,
|
||||
}
|
||||
|
||||
pub(super) struct Fixture {
|
||||
_home: tempfile::TempDir,
|
||||
_server: tokio_util::task::AbortOnDropHandle<std::io::Result<()>>,
|
||||
pub runtime: Arc<McpRuntime>,
|
||||
pub runtime_input: McpRuntimeInput,
|
||||
pub auth: Arc<AuthManager>,
|
||||
pub opened: mpsc::UnboundedReceiver<TestStream>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
pub async fn new() -> Result<Self> {
|
||||
let fixture = Self::start(/*blocked_tools*/ None, /*early_resources*/ false).await?;
|
||||
assert!(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT)
|
||||
.await
|
||||
);
|
||||
Ok(fixture)
|
||||
}
|
||||
|
||||
async fn start(
|
||||
blocked_tools: Option<Arc<BlockedTools>>,
|
||||
early_resources: bool,
|
||||
) -> Result<Self> {
|
||||
let (opened_tx, opened) = mpsc::unbounded_channel();
|
||||
let modern_with_sharing = blocked_tools
|
||||
.as_ref()
|
||||
.is_some_and(|blocked| blocked.modern_with_sharing);
|
||||
let stalled_initialize_timeout = blocked_tools
|
||||
.as_ref()
|
||||
.and_then(|blocked| blocked.stalled_initialize_timeout);
|
||||
let router = Router::new().fallback(post(
|
||||
move |headers: HeaderMap, Json(request): Json<Value>| {
|
||||
let opened = opened_tx.clone();
|
||||
let blocked_tools = blocked_tools.clone();
|
||||
async move {
|
||||
let method = request["method"].as_str();
|
||||
let session_id = blocked_tools.as_ref().and_then(|blocked| blocked.session_id);
|
||||
if let Some(session_id) = session_id && method != Some("initialize") {
|
||||
assert_eq!(headers["mcp-session-id"], session_id);
|
||||
}
|
||||
let mut result = match method {
|
||||
Some("server/discover") if modern_with_sharing => {
|
||||
blocked_tools.as_ref().unwrap().handshakes.fetch_add(1, Ordering::SeqCst);
|
||||
json!({
|
||||
"supportedVersions": ["2026-07-28"],
|
||||
"capabilities": {"tools": {}, "resources": {}},
|
||||
"_meta": {"io.modelcontextprotocol/serverInfo": {"name": "test", "version": "1"}},
|
||||
"ttlMs": 0, "cacheScope": "private",
|
||||
})
|
||||
}
|
||||
Some("initialize") if !modern_with_sharing => {
|
||||
if let Some(blocked) = &blocked_tools {
|
||||
blocked.handshakes.fetch_add(1, Ordering::SeqCst);
|
||||
if stalled_initialize_timeout.is_some() {
|
||||
blocked.started.notify_one();
|
||||
blocked.release.notified().await;
|
||||
}
|
||||
}
|
||||
json!({
|
||||
"protocolVersion": "2025-06-18", "capabilities": {"tools": {}, "resources": {}},
|
||||
"serverInfo": {"name": "test", "version": "1"},
|
||||
})
|
||||
}
|
||||
Some("tools/list") => {
|
||||
if let Some(blocked) = &blocked_tools {
|
||||
blocked.inventories.fetch_add(1, Ordering::SeqCst);
|
||||
blocked.started.notify_one();
|
||||
blocked.release.notified().await;
|
||||
blocked.inventory_returned.store(true, Ordering::SeqCst);
|
||||
if let Some(message) = blocked.inventory_error {
|
||||
return Json(json!({
|
||||
"jsonrpc": "2.0", "id": request["id"],
|
||||
"error": {"code": -32603, "message": message}
|
||||
})).into_response();
|
||||
}
|
||||
}
|
||||
json!({"tools": []})
|
||||
}
|
||||
Some("resources/list") => {
|
||||
if let Some(blocked) = &blocked_tools {
|
||||
assert_eq!(blocked.inventory_returned.load(Ordering::SeqCst), !early_resources,
|
||||
"unexpected catalog request ordering relative to the initial inventory");
|
||||
}
|
||||
let mime_type = request["params"]["mimeType"].as_str().unwrap();
|
||||
let cursor = match mime_type {
|
||||
"mcp/plugin" => "plugin-page-two",
|
||||
"mcp/skill" => "skill-page-two",
|
||||
other => panic!("unexpected resource type: {other}"),
|
||||
};
|
||||
if let Some(blocked) = &blocked_tools && blocked.held_mime_type == Some(mime_type) {
|
||||
blocked.resource_started.notify_one();
|
||||
blocked.release_resource.notified().await;
|
||||
}
|
||||
json!({"resources": [], "nextCursor": cursor})
|
||||
}
|
||||
Some("notifications/initialized") => {
|
||||
return StatusCode::ACCEPTED.into_response();
|
||||
}
|
||||
Some("events/stream") => {
|
||||
let (notifications, receive) = mpsc::unbounded_channel();
|
||||
opened
|
||||
.send(TestStream {
|
||||
request,
|
||||
headers,
|
||||
notifications,
|
||||
})
|
||||
.unwrap();
|
||||
let events = futures::stream::unfold(receive, |mut receive| async {
|
||||
receive.recv().await.map(|value| (value, receive))
|
||||
})
|
||||
.map(|value: Value| {
|
||||
Ok::<_, Infallible>(
|
||||
Event::default().event("message").data(value.to_string()),
|
||||
)
|
||||
});
|
||||
return Sse::new(events).into_response();
|
||||
}
|
||||
method => panic!("unexpected request: {method:?}"),
|
||||
};
|
||||
if modern_with_sharing {
|
||||
result["resultType"] = "complete".into();
|
||||
}
|
||||
let response = Json(json!({"jsonrpc": "2.0", "id": request["id"], "result": result}));
|
||||
if method == Some("initialize") && let Some(session_id) = session_id {
|
||||
return ([("mcp-session-id", session_id)], response).into_response();
|
||||
}
|
||||
response.into_response()
|
||||
}
|
||||
},
|
||||
));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let url = format!("http://{}", listener.local_addr()?);
|
||||
let server = tokio::spawn(async move { axum::serve(listener, router).await });
|
||||
let home = tempfile::tempdir()?;
|
||||
let auth_value = CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.first",
|
||||
"account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing_with_home(auth_value.clone(), home.path().into());
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().into())
|
||||
.fallback_cwd(Some(home.path().into()))
|
||||
.cli_overrides(vec![
|
||||
(
|
||||
"features.apps_early_resource_discovery".into(),
|
||||
early_resources.into(),
|
||||
),
|
||||
(
|
||||
"features.mcp_connection_sharing".into(),
|
||||
modern_with_sharing.into(),
|
||||
),
|
||||
(
|
||||
"features.codex_apps_mcp_2026_07_28".into(),
|
||||
modern_with_sharing.into(),
|
||||
),
|
||||
])
|
||||
.build()
|
||||
.await?;
|
||||
let plugins = plugins_manager_for_config(&config, Arc::clone(&auth));
|
||||
let mut config = config.to_mcp_config(&plugins).await;
|
||||
let mut server_config = codex_mcp::hosted_plugin_runtime_mcp_server_config(
|
||||
&url, /*apps_mcp_product_sku*/ None, /*originator*/ None,
|
||||
);
|
||||
let McpServerTransportConfig::StreamableHttp {
|
||||
bearer_token_env_var,
|
||||
..
|
||||
} = &mut server_config.transport
|
||||
else {
|
||||
panic!("HTTP server");
|
||||
};
|
||||
*bearer_token_env_var = None;
|
||||
if let Some(timeout) = stalled_initialize_timeout {
|
||||
server_config.startup_timeout_sec = Some(timeout);
|
||||
}
|
||||
let mut catalog = ResolvedMcpCatalog::builder();
|
||||
catalog.register(McpServerRegistration::from_hosted_apps(
|
||||
"test",
|
||||
/*contribution_order*/ 0,
|
||||
server_config.clone(),
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
let config = Arc::new(config);
|
||||
let startup_cancellation_token = CancellationToken::new();
|
||||
let runtime_input = || McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::clone(&config),
|
||||
plugins_available: false,
|
||||
ready_selected_capability_roots: Vec::new(),
|
||||
mcp_servers: HashMap::from([(
|
||||
CODEX_APPS_MCP_SERVER_NAME.into(),
|
||||
EffectiveMcpServer::from_host_config(server_config.clone()),
|
||||
)]),
|
||||
submit_id: "test".into(),
|
||||
tx_event: None,
|
||||
startup_cancellation_token: startup_cancellation_token.clone(),
|
||||
runtime_context: McpRuntimeContext::new(
|
||||
Arc::new(environment_manager_without_environments()),
|
||||
home.path().into(),
|
||||
)
|
||||
.with_connection_pool(Default::default()),
|
||||
codex_apps_tools_cache: Default::default(),
|
||||
tool_catalog_cache: Default::default(),
|
||||
codex_apps_tools_cache_key: codex_mcp::codex_apps_tools_cache_key(Some(&auth_value)),
|
||||
client_mcp_extensions: Default::default(),
|
||||
auth: Some(auth_value.clone()),
|
||||
auth_manager: Some(Arc::clone(&auth)),
|
||||
elicitation_reviewer: None,
|
||||
elicitation_lifecycle: None,
|
||||
};
|
||||
let runtime = Arc::new(McpRuntime::new(runtime_input()).await);
|
||||
let runtime_input = runtime_input();
|
||||
Ok(Self {
|
||||
_home: home,
|
||||
_server: tokio_util::task::AbortOnDropHandle::new(server),
|
||||
runtime,
|
||||
runtime_input,
|
||||
auth,
|
||||
opened,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_during_initial_tools_list() -> Result<()> {
|
||||
for (early_resources, modern_with_sharing) in [(false, false), (true, false), (true, true)] {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
modern_with_sharing,
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), early_resources).await?;
|
||||
timeout(WAIT, blocked.started.notified())
|
||||
.await
|
||||
.context("initial tools/list did not start")?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
if early_resources {
|
||||
assert_eq!(
|
||||
timeout(WAIT, &mut page)
|
||||
.await
|
||||
.context("gated catalog read waited for the blocked inventory")??
|
||||
.next_cursor
|
||||
.as_deref(),
|
||||
Some("plugin-page-two")
|
||||
);
|
||||
} else {
|
||||
assert!(futures::poll!(&mut page).is_pending());
|
||||
// A read already using the early client would now fail its generation check.
|
||||
// A read waiting for startup can still fetch the page after inventory returns.
|
||||
fixture.runtime.invalidate_resource_caches();
|
||||
}
|
||||
let mut ready = Box::pin(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT),
|
||||
);
|
||||
assert!(futures::poll!(&mut ready).is_pending());
|
||||
blocked.release.notify_one();
|
||||
assert!(ready.await);
|
||||
if !early_resources {
|
||||
assert_eq!(
|
||||
timeout(WAIT, page).await??.next_cursor.as_deref(),
|
||||
Some("plugin-page-two")
|
||||
);
|
||||
}
|
||||
assert_eq!(blocked.handshakes.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(blocked.inventories.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_times_out_during_stalled_initialization() -> Result<()> {
|
||||
let startup_timeout = Duration::from_secs(/*secs*/ 1);
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
stalled_initialize_timeout: Some(startup_timeout),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
assert!(futures::poll!(&mut page).is_pending());
|
||||
timeout(WAIT, blocked.started.notified())
|
||||
.await
|
||||
.context("initialize did not reach the server")?;
|
||||
let error = timeout(WAIT, page)
|
||||
.await
|
||||
.context("reader outlived its startup deadline")?
|
||||
.unwrap_err();
|
||||
// The handshake and early borrow each enforce the configured startup timeout.
|
||||
let message = format!("{error:#}");
|
||||
assert!(message.contains("timed out"), "{message}");
|
||||
assert_eq!(blocked.inventories.load(Ordering::SeqCst), 0);
|
||||
blocked.release.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_multiplexes_catalogs_while_tools_list_is_pending() -> Result<()> {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/plugin"),
|
||||
session_id: Some("apps-session"),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let plugin_reader = reader.clone();
|
||||
let plugin = tokio::spawn(async move {
|
||||
plugin_reader
|
||||
.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
})
|
||||
.await
|
||||
});
|
||||
timeout(WAIT, blocked.resource_started.notified())
|
||||
.await
|
||||
.context("plugin request did not reach the server while tools/list was pending")?;
|
||||
let skill = timeout(
|
||||
WAIT,
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/skill".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.context("skill request queued behind the pending plugin or inventory request")??;
|
||||
assert_eq!(skill.next_cursor.as_deref(), Some("skill-page-two"));
|
||||
assert!(!plugin.is_finished());
|
||||
|
||||
blocked.release_resource.notify_one();
|
||||
let plugin = timeout(WAIT, plugin).await???;
|
||||
assert_eq!(plugin.next_cursor.as_deref(), Some("plugin-page-two"));
|
||||
|
||||
let mut ready = Box::pin(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT),
|
||||
);
|
||||
assert!(futures::poll!(&mut ready).is_pending());
|
||||
blocked.release.notify_one();
|
||||
assert!(ready.await);
|
||||
assert_eq!(blocked.handshakes.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(blocked.inventories.load(Ordering::SeqCst), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_propagates_initial_tools_list_failure() -> Result<()> {
|
||||
const INVENTORY_ERROR: &str = "initial inventory unavailable";
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/plugin"),
|
||||
inventory_error: Some(INVENTORY_ERROR),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
tokio::select! {
|
||||
result = &mut page => panic!("catalog returned before inventory failed: {result:?}"),
|
||||
result = timeout(WAIT, blocked.resource_started.notified()) => result?,
|
||||
}
|
||||
|
||||
blocked.release.notify_one();
|
||||
let error = timeout(WAIT, page)
|
||||
.await
|
||||
.context("catalog reader kept waiting after tools/list failed")?
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.starts_with("MCP startup failed:"), "{error}");
|
||||
assert!(error.contains(INVENTORY_ERROR), "{error}");
|
||||
assert!(
|
||||
!fixture
|
||||
.runtime_input
|
||||
.startup_cancellation_token
|
||||
.is_cancelled()
|
||||
);
|
||||
blocked.release_resource.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_observes_cancellation_after_inventory_finishes() -> Result<()> {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/plugin"),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
tokio::select! {
|
||||
result = &mut page => panic!("catalog returned before release: {result:?}"),
|
||||
result = timeout(WAIT, blocked.resource_started.notified()) => result?,
|
||||
}
|
||||
blocked.release.notify_one();
|
||||
assert!(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT)
|
||||
.await
|
||||
);
|
||||
assert!(futures::poll!(&mut page).is_pending());
|
||||
fixture.runtime_input.startup_cancellation_token.cancel();
|
||||
let error = timeout(WAIT, page)
|
||||
.await
|
||||
.context("catalog ignored cancellation after startup")?
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().to_lowercase().contains("cancel"));
|
||||
blocked.release_resource.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_discards_invalidated_page() -> Result<()> {
|
||||
for cancel_startup in [false, true] {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/skill"),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let page = tokio::spawn(async move {
|
||||
reader
|
||||
.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/skill".into(),
|
||||
cursor: None,
|
||||
})
|
||||
.await
|
||||
});
|
||||
timeout(WAIT, blocked.resource_started.notified()).await?;
|
||||
let expected = if cancel_startup {
|
||||
fixture.runtime.cancel_startup();
|
||||
"cancel"
|
||||
} else {
|
||||
fixture.runtime.invalidate_resource_caches();
|
||||
blocked.release_resource.notify_one();
|
||||
"changed during catalog discovery"
|
||||
};
|
||||
let error = timeout(WAIT, page).await??.unwrap_err();
|
||||
assert!(error.to_string().to_lowercase().contains(expected));
|
||||
blocked.release.notify_one();
|
||||
blocked.release_resource.notify_one();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_discards_page_after_account_switch() -> Result<()> {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/skill"),
|
||||
..Default::default()
|
||||
});
|
||||
let mut fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/skill".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
tokio::select! {
|
||||
result = &mut page => panic!("catalog returned before account switch: {result:?}"),
|
||||
result = timeout(WAIT, blocked.resource_started.notified()) => result?,
|
||||
}
|
||||
|
||||
let previous_auth = reader.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME);
|
||||
let next_auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.second",
|
||||
"second-account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
fixture
|
||||
.auth
|
||||
.set_external_auth(Arc::new(StaticAuth(next_auth.clone())))
|
||||
.await?;
|
||||
fixture.runtime_input.codex_apps_tools_cache_key =
|
||||
codex_mcp::codex_apps_tools_cache_key(Some(&next_auth));
|
||||
fixture.runtime_input.auth = Some(next_auth);
|
||||
timeout(WAIT, fixture.runtime.replace(fixture.runtime_input)).await?;
|
||||
assert!(previous_auth != reader.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME));
|
||||
blocked.release_resource.notify_one();
|
||||
let error = timeout(WAIT, page).await?.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"Apps connection changed during catalog discovery"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) struct StaticAuth(pub CodexAuth);
|
||||
|
||||
impl ExternalAuth for StaticAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
fn refresh(&self, _: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn event_connections_open_after_runtime_shutdown_with_current_auth() -> Result<()> {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
fixture.runtime.shutdown().await;
|
||||
drop(fixture.runtime);
|
||||
|
||||
fixture
|
||||
.auth
|
||||
.set_external_auth(Arc::new(StaticAuth(
|
||||
CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.refreshed",
|
||||
"account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
)))
|
||||
.await?;
|
||||
let mut stream = opener
|
||||
.open("test.event", &json!({}), /*request_meta*/ None)
|
||||
.await?;
|
||||
let remote = timeout(WAIT, fixture.opened.recv()).await?.unwrap();
|
||||
assert_eq!(
|
||||
remote.headers["authorization"],
|
||||
"Bearer header.e30.refreshed"
|
||||
);
|
||||
let expected = remote.notify("notifications/events/active");
|
||||
assert_eq!(timeout(WAIT, stream.recv()).await??, Some(expected));
|
||||
drop(stream);
|
||||
timeout(WAIT, remote.notifications.closed()).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
mod catalog_observability;
|
||||
mod cloud_plugin;
|
||||
mod plugin;
|
||||
mod plugin_contributor;
|
||||
mod plugin_contributor_state;
|
||||
mod plugin_lifecycle;
|
||||
mod plugin_providers;
|
||||
mod stream_manager;
|
||||
|
||||
pub use codex_core_plugins::PluginListQuery;
|
||||
pub use codex_core_plugins::PluginProvider;
|
||||
@@ -15,6 +14,4 @@ pub use plugin_contributor::install_plugin_providers;
|
||||
pub use plugin_contributor::install_plugins;
|
||||
pub use plugin_contributor_state::PluginsThreadState;
|
||||
pub use plugin_providers::PluginProviders;
|
||||
pub use stream_manager::McpEventStreamManager;
|
||||
pub use stream_manager::McpEventStreamUpdate;
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ use std::collections::HashMap;
|
||||
|
||||
use self::provider::PluginMcpProvider;
|
||||
use crate::PluginsThreadState;
|
||||
use crate::cloud_plugin::hosted_plugin_connectors;
|
||||
use crate::plugin_contributor::PluginContributor;
|
||||
use crate::plugin_contributor_state::CachedPluginMetadata;
|
||||
use crate::plugin_contributor_state::CachedSelectedRoot;
|
||||
@@ -133,14 +132,12 @@ impl PluginContributor {
|
||||
);
|
||||
Vec::new()
|
||||
});
|
||||
let connector_ids = Vec::new();
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } =
|
||||
&selected_root.location;
|
||||
Some(SelectedPluginContribution {
|
||||
plugin_display_name: plugin.plugin().manifest().display_name().to_string(),
|
||||
source_environment_id: environment_id.clone(),
|
||||
servers,
|
||||
connector_ids,
|
||||
})
|
||||
}
|
||||
None => None,
|
||||
@@ -174,56 +171,9 @@ impl McpServerContributor<Config> for PluginContributor {
|
||||
|
||||
fn contribute<'a>(
|
||||
&'a self,
|
||||
context: McpServerContributionContext<'a, Config>,
|
||||
_context: McpServerContributionContext<'a, Config>,
|
||||
) -> ExtensionFuture<'a, Vec<McpServerContribution>> {
|
||||
Box::pin(async move {
|
||||
let Some(thread_store) = context.thread_store() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let cloud_plugins_enabled = self.providers.cloud.is_some()
|
||||
&& context.config().features.enabled(Feature::Plugins);
|
||||
let state = thread_store.get_or_init(PluginsThreadState::default);
|
||||
if !cloud_plugins_enabled {
|
||||
state.contributor_state().cloud_generation = None;
|
||||
return Vec::new();
|
||||
}
|
||||
// Core reads hosted connectors after finishing the executor registrations.
|
||||
state
|
||||
.cloud_catalog()
|
||||
.as_ref()
|
||||
.map(hosted_plugin_connectors)
|
||||
.unwrap_or_default()
|
||||
})
|
||||
}
|
||||
|
||||
fn hosted_plugin_ids(&self, context: McpServerContributionContext<'_, Config>) -> Vec<String> {
|
||||
if self.providers.cloud.is_none() || !context.config().features.enabled(Feature::Plugins) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(state) = context
|
||||
.thread_store()
|
||||
.and_then(codex_extension_api::ExtensionData::get::<PluginsThreadState>)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
state
|
||||
.contributor_state()
|
||||
.cloud_catalog()
|
||||
.map(|catalog| {
|
||||
hosted_plugin_connectors(catalog)
|
||||
.into_iter()
|
||||
.filter_map(|contribution| {
|
||||
if let McpServerContribution::HostedPluginConnectors { plugin_id, .. } =
|
||||
contribution
|
||||
{
|
||||
Some(plugin_id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
Box::pin(async { Vec::new() })
|
||||
}
|
||||
|
||||
fn selected_plugins<'a>(
|
||||
@@ -236,10 +186,6 @@ impl McpServerContributor<Config> for PluginContributor {
|
||||
return Vec::new();
|
||||
};
|
||||
let state = thread_store.get_or_init(PluginsThreadState::default);
|
||||
if context.auth_changed() {
|
||||
// Clear the old account before executor loading can yield to other work.
|
||||
state.contributor_state().cloud_generation = None;
|
||||
}
|
||||
let selected_roots = context
|
||||
.ready_selected_capability_roots()
|
||||
.unwrap_or_default();
|
||||
@@ -248,11 +194,7 @@ impl McpServerContributor<Config> for PluginContributor {
|
||||
let merged = {
|
||||
let mut cache = state.contributor_state();
|
||||
cache.update_executor_catalog(snapshots);
|
||||
let cloud = (self.providers.cloud.is_some()
|
||||
&& context.config().features.enabled(Feature::Plugins))
|
||||
.then(|| cache.cloud_catalog())
|
||||
.flatten();
|
||||
merge_catalogs(cache.executor_catalog.as_ref(), cloud)
|
||||
merge_catalogs(cache.executor_catalog.as_ref(), /*cloud*/ None)
|
||||
};
|
||||
for warning in &merged.warnings {
|
||||
tracing::warn!(%warning, "plugin catalog merge reported a warning");
|
||||
@@ -292,7 +234,6 @@ impl McpServerContributor<Config> for PluginContributor {
|
||||
plugin_display_name: metadata.plugin_display_name,
|
||||
source_environment_id: environment_id,
|
||||
servers: metadata.servers,
|
||||
connector_ids: metadata.connector_ids,
|
||||
};
|
||||
project_metadata(
|
||||
context.config(),
|
||||
@@ -418,7 +359,6 @@ fn denied_plugin(selected_root: &SelectedCapabilityRoot) -> SelectedPlugin<'stat
|
||||
plugin_display_name: selected_root.id.clone(),
|
||||
source_environment_id: environment_id.clone(),
|
||||
servers: Vec::new(),
|
||||
connector_ids: Vec::new(),
|
||||
};
|
||||
SelectedPlugin {
|
||||
selected_root_id: selected_root.id.clone(),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use crate::cloud_plugin::MAX_CONNECTOR_IDS_PER_PLUGIN;
|
||||
use crate::cloud_plugin::MAX_PLUGIN_DISPLAY_NAME_CHARS;
|
||||
/// Bounds the plugin display name projected into MCP tool attribution.
|
||||
const MAX_PLUGIN_DISPLAY_NAME_CHARS: usize = 64;
|
||||
use crate::plugin_contributor_state::SelectedPluginMetadata;
|
||||
use codex_connectors::parse_plugin_app_config;
|
||||
use codex_core_plugins::PluginCatalogEntry;
|
||||
use codex_core_plugins::PluginSourceLocation;
|
||||
use codex_core_plugins::manifest::UriPluginManifest;
|
||||
@@ -15,7 +14,6 @@ use codex_mcp::parse_executor_plugin_mcp_config;
|
||||
use codex_plugin::manifest::PluginManifestMcpServers;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(super) fn manifest_from_discovery<'a>(
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
@@ -99,46 +97,10 @@ pub(super) fn metadata_from_discovery(
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let connector_ids = manifest
|
||||
.paths
|
||||
.apps
|
||||
.as_ref()
|
||||
.and_then(|path| {
|
||||
plugin_files
|
||||
.apps_config
|
||||
.as_ref()
|
||||
.filter(|file| file.path == *path)
|
||||
.or_else(|| {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
path = %path,
|
||||
"exec-server capability bundle omitted declared connector config"
|
||||
);
|
||||
None
|
||||
})
|
||||
})
|
||||
.and_then(|file| match parse_plugin_app_config(&file.contents) {
|
||||
Ok(declarations) => Some(declarations),
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
path = %file.path,
|
||||
%error,
|
||||
"failed to parse exec-server-discovered connector config"
|
||||
);
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|declaration| declaration.connector_id.0)
|
||||
.collect();
|
||||
|
||||
SelectedPluginContribution {
|
||||
plugin_display_name: manifest.display_name().to_string(),
|
||||
source_environment_id: environment_id.clone(),
|
||||
servers,
|
||||
connector_ids,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,14 +112,6 @@ pub(super) fn v2_metadata_from_catalog(
|
||||
.chars()
|
||||
.take(MAX_PLUGIN_DISPLAY_NAME_CHARS)
|
||||
.collect();
|
||||
let mut seen_connector_ids = HashSet::new();
|
||||
let connector_ids: Vec<String> = entry
|
||||
.connector_ids
|
||||
.iter()
|
||||
.filter(|id| seen_connector_ids.insert(id.as_str()))
|
||||
.take(MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.cloned()
|
||||
.collect();
|
||||
let installations = entry
|
||||
.locations
|
||||
.iter()
|
||||
@@ -186,24 +140,9 @@ pub(super) fn v2_metadata_from_catalog(
|
||||
let metadata = SelectedPluginMetadata {
|
||||
plugin_display_name: plugin_display_name.clone(),
|
||||
servers,
|
||||
connector_ids: connector_ids.clone(),
|
||||
};
|
||||
projections.push((root_id, metadata));
|
||||
}
|
||||
if entry
|
||||
.locations
|
||||
.iter()
|
||||
.any(|location| matches!(location, PluginSourceLocation::Cloud { .. }))
|
||||
{
|
||||
projections.push((
|
||||
format!("cloud:{}", entry.id.as_str()),
|
||||
SelectedPluginMetadata {
|
||||
plugin_display_name,
|
||||
servers: Vec::new(),
|
||||
connector_ids,
|
||||
},
|
||||
));
|
||||
}
|
||||
projections
|
||||
}
|
||||
|
||||
|
||||
@@ -29,19 +29,14 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command":"node","args":["server.js"],"cwd":"mcp"}),
|
||||
)]),
|
||||
connector_ids: vec!["connector_example".to_string()],
|
||||
locations: vec![PluginSourceLocation::Cloud {
|
||||
resource_uri: "plugin://plugin_example".to_string(),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
};
|
||||
// Cloud locations no longer project hosted metadata.
|
||||
let projections = v2_metadata_from_catalog(&entry);
|
||||
let [(root_id, metadata)] = projections.as_slice() else {
|
||||
panic!("one cloud projection expected");
|
||||
};
|
||||
assert_eq!(root_id, "cloud:plugin_example");
|
||||
assert!(metadata.servers.is_empty());
|
||||
assert_eq!(metadata.connector_ids, vec!["connector_example"]);
|
||||
assert!(projections.is_empty());
|
||||
|
||||
// Attribution keeps the installation key; server configs distinguish the executors.
|
||||
let installations = [
|
||||
@@ -57,7 +52,7 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
|
||||
});
|
||||
}
|
||||
let projections = v2_metadata_from_catalog(&entry);
|
||||
assert_eq!(projections.len(), installations.len() + 1);
|
||||
assert_eq!(projections.len(), installations.len());
|
||||
for (index, ((root_id, metadata), (environment_id, plugin_id, root))) in
|
||||
projections.iter().zip(installations).enumerate()
|
||||
{
|
||||
@@ -70,10 +65,8 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
|
||||
plugin_display_name: metadata.plugin_display_name.clone(),
|
||||
source_environment_id: environment_id.to_string(),
|
||||
servers: metadata.servers.clone(),
|
||||
connector_ids: metadata.connector_ids.clone(),
|
||||
},
|
||||
);
|
||||
assert_eq!(contribution.connector_ids, entry.connector_ids);
|
||||
if index != 0 {
|
||||
assert!(contribution.servers.is_empty());
|
||||
continue;
|
||||
@@ -94,22 +87,11 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
|
||||
);
|
||||
}
|
||||
|
||||
let (root_id, metadata) = &projections[installations.len()];
|
||||
assert_eq!(root_id, "cloud:plugin_example");
|
||||
assert!(metadata.servers.is_empty());
|
||||
assert_eq!(metadata.connector_ids, vec!["connector_example"]);
|
||||
|
||||
// Bound projected metadata without mutating the source catalog or losing installations.
|
||||
entry.display_name = "界".repeat(MAX_PLUGIN_DISPLAY_NAME_CHARS + 1);
|
||||
entry.connector_ids = (0..=MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.flat_map(|index| vec![format!("connector_{index}"); 2])
|
||||
.collect();
|
||||
let expected_connectors = (0..MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.map(|index| format!("connector_{index}"))
|
||||
.collect::<Vec<_>>();
|
||||
entry.mcp_servers.clear();
|
||||
let projections = v2_metadata_from_catalog(&entry);
|
||||
assert_eq!(projections.len(), installations.len() + 1);
|
||||
assert_eq!(projections.len(), installations.len());
|
||||
assert!(
|
||||
projections
|
||||
.iter()
|
||||
@@ -120,15 +102,10 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
|
||||
metadata.plugin_display_name,
|
||||
"界".repeat(MAX_PLUGIN_DISPLAY_NAME_CHARS)
|
||||
);
|
||||
assert_eq!(metadata.connector_ids, expected_connectors);
|
||||
}
|
||||
assert_eq!(
|
||||
entry.display_name.chars().count(),
|
||||
MAX_PLUGIN_DISPLAY_NAME_CHARS + 1
|
||||
);
|
||||
assert_eq!(
|
||||
entry.connector_ids.len(),
|
||||
(MAX_CONNECTOR_IDS_PER_PLUGIN + 1) * 2
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -431,7 +431,6 @@ fn resolved_plugin(
|
||||
onboarding_skill: None,
|
||||
skills: Vec::new(),
|
||||
mcp_servers,
|
||||
apps: None,
|
||||
hooks: None,
|
||||
},
|
||||
interface: None,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Coordinates cloud turn refreshes and executor MCP contributions with thread-owned catalogs.
|
||||
//! Coordinates executor MCP contributions with thread-owned catalogs.
|
||||
//!
|
||||
//! One contributor is registered for both lifecycles. Provider instances are shared, while
|
||||
//! catalogs and executor metadata live together in thread extension data.
|
||||
//! Provider instances are shared, while catalogs and executor metadata live in thread extension
|
||||
//! data.
|
||||
|
||||
use crate::PluginProviders;
|
||||
use codex_core::config::Config;
|
||||
@@ -14,9 +14,7 @@ pub(crate) struct PluginContributor {
|
||||
pub(crate) providers: PluginProviders,
|
||||
}
|
||||
|
||||
/// Installs one coordinator for cloud turn-start and executor MCP callbacks.
|
||||
/// The optional cloud provider never disables executor plugins, and Core's plugin policy applies
|
||||
/// to both paths.
|
||||
/// Installs one coordinator for executor MCP callbacks; Core's plugin policy applies to it.
|
||||
pub fn install_plugin_providers(
|
||||
builder: &mut ExtensionRegistryBuilder<Config>,
|
||||
providers: PluginProviders,
|
||||
@@ -24,7 +22,6 @@ pub fn install_plugin_providers(
|
||||
let contributor = Arc::new(PluginContributor { providers });
|
||||
builder.thread_lifecycle_contributor(contributor.clone());
|
||||
builder.config_contributor(contributor.clone());
|
||||
builder.turn_lifecycle_contributor(contributor.clone());
|
||||
builder.mcp_server_contributor(contributor);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Thread-owned cloud catalog and stable selected-root metadata, guarded by a short-lived mutex.
|
||||
//! Thread-owned executor plugin catalog and stable selected-root metadata, guarded by a short-lived mutex.
|
||||
|
||||
use crate::catalog_observability::record_catalog;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
@@ -6,33 +6,22 @@ use codex_core_plugins::PluginRootOwnership;
|
||||
use codex_core_plugins::catalog_from_snapshots;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_extension_api::CatalogRefreshBackoff;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_extension_api::SelectedPluginContribution;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_mcp::McpResourceClientAuthKey;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::MutexGuard;
|
||||
use tokio::sync::Mutex as AsyncMutex;
|
||||
|
||||
/// Plugin configuration and caches owned by one thread; mutable state stays extension-private.
|
||||
#[derive(Default)]
|
||||
pub struct PluginsThreadState {
|
||||
/// Serializes discovery; true only when the last refresh published successfully.
|
||||
pub(crate) cloud_refresh_lock: AsyncMutex<bool>,
|
||||
state: Mutex<PluginContributorState>,
|
||||
}
|
||||
|
||||
impl PluginsThreadState {
|
||||
/// Returns an owned cloud snapshot only while its auth generation is current.
|
||||
pub fn cloud_catalog(&self) -> Option<PluginCatalog> {
|
||||
self.contributor_state().cloud_catalog().cloned()
|
||||
}
|
||||
|
||||
/// Locks the thread's contributor state, recovering it if a holder panicked.
|
||||
pub(crate) fn contributor_state(&self) -> MutexGuard<'_, PluginContributorState> {
|
||||
self.state
|
||||
.lock()
|
||||
@@ -45,30 +34,11 @@ impl PluginsThreadState {
|
||||
pub(crate) struct PluginContributorState {
|
||||
pub(crate) extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
|
||||
pub(crate) plugins_enabled: bool,
|
||||
pub(crate) cloud_generation: Option<CloudPluginGeneration>,
|
||||
pub(crate) cloud_retry: Option<CatalogRefreshBackoff>,
|
||||
pub(crate) executor_catalog: Option<PluginCatalog>,
|
||||
executor_snapshots: Vec<ExecutorCapabilityDiscoveryV2Snapshot>,
|
||||
pub(crate) executor_cache: Vec<CachedSelectedRoot>,
|
||||
}
|
||||
|
||||
/// Keeps cloud plugin metadata within one published auth scope and Apps availability state.
|
||||
pub(crate) struct CloudPluginGeneration {
|
||||
pub(crate) auth_cache_key: Option<McpResourceClientAuthKey>,
|
||||
pub(crate) mcp_resources: Option<McpResourceClient>,
|
||||
pub(crate) catalog: Option<PluginCatalog>,
|
||||
}
|
||||
|
||||
impl CloudPluginGeneration {
|
||||
pub(crate) fn is_auth_current(&self) -> bool {
|
||||
self.auth_cache_key
|
||||
== self
|
||||
.mcp_resources
|
||||
.as_ref()
|
||||
.map(|client| client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME))
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginContributorState {
|
||||
/// Reuses unchanged discovery and preserves surviving installations' order on refresh.
|
||||
pub(crate) fn update_executor_catalog(
|
||||
@@ -104,67 +74,6 @@ impl PluginContributorState {
|
||||
self.executor_snapshots.clear();
|
||||
}
|
||||
|
||||
/// Returns the cloud catalog only while it belongs to the live auth generation.
|
||||
pub(crate) fn cloud_catalog(&self) -> Option<&PluginCatalog> {
|
||||
self.cloud_generation
|
||||
.as_ref()
|
||||
.filter(|generation| generation.is_auth_current())
|
||||
.and_then(|generation| generation.catalog.as_ref())
|
||||
}
|
||||
|
||||
/// Establishes the auth scope and returns the key used by that generation.
|
||||
pub(crate) fn prepare_cloud_generation(
|
||||
&mut self,
|
||||
mcp_resources: Option<McpResourceClient>,
|
||||
) -> Option<McpResourceClientAuthKey> {
|
||||
let auth_cache_key = mcp_resources
|
||||
.as_ref()
|
||||
.map(|client| client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME));
|
||||
if self
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.is_none_or(|generation| generation.auth_cache_key != auth_cache_key)
|
||||
{
|
||||
self.cloud_generation = Some(CloudPluginGeneration {
|
||||
auth_cache_key: auth_cache_key.clone(),
|
||||
mcp_resources,
|
||||
catalog: None,
|
||||
});
|
||||
}
|
||||
auth_cache_key
|
||||
}
|
||||
|
||||
/// Accepts current-auth results, retaining prior complete entries as partial after an incomplete refresh.
|
||||
/// Returns false only when the result belongs to a stale auth generation.
|
||||
pub(crate) fn publish_cloud_catalog(
|
||||
&mut self,
|
||||
auth_cache_key: Option<&McpResourceClientAuthKey>,
|
||||
mut catalog: PluginCatalog,
|
||||
) -> bool {
|
||||
let Some(generation) = self
|
||||
.cloud_generation
|
||||
.as_mut()
|
||||
.filter(|generation| generation.auth_cache_key.as_ref() == auth_cache_key)
|
||||
.filter(|generation| generation.is_auth_current())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if catalog.is_partial
|
||||
&& let Some(previous) = generation
|
||||
.catalog
|
||||
.as_ref()
|
||||
.filter(|previous| !previous.is_partial)
|
||||
{
|
||||
catalog = previous.clone();
|
||||
catalog.is_partial = true;
|
||||
tracing::warn!(
|
||||
"cloud plugin discovery was partial; retaining prior auth-scoped entries as partial"
|
||||
);
|
||||
}
|
||||
record_catalog(self.extension_metrics.as_deref(), "cloud", &catalog);
|
||||
generation.catalog = Some(catalog);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CachedSelectedRoot {
|
||||
@@ -185,7 +94,6 @@ pub(crate) enum CachedPluginMetadata {
|
||||
pub(crate) struct SelectedPluginMetadata {
|
||||
pub(crate) plugin_display_name: String,
|
||||
pub(crate) servers: Vec<(String, codex_config::McpServerConfig)>,
|
||||
pub(crate) connector_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -5,11 +5,6 @@ use crate::PluginProviders;
|
||||
use crate::plugin_contributor::PluginContributor;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginCatalogEntry;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_core_plugins::PluginProvider;
|
||||
use codex_core_plugins::PluginSourceLocation;
|
||||
use codex_exec_server::CapabilityTextFile;
|
||||
use codex_exec_server::DiscoverV2CapabilitiesResponse;
|
||||
use codex_exec_server::DiscoveredPluginFiles;
|
||||
@@ -19,14 +14,12 @@ use codex_exec_server::ExecutorPlugin;
|
||||
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
use codex_extension_api::McpServerContribution;
|
||||
use codex_extension_api::McpServerContributionContext;
|
||||
use codex_extension_api::McpServerContributor;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
async fn contribution_labels(
|
||||
@@ -49,36 +42,11 @@ async fn contribution_labels(
|
||||
);
|
||||
labels.push(plugin.selected_root_id);
|
||||
}
|
||||
for contribution in contributor.contribute(context).await {
|
||||
if let McpServerContribution::HostedPluginConnectors { plugin_id, .. } = contribution {
|
||||
labels.push(format!("cloud:{plugin_id}"));
|
||||
} else {
|
||||
panic!("unexpected contribution: {contribution:?}");
|
||||
}
|
||||
}
|
||||
// Plugins no longer contribute hosted servers outside their selected roots.
|
||||
assert!(contributor.contribute(context).await.is_empty());
|
||||
labels
|
||||
}
|
||||
|
||||
fn cloud_plugin(remote_id: &str) -> PluginCatalogEntry {
|
||||
PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: remote_id.to_string(),
|
||||
},
|
||||
display_name: "Example".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
mcp_servers: BTreeMap::from([(
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command":"node","args":["server.js"]}),
|
||||
)]),
|
||||
connector_ids: vec!["connector_example".to_string()],
|
||||
locations: vec![PluginSourceLocation::Cloud {
|
||||
resource_uri: format!("plugin://{remote_id}"),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn executor_snapshot(
|
||||
environment_id: &str,
|
||||
) -> anyhow::Result<ExecutorCapabilityDiscoveryV2Snapshot> {
|
||||
@@ -89,7 +57,6 @@ fn executor_snapshot(
|
||||
plugins: vec![ExecutorPlugin {
|
||||
id: "example@marketplace".to_string(),
|
||||
display_name: "Example".to_string(),
|
||||
remote_plugin_id: Some("plugin_a".to_string()),
|
||||
version: "1.0.0".to_string(),
|
||||
files: DiscoveredPluginFiles {
|
||||
manifest: CapabilityTextFile {
|
||||
@@ -107,39 +74,6 @@ fn executor_snapshot(
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_refresh_retains_entries_without_excluding_new_executor_plugins() -> anyhow::Result<()> {
|
||||
let mut state = PluginContributorState::default();
|
||||
let auth_key = state.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
let original = PluginCatalog {
|
||||
entries: vec![cloud_plugin("old_plugin")],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(state.publish_cloud_catalog(auth_key.as_ref(), original.clone()));
|
||||
assert!(state.publish_cloud_catalog(
|
||||
auth_key.as_ref(),
|
||||
PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
is_partial: true,
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
let mut expected = original;
|
||||
expected.is_partial = true;
|
||||
assert_eq!(state.cloud_catalog(), Some(&expected));
|
||||
|
||||
state.update_executor_catalog(&[executor_snapshot("executor-a")?]);
|
||||
let merged =
|
||||
codex_core_plugins::merge_catalogs(state.executor_catalog.as_ref(), state.cloud_catalog());
|
||||
assert!(
|
||||
merged
|
||||
.entries
|
||||
.iter()
|
||||
.any(|entry| { entry.id.as_str() == "plugin_a" && entry.enabled })
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executor_refresh_preserves_order_and_removes_stale_entries() -> anyhow::Result<()> {
|
||||
let mut state = PluginContributorState::default();
|
||||
@@ -190,9 +124,6 @@ fn executor_refresh_preserves_order_and_removes_stale_entries() -> anyhow::Resul
|
||||
|
||||
#[tokio::test]
|
||||
async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> anyhow::Result<()> {
|
||||
struct CloudProvider;
|
||||
impl PluginProvider for CloudProvider {}
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let root = home.path().join("legacy");
|
||||
std::fs::create_dir_all(root.join(".codex-plugin"))?;
|
||||
@@ -226,24 +157,12 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
let v1 = ExecutorCapabilityDiscoveryCache::default()
|
||||
.snapshot(&resolved_roots, &Default::default())
|
||||
.await;
|
||||
let mut contributor = PluginContributor {
|
||||
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(environments)))
|
||||
.with_cloud_provider(Arc::new(CloudProvider)),
|
||||
let contributor = PluginContributor {
|
||||
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(environments))),
|
||||
};
|
||||
let thread = ExtensionData::new("projection-test");
|
||||
let init = ExtensionDataInit::default();
|
||||
let state = thread.get_or_init(PluginsThreadState::default);
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
let key = state.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
assert!(state.publish_cloud_catalog(
|
||||
key.as_ref(),
|
||||
PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
..Default::default()
|
||||
}
|
||||
));
|
||||
}
|
||||
// A different environment ensures per-root filtering cannot hide a legacy fallback.
|
||||
let mut valid = [executor_snapshot("executor-a")?];
|
||||
Arc::make_mut(valid[0].result.as_mut().unwrap()).plugins[0]
|
||||
@@ -252,13 +171,10 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
path: PathUri::parse("file:///plugins/example/1.0.0/.mcp.json")?,
|
||||
contents: r#"{"executor-only":{"command":"node"}}"#.to_string(),
|
||||
});
|
||||
let mut local = [
|
||||
let local = [
|
||||
executor_snapshot("executor-a")?,
|
||||
executor_snapshot("executor-b")?,
|
||||
];
|
||||
for snapshot in &mut local {
|
||||
Arc::make_mut(snapshot.result.as_mut().unwrap()).plugins[0].remote_plugin_id = None;
|
||||
}
|
||||
let empty = [ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "executor-a".to_string(),
|
||||
result: Ok(Arc::new(DiscoverV2CapabilitiesResponse::default())),
|
||||
@@ -272,51 +188,33 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
"snapshot selects V2 independently of the acquisition flag",
|
||||
false,
|
||||
Some(valid.as_slice()),
|
||||
vec![
|
||||
"mcp:example",
|
||||
"executor-a:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
],
|
||||
),
|
||||
(
|
||||
"legacy",
|
||||
false,
|
||||
None,
|
||||
vec!["mcp:legacy", "legacy-root", "cloud:plugin_a"],
|
||||
vec!["disabled:example@marketplace"],
|
||||
),
|
||||
("legacy", false, None, vec!["mcp:legacy", "legacy-root"]),
|
||||
(
|
||||
"no V2 snapshot",
|
||||
true,
|
||||
None,
|
||||
vec!["mcp:legacy", "legacy-root", "cloud:plugin_a"],
|
||||
vec!["mcp:legacy", "legacy-root"],
|
||||
),
|
||||
(
|
||||
"empty snapshots",
|
||||
true,
|
||||
Some([].as_slice()),
|
||||
vec!["cloud:plugin_a"],
|
||||
Vec::<&str>::new(),
|
||||
),
|
||||
(
|
||||
"empty inventory",
|
||||
true,
|
||||
Some(empty.as_slice()),
|
||||
vec!["cloud:plugin_a"],
|
||||
),
|
||||
(
|
||||
"failed",
|
||||
true,
|
||||
Some(failed.as_slice()),
|
||||
vec!["cloud:plugin_a"],
|
||||
Vec::<&str>::new(),
|
||||
),
|
||||
("failed", true, Some(failed.as_slice()), Vec::<&str>::new()),
|
||||
(
|
||||
"valid",
|
||||
true,
|
||||
Some(valid.as_slice()),
|
||||
vec![
|
||||
"mcp:example",
|
||||
"executor-a:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
],
|
||||
vec!["disabled:example@marketplace"],
|
||||
),
|
||||
(
|
||||
"unconfigured local",
|
||||
@@ -325,7 +223,6 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
vec![
|
||||
"disabled:example@marketplace",
|
||||
"disabled:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
],
|
||||
),
|
||||
] {
|
||||
@@ -375,68 +272,19 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
.features
|
||||
.enable(Feature::ExecutorCapabilityDiscoveryV2)?;
|
||||
|
||||
// Cloud counterparts control enablement without deleting the executor installation.
|
||||
let mut disabled_cloud = cloud_plugin("plugin_a");
|
||||
disabled_cloud.enabled = false;
|
||||
for (case, cloud_enabled, catalog, enabled) in [
|
||||
("no cloud provider", false, None, true),
|
||||
("no cloud catalog", true, None, true),
|
||||
("absent", true, Some(PluginCatalog::default()), false),
|
||||
// Executor installations are local and enabled by configuration alone.
|
||||
for (case, snapshots, expected) in [
|
||||
(
|
||||
"partial absent",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
is_partial: true,
|
||||
warnings: vec!["partial cloud listing".to_string()],
|
||||
..Default::default()
|
||||
}),
|
||||
true,
|
||||
"configured",
|
||||
&valid[..],
|
||||
vec!["mcp:executor-only", "executor-a:example@marketplace"],
|
||||
),
|
||||
(
|
||||
"disabled",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
entries: vec![disabled_cloud],
|
||||
..Default::default()
|
||||
}),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"re-enabled",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
..Default::default()
|
||||
}),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"partial counterpart",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
is_partial: true,
|
||||
warnings: vec!["partial cloud listing".to_string()],
|
||||
}),
|
||||
true,
|
||||
"configured without MCP config",
|
||||
&local[..1],
|
||||
vec!["executor-a:example@marketplace"],
|
||||
),
|
||||
] {
|
||||
let has_cloud_counterpart = catalog
|
||||
.as_ref()
|
||||
.is_some_and(|catalog| !catalog.entries.is_empty());
|
||||
contributor.providers.cloud = if cloud_enabled {
|
||||
Some(Arc::new(CloudProvider))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
{
|
||||
let mut cache = state.contributor_state();
|
||||
cache.cloud_generation = None;
|
||||
let key = cache.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
if let Some(catalog) = catalog {
|
||||
assert!(cache.publish_cloud_catalog(key.as_ref(), catalog));
|
||||
}
|
||||
}
|
||||
let contributions = contribution_labels(
|
||||
&contributor,
|
||||
McpServerContributionContext::for_step(
|
||||
@@ -446,62 +294,16 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
case,
|
||||
&roots,
|
||||
/*executor_capability_discovery*/ None,
|
||||
Some(&valid),
|
||||
Some(snapshots),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let expected = if enabled && !has_cloud_counterpart {
|
||||
vec!["mcp:executor-only", "executor-a:example@marketplace"]
|
||||
} else if enabled {
|
||||
vec![
|
||||
"mcp:example",
|
||||
"executor-a:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
]
|
||||
} else {
|
||||
vec!["disabled:example@marketplace"]
|
||||
};
|
||||
assert_eq!(contributions, expected, "{case}");
|
||||
assert_eq!(
|
||||
state.contributor_state().executor_catalog,
|
||||
Some(catalog_from_snapshots(&valid)),
|
||||
Some(catalog_from_snapshots(snapshots)),
|
||||
"{case}"
|
||||
);
|
||||
}
|
||||
|
||||
// A full Cloud catalog must not crowd out enabled executor-local plugins.
|
||||
let cloud_plugin_count = 100;
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
let key = state.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
let entries = (0..cloud_plugin_count)
|
||||
.map(|index| cloud_plugin(&format!("plugin_{index}")))
|
||||
.collect::<Vec<_>>();
|
||||
assert!(state.publish_cloud_catalog(
|
||||
key.as_ref(),
|
||||
PluginCatalog {
|
||||
entries,
|
||||
..Default::default()
|
||||
}
|
||||
));
|
||||
}
|
||||
let contributions = contribution_labels(
|
||||
&contributor,
|
||||
McpServerContributionContext::for_step(
|
||||
&config,
|
||||
&init,
|
||||
&thread,
|
||||
"merged",
|
||||
&roots,
|
||||
/*executor_capability_discovery*/ None,
|
||||
Some(&local[..1]),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(contributions.len(), cloud_plugin_count + 1);
|
||||
assert_eq!(contributions[0], "executor-a:example@marketplace");
|
||||
for (index, contribution) in contributions[1..].iter().enumerate() {
|
||||
assert_eq!(contribution, &format!("cloud:plugin_{index}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
43
codex-rs/ext/mcp/src/plugin_lifecycle.rs
Normal file
43
codex-rs/ext/mcp/src/plugin_lifecycle.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
//! Tracks plugin enablement and shares the thread's MCP resource client.
|
||||
|
||||
use crate::PluginsThreadState;
|
||||
use crate::plugin_contributor::PluginContributor;
|
||||
use codex_core::config::Config;
|
||||
use codex_extension_api::ConfigContributor;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_features::Feature;
|
||||
|
||||
impl ThreadLifecycleContributor<Config> for PluginContributor {
|
||||
fn on_thread_start<'a>(
|
||||
&'a self,
|
||||
input: ThreadStartInput<'a, Config>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let state = input.thread_store.get_or_init(PluginsThreadState::default);
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
state.plugins_enabled = input.config.features.enabled(Feature::Plugins);
|
||||
state.extension_metrics = input.extension_metrics;
|
||||
}
|
||||
if let Some(resources) = &input.mcp_resource_client {
|
||||
input.session_store.insert(resources.as_ref().clone());
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigContributor<Config> for PluginContributor {
|
||||
fn on_config_changed(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
_previous_config: &Config,
|
||||
new_config: &Config,
|
||||
) {
|
||||
let state = thread_store.get_or_init(PluginsThreadState::default);
|
||||
state.contributor_state().plugins_enabled = new_config.features.enabled(Feature::Plugins);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,16 @@
|
||||
//! Host-assembled plugin sources; discovery results belong to the active thread, not this registry.
|
||||
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_core_plugins::PluginProvider;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Cloud discovery is optional and never replaces executor plugin support.
|
||||
/// Plugin providers available to a host.
|
||||
pub struct PluginProviders {
|
||||
// CCA owns and supplies the cloud provider implementation.
|
||||
pub(crate) cloud: Option<Arc<dyn PluginProvider>>,
|
||||
// Keep concrete access to resolve_bound so loaders retain the exact executor filesystem.
|
||||
pub(crate) executor: Arc<ExecutorPluginProvider>,
|
||||
}
|
||||
|
||||
impl PluginProviders {
|
||||
pub fn new(executor: Arc<ExecutorPluginProvider>) -> Self {
|
||||
Self {
|
||||
cloud: None,
|
||||
executor,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_cloud_provider(mut self, provider: Arc<dyn PluginProvider>) -> Self {
|
||||
self.cloud = Some(provider);
|
||||
self
|
||||
Self { executor }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,290 +0,0 @@
|
||||
//! Owns task-scoped MCP event streams without retaining their thread or runtime.
|
||||
//! Each subscription has one worker, and cancellation never waits for output capacity.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadReadyInput;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_mcp::McpEventNotification;
|
||||
use codex_mcp::McpEventStreamOpener;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_protocol::ThreadId;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::timeout_at;
|
||||
|
||||
const EVENT_UPDATE_CAPACITY: usize = 64;
|
||||
const ACTIVATION_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 90);
|
||||
|
||||
/// A notification or stream ending, identified by task, subscription, and stream attempt.
|
||||
pub enum McpEventStreamUpdate {
|
||||
Notification {
|
||||
thread_id: ThreadId,
|
||||
subscription_id: String,
|
||||
stream_attempt_id: u64,
|
||||
notification: McpEventNotification,
|
||||
},
|
||||
Ended {
|
||||
thread_id: ThreadId,
|
||||
subscription_id: String,
|
||||
stream_attempt_id: u64,
|
||||
result: Result<()>,
|
||||
},
|
||||
}
|
||||
|
||||
struct ManagedEventStream {
|
||||
stream_attempt_id: u64,
|
||||
active: Arc<AtomicBool>,
|
||||
worker: JoinHandle<()>,
|
||||
cancel_event_streams_on_server_removal: watch::Sender<()>,
|
||||
}
|
||||
|
||||
/// Tracks event streams by thread and subscription ID.
|
||||
///
|
||||
/// Notifications and stream endings go into a queue. Cancelling a
|
||||
/// stream does not require adding an `Ended` update, so it still works when the queue is full.
|
||||
pub struct McpEventStreamManager {
|
||||
streams: Mutex<HashMap<(ThreadId, String), ManagedEventStream>>,
|
||||
next_stream_attempt_id: AtomicU64,
|
||||
updates: mpsc::Sender<McpEventStreamUpdate>,
|
||||
shutdown: AtomicBool,
|
||||
}
|
||||
|
||||
impl McpEventStreamManager {
|
||||
pub fn new() -> (Self, mpsc::Receiver<McpEventStreamUpdate>) {
|
||||
let (updates, receiver) = mpsc::channel(EVENT_UPDATE_CAPACITY);
|
||||
(
|
||||
Self {
|
||||
streams: Mutex::default(),
|
||||
next_stream_attempt_id: AtomicU64::new(/*v*/ 1),
|
||||
updates,
|
||||
shutdown: AtomicBool::new(/*v*/ false),
|
||||
},
|
||||
receiver,
|
||||
)
|
||||
}
|
||||
|
||||
/// Opens a stream and returns its attempt ID after the server confirms activation.
|
||||
pub async fn start(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
subscription_id: String,
|
||||
opener: McpEventStreamOpener,
|
||||
event_name: String,
|
||||
arguments: Value,
|
||||
request_meta: Option<Map<String, Value>>,
|
||||
) -> Result<u64> {
|
||||
let key = (thread_id, subscription_id.clone());
|
||||
let (ready_tx, ready_rx) = oneshot::channel();
|
||||
{
|
||||
let mut streams = self.streams.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if self.shutdown.load(Ordering::Acquire) {
|
||||
return Err(anyhow!("MCP event stream manager is shut down"));
|
||||
}
|
||||
streams.retain(|_, stream| !stream.worker.is_finished());
|
||||
if let Some(stream) = streams.get(&key) {
|
||||
if stream.active.load(Ordering::Acquire) {
|
||||
return Ok(stream.stream_attempt_id);
|
||||
}
|
||||
return Err(anyhow!(
|
||||
"MCP event subscription is already starting or finishing"
|
||||
));
|
||||
}
|
||||
|
||||
let stream_attempt_id = self
|
||||
.next_stream_attempt_id
|
||||
.fetch_add(/*val*/ 1, Ordering::Relaxed);
|
||||
let active = Arc::new(AtomicBool::new(/*v*/ false));
|
||||
let worker_active = Arc::clone(&active);
|
||||
let cancel_event_streams_on_server_removal = opener.event_stream_cancellation_sender();
|
||||
let updates = self.updates.clone();
|
||||
let deadline = Instant::now() + ACTIVATION_TIMEOUT;
|
||||
// Keep the stream running if the caller stops waiting for activation.
|
||||
let worker = tokio::spawn(async move {
|
||||
let mut ready = Some(ready_tx);
|
||||
let forward = async {
|
||||
let mut stream = timeout_at(
|
||||
deadline,
|
||||
opener.open(&event_name, &arguments, request_meta.as_ref()),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream activation timed out"))??;
|
||||
|
||||
loop {
|
||||
let notification = if ready.is_some() {
|
||||
timeout_at(deadline, stream.recv())
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream activation timed out"))??
|
||||
} else {
|
||||
stream.recv().await?
|
||||
};
|
||||
let Some(notification) = notification else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let activates = notification.method == "notifications/events/active";
|
||||
let terminates = notification.method == "notifications/events/terminated";
|
||||
if activates {
|
||||
worker_active.store(/*val*/ true, Ordering::Release);
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Ok(stream_attempt_id));
|
||||
}
|
||||
}
|
||||
|
||||
let send = updates.send(McpEventStreamUpdate::Notification {
|
||||
thread_id,
|
||||
subscription_id: subscription_id.clone(),
|
||||
stream_attempt_id,
|
||||
notification,
|
||||
});
|
||||
let sent = if ready.is_some() {
|
||||
timeout_at(deadline, send)
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream activation timed out"))?
|
||||
} else {
|
||||
send.await
|
||||
};
|
||||
sent.map_err(|_| anyhow!("MCP event stream receiver was dropped"))?;
|
||||
|
||||
if terminates {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
() = opener.wait_for_access_change() => {
|
||||
Err(anyhow!("MCP event stream access changed"))
|
||||
}
|
||||
() = updates.closed() => {
|
||||
Err(anyhow!("MCP event stream receiver was dropped"))
|
||||
}
|
||||
result = forward => result,
|
||||
};
|
||||
|
||||
worker_active.store(/*val*/ false, Ordering::Release);
|
||||
drop(opener);
|
||||
if let Some(ready) = ready {
|
||||
let error = match &result {
|
||||
Ok(()) => anyhow!("MCP event stream ended before becoming active"),
|
||||
Err(error) => anyhow!("{error:#}"),
|
||||
};
|
||||
let _ = ready.send(Err(error));
|
||||
}
|
||||
|
||||
let _ = updates
|
||||
.send(McpEventStreamUpdate::Ended {
|
||||
thread_id,
|
||||
subscription_id,
|
||||
stream_attempt_id,
|
||||
result,
|
||||
})
|
||||
.await;
|
||||
});
|
||||
streams.insert(
|
||||
key,
|
||||
ManagedEventStream {
|
||||
stream_attempt_id,
|
||||
active,
|
||||
worker,
|
||||
cancel_event_streams_on_server_removal,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
ready_rx
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream ended before becoming active"))?
|
||||
}
|
||||
|
||||
/// Await cancellation before starting the same subscription again.
|
||||
pub async fn cancel(&self, thread_id: ThreadId, subscription_id: &str) {
|
||||
let stream = self
|
||||
.streams
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(&(thread_id, subscription_id.to_owned()));
|
||||
if let Some(stream) = stream {
|
||||
stream.worker.abort();
|
||||
let _ = stream.worker.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Permanently rejects new starts and waits for all current workers to release their streams.
|
||||
pub async fn shutdown(&self) {
|
||||
self.shutdown.store(/*val*/ true, Ordering::Release);
|
||||
let streams = self
|
||||
.streams
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.drain()
|
||||
.map(|(_, stream)| stream)
|
||||
.collect::<Vec<_>>();
|
||||
for stream in &streams {
|
||||
stream.worker.abort();
|
||||
}
|
||||
for stream in streams {
|
||||
let _ = stream.worker.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Sync> ThreadLifecycleContributor<C> for McpEventStreamManager {
|
||||
fn on_thread_start<'a>(&'a self, input: ThreadStartInput<'a, C>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
if let Some(client) = input.mcp_resource_client {
|
||||
input.thread_store.insert(client.as_ref().clone());
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn on_thread_ready<'a>(&'a self, input: ThreadReadyInput<'a, C>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let Some(client) = input.thread_store.get::<McpResourceClient>() else {
|
||||
return;
|
||||
};
|
||||
let Ok(thread_id) = ThreadId::from_string(input.thread_store.level_id()) else {
|
||||
return;
|
||||
};
|
||||
let cancellation = self
|
||||
.streams
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.iter()
|
||||
.find(|((owner, _), stream)| {
|
||||
let belongs_to_task = *owner == thread_id;
|
||||
let worker_is_running = !stream.worker.is_finished();
|
||||
belongs_to_task && worker_is_running
|
||||
})
|
||||
.map(|(_, stream)| stream.cancel_event_streams_on_server_removal.clone());
|
||||
if let Some(cancellation) = cancellation {
|
||||
client.forward_event_server_removals_to(cancellation);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for McpEventStreamManager {
|
||||
fn drop(&mut self) {
|
||||
let mut streams = self.streams.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for (_, stream) in streams.drain() {
|
||||
stream.worker.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,357 +0,0 @@
|
||||
//! Exercises stream activation, task ownership, and cancellation.
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadReadyInput;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_mcp::McpEventStreamOpener;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::event_stream_tests::Fixture;
|
||||
use super::event_stream_tests::StaticAuth;
|
||||
use super::event_stream_tests::WAIT;
|
||||
use crate::McpEventStreamManager;
|
||||
use crate::McpEventStreamUpdate;
|
||||
|
||||
async fn start_subscription(
|
||||
manager: &McpEventStreamManager,
|
||||
opener: &McpEventStreamOpener,
|
||||
thread_id: ThreadId,
|
||||
) -> Result<u64> {
|
||||
manager
|
||||
.start(
|
||||
thread_id,
|
||||
"sub".into(),
|
||||
opener.clone(),
|
||||
"test.event".into(),
|
||||
json!({}),
|
||||
/*request_meta*/ None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn connect_loaded_task(
|
||||
manager: &McpEventStreamManager,
|
||||
thread_id: ThreadId,
|
||||
client: Arc<McpResourceClient>,
|
||||
) {
|
||||
let session_store = ExtensionData::new("test");
|
||||
let thread_store = ExtensionData::new(thread_id.to_string());
|
||||
manager
|
||||
.on_thread_start(ThreadStartInput {
|
||||
config: &(),
|
||||
session_source: &SessionSource::Exec,
|
||||
persistent_thread_state_available: false,
|
||||
environments: &[],
|
||||
mcp_resource_client: Some(client),
|
||||
extension_metrics: None,
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
})
|
||||
.await;
|
||||
manager
|
||||
.on_thread_ready(ThreadReadyInput {
|
||||
config: &(),
|
||||
session_source: &SessionSource::Exec,
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reloaded_tasks_can_cancel_surviving_streams() -> Result<()> {
|
||||
for removed_before_ready in [false, true] {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let (result, stream) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
result?;
|
||||
timeout(WAIT, updates.recv()).await?.unwrap();
|
||||
fixture.runtime.shutdown().await;
|
||||
drop(fixture.runtime);
|
||||
|
||||
let mut replacement = Fixture::new().await?;
|
||||
let client = Arc::new(McpResourceClient::new(Arc::clone(&replacement.runtime)));
|
||||
replacement.runtime_input.mcp_servers.clear();
|
||||
if removed_before_ready {
|
||||
replacement.runtime.replace(replacement.runtime_input).await;
|
||||
connect_loaded_task(&manager, thread_id, client).await;
|
||||
} else {
|
||||
connect_loaded_task(&manager, thread_id, client).await;
|
||||
let expected = stream.notify("notifications/events/event");
|
||||
let McpEventStreamUpdate::Notification { notification, .. } =
|
||||
timeout(WAIT, updates.recv()).await?.unwrap()
|
||||
else {
|
||||
panic!("event expected after task reload");
|
||||
};
|
||||
assert_eq!(notification, expected);
|
||||
replacement.runtime.replace(replacement.runtime_input).await;
|
||||
}
|
||||
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
let McpEventStreamUpdate::Ended { result, .. } =
|
||||
timeout(WAIT, updates.recv()).await?.unwrap()
|
||||
else {
|
||||
panic!("stream should end after the event server is removed");
|
||||
};
|
||||
assert!(result.is_err());
|
||||
manager.shutdown().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn streams_outlive_tasks_and_activate_with_full_output() -> Result<()> {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let first_thread = ThreadId::new();
|
||||
let second_thread = ThreadId::new();
|
||||
let mut streams = Vec::new();
|
||||
for thread_id in [first_thread, second_thread] {
|
||||
let start = manager.start(
|
||||
thread_id,
|
||||
"sub".into(),
|
||||
opener.clone(),
|
||||
"test.event".into(),
|
||||
json!({"resource_id": "resource-123"}),
|
||||
Some(serde_json::Map::from_iter([(
|
||||
"saved_id".into(),
|
||||
json!("sub"),
|
||||
)])),
|
||||
);
|
||||
tokio::pin!(start);
|
||||
let stream = tokio::select! {
|
||||
result = &mut start => panic!("start returned before activation: {result:?}"),
|
||||
stream = timeout(WAIT, fixture.opened.recv()) => stream?.unwrap(),
|
||||
};
|
||||
let mut params = stream.request["params"].clone();
|
||||
params["_meta"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("progressToken");
|
||||
assert_eq!(
|
||||
params,
|
||||
json!({"name": "test.event", "arguments": {"resource_id": "resource-123"}, "_meta": {"saved_id": "sub"}})
|
||||
);
|
||||
stream.notify("notifications/events/active");
|
||||
timeout(WAIT, start).await??;
|
||||
timeout(WAIT, updates.recv()).await?.unwrap();
|
||||
streams.push(stream);
|
||||
}
|
||||
start_subscription(&manager, &opener, first_thread).await?;
|
||||
assert!(fixture.opened.try_recv().is_err());
|
||||
|
||||
fixture.runtime.shutdown().await;
|
||||
let expected = streams[1].notify("notifications/events/event");
|
||||
let McpEventStreamUpdate::Notification {
|
||||
thread_id,
|
||||
subscription_id,
|
||||
notification,
|
||||
..
|
||||
} = timeout(WAIT, updates.recv()).await?.unwrap()
|
||||
else {
|
||||
panic!("event expected");
|
||||
};
|
||||
assert_eq!(
|
||||
(thread_id, subscription_id, notification),
|
||||
(second_thread, "sub".into(), expected)
|
||||
);
|
||||
for _ in 0..=updates.max_capacity() {
|
||||
streams[0].notify("notifications/events/event");
|
||||
}
|
||||
timeout(WAIT, async {
|
||||
while updates.capacity() != 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
let third_thread = ThreadId::new();
|
||||
let (started, stream) = tokio::join!(
|
||||
timeout(WAIT, start_subscription(&manager, &opener, third_thread)),
|
||||
async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
}
|
||||
);
|
||||
started??;
|
||||
assert_eq!(updates.capacity(), 0);
|
||||
manager.cancel(third_thread, "sub").await;
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
|
||||
manager.cancel(first_thread, "sub").await;
|
||||
timeout(WAIT, streams[0].notifications.closed()).await?;
|
||||
manager.shutdown().await;
|
||||
timeout(WAIT, streams[1].notifications.closed()).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queued_updates_keep_their_stream_attempt_after_replacement() -> Result<()> {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let (first_attempt, stream) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
let first_attempt = first_attempt?;
|
||||
assert_eq!(
|
||||
start_subscription(&manager, &opener, thread_id).await?,
|
||||
first_attempt
|
||||
);
|
||||
|
||||
stream.notify("notifications/events/terminated");
|
||||
// Leave activation, termination, and the ending queued while opening a replacement.
|
||||
timeout(WAIT, async {
|
||||
while updates.len() < 3 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
manager.cancel(thread_id, "sub").await;
|
||||
|
||||
let (second_attempt, replacement) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
let second_attempt = second_attempt?;
|
||||
assert_ne!(first_attempt, second_attempt);
|
||||
|
||||
let mut queued_attempts = Vec::new();
|
||||
for _ in 0..4 {
|
||||
let stream_attempt_id = match timeout(WAIT, updates.recv()).await?.unwrap() {
|
||||
McpEventStreamUpdate::Notification {
|
||||
stream_attempt_id, ..
|
||||
} => stream_attempt_id,
|
||||
McpEventStreamUpdate::Ended {
|
||||
stream_attempt_id,
|
||||
result,
|
||||
..
|
||||
} => {
|
||||
result?;
|
||||
assert_eq!(stream_attempt_id, first_attempt);
|
||||
stream_attempt_id
|
||||
}
|
||||
};
|
||||
queued_attempts.push(stream_attempt_id);
|
||||
}
|
||||
assert_eq!(
|
||||
queued_attempts,
|
||||
vec![first_attempt, first_attempt, first_attempt, second_attempt]
|
||||
);
|
||||
manager.shutdown().await;
|
||||
timeout(WAIT, replacement.notifications.closed()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_before_activation_releases_the_subscription_id() -> Result<()> {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, _updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let start = start_subscription(&manager, &opener, thread_id);
|
||||
tokio::pin!(start);
|
||||
let stream = tokio::select! {
|
||||
result = &mut start => panic!("start returned before activation: {result:?}"),
|
||||
stream = timeout(WAIT, fixture.opened.recv()) => stream?.unwrap(),
|
||||
};
|
||||
manager.cancel(thread_id, "sub").await;
|
||||
assert!(timeout(WAIT, start).await?.is_err());
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
let (result, replacement) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
result?;
|
||||
manager.shutdown().await;
|
||||
timeout(WAIT, replacement.notifications.closed()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn access_changes_cancel_streams_with_full_output() -> Result<()> {
|
||||
for remove_server in [false, true] {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let (result, stream) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
result?;
|
||||
timeout(WAIT, updates.recv()).await?.unwrap();
|
||||
for _ in 0..=updates.max_capacity() {
|
||||
stream.notify("notifications/events/event");
|
||||
}
|
||||
timeout(WAIT, async {
|
||||
while updates.capacity() != 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
if remove_server {
|
||||
fixture.runtime_input.mcp_servers.clear();
|
||||
fixture.runtime.replace(fixture.runtime_input).await;
|
||||
} else {
|
||||
fixture
|
||||
.auth
|
||||
.set_external_auth(Arc::new(StaticAuth(
|
||||
CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.other",
|
||||
"other-account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
)))
|
||||
.await?;
|
||||
}
|
||||
// Access changes close the stream even while its output is blocked.
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
let result = timeout(WAIT, async {
|
||||
loop {
|
||||
if let McpEventStreamUpdate::Ended { result, .. } = updates.recv().await.unwrap() {
|
||||
break result;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
assert!(result.is_err());
|
||||
assert!(
|
||||
opener
|
||||
.open("test.event", &json!({}), /*request_meta*/ None)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,20 +1,12 @@
|
||||
use anyhow::Context;
|
||||
use codex_config::AppToolApproval;
|
||||
use codex_config::McpServerToolConfig;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_config::test_support::ManagedConfigFixture;
|
||||
use codex_core::EnvironmentConfig;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::windows_sandbox::WindowsSandboxLevelExt;
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginCatalogEntry;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_core_plugins::PluginListQuery;
|
||||
use codex_core_plugins::PluginProvider;
|
||||
use codex_core_plugins::PluginProviderError;
|
||||
use codex_core_plugins::PluginProviderFuture;
|
||||
use codex_core_plugins::PluginSourceLocation;
|
||||
use codex_exec_server::CapabilityRootDiscovery;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryCache;
|
||||
@@ -29,15 +21,14 @@ use codex_extension_api::SelectedPluginContribution;
|
||||
use codex_features::Feature;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_mcp_extension::PluginProviders;
|
||||
use codex_mcp_extension::PluginsThreadState;
|
||||
use codex_mcp_extension::install_plugin_providers;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_protocol::models::PermissionProfileSnapshot;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use core_test_support::apps_test_server::AppsTestServer;
|
||||
use core_test_support::apps_test_server::recorded_apps_tool_calls;
|
||||
use core_test_support::mcp_test_server::McpTestServer;
|
||||
use core_test_support::mcp_test_server::recorded_mcp_tool_calls;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::ev_function_call_with_namespace;
|
||||
@@ -53,8 +44,6 @@ use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
type TestResult = Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
@@ -73,7 +62,6 @@ struct PackageSummary {
|
||||
plugin_id: String,
|
||||
plugin_display_name: String,
|
||||
source_environment_id: String,
|
||||
connector_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -102,8 +90,8 @@ async fn selected_plugin_servers_use_managed_requirements_for_the_selected_root_
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.cloud_config_bundle(
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement(
|
||||
.loader_overrides(
|
||||
(ManagedConfigFixture::requirements(
|
||||
r#"
|
||||
[plugins."selected-root".mcp_servers.allowed.identity]
|
||||
command = "allowed-command"
|
||||
@@ -111,7 +99,9 @@ command = "allowed-command"
|
||||
[plugins."selected-root".mcp_servers.mismatched.identity]
|
||||
command = "expected-command"
|
||||
"#,
|
||||
),
|
||||
))
|
||||
.loader_overrides_for_tests(codex_home.path())
|
||||
.expect("write managed config fixture"),
|
||||
)
|
||||
.build()
|
||||
.await?;
|
||||
@@ -151,7 +141,7 @@ command = "expected-command"
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn selected_plugin_package_is_contributed_without_servers_or_connectors() -> TestResult {
|
||||
async fn selected_plugin_package_is_contributed_without_servers() -> TestResult {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let plugin_root = tempfile::tempdir()?;
|
||||
std::fs::create_dir_all(plugin_root.path().join(".codex-plugin"))?;
|
||||
@@ -178,7 +168,6 @@ async fn selected_plugin_package_is_contributed_without_servers_or_connectors()
|
||||
plugin_id,
|
||||
plugin_display_name: contribution.plugin_display_name,
|
||||
source_environment_id: contribution.source_environment_id,
|
||||
connector_ids: contribution.connector_ids,
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
@@ -187,7 +176,6 @@ async fn selected_plugin_package_is_contributed_without_servers_or_connectors()
|
||||
plugin_id: "selected-root".to_string(),
|
||||
plugin_display_name: "Skill Only".to_string(),
|
||||
source_environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
connector_ids: Vec::new(),
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
@@ -235,7 +223,6 @@ async fn denied_malformed_plugin_retains_identity_without_capabilities() -> Test
|
||||
vec![(
|
||||
("selected-root".to_string(), "selected-root".to_string()),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
)]
|
||||
} else {
|
||||
Vec::new()
|
||||
@@ -248,7 +235,6 @@ async fn denied_malformed_plugin_retains_identity_without_capabilities() -> Test
|
||||
.map(|(root_id, plugin_id, contribution)| (
|
||||
(root_id, plugin_id),
|
||||
contribution.servers,
|
||||
contribution.connector_ids,
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
expected
|
||||
@@ -395,7 +381,6 @@ async fn selected_root_ownership_retries_errors_and_caches_success() -> TestResu
|
||||
.into_iter()
|
||||
.map(|(name, _)| name)
|
||||
.collect::<Vec<_>>(),
|
||||
contribution.connector_ids,
|
||||
));
|
||||
}
|
||||
assert_eq!(
|
||||
@@ -405,7 +390,6 @@ async fn selected_root_ownership_retries_errors_and_caches_success() -> TestResu
|
||||
.map(|(id, servers)| (
|
||||
id.to_string(),
|
||||
servers.into_iter().map(str::to_string).collect::<Vec<_>>(),
|
||||
Vec::new(),
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
"phase {phase}",
|
||||
@@ -430,13 +414,15 @@ async fn managed_plugins_requirement_disables_selected_plugin_capabilities() ->
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.cloud_config_bundle(
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement(
|
||||
.loader_overrides(
|
||||
(ManagedConfigFixture::requirements(
|
||||
r#"
|
||||
[features]
|
||||
plugins = false
|
||||
"#,
|
||||
),
|
||||
))
|
||||
.loader_overrides_for_tests(codex_home.path())
|
||||
.expect("write managed config fixture"),
|
||||
)
|
||||
.build()
|
||||
.await?;
|
||||
@@ -692,43 +678,22 @@ async fn raw_selected_plugin_contributions(
|
||||
Ok(contributions)
|
||||
}
|
||||
|
||||
struct CloudCatalogFixture {
|
||||
reply: Result<PluginCatalog, String>,
|
||||
calls: AtomicUsize,
|
||||
}
|
||||
|
||||
impl PluginProvider for CloudCatalogFixture {
|
||||
fn list(&self, _query: PluginListQuery) -> PluginProviderFuture<'_, PluginCatalog> {
|
||||
Box::pin(async {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
self.reply.clone().map_err(PluginProviderError::Message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloud_plugins_append_apps_without_changing_executor_tools() -> anyhow::Result<()> {
|
||||
fn installed_executor_plugin_exposes_and_calls_its_mcp_tools() -> anyhow::Result<()> {
|
||||
run_test_with_large_stack(
|
||||
"cloud-plugin-projection",
|
||||
run_cloud_plugin_projection_scenarios,
|
||||
"executor-plugin-projection",
|
||||
run_executor_plugin_projection_scenarios,
|
||||
)
|
||||
}
|
||||
|
||||
async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
async fn run_executor_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
core_test_support::skip_if_remote!(Ok(()), "V1 plugin fixtures use host-local files");
|
||||
// Fresh sessions keep unavailable-cloud fallback independent of a previously cached catalog.
|
||||
for (case, installed, cloud_enabled, cloud_available, cloud_empty) in [
|
||||
("cloud_only", false, true, true, false),
|
||||
("cloud_and_executor", true, true, true, false),
|
||||
("unavailable_cloud", true, true, false, false),
|
||||
("rollout_disabled", true, false, true, false),
|
||||
("empty_cloud", true, true, true, true),
|
||||
] {
|
||||
// Uninstalled plugins must not start MCPs; installed ones expose and run their tools.
|
||||
for (case, installed) in [("not_installed", false), ("installed", true)] {
|
||||
let server = start_mock_server().await;
|
||||
let apps = AppsTestServer::mount(&server).await?;
|
||||
let plugin_server = start_mock_server().await;
|
||||
let plugin_mcp = AppsTestServer::mount_with_tools(
|
||||
let plugin_mcp = McpTestServer::mount_with_tools(
|
||||
&plugin_server,
|
||||
Arc::new(std::sync::Mutex::new(vec![json!({
|
||||
"name": "echo", "description": "Echo a note.",
|
||||
@@ -749,56 +714,24 @@ async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
})
|
||||
.with_priority(1)
|
||||
.mount(&plugin_server).await;
|
||||
let declaration =
|
||||
json!({"url": format!("{}/api/codex/ps/mcp", plugin_mcp.chatgpt_base_url)});
|
||||
let cloud = Arc::new(CloudCatalogFixture {
|
||||
reply: if cloud_empty {
|
||||
Ok(PluginCatalog::default())
|
||||
} else if cloud_available {
|
||||
Ok(PluginCatalog {
|
||||
entries: vec![PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: "plugin_notes".into(),
|
||||
},
|
||||
display_name: "Cloud Notes".into(),
|
||||
version: "1".into(),
|
||||
mcp_servers: [("notes".into(), declaration.clone())].into(),
|
||||
connector_ids: vec!["calendar".into()],
|
||||
locations: vec![PluginSourceLocation::Cloud {
|
||||
resource_uri: "plugin://plugin_notes".into(),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
})
|
||||
} else {
|
||||
Err("plugin-service unavailable".into())
|
||||
},
|
||||
calls: AtomicUsize::new(0),
|
||||
});
|
||||
let declaration = json!({"url": plugin_mcp.mcp_url()});
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
let mut providers = PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
let providers = PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
))));
|
||||
if cloud_enabled {
|
||||
providers = providers.with_cloud_provider(cloud.clone());
|
||||
}
|
||||
install_plugin_providers(&mut extensions, providers);
|
||||
let mut builder = test_codex()
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_auth(CodexAuth::from_api_key("Test API Key"))
|
||||
.with_model_info_override("gpt-5.5", |model| model.supports_search_tool = false)
|
||||
.with_config(move |config| {
|
||||
assert!(config.features.enable(Feature::Plugins).is_ok());
|
||||
assert!(config.features.enable(Feature::Apps).is_ok());
|
||||
assert!(
|
||||
config
|
||||
.features
|
||||
.enable(Feature::ExecutorCapabilityDiscovery)
|
||||
.is_ok()
|
||||
);
|
||||
config.chatgpt_base_url = apps.chatgpt_base_url;
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
if installed {
|
||||
@@ -887,7 +820,7 @@ async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
"{case}: {output}"
|
||||
);
|
||||
}
|
||||
let calls = recorded_apps_tool_calls(&plugin_server).await;
|
||||
let calls = recorded_mcp_tool_calls(&plugin_server).await;
|
||||
assert_eq!(calls.len(), usize::from(installed), "{case}");
|
||||
if installed {
|
||||
assert_eq!(calls[0]["params"]["name"], "echo");
|
||||
@@ -907,34 +840,7 @@ async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
});
|
||||
assert_eq!(
|
||||
initialized, installed,
|
||||
"{case}: cloud-only declarations must not start MCPs"
|
||||
);
|
||||
// Failed discovery stays in cooldown across both model steps.
|
||||
assert_eq!(
|
||||
cloud.calls.load(Ordering::SeqCst),
|
||||
usize::from(cloud_enabled),
|
||||
"{case}"
|
||||
);
|
||||
let state = test
|
||||
.codex
|
||||
.thread_extension_data()
|
||||
.get::<PluginsThreadState>()
|
||||
.context("plugin state missing")?;
|
||||
assert_eq!(
|
||||
state.cloud_catalog().is_some(),
|
||||
cloud_enabled && cloud_available,
|
||||
"{case}"
|
||||
);
|
||||
let calendar = requests[0]
|
||||
.tool_by_name("mcp__codex_apps__calendar", "_list_events")
|
||||
.context("Calendar tool missing")?;
|
||||
assert_eq!(
|
||||
calendar["description"]
|
||||
.as_str()
|
||||
.context("Apps description missing")?
|
||||
.contains("Cloud Notes"),
|
||||
cloud_enabled && cloud_available && !cloud_empty,
|
||||
"{case}"
|
||||
"{case}: uninstalled declarations must not start MCPs"
|
||||
);
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
}
|
||||
|
||||
@@ -40,7 +40,6 @@ async fn copy_file_transfers_between_selected_and_native_executors() -> Result<(
|
||||
)
|
||||
.expect("fixture config layers");
|
||||
config.model_catalog = Some(bundled_models_response().expect("bundled model catalog"));
|
||||
config.cloud_skill_enabled = false;
|
||||
})
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
|
||||
@@ -13,7 +13,6 @@ use crate::step_state::SkillToolAuthoritySelector;
|
||||
|
||||
fn alias_prefix(source: &SkillSourceKind) -> Option<&'static str> {
|
||||
match source {
|
||||
SkillSourceKind::Cloud => Some("c"),
|
||||
SkillSourceKind::Executor => Some("e"),
|
||||
SkillSourceKind::Host => Some("r"),
|
||||
SkillSourceKind::Custom(_) => None,
|
||||
@@ -42,7 +41,6 @@ impl From<String> for SkillLocator {
|
||||
}
|
||||
index.parse::<usize>().ok()?;
|
||||
[
|
||||
SkillSourceKind::Cloud,
|
||||
SkillSourceKind::Executor,
|
||||
SkillSourceKind::Host,
|
||||
]
|
||||
@@ -89,7 +87,6 @@ impl SkillAliasState {
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for (kind, root) in roots {
|
||||
let selector = match kind {
|
||||
SkillSourceKind::Cloud => SkillToolAuthoritySelector::Cloud,
|
||||
SkillSourceKind::Executor => SkillToolAuthoritySelector::Executor,
|
||||
SkillSourceKind::Host | SkillSourceKind::Custom(_) => continue,
|
||||
};
|
||||
@@ -102,7 +99,6 @@ impl SkillAliasState {
|
||||
/// Thread-wide assignments, captured alongside each step's catalog.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct SkillCatalogAliases {
|
||||
cloud: Arc<AliasPlan>,
|
||||
executor: Arc<AliasPlan>,
|
||||
budget: AliasBudget,
|
||||
}
|
||||
@@ -110,7 +106,6 @@ pub(crate) struct SkillCatalogAliases {
|
||||
impl SkillCatalogAliases {
|
||||
pub(crate) fn resolve(&self, locator: &SkillLocator) -> Option<String> {
|
||||
let plan = match locator.alias_source() {
|
||||
Some(SkillSourceKind::Cloud) => &self.cloud,
|
||||
Some(SkillSourceKind::Executor) => &self.executor,
|
||||
Some(SkillSourceKind::Host | SkillSourceKind::Custom(_)) | None => return None,
|
||||
};
|
||||
@@ -123,7 +118,6 @@ impl SkillCatalogAliases {
|
||||
roots: impl IntoIterator<Item = &'a str>,
|
||||
) {
|
||||
let (plan, prefix) = match selector {
|
||||
SkillToolAuthoritySelector::Cloud => (&mut self.cloud, "c"),
|
||||
SkillToolAuthoritySelector::Executor => (&mut self.executor, "e"),
|
||||
};
|
||||
plan.extend_alias_plan(prefix, roots, &mut self.budget);
|
||||
@@ -131,7 +125,6 @@ impl SkillCatalogAliases {
|
||||
|
||||
pub(crate) fn for_authority(&self, selector: SkillToolAuthoritySelector) -> &AliasPlan {
|
||||
match selector {
|
||||
SkillToolAuthoritySelector::Cloud => &self.cloud,
|
||||
SkillToolAuthoritySelector::Executor => &self.executor,
|
||||
}
|
||||
}
|
||||
@@ -140,7 +133,7 @@ impl SkillCatalogAliases {
|
||||
const MAX_ALIAS_ROOTS: usize = 2_048;
|
||||
const MAX_ALIAS_BYTES: usize = 16 * 1024;
|
||||
|
||||
/// Shared bound on thread-local Cloud/executor alias assignments and their rendered mappings.
|
||||
/// Shared bound on thread-local executor alias assignments and their rendered mappings.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct AliasBudget {
|
||||
roots: usize,
|
||||
|
||||
@@ -52,12 +52,6 @@ fn shortens_filesystem_and_skill_resource_locators() {
|
||||
"skill://executor/workspace/skills/alpha/SKILL.md",
|
||||
"e0/alpha/SKILL.md",
|
||||
),
|
||||
(
|
||||
SkillSourceKind::Cloud,
|
||||
"skill://plugin",
|
||||
"skill://plugin/alpha",
|
||||
"c0/alpha",
|
||||
),
|
||||
] {
|
||||
let plan = AliasPlan::build(&source, &[root, root]).expect("alias plan should build");
|
||||
|
||||
@@ -104,7 +98,7 @@ fn aliases_roots_used_by_only_one_skill() {
|
||||
#[test]
|
||||
fn locator_serde_recognizes_aliases_and_preserves_package_strings() {
|
||||
for (value, expected_source) in [
|
||||
("c0/release", Some(SkillSourceKind::Cloud)),
|
||||
("c0/release", None),
|
||||
("e12/references/details.md", Some(SkillSourceKind::Executor)),
|
||||
("r1/release/SKILL.md", Some(SkillSourceKind::Host)),
|
||||
("skill://Plugin_123/release", None),
|
||||
@@ -152,18 +146,18 @@ fn appended_aliases_preserve_captured_steps_and_existing_locators() {
|
||||
|
||||
#[test]
|
||||
fn alias_number_and_byte_budgets_are_shared_without_reassigning_existing_roots() {
|
||||
let mut cloud = std::sync::Arc::new(AliasPlan::default());
|
||||
let mut other = std::sync::Arc::new(AliasPlan::default());
|
||||
let mut executor = std::sync::Arc::new(AliasPlan::default());
|
||||
let mut budget = super::AliasBudget {
|
||||
roots: super::MAX_ALIAS_ROOTS - 2,
|
||||
..Default::default()
|
||||
};
|
||||
cloud.extend_alias_plan("c", ["skill://cloud"], &mut budget);
|
||||
other.extend_alias_plan("r", ["skill://other"], &mut budget);
|
||||
executor.extend_alias_plan("e", ["skill://first", "skill://second"], &mut budget);
|
||||
assert_eq!(budget.roots, super::MAX_ALIAS_ROOTS);
|
||||
assert_eq!(executor.root_lines(), vec!["- `e0` = `skill://first`"]);
|
||||
assert_eq!(executor.shorten("skill://second/demo"), None);
|
||||
assert_eq!(cloud.shorten("skill://cloud/demo"), Some("c0/demo".into()));
|
||||
assert_eq!(other.shorten("skill://other/demo"), Some("r0/demo".into()));
|
||||
|
||||
let mut budget = super::AliasBudget::default();
|
||||
let mut aliases = std::sync::Arc::new(AliasPlan::default());
|
||||
|
||||
@@ -14,8 +14,6 @@ pub enum SkillSourceKind {
|
||||
Host,
|
||||
/// Skills owned by an execution environment.
|
||||
Executor,
|
||||
/// Skills owned by the cloud rather than an execution environment.
|
||||
Cloud,
|
||||
/// Extension-private source kind for future providers that do not fit an
|
||||
/// existing transport category.
|
||||
Custom(String),
|
||||
@@ -30,7 +28,6 @@ impl SkillSourceKind {
|
||||
match self {
|
||||
Self::Host => "host",
|
||||
Self::Executor => "executor",
|
||||
Self::Cloud => "cloud",
|
||||
Self::Custom(kind) => kind,
|
||||
}
|
||||
}
|
||||
@@ -306,7 +303,7 @@ impl SkillCatalogEntry {
|
||||
|
||||
pub(crate) fn unaliased_locator(&self) -> &str {
|
||||
match &self.authority.kind {
|
||||
SkillSourceKind::Executor | SkillSourceKind::Cloud => self.id.0.as_str(),
|
||||
SkillSourceKind::Executor => self.id.0.as_str(),
|
||||
SkillSourceKind::Host | SkillSourceKind::Custom(_) => self.rendered_path(),
|
||||
}
|
||||
}
|
||||
@@ -374,40 +371,27 @@ impl SkillCatalog {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies plugin denials and requires accepted Cloud or executor roots before merging skills.
|
||||
/// Applies plugin denials and requires accepted executor roots before merging skills.
|
||||
pub(crate) fn apply_plugin_denials(catalog: &mut SkillCatalog, snapshot: &SelectedPluginSnapshot) {
|
||||
for skill in &mut catalog.entries {
|
||||
if !matches!(
|
||||
skill.authority.kind,
|
||||
SkillSourceKind::Cloud | SkillSourceKind::Executor
|
||||
) {
|
||||
if skill.authority.kind != SkillSourceKind::Executor {
|
||||
continue;
|
||||
}
|
||||
// Standalone skills do not require plugin acceptance.
|
||||
if skill.remote_plugin_id.is_none() && skill.plugin_id.is_none() {
|
||||
continue;
|
||||
}
|
||||
let accepted = if skill.authority.kind == SkillSourceKind::Executor {
|
||||
let (Some(environment_id), Some(plugin_id)) =
|
||||
(skill.main_prompt.environment_id(), &skill.plugin_id)
|
||||
else {
|
||||
skill.enabled = false;
|
||||
continue;
|
||||
};
|
||||
let root_id = format!("{environment_id}:{plugin_id}");
|
||||
snapshot
|
||||
.plugins
|
||||
.iter()
|
||||
.any(|plugin| plugin.selected_root_id.as_deref() == Some(root_id.as_str()))
|
||||
} else {
|
||||
let Some(remote_plugin_id) = &skill.remote_plugin_id else {
|
||||
skill.enabled = false;
|
||||
continue;
|
||||
};
|
||||
snapshot.plugins.iter().any(|plugin| {
|
||||
plugin.selected_root_id.is_none() && plugin.plugin_id.as_str() == remote_plugin_id
|
||||
})
|
||||
let (Some(environment_id), Some(plugin_id)) =
|
||||
(skill.main_prompt.environment_id(), &skill.plugin_id)
|
||||
else {
|
||||
skill.enabled = false;
|
||||
continue;
|
||||
};
|
||||
let root_id = format!("{environment_id}:{plugin_id}");
|
||||
let accepted = snapshot
|
||||
.plugins
|
||||
.iter()
|
||||
.any(|plugin| plugin.selected_root_id.as_deref() == Some(root_id.as_str()));
|
||||
skill.enabled &= skill
|
||||
.remote_plugin_id
|
||||
.as_ref()
|
||||
@@ -420,54 +404,6 @@ pub(crate) fn apply_plugin_denials(catalog: &mut SkillCatalog, snapshot: &Select
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_key(entry: &SkillCatalogEntry) -> Option<(&str, &str)> {
|
||||
Some((entry.remote_plugin_id.as_deref()?, entry.name.as_str()))
|
||||
}
|
||||
|
||||
/// Merges available Cloud counterparts, disabling unmatched remote skills only when Cloud is complete.
|
||||
pub fn merge_catalogs(cloud: Option<SkillCatalog>, executor: SkillCatalog) -> SkillCatalog {
|
||||
let Some(mut merged) = cloud else {
|
||||
return executor;
|
||||
};
|
||||
let cloud_is_partial = merged.is_partial;
|
||||
merged.is_partial |= executor.is_partial;
|
||||
let cloud_entry_count = merged.entries.len();
|
||||
merged.warnings.extend(executor.warnings);
|
||||
for mut entry in executor.entries {
|
||||
let Some(key) = remote_key(&entry) else {
|
||||
merged.entries.push(entry);
|
||||
continue;
|
||||
};
|
||||
// Executor entries cannot authorize or merge with one another.
|
||||
let Some(cloud_entry) = merged.entries[..cloud_entry_count]
|
||||
.iter_mut()
|
||||
.find(|cloud_entry| remote_key(cloud_entry) == Some(key))
|
||||
else {
|
||||
if !cloud_is_partial {
|
||||
entry.enabled = false;
|
||||
for source in &mut entry.sources {
|
||||
source.enabled = false;
|
||||
}
|
||||
}
|
||||
merged.entries.push(entry);
|
||||
continue;
|
||||
};
|
||||
let primary_source = entry.primary_source();
|
||||
for mut source in std::iter::once(primary_source).chain(entry.sources) {
|
||||
source.enabled &= cloud_entry.enabled;
|
||||
let already_present = cloud_entry.sources.iter().any(|existing| {
|
||||
existing.authority == source.authority
|
||||
&& existing.package == source.package
|
||||
&& existing.main_prompt.environment_id() == source.main_prompt.environment_id()
|
||||
});
|
||||
if !already_present {
|
||||
cloud_entry.sources.push(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// Contents returned after resolving a skill resource through its owner.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SkillReadResult {
|
||||
@@ -511,7 +447,3 @@ impl std::fmt::Display for SkillProviderError {
|
||||
impl std::error::Error for SkillProviderError {}
|
||||
|
||||
pub type SkillProviderResult<T> = Result<T, SkillProviderError>;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "catalog_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -26,7 +26,6 @@ use crate::render::SkillMetadataBudget;
|
||||
use crate::render::SkillRenderReport;
|
||||
use crate::render::aliased_metadata_overhead_cost;
|
||||
use crate::render::metadata_line_cost;
|
||||
use crate::world_state_catalogs::CatalogBudgetAllocation;
|
||||
|
||||
const SNAPSHOT_VERSION: u8 = 1;
|
||||
const ROOTS_HEADING: &str =
|
||||
@@ -92,14 +91,12 @@ struct CatalogSnapshot {
|
||||
omit_descriptions: bool,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
tracks_grants: bool,
|
||||
allocation: Option<CatalogBudgetAllocation>,
|
||||
}
|
||||
|
||||
pub(crate) struct CatalogDelta {
|
||||
pub(crate) rendered: Option<AvailableSkillsRender>,
|
||||
pub(crate) include_usage: bool,
|
||||
pub(crate) tracks_grants: bool,
|
||||
pub(crate) allocation: Option<CatalogBudgetAllocation>,
|
||||
}
|
||||
|
||||
struct CatalogResult {
|
||||
@@ -151,7 +148,6 @@ pub(crate) fn skills_delta_section(
|
||||
fn build_initial_catalog(source: &str, catalog: CatalogDelta) -> CatalogResult {
|
||||
let mut snapshot = CatalogSnapshot {
|
||||
version: SNAPSHOT_VERSION,
|
||||
allocation: catalog.allocation,
|
||||
tracks_grants: catalog.tracks_grants,
|
||||
..CatalogSnapshot::default()
|
||||
};
|
||||
@@ -277,7 +273,6 @@ fn build_catalog_update(
|
||||
}
|
||||
previous.entries = entries;
|
||||
previous.instructions_sent |= body.is_some();
|
||||
previous.allocation = catalog.allocation;
|
||||
CatalogResult {
|
||||
snapshot: previous,
|
||||
report,
|
||||
|
||||
@@ -5,7 +5,7 @@ use pretty_assertions::assert_eq;
|
||||
fn update_spends_budget_only_on_accepted_rows_and_their_new_roots() {
|
||||
let mut draft = UpdateDraft {
|
||||
message: CatalogMessage::Update {
|
||||
heading: "\n## Cloud skills update\n".to_string(),
|
||||
heading: "\n## Selected-environment skills update\n".to_string(),
|
||||
},
|
||||
skill_lines: Vec::new(),
|
||||
root_lines: Vec::new(),
|
||||
@@ -23,12 +23,12 @@ fn update_spends_budget_only_on_accepted_rows_and_their_new_roots() {
|
||||
}),
|
||||
};
|
||||
let notes = skill(
|
||||
"- release-notes: (cloud package: c0/notes)",
|
||||
"c0",
|
||||
"- release-notes: (executor package: e0/notes)",
|
||||
"e0",
|
||||
"skill://writing",
|
||||
);
|
||||
let docs = skill("- docs: (cloud package: c0/docs)", "c0", "skill://writing");
|
||||
let expected = "\n## Cloud skills update\n### Skill roots\nThese mappings replace earlier mappings for the same aliases.\n- `c0` = `skill://writing`\n### Added or updated skills:\n- release-notes: (cloud package: c0/notes)\n- docs: (cloud package: c0/docs)\n";
|
||||
let docs = skill("- docs: (executor package: e0/docs)", "e0", "skill://writing");
|
||||
let expected = "\n## Selected-environment skills update\n### Skill roots\nThese mappings replace earlier mappings for the same aliases.\n- `e0` = `skill://writing`\n### Added or updated skills:\n- release-notes: (executor package: e0/notes)\n- docs: (executor package: e0/docs)\n";
|
||||
let mut remaining = SkillMetadataBudget::Characters(expected.chars().count());
|
||||
let mut snapshot = CatalogSnapshot::default();
|
||||
let large = skill(&"a".repeat(remaining.limit()), "c1", "skill://design");
|
||||
@@ -37,10 +37,10 @@ fn update_spends_budget_only_on_accepted_rows_and_their_new_roots() {
|
||||
assert!(draft.try_append_skill(¬es, &mut snapshot, &mut remaining));
|
||||
assert!(draft.try_append_skill(&docs, &mut snapshot, &mut remaining));
|
||||
|
||||
assert_eq!(draft.into_body("Cloud").as_deref(), Some(expected));
|
||||
assert_eq!(draft.into_body("Selected-environment").as_deref(), Some(expected));
|
||||
assert_eq!(
|
||||
snapshot.roots,
|
||||
BTreeMap::from([("c0".into(), "skill://writing".into())])
|
||||
BTreeMap::from([("e0".into(), "skill://writing".into())])
|
||||
);
|
||||
assert_eq!(snapshot.usage.characters, expected.chars().count());
|
||||
assert_eq!(remaining, SkillMetadataBudget::Characters(0));
|
||||
|
||||
@@ -51,7 +51,7 @@ impl SkillPromptKind {
|
||||
pub(crate) fn for_aliased_source(source: &SkillSourceKind) -> Self {
|
||||
match source {
|
||||
SkillSourceKind::Host => Self::HostAliases,
|
||||
SkillSourceKind::Executor | SkillSourceKind::Cloud => Self::ResourceAliases,
|
||||
SkillSourceKind::Executor => Self::ResourceAliases,
|
||||
SkillSourceKind::Custom(_) => Self::Unaliased,
|
||||
}
|
||||
}
|
||||
@@ -119,7 +119,7 @@ pub(crate) fn render_available_skills_body(
|
||||
}
|
||||
if skill_lines
|
||||
.iter()
|
||||
.any(|line| line.contains("(executor package: ") || line.contains("(cloud package: "))
|
||||
.any(|line| line.contains("(executor package: "))
|
||||
{
|
||||
lines.push(
|
||||
"Read a skill package directly with `skills.read({\"package\":\"<package>\"})` to read its `SKILL.md`; root aliases are resolved automatically. To read another file from that skill, use the same `package` and pass the file's complete `skill://` identifier as `resource`. If the package is not provided, use `skills.list` to find it."
|
||||
|
||||
@@ -1,27 +1,13 @@
|
||||
//! Reusable provider catalog caches and Cloud resource contents.
|
||||
//! Reusable provider catalog caches.
|
||||
//! Provider catalogs remain unfiltered until step preparation applies policy.
|
||||
//! Cloud discovery publishes only into its current auth and resource generation.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_exec_server::EnvironmentAccessKey;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoverySnapshot;
|
||||
use codex_extension_api::CatalogRefreshBackoff;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_mcp::McpResourceClientAuthKey;
|
||||
use codex_mcp::McpResourceServerCacheKey;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
|
||||
use crate::catalog::SkillAuthority;
|
||||
use crate::catalog::SkillCatalog;
|
||||
use crate::catalog::SkillPackageId;
|
||||
use crate::catalog::SkillReadResult;
|
||||
use crate::catalog::SkillResourceId;
|
||||
use crate::provider::SkillReadRequest;
|
||||
|
||||
const MAX_CACHED_CLOUD_RESOURCES: usize = 100;
|
||||
const MAX_CACHED_CLOUD_CONTENT_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
/// Reusable provider catalogs, before step-specific plugin policy and merging.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -32,72 +18,6 @@ pub(crate) struct SkillCatalogState {
|
||||
pub(crate) executor_discovery_cache: Option<CachedExecutorDiscoveryCatalog>,
|
||||
// DiscoveryV2.
|
||||
pub(crate) executor_v2_cache: Option<CachedExecutorV2Catalog>,
|
||||
// Shared by both discovery modes.
|
||||
pub(crate) cloud_generation: Option<Arc<CloudSkillGeneration>>,
|
||||
pub(crate) cloud_retry: Option<CatalogRefreshBackoff>,
|
||||
pub(crate) cloud_resources: CloudResourceCache,
|
||||
}
|
||||
|
||||
impl SkillCatalogState {
|
||||
/// Reuses the auth scope or replaces it, clearing contents from the previous scope.
|
||||
pub(crate) fn prepare_cloud_generation(
|
||||
&mut self,
|
||||
mcp_resources: Option<&McpResourceClient>,
|
||||
) -> Arc<CloudSkillGeneration> {
|
||||
let auth_cache_key = mcp_resources
|
||||
.map(|client| client.auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME));
|
||||
if let Some(generation) = self
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.filter(|generation| generation.auth_cache_key == auth_cache_key)
|
||||
{
|
||||
return Arc::clone(generation);
|
||||
}
|
||||
|
||||
let generation = Arc::new(CloudSkillGeneration {
|
||||
auth_cache_key,
|
||||
resource_cache_key: None,
|
||||
mcp_resources: mcp_resources.cloned(),
|
||||
catalog: None,
|
||||
});
|
||||
self.cloud_generation = Some(Arc::clone(&generation));
|
||||
self.cloud_resources = CloudResourceCache::default();
|
||||
generation
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps cloud metadata within one published auth scope and Apps availability state.
|
||||
/// Warning-free discovery is reused until the Apps resource generation changes.
|
||||
/// A published refresh replaces the Arc so late reads cannot populate its successor.
|
||||
pub(crate) struct CloudSkillGeneration {
|
||||
pub(crate) auth_cache_key: Option<McpResourceClientAuthKey>,
|
||||
pub(crate) resource_cache_key: Option<McpResourceServerCacheKey>,
|
||||
pub(crate) mcp_resources: Option<McpResourceClient>,
|
||||
pub(crate) catalog: Option<SkillCatalog>,
|
||||
}
|
||||
|
||||
impl CloudSkillGeneration {
|
||||
pub(crate) fn current_resource_cache_key(&self) -> Option<McpResourceServerCacheKey> {
|
||||
self.mcp_resources
|
||||
.as_ref()
|
||||
.and_then(|client| client.server_cache_key(codex_mcp::CODEX_APPS_MCP_SERVER_NAME))
|
||||
}
|
||||
|
||||
pub(crate) fn is_auth_current(&self) -> bool {
|
||||
self.auth_cache_key
|
||||
== self.mcp_resources.as_ref().map(|client| {
|
||||
client.auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CloudSkillGeneration {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("CloudSkillGeneration")
|
||||
.field("catalog", &self.catalog)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Reuses the projection of unchanged successful V2 inventories, before plugin policy.
|
||||
@@ -180,66 +100,3 @@ impl CachedExecutorDiscoveryCatalog {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct SkillReadCacheKey {
|
||||
authority: SkillAuthority,
|
||||
package: SkillPackageId,
|
||||
pub(crate) resource: SkillResourceId,
|
||||
}
|
||||
|
||||
impl From<&SkillReadRequest<'_>> for SkillReadCacheKey {
|
||||
fn from(request: &SkillReadRequest<'_>) -> Self {
|
||||
Self {
|
||||
authority: request.authority.clone(),
|
||||
package: request.package.clone(),
|
||||
resource: request.resource.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct CloudResourceCache {
|
||||
entries: HashMap<SkillReadCacheKey, SkillReadResult>,
|
||||
contents_bytes: usize,
|
||||
}
|
||||
|
||||
impl CloudResourceCache {
|
||||
pub(crate) fn get(&self, key: &SkillReadCacheKey) -> Option<SkillReadResult> {
|
||||
self.entries.get(key).cloned()
|
||||
}
|
||||
|
||||
pub(crate) fn insert(
|
||||
&mut self,
|
||||
key: SkillReadCacheKey,
|
||||
result: SkillReadResult,
|
||||
) -> SkillReadResult {
|
||||
if let Some(cached) = self.entries.get(&key) {
|
||||
return cached.clone();
|
||||
}
|
||||
|
||||
let contents_bytes = result.contents.len();
|
||||
let Some(next_contents_bytes) = self.contents_bytes.checked_add(contents_bytes) else {
|
||||
return result;
|
||||
};
|
||||
if self.entries.len() >= MAX_CACHED_CLOUD_RESOURCES
|
||||
|| next_contents_bytes > MAX_CACHED_CLOUD_CONTENT_BYTES
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
self.contents_bytes = next_contents_bytes;
|
||||
self.entries.insert(key, result.clone());
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CloudResourceCache {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("CloudResourceCache")
|
||||
.field("entry_count", &self.entries.len())
|
||||
.field("contents_bytes", &self.contents_bytes)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
//! Tests partial Cloud reconciliation without changing source-specific enablement.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn skill(kind: SkillSourceKind, name: &str) -> SkillCatalogEntry {
|
||||
SkillCatalogEntry::new(
|
||||
SkillPackageId(format!("skill://{kind}/{name}")),
|
||||
SkillAuthority::new(kind.clone(), kind.to_string()),
|
||||
name,
|
||||
"",
|
||||
SkillResourceId::new(format!("skill://{kind}/{name}/SKILL.md")),
|
||||
)
|
||||
.with_remote_plugin_id(Some("plugin_a".to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_cloud_merges_matches_without_disabling_unmatched_installations() {
|
||||
for (cloud_is_partial, cloud_has_match) in [
|
||||
(None, false),
|
||||
(Some(false), false),
|
||||
(Some(true), false),
|
||||
(Some(false), true),
|
||||
(Some(true), true),
|
||||
] {
|
||||
for executor_is_partial in [false, true] {
|
||||
let cloud_entry = skill(SkillSourceKind::Cloud, "matched");
|
||||
let matched = skill(SkillSourceKind::Executor, "matched").disabled();
|
||||
let mut unmatched = skill(SkillSourceKind::Executor, "unmatched");
|
||||
let mut denied_source = unmatched.primary_source();
|
||||
denied_source.enabled = false;
|
||||
unmatched.sources.push(denied_source);
|
||||
let denied = skill(SkillSourceKind::Executor, "denied").disabled();
|
||||
let mut executor = SkillCatalog::default();
|
||||
executor.extend(SkillCatalog {
|
||||
entries: vec![matched.clone(), unmatched.clone(), denied.clone()],
|
||||
is_partial: executor_is_partial,
|
||||
..Default::default()
|
||||
});
|
||||
// Appending a complete provider must not clear an earlier partial result.
|
||||
executor.extend(SkillCatalog::default());
|
||||
let cloud = cloud_is_partial.map(|is_partial| SkillCatalog {
|
||||
entries: if cloud_has_match {
|
||||
vec![cloud_entry.clone()]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
is_partial,
|
||||
// Diagnostic warnings alone do not make membership incomplete.
|
||||
warnings: vec!["diagnostic".to_string()],
|
||||
});
|
||||
let expected_match = if cloud_has_match {
|
||||
let mut entry = cloud_entry;
|
||||
entry.sources.push(matched.primary_source());
|
||||
entry
|
||||
} else {
|
||||
matched
|
||||
};
|
||||
if cloud_is_partial == Some(false) {
|
||||
unmatched.enabled = false;
|
||||
}
|
||||
assert_eq!(
|
||||
merge_catalogs(cloud, executor),
|
||||
SkillCatalog {
|
||||
entries: vec![expected_match, unmatched, denied],
|
||||
warnings: if cloud_is_partial.is_some() {
|
||||
vec!["diagnostic".to_string()]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
is_partial: cloud_is_partial.unwrap_or(false) || executor_is_partial,
|
||||
},
|
||||
"cloud_is_partial={cloud_is_partial:?}, cloud_has_match={cloud_has_match}, executor_is_partial={executor_is_partial}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,620 +0,0 @@
|
||||
//! Tests cloud cache isolation, refresh retries, and late completion.
|
||||
|
||||
use super::*;
|
||||
use crate::catalog::SkillCatalogEntry;
|
||||
use crate::catalog::SkillResourceId;
|
||||
use crate::catalog::SkillSearchResult;
|
||||
use crate::provider::SkillProvider;
|
||||
use crate::provider::SkillProviderFuture;
|
||||
use crate::provider::SkillReadContext;
|
||||
use crate::provider::SkillSearchRequest;
|
||||
use codex_extension_api::CatalogRefreshInput;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionEventSink;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::ExtensionWarning;
|
||||
use codex_mcp::McpRuntime;
|
||||
use codex_protocol::protocol::Event;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Provider {
|
||||
reads: AtomicUsize,
|
||||
lists: AtomicUsize,
|
||||
fail_list: AtomicBool,
|
||||
partial_list: AtomicBool,
|
||||
next_catalog: Mutex<Option<SkillCatalog>>,
|
||||
pause_read: AtomicBool,
|
||||
pause_list: AtomicBool,
|
||||
entered: Notify,
|
||||
resume: Notify,
|
||||
}
|
||||
|
||||
impl SkillProvider for Provider {
|
||||
fn list<'a>(&'a self, _query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog> {
|
||||
Box::pin(async move {
|
||||
self.lists.fetch_add(1, Ordering::SeqCst);
|
||||
let fail = self.fail_list.swap(false, Ordering::SeqCst);
|
||||
let catalog = self
|
||||
.next_catalog
|
||||
.lock()
|
||||
.expect("test provider catalog mutex should not be poisoned")
|
||||
.take();
|
||||
if self.pause_list.swap(false, Ordering::SeqCst) {
|
||||
self.entered.notify_one();
|
||||
self.resume.notified().await;
|
||||
}
|
||||
if fail {
|
||||
return Err(SkillProviderError::new("discovery failed"));
|
||||
}
|
||||
if let Some(catalog) = catalog {
|
||||
return Ok(catalog);
|
||||
}
|
||||
let is_partial = self.partial_list.swap(false, Ordering::SeqCst);
|
||||
Ok(SkillCatalog {
|
||||
is_partial,
|
||||
warnings: if is_partial {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec!["account catalog".into()]
|
||||
},
|
||||
..Default::default()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn read<'a>(
|
||||
&'a self,
|
||||
request: SkillReadRequest<'a>,
|
||||
) -> SkillProviderFuture<'a, SkillReadResult> {
|
||||
let revision = self.reads.fetch_add(1, Ordering::SeqCst);
|
||||
Box::pin(async move {
|
||||
if self.pause_read.swap(false, Ordering::SeqCst) {
|
||||
self.entered.notify_one();
|
||||
self.resume.notified().await;
|
||||
}
|
||||
Ok(SkillReadResult {
|
||||
resource: request.resource,
|
||||
contents: format!("contents {revision}"),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn search(&self, _request: SkillSearchRequest) -> SkillProviderFuture<'_, SkillSearchResult> {
|
||||
Box::pin(async { Ok(SkillSearchResult::default()) })
|
||||
}
|
||||
}
|
||||
|
||||
fn state() -> SkillsThreadState {
|
||||
SkillsThreadState::new(
|
||||
SkillsExtensionConfig {
|
||||
include_instructions: true,
|
||||
catalog_deltas_enabled: false,
|
||||
omit_descriptions: false,
|
||||
max_context_tokens: None,
|
||||
bundled_skills_enabled: false,
|
||||
cloud_skill_enabled: true,
|
||||
shadow_selection_enabled: false,
|
||||
},
|
||||
/*cloud_skills_available*/ true,
|
||||
/*extension_metrics*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
fn client() -> Arc<McpResourceClient> {
|
||||
Arc::new(McpResourceClient::new(Arc::new(McpRuntime::empty(
|
||||
/*prefix_mcp_tool_names*/ false,
|
||||
))))
|
||||
}
|
||||
|
||||
fn query(client: Option<Arc<McpResourceClient>>) -> SkillListQuery<'static> {
|
||||
SkillListQuery {
|
||||
turn_id: "turn".into(),
|
||||
executor_roots: Vec::new(),
|
||||
host_snapshot: None,
|
||||
include_host_skills: false,
|
||||
include_bundled_skills: false,
|
||||
include_cloud_skills: true,
|
||||
mcp_resources: client,
|
||||
executor_capability_discovery: None,
|
||||
executor_capability_discovery_v2: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn request(client: Option<Arc<McpResourceClient>>) -> SkillReadRequest<'static> {
|
||||
SkillReadRequest {
|
||||
authority: SkillAuthority::new(SkillSourceKind::Cloud, "codex_apps"),
|
||||
package: SkillPackageId("skill://demo".into()),
|
||||
resource: SkillResourceId::new("skill://demo/SKILL.md"),
|
||||
context: SkillReadContext::Cloud {
|
||||
mcp_resources: client,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn frozen_cloud_catalog_and_reads_ignore_live_mcp_changes() {
|
||||
let state = state();
|
||||
let provider = crate::FrozenCloudSkillProvider::from_json(
|
||||
serde_json::json!({"skills": [{
|
||||
"package": "skill://demo/work", "name": "demo", "description": "Frozen skill",
|
||||
"alias_root": "skill://demo", "main_resource": "skill://demo/work/SKILL.md",
|
||||
"resources": {"skill://demo/work/SKILL.md": "Frozen contents"}
|
||||
}]})
|
||||
.to_string()
|
||||
.as_bytes(),
|
||||
)
|
||||
.expect("frozen cloud skill fixture should be valid");
|
||||
let providers = SkillProviders::new().with_cloud_provider(Arc::new(provider));
|
||||
let turn_store = ExtensionData::new("turn");
|
||||
state
|
||||
.refresh_cloud_catalog(&providers, query(Some(client())), &turn_store)
|
||||
.await
|
||||
.expect("cloud catalog refresh should succeed");
|
||||
assert!(
|
||||
turn_store
|
||||
.get::<LatestCloudSkillsAuth>()
|
||||
.expect("successful discovery should record its auth scope")
|
||||
.0
|
||||
.is_none()
|
||||
);
|
||||
let catalog = state
|
||||
.available_cloud_catalog()
|
||||
.expect("cloud catalog should be available after refresh");
|
||||
let generation = state
|
||||
.catalog_state
|
||||
.lock()
|
||||
.expect("catalog state mutex should not be poisoned")
|
||||
.cloud_generation
|
||||
.clone()
|
||||
.expect("initial refresh should publish a cloud generation");
|
||||
for mcp_resources in [Some(client()), None, Some(client())] {
|
||||
let request = SkillReadRequest {
|
||||
package: SkillPackageId("skill://demo/work".into()),
|
||||
resource: SkillResourceId::new("skill://demo/work/SKILL.md"),
|
||||
..request(mcp_resources.clone())
|
||||
};
|
||||
assert_eq!(
|
||||
state
|
||||
.read_skill(&providers, request)
|
||||
.await
|
||||
.expect("cloud skill read should succeed"),
|
||||
SkillReadResult {
|
||||
resource: SkillResourceId::new("skill://demo/work/SKILL.md"),
|
||||
contents: "Frozen contents".into(),
|
||||
}
|
||||
);
|
||||
state
|
||||
.refresh_cloud_catalog(&providers, query(mcp_resources), &turn_store)
|
||||
.await
|
||||
.expect("cloud catalog refresh should succeed");
|
||||
assert_eq!(state.available_cloud_catalog(), Some(catalog.clone()));
|
||||
assert!(Arc::ptr_eq(
|
||||
&generation,
|
||||
state
|
||||
.catalog_state
|
||||
.lock()
|
||||
.expect("catalog state mutex should not be poisoned")
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.expect("frozen cloud generation should remain available")
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn step_cloud_refresh_serializes_waiters_and_retries() {
|
||||
#[derive(Default)]
|
||||
struct WarningCounter(AtomicUsize);
|
||||
|
||||
impl ExtensionEventSink for WarningCounter {
|
||||
fn emit(&self, _event: Event) {}
|
||||
|
||||
fn emit_warning(&self, _warning: ExtensionWarning) {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
let cloud = Arc::new(Provider::default());
|
||||
let providers = SkillProviders::new().with_cloud_provider(cloud.clone());
|
||||
let session_store = ExtensionData::new("session");
|
||||
let thread_store = ExtensionData::new("thread");
|
||||
thread_store.insert(state());
|
||||
let thread_state = thread_store
|
||||
.get::<SkillsThreadState>()
|
||||
.expect("skills thread state should be initialized");
|
||||
let turn_store = ExtensionData::new("turn");
|
||||
let config = thread_state.config();
|
||||
let warnings = Arc::new(WarningCounter::default());
|
||||
let mut builder = ExtensionRegistryBuilder::with_event_sink(warnings.clone());
|
||||
crate::install_with_providers(&mut builder, providers, move |_: &()| config.clone());
|
||||
let registry = builder.build();
|
||||
let contributor = registry
|
||||
.turn_lifecycle_contributors()
|
||||
.iter()
|
||||
.find(|contributor| contributor.requires_mcp_runtime(&thread_store))
|
||||
.expect("cloud skills contributor should be registered");
|
||||
let refresh_input = CatalogRefreshInput {
|
||||
turn_id: "turn",
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
turn_store: &turn_store,
|
||||
};
|
||||
|
||||
for (index, delay) in [30, 60, 120, 240, 300, 300].into_iter().enumerate() {
|
||||
cloud.fail_list.store(true, Ordering::SeqCst);
|
||||
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
|
||||
assert_eq!(thread_state.available_cloud_catalog(), None);
|
||||
assert_eq!(cloud.lists.load(Ordering::SeqCst), index + 1);
|
||||
assert_eq!(warnings.0.load(Ordering::SeqCst), 1);
|
||||
tokio::time::advance(Duration::from_secs(delay - 1)).await;
|
||||
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
|
||||
assert_eq!(cloud.lists.load(Ordering::SeqCst), index + 1);
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
}
|
||||
cloud.pause_list.store(true, Ordering::SeqCst);
|
||||
let mut cancelled = contributor.refresh_catalog_for_step(refresh_input);
|
||||
assert!(futures::poll!(&mut cancelled).is_pending());
|
||||
drop(cancelled);
|
||||
*cloud
|
||||
.next_catalog
|
||||
.lock()
|
||||
.expect("test provider catalog mutex should not be poisoned") =
|
||||
Some(SkillCatalog::default());
|
||||
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
|
||||
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
|
||||
assert_eq!(cloud.lists.load(Ordering::SeqCst), 8);
|
||||
|
||||
// Waiting callers reuse success and share failures' cooldowns; cancellation allows retry.
|
||||
for (fails, cancelled) in [(false, false), (true, false), (false, true)] {
|
||||
session_store.insert(SkillsSessionState {
|
||||
mcp_resources: Some(client()),
|
||||
extension_metrics: None,
|
||||
});
|
||||
let previous_calls = cloud.lists.load(Ordering::SeqCst);
|
||||
let prewarm_store = ExtensionData::new("prewarm");
|
||||
let first_catalog = SkillCatalog {
|
||||
warnings: vec!["catalog warning".into()],
|
||||
..Default::default()
|
||||
};
|
||||
*cloud
|
||||
.next_catalog
|
||||
.lock()
|
||||
.expect("test provider catalog mutex should not be poisoned") =
|
||||
Some(first_catalog.clone());
|
||||
cloud.fail_list.store(fails, Ordering::SeqCst);
|
||||
cloud.pause_list.store(true, Ordering::SeqCst);
|
||||
let mut turn_start = contributor.refresh_catalog_for_step(refresh_input);
|
||||
assert!(futures::poll!(&mut turn_start).is_pending());
|
||||
let prewarm_input = CatalogRefreshInput {
|
||||
turn_id: "prewarm",
|
||||
turn_store: &prewarm_store,
|
||||
..refresh_input
|
||||
};
|
||||
let mut prewarm = contributor.refresh_catalog_for_step(prewarm_input);
|
||||
assert!(futures::poll!(&mut prewarm).is_pending());
|
||||
let mut cancelled_waiter = contributor.refresh_catalog_for_step(prewarm_input);
|
||||
assert!(futures::poll!(&mut cancelled_waiter).is_pending());
|
||||
drop(cancelled_waiter);
|
||||
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 1);
|
||||
*cloud
|
||||
.next_catalog
|
||||
.lock()
|
||||
.expect("test provider catalog mutex should not be poisoned") =
|
||||
Some(SkillCatalog::default());
|
||||
if cancelled {
|
||||
drop(turn_start);
|
||||
} else {
|
||||
cloud.resume.notify_one();
|
||||
assert!(!turn_start.await);
|
||||
}
|
||||
assert!(
|
||||
!tokio::time::timeout(std::time::Duration::from_secs(5), prewarm)
|
||||
.await
|
||||
.expect("waiting discovery should complete after its predecessor stops")
|
||||
);
|
||||
if fails {
|
||||
assert_eq!(thread_state.available_cloud_catalog(), None);
|
||||
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 1);
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
}
|
||||
assert_eq!(
|
||||
thread_state.available_cloud_catalog(),
|
||||
Some(if fails || cancelled {
|
||||
SkillCatalog::default()
|
||||
} else {
|
||||
first_catalog
|
||||
})
|
||||
);
|
||||
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
|
||||
assert_eq!(
|
||||
cloud.lists.load(Ordering::SeqCst),
|
||||
previous_calls + 1 + usize::from(fails || cancelled)
|
||||
);
|
||||
assert_eq!(warnings.0.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
// New turns share the thread's cooldown and failure progression.
|
||||
session_store.insert(SkillsSessionState {
|
||||
mcp_resources: Some(client()),
|
||||
extension_metrics: None,
|
||||
});
|
||||
let next_turn = ExtensionData::new("next turn");
|
||||
let previous_calls = cloud.lists.load(Ordering::SeqCst);
|
||||
for turn_store in [&turn_store, &next_turn] {
|
||||
cloud.fail_list.store(true, Ordering::SeqCst);
|
||||
assert!(
|
||||
!contributor
|
||||
.refresh_catalog_for_step(CatalogRefreshInput {
|
||||
turn_store,
|
||||
..refresh_input
|
||||
})
|
||||
.await
|
||||
);
|
||||
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 1);
|
||||
}
|
||||
assert_eq!(warnings.0.load(Ordering::SeqCst), 1);
|
||||
let next_input = CatalogRefreshInput {
|
||||
turn_id: "next turn",
|
||||
turn_store: &next_turn,
|
||||
..refresh_input
|
||||
};
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
assert!(!contributor.refresh_catalog_for_step(next_input).await);
|
||||
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 2);
|
||||
tokio::time::advance(Duration::from_secs(59)).await;
|
||||
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
|
||||
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 2);
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
assert!(!contributor.refresh_catalog_for_step(next_input).await);
|
||||
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 3);
|
||||
assert_eq!(warnings.0.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn late_read_cannot_return_or_populate_a_replaced_cache() {
|
||||
for replacement in [Some(client()), None] {
|
||||
let state = state();
|
||||
let provider = Arc::new(Provider::default());
|
||||
let providers = SkillProviders::new().with_cloud_provider(provider.clone());
|
||||
let original = Some(client());
|
||||
// None here exercises a successful per-turn refresh on the SAME generation.
|
||||
let replacement = replacement.or_else(|| original.clone());
|
||||
provider.pause_read.store(true, Ordering::SeqCst);
|
||||
let (late, ()) = tokio::join!(state.read_skill(&providers, request(original)), async {
|
||||
provider.entered.notified().await;
|
||||
state
|
||||
.refresh_cloud_catalog(
|
||||
&providers,
|
||||
query(replacement.clone()),
|
||||
&ExtensionData::new("turn"),
|
||||
)
|
||||
.await
|
||||
.expect("cloud catalog refresh should succeed");
|
||||
provider.resume.notify_one();
|
||||
});
|
||||
assert!(late.is_err());
|
||||
assert_eq!(
|
||||
state
|
||||
.read_skill(&providers, request(replacement))
|
||||
.await
|
||||
.expect("cloud skill read should succeed")
|
||||
.contents,
|
||||
"contents 1"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn late_discovery_cannot_publish_into_a_new_generation() {
|
||||
let state = state();
|
||||
let provider = Arc::new(Provider::default());
|
||||
let providers = SkillProviders::new().with_cloud_provider(provider.clone());
|
||||
provider.pause_list.store(true, Ordering::SeqCst);
|
||||
let turn_store = ExtensionData::new("turn");
|
||||
let (late, ()) = tokio::join!(
|
||||
state.refresh_cloud_catalog(&providers, query(Some(client())), &turn_store),
|
||||
async {
|
||||
provider.entered.notified().await;
|
||||
state
|
||||
.catalog_state
|
||||
.lock()
|
||||
.expect("catalog state mutex should not be poisoned")
|
||||
.prepare_cloud_generation(Some(&client()));
|
||||
provider.resume.notify_one();
|
||||
}
|
||||
);
|
||||
late.expect("superseded discovery should be discarded without an error");
|
||||
assert!(turn_store.get::<LatestCloudSkillsAuth>().is_none());
|
||||
assert!(
|
||||
state
|
||||
.catalog_state
|
||||
.lock()
|
||||
.expect("catalog state mutex should not be poisoned")
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.expect("replacement cloud generation should exist")
|
||||
.catalog
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn partial_cloud_catalog_without_warnings_is_refreshed_next_turn() {
|
||||
let state = state();
|
||||
let provider = Arc::new(Provider::default());
|
||||
provider.partial_list.store(true, Ordering::SeqCst);
|
||||
let providers = SkillProviders::new().with_cloud_provider(provider.clone());
|
||||
let client = Some(client());
|
||||
let turn_store = ExtensionData::new("turn");
|
||||
state
|
||||
.refresh_cloud_catalog(&providers, query(client.clone()), &turn_store)
|
||||
.await
|
||||
.expect("cloud catalog refresh should succeed");
|
||||
// Reuse partial catalogs for the rest of the turn.
|
||||
state
|
||||
.refresh_cloud_catalog(&providers, query(client.clone()), &turn_store)
|
||||
.await
|
||||
.expect("cloud catalog refresh should succeed");
|
||||
assert_eq!(provider.lists.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(
|
||||
state
|
||||
.available_cloud_catalog()
|
||||
.expect("cloud catalog should be available after refresh"),
|
||||
SkillCatalog {
|
||||
is_partial: true,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
state
|
||||
.refresh_cloud_catalog(
|
||||
&providers,
|
||||
query(client.clone()),
|
||||
&ExtensionData::new("next turn"),
|
||||
)
|
||||
.await
|
||||
.expect("cloud catalog refresh should succeed");
|
||||
assert_eq!(
|
||||
state
|
||||
.available_cloud_catalog()
|
||||
.expect("cloud catalog should be available after refresh"),
|
||||
SkillCatalog {
|
||||
is_partial: false,
|
||||
warnings: vec!["account catalog".into()],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
// Retry failures even when the previous catalog remains available.
|
||||
let retry_turn = ExtensionData::new("retry turn");
|
||||
provider.fail_list.store(true, Ordering::SeqCst);
|
||||
assert!(
|
||||
state
|
||||
.refresh_cloud_catalog(&providers, query(client.clone()), &retry_turn)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(state.available_cloud_catalog().is_some());
|
||||
assert!(retry_turn.get::<LatestCloudSkillsAuth>().is_none());
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
state
|
||||
.refresh_cloud_catalog(&providers, query(client), &retry_turn)
|
||||
.await
|
||||
.expect("cloud catalog refresh should succeed");
|
||||
assert_eq!(provider.lists.load(Ordering::SeqCst), 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cloud_refresh_preserves_complete_catalogs_only_within_the_same_auth_scope() {
|
||||
let catalog = |name: &str, is_partial| SkillCatalog {
|
||||
entries: vec![SkillCatalogEntry::new(
|
||||
SkillPackageId("skill://demo".into()),
|
||||
SkillAuthority::new(SkillSourceKind::Cloud, "codex_apps"),
|
||||
name,
|
||||
"test catalog",
|
||||
SkillResourceId::new("skill://demo/SKILL.md"),
|
||||
)],
|
||||
// Complete listings can have diagnostics; these also keep discovery eligible for refresh.
|
||||
warnings: vec![format!("{name} catalog diagnostic")],
|
||||
is_partial,
|
||||
};
|
||||
for previous_partial in [false, true] {
|
||||
for incoming_partial in [false, true] {
|
||||
for changed_auth in [false, true] {
|
||||
let state = state();
|
||||
let provider = Arc::new(Provider::default());
|
||||
let providers = SkillProviders::new().with_cloud_provider(provider.clone());
|
||||
let original_client = client();
|
||||
let mut previous = catalog("previous", previous_partial);
|
||||
*provider
|
||||
.next_catalog
|
||||
.lock()
|
||||
.expect("test provider catalog mutex should not be poisoned") =
|
||||
Some(previous.clone());
|
||||
state
|
||||
.refresh_cloud_catalog(
|
||||
&providers,
|
||||
query(Some(original_client.clone())),
|
||||
&ExtensionData::new("turn"),
|
||||
)
|
||||
.await
|
||||
.expect("cloud catalog refresh should succeed");
|
||||
let generation = state
|
||||
.catalog_state
|
||||
.lock()
|
||||
.expect("catalog state mutex should not be poisoned")
|
||||
.cloud_generation
|
||||
.clone()
|
||||
.expect("initial refresh should publish a cloud generation");
|
||||
let contents = state
|
||||
.read_skill(&providers, request(Some(original_client.clone())))
|
||||
.await
|
||||
.expect("cloud skill read should succeed");
|
||||
|
||||
let incoming = catalog("incoming", incoming_partial);
|
||||
*provider
|
||||
.next_catalog
|
||||
.lock()
|
||||
.expect("test provider catalog mutex should not be poisoned") =
|
||||
Some(incoming.clone());
|
||||
let current_client = if changed_auth {
|
||||
client()
|
||||
} else {
|
||||
original_client
|
||||
};
|
||||
state
|
||||
.refresh_cloud_catalog(
|
||||
&providers,
|
||||
query(Some(current_client.clone())),
|
||||
&ExtensionData::new("next turn"),
|
||||
)
|
||||
.await
|
||||
.expect("cloud catalog refresh should succeed");
|
||||
let retained = !changed_auth && !previous_partial && incoming_partial;
|
||||
assert_eq!(
|
||||
generation
|
||||
.catalog
|
||||
.as_ref()
|
||||
.expect("published generation should contain a catalog")
|
||||
.is_partial,
|
||||
previous_partial
|
||||
);
|
||||
if retained {
|
||||
previous.is_partial = true;
|
||||
}
|
||||
assert_eq!(
|
||||
state.available_cloud_catalog(),
|
||||
Some(if retained { previous } else { incoming })
|
||||
);
|
||||
assert!(!Arc::ptr_eq(
|
||||
&generation,
|
||||
state
|
||||
.catalog_state
|
||||
.lock()
|
||||
.expect("catalog state mutex should not be poisoned")
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.expect("refresh should publish a cloud generation")
|
||||
));
|
||||
assert_eq!(
|
||||
state
|
||||
.read_skill(&providers, request(Some(current_client)))
|
||||
.await
|
||||
.expect("cloud skill read should succeed")
|
||||
.contents,
|
||||
if retained {
|
||||
contents.contents
|
||||
} else {
|
||||
"contents 1".to_string()
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
//! Refreshes cloud skills at turn start and after auth changes.
|
||||
|
||||
use codex_extension_api::CatalogRefreshInput;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::TurnLifecycleContributor;
|
||||
use codex_extension_api::TurnStartInput;
|
||||
use codex_extension_api::TurnStartPhase;
|
||||
|
||||
use super::SkillsExtension;
|
||||
use crate::provider::SkillListQuery;
|
||||
use crate::state::LatestCloudSkillsAuth;
|
||||
use crate::state::SkillsSessionState;
|
||||
use crate::state::SkillsThreadState;
|
||||
|
||||
struct CloudDiscoveryWarningEmitted;
|
||||
|
||||
impl<C: Send + Sync + 'static> SkillsExtension<C> {
|
||||
async fn refresh_cloud_catalog(&self, input: CatalogRefreshInput<'_>) {
|
||||
let Some(state) = input.thread_store.get::<SkillsThreadState>() else {
|
||||
return;
|
||||
};
|
||||
if !state.cloud_skill_enabled() {
|
||||
return;
|
||||
}
|
||||
let config = state.config();
|
||||
let query = SkillListQuery {
|
||||
turn_id: input.turn_id.to_string(),
|
||||
executor_roots: Vec::new(),
|
||||
host_snapshot: None,
|
||||
include_host_skills: false,
|
||||
include_bundled_skills: config.bundled_skills_enabled,
|
||||
include_cloud_skills: true,
|
||||
mcp_resources: input
|
||||
.session_store
|
||||
.get::<SkillsSessionState>()
|
||||
.and_then(|state| state.mcp_resources.clone()),
|
||||
executor_capability_discovery: None,
|
||||
executor_capability_discovery_v2: None,
|
||||
};
|
||||
if let Err(error) = state
|
||||
.refresh_cloud_catalog(&self.providers, query, input.turn_store)
|
||||
.await
|
||||
&& input
|
||||
.turn_store
|
||||
.insert(CloudDiscoveryWarningEmitted)
|
||||
.is_none()
|
||||
{
|
||||
self.emit_warning(
|
||||
input.thread_store.level_id(),
|
||||
Some(input.turn_id),
|
||||
format!(
|
||||
"Cloud skill discovery failed; retaining any catalog from the same cloud auth scope: {error}"
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Send + Sync + 'static> TurnLifecycleContributor for SkillsExtension<C> {
|
||||
fn turn_start_phase(&self, thread_store: &ExtensionData) -> TurnStartPhase {
|
||||
if thread_store
|
||||
.get::<SkillsThreadState>()
|
||||
.is_some_and(|state| state.cloud_skill_enabled())
|
||||
{
|
||||
TurnStartPhase::RegularTaskStart
|
||||
} else {
|
||||
TurnStartPhase::BeforeTaskRegistration
|
||||
}
|
||||
}
|
||||
|
||||
fn requires_mcp_runtime(&self, thread_store: &ExtensionData) -> bool {
|
||||
self.turn_start_phase(thread_store) == TurnStartPhase::RegularTaskStart
|
||||
}
|
||||
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
input.turn_store.remove::<LatestCloudSkillsAuth>();
|
||||
self.refresh_cloud_catalog(CatalogRefreshInput {
|
||||
turn_id: input.turn_id,
|
||||
session_store: input.session_store,
|
||||
thread_store: input.thread_store,
|
||||
turn_store: input.turn_store,
|
||||
})
|
||||
.await;
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh_catalog_for_step<'a>(
|
||||
&'a self,
|
||||
input: CatalogRefreshInput<'a>,
|
||||
) -> ExtensionFuture<'a, bool> {
|
||||
Box::pin(async move {
|
||||
self.refresh_cloud_catalog(input).await;
|
||||
false
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,6 @@ pub struct SkillsExtensionConfig {
|
||||
pub max_context_tokens: Option<NonZeroUsize>,
|
||||
/// Whether bundled skills are eligible for discovery.
|
||||
pub bundled_skills_enabled: bool,
|
||||
/// Whether cloud skills are discovered and exposed to the model.
|
||||
pub cloud_skill_enabled: bool,
|
||||
/// Whether cheap skill selectors run in shadow mode without changing prompt contents.
|
||||
pub shadow_selection_enabled: bool,
|
||||
}
|
||||
|
||||
@@ -38,7 +38,6 @@ fn host_interface_metadata_makes_unlisted_workflow_discoverable() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
});
|
||||
let snapshot = HostSkillsSnapshot::new(std::sync::Arc::new(outcome));
|
||||
let catalog = SkillCatalog {
|
||||
|
||||
@@ -2,7 +2,6 @@ use std::sync::Arc;
|
||||
|
||||
use crate::HostSkillsSnapshot;
|
||||
use crate::InjectedHostSkillPrompts;
|
||||
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
|
||||
use codex_extension_api::ConfigContributor;
|
||||
use codex_extension_api::ContextContributor;
|
||||
use codex_extension_api::ContextualUserFragment;
|
||||
@@ -70,9 +69,6 @@ use crate::tools::skill_tools;
|
||||
use crate::warnings::bounded_warnings;
|
||||
use crate::world_state_catalogs::render_world_state_sections;
|
||||
|
||||
#[path = "cloud_skill.rs"]
|
||||
mod cloud_skill;
|
||||
|
||||
struct SkillsExtension<C> {
|
||||
providers: SkillProviders,
|
||||
event_sink: Arc<dyn ExtensionEventSink>,
|
||||
@@ -150,14 +146,8 @@ where
|
||||
mcp_resources: input.mcp_resource_client.clone(),
|
||||
extension_metrics: input.extension_metrics.clone(),
|
||||
});
|
||||
let cloud_skills_available = self.providers.has_cloud_provider()
|
||||
&& !input
|
||||
.environments
|
||||
.iter()
|
||||
.any(|environment| environment.environment_id == LOCAL_ENVIRONMENT_ID);
|
||||
input.thread_store.insert(SkillsThreadState::new(
|
||||
(self.config_from_host)(input.config),
|
||||
cloud_skills_available,
|
||||
input.extension_metrics,
|
||||
));
|
||||
})
|
||||
@@ -179,10 +169,8 @@ where
|
||||
if let Some(state) = thread_store.get::<SkillsThreadState>() {
|
||||
state.set_config(next_config);
|
||||
} else {
|
||||
let cloud_skills_available = self.providers.has_cloud_provider();
|
||||
thread_store.insert(SkillsThreadState::new(
|
||||
next_config,
|
||||
cloud_skills_available,
|
||||
session_store
|
||||
.get::<SkillsSessionState>()
|
||||
.and_then(|state| state.extension_metrics.clone()),
|
||||
@@ -216,7 +204,6 @@ where
|
||||
host_snapshot: None,
|
||||
include_host_skills: false,
|
||||
include_bundled_skills: config.bundled_skills_enabled,
|
||||
include_cloud_skills: false,
|
||||
mcp_resources: session_store
|
||||
.get::<SkillsSessionState>()
|
||||
.and_then(|state| state.mcp_resources.clone()),
|
||||
@@ -360,8 +347,7 @@ where
|
||||
host_snapshot: host_snapshot.clone(),
|
||||
include_host_skills: host_skills.is_none() && !host_catalog_in_world_state,
|
||||
include_bundled_skills: config.bundled_skills_enabled,
|
||||
// Cloud and executor catalogs come from the prepared step snapshot.
|
||||
include_cloud_skills: false,
|
||||
// Executor catalogs come from the prepared step snapshot.
|
||||
mcp_resources: mcp_resources.clone(),
|
||||
executor_capability_discovery: None,
|
||||
executor_capability_discovery_v2: None,
|
||||
@@ -401,7 +387,6 @@ where
|
||||
let mut turn_catalog = catalog.clone();
|
||||
turn_catalog.entries.retain(|entry| {
|
||||
entry.authority.kind != SkillSourceKind::Executor
|
||||
&& entry.authority.kind != SkillSourceKind::Cloud
|
||||
});
|
||||
let model_info = thread_store.get::<ModelInfo>();
|
||||
let include_usage = model_info
|
||||
@@ -537,7 +522,6 @@ impl<C> SkillsExtension<C> {
|
||||
input: &TurnInputContext<'_>,
|
||||
) -> Result<SkillReadResult, String> {
|
||||
let context = match entry.authority.kind {
|
||||
SkillSourceKind::Cloud => SkillReadContext::Cloud { mcp_resources },
|
||||
SkillSourceKind::Custom(_) => SkillReadContext::Custom { mcp_resources },
|
||||
SkillSourceKind::Host => SkillReadContext::Host {
|
||||
host_snapshot,
|
||||
@@ -631,7 +615,6 @@ pub fn install_with_providers_and_metrics<C>(
|
||||
});
|
||||
registry.thread_lifecycle_contributor(extension.clone());
|
||||
registry.turn_lifecycle_contributor(Arc::new(SkillTelemetry));
|
||||
registry.turn_lifecycle_contributor(extension.clone());
|
||||
registry.config_contributor(extension.clone());
|
||||
registry.prompt_contributor(extension.clone());
|
||||
registry.turn_input_contributor(extension.clone());
|
||||
|
||||
@@ -12,7 +12,7 @@ use crate::render::truncate_main_prompt_contents;
|
||||
/// Host skill prompts already supplied or superseded by an extension.
|
||||
///
|
||||
/// Core preserves its host skill invocation lifecycle while avoiding duplicate
|
||||
/// prompts and retaining executor/cloud skill precedence.
|
||||
/// prompts and retaining executor skill precedence.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct InjectedHostSkillPrompts {
|
||||
paths: HashSet<String>,
|
||||
|
||||
@@ -179,7 +179,6 @@ fn roots_from_layer_stack<'a>(
|
||||
}
|
||||
ConfigLayerSource::PackagedDefaults { .. }
|
||||
| ConfigLayerSource::Mdm { .. }
|
||||
| ConfigLayerSource::EnterpriseManaged { .. }
|
||||
| ConfigLayerSource::SessionFlags
|
||||
| ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. }
|
||||
| ConfigLayerSource::LegacyManagedConfigTomlFromMdm => {}
|
||||
|
||||
@@ -298,7 +298,6 @@ fn expected_skill(path: AbsolutePathBuf, name: &str, scope: SkillScope) -> Skill
|
||||
path_to_skills_md: PathUri::from_abs_path(&path),
|
||||
scope,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,7 +355,6 @@ async fn plugin_roots_preserve_plugin_resolution_metadata() {
|
||||
let skills_root = plugin_root.join("skills");
|
||||
let plugin_identity = PluginIdentity {
|
||||
plugin_id: "example@test".to_string(),
|
||||
remote_plugin_id: Some("plugins~Plugin_example".to_string()),
|
||||
};
|
||||
let plugin_namespace = "example".to_string();
|
||||
|
||||
|
||||
@@ -97,7 +97,6 @@ fn plugin_skill_root_for_skill_path(
|
||||
path: skills_root.abs(),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: plugin_id.to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: plugin_namespace.to_string(),
|
||||
plugin_root: plugin_root.abs(),
|
||||
@@ -432,7 +431,6 @@ async fn snapshot_for_config_preserves_host_precedence_for_symlinked_plugin_root
|
||||
),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -502,91 +500,6 @@ async fn skills_list_snapshots_share_host_roots_only_within_one_request() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn skills_for_config_refreshes_cache_when_remote_plugin_id_changes() {
|
||||
let codex_home = tempfile::tempdir().expect("tempdir");
|
||||
let cwd = tempfile::tempdir().expect("tempdir");
|
||||
let skill_path = write_plugin_skill(
|
||||
&codex_home,
|
||||
"test",
|
||||
"sample",
|
||||
"sample-search",
|
||||
"sample-search",
|
||||
"search sample data",
|
||||
);
|
||||
let config_layer_stack = config_stack(&codex_home, "");
|
||||
let mut plugin_skill_root =
|
||||
plugin_skill_root_for_skill_path(&skill_path, "sample@test", "sample");
|
||||
let skills_service = HostSkillsService::new(
|
||||
codex_home.path().abs(),
|
||||
/*bundled_skills_enabled*/ true,
|
||||
);
|
||||
|
||||
let plugin_input = HostSkillsLoadInput::new(
|
||||
cwd.path().abs(),
|
||||
vec![plugin_skill_root.clone()],
|
||||
config_layer_stack.clone(),
|
||||
)
|
||||
.with_plugin_skill_snapshots(Some(test_plugin_skill_snapshots()));
|
||||
let plugin_snapshot = skills_service
|
||||
.snapshot_for_config(
|
||||
&plugin_input,
|
||||
Some(&codex_exec_server::FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS)),
|
||||
)
|
||||
.await;
|
||||
fs::write(
|
||||
&skill_path,
|
||||
"---\nname: sample-search\ndescription: updated sample data\n---\n\n# Body\n",
|
||||
)
|
||||
.expect("update plugin skill");
|
||||
let listing_input = plugin_input
|
||||
.clone()
|
||||
.with_plugin_skill_snapshots(/*plugin_skill_snapshots*/ None);
|
||||
let listing_snapshot = skills_service
|
||||
.for_request()
|
||||
.snapshot_for_cwd(
|
||||
&listing_input,
|
||||
/*force_reload*/ false,
|
||||
Some(Arc::clone(&LOCAL_FS)),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
(
|
||||
plugin_snapshot
|
||||
.outcome()
|
||||
.skills
|
||||
.iter()
|
||||
.find(|skill| skill.name == "sample:sample-search")
|
||||
.map(|skill| skill.description.as_str()),
|
||||
listing_snapshot
|
||||
.outcome()
|
||||
.skills
|
||||
.iter()
|
||||
.find(|skill| skill.name == "sample:sample-search")
|
||||
.map(|skill| skill.description.as_str()),
|
||||
),
|
||||
(Some("search sample data"), Some("updated sample data"))
|
||||
);
|
||||
|
||||
plugin_skill_root.plugin_identity.remote_plugin_id = Some("plugins~Plugin_sample".to_string());
|
||||
let refreshed = skills_for_config_with_stack(
|
||||
&skills_service,
|
||||
&cwd,
|
||||
&config_layer_stack,
|
||||
&[plugin_skill_root],
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
refreshed
|
||||
.skills
|
||||
.iter()
|
||||
.find(|skill| skill.name == "sample:sample-search")
|
||||
.and_then(|skill| skill.remote_plugin_id.as_deref()),
|
||||
Some("plugins~Plugin_sample")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn set_extra_roots_replaces_runtime_roots_and_clears_cache() {
|
||||
let codex_home = tempfile::tempdir().expect("tempdir");
|
||||
|
||||
@@ -85,7 +85,7 @@ pub fn detect_implicit_skill_invocation(
|
||||
scope: skill.scope,
|
||||
},
|
||||
plugin_id: skill.plugin_id,
|
||||
remote_plugin_id: skill.remote_plugin_id,
|
||||
remote_plugin_id: None,
|
||||
invocation_type: InvocationType::Implicit,
|
||||
});
|
||||
}
|
||||
@@ -114,12 +114,12 @@ pub fn detect_implicit_skill_invocation(
|
||||
.is_some_and(|scripts_dir| path.starts_with(&scripts_dir)),
|
||||
}
|
||||
};
|
||||
for entry in step_catalog.merged.entries.iter().filter(|entry| {
|
||||
matches!(
|
||||
entry.authority.kind,
|
||||
SkillSourceKind::Cloud | SkillSourceKind::Executor
|
||||
)
|
||||
}) {
|
||||
for entry in step_catalog
|
||||
.merged
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|entry| entry.authority.kind == SkillSourceKind::Executor)
|
||||
{
|
||||
if entry.enabled && matches_route(&entry.authority, &entry.main_prompt) {
|
||||
return Some(entry.invocation(&entry.primary_source(), InvocationType::Implicit));
|
||||
}
|
||||
|
||||
@@ -31,7 +31,6 @@ fn detect_executor_skill(command: &str, environments: &[&str]) -> Option<SkillIn
|
||||
};
|
||||
let turn_store = ExtensionData::new("test-turn");
|
||||
let step_catalog = crate::step_state::SkillStepCatalog::new(
|
||||
/*cloud*/ None,
|
||||
catalog,
|
||||
/*discovery_v2*/ false,
|
||||
Default::default(),
|
||||
@@ -42,14 +41,12 @@ fn detect_executor_skill(command: &str, environments: &[&str]) -> Option<SkillIn
|
||||
tools_enabled: true,
|
||||
catalog: step_catalog,
|
||||
host_catalog: None,
|
||||
cloud_status: crate::step_state::CatalogStatus::Unavailable,
|
||||
config: crate::SkillsExtensionConfig {
|
||||
include_instructions: true,
|
||||
catalog_deltas_enabled: false,
|
||||
omit_descriptions: false,
|
||||
max_context_tokens: None,
|
||||
bundled_skills_enabled: false,
|
||||
cloud_skill_enabled: false,
|
||||
shadow_selection_enabled: false,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -32,7 +32,6 @@ mod warnings;
|
||||
mod world_state;
|
||||
mod world_state_catalogs;
|
||||
|
||||
pub use catalog::merge_catalogs;
|
||||
pub use config::SkillsExtensionConfig;
|
||||
pub use extension::install;
|
||||
pub use extension::install_with_providers;
|
||||
@@ -48,7 +47,6 @@ pub use invocation::SkillInvocation;
|
||||
pub use invocation::SkillInvocationLocation;
|
||||
pub use invocation::detect_implicit_skill_invocation;
|
||||
pub use provider::ExecutorSkillProvider;
|
||||
pub use provider::FrozenCloudSkillProvider;
|
||||
pub use provider::HostSkillProvider;
|
||||
pub use provider::SkillProvider;
|
||||
pub use required::EnvironmentSkillRequirements;
|
||||
|
||||
@@ -390,7 +390,6 @@ async fn parse_skill_file(
|
||||
path_to_skills_md: path_uri.clone(),
|
||||
scope,
|
||||
plugin_id: plugin_identity.map(|identity| identity.plugin_id.clone()),
|
||||
remote_plugin_id: plugin_identity.and_then(|identity| identity.remote_plugin_id.clone()),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -95,7 +95,6 @@ async fn host_loading_reuses_walk_inventory_for_symlinked_skill_pack() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&first_skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
SkillMetadata {
|
||||
name: "linked:second".to_string(),
|
||||
@@ -107,7 +106,6 @@ async fn host_loading_reuses_walk_inventory_for_symlinked_skill_pack() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&second_skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
@@ -93,7 +93,6 @@ impl PluginSkillsFixture {
|
||||
access: FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS),
|
||||
identity: PluginIdentity {
|
||||
plugin_id: "sample@test".to_string(),
|
||||
remote_plugin_id: Some("remote-sample".to_string()),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -267,8 +266,8 @@ async fn reuses_owner_managed_plugin_root_snapshots() {
|
||||
assert_eq!(cached_outcome.skills[0].description, "native");
|
||||
assert_eq!(refreshed_outcome.skills[0].description, "updated");
|
||||
assert_eq!(
|
||||
cached_outcome.skills[0].remote_plugin_id.as_deref(),
|
||||
Some("remote-sample")
|
||||
cached_outcome.skills[0].plugin_id.as_deref(),
|
||||
Some("sample@test")
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -98,7 +98,6 @@ impl PluginSkillFixture {
|
||||
path: self.plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "fixture@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: "plugin".to_string(),
|
||||
plugin_root: self.plugin_root.clone(),
|
||||
@@ -162,7 +161,6 @@ policy:
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -189,7 +187,6 @@ async fn invalid_optional_metadata_fails_open() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::Repo,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -236,7 +233,6 @@ async fn loads_host_interface_metadata_and_local_asset_paths() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -279,7 +275,6 @@ async fn loads_plugin_skill_interface_icons_from_local_and_shared_assets() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&fixture.skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("fixture@test".to_string()),
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -317,7 +312,6 @@ async fn rejects_plugin_skill_interface_icons_outside_shared_assets() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&fixture.skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("fixture@test".to_string()),
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -348,7 +342,6 @@ async fn rejects_interface_fields_that_escape_or_fail_validation() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -403,7 +396,6 @@ async fn discovers_nested_plugin_namespace_without_plugin_identity() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -426,7 +418,6 @@ async fn plugin_root_accepts_maximum_length_qualified_skill_name() {
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: plugin_namespace.clone(),
|
||||
plugin_root,
|
||||
@@ -449,7 +440,6 @@ async fn plugin_root_accepts_maximum_length_qualified_skill_name() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("demo@test".to_string()),
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -471,7 +461,6 @@ async fn plugin_root_rejects_overlong_qualified_skill_name() {
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: "p".repeat(MAX_NAME_LEN + 1),
|
||||
plugin_root,
|
||||
@@ -522,7 +511,6 @@ async fn recursive_plugin_root_preserves_owner_namespace_and_shared_asset_policy
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: Some("remote-demo".to_string()),
|
||||
},
|
||||
plugin_namespace: "plugin".to_string(),
|
||||
plugin_root,
|
||||
@@ -552,7 +540,6 @@ async fn recursive_plugin_root_preserves_owner_namespace_and_shared_asset_policy
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("demo@test".to_string()),
|
||||
remote_plugin_id: Some("remote-demo".to_string()),
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -584,7 +571,6 @@ async fn direct_child_plugin_root_ignores_nested_skills() {
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: "plugin".to_string(),
|
||||
plugin_root,
|
||||
@@ -607,7 +593,6 @@ async fn direct_child_plugin_root_ignores_nested_skills() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&direct_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("demo@test".to_string()),
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -636,7 +621,6 @@ async fn direct_child_plugin_root_skips_skills_resolving_outside_plugin_root() {
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: "plugin".to_string(),
|
||||
plugin_root,
|
||||
@@ -667,7 +651,6 @@ async fn recursive_plugin_root_preserves_symlinked_skill_discovery_path() {
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: "plugin".to_string(),
|
||||
plugin_root,
|
||||
@@ -690,7 +673,6 @@ async fn recursive_plugin_root_preserves_symlinked_skill_discovery_path() {
|
||||
path_to_skills_md: PathUri::from_abs_path(&target_skill),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("demo@test".to_string()),
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
|
||||
@@ -10,7 +10,6 @@ use crate::provider::attribute_executor_plugins;
|
||||
use crate::sources::SkillProviders;
|
||||
use crate::state::SkillsSessionState;
|
||||
use crate::state::SkillsThreadState;
|
||||
use crate::step_state::CatalogStatus;
|
||||
use crate::step_state::SkillsStepState;
|
||||
use codex_extension_api::StepPreparationInput;
|
||||
|
||||
@@ -20,38 +19,21 @@ pub(crate) async fn prepare_catalogs(
|
||||
input: &StepPreparationInput<'_>,
|
||||
) -> SkillsStepState {
|
||||
let config = thread_state.config();
|
||||
let cloud_enabled = config.cloud_skill_enabled && thread_state.cloud_skills_available();
|
||||
let discovery_v2 = input.executor_capability_discovery_v2.is_some();
|
||||
let mut cloud = cloud_enabled
|
||||
.then(|| thread_state.available_cloud_catalog())
|
||||
.flatten();
|
||||
let (mut executor, host_catalog) = futures::join!(
|
||||
discover_executor_catalog(thread_state, providers, input, &config, cloud_enabled),
|
||||
discover_executor_catalog(thread_state, providers, input, &config),
|
||||
discover_host_catalog(providers, input, &config),
|
||||
);
|
||||
if discovery_v2 {
|
||||
apply_plugin_denials(&mut executor, input.selected_plugins);
|
||||
if let Some(cloud) = &mut cloud {
|
||||
apply_plugin_denials(cloud, input.selected_plugins);
|
||||
}
|
||||
} else {
|
||||
attribute_executor_plugins(&mut executor, input.selected_plugins);
|
||||
}
|
||||
let cloud_status = if !providers.has_cloud_provider() {
|
||||
CatalogStatus::Unavailable
|
||||
} else if cloud_enabled {
|
||||
CatalogStatus::Enabled
|
||||
} else {
|
||||
CatalogStatus::Disabled
|
||||
};
|
||||
SkillsStepState {
|
||||
discovery_v2,
|
||||
tools_enabled: cloud_enabled
|
||||
|| !input.ready_selected_capability_roots.is_empty()
|
||||
|| discovery_v2,
|
||||
catalog: thread_state.prepare_step_catalog(cloud, executor, discovery_v2),
|
||||
tools_enabled: !input.ready_selected_capability_roots.is_empty() || discovery_v2,
|
||||
catalog: thread_state.prepare_step_catalog(executor, discovery_v2),
|
||||
host_catalog,
|
||||
cloud_status,
|
||||
config,
|
||||
}
|
||||
}
|
||||
@@ -61,7 +43,6 @@ async fn discover_executor_catalog(
|
||||
providers: &SkillProviders,
|
||||
input: &StepPreparationInput<'_>,
|
||||
config: &SkillsExtensionConfig,
|
||||
cloud_enabled: bool,
|
||||
) -> SkillCatalog {
|
||||
let query = SkillListQuery {
|
||||
turn_id: input.turn_id.to_string(),
|
||||
@@ -69,7 +50,6 @@ async fn discover_executor_catalog(
|
||||
host_snapshot: None,
|
||||
include_host_skills: false,
|
||||
include_bundled_skills: config.bundled_skills_enabled,
|
||||
include_cloud_skills: cloud_enabled,
|
||||
mcp_resources: input
|
||||
.session_store
|
||||
.get::<SkillsSessionState>()
|
||||
@@ -100,7 +80,6 @@ async fn discover_host_catalog(
|
||||
host_snapshot: Some(host_snapshot),
|
||||
include_host_skills: true,
|
||||
include_bundled_skills: false,
|
||||
include_cloud_skills: false,
|
||||
mcp_resources: None,
|
||||
executor_capability_discovery: None,
|
||||
executor_capability_discovery_v2: None,
|
||||
|
||||
@@ -3,7 +3,6 @@ use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
mod executor;
|
||||
mod frozen_cloud;
|
||||
mod host;
|
||||
|
||||
use crate::HostSkillsSnapshot;
|
||||
@@ -23,7 +22,6 @@ use crate::catalog::SkillSearchResult;
|
||||
|
||||
pub use executor::ExecutorSkillProvider;
|
||||
pub(crate) use executor::attribute_executor_plugins;
|
||||
pub use frozen_cloud::FrozenCloudSkillProvider;
|
||||
pub use host::HostSkillProvider;
|
||||
|
||||
pub(crate) const MAX_SKILL_RESOURCE_CONTENT_BYTES: usize = 1024 * 1024;
|
||||
@@ -36,7 +34,6 @@ pub struct SkillListQuery<'a> {
|
||||
pub host_snapshot: Option<Arc<HostSkillsSnapshot>>,
|
||||
pub include_host_skills: bool,
|
||||
pub include_bundled_skills: bool,
|
||||
pub include_cloud_skills: bool,
|
||||
pub mcp_resources: Option<Arc<McpResourceClient>>,
|
||||
/// Present only when the opt-in high-level executor discovery path is selected.
|
||||
pub executor_capability_discovery: Option<ExecutorCapabilityDiscoverySnapshot>,
|
||||
@@ -63,9 +60,6 @@ pub enum SkillReadContext<'a> {
|
||||
Executor {
|
||||
fs: &'a dyn EnvironmentAccess,
|
||||
},
|
||||
Cloud {
|
||||
mcp_resources: Option<Arc<McpResourceClient>>,
|
||||
},
|
||||
Custom {
|
||||
mcp_resources: Option<Arc<McpResourceClient>>,
|
||||
},
|
||||
@@ -87,12 +81,6 @@ pub type SkillProviderFuture<'a, T> =
|
||||
/// provider must be read or searched through the same provider/authority rather
|
||||
/// than converted into an ambient local path.
|
||||
pub trait SkillProvider: Send + Sync {
|
||||
/// Whether Cloud catalog and read caches must follow the live MCP auth/resource scope.
|
||||
/// When all configured Cloud providers opt out, their caches are independent of MCP.
|
||||
fn uses_mcp_resources(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Providers set `is_partial` when listing omits entries; warnings are diagnostic only.
|
||||
fn list<'a>(&'a self, query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog>;
|
||||
|
||||
|
||||
@@ -43,7 +43,6 @@ impl ExecutorSkillProvider {
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
entry.remote_plugin_id = plugin.remote_plugin_id.clone();
|
||||
entry.plugin_id = Some(plugin.id.clone());
|
||||
entry.invocation_scope = Some(SkillScope::User);
|
||||
catalog.push_entry(entry);
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
//! Immutable cloud skill snapshots for offline sources. Only declared package resources are
|
||||
//! readable; the normal skills extension owns aliases, tool schemas, rendering, and pagination.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::MAX_SKILL_RESOURCE_CONTENT_BYTES;
|
||||
use super::SkillListQuery;
|
||||
use super::SkillProvider;
|
||||
use super::SkillProviderFuture;
|
||||
use super::SkillReadRequest;
|
||||
use super::SkillSearchRequest;
|
||||
use crate::catalog::SkillAuthority;
|
||||
use crate::catalog::SkillCatalog;
|
||||
use crate::catalog::SkillCatalogEntry;
|
||||
use crate::catalog::SkillPackageId;
|
||||
use crate::catalog::SkillProviderError;
|
||||
use crate::catalog::SkillProviderResult;
|
||||
use crate::catalog::SkillReadResult;
|
||||
use crate::catalog::SkillResourceId;
|
||||
use crate::catalog::SkillSearchResult;
|
||||
use crate::catalog::SkillSourceKind;
|
||||
|
||||
const MAX_SNAPSHOT_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Snapshot {
|
||||
skills: Vec<SnapshotSkill>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SnapshotSkill {
|
||||
package: String,
|
||||
name: String,
|
||||
description: String,
|
||||
alias_root: String,
|
||||
main_resource: String,
|
||||
#[serde(default = "default_prompt_visible")]
|
||||
prompt_visible: bool,
|
||||
resources: HashMap<String, String>,
|
||||
}
|
||||
|
||||
fn default_prompt_visible() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Supplies a fixed cloud catalog and resource contents without contacting a skill service.
|
||||
pub struct FrozenCloudSkillProvider {
|
||||
catalog: SkillCatalog,
|
||||
resources: HashMap<SkillPackageId, HashMap<String, String>>,
|
||||
}
|
||||
|
||||
impl FrozenCloudSkillProvider {
|
||||
/// Loads once from a host-owned file; subsequent reads never access the filesystem.
|
||||
pub fn from_file(path: &Path) -> SkillProviderResult<Self> {
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::open(path)
|
||||
.and_then(|file| {
|
||||
file.take((MAX_SNAPSHOT_BYTES + 1) as u64)
|
||||
.read_to_end(&mut bytes)
|
||||
})
|
||||
.map_err(|err| SkillProviderError::new(format!("cannot read skill snapshot: {err}")))?;
|
||||
Self::from_json(&bytes)
|
||||
}
|
||||
|
||||
/// Rejects missing main resources, duplicate packages, and resources outside their package.
|
||||
pub fn from_json(bytes: &[u8]) -> SkillProviderResult<Self> {
|
||||
if bytes.len() > MAX_SNAPSHOT_BYTES {
|
||||
return Err(SkillProviderError::new("skill snapshot exceeds 64 MiB"));
|
||||
}
|
||||
let snapshot: Snapshot = serde_json::from_slice(bytes)
|
||||
.map_err(|err| SkillProviderError::new(format!("invalid skill snapshot: {err}")))?;
|
||||
let mut catalog = SkillCatalog::default();
|
||||
let mut resources = HashMap::new();
|
||||
for skill in snapshot.skills {
|
||||
let package = SkillPackageId(skill.package);
|
||||
let root = SkillPackageId(skill.alias_root.clone());
|
||||
if !skill.alias_root.starts_with("skill://")
|
||||
|| root.relative_resource_path(&package.0).is_none()
|
||||
|| skill.name.trim().is_empty()
|
||||
|| !skill.resources.contains_key(&skill.main_resource)
|
||||
|| skill.resources.iter().any(|(resource, contents)| {
|
||||
package.relative_resource_path(resource).is_none()
|
||||
|| contents.len() > MAX_SKILL_RESOURCE_CONTENT_BYTES
|
||||
})
|
||||
{
|
||||
return Err(SkillProviderError::new("invalid skill package or resource"));
|
||||
}
|
||||
let mut entry = SkillCatalogEntry::new(
|
||||
package.clone(),
|
||||
SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME),
|
||||
skill.name,
|
||||
skill.description,
|
||||
SkillResourceId::new(skill.main_resource),
|
||||
)
|
||||
.with_display_path(&package.0)
|
||||
.with_alias_root(skill.alias_root);
|
||||
if !skill.prompt_visible {
|
||||
entry = entry.hidden_from_prompt();
|
||||
}
|
||||
catalog.entries.push(entry);
|
||||
if resources.insert(package, skill.resources).is_some() {
|
||||
return Err(SkillProviderError::new("duplicate skill package"));
|
||||
}
|
||||
}
|
||||
Ok(Self { catalog, resources })
|
||||
}
|
||||
}
|
||||
|
||||
impl SkillProvider for FrozenCloudSkillProvider {
|
||||
fn uses_mcp_resources(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn list<'a>(&'a self, query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog> {
|
||||
Box::pin(async move {
|
||||
Ok(if query.include_cloud_skills {
|
||||
self.catalog.clone()
|
||||
} else {
|
||||
SkillCatalog::default()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn read<'a>(
|
||||
&'a self,
|
||||
request: SkillReadRequest<'a>,
|
||||
) -> SkillProviderFuture<'a, SkillReadResult> {
|
||||
Box::pin(async move {
|
||||
if request.authority
|
||||
!= SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME)
|
||||
{
|
||||
return Err(SkillProviderError::new("invalid frozen skill authority"));
|
||||
}
|
||||
let contents = self
|
||||
.resources
|
||||
.get(&request.package)
|
||||
.and_then(|resources| resources.get(request.resource.as_str()))
|
||||
.ok_or_else(|| SkillProviderError::new("unknown frozen skill resource"))?;
|
||||
Ok(SkillReadResult {
|
||||
resource: request.resource,
|
||||
contents: contents.clone(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn search(&self, _request: SkillSearchRequest) -> SkillProviderFuture<'_, SkillSearchResult> {
|
||||
Box::pin(async {
|
||||
Err(SkillProviderError::new(
|
||||
"frozen skill snapshots do not support search",
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "frozen_cloud_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,92 +0,0 @@
|
||||
//! Snapshot validation and immutable resource reads across authority boundaries.
|
||||
|
||||
use super::*;
|
||||
use crate::provider::SkillReadContext;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
fn snapshot() -> serde_json::Value {
|
||||
json!({"skills": [{
|
||||
"package": "skill://demo/work",
|
||||
"name": "demo:work",
|
||||
"description": "Do the work.",
|
||||
"alias_root": "skill://demo",
|
||||
"main_resource": "skill://demo/work/SKILL.md",
|
||||
"resources": {"skill://demo/work/SKILL.md": "# Work\nKeep it readable.\n"}
|
||||
}]})
|
||||
}
|
||||
|
||||
fn request() -> SkillReadRequest<'static> {
|
||||
SkillReadRequest {
|
||||
authority: SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME),
|
||||
package: SkillPackageId("skill://demo/work".into()),
|
||||
resource: SkillResourceId::new("skill://demo/work/SKILL.md"),
|
||||
context: SkillReadContext::Cloud {
|
||||
mcp_resources: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn file_is_loaded_once_and_reads_preserve_the_exact_contents() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("skills.json");
|
||||
std::fs::write(&path, snapshot().to_string()).unwrap();
|
||||
let provider = FrozenCloudSkillProvider::from_file(&path).unwrap();
|
||||
std::fs::remove_file(path).unwrap();
|
||||
assert_eq!(
|
||||
provider.read(request()).await.unwrap(),
|
||||
SkillReadResult {
|
||||
resource: request().resource,
|
||||
contents: "# Work\nKeep it readable.\n".into(),
|
||||
}
|
||||
);
|
||||
assert_eq!(provider.catalog.entries.len(), 1);
|
||||
assert!(provider.catalog.entries[0].prompt_visible);
|
||||
assert_eq!(
|
||||
provider.catalog.entries[0].rendered_path(),
|
||||
"skill://demo/work"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hidden_skills_remain_readable_without_implicit_prompt_exposure() {
|
||||
let mut value = snapshot();
|
||||
value["skills"][0]["prompt_visible"] = json!(false);
|
||||
let provider = FrozenCloudSkillProvider::from_json(value.to_string().as_bytes()).unwrap();
|
||||
assert!(!provider.catalog.entries[0].prompt_visible);
|
||||
assert_eq!(
|
||||
provider.read(request()).await.unwrap().contents,
|
||||
"# Work\nKeep it readable.\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reads_cannot_cross_authority_or_package_boundaries() {
|
||||
let provider = FrozenCloudSkillProvider::from_json(snapshot().to_string().as_bytes()).unwrap();
|
||||
let mut other_authority = request();
|
||||
other_authority.authority = SkillAuthority::new(SkillSourceKind::Executor, "demo");
|
||||
let mut other_package = request();
|
||||
other_package.package = SkillPackageId("skill://other/work".into());
|
||||
let mut other_resource = request();
|
||||
other_resource.resource = SkillResourceId::new("skill://demo/work/../SKILL.md");
|
||||
for request in [other_authority, other_package, other_resource] {
|
||||
assert!(provider.read(request).await.is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_snapshots_are_rejected_before_inference() {
|
||||
let mut missing_main = snapshot();
|
||||
missing_main["skills"][0]["main_resource"] = json!("skill://demo/work/missing.md");
|
||||
let mut escaped = snapshot();
|
||||
escaped["skills"][0]["resources"]["skill://other/secret.md"] = json!("secret");
|
||||
let mut oversized = snapshot();
|
||||
oversized["skills"][0]["resources"]["skill://demo/work/SKILL.md"] =
|
||||
json!("x".repeat(MAX_SKILL_RESOURCE_CONTENT_BYTES + 1));
|
||||
let mut duplicate = snapshot();
|
||||
duplicate["skills"] = json!([snapshot()["skills"][0], snapshot()["skills"][0]]);
|
||||
for value in [missing_main, escaped, oversized, duplicate] {
|
||||
assert!(FrozenCloudSkillProvider::from_json(value.to_string().as_bytes()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -262,7 +262,6 @@ impl<'a> SkillLine<'a> {
|
||||
locator_kind: match &entry.authority.kind {
|
||||
SkillSourceKind::Host => "file",
|
||||
SkillSourceKind::Executor => "executor package",
|
||||
SkillSourceKind::Cloud => "cloud package",
|
||||
SkillSourceKind::Custom(_) => "custom resource",
|
||||
},
|
||||
}
|
||||
@@ -530,7 +529,6 @@ pub(crate) struct AvailableSkillsRender {
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RenderedSkillCatalogs {
|
||||
pub(crate) executor: Option<AvailableSkillsRender>,
|
||||
pub(crate) cloud: Option<AvailableSkillsRender>,
|
||||
pub(crate) host: Option<AvailableSkillsRender>,
|
||||
}
|
||||
|
||||
@@ -593,70 +591,40 @@ pub(crate) fn render_available_skills(
|
||||
|
||||
pub(crate) fn render_prepared_skill_catalogs(
|
||||
executor: &PreparedSkillCatalog<'_>,
|
||||
cloud: &PreparedSkillCatalog<'_>,
|
||||
host: &PreparedSkillCatalog<'_>,
|
||||
budget: SkillMetadataBudget,
|
||||
include_skills_usage_instructions: bool,
|
||||
) -> RenderedSkillCatalogs {
|
||||
let nonempty_catalog_count = [
|
||||
!executor.entries.is_empty(),
|
||||
!cloud.entries.is_empty(),
|
||||
!host.entries.is_empty(),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|nonempty| *nonempty)
|
||||
.count();
|
||||
if nonempty_catalog_count <= 1 {
|
||||
if executor.entries.is_empty() || host.entries.is_empty() {
|
||||
return RenderedSkillCatalogs {
|
||||
executor: executor.render(budget, include_skills_usage_instructions),
|
||||
cloud: cloud.render(budget, include_skills_usage_instructions),
|
||||
host: host.render(budget, include_skills_usage_instructions),
|
||||
};
|
||||
}
|
||||
|
||||
let absolute = render_combined_lines(
|
||||
executor.unaliased(),
|
||||
cloud.unaliased(),
|
||||
host.unaliased(),
|
||||
budget,
|
||||
);
|
||||
let absolute = render_combined_lines(executor.unaliased(), host.unaliased(), budget);
|
||||
|
||||
let mut selected = absolute;
|
||||
let host_only_aliases = build_aliased_combined_catalog(
|
||||
executor.unaliased(),
|
||||
cloud.unaliased(),
|
||||
host.aliased(),
|
||||
budget,
|
||||
include_skills_usage_instructions,
|
||||
);
|
||||
let executor_only_aliases = build_aliased_combined_catalog(
|
||||
executor.aliased(),
|
||||
cloud.unaliased(),
|
||||
host.unaliased(),
|
||||
budget,
|
||||
include_skills_usage_instructions,
|
||||
);
|
||||
let cloud_only_aliases = build_aliased_combined_catalog(
|
||||
executor.unaliased(),
|
||||
cloud.aliased(),
|
||||
host.unaliased(),
|
||||
budget,
|
||||
include_skills_usage_instructions,
|
||||
);
|
||||
let all_source_aliases = build_aliased_combined_catalog(
|
||||
executor.aliased(),
|
||||
cloud.aliased(),
|
||||
host.aliased(),
|
||||
budget,
|
||||
include_skills_usage_instructions,
|
||||
);
|
||||
|
||||
for candidate in [
|
||||
host_only_aliases,
|
||||
executor_only_aliases,
|
||||
cloud_only_aliases,
|
||||
all_source_aliases,
|
||||
]
|
||||
for candidate in [host_only_aliases, executor_only_aliases, all_source_aliases]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
@@ -672,14 +640,12 @@ pub(crate) fn render_prepared_skill_catalogs(
|
||||
|
||||
RenderedSkillCatalogs {
|
||||
executor: Some(selected.executor),
|
||||
cloud: Some(selected.cloud),
|
||||
host: Some(selected.host),
|
||||
}
|
||||
}
|
||||
|
||||
struct CombinedAvailableSkillsRender {
|
||||
executor: AvailableSkillsRender,
|
||||
cloud: AvailableSkillsRender,
|
||||
host: AvailableSkillsRender,
|
||||
}
|
||||
|
||||
@@ -748,23 +714,15 @@ impl<'a> CatalogLines<'a> {
|
||||
|
||||
fn render_combined_lines(
|
||||
executor: CatalogLines<'_>,
|
||||
cloud: CatalogLines<'_>,
|
||||
host: CatalogLines<'_>,
|
||||
budget: SkillMetadataBudget,
|
||||
) -> CombinedAvailableSkillsRender {
|
||||
let executor_end = executor.skills.len();
|
||||
let cloud_end = executor_end.saturating_add(cloud.skills.len());
|
||||
let mut lines = executor.skills;
|
||||
lines.extend(cloud.skills);
|
||||
lines.extend(host.skills);
|
||||
let mut allocations = allocate_skill_lines(&lines, budget);
|
||||
let omission_marker =
|
||||
reserve_non_host_omission_marker(&lines, executor_end, cloud_end, budget, &mut allocations);
|
||||
let (executor_omission_marker, cloud_omission_marker) = if executor_end == cloud_end {
|
||||
(omission_marker, None)
|
||||
} else {
|
||||
(None, omission_marker)
|
||||
};
|
||||
reserve_non_host_omission_marker(&lines, executor_end, budget, &mut allocations);
|
||||
|
||||
CombinedAvailableSkillsRender {
|
||||
executor: render_combined_group(
|
||||
@@ -772,18 +730,11 @@ fn render_combined_lines(
|
||||
&allocations[..executor_end],
|
||||
executor.prompt,
|
||||
executor.root_lines,
|
||||
executor_omission_marker,
|
||||
),
|
||||
cloud: render_combined_group(
|
||||
&lines[executor_end..cloud_end],
|
||||
&allocations[executor_end..cloud_end],
|
||||
cloud.prompt,
|
||||
cloud.root_lines,
|
||||
cloud_omission_marker,
|
||||
omission_marker,
|
||||
),
|
||||
host: render_combined_group(
|
||||
&lines[cloud_end..],
|
||||
&allocations[cloud_end..],
|
||||
&lines[executor_end..],
|
||||
&allocations[executor_end..],
|
||||
host.prompt,
|
||||
host.root_lines,
|
||||
/*omission_marker*/ None,
|
||||
@@ -827,19 +778,18 @@ fn render_combined_group(
|
||||
|
||||
fn build_aliased_combined_catalog(
|
||||
executor: CatalogLines<'_>,
|
||||
cloud: CatalogLines<'_>,
|
||||
host: CatalogLines<'_>,
|
||||
budget: SkillMetadataBudget,
|
||||
include_skills_usage_instructions: bool,
|
||||
) -> Option<CombinedAvailableSkillsRender> {
|
||||
if [&executor.root_lines, &cloud.root_lines, &host.root_lines]
|
||||
if [&executor.root_lines, &host.root_lines]
|
||||
.into_iter()
|
||||
.all(Vec::is_empty)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let table_cost = [&executor, &cloud, &host]
|
||||
let table_cost = [&executor, &host]
|
||||
.into_iter()
|
||||
.filter(|catalog| !catalog.root_lines.is_empty())
|
||||
.map(|catalog| {
|
||||
@@ -860,12 +810,7 @@ fn build_aliased_combined_catalog(
|
||||
SkillMetadataBudget::Tokens(_) => SkillMetadataBudget::Tokens(adjusted_limit),
|
||||
SkillMetadataBudget::Characters(_) => SkillMetadataBudget::Characters(adjusted_limit),
|
||||
};
|
||||
Some(render_combined_lines(
|
||||
executor,
|
||||
cloud,
|
||||
host,
|
||||
adjusted_budget,
|
||||
))
|
||||
Some(render_combined_lines(executor, host, adjusted_budget))
|
||||
}
|
||||
|
||||
fn combined_render_is_better(
|
||||
@@ -877,7 +822,6 @@ fn combined_render_is_better(
|
||||
let priority = |rendered: &CombinedAvailableSkillsRender| {
|
||||
(
|
||||
rendered.executor.report.included_count,
|
||||
rendered.cloud.report.included_count,
|
||||
rendered.host.report.included_count,
|
||||
)
|
||||
};
|
||||
@@ -886,7 +830,7 @@ fn combined_render_is_better(
|
||||
}
|
||||
|
||||
let truncated_chars = |rendered: &CombinedAvailableSkillsRender| {
|
||||
[&rendered.executor, &rendered.cloud, &rendered.host]
|
||||
[&rendered.executor, &rendered.host]
|
||||
.into_iter()
|
||||
.fold(0usize, |total, catalog| {
|
||||
total.saturating_add(catalog.report.truncated_description_chars)
|
||||
@@ -905,7 +849,7 @@ fn combined_available_skills_cost(
|
||||
rendered: &CombinedAvailableSkillsRender,
|
||||
include_skills_usage_instructions: bool,
|
||||
) -> usize {
|
||||
[&rendered.executor, &rendered.cloud, &rendered.host]
|
||||
[&rendered.executor, &rendered.host]
|
||||
.into_iter()
|
||||
.fold(0usize, |used, catalog| {
|
||||
used.saturating_add(catalog.metadata_cost(budget, include_skills_usage_instructions))
|
||||
@@ -915,12 +859,11 @@ fn combined_available_skills_cost(
|
||||
fn reserve_non_host_omission_marker(
|
||||
skill_lines: &[SkillLine<'_>],
|
||||
executor_end: usize,
|
||||
cloud_end: usize,
|
||||
budget: SkillMetadataBudget,
|
||||
allocations: &mut [SkillLineAllocation],
|
||||
) -> Option<String> {
|
||||
loop {
|
||||
let omitted_count = allocations[..cloud_end]
|
||||
let omitted_count = allocations[..executor_end]
|
||||
.iter()
|
||||
.filter(|allocation| matches!(allocation, SkillLineAllocation::Omitted))
|
||||
.count();
|
||||
@@ -934,9 +877,8 @@ fn reserve_non_host_omission_marker(
|
||||
return Some(marker);
|
||||
}
|
||||
|
||||
let index = (cloud_end..allocations.len())
|
||||
let index = (executor_end..allocations.len())
|
||||
.rev()
|
||||
.chain((executor_end..cloud_end).rev())
|
||||
.chain((0..executor_end).rev())
|
||||
.find(|index| {
|
||||
matches!(
|
||||
@@ -1078,7 +1020,7 @@ pub(crate) fn build_alias_plan(entries: &[&SkillCatalogEntry]) -> Option<AliasPl
|
||||
alias_ordered_entries.sort_by_key(|entry| entry.alias_root_order().unwrap_or(usize::MAX));
|
||||
let roots = match source {
|
||||
SkillSourceKind::Host => shared_host_alias_roots(&alias_ordered_entries),
|
||||
SkillSourceKind::Executor | SkillSourceKind::Cloud => alias_ordered_entries
|
||||
SkillSourceKind::Executor => alias_ordered_entries
|
||||
.iter()
|
||||
.filter_map(|entry| entry.alias_root())
|
||||
.map(str::to_string)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user