@ethlete/agent-rules 0.1.0-next.2 → 0.1.0-next.21

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 (178) hide show
  1. package/CHANGELOG.md +275 -0
  2. package/README.md +350 -29
  3. package/THIRD-PARTY-LICENSES.md +35 -0
  4. package/content/git-hooks/post-checkout.sh +10 -0
  5. package/content/git-hooks/pre-push.sh +5 -0
  6. package/content/hooks/context-warning.py +766 -108
  7. package/content/hooks/subagent-model-policy.py +193 -0
  8. package/content/output-styles/ste-clarity.md +131 -0
  9. package/content/rules/app-styling.md +59 -0
  10. package/content/rules/comments.md +53 -20
  11. package/content/rules/lint-and-format.md +6 -5
  12. package/content/rules/nx-layout.md +47 -0
  13. package/content/rules/reactive-state.md +1 -1
  14. package/content/rules/styling.md +9 -7
  15. package/content/rules/subagent-models.md +29 -0
  16. package/content/skills/angular-patterns/SKILL.md +30 -7
  17. package/content/skills/api-source/SKILL.md +130 -0
  18. package/content/skills/app-testing/SKILL.md +141 -0
  19. package/content/skills/codex-subagent/SKILL.md +90 -0
  20. package/content/skills/codex-subagent/codex-agent.mjs +229 -0
  21. package/content/skills/design-exploration/SKILL.md +205 -0
  22. package/content/skills/design-exploration/check-story.mjs +139 -0
  23. package/content/skills/design-exploration/shoot-template.mjs +61 -0
  24. package/content/skills/domain-modeling/ADR-FORMAT.md +47 -0
  25. package/content/skills/domain-modeling/CONTEXT-FORMAT.md +60 -0
  26. package/content/skills/domain-modeling/SKILL.md +80 -0
  27. package/content/skills/figma-export/SKILL.md +191 -0
  28. package/content/skills/figma-export/dump-figma-layers.py +83 -0
  29. package/content/skills/figma-export/dump-figma-svg.py +235 -0
  30. package/content/skills/figma-export/measure-template.mjs +87 -0
  31. package/content/skills/git-commit/SKILL.md +6 -7
  32. package/content/skills/git-flow/SKILL.md +87 -0
  33. package/content/skills/grill-with-docs/SKILL.md +13 -0
  34. package/content/skills/grilling/SKILL.md +34 -0
  35. package/content/skills/handoff/SKILL.md +74 -4
  36. package/content/skills/query/SKILL.md +165 -64
  37. package/content/skills/rxjs-signals/SKILL.md +31 -4
  38. package/content/skills/sdk-docs/SKILL.md +50 -14
  39. package/content/skills/sdk-local-build/SKILL.md +30 -10
  40. package/content/skills/sdk-local-build/sdk-local-baseline.mjs +64 -0
  41. package/content/skills/sdk-source/SKILL.md +49 -21
  42. package/content/skills/sdk-update/SKILL.md +96 -0
  43. package/content/skills/story-styling/SKILL.md +10 -8
  44. package/content/skills/styleguide/SKILL.md +12 -7
  45. package/content/skills/styleguide/assets.md +54 -0
  46. package/content/skills/styleguide/changesets.md +17 -0
  47. package/content/skills/styleguide/file-structure.md +73 -0
  48. package/content/skills/styleguide/lint-rule-lookup.md +51 -0
  49. package/content/skills/styleguide/storybook-structure.md +25 -0
  50. package/content/skills/theming/SKILL.md +41 -28
  51. package/content/skills/timetrack/SKILL.md +397 -0
  52. package/content/skills/verify-in-app/SKILL.md +107 -0
  53. package/migrations/app-styling-utilities.md +63 -0
  54. package/migrations/list-state-query-form.md +20 -0
  55. package/migrations/nx-layout.md +29 -0
  56. package/migrations/sdk-components-over-hand-built-ui.md +27 -0
  57. package/migrations/search-query-field.md +52 -0
  58. package/migrations.json +48 -0
  59. package/package.json +16 -2
  60. package/src/index.js +63 -28
  61. package/src/index.js.map +1 -1
  62. package/src/lib/cli-args.d.ts +9 -0
  63. package/src/lib/cli-args.js +48 -0
  64. package/src/lib/cli-args.js.map +1 -0
  65. package/src/lib/commitlint.d.ts +10 -0
  66. package/src/lib/commitlint.js +51 -0
  67. package/src/lib/commitlint.js.map +1 -0
  68. package/src/lib/config.d.ts +38 -4
  69. package/src/lib/config.js +84 -8
  70. package/src/lib/config.js.map +1 -1
  71. package/src/lib/filter.d.ts +2 -0
  72. package/src/lib/filter.js +4 -4
  73. package/src/lib/filter.js.map +1 -1
  74. package/src/lib/frontmatter.d.ts +2 -0
  75. package/src/lib/frontmatter.js +33 -5
  76. package/src/lib/frontmatter.js.map +1 -1
  77. package/src/lib/git-flow/build.d.ts +35 -0
  78. package/src/lib/git-flow/build.js +24 -0
  79. package/src/lib/git-flow/build.js.map +1 -0
  80. package/src/lib/git-flow/config.d.ts +59 -0
  81. package/src/lib/git-flow/config.js +50 -0
  82. package/src/lib/git-flow/config.js.map +1 -0
  83. package/src/lib/git-flow/index.d.ts +6 -0
  84. package/src/lib/git-flow/index.js +10 -0
  85. package/src/lib/git-flow/index.js.map +1 -0
  86. package/src/lib/git-flow/parse.d.ts +49 -0
  87. package/src/lib/git-flow/parse.js +300 -0
  88. package/src/lib/git-flow/parse.js.map +1 -0
  89. package/src/lib/git-flow/rename.d.ts +24 -0
  90. package/src/lib/git-flow/rename.js +70 -0
  91. package/src/lib/git-flow/rename.js.map +1 -0
  92. package/src/lib/git-flow/start.d.ts +49 -0
  93. package/src/lib/git-flow/start.js +57 -0
  94. package/src/lib/git-flow/start.js.map +1 -0
  95. package/src/lib/git-flow/validate.d.ts +34 -0
  96. package/src/lib/git-flow/validate.js +72 -0
  97. package/src/lib/git-flow/validate.js.map +1 -0
  98. package/src/lib/git-flow-command.d.ts +4 -0
  99. package/src/lib/git-flow-command.js +157 -0
  100. package/src/lib/git-flow-command.js.map +1 -0
  101. package/src/lib/git-flow-repair.d.ts +17 -0
  102. package/src/lib/git-flow-repair.js +157 -0
  103. package/src/lib/git-flow-repair.js.map +1 -0
  104. package/src/lib/git-flow-start.d.ts +20 -0
  105. package/src/lib/git-flow-start.js +132 -0
  106. package/src/lib/git-flow-start.js.map +1 -0
  107. package/src/lib/git.d.ts +64 -0
  108. package/src/lib/git.js +131 -0
  109. package/src/lib/git.js.map +1 -0
  110. package/src/lib/gitlab.d.ts +35 -0
  111. package/src/lib/gitlab.js +108 -0
  112. package/src/lib/gitlab.js.map +1 -0
  113. package/src/lib/index.d.ts +2 -0
  114. package/src/lib/index.js +2 -0
  115. package/src/lib/index.js.map +1 -1
  116. package/src/lib/migrate.js +1 -1
  117. package/src/lib/migrate.js.map +1 -1
  118. package/src/lib/output-style-command.d.ts +3 -0
  119. package/src/lib/output-style-command.js +69 -0
  120. package/src/lib/output-style-command.js.map +1 -0
  121. package/src/lib/output-style.d.ts +38 -0
  122. package/src/lib/output-style.js +134 -0
  123. package/src/lib/output-style.js.map +1 -0
  124. package/src/lib/owned-paths.js +27 -3
  125. package/src/lib/owned-paths.js.map +1 -1
  126. package/src/lib/package-runner.d.ts +3 -0
  127. package/src/lib/package-runner.js +69 -0
  128. package/src/lib/package-runner.js.map +1 -0
  129. package/src/lib/plain-text.d.ts +9 -0
  130. package/src/lib/plain-text.js +22 -0
  131. package/src/lib/plain-text.js.map +1 -0
  132. package/src/lib/plan.d.ts +6 -6
  133. package/src/lib/plan.js +147 -40
  134. package/src/lib/plan.js.map +1 -1
  135. package/src/lib/prompt.d.ts +8 -0
  136. package/src/lib/prompt.js +27 -0
  137. package/src/lib/prompt.js.map +1 -0
  138. package/src/lib/render.d.ts +24 -2
  139. package/src/lib/render.js +39 -10
  140. package/src/lib/render.js.map +1 -1
  141. package/src/lib/sync.d.ts +0 -1
  142. package/src/lib/sync.js +23 -15
  143. package/src/lib/sync.js.map +1 -1
  144. package/src/lib/targets/agents-skills.js +1 -1
  145. package/src/lib/targets/agents-skills.js.map +1 -1
  146. package/src/lib/targets/claude-hooks.d.ts +1 -23
  147. package/src/lib/targets/claude-hooks.js +17 -85
  148. package/src/lib/targets/claude-hooks.js.map +1 -1
  149. package/src/lib/targets/claude.js +1 -2
  150. package/src/lib/targets/claude.js.map +1 -1
  151. package/src/lib/targets/codex-hooks.d.ts +12 -0
  152. package/src/lib/targets/codex-hooks.js +34 -0
  153. package/src/lib/targets/codex-hooks.js.map +1 -0
  154. package/src/lib/targets/codex.js +4 -4
  155. package/src/lib/targets/codex.js.map +1 -1
  156. package/src/lib/targets/copilot.js +3 -3
  157. package/src/lib/targets/copilot.js.map +1 -1
  158. package/src/lib/targets/cursor.js +2 -2
  159. package/src/lib/targets/cursor.js.map +1 -1
  160. package/src/lib/targets/git-hooks.d.ts +24 -0
  161. package/src/lib/targets/git-hooks.js +71 -0
  162. package/src/lib/targets/git-hooks.js.map +1 -0
  163. package/src/lib/targets/hooks-shared.d.ts +58 -0
  164. package/src/lib/targets/hooks-shared.js +128 -0
  165. package/src/lib/targets/hooks-shared.js.map +1 -0
  166. package/src/lib/targets/shared.d.ts +1 -9
  167. package/src/lib/targets/shared.js +4 -8
  168. package/src/lib/targets/shared.js.map +1 -1
  169. package/src/lib/timetrack-command.d.ts +11 -0
  170. package/src/lib/timetrack-command.js +1055 -0
  171. package/src/lib/timetrack-command.js.map +1 -0
  172. package/src/lib/timetrack-snapshot.d.ts +55 -0
  173. package/src/lib/timetrack-snapshot.js +120 -0
  174. package/src/lib/timetrack-snapshot.js.map +1 -0
  175. package/src/lib/timetrack.d.ts +561 -0
  176. package/src/lib/timetrack.js +271 -0
  177. package/src/lib/timetrack.js.map +1 -0
  178. package/content/skills/styleguide/STYLEGUIDE.md +0 -520
