Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
//! Request-scoped approval decisions. A review only satisfies the review gate; the host enforces permissions.
use std::sync::Arc;
use codex_protocol::ThreadId;
use crate::ExtensionData;
/// Thread-local state installed only after Guardian V2's async classifier initializes.
pub struct GuardianV2Enabled;
/// Guardian's choice for one approval. Synchronous results pass through unchanged.
#[derive(Clone, Debug, PartialEq)]
pub enum ApprovalDecision {
/// Existing async evidence allows this action without synchronous review.
Allow,
Reviewed(codex_protocol::protocol::ReviewDecision),
AskUser,
}
/// Runs an extension-owned review already bound to an action by the host.
/// `None` requests the host user flow when automatic review exhausts its input budget
/// and host policy permits it. An optional async approval resolves only when current
/// cached evidence authorizes the action; it races the complete synchronous review.
pub trait SynchronousApprovalReviewer: Send + Sync {
fn review<'a>(
&'a self,
reason: codex_protocol::approvals::GuardianReviewReason,
async_approval: Option<crate::ExtensionFuture<'a, ()>>,
) -> crate::ExtensionFuture<'a, Option<codex_protocol::protocol::ReviewDecision>>;
}
/// Inputs to Guardian's policy choice. Conversation and scores stay thread-owned.
pub struct ApprovalDecisionInput<'a> {
/// Final serving value for this action. The host still requires fresh review when stale.
pub serving_assessment: Option<bool>,
pub approval_id: &'a str,
/// Host tool invocation being approved, absent for approvals without a tool call.
pub tool_call_id: Option<&'a str>,
/// Host-resolved permission evidence; unavailable evidence cannot authorize cached approval.
pub permissions: Option<&'a codex_guardian_context::PermissionContext>,
pub action: &'a serde_json::Value,
pub thread_id: ThreadId,
pub thread_store: &'a ExtensionData,
/// Captured configuration and evidence owned by the requesting turn.
pub turn_store: &'a ExtensionData,
pub category: codex_protocol::openai_models::GuardianScope,
pub approval_policy: codex_protocol::protocol::AskForApproval,
pub approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer,
pub require_guardian: bool,
/// Existing retry and sensitive-action rules require a synchronous review.
pub require_fresh_review: bool,
pub full_access: bool,
pub metrics: Option<Arc<dyn crate::ExtensionMetrics>>,
pub synchronous_reviewer: &'a dyn SynchronousApprovalReviewer,
}

View File

@@ -0,0 +1,20 @@
use codex_protocol::ThreadId;
use crate::ExtensionData;
/// Host context available while extensions contribute turn-scoped context fragments.
#[derive(Clone, Copy)]
pub struct TurnContextContributionInput<'a> {
/// Stable host-owned thread identifier.
pub thread_id: ThreadId,
/// Stable host-owned turn identifier.
pub turn_id: &'a str,
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
/// Store scoped to this turn.
pub turn_store: &'a ExtensionData,
/// Usable context window of the captured model for this context build, when known.
pub model_context_window: Option<i64>,
}

View File

