Base: codex-main originale (prima del fork aKode)
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
use codex_history::CompactionCheckpoint;
|
||||
use codex_history::RetainedContext;
|
||||
|
||||
use codex_protocol::models::ResponseItem;
|
||||
|
||||
/// Read-only conversation-history snapshot supplied by the extension host.
|
||||
///
|
||||
/// Implementations should retain the host's existing snapshot storage rather than
|
||||
/// copying response payloads into an extension-owned collection.
|
||||
pub trait ConversationHistorySnapshot: Send + Sync {
|
||||
/// Returns the generation of the history captured by this snapshot.
|
||||
fn history_version(&self) -> u64;
|
||||
|
||||
/// Host-owned revision captured with this snapshot. Advances on user messages and
|
||||
/// history resets, but stays unchanged for compaction and internal context.
|
||||
fn user_message_revision(&self) -> u64;
|
||||
|
||||
/// Changes when host-confirmed assistant evidence can change how Guardian interprets input.
|
||||
/// Hosts without out-of-band assistant evidence may retain the default.
|
||||
fn guardian_review_context_revision(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
/// Returns the snapshot's response items in conversation order.
|
||||
fn items(&self) -> Box<dyn Iterator<Item = &ResponseItem> + Send + '_>;
|
||||
|
||||
/// Host-owned retained facts captured atomically with the parent model window.
|
||||
/// These facts may be available while review still uses a legacy transcript.
|
||||
fn retained_context(&self) -> Option<&RetainedContext> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether review uses the parent checkpoint and model window instead of a legacy transcript.
|
||||
/// Checkpoint compatibility is independent of access to retained user evidence.
|
||||
fn uses_parent_context_for_review(&self) -> bool {
|
||||
self.retained_context().is_some()
|
||||
}
|
||||
|
||||
/// Whether the host retains a bounded review transcript independently of parent compaction.
|
||||
/// Such snapshots must never seed reviewers with the parent's opaque checkpoint.
|
||||
fn uses_independent_review_history(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Latest opaque checkpoint, including unusable items, with its recorded producer.
|
||||
/// Hosts without provenance leave the producer unknown rather than using the live model.
|
||||
fn latest_compaction(&self) -> Option<CompactionCheckpoint<'_>> {
|
||||
self.items()
|
||||
.filter_map(|item| CompactionCheckpoint::from_item(item, /*model_hash*/ None))
|
||||
.last()
|
||||
}
|
||||
|
||||
/// Original review evidence retained across parent compaction, in conversation order.
|
||||
/// Hosts without separate retention provide their current history.
|
||||
fn review_items(&self) -> Box<dyn Iterator<Item = &ResponseItem> + Send + '_> {
|
||||
self.items()
|
||||
}
|
||||
|
||||
/// Original source metadata stays attached to the exact unshortened history item.
|
||||
/// Legacy providers cannot establish completeness from a message ID alone.
|
||||
fn review_items_with_sources(
|
||||
&self,
|
||||
) -> Box<dyn Iterator<Item = (&ResponseItem, Option<&codex_history::RetainedSource>)> + Send + '_>
|
||||
{
|
||||
Box::new(self.review_items().map(|item| (item, None)))
|
||||
}
|
||||
|
||||
/// Changes whenever offsets into the retained review evidence become invalid.
|
||||
fn review_history_version(&self) -> u64 {
|
||||
self.history_version()
|
||||
}
|
||||
}
|
||||
38
codex-rs/ext/extension-api/src/capabilities/events.rs
Normal file
38
codex-rs/ext/extension-api/src/capabilities/events.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
use codex_protocol::protocol::Event;
|
||||
|
||||
/// Extension warning with an explicit thread target and optional turn correlation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ExtensionWarning {
|
||||
/// Stable host-owned thread identifier used for delivery.
|
||||
pub thread_id: String,
|
||||
/// Stable host-owned turn identifier when the warning arose in a turn callback.
|
||||
pub turn_id: Option<String>,
|
||||
/// Concise warning message for the user.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Host-provided fire-and-forget sink for extension-generated events.
|
||||
///
|
||||
/// Extensions construct protocol events with the correlation id appropriate for
|
||||
/// the callback they are handling, then leave persistence, ordering, transport
|
||||
/// fanout, and logging decisions to the host.
|
||||
pub trait ExtensionEventSink: Send + Sync {
|
||||
/// Queue one protocol event for host-owned delivery.
|
||||
fn emit(&self, event: Event);
|
||||
|
||||
/// Queue one warning for host-owned delivery.
|
||||
///
|
||||
/// Implementations must use [`ExtensionWarning::thread_id`] for routing. The optional
|
||||
/// [`ExtensionWarning::turn_id`] is correlation metadata and does not identify a thread.
|
||||
fn emit_warning(&self, warning: ExtensionWarning);
|
||||
}
|
||||
|
||||
/// Event sink used when the host does not expose extension event emission.
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub struct NoopExtensionEventSink;
|
||||
|
||||
impl ExtensionEventSink for NoopExtensionEventSink {
|
||||
fn emit(&self, _event: Event) {}
|
||||
|
||||
fn emit_warning(&self, _warning: ExtensionWarning) {}
|
||||
}
|
||||
48
codex-rs/ext/extension-api/src/capabilities/metrics.rs
Normal file
48
codex-rs/ext/extension-api/src/capabilities/metrics.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
/// Host-provided metrics capability for extension-owned behavior.
|
||||
///
|
||||
/// Implementations are expected to attach the host's session attribution before
|
||||
/// forwarding samples to the configured metrics backend.
|
||||
pub trait ExtensionMetrics: Send + Sync {
|
||||
/// Increments a counter with optional extension-provided tags.
|
||||
fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]);
|
||||
|
||||
/// Records one histogram sample with optional extension-provided tags.
|
||||
fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]);
|
||||
|
||||
/// Records a histogram with explicit buckets, preserving host attribution.
|
||||
/// All callers of the same metric name must use the same boundaries.
|
||||
fn histogram_with_boundaries(
|
||||
&self,
|
||||
name: &str,
|
||||
value: i64,
|
||||
boundaries: &[f64],
|
||||
tags: &[(&str, &str)],
|
||||
);
|
||||
}
|
||||
|
||||
/// Records a published catalog size, with partial results taking precedence over warnings.
|
||||
pub fn record_catalog_entries(
|
||||
metrics: Option<&dyn ExtensionMetrics>,
|
||||
name: &str,
|
||||
stage: &str,
|
||||
entry_count: usize,
|
||||
is_partial: bool,
|
||||
warning_count: usize,
|
||||
) {
|
||||
let Some(metrics) = metrics else {
|
||||
return;
|
||||
};
|
||||
let status = if is_partial {
|
||||
"partial"
|
||||
} else if warning_count > 0 {
|
||||
"warning"
|
||||
} else {
|
||||
"complete"
|
||||
};
|
||||
metrics.histogram_with_boundaries(
|
||||
name,
|
||||
i64::try_from(entry_count).unwrap_or(i64::MAX),
|
||||
&[0., 1., 2., 5., 10., 20., 50., 100., 200., 500., 1000.],
|
||||
&[("stage", stage), ("status", status)],
|
||||
);
|
||||
}
|
||||
14
codex-rs/ext/extension-api/src/capabilities/mod.rs
Normal file
14
codex-rs/ext/extension-api/src/capabilities/mod.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
mod conversation_history;
|
||||
mod events;
|
||||
mod metrics;
|
||||
mod response_items;
|
||||
|
||||
pub use conversation_history::ConversationHistorySnapshot;
|
||||
pub use events::ExtensionEventSink;
|
||||
pub use events::ExtensionWarning;
|
||||
pub use events::NoopExtensionEventSink;
|
||||
pub use metrics::ExtensionMetrics;
|
||||
pub use metrics::record_catalog_entries;
|
||||
pub use response_items::NoopResponseItemInjector;
|
||||
pub use response_items::ResponseItemInjectionFuture;
|
||||
pub use response_items::ResponseItemInjector;
|
||||
@@ -0,0 +1,33 @@
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
|
||||
/// Future returned when an extension asks the host to inject model-visible input.
|
||||
pub type ResponseItemInjectionFuture<'a> =
|
||||
Pin<Box<dyn Future<Output = Result<(), Vec<ResponseInputItem>>> + Send + 'a>>;
|
||||
|
||||
/// Host-provided helper for extensions that need to steer the active model turn.
|
||||
///
|
||||
/// Implementations should inject the supplied response items into the active turn
|
||||
/// when one can accept same-turn model input. If injection is unavailable, they
|
||||
/// return the unchanged items to the caller.
|
||||
pub trait ResponseItemInjector: Send + Sync {
|
||||
fn inject_response_items<'a>(
|
||||
&'a self,
|
||||
items: Vec<ResponseInputItem>,
|
||||
) -> ResponseItemInjectionFuture<'a>;
|
||||
}
|
||||
|
||||
/// Injector used when a host does not expose same-turn model steering.
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub struct NoopResponseItemInjector;
|
||||
|
||||
impl ResponseItemInjector for NoopResponseItemInjector {
|
||||
fn inject_response_items<'a>(
|
||||
&'a self,
|
||||
items: Vec<ResponseInputItem>,
|
||||
) -> ResponseItemInjectionFuture<'a> {
|
||||
Box::pin(std::future::ready(Err(items)))
|
||||
}
|
||||
}
|
||||
55
codex-rs/ext/extension-api/src/catalog_refresh.rs
Normal file
55
codex-rs/ext/extension-api/src/catalog_refresh.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
//! Thread-owned cloud catalog retry cooldowns scoped to auth and resource generations.
|
||||
|
||||
use codex_mcp::McpResourceClientAuthKey;
|
||||
use codex_mcp::McpResourceServerCacheKey;
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
|
||||
/// Store per catalog and thread; clear on success or configuration reset.
|
||||
#[derive(Clone)]
|
||||
pub struct CatalogRefreshBackoff {
|
||||
auth: Option<McpResourceClientAuthKey>,
|
||||
resources: Option<McpResourceServerCacheKey>,
|
||||
delay: Duration,
|
||||
retry_at: Instant,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CatalogRefreshBackoff {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("CatalogRefreshBackoff")
|
||||
.field("delay", &self.delay)
|
||||
.field("retry_at", &self.retry_at)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl CatalogRefreshBackoff {
|
||||
pub fn is_pending(
|
||||
&self,
|
||||
auth: Option<&McpResourceClientAuthKey>,
|
||||
resources: Option<&McpResourceServerCacheKey>,
|
||||
) -> bool {
|
||||
self.auth.as_ref() == auth
|
||||
&& self.resources.as_ref() == resources
|
||||
&& Instant::now() < self.retry_at
|
||||
}
|
||||
|
||||
pub fn after_failure(
|
||||
auth: Option<McpResourceClientAuthKey>,
|
||||
resources: Option<McpResourceServerCacheKey>,
|
||||
previous: Option<&Self>,
|
||||
) -> Self {
|
||||
let delay = previous
|
||||
.filter(|previous| previous.auth == auth && previous.resources == resources)
|
||||
.map_or(Duration::from_secs(30), |previous| {
|
||||
(previous.delay * 2).min(Duration::from_secs(300))
|
||||
});
|
||||
Self {
|
||||
auth,
|
||||
resources,
|
||||
delay,
|
||||
retry_at: Instant::now() + delay,
|
||||
}
|
||||
}
|
||||
}
|
||||
512
codex-rs/ext/extension-api/src/contributors.rs
Normal file
512
codex-rs/ext/extension-api/src/contributors.rs
Normal file
@@ -0,0 +1,512 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_config::types::PluginsConfigToml;
|
||||
use codex_context_fragments::ContextualUserFragment;
|
||||
use codex_exec_server_protocol::ExecutorCapabilityDiscoverySnapshot;
|
||||
use codex_exec_server_protocol::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::protocol::TokenUsageInfo;
|
||||
use codex_tools::ToolCall;
|
||||
use codex_tools::ToolExecutor;
|
||||
|
||||
use crate::ExtensionData;
|
||||
use crate::ExtensionMetrics;
|
||||
|
||||
mod approval_review;
|
||||
mod context;
|
||||
mod mcp;
|
||||
mod prompt;
|
||||
mod skill_invocation;
|
||||
mod thread_lifecycle;
|
||||
mod tool_lifecycle;
|
||||
mod turn_input;
|
||||
mod turn_lifecycle;
|
||||
mod world_state;
|
||||
|
||||
pub use approval_review::ApprovalDecision;
|
||||
pub use approval_review::ApprovalDecisionInput;
|
||||
pub use approval_review::GuardianV2Enabled;
|
||||
pub use approval_review::SynchronousApprovalReviewer;
|
||||
pub use context::TurnContextContributionInput;
|
||||
pub use mcp::McpServerContribution;
|
||||
pub use mcp::McpServerContributionContext;
|
||||
pub use mcp::SelectedPlugin;
|
||||
pub use mcp::SelectedPluginContribution;
|
||||
pub use mcp::SelectedPluginIdentity;
|
||||
pub use mcp::SelectedPluginSnapshot;
|
||||
pub use prompt::PromptFragment;
|
||||
pub use prompt::PromptSlot;
|
||||
pub use skill_invocation::SkillInvocationInput;
|
||||
pub use skill_invocation::SkillInvocationKind;
|
||||
pub use thread_lifecycle::ThreadIdleCause;
|
||||
pub use thread_lifecycle::ThreadIdleInput;
|
||||
pub use thread_lifecycle::ThreadOriginator;
|
||||
pub use thread_lifecycle::ThreadReadyInput;
|
||||
pub use thread_lifecycle::ThreadResumeInput;
|
||||
pub use thread_lifecycle::ThreadStartInput;
|
||||
pub use thread_lifecycle::ThreadStopInput;
|
||||
pub use tool_lifecycle::CodeModeCellTiming;
|
||||
pub use tool_lifecycle::CommandStartInput;
|
||||
pub use tool_lifecycle::McpToolContext;
|
||||
pub use tool_lifecycle::McpToolResultInput;
|
||||
pub use tool_lifecycle::McpToolSource;
|
||||
pub use tool_lifecycle::ToolCallOutcome;
|
||||
pub use tool_lifecycle::ToolFinishInput;
|
||||
pub use tool_lifecycle::ToolLifecycleFuture;
|
||||
pub use tool_lifecycle::ToolStartInput;
|
||||
pub use tool_lifecycle::ToolTimingBoundary;
|
||||
pub use tool_lifecycle::ToolTimingInput;
|
||||
pub use turn_input::TurnInputContext;
|
||||
pub use turn_input::TurnInputEnvironment;
|
||||
pub use turn_lifecycle::CatalogRefreshInput;
|
||||
pub use turn_lifecycle::TurnAbortInput;
|
||||
pub use turn_lifecycle::TurnErrorInput;
|
||||
pub use turn_lifecycle::TurnStartInput;
|
||||
pub use turn_lifecycle::TurnStartPhase;
|
||||
pub use turn_lifecycle::TurnStopInput;
|
||||
pub use world_state::PreviousWorldStateSection;
|
||||
pub use world_state::RenderedWorldStateFragment;
|
||||
pub use world_state::WorldStateContributionInput;
|
||||
pub use world_state::WorldStateSectionContribution;
|
||||
|
||||
/// Boxed, sendable future returned by asynchronous extension contributors.
|
||||
pub type ExtensionFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
||||
/// Extension contribution that resolves runtime MCP servers from host config.
|
||||
///
|
||||
/// Contributors run in registration order. Later ordinary server contributions for the same
|
||||
/// name replace earlier ones. Implementations must contribute only names they
|
||||
/// own and must apply any source-specific policy before returning a server.
|
||||
/// Thread-scoped resolution exposes the host-seeded thread inputs; global
|
||||
/// resolution exposes none and must not imply a local fallback. Thread inputs
|
||||
/// 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.
|
||||
pub trait McpServerContributor<C: Sync>: Send + Sync {
|
||||
/// Stable identity used for registration provenance and conflict diagnostics.
|
||||
fn id(&self) -> &'static str;
|
||||
|
||||
fn contribute<'a>(
|
||||
&'a self,
|
||||
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
|
||||
/// 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
|
||||
/// admission and deferred projection; a step's policy may be newer than its other config.
|
||||
fn selected_plugins<'a>(
|
||||
&'a self,
|
||||
_context: McpServerContributionContext<'a, C>,
|
||||
_plugins_config: &'a PluginsConfigToml,
|
||||
) -> ExtensionFuture<'a, Vec<SelectedPlugin<'a>>> {
|
||||
Box::pin(async { Vec::new() })
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension contribution that adds prompt fragments during prompt assembly.
|
||||
///
|
||||
/// Implementations should use the method matching the scope needed by the
|
||||
/// fragment: thread/session context for stable inputs, and turn context for
|
||||
/// fragments that depend on turn-local host state.
|
||||
pub trait ContextContributor: Send + Sync {
|
||||
/// Returns thread-scoped context using the supplied extension state.
|
||||
fn contribute_thread_context<'a>(
|
||||
&'a self,
|
||||
session_store: &'a ExtensionData,
|
||||
thread_store: &'a ExtensionData,
|
||||
) -> ExtensionFuture<'a, Vec<PromptFragment>> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _session_store = session_store;
|
||||
let _thread_store = thread_store;
|
||||
Vec::new()
|
||||
})
|
||||
}
|
||||
|
||||
fn contribute_turn_context<'a>(
|
||||
&'a self,
|
||||
input: TurnContextContributionInput<'a>,
|
||||
) -> ExtensionFuture<'a, Vec<PromptFragment>> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
Vec::new()
|
||||
})
|
||||
}
|
||||
|
||||
fn contribute_world_state<'a>(
|
||||
&'a self,
|
||||
input: WorldStateContributionInput<'a>,
|
||||
) -> ExtensionFuture<'a, Vec<WorldStateSectionContribution>> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
Vec::new()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Contributor for host-owned thread lifecycle gates.
|
||||
///
|
||||
/// Implementations should use these callbacks to seed, rehydrate, or flush
|
||||
/// extension-private thread state and retain any session capabilities supplied
|
||||
/// by the host. Other heavy dependencies belong on the extension value.
|
||||
pub trait ThreadLifecycleContributor<C: Sync>: Send + Sync {
|
||||
/// Called after host startup has initialized the thread-scoped store.
|
||||
fn on_thread_start<'a>(&'a self, input: ThreadStartInput<'a, C>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
})
|
||||
}
|
||||
|
||||
/// Called after the initialized thread is registered with its host.
|
||||
fn on_thread_ready<'a>(&'a self, input: ThreadReadyInput<'a, C>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
})
|
||||
}
|
||||
|
||||
/// Called after the host constructs a runtime from persisted history.
|
||||
fn on_thread_resume<'a>(&'a self, input: ThreadResumeInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
})
|
||||
}
|
||||
|
||||
/// Called after the host has drained immediately pending thread work.
|
||||
///
|
||||
/// Implementations may use host capabilities captured by the extension to
|
||||
/// submit follow-up input. The host remains responsible for deciding
|
||||
/// whether that input starts a turn, is queued, or is ignored.
|
||||
fn on_thread_idle<'a>(&'a self, input: ThreadIdleInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
})
|
||||
}
|
||||
|
||||
/// Called during runtime teardown, before the host closes persistent history.
|
||||
/// Contributors must cancel and join their background work before returning.
|
||||
fn on_thread_stop<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Contributor for host-owned turn lifecycle gates.
|
||||
///
|
||||
/// Implementations should use these callbacks to seed, observe, or clear
|
||||
/// extension-private turn state. The host exposes stable identifiers and
|
||||
/// extension stores instead of core runtime objects.
|
||||
pub trait TurnLifecycleContributor: Send + Sync {
|
||||
/// Selects the start phase using the current thread policy. Disabled callbacks
|
||||
/// may retain the default phase and return without doing any work.
|
||||
fn turn_start_phase(&self, _thread_store: &ExtensionData) -> TurnStartPhase {
|
||||
TurnStartPhase::BeforeTaskRegistration
|
||||
}
|
||||
|
||||
/// Whether regular-task startup must reconcile MCP before this callback runs.
|
||||
/// Ignored before task registration; contributors unrelated to MCP keep the default.
|
||||
fn requires_mcp_runtime(&self, _thread_store: &ExtensionData) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Called once in the selected phase, before task-specific work begins.
|
||||
/// Regular-task preparation may be cancelled before this callback completes;
|
||||
/// stop and abort callbacks must tolerate missing or partial initialization.
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
})
|
||||
}
|
||||
|
||||
/// Refreshes catalogs before a step; returns true when MCP needs rebuilding.
|
||||
fn refresh_catalog_for_step<'a>(
|
||||
&'a self,
|
||||
_input: CatalogRefreshInput<'a>,
|
||||
) -> ExtensionFuture<'a, bool> {
|
||||
Box::pin(async { false })
|
||||
}
|
||||
|
||||
/// Observes a completed item without changing it or delaying streamed deltas.
|
||||
fn on_item_completed<'a>(
|
||||
&'a self,
|
||||
_thread_store: &'a ExtensionData,
|
||||
_turn_store: &'a ExtensionData,
|
||||
_item: &'a TurnItem,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(std::future::ready(()))
|
||||
}
|
||||
|
||||
/// Observes the same completion with host-supplied data for a recorded user input.
|
||||
/// The default forwards to [`Self::on_item_completed`].
|
||||
fn on_item_completed_with_metadata<'a>(
|
||||
&'a self,
|
||||
thread_store: &'a ExtensionData,
|
||||
turn_store: &'a ExtensionData,
|
||||
item: &'a TurnItem,
|
||||
_user_input_extension_data: Option<&'a BTreeMap<String, serde_json::Value>>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
self.on_item_completed(thread_store, turn_store, item)
|
||||
}
|
||||
|
||||
/// Called before the host drops the completed turn runtime and turn store.
|
||||
/// The callback completes before the host emits the turn-complete event.
|
||||
fn on_turn_stop<'a>(&'a self, input: TurnStopInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
})
|
||||
}
|
||||
|
||||
/// Called after the host aborts a running turn.
|
||||
/// The callback completes before the host emits the turn-aborted event, if any.
|
||||
fn on_turn_abort<'a>(&'a self, input: TurnAbortInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
})
|
||||
}
|
||||
|
||||
/// Called when the host observes an error for a running turn.
|
||||
fn on_turn_error<'a>(&'a self, input: TurnErrorInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension contribution that can add turn-local model input.
|
||||
///
|
||||
/// Implementations should resolve only the model-visible input they own and
|
||||
/// must preserve authority boundaries for external resources. Expensive or
|
||||
/// host-specific dependencies belong on the extension value installed by the
|
||||
/// host, not in this input.
|
||||
pub trait TurnInputContributor: Send + Sync {
|
||||
/// Returns additional contextual fragments for one submitted turn. The optional metrics
|
||||
/// capability is bound to the effective model for that turn.
|
||||
fn contribute<'a>(
|
||||
&'a self,
|
||||
input: TurnInputContext<'a>,
|
||||
extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
|
||||
session_store: &'a ExtensionData,
|
||||
thread_store: &'a ExtensionData,
|
||||
turn_store: &'a ExtensionData,
|
||||
) -> ExtensionFuture<'a, Vec<Box<dyn ContextualUserFragment + Send>>>;
|
||||
}
|
||||
|
||||
/// Contributor for host-owned configuration changes.
|
||||
///
|
||||
/// Implementations should treat the supplied values as immutable before/after
|
||||
/// snapshots of the effective thread configuration.
|
||||
pub trait ConfigContributor<C>: Send + Sync {
|
||||
/// Called after the host commits a changed thread configuration.
|
||||
fn on_config_changed(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
_thread_store: &ExtensionData,
|
||||
_previous_config: &C,
|
||||
_new_config: &C,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Contributor for token usage checkpoints reported by the model provider.
|
||||
///
|
||||
/// Implementations should keep this callback cheap. The host calls it after
|
||||
/// updating cached token usage and before emitting the corresponding client
|
||||
/// token-count notification.
|
||||
pub trait TokenUsageContributor: Send + Sync {
|
||||
/// Called each time the host records token usage from a model response.
|
||||
fn on_token_usage<'a>(
|
||||
&'a self,
|
||||
_session_store: &'a ExtensionData,
|
||||
_thread_store: &'a ExtensionData,
|
||||
_turn_store: &'a ExtensionData,
|
||||
_token_usage: &'a TokenUsageInfo,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _inputs = (_session_store, _thread_store, _turn_store, _token_usage);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Contributor for skill invocations observed by the host or an owning extension.
|
||||
///
|
||||
/// Implementations should treat the skill resource as an opaque identity and keep this callback
|
||||
/// cheap because it runs inline with skill loading or command dispatch.
|
||||
pub trait SkillInvocationContributor: Send + Sync {
|
||||
/// Whether this contributor needs a snapshot of host-owned skills.
|
||||
///
|
||||
/// The default preserves legacy discovery for contributors that do not explicitly opt out.
|
||||
fn requires_host_skill_discovery(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Called after one explicit skill load or deduplicated implicit skill invocation is observed.
|
||||
fn on_skill_invocation<'a>(
|
||||
&'a self,
|
||||
_input: SkillInvocationInput<'a>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = _input;
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected capability root bound to filesystem access for the current callback.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct AccessedSelectedCapabilityRoot<'a> {
|
||||
pub root: &'a SelectedCapabilityRoot,
|
||||
pub fs: &'a dyn codex_file_system::EnvironmentAccess,
|
||||
}
|
||||
|
||||
/// Runtime inputs shared by preparation, tool construction, and later context consumers.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct StepPreparationInput<'a> {
|
||||
pub turn_id: &'a str,
|
||||
pub ready_selected_capability_roots: &'a [AccessedSelectedCapabilityRoot<'a>],
|
||||
pub executor_capability_discovery: Option<&'a ExecutorCapabilityDiscoverySnapshot>,
|
||||
pub executor_capability_discovery_v2: Option<&'a [ExecutorCapabilityDiscoveryV2Snapshot]>,
|
||||
/// Captured plugin policy; an empty snapshot represents no selected plugins.
|
||||
pub selected_plugins: &'a SelectedPluginSnapshot,
|
||||
pub session_store: &'a ExtensionData,
|
||||
pub thread_store: &'a ExtensionData,
|
||||
pub turn_store: &'a ExtensionData,
|
||||
/// Contains captured environment handles and permissions.
|
||||
pub step_store: &'a ExtensionData,
|
||||
}
|
||||
|
||||
/// Extension contribution that exposes native tools owned by a feature.
|
||||
pub trait ToolContributor: Send + Sync {
|
||||
/// Prepares step state once, before tools are built and without rendering.
|
||||
/// Never publish partial state; discovery failures may report warnings.
|
||||
fn prepare_for_step<'a>(&'a self, _input: StepPreparationInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async {})
|
||||
}
|
||||
|
||||
/// Returns native tools bound to the supplied extension state.
|
||||
/// Step-only contributors can leave this empty default unchanged.
|
||||
fn tools(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
_thread_store: &ExtensionData,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Returns native tools bound to one sampling step.
|
||||
fn tools_for_step(
|
||||
&self,
|
||||
session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
_step_store: &ExtensionData,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
self.tools(session_store, thread_store)
|
||||
}
|
||||
}
|
||||
|
||||
/// Contributor for host-owned tool lifecycle gates.
|
||||
///
|
||||
/// Implementations can observe tool execution and process MCP responses without
|
||||
/// rewriting the invocation. Use `ToolContributor` for owning a tool implementation
|
||||
/// and hooks for policy that changes tool payloads.
|
||||
pub trait ToolLifecycleContributor: Send + Sync {
|
||||
/// Observe direct calls before readiness, dispatch waiting, and hooks, including blocked calls.
|
||||
/// Excludes nested code-mode calls. Observers must return promptly.
|
||||
fn on_tool_dispatch(&self, _input: ToolDispatchInput<'_>) {}
|
||||
|
||||
/// Called after pre-tool hooks finalize an invocation and before execution.
|
||||
///
|
||||
/// Calls blocked by hooks, or whose hook-provided input cannot be applied,
|
||||
/// do not reach this callback.
|
||||
fn on_tool_start<'a>(&'a self, _input: ToolStartInput<'a>) -> ToolLifecycleFuture<'a> {
|
||||
Box::pin(std::future::ready(()))
|
||||
}
|
||||
|
||||
/// Called for a resolved builtin command before attribution and execution.
|
||||
///
|
||||
/// This includes commands issued by code mode. It does not imply that
|
||||
/// subsequent approval or process creation will succeed.
|
||||
fn on_command_start<'a>(&'a self, _input: CommandStartInput<'a>) -> ToolLifecycleFuture<'a> {
|
||||
Box::pin(std::future::ready(()))
|
||||
}
|
||||
|
||||
/// Runs before the MCP result is sent to the client and model.
|
||||
fn on_mcp_tool_result<'a>(&'a self, _input: McpToolResultInput<'a>) -> ToolLifecycleFuture<'a> {
|
||||
Box::pin(std::future::ready(()))
|
||||
}
|
||||
|
||||
/// Called after the tool call returns, is blocked, fails, or is cancelled.
|
||||
///
|
||||
/// A matching start callback does not exist when execution is blocked,
|
||||
/// hook-provided input cannot be applied, or cancellation wins first.
|
||||
fn on_tool_finish<'a>(&'a self, _input: ToolFinishInput<'a>) -> ToolLifecycleFuture<'a> {
|
||||
Box::pin(std::future::ready(()))
|
||||
}
|
||||
|
||||
/// Observe handler or remote host duration as defined by `ToolTimingBoundary`.
|
||||
/// Handler timing includes cancellation. Observers must return promptly.
|
||||
fn on_tool_timing(&self, _input: ToolTimingInput<'_>) {}
|
||||
|
||||
/// Observe the exec that yielded a cell and the wait that collected its terminal result
|
||||
/// or found the cell unavailable.
|
||||
/// `call_id` identifies that dispatch. `cell_id` stays the same across waits.
|
||||
fn on_code_mode_cell_timing(
|
||||
&self,
|
||||
_thread_id: &str,
|
||||
_call_id: &str,
|
||||
_cell_id: &str,
|
||||
_timing: CodeModeCellTiming,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the complete approval decision, including whether to consult a reviewer.
|
||||
/// Returning `None` leaves the request to the next contributor.
|
||||
pub trait ApprovalReviewContributor: Send + Sync {
|
||||
/// Claims one request, including a handoff to the user.
|
||||
fn decide<'a>(
|
||||
&'a self,
|
||||
_input: &'a ApprovalDecisionInput<'_>,
|
||||
) -> ExtensionFuture<'a, Option<ApprovalDecision>> {
|
||||
Box::pin(std::future::ready(None))
|
||||
}
|
||||
}
|
||||
|
||||
/// Ordered post-processing contribution for one parsed turn item.
|
||||
///
|
||||
/// Implementations may mutate the item before it is emitted and may use the
|
||||
/// explicitly exposed thread- and turn-lifetime stores when they need durable
|
||||
/// extension-private state.
|
||||
pub trait TurnItemContributor: Send + Sync {
|
||||
fn contribute<'a>(
|
||||
&'a self,
|
||||
thread_store: &'a ExtensionData,
|
||||
turn_store: &'a ExtensionData,
|
||||
item: &'a mut TurnItem,
|
||||
) -> ExtensionFuture<'a, Result<(), String>>;
|
||||
}
|
||||
|
||||
pub use tool_lifecycle::ToolDispatchInput;
|
||||
@@ -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,
|
||||
}
|
||||
20
codex-rs/ext/extension-api/src/contributors/context.rs
Normal file
20
codex-rs/ext/extension-api/src/contributors/context.rs
Normal 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>,
|
||||
}
|
||||
237
codex-rs/ext/extension-api/src/contributors/mcp.rs
Normal file
237
codex-rs/ext/extension-api/src/contributors/mcp.rs
Normal 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 },
|
||||
}
|
||||
94
codex-rs/ext/extension-api/src/contributors/prompt.rs
Normal file
94
codex-rs/ext/extension-api/src/contributors/prompt.rs
Normal 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)
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
272
codex-rs/ext/extension-api/src/contributors/tool_lifecycle.rs
Normal file
272
codex-rs/ext/extension-api/src/contributors/tool_lifecycle.rs
Normal 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,
|
||||
}
|
||||
50
codex-rs/ext/extension-api/src/contributors/turn_input.rs
Normal file
50
codex-rs/ext/extension-api/src/contributors/turn_input.rs
Normal 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()
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
200
codex-rs/ext/extension-api/src/contributors/world_state.rs
Normal file
200
codex-rs/ext/extension-api/src/contributors/world_state.rs
Normal 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))
|
||||
}
|
||||
}
|
||||
137
codex-rs/ext/extension-api/src/lib.rs
Normal file
137
codex-rs/ext/extension-api/src/lib.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
mod capabilities;
|
||||
mod catalog_refresh;
|
||||
mod contributors;
|
||||
mod message_lifecycle;
|
||||
mod registry;
|
||||
mod session_isolation;
|
||||
mod state;
|
||||
mod tool_policy;
|
||||
mod turn_admission;
|
||||
mod user_instructions;
|
||||
|
||||
pub use message_lifecycle::MessageLifecycleContributor;
|
||||
pub use message_lifecycle::MessageLifecycleInput;
|
||||
pub use session_isolation::IsolatedSessionExtensions;
|
||||
pub use session_isolation::SessionIsolation;
|
||||
pub use tool_policy::ToolPolicy;
|
||||
|
||||
pub use capabilities::ConversationHistorySnapshot;
|
||||
pub use capabilities::ExtensionEventSink;
|
||||
pub use capabilities::ExtensionMetrics;
|
||||
pub use capabilities::ExtensionWarning;
|
||||
pub use capabilities::NoopExtensionEventSink;
|
||||
pub use capabilities::NoopResponseItemInjector;
|
||||
pub use capabilities::ResponseItemInjectionFuture;
|
||||
pub use capabilities::ResponseItemInjector;
|
||||
pub use capabilities::record_catalog_entries;
|
||||
pub use catalog_refresh::CatalogRefreshBackoff;
|
||||
pub use codex_context_fragments::ContextualUserFragment;
|
||||
pub use codex_mcp::McpProtocolMode;
|
||||
pub use codex_mcp::ToolInfo as McpToolInfo;
|
||||
pub use codex_protocol::models::ContentItem;
|
||||
pub use codex_protocol::models::ContentItemKind;
|
||||
pub use codex_protocol::models::ResponseItem;
|
||||
pub use codex_protocol::models::input_text;
|
||||
pub use codex_protocol::security_risk::SecurityRiskScore;
|
||||
pub use codex_tools::ConversationHistory;
|
||||
pub use codex_tools::ExtensionTurnItem;
|
||||
pub use codex_tools::FunctionCallError;
|
||||
pub use codex_tools::JsonToolOutput;
|
||||
pub use codex_tools::NoopTurnItemEmitter;
|
||||
pub use codex_tools::ResponsesApiTool;
|
||||
pub use codex_tools::ToolCall;
|
||||
pub use codex_tools::ToolCallSource;
|
||||
pub use codex_tools::ToolEnvironment;
|
||||
pub use codex_tools::ToolExecutor;
|
||||
pub use codex_tools::ToolExecutorFuture;
|
||||
pub use codex_tools::ToolName;
|
||||
pub use codex_tools::ToolOutput;
|
||||
pub use codex_tools::ToolPayload;
|
||||
pub use codex_tools::ToolSpec;
|
||||
pub use codex_tools::TurnItemEmissionFuture;
|
||||
pub use codex_tools::TurnItemEmitter;
|
||||
pub use codex_tools::parse_tool_input_schema;
|
||||
pub use codex_tools::parse_tool_input_schema_without_compaction;
|
||||
pub use contributors::AccessedSelectedCapabilityRoot;
|
||||
pub use contributors::ApprovalDecision;
|
||||
pub use contributors::ApprovalDecisionInput;
|
||||
pub use contributors::ApprovalReviewContributor;
|
||||
pub use contributors::CatalogRefreshInput;
|
||||
pub use contributors::CodeModeCellTiming;
|
||||
pub use contributors::CommandStartInput;
|
||||
pub use contributors::ConfigContributor;
|
||||
pub use contributors::ContextContributor;
|
||||
pub use contributors::ExtensionFuture;
|
||||
pub use contributors::GuardianV2Enabled;
|
||||
pub use contributors::McpServerContribution;
|
||||
pub use contributors::McpServerContributionContext;
|
||||
pub use contributors::McpServerContributor;
|
||||
pub use contributors::McpToolContext;
|
||||
pub use contributors::McpToolResultInput;
|
||||
pub use contributors::McpToolSource;
|
||||
pub use contributors::PreviousWorldStateSection;
|
||||
pub use contributors::PromptFragment;
|
||||
pub use contributors::PromptSlot;
|
||||
pub use contributors::RenderedWorldStateFragment;
|
||||
pub use contributors::SelectedPlugin;
|
||||
pub use contributors::SelectedPluginContribution;
|
||||
pub use contributors::SelectedPluginIdentity;
|
||||
pub use contributors::SelectedPluginSnapshot;
|
||||
pub use contributors::SkillInvocationContributor;
|
||||
pub use contributors::SkillInvocationInput;
|
||||
pub use contributors::SkillInvocationKind;
|
||||
pub use contributors::StepPreparationInput;
|
||||
pub use contributors::SynchronousApprovalReviewer;
|
||||
pub use contributors::ThreadIdleCause;
|
||||
pub use contributors::ThreadIdleInput;
|
||||
pub use contributors::ThreadLifecycleContributor;
|
||||
pub use contributors::ThreadOriginator;
|
||||
pub use contributors::ThreadReadyInput;
|
||||
pub use contributors::ThreadResumeInput;
|
||||
pub use contributors::ThreadStartInput;
|
||||
pub use contributors::ThreadStopInput;
|
||||
pub use contributors::TokenUsageContributor;
|
||||
pub use contributors::ToolCallOutcome;
|
||||
pub use contributors::ToolContributor;
|
||||
pub use contributors::ToolFinishInput;
|
||||
pub use contributors::ToolLifecycleContributor;
|
||||
pub use contributors::ToolLifecycleFuture;
|
||||
pub use contributors::ToolStartInput;
|
||||
pub use contributors::ToolTimingBoundary;
|
||||
pub use contributors::ToolTimingInput;
|
||||
pub use contributors::TurnAbortInput;
|
||||
pub use contributors::TurnContextContributionInput;
|
||||
pub use contributors::TurnErrorInput;
|
||||
pub use contributors::TurnInputContext;
|
||||
pub use contributors::TurnInputContributor;
|
||||
pub use contributors::TurnInputEnvironment;
|
||||
pub use contributors::TurnItemContributor;
|
||||
pub use contributors::TurnLifecycleContributor;
|
||||
pub use contributors::TurnStartInput;
|
||||
pub use contributors::TurnStartPhase;
|
||||
pub use contributors::TurnStopInput;
|
||||
pub use contributors::WorldStateContributionInput;
|
||||
pub use contributors::WorldStateSectionContribution;
|
||||
pub use registry::ExtensionRegistry;
|
||||
pub use registry::ExtensionRegistryBuilder;
|
||||
pub use registry::empty_extension_registry;
|
||||
pub use state::ExtensionData;
|
||||
pub use state::ExtensionDataInit;
|
||||
pub use turn_admission::TurnStartAdmission;
|
||||
pub use user_instructions::Instructions;
|
||||
pub use user_instructions::LoadInstructionsFuture;
|
||||
pub use user_instructions::LoadedUserInstructions;
|
||||
pub use user_instructions::ThreadInstructionsProvider;
|
||||
pub use user_instructions::UserInstructionsProvider;
|
||||
|
||||
pub use contributors::ToolDispatchInput;
|
||||
|
||||
mod model_request;
|
||||
pub use model_request::GuardianAssessment;
|
||||
pub use model_request::ModelRequestContributor;
|
||||
pub use model_request::ModelRequestInput;
|
||||
pub use model_request::ModelRequestKind;
|
||||
pub use model_request::ModelResponseError;
|
||||
pub use model_request::ModelResponseInterceptor;
|
||||
pub use model_request::ModelResponseStream;
|
||||
pub use model_request::ResponseEvent;
|
||||
22
codex-rs/ext/extension-api/src/message_lifecycle.rs
Normal file
22
codex-rs/ext/extension-api/src/message_lifecycle.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
//! Capture publication state once; consume it independently for each delivery.
|
||||
|
||||
use crate::ExtensionData;
|
||||
use codex_protocol::ThreadId;
|
||||
|
||||
/// State shared by all deliveries of a publication, including recipients resolved later.
|
||||
/// The model-visible item ID may still be unknown until the recipient records the message.
|
||||
pub struct MessageLifecycleInput {
|
||||
pub sender: ThreadId,
|
||||
/// Capture contributor-specific state at publication; read it at consumption.
|
||||
pub data: ExtensionData,
|
||||
}
|
||||
|
||||
/// Observes messages from local agent control and the initial task of a host-spawned child.
|
||||
/// Callbacks are synchronous and must not block. Replaying history or submitting raw
|
||||
/// protocol input does not create a publication.
|
||||
pub trait MessageLifecycleContributor: Send + Sync {
|
||||
/// Called once before the message is exposed to any recipient.
|
||||
fn on_publish(&self, _input: &MessageLifecycleInput) {}
|
||||
/// Called at most once per logical delivery, at history commitment before sampling.
|
||||
fn on_consumed(&self, _input: &MessageLifecycleInput, _recipient: ThreadId) {}
|
||||
}
|
||||
53
codex-rs/ext/extension-api/src/model_request.rs
Normal file
53
codex-rs/ext/extension-api/src/model_request.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
//! Request-scoped interception of model response streams.
|
||||
use crate::ExtensionFuture;
|
||||
pub use codex_api::ApiError as ModelResponseError;
|
||||
pub use codex_api::GuardianAssessment;
|
||||
pub use codex_api::ResponseEvent;
|
||||
use futures::stream::BoxStream;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Model response events owned by an interceptor or its downstream consumer.
|
||||
pub type ModelResponseStream = BoxStream<'static, Result<ResponseEvent, ModelResponseError>>;
|
||||
|
||||
/// Whether a request generates output or only prepares a session.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ModelRequestKind {
|
||||
/// Generate model output.
|
||||
Generation,
|
||||
/// Prepare the session without generating output.
|
||||
Warmup,
|
||||
}
|
||||
|
||||
/// Request identity and additional metadata supplied before sending to the provider.
|
||||
pub struct ModelRequestInput<'a> {
|
||||
/// Whether this request generates output or warms up the session.
|
||||
pub kind: ModelRequestKind,
|
||||
/// Thread making the request.
|
||||
pub thread_id: &'a str,
|
||||
/// Additional provider metadata for request tracking; existing and reserved keys cannot be replaced.
|
||||
pub client_metadata: &'a mut Option<HashMap<String, String>>,
|
||||
/// Requested model identifier.
|
||||
pub model: &'a str,
|
||||
}
|
||||
|
||||
/// Checks model requests and creates request-scoped response interceptors.
|
||||
pub trait ModelRequestContributor: Send + Sync + std::fmt::Debug {
|
||||
/// Core awaits this check before submitting generation to the transport.
|
||||
/// Return true to fail with `SessionBudgetExceeded`. Requests already handed to the
|
||||
/// transport can still complete or retry. WebSocket warmup skips this check.
|
||||
fn budget_exhausted<'a>(&'a self, _thread_id: &'a str) -> ExtensionFuture<'a, bool> {
|
||||
Box::pin(async { false })
|
||||
}
|
||||
|
||||
/// Return None for requests this contributor does not intercept.
|
||||
fn request(&self, input: ModelRequestInput<'_>) -> Option<Box<dyn ModelResponseInterceptor>>;
|
||||
}
|
||||
|
||||
/// Owns request state until consumed by the response stream or dropped on failure.
|
||||
/// Interceptors compose in registration order; dropping their stream must release unfinished work.
|
||||
/// Trusted host implementations must bound any model-visible content they synthesize.
|
||||
pub trait ModelResponseInterceptor: Send + Sync {
|
||||
/// Wrap the response stream, optionally buffering, inspecting, or transforming events.
|
||||
/// The returned stream must own request state and propagate cancellation by dropping upstream.
|
||||
fn intercept(self: Box<Self>, stream: ModelResponseStream) -> ModelResponseStream;
|
||||
}
|
||||
312
codex-rs/ext/extension-api/src/registry.rs
Normal file
312
codex-rs/ext/extension-api/src/registry.rs
Normal file
@@ -0,0 +1,312 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::ApprovalReviewContributor;
|
||||
use crate::ConfigContributor;
|
||||
use crate::ContextContributor;
|
||||
use crate::ExtensionEventSink;
|
||||
use crate::McpServerContributor;
|
||||
use crate::MessageLifecycleContributor;
|
||||
use crate::ModelRequestContributor;
|
||||
use crate::NoopExtensionEventSink;
|
||||
use crate::SkillInvocationContributor;
|
||||
use crate::ThreadLifecycleContributor;
|
||||
use crate::TokenUsageContributor;
|
||||
use crate::ToolContributor;
|
||||
use crate::ToolLifecycleContributor;
|
||||
use crate::TurnInputContributor;
|
||||
use crate::TurnItemContributor;
|
||||
use crate::TurnLifecycleContributor;
|
||||
use crate::TurnStartAdmission;
|
||||
|
||||
/// Mutable registry used while hosts register typed runtime contributions.
|
||||
pub struct ExtensionRegistryBuilder<C: Sync> {
|
||||
registry: ExtensionRegistry<C>,
|
||||
}
|
||||
|
||||
impl<C: Sync> Default for ExtensionRegistryBuilder<C> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
registry: ExtensionRegistry {
|
||||
event_sink: Arc::new(NoopExtensionEventSink),
|
||||
turn_start_admission: None,
|
||||
thread_lifecycle_contributors: Vec::new(),
|
||||
turn_lifecycle_contributors: Vec::new(),
|
||||
config_contributors: Vec::new(),
|
||||
token_usage_contributors: Vec::new(),
|
||||
skill_invocation_contributors: Vec::new(),
|
||||
approval_review_contributors: Vec::new(),
|
||||
context_contributors: Vec::new(),
|
||||
mcp_server_contributors: Vec::new(),
|
||||
turn_input_contributors: Vec::new(),
|
||||
tool_contributors: Vec::new(),
|
||||
tool_lifecycle_contributors: Vec::new(),
|
||||
model_request_contributors: Vec::new(),
|
||||
message_observers: Vec::new(),
|
||||
turn_item_contributors: Vec::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Sync> ExtensionRegistryBuilder<C> {
|
||||
/// Creates an empty registry builder.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Creates an empty registry builder with a host-provided event sink.
|
||||
pub fn with_event_sink(event_sink: Arc<dyn ExtensionEventSink>) -> Self {
|
||||
let mut builder = Self::default();
|
||||
builder.registry.event_sink = event_sink;
|
||||
builder
|
||||
}
|
||||
|
||||
/// Returns the host event sink to pass into extension constructors.
|
||||
pub fn event_sink(&self) -> Arc<dyn ExtensionEventSink> {
|
||||
Arc::clone(&self.registry.event_sink)
|
||||
}
|
||||
|
||||
/// Installs the host gate for turn-input submissions that start a new turn.
|
||||
pub fn turn_start_admission(&mut self, admission: Arc<dyn TurnStartAdmission>) {
|
||||
self.registry.turn_start_admission = Some(admission);
|
||||
}
|
||||
|
||||
/// Registers one approval-review contributor.
|
||||
pub fn approval_review_contributor(&mut self, contributor: Arc<dyn ApprovalReviewContributor>) {
|
||||
self.registry.approval_review_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one thread-lifecycle contributor.
|
||||
pub fn thread_lifecycle_contributor(
|
||||
&mut self,
|
||||
contributor: Arc<dyn ThreadLifecycleContributor<C>>,
|
||||
) {
|
||||
self.registry
|
||||
.thread_lifecycle_contributors
|
||||
.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one turn-lifecycle contributor.
|
||||
pub fn turn_lifecycle_contributor(&mut self, contributor: Arc<dyn TurnLifecycleContributor>) {
|
||||
self.registry.turn_lifecycle_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one config contributor.
|
||||
pub fn config_contributor(&mut self, contributor: Arc<dyn ConfigContributor<C>>) {
|
||||
self.registry.config_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one token-usage contributor.
|
||||
pub fn token_usage_contributor(&mut self, contributor: Arc<dyn TokenUsageContributor>) {
|
||||
self.registry.token_usage_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one skill-invocation contributor.
|
||||
pub fn skill_invocation_contributor(
|
||||
&mut self,
|
||||
contributor: Arc<dyn SkillInvocationContributor>,
|
||||
) {
|
||||
self.registry
|
||||
.skill_invocation_contributors
|
||||
.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one prompt contributor.
|
||||
pub fn prompt_contributor(&mut self, contributor: Arc<dyn ContextContributor>) {
|
||||
self.registry.context_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one runtime MCP server contributor.
|
||||
pub fn mcp_server_contributor(&mut self, contributor: Arc<dyn McpServerContributor<C>>) {
|
||||
self.registry.mcp_server_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one turn-input contributor.
|
||||
pub fn turn_input_contributor(&mut self, contributor: Arc<dyn TurnInputContributor>) {
|
||||
self.registry.turn_input_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers a contributor for request-scoped response interception.
|
||||
pub fn model_request_contributor(&mut self, contributor: Arc<dyn ModelRequestContributor>) {
|
||||
self.registry.model_request_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one native tool contributor.
|
||||
pub fn tool_contributor(&mut self, contributor: Arc<dyn ToolContributor>) {
|
||||
self.registry.tool_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one tool-lifecycle contributor.
|
||||
pub fn tool_lifecycle_contributor(&mut self, contributor: Arc<dyn ToolLifecycleContributor>) {
|
||||
self.registry.tool_lifecycle_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one ordered turn-item contributor.
|
||||
pub fn turn_item_contributor(&mut self, contributor: Arc<dyn TurnItemContributor>) {
|
||||
self.registry.turn_item_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers a synchronous direct-message observer.
|
||||
pub fn message_lifecycle_contributor(&mut self, hook: Arc<dyn MessageLifecycleContributor>) {
|
||||
self.registry.message_observers.push(hook);
|
||||
}
|
||||
|
||||
/// Finishes construction and returns the immutable registry.
|
||||
pub fn build(self) -> ExtensionRegistry<C> {
|
||||
self.registry
|
||||
}
|
||||
}
|
||||
|
||||
/// Immutable typed registry produced after extensions are installed.
|
||||
pub struct ExtensionRegistry<C: Sync> {
|
||||
event_sink: Arc<dyn ExtensionEventSink>,
|
||||
turn_start_admission: Option<Arc<dyn TurnStartAdmission>>,
|
||||
thread_lifecycle_contributors: Vec<Arc<dyn ThreadLifecycleContributor<C>>>,
|
||||
turn_lifecycle_contributors: Vec<Arc<dyn TurnLifecycleContributor>>,
|
||||
config_contributors: Vec<Arc<dyn ConfigContributor<C>>>,
|
||||
token_usage_contributors: Vec<Arc<dyn TokenUsageContributor>>,
|
||||
skill_invocation_contributors: Vec<Arc<dyn SkillInvocationContributor>>,
|
||||
context_contributors: Vec<Arc<dyn ContextContributor>>,
|
||||
mcp_server_contributors: Vec<Arc<dyn McpServerContributor<C>>>,
|
||||
turn_input_contributors: Vec<Arc<dyn TurnInputContributor>>,
|
||||
tool_contributors: Vec<Arc<dyn ToolContributor>>,
|
||||
tool_lifecycle_contributors: Vec<Arc<dyn ToolLifecycleContributor>>,
|
||||
model_request_contributors: Vec<Arc<dyn ModelRequestContributor>>,
|
||||
message_observers: Vec<Arc<dyn MessageLifecycleContributor>>,
|
||||
turn_item_contributors: Vec<Arc<dyn TurnItemContributor>>,
|
||||
approval_review_contributors: Vec<Arc<dyn ApprovalReviewContributor>>,
|
||||
}
|
||||
|
||||
impl<C: Sync> ExtensionRegistry<C> {
|
||||
/// Copies the registered contributors into a builder for host-specific additions.
|
||||
pub fn to_builder(&self) -> ExtensionRegistryBuilder<C> {
|
||||
ExtensionRegistryBuilder {
|
||||
registry: Self {
|
||||
event_sink: self.event_sink.clone(),
|
||||
turn_start_admission: self.turn_start_admission.clone(),
|
||||
thread_lifecycle_contributors: self.thread_lifecycle_contributors.clone(),
|
||||
turn_lifecycle_contributors: self.turn_lifecycle_contributors.clone(),
|
||||
config_contributors: self.config_contributors.clone(),
|
||||
token_usage_contributors: self.token_usage_contributors.clone(),
|
||||
skill_invocation_contributors: self.skill_invocation_contributors.clone(),
|
||||
context_contributors: self.context_contributors.clone(),
|
||||
mcp_server_contributors: self.mcp_server_contributors.clone(),
|
||||
turn_input_contributors: self.turn_input_contributors.clone(),
|
||||
tool_contributors: self.tool_contributors.clone(),
|
||||
tool_lifecycle_contributors: self.tool_lifecycle_contributors.clone(),
|
||||
model_request_contributors: self.model_request_contributors.clone(),
|
||||
message_observers: self.message_observers.clone(),
|
||||
turn_item_contributors: self.turn_item_contributors.clone(),
|
||||
approval_review_contributors: self.approval_review_contributors.clone(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Acquires the host's turn-start permit, or an empty permit for ungated hosts.
|
||||
/// A missing permit rejects the start before Core consumes pending input.
|
||||
pub fn admit_turn_start(&self) -> Option<Box<dyn Send>> {
|
||||
match &self.turn_start_admission {
|
||||
Some(admission) => admission.admit_turn_start(),
|
||||
None => Some(Box::new(())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the host event sink retained by this registry.
|
||||
pub fn event_sink(&self) -> Arc<dyn ExtensionEventSink> {
|
||||
Arc::clone(&self.event_sink)
|
||||
}
|
||||
|
||||
/// Returns the registered thread-lifecycle contributors.
|
||||
pub fn thread_lifecycle_contributors(&self) -> &[Arc<dyn ThreadLifecycleContributor<C>>] {
|
||||
&self.thread_lifecycle_contributors
|
||||
}
|
||||
|
||||
/// Returns the registered turn-lifecycle contributors.
|
||||
pub fn turn_lifecycle_contributors(&self) -> &[Arc<dyn TurnLifecycleContributor>] {
|
||||
&self.turn_lifecycle_contributors
|
||||
}
|
||||
|
||||
/// Returns the registered config contributors.
|
||||
pub fn config_contributors(&self) -> &[Arc<dyn ConfigContributor<C>>] {
|
||||
&self.config_contributors
|
||||
}
|
||||
|
||||
/// Returns the registered token-usage contributors.
|
||||
pub fn token_usage_contributors(&self) -> &[Arc<dyn TokenUsageContributor>] {
|
||||
&self.token_usage_contributors
|
||||
}
|
||||
|
||||
/// Returns the registered skill-invocation contributors.
|
||||
pub fn skill_invocation_contributors(&self) -> &[Arc<dyn SkillInvocationContributor>] {
|
||||
&self.skill_invocation_contributors
|
||||
}
|
||||
|
||||
/// Whether any installed skill contributor needs a snapshot of host-owned skills.
|
||||
///
|
||||
/// Registries without skill contributors retain legacy host discovery behavior.
|
||||
pub fn requires_host_skill_discovery(&self) -> bool {
|
||||
self.skill_invocation_contributors.is_empty()
|
||||
|| self
|
||||
.skill_invocation_contributors
|
||||
.iter()
|
||||
.any(|contributor| contributor.requires_host_skill_discovery())
|
||||
}
|
||||
|
||||
/// Returns the first claimed decision in registration order.
|
||||
pub async fn decide_approval(
|
||||
&self,
|
||||
input: &crate::ApprovalDecisionInput<'_>,
|
||||
) -> Option<crate::ApprovalDecision> {
|
||||
for contributor in &self.approval_review_contributors {
|
||||
if let Some(decision) = contributor.decide(input).await {
|
||||
return Some(decision);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns the registered prompt contributors.
|
||||
pub fn context_contributors(&self) -> &[Arc<dyn ContextContributor>] {
|
||||
&self.context_contributors
|
||||
}
|
||||
|
||||
/// Returns the registered runtime MCP server contributors.
|
||||
pub fn mcp_server_contributors(&self) -> &[Arc<dyn McpServerContributor<C>>] {
|
||||
&self.mcp_server_contributors
|
||||
}
|
||||
|
||||
/// Returns the registered turn-input contributors.
|
||||
pub fn turn_input_contributors(&self) -> &[Arc<dyn TurnInputContributor>] {
|
||||
&self.turn_input_contributors
|
||||
}
|
||||
|
||||
/// Returns the registered native tool contributors.
|
||||
pub fn tool_contributors(&self) -> &[Arc<dyn ToolContributor>] {
|
||||
&self.tool_contributors
|
||||
}
|
||||
|
||||
/// Returns direct-message observers in registration order.
|
||||
pub fn message_lifecycle_contributors(&self) -> &[Arc<dyn MessageLifecycleContributor>] {
|
||||
&self.message_observers
|
||||
}
|
||||
|
||||
/// Returns response interceptor contributors in registration order.
|
||||
pub fn model_request_contributors(&self) -> &[Arc<dyn ModelRequestContributor>] {
|
||||
&self.model_request_contributors
|
||||
}
|
||||
|
||||
/// Returns the registered tool-lifecycle contributors.
|
||||
pub fn tool_lifecycle_contributors(&self) -> &[Arc<dyn ToolLifecycleContributor>] {
|
||||
&self.tool_lifecycle_contributors
|
||||
}
|
||||
|
||||
/// Returns the registered ordered turn-item contributors.
|
||||
pub fn turn_item_contributors(&self) -> &[Arc<dyn TurnItemContributor>] {
|
||||
&self.turn_item_contributors
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an empty shared registry for hosts that do not register contributions.
|
||||
pub fn empty_extension_registry<C: Sync>() -> Arc<ExtensionRegistry<C>> {
|
||||
Arc::new(ExtensionRegistryBuilder::new().build())
|
||||
}
|
||||
24
codex-rs/ext/extension-api/src/session_isolation.rs
Normal file
24
codex-rs/ext/extension-api/src/session_isolation.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
//! Host-supplied isolation for internal runtimes, independent of their attribution.
|
||||
//! Isolation only removes inherited capabilities; it never grants review authority.
|
||||
//! Isolated sessions may receive a separate registry of explicit extensions.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::ExtensionRegistry;
|
||||
|
||||
/// Runtime policy supplied through `ExtensionDataInit` before session startup.
|
||||
/// The host captures this value once so later extension-state changes cannot alter it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum SessionIsolation {
|
||||
/// Use the host's ordinary instruction providers, extensions and execution rules.
|
||||
#[default]
|
||||
Inherit,
|
||||
/// Start without inherited instruction providers or extensions, retain only managed
|
||||
/// execution rules, and omit implicit Apps and executor-discovered MCP servers. Explicitly supplied
|
||||
/// instructions and permissions remain the responsibility of the internal caller.
|
||||
Isolated,
|
||||
}
|
||||
|
||||
/// Explicit extensions for an isolated session, supplied through `ExtensionDataInit`.
|
||||
/// The host uses only this registry and never combines it with inherited extensions.
|
||||
pub struct IsolatedSessionExtensions<C: Sync>(pub Arc<ExtensionRegistry<C>>);
|
||||
160
codex-rs/ext/extension-api/src/state.rs
Normal file
160
codex-rs/ext/extension-api/src/state.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
use std::any::Any;
|
||||
use std::any::TypeId;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
type ErasedData = Arc<dyn Any + Send + Sync>;
|
||||
|
||||
/// Typed values supplied before an [`ExtensionData`] scope is created.
|
||||
///
|
||||
/// Hosts may retain a clone when later operations must use the same initial
|
||||
/// inputs. Cloning freezes the attachment map and shares each value by `Arc`;
|
||||
/// values with interior mutability remain shared. This type does not install
|
||||
/// extensions or provide persistence.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ExtensionDataInit {
|
||||
entries: HashMap<TypeId, ErasedData>,
|
||||
}
|
||||
|
||||
impl ExtensionDataInit {
|
||||
/// Creates an empty extension data initializer.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Stores `value` as the initial attachment of type `T`.
|
||||
pub fn insert<T>(&mut self, value: T) -> Option<Arc<T>>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
{
|
||||
self.entries
|
||||
.insert(TypeId::of::<T>(), Arc::new(value))
|
||||
.map(downcast_data)
|
||||
}
|
||||
|
||||
/// Consumes a startup-only attachment before creating the live scope.
|
||||
pub fn remove<T: Any + Send + Sync>(&mut self) -> Option<Arc<T>> {
|
||||
self.entries.remove(&TypeId::of::<T>()).map(downcast_data)
|
||||
}
|
||||
|
||||
/// Returns a host-supplied initial attachment without creating a mutable scope.
|
||||
pub fn get<T>(&self) -> Option<Arc<T>>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
{
|
||||
let value = self.entries.get(&TypeId::of::<T>())?.clone();
|
||||
Some(downcast_data(value))
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed extension-owned data attached to one host object.
|
||||
#[derive(Debug)]
|
||||
pub struct ExtensionData {
|
||||
level_id: String,
|
||||
entries: Mutex<HashMap<TypeId, ErasedData>>,
|
||||
}
|
||||
|
||||
impl ExtensionData {
|
||||
/// Creates an empty attachment map for one host-owned scope.
|
||||
pub fn new(level_id: impl Into<String>) -> Self {
|
||||
Self::new_with_init(level_id, ExtensionDataInit::default())
|
||||
}
|
||||
|
||||
/// Creates an attachment map seeded with host-supplied initial data.
|
||||
pub fn new_with_init(level_id: impl Into<String>, init: ExtensionDataInit) -> Self {
|
||||
Self {
|
||||
level_id: level_id.into(),
|
||||
entries: Mutex::new(init.entries),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the host identity for the scope this data is attached to.
|
||||
pub fn level_id(&self) -> &str {
|
||||
&self.level_id
|
||||
}
|
||||
|
||||
/// Returns the attached value of type `T`, if one exists.
|
||||
pub fn get<T>(&self) -> Option<Arc<T>>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
{
|
||||
let value = self.entries().get(&TypeId::of::<T>())?.clone();
|
||||
Some(downcast_data(value))
|
||||
}
|
||||
|
||||
/// Returns the attached value of type `T`, inserting one from `init` when absent.
|
||||
///
|
||||
/// The initializer runs while this map is locked, so it should stay cheap;
|
||||
/// heavyweight lazy work belongs inside the attached value itself.
|
||||
pub fn get_or_init<T>(&self, init: impl FnOnce() -> T) -> Arc<T>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
{
|
||||
let mut entries = self.entries();
|
||||
let value = entries
|
||||
.entry(TypeId::of::<T>())
|
||||
.or_insert_with(|| Arc::new(init()));
|
||||
downcast_data(Arc::clone(value))
|
||||
}
|
||||
|
||||
/// Stores `value` as the attachment of type `T`, returning any previous value.
|
||||
pub fn insert<T>(&self, value: T) -> Option<Arc<T>>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
{
|
||||
self.insert_arc(Arc::new(value))
|
||||
}
|
||||
|
||||
/// Stores a shared attachment without cloning its contents.
|
||||
pub fn insert_arc<T>(&self, value: Arc<T>) -> Option<Arc<T>>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
{
|
||||
self.entries()
|
||||
.insert(TypeId::of::<T>(), value)
|
||||
.map(downcast_data)
|
||||
}
|
||||
|
||||
/// Stores `value` only when `should_insert` accepts the current attachment.
|
||||
///
|
||||
/// The predicate and insertion happen while this map is locked, so concurrent
|
||||
/// callers cannot replace a value after checking a stale attachment.
|
||||
pub fn insert_if<T>(&self, value: T, should_insert: impl FnOnce(Option<&T>) -> bool) -> bool
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
{
|
||||
let mut entries = self.entries();
|
||||
let existing = entries
|
||||
.get(&TypeId::of::<T>())
|
||||
.map(|value| downcast_data::<T>(Arc::clone(value)));
|
||||
if !should_insert(existing.as_deref()) {
|
||||
return false;
|
||||
}
|
||||
entries.insert(TypeId::of::<T>(), Arc::new(value));
|
||||
true
|
||||
}
|
||||
|
||||
/// Removes and returns the attached value of type `T`, if one exists.
|
||||
pub fn remove<T>(&self) -> Option<Arc<T>>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
{
|
||||
self.entries().remove(&TypeId::of::<T>()).map(downcast_data)
|
||||
}
|
||||
|
||||
fn entries(&self) -> std::sync::MutexGuard<'_, HashMap<TypeId, ErasedData>> {
|
||||
self.entries.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
fn downcast_data<T>(value: ErasedData) -> Arc<T>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
{
|
||||
let Ok(value) = value.downcast::<T>() else {
|
||||
unreachable!("typed extension data stored an incompatible value");
|
||||
};
|
||||
value
|
||||
}
|
||||
44
codex-rs/ext/extension-api/src/tool_policy.rs
Normal file
44
codex-rs/ext/extension-api/src/tool_policy.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
//! A startup ceiling on tool selection and construction, independent of session identity.
|
||||
//! This policy only restricts tools; permission and approval checks still apply.
|
||||
|
||||
use crate::ToolName;
|
||||
|
||||
/// Supply through `ExtensionDataInit` before starting a thread. The host captures
|
||||
/// the policy once; later extension-state changes cannot relax it. Callers must
|
||||
/// supply it again when resuming a thread.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ToolPolicy {
|
||||
/// `None` keeps ordinary tool selection; an empty list permits no tools.
|
||||
/// Names include their namespace; plain names use the default namespace.
|
||||
/// Generated tools such as Code Mode's `exec` and `wait` must also be listed.
|
||||
pub allowed_tools: Option<Vec<ToolName>>,
|
||||
/// Omit core tools unless the thread and every ready environment use a managed sandbox.
|
||||
pub require_managed_sandbox: bool,
|
||||
/// Omit shell tools when unified exec is disabled, instead of using one-shot exec.
|
||||
pub require_unified_exec: bool,
|
||||
/// Advertise additional-permission arguments when the feature is enabled.
|
||||
pub expose_additional_permissions: bool,
|
||||
}
|
||||
|
||||
impl Default for ToolPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
allowed_tools: None,
|
||||
require_managed_sandbox: false,
|
||||
require_unified_exec: false,
|
||||
expose_additional_permissions: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolPolicy {
|
||||
pub fn allows(&self, tool: &ToolName) -> bool {
|
||||
self.allowed_tools.as_ref().is_none_or(|tools| {
|
||||
tools.iter().any(|allowed| {
|
||||
allowed.name == tool.name
|
||||
&& (allowed.namespace == tool.namespace
|
||||
|| (allowed.is_default_namespace() && tool.is_default_namespace()))
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
12
codex-rs/ext/extension-api/src/turn_admission.rs
Normal file
12
codex-rs/ext/extension-api/src/turn_admission.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
//! Lets Core turn-input submissions participate in a host's shutdown drain.
|
||||
|
||||
/// A host-provided gate checked before Core starts a turn-input submission.
|
||||
///
|
||||
/// Implementations return a permit for work admitted before shutdown and
|
||||
/// Core retains it through submission. `None` skips the start without consuming
|
||||
/// pending input. Steering an existing turn does not acquire a new permit.
|
||||
/// Memory-only mailbox wakeups and parent-delegated subagent input bypass this
|
||||
/// gate so delegated work can finish before exit. Automatic starts remain gated.
|
||||
pub trait TurnStartAdmission: std::fmt::Debug + Send + Sync {
|
||||
fn admit_turn_start(&self) -> Option<Box<dyn Send>>;
|
||||
}
|
||||
70
codex-rs/ext/extension-api/src/user_instructions.rs
Normal file
70
codex-rs/ext/extension-api/src/user_instructions.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
/// Instructions supplied by the host.
|
||||
///
|
||||
/// Filesystem-backed instructions retain their absolute source path for the
|
||||
/// app-server `instructionSources` API. Other host-provided instructions do
|
||||
/// not report a filesystem source.
|
||||
// TODO(anp): Replace the absolute path with a more general instruction-source
|
||||
// abstraction when non-filesystem providers need first-class attribution.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct Instructions {
|
||||
/// Model-visible instruction text.
|
||||
pub text: String,
|
||||
/// Absolute filesystem path reported through `instructionSources`, if any.
|
||||
pub source: Option<AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
/// Result of loading host-provided user instructions.
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct LoadedUserInstructions {
|
||||
/// Loaded instructions, or `None` when the provider has no applicable text.
|
||||
pub instructions: Option<Instructions>,
|
||||
/// Recoverable loading problems that should be surfaced to the host.
|
||||
/// Providers own suppression of recurring warnings; Core forwards each returned warning.
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Future returned by an instruction provider.
|
||||
pub type LoadInstructionsFuture<'a> =
|
||||
Pin<Box<dyn Future<Output = LoadedUserInstructions> + Send + 'a>>;
|
||||
|
||||
/// Loads host-provided instructions that apply to one root thread.
|
||||
///
|
||||
/// These instructions follow the global [`UserInstructionsProvider`] snapshot
|
||||
/// and precede repository instructions. A result with no instructions or
|
||||
/// blank instructions clears only the thread-scoped contribution. Core retains
|
||||
/// the provider and reads it at startup and when capturing model-request context.
|
||||
/// Implementations own fetching and caching; repeated reads should be cheap and
|
||||
/// return a coherent snapshot. On a recoverable fetch failure, return the last
|
||||
/// usable snapshot with warnings rather than an empty result that clears it.
|
||||
pub trait ThreadInstructionsProvider: Send + Sync {
|
||||
/// Loads the current snapshot for the provider's root thread.
|
||||
fn load_thread_instructions(&self) -> LoadInstructionsFuture<'_>;
|
||||
|
||||
/// Whether descendants should retain this provider instead of only its applied text.
|
||||
/// Defaults to snapshot inheritance. Opt in only when the same instruction scope and
|
||||
/// credentials apply to descendants. Descendants share the installed provider; a root
|
||||
/// resume can replace it for surviving descendants. Providers must coalesce/cache
|
||||
/// concurrent reads and retain a usable snapshot during outages.
|
||||
/// If a resumed root supplies a non-sharing provider, existing descendants keep their
|
||||
/// last shared instructions without receiving any new private updates.
|
||||
/// Updates are loaded at each descendant's next model-request boundary, not mid-request.
|
||||
fn share_with_subagents(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads global user instructions shared across root threads.
|
||||
///
|
||||
/// Core reads this provider at startup and when capturing model-request context.
|
||||
/// Implementations own fetching and caching, so repeated reads should be cheap.
|
||||
/// Implementations should return any recoverable loading problems as warnings
|
||||
/// while still returning usable fallback instructions when available.
|
||||
pub trait UserInstructionsProvider: Send + Sync {
|
||||
/// Loads the current global snapshot for a root runtime.
|
||||
fn load_user_instructions(&self) -> LoadInstructionsFuture<'_>;
|
||||
}
|
||||
Reference in New Issue
Block a user