@@ -1,43 +1,143 @@
1
1
  #!/usr/bin/env python3
2
- """UserPromptSubmit hook: warn when the context window is getting large.
2
+ """Context-budget hook: keep the agent aware of how much context it may still spend.
3
3
 
4
4
  Reads the hook input JSON from stdin, estimates the current context size from
5
- the last main-chain assistant message in the session transcript, and emits a
6
- warning (visible to both the user and Claude) when it crosses a threshold.
7
- Recommends the /handoff skill so work can continue in a fresh session.
5
+ the session transcript, and emits a warning (visible to both the user and the
6
+ agent) when it crosses a threshold. Recommends the handoff skill so work can
7
+ continue in a fresh session.
8
8
 
9
- The thresholds are fractions of a token budget, and the budget is capped at the
10
- 200k long-context pricing boundary: on models with a larger window, every
11
- request past that point bills the entire context at the premium rate, which
12
- costs far more than handing off into a fresh session ever would.
9
+ Registered on four events, because a warning the agent cannot see while it works
10
+ is not a warning:
11
+
12
+ * SessionStart - states the budget and how to scope work to it, before the
13
+ first request. Nothing else tells the model what its budget is.
14
+ * UserPromptSubmit - the tiered warning, plus a short reminder on every later
15
+ prompt.
16
+ * PostToolBatch - the same tiered warning, delivered mid-run. This is the only
17
+ event that fires between an agent's own model requests, so without it a long
18
+ autonomous run never learns its token count until the user types something.
19
+ * Stop - fires as the agent tries to end its turn. Its additionalContext is
20
+ delivered to the model and the conversation continues, so the decision to
21
+ finish or hand off happens without the user having to ask for it.
22
+
23
+ Runs under both Claude Code and Codex, selected by `--agent` on the command
24
+ line rather than sniffed from the payload - the generator writes the flag, so
25
+ the two never have to be told apart at runtime. Codex has only UserPromptSubmit;
26
+ the other three events are registered for Claude alone. The two differ in three
27
+ ways that matter here, all captured in AGENT_PROFILES:
28
+
29
+ * Transcript format. Claude writes one JSON object per message with
30
+ `message.usage`; Codex writes a rollout stream whose `token_count` events
31
+ carry a TokenUsageInfo. Codex's rollout format is explicitly not a stable
32
+ interface, so the parser searches each line for the usage object instead of
33
+ walking a fixed path.
34
+ * Sub-agents. Codex gives each sub-agent its own rollout and thread id while
35
+ retaining the root session id. Warnings identify that thread explicitly and
36
+ tell it to report back to its parent instead of making the main agent hand
37
+ off its session.
38
+ * Context budget. Claude's budget is capped at its 200k long-context pricing
39
+ boundary. Codex uses the model-specific pricing boundary where OpenAI
40
+ documents one, and the reported window otherwise. Crossing either boundary
41
+ costs far more than handing off into a fresh session ever would.
42
+ * How a handoff is invoked. Claude has a slash command and /clear; Codex has
43
+ neither and reads the skill from disk. The skill's own name differs per repo
44
+ (`ethlete-handoff` where the generator installed it, `handoff` where the repo
45
+ ships its own copy), so it is resolved at runtime - see handoff_skill().
46
+
47
+ At the critical tier, if the session's permission_mode is "auto", the
48
+ instruction escalates from "recommend" to "just do it": auto mode already
49
+ means the user wants the agent acting without stopping to ask, and clearing +
50
+ resuming can't be triggered programmatically (no hook or tool can submit
51
+ input to a running session), so the best available automation is to save the
52
+ handoff file itself immediately rather than waiting for a natural stopping
53
+ point. Codex's permission_mode value set is undocumented, so its profile lists
54
+ no auto modes and the escalation stays off there.
55
+
56
+ Neither the critical tier nor the Stop event forces a handoff. A session is
57
+ often a step or two from done when they fire, and some sessions hold reasoning
58
+ that no handoff file survives - crossing the boundary is then the cheaper
59
+ choice. So the Stop event offers three options and demands the agent name the
60
+ one it took: finish, hand off, or continue past the boundary for a reason it
61
+ states in one sentence. A third tier at 95% withdraws only the "finish" option,
62
+ because a budget that small covers no task.
63
+
64
+ Goes quiet while a handoff is being saved: from a prompt that requests save mode, or the
65
+ auto-mode save this hook ordered, until the next prompt; and for the rest of a turn in
66
+ which the agent invoked the handoff skill or wrote a handoff file. A save that is told to
67
+ choose between finishing and handing off again never ends. `resume` is not a save.
13
68
 