@@ -0,0 +1,237 @@
use codex_config::McpServerConfig;
use codex_core_plugin_common::PluginIdentity;
use codex_exec_server_protocol::ExecutorCapabilityDiscoverySnapshot;
use codex_exec_server_protocol::ExecutorCapabilityDiscoveryV2Snapshot;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::TurnEnvironmentSelection;
use crate::ExtensionData;
use crate::ExtensionDataInit;
use crate::ExtensionFuture;
/// Input supplied while resolving MCP server contributions.
///
/// Thread-scoped implementations can read stable host inputs through [`Self::thread_init`] and
/// keep their cache in [`Self::thread_store`]. Implementations should not retain borrowed context
/// after contribution completes.
pub struct McpServerContributionContext<'a, C> {
/// Host configuration visible during MCP resolution.
config: &'a C,
/// Whether pending auth differs from published auth; invalidate catalogs before projection.
auth_changed: bool,
/// Extension-owned data for the active thread, when resolution is thread-scoped.
thread_store: Option<&'a ExtensionData>,
/// Stable host inputs for the active thread, when resolution is thread-scoped.
thread_init: Option<&'a ExtensionDataInit>,
/// Source of the active thread, when supplied by the host runtime.
session_source: Option<&'a SessionSource>,
/// Effective request originator for the active thread, when resolution is thread-scoped.
originator: Option<&'a str>,
/// All selected environments captured for this projection, in priority order.
selected_environments: Option<&'a [TurnEnvironmentSelection]>,
/// Selected roots resolved against ready environments for this exact step.
ready_selected_capability_roots: Option<&'a [SelectedCapabilityRoot]>,
/// Executor-materialized capability files shared by all consumers in this exact step.
executor_capability_discovery: Option<&'a ExecutorCapabilityDiscoverySnapshot>,
/// V2 inventories supplied by the host for this contribution.
executor_capability_discovery_v2: Option<&'a [ExecutorCapabilityDiscoveryV2Snapshot]>,
}
impl<C> Clone for McpServerContributionContext<'_, C> {
fn clone(&self) -> Self {
*self
}
}
impl<C> Copy for McpServerContributionContext<'_, C> {}
impl<'a, C> McpServerContributionContext<'a, C> {
/// Creates context for resolution that is not associated with a running thread.
pub fn global(config: &'a C) -> Self {
Self {
config,
auth_changed: false,
thread_store: None,
thread_init: None,
session_source: None,
originator: None,
selected_environments: None,
ready_selected_capability_roots: None,
executor_capability_discovery: None,
executor_capability_discovery_v2: None,
}
}
/// Creates context for one model step using only currently available environments.
pub fn for_step(
config: &'a C,
thread_init: &'a ExtensionDataInit,
thread_store: &'a ExtensionData,
originator: &'a str,
ready_selected_capability_roots: &'a [SelectedCapabilityRoot],
executor_capability_discovery: Option<&'a ExecutorCapabilityDiscoverySnapshot>,
executor_capability_discovery_v2: Option<&'a [ExecutorCapabilityDiscoveryV2Snapshot]>,
) -> Self {
Self {
config,
auth_changed: false,
thread_store: Some(thread_store),
thread_init: Some(thread_init),
session_source: None,
originator: Some(originator),
selected_environments: None,
ready_selected_capability_roots: Some(ready_selected_capability_roots),
executor_capability_discovery,
executor_capability_discovery_v2,
}
}
/// Attaches the same environment snapshot used to project MCP authority.
///
/// Preserve pending and failed selections: an unavailable primary executor
/// must not silently select a different ready executor for hosted tools.
pub fn with_selected_environments(
mut self,
environments: &'a [TurnEnvironmentSelection],
) -> Self {
self.selected_environments = Some(environments);
self
}
/// Returns the selected executor snapshot, or `None` for threadless discovery.
/// An empty slice means the thread explicitly has no selected environments.
pub fn selected_environments(&self) -> Option<&'a [TurnEnvironmentSelection]> {
self.selected_environments
}
/// Marks whether this projection replaces the published MCP authentication.
pub fn with_auth_changed(mut self, auth_changed: bool) -> Self {
self.auth_changed = auth_changed;
self
}
/// Returns whether auth-scoped catalogs must be invalidated before projection.
pub fn auth_changed(&self) -> bool {
self.auth_changed
}
/// Attaches the stable source of the active thread to this contribution.
pub fn with_session_source(mut self, session_source: &'a SessionSource) -> Self {
self.session_source = Some(session_source);
self
}
/// Returns the host configuration visible during resolution.
pub fn config(&self) -> &'a C {
self.config
}
/// Returns extension-owned state when resolving for a running thread.
pub fn thread_store(&self) -> Option<&'a ExtensionData> {
self.thread_store
}
/// Returns stable host inputs when resolving for a running thread.
pub fn thread_init(&self) -> Option<&'a ExtensionDataInit> {
self.thread_init
}
/// Returns the active thread's source when supplied by the host runtime.
pub fn session_source(&self) -> Option<&'a SessionSource> {
self.session_source
}
/// Returns the effective request originator when resolving for a running thread.
pub fn originator(&self) -> Option<&'a str> {
self.originator
}
/// Returns selected roots resolved against the ready environments for this model step.
pub fn ready_selected_capability_roots(&self) -> Option<&'a [SelectedCapabilityRoot]> {
self.ready_selected_capability_roots
}
/// `Some` selects V2, including an empty inventory list; `None` selects legacy discovery.
pub fn executor_capability_discovery_v2(
&self,
) -> Option<&'a [ExecutorCapabilityDiscoveryV2Snapshot]> {
self.executor_capability_discovery_v2
}
/// Returns the executor-materialized capability files for this model step, when enabled.
pub fn executor_capability_discovery(&self) -> Option<&'a ExecutorCapabilityDiscoverySnapshot> {
self.executor_capability_discovery
}
}
/// Selected plugin identities and executor roots whose skills must be hidden.
#[derive(Clone, Debug, Default)]
pub struct SelectedPluginSnapshot {
pub plugins: Vec<SelectedPluginIdentity>,
/// Selected plugin roots suppressed by the effective plugin feature policy.
pub disabled_plugin_roots: Vec<String>,
pub disabled_plugin_ids: Vec<String>,
}
/// The configured identity of a selected plugin and, when present, the root owning its skills.
#[derive(Clone, Debug)]
pub struct SelectedPluginIdentity {
/// Hosted plugins have no executor root and cannot own skills from an executor folder.
pub selected_root_id: Option<String>,
pub plugin_id: PluginIdentity,
}
/// 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
/// it has no MCP data.
pub struct SelectedPlugin<'a> {
pub selected_root_id: String,
pub plugin_id: String,
pub identity: PluginIdentity,
pub enabled: bool,
pub mcp: ExtensionFuture<'a, SelectedPluginContribution>,
}
/// MCP data attributed by the host to the plugin that declared it.
#[derive(Clone)]
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)>,
}
/// One extension-owned overlay for the runtime MCP server configuration.
#[derive(Clone, Debug)]
pub enum McpServerContribution {
/// Adds or replaces a named MCP server.
Set {
name: String,
config: Box<McpServerConfig>,
},
/// 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.
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 },
}

