
    epj                        U d Z ddlmZ ddlZddlmZmZ dZddZddZ	ddZ
ddZddZddZddZeee	e
eeegZded<   ddddZded<   ddZdS )u  Output-pattern failure hints for the terminal tool.

When a command exits non-zero, the raw stderr often confuses models into
wasted diagnostic turns (e.g. retrying `python` when only `python3` exists,
or re-sending a gh field list that the installed gh doesn't support).

This module extends the exit-code semantics table in ``terminal_tool`` with
an *output-pattern* tier: a bounded scan of the command output that maps
well-known failure shapes to one short, actionable recovery hint.

Design rules (keep these when adding patterns):

* Only fires on non-zero exit codes — never annotate success.
* At most ONE hint per result, first match wins; patterns are ordered by
  observed frequency in production trajectories (state.db mining, Aug 2026).
* Scans only the first ``_SCAN_CHARS`` of output — hints must key on error
  headers, not deep context.
* Hints state the *next action*, not a diagnosis essay. One or two sentences.
* Pure function, no I/O, no config reads — trivially unit-testable.

Frequencies quoted below come from a 250k-terminal-result window of the
production session DB (Aug 2026): together these classes cover ~14k failed
calls whose retry chains averaged 1.4 extra tool turns each.
    )annotationsN)CallableOptionali  commandstroutputreturnOptional[str]c                f    t          j        d|          }|sd S d|                    d           dS )NzUnknown JSON field: "?(\w+)z2The installed gh does not support the JSON field '   ub   '. The valid field list is printed in the output above — retry using only fields from that list.researchgroupr   r   ms      :/home/thesage/.hermes/hermes-agent/tools/terminal_hints.py_hint_gh_unknown_json_fieldr   #   sH     		0&99A t	&QWWQZZ 	& 	& 	&    c                    t          j        d|          }|sd S |                    d          }|dk    r	 dS |dk    r	 dS d| d| d	S )
NzE(?:bash: line \d+: |bash: |sh: \d*:? ?)?([\w.+-]+): command not foundr   pythonun   This system has no bare `python` — use `python3`, or the project venv's interpreter (e.g. .venv/bin/python).pipuo   This system has no bare `pip` — use `pip3`, `python3 -m pip`, or the project venv's pip (e.g. .venv/bin/pip).`z6` is not installed or not on PATH. Verify with `which zK`; install it or use an absolute path instead of retrying the same command.r   )r   r   r   missings       r   _hint_command_not_foundr   0   s    
	Z\bccA tggajjG(B	
 	
 %>	
 	

	%G 	% 	%	% 	% 	%r   c                f    t          j        d|          }|sd S d|                    d           dS )Nz?(?:ModuleNotFoundError|ImportError): No module named '?([\w.]+)zPython cannot import 'r   z'. Most often the wrong interpreter is running: activate the project venv (e.g. `source .venv/bin/activate`) or invoke its python directly. Only pip install if the package is genuinely absent from that venv.r   r   s      r   _hint_module_not_foundr   G   sK    
	TV\]]A t	E 	E 	E 	Er   c                L    t          j        d|t           j                  sd S 	 dS )Nz-^CONFLICT |Automatic merge failed|needs mergeu   Git merge conflict. Do not retry this command. Resolve the conflicted files listed above (edit, then `git add`), then continue (`git rebase --continue` / commit the merge) — or abort with `--abort`.)r   r   Mr   r   s     r   _hint_merge_conflictr!   T   s/    9EvrtTT t	 r   c                f    t          j        d|          }|sd S d|                    d           dS )Nz+(?:fatal|error):.*?'([^']+)' already exists'r   u   ' already exists — retrying unchanged will keep failing. Reuse it, choose another name, or delete it first if it is genuinely stale.r   r   s      r   _hint_already_existsr$   `   sF    
	@&IIA t	AGGAJJ 	 	 	r   c                    d|vrd|vrd S 	 dS )NzAPI rate limitzwas submitted too quicklyu{   GitHub API rate limit hit — immediate retries will keep failing. Continue with other work and retry this operation later. r    s     r   _hint_gh_rate_limitr'   l   s-    v%%*EV*S*St	C r   c                    d|vrd|vrd S 	 dS )NzPermission deniedEACCESzPermission denied. Check ownership/mode of the target path (`ls -la`); prefer a user-writable location. Only escalate to sudo if the task genuinely requires it.r&   r    s     r   _hint_permission_deniedr*   v   s+    &((XV-C-Ct	- r   z)list[Callable[[str, str], Optional[str]]]_OUTPUT_HINTSu~   Exit 126: the file was found but is not executable — `chmod +x` it or invoke it via its interpreter (e.g. `bash script.sh`).u   Exit 137: the process was SIGKILLed — usually out-of-memory or an external kill. Reduce memory use or check `dmesg | tail` before retrying.zExit 124: the command hit its timeout. Raise timeout= (foreground max 600s) or run it with background=true and notify_on_complete=true.)~      |   zdict[int, str]_EXIT_CODE_HINTS	exit_codeintc                    |dk    rdS |pddt                    }|r0t          D ](}	  || pd|          }n# t          $ r Y w xY w|r|c S )t                              |          S )a  Return one short recovery hint for a failed command, or None.

    Args:
        command: The command string that ran.
        exit_code: Its exit code (non-zero for failures).
        output: Combined stdout/stderr as returned to the model.

    Only the first ``_SCAN_CHARS`` characters of output are examined and at
    most one hint is returned. Returns None for exit_code == 0.
    r   N )_SCAN_CHARSr+   	Exceptionr/   get)r   r0   r   windowfnhints         r   annotate_failurer:      s     A~~tlL[L)F  	 	Br'-R00    	***s   5
AA)r   r   r   r   r	   r
   )r   r   r0   r1   r   r   r	   r
   )__doc__
__future__r   r   typingr   r   r4   r   r   r   r!   r$   r'   r*   r+   __annotations__r/   r:   r&   r   r   <module>r?      s_    2 # " " " " " 				 % % % % % % % % 
 
 
 
   .
 
 
 
	 	 	 		 	 	 	        <     
J 
Y 
S$ $     + + + + + +r   