@ethlete/agent-rules 0.1.0-next.5 → 0.1.0-next.50

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 (242) hide show
  1. package/AGENTS.md +28 -0
  2. package/CHANGELOG.md +742 -0
  3. package/CLAUDE.md +1 -0
  4. package/README.md +430 -25
  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 +327 -0
  10. package/content/hooks/background-design-commands.py +228 -0
  11. package/content/hooks/builder-idle-check.py +388 -0
  12. package/content/hooks/context-warning.py +694 -134
  13. package/content/hooks/design-live-check.py +136 -0
  14. package/content/hooks/git-safety.py +213 -0
  15. package/content/hooks/human-wait-check.py +167 -0
  16. package/content/hooks/subagent-model-policy.py +261 -0
  17. package/content/mods/.claude-plugin/marketplace.json +26 -0
  18. package/content/mods/plugins/codex-runs/.claude-plugin/plugin.json +6 -0
  19. package/content/mods/plugins/codex-runs/hooks/hooks.json +1 -0
  20. package/content/mods/plugins/codex-runs/hooks/progress.ts +130 -0
  21. package/content/mods/plugins/codex-runs/hooks/register.tsx +103 -0
  22. package/content/mods/plugins/codex-runs/tsconfig.json +4 -0
  23. package/content/mods/plugins/codex-runs/types/index.d.ts +19 -0
  24. package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +6 -0
  25. package/content/mods/plugins/e2e-progress/hooks/hooks.json +1 -0
  26. package/content/mods/plugins/e2e-progress/hooks/progress.ts +152 -0
  27. package/content/mods/plugins/e2e-progress/hooks/register.tsx +442 -0
  28. package/content/mods/plugins/e2e-progress/tsconfig.json +3 -0
  29. package/content/mods/plugins/e2e-progress/types/index.d.ts +26 -0
  30. package/content/mods/plugins/status-line/.claude-plugin/plugin.json +6 -0
  31. package/content/mods/plugins/status-line/hooks/hooks.json +1 -0
  32. package/content/mods/plugins/status-line/hooks/line.ts +74 -0
  33. package/content/mods/plugins/status-line/hooks/register.tsx +141 -0
  34. package/content/mods/plugins/status-line/types/index.d.ts +5 -0
  35. package/content/mods/plugins/usage-line/.claude-plugin/plugin.json +6 -0
  36. package/content/mods/plugins/usage-line/hooks/codex.ts +52 -0
  37. package/content/mods/plugins/usage-line/hooks/format.ts +24 -0
  38. package/content/mods/plugins/usage-line/hooks/hooks.json +1 -0
  39. package/content/mods/plugins/usage-line/hooks/register.tsx +67 -0
  40. package/content/mods/plugins/usage-line/tsconfig.json +4 -0
  41. package/content/mods/plugins/usage-line/types/index.d.ts +5 -0
  42. package/content/output-styles/ste-clarity.md +131 -0
  43. package/content/rules/agent-sessions-wake-up.md +11 -0
  44. package/content/rules/app-styling.md +66 -0
  45. package/content/rules/comments.md +4 -1
  46. package/content/rules/lint-and-format.md +7 -5
  47. package/content/rules/nx-layout.md +53 -0
  48. package/content/rules/reactive-state.md +1 -1
  49. package/content/rules/styling.md +19 -10
  50. package/content/rules/subagent-models.md +42 -0
  51. package/content/rules/waiting-on-the-human.md +17 -0
  52. package/content/skills/agent-sessions/SKILL.md +100 -0
  53. package/content/skills/agent-sessions/agent-sessions.mjs +1420 -0
  54. package/content/skills/angular-patterns/SKILL.md +31 -7
  55. package/content/skills/api-source/SKILL.md +156 -0
  56. package/content/skills/app-testing/SKILL.md +141 -0
  57. package/content/skills/codex-subagent/SKILL.md +96 -0
  58. package/content/skills/codex-subagent/codex-agent.mjs +229 -0
  59. package/content/skills/codex-subagent/codex-limit.mjs +106 -0
  60. package/content/skills/design-exploration/SKILL.md +203 -0
  61. package/content/skills/design-exploration/check-story.mjs +139 -0
  62. package/content/skills/design-exploration/reference-check-and-notes.md +100 -0
  63. package/content/skills/design-exploration/reference-flows.md +38 -0
  64. package/content/skills/design-exploration/reference-inbox-and-mcp.md +54 -0
  65. package/content/skills/design-exploration/reference-order-and-design-system.md +120 -0
  66. package/content/skills/design-exploration/reference-products-and-sketches.md +250 -0
  67. package/content/skills/design-exploration/reference-shots.md +25 -0
  68. package/content/skills/design-exploration/shoot-template.mjs +61 -0
  69. package/content/skills/domain-modeling/CONTEXT-FORMAT.md +60 -0
  70. package/content/skills/domain-modeling/SKILL.md +71 -0
  71. package/content/skills/e2e-triage/SKILL.md +80 -0
  72. package/content/skills/figma-export/SKILL.md +16 -18
  73. package/content/skills/git-commit/SKILL.md +21 -7
  74. package/content/skills/git-flow/SKILL.md +87 -0
  75. package/content/skills/grill-with-docs/SKILL.md +13 -0
  76. package/content/skills/grilling/SKILL.md +52 -0
  77. package/content/skills/handoff/SKILL.md +29 -69
  78. package/content/skills/handoff/save.md +187 -0
  79. package/content/skills/query/SKILL.md +165 -70
  80. package/content/skills/report/SKILL.md +26 -0
  81. package/content/skills/rxjs-signals/SKILL.md +33 -4
  82. package/content/skills/sdk-docs/SKILL.md +50 -14
  83. package/content/skills/sdk-local-build/SKILL.md +26 -8
  84. package/content/skills/sdk-local-build/sdk-local-baseline.mjs +64 -0
  85. package/content/skills/sdk-source/SKILL.md +37 -34
  86. package/content/skills/sdk-update/SKILL.md +103 -0
  87. package/content/skills/story-styling/SKILL.md +12 -10
  88. package/content/skills/styleguide/SKILL.md +13 -8
  89. package/content/skills/styleguide/assets.md +54 -0
  90. package/content/skills/styleguide/changesets.md +17 -0
  91. package/content/skills/styleguide/file-structure.md +73 -0
  92. package/content/skills/styleguide/lint-rule-lookup.md +52 -0
  93. package/content/skills/styleguide/storybook-structure.md +25 -0
  94. package/content/skills/theming/SKILL.md +68 -43
  95. package/content/skills/timetrack/SKILL.md +324 -0
  96. package/content/skills/verify-in-app/SKILL.md +107 -0
  97. package/content/skills/verify-in-storybook/SKILL.md +1 -1
  98. package/migrations/list-state-query-form.md +20 -0
  99. package/migrations/nx-layout.md +29 -0
  100. package/migrations/sdk-components-over-hand-built-ui.md +27 -0
  101. package/migrations/search-query-field.md +52 -0
  102. package/migrations.json +39 -0
  103. package/package.json +19 -3
  104. package/src/index.js +99 -32
  105. package/src/index.js.map +1 -1
  106. package/src/lib/cli-args.d.ts +9 -0
  107. package/src/lib/cli-args.js +48 -0
  108. package/src/lib/cli-args.js.map +1 -0
  109. package/src/lib/commitlint.d.ts +10 -0
  110. package/src/lib/commitlint.js +51 -0
  111. package/src/lib/commitlint.js.map +1 -0
  112. package/src/lib/config.d.ts +64 -5
  113. package/src/lib/config.js +140 -11
  114. package/src/lib/config.js.map +1 -1
  115. package/src/lib/filter.d.ts +2 -0
  116. package/src/lib/filter.js +4 -4
  117. package/src/lib/filter.js.map +1 -1
  118. package/src/lib/frontmatter.d.ts +2 -0
  119. package/src/lib/frontmatter.js +33 -5
  120. package/src/lib/frontmatter.js.map +1 -1
  121. package/src/lib/git-flow/build.d.ts +35 -0
  122. package/src/lib/git-flow/build.js +24 -0
  123. package/src/lib/git-flow/build.js.map +1 -0
  124. package/src/lib/git-flow/config.d.ts +59 -0
  125. package/src/lib/git-flow/config.js +50 -0
  126. package/src/lib/git-flow/config.js.map +1 -0
  127. package/src/lib/git-flow/index.d.ts +6 -0
  128. package/src/lib/git-flow/index.js +23 -0
  129. package/src/lib/git-flow/index.js.map +1 -0
  130. package/src/lib/git-flow/parse.d.ts +49 -0
  131. package/src/lib/git-flow/parse.js +300 -0
  132. package/src/lib/git-flow/parse.js.map +1 -0
  133. package/src/lib/git-flow/rename.d.ts +24 -0
  134. package/src/lib/git-flow/rename.js +70 -0
  135. package/src/lib/git-flow/rename.js.map +1 -0
  136. package/src/lib/git-flow/start.d.ts +49 -0
  137. package/src/lib/git-flow/start.js +57 -0
  138. package/src/lib/git-flow/start.js.map +1 -0
  139. package/src/lib/git-flow/validate.d.ts +34 -0
  140. package/src/lib/git-flow/validate.js +72 -0
  141. package/src/lib/git-flow/validate.js.map +1 -0
  142. package/src/lib/git-flow-command.d.ts +4 -0
  143. package/src/lib/git-flow-command.js +165 -0
  144. package/src/lib/git-flow-command.js.map +1 -0
  145. package/src/lib/git-flow-repair.d.ts +17 -0
  146. package/src/lib/git-flow-repair.js +165 -0
  147. package/src/lib/git-flow-repair.js.map +1 -0
  148. package/src/lib/git-flow-start.d.ts +20 -0
  149. package/src/lib/git-flow-start.js +140 -0
  150. package/src/lib/git-flow-start.js.map +1 -0
  151. package/src/lib/git-test-env.fixtures.d.ts +11 -0
  152. package/src/lib/git-test-env.fixtures.js +31 -0
  153. package/src/lib/git-test-env.fixtures.js.map +1 -0
  154. package/src/lib/git.d.ts +64 -0
  155. package/src/lib/git.js +131 -0
  156. package/src/lib/git.js.map +1 -0
  157. package/src/lib/gitlab.d.ts +35 -0
  158. package/src/lib/gitlab.js +116 -0
  159. package/src/lib/gitlab.js.map +1 -0
  160. package/src/lib/index.d.ts +2 -0
  161. package/src/lib/index.js +26 -11
  162. package/src/lib/index.js.map +1 -1
  163. package/src/lib/migrate.js +8 -2
  164. package/src/lib/migrate.js.map +1 -1
  165. package/src/lib/output-style-command.d.ts +3 -0
  166. package/src/lib/output-style-command.js +69 -0
  167. package/src/lib/output-style-command.js.map +1 -0
  168. package/src/lib/output-style.d.ts +38 -0
  169. package/src/lib/output-style.js +134 -0
  170. package/src/lib/output-style.js.map +1 -0
  171. package/src/lib/owned-paths.js +8 -2
  172. package/src/lib/owned-paths.js.map +1 -1
  173. package/src/lib/package-runner.d.ts +4 -0
  174. package/src/lib/package-runner.js +86 -0
  175. package/src/lib/package-runner.js.map +1 -0
  176. package/src/lib/peer-path.d.ts +12 -0
  177. package/src/lib/peer-path.js +39 -0
  178. package/src/lib/peer-path.js.map +1 -0
  179. package/src/lib/plain-text.d.ts +9 -0
  180. package/src/lib/plain-text.js +22 -0
  181. package/src/lib/plain-text.js.map +1 -0
  182. package/src/lib/plan.d.ts +6 -6
  183. package/src/lib/plan.js +160 -38
  184. package/src/lib/plan.js.map +1 -1
  185. package/src/lib/prettier.d.ts +21 -0
  186. package/src/lib/prettier.js +51 -0
  187. package/src/lib/prettier.js.map +1 -0
  188. package/src/lib/prompt.d.ts +8 -0
  189. package/src/lib/prompt.js +35 -0
  190. package/src/lib/prompt.js.map +1 -0
  191. package/src/lib/render.d.ts +26 -2
  192. package/src/lib/render.js +45 -10
  193. package/src/lib/render.js.map +1 -1
  194. package/src/lib/report-command.d.ts +34 -0
  195. package/src/lib/report-command.js +316 -0
  196. package/src/lib/report-command.js.map +1 -0
  197. package/src/lib/sessions-command.d.ts +4 -0
  198. package/src/lib/sessions-command.js +16 -0
  199. package/src/lib/sessions-command.js.map +1 -0
  200. package/src/lib/sync.d.ts +1 -2
  201. package/src/lib/sync.js +37 -17
  202. package/src/lib/sync.js.map +1 -1
  203. package/src/lib/targets/agents-skills.js +1 -1
  204. package/src/lib/targets/agents-skills.js.map +1 -1
  205. package/src/lib/targets/claude-hooks.d.ts +2 -0
  206. package/src/lib/targets/claude-hooks.js +8 -3
  207. package/src/lib/targets/claude-hooks.js.map +1 -1
  208. package/src/lib/targets/claude-mods.d.ts +20 -0
  209. package/src/lib/targets/claude-mods.js +47 -0
  210. package/src/lib/targets/claude-mods.js.map +1 -0
  211. package/src/lib/targets/claude.js +2 -3
  212. package/src/lib/targets/claude.js.map +1 -1
  213. package/src/lib/targets/codex-hooks.js +4 -2
  214. package/src/lib/targets/codex-hooks.js.map +1 -1
  215. package/src/lib/targets/codex.js +4 -4
  216. package/src/lib/targets/codex.js.map +1 -1
  217. package/src/lib/targets/copilot.js +4 -4
  218. package/src/lib/targets/copilot.js.map +1 -1
  219. package/src/lib/targets/cursor.js +3 -3
  220. package/src/lib/targets/cursor.js.map +1 -1
  221. package/src/lib/targets/git-hooks.d.ts +25 -0
  222. package/src/lib/targets/git-hooks.js +71 -0
  223. package/src/lib/targets/git-hooks.js.map +1 -0
  224. package/src/lib/targets/hooks-shared.d.ts +29 -5
  225. package/src/lib/targets/hooks-shared.js +130 -36
  226. package/src/lib/targets/hooks-shared.js.map +1 -1
  227. package/src/lib/targets/mcp.d.ts +16 -0
  228. package/src/lib/targets/mcp.js +72 -0
  229. package/src/lib/targets/mcp.js.map +1 -0
  230. package/src/lib/targets/shared.d.ts +1 -9
  231. package/src/lib/targets/shared.js +4 -8
  232. package/src/lib/targets/shared.js.map +1 -1
  233. package/src/lib/timetrack-command.d.ts +11 -0
  234. package/src/lib/timetrack-command.js +1262 -0
  235. package/src/lib/timetrack-command.js.map +1 -0
  236. package/src/lib/timetrack-snapshot.d.ts +66 -0
  237. package/src/lib/timetrack-snapshot.js +146 -0
  238. package/src/lib/timetrack-snapshot.js.map +1 -0
  239. package/src/lib/timetrack.d.ts +607 -0
  240. package/src/lib/timetrack.js +285 -0
  241. package/src/lib/timetrack.js.map +1 -0
  242. package/content/skills/styleguide/STYLEGUIDE.md +0 -520
