@ethlete/agent-rules 0.1.0-next.34 → 0.1.0-next.36

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,18 @@
1
1
  # @ethlete/agent-rules
2
2
 
3
+ ## 0.1.0-next.36
4
+
5
+ ### Patch Changes
6
+
7
+ - agent-sessions: the dispatcher types unread mailbox messages into the pane, a pending restart blocks a second one and the wake, and `run` without a terminal starts a detached session.
8
+
9
+ ## 0.1.0-next.35
10
+
11
+ ### Patch Changes
12
+
13
+ - The context warning and the shell functions from `shell-install` also find the agent-sessions script under `.claude/skills`, so a session in such a repo starts in tmux and restarts itself after a handoff instead of asking the user to clear.
14
+ - List the collapse guide in the sdk-docs skill.
15
+
3
16
  ## 0.1.0-next.34
4
17
 
5
18
  ### Minor Changes
@@ -52,11 +52,10 @@ ways that matter here, all captured in AGENT_PROFILES:
52
52
 
53
53
  At the critical tier, if the session's permission_mode is "auto", the
54
54
  instruction escalates from "recommend" to "just do it": auto mode already
55
- means the user wants the agent acting without stopping to ask, and clearing +
56
- resuming can't be triggered programmatically (no hook or tool can submit
57
- input to a running session), so the best available automation is to save the
55
+ means the user wants the agent acting without stopping to ask, so it saves the
58
56
  handoff file itself immediately rather than waiting for a natural stopping
59
- point. Codex's permission_mode value set is undocumented, so its profile lists
57
+ point. In an agent-sessions tmux pane the agent also clears and resumes itself
58
+ with the `restart` command; elsewhere that last step stays with the user. Codex's permission_mode value set is undocumented, so its profile lists
60
59
  no auto modes and the escalation stays off there.
61
60
 
62
61
  Neither the critical tier nor the Stop event forces a handoff. A session is
@@ -193,9 +192,7 @@ AGENT_PROFILES = {
193
192
  "edit first, nothing new. Apply its own test: with every change committed, no "
194
193
  "step left and nothing running, write no file, say that instead, and recommend "
195
194
  "/clear. If a file is warranted, tell the user exactly which one was written and "
196
- "that they should run /clear, then '/{handoff} resume <slug>', to continue - "
197
- "clearing and resuming can't be done programmatically, so this is the one step "
198
- "still on them."
195
+ "that they should run /clear, then '/{handoff} resume <slug>', to continue."
199
196
  ),
