@ethlete/agent-rules 0.1.0-next.39 → 0.1.0-next.40

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # @ethlete/agent-rules
2
2
 
3
+ ## 0.1.0-next.40
4
+
5
+ ### Patch Changes
6
+
7
+ - `agent-sessions restart` takes the `--process` path when the pane shows background shells or agents, so their reports no longer start a turn in a cleared session.
8
+ - `restart` heals a stored command without an agent program (written by an older `run`) or refuses before stopping the session, and `run` exits non-zero with a message when it started no agent.
9
+ - `agent-sessions restart` (also with `--process`) starts the mailbox dispatcher when none runs for the checkout, so a session that was restarted into a repo without one still receives messages.
10
+ - `agent-sessions run` inside tmux switches your client to the new session or refuses a duplicate, and keeps one `CLAUDE_CONFIG_DIR` per checkout.
11
+ - Keep the agent binary in the command `agent-sessions run` stores when it follows an `env` wrapper, so `restart --process` starts the agent again.
12
+
3
13
  ## 0.1.0-next.39
4
14
 
5
15
  ### Minor Changes
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "e2e-progress",
3
- "version": "0.1.0-next.39",
3
+ "version": "0.1.0-next.40",
4
4
  "description": "Live Playwright e2e progress from a run log, as a status line entry and a pane",
5
5
  "types": "./types/index.d.ts"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "status-line",
3
- "version": "0.1.0-next.39",
3
+ "version": "0.1.0-next.40",
4
4
  "description": "Always-visible band with the running task, its duration, the open queue, open questions and a CI blocked mark",
5
5
  "types": "./types/index.d.ts"
6
6
  }
@@ -45,11 +45,11 @@ Nothing runs until you start it, so a person who does not use this does nothing.
45
45
 
46
46
  ## Sessions
47
47
 
48
- `run <name> <command...>` starts the command in the `tmux` session `<name>@<repo>`, or attaches if it runs already. It also starts the dispatcher when none runs. Session names carry the repo name, so `codex` in two repos never collides. If that session has a terminal attached already, `run` starts `<name>-2`, then `<name>-3`, and so on. A detached session is attached again. Without a terminal, for example from an agent's shell tool, `run` starts the session detached and prints how to attach. `--role builder` sets `ETHLETE_AGENT_ROLE=builder` and, for `claude`, appends a system prompt that keeps the chat silent and sends reports to the grill session. Every agent `run` starts, and every process `restart --process` starts, gets `CLAUDE_CODE_TMPDIR=~/.cache/claude-tmp`, so a full `/tmp` does not stop its shell. `--dry-run` prints the command instead of starting it. So a second `claude` terminal gets its own agent.
48
+ `run <name> <command...>` starts the command in the `tmux` session `<name>@<repo>`, or attaches if it runs already. It also starts the dispatcher when none runs, as do `up` and `restart`. Session names carry the repo name, so `codex` in two repos never collides. If that session has a terminal attached already, `run` starts `<name>-2`, then `<name>-3`, and so on. A detached session is attached again. Without a terminal, for example from an agent's shell tool, `run` starts the session detached and prints how to attach. `--role builder` sets `ETHLETE_AGENT_ROLE=builder` and, for `claude`, appends a system prompt that keeps the chat silent and sends reports to the grill session. Every agent `run` starts, and every process `restart --process` starts, gets `CLAUDE_CODE_TMPDIR=~/.cache/claude-tmp`, so a full `/tmp` does not stop its shell. `--dry-run` prints the command instead of starting it.
49
49
 
50
50
  `up codex=codex gemini=gemini` starts a detached `tmux` session per agent, named like its sender name, and runs the command in it. It also starts a session named `mailbox-dispatch` that runs `dispatch`. A running session is left alone. Attach to a session with `tmux attach -t <name>`. Detach with `Ctrl-b`, then `d`. The session and its agent keep running. Use `down` to stop the dispatcher and the named sessions.