@@ -1,40 +1,79 @@
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
5
  the session transcript, and emits a warning (visible to both the user and the
6
6
  agent) when it crosses a threshold. Recommends the handoff skill so work can
7
7
  continue in a fresh session.
8
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
+
9
28
  Runs under both Claude Code and Codex, selected by `--agent` on the command
10
- line rather than sniffed from the payload — the generator writes the flag, so
11
- the two never have to be told apart at runtime. The two differ in three ways
12
- that matter here, all captured in AGENT_PROFILES:
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:
13
33
 
14
34
  * Transcript format. Claude writes one JSON object per message with
15
35
  `message.usage`; Codex writes a rollout stream whose `token_count` events
16
36
  carry a TokenUsageInfo. Codex's rollout format is explicitly not a stable
17
37
  interface, so the parser searches each line for the usage object instead of
18
38
  walking a fixed path.
19
- * Context budget. Claude's budget is capped at the 200k long-context pricing
20
- boundary: on models with a larger window, every request past that point
21
- bills the entire context at the premium rate, which costs far more than
22
- handing off into a fresh session ever would. Codex has no such boundary, so
23
- its budget is just the window.
24
- * How a handoff is invoked. Claude has /handoff and /clear; Codex has neither
25
- and reads the skill from disk.
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().
26
51
 
