claude-dev-env 8.119.2 → 8.120.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,286 @@
1
+ #!/usr/bin/env python3
2
+ """PreToolUse gate: keep agents from draining the GitHub API limit.
3
+
4
+ The gate refuses three kinds of gh call, checked in this order::
5
+
6
+ gh run watch 123 watch command
7
+ gh pr checks 12 --watch watch command
8
+ while :; do gh run view 1; sleep 10; done tight polling loop
9
+ watch -n 5 gh run view 1 tight polling loop
10
+ gh pr view 12 (core limit 4000 of 5000 used) spent budget
11
+
12
+ A watch command polls every few seconds until a run ends. A polling loop is a
13
+ Bash ``while``, ``until`` or ``for`` loop, a PowerShell ``while``, ``do``,
14
+ ``for`` or ``foreach`` loop or ``ForEach-Object`` or ``%`` pipeline loop, or
15
+ ``watch``, that calls gh and sleeps under 60 seconds in total per pass. Each
16
+ outermost loop is read on its own, from its keyword through the ``done`` or
17
+ ``}`` that closes it, and a loop nested inside it counts toward it. A brace
18
+ glued to a word, as in ``{gh run view 1}``, counts as its own token. An
19
+ endless loop such as ``while :`` or
20
+ ``for (;;)``, or a ``while`` or ``until`` loop whose condition calls gh, is
21
+ refused when it calls gh with no sleep. Any other loop with no sleep passes,
22
+ and so does a loop whose sleep is a variable.
23
+
24
+ A gh read on the core REST limit is refused while ``used * 5 >= limit * 4``.
25
+ The reads are the ``gh api`` calls with no write method and no field or input
26
+ option, and the subcommands the constants table lists, such as ``pr view`` and
27
+ ``run list``. Writes, local commands, ``gh api graphql`` and ``gh api
28
+ rate_limit`` pass. ``hooks_constants/gh_api_budget.py`` reads the limit and
29
+ caches it for five minutes, and a limit it cannot read lets the call through.
30
+
31
+ The program is read past wrappers, chained commands and a leading PowerShell
32
+ ``$name =`` assignment, so ``bash -c "gh run watch 1"`` and ``$s = gh run
33
+ watch 1`` are refused, while quoted text such as ``echo "gh run watch"``
34
+ passes. A command with no gh call reads no cache and runs no query.
35
+
36
+ Hosted by ``blocking/bash_pre_tool_use_dispatcher.py`` for the Bash and
37
+ PowerShell tools.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import json
43
+ import sys
44
+ import time
45
+ from itertools import pairwise
46
+ from pathlib import Path
47
+
48
+ try:
49
+ _hooks_root_directory = str(Path(__file__).resolve().parent.parent)
50
+ if _hooks_root_directory not in sys.path:
51
+ sys.path.insert(0, _hooks_root_directory)
52
+ from hooks_constants.bash_pre_tool_use_dispatcher_constants import (
53
+ ALL_BASH_AND_POWERSHELL_TOOL_NAMES,
54
+ DENY_DECISION,
55
+ HOOK_EVENT_NAME,
56
+ )
57
+ from hooks_constants.cloud_graphql_gate_constants import (
58
+ ALL_GH_HELP_FLAGS,
59
+ GH_API_SUBCOMMAND,
60
+ GH_ENDPOINT_PATH_SEPARATOR,
61
+ GITHUB_GRAPHQL_ENDPOINT_PATTERN,
62
+ )
63
+ from hooks_constants.gh_api_budget import (
64
+ CoreRateBudget,
65
+ is_core_budget_spent,
66
+ read_core_rate_budget,
67
+ )
68
+ from hooks_constants.gh_api_budget_gate_constants import (
69
+ ALL_GH_API_BODY_OPTIONS,
70
+ ALL_GH_API_METHOD_OPTIONS,
71
+ ALL_GH_API_READ_METHODS,
72
+ ALL_GH_API_SHORT_BODY_OPTIONS,
73
+ ALL_GH_API_UNBUDGETED_ENDPOINTS,
74
+ ALL_GH_PR_CHECKS_COMMAND_WORDS,
75
+ ALL_GH_READ_COMMAND_GROUPS,
76
+ ALL_GH_READ_SUBCOMMANDS_BY_COMMAND_GROUP,
77
+ ALL_GH_RUN_WATCH_COMMAND_WORDS,
78
+ GATE_HOOK_NAME,
79
+ GH_API_SHORT_METHOD_OPTION,
80
+ GH_COMMAND_PATH_LENGTH,
81
+ GH_SHORT_OPTION_LENGTH,
82
+ GH_WATCH_OPTION,
83
+ RESET_TIME_FORMAT,
84
+ SPENT_BUDGET_DENY_REASON_TEMPLATE,
85
+ SPENT_BUDGET_RESET_SENTENCE_TEMPLATE,
86
+ TIGHT_POLLING_LOOP_DENY_REASON,
87
+ WATCH_COMMAND_DENY_REASON,
88
+ )
89
+ from hooks_constants.gh_argument_lists import all_gh_call_argument_lists
90
+ from hooks_constants.gh_command_words import gh_command_words_and_options
91
+ from hooks_constants.gh_command_words_constants import GH_OPTION_VALUE_SEPARATOR
92
+ from hooks_constants.gh_shell_loop_scan import (
93
+ is_tight_gh_loop_text,
94
+ is_tight_gh_watch_segment,
95
+ )
96
+ from hooks_constants.hook_block_logger import log_hook_block
97
+ from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
98
+ from hooks_constants.pytest_invocation import unquoted_token
99
+ from hooks_constants.shell_command_wrappers import (
100
+ all_wrapped_command_segments,
101
+ all_wrapped_command_texts,
102
+ )
103
+ except ImportError as import_error:
104
+ raise ImportError(
105
+ "The gh API budget gate cannot import its dependencies; "
106
+ "ensure the hooks directory is importable."
107
+ ) from import_error
108
+
109
+
110
+ def _is_gh_watch_call(all_gh_arguments: list[str]) -> bool:
111
+ all_command_words, all_option_names = gh_command_words_and_options(all_gh_arguments)
112
+ if any(each_option in ALL_GH_HELP_FLAGS for each_option in all_option_names):
113
+ return False
114
+ command_path = tuple(all_command_words[:GH_COMMAND_PATH_LENGTH])
115
+ if command_path == ALL_GH_RUN_WATCH_COMMAND_WORDS:
116
+ return True
117
+ return command_path == ALL_GH_PR_CHECKS_COMMAND_WORDS and GH_WATCH_OPTION in all_option_names
118
+
119
+
120
+ def runs_gh_watch_command(command: str) -> bool:
121
+ """Return True when the command runs ``gh run watch`` or ``gh pr checks --watch``.
122
+
123
+ ::
124
+
125
+ gh run watch 123 -> True
126
+ cd repo && gh pr checks --watch -> True
127
+ echo "gh run watch" -> False
128
+
129
+ Args:
130
+ command: The shell command text the agent is about to run.
131
+ """
132
+ return any(_is_gh_watch_call(each) for each in all_gh_call_argument_lists(command))
133
+
134
+
135
+ def runs_tight_gh_polling_loop(command: str) -> bool:
136
+ """Return True when a shell loop or ``watch`` calls gh with under 60 seconds of sleep.
137
+
138
+ ::
139
+
140
+ while :; do gh run view 1; sleep 30; done -> True
141
+ while ($true) { gh run view 1 } -> True
142
+ watch -n 5 gh run view 1 -> True
143
+ while :; do gh run view 1; sleep 60; done -> False
144
+ for x in a b c; do gh pr view $x; done -> False
145
+
146
+ Args:
147
+ command: The shell command text the agent is about to run.
148
+ """
149
+ if any(is_tight_gh_watch_segment(each) for each in all_wrapped_command_segments(command)):
150
+ return True
151
+ return any(is_tight_gh_loop_text(each) for each in all_wrapped_command_texts(command))
152
+
153
+
154
+ def _gh_api_method(all_gh_arguments: list[str]) -> str | None:
155
+ """Return the HTTP method a ``gh api`` call names, uppercased, or None when it names none."""
156
+ all_unquoted_arguments = [unquoted_token(each) for each in all_gh_arguments]
157
+ for each_previous_argument, each_argument in pairwise(["", *all_unquoted_arguments]):
158
+ if each_previous_argument in ALL_GH_API_METHOD_OPTIONS:
159
+ return each_argument.upper()
160
+ option, separator, attached_method = each_argument.partition(GH_OPTION_VALUE_SEPARATOR)
161
+ if option in ALL_GH_API_METHOD_OPTIONS and separator:
162
+ return attached_method.upper()
163
+ is_glued_short_method = each_argument.startswith(GH_API_SHORT_METHOD_OPTION)
164
+ if is_glued_short_method and len(each_argument) > GH_SHORT_OPTION_LENGTH:
165
+ return each_argument[GH_SHORT_OPTION_LENGTH:].upper()
166
+ return None
167
+
168
+
169
+ def _is_budgeted_api_call(
170
+ all_gh_arguments: list[str], all_command_words: list[str], all_option_names: list[str]
171
+ ) -> bool:
172
+ endpoint = unquoted_token(all_command_words[1]) if len(all_command_words) > 1 else ""
173
+ is_unbudgeted_endpoint = (
174
+ endpoint.strip(GH_ENDPOINT_PATH_SEPARATOR).lower() in ALL_GH_API_UNBUDGETED_ENDPOINTS
175
+ or GITHUB_GRAPHQL_ENDPOINT_PATTERN.search(endpoint) is not None
176
+ )
177
+ if not endpoint or is_unbudgeted_endpoint:
178
+ return False
179
+ method = _gh_api_method(all_gh_arguments)
180
+ if method is not None:
181
+ return method in ALL_GH_API_READ_METHODS
182
+ return not any(
183
+ each_option in ALL_GH_API_BODY_OPTIONS
184
+ or each_option[:GH_SHORT_OPTION_LENGTH] in ALL_GH_API_SHORT_BODY_OPTIONS
185
+ for each_option in all_option_names
186
+ )
187
+
188
+
189
+ def _is_budgeted_gh_read(all_gh_arguments: list[str]) -> bool:
190
+ all_command_words, all_option_names = gh_command_words_and_options(all_gh_arguments)
191
+ if not all_command_words or any(each in ALL_GH_HELP_FLAGS for each in all_option_names):
192
+ return False
193
+ command_group = all_command_words[0]
194
+ if command_group == GH_API_SUBCOMMAND:
195
+ return _is_budgeted_api_call(all_gh_arguments, all_command_words, all_option_names)
196
+ if command_group in ALL_GH_READ_COMMAND_GROUPS:
197
+ return True
198
+ all_read_subcommands = ALL_GH_READ_SUBCOMMANDS_BY_COMMAND_GROUP.get(command_group, frozenset())
199
+ return len(all_command_words) > 1 and all_command_words[1] in all_read_subcommands
200
+
201
+
202
+ def runs_budgeted_gh_read(command: str) -> bool:
203
+ """Return True when the command runs a gh read that draws on the core REST limit.
204
+
205
+ ::
206
+
207
+ gh pr view 12 -> True
208
+ gh api repos/o/r/pulls -> True
209
+ gh api -X POST repos/o/r/issues -> False
210
+ gh api graphql -f query=@q.graphql -> False
211
+ gh auth status -> False
212
+
213
+ Args:
214
+ command: The shell command text the agent is about to run.
215
+ """
216
+ return any(_is_budgeted_gh_read(each) for each in all_gh_call_argument_lists(command))
217
+
218
+
219
+ def _spent_budget_reason(budget: CoreRateBudget) -> str:
220
+ reset_sentence = ""
221
+ try:
222
+ if budget.reset is not None:
223
+ reset_time = time.strftime(RESET_TIME_FORMAT, time.gmtime(budget.reset))
224
+ reset_sentence = SPENT_BUDGET_RESET_SENTENCE_TEMPLATE.format(reset_time=reset_time)
225
+ except (OverflowError, OSError, ValueError):
226
+ reset_sentence = ""
227
+ return SPENT_BUDGET_DENY_REASON_TEMPLATE.format(
228
+ used=budget.used, limit=budget.limit, reset_sentence=reset_sentence
229
+ )
230
+
231
+
232
+ def _deny_reason(command: str, all_gh_argument_lists: list[list[str]]) -> str | None:
233
+ """Return the first refusal's reason for a command that calls gh, or None when it passes."""
234
+ if any(_is_gh_watch_call(each) for each in all_gh_argument_lists):
235
+ return WATCH_COMMAND_DENY_REASON
236
+ if runs_tight_gh_polling_loop(command):
237
+ return TIGHT_POLLING_LOOP_DENY_REASON
238
+ if not any(_is_budgeted_gh_read(each) for each in all_gh_argument_lists):
239
+ return None
240
+ budget = read_core_rate_budget()
241
+ if budget is None or not is_core_budget_spent(budget):
242
+ return None
243
+ return _spent_budget_reason(budget)
244
+
245
+
246
+ def main() -> None:
247
+ """Deny a gh watch command, a tight gh polling loop, or a gh read on a spent budget."""
248
+ hook_payload = read_hook_input_dictionary_from_stdin()
249
+ if hook_payload is None:
250
+ return
251
+ tool_name = hook_payload.get("tool_name")
252
+ if tool_name not in ALL_BASH_AND_POWERSHELL_TOOL_NAMES:
253
+ return
254
+ tool_input = hook_payload.get("tool_input")
255
+ if not isinstance(tool_input, dict):
256
+ return
257
+ command = tool_input.get("command", "")
258
+ if not isinstance(command, str):
259
+ return
260
+ all_gh_argument_lists = all_gh_call_argument_lists(command)
261
+ if not all_gh_argument_lists:
262
+ return
263
+ deny_reason = _deny_reason(command, all_gh_argument_lists)
264
+ if deny_reason is None:
265
+ return
266
+ log_hook_block(GATE_HOOK_NAME, HOOK_EVENT_NAME, deny_reason, str(tool_name), command)
267
+ _write_deny_decision(deny_reason)
268
+
269
+
270
+ def _write_deny_decision(deny_reason: str) -> None:
271
+ sys.stdout.write(
272
+ json.dumps(
273
+ {
274
+ "hookSpecificOutput": {
275
+ "hookEventName": HOOK_EVENT_NAME,
276
+ "permissionDecision": DENY_DECISION,
277
+ "permissionDecisionReason": deny_reason,
278
+ }
279
+ }
280
+ )
281
+ )
282
+ sys.stdout.flush()
283
+
284
+
285
+ if __name__ == "__main__":
286
+ main()
@@ -3,8 +3,9 @@
3
3
  A Bash tool call starts one interpreter, the dispatcher's own. Each roster
