10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Codexのエージェントが使っているツールって知ってますか?

10
Last updated at Posted at 2025-10-18

Codexのエージェントが内部で使用している全てのツールについて説明します。

はじめに

このドキュメントについて

このドキュメントは、Codex CLIエージェントが内部で使用する全てのツール、コマンド、シェル、スクリプト、バイナリを網羅的に調査・記録した技術リファレンスです。Codexのソースコード(Rustコードベース)を直接解析し、実装の詳細から使用方法まで、エージェントの内部動作を完全に理解するために必要な情報を提供します。

ドキュメントの構成

このドキュメントは以下の7つの主要セクションで構成されています:

  1. エージェントツール: LLMが直接呼び出せる13種類のツールの完全仕様
  2. シェル環境: Bash、Zsh、PowerShellなど、各プラットフォームのシェル実装
  3. 内部バイナリ: Codexが使用する3つのRustバイナリの詳細
  4. 外部コマンド: Git、ripgrepなど、システムコマンドの使用方法
  5. サンドボックス機構: macOS、Linux、Windowsの多層セキュリティアーキテクチャ
  6. 実行フロー: ツール呼び出しからコマンド実行までのフローチャート
  7. セーフティチェック: コマンドの安全性検証とホワイトリスト/ブラックリスト

概要

  • ツール総数: 13種類(基本ツール + 実験的ツール + MCP拡張)
  • シェルサポート: 4種類(Bash, Zsh, PowerShell, sh)
  • 内部バイナリ: 3個(apply_patch, linux-sandbox, responses-api-proxy)
  • 外部コマンド: Git(35+サブコマンド)、ripgrep、sandbox-exec など
  • サンドボックス: macOS(Seatbelt)、Linux(Landlock+Seccomp)、Windows(なし)
  • セキュリティ層: 3層防御(Safety Check → Approval Policy → Sandbox)

目次

  1. エージェントツール
  2. シェル環境
  3. 内部バイナリ
  4. 外部コマンド
  5. サンドボックス機構
  6. 実行フロー
  7. セーフティチェック

エージェントツール

Codexエージェントは以下のツールをLLMに提供します。これらはモデルから直接呼び出し可能です。

ツール一覧表

以下は全エージェントツールの概要です:

ツール名 カテゴリ 説明 有効化方法 並列実行
shell シェル実行 基本的なシェルコマンド実行 デフォルト有効
local_shell シェル実行 Responses API組み込みシェル モデル依存 (GPT-5系)
exec_command シェル実行 PTYベースストリーミングコマンド実行 streamable_shell
write_stdin シェル実行 exec_command セッションへの入力 streamable_shell
unified_exec シェル実行 統合PTY実行ツール(実験的) unified_exec
apply_patch ファイル操作 ファイル作成・更新・削除 apply_patch_freeform
read_file ファイル操作 ファイル読み取り(行番号付き) experimental_supported_tools
list_dir ファイル操作 ディレクトリ一覧表示 experimental_supported_tools
grep_files ファイル操作 ファイル内容検索 experimental_supported_tools
view_image ファイル操作 画像ファイルをコンテキストに添付 view_image_tool
update_plan プランニング タスクプランの記録・更新 plan_tool
web_search 外部連携 Web検索(Responses API経由) web_search_request
MCP Tools 外部連携 MCPサーバー経由のカスタムツール mcp_servers 設定 モデル依存

ツールカテゴリ別Mermaid図


1. シェル実行ツール

1.1 shell (デフォルト)

説明: シェルコマンドを実行して出力を返す

定義場所: codex-rs/core/src/tools/spec.rs:189

パラメータ:

{
  "command": ["string"],           // 実行するコマンド(必須)
  "workdir": "string",             // 作業ディレクトリ(オプション)
  "timeout_ms": number,            // タイムアウト(ミリ秒、オプション)
  "with_escalated_permissions": boolean,  // 昇格された権限(オプション)
  "justification": "string"        // 権限昇格の理由(オプション)
}

ハンドラー: ShellHandler (codex-rs/core/src/tools/handlers/shell.rs)

使用シェル:

  • macOS/Linux: bash, zsh(ユーザー環境に応じて自動検出)
  • Windows: PowerShell (pwsh または powershell.exe)