200
197
  "save_at_stop": (
201
198
  "save a handoff with the handoff skill, then tell the user which file was "
@@ -258,14 +255,15 @@ def handoff_skill(root):
258
255
 
259
256
 
260
257
  SELF_RESTART = (
261
- "you run in an agent-sessions tmux session, so do not hand this step to the user and never ask them to clear: "
262
- "apply the {handoff} skill's save test and save the handoff if it calls for a file, then run "
263
- '`node {script} restart {name} "/{handoff} resume"` yourself and end the turn - with no file, '
264
- "restart with a prompt that names the next step"
258
+ "you run in an agent-sessions tmux session, so you clear and resume yourself and never ask the user to clear: "
259
+ "apply the {handoff} skill's save test and save the handoff if it calls for a file, then, when every condition "
260
+ "of its 'Clear and resume on your own' section holds, run "
261
+ '`node {script} restart {name} "/{handoff} resume <slug>"` yourself and end the turn - with no file, '
262
+ "restart with a prompt that names the next step. Only when a condition cannot be met, tell the user"
265
263
  )
266
264
  SELF_RESTART_ACT_NOW = (
267
- "Save the handoff, then run `node {script} restart {name} \"/{handoff} resume\"` yourself and end the turn. "
268
- "Never ask the user to clear."
265
+ "Save the handoff, then run `node {script} restart {name} \"/{handoff} resume <slug>\"` yourself and end the "
266
+ "turn, as the {handoff} skill's 'Clear and resume on your own' section says. Never ask the user to clear."
269
267
  )
270
268
  USER_DIRECTED_KEYS = ("recommend", "suggest", "save_now", "save_at_stop")
271
269
 
@@ -279,7 +277,8 @@ def self_restart_target(root):
279
277
  (
280
278
  path
281
279
  for path in (
282
- os.path.join(".agents/skills", name, "agent-sessions.mjs")
280
+ os.path.join(skills_dir, name, "agent-sessions.mjs")
281
+ for skills_dir in (".agents/skills", ".claude/skills")
283
282
  for name in ("ethlete-agent-sessions", "agent-sessions")
284
283
  )
285
284
  if os.path.isfile(os.path.join(root, path))
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "e2e-progress",
3
- "version": "0.1.0-next.34",
3
+ "version": "0.1.0-next.36",
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,11 +1,11 @@
1
1
  ---
2
2
  name: agent-sessions-wake-up
3
- description: A prompt that says "New mailbox message for <name>" means run the inbox command in it and act on the result; read the agent-sessions skill before you edit a file another agent may edit.
3
+ description: A prompt that starts with "Mailbox message from <sender>:" is a message from another agent; act on it; read the agent-sessions skill before you edit a file another agent may edit.
4
4
  kind: rule
5
5
  scope: both
6
6
  ---
7
7
 
8
8
  ## Agent sessions
9
9
 
10
- If a prompt says `New mailbox message for <name>`, run the `inbox` command in that prompt and act on
11
- the messages. Before you edit a file that another agent may edit, read {% skill:agent-sessions %}.
10
+ A prompt that starts with `Mailbox message from <sender>:` is a mailbox message from another agent: act
11
+ on it. Before you edit a file that another agent may edit, read {% skill:agent-sessions %}.
@@ -37,3 +37,8 @@ Theme **names** (`brand`, `danger`, `dark-elevated`, …) are registered by the
37
37
  the SDK ships none. Never hardcode them as an SDK-defined union or reusable API contract.
38
38
  If an app-specific example names one, label it as belonging to that app. Semantic colours
39
39
  resolve by theme `type` (e.g. `injectSemanticColorTheme('error')`).
40
+
41
+ **Style an SDK component's state through its inputs.** A pressed, active, selected or loading
42
+ look comes from the component's state inputs (`pressed`, `pressedColor`, `variant`, `color`),
43
+ never from a `!`-utility or an override of an `--et-*` custom property in an app template. If
44
+ no input fits, ask the doc session for one instead of building the override.
@@ -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. `--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. 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.
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.
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>`.
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.
@@ -70,7 +70,7 @@ Choose a `<name>` that no other agent uses, for example `agent-a` or `agent-b`.
70
70
 
71
71
  The mailbox file is `.ethlete/mailbox.jsonl` in the git root. The first write also creates `.ethlete/.gitignore`, so the file stays out of git. Set `AGENT_MAILBOX` to use another path. For two Claude Code sessions, the `SendMessage` tool is the better channel. The mailbox is for agents that cannot reach each other directly.
72
72
 
73
- An idle agent cannot read the mailbox. One `dispatch` process outside every agent fixes this. It polls the mailbox for free. When a message carries `--to <agent>`, it waits a short grace period and then, if the agent has not read the message, types a wake-up line into the `tmux` session `<agent>@<repo>`, or a session named only `<agent>`. The agent then runs `inbox` and acts. A message without `--to` wakes nobody.
73
+ An idle agent cannot read the mailbox. One `dispatch` process outside every agent fixes this. It polls the mailbox for free. When a message carries `--to <agent>`, it waits a short grace period and then, if the agent has not read the message, types the unread messages addressed to it into the `tmux` session `<agent>@<repo>`, or a session named only `<agent>` whose pane runs in this checkout, one line each as `Mailbox message from <sender>: <text>` with newlines collapsed. It never types a message from before the dispatcher started. Once the agent has run `inbox`, the wake marks them read as `inbox` does; until then `inbox` still lists them. The agent acts on them. A message without `--to` wakes nobody and is never typed. The dispatcher never types into a session of another checkout, and `send --to <agent>` refuses with a non-zero exit when no such session of this checkout runs.
74
74
 
75
75
  If the prompt of the agent holds typed text, the dispatcher waits until that text is sent or cleared. It checks again every 2 seconds. An open menu, for example a permission dialog, also makes it wait. If the agent is in the middle of a turn, the wake-up line waits as its next prompt. An agent in a `tmux` session does not need the `--wait` loop, which costs a turn at every timeout. If you wait for an answer in a session without `tmux`, run `inbox <name> --wait 120`: it blocks until a message arrives or 120 seconds pass. If it prints "No new messages.", run it again. A background `--wait` ends after one message, so it is not a lasting watch.
76
76
 
@@ -1,5 +1,14 @@
1
1
  import { execFileSync, spawn, spawnSync } from 'node:child_process';
2
- import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, watchFile, writeFileSync } from 'node:fs';
2
+ import {
3
+ appendFileSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ readdirSync,
7
+ readFileSync,
8
+ rmSync,
9
+ watchFile,
10
+ writeFileSync,
11
+ } from 'node:fs';
3
12
  import { basename, dirname, join, relative, resolve } from 'node:path';
4
13
  import { homedir } from 'node:os';
5
14
  import { fileURLToPath } from 'node:url';
@@ -16,18 +25,6 @@ const root = (() => {
16
25
  })();
17
26
  const mailbox = process.env.AGENT_MAILBOX ?? join(root, '.ethlete/mailbox.jsonl');
18
27
  const script = fileURLToPath(import.meta.url);
19
- const hasRootScript = (name) => {
20
- try {
21
- return Boolean(JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).scripts?.[name]);
22
- } catch {
23
- return false;
24
- }
25
- };
26
- const inboxCommand = (agent) => {
27
- if (existsSync(join(root, 'node_modules/.bin/ethlete-agents'))) return `npx ethlete-agents sessions inbox ${agent}`;
28
- if (hasRootScript('agents:sessions')) return `yarn agents:sessions inbox ${agent}`;
29
- return `node ${script} inbox ${agent}`;
30
- };
31
28
  const DEFAULT_TTL_HOURS = 4;
