Merge remote-tracking branch 'origin/main' into etraut/goal-resume-metadata

This commit is contained in:
Eric Traut
2026-05-06 22:20:55 -07:00
89 changed files with 2759 additions and 809 deletions
+2
View File
@@ -880,6 +880,8 @@ fn analytics_hook_event_name(event_name: HookEventName) -> &'static str {
HookEventName::PreToolUse => "PreToolUse",
HookEventName::PermissionRequest => "PermissionRequest",
HookEventName::PostToolUse => "PostToolUse",
HookEventName::PreCompact => "PreCompact",
HookEventName::PostCompact => "PostCompact",
HookEventName::SessionStart => "SessionStart",
HookEventName::UserPromptSubmit => "UserPromptSubmit",
HookEventName::Stop => "Stop",
@@ -1736,6 +1736,8 @@
"preToolUse",
"permissionRequest",
"postToolUse",
"preCompact",
"postCompact",
"sessionStart",
"userPromptSubmit",
"stop"
@@ -9824,6 +9824,8 @@
"preToolUse",
"permissionRequest",
"postToolUse",
"preCompact",
"postCompact",
"sessionStart",
"userPromptSubmit",
"stop"
@@ -10664,12 +10666,24 @@
},
"type": "array"
},
"PostCompact": {
"items": {
"$ref": "#/definitions/v2/ConfiguredHookMatcherGroup"
},
"type": "array"
},
"PostToolUse": {
"items": {
"$ref": "#/definitions/v2/ConfiguredHookMatcherGroup"
},
"type": "array"
},
"PreCompact": {
"items": {
"$ref": "#/definitions/v2/ConfiguredHookMatcherGroup"
},
"type": "array"
},
"PreToolUse": {
"items": {
"$ref": "#/definitions/v2/ConfiguredHookMatcherGroup"
@@ -10709,7 +10723,9 @@
},
"required": [
"PermissionRequest",
"PostCompact",
"PostToolUse",
"PreCompact",
"PreToolUse",
"SessionStart",
"Stop",
@@ -6391,6 +6391,8 @@
"preToolUse",
"permissionRequest",
"postToolUse",
"preCompact",
"postCompact",
"sessionStart",
"userPromptSubmit",
"stop"
@@ -7275,12 +7277,24 @@
},
"type": "array"
},
"PostCompact": {
"items": {
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
},
"type": "array"
},
"PostToolUse": {
"items": {
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
},
"type": "array"
},
"PreCompact": {
"items": {
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
},
"type": "array"
},
"PreToolUse": {
"items": {
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
@@ -7320,7 +7334,9 @@
},
"required": [
"PermissionRequest",
"PostCompact",
"PostToolUse",
"PreCompact",
"PreToolUse",
"SessionStart",
"Stop",
@@ -213,12 +213,24 @@
},
"type": "array"
},
"PostCompact": {
"items": {
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
},
"type": "array"
},
"PostToolUse": {
"items": {
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
},
"type": "array"
},
"PreCompact": {
"items": {
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
},
"type": "array"
},
"PreToolUse": {
"items": {
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
@@ -258,7 +270,9 @@
},
"required": [
"PermissionRequest",
"PostCompact",
"PostToolUse",
"PreCompact",
"PreToolUse",
"SessionStart",
"Stop",
@@ -10,6 +10,8 @@
"preToolUse",
"permissionRequest",
"postToolUse",
"preCompact",
"postCompact",
"sessionStart",
"userPromptSubmit",
"stop"
@@ -10,6 +10,8 @@
"preToolUse",
"permissionRequest",
"postToolUse",
"preCompact",
"postCompact",
"sessionStart",
"userPromptSubmit",
"stop"
@@ -25,6 +25,8 @@
"preToolUse",
"permissionRequest",
"postToolUse",
"preCompact",
"postCompact",
"sessionStart",
"userPromptSubmit",
"stop"
@@ -2,4 +2,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type HookEventName = "preToolUse" | "permissionRequest" | "postToolUse" | "sessionStart" | "userPromptSubmit" | "stop";
export type HookEventName = "preToolUse" | "permissionRequest" | "postToolUse" | "preCompact" | "postCompact" | "sessionStart" | "userPromptSubmit" | "stop";
@@ -3,4 +3,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ConfiguredHookMatcherGroup } from "./ConfiguredHookMatcherGroup";
export type ManagedHooksRequirements = { managedDir: string | null, windowsManagedDir: string | null, PreToolUse: Array<ConfiguredHookMatcherGroup>, PermissionRequest: Array<ConfiguredHookMatcherGroup>, PostToolUse: Array<ConfiguredHookMatcherGroup>, SessionStart: Array<ConfiguredHookMatcherGroup>, UserPromptSubmit: Array<ConfiguredHookMatcherGroup>, Stop: Array<ConfiguredHookMatcherGroup>, };
export type ManagedHooksRequirements = { managedDir: string | null, windowsManagedDir: string | null, PreToolUse: Array<ConfiguredHookMatcherGroup>, PermissionRequest: Array<ConfiguredHookMatcherGroup>, PostToolUse: Array<ConfiguredHookMatcherGroup>, PreCompact: Array<ConfiguredHookMatcherGroup>, PostCompact: Array<ConfiguredHookMatcherGroup>, SessionStart: Array<ConfiguredHookMatcherGroup>, UserPromptSubmit: Array<ConfiguredHookMatcherGroup>, Stop: Array<ConfiguredHookMatcherGroup>, };
@@ -77,6 +77,7 @@ macro_rules! experimental_type_entry {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClientRequestSerializationScope {
Global(&'static str),
GlobalSharedRead(&'static str),
Thread { thread_id: String },
ThreadPath { path: PathBuf },
CommandExecProcess { process_id: String },
@@ -93,6 +94,9 @@ macro_rules! serialization_scope_expr {
($actual_params:ident, global($key:literal)) => {
Some(ClientRequestSerializationScope::Global($key))
};
($actual_params:ident, global_shared_read($key:literal)) => {
Some(ClientRequestSerializationScope::GlobalSharedRead($key))
};
($actual_params:ident, thread_id($params:ident . $field:ident)) => {
Some(ClientRequestSerializationScope::Thread {
thread_id: $actual_params.$field.clone(),
@@ -585,7 +589,7 @@ client_request_definitions! {
},
SkillsList => "skills/list" {
params: v2::SkillsListParams,
serialization: global("config"),
serialization: global_shared_read("config"),
response: v2::SkillsListResponse,
},
HooksList => "hooks/list" {
@@ -610,7 +614,7 @@ client_request_definitions! {
},
PluginList => "plugin/list" {
params: v2::PluginListParams,
serialization: global("config"),
serialization: global_shared_read("config"),
response: v2::PluginListResponse,
},
PluginRead => "plugin/read" {
@@ -947,7 +951,7 @@ client_request_definitions! {
ConfigRead => "config/read" {
params: v2::ConfigReadParams,
serialization: global("config"),
serialization: global_shared_read("config"),
response: v2::ConfigReadResponse,
},
ExternalAgentConfigDetect => "externalAgentConfig/detect" {
@@ -1655,6 +1659,28 @@ mod tests {
Some(ClientRequestSerializationScope::Global("config"))
);
let skills_list = ClientRequest::SkillsList {
request_id: request_id(),
params: v2::SkillsListParams {
cwds: Vec::new(),
force_reload: false,
per_cwd_extra_user_roots: None,
},
};
assert_eq!(
skills_list.serialization_scope(),
Some(ClientRequestSerializationScope::GlobalSharedRead("config"))
);
let plugin_list = ClientRequest::PluginList {
request_id: request_id(),
params: v2::PluginListParams { cwds: None },
};
assert_eq!(
plugin_list.serialization_scope(),
Some(ClientRequestSerializationScope::GlobalSharedRead("config"))
);
let plugin_uninstall = ClientRequest::PluginUninstall {
request_id: request_id(),
params: v2::PluginUninstallParams {
@@ -1705,7 +1731,7 @@ mod tests {
};
assert_eq!(
config_read.serialization_scope(),
Some(ClientRequestSerializationScope::Global("config"))
Some(ClientRequestSerializationScope::GlobalSharedRead("config"))
);
let account_read = ClientRequest::GetAccount {
@@ -380,6 +380,12 @@ pub struct ManagedHooksRequirements {
#[serde(rename = "PostToolUse")]
#[ts(rename = "PostToolUse")]
pub post_tool_use: Vec<ConfiguredHookMatcherGroup>,
#[serde(rename = "PreCompact")]
#[ts(rename = "PreCompact")]
pub pre_compact: Vec<ConfiguredHookMatcherGroup>,
#[serde(rename = "PostCompact")]
#[ts(rename = "PostCompact")]
pub post_compact: Vec<ConfiguredHookMatcherGroup>,
#[serde(rename = "SessionStart")]
#[ts(rename = "SessionStart")]
pub session_start: Vec<ConfiguredHookMatcherGroup>,
@@ -17,7 +17,7 @@ use ts_rs::TS;
v2_enum_from_core!(
pub enum HookEventName from CoreHookEventName {
PreToolUse, PermissionRequest, PostToolUse, SessionStart, UserPromptSubmit, Stop
PreToolUse, PermissionRequest, PostToolUse, PreCompact, PostCompact, SessionStart, UserPromptSubmit, Stop
}
);
@@ -49,6 +49,7 @@ use codex_app_server_protocol::RawResponseItemCompletedNotification;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ServerRequestPayload;
use codex_app_server_protocol::SkillsChangedNotification;
use codex_app_server_protocol::ThreadGoalUpdatedNotification;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadRealtimeClosedNotification;
@@ -193,6 +194,13 @@ pub(crate) async fn apply_bespoke_event_handling(
)
.await;
}
EventMsg::SkillsUpdateAvailable => {
outgoing
.send_server_notification(ServerNotification::SkillsChanged(
SkillsChangedNotification {},
))
.await;
}
EventMsg::McpStartupUpdate(update) => {
let (status, error) = match update.status {
codex_protocol::protocol::McpStartupStatus::Starting => {
-1
View File
@@ -93,7 +93,6 @@ mod outgoing_message;
mod request_processors;
mod request_serialization;
mod server_request_error;
mod skills_watcher;
mod thread_state;
mod thread_status;
mod transport;
+2 -6
View File
@@ -35,7 +35,6 @@ use crate::request_processors::WindowsSandboxRequestProcessor;
use crate::request_serialization::QueuedInitializedRequest;
use crate::request_serialization::RequestSerializationQueueKey;
use crate::request_serialization::RequestSerializationQueues;
use crate::skills_watcher::SkillsWatcher;
use crate::thread_state::ThreadStateManager;
use crate::transport::AppServerTransport;
use crate::transport::ConnectionOrigin;
@@ -310,7 +309,6 @@ impl MessageProcessor {
thread_manager
.plugins_manager()
.set_analytics_events_client(analytics_events_client.clone());
let skills_watcher = SkillsWatcher::new(thread_manager.skills_manager(), outgoing.clone());
let pending_thread_unloads = Arc::new(Mutex::new(HashSet::new()));
let thread_state_manager = ThreadStateManager::new();
@@ -403,7 +401,6 @@ impl MessageProcessor {
Arc::clone(&thread_list_state_permit),
thread_goal_processor.clone(),
Some(state_db.clone()),
Arc::clone(&skills_watcher),
);
let turn_processor = TurnRequestProcessor::new(
auth_manager.clone(),
@@ -417,7 +414,6 @@ impl MessageProcessor {
thread_state_manager,
thread_watch_manager,
thread_list_state_permit,
Arc::clone(&skills_watcher),
);
if matches!(plugin_startup_tasks, crate::PluginStartupTasks::Start) {
// Keep plugin startup warmups aligned at app-server startup.
@@ -804,9 +800,9 @@ impl MessageProcessor {
);
if let Some(scope) = serialization_scope {
let key = RequestSerializationQueueKey::from_scope(connection_id, scope);
let (key, access) = RequestSerializationQueueKey::from_scope(connection_id, scope);
self.request_serialization_queues
.enqueue(key, request)
.enqueue(key, access, request)
.await;
} else {
tokio::spawn(async move {
@@ -11,7 +11,6 @@ use crate::outgoing_message::ConnectionRequestId;
use crate::outgoing_message::OutgoingMessageSender;
use crate::outgoing_message::RequestContext;
use crate::outgoing_message::ThreadScopedOutgoingMessageSender;
use crate::skills_watcher::SkillsWatcher;
use crate::thread_status::ThreadWatchManager;
use crate::thread_status::resolve_thread_status;
use chrono::DateTime;
@@ -1,4 +1,5 @@
use super::*;
use futures::StreamExt;
#[derive(Clone)]
pub(crate) struct CatalogRequestProcessor {
@@ -9,6 +10,8 @@ pub(crate) struct CatalogRequestProcessor {
pub(super) workspace_settings_cache: Arc<workspace_settings::WorkspaceSettingsCache>,
}
const SKILLS_LIST_CWD_CONCURRENCY: usize = 5;
fn skills_to_info(
skills: &[codex_core::skills::SkillMetadata],
disabled_paths: &HashSet<AbsolutePathBuf>,
@@ -430,56 +433,76 @@ impl CatalogRequestProcessor {
.environment_manager()
.default_environment()
.map(|environment| environment.get_filesystem());
let mut data = Vec::new();
for cwd in cwds {
let (cwd_abs, config_layer_stack) = match self.resolve_cwd_config(&cwd).await {
Ok(resolved) => resolved,
Err(message) => {
let error_path = cwd.clone();
data.push(codex_app_server_protocol::SkillsListEntry {
cwd,
skills: Vec::new(),
errors: vec![codex_app_server_protocol::SkillErrorInfo {
path: error_path,
message,
}],
});
continue;
let mut data = futures::stream::iter(cwds.into_iter().enumerate())
.map(|(index, cwd)| {
let config = &config;
let extra_roots_by_cwd = &extra_roots_by_cwd;
let fs = fs.clone();
let plugins_manager = &plugins_manager;
let skills_manager = &skills_manager;
async move {
let (cwd_abs, config_layer_stack) = match self.resolve_cwd_config(&cwd).await {
Ok(resolved) => resolved,
Err(message) => {
let error_path = cwd.clone();
return (
index,
codex_app_server_protocol::SkillsListEntry {
cwd,
skills: Vec::new(),
errors: vec![codex_app_server_protocol::SkillErrorInfo {
path: error_path,
message,
}],
},
);
}
};
let extra_roots = extra_roots_by_cwd
.get(&cwd)
.map_or(&[][..], std::vec::Vec::as_slice);
let effective_skill_roots = if workspace_codex_plugins_enabled {
let plugins_input = config.plugins_config_input();
plugins_manager
.effective_skill_roots_for_layer_stack(
&config_layer_stack,
&plugins_input,
)
.await
} else {
Vec::new()
};
let skills_input = codex_core::skills::SkillsLoadInput::new(
cwd_abs.clone(),
effective_skill_roots,
config_layer_stack,
config.bundled_skills_enabled(),
);
let outcome = skills_manager
.skills_for_cwd_with_extra_user_roots(
&skills_input,
force_reload,
extra_roots,
fs,
)
.await;
let errors = errors_to_info(&outcome.errors);
let skills = skills_to_info(&outcome.skills, &outcome.disabled_paths);
(
index,
codex_app_server_protocol::SkillsListEntry {
cwd,
skills,
errors,
},
)
}
};
let extra_roots = extra_roots_by_cwd
.get(&cwd)
.map_or(&[][..], std::vec::Vec::as_slice);
let effective_skill_roots = if workspace_codex_plugins_enabled {
let plugins_input = config.plugins_config_input();
plugins_manager
.effective_skill_roots_for_layer_stack(&config_layer_stack, &plugins_input)
.await
} else {
Vec::new()
};
let skills_input = codex_core::skills::SkillsLoadInput::new(
cwd_abs.clone(),
effective_skill_roots,
config_layer_stack,
config.bundled_skills_enabled(),
);
let outcome = skills_manager
.skills_for_cwd_with_extra_user_roots(
&skills_input,
force_reload,
extra_roots,
fs.clone(),
)
.await;
let errors = errors_to_info(&outcome.errors);
let skills = skills_to_info(&outcome.skills, &outcome.disabled_paths);
data.push(codex_app_server_protocol::SkillsListEntry {
cwd,
skills,
errors,
});
}
})
.buffer_unordered(SKILLS_LIST_CWD_CONCURRENCY)
.collect::<Vec<_>>()
.await;
data.sort_unstable_by_key(|(index, _)| *index);
let data = data.into_iter().map(|(_, entry)| entry).collect();
Ok(SkillsListResponse { data })
}
@@ -462,6 +462,8 @@ fn map_hooks_requirements_to_api(hooks: ManagedHooksRequirementsToml) -> Managed
pre_tool_use,
permission_request,
post_tool_use,
pre_compact,
post_compact,
session_start,
user_prompt_submit,
stop,
@@ -473,6 +475,8 @@ fn map_hooks_requirements_to_api(hooks: ManagedHooksRequirementsToml) -> Managed
pre_tool_use: map_hook_matcher_groups_to_api(pre_tool_use),
permission_request: map_hook_matcher_groups_to_api(permission_request),
post_tool_use: map_hook_matcher_groups_to_api(post_tool_use),
pre_compact: map_hook_matcher_groups_to_api(pre_compact),
post_compact: map_hook_matcher_groups_to_api(post_compact),
session_start: map_hook_matcher_groups_to_api(session_start),
user_prompt_submit: map_hook_matcher_groups_to_api(user_prompt_submit),
stop: map_hook_matcher_groups_to_api(stop),
@@ -12,7 +12,6 @@ pub(super) struct ListenerTaskContext {
pub(super) thread_list_state_permit: Arc<Semaphore>,
pub(super) fallback_model_provider: String,
pub(super) codex_home: PathBuf,
pub(super) skills_watcher: Arc<SkillsWatcher>,
}
struct UnloadingState {
@@ -227,22 +226,12 @@ pub(super) async fn ensure_listener_task_running(
"thread {conversation_id} is closing; retry after the thread is closed"
)));
};
let config = conversation.config().await;
let environments = conversation.environment_selections().await;
let watch_registration = listener_task_context
.skills_watcher
.register_thread_config(
config.as_ref(),
listener_task_context.thread_manager.as_ref(),
&environments,
)
.await;
let (mut listener_command_rx, listener_generation) = {
let mut thread_state = thread_state.lock().await;
if thread_state.listener_matches(&conversation) {
return Ok(());
}
thread_state.set_listener(cancel_tx, &conversation, watch_registration)
thread_state.set_listener(cancel_tx, &conversation)
};
let ListenerTaskContext {
outgoing,
@@ -253,7 +242,6 @@ pub(super) async fn ensure_listener_task_running(
thread_list_state_permit,
fallback_model_provider,
codex_home,
..
} = listener_task_context;
let outgoing_for_task = Arc::clone(&outgoing);
tokio::spawn(async move {
@@ -316,7 +316,6 @@ pub(crate) struct ThreadRequestProcessor {
pub(super) thread_goal_processor: ThreadGoalRequestProcessor,
pub(super) state_db: Option<StateDbHandle>,
pub(super) background_tasks: TaskTracker,
pub(super) skills_watcher: Arc<SkillsWatcher>,
}
impl ThreadRequestProcessor {
@@ -335,7 +334,6 @@ impl ThreadRequestProcessor {
thread_list_state_permit: Arc<Semaphore>,
thread_goal_processor: ThreadGoalRequestProcessor,
state_db: Option<StateDbHandle>,
skills_watcher: Arc<SkillsWatcher>,
) -> Self {
Self {
auth_manager,
@@ -352,7 +350,6 @@ impl ThreadRequestProcessor {
thread_goal_processor,
state_db,
background_tasks: TaskTracker::new(),
skills_watcher,
}
}
@@ -745,7 +742,6 @@ impl ThreadRequestProcessor {
thread_list_state_permit: self.thread_list_state_permit.clone(),
fallback_model_provider: self.config.model_provider_id.clone(),
codex_home: self.config.codex_home.to_path_buf(),
skills_watcher: Arc::clone(&self.skills_watcher),
}
}
@@ -843,7 +839,6 @@ impl ThreadRequestProcessor {
thread_list_state_permit: self.thread_list_state_permit.clone(),
fallback_model_provider: self.config.model_provider_id.clone(),
codex_home: self.config.codex_home.to_path_buf(),
skills_watcher: Arc::clone(&self.skills_watcher),
};
let request_trace = request_context.request_trace();
let config_manager = self.config_manager.clone();
@@ -1044,6 +1039,7 @@ impl ThreadRequestProcessor {
.collect()
};
let core_dynamic_tool_count = core_dynamic_tools.len();
let NewThread {
thread_id,
thread,
@@ -13,7 +13,6 @@ pub(crate) struct TurnRequestProcessor {
thread_state_manager: ThreadStateManager,
thread_watch_manager: ThreadWatchManager,
thread_list_state_permit: Arc<Semaphore>,
skills_watcher: Arc<SkillsWatcher>,
}
impl TurnRequestProcessor {
@@ -30,7 +29,6 @@ impl TurnRequestProcessor {
thread_state_manager: ThreadStateManager,
thread_watch_manager: ThreadWatchManager,
thread_list_state_permit: Arc<Semaphore>,
skills_watcher: Arc<SkillsWatcher>,
) -> Self {
Self {
auth_manager,
@@ -44,7 +42,6 @@ impl TurnRequestProcessor {
thread_state_manager,
thread_watch_manager,
thread_list_state_permit,
skills_watcher,
}
}
@@ -1090,7 +1087,6 @@ impl TurnRequestProcessor {
thread_list_state_permit: self.thread_list_state_permit.clone(),
fallback_model_provider: self.config.model_provider_id.clone(),
codex_home: self.config.codex_home.to_path_buf(),
skills_watcher: Arc::clone(&self.skills_watcher),
}
}
+319 -25
View File
@@ -6,6 +6,7 @@ use std::pin::Pin;
use std::sync::Arc;
use codex_app_server_protocol::ClientRequestSerializationScope;
use futures::future::join_all;
use tokio::sync::Mutex;
use tracing::Instrument;
@@ -43,35 +44,61 @@ pub(crate) enum RequestSerializationQueueKey {
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum RequestSerializationAccess {
Exclusive,
SharedRead,
}
impl RequestSerializationQueueKey {
pub(crate) fn from_scope(
connection_id: ConnectionId,
scope: ClientRequestSerializationScope,
) -> Self {
) -> (Self, RequestSerializationAccess) {
match scope {
ClientRequestSerializationScope::Global(name) => Self::Global(name),
ClientRequestSerializationScope::Thread { thread_id } => Self::Thread { thread_id },
ClientRequestSerializationScope::ThreadPath { path } => Self::ThreadPath { path },
ClientRequestSerializationScope::CommandExecProcess { process_id } => {
ClientRequestSerializationScope::Global(name) => {
(Self::Global(name), RequestSerializationAccess::Exclusive)
}
ClientRequestSerializationScope::GlobalSharedRead(name) => {
(Self::Global(name), RequestSerializationAccess::SharedRead)
}
ClientRequestSerializationScope::Thread { thread_id } => (
Self::Thread { thread_id },
RequestSerializationAccess::Exclusive,
),
ClientRequestSerializationScope::ThreadPath { path } => (
Self::ThreadPath { path },
RequestSerializationAccess::Exclusive,
),
ClientRequestSerializationScope::CommandExecProcess { process_id } => (
Self::CommandExecProcess {
connection_id,
process_id,
}
}
ClientRequestSerializationScope::Process { process_handle } => Self::Process {
connection_id,
process_handle,
},
ClientRequestSerializationScope::FuzzyFileSearchSession { session_id } => {
Self::FuzzyFileSearchSession { session_id }
}
ClientRequestSerializationScope::FsWatch { watch_id } => Self::FsWatch {
connection_id,
watch_id,
},
ClientRequestSerializationScope::McpOauth { server_name } => {
Self::McpOauth { server_name }
}
},
RequestSerializationAccess::Exclusive,
),
ClientRequestSerializationScope::Process { process_handle } => (
Self::Process {
connection_id,
process_handle,
},
RequestSerializationAccess::Exclusive,
),
ClientRequestSerializationScope::FuzzyFileSearchSession { session_id } => (
Self::FuzzyFileSearchSession { session_id },
RequestSerializationAccess::Exclusive,
),
ClientRequestSerializationScope::FsWatch { watch_id } => (
Self::FsWatch {
connection_id,
watch_id,
},
RequestSerializationAccess::Exclusive,
),
ClientRequestSerializationScope::McpOauth { server_name } => (
Self::McpOauth { server_name },
RequestSerializationAccess::Exclusive,
),
}
}
}
@@ -98,17 +125,24 @@ impl QueuedInitializedRequest {
}
}
struct QueuedSerializedRequest {
access: RequestSerializationAccess,
request: QueuedInitializedRequest,
}
#[derive(Clone, Default)]
pub(crate) struct RequestSerializationQueues {
inner: Arc<Mutex<HashMap<RequestSerializationQueueKey, VecDeque<QueuedInitializedRequest>>>>,
inner: Arc<Mutex<HashMap<RequestSerializationQueueKey, VecDeque<QueuedSerializedRequest>>>>,
}
impl RequestSerializationQueues {
pub(crate) async fn enqueue(
&self,
key: RequestSerializationQueueKey,
access: RequestSerializationAccess,
request: QueuedInitializedRequest,
) {
let request = QueuedSerializedRequest { access, request };
let should_spawn = {
let mut queues = self.inner.lock().await;
match queues.get_mut(&key) {
@@ -134,13 +168,27 @@ impl RequestSerializationQueues {
async fn drain(self, key: RequestSerializationQueueKey) {
loop {
let request = {
let requests = {
let mut queues = self.inner.lock().await;
let Some(queue) = queues.get_mut(&key) else {
return;
};
match queue.pop_front() {
Some(request) => request,
Some(request) => {
let access = request.access;
let mut requests = vec![request];
if access == RequestSerializationAccess::SharedRead {
while queue.front().is_some_and(|request| {
request.access == RequestSerializationAccess::SharedRead
}) {
let Some(request) = queue.pop_front() else {
break;
};
requests.push(request);
}
}
requests
}
None => {
queues.remove(&key);
return;
@@ -148,7 +196,7 @@ impl RequestSerializationQueues {
}
};
request.run().await;
join_all(requests.into_iter().map(|request| request.request.run())).await;
}
}
}
@@ -158,6 +206,7 @@ mod tests {
use super::*;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::time::Duration;
@@ -195,6 +244,7 @@ mod tests {
queues
.enqueue(
key.clone(),
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(Arc::clone(&gate), async move {
tx.send(value).expect("receiver should be open");
}),
@@ -230,6 +280,7 @@ mod tests {
queues
.enqueue(
RequestSerializationQueueKey::Global("blocked"),
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(gate(), async move {
let _ = blocked_rx.await;
}),
@@ -238,6 +289,7 @@ mod tests {
queues
.enqueue(
RequestSerializationQueueKey::Global("other"),
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(gate(), async move {
ran_tx.send(()).expect("receiver should be open");
}),
@@ -268,6 +320,7 @@ mod tests {
queues
.enqueue(
key.clone(),
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(Arc::clone(&live_gate), async move {
tx.send(FIRST_REQUEST_VALUE)
.expect("receiver should be open");
@@ -281,6 +334,7 @@ mod tests {
queues
.enqueue(
key.clone(),
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(closed_gate, async move {
tx.send(SECOND_REQUEST_VALUE)
.expect("receiver should be open");
@@ -293,6 +347,7 @@ mod tests {
queues
.enqueue(
key,
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(live_gate, async move {
tx.send(THIRD_REQUEST_VALUE)
.expect("receiver should be open");
@@ -336,6 +391,7 @@ mod tests {
queues
.enqueue(
key.clone(),
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(Arc::clone(&live_gate), async move {
tx.send(FIRST_REQUEST_VALUE)
.expect("receiver should be open");
@@ -349,6 +405,7 @@ mod tests {
queues
.enqueue(
key,
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(live_gate.clone(), async move {
tx.send(SECOND_REQUEST_VALUE)
.expect("receiver should be open");
@@ -385,4 +442,241 @@ mod tests {
None
);
}
#[tokio::test]
async fn same_key_shared_reads_run_concurrently() {
let queues = RequestSerializationQueues::default();
let key = RequestSerializationQueueKey::Global("test");
let (blocker_started_tx, blocker_started_rx) = oneshot::channel::<()>();
let (blocker_release_tx, blocker_release_rx) = oneshot::channel::<()>();
let (started_tx, mut started_rx) = mpsc::unbounded_channel();
let (release_tx, _) = broadcast::channel::<()>(/*capacity*/ 1);
queues
.enqueue(
key.clone(),
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(gate(), async move {
blocker_started_tx
.send(())
.expect("receiver should be open");
let _ = blocker_release_rx.await;
}),
)
.await;
timeout(queue_drain_timeout(), blocker_started_rx)
.await
.expect("blocker should start")
.expect("sender should be open");
for value in [FIRST_REQUEST_VALUE, SECOND_REQUEST_VALUE] {
let started_tx = started_tx.clone();
let mut release_rx = release_tx.subscribe();
queues
.enqueue(
key.clone(),
RequestSerializationAccess::SharedRead,
QueuedInitializedRequest::new(gate(), async move {
started_tx.send(value).expect("receiver should be open");
let _ = release_rx.recv().await;
}),
)
.await;
}
drop(started_tx);
blocker_release_tx
.send(())
.expect("blocker should still be waiting");
let mut started = Vec::new();
for _ in 0..2 {
started.push(
timeout(queue_drain_timeout(), started_rx.recv())
.await
.expect("timed out waiting for shared read")
.expect("sender should be open"),
);
}
assert_eq!(started, vec![FIRST_REQUEST_VALUE, SECOND_REQUEST_VALUE]);
release_tx
.send(())
.expect("shared reads should still be waiting");
}
#[tokio::test]
async fn exclusive_write_waits_for_running_shared_reads() {
let queues = RequestSerializationQueues::default();
let key = RequestSerializationQueueKey::Global("test");
let (blocker_started_tx, blocker_started_rx) = oneshot::channel::<()>();
let (blocker_release_tx, blocker_release_rx) = oneshot::channel::<()>();
let (read_started_tx, mut read_started_rx) = mpsc::unbounded_channel();
let (read_release_tx, _) = broadcast::channel::<()>(/*capacity*/ 1);
let (write_started_tx, write_started_rx) = oneshot::channel::<()>();
queues
.enqueue(
key.clone(),
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(gate(), async move {
blocker_started_tx
.send(())
.expect("receiver should be open");
let _ = blocker_release_rx.await;
}),
)
.await;
timeout(queue_drain_timeout(), blocker_started_rx)
.await
.expect("blocker should start")
.expect("sender should be open");
for value in [FIRST_REQUEST_VALUE, SECOND_REQUEST_VALUE] {
let read_started_tx = read_started_tx.clone();
let mut read_release_rx = read_release_tx.subscribe();
queues
.enqueue(
key.clone(),
RequestSerializationAccess::SharedRead,
QueuedInitializedRequest::new(gate(), async move {
read_started_tx
.send(value)
.expect("receiver should be open");
let _ = read_release_rx.recv().await;
}),
)
.await;
}
queues
.enqueue(
key.clone(),
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(gate(), async move {
write_started_tx.send(()).expect("receiver should be open");
}),
)
.await;
drop(read_started_tx);
blocker_release_tx
.send(())
.expect("blocker should still be waiting");
for _ in 0..2 {
timeout(queue_drain_timeout(), read_started_rx.recv())
.await
.expect("timed out waiting for shared read")
.expect("sender should be open");
}
let mut write_started_rx = Box::pin(write_started_rx);
timeout(shutdown_wait_timeout(), &mut write_started_rx)
.await
.expect_err("write should wait for running shared reads");
read_release_tx
.send(())
.expect("shared reads should still be waiting");
timeout(queue_drain_timeout(), &mut write_started_rx)
.await
.expect("write should start after shared reads finish")
.expect("sender should be open");
}
#[tokio::test]
async fn later_shared_reads_do_not_jump_ahead_of_queued_write() {
let queues = RequestSerializationQueues::default();
let key = RequestSerializationQueueKey::Global("test");
let (blocker_started_tx, blocker_started_rx) = oneshot::channel::<()>();
let (blocker_release_tx, blocker_release_rx) = oneshot::channel::<()>();
let (first_read_started_tx, first_read_started_rx) = oneshot::channel::<()>();
let (first_read_release_tx, first_read_release_rx) = oneshot::channel::<()>();
let (write_started_tx, write_started_rx) = oneshot::channel::<()>();
let (write_release_tx, write_release_rx) = oneshot::channel::<()>();
let (later_read_started_tx, later_read_started_rx) = oneshot::channel::<()>();
queues
.enqueue(
key.clone(),
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(gate(), async move {
blocker_started_tx
.send(())
.expect("receiver should be open");
let _ = blocker_release_rx.await;
}),
)
.await;
timeout(queue_drain_timeout(), blocker_started_rx)
.await
.expect("blocker should start")
.expect("sender should be open");
queues
.enqueue(
key.clone(),
RequestSerializationAccess::SharedRead,
QueuedInitializedRequest::new(gate(), async move {
first_read_started_tx
.send(())
.expect("receiver should be open");
let _ = first_read_release_rx.await;
}),
)
.await;
queues
.enqueue(
key.clone(),
RequestSerializationAccess::Exclusive,
QueuedInitializedRequest::new(gate(), async move {
write_started_tx.send(()).expect("receiver should be open");
let _ = write_release_rx.await;
}),
)
.await;
queues
.enqueue(
key.clone(),
RequestSerializationAccess::SharedRead,
QueuedInitializedRequest::new(gate(), async move {
later_read_started_tx
.send(())
.expect("receiver should be open");
}),
)
.await;
blocker_release_tx
.send(())
.expect("blocker should still be waiting");
timeout(queue_drain_timeout(), first_read_started_rx)
.await
.expect("first read should start")
.expect("sender should be open");
let mut write_started_rx = Box::pin(write_started_rx);
timeout(shutdown_wait_timeout(), &mut write_started_rx)
.await
.expect_err("write should wait for the first read");
let mut later_read_started_rx = Box::pin(later_read_started_rx);
timeout(shutdown_wait_timeout(), &mut later_read_started_rx)
.await
.expect_err("later read should wait behind the queued write");
first_read_release_tx
.send(())
.expect("first read should still be waiting");
timeout(queue_drain_timeout(), &mut write_started_rx)
.await
.expect("write should start after the first read")
.expect("sender should be open");
timeout(shutdown_wait_timeout(), &mut later_read_started_rx)
.await
.expect_err("later read should still wait while the write is running");
write_release_tx
.send(())
.expect("write should still be waiting");
timeout(queue_drain_timeout(), &mut later_read_started_rx)
.await
.expect("later read should start after the write")
.expect("sender should be open");
}
}
-112
View File
@@ -1,112 +0,0 @@
use std::sync::Arc;
use std::time::Duration;
use crate::outgoing_message::OutgoingMessageSender;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::SkillsChangedNotification;
use codex_core::ThreadManager;
use codex_core::config::Config;
use codex_core::file_watcher::FileWatcher;
use codex_core::file_watcher::FileWatcherSubscriber;
use codex_core::file_watcher::Receiver;
use codex_core::file_watcher::ThrottledWatchReceiver;
use codex_core::file_watcher::WatchPath;
use codex_core::file_watcher::WatchRegistration;
use codex_core::skills::SkillsLoadInput;
use codex_core::skills::SkillsManager;
use codex_protocol::protocol::TurnEnvironmentSelection;
use tracing::warn;
#[cfg(not(test))]
const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_secs(10);
#[cfg(test)]
const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_millis(50);
pub(crate) struct SkillsWatcher {
subscriber: FileWatcherSubscriber,
}
impl SkillsWatcher {
pub(crate) fn new(
skills_manager: Arc<SkillsManager>,
outgoing: Arc<OutgoingMessageSender>,
) -> Arc<Self> {
let file_watcher = match FileWatcher::new() {
Ok(file_watcher) => Arc::new(file_watcher),
Err(err) => {
warn!("failed to initialize skills file watcher: {err}");
Arc::new(FileWatcher::noop())
}
};
let (subscriber, rx) = file_watcher.add_subscriber();
Self::spawn_event_loop(rx, skills_manager, outgoing);
Arc::new(Self { subscriber })
}
pub(crate) async fn register_thread_config(
&self,
config: &Config,
thread_manager: &ThreadManager,
environments: &[TurnEnvironmentSelection],
) -> WatchRegistration {
let Some(environment_selection) = environments.first() else {
return WatchRegistration::default();
};
let Some(environment) = thread_manager
.environment_manager()
.get_environment(&environment_selection.environment_id)
else {
warn!(
"failed to register skills watcher for unknown environment `{}`",
environment_selection.environment_id
);
return WatchRegistration::default();
};
if environment.is_remote() {
return WatchRegistration::default();
}
let plugins_input = config.plugins_config_input();
let plugins_manager = thread_manager.plugins_manager();
let plugin_outcome = plugins_manager.plugins_for_config(&plugins_input).await;
let skills_input = SkillsLoadInput::new(
config.cwd.clone(),
plugin_outcome.effective_plugin_skill_roots(),
config.config_layer_stack.clone(),
config.bundled_skills_enabled(),
);
let roots = thread_manager
.skills_manager()
.skill_roots_for_config(&skills_input, Some(environment.get_filesystem()))
.await
.into_iter()
.map(|root| WatchPath {
path: root.path.into_path_buf(),
recursive: true,
})
.collect();
self.subscriber.register_paths(roots)
}
fn spawn_event_loop(
rx: Receiver,
skills_manager: Arc<SkillsManager>,
outgoing: Arc<OutgoingMessageSender>,
) {
let mut rx = ThrottledWatchReceiver::new(rx, WATCHER_THROTTLE_INTERVAL);
let Ok(handle) = tokio::runtime::Handle::try_current() else {
warn!("skills watcher listener skipped: no Tokio runtime available");
return;
};
handle.spawn(async move {
while rx.recv().await.is_some() {
skills_manager.clear_cache();
outgoing
.send_server_notification(ServerNotification::SkillsChanged(
SkillsChangedNotification {},
))
.await;
}
});
}
}
-5
View File
@@ -7,7 +7,6 @@ use codex_app_server_protocol::Turn;
use codex_app_server_protocol::TurnError;
use codex_core::CodexThread;
use codex_core::ThreadConfigSnapshot;
use codex_core::file_watcher::WatchRegistration;
use codex_protocol::ThreadId;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::RolloutItem;
@@ -78,7 +77,6 @@ pub(crate) struct ThreadState {
listener_command_tx: Option<mpsc::UnboundedSender<ThreadListenerCommand>>,
current_turn_history: ThreadHistoryBuilder,
listener_thread: Option<Weak<CodexThread>>,
watch_registration: WatchRegistration,
}
impl ThreadState {
@@ -93,7 +91,6 @@ impl ThreadState {
&mut self,
cancel_tx: oneshot::Sender<()>,
conversation: &Arc<CodexThread>,
watch_registration: WatchRegistration,
) -> (mpsc::UnboundedReceiver<ThreadListenerCommand>, u64) {
if let Some(previous) = self.cancel_tx.replace(cancel_tx) {
let _ = previous.send(());
@@ -102,7 +99,6 @@ impl ThreadState {
let (listener_command_tx, listener_command_rx) = mpsc::unbounded_channel();
self.listener_command_tx = Some(listener_command_tx);
self.listener_thread = Some(Arc::downgrade(conversation));
self.watch_registration = watch_registration;
(listener_command_rx, self.listener_generation)
}
@@ -113,7 +109,6 @@ impl ThreadState {
self.listener_command_tx = None;
self.current_turn_history.reset();
self.listener_thread = None;
self.watch_registration = WatchRegistration::default();
}
pub(crate) fn set_experimental_raw_events(&mut self, enabled: bool) {
@@ -533,6 +533,44 @@ async fn skills_list_accepts_relative_cwds() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn skills_list_preserves_requested_cwd_order() -> Result<()> {
let codex_home = TempDir::new()?;
let first_cwd = TempDir::new()?;
let second_cwd = TempDir::new()?;
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_skills_list_request(SkillsListParams {
cwds: vec![
first_cwd.path().to_path_buf(),
second_cwd.path().to_path_buf(),
],
force_reload: true,
per_cwd_extra_user_roots: None,
})
.await?;
let response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let SkillsListResponse { data } = to_response(response)?;
assert_eq!(
data.iter()
.map(|entry| entry.cwd.clone())
.collect::<Vec<_>>(),
vec![
first_cwd.path().to_path_buf(),
second_cwd.path().to_path_buf(),
]
);
Ok(())
}
#[tokio::test]
async fn skills_list_ignores_per_cwd_extra_roots_for_unknown_cwd() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -661,27 +699,6 @@ async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<(
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let initial_skills_request_id = mcp
.send_skills_list_request(SkillsListParams {
cwds: vec![codex_home.path().to_path_buf()],
force_reload: true,
per_cwd_extra_user_roots: None,
})
.await?;
let initial_skills_response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(initial_skills_request_id)),
)
.await??;
let SkillsListResponse { data } = to_response(initial_skills_response)?;
assert_eq!(data.len(), 1);
assert!(
data[0]
.skills
.iter()
.any(|skill| { skill.name == "demo" && skill.description == "demo description" })
);
let thread_start_request_id = mcp
.send_thread_start_request(ThreadStartParams {
model: None,
@@ -734,25 +751,5 @@ async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<(
let notification: SkillsChangedNotification = serde_json::from_value(params)?;
assert_eq!(notification, SkillsChangedNotification {});
let updated_skills_request_id = mcp
.send_skills_list_request(SkillsListParams {
cwds: vec![codex_home.path().to_path_buf()],
force_reload: false,
per_cwd_extra_user_roots: None,
})
.await?;
let updated_skills_response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(updated_skills_request_id)),
)
.await??;
let SkillsListResponse { data } = to_response(updated_skills_response)?;
assert_eq!(data.len(), 1);
assert!(
data[0]
.skills
.iter()
.any(|skill| skill.name == "demo" && skill.description == "updated")
);
Ok(())
}
+15 -1
View File
@@ -37,6 +37,10 @@ pub struct HookEventsToml {
pub permission_request: Vec<MatcherGroup>,
#[serde(rename = "PostToolUse", default)]
pub post_tool_use: Vec<MatcherGroup>,
#[serde(rename = "PreCompact", default)]
pub pre_compact: Vec<MatcherGroup>,
#[serde(rename = "PostCompact", default)]
pub post_compact: Vec<MatcherGroup>,
#[serde(rename = "SessionStart", default)]
pub session_start: Vec<MatcherGroup>,
#[serde(rename = "UserPromptSubmit", default)]
@@ -51,6 +55,8 @@ impl HookEventsToml {
pre_tool_use,
permission_request,
post_tool_use,
pre_compact,
post_compact,
session_start,
user_prompt_submit,
stop,
@@ -58,6 +64,8 @@ impl HookEventsToml {
pre_tool_use.is_empty()
&& permission_request.is_empty()
&& post_tool_use.is_empty()
&& pre_compact.is_empty()
&& post_compact.is_empty()
&& session_start.is_empty()
&& user_prompt_submit.is_empty()
&& stop.is_empty()
@@ -68,6 +76,8 @@ impl HookEventsToml {
pre_tool_use,
permission_request,
post_tool_use,
pre_compact,
post_compact,
session_start,
user_prompt_submit,
stop,
@@ -76,6 +86,8 @@ impl HookEventsToml {
pre_tool_use,
permission_request,
post_tool_use,
pre_compact,
post_compact,
session_start,
user_prompt_submit,
stop,
@@ -86,11 +98,13 @@ impl HookEventsToml {
.sum()
}
pub fn into_matcher_groups(self) -> [(HookEventName, Vec<MatcherGroup>); 6] {
pub fn into_matcher_groups(self) -> [(HookEventName, Vec<MatcherGroup>); 8] {
[
(HookEventName::PreToolUse, self.pre_tool_use),
(HookEventName::PermissionRequest, self.permission_request),
(HookEventName::PostToolUse, self.post_tool_use),
(HookEventName::PreCompact, self.pre_compact),
(HookEventName::PostCompact, self.post_compact),
(HookEventName::SessionStart, self.session_start),
(HookEventName::UserPromptSubmit, self.user_prompt_submit),
(HookEventName::Stop, self.stop),
+1
View File
@@ -26,6 +26,7 @@ pub const TOOL_SUGGEST_DISCOVERABLE_PLUGIN_ALLOWLIST: &[&str] = &[
"gmail@openai-curated",
"google-calendar@openai-curated",
"google-drive@openai-curated",
"openai-developers@openai-curated",
"canva@openai-curated",
"teams@openai-curated",
"sharepoint@openai-curated",
+14
View File
@@ -1033,6 +1033,13 @@
},
"type": "array"
},
"PostCompact": {
"default": [],
"items": {
"$ref": "#/definitions/MatcherGroup"
},
"type": "array"
},
"PostToolUse": {
"default": [],
"items": {
@@ -1040,6 +1047,13 @@
},
"type": "array"
},
"PreCompact": {
"default": [],
"items": {
"$ref": "#/definitions/MatcherGroup"
},
"type": "array"
},
"PreToolUse": {
"default": [],
"items": {
+1
View File
@@ -83,6 +83,7 @@ pub(crate) async fn run_codex_thread_interactive(
skills_manager: Arc::clone(&parent_session.services.skills_manager),
plugins_manager: Arc::clone(&parent_session.services.plugins_manager),
mcp_manager: Arc::clone(&parent_session.services.mcp_manager),
skills_watcher: Arc::clone(&parent_session.services.skills_watcher),
conversation_history: initial_history.unwrap_or(InitialHistory::New),
session_source: SessionSource::SubAgent(subagent_source.clone()),
thread_source: Some(ThreadSource::Subagent),
+4 -5
View File
@@ -1,5 +1,6 @@
use crate::agent::AgentStatus;
use crate::config::ConstraintResult;
use crate::file_watcher::WatchRegistration;
use crate::goals::ExternalGoalSet;
use crate::goals::GoalRuntimeEvent;
use crate::session::Codex;
@@ -30,7 +31,6 @@ use codex_protocol::protocol::Submission;
use codex_protocol::protocol::ThreadMemoryMode;
use codex_protocol::protocol::ThreadSource;
use codex_protocol::protocol::TokenUsageInfo;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::protocol::W3cTraceContext;
use codex_protocol::user_input::UserInput;
use codex_thread_store::StoredThread;
@@ -101,6 +101,7 @@ pub struct CodexThread {
session_configured: SessionConfiguredEvent,
rollout_path: Option<PathBuf>,
out_of_band_elicitation_count: Mutex<u64>,
_watch_registration: WatchRegistration,
}
/// Conduit for the bidirectional stream of messages that compose a thread
@@ -111,6 +112,7 @@ impl CodexThread {
session_configured: SessionConfiguredEvent,
rollout_path: Option<PathBuf>,
session_source: SessionSource,
watch_registration: WatchRegistration,
) -> Self {
Self {
codex,
@@ -118,6 +120,7 @@ impl CodexThread {
session_configured,
rollout_path,
out_of_band_elicitation_count: Mutex::new(0),
_watch_registration: watch_registration,
}
}
@@ -461,10 +464,6 @@ impl CodexThread {
self.codex.session.get_config().await
}
pub async fn environment_selections(&self) -> Vec<TurnEnvironmentSelection> {
self.codex.thread_environment_selections().await
}
pub async fn read_mcp_resource(
&self,
server: &str,
+30 -11
View File
@@ -4,6 +4,10 @@ use std::time::Instant;
use crate::Prompt;
use crate::client::ModelClientSession;
use crate::client_common::ResponseEvent;
use crate::hook_runtime::PostCompactHookOutcome;
use crate::hook_runtime::PreCompactHookOutcome;
use crate::hook_runtime::run_post_compact_hooks;
use crate::hook_runtime::run_pre_compact_hooks;
#[cfg(test)]
use crate::session::PreviousTurnSettings;
use crate::session::session::Session;
@@ -110,7 +114,8 @@ pub(crate) async fn run_compact_task(
CompactionReason::UserRequested,
CompactionPhase::StandaloneTurn,
)
.await
.await?;
Ok(())
}
async fn run_compact_task_inner(
@@ -131,6 +136,17 @@ async fn run_compact_task_inner(
phase,
)
.await;
let pre_compact_outcome = run_pre_compact_hooks(&sess, &turn_context, trigger).await;
match pre_compact_outcome {
PreCompactHookOutcome::Continue => {}
PreCompactHookOutcome::Stopped { reason } => {
let error = reason.unwrap_or_else(|| "PreCompact hook stopped execution".to_string());
attempt
.track(sess.as_ref(), CompactionStatus::Interrupted, Some(error))
.await;
return Err(CodexErr::TurnAborted);
}
}
let result = run_compact_task_inner_impl(
Arc::clone(&sess),
Arc::clone(&turn_context),
@@ -138,14 +154,17 @@ async fn run_compact_task_inner(
initial_context_injection,
)
.await;
attempt
.track(
sess.as_ref(),
compaction_status_from_result(&result),
result.as_ref().err().map(ToString::to_string),
)
.await;
result
let status = compaction_status_from_result(&result);
let error = result.as_ref().err().map(ToString::to_string);
if result.is_ok() {
let post_compact_outcome = run_post_compact_hooks(&sess, &turn_context, trigger).await;
if let PostCompactHookOutcome::Stopped = post_compact_outcome {
attempt.track(sess.as_ref(), status, error).await;
return Err(CodexErr::TurnAborted);
}
}
attempt.track(sess.as_ref(), status, error).await;
result.map(|_| ())
}
async fn run_compact_task_inner_impl(
@@ -153,7 +172,7 @@ async fn run_compact_task_inner_impl(
turn_context: Arc<TurnContext>,
input: Vec<UserInput>,
initial_context_injection: InitialContextInjection,
) -> CodexResult<()> {
) -> CodexResult<String> {
let compaction_item = TurnItem::ContextCompaction(ContextCompactionItem::new());
sess.emit_turn_item_started(&turn_context, &compaction_item)
.await;
@@ -272,7 +291,7 @@ async fn run_compact_task_inner_impl(
message: "Heads up: Long threads and multiple compactions can cause the model to be less accurate. Start a new thread when possible to keep threads small and targeted.".to_string(),
});
sess.send_event(&turn_context, warning).await;
Ok(())
Ok(summary_suffix)
}
pub(crate) struct CompactionAnalyticsAttempt {
+31 -8
View File
@@ -11,6 +11,10 @@ use crate::context_manager::ContextManager;
use crate::context_manager::TotalTokenUsageBreakdown;
use crate::context_manager::estimate_response_item_model_visible_bytes;
use crate::context_manager::is_codex_generated_item;
use crate::hook_runtime::PostCompactHookOutcome;
use crate::hook_runtime::PreCompactHookOutcome;
use crate::hook_runtime::run_post_compact_hooks;
use crate::hook_runtime::run_pre_compact_hooks;
use crate::session::session::Session;
use crate::session::turn::built_tools;
use crate::session::turn_context::TurnContext;
@@ -72,7 +76,8 @@ pub(crate) async fn run_remote_compact_task(
CompactionReason::UserRequested,
CompactionPhase::StandaloneTurn,
)
.await
.await?;
Ok(())
}
async fn run_remote_compact_task_inner(
@@ -92,15 +97,33 @@ async fn run_remote_compact_task_inner(
phase,
)
.await;
let pre_compact_outcome = run_pre_compact_hooks(sess, turn_context, trigger).await;
match pre_compact_outcome {
PreCompactHookOutcome::Continue => {}
PreCompactHookOutcome::Stopped { reason } => {
let error = reason.unwrap_or_else(|| "PreCompact hook stopped execution".to_string());
attempt
.track(
sess.as_ref(),
codex_analytics::CompactionStatus::Interrupted,
Some(error),
)
.await;
return Err(CodexErr::TurnAborted);
}
}
let result =
run_remote_compact_task_inner_impl(sess, turn_context, initial_context_injection).await;
attempt
.track(
sess.as_ref(),
compaction_status_from_result(&result),
result.as_ref().err().map(ToString::to_string),
)
.await;
let status = compaction_status_from_result(&result);
let error = result.as_ref().err().map(ToString::to_string);
if result.is_ok() {
let post_compact_outcome = run_post_compact_hooks(sess, turn_context, trigger).await;
if let PostCompactHookOutcome::Stopped = post_compact_outcome {
attempt.track(sess.as_ref(), status, error).await;
return Err(CodexErr::TurnAborted);
}
}
attempt.track(sess.as_ref(), status, error.clone()).await;
if let Err(err) = result {
let event = EventMsg::Error(
err.to_error_event(Some("Error running remote compact task".to_string())),
+72
View File
@@ -2,6 +2,7 @@ use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use codex_analytics::CompactionTrigger;
use codex_analytics::HookRunFact;
use codex_analytics::build_track_events_context;
use codex_hooks::PermissionRequestDecision;
@@ -255,6 +256,68 @@ pub(crate) async fn run_post_tool_use_hooks(
outcome
}
pub(crate) async fn run_pre_compact_hooks(
sess: &Arc<Session>,
turn_context: &Arc<TurnContext>,
trigger: CompactionTrigger,
) -> PreCompactHookOutcome {
let request = codex_hooks::PreCompactRequest {
session_id: sess.conversation_id,
turn_id: turn_context.sub_id.clone(),
cwd: turn_context.cwd.clone(),
transcript_path: sess.hook_transcript_path().await,
model: turn_context.model_info.slug.clone(),
trigger: compaction_trigger_label(trigger).to_string(),
};
let preview_runs = sess.hooks().preview_pre_compact(&request);
emit_hook_started_events(sess, turn_context, preview_runs).await;
let outcome = sess.hooks().run_pre_compact(request).await;
emit_hook_completed_events(sess, turn_context, outcome.hook_events).await;
if outcome.should_stop {
PreCompactHookOutcome::Stopped {
reason: outcome.stop_reason,
}
} else {
PreCompactHookOutcome::Continue
}
}
pub(crate) enum PreCompactHookOutcome {
Continue,
Stopped { reason: Option<String> },
}
pub(crate) enum PostCompactHookOutcome {
Continue,
Stopped,
}
pub(crate) async fn run_post_compact_hooks(
sess: &Arc<Session>,
turn_context: &Arc<TurnContext>,
trigger: CompactionTrigger,
) -> PostCompactHookOutcome {
let request = codex_hooks::PostCompactRequest {
session_id: sess.conversation_id,
turn_id: turn_context.sub_id.clone(),
cwd: turn_context.cwd.clone(),
transcript_path: sess.hook_transcript_path().await,
model: turn_context.model_info.slug.clone(),
trigger: compaction_trigger_label(trigger).to_string(),
};
let preview_runs = sess.hooks().preview_post_compact(&request);
emit_hook_started_events(sess, turn_context, preview_runs).await;
let outcome = sess.hooks().run_post_compact(request).await;
emit_hook_completed_events(sess, turn_context, outcome.hook_events).await;
if outcome.should_stop {
PostCompactHookOutcome::Stopped
} else {
PostCompactHookOutcome::Continue
}
}
pub(crate) async fn run_user_prompt_submit_hooks(
sess: &Arc<Session>,
turn_context: &Arc<TurnContext>,
@@ -469,6 +532,8 @@ fn hook_run_metric_tags(run: &HookRunSummary) -> [(&'static str, &'static str);
HookEventName::PreToolUse => "PreToolUse",
HookEventName::PermissionRequest => "PermissionRequest",
HookEventName::PostToolUse => "PostToolUse",
HookEventName::PreCompact => "PreCompact",
HookEventName::PostCompact => "PostCompact",
HookEventName::SessionStart => "SessionStart",
HookEventName::UserPromptSubmit => "UserPromptSubmit",
HookEventName::Stop => "Stop",
@@ -511,6 +576,13 @@ fn hook_permission_mode(turn_context: &TurnContext) -> String {
.to_string()
}
fn compaction_trigger_label(value: CompactionTrigger) -> &'static str {
match value {
CompactionTrigger::Manual => "manual",
CompactionTrigger::Auto => "auto",
}
}
#[cfg(test)]
mod tests {
use codex_protocol::models::ContentItem;
+1
View File
@@ -99,6 +99,7 @@ pub(crate) use skills::manager;
pub(crate) use skills::maybe_emit_implicit_skill_invocation;
pub(crate) use skills::resolve_skill_dependencies_for_turn;
pub(crate) use skills::skills_load_input_from_config;
mod skills_watcher;
mod stream_events_utils;
pub mod test_support;
mod unified_exec;
+23 -11
View File
@@ -19,7 +19,7 @@ use tracing_test::internal::MockWriter;
async fn list_tool_suggest_discoverable_plugins_returns_uninstalled_curated_plugins() {
let codex_home = tempdir().expect("tempdir should succeed");
let curated_root = curated_plugins_repo_path(codex_home.path());
write_openai_curated_marketplace(&curated_root, &["sample", "slack"]);
write_openai_curated_marketplace(&curated_root, &["sample", "slack", "openai-developers"]);
write_plugins_feature_config(codex_home.path());
let config = load_plugins_config(codex_home.path()).await;
@@ -29,16 +29,28 @@ async fn list_tool_suggest_discoverable_plugins_returns_uninstalled_curated_plug
assert_eq!(
discoverable_plugins,
vec![DiscoverablePluginInfo {
id: "slack@openai-curated".to_string(),
name: "slack".to_string(),
description: Some(
"Plugin that includes skills, MCP servers, and app connectors".to_string(),
),
has_skills: true,
mcp_server_names: vec!["sample-docs".to_string()],
app_connector_ids: vec!["connector_calendar".to_string()],
}]
vec![
DiscoverablePluginInfo {
id: "openai-developers@openai-curated".to_string(),
name: "openai-developers".to_string(),
description: Some(
"Plugin that includes skills, MCP servers, and app connectors".to_string(),
),
has_skills: true,
mcp_server_names: vec!["sample-docs".to_string()],
app_connector_ids: vec!["connector_calendar".to_string()],
},
DiscoverablePluginInfo {
id: "slack@openai-curated".to_string(),
name: "slack".to_string(),
description: Some(
"Plugin that includes skills, MCP servers, and app connectors".to_string(),
),
has_skills: true,
mcp_server_names: vec!["sample-docs".to_string()],
app_connector_ids: vec!["connector_calendar".to_string()],
},
]
);
}
+28 -6
View File
@@ -113,7 +113,6 @@ use codex_protocol::protocol::ThreadSource;
use codex_protocol::protocol::TurnAbortReason;
use codex_protocol::protocol::TurnContextItem;
use codex_protocol::protocol::TurnContextNetworkItem;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::protocol::W3cTraceContext;
use codex_protocol::request_permissions::PermissionGrantScope;
use codex_protocol::request_permissions::RequestPermissionProfile;
@@ -282,6 +281,8 @@ use crate::rollout::map_session_init_error;
use crate::session_startup_prewarm::SessionStartupPrewarmHandle;
use crate::shell;
use crate::shell_snapshot::ShellSnapshot;
use crate::skills_watcher::SkillsWatcher;
use crate::skills_watcher::SkillsWatcherEvent;
use crate::state::ActiveTurn;
use crate::state::MailboxDeliveryPhase;
use crate::state::PendingRequestPermissions;
@@ -389,6 +390,7 @@ pub(crate) struct CodexSpawnArgs {
pub(crate) skills_manager: Arc<SkillsManager>,
pub(crate) plugins_manager: Arc<PluginsManager>,
pub(crate) mcp_manager: Arc<McpManager>,
pub(crate) skills_watcher: Arc<SkillsWatcher>,
pub(crate) conversation_history: InitialHistory,
pub(crate) session_source: SessionSource,
pub(crate) thread_source: Option<ThreadSource>,
@@ -452,6 +454,7 @@ impl Codex {
skills_manager,
plugins_manager,
mcp_manager,
skills_watcher,
conversation_history,
session_source,
thread_source,
@@ -639,6 +642,7 @@ impl Codex {
skills_manager,
plugins_manager,
mcp_manager.clone(),
skills_watcher,
agent_control,
environment_manager,
analytics_events_client,
@@ -773,11 +777,6 @@ impl Codex {
state.session_configuration.thread_config_snapshot()
}
pub(crate) async fn thread_environment_selections(&self) -> Vec<TurnEnvironmentSelection> {
let state = self.session.state.lock().await;
state.session_configuration.environments.clone()
}
pub(crate) fn state_db(&self) -> Option<state_db::StateDbHandle> {
self.session.state_db()
}
@@ -1002,6 +1001,29 @@ impl Session {
self.out_of_band_elicitation_paused.send_replace(paused);
}
fn start_skills_watcher_listener(self: &Arc<Self>) {
let mut rx = self.services.skills_watcher.subscribe();
let weak_sess = Arc::downgrade(self);
tokio::spawn(async move {
loop {
match rx.recv().await {
Ok(SkillsWatcherEvent::SkillsChanged { .. }) => {
let Some(sess) = weak_sess.upgrade() else {
break;
};
let event = Event {
id: sess.next_internal_sub_id(),
msg: EventMsg::SkillsUpdateAvailable,
};
sess.send_event_raw(event).await;
}
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
}
}
});
}
pub(crate) fn get_tx_event(&self) -> Sender<Event> {
self.tx_event.clone()
}
+4
View File
@@ -364,6 +364,7 @@ impl Session {
skills_manager: Arc<SkillsManager>,
plugins_manager: Arc<PluginsManager>,
mcp_manager: Arc<McpManager>,
skills_watcher: Arc<SkillsWatcher>,
agent_control: AgentControl,
environment_manager: Arc<EnvironmentManager>,
analytics_events_client: Option<AnalyticsEventsClient>,
@@ -830,6 +831,7 @@ impl Session {
skills_manager,
plugins_manager: Arc::clone(&plugins_manager),
mcp_manager: Arc::clone(&mcp_manager),
skills_watcher,
agent_control,
network_proxy,
network_approval: Arc::clone(&network_approval),
@@ -916,6 +918,8 @@ impl Session {
sess.send_event_raw(event).await;
}
// Start the watcher after SessionConfigured so it cannot emit earlier events.
sess.start_skills_watcher_listener();
let mut required_mcp_servers: Vec<String> = mcp_servers
.iter()
.filter(|(_, server)| server.enabled && server.required)
+7
View File
@@ -3594,6 +3594,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() {
skills_manager,
plugins_manager,
mcp_manager,
Arc::new(SkillsWatcher::noop()),
AgentControl::default(),
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
/*analytics_events_client*/ None,
@@ -3710,6 +3711,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
.expect("create environment"),
);
let skills_watcher = Arc::new(SkillsWatcher::noop());
let services = SessionServices {
mcp_connection_manager: Arc::new(RwLock::new(McpConnectionManager::new_uninitialized(
&config.permissions.approval_policy,
@@ -3745,6 +3747,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
skills_manager,
plugins_manager,
mcp_manager,
skills_watcher,
agent_control,
network_proxy: None,
network_approval: Arc::clone(&network_approval),
@@ -3932,6 +3935,7 @@ async fn make_session_with_config_and_rx(
skills_manager,
plugins_manager,
mcp_manager,
Arc::new(SkillsWatcher::noop()),
AgentControl::default(),
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
/*analytics_events_client*/ None,
@@ -4039,6 +4043,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx(
skills_manager,
plugins_manager,
mcp_manager,
Arc::new(SkillsWatcher::noop()),
agent_control,
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
/*analytics_events_client*/ None,
@@ -5397,6 +5402,7 @@ where
)
.await
.expect("state db should initialize");
let skills_watcher = Arc::new(SkillsWatcher::noop());
let services = SessionServices {
mcp_connection_manager: Arc::new(RwLock::new(McpConnectionManager::new_uninitialized(
&config.permissions.approval_policy,
@@ -5432,6 +5438,7 @@ where
skills_manager,
plugins_manager,
mcp_manager,
skills_watcher,
agent_control,
network_proxy: None,
network_approval: Arc::clone(&network_approval),
@@ -728,6 +728,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
/*bundled_skills_enabled*/ true,
));
let mcp_manager = Arc::new(McpManager::new(Arc::clone(&plugins_manager)));
let skills_watcher = Arc::new(SkillsWatcher::noop());
let thread_store = Arc::new(codex_thread_store::LocalThreadStore::new(
codex_thread_store::LocalThreadStoreConfig::from_config(&config),
codex_state::StateRuntime::init(
@@ -747,6 +748,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
skills_manager,
plugins_manager,
mcp_manager,
skills_watcher,
conversation_history: InitialHistory::New,
session_source: SessionSource::SubAgent(SubAgentSource::Other(
GUARDIAN_REVIEWER_NAME.to_string(),
+1
View File
@@ -1511,6 +1511,7 @@ pub(super) fn realtime_text_for_event(msg: &EventMsg) -> Option<String> {
| EventMsg::StreamError(_)
| EventMsg::TurnDiff(_)
| EventMsg::RealtimeConversationListVoicesResponse(_)
| EventMsg::SkillsUpdateAvailable
| EventMsg::PlanUpdate(_)
| EventMsg::TurnAborted(_)
| EventMsg::ShutdownComplete
+125
View File
@@ -0,0 +1,125 @@
//! Skills-specific watcher built on top of the generic [`FileWatcher`].
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::runtime::Handle;
use tokio::sync::broadcast;
use tracing::warn;
use crate::SkillsManager;
use crate::config::Config;
use crate::file_watcher::FileWatcher;
use crate::file_watcher::FileWatcherSubscriber;
use crate::file_watcher::Receiver;
use crate::file_watcher::ThrottledWatchReceiver;
use crate::file_watcher::WatchPath;
use crate::file_watcher::WatchRegistration;
use crate::skills_load_input_from_config;
use codex_core_plugins::PluginsManager;
#[cfg(not(test))]
const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_secs(10);
#[cfg(test)]
const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_millis(50);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkillsWatcherEvent {
SkillsChanged { paths: Vec<PathBuf> },
}
pub(crate) struct SkillsWatcher {
subscriber: FileWatcherSubscriber,
tx: broadcast::Sender<SkillsWatcherEvent>,
}
impl SkillsWatcher {
pub(crate) fn new(file_watcher: &Arc<FileWatcher>) -> Self {
let (subscriber, rx) = file_watcher.add_subscriber();
let (tx, _) = broadcast::channel(128);
let skills_watcher = Self {
subscriber,
tx: tx.clone(),
};
Self::spawn_event_loop(rx, tx);
skills_watcher
}
pub(crate) fn noop() -> Self {
Self::new(&Arc::new(FileWatcher::noop()))
}
pub(crate) fn subscribe(&self) -> broadcast::Receiver<SkillsWatcherEvent> {
self.tx.subscribe()
}
pub(crate) async fn register_config(
&self,
config: &Config,
skills_manager: &SkillsManager,
plugins_manager: &PluginsManager,
fs: Option<Arc<dyn codex_exec_server::ExecutorFileSystem>>,
) -> WatchRegistration {
let plugins_input = config.plugins_config_input();
let plugin_outcome = plugins_manager.plugins_for_config(&plugins_input).await;
let effective_skill_roots = plugin_outcome.effective_plugin_skill_roots();
let skills_input = skills_load_input_from_config(config, effective_skill_roots);
let roots = skills_manager
.skill_roots_for_config(&skills_input, fs)
.await
.into_iter()
.map(|root| WatchPath {
path: root.path.into_path_buf(),
recursive: true,
})
.collect();
self.subscriber.register_paths(roots)
}
fn spawn_event_loop(rx: Receiver, tx: broadcast::Sender<SkillsWatcherEvent>) {
let mut rx = ThrottledWatchReceiver::new(rx, WATCHER_THROTTLE_INTERVAL);
if let Ok(handle) = Handle::try_current() {
handle.spawn(async move {
while let Some(event) = rx.recv().await {
let _ = tx.send(SkillsWatcherEvent::SkillsChanged { paths: event.paths });
}
});
} else {
warn!("skills watcher listener skipped: no Tokio runtime available");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use tokio::time::Duration;
use tokio::time::timeout;
#[tokio::test]
async fn forwards_file_watcher_events() {
let file_watcher = Arc::new(FileWatcher::noop());
let skills_watcher = SkillsWatcher::new(&file_watcher);
let mut rx = skills_watcher.subscribe();
let _registration = skills_watcher
.subscriber
.register_path(PathBuf::from("/tmp/skill"), /*recursive*/ true);
file_watcher
.send_paths_for_test(vec![PathBuf::from("/tmp/skill/SKILL.md")])
.await;
let event = timeout(Duration::from_secs(2), rx.recv())
.await
.expect("skills watcher event")
.expect("broadcast recv");
assert_eq!(
event,
SkillsWatcherEvent::SkillsChanged {
paths: vec![PathBuf::from("/tmp/skill/SKILL.md")],
}
);
}
}
+2
View File
@@ -9,6 +9,7 @@ use crate::exec_policy::ExecPolicyManager;
use crate::guardian::GuardianRejection;
use crate::guardian::GuardianRejectionCircuitBreaker;
use crate::mcp::McpManager;
use crate::skills_watcher::SkillsWatcher;
use crate::tools::code_mode::CodeModeService;
use crate::tools::network_approval::NetworkApprovalService;
use crate::tools::sandboxing::ApprovalStore;
@@ -58,6 +59,7 @@ pub(crate) struct SessionServices {
pub(crate) skills_manager: Arc<SkillsManager>,
pub(crate) plugins_manager: Arc<PluginsManager>,
pub(crate) mcp_manager: Arc<McpManager>,
pub(crate) skills_watcher: Arc<SkillsWatcher>,
pub(crate) agent_control: AgentControl,
pub(crate) network_proxy: Option<StartedNetworkProxy>,
pub(crate) network_approval: Arc<NetworkApprovalService>,
+68 -1
View File
@@ -5,6 +5,7 @@ use crate::config::Config;
use crate::config::ThreadStoreConfig;
use crate::environment_selection::default_thread_environment_selections;
use crate::environment_selection::resolve_environment_selections;
use crate::file_watcher::FileWatcher;
use crate::mcp::McpManager;
use crate::resolve_installation_id;
use crate::rollout::RolloutRecorder;
@@ -14,6 +15,8 @@ use crate::session::CodexSpawnArgs;
use crate::session::CodexSpawnOk;
use crate::session::INITIAL_SUBMIT_ID;
use crate::shell_snapshot::ShellSnapshot;
use crate::skills_watcher::SkillsWatcher;
use crate::skills_watcher::SkillsWatcherEvent;
use crate::tasks::InterruptedTurnHistoryMarker;
use crate::tasks::interrupted_turn_history_marker;
use codex_agent_graph_store::AgentGraphStore;
@@ -70,6 +73,8 @@ use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tokio::runtime::Handle;
use tokio::runtime::RuntimeFlavor;
use tokio::sync::RwLock;
use tokio::sync::broadcast;
use tracing::warn;
@@ -103,6 +108,47 @@ impl Drop for TempCodexHomeGuard {
}
}
fn build_skills_watcher(skills_manager: Arc<SkillsManager>) -> Arc<SkillsWatcher> {
if should_use_test_thread_manager_behavior()
&& let Ok(handle) = Handle::try_current()
&& handle.runtime_flavor() == RuntimeFlavor::CurrentThread
{
// The real watcher spins background tasks that can starve the
// current-thread test runtime and cause event waits to time out.
warn!("using noop skills watcher under current-thread test runtime");
return Arc::new(SkillsWatcher::noop());
}
let file_watcher = match FileWatcher::new() {
Ok(file_watcher) => Arc::new(file_watcher),
Err(err) => {
warn!("failed to initialize file watcher: {err}");
Arc::new(FileWatcher::noop())
}
};
let skills_watcher = Arc::new(SkillsWatcher::new(&file_watcher));
let mut rx = skills_watcher.subscribe();
let skills_manager = Arc::clone(&skills_manager);
if let Ok(handle) = Handle::try_current() {
handle.spawn(async move {
loop {
match rx.recv().await {
Ok(SkillsWatcherEvent::SkillsChanged { .. }) => {
skills_manager.clear_cache();
}
Err(broadcast::error::RecvError::Closed) => break,
Err(broadcast::error::RecvError::Lagged(_)) => continue,
}
}
});
} else {
warn!("skills watcher listener skipped: no Tokio runtime available");
}
skills_watcher
}
/// Represents a newly created Codex thread (formerly called a conversation), including the first event
/// (which is [`EventMsg::SessionConfigured`]).
pub struct NewThread {
@@ -203,6 +249,7 @@ pub(crate) struct ThreadManagerState {
skills_manager: Arc<SkillsManager>,
plugins_manager: Arc<PluginsManager>,
mcp_manager: Arc<McpManager>,
skills_watcher: Arc<SkillsWatcher>,
thread_store: Arc<dyn ThreadStore>,
state_db: StateDbHandle,
agent_graph_store: Arc<dyn AgentGraphStore>,
@@ -286,6 +333,7 @@ impl ThreadManager {
config.bundled_skills_enabled(),
restriction_product,
));
let skills_watcher = build_skills_watcher(Arc::clone(&skills_manager));
Self {
state: Arc::new(ThreadManagerState {
threads: Arc::new(RwLock::new(HashMap::new())),
@@ -295,6 +343,7 @@ impl ThreadManager {
skills_manager,
plugins_manager,
mcp_manager,
skills_watcher,
thread_store,
state_db,
agent_graph_store,
@@ -403,6 +452,7 @@ impl ThreadManager {
/*bundled_skills_enabled*/ true,
restriction_product,
));
let skills_watcher = build_skills_watcher(Arc::clone(&skills_manager));
// This test constructor has no Config input. Tests that need a non-local
// process store should construct ThreadManager::new with an explicit store.
let thread_store: Arc<dyn ThreadStore> = Arc::new(LocalThreadStore::new(
@@ -423,6 +473,7 @@ impl ThreadManager {
skills_manager,
plugins_manager,
mcp_manager,
skills_watcher,
thread_store,
state_db,
agent_graph_store,
@@ -1148,6 +1199,19 @@ impl ThreadManagerState {
}
let environment_selections =
resolve_environment_selections(self.environment_manager.as_ref(), &environments)?;
let watch_registration = match environment_selections.primary() {
Some(turn_environment) if !turn_environment.environment.is_remote() => {
self.skills_watcher
.register_config(
&config,
self.skills_manager.as_ref(),
self.plugins_manager.as_ref(),
Some(turn_environment.environment.get_filesystem()),
)
.await
}
Some(_) | None => crate::file_watcher::WatchRegistration::default(),
};
let parent_rollout_thread_trace = self
.parent_rollout_thread_trace_for_source(&session_source, &initial_history)
.await;
@@ -1163,6 +1227,7 @@ impl ThreadManagerState {
skills_manager: Arc::clone(&self.skills_manager),
plugins_manager: Arc::clone(&self.plugins_manager),
mcp_manager: Arc::clone(&self.mcp_manager),
skills_watcher: Arc::clone(&self.skills_watcher),
conversation_history: initial_history,
session_source,
thread_source,
@@ -1182,7 +1247,7 @@ impl ThreadManagerState {
})
.await?;
let new_thread = self
.finalize_thread_spawn(codex, thread_id, tracked_session_source)
.finalize_thread_spawn(codex, thread_id, tracked_session_source, watch_registration)
.await?;
if is_resumed_thread
&& let Err(err) = new_thread.thread.apply_goal_resume_runtime_effects().await
@@ -1197,6 +1262,7 @@ impl ThreadManagerState {
codex: Codex,
thread_id: ThreadId,
session_source: SessionSource,
watch_registration: crate::file_watcher::WatchRegistration,
) -> CodexResult<NewThread> {
let event = codex.next_event().await?;
let session_configured = match event {
@@ -1217,6 +1283,7 @@ impl ThreadManagerState {
session_configured.clone(),
session_configured.rollout_path.clone(),
session_source,
watch_registration,
));
e.insert(thread.clone());
return Ok(NewThread {
+18 -4
View File
@@ -522,10 +522,6 @@ impl ToolRegistryBuilder {
}
}
pub fn push_spec(&mut self, spec: ToolSpec) {
self.push_spec_with_parallel_support(spec, /*supports_parallel_tool_calls*/ false);
}
pub fn push_spec_with_parallel_support(
&mut self,
spec: ToolSpec,
@@ -535,6 +531,20 @@ impl ToolRegistryBuilder {
.push(ConfiguredToolSpec::new(spec, supports_parallel_tool_calls));
}
pub(crate) fn push_spec(
&mut self,
spec: ToolSpec,
supports_parallel_tool_calls: bool,
code_mode_enabled: bool,
) {
let spec = if code_mode_enabled {
codex_tools::augment_tool_spec_for_code_mode(spec)
} else {
spec
};
self.push_spec_with_parallel_support(spec, supports_parallel_tool_calls);
}
pub fn register_handler<H>(&mut self, handler: Arc<H>)
where
H: ToolHandler + 'static,
@@ -547,6 +557,10 @@ impl ToolRegistryBuilder {
}
}
pub(crate) fn specs(&self) -> &[ConfiguredToolSpec] {
&self.specs
}
pub fn build(self) -> (Vec<ConfiguredToolSpec>, ToolRegistry) {
let registry = ToolRegistry::new(self.handlers);
(self.specs, registry)
+27 -207
View File
@@ -1,18 +1,15 @@
use crate::shell::Shell;
use crate::shell::ShellType;
use crate::tools::handlers::agent_jobs::ReportAgentJobResultHandler;
use crate::tools::handlers::agent_jobs::SpawnAgentsOnCsvHandler;
use crate::tools::handlers::multi_agents_common::DEFAULT_WAIT_TIMEOUT_MS;
use crate::tools::handlers::multi_agents_common::MAX_WAIT_TIMEOUT_MS;
use crate::tools::handlers::multi_agents_common::MIN_WAIT_TIMEOUT_MS;
use crate::tools::handlers::multi_agents_spec::WaitAgentTimeoutOptions;
use crate::tools::registry::ToolRegistryBuilder;
use crate::tools::spec_plan::build_tool_registry_plan;
use crate::tools::spec_plan_types::ToolHandlerKind;
use crate::tools::spec_plan::build_tool_registry_builder;
use crate::tools::spec_plan_types::ToolNamespace;
use crate::tools::spec_plan_types::ToolRegistryPlanDeferredTool;
use crate::tools::spec_plan_types::ToolRegistryPlanMcpTool;
use crate::tools::spec_plan_types::ToolRegistryPlanParams;
use crate::tools::spec_plan_types::ToolRegistryBuildDeferredTool;
use crate::tools::spec_plan_types::ToolRegistryBuildMcpTool;
use crate::tools::spec_plan_types::ToolRegistryBuildParams;
use codex_mcp::ToolInfo;
use codex_protocol::dynamic_tools::DynamicToolSpec;
use codex_tools::AdditionalProperties;
@@ -22,7 +19,6 @@ use codex_tools::ResponsesApiTool;
use codex_tools::ToolName;
use codex_tools::ToolUserShellType;
use codex_tools::ToolsConfig;
use codex_tools::augment_tool_spec_for_code_mode;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
@@ -38,7 +34,7 @@ pub(crate) fn tool_user_shell_type(user_shell: &Shell) -> ToolUserShellType {
}
struct McpToolPlanInputs<'a> {
mcp_tools: Vec<ToolRegistryPlanMcpTool<'a>>,
mcp_tools: Vec<ToolRegistryBuildMcpTool<'a>>,
tool_namespaces: HashMap<String, ToolNamespace>,
}
@@ -46,7 +42,7 @@ fn map_mcp_tools_for_plan(mcp_tools: &HashMap<String, ToolInfo>) -> McpToolPlanI
McpToolPlanInputs {
mcp_tools: mcp_tools
.values()
.map(|tool| ToolRegistryPlanMcpTool {
.map(|tool| ToolRegistryBuildMcpTool {
name: tool.canonical_tool_name(),
tool: &tool.tool,
})
@@ -74,51 +70,15 @@ pub(crate) fn build_specs_with_discoverable_tools(
discoverable_tools: Option<Vec<DiscoverableTool>>,
dynamic_tools: &[DynamicToolSpec],
) -> ToolRegistryBuilder {
use crate::tools::handlers::ApplyPatchHandler;
use crate::tools::handlers::CodeModeExecuteHandler;
use crate::tools::handlers::CodeModeWaitHandler;
use crate::tools::handlers::ContainerExecHandler;
use crate::tools::handlers::CreateGoalHandler;
use crate::tools::handlers::DynamicToolHandler;
use crate::tools::handlers::ExecCommandHandler;
use crate::tools::handlers::GetGoalHandler;
use crate::tools::handlers::ListMcpResourceTemplatesHandler;
use crate::tools::handlers::ListMcpResourcesHandler;
use crate::tools::handlers::LocalShellHandler;
use crate::tools::handlers::McpHandler;
use crate::tools::handlers::PlanHandler;
use crate::tools::handlers::ReadMcpResourceHandler;
use crate::tools::handlers::RequestPermissionsHandler;
use crate::tools::handlers::RequestPluginInstallHandler;
use crate::tools::handlers::RequestUserInputHandler;
use crate::tools::handlers::ShellCommandHandler;
use crate::tools::handlers::ShellHandler;
use crate::tools::handlers::TestSyncHandler;
use crate::tools::handlers::ToolSearchHandler;
use crate::tools::handlers::UnavailableToolHandler;
use crate::tools::handlers::UpdateGoalHandler;
use crate::tools::handlers::ViewImageHandler;
use crate::tools::handlers::WriteStdinHandler;
use crate::tools::handlers::multi_agents::CloseAgentHandler;
use crate::tools::handlers::multi_agents::ResumeAgentHandler;
use crate::tools::handlers::multi_agents::SendInputHandler;
use crate::tools::handlers::multi_agents::SpawnAgentHandler;
use crate::tools::handlers::multi_agents::WaitAgentHandler;
use crate::tools::handlers::multi_agents_v2::CloseAgentHandler as CloseAgentHandlerV2;
use crate::tools::handlers::multi_agents_v2::FollowupTaskHandler as FollowupTaskHandlerV2;
use crate::tools::handlers::multi_agents_v2::ListAgentsHandler as ListAgentsHandlerV2;
use crate::tools::handlers::multi_agents_v2::SendMessageHandler as SendMessageHandlerV2;
use crate::tools::handlers::multi_agents_v2::SpawnAgentHandler as SpawnAgentHandlerV2;
use crate::tools::handlers::multi_agents_v2::WaitAgentHandler as WaitAgentHandlerV2;
use crate::tools::handlers::unavailable_tool_message;
use crate::tools::tool_search_entry::build_tool_search_entries_for_config;
let mut builder = ToolRegistryBuilder::new();
let mcp_tool_plan_inputs = mcp_tools.as_ref().map(map_mcp_tools_for_plan);
let deferred_mcp_tool_sources = deferred_mcp_tools.as_ref().map(|tools| {
tools
.values()
.map(|tool| ToolRegistryPlanDeferredTool {
.map(|tool| ToolRegistryBuildDeferredTool {
name: tool.canonical_tool_name(),
server_name: tool.server_name.as_str(),
connector_name: tool.connector_name.as_deref(),
@@ -138,9 +98,19 @@ pub(crate) fn build_specs_with_discoverable_tools(
};
let default_wait_timeout_ms =
DEFAULT_WAIT_TIMEOUT_MS.clamp(min_wait_timeout_ms, MAX_WAIT_TIMEOUT_MS);
let plan = build_tool_registry_plan(
let deferred_dynamic_tools = dynamic_tools
.iter()
.filter(|tool| tool.defer_loading && (config.namespace_tools || tool.namespace.is_none()))
.cloned()
.collect::<Vec<_>>();
let tool_search_entries = build_tool_search_entries_for_config(
config,
ToolRegistryPlanParams {
deferred_mcp_tools.as_ref(),
&deferred_dynamic_tools,
);
let mut builder = build_tool_registry_builder(
config,
ToolRegistryBuildParams {
mcp_tools: mcp_tool_plan_inputs
.as_ref()
.map(|inputs| inputs.mcp_tools.as_slice()),
@@ -156,164 +126,15 @@ pub(crate) fn build_specs_with_discoverable_tools(
min_timeout_ms: min_wait_timeout_ms,
max_timeout_ms: MAX_WAIT_TIMEOUT_MS,
},
tool_search_entries: &tool_search_entries,
},
);
let deferred_dynamic_tools = dynamic_tools
.iter()
.filter(|tool| tool.defer_loading && (config.namespace_tools || tool.namespace.is_none()))
.cloned()
.collect::<Vec<_>>();
let mut existing_spec_names = plan
.specs
let mut existing_spec_names = builder
.specs()
.iter()
.map(|configured_tool| configured_tool.name().to_string())
.collect::<HashSet<_>>();
for spec in plan.specs {
if spec.supports_parallel_tool_calls {
builder.push_spec_with_parallel_support(
spec.spec, /*supports_parallel_tool_calls*/ true,
);
} else {
builder.push_spec(spec.spec);
}
}
for handler in plan.handlers {
let name = handler.name;
match handler.kind {
ToolHandlerKind::ApplyPatch => {
builder.register_handler(Arc::new(ApplyPatchHandler));
}
ToolHandlerKind::CloseAgentV1 => {
builder.register_handler(Arc::new(CloseAgentHandler));
}
ToolHandlerKind::CloseAgentV2 => {
builder.register_handler(Arc::new(CloseAgentHandlerV2));
}
ToolHandlerKind::CodeModeExecute => {
builder.register_handler(Arc::new(CodeModeExecuteHandler));
}
ToolHandlerKind::CodeModeWait => {
builder.register_handler(Arc::new(CodeModeWaitHandler));
}
ToolHandlerKind::ContainerExec => {
builder.register_handler(Arc::new(ContainerExecHandler));
}
ToolHandlerKind::CreateGoal => {
builder.register_handler(Arc::new(CreateGoalHandler));
}
ToolHandlerKind::DynamicTool => {
builder.register_handler(Arc::new(DynamicToolHandler::new(name)));
}
ToolHandlerKind::ExecCommand => {
builder.register_handler(Arc::new(ExecCommandHandler));
}
ToolHandlerKind::FollowupTaskV2 => {
builder.register_handler(Arc::new(FollowupTaskHandlerV2));
}
ToolHandlerKind::GetGoal => {
builder.register_handler(Arc::new(GetGoalHandler));
}
ToolHandlerKind::ListAgentsV2 => {
builder.register_handler(Arc::new(ListAgentsHandlerV2));
}
ToolHandlerKind::ListMcpResources => {
builder.register_handler(Arc::new(ListMcpResourcesHandler));
}
ToolHandlerKind::ListMcpResourceTemplates => {
builder.register_handler(Arc::new(ListMcpResourceTemplatesHandler));
}
ToolHandlerKind::LocalShell => {
builder.register_handler(Arc::new(LocalShellHandler));
}
ToolHandlerKind::Mcp => {
builder.register_handler(Arc::new(McpHandler::new(name)));
}
ToolHandlerKind::Plan => {
builder.register_handler(Arc::new(PlanHandler));
}
ToolHandlerKind::ReadMcpResource => {
builder.register_handler(Arc::new(ReadMcpResourceHandler));
}
ToolHandlerKind::ReportAgentJobResult => {
builder.register_handler(Arc::new(ReportAgentJobResultHandler));
}
ToolHandlerKind::RequestPermissions => {
builder.register_handler(Arc::new(RequestPermissionsHandler));
}
ToolHandlerKind::RequestUserInput => {
builder.register_handler(Arc::new(RequestUserInputHandler {
available_modes: config.request_user_input_available_modes.clone(),
}));
}
ToolHandlerKind::ResumeAgentV1 => {
builder.register_handler(Arc::new(ResumeAgentHandler));
}
ToolHandlerKind::SendInputV1 => {
builder.register_handler(Arc::new(SendInputHandler));
}
ToolHandlerKind::SendMessageV2 => {
builder.register_handler(Arc::new(SendMessageHandlerV2));
}
ToolHandlerKind::Shell => {
builder.register_handler(Arc::new(ShellHandler));
}
ToolHandlerKind::ShellCommand => {
builder.register_handler(Arc::new(ShellCommandHandler::from(
config.shell_command_backend,
)));
}
ToolHandlerKind::SpawnAgentsOnCsv => {
builder.register_handler(Arc::new(SpawnAgentsOnCsvHandler));
}
ToolHandlerKind::SpawnAgentV1 => {
builder.register_handler(Arc::new(SpawnAgentHandler));
}
ToolHandlerKind::SpawnAgentV2 => {
builder.register_handler(Arc::new(SpawnAgentHandlerV2));
}
ToolHandlerKind::TestSync => {
builder.register_handler(Arc::new(TestSyncHandler));
}
ToolHandlerKind::ToolSearch => {
let entries = build_tool_search_entries_for_config(
config,
deferred_mcp_tools.as_ref(),
&deferred_dynamic_tools,
);
builder.register_handler(Arc::new(ToolSearchHandler::new(entries)));
}
ToolHandlerKind::RequestPluginInstall => {
builder.register_handler(Arc::new(RequestPluginInstallHandler));
}
ToolHandlerKind::UpdateGoal => {
builder.register_handler(Arc::new(UpdateGoalHandler));
}
ToolHandlerKind::ViewImage => {
builder.register_handler(Arc::new(ViewImageHandler));
}
ToolHandlerKind::WaitAgentV1 => {
builder.register_handler(Arc::new(WaitAgentHandler));
}
ToolHandlerKind::WaitAgentV2 => {
builder.register_handler(Arc::new(WaitAgentHandlerV2));
}
ToolHandlerKind::WriteStdin => {
builder.register_handler(Arc::new(WriteStdinHandler));
}
}
}
if let Some(deferred_mcp_tools) = deferred_mcp_tools.as_ref() {
for (_, tool) in deferred_mcp_tools.iter().filter(|(name, _)| {
!mcp_tools
.as_ref()
.is_some_and(|tools| tools.contains_key(*name))
}) {
builder.register_handler(Arc::new(McpHandler::new(tool.canonical_tool_name())));
}
}
for unavailable_tool in unavailable_called_tools {
let tool_name = unavailable_tool.display();
if existing_spec_names.insert(tool_name.clone()) {
@@ -332,12 +153,11 @@ pub(crate) fn build_specs_with_discoverable_tools(
output_schema: None,
defer_loading: None,
});
let spec = if config.code_mode_enabled {
augment_tool_spec_for_code_mode(spec)
} else {
spec
};
builder.push_spec(spec);
builder.push_spec(
spec,
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
}
builder.register_handler(Arc::new(UnavailableToolHandler::new(unavailable_tool)));
}
+148 -123
View File
@@ -1,5 +1,31 @@
use crate::tools::code_mode::execute_spec::create_code_mode_tool;
use crate::tools::code_mode::wait_spec::create_wait_tool;
use crate::tools::handlers::ApplyPatchHandler;
use crate::tools::handlers::CodeModeExecuteHandler;
use crate::tools::handlers::CodeModeWaitHandler;
use crate::tools::handlers::ContainerExecHandler;
use crate::tools::handlers::CreateGoalHandler;
use crate::tools::handlers::DynamicToolHandler;
use crate::tools::handlers::ExecCommandHandler;
use crate::tools::handlers::GetGoalHandler;
use crate::tools::handlers::ListMcpResourceTemplatesHandler;
use crate::tools::handlers::ListMcpResourcesHandler;
use crate::tools::handlers::LocalShellHandler;
use crate::tools::handlers::McpHandler;
use crate::tools::handlers::PlanHandler;
use crate::tools::handlers::ReadMcpResourceHandler;
use crate::tools::handlers::RequestPermissionsHandler;
use crate::tools::handlers::RequestPluginInstallHandler;
use crate::tools::handlers::RequestUserInputHandler;
use crate::tools::handlers::ShellCommandHandler;
use crate::tools::handlers::ShellHandler;
use crate::tools::handlers::TestSyncHandler;
use crate::tools::handlers::ToolSearchHandler;
use crate::tools::handlers::UpdateGoalHandler;
use crate::tools::handlers::ViewImageHandler;
use crate::tools::handlers::WriteStdinHandler;
use crate::tools::handlers::agent_jobs::ReportAgentJobResultHandler;
use crate::tools::handlers::agent_jobs::SpawnAgentsOnCsvHandler;
use crate::tools::handlers::agent_jobs_spec::create_report_agent_job_result_tool;
use crate::tools::handlers::agent_jobs_spec::create_spawn_agents_on_csv_tool;
use crate::tools::handlers::apply_patch_spec::create_apply_patch_freeform_tool;
@@ -10,6 +36,11 @@ use crate::tools::handlers::goal_spec::create_update_goal_tool;
use crate::tools::handlers::mcp_resource_spec::create_list_mcp_resource_templates_tool;
use crate::tools::handlers::mcp_resource_spec::create_list_mcp_resources_tool;
use crate::tools::handlers::mcp_resource_spec::create_read_mcp_resource_tool;
use crate::tools::handlers::multi_agents::CloseAgentHandler;
use crate::tools::handlers::multi_agents::ResumeAgentHandler;
use crate::tools::handlers::multi_agents::SendInputHandler;
use crate::tools::handlers::multi_agents::SpawnAgentHandler;
use crate::tools::handlers::multi_agents::WaitAgentHandler;
use crate::tools::handlers::multi_agents_spec::SpawnAgentToolOptions;
use crate::tools::handlers::multi_agents_spec::create_close_agent_tool_v1;
use crate::tools::handlers::multi_agents_spec::create_close_agent_tool_v2;
@@ -22,9 +53,14 @@ use crate::tools::handlers::multi_agents_spec::create_spawn_agent_tool_v1;
use crate::tools::handlers::multi_agents_spec::create_spawn_agent_tool_v2;
use crate::tools::handlers::multi_agents_spec::create_wait_agent_tool_v1;
use crate::tools::handlers::multi_agents_spec::create_wait_agent_tool_v2;
use crate::tools::handlers::multi_agents_v2::CloseAgentHandler as CloseAgentHandlerV2;
use crate::tools::handlers::multi_agents_v2::FollowupTaskHandler as FollowupTaskHandlerV2;
use crate::tools::handlers::multi_agents_v2::ListAgentsHandler as ListAgentsHandlerV2;
use crate::tools::handlers::multi_agents_v2::SendMessageHandler as SendMessageHandlerV2;
use crate::tools::handlers::multi_agents_v2::SpawnAgentHandler as SpawnAgentHandlerV2;
use crate::tools::handlers::multi_agents_v2::WaitAgentHandler as WaitAgentHandlerV2;
use crate::tools::handlers::plan_spec::create_update_plan_tool;
use crate::tools::handlers::request_plugin_install_spec::create_request_plugin_install_tool;
use crate::tools::handlers::request_user_input_spec::REQUEST_USER_INPUT_TOOL_NAME;
use crate::tools::handlers::request_user_input_spec::create_request_user_input_tool;
use crate::tools::handlers::request_user_input_spec::request_user_input_tool_description;
use crate::tools::handlers::shell_spec::CommandToolOptions;
@@ -43,17 +79,14 @@ use crate::tools::handlers::view_image_spec::create_view_image_tool;
use crate::tools::hosted_spec::WebSearchToolOptions;
use crate::tools::hosted_spec::create_image_generation_tool;
use crate::tools::hosted_spec::create_web_search_tool;
use crate::tools::spec_plan_types::ToolHandlerKind;
use crate::tools::spec_plan_types::ToolRegistryPlan;
use crate::tools::spec_plan_types::ToolRegistryPlanParams;
use crate::tools::registry::ToolRegistryBuilder;
use crate::tools::spec_plan_types::ToolRegistryBuildParams;
use crate::tools::spec_plan_types::agent_type_description;
use codex_protocol::openai_models::ApplyPatchToolType;
use codex_protocol::openai_models::ConfigShellToolType;
use codex_tools::REQUEST_PLUGIN_INSTALL_TOOL_NAME;
use codex_tools::ResponsesApiNamespace;
use codex_tools::ResponsesApiNamespaceTool;
use codex_tools::TOOL_SEARCH_DEFAULT_LIMIT;
use codex_tools::TOOL_SEARCH_TOOL_NAME;
use codex_tools::ToolEnvironmentMode;
use codex_tools::ToolName;
use codex_tools::ToolSearchSource;
@@ -68,12 +101,13 @@ use codex_tools::default_namespace_description;
use codex_tools::dynamic_tool_to_loadable_tool_spec;
use codex_tools::mcp_tool_to_responses_api_tool;
use std::collections::BTreeMap;
use std::sync::Arc;
pub fn build_tool_registry_plan(
pub fn build_tool_registry_builder(
config: &ToolsConfig,
params: ToolRegistryPlanParams<'_>,
) -> ToolRegistryPlan {
let mut plan = ToolRegistryPlan::new();
params: ToolRegistryBuildParams<'_>,
) -> ToolRegistryBuilder {
let mut builder = ToolRegistryBuilder::new();
let exec_permission_approvals_enabled = config.exec_permission_approvals_enabled;
if config.code_mode_enabled {
@@ -92,22 +126,22 @@ pub fn build_tool_registry_plan(
})
.collect::<BTreeMap<_, _>>();
let nested_config = config.for_code_mode_nested_tools();
let nested_plan = build_tool_registry_plan(
let nested_builder = build_tool_registry_builder(
&nested_config,
ToolRegistryPlanParams {
ToolRegistryBuildParams {
discoverable_tools: None,
..params
},
);
let mut enabled_tools = collect_code_mode_exec_prompt_tool_definitions(
nested_plan
.specs
nested_builder
.specs()
.iter()
.map(|configured_tool| &configured_tool.spec),
);
enabled_tools
.sort_by(|left, right| compare_code_mode_tools(left, right, &namespace_descriptions));
plan.push_spec(
builder.push_spec(
create_code_mode_tool(
&enabled_tools,
&namespace_descriptions,
@@ -120,19 +154,13 @@ pub fn build_tool_registry_plan(
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler(
codex_code_mode::PUBLIC_TOOL_NAME,
ToolHandlerKind::CodeModeExecute,
);
plan.push_spec(
builder.register_handler(Arc::new(CodeModeExecuteHandler));
builder.push_spec(
create_wait_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler(
codex_code_mode::WAIT_TOOL_NAME,
ToolHandlerKind::CodeModeWait,
);
builder.register_handler(Arc::new(CodeModeWaitHandler));
}
if config.environment_mode.has_environment() {
@@ -140,7 +168,7 @@ pub fn build_tool_registry_plan(
matches!(config.environment_mode, ToolEnvironmentMode::Multiple);
match &config.shell_type {
ConfigShellToolType::Default => {
plan.push_spec(
builder.push_spec(
create_shell_tool(ShellToolOptions {
exec_permission_approvals_enabled,
}),
@@ -149,14 +177,14 @@ pub fn build_tool_registry_plan(
);
}
ConfigShellToolType::Local => {
plan.push_spec(
builder.push_spec(
create_local_shell_tool(),
/*supports_parallel_tool_calls*/ true,
config.code_mode_enabled,
);
}
ConfigShellToolType::UnifiedExec => {
plan.push_spec(
builder.push_spec(
create_exec_command_tool_with_environment_id(
CommandToolOptions {
allow_login_shell: config.allow_login_shell,
@@ -167,17 +195,17 @@ pub fn build_tool_registry_plan(
/*supports_parallel_tool_calls*/ true,
config.code_mode_enabled,
);
plan.push_spec(
builder.push_spec(
create_write_stdin_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler("exec_command", ToolHandlerKind::ExecCommand);
plan.register_handler("write_stdin", ToolHandlerKind::WriteStdin);
builder.register_handler(Arc::new(ExecCommandHandler));
builder.register_handler(Arc::new(WriteStdinHandler));
}
ConfigShellToolType::Disabled => {}
ConfigShellToolType::ShellCommand => {
plan.push_spec(
builder.push_spec(
create_shell_command_tool(CommandToolOptions {
allow_login_shell: config.allow_login_shell,
exec_permission_approvals_enabled,
@@ -192,82 +220,80 @@ pub fn build_tool_registry_plan(
if config.environment_mode.has_environment()
&& config.shell_type != ConfigShellToolType::Disabled
{
plan.register_handler("shell", ToolHandlerKind::Shell);
plan.register_handler("container.exec", ToolHandlerKind::ContainerExec);
plan.register_handler("local_shell", ToolHandlerKind::LocalShell);
plan.register_handler("shell_command", ToolHandlerKind::ShellCommand);
builder.register_handler(Arc::new(ShellHandler));
builder.register_handler(Arc::new(ContainerExecHandler));
builder.register_handler(Arc::new(LocalShellHandler));
builder.register_handler(Arc::new(ShellCommandHandler::from(
config.shell_command_backend,
)));
}
if params.mcp_tools.is_some() {
plan.push_spec(
builder.push_spec(
create_list_mcp_resources_tool(),
/*supports_parallel_tool_calls*/ true,
config.code_mode_enabled,
);
plan.push_spec(
builder.push_spec(
create_list_mcp_resource_templates_tool(),
/*supports_parallel_tool_calls*/ true,
config.code_mode_enabled,
);
plan.push_spec(
builder.push_spec(
create_read_mcp_resource_tool(),
/*supports_parallel_tool_calls*/ true,
config.code_mode_enabled,
);
plan.register_handler("list_mcp_resources", ToolHandlerKind::ListMcpResources);
plan.register_handler(
"list_mcp_resource_templates",
ToolHandlerKind::ListMcpResourceTemplates,
);
plan.register_handler("read_mcp_resource", ToolHandlerKind::ReadMcpResource);
builder.register_handler(Arc::new(ListMcpResourcesHandler));
builder.register_handler(Arc::new(ListMcpResourceTemplatesHandler));
builder.register_handler(Arc::new(ReadMcpResourceHandler));
}
plan.push_spec(
builder.push_spec(
create_update_plan_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler("update_plan", ToolHandlerKind::Plan);
builder.register_handler(Arc::new(PlanHandler));
if config.goal_tools {
plan.push_spec(
builder.push_spec(
create_get_goal_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler("get_goal", ToolHandlerKind::GetGoal);
plan.push_spec(
builder.register_handler(Arc::new(GetGoalHandler));
builder.push_spec(
create_create_goal_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler("create_goal", ToolHandlerKind::CreateGoal);
plan.push_spec(
builder.register_handler(Arc::new(CreateGoalHandler));
builder.push_spec(
create_update_goal_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler("update_goal", ToolHandlerKind::UpdateGoal);
builder.register_handler(Arc::new(UpdateGoalHandler));
}
plan.push_spec(
builder.push_spec(
create_request_user_input_tool(request_user_input_tool_description(
&config.request_user_input_available_modes,
)),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler(
REQUEST_USER_INPUT_TOOL_NAME,
ToolHandlerKind::RequestUserInput,
);
builder.register_handler(Arc::new(RequestUserInputHandler {
available_modes: config.request_user_input_available_modes.clone(),
}));
if config.request_permissions_tool_enabled {
plan.push_spec(
builder.push_spec(
create_request_permissions_tool(request_permissions_tool_description()),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler("request_permissions", ToolHandlerKind::RequestPermissions);
builder.register_handler(Arc::new(RequestPermissionsHandler));
}
let deferred_dynamic_tools = params
@@ -303,35 +329,28 @@ pub fn build_tool_registry_plan(
});
}
plan.push_spec(
builder.push_spec(
create_tool_search_tool(&search_source_infos, TOOL_SEARCH_DEFAULT_LIMIT),
/*supports_parallel_tool_calls*/ true,
config.code_mode_enabled,
);
plan.register_handler(TOOL_SEARCH_TOOL_NAME, ToolHandlerKind::ToolSearch);
if let Some(deferred_mcp_tools) = deferred_mcp_tools_for_search {
for tool in deferred_mcp_tools {
plan.register_handler(tool.name.clone(), ToolHandlerKind::Mcp);
}
}
builder.register_handler(Arc::new(ToolSearchHandler::new(
params.tool_search_entries.to_vec(),
)));
}
if config.tool_suggest
&& let Some(discoverable_tools) =
params.discoverable_tools.filter(|tools| !tools.is_empty())
{
plan.push_spec(
builder.push_spec(
create_request_plugin_install_tool(&collect_request_plugin_install_entries(
discoverable_tools,
)),
/*supports_parallel_tool_calls*/ true,
/*code_mode_enabled*/ false,
);
plan.register_handler(
REQUEST_PLUGIN_INSTALL_TOOL_NAME,
ToolHandlerKind::RequestPluginInstall,
);
builder.register_handler(Arc::new(RequestPluginInstallHandler));
}
if config.environment_mode.has_environment()
@@ -339,21 +358,21 @@ pub fn build_tool_registry_plan(
{
match apply_patch_tool_type {
ApplyPatchToolType::Freeform => {
plan.push_spec(
builder.push_spec(
create_apply_patch_freeform_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
}
ApplyPatchToolType::Function => {
plan.push_spec(
builder.push_spec(
create_apply_patch_json_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
}
}
plan.register_handler("apply_patch", ToolHandlerKind::ApplyPatch);
builder.register_handler(Arc::new(ApplyPatchHandler));
}
if config
@@ -361,12 +380,12 @@ pub fn build_tool_registry_plan(
.iter()
.any(|tool| tool == "test_sync_tool")
{
plan.push_spec(
builder.push_spec(
create_test_sync_tool(),
/*supports_parallel_tool_calls*/ true,
config.code_mode_enabled,
);
plan.register_handler("test_sync_tool", ToolHandlerKind::TestSync);
builder.register_handler(Arc::new(TestSyncHandler));
}
if let Some(web_search_tool) = create_web_search_tool(WebSearchToolOptions {
@@ -374,7 +393,7 @@ pub fn build_tool_registry_plan(
web_search_config: config.web_search_config.as_ref(),
web_search_tool_type: config.web_search_tool_type,
}) {
plan.push_spec(
builder.push_spec(
web_search_tool,
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
@@ -382,7 +401,7 @@ pub fn build_tool_registry_plan(
}
if config.image_gen_tool {
plan.push_spec(
builder.push_spec(
create_image_generation_tool("png"),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
@@ -390,21 +409,21 @@ pub fn build_tool_registry_plan(
}
if config.environment_mode.has_environment() {
plan.push_spec(
builder.push_spec(
create_view_image_tool(ViewImageToolOptions {
can_request_original_image_detail: config.can_request_original_image_detail,
}),
/*supports_parallel_tool_calls*/ true,
config.code_mode_enabled,
);
plan.register_handler("view_image", ToolHandlerKind::ViewImage);
builder.register_handler(Arc::new(ViewImageHandler));
}
if config.collab_tools {
if config.multi_agent_v2 {
let agent_type_description =
agent_type_description(config, params.default_agent_type_description);
plan.push_spec(
builder.push_spec(
create_spawn_agent_tool_v2(SpawnAgentToolOptions {
available_models: &config.available_models,
agent_type_description,
@@ -416,41 +435,41 @@ pub fn build_tool_registry_plan(
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.push_spec(
builder.push_spec(
create_send_message_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.push_spec(
builder.push_spec(
create_followup_task_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.push_spec(
builder.push_spec(
create_wait_agent_tool_v2(params.wait_agent_timeouts),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.push_spec(
builder.push_spec(
create_close_agent_tool_v2(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.push_spec(
builder.push_spec(
create_list_agents_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler("spawn_agent", ToolHandlerKind::SpawnAgentV2);
plan.register_handler("send_message", ToolHandlerKind::SendMessageV2);
plan.register_handler("followup_task", ToolHandlerKind::FollowupTaskV2);
plan.register_handler("wait_agent", ToolHandlerKind::WaitAgentV2);
plan.register_handler("close_agent", ToolHandlerKind::CloseAgentV2);
plan.register_handler("list_agents", ToolHandlerKind::ListAgentsV2);
builder.register_handler(Arc::new(SpawnAgentHandlerV2));
builder.register_handler(Arc::new(SendMessageHandlerV2));
builder.register_handler(Arc::new(FollowupTaskHandlerV2));
builder.register_handler(Arc::new(WaitAgentHandlerV2));
builder.register_handler(Arc::new(CloseAgentHandlerV2));
builder.register_handler(Arc::new(ListAgentsHandlerV2));
} else {
let agent_type_description =
agent_type_description(config, params.default_agent_type_description);
plan.push_spec(
builder.push_spec(
create_spawn_agent_tool_v1(SpawnAgentToolOptions {
available_models: &config.available_models,
agent_type_description,
@@ -462,51 +481,48 @@ pub fn build_tool_registry_plan(
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.push_spec(
builder.push_spec(
create_send_input_tool_v1(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.push_spec(
builder.push_spec(
create_resume_agent_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler("resume_agent", ToolHandlerKind::ResumeAgentV1);
plan.push_spec(
builder.register_handler(Arc::new(ResumeAgentHandler));
builder.push_spec(
create_wait_agent_tool_v1(params.wait_agent_timeouts),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.push_spec(
builder.push_spec(
create_close_agent_tool_v1(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler("spawn_agent", ToolHandlerKind::SpawnAgentV1);
plan.register_handler("send_input", ToolHandlerKind::SendInputV1);
plan.register_handler("wait_agent", ToolHandlerKind::WaitAgentV1);
plan.register_handler("close_agent", ToolHandlerKind::CloseAgentV1);
builder.register_handler(Arc::new(SpawnAgentHandler));
builder.register_handler(Arc::new(SendInputHandler));
builder.register_handler(Arc::new(WaitAgentHandler));
builder.register_handler(Arc::new(CloseAgentHandler));
}
}
if config.agent_jobs_tools {
plan.push_spec(
builder.push_spec(
create_spawn_agents_on_csv_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler("spawn_agents_on_csv", ToolHandlerKind::SpawnAgentsOnCsv);
builder.register_handler(Arc::new(SpawnAgentsOnCsvHandler));
if config.agent_jobs_worker_tools {
plan.push_spec(
builder.push_spec(
create_report_agent_job_result_tool(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
plan.register_handler(
"report_agent_job_result",
ToolHandlerKind::ReportAgentJobResult,
);
builder.register_handler(Arc::new(ReportAgentJobResultHandler));
}
}
@@ -548,7 +564,7 @@ pub fn build_tool_registry_plan(
match mcp_tool_to_responses_api_tool(&tool.name, tool.tool) {
Ok(converted_tool) => {
tools.push(ResponsesApiNamespaceTool::Function(converted_tool));
plan.register_handler(tool.name, ToolHandlerKind::Mcp);
builder.register_handler(Arc::new(McpHandler::new(tool.name)));
}
Err(error) => {
let tool_name = &tool.name;
@@ -559,8 +575,8 @@ pub fn build_tool_registry_plan(
}
}
if !tools.is_empty() {
plan.push_spec(
if config.namespace_tools && !tools.is_empty() {
builder.push_spec(
ToolSpec::Namespace(ResponsesApiNamespace {
name: namespace,
description,
@@ -579,7 +595,7 @@ pub fn build_tool_registry_plan(
Ok(loadable_tool) => {
let handler_name = ToolName::new(tool.namespace.clone(), tool.name.clone());
dynamic_tool_specs.push(loadable_tool);
plan.register_handler(handler_name, ToolHandlerKind::DynamicTool);
builder.register_handler(Arc::new(DynamicToolHandler::new(handler_name)));
}
Err(error) => {
tracing::error!(
@@ -590,19 +606,28 @@ pub fn build_tool_registry_plan(
}
}
for spec in coalesce_loadable_tool_specs(dynamic_tool_specs) {
plan.push_spec(
spec.into(),
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
let spec = spec.into();
if config.namespace_tools || !matches!(spec, ToolSpec::Namespace(_)) {
builder.push_spec(
spec,
/*supports_parallel_tool_calls*/ false,
config.code_mode_enabled,
);
}
}
if !config.namespace_tools {
plan.specs
.retain(|configured_tool| !matches!(&configured_tool.spec, ToolSpec::Namespace(_)));
if let Some(deferred_mcp_tools) = params.deferred_mcp_tools {
for tool in deferred_mcp_tools {
let registered_directly = params
.mcp_tools
.is_some_and(|mcp_tools| mcp_tools.iter().any(|direct| direct.name == tool.name));
if !registered_directly {
builder.register_handler(Arc::new(McpHandler::new(tool.name.clone())));
}
}
}
plan
builder
}
fn compare_code_mode_tools(
+37 -57
View File
@@ -1,11 +1,12 @@
use super::*;
use crate::tools::handlers::multi_agents_spec::WaitAgentTimeoutOptions;
use crate::tools::handlers::request_user_input_spec::REQUEST_USER_INPUT_TOOL_NAME;
use crate::tools::handlers::shell_spec::CommandToolOptions;
use crate::tools::handlers::shell_spec::create_exec_command_tool;
use crate::tools::spec_plan_types::ToolHandlerSpec;
use crate::tools::registry::ToolRegistry;
use crate::tools::spec_plan_types::ToolNamespace;
use crate::tools::spec_plan_types::ToolRegistryPlanDeferredTool;
use crate::tools::spec_plan_types::ToolRegistryPlanMcpTool;
use crate::tools::spec_plan_types::ToolRegistryBuildDeferredTool;
use crate::tools::spec_plan_types::ToolRegistryBuildMcpTool;
use codex_app_server_protocol::AppInfo;
use codex_features::Feature;
use codex_features::Features;
@@ -29,10 +30,12 @@ use codex_tools::FreeformTool;
use codex_tools::JsonSchema;
use codex_tools::JsonSchemaPrimitiveType;
use codex_tools::JsonSchemaType;
use codex_tools::REQUEST_PLUGIN_INSTALL_TOOL_NAME;
use codex_tools::ResponsesApiNamespaceTool;
use codex_tools::ResponsesApiTool;
use codex_tools::ResponsesApiWebSearchFilters;
use codex_tools::ResponsesApiWebSearchUserLocation;
use codex_tools::TOOL_SEARCH_TOOL_NAME;
use codex_tools::ToolEnvironmentMode;
use codex_tools::ToolName;
use codex_tools::ToolsConfigParams;
@@ -1244,7 +1247,7 @@ fn namespace_specs_are_hidden_when_namespace_tools_are_disabled() {
});
tools_config.namespace_tools = false;
let (tools, handlers) = build_specs(
let (tools, registry) = build_specs(
&tools_config,
Some(HashMap::from([(
ToolName::namespaced("mcp__sample__", "echo"),
@@ -1255,10 +1258,7 @@ fn namespace_specs_are_hidden_when_namespace_tools_are_disabled() {
);
assert_lacks_tool_name(&tools, "mcp__sample__");
assert!(handlers.contains(&ToolHandlerSpec {
name: ToolName::namespaced("mcp__sample__", "echo"),
kind: ToolHandlerKind::Mcp,
}));
assert!(registry.has_handler(&ToolName::namespaced("mcp__sample__", "echo")));
}
#[test]
@@ -1412,7 +1412,7 @@ fn search_tool_description_lists_each_mcp_source_once() {
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, handlers) = build_specs(
let (tools, registry) = build_specs(
&tools_config,
Some(HashMap::from([
(
@@ -1477,14 +1477,11 @@ fn search_tool_description_lists_each_mcp_source_once() {
assert!(description.contains("- rmcp: Remote memory tools."));
assert!(!description.contains("mcp__rmcp__echo"));
assert!(handlers.contains(&ToolHandlerSpec {
name: ToolName::namespaced("mcp__codex_apps__calendar", "_create_event"),
kind: ToolHandlerKind::Mcp,
}));
assert!(handlers.contains(&ToolHandlerSpec {
name: ToolName::namespaced("mcp__rmcp__", "echo"),
kind: ToolHandlerKind::Mcp,
}));
assert!(registry.has_handler(&ToolName::namespaced(
"mcp__codex_apps__calendar",
"_create_event",
)));
assert!(registry.has_handler(&ToolName::namespaced("mcp__rmcp__", "echo")));
}
#[test]
@@ -1578,7 +1575,7 @@ fn search_tool_is_hidden_when_only_deferred_namespace_tools_are_available() {
});
tools_config.namespace_tools = false;
let (tools, handlers) = build_specs(
let (tools, registry) = build_specs(
&tools_config,
/*mcp_tools*/ None,
Some(vec![deferred_mcp_tool(
@@ -1592,10 +1589,7 @@ fn search_tool_is_hidden_when_only_deferred_namespace_tools_are_available() {
);
assert_lacks_tool_name(&tools, TOOL_SEARCH_TOOL_NAME);
assert!(!handlers.contains(&ToolHandlerSpec {
name: ToolName::plain(TOOL_SEARCH_TOOL_NAME),
kind: ToolHandlerKind::ToolSearch,
}));
assert!(!registry.has_handler(&ToolName::plain(TOOL_SEARCH_TOOL_NAME)));
}
#[test]
@@ -1639,7 +1633,7 @@ fn search_tool_registers_for_deferred_dynamic_tools() {
},
];
let (tools, handlers) = build_specs(
let (tools, registry) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*deferred_mcp_tools*/ None,
@@ -1670,18 +1664,9 @@ fn search_tool_registers_for_deferred_dynamic_tools() {
let dynamic_tool = find_namespace_function_tool(&tools, "codex_app", tool_name);
assert_eq!(dynamic_tool.defer_loading, Some(true));
}
assert!(handlers.contains(&ToolHandlerSpec {
name: ToolName::plain(TOOL_SEARCH_TOOL_NAME),
kind: ToolHandlerKind::ToolSearch,
}));
assert!(handlers.contains(&ToolHandlerSpec {
name: ToolName::namespaced("codex_app", "automation_update"),
kind: ToolHandlerKind::DynamicTool,
}));
assert!(handlers.contains(&ToolHandlerSpec {
name: ToolName::namespaced("codex_app", "automation_list"),
kind: ToolHandlerKind::DynamicTool,
}));
assert!(registry.has_handler(&ToolName::plain(TOOL_SEARCH_TOOL_NAME)));
assert!(registry.has_handler(&ToolName::namespaced("codex_app", "automation_update")));
assert!(registry.has_handler(&ToolName::namespaced("codex_app", "automation_list")));
}
#[test]
@@ -1718,7 +1703,7 @@ fn search_tool_keeps_plain_deferred_dynamic_tools_when_namespace_tools_are_disab
},
];
let (tools, handlers) = build_specs(
let (tools, registry) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*deferred_mcp_tools*/ None,
@@ -1727,10 +1712,7 @@ fn search_tool_keeps_plain_deferred_dynamic_tools_when_namespace_tools_are_disab
assert_contains_tool_names(&tools, &[TOOL_SEARCH_TOOL_NAME, "plain_dynamic"]);
assert_lacks_tool_name(&tools, "codex_app");
assert!(handlers.contains(&ToolHandlerSpec {
name: ToolName::plain(TOOL_SEARCH_TOOL_NAME),
kind: ToolHandlerKind::ToolSearch,
}));
assert!(registry.has_handler(&ToolName::plain(TOOL_SEARCH_TOOL_NAME)));
}
#[test]
@@ -1862,17 +1844,14 @@ fn request_plugin_install_description_lists_discoverable_tools() {
})),
];
let (tools, handlers) = build_specs_with_discoverable_tools(
let (tools, registry) = build_specs_with_discoverable_tools(
&tools_config,
/*mcp_tools*/ None,
/*deferred_mcp_tools*/ None,
Some(discoverable_tools),
&[],
);
assert!(handlers.contains(&ToolHandlerSpec {
name: ToolName::plain(REQUEST_PLUGIN_INSTALL_TOOL_NAME),
kind: ToolHandlerKind::RequestPluginInstall,
}));
assert!(registry.has_handler(&ToolName::plain(REQUEST_PLUGIN_INSTALL_TOOL_NAME)));
let request_plugin_install = find_tool(&tools, REQUEST_PLUGIN_INSTALL_TOOL_NAME);
let ToolSpec::Function(ResponsesApiTool {
@@ -2225,9 +2204,9 @@ fn search_capable_model_info() -> ModelInfo {
fn build_specs<'a>(
config: &ToolsConfig,
mcp_tools: Option<HashMap<ToolName, rmcp::model::Tool>>,
deferred_mcp_tools: Option<Vec<ToolRegistryPlanDeferredTool<'a>>>,
deferred_mcp_tools: Option<Vec<ToolRegistryBuildDeferredTool<'a>>>,
dynamic_tools: &[DynamicToolSpec],
) -> (Vec<ConfiguredToolSpec>, Vec<ToolHandlerSpec>) {
) -> (Vec<ConfiguredToolSpec>, ToolRegistry) {
build_specs_with_discoverable_tools(
config,
mcp_tools,
@@ -2240,10 +2219,10 @@ fn build_specs<'a>(
fn build_specs_with_discoverable_tools<'a>(
config: &ToolsConfig,
mcp_tools: Option<HashMap<ToolName, rmcp::model::Tool>>,
deferred_mcp_tools: Option<Vec<ToolRegistryPlanDeferredTool<'a>>>,
deferred_mcp_tools: Option<Vec<ToolRegistryBuildDeferredTool<'a>>>,
discoverable_tools: Option<Vec<DiscoverableTool>>,
dynamic_tools: &[DynamicToolSpec],
) -> (Vec<ConfiguredToolSpec>, Vec<ToolHandlerSpec>) {
) -> (Vec<ConfiguredToolSpec>, ToolRegistry) {
build_specs_with_optional_tool_namespaces(
config,
mcp_tools,
@@ -2257,23 +2236,23 @@ fn build_specs_with_discoverable_tools<'a>(
fn build_specs_with_optional_tool_namespaces<'a>(
config: &ToolsConfig,
mcp_tools: Option<HashMap<ToolName, rmcp::model::Tool>>,
deferred_mcp_tools: Option<Vec<ToolRegistryPlanDeferredTool<'a>>>,
deferred_mcp_tools: Option<Vec<ToolRegistryBuildDeferredTool<'a>>>,
tool_namespaces: Option<HashMap<String, ToolNamespace>>,
discoverable_tools: Option<Vec<DiscoverableTool>>,
dynamic_tools: &[DynamicToolSpec],
) -> (Vec<ConfiguredToolSpec>, Vec<ToolHandlerSpec>) {
) -> (Vec<ConfiguredToolSpec>, ToolRegistry) {
let mcp_tool_inputs = mcp_tools.as_ref().map(|mcp_tools| {
mcp_tools
.iter()
.map(|(name, tool)| ToolRegistryPlanMcpTool {
.map(|(name, tool)| ToolRegistryBuildMcpTool {
name: name.clone(),
tool,
})
.collect::<Vec<_>>()
});
let plan = build_tool_registry_plan(
let builder = build_tool_registry_builder(
config,
ToolRegistryPlanParams {
ToolRegistryBuildParams {
mcp_tools: mcp_tool_inputs.as_deref(),
deferred_mcp_tools: deferred_mcp_tools.as_deref(),
tool_namespaces: tool_namespaces.as_ref(),
@@ -2281,9 +2260,10 @@ fn build_specs_with_optional_tool_namespaces<'a>(
dynamic_tools,
default_agent_type_description: DEFAULT_AGENT_TYPE_DESCRIPTION,
wait_agent_timeouts: wait_agent_timeout_options(),
tool_search_entries: &[],
},
);
(plan.specs, plan.handlers)
builder.build()
}
fn mcp_tool(name: &str, description: &str, input_schema: serde_json::Value) -> rmcp::model::Tool {
@@ -2397,8 +2377,8 @@ fn deferred_mcp_tool<'a>(
server_name: &'a str,
connector_name: Option<&'a str>,
description: Option<&'a str>,
) -> ToolRegistryPlanDeferredTool<'a> {
ToolRegistryPlanDeferredTool {
) -> ToolRegistryBuildDeferredTool<'a> {
ToolRegistryBuildDeferredTool {
name: ToolName::namespaced(tool_namespace, tool_name),
server_name,
connector_name,
+7 -93
View File
@@ -1,75 +1,20 @@
use crate::tools::handlers::multi_agents_spec::WaitAgentTimeoutOptions;
use codex_protocol::dynamic_tools::DynamicToolSpec;
use codex_tools::ConfiguredToolSpec;
use codex_tools::DiscoverableTool;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
use codex_tools::ToolsConfig;
use codex_tools::augment_tool_spec_for_code_mode;
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolHandlerKind {
ApplyPatch,
CloseAgentV1,
CloseAgentV2,
CodeModeExecute,
CodeModeWait,
ContainerExec,
CreateGoal,
DynamicTool,
ExecCommand,
FollowupTaskV2,
GetGoal,
ListAgentsV2,
ListMcpResourceTemplates,
ListMcpResources,
LocalShell,
Mcp,
Plan,
ReadMcpResource,
ReportAgentJobResult,
RequestPluginInstall,
RequestPermissions,
RequestUserInput,
ResumeAgentV1,
SendInputV1,
SendMessageV2,
Shell,
ShellCommand,
SpawnAgentsOnCsv,
SpawnAgentV1,
SpawnAgentV2,
TestSync,
ToolSearch,
UpdateGoal,
ViewImage,
WaitAgentV1,
WaitAgentV2,
WriteStdin,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolHandlerSpec {
pub name: ToolName,
pub kind: ToolHandlerKind,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ToolRegistryPlan {
pub specs: Vec<ConfiguredToolSpec>,
pub handlers: Vec<ToolHandlerSpec>,
}
#[derive(Debug, Clone, Copy)]
pub struct ToolRegistryPlanParams<'a> {
pub mcp_tools: Option<&'a [ToolRegistryPlanMcpTool<'a>]>,
pub deferred_mcp_tools: Option<&'a [ToolRegistryPlanDeferredTool<'a>]>,
#[derive(Clone, Copy)]
pub struct ToolRegistryBuildParams<'a> {
pub mcp_tools: Option<&'a [ToolRegistryBuildMcpTool<'a>]>,
pub deferred_mcp_tools: Option<&'a [ToolRegistryBuildDeferredTool<'a>]>,
pub tool_namespaces: Option<&'a HashMap<String, ToolNamespace>>,
pub discoverable_tools: Option<&'a [DiscoverableTool]>,
pub dynamic_tools: &'a [DynamicToolSpec],
pub default_agent_type_description: &'a str,
pub wait_agent_timeouts: WaitAgentTimeoutOptions,
pub tool_search_entries: &'a [crate::tools::tool_search_entry::ToolSearchEntry],
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -82,50 +27,19 @@ pub struct ToolNamespace {
/// while registering its runtime handler with the canonical namespace/name
/// identity.
#[derive(Debug, Clone)]
pub struct ToolRegistryPlanMcpTool<'a> {
pub struct ToolRegistryBuildMcpTool<'a> {
pub name: ToolName,
pub tool: &'a rmcp::model::Tool,
}
#[derive(Debug, Clone)]
pub struct ToolRegistryPlanDeferredTool<'a> {
pub struct ToolRegistryBuildDeferredTool<'a> {
pub name: ToolName,
pub server_name: &'a str,
pub connector_name: Option<&'a str>,
pub description: Option<&'a str>,
}
impl ToolRegistryPlan {
pub(crate) fn new() -> Self {
Self {
specs: Vec::new(),
handlers: Vec::new(),
}
}
pub(crate) fn push_spec(
&mut self,
spec: ToolSpec,
supports_parallel_tool_calls: bool,
code_mode_enabled: bool,
) {
let spec = if code_mode_enabled {
augment_tool_spec_for_code_mode(spec)
} else {
spec
};
self.specs
.push(ConfiguredToolSpec::new(spec, supports_parallel_tool_calls));
}
pub(crate) fn register_handler(&mut self, name: impl Into<ToolName>, kind: ToolHandlerKind) {
self.handlers.push(ToolHandlerSpec {
name: name.into(),
kind,
});
}
}
pub(crate) fn agent_type_description(
config: &ToolsConfig,
default_agent_type_description: &str,
+246
View File
@@ -13,6 +13,8 @@ use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelsResponse;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookRunStatus;
use codex_protocol::protocol::ItemCompletedEvent;
use codex_protocol::protocol::ItemStartedEvent;
use codex_protocol::protocol::Op;
@@ -23,6 +25,7 @@ use codex_protocol::user_input::UserInput;
use core_test_support::context_snapshot;
use core_test_support::context_snapshot::ContextSnapshotOptions;
use core_test_support::context_snapshot::ContextSnapshotRenderMode;
use core_test_support::hooks::trust_discovered_hooks;
use core_test_support::responses::ev_local_shell_call;
use core_test_support::responses::ev_reasoning_item;
use core_test_support::responses::mount_models_once;
@@ -47,7 +50,10 @@ use core_test_support::responses::sse_failed;
use core_test_support::responses::sse_response;
use core_test_support::responses::start_mock_server;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::fs;
use std::path::Path;
use wiremock::MockServer;
// --- Test helpers -----------------------------------------------------------
@@ -119,6 +125,107 @@ fn json_fragment(text: &str) -> String {
.to_string()
}
fn read_hook_inputs(path: &Path) -> Vec<Value> {
let text = fs::read_to_string(path)
.unwrap_or_else(|err| panic!("failed to read hook input log {}: {err}", path.display()));
text.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| {
serde_json::from_str(line)
.unwrap_or_else(|err| panic!("failed to parse hook input log line: {err}"))
})
.collect()
}
fn python_hook_command(script_path: &Path) -> String {
format!("python3 \"{}\"", script_path.display())
}
fn write_unsupported_blocking_pre_compact_hook(home: &Path) {
let script_path = home.join("pre_compact_block.py");
let log_path = home.join("pre_compact_block_log.jsonl");
let script = format!(
r#"import json
from pathlib import Path
import sys
payload = json.load(sys.stdin)
with Path(r"{log_path}").open("a", encoding="utf-8") as handle:
handle.write(json.dumps(payload) + "\n")
print(json.dumps({{"decision": "block", "reason": "blocked by policy"}}))
"#,
log_path = log_path.display(),
);
let hooks = json!({
"hooks": {
"PreCompact": [{
"matcher": "manual",
"hooks": [{
"type": "command",
"command": python_hook_command(&script_path),
"statusMessage": "checking compact policy",
}]
}]
}
});
fs::write(&script_path, script).expect("write pre compact hook script");
fs::write(home.join("hooks.json"), hooks.to_string()).expect("write hooks.json");
}
fn write_matching_compact_hooks(home: &Path) {
let auto_script_path = home.join("pre_compact_auto.py");
let auto_log_path = home.join("pre_compact_auto_log.jsonl");
let manual_post_script_path = home.join("post_compact_manual.py");
let manual_post_log_path = home.join("post_compact_manual_log.jsonl");
let auto_script = format!(
r#"import json
from pathlib import Path
import sys
payload = json.load(sys.stdin)
with Path(r"{auto_log_path}").open("a", encoding="utf-8") as handle:
handle.write(json.dumps(payload) + "\n")
"#,
auto_log_path = auto_log_path.display(),
);
let manual_post_script = format!(
r#"import json
from pathlib import Path
import sys
payload = json.load(sys.stdin)
with Path(r"{manual_post_log_path}").open("a", encoding="utf-8") as handle:
handle.write(json.dumps(payload) + "\n")
"#,
manual_post_log_path = manual_post_log_path.display(),
);
let hooks = json!({
"hooks": {
"PreCompact": [{
"matcher": "auto",
"hooks": [{
"type": "command",
"command": python_hook_command(&auto_script_path),
}]
}],
"PostCompact": [{
"matcher": "manual",
"hooks": [{
"type": "command",
"command": python_hook_command(&manual_post_script_path),
}]
}]
}
});
fs::write(&auto_script_path, auto_script).expect("write auto pre compact hook script");
fs::write(&manual_post_script_path, manual_post_script)
.expect("write manual post compact hook script");
fs::write(home.join("hooks.json"), hooks.to_string()).expect("write hooks.json");
}
fn non_openai_model_provider(server: &MockServer) -> ModelProviderInfo {
let mut provider =
built_in_model_providers(/* openai_base_url */ /*openai_base_url*/ None)["openai"].clone();
@@ -437,6 +544,145 @@ async fn summarize_context_three_requests_and_instructions() {
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn manual_pre_compact_block_decision_does_not_block_compaction() {
skip_if_no_network!();
let server = start_mock_server().await;
let first_turn = sse(vec![
ev_assistant_message("m0", FIRST_REPLY),
ev_completed_with_tokens("r0", /*total_tokens*/ 80),
]);
let compact_turn = sse(vec![
ev_assistant_message("m1", SUMMARY_TEXT),
ev_completed_with_tokens("r1", /*total_tokens*/ 100),
]);
let request_log = mount_sse_sequence(&server, vec![first_turn, compact_turn]).await;
let model_provider = non_openai_model_provider(&server);
let mut builder = test_codex()
.with_pre_build_hook(write_unsupported_blocking_pre_compact_hook)
.with_config(move |config| {
config.model_provider = model_provider;
trust_discovered_hooks(config);
set_test_compact_prompt(config);
});
let test = builder.build(&server).await.expect("create conversation");
let codex = test.codex.clone();
codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "hello before blocked compact".to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await
.expect("submit first user turn");
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
codex.submit(Op::Compact).await.expect("trigger compact");
let completed = wait_for_event_match(&codex, |ev| match ev {
EventMsg::HookCompleted(completed)
if completed.run.event_name == HookEventName::PreCompact =>
{
Some(completed.clone())
}
_ => None,
})
.await;
assert_eq!(completed.run.status, HookRunStatus::Failed);
wait_for_event(&codex, |ev| matches!(ev, EventMsg::Warning(_))).await;
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
let requests = request_log.requests();
assert_eq!(
requests.len(),
2,
"unsupported PreCompact block output should not prevent the compact request"
);
let hook_inputs = read_hook_inputs(&test.codex_home_path().join("pre_compact_block_log.jsonl"));
assert_eq!(hook_inputs.len(), 1);
let input = &hook_inputs[0];
assert_eq!(input["hook_event_name"], "PreCompact");
assert_eq!(input["trigger"], "manual");
assert!(input.get("reason").is_none());
assert!(input.get("phase").is_none());
assert!(input.get("implementation").is_none());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn compact_hooks_respect_matchers_and_post_runs_after_compaction() {
skip_if_no_network!();
let server = start_mock_server().await;
let first_turn = sse(vec![
ev_assistant_message("m0", FIRST_REPLY),
ev_completed_with_tokens("r0", /*total_tokens*/ 80),
]);
let compact_turn = sse(vec![
ev_assistant_message("m1", SUMMARY_TEXT),
ev_completed_with_tokens("r1", /*total_tokens*/ 100),
]);
let request_log = mount_sse_sequence(&server, vec![first_turn, compact_turn]).await;
let model_provider = non_openai_model_provider(&server);
let mut builder = test_codex()
.with_pre_build_hook(write_matching_compact_hooks)
.with_config(move |config| {
config.model_provider = model_provider;
trust_discovered_hooks(config);
set_test_compact_prompt(config);
});
let test = builder.build(&server).await.expect("create conversation");
let codex = test.codex.clone();
codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "hello before matched compact".to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await
.expect("submit first user turn");
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
codex.submit(Op::Compact).await.expect("trigger compact");
wait_for_event(&codex, |ev| matches!(ev, EventMsg::Warning(_))).await;
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
assert_eq!(request_log.requests().len(), 2);
assert!(
!test
.codex_home_path()
.join("pre_compact_auto_log.jsonl")
.exists(),
"auto matcher should not run for manual compaction"
);
let hook_inputs =
read_hook_inputs(&test.codex_home_path().join("post_compact_manual_log.jsonl"));
assert_eq!(hook_inputs.len(), 1);
let input = &hook_inputs[0];
assert_eq!(input["hook_event_name"], "PostCompact");
assert_eq!(input["trigger"], "manual");
assert!(input.get("compact_summary").is_none());
assert!(input.get("status").is_none());
assert!(input.get("error").is_none());
assert!(input.get("reason").is_none());
assert!(input.get("phase").is_none());
assert!(input.get("implementation").is_none());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn manual_compact_uses_custom_prompt() {
skip_if_no_network!();
+157
View File
@@ -0,0 +1,157 @@
#![allow(clippy::expect_used, clippy::unwrap_used)]
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use anyhow::Result;
use codex_config::config_toml::ProjectConfig;
use codex_protocol::config_types::TrustLevel;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::user_input::UserInput;
use core_test_support::responses;
use core_test_support::responses::ResponsesRequest;
use core_test_support::responses::mount_sse_sequence;
use core_test_support::responses::start_mock_server;
use core_test_support::test_codex::TestCodex;
use core_test_support::test_codex::test_codex;
use core_test_support::test_codex::turn_permission_fields;
use core_test_support::wait_for_event;
use tokio::time::timeout;
fn enable_trusted_project(config: &mut codex_core::config::Config) {
config.active_project = ProjectConfig {
trust_level: Some(TrustLevel::Trusted),
};
}
fn write_skill(home: &Path, name: &str, description: &str, body: &str) -> PathBuf {
let skill_dir = home.join("skills").join(name);
fs::create_dir_all(&skill_dir).expect("create skill dir");
let contents = format!("---\nname: {name}\ndescription: {description}\n---\n\n{body}\n");
let path = skill_dir.join("SKILL.md");
fs::write(&path, contents).expect("write skill");
path
}
fn contains_skill_body(request: &ResponsesRequest, skill_body: &str) -> bool {
request
.message_input_texts("user")
.iter()
.any(|text| text.contains(skill_body) && text.contains("<skill>"))
}
async fn submit_skill_turn(test: &TestCodex, skill_path: PathBuf, prompt: &str) -> Result<()> {
let session_model = test.session_configured.model.clone();
let (sandbox_policy, permission_profile) =
turn_permission_fields(PermissionProfile::Disabled, test.cwd_path());
test.codex
.submit(Op::UserTurn {
environments: None,
items: vec![
UserInput::Text {
text: prompt.to_string(),
text_elements: Vec::new(),
},
UserInput::Skill {
name: "demo".to_string(),
path: skill_path,
},
],
final_output_json_schema: None,
cwd: test.cwd_path().to_path_buf(),
approval_policy: AskForApproval::Never,
approvals_reviewer: None,
sandbox_policy,
permission_profile,
model: session_model,
effort: None,
summary: None,
service_tier: None,
collaboration_mode: None,
personality: None,
})
.await?;
wait_for_event(test.codex.as_ref(), |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn live_skills_reload_refreshes_skill_cache_after_skill_change() -> Result<()> {
let server = start_mock_server().await;
let responses = mount_sse_sequence(
&server,
vec![
responses::sse(vec![responses::ev_completed("resp-1")]),
responses::sse(vec![responses::ev_completed("resp-2")]),
],
)
.await;
let skill_v1 = "skill body v1";
let skill_v2 = "skill body v2";
let mut builder = test_codex()
.with_pre_build_hook(move |home| {
write_skill(home, "demo", "demo skill", skill_v1);
})
.with_config(|config| {
enable_trusted_project(config);
});
let test = builder.build(&server).await?;
let skill_path = dunce::canonicalize(test.codex_home_path().join("skills/demo/SKILL.md"))?;
submit_skill_turn(&test, skill_path.clone(), "please use $demo").await?;
let first_request = responses
.requests()
.first()
.cloned()
.expect("first request captured");
assert!(
contains_skill_body(&first_request, skill_v1),
"expected initial skill body in request"
);
write_skill(test.codex_home_path(), "demo", "demo skill", skill_v2);
let saw_skills_update = timeout(Duration::from_secs(5), async {
loop {
match test.codex.next_event().await {
Ok(event) => {
if matches!(event.msg, EventMsg::SkillsUpdateAvailable) {
break;
}
}
Err(err) => panic!("event stream ended unexpectedly: {err}"),
}
}
})
.await;
if saw_skills_update.is_err() {
// Some environments do not reliably surface file watcher events for
// skill changes. Clear the cache explicitly so we can still validate
// that the updated skill body is injected on the next turn.
test.thread_manager.skills_manager().clear_cache();
}
submit_skill_turn(&test, skill_path.clone(), "please use $demo again").await?;
let last_request = responses
.last_request()
.expect("request captured after skill update");
assert!(
contains_skill_body(&last_request, skill_v2),
"expected updated skill body after reload"
);
Ok(())
}
+1
View File
@@ -57,6 +57,7 @@ mod image_rollout;
mod items;
mod json_result;
mod live_cli;
mod live_reload;
mod model_overrides;
mod model_switching;
mod model_visible_layout;
@@ -7,6 +7,8 @@
"PreToolUse",
"PermissionRequest",
"PostToolUse",
"PreCompact",
"PostCompact",
"SessionStart",
"UserPromptSubmit",
"Stop"
@@ -0,0 +1,52 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": false,
"definitions": {
"NullableString": {
"type": [
"string",
"null"
]
}
},
"properties": {
"cwd": {
"type": "string"
},
"hook_event_name": {
"const": "PostCompact",
"type": "string"
},
"model": {
"type": "string"
},
"session_id": {
"type": "string"
},
"transcript_path": {
"$ref": "#/definitions/NullableString"
},
"trigger": {
"enum": [
"manual",
"auto"
],
"type": "string"
},
"turn_id": {
"description": "Codex extension: expose the active turn id to internal turn-scoped hooks.",
"type": "string"
}
},
"required": [
"cwd",
"hook_event_name",
"model",
"session_id",
"transcript_path",
"trigger",
"turn_id"
],
"title": "post-compact.command.input",
"type": "object"
}
@@ -0,0 +1,24 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": false,
"properties": {
"continue": {
"default": true,
"type": "boolean"
},
"stopReason": {
"default": null,
"type": "string"
},
"suppressOutput": {
"default": false,
"type": "boolean"
},
"systemMessage": {
"default": null,
"type": "string"
}
},
"title": "post-compact.command.output",
"type": "object"
}
@@ -13,6 +13,8 @@
"PreToolUse",
"PermissionRequest",
"PostToolUse",
"PreCompact",
"PostCompact",
"SessionStart",
"UserPromptSubmit",
"Stop"
@@ -0,0 +1,52 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": false,
"definitions": {
"NullableString": {
"type": [
"string",
"null"
]
}
},
"properties": {
"cwd": {
"type": "string"
},
"hook_event_name": {
"const": "PreCompact",
"type": "string"
},
"model": {
"type": "string"
},
"session_id": {
"type": "string"
},
"transcript_path": {
"$ref": "#/definitions/NullableString"
},
"trigger": {
"enum": [
"manual",
"auto"
],
"type": "string"
},
"turn_id": {
"description": "Codex extension: expose the active turn id to internal turn-scoped hooks.",
"type": "string"
}
},
"required": [
"cwd",
"hook_event_name",
"model",
"session_id",
"transcript_path",
"trigger",
"turn_id"
],
"title": "pre-compact.command.input",
"type": "object"
}
@@ -0,0 +1,24 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": false,
"properties": {
"continue": {
"default": true,
"type": "boolean"
},
"stopReason": {
"default": null,
"type": "string"
},
"suppressOutput": {
"default": false,
"type": "boolean"
},
"systemMessage": {
"default": null,
"type": "string"
}
},
"title": "pre-compact.command.output",
"type": "object"
}
@@ -7,6 +7,8 @@
"PreToolUse",
"PermissionRequest",
"PostToolUse",
"PreCompact",
"PostCompact",
"SessionStart",
"UserPromptSubmit",
"Stop"
@@ -7,6 +7,8 @@
"PreToolUse",
"PermissionRequest",
"PostToolUse",
"PreCompact",
"PostCompact",
"SessionStart",
"UserPromptSubmit",
"Stop"
@@ -13,6 +13,8 @@
"PreToolUse",
"PermissionRequest",
"PostToolUse",
"PreCompact",
"PostCompact",
"SessionStart",
"UserPromptSubmit",
"Stop"
+2
View File
@@ -511,6 +511,8 @@ fn hook_event_key_label(event_name: codex_protocol::protocol::HookEventName) ->
codex_protocol::protocol::HookEventName::PreToolUse => "pre_tool_use",
codex_protocol::protocol::HookEventName::PermissionRequest => "permission_request",
codex_protocol::protocol::HookEventName::PostToolUse => "post_tool_use",
codex_protocol::protocol::HookEventName::PreCompact => "pre_compact",
codex_protocol::protocol::HookEventName::PostCompact => "post_compact",
codex_protocol::protocol::HookEventName::SessionStart => "session_start",
codex_protocol::protocol::HookEventName::UserPromptSubmit => "user_prompt_submit",
codex_protocol::protocol::HookEventName::Stop => "stop",
+28 -1
View File
@@ -46,7 +46,9 @@ pub(crate) fn select_handlers_for_matcher_inputs(
HookEventName::PreToolUse
| HookEventName::PermissionRequest
| HookEventName::PostToolUse
| HookEventName::SessionStart => {
| HookEventName::SessionStart
| HookEventName::PreCompact
| HookEventName::PostCompact => {
if matcher_inputs.is_empty() {
matches_matcher(handler.matcher.as_deref(), /*input*/ None)
} else {
@@ -132,6 +134,8 @@ fn scope_for_event(event_name: HookEventName) -> HookScope {
HookEventName::PreToolUse
| HookEventName::PermissionRequest
| HookEventName::PostToolUse
| HookEventName::PreCompact
| HookEventName::PostCompact
| HookEventName::UserPromptSubmit
| HookEventName::Stop => HookScope::Turn,
}
@@ -215,6 +219,29 @@ mod tests {
assert_eq!(selected[1].display_order, 1);
}
#[test]
fn compact_hooks_match_trigger() {
let handlers = vec![
make_handler(
HookEventName::PreCompact,
Some("manual"),
"echo manual",
/*display_order*/ 0,
),
make_handler(
HookEventName::PreCompact,
Some("auto"),
"echo auto",
/*display_order*/ 1,
),
];
let selected = select_handlers(&handlers, HookEventName::PreCompact, Some("manual"));
assert_eq!(selected.len(), 1);
assert_eq!(selected[0].display_order, 0);
}
#[test]
fn pre_tool_use_matches_tool_name() {
let handlers = vec![
+25
View File
@@ -6,6 +6,10 @@ pub(crate) mod schema_loader;
use std::collections::HashMap;
use crate::events::compact::PostCompactRequest;
use crate::events::compact::PreCompactOutcome;
use crate::events::compact::PreCompactRequest;
use crate::events::compact::StatelessHookOutcome;
use crate::events::permission_request::PermissionRequestOutcome;
use crate::events::permission_request::PermissionRequestRequest;
use crate::events::post_tool_use::PostToolUseOutcome;
@@ -63,6 +67,8 @@ impl ConfiguredHandler {
codex_protocol::protocol::HookEventName::PreToolUse => "pre-tool-use",
codex_protocol::protocol::HookEventName::PermissionRequest => "permission-request",
codex_protocol::protocol::HookEventName::PostToolUse => "post-tool-use",
codex_protocol::protocol::HookEventName::PreCompact => "pre-compact",
codex_protocol::protocol::HookEventName::PostCompact => "post-compact",
codex_protocol::protocol::HookEventName::SessionStart => "session-start",
codex_protocol::protocol::HookEventName::UserPromptSubmit => "user-prompt-submit",
codex_protocol::protocol::HookEventName::Stop => "stop",
@@ -198,6 +204,25 @@ impl ClaudeHooksEngine {
outcome
}
pub(crate) fn preview_pre_compact(&self, request: &PreCompactRequest) -> Vec<HookRunSummary> {
crate::events::compact::preview_pre(&self.handlers, request)
}
pub(crate) async fn run_pre_compact(&self, request: PreCompactRequest) -> PreCompactOutcome {
crate::events::compact::run_pre(&self.handlers, &self.shell, request).await
}
pub(crate) fn preview_post_compact(&self, request: &PostCompactRequest) -> Vec<HookRunSummary> {
crate::events::compact::preview_post(&self.handlers, request)
}
pub(crate) async fn run_post_compact(
&self,
request: PostCompactRequest,
) -> StatelessHookOutcome {
crate::events::compact::run_post(&self.handlers, &self.shell, request).await
}
pub(crate) fn preview_user_prompt_submit(
&self,
request: &UserPromptSubmitRequest,
@@ -60,12 +60,26 @@ pub(crate) struct StopOutput {
pub invalid_block_reason: Option<String>,
}
#[derive(Debug, Clone)]
pub(crate) struct PreCompactOutput {
pub universal: UniversalOutput,
pub invalid_reason: Option<String>,
}
#[derive(Debug, Clone)]
pub(crate) struct StatelessHookOutput {
pub universal: UniversalOutput,
pub invalid_reason: Option<String>,
}
use crate::schema::BlockDecisionWire;
use crate::schema::HookUniversalOutputWire;
use crate::schema::PermissionRequestBehaviorWire;
use crate::schema::PermissionRequestCommandOutputWire;
use crate::schema::PermissionRequestDecisionWire;
use crate::schema::PostCompactCommandOutputWire;
use crate::schema::PostToolUseCommandOutputWire;
use crate::schema::PreCompactCommandOutputWire;
use crate::schema::PreToolUseCommandOutputWire;
use crate::schema::PreToolUseDecisionWire;
use crate::schema::PreToolUsePermissionDecisionWire;
@@ -191,6 +205,24 @@ pub(crate) fn parse_post_tool_use(stdout: &str) -> Option<PostToolUseOutput> {
})
}
pub(crate) fn parse_pre_compact(stdout: &str) -> Option<PreCompactOutput> {
let wire: PreCompactCommandOutputWire = parse_json(stdout)?;
let universal = UniversalOutput::from(wire.universal);
Some(PreCompactOutput {
universal,
invalid_reason: None,
})
}
pub(crate) fn parse_post_compact(stdout: &str) -> Option<StatelessHookOutput> {
let wire: PostCompactCommandOutputWire = parse_json(stdout)?;
let universal = UniversalOutput::from(wire.universal);
Some(StatelessHookOutput {
universal,
invalid_reason: None,
})
}
pub(crate) fn parse_user_prompt_submit(stdout: &str) -> Option<UserPromptSubmitOutput> {
let wire: UserPromptSubmitCommandOutputWire = parse_json(stdout)?;
let should_block = matches!(wire.decision, Some(BlockDecisionWire::Block));
@@ -261,6 +293,11 @@ where
serde_json::from_value(value).ok()
}
pub(crate) fn looks_like_json(stdout: &str) -> bool {
let trimmed = stdout.trim_start();
trimmed.starts_with('{') || trimmed.starts_with('[')
}
fn invalid_block_message(event_name: &str) -> String {
format!("{event_name} hook returned decision:block without a non-empty reason")
}
@@ -8,8 +8,12 @@ pub(crate) struct GeneratedHookSchemas {
pub post_tool_use_command_output: Value,
pub permission_request_command_input: Value,
pub permission_request_command_output: Value,
pub post_compact_command_input: Value,
pub post_compact_command_output: Value,
pub pre_tool_use_command_input: Value,
pub pre_tool_use_command_output: Value,
pub pre_compact_command_input: Value,
pub pre_compact_command_output: Value,
pub session_start_command_input: Value,
pub session_start_command_output: Value,
pub user_prompt_submit_command_input: Value,
@@ -37,6 +41,14 @@ pub(crate) fn generated_hook_schemas() -> &'static GeneratedHookSchemas {
"permission-request.command.output",
include_str!("../../schema/generated/permission-request.command.output.schema.json"),
),
post_compact_command_input: parse_json_schema(
"post-compact.command.input",
include_str!("../../schema/generated/post-compact.command.input.schema.json"),
),
post_compact_command_output: parse_json_schema(
"post-compact.command.output",
include_str!("../../schema/generated/post-compact.command.output.schema.json"),
),
pre_tool_use_command_input: parse_json_schema(
"pre-tool-use.command.input",
include_str!("../../schema/generated/pre-tool-use.command.input.schema.json"),
@@ -45,6 +57,14 @@ pub(crate) fn generated_hook_schemas() -> &'static GeneratedHookSchemas {
"pre-tool-use.command.output",
include_str!("../../schema/generated/pre-tool-use.command.output.schema.json"),
),
pre_compact_command_input: parse_json_schema(
"pre-compact.command.input",
include_str!("../../schema/generated/pre-compact.command.input.schema.json"),
),
pre_compact_command_output: parse_json_schema(
"pre-compact.command.output",
include_str!("../../schema/generated/pre-compact.command.output.schema.json"),
),
session_start_command_input: parse_json_schema(
"session-start.command.input",
include_str!("../../schema/generated/session-start.command.input.schema.json"),
@@ -90,8 +110,12 @@ mod tests {
assert_eq!(schemas.post_tool_use_command_output["type"], "object");
assert_eq!(schemas.permission_request_command_input["type"], "object");
assert_eq!(schemas.permission_request_command_output["type"], "object");
assert_eq!(schemas.post_compact_command_input["type"], "object");
assert_eq!(schemas.post_compact_command_output["type"], "object");
assert_eq!(schemas.pre_tool_use_command_input["type"], "object");
assert_eq!(schemas.pre_tool_use_command_output["type"], "object");
assert_eq!(schemas.pre_compact_command_input["type"], "object");
assert_eq!(schemas.pre_compact_command_output["type"], "object");
assert_eq!(schemas.session_start_command_input["type"], "object");
assert_eq!(schemas.session_start_command_output["type"], "object");
assert_eq!(schemas.user_prompt_submit_command_input["type"], "object");
+11 -1
View File
@@ -103,7 +103,9 @@ pub(crate) fn matcher_pattern_for_event(
HookEventName::PreToolUse
| HookEventName::PermissionRequest
| HookEventName::PostToolUse
| HookEventName::SessionStart => matcher,
| HookEventName::SessionStart
| HookEventName::PreCompact
| HookEventName::PostCompact => matcher,
HookEventName::UserPromptSubmit | HookEventName::Stop => None,
}
}
@@ -267,5 +269,13 @@ mod tests {
matcher_pattern_for_event(HookEventName::SessionStart, Some("startup|resume")),
Some("startup|resume")
);
assert_eq!(
matcher_pattern_for_event(HookEventName::PreCompact, Some("^auto$")),
Some("^auto$")
);
assert_eq!(
matcher_pattern_for_event(HookEventName::PostCompact, Some("manual|auto")),
Some("manual|auto")
);
}
}
+608
View File
@@ -0,0 +1,608 @@
use std::path::PathBuf;
use codex_protocol::ThreadId;
use codex_protocol::protocol::HookCompletedEvent;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_protocol::protocol::HookRunSummary;
use codex_utils_absolute_path::AbsolutePathBuf;
use super::common;
use crate::engine::CommandShell;
use crate::engine::ConfiguredHandler;
use crate::engine::command_runner::CommandRunResult;
use crate::engine::dispatcher;
use crate::engine::output_parser;
use crate::schema::PostCompactCommandInput;
use crate::schema::PreCompactCommandInput;
#[derive(Debug, Clone)]
pub struct PreCompactRequest {
pub session_id: ThreadId,
pub turn_id: String,
pub cwd: AbsolutePathBuf,
pub transcript_path: Option<PathBuf>,
pub model: String,
pub trigger: String,
}
#[derive(Debug, Clone)]
pub struct PostCompactRequest {
pub session_id: ThreadId,
pub turn_id: String,
pub cwd: AbsolutePathBuf,
pub transcript_path: Option<PathBuf>,
pub model: String,
pub trigger: String,
}
#[derive(Debug)]
pub struct StatelessHookOutcome {
pub hook_events: Vec<HookCompletedEvent>,
pub should_stop: bool,
pub stop_reason: Option<String>,
}
#[derive(Debug)]
pub struct PreCompactOutcome {
pub hook_events: Vec<HookCompletedEvent>,
pub should_stop: bool,
pub stop_reason: Option<String>,
}
pub(crate) fn preview_pre(
handlers: &[ConfiguredHandler],
request: &PreCompactRequest,
) -> Vec<HookRunSummary> {
dispatcher::select_handlers(
handlers,
HookEventName::PreCompact,
Some(request.trigger.as_str()),
)
.into_iter()
.map(|handler| dispatcher::running_summary(&handler))
.collect()
}
pub(crate) async fn run_pre(
handlers: &[ConfiguredHandler],
shell: &CommandShell,
request: PreCompactRequest,
) -> PreCompactOutcome {
let matched = dispatcher::select_handlers(
handlers,
HookEventName::PreCompact,
Some(request.trigger.as_str()),
);
if matched.is_empty() {
return PreCompactOutcome {
hook_events: Vec::new(),
should_stop: false,
stop_reason: None,
};
}
let input_json = match pre_command_input_json(&request) {
Ok(input_json) => input_json,
Err(error) => {
return PreCompactOutcome {
hook_events: common::serialization_failure_hook_events(
matched,
Some(request.turn_id),
format!("failed to serialize pre compact hook input: {error}"),
),
should_stop: false,
stop_reason: None,
};
}
};
let results = dispatcher::execute_handlers(
shell,
matched,
input_json,
request.cwd.as_path(),
Some(request.turn_id),
parse_pre_completed,
)
.await;
let should_stop = results.iter().any(|result| result.data.should_stop);
let stop_reason = results
.iter()
.find_map(|result| result.data.stop_reason.clone());
PreCompactOutcome {
hook_events: results.into_iter().map(|result| result.completed).collect(),
should_stop,
stop_reason,
}
}
fn pre_command_input_json(request: &PreCompactRequest) -> Result<String, serde_json::Error> {
serde_json::to_string(&PreCompactCommandInput {
session_id: request.session_id.to_string(),
turn_id: request.turn_id.clone(),
transcript_path: crate::schema::NullableString::from_path(request.transcript_path.clone()),
cwd: request.cwd.display().to_string(),
hook_event_name: "PreCompact".to_string(),
model: request.model.clone(),
trigger: request.trigger.clone(),
})
}
pub(crate) fn preview_post(
handlers: &[ConfiguredHandler],
request: &PostCompactRequest,
) -> Vec<HookRunSummary> {
dispatcher::select_handlers(
handlers,
HookEventName::PostCompact,
Some(request.trigger.as_str()),
)
.into_iter()
.map(|handler| dispatcher::running_summary(&handler))
.collect()
}
pub(crate) async fn run_post(
handlers: &[ConfiguredHandler],
shell: &CommandShell,
request: PostCompactRequest,
) -> StatelessHookOutcome {
let matched = dispatcher::select_handlers(
handlers,
HookEventName::PostCompact,
Some(request.trigger.as_str()),
);
if matched.is_empty() {
return StatelessHookOutcome {
hook_events: Vec::new(),
should_stop: false,
stop_reason: None,
};
}
let input_json = match post_command_input_json(&request) {
Ok(input_json) => input_json,
Err(error) => {
return StatelessHookOutcome {
hook_events: common::serialization_failure_hook_events(
matched,
Some(request.turn_id),
format!("failed to serialize post compact hook input: {error}"),
),
should_stop: false,
stop_reason: None,
};
}
};
let results = dispatcher::execute_handlers(
shell,
matched,
input_json,
request.cwd.as_path(),
Some(request.turn_id),
parse_post_completed,
)
.await;
let should_stop = results.iter().any(|result| result.data.should_stop);
let stop_reason = results
.iter()
.find_map(|result| result.data.stop_reason.clone());
StatelessHookOutcome {
hook_events: results.into_iter().map(|result| result.completed).collect(),
should_stop,
stop_reason,
}
}
fn post_command_input_json(request: &PostCompactRequest) -> Result<String, serde_json::Error> {
serde_json::to_string(&PostCompactCommandInput {
session_id: request.session_id.to_string(),
turn_id: request.turn_id.clone(),
transcript_path: crate::schema::NullableString::from_path(request.transcript_path.clone()),
cwd: request.cwd.display().to_string(),
hook_event_name: "PostCompact".to_string(),
model: request.model.clone(),
trigger: request.trigger.clone(),
})
}
#[derive(Default)]
struct CompactHandlerData {
should_stop: bool,
stop_reason: Option<String>,
}
fn parse_pre_completed(
handler: &ConfiguredHandler,
run_result: CommandRunResult,
turn_id: Option<String>,
) -> dispatcher::ParsedHandler<CompactHandlerData> {
let mut entries = Vec::new();
let mut status = HookRunStatus::Completed;
let mut should_stop = false;
let mut stop_reason = None;
match run_result.error.as_deref() {
Some(error) => {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
text: error.to_string(),
});
}
None => match run_result.exit_code {
Some(0) => {
let trimmed_stdout = run_result.stdout.trim();
if trimmed_stdout.is_empty() {
} else if let Some(parsed) = output_parser::parse_pre_compact(&run_result.stdout) {
if let Some(system_message) = parsed.universal.system_message {
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Warning,
text: system_message,
});
}
let _ = parsed.universal.suppress_output;
if !parsed.universal.continue_processing {
status = HookRunStatus::Stopped;
should_stop = true;
stop_reason = parsed.universal.stop_reason.clone();
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Stop,
text: parsed
.universal
.stop_reason
.unwrap_or_else(|| "PreCompact hook stopped execution".to_string()),
});
} else if let Some(invalid_reason) = parsed.invalid_reason {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
text: invalid_reason,
});
}
} else if output_parser::looks_like_json(&run_result.stdout) {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
text: "hook returned invalid PreCompact hook JSON output".to_string(),
});
}
}
Some(code) => {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
text: common::trimmed_non_empty(&run_result.stderr)
.unwrap_or_else(|| format!("hook exited with code {code}")),
});
}
None => {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
text: "hook process terminated without an exit code".to_string(),
});
}
},
}
dispatcher::ParsedHandler {
completed: HookCompletedEvent {
turn_id,
run: dispatcher::completed_summary(handler, &run_result, status, entries),
},
data: CompactHandlerData {
should_stop,
stop_reason,
},
}
}
fn parse_post_completed(
handler: &ConfiguredHandler,
run_result: CommandRunResult,
turn_id: Option<String>,
) -> dispatcher::ParsedHandler<CompactHandlerData> {
parse_completed(
handler,
run_result,
turn_id,
"PostCompact",
output_parser::parse_post_compact,
)
}
fn parse_completed(
handler: &ConfiguredHandler,
run_result: CommandRunResult,
turn_id: Option<String>,
event_label: &'static str,
parse_output: fn(&str) -> Option<output_parser::StatelessHookOutput>,
) -> dispatcher::ParsedHandler<CompactHandlerData> {
let mut entries = Vec::new();
let mut status = HookRunStatus::Completed;
let mut should_stop = false;
let mut stop_reason = None;
match run_result.error.as_deref() {
Some(error) => {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
text: error.to_string(),
});
}
None => match run_result.exit_code {
Some(0) => {
let trimmed_stdout = run_result.stdout.trim();
if trimmed_stdout.is_empty() {
} else if let Some(parsed) = parse_output(&run_result.stdout) {
if let Some(system_message) = parsed.universal.system_message {
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Warning,
text: system_message,
});
}
let _ = parsed.universal.suppress_output;
if !parsed.universal.continue_processing {
status = HookRunStatus::Stopped;
should_stop = true;
stop_reason = parsed.universal.stop_reason.clone();
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Stop,
text: parsed
.universal
.stop_reason
.unwrap_or_else(|| format!("{event_label} hook stopped execution")),
});
} else if let Some(invalid_reason) = parsed.invalid_reason {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
text: invalid_reason,
});
}
} else if output_parser::looks_like_json(&run_result.stdout) {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
text: format!("hook returned invalid {event_label} hook JSON output"),
});
}
}
Some(code) => {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
text: common::trimmed_non_empty(&run_result.stderr)
.unwrap_or_else(|| format!("hook exited with code {code}")),
});
}
None => {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
text: "hook process terminated without an exit code".to_string(),
});
}
},
}
dispatcher::ParsedHandler {
completed: HookCompletedEvent {
turn_id,
run: dispatcher::completed_summary(handler, &run_result, status, entries),
},
data: CompactHandlerData {
should_stop,
stop_reason,
},
}
}
#[cfg(test)]
mod tests {
use codex_protocol::ThreadId;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use serde_json::json;
use super::parse_post_completed;
use super::parse_pre_completed;
use super::post_command_input_json;
use super::pre_command_input_json;
use crate::engine::ConfiguredHandler;
use crate::engine::command_runner::CommandRunResult;
#[test]
fn pre_compact_input_includes_lifecycle_metadata() {
let input_json = pre_command_input_json(&pre_request()).expect("serialize command input");
let input: serde_json::Value =
serde_json::from_str(&input_json).expect("parse command input");
assert_eq!(
input,
json!({
"session_id": pre_request().session_id.to_string(),
"turn_id": "turn-1",
"transcript_path": null,
"cwd": test_path_buf("/tmp").display().to_string(),
"hook_event_name": "PreCompact",
"model": "gpt-test",
"trigger": "manual",
})
);
}
#[test]
fn post_compact_input_includes_lifecycle_metadata() {
let input_json = post_command_input_json(&post_request()).expect("serialize command input");
let input: serde_json::Value =
serde_json::from_str(&input_json).expect("parse command input");
assert_eq!(
input,
json!({
"session_id": post_request().session_id.to_string(),
"turn_id": "turn-1",
"transcript_path": null,
"cwd": test_path_buf("/tmp").display().to_string(),
"hook_event_name": "PostCompact",
"model": "gpt-test",
"trigger": "manual",
})
);
}
#[test]
fn block_decision_is_not_supported_for_pre_compact() {
let parsed = parse_pre_completed(
&handler(HookEventName::PreCompact),
run_result(
Some(0),
r#"{"decision":"block","reason":"policy blocked compaction"}"#,
"",
),
Some("turn-1".to_string()),
);
assert_eq!(parsed.completed.run.status, HookRunStatus::Failed);
assert_eq!(
parsed.completed.run.entries,
vec![HookOutputEntry {
kind: HookOutputEntryKind::Error,
text: "hook returned invalid PreCompact hook JSON output".to_string(),
}]
);
}
#[test]
fn continue_false_stops_before_compaction() {
let parsed = parse_pre_completed(
&handler(HookEventName::PreCompact),
run_result(Some(0), r#"{"continue":false,"stopReason":"nope"}"#, ""),
Some("turn-1".to_string()),
);
assert_eq!(parsed.completed.run.status, HookRunStatus::Stopped);
assert_eq!(parsed.data.should_stop, true);
assert_eq!(parsed.data.stop_reason, Some("nope".to_string()));
assert_eq!(
parsed.completed.run.entries,
vec![HookOutputEntry {
kind: HookOutputEntryKind::Stop,
text: "nope".to_string(),
}]
);
}
#[test]
fn post_compact_continue_false_stops_after_compaction() {
let parsed = parse_post_completed(
&handler(HookEventName::PostCompact),
run_result(
Some(0),
r#"{"continue":false,"stopReason":"pause after compact"}"#,
"",
),
Some("turn-1".to_string()),
);
assert_eq!(parsed.completed.run.status, HookRunStatus::Stopped);
assert_eq!(parsed.data.should_stop, true);
assert_eq!(
parsed.data.stop_reason,
Some("pause after compact".to_string())
);
assert_eq!(
parsed.completed.run.entries,
vec![HookOutputEntry {
kind: HookOutputEntryKind::Stop,
text: "pause after compact".to_string(),
}]
);
}
#[test]
fn pre_compact_ignores_plain_stdout() {
let parsed = parse_pre_completed(
&handler(HookEventName::PreCompact),
run_result(Some(0), "checking compact policy\n", ""),
Some("turn-1".to_string()),
);
assert_eq!(parsed.completed.run.status, HookRunStatus::Completed);
assert_eq!(parsed.completed.run.entries, Vec::new());
}
#[test]
fn post_compact_ignores_plain_stdout() {
let parsed = parse_post_completed(
&handler(HookEventName::PostCompact),
run_result(Some(0), "logged compact summary\n", ""),
Some("turn-1".to_string()),
);
assert_eq!(parsed.completed.run.status, HookRunStatus::Completed);
assert_eq!(parsed.completed.run.entries, Vec::new());
}
fn pre_request() -> super::PreCompactRequest {
super::PreCompactRequest {
session_id: ThreadId::from_string("00000000-0000-4000-8000-000000000001")
.expect("valid thread id"),
turn_id: "turn-1".to_string(),
cwd: test_path_buf("/tmp").abs(),
transcript_path: None,
model: "gpt-test".to_string(),
trigger: "manual".to_string(),
}
}
fn post_request() -> super::PostCompactRequest {
super::PostCompactRequest {
session_id: ThreadId::from_string("00000000-0000-4000-8000-000000000002")
.expect("valid thread id"),
turn_id: "turn-1".to_string(),
cwd: test_path_buf("/tmp").abs(),
transcript_path: None,
model: "gpt-test".to_string(),
trigger: "manual".to_string(),
}
}
fn handler(event_name: HookEventName) -> ConfiguredHandler {
ConfiguredHandler {
event_name,
matcher: None,
command: "python3 compact_hook.py".to_string(),
timeout_sec: 5,
status_message: Some("running compact hook".to_string()),
source_path: test_path_buf("/tmp/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::User,
display_order: 0,
env: std::collections::HashMap::new(),
}
}
fn run_result(exit_code: Option<i32>, stdout: &str, stderr: &str) -> CommandRunResult {
CommandRunResult {
started_at: 1_700_000_000,
completed_at: 1_700_000_001,
duration_ms: 12,
exit_code,
stdout: stdout.to_string(),
stderr: stderr.to_string(),
error: None,
}
}
}
+1
View File
@@ -1,4 +1,5 @@
pub(crate) mod common;
pub mod compact;
pub mod permission_request;
pub mod post_tool_use;
pub mod pre_tool_use;
@@ -232,7 +232,7 @@ fn parse_completed(
}
}
}
} else if trimmed_stdout.starts_with('{') || trimmed_stdout.starts_with('[') {
} else if output_parser::looks_like_json(&run_result.stdout) {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
+1 -1
View File
@@ -245,7 +245,7 @@ fn parse_completed(
feedback_messages_for_model.push(reason);
}
}
} else if trimmed_stdout.starts_with('{') || trimmed_stdout.starts_with('[') {
} else if output_parser::looks_like_json(&run_result.stdout) {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
+1 -1
View File
@@ -205,7 +205,7 @@ fn parse_completed(
});
}
}
} else if trimmed_stdout.starts_with('{') || trimmed_stdout.starts_with('[') {
} else if output_parser::looks_like_json(&run_result.stdout) {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
+1 -1
View File
@@ -190,7 +190,7 @@ fn parse_completed(
}
}
// Preserve plain-text context support without treating malformed JSON as context.
} else if trimmed_stdout.starts_with('{') || trimmed_stdout.starts_with('[') {
} else if output_parser::looks_like_json(&run_result.stdout) {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
@@ -194,7 +194,7 @@ fn parse_completed(
});
}
}
} else if trimmed_stdout.starts_with('{') || trimmed_stdout.starts_with('[') {
} else if output_parser::looks_like_json(&run_result.stdout) {
status = HookRunStatus::Failed;
entries.push(HookOutputEntry {
kind: HookOutputEntryKind::Error,
+13 -4
View File
@@ -9,10 +9,12 @@ mod types;
pub use engine::HookListEntry;
/// Hook event names as they appear in hooks JSON and config files.
pub const HOOK_EVENT_NAMES: [&str; 6] = [
pub const HOOK_EVENT_NAMES: [&str; 8] = [
"PreToolUse",
"PermissionRequest",
"PostToolUse",
"PreCompact",
"PostCompact",
"SessionStart",
"UserPromptSubmit",
"Stop",
@@ -21,14 +23,21 @@ pub const HOOK_EVENT_NAMES: [&str; 6] = [
/// Hook event names whose matcher fields are meaningful during dispatch.
///
/// Other events can appear in hooks JSON, but Codex ignores their matcher
/// fields because those events do not dispatch against a tool or session-start
/// source.
pub const HOOK_EVENT_NAMES_WITH_MATCHERS: [&str; 4] = [
/// fields because those events do not dispatch against a tool, compaction
/// trigger, or session-start source.
pub const HOOK_EVENT_NAMES_WITH_MATCHERS: [&str; 6] = [
"PreToolUse",
"PermissionRequest",
"PostToolUse",
"PreCompact",
"PostCompact",
"SessionStart",
];
pub use events::compact::PostCompactRequest;
pub use events::compact::PreCompactOutcome;
pub use events::compact::PreCompactRequest;
pub use events::compact::StatelessHookOutcome;
pub use events::permission_request::PermissionRequestDecision;
pub use events::permission_request::PermissionRequestOutcome;
pub use events::permission_request::PermissionRequestRequest;
+26
View File
@@ -5,6 +5,10 @@ use tokio::process::Command;
use crate::engine::ClaudeHooksEngine;
use crate::engine::CommandShell;
use crate::engine::HookListEntry;
use crate::events::compact::PostCompactRequest;
use crate::events::compact::PreCompactOutcome;
use crate::events::compact::PreCompactRequest;
use crate::events::compact::StatelessHookOutcome;
use crate::events::permission_request::PermissionRequestOutcome;
use crate::events::permission_request::PermissionRequestRequest;
use crate::events::post_tool_use::PostToolUseOutcome;
@@ -154,6 +158,28 @@ impl Hooks {
self.engine.run_post_tool_use(request).await
}
pub fn preview_pre_compact(
&self,
request: &PreCompactRequest,
) -> Vec<codex_protocol::protocol::HookRunSummary> {
self.engine.preview_pre_compact(request)
}
pub async fn run_pre_compact(&self, request: PreCompactRequest) -> PreCompactOutcome {
self.engine.run_pre_compact(request).await
}
pub fn preview_post_compact(
&self,
request: &PostCompactRequest,
) -> Vec<codex_protocol::protocol::HookRunSummary> {
self.engine.preview_post_compact(request)
}
pub async fn run_post_compact(&self, request: PostCompactRequest) -> StatelessHookOutcome {
self.engine.run_post_compact(request).await
}
pub fn preview_user_prompt_submit(
&self,
request: &UserPromptSubmitRequest,
+118
View File
@@ -17,8 +17,12 @@ const POST_TOOL_USE_INPUT_FIXTURE: &str = "post-tool-use.command.input.schema.js
const POST_TOOL_USE_OUTPUT_FIXTURE: &str = "post-tool-use.command.output.schema.json";
const PERMISSION_REQUEST_INPUT_FIXTURE: &str = "permission-request.command.input.schema.json";
const PERMISSION_REQUEST_OUTPUT_FIXTURE: &str = "permission-request.command.output.schema.json";
const POST_COMPACT_INPUT_FIXTURE: &str = "post-compact.command.input.schema.json";
const POST_COMPACT_OUTPUT_FIXTURE: &str = "post-compact.command.output.schema.json";
const PRE_TOOL_USE_INPUT_FIXTURE: &str = "pre-tool-use.command.input.schema.json";
const PRE_TOOL_USE_OUTPUT_FIXTURE: &str = "pre-tool-use.command.output.schema.json";
const PRE_COMPACT_INPUT_FIXTURE: &str = "pre-compact.command.input.schema.json";
const PRE_COMPACT_OUTPUT_FIXTURE: &str = "pre-compact.command.output.schema.json";
const SESSION_START_INPUT_FIXTURE: &str = "session-start.command.input.schema.json";
const SESSION_START_OUTPUT_FIXTURE: &str = "session-start.command.output.schema.json";
const USER_PROMPT_SUBMIT_INPUT_FIXTURE: &str = "user-prompt-submit.command.input.schema.json";
@@ -75,6 +79,10 @@ pub(crate) enum HookEventNameWire {
PermissionRequest,
#[serde(rename = "PostToolUse")]
PostToolUse,
#[serde(rename = "PreCompact")]
PreCompact,
#[serde(rename = "PostCompact")]
PostCompact,
#[serde(rename = "SessionStart")]
SessionStart,
#[serde(rename = "UserPromptSubmit")]
@@ -124,6 +132,24 @@ pub(crate) struct PermissionRequestCommandOutputWire {
pub hook_specific_output: Option<PermissionRequestHookSpecificOutputWire>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
#[schemars(rename = "pre-compact.command.output")]
pub(crate) struct PreCompactCommandOutputWire {
#[serde(flatten)]
pub universal: HookUniversalOutputWire,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
#[schemars(rename = "post-compact.command.output")]
pub(crate) struct PostCompactCommandOutputWire {
#[serde(flatten)]
pub universal: HookUniversalOutputWire,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
@@ -267,6 +293,38 @@ pub(crate) struct PostToolUseCommandInput {
pub tool_use_id: String,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(rename = "pre-compact.command.input")]
pub(crate) struct PreCompactCommandInput {
pub session_id: String,
/// Codex extension: expose the active turn id to internal turn-scoped hooks.
pub turn_id: String,
pub transcript_path: NullableString,
pub cwd: String,
#[schemars(schema_with = "pre_compact_hook_event_name_schema")]
pub hook_event_name: String,
pub model: String,
#[schemars(schema_with = "compaction_trigger_schema")]
pub trigger: String,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(rename = "post-compact.command.input")]
pub(crate) struct PostCompactCommandInput {
pub session_id: String,
/// Codex extension: expose the active turn id to internal turn-scoped hooks.
pub turn_id: String,
pub transcript_path: NullableString,
pub cwd: String,
#[schemars(schema_with = "post_compact_hook_event_name_schema")]
pub hook_event_name: String,
pub model: String,
#[schemars(schema_with = "compaction_trigger_schema")]
pub trigger: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
@@ -424,6 +482,22 @@ pub fn write_schema_fixtures(schema_root: &Path) -> anyhow::Result<()> {
&generated_dir.join(PERMISSION_REQUEST_OUTPUT_FIXTURE),
schema_json::<PermissionRequestCommandOutputWire>()?,
)?;
write_schema(
&generated_dir.join(POST_COMPACT_INPUT_FIXTURE),
schema_json::<PostCompactCommandInput>()?,
)?;
write_schema(
&generated_dir.join(POST_COMPACT_OUTPUT_FIXTURE),
schema_json::<PostCompactCommandOutputWire>()?,
)?;
write_schema(
&generated_dir.join(PRE_COMPACT_INPUT_FIXTURE),
schema_json::<PreCompactCommandInput>()?,
)?;
write_schema(
&generated_dir.join(PRE_COMPACT_OUTPUT_FIXTURE),
schema_json::<PreCompactCommandOutputWire>()?,
)?;
write_schema(
&generated_dir.join(PRE_TOOL_USE_INPUT_FIXTURE),
schema_json::<PreToolUseCommandInput>()?,
@@ -519,6 +593,14 @@ fn post_tool_use_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema {
string_const_schema("PostToolUse")
}
fn pre_compact_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema {
string_const_schema("PreCompact")
}
fn post_compact_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema {
string_const_schema("PostCompact")
}
fn pre_tool_use_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema {
string_const_schema("PreToolUse")
}
@@ -549,6 +631,10 @@ fn session_start_source_schema(_gen: &mut SchemaGenerator) -> Schema {
string_enum_schema(&["startup", "resume", "clear"])
}
fn compaction_trigger_schema(_gen: &mut SchemaGenerator) -> Schema {
string_enum_schema(&["manual", "auto"])
}
fn string_const_schema(value: &str) -> Schema {
let mut schema = SchemaObject {
instance_type: Some(InstanceType::String.into()),
@@ -580,12 +666,18 @@ fn default_continue() -> bool {
mod tests {
use super::PERMISSION_REQUEST_INPUT_FIXTURE;
use super::PERMISSION_REQUEST_OUTPUT_FIXTURE;
use super::POST_COMPACT_INPUT_FIXTURE;
use super::POST_COMPACT_OUTPUT_FIXTURE;
use super::POST_TOOL_USE_INPUT_FIXTURE;
use super::POST_TOOL_USE_OUTPUT_FIXTURE;
use super::PRE_COMPACT_INPUT_FIXTURE;
use super::PRE_COMPACT_OUTPUT_FIXTURE;
use super::PRE_TOOL_USE_INPUT_FIXTURE;
use super::PRE_TOOL_USE_OUTPUT_FIXTURE;
use super::PermissionRequestCommandInput;
use super::PostCompactCommandInput;
use super::PostToolUseCommandInput;
use super::PreCompactCommandInput;
use super::PreToolUseCommandInput;
use super::SESSION_START_INPUT_FIXTURE;
use super::SESSION_START_OUTPUT_FIXTURE;
@@ -615,6 +707,18 @@ mod tests {
PERMISSION_REQUEST_OUTPUT_FIXTURE => {
include_str!("../schema/generated/permission-request.command.output.schema.json")
}
POST_COMPACT_INPUT_FIXTURE => {
include_str!("../schema/generated/post-compact.command.input.schema.json")
}
POST_COMPACT_OUTPUT_FIXTURE => {
include_str!("../schema/generated/post-compact.command.output.schema.json")
}
PRE_COMPACT_INPUT_FIXTURE => {
include_str!("../schema/generated/pre-compact.command.input.schema.json")
}
PRE_COMPACT_OUTPUT_FIXTURE => {
include_str!("../schema/generated/pre-compact.command.output.schema.json")
}
PRE_TOOL_USE_INPUT_FIXTURE => {
include_str!("../schema/generated/pre-tool-use.command.input.schema.json")
}
@@ -658,6 +762,10 @@ mod tests {
POST_TOOL_USE_OUTPUT_FIXTURE,
PERMISSION_REQUEST_INPUT_FIXTURE,
PERMISSION_REQUEST_OUTPUT_FIXTURE,
POST_COMPACT_INPUT_FIXTURE,
POST_COMPACT_OUTPUT_FIXTURE,
PRE_COMPACT_INPUT_FIXTURE,
PRE_COMPACT_OUTPUT_FIXTURE,
PRE_TOOL_USE_INPUT_FIXTURE,
PRE_TOOL_USE_OUTPUT_FIXTURE,
SESSION_START_INPUT_FIXTURE,
@@ -688,6 +796,14 @@ mod tests {
.expect("serialize post tool use input schema"),
)
.expect("parse post tool use input schema");
let pre_compact: Value = serde_json::from_slice(
&schema_json::<PreCompactCommandInput>().expect("serialize pre compact input schema"),
)
.expect("parse pre compact input schema");
let post_compact: Value = serde_json::from_slice(
&schema_json::<PostCompactCommandInput>().expect("serialize post compact input schema"),
)
.expect("parse post compact input schema");
let permission_request: Value = serde_json::from_slice(
&schema_json::<PermissionRequestCommandInput>()
.expect("serialize permission request input schema"),
@@ -707,6 +823,8 @@ mod tests {
&pre_tool_use,
&permission_request,
&post_tool_use,
&pre_compact,
&post_compact,
&user_prompt_submit,
&stop,
] {
@@ -362,6 +362,7 @@ async fn run_codex_tool_session_inner(
| EventMsg::AgentMessageContentDelta(_)
| EventMsg::ReasoningContentDelta(_)
| EventMsg::ReasoningRawContentDelta(_)
| EventMsg::SkillsUpdateAvailable
| EventMsg::ExitedReviewMode(_)
| EventMsg::RequestUserInput(_)
| EventMsg::RequestPermissions(_)
+5
View File
@@ -1401,6 +1401,9 @@ pub enum EventMsg {
/// List of voices supported by realtime conversation streams.
RealtimeConversationListVoicesResponse(RealtimeConversationListVoicesResponseEvent),
/// Notification that skill data may have been updated and clients may want to reload.
SkillsUpdateAvailable,
PlanUpdate(UpdatePlanArgs),
TurnAborted(TurnAbortedEvent),
@@ -1454,6 +1457,8 @@ pub enum HookEventName {
PreToolUse,
PermissionRequest,
PostToolUse,
PreCompact,
PostCompact,
SessionStart,
UserPromptSubmit,
Stop,
@@ -260,6 +260,7 @@ pub(crate) fn tool_runtime_trace_event(event: &EventMsg) -> Option<ToolRuntimeTr
| EventMsg::PatchApplyUpdated(_)
| EventMsg::TurnDiff(_)
| EventMsg::RealtimeConversationListVoicesResponse(_)
| EventMsg::SkillsUpdateAvailable
| EventMsg::PlanUpdate(_)
| EventMsg::TurnAborted(_)
| EventMsg::ShutdownComplete
@@ -332,6 +333,7 @@ pub(crate) fn wrapped_protocol_event_type(event: &EventMsg) -> Option<&'static s
| EventMsg::PatchApplyEnd(_)
| EventMsg::TurnDiff(_)
| EventMsg::RealtimeConversationListVoicesResponse(_)
| EventMsg::SkillsUpdateAvailable
| EventMsg::PlanUpdate(_)
| EventMsg::EnteredReviewMode(_)
| EventMsg::ExitedReviewMode(_)
+1
View File
@@ -169,6 +169,7 @@ fn event_msg_persistence_mode(ev: &EventMsg) -> Option<EventPersistenceMode> {
| EventMsg::ReasoningContentDelta(_)
| EventMsg::ReasoningRawContentDelta(_)
| EventMsg::ImageGenerationBegin(_)
| EventMsg::SkillsUpdateAvailable
| EventMsg::CollabAgentSpawnBegin(_)
| EventMsg::CollabAgentInteractionBegin(_)
| EventMsg::CollabWaitingBegin(_)
@@ -662,6 +662,8 @@ fn event_label(event_name: HookEventName) -> &'static str {
HookEventName::PreToolUse => "PreToolUse",
HookEventName::PermissionRequest => "PermissionRequest",
HookEventName::PostToolUse => "PostToolUse",
HookEventName::PreCompact => "PreCompact",
HookEventName::PostCompact => "PostCompact",
HookEventName::SessionStart => "SessionStart",
HookEventName::UserPromptSubmit => "UserPromptSubmit",
HookEventName::Stop => "Stop",
@@ -673,6 +675,8 @@ fn event_description(event_name: HookEventName) -> &'static str {
HookEventName::PreToolUse => "Before a tool executes",
HookEventName::PermissionRequest => "When permission is requested",
HookEventName::PostToolUse => "After a tool executes",
HookEventName::PreCompact => "Before context compaction",
HookEventName::PostCompact => "After context compaction",
HookEventName::SessionStart => "When a new session starts",
HookEventName::UserPromptSubmit => "When the user submits a prompt",
HookEventName::Stop => "Right before Codex ends its turn",
@@ -10,6 +10,8 @@ expression: "render_lines(&view, 112)"
PreToolUse 2 1 Before a tool executes
PermissionRequest 1 1 When permission is requested
PostToolUse 0 0 After a tool executes
PreCompact 0 0 Before context compaction
PostCompact 0 0 After context compaction
SessionStart 0 0 When a new session starts
UserPromptSubmit 0 0 When the user submits a prompt
Stop 0 0 Right before Codex ends its turn
@@ -14,6 +14,8 @@ expression: "render_lines(&view, 112)"
PreToolUse 0 0 Before a tool executes
PermissionRequest 0 0 When permission is requested
PostToolUse 0 0 After a tool executes
PreCompact 0 0 Before context compaction
PostCompact 0 0 After context compaction
SessionStart 0 0 When a new session starts
UserPromptSubmit 0 0 When the user submits a prompt
Stop 0 0 Right before Codex ends its turn
@@ -10,6 +10,8 @@ expression: "render_lines(&view, 112)"
PreToolUse 1 0 1 Before a tool executes
PermissionRequest 0 0 0 When permission is requested
PostToolUse 0 0 0 After a tool executes
PreCompact 0 0 0 Before context compaction
PostCompact 0 0 0 After context compaction
SessionStart 0 0 0 When a new session starts
UserPromptSubmit 0 0 0 When the user submits a prompt
Stop 0 0 0 Right before Codex ends its turn
@@ -13,6 +13,8 @@ expression: popup
PreToolUse 0 0 Before a tool executes
PermissionRequest 0 0 When permission is requested
PostToolUse 0 0 After a tool executes
PreCompact 0 0 Before context compaction
PostCompact 0 0 After context compaction
SessionStart 0 0 When a new session starts
UserPromptSubmit 0 0 When the user submits a prompt
Stop 0 0 Right before Codex ends its turn
@@ -1677,6 +1677,8 @@ fn hook_event_label(event_name: codex_app_server_protocol::HookEventName) -> &'s
codex_app_server_protocol::HookEventName::PreToolUse => "PreToolUse",
codex_app_server_protocol::HookEventName::PermissionRequest => "PermissionRequest",
codex_app_server_protocol::HookEventName::PostToolUse => "PostToolUse",
codex_app_server_protocol::HookEventName::PreCompact => "PreCompact",
codex_app_server_protocol::HookEventName::PostCompact => "PostCompact",
codex_app_server_protocol::HookEventName::SessionStart => "SessionStart",
codex_app_server_protocol::HookEventName::UserPromptSubmit => "UserPromptSubmit",
codex_app_server_protocol::HookEventName::Stop => "Stop",
@@ -716,6 +716,8 @@ fn hook_event_label(event_name: HookEventName) -> &'static str {
HookEventName::PreToolUse => "PreToolUse",
HookEventName::PermissionRequest => "PermissionRequest",
HookEventName::PostToolUse => "PostToolUse",
HookEventName::PreCompact => "PreCompact",
HookEventName::PostCompact => "PostCompact",
HookEventName::SessionStart => "SessionStart",
HookEventName::UserPromptSubmit => "UserPromptSubmit",
HookEventName::Stop => "Stop",
+64 -2
View File
@@ -3,6 +3,7 @@ use std::future::Future;
use std::io::IsTerminal;
use std::io::Result;
use std::io::Stdout;
use std::io::Write;
use std::io::stdin;
use std::io::stdout;
use std::panic;
@@ -76,8 +77,15 @@ fn should_emit_notification(condition: NotificationCondition, terminal_focused:
#[cfg(test)]
mod tests {
use std::io::Write as _;
use super::clear_for_viewport_change;
use super::should_emit_notification;
use crate::custom_terminal::Terminal as CustomTerminal;
use crate::test_backend::VT100Backend;
use codex_config::types::NotificationCondition;
use ratatui::layout::Position;
use ratatui::layout::Rect;
#[test]
fn unfocused_notification_condition_is_suppressed_when_focused() {
@@ -102,6 +110,47 @@ mod tests {
/*terminal_focused*/ false
));
}
#[test]
fn first_viewport_change_clears_from_new_viewport_when_old_viewport_is_empty() {
let width = 12;
let height = 4;
let backend = VT100Backend::new(width, height);
let mut terminal =
CustomTerminal::with_options_and_cursor_position(backend, Position { x: 0, y: 1 })
.expect("terminal");
write!(
terminal.backend_mut(),
"shell line\r\nstale cells\r\nmore stale"
)
.expect("prefill terminal");
clear_for_viewport_change(
&mut terminal,
Rect::new(
/*x*/ 0,
/*y*/ 1,
/*width*/ width,
/*height*/ height - 1,
),
)
.expect("clear transition");
let rows: Vec<String> = terminal
.backend()
.vt100()
.screen()
.rows(/*start*/ 0, width)
.collect();
assert!(
rows[0].contains("shell line"),
"expected content before the viewport to remain visible, rows: {rows:?}"
);
assert!(
!rows.iter().skip(1).any(|row| row.contains("stale")),
"expected stale cells inside the new viewport to be cleared, rows: {rows:?}"
);
}
}
pub fn set_modes() -> Result<()> {
@@ -391,6 +440,18 @@ struct PendingHistoryLines {
wrap_policy: HistoryLineWrapPolicy,
}
fn clear_for_viewport_change<B>(terminal: &mut CustomTerminal<B>, new_area: Rect) -> Result<()>
where
B: Backend + Write,
{
let clear_position = if terminal.viewport_area.is_empty() {
new_area.as_position()
} else {
terminal.viewport_area.as_position()
};
terminal.clear_after_position(clear_position)
}
impl Tui {
pub fn new(terminal: Terminal) -> Self {
let (draw_tx, _) = broadcast::channel(1);
@@ -642,8 +703,9 @@ impl Tui {
area.y = size.height - area.height;
}
if area != terminal.viewport_area {
// TODO(nornagon): probably this could be collapsed with the clear + set_viewport_area above.
terminal.clear()?;
// On startup, the old viewport can still be empty. Clear from the
// new viewport top so stale shell cells do not show through spaces.
clear_for_viewport_change(terminal, area)?;
terminal.set_viewport_area(area);
}