= match sandbox_type
{
- SandboxType::None => exec(params, sandbox_policy, ctrl_c, stdout_stream.clone()).await,
+ SandboxType::None => exec(params, sandbox_policy, stdout_stream.clone()).await,
SandboxType::MacosSeatbelt => {
let timeout = params.timeout_duration();
let ExecParams {
@@ -103,7 +100,7 @@ pub async fn process_exec_tool_call(
env,
)
.await?;
- consume_truncated_output(child, ctrl_c, timeout, stdout_stream.clone()).await
+ consume_truncated_output(child, timeout, stdout_stream.clone()).await
}
SandboxType::LinuxSeccomp => {
let timeout = params.timeout_duration();
@@ -124,14 +121,14 @@ pub async fn process_exec_tool_call(
)
.await?;
- consume_truncated_output(child, ctrl_c, timeout, stdout_stream).await
+ consume_truncated_output(child, timeout, stdout_stream).await
}
};
let duration = start.elapsed();
match raw_output_result {
Ok(raw_output) => {
- let stdout = String::from_utf8_lossy(&raw_output.stdout).to_string();
- let stderr = String::from_utf8_lossy(&raw_output.stderr).to_string();
+ let stdout = raw_output.stdout.from_utf8_lossy();
+ let stderr = raw_output.stderr.from_utf8_lossy();
#[cfg(target_family = "unix")]
match raw_output.exit_status.signal() {
@@ -146,7 +143,9 @@ pub async fn process_exec_tool_call(
if exit_code != 0 && is_likely_sandbox_denied(sandbox_type, exit_code) {
return Err(CodexErr::Sandbox(SandboxErr::Denied(
- exit_code, stdout, stderr,
+ exit_code,
+ stdout.text,
+ stderr.text,
)));
}
@@ -164,65 +163,6 @@ pub async fn process_exec_tool_call(
}
}
-/// Spawn a shell tool command under the Linux Landlock+seccomp sandbox helper
-/// (codex-linux-sandbox).
-///
-/// Unlike macOS Seatbelt where we directly embed the policy text, the Linux
-/// helper accepts a list of `--sandbox-permission`/`-s` flags mirroring the
-/// public CLI. We convert the internal [`SandboxPolicy`] representation into
-/// the equivalent CLI options.
-pub async fn spawn_command_under_linux_sandbox(
- codex_linux_sandbox_exe: P,
- command: Vec,
- sandbox_policy: &SandboxPolicy,
- cwd: PathBuf,
- stdio_policy: StdioPolicy,
- env: HashMap,
-) -> std::io::Result
-where
- P: AsRef,
-{
- let args = create_linux_sandbox_command_args(command, sandbox_policy, &cwd);
- let arg0 = Some("codex-linux-sandbox");
- spawn_child_async(
- codex_linux_sandbox_exe.as_ref().to_path_buf(),
- args,
- arg0,
- cwd,
- sandbox_policy,
- stdio_policy,
- env,
- )
- .await
-}
-
-/// Converts the sandbox policy into the CLI invocation for `codex-linux-sandbox`.
-fn create_linux_sandbox_command_args(
- command: Vec,
- sandbox_policy: &SandboxPolicy,
- cwd: &Path,
-) -> Vec {
- #[expect(clippy::expect_used)]
- let sandbox_policy_cwd = cwd.to_str().expect("cwd must be valid UTF-8").to_string();
-
- #[expect(clippy::expect_used)]
- let sandbox_policy_json =
- serde_json::to_string(sandbox_policy).expect("Failed to serialize SandboxPolicy to JSON");
-
- let mut linux_cmd: Vec = vec![
- sandbox_policy_cwd,
- sandbox_policy_json,
- // Separator so that command arguments starting with `-` are not parsed as
- // options of the helper itself.
- "--".to_string(),
- ];
-
- // Append the original tool command.
- linux_cmd.extend(command);
-
- linux_cmd
-}
-
/// We don't have a fully deterministic way to tell if our command failed
/// because of the sandbox - a command in the user's zshrc file might hit an
/// error, but the command itself might fail or succeed for other reasons.
@@ -243,25 +183,47 @@ fn is_likely_sandbox_denied(sandbox_type: SandboxType, exit_code: i32) -> bool {
true
}
+#[derive(Debug)]
+pub struct StreamOutput {
+ pub text: T,
+ pub truncated_after_lines: Option,
+}
#[derive(Debug)]
pub struct RawExecToolCallOutput {
pub exit_status: ExitStatus,
- pub stdout: Vec,
- pub stderr: Vec,
+ pub stdout: StreamOutput>,
+ pub stderr: StreamOutput>,
+}
+
+impl StreamOutput {
+ pub fn new(text: String) -> Self {
+ Self {
+ text,
+ truncated_after_lines: None,
+ }
+ }
+}
+
+impl StreamOutput> {
+ pub fn from_utf8_lossy(&self) -> StreamOutput {
+ StreamOutput {
+ text: String::from_utf8_lossy(&self.text).to_string(),
+ truncated_after_lines: self.truncated_after_lines,
+ }
+ }
}
#[derive(Debug)]
pub struct ExecToolCallOutput {
pub exit_code: i32,
- pub stdout: String,
- pub stderr: String,
+ pub stdout: StreamOutput,
+ pub stderr: StreamOutput,
pub duration: Duration,
}
async fn exec(
params: ExecParams,
sandbox_policy: &SandboxPolicy,
- ctrl_c: Arc,
stdout_stream: Option,
) -> Result {
let timeout = params.timeout_duration();
@@ -286,14 +248,13 @@ async fn exec(
env,
)
.await?;
- consume_truncated_output(child, ctrl_c, timeout, stdout_stream).await
+ consume_truncated_output(child, timeout, stdout_stream).await
}
/// Consumes the output of a child process, truncating it so it is suitable for
/// use as the output of a `shell` tool call. Also enforces specified timeout.
pub(crate) async fn consume_truncated_output(
mut child: Child,
- ctrl_c: Arc,
timeout: Duration,
stdout_stream: Option,
) -> Result {
@@ -327,7 +288,6 @@ pub(crate) async fn consume_truncated_output(
true,
));
- let interrupted = ctrl_c.notified();
let exit_status = tokio::select! {
result = tokio::time::timeout(timeout, child.wait()) => {
match result {
@@ -341,7 +301,7 @@ pub(crate) async fn consume_truncated_output(
}
}
}
- _ = interrupted => {
+ _ = tokio::signal::ctrl_c() => {
child.start_kill()?;
synthetic_exit_status(128 + SIGKILL_CODE)
}
@@ -363,7 +323,7 @@ async fn read_capped(
max_lines: usize,
stream: Option,
is_stderr: bool,
-) -> io::Result> {
+) -> io::Result>> {
let mut buf = Vec::with_capacity(max_output.min(8 * 1024));
let mut tmp = [0u8; 8192];
@@ -413,7 +373,16 @@ async fn read_capped(
// Continue reading to EOF to avoid back-pressure, but discard once caps are hit.
}
- Ok(buf)
+ let truncated = remaining_lines == 0 || remaining_bytes == 0;
+
+ Ok(StreamOutput {
+ text: buf,
+ truncated_after_lines: if truncated {
+ Some((max_lines - remaining_lines) as u32)
+ } else {
+ None
+ },
+ })
}
#[cfg(unix)]
diff --git a/codex-rs/core/src/exec_env.rs b/codex-rs/core/src/exec_env.rs
index 2957f3da15..88246b063c 100644
--- a/codex-rs/core/src/exec_env.rs
+++ b/codex-rs/core/src/exec_env.rs
@@ -70,8 +70,6 @@ where
#[cfg(test)]
mod tests {
- #![allow(clippy::unwrap_used, clippy::expect_used)]
-
use super::*;
use crate::config_types::ShellEnvironmentPolicyInherit;
use maplit::hashmap;
diff --git a/codex-rs/core/src/git_info.rs b/codex-rs/core/src/git_info.rs
index 52d029f669..09a59b7b8c 100644
--- a/codex-rs/core/src/git_info.rs
+++ b/codex-rs/core/src/git_info.rs
@@ -99,9 +99,6 @@ async fn run_git_command_with_timeout(args: &[&str], cwd: &Path) -> Option) -> bool {
#[cfg(test)]
mod tests {
- #![allow(clippy::unwrap_used)]
use super::*;
fn vec_str(args: &[&str]) -> Vec {
diff --git a/codex-rs/core/src/landlock.rs b/codex-rs/core/src/landlock.rs
new file mode 100644
index 0000000000..8c8840c269
--- /dev/null
+++ b/codex-rs/core/src/landlock.rs
@@ -0,0 +1,66 @@
+use crate::protocol::SandboxPolicy;
+use crate::spawn::StdioPolicy;
+use crate::spawn::spawn_child_async;
+use std::collections::HashMap;
+use std::path::Path;
+use std::path::PathBuf;
+use tokio::process::Child;
+
+/// Spawn a shell tool command under the Linux Landlock+seccomp sandbox helper
+/// (codex-linux-sandbox).
+///
+/// Unlike macOS Seatbelt where we directly embed the policy text, the Linux
+/// helper accepts a list of `--sandbox-permission`/`-s` flags mirroring the
+/// public CLI. We convert the internal [`SandboxPolicy`] representation into
+/// the equivalent CLI options.
+pub async fn spawn_command_under_linux_sandbox(
+ codex_linux_sandbox_exe: P,
+ command: Vec,
+ sandbox_policy: &SandboxPolicy,
+ cwd: PathBuf,
+ stdio_policy: StdioPolicy,
+ env: HashMap,
+) -> std::io::Result
+where
+ P: AsRef,
+{
+ let args = create_linux_sandbox_command_args(command, sandbox_policy, &cwd);
+ let arg0 = Some("codex-linux-sandbox");
+ spawn_child_async(
+ codex_linux_sandbox_exe.as_ref().to_path_buf(),
+ args,
+ arg0,
+ cwd,
+ sandbox_policy,
+ stdio_policy,
+ env,
+ )
+ .await
+}
+
+/// Converts the sandbox policy into the CLI invocation for `codex-linux-sandbox`.
+fn create_linux_sandbox_command_args(
+ command: Vec,
+ sandbox_policy: &SandboxPolicy,
+ cwd: &Path,
+) -> Vec {
+ #[expect(clippy::expect_used)]
+ let sandbox_policy_cwd = cwd.to_str().expect("cwd must be valid UTF-8").to_string();
+
+ #[expect(clippy::expect_used)]
+ let sandbox_policy_json =
+ serde_json::to_string(sandbox_policy).expect("Failed to serialize SandboxPolicy to JSON");
+
+ let mut linux_cmd: Vec = vec![
+ sandbox_policy_cwd,
+ sandbox_policy_json,
+ // Separator so that command arguments starting with `-` are not parsed as
+ // options of the helper itself.
+ "--".to_string(),
+ ];
+
+ // Append the original tool command.
+ linux_cmd.extend(command);
+
+ linux_cmd
+}
diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs
index c728bd3125..28d35f5376 100644
--- a/codex-rs/core/src/lib.rs
+++ b/codex-rs/core/src/lib.rs
@@ -11,42 +11,53 @@ mod chat_completions;
mod client;
mod client_common;
pub mod codex;
-pub use codex::Codex;
-pub use codex::CodexSpawnOk;
-pub mod codex_wrapper;
+mod codex_conversation;
+pub use codex_conversation::CodexConversation;
pub mod config;
pub mod config_profile;
pub mod config_types;
mod conversation_history;
+mod environment_context;
pub mod error;
pub mod exec;
pub mod exec_env;
mod flags;
pub mod git_info;
mod is_safe_command;
+pub mod landlock;
mod mcp_connection_manager;
mod mcp_tool_call;
mod message_history;
mod model_provider_info;
+pub mod parse_command;
pub use model_provider_info::BUILT_IN_OSS_MODEL_PROVIDER_ID;
pub use model_provider_info::ModelProviderInfo;
pub use model_provider_info::WireApi;
pub use model_provider_info::built_in_model_providers;
pub use model_provider_info::create_oss_provider_with_base_url;
+mod conversation_manager;
+pub use conversation_manager::ConversationManager;
+pub use conversation_manager::NewConversation;
pub mod model_family;
mod models;
mod openai_model_info;
mod openai_tools;
pub mod plan_tool;
mod project_doc;
-pub mod protocol;
mod rollout;
pub(crate) mod safety;
pub mod seatbelt;
pub mod shell;
pub mod spawn;
pub mod turn_diff_tracker;
+pub mod user_agent;
mod user_notification;
pub mod util;
pub use apply_patch::CODEX_APPLY_PATCH_ARG1;
pub use safety::get_platform_sandbox;
+// Re-export the protocol types from the standalone `codex-protocol` crate so existing
+// `codex_core::protocol::...` references continue to work across the workspace.
+pub use codex_protocol::protocol;
+// Re-export protocol config enums to ensure call sites can use the same types
+// as those in the protocol crate when constructing protocol messages.
+pub use codex_protocol::config_types as protocol_config_types;
diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs
index 2e33c8754b..b5813a0462 100644
--- a/codex-rs/core/src/mcp_connection_manager.rs
+++ b/codex-rs/core/src/mcp_connection_manager.rs
@@ -281,7 +281,6 @@ fn is_valid_mcp_server_name(server_name: &str) -> bool {
}
#[cfg(test)]
-#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use mcp_types::ToolInputSchema;
diff --git a/codex-rs/core/src/model_family.rs b/codex-rs/core/src/model_family.rs
index 1245a030c6..6d1c2efcc1 100644
--- a/codex-rs/core/src/model_family.rs
+++ b/codex-rs/core/src/model_family.rs
@@ -23,6 +23,10 @@ pub struct ModelFamily {
// the model such that its description can be omitted.
// See https://platform.openai.com/docs/guides/tools-local-shell
pub uses_local_shell_tool: bool,
+
+ /// True if the model performs better when `apply_patch` is provided as
+ /// a tool call instead of just a bash command.
+ pub uses_apply_patch_tool: bool,
}
macro_rules! model_family {
@@ -36,6 +40,7 @@ macro_rules! model_family {
needs_special_apply_patch_instructions: false,
supports_reasoning_summaries: false,
uses_local_shell_tool: false,
+ uses_apply_patch_tool: false,
};
// apply overrides
$(
@@ -55,6 +60,7 @@ macro_rules! simple_model_family {
needs_special_apply_patch_instructions: false,
supports_reasoning_summaries: false,
uses_local_shell_tool: false,
+ uses_apply_patch_tool: false,
})
}};
}
@@ -78,15 +84,20 @@ pub fn find_family_for_model(slug: &str) -> Option {
supports_reasoning_summaries: true,
uses_local_shell_tool: true,
)
+ } else if slug.starts_with("codex-") {
+ model_family!(
+ slug, slug,
+ supports_reasoning_summaries: true,
+ )
} else if slug.starts_with("gpt-4.1") {
model_family!(
slug, "gpt-4.1",
needs_special_apply_patch_instructions: true,
)
+ } else if slug.starts_with("gpt-oss") {
+ model_family!(slug, "gpt-oss", uses_apply_patch_tool: true)
} else if slug.starts_with("gpt-4o") {
simple_model_family!(slug, "gpt-4o")
- } else if slug.starts_with("gpt-oss") {
- simple_model_family!(slug, "gpt-oss")
} else if slug.starts_with("gpt-3.5") {
simple_model_family!(slug, "gpt-3.5")
} else if slug.starts_with("gpt-5") {
diff --git a/codex-rs/core/src/model_provider_info.rs b/codex-rs/core/src/model_provider_info.rs
index 98f07deb1e..00eabc539c 100644
--- a/codex-rs/core/src/model_provider_info.rs
+++ b/codex-rs/core/src/model_provider_info.rs
@@ -322,7 +322,6 @@ pub fn create_oss_provider_with_base_url(base_url: &str) -> ModelProviderInfo {
#[cfg(test)]
mod tests {
- #![allow(clippy::unwrap_used)]
use super::*;
use pretty_assertions::assert_eq;
diff --git a/codex-rs/core/src/models.rs b/codex-rs/core/src/models.rs
index e052bc43a4..f6323e2724 100644
--- a/codex-rs/core/src/models.rs
+++ b/codex-rs/core/src/models.rs
@@ -45,7 +45,7 @@ pub enum ResponseItem {
Reasoning {
id: String,
summary: Vec,
- #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[serde(default, skip_serializing_if = "should_serialize_reasoning_content")]
content: Option>,
encrypted_content: Option,
},
@@ -81,6 +81,15 @@ pub enum ResponseItem {
Other,
}
+fn should_serialize_reasoning_content(content: &Option>) -> bool {
+ match content {
+ Some(content) => !content
+ .iter()
+ .any(|c| matches!(c, ReasoningItemContent::ReasoningText { .. })),
+ None => false,
+ }
+}
+
impl From for ResponseItem {
fn from(item: ResponseInputItem) -> Self {
match item {
@@ -142,6 +151,7 @@ pub enum ReasoningItemReasoningSummary {
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ReasoningItemContent {
ReasoningText { text: String },
+ Text { text: String },
}
impl From> for ResponseInputItem {
@@ -173,6 +183,7 @@ impl From> for ResponseInputItem {
None
}
},
+ _ => None,
})
.collect::>(),
}
@@ -256,7 +267,6 @@ impl std::ops::Deref for FunctionCallOutputPayload {
#[cfg(test)]
mod tests {
- #![allow(clippy::unwrap_used)]
use super::*;
#[test]
diff --git a/codex-rs/core/src/openai_model_info.rs b/codex-rs/core/src/openai_model_info.rs
index a072d409c6..66f3c626ea 100644
--- a/codex-rs/core/src/openai_model_info.rs
+++ b/codex-rs/core/src/openai_model_info.rs
@@ -15,7 +15,8 @@ pub(crate) struct ModelInfo {
}
pub(crate) fn get_model_info(model_family: &ModelFamily) -> Option {
- match model_family.slug.as_str() {
+ let slug = model_family.slug.as_str();
+ match slug {
// OSS models have a 128k shared token pool.
// Arbitrarily splitting it: 3/4 input context, 1/4 output.
// https://openai.com/index/gpt-oss-model-card/
@@ -82,6 +83,11 @@ pub(crate) fn get_model_info(model_family: &ModelFamily) -> Option {
max_output_tokens: 100_000,
}),
+ _ if slug.starts_with("codex-") => Some(ModelInfo {
+ context_window: 200_000,
+ max_output_tokens: 100_000,
+ }),
+
_ => None,
}
}
diff --git a/codex-rs/core/src/openai_tools.rs b/codex-rs/core/src/openai_tools.rs
index 1c92c07c12..32ead20e7d 100644
--- a/codex-rs/core/src/openai_tools.rs
+++ b/codex-rs/core/src/openai_tools.rs
@@ -1,5 +1,6 @@
use serde::Deserialize;
use serde::Serialize;
+use serde_json::Value as JsonValue;
use serde_json::json;
use std::collections::BTreeMap;
use std::collections::HashMap;
@@ -42,6 +43,7 @@ pub enum ConfigShellToolType {
pub struct ToolsConfig {
pub shell_type: ConfigShellToolType,
pub plan_tool: bool,
+ pub apply_patch_tool: bool,
}
impl ToolsConfig {
@@ -50,6 +52,7 @@ impl ToolsConfig {
approval_policy: AskForApproval,
sandbox_policy: SandboxPolicy,
include_plan_tool: bool,
+ include_apply_patch_tool: bool,
) -> Self {
let mut shell_type = if model_family.uses_local_shell_tool {
ConfigShellToolType::LocalShell
@@ -65,6 +68,7 @@ impl ToolsConfig {
Self {
shell_type,
plan_tool: include_plan_tool,
+ apply_patch_tool: include_apply_patch_tool || model_family.uses_apply_patch_tool,
}
}
}
@@ -81,6 +85,8 @@ pub(crate) enum JsonSchema {
#[serde(skip_serializing_if = "Option::is_none")]
description: Option,
},
+ /// MCP schema allows "number" | "integer" for Number
+ #[serde(alias = "integer")]
Number {
#[serde(skip_serializing_if = "Option::is_none")]
description: Option,
@@ -232,6 +238,87 @@ The shell tool is used to execute shell commands.
})
}
+#[derive(Serialize, Deserialize)]
+pub(crate) struct ApplyPatchToolArgs {
+ pub(crate) input: String,
+}
+
+fn create_apply_patch_tool() -> OpenAiTool {
+ // Minimal schema: one required string argument containing the patch body
+ let mut properties = BTreeMap::new();
+ properties.insert(
+ "input".to_string(),
+ JsonSchema::String {
+ description: Some(r#"The entire contents of the apply_patch command"#.to_string()),
+ },
+ );
+
+ OpenAiTool::Function(ResponsesApiTool {
+ name: "apply_patch".to_string(),
+ description: r#"Use this tool to edit files.
+Your patch language is a stripped‑down, file‑oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high‑level envelope:
+
+**_ Begin Patch
+[ one or more file sections ]
+_** End Patch
+
+Within that envelope, you get a sequence of file operations.
+You MUST include a header to specify the action you are taking.
+Each operation starts with one of three headers:
+
+**_ Add File: - create a new file. Every following line is a + line (the initial contents).
+_** Delete File: - remove an existing file. Nothing follows.
+\*\*\* Update File: - patch an existing file in place (optionally with a rename).
+
+May be immediately followed by \*\*\* Move to: if you want to rename the file.
+Then one or more “hunks”, each introduced by @@ (optionally followed by a hunk header).
+Within a hunk each line starts with:
+
+- for inserted text,
+
+* for removed text, or
+ space ( ) for context.
+ At the end of a truncated hunk you can emit \*\*\* End of File.
+
+Patch := Begin { FileOp } End
+Begin := "**_ Begin Patch" NEWLINE
+End := "_** End Patch" NEWLINE
+FileOp := AddFile | DeleteFile | UpdateFile
+AddFile := "**_ Add File: " path NEWLINE { "+" line NEWLINE }
+DeleteFile := "_** Delete File: " path NEWLINE
+UpdateFile := "**_ Update File: " path NEWLINE [ MoveTo ] { Hunk }
+MoveTo := "_** Move to: " newPath NEWLINE
+Hunk := "@@" [ header ] NEWLINE { HunkLine } [ "*** End of File" NEWLINE ]
+HunkLine := (" " | "-" | "+") text NEWLINE
+
+A full patch can combine several operations:
+
+**_ Begin Patch
+_** Add File: hello.txt
++Hello world
+**_ Update File: src/app.py
+_** Move to: src/main.py
+@@ def greet():
+-print("Hi")
++print("Hello, world!")
+**_ Delete File: obsolete.txt
+_** End Patch
+
+It is important to remember:
+
+- You must include a header with your intended action (Add/Delete/Update)
+- You must prefix new lines with `+` even when creating a new file
+"#
+ .to_string(),
+ strict: false,
+ parameters: JsonSchema::Object {
+ properties,
+ required: Some(vec!["input".to_string()]),
+ additional_properties: Some(false),
+ },
+ })
+}
+
/// Returns JSON values that are compatible with Function Calling in the
/// Responses API:
/// https://platform.openai.com/docs/guides/function-calling?api-mode=responses
@@ -296,7 +383,13 @@ pub(crate) fn mcp_tool_to_openai_tool(
input_schema.properties = Some(serde_json::Value::Object(serde_json::Map::new()));
}
- let serialized_input_schema = serde_json::to_value(input_schema)?;
+ // Serialize to a raw JSON value so we can sanitize schemas coming from MCP
+ // servers. Some servers omit the top-level or nested `type` in JSON
+ // Schemas (e.g. using enum/anyOf), or use unsupported variants like
+ // `integer`. Our internal JsonSchema is a small subset and requires
+ // `type`, so we coerce/sanitize here for compatibility.
+ let mut serialized_input_schema = serde_json::to_value(input_schema)?;
+ sanitize_json_schema(&mut serialized_input_schema);
let input_schema = serde_json::from_value::(serialized_input_schema)?;
Ok(ResponsesApiTool {
@@ -307,6 +400,120 @@ pub(crate) fn mcp_tool_to_openai_tool(
})
}
+/// Sanitize a JSON Schema (as serde_json::Value) so it can fit our limited
+/// JsonSchema enum. This function:
+/// - Ensures every schema object has a "type". If missing, infers it from
+/// common keywords (properties => object, items => array, enum/const/format => string)
+/// and otherwise defaults to "string".
+/// - Fills required child fields (e.g. array items, object properties) with
+/// permissive defaults when absent.
+fn sanitize_json_schema(value: &mut JsonValue) {
+ match value {
+ JsonValue::Bool(_) => {
+ // JSON Schema boolean form: true/false. Coerce to an accept-all string.
+ *value = json!({ "type": "string" });
+ }
+ JsonValue::Array(arr) => {
+ for v in arr.iter_mut() {
+ sanitize_json_schema(v);
+ }
+ }
+ JsonValue::Object(map) => {
+ // First, recursively sanitize known nested schema holders
+ if let Some(props) = map.get_mut("properties") {
+ if let Some(props_map) = props.as_object_mut() {
+ for (_k, v) in props_map.iter_mut() {
+ sanitize_json_schema(v);
+ }
+ }
+ }
+ if let Some(items) = map.get_mut("items") {
+ sanitize_json_schema(items);
+ }
+ // Some schemas use oneOf/anyOf/allOf - sanitize their entries
+ for combiner in ["oneOf", "anyOf", "allOf", "prefixItems"] {
+ if let Some(v) = map.get_mut(combiner) {
+ sanitize_json_schema(v);
+ }
+ }
+
+ // Normalize/ensure type
+ let mut ty = map
+ .get("type")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+
+ // If type is an array (union), pick first supported; else leave to inference
+ if ty.is_none() {
+ if let Some(JsonValue::Array(types)) = map.get("type") {
+ for t in types {
+ if let Some(tt) = t.as_str() {
+ if matches!(
+ tt,
+ "object" | "array" | "string" | "number" | "integer" | "boolean"
+ ) {
+ ty = Some(tt.to_string());
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ // Infer type if still missing
+ if ty.is_none() {
+ if map.contains_key("properties")
+ || map.contains_key("required")
+ || map.contains_key("additionalProperties")
+ {
+ ty = Some("object".to_string());
+ } else if map.contains_key("items") || map.contains_key("prefixItems") {
+ ty = Some("array".to_string());
+ } else if map.contains_key("enum")
+ || map.contains_key("const")
+ || map.contains_key("format")
+ {
+ ty = Some("string".to_string());
+ } else if map.contains_key("minimum")
+ || map.contains_key("maximum")
+ || map.contains_key("exclusiveMinimum")
+ || map.contains_key("exclusiveMaximum")
+ || map.contains_key("multipleOf")
+ {
+ ty = Some("number".to_string());
+ }
+ }
+ // If we still couldn't infer, default to string
+ let ty = ty.unwrap_or_else(|| "string".to_string());
+ map.insert("type".to_string(), JsonValue::String(ty.to_string()));
+
+ // Ensure object schemas have properties map
+ if ty == "object" {
+ if !map.contains_key("properties") {
+ map.insert(
+ "properties".to_string(),
+ JsonValue::Object(serde_json::Map::new()),
+ );
+ }
+ // If additionalProperties is an object schema, sanitize it too.
+ // Leave booleans as-is, since JSON Schema allows boolean here.
+ if let Some(ap) = map.get_mut("additionalProperties") {
+ let is_bool = matches!(ap, JsonValue::Bool(_));
+ if !is_bool {
+ sanitize_json_schema(ap);
+ }
+ }
+ }
+
+ // Ensure array schemas have items
+ if ty == "array" && !map.contains_key("items") {
+ map.insert("items".to_string(), json!({ "type": "string" }));
+ }
+ }
+ _ => {}
+ }
+}
+
/// Returns a list of OpenAiTools based on the provided config and MCP tools.
/// Note that the keys of mcp_tools should be fully qualified names. See
/// [`McpConnectionManager`] for more details.
@@ -332,6 +539,10 @@ pub(crate) fn get_openai_tools(
tools.push(PLAN_TOOL.clone());
}
+ if config.apply_patch_tool {
+ tools.push(create_apply_patch_tool());
+ }
+
if let Some(mcp_tools) = mcp_tools {
for (name, tool) in mcp_tools {
match mcp_tool_to_openai_tool(name.clone(), tool.clone()) {
@@ -347,10 +558,10 @@ pub(crate) fn get_openai_tools(
}
#[cfg(test)]
-#[allow(clippy::expect_used)]
mod tests {
use crate::model_family::find_family_for_model;
use mcp_types::ToolInputSchema;
+ use pretty_assertions::assert_eq;
use super::*;
@@ -385,6 +596,7 @@ mod tests {
AskForApproval::Never,
SandboxPolicy::ReadOnly,
true,
+ model_family.uses_apply_patch_tool,
);
let tools = get_openai_tools(&config, Some(HashMap::new()));
@@ -399,6 +611,7 @@ mod tests {
AskForApproval::Never,
SandboxPolicy::ReadOnly,
true,
+ model_family.uses_apply_patch_tool,
);
let tools = get_openai_tools(&config, Some(HashMap::new()));
@@ -413,6 +626,7 @@ mod tests {
AskForApproval::Never,
SandboxPolicy::ReadOnly,
false,
+ model_family.uses_apply_patch_tool,
);
let tools = get_openai_tools(
&config,
@@ -497,4 +711,216 @@ mod tests {
})
);
}
+
+ #[test]
+ fn test_mcp_tool_property_missing_type_defaults_to_string() {
+ let model_family = find_family_for_model("o3").expect("o3 should be a valid model family");
+ let config = ToolsConfig::new(
+ &model_family,
+ AskForApproval::Never,
+ SandboxPolicy::ReadOnly,
+ false,
+ model_family.uses_apply_patch_tool,
+ );
+
+ let tools = get_openai_tools(
+ &config,
+ Some(HashMap::from([(
+ "dash/search".to_string(),
+ mcp_types::Tool {
+ name: "search".to_string(),
+ input_schema: ToolInputSchema {
+ properties: Some(serde_json::json!({
+ "query": {
+ "description": "search query"
+ }
+ })),
+ required: None,
+ r#type: "object".to_string(),
+ },
+ output_schema: None,
+ title: None,
+ annotations: None,
+ description: Some("Search docs".to_string()),
+ },
+ )])),
+ );
+
+ assert_eq_tool_names(&tools, &["shell", "dash/search"]);
+
+ assert_eq!(
+ tools[1],
+ OpenAiTool::Function(ResponsesApiTool {
+ name: "dash/search".to_string(),
+ parameters: JsonSchema::Object {
+ properties: BTreeMap::from([(
+ "query".to_string(),
+ JsonSchema::String {
+ description: Some("search query".to_string())
+ }
+ )]),
+ required: None,
+ additional_properties: None,
+ },
+ description: "Search docs".to_string(),
+ strict: false,
+ })
+ );
+ }
+
+ #[test]
+ fn test_mcp_tool_integer_normalized_to_number() {
+ let model_family = find_family_for_model("o3").expect("o3 should be a valid model family");
+ let config = ToolsConfig::new(
+ &model_family,
+ AskForApproval::Never,
+ SandboxPolicy::ReadOnly,
+ false,
+ model_family.uses_apply_patch_tool,
+ );
+
+ let tools = get_openai_tools(
+ &config,
+ Some(HashMap::from([(
+ "dash/paginate".to_string(),
+ mcp_types::Tool {
+ name: "paginate".to_string(),
+ input_schema: ToolInputSchema {
+ properties: Some(serde_json::json!({
+ "page": { "type": "integer" }
+ })),
+ required: None,
+ r#type: "object".to_string(),
+ },
+ output_schema: None,
+ title: None,
+ annotations: None,
+ description: Some("Pagination".to_string()),
+ },
+ )])),
+ );
+
+ assert_eq_tool_names(&tools, &["shell", "dash/paginate"]);
+ assert_eq!(
+ tools[1],
+ OpenAiTool::Function(ResponsesApiTool {
+ name: "dash/paginate".to_string(),
+ parameters: JsonSchema::Object {
+ properties: BTreeMap::from([(
+ "page".to_string(),
+ JsonSchema::Number { description: None }
+ )]),
+ required: None,
+ additional_properties: None,
+ },
+ description: "Pagination".to_string(),
+ strict: false,
+ })
+ );
+ }
+
+ #[test]
+ fn test_mcp_tool_array_without_items_gets_default_string_items() {
+ let model_family = find_family_for_model("o3").expect("o3 should be a valid model family");
+ let config = ToolsConfig::new(
+ &model_family,
+ AskForApproval::Never,
+ SandboxPolicy::ReadOnly,
+ false,
+ model_family.uses_apply_patch_tool,
+ );
+
+ let tools = get_openai_tools(
+ &config,
+ Some(HashMap::from([(
+ "dash/tags".to_string(),
+ mcp_types::Tool {
+ name: "tags".to_string(),
+ input_schema: ToolInputSchema {
+ properties: Some(serde_json::json!({
+ "tags": { "type": "array" }
+ })),
+ required: None,
+ r#type: "object".to_string(),
+ },
+ output_schema: None,
+ title: None,
+ annotations: None,
+ description: Some("Tags".to_string()),
+ },
+ )])),
+ );
+
+ assert_eq_tool_names(&tools, &["shell", "dash/tags"]);
+ assert_eq!(
+ tools[1],
+ OpenAiTool::Function(ResponsesApiTool {
+ name: "dash/tags".to_string(),
+ parameters: JsonSchema::Object {
+ properties: BTreeMap::from([(
+ "tags".to_string(),
+ JsonSchema::Array {
+ items: Box::new(JsonSchema::String { description: None }),
+ description: None
+ }
+ )]),
+ required: None,
+ additional_properties: None,
+ },
+ description: "Tags".to_string(),
+ strict: false,
+ })
+ );
+ }
+
+ #[test]
+ fn test_mcp_tool_anyof_defaults_to_string() {
+ let model_family = find_family_for_model("o3").expect("o3 should be a valid model family");
+ let config = ToolsConfig::new(
+ &model_family,
+ AskForApproval::Never,
+ SandboxPolicy::ReadOnly,
+ false,
+ model_family.uses_apply_patch_tool,
+ );
+
+ let tools = get_openai_tools(
+ &config,
+ Some(HashMap::from([(
+ "dash/value".to_string(),
+ mcp_types::Tool {
+ name: "value".to_string(),
+ input_schema: ToolInputSchema {
+ properties: Some(serde_json::json!({
+ "value": { "anyOf": [ { "type": "string" }, { "type": "number" } ] }
+ })),
+ required: None,
+ r#type: "object".to_string(),
+ },
+ output_schema: None,
+ title: None,
+ annotations: None,
+ description: Some("AnyOf Value".to_string()),
+ },
+ )])),
+ );
+
+ assert_eq_tool_names(&tools, &["shell", "dash/value"]);
+ assert_eq!(
+ tools[1],
+ OpenAiTool::Function(ResponsesApiTool {
+ name: "dash/value".to_string(),
+ parameters: JsonSchema::Object {
+ properties: BTreeMap::from([(
+ "value".to_string(),
+ JsonSchema::String { description: None }
+ )]),
+ required: None,
+ additional_properties: None,
+ },
+ description: "AnyOf Value".to_string(),
+ strict: false,
+ })
+ );
+ }
}
diff --git a/codex-rs/core/src/parse_command.rs b/codex-rs/core/src/parse_command.rs
new file mode 100644
index 0000000000..6ea0626814
--- /dev/null
+++ b/codex-rs/core/src/parse_command.rs
@@ -0,0 +1,2068 @@
+use crate::bash::try_parse_bash;
+use crate::bash::try_parse_word_only_commands_sequence;
+use serde::Deserialize;
+use serde::Serialize;
+use shlex::split as shlex_split;
+use shlex::try_join as shlex_try_join;
+
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
+pub enum ParsedCommand {
+ Read {
+ cmd: String,
+ name: String,
+ },
+ ListFiles {
+ cmd: String,
+ path: Option,
+ },
+ Search {
+ cmd: String,
+ query: Option,
+ path: Option,
+ },
+ Format {
+ cmd: String,
+ tool: Option,
+ targets: Option>,
+ },
+ Test {
+ cmd: String,
+ },
+ Lint {
+ cmd: String,
+ tool: Option,
+ targets: Option>,
+ },
+ Noop {
+ cmd: String,
+ },
+ Unknown {
+ cmd: String,
+ },
+}
+
+// Convert core's parsed command enum into the protocol's simplified type so
+// events can carry the canonical representation across process boundaries.
+impl From for codex_protocol::parse_command::ParsedCommand {
+ fn from(v: ParsedCommand) -> Self {
+ use codex_protocol::parse_command::ParsedCommand as P;
+ match v {
+ ParsedCommand::Read { cmd, name } => P::Read { cmd, name },
+ ParsedCommand::ListFiles { cmd, path } => P::ListFiles { cmd, path },
+ ParsedCommand::Search { cmd, query, path } => P::Search { cmd, query, path },
+ ParsedCommand::Format { cmd, tool, targets } => P::Format { cmd, tool, targets },
+ ParsedCommand::Test { cmd } => P::Test { cmd },
+ ParsedCommand::Lint { cmd, tool, targets } => P::Lint { cmd, tool, targets },
+ ParsedCommand::Noop { cmd } => P::Noop { cmd },
+ ParsedCommand::Unknown { cmd } => P::Unknown { cmd },
+ }
+ }
+}
+
+fn shlex_join(tokens: &[String]) -> String {
+ shlex_try_join(tokens.iter().map(|s| s.as_str()))
+ .unwrap_or_else(|_| "".to_string())
+}
+
+/// DO NOT REVIEW THIS CODE BY HAND
+/// This parsing code is quite complex and not easy to hand-modify.
+/// The easiest way to iterate is to add unit tests and have Codex fix the implementation.
+/// To encourage this, the tests have been put directly below this function rather than at the bottom of the
+///
+/// Parses metadata out of an arbitrary command.
+/// These commands are model driven and could include just about anything.
+/// The parsing is slightly lossy due to the ~infinite expressiveness of an arbitrary command.
+/// The goal of the parsed metadata is to be able to provide the user with a human readable gis
+/// of what it is doing.
+pub fn parse_command(command: &[String]) -> Vec {
+ // Parse and then collapse consecutive duplicate commands to avoid redundant summaries.
+ let parsed = parse_command_impl(command);
+ let mut deduped: Vec = Vec::with_capacity(parsed.len());
+ for cmd in parsed.into_iter() {
+ if deduped.last().is_some_and(|prev| prev == &cmd) {
+ continue;
+ }
+ deduped.push(cmd);
+ }
+ deduped
+}
+
+#[cfg(test)]
+#[allow(clippy::items_after_test_module)]
+/// Tests are at the top to encourage using TDD + Codex to fix the implementation.
+mod tests {
+ use super::*;
+
+ fn shlex_split_safe(s: &str) -> Vec {
+ shlex_split(s).unwrap_or_else(|| s.split_whitespace().map(|s| s.to_string()).collect())
+ }
+
+ fn vec_str(args: &[&str]) -> Vec {
+ args.iter().map(|s| s.to_string()).collect()
+ }
+
+ fn assert_parsed(args: &[String], expected: Vec) {
+ let out = parse_command(args);
+ assert_eq!(out, expected);
+ }
+
+ #[test]
+ fn git_status_is_unknown() {
+ assert_parsed(
+ &vec_str(&["git", "status"]),
+ vec![ParsedCommand::Unknown {
+ cmd: "git status".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn handles_git_pipe_wc() {
+ let inner = "git status | wc -l";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Unknown {
+ cmd: "git status | wc -l".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn bash_lc_redirect_not_quoted() {
+ let inner = "echo foo > bar";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Unknown {
+ cmd: "echo foo > bar".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn handles_complex_bash_command_head() {
+ let inner =
+ "rg --version && node -v && pnpm -v && rg --files | wc -l && rg --files | head -n 40";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![
+ // Expect commands in left-to-right execution order
+ ParsedCommand::Search {
+ cmd: "rg --version".to_string(),
+ query: None,
+ path: None,
+ },
+ ParsedCommand::Unknown {
+ cmd: "node -v".to_string(),
+ },
+ ParsedCommand::Unknown {
+ cmd: "pnpm -v".to_string(),
+ },
+ ParsedCommand::Search {
+ cmd: "rg --files".to_string(),
+ query: None,
+ path: None,
+ },
+ ParsedCommand::Unknown {
+ cmd: "head -n 40".to_string(),
+ },
+ ],
+ );
+ }
+
+ #[test]
+ fn supports_searching_for_navigate_to_route() -> anyhow::Result<()> {
+ let inner = "rg -n \"navigate-to-route\" -S";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Search {
+ cmd: "rg -n navigate-to-route -S".to_string(),
+ query: Some("navigate-to-route".to_string()),
+ path: None,
+ }],
+ );
+ Ok(())
+ }
+
+ #[test]
+ fn handles_complex_bash_command() {
+ let inner = "rg -n \"BUG|FIXME|TODO|XXX|HACK\" -S | head -n 200";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![
+ ParsedCommand::Search {
+ cmd: "rg -n 'BUG|FIXME|TODO|XXX|HACK' -S".to_string(),
+ query: Some("BUG|FIXME|TODO|XXX|HACK".to_string()),
+ path: None,
+ },
+ ParsedCommand::Unknown {
+ cmd: "head -n 200".to_string(),
+ },
+ ],
+ );
+ }
+
+ #[test]
+ fn supports_rg_files_with_path_and_pipe() {
+ let inner = "rg --files webview/src | sed -n";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Search {
+ cmd: "rg --files webview/src".to_string(),
+ query: None,
+ path: Some("webview".to_string()),
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_rg_files_then_head() {
+ let inner = "rg --files | head -n 50";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![
+ ParsedCommand::Search {
+ cmd: "rg --files".to_string(),
+ query: None,
+ path: None,
+ },
+ ParsedCommand::Unknown {
+ cmd: "head -n 50".to_string(),
+ },
+ ],
+ );
+ }
+
+ #[test]
+ fn supports_cat() {
+ let inner = "cat webview/README.md";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Read {
+ cmd: inner.to_string(),
+ name: "README.md".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_ls_with_pipe() {
+ let inner = "ls -la | sed -n '1,120p'";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::ListFiles {
+ cmd: "ls -la".to_string(),
+ path: None,
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_head_n() {
+ let inner = "head -n 50 Cargo.toml";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Read {
+ cmd: inner.to_string(),
+ name: "Cargo.toml".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_cat_sed_n() {
+ let inner = "cat tui/Cargo.toml | sed -n '1,200p'";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Read {
+ cmd: inner.to_string(),
+ name: "Cargo.toml".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_tail_n_plus() {
+ let inner = "tail -n +522 README.md";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Read {
+ cmd: inner.to_string(),
+ name: "README.md".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_tail_n_last_lines() {
+ let inner = "tail -n 30 README.md";
+ let out = parse_command(&vec_str(&["bash", "-lc", inner]));
+ assert_eq!(
+ out,
+ vec![ParsedCommand::Read {
+ cmd: inner.to_string(),
+ name: "README.md".to_string(),
+ }]
+ );
+ }
+
+ #[test]
+ fn supports_npm_run_build_is_unknown() {
+ assert_parsed(
+ &vec_str(&["npm", "run", "build"]),
+ vec![ParsedCommand::Unknown {
+ cmd: "npm run build".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_npm_run_with_forwarded_args() {
+ assert_parsed(
+ &vec_str(&[
+ "npm",
+ "run",
+ "lint",
+ "--",
+ "--max-warnings",
+ "0",
+ "--format",
+ "json",
+ ]),
+ vec![ParsedCommand::Lint {
+ cmd: "npm run lint -- --max-warnings 0 --format json".to_string(),
+ tool: Some("npm-script:lint".to_string()),
+ targets: None,
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_grep_recursive_current_dir() {
+ assert_parsed(
+ &vec_str(&["grep", "-R", "CODEX_SANDBOX_ENV_VAR", "-n", "."]),
+ vec![ParsedCommand::Search {
+ cmd: "grep -R CODEX_SANDBOX_ENV_VAR -n .".to_string(),
+ query: Some("CODEX_SANDBOX_ENV_VAR".to_string()),
+ path: Some(".".to_string()),
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_grep_recursive_specific_file() {
+ assert_parsed(
+ &vec_str(&[
+ "grep",
+ "-R",
+ "CODEX_SANDBOX_ENV_VAR",
+ "-n",
+ "core/src/spawn.rs",
+ ]),
+ vec![ParsedCommand::Search {
+ cmd: "grep -R CODEX_SANDBOX_ENV_VAR -n core/src/spawn.rs".to_string(),
+ query: Some("CODEX_SANDBOX_ENV_VAR".to_string()),
+ path: Some("spawn.rs".to_string()),
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_grep_query_with_slashes_not_shortened() {
+ // Query strings may contain slashes and should not be shortened to the basename.
+ // Previously, grep queries were passed through short_display_path, which is incorrect.
+ assert_parsed(
+ &shlex_split_safe("grep -R src/main.rs -n ."),
+ vec![ParsedCommand::Search {
+ cmd: "grep -R src/main.rs -n .".to_string(),
+ query: Some("src/main.rs".to_string()),
+ path: Some(".".to_string()),
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_grep_weird_backtick_in_query() {
+ assert_parsed(
+ &shlex_split_safe("grep -R COD`EX_SANDBOX -n"),
+ vec![ParsedCommand::Search {
+ cmd: "grep -R 'COD`EX_SANDBOX' -n".to_string(),
+ query: Some("COD`EX_SANDBOX".to_string()),
+ path: None,
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_cd_and_rg_files() {
+ assert_parsed(
+ &shlex_split_safe("cd codex-rs && rg --files"),
+ vec![
+ ParsedCommand::Unknown {
+ cmd: "cd codex-rs".to_string(),
+ },
+ ParsedCommand::Search {
+ cmd: "rg --files".to_string(),
+ query: None,
+ path: None,
+ },
+ ],
+ );
+ }
+
+ #[test]
+ fn echo_then_cargo_test_sequence() {
+ assert_parsed(
+ &shlex_split_safe("echo Running tests... && cargo test --all-features --quiet"),
+ vec![ParsedCommand::Test {
+ cmd: "cargo test --all-features --quiet".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_cargo_fmt_and_test_with_config() {
+ assert_parsed(
+ &shlex_split_safe(
+ "cargo fmt -- --config imports_granularity=Item && cargo test -p core --all-features",
+ ),
+ vec![
+ ParsedCommand::Format {
+ cmd: "cargo fmt -- --config 'imports_granularity=Item'".to_string(),
+ tool: Some("cargo fmt".to_string()),
+ targets: None,
+ },
+ ParsedCommand::Test {
+ cmd: "cargo test -p core --all-features".to_string(),
+ },
+ ],
+ );
+ }
+
+ #[test]
+ fn recognizes_rustfmt_and_clippy() {
+ assert_parsed(
+ &shlex_split_safe("rustfmt src/main.rs"),
+ vec![ParsedCommand::Format {
+ cmd: "rustfmt src/main.rs".to_string(),
+ tool: Some("rustfmt".to_string()),
+ targets: Some(vec!["src/main.rs".to_string()]),
+ }],
+ );
+
+ assert_parsed(
+ &shlex_split_safe("cargo clippy -p core --all-features -- -D warnings"),
+ vec![ParsedCommand::Lint {
+ cmd: "cargo clippy -p core --all-features -- -D warnings".to_string(),
+ tool: Some("cargo clippy".to_string()),
+ targets: None,
+ }],
+ );
+ }
+
+ #[test]
+ fn recognizes_pytest_go_and_tools() {
+ assert_parsed(
+ &shlex_split_safe(
+ "pytest -k 'Login and not slow' tests/test_login.py::TestLogin::test_ok",
+ ),
+ vec![ParsedCommand::Test {
+ cmd: "pytest -k 'Login and not slow' tests/test_login.py::TestLogin::test_ok"
+ .to_string(),
+ }],
+ );
+
+ assert_parsed(
+ &shlex_split_safe("go fmt ./..."),
+ vec![ParsedCommand::Format {
+ cmd: "go fmt ./...".to_string(),
+ tool: Some("go fmt".to_string()),
+ targets: Some(vec!["./...".to_string()]),
+ }],
+ );
+
+ assert_parsed(
+ &shlex_split_safe("go test ./pkg -run TestThing"),
+ vec![ParsedCommand::Test {
+ cmd: "go test ./pkg -run TestThing".to_string(),
+ }],
+ );
+
+ assert_parsed(
+ &shlex_split_safe("eslint . --max-warnings 0"),
+ vec![ParsedCommand::Lint {
+ cmd: "eslint . --max-warnings 0".to_string(),
+ tool: Some("eslint".to_string()),
+ targets: Some(vec![".".to_string()]),
+ }],
+ );
+
+ assert_parsed(
+ &shlex_split_safe("prettier -w ."),
+ vec![ParsedCommand::Format {
+ cmd: "prettier -w .".to_string(),
+ tool: Some("prettier".to_string()),
+ targets: Some(vec![".".to_string()]),
+ }],
+ );
+ }
+
+ #[test]
+ fn recognizes_jest_and_vitest_filters() {
+ assert_parsed(
+ &shlex_split_safe("jest -t 'should work' src/foo.test.ts"),
+ vec![ParsedCommand::Test {
+ cmd: "jest -t 'should work' src/foo.test.ts".to_string(),
+ }],
+ );
+
+ assert_parsed(
+ &shlex_split_safe("vitest -t 'runs' src/foo.test.tsx"),
+ vec![ParsedCommand::Test {
+ cmd: "vitest -t runs src/foo.test.tsx".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn recognizes_npx_and_scripts() {
+ assert_parsed(
+ &shlex_split_safe("npx eslint src"),
+ vec![ParsedCommand::Lint {
+ cmd: "npx eslint src".to_string(),
+ tool: Some("eslint".to_string()),
+ targets: Some(vec!["src".to_string()]),
+ }],
+ );
+
+ assert_parsed(
+ &shlex_split_safe("npx prettier -c ."),
+ vec![ParsedCommand::Format {
+ cmd: "npx prettier -c .".to_string(),
+ tool: Some("prettier".to_string()),
+ targets: Some(vec![".".to_string()]),
+ }],
+ );
+
+ assert_parsed(
+ &shlex_split_safe("pnpm run lint -- --max-warnings 0"),
+ vec![ParsedCommand::Lint {
+ cmd: "pnpm run lint -- --max-warnings 0".to_string(),
+ tool: Some("pnpm-script:lint".to_string()),
+ targets: None,
+ }],
+ );
+
+ assert_parsed(
+ &shlex_split_safe("npm test"),
+ vec![ParsedCommand::Test {
+ cmd: "npm test".to_string(),
+ }],
+ );
+
+ assert_parsed(
+ &shlex_split_safe("yarn test"),
+ vec![ParsedCommand::Test {
+ cmd: "yarn test".to_string(),
+ }],
+ );
+ }
+
+ // ---- is_small_formatting_command unit tests ----
+ #[test]
+ fn small_formatting_always_true_commands() {
+ for cmd in [
+ "wc", "tr", "cut", "sort", "uniq", "xargs", "tee", "column", "awk",
+ ] {
+ assert!(is_small_formatting_command(&shlex_split_safe(cmd)));
+ assert!(is_small_formatting_command(&shlex_split_safe(&format!(
+ "{cmd} -x"
+ ))));
+ }
+ }
+
+ #[test]
+ fn head_behavior() {
+ // No args -> small formatting
+ assert!(is_small_formatting_command(&vec_str(&["head"])));
+ // Numeric count only -> not considered small formatting by implementation
+ assert!(!is_small_formatting_command(&shlex_split_safe(
+ "head -n 40"
+ )));
+ // With explicit file -> not small formatting
+ assert!(!is_small_formatting_command(&shlex_split_safe(
+ "head -n 40 file.txt"
+ )));
+ // File only (no count) -> treated as small formatting by implementation
+ assert!(is_small_formatting_command(&vec_str(&["head", "file.txt"])));
+ }
+
+ #[test]
+ fn tail_behavior() {
+ // No args -> small formatting
+ assert!(is_small_formatting_command(&vec_str(&["tail"])));
+ // Numeric with plus offset -> not small formatting
+ assert!(!is_small_formatting_command(&shlex_split_safe(
+ "tail -n +10"
+ )));
+ assert!(!is_small_formatting_command(&shlex_split_safe(
+ "tail -n +10 file.txt"
+ )));
+ // Numeric count
+ assert!(!is_small_formatting_command(&shlex_split_safe(
+ "tail -n 30"
+ )));
+ assert!(!is_small_formatting_command(&shlex_split_safe(
+ "tail -n 30 file.txt"
+ )));
+ // File only -> small formatting by implementation
+ assert!(is_small_formatting_command(&vec_str(&["tail", "file.txt"])));
+ }
+
+ #[test]
+ fn sed_behavior() {
+ // Plain sed -> small formatting
+ assert!(is_small_formatting_command(&vec_str(&["sed"])));
+ // sed -n (no file) -> still small formatting
+ assert!(is_small_formatting_command(&vec_str(&["sed", "-n", "10p"])));
+ // Valid range with file -> not small formatting
+ assert!(!is_small_formatting_command(&shlex_split_safe(
+ "sed -n 10p file.txt"
+ )));
+ assert!(!is_small_formatting_command(&shlex_split_safe(
+ "sed -n 1,200p file.txt"
+ )));
+ // Invalid ranges with file -> small formatting
+ assert!(is_small_formatting_command(&shlex_split_safe(
+ "sed -n p file.txt"
+ )));
+ assert!(is_small_formatting_command(&shlex_split_safe(
+ "sed -n +10p file.txt"
+ )));
+ }
+
+ #[test]
+ fn empty_tokens_is_not_small() {
+ let empty: Vec = Vec::new();
+ assert!(!is_small_formatting_command(&empty));
+ }
+
+ #[test]
+ fn supports_nl_then_sed_reading() {
+ let inner = "nl -ba core/src/parse_command.rs | sed -n '1200,1720p'";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Read {
+ cmd: inner.to_string(),
+ name: "parse_command.rs".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_sed_n() {
+ let inner = "sed -n '2000,2200p' tui/src/history_cell.rs";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Read {
+ cmd: inner.to_string(),
+ name: "history_cell.rs".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn filters_out_printf() {
+ let inner =
+ r#"printf "\n===== ansi-escape/Cargo.toml =====\n"; cat -- ansi-escape/Cargo.toml"#;
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Read {
+ cmd: "cat -- ansi-escape/Cargo.toml".to_string(),
+ name: "Cargo.toml".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn drops_yes_in_pipelines() {
+ // Inside bash -lc, `yes | rg --files` should focus on the primary command.
+ let inner = "yes | rg --files";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Search {
+ cmd: "rg --files".to_string(),
+ query: None,
+ path: None,
+ }],
+ );
+ }
+
+ #[test]
+ fn supports_sed_n_then_nl_as_search() {
+ // Ensure `sed -n '' | nl -ba` is summarized as a search for that file.
+ let args = shlex_split_safe(
+ "sed -n '260,640p' exec/src/event_processor_with_human_output.rs | nl -ba",
+ );
+ assert_parsed(
+ &args,
+ vec![ParsedCommand::Read {
+ cmd: "sed -n '260,640p' exec/src/event_processor_with_human_output.rs".to_string(),
+ name: "event_processor_with_human_output.rs".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn preserves_rg_with_spaces() {
+ assert_parsed(
+ &shlex_split_safe("yes | rg -n 'foo bar' -S"),
+ vec![ParsedCommand::Search {
+ cmd: "rg -n 'foo bar' -S".to_string(),
+ query: Some("foo bar".to_string()),
+ path: None,
+ }],
+ );
+ }
+
+ #[test]
+ fn ls_with_glob() {
+ assert_parsed(
+ &shlex_split_safe("ls -I '*.test.js'"),
+ vec![ParsedCommand::ListFiles {
+ cmd: "ls -I '*.test.js'".to_string(),
+ path: None,
+ }],
+ );
+ }
+
+ #[test]
+ fn trim_on_semicolon() {
+ assert_parsed(
+ &shlex_split_safe("rg foo ; echo done"),
+ vec![
+ ParsedCommand::Search {
+ cmd: "rg foo".to_string(),
+ query: Some("foo".to_string()),
+ path: None,
+ },
+ ParsedCommand::Unknown {
+ cmd: "echo done".to_string(),
+ },
+ ],
+ );
+ }
+
+ #[test]
+ fn split_on_or_connector() {
+ // Ensure we split commands on the logical OR operator as well.
+ assert_parsed(
+ &shlex_split_safe("rg foo || echo done"),
+ vec![
+ ParsedCommand::Search {
+ cmd: "rg foo".to_string(),
+ query: Some("foo".to_string()),
+ path: None,
+ },
+ ParsedCommand::Unknown {
+ cmd: "echo done".to_string(),
+ },
+ ],
+ );
+ }
+
+ #[test]
+ fn strips_true_in_sequence() {
+ // `true` should be dropped from parsed sequences
+ assert_parsed(
+ &shlex_split_safe("true && rg --files"),
+ vec![ParsedCommand::Search {
+ cmd: "rg --files".to_string(),
+ query: None,
+ path: None,
+ }],
+ );
+
+ assert_parsed(
+ &shlex_split_safe("rg --files && true"),
+ vec![ParsedCommand::Search {
+ cmd: "rg --files".to_string(),
+ query: None,
+ path: None,
+ }],
+ );
+ }
+
+ #[test]
+ fn strips_true_inside_bash_lc() {
+ let inner = "true && rg --files";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner]),
+ vec![ParsedCommand::Search {
+ cmd: "rg --files".to_string(),
+ query: None,
+ path: None,
+ }],
+ );
+
+ let inner2 = "rg --files || true";
+ assert_parsed(
+ &vec_str(&["bash", "-lc", inner2]),
+ vec![ParsedCommand::Search {
+ cmd: "rg --files".to_string(),
+ query: None,
+ path: None,
+ }],
+ );
+ }
+
+ #[test]
+ fn shorten_path_on_windows() {
+ assert_parsed(
+ &shlex_split_safe(r#"cat "pkg\src\main.rs""#),
+ vec![ParsedCommand::Read {
+ cmd: r#"cat "pkg\\src\\main.rs""#.to_string(),
+ name: "main.rs".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn head_with_no_space() {
+ assert_parsed(
+ &shlex_split_safe("bash -lc 'head -n50 Cargo.toml'"),
+ vec![ParsedCommand::Read {
+ cmd: "head -n50 Cargo.toml".to_string(),
+ name: "Cargo.toml".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn bash_dash_c_pipeline_parsing() {
+ // Ensure -c is handled similarly to -lc by normalization
+ let inner = "rg --files | head -n 1";
+ assert_parsed(
+ &shlex_split_safe(inner),
+ vec![
+ ParsedCommand::Search {
+ cmd: "rg --files".to_string(),
+ query: None,
+ path: None,
+ },
+ ParsedCommand::Unknown {
+ cmd: "head -n 1".to_string(),
+ },
+ ],
+ );
+ }
+
+ #[test]
+ fn tail_with_no_space() {
+ assert_parsed(
+ &shlex_split_safe("bash -lc 'tail -n+10 README.md'"),
+ vec![ParsedCommand::Read {
+ cmd: "tail -n+10 README.md".to_string(),
+ name: "README.md".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn pnpm_test_is_parsed_as_test() {
+ assert_parsed(
+ &shlex_split_safe("pnpm test"),
+ vec![ParsedCommand::Test {
+ cmd: "pnpm test".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn pnpm_exec_vitest_is_unknown() {
+ // From commands_combined: cd codex-cli && pnpm exec vitest run tests/... --threads=false --passWithNoTests
+ let inner = "cd codex-cli && pnpm exec vitest run tests/file-tag-utils.test.ts --threads=false --passWithNoTests";
+ assert_parsed(
+ &shlex_split_safe(inner),
+ vec![
+ ParsedCommand::Unknown {
+ cmd: "cd codex-cli".to_string(),
+ },
+ ParsedCommand::Unknown {
+ cmd: "pnpm exec vitest run tests/file-tag-utils.test.ts '--threads=false' --passWithNoTests".to_string(),
+ },
+ ],
+ );
+ }
+
+ #[test]
+ fn cargo_test_with_crate() {
+ assert_parsed(
+ &shlex_split_safe("cargo test -p codex-core parse_command::"),
+ vec![ParsedCommand::Test {
+ cmd: "cargo test -p codex-core parse_command::".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn cargo_test_with_crate_2() {
+ assert_parsed(
+ &shlex_split_safe(
+ "cd core && cargo test -q parse_command::tests::bash_dash_c_pipeline_parsing parse_command::tests::fd_file_finder_variants",
+ ),
+ vec![ParsedCommand::Test {
+ cmd: "cargo test -q parse_command::tests::bash_dash_c_pipeline_parsing parse_command::tests::fd_file_finder_variants".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn cargo_test_with_crate_3() {
+ assert_parsed(
+ &shlex_split_safe("cd core && cargo test -q parse_command::tests"),
+ vec![ParsedCommand::Test {
+ cmd: "cargo test -q parse_command::tests".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn cargo_test_with_crate_4() {
+ assert_parsed(
+ &shlex_split_safe("cd core && cargo test --all-features parse_command -- --nocapture"),
+ vec![ParsedCommand::Test {
+ cmd: "cargo test --all-features parse_command -- --nocapture".to_string(),
+ }],
+ );
+ }
+
+ // Additional coverage for other common tools/frameworks
+ #[test]
+ fn recognizes_black_and_ruff() {
+ // black formats Python code
+ assert_parsed(
+ &shlex_split_safe("black src"),
+ vec![ParsedCommand::Format {
+ cmd: "black src".to_string(),
+ tool: Some("black".to_string()),
+ targets: Some(vec!["src".to_string()]),
+ }],
+ );
+
+ // ruff check is a linter; ensure we collect targets
+ assert_parsed(
+ &shlex_split_safe("ruff check ."),
+ vec![ParsedCommand::Lint {
+ cmd: "ruff check .".to_string(),
+ tool: Some("ruff".to_string()),
+ targets: Some(vec![".".to_string()]),
+ }],
+ );
+
+ // ruff format is a formatter
+ assert_parsed(
+ &shlex_split_safe("ruff format pkg/"),
+ vec![ParsedCommand::Format {
+ cmd: "ruff format pkg/".to_string(),
+ tool: Some("ruff".to_string()),
+ targets: Some(vec!["pkg/".to_string()]),
+ }],
+ );
+ }
+
+ #[test]
+ fn recognizes_pnpm_monorepo_test_and_npm_format_script() {
+ // pnpm -r test in a monorepo should still parse as a test action
+ assert_parsed(
+ &shlex_split_safe("pnpm -r test"),
+ vec![ParsedCommand::Test {
+ cmd: "pnpm -r test".to_string(),
+ }],
+ );
+
+ // npm run format should be recognized as a format action
+ assert_parsed(
+ &shlex_split_safe("npm run format -- -w ."),
+ vec![ParsedCommand::Format {
+ cmd: "npm run format -- -w .".to_string(),
+ tool: Some("npm-script:format".to_string()),
+ targets: None,
+ }],
+ );
+ }
+
+ #[test]
+ fn yarn_test_is_parsed_as_test() {
+ assert_parsed(
+ &shlex_split_safe("yarn test"),
+ vec![ParsedCommand::Test {
+ cmd: "yarn test".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn pytest_file_only_and_go_run_regex() {
+ // pytest invoked with a file path should be captured as a filter
+ assert_parsed(
+ &shlex_split_safe("pytest tests/test_example.py"),
+ vec![ParsedCommand::Test {
+ cmd: "pytest tests/test_example.py".to_string(),
+ }],
+ );
+
+ // go test with -run regex should capture the filter
+ assert_parsed(
+ &shlex_split_safe("go test ./... -run '^TestFoo$'"),
+ vec![ParsedCommand::Test {
+ cmd: "go test ./... -run '^TestFoo$'".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn grep_with_query_and_path() {
+ assert_parsed(
+ &shlex_split_safe("grep -R TODO src"),
+ vec![ParsedCommand::Search {
+ cmd: "grep -R TODO src".to_string(),
+ query: Some("TODO".to_string()),
+ path: Some("src".to_string()),
+ }],
+ );
+ }
+
+ #[test]
+ fn rg_with_equals_style_flags() {
+ assert_parsed(
+ &shlex_split_safe("rg --colors=never -n foo src"),
+ vec![ParsedCommand::Search {
+ cmd: "rg '--colors=never' -n foo src".to_string(),
+ query: Some("foo".to_string()),
+ path: Some("src".to_string()),
+ }],
+ );
+ }
+
+ #[test]
+ fn cat_with_double_dash_and_sed_ranges() {
+ // cat -- should be treated as a read of that file
+ assert_parsed(
+ &shlex_split_safe("cat -- ./-strange-file-name"),
+ vec![ParsedCommand::Read {
+ cmd: "cat -- ./-strange-file-name".to_string(),
+ name: "-strange-file-name".to_string(),
+ }],
+ );
+
+ // sed -n should be treated as a read of
+ assert_parsed(
+ &shlex_split_safe("sed -n '12,20p' Cargo.toml"),
+ vec![ParsedCommand::Read {
+ cmd: "sed -n '12,20p' Cargo.toml".to_string(),
+ name: "Cargo.toml".to_string(),
+ }],
+ );
+ }
+
+ #[test]
+ fn drop_trailing_nl_in_pipeline() {
+ // When an `nl` stage has only flags, it should be dropped from the summary
+ assert_parsed(
+ &shlex_split_safe("rg --files | nl -ba"),
+ vec![ParsedCommand::Search {
+ cmd: "rg --files".to_string(),
+ query: None,
+ path: None,
+ }],
+ );
+ }
+
+ #[test]
+ fn ls_with_time_style_and_path() {
+ assert_parsed(
+ &shlex_split_safe("ls --time-style=long-iso ./dist"),
+ vec![ParsedCommand::ListFiles {
+ cmd: "ls '--time-style=long-iso' ./dist".to_string(),
+ // short_display_path drops "dist" and shows "." as the last useful segment
+ path: Some(".".to_string()),
+ }],
+ );
+ }
+
+ #[test]
+ fn eslint_with_config_path_and_target() {
+ assert_parsed(
+ &shlex_split_safe("eslint -c .eslintrc.json src"),
+ vec![ParsedCommand::Lint {
+ cmd: "eslint -c .eslintrc.json src".to_string(),
+ tool: Some("eslint".to_string()),
+ targets: Some(vec!["src".to_string()]),
+ }],
+ );
+ }
+
+ #[test]
+ fn npx_eslint_with_config_path_and_target() {
+ assert_parsed(
+ &shlex_split_safe("npx eslint -c .eslintrc src"),
+ vec![ParsedCommand::Lint {
+ cmd: "npx eslint -c .eslintrc src".to_string(),
+ tool: Some("eslint".to_string()),
+ targets: Some(vec!["src".to_string()]),
+ }],
+ );
+ }
+
+ #[test]
+ fn fd_file_finder_variants() {
+ assert_parsed(
+ &shlex_split_safe("fd -t f src/"),
+ vec![ParsedCommand::Search {
+ cmd: "fd -t f src/".to_string(),
+ query: None,
+ path: Some("src".to_string()),
+ }],
+ );
+
+ // fd with query and path should capture both
+ assert_parsed(
+ &shlex_split_safe("fd main src"),
+ vec![ParsedCommand::Search {
+ cmd: "fd main src".to_string(),
+ query: Some("main".to_string()),
+ path: Some("src".to_string()),
+ }],
+ );
+ }
+
+ #[test]
+ fn find_basic_name_filter() {
+ assert_parsed(
+ &shlex_split_safe("find . -name '*.rs'"),
+ vec![ParsedCommand::Search {
+ cmd: "find . -name '*.rs'".to_string(),
+ query: Some("*.rs".to_string()),
+ path: Some(".".to_string()),
+ }],
+ );
+ }
+
+ #[test]
+ fn find_type_only_path() {
+ assert_parsed(
+ &shlex_split_safe("find src -type f"),
+ vec![ParsedCommand::Search {
+ cmd: "find src -type f".to_string(),
+ query: None,
+ path: Some("src".to_string()),
+ }],
+ );
+ }
+}
+
+pub fn parse_command_impl(command: &[String]) -> Vec {
+ if let Some(commands) = parse_bash_lc_commands(command) {
+ return commands;
+ }
+
+ let normalized = normalize_tokens(command);
+
+ let parts = if contains_connectors(&normalized) {
+ split_on_connectors(&normalized)
+ } else {
+ vec![normalized.clone()]
+ };
+
+ // Preserve left-to-right execution order for all commands, including bash -c/-lc
+ // so summaries reflect the order they will run.
+
+ // Map each pipeline segment to its parsed summary.
+ let mut commands: Vec = parts
+ .iter()
+ .map(|tokens| summarize_main_tokens(tokens))
+ .collect();
+
+ while let Some(next) = simplify_once(&commands) {
+ commands = next;
+ }
+
+ commands
+}
+
+fn simplify_once(commands: &[ParsedCommand]) -> Option> {
+ if commands.len() <= 1 {
+ return None;
+ }
+
+ // echo ... && ...rest => ...rest
+ if let ParsedCommand::Unknown { cmd } = &commands[0] {
+ if shlex_split(cmd).is_some_and(|t| t.first().map(|s| s.as_str()) == Some("echo")) {
+ return Some(commands[1..].to_vec());
+ }
+ }
+
+ // cd foo && [any Test command] => [any Test command]
+ if let Some(idx) = commands.iter().position(|pc| match pc {
+ ParsedCommand::Unknown { cmd } => {
+ shlex_split(cmd).is_some_and(|t| t.first().map(|s| s.as_str()) == Some("cd"))
+ }
+ _ => false,
+ }) {
+ if commands
+ .iter()
+ .skip(idx + 1)
+ .any(|pc| matches!(pc, ParsedCommand::Test { .. }))
+ {
+ let mut out = Vec::with_capacity(commands.len() - 1);
+ out.extend_from_slice(&commands[..idx]);
+ out.extend_from_slice(&commands[idx + 1..]);
+ return Some(out);
+ }
+ }
+
+ // cmd || true => cmd
+ if let Some(idx) = commands.iter().position(|pc| match pc {
+ ParsedCommand::Noop { cmd } => cmd == "true",
+ _ => false,
+ }) {
+ let mut out = Vec::with_capacity(commands.len() - 1);
+ out.extend_from_slice(&commands[..idx]);
+ out.extend_from_slice(&commands[idx + 1..]);
+ return Some(out);
+ }
+
+ // nl -[any_flags] && ...rest => ...rest
+ if let Some(idx) = commands.iter().position(|pc| match pc {
+ ParsedCommand::Unknown { cmd } => {
+ if let Some(tokens) = shlex_split(cmd) {
+ tokens.first().is_some_and(|s| s.as_str() == "nl")
+ && tokens.iter().skip(1).all(|t| t.starts_with('-'))
+ } else {
+ false
+ }
+ }
+ _ => false,
+ }) {
+ let mut out = Vec::with_capacity(commands.len() - 1);
+ out.extend_from_slice(&commands[..idx]);
+ out.extend_from_slice(&commands[idx + 1..]);
+ return Some(out);
+ }
+
+ None
+}
+
+/// Validates that this is a `sed -n 123,123p` command.
+fn is_valid_sed_n_arg(arg: Option<&str>) -> bool {
+ let s = match arg {
+ Some(s) => s,
+ None => return false,
+ };
+ let core = match s.strip_suffix('p') {
+ Some(rest) => rest,
+ None => return false,
+ };
+ let parts: Vec<&str> = core.split(',').collect();
+ match parts.as_slice() {
+ [num] => !num.is_empty() && num.chars().all(|c| c.is_ascii_digit()),
+ [a, b] => {
+ !a.is_empty()
+ && !b.is_empty()
+ && a.chars().all(|c| c.is_ascii_digit())
+ && b.chars().all(|c| c.is_ascii_digit())
+ }
+ _ => false,
+ }
+}
+
+/// Normalize a command by:
+/// - Removing `yes`/`no`/`bash -c`/`bash -lc` prefixes.
+/// - Splitting on `|` and `&&`/`||`/`;
+fn normalize_tokens(cmd: &[String]) -> Vec {
+ match cmd {
+ [first, pipe, rest @ ..] if (first == "yes" || first == "y") && pipe == "|" => {
+ // Do not re-shlex already-tokenized input; just drop the prefix.
+ rest.to_vec()
+ }
+ [first, pipe, rest @ ..] if (first == "no" || first == "n") && pipe == "|" => {
+ // Do not re-shlex already-tokenized input; just drop the prefix.
+ rest.to_vec()
+ }
+ [bash, flag, script] if bash == "bash" && (flag == "-c" || flag == "-lc") => {
+ shlex_split(script)
+ .unwrap_or_else(|| vec!["bash".to_string(), flag.clone(), script.clone()])
+ }
+ _ => cmd.to_vec(),
+ }
+}
+
+fn contains_connectors(tokens: &[String]) -> bool {
+ tokens
+ .iter()
+ .any(|t| t == "&&" || t == "||" || t == "|" || t == ";")
+}
+
+fn split_on_connectors(tokens: &[String]) -> Vec> {
+ let mut out: Vec> = Vec::new();
+ let mut cur: Vec = Vec::new();
+ for t in tokens {
+ if t == "&&" || t == "||" || t == "|" || t == ";" {
+ if !cur.is_empty() {
+ out.push(std::mem::take(&mut cur));
+ }
+ } else {
+ cur.push(t.clone());
+ }
+ }
+ if !cur.is_empty() {
+ out.push(cur);
+ }
+ out
+}
+
+fn trim_at_connector(tokens: &[String]) -> Vec {
+ let idx = tokens
+ .iter()
+ .position(|t| t == "|" || t == "&&" || t == "||" || t == ";")
+ .unwrap_or(tokens.len());
+ tokens[..idx].to_vec()
+}
+
+/// Shorten a path to the last component, excluding `build`/`dist`/`node_modules`/`src`.
+/// It also pulls out a useful path from a directory such as:
+/// - webview/src -> webview
+/// - foo/src/ -> foo
+/// - packages/app/node_modules/ -> app
+fn short_display_path(path: &str) -> String {
+ // Normalize separators and drop any trailing slash for display.
+ let normalized = path.replace('\\', "/");
+ let trimmed = normalized.trim_end_matches('/');
+ let mut parts = trimmed.split('/').rev().filter(|p| {
+ !p.is_empty() && *p != "build" && *p != "dist" && *p != "node_modules" && *p != "src"
+ });
+ parts
+ .next()
+ .map(|s| s.to_string())
+ .unwrap_or_else(|| trimmed.to_string())
+}
+
+// Skip values consumed by specific flags and ignore --flag=value style arguments.
+fn skip_flag_values<'a>(args: &'a [String], flags_with_vals: &[&str]) -> Vec<&'a String> {
+ let mut out: Vec<&'a String> = Vec::new();
+ let mut skip_next = false;
+ for (i, a) in args.iter().enumerate() {
+ if skip_next {
+ skip_next = false;
+ continue;
+ }
+ if a == "--" {
+ // From here on, everything is positional operands; push the rest and break.
+ for rest in &args[i + 1..] {
+ out.push(rest);
+ }
+ break;
+ }
+ if a.starts_with("--") && a.contains('=') {
+ // --flag=value form: treat as a flag taking a value; skip entirely.
+ continue;
+ }
+ if flags_with_vals.contains(&a.as_str()) {
+ // This flag consumes the next argument as its value.
+ if i + 1 < args.len() {
+ skip_next = true;
+ }
+ continue;
+ }
+ out.push(a);
+ }
+ out
+}
+
+/// Common flags for ESLint that take a following value and should not be
+/// considered positional targets.
+const ESLINT_FLAGS_WITH_VALUES: &[&str] = &[
+ "-c",
+ "--config",
+ "--parser",
+ "--parser-options",
+ "--rulesdir",
+ "--plugin",
+ "--max-warnings",
+ "--format",
+];
+
+fn collect_non_flag_targets(args: &[String]) -> Option> {
+ let mut targets = Vec::new();
+ let mut skip_next = false;
+ for (i, a) in args.iter().enumerate() {
+ if a == "--" {
+ break;
+ }
+ if skip_next {
+ skip_next = false;
+ continue;
+ }
+ if a == "-p"
+ || a == "--package"
+ || a == "--features"
+ || a == "-C"
+ || a == "--config"
+ || a == "--config-path"
+ || a == "--out-dir"
+ || a == "-o"
+ || a == "--run"
+ || a == "--max-warnings"
+ || a == "--format"
+ {
+ if i + 1 < args.len() {
+ skip_next = true;
+ }
+ continue;
+ }
+ if a.starts_with('-') {
+ continue;
+ }
+ targets.push(a.clone());
+ }
+ if targets.is_empty() {
+ None
+ } else {
+ Some(targets)
+ }
+}
+
+fn collect_non_flag_targets_with_flags(
+ args: &[String],
+ flags_with_vals: &[&str],
+) -> Option> {
+ let targets: Vec = skip_flag_values(args, flags_with_vals)
+ .into_iter()
+ .filter(|a| !a.starts_with('-'))
+ .cloned()
+ .collect();
+ if targets.is_empty() {
+ None
+ } else {
+ Some(targets)
+ }
+}
+
+fn is_pathish(s: &str) -> bool {
+ s == "."
+ || s == ".."
+ || s.starts_with("./")
+ || s.starts_with("../")
+ || s.contains('/')
+ || s.contains('\\')
+}
+
+fn parse_fd_query_and_path(tail: &[String]) -> (Option, Option