rust-cli-agent-style

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OpenAI Codex Rust CLI Agent Best Practices

OpenAI Codex Rust CLI Agent 最佳实践

This skill teaches you to write Rust code in the style of the OpenAI Codex codebase - a production CLI/agent system with 50 crates and 787 Rust files.
本技能将教你以OpenAI Codex代码库的风格编写Rust代码——这是一个包含50个crate和787个Rust文件的生产级CLI/Agent系统。

Key Characteristics

核心特性

  • Edition 2024 with strict Clippy configuration
  • Zero unwrap/expect in non-test code (enforced at workspace level)
  • Tokio async runtime with proper Send + Sync bounds
  • thiserror for library errors, anyhow for application code
  • Flat workspace structure with centralized dependencies
  • 采用2024 Edition及严格的Clippy配置
  • 非测试代码中禁止使用unwrap/expect(在工作区层面强制执行)
  • 带有正确Send + Sync约束的Tokio异步运行时
  • 库错误使用thiserror,应用代码使用anyhow
  • 集中管理依赖的扁平化工作区结构

When to Apply

适用场景

Apply this skill when:
  • Building CLI tools or agent systems in Rust
  • Writing async Rust with Tokio
  • Designing Rust workspace organization
  • Implementing error handling patterns
  • Working on production Rust codebases
在以下场景中应用本技能:
  • 使用Rust构建CLI工具或Agent系统
  • 编写基于Tokio的异步Rust代码
  • 设计Rust工作区的组织结构
  • 实现错误处理模式
  • 开发生产级Rust代码库

Quick Reference

快速参考

Critical Rules (Must Follow)

核心规则(必须遵守)

RuleDescription
err-no-unwrapNever use
unwrap()
in non-test code
err-no-expectAvoid
expect()
in library code
err-thiserror-domainUse thiserror for domain errors
err-context-chainAdd context to errors with
.context()
规则描述
err-no-unwrap非测试代码中禁止使用
unwrap()
err-no-expect库代码中避免使用
expect()
err-thiserror-domain使用thiserror处理领域错误
err-context-chain使用
.context()
为错误添加上下文信息

Error Handling

错误处理

RuleDescription
err-anyhow-applicationUse anyhow::Result for entry points
err-from-deriveUse #[from] for error conversion
err-transparentUse #[error(transparent)] for wrapped errors
err-structured-variantsInclude relevant data in error variants
err-io-resultUse std::io::Result for I/O functions
err-map-err-conversionUse map_err for error conversion
err-doc-errorsDocument error conditions
规则描述
err-anyhow-application入口点使用anyhow::Result
err-from-derive使用#[from]进行错误转换
err-transparent使用#[error(transparent)]包装错误
err-structured-variants错误变体中包含相关数据
err-io-resultI/O函数使用std::io::Result
err-map-err-conversion使用map_err进行错误转换
err-doc-errors为错误场景添加文档说明

Organization

组织结构

RuleDescription
org-workspace-flatFlat workspace with utils subdirectory
org-crate-namingkebab-case directories, project prefix
org-module-visibilityUse pub(crate) for internal APIs
org-test-common-crateShared test utilities crate
org-integration-tests-suiteTests in suite directory
org-feature-modulesFeature-based module organization
org-handlers-subdirHandlers in dedicated subdirectory
org-errors-fileErrors in dedicated file
规则描述
org-workspace-flat带有utils子目录的扁平化工作区
org-crate-naming目录使用kebab-case,带项目前缀
org-module-visibility内部API使用pub(crate)
org-test-common-crate共享测试工具crate
org-integration-tests-suite测试用例放在suite目录
org-feature-modules基于功能的模块组织方式
org-handlers-subdir处理器放在专用子目录
org-errors-file错误定义放在专用文件

Component Patterns

组件模式

RuleDescription
mod-derive-orderConsistent derive macro ordering
mod-async-trait-macroUse #[async_trait] for async traits
mod-trait-boundsSend + Sync + 'static for concurrent traits
mod-extension-trait-suffixExt suffix for extension traits
mod-builder-patternBuilder pattern for complex config
mod-type-alias-complexType aliases for complex generics
mod-impl-block-orderConsistent impl block ordering
mod-generic-constraintsWhere clauses for complex bounds
mod-newtype-patternNewtypes for type safety
mod-struct-visibilityPrivate fields with public constructor
mod-serde-renameSerde rename for wire format
mod-jsonschema-deriveJsonSchema for API types
规则描述
mod-derive-order一致的derive宏顺序
mod-async-trait-macro异步 trait 使用#[async_trait]
mod-trait-bounds并发 trait 需满足Send + Sync + 'static
mod-extension-trait-suffix扩展 trait 使用Ext后缀
mod-builder-pattern复杂配置使用建造者模式
mod-type-alias-complex复杂泛型使用类型别名
mod-impl-block-order一致的impl块顺序
mod-generic-constraints复杂约束使用Where子句
mod-newtype-pattern使用Newtype模式保证类型安全
mod-struct-visibility私有字段搭配公共构造函数
mod-serde-renameSerde重命名适配有线格式
mod-jsonschema-deriveAPI类型使用JsonSchema

