diff --git a/codd/ai_invoke.py b/codd/ai_invoke.py index 50f7532..a43f221 100644 --- a/codd/ai_invoke.py +++ b/codd/ai_invoke.py @@ -421,7 +421,7 @@ def invoke_file_writing_agent( _record_retry_stderr(result.stderr) detail = (result.stderr.strip() or result.stdout.strip() or f"exit code {result.returncode}") - raise ValueError(f"AI command failed: {detail}") + raise ValueError(f"AI command failed: {_with_usage_headline(detail)}") # Keep UTF-8 names literal in both listings and make diff paths relative to cwd. # Set the options in the subprocess environments to preserve the Git argv. @@ -599,7 +599,7 @@ def _invoke_subprocess( stderr = result.stderr.strip() exit_code = f"exit code {result.returncode}" detail = stderr or result.stdout.strip() or exit_code - error = ValueError(f"AI command failed: {detail}") + error = ValueError(f"AI command failed: {_with_usage_headline(detail)}") # Keep the existing exception contract and provide feedback without stdout. error.__dict__["retry_diagnostic"] = stderr or exit_code raise error @@ -614,6 +614,8 @@ def _invoke_subprocess( def _is_transient_failure(exc: ValueError) -> bool: """Transient = nonzero exit or empty output. Missing binary is permanent.""" message = str(exc) + if message.startswith("AI command failed") and _usage_exhausted_line(message): + return False # an exhausted usage limit does not clear on retry return message.startswith("AI command failed") or message == "AI command returned empty output" @@ -712,6 +714,46 @@ def _transport_error_text(detail: str, stderr: str | None, prompt: str) -> str: return "".join(parts).strip() or detail +#: A CLI's own error line ("ERROR: ...", "error: ...", "fatal: ..."), also when +#: it follows the "AI command failed: " prefix on the message's first line. +_ERROR_LINE = re.compile(r"^\s*(?:AI command failed:\s*)?(?:error|fatal)\s*[:!]", re.IGNORECASE) + +# An exhausted usage limit or credit balance: permanent for the rest of the +# run (the CLI usually says when it resets). Deliberately narrow: per-minute +# quotas and rate limits ("429", "quota exceeded for ... per minute") stay +# transient and keep their retry. +_USAGE_EXHAUSTED = re.compile( + r"\busage limit\b|\bpurchase more credits\b|\bout of credits\b|\binsufficient credits?\b", + re.IGNORECASE, +) + + +def _usage_exhausted_line(text: str) -> str | None: + """The CLI's last own error line, when it says the usage limit or credits + are exhausted. Only the last error line counts: earlier "ERROR:" lines can + be log output the agent printed while working.""" + last = None + for line in (text or "").splitlines(): + if _ERROR_LINE.match(line): + last = line + if last is None or not _USAGE_EXHAUSTED.search(last): + return None + return re.sub(r"^\s*AI command failed:\s*", "", last).strip() + + +def _with_usage_headline(detail: str) -> str: + """Put an exhausted-usage error line first, so the one-line summary of the + failure names it instead of a leading warning. Any other failure keeps its + detail unchanged.""" + line = _usage_exhausted_line(detail) + if line is None: + return detail + first = detail.strip().splitlines()[0].strip() if detail.strip() else "" + if first == line: + return detail + return f"{line}\n{detail}" + + def _is_transient_error(stderr: str) -> bool: """True when *stderr* clearly describes a transient/recoverable transport failure (socket/connection drop, timeout, 429/5xx gateway, overload). @@ -812,9 +854,14 @@ def _invoke_with_recovery( os.environ[OUTPUT_TOKENS_ENV] = prior else: return attempt(prompt, raised_env) - # Transient transport: bounded auto-retry with backoff. - if transient_attempts < TRANSIENT_AUTO_RETRIES and _is_transient_error( - _transport_error_text(detail, _retry_stderr.get(), prompt) + # Transient transport: bounded auto-retry with backoff. An exhausted + # usage limit or quota is never transient, whatever else the + # transcript mentions: re-issuing the call cannot succeed. + transport_text = _transport_error_text(detail, _retry_stderr.get(), prompt) + if ( + transient_attempts < TRANSIENT_AUTO_RETRIES + and not _usage_exhausted_line(detail) + and _is_transient_error(transport_text) ): transient_attempts += 1 print( diff --git a/tests/test_ai_failure_headline.py b/tests/test_ai_failure_headline.py new file mode 100644 index 0000000..7c5c466 --- /dev/null +++ b/tests/test_ai_failure_headline.py @@ -0,0 +1,101 @@ +"""An AI command failure names the CLI's own error line first, and an exhausted +usage limit is not retried as a transient transport error. + +Live symptom: an agent CLI printed a benign configuration warning on its first +stderr line and "ERROR: You've hit your usage limit ... try again at