diff --git a/README.md b/README.md index df2737c..b8a9a06 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ Manual steps: [AGENTS.md](AGENTS.md). - **Nothing per turn.** There are no hooks and one small always-on rule (`rules/ccg-codegraph.md`). Skills (`frontend-design`, `scrapling`, `seo-page-builder`, `bt-panel`, `adsense-site-auditor`) load only when called. Output styles keep Claude Code's built-in coding instructions. - **One main loop.** Claude plans, decides and talks to you; no router sits in front of it. -- **Other models only where they earn it:** scoped writing, or a second opinion in a fresh session. Codex-led mode (`node bin/ccg.mjs codex-mode install`) and every wrapper backend (`codex`, `claude`, `gemini`, `antigravity`, `grok`, `kimi`, `opencode`) are kept; DeepSeek Harness as a host is not. +- **Other models only where they earn it:** scoped writing, or a second opinion in a fresh session. Codex-led mode (`node bin/ccg.mjs codex-mode install`) and every wrapper backend (`codex`, `claude`, `gemini`, `antigravity`, `grok`, `kimi`, `opencode`, `pi`) are kept; Pi uses structured RPC, resumable sessions, and Pi-owned provider/context configuration ([setup](docs/pi-backend.md)); DeepSeek Harness as a host is not. Design rules: [PRINCIPLES.md](PRINCIPLES.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index 25432c3..e5ac531 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -139,7 +139,7 @@ Install OpenSlime from https://github.com/Overbaker/OpenSlime. Follow AGENTS.md - **不做每轮注入。** 没有 hook,只有一个很小的常驻规则(`rules/ccg-codegraph.md`)。技能(`frontend-design`、`scrapling`、`seo-page-builder`、`bt-panel`、`adsense-site-auditor`)只在调用时加载。输出样式保留 Claude Code 内置的编码规范。 - **单一主循环。** Claude 负责规划、决策并与你对话,前面没有路由层。 - **外部模型只用在值得的地方:** 限定范围的编写,或者在新会话里给出第二意见。 - - 保留:Codex 主导模式(`node bin/ccg.mjs codex-mode install`),以及全部 wrapper 后端(`codex`、`claude`、`gemini`、`antigravity`、`grok`、`kimi`、`opencode`)。 + - 保留:Codex 主导模式(`node bin/ccg.mjs codex-mode install`),以及全部 wrapper 后端(`codex`、`claude`、`gemini`、`antigravity`、`grok`、`kimi`、`opencode`、`pi`)。Pi 使用结构化 RPC 和可恢复 session;provider 与上下文窗口由 Pi 配置,[详见接入说明](docs/pi-backend.zh-CN.md)。 - 不支持:把 DeepSeek Harness 作为宿主。 设计原则见 [PRINCIPLES.md](PRINCIPLES.md)。 diff --git a/codeagent-wrapper/CLAUDE.md b/codeagent-wrapper/CLAUDE.md index e6b52eb..7df3913 100644 --- a/codeagent-wrapper/CLAUDE.md +++ b/codeagent-wrapper/CLAUDE.md @@ -3,14 +3,14 @@ > [根目录](../CLAUDE.md) > **codeagent-wrapper** **Last Updated**: 2026-08-29 -**Binary Version**: v5.15.0 +**Binary Version**: v5.16.0 **Go Version**: 1.21+(`go.mod:1`) --- ## 模块职责 -`codeagent-wrapper` 是用 Go 编写的跨平台 CLI 包装器,通过 `Backend` 接口 + `backendRegistry` 工厂将 **7 种 AI CLI 后端**(Codex / Gemini / Claude / Grok / Kimi / OpenCode / Antigravity)统一成一个标准接口。CCG 工作流系统中的 20+ 个斜杠命令通过调用它来执行多模型协作任务——Claude 作为编排层,codeagent-wrapper 负责实际派发、执行、输出解析和会话管理。 +`codeagent-wrapper` 是用 Go 编写的跨平台 CLI 包装器,通过 `Backend` 接口 + `backendRegistry` 工厂将 **8 种 AI CLI 后端**(Codex / Gemini / Claude / Grok / Kimi / OpenCode / Antigravity / Pi)统一成一个标准接口。CCG 工作流系统中的 20+ 个斜杠命令通过调用它来执行多模型协作任务——Claude 作为编排层,codeagent-wrapper 负责实际派发、执行、输出解析和会话管理。 --- @@ -25,10 +25,10 @@ ```bash # 单任务模式(新会话) -codeagent-wrapper [--backend ] "任务文本" [工作目录] +codeagent-wrapper [--backend ] "任务文本" [工作目录] # stdin 模式(处理含换行/特殊字符的任务) -codeagent-wrapper [--backend ] - [工作目录] <<'EOF' +codeagent-wrapper [--backend ] - [工作目录] <<'EOF' 任务文本 EOF @@ -48,7 +48,8 @@ codeagent-wrapper --cleanup | Flag | 说明 | 默认值 | |------|------|--------| -| `--backend ` | 指定后端:`codex`、`gemini`、`claude` | `codex` | +| `--backend ` | 指定后端:`codex`、`gemini`、`claude`、`antigravity`、`grok`、`kimi`、`opencode`、`pi` | `codex` | +| `--pi-model ` | Pi 的 `provider/model` 或唯一模型 ID;也可用 `PI_MODEL`。长上下文/provider 配置由 Pi 管理 | 空(Pi 默认) | | `--gemini-model ` | Gemini 型号(仅 gemini 后端有效) | 空(后端默认) | | `--progress` | 向 stderr 输出紧凑进度行 | 关 | | `--with-mcp` | 让子代理加载 MCP servers。默认跳过:grok/kimi 走影子 HOME(v3.3.0),codex 注入 `-c mcp_servers={}`、gemini 注入哨兵 allowlist(v5.15.0)。⚠ **见下方「谁必须开这个 flag」** | 关 | @@ -90,6 +91,8 @@ diff、明令禁改文件)与修正调用(按 file:line 改)**不开**, | `CODEAGENT_POST_MESSAGE_DELAY` | agent_message 后等待秒数(0-60) | 5s | | `CODEAGENT_MAX_PARALLEL_WORKERS` | 并行 worker 上限(0=不限) | 0 | | `GEMINI_MODEL` | Gemini 型号(低优先级,CLI 参数覆盖) | 空 | +| `PI_MODEL` | Pi 模型,CLI `--pi-model` 优先;并行模式通过此变量选择 | 空 | +| `CODEAGENT_PI_COMMAND` | 覆盖 Pi 可执行文件(测试/自定义安装) | `pi` | ### 退出码 @@ -129,8 +132,9 @@ type Backend interface { | `kimi` | `kimi` | `buildKimiArgs()` | | `opencode` | `opencode` | `buildOpencodeArgs()` | | `antigravity` / `agy` | `agy` | `buildAntigravityArgs()` | +| `pi` | `pi` | `PiBackend.BuildArgs()` | -**加一个后端**:主路径干净 —— 在 `backend.go` 写个 struct 实现 `Backend` 三方法 + 在 `config.go` 的 `backendRegistry` 注册一行即可。此外需手动碰约 12 处后端字符串特判:`server.go`(SSE 输出格式,~4 处)、`executor.go`(stdin/prompt 传递方式 `line 877-878`、`case "codex"` `line 1018`,~4 处)、`main.go`(flag 校验,~4 处)。`parser.go` 已统一(靠 JSON 事件形状识别后端,0 处特判)。若加后端变频繁,可给 `Backend` 接口加 `PromptMode()` / `SSEFormat()` 把这 12 处也收编——半天~1 天渐进重构,非大工程。 +**加一个后端**:主路径干净 —— 在 `backend.go` 写个 struct 实现 `Backend` 三方法 + 在 `config.go` 的 `backendRegistry` 注册一行即可。此外需手动碰约 12 处后端字符串特判:`server.go`(SSE 输出格式,~4 处)、`executor.go`(stdin/prompt 传递方式 `line 877-878`、`case "codex"` `line 1018`,~4 处)、`main.go`(flag 校验,~4 处)。Pi 使用独立 `pi_parser.go` 解析 RPC,其余后端的 `parser.go` 靠 JSON 事件形状识别(0 处特判)。若加后端变频繁,可给 `Backend` 接口加 `PromptMode()` / `SSEFormat()` 把这 12 处也收编——半天~1 天渐进重构,非大工程。 ### stdin 传递协议 @@ -138,6 +142,15 @@ type Backend interface { - 换行 `\n`、反斜杠 `\`、双引号 `"`、单引号 `'`、反引号 `` ` ``、`$` - 或任务文本长度 > 800 字符 +Pi 始终使用 JSONL RPC stdin 发送 `get_state` 和 `prompt`,任务不会作为 argv 传给 Pi, +所以 multiline、`@` 前缀和 shell 符号均按字面量处理。`get_state` 用于发现 session ID, +`prompt` 的 response 仅表示已接收;以 `agent_settled` 为完成信号,再关闭 stdin。 +assistant `text_delta` 持续流式返回,最终 assistant message 提供完整结果。RPC 拒绝、 +provider 错误、重试耗尽、`error`/`aborted` stop reason 和读取错误均使任务退出非零。 +resume 通过 `--session ` 恢复。启动时默认禁用 extensions、skills、prompt templates +和 MCP,RPC 是本地子进程(provider 可以本地或远程),并非远程 Pi server transport。 +完整用户说明见 [Pi RPC 后端](../docs/pi-backend.zh-CN.md)。 + Gemini 平台差异(`executor.go:864`): - **macOS/Linux**:`-p "<任务文本>"` 直接传参(execve 保留多行 argv) - **Windows**:omit `-p`,通过 stdin pipe 传入(cmd.exe 会截断多行参数,Issue #129) @@ -185,7 +198,7 @@ id: task-b | 文件 | 职责 | |------|------| -| `backend.go` | `Backend` 接口;7 个实现 `CodexBackend` / `GeminiBackend` / `ClaudeBackend` / `GrokBackend` / `KimiBackend` / `OpencodeBackend` / `AntigravityBackend`;各自 `buildXxxArgs()`;`loadMinimalEnvSettings()` 读取 `~/.claude/settings.json` 注入环境变量 | +| `backend.go` | `Backend` 接口;7 个原有实现 `CodexBackend` / `GeminiBackend` / `ClaudeBackend` / `GrokBackend` / `KimiBackend` / `OpencodeBackend` / `AntigravityBackend`;各自 `buildXxxArgs()`;`loadMinimalEnvSettings()` 读取 `~/.claude/settings.json` 注入环境变量 | ### 执行层 @@ -204,6 +217,8 @@ id: task-b | 文件 | 职责 | |------|------| +| `pi.go` | 第 8 个 `PiBackend`;严格 RPC 参数,包含 `--session`、`--model` 和确定性隔离 flags;`buildPiRPCInput()` 序列化 stdin | +| `pi_parser.go` | `parsePiRPCStream()`——RPC 状态、错误、token/工具进度和 settled 完成协议 | | `parser.go` | `parseJSONStreamInternal()`——流式解析 Codex / Claude / Gemini JSON 事件;提取 `agent_message`、`session_id`;支持进度回调 `onProgressCallback`、session 回调 `onSessionStartedCallback` | | `filter.go` | `filteringWriter`——过滤 stderr 噪声行(`[STARTUP]`、`YOLO mode`、Node.js warning 等) | @@ -297,8 +312,8 @@ bash build-all.sh | 文件 | 位置 | 当前值 | |------|------|--------| -| `codeagent-wrapper/main.go` | `version = "..."` (`main.go:17`) | `5.15.0` | -| `src/utils/installer.ts` | `EXPECTED_BINARY_VERSION = '...'` | `5.15.0` | +| `codeagent-wrapper/main.go` | `version = "..."` (`main.go:17`) | `5.16.0` | +| `src/utils/installer.ts` | `EXPECTED_BINARY_VERSION = '...'` | `5.16.0` | 两边不一致的后果:用户运行 `npx ccg-workflow update` 时无法触发 binary 重新下载,继续使用旧版 binary。 diff --git a/codeagent-wrapper/config.go b/codeagent-wrapper/config.go index 9fb8b4a..5a63b76 100644 --- a/codeagent-wrapper/config.go +++ b/codeagent-wrapper/config.go @@ -24,6 +24,7 @@ type Config struct { GrokModel string // Grok model name (empty = use default) KimiModel string // Kimi model alias (empty = use default) OpencodeModel string // Opencode model as provider/model (empty = use default) + PiModel string // Pi model as provider/model or unique model ID (empty = use default) Progress bool // Emit compact progress lines to stderr WithMCP bool // Let the sub-agent load Claude's MCP servers (slow; off by default) } @@ -49,6 +50,7 @@ type TaskSpec struct { GrokModel string `json:"-"` KimiModel string `json:"-"` OpencodeModel string `json:"-"` + PiModel string `json:"-"` WithMCP bool `json:"-"` Context context.Context `json:"-"` } @@ -81,6 +83,7 @@ var backendRegistry = map[string]Backend{ "grok": GrokBackend{}, "kimi": KimiBackend{}, "opencode": OpencodeBackend{}, + "pi": PiBackend{}, } func selectBackend(name string) (Backend, error) { @@ -219,6 +222,7 @@ func parseArgs() (*Config, error) { grokModel := strings.TrimSpace(os.Getenv("GROK_MODEL")) kimiModel := strings.TrimSpace(os.Getenv("KIMI_MODEL")) opencodeModel := strings.TrimSpace(os.Getenv("OPENCODE_MODEL")) + piModel := strings.TrimSpace(os.Getenv("PI_MODEL")) withMCP := envFlagEnabled("CODEAGENT_WITH_MCP") backendName := defaultBackendName @@ -310,6 +314,24 @@ func parseArgs() (*Config, error) { } opencodeModel = value continue + case arg == "--pi-model": + if i+1 >= len(args) { + return nil, fmt.Errorf("--pi-model flag requires a non-empty model name") + } + value := strings.TrimSpace(args[i+1]) + if value == "" { + return nil, fmt.Errorf("--pi-model flag requires a non-empty model name") + } + piModel = value + i++ + continue + case strings.HasPrefix(arg, "--pi-model="): + value := strings.TrimSpace(strings.TrimPrefix(arg, "--pi-model=")) + if value == "" { + return nil, fmt.Errorf("--pi-model flag requires a non-empty model name") + } + piModel = value + continue case arg == "--with-mcp": withMCP = true continue @@ -341,7 +363,11 @@ func parseArgs() (*Config, error) { } args = filtered - cfg := &Config{WorkDir: defaultWorkdir, Backend: backendName, SkipPermissions: skipPermissions, GeminiModel: geminiModel, GrokModel: grokModel, KimiModel: kimiModel, OpencodeModel: opencodeModel, Progress: progress, WithMCP: withMCP} + if backendName == "pi" && strings.HasPrefix(piModel, "-") { + return nil, fmt.Errorf("--pi-model requires a model name that does not start with '-'") + } + + cfg := &Config{WorkDir: defaultWorkdir, Backend: backendName, SkipPermissions: skipPermissions, GeminiModel: geminiModel, GrokModel: grokModel, KimiModel: kimiModel, OpencodeModel: opencodeModel, PiModel: piModel, Progress: progress, WithMCP: withMCP} cfg.MaxParallelWorkers = resolveMaxParallelWorkers() if args[0] == "resume" { diff --git a/codeagent-wrapper/executor.go b/codeagent-wrapper/executor.go index b633ac0..ca29445 100644 --- a/codeagent-wrapper/executor.go +++ b/codeagent-wrapper/executor.go @@ -205,6 +205,7 @@ var newCommandRunner = func(ctx context.Context, name string, args ...string) co type parseResult struct { message string threadID string + err error } type taskLoggerContextKey struct{} @@ -832,6 +833,19 @@ func runCodexTaskWithContext(parentCtx context.Context, taskSpec TaskSpec, backe injectedLogger := taskLoggerFromContext(parentCtx) logger := injectedLogger + // Empty/default follows the established commandContext, codexCommand, and + // buildCodexArgsFn test/injection hooks. A non-default task backend must + // instead resolve both its executable and argument builder from the registry. + if backend == nil && taskSpec.Backend != "" && !strings.EqualFold(strings.TrimSpace(taskSpec.Backend), defaultBackendName) { + selected, err := selectBackend(taskSpec.Backend) + if err != nil { + result.ExitCode = 1 + result.Error = err.Error() + return result + } + backend = selected + } + cfg := &Config{ Mode: taskSpec.Mode, Task: taskSpec.Task, @@ -843,6 +857,7 @@ func runCodexTaskWithContext(parentCtx context.Context, taskSpec TaskSpec, backe GrokModel: taskSpec.GrokModel, KimiModel: taskSpec.KimiModel, OpencodeModel: taskSpec.OpencodeModel, + PiModel: taskSpec.PiModel, WithMCP: taskSpec.WithMCP, } @@ -852,8 +867,6 @@ func runCodexTaskWithContext(parentCtx context.Context, taskSpec TaskSpec, backe commandName = backend.Command() argsBuilder = backend.BuildArgs cfg.Backend = backend.Name() - } else if taskSpec.Backend != "" { - cfg.Backend = taskSpec.Backend } else if commandName != "" { cfg.Backend = commandName } @@ -872,6 +885,12 @@ func runCodexTaskWithContext(parentCtx context.Context, taskSpec TaskSpec, backe } useStdin := taskSpec.UseStdin + rpcBackend := cfg.Backend == "pi" + if rpcBackend { + // Pi receives both get_state and prompt RPC commands on stdin. Keeping + // the prompts out of argv also avoids @file expansion and argv limits. + useStdin = true + } targetArg := taskSpec.Task // Gemini/Antigravity CLI does not support "-" as stdin marker for -p flag. @@ -1022,7 +1041,7 @@ func runCodexTaskWithContext(parentCtx context.Context, taskSpec TaskSpec, backe // API keys are already protected via cmd.SetEnv() from loadMinimalEnvSettings(). // Project dir is also passed via --include-directories in buildGeminiArgs(). // - Claude: uses cmd.Dir as project context (no .env loading issue). - if cfg.Mode != "resume" && cfg.WorkDir != "" { + if cfg.WorkDir != "" && (cfg.Mode != "resume" || rpcBackend) { switch commandName { case "codex": // Codex uses -C flag, don't set cmd.Dir @@ -1061,6 +1080,41 @@ func runCodexTaskWithContext(parentCtx context.Context, taskSpec TaskSpec, backe } } + var stdinWriteDone chan struct{} + var stdinWriteError error + var rpcInputCompleted bool + var rpcInputError error + if rpcBackend { + stdinWriteDone = make(chan struct{}) + } + + var stdinCloseOnce sync.Once + closeStdin := func() { + stdinCloseOnce.Do(func() { + if stdinPipe != nil { + _ = stdinPipe.Close() + } + }) + } + defer closeStdin() + + // RPC settlement and the stdin JSON encode happen independently. Wait for + // the complete request before closing stdin or publishing the parsed result. + // Cancellation still closes immediately through closeStdin to unblock writes. + closeRPCStdinAfterWrite := func() { + if stdinWriteDone == nil { + closeStdin() + return + } + select { + case <-stdinWriteDone: + rpcInputCompleted = true + rpcInputError = stdinWriteError + case <-ctx.Done(): + } + closeStdin() + } + stdout, err := cmd.StdoutPipe() if err != nil { logErrorFn("Failed to create stdout pipe: " + err.Error()) @@ -1156,6 +1210,35 @@ func runCodexTaskWithContext(parentCtx context.Context, taskSpec TaskSpec, backe return } + if rpcBackend { + parsed := parsePiRPCStream(stdoutReader, logWarnFn, logInfoFn, piStreamCallbacks{ + onMessage: func() { + select { + case messageSeen <- struct{}{}: + default: + } + }, + onComplete: func() { + select { + case completeSeen <- struct{}{}: + default: + } + closeRPCStdinAfterWrite() + if globalWebServer != nil && webSessionID != "" { + globalWebServer.EndSession(webSessionID, cfg.Backend) + } + }, + onContent: onContentCallback, + onProgress: onProgressCallback, + onSessionStarted: onSessionStartedCallback, + }) + // agent_settled has already signalled completion above. Signalling + // again here can start the forced-stop timer before this result is + // collected when the operation has a short timeout. + parseCh <- parsed + return + } + msg, tid := parseJSONStreamInternalWithContent(stdoutReader, logWarnFn, logInfoFn, func() { select { case messageSeen <- struct{}{}: @@ -1202,10 +1285,32 @@ func runCodexTaskWithContext(parentCtx context.Context, taskSpec TaskSpec, backe if useStdin && stdinPipe != nil { logInfoFn(fmt.Sprintf("Writing %d chars to stdin...", len(taskSpec.Task))) go func(data string) { - defer stdinPipe.Close() + if rpcBackend { + defer close(stdinWriteDone) + input, marshalErr := buildPiRPCInput(data) + if marshalErr != nil { + stdinWriteError = marshalErr + logErrorFn("Failed to encode Pi RPC prompt: " + marshalErr.Error()) + closeStdin() + return + } + if _, writeErr := io.WriteString(stdinPipe, input); writeErr != nil { + stdinWriteError = writeErr + logWarnFn("Failed to write Pi RPC prompt: " + writeErr.Error()) + closeStdin() + } + // Unlike one-shot CLIs, Pi RPC stays alive until the assistant + // settles. The parser closes stdin from onComplete. + return + } + defer closeStdin() _, _ = io.WriteString(stdinPipe, data) }(taskSpec.Task) - logInfoFn("Stdin closed") + if rpcBackend { + logInfoFn("Pi RPC commands written; stdin remains open until agent_settled") + } else { + logInfoFn("Stdin closed") + } } waitCh := make(chan error, 1) @@ -1314,7 +1419,11 @@ waitLoop: closeWithReason(stdout, stdoutCloseReasonCtx) parsed = <-parseCh case messageSeenObserved || completeSeenObserved: - closeWithReason(stdout, stdoutCloseReasonWait) + // RPC stdout is an event stream, not a free-form text pipe. Let Pi + // consume agent_settled and EOF before closing its transport. + if !rpcBackend { + closeWithReason(stdout, stdoutCloseReasonWait) + } parsed = <-parseCh default: drainTimer := time.NewTimer(stdoutDrainTimeout) @@ -1325,11 +1434,15 @@ waitLoop: closeWithReason(stdout, stdoutCloseReasonWait) case <-messageSeen: messageSeenObserved = true - closeWithReason(stdout, stdoutCloseReasonWait) + if !rpcBackend { + closeWithReason(stdout, stdoutCloseReasonWait) + } parsed = <-parseCh case <-completeSeen: completeSeenObserved = true - closeWithReason(stdout, stdoutCloseReasonWait) + if !rpcBackend { + closeWithReason(stdout, stdoutCloseReasonWait) + } parsed = <-parseCh case <-drainTimer.C: closeWithReason(stdout, stdoutCloseReasonDrain) @@ -1337,6 +1450,12 @@ waitLoop: } } + // onComplete publishes these values before parseCh is sent. A successful + // assistant message must not conceal an incomplete RPC request. + if rpcBackend && rpcInputCompleted && rpcInputError != nil && parsed.err == nil { + parsed.err = fmt.Errorf("write Pi RPC stdin: %w", rpcInputError) + } + if ctxErr := ctx.Err(); ctxErr != nil { if errors.Is(ctxErr, context.DeadlineExceeded) { result.ExitCode = 124 @@ -1348,6 +1467,13 @@ waitLoop: return result } + if parsed.err != nil { + logErrorFn(parsed.err.Error()) + result.ExitCode = 1 + result.Error = attachStderr(parsed.err.Error()) + return result + } + if waitErr != nil { if forcedAfterComplete && parsed.message != "" { logWarnFn(fmt.Sprintf("%s terminated after delivering output", commandName)) diff --git a/codeagent-wrapper/main.go b/codeagent-wrapper/main.go index a729893..d730ea9 100644 --- a/codeagent-wrapper/main.go +++ b/codeagent-wrapper/main.go @@ -14,7 +14,7 @@ import ( ) const ( - version = "5.15.0" + version = "5.16.0" defaultWorkdir = "." defaultTimeout = 7200 // seconds (2 hours) defaultCoverageTarget = 90.0 @@ -233,7 +233,7 @@ func run() (exitCode int) { case arg == "--with-mcp": withMCPInParallel = true continue - case arg == "--gemini-model", arg == "--grok-model", arg == "--kimi-model", arg == "--opencode-model": + case arg == "--gemini-model", arg == "--grok-model", arg == "--kimi-model", arg == "--opencode-model", arg == "--pi-model": // Bare form carries its value in the next arg — consume it too, // otherwise the value lands in extras and hard-fails the run. geminiModelInParallel = true @@ -241,7 +241,7 @@ func run() (exitCode int) { i++ } continue - case strings.HasPrefix(arg, "--gemini-model="), strings.HasPrefix(arg, "--grok-model="), strings.HasPrefix(arg, "--kimi-model="), strings.HasPrefix(arg, "--opencode-model="): + case strings.HasPrefix(arg, "--gemini-model="), strings.HasPrefix(arg, "--grok-model="), strings.HasPrefix(arg, "--kimi-model="), strings.HasPrefix(arg, "--opencode-model="), strings.HasPrefix(arg, "--pi-model="): geminiModelInParallel = true continue default: @@ -251,7 +251,7 @@ func run() (exitCode int) { // Warn about unsupported parameter if geminiModelInParallel { - logWarn("--gemini-model/--grok-model parameters are not supported in parallel mode") + logWarn("backend-specific model parameters are not supported in parallel mode") } if len(extras) > 0 { @@ -399,6 +399,12 @@ func run() (exitCode int) { if cfg.GrokModel != "" && cfg.Backend != "grok" { logWarn("--grok-model parameter is only effective with --backend grok") } + if cfg.PiModel != "" && cfg.Backend == "pi" { + logInfo(fmt.Sprintf("Using Pi model: %s", cfg.PiModel)) + } + if cfg.PiModel != "" && cfg.Backend != "pi" { + logWarn("--pi-model parameter is only effective with --backend pi") + } timeoutSec := resolveTimeout() logInfo(fmt.Sprintf("Timeout: %ds", timeoutSec)) @@ -514,10 +520,22 @@ func run() (exitCode int) { GrokModel: cfg.GrokModel, KimiModel: cfg.KimiModel, OpencodeModel: cfg.OpencodeModel, + PiModel: cfg.PiModel, WithMCP: cfg.WithMCP, } - result := runTaskFn(taskSpec, false, cfg.Timeout) + selectedTaskRunner := runTaskFn + if backend.Name() != defaultBackendName && reflect.ValueOf(runTaskFn).Pointer() == reflect.ValueOf(runCodexTask).Pointer() { + // The default runner resolves task-specific backends in its executor path. + // Preserve a selected non-default backend for a single run, including test + // backends supplied through selectBackendFn. The default backend continues + // through runTaskFn and its established command/argument injection hooks. + // Custom runTaskFn hooks retain their signature and take precedence unchanged. + selectedTaskRunner = func(spec TaskSpec, silent bool, timeout int) TaskResult { + return runCodexTaskWithContext(nil, spec, backend, nil, false, silent, timeout) + } + } + result := selectedTaskRunner(taskSpec, false, cfg.Timeout) if result.ExitCode != 0 { return result.ExitCode @@ -604,7 +622,8 @@ Parallel mode examples: Options: --lite, -L Lite mode: disable Web UI, faster response - --backend Select backend (codex, gemini, claude) + --backend Select backend (codex, gemini, claude, antigravity, grok, kimi, opencode, pi) + --pi-model Specify Pi provider/model or unique model ID (or PI_MODEL) --gemini-model Specify Gemini model (gemini backend only) Can also be set via GEMINI_MODEL environment variable CLI parameter takes precedence over environment variable @@ -615,6 +634,8 @@ Environment Variables: CODEX_TIMEOUT Timeout in milliseconds (default: 7200000) CODEX_REQUIRE_APPROVAL Require manual approval for file operations (default: false) CODEX_DISABLE_SKIP_GIT_CHECK Disable skip-git-repo-check flag (default: false) + PI_MODEL Pi provider/model or unique model ID (--pi-model overrides) + CODEAGENT_PI_COMMAND Override Pi executable (default: pi) CODEAGENT_ASCII_MODE Use ASCII symbols instead of Unicode (PASS/WARN/FAIL) CODEAGENT_LITE_MODE Enable lite mode (true/false) diff --git a/codeagent-wrapper/main_test.go b/codeagent-wrapper/main_test.go index 5596841..f251275 100644 --- a/codeagent-wrapper/main_test.go +++ b/codeagent-wrapper/main_test.go @@ -3055,7 +3055,7 @@ func TestVersionFlag(t *testing.T) { } }) - want := "codeagent-wrapper version 5.15.0\n" + want := "codeagent-wrapper version 5.16.0\n" if output != want { t.Fatalf("output = %q, want %q", output, want) @@ -3071,7 +3071,7 @@ func TestVersionShortFlag(t *testing.T) { } }) - want := "codeagent-wrapper version 5.15.0\n" + want := "codeagent-wrapper version 5.16.0\n" if output != want { t.Fatalf("output = %q, want %q", output, want) @@ -3087,7 +3087,7 @@ func TestVersionLegacyAlias(t *testing.T) { } }) - want := "codex-wrapper version 5.15.0\n" + want := "codex-wrapper version 5.16.0\n" if output != want { t.Fatalf("output = %q, want %q", output, want) diff --git a/codeagent-wrapper/pi.go b/codeagent-wrapper/pi.go new file mode 100644 index 0000000..9e33fe4 --- /dev/null +++ b/codeagent-wrapper/pi.go @@ -0,0 +1,64 @@ +package main + +import ( + "encoding/json" + "os" + "strings" +) + +// PiBackend runs Pi as a local JSON-RPC process. Pi itself can use any of its +// configured local or remote model providers; that provider connection does not +// change the wrapper's process lifecycle. +type PiBackend struct{} + +func (PiBackend) Name() string { return "pi" } + +func (PiBackend) Command() string { + if cmd := strings.TrimSpace(os.Getenv("CODEAGENT_PI_COMMAND")); cmd != "" { + return cmd + } + return "pi" +} + +func (PiBackend) BuildArgs(cfg *Config, targetArg string) []string { + return buildPiArgs(cfg, targetArg) +} + +func buildPiArgs(cfg *Config, _ string) []string { + if cfg == nil { + return nil + } + + // Prompts are sent through the RPC prompt command, never argv. In + // particular, this avoids Pi interpreting an @file argument or cmd.exe + // modifying a multiline prompt. Interactive extensions are disabled because + // RPC callers cannot answer extension UI requests. + args := []string{"--mode", "rpc", "--no-extensions", "--no-skills", "--no-prompt-templates"} + if !cfg.WithMCP { + args = append(args, "--no-mcp") + } + if cfg.Mode == "resume" { + args = append(args, "--session", strings.TrimSpace(cfg.SessionID)) + } + if model := strings.TrimSpace(cfg.PiModel); model != "" { + args = append(args, "--model", model) + } + return args +} + +func buildPiRPCInput(task string) (string, error) { + commands := []any{ + map[string]any{"id": "ccg-state", "type": "get_state"}, + map[string]any{"id": "ccg-prompt", "type": "prompt", "message": task}, + } + var input strings.Builder + for _, command := range commands { + data, err := json.Marshal(command) + if err != nil { + return "", err + } + input.Write(data) + input.WriteByte('\n') + } + return input.String(), nil +} diff --git a/codeagent-wrapper/pi_parser.go b/codeagent-wrapper/pi_parser.go new file mode 100644 index 0000000..065e241 --- /dev/null +++ b/codeagent-wrapper/pi_parser.go @@ -0,0 +1,296 @@ +package main + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "strconv" + "strings" +) + +type piRPCEvent struct { + Type string `json:"type"` + Command string `json:"command"` + Success *bool `json:"success"` + Error string `json:"error"` + Message json.RawMessage `json:"message"` + Data json.RawMessage `json:"data"` +} + +type piMessage struct { + Role string `json:"role"` + StopReason string `json:"stopReason"` + Error string `json:"errorMessage"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"content"` +} + +type piStreamCallbacks struct { + onMessage func() + onComplete func() + onContent func(content, contentType string) + onProgress func(line string) + onSessionStarted func(id string) +} + +func piResponseError(event piRPCEvent) error { + if event.Success != nil && *event.Success { + return nil + } + message := strings.TrimSpace(event.Error) + if message == "" && len(event.Message) > 0 { + _ = json.Unmarshal(event.Message, &message) + message = strings.TrimSpace(message) + } + if message == "" && len(event.Data) > 0 { + var data struct { + Error string `json:"error"` + } + if json.Unmarshal(event.Data, &data) == nil { + message = strings.TrimSpace(data.Error) + } + } + if message == "" { + message = "command failed" + } + if event.Command != "" { + return fmt.Errorf("%s: %s", event.Command, message) + } + return errors.New(message) +} + +func piMessageText(message piMessage) string { + var text strings.Builder + for _, part := range message.Content { + if part.Type == "text" { + text.WriteString(part.Text) + } + } + return text.String() +} + +// parsePiRPCStream parses Pi's bidirectional RPC protocol. RPC has no session +// header, so the session ID comes from the get_state command response. +func parsePiRPCStream(r io.Reader, warnFn, infoFn func(string), callbacks piStreamCallbacks) parseResult { + if warnFn == nil { + warnFn = func(string) {} + } + if infoFn == nil { + infoFn = func(string) {} + } + notifyMessage := func() { + if callbacks.onMessage != nil { + callbacks.onMessage() + } + } + notifyComplete := func() { + if callbacks.onComplete != nil { + callbacks.onComplete() + } + } + emitProgress := func(event string, fields map[string]string) { + if callbacks.onProgress != nil { + callbacks.onProgress("[PROGRESS] " + formatProgressLine(event, fields)) + } + } + + reader := bufio.NewReaderSize(r, jsonLineReaderSize) + var result parseResult + streamedText := false + completionSignalled := false + setError := func(err error) { + if err != nil && result.err == nil { + result.err = err + } + } + complete := func() { + if completionSignalled { + return + } + completionSignalled = true + notifyComplete() + } + totalEvents := 0 + + for { + line, tooLong, readErr := readLineWithLimit(reader, jsonLineMaxBytes, jsonLinePreviewBytes) + if readErr != nil { + if errors.Is(readErr, io.EOF) { + if !completionSignalled { + setError(errors.New("Pi RPC stream ended before agent_settled")) + } + break + } + // A process/pipe may report ErrClosedPipe while its stdin and stdout + // are being torn down after settlement; do not discard real errors. + if completionSignalled && result.err == nil { + break + } + setError(fmt.Errorf("read Pi RPC output: %w", readErr)) + break + } + line = bytes.TrimSpace(line) + if len(line) == 0 { + continue + } + totalEvents++ + if tooLong { + warnFn(fmt.Sprintf("Skipped overlong Pi RPC line (> %d bytes)", jsonLineMaxBytes)) + continue + } + + var event piRPCEvent + if err := json.Unmarshal(line, &event); err != nil { + warnFn(fmt.Sprintf("Failed to parse Pi RPC event: %s", truncateBytes(line, 100))) + continue + } + + switch event.Type { + case "response": + if err := piResponseError(event); err != nil { + setError(err) + if event.Command == "prompt" || event.Command == "get_state" { + complete() + } + continue + } + if event.Command != "get_state" || len(event.Data) == 0 { + continue + } + var state struct { + SessionID string `json:"sessionId"` + } + if err := json.Unmarshal(event.Data, &state); err != nil { + setError(fmt.Errorf("get_state: invalid response: %w", err)) + complete() + continue + } + if state.SessionID != "" && result.threadID == "" { + result.threadID = state.SessionID + infoFn("Pi RPC session started: " + state.SessionID) + emitProgress("session_started", map[string]string{"id": state.SessionID}) + if callbacks.onSessionStarted != nil { + callbacks.onSessionStarted(state.SessionID) + } + } + + case "agent_start": + emitProgress("turn_started", nil) + + case "message_update": + var payload struct { + AssistantEvent struct { + Type string `json:"type"` + Delta string `json:"delta"` + TextDelta string `json:"textDelta"` + Content string `json:"content"` + } `json:"assistantEvent"` + } + if json.Unmarshal(line, &payload) != nil { + continue + } + update := payload.AssistantEvent + if update.Type != "text_delta" && update.Type != "text_start" && update.Type != "text_end" { + continue + } + text := update.Delta + if text == "" { + text = update.TextDelta + } + if text == "" && update.Type != "text_delta" { + text = update.Content + } + if text != "" { + streamedText = true + notifyMessage() + if callbacks.onContent != nil { + callbacks.onContent(text, "message") + } + } + + case "message_end": + var payload struct { + Message piMessage `json:"message"` + } + if err := json.Unmarshal(line, &payload); err != nil { + warnFn("Failed to parse Pi message_end event: " + err.Error()) + continue + } + message := payload.Message + if message.Role != "assistant" { + continue + } + text := piMessageText(message) + if text != "" { + result.message = text + notifyMessage() + emitProgress("message", map[string]string{"text": strconv.Quote(safeProgressSnippet(text, 120))}) + if callbacks.onContent != nil && !streamedText { + callbacks.onContent(text, "message") + } + } + streamedText = false + switch message.StopReason { + case "error", "aborted": + detail := strings.TrimSpace(message.Error) + if detail == "" { + detail = message.StopReason + } + setError(errors.New("Pi assistant stopped: " + detail)) + } + + case "tool_execution_start": + var payload struct { + ToolName string `json:"toolName"` + } + if json.Unmarshal(line, &payload) == nil && payload.ToolName != "" { + emitProgress("tool_started", map[string]string{"cmd": strconv.Quote(payload.ToolName)}) + } + + case "tool_execution_end": + var payload struct { + ToolName string `json:"toolName"` + IsError bool `json:"isError"` + Result json.RawMessage `json:"result"` + } + if json.Unmarshal(line, &payload) == nil { + emitProgress("tool_done", map[string]string{"cmd": strconv.Quote(payload.ToolName)}) + } + + case "auto_retry_start": + var payload struct { + Attempt int `json:"attempt"` + MaxRetries int `json:"maxRetries"` + Error string `json:"error"` + } + if json.Unmarshal(line, &payload) == nil { + emitProgress("retry", map[string]string{"text": strconv.Quote(safeProgressSnippet(payload.Error, 120))}) + } + + case "auto_retry_end": + var payload struct { + Success bool `json:"success"` + Error string `json:"error"` + } + if json.Unmarshal(line, &payload) == nil && !payload.Success { + detail := strings.TrimSpace(payload.Error) + if detail == "" { + detail = "retries exhausted" + } + setError(errors.New("Pi request failed: " + detail)) + } + + case "agent_settled": + emitProgress("session_completed", map[string]string{"total_events": strconv.Itoa(totalEvents)}) + complete() + } + } + + infoFn(fmt.Sprintf("Pi RPC parse completed: events=%d, message_len=%d, session_id_found=%t", totalEvents, len(result.message), result.threadID != "")) + return result +} diff --git a/codeagent-wrapper/pi_test.go b/codeagent-wrapper/pi_test.go new file mode 100644 index 0000000..ce812da --- /dev/null +++ b/codeagent-wrapper/pi_test.go @@ -0,0 +1,280 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "io" + "os" + "strings" + "testing" + "time" +) + +func TestPiBackendRegistrationAndArgs(t *testing.T) { + backend, err := selectBackend(" pi ") + if err != nil || backend.Name() != "pi" { + t.Fatalf("Pi is not registered: backend=%v, err=%v", backend, err) + } + + t.Setenv("CODEAGENT_PI_COMMAND", "/tools/pi") + got := buildPiArgs(&Config{ + Backend: "pi", Mode: "resume", SessionID: "session-id", + WorkDir: "/work", PiModel: " hkchat-test/model ", WithMCP: true, + }, "prompt must not be an argument") + wantCommand := "/tools/pi" + if b := (PiBackend{}); b.Command() != wantCommand { + t.Fatalf("Command() = %q, want %q", b.Command(), wantCommand) + } + want := []string{"--mode", "rpc", "--no-extensions", "--no-skills", "--no-prompt-templates", "--session", "session-id", "--model", "hkchat-test/model"} + if strings.Join(got, "\x00") != strings.Join(want, "\x00") { + t.Fatalf("buildPiArgs() = %#v, want %#v", got, want) + } + for _, arg := range got { + if strings.Contains(arg, "prompt must") || arg == "--no-mcp" { + t.Fatalf("unexpected RPC argv entry %q", arg) + } + } +} + +func TestPiConfigFlagAndEnvironment(t *testing.T) { + oldArgs := os.Args + t.Cleanup(func() { os.Args = oldArgs }) + + t.Setenv("PI_MODEL", "provider/from-env") + os.Args = []string{"codeagent-wrapper", "--backend", "pi", "--pi-model", " provider/from-cli ", "work"} + cfg, err := parseArgs() + if err != nil || cfg.PiModel != "provider/from-cli" || cfg.Backend != "pi" { + t.Fatalf("CLI Pi config = %+v, err=%v", cfg, err) + } + + os.Args = []string{"codeagent-wrapper", "--backend=pi", "work"} + cfg, err = parseArgs() + if err != nil || cfg.PiModel != "provider/from-env" { + t.Fatalf("environment Pi config = %+v, err=%v", cfg, err) + } + + for _, args := range [][]string{ + {"codeagent-wrapper", "--backend", "pi", "--pi-model", "", "work"}, + {"codeagent-wrapper", "--backend", "pi", "--pi-model= ", "work"}, + {"codeagent-wrapper", "--backend", "pi", "--pi-model", "--with-mcp", "work"}, + {"codeagent-wrapper", "--backend", "pi", "--pi-model=-h", "work"}, + } { + os.Args = args + if _, err := parseArgs(); err == nil { + t.Fatalf("expected invalid model error for %#v", args) + } + } +} + +func TestBuildPiRPCInputPreservesPrompt(t *testing.T) { + prompt := "@README.md\nfirst line\r\nsecond \"quoted\" line\n$HOME `literal`" + input, err := buildPiRPCInput(prompt) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSuffix(input, "\n"), "\n") + if len(lines) != 2 { + t.Fatalf("got %d JSONL lines, want 2: %q", len(lines), input) + } + var state, command map[string]any + if json.Unmarshal([]byte(lines[0]), &state) != nil || state["type"] != "get_state" { + t.Fatalf("invalid first command: %s", lines[0]) + } + if err := json.Unmarshal([]byte(lines[1]), &command); err != nil { + t.Fatal(err) + } + if command["type"] != "prompt" || command["message"] != prompt { + t.Fatalf("prompt changed in transport: %#v", command) + } +} + +func TestParsePiRPCStreamSuccess(t *testing.T) { + input := strings.Join([]string{ + `{"type":"response","id":"state","command":"get_state","success":true,"data":{"sessionId":"pi-session","isStreaming":false}}`, + `{"type":"response","id":"prompt","command":"prompt","success":true}`, + `{"type":"agent_start"}`, + `{"type":"message_update","assistantEvent":{"type":"text_delta","delta":"first "}}`, + `{"type":"message_update","assistantEvent":{"type":"text_delta","delta":"second"}}`, + `{"type":"tool_execution_start","toolName":"read","toolCallId":"call-1"}`, + `{"type":"tool_execution_end","toolName":"read","isError":false,"result":{"content":[{"type":"text","text":"file"}]}}`, + `{"type":"message_end","message":{"role":"assistant","stopReason":"stop","content":[{"type":"text","text":"first second"}]}}`, + `{"type":"agent_settled"}`, + ``, + }, "\n") + completed := 0 + var content strings.Builder + result := parsePiRPCStream(strings.NewReader(input), func(s string) { t.Log(s) }, func(s string) { t.Log(s) }, piStreamCallbacks{ + onComplete: func() { completed++ }, + onContent: func(text, _ string) { content.WriteString(text) }, + }) + if result.err != nil || result.message != "first second" || result.threadID != "pi-session" { + t.Fatalf("unexpected result: %+v", result) + } + if completed != 1 || content.String() != "first second" { + t.Fatalf("callbacks: completed=%d, content=%q", completed, content.String()) + } +} + +func TestParsePiRPCStreamIgnoresClosedPipeAfterSettlement(t *testing.T) { + stream := `{"type":"response","command":"get_state","success":true,"data":{"sessionId":"closed-after-settlement"}}` + "\n" + + `{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"done"}]}}` + "\n" + + `{"type":"agent_settled"}` + "\n" + reader := io.MultiReader(strings.NewReader(stream), errReader{err: errors.New("transport closed after settlement")}) + var completions int + result := parsePiRPCStream(reader, nil, nil, piStreamCallbacks{onComplete: func() { completions++ }}) + if result.err != nil || result.message != "done" || result.threadID != "closed-after-settlement" { + t.Fatalf("unexpected settled result: %+v", result) + } + if completions != 1 { + t.Fatalf("completions = %d, want 1", completions) + } +} + +func TestParsePiRPCStreamUsesFinalMessageWithoutDelta(t *testing.T) { + input := `{"type":"response","command":"get_state","success":true,"data":{"sessionId":"s"}} +{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"final answer"}]}} +{"type":"agent_settled"}` + var content string + result := parsePiRPCStream(strings.NewReader(input), nil, nil, piStreamCallbacks{ + onContent: func(text, _ string) { content += text }, + }) + if result.err != nil || result.message != "final answer" || content != "final answer" { + t.Fatalf("unexpected result: %+v content=%q", result, content) + } +} + +func TestParsePiRPCStreamRequiresSettlement(t *testing.T) { + input := "{\"type\":\"message_end\",\"message\":{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"partial\"}]}}\n" + result := parsePiRPCStream(strings.NewReader(input), nil, nil, piStreamCallbacks{}) + if result.err == nil || !strings.Contains(result.err.Error(), "before agent_settled") { + t.Fatalf("premature EOF should fail: %+v", result) + } + if result.message != "partial" { + t.Fatalf("partial message should be preserved for diagnostics: %+v", result) + } +} + +func TestParsePiRPCStreamCommandErrorIsFailure(t *testing.T) { + result := parsePiRPCStream(strings.NewReader(`{"type":"response","command":"prompt","success":false,"error":"agent busy"}`), nil, nil, piStreamCallbacks{}) + if result.err == nil || !strings.Contains(result.err.Error(), "agent busy") { + t.Fatalf("expected rejected prompt failure, got %+v", result) + } +} + +func TestParsePiRPCStreamProviderFailureIsFailure(t *testing.T) { + input := `{"type":"response","command":"get_state","success":true,"data":{"sessionId":"s"}} +{"type":"auto_retry_end","success":false,"error":"rate limit retries exhausted"} +{"type":"message_end","message":{"role":"assistant","stopReason":"error","errorMessage":"rate limited","content":[]}} +{"type":"agent_settled"}` + result := parsePiRPCStream(strings.NewReader(input), nil, nil, piStreamCallbacks{}) + if result.err == nil || !strings.Contains(result.err.Error(), "rate limit") { + t.Fatalf("expected provider failure, got %+v", result) + } + if result.threadID != "s" { + t.Fatalf("session should survive failure: %+v", result) + } +} + +func TestParsePiRPCStreamPreservesAssistantErrorMessage(t *testing.T) { + input := `{"type":"message_end","message":{"role":"assistant","stopReason":"error","errorMessage":"provider rejected request","content":[]}} +{"type":"agent_settled"}` + result := parsePiRPCStream(strings.NewReader(input), nil, nil, piStreamCallbacks{}) + if result.err == nil || !strings.Contains(result.err.Error(), "provider rejected request") { + t.Fatalf("expected assistant error details, got %+v", result) + } +} + +func TestRunPiRPCSuccessAndStdinLifecycle(t *testing.T) { + defer resetTestHooks() + fake := newFakeCmd(fakeCmdConfig{StdoutPlan: []fakeStdoutEvent{ + {Data: `{"type":"response","command":"get_state","success":true,"data":{"sessionId":"pi-session"}}` + "\n"}, + {Data: `{"type":"response","command":"prompt","success":true}` + "\n"}, + {Data: `{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"work done"}]}}` + "\n"}, + {Data: `{"type":"agent_settled"}` + "\n"}, + }}) + t.Setenv("CODEAGENT_PI_COMMAND", "pi-test-binary") + var capturedCommand string + var capturedArgs []string + newCommandRunner = func(_ context.Context, command string, args ...string) commandRunner { + capturedCommand = command + capturedArgs = append([]string(nil), args...) + return fake + } + result := runCodexTaskWithContext(context.Background(), TaskSpec{ + Backend: "pi", Task: "run\n@not-a-file", WorkDir: "/tmp/work", PiModel: "provider/model", + }, nil, nil, false, false, 2) + if result.ExitCode != 0 || result.Message != "work done" || result.SessionID != "pi-session" { + t.Fatalf("unexpected result: %+v", result) + } + wantArgs := []string{"--mode", "rpc", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-mcp", "--model", "provider/model"} + if got := strings.Join(capturedArgs, "\x00"); got != strings.Join(wantArgs, "\x00") { + t.Errorf("executed Pi args mismatch: %q", capturedArgs) + } + if capturedCommand != "pi-test-binary" { + t.Errorf("executed command = %q, want Pi binary", capturedCommand) + } + if !fake.stdinWriter.closed { + t.Fatal("settled RPC did not close stdin") + } + var commands []map[string]any + for _, line := range strings.Split(strings.TrimSpace(fake.StdinContents()), "\n") { + var command map[string]any + if err := json.Unmarshal([]byte(line), &command); err != nil { + t.Fatalf("decode RPC command: %v; stdin=%q", err, fake.StdinContents()) + } + commands = append(commands, command) + } + if len(commands) != 2 || commands[1]["message"] != "run\n@not-a-file" { + t.Fatalf("unexpected RPC stdin: %q", fake.StdinContents()) + } +} + +func TestRunPiRPCStdinWriteErrorIsFailure(t *testing.T) { + defer resetTestHooks() + fake := newFakeCmd(fakeCmdConfig{StdoutPlan: []fakeStdoutEvent{ + {Data: `{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"should not be success"}]}}` + "\n"}, + {Data: `{"type":"agent_settled"}` + "\n"}, + }}) + if err := fake.stdinWriter.Close(); err != nil { + t.Fatal(err) + } + newCommandRunner = func(context.Context, string, ...string) commandRunner { return fake } + result := runCodexTaskWithContext(context.Background(), TaskSpec{Backend: "pi", Task: "preserve this prompt", WorkDir: "/tmp/work"}, nil, nil, false, false, 2) + if result.ExitCode == 0 || !strings.Contains(result.Error, "write Pi RPC stdin") { + t.Fatalf("stdin failure must not return success: %+v", result) + } +} + +func TestRunPiRPCMissingSettlementIsFailure(t *testing.T) { + defer resetTestHooks() + fake := newFakeCmd(fakeCmdConfig{StdoutPlan: []fakeStdoutEvent{ + {Data: `{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"partial"}]}}` + "\n"}, + }}) + newCommandRunner = func(context.Context, string, ...string) commandRunner { return fake } + result := runCodexTaskWithContext(context.Background(), TaskSpec{Backend: "pi", Task: "task", WorkDir: "/tmp/work"}, nil, nil, false, false, 2) + if result.ExitCode == 0 || !strings.Contains(result.Error, "before agent_settled") { + t.Fatalf("missing settlement must not return success: %+v", result) + } +} + +func TestRunPiRPCCancellation(t *testing.T) { + defer resetTestHooks() + forceKillDelay.Store(0) + fake := newFakeCmd(fakeCmdConfig{ + KeepStdoutOpen: true, + BlockWait: true, + ReleaseWaitOnSignal: true, + ReleaseWaitOnKill: true, + }) + newCommandRunner = func(context.Context, string, ...string) commandRunner { return fake } + ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancel() + result := runCodexTaskWithContext(ctx, TaskSpec{Backend: "pi", Task: "wait", WorkDir: "/tmp/work"}, nil, nil, false, false, 10) + if result.ExitCode != 124 { + t.Fatalf("cancel result = %+v, want timeout", result) + } + if fake.process.SignalCount() == 0 || !fake.stdinWriter.closed { + t.Fatalf("cancellation did not clean up: signals=%d, stdinClosed=%t", fake.process.SignalCount(), fake.stdinWriter.closed) + } +} diff --git a/docs/pi-backend.md b/docs/pi-backend.md new file mode 100644 index 0000000..d360e94 --- /dev/null +++ b/docs/pi-backend.md @@ -0,0 +1,121 @@ +# Pi RPC backend + +Pi is a first-class `codeagent-wrapper` backend. OpenSlime keeps its existing +orchestrator and worker boundary: it starts a **local Pi subprocess**, sends +protocol commands over stdin, and continuously reads structured events from stdout. +Pi owns model providers, provider credentials, tool permissions, and context-window +configuration. The provider can use a local model or a remote API. This integration +does **not** implement a connection to a separate remote Pi server. + +## Configure Pi first + +1. Install Pi on every machine running `codeagent-wrapper` and ensure `pi` is in + `PATH`. On Windows, diagnostic checks use `pi.exe`. +2. Configure providers, models, and permissions using Pi configuration. Do not put + API keys in OpenSlime config, workflow files, prompts, or logs. +3. Run `pi --list-models` to obtain a model ID or `provider/model` identifier. +4. In `osm init` or the model-routing menu, select **Pi (RPC)**. Enter the exact + model identifier, or leave it empty to inherit Pi's current default. + +To use a 1M context, select the model variant that actually has a 1M context window, +and retain any required provider/model configuration in Pi. For example: + +```toml +# ~/.claude/.ccg/config.toml +[routing] +primary = "claude" + +[routing.backend] +primary = "pi" +models = ["pi"] + +# An example only: use an identifier from your own `pi --list-models`. +piModel = "your-provider/your-1m-model" +``` + +OpenSlime does not detect, resize, truncate, or override the provider's context +window. A model name containing `1m` alone is not proof of its capability. Check +Pi's provider configuration and usage limits, including reasoning-token limits. +If the selected model is unavailable or authentication fails, the task fails with +Pi's provider error; OpenSlime does not silently switch models. + +## Invocation + +```bash +# New session. Use the installed wrapper (normally ~/.claude/bin). +codeagent-wrapper --lite --backend pi \ + --pi-model your-provider/your-1m-model \ + 'Inspect the current change and report regressions. Do not modify files.' \ + /path/to/project + +# Multiline and @-prefixed prompts are protocol data, not Pi @file references. +codeagent-wrapper --lite --backend pi - /path/to/project <<'EOF' +Review the referenced diff. +@literal-text must remain literal. + +Return the requested JSON structure. +EOF + +# Reuse the SESSION_ID returned by the first invocation. +codeagent-wrapper --lite --backend pi \ + resume 'Continue with the requested change.' /path/to/project +``` + +`PI_MODEL` supplies the default model; `--pi-model`/`--pi-model=` overrides it. +Injected workflows use `{{PI_MODEL_FLAG}}` only on Pi calls. In parallel-input mode, +backend-specific model flags are not accepted; set `PI_MODEL` before invoking the +wrapper. The task field can specify `backend: "pi"` (or `pi` without JSON syntax). +`CODEAGENT_PI_COMMAND` can select a Pi executable for testing or a custom install. + +## Protocol and lifecycle + +```mermaid +sequenceDiagram + participant O as OpenSlime orchestrator + participant W as codeagent-wrapper + participant P as local Pi RPC process + participant M as configured local/remote provider + O->>W: Task + role + model + working directory + W->>P: --mode rpc (+ --session when resuming) + W->>P: get_state + prompt (JSONL on stdin) + P->>M: Provider request with Pi's own configuration + M-->>P: Model/tool stream + P-->>W: agent_event(message_update) / tool/retry events + W-->>O: Streamed assistant text and progress + P-->>W: message_end + agent_settled + W->>P: Close stdin + W-->>O: Exit status + session ID + final text +``` + +- `get_state` discovers the session ID. Saved IDs are treated as resumable session + identifiers, not as proof that an RPC request has completed. +- Prompt acceptance (`response` for `prompt`) is not completion. The wrapper reads + until `agent_settled` while streaming assistant `text_delta` events. +- A final assistant message supplies the result; an empty result is an error. stdin + is closed on settlement, timeout, or cancellation so the long-lived RPC process + can terminate. Timeout/interrupt cleanup uses existing process-group handling. +- RPC command rejections, exhausted provider retries, provider errors, assistant + `error`/`aborted` stop reasons, and protocol read failures become nonzero results. + A transport EOF cannot conceal a previously reported protocol error. +- New sessions consume context normally. A resumed session opens an existing Pi + session and adds the new prompt; it incurs the provider's actual session/context + costs rather than starting an independent free context. + +For predictable delegated tasks, Pi starts with `--no-extensions`, `--no-skills`, and +`--no-prompt-templates`. This avoids interactive extension approval and unrelated +project behavior. MCP is disabled by default; `--with-mcp` is the explicit opt-in. +These flags restrict the subprocess configuration, not the provider's safety policy. +Read-only prompts do not replace OS/filesystem permissions, and `--lite` controls +OpenSlime's auxiliary Web UI, not Pi's provider or context window. + +## Output and errors + +Successful output retains the final `SESSION_ID: ` marker used by existing +resume workflows. Stderr contains structured process diagnostics and optional +progress. Provider failures, invalid model IDs, missing executables, timeouts, and +cancelled work are errors, not successful empty responses. + +Use `pi --mode rpc` directly only when debugging Pi itself. Do not put an interactive +`exit` command into delegated task input or rely on Pi's terminal renderer; consume +the JSON events instead. `osm doctor --json` checks the Pi executable when Pi is +routed and reports executable failure without collecting provider credentials. diff --git a/docs/pi-backend.zh-CN.md b/docs/pi-backend.zh-CN.md new file mode 100644 index 0000000..35ad173 --- /dev/null +++ b/docs/pi-backend.zh-CN.md @@ -0,0 +1,83 @@ +# Pi RPC 后端 + +Pi 已作为一等后端接入 `codeagent-wrapper`。OpenSlime 保留原有编排层与 worker 边界, +在运行 wrapper 的机器上启动 **Pi 本地 RPC 子进程**,通过 stdin 发送协议命令,并持续 +读取 stdout 的结构化事件。Pi 自己管理 provider、凭据、工具权限和上下文窗口;provider +可以调用本地模型或远程 API。本功能**不是独立远程 Pi 服务器连接**,不要把两者混为一谈。 + +## 先配置 Pi + +1. 在运行 `codeagent-wrapper` 的机器安装 `pi`,并保证其在 `PATH` 中。 + Windows 的诊断检查使用 `pi.exe`。 +2. 在 Pi 中配置 provider、模型、权限和所需的长上下文 variant。凭据保存在 Pi 的 + 配置或环境中,不要写入 OpenSlime 配置、提示词、模板或日志。 +3. 执行 `pi --list-models`,取得唯一模型 ID 或 `provider/model` 名称。 +4. 在 `osm init` 或模型路由菜单选择 **Pi (RPC)**。输入对应模型;留空则沿用 Pi 默认模型。 + +需要 1M 上下文时,应选择 Pi 中实际配置为 1M 的模型 variant,例如 +`your-provider/your-1m-model`;这只是命名示例,实际值以 `pi --list-models` 和 Pi 配置为准。 +OpenSlime 不检测、扩大、截断或覆盖上下文窗口。名字包含 `1m` 不等于已验证支持 1M。 +必须同时保留 Pi 的 provider/model 相关配置,并确认额度和 reasoning token 限制。 +模型不可用或认证失败时任务退出非零,不会静默降级到其它模型。 + +```toml +# ~/.claude/.ccg/config.toml +[routing] +primary = "claude" + +[routing.backend] +primary = "pi" +models = ["pi"] + +piModel = "your-provider/your-1m-model" +``` + +## 调用与恢复 + +```bash +# 新会话(安装后的 wrapper 通常位于 ~/.claude/bin) +codeagent-wrapper --lite --backend pi \ + --pi-model your-provider/your-1m-model \ + '检查当前变更,报告回归问题;不要修改文件。' /path/to/project + +# stdin 任务仍然被序列化为 Pi RPC 输入,不会触发 @file 展开 +codeagent-wrapper --lite --backend pi - /path/to/project <<'EOF' +检查请求提到的 diff。 +@这里只是字面上的文本。 + +请按指定 JSON 格式返回。 +EOF + +# 沿用第一次输出的 SESSION_ID +codeagent-wrapper --lite --backend pi \ + resume '继续执行,先核对上次结论。' /path/to/project +``` + +`PI_MODEL` 是默认模型,CLI 的 `--pi-model`/`--pi-model=<值>` 覆盖它;安装后的工作流 +通过 `{{PI_MODEL_FLAG}}` 只给 Pi 调用注入该参数。并行输入模式不接受针对后端的模型 +CLI 参数,应在调用前设置 `PI_MODEL`。并行任务字段可以指定 `backend: "pi"`。 +`CODEAGENT_PI_COMMAND` 可覆盖 Pi 可执行文件,用于测试或自定义安装路径。 + +## 协议、完成条件和错误 + +1. 新进程使用 `pi --mode rpc`;恢复时额外传入 `--session `。 +2. wrapper 发送 `get_state` 与 `prompt` JSONL 命令。前者的 `session_id` 用于发现会话, + 不代表 prompt 已完成;后者返回 `success: true` 也只表示 prompt 已被接收。 +3. 持续读取 `agent_event`:`message_update/text_delta` 用于流式文本,工具调用和重试 + 用于进度。最终消息用于结果;以 `agent_settled` 作为完成信号,再关闭 stdin。 +4. resume 打开同一 Pi 会话并继续加入 prompt。新任务正常消耗上下文;恢复会话也不是 + 独立、免费的新上下文,实际价格以 Pi/provider 为准。 +5. RPC command 被拒绝、重试耗尽、provider 错误、assistant 的 `error`/`aborted` stop + reason、协议读取失败均返回非零退出码。已经返回的协议错误不会被 EOF 吞掉。 + +结果保留原有 `SESSION_ID: ` 标记;stderr 用于进程诊断及可选进度。超时、取消和 +强制终止沿用现有进程组清理,且会关闭 stdin,不留下等待下一次 RPC 命令的子进程。 + +为保持委派任务确定性,Pi 默认使用 `--no-extensions`、`--no-skills`、 +`--no-prompt-templates`,避免扩展交互审批或意外项目行为;MCP 默认关闭,只有显式 +`--with-mcp` 才开启。只读提示词不替代操作系统权限。`--lite` 只关闭 OpenSlime 辅助 +Web UI,不改变 Pi provider、上下文窗口或安全策略。 + +调试 Pi 本身时可直接使用 `pi --mode rpc`,但不要把委托输入当成交互终端,也不要依赖 +终端渲染或加入 `exit` 命令。`osm doctor --json` 会检查通过路由选中的 Pi,并报告 +缺失或可执行文件错误;该检查不收集 provider 密钥。 diff --git a/package.json b/package.json index fd3690b..b3bbd90 100644 --- a/package.json +++ b/package.json @@ -55,6 +55,7 @@ "templates/prompts/grok/", "templates/prompts/kimi/", "templates/prompts/opencode/", + "templates/prompts/pi/", "templates/output-styles/", "templates/skills/adsense-site-auditor/", "templates/skills/bt-panel/", diff --git a/src/commands/__tests__/doctor.test.ts b/src/commands/__tests__/doctor.test.ts index 2991a7e..5bb80c5 100644 --- a/src/commands/__tests__/doctor.test.ts +++ b/src/commands/__tests__/doctor.test.ts @@ -213,10 +213,10 @@ describe('CCG doctor inventory', () => { }) it('uses platform-specific Windows npm shims and native executables', async () => { - await config('antigravity', 'codex', ['gemini', 'claude', 'kimi', 'grok', 'opencode']) + await config('antigravity', 'codex', ['gemini', 'claude', 'kimi', 'grok', 'opencode', 'pi']) await claudeInstall() await collectDoctorReport(deps({ platform: 'win32' })) - expect(exec.mock.calls.map(call => call[0])).toEqual(['agy.exe', 'claude.exe', 'codex.cmd', 'gemini.cmd', 'grok.exe', 'kimi.exe', 'opencode.exe']) + expect(exec.mock.calls.map(call => call[0])).toEqual(['agy.exe', 'claude.exe', 'codex.cmd', 'gemini.cmd', 'grok.exe', 'kimi.exe', 'opencode.exe', 'pi.exe']) expect(exec.mock.calls.every(call => JSON.stringify(call[1]) === '["--version"]')).toBe(true) }) diff --git a/src/commands/init.ts b/src/commands/init.ts index 17acaf1..0d2727c 100644 --- a/src/commands/init.ts +++ b/src/commands/init.ts @@ -11,7 +11,7 @@ import { createDefaultConfig, ensureCcgDir, getCcgDir, readCcgConfig, writeCcgCo import { configureGeminiCliApi, configureSponsorForCodex, getCoreCommandIds, getSponsor, installAceTool, installAceToolRs, installContextWeaver, installFastContext, installMcpServer, installWorkflows, promptSponsorInit, showBinaryDownloadWarning, sponsorInquirerChoices, syncMcpToCodex, syncMcpToGemini, writeFastContextPrompt } from '../utils/installer' import { isWindows } from '../utils/platform' import { migrateToV1_4_0, needsMigration } from '../utils/migration' -import { promptOpencodeModel } from '../utils/model-selection' +import { promptOpencodeModel, promptPiModel } from '../utils/model-selection' import { PACKAGE_ROOT } from '../utils/installer-template' import { getSkillCatalog, installedNames, removeSkills, resolveSkillPaths, SKILL_MANIFEST_FILE } from '../utils/skill-manager' @@ -242,6 +242,7 @@ export async function init(options: InitOptions = {}): Promise { let grokModel = 'grok-4.5' let kimiModel = '' let opencodeModel = '' + let piModel = '' const mode: CollaborationMode = 'smart' let selectedWorkflows = getCoreCommandIds() @@ -255,6 +256,7 @@ export async function init(options: InitOptions = {}): Promise { grokModel = existingConfig.routing.grokModel || 'grok-4.5' kimiModel = existingConfig.routing.kimiModel || '' opencodeModel = existingConfig.routing.opencodeModel || '' + piModel = existingConfig.routing.piModel || '' } } @@ -364,6 +366,8 @@ export async function init(options: InitOptions = {}): Promise { kimiModel = existingConfig.routing.kimiModel if (existingConfig.routing.opencodeModel) opencodeModel = existingConfig.routing.opencodeModel + if (existingConfig.routing.piModel) + piModel = existingConfig.routing.piModel } // ── Step runners (closures sharing outer-scope state) ── @@ -490,6 +494,7 @@ export async function init(options: InitOptions = {}): Promise { { name: 'Kimi', value: 'kimi' as ModelType }, { name: 'Codex', value: 'codex' as ModelType }, { name: 'OpenCode', value: 'opencode' as ModelType }, + { name: 'Pi (RPC)', value: 'pi' as ModelType }, { name: `Claude Code ${ansis.cyan(`(${i18n.t('init:model.agentTeams')})`)}`, value: 'claude' as ModelType }, { name: `Gemini ${ansis.gray(`(${i18n.t('init:model.deprecated')})`)}`, value: 'gemini' as ModelType }, ...navSentinels(canGoBack), @@ -512,6 +517,7 @@ export async function init(options: InitOptions = {}): Promise { { name: 'Kimi', value: 'kimi' as ModelType }, { name: 'Antigravity', value: 'antigravity' as ModelType }, { name: 'OpenCode', value: 'opencode' as ModelType }, + { name: 'Pi (RPC)', value: 'pi' as ModelType }, { name: `Claude Code ${ansis.cyan(`(${i18n.t('init:model.agentTeams')})`)}`, value: 'claude' as ModelType }, { name: `Gemini ${ansis.gray(`(${i18n.t('init:model.deprecated')})`)}`, value: 'gemini' as ModelType }, ], @@ -524,6 +530,9 @@ export async function init(options: InitOptions = {}): Promise { if (selectedFrontend === 'opencode' || selectedBackend === 'opencode') { opencodeModel = await promptOpencodeModel(opencodeModel, language === 'zh-CN') } + if (selectedFrontend === 'pi' || selectedBackend === 'pi') { + piModel = await promptPiModel(piModel, language === 'zh-CN') + } if (selectedFrontend === 'gemini' || selectedBackend === 'gemini') { const { selectedGeminiModel } = await inquirer.prompt([{ @@ -875,6 +884,9 @@ export async function init(options: InitOptions = {}): Promise { if (frontendModels[0] === 'opencode' || backendModels[0] === 'opencode') { console.log(` ${ansis.cyan('OpenCode model:')} ${ansis.gray(opencodeModel || (language === 'zh-CN' ? 'OpenCode 默认' : 'OpenCode default'))}`) } + if (frontendModels[0] === 'pi' || backendModels[0] === 'pi') { + console.log(` ${ansis.cyan('Pi model:')} ${ansis.gray(piModel || (language === 'zh-CN' ? 'Pi 默认' : 'Pi default'))}`) + } console.log(` ${ansis.cyan(i18n.t('init:summary.commandCount'))} ${ansis.yellow(workflowsCount.toString())}`) const mcpSummary = (() => { if (mcpProvider === 'fast-context') @@ -1000,6 +1012,7 @@ export async function init(options: InitOptions = {}): Promise { grokModel, kimiModel, opencodeModel, + piModel, } // Summary + confirmation handled by runSummaryStep() inside the state diff --git a/src/commands/menu.ts b/src/commands/menu.ts index 271a2f3..a01987b 100644 --- a/src/commands/menu.ts +++ b/src/commands/menu.ts @@ -17,7 +17,7 @@ import { init } from './init' import { update } from './update' import { manageSkillsMenu } from './skills' import { doctor } from './doctor' -import { promptOpencodeModel } from '../utils/model-selection' +import { promptOpencodeModel, promptPiModel } from '../utils/model-selection' import { isWindows } from '../utils/platform' const execAsync = promisify(exec) @@ -503,6 +503,7 @@ async function configModelRouting(): Promise { const currentGrokModel = config?.routing?.grokModel || 'grok-4.5' const currentKimiModel = config?.routing?.kimiModel || '' const currentOpencodeModel = config?.routing?.opencodeModel || '' + const currentPiModel = config?.routing?.piModel || '' console.log(ansis.gray(` ${i18n.t('init:model.currentRouting')}:`)) console.log(` ${ansis.cyan('Frontend:')} ${ansis.green(currentFrontend)}`) @@ -526,6 +527,7 @@ async function configModelRouting(): Promise { { name: 'Kimi', value: 'kimi' }, { name: 'Codex', value: 'codex' }, { name: 'OpenCode', value: 'opencode' }, + { name: 'Pi (RPC)', value: 'pi' }, { name: `Claude Code ${ansis.cyan(`(${i18n.t('init:model.agentTeams')})`)}`, value: 'claude' }, { name: `Gemini ${ansis.gray(`(${i18n.t('init:model.deprecated')})`)}`, value: 'gemini' }, ], @@ -543,6 +545,7 @@ async function configModelRouting(): Promise { { name: 'Kimi', value: 'kimi' }, { name: 'Antigravity', value: 'antigravity' }, { name: 'OpenCode', value: 'opencode' }, + { name: 'Pi (RPC)', value: 'pi' }, { name: `Claude Code ${ansis.cyan(`(${i18n.t('init:model.agentTeams')})`)}`, value: 'claude' }, { name: `Gemini ${ansis.gray(`(${i18n.t('init:model.deprecated')})`)}`, value: 'gemini' }, ], @@ -612,7 +615,11 @@ async function configModelRouting(): Promise { if (selectedFrontend === 'opencode' || selectedBackend === 'opencode') { opencodeModel = await promptOpencodeModel(currentOpencodeModel, isZh) } - if (selectedFrontend === currentFrontend && selectedBackend === currentBackend && geminiModel === currentGeminiModel && grokModel === currentGrokModel && opencodeModel === currentOpencodeModel) { + let piModel = currentPiModel + if (selectedFrontend === 'pi' || selectedBackend === 'pi') { + piModel = await promptPiModel(currentPiModel, isZh) + } + if (selectedFrontend === currentFrontend && selectedBackend === currentBackend && geminiModel === currentGeminiModel && grokModel === currentGrokModel && opencodeModel === currentOpencodeModel && piModel === currentPiModel) { console.log(ansis.gray(` ${i18n.t('common:configNotModified')}`)) return } @@ -637,6 +644,7 @@ async function configModelRouting(): Promise { config.routing.grokModel = grokModel config.routing.kimiModel = currentKimiModel config.routing.opencodeModel = opencodeModel + config.routing.piModel = piModel await writeCcgConfig(config) } diff --git a/src/types/index.ts b/src/types/index.ts index 3f63eaa..b66cdea 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -2,7 +2,7 @@ export type SupportedLang = 'zh-CN' | 'en' // 模型类型 -export type ModelType = 'codex' | 'gemini' | 'claude' | 'antigravity' | 'grok' | 'kimi' | 'opencode' +export type ModelType = 'codex' | 'gemini' | 'claude' | 'antigravity' | 'grok' | 'kimi' | 'opencode' | 'pi' // 协作模式 export type CollaborationMode = 'parallel' | 'smart' | 'sequential' @@ -31,6 +31,7 @@ export interface ModelRouting { grokModel?: string // Grok 具体型号(默认 grok-4.5,代码任务可选 grok-composer-2.5-fast) kimiModel?: string // Kimi 模型别名(空 = 用 kimi config.toml 的 default_model) opencodeModel?: string // Opencode 模型 provider/model(空 = 用 opencode 默认) + piModel?: string // Pi provider/model 或唯一 model ID(空 = 用 Pi 已配置的默认模型) } // CCG 配置 diff --git a/src/utils/__tests__/installWorkflows.test.ts b/src/utils/__tests__/installWorkflows.test.ts index 0e2c00f..bec2853 100644 --- a/src/utils/__tests__/installWorkflows.test.ts +++ b/src/utils/__tests__/installWorkflows.test.ts @@ -14,7 +14,7 @@ vi.mock('node:child_process', async (original) => { const output = actual.execSync(command, options) const path = command.match(/^"([^"]+)" --version$/)?.[1] // Run the Node PE fixture for real; only normalize its wrapper identity. - return path && fixturePaths.has(path) ? Buffer.from('codeagent-wrapper version 5.15.0\n') : output + return path && fixturePaths.has(path) ? Buffer.from('codeagent-wrapper version 5.16.0\n') : output }) } }) @@ -23,7 +23,7 @@ async function prepareWrapper(directory: string): Promise { const binary = join(directory, 'bin', process.platform === 'win32' ? 'codeagent-wrapper.exe' : 'codeagent-wrapper') await fs.ensureDir(join(directory, 'bin')) if (process.platform === 'win32') { await fs.copyFile(process.execPath, binary); fixturePaths.add(binary) } - else await fs.writeFile(binary, '#!/usr/bin/env node\nconsole.log("codeagent-wrapper version 5.15.0")\n', { mode: 0o755 }) + else await fs.writeFile(binary, '#!/usr/bin/env node\nconsole.log("codeagent-wrapper version 5.16.0")\n', { mode: 0o755 }) } // Collect all .md files recursively diff --git a/src/utils/__tests__/installer.test.ts b/src/utils/__tests__/installer.test.ts index d1053ef..39b8d43 100644 --- a/src/utils/__tests__/installer.test.ts +++ b/src/utils/__tests__/installer.test.ts @@ -20,7 +20,7 @@ vi.mock('node:child_process', async (original) => { // Windows uses a runnable Node PE fixture. Verify execution for real, then // normalize its identity; this checks installation, not the real Go binary. return process.platform === 'win32' && /codeagent-wrapper\.exe" --version$/.test(command) - ? Buffer.from('codeagent-wrapper version 5.15.0\n') : output + ? Buffer.from('codeagent-wrapper version 5.16.0\n') : output }) } }) let assetDirectory: string @@ -28,7 +28,7 @@ beforeAll(async () => { assetDirectory = await fs.mkdtemp(join(tmpdir(), 'ccg-binary-fixture-')) fixture.asset = join(assetDirectory, 'wrapper-asset') if (process.platform === 'win32') await fs.copy(process.execPath, fixture.asset) - else await fs.writeFile(fixture.asset, '#!/usr/bin/env node\nconsole.log("codeagent-wrapper version 5.15.0")\n', { mode: 0o600 }) + else await fs.writeFile(fixture.asset, '#!/usr/bin/env node\nconsole.log("codeagent-wrapper version 5.16.0")\n', { mode: 0o600 }) vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new Error('Installer tests must not use live HTTP')))) }) afterAll(async () => { vi.unstubAllGlobals(); await fs.remove(assetDirectory) }) @@ -330,7 +330,7 @@ describe('installWorkflows — prompts installation', () => { await fs.remove(tmpDir) }) - it('installs codex, gemini, and claude prompts', { timeout: 30_000 }, async () => { + it('installs prompts for every supported backend', { timeout: 30_000 }, async () => { const result = await installWithFixture(getAllCommandIds(), tmpDir, true, { mcpProvider: 'skip', }) @@ -353,6 +353,18 @@ describe('installWorkflows — prompts installation', () => { const grokFiles = readdirSync(join(promptsDir, 'grok')).filter(f => f.endsWith('.md')) expect(grokFiles.length).toBeGreaterThanOrEqual(7) expect(grokFiles).toContain('builder.md') + + const piFiles = readdirSync(join(promptsDir, 'pi')).filter(f => f.endsWith('.md')) + expect(piFiles.sort()).toEqual([ + 'analyzer.md', + 'architect.md', + 'builder.md', + 'debugger.md', + 'frontend.md', + 'optimizer.md', + 'reviewer.md', + 'tester.md', + ]) }) }) diff --git a/src/utils/__tests__/ledger-lifecycle.test.ts b/src/utils/__tests__/ledger-lifecycle.test.ts index 13fb86d..79a04f2 100644 --- a/src/utils/__tests__/ledger-lifecycle.test.ts +++ b/src/utils/__tests__/ledger-lifecycle.test.ts @@ -24,7 +24,7 @@ function manifest(dir: string): string { async function prepareWrapper(installDir: string): Promise { await fs.ensureDir(join(installDir, 'bin')) - if (process.platform !== 'win32') await fs.writeFile(join(installDir, 'bin', 'codeagent-wrapper'), '#!/usr/bin/env node\nconsole.log("codeagent-wrapper version 5.15.0")\n', { mode: 0o755 }) + if (process.platform !== 'win32') await fs.writeFile(join(installDir, 'bin', 'codeagent-wrapper'), '#!/usr/bin/env node\nconsole.log("codeagent-wrapper version 5.16.0")\n', { mode: 0o755 }) } describe('P13: install, force-install and uninstall preserve the ledger', () => { diff --git a/src/utils/__tests__/ledger-templates.test.ts b/src/utils/__tests__/ledger-templates.test.ts index 888d42a..c793777 100644 --- a/src/utils/__tests__/ledger-templates.test.ts +++ b/src/utils/__tests__/ledger-templates.test.ts @@ -44,7 +44,7 @@ describe('installed ledger prompts', () => { it('installs osm-ledger.md next to osm-report.md with ~/.claude rewritten', async () => { const installDir = join(tmpdir(), `osm-tpl-${Date.now()}`, '.claude') await fs.ensureDir(join(installDir, 'bin')) - await fs.writeFile(join(installDir, 'bin', 'codeagent-wrapper'), '#!/usr/bin/env node\nconsole.log("codeagent-wrapper version 5.15.0")\n', { mode: 0o755 }) + await fs.writeFile(join(installDir, 'bin', 'codeagent-wrapper'), '#!/usr/bin/env node\nconsole.log("codeagent-wrapper version 5.16.0")\n', { mode: 0o755 }) await installWorkflows(getAllCommandIds(), installDir, true, { mcpProvider: 'skip' }) const installed = readFileSync(join(installDir, '.ccg', 'prompts', 'claude', 'osm-ledger.md'), 'utf8') expect(installed).toContain(`${installDir}/bin/osm ledger lessons query`) diff --git a/src/utils/__tests__/native-skill-installation.test.ts b/src/utils/__tests__/native-skill-installation.test.ts index a926e11..04c2651 100644 --- a/src/utils/__tests__/native-skill-installation.test.ts +++ b/src/utils/__tests__/native-skill-installation.test.ts @@ -14,7 +14,7 @@ async function setup() { directories.push(root) await fs.ensureDir(join(root, 'bin')) const binary = join(root, 'bin', 'codeagent-wrapper') - await fs.writeFile(binary, '#!/usr/bin/env node\nconsole.log("codeagent-wrapper version 5.15.0")\n', { mode: 0o755 }) + await fs.writeFile(binary, '#!/usr/bin/env node\nconsole.log("codeagent-wrapper version 5.16.0")\n', { mode: 0o755 }) return root } diff --git a/src/utils/__tests__/pi-model-selection.test.ts b/src/utils/__tests__/pi-model-selection.test.ts new file mode 100644 index 0000000..de807e1 --- /dev/null +++ b/src/utils/__tests__/pi-model-selection.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it, vi } from 'vitest' +import { injectConfigVariables } from '../installer-template' +import { promptPiModel, validatePiModel } from '../model-selection' + +vi.mock('inquirer', () => ({ + default: { prompt: vi.fn(async () => ({ selectedPiModel: 'provider/large-context-1m' })) }, +})) + +describe('Pi model configuration', () => { + it.each([ + '', + 'large-context-1m', + 'provider/large-context-1m', + 't2_provider/model.example:version-1', + ])('accepts a valid model or an empty default: %s', (model) => { + expect(validatePiModel(model)).toBe(true) + }) + + it.each(['model with spaces', '--no-mcp', '-h', 'model; rm -rf /', 'model$(command)', 'provider/model\nnext'])('rejects shell syntax: %s', (model) => { + expect(validatePiModel(model)).not.toBe(true) + }) + + it('reads and trims the model from the shared interactive prompt', async () => { + await expect(promptPiModel('existing/model')).resolves.toBe('provider/large-context-1m') + }) + + it('injects the selected Pi model into routed wrapper calls', () => { + const rendered = injectConfigVariables( + 'codeagent-wrapper --backend {{BACKEND_PRIMARY}} {{PI_MODEL_FLAG}}- /work\n' + + 'codeagent-wrapper --backend pi {{PI_MODEL_FLAG}}resume id -\n' + + 'codeagent-wrapper --backend codex {{PI_MODEL_FLAG}}- /work', + { routing: { backend: { models: ['pi'], primary: 'pi' }, piModel: 'provider/large-context-1m' } }, + ) + expect(rendered).toBe( + 'codeagent-wrapper --backend pi --pi-model provider/large-context-1m - /work\n' + + 'codeagent-wrapper --backend pi --pi-model provider/large-context-1m resume id -\n' + + 'codeagent-wrapper --backend codex - /work', + ) + }) + + it('uses the configured Pi default when the model is empty or Pi is not routed', () => { + const template = 'codeagent-wrapper --backend {{BACKEND_PRIMARY}} {{PI_MODEL_FLAG}}-\n{{PI_MODEL_FLAG}}' + expect(injectConfigVariables(template, { + routing: { backend: { models: ['pi'], primary: 'pi' }, piModel: '' }, + })).toBe('codeagent-wrapper --backend pi -\n') + expect(injectConfigVariables(template, { + routing: { backend: { models: ['codex'], primary: 'codex' }, piModel: 'provider/not-routed' }, + })).toBe('codeagent-wrapper --backend codex -\n') + }) +}) diff --git a/src/utils/doctor-checks.ts b/src/utils/doctor-checks.ts index fdd95c2..3546916 100644 --- a/src/utils/doctor-checks.ts +++ b/src/utils/doctor-checks.ts @@ -48,6 +48,7 @@ const BACKENDS: Record { + if (!line.includes('{{PI_MODEL_FLAG}}')) { + return line + } + const m = line.match(hardCodedBackendRe) + if (m && m[1] !== 'pi') { + return line.replace(/\{\{PI_MODEL_FLAG\}\}/g, '') + } + return line.replace(/\{\{PI_MODEL_FLAG\}\}/g, piModelFlagValue) + }).join('\n') + } + // MCP tool injection based on provider (registry-driven) const mcpProvider = config.mcpProvider || 'ace-tool' if (mcpProvider === 'skip') { diff --git a/src/utils/installer.ts b/src/utils/installer.ts index f9650cb..8f42728 100644 --- a/src/utils/installer.ts +++ b/src/utils/installer.ts @@ -92,7 +92,7 @@ export type { SkillMeta } from './skill-registry' * Must match the `version` constant in codeagent-wrapper/main.go. * When this differs from the installed binary, update triggers re-download. */ -const EXPECTED_BINARY_VERSION = '5.15.0' +const EXPECTED_BINARY_VERSION = '5.16.0' // ═══════════════════════════════════════════════════════ // Install context — shared across sub-functions @@ -108,6 +108,7 @@ interface InstallConfig { grokModel?: string kimiModel?: string opencodeModel?: string + piModel?: string } mcpProvider: string skillsProfile?: string[] @@ -309,7 +310,7 @@ async function installPromptFiles(ctx: InstallContext): Promise { return } - for (const model of ['codex', 'gemini', 'claude', 'antigravity', 'grok', 'kimi', 'opencode']) { + for (const model of ['codex', 'gemini', 'claude', 'antigravity', 'grok', 'kimi', 'opencode', 'pi']) { try { const installed = await copyMdTemplates( ctx, @@ -1013,6 +1014,7 @@ export async function installWorkflows( grokModel?: string kimiModel?: string opencodeModel?: string + piModel?: string } mcpProvider?: string skillsProfile?: string[] diff --git a/src/utils/model-selection.ts b/src/utils/model-selection.ts index 6c4e3c3..a2c09d8 100644 --- a/src/utils/model-selection.ts +++ b/src/utils/model-selection.ts @@ -25,3 +25,29 @@ export async function promptOpencodeModel(currentModel = '', isZh = true): Promi }]) return selectedOpencodeModel.trim() } + +/** Pi accepts provider/model or a globally unique model ID; no argv/shell characters. */ +export function validatePiModel(value: string, isZh = true): true | string { + const model = value.trim() + if (!model || /^(?!-)[\w.-]+(?:\/[\w.:/-]+)?$/.test(model)) + return true + return isZh + ? '请填写 provider/model 或唯一模型 ID(不能包含空格或 shell 符号),或留空使用 Pi 默认模型' + : 'Enter provider/model or a unique model ID without spaces or shell syntax, or leave empty for the Pi default' +} + +export async function promptPiModel(currentModel = '', isZh = true): Promise { + const { selectedPiModel } = await inquirer.prompt([{ + type: 'input', + name: 'selectedPiModel', + message: isZh + ? 'Pi 模型 provider/model 或唯一模型 ID(留空使用 Pi 默认)' + : 'Pi model provider/model or unique model ID (empty uses the Pi default)', + default: currentModel, + suffix: isZh + ? '\n 先在 Pi 中配置 provider/模型;用 pi --list-models 查看。支持 1M 上下文需在 Pi/model 自身配置中启用。\n' + : '\n Configure providers/models in Pi first; inspect them with pi --list-models. Enable 1M context in Pi/model configuration.\n', + validate: (value: string) => validatePiModel(value, isZh), + }]) + return selectedPiModel.trim() +} diff --git a/templates/codex/AGENTS.md b/templates/codex/AGENTS.md index fb4ac4d..ce6d77e 100644 --- a/templates/codex/AGENTS.md +++ b/templates/codex/AGENTS.md @@ -127,7 +127,7 @@ ls .ccg/spec/ 2>/dev/null ### ⛔ 默认调用方式:双模型并行(M+ 复杂度必须用这个) ```bash -~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} - "$(pwd)" <<'FRONTEND_EOF' +~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} {{PI_MODEL_FLAG}}- "$(pwd)" <<'FRONTEND_EOF' ROLE_FILE: ~/.claude/.ccg/prompts/{{FRONTEND_PRIMARY}}/$ROLE.md {任务描述 + 上下文} @@ -152,7 +152,7 @@ wait #### {{FRONTEND_PRIMARY}}(前端/UI 分析) ```bash -~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} - "$(pwd)" <<'EOF' +~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} {{PI_MODEL_FLAG}}- "$(pwd)" <<'EOF' ROLE_FILE: ~/.claude/.ccg/prompts/{{FRONTEND_PRIMARY}}/$ROLE.md {任务描述 + 上下文} @@ -287,7 +287,7 @@ Critical 问题 → spawn 修复代理。Warning → 视情况修复。 ```bash # 必须并行调用两个模型审查 git diff -~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} - "$(pwd)" <<'EOF' +~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} {{PI_MODEL_FLAG}}- "$(pwd)" <<'EOF' ROLE_FILE: ~/.claude/.ccg/prompts/{{FRONTEND_PRIMARY}}/reviewer.md 审查以下代码变更:$(git diff) OUTPUT: Critical/Warning/Info 分级审查报告 diff --git a/templates/commands/impl.md b/templates/commands/impl.md index 0eff786..dc0fd4a 100644 --- a/templates/commands/impl.md +++ b/templates/commands/impl.md @@ -52,7 +52,7 @@ description: 'codex/antigravity 按任务写代码,Claude 监控审查 + 归 For each task (independent tasks with disjoint files may go in one `--parallel` batch; use `dependencies:` for ordering): ``` - ~/.claude/bin/codeagent-wrapper --progress --backend <{{BACKEND_PRIMARY}}|{{FRONTEND_PRIMARY}}> {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}- "{{WORKDIR}}" <<'EOF' + ~/.claude/bin/codeagent-wrapper --progress --backend <{{BACKEND_PRIMARY}}|{{FRONTEND_PRIMARY}}> {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}{{PI_MODEL_FLAG}}- "{{WORKDIR}}" <<'EOF' ROLE_FILE: ~/.claude/.ccg/prompts//builder.md You are authorized to edit files in {{WORKDIR}} for this task only. TASK: @@ -85,7 +85,7 @@ description: 'codex/antigravity 按任务写代码,Claude 监控审查 + 归 **FIRST Bash call ({{BACKEND_PRIMARY}})**: ``` Bash({ - command: "~/.claude/bin/codeagent-wrapper --progress --backend {{BACKEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nROLE_FILE: ~/.claude/.ccg/prompts/{{BACKEND_PRIMARY}}/reviewer.md\nReview the uncommitted changes for against the spec constraints. Read callers of every changed function, not only the diff.\nMain candidate: {{WORKDIR}}; inspect `git -C \"{{WORKDIR}}\" diff` and its changed files. With --compare explore, also inspect comparison candidate at , base commit : `git -C \"\" diff ` and its changed files. Report findings separately for each candidate, including candidate name on every finding.\nOUTPUT: JSON with findings per candidate\nEOF", + command: "~/.claude/bin/codeagent-wrapper --progress --backend {{BACKEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}{{PI_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nROLE_FILE: ~/.claude/.ccg/prompts/{{BACKEND_PRIMARY}}/reviewer.md\nReview the uncommitted changes for against the spec constraints. Read callers of every changed function, not only the diff.\nMain candidate: {{WORKDIR}}; inspect `git -C \"{{WORKDIR}}\" diff` and its changed files. With --compare explore, also inspect comparison candidate at , base commit : `git -C \"\" diff ` and its changed files. Report findings separately for each candidate, including candidate name on every finding.\nOUTPUT: JSON with findings per candidate\nEOF", run_in_background: true, timeout: 300000, description: "{{BACKEND_PRIMARY}}: correctness/security review" @@ -95,7 +95,7 @@ description: 'codex/antigravity 按任务写代码,Claude 监控审查 + 归 **SECOND Bash call ({{FRONTEND_PRIMARY}}) — same message**: ``` Bash({ - command: "~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nROLE_FILE: ~/.claude/.ccg/prompts/{{FRONTEND_PRIMARY}}/reviewer.md\nIndependently review the uncommitted changes for : logic, integration and security; UI states and accessibility if UI code changed.\nMain candidate: {{WORKDIR}}; inspect `git -C \"{{WORKDIR}}\" diff` and its changed files. With --compare explore, also inspect comparison candidate at , base commit : `git -C \"\" diff ` and its changed files. Report findings separately for each candidate, including candidate name on every finding.\nOUTPUT: JSON with findings per candidate\nEOF", + command: "~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}{{PI_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nROLE_FILE: ~/.claude/.ccg/prompts/{{FRONTEND_PRIMARY}}/reviewer.md\nIndependently review the uncommitted changes for : logic, integration and security; UI states and accessibility if UI code changed.\nMain candidate: {{WORKDIR}}; inspect `git -C \"{{WORKDIR}}\" diff` and its changed files. With --compare explore, also inspect comparison candidate at , base commit : `git -C \"\" diff ` and its changed files. Report findings separately for each candidate, including candidate name on every finding.\nOUTPUT: JSON with findings per candidate\nEOF", run_in_background: true, timeout: 300000, description: "{{FRONTEND_PRIMARY}}: maintainability/patterns review" diff --git a/templates/commands/init.md b/templates/commands/init.md index 47c0bca..871b985 100644 --- a/templates/commands/init.md +++ b/templates/commands/init.md @@ -68,11 +68,11 @@ description: '初始化 OpenSpec (OPSX) 环境 + 验证多模型 MCP 工具' - **工作目录**:`{{WORKDIR}}` **必须通过 Bash 执行 `pwd`(Unix)或 `cd`(Windows CMD)获取当前工作目录的绝对路径**,禁止从 `$HOME` 或环境变量推断。如果用户通过 `/add-dir` 添加了多个工作区,先确定任务相关的工作区。 - Test {{BACKEND_PRIMARY}} backend: ```bash - echo "echo test" | ~/.claude/bin/codeagent-wrapper --backend {{BACKEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}- "{{WORKDIR}}" + echo "echo test" | ~/.claude/bin/codeagent-wrapper --backend {{BACKEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}{{PI_MODEL_FLAG}}- "{{WORKDIR}}" ``` - Test {{FRONTEND_PRIMARY}} backend: ```bash - echo "echo test" | ~/.claude/bin/codeagent-wrapper --backend {{FRONTEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}- "{{WORKDIR}}" + echo "echo test" | ~/.claude/bin/codeagent-wrapper --backend {{FRONTEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}{{PI_MODEL_FLAG}}- "{{WORKDIR}}" ``` - For each unavailable tool, display warning with installation instructions. diff --git a/templates/commands/plan.md b/templates/commands/plan.md index 460a731..8f11024 100644 --- a/templates/commands/plan.md +++ b/templates/commands/plan.md @@ -32,7 +32,7 @@ description: 'codex + antigravity 交叉分析 → 消除歧义 → 零决策可 **FIRST Bash call ({{BACKEND_PRIMARY}})**: ``` Bash({ - command: "~/.claude/bin/codeagent-wrapper --progress --backend {{BACKEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nAnalyze change from backend perspective:\n- Implementation approach\n- Technical risks\n- Alternative architectures\n- Edge cases and failure modes\nOUTPUT: JSON with analysis\nEOF", + command: "~/.claude/bin/codeagent-wrapper --progress --backend {{BACKEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}{{PI_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nAnalyze change from backend perspective:\n- Implementation approach\n- Technical risks\n- Alternative architectures\n- Edge cases and failure modes\nOUTPUT: JSON with analysis\nEOF", run_in_background: true, timeout: 300000, description: "{{BACKEND_PRIMARY}}: backend analysis" @@ -42,7 +42,7 @@ description: 'codex + antigravity 交叉分析 → 消除歧义 → 零决策可 **SECOND Bash call ({{FRONTEND_PRIMARY}}) — same message**: ``` Bash({ - command: "~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nAnalyze change from frontend/integration perspective:\n- Maintainability assessment\n- Scalability considerations\n- Integration conflicts\nOUTPUT: JSON with analysis\nEOF", + command: "~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}{{PI_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nAnalyze change from frontend/integration perspective:\n- Maintainability assessment\n- Scalability considerations\n- Integration conflicts\nOUTPUT: JSON with analysis\nEOF", run_in_background: true, timeout: 300000, description: "{{FRONTEND_PRIMARY}}: integration analysis" diff --git a/templates/commands/research.md b/templates/commands/research.md index a66df04..7283f28 100644 --- a/templates/commands/research.md +++ b/templates/commands/research.md @@ -57,7 +57,7 @@ description: '需求 → 约束集(codex + antigravity 交叉探索 + OpenSpec **FIRST Bash call ({{BACKEND_PRIMARY}} — backend boundaries)**: ``` Bash({ - command: "~/.claude/bin/codeagent-wrapper --progress --backend {{BACKEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nExplore backend context boundaries for :\n- Existing structures and patterns\n- Conventions in use\n- Hard constraints limiting solution space\n- Dependencies and risks\nOUTPUT: JSON using the output template above\nEOF", + command: "~/.claude/bin/codeagent-wrapper --progress --backend {{BACKEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}{{PI_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nExplore backend context boundaries for :\n- Existing structures and patterns\n- Conventions in use\n- Hard constraints limiting solution space\n- Dependencies and risks\nOUTPUT: JSON using the output template above\nEOF", run_in_background: true, timeout: 300000, description: "{{BACKEND_PRIMARY}}: backend boundary exploration" @@ -67,7 +67,7 @@ description: '需求 → 约束集(codex + antigravity 交叉探索 + OpenSpec **SECOND Bash call ({{FRONTEND_PRIMARY}}) — same message**: ``` Bash({ - command: "~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nIndependently explore context boundaries for from the integration and user-facing side (frontend if any):\n- Existing structures and patterns\n- Conventions in use\n- Hard constraints limiting solution space\n- Dependencies and risks\nOUTPUT: JSON using the output template above\nEOF", + command: "~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}{{PI_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nIndependently explore context boundaries for from the integration and user-facing side (frontend if any):\n- Existing structures and patterns\n- Conventions in use\n- Hard constraints limiting solution space\n- Dependencies and risks\nOUTPUT: JSON using the output template above\nEOF", run_in_background: true, timeout: 300000, description: "{{FRONTEND_PRIMARY}}: integration/user-facing exploration" diff --git a/templates/commands/review.md b/templates/commands/review.md index 004ca32..ee62992 100644 --- a/templates/commands/review.md +++ b/templates/commands/review.md @@ -34,7 +34,7 @@ description: 'codex + antigravity 独立会话交叉审查 → Critical 必须 **FIRST Bash call ({{BACKEND_PRIMARY}})**: ``` Bash({ - command: "~/.claude/bin/codeagent-wrapper --progress --backend {{BACKEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nReview proposal implementation:\n\n## {{BACKEND_PRIMARY}} Review Dimensions\n1. **Spec Compliance**: Verify ALL constraints from spec are satisfied\n2. **PBT Properties**: Check invariants, idempotency, bounds are correctly implemented\n3. **Logic Correctness**: Edge cases, error handling, algorithm correctness\n4. **Backend Security**: Injection vulnerabilities, auth checks, input validation\n5. **Regression Risk**: Callers broken by changed signatures or behavior\n\n## Rules\n- Read callers of every changed function and the tests, not only the diff.\n- Every finding needs a concrete case: this input or state leads to this wrong result. No case, no finding.\n- No style taste, no vague worries. Propose the smallest fix.\n\n## Output Format (JSON)\n{\n \"findings\": [\n {\n \"severity\": \"Critical|Warning|Info\",\n \"dimension\": \"spec_compliance|pbt|logic|security|regression\",\n \"file\": \"path/to/file.ts\",\n \"line\": 42,\n \"description\": \"What is wrong\",\n \"constraint_violated\": \"Constraint ID from spec (if applicable)\",\n \"fix_suggestion\": \"How to fix\"\n }\n ],\n \"passed_checks\": [\"List of verified constraints/properties\"],\n \"summary\": \"Overall assessment\"\n}\nEOF", + command: "~/.claude/bin/codeagent-wrapper --progress --backend {{BACKEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}{{PI_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nReview proposal implementation:\n\n## {{BACKEND_PRIMARY}} Review Dimensions\n1. **Spec Compliance**: Verify ALL constraints from spec are satisfied\n2. **PBT Properties**: Check invariants, idempotency, bounds are correctly implemented\n3. **Logic Correctness**: Edge cases, error handling, algorithm correctness\n4. **Backend Security**: Injection vulnerabilities, auth checks, input validation\n5. **Regression Risk**: Callers broken by changed signatures or behavior\n\n## Rules\n- Read callers of every changed function and the tests, not only the diff.\n- Every finding needs a concrete case: this input or state leads to this wrong result. No case, no finding.\n- No style taste, no vague worries. Propose the smallest fix.\n\n## Output Format (JSON)\n{\n \"findings\": [\n {\n \"severity\": \"Critical|Warning|Info\",\n \"dimension\": \"spec_compliance|pbt|logic|security|regression\",\n \"file\": \"path/to/file.ts\",\n \"line\": 42,\n \"description\": \"What is wrong\",\n \"constraint_violated\": \"Constraint ID from spec (if applicable)\",\n \"fix_suggestion\": \"How to fix\"\n }\n ],\n \"passed_checks\": [\"List of verified constraints/properties\"],\n \"summary\": \"Overall assessment\"\n}\nEOF", run_in_background: true, timeout: 300000, description: "{{BACKEND_PRIMARY}}: backend/logic review" @@ -44,7 +44,7 @@ description: 'codex + antigravity 独立会话交叉审查 → Critical 必须 **SECOND Bash call ({{FRONTEND_PRIMARY}}) — same message**: ``` Bash({ - command: "~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nReview proposal implementation:\n\n## {{FRONTEND_PRIMARY}} Review Dimensions\n1. **Logic**: Edge cases and failure paths the first reviewer may miss\n2. **Integration Risk**: Cross-module impacts, callers, dependency changes\n3. **Security**: Input checks, XSS/CSRF, sensitive data exposure\n4. **Spec Alignment**: Implementation matches spec intent (not just letter)\n5. **UI** (only if UI code changed): broken loading/empty/error states, accessibility\n\n## Rules\n- Read callers of every changed function and the tests, not only the diff.\n- Every finding needs a concrete case: this input or state leads to this wrong result. No case, no finding.\n- No style taste, no vague worries. Propose the smallest fix.\n\n## Output Format (JSON)\n{\n \"findings\": [\n {\n \"severity\": \"Critical|Warning|Info\",\n \"dimension\": \"logic|integration|security|alignment|ui\",\n \"file\": \"path/to/file.ts\",\n \"line\": 42,\n \"description\": \"What is wrong\",\n \"spec_reference\": \"Spec section (if applicable)\",\n \"fix_suggestion\": \"How to fix\"\n }\n ],\n \"passed_checks\": [\"List of verified aspects\"],\n \"summary\": \"Overall assessment\"\n}\nEOF", + command: "~/.claude/bin/codeagent-wrapper --progress --backend {{FRONTEND_PRIMARY}} {{GEMINI_MODEL_FLAG}}{{GROK_MODEL_FLAG}}{{KIMI_MODEL_FLAG}}{{OPENCODE_MODEL_FLAG}}{{PI_MODEL_FLAG}}- \"{{WORKDIR}}\" <<'EOF'\nReview proposal implementation:\n\n## {{FRONTEND_PRIMARY}} Review Dimensions\n1. **Logic**: Edge cases and failure paths the first reviewer may miss\n2. **Integration Risk**: Cross-module impacts, callers, dependency changes\n3. **Security**: Input checks, XSS/CSRF, sensitive data exposure\n4. **Spec Alignment**: Implementation matches spec intent (not just letter)\n5. **UI** (only if UI code changed): broken loading/empty/error states, accessibility\n\n## Rules\n- Read callers of every changed function and the tests, not only the diff.\n- Every finding needs a concrete case: this input or state leads to this wrong result. No case, no finding.\n- No style taste, no vague worries. Propose the smallest fix.\n\n## Output Format (JSON)\n{\n \"findings\": [\n {\n \"severity\": \"Critical|Warning|Info\",\n \"dimension\": \"logic|integration|security|alignment|ui\",\n \"file\": \"path/to/file.ts\",\n \"line\": 42,\n \"description\": \"What is wrong\",\n \"spec_reference\": \"Spec section (if applicable)\",\n \"fix_suggestion\": \"How to fix\"\n }\n ],\n \"passed_checks\": [\"List of verified aspects\"],\n \"summary\": \"Overall assessment\"\n}\nEOF", run_in_background: true, timeout: 300000, description: "{{FRONTEND_PRIMARY}}: patterns/integration review" diff --git a/templates/prompts/pi/analyzer.md b/templates/prompts/pi/analyzer.md new file mode 100644 index 0000000..a58abc6 --- /dev/null +++ b/templates/prompts/pi/analyzer.md @@ -0,0 +1,22 @@ +# Pi Role: Technical Analyst + +You are a senior technical analyst specializing in architecture, system behavior, and strategic technical decisions. + +## Constraints + +- Read-only: do not create, modify, or delete files. +- Return a structured analysis report, not code changes. +- Base findings on repository evidence and explicit assumptions. + +## Expertise + +- Architecture and module boundaries +- Technical debt, scalability, and performance +- Security, privacy, and failure modes +- Compatibility and operational risks + +## Method + +Trace the existing execution path before proposing changes. Identify constraints, +tradeoffs, impacted callers, observability requirements, and validation steps. +When asked for JSON or another output structure, return exactly that structure. diff --git a/templates/prompts/pi/architect.md b/templates/prompts/pi/architect.md new file mode 100644 index 0000000..f8d8a82 --- /dev/null +++ b/templates/prompts/pi/architect.md @@ -0,0 +1,19 @@ +# Pi Role: Software Architect + +You are a senior architect specializing in maintainable interfaces, backend design, APIs, and data integrity. + +## Constraints + +- Read-only: never execute actual modifications. +- Return analysis and a Unified Diff Patch when implementation changes are requested. +- Keep changes minimal and aligned with existing architecture. + +## Expertise + +- API contracts, validation, errors, and compatibility +- Database schemas, concurrency, and transaction boundaries +- Authentication, authorization, and privacy +- Process lifecycles, asynchronous protocols, and observability + +Design from observed constraints. Include migration, rollback, failure behavior, +and test strategy. Do not invent requirements or introduce broad rewrites. diff --git a/templates/prompts/pi/builder.md b/templates/prompts/pi/builder.md new file mode 100644 index 0000000..eda1cea --- /dev/null +++ b/templates/prompts/pi/builder.md @@ -0,0 +1,22 @@ +# Pi Role: Builder (Implementation Agent) + +> For: /osm:impl delegated tasks + +You are an implementation engineer. The orchestrator has planned the work; implement it in the project working directory. + +## Permissions + +- You may create, modify, and delete files required by the task. +- You may run tests, linters, builds, and other relevant commands. +- Do not modify configuration outside the project or change unrelated files. + +## Rules + +1. Read the referenced files, repository instructions, and existing tests first. +2. Follow the requested design; do not widen scope or add speculative features. +3. Preserve existing public contracts unless explicitly permitted otherwise. +4. Handle errors, resource cleanup, and requested output formats deliberately. +5. Run focused checks, then relevant broader checks. Treat failures as actionable. +6. Report changed files, verification results, and unresolved limitations honestly. + +Never claim commands or tests ran unless you observed the tool results. diff --git a/templates/prompts/pi/debugger.md b/templates/prompts/pi/debugger.md new file mode 100644 index 0000000..006da28 --- /dev/null +++ b/templates/prompts/pi/debugger.md @@ -0,0 +1,18 @@ +# Pi Role: Debugging Specialist + +You are a senior debugging specialist focused on reproducible failures and root-cause isolation. + +## Constraints + +- Read-only unless the request explicitly assigns implementation. +- Produce a structured diagnostic report; do not make speculative changes. +- Separate observed evidence from hypotheses. + +## Method + +Reproduce the failure, inspect logs and state, trace inputs through the execution +path, and identify the earliest divergent behavior. Consider timing, concurrency, +I/O framing, process cleanup, permissions, and platform differences. + +For the leading cause, cite file:line evidence, propose the smallest fix, and give +a regression test that fails before and passes after the fix. List discarded hypotheses. diff --git a/templates/prompts/pi/frontend.md b/templates/prompts/pi/frontend.md new file mode 100644 index 0000000..dbc32c9 --- /dev/null +++ b/templates/prompts/pi/frontend.md @@ -0,0 +1,19 @@ +# Pi Role: Frontend Specialist + +You are a senior frontend engineer specializing in UI architecture, accessibility, performance, and reliable state handling. + +## Constraints + +- Read-only unless implementation is explicitly assigned. +- Do not alter files during analysis. +- Return actionable analysis and targeted patches, not unrelated redesigns. + +## Expertise + +- React/Vue/Svelte/Angular and platform-native interfaces +- Responsive layout, styling, and design systems +- Keyboard, focus, screen reader, loading, empty, and error states +- Rendering performance and asynchronous state consistency + +Verify actual component and data flows. Include regression checks for interaction, +accessibility, and visual states. Follow product requirements and existing conventions. diff --git a/templates/prompts/pi/optimizer.md b/templates/prompts/pi/optimizer.md new file mode 100644 index 0000000..98955c7 --- /dev/null +++ b/templates/prompts/pi/optimizer.md @@ -0,0 +1,16 @@ +# Pi Role: Performance Optimizer + +You are a senior performance engineer specializing in measurement-driven backend and client optimization. + +## Constraints + +- Read-only unless implementation is explicitly assigned. +- Measure before optimizing; no speculative rewrites. +- Return an analysis and a Unified Diff Patch when changes are requested. + +## Method + +Establish a baseline and representative workload. Locate bottlenecks using evidence, +then evaluate asymptotic complexity, memory use, I/O, concurrency, and resource cleanup. +Preserve behavior and public contracts. Quantify wins, tradeoffs, and regression checks. +Avoid caching or concurrency changes without addressing consistency and invalidation. diff --git a/templates/prompts/pi/reviewer.md b/templates/prompts/pi/reviewer.md new file mode 100644 index 0000000..1d9257a --- /dev/null +++ b/templates/prompts/pi/reviewer.md @@ -0,0 +1,26 @@ +# Pi Role: Code Reviewer + +> For: /osm:review, /osm:impl review step + +Review a change like the developer who gets paged when it breaks. Read-only: do not modify files. + +## Understand first + +- Read the diff, all callers/callees of changed functions, and relevant tests. +- Trace the actual data, error, cancellation, and process-lifecycle flows. +- Find concrete regressions, not hypothetical architecture preferences. + +## Priorities + +1. Correctness and data loss +2. Security, privacy, and trust-boundary violations +3. Failure handling and resource cleanup +4. API compatibility and cross-platform behavior +5. Missing regression tests + +## Output + +Return structured findings ordered by severity. For each finding include file:line, +the specific execution path, observable impact, a reproducing input or state, and +the smallest suitable fix. State assumptions and checked non-issues separately. +Do not report style preferences or unverified claims. diff --git a/templates/prompts/pi/tester.md b/templates/prompts/pi/tester.md new file mode 100644 index 0000000..8969572 --- /dev/null +++ b/templates/prompts/pi/tester.md @@ -0,0 +1,16 @@ +# Pi Role: Test Engineer + +You are a senior test engineer specializing in behavioral regression tests, integration contracts, and failure-path coverage. + +## Constraints + +- Read-only analysis unless test implementation is explicitly assigned. +- Test-file changes only; never modify production code to make tests pass. +- Return Unified Diff Patches when modifications are requested. + +## Method + +Start from the existing test conventions. Cover normal behavior, malformed input, +boundaries, concurrency, timeouts, cancellation, resource cleanup, and error propagation +where relevant. Tests must verify observable behavior rather than implementation trivia. +Include the command used to execute them and distinguish coverage from execution proof.