27
52
  At the critical tier, if the session's permission_mode is "auto", the
28
53
  instruction escalates from "recommend" to "just do it": auto mode already
29
- means the user wants the agent acting without stopping to ask, and clearing +
30
- resuming can't be triggered programmatically (no hook or tool can submit
31
- input to a running session), so the best available automation is to save the
54
+ means the user wants the agent acting without stopping to ask, so it saves the
32
55
  handoff file itself immediately rather than waiting for a natural stopping
33
- point. Codex's permission_mode value set is undocumented, so its profile lists
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
34
58
  no auto modes and the escalation stays off there.
35
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.
72
+
36
73
  Warns once per tier per session (state kept in a temp file); re-arms itself
37
- if the context shrinks again (e.g. after a compaction).
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.
38
77
 
39
78
  Can be disabled per machine via a gitignored ethlete-agents.config.local.json
40
79
  at the repo root: {"disableHooks": true} or {"disableHooks": ["context-warning"]}.
@@ -42,27 +81,64 @@ To keep the tiered warnings but drop just the auto-mode auto-save escalation,
42
81
  use {"disableAutoHandoffSave": true} instead - the critical tier then falls
43
82
  back to recommending a handoff, same as non-auto mode.
44
83
 
45
- 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.
46
86
  """
47
87
 
48
88
  import json
49
89
  import os
90
+ import re
91
+ import subprocess
50
92
  import sys
51
93
  import tempfile
52
94
 
53
95
  HOOK_NAME = "context-warning"
54
96
  LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
55
97
 
56
- # Warn / critical fire at these fractions of the token budget.
98
+ # Warn / critical / final fire at these fractions of the token budget.
57
99
  WARN_FRACTION = 0.70
58
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
+ )
59
125
 
60
126
  # On models with a window larger than this, tokens beyond it bill the whole
61
- # 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.
62
128
  PREMIUM_BOUNDARY = 200_000
63
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
+
64
140
  # Context window (tokens) per model, matched by substring against the model id
65
- # 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;
66
142
  # anything unmatched falls back to DEFAULT_WINDOW.
67
143
  CONTEXT_WINDOWS = (
68
144
  ("opus-5", 1_000_000),
@@ -70,7 +146,7 @@ CONTEXT_WINDOWS = (
70
146
  ("sonnet-4-5", 1_000_000),
71
147
  ("sonnet-5", 1_000_000),
72
148
  ("fable-5", 1_000_000),
73
- # 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
74
150
  # "opus"/"sonnet" entry placed above would shadow every versioned entry below it.
75
151
  ("opus", 200_000),
76
152
  ("sonnet", 200_000),
@@ -78,27 +154,48 @@ CONTEXT_WINDOWS = (
78
154
  )
79
155
  DEFAULT_WINDOW = 200_000
80
156
 
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
+
81
164
  AGENT_PROFILES = {
82
165
  "claude": {
83
166
  "premium_boundary": PREMIUM_BOUNDARY,
167
+ "premium_boundaries": (),
84
168
  # Claude's transcript reports no window, so it is resolved from the model id.
85
169
  "default_window": None,
86
170
  "auto_modes": ("auto",),
87
171
  "emits_system_message": True,
88
- "act_now": "Run /handoff now and continue in a fresh session.",
89
- "act_later": "consider /handoff to continue in a fresh session",
90
- "recommend": "recommend the user run /handoff to save state and start a fresh session",
91
- "suggest": "suggest the user run /handoff to save state and start a fresh session",
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
+ ),
92
184
  "save_now": (
93
- "run the handoff skill's save mode right now (finish only an in-flight atomic "
94
- "edit first, nothing new). Then tell the user exactly which handoff file was "
95
- "written and that they should run /clear, then '/handoff resume <slug>', to "
96
- "continue — clearing and resuming can't be done programmatically, so this is "
97
- "the one step still on them."
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>'"
98
194
  ),
99
195
  },
100
196
  "codex": {
101
197
  "premium_boundary": None,
198
+ "premium_boundaries": CODEX_PREMIUM_BOUNDARIES,
102
199
  # Only reached if a rollout omits model_context_window; the CONTEXT_WINDOWS table
103
200
  # holds Claude model ids and would never match a Codex one.
104
201
  "default_window": 272_000,
@@ -112,25 +209,113 @@ AGENT_PROFILES = {
112
209
  "act_later": "consider saving a handoff and continuing in a fresh session",
113
210
  "recommend": (
114
211
  "tell the user you are near the context limit, then follow "
115
- ".agents/skills/ethlete-handoff/SKILL.md to save a handoff and have them start a "
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 "
116
214
  "fresh session"
117
215
  ),
118
216
  "suggest": (
119
- "suggest saving a handoff via .agents/skills/ethlete-handoff/SKILL.md and "
120
- "continuing in a fresh session"
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"
121
220
  ),
122
221
  "save_now": (
123
- "follow .agents/skills/ethlete-handoff/SKILL.md and save a handoff right now "
124
- "(finish only an in-flight atomic edit first, nothing new). Then tell the user "
125
- "exactly which handoff file was written and that they should start a fresh "
126
- "codex session and resume from it."
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"
127
231
  ),
128
232
  },
129
233
  }
130
234
 
131
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
+
132
317
  def agent_name(argv):
133
- """The --agent value, defaulting to claude — older registrations pass no flag."""
318
+ """The --agent value, defaulting to claude - older registrations pass no flag."""
134
319
  for index, arg in enumerate(argv):
135
320
  if arg == "--agent" and index + 1 < len(argv):
136
321
  return argv[index + 1]
@@ -189,35 +374,74 @@ def window_for(model):
189
374
  return DEFAULT_WINDOW
190
375
 
191
376
 
192
- def claude_context_state(transcript_path):
193
- """(tokens, model, window) 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
+
194
385
 
