58 lines
2.6 KiB
Python
58 lines
2.6 KiB
Python
from loop_claude.cycle.judge_reply import ANSWERS_RECORDED, QuotedAnswer
|
|
from loop_claude.claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until
|
|
from loop_claude.effects import Effects
|
|
from failure import Failure
|
|
from loop_claude.cycle.retry import Limited
|
|
from loop_claude.claude_code.transcript import part_line
|
|
from loop_claude.project.records import QUOTE_SOURCES
|
|
from loop_claude.claude_code.session import Session
|
|
|
|
PRINTED_TOOL_INPUT = 160
|
|
|
|
|
|
def run_worker(root: str, args: list[str], effects: Effects) -> Failure | Limited | None:
|
|
try:
|
|
proc = effects.stream_claude(args, root)
|
|
except OSError as failure:
|
|
return Failure(f"could not start claude: {failure.strerror}")
|
|
result: dict | None = None
|
|
resets: list[int] = []
|
|
for raw in proc.lines():
|
|
event = parse_entry(raw) or {}
|
|
if ends_stream(event):
|
|
result = event
|
|
if (resets_at := rejected_until(event)) is not None:
|
|
resets.append(resets_at)
|
|
for part in assistant_parts(event):
|
|
if line := part_line(part, PRINTED_TOOL_INPUT):
|
|
print(line, flush=True)
|
|
return worker_outcome(proc.wait(), result, resets)
|
|
|
|
|
|
def worker_outcome(code: int, result: dict | None, resets: list[int]) -> Failure | Limited | None:
|
|
if result is not None and hit_limit(result):
|
|
return Limited(max(resets, default=None), limit_said(result))
|
|
if code < 0:
|
|
return Failure(f"claude killed by signal {-code}")
|
|
if code:
|
|
return Failure(f"claude exited {code}")
|
|
return None if result is not None else Failure("claude exited 0 without a result event")
|
|
|
|
|
|
def worker_args(task: str, session: Session, model: str, resuming: bool, answered: QuotedAnswer | None = None) -> list[str]:
|
|
if answered is not None:
|
|
start = ["-p", f"Your question: {answered.question}\n\n{QUOTE_SOURCES} answers it:\n\n{answered.answer}\n\nContinue the task.", "--resume", str(session.id)]
|
|
elif resuming:
|
|
start = ["-p", f"Continue the task; the previous run stopped before it was finished. The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}.", "--resume", str(session.id)]
|
|
else:
|
|
# --session-id creates the session under the id loop-claude keeps; --resume continues that session.
|
|
start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.", "--name", session.name, "--session-id", str(session.id)]
|
|
# -p fails without --verbose under stream-json.
|
|
return [
|
|
*start,
|
|
"--output-format", "stream-json",
|
|
"--permission-mode", "bypassPermissions",
|
|
"--verbose",
|
|
"--model", model,
|
|
]
|