From 8ef807dbf77200118b59875a41e4fef68755a286 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AI=E4=B8=8D=E6=AD=A2=E8=AF=AD?= <12096460+jnMetaCode@users.noreply.github.com> Date: Tue, 29 Sep 2026 07:25:19 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0=20Claude=20Code=20/?= =?UTF-8?q?=20Codex=20CLI=20/=20Gemini=20CLI=20=E6=8C=87=E5=8D=97=E8=87=B3?= =?UTF-8?q?=202026-09?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Claude Code:Skill 改为文件夹结构、角色文件归入 .claude/agents/;Hook 仅 exit 2 阻断、stdout 可见范围修正;.claude/rules 用 paths;原生安装器;模型定价与上下文;ultrathink 与 /effort;自动记忆;文档链接迁移到 code.claude.com;新增 2026 下半年功能速览 - Codex CLI:exec 去掉 --ask-for-approval;untrusted 退役;profile 改为独立文件;web_search 顶层配置;mcp add 语法;mcp-server 改 app-server;模型更新为 gpt-6 系列;slash 命令、沙箱、hooks、memories 状态更新;文档链接迁移到 learn.chatgpt.com;新增 2026 下半年功能速览 - Gemini CLI:新增停止服务个人用户的说明(转向 Antigravity CLI);上下文修正为 1M;移除免费额度说法;补充 skills/MCP/hooks 等内置能力 - 陷阱合集:自动压缩为摘要而非截断;rules 用 paths --- claude-code/README.en.md | 60 +++++++---- claude-code/README.md | 60 +++++++---- codex/README.en.md | 160 ++++++++++++++++------------ codex/README.md | 160 ++++++++++++++++------------ codex/templates/AGENTS.md | 2 +- codex/templates/agent-explorer.toml | 10 +- codex/templates/config.toml | 57 +++++----- gemini-cli/README.en.md | 29 +++-- gemini-cli/README.md | 29 +++-- pitfalls/claude-code.en.md | 5 +- pitfalls/claude-code.md | 5 +- 11 files changed, 342 insertions(+), 235 deletions(-) diff --git a/claude-code/README.en.md b/claude-code/README.en.md index 79931b9..5ac8a13 100644 --- a/claude-code/README.en.md +++ b/claude-code/README.en.md @@ -14,7 +14,7 @@ Before diving into tips, get familiar with these core concepts: |---------|-------------|----------| | **Subagent** | Child process Agent, executes tasks independently | Parallel processing, context isolation | | **Command** | Shortcuts starting with `/` | Quick access to common operations | -| **Skill** | Methodology files under `.claude/skills/` | Teach the AI how to do things | +| **Skill** | Methodology folders at `.claude/skills//SKILL.md` | Teach the AI how to do things | | **Hook** | Scripts that run before/after tool calls | Automated validation, notifications | | **MCP Server** | Model Context Protocol service | Extend AI capabilities (databases, APIs, etc.) | | **Memory** | Persistent memory | Retain context across conversations | @@ -27,13 +27,19 @@ Before diving into tips, get familiar with these core concepts: ### Installation ```bash -# Install globally via npm -npm install -g @anthropic-ai/claude-code +# Recommended: official native installer (macOS / Linux / WSL, auto-updates) +curl -fsSL https://claude.ai/install.sh | bash + +# Or use a package manager +brew install --cask claude-code # macOS +winget install Anthropic.ClaudeCode # Windows -# Or run directly with npx -npx @anthropic-ai/claude-code +# npm still works (requires Node.js 22+) +npm install -g @anthropic-ai/claude-code ``` +> Requires a Claude Pro / Max / Team / Enterprise subscription or a Console API account (the Free plan doesn't include Claude Code). Amazon Bedrock, Google Vertex AI, and Microsoft Foundry are also supported. + ### First Run ```bash @@ -154,14 +160,14 @@ Use subagents to execute each one independently. ### Skill Files -Skills are one of the most powerful features. Place methodology files under `.claude/skills/` and the AI loads them automatically: +Skills are one of the most powerful features. Each skill is a **folder** under `.claude/skills/` whose entry file must be named `SKILL.md` (a lone `.md` file dropped directly into `.claude/skills/` is ignored). The AI loads them automatically based on their descriptions: ``` .claude/skills/ -├── brainstorming.md # Requirements analysis workflow -├── debugging.md # Debugging methodology -├── code-review.md # Code review standards -└── verification.md # Pre-completion verification +├── brainstorming/SKILL.md # Requirements analysis workflow +├── debugging/SKILL.md # Debugging methodology +├── code-review/SKILL.md # Code review standards +└── verification/SKILL.md # Pre-completion verification ``` **Quick-install superpowers-zh** (20 battle-tested skills): @@ -178,7 +184,7 @@ After installation, Claude Code loads these skills automatically. Invoke them wi **Need specialized roles?** Use the 277 AI expert personas from [agency-agents-zh](https://github.com/jnMetaCode/agency-agents-zh): ```bash -# Copy role files to .claude/skills/ to use them +# Role files are subagents — copy them to .claude/agents/ to use them # Examples: database optimizer, security engineer, code reviewer, etc. ``` @@ -186,7 +192,7 @@ Reference roles in CLAUDE.md: ```markdown # Roles -When I say "review as a security expert", act according to .claude/skills/security-engineer.md. +When I say "review as a security expert", use the security-engineer subagent (.claude/agents/security-engineer.md). ``` ### Hook Automation @@ -217,7 +223,7 @@ Hooks run scripts automatically before or after tool calls: } ``` -> Hook trigger points include `PreToolUse`, `PostToolUse`, `Notification`, etc. Each trigger uses `matcher` to match tool names. See the [official docs](https://docs.anthropic.com/en/docs/claude-code/hooks). +> Hook trigger points include `PreToolUse`, `PostToolUse`, `Notification`, `Stop`, `SessionStart`, `UserPromptSubmit`, and 30+ events in total. Each trigger uses `matcher` to match tool names. Besides `command`, hook types include `http`, `mcp_tool`, `prompt`, and `agent`. See the [official docs](https://code.claude.com/docs/en/hooks). Use cases: - Auto-run related tests after every file edit @@ -235,7 +241,7 @@ If the result is good, merge it. If not, discard it. ### Memory Across Conversations -Claude Code stores memory under `~/.claude/` for cross-conversation use: +Auto memory is on by default, stored per project at `~/.claude/projects//memory/MEMORY.md`; view, edit, or toggle it with `/memory`. You can also ask it to remember things directly: ``` Remember: this project deploys on Vercel, @@ -265,6 +271,20 @@ steps: Best for: team-scale complex tasks, deliverables requiring multiple review rounds, standardized development workflows. +### New in H2 2026 + +- **Models**: Opus 5.5 is the default on all plans; aliases `default` / `best` / `fable` / `opus` / `sonnet` / `haiku` / `opusplan`. Price per million input/output tokens: Haiku 4.5 $1/$5, Sonnet 5.5 $2/$10, Opus 5.5 $4/$20, Fable 5.1 $10/$50. Opus 5.5, Sonnet 5.5, and Fable 5.1 have 1M context; Haiku 4.5 has 200K +- **Permission modes**: `default` / `acceptEdits` / `plan` / `auto` / `dontAsk` / `bypassPermissions`; interactive sessions start in **auto mode** (a classifier decides what needs confirmation) by default +- **`/effort`**: set thinking depth (low / medium / high / xhigh / max), or press Option/Alt+T +- **Background agents**: `claude agents`, `claude --bg`, `/background` keep tasks running in the background +- **`/fork`**, **`/btw`** (side question without derailing the main thread), **`/rewind`** (roll back code and conversation) +- **`/loop`**, **`/schedule`**: recurring runs and scheduled cloud tasks +- **`/code-review`**, **`/ultrareview`**, **`/security-review`**: built-in code / security review +- **`/plugin`**: install plugins (bundles of skills, agents, hooks, MCP); **`/context`**: inspect context usage +- **Bash sandbox**: `/sandbox` enables OS-level isolation (Seatbelt on macOS, bubblewrap on Linux/WSL2) +- **AGENTS.md**: read automatically when the project has no CLAUDE.md +- **Subagents**: the `/agents` wizard is gone — edit Markdown files under `.claude/agents/` directly + --- ## Debugging Tips @@ -311,7 +331,7 @@ Organized by category, one tip per row. Bookmark this section — it's all you n | 7 | Ask for 2-3 options | "Give me 2 options with pros and cons. I'll pick one, then you implement it" | | 8 | Confirm step by step | "Pause after each step and wait for my confirmation. Don't do everything at once" | | 9 | Define done criteria | "Definition of done: all tests pass + zero TypeScript errors + lint passes" | -| 10 | Use ultrathink for deep reasoning | Start your prompt with "ultrathink" or "think really hard" to trigger extended thinking | +| 10 | Use ultrathink for deep reasoning | Include "ultrathink" in your prompt for deeper reasoning ("think hard" etc. are just plain text). Set overall thinking depth with `/effort` or Option/Alt+T | | 11 | Let it write commit messages | "Write a commit message that explains *why* this change was made, not *what* changed" | | 12 | English prompts are more precise | For complex technical tasks, English prompts yield more precise results. Use your native language for simple tasks | @@ -328,7 +348,7 @@ Organized by category, one tip per row. Bookmark this section — it's all you n | 7 | Document directory structure | Describe key directories so the AI knows where things live | | 8 | Layer your CLAUDE.md files | Global rules in the root, module-specific rules in subdirectories (e.g., `src/api/CLAUDE.md`) | | 9 | Update regularly | As the project evolves, keep CLAUDE.md current. Stale rules are worse than no rules | -| 10 | Use `.claude/rules/` for conditional loading | In large projects, use globs to load rules by file type instead of cramming everything in one file | +| 10 | Use `.claude/rules/` for conditional loading | In large projects, use `paths:` in rule frontmatter to load rules by file path instead of cramming everything in one file | ### Agent & Subagent (10) @@ -354,8 +374,8 @@ Organized by category, one tip per row. Bookmark this section — it's all you n | 3 | PreToolUse block dangerous ops | Check commands before `Bash` tool execution; block `rm -rf` and similar | | 4 | Notification hook for alerts | Auto-send Slack/webhook notifications when long tasks complete | | 5 | Stop hook for forced verification | Remind Claude to verify its own output at the end of each turn | -| 6 | Exit 1 in hooks to block execution | A non-zero exit from a hook script blocks the tool call — use this to enforce rules | -| 7 | Hook stdout as context | Claude sees the hook's stdout, so you can pass extra information through it | +| 6 | Exit 2 in hooks to block execution | Only exit code 2 blocks the tool call (stderr is fed back to Claude). Exit 1 is a non-blocking error and the call proceeds | +| 7 | Hook output as context | stdout from events like `UserPromptSubmit` and `SessionStart` is added to context; `PreToolUse`/`PostToolUse` stdout only goes to the debug log — use JSON `hookSpecificOutput.additionalContext` to pass info | | 8 | Match tool names precisely | Matcher supports `Write\|Edit`, `Bash`, etc. Don't use `*` to match everything | ### Workflow (12) @@ -407,7 +427,7 @@ Organized by category, one tip per row. Bookmark this section — it's all you n | # | Tip | Details | |---|-----|---------| -| 1 | Use Haiku for simple tasks | `claude --model haiku` for straightforward work — 10x cheaper | +| 1 | Use Haiku for simple tasks | `claude --model haiku` for straightforward work — about 1/4 the price of the default Opus, 1/2 of Sonnet | | 2 | Use headless mode for batch jobs | Scripted batch calls consume fewer tokens than interactive mode | | 3 | A precise CLAUDE.md saves tokens | The more precise your context, the fewer files the AI needs to read, and the lower the cost | | 4 | Avoid repeatedly reading large files | Tell Claude the exact line range instead of having it read the entire file every time | @@ -445,6 +465,6 @@ Copy these directly into your project: ## Further Reading -- [Claude Code Official Docs](https://docs.anthropic.com/en/docs/claude-code) +- [Claude Code Official Docs](https://code.claude.com/docs/en/overview) - [superpowers-zh](https://github.com/jnMetaCode/superpowers-zh) — 20 AI coding skills - [agency-agents-zh](https://github.com/jnMetaCode/agency-agents-zh) — 277 AI expert personas diff --git a/claude-code/README.md b/claude-code/README.md index 9f94665..aedcc6b 100644 --- a/claude-code/README.md +++ b/claude-code/README.md @@ -12,7 +12,7 @@ |------|------|------| | **Subagent** | 子进程 Agent,独立执行任务 | 并行处理、隔离上下文 | | **Command** | `/` 开头的快捷命令 | 快速执行常用操作 | -| **Skill** | `.claude/skills/` 下的方法论文件 | 教 AI 怎么做事 | +| **Skill** | `.claude/skills//SKILL.md` 方法论文件夹 | 教 AI 怎么做事 | | **Hook** | 工具调用前后的钩子脚本 | 自动化校验、通知 | | **MCP Server** | Model Context Protocol 服务 | 扩展 AI 能力(数据库、API 等) | | **Memory** | 持久化记忆 | 跨对话保留上下文 | @@ -25,13 +25,19 @@ ### 安装 ```bash -# npm 全局安装 -npm install -g @anthropic-ai/claude-code +# 推荐:官方原生安装器(macOS / Linux / WSL,自动更新) +curl -fsSL https://claude.ai/install.sh | bash + +# 或者用包管理器 +brew install --cask claude-code # macOS +winget install Anthropic.ClaudeCode # Windows -# 或者直接用 npx -npx @anthropic-ai/claude-code +# npm 仍可用(需要 Node.js 22+) +npm install -g @anthropic-ai/claude-code ``` +> 需要 Claude Pro / Max / Team / Enterprise 订阅或 Console API 账号(免费版不含 Claude Code),也支持 Amazon Bedrock、Google Vertex AI、Microsoft Foundry。 + ### 第一次使用 ```bash @@ -152,14 +158,14 @@ Claude Code 会自己:读代码 → 制定计划 → 写测试 → 跑测试 ### Skill 文件 -Skill 是最强大的功能之一。在 `.claude/skills/` 下放方法论文件,AI 会自动加载: +Skill 是最强大的功能之一。每个 skill 是 `.claude/skills/` 下的一个**文件夹**,入口文件固定叫 `SKILL.md`(直接丢一个单独的 `.md` 进 `.claude/skills/` 不会被识别),AI 会按描述自动加载: ``` .claude/skills/ -├── brainstorming.md # 需求分析流程 -├── debugging.md # 调试方法论 -├── code-review.md # 代码审查规范 -└── verification.md # 完成前验证 +├── brainstorming/SKILL.md # 需求分析流程 +├── debugging/SKILL.md # 调试方法论 +├── code-review/SKILL.md # 代码审查规范 +└── verification/SKILL.md # 完成前验证 ``` **快速安装 superpowers-zh**(20 个经过实战验证的 skill): @@ -176,7 +182,7 @@ npx superpowers-zh **需要专业角色?** 用 [agency-agents-zh](https://github.com/jnMetaCode/agency-agents-zh) 的 277 个 AI 专家角色: ```bash -# 把角色文件复制到 .claude/skills/ 即可使用 +# 角色文件属于 subagent,复制到 .claude/agents/ 即可使用 # 比如数据库优化师、安全工程师、代码审查员等 ``` @@ -184,7 +190,7 @@ npx superpowers-zh ```markdown # 角色 -当我说"用安全专家审查"时,按 .claude/skills/security-engineer.md 的角色行事。 +当我说"用安全专家审查"时,调用 security-engineer subagent(.claude/agents/security-engineer.md)。 ``` ### Hook 自动化 @@ -215,7 +221,7 @@ Hook 在工具调用前后自动执行脚本: } ``` -> Hook 的触发点有 `PreToolUse`、`PostToolUse`、`Notification` 等,每个触发点下用 `matcher` 匹配工具名。详见 [官方文档](https://docs.anthropic.com/en/docs/claude-code/hooks)。 +> Hook 的触发点有 `PreToolUse`、`PostToolUse`、`Notification`、`Stop`、`SessionStart`、`UserPromptSubmit` 等 30 多个事件,每个触发点下用 `matcher` 匹配工具名;hook 类型除了 `command`,还有 `http`、`mcp_tool`、`prompt`、`agent`。详见 [官方文档](https://code.claude.com/docs/en/hooks)。 用途: - 每次修改文件后自动跑相关测试 @@ -233,7 +239,7 @@ Hook 在工具调用前后自动执行脚本: ### Memory 跨对话记忆 -Claude Code 可以在 `~/.claude/` 下存储记忆,跨对话使用: +Claude Code 默认开启自动记忆(auto memory),按项目存在 `~/.claude/projects//memory/MEMORY.md`,用 `/memory` 查看、编辑或开关。你也可以直接让它记住: ``` 记住:这个项目的部署用的是 Vercel, @@ -263,6 +269,20 @@ steps: 适合场景:团队级复杂任务、需要多轮审查的交付、标准化开发流程。 +### 2026 下半年新增 + +- **模型**:所有套餐默认 Opus 5.5;别名 `default` / `best` / `fable` / `opus` / `sonnet` / `haiku` / `opusplan`。每百万 token 输入/输出价:Haiku 4.5 $1/$5、Sonnet 5.5 $2/$10、Opus 5.5 $4/$20、Fable 5.1 $10/$50;Opus 5.5、Sonnet 5.5、Fable 5.1 为 1M 上下文,Haiku 4.5 为 200K +- **权限模式**:`default` / `acceptEdits` / `plan` / `auto` / `dontAsk` / `bypassPermissions`;交互会话默认以 **auto 模式**(分类器判断是否需要确认)启动 +- **`/effort`**:调思考深度(low / medium / high / xhigh / max),也可 Option/Alt+T +- **后台 agent**:`claude agents`、`claude --bg`、`/background`,任务丢后台继续跑 +- **`/fork`**、**`/btw`**(不打断主线的旁支提问)、**`/rewind`**(回退代码和对话) +- **`/loop`**、**`/schedule`**:循环执行、定时云端任务 +- **`/code-review`**、**`/ultrareview`**、**`/security-review`**:内置代码审查 / 安全审查 +- **`/plugin`**:安装插件(打包 skills、agents、hooks、MCP);**`/context`**:查看上下文占用 +- **Bash 沙箱**:`/sandbox` 开启系统级隔离(macOS Seatbelt,Linux/WSL2 bubblewrap) +- **AGENTS.md**:项目没有 CLAUDE.md 时自动读取 AGENTS.md +- **Subagent**:`/agents` 向导已移除,直接在 `.claude/agents/` 下编辑 Markdown 文件 + --- ## 调试技巧 @@ -309,7 +329,7 @@ git log 看看 src/api/payment.ts 最近的改动, | 7 | 给出 2-3 个方案让我选 | "给出 2 个方案,分析优缺点,我选了再做" | | 8 | 分步确认 | "每步做完暂停等我确认,不要一口气做完" | | 9 | 明确完成标准 | "完成标准:所有测试通过 + TypeScript 无报错 + lint 通过" | -| 10 | 用 ultrathink 深度思考 | 在提示词开头加"ultrathink"或"think really hard"触发扩展思考 | +| 10 | 用 ultrathink 深度思考 | 提示词里加 "ultrathink" 触发更深思考("think hard" 等只是普通文字);整体思考深度用 `/effort` 或 Option/Alt+T 调 | | 11 | 让它写 commit message | "帮我写 commit message,描述这次改动的 why 而不是 what" | | 12 | 英文提示词更精确 | 复杂技术任务用英文描述更精确,简单任务中文即可 | @@ -326,7 +346,7 @@ git log 看看 src/api/payment.ts 最近的改动, | 7 | 写目录结构 | 关键目录说明,让 AI 知道代码在哪里 | | 8 | 分层 CLAUDE.md | 根目录放全局规则,子目录放模块规则(如 `src/api/CLAUDE.md`) | | 9 | 定期更新 | 项目演进了 CLAUDE.md 也要跟着更新,过时的规则比没有规则更糟 | -| 10 | 用 `.claude/rules/` 按条件加载 | 大项目用 globs 按文件类型加载规则,避免一次全塞进去 | +| 10 | 用 `.claude/rules/` 按条件加载 | 大项目在规则 frontmatter 里用 `paths:` 按文件路径加载,避免一次全塞进去 | ### Agent 与 Subagent(10) @@ -352,8 +372,8 @@ git log 看看 src/api/payment.ts 最近的改动, | 3 | PreToolUse 拦截危险操作 | 在 `Bash` 工具执行前检查命令,拦截 `rm -rf` 等危险操作 | | 4 | Notification hook 发通知 | 长任务完成后自动发 Slack/钉钉通知 | | 5 | Stop hook 强制验证 | 在每轮结束时提醒 Claude 检查自己的输出 | -| 6 | hook 里用 exit 1 阻止执行 | hook 脚本返回非 0 就会阻止工具调用,用于强制规则 | -| 7 | hook 输出作为上下文 | hook 的 stdout 会被 Claude 看到,可以传递额外信息 | +| 6 | hook 里用 exit 2 阻止执行 | 只有 exit 2 会阻止工具调用(stderr 反馈给 Claude);exit 1 只是非阻塞错误,照样执行 | +| 7 | hook 输出作为上下文 | `UserPromptSubmit`、`SessionStart` 等事件的 stdout 会进上下文;`PreToolUse`/`PostToolUse` 的 stdout 只进 debug 日志,要传信息用 JSON `hookSpecificOutput.additionalContext` | | 8 | 按工具名精确匹配 | matcher 支持 `Write\|Edit`、`Bash` 等,不要用 `*` 匹配所有 | ### 工作流(12) @@ -405,7 +425,7 @@ git log 看看 src/api/payment.ts 最近的改动, | # | 技巧 | 说明 | |---|------|------| -| 1 | 简单任务用 haiku | `claude --model haiku` 做简单任务,便宜 10 倍 | +| 1 | 简单任务用 haiku | `claude --model haiku` 做简单任务,单价约为默认 Opus 的 1/4、Sonnet 的 1/2 | | 2 | 批量任务用 headless | 脚本批量调用比交互模式省 token | | 3 | 精准的 CLAUDE.md 省 token | 上下文越精准,AI 需要读的文件越少,成本越低 | | 4 | 避免反复读大文件 | 告诉 Claude 具体行号范围,不要每次都读整个文件 | @@ -443,6 +463,6 @@ git log 看看 src/api/payment.ts 最近的改动, ## 延伸阅读 -- [Claude Code 官方文档](https://docs.anthropic.com/en/docs/claude-code) +- [Claude Code 官方文档](https://code.claude.com/docs/en/overview) - [superpowers-zh](https://github.com/jnMetaCode/superpowers-zh) — 20 个 AI 编程 skills - [agency-agents-zh](https://github.com/jnMetaCode/agency-agents-zh) — 277 个 AI 专家角色 diff --git a/codex/README.en.md b/codex/README.en.md index a1be135..248a66f 100644 --- a/codex/README.en.md +++ b/codex/README.en.md @@ -2,7 +2,7 @@ # OpenAI Codex CLI Best Practices -> Codex CLI is OpenAI's open-source terminal coding agent, written in Rust — sitting alongside Claude Code and Gemini CLI as the "big three" terminal agents. This guide is verified against the official docs (developers.openai.com/codex) and the [openai/codex](https://github.com/openai/codex) repo at v0.125.0 (April 2026). +> Codex CLI is OpenAI's open-source terminal coding agent, written in Rust — sitting alongside Claude Code and Gemini CLI as the "big three" terminal agents. This guide is verified against the official docs (learn.chatgpt.com, formerly developers.openai.com/codex) and the [openai/codex](https://github.com/openai/codex) repo — originally at v0.125.0 (April 2026), updated in September 2026 for v0.158.0. > ⚠️ Note: this is the **new Codex CLI** released in 2025 (open-source, terminal agent), *not* the original Codex model that was deprecated in 2023. The product family also includes **Codex App** (desktop) and **Codex Web** (cloud agent at `chatgpt.com/codex`); this doc covers the CLI only. @@ -13,9 +13,9 @@ | Concept | Description | Use Case | |---------|-------------|----------| | **AGENTS.md** | Project/global instruction file | Like Claude Code's CLAUDE.md; auto-loaded on launch | -| **Approval Mode** | When does Codex pause to ask | `untrusted` / `on-request` / `never` | +| **Approval Mode** | When does Codex pause to ask | `on-request` / `never` (config also accepts `granular`) | | **Sandbox Mode** | What files/network it can touch | `read-only` / `workspace-write` / `danger-full-access` | -| **Profile** | Named bundle of config | `--profile work` to swap model/permissions | +| **Profile** | Separate `.config.toml` overlay | `--profile work` to swap model/permissions | | **Subagent** | Child agent for bounded tasks | TOML-defined, can have its own model/sandbox | | **Skill** | Reusable workflow (SKILL.md) | Package a recurring task as a named capability | | **MCP Server** | External tool integration | STDIO or HTTP/OAuth | @@ -28,7 +28,13 @@ ### Installation ```bash -# npm (recommended) +# Official install script (recommended, macOS / Linux / WSL) +curl -fsSL https://chatgpt.com/codex/install.sh | sh + +# Windows PowerShell +irm https://chatgpt.com/codex/install.ps1 | iex + +# or npm npm install -g @openai/codex # or Homebrew (macOS) @@ -49,7 +55,7 @@ codex # On first launch, choose "Sign in with ChatGPT" Two options: - **ChatGPT account login** (officially recommended) — uses your ChatGPT Plus / Pro / Business / Edu / Enterprise quota; opens a browser for OAuth. -- **API key** — for CI, corporate proxies, or precise per-token billing; needs extra setup (see `developers.openai.com/codex/auth`). +- **API key** — for CI, corporate proxies, or precise per-token billing; needs extra setup (see [learn.chatgpt.com/docs/auth](https://learn.chatgpt.com/docs/auth)). ### Your First Run @@ -106,13 +112,13 @@ Discovery order (important): /AGENTS.md ← module-local (overrides parents) ``` -Files are concatenated from shallow to deep; closer-to-cwd files win. Default 32 KiB cap per file, tunable via `project_doc_max_bytes`. +Files are concatenated from shallow to deep; closer-to-cwd files win. The default 32 KiB cap applies to **all instruction files combined** (not per file), tunable via `project_doc_max_bytes`. --- ## Prompting Tips -OpenAI's recommended four-element prompt template (from `developers.openai.com/codex/learn/best-practices`): +OpenAI's recommended four-element prompt template (from [learn.chatgpt.com/guides/best-practices](https://learn.chatgpt.com/guides/best-practices)): ``` Goal: what to change or build @@ -147,6 +153,8 @@ Push harder for hard problems, dial back for easy ones: - **low** — small edits, formatting - **medium / high** — most refactors and bugfixes - **xhigh** — architectural, multi-file, deeply coupled +- **max** — hardest problems, maximum reasoning depth +- **ultra** — parallel task delegation via subagents (not supported by `gpt-6-luna`) Switch in the TUI via shortcut, or set the default in `config.toml`. @@ -187,18 +195,20 @@ Codex's distinguishing design — two independent dimensions. Enforcement (verified against `codex-rs/cli/src/debug_sandbox.rs`): - **macOS** — Seatbelt (built-in) -- **Linux / WSL2** — **Landlock** kernel LSM + seccomp filtering (requires Linux 5.13+ with Landlock enabled) +- **Linux / WSL2** — **bubblewrap** by default (the older Landlock + seccomp path is kept as legacy) - **Windows** — Restricted-token sandbox (active in PowerShell) -> Tip: `codex sandbox seatbelt|landlock|windows -- ` is the debug subcommand to verify whether a single command would survive the sandbox. +> Tip: `codex sandbox [--] ` verifies whether a single command would survive the sandbox; it auto-selects the current platform's sandbox. ### Approval (when it asks) | Mode | Behavior | |------|----------| -| `untrusted` | Only known-safe read ops auto-run; everything else asks | | `on-request` ⭐ default | Auto-runs inside sandbox; only asks when going outside | | `never` | Never asks (CI / scripts — pair with a tight sandbox) | +| `granular` | config.toml only; fine-grained control over which request categories ask | + +> `untrusted` was retired in v0.149; the CLI's `--ask-for-approval` only accepts `on-request | never`. ### Common Combos @@ -216,7 +226,7 @@ codex --sandbox read-only codex --add-dir ../sibling-repo --add-dir /tmp/scratch # Non-interactive in CI / scripts -codex exec --sandbox workspace-write --ask-for-approval never "run tests and fix failures" +codex exec --sandbox workspace-write "run tests and fix failures" # Open the sandbox fully (you understand the consequences) codex --sandbox danger-full-access --ask-for-approval never @@ -226,9 +236,9 @@ codex --yolo # equivalent to: codex --dangerously-bypass-approvals-and-sandbox ``` -> ⚠️ **`--full-auto` is deprecated and removed** (v0.125.0 still keeps it inside `codex exec` only to print a migration warning). Use `--sandbox workspace-write` — that's the official replacement; approval defaults to `on-request` already. +> ⚠️ **`--full-auto` is removed** (as of v0.147 even the migration warning in `codex exec` is gone). Use `--sandbox workspace-write` — that's the official replacement; approval defaults to `on-request` already. > -> 🚨 **CI gotcha**: the default approval mode is interactive — CI will hang on the prompt and time out. `codex exec` + `--ask-for-approval never` is the canonical CI shape. +> 🚨 **CI gotcha**: interactive `codex` waits for approvals — CI will hang on the prompt and time out. Use `codex exec` in CI: it already runs with `never` and **does not accept** `--ask-for-approval` / `-a` (passing it is an error). --- @@ -239,35 +249,36 @@ codex --yolo `~/.codex/config.toml` (user) / `.codex/config.toml` (project): ```toml -model = "gpt-5.5" +model = "gpt-6-sol" approval_policy = "on-request" sandbox_mode = "workspace-write" +web_search = "cached" # top-level key: disabled / cached / indexed / live ([features] web_search is deprecated) [features] -web_search = "cached" # cached by default; --search switches to live multi_agent = true -[profiles.review] -model = "gpt-5.5" -approval_policy = "untrusted" -sandbox_mode = "read-only" - -[profiles.ci] -approval_policy = "never" -sandbox_mode = "workspace-write" - [mcp_servers.github] -command = "npx @modelcontextprotocol/server-github" +command = "npx" +args = ["-y", "@modelcontextprotocol/server-github"] enabled = true ``` -Switch profiles: +Profiles are now **separate files** at `$CODEX_HOME/.config.toml` (default `~/.codex/`) containing top-level keys; `--profile ` layers one on top of the main config: + +```toml +# ~/.codex/review.config.toml +model = "gpt-6-sol" +approval_policy = "on-request" +sandbox_mode = "read-only" +``` ```bash codex --profile review # read-only review pass -codex exec --profile ci "..." # CI / scripted run +codex exec --profile ci "..." # CI / scripted run (~/.codex/ci.config.toml) ``` +> ⚠️ If `config.toml` still contains the legacy `[profiles.]` tables or `profile = "..."`, Codex **errors out** — migrate them to separate files. + ### 2. Slash Commands Cheat Sheet | Command | Use | @@ -277,9 +288,10 @@ codex exec --profile ci "..." # CI / scripted run | `/plan` | Enter Plan Mode | | `/review` | Have Codex review the current diff / branch / commit | | `/compact` | Compress conversation history; free up tokens | -| `/agent` | Switch between active subagent threads (`/multi-agents` alias) | -| `/side` | Open a side conversation in an ephemeral fork — won't pollute main thread | -| `/permissions` `/approvals` | Adjust approval mode on the fly | +| `/multi-agents` | Switch between active subagent threads (alias `/subagents`; formerly `/agent`) | +| `/agents` | Open the agent command center | +| `/side` `/btw` | Open a side conversation in an ephemeral fork — won't pollute main thread | +| `/permissions` | Adjust approval mode on the fly (formerly `/approvals`) | | `/resume` `/fork` | Resume / branch from a prior thread | | `/new` `/clear` | Start a new conversation in the same session / clear and restart | | `/rename` | Rename the current thread | @@ -291,11 +303,14 @@ codex exec --profile ci "..." # CI / scripted run | `/plugins` `/apps` | Browse plugins / apps | | `/status` | Session details and token usage | | `/goal` | Set / view goal for a long-running task | -| `/fast` | Toggle Fast mode (`on`/`off`/`status`) | | `/debug-config` | Print config layers and requirements diagnostics (**use this when config.toml edits don't take effect**) | | `/feedback` | Send logs to OpenAI maintainers | +| `/import` | Import config from Claude Code / Cursor | +| `/worktree` | Start an isolated task in a git worktree | +| `/hooks` | View / manage hooks | +| `/voice` `/tui` `/export` `/usage` | Voice input / TUI settings / export conversation / view usage | -> Complete list (46 commands) lives in source `codex-rs/tui/src/slash_command.rs::SlashCommand`. Just press `/` in the TUI for autocomplete. +> Complete list (~70 commands) lives in source `codex-rs/tui/src/slash_command.rs::SlashCommand`. Just press `/` in the TUI for autocomplete. ### 3. Non-interactive Execution (`exec`) @@ -308,8 +323,8 @@ codex exec "replace all console.log with logger.debug" # Pipe in git diff main..HEAD | codex exec "review this diff for bugs" -# Pin model + skip approvals -codex exec -m gpt-5.5 --ask-for-approval never "add unit tests for new files" +# Pin model (exec never asks for approval anyway) +codex exec -m gpt-6-sol "add unit tests for new files" # Stream events as JSONL (one JSON object per line) codex exec --json "..." | jq -c . @@ -325,7 +340,7 @@ codex exec -o /tmp/answer.txt "..." ```toml name = "explorer" description = "Read-only codebase explorer; gathers evidence before any change." -model = "gpt-5.3-codex" +model = "gpt-6-luna" sandbox_mode = "read-only" developer_instructions = """ Stay in exploration mode. @@ -345,7 +360,7 @@ Each subagent runs in its own sandbox + model and returns its summary to the mai ### 5. MCP — External Tools ```bash -codex mcp add github --command "npx @modelcontextprotocol/server-github" +codex mcp add github -- npx -y @modelcontextprotocol/server-github codex mcp list ``` @@ -385,9 +400,9 @@ $skill-creator # explicit trigger with $ prefix > Ready-made skill libraries: [ComposioHQ/awesome-codex-skills](https://github.com/composio-community/awesome-codex-skills), [VoltAgent/awesome-agent-skills](https://github.com/VoltAgent/awesome-agent-skills) (cross-tool). -### 7. Hooks — Inject Custom Scripts into the Agent Loop (beta) +### 7. Hooks — Inject Custom Scripts into the Agent Loop -Enable `[features] codex_hooks = true` and Codex will invoke your shell scripts at 6 event points: +The `hooks` feature is stable and **on by default** (the old `codex_hooks` flag name remains as an alias; set `[features] hooks = false` to turn it off). Codex invokes your scripts at 12 event points; the most common: | Event | When | Typical Use | |-------|------|-------------| @@ -396,19 +411,21 @@ Enable `[features] codex_hooks = true` and Codex will invoke your shell scripts | `PostToolUse` | After a tool call | Auto lint / format / test | | `SessionStart` | Session boot | Inject project-specific context | | `UserPromptSubmit` | User submits prompt | Insert disclaimer, run safety scan | -| `Stop` | Session ends | Upload logs, clean tmp files | +| `Stop` | Turn ends | Enforce verification, wrap up | + +> Other events: `PreCompact`, `PostCompact`, `SessionEnd`, `SubagentStart`, `SubagentStop`, `Interrupt`. > 💡 The hooks JSON schema reuses Claude Code's `hooks.json` format directly (the source engine is literally named `ClaudeHooksEngine`), so migrating from Claude Code is zero-change. -Config goes in `.codex/hooks.json`. Reference impl: [shanraisshan/codex-cli-hooks](https://github.com/shanraisshan/codex-cli-hooks). +Config goes in `.codex/hooks.json`, or inline in `config.toml` as `[[hooks.PreToolUse]]` etc. tables. Reference impl: [shanraisshan/codex-cli-hooks](https://github.com/shanraisshan/codex-cli-hooks). The two highest-leverage uses: - **PostToolUse → run prettier / ruff / clang-format** — Codex edits, hook formats, CI stays green - **PreToolUse → intercept `rm -rf` / `git push --force` / DB DROP** — belt-and-suspenders safety -### 8. Memories — Cross-Session Long-Term Memory (beta) +### 8. Memories — Cross-Session Long-Term Memory -Enable `[features] memories = true` and Codex carries facts you've confirmed across sessions ("this project uses pnpm — don't suggest npm"). +Stable, but still **off by default**. Enable `[features] memories = true` and Codex carries facts you've confirmed across sessions ("this project uses pnpm — don't suggest npm"). ```bash /memories # TUI: view / generate / reset @@ -442,19 +459,19 @@ codex plugin marketplace remove Community marketplace index: [hashgraph-online/awesome-codex-plugins](https://github.com/hashgraph-online/awesome-codex-plugins). -### 10. Fast Mode — 1.5× speed, 2× credits (gpt-5.4 only) +### 10. Speed Tier — `service_tier` -``` -/fast on # enable -/fast status # current -/fast off # disable +The old `/fast` command is gone; set the speed tier in config instead: + +```toml +service_tier = "priority" # default / priority (faster) / flex (slower, cheaper) ``` -Best when "I know roughly what to change, I just need a fast typist." Pro subscribers can also use `gpt-5.3-codex-spark` for near-realtime micro-iteration. +Best when "I know roughly what to change, I just need a fast typist." ### 11. Web Search -On by default in `cached` mode (OpenAI's pre-indexed snapshot). For real-time, add `--search`: +On by default in `cached` mode (OpenAI's pre-indexed snapshot). Configure it with the top-level `web_search = "disabled|cached|indexed|live"`; for real-time, add `--search`: ```bash codex --search "Latest React 19 useActionState best practices" @@ -469,8 +486,8 @@ codex -i screenshot.png "match this design in src/components/Pricing.tsx" PNG / JPEG; you can also paste screenshots directly into the TUI composer. Combined with Chrome DevTools / Playwright MCP, Codex can read browser console output itself: ```bash -codex mcp add chrome-devtools --command "npx chrome-devtools-mcp" -codex mcp add playwright --command "npx @playwright/mcp" +codex mcp add chrome-devtools -- npx chrome-devtools-mcp +codex mcp add playwright -- npx @playwright/mcp ``` ### 13. Local Open-Source Models (`--oss`) @@ -486,7 +503,7 @@ codex --oss --local-provider ollama -m deepseek-coder-v2 codex --oss --local-provider lmstudio ``` -Fully offline, zero API cost. Trade-off: local models are noticeably weaker than GPT-5.5. Best for: sensitive on-premise data, no-network environments, bulk low-complexity tasks. +Fully offline, zero API cost. Trade-off: local models are noticeably weaker than the GPT-6 family. Best for: sensitive on-premise data, no-network environments, bulk low-complexity tasks. > Model IDs follow Ollama / LM Studio naming (run `ollama list` to see what's local). Codex doesn't maintain a separate catalog. @@ -533,13 +550,15 @@ jobs: ⚠️ **The sandbox blocks network by default** — if your review prompt needs to run tests or install deps, do `npm ci` in a step *before* invoking `codex-action`. -### 15. Codex as an MCP Server (Reverse Integration) +### 15. Codex as a Backend Service (Reverse Integration) ```bash -codex mcp-server # expose Codex as an MCP server +codex app-server # expose Codex to other programs ``` -Source confirms this exposes `codex()` and `codex-reply()` MCP tools. Use case: let Claude Code, Cursor, or any other agent call Codex as "a colleague" for parallel work or cross-verification. +> ⚠️ The old `codex mcp-server` was removed in v0.154 — use `codex app-server` instead. + +Use case: let IDEs, Claude Code, Cursor, or other tools call Codex as "a colleague" for parallel work or cross-verification. ### 16. Rules / Execpolicy (Advanced Safety) @@ -565,6 +584,15 @@ codex execpolicy check --rules .codex/rules/safety.rules git push --force Best for enterprise / team setups — finer-grained than approval modes. See [`codex-rs/execpolicy/README.md`](https://github.com/openai/codex/blob/main/codex-rs/execpolicy/README.md). +### 17. New in H2 2026 + +- **Models**: `gpt-6-sol` is recommended (everyday + complex coding), plus `gpt-6-astra` (most capable) and `gpt-6-luna` (lightweight). `gpt-5.4` / `gpt-5.4-mini` were retired on 2026-08-31, `gpt-5.5` retires on 2026-10-14, and `gpt-5.3-codex` is deprecated +- **Reasoning effort**: now goes up to `max` / `ultra` +- **`/import`**: one-shot import of config from Claude Code / Cursor +- **Worktrees by default**: tasks run in isolated worktrees by default; see `/worktree` +- **`codex agents`**: agent command center; **`codex review`**: code review straight from the CLI; **`codex doctor`**: environment diagnostics +- New **`--approve-for-me`** approval-related flag (see `codex --help`) + --- ## High-Signal Prompting & Workflow Patterns @@ -594,7 +622,7 @@ Distilled from high-star community guides ([shanraisshan/codex-cli-best-practice ``` ✅ Heuristic: a fresh dev should be able to launch codex → "run the tests" → it works first try If not, your AGENTS.md is missing build/setup/test commands -✅ Aim for ~150 lines (hard limit is 32 KiB byte-wise) — longer ≠ better +✅ Aim for ~150 lines (default cap is 32 KiB across all instruction files combined) — longer ≠ better ✅ Behavior rules (approval / sandbox / model) belong in config.toml, NOT AGENTS.md ✅ AGENTS.override.md for personal preferences — keeps team's AGENTS.md clean ``` @@ -623,14 +651,14 @@ Distilled from high-star community guides ([shanraisshan/codex-cli-best-practice |---------|-----------|-----| | Browser pops up demanding login | Token expired | Re-run `codex` (or `codex login`) and complete OAuth | | `429 Too Many Requests` | Rate-limited | Wait for quota; for scripts, switch to API key + throttle | -| CI job hangs and times out | Default approval is interactive | `codex exec --ask-for-approval never` | +| CI job hangs and times out | Interactive `codex` waits for approvals | Use `codex exec` (never asks; don't pass `-a`) | | `config.toml` edits don't take effect | Wrong path / config layering overrides yours | Run `/debug-config` in the TUI to see the resolved config stack and requirements | | `npm i -g` fails with `EACCES` | Global dir owned by root | Install Node via nvm/fnm; never `sudo npm` | | `which -a codex` shows multiple paths | npm + brew + binary all installed | Remove dupes; `hash -r` your shell | | Codex "can't see" your edits | Outside workspace / wrong root | `codex --cd ` to set the root | | Long thread getting slow / pricey | Context bloat | `/compact` or `/fork` to trim | | Two agents clobber the same file | Main + subagent both writing | Give the subagent a git worktree | -| Linux sandbox refuses to start | Kernel < 5.13 or Landlock not enabled | Update the kernel (check `uname -r`); on older distros fall back to `--sandbox read-only` | +| Linux sandbox refuses to start | Unprivileged user namespaces (needed by the default bubblewrap sandbox) are disabled | Check your distro's user-namespace settings; reproduce with `codex sandbox -- `; fall back to `--sandbox read-only` temporarily | --- @@ -642,8 +670,8 @@ These two are the closest analogs, but they optimize differently: |-----------|-----------|-------------| | Vendor | OpenAI | Anthropic | | Open-source | ✅ Apache-2.0 (Rust) | ❌ Closed-source CLI | -| Sandbox | OS-kernel level (Seatbelt / Landlock) | App-layer + 26 hook events | -| Default account | ChatGPT subscription | Claude API / Pro | +| Sandbox | OS level (Seatbelt / bubblewrap) | OS-level Bash sandbox via `/sandbox` (Seatbelt / bubblewrap) + 30+ hook events | +| Default account | ChatGPT subscription | Claude Pro / Max / Team / Enterprise or Console API (Bedrock / Vertex / Foundry also supported) | | Config files | `AGENTS.md` + `config.toml` | `CLAUDE.md` + `settings.json` | | Plan mode | `/plan` or Shift+Tab | `/plan` | | Subagents | TOML files | Markdown files | @@ -664,7 +692,7 @@ Already paying for ChatGPT and budget-sensitive → Codex comes practically free The `templates/` directory provides: - [`AGENTS.md`](./templates/AGENTS.md) — generic project instruction template -- [`config.toml`](./templates/config.toml) — user-level config with profiles +- [`config.toml`](./templates/config.toml) — user-level config (with profile-file examples) - [`agent-explorer.toml`](./templates/agent-explorer.toml) — read-only exploration subagent - [`SKILL.md`](./templates/SKILL.md) — Skill template (with Gotchas + trigger-style description) @@ -675,11 +703,11 @@ The `templates/` directory provides: ### Official - Repo: [openai/codex](https://github.com/openai/codex) (Apache-2.0, Rust) -- Docs: [developers.openai.com/codex](https://developers.openai.com/codex) +- Docs: [learn.chatgpt.com/docs](https://learn.chatgpt.com/docs) (formerly developers.openai.com/codex) - Install guide: [docs/install.md](https://github.com/openai/codex/blob/main/docs/install.md) -- Best practices: [Best practices](https://developers.openai.com/codex/learn/best-practices) -- Sandboxing internals: [Sandboxing](https://developers.openai.com/codex/concepts/sandboxing) -- Slash commands: [Slash commands](https://developers.openai.com/codex/cli/slash-commands) +- Best practices: [Best practices](https://learn.chatgpt.com/guides/best-practices) +- Sandboxing internals: [Sandboxing](https://learn.chatgpt.com/docs/sandboxing) +- Slash commands: [Slash commands](https://learn.chatgpt.com/docs/developer-commands?surface=cli) - Official GitHub Action (CI integration): [openai/codex-action](https://github.com/openai/codex-action) - Official skills catalog: [openai/skills](https://github.com/openai/skills) @@ -705,4 +733,4 @@ The `templates/` directory provides: In this repo: [workflows/tool-selection.en.md](../workflows/tool-selection.en.md) -> Verified through: **2026-04-30** (codex CLI v0.125.0). Every CLI flag, subcommand, slash command, and config field in this guide was cross-checked against the `codex-rs` source code; models and pricing change quickly — the OpenAI docs are always the source of truth. +> Verified through: **2026-09** (codex CLI v0.158.0). Every CLI flag, subcommand, slash command, and config field in this guide was cross-checked against the `codex-rs` source code; models and pricing change quickly — the OpenAI docs are always the source of truth. diff --git a/codex/README.md b/codex/README.md index d1acd7e..d7565a7 100644 --- a/codex/README.md +++ b/codex/README.md @@ -2,7 +2,7 @@ **简体中文** | [English](./README.en.md) -> Codex CLI 是 OpenAI 官方的开源终端编程 Agent,用 Rust 写成,与 Claude Code、Gemini CLI 同属"终端 Agent 三巨头"。本文基于官方文档(developers.openai.com/codex)和仓库 [openai/codex](https://github.com/openai/codex) 的 v0.125.0(2026-04)核实整理。 +> Codex CLI 是 OpenAI 官方的开源终端编程 Agent,用 Rust 写成,与 Claude Code、Gemini CLI 同属"终端 Agent 三巨头"。本文基于官方文档(learn.chatgpt.com,原 developers.openai.com/codex)和仓库 [openai/codex](https://github.com/openai/codex) 核实整理,最初对齐 v0.125.0(2026-04),2026-09 按 v0.158.0 更新。 > ⚠️ 注意:这里讲的是 2025 年发布的**新 Codex CLI**(开源、终端 Agent),不是 2023 年退役的旧 Codex 模型。同名产品系列还包括 **Codex App**(桌面端)和 **Codex Web**(云端 Agent,`chatgpt.com/codex`),本文只覆盖 CLI。 @@ -13,9 +13,9 @@ | 概念 | 说明 | 用途 | |------|------|------| | **AGENTS.md** | 项目/全局指令文件 | 类似 Claude Code 的 CLAUDE.md,启动时自动加载 | -| **Approval Mode** | 何时需要人来批 | `untrusted` / `on-request` / `never` | +| **Approval Mode** | 何时需要人来批 | `on-request` / `never`(config 里另有 `granular`) | | **Sandbox Mode** | 能动什么文件、能不能联网 | `read-only` / `workspace-write` / `danger-full-access` | -| **Profile** | 一组 config 的命名预设 | `--profile work` 一键切换模型/权限 | +| **Profile** | 独立的 `.config.toml` 叠加层 | `--profile work` 一键切换模型/权限 | | **Subagent** | 子 Agent,独立任务 | TOML 定义,可设置不同模型/权限 | | **Skill** | 可复用工作流(SKILL.md) | 把重复任务封装成命名能力 | | **MCP Server** | 外部工具接入 | STDIO 或 HTTP/OAuth | @@ -28,7 +28,13 @@ ### 安装 ```bash -# npm(推荐) +# 官方安装脚本(推荐,macOS / Linux / WSL) +curl -fsSL https://chatgpt.com/codex/install.sh | sh + +# Windows PowerShell +irm https://chatgpt.com/codex/install.ps1 | iex + +# 或 npm npm install -g @openai/codex # 或 Homebrew (macOS) @@ -49,7 +55,7 @@ codex # 第一次启动,按提示选 "Sign in with ChatGPT" 两种方式: - **ChatGPT 账号登录**(官方推荐)—— 走 ChatGPT Plus / Pro / Business / Edu / Enterprise 订阅额度,开浏览器走 OAuth。 -- **API Key** —— 适合 CI、企业代理或想精确按量计费的场景,需要额外设置(详见 `developers.openai.com/codex/auth`)。 +- **API Key** —— 适合 CI、企业代理或想精确按量计费的场景,需要额外设置(详见 [learn.chatgpt.com/docs/auth](https://learn.chatgpt.com/docs/auth))。 ### 第一次跑 @@ -106,13 +112,13 @@ Next.js 14 + TypeScript 电商后台。 子目录/AGENTS.md ← 模块级局部规则(覆盖父级) ``` -文件按目录从浅到深拼接,越靠近当前目录的越优先生效。默认每个文件最多 32 KiB,可通过 `project_doc_max_bytes` 调。 +文件按目录从浅到深拼接,越靠近当前目录的越优先生效。所有指令文件**合计**默认最多 32 KiB(不是每个文件各 32 KiB),可通过 `project_doc_max_bytes` 调。 --- ## 提示词技巧 -Codex 官方推荐"四元素"提示模板(来源:developers.openai.com/codex/learn/best-practices): +Codex 官方推荐"四元素"提示模板(来源:[learn.chatgpt.com/guides/best-practices](https://learn.chatgpt.com/guides/best-practices)): ``` Goal: 要做什么?要改什么? @@ -147,6 +153,8 @@ Done when: 完成判定条件是什么? - **low** — 简单改动、风格调整 - **medium / high** — 大多数日常重构、Bug 修复 - **xhigh** — 架构级、多文件复杂逻辑 +- **max** — 最难的问题,最大推理深度 +- **ultra** — 用 subagent 并行分派任务(`gpt-6-luna` 不支持) 可在 TUI 里通过快捷键切换,或在 config.toml 里设默认。 @@ -187,18 +195,20 @@ Done when: 完成判定条件是什么? 技术实现(核实自 `codex-rs/cli/src/debug_sandbox.rs` 源码): - **macOS** — Seatbelt(系统自带) -- **Linux / WSL2** — **Landlock** 内核 LSM + seccomp 过滤(需要 Linux 5.13+ 且 Landlock 已启用) +- **Linux / WSL2** — 默认 **bubblewrap**(旧的 Landlock + seccomp 方案保留为 legacy) - **Windows** — Restricted token sandbox(PowerShell 下生效) -> 提示:可以用 `codex sandbox seatbelt|landlock|windows -- ` 这组调试子命令,单独验证某条命令在沙箱里能不能跑。 +> 提示:可以用 `codex sandbox [--] ` 单独验证某条命令在沙箱里能不能跑,会自动选当前平台的沙箱实现。 ### Approval(什么时候问你) | 模式 | 行为 | |------|------| -| `untrusted` | 只有官方判定为安全的只读操作自动跑,其他都要批 | | `on-request` ⭐ 默认 | 在 sandbox 内自动跑,越界(写外、联网)才问 | | `never` | 永不询问(用于 CI / 脚本,配 sandbox 用) | +| `granular` | 仅 config.toml 可用,按类别细分哪些请求要问 | + +> `untrusted` 已在 v0.149 退役,CLI 的 `--ask-for-approval` 只接受 `on-request | never`。 ### 常用组合 @@ -216,7 +226,7 @@ codex --sandbox read-only codex --add-dir ../sibling-repo --add-dir /tmp/scratch # 在 CI / 脚本里非交互执行 -codex exec --sandbox workspace-write --ask-for-approval never "跑测试并修复失败用例" +codex exec --sandbox workspace-write "跑测试并修复失败用例" # 临时完全放开沙箱(明白后果再用) codex --sandbox danger-full-access --ask-for-approval never @@ -226,9 +236,9 @@ codex --yolo # 等价于:codex --dangerously-bypass-approvals-and-sandbox ``` -> ⚠️ **`--full-auto` 已废弃移除**(v0.125.0 仍在 `codex exec` 里保留作迁移提示)。直接 `--sandbox workspace-write` 就是同义;approval 默认本就是 `on-request`。 +> ⚠️ **`--full-auto` 已移除**(v0.147 起 `codex exec` 里的迁移提示也删了)。直接 `--sandbox workspace-write` 就是同义;approval 默认本就是 `on-request`。 > -> 🚨 **CI 踩坑**:默认 approval 是交互式的,CI 里会卡死等输入超时。`codex exec` + `--ask-for-approval never` 是 CI 的标准姿势。 +> 🚨 **CI 踩坑**:交互式 `codex` 默认会等人批,CI 里会卡死等输入超时。CI 用 `codex exec`——它本身就按 `never` 运行,**不接受** `--ask-for-approval` / `-a`,加了反而报错。 --- @@ -239,35 +249,36 @@ codex --yolo `~/.codex/config.toml`(用户级)/ `.codex/config.toml`(项目级): ```toml -model = "gpt-5.5" +model = "gpt-6-sol" approval_policy = "on-request" sandbox_mode = "workspace-write" +web_search = "cached" # 顶层 key:disabled / cached / indexed / live([features] web_search 已废弃) [features] -web_search = "cached" # 默认走缓存;--search 切 live multi_agent = true -[profiles.review] -model = "gpt-5.5" -approval_policy = "untrusted" -sandbox_mode = "read-only" - -[profiles.ci] -approval_policy = "never" -sandbox_mode = "workspace-write" - [mcp_servers.github] -command = "npx @modelcontextprotocol/server-github" +command = "npx" +args = ["-y", "@modelcontextprotocol/server-github"] enabled = true ``` -切换 profile: +Profile 现在是**独立文件** `$CODEX_HOME/.config.toml`(默认 `~/.codex/`),里面直接写顶层 key,用 `--profile ` 叠加到主配置上: + +```toml +# ~/.codex/review.config.toml +model = "gpt-6-sol" +approval_policy = "on-request" +sandbox_mode = "read-only" +``` ```bash codex --profile review # 只读模式跑代码审查 -codex exec --profile ci "..." # CI 用脚本模式 +codex exec --profile ci "..." # CI 用脚本模式(~/.codex/ci.config.toml) ``` +> ⚠️ `config.toml` 里如果还有旧写法 `[profiles.]` 或 `profile = "..."`,Codex 会**直接报错**,需要迁移到独立文件。 + ### 2. Slash 命令速查 TUI 内常用: @@ -279,9 +290,10 @@ TUI 内常用: | `/plan` | 进入 Plan Mode | | `/review` | 让 Codex 审查当前 diff / 分支 / 指定 commit | | `/compact` | 压缩对话历史,释放 token | -| `/agent` | 在多个 subagent thread 间切换(`/multi-agents` 别名) | -| `/side` | 在临时 fork 里开支线对话,问完不污染主线 | -| `/permissions` `/approvals` | 临时调权限 | +| `/multi-agents` | 在多个 subagent thread 间切换(别名 `/subagents`,原 `/agent`) | +| `/agents` | 打开 agent 指挥中心 | +| `/side` `/btw` | 在临时 fork 里开支线对话,问完不污染主线 | +| `/permissions` | 临时调权限(原 `/approvals`) | | `/resume` `/fork` | 恢复 / 从某个时刻分叉对话 | | `/new` `/clear` | 同 session 内开新对话 / 清屏重开 | | `/rename` | 给当前 thread 改名 | @@ -293,11 +305,14 @@ TUI 内常用: | `/plugins` `/apps` | 浏览插件 / 应用 | | `/status` | 当前 session 详情、token 使用 | | `/goal` | 设定 / 查看长任务的目标 | -| `/fast` | 切 Fast mode(`on`/`off`/`status`) | | `/debug-config` | 打印配置层级与 requirements 诊断(**改 config.toml 不生效时用这个**) | | `/feedback` | 给 OpenAI 发日志反馈 | +| `/import` | 从 Claude Code / Cursor 导入配置 | +| `/worktree` | 在 git worktree 里开隔离任务 | +| `/hooks` | 查看 / 管理 hooks | +| `/voice` `/tui` `/export` `/usage` | 语音输入 / TUI 设置 / 导出对话 / 查看用量 | -> 完整表(46 个)见源码 `codex-rs/tui/src/slash_command.rs::SlashCommand` 枚举。在 TUI 里按 `/` 也会弹自动补全。 +> 完整列表(约 70 个)见源码 `codex-rs/tui/src/slash_command.rs::SlashCommand` 枚举。在 TUI 里按 `/` 也会弹自动补全。 ### 3. 非交互执行(exec) @@ -310,8 +325,8 @@ codex exec "把所有 console.log 改成 logger.debug" # 管道 git diff main..HEAD | codex exec "审查这份 diff,找出潜在 bug" -# 指定模型 + 不询问 -codex exec -m gpt-5.5 --ask-for-approval never "为新文件补单测" +# 指定模型(exec 本身就不询问) +codex exec -m gpt-6-sol "为新文件补单测" # 输出 JSONL(每行一个事件)给后续程序处理 codex exec --json "..." | jq -c . @@ -327,7 +342,7 @@ codex exec -o /tmp/answer.txt "..." ```toml name = "explorer" description = "Read-only codebase explorer; gathers evidence before any change." -model = "gpt-5.3-codex" +model = "gpt-6-luna" sandbox_mode = "read-only" developer_instructions = """ Stay in exploration mode. @@ -348,7 +363,7 @@ Never propose changes — just report findings. ```bash # CLI 直接添加 -codex mcp add github --command "npx @modelcontextprotocol/server-github" +codex mcp add github -- npx -y @modelcontextprotocol/server-github codex mcp list ``` @@ -388,9 +403,9 @@ $skill-creator # 用 $ 前缀显式触发某个技能 > 现成 Skill 库可以直接抄:[ComposioHQ/awesome-codex-skills](https://github.com/composio-community/awesome-codex-skills)、[VoltAgent/awesome-agent-skills](https://github.com/VoltAgent/awesome-agent-skills)(跨工具) -### 7. Hooks — 在 Agent 循环里挂自定义脚本(beta) +### 7. Hooks — 在 Agent 循环里挂自定义脚本 -启用 `[features] codex_hooks = true` 后,Codex 在 6 个事件点会调用你定义的 shell 脚本: +`hooks` 功能已稳定并**默认开启**(旧 flag 名 `codex_hooks` 仍作别名;要关就 `[features] hooks = false`)。Codex 在 12 个事件点会调用你定义的脚本,常用的有: | 事件 | 触发时机 | 典型用途 | |------|---------|---------| @@ -399,19 +414,21 @@ $skill-creator # 用 $ 前缀显式触发某个技能 | `PostToolUse` | 工具调用后 | 自动 lint / format / 测试 | | `SessionStart` | session 启动 | 加载项目特定上下文 | | `UserPromptSubmit` | 用户提交 prompt 时 | 注入企业 disclaimer / 安全扫描 | -| `Stop` | session 结束 | 上传日志 / 清理临时文件 | +| `Stop` | 一轮结束 | 强制验证 / 收尾 | + +> 其余事件:`PreCompact`、`PostCompact`、`SessionEnd`、`SubagentStart`、`SubagentStop`、`Interrupt`。 > 💡 hook schema 直接复用 Claude Code 的 `hooks.json` 格式(源码引擎名 `ClaudeHooksEngine`),所以从 Claude Code 迁移过来零改动。 -配置文件 `.codex/hooks.json`,参考实现:[shanraisshan/codex-cli-hooks](https://github.com/shanraisshan/codex-cli-hooks)。 +配置文件 `.codex/hooks.json`,也可以直接在 `config.toml` 里内联写 `[[hooks.PreToolUse]]` 等表。参考实现:[shanraisshan/codex-cli-hooks](https://github.com/shanraisshan/codex-cli-hooks)。 最常见的两个 use case: - **PostToolUse 跑 prettier/ruff** — Codex 改完代码自动格式化,避免 CI 红 - **PreToolUse 拦截 `rm -rf` / `git push --force` / 数据库 DROP** — 双保险 -### 8. Memories — 跨 session 的长期记忆(beta) +### 8. Memories — 跨 session 的长期记忆 -启用 `[features] memories = true`,Codex 会在 session 之间保留你确认过的事实("这个项目用 pnpm,不要建议 npm")。 +功能已稳定,但仍**默认关闭**。启用 `[features] memories = true`,Codex 会在 session 之间保留你确认过的事实("这个项目用 pnpm,不要建议 npm")。 ```bash /memories # TUI 里查看 / 生成 / 重置 @@ -445,19 +462,19 @@ codex plugin marketplace remove 社区 marketplace 索引:[hashgraph-online/awesome-codex-plugins](https://github.com/hashgraph-online/awesome-codex-plugins)。 -### 10. Fast Mode — 1.5× 速度,2× 额度(gpt-5.4 限定) +### 10. 速度档位 — `service_tier` -``` -/fast on # 开启 -/fast status # 看当前 -/fast off # 关 +原来的 `/fast` 命令已经没有了,速度档位改在 config 里设: + +```toml +service_tier = "priority" # default / priority(更快)/ flex(更慢更省) ``` -适合"知道大致怎么改、就缺打字员"的场景。Pro 订阅还能用 `gpt-5.3-codex-spark` 做近实时的小改动迭代。 +适合"知道大致怎么改、就缺打字员"的场景。 ### 11. Web 搜索 -默认开启,cached 模式(OpenAI 预索引)。需要实时结果加 `--search`: +默认开启,cached 模式(OpenAI 预索引)。config 里用顶层 `web_search = "disabled|cached|indexed|live"` 设置;需要实时结果加 `--search`: ```bash codex --search "React 19 useActionState 的最新最佳实践" @@ -472,8 +489,8 @@ codex -i screenshot.png "按这张设计稿改 src/components/Pricing.tsx" PNG / JPEG,可在 TUI 里直接粘贴截图。配 Chrome DevTools / Playwright MCP,让 Codex 自己看浏览器控制台日志: ```bash -codex mcp add chrome-devtools --command "npx chrome-devtools-mcp" -codex mcp add playwright --command "npx @playwright/mcp" +codex mcp add chrome-devtools -- npx chrome-devtools-mcp +codex mcp add playwright -- npx @playwright/mcp ``` ### 13. 本地开源模型(`--oss`) @@ -489,7 +506,7 @@ codex --oss --local-provider ollama -m deepseek-coder-v2 codex --oss --local-provider lmstudio ``` -完全离线、零 API 成本。代价是模型能力比 GPT-5.5 弱不少,适合:本地敏感数据 / 没网环境 / 跑批量低复杂度任务。 +完全离线、零 API 成本。代价是模型能力比 GPT-6 系列弱不少,适合:本地敏感数据 / 没网环境 / 跑批量低复杂度任务。 > 模型 ID 跟着 Ollama / LM Studio 自己的命名(`ollama list` 看本地有什么),Codex 不维护独立清单。 @@ -536,13 +553,15 @@ jobs: ⚠️ **沙箱默认禁网**——如果你的 review prompt 需要跑测试 / 装依赖,先在 Action 步骤里 `npm ci` 再调 `codex-action`。 -### 15. Codex 作为 MCP server(反向接入) +### 15. Codex 作为后端服务(反向接入) ```bash -codex mcp-server # 把 Codex 暴露成 MCP server +codex app-server # 把 Codex 暴露给其他程序调用 ``` -源码确认这会 expose `codex()` 和 `codex-reply()` 两个 MCP 工具。用法:让 Claude Code、Cursor 等其他 Agent 把 Codex 当成"我的同事"调用,做并行任务或交叉验证。 +> ⚠️ 旧的 `codex mcp-server` 已在 v0.154 移除,改用 `codex app-server`。 + +用法:让 IDE、Claude Code、Cursor 等其他工具把 Codex 当成"我的同事"调用,做并行任务或交叉验证。 ### 16. Rules / Execpolicy(高级安全) @@ -568,6 +587,15 @@ codex execpolicy check --rules .codex/rules/safety.rules git push --force 适合企业 / 团队场景,比单纯 approval 更细粒度。详见 [`codex-rs/execpolicy/README.md`](https://github.com/openai/codex/blob/main/codex-rs/execpolicy/README.md)。 +### 17. 2026 下半年新增 + +- **模型**:推荐 `gpt-6-sol`(日常 + 复杂编码),另有 `gpt-6-astra`(最强)、`gpt-6-luna`(轻量);`gpt-5.4` / `gpt-5.4-mini` 已于 2026-08-31 下线,`gpt-5.5` 将于 2026-10-14 下线,`gpt-5.3-codex` 已废弃 +- **推理强度**:最高到 `max` / `ultra` +- **`/import`**:一键从 Claude Code / Cursor 导入配置 +- **worktree 默认化**:任务默认在隔离 worktree 里跑,配 `/worktree` +- **`codex agents`**:agent 指挥中心;**`codex review`**:命令行直接做代码审查;**`codex doctor`**:环境诊断 +- 新增 **`--approve-for-me`** 审批相关 flag(用法见 `codex --help`) + --- ## 高质量提示词与工作模式 @@ -597,7 +625,7 @@ codex execpolicy check --rules .codex/rules/safety.rules git push --force ``` ✅ 经验法则:随便一个新人能跑 codex → "run the tests" → 一次过 不行就说明 AGENTS.md 漏了 build/test/setup 命令 -✅ 控制在 150 行附近(硬上限是 32 KiB)—— 长 ≠ 好 +✅ 控制在 150 行附近(所有指令文件合计默认上限 32 KiB)—— 长 ≠ 好 ✅ 行为约束(approval / sandbox / model)写 config.toml,不要写 AGENTS.md ✅ AGENTS.override.md 放个人偏好,别污染团队共享的 AGENTS.md ``` @@ -626,14 +654,14 @@ codex execpolicy check --rules .codex/rules/safety.rules git push --force |------|------|------| | 启动直接弹浏览器要求登录 | token 过期 | 重跑 `codex` 走 OAuth;或 `codex login` | | `429 Too Many Requests` | 触发速率限制 | 等额度恢复;脚本场景考虑切 API key + 限速 | -| CI 任务挂起超时 | 默认 approval 是交互式 | `codex exec --ask-for-approval never` | +| CI 任务挂起超时 | 交互式 `codex` 默认会等人批 | 改用 `codex exec`(本身不询问,别加 `-a`) | | 改了 config.toml 不生效 | 文件路径错 / 配置层叠被覆盖 | TUI 里跑 `/debug-config` 看实际生效的配置层级和 requirements | | `npm i -g` 报 `EACCES` | 全局目录归 root | 用 nvm/fnm 装 Node,不要 `sudo npm` | | `which -a codex` 返回多行 | 装重了(npm + brew + binary) | 删多余的,shell rehash | | 改完文件 Codex 不"看见" | 没在 git workspace 里 / 路径越界 | `codex --cd ` 指定根目录 | | 长 thread 越来越慢 / 涨钱 | 上下文累积 | `/compact` 压缩;或 `/fork` 重开 | | 多 agent 并行改同一文件冲突 | 主线 + subagent 同时改 | 给 subagent 用 git worktree | -| Linux 沙箱起不来 | 内核 < 5.13 或 Landlock 未启用 | 升级内核(`uname -r` 确认);旧发行版临时用 `--sandbox read-only` 绕过 | +| Linux 沙箱起不来 | 默认 bubblewrap 依赖的非特权 user namespace 被禁用 | 检查发行版 user namespace 设置;用 `codex sandbox -- ` 复现;临时用 `--sandbox read-only` 绕过 | --- @@ -645,8 +673,8 @@ codex execpolicy check --rules .codex/rules/safety.rules git push --force |------|-----------|-------------| | 厂商 | OpenAI | Anthropic | | 开源 | ✅ Apache-2.0(Rust) | ❌ 闭源 CLI | -| 沙箱 | OS 内核级(Seatbelt / Landlock) | 应用层 + 26 个 Hook | -| 默认账号 | ChatGPT 订阅 | Claude API / Pro | +| 沙箱 | OS 级(Seatbelt / bubblewrap) | OS 级 Bash 沙箱 `/sandbox`(Seatbelt / bubblewrap)+ 30+ 个 Hook 事件 | +| 默认账号 | ChatGPT 订阅 | Claude Pro / Max / Team / Enterprise 或 Console API(也支持 Bedrock / Vertex / Foundry) | | 配置文件 | `AGENTS.md` + `config.toml` | `CLAUDE.md` + `settings.json` | | Plan 模式 | `/plan` 或 Shift+Tab | `/plan` | | Subagent | TOML 文件 | Markdown 文件 | @@ -668,7 +696,7 @@ codex execpolicy check --rules .codex/rules/safety.rules git push --force `templates/` 目录提供: - [`AGENTS.md`](./templates/AGENTS.md) — 通用项目指令模板 -- [`config.toml`](./templates/config.toml) — 用户级配置模板(含 profiles) +- [`config.toml`](./templates/config.toml) — 用户级配置模板(含 profile 文件写法) - [`agent-explorer.toml`](./templates/agent-explorer.toml) — 只读探索 subagent 模板 - [`SKILL.md`](./templates/SKILL.md) — Skill 模板(含 Gotchas / 触发器写法范本) @@ -679,11 +707,11 @@ codex execpolicy check --rules .codex/rules/safety.rules git push --force ### 官方 - 仓库:[openai/codex](https://github.com/openai/codex)(Apache-2.0,Rust) -- 文档:[developers.openai.com/codex](https://developers.openai.com/codex) +- 文档:[learn.chatgpt.com/docs](https://learn.chatgpt.com/docs)(原 developers.openai.com/codex) - 安装详解:[docs/install.md](https://github.com/openai/codex/blob/main/docs/install.md) -- 最佳实践:[Best practices](https://developers.openai.com/codex/learn/best-practices) -- 沙箱原理:[Sandboxing](https://developers.openai.com/codex/concepts/sandboxing) -- Slash 命令:[Slash commands](https://developers.openai.com/codex/cli/slash-commands) +- 最佳实践:[Best practices](https://learn.chatgpt.com/guides/best-practices) +- 沙箱原理:[Sandboxing](https://learn.chatgpt.com/docs/sandboxing) +- Slash 命令:[Slash commands](https://learn.chatgpt.com/docs/developer-commands?surface=cli) - 官方 GitHub Action(CI 集成):[openai/codex-action](https://github.com/openai/codex-action) - 官方 Skills 目录:[openai/skills](https://github.com/openai/skills) @@ -709,4 +737,4 @@ codex execpolicy check --rules .codex/rules/safety.rules git push --force 本项目内:[workflows/tool-selection.md](../workflows/tool-selection.md) -> 信息核实截止:**2026-04-30**(codex CLI v0.125.0)。本教程的每条 CLI flag、子命令、slash 命令、config 字段都对照 `codex-rs` 源码核实过;模型能力和定价变化快,最终以 OpenAI 官方文档为准。 +> 信息核实截止:**2026-09**(codex CLI v0.158.0)。本教程的每条 CLI flag、子命令、slash 命令、config 字段都对照 `codex-rs` 源码核实过;模型能力和定价变化快,最终以 OpenAI 官方文档为准。 diff --git a/codex/templates/AGENTS.md b/codex/templates/AGENTS.md index 5fc7aee..9b49e02 100644 --- a/codex/templates/AGENTS.md +++ b/codex/templates/AGENTS.md @@ -2,7 +2,7 @@ > AGENTS.md — Codex CLI 项目指令文件 > 放在 git 仓库根目录,Codex 启动时自动加载(叠加 `~/.codex/AGENTS.md`)。 -> 默认大小限制 32 KiB,建议精简、把详尽内容拆到子目录的 AGENTS.md。 +> 默认大小限制 32 KiB(与其他层级的 AGENTS.md 合计),建议精简、把详尽内容拆到子目录的 AGENTS.md。 ## 项目概览 diff --git a/codex/templates/agent-explorer.toml b/codex/templates/agent-explorer.toml index c638ecd..ce8fe55 100644 --- a/codex/templates/agent-explorer.toml +++ b/codex/templates/agent-explorer.toml @@ -10,13 +10,13 @@ name = "explorer" description = "Read-only codebase explorer. Gathers evidence and maps execution paths before any change is proposed. Use when the change touches multiple files or unfamiliar areas." -# 强制只读 + 不会被批准任何写操作 +# 强制只读 + 不会被批准任何写操作(untrusted 已在 v0.149 退役,用 never 直接拒绝越界请求) sandbox_mode = "read-only" -approval_policy = "untrusted" +approval_policy = "never" -# 用强模型探索,结果质量更高(可换 gpt-5.4 / gpt-5.3-codex 省钱) -model = "gpt-5.5" -model_reasoning_effort = "high" # low / medium / high / xhigh +# 用强模型探索,结果质量更高(可换 gpt-6-luna 省钱) +model = "gpt-6-sol" +model_reasoning_effort = "high" # low / medium / high / xhigh / max developer_instructions = """ You are a read-only code archaeologist. diff --git a/codex/templates/config.toml b/codex/templates/config.toml index 82bdf32..0f204d6 100644 --- a/codex/templates/config.toml +++ b/codex/templates/config.toml @@ -4,12 +4,12 @@ # 强制约束(团队/企业管控):requirements.toml(用户不可覆盖) # ─── 默认行为 ────────────────────────────────────────────────── -model = "gpt-5.5" # 推荐:复杂编码用 gpt-5.5;轻任务可切 gpt-5.4 / gpt-5.3-codex -approval_policy = "on-request" # untrusted / on-request / never +model = "gpt-6-sol" # 推荐:日常 + 复杂编码用 gpt-6-sol;最强 gpt-6-astra,轻任务可切 gpt-6-luna +approval_policy = "on-request" # on-request / never / granular(untrusted 已在 v0.149 退役) sandbox_mode = "workspace-write" # read-only / workspace-write / danger-full-access # Web 搜索(顶层 key,不在 [features] 下) -web_search = "cached" # disabled / cached / live;CLI 用 --search 临时切 live +web_search = "cached" # disabled / cached / indexed / live;CLI 用 --search 临时切 live # ─── 实验性功能开关 ────────────────────────────────────────────── # 注:feature flag key 名以源码 codex-rs/features/src/lib.rs 为准; @@ -20,40 +20,35 @@ unified_exec = true # PTY-backed exec 工具(更接近真实 shell undo = true # 支持 undo 上一步 # ─── Profile:一组命名预设 ──────────────────────────────────── -# 用法:codex --profile review - -[profiles.review] -# 代码审查专用:只读、不批准、强模型 -model = "gpt-5.5" -approval_policy = "untrusted" -sandbox_mode = "read-only" - -[profiles.ci] -# CI / 自动化:永不询问、可写 workspace -approval_policy = "never" -sandbox_mode = "workspace-write" - -[profiles.explore] -# 大代码库探索:只读、强推理 -model = "gpt-5.5" -sandbox_mode = "read-only" - -[profiles.cheap] -# 省钱模式:轻模型 + 默认权限 -model = "gpt-5.3-codex" -approval_policy = "on-request" -sandbox_mode = "workspace-write" +# ⚠️ 不要在本文件写 [profiles.] 或 profile = "...",新版 Codex 会直接报错。 +# 每个 profile 是一个独立文件 $CODEX_HOME/.config.toml(默认 ~/.codex/), +# 里面写顶层 key;用法:codex --profile review +# +# ~/.codex/review.config.toml —— 代码审查专用:只读、强模型 +# model = "gpt-6-sol" +# approval_policy = "on-request" +# sandbox_mode = "read-only" +# +# ~/.codex/ci.config.toml —— CI / 自动化:永不询问、可写 workspace +# approval_policy = "never" +# sandbox_mode = "workspace-write" +# +# ~/.codex/cheap.config.toml —— 省钱模式:轻模型 + 默认权限 +# model = "gpt-6-luna" +# approval_policy = "on-request" +# sandbox_mode = "workspace-write" # ─── MCP Servers ────────────────────────────────────────────── -# 也可以用 `codex mcp add --command "..."` 命令式添加 +# 也可以用 `codex mcp add -- [args...]` 命令式添加 [mcp_servers.github] -command = "npx @modelcontextprotocol/server-github" +command = "npx" +args = ["-y", "@modelcontextprotocol/server-github"] enabled = true # [mcp_servers.postgres] -# command = "npx @modelcontextprotocol/server-postgres" -# args = ["postgresql://localhost:5432/mydb"] +# command = "npx" +# args = ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost:5432/mydb"] # enabled = true # ─── Subagent 全局参数 ──────────────────────────────────────── @@ -63,7 +58,7 @@ max_depth = 2 # 嵌套深度上限 job_max_runtime_seconds = 1800 # 单任务超时(30 分钟) # ─── 项目文档加载 ────────────────────────────────────────────── -project_doc_max_bytes = 32768 # 默认 32 KiB;大型 monorepo 可调高 +project_doc_max_bytes = 32768 # 默认 32 KiB(所有指令文件合计);大型 monorepo 可调高 # project_doc_fallback_filenames = ["AGENTS.md", "CLAUDE.md", "GEMINI.md"] # ↑ 如果项目里只有别家的指令文件,可以让 Codex 兼读 diff --git a/gemini-cli/README.en.md b/gemini-cli/README.en.md index d52ea72..f93b09a 100644 --- a/gemini-cli/README.en.md +++ b/gemini-cli/README.en.md @@ -2,7 +2,9 @@ # Gemini CLI Best Practices -> Gemini CLI is Google's command-line AI coding tool. Its biggest advantages: **generous free tier + massive context window (2M tokens)**. Great for large codebase analysis, long-running tasks, and budget-conscious individual developers. +> ⚠️ **Important change (since 2026-06-18)**: According to the [Google Developers Blog](https://developers.googleblog.com/an-important-update-transitioning-gemini-cli-to-antigravity-cli/), Gemini CLI **no longer serves individual users** (free Gemini Code Assist for individuals and Google AI Pro / Ultra sign-ins no longer work). Enterprise users (Gemini Code Assist Standard / Enterprise) and **paid Gemini API keys** still work, and Google continues to ship updates and support for enterprise users. Individual developers should switch to **Antigravity CLI**, which keeps Skills, Hooks, and Subagents, with Extensions becoming Antigravity plugins. + +> Gemini CLI is Google's command-line AI coding tool. Its biggest advantage: **a massive context window (1M tokens on Gemini 3 models)**. Great for large codebase analysis and long-running tasks. --- @@ -13,8 +15,10 @@ | **GEMINI.md** | Project configuration file | Similar to Claude Code's CLAUDE.md | | **Tools** | Built-in tools (read/write files, run commands, etc.) | Foundation for Agent capabilities | | **Extensions** | Plugins | Connect to Google services and third-party APIs | -| **Context Window** | 2M tokens | Understand massive codebases in a single pass | +| **Context Window** | 1M tokens (Gemini 3 models) | Understand massive codebases in a single pass | | **Sandbox** | Security sandbox | Isolate execution of untrusted code | +| **Skills** | `.gemini/skills/` or `.agents/skills/` | Manage with `gemini skills install / list / uninstall` | +| **Other built-ins** | Native MCP, Hooks, Subagents, Plan Mode, Policy Engine, checkpointing, headless mode | Broadly on par with Claude Code / Codex | --- @@ -24,9 +28,12 @@ ```bash npm install -g @google/gemini-cli + +# or Homebrew +brew install gemini-cli ``` -After installation, run `gemini` to enter interactive mode and follow the prompts to log in with your Google account. +After installation, run `gemini` to enter interactive mode and sign in with an enterprise Google account (Code Assist Standard / Enterprise), or set a paid `GEMINI_API_KEY`. Personal Google account sign-in has not worked since 2026-06-18. > For the latest installation instructions, see the [official repository](https://github.com/google-gemini/gemini-cli). @@ -58,7 +65,7 @@ This is a Go microservices project with 12 services. ## Using the Large Context Window Effectively -Gemini CLI's 2M token context window is its core advantage. But bigger isn't always better — the key is using it right. +Gemini CLI's 1M token context window is its core advantage. But bigger isn't always better — the key is using it right. ### Good Use Cases for Large Context @@ -89,7 +96,7 @@ Do NOT use large context as a substitute for precise investigation ## Prompting Tips -### 1. Leverage the Free Tier for Batch Analysis +### 1. Batch Analysis ``` Check error handling in every Go file under src/: @@ -128,12 +135,12 @@ Sort by migration priority. | Dimension | Gemini CLI | Claude Code | |-----------|-----------|-------------| -| Context window | **2M tokens** (largest) | 200K tokens | -| Free tier | **Generous** | Limited | +| Context window | 1M tokens (Gemini 3) | 1M tokens (Opus 5.5 / Sonnet 5.5) | +| Individual users | No longer served since 2026-06-18 (enterprise accounts / paid API keys only) | Pro / Max subscriptions or API | | Agent capabilities | 2/3 | 3/3 | | Tool ecosystem | Strong Google services integration | Richest MCP ecosystem | -| Skill support | Yes (`.gemini/skills/`) | Yes (`.claude/skills/`) | -| Best for | Large codebase analysis, budget-conscious | Complex Agent tasks, strong execution needed | +| Skill support | Yes (`.gemini/skills/` or `.agents/skills/`) | Yes (`.claude/skills/`) | +| Best for | Large codebase analysis, teams already on Google enterprise plans | Complex Agent tasks, strong execution needed | **Recommended combo**: Use Gemini CLI for large-scale analysis and comprehension, use Claude Code for precise modifications and execution. @@ -143,8 +150,8 @@ Sort by migration priority. | Pitfall | Description | Solution | |---------|-------------|----------| -| Too much context slows things down | Filling the full 2M is slow to process | Only use large context when you need a global view | -| Free tier runs out | Heavy usage triggers rate limits | Plan ahead, batch large tasks together | +| Too much context slows things down | Filling the full 1M is slow to process | Only use large context when you need a global view | +| Personal account sign-in fails | Individual users are no longer served since 2026-06-18 | Switch to Antigravity CLI, or use an enterprise account / paid API key | | Weaker tooling than Claude Code | File ops and command execution not as strong | Use Gemini for analysis, Claude Code for execution | --- diff --git a/gemini-cli/README.md b/gemini-cli/README.md index 786ea09..793a8ae 100644 --- a/gemini-cli/README.md +++ b/gemini-cli/README.md @@ -1,6 +1,8 @@ # Gemini CLI 最佳实践 -> Gemini CLI 是 Google 的命令行 AI 编程工具。最大优势:**免费额度充足 + 超大上下文窗口(2M tokens)**。适合大代码库分析、长任务执行、以及预算敏感的个人开发者。 +> ⚠️ **重要变化(2026-06-18 起)**:据 [Google Developers Blog](https://developers.googleblog.com/an-important-update-transitioning-gemini-cli-to-antigravity-cli/),Gemini CLI **已停止服务个人用户**(免费的 Gemini Code Assist 个人版、Google AI Pro / Ultra 账号登录都不能用了)。企业用户(Gemini Code Assist Standard / Enterprise)和**付费 Gemini API key** 仍可继续使用,Google 也继续为企业用户提供更新和支持。个人开发者请改用 **Antigravity CLI**——它保留了 Skills、Hooks、Subagents,Extensions 变成了 Antigravity plugins。 + +> Gemini CLI 是 Google 的命令行 AI 编程工具。最大优势:**超大上下文窗口(Gemini 3 模型 1M tokens)**。适合大代码库分析、长任务执行。 --- @@ -11,8 +13,10 @@ | **GEMINI.md** | 项目配置文件 | 类似 Claude Code 的 CLAUDE.md | | **Tools** | 内置工具(读写文件、执行命令等) | Agent 能力基础 | | **Extensions** | 扩展插件 | 连接 Google 服务和第三方 API | -| **Context Window** | 2M tokens | 能一次性理解超大代码库 | +| **Context Window** | 1M tokens(Gemini 3 模型) | 能一次性理解超大代码库 | | **Sandbox** | 安全沙箱 | 隔离执行不信任的代码 | +| **Skills** | `.gemini/skills/` 或 `.agents/skills/` | `gemini skills install / list / uninstall` 管理 | +| **其他内置能力** | 原生 MCP、Hooks、Subagents、Plan Mode、Policy Engine、Checkpointing、Headless 模式 | 和 Claude Code / Codex 基本对齐 | --- @@ -22,9 +26,12 @@ ```bash npm install -g @google/gemini-cli + +# 或 Homebrew +brew install gemini-cli ``` -安装后运行 `gemini` 进入交互模式,按提示登录 Google 账号即可。 +安装后运行 `gemini` 进入交互模式,按提示用企业 Google 账号(Code Assist Standard / Enterprise)登录,或设置付费的 `GEMINI_API_KEY`。个人 Google 账号登录自 2026-06-18 起已不可用。 > 最新安装方式请参考 [官方仓库](https://github.com/google-gemini/gemini-cli)。 @@ -56,7 +63,7 @@ npm install -g @google/gemini-cli ## 超大上下文的正确用法 -Gemini CLI 的 2M tokens 上下文窗口是它的核心优势。但大不等于好——关键是用对。 +Gemini CLI 的 1M tokens 上下文窗口是它的核心优势。但大不等于好——关键是用对。 ### 适合大上下文的场景 @@ -87,7 +94,7 @@ Gemini CLI 的 2M tokens 上下文窗口是它的核心优势。但大不等于 ## 提示词技巧 -### 1. 利用免费额度做批量分析 +### 1. 批量分析 ``` 依次检查 src/ 下每个 Go 文件的错误处理: @@ -126,12 +133,12 @@ Gemini CLI 的 2M tokens 上下文窗口是它的核心优势。但大不等于 | 维度 | Gemini CLI | Claude Code | |------|-----------|-------------| -| 上下文窗口 | **2M tokens**(最大) | 200K tokens | -| 免费额度 | **充足** | 有限 | +| 上下文窗口 | 1M tokens(Gemini 3) | 1M tokens(Opus 5.5 / Sonnet 5.5) | +| 个人用户 | 2026-06-18 起停止服务(仅企业账号 / 付费 API key 可用) | Pro / Max 等订阅或 API | | Agent 能力 | ★★☆ | ★★★ | | 工具生态 | Google 服务集成好 | MCP 生态最丰富 | -| Skill 支持 | 有(`.gemini/skills/`) | 有(`.claude/skills/`) | -| 适合 | 大代码库分析、预算敏感 | 复杂 Agent 任务、需要强执行力 | +| Skill 支持 | 有(`.gemini/skills/` 或 `.agents/skills/`) | 有(`.claude/skills/`) | +| 适合 | 大代码库分析、已有 Google 企业订阅 | 复杂 Agent 任务、需要强执行力 | **建议组合**:用 Gemini CLI 做大规模分析和理解,用 Claude Code 做精确的修改和执行。 @@ -141,8 +148,8 @@ Gemini CLI 的 2M tokens 上下文窗口是它的核心优势。但大不等于 | 陷阱 | 说明 | 解决 | |------|------|------| -| 上下文太大反而慢 | 2M 全塞满处理很慢 | 只在需要全局视角时用大上下文 | -| 免费额度用完 | 高频使用会触发限制 | 合理安排,大任务集中做 | +| 上下文太大反而慢 | 1M 全塞满处理很慢 | 只在需要全局视角时用大上下文 | +| 个人账号登录失败 | 2026-06-18 起不再服务个人用户 | 改用 Antigravity CLI,或用企业账号 / 付费 API key | | 工具能力弱于 Claude Code | 文件操作、命令执行不如 CC | 分析用 Gemini,执行用 CC | --- diff --git a/pitfalls/claude-code.en.md b/pitfalls/claude-code.en.md index 4d8e0ac..4a44513 100644 --- a/pitfalls/claude-code.en.md +++ b/pitfalls/claude-code.en.md @@ -16,10 +16,11 @@ - Responses get shorter and vaguer, ending mid-thought **Cause** -Claude has a context window limit. Once conversation + tool calls pass ~80%, the earliest messages get truncated — and the AI loses memory of early decisions. It won't tell you. It pretends to remember, by confabulating. +Claude has a context window limit. As conversation + tool calls approach it, auto-compaction kicks in: earlier conversation is **summarized**, and details or constraints stated only in chat can get lost in the summary (the root `CLAUDE.md` is re-read after compaction, so it survives). It won't tell you. It pretends to remember, by confabulating. **Recovery** ``` +/context # Inspect context usage /compact # Compress context, keep key decisions ``` Or just **start a new session** and pass important info through `CLAUDE.md`. @@ -145,7 +146,7 @@ The key rules are: [restate them yourself]. **Prevention** - Keep `CLAUDE.md` under 200 lines -- For large projects, split into `.claude/rules/` with `globs` for file-type loading +- For large projects, split into `.claude/rules/` with `paths:` frontmatter for path-based loading - Mark critical rules with `` - Use "must / forbidden" instead of "should / try to": diff --git a/pitfalls/claude-code.md b/pitfalls/claude-code.md index a7a96f9..4ee08a2 100644 --- a/pitfalls/claude-code.md +++ b/pitfalls/claude-code.md @@ -14,10 +14,11 @@ - 回答越来越短、越来越笼统,问题没回答完就 ↩ **根因** -Claude 有上下文窗口上限。对话+工具调用累计到 80% 以上时,最早的消息会被截断,AI "忘记"了早期设定。但它不会告诉你——它会**装作记得**,靠编造填空。 +Claude 有上下文窗口上限。对话+工具调用快占满时会触发自动压缩(auto-compaction):早期对话被**总结成摘要**,细节和只在对话里说过的约束可能在摘要里丢失(根目录 `CLAUDE.md` 会在压缩后重新读取,不受影响)。但它不会告诉你——它会**装作记得**,靠编造填空。 **出坑** ``` +/context # 查看上下文占用 /compact # 主动压缩上下文,保留关键决策 ``` 或者直接**开新对话**,把重要信息写进 `CLAUDE.md` 传递。 @@ -141,7 +142,7 @@ Claude 有时会**基于代码推断**测试应该通过,而不是真跑了测 **预防** - `CLAUDE.md` 控制在 200 行以内 -- 大项目拆到 `.claude/rules/` 用 `globs` 按文件类型加载 +- 大项目拆到 `.claude/rules/`,在 frontmatter 里用 `paths:` 按文件路径加载 - 关键规则加 `` 标签 - 用 "必须 / 禁止" 代替 "建议 / 尽量":