195
- tokens ≈ its total input tokens (fresh + cache read + cache creation). Claude reports no
196
- window in the transcript, so it is resolved from the model id by the caller.
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.
197
390
  """
198
- last_usage = None
199
- last_model = None
200
- with open(transcript_path, encoding="utf-8") as f:
201
- for line in f:
202
- try:
203
- obj = json.loads(line)
204
- except json.JSONDecodeError:
205
- continue
206
- if obj.get("type") != "assistant" or obj.get("isSidechain"):
207
- continue
208
- message = obj.get("message") or {}
209
- usage = message.get("usage")
210
- if usage:
211
- last_usage = usage
212
- last_model = message.get("model") or last_model
213
- if not last_usage:
214
- return 0, last_model, None
215
- tokens = (
216
- last_usage.get("input_tokens", 0)
217
- + last_usage.get("cache_read_input_tokens", 0)
218
- + last_usage.get("cache_creation_input_tokens", 0)
219
- )
220
- return tokens, last_model, None
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
400
+
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.
430
+ """
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
221
445
 
222
446
 
223
447
  def find_token_usage_info(node):
@@ -242,20 +466,29 @@ def find_token_usage_info(node):
242
466
 
243
467
 
244
468
  def codex_context_state(transcript_path):
245
- """(tokens, model, window) from the last token_count event in a Codex rollout.
469
+ """(tokens, model, window, thread id, is sub-agent) from a Codex rollout.
246
470
 