View File

@@ -0,0 +1,94 @@
//! Extension prompt placement with content and producer attribution kept together.
use codex_context_fragments::AnnotatedContent;
use codex_context_fragments::ContextualUserFragment;
use codex_context_fragments::RenderedFragment;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ContentItemKind;
use codex_protocol::models::ContentItemMetadata;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PromptSlot {
DeveloperPolicy,
DeveloperCapabilities,
/// Content inside the context-window message, supplied by `contribute_thread_context`.
ContextWindow,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PromptFragment {
slot: PromptSlot,
content: AnnotatedContent,
}
impl PromptFragment {
/// Places a contextual fragment in the prompt, preserving its content, kind, and source.
/// The slot determines placement within the developer message, regardless of its original role.
pub fn from_fragment(slot: PromptSlot, fragment: &impl ContextualUserFragment) -> Self {
Self {
slot,
content: fragment.render_fragment().into_parts().1,
}
}
/// Creates harness-provided context for the given slot.
pub fn new(slot: PromptSlot, text: impl Into<String>, content_kind: ContentItemKind) -> Self {
Self {
slot,
content: AnnotatedContent::text(text, content_kind, ContentItemMetadata::harness()),
}
}
/// Creates tool-supplied context without changing its prompt placement.
pub fn tool(
slot: PromptSlot,
text: impl Into<String>,
content_kind: ContentItemKind,
namespace: String,
) -> Self {
Self {
slot,
content: AnnotatedContent::text(
text,
content_kind,
ContentItemMetadata::tool(Some(namespace.into())),
),
}
}
/// Creates a developer-policy prompt fragment.
pub fn developer_policy(text: impl Into<String>, content_kind: ContentItemKind) -> Self {
Self::new(PromptSlot::DeveloperPolicy, text, content_kind)
}
/// Creates a developer-capabilities prompt fragment.
pub fn developer_capability(text: impl Into<String>, content_kind: ContentItemKind) -> Self {
Self::new(PromptSlot::DeveloperCapabilities, text, content_kind)
}
/// Returns the target prompt slot.
pub fn slot(&self) -> PromptSlot {
self.slot
}
/// Returns the model-visible content.
pub fn content(&self) -> &ContentItem {
self.content.content()
}
/// Returns the producer-owned classification of the model-visible content.
pub fn content_kind(&self) -> &ContentItemKind {
self.content.kind()
}
/// Consumes the placement wrapper when assembling a shared context message.
pub fn into_content(self) -> AnnotatedContent {
self.content
}
}
impl From<PromptFragment> for RenderedFragment {
fn from(fragment: PromptFragment) -> Self {
Self::new("developer", fragment.content)
}
}

View File

@@ -0,0 +1,26 @@
use crate::ExtensionData;
/// Input supplied when the host or an extension observes one skill invocation.
pub struct SkillInvocationInput<'a> {
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
/// Store scoped to this turn runtime.
pub turn_store: &'a ExtensionData,
/// Current turn submission id.
pub turn_id: &'a str,
/// Main prompt path or opaque resource id for the invoked skill.
pub skill_resource: &'a str,
/// How the skill invocation was initiated.
pub kind: SkillInvocationKind,
}
/// How an observed skill invocation was initiated.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SkillInvocationKind {
/// The user explicitly mentioned the skill.
Explicit,
/// The model read the skill instructions or ran one of its scripts.
Implicit,
}

