ralph-any 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.
ralph/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """Ralph Any — iterative AI dev loop via ACP."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from ralph.detect import detect_promise
6
+ from ralph.engine import LoopConfig, LoopResult, RalphEngine
7
+
8
+ __all__ = [
9
+ "__version__",
10
+ "detect_promise",
11
+ "LoopConfig",
12
+ "LoopResult",
13
+ "RalphEngine",
14
+ ]
ralph/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m ralph``."""
2
+
3
+ from ralph.cli import main
4
+
5
+ main()
ralph/cli.py ADDED
@@ -0,0 +1,122 @@
1
+ """CLI interface for Ralph Any."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from ralph.engine import LoopConfig, RalphEngine
11
+
12
+ EXIT_SUCCESS = 0
13
+ EXIT_FAILED = 1
14
+ EXIT_CANCELLED = 2
15
+ EXIT_TIMEOUT = 3
16
+ EXIT_MAX_ITERATIONS = 4
17
+
18
+ _STATE_TO_EXIT = {
19
+ "complete": EXIT_SUCCESS,
20
+ "failed": EXIT_FAILED,
21
+ "cancelled": EXIT_CANCELLED,
22
+ "timeout": EXIT_TIMEOUT,
23
+ "max_iterations": EXIT_MAX_ITERATIONS,
24
+ }
25
+
26
+
27
+ def _build_parser() -> argparse.ArgumentParser:
28
+ p = argparse.ArgumentParser(
29
+ prog="ralph",
30
+ description="Ralph Wiggum Loop — iterative AI dev loop via ACP",
31
+ )
32
+ p.add_argument(
33
+ "prompt",
34
+ help="Task description, or path to a .md/.txt file",
35
+ )
36
+ p.add_argument(
37
+ "-m", "--max-iterations",
38
+ type=int,
39
+ default=10,
40
+ help="Maximum loop iterations (default: 10)",
41
+ )
42
+ p.add_argument(
43
+ "-t", "--timeout",
44
+ type=int,
45
+ default=1800,
46
+ help="Maximum runtime in seconds (default: 1800 = 30m)",
47
+ )
48
+ p.add_argument(
49
+ "--promise",
50
+ default="任務完成!🥇",
51
+ help="Completion promise phrase (default: 任務完成!🥇)",
52
+ )
53
+ p.add_argument(
54
+ "-c", "--command",
55
+ default="claude-code-acp",
56
+ help="ACP CLI command (default: claude-code-acp)",
57
+ )
58
+ p.add_argument(
59
+ "--command-args",
60
+ nargs="*",
61
+ default=[],
62
+ help="Extra arguments for the ACP CLI",
63
+ )
64
+ p.add_argument(
65
+ "-d", "--working-dir",
66
+ default=".",
67
+ help="Working directory (default: .)",
68
+ )
69
+ p.add_argument(
70
+ "--dry-run",
71
+ action="store_true",
72
+ help="Show config without running",
73
+ )
74
+ return p
75
+
76
+
77
+ def _resolve_prompt(raw: str) -> str:
78
+ """If ``raw`` is a path to an existing .md or .txt file, read it."""
79
+ p = Path(raw)
80
+ if p.is_file() and p.suffix in (".md", ".txt"):
81
+ return p.read_text(encoding="utf-8")
82
+ return raw
83
+
84
+
85
+ def _run(config: LoopConfig) -> int:
86
+ engine = RalphEngine(config)
87
+ try:
88
+ result = asyncio.run(engine.run())
89
+ except KeyboardInterrupt:
90
+ print("\n⚠ Loop cancelled", flush=True)
91
+ return EXIT_CANCELLED
92
+
93
+ duration = f"{result.duration_seconds:.1f}s"
94
+ print(f"\n▶ Result: {result.state} ({result.iterations} iterations, {duration})")
95
+
96
+ return _STATE_TO_EXIT.get(result.state, EXIT_FAILED)
97
+
98
+
99
+ def main(argv: list[str] | None = None) -> None:
100
+ parser = _build_parser()
101
+ args = parser.parse_args(argv)
102
+
103
+ prompt_text = _resolve_prompt(args.prompt)
104
+
105
+ config = LoopConfig(
106
+ prompt=prompt_text,
107
+ promise_phrase=args.promise,
108
+ command=args.command,
109
+ command_args=args.command_args,
110
+ working_dir=args.working_dir,
111
+ max_iterations=args.max_iterations,
112
+ timeout_seconds=args.timeout,
113
+ dry_run=args.dry_run,
114
+ )
115
+
116
+ if config.dry_run:
117
+ print("Dry-run config:")
118
+ for k, v in vars(config).items():
119
+ print(f" {k}: {v}")
120
+ sys.exit(EXIT_SUCCESS)
121
+
122
+ sys.exit(_run(config))
ralph/detect.py ADDED
@@ -0,0 +1,7 @@
1
+ """Promise completion detection."""
2
+
3
+
4
+ def detect_promise(text: str, phrase: str) -> bool:
5
+ if not phrase:
6
+ return False
7
+ return f"<promise>{phrase}</promise>" in text
ralph/engine.py ADDED
@@ -0,0 +1,134 @@
1
+ """Ralph Loop engine — the core iteration loop over any ACP-compatible agent."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import sys
7
+ import time
8
+ from dataclasses import dataclass, field
9
+ from typing import Literal
10
+
11
+ from claude_code_acp import AcpClient
12
+
13
+ from ralph.detect import detect_promise
14
+ from ralph.prompt import build_system_prompt
15
+
16
+ LoopState = Literal["complete", "failed", "cancelled", "timeout", "max_iterations"]
17
+
18
+
19
+ @dataclass
20
+ class LoopConfig:
21
+ prompt: str
22
+ promise_phrase: str = "任務完成!🥇"
23
+ command: str = "claude-code-acp"
24
+ command_args: list[str] = field(default_factory=list)
25
+ working_dir: str = "."
26
+ max_iterations: int = 10
27
+ timeout_seconds: int = 1800 # 30 minutes
28
+ dry_run: bool = False
29
+
30
+
31
+ @dataclass
32
+ class LoopResult:
33
+ state: LoopState
34
+ iterations: int
35
+ duration_seconds: float
36
+ error: str | None = None
37
+
38
+
39
+ class RalphEngine:
40
+ def __init__(self, config: LoopConfig) -> None:
41
+ self.config = config
42
+ self.client = AcpClient(
43
+ command=config.command,
44
+ args=config.command_args or None,
45
+ cwd=config.working_dir,
46
+ )
47
+ self._register_events()
48
+
49
+ def _register_events(self) -> None:
50
+ client = self.client
51
+
52
+ @client.on_text
53
+ async def on_text(text: str) -> None:
54
+ sys.stdout.write(text)
55
+ sys.stdout.flush()
56
+
57
+ @client.on_tool_start
58
+ async def on_tool_start(tool_id: str, name: str, input: dict) -> None:
59
+ print(f"\n🛠️ {name}", flush=True)
60
+
61
+ @client.on_tool_end
62
+ async def on_tool_end(tool_id: str, status: str, output: object) -> None:
63
+ icon = "✔️" if status == "completed" else "❌"
64
+ print(f" {icon} {status}", flush=True)
65
+
66
+ @client.on_permission
67
+ async def on_permission(name: str, input: dict, options: list) -> str:
68
+ # Auto-allow all tool executions in the loop.
69
+ # Pick the first "allow" style option from what the agent offers.
70
+ for opt in options:
71
+ opt_id = opt if isinstance(opt, str) else opt.get("id", "")
72
+ if opt_id in ("allow", "allow_always", "proceed_once"):
73
+ return opt_id
74
+ # Fallback: return the first option's id
75
+ if options:
76
+ return options[0] if isinstance(options[0], str) else options[0].get("id", "allow")
77
+ return "allow"
78
+
79
+ @client.on_error
80
+ async def on_error(exception: Exception) -> None:
81
+ print(f"\n⚠️ Error: {exception}", file=sys.stderr, flush=True)
82
+
83
+ async def run(self) -> LoopResult:
84
+ config = self.config
85
+ system_prompt = build_system_prompt(config.promise_phrase)
86
+ start = time.monotonic()
87
+
88
+ async with self.client:
89
+ for i in range(1, config.max_iterations + 1):
90
+ elapsed = time.monotonic() - start
91
+ if elapsed >= config.timeout_seconds:
92
+ return LoopResult(
93
+ state="timeout",
94
+ iterations=i - 1,
95
+ duration_seconds=elapsed,
96
+ )
97
+
98
+ print(f"\n━━━ Iteration {i}/{config.max_iterations} ━━━", flush=True)
99
+
100
+ prompt = (
101
+ f"{system_prompt}\n\n---\n\n"
102
+ f"[Iteration {i}/{config.max_iterations}]\n\n{config.prompt}"
103
+ )
104
+
105
+ try:
106
+ response = await asyncio.wait_for(
107
+ self.client.prompt(prompt),
108
+ timeout=max(0, config.timeout_seconds - elapsed),
109
+ )
110
+ except asyncio.TimeoutError:
111
+ return LoopResult(
112
+ state="timeout",
113
+ iterations=i,
114
+ duration_seconds=time.monotonic() - start,
115
+ )
116
+
117
+ if detect_promise(response, config.promise_phrase):
118
+ print(
119
+ f"\n🎉 Promise detected: \"{config.promise_phrase}\"",
120
+ flush=True,
121
+ )
122
+ return LoopResult(
123
+ state="complete",
124
+ iterations=i,
125
+ duration_seconds=time.monotonic() - start,
126
+ )
127
+
128
+ print(f"\n✓ Iteration {i} complete", flush=True)
129
+
130
+ return LoopResult(
131
+ state="max_iterations",
132
+ iterations=config.max_iterations,
133
+ duration_seconds=time.monotonic() - start,
134
+ )
ralph/prompt.py ADDED
@@ -0,0 +1,46 @@
1
+ """System prompt template for the Ralph Wiggum Loop."""
2
+
3
+ _TEMPLATE = """\
4
+ # Ralph Loop System Instructions
5
+
6
+ You are operating inside the **Ralph Wiggum Loop**:
7
+ - The user prompt will be fed back to you *unchanged* after each response.
8
+ - You will see the repo state and any files you modified from previous iterations.
9
+ - Your job is to keep iterating until the task is fully complete, then exit with the \
10
+ completion phrase (see below).
11
+
12
+ ## Working Rules
13
+
14
+ 1. **Continue from the current repo state** each iteration. Do not repeat the same \
15
+ actions if they already happened.
16
+ 2. **Always make progress**: change files, run checks, or ask for specific missing \
17
+ info. If blocked, say exactly what is missing and what you need.
18
+ 3. **Be concrete**: report what you changed, what you verified, and what remains.
19
+ 4. **No hallucinations**: never claim edits or test results that did not happen.
20
+ 5. **Infinite Sessions + plan.md**: if you create `plan.md`, immediately begin \
21
+ implementation in the same response or the next iteration. Do **not** ask the \
22
+ user a follow-up question after writing `plan.md` unless a critical blocker \
23
+ makes implementation impossible.
24
+
25
+ ## Completion Signal
26
+
27
+ Only when the task is completely finished:
28
+ 1. Write a **short summary of all changes** (include files touched).
29
+ 2. As the **very last text** in your response, output this *exact* phrase:
30
+ "<promise>{{PROMISE}}</promise>"
31
+
32
+ Requirements for the completion phrase:
33
+ - It must be the final characters of the response (no trailing whitespace or text).
34
+ - Do not wrap it in a code block or quotes.
35
+ - Do not output it unless the task is **fully and verifiably** done.
36
+
37
+ ## Critical Rule
38
+
39
+ Never output the completion phrase to escape the loop. If you are stuck, blocked, \
40
+ or waiting on the user, explain the blocker and keep the loop going.\
41
+ """
42
+
43
+
44
+ def build_system_prompt(promise_phrase: str, template: str | None = None) -> str:
45
+ source = template if template is not None else _TEMPLATE
46
+ return source.replace("{{PROMISE}}", promise_phrase)
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.4
2
+ Name: ralph-any
3
+ Version: 0.1.0
4
+ Summary: Ralph Wiggum Loop — iterative AI dev loop via ACP (supports Claude, Gemini, and more)
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Programming Language :: Python :: 3
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: claude-code-acp
@@ -0,0 +1,11 @@
1
+ ralph/__init__.py,sha256=EzqzYypFDRxCeFKPx7ms7ocgrwDJ4jJ7Hf3VYXiww4A,287
2
+ ralph/__main__.py,sha256=FdEO4lE2dw6-b4Kk97vznatvCAEuO-6qFwOkWP6en-c,69
3
+ ralph/cli.py,sha256=Gd5GNdS3ErRQvspHrEFJ-Z6Hv8xGHtAKCCJC8vqVe10,3115
4
+ ralph/detect.py,sha256=e99V2o9KECN2fR6sZ7qLghVpdomShCW1Jf_rHjo0og0,180
5
+ ralph/engine.py,sha256=CZFU7GtmKnPIXuN9mx-5iSxcUCyCgUNZkilj1POuTyM,4600
6
+ ralph/prompt.py,sha256=9B5z6zeEyX0Jr6tJ6P7_ahMUVckQySWST51DypGdIDQ,2022
7
+ ralph_any-0.1.0.dist-info/METADATA,sha256=Wsf3QptDpsOKf81ZdYhuuOPT-3pzm0NSR8NfGD1kjZc,350
8
+ ralph_any-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
9
+ ralph_any-0.1.0.dist-info/entry_points.txt,sha256=39mDVcb7RNWfrI1JwWs7ae3TrLLzwzy6R6EurlGgTfI,41
10
+ ralph_any-0.1.0.dist-info/licenses/LICENSE,sha256=Losvcv3YtvA9lWEq2Ngj6bbejg6sBzR5vxZKb-Db5i0,1079
11
+ ralph_any-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ralph = ralph.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ralph Any Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.