実行例:

{
  "command": ["ls", "-la"],
  "workdir": "/home/user/project"
}

1.2 local_shell

説明: OpenAI Responses APIの組み込みシェルツール

定義場所: codex-rs/core/src/tools/spec.rs:753

特徴:

  • Responses API専用の特殊ツール
  • JSON形式ではなくAPI側で直接処理される
  • model_family.uses_local_shell_tool = true の場合に使用

使用モデル: GPT-5系モデル


1.3 exec_command + write_stdin (Streamable Shell)

説明: ストリーミング可能な対話型シェル実行ツール

定義場所: codex-rs/core/src/exec_command/responses_api.rs

特徴:

  • PTYベースの対話型セッション
  • セッションIDで状態を保持
  • リアルタイムで出力をストリーミング

exec_command パラメータ:

{
  "cmd": "string",              // 実行するシェルコマンド(必須)
  "yield_time_ms": number,      // 出力待機時間(オプション)
  "max_output_tokens": number,  // 最大出力トークン数(オプション)
  "shell": "string",            // シェルパス(デフォルト: /bin/bash)
  "login": boolean              // ログインシェルとして実行(デフォルト: true
}

write_stdin パラメータ:

{
  "session_id": number,         // exec_commandセッションID(必須)
  "chars": "string",            // stdinに書き込む文字列(必須)
  "yield_time_ms": number,      // 出力待機時間(オプション)
  "max_output_tokens": number   // 最大出力トークン数(オプション)
}

使用例:

// セッション開始
{ "cmd": "python3" }
//  session_id: 12345

// 対話的に入力
{ "session_id": 12345, "chars": "print('Hello')\n" }

// Ctrl-C送信
{ "session_id": 12345, "chars": "\u0003" }

ハンドラー: ExecStreamHandler (codex-rs/core/src/tools/handlers/exec_stream.rs)


1.4 unified_exec (実験的)

説明: 統一されたPTYベースの実行ツール

定義場所: codex-rs/core/src/tools/spec.rs:142

パラメータ:

{
  "input": ["string"],          // コマンド配列またはstdin入力(必須)
  "session_id": "string",       // 既存セッションID(オプション)
  "timeout_ms": number          // タイムアウト(オプション)
}

特徴:

  • exec_commandwrite_stdin を統合
  • フィーチャーフラグ unified_exec = true で有効化

ハンドラー: UnifiedExecHandler (codex-rs/core/src/tools/handlers/unified_exec.rs)


2. ファイル操作ツール

2.1 apply_patch

説明: ファイルの作成・更新・削除を行うパッチツール

定義場所: codex-rs/core/src/tools/handlers/apply_patch.rs

タイプ:

  • Freeform: カスタム文法(Lark Grammar)を使用
  • Function: JSON形式

Freeform文法例:

*** Begin Patch
*** Update File: src/main.rs
@@ class MyClass
- old line
+ new line
*** End Patch

Function形式:

{
  "input": "*** Begin Patch\n*** Update File: ...\n*** End Patch"
}

内部実装:

  • apply_patch Rustバイナリを呼び出し
  • 場所: codex-rs/apply-patch/src/
  • パーサー: parser.rs, seek_sequence.rs

ハンドラー: ApplyPatchHandler


2.2 read_file

説明: ローカルファイルを読み込む(行番号付き)

定義場所: codex-rs/core/src/tools/spec.rs:372

パラメータ:

{
  "file_path": "string",        // ファイルパス(必須)
  "offset": number,             // 開始行番号(1-indexed、オプション)
  "limit": number,              // 最大行数(オプション)
  "mode": "slice|indentation",  // 読み取りモード(オプション)
  "indentation": {              // インデントモード設定(オプション)
    "anchor_line": number,
    "max_levels": number,
    "include_siblings": boolean,
    "include_header": boolean,
    "max_lines": number
  }
}

機能:

  • sliceモード: 単純な行範囲読み取り
  • indentationモード: インデントレベルを考慮したブロック読み取り

ハンドラー: ReadFileHandler (codex-rs/core/src/tools/handlers/read_file.rs)


2.3 list_dir