51
51
 
52
- `restart <name> <prompt...>` types the clear command (`/clear`, or `/new` for a `codex` name) and then the prompt into the session `<name>@<repo>`. An agent uses it to clear itself and resume from its saved work state. The command returns at once, so end your turn after it. While a restart of a session is pending, a second one is refused, and the dispatcher types no message into that session until the resumed agent started its first turn; the marker is `.ethlete/restart.lock.<session>`.
52
+ `restart <name> <prompt...>` types the clear command (`/clear`, or `/new` for a `codex` name) and then the prompt into the session `<name>@<repo>`. With background shells or agents in the pane it takes the `--process` path and logs why. The command returns at once, so end your turn after it. While a restart is pending, a second one is refused, and the dispatcher types no message into that session until the resumed agent started its first turn; the marker is `.ethlete/restart.lock.<session>`.
53
53
 
54
54
  - **When it types.** No sooner than `--after` seconds (default 5), and only when the pane is idle and its prompt holds no typed text. It gives up after 30 minutes. The prompt is the text between the two rules of the input box; the background-agent panel below does not count (it presses Up out of that panel and clears the line with C-u first).
55
55
  - **Busy.** A pane is busy only when "esc to interrupt" or "Waiting for" shows in the spinner line above the input box or in the footer below it (a turn that waits on background agents is busy). A chat line that starts with `●` or `⎿` never counts, so an agent that ends its turn with its own "Waiting for ..." text is idle.
@@ -40,6 +40,7 @@ const RESTART_DRAFT_NOTICE_MS = Number(process.env.AGENT_RESTART_DRAFT_NOTICE_MS
40
40
  const RESTART_CLEAR_WAIT_MS = Number(process.env.AGENT_RESTART_CLEAR_WAIT_MS ?? 60 * 1000);
41
41
  const RESTART_EXIT_WAIT_MS = Number(process.env.AGENT_RESTART_EXIT_WAIT_MS ?? 30 * 1000);
42
42
  const RESTART_RESUME_WAIT_MS = Number(process.env.AGENT_RESTART_RESUME_WAIT_MS ?? 60 * 1000);
43
+ const RUN_EXIT_CHECK_MS = Number(process.env.AGENT_RUN_EXIT_CHECK_MS ?? 400);
43
44
  const RESTART_LOCK_MS = Number(process.env.AGENT_RESTART_LOCK_MS ?? RESTART_WAIT_MS + 10 * 60 * 1000);
44
45
  const repoSlug = basename(root).replace(/[.:]/g, '-');
45
46
  const sessionFor = (agent) => `${agent}@${repoSlug}`;
@@ -162,6 +163,21 @@ const foreignCheckoutsOf = (agent) => [
162
163
  .filter(Boolean),
163
164
  ),
164
165
  ];
166
+ const createRunSession = (session, shellCommand, baseCommand) => {
167
+ const result = tmux('new-session', '-d', '-s', session, '-c', process.cwd(), shellCommand);
168
+ if (result.status !== 0) {
169
+ process.stderr.write(`No agent was started: tmux could not create ${session}: ${result.stderr.trim()}\n`);
170
+ process.exitCode = 1;
171
+ return;
172
+ }
173
+ tmux('set-option', '-t', `=${session}:`, COMMAND_OPTION, baseCommand);
174
+ if (role) tmux('set-option', '-t', `=${session}:`, ROLE_OPTION, role);
175
+ sleep(RUN_EXIT_CHECK_MS);
176
+ if (!sessionExists(session)) {
177
+ process.stderr.write(`No agent stayed up: ${session} ended right after the start of ${baseCommand}\n`);
178
+ process.exitCode = 1;
179
+ }
180
+ };
165
181
  const ONE_SHOT_FLAGS = new Set(['-p', '--print', '-v', '--version', '-h', '--help']);