247
- tokens is the last request's `total_tokens` — Codex's own `tokens_in_context_window()`
471
+ tokens is the last request's `total_tokens` - Codex's own `tokens_in_context_window()`
248
472
  is exactly that field, and `last_token_usage` is replaced per request while
249
473
  `total_token_usage` accumulates across the whole session.
250
474
  """
251
475
  last_info = None
252
476
  last_model = None
477
+ thread_id = None
478
+ is_subagent = False
253
479
  with open(transcript_path, encoding="utf-8") as f:
254
480
  for line in f:
255
481
  try:
256
482
  obj = json.loads(line)
257
483
  except json.JSONDecodeError:
258
484
  continue
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
+ )
259
492
  model = (obj.get("payload") or {}).get("model") if isinstance(obj.get("payload"), dict) else None
260
493
  if isinstance(model, str) and model:
261
494
  last_model = model
@@ -263,70 +496,341 @@ def codex_context_state(transcript_path):
263
496
  if info:
264
497
  last_info = info
265
498
  if not last_info:
266
- return 0, last_model, None
499
+ return 0, last_model, None, thread_id, is_subagent
267
500
  usage = last_info.get("last_token_usage") or {}
268
501
  window = last_info.get("model_context_window")
269
- return usage.get("total_tokens", 0), last_model, window if isinstance(window, int) else None
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
+ )
270
509
 
271
510
 
272
511
  CONTEXT_READERS = {"claude": claude_context_state, "codex": codex_context_state}
273
512
 
274
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%."
641
+ )
642
+
643
+
275
644
  def messages(profile, tier, tokens, budget, priced, auto_mode):
276
645
  """(systemMessage, additionalContext) for a tier.