説明: ディレクトリ内のファイル・フォルダを一覧表示

定義場所: codex-rs/core/src/tools/spec.rs:470

パラメータ:

{
  "dir_path": "string",         // ディレクトリパス(必須)
  "offset": number,             // 開始エントリ番号(1-indexed、オプション)
  "limit": number,              // 最大エントリ数(オプション)
  "depth": number               // 最大ディレクトリ深度(オプション)
}

ハンドラー: ListDirHandler (codex-rs/core/src/tools/handlers/list_dir.rs)


2.4 grep_files

説明: ファイル内容を正規表現で検索

定義場所: codex-rs/core/src/tools/spec.rs:322

パラメータ:

{
  "pattern": "string",          // 正規表現パターン(必須)
  "include": "string",          // ファイルグロブパターン(オプション、例: "*.rs"
  "path": "string",             // 検索パス(オプション)
  "limit": number               // 最大ファイル数(デフォルト: 100
}

内部実装: ripgrep (rg) コマンドを使用

ハンドラー: GrepFilesHandler (codex-rs/core/src/tools/handlers/grep_files.rs)

使用コマンド:

rg <pattern> --files-with-matches --sort modified --max-count 1

2.5 view_image

説明: ローカル画像ファイルを会話コンテキストに添付

定義場所: codex-rs/core/src/tools/spec.rs:236

パラメータ:

{
  "path": "string"              // 画像ファイルパス(必須)
}

サポート形式: JPEG, PNG, GIF, WebP

ハンドラー: ViewImageHandler (codex-rs/core/src/tools/handlers/view_image.rs)


3. プランニングツール

3.1 update_plan

説明: タスクプランを更新・記録する

定義場所: codex-rs/core/src/tools/handlers/plan.rs

パラメータ:

{
  "explanation": "string",      // プランの説明(オプション)
  "plan": [                     // プランアイテム配列(必須)
    {
      "step": "string",         // ステップ名(必須)
      "status": "pending|in_progress|completed"  // ステータス(必須)
    }
  ]
}

特徴:

  • 実際の処理は行わない(記録のみ)
  • クライアントがプランをレンダリングするための情報提供
  • 同時に in_progress にできるステップは1つのみ

ハンドラー: PlanHandler


4. 外部連携ツール

4.1 web_search

説明: Webサーチをリクエスト(OpenAI API経由)

定義場所: codex-rs/core/src/tools/spec.rs:828

特徴:

  • Responses APIの組み込み機能
  • パラメータなし
  • フィーチャーフラグ web_search_request = true で有効化

4.2 MCPツール (外部)

説明: Model Context Protocol サーバー経由のカスタムツール

定義場所: codex-rs/core/src/mcp_connection_manager.rs

設定例:

[mcp_servers.filesystem]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"]

特徴:

  • 外部プロセスとして起動
  • STDIO または Streamable HTTP で通信
  • ツール定義を動的に取得

ハンドラー: McpHandler (codex-rs/core/src/tools/handlers/mcp.rs)


5. テスト用ツール

5.1 test_sync_tool

説明: 並列ツール呼び出しのテスト用

定義場所: codex-rs/core/src/tools/spec.rs:260

パラメータ:

{
  "sleep_before_ms": number,
  "sleep_after_ms": number,
  "barrier": {
    "id": "string",
    "participants": number
  }
}

用途: 内部テストのみ

ハンドラー: TestSyncHandler (codex-rs/core/src/tools/handlers/test_sync.rs)


シェル環境

Codexが使用するシェルとその検出ロジック。

サポートシェル一覧

サポートシェル

1. Bash

定義: codex-rs/core/src/shell.rs:13

pub struct BashShell {
    pub shell_path: String,     // 例: "/bin/bash"
    pub bashrc_path: String,    // 例: "/Users/name/.bashrc"
}

検出ロジック:

  1. $SHELL 環境変数を確認
  2. /bin/bash の存在確認
  3. .bashrc または .bash_profile を探索

呼び出し形式:

/bin/bash -lc "command"

2. Zsh

定義: codex-rs/core/src/shell.rs:7

pub struct ZshShell {
    pub shell_path: String,     // 例: "/bin/zsh"
    pub zshrc_path: String,     // 例: "/Users/name/.zshrc"
}

