cli-router 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cli_router/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """CLI-Router package."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,50 @@
1
+ """Run artifact persistence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import yaml
11
+
12
+ from .runner import ToolRunResult
13
+
14
+
15
+ def create_run_dir(run_root: str | Path) -> Path:
16
+ root = Path(run_root)
17
+ root.mkdir(parents=True, exist_ok=True)
18
+
19
+ base = datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
20
+ candidate = root / base
21
+ counter = 1
22
+ while candidate.exists():
23
+ candidate = root / f"{base}-{counter}"
24
+ counter += 1
25
+ candidate.mkdir()
26
+ return candidate
27
+
28
+
29
+ def write_stage_artifacts(run_dir: Path, stage_id: str, result: ToolRunResult, extracted: str | None = None) -> None:
30
+ (run_dir / f"{stage_id}.stdout").write_text(result.stdout, encoding="utf-8")
31
+ (run_dir / f"{stage_id}.stderr").write_text(result.stderr, encoding="utf-8")
32
+ if extracted is not None:
33
+ (run_dir / f"{stage_id}.extracted.md").write_text(extracted, encoding="utf-8")
34
+
35
+
36
+ def write_run_manifest(run_dir: Path, manifest: dict[str, Any]) -> None:
37
+ serializable = _serialize(manifest)
38
+ (run_dir / "run.yaml").write_text(yaml.safe_dump(serializable, sort_keys=False), encoding="utf-8")
39
+
40
+
41
+ def _serialize(value: Any) -> Any:
42
+ if isinstance(value, Path):
43
+ return str(value)
44
+ if hasattr(value, "__dataclass_fields__"):
45
+ return _serialize(asdict(value))
46
+ if isinstance(value, dict):
47
+ return {key: _serialize(item) for key, item in value.items()}
48
+ if isinstance(value, list):
49
+ return [_serialize(item) for item in value]
50
+ return value
cli_router/cli.py ADDED
@@ -0,0 +1,96 @@
1
+ """Command-line interface for CLI-Router."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from typing import Sequence
8
+
9
+ from .config import ConfigError, config_to_yaml, load_config
10
+ from .tools import list_tools, test_tool
11
+ from .workflows import WorkflowSummary, implement_workflow, plan_workflow, run_workflow
12
+
13
+
14
+ def main(argv: Sequence[str] | None = None) -> int:
15
+ parser = _build_parser()
16
+ try:
17
+ args = parser.parse_args(argv)
18
+ except SystemExit as exc:
19
+ return int(exc.code)
20
+
21
+ try:
22
+ config = load_config(args.config)
23
+ if args.command == "plan":
24
+ return _print_summary(plan_workflow(config, args.prompt, args.workflow))
25
+ if args.command == "run":
26
+ return _print_summary(run_workflow(config, args.prompt, args.workflow))
27
+ if args.command == "implement":
28
+ return _print_summary(implement_workflow(config, args.workflow))
29
+ if args.command == "check":
30
+ print("Configuration OK")
31
+ return 0
32
+ if args.command == "config" and args.config_command == "show":
33
+ print(config_to_yaml(config), end="")
34
+ return 0
35
+ if args.command == "tools" and args.tools_command == "list":
36
+ for name in list_tools(config):
37
+ print(name)
38
+ return 0
39
+ if args.command == "tools" and args.tools_command == "test":
40
+ summary = test_tool(config, args.name)
41
+ print(f"{args.name}: exit {summary.result.returncode}")
42
+ print(f"run_dir: {summary.run_dir}")
43
+ return summary.result.returncode
44
+ except (ConfigError, KeyError) as exc:
45
+ print(f"cli-router: {exc}", file=sys.stderr)
46
+ return 2
47
+
48
+ parser.print_help()
49
+ return 0
50
+
51
+
52
+ def _build_parser() -> argparse.ArgumentParser:
53
+ parser = argparse.ArgumentParser(prog="cli-router", description="Route planning and coding stages across external CLIs.")
54
+ parser.add_argument("--config", help="Path to a cli-router YAML config file.")
55
+
56
+ subparsers = parser.add_subparsers(dest="command")
57
+
58
+ run_parser = subparsers.add_parser("run", help="Run planner and coder stages.")
59
+ run_parser.add_argument("prompt")
60
+ run_parser.add_argument("--workflow", default="default")
61
+
62
+ plan_parser = subparsers.add_parser("plan", help="Run only the planner stage.")
63
+ plan_parser.add_argument("prompt")
64
+ plan_parser.add_argument("--workflow", default="default")
65
+
66
+ implement_parser = subparsers.add_parser("implement", help="Run only the coder stage using the plan file.")
67
+ implement_parser.add_argument("--workflow", default="default")
68
+
69
+ subparsers.add_parser("check", help="Validate the loaded configuration.")
70
+
71
+ config_parser = subparsers.add_parser("config", help="Inspect configuration.")
72
+ config_subparsers = config_parser.add_subparsers(dest="config_command")
73
+ config_subparsers.add_parser("show", help="Print the loaded configuration.")
74
+
75
+ tools_parser = subparsers.add_parser("tools", help="Inspect configured tools.")
76
+ tools_subparsers = tools_parser.add_subparsers(dest="tools_command")
77
+ tools_subparsers.add_parser("list", help="List configured tools.")
78
+ test_parser = tools_subparsers.add_parser("test", help="Run a configured tool with a test prompt.")
79
+ test_parser.add_argument("name")
80
+
81
+ return parser
82
+
83
+
84
+ def _print_summary(summary: WorkflowSummary) -> int:
85
+ print(f"run_dir: {summary.run_dir}")
86
+ print(f"plan_path: {summary.plan_path}")
87
+ for stage in summary.stages:
88
+ print(f"{stage.stage_id}: exit {stage.result.returncode}")
89
+ if summary.error:
90
+ print(f"error: {summary.error}", file=sys.stderr)
91
+ print(f"exit_code: {summary.exit_code}")
92
+ return summary.exit_code
93
+
94
+
95
+ if __name__ == "__main__":
96
+ raise SystemExit(main())
cli_router/config.py ADDED
@@ -0,0 +1,139 @@
1
+ """Configuration loading and validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from copy import deepcopy
6
+ from dataclasses import dataclass
7
+ from importlib import resources
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import yaml
12
+
13
+
14
+ class ConfigError(RuntimeError):
15
+ """Raised when CLI-Router configuration is invalid."""
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class RouterConfig:
20
+ data: dict[str, Any]
21
+ source: Path | None
22
+
23
+ @property
24
+ def defaults(self) -> dict[str, Any]:
25
+ return self.data.setdefault("defaults", {})
26
+
27
+ @property
28
+ def tools(self) -> dict[str, Any]:
29
+ return self.data.setdefault("tools", {})
30
+
31
+ @property
32
+ def workflows(self) -> dict[str, Any]:
33
+ return self.data.setdefault("workflows", {})
34
+
35
+
36
+ CONFIG_CANDIDATES = (
37
+ Path("cli-router.yaml"),
38
+ Path(".cli-router.yaml"),
39
+ Path.home() / ".config" / "cli-router" / "config.yaml",
40
+ )
41
+
42
+
43
+ def load_config(path: str | Path | None = None) -> RouterConfig:
44
+ source = Path(path) if path else _find_config()
45
+ config = _built_in_config()
46
+
47
+ if source:
48
+ user_config = _read_yaml(source)
49
+ _validate_version(user_config, source)
50
+ config = _deep_merge(config, user_config)
51
+
52
+ _validate_config(config, source)
53
+ return RouterConfig(config, source)
54
+
55
+
56
+ def config_to_yaml(config: RouterConfig) -> str:
57
+ return yaml.safe_dump(config.data, sort_keys=False)
58
+
59
+
60
+ def _find_config() -> Path | None:
61
+ for candidate in CONFIG_CANDIDATES:
62
+ if candidate.exists():
63
+ return candidate.resolve()
64
+ return None
65
+
66
+
67
+ def _built_in_config() -> dict[str, Any]:
68
+ text = resources.files("cli_router.presets").joinpath("generic.yaml").read_text(encoding="utf-8")
69
+ data = yaml.safe_load(text) or {}
70
+ _validate_version(data, None)
71
+ return data
72
+
73
+
74
+ def _read_yaml(path: Path) -> dict[str, Any]:
75
+ try:
76
+ loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
77
+ except OSError as exc:
78
+ raise ConfigError(f"Could not read config {path}: {exc}") from exc
79
+ except yaml.YAMLError as exc:
80
+ raise ConfigError(f"Invalid YAML in {path}: {exc}") from exc
81
+
82
+ if loaded is None:
83
+ return {}
84
+ if not isinstance(loaded, dict):
85
+ raise ConfigError(f"Config {path} must contain a YAML mapping")
86
+ return loaded
87
+
88
+
89
+ def _validate_version(data: dict[str, Any], source: Path | None) -> None:
90
+ version = data.get("version", 1)
91
+ if version != 1:
92
+ location = f" in {source}" if source else ""
93
+ raise ConfigError(f"Unsupported config version{location}: {version}")
94
+
95
+
96
+ def _validate_config(data: dict[str, Any], source: Path | None) -> None:
97
+ _validate_version(data, source)
98
+ if not isinstance(data.get("defaults", {}), dict):
99
+ raise ConfigError("defaults must be a mapping")
100
+ if not isinstance(data.get("tools", {}), dict):
101
+ raise ConfigError("tools must be a mapping")
102
+ if not isinstance(data.get("workflows", {}), dict):
103
+ raise ConfigError("workflows must be a mapping")
104
+
105
+ for name, tool in data.get("tools", {}).items():
106
+ if not isinstance(tool, dict):
107
+ raise ConfigError(f"tool {name!r} must be a mapping")
108
+ if "command" not in tool:
109
+ raise ConfigError(f"tool {name!r} is missing command")
110
+
111
+ for name, workflow in data.get("workflows", {}).items():
112
+ if not isinstance(workflow, dict):
113
+ raise ConfigError(f"workflow {name!r} must be a mapping")
114
+ stages = workflow.get("stages", [])
115
+ if not isinstance(stages, list):
116
+ raise ConfigError(f"workflow {name!r} stages must be a list")
117
+ for stage in stages:
118
+ if not isinstance(stage, dict):
119
+ raise ConfigError(f"workflow {name!r} stage must be a mapping")
120
+ if "id" not in stage or "tool" not in stage:
121
+ raise ConfigError(f"workflow {name!r} stage is missing id or tool")
122
+ if stage["tool"] not in data.get("tools", {}):
123
+ raise ConfigError(f"workflow {name!r} references unknown tool {stage['tool']!r}")
124
+ fallback_tools = stage.get("fallback_tools", [])
125
+ if not isinstance(fallback_tools, list):
126
+ raise ConfigError(f"workflow {name!r} stage fallback_tools must be a list")
127
+ for fallback_tool in fallback_tools:
128
+ if fallback_tool not in data.get("tools", {}):
129
+ raise ConfigError(f"workflow {name!r} references unknown fallback tool {fallback_tool!r}")
130
+
131
+
132
+ def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
133
+ result = deepcopy(base)
134
+ for key, value in override.items():
135
+ if isinstance(value, dict) and isinstance(result.get(key), dict):
136
+ result[key] = _deep_merge(result[key], value)
137
+ else:
138
+ result[key] = deepcopy(value)
139
+ return result
@@ -0,0 +1,39 @@
1
+ """Output extraction helpers for external CLI results."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+
9
+ class ExtractionError(RuntimeError):
10
+ """Raised when tool output cannot be extracted as configured."""
11
+
12
+
13
+ def extract_output(stdout: str, output_config: dict[str, Any] | None = None) -> str:
14
+ config = output_config or {}
15
+ output_format = config.get("format", "text")
16
+
17
+ if output_format == "text":
18
+ return stdout
19
+ if output_format == "json":
20
+ return _extract_json(stdout, config.get("extract"))
21
+
22
+ raise ExtractionError(f"Unsupported output format: {output_format}")
23
+
24
+
25
+ def _extract_json(stdout: str, path: str | None) -> str:
26
+ try:
27
+ value: Any = json.loads(stdout)
28
+ except json.JSONDecodeError as exc:
29
+ raise ExtractionError(f"Invalid JSON output: {exc}") from exc
30
+
31
+ if path:
32
+ for part in path.split("."):
33
+ if not isinstance(value, dict) or part not in value:
34
+ raise ExtractionError(f"Missing JSON extraction path: {path}")
35
+ value = value[part]
36
+
37
+ if isinstance(value, str):
38
+ return value
39
+ return json.dumps(value, indent=2, sort_keys=True)
cli_router/failures.py ADDED
@@ -0,0 +1,52 @@
1
+ """Failure helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .runner import ToolRunResult
6
+
7
+
8
+ USAGE_LIMIT_PATTERNS = (
9
+ "usage limit",
10
+ "session limit",
11
+ "hit your limit",
12
+ "hit your session limit",
13
+ "rate limit",
14
+ "quota exceeded",
15
+ "credit balance is too low",
16
+ "too many requests",
17
+ "429",
18
+ )
19
+
20
+ UNSUPPORTED_MODEL_PATTERNS = (
21
+ "model is not supported",
22
+ "model not supported",
23
+ "unsupported model",
24
+ )
25
+
26
+
27
+ def classify_failure(result: ToolRunResult) -> str | None:
28
+ if result.returncode == 0:
29
+ return None
30
+ combined = f"{result.stdout}\n{result.stderr}".lower()
31
+ if result.returncode == 124 or "timed out" in combined:
32
+ return "timeout"
33
+ if any(pattern in combined for pattern in USAGE_LIMIT_PATTERNS):
34
+ return "usage_limit"
35
+ if any(pattern in combined for pattern in UNSUPPORTED_MODEL_PATTERNS):
36
+ return "unsupported_model"
37
+ if result.returncode == 127:
38
+ return "command_not_found"
39
+ return "command_failed"
40
+
41
+
42
+ def stage_failure_message(stage_id: str, result: ToolRunResult) -> str:
43
+ failure_kind = classify_failure(result)
44
+ if failure_kind == "usage_limit":
45
+ return f"Stage {stage_id!r} failed because the provider reported a usage limit"
46
+ if failure_kind == "command_not_found":
47
+ return f"Stage {stage_id!r} failed because the command was not found"
48
+ if failure_kind == "timeout":
49
+ return f"Stage {stage_id!r} failed because the command timed out"
50
+ if failure_kind == "unsupported_model":
51
+ return f"Stage {stage_id!r} failed because the configured model is not supported by the provider"
52
+ return f"Stage {stage_id!r} failed with exit code {result.returncode}"
@@ -0,0 +1 @@
1
+ """Built-in CLI-Router presets."""
@@ -0,0 +1,14 @@
1
+ tools:
2
+ claude-planner:
3
+ type: claude
4
+ command:
5
+ - claude
6
+ - -p
7
+ - --permission-mode
8
+ - plan
9
+ - --output-format
10
+ - json
11
+ - "{prompt}"
12
+ output:
13
+ format: json
14
+ extract: result
@@ -0,0 +1,9 @@
1
+ tools:
2
+ codex-coder:
3
+ type: codex
4
+ command:
5
+ - codex
6
+ - exec
7
+ - "{prompt}"
8
+ output:
9
+ format: text
@@ -0,0 +1,60 @@
1
+ version: 1
2
+
3
+ defaults:
4
+ plan_file: PLAN.md
5
+ run_dir: .cli-router/runs
6
+ stop_on_failure: true
7
+
8
+ tools:
9
+ generic-planner:
10
+ type: generic
11
+ command:
12
+ - python
13
+ - -c
14
+ - "import sys; print(sys.argv[1])"
15
+ - "{prompt}"
16
+ output:
17
+ format: text
18
+
19
+ generic-coder:
20
+ type: generic
21
+ command:
22
+ - python
23
+ - -c
24
+ - "import sys; print(sys.argv[1])"
25
+ - "{prompt}"
26
+ output:
27
+ format: text
28
+
29
+ workflows:
30
+ default:
31
+ stages:
32
+ - id: planner
33
+ tool: generic-planner
34
+ input_template: |
35
+ You are the planning model for a coding-agent handoff.
36
+
37
+ User request:
38
+ {user_prompt}
39
+
40
+ Inspect this repository and produce a concrete implementation plan.
41
+
42
+ Do not edit files.
43
+
44
+ Write the plan in Markdown.
45
+ output_file: PLAN.md
46
+
47
+ - id: coder
48
+ tool: generic-coder
49
+ input_template: |
50
+ Please implement the plan in {plan_path}.
51
+
52
+ Original user request:
53
+ {user_prompt}
54
+
55
+ Rules:
56
+ - Read the plan first.
57
+ - Follow it closely.
58
+ - Make the smallest safe changes.
59
+ - Run relevant tests.
60
+ - Report any deviations.
@@ -0,0 +1,9 @@
1
+ tools:
2
+ hermes-coder:
3
+ type: hermes
4
+ command:
5
+ - hermes
6
+ - run
7
+ - "{prompt}"
8
+ output:
9
+ format: text
cli_router/runner.py ADDED
@@ -0,0 +1,75 @@
1
+ """Subprocess runner for configured external tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shlex
6
+ import subprocess
7
+ from dataclasses import dataclass
8
+ from typing import Any, Mapping
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class ToolRunResult:
13
+ command: list[str]
14
+ returncode: int
15
+ stdout: str
16
+ stderr: str
17
+
18
+
19
+ def run_tool(tool: Mapping[str, Any], variables: Mapping[str, Any]) -> ToolRunResult:
20
+ raw_command = tool.get("command")
21
+ if not raw_command:
22
+ return ToolRunResult([], 2, "", "Tool is missing a command\n")
23
+
24
+ command = _normalize_command(raw_command)
25
+ rendered = [_render_arg(arg, variables) for arg in command]
26
+ timeout_seconds = _timeout_seconds(tool.get("timeout_seconds"))
27
+
28
+ try:
29
+ completed = subprocess.run(
30
+ rendered,
31
+ capture_output=True,
32
+ text=True,
33
+ check=False,
34
+ timeout=timeout_seconds,
35
+ )
36
+ except subprocess.TimeoutExpired as exc:
37
+ stdout = exc.stdout or ""
38
+ stderr = exc.stderr or ""
39
+ if isinstance(stdout, bytes):
40
+ stdout = stdout.decode(errors="replace")
41
+ if isinstance(stderr, bytes):
42
+ stderr = stderr.decode(errors="replace")
43
+ stderr += f"Command timed out after {timeout_seconds:g} seconds\n"
44
+ return ToolRunResult(rendered, 124, stdout, stderr)
45
+ except FileNotFoundError:
46
+ return ToolRunResult(rendered, 127, "", f"Command not found: {rendered[0]}\n")
47
+ except OSError as exc:
48
+ return ToolRunResult(rendered, 126, "", f"Failed to run command: {exc}\n")
49
+
50
+ return ToolRunResult(rendered, completed.returncode, completed.stdout, completed.stderr)
51
+
52
+
53
+ def _normalize_command(raw_command: Any) -> list[str]:
54
+ if isinstance(raw_command, str):
55
+ return shlex.split(raw_command)
56
+ if isinstance(raw_command, list) and all(isinstance(item, str) for item in raw_command):
57
+ return raw_command
58
+ return []
59
+
60
+
61
+ def _render_arg(arg: str, variables: Mapping[str, Any]) -> str:
62
+ rendered = arg
63
+ for key, value in variables.items():
64
+ rendered = rendered.replace("{" + key + "}", str(value))
65
+ return rendered
66
+
67
+
68
+ def _timeout_seconds(value: Any) -> float | None:
69
+ if value in (None, ""):
70
+ return None
71
+ try:
72
+ timeout = float(value)
73
+ except (TypeError, ValueError):
74
+ return None
75
+ return timeout if timeout > 0 else None
cli_router/tools.py ADDED
@@ -0,0 +1,39 @@
1
+ """Tool inspection commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ from .artifacts import create_run_dir, write_run_manifest, write_stage_artifacts
9
+ from .config import RouterConfig
10
+ from .runner import ToolRunResult, run_tool
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ToolTestSummary:
15
+ run_dir: Path
16
+ result: ToolRunResult
17
+
18
+
19
+ def list_tools(config: RouterConfig) -> list[str]:
20
+ return sorted(config.tools)
21
+
22
+
23
+ def test_tool(config: RouterConfig, name: str, prompt: str = "CLI-Router tool test") -> ToolTestSummary:
24
+ if name not in config.tools:
25
+ raise KeyError(f"Unknown tool: {name}")
26
+ run_dir = create_run_dir(config.defaults.get("run_dir", ".cli-router/runs"))
27
+ result = run_tool(config.tools[name], {"prompt": prompt, "user_prompt": prompt, "plan_path": "PLAN.md"})
28
+ write_stage_artifacts(run_dir, name, result)
29
+ write_run_manifest(
30
+ run_dir,
31
+ {
32
+ "command": "tools test",
33
+ "tool": name,
34
+ "prompt": prompt,
35
+ "exit_code": result.returncode,
36
+ "result": result,
37
+ },
38
+ )
39
+ return ToolTestSummary(run_dir, result)
@@ -0,0 +1,176 @@
1
+ """Workflow execution for planner and coder stages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from .artifacts import create_run_dir, write_run_manifest, write_stage_artifacts
10
+ from .config import RouterConfig
11
+ from .extractors import ExtractionError, extract_output
12
+ from .failures import classify_failure, stage_failure_message
13
+ from .runner import ToolRunResult, run_tool
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class StageSummary:
18
+ stage_id: str
19
+ tool: str
20
+ result: ToolRunResult
21
+ extracted: str | None = None
22
+ failure_kind: str | None = None
23
+
24
+
25
+ @dataclass
26
+ class WorkflowSummary:
27
+ run_dir: Path
28
+ plan_path: Path
29
+ exit_code: int = 0
30
+ stages: list[StageSummary] = field(default_factory=list)
31
+ error: str | None = None
32
+
33
+
34
+ def plan_workflow(config: RouterConfig, user_prompt: str, workflow_name: str = "default") -> WorkflowSummary:
35
+ workflow = _workflow(config, workflow_name)
36
+ run_dir = create_run_dir(_default(config, "run_dir", ".cli-router/runs"))
37
+ plan_path = Path(_default(config, "plan_file", "PLAN.md"))
38
+ summary = WorkflowSummary(run_dir=run_dir, plan_path=plan_path)
39
+ planner_stage = _stage(workflow, "planner", index=0)
40
+ _run_stage(config, summary, planner_stage, user_prompt, write_plan=True)
41
+ _finalize(summary, user_prompt, workflow_name)
42
+ return summary
43
+
44
+
45
+ def implement_workflow(config: RouterConfig, workflow_name: str = "default") -> WorkflowSummary:
46
+ workflow = _workflow(config, workflow_name)
47
+ run_dir = create_run_dir(_default(config, "run_dir", ".cli-router/runs"))
48
+ plan_path = Path(_default(config, "plan_file", "PLAN.md"))
49
+ summary = WorkflowSummary(run_dir=run_dir, plan_path=plan_path)
50
+
51
+ if not plan_path.exists():
52
+ summary.exit_code = 2
53
+ summary.error = f"Plan file does not exist: {plan_path}"
54
+ _finalize(summary, "", workflow_name)
55
+ return summary
56
+
57
+ coder_stage = _stage(workflow, "coder", index=1)
58
+ _run_stage(config, summary, coder_stage, "", write_plan=False)
59
+ _finalize(summary, "", workflow_name)
60
+ return summary
61
+
62
+
63
+ def run_workflow(config: RouterConfig, user_prompt: str, workflow_name: str = "default") -> WorkflowSummary:
64
+ workflow = _workflow(config, workflow_name)
65
+ run_dir = create_run_dir(_default(config, "run_dir", ".cli-router/runs"))
66
+ plan_path = Path(_default(config, "plan_file", "PLAN.md"))
67
+ summary = WorkflowSummary(run_dir=run_dir, plan_path=plan_path)
68
+ stop_on_failure = bool(_default(config, "stop_on_failure", True))
69
+
70
+ planner_stage = _stage(workflow, "planner", index=0)
71
+ _run_stage(config, summary, planner_stage, user_prompt, write_plan=True)
72
+ if summary.exit_code and stop_on_failure:
73
+ _finalize(summary, user_prompt, workflow_name)
74
+ return summary
75
+
76
+ coder_stage = _stage(workflow, "coder", index=1)
77
+ _run_stage(config, summary, coder_stage, user_prompt, write_plan=False)
78
+ _finalize(summary, user_prompt, workflow_name)
79
+ return summary
80
+
81
+
82
+ def _run_stage(
83
+ config: RouterConfig,
84
+ summary: WorkflowSummary,
85
+ stage: dict[str, Any],
86
+ user_prompt: str,
87
+ *,
88
+ write_plan: bool,
89
+ ) -> None:
90
+ stage_id = str(stage["id"])
91
+ rendered_input = _render_template(
92
+ str(stage.get("input_template", "{user_prompt}")),
93
+ user_prompt=user_prompt,
94
+ plan_path=str(summary.plan_path),
95
+ )
96
+ tool_names = [str(stage["tool"]), *[str(tool_name) for tool_name in stage.get("fallback_tools", [])]]
97
+
98
+ for attempt_index, tool_name in enumerate(tool_names):
99
+ tool = config.tools[tool_name]
100
+ result = run_tool(
101
+ tool,
102
+ {
103
+ "prompt": rendered_input,
104
+ "user_prompt": user_prompt,
105
+ "plan_path": str(summary.plan_path),
106
+ },
107
+ )
108
+
109
+ extracted: str | None = None
110
+ failure_kind = classify_failure(result)
111
+ if result.returncode == 0:
112
+ try:
113
+ extracted = extract_output(result.stdout, tool.get("output"))
114
+ summary.exit_code = 0
115
+ summary.error = None
116
+ except ExtractionError as exc:
117
+ summary.exit_code = 3
118
+ summary.error = str(exc)
119
+ failure_kind = "extraction_failed"
120
+ else:
121
+ summary.exit_code = result.returncode
122
+ summary.error = stage_failure_message(stage_id, result)
123
+
124
+ artifact_prefix = stage_id if attempt_index == 0 else f"{stage_id}.{tool_name}"
125
+ write_stage_artifacts(summary.run_dir, artifact_prefix, result, extracted)
126
+ summary.stages.append(StageSummary(stage_id, tool_name, result, extracted, failure_kind))
127
+
128
+ if summary.exit_code == 0:
129
+ if write_plan and extracted is not None:
130
+ output_file = Path(stage.get("output_file") or summary.plan_path)
131
+ summary.plan_path = output_file
132
+ output_file.write_text(extracted, encoding="utf-8")
133
+ return
134
+
135
+
136
+ def _workflow(config: RouterConfig, name: str) -> dict[str, Any]:
137
+ try:
138
+ return config.workflows[name]
139
+ except KeyError as exc:
140
+ raise KeyError(f"Unknown workflow: {name}") from exc
141
+
142
+
143
+ def _stage(workflow: dict[str, Any], stage_id: str, *, index: int) -> dict[str, Any]:
144
+ stages = workflow.get("stages", [])
145
+ for stage in stages:
146
+ if stage.get("id") == stage_id:
147
+ return stage
148
+ try:
149
+ return stages[index]
150
+ except IndexError as exc:
151
+ raise KeyError(f"Workflow is missing {stage_id} stage") from exc
152
+
153
+
154
+ def _default(config: RouterConfig, key: str, fallback: Any) -> Any:
155
+ return config.defaults.get(key, fallback)
156
+
157
+
158
+ def _render_template(template: str, **variables: str) -> str:
159
+ rendered = template
160
+ for key, value in variables.items():
161
+ rendered = rendered.replace("{" + key + "}", value)
162
+ return rendered
163
+
164
+
165
+ def _finalize(summary: WorkflowSummary, user_prompt: str, workflow_name: str) -> None:
166
+ write_run_manifest(
167
+ summary.run_dir,
168
+ {
169
+ "workflow": workflow_name,
170
+ "user_prompt": user_prompt,
171
+ "plan_path": summary.plan_path,
172
+ "exit_code": summary.exit_code,
173
+ "error": summary.error,
174
+ "stages": summary.stages,
175
+ },
176
+ )
@@ -0,0 +1,172 @@
1
+ Metadata-Version: 2.4
2
+ Name: cli-router
3
+ Version: 0.1.0
4
+ Summary: A simple Python CLI router for AI planning and coding agents.
5
+ Project-URL: Homepage, https://github.com/coolrazor007/cli-router
6
+ Project-URL: Repository, https://github.com/coolrazor007/cli-router
7
+ Project-URL: Issues, https://github.com/coolrazor007/cli-router/issues
8
+ Author-email: Razor <tim@ephillips.net>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: agents,ai,claude,cli,codex,coding-agent,llm,router
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development
22
+ Classifier: Topic :: Utilities
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: pyyaml>=6.0
25
+ Requires-Dist: rich>=13.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # CLI-Router
29
+
30
+ CLI-Router is a Python command-line orchestrator for AI coding tools. It routes planning and coding stages across external CLIs such as Claude Code, Codex, Hermes, and local model tools.
31
+
32
+ The router is intentionally programmatic and non-intelligent: it loads configured commands, renders prompt templates, captures stdout/stderr, extracts planner output, writes `PLAN.md`, and records run artifacts.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install cli-router
38
+ ```
39
+
40
+ For CLI usage, `pipx` is recommended:
41
+
42
+ ```bash
43
+ pipx install cli-router
44
+ ```
45
+
46
+ From a local checkout:
47
+
48
+ ```bash
49
+ python -m pip install -e .
50
+ ```
51
+
52
+ ## Commands
53
+
54
+ ```bash
55
+ cli-router --help
56
+ cli-router plan "Add a health check endpoint"
57
+ cli-router run "Add a health check endpoint"
58
+ cli-router implement
59
+ cli-router check
60
+ cli-router config show
61
+ cli-router tools list
62
+ cli-router tools test claude-planner
63
+ ```
64
+
65
+ `plan` runs the planner stage and writes `PLAN.md`. `run` runs planner then coder. `implement` runs the coder stage using the existing plan file.
66
+
67
+ ## Configuration
68
+
69
+ CLI-Router looks for config in this order:
70
+
71
+ 1. `./cli-router.yaml`
72
+ 2. `./.cli-router.yaml`
73
+ 3. `~/.config/cli-router/config.yaml`
74
+ 4. Built-in defaults
75
+
76
+ Minimal example:
77
+
78
+ ```yaml
79
+ version: 1
80
+
81
+ defaults:
82
+ plan_file: PLAN.md
83
+ run_dir: .cli-router/runs
84
+ stop_on_failure: true
85
+
86
+ tools:
87
+ claude-planner:
88
+ type: claude
89
+ timeout_seconds: 60
90
+ command:
91
+ - claude
92
+ - -p
93
+ - --permission-mode
94
+ - plan
95
+ - --output-format
96
+ - json
97
+ - "{prompt}"
98
+ output:
99
+ format: json
100
+ extract: result
101
+
102
+ codex-coder:
103
+ type: codex
104
+ timeout_seconds: 120
105
+ command:
106
+ - codex
107
+ - --ask-for-approval
108
+ - never
109
+ - exec
110
+ - "{prompt}"
111
+ output:
112
+ format: text
113
+
114
+ workflows:
115
+ default:
116
+ stages:
117
+ - id: planner
118
+ tool: claude-planner
119
+ fallback_tools:
120
+ - codex-planner
121
+ input_template: |
122
+ You are the planning model for a coding-agent handoff.
123
+
124
+ User request:
125
+ {user_prompt}
126
+
127
+ Inspect this repository and produce a concrete implementation plan.
128
+ Do not edit files.
129
+ Write the plan in Markdown.
130
+ output_file: PLAN.md
131
+
132
+ - id: coder
133
+ tool: codex-coder
134
+ input_template: |
135
+ Please implement the plan in {plan_path}.
136
+
137
+ Original user request:
138
+ {user_prompt}
139
+ ```
140
+
141
+ Command args and templates support `{prompt}`, `{user_prompt}`, and `{plan_path}` placeholders.
142
+
143
+ When a stage command fails, CLI-Router records stdout/stderr and classifies common failures. Usage-limit messages such as provider quota, rate-limit, or 429 errors are reported as usage-limit failures. Commands can set `timeout_seconds`; timed-out commands are recorded with exit code `124`. A stage can define `fallback_tools` to try alternate configured tools in order after a failed primary tool.
144
+
145
+ ## Artifacts
146
+
147
+ Each run writes artifacts under `.cli-router/runs/`:
148
+
149
+ ```text
150
+ .cli-router/runs/2026-07-07T14-22-10/
151
+ run.yaml
152
+ planner.stdout
153
+ planner.stderr
154
+ planner.extracted.md
155
+ coder.stdout
156
+ coder.stderr
157
+ ```
158
+
159
+ ## Development
160
+
161
+ ```bash
162
+ python -m pip install -e .
163
+ python -m pytest
164
+ ```
165
+
166
+ Build and check a release locally:
167
+
168
+ ```bash
169
+ python -m pip install --upgrade build twine
170
+ python -m build
171
+ python -m twine check dist/*
172
+ ```
@@ -0,0 +1,19 @@
1
+ cli_router/__init__.py,sha256=3QhNrthPh0_O3zrSBg5g1iMXftPfexCrkC_X88f2sdw,49
2
+ cli_router/artifacts.py,sha256=4mR-eTUEIyUDauKWfU9C1GoOSJIJ8R7XMSgjfSpVkR4,1593
3
+ cli_router/cli.py,sha256=izjv8ODGtZ44rJHirdyPV9wmTB-YvC5hK4W8SnQ_XT8,3784
4
+ cli_router/config.py,sha256=PTGbRXf7HSiY5ndAFJVucnhhJYqgvGk5emeaXXkgCz8,4813
5
+ cli_router/extractors.py,sha256=YF8sSixJTpUgXUivugmwPKyDg4NejeASmfiUxIM5iVw,1181
6
+ cli_router/failures.py,sha256=YUZ4QTbByYSm7J8cdYt0Ze8QmXzTtxvZS_ccSi-lIIo,1699
7
+ cli_router/runner.py,sha256=afcgdBTpHHlZZXVFGYCoZMEN1uLjSpp1NgHMCEcIelQ,2377
8
+ cli_router/tools.py,sha256=2iw4_37QpMpARq0WiOFQexp2WDWX7Rvg1EEUgTIDDZQ,1171
9
+ cli_router/workflows.py,sha256=pV6sxQLy0WfmhEIWv5JCIel0QFoDaEdkqHJKkInipw0,6290
10
+ cli_router/presets/__init__.py,sha256=goPX_HPi3rfQZwMfuNU4yPaDX04YPdGKYr02oKfFZvs,35
11
+ cli_router/presets/claude.yaml,sha256=u_V2tnPgIgiVjBx31XTOmMRBNZWBTbd-ukL92nLi36g,229
12
+ cli_router/presets/codex.yaml,sha256=iGhLAibj00TANUfDdWxLTiXq8u8FjOlrkQuZYVa0Qc8,128
13
+ cli_router/presets/generic.yaml,sha256=fDtyzntCnkAvBKaadK2ahtoPALhj08fDAzmkMu9sXDE,1214
14
+ cli_router/presets/hermes.yaml,sha256=96WynLV4YuTxjQLik3WtdJbK3w0_gG587VHgLWYfzP0,130
15
+ cli_router-0.1.0.dist-info/METADATA,sha256=sg5-ZR9p_N922iqmuRWio-jjWpy4TXt0IFbAohEVFy8,4410
16
+ cli_router-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
17
+ cli_router-0.1.0.dist-info/entry_points.txt,sha256=bb7Zjk0RRFNI0dcAz-nZIhNwPe73i7Dx7rDS8OTs-e8,51
18
+ cli_router-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
19
+ cli_router-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ cli-router = cli_router.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.