166
182
  const hasTerminal = Boolean(process.stdin.isTTY && process.stdout.isTTY);
167
183
  const runsInSession = (agentArgs) => !agentArgs.some((arg) => ONE_SHOT_FLAGS.has(arg));
@@ -170,15 +186,47 @@ const withoutPrompt = (words) => {
170
186
  const separator = words.indexOf('--');
171
187
  if (separator > 0) return words.slice(0, separator);
172
188
  const [previous, last] = words.slice(-2);
189
+ let binary = 0;
190
+ while (
191
+ binary < words.length - 1 &&
192
+ (ENV_WORD.test(words[binary]) ||
193
+ words[binary] === 'env' ||
194
+ (binary > 0 && words[0] === 'env' && words[binary].startsWith('-')))
195
+ )
196
+ binary++;
173
197
  const isPrompt =
174
- words.length > 1 &&
198
+ words.length - 1 > binary &&
175
199
  !last.startsWith('-') &&
176
200
  (!previous.startsWith('-') || (/\s/.test(last) && !TEXT_VALUE_FLAGS.has(previous)));
177
201
  return isPrompt ? words.slice(0, -1) : words;
178
202
  };
179
203
  const SHELL_WORD = /(?:'[^']*'|\\.|[^\s'\\])+/g;
180
204
  const ENV_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/;
205
+ const CONFIG_WORD = 'CLAUDE_CONFIG_DIR=';
206
+ const callerConfigDir = () => resolve(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'));
207
+ const configDirOf = (words) => words.find((word) => word.startsWith(CONFIG_WORD))?.slice(CONFIG_WORD.length);
208
+ const configMismatch = (words) => {
209
+ const given = configDirOf(words);
210
+ return given !== undefined && resolve(given) !== callerConfigDir();
211
+ };
181
212
  const unquoteWord = (word) => word.replace(/'([^']*)'|\\(.)/g, (_, quoted, escaped) => quoted ?? escaped);