14
69
  Warns once per tier per session (state kept in a temp file); re-arms itself
15
- if the context shrinks again (e.g. after /compact).
70
+ if the context shrinks again (e.g. after a compaction). The Stop event keeps its
71
+ own per-tier counter, so crossing a tier mid-run costs at most one notice while
72
+ working and one demand at the end of the turn. Every prompt after the first
73
+ warning carries a short reminder instead: how much budget is left, and how to
74
+ work so that either ending stays cheap. One warning at 70% is stale by the time
75
+ it matters, and the agent cannot see its own token count.
16
76
 
17
77
  Can be disabled per machine via a gitignored ethlete-agents.config.local.json
18
78
  at the repo root: {"disableHooks": true} or {"disableHooks": ["context-warning"]}.
79
+ To keep the tiered warnings but drop just the auto-mode auto-save escalation,
80
+ use {"disableAutoHandoffSave": true} instead - the critical tier then falls
81
+ back to recommending a handoff, same as non-auto mode.
19
82
 
20
- Fail-safe: any error exits 0 with no output — the hook must never block a prompt.
83
+ Fail-safe: any error exits 0 with no output - the hook must never block a prompt,
84
+ a tool batch or the end of a turn.
21
85
  """
22
86
 
23
87
  import json
24
88
  import os
89
+ import re
25
90
  import sys
26
91
  import tempfile
27
92
 
28
93
  HOOK_NAME = "context-warning"
29
94
  LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
30
95
 
31
- # Warn / critical fire at these fractions of the token budget.
96
+ # Warn / critical / final fire at these fractions of the token budget.
32
97
  WARN_FRACTION = 0.70
33
98
  CRITICAL_FRACTION = 0.85
99
+ FINAL_FRACTION = 0.95
100
+
101
+ # How to work once the budget is tight - repeated on every prompt from the first
102
+ # warning on, so it stays in view as the budget shrinks.
103
+ HANDOFF_MODE = (
104
+ "Work in slices that each end in a committable state. Send bulky reads, searches and "
105
+ "test runs to a sub-agent so their output stays out of this context. Write down each "
106
+ "decision and dead end as you reach it, in the commit message or the handoff file. "
107
+ "Start nothing you cannot finish or hand off inside the remaining budget."
108
+ )
109
+
110
+ # Said once at session start, before anything has been read - the only point at which the
111
+ # scope of the whole session is still open.
112
+ SESSION_BUDGET = (
113
+ "Scope the session to it. Send bulky reads, searches and test runs to a sub-agent so "
114
+ "their output never enters this context. Commit in slices. A task that plainly does not "
115
+ "fit should be split now, not abandoned at 90%."
116
+ )
117
+
118
+ # The escape from a handoff at the critical tier, with the test that keeps it honest.
119
+ FINISH_FIRST = (
120
+ "If you can name every step that is left, and they plainly fit the remaining budget, "
121
+ "finish the task, commit, and then apply the handoff skill's own save test - with "
122
+ "everything committed and no step left, write no handoff file and say so instead. "
123
+ "\"Nearly done\" means you can name the last steps now, not that the end feels close."
124
+ )
34
125
 
35
126
  # On models with a window larger than this, tokens beyond it bill the whole
36
- # context at the long-context premium rate — so the budget never exceeds it.
127
+ # context at the long-context premium rate - so the budget never exceeds it.
37
128
  PREMIUM_BOUNDARY = 200_000
38
129
 
130
+ # Codex models whose long-context pricing starts above 272k input tokens. Models
131
+ # without that pricing rule use their reported context window instead.
132
+ CODEX_PREMIUM_BOUNDARIES = (
133
+ ("gpt-5.6", 272_000),
134
+ ("gpt-5.5", 272_000),
135
+ ("gpt-5.4-mini", None),
136
+ ("gpt-5.4", 272_000),
137
+ )
138
+
39
139
  # Context window (tokens) per model, matched by substring against the model id
40
- # from the transcript — first match wins. Edit these as model windows change;
140
+ # from the transcript - first match wins. Edit these as model windows change;
41
141
  # anything unmatched falls back to DEFAULT_WINDOW.
42
142
  CONTEXT_WINDOWS = (
43
143
  ("opus-5", 1_000_000),
@@ -45,7 +145,7 @@ CONTEXT_WINDOWS = (
45
145
  ("sonnet-4-5", 1_000_000),
46
146
  ("sonnet-5", 1_000_000),
47
147
  ("fable-5", 1_000_000),
48
- # Generic fallbacks — keep these last: the first substring match wins, so a bare
148
+ # Generic fallbacks - keep these last: the first substring match wins, so a bare
49
149
  # "opus"/"sonnet" entry placed above would shadow every versioned entry below it.
50
150
  ("opus", 200_000),
51
151
  ("sonnet", 200_000),
@@ -53,20 +153,151 @@ CONTEXT_WINDOWS = (
53
153
  )
54
154
  DEFAULT_WINDOW = 200_000
55
155
 
156
+ # Bytes read from the end of a Claude transcript to find the newest usage report. Read on
157
+ # every tool batch, so a full parse of a multi-megabyte transcript would add latency to
158
+ # every model request. Grows by GROWTH_FACTOR until a usage report is found.
159
+ TAIL_BYTES = 256 * 1024
160
+ MAX_TAIL_BYTES = 16 * 1024 * 1024
161
+ GROWTH_FACTOR = 8
56
162
 
57
- def disabled_locally():
58
- """True when the local config disables this hook (or all hooks) on this machine."""
59
- root = os.environ.get("CLAUDE_PROJECT_DIR")
163
+ AGENT_PROFILES = {
164
+ "claude": {
165
+ "premium_boundary": PREMIUM_BOUNDARY,
166
+ "premium_boundaries": (),
167
+ # Claude's transcript reports no window, so it is resolved from the model id.
168
+ "default_window": None,
169
+ "auto_modes": ("auto",),
170
+ "emits_system_message": True,
171
+ "act_now": "Run /{handoff} now and continue in a fresh session.",
172
+ "act_later": "consider /{handoff} to continue in a fresh session",
173
+ "recommend": "recommend the user run /{handoff} to save state and start a fresh session",
174
+ "suggest": "suggest the user run /{handoff} to save state and start a fresh session",
175
+ "save_now": (
176
+ "run the handoff skill's save mode right now - finish only an in-flight atomic "
177
+ "edit first, nothing new. Apply its own test: with every change committed, no "
178
+ "step left and nothing running, write no file, say that instead, and recommend "
179
+ "/clear. If a file is warranted, tell the user exactly which one was written and "
180
+ "that they should run /clear, then '/{handoff} resume <slug>', to continue - "
181
+ "clearing and resuming can't be done programmatically, so this is the one step "
182
+ "still on them."
183
+ ),
184
+ "save_at_stop": (
185
+ "save a handoff with the handoff skill, then tell the user which file was "
186
+ "written and that they should run /clear, then '/{handoff} resume <slug>'"
187
+ ),
188
+ },
189
+ "codex": {
190
+ "premium_boundary": None,
191
+ "premium_boundaries": CODEX_PREMIUM_BOUNDARIES,
192
+ # Only reached if a rollout omits model_context_window; the CONTEXT_WINDOWS table
193
+ # holds Claude model ids and would never match a Codex one.
194
+ "default_window": 272_000,
195
+ # Codex's permission_mode values are undocumented; until one is confirmed to mean
196
+ # "never ask", no value enables the auto-save escalation.
197
+ "auto_modes": (),
198
+ # Only hookSpecificOutput.additionalContext is documented for Codex, so the
199
+ # user-facing line is folded into the model-facing text instead.
200
+ "emits_system_message": False,
201
+ "act_now": "Save a handoff now and continue in a fresh session.",
202
+ "act_later": "consider saving a handoff and continuing in a fresh session",
203
+ "recommend": (
204
+ "tell the user you are near the context limit, then follow "
205
+ ".agents/skills/{handoff}/SKILL.md to save a handoff and have them start a "
206
+ "fresh session"
207
+ ),
208
+ "suggest": (
209
+ "suggest saving a handoff via .agents/skills/{handoff}/SKILL.md and "
210
+ "continuing in a fresh session"
211
+ ),
212
+ "save_now": (
213
+ "follow .agents/skills/{handoff}/SKILL.md and save a handoff right now - finish "
214
+ "only an in-flight atomic edit first, nothing new. Apply its own test: with "
215
+ "every change committed, no step left and nothing running, write no file and say "
216
+ "that instead. If a file is warranted, tell the user exactly which one was "
217
+ "written and that they should start a fresh codex session and resume from it."
218
+ ),
219
+ "save_at_stop": (
220
+ "save a handoff via .agents/skills/{handoff}/SKILL.md, then tell the user which "
221
+ "file was written and that a fresh session should resume from it"
222
+ ),
223
+ },
224
+ }
225
+
226
+
227
+ def handoff_skill(root):
228
+ """Name of the handoff skill installed in this repo.
229
+
230
+ The generator prefixes every skill it writes, so the command is /ethlete-handoff in a
231
+ consumer repo - but a repo that excludes the generated copy and ships its own (the SDK
232
+ itself) has a plain /handoff instead. Naming the wrong one sends the user to a slash
233
+ command that does not exist, so it is read off disk rather than assumed.
234
+ """
235
+ for name in ("ethlete-handoff", "handoff"):
236
+ for skills_dir in (".claude/skills", ".agents/skills"):
237
+ if os.path.isdir(os.path.join(root or ".", skills_dir, name)):
238
+ return name
239
+ return "ethlete-handoff"
240
+
241
+
242
+ def resolve_profile(profile, skill):
243
+ """Fills the installed handoff skill's name into a profile's message fragments."""
244
+ return {
245
+ key: value.replace("{handoff}", skill) if isinstance(value, str) else value
246
+ for key, value in profile.items()
247
+ }
248
+
249
+
250
+ def agent_name(argv):
251
+ """The --agent value, defaulting to claude - older registrations pass no flag."""
252
+ for index, arg in enumerate(argv):
253
+ if arg == "--agent" and index + 1 < len(argv):
254
+ return argv[index + 1]
255
+ if arg.startswith("--agent="):
256
+ return arg.split("=", 1)[1]
257
+ return "claude"
258
+
259
+
260
+ def repo_root(data):
261
+ """Repo root: the env var the agent sets, else derived from this script's own location.
262
+
263
+ The script always lives at <root>/.<agent>/hooks/ethlete/context-warning.py, so walking
264
+ four levels up works for any agent that has no project-dir variable of its own.
265
+ """
266
+ for variable in ("CLAUDE_PROJECT_DIR", "CODEX_PROJECT_DIR"):
267
+ value = os.environ.get(variable)
268
+ if value:
269
+ return value
270
+ here = os.path.abspath(__file__)
271
+ derived = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(here))))
272
+ if os.path.isfile(os.path.join(derived, LOCAL_CONFIG_FILE)):
273
+ return derived
274
+ cwd = data.get("cwd")
275
+ return cwd if isinstance(cwd, str) and cwd else derived
276
+
277
+
278
+ def load_local_config(root):
279
+ """Parsed ethlete-agents.config.local.json at the repo root, or {} if missing/unreadable."""
60
280
  if not root:
61
- return False
281
+ return {}
62
282
  try:
63
283
  with open(os.path.join(root, LOCAL_CONFIG_FILE), encoding="utf-8") as f:
64
- disabled = json.load(f).get("disableHooks")
284
+ config = json.load(f)
65
285
  except (OSError, ValueError, AttributeError):
66
- return False
286
+ return {}
287
+ return config if isinstance(config, dict) else {}
288
+
289
+
290
+ def disabled_locally(config):
291
+ """True when the local config disables this hook (or all hooks) on this machine."""
292
+ disabled = config.get("disableHooks")
67
293
  return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
68
294
 
69
295
 
296
+ def auto_handoff_save_disabled(config):
297
+ """True when the local config opts out of the auto-mode critical-tier auto-save."""
298
+ return config.get("disableAutoHandoffSave") is True
299
+
300
+
70
301
  def window_for(model):
71
302
  """Context window for a model id, by first substring match; DEFAULT_WINDOW otherwise."""
72
303
  if model:
@@ -76,135 +307,562 @@ def window_for(model):
76
307
  return DEFAULT_WINDOW
77
308
 
78
309
 
79
- def context_state(transcript_path):
80
- """(tokens, model) from the last main-chain assistant message.
310
+ def premium_boundary_for(profile, model):
311
+ """Model-specific pricing boundary, falling back to the agent-wide value."""
312
+ if model:
313
+ for needle, boundary in profile["premium_boundaries"]:
314
+ if needle in model:
315
+ return boundary
316
+ return profile["premium_boundary"]
317
+
318
+
319
+ def tail_lines(path, limit):
320
+ """(lines newest-first, whole file read) for the last `limit` bytes of a file.
81
321
 
82
- tokens ≈ its total input tokens (fresh + cache read + cache creation).
322
+ A partial first line is dropped, so every returned line is complete.
83
323
  """
