| 1 | // Package backend describes the CLI contracts used by Klaus coordinators and workers. |
| 2 | package backend |
| 3 | |
| 4 | import ( |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | type Kind string |
| 13 | |
| 14 | const ( |
| 15 | Claude Kind = "claude" |
| 16 | Codex Kind = "codex" |
| 17 | Agy Kind = "agy" |
| 18 | ) |
| 19 | |
| 20 | func Parse(s string) (Kind, error) { |
| 21 | if s == "" { |
| 22 | return Claude, nil |
| 23 | } |
| 24 | switch Kind(s) { |
| 25 | case Claude, Codex, Agy: |
| 26 | return Kind(s), nil |
| 27 | } |
| 28 | return "", fmt.Errorf("unknown backend %q: choose claude, codex, or agy", s) |
| 29 | } |
| 30 | |
| 31 | func (k Kind) ValidateEffort(s string) error { |
| 32 | if s == "" { |
| 33 | return nil |
| 34 | } |
| 35 | allowed := "low medium high" |
| 36 | if k == Claude { |
| 37 | allowed += " xhigh max" |
| 38 | } |
| 39 | if k == Codex { |
| 40 | allowed += " minimal xhigh" |
| 41 | } |
| 42 | for _, v := range strings.Fields(allowed) { |
| 43 | if s == v { |
| 44 | return nil |
| 45 | } |
| 46 | } |
| 47 | return fmt.Errorf("invalid effort %q for %s: choose %s", s, k, allowed) |
| 48 | } |
| 49 | |
| 50 | // ClaudeSettings turns off Claude Code's commit trailer, PR-body line and |
| 51 | // session link. --settings layers this over the user's settings files rather |
| 52 | // than replacing them. Klaus work must not carry AI attribution; the |
| 53 | // commit-msg hook and the agent brief enforce the same rule. |
| 54 | const ClaudeSettings = `{"attribution":{"commit":"","pr":"","sessionUrl":false}}` |
| 55 | |
| 56 | // ClaudeSettingsWithStatusLine is ClaudeSettings plus a status line showing |
| 57 | // repoName and the branch checked out where the coordinator runs. klaus |
| 58 | // writes it to a file in the session's state that Options.SettingsFile |
| 59 | // names, never into the worktree, where git would see it. A repository's own |
| 60 | // .claude/settings.json still loads beneath it, untouched. Workers get no |
| 61 | // status line: claude -p, piped into _format-stream, never renders one. |
| 62 | func ClaudeSettingsWithStatusLine(repoName string) string { |
| 63 | var settings map[string]any |
| 64 | if err := json.Unmarshal([]byte(ClaudeSettings), &settings); err != nil { |
| 65 | panic(err) |
| 66 | } |
| 67 | settings["statusLine"] = map[string]any{ |
| 68 | "type": "command", |
| 69 | "command": fmt.Sprintf( |
| 70 | `input=$(cat); cwd=$(echo "$input" | jq -r '.workspace.current_dir'); branch=$(git -C "$cwd" --no-optional-locks branch --show-current 2>/dev/null); if [ -n "$branch" ]; then echo "%s ($branch)"; else echo "%s"; fi`, |
| 71 | repoName, repoName, |
| 72 | ), |
| 73 | } |
| 74 | out, err := json.MarshalIndent(settings, "", " ") |
| 75 | if err != nil { |
| 76 | panic(err) |
| 77 | } |
| 78 | return string(out) + "\n" |
| 79 | } |
| 80 | |
| 81 | type Options struct { |
| 82 | SystemPrompt, Prompt, RunID, ResumeID, Model, Effort, Budget string |
| 83 | // SystemPromptFile replaces SystemPrompt for Claude workers; other backends have no file flag. |
| 84 | SystemPromptFile string |
| 85 | // SettingsFile replaces the inline ClaudeSettings for a Claude coordinator |
| 86 | // with a file holding ClaudeSettingsWithStatusLine. Claude takes one |
| 87 | // --settings, so the file carries ClaudeSettings too. Workers always get |
| 88 | // the inline settings; other backends have no settings flag. |
| 89 | SettingsFile string |
| 90 | Continue bool |
| 91 | } |
| 92 | |
| 93 | // Worker returns argv, without shell interpolation. The prompt is never in |
| 94 | // argv: the caller feeds the worker k.Stdin(o.SystemPrompt, o.Prompt) on |
| 95 | // stdin, which keeps long briefs out of the tmux command. Dollar budgets are |
| 96 | // a Claude capability. |
| 97 | func (k Kind) Worker(o Options) []string { |
| 98 | var a []string |
| 99 | switch k { |
| 100 | case Claude: |
| 101 | a = []string{"claude", "-p", "-n", o.RunID} |
| 102 | if o.ResumeID != "" { |
| 103 | a = append(a, "--resume", o.ResumeID, "--fork-session") |
| 104 | } |
| 105 | a = append(a, "--dangerously-skip-permissions", "--verbose", "--output-format", "stream-json", "--max-budget-usd", o.Budget, "--settings", ClaudeSettings) |
| 106 | if o.SystemPromptFile != "" { |
| 107 | a = append(a, "--append-system-prompt-file", o.SystemPromptFile) |
| 108 | } else { |
| 109 | a = append(a, "--append-system-prompt", o.SystemPrompt) |
| 110 | } |
| 111 | case Codex: |
| 112 | a = []string{"codex", "exec"} |
| 113 | if o.ResumeID != "" { |
| 114 | a = append(a, "fork", o.ResumeID) |
| 115 | } |
| 116 | a = append(a, "--json", "--dangerously-bypass-approvals-and-sandbox", "-c", "developer_instructions="+tomlString(o.SystemPrompt)) |
| 117 | case Agy: |
| 118 | a = []string{"agy", "--add-dir", ".", "--output-format", "stream-json", "--dangerously-skip-permissions", "--print-timeout", "24h"} |
| 119 | } |
| 120 | a = k.modelArgs(a, o) |
| 121 | if k == Codex { |
| 122 | // "-" reads stdin; exec fork needs it spelled out. |
| 123 | return append(a, "-") |
| 124 | } |
| 125 | // claude -p reads stdin when no prompt argument is given. agy, given no |
| 126 | // --print, runs print mode on the prompt it reads from a stdin that isn't |
| 127 | // a terminal; --print "-" would be taken as the literal prompt. |
| 128 | return a |
| 129 | } |
| 130 | |
| 131 | // need is a command a backend's worker runs by name, and why. |
| 132 | type need struct{ command, why string } |
| 133 | |
| 134 | // needs are the commands each backend's worker runs by name, so they must |
| 135 | // resolve on the PATH it gets: its own CLI, and for agy, bash, which runs |
| 136 | // every command agy's run_command tool runs. An agy worker without bash |
| 137 | // can't run any command, only edit files. |
| 138 | func (k Kind) needs() []need { |
| 139 | cli := need{string(k), "the worker's own CLI"} |
| 140 | if k == Agy { |
| 141 | return []need{cli, {"bash", "agy runs every command through bash"}} |
| 142 | } |
| 143 | return []need{cli} |
| 144 | } |
| 145 | |
| 146 | // CheckPath returns an error naming the first command k's worker needs that |
| 147 | // doesn't resolve on path, a PATH value, for a worker that runs in dir, and |
| 148 | // the PATH it searched. |
| 149 | func (k Kind) CheckPath(path, dir string) error { |
| 150 | for _, n := range k.needs() { |
| 151 | if !onPath(n.command, path, dir) { |
| 152 | return fmt.Errorf("the %s worker can't run: %s isn't on the PATH it gets (%s); searched PATH=%q", k, n.command, n.why, path) |
| 153 | } |
| 154 | } |
| 155 | return nil |
| 156 | } |
| 157 | |
| 158 | // onPath reports whether name resolves to an executable file in a directory |
| 159 | // of path, as a shell's PATH lookup finds it in cwd: an empty or relative |
| 160 | // entry is taken from cwd. |
| 161 | func onPath(name, path, cwd string) bool { |
| 162 | for _, dir := range filepath.SplitList(path) { |
| 163 | if !filepath.IsAbs(dir) { |
| 164 | dir = filepath.Join(cwd, dir) |
| 165 | } |
| 166 | info, err := os.Stat(filepath.Join(dir, name)) |
| 167 | if err == nil && info.Mode().IsRegular() && info.Mode().Perm()&0o111 != 0 { |
| 168 | return true |
| 169 | } |
| 170 | } |
| 171 | return false |
| 172 | } |
| 173 | |
| 174 | // Stdin is what a worker or a one-shot call reads on stdin: the prompt, with |
| 175 | // the system prompt ahead of it for agy, which has no flag for one. |
| 176 | func (k Kind) Stdin(systemPrompt, prompt string) string { |
| 177 | if k == Agy { |
| 178 | return systemPrompt + "\n\n" + prompt |
| 179 | } |
| 180 | return prompt |
| 181 | } |
| 182 | |
| 183 | func (k Kind) Coordinator(o Options) []string { |
| 184 | var a []string |
| 185 | switch k { |
| 186 | case Claude: |
| 187 | settings := ClaudeSettings |
| 188 | if o.SettingsFile != "" { |
| 189 | settings = o.SettingsFile |
| 190 | } |
| 191 | a = []string{"claude", "--dangerously-skip-permissions", "-n", o.RunID, "--settings", settings, "--append-system-prompt", o.SystemPrompt} |
| 192 | if o.Continue { |
| 193 | if o.ResumeID != "" { |
| 194 | a = append(a, "--resume", o.ResumeID) |
| 195 | } else { |
| 196 | a = append(a, "--continue") |
| 197 | } |
| 198 | } else if o.ResumeID != "" { |
| 199 | a = append(a, "--session-id", o.ResumeID) |
| 200 | } |
| 201 | case Codex: |
| 202 | a = []string{"codex"} |
| 203 | if o.Continue { |
| 204 | // Klaus allocates a distinct workspace per coordinator; do not add --all. |
| 205 | a = append(a, "resume", "--last") |
| 206 | } |
| 207 | a = append(a, "--dangerously-bypass-approvals-and-sandbox", "-c", "developer_instructions="+tomlString(o.SystemPrompt)) |
| 208 | case Agy: |
| 209 | prompt := o.SystemPrompt |
| 210 | if o.Continue && o.ResumeID != "" { |
| 211 | prompt = "Flow coordinator session resumed. Continue using the existing coordinator instructions; use valley flow status to refresh worker state. Your background valley flow watch ended with the last session: start the command on the latest next: line it printed again as a background task, or, if no watch printed one, the first watch command your instructions give." |
| 212 | } |
| 213 | a = []string{"agy", "--add-dir", ".", "--dangerously-skip-permissions", "--prompt-interactive", prompt} |
| 214 | if o.Continue && o.ResumeID != "" { |
| 215 | a = append(a, "--conversation", o.ResumeID) |
| 216 | } |
| 217 | } |
| 218 | return k.modelArgs(a, o) |
| 219 | } |
| 220 | |
| 221 | func (k Kind) modelArgs(a []string, o Options) []string { |
| 222 | if o.Model != "" { |
| 223 | a = append(a, "--model", o.Model) |
| 224 | } |
| 225 | if o.Effort != "" { |
| 226 | if k == Codex { |
| 227 | a = append(a, "-c", "model_reasoning_effort="+tomlString(o.Effort)) |
| 228 | } else { |
| 229 | a = append(a, "--effort", o.Effort) |
| 230 | } |
| 231 | } |
| 232 | return a |
| 233 | } |
| 234 | |
| 235 | // ShellCommand quotes every argument, including multiline prompts and model names. |
| 236 | func ShellCommand(args []string) string { |
| 237 | quoted := make([]string, len(args)) |
| 238 | for i, a := range args { |
| 239 | quoted[i] = "'" + strings.ReplaceAll(a, "'", "'\\''") + "'" |
| 240 | } |
| 241 | return strings.Join(quoted, " ") |
| 242 | } |
| 243 | |
| 244 | // JSON string quoting uses TOML-compatible Unicode escapes for control characters. |
| 245 | func tomlString(s string) string { |
| 246 | b, _ := json.Marshal(s) |
| 247 | return strings.ReplaceAll(string(b), "\x7f", `\u007f`) |
| 248 | } |