@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
@@ -0,0 +1,410 @@
1
+ #!/usr/bin/env python3
2
+ """UserPromptSubmit and PostToolUse (Skill, CronCreate) hook: switch an interactive session into "user is away" mode on its own.
3
+
4
+ A session opts in through `awayMode` in ethlete-agents.config.json (the local config file
5
+ overrides it): {"awayMode": {"skills": ["doc-agent"], "thresholdMinutes": 15}}. Without `skills`
6
+ the hook does nothing. A session becomes active when a prompt starts with `/<skill>` or with
7
+ `/handoff resume <skill>-`, or when the Skill tool loads a configured skill (PostToolUse), however the
8
+ session was started.
9
+
10
+ Prompts the agent sessions send themselves (mailbox messages, cross-session messages, task
11
+ notifications, system reminders, the restart prompt, scheduled-task (cron) prompts, found through
12
+ the prompts recorded when CronCreate ran, the transcript's `scheduled_task_fire` entry or its
13
+ start-of-session `session_cron_carry` entry) are not
14
+ human input. The last human-typed
15
+ prompt is stored per session; when a non-human prompt arrives after the threshold, the hook injects
16
+ the away message once and a one-line reminder afterwards. The next human-typed prompt injects the
17
+ back message; with `awayMode.reportCommand` (e.g. `node dist/libs/agent-rules/src/index.js report`)
18
+ it also carries that command's table for the time away (`--since <last typed input>`), left out when the
19
+ command fails or takes over 10 s. A human prompt that is exactly `afk` marks the session away at once.
20
+
21
+ State lives in `<git common dir>/ethlete/away/<session_id>.json`, so it is never committed.
22
+
23
+ Can be disabled per machine via a gitignored ethlete-agents.config.local.json at the repo root:
24
+ {"disableHooks": true} or {"disableHooks": ["away-mode"]}.
25
+
26
+ Fail-safe: any error exits 0 with no output - the hook must never block work because it could
27
+ not read its own input.
28
+ """
29
+
30
+ import json
31
+ import os
32
+ import re
33
+ import shlex
34
+ import subprocess
35
+ import sys
36
+ from datetime import datetime, timezone
37
+
38
+ HOOK_NAME = "away-mode"
39
+ CONFIG_FILE = "ethlete-agents.config.json"
40
+ LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
41
+ DEFAULT_THRESHOLD_MINUTES = 15
42
+ AGENT_SESSIONS_SUFFIX = "[typed by agent-sessions]"
43
+
44
+ BACK_MESSAGE = (
45
+ "The user is back (typed input after {minutes} min away). Leave away mode: put every question you "
46
+ "collected while they were away once, in full, in your round format."
47
+ )
48
+ AWAY_MESSAGE = (
49
+ "The user is away (no typed input for {minutes} min). Work by your skill's away rules: collect "
50
+ "questions, one short line per event, no round. Typed input switches back on its own."
51
+ )
52
+ BACK_REPORT_MESSAGE = (
53
+ " Paste this report for the time away unchanged, then the collected questions:\n\n{report}"
54
+ )
55
+ REPORT_TIMEOUT_SECONDS = 10
56
+ MAX_CRON_PROMPTS = 20
57
+ STILL_AWAY_MESSAGE = "The user is still away (no typed input for {minutes} min)."
58
+
59
+
60
+ def agent_name(argv):
61
+ """The --agent value, defaulting to claude — older registrations pass no flag."""
62
+ for index, arg in enumerate(argv):
63
+ if arg == "--agent" and index + 1 < len(argv):
64
+ return argv[index + 1]
65
+ if arg.startswith("--agent="):
66
+ return arg.split("=", 1)[1]
67
+ return "claude"
68
+
69
+
70
+ def repo_root(data):
71
+ """Repo root: the env var the agent sets, else the script's own location, else the cwd."""
72
+ for variable in ("CLAUDE_PROJECT_DIR", "CODEX_PROJECT_DIR"):
73
+ value = os.environ.get(variable)
74
+ if value:
75
+ return value
76
+ here = os.path.abspath(__file__)
77
+ derived = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(here))))
78
+ if os.path.isfile(os.path.join(derived, LOCAL_CONFIG_FILE)):
79
+ return derived
80
+ cwd = data.get("cwd")
81
+ return cwd if isinstance(cwd, str) and cwd else derived
82
+
83
+
84
+ def load_config(root, file_name):
85
+ """Parsed JSON object at the repo root, or {} if missing/unreadable."""
86
+ if not root:
87
+ return {}
88
+ try:
89
+ with open(os.path.join(root, file_name), encoding="utf-8") as f:
90
+ config = json.load(f)
91
+ except (OSError, ValueError, AttributeError):
92
+ return {}
93
+ return config if isinstance(config, dict) else {}
94
+
95
+
96
+ def load_local_config(root):
97
+ return load_config(root, LOCAL_CONFIG_FILE)
98
+
99
+
100
+ def disabled_locally(config):
101
+ """True when the local config disables this hook (or all hooks) on this machine."""
102
+ disabled = config.get("disableHooks")
103
+ return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
104
+
105
+
106
+ def away_settings(root, local_config):
107
+ """(skills, threshold in minutes); the local config's `awayMode` replaces the shared one."""
108
+ setting = local_config.get("awayMode")
109
+ if not isinstance(setting, dict):
110
+ setting = load_config(root, CONFIG_FILE).get("awayMode")
111
+ if not isinstance(setting, dict):
112
+ return [], DEFAULT_THRESHOLD_MINUTES
113
+ skills = setting.get("skills")
114
+ skills = [s for s in skills if isinstance(s, str) and s] if isinstance(skills, list) else []
115
+ threshold = setting.get("thresholdMinutes")
116
+ if isinstance(threshold, bool) or not isinstance(threshold, (int, float)) or threshold <= 0:
117
+ threshold = DEFAULT_THRESHOLD_MINUTES
118
+ return skills, threshold
119
+
120
+
121
+ def report_command(root, local_config):
122
+ """The configured report command; the local config's `awayMode` replaces the shared one."""
123
+ setting = local_config.get("awayMode")
124
+ if not isinstance(setting, dict):
125
+ setting = load_config(root, CONFIG_FILE).get("awayMode")
126
+ command = setting.get("reportCommand") if isinstance(setting, dict) else None
127
+ return command.strip() if isinstance(command, str) and command.strip() else None
128
+
129
+
130
+ def away_report(root, command, since):
131
+ """The report table since `since`, or None when the command is missing, fails or is too slow."""
132
+ if not command or not since:
133
+ return None
134
+ try:
135
+ result = subprocess.run(
136
+ shlex.split(command) + ["--since", since],
137
+ cwd=root,
138
+ capture_output=True,
139
+ text=True,
140
+ timeout=REPORT_TIMEOUT_SECONDS,
141
+ )
142
+ except Exception:
143
+ return None
144
+ output = result.stdout.strip()
145
+ return output if result.returncode == 0 and output else None
146
+
147
+
148
+ def prompt_fired_before(prompt, transcript_path):
149
+ """A resumed session loses the CronCreate record; its own earlier fire lines still name the prompt."""
150
+ wanted = prompt.strip()
151
+ try:
152
+ with open(transcript_path, encoding="utf-8", errors="ignore") as f:
153
+ for raw in f:
154
+ if '"scheduled_task_fire"' not in raw:
155
+ continue
156
+ try:
157
+ line = json.loads(raw)
158
+ except ValueError:
159
+ continue
160
+ fired = line.get("prompt") if isinstance(line, dict) else None
161
+ if line.get("subtype") == "scheduled_task_fire" and isinstance(fired, str) and fired.strip():
162
+ if wanted.startswith(fired.strip()[:200]):
163
+ return True
164
+ except OSError:
165
+ return False
166
+ return False
167
+
168
+
169
+ def prompt_carried_over(prompt, transcript_path):
170
+ """A resumed or cleared session starts with a `session_cron_carry` entry naming the crons it re-armed."""
171
+ wanted = prompt.strip()
172
+ try:
173
+ with open(transcript_path, encoding="utf-8", errors="ignore") as f:
174
+ for _, raw in zip(range(40), f):
175
+ if '"session_cron_carry"' not in raw:
176
+ continue
177
+ try:
178
+ attachment = json.loads(raw).get("attachment")
179
+ except (ValueError, AttributeError):
180
+ continue
181
+ if not isinstance(attachment, dict):
182
+ continue
183
+ for key in ("tasks", "otherArmed"):
184
+ entries = attachment.get(key)
185
+ for entry in entries if isinstance(entries, list) else []:
186
+ carried = entry.get("prompt") if isinstance(entry, dict) else None
187
+ if isinstance(carried, str) and carried.strip() and wanted.startswith(carried.strip()[:200]):
188
+ return True
189
+ except OSError:
190
+ return False
191
+ return False
192
+
193
+
194
+ def fired_by_schedule(prompt, transcript_path):
195
+ if not isinstance(transcript_path, str):
196
+ return False
197
+ try:
198
+ with open(transcript_path, "rb") as f:
199
+ f.seek(0, 2)
200
+ f.seek(max(0, f.tell() - 65536))
201
+ tail = f.read().decode("utf-8", errors="ignore").splitlines()[-40:]
202
+ except OSError:
203
+ return False
204
+ if prompt_fired_before(prompt, transcript_path) or prompt_carried_over(prompt, transcript_path):
205
+ return True
206
+ for raw in reversed(tail):
207
+ try:
208
+ line = json.loads(raw)
209
+ except ValueError:
210
+ continue
211
+ if not isinstance(line, dict):
212
+ continue
213
+ if line.get("subtype") == "scheduled_task_fire" and isinstance(line.get("prompt"), str):
214
+ return prompt.strip().startswith(line["prompt"].strip()[:200])
215
+ if line.get("type") == "user" and line.get("turnOrigin") == "scheduled":
216
+ return True
217
+ if line.get("type") == "user" and not line.get("isMeta"):
218
+ return False
219
+ return False
220
+
221
+
222
+ def is_human_typed(prompt, transcript_path=None, cron_prompts=()):
223
+ stripped = prompt.strip()
224
+ if stripped in cron_prompts or fired_by_schedule(prompt, transcript_path):
225
+ return False
226
+ return not (
227
+ stripped.startswith("Mailbox message from ")
228
+ or "<cross-session-message" in stripped
229
+ or stripped.endswith(AGENT_SESSIONS_SUFFIX)
230
+ or stripped.startswith("<task-notification")
231
+ or stripped.startswith("<system-reminder")
232
+ )
233
+
234
+
235
+ def record_cron_prompt(path, tool_input):
236
+ cron_prompt = tool_input.get("prompt") if isinstance(tool_input, dict) else None
237
+ if not isinstance(cron_prompt, str) or not cron_prompt.strip():
238
+ return
239
+ state = read_state(path) or {"active": False, "lastHumanInput": None, "away": False}
240
+ recorded = [p for p in cron_prompts_of(state) if p != cron_prompt.strip()]
241
+ recorded.append(cron_prompt.strip())
242
+ state["cronPrompts"] = recorded[-MAX_CRON_PROMPTS:]
243
+ write_state(path, state)
244
+
245
+
246
+ def cron_prompts_of(state):
247
+ recorded = state.get("cronPrompts") if isinstance(state, dict) else None
248
+ return [p for p in recorded if isinstance(p, str)] if isinstance(recorded, list) else []
249
+
250
+
251
+ def invokes_skill(prompt, skills):
252
+ text = prompt.strip()
253
+ if text.endswith(AGENT_SESSIONS_SUFFIX):
254
+ text = text[: -len(AGENT_SESSIONS_SUFFIX)].strip()
255
+ for skill in skills:
256
+ name = re.escape(skill)
257
+ if re.match(rf"/{name}(?![\w-])", text) or re.match(rf"/handoff\s+resume\s+{name}-", text):
258
+ return True
259
+ return False
260
+
261
+
262
+ def state_path(root, session_id):
263
+ result = subprocess.run(
264
+ ["git", "-C", root, "rev-parse", "--path-format=absolute", "--git-common-dir"],
265
+ capture_output=True,
266
+ text=True,
267
+ timeout=3,
268
+ )
269
+ common_dir = result.stdout.strip() if result.returncode == 0 else ""
270
+ if not common_dir:
271
+ return None
272
+ safe_id = re.sub(r"[^\w.-]", "_", str(session_id))
273
+ return os.path.join(common_dir, "ethlete", "away", f"{safe_id}.json")
274
+
275
+
276
+ def read_state(path):
277
+ try:
278
+ with open(path, encoding="utf-8") as f:
279
+ state = json.load(f)
280
+ except (OSError, ValueError):
281
+ return None
282
+ return state if isinstance(state, dict) else None
283
+
284
+
285
+ def write_state(path, state):
286
+ os.makedirs(os.path.dirname(path), exist_ok=True)
287
+ with open(path, "w", encoding="utf-8") as f:
288
+ json.dump(state, f)
289
+
290
+
291
+ def minutes_since(iso, now):
292
+ try:
293
+ then = datetime.fromisoformat(iso)
294
+ except (TypeError, ValueError):
295
+ return None
296
+ if then.tzinfo is None:
297
+ then = then.replace(tzinfo=timezone.utc)
298
+ return max(0, int((now - then).total_seconds() // 60))
299
+
300
+
301
+ def emit(message):
302
+ print(
303
+ json.dumps(
304
+ {"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": message}}
305
+ )
306
+ )
307
+
308
+
309
+ def main():
310
+ if agent_name(sys.argv[1:]) != "claude":
311
+ return
312
+
313
+ data = json.load(sys.stdin)
314
+ prompt = data.get("prompt")
315
+ session_id = data.get("session_id")
316
+ skill_load = data.get("hook_event_name") == "PostToolUse"
317
+
318
+ if not session_id or not (skill_load or isinstance(prompt, str)):
319
+ return
320
+
321
+ root = repo_root(data)
322
+ local_config = load_local_config(root)
323
+
324
+ if disabled_locally(local_config):
325
+ return
326
+
327
+ skills, threshold = away_settings(root, local_config)
328
+
329
+ if not skills:
330
+ return
331
+
332
+ path = state_path(root, session_id)
333
+
334
+ if not path:
335
+ return
336
+
337
+ if skill_load:
338
+ tool_input = data.get("tool_input")
339
+ if data.get("tool_name") == "CronCreate":
340
+ record_cron_prompt(path, tool_input)
341
+ return
342
+ loaded = tool_input.get("skill") if isinstance(tool_input, dict) else None
343
+ loaded = loaded.split(":")[-1] if isinstance(loaded, str) else None
344
+ existing = read_state(path)
345
+ if loaded in skills and not (existing and existing.get("active")):
346
+ write_state(
347
+ path,
348
+ {
349
+ "active": True,
350
+ "lastHumanInput": None,
351
+ "away": False,
352
+ "cronPrompts": cron_prompts_of(existing),
353
+ },
354
+ )
355
+ return
356
+
357
+ now = datetime.now(timezone.utc)
358
+ now_iso = now.isoformat(timespec="seconds")
359
+ state = read_state(path)
360
+ human = is_human_typed(prompt, data.get("transcript_path"), cron_prompts_of(state))
361
+
362
+ if not state or not state.get("active"):
363
+ if not invokes_skill(prompt, skills):
364
+ return
365
+ state = {
366
+ "active": True,
367
+ "lastHumanInput": now_iso if human else None,
368
+ "away": False,
369
+ "cronPrompts": cron_prompts_of(state),
370
+ }
371
+ write_state(path, state)
372
+ return
373
+
374
+ if human:
375
+ was_away = state.get("away") is True
376
+ since = state.get("lastHumanInput")
377
+ minutes = minutes_since(since, now)
378
+ state["lastHumanInput"] = now_iso
379
+ state["away"] = prompt.strip().lower() == "afk"
380
+ write_state(path, state)
381
+ if was_away and not state["away"]:
382
+ message = BACK_MESSAGE.format(minutes=minutes if minutes is not None else threshold)
383
+ report = away_report(root, report_command(root, local_config), since)
384
+ if report:
385
+ message += BACK_REPORT_MESSAGE.format(report=report)
386
+ emit(message)
387
+ return
388
+
389
+ minutes = minutes_since(state.get("lastHumanInput"), now)
390
+
391
+ if minutes is not None and minutes < threshold:
392
+ return
393
+
394
+ shown = minutes if minutes is not None else int(threshold)
395
+
396
+ if state.get("away") is True:
397
+ emit(STILL_AWAY_MESSAGE.format(minutes=shown))
398
+ return
399
+
400
+ state["away"] = True
401
+ write_state(path, state)
402
+ emit(AWAY_MESSAGE.format(minutes=shown))
403
+
404
+
405
+ if __name__ == "__main__":
406
+ try:
407
+ main()
408
+ except Exception:
409
+ pass
410
+ sys.exit(0)
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env python3
2
+ """PreToolUse hook: wait loops run in the background, and sub-agent calls carry their agent id.
3
+
4
+ An `until` or `while` loop whose body runs `sleep` holds the session for the whole wait in the
5
+ foreground and ends at the Bash timeout, so a Bash call that runs one without
6
+ `run_in_background: true` is allowed with that flag set.
7
+
8
+ A Bash call from a sub-agent (hook input `agent_id`) gets `export ET_AGENT_ID=<id>;` prepended, so every
9
+ process it starts carries the id and `agent-sessions stop-own` can tell sibling sub-agents apart. Both
10
+ share one hook because parallel hooks cannot both rewrite one call.
11
+
12
+ Quoted text and heredoc bodies are ignored, so free text that mentions a loop does not trip the hook.
13
+
14
+ Can be disabled per machine via a gitignored ethlete-agents.config.local.json at the repo
15
+ root: {"disableHooks": true} or {"disableHooks": ["background-commands"]}.
16
+
17
+ Fail-safe: any error exits 0 with no output.
18
+ """
19
+
20
+ import json
21
+ import os
22
+ import re
23
+ import sys
24
+
25
+ HOOK_NAME = "background-commands"
26
+ AGENT_STAMP = "ET_AGENT_ID="
27
+ AGENT_ID = re.compile(r"[\w-]+")
28
+ LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
29
+
30
+ QUOTED = re.compile(r"\"(?:\\.|[^\"\\])*\"|'[^']*'")
31
+ HEREDOC = re.compile(r"<<-?\s*(?:\"(\w+)\"|'(\w+)'|\\?(\w+))")
32
+ SEPARATORS = re.compile(r"&&|\|\||[;&|\n(){}`]")
33
+ ASSIGNMENT = re.compile(r"^[A-Za-z_]\w*=")
34
+ LOOP_KEYWORDS = frozenset(("until", "while"))
35
+ LOOP_BODY_KEYWORDS = frozenset(("do", "then", "else"))
36
+
37
+
38
+ def without_heredoc_bodies(command):
39
+ lines = command.split("\n")
40
+ kept = []
41
+ delimiter = None
42
+ for line in lines:
43
+ if delimiter is not None:
44
+ if line.strip() == delimiter:
45
+ delimiter = None
46
+ continue
47
+ kept.append(line)
48
+ match = HEREDOC.search(line)
49
+ if match:
50
+ delimiter = match.group(1) or match.group(2) or match.group(3)
51
+ return "\n".join(kept)
52
+
53
+
54
+ def command_segments(command):
55
+ """The shell string split into simple commands, with heredoc bodies and quoted text removed."""
56
+ text = QUOTED.sub(" ", without_heredoc_bodies(command))
57
+ text = text.replace("$(", ";")
58
+ return [segment.strip() for segment in SEPARATORS.split(text) if segment.strip()]
59
+
60
+
61
+ def agent_name(argv):
62
+ for index, arg in enumerate(argv):
63
+ if arg == "--agent" and index + 1 < len(argv):
64
+ return argv[index + 1]
65
+ if arg.startswith("--agent="):
66
+ return arg.split("=", 1)[1]
67
+ return "claude"
68
+
69
+
70
+ def repo_root(data):
71
+ for variable in ("CLAUDE_PROJECT_DIR", "CODEX_PROJECT_DIR"):
72
+ value = os.environ.get(variable)
73
+ if value:
74
+ return value
75
+ here = os.path.abspath(__file__)
76
+ derived = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(here))))
77
+ if os.path.isfile(os.path.join(derived, LOCAL_CONFIG_FILE)):
78
+ return derived
79
+ cwd = data.get("cwd")
80
+ return cwd if isinstance(cwd, str) and cwd else derived
81
+
82
+
83
+ def load_local_config(root):
84
+ if not root:
85
+ return {}
86
+ try:
87
+ with open(os.path.join(root, LOCAL_CONFIG_FILE), encoding="utf-8") as f:
88
+ config = json.load(f)
89
+ except (OSError, ValueError, AttributeError):
90
+ return {}
91
+ return config if isinstance(config, dict) else {}
92
+
93
+
94
+ def disabled_locally(config):
95
+ disabled = config.get("disableHooks")
96
+ return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
97
+
98
+
99
+ def command_words(segment):
100
+ words = [word for word in segment.split() if not ASSIGNMENT.match(word)]
101
+ while words and words[0] in LOOP_BODY_KEYWORDS:
102
+ words = words[1:]
103
+ return words
104
+
105
+
106
+ def wait_loop_in(command):
107
+ """True when the shell string runs an `until` or `while` loop that sleeps."""
108
+ loop_open = False
109
+ for segment in command_segments(command):
110
+ words = command_words(segment)
111
+ if not words:
112
+ continue
113
+ if words[0] in LOOP_KEYWORDS:
114
+ loop_open = True
115
+ words = words[1:]
116
+ if loop_open and words and os.path.basename(words[0]) == "sleep":
117
+ return True
118
+ if words and words[0] == "done":
119
+ loop_open = False
120
+ return False
121
+
122
+
123
+ def main():
124
+ if agent_name(sys.argv[1:]) != "claude":
125
+ return
126
+
127
+ data = json.load(sys.stdin)
128
+
129
+ if data.get("tool_name") != "Bash":
130
+ return
131
+
132
+ tool_input = data.get("tool_input")
133
+
134
+ if not isinstance(tool_input, dict):
135
+ return
136
+
137
+ command = tool_input.get("command")
138
+
139
+ if not isinstance(command, str):
140
+ return
141
+
142
+ if disabled_locally(load_local_config(repo_root(data))):
143
+ return
144
+
145
+ updated = dict(tool_input)
146
+ reason = None
147
+ agent_id = data.get("agent_id")
148
+
149
+ if isinstance(agent_id, str) and AGENT_ID.fullmatch(agent_id) and AGENT_STAMP not in command:
150
+ updated["command"] = f"export {AGENT_STAMP}{agent_id}; {command}"
151
+
152
+ if tool_input.get("run_in_background") is not True:
153
+ if wait_loop_in(command):
154
+ updated["run_in_background"] = True
155
+ reason = (
156
+ "A loop that sleeps until a condition holds blocks the session, so this call runs with "
157
+ "`run_in_background: true`. Go on with other work; the completion notice wakes you."
158
+ )
159
+
160
+ if updated == tool_input:
161
+ return
162
+
163
+ output = {"hookEventName": "PreToolUse", "updatedInput": updated}
164
+
165
+ if reason:
166
+ output["permissionDecision"] = "allow"
167
+ output["permissionDecisionReason"] = reason
168
+
169
+ print(json.dumps({"hookSpecificOutput": output}))
170
+
171
+
172
+ if __name__ == "__main__":
173
+ try:
174
+ main()
175
+ except Exception:
176
+ pass
177
+ sys.exit(0)