View File

@@ -0,0 +1,84 @@
use std::sync::Arc;
use crate::ExtensionData;
use crate::ExtensionMetrics;
use codex_mcp::McpResourceClient;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::TurnEnvironmentSelection;
/// Trusted, host-resolved billing attribution for a thread.
///
/// Extensions may forward this value to first-party APIs. It is seeded by Core
/// after resolving persisted and host-provided originator state, rather than
/// from model- or tool-controlled input.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ThreadOriginator(pub String);
/// Input supplied when the host starts a runtime for a thread.
pub struct ThreadStartInput<'a, C> {
/// Host configuration visible at thread start.
pub config: &'a C,
/// Source that created the session for this thread.
pub session_source: &'a SessionSource,
/// Whether persistent thread-scoped state is available for this thread.
pub persistent_thread_state_available: bool,
/// Execution environments selected for this thread.
pub environments: &'a [TurnEnvironmentSelection],
/// MCP resource access supplied by the host for this session.
pub mcp_resource_client: Option<Arc<McpResourceClient>>,
/// Session-attributed metrics supplied by the host.
pub extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
}
/// Input supplied after the host has registered a fully initialized thread.
pub struct ThreadReadyInput<'a, C> {
/// Host configuration visible after thread registration.
pub config: &'a C,
/// Source that created the session for this thread.
pub session_source: &'a SessionSource,
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
}
/// Input supplied when the host resumes an existing thread.
pub struct ThreadResumeInput<'a> {
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
}
/// Why a thread has no immediately pending work.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ThreadIdleCause {
/// The previous turn completed and automatic follow-up work can run.
Completed,
/// The user interrupted the previous turn.
Interrupted,
/// The previous turn ended with a terminal error.
Failed,
}
/// Input supplied when the host has no immediately pending thread work.
pub struct ThreadIdleInput<'a> {
/// Why the thread became idle.
pub cause: ThreadIdleCause,
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
}
/// Input supplied during runtime teardown, before persistent history closes.
pub struct ThreadStopInput<'a> {
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
}

View File

