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

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 +847 -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 +413 -0
  8. package/content/hooks/background-commands.py +177 -0
  9. package/content/hooks/builder-idle-check.py +562 -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,413 @@
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
+ MAILBOX_PROMPT = re.compile(r"(?:<pasted_content\b[^>]*>\s*)?Mailbox message from ")
44
+ AGENT_MESSAGE = re.compile(r"(?:Another Claude session sent a message:\s*)?<agent-message(?:\s|>)")
45
+
46
+ BACK_MESSAGE = (
47
+ "The user is back (typed input after {minutes} min away). Leave away mode: put every question you "
48
+ "collected while they were away once, in full, in your round format."
49
+ )
50
+ AWAY_MESSAGE = (
51
+ "The user is away (no typed input for {minutes} min). Work by your skill's away rules: collect "
52
+ "questions, one short line per event, no round. Typed input switches back on its own."
53
+ )
54
+ BACK_REPORT_MESSAGE = (
55
+ " Paste this report for the time away unchanged, then the collected questions:\n\n{report}"
56
+ )
57
+ REPORT_TIMEOUT_SECONDS = 10
58
+ MAX_CRON_PROMPTS = 20
59
+ STILL_AWAY_MESSAGE = "The user is still away (no typed input for {minutes} min)."
60
+
61
+
62
+ def agent_name(argv):
63
+ """The --agent value, defaulting to claude — older registrations pass no flag."""
64
+ for index, arg in enumerate(argv):
65
+ if arg == "--agent" and index + 1 < len(argv):
66
+ return argv[index + 1]
67
+ if arg.startswith("--agent="):
68
+ return arg.split("=", 1)[1]
69
+ return "claude"
70
+
71
+
72
+ def repo_root(data):
73
+ """Repo root: the env var the agent sets, else the script's own location, else the cwd."""
74
+ for variable in ("CLAUDE_PROJECT_DIR", "CODEX_PROJECT_DIR"):
75
+ value = os.environ.get(variable)
76
+ if value:
77
+ return value
78
+ here = os.path.abspath(__file__)
79
+ derived = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(here))))
80
+ if os.path.isfile(os.path.join(derived, LOCAL_CONFIG_FILE)):
81
+ return derived
82
+ cwd = data.get("cwd")
83
+ return cwd if isinstance(cwd, str) and cwd else derived
84
+
85
+
86
+ def load_config(root, file_name):
87
+ """Parsed JSON object at the repo root, or {} if missing/unreadable."""
88
+ if not root:
89
+ return {}
90
+ try:
91
+ with open(os.path.join(root, file_name), encoding="utf-8") as f:
92
+ config = json.load(f)
93
+ except (OSError, ValueError, AttributeError):
94
+ return {}
95
+ return config if isinstance(config, dict) else {}
96
+
97
+
98
+ def load_local_config(root):
99
+ return load_config(root, LOCAL_CONFIG_FILE)
100
+
101
+
102
+ def disabled_locally(config):
103
+ """True when the local config disables this hook (or all hooks) on this machine."""
104
+ disabled = config.get("disableHooks")
105
+ return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
106
+
107
+
108
+ def away_settings(root, local_config):
109
+ """(skills, threshold in minutes); the local config's `awayMode` replaces the shared one."""
110
+ setting = local_config.get("awayMode")
111
+ if not isinstance(setting, dict):
112
+ setting = load_config(root, CONFIG_FILE).get("awayMode")
113
+ if not isinstance(setting, dict):
114
+ return [], DEFAULT_THRESHOLD_MINUTES
115
+ skills = setting.get("skills")
116
+ skills = [s for s in skills if isinstance(s, str) and s] if isinstance(skills, list) else []
117
+ threshold = setting.get("thresholdMinutes")
118
+ if isinstance(threshold, bool) or not isinstance(threshold, (int, float)) or threshold <= 0:
119
+ threshold = DEFAULT_THRESHOLD_MINUTES
120
+ return skills, threshold
121
+
122
+
123
+ def report_command(root, local_config):
124
+ """The configured report command; the local config's `awayMode` replaces the shared one."""
125
+ setting = local_config.get("awayMode")
126
+ if not isinstance(setting, dict):
127
+ setting = load_config(root, CONFIG_FILE).get("awayMode")
128
+ command = setting.get("reportCommand") if isinstance(setting, dict) else None
129
+ return command.strip() if isinstance(command, str) and command.strip() else None
130
+
131
+
132
+ def away_report(root, command, since):
133
+ """The report table since `since`, or None when the command is missing, fails or is too slow."""
134
+ if not command or not since:
135
+ return None
136
+ try:
137
+ result = subprocess.run(
138
+ shlex.split(command) + ["--since", since],
139
+ cwd=root,
140
+ capture_output=True,
141
+ text=True,
142
+ timeout=REPORT_TIMEOUT_SECONDS,
143
+ )
144
+ except Exception:
145
+ return None
146
+ output = result.stdout.strip()
147
+ return output if result.returncode == 0 and output else None
148
+
149
+
150
+ def prompt_fired_before(prompt, transcript_path):
151
+ """A resumed session loses the CronCreate record; its own earlier fire lines still name the prompt."""
152
+ wanted = prompt.strip()
153
+ try:
154
+ with open(transcript_path, encoding="utf-8", errors="ignore") as f:
155
+ for raw in f:
156
+ if '"scheduled_task_fire"' not in raw:
157
+ continue
158
+ try:
159
+ line = json.loads(raw)
160
+ except ValueError:
161
+ continue
162
+ fired = line.get("prompt") if isinstance(line, dict) else None
163
+ if line.get("subtype") == "scheduled_task_fire" and isinstance(fired, str) and fired.strip():
164
+ if wanted.startswith(fired.strip()[:200]):
165
+ return True
166
+ except OSError:
167
+ return False
168
+ return False
169
+
170
+
171
+ def prompt_carried_over(prompt, transcript_path):
172
+ """A resumed or cleared session starts with a `session_cron_carry` entry naming the crons it re-armed."""
173
+ wanted = prompt.strip()
174
+ try:
175
+ with open(transcript_path, encoding="utf-8", errors="ignore") as f:
176
+ for _, raw in zip(range(40), f):
177
+ if '"session_cron_carry"' not in raw:
178
+ continue
179
+ try:
180
+ attachment = json.loads(raw).get("attachment")
181
+ except (ValueError, AttributeError):
182
+ continue
183
+ if not isinstance(attachment, dict):
184
+ continue
185
+ for key in ("tasks", "otherArmed"):
186
+ entries = attachment.get(key)
187
+ for entry in entries if isinstance(entries, list) else []:
188
+ carried = entry.get("prompt") if isinstance(entry, dict) else None
189
+ if isinstance(carried, str) and carried.strip() and wanted.startswith(carried.strip()[:200]):
190
+ return True
191
+ except OSError:
192
+ return False
193
+ return False
194
+
195
+
196
+ def fired_by_schedule(prompt, transcript_path):
197
+ if not isinstance(transcript_path, str):
198
+ return False
199
+ try:
200
+ with open(transcript_path, "rb") as f:
201
+ f.seek(0, 2)
202
+ f.seek(max(0, f.tell() - 65536))
203
+ tail = f.read().decode("utf-8", errors="ignore").splitlines()[-40:]
204
+ except OSError:
205
+ return False
206
+ if prompt_fired_before(prompt, transcript_path) or prompt_carried_over(prompt, transcript_path):
207
+ return True
208
+ for raw in reversed(tail):
209
+ try:
210
+ line = json.loads(raw)
211
+ except ValueError:
212
+ continue
213
+ if not isinstance(line, dict):
214
+ continue
215
+ if line.get("subtype") == "scheduled_task_fire" and isinstance(line.get("prompt"), str):
216
+ return prompt.strip().startswith(line["prompt"].strip()[:200])
217
+ if line.get("type") == "user" and line.get("turnOrigin") == "scheduled":
218
+ return True
219
+ if line.get("type") == "user" and not line.get("isMeta"):
220
+ return False
221
+ return False
222
+
223
+
224
+ def is_human_typed(prompt, transcript_path=None, cron_prompts=()):
225
+ stripped = prompt.strip()
226
+ if stripped in cron_prompts or fired_by_schedule(prompt, transcript_path):
227
+ return False
228
+ return not (
229
+ MAILBOX_PROMPT.match(stripped)
230
+ or AGENT_MESSAGE.match(stripped)
231
+ or "<cross-session-message" in stripped
232
+ or stripped.endswith(AGENT_SESSIONS_SUFFIX)
233
+ or stripped.startswith("<task-notification")
234
+ or stripped.startswith("<system-reminder")
235
+ )
236
+
237
+
238
+ def record_cron_prompt(path, tool_input):
239
+ cron_prompt = tool_input.get("prompt") if isinstance(tool_input, dict) else None
240
+ if not isinstance(cron_prompt, str) or not cron_prompt.strip():
241
+ return
242
+ state = read_state(path) or {"active": False, "lastHumanInput": None, "away": False}
243
+ recorded = [p for p in cron_prompts_of(state) if p != cron_prompt.strip()]
244
+ recorded.append(cron_prompt.strip())
245
+ state["cronPrompts"] = recorded[-MAX_CRON_PROMPTS:]
246
+ write_state(path, state)
247
+
248
+
249
+ def cron_prompts_of(state):
250
+ recorded = state.get("cronPrompts") if isinstance(state, dict) else None
251
+ return [p for p in recorded if isinstance(p, str)] if isinstance(recorded, list) else []
252
+
253
+
254
+ def invokes_skill(prompt, skills):
255
+ text = prompt.strip()
256
+ if text.endswith(AGENT_SESSIONS_SUFFIX):
257
+ text = text[: -len(AGENT_SESSIONS_SUFFIX)].strip()
258
+ for skill in skills:
259
+ name = re.escape(skill)
260
+ if re.match(rf"/{name}(?![\w-])", text) or re.match(rf"/handoff\s+resume\s+{name}-", text):
261
+ return True
262
+ return False
263
+
264
+
265
+ def state_path(root, session_id):
266
+ result = subprocess.run(
267
+ ["git", "-C", root, "rev-parse", "--path-format=absolute", "--git-common-dir"],
268
+ capture_output=True,
269
+ text=True,
270
+ timeout=3,
271
+ )
272
+ common_dir = result.stdout.strip() if result.returncode == 0 else ""
273
+ if not common_dir:
274
+ return None
275
+ safe_id = re.sub(r"[^\w.-]", "_", str(session_id))
276
+ return os.path.join(common_dir, "ethlete", "away", f"{safe_id}.json")
277
+
278
+
279
+ def read_state(path):
280
+ try:
281
+ with open(path, encoding="utf-8") as f:
282
+ state = json.load(f)
283
+ except (OSError, ValueError):
284
+ return None
285
+ return state if isinstance(state, dict) else None
286
+
287
+
288
+ def write_state(path, state):
289
+ os.makedirs(os.path.dirname(path), exist_ok=True)
290
+ with open(path, "w", encoding="utf-8") as f:
291
+ json.dump(state, f)
292
+
293
+
294
+ def minutes_since(iso, now):
295
+ try:
296
+ then = datetime.fromisoformat(iso)
297
+ except (TypeError, ValueError):
298
+ return None
299
+ if then.tzinfo is None:
300
+ then = then.replace(tzinfo=timezone.utc)
301
+ return max(0, int((now - then).total_seconds() // 60))
302
+
303
+
304
+ def emit(message):
305
+ print(
306
+ json.dumps(
307
+ {"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": message}}
308
+ )
309
+ )
310
+
311
+
312
+ def main():
313
+ if agent_name(sys.argv[1:]) != "claude":
314
+ return
315
+
316
+ data = json.load(sys.stdin)
317
+ prompt = data.get("prompt")
318
+ session_id = data.get("session_id")
319
+ skill_load = data.get("hook_event_name") == "PostToolUse"
320
+
321
+ if not session_id or not (skill_load or isinstance(prompt, str)):
322
+ return
323
+
324
+ root = repo_root(data)
325
+ local_config = load_local_config(root)
326
+
327
+ if disabled_locally(local_config):
328
+ return
329
+
330
+ skills, threshold = away_settings(root, local_config)
331
+
332
+ if not skills:
333
+ return
334
+
335
+ path = state_path(root, session_id)
336
+
337
+ if not path:
338
+ return
339
+
340
+ if skill_load:
341
+ tool_input = data.get("tool_input")
342
+ if data.get("tool_name") == "CronCreate":
343
+ record_cron_prompt(path, tool_input)
344
+ return
345
+ loaded = tool_input.get("skill") if isinstance(tool_input, dict) else None
346
+ loaded = loaded.split(":")[-1] if isinstance(loaded, str) else None
347
+ existing = read_state(path)
348
+ if loaded in skills and not (existing and existing.get("active")):
349
+ write_state(
350
+ path,
351
+ {
352
+ "active": True,
353
+ "lastHumanInput": None,
354
+ "away": False,
355
+ "cronPrompts": cron_prompts_of(existing),
356
+ },
357
+ )
358
+ return
359
+
360
+ now = datetime.now(timezone.utc)
361
+ now_iso = now.isoformat(timespec="seconds")
362
+ state = read_state(path)
363
+ human = is_human_typed(prompt, data.get("transcript_path"), cron_prompts_of(state))
364
+
365
+ if not state or not state.get("active"):
366
+ if not invokes_skill(prompt, skills):
367
+ return
368
+ state = {
369
+ "active": True,
370
+ "lastHumanInput": now_iso if human else None,
371
+ "away": False,
372
+ "cronPrompts": cron_prompts_of(state),
373
+ }
374
+ write_state(path, state)
375
+ return
376
+
377
+ if human:
378
+ was_away = state.get("away") is True
379
+ since = state.get("lastHumanInput")
380
+ minutes = minutes_since(since, now)
381
+ state["lastHumanInput"] = now_iso
382
+ state["away"] = prompt.strip().lower() == "afk"
383
+ write_state(path, state)
384
+ if was_away and not state["away"]:
385
+ message = BACK_MESSAGE.format(minutes=minutes if minutes is not None else threshold)
386
+ report = away_report(root, report_command(root, local_config), since)
387
+ if report:
388
+ message += BACK_REPORT_MESSAGE.format(report=report)
389
+ emit(message)
390
+ return
391
+
392
+ minutes = minutes_since(state.get("lastHumanInput"), now)
393
+
394
+ if minutes is not None and minutes < threshold:
395
+ return
396
+
397
+ shown = minutes if minutes is not None else int(threshold)
398
+
399
+ if state.get("away") is True:
400
+ emit(STILL_AWAY_MESSAGE.format(minutes=shown))
401
+ return
402
+
403
+ state["away"] = True
404
+ write_state(path, state)
405
+ emit(AWAY_MESSAGE.format(minutes=shown))
406
+
407
+
408
+ if __name__ == "__main__":
409
+ try:
410
+ main()
411
+ except Exception:
412
+ pass
413
+ 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)