claude-dev-env 8.119.2 → 8.121.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.
Files changed (44) hide show
  1. package/bin/ever-registered-hooks.mjs +1 -0
  2. package/hooks/advisory/auto_mode_denial_quick_fix.py +275 -27
  3. package/hooks/advisory/auto_mode_rule_flow_eval/auto_mode_rule_flow_cases.json +3475 -0
  4. package/hooks/advisory/auto_mode_rule_flow_eval/auto_mode_rule_flow_runner.py +849 -0
  5. package/hooks/advisory/auto_mode_rule_flow_eval/stub_allow_hook.py +20 -0
  6. package/hooks/advisory/auto_mode_rule_flow_eval/stub_hold_hook.py +54 -0
  7. package/hooks/advisory/auto_mode_rule_flow_eval/test_auto_mode_rule_flow_runner.py +143 -0
  8. package/hooks/advisory/test_auto_mode_denial_quick_fix.py +533 -9
  9. package/hooks/auto_mode_question_transcript.py +215 -0
  10. package/hooks/auto_mode_refusal_ledger.py +481 -0
  11. package/hooks/auto_mode_refusal_ledger_files.py +336 -0
  12. package/hooks/auto_mode_rule_steps.py +177 -0
  13. package/hooks/blocking/auto_mode_refusal_stop_gate.py +384 -0
  14. package/hooks/blocking/gh_api_budget_gate.py +286 -0
  15. package/hooks/blocking/test_auto_mode_refusal_stop_gate.py +484 -0
  16. package/hooks/blocking/test_bash_dispatcher_interpreter_starts.py +8 -3
  17. package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +1 -0
  18. package/hooks/blocking/test_gh_api_budget_gate.py +602 -0
  19. package/hooks/features/README.md +1 -1
  20. package/hooks/features/bash-dispatchers.md +3 -0
  21. package/hooks/features/session-context.md +5 -2
  22. package/hooks/hooks.json +5 -0
  23. package/hooks/hooks_constants/auto_mode_denial_quick_fix_constants.py +51 -3
  24. package/hooks/hooks_constants/auto_mode_refusal_ledger_constants.py +85 -0
  25. package/hooks/hooks_constants/auto_mode_refusal_stop_gate_constants.py +80 -0
  26. package/hooks/hooks_constants/auto_mode_rule_flow_runner_constants.py +225 -0
  27. package/hooks/hooks_constants/auto_mode_rule_steps_constants.py +82 -0
  28. package/hooks/hooks_constants/bash_pre_tool_use_dispatcher_constants.py +4 -0
  29. package/hooks/hooks_constants/gh_api_budget.py +186 -0
  30. package/hooks/hooks_constants/gh_api_budget_gate_constants.py +215 -0
  31. package/hooks/hooks_constants/gh_argument_lists.py +169 -0
  32. package/hooks/hooks_constants/gh_shell_loop_scan.py +386 -0
  33. package/hooks/hooks_constants/test_bash_pre_tool_use_dispatcher_constants.py +5 -1
  34. package/hooks/hooks_constants/test_gh_api_budget.py +125 -0
  35. package/hooks/hooks_constants/test_gh_argument_lists.py +49 -0
  36. package/hooks/hooks_constants/test_gh_shell_loop_scan.py +50 -0
  37. package/hooks/test_auto_mode_question_transcript.py +113 -0
  38. package/hooks/test_auto_mode_refusal_ledger.py +398 -0
  39. package/hooks/test_auto_mode_refusal_ledger_files.py +155 -0
  40. package/hooks/test_auto_mode_rule_steps.py +210 -0
  41. package/package.json +1 -1
  42. package/scripts/policy_lint/adapter_configuration.py +5 -0
  43. package/scripts/policy_lint/config/constants.py +1 -0
  44. package/scripts/tests/test_adapter_configuration.py +8 -0