@@ -0,0 +1,272 @@
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use codex_config::McpServerConfig;
use codex_file_system::ExecutorFileSystem;
use codex_mcp::McpServerSource;
use codex_mcp::PreparedMcpCall;
use codex_mcp::ResolvedMcpServer;
use codex_protocol::mcp::CallToolResult;
use codex_tools::ToolCallSource;
use codex_tools::ToolName;
use codex_tools::ToolPayload;
use codex_utils_path_uri::PathUri;
use crate::ConversationHistorySnapshot;
use crate::ExtensionData;
/// Future returned by one tool-lifecycle callback.
pub type ToolLifecycleFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
/// Extension-facing outcome for a finished tool call.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ToolCallOutcome {
/// The tool returned a normal output.
Completed {
/// The tool output's own success marker for telemetry/logging.
success: bool,
},
/// The tool was blocked by host policy before the handler ran.
Blocked,
/// The tool did not produce a normal output.
Failed {
/// Whether the host reached the tool handler before the failure.
handler_executed: bool,
},
/// The host cancelled the tool before normal completion. Cancellation can
/// win before the dispatch path accepts the call, so contributors should not
/// assume a matching start callback exists.
Aborted,
}
/// 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.
Plugin {
/// Identifier of the plugin that owns this MCP server.
id: String,
/// Host-local plugin root captured with the exact server registration.
root: PathUri,
},
/// An executor-selected plugin whose root has not been attested by the host.
SelectedPlugin,
/// A compatibility or extension registration without user-owned provenance.
Other,
}
/// Read-only metadata and provenance captured from the MCP call that will execute.
#[derive(Clone, Debug)]
pub struct McpToolContext {
tool: crate::McpToolInfo,
source: McpToolSource,
}
impl McpToolContext {
/// Snapshots a prepared call without exposing its executable client to extensions.
///
/// Configured servers retain their provenance only when their captured connection
/// still matches the host configuration for the current tool invocation.
pub fn from_prepared_call(
call: &PreparedMcpCall,
configured_server: Option<&McpServerConfig>,
) -> 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() {
McpToolSource::SelectedPlugin
} else if let Some(McpServerSource::Plugin(plugin)) =
registration.map(ResolvedMcpServer::source)
&& Some(plugin.plugin_id()) == call.plugin_id()
&& let Some(root) = plugin.host_root()
{
McpToolSource::Plugin {
id: plugin.plugin_id().to_owned(),
root: root.clone(),
}
} else if registration.is_some_and(|server| {
matches!(server.source(), McpServerSource::Config)
&& configured_server.is_some_and(|configured| server.config() == configured)
}) {
McpToolSource::Config
} else {
McpToolSource::Other
};
Self { tool, source }
}
/// Returns frozen metadata for the exact model-visible MCP tool being executed.
pub fn tool_info(&self) -> &crate::McpToolInfo {
&self.tool
}
/// Returns the registration source captured with the executable call.
pub fn source(&self) -> &McpToolSource {
&self.source
}
}
/// Input supplied when the host starts executing one tool call.
pub struct ToolStartInput<'a> {
/// Final serving assessment for the unchanged action, including its code cell's value.
/// When present, replaces asynchronous scoring; it does not grant execution permission.
pub serving_assessment: Option<bool>,
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
/// Store scoped to this turn runtime.
pub turn_store: &'a ExtensionData,
/// Current turn submission id.
pub turn_id: &'a str,
/// Trusted causal root of the owning turn, absent when unknown or ambiguous.
pub root_turn_id: Option<&'a str>,
/// Model-visible tool call id.
pub call_id: &'a str,
/// Responses item that issued this call or started its code-mode cell.
/// Hosts preserve the original wrapper identity across yields and waits.
pub originating_item_id: Option<&'a codex_protocol::ResponseItemId>,
/// Tool name as routed by the host.
pub tool_name: &'a ToolName,
/// Read-only metadata and provenance from the exact MCP call that will execute.
pub mcp_tool: Option<&'a McpToolContext>,
/// Resolves evidence from the issuing step only when awaited; `None` prevents cached approval.
pub permissions: crate::ExtensionFuture<'a, Option<codex_guardian_context::PermissionContext>>,
/// Finalized tool arguments, including any pre-tool-use hook rewrites.
///
/// Payloads can contain sensitive plaintext and must not be logged.
pub payload: &'a ToolPayload,
/// Shared read-only snapshot taken after pre-tool hooks have completed.
pub conversation_history: Arc<dyn ConversationHistorySnapshot>,
/// Source that issued the tool call.
pub source: ToolCallSource,
}
/// Finalized builtin command and the executor that will run it.
///
/// This runs after command hooks and environment resolution, before command
/// attribution and measurement selection. Filesystem paths belong to the selected
/// executor and must not be interpreted as host-local paths.
pub struct CommandStartInput<'a> {
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
/// Store scoped to this turn runtime.
pub turn_store: &'a ExtensionData,
/// Current turn submission id.
pub turn_id: &'a str,
/// Host tool call id.
pub call_id: &'a str,
/// Resolved argv, including the selected executor's shell wrapper.
/// Commands can contain sensitive plaintext and must not be logged.
pub command: &'a [String],
/// Effective working directory in the selected executor.
pub cwd: &'a PathUri,
/// Filesystem of the selected executor.
pub file_system: &'a dyn ExecutorFileSystem,
}
/// Input supplied after an MCP server responds, before the host reports completion.
pub struct McpToolResultInput<'a> {
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
/// Store scoped to this turn runtime.
pub turn_store: &'a ExtensionData,
/// Current turn submission id.
pub turn_id: &'a str,
/// Host tool call id, also used in the MCP completion notification.
pub call_id: &'a str,
/// Read-only metadata and provenance from the exact MCP call that executed.
pub mcp_tool: &'a McpToolContext,
/// Tool arguments after host-side rewriting, including file uploads.
pub arguments: &'a serde_json::Value,
/// Server response, including `_meta`. Changes feed the normal client and model output paths.
///
/// Arguments and results can contain sensitive plaintext and must not be logged.
pub result: &'a mut CallToolResult,
}
/// Input supplied when the host finishes executing one tool call.
pub struct ToolFinishInput<'a> {
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
/// Store scoped to this turn runtime.
pub turn_store: &'a ExtensionData,
/// Current turn submission id.
pub turn_id: &'a str,
/// Model-visible tool call id.
pub call_id: &'a str,
/// Tool name as routed by the host.
pub tool_name: &'a ToolName,
/// Source that issued the tool call.
pub source: ToolCallSource,
/// Host-observed result of the tool call.
pub outcome: ToolCallOutcome,
}
/// The execution interval represented by a tool timing observation.
#[derive(Clone, Copy, Debug)]
pub enum ToolTimingBoundary {
/// Elapsed time from admission through the parallel-execution gate until the
/// outer dispatch completes or is dropped. Includes routing, hooks, policy
/// checks, and result processing; excludes runtime readiness and gate waiting.
/// Zero if dispatch never passed the gate.
Handler,
/// Duration reported by the code-mode host for its exec or wait operation.
/// Measures the remote operation rather than the enclosing local dispatch.
HostOperation,
}
/// Lifecycle of work that continues after a code-mode `exec` yields.
#[derive(Clone, Copy, Debug)]
pub enum CodeModeCellTiming {
ExecYielded,
WaitFinished {
/// Time the finished result was buffered before this wait retrieved it.
result_buffered_for: std::time::Duration,
},
/// The runtime reported that the cell is missing or closed; its completion time is unknown.
CellUnavailable,
}
/// A measured tool interval. Handler observations also cover cancellation;
/// host-operation observations are available only when the host reports a duration.
/// Observers must not block.
pub struct ToolTimingInput<'a> {
/// Thread that owns the tool call.
pub thread_id: &'a str,
/// Current turn submission id.
pub turn_id: &'a str,
/// Model-visible tool call id used to correlate dispatch and timing observations.
pub call_id: &'a str,
/// Execution interval measured by this observation.
pub boundary: ToolTimingBoundary,
/// Elapsed time within the specified boundary.
pub duration: std::time::Duration,
}
/// A direct call entering dispatch, before readiness, hooks, or policy checks.
/// Observers must return promptly and cannot affect tool execution.
pub struct ToolDispatchInput<'a> {
/// Thread that owns the tool call.
pub thread_id: &'a str,
/// Current turn submission id.
pub turn_id: &'a str,
/// Model-visible tool call id used to correlate dispatch and timing observations.
pub call_id: &'a str,
/// Tool name supplied to dispatch, before pre-tool hooks run.
pub tool_name: &'a ToolName,
}

