repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/cli/tests/mcp_list.rs
codex-rs/cli/tests/mcp_list.rs
use std::path::Path; use anyhow::Result; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config::load_global_mcp_servers; use codex_core::config::types::McpServerTransportConfig; use predicates::prelude::PredicateBooleanExt; use predicates::str::contains; use pretty_assertions::assert_eq; use serde_json::Value as JsonValue; use serde_json::json; use tempfile::TempDir; fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> { let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?); cmd.env("CODEX_HOME", codex_home); Ok(cmd) } #[test] fn list_shows_empty_state() -> Result<()> { let codex_home = TempDir::new()?; let mut cmd = codex_command(codex_home.path())?; let output = cmd.args(["mcp", "list"]).output()?; assert!(output.status.success()); let stdout = String::from_utf8(output.stdout)?; assert!(stdout.contains("No MCP servers configured yet.")); Ok(()) } #[tokio::test] async fn list_and_get_render_expected_output() -> Result<()> { let codex_home = TempDir::new()?; let mut add = codex_command(codex_home.path())?; add.args([ "mcp", "add", "docs", "--env", "TOKEN=secret", "--", "docs-server", "--port", "4000", ]) .assert() .success(); let mut servers = load_global_mcp_servers(codex_home.path()).await?; let docs_entry = servers .get_mut("docs") .expect("docs server should exist after add"); match &mut docs_entry.transport { McpServerTransportConfig::Stdio { env_vars, .. } => { *env_vars = vec!["APP_TOKEN".to_string(), "WORKSPACE_ID".to_string()]; } other => panic!("unexpected transport: {other:?}"), } ConfigEditsBuilder::new(codex_home.path()) .replace_mcp_servers(&servers) .apply_blocking()?; let mut list_cmd = codex_command(codex_home.path())?; let list_output = list_cmd.args(["mcp", "list"]).output()?; assert!(list_output.status.success()); let stdout = String::from_utf8(list_output.stdout)?; assert!(stdout.contains("Name")); assert!(stdout.contains("docs")); assert!(stdout.contains("docs-server")); assert!(stdout.contains("TOKEN=*****")); assert!(stdout.contains("APP_TOKEN=*****")); assert!(stdout.contains("WORKSPACE_ID=*****")); assert!(stdout.contains("Status")); assert!(stdout.contains("Auth")); assert!(stdout.contains("enabled")); assert!(stdout.contains("Unsupported")); let mut list_json_cmd = codex_command(codex_home.path())?; let json_output = list_json_cmd.args(["mcp", "list", "--json"]).output()?; assert!(json_output.status.success()); let stdout = String::from_utf8(json_output.stdout)?; let parsed: JsonValue = serde_json::from_str(&stdout)?; assert_eq!( parsed, json!([ { "name": "docs", "enabled": true, "transport": { "type": "stdio", "command": "docs-server", "args": [ "--port", "4000" ], "env": { "TOKEN": "secret" }, "env_vars": [ "APP_TOKEN", "WORKSPACE_ID" ], "cwd": null }, "startup_timeout_sec": null, "tool_timeout_sec": null, "auth_status": "unsupported" } ] ) ); let mut get_cmd = codex_command(codex_home.path())?; let get_output = get_cmd.args(["mcp", "get", "docs"]).output()?; assert!(get_output.status.success()); let stdout = String::from_utf8(get_output.stdout)?; assert!(stdout.contains("docs")); assert!(stdout.contains("transport: stdio")); assert!(stdout.contains("command: docs-server")); assert!(stdout.contains("args: --port 4000")); assert!(stdout.contains("env: TOKEN=*****")); assert!(stdout.contains("APP_TOKEN=*****")); assert!(stdout.contains("WORKSPACE_ID=*****")); assert!(stdout.contains("enabled: true")); assert!(stdout.contains("remove: codex mcp remove docs")); let mut get_json_cmd = codex_command(codex_home.path())?; get_json_cmd .args(["mcp", "get", "docs", "--json"]) .assert() .success() .stdout(contains("\"name\": \"docs\"").and(contains("\"enabled\": true"))); Ok(()) } #[tokio::test] async fn get_disabled_server_shows_single_line() -> Result<()> { let codex_home = TempDir::new()?; let mut add = codex_command(codex_home.path())?; add.args(["mcp", "add", "docs", "--", "docs-server"]) .assert() .success(); let mut servers = load_global_mcp_servers(codex_home.path()).await?; let docs = servers .get_mut("docs") .expect("docs server should exist after add"); docs.enabled = false; ConfigEditsBuilder::new(codex_home.path()) .replace_mcp_servers(&servers) .apply_blocking()?; let mut get_cmd = codex_command(codex_home.path())?; let get_output = get_cmd.args(["mcp", "get", "docs"]).output()?; assert!(get_output.status.success()); let stdout = String::from_utf8(get_output.stdout)?; assert_eq!(stdout.trim_end(), "docs (disabled)"); Ok(()) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/cli/tests/execpolicy.rs
codex-rs/cli/tests/execpolicy.rs
use std::fs; use assert_cmd::Command; use pretty_assertions::assert_eq; use serde_json::json; use tempfile::TempDir; #[test] fn execpolicy_check_matches_expected_json() -> Result<(), Box<dyn std::error::Error>> { let codex_home = TempDir::new()?; let policy_path = codex_home.path().join("rules").join("policy.rules"); fs::create_dir_all( policy_path .parent() .expect("policy path should have a parent"), )?; fs::write( &policy_path, r#" prefix_rule( pattern = ["git", "push"], decision = "forbidden", ) "#, )?; let output = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?) .env("CODEX_HOME", codex_home.path()) .args([ "execpolicy", "check", "--rules", policy_path .to_str() .expect("policy path should be valid UTF-8"), "git", "push", "origin", "main", ]) .output()?; assert!(output.status.success()); let result: serde_json::Value = serde_json::from_slice(&output.stdout)?; assert_eq!( result, json!({ "decision": "forbidden", "matchedRules": [ { "prefixRuleMatch": { "matchedPrefix": ["git", "push"], "decision": "forbidden" } } ] }) ); Ok(()) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/cli/tests/mcp_add_remove.rs
codex-rs/cli/tests/mcp_add_remove.rs
use std::path::Path; use anyhow::Result; use codex_core::config::load_global_mcp_servers; use codex_core::config::types::McpServerTransportConfig; use predicates::str::contains; use pretty_assertions::assert_eq; use tempfile::TempDir; fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> { let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?); cmd.env("CODEX_HOME", codex_home); Ok(cmd) } #[tokio::test] async fn add_and_remove_server_updates_global_config() -> Result<()> { let codex_home = TempDir::new()?; let mut add_cmd = codex_command(codex_home.path())?; add_cmd .args(["mcp", "add", "docs", "--", "echo", "hello"]) .assert() .success() .stdout(contains("Added global MCP server 'docs'.")); let servers = load_global_mcp_servers(codex_home.path()).await?; assert_eq!(servers.len(), 1); let docs = servers.get("docs").expect("server should exist"); match &docs.transport { McpServerTransportConfig::Stdio { command, args, env, env_vars, cwd, } => { assert_eq!(command, "echo"); assert_eq!(args, &vec!["hello".to_string()]); assert!(env.is_none()); assert!(env_vars.is_empty()); assert!(cwd.is_none()); } other => panic!("unexpected transport: {other:?}"), } assert!(docs.enabled); let mut remove_cmd = codex_command(codex_home.path())?; remove_cmd .args(["mcp", "remove", "docs"]) .assert() .success() .stdout(contains("Removed global MCP server 'docs'.")); let servers = load_global_mcp_servers(codex_home.path()).await?; assert!(servers.is_empty()); let mut remove_again_cmd = codex_command(codex_home.path())?; remove_again_cmd .args(["mcp", "remove", "docs"]) .assert() .success() .stdout(contains("No MCP server named 'docs' found.")); let servers = load_global_mcp_servers(codex_home.path()).await?; assert!(servers.is_empty()); Ok(()) } #[tokio::test] async fn add_with_env_preserves_key_order_and_values() -> Result<()> { let codex_home = TempDir::new()?; let mut add_cmd = codex_command(codex_home.path())?; add_cmd .args([ "mcp", "add", "envy", "--env", "FOO=bar", "--env", "ALPHA=beta", "--", "python", "server.py", ]) .assert() .success(); let servers = load_global_mcp_servers(codex_home.path()).await?; let envy = servers.get("envy").expect("server should exist"); let env = match &envy.transport { McpServerTransportConfig::Stdio { env: Some(env), .. } => env, other => panic!("unexpected transport: {other:?}"), }; assert_eq!(env.len(), 2); assert_eq!(env.get("FOO"), Some(&"bar".to_string())); assert_eq!(env.get("ALPHA"), Some(&"beta".to_string())); assert!(envy.enabled); Ok(()) } #[tokio::test] async fn add_streamable_http_without_manual_token() -> Result<()> { let codex_home = TempDir::new()?; let mut add_cmd = codex_command(codex_home.path())?; add_cmd .args(["mcp", "add", "github", "--url", "https://example.com/mcp"]) .assert() .success(); let servers = load_global_mcp_servers(codex_home.path()).await?; let github = servers.get("github").expect("github server should exist"); match &github.transport { McpServerTransportConfig::StreamableHttp { url, bearer_token_env_var, http_headers, env_http_headers, } => { assert_eq!(url, "https://example.com/mcp"); assert!(bearer_token_env_var.is_none()); assert!(http_headers.is_none()); assert!(env_http_headers.is_none()); } other => panic!("unexpected transport: {other:?}"), } assert!(github.enabled); assert!(!codex_home.path().join(".credentials.json").exists()); assert!(!codex_home.path().join(".env").exists()); Ok(()) } #[tokio::test] async fn add_streamable_http_with_custom_env_var() -> Result<()> { let codex_home = TempDir::new()?; let mut add_cmd = codex_command(codex_home.path())?; add_cmd .args([ "mcp", "add", "issues", "--url", "https://example.com/issues", "--bearer-token-env-var", "GITHUB_TOKEN", ]) .assert() .success(); let servers = load_global_mcp_servers(codex_home.path()).await?; let issues = servers.get("issues").expect("issues server should exist"); match &issues.transport { McpServerTransportConfig::StreamableHttp { url, bearer_token_env_var, http_headers, env_http_headers, } => { assert_eq!(url, "https://example.com/issues"); assert_eq!(bearer_token_env_var.as_deref(), Some("GITHUB_TOKEN")); assert!(http_headers.is_none()); assert!(env_http_headers.is_none()); } other => panic!("unexpected transport: {other:?}"), } assert!(issues.enabled); Ok(()) } #[tokio::test] async fn add_streamable_http_rejects_removed_flag() -> Result<()> { let codex_home = TempDir::new()?; let mut add_cmd = codex_command(codex_home.path())?; add_cmd .args([ "mcp", "add", "github", "--url", "https://example.com/mcp", "--with-bearer-token", ]) .assert() .failure() .stderr(contains("--with-bearer-token")); let servers = load_global_mcp_servers(codex_home.path()).await?; assert!(servers.is_empty()); Ok(()) } #[tokio::test] async fn add_cant_add_command_and_url() -> Result<()> { let codex_home = TempDir::new()?; let mut add_cmd = codex_command(codex_home.path())?; add_cmd .args([ "mcp", "add", "github", "--url", "https://example.com/mcp", "--command", "--", "echo", "hello", ]) .assert() .failure() .stderr(contains("unexpected argument '--command' found")); let servers = load_global_mcp_servers(codex_home.path()).await?; assert!(servers.is_empty()); Ok(()) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/src/error_code.rs
codex-rs/mcp-server/src/error_code.rs
pub(crate) const INVALID_REQUEST_ERROR_CODE: i64 = -32600; pub(crate) const INTERNAL_ERROR_CODE: i64 = -32603;
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/src/codex_tool_runner.rs
codex-rs/mcp-server/src/codex_tool_runner.rs
//! Asynchronous worker that executes a **Codex** tool-call inside a spawned //! Tokio task. Separated from `message_processor.rs` to keep that file small //! and to make future feature-growth easier to manage. use std::collections::HashMap; use std::sync::Arc; use crate::exec_approval::handle_exec_approval_request; use crate::outgoing_message::OutgoingMessageSender; use crate::outgoing_message::OutgoingNotificationMeta; use crate::patch_approval::handle_patch_approval_request; use codex_core::CodexConversation; use codex_core::ConversationManager; use codex_core::NewConversation; use codex_core::config::Config as CodexConfig; use codex_core::protocol::AgentMessageEvent; use codex_core::protocol::ApplyPatchApprovalRequestEvent; use codex_core::protocol::Event; use codex_core::protocol::EventMsg; use codex_core::protocol::ExecApprovalRequestEvent; use codex_core::protocol::Op; use codex_core::protocol::Submission; use codex_core::protocol::TaskCompleteEvent; use codex_protocol::ConversationId; use codex_protocol::user_input::UserInput; use mcp_types::CallToolResult; use mcp_types::ContentBlock; use mcp_types::RequestId; use mcp_types::TextContent; use serde_json::json; use tokio::sync::Mutex; pub(crate) const INVALID_PARAMS_ERROR_CODE: i64 = -32602; /// Run a complete Codex session and stream events back to the client. /// /// On completion (success or error) the function sends the appropriate /// `tools/call` response so the LLM can continue the conversation. pub async fn run_codex_tool_session( id: RequestId, initial_prompt: String, config: CodexConfig, outgoing: Arc<OutgoingMessageSender>, conversation_manager: Arc<ConversationManager>, running_requests_id_to_codex_uuid: Arc<Mutex<HashMap<RequestId, ConversationId>>>, ) { let NewConversation { conversation_id, conversation, session_configured, } = match conversation_manager.new_conversation(config).await { Ok(res) => res, Err(e) => { let result = CallToolResult { content: vec![ContentBlock::TextContent(TextContent { r#type: "text".to_string(), text: format!("Failed to start Codex session: {e}"), annotations: None, })], is_error: Some(true), structured_content: None, }; outgoing.send_response(id.clone(), result).await; return; } }; let session_configured_event = Event { // Use a fake id value for now. id: "".to_string(), msg: EventMsg::SessionConfigured(session_configured.clone()), }; outgoing .send_event_as_notification( &session_configured_event, Some(OutgoingNotificationMeta::new(Some(id.clone()))), ) .await; // Use the original MCP request ID as the `sub_id` for the Codex submission so that // any events emitted for this tool-call can be correlated with the // originating `tools/call` request. let sub_id = match &id { RequestId::String(s) => s.clone(), RequestId::Integer(n) => n.to_string(), }; running_requests_id_to_codex_uuid .lock() .await .insert(id.clone(), conversation_id); let submission = Submission { id: sub_id.clone(), op: Op::UserInput { items: vec![UserInput::Text { text: initial_prompt.clone(), }], }, }; if let Err(e) = conversation.submit_with_id(submission).await { tracing::error!("Failed to submit initial prompt: {e}"); // unregister the id so we don't keep it in the map running_requests_id_to_codex_uuid.lock().await.remove(&id); return; } run_codex_tool_session_inner( conversation, outgoing, id, running_requests_id_to_codex_uuid, ) .await; } pub async fn run_codex_tool_session_reply( conversation: Arc<CodexConversation>, outgoing: Arc<OutgoingMessageSender>, request_id: RequestId, prompt: String, running_requests_id_to_codex_uuid: Arc<Mutex<HashMap<RequestId, ConversationId>>>, conversation_id: ConversationId, ) { running_requests_id_to_codex_uuid .lock() .await .insert(request_id.clone(), conversation_id); if let Err(e) = conversation .submit(Op::UserInput { items: vec![UserInput::Text { text: prompt }], }) .await { tracing::error!("Failed to submit user input: {e}"); // unregister the id so we don't keep it in the map running_requests_id_to_codex_uuid .lock() .await .remove(&request_id); return; } run_codex_tool_session_inner( conversation, outgoing, request_id, running_requests_id_to_codex_uuid, ) .await; } async fn run_codex_tool_session_inner( codex: Arc<CodexConversation>, outgoing: Arc<OutgoingMessageSender>, request_id: RequestId, running_requests_id_to_codex_uuid: Arc<Mutex<HashMap<RequestId, ConversationId>>>, ) { let request_id_str = match &request_id { RequestId::String(s) => s.clone(), RequestId::Integer(n) => n.to_string(), }; // Stream events until the task needs to pause for user interaction or // completes. loop { match codex.next_event().await { Ok(event) => { outgoing .send_event_as_notification( &event, Some(OutgoingNotificationMeta::new(Some(request_id.clone()))), ) .await; match event.msg { EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent { turn_id: _, command, cwd, call_id, reason: _, proposed_execpolicy_amendment: _, parsed_cmd, }) => { handle_exec_approval_request( command, cwd, outgoing.clone(), codex.clone(), request_id.clone(), request_id_str.clone(), event.id.clone(), call_id, parsed_cmd, ) .await; continue; } EventMsg::Error(err_event) => { // Return a response to conclude the tool call when the Codex session reports an error (e.g., interruption). let result = json!({ "error": err_event.message, }); outgoing.send_response(request_id.clone(), result).await; break; } EventMsg::Warning(_) => { continue; } EventMsg::ElicitationRequest(_) => { // TODO: forward elicitation requests to the client? continue; } EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent { call_id, turn_id: _, reason, grant_root, changes, }) => { handle_patch_approval_request( call_id, reason, grant_root, changes, outgoing.clone(), codex.clone(), request_id.clone(), request_id_str.clone(), event.id.clone(), ) .await; continue; } EventMsg::TaskComplete(TaskCompleteEvent { last_agent_message }) => { let text = match last_agent_message { Some(msg) => msg, None => "".to_string(), }; let result = CallToolResult { content: vec![ContentBlock::TextContent(TextContent { r#type: "text".to_string(), text, annotations: None, })], is_error: None, structured_content: None, }; outgoing.send_response(request_id.clone(), result).await; // unregister the id so we don't keep it in the map running_requests_id_to_codex_uuid .lock() .await .remove(&request_id); break; } EventMsg::SessionConfigured(_) => { tracing::error!("unexpected SessionConfigured event"); } EventMsg::AgentMessageDelta(_) => { // TODO: think how we want to support this in the MCP } EventMsg::AgentReasoningDelta(_) => { // TODO: think how we want to support this in the MCP } EventMsg::McpStartupUpdate(_) | EventMsg::McpStartupComplete(_) => { // Ignored in MCP tool runner. } EventMsg::AgentMessage(AgentMessageEvent { .. }) => { // TODO: think how we want to support this in the MCP } EventMsg::AgentReasoningRawContent(_) | EventMsg::AgentReasoningRawContentDelta(_) | EventMsg::TaskStarted(_) | EventMsg::TokenCount(_) | EventMsg::AgentReasoning(_) | EventMsg::AgentReasoningSectionBreak(_) | EventMsg::McpToolCallBegin(_) | EventMsg::McpToolCallEnd(_) | EventMsg::McpListToolsResponse(_) | EventMsg::ListCustomPromptsResponse(_) | EventMsg::ListSkillsResponse(_) | EventMsg::ExecCommandBegin(_) | EventMsg::TerminalInteraction(_) | EventMsg::ExecCommandOutputDelta(_) | EventMsg::ExecCommandEnd(_) | EventMsg::BackgroundEvent(_) | EventMsg::StreamError(_) | EventMsg::PatchApplyBegin(_) | EventMsg::PatchApplyEnd(_) | EventMsg::TurnDiff(_) | EventMsg::WebSearchBegin(_) | EventMsg::WebSearchEnd(_) | EventMsg::GetHistoryEntryResponse(_) | EventMsg::PlanUpdate(_) | EventMsg::TurnAborted(_) | EventMsg::UserMessage(_) | EventMsg::ShutdownComplete | EventMsg::ViewImageToolCall(_) | EventMsg::RawResponseItem(_) | EventMsg::EnteredReviewMode(_) | EventMsg::ItemStarted(_) | EventMsg::ItemCompleted(_) | EventMsg::AgentMessageContentDelta(_) | EventMsg::ReasoningContentDelta(_) | EventMsg::ReasoningRawContentDelta(_) | EventMsg::SkillsUpdateAvailable | EventMsg::UndoStarted(_) | EventMsg::UndoCompleted(_) | EventMsg::ExitedReviewMode(_) | EventMsg::ContextCompacted(_) | EventMsg::DeprecationNotice(_) => { // For now, we do not do anything extra for these // events. Note that // send(codex_event_to_notification(&event)) above has // already dispatched these events as notifications, // though we may want to do give different treatment to // individual events in the future. } } } Err(e) => { let result = CallToolResult { content: vec![ContentBlock::TextContent(TextContent { r#type: "text".to_string(), text: format!("Codex runtime error: {e}"), annotations: None, })], is_error: Some(true), // TODO(mbolin): Could present the error in a more // structured way. structured_content: None, }; outgoing.send_response(request_id.clone(), result).await; break; } } } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/src/codex_tool_config.rs
codex-rs/mcp-server/src/codex_tool_config.rs
//! Configuration object accepted by the `codex` MCP tool-call. use codex_core::config::Config; use codex_core::config::ConfigOverrides; use codex_core::protocol::AskForApproval; use codex_protocol::config_types::SandboxMode; use codex_utils_json_to_toml::json_to_toml; use mcp_types::Tool; use mcp_types::ToolInputSchema; use schemars::JsonSchema; use schemars::r#gen::SchemaSettings; use serde::Deserialize; use serde::Serialize; use std::collections::HashMap; use std::path::PathBuf; /// Client-supplied configuration for a `codex` tool-call. #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)] #[serde(rename_all = "kebab-case")] pub struct CodexToolCallParam { /// The *initial user prompt* to start the Codex conversation. pub prompt: String, /// Optional override for the model name (e.g. "o3", "o4-mini"). #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option<String>, /// Configuration profile from config.toml to specify default options. #[serde(default, skip_serializing_if = "Option::is_none")] pub profile: Option<String>, /// Working directory for the session. If relative, it is resolved against /// the server process's current working directory. #[serde(default, skip_serializing_if = "Option::is_none")] pub cwd: Option<String>, /// Approval policy for shell commands generated by the model: /// `untrusted`, `on-failure`, `on-request`, `never`. #[serde(default, skip_serializing_if = "Option::is_none")] pub approval_policy: Option<CodexToolCallApprovalPolicy>, /// Sandbox mode: `read-only`, `workspace-write`, or `danger-full-access`. #[serde(default, skip_serializing_if = "Option::is_none")] pub sandbox: Option<CodexToolCallSandboxMode>, /// Individual config settings that will override what is in /// CODEX_HOME/config.toml. #[serde(default, skip_serializing_if = "Option::is_none")] pub config: Option<HashMap<String, serde_json::Value>>, /// The set of instructions to use instead of the default ones. #[serde(default, skip_serializing_if = "Option::is_none")] pub base_instructions: Option<String>, /// Developer instructions that should be injected as a developer role message. #[serde(default, skip_serializing_if = "Option::is_none")] pub developer_instructions: Option<String>, /// Prompt used when compacting the conversation. #[serde(default, skip_serializing_if = "Option::is_none")] pub compact_prompt: Option<String>, } /// Custom enum mirroring [`AskForApproval`], but has an extra dependency on /// [`JsonSchema`]. #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)] #[serde(rename_all = "kebab-case")] pub enum CodexToolCallApprovalPolicy { Untrusted, OnFailure, OnRequest, Never, } impl From<CodexToolCallApprovalPolicy> for AskForApproval { fn from(value: CodexToolCallApprovalPolicy) -> Self { match value { CodexToolCallApprovalPolicy::Untrusted => AskForApproval::UnlessTrusted, CodexToolCallApprovalPolicy::OnFailure => AskForApproval::OnFailure, CodexToolCallApprovalPolicy::OnRequest => AskForApproval::OnRequest, CodexToolCallApprovalPolicy::Never => AskForApproval::Never, } } } /// Custom enum mirroring [`SandboxMode`] from config_types.rs, but with /// `JsonSchema` support. #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)] #[serde(rename_all = "kebab-case")] pub enum CodexToolCallSandboxMode { ReadOnly, WorkspaceWrite, DangerFullAccess, } impl From<CodexToolCallSandboxMode> for SandboxMode { fn from(value: CodexToolCallSandboxMode) -> Self { match value { CodexToolCallSandboxMode::ReadOnly => SandboxMode::ReadOnly, CodexToolCallSandboxMode::WorkspaceWrite => SandboxMode::WorkspaceWrite, CodexToolCallSandboxMode::DangerFullAccess => SandboxMode::DangerFullAccess, } } } /// Builds a `Tool` definition (JSON schema etc.) for the Codex tool-call. pub(crate) fn create_tool_for_codex_tool_call_param() -> Tool { let schema = SchemaSettings::draft2019_09() .with(|s| { s.inline_subschemas = true; s.option_add_null_type = false; }) .into_generator() .into_root_schema_for::<CodexToolCallParam>(); #[expect(clippy::expect_used)] let schema_value = serde_json::to_value(&schema).expect("Codex tool schema should serialise to JSON"); let tool_input_schema = serde_json::from_value::<ToolInputSchema>(schema_value).unwrap_or_else(|e| { panic!("failed to create Tool from schema: {e}"); }); Tool { name: "codex".to_string(), title: Some("Codex".to_string()), input_schema: tool_input_schema, // TODO(mbolin): This should be defined. output_schema: None, description: Some( "Run a Codex session. Accepts configuration parameters matching the Codex Config struct.".to_string(), ), annotations: None, } } impl CodexToolCallParam { /// Returns the initial user prompt to start the Codex conversation and the /// effective Config object generated from the supplied parameters. pub async fn into_config( self, codex_linux_sandbox_exe: Option<PathBuf>, ) -> std::io::Result<(String, Config)> { let Self { prompt, model, profile, cwd, approval_policy, sandbox, config: cli_overrides, base_instructions, developer_instructions, compact_prompt, } = self; // Build the `ConfigOverrides` recognized by codex-core. let overrides = ConfigOverrides { model, config_profile: profile, cwd: cwd.map(PathBuf::from), approval_policy: approval_policy.map(Into::into), sandbox_mode: sandbox.map(Into::into), codex_linux_sandbox_exe, base_instructions, developer_instructions, compact_prompt, ..Default::default() }; let cli_overrides = cli_overrides .unwrap_or_default() .into_iter() .map(|(k, v)| (k, json_to_toml(v))) .collect(); let cfg = Config::load_with_cli_overrides_and_harness_overrides(cli_overrides, overrides).await?; Ok((prompt, cfg)) } } #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] pub struct CodexToolCallReplyParam { /// The conversation id for this Codex session. pub conversation_id: String, /// The *next user prompt* to continue the Codex conversation. pub prompt: String, } /// Builds a `Tool` definition for the `codex-reply` tool-call. pub(crate) fn create_tool_for_codex_tool_call_reply_param() -> Tool { let schema = SchemaSettings::draft2019_09() .with(|s| { s.inline_subschemas = true; s.option_add_null_type = false; }) .into_generator() .into_root_schema_for::<CodexToolCallReplyParam>(); #[expect(clippy::expect_used)] let schema_value = serde_json::to_value(&schema).expect("Codex reply tool schema should serialise to JSON"); let tool_input_schema = serde_json::from_value::<ToolInputSchema>(schema_value).unwrap_or_else(|e| { panic!("failed to create Tool from schema: {e}"); }); Tool { name: "codex-reply".to_string(), title: Some("Codex Reply".to_string()), input_schema: tool_input_schema, output_schema: None, description: Some( "Continue a Codex conversation by providing the conversation id and prompt." .to_string(), ), annotations: None, } } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; /// We include a test to verify the exact JSON schema as "executable /// documentation" for the schema. When can track changes to this test as a /// way to audit changes to the generated schema. /// /// Seeing the fully expanded schema makes it easier to casually verify that /// the generated JSON for enum types such as "approval-policy" is compact. /// Ideally, modelcontextprotocol/inspector would provide a simpler UI for /// enum fields versus open string fields to take advantage of this. /// /// As of 2025-05-04, there is an open PR for this: /// https://github.com/modelcontextprotocol/inspector/pull/196 #[test] fn verify_codex_tool_json_schema() { let tool = create_tool_for_codex_tool_call_param(); let tool_json = serde_json::to_value(&tool).expect("tool serializes"); let expected_tool_json = serde_json::json!({ "name": "codex", "title": "Codex", "description": "Run a Codex session. Accepts configuration parameters matching the Codex Config struct.", "inputSchema": { "type": "object", "properties": { "approval-policy": { "description": "Approval policy for shell commands generated by the model: `untrusted`, `on-failure`, `on-request`, `never`.", "enum": [ "untrusted", "on-failure", "on-request", "never" ], "type": "string" }, "sandbox": { "description": "Sandbox mode: `read-only`, `workspace-write`, or `danger-full-access`.", "enum": [ "read-only", "workspace-write", "danger-full-access" ], "type": "string" }, "config": { "description": "Individual config settings that will override what is in CODEX_HOME/config.toml.", "additionalProperties": true, "type": "object" }, "cwd": { "description": "Working directory for the session. If relative, it is resolved against the server process's current working directory.", "type": "string" }, "model": { "description": "Optional override for the model name (e.g. \"o3\", \"o4-mini\").", "type": "string" }, "profile": { "description": "Configuration profile from config.toml to specify default options.", "type": "string" }, "prompt": { "description": "The *initial user prompt* to start the Codex conversation.", "type": "string" }, "base-instructions": { "description": "The set of instructions to use instead of the default ones.", "type": "string" }, "developer-instructions": { "description": "Developer instructions that should be injected as a developer role message.", "type": "string" }, "compact-prompt": { "description": "Prompt used when compacting the conversation.", "type": "string" }, }, "required": [ "prompt" ] } }); assert_eq!(expected_tool_json, tool_json); } #[test] fn verify_codex_tool_reply_json_schema() { let tool = create_tool_for_codex_tool_call_reply_param(); let tool_json = serde_json::to_value(&tool).expect("tool serializes"); let expected_tool_json = serde_json::json!({ "description": "Continue a Codex conversation by providing the conversation id and prompt.", "inputSchema": { "properties": { "conversationId": { "description": "The conversation id for this Codex session.", "type": "string" }, "prompt": { "description": "The *next user prompt* to continue the Codex conversation.", "type": "string" }, }, "required": [ "conversationId", "prompt", ], "type": "object", }, "name": "codex-reply", "title": "Codex Reply", }); assert_eq!(expected_tool_json, tool_json); } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/src/lib.rs
codex-rs/mcp-server/src/lib.rs
//! Prototype MCP server. #![deny(clippy::print_stdout, clippy::print_stderr)] use std::io::ErrorKind; use std::io::Result as IoResult; use std::path::PathBuf; use codex_common::CliConfigOverrides; use codex_core::config::Config; use mcp_types::JSONRPCMessage; use tokio::io::AsyncBufReadExt; use tokio::io::AsyncWriteExt; use tokio::io::BufReader; use tokio::io::{self}; use tokio::sync::mpsc; use tracing::debug; use tracing::error; use tracing::info; use tracing_subscriber::EnvFilter; mod codex_tool_config; mod codex_tool_runner; mod error_code; mod exec_approval; pub(crate) mod message_processor; mod outgoing_message; mod patch_approval; use crate::message_processor::MessageProcessor; use crate::outgoing_message::OutgoingMessage; use crate::outgoing_message::OutgoingMessageSender; pub use crate::codex_tool_config::CodexToolCallParam; pub use crate::codex_tool_config::CodexToolCallReplyParam; pub use crate::exec_approval::ExecApprovalElicitRequestParams; pub use crate::exec_approval::ExecApprovalResponse; pub use crate::patch_approval::PatchApprovalElicitRequestParams; pub use crate::patch_approval::PatchApprovalResponse; /// Size of the bounded channels used to communicate between tasks. The value /// is a balance between throughput and memory usage – 128 messages should be /// plenty for an interactive CLI. const CHANNEL_CAPACITY: usize = 128; pub async fn run_main( codex_linux_sandbox_exe: Option<PathBuf>, cli_config_overrides: CliConfigOverrides, ) -> IoResult<()> { // Install a simple subscriber so `tracing` output is visible. Users can // control the log level with `RUST_LOG`. tracing_subscriber::fmt() .with_writer(std::io::stderr) .with_env_filter(EnvFilter::from_default_env()) .init(); // Set up channels. let (incoming_tx, mut incoming_rx) = mpsc::channel::<JSONRPCMessage>(CHANNEL_CAPACITY); let (outgoing_tx, mut outgoing_rx) = mpsc::unbounded_channel::<OutgoingMessage>(); // Task: read from stdin, push to `incoming_tx`. let stdin_reader_handle = tokio::spawn({ async move { let stdin = io::stdin(); let reader = BufReader::new(stdin); let mut lines = reader.lines(); while let Some(line) = lines.next_line().await.unwrap_or_default() { match serde_json::from_str::<JSONRPCMessage>(&line) { Ok(msg) => { if incoming_tx.send(msg).await.is_err() { // Receiver gone – nothing left to do. break; } } Err(e) => error!("Failed to deserialize JSONRPCMessage: {e}"), } } debug!("stdin reader finished (EOF)"); } }); // Parse CLI overrides once and derive the base Config eagerly so later // components do not need to work with raw TOML values. let cli_kv_overrides = cli_config_overrides.parse_overrides().map_err(|e| { std::io::Error::new( ErrorKind::InvalidInput, format!("error parsing -c overrides: {e}"), ) })?; let config = Config::load_with_cli_overrides(cli_kv_overrides) .await .map_err(|e| { std::io::Error::new(ErrorKind::InvalidData, format!("error loading config: {e}")) })?; // Task: process incoming messages. let processor_handle = tokio::spawn({ let outgoing_message_sender = OutgoingMessageSender::new(outgoing_tx); let mut processor = MessageProcessor::new( outgoing_message_sender, codex_linux_sandbox_exe, std::sync::Arc::new(config), ); async move { while let Some(msg) = incoming_rx.recv().await { match msg { JSONRPCMessage::Request(r) => processor.process_request(r).await, JSONRPCMessage::Response(r) => processor.process_response(r).await, JSONRPCMessage::Notification(n) => processor.process_notification(n).await, JSONRPCMessage::Error(e) => processor.process_error(e), } } info!("processor task exited (channel closed)"); } }); // Task: write outgoing messages to stdout. let stdout_writer_handle = tokio::spawn(async move { let mut stdout = io::stdout(); while let Some(outgoing_message) = outgoing_rx.recv().await { let msg: JSONRPCMessage = outgoing_message.into(); match serde_json::to_string(&msg) { Ok(json) => { if let Err(e) = stdout.write_all(json.as_bytes()).await { error!("Failed to write to stdout: {e}"); break; } if let Err(e) = stdout.write_all(b"\n").await { error!("Failed to write newline to stdout: {e}"); break; } } Err(e) => error!("Failed to serialize JSONRPCMessage: {e}"), } } info!("stdout writer exited (channel closed)"); }); // Wait for all tasks to finish. The typical exit path is the stdin reader // hitting EOF which, once it drops `incoming_tx`, propagates shutdown to // the processor and then to the stdout task. let _ = tokio::join!(stdin_reader_handle, processor_handle, stdout_writer_handle); Ok(()) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/src/message_processor.rs
codex-rs/mcp-server/src/message_processor.rs
use std::collections::HashMap; use std::path::PathBuf; use crate::codex_tool_config::CodexToolCallParam; use crate::codex_tool_config::CodexToolCallReplyParam; use crate::codex_tool_config::create_tool_for_codex_tool_call_param; use crate::codex_tool_config::create_tool_for_codex_tool_call_reply_param; use crate::error_code::INVALID_REQUEST_ERROR_CODE; use crate::outgoing_message::OutgoingMessageSender; use codex_protocol::ConversationId; use codex_protocol::protocol::SessionSource; use codex_core::AuthManager; use codex_core::ConversationManager; use codex_core::config::Config; use codex_core::default_client::USER_AGENT_SUFFIX; use codex_core::default_client::get_codex_user_agent; use codex_core::protocol::Submission; use mcp_types::CallToolRequestParams; use mcp_types::CallToolResult; use mcp_types::ClientRequest as McpClientRequest; use mcp_types::ContentBlock; use mcp_types::JSONRPCError; use mcp_types::JSONRPCErrorError; use mcp_types::JSONRPCNotification; use mcp_types::JSONRPCRequest; use mcp_types::JSONRPCResponse; use mcp_types::ListToolsResult; use mcp_types::ModelContextProtocolRequest; use mcp_types::RequestId; use mcp_types::ServerCapabilitiesTools; use mcp_types::ServerNotification; use mcp_types::TextContent; use serde_json::json; use std::sync::Arc; use tokio::sync::Mutex; use tokio::task; pub(crate) struct MessageProcessor { outgoing: Arc<OutgoingMessageSender>, initialized: bool, codex_linux_sandbox_exe: Option<PathBuf>, conversation_manager: Arc<ConversationManager>, running_requests_id_to_codex_uuid: Arc<Mutex<HashMap<RequestId, ConversationId>>>, } impl MessageProcessor { /// Create a new `MessageProcessor`, retaining a handle to the outgoing /// `Sender` so handlers can enqueue messages to be written to stdout. pub(crate) fn new( outgoing: OutgoingMessageSender, codex_linux_sandbox_exe: Option<PathBuf>, config: Arc<Config>, ) -> Self { let outgoing = Arc::new(outgoing); let auth_manager = AuthManager::shared( config.codex_home.clone(), false, config.cli_auth_credentials_store_mode, ); let conversation_manager = Arc::new(ConversationManager::new(auth_manager, SessionSource::Mcp)); Self { outgoing, initialized: false, codex_linux_sandbox_exe, conversation_manager, running_requests_id_to_codex_uuid: Arc::new(Mutex::new(HashMap::new())), } } pub(crate) async fn process_request(&mut self, request: JSONRPCRequest) { // Hold on to the ID so we can respond. let request_id = request.id.clone(); let client_request = match McpClientRequest::try_from(request) { Ok(client_request) => client_request, Err(e) => { tracing::warn!("Failed to convert request: {e}"); return; } }; // Dispatch to a dedicated handler for each request type. match client_request { McpClientRequest::InitializeRequest(params) => { self.handle_initialize(request_id, params).await; } McpClientRequest::PingRequest(params) => { self.handle_ping(request_id, params).await; } McpClientRequest::ListResourcesRequest(params) => { self.handle_list_resources(params); } McpClientRequest::ListResourceTemplatesRequest(params) => { self.handle_list_resource_templates(params); } McpClientRequest::ReadResourceRequest(params) => { self.handle_read_resource(params); } McpClientRequest::SubscribeRequest(params) => { self.handle_subscribe(params); } McpClientRequest::UnsubscribeRequest(params) => { self.handle_unsubscribe(params); } McpClientRequest::ListPromptsRequest(params) => { self.handle_list_prompts(params); } McpClientRequest::GetPromptRequest(params) => { self.handle_get_prompt(params); } McpClientRequest::ListToolsRequest(params) => { self.handle_list_tools(request_id, params).await; } McpClientRequest::CallToolRequest(params) => { self.handle_call_tool(request_id, params).await; } McpClientRequest::SetLevelRequest(params) => { self.handle_set_level(params); } McpClientRequest::CompleteRequest(params) => { self.handle_complete(params); } } } /// Handle a standalone JSON-RPC response originating from the peer. pub(crate) async fn process_response(&mut self, response: JSONRPCResponse) { tracing::info!("<- response: {:?}", response); let JSONRPCResponse { id, result, .. } = response; self.outgoing.notify_client_response(id, result).await } /// Handle a fire-and-forget JSON-RPC notification. pub(crate) async fn process_notification(&mut self, notification: JSONRPCNotification) { let server_notification = match ServerNotification::try_from(notification) { Ok(n) => n, Err(e) => { tracing::warn!("Failed to convert notification: {e}"); return; } }; // Similar to requests, route each notification type to its own stub // handler so additional logic can be implemented incrementally. match server_notification { ServerNotification::CancelledNotification(params) => { self.handle_cancelled_notification(params).await; } ServerNotification::ProgressNotification(params) => { self.handle_progress_notification(params); } ServerNotification::ResourceListChangedNotification(params) => { self.handle_resource_list_changed(params); } ServerNotification::ResourceUpdatedNotification(params) => { self.handle_resource_updated(params); } ServerNotification::PromptListChangedNotification(params) => { self.handle_prompt_list_changed(params); } ServerNotification::ToolListChangedNotification(params) => { self.handle_tool_list_changed(params); } ServerNotification::LoggingMessageNotification(params) => { self.handle_logging_message(params); } } } /// Handle an error object received from the peer. pub(crate) fn process_error(&mut self, err: JSONRPCError) { tracing::error!("<- error: {:?}", err); } async fn handle_initialize( &mut self, id: RequestId, params: <mcp_types::InitializeRequest as ModelContextProtocolRequest>::Params, ) { tracing::info!("initialize -> params: {:?}", params); if self.initialized { // Already initialised: send JSON-RPC error response. let error = JSONRPCErrorError { code: INVALID_REQUEST_ERROR_CODE, message: "initialize called more than once".to_string(), data: None, }; self.outgoing.send_error(id, error).await; return; } let client_info = params.client_info; let name = client_info.name; let version = client_info.version; let user_agent_suffix = format!("{name}; {version}"); if let Ok(mut suffix) = USER_AGENT_SUFFIX.lock() { *suffix = Some(user_agent_suffix); } self.initialized = true; // Build a minimal InitializeResult. Fill with placeholders. let result = mcp_types::InitializeResult { capabilities: mcp_types::ServerCapabilities { completions: None, experimental: None, logging: None, prompts: None, resources: None, tools: Some(ServerCapabilitiesTools { list_changed: Some(true), }), }, instructions: None, protocol_version: params.protocol_version.clone(), server_info: mcp_types::Implementation { name: "codex-mcp-server".to_string(), version: env!("CARGO_PKG_VERSION").to_string(), title: Some("Codex".to_string()), user_agent: Some(get_codex_user_agent()), }, }; self.send_response::<mcp_types::InitializeRequest>(id, result) .await; } async fn send_response<T>(&self, id: RequestId, result: T::Result) where T: ModelContextProtocolRequest, { self.outgoing.send_response(id, result).await; } async fn handle_ping( &self, id: RequestId, params: <mcp_types::PingRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::info!("ping -> params: {:?}", params); let result = json!({}); self.send_response::<mcp_types::PingRequest>(id, result) .await; } fn handle_list_resources( &self, params: <mcp_types::ListResourcesRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::info!("resources/list -> params: {:?}", params); } fn handle_list_resource_templates( &self, params: <mcp_types::ListResourceTemplatesRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::info!("resources/templates/list -> params: {:?}", params); } fn handle_read_resource( &self, params: <mcp_types::ReadResourceRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::info!("resources/read -> params: {:?}", params); } fn handle_subscribe( &self, params: <mcp_types::SubscribeRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::info!("resources/subscribe -> params: {:?}", params); } fn handle_unsubscribe( &self, params: <mcp_types::UnsubscribeRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::info!("resources/unsubscribe -> params: {:?}", params); } fn handle_list_prompts( &self, params: <mcp_types::ListPromptsRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::info!("prompts/list -> params: {:?}", params); } fn handle_get_prompt( &self, params: <mcp_types::GetPromptRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::info!("prompts/get -> params: {:?}", params); } async fn handle_list_tools( &self, id: RequestId, params: <mcp_types::ListToolsRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::trace!("tools/list -> {params:?}"); let result = ListToolsResult { tools: vec![ create_tool_for_codex_tool_call_param(), create_tool_for_codex_tool_call_reply_param(), ], next_cursor: None, }; self.send_response::<mcp_types::ListToolsRequest>(id, result) .await; } async fn handle_call_tool( &self, id: RequestId, params: <mcp_types::CallToolRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::info!("tools/call -> params: {:?}", params); let CallToolRequestParams { name, arguments } = params; match name.as_str() { "codex" => self.handle_tool_call_codex(id, arguments).await, "codex-reply" => { self.handle_tool_call_codex_session_reply(id, arguments) .await } _ => { let result = CallToolResult { content: vec![ContentBlock::TextContent(TextContent { r#type: "text".to_string(), text: format!("Unknown tool '{name}'"), annotations: None, })], is_error: Some(true), structured_content: None, }; self.send_response::<mcp_types::CallToolRequest>(id, result) .await; } } } async fn handle_tool_call_codex(&self, id: RequestId, arguments: Option<serde_json::Value>) { let (initial_prompt, config): (String, Config) = match arguments { Some(json_val) => match serde_json::from_value::<CodexToolCallParam>(json_val) { Ok(tool_cfg) => match tool_cfg .into_config(self.codex_linux_sandbox_exe.clone()) .await { Ok(cfg) => cfg, Err(e) => { let result = CallToolResult { content: vec![ContentBlock::TextContent(TextContent { r#type: "text".to_owned(), text: format!( "Failed to load Codex configuration from overrides: {e}" ), annotations: None, })], is_error: Some(true), structured_content: None, }; self.send_response::<mcp_types::CallToolRequest>(id, result) .await; return; } }, Err(e) => { let result = CallToolResult { content: vec![ContentBlock::TextContent(TextContent { r#type: "text".to_owned(), text: format!("Failed to parse configuration for Codex tool: {e}"), annotations: None, })], is_error: Some(true), structured_content: None, }; self.send_response::<mcp_types::CallToolRequest>(id, result) .await; return; } }, None => { let result = CallToolResult { content: vec![ContentBlock::TextContent(TextContent { r#type: "text".to_string(), text: "Missing arguments for codex tool-call; the `prompt` field is required." .to_string(), annotations: None, })], is_error: Some(true), structured_content: None, }; self.send_response::<mcp_types::CallToolRequest>(id, result) .await; return; } }; // Clone outgoing and server to move into async task. let outgoing = self.outgoing.clone(); let conversation_manager = self.conversation_manager.clone(); let running_requests_id_to_codex_uuid = self.running_requests_id_to_codex_uuid.clone(); // Spawn an async task to handle the Codex session so that we do not // block the synchronous message-processing loop. task::spawn(async move { // Run the Codex session and stream events back to the client. crate::codex_tool_runner::run_codex_tool_session( id, initial_prompt, config, outgoing, conversation_manager, running_requests_id_to_codex_uuid, ) .await; }); } async fn handle_tool_call_codex_session_reply( &self, request_id: RequestId, arguments: Option<serde_json::Value>, ) { tracing::info!("tools/call -> params: {:?}", arguments); // parse arguments let CodexToolCallReplyParam { conversation_id, prompt, } = match arguments { Some(json_val) => match serde_json::from_value::<CodexToolCallReplyParam>(json_val) { Ok(params) => params, Err(e) => { tracing::error!("Failed to parse Codex tool call reply parameters: {e}"); let result = CallToolResult { content: vec![ContentBlock::TextContent(TextContent { r#type: "text".to_owned(), text: format!("Failed to parse configuration for Codex tool: {e}"), annotations: None, })], is_error: Some(true), structured_content: None, }; self.send_response::<mcp_types::CallToolRequest>(request_id, result) .await; return; } }, None => { tracing::error!( "Missing arguments for codex-reply tool-call; the `conversation_id` and `prompt` fields are required." ); let result = CallToolResult { content: vec![ContentBlock::TextContent(TextContent { r#type: "text".to_owned(), text: "Missing arguments for codex-reply tool-call; the `conversation_id` and `prompt` fields are required.".to_owned(), annotations: None, })], is_error: Some(true), structured_content: None, }; self.send_response::<mcp_types::CallToolRequest>(request_id, result) .await; return; } }; let conversation_id = match ConversationId::from_string(&conversation_id) { Ok(id) => id, Err(e) => { tracing::error!("Failed to parse conversation_id: {e}"); let result = CallToolResult { content: vec![ContentBlock::TextContent(TextContent { r#type: "text".to_owned(), text: format!("Failed to parse conversation_id: {e}"), annotations: None, })], is_error: Some(true), structured_content: None, }; self.send_response::<mcp_types::CallToolRequest>(request_id, result) .await; return; } }; // Clone outgoing to move into async task. let outgoing = self.outgoing.clone(); let running_requests_id_to_codex_uuid = self.running_requests_id_to_codex_uuid.clone(); let codex = match self .conversation_manager .get_conversation(conversation_id) .await { Ok(c) => c, Err(_) => { tracing::warn!("Session not found for conversation_id: {conversation_id}"); let result = CallToolResult { content: vec![ContentBlock::TextContent(TextContent { r#type: "text".to_owned(), text: format!("Session not found for conversation_id: {conversation_id}"), annotations: None, })], is_error: Some(true), structured_content: None, }; outgoing.send_response(request_id, result).await; return; } }; // Spawn the long-running reply handler. tokio::spawn({ let outgoing = outgoing.clone(); let prompt = prompt.clone(); let running_requests_id_to_codex_uuid = running_requests_id_to_codex_uuid.clone(); async move { crate::codex_tool_runner::run_codex_tool_session_reply( codex, outgoing, request_id, prompt, running_requests_id_to_codex_uuid, conversation_id, ) .await; } }); } fn handle_set_level( &self, params: <mcp_types::SetLevelRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::info!("logging/setLevel -> params: {:?}", params); } fn handle_complete( &self, params: <mcp_types::CompleteRequest as mcp_types::ModelContextProtocolRequest>::Params, ) { tracing::info!("completion/complete -> params: {:?}", params); } // --------------------------------------------------------------------- // Notification handlers // --------------------------------------------------------------------- async fn handle_cancelled_notification( &self, params: <mcp_types::CancelledNotification as mcp_types::ModelContextProtocolNotification>::Params, ) { let request_id = params.request_id; // Create a stable string form early for logging and submission id. let request_id_string = match &request_id { RequestId::String(s) => s.clone(), RequestId::Integer(i) => i.to_string(), }; // Obtain the conversation id while holding the first lock, then release. let conversation_id = { let map_guard = self.running_requests_id_to_codex_uuid.lock().await; match map_guard.get(&request_id) { Some(id) => *id, None => { tracing::warn!("Session not found for request_id: {}", request_id_string); return; } } }; tracing::info!("conversation_id: {conversation_id}"); // Obtain the Codex conversation from the server. let codex_arc = match self .conversation_manager .get_conversation(conversation_id) .await { Ok(c) => c, Err(_) => { tracing::warn!("Session not found for conversation_id: {conversation_id}"); return; } }; // Submit interrupt to Codex. let err = codex_arc .submit_with_id(Submission { id: request_id_string, op: codex_core::protocol::Op::Interrupt, }) .await; if let Err(e) = err { tracing::error!("Failed to submit interrupt to Codex: {e}"); return; } // unregister the id so we don't keep it in the map self.running_requests_id_to_codex_uuid .lock() .await .remove(&request_id); } fn handle_progress_notification( &self, params: <mcp_types::ProgressNotification as mcp_types::ModelContextProtocolNotification>::Params, ) { tracing::info!("notifications/progress -> params: {:?}", params); } fn handle_resource_list_changed( &self, params: <mcp_types::ResourceListChangedNotification as mcp_types::ModelContextProtocolNotification>::Params, ) { tracing::info!( "notifications/resources/list_changed -> params: {:?}", params ); } fn handle_resource_updated( &self, params: <mcp_types::ResourceUpdatedNotification as mcp_types::ModelContextProtocolNotification>::Params, ) { tracing::info!("notifications/resources/updated -> params: {:?}", params); } fn handle_prompt_list_changed( &self, params: <mcp_types::PromptListChangedNotification as mcp_types::ModelContextProtocolNotification>::Params, ) { tracing::info!("notifications/prompts/list_changed -> params: {:?}", params); } fn handle_tool_list_changed( &self, params: <mcp_types::ToolListChangedNotification as mcp_types::ModelContextProtocolNotification>::Params, ) { tracing::info!("notifications/tools/list_changed -> params: {:?}", params); } fn handle_logging_message( &self, params: <mcp_types::LoggingMessageNotification as mcp_types::ModelContextProtocolNotification>::Params, ) { tracing::info!("notifications/message -> params: {:?}", params); } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/src/exec_approval.rs
codex-rs/mcp-server/src/exec_approval.rs
use std::path::PathBuf; use std::sync::Arc; use codex_core::CodexConversation; use codex_core::protocol::Op; use codex_core::protocol::ReviewDecision; use codex_protocol::parse_command::ParsedCommand; use mcp_types::ElicitRequest; use mcp_types::ElicitRequestParamsRequestedSchema; use mcp_types::JSONRPCErrorError; use mcp_types::ModelContextProtocolRequest; use mcp_types::RequestId; use serde::Deserialize; use serde::Serialize; use serde_json::json; use tracing::error; use crate::codex_tool_runner::INVALID_PARAMS_ERROR_CODE; /// Conforms to [`mcp_types::ElicitRequestParams`] so that it can be used as the /// `params` field of an [`ElicitRequest`]. #[derive(Debug, Deserialize, Serialize)] pub struct ExecApprovalElicitRequestParams { // These fields are required so that `params` // conforms to ElicitRequestParams. pub message: String, #[serde(rename = "requestedSchema")] pub requested_schema: ElicitRequestParamsRequestedSchema, // These are additional fields the client can use to // correlate the request with the codex tool call. pub codex_elicitation: String, pub codex_mcp_tool_call_id: String, pub codex_event_id: String, pub codex_call_id: String, pub codex_command: Vec<String>, pub codex_cwd: PathBuf, pub codex_parsed_cmd: Vec<ParsedCommand>, } // TODO(mbolin): ExecApprovalResponse does not conform to ElicitResult. See: // - https://github.com/modelcontextprotocol/modelcontextprotocol/blob/f962dc1780fa5eed7fb7c8a0232f1fc83ef220cd/schema/2025-06-18/schema.json#L617-L636 // - https://modelcontextprotocol.io/specification/draft/client/elicitation#protocol-messages // It should have "action" and "content" fields. #[derive(Debug, Serialize, Deserialize)] pub struct ExecApprovalResponse { pub decision: ReviewDecision, } #[allow(clippy::too_many_arguments)] pub(crate) async fn handle_exec_approval_request( command: Vec<String>, cwd: PathBuf, outgoing: Arc<crate::outgoing_message::OutgoingMessageSender>, codex: Arc<CodexConversation>, request_id: RequestId, tool_call_id: String, event_id: String, call_id: String, codex_parsed_cmd: Vec<ParsedCommand>, ) { let escaped_command = shlex::try_join(command.iter().map(String::as_str)).unwrap_or_else(|_| command.join(" ")); let message = format!( "Allow Codex to run `{escaped_command}` in `{cwd}`?", cwd = cwd.to_string_lossy() ); let params = ExecApprovalElicitRequestParams { message, requested_schema: ElicitRequestParamsRequestedSchema { r#type: "object".to_string(), properties: json!({}), required: None, }, codex_elicitation: "exec-approval".to_string(), codex_mcp_tool_call_id: tool_call_id.clone(), codex_event_id: event_id.clone(), codex_call_id: call_id, codex_command: command, codex_cwd: cwd, codex_parsed_cmd, }; let params_json = match serde_json::to_value(&params) { Ok(value) => value, Err(err) => { let message = format!("Failed to serialize ExecApprovalElicitRequestParams: {err}"); error!("{message}"); outgoing .send_error( request_id.clone(), JSONRPCErrorError { code: INVALID_PARAMS_ERROR_CODE, message, data: None, }, ) .await; return; } }; let on_response = outgoing .send_request(ElicitRequest::METHOD, Some(params_json)) .await; // Listen for the response on a separate task so we don't block the main agent loop. { let codex = codex.clone(); let event_id = event_id.clone(); tokio::spawn(async move { on_exec_approval_response(event_id, on_response, codex).await; }); } } async fn on_exec_approval_response( event_id: String, receiver: tokio::sync::oneshot::Receiver<mcp_types::Result>, codex: Arc<CodexConversation>, ) { let response = receiver.await; let value = match response { Ok(value) => value, Err(err) => { error!("request failed: {err:?}"); return; } }; // Try to deserialize `value` and then make the appropriate call to `codex`. let response = serde_json::from_value::<ExecApprovalResponse>(value).unwrap_or_else(|err| { error!("failed to deserialize ExecApprovalResponse: {err}"); // If we cannot deserialize the response, we deny the request to be // conservative. ExecApprovalResponse { decision: ReviewDecision::Denied, } }); if let Err(err) = codex .submit(Op::ExecApproval { id: event_id, decision: response.decision, }) .await { error!("failed to submit ExecApproval: {err}"); } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/src/patch_approval.rs
codex-rs/mcp-server/src/patch_approval.rs
use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; use codex_core::CodexConversation; use codex_core::protocol::FileChange; use codex_core::protocol::Op; use codex_core::protocol::ReviewDecision; use mcp_types::ElicitRequest; use mcp_types::ElicitRequestParamsRequestedSchema; use mcp_types::JSONRPCErrorError; use mcp_types::ModelContextProtocolRequest; use mcp_types::RequestId; use serde::Deserialize; use serde::Serialize; use serde_json::json; use tracing::error; use crate::codex_tool_runner::INVALID_PARAMS_ERROR_CODE; use crate::outgoing_message::OutgoingMessageSender; #[derive(Debug, Serialize)] pub struct PatchApprovalElicitRequestParams { pub message: String, #[serde(rename = "requestedSchema")] pub requested_schema: ElicitRequestParamsRequestedSchema, pub codex_elicitation: String, pub codex_mcp_tool_call_id: String, pub codex_event_id: String, pub codex_call_id: String, #[serde(skip_serializing_if = "Option::is_none")] pub codex_reason: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub codex_grant_root: Option<PathBuf>, pub codex_changes: HashMap<PathBuf, FileChange>, } #[derive(Debug, Deserialize, Serialize)] pub struct PatchApprovalResponse { pub decision: ReviewDecision, } #[allow(clippy::too_many_arguments)] pub(crate) async fn handle_patch_approval_request( call_id: String, reason: Option<String>, grant_root: Option<PathBuf>, changes: HashMap<PathBuf, FileChange>, outgoing: Arc<OutgoingMessageSender>, codex: Arc<CodexConversation>, request_id: RequestId, tool_call_id: String, event_id: String, ) { let mut message_lines = Vec::new(); if let Some(r) = &reason { message_lines.push(r.clone()); } message_lines.push("Allow Codex to apply proposed code changes?".to_string()); let params = PatchApprovalElicitRequestParams { message: message_lines.join("\n"), requested_schema: ElicitRequestParamsRequestedSchema { r#type: "object".to_string(), properties: json!({}), required: None, }, codex_elicitation: "patch-approval".to_string(), codex_mcp_tool_call_id: tool_call_id.clone(), codex_event_id: event_id.clone(), codex_call_id: call_id, codex_reason: reason, codex_grant_root: grant_root, codex_changes: changes, }; let params_json = match serde_json::to_value(&params) { Ok(value) => value, Err(err) => { let message = format!("Failed to serialize PatchApprovalElicitRequestParams: {err}"); error!("{message}"); outgoing .send_error( request_id.clone(), JSONRPCErrorError { code: INVALID_PARAMS_ERROR_CODE, message, data: None, }, ) .await; return; } }; let on_response = outgoing .send_request(ElicitRequest::METHOD, Some(params_json)) .await; // Listen for the response on a separate task so we don't block the main agent loop. { let codex = codex.clone(); let event_id = event_id.clone(); tokio::spawn(async move { on_patch_approval_response(event_id, on_response, codex).await; }); } } pub(crate) async fn on_patch_approval_response( event_id: String, receiver: tokio::sync::oneshot::Receiver<mcp_types::Result>, codex: Arc<CodexConversation>, ) { let response = receiver.await; let value = match response { Ok(value) => value, Err(err) => { error!("request failed: {err:?}"); if let Err(submit_err) = codex .submit(Op::PatchApproval { id: event_id.clone(), decision: ReviewDecision::Denied, }) .await { error!("failed to submit denied PatchApproval after request failure: {submit_err}"); } return; } }; let response = serde_json::from_value::<PatchApprovalResponse>(value).unwrap_or_else(|err| { error!("failed to deserialize PatchApprovalResponse: {err}"); PatchApprovalResponse { decision: ReviewDecision::Denied, } }); if let Err(err) = codex .submit(Op::PatchApproval { id: event_id, decision: response.decision, }) .await { error!("failed to submit PatchApproval: {err}"); } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/src/main.rs
codex-rs/mcp-server/src/main.rs
use codex_arg0::arg0_dispatch_or_else; use codex_common::CliConfigOverrides; use codex_mcp_server::run_main; fn main() -> anyhow::Result<()> { arg0_dispatch_or_else(|codex_linux_sandbox_exe| async move { run_main(codex_linux_sandbox_exe, CliConfigOverrides::default()).await?; Ok(()) }) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/src/outgoing_message.rs
codex-rs/mcp-server/src/outgoing_message.rs
use std::collections::HashMap; use std::sync::atomic::AtomicI64; use std::sync::atomic::Ordering; use codex_core::protocol::Event; use mcp_types::JSONRPC_VERSION; use mcp_types::JSONRPCError; use mcp_types::JSONRPCErrorError; use mcp_types::JSONRPCMessage; use mcp_types::JSONRPCNotification; use mcp_types::JSONRPCRequest; use mcp_types::JSONRPCResponse; use mcp_types::RequestId; use mcp_types::Result; use serde::Serialize; use tokio::sync::Mutex; use tokio::sync::mpsc; use tokio::sync::oneshot; use tracing::warn; use crate::error_code::INTERNAL_ERROR_CODE; /// Sends messages to the client and manages request callbacks. pub(crate) struct OutgoingMessageSender { next_request_id: AtomicI64, sender: mpsc::UnboundedSender<OutgoingMessage>, request_id_to_callback: Mutex<HashMap<RequestId, oneshot::Sender<Result>>>, } impl OutgoingMessageSender { pub(crate) fn new(sender: mpsc::UnboundedSender<OutgoingMessage>) -> Self { Self { next_request_id: AtomicI64::new(0), sender, request_id_to_callback: Mutex::new(HashMap::new()), } } pub(crate) async fn send_request( &self, method: &str, params: Option<serde_json::Value>, ) -> oneshot::Receiver<Result> { let id = RequestId::Integer(self.next_request_id.fetch_add(1, Ordering::Relaxed)); let outgoing_message_id = id.clone(); let (tx_approve, rx_approve) = oneshot::channel(); { let mut request_id_to_callback = self.request_id_to_callback.lock().await; request_id_to_callback.insert(id, tx_approve); } let outgoing_message = OutgoingMessage::Request(OutgoingRequest { id: outgoing_message_id, method: method.to_string(), params, }); let _ = self.sender.send(outgoing_message); rx_approve } pub(crate) async fn notify_client_response(&self, id: RequestId, result: Result) { let entry = { let mut request_id_to_callback = self.request_id_to_callback.lock().await; request_id_to_callback.remove_entry(&id) }; match entry { Some((id, sender)) => { if let Err(err) = sender.send(result) { warn!("could not notify callback for {id:?} due to: {err:?}"); } } None => { warn!("could not find callback for {id:?}"); } } } pub(crate) async fn send_response<T: Serialize>(&self, id: RequestId, response: T) { match serde_json::to_value(response) { Ok(result) => { let outgoing_message = OutgoingMessage::Response(OutgoingResponse { id, result }); let _ = self.sender.send(outgoing_message); } Err(err) => { self.send_error( id, JSONRPCErrorError { code: INTERNAL_ERROR_CODE, message: format!("failed to serialize response: {err}"), data: None, }, ) .await; } } } /// This is used with the MCP server, but not the more general JSON-RPC app /// server. Prefer [`OutgoingMessageSender::send_server_notification`] where /// possible. pub(crate) async fn send_event_as_notification( &self, event: &Event, meta: Option<OutgoingNotificationMeta>, ) { #[expect(clippy::expect_used)] let event_json = serde_json::to_value(event).expect("Event must serialize"); let params = if let Ok(params) = serde_json::to_value(OutgoingNotificationParams { meta, event: event_json.clone(), }) { params } else { warn!("Failed to serialize event as OutgoingNotificationParams"); event_json }; self.send_notification(OutgoingNotification { method: "codex/event".to_string(), params: Some(params.clone()), }) .await; } pub(crate) async fn send_notification(&self, notification: OutgoingNotification) { let outgoing_message = OutgoingMessage::Notification(notification); let _ = self.sender.send(outgoing_message); } pub(crate) async fn send_error(&self, id: RequestId, error: JSONRPCErrorError) { let outgoing_message = OutgoingMessage::Error(OutgoingError { id, error }); let _ = self.sender.send(outgoing_message); } } /// Outgoing message from the server to the client. pub(crate) enum OutgoingMessage { Request(OutgoingRequest), Notification(OutgoingNotification), Response(OutgoingResponse), Error(OutgoingError), } impl From<OutgoingMessage> for JSONRPCMessage { fn from(val: OutgoingMessage) -> Self { use OutgoingMessage::*; match val { Request(OutgoingRequest { id, method, params }) => { JSONRPCMessage::Request(JSONRPCRequest { jsonrpc: JSONRPC_VERSION.into(), id, method, params, }) } Notification(OutgoingNotification { method, params }) => { JSONRPCMessage::Notification(JSONRPCNotification { jsonrpc: JSONRPC_VERSION.into(), method, params, }) } Response(OutgoingResponse { id, result }) => { JSONRPCMessage::Response(JSONRPCResponse { jsonrpc: JSONRPC_VERSION.into(), id, result, }) } Error(OutgoingError { id, error }) => JSONRPCMessage::Error(JSONRPCError { jsonrpc: JSONRPC_VERSION.into(), id, error, }), } } } #[derive(Debug, Clone, PartialEq, Serialize)] pub(crate) struct OutgoingRequest { pub id: RequestId, pub method: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub params: Option<serde_json::Value>, } #[derive(Debug, Clone, PartialEq, Serialize)] pub(crate) struct OutgoingNotification { pub method: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub params: Option<serde_json::Value>, } #[derive(Debug, Clone, PartialEq, Serialize)] pub(crate) struct OutgoingNotificationParams { #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] pub meta: Option<OutgoingNotificationMeta>, #[serde(flatten)] pub event: serde_json::Value, } // Additional mcp-specific data to be added to a [`codex_core::protocol::Event`] as notification.params._meta // MCP Spec: https://modelcontextprotocol.io/specification/2025-06-18/basic#meta // Typescript Schema: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/0695a497eb50a804fc0e88c18a93a21a675d6b3e/schema/2025-06-18/schema.ts #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub(crate) struct OutgoingNotificationMeta { pub request_id: Option<RequestId>, } impl OutgoingNotificationMeta { pub(crate) fn new(request_id: Option<RequestId>) -> Self { Self { request_id } } } #[derive(Debug, Clone, PartialEq, Serialize)] pub(crate) struct OutgoingResponse { pub id: RequestId, pub result: Result, } #[derive(Debug, Clone, PartialEq, Serialize)] pub(crate) struct OutgoingError { pub error: JSONRPCErrorError, pub id: RequestId, } #[cfg(test)] mod tests { use std::path::PathBuf; use anyhow::Result; use codex_core::protocol::AskForApproval; use codex_core::protocol::EventMsg; use codex_core::protocol::SandboxPolicy; use codex_core::protocol::SessionConfiguredEvent; use codex_protocol::ConversationId; use codex_protocol::openai_models::ReasoningEffort; use pretty_assertions::assert_eq; use serde_json::json; use tempfile::NamedTempFile; use super::*; #[tokio::test] async fn test_send_event_as_notification() -> Result<()> { let (outgoing_tx, mut outgoing_rx) = mpsc::unbounded_channel::<OutgoingMessage>(); let outgoing_message_sender = OutgoingMessageSender::new(outgoing_tx); let conversation_id = ConversationId::new(); let rollout_file = NamedTempFile::new()?; let event = Event { id: "1".to_string(), msg: EventMsg::SessionConfigured(SessionConfiguredEvent { session_id: conversation_id, model: "gpt-4o".to_string(), model_provider_id: "test-provider".to_string(), approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::ReadOnly, cwd: PathBuf::from("/home/user/project"), reasoning_effort: Some(ReasoningEffort::default()), history_log_id: 1, history_entry_count: 1000, initial_messages: None, rollout_path: rollout_file.path().to_path_buf(), }), }; outgoing_message_sender .send_event_as_notification(&event, None) .await; let result = outgoing_rx.recv().await.unwrap(); let OutgoingMessage::Notification(OutgoingNotification { method, params }) = result else { panic!("expected Notification for first message"); }; assert_eq!(method, "codex/event"); let Ok(expected_params) = serde_json::to_value(&event) else { panic!("Event must serialize"); }; assert_eq!(params, Some(expected_params)); Ok(()) } #[tokio::test] async fn test_send_event_as_notification_with_meta() -> Result<()> { let (outgoing_tx, mut outgoing_rx) = mpsc::unbounded_channel::<OutgoingMessage>(); let outgoing_message_sender = OutgoingMessageSender::new(outgoing_tx); let conversation_id = ConversationId::new(); let rollout_file = NamedTempFile::new()?; let session_configured_event = SessionConfiguredEvent { session_id: conversation_id, model: "gpt-4o".to_string(), model_provider_id: "test-provider".to_string(), approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::ReadOnly, cwd: PathBuf::from("/home/user/project"), reasoning_effort: Some(ReasoningEffort::default()), history_log_id: 1, history_entry_count: 1000, initial_messages: None, rollout_path: rollout_file.path().to_path_buf(), }; let event = Event { id: "1".to_string(), msg: EventMsg::SessionConfigured(session_configured_event.clone()), }; let meta = OutgoingNotificationMeta { request_id: Some(RequestId::String("123".to_string())), }; outgoing_message_sender .send_event_as_notification(&event, Some(meta)) .await; let result = outgoing_rx.recv().await.unwrap(); let OutgoingMessage::Notification(OutgoingNotification { method, params }) = result else { panic!("expected Notification for first message"); }; assert_eq!(method, "codex/event"); let expected_params = json!({ "_meta": { "requestId": "123", }, "id": "1", "msg": { "type": "session_configured", "session_id": session_configured_event.session_id, "model": "gpt-4o", "model_provider_id": "test-provider", "approval_policy": "never", "sandbox_policy": { "type": "read-only" }, "cwd": "/home/user/project", "reasoning_effort": session_configured_event.reasoning_effort, "history_log_id": session_configured_event.history_log_id, "history_entry_count": session_configured_event.history_entry_count, "rollout_path": rollout_file.path().to_path_buf(), } }); assert_eq!(params.unwrap(), expected_params); Ok(()) } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/src/tool_handlers/mod.rs
codex-rs/mcp-server/src/tool_handlers/mod.rs
pub(crate) mod create_conversation; pub(crate) mod send_message;
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/tests/all.rs
codex-rs/mcp-server/tests/all.rs
// Single integration test binary that aggregates all test modules. // The submodules live in `tests/suite/`. mod suite;
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/tests/suite/mod.rs
codex-rs/mcp-server/tests/suite/mod.rs
mod codex_tool;
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/tests/suite/codex_tool.rs
codex-rs/mcp-server/tests/suite/codex_tool.rs
use std::collections::HashMap; use std::env; use std::path::Path; use std::path::PathBuf; use codex_core::parse_command; use codex_core::protocol::FileChange; use codex_core::protocol::ReviewDecision; use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use codex_mcp_server::CodexToolCallParam; use codex_mcp_server::ExecApprovalElicitRequestParams; use codex_mcp_server::ExecApprovalResponse; use codex_mcp_server::PatchApprovalElicitRequestParams; use codex_mcp_server::PatchApprovalResponse; use mcp_types::ElicitRequest; use mcp_types::ElicitRequestParamsRequestedSchema; use mcp_types::JSONRPC_VERSION; use mcp_types::JSONRPCRequest; use mcp_types::JSONRPCResponse; use mcp_types::ModelContextProtocolRequest; use mcp_types::RequestId; use pretty_assertions::assert_eq; use serde_json::json; use tempfile::TempDir; use tokio::time::timeout; use wiremock::MockServer; use core_test_support::skip_if_no_network; use mcp_test_support::McpProcess; use mcp_test_support::create_apply_patch_sse_response; use mcp_test_support::create_final_assistant_message_sse_response; use mcp_test_support::create_mock_chat_completions_server; use mcp_test_support::create_shell_command_sse_response; use mcp_test_support::format_with_current_shell; // Allow ample time on slower CI or under load to avoid flakes. const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); /// Test that a shell command that is not on the "trusted" list triggers an /// elicitation request to the MCP and that sending the approval runs the /// command, as expected. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn test_shell_command_approval_triggers_elicitation() { if env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { println!( "Skipping test because it cannot execute when network is disabled in a Codex sandbox." ); return; } // Apparently `#[tokio::test]` must return `()`, so we create a helper // function that returns `Result` so we can use `?` in favor of `unwrap`. if let Err(err) = shell_command_approval_triggers_elicitation().await { panic!("failure: {err}"); } } async fn shell_command_approval_triggers_elicitation() -> anyhow::Result<()> { // Use a simple, untrusted command that creates a file so we can // observe a side-effect. // // Cross‑platform approach: run a tiny Python snippet to touch the file // using `python3 -c ...` on all platforms. let workdir_for_shell_function_call = TempDir::new()?; let created_filename = "created_by_shell_tool.txt"; let created_file = workdir_for_shell_function_call .path() .join(created_filename); let shell_command = vec![ "python3".to_string(), "-c".to_string(), format!("import pathlib; pathlib.Path('{created_filename}').touch()"), ]; let expected_shell_command = format_with_current_shell(&format!( "python3 -c \"import pathlib; pathlib.Path('{created_filename}').touch()\"" )); let McpHandle { process: mut mcp_process, server: _server, dir: _dir, } = create_mcp_process(vec![ create_shell_command_sse_response( shell_command.clone(), Some(workdir_for_shell_function_call.path()), Some(5_000), "call1234", )?, create_final_assistant_message_sse_response("File created!")?, ]) .await?; // Send a "codex" tool request, which should hit the completions endpoint. // In turn, it should reply with a tool call, which the MCP should forward // as an elicitation. let codex_request_id = mcp_process .send_codex_tool_call(CodexToolCallParam { prompt: "run `git init`".to_string(), ..Default::default() }) .await?; let elicitation_request = timeout( DEFAULT_READ_TIMEOUT, mcp_process.read_stream_until_request_message(), ) .await??; let elicitation_request_id = elicitation_request.id.clone(); let params = serde_json::from_value::<ExecApprovalElicitRequestParams>( elicitation_request .params .clone() .ok_or_else(|| anyhow::anyhow!("elicitation_request.params must be set"))?, )?; let expected_elicitation_request = create_expected_elicitation_request( elicitation_request_id.clone(), expected_shell_command, workdir_for_shell_function_call.path(), codex_request_id.to_string(), params.codex_event_id.clone(), )?; assert_eq!(expected_elicitation_request, elicitation_request); // Accept the `git init` request by responding to the elicitation. mcp_process .send_response( elicitation_request_id, serde_json::to_value(ExecApprovalResponse { decision: ReviewDecision::Approved, })?, ) .await?; // Verify task_complete notification arrives before the tool call completes. #[expect(clippy::expect_used)] let _task_complete = timeout( DEFAULT_READ_TIMEOUT, mcp_process.read_stream_until_legacy_task_complete_notification(), ) .await .expect("task_complete_notification timeout") .expect("task_complete_notification resp"); // Verify the original `codex` tool call completes and that the file was created. let codex_response = timeout( DEFAULT_READ_TIMEOUT, mcp_process.read_stream_until_response_message(RequestId::Integer(codex_request_id)), ) .await??; assert_eq!( JSONRPCResponse { jsonrpc: JSONRPC_VERSION.into(), id: RequestId::Integer(codex_request_id), result: json!({ "content": [ { "text": "File created!", "type": "text" } ] }), }, codex_response ); assert!(created_file.is_file(), "created file should exist"); Ok(()) } fn create_expected_elicitation_request( elicitation_request_id: RequestId, command: Vec<String>, workdir: &Path, codex_mcp_tool_call_id: String, codex_event_id: String, ) -> anyhow::Result<JSONRPCRequest> { let expected_message = format!( "Allow Codex to run `{}` in `{}`?", shlex::try_join(command.iter().map(std::convert::AsRef::as_ref))?, workdir.to_string_lossy() ); let codex_parsed_cmd = parse_command::parse_command(&command); Ok(JSONRPCRequest { jsonrpc: JSONRPC_VERSION.into(), id: elicitation_request_id, method: ElicitRequest::METHOD.to_string(), params: Some(serde_json::to_value(&ExecApprovalElicitRequestParams { message: expected_message, requested_schema: ElicitRequestParamsRequestedSchema { r#type: "object".to_string(), properties: json!({}), required: None, }, codex_elicitation: "exec-approval".to_string(), codex_mcp_tool_call_id, codex_event_id, codex_command: command, codex_cwd: workdir.to_path_buf(), codex_call_id: "call1234".to_string(), codex_parsed_cmd, })?), }) } /// Test that patch approval triggers an elicitation request to the MCP and that /// sending the approval applies the patch, as expected. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_patch_approval_triggers_elicitation() { if env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { println!( "Skipping test because it cannot execute when network is disabled in a Codex sandbox." ); return; } if let Err(err) = patch_approval_triggers_elicitation().await { panic!("failure: {err}"); } } async fn patch_approval_triggers_elicitation() -> anyhow::Result<()> { if cfg!(windows) { // powershell apply_patch shell calls are not parsed into apply patch approvals return Ok(()); } let cwd = TempDir::new()?; let test_file = cwd.path().join("destination_file.txt"); std::fs::write(&test_file, "original content\n")?; let patch_content = format!( "*** Begin Patch\n*** Update File: {}\n-original content\n+modified content\n*** End Patch", test_file.as_path().to_string_lossy() ); let McpHandle { process: mut mcp_process, server: _server, dir: _dir, } = create_mcp_process(vec![ create_apply_patch_sse_response(&patch_content, "call1234")?, create_final_assistant_message_sse_response("Patch has been applied successfully!")?, ]) .await?; // Send a "codex" tool request that will trigger the apply_patch command let codex_request_id = mcp_process .send_codex_tool_call(CodexToolCallParam { cwd: Some(cwd.path().to_string_lossy().to_string()), prompt: "please modify the test file".to_string(), ..Default::default() }) .await?; let elicitation_request = timeout( DEFAULT_READ_TIMEOUT, mcp_process.read_stream_until_request_message(), ) .await??; let elicitation_request_id = RequestId::Integer(0); let mut expected_changes = HashMap::new(); expected_changes.insert( test_file.as_path().to_path_buf(), FileChange::Update { unified_diff: "@@ -1 +1 @@\n-original content\n+modified content\n".to_string(), move_path: None, }, ); let expected_elicitation_request = create_expected_patch_approval_elicitation_request( elicitation_request_id.clone(), expected_changes, None, // No grant_root expected None, // No reason expected codex_request_id.to_string(), "1".to_string(), )?; assert_eq!(expected_elicitation_request, elicitation_request); // Accept the patch approval request by responding to the elicitation mcp_process .send_response( elicitation_request_id, serde_json::to_value(PatchApprovalResponse { decision: ReviewDecision::Approved, })?, ) .await?; // Verify the original `codex` tool call completes let codex_response = timeout( DEFAULT_READ_TIMEOUT, mcp_process.read_stream_until_response_message(RequestId::Integer(codex_request_id)), ) .await??; assert_eq!( JSONRPCResponse { jsonrpc: JSONRPC_VERSION.into(), id: RequestId::Integer(codex_request_id), result: json!({ "content": [ { "text": "Patch has been applied successfully!", "type": "text" } ] }), }, codex_response ); let file_contents = std::fs::read_to_string(test_file.as_path())?; assert_eq!(file_contents, "modified content\n"); Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_codex_tool_passes_base_instructions() { skip_if_no_network!(); // Apparently `#[tokio::test]` must return `()`, so we create a helper // function that returns `Result` so we can use `?` in favor of `unwrap`. if let Err(err) = codex_tool_passes_base_instructions().await { panic!("failure: {err}"); } } async fn codex_tool_passes_base_instructions() -> anyhow::Result<()> { #![expect(clippy::unwrap_used)] let server = create_mock_chat_completions_server(vec![create_final_assistant_message_sse_response( "Enjoy!", )?]) .await; // Run `codex mcp` with a specific config.toml. let codex_home = TempDir::new()?; create_config_toml(codex_home.path(), &server.uri())?; let mut mcp_process = McpProcess::new(codex_home.path()).await?; timeout(DEFAULT_READ_TIMEOUT, mcp_process.initialize()).await??; // Send a "codex" tool request, which should hit the completions endpoint. let codex_request_id = mcp_process .send_codex_tool_call(CodexToolCallParam { prompt: "How are you?".to_string(), base_instructions: Some("You are a helpful assistant.".to_string()), developer_instructions: Some("Foreshadow upcoming tool calls.".to_string()), ..Default::default() }) .await?; let codex_response = timeout( DEFAULT_READ_TIMEOUT, mcp_process.read_stream_until_response_message(RequestId::Integer(codex_request_id)), ) .await??; assert_eq!( JSONRPCResponse { jsonrpc: JSONRPC_VERSION.into(), id: RequestId::Integer(codex_request_id), result: json!({ "content": [ { "text": "Enjoy!", "type": "text" } ] }), }, codex_response ); let requests = server.received_requests().await.unwrap(); let request = requests[0].body_json::<serde_json::Value>()?; let instructions = request["messages"][0]["content"].as_str().unwrap(); assert!(instructions.starts_with("You are a helpful assistant.")); let developer_msg = request["messages"] .as_array() .and_then(|messages| { messages .iter() .find(|msg| msg.get("role").and_then(|role| role.as_str()) == Some("developer")) }) .unwrap(); let developer_content = developer_msg .get("content") .and_then(|value| value.as_str()) .unwrap(); assert!( !developer_content.contains('<'), "expected developer instructions without XML tags, got `{developer_content}`" ); assert_eq!(developer_content, "Foreshadow upcoming tool calls."); Ok(()) } fn create_expected_patch_approval_elicitation_request( elicitation_request_id: RequestId, changes: HashMap<PathBuf, FileChange>, grant_root: Option<PathBuf>, reason: Option<String>, codex_mcp_tool_call_id: String, codex_event_id: String, ) -> anyhow::Result<JSONRPCRequest> { let mut message_lines = Vec::new(); if let Some(r) = &reason { message_lines.push(r.clone()); } message_lines.push("Allow Codex to apply proposed code changes?".to_string()); Ok(JSONRPCRequest { jsonrpc: JSONRPC_VERSION.into(), id: elicitation_request_id, method: ElicitRequest::METHOD.to_string(), params: Some(serde_json::to_value(&PatchApprovalElicitRequestParams { message: message_lines.join("\n"), requested_schema: ElicitRequestParamsRequestedSchema { r#type: "object".to_string(), properties: json!({}), required: None, }, codex_elicitation: "patch-approval".to_string(), codex_mcp_tool_call_id, codex_event_id, codex_reason: reason, codex_grant_root: grant_root, codex_changes: changes, codex_call_id: "call1234".to_string(), })?), }) } /// This handle is used to ensure that the MockServer and TempDir are not dropped while /// the McpProcess is still running. pub struct McpHandle { pub process: McpProcess, /// Retain the server for the lifetime of the McpProcess. #[allow(dead_code)] server: MockServer, /// Retain the temporary directory for the lifetime of the McpProcess. #[allow(dead_code)] dir: TempDir, } async fn create_mcp_process(responses: Vec<String>) -> anyhow::Result<McpHandle> { let server = create_mock_chat_completions_server(responses).await; let codex_home = TempDir::new()?; create_config_toml(codex_home.path(), &server.uri())?; let mut mcp_process = McpProcess::new(codex_home.path()).await?; timeout(DEFAULT_READ_TIMEOUT, mcp_process.initialize()).await??; Ok(McpHandle { process: mcp_process, server, dir: codex_home, }) } /// Create a Codex config that uses the mock server as the model provider. /// It also uses `approval_policy = "untrusted"` so that we exercise the /// elicitation code path for shell commands. fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { let config_toml = codex_home.join("config.toml"); std::fs::write( config_toml, format!( r#" model = "mock-model" approval_policy = "untrusted" sandbox_policy = "workspace-write" model_provider = "mock_provider" [model_providers.mock_provider] name = "Mock provider for test" base_url = "{server_uri}/v1" wire_api = "chat" request_max_retries = 0 stream_max_retries = 0 "# ), ) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/tests/common/responses.rs
codex-rs/mcp-server/tests/common/responses.rs
use serde_json::json; use std::path::Path; pub fn create_shell_command_sse_response( command: Vec<String>, workdir: Option<&Path>, timeout_ms: Option<u64>, call_id: &str, ) -> anyhow::Result<String> { // The `arguments` for the `shell_command` tool is a serialized JSON object. let command_str = shlex::try_join(command.iter().map(String::as_str))?; let tool_call_arguments = serde_json::to_string(&json!({ "command": command_str, "workdir": workdir.map(|w| w.to_string_lossy()), "timeout_ms": timeout_ms }))?; let tool_call = json!({ "choices": [ { "delta": { "tool_calls": [ { "id": call_id, "function": { "name": "shell_command", "arguments": tool_call_arguments } } ] }, "finish_reason": "tool_calls" } ] }); let sse = format!( "data: {}\n\ndata: DONE\n\n", serde_json::to_string(&tool_call)? ); Ok(sse) } pub fn create_final_assistant_message_sse_response(message: &str) -> anyhow::Result<String> { let assistant_message = json!({ "choices": [ { "delta": { "content": message }, "finish_reason": "stop" } ] }); let sse = format!( "data: {}\n\ndata: DONE\n\n", serde_json::to_string(&assistant_message)? ); Ok(sse) } pub fn create_apply_patch_sse_response( patch_content: &str, call_id: &str, ) -> anyhow::Result<String> { // Use shell_command to call apply_patch with heredoc format let command = format!("apply_patch <<'EOF'\n{patch_content}\nEOF"); let tool_call_arguments = serde_json::to_string(&json!({ "command": command }))?; let tool_call = json!({ "choices": [ { "delta": { "tool_calls": [ { "id": call_id, "function": { "name": "shell_command", "arguments": tool_call_arguments } } ] }, "finish_reason": "tool_calls" } ] }); let sse = format!( "data: {}\n\ndata: DONE\n\n", serde_json::to_string(&tool_call)? ); Ok(sse) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/tests/common/lib.rs
codex-rs/mcp-server/tests/common/lib.rs
mod mcp_process; mod mock_model_server; mod responses; pub use core_test_support::format_with_current_shell; pub use core_test_support::format_with_current_shell_display_non_login; pub use core_test_support::format_with_current_shell_non_login; pub use mcp_process::McpProcess; use mcp_types::JSONRPCResponse; pub use mock_model_server::create_mock_chat_completions_server; pub use responses::create_apply_patch_sse_response; pub use responses::create_final_assistant_message_sse_response; pub use responses::create_shell_command_sse_response; use serde::de::DeserializeOwned; pub fn to_response<T: DeserializeOwned>(response: JSONRPCResponse) -> anyhow::Result<T> { let value = serde_json::to_value(response.result)?; let codex_response = serde_json::from_value(value)?; Ok(codex_response) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/tests/common/mcp_process.rs
codex-rs/mcp-server/tests/common/mcp_process.rs
use std::path::Path; use std::process::Stdio; use std::sync::atomic::AtomicI64; use std::sync::atomic::Ordering; use tokio::io::AsyncBufReadExt; use tokio::io::AsyncWriteExt; use tokio::io::BufReader; use tokio::process::Child; use tokio::process::ChildStdin; use tokio::process::ChildStdout; use anyhow::Context; use codex_mcp_server::CodexToolCallParam; use mcp_types::CallToolRequestParams; use mcp_types::ClientCapabilities; use mcp_types::Implementation; use mcp_types::InitializeRequestParams; use mcp_types::JSONRPC_VERSION; use mcp_types::JSONRPCMessage; use mcp_types::JSONRPCNotification; use mcp_types::JSONRPCRequest; use mcp_types::JSONRPCResponse; use mcp_types::ModelContextProtocolNotification; use mcp_types::ModelContextProtocolRequest; use mcp_types::RequestId; use pretty_assertions::assert_eq; use serde_json::json; use tokio::process::Command; pub struct McpProcess { next_request_id: AtomicI64, /// Retain this child process until the client is dropped. The Tokio runtime /// will make a "best effort" to reap the process after it exits, but it is /// not a guarantee. See the `kill_on_drop` documentation for details. #[allow(dead_code)] process: Child, stdin: ChildStdin, stdout: BufReader<ChildStdout>, } impl McpProcess { pub async fn new(codex_home: &Path) -> anyhow::Result<Self> { Self::new_with_env(codex_home, &[]).await } /// Creates a new MCP process, allowing tests to override or remove /// specific environment variables for the child process only. /// /// Pass a tuple of (key, Some(value)) to set/override, or (key, None) to /// remove a variable from the child's environment. pub async fn new_with_env( codex_home: &Path, env_overrides: &[(&str, Option<&str>)], ) -> anyhow::Result<Self> { let program = codex_utils_cargo_bin::cargo_bin("codex-mcp-server") .context("should find binary for codex-mcp-server")?; let mut cmd = Command::new(program); cmd.stdin(Stdio::piped()); cmd.stdout(Stdio::piped()); cmd.stderr(Stdio::piped()); cmd.env("CODEX_HOME", codex_home); cmd.env("RUST_LOG", "debug"); for (k, v) in env_overrides { match v { Some(val) => { cmd.env(k, val); } None => { cmd.env_remove(k); } } } let mut process = cmd .kill_on_drop(true) .spawn() .context("codex-mcp-server proc should start")?; let stdin = process .stdin .take() .ok_or_else(|| anyhow::format_err!("mcp should have stdin fd"))?; let stdout = process .stdout .take() .ok_or_else(|| anyhow::format_err!("mcp should have stdout fd"))?; let stdout = BufReader::new(stdout); // Forward child's stderr to our stderr so failures are visible even // when stdout/stderr are captured by the test harness. if let Some(stderr) = process.stderr.take() { let mut stderr_reader = BufReader::new(stderr).lines(); tokio::spawn(async move { while let Ok(Some(line)) = stderr_reader.next_line().await { eprintln!("[mcp stderr] {line}"); } }); } Ok(Self { next_request_id: AtomicI64::new(0), process, stdin, stdout, }) } /// Performs the initialization handshake with the MCP server. pub async fn initialize(&mut self) -> anyhow::Result<()> { let request_id = self.next_request_id.fetch_add(1, Ordering::Relaxed); let params = InitializeRequestParams { capabilities: ClientCapabilities { elicitation: Some(json!({})), experimental: None, roots: None, sampling: None, }, client_info: Implementation { name: "elicitation test".into(), title: Some("Elicitation Test".into()), version: "0.0.0".into(), user_agent: None, }, protocol_version: mcp_types::MCP_SCHEMA_VERSION.into(), }; let params_value = serde_json::to_value(params)?; self.send_jsonrpc_message(JSONRPCMessage::Request(JSONRPCRequest { jsonrpc: JSONRPC_VERSION.into(), id: RequestId::Integer(request_id), method: mcp_types::InitializeRequest::METHOD.into(), params: Some(params_value), })) .await?; let initialized = self.read_jsonrpc_message().await?; let os_info = os_info::get(); let user_agent = format!( "codex_cli_rs/0.0.0 ({} {}; {}) {} (elicitation test; 0.0.0)", os_info.os_type(), os_info.version(), os_info.architecture().unwrap_or("unknown"), codex_core::terminal::user_agent() ); assert_eq!( JSONRPCMessage::Response(JSONRPCResponse { jsonrpc: JSONRPC_VERSION.into(), id: RequestId::Integer(request_id), result: json!({ "capabilities": { "tools": { "listChanged": true }, }, "serverInfo": { "name": "codex-mcp-server", "title": "Codex", "version": "0.0.0", "user_agent": user_agent }, "protocolVersion": mcp_types::MCP_SCHEMA_VERSION }) }), initialized ); // Send notifications/initialized to ack the response. self.send_jsonrpc_message(JSONRPCMessage::Notification(JSONRPCNotification { jsonrpc: JSONRPC_VERSION.into(), method: mcp_types::InitializedNotification::METHOD.into(), params: None, })) .await?; Ok(()) } /// Returns the id used to make the request so it can be used when /// correlating notifications. pub async fn send_codex_tool_call( &mut self, params: CodexToolCallParam, ) -> anyhow::Result<i64> { let codex_tool_call_params = CallToolRequestParams { name: "codex".to_string(), arguments: Some(serde_json::to_value(params)?), }; self.send_request( mcp_types::CallToolRequest::METHOD, Some(serde_json::to_value(codex_tool_call_params)?), ) .await } async fn send_request( &mut self, method: &str, params: Option<serde_json::Value>, ) -> anyhow::Result<i64> { let request_id = self.next_request_id.fetch_add(1, Ordering::Relaxed); let message = JSONRPCMessage::Request(JSONRPCRequest { jsonrpc: JSONRPC_VERSION.into(), id: RequestId::Integer(request_id), method: method.to_string(), params, }); self.send_jsonrpc_message(message).await?; Ok(request_id) } pub async fn send_response( &mut self, id: RequestId, result: serde_json::Value, ) -> anyhow::Result<()> { self.send_jsonrpc_message(JSONRPCMessage::Response(JSONRPCResponse { jsonrpc: JSONRPC_VERSION.into(), id, result, })) .await } async fn send_jsonrpc_message(&mut self, message: JSONRPCMessage) -> anyhow::Result<()> { eprintln!("writing message to stdin: {message:?}"); let payload = serde_json::to_string(&message)?; self.stdin.write_all(payload.as_bytes()).await?; self.stdin.write_all(b"\n").await?; self.stdin.flush().await?; Ok(()) } async fn read_jsonrpc_message(&mut self) -> anyhow::Result<JSONRPCMessage> { let mut line = String::new(); self.stdout.read_line(&mut line).await?; let message = serde_json::from_str::<JSONRPCMessage>(&line)?; eprintln!("read message from stdout: {message:?}"); Ok(message) } pub async fn read_stream_until_request_message(&mut self) -> anyhow::Result<JSONRPCRequest> { eprintln!("in read_stream_until_request_message()"); loop { let message = self.read_jsonrpc_message().await?; match message { JSONRPCMessage::Notification(_) => { eprintln!("notification: {message:?}"); } JSONRPCMessage::Request(jsonrpc_request) => { return Ok(jsonrpc_request); } JSONRPCMessage::Error(_) => { anyhow::bail!("unexpected JSONRPCMessage::Error: {message:?}"); } JSONRPCMessage::Response(_) => { anyhow::bail!("unexpected JSONRPCMessage::Response: {message:?}"); } } } } pub async fn read_stream_until_response_message( &mut self, request_id: RequestId, ) -> anyhow::Result<JSONRPCResponse> { eprintln!("in read_stream_until_response_message({request_id:?})"); loop { let message = self.read_jsonrpc_message().await?; match message { JSONRPCMessage::Notification(_) => { eprintln!("notification: {message:?}"); } JSONRPCMessage::Request(_) => { anyhow::bail!("unexpected JSONRPCMessage::Request: {message:?}"); } JSONRPCMessage::Error(_) => { anyhow::bail!("unexpected JSONRPCMessage::Error: {message:?}"); } JSONRPCMessage::Response(jsonrpc_response) => { if jsonrpc_response.id == request_id { return Ok(jsonrpc_response); } } } } } /// Reads notifications until a legacy TaskComplete event is observed: /// Method "codex/event" with params.msg.type == "task_complete". pub async fn read_stream_until_legacy_task_complete_notification( &mut self, ) -> anyhow::Result<JSONRPCNotification> { eprintln!("in read_stream_until_legacy_task_complete_notification()"); loop { let message = self.read_jsonrpc_message().await?; match message { JSONRPCMessage::Notification(notification) => { let is_match = if notification.method == "codex/event" { if let Some(params) = &notification.params { params .get("msg") .and_then(|m| m.get("type")) .and_then(|t| t.as_str()) == Some("task_complete") } else { false } } else { false }; if is_match { return Ok(notification); } else { eprintln!("ignoring notification: {notification:?}"); } } JSONRPCMessage::Request(_) => { anyhow::bail!("unexpected JSONRPCMessage::Request: {message:?}"); } JSONRPCMessage::Error(_) => { anyhow::bail!("unexpected JSONRPCMessage::Error: {message:?}"); } JSONRPCMessage::Response(_) => { anyhow::bail!("unexpected JSONRPCMessage::Response: {message:?}"); } } } } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/mcp-server/tests/common/mock_model_server.rs
codex-rs/mcp-server/tests/common/mock_model_server.rs
use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use wiremock::Mock; use wiremock::MockServer; use wiremock::Respond; use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; /// Create a mock server that will provide the responses, in order, for /// requests to the `/v1/chat/completions` endpoint. pub async fn create_mock_chat_completions_server(responses: Vec<String>) -> MockServer { let server = MockServer::start().await; let num_calls = responses.len(); let seq_responder = SeqResponder { num_calls: AtomicUsize::new(0), responses, }; Mock::given(method("POST")) .and(path("/v1/chat/completions")) .respond_with(seq_responder) .expect(num_calls as u64) .mount(&server) .await; server } struct SeqResponder { num_calls: AtomicUsize, responses: Vec<String>, } impl Respond for SeqResponder { fn respond(&self, _: &wiremock::Request) -> ResponseTemplate { let call_num = self.num_calls.fetch_add(1, Ordering::SeqCst); match self.responses.get(call_num) { Some(response) => ResponseTemplate::new(200) .insert_header("content-type", "text/event-stream") .set_body_raw(response.clone(), "text/event-stream"), None => panic!("no response for {call_num}"), } } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/process-hardening/src/lib.rs
codex-rs/process-hardening/src/lib.rs
#[cfg(unix)] use std::ffi::OsString; #[cfg(unix)] use std::os::unix::ffi::OsStrExt; /// This is designed to be called pre-main() (using `#[ctor::ctor]`) to perform /// various process hardening steps, such as /// - disabling core dumps /// - disabling ptrace attach on Linux and macOS. /// - removing dangerous environment variables such as LD_PRELOAD and DYLD_* pub fn pre_main_hardening() { #[cfg(any(target_os = "linux", target_os = "android"))] pre_main_hardening_linux(); #[cfg(target_os = "macos")] pre_main_hardening_macos(); // On FreeBSD and OpenBSD, apply similar hardening to Linux/macOS: #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] pre_main_hardening_bsd(); #[cfg(windows)] pre_main_hardening_windows(); } #[cfg(any(target_os = "linux", target_os = "android"))] const PRCTL_FAILED_EXIT_CODE: i32 = 5; #[cfg(target_os = "macos")] const PTRACE_DENY_ATTACH_FAILED_EXIT_CODE: i32 = 6; #[cfg(any( target_os = "linux", target_os = "android", target_os = "macos", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ))] const SET_RLIMIT_CORE_FAILED_EXIT_CODE: i32 = 7; #[cfg(any(target_os = "linux", target_os = "android"))] pub(crate) fn pre_main_hardening_linux() { // Disable ptrace attach / mark process non-dumpable. let ret_code = unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) }; if ret_code != 0 { eprintln!( "ERROR: prctl(PR_SET_DUMPABLE, 0) failed: {}", std::io::Error::last_os_error() ); std::process::exit(PRCTL_FAILED_EXIT_CODE); } // For "defense in depth," set the core file size limit to 0. set_core_file_size_limit_to_zero(); // Official Codex releases are MUSL-linked, which means that variables such // as LD_PRELOAD are ignored anyway, but just to be sure, clear them here. let ld_keys = env_keys_with_prefix(std::env::vars_os(), b"LD_"); for key in ld_keys { unsafe { std::env::remove_var(key); } } } #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] pub(crate) fn pre_main_hardening_bsd() { // FreeBSD/OpenBSD: set RLIMIT_CORE to 0 and clear LD_* env vars set_core_file_size_limit_to_zero(); let ld_keys = env_keys_with_prefix(std::env::vars_os(), b"LD_"); for key in ld_keys { unsafe { std::env::remove_var(key); } } } #[cfg(target_os = "macos")] pub(crate) fn pre_main_hardening_macos() { // Prevent debuggers from attaching to this process. let ret_code = unsafe { libc::ptrace(libc::PT_DENY_ATTACH, 0, std::ptr::null_mut(), 0) }; if ret_code == -1 { eprintln!( "ERROR: ptrace(PT_DENY_ATTACH) failed: {}", std::io::Error::last_os_error() ); std::process::exit(PTRACE_DENY_ATTACH_FAILED_EXIT_CODE); } // Set the core file size limit to 0 to prevent core dumps. set_core_file_size_limit_to_zero(); // Remove all DYLD_ environment variables, which can be used to subvert // library loading. let dyld_keys = env_keys_with_prefix(std::env::vars_os(), b"DYLD_"); for key in dyld_keys { unsafe { std::env::remove_var(key); } } } #[cfg(unix)] fn set_core_file_size_limit_to_zero() { let rlim = libc::rlimit { rlim_cur: 0, rlim_max: 0, }; let ret_code = unsafe { libc::setrlimit(libc::RLIMIT_CORE, &rlim) }; if ret_code != 0 { eprintln!( "ERROR: setrlimit(RLIMIT_CORE) failed: {}", std::io::Error::last_os_error() ); std::process::exit(SET_RLIMIT_CORE_FAILED_EXIT_CODE); } } #[cfg(windows)] pub(crate) fn pre_main_hardening_windows() { // TODO(mbolin): Perform the appropriate configuration for Windows. } #[cfg(unix)] fn env_keys_with_prefix<I>(vars: I, prefix: &[u8]) -> Vec<OsString> where I: IntoIterator<Item = (OsString, OsString)>, { vars.into_iter() .filter_map(|(key, _)| { key.as_os_str() .as_bytes() .starts_with(prefix) .then_some(key) }) .collect() } #[cfg(all(test, unix))] mod tests { use super::*; use pretty_assertions::assert_eq; use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; use std::os::unix::ffi::OsStringExt; #[test] fn env_keys_with_prefix_handles_non_utf8_entries() { // RÖDBURK let non_utf8_key1 = OsStr::from_bytes(b"R\xD6DBURK").to_os_string(); assert!(non_utf8_key1.clone().into_string().is_err()); let non_utf8_key2 = OsString::from_vec(vec![b'L', b'D', b'_', 0xF0]); assert!(non_utf8_key2.clone().into_string().is_err()); let non_utf8_value = OsString::from_vec(vec![0xF0, 0x9F, 0x92, 0xA9]); let keys = env_keys_with_prefix( vec![ (non_utf8_key1, non_utf8_value.clone()), (non_utf8_key2.clone(), non_utf8_value), ], b"LD_", ); assert_eq!( keys, vec![non_utf8_key2], "non-UTF-8 env entries with LD_ prefix should be retained" ); } #[test] fn env_keys_with_prefix_filters_only_matching_keys() { let ld_test_var = OsStr::from_bytes(b"LD_TEST"); let vars = vec![ (OsString::from("PATH"), OsString::from("/usr/bin")), (ld_test_var.to_os_string(), OsString::from("1")), (OsString::from("DYLD_FOO"), OsString::from("bar")), ]; let keys = env_keys_with_prefix(vars, b"LD_"); assert_eq!(keys.len(), 1); assert_eq!(keys[0].as_os_str(), ld_test_var); } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/async-utils/src/lib.rs
codex-rs/async-utils/src/lib.rs
use async_trait::async_trait; use std::future::Future; use tokio_util::sync::CancellationToken; #[derive(Debug, PartialEq, Eq)] pub enum CancelErr { Cancelled, } #[async_trait] pub trait OrCancelExt: Sized { type Output; async fn or_cancel(self, token: &CancellationToken) -> Result<Self::Output, CancelErr>; } #[async_trait] impl<F> OrCancelExt for F where F: Future + Send, F::Output: Send, { type Output = F::Output; async fn or_cancel(self, token: &CancellationToken) -> Result<Self::Output, CancelErr> { tokio::select! { _ = token.cancelled() => Err(CancelErr::Cancelled), res = self => Ok(res), } } } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; use std::time::Duration; use tokio::task; use tokio::time::sleep; #[tokio::test] async fn returns_ok_when_future_completes_first() { let token = CancellationToken::new(); let value = async { 42 }; let result = value.or_cancel(&token).await; assert_eq!(Ok(42), result); } #[tokio::test] async fn returns_err_when_token_cancelled_first() { let token = CancellationToken::new(); let token_clone = token.clone(); let cancel_handle = task::spawn(async move { sleep(Duration::from_millis(10)).await; token_clone.cancel(); }); let result = async { sleep(Duration::from_millis(100)).await; 7 } .or_cancel(&token) .await; cancel_handle.await.expect("cancel task panicked"); assert_eq!(Err(CancelErr::Cancelled), result); } #[tokio::test] async fn returns_err_when_token_already_cancelled() { let token = CancellationToken::new(); token.cancel(); let result = async { sleep(Duration::from_millis(50)).await; 5 } .or_cancel(&token) .await; assert_eq!(Err(CancelErr::Cancelled), result); } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/apply-patch/src/invocation.rs
codex-rs/apply-patch/src/invocation.rs
use std::collections::HashMap; use std::path::Path; use std::sync::LazyLock; use tree_sitter::Parser; use tree_sitter::Query; use tree_sitter::QueryCursor; use tree_sitter::StreamingIterator; use tree_sitter_bash::LANGUAGE as BASH; use crate::ApplyPatchAction; use crate::ApplyPatchArgs; use crate::ApplyPatchError; use crate::ApplyPatchFileChange; use crate::ApplyPatchFileUpdate; use crate::IoError; use crate::MaybeApplyPatchVerified; use crate::parser::Hunk; use crate::parser::ParseError; use crate::parser::parse_patch; use crate::unified_diff_from_chunks; use std::str::Utf8Error; use tree_sitter::LanguageError; const APPLY_PATCH_COMMANDS: [&str; 2] = ["apply_patch", "applypatch"]; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ApplyPatchShell { Unix, PowerShell, Cmd, } #[derive(Debug, PartialEq)] pub enum MaybeApplyPatch { Body(ApplyPatchArgs), ShellParseError(ExtractHeredocError), PatchParseError(ParseError), NotApplyPatch, } #[derive(Debug, PartialEq)] pub enum ExtractHeredocError { CommandDidNotStartWithApplyPatch, FailedToLoadBashGrammar(LanguageError), HeredocNotUtf8(Utf8Error), FailedToParsePatchIntoAst, FailedToFindHeredocBody, } fn classify_shell_name(shell: &str) -> Option<String> { std::path::Path::new(shell) .file_stem() .and_then(|name| name.to_str()) .map(str::to_ascii_lowercase) } fn classify_shell(shell: &str, flag: &str) -> Option<ApplyPatchShell> { classify_shell_name(shell).and_then(|name| match name.as_str() { "bash" | "zsh" | "sh" if matches!(flag, "-lc" | "-c") => Some(ApplyPatchShell::Unix), "pwsh" | "powershell" if flag.eq_ignore_ascii_case("-command") => { Some(ApplyPatchShell::PowerShell) } "cmd" if flag.eq_ignore_ascii_case("/c") => Some(ApplyPatchShell::Cmd), _ => None, }) } fn can_skip_flag(shell: &str, flag: &str) -> bool { classify_shell_name(shell).is_some_and(|name| { matches!(name.as_str(), "pwsh" | "powershell") && flag.eq_ignore_ascii_case("-noprofile") }) } fn parse_shell_script(argv: &[String]) -> Option<(ApplyPatchShell, &str)> { match argv { [shell, flag, script] => classify_shell(shell, flag).map(|shell_type| { let script = script.as_str(); (shell_type, script) }), [shell, skip_flag, flag, script] if can_skip_flag(shell, skip_flag) => { classify_shell(shell, flag).map(|shell_type| { let script = script.as_str(); (shell_type, script) }) } _ => None, } } fn extract_apply_patch_from_shell( shell: ApplyPatchShell, script: &str, ) -> std::result::Result<(String, Option<String>), ExtractHeredocError> { match shell { ApplyPatchShell::Unix | ApplyPatchShell::PowerShell | ApplyPatchShell::Cmd => { extract_apply_patch_from_bash(script) } } } // TODO: make private once we remove tests in lib.rs pub fn maybe_parse_apply_patch(argv: &[String]) -> MaybeApplyPatch { match argv { // Direct invocation: apply_patch <patch> [cmd, body] if APPLY_PATCH_COMMANDS.contains(&cmd.as_str()) => match parse_patch(body) { Ok(source) => MaybeApplyPatch::Body(source), Err(e) => MaybeApplyPatch::PatchParseError(e), }, // Shell heredoc form: (optional `cd <path> &&`) apply_patch <<'EOF' ... _ => match parse_shell_script(argv) { Some((shell, script)) => match extract_apply_patch_from_shell(shell, script) { Ok((body, workdir)) => match parse_patch(&body) { Ok(mut source) => { source.workdir = workdir; MaybeApplyPatch::Body(source) } Err(e) => MaybeApplyPatch::PatchParseError(e), }, Err(ExtractHeredocError::CommandDidNotStartWithApplyPatch) => { MaybeApplyPatch::NotApplyPatch } Err(e) => MaybeApplyPatch::ShellParseError(e), }, None => MaybeApplyPatch::NotApplyPatch, }, } } /// cwd must be an absolute path so that we can resolve relative paths in the /// patch. pub fn maybe_parse_apply_patch_verified(argv: &[String], cwd: &Path) -> MaybeApplyPatchVerified { // Detect a raw patch body passed directly as the command or as the body of a shell // script. In these cases, report an explicit error rather than applying the patch. if let [body] = argv && parse_patch(body).is_ok() { return MaybeApplyPatchVerified::CorrectnessError(ApplyPatchError::ImplicitInvocation); } if let Some((_, script)) = parse_shell_script(argv) && parse_patch(script).is_ok() { return MaybeApplyPatchVerified::CorrectnessError(ApplyPatchError::ImplicitInvocation); } match maybe_parse_apply_patch(argv) { MaybeApplyPatch::Body(ApplyPatchArgs { patch, hunks, workdir, }) => { let effective_cwd = workdir .as_ref() .map(|dir| { let path = Path::new(dir); if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) } }) .unwrap_or_else(|| cwd.to_path_buf()); let mut changes = HashMap::new(); for hunk in hunks { let path = hunk.resolve_path(&effective_cwd); match hunk { Hunk::AddFile { contents, .. } => { changes.insert(path, ApplyPatchFileChange::Add { content: contents }); } Hunk::DeleteFile { .. } => { let content = match std::fs::read_to_string(&path) { Ok(content) => content, Err(e) => { return MaybeApplyPatchVerified::CorrectnessError( ApplyPatchError::IoError(IoError { context: format!("Failed to read {}", path.display()), source: e, }), ); } }; changes.insert(path, ApplyPatchFileChange::Delete { content }); } Hunk::UpdateFile { move_path, chunks, .. } => { let ApplyPatchFileUpdate { unified_diff, content: contents, } = match unified_diff_from_chunks(&path, &chunks) { Ok(diff) => diff, Err(e) => { return MaybeApplyPatchVerified::CorrectnessError(e); } }; changes.insert( path, ApplyPatchFileChange::Update { unified_diff, move_path: move_path.map(|p| effective_cwd.join(p)), new_content: contents, }, ); } } } MaybeApplyPatchVerified::Body(ApplyPatchAction { changes, patch, cwd: effective_cwd, }) } MaybeApplyPatch::ShellParseError(e) => MaybeApplyPatchVerified::ShellParseError(e), MaybeApplyPatch::PatchParseError(e) => MaybeApplyPatchVerified::CorrectnessError(e.into()), MaybeApplyPatch::NotApplyPatch => MaybeApplyPatchVerified::NotApplyPatch, } } /// Extract the heredoc body (and optional `cd` workdir) from a `bash -lc` script /// that invokes the apply_patch tool using a heredoc. /// /// Supported top‑level forms (must be the only top‑level statement): /// - `apply_patch <<'EOF'\n...\nEOF` /// - `cd <path> && apply_patch <<'EOF'\n...\nEOF` /// /// Notes about matching: /// - Parsed with Tree‑sitter Bash and a strict query that uses anchors so the /// heredoc‑redirected statement is the only top‑level statement. /// - The connector between `cd` and `apply_patch` must be `&&` (not `|` or `||`). /// - Exactly one positional `word` argument is allowed for `cd` (no flags, no quoted /// strings, no second argument). /// - The apply command is validated in‑query via `#any-of?` to allow `apply_patch` /// or `applypatch`. /// - Preceding or trailing commands (e.g., `echo ...;` or `... && echo done`) do not match. /// /// Returns `(heredoc_body, Some(path))` when the `cd` variant matches, or /// `(heredoc_body, None)` for the direct form. Errors are returned if the script /// cannot be parsed or does not match the allowed patterns. fn extract_apply_patch_from_bash( src: &str, ) -> std::result::Result<(String, Option<String>), ExtractHeredocError> { // This function uses a Tree-sitter query to recognize one of two // whole-script forms, each expressed as a single top-level statement: // // 1. apply_patch <<'EOF'\n...\nEOF // 2. cd <path> && apply_patch <<'EOF'\n...\nEOF // // Key ideas when reading the query: // - dots (`.`) between named nodes enforces adjacency among named children and // anchor to the start/end of the expression. // - we match a single redirected_statement directly under program with leading // and trailing anchors (`.`). This ensures it is the only top-level statement // (so prefixes like `echo ...;` or suffixes like `... && echo done` do not match). // // Overall, we want to be conservative and only match the intended forms, as other // forms are likely to be model errors, or incorrectly interpreted by later code. // // If you're editing this query, it's helpful to start by creating a debugging binary // which will let you see the AST of an arbitrary bash script passed in, and optionally // also run an arbitrary query against the AST. This is useful for understanding // how tree-sitter parses the script and whether the query syntax is correct. Be sure // to test both positive and negative cases. static APPLY_PATCH_QUERY: LazyLock<Query> = LazyLock::new(|| { let language = BASH.into(); #[expect(clippy::expect_used)] Query::new( &language, r#" ( program . (redirected_statement body: (command name: (command_name (word) @apply_name) .) (#any-of? @apply_name "apply_patch" "applypatch") redirect: (heredoc_redirect . (heredoc_start) . (heredoc_body) @heredoc . (heredoc_end) .)) .) ( program . (redirected_statement body: (list . (command name: (command_name (word) @cd_name) . argument: [ (word) @cd_path (string (string_content) @cd_path) (raw_string) @cd_raw_string ] .) "&&" . (command name: (command_name (word) @apply_name)) .) (#eq? @cd_name "cd") (#any-of? @apply_name "apply_patch" "applypatch") redirect: (heredoc_redirect . (heredoc_start) . (heredoc_body) @heredoc . (heredoc_end) .)) .) "#, ) .expect("valid bash query") }); let lang = BASH.into(); let mut parser = Parser::new(); parser .set_language(&lang) .map_err(ExtractHeredocError::FailedToLoadBashGrammar)?; let tree = parser .parse(src, None) .ok_or(ExtractHeredocError::FailedToParsePatchIntoAst)?; let bytes = src.as_bytes(); let root = tree.root_node(); let mut cursor = QueryCursor::new(); let mut matches = cursor.matches(&APPLY_PATCH_QUERY, root, bytes); while let Some(m) = matches.next() { let mut heredoc_text: Option<String> = None; let mut cd_path: Option<String> = None; for capture in m.captures.iter() { let name = APPLY_PATCH_QUERY.capture_names()[capture.index as usize]; match name { "heredoc" => { let text = capture .node .utf8_text(bytes) .map_err(ExtractHeredocError::HeredocNotUtf8)? .trim_end_matches('\n') .to_string(); heredoc_text = Some(text); } "cd_path" => { let text = capture .node .utf8_text(bytes) .map_err(ExtractHeredocError::HeredocNotUtf8)? .to_string(); cd_path = Some(text); } "cd_raw_string" => { let raw = capture .node .utf8_text(bytes) .map_err(ExtractHeredocError::HeredocNotUtf8)?; let trimmed = raw .strip_prefix('\'') .and_then(|s| s.strip_suffix('\'')) .unwrap_or(raw); cd_path = Some(trimmed.to_string()); } _ => {} } } if let Some(heredoc) = heredoc_text { return Ok((heredoc, cd_path)); } } Err(ExtractHeredocError::CommandDidNotStartWithApplyPatch) } #[cfg(test)] mod tests { use super::*; use assert_matches::assert_matches; use pretty_assertions::assert_eq; use std::fs; use std::path::PathBuf; use std::string::ToString; use tempfile::tempdir; /// Helper to construct a patch with the given body. fn wrap_patch(body: &str) -> String { format!("*** Begin Patch\n{body}\n*** End Patch") } fn strs_to_strings(strs: &[&str]) -> Vec<String> { strs.iter().map(ToString::to_string).collect() } // Test helpers to reduce repetition when building bash -lc heredoc scripts fn args_bash(script: &str) -> Vec<String> { strs_to_strings(&["bash", "-lc", script]) } fn args_powershell(script: &str) -> Vec<String> { strs_to_strings(&["powershell.exe", "-Command", script]) } fn args_powershell_no_profile(script: &str) -> Vec<String> { strs_to_strings(&["powershell.exe", "-NoProfile", "-Command", script]) } fn args_pwsh(script: &str) -> Vec<String> { strs_to_strings(&["pwsh", "-NoProfile", "-Command", script]) } fn args_cmd(script: &str) -> Vec<String> { strs_to_strings(&["cmd.exe", "/c", script]) } fn heredoc_script(prefix: &str) -> String { format!( "{prefix}apply_patch <<'PATCH'\n*** Begin Patch\n*** Add File: foo\n+hi\n*** End Patch\nPATCH" ) } fn heredoc_script_ps(prefix: &str, suffix: &str) -> String { format!( "{prefix}apply_patch <<'PATCH'\n*** Begin Patch\n*** Add File: foo\n+hi\n*** End Patch\nPATCH{suffix}" ) } fn expected_single_add() -> Vec<Hunk> { vec![Hunk::AddFile { path: PathBuf::from("foo"), contents: "hi\n".to_string(), }] } fn assert_match_args(args: Vec<String>, expected_workdir: Option<&str>) { match maybe_parse_apply_patch(&args) { MaybeApplyPatch::Body(ApplyPatchArgs { hunks, workdir, .. }) => { assert_eq!(workdir.as_deref(), expected_workdir); assert_eq!(hunks, expected_single_add()); } result => panic!("expected MaybeApplyPatch::Body got {result:?}"), } } fn assert_match(script: &str, expected_workdir: Option<&str>) { let args = args_bash(script); assert_match_args(args, expected_workdir); } fn assert_not_match(script: &str) { let args = args_bash(script); assert_matches!( maybe_parse_apply_patch(&args), MaybeApplyPatch::NotApplyPatch ); } #[test] fn test_implicit_patch_single_arg_is_error() { let patch = "*** Begin Patch\n*** Add File: foo\n+hi\n*** End Patch".to_string(); let args = vec![patch]; let dir = tempdir().unwrap(); assert_matches!( maybe_parse_apply_patch_verified(&args, dir.path()), MaybeApplyPatchVerified::CorrectnessError(ApplyPatchError::ImplicitInvocation) ); } #[test] fn test_implicit_patch_bash_script_is_error() { let script = "*** Begin Patch\n*** Add File: foo\n+hi\n*** End Patch"; let args = args_bash(script); let dir = tempdir().unwrap(); assert_matches!( maybe_parse_apply_patch_verified(&args, dir.path()), MaybeApplyPatchVerified::CorrectnessError(ApplyPatchError::ImplicitInvocation) ); } #[test] fn test_literal() { let args = strs_to_strings(&[ "apply_patch", r#"*** Begin Patch *** Add File: foo +hi *** End Patch "#, ]); match maybe_parse_apply_patch(&args) { MaybeApplyPatch::Body(ApplyPatchArgs { hunks, .. }) => { assert_eq!( hunks, vec![Hunk::AddFile { path: PathBuf::from("foo"), contents: "hi\n".to_string() }] ); } result => panic!("expected MaybeApplyPatch::Body got {result:?}"), } } #[test] fn test_literal_applypatch() { let args = strs_to_strings(&[ "applypatch", r#"*** Begin Patch *** Add File: foo +hi *** End Patch "#, ]); match maybe_parse_apply_patch(&args) { MaybeApplyPatch::Body(ApplyPatchArgs { hunks, .. }) => { assert_eq!( hunks, vec![Hunk::AddFile { path: PathBuf::from("foo"), contents: "hi\n".to_string() }] ); } result => panic!("expected MaybeApplyPatch::Body got {result:?}"), } } #[test] fn test_heredoc() { assert_match(&heredoc_script(""), None); } #[test] fn test_heredoc_non_login_shell() { let script = heredoc_script(""); let args = strs_to_strings(&["bash", "-c", &script]); assert_match_args(args, None); } #[test] fn test_heredoc_applypatch() { let args = strs_to_strings(&[ "bash", "-lc", r#"applypatch <<'PATCH' *** Begin Patch *** Add File: foo +hi *** End Patch PATCH"#, ]); match maybe_parse_apply_patch(&args) { MaybeApplyPatch::Body(ApplyPatchArgs { hunks, workdir, .. }) => { assert_eq!(workdir, None); assert_eq!( hunks, vec![Hunk::AddFile { path: PathBuf::from("foo"), contents: "hi\n".to_string() }] ); } result => panic!("expected MaybeApplyPatch::Body got {result:?}"), } } #[test] fn test_powershell_heredoc() { let script = heredoc_script(""); assert_match_args(args_powershell(&script), None); } #[test] fn test_powershell_heredoc_no_profile() { let script = heredoc_script(""); assert_match_args(args_powershell_no_profile(&script), None); } #[test] fn test_pwsh_heredoc() { let script = heredoc_script(""); assert_match_args(args_pwsh(&script), None); } #[test] fn test_cmd_heredoc_with_cd() { let script = heredoc_script("cd foo && "); assert_match_args(args_cmd(&script), Some("foo")); } #[test] fn test_heredoc_with_leading_cd() { assert_match(&heredoc_script("cd foo && "), Some("foo")); } #[test] fn test_cd_with_semicolon_is_ignored() { assert_not_match(&heredoc_script("cd foo; ")); } #[test] fn test_cd_or_apply_patch_is_ignored() { assert_not_match(&heredoc_script("cd bar || ")); } #[test] fn test_cd_pipe_apply_patch_is_ignored() { assert_not_match(&heredoc_script("cd bar | ")); } #[test] fn test_cd_single_quoted_path_with_spaces() { assert_match(&heredoc_script("cd 'foo bar' && "), Some("foo bar")); } #[test] fn test_cd_double_quoted_path_with_spaces() { assert_match(&heredoc_script("cd \"foo bar\" && "), Some("foo bar")); } #[test] fn test_echo_and_apply_patch_is_ignored() { assert_not_match(&heredoc_script("echo foo && ")); } #[test] fn test_apply_patch_with_arg_is_ignored() { let script = "apply_patch foo <<'PATCH'\n*** Begin Patch\n*** Add File: foo\n+hi\n*** End Patch\nPATCH"; assert_not_match(script); } #[test] fn test_double_cd_then_apply_patch_is_ignored() { assert_not_match(&heredoc_script("cd foo && cd bar && ")); } #[test] fn test_cd_two_args_is_ignored() { assert_not_match(&heredoc_script("cd foo bar && ")); } #[test] fn test_cd_then_apply_patch_then_extra_is_ignored() { let script = heredoc_script_ps("cd bar && ", " && echo done"); assert_not_match(&script); } #[test] fn test_echo_then_cd_and_apply_patch_is_ignored() { // Ensure preceding commands before the `cd && apply_patch <<...` sequence do not match. assert_not_match(&heredoc_script("echo foo; cd bar && ")); } #[test] fn test_unified_diff_last_line_replacement() { // Replace the very last line of the file. let dir = tempdir().unwrap(); let path = dir.path().join("last.txt"); fs::write(&path, "foo\nbar\nbaz\n").unwrap(); let patch = wrap_patch(&format!( r#"*** Update File: {} @@ foo bar -baz +BAZ "#, path.display() )); let patch = parse_patch(&patch).unwrap(); let chunks = match patch.hunks.as_slice() { [Hunk::UpdateFile { chunks, .. }] => chunks, _ => panic!("Expected a single UpdateFile hunk"), }; let diff = unified_diff_from_chunks(&path, chunks).unwrap(); let expected_diff = r#"@@ -2,2 +2,2 @@ bar -baz +BAZ "#; let expected = ApplyPatchFileUpdate { unified_diff: expected_diff.to_string(), content: "foo\nbar\nBAZ\n".to_string(), }; assert_eq!(expected, diff); } #[test] fn test_unified_diff_insert_at_eof() { // Insert a new line at end‑of‑file. let dir = tempdir().unwrap(); let path = dir.path().join("insert.txt"); fs::write(&path, "foo\nbar\nbaz\n").unwrap(); let patch = wrap_patch(&format!( r#"*** Update File: {} @@ +quux *** End of File "#, path.display() )); let patch = parse_patch(&patch).unwrap(); let chunks = match patch.hunks.as_slice() { [Hunk::UpdateFile { chunks, .. }] => chunks, _ => panic!("Expected a single UpdateFile hunk"), }; let diff = unified_diff_from_chunks(&path, chunks).unwrap(); let expected_diff = r#"@@ -3 +3,2 @@ baz +quux "#; let expected = ApplyPatchFileUpdate { unified_diff: expected_diff.to_string(), content: "foo\nbar\nbaz\nquux\n".to_string(), }; assert_eq!(expected, diff); } #[test] fn test_apply_patch_should_resolve_absolute_paths_in_cwd() { let session_dir = tempdir().unwrap(); let relative_path = "source.txt"; // Note that we need this file to exist for the patch to be "verified" // and parsed correctly. let session_file_path = session_dir.path().join(relative_path); fs::write(&session_file_path, "session directory content\n").unwrap(); let argv = vec![ "apply_patch".to_string(), r#"*** Begin Patch *** Update File: source.txt @@ -session directory content +updated session directory content *** End Patch"# .to_string(), ]; let result = maybe_parse_apply_patch_verified(&argv, session_dir.path()); // Verify the patch contents - as otherwise we may have pulled contents // from the wrong file (as we're using relative paths) assert_eq!( result, MaybeApplyPatchVerified::Body(ApplyPatchAction { changes: HashMap::from([( session_dir.path().join(relative_path), ApplyPatchFileChange::Update { unified_diff: r#"@@ -1 +1 @@ -session directory content +updated session directory content "# .to_string(), move_path: None, new_content: "updated session directory content\n".to_string(), }, )]), patch: argv[1].clone(), cwd: session_dir.path().to_path_buf(), }) ); } #[test] fn test_apply_patch_resolves_move_path_with_effective_cwd() { let session_dir = tempdir().unwrap(); let worktree_rel = "alt"; let worktree_dir = session_dir.path().join(worktree_rel); fs::create_dir_all(&worktree_dir).unwrap(); let source_name = "old.txt"; let dest_name = "renamed.txt"; let source_path = worktree_dir.join(source_name); fs::write(&source_path, "before\n").unwrap(); let patch = wrap_patch(&format!( r#"*** Update File: {source_name} *** Move to: {dest_name} @@ -before +after"# )); let shell_script = format!("cd {worktree_rel} && apply_patch <<'PATCH'\n{patch}\nPATCH"); let argv = vec!["bash".into(), "-lc".into(), shell_script]; let result = maybe_parse_apply_patch_verified(&argv, session_dir.path()); let action = match result { MaybeApplyPatchVerified::Body(action) => action, other => panic!("expected verified body, got {other:?}"), }; assert_eq!(action.cwd, worktree_dir); let change = action .changes() .get(&worktree_dir.join(source_name)) .expect("source file change present"); match change { ApplyPatchFileChange::Update { move_path, .. } => { assert_eq!( move_path.as_deref(), Some(worktree_dir.join(dest_name).as_path()) ); } other => panic!("expected update change, got {other:?}"), } } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/apply-patch/src/standalone_executable.rs
codex-rs/apply-patch/src/standalone_executable.rs
use std::io::Read; use std::io::Write; pub fn main() -> ! { let exit_code = run_main(); std::process::exit(exit_code); } /// We would prefer to return `std::process::ExitCode`, but its `exit_process()` /// method is still a nightly API and we want main() to return !. pub fn run_main() -> i32 { // Expect either one argument (the full apply_patch payload) or read it from stdin. let mut args = std::env::args_os(); let _argv0 = args.next(); let patch_arg = match args.next() { Some(arg) => match arg.into_string() { Ok(s) => s, Err(_) => { eprintln!("Error: apply_patch requires a UTF-8 PATCH argument."); return 1; } }, None => { // No argument provided; attempt to read the patch from stdin. let mut buf = String::new(); match std::io::stdin().read_to_string(&mut buf) { Ok(_) => { if buf.is_empty() { eprintln!("Usage: apply_patch 'PATCH'\n echo 'PATCH' | apply-patch"); return 2; } buf } Err(err) => { eprintln!("Error: Failed to read PATCH from stdin.\n{err}"); return 1; } } } }; // Refuse extra args to avoid ambiguity. if args.next().is_some() { eprintln!("Error: apply_patch accepts exactly one argument."); return 2; } let mut stdout = std::io::stdout(); let mut stderr = std::io::stderr(); match crate::apply_patch(&patch_arg, &mut stdout, &mut stderr) { Ok(()) => { // Flush to ensure output ordering when used in pipelines. let _ = stdout.flush(); 0 } Err(_) => 1, } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/apply-patch/src/lib.rs
codex-rs/apply-patch/src/lib.rs
mod invocation; mod parser; mod seek_sequence; mod standalone_executable; use std::collections::HashMap; use std::path::Path; use std::path::PathBuf; use anyhow::Context; use anyhow::Result; pub use parser::Hunk; pub use parser::ParseError; use parser::ParseError::*; use parser::UpdateFileChunk; pub use parser::parse_patch; use similar::TextDiff; use thiserror::Error; pub use invocation::maybe_parse_apply_patch_verified; pub use standalone_executable::main; use crate::invocation::ExtractHeredocError; /// Detailed instructions for gpt-4.1 on how to use the `apply_patch` tool. pub const APPLY_PATCH_TOOL_INSTRUCTIONS: &str = include_str!("../apply_patch_tool_instructions.md"); #[derive(Debug, Error, PartialEq)] pub enum ApplyPatchError { #[error(transparent)] ParseError(#[from] ParseError), #[error(transparent)] IoError(#[from] IoError), /// Error that occurs while computing replacements when applying patch chunks #[error("{0}")] ComputeReplacements(String), /// A raw patch body was provided without an explicit `apply_patch` invocation. #[error( "patch detected without explicit call to apply_patch. Rerun as [\"apply_patch\", \"<patch>\"]" )] ImplicitInvocation, } impl From<std::io::Error> for ApplyPatchError { fn from(err: std::io::Error) -> Self { ApplyPatchError::IoError(IoError { context: "I/O error".to_string(), source: err, }) } } impl From<&std::io::Error> for ApplyPatchError { fn from(err: &std::io::Error) -> Self { ApplyPatchError::IoError(IoError { context: "I/O error".to_string(), source: std::io::Error::new(err.kind(), err.to_string()), }) } } #[derive(Debug, Error)] #[error("{context}: {source}")] pub struct IoError { context: String, #[source] source: std::io::Error, } impl PartialEq for IoError { fn eq(&self, other: &Self) -> bool { self.context == other.context && self.source.to_string() == other.source.to_string() } } /// Both the raw PATCH argument to `apply_patch` as well as the PATCH argument /// parsed into hunks. #[derive(Debug, PartialEq)] pub struct ApplyPatchArgs { pub patch: String, pub hunks: Vec<Hunk>, pub workdir: Option<String>, } #[derive(Debug, PartialEq)] pub enum ApplyPatchFileChange { Add { content: String, }, Delete { content: String, }, Update { unified_diff: String, move_path: Option<PathBuf>, /// new_content that will result after the unified_diff is applied. new_content: String, }, } #[derive(Debug, PartialEq)] pub enum MaybeApplyPatchVerified { /// `argv` corresponded to an `apply_patch` invocation, and these are the /// resulting proposed file changes. Body(ApplyPatchAction), /// `argv` could not be parsed to determine whether it corresponds to an /// `apply_patch` invocation. ShellParseError(ExtractHeredocError), /// `argv` corresponded to an `apply_patch` invocation, but it could not /// be fulfilled due to the specified error. CorrectnessError(ApplyPatchError), /// `argv` decidedly did not correspond to an `apply_patch` invocation. NotApplyPatch, } /// ApplyPatchAction is the result of parsing an `apply_patch` command. By /// construction, all paths should be absolute paths. #[derive(Debug, PartialEq)] pub struct ApplyPatchAction { changes: HashMap<PathBuf, ApplyPatchFileChange>, /// The raw patch argument that can be used with `apply_patch` as an exec /// call. i.e., if the original arg was parsed in "lenient" mode with a /// heredoc, this should be the value without the heredoc wrapper. pub patch: String, /// The working directory that was used to resolve relative paths in the patch. pub cwd: PathBuf, } impl ApplyPatchAction { pub fn is_empty(&self) -> bool { self.changes.is_empty() } /// Returns the changes that would be made by applying the patch. pub fn changes(&self) -> &HashMap<PathBuf, ApplyPatchFileChange> { &self.changes } /// Should be used exclusively for testing. (Not worth the overhead of /// creating a feature flag for this.) pub fn new_add_for_test(path: &Path, content: String) -> Self { if !path.is_absolute() { panic!("path must be absolute"); } #[expect(clippy::expect_used)] let filename = path .file_name() .expect("path should not be empty") .to_string_lossy(); let patch = format!( r#"*** Begin Patch *** Update File: {filename} @@ + {content} *** End Patch"#, ); let changes = HashMap::from([(path.to_path_buf(), ApplyPatchFileChange::Add { content })]); #[expect(clippy::expect_used)] Self { changes, cwd: path .parent() .expect("path should have parent") .to_path_buf(), patch, } } } /// Applies the patch and prints the result to stdout/stderr. pub fn apply_patch( patch: &str, stdout: &mut impl std::io::Write, stderr: &mut impl std::io::Write, ) -> Result<(), ApplyPatchError> { let hunks = match parse_patch(patch) { Ok(source) => source.hunks, Err(e) => { match &e { InvalidPatchError(message) => { writeln!(stderr, "Invalid patch: {message}").map_err(ApplyPatchError::from)?; } InvalidHunkError { message, line_number, } => { writeln!( stderr, "Invalid patch hunk on line {line_number}: {message}" ) .map_err(ApplyPatchError::from)?; } } return Err(ApplyPatchError::ParseError(e)); } }; apply_hunks(&hunks, stdout, stderr)?; Ok(()) } /// Applies hunks and continues to update stdout/stderr pub fn apply_hunks( hunks: &[Hunk], stdout: &mut impl std::io::Write, stderr: &mut impl std::io::Write, ) -> Result<(), ApplyPatchError> { let _existing_paths: Vec<&Path> = hunks .iter() .filter_map(|hunk| match hunk { Hunk::AddFile { .. } => { // The file is being added, so it doesn't exist yet. None } Hunk::DeleteFile { path } => Some(path.as_path()), Hunk::UpdateFile { path, move_path, .. } => match move_path { Some(move_path) => { if std::fs::metadata(move_path) .map(|m| m.is_file()) .unwrap_or(false) { Some(move_path.as_path()) } else { None } } None => Some(path.as_path()), }, }) .collect::<Vec<&Path>>(); // Delegate to a helper that applies each hunk to the filesystem. match apply_hunks_to_files(hunks) { Ok(affected) => { print_summary(&affected, stdout).map_err(ApplyPatchError::from)?; Ok(()) } Err(err) => { let msg = err.to_string(); writeln!(stderr, "{msg}").map_err(ApplyPatchError::from)?; if let Some(io) = err.downcast_ref::<std::io::Error>() { Err(ApplyPatchError::from(io)) } else { Err(ApplyPatchError::IoError(IoError { context: msg, source: std::io::Error::other(err), })) } } } } /// Applies each parsed patch hunk to the filesystem. /// Returns an error if any of the changes could not be applied. /// Tracks file paths affected by applying a patch. pub struct AffectedPaths { pub added: Vec<PathBuf>, pub modified: Vec<PathBuf>, pub deleted: Vec<PathBuf>, } /// Apply the hunks to the filesystem, returning which files were added, modified, or deleted. /// Returns an error if the patch could not be applied. fn apply_hunks_to_files(hunks: &[Hunk]) -> anyhow::Result<AffectedPaths> { if hunks.is_empty() { anyhow::bail!("No files were modified."); } let mut added: Vec<PathBuf> = Vec::new(); let mut modified: Vec<PathBuf> = Vec::new(); let mut deleted: Vec<PathBuf> = Vec::new(); for hunk in hunks { match hunk { Hunk::AddFile { path, contents } => { if let Some(parent) = path.parent() && !parent.as_os_str().is_empty() { std::fs::create_dir_all(parent).with_context(|| { format!("Failed to create parent directories for {}", path.display()) })?; } std::fs::write(path, contents) .with_context(|| format!("Failed to write file {}", path.display()))?; added.push(path.clone()); } Hunk::DeleteFile { path } => { std::fs::remove_file(path) .with_context(|| format!("Failed to delete file {}", path.display()))?; deleted.push(path.clone()); } Hunk::UpdateFile { path, move_path, chunks, } => { let AppliedPatch { new_contents, .. } = derive_new_contents_from_chunks(path, chunks)?; if let Some(dest) = move_path { if let Some(parent) = dest.parent() && !parent.as_os_str().is_empty() { std::fs::create_dir_all(parent).with_context(|| { format!("Failed to create parent directories for {}", dest.display()) })?; } std::fs::write(dest, new_contents) .with_context(|| format!("Failed to write file {}", dest.display()))?; std::fs::remove_file(path) .with_context(|| format!("Failed to remove original {}", path.display()))?; modified.push(dest.clone()); } else { std::fs::write(path, new_contents) .with_context(|| format!("Failed to write file {}", path.display()))?; modified.push(path.clone()); } } } } Ok(AffectedPaths { added, modified, deleted, }) } struct AppliedPatch { original_contents: String, new_contents: String, } /// Return *only* the new file contents (joined into a single `String`) after /// applying the chunks to the file at `path`. fn derive_new_contents_from_chunks( path: &Path, chunks: &[UpdateFileChunk], ) -> std::result::Result<AppliedPatch, ApplyPatchError> { let original_contents = match std::fs::read_to_string(path) { Ok(contents) => contents, Err(err) => { return Err(ApplyPatchError::IoError(IoError { context: format!("Failed to read file to update {}", path.display()), source: err, })); } }; let mut original_lines: Vec<String> = original_contents.split('\n').map(String::from).collect(); // Drop the trailing empty element that results from the final newline so // that line counts match the behaviour of standard `diff`. if original_lines.last().is_some_and(String::is_empty) { original_lines.pop(); } let replacements = compute_replacements(&original_lines, path, chunks)?; let new_lines = apply_replacements(original_lines, &replacements); let mut new_lines = new_lines; if !new_lines.last().is_some_and(String::is_empty) { new_lines.push(String::new()); } let new_contents = new_lines.join("\n"); Ok(AppliedPatch { original_contents, new_contents, }) } /// Compute a list of replacements needed to transform `original_lines` into the /// new lines, given the patch `chunks`. Each replacement is returned as /// `(start_index, old_len, new_lines)`. fn compute_replacements( original_lines: &[String], path: &Path, chunks: &[UpdateFileChunk], ) -> std::result::Result<Vec<(usize, usize, Vec<String>)>, ApplyPatchError> { let mut replacements: Vec<(usize, usize, Vec<String>)> = Vec::new(); let mut line_index: usize = 0; for chunk in chunks { // If a chunk has a `change_context`, we use seek_sequence to find it, then // adjust our `line_index` to continue from there. if let Some(ctx_line) = &chunk.change_context { if let Some(idx) = seek_sequence::seek_sequence( original_lines, std::slice::from_ref(ctx_line), line_index, false, ) { line_index = idx + 1; } else { return Err(ApplyPatchError::ComputeReplacements(format!( "Failed to find context '{}' in {}", ctx_line, path.display() ))); } } if chunk.old_lines.is_empty() { // Pure addition (no old lines). We'll add them at the end or just // before the final empty line if one exists. let insertion_idx = if original_lines.last().is_some_and(String::is_empty) { original_lines.len() - 1 } else { original_lines.len() }; replacements.push((insertion_idx, 0, chunk.new_lines.clone())); continue; } // Otherwise, try to match the existing lines in the file with the old lines // from the chunk. If found, schedule that region for replacement. // Attempt to locate the `old_lines` verbatim within the file. In many // real‑world diffs the last element of `old_lines` is an *empty* string // representing the terminating newline of the region being replaced. // This sentinel is not present in `original_lines` because we strip the // trailing empty slice emitted by `split('\n')`. If a direct search // fails and the pattern ends with an empty string, retry without that // final element so that modifications touching the end‑of‑file can be // located reliably. let mut pattern: &[String] = &chunk.old_lines; let mut found = seek_sequence::seek_sequence(original_lines, pattern, line_index, chunk.is_end_of_file); let mut new_slice: &[String] = &chunk.new_lines; if found.is_none() && pattern.last().is_some_and(String::is_empty) { // Retry without the trailing empty line which represents the final // newline in the file. pattern = &pattern[..pattern.len() - 1]; if new_slice.last().is_some_and(String::is_empty) { new_slice = &new_slice[..new_slice.len() - 1]; } found = seek_sequence::seek_sequence( original_lines, pattern, line_index, chunk.is_end_of_file, ); } if let Some(start_idx) = found { replacements.push((start_idx, pattern.len(), new_slice.to_vec())); line_index = start_idx + pattern.len(); } else { return Err(ApplyPatchError::ComputeReplacements(format!( "Failed to find expected lines in {}:\n{}", path.display(), chunk.old_lines.join("\n"), ))); } } replacements.sort_by(|(lhs_idx, _, _), (rhs_idx, _, _)| lhs_idx.cmp(rhs_idx)); Ok(replacements) } /// Apply the `(start_index, old_len, new_lines)` replacements to `original_lines`, /// returning the modified file contents as a vector of lines. fn apply_replacements( mut lines: Vec<String>, replacements: &[(usize, usize, Vec<String>)], ) -> Vec<String> { // We must apply replacements in descending order so that earlier replacements // don't shift the positions of later ones. for (start_idx, old_len, new_segment) in replacements.iter().rev() { let start_idx = *start_idx; let old_len = *old_len; // Remove old lines. for _ in 0..old_len { if start_idx < lines.len() { lines.remove(start_idx); } } // Insert new lines. for (offset, new_line) in new_segment.iter().enumerate() { lines.insert(start_idx + offset, new_line.clone()); } } lines } /// Intended result of a file update for apply_patch. #[derive(Debug, Eq, PartialEq)] pub struct ApplyPatchFileUpdate { unified_diff: String, content: String, } pub fn unified_diff_from_chunks( path: &Path, chunks: &[UpdateFileChunk], ) -> std::result::Result<ApplyPatchFileUpdate, ApplyPatchError> { unified_diff_from_chunks_with_context(path, chunks, 1) } pub fn unified_diff_from_chunks_with_context( path: &Path, chunks: &[UpdateFileChunk], context: usize, ) -> std::result::Result<ApplyPatchFileUpdate, ApplyPatchError> { let AppliedPatch { original_contents, new_contents, } = derive_new_contents_from_chunks(path, chunks)?; let text_diff = TextDiff::from_lines(&original_contents, &new_contents); let unified_diff = text_diff.unified_diff().context_radius(context).to_string(); Ok(ApplyPatchFileUpdate { unified_diff, content: new_contents, }) } /// Print the summary of changes in git-style format. /// Write a summary of changes to the given writer. pub fn print_summary( affected: &AffectedPaths, out: &mut impl std::io::Write, ) -> std::io::Result<()> { writeln!(out, "Success. Updated the following files:")?; for path in &affected.added { writeln!(out, "A {}", path.display())?; } for path in &affected.modified { writeln!(out, "M {}", path.display())?; } for path in &affected.deleted { writeln!(out, "D {}", path.display())?; } Ok(()) } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; use std::fs; use std::string::ToString; use tempfile::tempdir; /// Helper to construct a patch with the given body. fn wrap_patch(body: &str) -> String { format!("*** Begin Patch\n{body}\n*** End Patch") } #[test] fn test_add_file_hunk_creates_file_with_contents() { let dir = tempdir().unwrap(); let path = dir.path().join("add.txt"); let patch = wrap_patch(&format!( r#"*** Add File: {} +ab +cd"#, path.display() )); let mut stdout = Vec::new(); let mut stderr = Vec::new(); apply_patch(&patch, &mut stdout, &mut stderr).unwrap(); // Verify expected stdout and stderr outputs. let stdout_str = String::from_utf8(stdout).unwrap(); let stderr_str = String::from_utf8(stderr).unwrap(); let expected_out = format!( "Success. Updated the following files:\nA {}\n", path.display() ); assert_eq!(stdout_str, expected_out); assert_eq!(stderr_str, ""); let contents = fs::read_to_string(path).unwrap(); assert_eq!(contents, "ab\ncd\n"); } #[test] fn test_delete_file_hunk_removes_file() { let dir = tempdir().unwrap(); let path = dir.path().join("del.txt"); fs::write(&path, "x").unwrap(); let patch = wrap_patch(&format!("*** Delete File: {}", path.display())); let mut stdout = Vec::new(); let mut stderr = Vec::new(); apply_patch(&patch, &mut stdout, &mut stderr).unwrap(); let stdout_str = String::from_utf8(stdout).unwrap(); let stderr_str = String::from_utf8(stderr).unwrap(); let expected_out = format!( "Success. Updated the following files:\nD {}\n", path.display() ); assert_eq!(stdout_str, expected_out); assert_eq!(stderr_str, ""); assert!(!path.exists()); } #[test] fn test_update_file_hunk_modifies_content() { let dir = tempdir().unwrap(); let path = dir.path().join("update.txt"); fs::write(&path, "foo\nbar\n").unwrap(); let patch = wrap_patch(&format!( r#"*** Update File: {} @@ foo -bar +baz"#, path.display() )); let mut stdout = Vec::new(); let mut stderr = Vec::new(); apply_patch(&patch, &mut stdout, &mut stderr).unwrap(); // Validate modified file contents and expected stdout/stderr. let stdout_str = String::from_utf8(stdout).unwrap(); let stderr_str = String::from_utf8(stderr).unwrap(); let expected_out = format!( "Success. Updated the following files:\nM {}\n", path.display() ); assert_eq!(stdout_str, expected_out); assert_eq!(stderr_str, ""); let contents = fs::read_to_string(&path).unwrap(); assert_eq!(contents, "foo\nbaz\n"); } #[test] fn test_update_file_hunk_can_move_file() { let dir = tempdir().unwrap(); let src = dir.path().join("src.txt"); let dest = dir.path().join("dst.txt"); fs::write(&src, "line\n").unwrap(); let patch = wrap_patch(&format!( r#"*** Update File: {} *** Move to: {} @@ -line +line2"#, src.display(), dest.display() )); let mut stdout = Vec::new(); let mut stderr = Vec::new(); apply_patch(&patch, &mut stdout, &mut stderr).unwrap(); // Validate move semantics and expected stdout/stderr. let stdout_str = String::from_utf8(stdout).unwrap(); let stderr_str = String::from_utf8(stderr).unwrap(); let expected_out = format!( "Success. Updated the following files:\nM {}\n", dest.display() ); assert_eq!(stdout_str, expected_out); assert_eq!(stderr_str, ""); assert!(!src.exists()); let contents = fs::read_to_string(&dest).unwrap(); assert_eq!(contents, "line2\n"); } /// Verify that a single `Update File` hunk with multiple change chunks can update different /// parts of a file and that the file is listed only once in the summary. #[test] fn test_multiple_update_chunks_apply_to_single_file() { // Start with a file containing four lines. let dir = tempdir().unwrap(); let path = dir.path().join("multi.txt"); fs::write(&path, "foo\nbar\nbaz\nqux\n").unwrap(); // Construct an update patch with two separate change chunks. // The first chunk uses the line `foo` as context and transforms `bar` into `BAR`. // The second chunk uses `baz` as context and transforms `qux` into `QUX`. let patch = wrap_patch(&format!( r#"*** Update File: {} @@ foo -bar +BAR @@ baz -qux +QUX"#, path.display() )); let mut stdout = Vec::new(); let mut stderr = Vec::new(); apply_patch(&patch, &mut stdout, &mut stderr).unwrap(); let stdout_str = String::from_utf8(stdout).unwrap(); let stderr_str = String::from_utf8(stderr).unwrap(); let expected_out = format!( "Success. Updated the following files:\nM {}\n", path.display() ); assert_eq!(stdout_str, expected_out); assert_eq!(stderr_str, ""); let contents = fs::read_to_string(&path).unwrap(); assert_eq!(contents, "foo\nBAR\nbaz\nQUX\n"); } /// A more involved `Update File` hunk that exercises additions, deletions and /// replacements in separate chunks that appear in non‑adjacent parts of the /// file. Verifies that all edits are applied and that the summary lists the /// file only once. #[test] fn test_update_file_hunk_interleaved_changes() { let dir = tempdir().unwrap(); let path = dir.path().join("interleaved.txt"); // Original file: six numbered lines. fs::write(&path, "a\nb\nc\nd\ne\nf\n").unwrap(); // Patch performs: // • Replace `b` → `B` // • Replace `e` → `E` (using surrounding context) // • Append new line `g` at the end‑of‑file let patch = wrap_patch(&format!( r#"*** Update File: {} @@ a -b +B @@ c d -e +E @@ f +g *** End of File"#, path.display() )); let mut stdout = Vec::new(); let mut stderr = Vec::new(); apply_patch(&patch, &mut stdout, &mut stderr).unwrap(); let stdout_str = String::from_utf8(stdout).unwrap(); let stderr_str = String::from_utf8(stderr).unwrap(); let expected_out = format!( "Success. Updated the following files:\nM {}\n", path.display() ); assert_eq!(stdout_str, expected_out); assert_eq!(stderr_str, ""); let contents = fs::read_to_string(&path).unwrap(); assert_eq!(contents, "a\nB\nc\nd\nE\nf\ng\n"); } #[test] fn test_pure_addition_chunk_followed_by_removal() { let dir = tempdir().unwrap(); let path = dir.path().join("panic.txt"); fs::write(&path, "line1\nline2\nline3\n").unwrap(); let patch = wrap_patch(&format!( r#"*** Update File: {} @@ +after-context +second-line @@ line1 -line2 -line3 +line2-replacement"#, path.display() )); let mut stdout = Vec::new(); let mut stderr = Vec::new(); apply_patch(&patch, &mut stdout, &mut stderr).unwrap(); let contents = fs::read_to_string(path).unwrap(); assert_eq!( contents, "line1\nline2-replacement\nafter-context\nsecond-line\n" ); } /// Ensure that patches authored with ASCII characters can update lines that /// contain typographic Unicode punctuation (e.g. EN DASH, NON-BREAKING /// HYPHEN). Historically `git apply` succeeds in such scenarios but our /// internal matcher failed requiring an exact byte-for-byte match. The /// fuzzy-matching pass that normalises common punctuation should now bridge /// the gap. #[test] fn test_update_line_with_unicode_dash() { let dir = tempdir().unwrap(); let path = dir.path().join("unicode.py"); // Original line contains EN DASH (\u{2013}) and NON-BREAKING HYPHEN (\u{2011}). let original = "import asyncio # local import \u{2013} avoids top\u{2011}level dep\n"; std::fs::write(&path, original).unwrap(); // Patch uses plain ASCII dash / hyphen. let patch = wrap_patch(&format!( r#"*** Update File: {} @@ -import asyncio # local import - avoids top-level dep +import asyncio # HELLO"#, path.display() )); let mut stdout = Vec::new(); let mut stderr = Vec::new(); apply_patch(&patch, &mut stdout, &mut stderr).unwrap(); // File should now contain the replaced comment. let expected = "import asyncio # HELLO\n"; let contents = std::fs::read_to_string(&path).unwrap(); assert_eq!(contents, expected); // Ensure success summary lists the file as modified. let stdout_str = String::from_utf8(stdout).unwrap(); let expected_out = format!( "Success. Updated the following files:\nM {}\n", path.display() ); assert_eq!(stdout_str, expected_out); // No stderr expected. assert_eq!(String::from_utf8(stderr).unwrap(), ""); } #[test] fn test_unified_diff() { // Start with a file containing four lines. let dir = tempdir().unwrap(); let path = dir.path().join("multi.txt"); fs::write(&path, "foo\nbar\nbaz\nqux\n").unwrap(); let patch = wrap_patch(&format!( r#"*** Update File: {} @@ foo -bar +BAR @@ baz -qux +QUX"#, path.display() )); let patch = parse_patch(&patch).unwrap(); let update_file_chunks = match patch.hunks.as_slice() { [Hunk::UpdateFile { chunks, .. }] => chunks, _ => panic!("Expected a single UpdateFile hunk"), }; let diff = unified_diff_from_chunks(&path, update_file_chunks).unwrap(); let expected_diff = r#"@@ -1,4 +1,4 @@ foo -bar +BAR baz -qux +QUX "#; let expected = ApplyPatchFileUpdate { unified_diff: expected_diff.to_string(), content: "foo\nBAR\nbaz\nQUX\n".to_string(), }; assert_eq!(expected, diff); } #[test] fn test_unified_diff_first_line_replacement() { // Replace the very first line of the file. let dir = tempdir().unwrap(); let path = dir.path().join("first.txt"); fs::write(&path, "foo\nbar\nbaz\n").unwrap(); let patch = wrap_patch(&format!( r#"*** Update File: {} @@ -foo +FOO bar "#, path.display() )); let patch = parse_patch(&patch).unwrap(); let chunks = match patch.hunks.as_slice() { [Hunk::UpdateFile { chunks, .. }] => chunks, _ => panic!("Expected a single UpdateFile hunk"), }; let diff = unified_diff_from_chunks(&path, chunks).unwrap(); let expected_diff = r#"@@ -1,2 +1,2 @@ -foo +FOO bar "#; let expected = ApplyPatchFileUpdate { unified_diff: expected_diff.to_string(), content: "FOO\nbar\nbaz\n".to_string(), }; assert_eq!(expected, diff); } #[test] fn test_unified_diff_last_line_replacement() { // Replace the very last line of the file. let dir = tempdir().unwrap(); let path = dir.path().join("last.txt"); fs::write(&path, "foo\nbar\nbaz\n").unwrap(); let patch = wrap_patch(&format!( r#"*** Update File: {} @@ foo bar -baz +BAZ "#, path.display() )); let patch = parse_patch(&patch).unwrap(); let chunks = match patch.hunks.as_slice() { [Hunk::UpdateFile { chunks, .. }] => chunks, _ => panic!("Expected a single UpdateFile hunk"), }; let diff = unified_diff_from_chunks(&path, chunks).unwrap(); let expected_diff = r#"@@ -2,2 +2,2 @@ bar -baz +BAZ "#; let expected = ApplyPatchFileUpdate { unified_diff: expected_diff.to_string(), content: "foo\nbar\nBAZ\n".to_string(), }; assert_eq!(expected, diff); } #[test] fn test_unified_diff_insert_at_eof() { // Insert a new line at end‑of‑file. let dir = tempdir().unwrap(); let path = dir.path().join("insert.txt"); fs::write(&path, "foo\nbar\nbaz\n").unwrap(); let patch = wrap_patch(&format!( r#"*** Update File: {} @@ +quux *** End of File "#, path.display() )); let patch = parse_patch(&patch).unwrap(); let chunks = match patch.hunks.as_slice() { [Hunk::UpdateFile { chunks, .. }] => chunks, _ => panic!("Expected a single UpdateFile hunk"), }; let diff = unified_diff_from_chunks(&path, chunks).unwrap(); let expected_diff = r#"@@ -3 +3,2 @@ baz +quux "#; let expected = ApplyPatchFileUpdate { unified_diff: expected_diff.to_string(), content: "foo\nbar\nbaz\nquux\n".to_string(), }; assert_eq!(expected, diff); } #[test] fn test_unified_diff_interleaved_changes() { // Original file with six lines. let dir = tempdir().unwrap(); let path = dir.path().join("interleaved.txt"); fs::write(&path, "a\nb\nc\nd\ne\nf\n").unwrap(); // Patch replaces two separate lines and appends a new one at EOF using // three distinct chunks. let patch_body = format!( r#"*** Update File: {} @@ a -b +B @@ d -e +E @@ f +g *** End of File"#, path.display() ); let patch = wrap_patch(&patch_body); // Extract chunks then build the unified diff. let parsed = parse_patch(&patch).unwrap(); let chunks = match parsed.hunks.as_slice() { [Hunk::UpdateFile { chunks, .. }] => chunks, _ => panic!("Expected a single UpdateFile hunk"),
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
true
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/apply-patch/src/parser.rs
codex-rs/apply-patch/src/parser.rs
//! This module is responsible for parsing & validating a patch into a list of "hunks". //! (It does not attempt to actually check that the patch can be applied to the filesystem.) //! //! The official Lark grammar for the apply-patch format is: //! //! start: begin_patch hunk+ end_patch //! begin_patch: "*** Begin Patch" LF //! end_patch: "*** End Patch" LF? //! //! hunk: add_hunk | delete_hunk | update_hunk //! add_hunk: "*** Add File: " filename LF add_line+ //! delete_hunk: "*** Delete File: " filename LF //! update_hunk: "*** Update File: " filename LF change_move? change? //! filename: /(.+)/ //! add_line: "+" /(.+)/ LF -> line //! //! change_move: "*** Move to: " filename LF //! change: (change_context | change_line)+ eof_line? //! change_context: ("@@" | "@@ " /(.+)/) LF //! change_line: ("+" | "-" | " ") /(.+)/ LF //! eof_line: "*** End of File" LF //! //! The parser below is a little more lenient than the explicit spec and allows for //! leading/trailing whitespace around patch markers. use crate::ApplyPatchArgs; use std::path::Path; use std::path::PathBuf; use thiserror::Error; const BEGIN_PATCH_MARKER: &str = "*** Begin Patch"; const END_PATCH_MARKER: &str = "*** End Patch"; const ADD_FILE_MARKER: &str = "*** Add File: "; const DELETE_FILE_MARKER: &str = "*** Delete File: "; const UPDATE_FILE_MARKER: &str = "*** Update File: "; const MOVE_TO_MARKER: &str = "*** Move to: "; const EOF_MARKER: &str = "*** End of File"; const CHANGE_CONTEXT_MARKER: &str = "@@ "; const EMPTY_CHANGE_CONTEXT_MARKER: &str = "@@"; /// Currently, the only OpenAI model that knowingly requires lenient parsing is /// gpt-4.1. While we could try to require everyone to pass in a strictness /// param when invoking apply_patch, it is a pain to thread it through all of /// the call sites, so we resign ourselves allowing lenient parsing for all /// models. See [`ParseMode::Lenient`] for details on the exceptions we make for /// gpt-4.1. const PARSE_IN_STRICT_MODE: bool = false; #[derive(Debug, PartialEq, Error, Clone)] pub enum ParseError { #[error("invalid patch: {0}")] InvalidPatchError(String), #[error("invalid hunk at line {line_number}, {message}")] InvalidHunkError { message: String, line_number: usize }, } use ParseError::*; #[derive(Debug, PartialEq, Clone)] #[allow(clippy::enum_variant_names)] pub enum Hunk { AddFile { path: PathBuf, contents: String, }, DeleteFile { path: PathBuf, }, UpdateFile { path: PathBuf, move_path: Option<PathBuf>, /// Chunks should be in order, i.e. the `change_context` of one chunk /// should occur later in the file than the previous chunk. chunks: Vec<UpdateFileChunk>, }, } impl Hunk { pub fn resolve_path(&self, cwd: &Path) -> PathBuf { match self { Hunk::AddFile { path, .. } => cwd.join(path), Hunk::DeleteFile { path } => cwd.join(path), Hunk::UpdateFile { path, .. } => cwd.join(path), } } } use Hunk::*; #[derive(Debug, PartialEq, Clone)] pub struct UpdateFileChunk { /// A single line of context used to narrow down the position of the chunk /// (this is usually a class, method, or function definition.) pub change_context: Option<String>, /// A contiguous block of lines that should be replaced with `new_lines`. /// `old_lines` must occur strictly after `change_context`. pub old_lines: Vec<String>, pub new_lines: Vec<String>, /// If set to true, `old_lines` must occur at the end of the source file. /// (Tolerance around trailing newlines should be encouraged.) pub is_end_of_file: bool, } pub fn parse_patch(patch: &str) -> Result<ApplyPatchArgs, ParseError> { let mode = if PARSE_IN_STRICT_MODE { ParseMode::Strict } else { ParseMode::Lenient }; parse_patch_text(patch, mode) } enum ParseMode { /// Parse the patch text argument as is. Strict, /// GPT-4.1 is known to formulate the `command` array for the `local_shell` /// tool call for `apply_patch` call using something like the following: /// /// ```json /// [ /// "apply_patch", /// "<<'EOF'\n*** Begin Patch\n*** Update File: README.md\n@@...\n*** End Patch\nEOF\n", /// ] /// ``` /// /// This is a problem because `local_shell` is a bit of a misnomer: the /// `command` is not invoked by passing the arguments to a shell like Bash, /// but are invoked using something akin to `execvpe(3)`. /// /// This is significant in this case because where a shell would interpret /// `<<'EOF'...` as a heredoc and pass the contents via stdin (which is /// fine, as `apply_patch` is specified to read from stdin if no argument is /// passed), `execvpe(3)` interprets the heredoc as a literal string. To get /// the `local_shell` tool to run a command the way shell would, the /// `command` array must be something like: /// /// ```json /// [ /// "bash", /// "-lc", /// "apply_patch <<'EOF'\n*** Begin Patch\n*** Update File: README.md\n@@...\n*** End Patch\nEOF\n", /// ] /// ``` /// /// In lenient mode, we check if the argument to `apply_patch` starts with /// `<<'EOF'` and ends with `EOF\n`. If so, we strip off these markers, /// trim() the result, and treat what is left as the patch text. Lenient, } fn parse_patch_text(patch: &str, mode: ParseMode) -> Result<ApplyPatchArgs, ParseError> { let lines: Vec<&str> = patch.trim().lines().collect(); let lines: &[&str] = match check_patch_boundaries_strict(&lines) { Ok(()) => &lines, Err(e) => match mode { ParseMode::Strict => { return Err(e); } ParseMode::Lenient => check_patch_boundaries_lenient(&lines, e)?, }, }; let mut hunks: Vec<Hunk> = Vec::new(); // The above checks ensure that lines.len() >= 2. let last_line_index = lines.len().saturating_sub(1); let mut remaining_lines = &lines[1..last_line_index]; let mut line_number = 2; while !remaining_lines.is_empty() { let (hunk, hunk_lines) = parse_one_hunk(remaining_lines, line_number)?; hunks.push(hunk); line_number += hunk_lines; remaining_lines = &remaining_lines[hunk_lines..] } let patch = lines.join("\n"); Ok(ApplyPatchArgs { hunks, patch, workdir: None, }) } /// Checks the start and end lines of the patch text for `apply_patch`, /// returning an error if they do not match the expected markers. fn check_patch_boundaries_strict(lines: &[&str]) -> Result<(), ParseError> { let (first_line, last_line) = match lines { [] => (None, None), [first] => (Some(first), Some(first)), [first, .., last] => (Some(first), Some(last)), }; check_start_and_end_lines_strict(first_line, last_line) } /// If we are in lenient mode, we check if the first line starts with `<<EOF` /// (possibly quoted) and the last line ends with `EOF`. There must be at least /// 4 lines total because the heredoc markers take up 2 lines and the patch text /// must have at least 2 lines. /// /// If successful, returns the lines of the patch text that contain the patch /// contents, excluding the heredoc markers. fn check_patch_boundaries_lenient<'a>( original_lines: &'a [&'a str], original_parse_error: ParseError, ) -> Result<&'a [&'a str], ParseError> { match original_lines { [first, .., last] => { if (first == &"<<EOF" || first == &"<<'EOF'" || first == &"<<\"EOF\"") && last.ends_with("EOF") && original_lines.len() >= 4 { let inner_lines = &original_lines[1..original_lines.len() - 1]; match check_patch_boundaries_strict(inner_lines) { Ok(()) => Ok(inner_lines), Err(e) => Err(e), } } else { Err(original_parse_error) } } _ => Err(original_parse_error), } } fn check_start_and_end_lines_strict( first_line: Option<&&str>, last_line: Option<&&str>, ) -> Result<(), ParseError> { match (first_line, last_line) { (Some(&first), Some(&last)) if first == BEGIN_PATCH_MARKER && last == END_PATCH_MARKER => { Ok(()) } (Some(&first), _) if first != BEGIN_PATCH_MARKER => Err(InvalidPatchError(String::from( "The first line of the patch must be '*** Begin Patch'", ))), _ => Err(InvalidPatchError(String::from( "The last line of the patch must be '*** End Patch'", ))), } } /// Attempts to parse a single hunk from the start of lines. /// Returns the parsed hunk and the number of lines parsed (or a ParseError). fn parse_one_hunk(lines: &[&str], line_number: usize) -> Result<(Hunk, usize), ParseError> { // Be tolerant of case mismatches and extra padding around marker strings. let first_line = lines[0].trim(); if let Some(path) = first_line.strip_prefix(ADD_FILE_MARKER) { // Add File let mut contents = String::new(); let mut parsed_lines = 1; for add_line in &lines[1..] { if let Some(line_to_add) = add_line.strip_prefix('+') { contents.push_str(line_to_add); contents.push('\n'); parsed_lines += 1; } else { break; } } return Ok(( AddFile { path: PathBuf::from(path), contents, }, parsed_lines, )); } else if let Some(path) = first_line.strip_prefix(DELETE_FILE_MARKER) { // Delete File return Ok(( DeleteFile { path: PathBuf::from(path), }, 1, )); } else if let Some(path) = first_line.strip_prefix(UPDATE_FILE_MARKER) { // Update File let mut remaining_lines = &lines[1..]; let mut parsed_lines = 1; // Optional: move file line let move_path = remaining_lines .first() .and_then(|x| x.strip_prefix(MOVE_TO_MARKER)); if move_path.is_some() { remaining_lines = &remaining_lines[1..]; parsed_lines += 1; } let mut chunks = Vec::new(); // NOTE: we need to know to stop once we reach the next special marker header. while !remaining_lines.is_empty() { // Skip over any completely blank lines that may separate chunks. if remaining_lines[0].trim().is_empty() { parsed_lines += 1; remaining_lines = &remaining_lines[1..]; continue; } if remaining_lines[0].starts_with("***") { break; } let (chunk, chunk_lines) = parse_update_file_chunk( remaining_lines, line_number + parsed_lines, chunks.is_empty(), )?; chunks.push(chunk); parsed_lines += chunk_lines; remaining_lines = &remaining_lines[chunk_lines..] } if chunks.is_empty() { return Err(InvalidHunkError { message: format!("Update file hunk for path '{path}' is empty"), line_number, }); } return Ok(( UpdateFile { path: PathBuf::from(path), move_path: move_path.map(PathBuf::from), chunks, }, parsed_lines, )); } Err(InvalidHunkError { message: format!( "'{first_line}' is not a valid hunk header. Valid hunk headers: '*** Add File: {{path}}', '*** Delete File: {{path}}', '*** Update File: {{path}}'" ), line_number, }) } fn parse_update_file_chunk( lines: &[&str], line_number: usize, allow_missing_context: bool, ) -> Result<(UpdateFileChunk, usize), ParseError> { if lines.is_empty() { return Err(InvalidHunkError { message: "Update hunk does not contain any lines".to_string(), line_number, }); } // If we see an explicit context marker @@ or @@ <context>, consume it; otherwise, optionally // allow treating the chunk as starting directly with diff lines. let (change_context, start_index) = if lines[0] == EMPTY_CHANGE_CONTEXT_MARKER { (None, 1) } else if let Some(context) = lines[0].strip_prefix(CHANGE_CONTEXT_MARKER) { (Some(context.to_string()), 1) } else { if !allow_missing_context { return Err(InvalidHunkError { message: format!( "Expected update hunk to start with a @@ context marker, got: '{}'", lines[0] ), line_number, }); } (None, 0) }; if start_index >= lines.len() { return Err(InvalidHunkError { message: "Update hunk does not contain any lines".to_string(), line_number: line_number + 1, }); } let mut chunk = UpdateFileChunk { change_context, old_lines: Vec::new(), new_lines: Vec::new(), is_end_of_file: false, }; let mut parsed_lines = 0; for line in &lines[start_index..] { match *line { EOF_MARKER => { if parsed_lines == 0 { return Err(InvalidHunkError { message: "Update hunk does not contain any lines".to_string(), line_number: line_number + 1, }); } chunk.is_end_of_file = true; parsed_lines += 1; break; } line_contents => { match line_contents.chars().next() { None => { // Interpret this as an empty line. chunk.old_lines.push(String::new()); chunk.new_lines.push(String::new()); } Some(' ') => { chunk.old_lines.push(line_contents[1..].to_string()); chunk.new_lines.push(line_contents[1..].to_string()); } Some('+') => { chunk.new_lines.push(line_contents[1..].to_string()); } Some('-') => { chunk.old_lines.push(line_contents[1..].to_string()); } _ => { if parsed_lines == 0 { return Err(InvalidHunkError { message: format!( "Unexpected line found in update hunk: '{line_contents}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)" ), line_number: line_number + 1, }); } // Assume this is the start of the next hunk. break; } } parsed_lines += 1; } } } Ok((chunk, parsed_lines + start_index)) } #[test] fn test_parse_patch() { assert_eq!( parse_patch_text("bad", ParseMode::Strict), Err(InvalidPatchError( "The first line of the patch must be '*** Begin Patch'".to_string() )) ); assert_eq!( parse_patch_text("*** Begin Patch\nbad", ParseMode::Strict), Err(InvalidPatchError( "The last line of the patch must be '*** End Patch'".to_string() )) ); assert_eq!( parse_patch_text( "*** Begin Patch\n\ *** Update File: test.py\n\ *** End Patch", ParseMode::Strict ), Err(InvalidHunkError { message: "Update file hunk for path 'test.py' is empty".to_string(), line_number: 2, }) ); assert_eq!( parse_patch_text( "*** Begin Patch\n\ *** End Patch", ParseMode::Strict ) .unwrap() .hunks, Vec::new() ); assert_eq!( parse_patch_text( "*** Begin Patch\n\ *** Add File: path/add.py\n\ +abc\n\ +def\n\ *** Delete File: path/delete.py\n\ *** Update File: path/update.py\n\ *** Move to: path/update2.py\n\ @@ def f():\n\ - pass\n\ + return 123\n\ *** End Patch", ParseMode::Strict ) .unwrap() .hunks, vec![ AddFile { path: PathBuf::from("path/add.py"), contents: "abc\ndef\n".to_string() }, DeleteFile { path: PathBuf::from("path/delete.py") }, UpdateFile { path: PathBuf::from("path/update.py"), move_path: Some(PathBuf::from("path/update2.py")), chunks: vec![UpdateFileChunk { change_context: Some("def f():".to_string()), old_lines: vec![" pass".to_string()], new_lines: vec![" return 123".to_string()], is_end_of_file: false }] } ] ); // Update hunk followed by another hunk (Add File). assert_eq!( parse_patch_text( "*** Begin Patch\n\ *** Update File: file.py\n\ @@\n\ +line\n\ *** Add File: other.py\n\ +content\n\ *** End Patch", ParseMode::Strict ) .unwrap() .hunks, vec![ UpdateFile { path: PathBuf::from("file.py"), move_path: None, chunks: vec![UpdateFileChunk { change_context: None, old_lines: vec![], new_lines: vec!["line".to_string()], is_end_of_file: false }], }, AddFile { path: PathBuf::from("other.py"), contents: "content\n".to_string() } ] ); // Update hunk without an explicit @@ header for the first chunk should parse. // Use a raw string to preserve the leading space diff marker on the context line. assert_eq!( parse_patch_text( r#"*** Begin Patch *** Update File: file2.py import foo +bar *** End Patch"#, ParseMode::Strict ) .unwrap() .hunks, vec![UpdateFile { path: PathBuf::from("file2.py"), move_path: None, chunks: vec![UpdateFileChunk { change_context: None, old_lines: vec!["import foo".to_string()], new_lines: vec!["import foo".to_string(), "bar".to_string()], is_end_of_file: false, }], }] ); } #[test] fn test_parse_patch_lenient() { let patch_text = r#"*** Begin Patch *** Update File: file2.py import foo +bar *** End Patch"#; let expected_patch = vec![UpdateFile { path: PathBuf::from("file2.py"), move_path: None, chunks: vec![UpdateFileChunk { change_context: None, old_lines: vec!["import foo".to_string()], new_lines: vec!["import foo".to_string(), "bar".to_string()], is_end_of_file: false, }], }]; let expected_error = InvalidPatchError("The first line of the patch must be '*** Begin Patch'".to_string()); let patch_text_in_heredoc = format!("<<EOF\n{patch_text}\nEOF\n"); assert_eq!( parse_patch_text(&patch_text_in_heredoc, ParseMode::Strict), Err(expected_error.clone()) ); assert_eq!( parse_patch_text(&patch_text_in_heredoc, ParseMode::Lenient), Ok(ApplyPatchArgs { hunks: expected_patch.clone(), patch: patch_text.to_string(), workdir: None, }) ); let patch_text_in_single_quoted_heredoc = format!("<<'EOF'\n{patch_text}\nEOF\n"); assert_eq!( parse_patch_text(&patch_text_in_single_quoted_heredoc, ParseMode::Strict), Err(expected_error.clone()) ); assert_eq!( parse_patch_text(&patch_text_in_single_quoted_heredoc, ParseMode::Lenient), Ok(ApplyPatchArgs { hunks: expected_patch.clone(), patch: patch_text.to_string(), workdir: None, }) ); let patch_text_in_double_quoted_heredoc = format!("<<\"EOF\"\n{patch_text}\nEOF\n"); assert_eq!( parse_patch_text(&patch_text_in_double_quoted_heredoc, ParseMode::Strict), Err(expected_error.clone()) ); assert_eq!( parse_patch_text(&patch_text_in_double_quoted_heredoc, ParseMode::Lenient), Ok(ApplyPatchArgs { hunks: expected_patch, patch: patch_text.to_string(), workdir: None, }) ); let patch_text_in_mismatched_quotes_heredoc = format!("<<\"EOF'\n{patch_text}\nEOF\n"); assert_eq!( parse_patch_text(&patch_text_in_mismatched_quotes_heredoc, ParseMode::Strict), Err(expected_error.clone()) ); assert_eq!( parse_patch_text(&patch_text_in_mismatched_quotes_heredoc, ParseMode::Lenient), Err(expected_error.clone()) ); let patch_text_with_missing_closing_heredoc = "<<EOF\n*** Begin Patch\n*** Update File: file2.py\nEOF\n".to_string(); assert_eq!( parse_patch_text(&patch_text_with_missing_closing_heredoc, ParseMode::Strict), Err(expected_error) ); assert_eq!( parse_patch_text(&patch_text_with_missing_closing_heredoc, ParseMode::Lenient), Err(InvalidPatchError( "The last line of the patch must be '*** End Patch'".to_string() )) ); } #[test] fn test_parse_one_hunk() { assert_eq!( parse_one_hunk(&["bad"], 234), Err(InvalidHunkError { message: "'bad' is not a valid hunk header. \ Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'".to_string(), line_number: 234 }) ); // Other edge cases are already covered by tests above/below. } #[test] fn test_update_file_chunk() { assert_eq!( parse_update_file_chunk(&["bad"], 123, false), Err(InvalidHunkError { message: "Expected update hunk to start with a @@ context marker, got: 'bad'" .to_string(), line_number: 123 }) ); assert_eq!( parse_update_file_chunk(&["@@"], 123, false), Err(InvalidHunkError { message: "Update hunk does not contain any lines".to_string(), line_number: 124 }) ); assert_eq!( parse_update_file_chunk(&["@@", "bad"], 123, false), Err(InvalidHunkError { message: "Unexpected line found in update hunk: 'bad'. \ Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)".to_string(), line_number: 124 }) ); assert_eq!( parse_update_file_chunk(&["@@", "*** End of File"], 123, false), Err(InvalidHunkError { message: "Update hunk does not contain any lines".to_string(), line_number: 124 }) ); assert_eq!( parse_update_file_chunk( &[ "@@ change_context", "", " context", "-remove", "+add", " context2", "*** End Patch", ], 123, false ), Ok(( (UpdateFileChunk { change_context: Some("change_context".to_string()), old_lines: vec![ "".to_string(), "context".to_string(), "remove".to_string(), "context2".to_string() ], new_lines: vec![ "".to_string(), "context".to_string(), "add".to_string(), "context2".to_string() ], is_end_of_file: false }), 6 )) ); assert_eq!( parse_update_file_chunk(&["@@", "+line", "*** End of File"], 123, false), Ok(( (UpdateFileChunk { change_context: None, old_lines: vec![], new_lines: vec!["line".to_string()], is_end_of_file: true }), 3 )) ); }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/apply-patch/src/main.rs
codex-rs/apply-patch/src/main.rs
pub fn main() -> ! { codex_apply_patch::main() }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/apply-patch/src/seek_sequence.rs
codex-rs/apply-patch/src/seek_sequence.rs
/// Attempt to find the sequence of `pattern` lines within `lines` beginning at or after `start`. /// Returns the starting index of the match or `None` if not found. Matches are attempted with /// decreasing strictness: exact match, then ignoring trailing whitespace, then ignoring leading /// and trailing whitespace. When `eof` is true, we first try starting at the end-of-file (so that /// patterns intended to match file endings are applied at the end), and fall back to searching /// from `start` if needed. /// /// Special cases handled defensively: /// • Empty `pattern` → returns `Some(start)` (no-op match) /// • `pattern.len() > lines.len()` → returns `None` (cannot match, avoids /// out‑of‑bounds panic that occurred pre‑2025‑04‑12) pub(crate) fn seek_sequence( lines: &[String], pattern: &[String], start: usize, eof: bool, ) -> Option<usize> { if pattern.is_empty() { return Some(start); } // When the pattern is longer than the available input there is no possible // match. Early‑return to avoid the out‑of‑bounds slice that would occur in // the search loops below (previously caused a panic when // `pattern.len() > lines.len()`). if pattern.len() > lines.len() { return None; } let search_start = if eof && lines.len() >= pattern.len() { lines.len() - pattern.len() } else { start }; // Exact match first. for i in search_start..=lines.len().saturating_sub(pattern.len()) { if lines[i..i + pattern.len()] == *pattern { return Some(i); } } // Then rstrip match. for i in search_start..=lines.len().saturating_sub(pattern.len()) { let mut ok = true; for (p_idx, pat) in pattern.iter().enumerate() { if lines[i + p_idx].trim_end() != pat.trim_end() { ok = false; break; } } if ok { return Some(i); } } // Finally, trim both sides to allow more lenience. for i in search_start..=lines.len().saturating_sub(pattern.len()) { let mut ok = true; for (p_idx, pat) in pattern.iter().enumerate() { if lines[i + p_idx].trim() != pat.trim() { ok = false; break; } } if ok { return Some(i); } } // ------------------------------------------------------------------ // Final, most permissive pass – attempt to match after *normalising* // common Unicode punctuation to their ASCII equivalents so that diffs // authored with plain ASCII characters can still be applied to source // files that contain typographic dashes / quotes, etc. This mirrors the // fuzzy behaviour of `git apply` which ignores minor byte-level // differences when locating context lines. // ------------------------------------------------------------------ fn normalise(s: &str) -> String { s.trim() .chars() .map(|c| match c { // Various dash / hyphen code-points → ASCII '-' '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}' | '\u{2212}' => '-', // Fancy single quotes → '\'' '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' => '\'', // Fancy double quotes → '"' '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' => '"', // Non-breaking space and other odd spaces → normal space '\u{00A0}' | '\u{2002}' | '\u{2003}' | '\u{2004}' | '\u{2005}' | '\u{2006}' | '\u{2007}' | '\u{2008}' | '\u{2009}' | '\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}' => ' ', other => other, }) .collect::<String>() } for i in search_start..=lines.len().saturating_sub(pattern.len()) { let mut ok = true; for (p_idx, pat) in pattern.iter().enumerate() { if normalise(&lines[i + p_idx]) != normalise(pat) { ok = false; break; } } if ok { return Some(i); } } None } #[cfg(test)] mod tests { use super::seek_sequence; use std::string::ToString; fn to_vec(strings: &[&str]) -> Vec<String> { strings.iter().map(ToString::to_string).collect() } #[test] fn test_exact_match_finds_sequence() { let lines = to_vec(&["foo", "bar", "baz"]); let pattern = to_vec(&["bar", "baz"]); assert_eq!(seek_sequence(&lines, &pattern, 0, false), Some(1)); } #[test] fn test_rstrip_match_ignores_trailing_whitespace() { let lines = to_vec(&["foo ", "bar\t\t"]); // Pattern omits trailing whitespace. let pattern = to_vec(&["foo", "bar"]); assert_eq!(seek_sequence(&lines, &pattern, 0, false), Some(0)); } #[test] fn test_trim_match_ignores_leading_and_trailing_whitespace() { let lines = to_vec(&[" foo ", " bar\t"]); // Pattern omits any additional whitespace. let pattern = to_vec(&["foo", "bar"]); assert_eq!(seek_sequence(&lines, &pattern, 0, false), Some(0)); } #[test] fn test_pattern_longer_than_input_returns_none() { let lines = to_vec(&["just one line"]); let pattern = to_vec(&["too", "many", "lines"]); // Should not panic – must return None when pattern cannot possibly fit. assert_eq!(seek_sequence(&lines, &pattern, 0, false), None); } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/apply-patch/tests/all.rs
codex-rs/apply-patch/tests/all.rs
// Single integration test binary that aggregates all test modules. // The submodules live in `tests/suite/`. mod suite;
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/apply-patch/tests/suite/scenarios.rs
codex-rs/apply-patch/tests/suite/scenarios.rs
use pretty_assertions::assert_eq; use std::collections::BTreeMap; use std::fs; use std::path::Path; use std::path::PathBuf; use std::process::Command; use tempfile::tempdir; #[test] fn test_apply_patch_scenarios() -> anyhow::Result<()> { let scenarios_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/scenarios"); for scenario in fs::read_dir(scenarios_dir)? { let scenario = scenario?; let path = scenario.path(); if path.is_dir() { run_apply_patch_scenario(&path)?; } } Ok(()) } /// Reads a scenario directory, copies the input files to a temporary directory, runs apply-patch, /// and asserts that the final state matches the expected state exactly. fn run_apply_patch_scenario(dir: &Path) -> anyhow::Result<()> { let tmp = tempdir()?; // Copy the input files to the temporary directory let input_dir = dir.join("input"); if input_dir.is_dir() { copy_dir_recursive(&input_dir, tmp.path())?; } // Read the patch.txt file let patch = fs::read_to_string(dir.join("patch.txt"))?; // Run apply_patch in the temporary directory. We intentionally do not assert // on the exit status here; the scenarios are specified purely in terms of // final filesystem state, which we compare below. Command::new(codex_utils_cargo_bin::cargo_bin("apply_patch")?) .arg(patch) .current_dir(tmp.path()) .output()?; // Assert that the final state matches the expected state exactly let expected_dir = dir.join("expected"); let expected_snapshot = snapshot_dir(&expected_dir)?; let actual_snapshot = snapshot_dir(tmp.path())?; assert_eq!( actual_snapshot, expected_snapshot, "Scenario {} did not match expected final state", dir.display() ); Ok(()) } #[derive(Debug, Clone, PartialEq, Eq)] enum Entry { File(Vec<u8>), Dir, } fn snapshot_dir(root: &Path) -> anyhow::Result<BTreeMap<PathBuf, Entry>> { let mut entries = BTreeMap::new(); if root.is_dir() { snapshot_dir_recursive(root, root, &mut entries)?; } Ok(entries) } fn snapshot_dir_recursive( base: &Path, dir: &Path, entries: &mut BTreeMap<PathBuf, Entry>, ) -> anyhow::Result<()> { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); let Some(stripped) = path.strip_prefix(base).ok() else { continue; }; let rel = stripped.to_path_buf(); // Under Buck2, files in `__srcs` are often materialized as symlinks. // Use `metadata()` (follows symlinks) so our fixture snapshots work // under both Cargo and Buck2. let metadata = fs::metadata(&path)?; if metadata.is_dir() { entries.insert(rel.clone(), Entry::Dir); snapshot_dir_recursive(base, &path, entries)?; } else if metadata.is_file() { let contents = fs::read(&path)?; entries.insert(rel, Entry::File(contents)); } } Ok(()) } fn copy_dir_recursive(src: &Path, dst: &Path) -> anyhow::Result<()> { for entry in fs::read_dir(src)? { let entry = entry?; let path = entry.path(); let dest_path = dst.join(entry.file_name()); // See note in `snapshot_dir_recursive` about Buck2 symlink trees. let metadata = fs::metadata(&path)?; if metadata.is_dir() { fs::create_dir_all(&dest_path)?; copy_dir_recursive(&path, &dest_path)?; } else if metadata.is_file() { if let Some(parent) = dest_path.parent() { fs::create_dir_all(parent)?; } fs::copy(&path, &dest_path)?; } } Ok(()) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/apply-patch/tests/suite/cli.rs
codex-rs/apply-patch/tests/suite/cli.rs
use assert_cmd::Command; use std::fs; use tempfile::tempdir; fn apply_patch_command() -> anyhow::Result<Command> { Ok(Command::new(codex_utils_cargo_bin::cargo_bin( "apply_patch", )?)) } #[test] fn test_apply_patch_cli_add_and_update() -> anyhow::Result<()> { let tmp = tempdir()?; let file = "cli_test.txt"; let absolute_path = tmp.path().join(file); // 1) Add a file let add_patch = format!( r#"*** Begin Patch *** Add File: {file} +hello *** End Patch"# ); apply_patch_command()? .arg(add_patch) .current_dir(tmp.path()) .assert() .success() .stdout(format!("Success. Updated the following files:\nA {file}\n")); assert_eq!(fs::read_to_string(&absolute_path)?, "hello\n"); // 2) Update the file let update_patch = format!( r#"*** Begin Patch *** Update File: {file} @@ -hello +world *** End Patch"# ); apply_patch_command()? .arg(update_patch) .current_dir(tmp.path()) .assert() .success() .stdout(format!("Success. Updated the following files:\nM {file}\n")); assert_eq!(fs::read_to_string(&absolute_path)?, "world\n"); Ok(()) } #[test] fn test_apply_patch_cli_stdin_add_and_update() -> anyhow::Result<()> { let tmp = tempdir()?; let file = "cli_test_stdin.txt"; let absolute_path = tmp.path().join(file); // 1) Add a file via stdin let add_patch = format!( r#"*** Begin Patch *** Add File: {file} +hello *** End Patch"# ); apply_patch_command()? .current_dir(tmp.path()) .write_stdin(add_patch) .assert() .success() .stdout(format!("Success. Updated the following files:\nA {file}\n")); assert_eq!(fs::read_to_string(&absolute_path)?, "hello\n"); // 2) Update the file via stdin let update_patch = format!( r#"*** Begin Patch *** Update File: {file} @@ -hello +world *** End Patch"# ); apply_patch_command()? .current_dir(tmp.path()) .write_stdin(update_patch) .assert() .success() .stdout(format!("Success. Updated the following files:\nM {file}\n")); assert_eq!(fs::read_to_string(&absolute_path)?, "world\n"); Ok(()) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/apply-patch/tests/suite/mod.rs
codex-rs/apply-patch/tests/suite/mod.rs
mod cli; mod scenarios; #[cfg(not(target_os = "windows"))] mod tool;
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/apply-patch/tests/suite/tool.rs
codex-rs/apply-patch/tests/suite/tool.rs
use assert_cmd::Command; use pretty_assertions::assert_eq; use std::fs; use std::path::Path; use tempfile::tempdir; fn run_apply_patch_in_dir(dir: &Path, patch: &str) -> anyhow::Result<assert_cmd::assert::Assert> { let mut cmd = Command::new(codex_utils_cargo_bin::cargo_bin("apply_patch")?); cmd.current_dir(dir); Ok(cmd.arg(patch).assert()) } fn apply_patch_command(dir: &Path) -> anyhow::Result<Command> { let mut cmd = Command::new(codex_utils_cargo_bin::cargo_bin("apply_patch")?); cmd.current_dir(dir); Ok(cmd) } #[test] fn test_apply_patch_cli_applies_multiple_operations() -> anyhow::Result<()> { let tmp = tempdir()?; let modify_path = tmp.path().join("modify.txt"); let delete_path = tmp.path().join("delete.txt"); fs::write(&modify_path, "line1\nline2\n")?; fs::write(&delete_path, "obsolete\n")?; let patch = "*** Begin Patch\n*** Add File: nested/new.txt\n+created\n*** Delete File: delete.txt\n*** Update File: modify.txt\n@@\n-line2\n+changed\n*** End Patch"; run_apply_patch_in_dir(tmp.path(), patch)?.success().stdout( "Success. Updated the following files:\nA nested/new.txt\nM modify.txt\nD delete.txt\n", ); assert_eq!( fs::read_to_string(tmp.path().join("nested/new.txt"))?, "created\n" ); assert_eq!(fs::read_to_string(&modify_path)?, "line1\nchanged\n"); assert!(!delete_path.exists()); Ok(()) } #[test] fn test_apply_patch_cli_applies_multiple_chunks() -> anyhow::Result<()> { let tmp = tempdir()?; let target_path = tmp.path().join("multi.txt"); fs::write(&target_path, "line1\nline2\nline3\nline4\n")?; let patch = "*** Begin Patch\n*** Update File: multi.txt\n@@\n-line2\n+changed2\n@@\n-line4\n+changed4\n*** End Patch"; run_apply_patch_in_dir(tmp.path(), patch)? .success() .stdout("Success. Updated the following files:\nM multi.txt\n"); assert_eq!( fs::read_to_string(&target_path)?, "line1\nchanged2\nline3\nchanged4\n" ); Ok(()) } #[test] fn test_apply_patch_cli_moves_file_to_new_directory() -> anyhow::Result<()> { let tmp = tempdir()?; let original_path = tmp.path().join("old/name.txt"); let new_path = tmp.path().join("renamed/dir/name.txt"); fs::create_dir_all(original_path.parent().expect("parent should exist"))?; fs::write(&original_path, "old content\n")?; let patch = "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/dir/name.txt\n@@\n-old content\n+new content\n*** End Patch"; run_apply_patch_in_dir(tmp.path(), patch)? .success() .stdout("Success. Updated the following files:\nM renamed/dir/name.txt\n"); assert!(!original_path.exists()); assert_eq!(fs::read_to_string(&new_path)?, "new content\n"); Ok(()) } #[test] fn test_apply_patch_cli_rejects_empty_patch() -> anyhow::Result<()> { let tmp = tempdir()?; apply_patch_command(tmp.path())? .arg("*** Begin Patch\n*** End Patch") .assert() .failure() .stderr("No files were modified.\n"); Ok(()) } #[test] fn test_apply_patch_cli_reports_missing_context() -> anyhow::Result<()> { let tmp = tempdir()?; let target_path = tmp.path().join("modify.txt"); fs::write(&target_path, "line1\nline2\n")?; apply_patch_command(tmp.path())? .arg("*** Begin Patch\n*** Update File: modify.txt\n@@\n-missing\n+changed\n*** End Patch") .assert() .failure() .stderr("Failed to find expected lines in modify.txt:\nmissing\n"); assert_eq!(fs::read_to_string(&target_path)?, "line1\nline2\n"); Ok(()) } #[test] fn test_apply_patch_cli_rejects_missing_file_delete() -> anyhow::Result<()> { let tmp = tempdir()?; apply_patch_command(tmp.path())? .arg("*** Begin Patch\n*** Delete File: missing.txt\n*** End Patch") .assert() .failure() .stderr("Failed to delete file missing.txt\n"); Ok(()) } #[test] fn test_apply_patch_cli_rejects_empty_update_hunk() -> anyhow::Result<()> { let tmp = tempdir()?; apply_patch_command(tmp.path())? .arg("*** Begin Patch\n*** Update File: foo.txt\n*** End Patch") .assert() .failure() .stderr("Invalid patch hunk on line 2: Update file hunk for path 'foo.txt' is empty\n"); Ok(()) } #[test] fn test_apply_patch_cli_requires_existing_file_for_update() -> anyhow::Result<()> { let tmp = tempdir()?; apply_patch_command(tmp.path())? .arg("*** Begin Patch\n*** Update File: missing.txt\n@@\n-old\n+new\n*** End Patch") .assert() .failure() .stderr( "Failed to read file to update missing.txt: No such file or directory (os error 2)\n", ); Ok(()) } #[test] fn test_apply_patch_cli_move_overwrites_existing_destination() -> anyhow::Result<()> { let tmp = tempdir()?; let original_path = tmp.path().join("old/name.txt"); let destination = tmp.path().join("renamed/dir/name.txt"); fs::create_dir_all(original_path.parent().expect("parent should exist"))?; fs::create_dir_all(destination.parent().expect("parent should exist"))?; fs::write(&original_path, "from\n")?; fs::write(&destination, "existing\n")?; run_apply_patch_in_dir( tmp.path(), "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/dir/name.txt\n@@\n-from\n+new\n*** End Patch", )? .success() .stdout("Success. Updated the following files:\nM renamed/dir/name.txt\n"); assert!(!original_path.exists()); assert_eq!(fs::read_to_string(&destination)?, "new\n"); Ok(()) } #[test] fn test_apply_patch_cli_add_overwrites_existing_file() -> anyhow::Result<()> { let tmp = tempdir()?; let path = tmp.path().join("duplicate.txt"); fs::write(&path, "old content\n")?; run_apply_patch_in_dir( tmp.path(), "*** Begin Patch\n*** Add File: duplicate.txt\n+new content\n*** End Patch", )? .success() .stdout("Success. Updated the following files:\nA duplicate.txt\n"); assert_eq!(fs::read_to_string(&path)?, "new content\n"); Ok(()) } #[test] fn test_apply_patch_cli_delete_directory_fails() -> anyhow::Result<()> { let tmp = tempdir()?; fs::create_dir(tmp.path().join("dir"))?; apply_patch_command(tmp.path())? .arg("*** Begin Patch\n*** Delete File: dir\n*** End Patch") .assert() .failure() .stderr("Failed to delete file dir\n"); Ok(()) } #[test] fn test_apply_patch_cli_rejects_invalid_hunk_header() -> anyhow::Result<()> { let tmp = tempdir()?; apply_patch_command(tmp.path())? .arg("*** Begin Patch\n*** Frobnicate File: foo\n*** End Patch") .assert() .failure() .stderr("Invalid patch hunk on line 2: '*** Frobnicate File: foo' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'\n"); Ok(()) } #[test] fn test_apply_patch_cli_updates_file_appends_trailing_newline() -> anyhow::Result<()> { let tmp = tempdir()?; let target_path = tmp.path().join("no_newline.txt"); fs::write(&target_path, "no newline at end")?; run_apply_patch_in_dir( tmp.path(), "*** Begin Patch\n*** Update File: no_newline.txt\n@@\n-no newline at end\n+first line\n+second line\n*** End Patch", )? .success() .stdout("Success. Updated the following files:\nM no_newline.txt\n"); let contents = fs::read_to_string(&target_path)?; assert!(contents.ends_with('\n')); assert_eq!(contents, "first line\nsecond line\n"); Ok(()) } #[test] fn test_apply_patch_cli_failure_after_partial_success_leaves_changes() -> anyhow::Result<()> { let tmp = tempdir()?; let new_file = tmp.path().join("created.txt"); apply_patch_command(tmp.path())? .arg("*** Begin Patch\n*** Add File: created.txt\n+hello\n*** Update File: missing.txt\n@@\n-old\n+new\n*** End Patch") .assert() .failure() .stdout("") .stderr("Failed to read file to update missing.txt: No such file or directory (os error 2)\n"); assert_eq!(fs::read_to_string(&new_file)?, "hello\n"); Ok(()) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/file-search/src/lib.rs
codex-rs/file-search/src/lib.rs
use ignore::WalkBuilder; use ignore::overrides::OverrideBuilder; use nucleo_matcher::Matcher; use nucleo_matcher::Utf32Str; use nucleo_matcher::pattern::AtomKind; use nucleo_matcher::pattern::CaseMatching; use nucleo_matcher::pattern::Normalization; use nucleo_matcher::pattern::Pattern; use serde::Serialize; use std::cell::UnsafeCell; use std::cmp::Reverse; use std::collections::BinaryHeap; use std::num::NonZero; use std::path::Path; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use tokio::process::Command; mod cli; pub use cli::Cli; /// A single match result returned from the search. /// /// * `score` – Relevance score returned by `nucleo_matcher`. /// * `path` – Path to the matched file (relative to the search directory). /// * `indices` – Optional list of character indices that matched the query. /// These are only filled when the caller of [`run`] sets /// `compute_indices` to `true`. The indices vector follows the /// guidance from `nucleo_matcher::Pattern::indices`: they are /// unique and sorted in ascending order so that callers can use /// them directly for highlighting. #[derive(Debug, Clone, Serialize)] pub struct FileMatch { pub score: u32, pub path: String, #[serde(skip_serializing_if = "Option::is_none")] pub indices: Option<Vec<u32>>, // Sorted & deduplicated when present } /// Returns the final path component for a matched path, falling back to the full path. pub fn file_name_from_path(path: &str) -> String { Path::new(path) .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_else(|| path.to_string()) } #[derive(Debug)] pub struct FileSearchResults { pub matches: Vec<FileMatch>, pub total_match_count: usize, } pub trait Reporter { fn report_match(&self, file_match: &FileMatch); fn warn_matches_truncated(&self, total_match_count: usize, shown_match_count: usize); fn warn_no_search_pattern(&self, search_directory: &Path); } pub async fn run_main<T: Reporter>( Cli { pattern, limit, cwd, compute_indices, json: _, exclude, threads, }: Cli, reporter: T, ) -> anyhow::Result<()> { let search_directory = match cwd { Some(dir) => dir, None => std::env::current_dir()?, }; let pattern_text = match pattern { Some(pattern) => pattern, None => { reporter.warn_no_search_pattern(&search_directory); #[cfg(unix)] Command::new("ls") .arg("-al") .current_dir(search_directory) .stdout(std::process::Stdio::inherit()) .stderr(std::process::Stdio::inherit()) .status() .await?; #[cfg(windows)] { Command::new("cmd") .arg("/c") .arg(search_directory) .stdout(std::process::Stdio::inherit()) .stderr(std::process::Stdio::inherit()) .status() .await?; } return Ok(()); } }; let cancel_flag = Arc::new(AtomicBool::new(false)); let FileSearchResults { total_match_count, matches, } = run( &pattern_text, limit, &search_directory, exclude, threads, cancel_flag, compute_indices, true, )?; let match_count = matches.len(); let matches_truncated = total_match_count > match_count; for file_match in matches { reporter.report_match(&file_match); } if matches_truncated { reporter.warn_matches_truncated(total_match_count, match_count); } Ok(()) } /// The worker threads will periodically check `cancel_flag` to see if they /// should stop processing files. #[allow(clippy::too_many_arguments)] pub fn run( pattern_text: &str, limit: NonZero<usize>, search_directory: &Path, exclude: Vec<String>, threads: NonZero<usize>, cancel_flag: Arc<AtomicBool>, compute_indices: bool, respect_gitignore: bool, ) -> anyhow::Result<FileSearchResults> { let pattern = create_pattern(pattern_text); // Create one BestMatchesList per worker thread so that each worker can // operate independently. The results across threads will be merged when // the traversal is complete. let WorkerCount { num_walk_builder_threads, num_best_matches_lists, } = create_worker_count(threads); let best_matchers_per_worker: Vec<UnsafeCell<BestMatchesList>> = (0..num_best_matches_lists) .map(|_| { UnsafeCell::new(BestMatchesList::new( limit.get(), pattern.clone(), Matcher::new(nucleo_matcher::Config::DEFAULT), )) }) .collect(); // Use the same tree-walker library that ripgrep uses. We use it directly so // that we can leverage the parallelism it provides. let mut walk_builder = WalkBuilder::new(search_directory); walk_builder .threads(num_walk_builder_threads) // Allow hidden entries. .hidden(false) // Follow symlinks to search their contents. .follow_links(true) // Don't require git to be present to apply to apply git-related ignore rules. .require_git(false); if !respect_gitignore { walk_builder .git_ignore(false) .git_global(false) .git_exclude(false) .ignore(false) .parents(false); } if !exclude.is_empty() { let mut override_builder = OverrideBuilder::new(search_directory); for exclude in exclude { // The `!` prefix is used to indicate an exclude pattern. let exclude_pattern = format!("!{exclude}"); override_builder.add(&exclude_pattern)?; } let override_matcher = override_builder.build()?; walk_builder.overrides(override_matcher); } let walker = walk_builder.build_parallel(); // Each worker created by `WalkParallel::run()` will have its own // `BestMatchesList` to update. let index_counter = AtomicUsize::new(0); walker.run(|| { let index = index_counter.fetch_add(1, Ordering::Relaxed); let best_list_ptr = best_matchers_per_worker[index].get(); let best_list = unsafe { &mut *best_list_ptr }; // Each worker keeps a local counter so we only read the atomic flag // every N entries which is cheaper than checking on every file. const CHECK_INTERVAL: usize = 1024; let mut processed = 0; let cancel = cancel_flag.clone(); Box::new(move |entry| { if let Some(path) = get_file_path(&entry, search_directory) { best_list.insert(path); } processed += 1; if processed % CHECK_INTERVAL == 0 && cancel.load(Ordering::Relaxed) { ignore::WalkState::Quit } else { ignore::WalkState::Continue } }) }); fn get_file_path<'a>( entry_result: &'a Result<ignore::DirEntry, ignore::Error>, search_directory: &std::path::Path, ) -> Option<&'a str> { let entry = match entry_result { Ok(e) => e, Err(_) => return None, }; if entry.file_type().is_some_and(|ft| ft.is_dir()) { return None; } let path = entry.path(); match path.strip_prefix(search_directory) { Ok(rel_path) => rel_path.to_str(), Err(_) => None, } } // If the cancel flag is set, we return early with an empty result. if cancel_flag.load(Ordering::Relaxed) { return Ok(FileSearchResults { matches: Vec::new(), total_match_count: 0, }); } // Merge results across best_matchers_per_worker. let mut global_heap: BinaryHeap<Reverse<(u32, String)>> = BinaryHeap::new(); let mut total_match_count = 0; for best_list_cell in best_matchers_per_worker.iter() { let best_list = unsafe { &*best_list_cell.get() }; total_match_count += best_list.num_matches; for &Reverse((score, ref line)) in best_list.binary_heap.iter() { if global_heap.len() < limit.get() { global_heap.push(Reverse((score, line.clone()))); } else if let Some(min_element) = global_heap.peek() && score > min_element.0.0 { global_heap.pop(); global_heap.push(Reverse((score, line.clone()))); } } } let mut raw_matches: Vec<(u32, String)> = global_heap.into_iter().map(|r| r.0).collect(); sort_matches(&mut raw_matches); // Transform into `FileMatch`, optionally computing indices. let mut matcher = if compute_indices { Some(Matcher::new(nucleo_matcher::Config::DEFAULT)) } else { None }; let matches: Vec<FileMatch> = raw_matches .into_iter() .map(|(score, path)| { let indices = if compute_indices { let mut buf = Vec::<char>::new(); let haystack: Utf32Str<'_> = Utf32Str::new(&path, &mut buf); let mut idx_vec: Vec<u32> = Vec::new(); if let Some(ref mut m) = matcher { // Ignore the score returned from indices – we already have `score`. pattern.indices(haystack, m, &mut idx_vec); } idx_vec.sort_unstable(); idx_vec.dedup(); Some(idx_vec) } else { None }; FileMatch { score, path, indices, } }) .collect(); Ok(FileSearchResults { matches, total_match_count, }) } /// Sort matches in-place by descending score, then ascending path. fn sort_matches(matches: &mut [(u32, String)]) { matches.sort_by(cmp_by_score_desc_then_path_asc::<(u32, String), _, _>( |t| t.0, |t| t.1.as_str(), )); } /// Returns a comparator closure suitable for `slice.sort_by(...)` that orders /// items by descending score and then ascending path using the provided accessors. pub fn cmp_by_score_desc_then_path_asc<T, FScore, FPath>( score_of: FScore, path_of: FPath, ) -> impl FnMut(&T, &T) -> std::cmp::Ordering where FScore: Fn(&T) -> u32, FPath: Fn(&T) -> &str, { use std::cmp::Ordering; move |a, b| match score_of(b).cmp(&score_of(a)) { Ordering::Equal => path_of(a).cmp(path_of(b)), other => other, } } /// Maintains the `max_count` best matches for a given pattern. struct BestMatchesList { max_count: usize, num_matches: usize, pattern: Pattern, matcher: Matcher, binary_heap: BinaryHeap<Reverse<(u32, String)>>, /// Internal buffer for converting strings to UTF-32. utf32buf: Vec<char>, } impl BestMatchesList { fn new(max_count: usize, pattern: Pattern, matcher: Matcher) -> Self { Self { max_count, num_matches: 0, pattern, matcher, binary_heap: BinaryHeap::new(), utf32buf: Vec::<char>::new(), } } fn insert(&mut self, line: &str) { let haystack: Utf32Str<'_> = Utf32Str::new(line, &mut self.utf32buf); if let Some(score) = self.pattern.score(haystack, &mut self.matcher) { // In the tests below, we verify that score() returns None for a // non-match, so we can categorically increment the count here. self.num_matches += 1; if self.binary_heap.len() < self.max_count { self.binary_heap.push(Reverse((score, line.to_string()))); } else if let Some(min_element) = self.binary_heap.peek() && score > min_element.0.0 { self.binary_heap.pop(); self.binary_heap.push(Reverse((score, line.to_string()))); } } } } struct WorkerCount { num_walk_builder_threads: usize, num_best_matches_lists: usize, } fn create_worker_count(num_workers: NonZero<usize>) -> WorkerCount { // It appears that the number of times the function passed to // `WalkParallel::run()` is called is: the number of threads specified to // the builder PLUS ONE. // // In `WalkParallel::visit()`, the builder function gets called once here: // https://github.com/BurntSushi/ripgrep/blob/79cbe89deb1151e703f4d91b19af9cdcc128b765/crates/ignore/src/walk.rs#L1233 // // And then once for every worker here: // https://github.com/BurntSushi/ripgrep/blob/79cbe89deb1151e703f4d91b19af9cdcc128b765/crates/ignore/src/walk.rs#L1288 let num_walk_builder_threads = num_workers.get(); let num_best_matches_lists = num_walk_builder_threads + 1; WorkerCount { num_walk_builder_threads, num_best_matches_lists, } } fn create_pattern(pattern: &str) -> Pattern { Pattern::new( pattern, CaseMatching::Smart, Normalization::Smart, AtomKind::Fuzzy, ) } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; #[test] fn verify_score_is_none_for_non_match() { let mut utf32buf = Vec::<char>::new(); let line = "hello"; let mut matcher = Matcher::new(nucleo_matcher::Config::DEFAULT); let haystack: Utf32Str<'_> = Utf32Str::new(line, &mut utf32buf); let pattern = create_pattern("zzz"); let score = pattern.score(haystack, &mut matcher); assert_eq!(score, None); } #[test] fn tie_breakers_sort_by_path_when_scores_equal() { let mut matches = vec![ (100, "b_path".to_string()), (100, "a_path".to_string()), (90, "zzz".to_string()), ]; sort_matches(&mut matches); // Highest score first; ties broken alphabetically. let expected = vec![ (100, "a_path".to_string()), (100, "b_path".to_string()), (90, "zzz".to_string()), ]; assert_eq!(matches, expected); } #[test] fn file_name_from_path_uses_basename() { assert_eq!(file_name_from_path("foo/bar.txt"), "bar.txt"); } #[test] fn file_name_from_path_falls_back_to_full_path() { assert_eq!(file_name_from_path(""), ""); } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/file-search/src/cli.rs
codex-rs/file-search/src/cli.rs
use std::num::NonZero; use std::path::PathBuf; use clap::ArgAction; use clap::Parser; /// Fuzzy matches filenames under a directory. #[derive(Parser)] #[command(version)] pub struct Cli { /// Whether to output results in JSON format. #[clap(long, default_value = "false")] pub json: bool, /// Maximum number of results to return. #[clap(long, short = 'l', default_value = "64")] pub limit: NonZero<usize>, /// Directory to search. #[clap(long, short = 'C')] pub cwd: Option<PathBuf>, /// Include matching file indices in the output. #[arg(long, default_value = "false")] pub compute_indices: bool, // While it is common to default to the number of logical CPUs when creating // a thread pool, empirically, the I/O of the filetree traversal offers // limited parallelism and is the bottleneck, so using a smaller number of // threads is more efficient. (Empirically, using more than 2 threads doesn't seem to provide much benefit.) // /// Number of worker threads to use. #[clap(long, default_value = "2")] pub threads: NonZero<usize>, /// Exclude patterns #[arg(short, long, action = ArgAction::Append)] pub exclude: Vec<String>, /// Search pattern. pub pattern: Option<String>, }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/file-search/src/main.rs
codex-rs/file-search/src/main.rs
use std::io::IsTerminal; use std::path::Path; use clap::Parser; use codex_file_search::Cli; use codex_file_search::FileMatch; use codex_file_search::Reporter; use codex_file_search::run_main; use serde_json::json; #[tokio::main] async fn main() -> anyhow::Result<()> { let cli = Cli::parse(); let reporter = StdioReporter { write_output_as_json: cli.json, show_indices: cli.compute_indices && std::io::stdout().is_terminal(), }; run_main(cli, reporter).await?; Ok(()) } struct StdioReporter { write_output_as_json: bool, show_indices: bool, } impl Reporter for StdioReporter { fn report_match(&self, file_match: &FileMatch) { if self.write_output_as_json { println!("{}", serde_json::to_string(&file_match).unwrap()); } else if self.show_indices { let indices = file_match .indices .as_ref() .expect("--compute-indices was specified"); // `indices` is guaranteed to be sorted in ascending order. Instead // of calling `contains` for every character (which would be O(N^2) // in the worst-case), walk through the `indices` vector once while // iterating over the characters. let mut indices_iter = indices.iter().peekable(); for (i, c) in file_match.path.chars().enumerate() { match indices_iter.peek() { Some(next) if **next == i as u32 => { // ANSI escape code for bold: \x1b[1m ... \x1b[0m print!("\x1b[1m{c}\x1b[0m"); // advance the iterator since we've consumed this index indices_iter.next(); } _ => { print!("{c}"); } } } println!(); } else { println!("{}", file_match.path); } } fn warn_matches_truncated(&self, total_match_count: usize, shown_match_count: usize) { if self.write_output_as_json { let value = json!({"matches_truncated": true}); println!("{}", serde_json::to_string(&value).unwrap()); } else { eprintln!( "Warning: showing {shown_match_count} out of {total_match_count} results. Provide a more specific pattern or increase the --limit.", ); } } fn warn_no_search_pattern(&self, search_directory: &Path) { eprintln!( "No search pattern specified. Showing the contents of the current directory ({}):", search_directory.to_string_lossy() ); } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/stdio-to-uds/src/lib.rs
codex-rs/stdio-to-uds/src/lib.rs
#![deny(clippy::print_stdout)] use std::io; use std::io::Write; use std::net::Shutdown; use std::path::Path; use std::thread; use anyhow::Context; use anyhow::anyhow; #[cfg(unix)] use std::os::unix::net::UnixStream; #[cfg(windows)] use uds_windows::UnixStream; /// Connects to the Unix Domain Socket at `socket_path` and relays data between /// standard input/output and the socket. pub fn run(socket_path: &Path) -> anyhow::Result<()> { let mut stream = UnixStream::connect(socket_path) .with_context(|| format!("failed to connect to socket at {}", socket_path.display()))?; let mut reader = stream .try_clone() .context("failed to clone socket for reading")?; let stdout_thread = thread::spawn(move || -> io::Result<()> { let stdout = io::stdout(); let mut handle = stdout.lock(); io::copy(&mut reader, &mut handle)?; handle.flush()?; Ok(()) }); let stdin = io::stdin(); { let mut handle = stdin.lock(); io::copy(&mut handle, &mut stream).context("failed to copy data from stdin to socket")?; } stream .shutdown(Shutdown::Write) .context("failed to shutdown socket writer")?; let stdout_result = stdout_thread .join() .map_err(|_| anyhow!("thread panicked while copying socket data to stdout"))?; stdout_result.context("failed to copy data from socket to stdout")?; Ok(()) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/stdio-to-uds/src/main.rs
codex-rs/stdio-to-uds/src/main.rs
use std::env; use std::path::PathBuf; use std::process; fn main() -> anyhow::Result<()> { let mut args = env::args_os().skip(1); let Some(socket_path) = args.next() else { eprintln!("Usage: codex-stdio-to-uds <socket-path>"); process::exit(1); }; if args.next().is_some() { eprintln!("Expected exactly one argument: <socket-path>"); process::exit(1); } let socket_path = PathBuf::from(socket_path); codex_stdio_to_uds::run(&socket_path) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/stdio-to-uds/tests/stdio_to_uds.rs
codex-rs/stdio-to-uds/tests/stdio_to_uds.rs
use std::io::ErrorKind; use std::io::Read; use std::io::Write; use std::sync::mpsc; use std::thread; use std::time::Duration; use anyhow::Context; use assert_cmd::Command; use pretty_assertions::assert_eq; #[cfg(unix)] use std::os::unix::net::UnixListener; #[cfg(windows)] use uds_windows::UnixListener; #[test] fn pipes_stdin_and_stdout_through_socket() -> anyhow::Result<()> { let dir = tempfile::TempDir::new().context("failed to create temp dir")?; let socket_path = dir.path().join("socket"); let listener = match UnixListener::bind(&socket_path) { Ok(listener) => listener, Err(err) if err.kind() == ErrorKind::PermissionDenied => { eprintln!("skipping test: failed to bind unix socket: {err}"); return Ok(()); } Err(err) => { return Err(err).context("failed to bind test unix socket"); } }; let (tx, rx) = mpsc::channel(); let server_thread = thread::spawn(move || -> anyhow::Result<()> { let (mut connection, _) = listener .accept() .context("failed to accept test connection")?; let mut received = Vec::new(); connection .read_to_end(&mut received) .context("failed to read data from client")?; tx.send(received) .map_err(|_| anyhow::anyhow!("failed to send received bytes to test thread"))?; connection .write_all(b"response") .context("failed to write response to client")?; Ok(()) }); Command::new(codex_utils_cargo_bin::cargo_bin("codex-stdio-to-uds")?) .arg(&socket_path) .write_stdin("request") .assert() .success() .stdout("response"); let received = rx .recv_timeout(Duration::from_secs(1)) .context("server did not receive data in time")?; assert_eq!(received, b"request"); let server_result = server_thread .join() .map_err(|_| anyhow::anyhow!("server thread panicked"))?; server_result.context("server failed")?; Ok(()) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/config_types.rs
codex-rs/protocol/src/config_types.rs
use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use strum_macros::Display; use ts_rs::TS; /// A summary of the reasoning performed by the model. This can be useful for /// debugging and understanding the model's reasoning process. /// See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries #[derive( Debug, Serialize, Deserialize, Default, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum ReasoningSummary { #[default] Auto, Concise, Detailed, /// Option to disable reasoning summaries. None, } /// Controls output length/detail on GPT-5 models via the Responses API. /// Serialized with lowercase values to match the OpenAI API. #[derive( Hash, Debug, Serialize, Deserialize, Default, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum Verbosity { Low, #[default] Medium, High, } #[derive( Deserialize, Debug, Clone, Copy, PartialEq, Default, Serialize, Display, JsonSchema, TS, )] #[serde(rename_all = "kebab-case")] #[strum(serialize_all = "kebab-case")] pub enum SandboxMode { #[serde(rename = "read-only")] #[default] ReadOnly, #[serde(rename = "workspace-write")] WorkspaceWrite, #[serde(rename = "danger-full-access")] DangerFullAccess, } #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum ForcedLoginMethod { Chatgpt, Api, } /// Represents the trust level for a project directory. /// This determines the approval policy and sandbox mode applied. #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum TrustLevel { Trusted, Untrusted, }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/plan_tool.rs
codex-rs/protocol/src/plan_tool.rs
use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use ts_rs::TS; // Types for the TODO tool arguments matching codex-vscode/todo-mcp/src/main.rs #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, TS)] #[serde(rename_all = "snake_case")] pub enum StepStatus { Pending, InProgress, Completed, } #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, TS)] #[serde(deny_unknown_fields)] pub struct PlanItemArg { pub step: String, pub status: StepStatus, } #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, TS)] #[serde(deny_unknown_fields)] pub struct UpdatePlanArgs { #[serde(default)] pub explanation: Option<String>, pub plan: Vec<PlanItemArg>, }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/lib.rs
codex-rs/protocol/src/lib.rs
pub mod account; mod conversation_id; pub use conversation_id::ConversationId; pub mod approvals; pub mod config_types; pub mod custom_prompts; pub mod items; pub mod message_history; pub mod models; pub mod num_format; pub mod openai_models; pub mod parse_command; pub mod plan_tool; pub mod protocol; pub mod user_input;
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/num_format.rs
codex-rs/protocol/src/num_format.rs
use std::sync::OnceLock; use icu_decimal::DecimalFormatter; use icu_decimal::input::Decimal; use icu_decimal::options::DecimalFormatterOptions; use icu_locale_core::Locale; fn make_local_formatter() -> Option<DecimalFormatter> { let loc: Locale = sys_locale::get_locale()?.parse().ok()?; DecimalFormatter::try_new(loc.into(), DecimalFormatterOptions::default()).ok() } fn make_en_us_formatter() -> DecimalFormatter { #![allow(clippy::expect_used)] let loc: Locale = "en-US".parse().expect("en-US wasn't a valid locale"); DecimalFormatter::try_new(loc.into(), DecimalFormatterOptions::default()) .expect("en-US wasn't a valid locale") } fn formatter() -> &'static DecimalFormatter { static FORMATTER: OnceLock<DecimalFormatter> = OnceLock::new(); FORMATTER.get_or_init(|| make_local_formatter().unwrap_or_else(make_en_us_formatter)) } /// Format an i64 with locale-aware digit separators (e.g. "12345" -> "12,345" /// for en-US). pub fn format_with_separators(n: i64) -> String { formatter().format(&Decimal::from(n)).to_string() } fn format_si_suffix_with_formatter(n: i64, formatter: &DecimalFormatter) -> String { let n = n.max(0); if n < 1000 { return formatter.format(&Decimal::from(n)).to_string(); } // Format `n / scale` with the requested number of fractional digits. let format_scaled = |n: i64, scale: i64, frac_digits: u32| -> String { let value = n as f64 / scale as f64; let scaled: i64 = (value * 10f64.powi(frac_digits as i32)).round() as i64; let mut dec = Decimal::from(scaled); dec.multiply_pow10(-(frac_digits as i16)); formatter.format(&dec).to_string() }; const UNITS: [(i64, &str); 3] = [(1_000, "K"), (1_000_000, "M"), (1_000_000_000, "G")]; let f = n as f64; for &(scale, suffix) in &UNITS { if (100.0 * f / scale as f64).round() < 1000.0 { return format!("{}{}", format_scaled(n, scale, 2), suffix); } else if (10.0 * f / scale as f64).round() < 1000.0 { return format!("{}{}", format_scaled(n, scale, 1), suffix); } else if (f / scale as f64).round() < 1000.0 { return format!("{}{}", format_scaled(n, scale, 0), suffix); } } // Above 1000G, keep whole‑G precision. format!( "{}G", format_with_separators(((n as f64) / 1e9).round() as i64) ) } /// Format token counts to 3 significant figures, using base-10 SI suffixes. /// /// Examples (en-US): /// - 999 -> "999" /// - 1200 -> "1.20K" /// - 123456789 -> "123M" pub fn format_si_suffix(n: i64) -> String { format_si_suffix_with_formatter(n, formatter()) } #[cfg(test)] mod tests { use super::*; #[test] fn kmg() { let formatter = make_en_us_formatter(); let fmt = |n: i64| format_si_suffix_with_formatter(n, &formatter); assert_eq!(fmt(0), "0"); assert_eq!(fmt(999), "999"); assert_eq!(fmt(1_000), "1.00K"); assert_eq!(fmt(1_200), "1.20K"); assert_eq!(fmt(10_000), "10.0K"); assert_eq!(fmt(100_000), "100K"); assert_eq!(fmt(999_500), "1.00M"); assert_eq!(fmt(1_000_000), "1.00M"); assert_eq!(fmt(1_234_000), "1.23M"); assert_eq!(fmt(12_345_678), "12.3M"); assert_eq!(fmt(999_950_000), "1.00G"); assert_eq!(fmt(1_000_000_000), "1.00G"); assert_eq!(fmt(1_234_000_000), "1.23G"); // Above 1000G we keep whole‑G precision (no higher unit supported here). assert_eq!(fmt(1_234_000_000_000), "1,234G"); } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/custom_prompts.rs
codex-rs/protocol/src/custom_prompts.rs
use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use std::path::PathBuf; use ts_rs::TS; /// Base namespace for custom prompt slash commands (without trailing colon). /// Example usage forms constructed in code: /// - Command token after '/': `"{PROMPTS_CMD_PREFIX}:name"` /// - Full slash prefix: `"/{PROMPTS_CMD_PREFIX}:"` pub const PROMPTS_CMD_PREFIX: &str = "prompts"; #[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS)] pub struct CustomPrompt { pub name: String, pub path: PathBuf, pub content: String, pub description: Option<String>, pub argument_hint: Option<String>, }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/items.rs
codex-rs/protocol/src/items.rs
use crate::protocol::AgentMessageEvent; use crate::protocol::AgentReasoningEvent; use crate::protocol::AgentReasoningRawContentEvent; use crate::protocol::EventMsg; use crate::protocol::UserMessageEvent; use crate::protocol::WebSearchEndEvent; use crate::user_input::UserInput; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use ts_rs::TS; #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] #[serde(tag = "type")] #[ts(tag = "type")] pub enum TurnItem { UserMessage(UserMessageItem), AgentMessage(AgentMessageItem), Reasoning(ReasoningItem), WebSearch(WebSearchItem), } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct UserMessageItem { pub id: String, pub content: Vec<UserInput>, } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] #[serde(tag = "type")] #[ts(tag = "type")] pub enum AgentMessageContent { Text { text: String }, } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct AgentMessageItem { pub id: String, pub content: Vec<AgentMessageContent>, } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct ReasoningItem { pub id: String, pub summary_text: Vec<String>, #[serde(default)] pub raw_content: Vec<String>, } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct WebSearchItem { pub id: String, pub query: String, } impl UserMessageItem { pub fn new(content: &[UserInput]) -> Self { Self { id: uuid::Uuid::new_v4().to_string(), content: content.to_vec(), } } pub fn as_legacy_event(&self) -> EventMsg { EventMsg::UserMessage(UserMessageEvent { message: self.message(), images: Some(self.image_urls()), }) } pub fn message(&self) -> String { self.content .iter() .map(|c| match c { UserInput::Text { text } => text.clone(), _ => String::new(), }) .collect::<Vec<String>>() .join("") } pub fn image_urls(&self) -> Vec<String> { self.content .iter() .filter_map(|c| match c { UserInput::Image { image_url } => Some(image_url.clone()), _ => None, }) .collect() } } impl AgentMessageItem { pub fn new(content: &[AgentMessageContent]) -> Self { Self { id: uuid::Uuid::new_v4().to_string(), content: content.to_vec(), } } pub fn as_legacy_events(&self) -> Vec<EventMsg> { self.content .iter() .map(|c| match c { AgentMessageContent::Text { text } => EventMsg::AgentMessage(AgentMessageEvent { message: text.clone(), }), }) .collect() } } impl ReasoningItem { pub fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec<EventMsg> { let mut events = Vec::new(); for summary in &self.summary_text { events.push(EventMsg::AgentReasoning(AgentReasoningEvent { text: summary.clone(), })); } if show_raw_agent_reasoning { for entry in &self.raw_content { events.push(EventMsg::AgentReasoningRawContent( AgentReasoningRawContentEvent { text: entry.clone(), }, )); } } events } } impl WebSearchItem { pub fn as_legacy_event(&self) -> EventMsg { EventMsg::WebSearchEnd(WebSearchEndEvent { call_id: self.id.clone(), query: self.query.clone(), }) } } impl TurnItem { pub fn id(&self) -> String { match self { TurnItem::UserMessage(item) => item.id.clone(), TurnItem::AgentMessage(item) => item.id.clone(), TurnItem::Reasoning(item) => item.id.clone(), TurnItem::WebSearch(item) => item.id.clone(), } } pub fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec<EventMsg> { match self { TurnItem::UserMessage(item) => vec![item.as_legacy_event()], TurnItem::AgentMessage(item) => item.as_legacy_events(), TurnItem::WebSearch(item) => vec![item.as_legacy_event()], TurnItem::Reasoning(item) => item.as_legacy_events(show_raw_agent_reasoning), } } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/parse_command.rs
codex-rs/protocol/src/parse_command.rs
use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use std::path::PathBuf; use ts_rs::TS; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema, TS)] #[serde(tag = "type", rename_all = "snake_case")] pub enum ParsedCommand { Read { cmd: String, name: String, /// (Best effort) Path to the file being read by the command. When /// possible, this is an absolute path, though when relative, it should /// be resolved against the `cwd`` that will be used to run the command /// to derive the absolute path. path: PathBuf, }, ListFiles { cmd: String, path: Option<String>, }, Search { cmd: String, query: Option<String>, path: Option<String>, }, Unknown { cmd: String, }, }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/openai_models.rs
codex-rs/protocol/src/openai_models.rs
use std::collections::HashMap; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use strum::IntoEnumIterator; use strum_macros::Display; use strum_macros::EnumIter; use ts_rs::TS; use crate::config_types::Verbosity; /// See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning #[derive( Debug, Serialize, Deserialize, Default, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS, EnumIter, Hash, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum ReasoningEffort { None, Minimal, Low, #[default] Medium, High, XHigh, } /// A reasoning effort option that can be surfaced for a model. #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)] pub struct ReasoningEffortPreset { /// Effort level that the model supports. pub effort: ReasoningEffort, /// Short human description shown next to the effort in UIs. pub description: String, } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)] pub struct ModelUpgrade { pub id: String, pub reasoning_effort_mapping: Option<HashMap<ReasoningEffort, ReasoningEffort>>, pub migration_config_key: String, pub model_link: Option<String>, pub upgrade_copy: Option<String>, } /// Metadata describing a Codex-supported model. #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)] pub struct ModelPreset { /// Stable identifier for the preset. pub id: String, /// Model slug (e.g., "gpt-5"). pub model: String, /// Display name shown in UIs. pub display_name: String, /// Short human description shown in UIs. pub description: String, /// Reasoning effort applied when none is explicitly chosen. pub default_reasoning_effort: ReasoningEffort, /// Supported reasoning effort options. pub supported_reasoning_efforts: Vec<ReasoningEffortPreset>, /// Whether this is the default model for new users. pub is_default: bool, /// recommended upgrade model pub upgrade: Option<ModelUpgrade>, /// Whether this preset should appear in the picker UI. pub show_in_picker: bool, /// whether this model is supported in the api pub supported_in_api: bool, } /// Visibility of a model in the picker or APIs. #[derive( Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema, EnumIter, Display, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum ModelVisibility { List, Hide, None, } /// Shell execution capability for a model. #[derive( Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema, EnumIter, Display, Hash, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ConfigShellToolType { Default, Local, UnifiedExec, Disabled, ShellCommand, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, TS, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ApplyPatchToolType { Freeform, Function, } /// Server-provided truncation policy metadata for a model. #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum TruncationMode { Bytes, Tokens, } #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)] pub struct TruncationPolicyConfig { pub mode: TruncationMode, pub limit: i64, } impl TruncationPolicyConfig { pub const fn bytes(limit: i64) -> Self { Self { mode: TruncationMode::Bytes, limit, } } pub const fn tokens(limit: i64) -> Self { Self { mode: TruncationMode::Tokens, limit, } } } /// Semantic version triple encoded as an array in JSON (e.g. [0, 62, 0]). #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)] pub struct ClientVersion(pub i32, pub i32, pub i32); /// Model metadata returned by the Codex backend `/models` endpoint. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)] pub struct ModelInfo { pub slug: String, pub display_name: String, pub description: Option<String>, pub default_reasoning_level: ReasoningEffort, pub supported_reasoning_levels: Vec<ReasoningEffortPreset>, pub shell_type: ConfigShellToolType, pub visibility: ModelVisibility, pub supported_in_api: bool, pub priority: i32, pub upgrade: Option<String>, pub base_instructions: Option<String>, pub supports_reasoning_summaries: bool, pub support_verbosity: bool, pub default_verbosity: Option<Verbosity>, pub apply_patch_tool_type: Option<ApplyPatchToolType>, pub truncation_policy: TruncationPolicyConfig, pub supports_parallel_tool_calls: bool, pub context_window: Option<i64>, pub experimental_supported_tools: Vec<String>, } /// Response wrapper for `/models`. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema, Default)] pub struct ModelsResponse { pub models: Vec<ModelInfo>, } // convert ModelInfo to ModelPreset impl From<ModelInfo> for ModelPreset { fn from(info: ModelInfo) -> Self { ModelPreset { id: info.slug.clone(), model: info.slug.clone(), display_name: info.display_name, description: info.description.unwrap_or_default(), default_reasoning_effort: info.default_reasoning_level, supported_reasoning_efforts: info.supported_reasoning_levels.clone(), is_default: false, // default is the highest priority available model upgrade: info.upgrade.as_ref().map(|upgrade_slug| ModelUpgrade { id: upgrade_slug.clone(), reasoning_effort_mapping: reasoning_effort_mapping_from_presets( &info.supported_reasoning_levels, ), migration_config_key: info.slug.clone(), // todo(aibrahim): add the model link here. model_link: None, upgrade_copy: None, }), show_in_picker: info.visibility == ModelVisibility::List, supported_in_api: info.supported_in_api, } } } fn reasoning_effort_mapping_from_presets( presets: &[ReasoningEffortPreset], ) -> Option<HashMap<ReasoningEffort, ReasoningEffort>> { if presets.is_empty() { return None; } // Map every canonical effort to the closest supported effort for the new model. let supported: Vec<ReasoningEffort> = presets.iter().map(|p| p.effort).collect(); let mut map = HashMap::new(); for effort in ReasoningEffort::iter() { let nearest = nearest_effort(effort, &supported); map.insert(effort, nearest); } Some(map) } fn effort_rank(effort: ReasoningEffort) -> i32 { match effort { ReasoningEffort::None => 0, ReasoningEffort::Minimal => 1, ReasoningEffort::Low => 2, ReasoningEffort::Medium => 3, ReasoningEffort::High => 4, ReasoningEffort::XHigh => 5, } } fn nearest_effort(target: ReasoningEffort, supported: &[ReasoningEffort]) -> ReasoningEffort { let target_rank = effort_rank(target); supported .iter() .copied() .min_by_key(|candidate| (effort_rank(*candidate) - target_rank).abs()) .unwrap_or(target) }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/approvals.rs
codex-rs/protocol/src/approvals.rs
use std::collections::HashMap; use std::path::PathBuf; use crate::parse_command::ParsedCommand; use crate::protocol::FileChange; use mcp_types::RequestId; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use ts_rs::TS; /// Proposed execpolicy change to allow commands starting with this prefix. /// /// The `command` tokens form the prefix that would be added as an execpolicy /// `prefix_rule(..., decision="allow")`, letting the agent bypass approval for /// commands that start with this token sequence. #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] #[serde(transparent)] #[ts(type = "Array<string>")] pub struct ExecPolicyAmendment { pub command: Vec<String>, } impl ExecPolicyAmendment { pub fn new(command: Vec<String>) -> Self { Self { command } } pub fn command(&self) -> &[String] { &self.command } } impl From<Vec<String>> for ExecPolicyAmendment { fn from(command: Vec<String>) -> Self { Self { command } } } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct ExecApprovalRequestEvent { /// Identifier for the associated exec call, if available. pub call_id: String, /// Turn ID that this command belongs to. /// Uses `#[serde(default)]` for backwards compatibility. #[serde(default)] pub turn_id: String, /// The command to be executed. pub command: Vec<String>, /// The command's working directory. pub cwd: PathBuf, /// Optional human-readable reason for the approval (e.g. retry without sandbox). #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option<String>, /// Proposed execpolicy amendment that can be applied to allow future runs. #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub proposed_execpolicy_amendment: Option<ExecPolicyAmendment>, pub parsed_cmd: Vec<ParsedCommand>, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct ElicitationRequestEvent { pub server_name: String, pub id: RequestId, pub message: String, // TODO: MCP servers can request we fill out a schema for the elicitation. We don't support // this yet. // pub requested_schema: ElicitRequestParamsRequestedSchema, } #[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "lowercase")] pub enum ElicitationAction { Accept, Decline, Cancel, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct ApplyPatchApprovalRequestEvent { /// Responses API call id for the associated patch apply call, if available. pub call_id: String, /// Turn ID that this patch belongs to. /// Uses `#[serde(default)]` for backwards compatibility with older senders. #[serde(default)] pub turn_id: String, pub changes: HashMap<PathBuf, FileChange>, /// Optional explanatory reason (e.g. request for extra write access). #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option<String>, /// When set, the agent is asking the user to allow writes under this root for the remainder of the session. #[serde(skip_serializing_if = "Option::is_none")] pub grant_root: Option<PathBuf>, }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/message_history.rs
codex-rs/protocol/src/message_history.rs
use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use ts_rs::TS; #[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS)] pub struct HistoryEntry { pub conversation_id: String, pub ts: u64, pub text: String, }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/user_input.rs
codex-rs/protocol/src/user_input.rs
use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use ts_rs::TS; /// User input #[non_exhaustive] #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, TS, JsonSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum UserInput { Text { text: String, }, /// Pre‑encoded data: URI image. Image { image_url: String, }, /// Local image path provided by the user. This will be converted to an /// `Image` variant (base64 data URL) during request serialization. LocalImage { path: std::path::PathBuf, }, /// Skill selected by the user (name + path to SKILL.md). Skill { name: String, path: std::path::PathBuf, }, }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/protocol.rs
codex-rs/protocol/src/protocol.rs
//! Defines the protocol for a Codex session between a client and an agent. //! //! Uses a SQ (Submission Queue) / EQ (Event Queue) pattern to asynchronously communicate //! between user and agent. use std::collections::HashMap; use std::fmt; use std::path::Path; use std::path::PathBuf; use std::str::FromStr; use std::time::Duration; use crate::ConversationId; use crate::approvals::ElicitationRequestEvent; use crate::config_types::ReasoningSummary as ReasoningSummaryConfig; use crate::custom_prompts::CustomPrompt; use crate::items::TurnItem; use crate::message_history::HistoryEntry; use crate::models::ContentItem; use crate::models::ResponseItem; use crate::num_format::format_with_separators; use crate::openai_models::ReasoningEffort as ReasoningEffortConfig; use crate::parse_command::ParsedCommand; use crate::plan_tool::UpdatePlanArgs; use crate::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; use mcp_types::CallToolResult; use mcp_types::RequestId; use mcp_types::Resource as McpResource; use mcp_types::ResourceTemplate as McpResourceTemplate; use mcp_types::Tool as McpTool; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use serde_json::Value; use serde_with::serde_as; use strum_macros::Display; use tracing::error; use ts_rs::TS; pub use crate::approvals::ApplyPatchApprovalRequestEvent; pub use crate::approvals::ElicitationAction; pub use crate::approvals::ExecApprovalRequestEvent; pub use crate::approvals::ExecPolicyAmendment; /// Open/close tags for special user-input blocks. Used across crates to avoid /// duplicated hardcoded strings. pub const USER_INSTRUCTIONS_OPEN_TAG: &str = "<user_instructions>"; pub const USER_INSTRUCTIONS_CLOSE_TAG: &str = "</user_instructions>"; pub const ENVIRONMENT_CONTEXT_OPEN_TAG: &str = "<environment_context>"; pub const ENVIRONMENT_CONTEXT_CLOSE_TAG: &str = "</environment_context>"; pub const USER_MESSAGE_BEGIN: &str = "## My request for Codex:"; /// Submission Queue Entry - requests from user #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)] pub struct Submission { /// Unique id for this Submission to correlate with Events pub id: String, /// Payload pub op: Op, } /// Submission operation #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema)] #[serde(tag = "type", rename_all = "snake_case")] #[allow(clippy::large_enum_variant)] #[non_exhaustive] pub enum Op { /// Abort current task. /// This server sends [`EventMsg::TurnAborted`] in response. Interrupt, /// Input from the user UserInput { /// User input items, see `InputItem` items: Vec<UserInput>, }, /// Similar to [`Op::UserInput`], but contains additional context required /// for a turn of a [`crate::codex_conversation::CodexConversation`]. UserTurn { /// User input items, see `InputItem` items: Vec<UserInput>, /// `cwd` to use with the [`SandboxPolicy`] and potentially tool calls /// such as `local_shell`. cwd: PathBuf, /// Policy to use for command approval. approval_policy: AskForApproval, /// Policy to use for tool calls such as `local_shell`. sandbox_policy: SandboxPolicy, /// Must be a valid model slug for the [`crate::client::ModelClient`] /// associated with this conversation. model: String, /// Will only be honored if the model is configured to use reasoning. #[serde(skip_serializing_if = "Option::is_none")] effort: Option<ReasoningEffortConfig>, /// Will only be honored if the model is configured to use reasoning. summary: ReasoningSummaryConfig, // The JSON schema to use for the final assistant message final_output_json_schema: Option<Value>, }, /// Override parts of the persistent turn context for subsequent turns. /// /// All fields are optional; when omitted, the existing value is preserved. /// This does not enqueue any input – it only updates defaults used for /// future `UserInput` turns. OverrideTurnContext { /// Updated `cwd` for sandbox/tool calls. #[serde(skip_serializing_if = "Option::is_none")] cwd: Option<PathBuf>, /// Updated command approval policy. #[serde(skip_serializing_if = "Option::is_none")] approval_policy: Option<AskForApproval>, /// Updated sandbox policy for tool calls. #[serde(skip_serializing_if = "Option::is_none")] sandbox_policy: Option<SandboxPolicy>, /// Updated model slug. When set, the model family is derived /// automatically. #[serde(skip_serializing_if = "Option::is_none")] model: Option<String>, /// Updated reasoning effort (honored only for reasoning-capable models). /// /// Use `Some(Some(_))` to set a specific effort, `Some(None)` to clear /// the effort, or `None` to leave the existing value unchanged. #[serde(skip_serializing_if = "Option::is_none")] effort: Option<Option<ReasoningEffortConfig>>, /// Updated reasoning summary preference (honored only for reasoning-capable models). #[serde(skip_serializing_if = "Option::is_none")] summary: Option<ReasoningSummaryConfig>, }, /// Approve a command execution ExecApproval { /// The id of the submission we are approving id: String, /// The user's decision in response to the request. decision: ReviewDecision, }, /// Approve a code patch PatchApproval { /// The id of the submission we are approving id: String, /// The user's decision in response to the request. decision: ReviewDecision, }, /// Resolve an MCP elicitation request. ResolveElicitation { /// Name of the MCP server that issued the request. server_name: String, /// Request identifier from the MCP server. request_id: RequestId, /// User's decision for the request. decision: ElicitationAction, }, /// Append an entry to the persistent cross-session message history. /// /// Note the entry is not guaranteed to be logged if the user has /// history disabled, it matches the list of "sensitive" patterns, etc. AddToHistory { /// The message text to be stored. text: String, }, /// Request a single history entry identified by `log_id` + `offset`. GetHistoryEntryRequest { offset: usize, log_id: u64 }, /// Request the list of MCP tools available across all configured servers. /// Reply is delivered via `EventMsg::McpListToolsResponse`. ListMcpTools, /// Request the list of available custom prompts. ListCustomPrompts, /// Request the list of skills for the provided `cwd` values or the session default. ListSkills { /// Working directories to scope repo skills discovery. /// /// When empty, the session default working directory is used. #[serde(default, skip_serializing_if = "Vec::is_empty")] cwds: Vec<PathBuf>, /// When true, recompute skills even if a cached result exists. #[serde(default, skip_serializing_if = "std::ops::Not::not")] force_reload: bool, }, /// Request the agent to summarize the current conversation context. /// The agent will use its existing context (either conversation history or previous response id) /// to generate a summary which will be returned as an AgentMessage event. Compact, /// Request Codex to undo a turn (turn are stacked so it is the same effect as CMD + Z). Undo, /// Request a code review from the agent. Review { review_request: ReviewRequest }, /// Request to shut down codex instance. Shutdown, /// Execute a user-initiated one-off shell command (triggered by "!cmd"). /// /// The command string is executed using the user's default shell and may /// include shell syntax (pipes, redirects, etc.). Output is streamed via /// `ExecCommand*` events and the UI regains control upon `TaskComplete`. RunUserShellCommand { /// The raw command string after '!' command: String, }, /// Request the list of available models. ListModels, } /// Determines the conditions under which the user is consulted to approve /// running the command proposed by Codex. #[derive( Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, Display, JsonSchema, TS, )] #[serde(rename_all = "kebab-case")] #[strum(serialize_all = "kebab-case")] pub enum AskForApproval { /// Under this policy, only "known safe" commands—as determined by /// `is_safe_command()`—that **only read files** are auto‑approved. /// Everything else will ask the user to approve. #[serde(rename = "untrusted")] #[strum(serialize = "untrusted")] UnlessTrusted, /// *All* commands are auto‑approved, but they are expected to run inside a /// sandbox where network access is disabled and writes are confined to a /// specific set of paths. If the command fails, it will be escalated to /// the user to approve execution without a sandbox. OnFailure, /// The model decides when to ask the user for approval. #[default] OnRequest, /// Never ask the user to approve commands. Failures are immediately returned /// to the model, and never escalated to the user for approval. Never, } /// Represents whether outbound network access is available to the agent. #[derive( Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Display, Default, JsonSchema, TS, )] #[serde(rename_all = "kebab-case")] #[strum(serialize_all = "kebab-case")] pub enum NetworkAccess { #[default] Restricted, Enabled, } impl NetworkAccess { pub fn is_enabled(self) -> bool { matches!(self, NetworkAccess::Enabled) } } /// Determines execution restrictions for model shell commands. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Display, JsonSchema, TS)] #[strum(serialize_all = "kebab-case")] #[serde(tag = "type", rename_all = "kebab-case")] pub enum SandboxPolicy { /// No restrictions whatsoever. Use with caution. #[serde(rename = "danger-full-access")] DangerFullAccess, /// Read-only access to the entire file-system. #[serde(rename = "read-only")] ReadOnly, /// Indicates the process is already in an external sandbox. Allows full /// disk access while honoring the provided network setting. #[serde(rename = "external-sandbox")] ExternalSandbox { /// Whether the external sandbox permits outbound network traffic. #[serde(default)] network_access: NetworkAccess, }, /// Same as `ReadOnly` but additionally grants write access to the current /// working directory ("workspace"). #[serde(rename = "workspace-write")] WorkspaceWrite { /// Additional folders (beyond cwd and possibly TMPDIR) that should be /// writable from within the sandbox. #[serde(default, skip_serializing_if = "Vec::is_empty")] writable_roots: Vec<AbsolutePathBuf>, /// When set to `true`, outbound network access is allowed. `false` by /// default. #[serde(default)] network_access: bool, /// When set to `true`, will NOT include the per-user `TMPDIR` /// environment variable among the default writable roots. Defaults to /// `false`. #[serde(default)] exclude_tmpdir_env_var: bool, /// When set to `true`, will NOT include the `/tmp` among the default /// writable roots on UNIX. Defaults to `false`. #[serde(default)] exclude_slash_tmp: bool, }, } /// A writable root path accompanied by a list of subpaths that should remain /// read‑only even when the root is writable. This is primarily used to ensure /// that folders containing files that could be modified to escalate the /// privileges of the agent (e.g. `.codex`, `.git`, notably `.git/hooks`) under /// a writable root are not modified by the agent. #[derive(Debug, Clone, PartialEq, Eq, JsonSchema)] pub struct WritableRoot { pub root: AbsolutePathBuf, /// By construction, these subpaths are all under `root`. pub read_only_subpaths: Vec<AbsolutePathBuf>, } impl WritableRoot { pub fn is_path_writable(&self, path: &Path) -> bool { // Check if the path is under the root. if !path.starts_with(&self.root) { return false; } // Check if the path is under any of the read-only subpaths. for subpath in &self.read_only_subpaths { if path.starts_with(subpath) { return false; } } true } } impl FromStr for SandboxPolicy { type Err = serde_json::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { serde_json::from_str(s) } } impl SandboxPolicy { /// Returns a policy with read-only disk access and no network. pub fn new_read_only_policy() -> Self { SandboxPolicy::ReadOnly } /// Returns a policy that can read the entire disk, but can only write to /// the current working directory and the per-user tmp dir on macOS. It does /// not allow network access. pub fn new_workspace_write_policy() -> Self { SandboxPolicy::WorkspaceWrite { writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, } } /// Always returns `true`; restricting read access is not supported. pub fn has_full_disk_read_access(&self) -> bool { true } pub fn has_full_disk_write_access(&self) -> bool { match self { SandboxPolicy::DangerFullAccess => true, SandboxPolicy::ExternalSandbox { .. } => true, SandboxPolicy::ReadOnly => false, SandboxPolicy::WorkspaceWrite { .. } => false, } } pub fn has_full_network_access(&self) -> bool { match self { SandboxPolicy::DangerFullAccess => true, SandboxPolicy::ExternalSandbox { network_access } => network_access.is_enabled(), SandboxPolicy::ReadOnly => false, SandboxPolicy::WorkspaceWrite { network_access, .. } => *network_access, } } /// Returns the list of writable roots (tailored to the current working /// directory) together with subpaths that should remain read‑only under /// each writable root. pub fn get_writable_roots_with_cwd(&self, cwd: &Path) -> Vec<WritableRoot> { match self { SandboxPolicy::DangerFullAccess => Vec::new(), SandboxPolicy::ExternalSandbox { .. } => Vec::new(), SandboxPolicy::ReadOnly => Vec::new(), SandboxPolicy::WorkspaceWrite { writable_roots, exclude_tmpdir_env_var, exclude_slash_tmp, network_access: _, } => { // Start from explicitly configured writable roots. let mut roots: Vec<AbsolutePathBuf> = writable_roots.clone(); // Always include defaults: cwd, /tmp (if present on Unix), and // on macOS, the per-user TMPDIR unless explicitly excluded. // TODO(mbolin): cwd param should be AbsolutePathBuf. let cwd_absolute = AbsolutePathBuf::from_absolute_path(cwd); match cwd_absolute { Ok(cwd) => { roots.push(cwd); } Err(e) => { error!( "Ignoring invalid cwd {:?} for sandbox writable root: {}", cwd, e ); } } // Include /tmp on Unix unless explicitly excluded. if cfg!(unix) && !exclude_slash_tmp { #[allow(clippy::expect_used)] let slash_tmp = AbsolutePathBuf::from_absolute_path("/tmp").expect("/tmp is absolute"); if slash_tmp.as_path().is_dir() { roots.push(slash_tmp); } } // Include $TMPDIR unless explicitly excluded. On macOS, TMPDIR // is per-user, so writes to TMPDIR should not be readable by // other users on the system. // // By comparison, TMPDIR is not guaranteed to be defined on // Linux or Windows, but supporting it here gives users a way to // provide the model with their own temporary directory without // having to hardcode it in the config. if !exclude_tmpdir_env_var && let Some(tmpdir) = std::env::var_os("TMPDIR") && !tmpdir.is_empty() { match AbsolutePathBuf::from_absolute_path(PathBuf::from(&tmpdir)) { Ok(tmpdir_path) => { roots.push(tmpdir_path); } Err(e) => { error!( "Ignoring invalid TMPDIR value {tmpdir:?} for sandbox writable root: {e}", ); } } } // For each root, compute subpaths that should remain read-only. roots .into_iter() .map(|writable_root| { let mut subpaths = Vec::new(); #[allow(clippy::expect_used)] let top_level_git = writable_root .join(".git") .expect(".git is a valid relative path"); if top_level_git.as_path().is_dir() { subpaths.push(top_level_git); } #[allow(clippy::expect_used)] let top_level_codex = writable_root .join(".codex") .expect(".codex is a valid relative path"); if top_level_codex.as_path().is_dir() { subpaths.push(top_level_codex); } WritableRoot { root: writable_root, read_only_subpaths: subpaths, } }) .collect() } } } } /// Event Queue Entry - events from agent #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Event { /// Submission `id` that this event is correlated with. pub id: String, /// Payload pub msg: EventMsg, } /// Response event from the agent /// NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen. #[derive(Debug, Clone, Deserialize, Serialize, Display, JsonSchema, TS)] #[serde(tag = "type", rename_all = "snake_case")] #[ts(tag = "type")] #[strum(serialize_all = "snake_case")] pub enum EventMsg { /// Error while executing a submission Error(ErrorEvent), /// Warning issued while processing a submission. Unlike `Error`, this /// indicates the task continued but the user should still be notified. Warning(WarningEvent), /// Conversation history was compacted (either automatically or manually). ContextCompacted(ContextCompactedEvent), /// Agent has started a task TaskStarted(TaskStartedEvent), /// Agent has completed all actions TaskComplete(TaskCompleteEvent), /// Usage update for the current session, including totals and last turn. /// Optional means unknown — UIs should not display when `None`. TokenCount(TokenCountEvent), /// Agent text output message AgentMessage(AgentMessageEvent), /// User/system input message (what was sent to the model) UserMessage(UserMessageEvent), /// Agent text output delta message AgentMessageDelta(AgentMessageDeltaEvent), /// Reasoning event from agent. AgentReasoning(AgentReasoningEvent), /// Agent reasoning delta event from agent. AgentReasoningDelta(AgentReasoningDeltaEvent), /// Raw chain-of-thought from agent. AgentReasoningRawContent(AgentReasoningRawContentEvent), /// Agent reasoning content delta event from agent. AgentReasoningRawContentDelta(AgentReasoningRawContentDeltaEvent), /// Signaled when the model begins a new reasoning summary section (e.g., a new titled block). AgentReasoningSectionBreak(AgentReasoningSectionBreakEvent), /// Ack the client's configure message. SessionConfigured(SessionConfiguredEvent), /// Incremental MCP startup progress updates. McpStartupUpdate(McpStartupUpdateEvent), /// Aggregate MCP startup completion summary. McpStartupComplete(McpStartupCompleteEvent), McpToolCallBegin(McpToolCallBeginEvent), McpToolCallEnd(McpToolCallEndEvent), WebSearchBegin(WebSearchBeginEvent), WebSearchEnd(WebSearchEndEvent), /// Notification that the server is about to execute a command. ExecCommandBegin(ExecCommandBeginEvent), /// Incremental chunk of output from a running command. ExecCommandOutputDelta(ExecCommandOutputDeltaEvent), /// Terminal interaction for an in-progress command (stdin sent and stdout observed). TerminalInteraction(TerminalInteractionEvent), ExecCommandEnd(ExecCommandEndEvent), /// Notification that the agent attached a local image via the view_image tool. ViewImageToolCall(ViewImageToolCallEvent), ExecApprovalRequest(ExecApprovalRequestEvent), ElicitationRequest(ElicitationRequestEvent), ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent), /// Notification advising the user that something they are using has been /// deprecated and should be phased out. DeprecationNotice(DeprecationNoticeEvent), BackgroundEvent(BackgroundEventEvent), UndoStarted(UndoStartedEvent), UndoCompleted(UndoCompletedEvent), /// Notification that a model stream experienced an error or disconnect /// and the system is handling it (e.g., retrying with backoff). StreamError(StreamErrorEvent), /// Notification that the agent is about to apply a code patch. Mirrors /// `ExecCommandBegin` so front‑ends can show progress indicators. PatchApplyBegin(PatchApplyBeginEvent), /// Notification that a patch application has finished. PatchApplyEnd(PatchApplyEndEvent), TurnDiff(TurnDiffEvent), /// Response to GetHistoryEntryRequest. GetHistoryEntryResponse(GetHistoryEntryResponseEvent), /// List of MCP tools available to the agent. McpListToolsResponse(McpListToolsResponseEvent), /// List of custom prompts available to the agent. ListCustomPromptsResponse(ListCustomPromptsResponseEvent), /// List of skills available to the agent. ListSkillsResponse(ListSkillsResponseEvent), /// Notification that skill data may have been updated and clients may want to reload. SkillsUpdateAvailable, PlanUpdate(UpdatePlanArgs), TurnAborted(TurnAbortedEvent), /// Notification that the agent is shutting down. ShutdownComplete, /// Entered review mode. EnteredReviewMode(ReviewRequest), /// Exited review mode with an optional final result to apply. ExitedReviewMode(ExitedReviewModeEvent), RawResponseItem(RawResponseItemEvent), ItemStarted(ItemStartedEvent), ItemCompleted(ItemCompletedEvent), AgentMessageContentDelta(AgentMessageContentDeltaEvent), ReasoningContentDelta(ReasoningContentDeltaEvent), ReasoningRawContentDelta(ReasoningRawContentDeltaEvent), } /// Codex errors that we expose to clients. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "snake_case")] #[ts(rename_all = "snake_case")] pub enum CodexErrorInfo { ContextWindowExceeded, UsageLimitExceeded, HttpConnectionFailed { http_status_code: Option<u16>, }, /// Failed to connect to the response SSE stream. ResponseStreamConnectionFailed { http_status_code: Option<u16>, }, InternalServerError, Unauthorized, BadRequest, SandboxError, /// The response SSE stream disconnected in the middle of a turnbefore completion. ResponseStreamDisconnected { http_status_code: Option<u16>, }, /// Reached the retry limit for responses. ResponseTooManyFailedAttempts { http_status_code: Option<u16>, }, Other, } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct RawResponseItemEvent { pub item: ResponseItem, } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct ItemStartedEvent { pub thread_id: ConversationId, pub turn_id: String, pub item: TurnItem, } impl HasLegacyEvent for ItemStartedEvent { fn as_legacy_events(&self, _: bool) -> Vec<EventMsg> { match &self.item { TurnItem::WebSearch(item) => vec![EventMsg::WebSearchBegin(WebSearchBeginEvent { call_id: item.id.clone(), })], _ => Vec::new(), } } } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct ItemCompletedEvent { pub thread_id: ConversationId, pub turn_id: String, pub item: TurnItem, } pub trait HasLegacyEvent { fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec<EventMsg>; } impl HasLegacyEvent for ItemCompletedEvent { fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec<EventMsg> { self.item.as_legacy_events(show_raw_agent_reasoning) } } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct AgentMessageContentDeltaEvent { pub thread_id: String, pub turn_id: String, pub item_id: String, pub delta: String, } impl HasLegacyEvent for AgentMessageContentDeltaEvent { fn as_legacy_events(&self, _: bool) -> Vec<EventMsg> { vec![EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { delta: self.delta.clone(), })] } } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct ReasoningContentDeltaEvent { pub thread_id: String, pub turn_id: String, pub item_id: String, pub delta: String, // load with default value so it's backward compatible with the old format. #[serde(default)] pub summary_index: i64, } impl HasLegacyEvent for ReasoningContentDeltaEvent { fn as_legacy_events(&self, _: bool) -> Vec<EventMsg> { vec![EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent { delta: self.delta.clone(), })] } } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct ReasoningRawContentDeltaEvent { pub thread_id: String, pub turn_id: String, pub item_id: String, pub delta: String, // load with default value so it's backward compatible with the old format. #[serde(default)] pub content_index: i64, } impl HasLegacyEvent for ReasoningRawContentDeltaEvent { fn as_legacy_events(&self, _: bool) -> Vec<EventMsg> { vec![EventMsg::AgentReasoningRawContentDelta( AgentReasoningRawContentDeltaEvent { delta: self.delta.clone(), }, )] } } impl HasLegacyEvent for EventMsg { fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec<EventMsg> { match self { EventMsg::ItemCompleted(event) => event.as_legacy_events(show_raw_agent_reasoning), EventMsg::AgentMessageContentDelta(event) => { event.as_legacy_events(show_raw_agent_reasoning) } EventMsg::ReasoningContentDelta(event) => { event.as_legacy_events(show_raw_agent_reasoning) } EventMsg::ReasoningRawContentDelta(event) => { event.as_legacy_events(show_raw_agent_reasoning) } _ => Vec::new(), } } } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct ExitedReviewModeEvent { pub review_output: Option<ReviewOutputEvent>, } // Individual event payload types matching each `EventMsg` variant. #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct ErrorEvent { pub message: String, #[serde(default)] pub codex_error_info: Option<CodexErrorInfo>, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct WarningEvent { pub message: String, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct ContextCompactedEvent; #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct TaskCompleteEvent { pub last_agent_message: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct TaskStartedEvent { pub model_context_window: Option<i64>, } #[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq, Eq, JsonSchema, TS)] pub struct TokenUsage { #[ts(type = "number")] pub input_tokens: i64, #[ts(type = "number")] pub cached_input_tokens: i64, #[ts(type = "number")] pub output_tokens: i64, #[ts(type = "number")] pub reasoning_output_tokens: i64, #[ts(type = "number")] pub total_tokens: i64, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] pub struct TokenUsageInfo { pub total_token_usage: TokenUsage, pub last_token_usage: TokenUsage, #[ts(type = "number | null")] pub model_context_window: Option<i64>, } impl TokenUsageInfo { pub fn new_or_append( info: &Option<TokenUsageInfo>, last: &Option<TokenUsage>, model_context_window: Option<i64>, ) -> Option<Self> { if info.is_none() && last.is_none() { return None; } let mut info = match info { Some(info) => info.clone(), None => Self { total_token_usage: TokenUsage::default(), last_token_usage: TokenUsage::default(), model_context_window, }, }; if let Some(last) = last { info.append_last_usage(last); } Some(info) } pub fn append_last_usage(&mut self, last: &TokenUsage) { self.total_token_usage.add_assign(last); self.last_token_usage = last.clone(); } pub fn fill_to_context_window(&mut self, context_window: i64) { let previous_total = self.total_token_usage.total_tokens; let delta = (context_window - previous_total).max(0); self.model_context_window = Some(context_window); self.total_token_usage = TokenUsage { total_tokens: context_window, ..TokenUsage::default() }; self.last_token_usage = TokenUsage { total_tokens: delta, ..TokenUsage::default() }; } pub fn full_context_window(context_window: i64) -> Self { let mut info = Self { total_token_usage: TokenUsage::default(), last_token_usage: TokenUsage::default(), model_context_window: Some(context_window), }; info.fill_to_context_window(context_window); info } } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct TokenCountEvent { pub info: Option<TokenUsageInfo>, pub rate_limits: Option<RateLimitSnapshot>, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct RateLimitSnapshot { pub primary: Option<RateLimitWindow>, pub secondary: Option<RateLimitWindow>, pub credits: Option<CreditsSnapshot>, pub plan_type: Option<crate::account::PlanType>, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct RateLimitWindow { /// Percentage (0-100) of the window that has been consumed. pub used_percent: f64, /// Rolling window duration, in minutes. #[ts(type = "number | null")] pub window_minutes: Option<i64>, /// Unix timestamp (seconds since epoch) when the window resets. #[ts(type = "number | null")] pub resets_at: Option<i64>, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
true
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/conversation_id.rs
codex-rs/protocol/src/conversation_id.rs
use std::fmt::Display; use schemars::JsonSchema; use schemars::r#gen::SchemaGenerator; use schemars::schema::Schema; use serde::Deserialize; use serde::Serialize; use ts_rs::TS; use uuid::Uuid; #[derive(Debug, Clone, Copy, PartialEq, Eq, TS, Hash)] #[ts(type = "string")] pub struct ConversationId { uuid: Uuid, } impl ConversationId { pub fn new() -> Self { Self { uuid: Uuid::now_v7(), } } pub fn from_string(s: &str) -> Result<Self, uuid::Error> { Ok(Self { uuid: Uuid::parse_str(s)?, }) } } impl Default for ConversationId { fn default() -> Self { Self::new() } } impl Display for ConversationId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.uuid) } } impl Serialize for ConversationId { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.collect_str(&self.uuid) } } impl<'de> Deserialize<'de> for ConversationId { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let value = String::deserialize(deserializer)?; let uuid = Uuid::parse_str(&value).map_err(serde::de::Error::custom)?; Ok(Self { uuid }) } } impl JsonSchema for ConversationId { fn schema_name() -> String { "ConversationId".to_string() } fn json_schema(generator: &mut SchemaGenerator) -> Schema { <String>::json_schema(generator) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_conversation_id_default_is_not_zeroes() { let id = ConversationId::default(); assert_ne!(id.uuid, Uuid::nil()); } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/models.rs
codex-rs/protocol/src/models.rs
use std::collections::HashMap; use codex_utils_image::load_and_resize_to_fit; use mcp_types::CallToolResult; use mcp_types::ContentBlock; use serde::Deserialize; use serde::Deserializer; use serde::Serialize; use serde::ser::Serializer; use ts_rs::TS; use crate::user_input::UserInput; use codex_git::GhostCommit; use codex_utils_image::error::ImageProcessingError; use schemars::JsonSchema; /// Controls whether a command should use the session sandbox or bypass it. #[derive( Debug, Clone, Copy, Default, Eq, Hash, PartialEq, Serialize, Deserialize, JsonSchema, TS, )] #[serde(rename_all = "snake_case")] pub enum SandboxPermissions { /// Run with the configured sandbox #[default] UseDefault, /// Request to run outside the sandbox RequireEscalated, } impl SandboxPermissions { pub fn requires_escalated_permissions(self) -> bool { matches!(self, SandboxPermissions::RequireEscalated) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "snake_case")] pub enum ResponseInputItem { Message { role: String, content: Vec<ContentItem>, }, FunctionCallOutput { call_id: String, output: FunctionCallOutputPayload, }, McpToolCallOutput { call_id: String, result: Result<CallToolResult, String>, }, CustomToolCallOutput { call_id: String, output: String, }, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "snake_case")] pub enum ContentItem { InputText { text: String }, InputImage { image_url: String }, OutputText { text: String }, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "snake_case")] pub enum ResponseItem { Message { #[serde(default, skip_serializing)] #[ts(skip)] id: Option<String>, role: String, content: Vec<ContentItem>, }, Reasoning { #[serde(default, skip_serializing)] #[ts(skip)] id: String, summary: Vec<ReasoningItemReasoningSummary>, #[serde(default, skip_serializing_if = "should_serialize_reasoning_content")] #[ts(optional)] content: Option<Vec<ReasoningItemContent>>, encrypted_content: Option<String>, }, LocalShellCall { /// Set when using the chat completions API. #[serde(default, skip_serializing)] #[ts(skip)] id: Option<String>, /// Set when using the Responses API. call_id: Option<String>, status: LocalShellStatus, action: LocalShellAction, }, FunctionCall { #[serde(default, skip_serializing)] #[ts(skip)] id: Option<String>, name: String, // The Responses API returns the function call arguments as a *string* that contains // JSON, not as an already‑parsed object. We keep it as a raw string here and let // Session::handle_function_call parse it into a Value. This exactly matches the // Chat Completions + Responses API behavior. arguments: String, call_id: String, }, // NOTE: The input schema for `function_call_output` objects that clients send to the // OpenAI /v1/responses endpoint is NOT the same shape as the objects the server returns on the // SSE stream. When *sending* we must wrap the string output inside an object that includes a // required `success` boolean. To ensure we serialize exactly the expected shape we introduce // a dedicated payload struct and flatten it here. FunctionCallOutput { call_id: String, output: FunctionCallOutputPayload, }, CustomToolCall { #[serde(default, skip_serializing)] #[ts(skip)] id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] status: Option<String>, call_id: String, name: String, input: String, }, CustomToolCallOutput { call_id: String, output: String, }, // Emitted by the Responses API when the agent triggers a web search. // Example payload (from SSE `response.output_item.done`): // { // "id":"ws_...", // "type":"web_search_call", // "status":"completed", // "action": {"type":"search","query":"weather: San Francisco, CA"} // } WebSearchCall { #[serde(default, skip_serializing)] #[ts(skip)] id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] status: Option<String>, action: WebSearchAction, }, // Generated by the harness but considered exactly as a model response. GhostSnapshot { ghost_commit: GhostCommit, }, #[serde(alias = "compaction_summary")] Compaction { encrypted_content: String, }, #[serde(other)] Other, } fn should_serialize_reasoning_content(content: &Option<Vec<ReasoningItemContent>>) -> bool { match content { Some(content) => !content .iter() .any(|c| matches!(c, ReasoningItemContent::ReasoningText { .. })), None => false, } } fn local_image_error_placeholder( path: &std::path::Path, error: impl std::fmt::Display, ) -> ContentItem { ContentItem::InputText { text: format!( "Codex could not read the local image at `{}`: {}", path.display(), error ), } } fn invalid_image_error_placeholder( path: &std::path::Path, error: impl std::fmt::Display, ) -> ContentItem { ContentItem::InputText { text: format!( "Image located at `{}` is invalid: {}", path.display(), error ), } } fn unsupported_image_error_placeholder(path: &std::path::Path, mime: &str) -> ContentItem { ContentItem::InputText { text: format!( "Codex cannot attach image at `{}`: unsupported image format `{}`.", path.display(), mime ), } } impl From<ResponseInputItem> for ResponseItem { fn from(item: ResponseInputItem) -> Self { match item { ResponseInputItem::Message { role, content } => Self::Message { role, content, id: None, }, ResponseInputItem::FunctionCallOutput { call_id, output } => { Self::FunctionCallOutput { call_id, output } } ResponseInputItem::McpToolCallOutput { call_id, result } => { let output = match result { Ok(result) => FunctionCallOutputPayload::from(&result), Err(tool_call_err) => FunctionCallOutputPayload { content: format!("err: {tool_call_err:?}"), success: Some(false), ..Default::default() }, }; Self::FunctionCallOutput { call_id, output } } ResponseInputItem::CustomToolCallOutput { call_id, output } => { Self::CustomToolCallOutput { call_id, output } } } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] #[serde(rename_all = "snake_case")] pub enum LocalShellStatus { Completed, InProgress, Incomplete, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "snake_case")] pub enum LocalShellAction { Exec(LocalShellExecAction), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] pub struct LocalShellExecAction { pub command: Vec<String>, pub timeout_ms: Option<u64>, pub working_directory: Option<String>, pub env: Option<HashMap<String, String>>, pub user: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "snake_case")] pub enum WebSearchAction { Search { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] query: Option<String>, }, OpenPage { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] url: Option<String>, }, FindInPage { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pattern: Option<String>, }, #[serde(other)] Other, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "snake_case")] pub enum ReasoningItemReasoningSummary { SummaryText { text: String }, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "snake_case")] pub enum ReasoningItemContent { ReasoningText { text: String }, Text { text: String }, } impl From<Vec<UserInput>> for ResponseInputItem { fn from(items: Vec<UserInput>) -> Self { Self::Message { role: "user".to_string(), content: items .into_iter() .filter_map(|c| match c { UserInput::Text { text } => Some(ContentItem::InputText { text }), UserInput::Image { image_url } => Some(ContentItem::InputImage { image_url }), UserInput::LocalImage { path } => match load_and_resize_to_fit(&path) { Ok(image) => Some(ContentItem::InputImage { image_url: image.into_data_url(), }), Err(err) => { if matches!(&err, ImageProcessingError::Read { .. }) { Some(local_image_error_placeholder(&path, &err)) } else if err.is_invalid_image() { Some(invalid_image_error_placeholder(&path, &err)) } else { let Some(mime_guess) = mime_guess::from_path(&path).first() else { return Some(local_image_error_placeholder( &path, "unsupported MIME type (unknown)", )); }; let mime = mime_guess.essence_str().to_owned(); if !mime.starts_with("image/") { return Some(local_image_error_placeholder( &path, format!("unsupported MIME type `{mime}`"), )); } Some(unsupported_image_error_placeholder(&path, &mime)) } } }, UserInput::Skill { .. } => None, // Skill bodies are injected later in core }) .collect::<Vec<ContentItem>>(), } } } /// If the `name` of a `ResponseItem::FunctionCall` is either `container.exec` /// or `shell`, the `arguments` field should deserialize to this struct. #[derive(Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] pub struct ShellToolCallParams { pub command: Vec<String>, pub workdir: Option<String>, /// This is the maximum time in milliseconds that the command is allowed to run. #[serde(alias = "timeout")] pub timeout_ms: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub sandbox_permissions: Option<SandboxPermissions>, #[serde(skip_serializing_if = "Option::is_none")] pub justification: Option<String>, } /// If the `name` of a `ResponseItem::FunctionCall` is `shell_command`, the /// `arguments` field should deserialize to this struct. #[derive(Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] pub struct ShellCommandToolCallParams { pub command: String, pub workdir: Option<String>, /// Whether to run the shell with login shell semantics #[serde(skip_serializing_if = "Option::is_none")] pub login: Option<bool>, /// This is the maximum time in milliseconds that the command is allowed to run. #[serde(alias = "timeout")] pub timeout_ms: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub sandbox_permissions: Option<SandboxPermissions>, #[serde(skip_serializing_if = "Option::is_none")] pub justification: Option<String>, } /// Responses API compatible content items that can be returned by a tool call. /// This is a subset of ContentItem with the types we support as function call outputs. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "snake_case")] pub enum FunctionCallOutputContentItem { // Do not rename, these are serialized and used directly in the responses API. InputText { text: String }, // Do not rename, these are serialized and used directly in the responses API. InputImage { image_url: String }, } /// The payload we send back to OpenAI when reporting a tool call result. /// /// `content` preserves the historical plain-string payload so downstream /// integrations (tests, logging, etc.) can keep treating tool output as /// `String`. When an MCP server returns richer data we additionally populate /// `content_items` with the structured form that the Responses/Chat /// Completions APIs understand. #[derive(Debug, Default, Clone, PartialEq, JsonSchema, TS)] pub struct FunctionCallOutputPayload { pub content: String, #[serde(skip_serializing_if = "Option::is_none")] pub content_items: Option<Vec<FunctionCallOutputContentItem>>, // TODO(jif) drop this. pub success: Option<bool>, } #[derive(Deserialize)] #[serde(untagged)] enum FunctionCallOutputPayloadSerde { Text(String), Items(Vec<FunctionCallOutputContentItem>), } // The Responses API expects two *different* shapes depending on success vs failure: // • success → output is a plain string (no nested object) // • failure → output is an object { content, success:false } impl Serialize for FunctionCallOutputPayload { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(items) = &self.content_items { items.serialize(serializer) } else { serializer.serialize_str(&self.content) } } } impl<'de> Deserialize<'de> for FunctionCallOutputPayload { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { match FunctionCallOutputPayloadSerde::deserialize(deserializer)? { FunctionCallOutputPayloadSerde::Text(content) => Ok(FunctionCallOutputPayload { content, ..Default::default() }), FunctionCallOutputPayloadSerde::Items(items) => { let content = serde_json::to_string(&items).map_err(serde::de::Error::custom)?; Ok(FunctionCallOutputPayload { content, content_items: Some(items), success: None, }) } } } } impl From<&CallToolResult> for FunctionCallOutputPayload { fn from(call_tool_result: &CallToolResult) -> Self { let CallToolResult { content, structured_content, is_error, } = call_tool_result; let is_success = is_error != &Some(true); if let Some(structured_content) = structured_content && !structured_content.is_null() { match serde_json::to_string(structured_content) { Ok(serialized_structured_content) => { return FunctionCallOutputPayload { content: serialized_structured_content, success: Some(is_success), ..Default::default() }; } Err(err) => { return FunctionCallOutputPayload { content: err.to_string(), success: Some(false), ..Default::default() }; } } } let serialized_content = match serde_json::to_string(content) { Ok(serialized_content) => serialized_content, Err(err) => { return FunctionCallOutputPayload { content: err.to_string(), success: Some(false), ..Default::default() }; } }; let content_items = convert_content_blocks_to_items(content); FunctionCallOutputPayload { content: serialized_content, content_items, success: Some(is_success), } } } fn convert_content_blocks_to_items( blocks: &[ContentBlock], ) -> Option<Vec<FunctionCallOutputContentItem>> { let mut saw_image = false; let mut items = Vec::with_capacity(blocks.len()); tracing::warn!("Blocks: {:?}", blocks); for block in blocks { match block { ContentBlock::TextContent(text) => { items.push(FunctionCallOutputContentItem::InputText { text: text.text.clone(), }); } ContentBlock::ImageContent(image) => { saw_image = true; // Just in case the content doesn't include a data URL, add it. let image_url = if image.data.starts_with("data:") { image.data.clone() } else { format!("data:{};base64,{}", image.mime_type, image.data) }; items.push(FunctionCallOutputContentItem::InputImage { image_url }); } // TODO: render audio, resource, and embedded resource content to the model. _ => return None, } } if saw_image { Some(items) } else { None } } // Implement Display so callers can treat the payload like a plain string when logging or doing // trivial substring checks in tests (existing tests call `.contains()` on the output). Display // returns the raw `content` field. impl std::fmt::Display for FunctionCallOutputPayload { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.content) } } impl std::ops::Deref for FunctionCallOutputPayload { type Target = str; fn deref(&self) -> &Self::Target { &self.content } } // (Moved event mapping logic into codex-core to avoid coupling protocol to UI-facing events.) #[cfg(test)] mod tests { use super::*; use anyhow::Result; use mcp_types::ImageContent; use mcp_types::TextContent; use pretty_assertions::assert_eq; use tempfile::tempdir; #[test] fn serializes_success_as_plain_string() -> Result<()> { let item = ResponseInputItem::FunctionCallOutput { call_id: "call1".into(), output: FunctionCallOutputPayload { content: "ok".into(), ..Default::default() }, }; let json = serde_json::to_string(&item)?; let v: serde_json::Value = serde_json::from_str(&json)?; // Success case -> output should be a plain string assert_eq!(v.get("output").unwrap().as_str().unwrap(), "ok"); Ok(()) } #[test] fn serializes_failure_as_string() -> Result<()> { let item = ResponseInputItem::FunctionCallOutput { call_id: "call1".into(), output: FunctionCallOutputPayload { content: "bad".into(), success: Some(false), ..Default::default() }, }; let json = serde_json::to_string(&item)?; let v: serde_json::Value = serde_json::from_str(&json)?; assert_eq!(v.get("output").unwrap().as_str().unwrap(), "bad"); Ok(()) } #[test] fn serializes_image_outputs_as_array() -> Result<()> { let call_tool_result = CallToolResult { content: vec![ ContentBlock::TextContent(TextContent { annotations: None, text: "caption".into(), r#type: "text".into(), }), ContentBlock::ImageContent(ImageContent { annotations: None, data: "BASE64".into(), mime_type: "image/png".into(), r#type: "image".into(), }), ], is_error: None, structured_content: None, }; let payload = FunctionCallOutputPayload::from(&call_tool_result); assert_eq!(payload.success, Some(true)); let items = payload.content_items.clone().expect("content items"); assert_eq!( items, vec![ FunctionCallOutputContentItem::InputText { text: "caption".into(), }, FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,BASE64".into(), }, ] ); let item = ResponseInputItem::FunctionCallOutput { call_id: "call1".into(), output: payload, }; let json = serde_json::to_string(&item)?; let v: serde_json::Value = serde_json::from_str(&json)?; let output = v.get("output").expect("output field"); assert!(output.is_array(), "expected array output"); Ok(()) } #[test] fn deserializes_array_payload_into_items() -> Result<()> { let json = r#"[ {"type": "input_text", "text": "note"}, {"type": "input_image", "image_url": "data:image/png;base64,XYZ"} ]"#; let payload: FunctionCallOutputPayload = serde_json::from_str(json)?; assert_eq!(payload.success, None); let expected_items = vec![ FunctionCallOutputContentItem::InputText { text: "note".into(), }, FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,XYZ".into(), }, ]; assert_eq!(payload.content_items, Some(expected_items.clone())); let expected_content = serde_json::to_string(&expected_items)?; assert_eq!(payload.content, expected_content); Ok(()) } #[test] fn deserializes_compaction_alias() -> Result<()> { let json = r#"{"type":"compaction_summary","encrypted_content":"abc"}"#; let item: ResponseItem = serde_json::from_str(json)?; assert_eq!( item, ResponseItem::Compaction { encrypted_content: "abc".into(), } ); Ok(()) } #[test] fn roundtrips_web_search_call_actions() -> Result<()> { let cases = vec![ ( r#"{ "type": "web_search_call", "status": "completed", "action": { "type": "search", "query": "weather seattle" } }"#, WebSearchAction::Search { query: Some("weather seattle".into()), }, Some("completed".into()), ), ( r#"{ "type": "web_search_call", "status": "open", "action": { "type": "open_page", "url": "https://example.com" } }"#, WebSearchAction::OpenPage { url: Some("https://example.com".into()), }, Some("open".into()), ), ( r#"{ "type": "web_search_call", "status": "in_progress", "action": { "type": "find_in_page", "url": "https://example.com/docs", "pattern": "installation" } }"#, WebSearchAction::FindInPage { url: Some("https://example.com/docs".into()), pattern: Some("installation".into()), }, Some("in_progress".into()), ), ]; for (json_literal, expected_action, expected_status) in cases { let parsed: ResponseItem = serde_json::from_str(json_literal)?; let expected = ResponseItem::WebSearchCall { id: None, status: expected_status.clone(), action: expected_action.clone(), }; assert_eq!(parsed, expected); let serialized = serde_json::to_value(&parsed)?; let original_value: serde_json::Value = serde_json::from_str(json_literal)?; assert_eq!(serialized, original_value); } Ok(()) } #[test] fn deserialize_shell_tool_call_params() -> Result<()> { let json = r#"{ "command": ["ls", "-l"], "workdir": "/tmp", "timeout": 1000 }"#; let params: ShellToolCallParams = serde_json::from_str(json)?; assert_eq!( ShellToolCallParams { command: vec!["ls".to_string(), "-l".to_string()], workdir: Some("/tmp".to_string()), timeout_ms: Some(1000), sandbox_permissions: None, justification: None, }, params ); Ok(()) } #[test] fn local_image_read_error_adds_placeholder() -> Result<()> { let dir = tempdir()?; let missing_path = dir.path().join("missing-image.png"); let item = ResponseInputItem::from(vec![UserInput::LocalImage { path: missing_path.clone(), }]); match item { ResponseInputItem::Message { content, .. } => { assert_eq!(content.len(), 1); match &content[0] { ContentItem::InputText { text } => { let display_path = missing_path.display().to_string(); assert!( text.contains(&display_path), "placeholder should mention missing path: {text}" ); assert!( text.contains("could not read"), "placeholder should mention read issue: {text}" ); } other => panic!("expected placeholder text but found {other:?}"), } } other => panic!("expected message response but got {other:?}"), } Ok(()) } #[test] fn local_image_non_image_adds_placeholder() -> Result<()> { let dir = tempdir()?; let json_path = dir.path().join("example.json"); std::fs::write(&json_path, br#"{"hello":"world"}"#)?; let item = ResponseInputItem::from(vec![UserInput::LocalImage { path: json_path.clone(), }]); match item { ResponseInputItem::Message { content, .. } => { assert_eq!(content.len(), 1); match &content[0] { ContentItem::InputText { text } => { assert!( text.contains("unsupported MIME type `application/json`"), "placeholder should mention unsupported MIME: {text}" ); assert!( text.contains(&json_path.display().to_string()), "placeholder should mention path: {text}" ); } other => panic!("expected placeholder text but found {other:?}"), } } other => panic!("expected message response but got {other:?}"), } Ok(()) } #[test] fn local_image_unsupported_image_format_adds_placeholder() -> Result<()> { let dir = tempdir()?; let svg_path = dir.path().join("example.svg"); std::fs::write( &svg_path, br#"<?xml version="1.0" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"></svg>"#, )?; let item = ResponseInputItem::from(vec![UserInput::LocalImage { path: svg_path.clone(), }]); match item { ResponseInputItem::Message { content, .. } => { assert_eq!(content.len(), 1); let expected = format!( "Codex cannot attach image at `{}`: unsupported image format `image/svg+xml`.", svg_path.display() ); match &content[0] { ContentItem::InputText { text } => assert_eq!(text, &expected), other => panic!("expected placeholder text but found {other:?}"), } } other => panic!("expected message response but got {other:?}"), } Ok(()) } }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
openai/codex
https://github.com/openai/codex/blob/279283fe02bf0ce7f93a160db34dd8cf9c8f42c8/codex-rs/protocol/src/account.rs
codex-rs/protocol/src/account.rs
use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use ts_rs::TS; #[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq, JsonSchema, TS, Default)] #[serde(rename_all = "lowercase")] #[ts(rename_all = "lowercase")] pub enum PlanType { #[default] Free, Plus, Pro, Team, Business, Enterprise, Edu, #[serde(other)] Unknown, }
rust
Apache-2.0
279283fe02bf0ce7f93a160db34dd8cf9c8f42c8
2026-01-04T15:31:59.292600Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/build.rs
build.rs
#[path = "src/cmd/cmd.rs"] mod cmd; use std::{env, io}; use clap::CommandFactory as _; use clap_complete::shells::{Bash, Elvish, Fish, PowerShell, Zsh}; use clap_complete_fig::Fig; use clap_complete_nushell::Nushell; use cmd::Cmd; fn main() -> io::Result<()> { // Since we are generating completions in the package directory, we need to // set this so that Cargo doesn't rebuild every time. println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=src/"); println!("cargo:rerun-if-changed=templates/"); println!("cargo:rerun-if-changed=tests/"); generate_completions() } fn generate_completions() -> io::Result<()> { const BIN_NAME: &str = env!("CARGO_PKG_NAME"); const OUT_DIR: &str = "contrib/completions"; let cmd = &mut Cmd::command(); clap_complete::generate_to(Bash, cmd, BIN_NAME, OUT_DIR)?; clap_complete::generate_to(Elvish, cmd, BIN_NAME, OUT_DIR)?; clap_complete::generate_to(Fig, cmd, BIN_NAME, OUT_DIR)?; clap_complete::generate_to(Fish, cmd, BIN_NAME, OUT_DIR)?; clap_complete::generate_to(Nushell, cmd, BIN_NAME, OUT_DIR)?; clap_complete::generate_to(PowerShell, cmd, BIN_NAME, OUT_DIR)?; clap_complete::generate_to(Zsh, cmd, BIN_NAME, OUT_DIR)?; Ok(()) }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/config.rs
src/config.rs
use std::env; use std::ffi::OsString; use std::path::PathBuf; use anyhow::{Context, Result, ensure}; use glob::Pattern; use crate::db::Rank; pub fn data_dir() -> Result<PathBuf> { let dir = match env::var_os("_ZO_DATA_DIR") { Some(path) => PathBuf::from(path), None => dirs::data_local_dir() .context("could not find data directory, please set _ZO_DATA_DIR manually")? .join("zoxide"), }; ensure!(dir.is_absolute(), "_ZO_DATA_DIR must be an absolute path"); Ok(dir) } pub fn echo() -> bool { env::var_os("_ZO_ECHO").is_some_and(|var| var == "1") } pub fn exclude_dirs() -> Result<Vec<Pattern>> { match env::var_os("_ZO_EXCLUDE_DIRS") { Some(paths) => env::split_paths(&paths) .map(|path| { let pattern = path.to_str().context("invalid unicode in _ZO_EXCLUDE_DIRS")?; Pattern::new(pattern) .with_context(|| format!("invalid glob in _ZO_EXCLUDE_DIRS: {pattern}")) }) .collect(), None => { let pattern = (|| { let home = dirs::home_dir()?; let home = Pattern::escape(home.to_str()?); Pattern::new(&home).ok() })(); Ok(pattern.into_iter().collect()) } } } pub fn fzf_opts() -> Option<OsString> { env::var_os("_ZO_FZF_OPTS") } pub fn maxage() -> Result<Rank> { env::var_os("_ZO_MAXAGE").map_or(Ok(10_000.0), |maxage| { let maxage = maxage.to_str().context("invalid unicode in _ZO_MAXAGE")?; let maxage = maxage .parse::<u32>() .with_context(|| format!("unable to parse _ZO_MAXAGE as integer: {maxage}"))?; Ok(maxage as Rank) }) } pub fn resolve_symlinks() -> bool { env::var_os("_ZO_RESOLVE_SYMLINKS").is_some_and(|var| var == "1") }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/shell.rs
src/shell.rs
use crate::cmd::InitHook; #[derive(Debug, Eq, PartialEq)] pub struct Opts<'a> { pub cmd: Option<&'a str>, pub hook: InitHook, pub echo: bool, pub resolve_symlinks: bool, } macro_rules! make_template { ($name:ident, $path:expr) => { #[derive(::std::fmt::Debug, ::askama::Template)] #[template(path = $path)] pub struct $name<'a>(pub &'a self::Opts<'a>); impl<'a> ::std::ops::Deref for $name<'a> { type Target = self::Opts<'a>; fn deref(&self) -> &Self::Target { self.0 } } }; } make_template!(Bash, "bash.txt"); make_template!(Elvish, "elvish.txt"); make_template!(Fish, "fish.txt"); make_template!(Nushell, "nushell.txt"); make_template!(Posix, "posix.txt"); make_template!(Powershell, "powershell.txt"); make_template!(Tcsh, "tcsh.txt"); make_template!(Xonsh, "xonsh.txt"); make_template!(Zsh, "zsh.txt"); #[cfg(feature = "nix-dev")] #[cfg(test)] mod tests { use askama::Template; use assert_cmd::Command; use rstest::rstest; use rstest_reuse::{apply, template}; use super::*; #[template] #[rstest] fn opts( #[values(None, Some("z"))] cmd: Option<&str>, #[values(InitHook::None, InitHook::Prompt, InitHook::Pwd)] hook: InitHook, #[values(false, true)] echo: bool, #[values(false, true)] resolve_symlinks: bool, ) { } #[apply(opts)] fn bash_bash(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Bash(&opts).render().unwrap(); Command::new("bash") .args(["--noprofile", "--norc", "-e", "-u", "-o", "pipefail", "-c", &source]) .assert() .success() .stdout("") .stderr(""); } #[apply(opts)] fn bash_shellcheck(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Bash(&opts).render().unwrap(); Command::new("shellcheck") .args(["--enable=all", "-"]) .write_stdin(source) .assert() .success() .stdout("") .stderr(""); } #[apply(opts)] fn bash_shfmt(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let mut source = Bash(&opts).render().unwrap(); source.push('\n'); Command::new("shfmt") .args(["--diff", "--indent=4", "--language-dialect=bash", "--simplify", "-"]) .write_stdin(source) .assert() .success() .stdout("") .stderr(""); } #[apply(opts)] fn elvish_elvish(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let mut source = String::new(); // Filter out lines using edit:*, since those functions are only available in // the interactive editor. for line in Elvish(&opts).render().unwrap().lines().filter(|line| !line.contains("edit:")) { source.push_str(line); source.push('\n'); } Command::new("elvish") .args(["-c", &source, "-norc"]) .assert() .success() .stdout("") .stderr(""); } #[apply(opts)] fn fish_no_builtin_abbr(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Fish(&opts).render().unwrap(); assert!( !source.contains("builtin abbr"), "`builtin abbr` does not work on older versions of Fish" ); } #[apply(opts)] fn fish_fish(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Fish(&opts).render().unwrap(); let tempdir = tempfile::tempdir().unwrap(); let tempdir = tempdir.path().to_str().unwrap(); Command::new("fish") .env("HOME", tempdir) .args(["--command", &source, "--no-config", "--private"]) .assert() .success() .stdout("") .stderr(""); } #[apply(opts)] fn fish_fishindent(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let mut source = Fish(&opts).render().unwrap(); source.push('\n'); let tempdir = tempfile::tempdir().unwrap(); let tempdir = tempdir.path().to_str().unwrap(); Command::new("fish_indent") .env("HOME", tempdir) .write_stdin(source.to_string()) .assert() .success() .stdout(source) .stderr(""); } #[apply(opts)] fn nushell_nushell(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Nushell(&opts).render().unwrap(); let tempdir = tempfile::tempdir().unwrap(); let tempdir = tempdir.path(); let assert = Command::new("nu") .env("HOME", tempdir) .args(["--commands", &source]) .assert() .success() .stderr(""); if opts.hook != InitHook::Pwd { assert.stdout(""); } } #[apply(opts)] fn posix_bash(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Posix(&opts).render().unwrap(); let assert = Command::new("bash") .args(["--posix", "--noprofile", "--norc", "-e", "-u", "-o", "pipefail", "-c", &source]) .assert() .success() .stderr(""); if opts.hook != InitHook::Pwd { assert.stdout(""); } } #[apply(opts)] fn posix_dash(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Posix(&opts).render().unwrap(); let assert = Command::new("dash").args(["-e", "-u", "-c", &source]).assert().success().stderr(""); if opts.hook != InitHook::Pwd { assert.stdout(""); } } #[apply(opts)] fn posix_shellcheck(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Posix(&opts).render().unwrap(); Command::new("shellcheck") .args(["--enable=all", "-"]) .write_stdin(source) .assert() .success() .stdout("") .stderr(""); } #[apply(opts)] fn posix_shfmt(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let mut source = Posix(&opts).render().unwrap(); source.push('\n'); Command::new("shfmt") .args(["--diff", "--indent=4", "--language-dialect=posix", "--simplify", "-"]) .write_stdin(source) .assert() .success() .stdout("") .stderr(""); } #[apply(opts)] fn powershell_pwsh(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let mut source = "Set-StrictMode -Version latest\n".to_string(); Powershell(&opts).render_into(&mut source).unwrap(); Command::new("pwsh") .args(["-NoLogo", "-NonInteractive", "-NoProfile", "-Command", &source]) .assert() .success() .stdout("") .stderr(""); } #[apply(opts)] fn tcsh_tcsh(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Tcsh(&opts).render().unwrap(); Command::new("tcsh") .args(["-e", "-f", "-s"]) .write_stdin(source) .assert() .success() .stdout("") .stderr(""); } #[apply(opts)] fn xonsh_black(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let mut source = Xonsh(&opts).render().unwrap(); source.push('\n'); Command::new("black") .args(["--check", "--diff", "-"]) .write_stdin(source) .assert() .success() .stdout(""); } #[apply(opts)] fn xonsh_mypy(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Xonsh(&opts).render().unwrap(); Command::new("mypy").args(["--command", &source, "--strict"]).assert().success().stderr(""); } #[apply(opts)] fn xonsh_pylint(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let mut source = Xonsh(&opts).render().unwrap(); source.push('\n'); Command::new("pylint") .args(["--from-stdin", "--persistent=n", "zoxide"]) .write_stdin(source) .assert() .success() .stderr(""); } #[apply(opts)] fn xonsh_xonsh(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Xonsh(&opts).render().unwrap(); let tempdir = tempfile::tempdir().unwrap(); let tempdir = tempdir.path().to_str().unwrap(); Command::new("xonsh") .args(["-c", &source, "--no-rc"]) .env("HOME", tempdir) .assert() .success() .stdout("") .stderr(""); } #[apply(opts)] fn zsh_shellcheck(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Zsh(&opts).render().unwrap(); // ShellCheck doesn't support zsh yet: https://github.com/koalaman/shellcheck/issues/809 Command::new("shellcheck") .args(["--enable=all", "-"]) .write_stdin(source) .assert() .success() .stdout("") .stderr(""); } #[apply(opts)] fn zsh_zsh(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Zsh(&opts).render().unwrap(); Command::new("zsh") .args(["-e", "-u", "-o", "pipefail", "--no-globalrcs", "--no-rcs", "-c", &source]) .assert() .success() .stdout("") .stderr(""); } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/error.rs
src/error.rs
use std::fmt::{self, Display, Formatter}; use std::io; use anyhow::{Context, Result, bail}; /// Custom error type for early exit. #[derive(Debug)] pub struct SilentExit { pub code: u8, } impl Display for SilentExit { fn fmt(&self, _: &mut Formatter<'_>) -> fmt::Result { Ok(()) } } pub trait BrokenPipeHandler { fn pipe_exit(self, device: &str) -> Result<()>; } impl BrokenPipeHandler for io::Result<()> { fn pipe_exit(self, device: &str) -> Result<()> { match self { Err(e) if e.kind() == io::ErrorKind::BrokenPipe => bail!(SilentExit { code: 0 }), result => result.with_context(|| format!("could not write to {device}")), } } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/util.rs
src/util.rs
use std::ffi::OsStr; use std::fs::{self, File, OpenOptions}; use std::io::{self, Read, Write}; use std::path::{Component, Path, PathBuf}; use std::process::{Child, Command, Stdio}; use std::time::SystemTime; use std::{env, mem}; #[cfg(windows)] use anyhow::anyhow; use anyhow::{Context, Result, bail}; use crate::db::{Dir, Epoch}; use crate::error::SilentExit; pub const SECOND: Epoch = 1; pub const MINUTE: Epoch = 60 * SECOND; pub const HOUR: Epoch = 60 * MINUTE; pub const DAY: Epoch = 24 * HOUR; pub const WEEK: Epoch = 7 * DAY; pub const MONTH: Epoch = 30 * DAY; pub struct Fzf(Command); impl Fzf { const ERR_FZF_NOT_FOUND: &'static str = "could not find fzf, is it installed?"; pub fn new() -> Result<Self> { // On Windows, CreateProcess implicitly searches the current working // directory for the executable, which is a potential security issue. // Instead, we resolve the path to the executable and then pass it to // CreateProcess. #[cfg(windows)] let program = which::which("fzf.exe").map_err(|_| anyhow!(Self::ERR_FZF_NOT_FOUND))?; #[cfg(not(windows))] let program = "fzf"; // TODO: check version of fzf here. let mut cmd = Command::new(program); cmd.args([ // Search mode "--delimiter=\t", "--nth=2", // Scripting "--read0", ]) .stdin(Stdio::piped()) .stdout(Stdio::piped()); Ok(Fzf(cmd)) } pub fn enable_preview(&mut self) -> &mut Self { // Previews are only supported on UNIX. if !cfg!(unix) { return self; } self.args([ // Non-POSIX args are only available on certain operating systems. if cfg!(target_os = "linux") { r"--preview=\command -p ls -Cp --color=always --group-directories-first {2..}" } else { r"--preview=\command -p ls -Cp {2..}" }, // Rounded edges don't display correctly on some terminals. "--preview-window=down,30%,sharp", ]) .envs([ // Enables colorized `ls` output on macOS / FreeBSD. ("CLICOLOR", "1"), // Forces colorized `ls` output when the output is not a // TTY (like in fzf's preview window) on macOS / // FreeBSD. ("CLICOLOR_FORCE", "1"), // Ensures that the preview command is run in a // POSIX-compliant shell, regardless of what shell the // user has selected. ("SHELL", "sh"), ]) } pub fn args<I, S>(&mut self, args: I) -> &mut Self where I: IntoIterator<Item = S>, S: AsRef<OsStr>, { self.0.args(args); self } pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Self where K: AsRef<OsStr>, V: AsRef<OsStr>, { self.0.env(key, val); self } pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self where I: IntoIterator<Item = (K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>, { self.0.envs(vars); self } pub fn spawn(&mut self) -> Result<FzfChild> { match self.0.spawn() { Ok(child) => Ok(FzfChild(child)), Err(e) if e.kind() == io::ErrorKind::NotFound => bail!(Self::ERR_FZF_NOT_FOUND), Err(e) => Err(e).context("could not launch fzf"), } } } pub struct FzfChild(Child); impl FzfChild { pub fn write(&mut self, dir: &Dir, now: Epoch) -> Result<Option<String>> { let handle = self.0.stdin.as_mut().unwrap(); match write!(handle, "{}\0", dir.display().with_score(now).with_separator('\t')) { Ok(()) => Ok(None), Err(e) if e.kind() == io::ErrorKind::BrokenPipe => self.wait().map(Some), Err(e) => Err(e).context("could not write to fzf"), } } pub fn wait(&mut self) -> Result<String> { // Drop stdin to prevent deadlock. mem::drop(self.0.stdin.take()); let mut stdout = self.0.stdout.take().unwrap(); let mut output = String::new(); stdout.read_to_string(&mut output).context("failed to read from fzf")?; let status = self.0.wait().context("wait failed on fzf")?; match status.code() { Some(0) => Ok(output), Some(1) => bail!("no match found"), Some(2) => bail!("fzf returned an error"), Some(130) => bail!(SilentExit { code: 130 }), Some(128..=254) | None => bail!("fzf was terminated"), _ => bail!("fzf returned an unknown error"), } } } /// Similar to [`fs::write`], but atomic (best effort on Windows). pub fn write(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Result<()> { let path = path.as_ref(); let contents = contents.as_ref(); let dir = path.parent().unwrap(); // Create a tmpfile. let (mut tmp_file, tmp_path) = tmpfile(dir)?; let result = (|| { // Write to the tmpfile. _ = tmp_file.set_len(contents.len() as u64); tmp_file .write_all(contents) .with_context(|| format!("could not write to file: {}", tmp_path.display()))?; // Set the owner of the tmpfile (UNIX only). #[cfg(unix)] if let Ok(metadata) = path.metadata() { use std::os::unix::fs::MetadataExt; use nix::unistd::{self, Gid, Uid}; let uid = Uid::from_raw(metadata.uid()); let gid = Gid::from_raw(metadata.gid()); _ = unistd::fchown(&tmp_file, Some(uid), Some(gid)); } // Close and rename the tmpfile. // In some cases, errors from the last write() are reported only on close(). // Rust ignores errors from close(), since it occurs inside `Drop`. To // catch these errors, we manually call `File::sync_all()` first. tmp_file .sync_all() .with_context(|| format!("could not sync writes to file: {}", tmp_path.display()))?; mem::drop(tmp_file); rename(&tmp_path, path) })(); // In case of an error, delete the tmpfile. if result.is_err() { _ = fs::remove_file(&tmp_path); } result } /// Atomically create a tmpfile in the given directory. fn tmpfile(dir: impl AsRef<Path>) -> Result<(File, PathBuf)> { const MAX_ATTEMPTS: usize = 5; const TMP_NAME_LEN: usize = 16; let dir = dir.as_ref(); let mut attempts = 0; loop { attempts += 1; // Generate a random name for the tmpfile. let mut name = String::with_capacity(TMP_NAME_LEN); name.push_str("tmp_"); while name.len() < TMP_NAME_LEN { name.push(fastrand::alphanumeric()); } let path = dir.join(name); // Atomically create the tmpfile. match OpenOptions::new().write(true).create_new(true).open(&path) { Ok(file) => break Ok((file, path)), Err(e) if e.kind() == io::ErrorKind::AlreadyExists && attempts < MAX_ATTEMPTS => {} Err(e) => { break Err(e).with_context(|| format!("could not create file: {}", path.display())); } } } } /// Similar to [`fs::rename`], but with retries on Windows. fn rename(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> { let from = from.as_ref(); let to = to.as_ref(); const MAX_ATTEMPTS: usize = if cfg!(windows) { 5 } else { 1 }; let mut attempts = 0; loop { match fs::rename(from, to) { Err(e) if e.kind() == io::ErrorKind::PermissionDenied && attempts < MAX_ATTEMPTS => { attempts += 1 } result => { break result.with_context(|| { format!("could not rename file: {} -> {}", from.display(), to.display()) }); } } } } pub fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf> { dunce::canonicalize(&path) .with_context(|| format!("could not resolve path: {}", path.as_ref().display())) } pub fn current_dir() -> Result<PathBuf> { env::current_dir().context("could not get current directory") } pub fn current_time() -> Result<Epoch> { let current_time = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .context("system clock set to invalid time")? .as_secs(); Ok(current_time) } pub fn path_to_str(path: &impl AsRef<Path>) -> Result<&str> { let path = path.as_ref(); path.to_str().with_context(|| format!("invalid unicode in path: {}", path.display())) } /// Returns the absolute version of a path. Like /// [`std::path::Path::canonicalize`], but doesn't resolve symlinks. pub fn resolve_path(path: impl AsRef<Path>) -> Result<PathBuf> { let path = path.as_ref(); let base_path; let mut components = path.components().peekable(); let mut stack = Vec::new(); // initialize root if cfg!(windows) { use std::path::Prefix; fn get_drive_letter(path: impl AsRef<Path>) -> Option<u8> { let path = path.as_ref(); let mut components = path.components(); match components.next() { Some(Component::Prefix(prefix)) => match prefix.kind() { Prefix::Disk(drive_letter) | Prefix::VerbatimDisk(drive_letter) => { Some(drive_letter) } _ => None, }, _ => None, } } fn get_drive_path(drive_letter: u8) -> PathBuf { format!(r"{}:\", drive_letter as char).into() } fn get_drive_relative(drive_letter: u8) -> Result<PathBuf> { let path = current_dir()?; if Some(drive_letter) == get_drive_letter(&path) { return Ok(path); } if let Some(path) = env::var_os(format!("={}:", drive_letter as char)) { return Ok(path.into()); } let path = get_drive_path(drive_letter); Ok(path) } match components.peek() { Some(Component::Prefix(prefix)) => match prefix.kind() { Prefix::Disk(drive_letter) => { let disk = components.next().unwrap(); if components.peek() == Some(&Component::RootDir) { let root = components.next().unwrap(); stack.push(disk); stack.push(root); } else { base_path = get_drive_relative(drive_letter)?; stack.extend(base_path.components()); } } Prefix::VerbatimDisk(drive_letter) => { components.next(); if components.peek() == Some(&Component::RootDir) { components.next(); } base_path = get_drive_path(drive_letter); stack.extend(base_path.components()); } _ => bail!("invalid path: {}", path.display()), }, Some(Component::RootDir) => { components.next(); let current_dir = env::current_dir()?; let drive_letter = get_drive_letter(&current_dir).with_context(|| { format!("could not get drive letter: {}", current_dir.display()) })?; base_path = get_drive_path(drive_letter); stack.extend(base_path.components()); } _ => { base_path = current_dir()?; stack.extend(base_path.components()); } } } else if components.peek() == Some(&Component::RootDir) { let root = components.next().unwrap(); stack.push(root); } else { base_path = current_dir()?; stack.extend(base_path.components()); } for component in components { match component { Component::Normal(_) => stack.push(component), Component::CurDir => {} Component::ParentDir => { if stack.last() != Some(&Component::RootDir) { stack.pop(); } } Component::Prefix(_) | Component::RootDir => unreachable!(), } } Ok(stack.iter().collect()) } /// Convert a string to lowercase, with a fast path for ASCII strings. pub fn to_lowercase(s: impl AsRef<str>) -> String { let s = s.as_ref(); if s.is_ascii() { s.to_ascii_lowercase() } else { s.to_lowercase() } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/main.rs
src/main.rs
#![allow(clippy::single_component_path_imports)] mod cmd; mod config; mod db; mod error; mod shell; mod util; use std::env; use std::io::{self, Write}; use std::process::ExitCode; use clap::Parser; use crate::cmd::{Cmd, Run}; use crate::error::SilentExit; pub fn main() -> ExitCode { // Forcibly disable backtraces. unsafe { env::remove_var("RUST_LIB_BACKTRACE") }; unsafe { env::remove_var("RUST_BACKTRACE") }; match Cmd::parse().run() { Ok(()) => ExitCode::SUCCESS, Err(e) => match e.downcast::<SilentExit>() { Ok(SilentExit { code }) => code.into(), Err(e) => { _ = writeln!(io::stderr(), "zoxide: {e:?}"); ExitCode::FAILURE } }, } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/cmd/mod.rs
src/cmd/mod.rs
mod add; mod cmd; mod edit; mod import; mod init; mod query; mod remove; use anyhow::Result; pub use crate::cmd::cmd::*; pub trait Run { fn run(&self) -> Result<()>; } impl Run for Cmd { fn run(&self) -> Result<()> { match self { Cmd::Add(cmd) => cmd.run(), Cmd::Edit(cmd) => cmd.run(), Cmd::Import(cmd) => cmd.run(), Cmd::Init(cmd) => cmd.run(), Cmd::Query(cmd) => cmd.run(), Cmd::Remove(cmd) => cmd.run(), } } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/cmd/init.rs
src/cmd/init.rs
use std::io::{self, Write}; use anyhow::{Context, Result}; use askama::Template; use crate::cmd::{Init, InitShell, Run}; use crate::config; use crate::error::BrokenPipeHandler; use crate::shell::{Bash, Elvish, Fish, Nushell, Opts, Posix, Powershell, Tcsh, Xonsh, Zsh}; impl Run for Init { fn run(&self) -> Result<()> { let cmd = if self.no_cmd { None } else { Some(self.cmd.as_str()) }; let echo = config::echo(); let resolve_symlinks = config::resolve_symlinks(); let opts = &Opts { cmd, hook: self.hook, echo, resolve_symlinks }; let source = match self.shell { InitShell::Bash => Bash(opts).render(), InitShell::Elvish => Elvish(opts).render(), InitShell::Fish => Fish(opts).render(), InitShell::Nushell => Nushell(opts).render(), InitShell::Posix => Posix(opts).render(), InitShell::Powershell => Powershell(opts).render(), InitShell::Tcsh => Tcsh(opts).render(), InitShell::Xonsh => Xonsh(opts).render(), InitShell::Zsh => Zsh(opts).render(), } .context("could not render template")?; writeln!(io::stdout(), "{source}").pipe_exit("stdout") } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/cmd/query.rs
src/cmd/query.rs
use std::io::{self, Write}; use anyhow::{Context, Result}; use crate::cmd::{Query, Run}; use crate::config; use crate::db::{Database, Epoch, Stream, StreamOptions}; use crate::error::BrokenPipeHandler; use crate::util::{self, Fzf, FzfChild}; impl Run for Query { fn run(&self) -> Result<()> { let mut db = crate::db::Database::open()?; self.query(&mut db).and(db.save()) } } impl Query { fn query(&self, db: &mut Database) -> Result<()> { let now = util::current_time()?; let mut stream = self.get_stream(db, now)?; if self.interactive { self.query_interactive(&mut stream, now) } else if self.list { self.query_list(&mut stream, now) } else { self.query_first(&mut stream, now) } } fn query_interactive(&self, stream: &mut Stream, now: Epoch) -> Result<()> { let mut fzf = Self::get_fzf()?; let selection = loop { match stream.next() { Some(dir) if Some(dir.path.as_ref()) == self.exclude.as_deref() => continue, Some(dir) => { if let Some(selection) = fzf.write(dir, now)? { break selection; } } None => break fzf.wait()?, } }; if self.score { print!("{selection}"); } else { let path = selection.get(7..).context("could not read selection from fzf")?; print!("{path}"); } Ok(()) } fn query_list(&self, stream: &mut Stream, now: Epoch) -> Result<()> { let handle = &mut io::stdout().lock(); while let Some(dir) = stream.next() { if Some(dir.path.as_ref()) == self.exclude.as_deref() { continue; } let dir = if self.score { dir.display().with_score(now) } else { dir.display() }; writeln!(handle, "{dir}").pipe_exit("stdout")?; } Ok(()) } fn query_first(&self, stream: &mut Stream, now: Epoch) -> Result<()> { let handle = &mut io::stdout(); let mut dir = stream.next().context("no match found")?; while Some(dir.path.as_ref()) == self.exclude.as_deref() { dir = stream.next().context("you are already in the only match")?; } let dir = if self.score { dir.display().with_score(now) } else { dir.display() }; writeln!(handle, "{dir}").pipe_exit("stdout") } fn get_stream<'a>(&self, db: &'a mut Database, now: Epoch) -> Result<Stream<'a>> { let mut options = StreamOptions::new(now) .with_keywords(self.keywords.iter().map(|s| s.as_str())) .with_exclude(config::exclude_dirs()?) .with_base_dir(self.base_dir.clone()); if !self.all { let resolve_symlinks = config::resolve_symlinks(); options = options.with_exists(true).with_resolve_symlinks(resolve_symlinks); } let stream = Stream::new(db, options); Ok(stream) } fn get_fzf() -> Result<FzfChild> { let mut fzf = Fzf::new()?; if let Some(fzf_opts) = config::fzf_opts() { fzf.env("FZF_DEFAULT_OPTS", fzf_opts) } else { fzf.args([ // Search mode "--exact", // Search result "--no-sort", // Interface "--bind=ctrl-z:ignore,btab:up,tab:down", "--cycle", "--keep-right", // Layout "--border=sharp", // rounded edges don't display correctly on some terminals "--height=45%", "--info=inline", "--layout=reverse", // Display "--tabstop=1", // Scripting "--exit-0", ]) .enable_preview() } .spawn() } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/cmd/edit.rs
src/cmd/edit.rs
use std::io::{self, Write}; use anyhow::Result; use crate::cmd::{Edit, EditCommand, Run}; use crate::db::Database; use crate::error::BrokenPipeHandler; use crate::util::{self, Fzf, FzfChild}; impl Run for Edit { fn run(&self) -> Result<()> { let now = util::current_time()?; let db = &mut Database::open()?; match &self.cmd { Some(cmd) => { match cmd { EditCommand::Decrement { path } => db.add(path, -1.0, now), EditCommand::Delete { path } => { db.remove(path); } EditCommand::Increment { path } => db.add(path, 1.0, now), EditCommand::Reload => {} } db.save()?; let stdout = &mut io::stdout().lock(); for dir in db.dirs().iter().rev() { write!(stdout, "{}\0", dir.display().with_score(now).with_separator('\t')) .pipe_exit("fzf")?; } Ok(()) } None => { db.sort_by_score(now); db.save()?; Self::get_fzf()?.wait()?; Ok(()) } } } } impl Edit { fn get_fzf() -> Result<FzfChild> { Fzf::new()? .args([ // Search mode "--exact", // Search result "--no-sort", // Interface "--bind=\ btab:up,\ ctrl-r:reload(zoxide edit reload),\ ctrl-d:reload(zoxide edit delete {2..}),\ ctrl-w:reload(zoxide edit increment {2..}),\ ctrl-s:reload(zoxide edit decrement {2..}),\ ctrl-z:ignore,\ double-click:ignore,\ enter:abort,\ start:reload(zoxide edit reload),\ tab:down", "--cycle", "--keep-right", // Layout "--border=sharp", "--border-label= zoxide-edit ", "--header=\ ctrl-r:reload \tctrl-d:delete ctrl-w:increment\tctrl-s:decrement SCORE\tPATH", "--info=inline", "--layout=reverse", "--padding=1,0,0,0", // Display "--color=label:bold", "--tabstop=1", ]) .enable_preview() .spawn() } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/cmd/add.rs
src/cmd/add.rs
use std::path::Path; use anyhow::{Result, bail}; use crate::cmd::{Add, Run}; use crate::db::Database; use crate::{config, util}; impl Run for Add { fn run(&self) -> Result<()> { // These characters can't be printed cleanly to a single line, so they can cause // confusion when writing to stdout. const EXCLUDE_CHARS: &[char] = &['\n', '\r']; let exclude_dirs = config::exclude_dirs()?; let max_age = config::maxage()?; let now = util::current_time()?; let mut db = Database::open()?; for path in &self.paths { let path = if config::resolve_symlinks() { util::canonicalize } else { util::resolve_path }( path, )?; let path = util::path_to_str(&path)?; // Ignore path if it contains unsupported characters, or if it's in the exclude // list. if path.contains(EXCLUDE_CHARS) || exclude_dirs.iter().any(|glob| glob.matches(path)) { continue; } if !Path::new(path).is_dir() { bail!("not a directory: {path}"); } let by = self.score.unwrap_or(1.0); db.add_update(path, by, now); } if db.dirty() { db.age(max_age); } db.save() } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/cmd/import.rs
src/cmd/import.rs
use std::fs; use anyhow::{Context, Result, bail}; use crate::cmd::{Import, ImportFrom, Run}; use crate::db::Database; impl Run for Import { fn run(&self) -> Result<()> { let buffer = fs::read_to_string(&self.path).with_context(|| { format!("could not open database for importing: {}", &self.path.display()) })?; let mut db = Database::open()?; if !self.merge && !db.dirs().is_empty() { bail!("current database is not empty, specify --merge to continue anyway"); } match self.from { ImportFrom::Autojump => import_autojump(&mut db, &buffer), ImportFrom::Z => import_z(&mut db, &buffer), } .context("import error")?; db.save() } } fn import_autojump(db: &mut Database, buffer: &str) -> Result<()> { for line in buffer.lines() { if line.is_empty() { continue; } let (rank, path) = line.split_once('\t').with_context(|| format!("invalid entry: {line}"))?; let mut rank = rank.parse::<f64>().with_context(|| format!("invalid rank: {rank}"))?; // Normalize the rank using a sigmoid function. Don't import actual ranks from // autojump, since its scoring algorithm is very different and might // take a while to get normalized. rank = sigmoid(rank); db.add_unchecked(path, rank, 0); } if db.dirty() { db.dedup(); } Ok(()) } fn import_z(db: &mut Database, buffer: &str) -> Result<()> { for line in buffer.lines() { if line.is_empty() { continue; } let mut split = line.rsplitn(3, '|'); let last_accessed = split.next().with_context(|| format!("invalid entry: {line}"))?; let last_accessed = last_accessed.parse().with_context(|| format!("invalid epoch: {last_accessed}"))?; let rank = split.next().with_context(|| format!("invalid entry: {line}"))?; let rank = rank.parse().with_context(|| format!("invalid rank: {rank}"))?; let path = split.next().with_context(|| format!("invalid entry: {line}"))?; db.add_unchecked(path, rank, last_accessed); } if db.dirty() { db.dedup(); } Ok(()) } fn sigmoid(x: f64) -> f64 { 1.0 / (1.0 + (-x).exp()) } #[cfg(test)] mod tests { use super::*; use crate::db::Dir; #[test] fn from_autojump() { let data_dir = tempfile::tempdir().unwrap(); let mut db = Database::open_dir(data_dir.path()).unwrap(); for (path, rank, last_accessed) in [ ("/quux/quuz", 1.0, 100), ("/corge/grault/garply", 6.0, 600), ("/waldo/fred/plugh", 3.0, 300), ("/xyzzy/thud", 8.0, 800), ("/foo/bar", 9.0, 900), ] { db.add_unchecked(path, rank, last_accessed); } let buffer = "\ 7.0 /baz 2.0 /foo/bar 5.0 /quux/quuz"; import_autojump(&mut db, buffer).unwrap(); db.sort_by_path(); println!("got: {:?}", &db.dirs()); let exp = [ Dir { path: "/baz".into(), rank: sigmoid(7.0), last_accessed: 0 }, Dir { path: "/corge/grault/garply".into(), rank: 6.0, last_accessed: 600 }, Dir { path: "/foo/bar".into(), rank: 9.0 + sigmoid(2.0), last_accessed: 900 }, Dir { path: "/quux/quuz".into(), rank: 1.0 + sigmoid(5.0), last_accessed: 100 }, Dir { path: "/waldo/fred/plugh".into(), rank: 3.0, last_accessed: 300 }, Dir { path: "/xyzzy/thud".into(), rank: 8.0, last_accessed: 800 }, ]; println!("exp: {exp:?}"); for (dir1, dir2) in db.dirs().iter().zip(exp) { assert_eq!(dir1.path, dir2.path); assert!((dir1.rank - dir2.rank).abs() < 0.01); assert_eq!(dir1.last_accessed, dir2.last_accessed); } } #[test] fn from_z() { let data_dir = tempfile::tempdir().unwrap(); let mut db = Database::open_dir(data_dir.path()).unwrap(); for (path, rank, last_accessed) in [ ("/quux/quuz", 1.0, 100), ("/corge/grault/garply", 6.0, 600), ("/waldo/fred/plugh", 3.0, 300), ("/xyzzy/thud", 8.0, 800), ("/foo/bar", 9.0, 900), ] { db.add_unchecked(path, rank, last_accessed); } let buffer = "\ /baz|7|700 /quux/quuz|4|400 /foo/bar|2|200 /quux/quuz|5|500"; import_z(&mut db, buffer).unwrap(); db.sort_by_path(); println!("got: {:?}", &db.dirs()); let exp = [ Dir { path: "/baz".into(), rank: 7.0, last_accessed: 700 }, Dir { path: "/corge/grault/garply".into(), rank: 6.0, last_accessed: 600 }, Dir { path: "/foo/bar".into(), rank: 11.0, last_accessed: 900 }, Dir { path: "/quux/quuz".into(), rank: 10.0, last_accessed: 500 }, Dir { path: "/waldo/fred/plugh".into(), rank: 3.0, last_accessed: 300 }, Dir { path: "/xyzzy/thud".into(), rank: 8.0, last_accessed: 800 }, ]; println!("exp: {exp:?}"); for (dir1, dir2) in db.dirs().iter().zip(exp) { assert_eq!(dir1.path, dir2.path); assert!((dir1.rank - dir2.rank).abs() < 0.01); assert_eq!(dir1.last_accessed, dir2.last_accessed); } } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/cmd/remove.rs
src/cmd/remove.rs
use anyhow::{Result, bail}; use crate::cmd::{Remove, Run}; use crate::db::Database; use crate::util; impl Run for Remove { fn run(&self) -> Result<()> { let mut db = Database::open()?; for path in &self.paths { if !db.remove(path) { let path_abs = util::resolve_path(path)?; let path_abs = util::path_to_str(&path_abs)?; if path_abs == path || !db.remove(path_abs) { bail!("path not found in database: {path}") } } } db.save() } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/cmd/cmd.rs
src/cmd/cmd.rs
#![allow(clippy::module_inception)] use std::path::PathBuf; use clap::builder::{IntoResettable, Resettable, StyledStr}; use clap::{Parser, Subcommand, ValueEnum, ValueHint}; struct HelpTemplate; impl IntoResettable<StyledStr> for HelpTemplate { fn into_resettable(self) -> Resettable<StyledStr> { color_print::cstr!("\ {before-help}<bold><underline>{name} {version}</underline></bold> {author} https://github.com/ajeetdsouza/zoxide {about} {usage-heading} {tab}{usage} {all-args}{after-help} <bold><underline>Environment variables:</underline></bold> {tab}<bold>_ZO_DATA_DIR</bold> {tab}Path for zoxide data files {tab}<bold>_ZO_ECHO</bold> {tab}Print the matched directory before navigating to it when set to 1 {tab}<bold>_ZO_EXCLUDE_DIRS</bold> {tab}List of directory globs to be excluded {tab}<bold>_ZO_FZF_OPTS</bold> {tab}Custom flags to pass to fzf {tab}<bold>_ZO_MAXAGE</bold> {tab}Maximum total age after which entries start getting deleted {tab}<bold>_ZO_RESOLVE_SYMLINKS</bold>{tab}Resolve symlinks when storing paths").into_resettable() } } #[derive(Debug, Parser)] #[clap( about, author, help_template = HelpTemplate, disable_help_subcommand = true, propagate_version = true, version, )] pub enum Cmd { Add(Add), Edit(Edit), Import(Import), Init(Init), Query(Query), Remove(Remove), } /// Add a new directory or increment its rank #[derive(Debug, Parser)] #[clap( author, help_template = HelpTemplate, )] pub struct Add { #[clap(num_args = 1.., required = true, value_hint = ValueHint::DirPath)] pub paths: Vec<PathBuf>, /// The rank to increment the entry if it exists or initialize it with if it /// doesn't #[clap(short, long)] pub score: Option<f64>, } /// Edit the database #[derive(Debug, Parser)] #[clap( author, help_template = HelpTemplate, )] pub struct Edit { #[clap(subcommand)] pub cmd: Option<EditCommand>, } #[derive(Clone, Debug, Subcommand)] pub enum EditCommand { #[clap(hide = true)] Decrement { path: String }, #[clap(hide = true)] Delete { path: String }, #[clap(hide = true)] Increment { path: String }, #[clap(hide = true)] Reload, } /// Import entries from another application #[derive(Debug, Parser)] #[clap( author, help_template = HelpTemplate, )] pub struct Import { #[clap(value_hint = ValueHint::FilePath)] pub path: PathBuf, /// Application to import from #[clap(value_enum, long)] pub from: ImportFrom, /// Merge into existing database #[clap(long)] pub merge: bool, } #[derive(ValueEnum, Clone, Debug)] pub enum ImportFrom { Autojump, #[clap(alias = "fasd")] Z, } /// Generate shell configuration #[derive(Debug, Parser)] #[clap( author, help_template = HelpTemplate, )] pub struct Init { #[clap(value_enum)] pub shell: InitShell, /// Prevents zoxide from defining the `z` and `zi` commands #[clap(long, alias = "no-aliases")] pub no_cmd: bool, /// Changes the prefix of the `z` and `zi` commands #[clap(long, default_value = "z")] pub cmd: String, /// Changes how often zoxide increments a directory's score #[clap(value_enum, long, default_value = "pwd")] pub hook: InitHook, } #[derive(ValueEnum, Clone, Copy, Debug, Eq, PartialEq)] pub enum InitHook { None, Prompt, Pwd, } #[derive(ValueEnum, Clone, Debug)] pub enum InitShell { Bash, Elvish, Fish, Nushell, #[clap(alias = "ksh")] Posix, Powershell, Tcsh, Xonsh, Zsh, } /// Search for a directory in the database #[derive(Debug, Parser)] #[clap( author, help_template = HelpTemplate, )] pub struct Query { pub keywords: Vec<String>, /// Show unavailable directories #[clap(long, short)] pub all: bool, /// Use interactive selection #[clap(long, short, conflicts_with = "list")] pub interactive: bool, /// List all matching directories #[clap(long, short, conflicts_with = "interactive")] pub list: bool, /// Print score with results #[clap(long, short)] pub score: bool, /// Exclude the current directory #[clap(long, value_hint = ValueHint::DirPath, value_name = "path")] pub exclude: Option<String>, /// Only search within this directory #[clap(long, value_hint = ValueHint::DirPath, value_name = "path")] pub base_dir: Option<String>, } /// Remove a directory from the database #[derive(Debug, Parser)] #[clap( author, help_template = HelpTemplate, )] pub struct Remove { #[clap(value_hint = ValueHint::DirPath)] pub paths: Vec<String>, }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/db/stream.rs
src/db/stream.rs
use std::iter::Rev; use std::ops::Range; use std::path::Path; use std::{fs, path}; use glob::Pattern; use crate::db::{Database, Dir, Epoch}; use crate::util::{self, MONTH}; pub struct Stream<'a> { db: &'a mut Database, idxs: Rev<Range<usize>>, options: StreamOptions, } impl<'a> Stream<'a> { pub fn new(db: &'a mut Database, options: StreamOptions) -> Self { db.sort_by_score(options.now); let idxs = (0..db.dirs().len()).rev(); Stream { db, idxs, options } } pub fn next(&mut self) -> Option<&Dir<'_>> { while let Some(idx) = self.idxs.next() { let dir = &self.db.dirs()[idx]; if !self.filter_by_keywords(&dir.path) { continue; } if !self.filter_by_base_dir(&dir.path) { continue; } if !self.filter_by_exclude(&dir.path) { self.db.swap_remove(idx); continue; } // Exists queries are slow, this should always be checked last. if !self.filter_by_exists(&dir.path) { if dir.last_accessed < self.options.ttl { self.db.swap_remove(idx); } continue; } let dir = &self.db.dirs()[idx]; return Some(dir); } None } fn filter_by_base_dir(&self, path: &str) -> bool { match &self.options.base_dir { Some(base_dir) => Path::new(path).starts_with(base_dir), None => true, } } fn filter_by_exclude(&self, path: &str) -> bool { !self.options.exclude.iter().any(|pattern| pattern.matches(path)) } fn filter_by_exists(&self, path: &str) -> bool { if !self.options.exists { return true; } // The logic here is reversed - if we resolve symlinks when adding entries to // the database, we should not return symlinks when querying back from // the database. let resolver = if self.options.resolve_symlinks { fs::symlink_metadata } else { fs::metadata }; resolver(path).map(|metadata| metadata.is_dir()).unwrap_or_default() } fn filter_by_keywords(&self, path: &str) -> bool { let (keywords_last, keywords) = match self.options.keywords.split_last() { Some(split) => split, None => return true, }; let path = util::to_lowercase(path); let mut path = path.as_str(); match path.rfind(keywords_last) { Some(idx) => { if path[idx + keywords_last.len()..].contains(path::is_separator) { return false; } path = &path[..idx]; } None => return false, } for keyword in keywords.iter().rev() { match path.rfind(keyword) { Some(idx) => path = &path[..idx], None => return false, } } true } } pub struct StreamOptions { /// The current time. now: Epoch, /// Only directories matching these keywords will be returned. keywords: Vec<String>, /// Directories that match any of these globs will be lazily removed. exclude: Vec<Pattern>, /// Directories will only be returned if they exist on the filesystem. exists: bool, /// Whether to resolve symlinks when checking if a directory exists. resolve_symlinks: bool, /// Directories that do not exist and haven't been accessed since TTL will /// be lazily removed. ttl: Epoch, /// Only return directories within this parent directory /// Does not check if the path exists base_dir: Option<String>, } impl StreamOptions { pub fn new(now: Epoch) -> Self { StreamOptions { now, keywords: Vec::new(), exclude: Vec::new(), exists: false, resolve_symlinks: false, ttl: now.saturating_sub(3 * MONTH), base_dir: None, } } pub fn with_keywords<I>(mut self, keywords: I) -> Self where I: IntoIterator, I::Item: AsRef<str>, { self.keywords = keywords.into_iter().map(util::to_lowercase).collect(); self } pub fn with_exclude(mut self, exclude: Vec<Pattern>) -> Self { self.exclude = exclude; self } pub fn with_exists(mut self, exists: bool) -> Self { self.exists = exists; self } pub fn with_resolve_symlinks(mut self, resolve_symlinks: bool) -> Self { self.resolve_symlinks = resolve_symlinks; self } pub fn with_base_dir(mut self, base_dir: Option<String>) -> Self { self.base_dir = base_dir; self } } #[cfg(test)] mod tests { use std::path::PathBuf; use rstest::rstest; use super::*; #[rstest] // Case normalization #[case(&["fOo", "bAr"], "/foo/bar", true)] // Last component #[case(&["ba"], "/foo/bar", true)] #[case(&["fo"], "/foo/bar", false)] // Slash as suffix #[case(&["foo/"], "/foo", false)] #[case(&["foo/"], "/foo/bar", true)] #[case(&["foo/"], "/foo/bar/baz", false)] #[case(&["foo", "/"], "/foo", false)] #[case(&["foo", "/"], "/foo/bar", true)] #[case(&["foo", "/"], "/foo/bar/baz", true)] // Split components #[case(&["/", "fo", "/", "ar"], "/foo/bar", true)] #[case(&["oo/ba"], "/foo/bar", true)] // Overlap #[case(&["foo", "o", "bar"], "/foo/bar", false)] #[case(&["/foo/", "/bar"], "/foo/bar", false)] #[case(&["/foo/", "/bar"], "/foo/baz/bar", true)] fn query(#[case] keywords: &[&str], #[case] path: &str, #[case] is_match: bool) { let db = &mut Database::new(PathBuf::new(), Vec::new(), |_| Vec::new(), false); let options = StreamOptions::new(0).with_keywords(keywords.iter()); let stream = Stream::new(db, options); assert_eq!(is_match, stream.filter_by_keywords(path)); } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/db/mod.rs
src/db/mod.rs
mod dir; mod stream; use std::path::{Path, PathBuf}; use std::{fs, io}; use anyhow::{Context, Result, bail}; use bincode::Options; use ouroboros::self_referencing; pub use crate::db::dir::{Dir, Epoch, Rank}; pub use crate::db::stream::{Stream, StreamOptions}; use crate::{config, util}; #[self_referencing] pub struct Database { path: PathBuf, bytes: Vec<u8>, #[borrows(bytes)] #[covariant] pub dirs: Vec<Dir<'this>>, dirty: bool, } impl Database { const VERSION: u32 = 3; pub fn open() -> Result<Self> { let data_dir = config::data_dir()?; Self::open_dir(data_dir) } pub fn open_dir(data_dir: impl AsRef<Path>) -> Result<Self> { let data_dir = data_dir.as_ref(); let path = data_dir.join("db.zo"); let path = fs::canonicalize(&path).unwrap_or(path); match fs::read(&path) { Ok(bytes) => Self::try_new(path, bytes, |bytes| Self::deserialize(bytes), false), Err(e) if e.kind() == io::ErrorKind::NotFound => { // Create data directory, but don't create any file yet. The file will be // created later by [`Database::save`] if any data is modified. fs::create_dir_all(data_dir).with_context(|| { format!("unable to create data directory: {}", data_dir.display()) })?; Ok(Self::new(path, Vec::new(), |_| Vec::new(), false)) } Err(e) => { Err(e).with_context(|| format!("could not read from database: {}", path.display())) } } } pub fn save(&mut self) -> Result<()> { // Only write to disk if the database is modified. if !self.dirty() { return Ok(()); } let bytes = Self::serialize(self.dirs())?; util::write(self.borrow_path(), bytes).context("could not write to database")?; self.with_dirty_mut(|dirty| *dirty = false); Ok(()) } /// Increments the rank of a directory, or creates it if it does not exist. pub fn add(&mut self, path: impl AsRef<str> + Into<String>, by: Rank, now: Epoch) { self.with_dirs_mut(|dirs| match dirs.iter_mut().find(|dir| dir.path == path.as_ref()) { Some(dir) => dir.rank = (dir.rank + by).max(0.0), None => { dirs.push(Dir { path: path.into().into(), rank: by.max(0.0), last_accessed: now }) } }); self.with_dirty_mut(|dirty| *dirty = true); } /// Creates a new directory. This will create a duplicate entry if this /// directory is always in the database, it is expected that the user either /// does a check before calling this, or calls `dedup()` afterward. pub fn add_unchecked(&mut self, path: impl AsRef<str> + Into<String>, rank: Rank, now: Epoch) { self.with_dirs_mut(|dirs| { dirs.push(Dir { path: path.into().into(), rank, last_accessed: now }) }); self.with_dirty_mut(|dirty| *dirty = true); } /// Increments the rank and updates the last_accessed of a directory, or /// creates it if it does not exist. pub fn add_update(&mut self, path: impl AsRef<str> + Into<String>, by: Rank, now: Epoch) { self.with_dirs_mut(|dirs| match dirs.iter_mut().find(|dir| dir.path == path.as_ref()) { Some(dir) => { dir.rank = (dir.rank + by).max(0.0); dir.last_accessed = now; } None => { dirs.push(Dir { path: path.into().into(), rank: by.max(0.0), last_accessed: now }) } }); self.with_dirty_mut(|dirty| *dirty = true); } /// Removes the directory with `path` from the store. This does not preserve /// ordering, but is O(1). pub fn remove(&mut self, path: impl AsRef<str>) -> bool { match self.dirs().iter().position(|dir| dir.path == path.as_ref()) { Some(idx) => { self.swap_remove(idx); true } None => false, } } pub fn swap_remove(&mut self, idx: usize) { self.with_dirs_mut(|dirs| dirs.swap_remove(idx)); self.with_dirty_mut(|dirty| *dirty = true); } pub fn age(&mut self, max_age: Rank) { let mut dirty = false; self.with_dirs_mut(|dirs| { let total_age = dirs.iter().map(|dir| dir.rank).sum::<Rank>(); if total_age > max_age { let factor = 0.9 * max_age / total_age; for idx in (0..dirs.len()).rev() { let dir = &mut dirs[idx]; dir.rank *= factor; if dir.rank < 1.0 { dirs.swap_remove(idx); } } dirty = true; } }); self.with_dirty_mut(|dirty_prev| *dirty_prev |= dirty); } pub fn dedup(&mut self) { // Sort by path, so that equal paths are next to each other. self.sort_by_path(); let mut dirty = false; self.with_dirs_mut(|dirs| { for idx in (1..dirs.len()).rev() { // Check if curr_dir and next_dir have equal paths. let curr_dir = &dirs[idx]; let next_dir = &dirs[idx - 1]; if next_dir.path != curr_dir.path { continue; } // Merge curr_dir's rank and last_accessed into next_dir. let rank = curr_dir.rank; let last_accessed = curr_dir.last_accessed; let next_dir = &mut dirs[idx - 1]; next_dir.last_accessed = next_dir.last_accessed.max(last_accessed); next_dir.rank += rank; // Delete curr_dir. dirs.swap_remove(idx); dirty = true; } }); self.with_dirty_mut(|dirty_prev| *dirty_prev |= dirty); } pub fn sort_by_path(&mut self) { self.with_dirs_mut(|dirs| dirs.sort_unstable_by(|dir1, dir2| dir1.path.cmp(&dir2.path))); self.with_dirty_mut(|dirty| *dirty = true); } pub fn sort_by_score(&mut self, now: Epoch) { self.with_dirs_mut(|dirs| { dirs.sort_unstable_by(|dir1: &Dir, dir2: &Dir| { dir1.score(now).total_cmp(&dir2.score(now)) }) }); self.with_dirty_mut(|dirty| *dirty = true); } pub fn dirty(&self) -> bool { *self.borrow_dirty() } pub fn dirs(&self) -> &[Dir<'_>] { self.borrow_dirs() } fn serialize(dirs: &[Dir<'_>]) -> Result<Vec<u8>> { (|| -> bincode::Result<_> { // Preallocate buffer with combined size of sections. let buffer_size = bincode::serialized_size(&Self::VERSION)? + bincode::serialized_size(&dirs)?; let mut buffer = Vec::with_capacity(buffer_size as usize); // Serialize sections into buffer. bincode::serialize_into(&mut buffer, &Self::VERSION)?; bincode::serialize_into(&mut buffer, &dirs)?; Ok(buffer) })() .context("could not serialize database") } fn deserialize(bytes: &[u8]) -> Result<Vec<Dir<'_>>> { // Assume a maximum size for the database. This prevents bincode from throwing // strange errors when it encounters invalid data. const MAX_SIZE: u64 = 32 << 20; // 32 MiB let deserializer = &mut bincode::options().with_fixint_encoding().with_limit(MAX_SIZE); // Split bytes into sections. let version_size = deserializer.serialized_size(&Self::VERSION).unwrap() as _; if bytes.len() < version_size { bail!("could not deserialize database: corrupted data"); } let (bytes_version, bytes_dirs) = bytes.split_at(version_size); // Deserialize sections. let version = deserializer.deserialize(bytes_version)?; let dirs = match version { Self::VERSION => { deserializer.deserialize(bytes_dirs).context("could not deserialize database")? } version => { bail!("unsupported version (got {version}, supports {})", Self::VERSION) } }; Ok(dirs) } } #[cfg(test)] mod tests { use super::*; #[test] fn add() { let data_dir = tempfile::tempdir().unwrap(); let path = if cfg!(windows) { r"C:\foo\bar" } else { "/foo/bar" }; let now = 946684800; { let mut db = Database::open_dir(data_dir.path()).unwrap(); db.add(path, 1.0, now); db.add(path, 1.0, now); db.save().unwrap(); } { let db = Database::open_dir(data_dir.path()).unwrap(); assert_eq!(db.dirs().len(), 1); let dir = &db.dirs()[0]; assert_eq!(dir.path, path); assert!((dir.rank - 2.0).abs() < 0.01); assert_eq!(dir.last_accessed, now); } } #[test] fn remove() { let data_dir = tempfile::tempdir().unwrap(); let path = if cfg!(windows) { r"C:\foo\bar" } else { "/foo/bar" }; let now = 946684800; { let mut db = Database::open_dir(data_dir.path()).unwrap(); db.add(path, 1.0, now); db.save().unwrap(); } { let mut db = Database::open_dir(data_dir.path()).unwrap(); assert!(db.remove(path)); db.save().unwrap(); } { let mut db = Database::open_dir(data_dir.path()).unwrap(); assert!(db.dirs().is_empty()); assert!(!db.remove(path)); db.save().unwrap(); } } }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/src/db/dir.rs
src/db/dir.rs
use std::borrow::Cow; use std::fmt::{self, Display, Formatter}; use serde::{Deserialize, Serialize}; use crate::util::{DAY, HOUR, WEEK}; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Dir<'a> { #[serde(borrow)] pub path: Cow<'a, str>, pub rank: Rank, pub last_accessed: Epoch, } impl Dir<'_> { pub fn display(&self) -> DirDisplay<'_> { DirDisplay::new(self) } pub fn score(&self, now: Epoch) -> Rank { // The older the entry, the lesser its importance. let duration = now.saturating_sub(self.last_accessed); if duration < HOUR { self.rank * 4.0 } else if duration < DAY { self.rank * 2.0 } else if duration < WEEK { self.rank * 0.5 } else { self.rank * 0.25 } } } pub struct DirDisplay<'a> { dir: &'a Dir<'a>, now: Option<Epoch>, separator: char, } impl<'a> DirDisplay<'a> { fn new(dir: &'a Dir) -> Self { Self { dir, separator: ' ', now: None } } pub fn with_score(mut self, now: Epoch) -> Self { self.now = Some(now); self } pub fn with_separator(mut self, separator: char) -> Self { self.separator = separator; self } } impl Display for DirDisplay<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { if let Some(now) = self.now { let score = self.dir.score(now).clamp(0.0, 9999.0); write!(f, "{score:>6.1}{}", self.separator)?; } write!(f, "{}", self.dir.path) } } pub type Rank = f64; pub type Epoch = u64;
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
ajeetdsouza/zoxide
https://github.com/ajeetdsouza/zoxide/blob/f00fe0f0aeaeaf8fda48ca467c706a5174830b77/tests/completions.rs
tests/completions.rs
//! Test clap generated completions. #![cfg(feature = "nix-dev")] use assert_cmd::Command; #[test] fn completions_bash() { let source = include_str!("../contrib/completions/zoxide.bash"); Command::new("bash") .args(["--noprofile", "--norc", "-c", source]) .assert() .success() .stdout("") .stderr(""); } // Elvish: the completions file uses editor commands to add completions to the // shell. However, Elvish does not support running editor commands from a // script, so we can't create a test for this. See: https://github.com/elves/elvish/issues/1299 #[test] fn completions_fish() { let source = include_str!("../contrib/completions/zoxide.fish"); let tempdir = tempfile::tempdir().unwrap(); let tempdir = tempdir.path().to_str().unwrap(); Command::new("fish") .env("HOME", tempdir) .args(["--command", source, "--private"]) .assert() .success() .stdout("") .stderr(""); } #[test] fn completions_powershell() { let source = include_str!("../contrib/completions/_zoxide.ps1"); Command::new("pwsh") .args(["-NoLogo", "-NonInteractive", "-NoProfile", "-Command", source]) .assert() .success() .stdout("") .stderr(""); } #[test] fn completions_zsh() { let source = r#" set -eu completions='./contrib/completions' test -d "$completions" fpath=("$completions" $fpath) autoload -Uz compinit compinit -u "#; Command::new("zsh").args(["-c", source, "--no-rcs"]).assert().success().stdout("").stderr(""); }
rust
MIT
f00fe0f0aeaeaf8fda48ca467c706a5174830b77
2026-01-04T15:32:37.541534Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/06-routing/link.rs
examples/06-routing/link.rs
//! How to use links in Dioxus //! //! The `router` crate gives us a `Link` component which is a much more powerful version of the standard HTML link. //! However, you can use the traditional `<a>` tag if you want to build your own `Link` component. //! //! The `Link` component integrates with the Router and is smart enough to detect if the link is internal or external. //! It also allows taking any `Route` as a target, making your links typesafe use dioxus::prelude::*; const STYLE: Asset = asset!("/examples/assets/links.css"); fn main() { dioxus::launch(app); } fn app() -> Element { rsx! ( Stylesheet { href: STYLE } Router::<Route> {} ) } #[derive(Routable, Clone)] #[rustfmt::skip] enum Route { #[layout(Header)] #[route("/")] Home {}, #[route("/default-links")] DefaultLinks {}, #[route("/settings")] Settings {}, } #[component] fn Header() -> Element { rsx! { h1 { "Your app here" } nav { id: "nav", Link { to: Route::Home {}, "home" } Link { to: Route::DefaultLinks {}, "default links" } Link { to: Route::Settings {}, "settings" } } Outlet::<Route> {} } } #[component] fn Home() -> Element { rsx!( h1 { "Home" } ) } #[component] fn Settings() -> Element { rsx!( h1 { "Settings" } ) } #[component] fn DefaultLinks() -> Element { rsx! { // Just some default links div { id: "external-links", // This link will open in a webbrowser a { href: "http://dioxuslabs.com/", "Default link - links outside of your app" } // This link will do nothing - we're preventing the default behavior // It will just log "Hello Dioxus" to the console a { href: "http://dioxuslabs.com/", onclick: |event| { event.prevent_default(); println!("Hello Dioxus") }, "Custom event link - links inside of your app" } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/06-routing/router_restore_scroll.rs
examples/06-routing/router_restore_scroll.rs
use std::rc::Rc; use dioxus::html::geometry::PixelsVector2D; use dioxus::prelude::*; #[derive(Clone, Routable, Debug, PartialEq)] enum Route { #[route("/")] Home {}, #[route("/blog/:id")] Blog { id: i32 }, } fn main() { dioxus::launch(App); } #[component] fn App() -> Element { use_context_provider(|| Signal::new(Scroll::default())); rsx! { Router::<Route> {} } } #[component] fn Blog(id: i32) -> Element { rsx! { GoBackButton { "Go back" } div { "Blog post {id}" } } } type Scroll = Option<PixelsVector2D>; #[component] fn Home() -> Element { let mut element: Signal<Option<Rc<MountedData>>> = use_signal(|| None); let mut scroll = use_context::<Signal<Scroll>>(); _ = use_resource(move || async move { if let (Some(element), Some(scroll)) = (element.read().as_ref(), *scroll.peek()) { element .scroll(scroll, ScrollBehavior::Instant) .await .unwrap(); } }); rsx! { div { height: "300px", overflow_y: "auto", border: "1px solid black", onmounted: move |event| element.set(Some(event.data())), onscroll: move |_| async move { if let Some(element) = element.cloned() { scroll.set(Some(element.get_scroll_offset().await.unwrap())) } }, for i in 0..100 { div { height: "20px", Link { to: Route::Blog { id: i }, "Blog {i}" } } } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/06-routing/router.rs
examples/06-routing/router.rs
//! An advanced usage of the router with nested routes and redirects. //! //! Dioxus implements an enum-based router, which allows you to define your routes in a type-safe way. //! However, since we need to bake quite a bit of logic into the enum, we have to add some extra syntax. //! //! Note that you don't need to use advanced features like nest, redirect, etc, since these can all be implemented //! manually, but they are provided as a convenience. use dioxus::prelude::*; const STYLE: Asset = asset!("/examples/assets/router.css"); fn main() { dioxus::launch(|| { rsx! { Stylesheet { href: STYLE } Router::<Route> {} } }); } // Turn off rustfmt since we're doing layouts and routes in the same enum #[derive(Routable, Clone, Debug, PartialEq)] #[rustfmt::skip] #[allow(clippy::empty_line_after_outer_attr)] enum Route { // Wrap Home in a Navbar Layout #[layout(NavBar)] // The default route is always "/" unless otherwise specified #[route("/")] Home {}, // Wrap the next routes in a layout and a nest #[nest("/blog")] #[layout(Blog)] // At "/blog", we want to show a list of blog posts #[route("/")] BlogList {}, // At "/blog/:name", we want to show a specific blog post, using the name slug #[route("/:name")] BlogPost { name: String }, // We need to end the blog layout and nest // Note we don't need either - we could've just done `/blog/` and `/blog/:name` without nesting, // but it's a bit cleaner this way #[end_layout] #[end_nest] // And the regular page layout #[end_layout] // Add some redirects for the `/myblog` route #[nest("/myblog")] #[redirect("/", || Route::BlogList {})] #[redirect("/:name", |name: String| Route::BlogPost { name })] #[end_nest] // Finally, we need to handle the 404 page #[route("/:..route")] PageNotFound { route: Vec<String>, }, } #[component] fn NavBar() -> Element { rsx! { nav { id: "navbar", Link { to: Route::Home {}, "Home" } Link { to: Route::BlogList {}, "Blog" } } Outlet::<Route> {} } } #[component] fn Home() -> Element { rsx! { h1 { "Welcome to the Dioxus Blog!" } } } #[component] fn Blog() -> Element { rsx! { h1 { "Blog" } Outlet::<Route> {} } } #[component] fn BlogList() -> Element { rsx! { h2 { "Choose a post" } div { id: "blog-list", Link { to: Route::BlogPost { name: "Blog post 1".into() }, "Read the first blog post" } Link { to: Route::BlogPost { name: "Blog post 2".into() }, "Read the second blog post" } } } } // We can use the `name` slug to show a specific blog post // In theory we could read from the filesystem or a database here #[component] fn BlogPost(name: String) -> Element { let contents = match name.as_str() { "Blog post 1" => "This is the first blog post. It's not very interesting.", "Blog post 2" => "This is the second blog post. It's not very interesting either.", _ => "This blog post doesn't exist.", }; rsx! { h2 { "{name}" } p { "{contents}" } } } #[component] fn PageNotFound(route: Vec<String>) -> Element { rsx! { h1 { "Page not found" } p { "We are terribly sorry, but the page you requested doesn't exist." } pre { color: "red", "log:\nattempted to navigate to: {route:?}" } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/06-routing/flat_router.rs
examples/06-routing/flat_router.rs
//! This example shows how to use the `Router` component to create a simple navigation system. //! The more complex router example uses all of the router features, while this simple example showcases //! just the `Layout` and `Route` features. //! //! Layouts let you wrap chunks of your app with a component. This is useful for things like a footers, heeaders, etc. //! Routes are enum variants with that match the name of a component in scope. This way you can create a new route //! in your app simply by adding the variant to the enum and creating a new component with the same name. You can //! override this of course. use dioxus::prelude::*; const STYLE: Asset = asset!("/examples/assets/flat_router.css"); fn main() { dioxus::launch(|| { rsx! { Stylesheet { href: STYLE } Router::<Route> {} } }) } #[derive(Routable, Clone)] #[rustfmt::skip] enum Route { #[layout(Footer)] // wrap the entire app in a footer #[route("/")] Home {}, #[route("/games")] Games {}, #[route("/play")] Play {}, #[route("/settings")] Settings {}, } #[component] fn Footer() -> Element { rsx! { nav { Link { to: Route::Home {}, class: "nav-btn", "Home" } Link { to: Route::Games {}, class: "nav-btn", "Games" } Link { to: Route::Play {}, class: "nav-btn", "Play" } Link { to: Route::Settings {}, class: "nav-btn", "Settings" } } div { id: "content", Outlet::<Route> {} } } } #[component] fn Home() -> Element { rsx!( h1 { "Home" } p { "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." } ) } #[component] fn Games() -> Element { rsx!( h1 { "Games" } // Dummy text that talks about video games p { "Lorem games are sit amet Sed do eiusmod tempor et dolore magna aliqua." } ) } #[component] fn Play() -> Element { rsx!( h1 { "Play" } p { "Always play with your full heart adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." } ) } #[component] fn Settings() -> Element { rsx!( h1 { "Settings" } p { "Settings are consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." } ) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/06-routing/simple_router.rs
examples/06-routing/simple_router.rs
//! A simple example of a router with a few routes and a nav bar. use dioxus::prelude::*; fn main() { // launch the router, using our `Route` component as the generic type // This will automatically boot the app to "/" unless otherwise specified dioxus::launch(|| rsx! { Router::<Route> {} }); } /// By default, the Routable derive will use the name of the variant as the route /// You can also specify a specific component by adding the Component name to the `#[route]` attribute #[rustfmt::skip] #[derive(Routable, Clone, PartialEq)] enum Route { // Wrap the app in a Nav layout #[layout(Nav)] #[route("/")] Homepage {}, #[route("/blog/:id")] Blog { id: String }, } #[component] fn Homepage() -> Element { rsx! { h1 { "Welcome home" } } } #[component] fn Blog(id: String) -> Element { rsx! { h1 { "How to make: " } p { "{id}" } } } /// A simple nav bar that links to the homepage and blog pages /// /// The `Route` enum gives up typesafe routes, allowing us to rename routes and serialize them automatically #[component] fn Nav() -> Element { rsx! { nav { li { Link { to: Route::Homepage {}, "Go home" } } li { Link { to: Route::Blog { id: "Brownies".to_string(), }, onclick: move |_| { println!("Clicked on Brownies") }, "Learn Brownies" } } li { Link { to: Route::Blog { id: "Cookies".to_string(), }, "Learn Cookies" } } } div { Outlet::<Route> {} } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/06-routing/router_resource.rs
examples/06-routing/router_resource.rs
//! Example: Updating components with use_resource //! ----------------- //! //! This example shows how to use ReadSignal to make props reactive //! when linking to it from the same component, when using use_resource use dioxus::prelude::*; #[derive(Clone, Routable, Debug, PartialEq)] enum Route { #[route("/")] Home {}, #[route("/blog/:id")] Blog { id: i32 }, } fn main() { dioxus::launch(App); } #[component] fn App() -> Element { rsx! { Router::<Route> {} } } // We use id: ReadSignal<i32> instead of id: i32 to make id work with reactive hooks // Any i32 we pass in will automatically be converted into a ReadSignal<i32> #[component] fn Blog(id: ReadSignal<i32>) -> Element { async fn future(n: i32) -> i32 { n } // Because we accept ReadSignal<i32> instead of i32, the resource will automatically subscribe to the id when we read it let res = use_resource(move || future(id())); match res() { Some(id) => rsx! { div { "Blog post {id}" } for i in 0..10 { div { Link { to: Route::Blog { id: i }, "Go to Blog {i}" } } } }, None => rsx! {}, } } #[component] fn Home() -> Element { rsx! { Link { to: Route::Blog { id: 0 }, "Go to blog" } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/06-routing/query_segment_search.rs
examples/06-routing/query_segment_search.rs
//! This example shows how to access and use query segments present in an url on the web. //! //! The enum router makes it easy to use your route as state in your app. This example shows how to use the router to encode search text into the url and decode it back into a string. //! //! Run this example on desktop with //! ```sh //! dx serve --example query_segment_search //! ``` //! Or on web with //! ```sh //! dx serve --platform web --features web --example query_segment_search -- --no-default-features //! ``` use dioxus::prelude::*; fn main() { dioxus::launch(|| { rsx! { Router::<Route> {} } }); } #[derive(Routable, Clone, Debug, PartialEq)] #[rustfmt::skip] enum Route { #[route("/")] Home {}, // The each query segment must implement <https://docs.rs/dioxus-router/latest/dioxus_router/routable/trait.FromQueryArgument.html> and Display. // You can use multiple query segments separated by `&`s. #[route("/search?:query&:word_count")] Search { query: String, word_count: usize, }, } #[component] fn Home() -> Element { // Display a list of example searches in the home page rsx! { ul { li { Link { to: Route::Search { query: "hello".to_string(), word_count: 1 }, "Search for results containing 'hello' and at least one word" } } li { Link { to: Route::Search { query: "dioxus".to_string(), word_count: 2 }, "Search for results containing 'dioxus' and at least two word" } } } } } // Instead of accepting String and usize directly, we use ReadSignal to make the parameters `Copy` and let us subscribe to them automatically inside the meme #[component] fn Search(query: ReadSignal<String>, word_count: ReadSignal<usize>) -> Element { const ITEMS: &[&str] = &[ "hello", "world", "hello world", "hello dioxus", "hello dioxus-router", ]; // Find all results that contain the query and the right number of words // This memo will automatically rerun when the query or word count changes because we read the signals inside the closure let results = use_memo(move || { ITEMS .iter() .filter(|item| { item.contains(&*query.read()) && item.split_whitespace().count() >= word_count() }) .collect::<Vec<_>>() }); rsx! { h1 { "Search for {query}" } input { oninput: move |e| { // Every time the query changes, we change the current route to the new query navigator().replace(Route::Search { query: e.value(), word_count: word_count(), }); }, value: "{query}", } input { r#type: "number", oninput: move |e| { // Every time the word count changes, we change the current route to the new query if let Ok(word_count) = e.value().parse() { navigator().replace(Route::Search { query: query(), word_count, }); } }, value: "{word_count}", } for result in results.read().iter() { div { "{result}" } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/06-routing/hash_fragment_state.rs
examples/06-routing/hash_fragment_state.rs
//! This example shows how to use the hash segment to store state in the url. //! //! You can set up two way data binding between the url hash and signals. //! //! Run this example on desktop with //! ```sh //! dx serve --example hash_fragment_state --features=ciborium,base64 //! ``` //! Or on web with //! ```sh //! dx serve --platform web --features web --example hash_fragment_state --features=ciborium,base64 -- --no-default-features //! ``` use std::{fmt::Display, str::FromStr}; use base64::engine::general_purpose::STANDARD; use base64::Engine; use dioxus::prelude::*; use serde::{Deserialize, Serialize}; fn main() { dioxus::launch(|| { rsx! { Router::<Route> {} } }); } #[derive(Routable, Clone, Debug, PartialEq)] #[rustfmt::skip] enum Route { #[route("/#:url_hash")] Home { url_hash: State, }, } // You can use a custom type with the hash segment as long as it implements Display, FromStr and Default #[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)] struct State { counters: Vec<usize>, } // Display the state in a way that can be parsed by FromStr impl Display for State { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut serialized = Vec::new(); if ciborium::into_writer(self, &mut serialized).is_ok() { write!(f, "{}", STANDARD.encode(serialized))?; } Ok(()) } } enum StateParseError { DecodeError(base64::DecodeError), CiboriumError(ciborium::de::Error<std::io::Error>), } impl std::fmt::Display for StateParseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::DecodeError(err) => write!(f, "Failed to decode base64: {}", err), Self::CiboriumError(err) => write!(f, "Failed to deserialize: {}", err), } } } // Parse the state from a string that was created by Display impl FromStr for State { type Err = StateParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let decompressed = STANDARD .decode(s.as_bytes()) .map_err(StateParseError::DecodeError)?; let parsed = ciborium::from_reader(std::io::Cursor::new(decompressed)) .map_err(StateParseError::CiboriumError)?; Ok(parsed) } } #[component] fn Home(url_hash: ReadSignal<State>) -> Element { // The initial state of the state comes from the url hash let mut state = use_signal(&*url_hash); // Change the state signal when the url hash changes use_memo(move || { if *state.peek() != *url_hash.read() { state.set(url_hash()); } }); // Change the url hash when the state changes use_memo(move || { if *state.read() != *url_hash.peek() { navigator().replace(Route::Home { url_hash: state() }); } }); rsx! { button { onclick: move |_| state.write().counters.clear(), "Reset" } button { onclick: move |_| { state.write().counters.push(0); }, "Add Counter" } for counter in 0..state.read().counters.len() { div { button { onclick: move |_| { state.write().counters.remove(counter); }, "Remove" } button { onclick: move |_| { state.write().counters[counter] += 1; }, "Count: {state.read().counters[counter]}" } } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/scripts/scrape_examples.rs
examples/scripts/scrape_examples.rs
use std::path::PathBuf; struct Example { name: String, path: PathBuf, } fn main() { let dir = PathBuf::from("/Users/jonathankelley/Development/dioxus/examples"); let out_file = PathBuf::from("/Users/jonathankelley/Development/dioxus/target/decl.toml"); let mut out_items = vec![]; // Iterate through the sub-directories of the examples directory for dir in dir.read_dir().unwrap().flatten() { // For each sub-directory, walk it too, collecting .rs files let Ok(dir) = dir.path().read_dir() else { continue; }; for dir in dir.flatten() { let path = dir.path(); if path.extension().and_then(|s| s.to_str()) == Some("rs") { let file_stem = path.file_stem().and_then(|s| s.to_str()).unwrap(); let workspace_path = path .strip_prefix("/Users/jonathankelley/Development/dioxus") .unwrap(); out_items.push(Example { name: file_stem.to_string(), path: workspace_path.to_path_buf(), }); } } } let mut out_toml = String::new(); out_items.sort_by(|a, b| a.path.cmp(&b.path)); for item in out_items { out_toml.push_str(&format!( "[[example]]\nname = \"{}\"\npath = \"{}\"\ndoc-scrape-examples = true\n\n", item.name, item.path.display() )); } std::fs::write(out_file, out_toml).unwrap(); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/read_size.rs
examples/08-apis/read_size.rs
//! Read the size of elements using the MountedData struct. //! //! Whenever an Element is finally mounted to the Dom, its data is available to be read. //! These fields can typically only be read asynchronously, since various renderers need to release the main thread to //! perform layout and painting. use std::rc::Rc; use dioxus::{html::geometry::euclid::Rect, prelude::*}; fn main() { dioxus::launch(app); } fn app() -> Element { let mut div_element = use_signal(|| None as Option<Rc<MountedData>>); let mut dimensions = use_signal(Rect::zero); let read_dims = move |_| async move { let read = div_element.read(); let client_rect = read.as_ref().map(|el| el.get_client_rect()); if let Some(client_rect) = client_rect { if let Ok(rect) = client_rect.await { dimensions.set(rect); } } }; rsx! { Stylesheet { href: asset!("/examples/assets/read_size.css") } div { width: "50%", height: "50%", background_color: "red", onmounted: move |cx| div_element.set(Some(cx.data())), "This element is {dimensions():?}" } button { onclick: read_dims, "Read dimensions" } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/multiwindow_with_tray_icon.rs
examples/08-apis/multiwindow_with_tray_icon.rs
//! Multiwindow with tray icon example //! //! This example shows how to implement a simple multiwindow application and tray icon using dioxus. //! This works by spawning a new window when the user clicks a button. We have to build a new virtualdom which has its //! own context, root elements, etc. //! //! This is useful for apps that incorporate settings panels or persistent windows like Raycast. use dioxus::desktop::{ WindowCloseBehaviour, trayicon::{default_tray_icon, init_tray_icon}, window, }; use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { use_hook(|| { // Set the close behavior for the main window // This will hide the window instead of closing it when the user clicks the close button window().set_close_behavior(WindowCloseBehaviour::WindowHides); // Initialize the tray icon with a default icon and no menu // This will provide the tray into context for the application init_tray_icon(default_tray_icon(), None) }); rsx! { button { onclick: move |_| { window().new_window(VirtualDom::new(popup), Default::default()); }, "New Window" } } } fn popup() -> Element { rsx! { div { "This is a popup window!" } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/window_focus.rs
examples/08-apis/window_focus.rs
//! Listen for window focus events using a wry event handler //! //! This example shows how to use the use_wry_event_handler hook to listen for window focus events. //! We can intercept any Wry event, but in this case we're only interested in the WindowEvent::Focused event. //! //! This lets you do things like backgrounding tasks, pausing animations, or changing the UI when the window is focused or not. use dioxus::desktop::tao::event::Event as WryEvent; use dioxus::desktop::tao::event::WindowEvent; use dioxus::desktop::use_wry_event_handler; use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { let mut focused = use_signal(|| true); use_wry_event_handler(move |event, _| { if let WryEvent::WindowEvent { event: WindowEvent::Focused(new_focused), .. } = event { focused.set(*new_focused) } }); rsx! { div { width: "100%", height: "100%", display: "flex", flex_direction: "column", align_items: "center", if focused() { "This window is focused!" } else { "This window is not focused!" } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/shortcut.rs
examples/08-apis/shortcut.rs
//! Add global shortcuts to your app while a component is active //! //! This demo shows how to add a global shortcut to your app that toggles a signal. You could use this to implement //! a raycast-type app, or to add a global shortcut to your app that toggles a component on and off. //! //! These are *global* shortcuts, so they will work even if your app is not in focus. use dioxus::desktop::{HotKeyState, use_global_shortcut}; use dioxus::prelude::*; fn main() { dioxus::LaunchBuilder::desktop().launch(app); } fn app() -> Element { let mut toggled = use_signal(|| false); _ = use_global_shortcut("ctrl+s", move |state| { if state == HotKeyState::Pressed { toggled.toggle(); } }); rsx!("toggle: {toggled}") }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/title.rs
examples/08-apis/title.rs
//! This example shows how to set the title of the page or window with the Title component use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { let mut count = use_signal(|| 0); rsx! { div { // You can set the title of the page with the Title component // In web applications, this sets the title in the head. // On desktop, it sets the window title Title { "My Application (Count {count})" } button { onclick: move |_| count += 1, "Up high!" } button { onclick: move |_| count -= 1, "Down low!" } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/multiwindow.rs
examples/08-apis/multiwindow.rs
//! Multiwindow example //! //! This example shows how to implement a simple multiwindow application using dioxus. //! This works by spawning a new window when the user clicks a button. We have to build a new virtualdom which has its //! own context, root elements, etc. use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { let onclick = move |_| { dioxus::desktop::window().new_window(VirtualDom::new(popup), Default::default()); }; rsx! { button { onclick, "New Window" } } } fn popup() -> Element { let mut count = use_signal(|| 0); rsx! { div { h1 { "Popup Window" } p { "Count: {count}" } button { onclick: move |_| count += 1, "Increment" } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/form.rs
examples/08-apis/form.rs
//! Forms //! //! Dioxus forms deviate slightly from html, automatically returning all named inputs //! in the "values" field. use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { let mut values = use_signal(Vec::new); let mut submitted_values = use_signal(Vec::new); rsx! { div { style: "display: flex", div { style: "width: 50%", h1 { "Form" } if !submitted_values.read().is_empty() { h2 { "Submitted! ✅" } } // The form element is used to create an HTML form for user input // You can attach regular attributes to it form { id: "cool-form", style: "display: flex; flex-direction: column;", // You can attach a handler to the entire form oninput: move |ev| { println!("Input event: {:#?}", ev); values.set(ev.values()); }, // On desktop/liveview, the form will not navigate the page - the expectation is that you handle // The form event. // However, if your form doesn't have a submit handler, it might navigate the page depending on the webview. // We suggest always attaching a submit handler to the form. onsubmit: move |ev| { println!("Submit event: {:#?}", ev); submitted_values.set(ev.values()); }, // Regular text inputs with handlers label { r#for: "username", "Username" } input { r#type: "text", name: "username", oninput: move |ev| { println!("setting username"); values.set(ev.values()); } } // And then the various inputs that might exist // Note for a value to be returned in .values(), it must be named! label { r#for: "full-name", "Full Name" } input { r#type: "text", name: "full-name" } input { r#type: "text", name: "full-name" } label { r#for: "email", "Email (matching <name>@example.com)" } input { r#type: "email", size: "30", id: "email", name: "email" } label { r#for: "password", "Password" } input { r#type: "password", name: "password" } label { r#for: "color", "Color" } input { r#type: "radio", checked: true, name: "color", value: "red" } input { r#type: "radio", name: "color", value: "blue" } input { r#type: "radio", name: "color", value: "green" } // Select multiple comes in as a comma separated list of selected values // You should split them on the comma to get the values manually label { r#for: "country", "Country" } select { name: "country", multiple: true, oninput: move |ev| { println!("Input event: {:#?}", ev); println!("Values: {:#?}", ev.value().split(',').collect::<Vec<_>>()); }, option { value: "usa", "USA" } option { value: "canada", "Canada" } option { value: "mexico", "Mexico" } } // Safari can be quirky with color inputs on mac. // We recommend always providing a text input for color as a fallback. label { r#for: "color", "Color" } input { r#type: "color", value: "#000002", name: "head", id: "head" } // Dates! input { min: "2018-01-01", value: "2018-07-22", r#type: "date", name: "trip-start", max: "2025-12-31", id: "start" } // CHekcboxes label { r#for: "cbox", "Color" } div { label { r#for: "cbox-red", "red" } input { r#type: "checkbox", checked: true, name: "cbox", value: "red", id: "cbox-red" } } div { label { r#for: "cbox-blue", "blue" } input { r#type: "checkbox", name: "cbox", value: "blue", id: "cbox-blue" } } div { label { r#for: "cbox-green", "green" } input { r#type: "checkbox", name: "cbox", value: "green", id: "cbox-green" } } div { label { r#for: "cbox-yellow", "yellow" } input { r#type: "checkbox", name: "cbox", value: "yellow", id: "cbox-yellow" } } // File input label { r#for: "headshot", "Headshot" } input { r#type: "file", name: "headshot", id: "headshot", multiple: true, accept: ".png,.jpg,.jpeg" } // Buttons will submit your form by default. button { r#type: "submit", value: "Submit", "Submit the form" } } } div { style: "width: 50%", h1 { "Oninput Values" } pre { "{values:#?}" } } } button { onclick: move |_| { println!("Values: {:#?}", values.read()); }, "Log values" } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/scroll_to_offset.rs
examples/08-apis/scroll_to_offset.rs
//! Scroll elements using their MountedData //! //! Dioxus exposes a few helpful APIs around elements (mimicking the DOM APIs) to allow you to interact with elements //! across the renderers. This includes scrolling, reading dimensions, and more. //! //! In this example we demonstrate how to scroll to a given y offset of the scrollable parent using the `scroll` method on the `MountedData` use dioxus::html::geometry::PixelsVector2D; use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { rsx! { ScrollToCoordinates {} ScrollToCoordinates {} } } #[component] fn ScrollToCoordinates() -> Element { let mut element = use_signal(|| None); rsx! { div { border: "1px solid black", position: "relative", div { height: "300px", overflow_y: "auto", onmounted: move |event| element.set(Some(event.data())), for i in 0..100 { div { height: "20px", "Item {i}" } } } div { position: "absolute", top: 0, right: 0, input { r#type: "number", min: "0", max: "99", oninput: move |event| async move { if let Some(ul) = element.cloned() { let data = event.data(); if let Ok(value) = data.parsed::<f64>() { ul.scroll(PixelsVector2D::new(0.0, 20.0 * value), ScrollBehavior::Smooth) .await .unwrap(); } } }, } } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/window_event.rs
examples/08-apis/window_event.rs
//! This example demonstrates how to handle window events and change window properties. //! //! We're able to do things like: //! - implement window dragging //! - toggle fullscreen //! - toggle always on top //! - toggle window decorations //! - change the window title //! //! The entire featuresuite of wry and tao is available to you use dioxus::desktop::{Config, WindowBuilder, window}; use dioxus::prelude::*; fn main() { dioxus::LaunchBuilder::desktop() .with_cfg( Config::new().with_window( WindowBuilder::new() .with_title("Borderless Window") .with_decorations(false), ), ) .launch(app) } fn app() -> Element { rsx!( document::Link { href: "https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css", rel: "stylesheet" } Header {} div { class: "container mx-auto", div { class: "grid grid-cols-5", SetOnTop {} SetDecorations {} SetTitle {} } } ) } #[component] fn Header() -> Element { let mut fullscreen = use_signal(|| false); rsx! { header { class: "text-gray-400 bg-gray-900 body-font", onmousedown: move |_| window().drag(), div { class: "container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center", a { class: "flex title-font font-medium items-center text-white mb-4 md:mb-0", span { class: "ml-3 text-xl", "Dioxus" } } nav { class: "md:ml-auto flex flex-wrap items-center text-base justify-center" } // Set the window to minimized button { class: "inline-flex items-center bg-gray-800 border-0 py-1 px-3 focus:outline-none hover:bg-gray-700 rounded text-base mt-4 md:mt-0", onmousedown: |evt| evt.stop_propagation(), onclick: move |_| window().set_minimized(true), "Minimize" } // Toggle fullscreen button { class: "inline-flex items-center bg-gray-800 border-0 py-1 px-3 focus:outline-none hover:bg-gray-700 rounded text-base mt-4 md:mt-0", onmousedown: |evt| evt.stop_propagation(), onclick: move |_| { window().set_fullscreen(!fullscreen()); window().set_resizable(fullscreen()); fullscreen.toggle(); }, "Fullscreen" } // Close the window // If the window is the last window open, the app will close, if you configured the close behavior to do so button { class: "inline-flex items-center bg-gray-800 border-0 py-1 px-3 focus:outline-none hover:bg-gray-700 rounded text-base mt-4 md:mt-0", onmousedown: |evt| evt.stop_propagation(), onclick: move |_| window().close(), "Close" } } } } } #[component] fn SetOnTop() -> Element { let mut always_on_top = use_signal(|| false); rsx! { div { button { class: "inline-flex items-center text-white bg-green-500 border-0 py-1 px-3 hover:bg-green-700 rounded", onmousedown: |evt| evt.stop_propagation(), onclick: move |_| { window().set_always_on_top(!always_on_top()); always_on_top.toggle(); }, "Always On Top" } } } } #[component] fn SetDecorations() -> Element { let mut decorations = use_signal(|| false); rsx! { div { button { class: "inline-flex items-center text-white bg-blue-500 border-0 py-1 px-3 hover:bg-green-700 rounded", onmousedown: |evt| evt.stop_propagation(), onclick: move |_| { window().set_decorations(!decorations()); decorations.toggle(); }, "Set Decorations" } } } } #[component] fn SetTitle() -> Element { rsx! { div { button { class: "inline-flex items-center text-white bg-blue-500 border-0 py-1 px-3 hover:bg-green-700 rounded", onmousedown: |evt| evt.stop_propagation(), onclick: move |_| window().set_title("Dioxus Application"), "Change Title" } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/window_zoom.rs
examples/08-apis/window_zoom.rs
//! Adjust the zoom of a desktop app //! //! This example shows how to adjust the zoom of a desktop app using the webview.zoom method. use dioxus::prelude::*; fn main() { dioxus::LaunchBuilder::desktop().launch(app); } fn app() -> Element { let mut level = use_signal(|| 1.0); rsx! { h1 { "Zoom level: {level}" } p { "Change the zoom level of the webview by typing a number in the input below." } input { r#type: "number", value: "{level}", oninput: move |e| { if let Ok(new_zoom) = e.value().parse::<f64>() { level.set(new_zoom); _ = dioxus::desktop::window().webview.zoom(new_zoom); } } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/file_upload.rs
examples/08-apis/file_upload.rs
//! This example shows how to use the `file` methods on FormEvent and DragEvent to handle file uploads and drops. //! //! Dioxus intercepts these events and provides a Rusty interface to the file data. Since we want this interface to //! be crossplatform, use dioxus::html::HasFileData; use dioxus::prelude::*; use dioxus_html::FileData; const STYLE: Asset = asset!("/examples/assets/file_upload.css"); fn main() { dioxus::launch(app); } struct UploadedFile { name: String, contents: String, } fn app() -> Element { let mut enable_directory_upload = use_signal(|| false); let mut files_uploaded = use_signal(|| Vec::new() as Vec<UploadedFile>); let mut hovered = use_signal(|| false); let upload_files = move |files: Vec<FileData>| async move { for file in files { let filename = file.name(); if let Ok(contents) = file.read_string().await { files_uploaded.push(UploadedFile { name: filename, contents, }); } else { files_uploaded.push(UploadedFile { name: filename, contents: "Failed to read file".into(), }); } } }; rsx! { Stylesheet { href: STYLE } h1 { "File Upload Example" } p { "Drop a .txt, .rs, or .js file here to read it" } button { onclick: move |_| files_uploaded.clear(), "Clear files" } div { label { r#for: "directory-upload", "Enable directory upload" } input { r#type: "checkbox", id: "directory-upload", checked: enable_directory_upload, oninput: move |evt| enable_directory_upload.set(evt.checked()), } } div { label { r#for: "textreader", "Upload text/rust files and read them" } input { r#type: "file", accept: ".txt,.rs,.js", multiple: true, name: "textreader", directory: enable_directory_upload, onchange: move |evt| async move { upload_files(evt.files()).await }, } } div { id: "drop-zone", background_color: if hovered() { "lightblue" } else { "lightgray" }, ondragover: move |evt| { evt.prevent_default(); hovered.set(true) }, ondragleave: move |_| hovered.set(false), ondrop: move |evt| async move { evt.prevent_default(); hovered.set(false); upload_files(evt.files()).await; }, "Drop files here" } ul { for file in files_uploaded.read().iter().rev() { li { span { "{file.name}" } pre { "{file.contents}" } } } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/custom_menu.rs
examples/08-apis/custom_menu.rs
//! This example shows how to use a custom menu bar with Dioxus desktop. //! This example is not supported on the mobile or web renderers. use dioxus::desktop::{muda::*, use_muda_event_handler}; use dioxus::prelude::*; fn main() { // Create a menu bar that only contains the edit menu let menu = Menu::new(); let edit_menu = Submenu::new("Edit", true); edit_menu .append_items(&[ &PredefinedMenuItem::undo(None), &PredefinedMenuItem::redo(None), &PredefinedMenuItem::separator(), &PredefinedMenuItem::cut(None), &PredefinedMenuItem::copy(None), &PredefinedMenuItem::paste(None), &PredefinedMenuItem::select_all(None), &MenuItem::with_id("switch-text", "Switch text", true, None), ]) .unwrap(); menu.append(&edit_menu).unwrap(); // Create a desktop config that overrides the default menu with the custom menu let config = dioxus::desktop::Config::new().with_menu(menu); // Launch the app with the custom menu dioxus::LaunchBuilder::new().with_cfg(config).launch(app) } fn app() -> Element { let mut text = use_signal(String::new); // You can use the `use_muda_event_handler` hook to run code when a menu event is triggered. use_muda_event_handler(move |muda_event| { if muda_event.id() == "switch-text" { text.set("Switched to text".to_string()); } }); rsx! { div { h1 { "Custom Menu" } p { "Text: {text}" } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/on_resize.rs
examples/08-apis/on_resize.rs
//! Run a callback //! //! Whenever an Element is finally mounted to the Dom, its data is available to be read. //! These fields can typically only be read asynchronously, since various renderers need to release the main thread to //! perform layout and painting. use dioxus::prelude::*; use dioxus_elements::geometry::euclid::Size2D; fn main() { dioxus::launch(app); } fn app() -> Element { let mut dimensions = use_signal(Size2D::zero); rsx!( Stylesheet { href: asset!("/examples/assets/read_size.css") } div { width: "50%", height: "50%", background_color: "red", onresize: move |evt| dimensions.set(evt.data().get_content_box_size().unwrap()), "This element is {dimensions():?}" } ) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/drag_and_drop.rs
examples/08-apis/drag_and_drop.rs
//! This example shows how to implement a simple drag-and-drop kanban board using Dioxus. //! You can drag items between different categories and edit their contents. //! //! This example uses the `.data_transfer()` API to handle drag-and-drop events. When an item is dragged, //! its ID is stored in the data transfer object. When the item is dropped into a new category, its ID is retrieved //! from the data transfer object and used to update the item's category. //! //! Note that in a real-world application, you'll want more sophisticated drop handling, such as visual //! feedback during dragging, and better drop-zone detection to allow dropping *between* items. use dioxus::prelude::*; fn main() { dioxus::launch(app); } struct Item { id: usize, name: String, category: String, contents: String, } fn app() -> Element { let mut items = use_signal(initial_kanban_data); rsx! { div { display: "flex", gap: "20px", flex_direction: "row", for category in ["A", "B", "C"] { div { class: "category", display: "flex", flex_direction: "column", gap: "10px", padding: "10px", flex_grow: "1", border: "2px solid black", min_height: "300px", background_color: "#f0f0f0", ondragover: |e| e.prevent_default(), ondrop: move |e| { if let Some(item_id) = e.data_transfer().get_data("text/plain").and_then(|data| data.parse::<usize>().ok()) { if let Some(pos) = items.iter().position(|item| item.id == item_id) { items.write()[pos].category = category.to_string(); } } }, h2 { "Category: {category}" } for (index, item) in items.iter().enumerate().filter(|item| item.1.category == category) { div { key: "{item.id}", width: "200px", height: "50px", border: "1px solid black", padding: "10px", class: "item", draggable: "true", background: "white", cursor: "grab", ondragstart: move |e| { let id = items.read()[index].id.to_string(); e.data_transfer().set_data("text/plain", &id).unwrap(); }, pre { webkit_user_select: "none", "{item.name}" } input { r#type: "text", value: "{item.contents}", oninput: move |e| { items.write()[index].contents = e.value(); } } } } } } } } } fn initial_kanban_data() -> Vec<Item> { vec![ Item { id: 1, name: "Item 1".into(), category: "A".into(), contents: "This is item 1".into(), }, Item { id: 2, name: "Item 2".into(), category: "A".into(), contents: "This is item 2".into(), }, Item { id: 3, name: "Item 3".into(), category: "A".into(), contents: "This is item 3".into(), }, Item { id: 4, name: "Item 4".into(), category: "B".into(), contents: "This is item 4".into(), }, Item { id: 5, name: "Item 5".into(), category: "B".into(), contents: "This is item 5".into(), }, Item { id: 6, name: "Item 6".into(), category: "C".into(), contents: "This is item 6".into(), }, ] }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/wgpu_child_window.rs
examples/08-apis/wgpu_child_window.rs
//! Demonstrate how to use dioxus as a child window for use in alternative renderers like wgpu. //! //! The code here is borrowed from wry's example: //! https://github.com/tauri-apps/wry/blob/dev/examples/wgpu.rs //! //! To use this feature set `with_as_child_window()` on your desktop config which will then let you use dioxus::prelude::*; use dioxus::{ desktop::tao::{event::Event as WryEvent, window::Window}, desktop::{Config, tao::window::WindowBuilder, use_wry_event_handler, window}, }; use std::sync::Arc; fn main() { let config = Config::new() .with_window(WindowBuilder::new().with_transparent(true)) .with_on_window(|window, dom| { let resources = Arc::new(pollster::block_on(async { let resource = GraphicsContextAsyncBuilder { desktop: window, resources_builder: |ctx| Box::pin(GraphicsResources::new(ctx.clone())), } .build() .await; resource.with_resources(|resources| resources.render()); resource })); dom.provide_root_context(resources); }) .with_as_child_window(); dioxus::LaunchBuilder::desktop() .with_cfg(config) .launch(app); } fn app() -> Element { let graphics_resources = consume_context::<Arc<GraphicsContext>>(); // on first render request a redraw use_effect(|| { window().window.request_redraw(); }); use_wry_event_handler(move |event, _| { use dioxus::desktop::tao::event::WindowEvent; if let WryEvent::WindowEvent { event: WindowEvent::Resized(new_size), .. } = event { graphics_resources.with_resources(|srcs| { let mut cfg = srcs.config.clone(); cfg.width = new_size.width; cfg.height = new_size.height; srcs.surface.configure(&srcs.device, &cfg); }); window().window.request_redraw(); } }); rsx! { div { color: "blue", width: "100vw", height: "100vh", display: "flex", justify_content: "center", align_items: "center", font_size: "20px", div { "text overlaid on a wgpu surface!" } } } } /// This borrows from the `window` which is contained within an `Arc` so we need to wrap it in a self-borrowing struct /// to be able to borrow the window for the wgpu::Surface #[ouroboros::self_referencing] struct GraphicsContext { desktop: Arc<Window>, #[borrows(desktop)] #[not_covariant] resources: GraphicsResources<'this>, } struct GraphicsResources<'a> { surface: wgpu::Surface<'a>, device: wgpu::Device, pipeline: wgpu::RenderPipeline, queue: wgpu::Queue, config: wgpu::SurfaceConfiguration, } impl<'a> GraphicsResources<'a> { async fn new(window: Arc<Window>) -> Self { let size = window.inner_size(); let instance = wgpu::Instance::default(); let surface: wgpu::Surface<'a> = instance.create_surface(window).unwrap(); let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::default(), force_fallback_adapter: false, // Request an adapter which can render to our surface compatible_surface: Some(&surface), }) .await .expect("Failed to find an appropriate adapter"); // Create the logical device and command queue let (device, queue) = adapter .request_device(&wgpu::DeviceDescriptor { label: None, required_features: wgpu::Features::empty(), // Make sure we use the texture resolution limits from the adapter, so we can support images the size of the swapchain. required_limits: wgpu::Limits::downlevel_webgl2_defaults() .using_resolution(adapter.limits()), memory_hints: wgpu::MemoryHints::default(), ..Default::default() }) .await .expect("Failed to create device"); // Load the shaders from disk let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl( r#" @vertex fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> @builtin(position) vec4<f32> { let x = f32(i32(in_vertex_index) - 1); let y = f32(i32(in_vertex_index & 1u) * 2 - 1); return vec4<f32>(x, y, 0.0, 1.0); } @fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.0, 0.0, 0.0, 1.0); } "# .into(), ), }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[], push_constant_ranges: &[], }); let swapchain_capabilities = surface.get_capabilities(&adapter); let swapchain_format = swapchain_capabilities.formats[0]; let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: None, layout: Some(&pipeline_layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_main"), buffers: &[], compilation_options: wgpu::PipelineCompilationOptions::default(), }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("fs_main"), targets: &[Some(swapchain_format.into())], compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: wgpu::PrimitiveState::default(), depth_stencil: None, multisample: wgpu::MultisampleState::default(), multiview: None, cache: None, }); let config = wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format: swapchain_format, width: size.width, height: size.height, present_mode: wgpu::PresentMode::Fifo, desired_maximum_frame_latency: 2, alpha_mode: wgpu::CompositeAlphaMode::PostMultiplied, view_formats: vec![], }; surface.configure(&device, &config); GraphicsResources { surface, device, pipeline, queue, config, } } fn render(&self) { let GraphicsResources { surface, device, pipeline, queue, .. } = self; let frame = surface .get_current_texture() .expect("Failed to acquire next swap chain texture"); let view = frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store, }, depth_slice: None, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }); rpass.set_pipeline(pipeline); rpass.draw(0..3, 0..1); } queue.submit(Some(encoder.finish())); frame.present(); } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/window_popup.rs
examples/08-apis/window_popup.rs
//! This example shows how to create a popup window and send data back to the parent window. //! Currently Dioxus doesn't support nested renderers, hence the need to create popups as separate windows. use dioxus::prelude::*; use std::rc::Rc; fn main() { dioxus::LaunchBuilder::desktop().launch(app); } fn app() -> Element { let mut emails_sent = use_signal(|| Vec::new() as Vec<String>); // Wait for responses to the compose channel, and then push them to the emails_sent signal. let handle = use_coroutine(move |mut rx: UnboundedReceiver<String>| async move { use futures_util::StreamExt; while let Some(message) = rx.next().await { emails_sent.push(message); } }); let open_compose_window = move |_evt: MouseEvent| { let tx = handle.tx(); dioxus::desktop::window().new_window( VirtualDom::new_with_props(popup, Rc::new(move |s| tx.unbounded_send(s).unwrap())), Default::default(), ); }; rsx! { h1 { "This is your email" } button { onclick: open_compose_window, "Click to compose a new email" } ul { for message in emails_sent.read().iter() { li { h3 { "email" } span { "{message}" } } } } } } fn popup(send: Rc<dyn Fn(String)>) -> Element { let mut user_input = use_signal(String::new); let window = dioxus::desktop::use_window(); let close_window = move |_| { println!("Attempting to close Window B"); window.close(); }; rsx! { div { h1 { "Compose a new email" } button { onclick: close_window, "Close Window B (button)" } button { onclick: move |_| { send(user_input.cloned()); dioxus::desktop::window().close(); }, "Send" } input { oninput: move |e| user_input.set(e.value()), value: "{user_input}" } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/on_visible.rs
examples/08-apis/on_visible.rs
//! Port of the https://codepen.io/ryanfinni/pen/VwZeGxN example use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { let mut animated_classes = use_signal(|| ["animated-text", ""]); rsx! { Stylesheet { href: asset!("/examples/assets/visible.css") } div { class: "container", p { "Scroll to the bottom of the page. The text will transition in when it becomes visible in the viewport." } p { "First, let's create a new project for our hacker news app. We can use the CLI to create a new project. You can select a platform of your choice or view the getting started guide for more information on each option. If you aren't sure what platform to try out, we recommend getting started with web or desktop:" } p { "The template contains some boilerplate to help you get started. For this guide, we will be rebuilding some of the code from scratch for learning purposes. You can clear the src/main.rs file. We will be adding new code in the next sections." } p { "Next, let's setup our dependencies. We need to set up a few dependencies to work with the hacker news API: " } p { "First, let's create a new project for our hacker news app. We can use the CLI to create a new project. You can select a platform of your choice or view the getting started guide for more information on each option. If you aren't sure what platform to try out, we recommend getting started with web or desktop:" } p { "The template contains some boilerplate to help you get started. For this guide, we will be rebuilding some of the code from scratch for learning purposes. You can clear the src/main.rs file. We will be adding new code in the next sections." } p { "Next, let's setup our dependencies. We need to set up a few dependencies to work with the hacker news API: " } p { "First, let's create a new project for our hacker news app. We can use the CLI to create a new project. You can select a platform of your choice or view the getting started guide for more information on each option. If you aren't sure what platform to try out, we recommend getting started with web or desktop:" } p { "The template contains some boilerplate to help you get started. For this guide, we will be rebuilding some of the code from scratch for learning purposes. You can clear the src/main.rs file. We will be adding new code in the next sections." } p { "Next, let's setup our dependencies. We need to set up a few dependencies to work with the hacker news API: " } h2 { class: animated_classes().join(" "), onvisible: move |evt| { let data = evt.data(); if let Ok(is_intersecting) = data.is_intersecting() { animated_classes.write()[1] = if is_intersecting { "visible" } else { "" }; } }, "Animated Text" } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/eval.rs
examples/08-apis/eval.rs
//! This example shows how to use the `eval` function to run JavaScript code in the webview. //! //! Eval will only work with renderers that support javascript - so currently only the web and desktop/mobile renderers //! that use a webview. Native renderers will throw "unsupported" errors when calling `eval`. use async_std::task::sleep; use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { // Create a future that will resolve once the javascript has been successfully executed. let future = use_resource(move || async move { // Wait a little bit just to give the appearance of a loading screen sleep(std::time::Duration::from_secs(1)).await; // The `eval` is available in the prelude - and simply takes a block of JS. // Dioxus' eval is interesting since it allows sending messages to and from the JS code using the `await dioxus.recv()` // builtin function. This allows you to create a two-way communication channel between Rust and JS. let mut eval = document::eval( r#" dioxus.send("Hi from JS!"); let msg = await dioxus.recv(); console.log(msg); return "hi from JS!"; "#, ); // Send a message to the JS code. eval.send("Hi from Rust!").unwrap(); // Our line on the JS side will log the message and then return "hello world". let res: String = eval.recv().await.unwrap(); // This will print "Hi from JS!" and "Hi from Rust!". println!("{:?}", eval.await); res }); match future.value().as_ref() { Some(v) => rsx!( p { "{v}" } ), _ => rsx!( p { "waiting.." } ), } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/overlay.rs
examples/08-apis/overlay.rs
//! This example demonstrates how to create an overlay window with dioxus. //! //! Basically, we just create a new window with a transparent background and no decorations, size it to the screen, and //! then we can draw whatever we want on it. In this case, we're drawing a simple overlay with a draggable header. //! //! We also add a global shortcut to toggle the overlay on and off, so you could build a raycast-type app with this. use dioxus::desktop::{ HotKeyState, LogicalSize, WindowBuilder, tao::dpi::PhysicalPosition, use_global_shortcut, }; use dioxus::prelude::*; fn main() { dioxus::LaunchBuilder::desktop() .with_cfg(make_config()) .launch(app); } fn app() -> Element { let mut show_overlay = use_signal(|| true); _ = use_global_shortcut("cmd+g", move |state| { if state == HotKeyState::Pressed { show_overlay.toggle(); } }); rsx! { Stylesheet { href: asset!("/examples/assets/overlay.css") } if show_overlay() { div { width: "100%", height: "100%", background_color: "red", border: "1px solid black", div { width: "100%", height: "10px", background_color: "black", onmousedown: move |_| dioxus::desktop::window().drag(), } "This is an overlay!" } } } } fn make_config() -> dioxus::desktop::Config { dioxus::desktop::Config::default().with_window(make_window()) } fn make_window() -> WindowBuilder { WindowBuilder::new() .with_transparent(true) .with_decorations(false) .with_resizable(false) .with_always_on_top(true) .with_position(PhysicalPosition::new(0, 0)) .with_max_inner_size(LogicalSize::new(100000, 50)) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false