検出ロジック:

  1. $SHELLzsh を含むか確認
  2. .zshrc の存在確認

呼び出し形式:

/bin/zsh -lc "command"

3. PowerShell (Windows)

定義: codex-rs/core/src/shell.rs:19

pub struct PowerShellConfig {
    pub exe: String,                        // "pwsh" or "powershell.exe"
    pub bash_exe_fallback: Option<PathBuf>, // Bash.exeのパス
}

検出ロジック:

  1. pwsh の存在確認(PowerShell Core)
  2. なければ powershell.exe(Windows PowerShell)
  3. Bash fallback: bash.exe の存在確認

呼び出し形式:

# PowerShellコマンド
pwsh -NoProfile -Command "Get-ChildItem"

# Bashコマンド(fallback)
bash.exe -lc "ls -la"

特殊処理:

  • モデルが bash -lc を生成した場合、自動的にBash fallbackに切り替え
  • Bashが利用不可の場合、PowerShell構文エラーを返してモデルに修正を促す

4. sh (フォールバック)

検出: /bin/sh の存在確認

用途: 他のシェルが見つからない場合の最終フォールバック


シェル環境変数ポリシー

定義場所: codex-rs/core/src/config_types.rs:365

継承ポリシーの比較:

継承ポリシー:

  • all: 親プロセスの全環境変数を継承(デフォルト)
  • core: HOME, PATH, USER, SHELL など最小限のみ
  • none: 環境変数を継承しない

除外パターン:

  • デフォルトで *KEY*, *SECRET*, *TOKEN* を含む変数は除外
  • カスタム除外パターンをサポート

設定例:

[shell_environment_policy]
inherit = "core"
exclude = ["AWS_*", "AZURE_*"]
set = { PATH = "/usr/local/bin:/usr/bin", MY_VAR = "value" }

内部バイナリ

Codexが内部で使用するRustバイナリ。

内部バイナリ一覧

バイナリ名 言語 用途 使用場面
apply_patch Rust ファイルパッチ適用 apply_patch ツール実行時
codex-linux-sandbox Rust Linuxサンドボックス実行 Linux環境でのコマンド実行
codex-responses-api-proxy Rust Responses API プロキシ Responses API使用時

バイナリアーキテクチャ

1. apply_patch

場所: codex-rs/apply-patch/

説明: ファイルパッチ適用専用バイナリ

機能:

  • カスタムパッチフォーマットのパース
  • ファイルの作成・更新・削除・リネーム
  • 行単位の差分適用

パーサー:

  • Lark文法: codex-rs/core/src/tools/handlers/tool_apply_patch.lark
  • パーサー実装: codex-rs/apply-patch/src/parser.rs

呼び出し:

apply_patch "*** Begin Patch\n..."

ソースファイル:

  • main.rs: エントリーポイント
  • lib.rs: コアロジック
  • parser.rs: パッチパーサー
  • seek_sequence.rs: シーケンスマッチング
  • standalone_executable.rs: スタンドアロン実行

2. codex-linux-sandbox

場所: codex-rs/linux-sandbox/

説明: Linux用サンドボックス実行ラッパー

機能:

  • Landlock LSMを使用したファイルシステム制限
  • Seccompフィルターによるシステムコール制限
  • ネットワークアクセス制御

使用技術:

  • Landlock: ファイルアクセス制御
  • Seccomp: システムコール制限

呼び出し:

codex-linux-sandbox <command> <args...>

設定場所: config.codex_linux_sandbox_exe

ソースファイル:

  • main.rs: エントリーポイント
  • lib.rs: サンドボックス設定
  • landlock.rs: Landlock実装
  • linux_run_main.rs: 実行ロジック

3. codex-responses-api-proxy

場所: codex-rs/responses-api-proxy/

説明: OpenAI Responses APIプロキシ

機能:

  • Responses APIとの通信を中継
  • SSEストリームの処理
  • トークンカウント

npmパッケージ: @openai/codex-responses-api-proxy

使用場面: Responses API使用時に自動的に起動


外部コマンド

Codexが使用する外部システムコマンド。

外部コマンド一覧