View File

@@ -0,0 +1,50 @@
use codex_file_system::EnvironmentAccess;
use codex_protocol::user_input::UserInput;
use codex_utils_path_uri::PathUri;
use std::fmt;
/// Host-owned turn environment summary visible to turn-input contributors.
#[derive(Clone)]
pub struct TurnInputEnvironment<'a> {
/// Stable host environment id used to route executor-scoped capabilities.
pub environment_id: String,
/// Effective working directory for this turn in the environment.
pub cwd: PathUri,
/// Whether this is the primary environment for the turn.
pub is_primary: bool,
/// Filesystem access with the permissions captured for this model turn.
pub fs: &'a dyn EnvironmentAccess,
}
/// Turn facts supplied before the host records turn-local model input items.
#[derive(Clone)]
pub struct TurnInputContext<'a> {
/// Prepared extension snapshots and read routes for the step processing this input.
pub step_store: &'a crate::ExtensionData,
/// Stable host-owned turn identifier.
pub turn_id: String,
/// User input submitted for this turn.
pub user_input: Vec<UserInput>,
/// Resolved turn environments, in host priority order.
pub environments: Vec<TurnInputEnvironment<'a>>,
}
impl fmt::Debug for TurnInputEnvironment<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TurnInputEnvironment")
.field("environment_id", &self.environment_id)
.field("cwd", &self.cwd)
.field("is_primary", &self.is_primary)
.finish_non_exhaustive()
}
}
impl fmt::Debug for TurnInputContext<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TurnInputContext")
.field("turn_id", &self.turn_id)
.field("user_input", &self.user_input)
.field("environments", &self.environments)
.finish_non_exhaustive()
}
}

