terminal_hints.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. """Output-pattern failure hints for the terminal tool.
  2. Extends the exit-code semantics table in ``terminal_tool`` with a bounded scan of failed-command
  3. output mapped to ONE short, actionable recovery hint. Rules: only fires on non-zero exit; first
  4. match wins, patterns ordered by observed production frequency; scans only the first
  5. ``_SCAN_CHARS`` so hints key on error headers, not deep context; hints state the *next action*
  6. in 1-2 sentences; pure function, no I/O or config reads.
  7. """
  8. from __future__ import annotations
  9. import re
  10. from typing import Callable, Optional
  11. _SCAN_CHARS = 4000
  12. def _regex_hint(pattern: str, message: str | Callable[[str], str], flags: int = 0) -> Callable[[str, str], Optional[str]]:
  13. """Hint firing when ``pattern`` matches; ``{0}`` = first group, or ``message(group1)``."""
  14. rx = re.compile(pattern, flags)
  15. def hint(command: str, output: str) -> Optional[str]:
  16. m = rx.search(output)
  17. if m:
  18. return message(m.group(1)) if callable(message) else message.format(*m.groups())
  19. return None
  20. return hint
  21. # Most `command not found` hits are bare `python` on python3-only distros.
  22. _MISSING_COMMAND_HINTS = {
  23. "python": "This system has no bare `python` — use `python3`, or the project venv's "
  24. "interpreter (e.g. .venv/bin/python).",
  25. "pip": "This system has no bare `pip` — use `pip3`, `python3 -m pip`, or the project venv's "
  26. "pip (e.g. .venv/bin/pip).",
  27. }
  28. def _missing_command_hint(missing: str) -> str:
  29. return _MISSING_COMMAND_HINTS.get(missing) or (
  30. f"`{missing}` is not installed or not on PATH. Verify with `which {missing}`; install it "
  31. "or use an absolute path instead of retrying the same command.")
  32. # Ordered by production frequency — first match wins.
  33. _OUTPUT_HINTS: list[Callable[[str, str], Optional[str]]] = [
  34. # gh version drift; gh already prints the valid field list.
  35. _regex_hint(r'Unknown JSON field: "?(\w+)',
  36. "The installed gh does not support the JSON field '{0}'. The valid field list is "
  37. "printed in the output above — retry using only fields from that list."),
  38. _regex_hint(r"^CONFLICT |Automatic merge failed|needs merge",
  39. "Git merge conflict. Do not retry this command. Resolve the conflicted files "
  40. "listed above (edit, then `git add`), then continue (`git rebase --continue` / "
  41. "commit the merge) — or abort with `--abort`.", re.MULTILINE),
  42. _regex_hint(r"(?:bash: line \d+: |bash: |sh: \d*:? ?)?([\w.+-]+): command not found",
  43. _missing_command_hint),
  44. # Almost always a venv-activation slip, not a missing dependency.
  45. _regex_hint(r"(?:ModuleNotFoundError|ImportError): No module named '?([\w.]+)",
  46. "Python cannot import '{0}'. Most often the wrong interpreter is running: "
  47. "activate the project venv (e.g. `source .venv/bin/activate`) or invoke its python "
  48. "directly. Only pip install if the package is genuinely absent from that venv."),
  49. _regex_hint(r"(?:fatal|error):.*?'([^']+)' already exists",
  50. "'{0}' already exists — retrying unchanged will keep failing. Reuse it, choose "
  51. "another name, or delete it first if it is genuinely stale."),
  52. _regex_hint(r"API rate limit|was submitted too quickly",
  53. "GitHub API rate limit hit — immediate retries will keep failing. Continue with "
  54. "other work and retry this operation later."),
  55. _regex_hint(r"Permission denied|EACCES",
  56. "Permission denied. Check ownership/mode of the target path (`ls -la`); prefer a "
  57. "user-writable location. Only escalate to sudo if the task genuinely requires it."),
  58. ]
  59. # Exit-code-only hints for codes the terminal_tool semantics table does not
  60. # cover per-command. Checked after output patterns.
  61. _EXIT_CODE_HINTS: dict[int, str] = {
  62. 126: "Exit 126: the file was found but is not executable — `chmod +x` it or invoke it via its interpreter (e.g. `bash script.sh`).",
  63. 137: "Exit 137: the process was SIGKILLed — usually out-of-memory or an external kill. Reduce memory use or check `dmesg | tail` before retrying.",
  64. 124: "Exit 124: the command hit its timeout. Raise timeout= (foreground max 600s) or run it with background=true and notify_on_complete=true.",
  65. }
  66. # Masked-success detection: `cargo build 2>&1 | tail -20` exits with tail's 0
  67. # (no pipefail) and `cargo build || echo FAILED` with echo's 0, so the model can
  68. # conclude a build passed while the output says it failed. Conservative: BOTH a
  69. # masking command shape AND a strong tool-specific failure shape must hold, and
  70. # read-only heads (`grep ... | head`) are excluded because their output
  71. # legitimately contains error text. Advisory only — exit_code is never changed.
  72. # Consumers whose exit status says nothing about the upstream command.
  73. _PASSTHROUGH_CONSUMERS = r"(?:tail|head|cat|tee|less|more|wc|sort|uniq)"
  74. # Command shapes that swallow an upstream status -> warning, checked in order.
  75. _MASKING_SHAPES: list[tuple[re.Pattern[str], str]] = [
  76. # Top-level `... | tail -20` (not `||`); consumer must be the LAST segment.
  77. (re.compile(r"(?<!\|)\|(?!\|)\s*" + _PASSTHROUGH_CONSUMERS + r"\b[^|]*$"),
  78. "exit_code 0 here is the status of the last pipeline command (tail/head/cat/...), NOT of "
  79. "the command before the pipe — and the output contains failure indicators. Treat this run "
  80. "as FAILED until proven otherwise: re-run the command WITHOUT the pipe (output is "
  81. "auto-truncated and the full text is saved to a file, so piping through tail/head is never "
  82. "needed) to get the real exit code."),
  83. # `cmd || echo ...` / `cmd || true` — fallback swallows the failure status.
  84. (re.compile(r"\|\|\s*(?:echo\b|printf\b|true\b|:\s|:$)"),
  85. "exit_code 0 here is the status of the `||` fallback (echo/true), NOT of the command before "
  86. "it — and the output contains failure indicators. Treat this run as FAILED until proven "
  87. "otherwise: re-run the command bare to get its real exit code."),
  88. ]
  89. _READONLY_HEADS = frozenset({
  90. "grep", "rg", "ag", "find", "ls", "cat", "head", "tail", "jq", "awk",
  91. "sed", "strings", "zcat", "journalctl", "dmesg", "echo", "printf"})
  92. # Strong failure shapes keyed to specific tools so that error-mentioning
  93. # *content* (diffs, logs, commit messages) rarely matches.
  94. _FAILURE_SHAPES = re.compile(
  95. r"(?:"
  96. r"error\[E\d+\]" # rustc
  97. r"|error: could not compile" # cargo
  98. r"|error: aborting due to" # rustc summary
  99. r"|Traceback \(most recent call last\)" # python
  100. r"|(?m:^(?:=+ )?\d+ failed)" # pytest summary
  101. r"|(?m:^FAILED (?:\S+::|\S+\.py))" # pytest per-test lines
  102. r"|compilation terminated\." # gcc/clang
  103. r"|npm ERR!" # npm
  104. r"|BUILD FAILED|Build FAILED" # gradle/msbuild/echoed fallbacks
  105. r"|FAILED: " # ninja
  106. r"|(?m:^make(?:\[\d+\])?: \*\*\*)" # make
  107. r")")
  108. def _first_token(command: str) -> str:
  109. """Basename of the command head, skipping leading env-var assignments."""
  110. for tok in (command or "").strip().split():
  111. if "=" not in tok or tok.startswith(("=", "./", "/")):
  112. return tok.rsplit("/", 1)[-1]
  113. return ""
  114. def annotate_masked_success(command: str, output: str) -> Optional[str]:
  115. """Warning note when an exit-0 result likely masks a failure (caller gates on exit 0)."""
  116. cmd = command or ""
  117. window = (output or "")[:_SCAN_CHARS]
  118. if (not cmd or not window or _first_token(cmd) in _READONLY_HEADS
  119. or not _FAILURE_SHAPES.search(window)):
  120. return None
  121. return next((note for rx, note in _MASKING_SHAPES if rx.search(cmd)), None)
  122. def annotate_failure(command: str, exit_code: int, output: str) -> Optional[str]:
  123. """Return one short recovery hint for a failed command, or None (exit 0)."""
  124. if exit_code == 0:
  125. return None
  126. window = (output or "")[:_SCAN_CHARS]
  127. for fn in _OUTPUT_HINTS if window else ():
  128. try:
  129. if hint := fn(command or "", window):
  130. return hint
  131. except Exception:
  132. continue
  133. return _EXIT_CODE_HINTS.get(exit_code)