@ethlete/agent-rules 0.1.0-next.4 → 0.1.0-next.41

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