View File

@@ -0,0 +1,81 @@
//! Turn lifecycle inputs and scheduling phases for host-owned contributors.
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::TokenUsage;
use codex_protocol::protocol::TurnAbortReason;
use crate::ExtensionData;
/// Runs before task registration or during cancellable regular-task startup.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TurnStartPhase {
BeforeTaskRegistration,
RegularTaskStart,
}
/// Input supplied when the host starts a turn.
pub struct TurnStartInput<'a> {
/// Stable host-owned turn identifier.
pub turn_id: &'a str,
/// Effective collaboration mode for this turn.
pub collaboration_mode: &'a CollaborationMode,
/// Total token usage snapshot captured when the turn started.
/// Present before task registration; absent during regular-task preparation.
/// Token-accounting contributors must remain in `BeforeTaskRegistration`.
pub token_usage_at_turn_start: Option<&'a TokenUsage>,
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
/// Store scoped to this turn runtime.
pub turn_store: &'a ExtensionData,
}
/// Inputs for refreshing catalogs before a model step.
#[derive(Clone, Copy)]
pub struct CatalogRefreshInput<'a> {
pub turn_id: &'a str,
pub session_store: &'a ExtensionData,
pub thread_store: &'a ExtensionData,
pub turn_store: &'a ExtensionData,
}
/// Input supplied when the host completes a turn.
pub struct TurnStopInput<'a> {
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
/// Store scoped to this turn runtime.
pub turn_store: &'a ExtensionData,
}
/// Input supplied when the host aborts a turn.
pub struct TurnAbortInput<'a> {
/// Reason the host aborted the turn.
pub reason: TurnAbortReason,
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
/// Store scoped to this turn runtime.
pub turn_store: &'a ExtensionData,
}
/// Input supplied when the host observes an error for a turn.
pub struct TurnErrorInput<'a> {
/// Stable host-owned turn identifier.
pub turn_id: &'a str,
/// Error surfaced by the host for this turn.
pub error: CodexErrorInfo,
/// Original error details, including backend metadata omitted from the public category.
pub error_details: &'a CodexErrorDetails,
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
/// Store scoped to this turn runtime.
pub turn_store: &'a ExtensionData,
}

View File

