Skip to content

The agent that grows with you

refactor(approval): table-drive interpreter families, fold home-prefix rewriters, compact re-export blocks, drop dead _SHELL_PUNCTUATION

Tekniumd43ad31c4dc9
diff --git a/tools/approval.py b/tools/approval.py
index 6bcc45902ea..5af188f7bc2 100644
--- a/tools/approval.py
+++ b/tools/approval.py
@@ -19,109 +19,49 @@ from typing import Optional
from utils import env_var_enabled, is_truthy_value
from tools.approval_context import ( # noqa: F401 -- re-exported for callers/tests
- _approval_session_key,
- _approval_turn_id,
- _approval_tool_call_id,
- _approval_session_id,
- _hermes_interactive_ctx,
- set_hermes_interactive_context,
- reset_hermes_interactive_context,
- _is_interactive_cli,
- _fire_approval_hook,
- set_current_session_key,
- reset_current_session_key,
- set_current_observability_context,
- reset_current_observability_context,
- get_current_session_key,
- _session_env_flag,
- _get_session_platform,
- _is_cron_approval_context,
- _UNATTENDED_APPROVAL_PLATFORMS,
- _is_unattended_platform_approval_context,
- _is_single_query_approval_context,
- _is_gateway_approval_context,
- _resolve_cli_approval_callback,
- _should_fall_through_to_cli_approval,
- _normalize_approval_mode,
- _get_approval_config,
- _get_approval_mode,
- _get_approval_timeout,
- _binary_approval_mode,
- _get_cron_approval_mode,
- _get_single_query_approval_mode,
- _get_unattended_approval_mode,
- _tirith_fail_open,
+ _approval_session_key, _approval_turn_id, _approval_tool_call_id,
+ set_hermes_interactive_context, reset_hermes_interactive_context,
+ _is_interactive_cli, _fire_approval_hook, set_current_session_key,
+ reset_current_session_key, set_current_observability_context,
+ reset_current_observability_context, get_current_session_key,
+ _get_session_platform, _is_cron_approval_context,
+ _UNATTENDED_APPROVAL_PLATFORMS, _is_unattended_platform_approval_context,
+ _is_single_query_approval_context, _is_gateway_approval_context,
+ _resolve_cli_approval_callback, _should_fall_through_to_cli_approval,
+ _normalize_approval_mode, _get_approval_config, _get_approval_mode,
+ _get_approval_timeout, _get_cron_approval_mode, _get_single_query_approval_mode,
+ _get_unattended_approval_mode, _tirith_fail_open,
_get_approval_transport_config,
)
from tools.approval_prompt import ( # noqa: F401 -- re-exported for callers/tests
- prompt_dangerous_approval,
- _CLI_CHOICE_ALIASES,
- _CLI_CHOICE_I18N,
- _prompt_dangerous_approval_inner,
- get_plugin_manager,
- _present_with_selected_transport,
- _transport_denied_result,
- _transport_choice,
- request_elicitation_consent,
+ prompt_dangerous_approval, get_plugin_manager, _present_with_selected_transport,
+ _transport_choice, request_elicitation_consent,
)
from tools.approval_floors import ( # noqa: F401 -- re-exported for callers/tests
- _match_user_deny_rule,
- _user_deny_block_result,
- _save_blocked_payload,
- _hardline_block_result,
- _sudo_stdin_block_result,
- _SHELL_CONTROL_CHARS,
- _REINTERPRETED_ARGUMENT_RE,
- _has_allowlist_shell_operator,
+ _match_user_deny_rule, _user_deny_block_result, _save_blocked_payload,
+ _hardline_block_result, _sudo_stdin_block_result, _has_allowlist_shell_operator,
_command_matches_permanent_allowlist,
)
from tools.approval_detection import ( # noqa: F401 -- re-exported for callers/tests
- _CREDENTIAL_FILES,
- _SYSTEM_CONFIG_PATH,
- _COMMAND_TAIL,
- HARDLINE_PATTERNS,
- _check_sudo_stdin_guard,
- detect_hardline_command,
- DANGEROUS_PATTERNS,
- _approval_key_aliases,
- _normalize_command_for_detection,
- _rewrite_resolved_user_home,
- _rewrite_resolved_hermes_home,
- _MAX_SEPARATOR_FREE_COMMAND_CHARS,
- _PARSER_LIMIT_DESCRIPTION,
- _MALFORMED_EXEC_DESCRIPTION,
- _bash_exec_payload,
- _read_shell_word,
- _deobfuscate_shell_word_for_detection,
- _iter_shell_command_starts,
- _command_detection_variants,
+ _SYSTEM_CONFIG_PATH, _COMMAND_TAIL, HARDLINE_PATTERNS, _check_sudo_stdin_guard,
+ detect_hardline_command, DANGEROUS_PATTERNS, _approval_key_aliases,
+ _normalize_command_for_detection, _rewrite_resolved_user_home,
+ _rewrite_resolved_hermes_home, _MAX_SEPARATOR_FREE_COMMAND_CHARS,
+ _PARSER_LIMIT_DESCRIPTION, _MALFORMED_EXEC_DESCRIPTION, _bash_exec_payload,
+ _read_shell_word, _deobfuscate_shell_word_for_detection,
+ _iter_shell_command_starts, _command_detection_variants,
detect_dangerous_command,
)
from tools.approval_human_wait import ( # noqa: F401 -- re-exported for callers/tests
- _HumanWaitState,
- _human_wait_lock,
- _human_wait_states,
- _HUMAN_WAIT_MAX_SESSIONS,
- HUMAN_WAIT_MARGIN_S,
- human_wait_ceiling,
- _clamped_window_seconds,
- _human_wait_state,
- human_wait_window,
- human_wait_seconds,
+ _human_wait_lock, _human_wait_states, _HUMAN_WAIT_MAX_SESSIONS,
+ HUMAN_WAIT_MARGIN_S, human_wait_ceiling, human_wait_window, human_wait_seconds,
)
from tools.approval_smart import ( # noqa: F401 -- re-exported for callers/tests
- _strip_shell_comments,
- _strip_line_comment,
- _get_smart_policy,
- _smart_approve,
- _prepare_smart_approval_observer,
- _observe_smart_approval_verdict,
+ _strip_shell_comments, _strip_line_comment, _get_smart_policy, _smart_approve,
_smart_verdict,
)
from tools.approval_gateway_wait import ( # noqa: F401 -- re-exported for callers/tests
- _ApprovalEntry,
- _await_coalesced_leader,
- _await_gateway_decision,
+ _ApprovalEntry, _await_gateway_decision,
)
logger = logging.getLogger(__name__)
diff --git a/tools/approval_detection.py b/tools/approval_detection.py
index 4521f543e53..54ace6db9d5 100644
--- a/tools/approval_detection.py
+++ b/tools/approval_detection.py
@@ -634,36 +634,39 @@ def _fold_home_prefixes(command: str, paths, replacement: str) -> str:
return command
-def _rewrite_resolved_user_home(command: str) -> str:
- """Rewrite the user's absolute home prefix (expanduser, realpath, and an
- explicit ``HOME`` — Windows expanduser uses USERPROFILE and ignores HOME) to
- ``~/``. No-op when the home is unset or degenerate."""
+def _user_home_candidates() -> list[str]:
+ # expanduser, realpath, and an explicit HOME — Windows expanduser uses
+ # USERPROFILE and ignores HOME.
+ home = os.path.expanduser("~")
+ return [home, os.path.realpath(home), os.environ.get("HOME", "")]
+
+
+def _hermes_home_candidates() -> list[str]:
+ from hermes_constants import get_hermes_home
+ home = get_hermes_home().expanduser()
+ return [str(home), str(home.resolve(strict=False))]
+
+
+def _rewrite_home(command: str, candidates, replacement: str) -> str:
+ """Fold a resolved absolute home prefix to its ``~`` spelling; no-op when
+ the home is unset, degenerate, or unresolvable."""
try:
- home = os.path.expanduser("~")
- candidates = [
- home,
- os.path.realpath(home),
- os.environ.get("HOME", ""),
- ]
+ paths = candidates()
except Exception:
return command
- return _fold_home_prefixes(command, candidates, "~")
+ return _fold_home_prefixes(command, paths, replacement)
+
+
+def _rewrite_resolved_user_home(command: str) -> str:
+ """User home (expanduser / realpath / $HOME) -> ``~/``."""
+ return _rewrite_home(command, _user_home_candidates, "~")
def _rewrite_resolved_hermes_home(command: str) -> str:
- """Rewrite the resolved HERMES_HOME prefix (and its realpath) to ``~/.hermes/``
- so _HERMES_CONFIG_PATH / _HERMES_ENV_PATH match Docker/gateway deployments
- that spell the absolute path. No-op when unresolvable."""
- try:
- from hermes_constants import get_hermes_home
- home = get_hermes_home().expanduser()
- candidates = [
- str(home),
- str(home.resolve(strict=False)),
- ]
- except Exception:
- return command
- return _fold_home_prefixes(command, candidates, "~/.hermes")
+ """Resolved HERMES_HOME (and its realpath) -> ``~/.hermes/`` so the
+ _HERMES_CONFIG_PATH / _HERMES_ENV_PATH rules match Docker/gateway
+ deployments that spell the absolute path."""
+ return _rewrite_home(command, _hermes_home_candidates, "~/.hermes")
_PARAM_REPLACEMENT_RE = re.compile(r"\$\{[^}/\s]+/[^}/]*/(?P<replacement>[^}]*)\}")
@@ -748,7 +751,6 @@ _READ_TOOL_SHORT_OPTIONS_WITH_ARG = {
"man": frozenset("CRLmMSserEPp"),
"ag": frozenset("gGmpW"),
}
-_SHELL_PUNCTUATION = {";", "&", "&&", "|", "||", "(", ")", "{", "}"}
_MAX_DETECTION_COMMAND_CHARS = 128_000
_MAX_SEPARATOR_FREE_COMMAND_CHARS = 4_096
_MAX_DETECTION_SEGMENTS = 25_000
@@ -756,7 +758,6 @@ _PARSER_LIMIT_DESCRIPTION = "command parser limit exceeded"
_MALFORMED_EXEC_DESCRIPTION = "command parser limit or malformed executable payload"
-
def _command_parser_limit_exceeded(command: str) -> bool:
"""Bound all parser work before normalization/tokenization.
@@ -944,20 +945,21 @@ def _grep_safe_detection_variant(command: str) -> tuple[str, bool]:
return "".join(parts), False
+_INTERPRETER_NAME_RES = (
+ ("python", re.compile(r"py(?:\.exe)?|python[23]?(?:\.\d+)*(?:\.exe)?")),
+ ("node", re.compile(r"node(?:js)?(?:\.exe)?")),
+ ("perl", re.compile(r"perl[0-9]*(?:\.\d+)*(?:\.exe)?")),
+ ("ruby", re.compile(r"ruby[0-9.]*(?:\.exe)?")),
+ ("php", re.compile(r"php(?:\.exe)?")),
+ ("powershell", re.compile(r"powershell(?:\.exe)?|pwsh(?:\.exe)?")),
+)
+
+
def _interpreter_family(executable: str) -> str | None:
name = os.path.basename(executable).lower()
- if re.fullmatch(r"py(?:\.exe)?|python[23]?(?:\.\d+)*(?:\.exe)?", name):
- return "python"
- if re.fullmatch(r"node(?:js)?(?:\.exe)?", name):
- return "node"
- if re.fullmatch(r"perl[0-9]*(?:\.\d+)*(?:\.exe)?", name):
- return "perl"
- if re.fullmatch(r"ruby[0-9.]*(?:\.exe)?", name):
- return "ruby"
- if re.fullmatch(r"php(?:\.exe)?", name):
- return "php"
- if re.fullmatch(r"powershell(?:\.exe)?|pwsh(?:\.exe)?", name):
- return "powershell"
+ for family, name_re in _INTERPRETER_NAME_RES:
+ if name_re.fullmatch(name):
+ return family
return None
@@ -1272,7 +1274,6 @@ def _read_shell_word(command: str, pos: int) -> tuple[int, int, str]:
return (start, i, command[start:i])
-
def _is_simple_shell_literal(value: str) -> bool:
return bool(value and _SIMPLE_SHELL_LITERAL_RE.fullmatch(value))