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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +18 -1
  3. package/content/hooks/builder-idle-check.py +18 -2
  4. package/content/hooks/human-wait-check.py +167 -0
  5. package/content/mods/.claude-plugin/marketplace.json +10 -0
  6. package/content/mods/plugins/codex-runs/.claude-plugin/plugin.json +6 -0
  7. package/content/mods/plugins/codex-runs/hooks/hooks.json +1 -0
  8. package/content/mods/plugins/codex-runs/hooks/progress.ts +130 -0
  9. package/content/mods/plugins/codex-runs/hooks/register.tsx +103 -0
  10. package/content/mods/plugins/codex-runs/tsconfig.json +4 -0
  11. package/content/mods/plugins/codex-runs/types/index.d.ts +19 -0
  12. package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +1 -1
  13. package/content/mods/plugins/e2e-progress/hooks/register.tsx +8 -1
  14. package/content/mods/plugins/status-line/.claude-plugin/plugin.json +1 -1
  15. package/content/mods/plugins/status-line/hooks/line.ts +3 -2
  16. package/content/mods/plugins/usage-line/.claude-plugin/plugin.json +6 -0
  17. package/content/mods/plugins/usage-line/hooks/codex.ts +52 -0
  18. package/content/mods/plugins/usage-line/hooks/format.ts +24 -0
  19. package/content/mods/plugins/usage-line/hooks/hooks.json +1 -0
  20. package/content/mods/plugins/usage-line/hooks/register.tsx +67 -0
  21. package/content/mods/plugins/usage-line/tsconfig.json +4 -0
  22. package/content/mods/plugins/usage-line/types/index.d.ts +5 -0
  23. package/content/rules/waiting-on-the-human.md +17 -0
  24. package/content/skills/agent-sessions/SKILL.md +3 -1
  25. package/content/skills/agent-sessions/agent-sessions.mjs +57 -19
  26. package/content/skills/codex-subagent/SKILL.md +8 -0
  27. package/content/skills/codex-subagent/codex-limit.mjs +106 -0
  28. package/package.json +1 -1
  29. package/src/lib/report-command.d.ts +1 -0
  30. package/src/lib/report-command.js +9 -5
  31. package/src/lib/report-command.js.map +1 -1
  32. package/src/lib/targets/claude-mods.js +1 -1
  33. package/src/lib/targets/claude-mods.js.map +1 -1
  34. package/src/lib/targets/hooks-shared.d.ts +2 -0
  35. package/src/lib/targets/hooks-shared.js +15 -6
  36. package/src/lib/targets/hooks-shared.js.map +1 -1