213
+ const hasAgentBinary = (words) => {
214
+ let index = 0;
215
+ while (
216
+ index < words.length &&
217
+ (ENV_WORD.test(words[index]) ||
218
+ words[index] === 'env' ||
219
+ (index > 0 && words.includes('env') && words[index].startsWith('-')))
220
+ )
221
+ index++;
222
+ return index < words.length;
223
+ };
224
+ const healedCommand = (command, agent) => {
225
+ const words = [...command.matchAll(SHELL_WORD)].map(([word]) => unquoteWord(word));
226
+ if (hasAgentBinary(words)) return command;
227
+ const binary = agent.match(/^(claude|codex)/)?.[1];
228
+ return binary ? `${command} ${quote(binary)}` : null;
229
+ };
182
230
  const commandWithoutPrompt = (command) => {
183
231
  const tokens = [...command.matchAll(SHELL_WORD)];
184
232
  const program = tokens.findIndex(([word]) => !ENV_WORD.test(word));
@@ -310,6 +358,7 @@ const commandWithRole = (command, agentRole) => {
310
358
  const bypassingShellFunction = (base) => base.replace(/^((?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*)/, '$1command ');
311
359
  const EXIT_DIALOG_JOBS = /will stop when you exit/i;
312
360
  const EXIT_AND_STOP = /exit and stop/i;
361
+ const BACKGROUND_FOOTER = /\b\d+ (?:shells?|agents?)\b|↓ to manage/i;
313
362
 
314
363
  /**
315
364
  * Reads the last prompt line (`❯` for Claude Code, `›` for Codex) of the pane. Dim text is the empty
@@ -389,6 +438,11 @@ const waitForQuiet = (session, limitMs = RESTART_WAIT_MS, allowBusy = false) =>
389
438
  return false;
390
439
  };
391
440
 
441
+ const backgroundWorkOf = (lines) => {
442
+ const footer = lines.slice(lastRuleIndex(lines) + 1).map(plain);
443
+ return footer.find((line) => BACKGROUND_FOOTER.test(line) || isPanelRow(line))?.trim() ?? null;
444
+ };
445
+
392
446
  /** The IDE context chip (`[⧉ In file.ts]`, `[⧉ 3 lines selected]`) shares the prompt line and survives `/clear`. */
393
447
  const IDE_CHIP = /\[⧉ [^\]]*\]/g;
394
448
  const plain = (line) => line.replace(new RegExp(SGR, 'g'), '');
@@ -484,6 +538,13 @@ const startSession = (name, shellCommand, quiet = false) => {
484
538
  if (!quiet) process.stdout.write(`Started ${name}. Attach with: tmux attach -t ${name}\n`);
485
539
  };
486
540
 
541
+ const ensureDispatch = (quiet = true) =>
542
+ startSession(
543
+ DISPATCH_SESSION,
544
+ `${process.env.AGENT_MAILBOX ? `AGENT_MAILBOX=${quote(process.env.AGENT_MAILBOX)} ` : ''}node ${quote(script)} dispatch`,
545
+ quiet,
546
+ );
547
+
487
548
  const IGNORED = ['mailbox.jsonl', 'mailbox.cursor.*', 'restart.log', 'restart.prompt.*', 'restart.lock.*'];
488
549
 
489
550
  const prepare = () => {
@@ -576,8 +637,7 @@ if (command === 'send' && sender) {
576
637
  process.stdout.write(`Sent as ${sender}.\n`);
577
638
  }
578
639
  } else if (command === 'up') {
579
- const withEnv = process.env.AGENT_MAILBOX ? `AGENT_MAILBOX=${quote(process.env.AGENT_MAILBOX)} ` : '';
580
- startSession(DISPATCH_SESSION, `${withEnv}node ${quote(script)} dispatch`);
640
+ ensureDispatch(false);
581
641
  [sender, ...words].filter(Boolean).forEach((spec) => {
582
642
  const [name, ...rest] = spec.split('=');
583
643
  startSession(sessionFor(name), rest.join('=') || undefined);
@@ -585,6 +645,14 @@ if (command === 'send' && sender) {
585
645
  } else if (command === 'run' && sender && words.length && role !== undefined && role !== 'builder') {
586
646
  process.stderr.write(`Unknown role ${role}. Only builder exists.\n`);
587
647
  process.exitCode = 1;
648
+ } else if (command === 'run' && sender && words.length && !hasAgentBinary(words)) {
649
+ process.stderr.write(`Refused: no agent was started, ${words.join(' ')} has no program to run.\n`);
650
+ process.exitCode = 1;
651
+ } else if (command === 'run' && sender && words.length && configMismatch(words)) {
652
+ process.stderr.write(
653
+ `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`,
654
+ );
655
+ process.exitCode = 1;
588
656
  } else if (command === 'run' && sender && words.length && dryRun) {
589
657
  process.stdout.write(`${withTempDir([...roleEnvWords(role), ...withRole(words).map(quote)].join(' '))}\n`);
590
658
  } else if (command === 'run' && sender && words.length && !runsInSession(words.slice(1))) {
@@ -599,28 +667,25 @@ if (command === 'send' && sender) {
599
667
  },
600
668
  }).status ?? 1;
601
669
  } else if (command === 'run' && sender && words.length) {
602
- const withEnv = process.env.AGENT_MAILBOX ? `AGENT_MAILBOX=${quote(process.env.AGENT_MAILBOX)} ` : '';
603
- if (!sessionExists(DISPATCH_SESSION))
604
- startSession(DISPATCH_SESSION, `${withEnv}node ${quote(script)} dispatch`, true);
670
+ ensureDispatch();
605
671
  const session = freeSessionFor(sender);
606
- const roleEnv = roleEnvWords(role)
672
+ const roleEnv = [
673
+ ...(process.env.CLAUDE_CONFIG_DIR && configDirOf(words) === undefined
674
+ ? [`${CONFIG_WORD}${quote(process.env.CLAUDE_CONFIG_DIR)}`]
675
+ : []),
676
+ ...roleEnvWords(role),
677
+ ]
607
678
  .map((word) => `${word} `)
608
679
  .join('');
609
680
  const shellCommand = withTempDir(`${roleEnv}${withRole(words).map(quote).join(' ')}`);
610
681
  const baseCommand = withTempDir(`${roleEnv}${withRole(withoutPrompt(words)).map(quote).join(' ')}`);
611
- if (!hasTerminal) {
612
- if (!sessionExists(session)) {
613
- tmux('new-session', '-d', '-s', session, '-c', process.cwd(), shellCommand);
614
- tmux('set-option', '-t', `=${session}:`, COMMAND_OPTION, baseCommand);
615
- if (role) tmux('set-option', '-t', `=${session}:`, ROLE_OPTION, role);
616
- }
617
- process.stdout.write(`Started ${session}. Attach with: tmux attach -t ${session}\n`);
618
- } else if (process.env.TMUX) {
619
- if (!sessionExists(session)) {
620
- tmux('new-session', '-d', '-s', session, '-c', process.cwd(), shellCommand);
621
- tmux('set-option', '-t', `=${session}:`, COMMAND_OPTION, baseCommand);
622
- if (role) tmux('set-option', '-t', `=${session}:`, ROLE_OPTION, role);
623
- }
682
+ if (process.env.TMUX) {
683
+ if (sessionExists(session)) {
684
+ process.stderr.write(
685
+ `Refused: ${session} already exists, no second agent was started. Switch to it with: tmux switch-client -t ${session}\n`,
686
+ );
687
+ process.exitCode = 1;
688
+ } else createRunSession(session, shellCommand, baseCommand);
624
689
  const callerSession = tmux(
625
690
  'display-message',
626
691
  '-p',
@@ -631,19 +696,20 @@ if (command === 'send' && sender) {
631
696
  const [callerClient] = callerSession
632
697
  ? tmux('list-clients', '-t', callerSession, '-F', '#{client_tty}').stdout.split('\n').filter(Boolean)
633
698
  : [];
634
- process.exitCode = callerClient
699
+ if (!process.exitCode && !callerClient)
700
+ process.stdout.write(`Started ${session}. Attach with: tmux attach -t ${session}\n`);
701
+ process.exitCode ||= callerClient
635
702
  ? (spawnSync('tmux', ['switch-client', '-c', callerClient, '-t', `=${session}`], { stdio: 'inherit' }).status ??
636
703
  1)
637
704
  : 0;
705
+ } else if (!hasTerminal) {
706
+ if (!sessionExists(session)) createRunSession(session, shellCommand, baseCommand);
707
+ if (!process.exitCode) process.stdout.write(`Started ${session}. Attach with: tmux attach -t ${session}\n`);
638
708
  } else {
639
- const created = sessionExists(session)
640
- ? []
641
- : ['new-session', '-d', '-s', session, '-c', process.cwd(), shellCommand];
642
- if (created.length && tmux(...created).status === 0) {
643
- tmux('set-option', '-t', `=${session}:`, COMMAND_OPTION, baseCommand);
644
- if (role) tmux('set-option', '-t', `=${session}:`, ROLE_OPTION, role);
645
- }
646
- process.exitCode = spawnSync('tmux', ['attach-session', '-t', `=${session}`], { stdio: 'inherit' }).status ?? 1;
709
+ if (!sessionExists(session)) createRunSession(session, shellCommand, baseCommand);
710
+ process.exitCode ||= !sessionExists(session)
711
+ ? 1
712
+ : (spawnSync('tmux', ['attach-session', '-t', `=${session}`], { stdio: 'inherit' }).status ?? 1);
647
713
  }
648
714
  } else if (command === 'shell-init' || command === 'shell-install') {
649
715
  const agents = [sender, ...words].filter(Boolean);
@@ -712,6 +778,7 @@ if (command === 'send' && sender) {
712
778
  const session = localSessionFor(sender) ?? (own === sender ? own : undefined);
713
779
  const dropped = session && !now ? droppedQuestions(session, own, words.join(' ')) : [];
714
780
  const pending = session ? pendingRestartOf(session) : null;
781
+ if (session) ensureDispatch();
715
782
  if (!session) {
716
783
  process.stderr.write(`No tmux session for ${sender}.\n`);
717
784
  process.exitCode = 1;
@@ -734,6 +801,15 @@ if (command === 'send' && sender) {
734
801
  `Refused: ${session} has no role and another agent session runs in this repo, so the new process could lose the builder rule. Resume a builder-* or doc-agent-* handoff, or pass --role builder or --role none.\n`,
735
802
  );
736
803
  process.exitCode = 1;
804
+ } else if (
805
+ (newProcess || (now && backgroundWorkOf(paneLines(session)) !== null)) &&
806
+ healedCommand(commandWithoutPrompt(agentCommandOf(session)), sender) === null
807
+ ) {
808
+ process.stderr.write(
809
+ `Refused: the stored command of ${session} has no agent program (${agentCommandOf(session)}), restarting would end the session. Nothing was stopped.\n`,
810
+ );
811
+ restartLog(`${session} refused, stored command has no agent program: ${agentCommandOf(session)}`);
812
+ process.exitCode = 1;
737
813
  } else if (dropped.length) {
738
814
  process.stderr.write(
739
815
  `Refused: ${session} asked the human a ❓ question that no later human message answers, and the handoff does not name it. Put each question verbatim under "Open for the human" in the handoff the prompt resumes (/handoff resume <name>), then restart again:\n${dropped.map((question) => `❓ ${question}`).join('\n')}\n`,
@@ -752,10 +828,24 @@ if (command === 'send' && sender) {
752
828
  `restart of ${session} gave up, the focus did not leave the agent panel after ${PANEL_UP_LIMIT} Up`,
753
829
  );
754
830
  process.exitCode = 1;
755
- } else if (newProcess) {
831
+ } else if (newProcess || backgroundWorkOf(paneLines(session)) !== null) {
832
+ const background = newProcess ? null : backgroundWorkOf(paneLines(session));
833
+ if (background !== null)
834
+ restartLog(`${session} shows background work (${background}), restart goes through --process`);
756
835
  const pane = `=${session}:`;
757
836
  const restartRole = restartRoleOf(session, words.join(' '));
758
- const stored = commandWithoutPrompt(agentCommandOf(session));
837
+ const recorded = commandWithoutPrompt(agentCommandOf(session));
838
+ const stored = healedCommand(recorded, sender);
839
+ if (configMismatch(stored.split(' ').map((word) => word.replaceAll("'", '')))) {
840
+ restartNotice(
841
+ `restart of ${session} refused, its command sets another CLAUDE_CONFIG_DIR than the caller (${callerConfigDir()})`,
842
+ );
843
+ process.exit(1);
844
+ }
845
+ if (stored !== recorded) {
846
+ tmux('set-option', '-t', pane, COMMAND_OPTION, stored);
847
+ restartLog(`${session} stored command had no agent program, healed to: ${stored}`);
848
+ }
759
849
  const base = withTempDir(restartRole ? commandWithRole(stored, restartRole) : stored);
760
850
  if (restartRole) tmux('set-option', '-t', pane, ROLE_OPTION, restartRole);
761
851
  tmux('set-option', '-p', '-t', pane, 'remain-on-exit', 'on');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ethlete/agent-rules",
3
- "version": "0.1.0-next.39",
3
+ "version": "0.1.0-next.40",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ethlete-io/ethdk",