mirror of
https://github.com/cexll/myclaude.git
synced 2026-02-05 02:30:26 +08:00
Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71305da77e | ||
|
|
c4021cf58a | ||
|
|
9a18a03061 | ||
|
|
b5183c7711 | ||
|
|
3fab18a6bb | ||
|
|
12af992d8c | ||
|
|
bbd2f50c38 | ||
|
|
3f7652f992 | ||
|
|
2cbe36b532 | ||
|
|
fdb152872d | ||
|
|
916b970665 |
@@ -226,6 +226,39 @@
|
||||
"skills": [
|
||||
"./SKILL.md"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "dev-workflow",
|
||||
"source": "./dev-workflow/",
|
||||
"description": "Minimal lightweight development workflow with requirements clarification, parallel codex execution, and mandatory 90% test coverage",
|
||||
"version": "1.0.0",
|
||||
"author": {
|
||||
"name": "Claude Code Dev Workflows",
|
||||
"url": "https://github.com/cexll/myclaude"
|
||||
},
|
||||
"homepage": "https://github.com/cexll/myclaude",
|
||||
"repository": "https://github.com/cexll/myclaude",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"dev",
|
||||
"workflow",
|
||||
"codex",
|
||||
"testing",
|
||||
"coverage",
|
||||
"concurrent",
|
||||
"lightweight"
|
||||
],
|
||||
"category": "workflows",
|
||||
"strict": false,
|
||||
"commands": [
|
||||
"./commands/dev.md"
|
||||
],
|
||||
"agents": [
|
||||
"./agents/dev-plan-generator.md"
|
||||
],
|
||||
"skills": [
|
||||
"../skills/codex/SKILL.md"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://claude.ai/code)
|
||||
[](https://github.com/cexll/myclaude)
|
||||
[](https://github.com/cexll/myclaude)
|
||||
[](https://docs.claude.com/en/docs/claude-code/plugins)
|
||||
|
||||
> Enterprise-grade agile development automation with AI-powered multi-agent orchestration
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://claude.ai/code)
|
||||
[](https://github.com/cexll/myclaude)
|
||||
[](https://github.com/cexll/myclaude)
|
||||
[](https://docs.claude.com/en/docs/claude-code/plugins)
|
||||
|
||||
> 企业级敏捷开发自动化与 AI 驱动的多智能体编排
|
||||
|
||||
@@ -1,163 +1,163 @@
|
||||
# /dev - 极简开发工作流
|
||||
# /dev - Minimal Dev Workflow
|
||||
|
||||
## 概述
|
||||
## Overview
|
||||
|
||||
全新设计的轻量级开发工作流,无历史包袱,专注快速交付高质量代码。
|
||||
A freshly designed lightweight development workflow with no legacy baggage, focused on delivering high-quality code fast.
|
||||
|
||||
## 工作流程
|
||||
## Flow
|
||||
|
||||
```
|
||||
/dev 触发
|
||||
/dev trigger
|
||||
↓
|
||||
AskUserQuestion(需求澄清)
|
||||
AskUserQuestion (requirements clarification)
|
||||
↓
|
||||
Codex 分析(提取要点和任务)
|
||||
Codex analysis (extract key points and tasks)
|
||||
↓
|
||||
develop-doc-generator(生成开发文档)
|
||||
develop-doc-generator (create dev doc)
|
||||
↓
|
||||
Codex 并发开发(2-5个任务)
|
||||
Codex concurrent development (2–5 tasks)
|
||||
↓
|
||||
Codex 测试验证(≥90%覆盖率)
|
||||
Codex testing & verification (≥90% coverage)
|
||||
↓
|
||||
完成(生成总结)
|
||||
Done (generate summary)
|
||||
```
|
||||
|
||||
## 6个步骤
|
||||
## The 6 Steps
|
||||
|
||||
### 1. 需求澄清
|
||||
- 使用 **AskUserQuestion** 直接问用户
|
||||
- 无评分系统,无复杂逻辑
|
||||
- 2-3 轮问答直到需求明确
|
||||
### 1. Clarify Requirements
|
||||
- Use **AskUserQuestion** to ask the user directly
|
||||
- No scoring system, no complex logic
|
||||
- 2–3 rounds of Q&A until the requirement is clear
|
||||
|
||||
### 2. Codex 分析
|
||||
- 调用 codex 分析需求
|
||||
- 提取:核心功能、技术要点、任务列表(2-5个)
|
||||
- 输出结构化分析结果
|
||||
### 2. Codex Analysis
|
||||
- Call codex to analyze the request
|
||||
- Extract: core functions, technical points, task list (2–5 items)
|
||||
- Output a structured analysis
|
||||
|
||||
### 3. 生成开发文档
|
||||
- 调用 **develop-doc-generator** agent
|
||||
- 生成 `dev-plan.md`(单一开发文档)
|
||||
- 包含:任务分解、文件范围、依赖关系、测试命令
|
||||
### 3. Generate Dev Doc
|
||||
- Call the **develop-doc-generator** agent
|
||||
- Produce a single `dev-plan.md`
|
||||
- Include: task breakdown, file scope, dependencies, test commands
|
||||
|
||||
### 4. 并发开发
|
||||
- 基于 dev-plan.md 的任务列表
|
||||
- 无依赖任务 → 并发执行
|
||||
- 有冲突任务 → 串行执行
|
||||
### 4. Concurrent Development
|
||||
- Work from the task list in dev-plan.md
|
||||
- Independent tasks → run in parallel
|
||||
- Conflicting tasks → run serially
|
||||
|
||||
### 5. 测试验证
|
||||
- 每个 codex 任务自己:
|
||||
- 实现功能
|
||||
- 编写测试
|
||||
- 运行覆盖率
|
||||
- 报告结果(≥90%)
|
||||
### 5. Testing & Verification
|
||||
- Each codex task:
|
||||
- Implements the feature
|
||||
- Writes tests
|
||||
- Runs coverage
|
||||
- Reports results (≥90%)
|
||||
|
||||
### 6. 完成
|
||||
- 汇总任务状态
|
||||
- 记录覆盖率
|
||||
### 6. Complete
|
||||
- Summarize task status
|
||||
- Record coverage
|
||||
|
||||
## 使用方法
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
/dev "实现用户登录功能,支持邮箱和密码验证"
|
||||
/dev "Implement user login with email + password"
|
||||
```
|
||||
|
||||
**无选项**,流程固定,开箱即用。
|
||||
**No options**, fixed workflow, works out of the box.
|
||||
|
||||
## 输出结构
|
||||
## Output Structure
|
||||
|
||||
```
|
||||
.claude/specs/{feature_name}/
|
||||
├── dev-plan.md # 开发文档(agent生成)
|
||||
└── dev-plan.md # Dev document generated by agent
|
||||
```
|
||||
|
||||
仅 2 个文件,极简清晰。
|
||||
Only one file—minimal and clear.
|
||||
|
||||
## 核心组件
|
||||
## Core Components
|
||||
|
||||
### 工具
|
||||
- **AskUserQuestion**:交互式需求澄清
|
||||
- **codex**:分析、开发、测试
|
||||
- **develop-doc-generator**:生成开发文档(subagent,节省上下文)
|
||||
### Tools
|
||||
- **AskUserQuestion**: interactive requirement clarification
|
||||
- **codex**: analysis, development, testing
|
||||
- **develop-doc-generator**: generate dev doc (subagent, saves context)
|
||||
|
||||
## 核心特性
|
||||
## Key Features
|
||||
|
||||
### ✅ 全新设计
|
||||
- 无历史项目残留
|
||||
- 无复杂评分逻辑
|
||||
- 无多余抽象层
|
||||
### ✅ Fresh Design
|
||||
- No legacy project residue
|
||||
- No complex scoring logic
|
||||
- No extra abstraction layers
|
||||
|
||||
### ✅ 极简编排
|
||||
- orchestrator 直接控制流程
|
||||
- 只用 3 个工具/组件
|
||||
- 步骤清晰易懂
|
||||
### ✅ Minimal Orchestration
|
||||
- Orchestrator controls the flow directly
|
||||
- Only three tools/components
|
||||
- Steps are straightforward
|
||||
|
||||
### ✅ 并发能力
|
||||
- 2-5 个任务并行
|
||||
- 自动检测依赖和冲突
|
||||
- codex 独立执行
|
||||
### ✅ Concurrency
|
||||
- 2–5 tasks in parallel
|
||||
- Auto-detect dependencies and conflicts
|
||||
- Codex executes independently
|
||||
|
||||
### ✅ 质量保证
|
||||
- 强制 90% 覆盖率
|
||||
- codex 自己测试和验证
|
||||
- 失败自动重试
|
||||
### ✅ Quality Assurance
|
||||
- Enforces 90% coverage
|
||||
- Codex tests and verifies its own work
|
||||
- Automatic retry on failure
|
||||
|
||||
## 示例
|
||||
## Example
|
||||
|
||||
```bash
|
||||
# 触发
|
||||
/dev "添加用户登录功能"
|
||||
# Trigger
|
||||
/dev "Add user login feature"
|
||||
|
||||
# 步骤 1: 需求澄清
|
||||
Q: 支持哪些登录方式?
|
||||
A: 邮箱 + 密码
|
||||
Q: 需要记住登录状态吗?
|
||||
A: 是,使用 JWT token
|
||||
# Step 1: Clarify requirements
|
||||
Q: What login methods are supported?
|
||||
A: Email + password
|
||||
Q: Should login be remembered?
|
||||
A: Yes, use JWT token
|
||||
|
||||
# 步骤 2: Codex 分析
|
||||
输出:
|
||||
- 核心功能:邮箱密码登录 + JWT认证
|
||||
- 任务 1:后端 API
|
||||
- 任务 2:密码加密
|
||||
- 任务 3:前端表单
|
||||
# Step 2: Codex analysis
|
||||
Output:
|
||||
- Core: email/password login + JWT auth
|
||||
- Task 1: Backend API
|
||||
- Task 2: Password hashing
|
||||
- Task 3: Frontend form
|
||||
|
||||
# 步骤 3: 生成文档
|
||||
dev-plan.md 已生成 ✓
|
||||
# Step 3: Generate doc
|
||||
dev-plan.md generated ✓
|
||||
|
||||
# 步骤 4-5: 并发开发
|
||||
[task-1] 后端API → 测试 → 92% ✓
|
||||
[task-2] 密码加密 → 测试 → 95% ✓
|
||||
[task-3] 前端表单 → 测试 → 91% ✓
|
||||
# Step 4-5: Concurrent development
|
||||
[task-1] Backend API → tests → 92% ✓
|
||||
[task-2] Password hashing → tests → 95% ✓
|
||||
[task-3] Frontend form → tests → 91% ✓
|
||||
```
|
||||
|
||||
## 目录结构
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
dev-workflow/
|
||||
├── README.md # 本文档
|
||||
├── README.md # This doc
|
||||
├── commands/
|
||||
│ └── dev.md # 工作流定义
|
||||
│ └── dev.md # Workflow definition
|
||||
└── agents/
|
||||
└── develop-doc-generator.md # 文档生成器
|
||||
└── develop-doc-generator.md # Doc generator
|
||||
```
|
||||
|
||||
极简结构,只有 3 个文件。
|
||||
Minimal structure, only three files.
|
||||
|
||||
## 适用场景
|
||||
## When to Use
|
||||
|
||||
✅ **适合**:
|
||||
- 任何规模的功能开发
|
||||
- 需要快速迭代
|
||||
- 需要高测试覆盖率
|
||||
- 希望并发提速
|
||||
✅ **Good for**:
|
||||
- Any feature size
|
||||
- Fast iterations
|
||||
- High test coverage needs
|
||||
- Wanting concurrent speed-up
|
||||
|
||||
## 设计原则
|
||||
## Design Principles
|
||||
|
||||
1. **KISS**:保持简单愚蠢
|
||||
2. **即用即抛**:无持久化配置
|
||||
3. **质量优先**:强制 90% 覆盖率
|
||||
4. **并发优先**:充分利用 codex 能力
|
||||
5. **无历史包袱**:全新设计,不受其他项目影响
|
||||
1. **KISS**: keep it simple
|
||||
2. **Disposable**: no persistent config
|
||||
3. **Quality first**: enforce 90% coverage
|
||||
4. **Concurrency first**: leverage codex
|
||||
5. **No legacy baggage**: clean-slate design
|
||||
|
||||
---
|
||||
|
||||
**哲学**:像 Linus 一样对复杂度零容忍,交付能立刻用的最小方案。
|
||||
**Philosophy**: zero tolerance for complexity—ship the smallest usable solution, like Linus would.
|
||||
|
||||
@@ -42,7 +42,7 @@ You are the /dev Workflow Orchestrator, an expert development workflow manager s
|
||||
- Extract core functionality, technical key points, and 2-5 parallelizable tasks with full metadata
|
||||
|
||||
- **Step 3: Generate Development Documentation**
|
||||
- Use Task tool to invoke develop-doc-generator:
|
||||
- invoke agent dev-plan-generator:
|
||||
```
|
||||
基于以下分析结果生成开发文档:
|
||||
|
||||
|
||||
@@ -14,27 +14,47 @@ Execute Codex CLI commands and parse structured JSON responses. Supports file re
|
||||
- Complex code analysis requiring deep understanding
|
||||
- Large-scale refactoring across multiple files
|
||||
- Automated code generation with safety controls
|
||||
- Tasks requiring specialized reasoning models (gpt-5.1, gpt-5.1-codex)
|
||||
|
||||
## Usage
|
||||
|
||||
**Mandatory**: Run every automated invocation through the Bash tool in the foreground with the command below, keeping the `timeout` parameter fixed at `7200000` milliseconds (do not change it or use any other entry point).
|
||||
**Mandatory**: Run every automated invocation through the Bash tool in the foreground with **HEREDOC syntax** to avoid shell quoting issues, keeping the `timeout` parameter fixed at `7200000` milliseconds (do not change it or use any other entry point).
|
||||
|
||||
```bash
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py - [working_dir] <<'EOF'
|
||||
<task content here>
|
||||
EOF
|
||||
```
|
||||
|
||||
**Optional methods** (direct execution or via Python):
|
||||
**Why HEREDOC?** Tasks often contain code blocks, nested quotes, shell metacharacters (`$`, `` ` ``, `\`), and multiline text. HEREDOC (Here Document) syntax passes these safely without shell interpretation, eliminating quote-escaping nightmares.
|
||||
|
||||
**Foreground only (no background/BashOutput)**: Never set `background: true`, never accept Claude's "Running in the background" mode, and avoid `BashOutput` streaming loops. Keep a single foreground Bash call per Codex task; if work might be long, split it into smaller foreground runs instead of offloading to background execution.
|
||||
|
||||
**Simple tasks** (backward compatibility):
|
||||
For simple single-line tasks without special characters, you can still use direct quoting:
|
||||
```bash
|
||||
~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
# or
|
||||
python3 ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "simple task here" [working_dir]
|
||||
```
|
||||
|
||||
Resume a session:
|
||||
**Resume a session with HEREDOC:**
|
||||
```bash
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py resume <session_id> "<task>" [model] [working_dir]
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py resume <session_id> - [working_dir] <<'EOF'
|
||||
<task content>
|
||||
EOF
|
||||
```
|
||||
|
||||
**Cross-platform notes:**
|
||||
- **Bash/Zsh**: Use `<<'EOF'` (single quotes prevent variable expansion)
|
||||
- **PowerShell 5.1+**: Use `@'` and `'@` (here-string syntax)
|
||||
```powershell
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py - @'
|
||||
task content
|
||||
'@
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
- **CODEX_TIMEOUT**: Override timeout in milliseconds (default: 7200000 = 2 hours)
|
||||
- Example: `export CODEX_TIMEOUT=3600000` for 1 hour
|
||||
|
||||
## Timeout Control
|
||||
|
||||
- **Built-in**: Script enforces 2-hour timeout by default
|
||||
@@ -46,9 +66,6 @@ uv run ~/.claude/skills/codex/scripts/codex.py resume <session_id> "<task>" [mod
|
||||
### Parameters
|
||||
|
||||
- `task` (required): Task description, supports `@file` references
|
||||
- `model` (optional): Model to use (default: gpt-5.1-codex)
|
||||
- `gpt-5.1-codex`: Default, optimized for code
|
||||
- `gpt-5.1`: Fast general purpose
|
||||
- `working_dir` (optional): Working directory (default: current)
|
||||
|
||||
### Return Format
|
||||
@@ -66,64 +83,86 @@ Error format (stderr):
|
||||
ERROR: Error message
|
||||
```
|
||||
|
||||
Return only the final agent message and session ID—do not paste raw `BashOutput` logs or background-task chatter into the conversation.
|
||||
|
||||
### Invocation Pattern
|
||||
|
||||
All automated executions may only invoke `uv run ~/.claude/skills/codex/scripts/codex.py "<task>" ...` through the Bash tool in the foreground, and the `timeout` must remain fixed at `7200000` (non-negotiable):
|
||||
All automated executions must use HEREDOC syntax through the Bash tool in the foreground, with `timeout` fixed at `7200000` (non-negotiable):
|
||||
|
||||
```
|
||||
Bash tool parameters:
|
||||
- command: uv run ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
- command: uv run ~/.claude/skills/codex/scripts/codex.py - [working_dir] <<'EOF'
|
||||
<task content>
|
||||
EOF
|
||||
- timeout: 7200000
|
||||
- description: <brief description of the task>
|
||||
```
|
||||
|
||||
Run every call in the foreground—never append `&` to background it—so logs and errors stay visible for timely interruption or diagnosis.
|
||||
|
||||
Alternatives:
|
||||
```
|
||||
# Direct execution (simplest)
|
||||
- command: ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
|
||||
# Using python3
|
||||
- command: python3 ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
```
|
||||
**Important:** Use HEREDOC (`<<'EOF'`) for all but the simplest tasks. This prevents shell interpretation of quotes, variables, and special characters.
|
||||
|
||||
### Examples
|
||||
|
||||
**Basic code analysis:**
|
||||
```bash
|
||||
# Recommended: via uv run (auto-manages Python environment)
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "explain @src/main.ts"
|
||||
# Recommended: via uv run with HEREDOC (handles any special characters)
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py - <<'EOF'
|
||||
explain @src/main.ts
|
||||
EOF
|
||||
# timeout: 7200000
|
||||
|
||||
# Alternative: direct execution
|
||||
~/.claude/skills/codex/scripts/codex.py "explain @src/main.ts"
|
||||
# Alternative: simple direct quoting (if task is simple)
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "explain @src/main.ts"
|
||||
```
|
||||
|
||||
**Refactoring with specific model:**
|
||||
**Refactoring with multiline instructions:**
|
||||
```bash
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "refactor @src/utils for performance" "gpt-5.1-codex"
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py - <<'EOF'
|
||||
refactor @src/utils for performance:
|
||||
- Extract duplicate code into helpers
|
||||
- Use memoization for expensive calculations
|
||||
- Add inline comments for non-obvious logic
|
||||
EOF
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**Multi-file analysis:**
|
||||
```bash
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "analyze @. and find security issues" "gpt-5.1-codex" "/path/to/project"
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py - "/path/to/project" <<'EOF'
|
||||
analyze @. and find security issues:
|
||||
1. Check for SQL injection vulnerabilities
|
||||
2. Identify XSS risks in templates
|
||||
3. Review authentication/authorization logic
|
||||
4. Flag hardcoded credentials or secrets
|
||||
EOF
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**Resume previous session:**
|
||||
```bash
|
||||
# First session
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "add comments to @utils.js" "gpt-5.1-codex"
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py - <<'EOF'
|
||||
add comments to @utils.js explaining the caching logic
|
||||
EOF
|
||||
# Output includes: SESSION_ID: 019a7247-ac9d-71f3-89e2-a823dbd8fd14
|
||||
|
||||
# Continue the conversation
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py resume 019a7247-ac9d-71f3-89e2-a823dbd8fd14 "now add type hints"
|
||||
# Continue the conversation with more context
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py resume 019a7247-ac9d-71f3-89e2-a823dbd8fd14 - <<'EOF'
|
||||
now add TypeScript type hints and handle edge cases where cache is null
|
||||
EOF
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**Using python3 directly (alternative):**
|
||||
**Task with code snippets and special characters:**
|
||||
```bash
|
||||
python3 ~/.claude/skills/codex/scripts/codex.py "your task here"
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py - <<'EOF'
|
||||
Fix the bug in @app.js where the regex /\d+/ doesn't match "123"
|
||||
The current code is:
|
||||
const re = /\d+/;
|
||||
if (re.test(input)) { ... }
|
||||
Add proper escaping and handle $variables correctly.
|
||||
EOF
|
||||
```
|
||||
|
||||
### Large Task Protocol
|
||||
@@ -134,8 +173,8 @@ python3 ~/.claude/skills/codex/scripts/codex.py "your task here"
|
||||
|
||||
| ID | Description | Scope | Dependencies | Tests | Command |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| T1 | Review @spec.md to extract requirements | docs/, @spec.md | None | None | uv run ~/.claude/skills/codex/scripts/codex.py "analyze requirements @spec.md" |
|
||||
| T2 | Implement the module and add test cases | src/module | T1 | npm test -- --runInBand | uv run ~/.claude/skills/codex/scripts/codex.py "implement and test @src/module" |
|
||||
| T1 | Review @spec.md to extract requirements | docs/, @spec.md | None | None | `uv run ~/.claude/skills/codex/scripts/codex.py - <<'EOF'`<br/>`analyze requirements @spec.md`<br/>`EOF` |
|
||||
| T2 | Implement the module and add test cases | src/module | T1 | npm test -- --runInBand | `uv run ~/.claude/skills/codex/scripts/codex.py - <<'EOF'`<br/>`implement and test @src/module`<br/>`EOF` |
|
||||
|
||||
## Notes
|
||||
|
||||
|
||||
@@ -8,10 +8,14 @@ Codex CLI wrapper with cross-platform support and session management.
|
||||
**FIXED**: Auto-detect long inputs and use stdin mode to avoid shell argument issues.
|
||||
|
||||
Usage:
|
||||
New session: uv run codex.py "task" [model] [workdir]
|
||||
Resume: uv run codex.py resume <session_id> "task" [model] [workdir]
|
||||
New session: uv run codex.py "task" [workdir]
|
||||
Stdin mode: uv run codex.py - [workdir]
|
||||
Resume: uv run codex.py resume <session_id> "task" [workdir]
|
||||
Resume stdin: uv run codex.py resume <session_id> - [workdir]
|
||||
Alternative: python3 codex.py "task"
|
||||
Direct exec: ./codex.py "task"
|
||||
|
||||
Model configuration: Set CODEX_MODEL environment variable (default: gpt-5.1-codex)
|
||||
"""
|
||||
import subprocess
|
||||
import json
|
||||
@@ -19,7 +23,7 @@ import sys
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
DEFAULT_MODEL = 'gpt-5.1-codex'
|
||||
DEFAULT_MODEL = os.environ.get('CODEX_MODEL', 'gpt-5.1-codex')
|
||||
DEFAULT_WORKDIR = '.'
|
||||
DEFAULT_TIMEOUT = 7200 # 2 hours in seconds
|
||||
FORCE_KILL_DELAY = 5
|
||||
@@ -78,21 +82,23 @@ def parse_args():
|
||||
if len(sys.argv) < 4:
|
||||
log_error('Resume mode requires: resume <session_id> <task>')
|
||||
sys.exit(1)
|
||||
task_arg = sys.argv[3]
|
||||
return {
|
||||
'mode': 'resume',
|
||||
'session_id': sys.argv[2],
|
||||
'task': sys.argv[3],
|
||||
'model': sys.argv[4] if len(sys.argv) > 4 else DEFAULT_MODEL,
|
||||
'workdir': sys.argv[5] if len(sys.argv) > 5 else DEFAULT_WORKDIR
|
||||
}
|
||||
else:
|
||||
return {
|
||||
'mode': 'new',
|
||||
'task': sys.argv[1],
|
||||
'model': sys.argv[2] if len(sys.argv) > 2 else DEFAULT_MODEL,
|
||||
'workdir': sys.argv[3] if len(sys.argv) > 3 else DEFAULT_WORKDIR
|
||||
'task': task_arg,
|
||||
'explicit_stdin': task_arg == '-',
|
||||
'workdir': sys.argv[4] if len(sys.argv) > 4 else DEFAULT_WORKDIR,
|
||||
}
|
||||
|
||||
task_arg = sys.argv[1]
|
||||
return {
|
||||
'mode': 'new',
|
||||
'task': task_arg,
|
||||
'explicit_stdin': task_arg == '-',
|
||||
'workdir': sys.argv[2] if len(sys.argv) > 2 else DEFAULT_WORKDIR,
|
||||
}
|
||||
|
||||
|
||||
def read_piped_task() -> Optional[str]:
|
||||
"""
|
||||
@@ -102,9 +108,16 @@ def read_piped_task() -> Optional[str]:
|
||||
"""
|
||||
stdin = sys.stdin
|
||||
if stdin is None or stdin.isatty():
|
||||
log_info("Stdin is tty or None, skipping pipe read")
|
||||
return None
|
||||
log_info("Reading from stdin pipe...")
|
||||
data = stdin.read()
|
||||
return data if data else None
|
||||
if not data:
|
||||
log_info("Stdin pipe returned empty data")
|
||||
return None
|
||||
|
||||
log_info(f"Read {len(data)} bytes from stdin pipe")
|
||||
return data
|
||||
|
||||
|
||||
def should_stream_via_stdin(task_text: str, piped: bool) -> bool:
|
||||
@@ -137,6 +150,7 @@ def build_codex_args(params: dict, target_arg: str) -> list:
|
||||
if params['mode'] == 'resume':
|
||||
return [
|
||||
'codex', 'e',
|
||||
'-m', DEFAULT_MODEL,
|
||||
'--skip-git-repo-check',
|
||||
'--json',
|
||||
'resume',
|
||||
@@ -146,7 +160,7 @@ def build_codex_args(params: dict, target_arg: str) -> list:
|
||||
else:
|
||||
base_args = [
|
||||
'codex', 'e',
|
||||
'-m', params['model'],
|
||||
'-m', DEFAULT_MODEL,
|
||||
'--dangerously-bypass-approvals-and-sandbox',
|
||||
'--skip-git-repo-check',
|
||||
'-C', params['workdir'],
|
||||
@@ -168,6 +182,7 @@ def run_codex_process(codex_args, task_text: str, use_stdin: bool, timeout_sec:
|
||||
|
||||
try:
|
||||
# 启动 codex 子进程(文本模式管道)
|
||||
log_info(f"Starting codex with args: {' '.join(codex_args[:5])}...")
|
||||
process = subprocess.Popen(
|
||||
codex_args,
|
||||
stdin=subprocess.PIPE if use_stdin else None,
|
||||
@@ -176,17 +191,23 @@ def run_codex_process(codex_args, task_text: str, use_stdin: bool, timeout_sec:
|
||||
text=True,
|
||||
bufsize=1,
|
||||
)
|
||||
log_info(f"Process started with PID: {process.pid}")
|
||||
|
||||
# 如果使用 stdin 模式,写入任务到 stdin 并关闭
|
||||
if use_stdin and process.stdin is not None:
|
||||
log_info(f"Writing {len(task_text)} chars to stdin...")
|
||||
process.stdin.write(task_text)
|
||||
process.stdin.flush() # 强制刷新缓冲区,避免大任务死锁
|
||||
process.stdin.close()
|
||||
log_info("Stdin closed")
|
||||
|
||||
# 逐行解析 JSON 输出
|
||||
if process.stdout is None:
|
||||
log_error('Codex stdout pipe not available')
|
||||
sys.exit(1)
|
||||
|
||||
log_info("Reading stdout...")
|
||||
|
||||
for line in process.stdout:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
@@ -247,19 +268,34 @@ def run_codex_process(codex_args, task_text: str, use_stdin: bool, timeout_sec:
|
||||
|
||||
|
||||
def main():
|
||||
log_info("Script started")
|
||||
params = parse_args()
|
||||
log_info(f"Parsed args: mode={params['mode']}, task_len={len(params['task'])}")
|
||||
timeout_sec = resolve_timeout()
|
||||
log_info(f"Timeout: {timeout_sec}s")
|
||||
|
||||
piped_task = read_piped_task()
|
||||
piped = piped_task is not None
|
||||
task_text = piped_task if piped else params['task']
|
||||
explicit_stdin = params.get('explicit_stdin', False)
|
||||
|
||||
use_stdin = should_stream_via_stdin(task_text, piped)
|
||||
if explicit_stdin:
|
||||
log_info("Explicit stdin mode: reading task from stdin")
|
||||
task_text = sys.stdin.read()
|
||||
if not task_text:
|
||||
log_error("Explicit stdin mode requires task input from stdin")
|
||||
sys.exit(1)
|
||||
piped = not sys.stdin.isatty()
|
||||
else:
|
||||
piped_task = read_piped_task()
|
||||
piped = piped_task is not None
|
||||
task_text = piped_task if piped else params['task']
|
||||
|
||||
use_stdin = explicit_stdin or should_stream_via_stdin(task_text, piped)
|
||||
|
||||
if use_stdin:
|
||||
reasons = []
|
||||
if piped:
|
||||
reasons.append('piped input')
|
||||
if explicit_stdin:
|
||||
reasons.append('explicit "-"')
|
||||
if '\n' in task_text:
|
||||
reasons.append('newline')
|
||||
if '\\' in task_text:
|
||||
|
||||
@@ -17,31 +17,32 @@ Execute Gemini CLI commands with support for multiple models and flexible prompt
|
||||
- Alternative perspective on code problems
|
||||
|
||||
## Usage
|
||||
|
||||
**推荐方式**(使用 uv run,自动管理 Python 环境):
|
||||
**Mandatory**: Run via uv with fixed timeout 7200000ms (foreground):
|
||||
```bash
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py -m <model> -p "<prompt>" [working_dir]
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py "<prompt>" [working_dir]
|
||||
```
|
||||
|
||||
**备选方式**(直接执行或使用 Python):
|
||||
**Optional** (direct execution or using Python):
|
||||
```bash
|
||||
~/.claude/skills/gemini/scripts/gemini.py -m <model> -p "<prompt>" [working_dir]
|
||||
# 或
|
||||
python3 ~/.claude/skills/gemini/scripts/gemini.py -m <model> -p "<prompt>" [working_dir]
|
||||
~/.claude/skills/gemini/scripts/gemini.py "<prompt>" [working_dir]
|
||||
# or
|
||||
python3 ~/.claude/skills/gemini/scripts/gemini.py "<prompt>" [working_dir]
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- **GEMINI_MODEL**: Configure model (default: `gemini-3-pro-preview`)
|
||||
- Example: `export GEMINI_MODEL=gemini-3`
|
||||
|
||||
## Timeout Control
|
||||
|
||||
- **Built-in**: Script enforces 2-hour timeout by default
|
||||
- **Override**: Set `GEMINI_TIMEOUT` environment variable (in milliseconds)
|
||||
- **Bash tool**: Always set `timeout: 7200000` parameter for double protection
|
||||
- **Fixed**: 7200000 milliseconds (2 hours), immutable
|
||||
- **Bash tool**: Always set `timeout: 7200000` for double protection
|
||||
|
||||
### Parameters
|
||||
|
||||
- `-m, --model` (optional): Model to use (default: gemini-3-pro-preview)
|
||||
- `gemini-3-pro-preview`: Latest flagship model
|
||||
- `-p, --prompt` (required): Task prompt or question
|
||||
- `working_dir` (optional): Working directory (default: current)
|
||||
- `prompt` (required): Task prompt or question
|
||||
- `working_dir` (optional): Working directory (default: current directory)
|
||||
|
||||
### Return Format
|
||||
|
||||
@@ -63,7 +64,7 @@ When calling via Bash tool, always include the timeout parameter:
|
||||
|
||||
```yaml
|
||||
Bash tool parameters:
|
||||
- command: uv run ~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "<prompt>"
|
||||
- command: uv run ~/.claude/skills/gemini/scripts/gemini.py "<prompt>"
|
||||
- timeout: 7200000
|
||||
- description: <brief description of the task>
|
||||
```
|
||||
@@ -72,10 +73,10 @@ Alternatives:
|
||||
|
||||
```yaml
|
||||
# Direct execution (simplest)
|
||||
- command: ~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "<prompt>"
|
||||
- command: ~/.claude/skills/gemini/scripts/gemini.py "<prompt>"
|
||||
|
||||
# Using python3
|
||||
- command: python3 ~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "<prompt>"
|
||||
- command: python3 ~/.claude/skills/gemini/scripts/gemini.py "<prompt>"
|
||||
```
|
||||
|
||||
### Examples
|
||||
@@ -83,39 +84,28 @@ Alternatives:
|
||||
**Basic query:**
|
||||
|
||||
```bash
|
||||
# Recommended: via uv run
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "explain quantum computing"
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py "explain quantum computing"
|
||||
# timeout: 7200000
|
||||
|
||||
# Alternative: direct execution
|
||||
~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "explain quantum computing"
|
||||
```
|
||||
|
||||
**Code analysis:**
|
||||
|
||||
```bash
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "review this code for security issues: $(cat app.py)"
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py "review this code for security issues: $(cat app.py)"
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**With specific working directory:**
|
||||
|
||||
```bash
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "analyze project structure" "/path/to/project"
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**Using fast model:**
|
||||
|
||||
```bash
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "quick code suggestion"
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py "analyze project structure" "/path/to/project"
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**Using python3 directly (alternative):**
|
||||
|
||||
```bash
|
||||
python3 ~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "your prompt here"
|
||||
python3 ~/.claude/skills/gemini/scripts/gemini.py "your prompt here"
|
||||
```
|
||||
|
||||
## Notes
|
||||
@@ -126,5 +116,5 @@ python3 ~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "yo
|
||||
- Cross-platform compatible (Windows/macOS/Linux)
|
||||
- PEP 723 compliant (inline script metadata)
|
||||
- Requires Gemini CLI installed and authenticated
|
||||
- Supports all Gemini model variants
|
||||
- Supports all Gemini model variants (configure via `GEMINI_MODEL` environment variable)
|
||||
- Output is streamed directly from Gemini CLI
|
||||
|
||||
@@ -7,18 +7,18 @@
|
||||
Gemini CLI wrapper with cross-platform support.
|
||||
|
||||
Usage:
|
||||
uv run gemini.py -m <model> -p "<prompt>" [workdir]
|
||||
python3 gemini.py -m <model> -p "<prompt>"
|
||||
./gemini.py -m gemini-3-pro-preview -p "your prompt"
|
||||
uv run gemini.py "<prompt>" [workdir]
|
||||
python3 gemini.py "<prompt>"
|
||||
./gemini.py "your prompt"
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
import argparse
|
||||
|
||||
DEFAULT_MODEL = 'gemini-3-pro-preview'
|
||||
DEFAULT_MODEL = os.environ.get('GEMINI_MODEL', 'gemini-3-pro-preview')
|
||||
DEFAULT_WORKDIR = '.'
|
||||
DEFAULT_TIMEOUT = 7200 # 2 hours in seconds
|
||||
TIMEOUT_MS = 7_200_000 # 固定 2 小时,毫秒
|
||||
DEFAULT_TIMEOUT = TIMEOUT_MS // 1000
|
||||
FORCE_KILL_DELAY = 5
|
||||
|
||||
|
||||
@@ -32,76 +32,56 @@ def log_warn(message: str):
|
||||
sys.stderr.write(f"WARN: {message}\n")
|
||||
|
||||
|
||||
def resolve_timeout() -> int:
|
||||
"""解析超时配置(秒)"""
|
||||
raw = os.environ.get('GEMINI_TIMEOUT', '')
|
||||
if not raw:
|
||||
return DEFAULT_TIMEOUT
|
||||
|
||||
try:
|
||||
parsed = int(raw)
|
||||
if parsed <= 0:
|
||||
log_warn(f"Invalid GEMINI_TIMEOUT '{raw}', falling back to {DEFAULT_TIMEOUT}s")
|
||||
return DEFAULT_TIMEOUT
|
||||
# 环境变量是毫秒,转换为秒
|
||||
return parsed // 1000 if parsed > 10000 else parsed
|
||||
except ValueError:
|
||||
log_warn(f"Invalid GEMINI_TIMEOUT '{raw}', falling back to {DEFAULT_TIMEOUT}s")
|
||||
return DEFAULT_TIMEOUT
|
||||
def log_info(message: str):
|
||||
"""输出信息到 stderr"""
|
||||
sys.stderr.write(f"INFO: {message}\n")
|
||||
|
||||
|
||||
def parse_args():
|
||||
"""解析命令行参数"""
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Gemini CLI wrapper for Claude Code integration',
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter
|
||||
)
|
||||
parser.add_argument(
|
||||
'-m', '--model',
|
||||
default=DEFAULT_MODEL,
|
||||
help=f'Gemini model to use (default: {DEFAULT_MODEL})'
|
||||
)
|
||||
parser.add_argument(
|
||||
'-p', '--prompt',
|
||||
required=True,
|
||||
help='Prompt to send to Gemini'
|
||||
)
|
||||
parser.add_argument(
|
||||
'workdir',
|
||||
nargs='?',
|
||||
default=DEFAULT_WORKDIR,
|
||||
help='Working directory (default: current directory)'
|
||||
)
|
||||
"""解析位置参数"""
|
||||
if len(sys.argv) < 2:
|
||||
log_error('Prompt required')
|
||||
sys.exit(1)
|
||||
|
||||
return parser.parse_args()
|
||||
return {
|
||||
'prompt': sys.argv[1],
|
||||
'workdir': sys.argv[2] if len(sys.argv) > 2 else DEFAULT_WORKDIR
|
||||
}
|
||||
|
||||
|
||||
def build_gemini_args(args) -> list:
|
||||
"""构建 gemini CLI 参数"""
|
||||
return [
|
||||
'gemini',
|
||||
'-m', args.model,
|
||||
'-p', args.prompt
|
||||
'-m', DEFAULT_MODEL,
|
||||
'-p', args['prompt']
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
log_info('Script started')
|
||||
args = parse_args()
|
||||
log_info(f"Prompt length: {len(args['prompt'])}")
|
||||
log_info(f"Working dir: {args['workdir']}")
|
||||
gemini_args = build_gemini_args(args)
|
||||
timeout_sec = resolve_timeout()
|
||||
timeout_sec = DEFAULT_TIMEOUT
|
||||
log_info(f"Timeout: {timeout_sec}s")
|
||||
|
||||
# 如果指定了工作目录,切换到该目录
|
||||
if args.workdir != DEFAULT_WORKDIR:
|
||||
if args['workdir'] != DEFAULT_WORKDIR:
|
||||
try:
|
||||
os.chdir(args.workdir)
|
||||
os.chdir(args['workdir'])
|
||||
except FileNotFoundError:
|
||||
log_error(f"Working directory not found: {args.workdir}")
|
||||
log_error(f"Working directory not found: {args['workdir']}")
|
||||
sys.exit(1)
|
||||
except PermissionError:
|
||||
log_error(f"Permission denied: {args.workdir}")
|
||||
log_error(f"Permission denied: {args['workdir']}")
|
||||
sys.exit(1)
|
||||
log_info('Changed working directory')
|
||||
|
||||
try:
|
||||
log_info(f"Starting gemini with model {DEFAULT_MODEL}")
|
||||
process = None
|
||||
# 启动 gemini 子进程,直接透传 stdout 和 stderr
|
||||
process = subprocess.Popen(
|
||||
gemini_args,
|
||||
@@ -112,11 +92,9 @@ def main():
|
||||
)
|
||||
|
||||
# 实时输出 stdout
|
||||
stdout_lines = []
|
||||
for line in process.stdout:
|
||||
sys.stdout.write(line)
|
||||
sys.stdout.flush()
|
||||
stdout_lines.append(line)
|
||||
|
||||
# 等待进程结束
|
||||
returncode = process.wait(timeout=timeout_sec)
|
||||
@@ -135,11 +113,12 @@ def main():
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
log_error(f'Gemini execution timeout ({timeout_sec}s)')
|
||||
process.kill()
|
||||
try:
|
||||
process.wait(timeout=FORCE_KILL_DELAY)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
if process is not None:
|
||||
process.kill()
|
||||
try:
|
||||
process.wait(timeout=FORCE_KILL_DELAY)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
sys.exit(124)
|
||||
|
||||
except FileNotFoundError:
|
||||
@@ -148,11 +127,12 @@ def main():
|
||||
sys.exit(127)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=FORCE_KILL_DELAY)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
if process is not None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=FORCE_KILL_DELAY)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
sys.exit(130)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user