コマンド 用途 使用頻度 主な使用場所
git リポジトリ情報取得、差分生成 非常に高 git_info.rs
rg (ripgrep) ファイル内容の高速検索 grep_files.rs
/usr/bin/sandbox-exec macOSサンドボックス macOSのみ seatbelt.rs
which 実行ファイルパス解決 shell.rs
pwsh / powershell.exe Windowsシェル Windowsのみ shell.rs
bash / zsh / sh Unix系シェル shell.rs

Git コマンド使用パターン

1. git

使用頻度: 非常に高い

使用場所: codex-rs/core/src/git_info.rs

主な用途:

  • リポジトリ情報の取得
  • 差分の生成
  • トラッキング状態の確認
  • コミット履歴の取得

使用サブコマンド:

git rev-parse --git-common-dir
git rev-parse --show-toplevel
git status --porcelain
git diff --staged
git diff HEAD
git diff --no-index /dev/null <file>  # 新規ファイルの差分
git log --oneline -n 1
git remote get-url origin
git ls-files --others --exclude-standard  # 未追跡ファイル
git show <commit>:<path>
git config --get user.name
git config --get user.email

タイムアウト: 各コマンド2秒

エラーハンドリング: タイムアウトまたはエラー時は無視して続行


2. rg (ripgrep)

使用場所: codex-rs/core/src/tools/handlers/grep_files.rs

用途: ファイル内容の高速検索

使用オプションと安全性:

使用オプション:

rg <pattern> \
  --files-with-matches \    # ファイル名のみ表示
  --sort modified \          # 更新日時でソート
  --max-count 1 \           # ファイルごとに1マッチまで
  --glob '*.rs' \           # グロブパターン
  --hidden \                # 隠しファイルも検索
  --no-ignore               # .gitignore無視

安全性チェック:

  • --pre: 禁止(任意のコマンド実行可能)
  • --search-zip: 禁止(zipファイル解凍)
  • --hostname-bin: 禁止

3. /usr/bin/sandbox-exec (macOS)

使用場所: codex-rs/core/src/seatbelt.rs

用途: macOS Seatbeltサンドボックス

定義: MACOS_PATH_TO_SEATBELT_EXECUTABLE

呼び出し:

/usr/bin/sandbox-exec -p '(version 1) ...' <command>

ポリシーファイル: codex-rs/core/src/seatbelt_base_policy.sbpl


4. シェル検出コマンド

使用場所: codex-rs/core/src/shell.rs

# PowerShell検出
pwsh --version

# Bash検出(Windows)
bash.exe --version

# シェル特定
sh -c "echo shell check"

5. which (ユーティリティ)

使用場所: codex-rs/core/src/shell.rs

用途: 実行ファイルのパス解決

使用例:

which::which("bash.exe")

サンドボックス機構

Codexの多層サンドボックスアーキテクチャ。

アーキテクチャ概要

3層防御アーキテクチャ:

  1. Safety Check Layer: コマンドの静的解析
  2. Approval Policy Layer: 危険操作の承認制御
  3. Sandbox Execution Layer: OS別の実行時制限

1. Safety Check Layer

場所: codex-rs/core/src/command_safety/

機能: コマンド実行前の安全性検証

Unix系セーフコマンドリスト

定義: codex-rs/core/src/command_safety/is_safe_command.rs:33

// 読み取り専用コマンド
"ls", "cat", "head", "tail", "wc", "grep", "find", "file",
"pwd", "echo", "printf", "which", "whoami", "hostname",
"date", "uname", "df", "du"

// Git読み取り専用
"git" (status, log, show, diff, blame, ls-files など)

// ripgrep
"rg" (安全なオプションのみ)

Windowsセーフコマンドリスト

定義: codex-rs/core/src/command_safety/windows_safe_commands.rs

# PowerShellコマンドレット
Get-ChildItem, Get-Content, Select-String, Measure-Object,
Get-Location, Test-Path, Get-Item, Select-Object

# エイリアス
ls, dir, cat, type, pwd, echo

# 外部コマンド
git (読み取り専用), rg (安全なオプション)

危険なコマンド検出

定義: codex-rs/core/src/command_safety/is_dangerous_command.rs