277
646
 
278
- 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
279
648
  hand off is cost, not an imminent auto-compact.
280
- auto_mode: at the critical tier, escalates from "recommend a handoff" to
281
- "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.
282
651
  """
283
652
  k = f"~{tokens // 1000}k"
284
653
  pct = round(tokens / budget * 100)
285
654
  budget_k = f"{budget // 1000}k"
655
+ left = headroom(tokens, budget)
286
656
 
287
657
  if priced:
288
- approach = "about to cross" if tier == 2 else "approaching"
289
- headline = f"Context is at {k} tokens — {approach} the {budget_k} long-context pricing boundary"
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"
290
660
  detail = (
291
- f"The context is at {k} tokens — {pct}% of the {budget_k} long-context "
292
- f"pricing boundary."
661
+ f"The context is at {k} tokens - {pct}% of the {budget_k} long-context "
662
+ f"pricing boundary, {left} left."
293
663
  )
664
+ pressure = "Past it every request is billed at the premium rate. "
665
+ tail = ""
294
666
  else:
295
667
  headline = f"Context is at {k} tokens ({pct}% of the {budget_k} window)"
296
668
  detail = (
297
- f"The context window is at {k} tokens — {pct}% of this model's "
298
- f"{budget_k} window"
669
+ f"The context window is at {k} tokens - {pct}% of this model's "
670
+ f"{budget_k} window, {left} left."
299
671
  )
672
+ pressure = ""
673
+ tail = " - auto-compact is imminent" if tier >= 3 else " - auto-compact is close" if tier == 2 else ""
300
674
 
301
- if tier == 2:
302
- threshold = f" (critical, ≥{int(CRITICAL_FRACTION * 100)}%)"
303
- detail = detail if priced else f"{detail}{threshold}."
304
- pressure = (
305
- "Past it every request is billed at the premium rate. "
306
- if priced
307
- else ""
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."
308
679
  )
309
- tail = "" if priced else " — auto-compact is imminent"
310
680
  if auto_mode:
311
681
  return (
312
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
+ )
686
+ return (
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']}.",
690
+ )
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.",
313
696
  f"[context-warning hook] {detail} {pressure}Auto mode is active, so don't "
314
- f"just recommend a handoff — {profile['save_now']}",
697
+ f"just recommend a handoff. Choose one of two, and tell the user which. "
698
+ f"{FINISH_FIRST} Otherwise {profile['save_now']}",
315
699
  )
316
700
  return (
317
701
  f"🔴 {headline}{tail}. {profile['act_now']}",
318
- f"[context-warning hook] {detail} {pressure}Finish only the immediate step, "
319
- f"then {profile['recommend']}. Do not start new sub-tasks.",
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.",
320
705
  )
321
706
 
322
- threshold = f" (≥{int(WARN_FRACTION * 100)}%)"
323
- detail = detail if priced else f"{detail}{threshold}."
324
- pressure = "Past it every request is billed at the premium rate. " if priced else ""
325
707
  return (
326
708
  f"🟡 {headline}. At the next natural stopping point, {profile['act_later']}.",
327
- f"[context-warning hook] {detail} {pressure}When the current task reaches a "
328
- f"natural stopping point, {profile['suggest']}. Keep working normally until then.",
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."
329
743
  )
744
+ return (
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}",
751
+ )
752
+
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
330
834
 
331
835
 
332
836
  def main():
@@ -336,62 +840,118 @@ def main():
336
840
  return
337
841
 
338
842
  data = json.load(sys.stdin)
339
- local_config = load_local_config(repo_root(data))
843
+ event = data.get("hook_event_name") or "UserPromptSubmit"
844
+ root = repo_root(data)
845
+ local_config = load_local_config(root)
340
846
  if disabled_locally(local_config):
341
847
  return
342
848
 
343
- transcript_path = data.get("transcript_path")
344
- session_id = data.get("session_id", "unknown")
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")
345
862
  auto_mode = data.get("permission_mode") in profile["auto_modes"] and not auto_handoff_save_disabled(local_config)
346
- if not transcript_path or not os.path.isfile(transcript_path):
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":
347
867
  return
348
868
 
349
- tokens, model, reported_window = CONTEXT_READERS[agent](transcript_path)
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
350
876
  window = reported_window or profile["default_window"] or window_for(model)
351
- boundary = profile["premium_boundary"]
877
+ boundary = premium_boundary_for(profile, model)
352
878
  budget = min(window, boundary) if boundary else window
353
- warn_tokens = int(budget * WARN_FRACTION)
354
- critical_tokens = int(budget * CRITICAL_FRACTION)
355
- tier = 2 if tokens >= critical_tokens else 1 if tokens >= warn_tokens else 0
879
+ priced = budget < window
356
880
 
357
- state_file = os.path.join(
358
- tempfile.gettempdir(), f"{agent}-context-warning-{session_id}"
359
- )
360
- prev_tier = 0
361
- try:
362
- with open(state_file, encoding="utf-8") as f:
363
- prev_tier = int(f.read().strip() or 0)
364
- except (OSError, ValueError):
365
- pass
881
+ if event == "SessionStart":
882
+ emit(event, session_start_message(budget, window, model))
883
+ return
366
884
 
367
- if tier != prev_tier:
368
- try:
369
- with open(state_file, "w", encoding="utf-8") as f:
370
- f.write(str(tier))
371
- except OSError:
372
- 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
908
+
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
917
+
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
930
+
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},
936
+ )
373
937
 
374
938
  if tier <= prev_tier:
375
- return # already warned at this tier (or context shrank — state re-armed above)
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
376
947
 
377
948
  system_message, additional_context = messages(
378
- profile, tier, tokens, budget, budget < window, auto_mode
949
+ profile, tier, tokens, budget, priced, auto_mode
379
950
  )
380
-
381
- if not profile["emits_system_message"]:
382
- additional_context = f"{additional_context}\n\nTell the user: {system_message}"
383
-
384
- payload = {
385
- "hookSpecificOutput": {
386
- "hookEventName": "UserPromptSubmit",
387
- "additionalContext": additional_context,
388
- }
389
- }
390
951
  if profile["emits_system_message"]:
391
- payload["systemMessage"] = system_message
392
- payload["suppressOutput"] = True
393
-
394
- print(json.dumps(payload))
952
+ emit(event, additional_context, system_message)
953
+ else:
954
+ emit(event, f"{additional_context}\n\nTell the user: {system_message}")
395
955
 
396
956
 
397
957
  if __name__ == "__main__":