84
- last_usage = None
324
+ size = os.path.getsize(path)
325
+ start = max(size - limit, 0)
326
+ with open(path, "rb") as f:
327
+ f.seek(start)
328
+ chunk = f.read()
329
+ if start > 0:
330
+ newline = chunk.find(b"\n")
331
+ chunk = chunk[newline + 1 :] if newline != -1 else b""
332
+ return list(reversed(chunk.split(b"\n"))), start == 0
333
+
334
+
335
+ def claude_usage_in(lines):
336
+ """(usage, model) from the newest main-chain assistant message in `lines`, or (None, None)."""
337
+ for line in lines:
338
+ if not line.strip():
339
+ continue
340
+ try:
341
+ obj = json.loads(line)
342
+ except (json.JSONDecodeError, UnicodeDecodeError):
343
+ continue
344
+ if obj.get("type") != "assistant" or obj.get("isSidechain"):
345
+ continue
346
+ message = obj.get("message") or {}
347
+ usage = message.get("usage")
348
+ if usage:
349
+ return usage, message.get("model")
350
+ return None, None
351
+
352
+
353
+ def claude_context_state(transcript_path):
354
+ """(tokens, model, window, thread id, is sub-agent) from the main-chain assistant message.
355
+
356
+ tokens is its total input tokens (fresh + cache read + cache creation). Claude reports no
357
+ window in the transcript, so it is resolved from the model id by the caller. Only the tail
358
+ of the transcript is read, growing until a usage report is found - this runs on every tool
359
+ batch, and a transcript reaches tens of megabytes.
360
+ """
361
+ limit = TAIL_BYTES
362
+ while True:
363
+ lines, complete = tail_lines(transcript_path, limit)
364
+ usage, model = claude_usage_in(lines)
365
+ if usage:
366
+ tokens = (
367
+ usage.get("input_tokens", 0)
368
+ + usage.get("cache_read_input_tokens", 0)
369
+ + usage.get("cache_creation_input_tokens", 0)
370
+ )
371
+ return tokens, model, None, None, False
372
+ if complete or limit >= MAX_TAIL_BYTES:
373
+ return 0, None, None, None, False
374
+ limit *= GROWTH_FACTOR
375
+
376
+
377
+ def find_token_usage_info(node):
378
+ """The deepest TokenUsageInfo-shaped dict in a parsed rollout line, or None.
379
+
380
+ Codex documents its rollout format as unstable, so this searches for the shape
381
+ (a dict carrying `last_token_usage`) rather than walking a fixed key path.
382
+ """
383
+ if isinstance(node, dict):
384
+ if isinstance(node.get("last_token_usage"), dict):
385
+ return node
386
+ for value in node.values():
387
+ found = find_token_usage_info(value)
388
+ if found:
389
+ return found
390
+ elif isinstance(node, list):
391
+ for value in node:
392
+ found = find_token_usage_info(value)
393
+ if found:
394
+ return found
395
+ return None
396
+
397
+
398
+ def codex_context_state(transcript_path):
399
+ """(tokens, model, window, thread id, is sub-agent) from a Codex rollout.
400
+
401
+ tokens is the last request's `total_tokens` - Codex's own `tokens_in_context_window()`
402
+ is exactly that field, and `last_token_usage` is replaced per request while
403
+ `total_token_usage` accumulates across the whole session.
404
+ """
405
+ last_info = None
85
406
  last_model = None