// 即座に拒否されるコマンド
"rm", "rmdir", "del", "rd",           // 削除
"format", "mkfs",                      // フォーマット
"shutdown", "reboot", "init",          // システム制御
"curl", "wget", "nc", "telnet",        // ネットワーク
"sudo", "su", "doas",                  // 権限昇格
"eval", "exec",                        // コード実行
"dd",                                  // 低レベルI/O

2. Approval Policy Layer

定義: codex-rs/protocol/src/protocol.rs

ポリシータイプ:

ポリシー 説明 ユースケース
untrusted すべてのコマンドで承認要求 最も安全
on-failure 失敗時のみ承認要求 バランス型
on-request モデルが明示的に要求した場合のみ 信頼環境
never 承認要求なし 完全自動化

設定:

approval_policy = "on-failure"

3. Sandbox Execution Layer

macOS: Seatbelt

定義: codex-rs/core/src/seatbelt.rs

ポリシーファイル: seatbelt_base_policy.sbpl

機能:

  • ファイルシステムアクセス制限
  • ネットワークアクセス制御
  • プロセス生成制限

ポリシー例:

(version 1)
(deny default)

; 読み取り許可
(allow file-read* (subpath "/usr"))
(allow file-read* (subpath "/System"))

; 書き込み許可(ワークスペースのみ)
(allow file-write* (subpath "/Users/name/project"))

; ネットワーク拒否
(deny network*)

呼び出し:

spawn_command_under_seatbelt(
    command,
    args,
    cwd,
    sandbox_policy,
    stdio_policy,
    env
)

Linux: Landlock + Seccomp

定義: codex-rs/core/src/landlock.rs

機能:

  • Landlock: ファイルシステムアクセス制御(Linux 5.13+)
  • Seccomp: システムコール制限

Lanlock設定:

// 読み取り許可パス
allowed_read_paths = [
    "/usr", "/lib", "/etc", "/bin", "/sbin"
]

// 書き込み許可パス
allowed_write_paths = [
    workspace_path
]

Seccompフィルター:

  • 許可: read, write, open, close, mmap, exit, etc.
  • 拒否: ptrace, setuid, mount, reboot, etc.

実装: codex-rs/linux-sandbox/

呼び出し:

spawn_command_under_linux_sandbox(
    command,
    args,
    cwd,
    sandbox_policy,
    stdio_policy,
    env
)

Windows: サンドボックスなし

理由: Windowsに相当するサンドボックス機構がない

代替策:

  • Safety Check Layerでの厳格な検証
  • Approval Policyによるユーザー確認

4. サンドボックスモード

定義: codex-rs/protocol/src/config_types.rs

pub enum SandboxMode {
    ReadOnly,              // 読み取り専用
    WorkspaceWrite,        // ワークスペース内書き込み可
    DangerFullAccess,      // 制限なし(危険)
}

設定:

sandbox_mode = "workspace-write"

[sandbox_workspace_write]
writable_roots = ["/tmp"]       # 追加の書き込み可能パス
network_access = false          # ネットワークアクセス
exclude_tmpdir_env_var = false  # $TMPDIRを除外
exclude_slash_tmp = false       # /tmpを除外

実行フロー

1. ツール呼び出しフロー


2. シェルコマンド実行フロー


3. apply_patch実行フロー


4. MCP Tool実行フロー


セーフティチェック

1. コマンド分類

セーフコマンド(自動承認)

Unix系:

# ファイル閲覧
ls, cat, head, tail, less, more, wc, file

# テキスト処理
grep, sed, awk, cut, sort, uniq, tr

# システム情報
pwd, whoami, hostname, uname, date, df, du

# Git(読み取り専用)
git status, git log, git diff, git show, git blame

# Ripgrep(安全なオプション)
rg <pattern> --files-with-matches

Windows:

# PowerShellコマンドレット
Get-ChildItem, Get-Content, Select-String, Get-Location,
Test-Path, Measure-Object, Select-Object

# 従来のコマンド
dir, type, echo, findstr

危険なコマンド(承認必須)

# 削除・変更
rm, rmdir, mv, cp, dd, shred

# システム操作
shutdown, reboot, systemctl, service

# ネットワーク
curl, wget, nc, telnet, ssh