32
29
  const DEFAULT_LAST = 20;
33
30
  const ENTER_DELAY_MS = 400;
@@ -40,6 +37,8 @@ const RESTART_WAIT_MS = Number(process.env.AGENT_RESTART_WAIT_MS ?? 30 * 60 * 10
40
37
  const RESTART_DRAFT_NOTICE_MS = Number(process.env.AGENT_RESTART_DRAFT_NOTICE_MS ?? 2 * 60 * 1000);
41
38
  const RESTART_CLEAR_WAIT_MS = Number(process.env.AGENT_RESTART_CLEAR_WAIT_MS ?? 60 * 1000);
42
39
  const RESTART_EXIT_WAIT_MS = Number(process.env.AGENT_RESTART_EXIT_WAIT_MS ?? 30 * 1000);
40
+ const RESTART_RESUME_WAIT_MS = Number(process.env.AGENT_RESTART_RESUME_WAIT_MS ?? 60 * 1000);
41
+ const RESTART_LOCK_MS = Number(process.env.AGENT_RESTART_LOCK_MS ?? RESTART_WAIT_MS + 10 * 60 * 1000);
43
42
  const repoSlug = basename(root).replace(/[.:]/g, '-');
44
43
  const sessionFor = (agent) => `${agent}@${repoSlug}`;
45
44
  const DISPATCH_SESSION = process.env.AGENT_MAILBOX_DISPATCH_SESSION ?? `mailbox-dispatch@${repoSlug}`;
@@ -94,7 +93,7 @@ Restart: node ${script} restart <name> [--after <seconds>] [--notify <agent,...>
94
93
  refuses while a ❓ question of a claude session has no later human message
95
94
  and the resumed handoff does not name it under "Open for the human")
96
95
  Down: node ${script} down [<name>...] (stop dispatch; stop the named sessions too)
97
- Dispatch: node ${script} dispatch (wake the tmux session named <agent> for each message sent --to <agent>)
96
+ Dispatch: node ${script} dispatch (wake the session <agent>@<repo> for each message sent --to <agent>)
98
97
 
99
98
  Protocol: append one JSON object per line; never rewrite or truncate.
100
99
  Fields: timestamp (UTC), sender, message. A claim also has paths and expires.
@@ -128,9 +127,28 @@ const agentCommandOf = (session) =>
128
127
  .replace(/^"(.*)"$/, '$1');
129
128
  const roleOf = (session) => tmux('show-options', '-v', '-t', `=${session}:`, ROLE_OPTION).stdout.trim() || null;
130
129
  const arePaired = (a, b) => (roleOf(a) === 'builder') !== (roleOf(b) === 'builder');
130
+ const checkoutOfSession = (session) => {
131
+ const path = tmux('display-message', '-p', '-t', `=${session}:`, '#{pane_current_path}').stdout.trim();
132
+ if (!path) return null;
133
+ const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: path, encoding: 'utf8' });
134
+ return top.status === 0 ? top.stdout.trim() : path;
135
+ };
136
+ const localSessionFor = (agent) =>
137
+ [sessionFor(agent), agent].find(
138
+ (name) => sessionExists(name) && (name === sessionFor(agent) || checkoutOfSession(name) === root),
139
+ ) ?? null;
140
+ const foreignCheckoutsOf = (agent) => [
141
+ ...new Set(
142
+ tmux('list-sessions', '-F', '#{session_name}')
143
+ .stdout.split('\n')
144
+ .filter((name) => name === agent || name.startsWith(`${agent}@`))
145
+ .map((name) => (name === agent ? basename(checkoutOfSession(name) ?? '') : name.slice(agent.length + 1)))
146
+ .filter(Boolean),
147
+ ),
148
+ ];
131
149
  const ONE_SHOT_FLAGS = new Set(['-p', '--print', '-v', '--version', '-h', '--help']);