@@ -0,0 +1,200 @@
use std::sync::Arc;
use codex_protocol::ThreadId;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ContentItemMetadata;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::protocol::TurnEnvironmentSelection;
use serde_json::Value;
use crate::ExtensionData;
use crate::ExtensionMetrics;
/// Host state available while an extension contributes one sampling step's World State.
pub struct WorldStateContributionInput<'a> {
pub thread_id: ThreadId,
pub turn_id: &'a str,
/// Resolved model metadata captured for this sampling step, retained across discovery.
pub model_info: &'a ModelInfo,
pub environments: &'a [TurnEnvironmentSelection],
/// Metrics bound to the captured model for this sampling step.
pub extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
pub session_store: &'a ExtensionData,
pub thread_store: &'a ExtensionData,
pub turn_store: &'a ExtensionData,
/// The same captured extension inputs that were used to build this step's tools.
pub step_store: &'a ExtensionData,
/// Persisted comparison state from the last recorded step. Its rendered text may have
/// left model history; use a retained-fragment matcher before referring back to it.
/// After compaction, sections may contain only retained extension metadata.
pub previous_world_state: Option<&'a serde_json::Map<String, Value>>,
}
/// What the harness knows about the previous value of one extension-owned section.
pub enum PreviousWorldStateSection<'a> {
Absent,
Unknown,
Known(&'a Value),
}
/// Model-visible content rendered by an extension-owned World State section.
/// Markers apply only to `InputText` bodies.
/// The producer owns size bounds for the content; rendering does not truncate it.
/// Non-text user-role bodies are currently classified as ordinary user media.
#[derive(Clone, Debug, PartialEq)]
pub struct RenderedWorldStateFragment {
role: &'static str,
markers: (&'static str, &'static str),
body: ContentItem,
metadata: ContentItemMetadata,
}
impl RenderedWorldStateFragment {
pub fn new(
role: &'static str,
markers: (&'static str, &'static str),
body: ContentItem,
) -> Self {
Self {
role,
markers,
body,
metadata: ContentItemMetadata::harness(),
}
}
/// Attach the producer's source before the harness assembles the context message.
pub fn with_metadata(mut self, metadata: ContentItemMetadata) -> Self {
self.metadata = metadata;
self
}
pub fn metadata(&self) -> &ContentItemMetadata {
&self.metadata
}
pub fn role(&self) -> &'static str {
self.role
}
pub fn markers(&self) -> (&'static str, &'static str) {
self.markers
}
pub fn body(&self) -> &ContentItem {
&self.body
}
}
type RenderDiff = dyn for<'a> Fn(PreviousWorldStateSection<'a>) -> (Option<Value>, Option<RenderedWorldStateFragment>)
+ Send
+ Sync;
type LegacyFragmentMatcher = dyn Fn(&str, &str) -> bool + Send + Sync;
/// One extension-owned World State section captured for a sampling step.
///
/// The extension owns the stable ID, comparison snapshot, and diff rendering. The harness owns
/// persistence and the concrete model-context fragment envelope.
#[derive(Clone)]
pub struct WorldStateSectionContribution {
id: &'static str,
include_in_full_context: bool,
window_prefix: bool,
render_diff: Arc<RenderDiff>,
matches_legacy_fragment: Arc<LegacyFragmentMatcher>,
matches_retained_fragment: Option<Arc<LegacyFragmentMatcher>>,
}
impl WorldStateSectionContribution {
/// Return a replacement snapshot and/or fragment. A missing snapshot retains the
/// previous section state; a missing fragment emits no model-visible update. A null
/// snapshot removes the section from persisted state.
pub fn new(
id: &'static str,
render_diff: impl for<'a> Fn(
PreviousWorldStateSection<'a>,
) -> (Option<Value>, Option<RenderedWorldStateFragment>)
+ Send
+ Sync
+ 'static,
) -> Self {
Self {
id,
include_in_full_context: true,
window_prefix: false,
render_diff: Arc::new(render_diff),
matches_legacy_fragment: Arc::new(|_, _| false),
matches_retained_fragment: None,
}
}
/// Recompute this section during ordinary step context updates instead of replaying
/// its captured value when initial or compacted context is rebuilt. Full rendering
/// omits both its fragment and comparison snapshot so a fresh contribution can emit.
/// After prefix compaction, the next diff receives [`PreviousWorldStateSection::Unknown`]
/// if the section's legacy matcher recognizes text in the retained suffix.
pub fn without_full_context(mut self) -> Self {
self.include_in_full_context = false;
self
}
pub fn include_in_full_context(&self) -> bool {
self.include_in_full_context
}
pub fn with_legacy_matcher(
mut self,
matcher: impl Fn(&str, &str) -> bool + Send + Sync + 'static,
) -> Self {
self.matches_legacy_fragment = Arc::new(matcher);
self
}
/// Render this section's developer fragments as separate messages before retained
/// history when the harness builds a window (including after compaction). Changes
/// within an existing window are still appended as ordinary history updates.
/// Fragments with any other role are not rendered, including in history updates.
/// The producer still owns content size bounds; prefix placement does not truncate.
pub fn with_window_prefix(mut self) -> Self {
self.window_prefix = true;
self
}
pub fn is_window_prefix(&self) -> bool {
self.window_prefix
}
/// Requires a matching model-visible fragment whenever a persisted snapshot is reused.
pub fn with_retained_fragment_matcher(
mut self,
matcher: impl Fn(&str, &str) -> bool + Send + Sync + 'static,
) -> Self {
self.matches_retained_fragment = Some(Arc::new(matcher));
self
}
pub fn id(&self) -> &'static str {
self.id
}
pub fn render_diff(
&self,
previous: PreviousWorldStateSection<'_>,
) -> (Option<Value>, Option<RenderedWorldStateFragment>) {
(self.render_diff)(previous)
}
pub fn matches_legacy_fragment(&self, role: &str, text: &str) -> bool {
(self.matches_legacy_fragment)(role, text)
}
pub fn has_retained_fragment_matcher(&self) -> bool {
self.matches_retained_fragment.is_some()
}
pub fn matches_retained_fragment(&self, role: &str, text: &str) -> bool {
self.matches_retained_fragment
.as_ref()
.is_some_and(|matcher| matcher(role, text))
}
}