diff --git a/codex-rs/app-server-client/src/lib.rs b/codex-rs/app-server-client/src/lib.rs index cfbef87030..c75915629c 100644 --- a/codex-rs/app-server-client/src/lib.rs +++ b/codex-rs/app-server-client/src/lib.rs @@ -665,6 +665,29 @@ impl InProcessAppServerClient { .map_err(|source| TypedRequestError::Deserialize { method, source }) } + /// Sends a typed client notification. + pub async fn notify(&self, notification: ClientNotification) -> IoResult<()> { + let (response_tx, response_rx) = oneshot::channel(); + self.command_tx + .send(ClientCommand::Notify { + notification, + response_tx, + }) + .await + .map_err(|_| { + IoError::new( + ErrorKind::BrokenPipe, + "in-process app-server worker channel is closed", + ) + })?; + response_rx.await.map_err(|_| { + IoError::new( + ErrorKind::BrokenPipe, + "in-process app-server notify channel is closed", + ) + })? + } + /// Resolves a pending server request. /// /// This should only be called with request IDs obtained from the current @@ -817,6 +840,13 @@ impl InProcessAppServerRequestHandle { } impl AppServerRequestHandle { + pub async fn request(&self, request: ClientRequest) -> IoResult { + match self { + Self::InProcess(handle) => handle.request(request).await, + Self::Remote(handle) => handle.request(request).await, + } + } + pub async fn request_typed(&self, request: ClientRequest) -> Result where T: DeserializeOwned, @@ -829,6 +859,13 @@ impl AppServerRequestHandle { } impl AppServerClient { + pub async fn request(&self, request: ClientRequest) -> IoResult { + match self { + Self::InProcess(client) => client.request(request).await, + Self::Remote(client) => client.request(request).await, + } + } + pub async fn request_typed(&self, request: ClientRequest) -> Result where T: DeserializeOwned, @@ -839,6 +876,13 @@ impl AppServerClient { } } + pub async fn notify(&self, notification: ClientNotification) -> IoResult<()> { + match self { + Self::InProcess(client) => client.notify(notification).await, + Self::Remote(client) => client.notify(notification).await, + } + } + pub async fn resolve_server_request( &self, request_id: RequestId, diff --git a/codex-rs/app-server-client/src/remote.rs b/codex-rs/app-server-client/src/remote.rs index c2794f62ed..98020c041c 100644 --- a/codex-rs/app-server-client/src/remote.rs +++ b/codex-rs/app-server-client/src/remote.rs @@ -524,6 +524,28 @@ impl RemoteAppServerClient { .map_err(|source| TypedRequestError::Deserialize { method, source }) } + pub async fn notify(&self, notification: ClientNotification) -> IoResult<()> { + let (response_tx, response_rx) = oneshot::channel(); + self.command_tx + .send(RemoteClientCommand::Notify { + notification, + response_tx, + }) + .await + .map_err(|_| { + IoError::new( + ErrorKind::BrokenPipe, + "remote app-server worker channel is closed", + ) + })?; + response_rx.await.map_err(|_| { + IoError::new( + ErrorKind::BrokenPipe, + "remote app-server notify channel is closed", + ) + })? + } + pub async fn resolve_server_request( &self, request_id: RequestId, diff --git a/codex-rs/app-server/src/in_process.rs b/codex-rs/app-server/src/in_process.rs index 7463627dcc..448a389851 100644 --- a/codex-rs/app-server/src/in_process.rs +++ b/codex-rs/app-server/src/in_process.rs @@ -283,6 +283,27 @@ impl InProcessClientHandle { self.client.notify(notification) } + /// Resolves a pending [`ServerRequest`](InProcessServerEvent::ServerRequest). + /// + /// This should be used only with request IDs received from the current + /// runtime event stream; sending arbitrary IDs has no effect on app-server + /// state and can mask a stuck approval flow in the caller. + pub fn respond_to_server_request(&self, request_id: RequestId, result: Result) -> IoResult<()> { + self.client.respond_to_server_request(request_id, result) + } + + /// Rejects a pending [`ServerRequest`](InProcessServerEvent::ServerRequest). + /// + /// Use this when the embedder cannot satisfy a server request; leaving + /// requests unanswered can stall turn progress. + pub fn fail_server_request( + &self, + request_id: RequestId, + error: JSONRPCErrorError, + ) -> IoResult<()> { + self.client.fail_server_request(request_id, error) + } + /// Receives the next server event from the in-process runtime. /// /// Returns `None` when the runtime task exits and no more events are diff --git a/codex-rs/backend-client/src/client.rs b/codex-rs/backend-client/src/client.rs index 8b5df7092d..63d6ec8e58 100644 --- a/codex-rs/backend-client/src/client.rs +++ b/codex-rs/backend-client/src/client.rs @@ -1,3 +1,4 @@ +use crate::types::AccountsCheckResponse; use crate::types::CodeTaskDetailsResponse; use crate::types::ConfigBundleResponse; use crate::types::PaginatedListTaskListItem; @@ -188,6 +189,21 @@ impl Client { self } + pub fn with_chatgpt_account_id(mut self, account_id: impl Into) -> Self { + self.chatgpt_account_id = Some(account_id.into()); + self + } + + pub fn with_fedramp_routing_header(mut self) -> Self { + self.chatgpt_account_is_fedramp = true; + self + } + + pub fn with_path_style(mut self, style: PathStyle) -> Self { + self.path_style = style; + self + } + fn headers(&self) -> HeaderMap { let mut h = HeaderMap::new(); if let Some(ua) = &self.user_agent { @@ -278,6 +294,16 @@ impl Client { Ok(Self::rate_limit_snapshots_from_payload(payload)) } + pub async fn get_accounts_check(&self) -> Result { + let url = match self.path_style { + PathStyle::CodexApi => format!("{}/api/codex/accounts/check", self.base_url), + PathStyle::ChatGptApi => format!("{}/wham/accounts/check", self.base_url), + }; + let req = self.http.get(&url).headers(self.headers()); + let (body, ct) = self.exec_request(req, "GET", &url).await?; + self.decode_json(&url, &ct, &body) + } + pub async fn send_add_credits_nudge_email( &self, credit_type: AddCreditsNudgeCreditType, diff --git a/codex-rs/codex-api/src/endpoint/images.rs b/codex-rs/codex-api/src/endpoint/images.rs index 7197658f09..9d1bd41eea 100644 --- a/codex-rs/codex-api/src/endpoint/images.rs +++ b/codex-rs/codex-api/src/endpoint/images.rs @@ -6,6 +6,7 @@ use crate::images::ImageGenerationRequest; use crate::images::ImageResponse; use crate::provider::Provider; use codex_client::HttpTransport; +use codex_client::RequestTelemetry; use http::HeaderMap; use http::Method; use serde::Serialize; @@ -23,6 +24,12 @@ impl ImagesClient { } } + pub fn with_telemetry(self, request: Option>) -> Self { + Self { + session: self.session.with_request_telemetry(request), + } + } + pub async fn generate( &self, request: &ImageGenerationRequest, diff --git a/codex-rs/codex-api/src/endpoint/realtime_call.rs b/codex-rs/codex-api/src/endpoint/realtime_call.rs index d0d296ebb1..b0342c5349 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_call.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_call.rs @@ -7,6 +7,7 @@ use crate::provider::Provider; use bytes::Bytes; use codex_client::HttpTransport; use codex_client::RequestBody; +use codex_client::RequestTelemetry; use http::HeaderMap; use http::HeaderValue; use http::Method; @@ -50,6 +51,12 @@ impl RealtimeCallClient { } } + pub fn with_telemetry(self, request: Option>) -> Self { + Self { + session: self.session.with_request_telemetry(request), + } + } + fn path() -> &'static str { "realtime/calls" } diff --git a/codex-rs/codex-api/src/endpoint/search.rs b/codex-rs/codex-api/src/endpoint/search.rs index 99872f4bdf..d01fbfb780 100644 --- a/codex-rs/codex-api/src/endpoint/search.rs +++ b/codex-rs/codex-api/src/endpoint/search.rs @@ -5,6 +5,7 @@ use crate::provider::Provider; use crate::search::SearchRequest; use crate::search::SearchResponse; use codex_client::HttpTransport; +use codex_client::RequestTelemetry; use http::HeaderMap; use http::Method; use serde_json::to_value; @@ -21,6 +22,12 @@ impl SearchClient { } } + pub fn with_telemetry(self, request: Option>) -> Self { + Self { + session: self.session.with_request_telemetry(request), + } + } + fn path() -> &'static str { "alpha/search" } diff --git a/codex-rs/ext/extension-api/src/contributors/prompt.rs b/codex-rs/ext/extension-api/src/contributors/prompt.rs index 200bae777f..1e29b72f9e 100644 --- a/codex-rs/ext/extension-api/src/contributors/prompt.rs +++ b/codex-rs/ext/extension-api/src/contributors/prompt.rs @@ -33,6 +33,11 @@ impl PromptFragment { Self::new(PromptSlot::DeveloperCapabilities, text) } + /// Creates a separate top-level developer prompt fragment. + pub fn separate_developer(text: impl Into) -> Self { + Self::new(PromptSlot::SeparateDeveloper, text) + } + /// Returns the target prompt slot. pub fn slot(&self) -> PromptSlot { self.slot diff --git a/codex-rs/ext/extension-api/src/registry.rs b/codex-rs/ext/extension-api/src/registry.rs index 068af80a64..0849387110 100644 --- a/codex-rs/ext/extension-api/src/registry.rs +++ b/codex-rs/ext/extension-api/src/registry.rs @@ -1,8 +1,11 @@ use std::sync::Arc; +use codex_protocol::protocol::ReviewDecision; + use crate::ApprovalReviewContributor; use crate::ConfigContributor; use crate::ContextContributor; +use crate::ExtensionData; use crate::ExtensionEventSink; use crate::NoopExtensionEventSink; use crate::ThreadLifecycleContributor; @@ -65,6 +68,11 @@ impl ExtensionRegistryBuilder { Arc::clone(&self.event_sink) } + /// Registers one approval-review contributor. + pub fn approval_review_contributor(&mut self, contributor: Arc) { + self.approval_review_contributors.push(contributor); + } + /// Registers one thread-lifecycle contributor. pub fn thread_lifecycle_contributor( &mut self, @@ -147,6 +155,11 @@ pub struct ExtensionRegistry { } impl ExtensionRegistry { + /// Returns the host event sink retained by this registry. + pub fn event_sink(&self) -> Arc { + Arc::clone(&self.event_sink) + } + /// Returns the registered thread-lifecycle contributors. pub fn thread_lifecycle_contributors(&self) -> &[Arc>] { &self.thread_lifecycle_contributors @@ -167,6 +180,26 @@ impl ExtensionRegistry { &self.token_usage_contributors } + /// Claims the first rendered approval-review prompt accepted by an + /// installed contributor. + pub async fn approval_review( + &self, + session_store: &ExtensionData, + thread_store: &ExtensionData, + prompt: &str, + ) -> Option { + for contributor in &self.approval_review_contributors { + if let Some(decision) = contributor + .contribute(session_store, thread_store, prompt) + .await + { + return Some(decision); + } + } + + None + } + /// Returns the registered prompt contributors. pub fn context_contributors(&self) -> &[Arc] { &self.context_contributors diff --git a/codex-rs/ext/extension-api/src/state.rs b/codex-rs/ext/extension-api/src/state.rs index 6d5eaff36f..aab37f5059 100644 --- a/codex-rs/ext/extension-api/src/state.rs +++ b/codex-rs/ext/extension-api/src/state.rs @@ -62,6 +62,14 @@ impl ExtensionData { .map(downcast_data) } + /// Removes and returns the attached value of type `T`, if one exists. + pub fn remove(&self) -> Option> + where + T: Any + Send + Sync, + { + self.entries().remove(&TypeId::of::()).map(downcast_data) + } + fn entries(&self) -> std::sync::MutexGuard<'_, HashMap> { self.entries.lock().unwrap_or_else(PoisonError::into_inner) } diff --git a/codex-rs/ext/guardian/src/lib.rs b/codex-rs/ext/guardian/src/lib.rs index dc093016b6..0591887c25 100644 --- a/codex-rs/ext/guardian/src/lib.rs +++ b/codex-rs/ext/guardian/src/lib.rs @@ -1,6 +1,8 @@ use std::sync::Arc; use codex_core::config::Config; +use codex_extension_api::AgentSpawnFuture; +use codex_extension_api::AgentSpawner; use codex_extension_api::ExtensionRegistryBuilder; use codex_extension_api::ThreadLifecycleContributor; use codex_extension_api::ThreadStartInput; @@ -17,6 +19,19 @@ impl GuardianExtension { pub fn new(agent_spawner: S) -> Self { Self { agent_spawner } } + + /// Delegates one guardian-owned subagent spawn request to the host helper. + pub fn spawn_subagent<'a, R>( + &'a self, + forked_from_thread_id: ThreadId, + request: R, + ) -> AgentSpawnFuture<'a, >::Spawned, >::Error> + where + S: AgentSpawner, + { + self.agent_spawner + .spawn_subagent(forked_from_thread_id, request) + } } /// Thread-local guardian state captured when the host starts a thread. @@ -25,6 +40,13 @@ pub struct GuardianThreadContext { forked_from_thread_id: ThreadId, } +impl GuardianThreadContext { + /// Returns the thread that future guardian subagents should fork from by default. + pub fn forked_from_thread_id(&self) -> ThreadId { + self.forked_from_thread_id + } +} + #[async_trait::async_trait] impl ThreadLifecycleContributor for GuardianExtension where diff --git a/codex-rs/ext/skills/src/catalog.rs b/codex-rs/ext/skills/src/catalog.rs index 45f4d14931..a09a81ff79 100644 --- a/codex-rs/ext/skills/src/catalog.rs +++ b/codex-rs/ext/skills/src/catalog.rs @@ -16,6 +16,10 @@ pub enum SkillSourceKind { } impl SkillSourceKind { + pub fn custom(kind: impl Into) -> Self { + Self::Custom(kind.into()) + } + fn as_str(&self) -> &str { match self { Self::Host => "host", @@ -93,11 +97,26 @@ impl SkillCatalogEntry { } } + pub fn with_short_description(mut self, short_description: Option) -> Self { + self.short_description = short_description; + self + } + pub fn with_display_path(mut self, display_path: impl Into) -> Self { self.display_path = Some(display_path.into()); self } + pub fn with_dependencies(mut self, dependencies: Option) -> Self { + self.dependencies = dependencies; + self + } + + pub fn disabled(mut self) -> Self { + self.enabled = false; + self + } + pub fn hidden_from_prompt(mut self) -> Self { self.prompt_visible = false; self diff --git a/codex-rs/ext/skills/src/sources.rs b/codex-rs/ext/skills/src/sources.rs index b5da61ffff..9049fcb550 100644 --- a/codex-rs/ext/skills/src/sources.rs +++ b/codex-rs/ext/skills/src/sources.rs @@ -4,10 +4,12 @@ use std::sync::Arc; use crate::catalog::SkillCatalog; use crate::catalog::SkillProviderError; use crate::catalog::SkillReadResult; +use crate::catalog::SkillSearchResult; use crate::catalog::SkillSourceKind; use crate::provider::SkillListQuery; use crate::provider::SkillProvider; use crate::provider::SkillReadRequest; +use crate::provider::SkillSearchRequest; #[derive(Clone)] pub struct SkillProviderSource { @@ -33,6 +35,10 @@ impl SkillProviderSource { Self::new(SkillSourceKind::Host, label, provider) } + pub fn executor(label: impl Into, provider: Arc) -> Self { + Self::new(SkillSourceKind::Executor, label, provider) + } + pub fn remote(label: impl Into, provider: Arc) -> Self { Self::new(SkillSourceKind::Remote, label, provider) } @@ -71,12 +77,23 @@ impl SkillProviders { Self::default() } + pub fn with_provider(mut self, source: SkillProviderSource) -> Self { + self.sources.push(source); + self + } + pub fn with_host_provider(mut self, provider: Arc) -> Self { self.sources .push(SkillProviderSource::host("host", provider)); self } + pub fn with_executor_provider(mut self, provider: Arc) -> Self { + self.sources + .push(SkillProviderSource::executor("executor", provider)); + self + } + pub fn with_remote_provider(mut self, provider: Arc) -> Self { self.sources .push(SkillProviderSource::remote("remote", provider)); @@ -125,6 +142,31 @@ impl SkillProviders { ))), } } + + pub async fn search( + &self, + request: SkillSearchRequest, + ) -> Result { + let mut last_error = None; + for source in self + .sources + .iter() + .filter(|source| source.owns_kind(&request.authority.kind)) + { + match source.provider.search(request.clone()).await { + Ok(result) => return Ok(result), + Err(err) => last_error = Some(err), + } + } + + match last_error { + Some(err) => Err(err), + None => Err(SkillProviderError::new(format!( + "{} skill provider is not configured", + request.authority.kind + ))), + } + } } fn extend_catalog( diff --git a/codex-rs/network-proxy/src/proxy.rs b/codex-rs/network-proxy/src/proxy.rs index df563f0939..9eb814ef28 100644 --- a/codex-rs/network-proxy/src/proxy.rs +++ b/codex-rs/network-proxy/src/proxy.rs @@ -769,6 +769,28 @@ impl NetworkProxyHandle { completed: true, } } + + pub async fn wait(mut self) -> Result<()> { + let http_task = self.http_task.take().context("missing http proxy task")?; + let socks_task = self.socks_task.take(); + let http_result = http_task.await; + let socks_result = match socks_task { + Some(task) => Some(task.await), + None => None, + }; + self.completed = true; + http_result??; + if let Some(socks_result) = socks_result { + socks_result??; + } + Ok(()) + } + + pub async fn shutdown(mut self) -> Result<()> { + abort_tasks(self.http_task.take(), self.socks_task.take()).await; + self.completed = true; + Ok(()) + } } async fn abort_task(task: Option>>) { diff --git a/codex-rs/rmcp-client/src/rmcp_client.rs b/codex-rs/rmcp-client/src/rmcp_client.rs index 626aa765ed..90b09d724c 100644 --- a/codex-rs/rmcp-client/src/rmcp_client.rs +++ b/codex-rs/rmcp-client/src/rmcp_client.rs @@ -22,14 +22,19 @@ use reqwest::header::AUTHORIZATION; use reqwest::header::HeaderMap; use rmcp::model::CallToolRequestParams; use rmcp::model::CallToolResult; +use rmcp::model::ClientNotification; use rmcp::model::ClientRequest; use rmcp::model::CreateElicitationRequestParams; use rmcp::model::CreateElicitationResult; +use rmcp::model::CustomNotification; +use rmcp::model::CustomRequest; use rmcp::model::ElicitationAction; +use rmcp::model::Extensions; use rmcp::model::InitializeRequestParams; use rmcp::model::InitializeResult; use rmcp::model::ListResourceTemplatesResult; use rmcp::model::ListResourcesResult; +use rmcp::model::ListToolsResult; use rmcp::model::PaginatedRequestParams; use rmcp::model::ReadResourceRequestParams; use rmcp::model::ReadResourceResult; @@ -278,6 +283,26 @@ pub struct RmcpClient { } impl RmcpClient { + pub async fn new_in_process_client( + factory: Arc, + ) -> io::Result { + let transport_recipe = TransportRecipe::InProcess { factory }; + let transport = Self::create_pending_transport(&transport_recipe) + .await + .map_err(io::Error::other)?; + + Ok(Self { + state: Mutex::new(ClientState::Connecting { + transport: Some(transport), + }), + stdio_process: None, + transport_recipe, + initialize_context: Mutex::new(None), + session_recovery_lock: Semaphore::new(/*permits*/ 1), + elicitation_pause_state: ElicitationPauseState::new(), + }) + } + pub async fn new_stdio_client( program: OsString, args: Vec, @@ -409,6 +434,22 @@ impl RmcpClient { Ok(initialize_result) } + pub async fn list_tools( + &self, + params: Option, + timeout: Option, + ) -> Result { + self.refresh_oauth_if_needed().await; + let result = self + .run_service_operation("tools/list", timeout, move |service| { + let params = params.clone(); + async move { service.list_tools(params).await }.boxed() + }) + .await?; + self.persist_oauth_tokens().await; + Ok(result) + } + pub async fn list_tools_with_connector_ids( &self, params: Option, @@ -560,6 +601,59 @@ impl RmcpClient { Ok(result) } + pub async fn send_custom_notification( + &self, + method: &str, + params: Option, + ) -> Result<()> { + self.refresh_oauth_if_needed().await; + self.run_service_operation( + "notifications/custom", + /*timeout*/ None, + move |service| { + let params = params.clone(); + async move { + service + .send_notification(ClientNotification::CustomNotification( + CustomNotification { + method: method.to_string(), + params, + extensions: Extensions::new(), + }, + )) + .await + } + .boxed() + }, + ) + .await?; + self.persist_oauth_tokens().await; + Ok(()) + } + + pub async fn send_custom_request( + &self, + method: &str, + params: Option, + ) -> Result { + self.refresh_oauth_if_needed().await; + let response = self + .run_service_operation("requests/custom", /*timeout*/ None, move |service| { + let params = params.clone(); + async move { + service + .send_request(ClientRequest::CustomRequest(CustomRequest::new( + method, params, + ))) + .await + } + .boxed() + }) + .await?; + self.persist_oauth_tokens().await; + Ok(response) + } + async fn service(&self) -> Result>> { let guard = self.state.lock().await; match &*guard { diff --git a/codex-rs/tui/src/public_widgets/composer_input.rs b/codex-rs/tui/src/public_widgets/composer_input.rs index a49cfb51ca..9c760b59a2 100644 --- a/codex-rs/tui/src/public_widgets/composer_input.rs +++ b/codex-rs/tui/src/public_widgets/composer_input.rs @@ -47,6 +47,17 @@ impl ComposerInput { Self { inner, _tx: tx, rx } } + /// Returns true if the input is empty. + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + + /// Clear the input text. + pub fn clear(&mut self) { + self.inner + .set_text_content(String::new(), Vec::new(), Vec::new()); + } + /// Feed a key event into the composer and return a high-level action. pub fn input(&mut self, key: KeyEvent) -> ComposerAction { let action = match self.inner.handle_key_event(key).0 { @@ -73,6 +84,11 @@ impl ComposerInput { self.inner.set_footer_hint_override(Some(mapped)); } + /// Clear any previously set custom hint items and restore the default hints. + pub fn clear_hint_items(&mut self) { + self.inner.set_footer_hint_override(/*items*/ None); + } + /// Desired height (in rows) for a given width. pub fn desired_height(&self, width: u16) -> u16 { self.inner.desired_height(width)