407
+ thread_id = None
408
+ is_subagent = False
86
409
  with open(transcript_path, encoding="utf-8") as f:
87
410
  for line in f:
88
411
  try:
89
412
  obj = json.loads(line)
90
413
  except json.JSONDecodeError:
91
414
  continue
92
- if obj.get("type") != "assistant" or obj.get("isSidechain"):
93
- continue
94
- message = obj.get("message") or {}
95
- usage = message.get("usage")
96
- if usage:
97
- last_usage = usage
98
- last_model = message.get("model") or last_model
99
- if not last_usage:
100
- return 0, last_model
101
- tokens = (
102
- last_usage.get("input_tokens", 0)
103
- + last_usage.get("cache_read_input_tokens", 0)
104
- + last_usage.get("cache_creation_input_tokens", 0)
415
+ if obj.get("type") == "session_meta":
416
+ payload = obj.get("payload") or {}
417
+ source = payload.get("source")
418
+ thread_id = payload.get("id") or thread_id
419
+ is_subagent = payload.get("thread_source") == "subagent" or (
420
+ isinstance(source, dict) and isinstance(source.get("subagent"), dict)
421
+ )
422
+ model = (obj.get("payload") or {}).get("model") if isinstance(obj.get("payload"), dict) else None
423
+ if isinstance(model, str) and model:
424
+ last_model = model
425
+ info = find_token_usage_info(obj)
426
+ if info:
427
+ last_info = info
428
+ if not last_info:
429
+ return 0, last_model, None, thread_id, is_subagent
430
+ usage = last_info.get("last_token_usage") or {}
431
+ window = last_info.get("model_context_window")
432
+ return (
433
+ usage.get("total_tokens", 0),
434
+ last_model,
435
+ window if isinstance(window, int) else None,
436
+ thread_id,
437
+ is_subagent,
105
438
  )
106
- return tokens, last_model
107
439
 
108
440
 
109
- def messages(tier, tokens, budget, priced):
441
+ CONTEXT_READERS = {"claude": claude_context_state, "codex": codex_context_state}
442
+
443
+
444
+ HANDOFF_SKILLS = ("handoff", "ethlete-handoff")
445
+ COMMAND_PATTERN = re.compile(r"<command-name>/?([^<]*)</command-name>")
446
+ ARGS_PATTERN = re.compile(r"<command-args>([^<]*)</command-args>")
447
+
448
+
449
+ def is_handoff_save(skill, args):
450
+ return skill in HANDOFF_SKILLS and not (args or "").strip().lower().startswith("resume")
451
+
452
+
453
+ def handoff_save_requested(prompt):
454
+ """True for a prompt that runs the handoff skill in save mode - a slash command or a plain one."""
455
+ if not isinstance(prompt, str):
456
+ return False
457
+ command = COMMAND_PATTERN.search(prompt)
458
+ if command:
459
+ args = ARGS_PATTERN.search(prompt)
460
+ return is_handoff_save(command.group(1).strip(), args.group(1) if args else "")
461
+ words = prompt.strip().split(None, 1)
462
+ return bool(words) and is_handoff_save(words[0].lstrip("/").lower(), words[1] if len(words) > 1 else "")
463
+
464
+
465
+ def is_turn_start(obj):
466
+ if obj.get("type") != "user" or obj.get("isSidechain") or obj.get("isMeta"):
467
+ return False
468
+ origin = obj.get("origin")
469
+ if isinstance(origin, dict):
470
+ return origin.get("kind") == "human"
471
+ content = (obj.get("message") or {}).get("content")
472
+ return isinstance(content, str)
473
+
474
+
475
+ def starts_handoff(block):
476
+ if not isinstance(block, dict) or block.get("type") != "tool_use":
477
+ return False
478
+ tool_input = block.get("input") or {}
479
+ if block.get("name") == "Skill":
480
+ return is_handoff_save(tool_input.get("skill"), tool_input.get("args"))
481
+ path = tool_input.get("file_path")
482
+ return isinstance(path, str) and path.endswith(".md") and "handoffs" in path.replace("\\", "/").split("/")
483
+
484
+
485
+ def handoff_under_way_in_turn(transcript_path):
486
+ """True when the current Claude turn requested, invoked or wrote a handoff save."""
487
+ lines, _ = tail_lines(transcript_path, TAIL_BYTES)
488
+ for line in lines:
489
+ if not line.strip():
490
+ continue
491
+ try:
492
+ obj = json.loads(line)
493
+ except (json.JSONDecodeError, UnicodeDecodeError):
494
+ continue
495
+ if obj.get("isSidechain"):
496
+ continue
497
+ content = (obj.get("message") or {}).get("content")
498
+ if is_turn_start(obj):
499
+ return handoff_save_requested(content if isinstance(content, str) else None)
500
+ if obj.get("type") == "assistant" and isinstance(content, list) and any(map(starts_handoff, content)):
501
+ return True
502
+ return False
503
+
504
+
505
+ def headroom(tokens, budget):
506
+ """How much budget is left, as a short human string."""
507
+ left = max(budget - tokens, 0)
508
+ return f"~{left // 1000}k tokens" if left >= 1000 else "under 1k tokens"
509
+
510
+
511
+ def limit_name(priced):
512
+ return "long-context pricing boundary" if priced else "context window"
513
+
514
+
515
+ def cost_of_crossing(priced):
516
+ """What the user pays for one more token past the budget."""
517
+ if priced:
518
+ return "every later request is billed at the premium rate"
519
+ return "auto-compact fires and the detail of this session is summarised away"
520
+
521
+
522
+ def token_count(tokens):
523
+ """A token count as a short label: 1M rather than 1000k."""
524
+ if tokens >= 1_000_000 and tokens % 1_000_000 == 0:
525
+ return f"{tokens // 1_000_000}M"
526
+ return f"{tokens // 1000}k"
527
+
528
+
529
+ def session_start_message(budget, window, model):
530
+ """The one line said before the first request, naming the budget and how to fit it.
531
+
532
+ A session that starts fresh has no assistant message yet, so the model - and with it the
533
+ window - is unknown. The budget is not: it is the pricing boundary either way.
534
+ """
535
+ budget_label = token_count(budget)
536
+ if not model:
537
+ frame = (
538
+ "past it a model with a larger window bills every request at the premium rate, and a "
539
+ f"{budget_label} model auto-compacts the session away"
540
+ )
541
+ elif budget < window:
542
+ frame = (
543
+ f"the long-context pricing boundary of this model's {token_count(window)} window; "
544
+ "past it every request is billed at the premium rate"
545
+ )
546
+ else:
547
+ frame = "this model's whole context window; past it auto-compact summarises the session away"
548
+ return (
549
+ f"[context-warning hook] Context budget for this session: {budget_label} tokens - {frame}. "
550
+ f"{SESSION_BUDGET} You will be warned at 70%, 85% and 95%."
551
+ )
552
+
553
+
554
+ def messages(profile, tier, tokens, budget, priced, auto_mode):
110
555
  """(systemMessage, additionalContext) for a tier.
111
556
 
112
- priced: the budget is the pricing boundary, not the window — the reason to
557
+ priced: the budget is the pricing boundary, not the window - the reason to
113
558
  hand off is cost, not an imminent auto-compact.
559
+ auto_mode: from the critical tier on, escalates from "recommend a handoff"
560
+ to "save it now" - see the module docstring for why.
114
561
  """
115
562
  k = f"~{tokens // 1000}k"
116
563
  pct = round(tokens / budget * 100)
117
564
  budget_k = f"{budget // 1000}k"
118
- if tier == 2 and priced:
119
- return (
120
- f"🔴 Context is at {k} tokens — about to cross the {budget_k} long-context "
121
- f"pricing boundary, after which every request bills the whole context at the "
122
- f"premium rate. Run /handoff now and continue in a fresh session.",
123
- f"[context-warning hook] The context is at {k} tokens — {pct}% of the "
124
- f"{budget_k} long-context pricing boundary. Past it every request is billed at "
125
- "the premium rate. Finish only the immediate step, then recommend the user run "
126
- "/handoff to save state and start a fresh session. Do not start new sub-tasks.",
565
+ left = headroom(tokens, budget)
566
+
567
+ if priced:
568
+ approach = "about to cross" if tier >= 2 else "approaching"
569
+ headline = f"Context is at {k} tokens - {approach} the {budget_k} long-context pricing boundary"
570
+ detail = (
571
+ f"The context is at {k} tokens - {pct}% of the {budget_k} long-context "
572
+ f"pricing boundary, {left} left."
127
573
  )
128
- if tier == 2:
574
+ pressure = "Past it every request is billed at the premium rate. "
575
+ tail = ""
576
+ else:
577
+ headline = f"Context is at {k} tokens ({pct}% of the {budget_k} window)"
578
+ detail = (
579
+ f"The context window is at {k} tokens - {pct}% of this model's "
580
+ f"{budget_k} window, {left} left."
581
+ )
582
+ pressure = ""
583
+ tail = " - auto-compact is imminent" if tier >= 3 else " - auto-compact is close" if tier == 2 else ""
584
+
585
+ if tier >= 3:
586
+ gone = (
587
+ f"The finish-first choice from the last warning is gone: {left} does not "
588
+ f"cover another task."
589
+ )
590
+ if auto_mode:
591
+ return (
592
+ f"🔴 {headline}{tail}. Auto mode is active: saving a handoff now.",
593
+ f"[context-warning hook] {detail} {pressure}{gone} Auto mode is active, so "
594
+ f"{profile['save_now']}",
595
+ )
129
596
  return (
130
- f"🔴 Context is at {k} tokens ({pct}% of the {budget_k} window) — "
131
- f"auto-compact is imminent. Run /handoff now and continue in a fresh session.",
132
- f"[context-warning hook] The context window is at {k} tokens — {pct}% of "
133
- f"this model's {budget_k} window (critical, ≥{int(CRITICAL_FRACTION * 100)}%). "
134
- "Finish only the immediate step, then recommend the user run /handoff to "
135
- "save state and start a fresh session. Do not start new sub-tasks.",
597
+ f"🔴 {headline}{tail}. {profile['act_now']}",
598
+ f"[context-warning hook] {detail} {pressure}{gone} Stop after the current tool "
599
+ f"call, then {profile['recommend']}.",
136
600
  )
137
- if priced:
601
+
602
+ if tier == 2:
603
+ if auto_mode:
604
+ return (
605
+ f"🔴 {headline}{tail}. Auto mode is active: finishing the task, or saving a handoff.",
606
+ f"[context-warning hook] {detail} {pressure}Auto mode is active, so don't "
607
+ f"just recommend a handoff. Choose one of two, and tell the user which. "
608
+ f"{FINISH_FIRST} Otherwise {profile['save_now']}",
609
+ )
138
610
  return (
139
- f"🟡 Context is at {k} tokens, approaching the {budget_k} long-context "
140
- f"pricing boundary. At the next natural stopping point, consider /handoff "
141
- f"to continue in a fresh session.",
142
- f"[context-warning hook] The context is at {k} tokens — {pct}% of the "
143
- f"{budget_k} long-context pricing boundary, past which every request is "
144
- "billed at the premium rate. When the current task reaches a natural "
145
- "stopping point, suggest the user run /handoff to save state and start a "
146
- "fresh session. Keep working normally until then.",
611
+ f"🔴 {headline}{tail}. {profile['act_now']}",
612
+ f"[context-warning hook] {detail} {pressure}Choose one of two, and tell the user "
613
+ f"which. {FINISH_FIRST} Otherwise finish only the immediate step, then "
614
+ f"{profile['recommend']}. Either way, start no new sub-tasks.",
147
615
  )
616
+
617
+ return (
618
+ f"🟡 {headline}. At the next natural stopping point, {profile['act_later']}.",
619
+ f"[context-warning hook] {detail} {pressure}Handoff mode is active from here on. "
620
+ f"{HANDOFF_MODE} Keep working; when the current task reaches a natural stopping "
621
+ f"point, {profile['suggest']}.",
622
+ )
623
+
624
+
625
+ def stop_messages(profile, tier, tokens, budget, priced):
626
+ """(systemMessage, additionalContext) for a turn that is about to end over budget.
627
+
628
+ The turn continues after this, so the agent acts on it without the user having to
629
+ send a message. It is the only point where the agent is between tasks and can still
630
+ spend tokens, so the choice is put here in full - including the option to cross the
631
+ boundary on purpose, which some sessions are worth.
632
+ """
633
+ k = f"~{tokens // 1000}k"
634
+ pct = round(tokens / budget * 100)
635
+ budget_k = f"{budget // 1000}k"
636
+ left = headroom(tokens, budget)
637
+ options = [
638
+ f"Hand off: {profile['save_at_stop']}.",
639
+ (
640
+ "Cross the boundary on purpose: take this only for a reason you can name in one "
641
+ "sentence right now, for example the task is one step from done, or this session "
642
+ f"holds reasoning a handoff file would lose. Say the reason, say that "
643
+ f"{cost_of_crossing(priced)}, and keep working."
644
+ ),
645
+ ]
646
+ if tier < 3:
647
+ options.insert(0, f"Finish the task now: {FINISH_FIRST}")
648
+ numbered = " ".join(f"{index}. {text}" for index, text in enumerate(options, start=1))
649
+ withdrawn = (
650
+ ""
651
+ if tier < 3
652
+ else f" The finish-first option is withdrawn at this tier: {left} does not cover another task."
653
+ )
654
+ return (
655
+ f"🔴 Turn ending at {k} tokens ({pct}% of the {budget_k} {limit_name(priced)}). "
656
+ f"Deciding whether to hand off.",
657
+ f"[context-warning hook] This turn is about to end at {k} tokens - {pct}% of the "
658
+ f"{budget_k} {limit_name(priced)}, {left} left. Past it {cost_of_crossing(priced)}."
659
+ f"{withdrawn} Do not end the turn without taking one of these, and tell the user "
660
+ f"which you took. {numbered}",
661
+ )
662
+
663
+
664
+ def reminder(tier, tokens, budget, priced):
665
+ """The short note repeated on every prompt after a tier was already warned about.
666
+
667
+ A single warning at 70% is stale by the time the budget is actually tight, and the
668
+ agent has no way to read its own token count between prompts.
669
+ """
670
+ stop = (
671
+ " You were already told to hand off. Do not take on new work."
672
+ if tier >= 2
673
+ else ""
674
+ )
675
+ return (
676
+ f"[context-warning hook] Handoff mode is active: {headroom(tokens, budget)} left of "
677
+ f"the {budget // 1000}k {limit_name(priced)}. {HANDOFF_MODE}{stop}"
678
+ )
679
+
680
+
681
+ def subagent_message(tier, tokens, budget, priced):
682
+ k = f"~{tokens // 1000}k"
683
+ pct = round(tokens / budget * 100)
684
+ budget_k = f"{budget // 1000}k"
685
+ next_step = (
686
+ "Finish only the immediate step, then send the parent agent detailed findings, "
687
+ "completed work, and remaining work, and stop."
688
+ if tier >= 2
689
+ else "Keep working normally; at the next natural stopping point, send detailed progress "
690
+ "and any remaining work to the parent agent."
691
+ )
692
+ return (
693
+ f"[context-warning hook] This warning applies to a sub-agent thread, not the "
694
+ f"parent/main agent. This sub-agent is at {k} tokens - {pct}% of its {budget_k} "
695
+ f"{limit_name(priced)}. {next_step} Do not create a user-facing session handoff or "
696
+ f"claim that the main agent's context is full."
697
+ )
698
+
699
+
700
+ def subagent_reminder(tokens, budget, priced):
148
701
  return (
149
- f"🟡 Context is at {k} tokens ({pct}% of the {budget_k} window). At the next "
150
- f"natural stopping point, consider /handoff to continue in a fresh session.",
151
- f"[context-warning hook] The context window is at {k} tokens — {pct}% of "
152
- f"this model's {budget_k} window (≥{int(WARN_FRACTION * 100)}%). When the "
153
- "current task reaches a natural stopping point, suggest the user run "
154
- "/handoff to save state and start a fresh session. Keep working normally until then.",
702
+ f"[context-warning hook] Handoff mode is active for this sub-agent thread, not the "
703
+ f"parent/main agent: {headroom(tokens, budget)} left of its {budget // 1000}k "
704
+ f"{limit_name(priced)}. Keep findings compact and send them to the parent agent "
705
+ f"before the budget runs out. Do not create a user-facing session handoff."
155
706
  )
156
707
 
157
708
 
709
+ def emit(event, additional_context, system_message=None):
710
+ payload = {
711
+ "hookSpecificOutput": {
712
+ "hookEventName": event,
713
+ "additionalContext": additional_context,
714
+ }
715
+ }
716
+ if system_message:
717
+ payload["systemMessage"] = system_message
718
+ payload["suppressOutput"] = True
719
+ print(json.dumps(payload))
720
+
721
+
722
+ def read_state(path):
723
+ """{"tier": n, "stop_tier": n, "saving": bool} from the state file; zeroes when absent or unreadable."""
724
+ empty = {"tier": 0, "stop_tier": 0, "saving": False}
725
+ try:
726
+ with open(path, encoding="utf-8") as f:
727
+ raw = f.read().strip()
728
+ except OSError:
729
+ return empty
730
+ try:
731
+ state = json.loads(raw)
732
+ if isinstance(state, dict):
733
+ return {
734
+ "tier": int(state.get("tier", 0)),
735
+ "stop_tier": int(state.get("stop_tier", 0)),
736
+ "saving": state.get("saving") is True,
737
+ }
738
+ except (ValueError, TypeError):
739
+ pass
740
+ try:
741
+ return {**empty, "tier": int(raw or 0)}
742
+ except ValueError:
743
+ return empty
744
+
745
+
746
+ def write_state(path, state):
747
+ try:
748
+ with open(path, "w", encoding="utf-8") as f:
749
+ json.dump(state, f)
750
+ except OSError:
751
+ pass
752
+
753
+
158
754
  def main():
159
- if disabled_locally():
755
+ agent = agent_name(sys.argv[1:])
756
+ profile = AGENT_PROFILES.get(agent)
757
+ if not profile:
160
758
  return
759
+
161
760
  data = json.load(sys.stdin)
761
+ event = data.get("hook_event_name") or "UserPromptSubmit"
762
+ root = repo_root(data)
763
+ local_config = load_local_config(root)
764
+ if disabled_locally(local_config):
765
+ return
766
+
767
+ profile = resolve_profile(profile, handoff_skill(root))
768
+
769
+ # PostToolBatch and Stop also fire inside an Agent-tool sub-agent, where the transcript
770
+ # read here belongs to the parent. Telling a sub-agent to hand off the user's session
771
+ # would be wrong, and its own token count is not available, so stay silent.
772
+ if data.get("agent_id") and event in ("PostToolBatch", "Stop"):
773
+ return
774
+
162
775
  transcript_path = data.get("transcript_path")
163
776
  session_id = data.get("session_id", "unknown")
164
- if not transcript_path or not os.path.isfile(transcript_path):
777
+ auto_mode = data.get("permission_mode") in profile["auto_modes"] and not auto_handoff_save_disabled(local_config)
778
+ has_transcript = bool(transcript_path) and os.path.isfile(transcript_path)
779
+
780
+ # SessionStart fires before the first request, so it must not need a transcript to exist.
781
+ if not has_transcript and event != "SessionStart":
165
782
  return
166
783
 
167
- tokens, model = context_state(transcript_path)
168
- window = window_for(model)
169
- budget = min(window, PREMIUM_BOUNDARY)
170
- warn_tokens = int(budget * WARN_FRACTION)
171
- critical_tokens = int(budget * CRITICAL_FRACTION)
172
- tier = 2 if tokens >= critical_tokens else 1 if tokens >= warn_tokens else 0
784
+ if has_transcript:
785
+ tokens, model, reported_window, thread_id, is_subagent = CONTEXT_READERS[agent](transcript_path)
786
+ else:
787
+ tokens, model, reported_window, thread_id, is_subagent = 0, None, None, None, False
788
+ window = reported_window or profile["default_window"] or window_for(model)
789
+ boundary = premium_boundary_for(profile, model)
790
+ budget = min(window, boundary) if boundary else window
791
+ priced = budget < window
173
792
 
174
- state_file = os.path.join(
175
- tempfile.gettempdir(), f"claude-context-warning-{session_id}"
176
- )
177
- prev_tier = 0
178
- try:
179
- with open(state_file, encoding="utf-8") as f:
180
- prev_tier = int(f.read().strip() or 0)
181
- except (OSError, ValueError):
182
- pass
793
+ if event == "SessionStart":
794
+ emit(event, session_start_message(budget, window, model))
795
+ return
183
796
 
184
- if tier != prev_tier:
185
- try:
186
- with open(state_file, "w", encoding="utf-8") as f:
187
- f.write(str(tier))
188
- except OSError:
189
- pass
797
+ tier = 0
798
+ for level, fraction in ((3, FINAL_FRACTION), (2, CRITICAL_FRACTION), (1, WARN_FRACTION)):
799
+ if tokens >= int(budget * fraction):
800
+ tier = level
801
+ break
802
+
803
+ state_id = thread_id or session_id
804
+ safe_state_id = "".join(char for char in str(state_id) if char.isalnum() or char in "-_")[:128]
805
+ state_file = os.path.join(tempfile.gettempdir(), f"{agent}-context-warning-{safe_state_id or 'unknown'}")
806
+ state = read_state(state_file)
807
+ prev_tier = state["tier"]
808
+
809
+ if event == "UserPromptSubmit":
810
+ saving = handoff_save_requested(data.get("prompt"))
811
+ if saving != state["saving"]:
812
+ state = {**state, "saving": saving}
813
+ write_state(state_file, state)
814
+ if saving:
815
+ return
816
+ elif tier and (state["saving"] or (agent == "claude" and handoff_under_way_in_turn(transcript_path))):
817
+ return
818
+
819
+ if event == "Stop":
820
+ # Below the critical tier the mid-run notice is enough; interrupting the end of a turn
821
+ # at 70% costs more than it saves.
822
+ if tier < 2 or tier <= state["stop_tier"] or is_subagent:
823
+ return
824
+ write_state(state_file, {**state, "stop_tier": tier})
825
+ system_message, additional_context = stop_messages(profile, tier, tokens, budget, priced)
826
+ if profile["emits_system_message"]:
827
+ emit(event, additional_context, system_message)
828
+ else:
829
+ emit(event, additional_context)
830
+ return
831
+
832
+ orders_save = auto_mode and tier >= 2 and tier > prev_tier and not is_subagent
833
+ if tier != prev_tier or orders_save:
834
+ write_state(
835
+ state_file,
836
+ {**state, "tier": tier, "stop_tier": min(state["stop_tier"], tier), "saving": state["saving"] or orders_save},
837
+ )
190
838
 
191
839
  if tier <= prev_tier:
192
- return # already warned at this tier (or context shrank — state re-armed above)
193
-
194
- system_message, additional_context = messages(tier, tokens, budget, budget < window)
195
-
196
- print(
197
- json.dumps(
198
- {
199
- "systemMessage": system_message,
200
- "suppressOutput": True,
201
- "hookSpecificOutput": {
202
- "hookEventName": "UserPromptSubmit",
203
- "additionalContext": additional_context,
204
- },
205
- }
840
+ # Below the first threshold, or the context shrank - the state was re-armed above.
841
+ if tier == 0:
842
+ return
843
+ # Only a prompt repeats the reminder. On a tool batch it would be re-injected before
844
+ # every model request, which costs more context than it saves.
845
+ if event != "UserPromptSubmit":
846
+ return
847
+ emit(
848
+ event,
849
+ subagent_reminder(tokens, budget, priced)
850
+ if is_subagent
851
+ else reminder(tier, tokens, budget, priced),
206
852
  )
853
+ return
854
+
855
+ if is_subagent:
856
+ emit(event, subagent_message(tier, tokens, budget, priced))
857
+ return
858
+
859
+ system_message, additional_context = messages(
860
+ profile, tier, tokens, budget, priced, auto_mode
207
861
  )
862
+ if profile["emits_system_message"]:
863
+ emit(event, additional_context, system_message)
864
+ else:
865
+ emit(event, f"{additional_context}\n\nTell the user: {system_message}")
208
866
 
209
867
 
210
868
  if __name__ == "__main__":