@ethlete/agent-rules 0.1.0-next.6 → 0.1.0-next.60

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