Naming Conventions

命名规范

RuleDescription
name-async-no-suffixNo _async suffix for async functions
name-try-prefix-fallibletry_ prefix for fallible constructors
name-with-prefix-builderwith_ prefix for builder methods
name-handler-suffixHandler suffix for handlers
name-error-suffixError suffix for error types
name-result-type-aliasCrate-specific Result alias
name-const-env-var_ENV_VAR suffix for env constants
name-request-responseRequest/Response type pairing
name-options-suffixOptions suffix for config bundles
name-info-suffixInfo suffix for read-only data
name-provider-suffixProvider suffix for services
name-client-suffixClient suffix for API clients
name-manager-suffixManager suffix for lifecycle mgmt
name-bool-is-prefixis_/has_/should_ for booleans
name-plural-collectionsPlural names for collections
规则描述
name-async-no-suffix异步函数不添加_async后缀
name-try-prefix-fallible可能失败的构造函数使用try_前缀
name-with-prefix-builder建造者方法使用with_前缀
name-handler-suffix处理器使用Handler后缀
name-error-suffix错误类型使用Error后缀
name-result-type-aliascrate专属的Result别名
name-const-env-var环境常量使用_ENV_VAR后缀
name-request-responseRequest/Response类型配对
name-options-suffix配置集合使用Options后缀
name-info-suffix只读数据使用Info后缀
name-provider-suffix服务使用Provider后缀
name-client-suffixAPI客户端使用Client后缀
name-manager-suffix生命周期管理使用Manager后缀
name-bool-is-prefix布尔值使用is_/has_/should_前缀
name-plural-collections集合使用复数名称

Style

代码风格

RuleDescription
style-import-granularityOne item per use statement
style-deny-stdoutDeny stdout/stderr in libraries
style-inline-format-argsInline format arguments
style-module-docsModule-level documentation
style-expect-reason#[expect] with reason for lints
style-cfg-test-moduleUnit tests in mod tests
规则描述
style-import-granularity每个use语句仅导入一个项
style-deny-stdout库中禁止直接输出到stdout/stderr
style-inline-format-args内联格式化参数
style-module-docs模块级文档说明
style-expect-reason为lint禁用添加#[expect]及原因
style-cfg-test-module单元测试放在mod tests中

Cross-Crate

跨Crate规范

RuleDescription
cross-workspace-lintsWorkspace-level lint config
cross-workspace-depsCentralized dependency versions
规则描述
cross-workspace-lints工作区级别的lint配置
cross-workspace-deps集中管理依赖版本

Example: Proper Error Handling

示例:正确的错误处理

rust
use thiserror::Error;
use anyhow::Context;

// Domain error with thiserror
#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("failed to read config file: {path}")]
    ReadFailed {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error(transparent)]
    Parse(#[from] toml::de::Error),
}

// Library function returns domain error
pub fn load_config(path: &Path) -> Result<Config, ConfigError> {
    let content = fs::read_to_string(path)
        .map_err(|source| ConfigError::ReadFailed {
            path: path.to_owned(),
            source,
        })?;
    toml::from_str(&content).map_err(Into::into)
}

// Application code uses anyhow with context
fn main() -> anyhow::Result<()> {
    let config = load_config(Path::new("config.toml"))
        .context("failed to load configuration")?;
    run(config).await
}
rust
use thiserror::Error;
use anyhow::Context;

// Domain error with thiserror
#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("failed to read config file: {path}")]
    ReadFailed {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error(transparent)]
    Parse(#[from] toml::de::Error),
}

// Library function returns domain error
pub fn load_config(path: &Path) -> Result<Config, ConfigError> {
    let content = fs::read_to_string(path)
        .map_err(|source| ConfigError::ReadFailed {
            path: path.to_owned(),
            source,
        })?;
    toml::from_str(&content).map_err(Into::into)
}

// Application code uses anyhow with context
fn main() -> anyhow::Result<()> {
    let config = load_config(Path::new("config.toml"))
        .context("failed to load configuration")?;
    run(config).await
}

Source

来源

Patterns extracted from OpenAI Codex (
codex-rs/
subdirectory) - a production Rust codebase with 50 crates and 787 Rust files.
这些模式提取自OpenAI Codex
codex-rs/
子目录——一个包含50个crate和787个Rust文件的生产级Rust代码库。