# 権限昇格
sudo, su, doas

# パッケージ管理
apt, yum, brew, npm install, pip install

# コンパイル・実行
gcc, make, ./script

# 圧縮・解凍(潜在的危険)
tar, unzip, gunzip

2. 検出アルゴリズム

パイプライン解析

サポート:

# 安全な組み合わせ
ls | grep pattern
cat file | wc -l
git log | head -n 10

実装: codex-rs/core/src/bash.rs

パース対象:

  • && (AND)
  • || (OR)
  • ; (セミコロン)
  • | (パイプ)

ロジック:

// すべてのコマンドが安全な場合のみ、全体を安全とみなす
if all_commands.iter().all(|cmd| is_safe_to_call_with_exec(cmd)) {
    return true;
}

リダイレクト検出

危険なパターン:

echo "data" > file.txt        # 書き込み
cat input >> log.txt          # 追記
rm -rf / 2>/dev/null          # エラー隠蔽

検出: >, >>, < の存在をチェック


シェルエスケープ検出

危険なパターン:

; rm -rf /                    # コマンド連鎖
$(malicious command)          # コマンド置換
`malicious command`           # バッククォート置換

検出: 特殊文字と構文解析


3. Gitコマンド特別ルール

許可されるサブコマンド:

git status
git log
git show
git diff
git blame
git ls-files
git rev-parse
git remote get-url

拒否されるサブコマンド:

git push           # リモート変更
git pull           # リモート取得
git commit         # 変更コミット
git rm             # ファイル削除
git reset --hard   # 履歴破壊
git clean -fd      # 未追跡削除

実装: codex-rs/core/src/command_safety/windows_safe_commands.rs:232


4. Ripgrep特別ルール

許可されるオプション:

rg pattern
rg pattern --files-with-matches
rg pattern --glob '*.rs'
rg pattern --max-count 10

拒否されるオプション:

rg --pre cat pattern           # 任意コマンド実行
rg --search-zip pattern        # zipファイル解凍
rg --hostname-bin /bin/sh      # カスタムバイナリ

実装: codex-rs/core/src/command_safety/windows_safe_commands.rs:218


ツール設定マトリクス

ツール デフォルト有効 フィーチャーフラグ モデル依存 並列実行
shell -
local_shell - ✅ (GPT-5系)
exec_command + write_stdin streamable_shell
unified_exec unified_exec
apply_patch apply_patch_freeform ✅ (GPT-5: freeform)
update_plan plan_tool
read_file experimental
list_dir experimental
grep_files experimental
view_image view_image_tool
web_search web_search_request ✅ (Responses API)
MCP Tools - rmcp_client モデル依存

設定例

最小構成(デフォルト)

# ~/.codex/config.toml

# shellツールのみ有効
model = "gpt-5-codex"
sandbox_mode = "read-only"
approval_policy = "untrusted"

バランス型構成

model = "gpt-5"
sandbox_mode = "workspace-write"
approval_policy = "on-failure"

[sandbox_workspace_write]
writable_roots = []
network_access = false

[features]
plan_tool = true
apply_patch_freeform = true
view_image_tool = true

フル機能構成

model = "gpt-5"
sandbox_mode = "workspace-write"
approval_policy = "on-failure"

[sandbox_workspace_write]
writable_roots = ["/tmp"]
network_access = false

[features]
streamable_shell = true
plan_tool = true
apply_patch_freeform = true
view_image_tool = true
web_search_request = true

# 実験的ツール
experimental_supported_tools = ["read_file", "list_dir", "grep_files"]

# MCPサーバー
[mcp_servers.filesystem]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"]

開発者用構成(危険)

model = "gpt-5"
sandbox_mode = "danger-full-access"  # ⚠️ 危険
approval_policy = "never"            # ⚠️ 危険

[features]
unified_exec = true
streamable_shell = true
plan_tool = true
apply_patch_freeform = true
view_image_tool = true
web_search_request = true

experimental_supported_tools = ["read_file", "list_dir", "grep_files", "test_sync_tool"]

⚠️ 警告: この構成はセキュリティ制限を無効化します。開発環境でのみ使用してください。


デバッグコマンド