@@ -0,0 +1,384 @@
1
+ #!/usr/bin/env python3
2
+ """Stop gate that holds a turn while a refused step waits on the user or on its rule.
3
+
4
+ At each turn end the gate reads the refusal ledger the PermissionDenied hook
5
+ keeps, and the session transcript::
6
+
7
+ flow switch off, playbook missing, or print mode -> turn ends, no output
8
+ answers read from transcript_path -> answered entries leave the queue
9
+ pending entry, not asked, held under 2 times -> question hold, 4 groups at most
10
+ allowed entry, no add call names it, held under 2 times -> rule hold
11
+ none left -> turn ends, no output
12
+ a transcript it cannot read -> no calls seen, holds as above
13
+ any other error -> turn ends, no output
14
+ reader closed stdout before the hold -> exit 0, the hold text is dropped
15
+
16
+ An entry counts as asked once an answered ``AskUserQuestion`` call at or after
17
+ a question record's ``transcript_offset`` asks that record's exact text, with
18
+ any answer, or once a decision card call claims it. A card call that did not
19
+ fail and carries the card question ``Should auto mode have refused this <tool>
20
+ step?`` claims the oldest pending, unasked group of that tool that has an
21
+ entry with a question record at or before the card, and within it those
22
+ entries. Each card claims one
23
+ group, and the entry keeps the card's offset so a later Stop does not claim
24
+ again with it. The asked mark stays on the entry. An add call
25
+ is a Bash call that did not fail whose command holds ``add_auto_mode_rule.py
26
+ add`` and the entry's id, which its ledger file name carries. The gate keeps
27
+ its own counts in each entry file, so it acts the same whether or not
28
+ ``stop_hook_active`` is set, and an entry holds four turns at most. A hold
29
+ exits 2 with a block object, through ``hold_stop``.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import json
35
+ import os
36
+ import sys
37
+ from pathlib import Path
38
+
39
+ _hooks_root_directory = str(Path(__file__).resolve().parent.parent)
40
+ if _hooks_root_directory not in sys.path:
41
+ sys.path.insert(0, _hooks_root_directory)
42
+
43
+ import auto_mode_refusal_ledger
44
+ from auto_mode_question_transcript import (
45
+ AskedQuestions,
46
+ TranscriptCall,
47
+ read_transcript,
48
+ )
49
+ from auto_mode_refusal_ledger_files import (
50
+ JsonObject,
51
+ LedgerEntry,
52
+ QuestionRecord,
53
+ entry_file_path,
54
+ )
55
+ from hooks_constants.auto_mode_refusal_ledger_constants import (
56
+ ALLOWED_ANSWER,
57
+ QUESTION_ASKED_FIELD,
58
+ QUESTION_CARD_OFFSET_FIELD,
59
+ QUESTION_HOLDS_FIELD,
60
+ RULE_HOLDS_FIELD,
61
+ )
62
+ from hooks_constants.auto_mode_refusal_stop_gate_constants import (
63
+ ALL_CARD_TOOL_NAMES,
64
+ ALLOW_EXIT_CODE,
65
+ BASH_TOOL_NAME,
66
+ CARD_QUESTION_TEMPLATE,
67
+ COMMAND_INPUT_KEY,
68
+ ENTRYPOINT_ENVIRONMENT_VARIABLE,
69
+ LIST_LINE_TEMPLATE,
70
+ MAXIMUM_HOLDS_PER_KIND,
71
+ MAXIMUM_QUESTIONS_PER_HOLD,
72
+ PRINT_MODE_ENTRYPOINT,
73
+ QUESTION_BLOCK_TEMPLATE,
74
+ QUESTION_SECTION_FOOTER_TEMPLATE,
75
+ QUESTION_SECTION_HEADER,
76
+ RULE_ADD_COMMAND_MARKER,
77
+ RULE_SECTION_HEADER_TEMPLATE,
78
+ SECTION_SEPARATOR,
79
+ STOP_EVENT_NAME,
80
+ )
81
+ from hooks_constants.hook_block_logger import log_hook_block
82
+ from hooks_constants.stop_hook_hold import hold_stop
83
+
84
+
85
+ def _all_text_values(tool_input: object) -> list[str]:
86
+ if isinstance(tool_input, str):
87
+ return [tool_input]
88
+ if isinstance(tool_input, dict):
89
+ return [each for each_value in tool_input.values() for each in _all_text_values(each_value)]
90
+ if isinstance(tool_input, list):
91
+ return [each for each_value in tool_input for each in _all_text_values(each_value)]
92
+ return []
93
+
94
+
95
+ def _is_card_for(call: TranscriptCall, tool_name: str) -> bool:
96
+ return (
97
+ call.tool_name in ALL_CARD_TOOL_NAMES
98
+ and not call.is_error
99
+ and CARD_QUESTION_TEMPLATE.format(tool_name=tool_name) in _all_text_values(call.tool_input)
100
+ )
101
+
102
+
103
+ def _is_text_asked(record: QuestionRecord, all_asked: list[AskedQuestions]) -> bool:
104
+ return any(
105
+ each_asked.call_offset >= record.transcript_offset
106
+ and record.question in each_asked.answer_by_question
107
+ for each_asked in all_asked
108
+ )
109
+
110
+
111
+ def _earliest_record_offset_by_id(all_records: list[QuestionRecord]) -> dict[str, int]:
112
+ offset_by_id: dict[str, int] = {}
113
+ for each_record in all_records:
114
+ for each_id in each_record.all_entry_ids:
115
+ offset_by_id[each_id] = min(
116
+ offset_by_id.get(each_id, each_record.transcript_offset),
117
+ each_record.transcript_offset,
118
+ )
119
+ return offset_by_id
120
+
121
+
122
+ def _card_offset_by_id(
123
+ all_unasked_entries: list[LedgerEntry],
124
+ all_records: list[QuestionRecord],
125
+ all_calls: list[TranscriptCall],
126
+ all_used_card_offsets: set[int | None],
127
+ ) -> dict[str, int]:
128
+ record_offset_by_id = _earliest_record_offset_by_id(all_records)
129
+ card_offset_by_id: dict[str, int] = {}
130
+ for each_call in all_calls:
131
+ if each_call.call_offset in all_used_card_offsets:
132
+ continue
133
+ for each_group in auto_mode_refusal_ledger.question_groups(
134
+ [each for each in all_unasked_entries if each.entry_id not in card_offset_by_id]
135
+ ):
136
+ all_card_ids = [
137
+ each_id
138
+ for each_id in each_group.all_entry_ids
139
+ if each_id in record_offset_by_id
140
+ and record_offset_by_id[each_id] <= each_call.call_offset
141
+ ]
142
+ if all_card_ids and _is_card_for(each_call, each_group.tool_name):
143
+ card_offset_by_id.update(dict.fromkeys(all_card_ids, each_call.call_offset))
144
+ break
145
+ return card_offset_by_id
146
+
147
+
148
+ def _asked_entry_ids(
149
+ ledger_directory: Path,
150
+ all_entries: list[LedgerEntry],
151
+ all_asked: list[AskedQuestions],
152
+ all_calls: list[TranscriptCall],
153
+ ) -> dict[str, int | None]:
154
+ all_known_ids = {each.entry_id for each in all_entries}
155
+ all_records = auto_mode_refusal_ledger.load_question_records(ledger_directory)
156
+ card_offset_by_id: dict[str, int | None] = {
157
+ each_id: None
158
+ for each_record in all_records
159
+ if _is_text_asked(each_record, all_asked)
160
+ for each_id in each_record.all_entry_ids
161
+ if each_id in all_known_ids
162
+ }
163
+ all_unasked_entries = [
164
+ each
165
+ for each in all_entries
166
+ if each.answer is None
167
+ and not each.is_question_asked
168
+ and each.entry_id not in card_offset_by_id
169
+ ]
170
+ card_offset_by_id.update(
171
+ _card_offset_by_id(
172
+ all_unasked_entries,
173
+ all_records,
174
+ all_calls,
175
+ {each.question_card_offset for each in all_entries},
176
+ )
177
+ )
178
+ return card_offset_by_id
179
+
180
+
181
+ def _has_add_call(entry: LedgerEntry, all_calls: list[TranscriptCall]) -> bool:
182
+ for each_call in all_calls:
183
+ if each_call.tool_name != BASH_TOOL_NAME or each_call.is_error:
184
+ continue
185
+ command = (
186
+ each_call.tool_input.get(COMMAND_INPUT_KEY)
187
+ if isinstance(each_call.tool_input, dict)
188
+ else None
189
+ )
190
+ if (
191
+ isinstance(command, str)
192
+ and RULE_ADD_COMMAND_MARKER in command
193
+ and entry.entry_id in command
194
+ ):
195
+ return True
196
+ return False
197
+
198
+
199
+ def _could_hold(entry: LedgerEntry) -> bool:
200
+ if entry.answer is None:
201
+ return entry.question_holds < MAXIMUM_HOLDS_PER_KIND and not entry.is_question_asked
202
+ return entry.answer == ALLOWED_ANSWER and entry.rule_holds < MAXIMUM_HOLDS_PER_KIND
203
+
204
+
205
+ def _ledger_lines(ledger_directory: Path, all_entry_ids: list[str]) -> str:
206
+ return "".join(
207
+ LIST_LINE_TEMPLATE.format(text=entry_file_path(ledger_directory, each_id))
208
+ for each_id in all_entry_ids
209
+ )
210
+
211
+
212
+ def hold_reason_for(
213
+ all_groups: list[auto_mode_refusal_ledger.QuestionGroup],
214
+ all_rule_entry_ids: list[str],
215
+ ledger_directory: Path,
216
+ playbook_path: Path,
217
+ ) -> str:
218
+ """Return the hold text for the questions to ask and the rules to add.
219
+
220
+ ::
221
+
222
+ one group, no rule entry -> header with the card question form,
223
+ "Question: ...", steps, the order after
224
+ Allow it, ledger files
225
+ no group, one rule entry -> the playbook path and the ledger file
226
+
227
+ Args:
228
+ all_groups: The question groups to ask, four at most.
229
+ all_rule_entry_ids: The allowed entries that still need a rule.
230
+ ledger_directory: One session's ledger folder.
231
+ playbook_path: The rule playbook the flow switch names.
232
+
233
+ Returns:
234
+ The question section, the rule section, or both.
235
+ """
236
+ all_sections: list[str] = []
237
+ if all_groups:
238
+ question_text = QUESTION_SECTION_HEADER
239
+ for each_group in all_groups:
240
+ question_text += QUESTION_BLOCK_TEMPLATE.format(question=each_group.question)
241
+ question_text += "".join(
242
+ LIST_LINE_TEMPLATE.format(text=each_summary)
243
+ for each_summary in each_group.all_action_summaries
244
+ )
245
+ question_text += QUESTION_SECTION_FOOTER_TEMPLATE.format(playbook_path=playbook_path)
246
+ question_text += _ledger_lines(
247
+ ledger_directory,
248
+ [each_id for each_group in all_groups for each_id in each_group.all_entry_ids],
249
+ )
250
+ all_sections.append(question_text)
251
+ if all_rule_entry_ids:
252
+ all_sections.append(
253
+ RULE_SECTION_HEADER_TEMPLATE.format(playbook_path=playbook_path)
254
+ + _ledger_lines(ledger_directory, all_rule_entry_ids)
255
+ )
256
+ return SECTION_SEPARATOR.join(all_sections)
257
+
258
+
259
+ def _flow_folders(all_stop_fields: dict[str, object]) -> tuple[Path, Path] | None:
260
+ if os.environ.get(ENTRYPOINT_ENVIRONMENT_VARIABLE) == PRINT_MODE_ENTRYPOINT:
261
+ return None
262
+ playbook_path = auto_mode_refusal_ledger.playbook_path_from_environment()
263
+ session_id = all_stop_fields.get("session_id")
264
+ if playbook_path is None or not isinstance(session_id, str) or not session_id:
265
+ return None
266
+ ledger_directory = auto_mode_refusal_ledger.ledger_directory_for(session_id)
267
+ if not ledger_directory.is_dir():
268
+ return None
269
+ return playbook_path, ledger_directory
270
+
271
+
272
+ def _counted_fields(
273
+ all_entries: list[LedgerEntry],
274
+ all_card_offset_by_asked_id: dict[str, int | None],
275
+ all_groups: list[auto_mode_refusal_ledger.QuestionGroup],
276
+ all_rule_entries: list[LedgerEntry],
277
+ ) -> dict[str, JsonObject]:
278
+ entry_by_id = {each.entry_id: each for each in all_entries}
279
+ fields_by_entry_id: dict[str, JsonObject] = {
280
+ each.entry_id: {QUESTION_ASKED_FIELD: True}
281
+ for each in all_entries
282
+ if each.entry_id in all_card_offset_by_asked_id and not each.is_question_asked
283
+ }
284
+ for each_id, each_card_offset in all_card_offset_by_asked_id.items():
285
+ if each_card_offset is not None:
286
+ fields_by_entry_id[each_id][QUESTION_CARD_OFFSET_FIELD] = each_card_offset
287
+ for each_id in (each for each_group in all_groups for each in each_group.all_entry_ids):
288
+ fields_by_entry_id.setdefault(each_id, {})[QUESTION_HOLDS_FIELD] = (
289
+ entry_by_id[each_id].question_holds + 1
290
+ )
291
+ for each_entry in all_rule_entries:
292
+ fields_by_entry_id.setdefault(each_entry.entry_id, {})[RULE_HOLDS_FIELD] = (
293
+ each_entry.rule_holds + 1
294
+ )
295
+ return fields_by_entry_id
296
+
297
+
298
+ def _entries_to_hold(
299
+ all_entries: list[LedgerEntry],
300
+ all_asked_ids: dict[str, int | None],
301
+ all_calls: list[TranscriptCall],
302
+ ) -> tuple[list[auto_mode_refusal_ledger.QuestionGroup], list[LedgerEntry]]:
303
+ all_groups = auto_mode_refusal_ledger.question_groups(
304
+ [
305
+ each
306
+ for each in all_entries
307
+ if each.answer is None and _could_hold(each) and each.entry_id not in all_asked_ids
308
+ ]
309
+ )[:MAXIMUM_QUESTIONS_PER_HOLD]
310
+ all_rule_entries = [
311
+ each
312
+ for each in all_entries
313
+ if each.answer == ALLOWED_ANSWER and _could_hold(each) and not _has_add_call(each, all_calls)
314
+ ]
315
+ return all_groups, all_rule_entries
316
+
317
+
318
+ def hold_reason_for_stop(all_stop_fields: dict[str, object]) -> str | None:
319
+ """Return the hold text for one Stop payload, and record the hold in the ledger.
320
+
321
+ Args:
322
+ all_stop_fields: The Stop hook input JSON.
323
+
324
+ Returns:
325
+ The hold text, or None to let the turn end.
326
+ """
327
+ flow_folders = _flow_folders(all_stop_fields)
328
+ if flow_folders is None:
329
+ return None
330
+ playbook_path, ledger_directory = flow_folders
331
+ raw_transcript_path = all_stop_fields.get("transcript_path")
332
+ transcript_path = Path(raw_transcript_path) if isinstance(raw_transcript_path, str) else None
333
+ all_entries = auto_mode_refusal_ledger.load_entries(ledger_directory)
334
+ if not any(each.answer is None or _could_hold(each) for each in all_entries):
335
+ return None
336
+ transcript_reading = read_transcript(transcript_path)
337
+ auto_mode_refusal_ledger.apply_asked_answers(ledger_directory, transcript_reading.all_asked)
338
+ all_entries = auto_mode_refusal_ledger.load_entries(ledger_directory)
339
+ if not any(_could_hold(each) for each in all_entries):
340
+ return None
341
+ all_calls = transcript_reading.all_calls
342
+ all_asked_ids = _asked_entry_ids(
343
+ ledger_directory, all_entries, transcript_reading.all_asked, all_calls
344
+ )
345
+ all_groups, all_rule_entries = _entries_to_hold(all_entries, all_asked_ids, all_calls)
346
+ if all_groups:
347
+ auto_mode_refusal_ledger.write_question_records(
348
+ ledger_directory, all_groups, transcript_path
349
+ )
350
+ auto_mode_refusal_ledger.merge_entry_fields(
351
+ ledger_directory, _counted_fields(all_entries, all_asked_ids, all_groups, all_rule_entries)
352
+ )
353
+ if not all_groups and not all_rule_entries:
354
+ return None
355
+ return hold_reason_for(
356
+ all_groups, [each.entry_id for each in all_rule_entries], ledger_directory, playbook_path
357
+ )
358
+
359
+
360
+ def main() -> int:
361
+ try:
362
+ payload = json.load(sys.stdin)
363
+ except (json.JSONDecodeError, ValueError):
364
+ return ALLOW_EXIT_CODE
365
+ if not isinstance(payload, dict):
366
+ return ALLOW_EXIT_CODE
367
+ try:
368
+ hold_reason = hold_reason_for_stop(payload)
369
+ except Exception:
370
+ return ALLOW_EXIT_CODE
371
+ if hold_reason is None:
372
+ return ALLOW_EXIT_CODE
373
+ log_hook_block(Path(__file__).name, STOP_EVENT_NAME, hold_reason)
374
+ try:
375
+ exit_code = hold_stop(payload, hold_reason)
376
+ sys.stdout.flush()
377
+ except OSError:
378
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
379
+ return ALLOW_EXIT_CODE
380
+ return exit_code
381
+
382
+
383
+ if __name__ == "__main__":
384
+ raise SystemExit(main())
@@ -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()