@@ -0,0 +1,52 @@
1
+ type Window = { used_percent: number; resets_at: number };
2
+ export type CodexSample = { at: number; primary: Window; secondary?: Window };
3
+
4
+ const pad = (value: number) => String(value).padStart(2, '0');
5
+
6
+ export function parseCodexLine(line: string): CodexSample | undefined {
7
+ if (!line.includes('"rate_limits"')) return undefined;
8
+ try {
9
+ const event = JSON.parse(line);
10
+ const limits = event?.payload?.rate_limits;
11
+ const at = Date.parse(event.timestamp);
12
+ if (!limits?.primary || limits.limit_id !== 'codex' || Number.isNaN(at)) return undefined;
13
+ return { at, primary: limits.primary, secondary: limits.secondary };
14
+ } catch {
15
+ return undefined;
16
+ }
17
+ }
18
+
19
+ export function latestCodexSample(text: string) {
20
+ let latest: CodexSample | undefined;
21
+ for (const line of text.split('\n')) {
22
+ const sample = parseCodexLine(line);
23
+ if (sample && (!latest || sample.at >= latest.at)) latest = sample;
24
+ }
25
+ return latest;
26
+ }
27
+
28
+ function windowOf(window: Window | undefined, now: number) {
29
+ if (!window) return undefined;
30
+ const resetsAt = window.resets_at * 1000;
31
+ const used = resetsAt <= now ? 0 : window.used_percent;
32
+ return { left: Math.max(0, Math.round(100 - used)), resetsAt, exhausted: used >= 100 };
33
+ }
34
+
35
+ function clock(ms: number, now: number) {
36
+ const date = new Date(ms);
37
+ const time = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
38
+ return date.toDateString() === new Date(now).toDateString()
39
+ ? time
40
+ : `${pad(date.getDate())}.${pad(date.getMonth() + 1)}. ${time}`;
41
+ }
42
+
43
+ export function formatCodex(sample: CodexSample | undefined, now: number) {
44
+ if (!sample) return undefined;
45
+ const fiveHour = windowOf(sample.primary, now);
46
+ const week = windowOf(sample.secondary, now);
47
+ if (!fiveHour) return undefined;
48
+ const mark = fiveHour.exhausted || week?.exhausted ? '⛔ ' : '';
49
+ const reset = fiveHour.exhausted ? ` (${clock(fiveHour.resetsAt, now)})` : '';
50
+ const weekText = week ? ` · wk ${week.left}%${week.exhausted ? ` (${clock(week.resetsAt, now)})` : ''}` : '';
51
+ return `${mark}codex 5h ${fiveHour.left}%${reset}${weekText}`;
52
+ }
@@ -0,0 +1,24 @@
1
+ type RateLimit = { kind: string; percentUsed: number; resetsAt?: string };
2
+
3
+ const pad = (value: number) => String(value).padStart(2, '0');
4
+
5
+ function clock(iso: string | undefined) {
6
+ if (!iso) return '';
7
+ const date = new Date(iso);
8
+ if (Number.isNaN(date.getTime())) return '';
9
+ return ` bis ${pad(date.getHours())}:${pad(date.getMinutes())}`;
10
+ }
11
+
12
+ const percent = (limit: RateLimit | undefined) => (limit ? String(limit.percentUsed) : '?');
13
+
14
+ export function formatUsage(limits: RateLimit[]) {
15
+ const fiveHour = limits.find((limit) => limit.kind === 'five_hour');
16
+ const sevenDay = limits.find((limit) => limit.kind === 'seven_day');
17
+ if (!fiveHour && !sevenDay) return undefined;
18
+ return `5h ${percent(fiveHour)}%${clock(fiveHour?.resetsAt)} · Woche ${percent(sevenDay)}%`;
19
+ }
20
+
21
+ export function statusTextOf(commandText: string | null, usage: string | null) {
22
+ if (!usage) return commandText;
23
+ return commandText ? `${commandText} · ${usage}` : usage;
24
+ }
@@ -0,0 +1 @@
1
+ { "modules": ["./register.tsx"] }
@@ -0,0 +1,67 @@
1
+ import { atom, update } from 'claude-code';
2
+ import type { EngineInterface, Register } from 'claude-code';
3
+
4
+ import { latestCodexSample, formatCodex } from './codex';
5
+ import type { CodexSample } from './codex';
6
+ import { formatUsage, statusTextOf } from './format';
7
+
8
+ const usage = atom({ plugin: 'usage-line', key: 'usage' } as const, null);
9
+
10
+ const CODEX_ROOT = '.codex/sessions';
11
+ const CODEX_REFRESH_MS = 30_000;
12
+ const CODEX_SCAN_FILES = 3;
13
+
14
+ let codexSample: CodexSample | undefined;
15
+ let codexCheckedAt = 0;
16
+
17
+ async function newestDirectory($: EngineInterface, path: string) {
18
+ const entries = await $.fs.list(path).catch(() => []);
19
+ return entries.filter((entry) => entry.kind === 'dir').sort((a, b) => b.name.localeCompare(a.name));
20
+ }
21
+
22
+ async function newestRollouts($: EngineInterface, root: string) {
23
+ for (const year of await newestDirectory($, root)) {
24
+ for (const month of await newestDirectory($, `${root}/${year.name}`)) {
25
+ for (const day of await newestDirectory($, `${root}/${year.name}/${month.name}`)) {
26
+ const dir = `${root}/${year.name}/${month.name}/${day.name}`;
27
+ const files = (await $.fs.list(dir).catch(() => [])).filter((entry) => entry.name.endsWith('.jsonl'));
28
+ if (files.length > 0) {
29
+ return files
30
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
31
+ .slice(0, CODEX_SCAN_FILES)
32
+ .map((f) => `${dir}/${f.name}`);
33
+ }
34
+ }
35
+ }
36
+ }
37
+ return [];
38
+ }
39
+
40
+ async function refreshCodex($: EngineInterface, now: number) {
41
+ if (now - codexCheckedAt < CODEX_REFRESH_MS) return;
42
+ codexCheckedAt = now;
43
+ const home = await $.env.get('HOME');
44
+ if (!home) return;
45
+ let latest: CodexSample | undefined;
46
+ for (const path of await newestRollouts($, `${home}/${CODEX_ROOT}`)) {
47
+ const sample = latestCodexSample(await $.fs.read(path).catch(() => ''));
48
+ if (sample && (!latest || sample.at >= latest.at)) latest = sample;
49
+ }
50
+ codexSample = latest ?? codexSample;
51
+ }
52
+
53
+ export const register: Register = (on) => {
54
+ on('session.measure', async ($, e, next) => {
55
+ const now = await $.clock.now();
56
+ await refreshCodex($, now).catch(() => undefined);
57
+ const parts = [formatUsage(e.rateLimits), formatCodex(codexSample, now)].filter(Boolean);
58
+ const text = parts.length > 0 ? parts.join(' · ') : null;
59
+ await update($, usage, () => text).catch(() => undefined);
60
+ return next(e);
61
+ });
62
+
63
+ on('ui.render', { component: 'StatusLine' }, async ($, e, next) => {
64
+ const text = (await $.state.get({ plugin: 'usage-line', key: 'usage' } as const)).value;
65
+ return next({ ...e, props: { ...e.props, text: statusTextOf(e.props.text, text ?? null) } });
66
+ });
67
+ };
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "../e2e-progress/.claude-plugin/types/tsconfig.json",
3
+ "include": ["hooks"]
4
+ }
@@ -0,0 +1,5 @@
1
+ declare module 'claude-code' {
2
+ interface PluginState {
3
+ 'usage-line': { usage: string | null };
4
+ }
5
+ }
@@ -0,0 +1,17 @@
1
+ ---
2
+ name: waiting-on-the-human
3
+ description: A turn that ends with a question or a `!` command for the human starts the next independent slice first; a recurring allowed action becomes a proposed permission rule.
4
+ kind: rule
5
+ scope: both
6
+ ---
7
+
8
+ ## Waiting on the human
9
+
10
+ A turn that ends with a question or a `! <command>` for the human is not a reason to idle. Before you
11
+ end it, start the next slice that does not need the answer (or a subagent on it), then ask. If every open
12
+ item needs the answer, say which item waits on what. The `human-wait-check` hook blocks such a stop
13
+ once while slots are free and the queue or the resumed handoff's Next steps list work.
14
+
15
+ When the human allows an action the permission mode keeps refusing (a label, a pipeline retry), write
16
+ no memory or handoff note as the fix: propose the exact permission rule for the settings file (for
17
+ example `Bash(glab mr update:*)`) and let the human add it. Never edit a settings permission rule yourself.
@@ -20,7 +20,7 @@ script, so you do not need `<skill-dir>`. The older name `npx ethlete-agents mai
20
20
  ```bash