ツール一覧の確認

# Codexが認識しているツールを確認
codex --help

# ログレベルを上げて実行
RUST_LOG=debug codex

サンドボックステスト

# macOS Seatbeltテスト
/usr/bin/sandbox-exec -p '(version 1) (deny default)' ls /

# Linux Landlockテスト
codex-linux-sandbox ls /

MCPサーバー確認

# MCPサーバー一覧
codex mcp list

# 特定サーバーの詳細
codex mcp get server_name

トラブルシューティング

問題: ツールが使えない

症状: unsupported call: tool_name

原因:

  1. フィーチャーフラグが無効
  2. モデルがツールをサポートしていない

解決策:

[features]
<tool_name> = true

問題: サンドボックスエラー

症状: Operation not permitted

原因:

  • Seatbelt/Landlockによるアクセス制限

解決策:

sandbox_mode = "workspace-write"

[sandbox_workspace_write]
writable_roots = ["/path/to/allowed"]
network_access = true

または

sandbox_mode = "danger-full-access"  # ⚠️ 開発用のみ

問題: コマンドが承認待ちになる

症状: コマンドのたびに承認を求められる

原因: approval_policy = "untrusted"

解決策:

approval_policy = "on-failure"  # または "never"

問題: MCPサーバーが起動しない

症状: MCP tools not available

原因:

  1. コマンドパスが間違っている
  2. 環境変数が設定されていない
  3. タイムアウト

解決策:

[mcp_servers.my_server]
command = "npx"
args = ["-y", "mcp-server"]
startup_timeout_sec = 20  # デフォルト10秒
env = { "PATH" = "/usr/local/bin:/usr/bin" }

参考資料

コードベース

  • ツール定義: codex-rs/core/src/tools/spec.rs
  • ハンドラー: codex-rs/core/src/tools/handlers/
  • シェル: codex-rs/core/src/shell.rs
  • 実行: codex-rs/core/src/exec.rs
  • 安全性: codex-rs/core/src/command_safety/
  • サンドボックス:
    • macOS: codex-rs/core/src/seatbelt.rs
    • Linux: codex-rs/core/src/landlock.rs, codex-rs/linux-sandbox/

ドキュメント

@yaseinod
コメントありがとうございます。こちら修正しました!


まとめ

全体アーキテクチャ

統計サマリー

項目 数量 詳細
ツール総数 13個 シェル実行5 + ファイル操作5 + その他3
サポートシェル 4種類 Bash, Zsh, PowerShell, sh
内部バイナリ 3個 apply_patch, linux-sandbox, responses-api-proxy
外部コマンド 4個 git, rg, sandbox-exec, which
サンドボックス 3種類 macOS: Seatbelt, Linux: Landlock+Seccomp, Windows: なし
セキュリティ層 3層 Safety Check → Approval Policy → Sandbox

ツール総数: 13個

  1. shell (基本)
  2. local_shell (Responses API専用)
  3. exec_command + write_stdin (ストリーミング)
  4. unified_exec (実験的)
  5. apply_patch (ファイル編集)
  6. read_file (ファイル読み取り)
  7. list_dir (ディレクトリ一覧)
  8. grep_files (ファイル検索)
  9. update_plan (プランニング)
  10. view_image (画像添付)
  11. web_search (Web検索)
  12. test_sync_tool (テスト用)
  13. MCP Tools (外部、数は可変)

ツール実装マトリクス

サポートシェル: 4種類

  1. Bash
  2. Zsh
  3. PowerShell (pwsh / powershell.exe)
  4. sh (フォールバック)

内部バイナリ: 3個

  1. apply_patch
  2. codex-linux-sandbox
  3. codex-responses-api-proxy

主要外部コマンド: 4個

  1. git (35+サブコマンド)
  2. rg (ripgrep)
  3. /usr/bin/sandbox-exec (macOS)
  4. which (ユーティリティ)

サンドボックス: 3種類

  1. macOS: Seatbelt
  2. Linux: Landlock + Seccomp
  3. Windows: なし(Safety Checkのみ)

** Codexの内部動作を理解するための包括的なリファレンスとしてご利用ください。**
対象バージョン: Codex CLI v0.46.0

10
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?