132
- const runsInSession = (agentArgs) =>
133
- Boolean(process.stdin.isTTY && process.stdout.isTTY) && !agentArgs.some((arg) => ONE_SHOT_FLAGS.has(arg));
150
+ const hasTerminal = Boolean(process.stdin.isTTY && process.stdout.isTTY);
151
+ const runsInSession = (agentArgs) => !agentArgs.some((arg) => ONE_SHOT_FLAGS.has(arg));
134
152
  const TEXT_VALUE_FLAGS = new Set(['--append-system-prompt', '--system-prompt']);
135
153
  const withoutPrompt = (words) => {
136
154
  const separator = words.indexOf('--');
@@ -309,6 +327,23 @@ const restartNotice = (message) => {
309
327
  .forEach((to) => append({ sender: 'restart', to, message }));
310
328
  };
311
329
 
330
+ const restartLockOf = (session) => join(dirname(mailbox), `restart.lock.${session}`);
331
+ const pendingRestartOf = (session) => {
332
+ const lock = readJson(restartLockOf(session));
333
+ return lock && isAlive(lock.pid) && Date.now() - lock.since < RESTART_LOCK_MS ? lock : null;
334
+ };
335
+ const lockRestart = (session, pid) => {
336
+ mkdirSync(dirname(mailbox), { recursive: true });
337
+ writeFileSync(restartLockOf(session), JSON.stringify({ pid, since: Date.now() }));
338
+ };
339
+ const unlockRestart = (session) => {
340
+ if (readJson(restartLockOf(session))?.pid === process.pid) rmSync(restartLockOf(session), { force: true });
341
+ };
342
+ const waitForFirstTurn = (session) => {
343
+ const end = Date.now() + RESTART_RESUME_WAIT_MS;
344
+ while (Date.now() < end && sessionExists(session) && busyLine(session) === null) sleep(RESTART_POLL_MS / 4);
345
+ };
346
+
312
347
  /**
313
348
  * Waits until the agent ended its turn and nobody types in its prompt, twice in a row; `false` after the time limit.
314
349
  * With `allowBusy`, a running turn does not block, since Claude Code queues input typed during a turn.
@@ -433,7 +468,7 @@ const startSession = (name, shellCommand, quiet = false) => {
433
468
  if (!quiet) process.stdout.write(`Started ${name}. Attach with: tmux attach -t ${name}\n`);
434
469
  };
435
470
 
436
- const IGNORED = ['mailbox.jsonl', 'mailbox.cursor.*', 'restart.log', 'restart.prompt.*'];
471
+ const IGNORED = ['mailbox.jsonl', 'mailbox.cursor.*', 'restart.log', 'restart.prompt.*', 'restart.lock.*'];
437
472
 
438
473
  const prepare = () => {
439
474
  mkdirSync(dirname(mailbox), { recursive: true });
@@ -514,6 +549,12 @@ if (command === 'send' && sender) {
514
549
  if (!message) {
515
550
  process.stderr.write('No message given.\n');
516
551
  process.exitCode = 1;
552
+ } else if (recipient && !localSessionFor(recipient)) {
553
+ const checkouts = foreignCheckoutsOf(recipient);
554
+ process.stderr.write(
555
+ `Refused: ${recipient} is not a session of ${repoSlug}${checkouts.length ? `; it belongs to ${checkouts.join(', ')}` : ''}. Nothing was sent. Pass the name of a session ${sessionFor('<agent>')} of this checkout.\n`,
556
+ );
557
+ process.exitCode = 1;
517
558
  } else {
518
559
  append({ sender, message, ...(recipient ? { to: recipient } : {}) });
519
560
  process.stdout.write(`Sent as ${sender}.\n`);
@@ -551,7 +592,14 @@ if (command === 'send' && sender) {
551
592
  const roleEnv = role ? `ETHLETE_AGENT_ROLE=${role} ` : '';
552
593
  const shellCommand = withTempDir(`${roleEnv}${withRole(words).map(quote).join(' ')}`);
553
594
  const baseCommand = withTempDir(`${roleEnv}${withRole(withoutPrompt(words)).map(quote).join(' ')}`);
554
- if (process.env.TMUX) {
595
+ if (!hasTerminal) {
596
+ if (!sessionExists(session)) {
597
+ tmux('new-session', '-d', '-s', session, '-c', process.cwd(), shellCommand);
598
+ tmux('set-option', '-t', `=${session}:`, COMMAND_OPTION, baseCommand);
599
+ if (role) tmux('set-option', '-t', `=${session}:`, ROLE_OPTION, role);
600
+ }
601
+ process.stdout.write(`Started ${session}. Attach with: tmux attach -t ${session}\n`);
602
+ } else if (process.env.TMUX) {
555
603
  if (!sessionExists(session)) {
556
604
  tmux('new-session', '-d', '-s', session, '-c', process.cwd(), shellCommand);
557
605
  tmux('set-option', '-t', `=${session}:`, COMMAND_OPTION, baseCommand);
@@ -583,12 +631,24 @@ if (command === 'send' && sender) {
583
631
  }
584
632
  } else if (command === 'shell-init' || command === 'shell-install') {
585
633
  const agents = [sender, ...words].filter(Boolean);
634
+ const locate = `_ethlete_agent_sessions_script() {
635
+ local root dir
636
+ root=$(git rev-parse --show-toplevel 2>/dev/null) || return 1
637
+ for dir in .agents/skills .claude/skills; do
638
+ if [ -f "$root/$dir/ethlete-agent-sessions/agent-sessions.mjs" ]; then
639
+ printf '%s\\n' "$root/$dir/ethlete-agent-sessions/agent-sessions.mjs"
640
+ return 0
641
+ fi
642
+ done
643
+ return 1
644
+ }
645
+ `;
586
646
  const functions = (agents.length ? agents : ['claude', 'codex'])
587
647
  .map(
588
648
  (agent) => `${agent}() {
589
- local root script
590
- root=$(git rev-parse --show-toplevel 2>/dev/null) && script="$root/.agents/skills/ethlete-agent-sessions/agent-sessions.mjs"
591
- if [ -n "$script" ] && [ -f "$script" ] && command -v tmux >/dev/null; then
649
+ local script
650
+ script=$(_ethlete_agent_sessions_script)
651
+ if [ -n "$script" ] && command -v tmux >/dev/null; then
592
652
  node "$script" run ${agent} ${agent} "$@"
593
653
  else
594
654
  command ${agent} "$@"
@@ -596,7 +656,7 @@ if (command === 'send' && sender) {
596
656
  }
597
657
  `,
598
658
  )
599
- .join('');
659
+ .reduce((text, fn) => text + fn, locate);
600
660
  if (command === 'shell-init') {
601
661
  process.stdout.write(functions);
602
662
  } else {
@@ -630,14 +690,21 @@ if (command === 'send' && sender) {
630
690
  }
631
691
  }
632
692
  } else if (command === 'restart' && sender && words.length) {
633
- const session = [sessionFor(sender), sender].find(sessionExists);
634
693
  const own = process.env.TMUX_PANE
635
694
  ? tmux('display-message', '-p', '-t', process.env.TMUX_PANE, '#{session_name}').stdout.trim()
636
695
  : null;
696
+ const session = localSessionFor(sender) ?? (own === sender ? own : undefined);
637
697
  const dropped = session && !now ? droppedQuestions(session, own, words.join(' ')) : [];
698
+ const pending = session ? pendingRestartOf(session) : null;
638
699
  if (!session) {
639
700
  process.stderr.write(`No tmux session for ${sender}.\n`);
640
701
  process.exitCode = 1;
702
+ } else if (pending && pending.pid !== process.pid) {
703
+ process.stderr.write(
704
+ `Refused: a restart of ${session} is already pending (pid ${pending.pid} since ${new Date(pending.since).toISOString()}). Let it finish, or end that process first.\n`,
705
+ );
706
+ restartLog(`${session} refused a second restart, pid ${pending.pid} still pending`);
707
+ process.exitCode = 1;
641
708
  } else if (own && own !== session && !arePaired(own, session)) {
642
709
  process.stderr.write(
643
710
  `Refused: ${session} is not your session. You run in ${own}, so pass ${own.replace(`@${repoSlug}`, '')}.\n`,
@@ -657,6 +724,8 @@ if (command === 'send' && sender) {
657
724
  );
658
725
  process.exitCode = 1;
659
726
  } else if (now) {
727
+ lockRestart(session, process.pid);
728
+ process.on('exit', () => unlockRestart(session));
660
729
  const type = (...keys) => tmux('send-keys', '-t', `=${session}:`, ...keys);
661
730
  sleep(Number(afterSeconds ?? RESTART_AFTER_SECONDS) * 1000);
662
731
  if (!waitForQuiet(session)) {
@@ -719,6 +788,7 @@ if (command === 'send' && sender) {
719
788
  tmux('set-option', '-p', '-t', pane, 'remain-on-exit', 'off');
720
789
  tmux('set-option', '-t', pane, COMMAND_OPTION, base);
721
790
  restartLog(`${session} started a new process: ${base}`);
791
+ waitForFirstTurn(session);
722
792
  } else {
723
793
  type('-l', sender.startsWith('codex') ? '/new' : '/clear');
724
794
  sleep(ENTER_DELAY_MS);
@@ -728,6 +798,7 @@ if (command === 'send' && sender) {
728
798
  type('-l', words.join(' '));
729
799
  sleep(ENTER_DELAY_MS);
730
800
  type('Enter');
801
+ waitForFirstTurn(session);
731
802
  } else {
732
803
  const saved = join(dirname(mailbox), `restart.prompt.${session}.txt`);
733
804
  writeFileSync(saved, `${words.join(' ')}\n`);
@@ -748,14 +819,16 @@ if (command === 'send' && sender) {
748
819
  const delay = Number(afterSeconds ?? RESTART_AFTER_SECONDS);
749
820
  const forward = notify ? ['--notify', notify] : [];
750
821
  const mode = [...(newProcess ? ['--process'] : []), ...(role ? ['--role', role] : [])];
751
- spawn(
822
+ const child = spawn(
752
823
  process.execPath,
753
824
  [script, 'restart', sender, '--now', '--after', String(delay), ...forward, ...mode, ...words],
754
825
  {
755
826
  detached: true,
756
827
  stdio: 'ignore',
757
828
  },
758
- ).unref();
829
+ );
830
+ lockRestart(session, child.pid);
831
+ child.unref();
759
832
  process.stdout.write(
760
833
  `${newProcess ? 'Starting a new process in' : 'Restarting'} ${session} once its turn ended and its prompt is empty, ${delay} seconds at the earliest. End your turn now.\n`,
761
834
  );
@@ -768,14 +841,32 @@ if (command === 'send' && sender) {
768
841
  } else if (command === 'dispatch') {
769
842
  prepare();
770
843
  appendFileSync(mailbox, '');
771
- let seen = entries().length;
844
+ const started = entries().length;
845
+ let seen = started;
846
+ const woken = {};
772
847
  const due = {};
773
848
  const waiting = new Set();
849
+ const addressedTo = (agent) => {
850
+ const history = entries();
851
+ const cursor = inboxCursor(agent);
852
+ const read = existsSync(cursor) ? Number(readFileSync(cursor, 'utf8')) : 0;
853
+ return {
854
+ count: history.length,
855
+ unread: history
856
+ .slice(Math.max(read, woken[agent] ?? started))
857
+ .filter((entry) => entry.to === agent && entry.sender !== agent),
858
+ };
859
+ };
774
860
  const wake = (agent) => {
775
- if (!unreadFor(agent).unread.length) return;
776
- const text = `New mailbox message for ${agent}. Run: ${inboxCommand(agent)}`;
777
- const session = [sessionFor(agent), agent].find(sessionExists);
778
- if (!session) return process.stderr.write(`No tmux session for ${agent}.\n`);
861
+ if (!addressedTo(agent).unread.length) return;
862
+ const session = localSessionFor(agent);
863
+ if (!session) return process.stderr.write(`No tmux session ${sessionFor(agent)} in this checkout.\n`);
864
+ if (pendingRestartOf(session)) {
865
+ if (!waiting.has(agent)) process.stdout.write(`Waiting for the restart of ${session}.\n`);
866
+ waiting.add(agent);
867
+ due[agent] = Date.now() + DRAFT_RETRY_MS;
868
+ return;
869
+ }
779
870
  if (hasDraft(session)) {
780
871
  if (!waiting.has(agent)) process.stdout.write(`Waiting for the typed text in ${session}.\n`);
781
872
  waiting.add(agent);
@@ -784,9 +875,20 @@ if (command === 'send' && sender) {
784
875
  }
785
876
  waiting.delete(agent);
786
877
  if (!leavePanel(session)) return process.stderr.write(`The focus of ${session} stays in the agent panel.\n`);
787
- spawnSync('tmux', ['send-keys', '-t', `=${session}:`, '-l', text]);
788
- sleep(ENTER_DELAY_MS);
789
- spawnSync('tmux', ['send-keys', '-t', `=${session}:`, 'Enter']);
878
+ const { count, unread } = addressedTo(agent);
879
+ unread.forEach((entry) => {
880
+ spawnSync('tmux', [
881
+ 'send-keys',
882
+ '-t',
883
+ `=${session}:`,
884
+ '-l',
885
+ `Mailbox message from ${entry.sender}: ${normalize(String(entry.message ?? ''))}`,
886
+ ]);
887
+ sleep(ENTER_DELAY_MS);
888
+ spawnSync('tmux', ['send-keys', '-t', `=${session}:`, 'Enter']);
889
+ });
890
+ woken[agent] = count;
891
+ if (existsSync(inboxCursor(agent))) writeFileSync(inboxCursor(agent), String(count));
790
892
  process.stdout.write(`Woke ${session}.\n`);
791
893
  };
792
894
  const poll = () => {
@@ -43,7 +43,7 @@ Component domains under `/components/`:
43
43
 
44
44
  `accordion` `avatar` `badge` `banner` `bracket` `bracket-prediction` `bracket-rounds-list`
45
45
  `breadcrumb` `button` `calendar` `card` `carousel` `cascader` `chart` `chip`
46
- `choice-inputs` `command-palette` `copy-button` `date-time-inputs` `description-list`
46
+ `choice-inputs` `collapse` `command-palette` `copy-button` `date-time-inputs` `description-list`
47
47
  `divider` `dropzone` `empty-state` `error-codes` `filter-overlay` `floating-action`
48
48
  `focus-ring` `forms` `grid` `icon` `kbd` `line-chart` `loader` `localization` `masonry`
49
49
  `match` `menu` `mixed-state` `notification` `overlay-openers` `overlays` `paged-query-trigger`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ethlete/agent-rules",
3
- "version": "0.1.0-next.34",
3
+ "version": "0.1.0-next.36",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ethlete-io/ethdk",