21
21
  node <skill-dir>/agent-sessions.mjs run <name> <command...> [--role builder] [--dry-run]
22
22
  node <skill-dir>/agent-sessions.mjs up <name>[=<command>]...
23
- node <skill-dir>/agent-sessions.mjs restart <name> [--after <seconds>] [--notify <agent,...>] [--process] [--role builder|none] <prompt...>
23
+ node <skill-dir>/agent-sessions.mjs restart <name> [--after <seconds>] [--notify <agent,...>] [--process [--config <dir>]] [--role builder|none] <prompt...>
24
24
  node <skill-dir>/agent-sessions.mjs down [<name>...]
25
25
  node <skill-dir>/agent-sessions.mjs shell-install [<agent>...] [--file <path>] [--remove] [--dry-run]
26
26
  node <skill-dir>/agent-sessions.mjs shell-init [<agent>...]
@@ -62,6 +62,8 @@ Nothing runs until you start it, so a person who does not use this does nothing.
62
62
 
63
63
  The new process takes the target's role, not the caller's: `--role`, else a resumed `builder-*` or `doc-agent-*` handoff's (`doc-agent-*` is none), else its own. A builder process gets `ETHLETE_AGENT_ROLE=builder` and, for `claude`, the builder system prompt once. A session with no role next to another agent session in the repo, none of them a builder, is refused unless the prompt resumes a `builder-*` or `doc-agent-*` handoff or `--role` is passed (`--role none` restarts it without a role).
64
64
 
65
+ Use `restart <name> --process --config ~/.claude-second <prompt...>` to save a new `CLAUDE_CONFIG_DIR` for the target and resume the handoff with its resolved role. Without `--config`, the process restart still refuses a saved config that differs from the calling agent's config.
66
+
65
67
  `shell-install` writes one shell function per agent into `~/.zshrc` or `~/.bashrc`, between two marker lines. A second run replaces the block, and `--remove` deletes it. Use `--file` for another startup file and `--dry-run` to preview. After a new terminal opens, typing `claude` or `codex` in a repo with this skill runs the agent through `run`. Elsewhere the function starts the plain command. Run `shell-install` only when the user asks: it changes a file the user owns. `shell-init` prints the same functions without writing a file.
66
68
 
67
69
  Choose a `<name>` that no other agent uses, for example `agent-a` or `agent-b`. Two sessions with one name look like one agent.
@@ -69,6 +69,8 @@ const dryRun = takeFlag(args, '--dry-run', false);
69
69
  const role = takeFlag(args, '--role', true);
70
70
  const notify = takeFlag(args, '--notify', true);
71
71
  const newProcess = takeFlag(args, '--process', false);
72
+ const config =
73
+ args[0] === 'restart' && args.includes('--config') ? (takeFlag(args, '--config', true) ?? '') : undefined;
72
74
  const [command, sender, ...words] = args;
