mirror of
https://github.com/cexll/myclaude.git
synced 2026-02-09 03:09:30 +08:00
Compare commits
18 Commits
v4.3
...
feat/codex
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e30f4e207 | ||
|
|
c8a652ec15 | ||
|
|
12e47affa9 | ||
|
|
612150f72e | ||
|
|
77d9870094 | ||
|
|
c96c07be2a | ||
|
|
cee467fc0e | ||
|
|
71305da77e | ||
|
|
c4021cf58a | ||
|
|
9a18a03061 | ||
|
|
b5183c7711 | ||
|
|
3fab18a6bb | ||
|
|
12af992d8c | ||
|
|
bbd2f50c38 | ||
|
|
3f7652f992 | ||
|
|
2cbe36b532 | ||
|
|
fdb152872d | ||
|
|
916b970665 |
@@ -226,6 +226,36 @@
|
|||||||
"skills": [
|
"skills": [
|
||||||
"./SKILL.md"
|
"./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"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
104
.github/workflows/release.yml
vendored
Normal file
104
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
name: Release codex-wrapper
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: Test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.21'
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
working-directory: codex-wrapper
|
||||||
|
run: go test -v -coverprofile=cover.out ./...
|
||||||
|
|
||||||
|
- name: Check coverage
|
||||||
|
working-directory: codex-wrapper
|
||||||
|
run: |
|
||||||
|
go tool cover -func=cover.out | grep total
|
||||||
|
COVERAGE=$(go tool cover -func=cover.out | grep total | awk '{print $3}' | sed 's/%//')
|
||||||
|
echo "Coverage: ${COVERAGE}%"
|
||||||
|
|
||||||
|
build:
|
||||||
|
name: Build
|
||||||
|
needs: test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- goos: linux
|
||||||
|
goarch: amd64
|
||||||
|
- goos: linux
|
||||||
|
goarch: arm64
|
||||||
|
- goos: darwin
|
||||||
|
goarch: amd64
|
||||||
|
- goos: darwin
|
||||||
|
goarch: arm64
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.21'
|
||||||
|
|
||||||
|
- name: Build binary
|
||||||
|
working-directory: codex-wrapper
|
||||||
|
env:
|
||||||
|
GOOS: ${{ matrix.goos }}
|
||||||
|
GOARCH: ${{ matrix.goarch }}
|
||||||
|
CGO_ENABLED: 0
|
||||||
|
run: |
|
||||||
|
VERSION=${GITHUB_REF#refs/tags/}
|
||||||
|
OUTPUT_NAME=codex-wrapper-${{ matrix.goos }}-${{ matrix.goarch }}
|
||||||
|
go build -ldflags="-s -w -X main.version=${VERSION}" -o ${OUTPUT_NAME} .
|
||||||
|
chmod +x ${OUTPUT_NAME}
|
||||||
|
|
||||||
|
- name: Upload artifact
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: codex-wrapper-${{ matrix.goos }}-${{ matrix.goarch }}
|
||||||
|
path: codex-wrapper/codex-wrapper-${{ matrix.goos }}-${{ matrix.goarch }}
|
||||||
|
|
||||||
|
release:
|
||||||
|
name: Create Release
|
||||||
|
needs: build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Download all artifacts
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
path: artifacts
|
||||||
|
|
||||||
|
- name: Prepare release files
|
||||||
|
run: |
|
||||||
|
mkdir -p release
|
||||||
|
find artifacts -type f -name "codex-wrapper-*" -exec mv {} release/ \;
|
||||||
|
cp install.sh release/
|
||||||
|
ls -la release/
|
||||||
|
|
||||||
|
- name: Create Release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
files: release/*
|
||||||
|
generate_release_notes: true
|
||||||
|
draft: false
|
||||||
|
prerelease: false
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
# Claude Code Plugin System
|
|
||||||
|
|
||||||
本项目已支持Claude Code插件系统,可以将命令和代理打包成可安装的插件包。
|
|
||||||
|
|
||||||
## 插件配置
|
|
||||||
|
|
||||||
插件配置文件位于 `.claude-plugin/marketplace.json`,定义了所有可用的插件包。
|
|
||||||
|
|
||||||
## 可用插件
|
|
||||||
|
|
||||||
### 1. Requirements-Driven Development
|
|
||||||
- **描述**: 需求驱动的开发工作流,包含90%质量门控
|
|
||||||
- **命令**: `/requirements-pilot`
|
|
||||||
- **代理**: requirements-generate, requirements-code, requirements-testing, requirements-review
|
|
||||||
|
|
||||||
### 2. BMAD Agile Workflow
|
|
||||||
- **描述**: 完整的BMAD敏捷工作流(产品负责人→架构师→SM→开发→QA)
|
|
||||||
- **命令**: `/bmad-pilot`
|
|
||||||
- **代理**: bmad-po, bmad-architect, bmad-sm, bmad-dev, bmad-qa, bmad-orchestrator
|
|
||||||
|
|
||||||
### 3. Development Essentials
|
|
||||||
- **描述**: 核心开发命令套件
|
|
||||||
- **命令**: `/code`, `/debug`, `/test`, `/optimize`, `/review`, `/bugfix`, `/refactor`, `/docs`, `/ask`, `/think`
|
|
||||||
- **代理**: code, bugfix, bugfix-verify, code-optimize, debug, develop
|
|
||||||
|
|
||||||
### 4. Advanced AI Agents
|
|
||||||
- **描述**: 高级AI代理,集成GPT-5进行深度分析
|
|
||||||
- **代理**: gpt5
|
|
||||||
|
|
||||||
## 使用插件命令
|
|
||||||
|
|
||||||
### 列出所有可用插件
|
|
||||||
```bash
|
|
||||||
/plugin list
|
|
||||||
```
|
|
||||||
|
|
||||||
### 查看插件详情
|
|
||||||
```bash
|
|
||||||
/plugin info <plugin-name>
|
|
||||||
```
|
|
||||||
例如:`/plugin info requirements-driven-development`
|
|
||||||
|
|
||||||
### 安装插件
|
|
||||||
```bash
|
|
||||||
/plugin install <plugin-name>
|
|
||||||
```
|
|
||||||
例如:`/plugin install bmad-agile-workflow`
|
|
||||||
|
|
||||||
### 移除插件
|
|
||||||
```bash
|
|
||||||
/plugin remove <plugin-name>
|
|
||||||
```
|
|
||||||
|
|
||||||
## 创建自定义插件
|
|
||||||
|
|
||||||
要创建自己的插件:
|
|
||||||
|
|
||||||
1. 在 `.claude-plugin/marketplace.json` 中添加新的插件定义
|
|
||||||
2. 指定插件包含的命令和代理文件路径
|
|
||||||
3. 设置适当的元数据(版本、作者、关键词等)
|
|
||||||
|
|
||||||
示例插件结构:
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"name": "my-custom-plugin",
|
|
||||||
"source": "./",
|
|
||||||
"description": "自定义插件描述",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"commands": [
|
|
||||||
"./commands/my-command.md"
|
|
||||||
],
|
|
||||||
"agents": [
|
|
||||||
"./agents/my-agent.md"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 分享插件
|
|
||||||
|
|
||||||
要分享插件给其他项目:
|
|
||||||
1. 复制整个 `.claude-plugin` 目录到目标项目
|
|
||||||
2. 确保相关的命令和代理文件存在
|
|
||||||
3. 在新项目中使用 `/plugin` 命令管理插件
|
|
||||||
|
|
||||||
## 注意事项
|
|
||||||
|
|
||||||
- 插件系统遵循Claude Code的插件规范
|
|
||||||
- 所有命令和代理文件必须是有效的Markdown格式
|
|
||||||
- 插件配置支持版本管理和依赖关系
|
|
||||||
- 插件可以包含多个命令、代理和输出样式
|
|
||||||
|
|
||||||
## 相关文档
|
|
||||||
|
|
||||||
- [Claude Code插件文档](https://docs.claude.com/en/docs/claude-code/plugins)
|
|
||||||
- [示例插件仓库](https://github.com/wshobson/agents)
|
|
||||||
15
README.md
15
README.md
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
[](https://opensource.org/licenses/MIT)
|
[](https://opensource.org/licenses/MIT)
|
||||||
[](https://claude.ai/code)
|
[](https://claude.ai/code)
|
||||||
[](https://github.com/cexll/myclaude)
|
[](https://github.com/cexll/myclaude)
|
||||||
[](https://docs.claude.com/en/docs/claude-code/plugins)
|
[](https://docs.claude.com/en/docs/claude-code/plugins)
|
||||||
|
|
||||||
> Enterprise-grade agile development automation with AI-powered multi-agent orchestration
|
> Enterprise-grade agile development automation with AI-powered multi-agent orchestration
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
|
|
||||||
**Plugin System (Recommended)**
|
**Plugin System (Recommended)**
|
||||||
```bash
|
```bash
|
||||||
/plugin github.com/cexll/myclaude
|
/plugin marketplace add cexll/myclaude
|
||||||
```
|
```
|
||||||
|
|
||||||
**Traditional Installation**
|
**Traditional Installation**
|
||||||
@@ -44,6 +44,8 @@ make install
|
|||||||
|--------|-------------|--------------|
|
|--------|-------------|--------------|
|
||||||
| **[bmad-agile-workflow](docs/BMAD-WORKFLOW.md)** | Complete BMAD methodology with 6 specialized agents | `/bmad-pilot` |
|
| **[bmad-agile-workflow](docs/BMAD-WORKFLOW.md)** | Complete BMAD methodology with 6 specialized agents | `/bmad-pilot` |
|
||||||
| **[requirements-driven-workflow](docs/REQUIREMENTS-WORKFLOW.md)** | Streamlined requirements-to-code workflow | `/requirements-pilot` |
|
| **[requirements-driven-workflow](docs/REQUIREMENTS-WORKFLOW.md)** | Streamlined requirements-to-code workflow | `/requirements-pilot` |
|
||||||
|
| **[dev-workflow](dev-workflow/README.md)** | Extreme lightweight end-to-end development workflow | `/dev` |
|
||||||
|
| **[codex-wrapper](codex-wrapper/)** | Go binary wrapper for Codex CLI integration | `codex-wrapper` |
|
||||||
| **[development-essentials](docs/DEVELOPMENT-COMMANDS.md)** | Core development slash commands | `/code` `/debug` `/test` `/optimize` |
|
| **[development-essentials](docs/DEVELOPMENT-COMMANDS.md)** | Core development slash commands | `/code` `/debug` `/test` `/optimize` |
|
||||||
| **[advanced-ai-agents](docs/ADVANCED-AGENTS.md)** | GPT-5 deep reasoning integration | Agent: `gpt5` |
|
| **[advanced-ai-agents](docs/ADVANCED-AGENTS.md)** | GPT-5 deep reasoning integration | Agent: `gpt5` |
|
||||||
| **[requirements-clarity](docs/REQUIREMENTS-CLARITY.md)** | Automated requirements clarification with 100-point scoring | Auto-activated skill |
|
| **[requirements-clarity](docs/REQUIREMENTS-CLARITY.md)** | Automated requirements clarification with 100-point scoring | Auto-activated skill |
|
||||||
@@ -88,6 +90,11 @@ make install
|
|||||||
|
|
||||||
## 🛠️ Installation Methods
|
## 🛠️ Installation Methods
|
||||||
|
|
||||||
|
**Codex Wrapper** (Go binary for Codex CLI)
|
||||||
|
```bash
|
||||||
|
curl -fsSL https://raw.githubusercontent.com/cexll/myclaude/refs/heads/master/install.sh | bash
|
||||||
|
```
|
||||||
|
|
||||||
**Method 1: Plugin Install** (One command)
|
**Method 1: Plugin Install** (One command)
|
||||||
```bash
|
```bash
|
||||||
/plugin install bmad-agile-workflow
|
/plugin install bmad-agile-workflow
|
||||||
@@ -101,8 +108,8 @@ make deploy-all # Everything
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Method 3: Manual Setup**
|
**Method 3: Manual Setup**
|
||||||
- Copy `/commands/*.md` to `~/.config/claude/commands/`
|
- Copy `./commands/*.md` to `~/.config/claude/commands/`
|
||||||
- Copy `/agents/*.md` to `~/.config/claude/agents/`
|
- Copy `./agents/*.md` to `~/.config/claude/agents/`
|
||||||
|
|
||||||
Run `make help` for all options.
|
Run `make help` for all options.
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
[](https://opensource.org/licenses/MIT)
|
[](https://opensource.org/licenses/MIT)
|
||||||
[](https://claude.ai/code)
|
[](https://claude.ai/code)
|
||||||
[](https://github.com/cexll/myclaude)
|
[](https://github.com/cexll/myclaude)
|
||||||
[](https://docs.claude.com/en/docs/claude-code/plugins)
|
[](https://docs.claude.com/en/docs/claude-code/plugins)
|
||||||
|
|
||||||
> 企业级敏捷开发自动化与 AI 驱动的多智能体编排
|
> 企业级敏捷开发自动化与 AI 驱动的多智能体编排
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
|
|
||||||
**插件系统(推荐)**
|
**插件系统(推荐)**
|
||||||
```bash
|
```bash
|
||||||
/plugin github.com/cexll/myclaude
|
/plugin marketplace add cexll/myclaude
|
||||||
```
|
```
|
||||||
|
|
||||||
**传统安装**
|
**传统安装**
|
||||||
@@ -44,6 +44,7 @@ make install
|
|||||||
|------|------|---------|
|
|------|------|---------|
|
||||||
| **[bmad-agile-workflow](docs/BMAD-WORKFLOW.md)** | 完整 BMAD 方法论,包含6个专业智能体 | `/bmad-pilot` |
|
| **[bmad-agile-workflow](docs/BMAD-WORKFLOW.md)** | 完整 BMAD 方法论,包含6个专业智能体 | `/bmad-pilot` |
|
||||||
| **[requirements-driven-workflow](docs/REQUIREMENTS-WORKFLOW.md)** | 精简的需求到代码工作流 | `/requirements-pilot` |
|
| **[requirements-driven-workflow](docs/REQUIREMENTS-WORKFLOW.md)** | 精简的需求到代码工作流 | `/requirements-pilot` |
|
||||||
|
| **[dev-workflow](dev-workflow/README.md)** | 极简端到端开发工作流 | `/dev` |
|
||||||
| **[development-essentials](docs/DEVELOPMENT-COMMANDS.md)** | 核心开发斜杠命令 | `/code` `/debug` `/test` `/optimize` |
|
| **[development-essentials](docs/DEVELOPMENT-COMMANDS.md)** | 核心开发斜杠命令 | `/code` `/debug` `/test` `/optimize` |
|
||||||
| **[advanced-ai-agents](docs/ADVANCED-AGENTS.md)** | GPT-5 深度推理集成 | 智能体: `gpt5` |
|
| **[advanced-ai-agents](docs/ADVANCED-AGENTS.md)** | GPT-5 深度推理集成 | 智能体: `gpt5` |
|
||||||
| **[requirements-clarity](docs/REQUIREMENTS-CLARITY.md)** | 自动需求澄清,100分制质量评分 | 自动激活技能 |
|
| **[requirements-clarity](docs/REQUIREMENTS-CLARITY.md)** | 自动需求澄清,100分制质量评分 | 自动激活技能 |
|
||||||
@@ -101,8 +102,8 @@ make deploy-all # 全部安装
|
|||||||
```
|
```
|
||||||
|
|
||||||
**方式3: 手动安装**
|
**方式3: 手动安装**
|
||||||
- 复制 `/commands/*.md` 到 `~/.config/claude/commands/`
|
- 复制 `./commands/*.md` 到 `~/.config/claude/commands/`
|
||||||
- 复制 `/agents/*.md` 到 `~/.config/claude/agents/`
|
- 复制 `./agents/*.md` 到 `~/.config/claude/agents/`
|
||||||
|
|
||||||
运行 `make help` 查看所有选项。
|
运行 `make help` 查看所有选项。
|
||||||
|
|
||||||
|
|||||||
3
codex-wrapper/go.mod
Normal file
3
codex-wrapper/go.mod
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module codex-wrapper
|
||||||
|
|
||||||
|
go 1.25.3
|
||||||
492
codex-wrapper/main.go
Normal file
492
codex-wrapper/main.go
Normal file
@@ -0,0 +1,492 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"os/signal"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
version = "1.0.0"
|
||||||
|
defaultWorkdir = "."
|
||||||
|
defaultTimeout = 7200 // seconds
|
||||||
|
forceKillDelay = 5 // seconds
|
||||||
|
)
|
||||||
|
|
||||||
|
// Test hooks for dependency injection
|
||||||
|
var (
|
||||||
|
stdinReader io.Reader = os.Stdin
|
||||||
|
isTerminalFn = defaultIsTerminal
|
||||||
|
codexCommand = "codex"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config holds CLI configuration
|
||||||
|
type Config struct {
|
||||||
|
Mode string // "new" or "resume"
|
||||||
|
Task string
|
||||||
|
SessionID string
|
||||||
|
WorkDir string
|
||||||
|
ExplicitStdin bool
|
||||||
|
Timeout int
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSONEvent represents a Codex JSON output event
|
||||||
|
type JSONEvent struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
ThreadID string `json:"thread_id,omitempty"`
|
||||||
|
Item *EventItem `json:"item,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// EventItem represents the item field in a JSON event
|
||||||
|
type EventItem struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Text interface{} `json:"text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
exitCode := run()
|
||||||
|
os.Exit(exitCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
// run is the main logic, returns exit code for testability
|
||||||
|
func run() int {
|
||||||
|
// Handle --version and --help first
|
||||||
|
if len(os.Args) > 1 {
|
||||||
|
switch os.Args[1] {
|
||||||
|
case "--version", "-v":
|
||||||
|
fmt.Printf("codex-wrapper version %s\n", version)
|
||||||
|
return 0
|
||||||
|
case "--help", "-h":
|
||||||
|
printHelp()
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logInfo("Script started")
|
||||||
|
|
||||||
|
cfg, err := parseArgs()
|
||||||
|
if err != nil {
|
||||||
|
logError(err.Error())
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
logInfo(fmt.Sprintf("Parsed args: mode=%s, task_len=%d", cfg.Mode, len(cfg.Task)))
|
||||||
|
|
||||||
|
timeoutSec := resolveTimeout()
|
||||||
|
logInfo(fmt.Sprintf("Timeout: %ds", timeoutSec))
|
||||||
|
cfg.Timeout = timeoutSec
|
||||||
|
|
||||||
|
// Determine task text and stdin mode
|
||||||
|
var taskText string
|
||||||
|
var piped bool
|
||||||
|
|
||||||
|
if cfg.ExplicitStdin {
|
||||||
|
logInfo("Explicit stdin mode: reading task from stdin")
|
||||||
|
data, err := io.ReadAll(stdinReader)
|
||||||
|
if err != nil {
|
||||||
|
logError("Failed to read stdin: " + err.Error())
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
taskText = string(data)
|
||||||
|
if taskText == "" {
|
||||||
|
logError("Explicit stdin mode requires task input from stdin")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
piped = !isTerminal()
|
||||||
|
} else {
|
||||||
|
pipedTask := readPipedTask()
|
||||||
|
piped = pipedTask != ""
|
||||||
|
if piped {
|
||||||
|
taskText = pipedTask
|
||||||
|
} else {
|
||||||
|
taskText = cfg.Task
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useStdin := cfg.ExplicitStdin || shouldUseStdin(taskText, piped)
|
||||||
|
|
||||||
|
if useStdin {
|
||||||
|
var reasons []string
|
||||||
|
if piped {
|
||||||
|
reasons = append(reasons, "piped input")
|
||||||
|
}
|
||||||
|
if cfg.ExplicitStdin {
|
||||||
|
reasons = append(reasons, "explicit \"-\"")
|
||||||
|
}
|
||||||
|
if strings.Contains(taskText, "\n") {
|
||||||
|
reasons = append(reasons, "newline")
|
||||||
|
}
|
||||||
|
if strings.Contains(taskText, "\\") {
|
||||||
|
reasons = append(reasons, "backslash")
|
||||||
|
}
|
||||||
|
if len(taskText) > 800 {
|
||||||
|
reasons = append(reasons, "length>800")
|
||||||
|
}
|
||||||
|
if len(reasons) > 0 {
|
||||||
|
logWarn(fmt.Sprintf("Using stdin mode for task due to: %s", strings.Join(reasons, ", ")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
targetArg := taskText
|
||||||
|
if useStdin {
|
||||||
|
targetArg = "-"
|
||||||
|
}
|
||||||
|
|
||||||
|
codexArgs := buildCodexArgs(cfg, targetArg)
|
||||||
|
logInfo("codex running...")
|
||||||
|
|
||||||
|
message, threadID, exitCode := runCodexProcess(codexArgs, taskText, useStdin, cfg.Timeout)
|
||||||
|
|
||||||
|
if exitCode != 0 {
|
||||||
|
return exitCode
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output agent_message
|
||||||
|
fmt.Println(message)
|
||||||
|
|
||||||
|
// Output session_id if present
|
||||||
|
if threadID != "" {
|
||||||
|
fmt.Printf("\n---\nSESSION_ID: %s\n", threadID)
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseArgs() (*Config, error) {
|
||||||
|
args := os.Args[1:]
|
||||||
|
if len(args) == 0 {
|
||||||
|
return nil, fmt.Errorf("task required")
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := &Config{
|
||||||
|
WorkDir: defaultWorkdir,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for resume mode
|
||||||
|
if args[0] == "resume" {
|
||||||
|
if len(args) < 3 {
|
||||||
|
return nil, fmt.Errorf("resume mode requires: resume <session_id> <task>")
|
||||||
|
}
|
||||||
|
cfg.Mode = "resume"
|
||||||
|
cfg.SessionID = args[1]
|
||||||
|
cfg.Task = args[2]
|
||||||
|
cfg.ExplicitStdin = (args[2] == "-")
|
||||||
|
if len(args) > 3 {
|
||||||
|
cfg.WorkDir = args[3]
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
cfg.Mode = "new"
|
||||||
|
cfg.Task = args[0]
|
||||||
|
cfg.ExplicitStdin = (args[0] == "-")
|
||||||
|
if len(args) > 1 {
|
||||||
|
cfg.WorkDir = args[1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readPipedTask() string {
|
||||||
|
if isTerminal() {
|
||||||
|
logInfo("Stdin is tty, skipping pipe read")
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
logInfo("Reading from stdin pipe...")
|
||||||
|
data, err := io.ReadAll(stdinReader)
|
||||||
|
if err != nil || len(data) == 0 {
|
||||||
|
logInfo("Stdin pipe returned empty data")
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
logInfo(fmt.Sprintf("Read %d bytes from stdin pipe", len(data)))
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func shouldUseStdin(taskText string, piped bool) bool {
|
||||||
|
if piped {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if strings.Contains(taskText, "\n") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if strings.Contains(taskText, "\\") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if len(taskText) > 800 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildCodexArgs(cfg *Config, targetArg string) []string {
|
||||||
|
if cfg.Mode == "resume" {
|
||||||
|
return []string{
|
||||||
|
"e",
|
||||||
|
"--skip-git-repo-check",
|
||||||
|
"--json",
|
||||||
|
"resume",
|
||||||
|
cfg.SessionID,
|
||||||
|
targetArg,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return []string{
|
||||||
|
"e",
|
||||||
|
"--skip-git-repo-check",
|
||||||
|
"-C", cfg.WorkDir,
|
||||||
|
"--json",
|
||||||
|
targetArg,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runCodexProcess(codexArgs []string, taskText string, useStdin bool, timeoutSec int) (message, threadID string, exitCode int) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSec)*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
cmd := exec.CommandContext(ctx, codexCommand, codexArgs...)
|
||||||
|
cmd.Stderr = os.Stderr
|
||||||
|
|
||||||
|
// Setup stdin if needed
|
||||||
|
var stdinPipe io.WriteCloser
|
||||||
|
var err error
|
||||||
|
if useStdin {
|
||||||
|
stdinPipe, err = cmd.StdinPipe()
|
||||||
|
if err != nil {
|
||||||
|
logError("Failed to create stdin pipe: " + err.Error())
|
||||||
|
return "", "", 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup stdout
|
||||||
|
stdout, err := cmd.StdoutPipe()
|
||||||
|
if err != nil {
|
||||||
|
logError("Failed to create stdout pipe: " + err.Error())
|
||||||
|
return "", "", 1
|
||||||
|
}
|
||||||
|
|
||||||
|
logInfo(fmt.Sprintf("Starting codex with args: codex %s...", strings.Join(codexArgs[:min(5, len(codexArgs))], " ")))
|
||||||
|
|
||||||
|
// Start process
|
||||||
|
if err := cmd.Start(); err != nil {
|
||||||
|
if strings.Contains(err.Error(), "executable file not found") {
|
||||||
|
logError("codex command not found in PATH")
|
||||||
|
return "", "", 127
|
||||||
|
}
|
||||||
|
logError("Failed to start codex: " + err.Error())
|
||||||
|
return "", "", 1
|
||||||
|
}
|
||||||
|
logInfo(fmt.Sprintf("Process started with PID: %d", cmd.Process.Pid))
|
||||||
|
|
||||||
|
// Write to stdin if needed
|
||||||
|
if useStdin && stdinPipe != nil {
|
||||||
|
logInfo(fmt.Sprintf("Writing %d chars to stdin...", len(taskText)))
|
||||||
|
go func() {
|
||||||
|
defer stdinPipe.Close()
|
||||||
|
io.WriteString(stdinPipe, taskText)
|
||||||
|
}()
|
||||||
|
logInfo("Stdin closed")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup signal handling
|
||||||
|
sigCh := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
go func() {
|
||||||
|
sig := <-sigCh
|
||||||
|
logError(fmt.Sprintf("Received signal: %v", sig))
|
||||||
|
if cmd.Process != nil {
|
||||||
|
cmd.Process.Signal(syscall.SIGTERM)
|
||||||
|
time.AfterFunc(time.Duration(forceKillDelay)*time.Second, func() {
|
||||||
|
if cmd.Process != nil {
|
||||||
|
cmd.Process.Kill()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
logInfo("Reading stdout...")
|
||||||
|
|
||||||
|
// Parse JSON stream
|
||||||
|
message, threadID = parseJSONStream(stdout)
|
||||||
|
|
||||||
|
// Wait for process to complete
|
||||||
|
err = cmd.Wait()
|
||||||
|
|
||||||
|
// Check for timeout
|
||||||
|
if ctx.Err() == context.DeadlineExceeded {
|
||||||
|
logError("Codex execution timeout")
|
||||||
|
if cmd.Process != nil {
|
||||||
|
cmd.Process.Kill()
|
||||||
|
}
|
||||||
|
return "", "", 124
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check exit code
|
||||||
|
if err != nil {
|
||||||
|
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||||
|
code := exitErr.ExitCode()
|
||||||
|
logError(fmt.Sprintf("Codex exited with status %d", code))
|
||||||
|
return "", "", code
|
||||||
|
}
|
||||||
|
logError("Codex error: " + err.Error())
|
||||||
|
return "", "", 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if message == "" {
|
||||||
|
logError("Codex completed without agent_message output")
|
||||||
|
return "", "", 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return message, threadID, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseJSONStream(r io.Reader) (message, threadID string) {
|
||||||
|
scanner := bufio.NewScanner(r)
|
||||||
|
// Set larger buffer for long lines
|
||||||
|
buf := make([]byte, 0, 64*1024)
|
||||||
|
scanner.Buffer(buf, 1024*1024)
|
||||||
|
|
||||||
|
for scanner.Scan() {
|
||||||
|
line := strings.TrimSpace(scanner.Text())
|
||||||
|
if line == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var event JSONEvent
|
||||||
|
if err := json.Unmarshal([]byte(line), &event); err != nil {
|
||||||
|
logWarn(fmt.Sprintf("Failed to parse line: %s", truncate(line, 100)))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture thread_id
|
||||||
|
if event.Type == "thread.started" {
|
||||||
|
threadID = event.ThreadID
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture agent_message
|
||||||
|
if event.Type == "item.completed" && event.Item != nil {
|
||||||
|
if event.Item.Type == "agent_message" {
|
||||||
|
text := normalizeText(event.Item.Text)
|
||||||
|
if text != "" {
|
||||||
|
message = text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := scanner.Err(); err != nil {
|
||||||
|
logWarn("Scanner error: " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
return message, threadID
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeText(text interface{}) string {
|
||||||
|
switch v := text.(type) {
|
||||||
|
case string:
|
||||||
|
return v
|
||||||
|
case []interface{}:
|
||||||
|
var sb strings.Builder
|
||||||
|
for _, item := range v {
|
||||||
|
if s, ok := item.(string); ok {
|
||||||
|
sb.WriteString(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sb.String()
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveTimeout() int {
|
||||||
|
raw := os.Getenv("CODEX_TIMEOUT")
|
||||||
|
if raw == "" {
|
||||||
|
return defaultTimeout
|
||||||
|
}
|
||||||
|
|
||||||
|
parsed, err := strconv.Atoi(raw)
|
||||||
|
if err != nil || parsed <= 0 {
|
||||||
|
logWarn(fmt.Sprintf("Invalid CODEX_TIMEOUT '%s', falling back to %ds", raw, defaultTimeout))
|
||||||
|
return defaultTimeout
|
||||||
|
}
|
||||||
|
|
||||||
|
// Environment variable is in milliseconds if > 10000, convert to seconds
|
||||||
|
if parsed > 10000 {
|
||||||
|
return parsed / 1000
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultIsTerminal() bool {
|
||||||
|
fi, err := os.Stdin.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return (fi.Mode() & os.ModeCharDevice) != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func isTerminal() bool {
|
||||||
|
return isTerminalFn()
|
||||||
|
}
|
||||||
|
|
||||||
|
func getEnv(key, defaultValue string) string {
|
||||||
|
if val := os.Getenv(key); val != "" {
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
func truncate(s string, maxLen int) string {
|
||||||
|
if len(s) <= maxLen {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return s[:maxLen] + "..."
|
||||||
|
}
|
||||||
|
|
||||||
|
func min(a, b int) int {
|
||||||
|
if a < b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func logInfo(msg string) {
|
||||||
|
fmt.Fprintf(os.Stderr, "INFO: %s\n", msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
func logWarn(msg string) {
|
||||||
|
fmt.Fprintf(os.Stderr, "WARN: %s\n", msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
func logError(msg string) {
|
||||||
|
fmt.Fprintf(os.Stderr, "ERROR: %s\n", msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
func printHelp() {
|
||||||
|
help := `codex-wrapper - Go wrapper for Codex CLI
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
codex-wrapper "task" [workdir]
|
||||||
|
codex-wrapper - [workdir] Read task from stdin
|
||||||
|
codex-wrapper resume <session_id> "task" [workdir]
|
||||||
|
codex-wrapper resume <session_id> - [workdir]
|
||||||
|
codex-wrapper --version
|
||||||
|
codex-wrapper --help
|
||||||
|
|
||||||
|
Environment Variables:
|
||||||
|
CODEX_TIMEOUT Timeout in milliseconds (default: 7200000)
|
||||||
|
|
||||||
|
Exit Codes:
|
||||||
|
0 Success
|
||||||
|
1 General error (missing args, no output)
|
||||||
|
124 Timeout
|
||||||
|
127 codex command not found
|
||||||
|
130 Interrupted (Ctrl+C)
|
||||||
|
* Passthrough from codex process`
|
||||||
|
fmt.Println(help)
|
||||||
|
}
|
||||||
748
codex-wrapper/main_test.go
Normal file
748
codex-wrapper/main_test.go
Normal file
@@ -0,0 +1,748 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Helper to reset test hooks
|
||||||
|
func resetTestHooks() {
|
||||||
|
stdinReader = os.Stdin
|
||||||
|
isTerminalFn = defaultIsTerminal
|
||||||
|
codexCommand = "codex"
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseArgs_NewMode(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
want *Config
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "simple task",
|
||||||
|
args: []string{"codex-wrapper", "analyze code"},
|
||||||
|
want: &Config{
|
||||||
|
Mode: "new",
|
||||||
|
Task: "analyze code",
|
||||||
|
WorkDir: ".",
|
||||||
|
ExplicitStdin: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "task with workdir",
|
||||||
|
args: []string{"codex-wrapper", "analyze code", "/path/to/dir"},
|
||||||
|
want: &Config{
|
||||||
|
Mode: "new",
|
||||||
|
Task: "analyze code",
|
||||||
|
WorkDir: "/path/to/dir",
|
||||||
|
ExplicitStdin: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "explicit stdin mode",
|
||||||
|
args: []string{"codex-wrapper", "-"},
|
||||||
|
want: &Config{
|
||||||
|
Mode: "new",
|
||||||
|
Task: "-",
|
||||||
|
WorkDir: ".",
|
||||||
|
ExplicitStdin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "stdin with workdir",
|
||||||
|
args: []string{"codex-wrapper", "-", "/some/dir"},
|
||||||
|
want: &Config{
|
||||||
|
Mode: "new",
|
||||||
|
Task: "-",
|
||||||
|
WorkDir: "/some/dir",
|
||||||
|
ExplicitStdin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "no args",
|
||||||
|
args: []string{"codex-wrapper"},
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
os.Args = tt.args
|
||||||
|
|
||||||
|
cfg, err := parseArgs()
|
||||||
|
|
||||||
|
if tt.wantErr {
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("parseArgs() expected error, got nil")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("parseArgs() unexpected error: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Mode != tt.want.Mode {
|
||||||
|
t.Errorf("Mode = %v, want %v", cfg.Mode, tt.want.Mode)
|
||||||
|
}
|
||||||
|
if cfg.Task != tt.want.Task {
|
||||||
|
t.Errorf("Task = %v, want %v", cfg.Task, tt.want.Task)
|
||||||
|
}
|
||||||
|
if cfg.WorkDir != tt.want.WorkDir {
|
||||||
|
t.Errorf("WorkDir = %v, want %v", cfg.WorkDir, tt.want.WorkDir)
|
||||||
|
}
|
||||||
|
if cfg.ExplicitStdin != tt.want.ExplicitStdin {
|
||||||
|
t.Errorf("ExplicitStdin = %v, want %v", cfg.ExplicitStdin, tt.want.ExplicitStdin)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseArgs_ResumeMode(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
want *Config
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "resume with task",
|
||||||
|
args: []string{"codex-wrapper", "resume", "session-123", "continue task"},
|
||||||
|
want: &Config{
|
||||||
|
Mode: "resume",
|
||||||
|
SessionID: "session-123",
|
||||||
|
Task: "continue task",
|
||||||
|
WorkDir: ".",
|
||||||
|
ExplicitStdin: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "resume with workdir",
|
||||||
|
args: []string{"codex-wrapper", "resume", "session-456", "task", "/work"},
|
||||||
|
want: &Config{
|
||||||
|
Mode: "resume",
|
||||||
|
SessionID: "session-456",
|
||||||
|
Task: "task",
|
||||||
|
WorkDir: "/work",
|
||||||
|
ExplicitStdin: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "resume with stdin",
|
||||||
|
args: []string{"codex-wrapper", "resume", "session-789", "-"},
|
||||||
|
want: &Config{
|
||||||
|
Mode: "resume",
|
||||||
|
SessionID: "session-789",
|
||||||
|
Task: "-",
|
||||||
|
WorkDir: ".",
|
||||||
|
ExplicitStdin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "resume missing session_id",
|
||||||
|
args: []string{"codex-wrapper", "resume"},
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "resume missing task",
|
||||||
|
args: []string{"codex-wrapper", "resume", "session-123"},
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
os.Args = tt.args
|
||||||
|
|
||||||
|
cfg, err := parseArgs()
|
||||||
|
|
||||||
|
if tt.wantErr {
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("parseArgs() expected error, got nil")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("parseArgs() unexpected error: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Mode != tt.want.Mode {
|
||||||
|
t.Errorf("Mode = %v, want %v", cfg.Mode, tt.want.Mode)
|
||||||
|
}
|
||||||
|
if cfg.SessionID != tt.want.SessionID {
|
||||||
|
t.Errorf("SessionID = %v, want %v", cfg.SessionID, tt.want.SessionID)
|
||||||
|
}
|
||||||
|
if cfg.Task != tt.want.Task {
|
||||||
|
t.Errorf("Task = %v, want %v", cfg.Task, tt.want.Task)
|
||||||
|
}
|
||||||
|
if cfg.WorkDir != tt.want.WorkDir {
|
||||||
|
t.Errorf("WorkDir = %v, want %v", cfg.WorkDir, tt.want.WorkDir)
|
||||||
|
}
|
||||||
|
if cfg.ExplicitStdin != tt.want.ExplicitStdin {
|
||||||
|
t.Errorf("ExplicitStdin = %v, want %v", cfg.ExplicitStdin, tt.want.ExplicitStdin)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestShouldUseStdin(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
task string
|
||||||
|
piped bool
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"simple task", "analyze code", false, false},
|
||||||
|
{"piped input", "analyze code", true, true},
|
||||||
|
{"contains newline", "line1\nline2", false, true},
|
||||||
|
{"contains backslash", "path\\to\\file", false, true},
|
||||||
|
{"long task", strings.Repeat("a", 801), false, true},
|
||||||
|
{"exactly 800 chars", strings.Repeat("a", 800), false, false},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := shouldUseStdin(tt.task, tt.piped)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("shouldUseStdin(%q, %v) = %v, want %v", truncate(tt.task, 20), tt.piped, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCodexArgs_NewMode(t *testing.T) {
|
||||||
|
cfg := &Config{
|
||||||
|
Mode: "new",
|
||||||
|
WorkDir: "/test/dir",
|
||||||
|
}
|
||||||
|
|
||||||
|
args := buildCodexArgs(cfg, "my task")
|
||||||
|
|
||||||
|
expected := []string{
|
||||||
|
"e",
|
||||||
|
"--skip-git-repo-check",
|
||||||
|
"-C", "/test/dir",
|
||||||
|
"--json",
|
||||||
|
"my task",
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(args) != len(expected) {
|
||||||
|
t.Errorf("buildCodexArgs() returned %d args, want %d", len(args), len(expected))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, arg := range args {
|
||||||
|
if arg != expected[i] {
|
||||||
|
t.Errorf("buildCodexArgs()[%d] = %v, want %v", i, arg, expected[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCodexArgs_ResumeMode(t *testing.T) {
|
||||||
|
cfg := &Config{
|
||||||
|
Mode: "resume",
|
||||||
|
SessionID: "session-abc",
|
||||||
|
}
|
||||||
|
|
||||||
|
args := buildCodexArgs(cfg, "-")
|
||||||
|
|
||||||
|
expected := []string{
|
||||||
|
"e",
|
||||||
|
"--skip-git-repo-check",
|
||||||
|
"--json",
|
||||||
|
"resume",
|
||||||
|
"session-abc",
|
||||||
|
"-",
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(args) != len(expected) {
|
||||||
|
t.Errorf("buildCodexArgs() returned %d args, want %d", len(args), len(expected))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, arg := range args {
|
||||||
|
if arg != expected[i] {
|
||||||
|
t.Errorf("buildCodexArgs()[%d] = %v, want %v", i, arg, expected[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveTimeout(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
envVal string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{"empty env", "", 7200},
|
||||||
|
{"milliseconds", "7200000", 7200},
|
||||||
|
{"seconds", "3600", 3600},
|
||||||
|
{"invalid", "invalid", 7200},
|
||||||
|
{"negative", "-100", 7200},
|
||||||
|
{"zero", "0", 7200},
|
||||||
|
{"small milliseconds", "5000", 5000},
|
||||||
|
{"boundary", "10000", 10000},
|
||||||
|
{"above boundary", "10001", 10},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
os.Setenv("CODEX_TIMEOUT", tt.envVal)
|
||||||
|
defer os.Unsetenv("CODEX_TIMEOUT")
|
||||||
|
|
||||||
|
got := resolveTimeout()
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("resolveTimeout() with env=%q = %v, want %v", tt.envVal, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeText(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
input interface{}
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"string", "hello world", "hello world"},
|
||||||
|
{"string array", []interface{}{"hello", " ", "world"}, "hello world"},
|
||||||
|
{"empty array", []interface{}{}, ""},
|
||||||
|
{"mixed array", []interface{}{"text", 123, "more"}, "textmore"},
|
||||||
|
{"nil", nil, ""},
|
||||||
|
{"number", 123, ""},
|
||||||
|
{"empty string", "", ""},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := normalizeText(tt.input)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("normalizeText(%v) = %q, want %q", tt.input, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseJSONStream(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
input string
|
||||||
|
wantMessage string
|
||||||
|
wantThreadID string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "thread started and agent message",
|
||||||
|
input: `{"type":"thread.started","thread_id":"abc-123"}
|
||||||
|
{"type":"item.completed","item":{"type":"agent_message","text":"Hello world"}}`,
|
||||||
|
wantMessage: "Hello world",
|
||||||
|
wantThreadID: "abc-123",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "multiple agent messages (last wins)",
|
||||||
|
input: `{"type":"item.completed","item":{"type":"agent_message","text":"First"}}
|
||||||
|
{"type":"item.completed","item":{"type":"agent_message","text":"Second"}}`,
|
||||||
|
wantMessage: "Second",
|
||||||
|
wantThreadID: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "text as array",
|
||||||
|
input: `{"type":"item.completed","item":{"type":"agent_message","text":["Hello"," ","World"]}}`,
|
||||||
|
wantMessage: "Hello World",
|
||||||
|
wantThreadID: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "ignore other event types",
|
||||||
|
input: `{"type":"other.event","data":"ignored"}
|
||||||
|
{"type":"item.completed","item":{"type":"other_type","text":"ignored"}}
|
||||||
|
{"type":"item.completed","item":{"type":"agent_message","text":"Valid"}}`,
|
||||||
|
wantMessage: "Valid",
|
||||||
|
wantThreadID: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty input",
|
||||||
|
input: "",
|
||||||
|
wantMessage: "",
|
||||||
|
wantThreadID: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid JSON (skipped)",
|
||||||
|
input: "not valid json\n{\"type\":\"thread.started\",\"thread_id\":\"xyz\"}",
|
||||||
|
wantMessage: "",
|
||||||
|
wantThreadID: "xyz",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "blank lines ignored",
|
||||||
|
input: "\n\n{\"type\":\"thread.started\",\"thread_id\":\"test\"}\n\n",
|
||||||
|
wantMessage: "",
|
||||||
|
wantThreadID: "test",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
r := strings.NewReader(tt.input)
|
||||||
|
gotMessage, gotThreadID := parseJSONStream(r)
|
||||||
|
|
||||||
|
if gotMessage != tt.wantMessage {
|
||||||
|
t.Errorf("parseJSONStream() message = %q, want %q", gotMessage, tt.wantMessage)
|
||||||
|
}
|
||||||
|
if gotThreadID != tt.wantThreadID {
|
||||||
|
t.Errorf("parseJSONStream() threadID = %q, want %q", gotThreadID, tt.wantThreadID)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetEnv(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
key string
|
||||||
|
defaultVal string
|
||||||
|
envVal string
|
||||||
|
setEnv bool
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"env set", "TEST_KEY", "default", "custom", true, "custom"},
|
||||||
|
{"env not set", "TEST_KEY_MISSING", "default", "", false, "default"},
|
||||||
|
{"env empty", "TEST_KEY_EMPTY", "default", "", true, "default"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
os.Unsetenv(tt.key)
|
||||||
|
if tt.setEnv {
|
||||||
|
os.Setenv(tt.key, tt.envVal)
|
||||||
|
defer os.Unsetenv(tt.key)
|
||||||
|
}
|
||||||
|
|
||||||
|
got := getEnv(tt.key, tt.defaultVal)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("getEnv(%q, %q) = %q, want %q", tt.key, tt.defaultVal, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTruncate(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
input string
|
||||||
|
maxLen int
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"short string", "hello", 10, "hello"},
|
||||||
|
{"exact length", "hello", 5, "hello"},
|
||||||
|
{"truncate", "hello world", 5, "hello..."},
|
||||||
|
{"empty", "", 5, ""},
|
||||||
|
{"zero maxLen", "hello", 0, "..."},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := truncate(tt.input, tt.maxLen)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("truncate(%q, %d) = %q, want %q", tt.input, tt.maxLen, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMin(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
a, b, want int
|
||||||
|
}{
|
||||||
|
{1, 2, 1},
|
||||||
|
{2, 1, 1},
|
||||||
|
{5, 5, 5},
|
||||||
|
{-1, 0, -1},
|
||||||
|
{0, -1, -1},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run("", func(t *testing.T) {
|
||||||
|
got := min(tt.a, tt.b)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("min(%d, %d) = %d, want %d", tt.a, tt.b, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogFunctions(t *testing.T) {
|
||||||
|
// Capture stderr
|
||||||
|
oldStderr := os.Stderr
|
||||||
|
r, w, _ := os.Pipe()
|
||||||
|
os.Stderr = w
|
||||||
|
|
||||||
|
logInfo("info message")
|
||||||
|
logWarn("warn message")
|
||||||
|
logError("error message")
|
||||||
|
|
||||||
|
w.Close()
|
||||||
|
os.Stderr = oldStderr
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
io.Copy(&buf, r)
|
||||||
|
output := buf.String()
|
||||||
|
|
||||||
|
if !strings.Contains(output, "INFO: info message") {
|
||||||
|
t.Errorf("logInfo output missing, got: %s", output)
|
||||||
|
}
|
||||||
|
if !strings.Contains(output, "WARN: warn message") {
|
||||||
|
t.Errorf("logWarn output missing, got: %s", output)
|
||||||
|
}
|
||||||
|
if !strings.Contains(output, "ERROR: error message") {
|
||||||
|
t.Errorf("logError output missing, got: %s", output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrintHelp(t *testing.T) {
|
||||||
|
// Capture stdout
|
||||||
|
oldStdout := os.Stdout
|
||||||
|
r, w, _ := os.Pipe()
|
||||||
|
os.Stdout = w
|
||||||
|
|
||||||
|
printHelp()
|
||||||
|
|
||||||
|
w.Close()
|
||||||
|
os.Stdout = oldStdout
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
io.Copy(&buf, r)
|
||||||
|
output := buf.String()
|
||||||
|
|
||||||
|
expectedPhrases := []string{
|
||||||
|
"codex-wrapper",
|
||||||
|
"Usage:",
|
||||||
|
"resume",
|
||||||
|
"CODEX_TIMEOUT",
|
||||||
|
"Exit Codes:",
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, phrase := range expectedPhrases {
|
||||||
|
if !strings.Contains(output, phrase) {
|
||||||
|
t.Errorf("printHelp() missing phrase %q", phrase)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tests for isTerminal with mock
|
||||||
|
func TestIsTerminal(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
mockFn func() bool
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"is terminal", func() bool { return true }, true},
|
||||||
|
{"is not terminal", func() bool { return false }, false},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
isTerminalFn = tt.mockFn
|
||||||
|
got := isTerminal()
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("isTerminal() = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tests for readPipedTask with mock
|
||||||
|
func TestReadPipedTask(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
isTerminal bool
|
||||||
|
stdinContent string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"terminal mode", true, "ignored", ""},
|
||||||
|
{"piped with data", false, "task from pipe", "task from pipe"},
|
||||||
|
{"piped empty", false, "", ""},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
isTerminalFn = func() bool { return tt.isTerminal }
|
||||||
|
stdinReader = strings.NewReader(tt.stdinContent)
|
||||||
|
|
||||||
|
got := readPipedTask()
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("readPipedTask() = %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tests for runCodexProcess with mock command
|
||||||
|
func TestRunCodexProcess_CommandNotFound(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
codexCommand = "nonexistent-command-xyz"
|
||||||
|
|
||||||
|
_, _, exitCode := runCodexProcess([]string{"arg1"}, "task", false, 10)
|
||||||
|
|
||||||
|
if exitCode != 127 {
|
||||||
|
t.Errorf("runCodexProcess() exitCode = %d, want 127 for command not found", exitCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunCodexProcess_WithEcho(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
// Use echo to simulate codex output
|
||||||
|
codexCommand = "echo"
|
||||||
|
|
||||||
|
jsonOutput := `{"type":"thread.started","thread_id":"test-session"}
|
||||||
|
{"type":"item.completed","item":{"type":"agent_message","text":"Test output"}}`
|
||||||
|
|
||||||
|
message, threadID, exitCode := runCodexProcess([]string{jsonOutput}, "", false, 10)
|
||||||
|
|
||||||
|
if exitCode != 0 {
|
||||||
|
t.Errorf("runCodexProcess() exitCode = %d, want 0", exitCode)
|
||||||
|
}
|
||||||
|
if message != "Test output" {
|
||||||
|
t.Errorf("runCodexProcess() message = %q, want %q", message, "Test output")
|
||||||
|
}
|
||||||
|
if threadID != "test-session" {
|
||||||
|
t.Errorf("runCodexProcess() threadID = %q, want %q", threadID, "test-session")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunCodexProcess_NoMessage(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
codexCommand = "echo"
|
||||||
|
|
||||||
|
// Output without agent_message
|
||||||
|
jsonOutput := `{"type":"thread.started","thread_id":"test-session"}`
|
||||||
|
|
||||||
|
_, _, exitCode := runCodexProcess([]string{jsonOutput}, "", false, 10)
|
||||||
|
|
||||||
|
if exitCode != 1 {
|
||||||
|
t.Errorf("runCodexProcess() exitCode = %d, want 1 for no message", exitCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunCodexProcess_WithStdin(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
// Use cat to echo stdin back
|
||||||
|
codexCommand = "cat"
|
||||||
|
|
||||||
|
message, _, exitCode := runCodexProcess([]string{}, `{"type":"item.completed","item":{"type":"agent_message","text":"from stdin"}}`, true, 10)
|
||||||
|
|
||||||
|
if exitCode != 0 {
|
||||||
|
t.Errorf("runCodexProcess() exitCode = %d, want 0", exitCode)
|
||||||
|
}
|
||||||
|
if message != "from stdin" {
|
||||||
|
t.Errorf("runCodexProcess() message = %q, want %q", message, "from stdin")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunCodexProcess_ExitError(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
// Use false command which exits with code 1
|
||||||
|
codexCommand = "false"
|
||||||
|
|
||||||
|
_, _, exitCode := runCodexProcess([]string{}, "", false, 10)
|
||||||
|
|
||||||
|
if exitCode == 0 {
|
||||||
|
t.Errorf("runCodexProcess() exitCode = 0, want non-zero for failed command")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDefaultIsTerminal(t *testing.T) {
|
||||||
|
// This test just ensures defaultIsTerminal doesn't panic
|
||||||
|
// The actual result depends on the test environment
|
||||||
|
_ = defaultIsTerminal()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tests for run() function
|
||||||
|
func TestRun_Version(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
os.Args = []string{"codex-wrapper", "--version"}
|
||||||
|
exitCode := run()
|
||||||
|
if exitCode != 0 {
|
||||||
|
t.Errorf("run() with --version returned %d, want 0", exitCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRun_VersionShort(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
os.Args = []string{"codex-wrapper", "-v"}
|
||||||
|
exitCode := run()
|
||||||
|
if exitCode != 0 {
|
||||||
|
t.Errorf("run() with -v returned %d, want 0", exitCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRun_Help(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
os.Args = []string{"codex-wrapper", "--help"}
|
||||||
|
exitCode := run()
|
||||||
|
if exitCode != 0 {
|
||||||
|
t.Errorf("run() with --help returned %d, want 0", exitCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRun_HelpShort(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
os.Args = []string{"codex-wrapper", "-h"}
|
||||||
|
exitCode := run()
|
||||||
|
if exitCode != 0 {
|
||||||
|
t.Errorf("run() with -h returned %d, want 0", exitCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRun_NoArgs(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
os.Args = []string{"codex-wrapper"}
|
||||||
|
exitCode := run()
|
||||||
|
if exitCode != 1 {
|
||||||
|
t.Errorf("run() with no args returned %d, want 1", exitCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRun_ExplicitStdinEmpty(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
os.Args = []string{"codex-wrapper", "-"}
|
||||||
|
stdinReader = strings.NewReader("")
|
||||||
|
isTerminalFn = func() bool { return false }
|
||||||
|
|
||||||
|
exitCode := run()
|
||||||
|
if exitCode != 1 {
|
||||||
|
t.Errorf("run() with empty stdin returned %d, want 1", exitCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRun_CommandFails(t *testing.T) {
|
||||||
|
defer resetTestHooks()
|
||||||
|
|
||||||
|
os.Args = []string{"codex-wrapper", "task"}
|
||||||
|
stdinReader = strings.NewReader("")
|
||||||
|
isTerminalFn = func() bool { return true }
|
||||||
|
codexCommand = "false"
|
||||||
|
|
||||||
|
exitCode := run()
|
||||||
|
if exitCode == 0 {
|
||||||
|
t.Errorf("run() with failing command returned 0, want non-zero")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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. 需求澄清
|
### 1. Clarify Requirements
|
||||||
- 使用 **AskUserQuestion** 直接问用户
|
- Use **AskUserQuestion** to ask the user directly
|
||||||
- 无评分系统,无复杂逻辑
|
- No scoring system, no complex logic
|
||||||
- 2-3 轮问答直到需求明确
|
- 2–3 rounds of Q&A until the requirement is clear
|
||||||
|
|
||||||
### 2. Codex 分析
|
### 2. Codex Analysis
|
||||||
- 调用 codex 分析需求
|
- Call codex to analyze the request
|
||||||
- 提取:核心功能、技术要点、任务列表(2-5个)
|
- Extract: core functions, technical points, task list (2–5 items)
|
||||||
- 输出结构化分析结果
|
- Output a structured analysis
|
||||||
|
|
||||||
### 3. 生成开发文档
|
### 3. Generate Dev Doc
|
||||||
- 调用 **develop-doc-generator** agent
|
- Call the **develop-doc-generator** agent
|
||||||
- 生成 `dev-plan.md`(单一开发文档)
|
- Produce a single `dev-plan.md`
|
||||||
- 包含:任务分解、文件范围、依赖关系、测试命令
|
- Include: task breakdown, file scope, dependencies, test commands
|
||||||
|
|
||||||
### 4. 并发开发
|
### 4. Concurrent Development
|
||||||
- 基于 dev-plan.md 的任务列表
|
- Work from the task list in dev-plan.md
|
||||||
- 无依赖任务 → 并发执行
|
- Independent tasks → run in parallel
|
||||||
- 有冲突任务 → 串行执行
|
- Conflicting tasks → run serially
|
||||||
|
|
||||||
### 5. 测试验证
|
### 5. Testing & Verification
|
||||||
- 每个 codex 任务自己:
|
- Each codex task:
|
||||||
- 实现功能
|
- Implements the feature
|
||||||
- 编写测试
|
- Writes tests
|
||||||
- 运行覆盖率
|
- Runs coverage
|
||||||
- 报告结果(≥90%)
|
- Reports results (≥90%)
|
||||||
|
|
||||||
### 6. 完成
|
### 6. Complete
|
||||||
- 汇总任务状态
|
- Summarize task status
|
||||||
- 记录覆盖率
|
- Record coverage
|
||||||
|
|
||||||
## 使用方法
|
## Usage
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
/dev "实现用户登录功能,支持邮箱和密码验证"
|
/dev "Implement user login with email + password"
|
||||||
```
|
```
|
||||||
|
|
||||||
**无选项**,流程固定,开箱即用。
|
**No options**, fixed workflow, works out of the box.
|
||||||
|
|
||||||
## 输出结构
|
## Output Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
.claude/specs/{feature_name}/
|
.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
|
||||||
|
|
||||||
### 工具
|
### Tools
|
||||||
- **AskUserQuestion**:交互式需求澄清
|
- **AskUserQuestion**: interactive requirement clarification
|
||||||
- **codex**:分析、开发、测试
|
- **codex**: analysis, development, testing
|
||||||
- **develop-doc-generator**:生成开发文档(subagent,节省上下文)
|
- **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
|
||||||
|
|
||||||
### ✅ 极简编排
|
### ✅ Minimal Orchestration
|
||||||
- orchestrator 直接控制流程
|
- Orchestrator controls the flow directly
|
||||||
- 只用 3 个工具/组件
|
- Only three tools/components
|
||||||
- 步骤清晰易懂
|
- Steps are straightforward
|
||||||
|
|
||||||
### ✅ 并发能力
|
### ✅ Concurrency
|
||||||
- 2-5 个任务并行
|
- 2–5 tasks in parallel
|
||||||
- 自动检测依赖和冲突
|
- Auto-detect dependencies and conflicts
|
||||||
- codex 独立执行
|
- Codex executes independently
|
||||||
|
|
||||||
### ✅ 质量保证
|
### ✅ Quality Assurance
|
||||||
- 强制 90% 覆盖率
|
- Enforces 90% coverage
|
||||||
- codex 自己测试和验证
|
- Codex tests and verifies its own work
|
||||||
- 失败自动重试
|
- Automatic retry on failure
|
||||||
|
|
||||||
## 示例
|
## Example
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 触发
|
# Trigger
|
||||||
/dev "添加用户登录功能"
|
/dev "Add user login feature"
|
||||||
|
|
||||||
# 步骤 1: 需求澄清
|
# Step 1: Clarify requirements
|
||||||
Q: 支持哪些登录方式?
|
Q: What login methods are supported?
|
||||||
A: 邮箱 + 密码
|
A: Email + password
|
||||||
Q: 需要记住登录状态吗?
|
Q: Should login be remembered?
|
||||||
A: 是,使用 JWT token
|
A: Yes, use JWT token
|
||||||
|
|
||||||
# 步骤 2: Codex 分析
|
# Step 2: Codex analysis
|
||||||
输出:
|
Output:
|
||||||
- 核心功能:邮箱密码登录 + JWT认证
|
- Core: email/password login + JWT auth
|
||||||
- 任务 1:后端 API
|
- Task 1: Backend API
|
||||||
- 任务 2:密码加密
|
- Task 2: Password hashing
|
||||||
- 任务 3:前端表单
|
- Task 3: Frontend form
|
||||||
|
|
||||||
# 步骤 3: 生成文档
|
# Step 3: Generate doc
|
||||||
dev-plan.md 已生成 ✓
|
dev-plan.md generated ✓
|
||||||
|
|
||||||
# 步骤 4-5: 并发开发
|
# Step 4-5: Concurrent development
|
||||||
[task-1] 后端API → 测试 → 92% ✓
|
[task-1] Backend API → tests → 92% ✓
|
||||||
[task-2] 密码加密 → 测试 → 95% ✓
|
[task-2] Password hashing → tests → 95% ✓
|
||||||
[task-3] 前端表单 → 测试 → 91% ✓
|
[task-3] Frontend form → tests → 91% ✓
|
||||||
```
|
```
|
||||||
|
|
||||||
## 目录结构
|
## Directory Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
dev-workflow/
|
dev-workflow/
|
||||||
├── README.md # 本文档
|
├── README.md # This doc
|
||||||
├── commands/
|
├── commands/
|
||||||
│ └── dev.md # 工作流定义
|
│ └── dev.md # Workflow definition
|
||||||
└── agents/
|
└── 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**:保持简单愚蠢
|
1. **KISS**: keep it simple
|
||||||
2. **即用即抛**:无持久化配置
|
2. **Disposable**: no persistent config
|
||||||
3. **质量优先**:强制 90% 覆盖率
|
3. **Quality first**: enforce 90% coverage
|
||||||
4. **并发优先**:充分利用 codex 能力
|
4. **Concurrency first**: leverage codex
|
||||||
5. **无历史包袱**:全新设计,不受其他项目影响
|
5. **No legacy baggage**: clean-slate design
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**哲学**:像 Linus 一样对复杂度零容忍,交付能立刻用的最小方案。
|
**Philosophy**: zero tolerance for complexity—ship the smallest usable solution, like Linus would.
|
||||||
|
|||||||
@@ -20,35 +20,35 @@ Your output is a single file: `./.claude/specs/{feature_name}/dev-plan.md`
|
|||||||
## Document Structure You Must Follow
|
## Document Structure You Must Follow
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# {Feature Name} - 开发计划
|
# {Feature Name} - Development Plan
|
||||||
|
|
||||||
## 功能概述
|
## Overview
|
||||||
[一句话描述核心功能]
|
[One-sentence description of core functionality]
|
||||||
|
|
||||||
## 任务分解
|
## Task Breakdown
|
||||||
|
|
||||||
### 任务 1: [任务名称]
|
### Task 1: [Task Name]
|
||||||
- **ID**: task-1
|
- **ID**: task-1
|
||||||
- **描述**: [具体要做什么]
|
- **Description**: [What needs to be done]
|
||||||
- **文件范围**: [涉及的目录或文件,如 src/auth/**, tests/auth/]
|
- **File Scope**: [Directories or files involved, e.g., src/auth/**, tests/auth/]
|
||||||
- **依赖**: [无 或 依赖 task-x]
|
- **Dependencies**: [None or depends on task-x]
|
||||||
- **测试命令**: [如 pytest tests/auth --cov=src/auth --cov-report=term]
|
- **Test Command**: [e.g., pytest tests/auth --cov=src/auth --cov-report=term]
|
||||||
- **测试重点**: [需要覆盖的场景]
|
- **Test Focus**: [Scenarios to cover]
|
||||||
|
|
||||||
### 任务 2: [任务名称]
|
### Task 2: [Task Name]
|
||||||
...
|
...
|
||||||
|
|
||||||
(2-5个任务)
|
(2-5 tasks)
|
||||||
|
|
||||||
## 验收标准
|
## Acceptance Criteria
|
||||||
- [ ] 功能点 1
|
- [ ] Feature point 1
|
||||||
- [ ] 功能点 2
|
- [ ] Feature point 2
|
||||||
- [ ] 所有单元测试通过
|
- [ ] All unit tests pass
|
||||||
- [ ] 代码覆盖率 ≥90%
|
- [ ] Code coverage ≥90%
|
||||||
|
|
||||||
## 技术要点
|
## Technical Notes
|
||||||
- [关键技术决策]
|
- [Key technical decisions]
|
||||||
- [需要注意的约束]
|
- [Constraints to be aware of]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Generation Rules You Must Enforce
|
## Generation Rules You Must Enforce
|
||||||
@@ -58,7 +58,7 @@ Your output is a single file: `./.claude/specs/{feature_name}/dev-plan.md`
|
|||||||
- Clear ID (task-1, task-2, etc.)
|
- Clear ID (task-1, task-2, etc.)
|
||||||
- Specific description of what needs to be done
|
- Specific description of what needs to be done
|
||||||
- Explicit file scope (directories or files affected)
|
- Explicit file scope (directories or files affected)
|
||||||
- Dependency declaration ("无" or "依赖 task-x")
|
- Dependency declaration ("None" or "depends on task-x")
|
||||||
- Complete test command with coverage parameters
|
- Complete test command with coverage parameters
|
||||||
- Testing focus points (scenarios to cover)
|
- Testing focus points (scenarios to cover)
|
||||||
3. **Task Independence**: Design tasks to be as independent as possible to enable parallel execution
|
3. **Task Independence**: Design tasks to be as independent as possible to enable parallel execution
|
||||||
@@ -78,7 +78,7 @@ Your output is a single file: `./.claude/specs/{feature_name}/dev-plan.md`
|
|||||||
## Quality Checks Before Writing
|
## Quality Checks Before Writing
|
||||||
|
|
||||||
- [ ] Task count is between 2-5
|
- [ ] Task count is between 2-5
|
||||||
- [ ] Every task has all 6 required fields (ID, 描述, 文件范围, 依赖, 测试命令, 测试重点)
|
- [ ] Every task has all 6 required fields (ID, Description, File Scope, Dependencies, Test Command, Test Focus)
|
||||||
- [ ] Test commands include coverage parameters
|
- [ ] Test commands include coverage parameters
|
||||||
- [ ] Dependencies are explicitly stated
|
- [ ] Dependencies are explicitly stated
|
||||||
- [ ] Acceptance criteria includes 90% coverage requirement
|
- [ ] Acceptance criteria includes 90% coverage requirement
|
||||||
@@ -90,7 +90,7 @@ Your output is a single file: `./.claude/specs/{feature_name}/dev-plan.md`
|
|||||||
- **Document Only**: You generate documentation. You do NOT execute code, run tests, or modify source files.
|
- **Document Only**: You generate documentation. You do NOT execute code, run tests, or modify source files.
|
||||||
- **Single Output**: You produce exactly one file: `dev-plan.md` in the correct location
|
- **Single Output**: You produce exactly one file: `dev-plan.md` in the correct location
|
||||||
- **Path Accuracy**: The path must be `./.claude/specs/{feature_name}/dev-plan.md` where {feature_name} matches the input
|
- **Path Accuracy**: The path must be `./.claude/specs/{feature_name}/dev-plan.md` where {feature_name} matches the input
|
||||||
- **Chinese Language**: The document must be in Chinese (as shown in the structure)
|
- **Language Matching**: Output language matches user input (Chinese input → Chinese doc, English input → English doc)
|
||||||
- **Structured Format**: Follow the exact markdown structure provided
|
- **Structured Format**: Follow the exact markdown structure provided
|
||||||
|
|
||||||
## Example Output Quality
|
## Example Output Quality
|
||||||
|
|||||||
@@ -20,61 +20,57 @@ You are the /dev Workflow Orchestrator, an expert development workflow manager s
|
|||||||
- Focus questions on functional boundaries, inputs/outputs, constraints, testing
|
- Focus questions on functional boundaries, inputs/outputs, constraints, testing
|
||||||
- Iterate 2-3 rounds until clear; rely on judgment; keep questions concise
|
- Iterate 2-3 rounds until clear; rely on judgment; keep questions concise
|
||||||
|
|
||||||
- **Step 2: Codex Analysis**
|
- **Step 2: Codex Deep Analysis (Plan Mode Style)**
|
||||||
- Run:
|
|
||||||
```bash
|
|
||||||
uv run ~/.claude/skills/codex/scripts/codex.py "分析以下需求并提取开发要点:
|
|
||||||
|
|
||||||
需求描述:
|
Use Codex Skill to perform deep analysis. Codex should operate in "plan mode" style:
|
||||||
[用户需求 + 澄清后的细节]
|
|
||||||
|
|
||||||
请输出:
|
**When Deep Analysis is Needed** (any condition triggers):
|
||||||
1. 核心功能(一句话)
|
- Multiple valid approaches exist (e.g., Redis vs in-memory vs file-based caching)
|
||||||
2. 关键技术点
|
- Significant architectural decisions required (e.g., WebSockets vs SSE vs polling)
|
||||||
3. 可并发的任务分解(2-5个):
|
- Large-scale changes touching many files or systems
|
||||||
- 任务ID
|
- Unclear scope requiring exploration first
|
||||||
- 任务描述
|
|
||||||
- 涉及文件/目录
|
**What Codex Does in Analysis Mode**:
|
||||||
- 是否依赖其他任务
|
1. **Explore Codebase**: Use Glob, Grep, Read to understand structure, patterns, architecture
|
||||||
- 测试重点
|
2. **Identify Existing Patterns**: Find how similar features are implemented, reuse conventions
|
||||||
" "gpt-5.1-codex"
|
3. **Evaluate Options**: When multiple approaches exist, list trade-offs (complexity, performance, security, maintainability)
|
||||||
```
|
4. **Make Architectural Decisions**: Choose patterns, APIs, data models with justification
|
||||||
- Extract core functionality, technical key points, and 2-5 parallelizable tasks with full metadata
|
5. **Design Task Breakdown**: Produce 2-5 parallelizable tasks with file scope and dependencies
|
||||||
|
|
||||||
|
**Analysis Output Structure**:
|
||||||
|
```
|
||||||
|
## Context & Constraints
|
||||||
|
[Tech stack, existing patterns, constraints discovered]
|
||||||
|
|
||||||
|
## Codebase Exploration
|
||||||
|
[Key files, modules, patterns found via Glob/Grep/Read]
|
||||||
|
|
||||||
|
## Implementation Options (if multiple approaches)
|
||||||
|
| Option | Pros | Cons | Recommendation |
|
||||||
|
|
||||||
|
## Technical Decisions
|
||||||
|
[API design, data models, architecture choices made]
|
||||||
|
|
||||||
|
## Task Breakdown
|
||||||
|
[2-5 tasks with: ID, description, file scope, dependencies, test command]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Skip Deep Analysis When**:
|
||||||
|
- Simple, straightforward implementation with obvious approach
|
||||||
|
- Small changes confined to 1-2 files
|
||||||
|
- Clear requirements with single implementation path
|
||||||
|
|
||||||
- **Step 3: Generate Development Documentation**
|
- **Step 3: Generate Development Documentation**
|
||||||
- Use Task tool to invoke develop-doc-generator:
|
- invoke agent dev-plan-generator
|
||||||
```
|
|
||||||
基于以下分析结果生成开发文档:
|
|
||||||
|
|
||||||
[Codex 分析输出]
|
|
||||||
|
|
||||||
输出文件:./.claude/specs/{feature_name}/dev-plan.md
|
|
||||||
|
|
||||||
包含:
|
|
||||||
1. 功能概述
|
|
||||||
2. 任务列表(2-5个并发任务)
|
|
||||||
- 每个任务:ID、描述、文件范围、依赖、测试命令
|
|
||||||
3. 验收标准
|
|
||||||
4. 覆盖率要求:≥90%
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Step 4: Parallel Development Execution**
|
- **Step 4: Parallel Development Execution**
|
||||||
- For each task in `dev-plan.md` run:
|
- For each task in `dev-plan.md`, invoke Codex with this brief:
|
||||||
```bash
|
```
|
||||||
uv run ~/.claude/skills/codex/scripts/codex.py "实现任务:[任务ID]
|
Task: [task-id]
|
||||||
|
Reference: @.claude/specs/{feature_name}/dev-plan.md
|
||||||
参考文档:@.claude/specs/{feature_name}/dev-plan.md
|
Scope: [task file scope]
|
||||||
|
Test: [test command]
|
||||||
你的职责:
|
Deliverables: code + unit tests + coverage ≥90% + coverage summary
|
||||||
1. 实现功能代码
|
|
||||||
2. 编写单元测试
|
|
||||||
3. 运行测试 + 覆盖率
|
|
||||||
4. 报告覆盖率结果
|
|
||||||
|
|
||||||
文件范围:[任务的文件范围]
|
|
||||||
测试命令:[任务指定的测试命令]
|
|
||||||
覆盖率目标:≥90%
|
|
||||||
" "gpt-5.1-codex"
|
|
||||||
```
|
```
|
||||||
- Execute independent tasks concurrently; serialize conflicting ones; track coverage reports
|
- Execute independent tasks concurrently; serialize conflicting ones; track coverage reports
|
||||||
|
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ This repository provides 4 ready-to-use Claude Code plugins that can be installe
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Install from GitHub repository
|
# Install from GitHub repository
|
||||||
/plugin github.com/cexll/myclaude
|
/plugin marketplace add cexll/myclaude
|
||||||
```
|
```
|
||||||
|
|
||||||
This will present all available plugins from the repository.
|
This will present all available plugins from the repository.
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Install everything with one command
|
# Install everything with one command
|
||||||
/plugin github.com/cexll/myclaude
|
/plugin marketplace add cexll/myclaude
|
||||||
```
|
```
|
||||||
|
|
||||||
### Option 2: Make Install
|
### Option 2: Make Install
|
||||||
|
|||||||
46
install.sh
Normal file
46
install.sh
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Detect platform
|
||||||
|
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
|
||||||
|
ARCH=$(uname -m)
|
||||||
|
|
||||||
|
# Normalize architecture names
|
||||||
|
case "$ARCH" in
|
||||||
|
x86_64) ARCH="amd64" ;;
|
||||||
|
aarch64|arm64) ARCH="arm64" ;;
|
||||||
|
*) echo "Unsupported architecture: $ARCH" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# Build download URL
|
||||||
|
REPO="cexll/myclaude"
|
||||||
|
VERSION="latest"
|
||||||
|
BINARY_NAME="codex-wrapper-${OS}-${ARCH}"
|
||||||
|
URL="https://github.com/${REPO}/releases/${VERSION}/download/${BINARY_NAME}"
|
||||||
|
|
||||||
|
echo "Downloading codex-wrapper from ${URL}..."
|
||||||
|
if ! curl -fsSL "$URL" -o /tmp/codex-wrapper; then
|
||||||
|
echo "ERROR: failed to download binary" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$HOME/bin"
|
||||||
|
|
||||||
|
mv /tmp/codex-wrapper "$HOME/bin/codex-wrapper"
|
||||||
|
chmod +x "$HOME/bin/codex-wrapper"
|
||||||
|
|
||||||
|
if "$HOME/bin/codex-wrapper" --version >/dev/null 2>&1; then
|
||||||
|
echo "codex-wrapper installed successfully to ~/bin/codex-wrapper"
|
||||||
|
else
|
||||||
|
echo "ERROR: installation verification failed" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ":$PATH:" != *":$HOME/bin:"* ]]; then
|
||||||
|
echo ""
|
||||||
|
echo "WARNING: ~/bin is not in your PATH"
|
||||||
|
echo "Add this line to your ~/.bashrc or ~/.zshrc:"
|
||||||
|
echo ""
|
||||||
|
echo " export PATH=\"\$HOME/bin:\$PATH\""
|
||||||
|
echo ""
|
||||||
|
fi
|
||||||
@@ -14,30 +14,51 @@ Execute Codex CLI commands and parse structured JSON responses. Supports file re
|
|||||||
- Complex code analysis requiring deep understanding
|
- Complex code analysis requiring deep understanding
|
||||||
- Large-scale refactoring across multiple files
|
- Large-scale refactoring across multiple files
|
||||||
- Automated code generation with safety controls
|
- Automated code generation with safety controls
|
||||||
- Tasks requiring specialized reasoning models (gpt-5.1, gpt-5.1-codex)
|
|
||||||
|
|
||||||
## Usage
|
## 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
|
```bash
|
||||||
uv run ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
codex-wrapper - [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
|
```bash
|
||||||
~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
codex-wrapper "simple task here" [working_dir]
|
||||||
# or
|
|
||||||
python3 ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Resume a session:
|
**Resume a session with HEREDOC:**
|
||||||
```bash
|
```bash
|
||||||
uv run ~/.claude/skills/codex/scripts/codex.py resume <session_id> "<task>" [model] [working_dir]
|
codex-wrapper 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
|
||||||
|
codex-wrapper - @'
|
||||||
|
task content
|
||||||
|
'@
|
||||||
|
```
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
- **CODEX_TIMEOUT**: Override timeout in milliseconds (default: 7200000 = 2 hours)
|
||||||
|
- Example: `export CODEX_TIMEOUT=3600000` for 1 hour
|
||||||
|
|
||||||
## Timeout Control
|
## Timeout Control
|
||||||
|
|
||||||
- **Built-in**: Script enforces 2-hour timeout by default
|
- **Built-in**: Binary enforces 2-hour timeout by default
|
||||||
- **Override**: Set `CODEX_TIMEOUT` environment variable (in milliseconds, e.g., `CODEX_TIMEOUT=3600000` for 1 hour)
|
- **Override**: Set `CODEX_TIMEOUT` environment variable (in milliseconds, e.g., `CODEX_TIMEOUT=3600000` for 1 hour)
|
||||||
- **Behavior**: On timeout, sends SIGTERM, then SIGKILL after 5s if process doesn't exit
|
- **Behavior**: On timeout, sends SIGTERM, then SIGKILL after 5s if process doesn't exit
|
||||||
- **Exit code**: Returns 124 on timeout (consistent with GNU timeout)
|
- **Exit code**: Returns 124 on timeout (consistent with GNU timeout)
|
||||||
@@ -46,9 +67,6 @@ uv run ~/.claude/skills/codex/scripts/codex.py resume <session_id> "<task>" [mod
|
|||||||
### Parameters
|
### Parameters
|
||||||
|
|
||||||
- `task` (required): Task description, supports `@file` references
|
- `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)
|
- `working_dir` (optional): Working directory (default: current)
|
||||||
|
|
||||||
### Return Format
|
### Return Format
|
||||||
@@ -66,64 +84,86 @@ Error format (stderr):
|
|||||||
ERROR: Error message
|
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
|
### 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:
|
Bash tool parameters:
|
||||||
- command: uv run ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
- command: codex-wrapper - [working_dir] <<'EOF'
|
||||||
|
<task content>
|
||||||
|
EOF
|
||||||
- timeout: 7200000
|
- timeout: 7200000
|
||||||
- description: <brief description of the task>
|
- 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.
|
Run every call in the foreground—never append `&` to background it—so logs and errors stay visible for timely interruption or diagnosis.
|
||||||
|
|
||||||
Alternatives:
|
**Important:** Use HEREDOC (`<<'EOF'`) for all but the simplest tasks. This prevents shell interpretation of quotes, variables, and special characters.
|
||||||
```
|
|
||||||
# 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]
|
|
||||||
```
|
|
||||||
|
|
||||||
### Examples
|
### Examples
|
||||||
|
|
||||||
**Basic code analysis:**
|
**Basic code analysis:**
|
||||||
```bash
|
```bash
|
||||||
# Recommended: via uv run (auto-manages Python environment)
|
# Recommended: with HEREDOC (handles any special characters)
|
||||||
uv run ~/.claude/skills/codex/scripts/codex.py "explain @src/main.ts"
|
codex-wrapper - <<'EOF'
|
||||||
|
explain @src/main.ts
|
||||||
|
EOF
|
||||||
# timeout: 7200000
|
# timeout: 7200000
|
||||||
|
|
||||||
# Alternative: direct execution
|
# Alternative: simple direct quoting (if task is simple)
|
||||||
~/.claude/skills/codex/scripts/codex.py "explain @src/main.ts"
|
codex-wrapper "explain @src/main.ts"
|
||||||
```
|
```
|
||||||
|
|
||||||
**Refactoring with specific model:**
|
**Refactoring with multiline instructions:**
|
||||||
```bash
|
```bash
|
||||||
uv run ~/.claude/skills/codex/scripts/codex.py "refactor @src/utils for performance" "gpt-5.1-codex"
|
codex-wrapper - <<'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
|
# timeout: 7200000
|
||||||
```
|
```
|
||||||
|
|
||||||
**Multi-file analysis:**
|
**Multi-file analysis:**
|
||||||
```bash
|
```bash
|
||||||
uv run ~/.claude/skills/codex/scripts/codex.py "analyze @. and find security issues" "gpt-5.1-codex" "/path/to/project"
|
codex-wrapper - "/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
|
# timeout: 7200000
|
||||||
```
|
```
|
||||||
|
|
||||||
**Resume previous session:**
|
**Resume previous session:**
|
||||||
```bash
|
```bash
|
||||||
# First session
|
# First session
|
||||||
uv run ~/.claude/skills/codex/scripts/codex.py "add comments to @utils.js" "gpt-5.1-codex"
|
codex-wrapper - <<'EOF'
|
||||||
|
add comments to @utils.js explaining the caching logic
|
||||||
|
EOF
|
||||||
# Output includes: SESSION_ID: 019a7247-ac9d-71f3-89e2-a823dbd8fd14
|
# Output includes: SESSION_ID: 019a7247-ac9d-71f3-89e2-a823dbd8fd14
|
||||||
|
|
||||||
# Continue the conversation
|
# Continue the conversation with more context
|
||||||
uv run ~/.claude/skills/codex/scripts/codex.py resume 019a7247-ac9d-71f3-89e2-a823dbd8fd14 "now add type hints"
|
codex-wrapper resume 019a7247-ac9d-71f3-89e2-a823dbd8fd14 - <<'EOF'
|
||||||
|
now add TypeScript type hints and handle edge cases where cache is null
|
||||||
|
EOF
|
||||||
# timeout: 7200000
|
# timeout: 7200000
|
||||||
```
|
```
|
||||||
|
|
||||||
**Using python3 directly (alternative):**
|
**Task with code snippets and special characters:**
|
||||||
```bash
|
```bash
|
||||||
python3 ~/.claude/skills/codex/scripts/codex.py "your task here"
|
codex-wrapper - <<'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
|
### Large Task Protocol
|
||||||
@@ -134,18 +174,16 @@ python3 ~/.claude/skills/codex/scripts/codex.py "your task here"
|
|||||||
|
|
||||||
| ID | Description | Scope | Dependencies | Tests | Command |
|
| 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" |
|
| T1 | Review @spec.md to extract requirements | docs/, @spec.md | None | None | `codex-wrapper - <<'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 "implement and test @src/module" |
|
| T2 | Implement the module and add test cases | src/module | T1 | npm test -- --runInBand | `codex-wrapper - <<'EOF'`<br/>`implement and test @src/module`<br/>`EOF` |
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
- **Recommended**: Use `uv run` for automatic Python environment management (requires uv installed)
|
- **Binary distribution**: Single Go binary, zero dependencies
|
||||||
- **Alternative**: Direct execution `./codex.py` (uses system Python via shebang)
|
- **Installation**: Download from GitHub Releases or use install.sh
|
||||||
- Python implementation using standard library (zero dependencies)
|
- **Cross-platform compatible**: Linux (amd64/arm64), macOS (amd64/arm64)
|
||||||
- All automated runs must use the Bash tool with the fixed timeout to provide dual timeout protection and unified logging/exit semantics; any alternative approach is limited to manual foreground execution.
|
- All automated runs must use the Bash tool with the fixed timeout to provide dual timeout protection and unified logging/exit semantics
|
||||||
- Cross-platform compatible (Windows/macOS/Linux)
|
for automation (new sessions only)
|
||||||
- PEP 723 compliant (inline script metadata)
|
|
||||||
- Runs with `--dangerously-bypass-approvals-and-sandbox` for automation (new sessions only)
|
|
||||||
- Uses `--skip-git-repo-check` to work in any directory
|
- Uses `--skip-git-repo-check` to work in any directory
|
||||||
- Streams progress, returns only final agent message
|
- Streams progress, returns only final agent message
|
||||||
- Every execution returns a session ID for resuming conversations
|
- Every execution returns a session ID for resuming conversations
|
||||||
|
|||||||
@@ -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.
|
**FIXED**: Auto-detect long inputs and use stdin mode to avoid shell argument issues.
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
New session: uv run codex.py "task" [model] [workdir]
|
New session: uv run codex.py "task" [workdir]
|
||||||
Resume: uv run codex.py resume <session_id> "task" [model] [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"
|
Alternative: python3 codex.py "task"
|
||||||
Direct exec: ./codex.py "task"
|
Direct exec: ./codex.py "task"
|
||||||
|
|
||||||
|
Model configuration: Set CODEX_MODEL environment variable (default: gpt-5.1-codex)
|
||||||
"""
|
"""
|
||||||
import subprocess
|
import subprocess
|
||||||
import json
|
import json
|
||||||
@@ -19,7 +23,7 @@ import sys
|
|||||||
import os
|
import os
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
DEFAULT_MODEL = 'gpt-5.1-codex'
|
DEFAULT_MODEL = os.environ.get('CODEX_MODEL', 'gpt-5.1-codex')
|
||||||
DEFAULT_WORKDIR = '.'
|
DEFAULT_WORKDIR = '.'
|
||||||
DEFAULT_TIMEOUT = 7200 # 2 hours in seconds
|
DEFAULT_TIMEOUT = 7200 # 2 hours in seconds
|
||||||
FORCE_KILL_DELAY = 5
|
FORCE_KILL_DELAY = 5
|
||||||
@@ -78,21 +82,23 @@ def parse_args():
|
|||||||
if len(sys.argv) < 4:
|
if len(sys.argv) < 4:
|
||||||
log_error('Resume mode requires: resume <session_id> <task>')
|
log_error('Resume mode requires: resume <session_id> <task>')
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
task_arg = sys.argv[3]
|
||||||
return {
|
return {
|
||||||
'mode': 'resume',
|
'mode': 'resume',
|
||||||
'session_id': sys.argv[2],
|
'session_id': sys.argv[2],
|
||||||
'task': sys.argv[3],
|
'task': task_arg,
|
||||||
'model': sys.argv[4] if len(sys.argv) > 4 else DEFAULT_MODEL,
|
'explicit_stdin': task_arg == '-',
|
||||||
'workdir': sys.argv[5] if len(sys.argv) > 5 else DEFAULT_WORKDIR
|
'workdir': sys.argv[4] if len(sys.argv) > 4 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_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]:
|
def read_piped_task() -> Optional[str]:
|
||||||
"""
|
"""
|
||||||
@@ -102,9 +108,16 @@ def read_piped_task() -> Optional[str]:
|
|||||||
"""
|
"""
|
||||||
stdin = sys.stdin
|
stdin = sys.stdin
|
||||||
if stdin is None or stdin.isatty():
|
if stdin is None or stdin.isatty():
|
||||||
|
log_info("Stdin is tty or None, skipping pipe read")
|
||||||
return None
|
return None
|
||||||
|
log_info("Reading from stdin pipe...")
|
||||||
data = stdin.read()
|
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:
|
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':
|
if params['mode'] == 'resume':
|
||||||
return [
|
return [
|
||||||
'codex', 'e',
|
'codex', 'e',
|
||||||
|
'-m', DEFAULT_MODEL,
|
||||||
'--skip-git-repo-check',
|
'--skip-git-repo-check',
|
||||||
'--json',
|
'--json',
|
||||||
'resume',
|
'resume',
|
||||||
@@ -146,7 +160,7 @@ def build_codex_args(params: dict, target_arg: str) -> list:
|
|||||||
else:
|
else:
|
||||||
base_args = [
|
base_args = [
|
||||||
'codex', 'e',
|
'codex', 'e',
|
||||||
'-m', params['model'],
|
'-m', DEFAULT_MODEL,
|
||||||
'--dangerously-bypass-approvals-and-sandbox',
|
'--dangerously-bypass-approvals-and-sandbox',
|
||||||
'--skip-git-repo-check',
|
'--skip-git-repo-check',
|
||||||
'-C', params['workdir'],
|
'-C', params['workdir'],
|
||||||
@@ -168,6 +182,7 @@ def run_codex_process(codex_args, task_text: str, use_stdin: bool, timeout_sec:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
# 启动 codex 子进程(文本模式管道)
|
# 启动 codex 子进程(文本模式管道)
|
||||||
|
log_info(f"Starting codex with args: {' '.join(codex_args[:5])}...")
|
||||||
process = subprocess.Popen(
|
process = subprocess.Popen(
|
||||||
codex_args,
|
codex_args,
|
||||||
stdin=subprocess.PIPE if use_stdin else None,
|
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,
|
text=True,
|
||||||
bufsize=1,
|
bufsize=1,
|
||||||
)
|
)
|
||||||
|
log_info(f"Process started with PID: {process.pid}")
|
||||||
|
|
||||||
# 如果使用 stdin 模式,写入任务到 stdin 并关闭
|
# 如果使用 stdin 模式,写入任务到 stdin 并关闭
|
||||||
if use_stdin and process.stdin is not None:
|
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.write(task_text)
|
||||||
|
process.stdin.flush() # 强制刷新缓冲区,避免大任务死锁
|
||||||
process.stdin.close()
|
process.stdin.close()
|
||||||
|
log_info("Stdin closed")
|
||||||
|
|
||||||
# 逐行解析 JSON 输出
|
# 逐行解析 JSON 输出
|
||||||
if process.stdout is None:
|
if process.stdout is None:
|
||||||
log_error('Codex stdout pipe not available')
|
log_error('Codex stdout pipe not available')
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
log_info("Reading stdout...")
|
||||||
|
|
||||||
for line in process.stdout:
|
for line in process.stdout:
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if not line:
|
if not line:
|
||||||
@@ -247,19 +268,34 @@ def run_codex_process(codex_args, task_text: str, use_stdin: bool, timeout_sec:
|
|||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
log_info("Script started")
|
||||||
params = parse_args()
|
params = parse_args()
|
||||||
|
log_info(f"Parsed args: mode={params['mode']}, task_len={len(params['task'])}")
|
||||||
timeout_sec = resolve_timeout()
|
timeout_sec = resolve_timeout()
|
||||||
|
log_info(f"Timeout: {timeout_sec}s")
|
||||||
|
|
||||||
piped_task = read_piped_task()
|
explicit_stdin = params.get('explicit_stdin', False)
|
||||||
piped = piped_task is not None
|
|
||||||
task_text = piped_task if piped else params['task']
|
|
||||||
|
|
||||||
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:
|
if use_stdin:
|
||||||
reasons = []
|
reasons = []
|
||||||
if piped:
|
if piped:
|
||||||
reasons.append('piped input')
|
reasons.append('piped input')
|
||||||
|
if explicit_stdin:
|
||||||
|
reasons.append('explicit "-"')
|
||||||
if '\n' in task_text:
|
if '\n' in task_text:
|
||||||
reasons.append('newline')
|
reasons.append('newline')
|
||||||
if '\\' in task_text:
|
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
|
- Alternative perspective on code problems
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
**Mandatory**: Run via uv with fixed timeout 7200000ms (foreground):
|
||||||
**推荐方式**(使用 uv run,自动管理 Python 环境):
|
|
||||||
```bash
|
```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
|
```bash
|
||||||
~/.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 -m <model> -p "<prompt>" [working_dir]
|
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
|
## Timeout Control
|
||||||
|
|
||||||
- **Built-in**: Script enforces 2-hour timeout by default
|
- **Fixed**: 7200000 milliseconds (2 hours), immutable
|
||||||
- **Override**: Set `GEMINI_TIMEOUT` environment variable (in milliseconds)
|
- **Bash tool**: Always set `timeout: 7200000` for double protection
|
||||||
- **Bash tool**: Always set `timeout: 7200000` parameter for double protection
|
|
||||||
|
|
||||||
### Parameters
|
### Parameters
|
||||||
|
|
||||||
- `-m, --model` (optional): Model to use (default: gemini-3-pro-preview)
|
- `prompt` (required): Task prompt or question
|
||||||
- `gemini-3-pro-preview`: Latest flagship model
|
- `working_dir` (optional): Working directory (default: current directory)
|
||||||
- `-p, --prompt` (required): Task prompt or question
|
|
||||||
- `working_dir` (optional): Working directory (default: current)
|
|
||||||
|
|
||||||
### Return Format
|
### Return Format
|
||||||
|
|
||||||
@@ -63,7 +64,7 @@ When calling via Bash tool, always include the timeout parameter:
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
Bash tool parameters:
|
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
|
- timeout: 7200000
|
||||||
- description: <brief description of the task>
|
- description: <brief description of the task>
|
||||||
```
|
```
|
||||||
@@ -72,10 +73,10 @@ Alternatives:
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# Direct execution (simplest)
|
# 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
|
# 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
|
### Examples
|
||||||
@@ -83,39 +84,28 @@ Alternatives:
|
|||||||
**Basic query:**
|
**Basic query:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Recommended: via uv run
|
uv run ~/.claude/skills/gemini/scripts/gemini.py "explain quantum computing"
|
||||||
uv run ~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "explain quantum computing"
|
|
||||||
# timeout: 7200000
|
# timeout: 7200000
|
||||||
|
|
||||||
# Alternative: direct execution
|
|
||||||
~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "explain quantum computing"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Code analysis:**
|
**Code analysis:**
|
||||||
|
|
||||||
```bash
|
```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
|
# timeout: 7200000
|
||||||
```
|
```
|
||||||
|
|
||||||
**With specific working directory:**
|
**With specific working directory:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
uv run ~/.claude/skills/gemini/scripts/gemini.py -m gemini-3-pro-preview -p "analyze project structure" "/path/to/project"
|
uv run ~/.claude/skills/gemini/scripts/gemini.py "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"
|
|
||||||
# timeout: 7200000
|
# timeout: 7200000
|
||||||
```
|
```
|
||||||
|
|
||||||
**Using python3 directly (alternative):**
|
**Using python3 directly (alternative):**
|
||||||
|
|
||||||
```bash
|
```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
|
## 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)
|
- Cross-platform compatible (Windows/macOS/Linux)
|
||||||
- PEP 723 compliant (inline script metadata)
|
- PEP 723 compliant (inline script metadata)
|
||||||
- Requires Gemini CLI installed and authenticated
|
- 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
|
- Output is streamed directly from Gemini CLI
|
||||||
|
|||||||
@@ -7,18 +7,18 @@
|
|||||||
Gemini CLI wrapper with cross-platform support.
|
Gemini CLI wrapper with cross-platform support.
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
uv run gemini.py -m <model> -p "<prompt>" [workdir]
|
uv run gemini.py "<prompt>" [workdir]
|
||||||
python3 gemini.py -m <model> -p "<prompt>"
|
python3 gemini.py "<prompt>"
|
||||||
./gemini.py -m gemini-3-pro-preview -p "your prompt"
|
./gemini.py "your prompt"
|
||||||
"""
|
"""
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
import argparse
|
|
||||||
|
|
||||||
DEFAULT_MODEL = 'gemini-3-pro-preview'
|
DEFAULT_MODEL = os.environ.get('GEMINI_MODEL', 'gemini-3-pro-preview')
|
||||||
DEFAULT_WORKDIR = '.'
|
DEFAULT_WORKDIR = '.'
|
||||||
DEFAULT_TIMEOUT = 7200 # 2 hours in seconds
|
TIMEOUT_MS = 7_200_000 # 固定 2 小时,毫秒
|
||||||
|
DEFAULT_TIMEOUT = TIMEOUT_MS // 1000
|
||||||
FORCE_KILL_DELAY = 5
|
FORCE_KILL_DELAY = 5
|
||||||
|
|
||||||
|
|
||||||
@@ -32,76 +32,56 @@ def log_warn(message: str):
|
|||||||
sys.stderr.write(f"WARN: {message}\n")
|
sys.stderr.write(f"WARN: {message}\n")
|
||||||
|
|
||||||
|
|
||||||
def resolve_timeout() -> int:
|
def log_info(message: str):
|
||||||
"""解析超时配置(秒)"""
|
"""输出信息到 stderr"""
|
||||||
raw = os.environ.get('GEMINI_TIMEOUT', '')
|
sys.stderr.write(f"INFO: {message}\n")
|
||||||
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 parse_args():
|
def parse_args():
|
||||||
"""解析命令行参数"""
|
"""解析位置参数"""
|
||||||
parser = argparse.ArgumentParser(
|
if len(sys.argv) < 2:
|
||||||
description='Gemini CLI wrapper for Claude Code integration',
|
log_error('Prompt required')
|
||||||
formatter_class=argparse.RawDescriptionHelpFormatter
|
sys.exit(1)
|
||||||
)
|
|
||||||
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)'
|
|
||||||
)
|
|
||||||
|
|
||||||
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:
|
def build_gemini_args(args) -> list:
|
||||||
"""构建 gemini CLI 参数"""
|
"""构建 gemini CLI 参数"""
|
||||||
return [
|
return [
|
||||||
'gemini',
|
'gemini',
|
||||||
'-m', args.model,
|
'-m', DEFAULT_MODEL,
|
||||||
'-p', args.prompt
|
'-p', args['prompt']
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
log_info('Script started')
|
||||||
args = parse_args()
|
args = parse_args()
|
||||||
|
log_info(f"Prompt length: {len(args['prompt'])}")
|
||||||
|
log_info(f"Working dir: {args['workdir']}")
|
||||||
gemini_args = build_gemini_args(args)
|
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:
|
try:
|
||||||
os.chdir(args.workdir)
|
os.chdir(args['workdir'])
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
log_error(f"Working directory not found: {args.workdir}")
|
log_error(f"Working directory not found: {args['workdir']}")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
except PermissionError:
|
except PermissionError:
|
||||||
log_error(f"Permission denied: {args.workdir}")
|
log_error(f"Permission denied: {args['workdir']}")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
log_info('Changed working directory')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
log_info(f"Starting gemini with model {DEFAULT_MODEL}")
|
||||||
|
process = None
|
||||||
# 启动 gemini 子进程,直接透传 stdout 和 stderr
|
# 启动 gemini 子进程,直接透传 stdout 和 stderr
|
||||||
process = subprocess.Popen(
|
process = subprocess.Popen(
|
||||||
gemini_args,
|
gemini_args,
|
||||||
@@ -112,11 +92,9 @@ def main():
|
|||||||
)
|
)
|
||||||
|
|
||||||
# 实时输出 stdout
|
# 实时输出 stdout
|
||||||
stdout_lines = []
|
|
||||||
for line in process.stdout:
|
for line in process.stdout:
|
||||||
sys.stdout.write(line)
|
sys.stdout.write(line)
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
stdout_lines.append(line)
|
|
||||||
|
|
||||||
# 等待进程结束
|
# 等待进程结束
|
||||||
returncode = process.wait(timeout=timeout_sec)
|
returncode = process.wait(timeout=timeout_sec)
|
||||||
@@ -135,11 +113,12 @@ def main():
|
|||||||
|
|
||||||
except subprocess.TimeoutExpired:
|
except subprocess.TimeoutExpired:
|
||||||
log_error(f'Gemini execution timeout ({timeout_sec}s)')
|
log_error(f'Gemini execution timeout ({timeout_sec}s)')
|
||||||
process.kill()
|
if process is not None:
|
||||||
try:
|
process.kill()
|
||||||
process.wait(timeout=FORCE_KILL_DELAY)
|
try:
|
||||||
except subprocess.TimeoutExpired:
|
process.wait(timeout=FORCE_KILL_DELAY)
|
||||||
pass
|
except subprocess.TimeoutExpired:
|
||||||
|
pass
|
||||||
sys.exit(124)
|
sys.exit(124)
|
||||||
|
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
@@ -148,11 +127,12 @@ def main():
|
|||||||
sys.exit(127)
|
sys.exit(127)
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
process.terminate()
|
if process is not None:
|
||||||
try:
|
process.terminate()
|
||||||
process.wait(timeout=FORCE_KILL_DELAY)
|
try:
|
||||||
except subprocess.TimeoutExpired:
|
process.wait(timeout=FORCE_KILL_DELAY)
|
||||||
process.kill()
|
except subprocess.TimeoutExpired:
|
||||||
|
process.kill()
|
||||||
sys.exit(130)
|
sys.exit(130)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user