4
4
  entry then runs in that process through runpy, so the roster's exact content is
5
5
  the chain's cost after that single start. The roster holds the MSYS rewriter,
6
- the headless Claude broker gate, and the gh global account gate; any other hook
7
- added here fails this test.
6
+ the headless Claude broker gate, the gh global account gate, the gh API budget
7
+ gate, the cloud GraphQL gate, the Python Windows invocation gate, and the
8
+ transcript root search gate; any other hook added here fails this test.
8
9
  """
9
10
 
10
11
  import sys
@@ -22,7 +23,7 @@ from hooks_constants.bash_pre_tool_use_dispatcher_constants import (
22
23
  )
23
24
 
24
25
 
25
- def test_bash_roster_starts_only_the_msys_rewriter_and_the_five_gates() -> None:
26
+ def test_bash_roster_starts_only_the_msys_rewriter_and_the_six_gates() -> None:
26
27
  assert ALL_BASH_HOSTED_HOOK_ENTRIES == (
27
28
  BashHostedHookEntry(
28
29
  script_relative_path="blocking/msys_rev_path_rewriter.py",
@@ -38,6 +39,10 @@ def test_bash_roster_starts_only_the_msys_rewriter_and_the_five_gates() -> None:
38
39
  applicable_tool_names=ALL_BASH_AND_POWERSHELL_TOOL_NAMES,
39
40
  replaced_by_plugin_name="shell-guards",
40
41
  ),
42
+ BashHostedHookEntry(
43
+ script_relative_path="blocking/gh_api_budget_gate.py",
44
+ applicable_tool_names=ALL_BASH_AND_POWERSHELL_TOOL_NAMES,
45
+ ),
41
46
  BashHostedHookEntry(
42
47
  script_relative_path="blocking/cloud_graphql_gate.py",
43
48
  applicable_tool_names=ALL_BASH_AND_POWERSHELL_TOOL_NAMES,
@@ -274,6 +274,7 @@ def test_should_drop_the_gates_the_shell_guards_mod_holds_while_it_is_on(
274
274
  all_script_paths = [each_entry.script_relative_path for each_entry in select_applicable_entries(BASH_TOOL_NAME)]
275
275
  assert all_script_paths == [
276
276
  "blocking/msys_rev_path_rewriter.py",
277
+ "blocking/gh_api_budget_gate.py",
277
278
  "blocking/cloud_graphql_gate.py",
278
279
  "blocking/python_windows_invocation_gate.py",
279
280
  "blocking/transcript_root_search_gate.py",