73
75
 
74
76
  const help = `Shared agent mailbox: ${mailbox}
@@ -88,10 +90,11 @@ Run: node ${script} run <name> <command...> [--role builder] [--dry-run]
88
90
  Install: node ${script} shell-install [<agent>...] [--file <path>] [--remove] [--dry-run]
89
91
  (write the shell functions into ~/.zshrc or ~/.bashrc)
90
92
  Shell: node ${script} shell-init [<agent>...] (print shell functions that wrap each agent with run; default: claude codex)
91
- Restart: node ${script} restart <name> [--after <seconds>] [--notify <agent,...>] [--process] [--role builder|none] <prompt...>
93
+ Restart: node ${script} restart <name> [--after <seconds>] [--notify <agent,...>] [--process [--config <dir>]] [--role builder|none] <prompt...>
92
94
  (type the clear command and then the prompt into the tmux session of <name>;
93
95
  a long wait on a draft and a give-up go to <name> and each --notify agent;
94
96
  --process ends the agent and starts it again in the same pane with the prompt;
97
+ --config changes the saved CLAUDE_CONFIG_DIR for a process restart;
95
98
  it takes --role, else the role a builder-*/doc-agent-* handoff names, else keeps the role, and refuses
96
99
  a session with no role while another agent session runs in the repo;
97
100
  refuses while a ❓ question of a claude session has no later human message
@@ -179,6 +182,8 @@ const foreignCheckoutsOf = (agent) => [
179
182
  ),
180
183
  ];
181
184
  const createRunSession = (session, shellCommand, baseCommand) => {
185
+ const owner = process.env.CLAUDE_CODE_SESSION_ID;
186
+ const ownerArgs = owner && basename(programOf(words) ?? '') === 'codex' ? ['-e', `ETHLETE_CODEX_OWNER=${owner}`] : [];
182
187
  const result = tmux(
183
188
  'new-session',
184
189
  '-d',
@@ -186,6 +191,7 @@ const createRunSession = (session, shellCommand, baseCommand) => {
186
191
  session,
187
192
  '-c',
188
193
  process.cwd(),
194
+ ...ownerArgs,
189
195
  ...withoutSshEnv(process.env.SHELL || 'sh', '-c', inAgentScopeCommand(shellCommand, session)),
190
196
  );
191
197
  if (result.status !== 0) {
@@ -233,11 +239,7 @@ const CONFIG_WORD = 'CLAUDE_CONFIG_DIR=';
233
239
  const callerConfigDir = () => resolve(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'));
234
240
  const configDirOf = (words) => words.find((word) => word.startsWith(CONFIG_WORD))?.slice(CONFIG_WORD.length);
235
241
  const callerIsAgent = () => Boolean(process.env.CLAUDECODE || process.env.CLAUDE_CONFIG_DIR);
236
- const configMismatch = (words) => {
237
- if (!callerIsAgent()) return false;
238
- const given = configDirOf(words);
239
- return given !== undefined && resolve(given) !== callerConfigDir();
240
- };
242
+ const configMismatch = (dir) => callerIsAgent() && dir !== undefined && resolve(dir) !== callerConfigDir();
241
243
  const callerConfigWords = (words) =>
242
244
  process.env.CLAUDE_CONFIG_DIR && configDirOf(words) === undefined
243
245
  ? [`${CONFIG_WORD}${quote(process.env.CLAUDE_CONFIG_DIR)}`]
@@ -315,6 +317,30 @@ const healedCommand = (command, agent) => {
315
317
  return binary ? `${command} ${quote(binary)}` : null;
316
318
  };
317
319
  const rewrapped = (wrap, head, inner) => `${head}${wrap.shell} ${wrap.flag} ${quote(inner)}`;
320
+ const commandConfigDir = (command) => {
321
+ const wrap = wrapOf(command);
322
+ if (wrap) return commandConfigDir(wrap.inner) ?? configDirOf(wordsOf(wrap.head).reverse());
323
+ const words = wordsOf(command);
324
+ return configDirOf(words.slice(0, programIndexOf(words)).reverse());
325
+ };
326
+ const withoutConfigWords = (tokens) => tokens.filter((token) => !unquoteWord(token).startsWith(CONFIG_WORD));
327
+ const commandWithConfig = (command, dir) => {
328
+ const wrap = wrapOf(command);
329
+ if (wrap) {
330
+ const head = withoutConfigWords(wrap.head.match(SHELL_WORD) ?? [])
331
+ .map((word) => `${word} `)
332
+ .join('');
333
+ return rewrapped(wrap, head, commandWithConfig(wrap.inner, dir));
334
+ }
335
+ const tokens = command.match(SHELL_WORD) ?? [];
336
+ const words = tokens.map(unquoteWord);
337
+ const program = programIndexOf(words);
338
+ const prefix = withoutConfigWords(tokens.slice(0, program));
339
+ const configured = words.slice(0, program).includes('env')
340
+ ? [...prefix, quote(`${CONFIG_WORD}${dir}`)]
341
+ : [`${CONFIG_WORD}${quote(dir)}`, ...prefix];
342
+ return [...configured, ...tokens.slice(program)].join(' ');
343
+ };
318
344
  const commandWithoutPrompt = (command) => {
319
345
  const wrap = wrapOf(command);
320
346
  if (wrap) {
@@ -336,7 +362,6 @@ const restartRoleOf = (session, prompt) => {
336
362
  const found = role ?? handoffRoleOf(prompt) ?? roleOf(session);
337
363
  return found === 'doc-agent' ? null : found;
338
364
  };
339
- const claudeDir = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
340
365
  const isAlive = (pid) => {
341
366
  try {
342
367
  process.kill(pid, 0);
@@ -352,7 +377,7 @@ const readJson = (path) => {
352
377
  return null;
353
378
  }
354
379
  };
355
- const claudeSessionIdOf = (session, own) => {
380
+ const claudeSessionIdOf = (session, own, claudeDir) => {
356
381
  const sessionsDir = join(claudeDir, 'sessions');
357
382
  const live = existsSync(sessionsDir)
358
383
  ? readdirSync(sessionsDir)
@@ -364,7 +389,7 @@ const claudeSessionIdOf = (session, own) => {
364
389
  if (live.length) return live[0].sessionId;
365
390
  return own === session ? process.env.CLAUDE_CODE_SESSION_ID || null : null;
366
391
  };
367
- const transcriptOf = (sessionId) => {
392
+ const transcriptOf = (sessionId, claudeDir) => {
368
393
  const projects = join(claudeDir, 'projects');
369
394
  if (!existsSync(projects)) return null;
370
395
  return (
@@ -418,8 +443,10 @@ const openForHumanOf = (prompt) => {
418
443
  };
419
444
  const droppedQuestions = (session, own, prompt) => {
420
445
  if (session.startsWith('codex')) return [];
421
- const sessionId = claudeSessionIdOf(session, own);
422
- const transcript = sessionId && transcriptOf(sessionId);
446
+ const recorded = agentCommandOf(session);
447
+ const claudeDir = commandConfigDir(healedCommand(recorded, session) ?? recorded) || callerConfigDir();
448
+ const sessionId = claudeSessionIdOf(session, own, claudeDir);
449
+ const transcript = sessionId && transcriptOf(sessionId, claudeDir);
423
450
  if (!transcript) return [];
424
451
  const open = openForHumanOf(prompt) ?? '';
425
452
  return unansweredQuestions(transcript).filter((question) => !open.includes(question));
@@ -459,7 +486,7 @@ const commandWithRole = (command, agentRole) => {
459
486
  ...[...kept, ...rule].map(quote),
460
487
  ].join(' ');
461
488
  };
462
- const LEADING_ENV_WORDS = /^((?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*)/;
489
+ const LEADING_ENV_WORDS = new RegExp(`^((?:[A-Za-z_][A-Za-z0-9_]*=(?:${SHELL_WORD.source})?\\s+)*)`);
463
490
  const bypassingShellFunction = (base) => base.replace(LEADING_ENV_WORDS, '$1command ');
464
491
  const inAgentScope = () => {
465
492
  try {
@@ -759,7 +786,8 @@ const parse = (line) => {
759
786
 
760
787
  const entries = () => (existsSync(mailbox) ? readFileSync(mailbox, 'utf8').split('\n').map(parse).filter(Boolean) : []);
761
788
 
762
- const show = (entry) => process.stdout.write(`[${entry.timestamp}] ${entry.sender}: ${entry.message}\n`);
789
+ const senderLabel = (entry) => (entry.session ? `${entry.sender} (tmux ${entry.session})` : entry.sender);
790
+ const show = (entry) => process.stdout.write(`[${entry.timestamp}] ${senderLabel(entry)}: ${entry.message}\n`);
763
791
 
764
792
  const inboxCursor = (reader) => join(dirname(mailbox), `mailbox.cursor.${reader}`);
765
793
 
@@ -921,7 +949,8 @@ if (command === 'stop-own') {
921
949
  );
922
950
  process.exitCode = 1;
923
951
  } else {
924
- append({ sender, message, ...(recipient ? { to: recipient } : {}) });
952
+ const session = ownSession();
953
+ append({ sender, message, ...(session ? { session } : {}), ...(recipient ? { to: recipient } : {}) });
925
954
  process.stdout.write(`Sent as ${sender}.\n`);
926
955
  }
927
956
  } else if (command === 'up') {
@@ -936,7 +965,7 @@ if (command === 'stop-own') {
936
965
  } else if (command === 'run' && sender && words.length && !hasAgentBinary(words)) {
937
966
  process.stderr.write(`Refused: no agent was started, ${words.join(' ')} has no program to run.\n`);
938
967
  process.exitCode = 1;
939
- } else if (command === 'run' && sender && words.length && configMismatch(words)) {
968
+ } else if (command === 'run' && sender && words.length && configMismatch(configDirOf(words))) {
940
969
  process.stderr.write(
941
970
  `Refused: no agent was started, the command sets CLAUDE_CONFIG_DIR=${configDirOf(words)} but the caller runs under ${callerConfigDir()}. One checkout keeps one config.\n`,
942
971
  );
@@ -1071,7 +1100,11 @@ if (command === 'stop-own') {
1071
1100
  }
1072
1101
  }
1073
1102
  }
1103
+ } else if (config !== undefined && (!newProcess || !config || config.startsWith('-'))) {
1104
+ process.stderr.write('Pass --config <dir> with restart --process.\n');
1105
+ process.exitCode = 1;
1074
1106
  } else if (command === 'restart' && sender && words.length) {
1107
+ const configOverride = config === undefined ? undefined : resolve(config.replace(/^~(?=\/|$)/, () => homedir()));
1075
1108
  const own = process.env.TMUX_PANE
1076
1109
  ? tmux('display-message', '-p', '-t', process.env.TMUX_PANE, '#{session_name}').stdout.trim()
1077
1110
  : null;
@@ -1134,7 +1167,7 @@ if (command === 'stop-own') {
1134
1167
  restartNotice(`restart of ${session} refused, its stored command has no agent program: ${recorded}`);
1135
1168
  process.exit(1);
1136
1169
  }
1137
- if (configMismatch(stored.split(' ').map((word) => word.replaceAll("'", '')))) {
1170
+ if (configOverride === undefined && configMismatch(commandConfigDir(stored))) {
1138
1171
  restartNotice(
1139
1172
  `restart of ${session} refused, its command sets another CLAUDE_CONFIG_DIR than the caller (${callerConfigDir()})`,
1140
1173
  );
@@ -1146,7 +1179,8 @@ if (command === 'stop-own') {
1146
1179
  }
1147
1180
  const staleRole =
1148
1181
  !restartRole && (roleOf(session) !== null || role === 'none' || handoffRoleOf(words.join(' ')) === 'doc-agent');
1149
- const base = withTempDir(restartRole || staleRole ? commandWithRole(stored, restartRole) : stored);
1182
+ const configured = configOverride === undefined ? stored : commandWithConfig(stored, configOverride);
1183
+ const base = withTempDir(restartRole || staleRole ? commandWithRole(configured, restartRole) : configured);
1150
1184
  if (restartRole) tmux('set-option', '-t', pane, ROLE_OPTION, restartRole);
1151
1185
  else if (staleRole) tmux('set-option', '-u', '-t', pane, ROLE_OPTION);
1152
1186
  tmux('set-option', '-p', '-t', pane, 'remain-on-exit', 'on');
@@ -1227,7 +1261,11 @@ if (command === 'stop-own') {
1227
1261
  if (own && own !== session) restartLog(`peer restart: ${own} restarted ${session}`);
1228
1262
  const delay = Number(afterSeconds ?? RESTART_AFTER_SECONDS);
1229
1263
  const forward = notify ? ['--notify', notify] : [];
1230
- const mode = [...(newProcess ? ['--process'] : []), ...(role ? ['--role', role] : [])];
1264
+ const mode = [
1265
+ ...(newProcess ? ['--process'] : []),
1266
+ ...(configOverride === undefined ? [] : ['--config', configOverride]),
1267
+ ...(role ? ['--role', role] : []),
1268
+ ];
1231
1269
  const child = spawn(
1232
1270
  process.execPath,
1233
1271
  [script, 'restart', sender, '--now', '--after', String(delay), ...forward, ...mode, ...words],
@@ -1291,7 +1329,7 @@ if (command === 'stop-own') {
1291
1329
  '-t',
1292
1330
  `=${session}:`,
1293
1331
  '-l',
1294
- `Mailbox message from ${entry.sender}: ${normalize(String(entry.message ?? ''))}`,
1332
+ `Mailbox message from ${senderLabel(entry)}: ${normalize(String(entry.message ?? ''))}`,
1295
1333
  ]);
1296
1334
  sleep(ENTER_DELAY_MS);
1297
1335
  spawnSync('tmux', ['send-keys', '-t', `=${session}:`, 'Enter']);
@@ -17,6 +17,14 @@ beside your own. Use it also when the Claude usage limit is close, because a Cod
17
17
  draw on it - move the delegatable work there and keep the limit for the work you lead. For
18
18
  everything else, a Claude subagent stays the cheaper choice.
19
19
 
20
+ ## Check the limit first
21
+
22
+ Run `node <skill-dir>/codex-limit.mjs` before every Codex start. It prints the share left of the
23
+ 5h and the weekly limit with their reset times, from the rollout files under `~/.codex`. Exit
24
+ code 1 means a window is exhausted: do not start Codex, use a Claude subagent instead, and do not
25
+ ask first. Exit code 2 means no data; start Codex as usual. The numbers come from the last Codex
26
+ call, so a window that has passed its reset time counts as full.
27
+
20
28
  ## The call
21
29
 
22
30
  The wrapper is {%resource:codex-agent.mjs%}. It keeps the Codex trace in a log file and prints
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Print how much of the Codex 5h and weekly limit is left and when each resets.
4
+ * Exit code 0 when Codex can start a task, 1 when a window is exhausted, 2 without data.
5
+ *
6
+ * Usage: node codex-limit.mjs [--json]
7
+ */
8
+
9
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
10
+ import { homedir } from 'node:os';
11
+ import { join } from 'node:path';
12
+ import { pathToFileURL } from 'node:url';
13
+
14
+ const SCAN_FILES = 12;
15
+ const EXHAUSTED_AT = 100;
16
+
17
+ /** Reads the `codex` rate limits out of one rollout line, or undefined when the line carries none. */
18
+ export function parseRateLimitLine(line) {
19
+ if (!line.includes('"rate_limits"')) return undefined;
20
+ let event;
21
+ try {
22
+ event = JSON.parse(line);
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ const limits = event?.payload?.rate_limits;
27
+ if (!limits?.primary || limits.limit_id !== 'codex') return undefined;
28
+ const at = Date.parse(event.timestamp);
29
+ if (Number.isNaN(at)) return undefined;
30
+ return { at, primary: limits.primary, secondary: limits.secondary };
31
+ }
32
+
33
+ /** Turns a window into what is left now: a window past its reset is full again. */
34
+ export function windowStatus(window, now) {
35
+ if (!window) return undefined;
36
+ const resetsAt = window.resets_at * 1000;
37
+ const expired = resetsAt <= now;
38
+ const usedPercent = expired ? 0 : window.used_percent;
39
+ return { leftPercent: Math.max(0, 100 - usedPercent), resetsAt, exhausted: usedPercent >= EXHAUSTED_AT };
40
+ }
41
+
42
+ export function limitStatus(sample, now) {
43
+ if (!sample) return undefined;
44
+ const fiveHour = windowStatus(sample.primary, now);
45
+ const week = windowStatus(sample.secondary, now);
46
+ return { fiveHour, week, exhausted: Boolean(fiveHour?.exhausted || week?.exhausted), sampledAt: sample.at };
47
+ }
48
+
49
+ function rolloutFiles(root) {
50
+ const found = [];
51
+ const walk = (dir) => {
52
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
53
+ const path = join(dir, entry.name);
54
+ if (entry.isDirectory()) walk(path);
55
+ else if (entry.name.endsWith('.jsonl')) found.push({ path, mtime: statSync(path).mtimeMs });
56
+ }
57
+ };
58
+ try {
59
+ walk(root);
60
+ } catch {
61
+ return [];
62
+ }
63
+ return found.sort((a, b) => b.mtime - a.mtime).slice(0, SCAN_FILES);
64
+ }
65
+
66
+ /** The newest rate-limit sample in the most recently written rollout files. */
67
+ export function latestSample(sessionsRoot) {
68
+ let latest;
69
+ for (const file of rolloutFiles(sessionsRoot)) {
70
+ for (const line of readFileSync(file.path, 'utf8').split('\n')) {
71
+ const sample = parseRateLimitLine(line);
72
+ if (sample && (!latest || sample.at >= latest.at)) latest = sample;
73
+ }
74
+ }
75
+ return latest;
76
+ }
77
+
78
+ const pad = (value) => String(value).padStart(2, '0');
79
+
80
+ function clock(ms, now) {
81
+ const date = new Date(ms);
82
+ const time = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
83
+ const sameDay = date.toDateString() === new Date(now).toDateString();
84
+ return sameDay ? time : `${pad(date.getDate())}.${pad(date.getMonth() + 1)}. ${time}`;
85
+ }
86
+
87
+ export function formatStatus(status, now) {
88
+ const part = (label, window) =>
89
+ window ? `${label} ${window.leftPercent}% left, resets ${clock(window.resetsAt, now)}` : `${label} unknown`;
90
+ const verdict = status.exhausted ? 'exhausted: use a Claude subagent' : 'ok';
91
+ return `${part('5h', status.fiveHour)}\n${part('week', status.week)}\nverdict: ${verdict}`;
92
+ }
93
+
94
+ function main() {
95
+ const now = Date.now();
96
+ const sample = latestSample(join(process.env.CODEX_HOME ?? join(homedir(), '.codex'), 'sessions'));
97
+ const status = limitStatus(sample, now);
98
+ if (!status) {
99
+ console.log('verdict: unknown (no Codex rate-limit data found), treat Codex as available');
100
+ process.exit(2);
101
+ }
102
+ console.log(process.argv.includes('--json') ? JSON.stringify(status) : formatStatus(status, now));
103
+ process.exit(status.exhausted ? 1 : 0);
104
+ }
105
+
106
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ethlete/agent-rules",
3
- "version": "0.1.0-next.49",
3
+ "version": "0.1.0-next.50",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ethlete-io/ethdk",
@@ -7,6 +7,7 @@ export type ReportOptions = {
7
7
  from: Date;
8
8
  to: Date;
9
9
  planFiles: string[];
10
+ now?: Date;
10
11
  ci: (query: {
11
12
  branch: string;
12
13
  from: Date;
@@ -168,7 +168,8 @@ const shaCell = (commits) => {
168
168
  const latest = commits[commits.length - 1];
169
169
  return commits.length > 1 ? `${latest.sha} +${commits.length - 1}` : latest.sha;
170
170
  };
171
- const readSlice = (root) => {
171
+ const SLICE_STALE_MS = 2 * 60 * 60 * 1000;
172
+ const readSlice = (root, now) => {
172
173
  var _a, _b, _c, _d;
173
174
  const path = git(root, 'rev-parse', '--git-path', 'slice-paths');
174
175
  if (!path || !(0, fs_1.existsSync)((0, path_1.resolve)(root, path)))
@@ -178,7 +179,10 @@ const readSlice = (root) => {
178
179
  const written = (_d = (_c = /^#\s*written:\s*(.+)$/m.exec(text)) === null || _c === void 0 ? void 0 : _c[1]) === null || _d === void 0 ? void 0 : _d.trim();
179
180
  if (!name)
180
181
  return null;
181
- return { name, since: written ? parseMoment(written) : null };
182
+ const since = written ? parseMoment(written) : null;
183
+ if (!since || now.getTime() - since.getTime() > SLICE_STALE_MS)
184
+ return null;
185
+ return { name, since };
182
186
  };
183
187
  const readSubagentStarts = (root, { from, to }) => {
184
188
  var _a;
@@ -228,7 +232,7 @@ const ghCiResult = ({ branch, from, to }) => {
228
232
  };
229
233
  exports.ghCiResult = ghCiResult;
230
234
  const buildReport = (options) => {
231
- var _a, _b, _c, _d;
235
+ var _a, _b, _c, _d, _e;
232
236
  const { root, from, to } = options;
233
237
  const commits = readCommits(root, { from, to });
234
238
  const plan = readPlan(root, options.planFiles);
@@ -280,7 +284,7 @@ const buildReport = (options) => {
280
284
  const branch = (_d = git(root, 'rev-parse', '--abbrev-ref', 'HEAD')) !== null && _d !== void 0 ? _d : '';
281
285
  const ci = branch ? options.ci({ branch, from, to }) : null;
282
286
  const starts = readSubagentStarts(root, { from, to });
283
- const slice = readSlice(root);
287
+ const slice = readSlice(root, (_e = options.now) !== null && _e !== void 0 ? _e : new Date());
284
288
  const figures = [
285
289
  `${commits.length} Commits${types.length ? ` (${types.join(', ')})` : ''}`,
286
290
  ...(reverts ? [`${reverts} ${reverts === 1 ? 'Revert' : 'Reverts'}`] : []),
@@ -305,7 +309,7 @@ const reportCommand = (options) => {
305
309
  console.error('ethlete-agents report must run inside a git repository.');
306
310
  return 1;
307
311
  }
308
- console.log((0, exports.buildReport)(Object.assign(Object.assign({ root: top }, period), { planFiles: (_b = (0, config_1.readReportConfig)(options.root).planFiles) !== null && _b !== void 0 ? _b : [], ci: (_c = options.ci) !== null && _c !== void 0 ? _c : exports.ghCiResult })));
312
+ console.log((0, exports.buildReport)(Object.assign(Object.assign({ root: top }, period), { planFiles: (_b = (0, config_1.readReportConfig)(options.root).planFiles) !== null && _b !== void 0 ? _b : [], now: options.now, ci: (_c = options.ci) !== null && _c !== void 0 ? _c : exports.ghCiResult })));
309
313
  return 0;
310
314
  };
311
315
  exports.reportCommand = reportCommand;