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

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.
@@ -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>] <prompt...>
23
+ node <skill-dir>/agent-sessions.mjs restart <name> [--after <seconds>] [--notify <agent,...>] [--process] [--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>...]
@@ -45,11 +45,22 @@ 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. `--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. `--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>`, no sooner than `--after` seconds (default 5). It waits until that session ended its turn and its prompt holds no typed text, and gives up after 30 minutes. After the clear, a new turn does not hold the prompt back: a message can wake the fresh session, and Claude Code queues input typed during a turn. Only typed text in its prompt holds the prompt back. After 60 seconds of typed text, it saves the prompt to `.ethlete/restart.prompt.<session>.txt` and logs why in `.ethlete/restart.log`. The command returns at once, so end your turn after it. An agent uses it to clear itself and resume from its saved work state. It refuses any session other than the caller's own (from `$TMUX_PANE`), and the error names the caller's own sender name. Background commands of the old session still report into the new one.
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.
53
+
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
+ - **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.
56
+ - **Typed text.** After 2 minutes of it, and when it gives up, it sends one mailbox line to `<name>` and to each `--notify` agent. After 60 seconds, it saves the prompt to `.ethlete/restart.prompt.<session>.txt` and logs why in `.ethlete/restart.log`.
57
+ - **Who may restart whom.** Only your own session (from `$TMUX_PANE`) and the paired session (the builder started with `run --role builder`, or the non-builder session opposite it). Other targets are refused, and the error names your sender name. A restart of the paired session is logged as `peer restart: <caller> restarted <target>`.
58
+ - **Denied by permissions.** If the permission system denies your own `restart`, send one mailbox line to the grill/docs session, for example `send <you> --to <grill> 'restart denied, please /clear my pane and type: <prompt>'`. It types into your pane only when the pane is idle by the rule above.
59
+ - **Open questions.** For a `claude` session, `restart` reads the transcript and refuses while a chat line that starts with `❓` has no later message the human typed, unless the handoff the prompt resumes (`/handoff resume <name>`) names that question verbatim under "Open for the human". The refusal lists the questions to copy there.
60
+
61
+ `restart --process` ends the agent process instead of clearing it: it types `/exit` (`/quit` for a `codex` name) and starts the agent command again in the same tmux pane, through a login shell, with the prompt as its first message.After a change to an installed plugin, a settings file, an MCP server or `PATH`, use `--process`. The agent command is the one `run` started, without its prompt. It starts with `command`, so the shell function of the same name does not start a new session. If the exit opens the background work dialog, it selects "exit and stop tasks" and writes the stopped jobs to `restart.log` and a mailbox notice.
62
+
63
+ The new process keeps the role: the session's own role, else `builder` from a prompt that resumes a `builder-*` handoff, else the one `--role` names. 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).
53
64
 
54
65
  `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.
55
66
 
@@ -78,6 +89,6 @@ If the prompt of the agent holds typed text, the dispatcher waits until that tex
78
89
  4. After each larger step, run `inbox` again. Most agents cannot wake on new output, so you must pull messages yourself.
79
90
  5. When you finish, run `release`. A claim also expires after 4 hours, or after `--ttl` hours.
80
91
 
81
- In this repo commit with `yarn commit -m "..." -- <paths>`: it runs the related specs first in a throwaway worktree of HEAD plus those paths, before it takes `.git/index.lock`, and the pre-commit hook then skips them for that exact tree (a plain `git commit` still runs them in the hook).
92
+ In this repo commit with `yarn commit -m "..." -- <paths>`: it adds untracked paths and waits for `.git/index.lock`. Specs, lint and typecheck run in CI, not in the hook.
82
93
 
83
94
  A claim is advisory, not a lock. `--force` claims over another agent: use it only after the holder agreed. Silence is not approval. Acknowledge each handoff in words. No agent starts automatically. The user starts each one.
@@ -1,5 +1,5 @@
1
1
  import { execFileSync, spawn, spawnSync } from 'node:child_process';
2
- import { appendFileSync, existsSync, mkdirSync, readFileSync, watchFile, writeFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, watchFile, writeFileSync } from 'node:fs';
3
3
  import { basename, dirname, join, relative, resolve } from 'node:path';
4
4
  import { homedir } from 'node:os';
5
5
  import { fileURLToPath } from 'node:url';
@@ -36,8 +36,10 @@ const DRAFT_RETRY_MS = 2000;
36
36
  const RESTART_AFTER_SECONDS = 5;
37
37
  const RESTART_CLEAR_MS = 2500;
38
38
  const RESTART_POLL_MS = 2000;
39
- const RESTART_WAIT_MS = 30 * 60 * 1000;
39
+ const RESTART_WAIT_MS = Number(process.env.AGENT_RESTART_WAIT_MS ?? 30 * 60 * 1000);
40
+ const RESTART_DRAFT_NOTICE_MS = Number(process.env.AGENT_RESTART_DRAFT_NOTICE_MS ?? 2 * 60 * 1000);
40
41
  const RESTART_CLEAR_WAIT_MS = Number(process.env.AGENT_RESTART_CLEAR_WAIT_MS ?? 60 * 1000);
42
+ const RESTART_EXIT_WAIT_MS = Number(process.env.AGENT_RESTART_EXIT_WAIT_MS ?? 30 * 1000);
41
43
  const repoSlug = basename(root).replace(/[.:]/g, '-');
42
44
  const sessionFor = (agent) => `${agent}@${repoSlug}`;
43
45
  const DISPATCH_SESSION = process.env.AGENT_MAILBOX_DISPATCH_SESSION ?? `mailbox-dispatch@${repoSlug}`;
@@ -62,6 +64,8 @@ const afterSeconds = takeFlag(args, '--after', true);
62
64
  const now = takeFlag(args, '--now', false);
63
65
  const dryRun = takeFlag(args, '--dry-run', false);
64
66
  const role = takeFlag(args, '--role', true);
67
+ const notify = takeFlag(args, '--notify', true);
68
+ const newProcess = takeFlag(args, '--process', false);
65
69
  const [command, sender, ...words] = args;
66
70
 
67
71
  const help = `Shared agent mailbox: ${mailbox}
@@ -81,8 +85,14 @@ Run: node ${script} run <name> <command...> [--role builder] [--dry-run]
81
85
  Install: node ${script} shell-install [<agent>...] [--file <path>] [--remove] [--dry-run]
82
86
  (write the shell functions into ~/.zshrc or ~/.bashrc)
83
87
  Shell: node ${script} shell-init [<agent>...] (print shell functions that wrap each agent with run; default: claude codex)
84
- Restart: node ${script} restart <name> [--after <seconds>] <prompt...>
85
- (type the clear command and then the prompt into the tmux session of <name>)
88
+ Restart: node ${script} restart <name> [--after <seconds>] [--notify <agent,...>] [--process] [--role builder|none] <prompt...>
89
+ (type the clear command and then the prompt into the tmux session of <name>;
90
+ a long wait on a draft and a give-up go to <name> and each --notify agent;
91
+ --process ends the agent and starts it again in the same pane with the prompt;
92
+ it keeps the role, else takes it from a builder-* handoff name, and refuses
93
+ a session with no role while another agent session runs in the repo;
94
+ refuses while a ❓ question of a claude session has no later human message
95
+ and the resumed handoff does not name it under "Open for the human")
86
96
  Down: node ${script} down [<name>...] (stop dispatch; stop the named sessions too)
87
97
  Dispatch: node ${script} dispatch (wake the tmux session named <agent> for each message sent --to <agent>)
88
98
 
@@ -99,12 +109,173 @@ const tmux = (...tmuxArgs) => spawnSync('tmux', tmuxArgs, { encoding: 'utf8' });
99
109
  const quote = (text) => `'${text.replaceAll("'", "'\\''")}'`;
100
110
  const BUILDER_PROMPT =
101
111
  'The user does not read this chat. Write no text between tool calls; end each turn with at most one line. Reports go to the grill session via SendMessage.';
112
+ const claudeTmpDir = join(homedir(), '.cache', 'claude-tmp');
113
+ const ensuredClaudeTmpDir = () => {
114
+ mkdirSync(claudeTmpDir, { recursive: true });
115
+ return claudeTmpDir;
116
+ };
117
+ const tempDirEnv = () => `CLAUDE_CODE_TMPDIR=${quote(ensuredClaudeTmpDir())} `;
118
+ const withTempDir = (command) => (/(^|\s)CLAUDE_CODE_TMPDIR=/.test(command) ? command : `${tempDirEnv()}${command}`);
102
119
  const withRole = (words) =>
103
120
  role === 'builder' && basename(words[0]) === 'claude' ? [...words, '--append-system-prompt', BUILDER_PROMPT] : words;
104
121
  const sessionExists = (name) => tmux('has-session', '-t', `=${name}`).status === 0;
122
+ const ROLE_OPTION = '@ethlete_role';
123
+ const COMMAND_OPTION = '@ethlete_command';
124
+ const agentCommandOf = (session) =>
125
+ tmux('show-options', '-v', '-t', `=${session}:`, COMMAND_OPTION).stdout.trim() ||
126
+ tmux('display-message', '-p', '-t', `=${session}:`, '#{pane_start_command}')
127
+ .stdout.trim()
128
+ .replace(/^"(.*)"$/, '$1');
129
+ const roleOf = (session) => tmux('show-options', '-v', '-t', `=${session}:`, ROLE_OPTION).stdout.trim() || null;
130
+ const arePaired = (a, b) => (roleOf(a) === 'builder') !== (roleOf(b) === 'builder');
105
131
  const ONE_SHOT_FLAGS = new Set(['-p', '--print', '-v', '--version', '-h', '--help']);
106
132
  const runsInSession = (agentArgs) =>
107
133
  Boolean(process.stdin.isTTY && process.stdout.isTTY) && !agentArgs.some((arg) => ONE_SHOT_FLAGS.has(arg));
134
+ const TEXT_VALUE_FLAGS = new Set(['--append-system-prompt', '--system-prompt']);
135
+ const withoutPrompt = (words) => {
136
+ const separator = words.indexOf('--');
137
+ if (separator > 0) return words.slice(0, separator);
138
+ const [previous, last] = words.slice(-2);
139
+ const isPrompt =
140
+ words.length > 1 &&
141
+ !last.startsWith('-') &&
142
+ (!previous.startsWith('-') || (/\s/.test(last) && !TEXT_VALUE_FLAGS.has(previous)));
143
+ return isPrompt ? words.slice(0, -1) : words;
144
+ };
145
+ const SHELL_WORD = /(?:'[^']*'|\\.|[^\s'\\])+/g;
146
+ const ENV_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/;
147
+ const unquoteWord = (word) => word.replace(/'([^']*)'|\\(.)/g, (_, quoted, escaped) => quoted ?? escaped);
148
+ const commandWithoutPrompt = (command) => {
149
+ const tokens = [...command.matchAll(SHELL_WORD)];
150
+ const program = tokens.findIndex(([word]) => !ENV_WORD.test(word));
151
+ if (program < 0) return command;
152
+ const words = tokens.slice(program).map(([word]) => unquoteWord(word));
153
+ const kept = withoutPrompt(words).length;
154
+ return kept === words.length ? command : command.slice(0, tokens[program + kept].index).trimEnd();
155
+ };
156
+ const HANDOFF_ROLE = /^\/handoff\s+resume\s+(builder|doc-agent)-/;
157
+ const handoffRoleOf = (prompt) => prompt.match(HANDOFF_ROLE)?.[1] ?? null;
158
+ const restartRoleOf = (session, prompt) => {
159
+ if (role === 'none') return null;
160
+ const found = role ?? roleOf(session) ?? handoffRoleOf(prompt);
161
+ return found === 'doc-agent' ? null : found;
162
+ };
163
+ const claudeDir = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
164
+ const isAlive = (pid) => {
165
+ try {
166
+ process.kill(pid, 0);
167
+ return true;
168
+ } catch (error) {
169
+ return error.code === 'EPERM';
170
+ }
171
+ };
172
+ const readJson = (path) => {
173
+ try {
174
+ return JSON.parse(readFileSync(path, 'utf8'));
175
+ } catch {
176
+ return null;
177
+ }
178
+ };
179
+ const claudeSessionIdOf = (session, own) => {
180
+ const sessionsDir = join(claudeDir, 'sessions');
181
+ const live = existsSync(sessionsDir)
182
+ ? readdirSync(sessionsDir)
183
+ .filter((name) => name.endsWith('.json'))
184
+ .map((name) => readJson(join(sessionsDir, name)))
185
+ .filter((entry) => entry?.sessionId && entry.tmux?.startsWith(`${session}:`) && isAlive(entry.pid))
186
+ .sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0))
187
+ : [];
188
+ if (live.length) return live[0].sessionId;
189
+ return own === session ? process.env.CLAUDE_CODE_SESSION_ID || null : null;
190
+ };
191
+ const transcriptOf = (sessionId) => {
192
+ const projects = join(claudeDir, 'projects');
193
+ if (!existsSync(projects)) return null;
194
+ return (
195
+ readdirSync(projects)
196
+ .map((project) => join(projects, project, `${sessionId}.jsonl`))
197
+ .find((path) => existsSync(path)) ?? null
198
+ );
199
+ };
200
+ const textOf = (content) =>
201
+ typeof content === 'string'
202
+ ? content
203
+ : (content ?? [])
204
+ .filter((block) => block?.type === 'text')
205
+ .map((block) => block.text)
206
+ .join('\n');
207
+ const isHumanTurn = (entry) =>
208
+ entry.type === 'user' &&
209
+ entry.origin?.kind === 'human' &&
210
+ !/^\s*<command-(name|message)>/.test(textOf(entry.message?.content));
211
+ const QUESTION_LINE = /^\s*(?:[-*]\s+)?❓\s*(.+)$/;
212
+ const normalize = (text) => text.replace(/\s+/g, ' ').trim();
213
+ const unansweredQuestions = (transcript) => {
214
+ let questions = [];
215
+ for (const line of readFileSync(transcript, 'utf8').split('\n')) {
216
+ let entry;
217
+ try {
218
+ entry = JSON.parse(line);
219
+ } catch {
220
+ continue;
221
+ }
222
+ if (isHumanTurn(entry)) questions = [];
223
+ else if (entry.type === 'assistant')
224
+ textOf(entry.message?.content)
225
+ .split('\n')
226
+ .map((text) => text.match(QUESTION_LINE)?.[1])
227
+ .filter(Boolean)
228
+ .forEach((question) => questions.push(normalize(question)));
229
+ }
230
+ return [...new Set(questions)];
231
+ };
232
+ const HANDOFF_NAME = /^\/handoff\s+resume\s+(\S+)/;
233
+ const openForHumanOf = (prompt) => {
234
+ const name = prompt.match(HANDOFF_NAME)?.[1];
235
+ const path = name && join(root, '.claude/handoffs', name.endsWith('.md') ? name : `${name}.md`);
236
+ if (!path || !existsSync(path)) return null;
237
+ const lines = readFileSync(path, 'utf8').split('\n');
238
+ const start = lines.findIndex((line) => /open for the human/i.test(line));
239
+ if (start < 0) return '';
240
+ const end = lines.findIndex((line, index) => index > start && /^#/.test(line));
241
+ return normalize(lines.slice(start, end < 0 ? undefined : end).join('\n'));
242
+ };
243
+ const droppedQuestions = (session, own, prompt) => {
244
+ if (session.startsWith('codex')) return [];
245
+ const sessionId = claudeSessionIdOf(session, own);
246
+ const transcript = sessionId && transcriptOf(sessionId);
247
+ if (!transcript) return [];
248
+ const open = openForHumanOf(prompt) ?? '';
249
+ return unansweredQuestions(transcript).filter((question) => !open.includes(question));
250
+ };
251
+ const hasUnknownRole = (session, prompt) => {
252
+ if (role !== undefined || roleOf(session) || handoffRoleOf(prompt)) return false;
253
+ const peers = tmux('list-sessions', '-F', '#{session_name}')
254
+ .stdout.split('\n')
255
+ .filter((name) => name.endsWith(`@${repoSlug}`) && name !== session && name !== DISPATCH_SESSION);
256
+ return peers.length > 0 && !peers.some((name) => roleOf(name) === 'builder');
257
+ };
258
+ const commandWithRole = (command, agentRole) => {
259
+ const tokens = [...command.matchAll(SHELL_WORD)].map(([word]) => word);
260
+ const program = tokens.findIndex((word) => !ENV_WORD.test(word));
261
+ const env = program < 0 ? tokens : tokens.slice(0, program);
262
+ const words = tokens.slice(env.length).map(unquoteWord);
263
+ const kept = words.filter(
264
+ (word, index) =>
265
+ !(word === '--append-system-prompt' && words[index + 1] === BUILDER_PROMPT) &&
266
+ !(word === BUILDER_PROMPT && words[index - 1] === '--append-system-prompt'),
267
+ );
268
+ const rule =
269
+ agentRole === 'builder' && basename(kept[0] ?? '') === 'claude' ? ['--append-system-prompt', BUILDER_PROMPT] : [];
270
+ return [
271
+ ...env.filter((word) => !word.startsWith('ETHLETE_AGENT_ROLE=')),
272
+ `ETHLETE_AGENT_ROLE=${agentRole}`,
273
+ ...[...kept, ...rule].map(quote),
274
+ ].join(' ');
275
+ };
276
+ const bypassingShellFunction = (base) => base.replace(/^((?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*)/, '$1command ');
277
+ const EXIT_DIALOG_JOBS = /will stop when you exit/i;
278
+ const EXIT_AND_STOP = /exit and stop/i;
108
279
 
109
280
  /**
110
281
  * Reads the last prompt line (`❯` for Claude Code, `›` for Codex) of the pane. Dim text is the empty
@@ -112,14 +283,31 @@ const runsInSession = (agentArgs) =>
112
283
  * wake-up line from answering a permission dialog.
113
284
  */
114
285
  const SGR = `${String.fromCharCode(27)}\\[([0-9;]*)m`;
115
- const busyLine = (session) =>
116
- (tmux('capture-pane', '-p', '-t', `=${session}:`).stdout ?? '')
117
- .split('\n')
118
- .find((line) => /esc to inte/i.test(line)) ?? null;
286
+ const BUSY_TEXT = /esc to interrupt|Waiting for/i;
287
+ const isTranscript = (line) => /^\s*[●⎿]/.test(line);
288
+ /**
289
+ * The line that shows a running turn: the spinner line right above the input box, or a footer line below it.
290
+ * A transcript line (`●`, `⎿`) never counts, since an agent can end its turn with its own "Waiting for ..." text.
291
+ */
292
+ const busyLineOf = (lines) => {
293
+ const bottom = lastRuleIndex(lines);
294
+ const top = lines.slice(0, bottom).findLastIndex(isRule);
295
+ if (bottom === -1 || top === -1) return lines.find((line) => BUSY_TEXT.test(line) && !isTranscript(line)) ?? null;
296
+ const spinner = lines.slice(0, top).findLast((line) => line.trim() !== '') ?? '';
297
+ return [spinner, ...lines.slice(bottom + 1)].find((line) => BUSY_TEXT.test(line) && !isTranscript(line)) ?? null;
298
+ };
299
+ const busyLine = (session) => busyLineOf((tmux('capture-pane', '-p', '-t', `=${session}:`).stdout ?? '').split('\n'));
119
300
  const restartLog = (message) => {
120
301
  mkdirSync(dirname(mailbox), { recursive: true });
121
302
  appendFileSync(join(dirname(mailbox), 'restart.log'), `${new Date().toISOString()} ${message}\n`);
122
303
  };
304
+ const restartNotice = (message) => {
305
+ restartLog(message);
306
+ [sender, ...(notify ?? '').split(',')]
307
+ .map((agent) => agent.trim())
308
+ .filter(Boolean)
309
+ .forEach((to) => append({ sender: 'restart', to, message }));
310
+ };
123
311
 
124
312
  /**
125
313
  * Waits until the agent ended its turn and nobody types in its prompt, twice in a row; `false` after the time limit.
@@ -130,12 +318,19 @@ const waitForQuiet = (session, limitMs = RESTART_WAIT_MS, allowBusy = false) =>
130
318
  const end = Date.now() + limitMs;
131
319
  let quiet = 0;
132
320
  let reason = '';
321
+ let draftSince = null;
322
+ let told = false;
133
323
  while (Date.now() < end) {
134
324
  const busy = allowBusy ? null : busyLine(session);
135
325
  const draft = busy === null ? draftLine(session) : null;
136
326
  const next = busy !== null ? `busy: ${busy.trim()}` : draft !== null ? `draft: ${draft}` : '';
137
327
  if (next !== reason) restartLog(`${session} ${next ? `waits, ${next}` : 'is quiet'}`);
138
328
  reason = next;
329
+ draftSince = draft === null ? null : (draftSince ?? Date.now());
330
+ if (!told && draftSince !== null && Date.now() - draftSince >= RESTART_DRAFT_NOTICE_MS) {
331
+ told = true;
332
+ restartNotice(`restart of ${session} waits ${Math.round((Date.now() - draftSince) / 1000)}s, draft: ${draft}`);
333
+ }
139
334
  quiet = next ? 0 : quiet + 1;
140
335
  if (quiet === 2) return true;
141
336
  sleep(RESTART_POLL_MS);
@@ -145,15 +340,29 @@ const waitForQuiet = (session, limitMs = RESTART_WAIT_MS, allowBusy = false) =>
145
340
 
146
341
  /** The IDE context chip (`[⧉ In file.ts]`, `[⧉ 3 lines selected]`) shares the prompt line and survives `/clear`. */
147
342
  const IDE_CHIP = /\[⧉ [^\]]*\]/g;
148
- const draftLine = (session) => {
149
- const pane = tmux('capture-pane', '-p', '-e', '-t', `=${session}:`).stdout ?? '';
150
- const prompt = pane
151
- .split('\n')
152
- .reverse()
153
- .find((line) => /^\s*[❯›]/.test(line.replace(new RegExp(SGR, 'g'), '')));
154
- if (!prompt) return null;
343
+ const plain = (line) => line.replace(new RegExp(SGR, 'g'), '');
344
+ const isRule = (line) => /^─{10,}$/.test(plain(line).trim());
345
+ const isPromptMark = (line) => /^\s*[❯›]/.test(plain(line));
346
+ /** A row of the background-agent panel below the footer (`❯ ⏺ main`, ` ● main`, ` ◯ general-purpose …`). */
347
+ const isPanelRow = (line) => /^\s*❯?\s*[⏺●◯]/.test(plain(line));
348
+ const paneLines = (session) => (tmux('capture-pane', '-p', '-e', '-t', `=${session}:`).stdout ?? '').split('\n');
349
+ const lastRuleIndex = (lines) => lines.findLastIndex(isRule);
350
+ /**
351
+ * The prompt is the text between the last two rules of the input box. A `❯` line below the last rule that is not a
352
+ * panel row is a menu (`❯ 1. Yes`) and wins, which keeps a wake-up line from answering a permission dialog.
353
+ */
354
+ const promptLines = (lines) => {
355
+ const below = lastRuleIndex(lines);
356
+ const menu = lines.slice(below + 1).findLast((line) => isPromptMark(line) && !isPanelRow(line));
357
+ if (menu) return [menu];
358
+ const above = lines.slice(0, below).findLastIndex(isRule);
359
+ if (below !== -1 && above !== -1) return lines.slice(above + 1, below);
360
+ const prompt = lines.findLast((line) => isPromptMark(line) && !isPanelRow(line));
361
+ return prompt ? [prompt] : [];
362
+ };
363
+ const withoutDim = (line) => {
155
364
  let dim = false;
156
- const visible = prompt
365
+ return line
157
366
  .split(new RegExp(`(${SGR.replace('(', '(?:')})`))
158
367
  .map((part) => {
159
368
  const codes = part.match(new RegExp(`^${SGR}$`))?.[1].split(';');
@@ -165,12 +374,50 @@ const draftLine = (session) => {
165
374
  return '';
166
375
  })
167
376
  .join('');
168
- const text = visible
377
+ };
378
+ const draftLine = (session) => {
379
+ const text = promptLines(paneLines(session))
380
+ .map(withoutDim)
381
+ .join('\n')
169
382
  .replace(/^\s*[❯›]/, '')
170
383
  .replace(IDE_CHIP, '')
171
384
  .trim();
172
385
  return text.length > 0 ? text : null;
173
386
  };
387
+ const isInverse = (codes) => {
388
+ for (let index = 0; index < codes.length; index++) {
389
+ if (codes[index] === '38' || codes[index] === '48') index += codes[index + 1] === '2' ? 4 : 2;
390
+ else if (codes[index] === '7') return true;
391
+ }
392
+ return false;
393
+ };
394
+ /** A focused footer pill or panel row is drawn inverse (`ESC[7m`); older builds mark a focused row with `❯`. */
395
+ const panelFocused = (lines) =>
396
+ lines
397
+ .slice(lastRuleIndex(lines) + 1)
398
+ .some(
399
+ (line) =>
400
+ [...line.matchAll(new RegExp(SGR, 'g'))].some((match) => isInverse(match[1].split(';'))) ||
401
+ /^\s*❯\s*[⏺●◯]/.test(plain(line)),
402
+ );
403
+ const PANEL_UP_LIMIT = 10;
404
+ /**
405
+ * Keys typed while the focus sits in the background-agent panel go into the panel. Up moves the focus back to the
406
+ * prompt, and an Up too many recalls history, so C-u clears the line after. `false` if the focus did not leave.
407
+ */
408
+ const leavePanel = (session) => {
409
+ if (!panelFocused(paneLines(session))) return true;
410
+ for (let press = 0; press < PANEL_UP_LIMIT; press++) {
411
+ tmux('send-keys', '-t', `=${session}:`, 'Up');
412
+ sleep(ENTER_DELAY_MS);
413
+ if (!panelFocused(paneLines(session))) {
414
+ tmux('send-keys', '-t', `=${session}:`, 'C-u');
415
+ sleep(ENTER_DELAY_MS);
416
+ return true;
417
+ }
418
+ }
419
+ return false;
420
+ };
174
421
  const hasDraft = (session) => draftLine(session) !== null;
175
422
  const isAttached = (name) => tmux('list-clients', '-t', `=${name}`).stdout.trim() !== '';
176
423
  const freeSessionFor = (agent) => {
@@ -282,27 +529,57 @@ if (command === 'send' && sender) {
282
529
  process.stderr.write(`Unknown role ${role}. Only builder exists.\n`);
283
530
  process.exitCode = 1;
284
531
  } else if (command === 'run' && sender && words.length && dryRun) {
285
- process.stdout.write(`${role ? `ETHLETE_AGENT_ROLE=${role} ` : ''}${withRole(words).map(quote).join(' ')}\n`);
532
+ process.stdout.write(
533
+ `${withTempDir(`${role ? `ETHLETE_AGENT_ROLE=${role} ` : ''}${withRole(words).map(quote).join(' ')}`)}\n`,
534
+ );
286
535
  } else if (command === 'run' && sender && words.length && !runsInSession(words.slice(1))) {
287
536
  const [program, ...programArgs] = withRole(words);
288
537
  process.exitCode =
289
538
  spawnSync(program, programArgs, {
290
539
  stdio: 'inherit',
291
- env: role ? { ...process.env, ETHLETE_AGENT_ROLE: role } : process.env,
540
+ env: {
541
+ ...process.env,
542
+ CLAUDE_CODE_TMPDIR: ensuredClaudeTmpDir(),
543
+ ...(role ? { ETHLETE_AGENT_ROLE: role } : {}),
544
+ },
292
545
  }).status ?? 1;
293
546
  } else if (command === 'run' && sender && words.length) {
294
547
  const withEnv = process.env.AGENT_MAILBOX ? `AGENT_MAILBOX=${quote(process.env.AGENT_MAILBOX)} ` : '';
295
548
  if (!sessionExists(DISPATCH_SESSION))
296
549
  startSession(DISPATCH_SESSION, `${withEnv}node ${quote(script)} dispatch`, true);
297
550
  const session = freeSessionFor(sender);
298
- const shellCommand = `${role ? `ETHLETE_AGENT_ROLE=${role} ` : ''}${withRole(words).map(quote).join(' ')}`;
551
+ const roleEnv = role ? `ETHLETE_AGENT_ROLE=${role} ` : '';
552
+ const shellCommand = withTempDir(`${roleEnv}${withRole(words).map(quote).join(' ')}`);
553
+ const baseCommand = withTempDir(`${roleEnv}${withRole(withoutPrompt(words)).map(quote).join(' ')}`);
299
554
  if (process.env.TMUX) {
300
- if (!sessionExists(session)) tmux('new-session', '-d', '-s', session, '-c', process.cwd(), shellCommand);
301
- process.exitCode = spawnSync('tmux', ['switch-client', '-t', `=${session}`], { stdio: 'inherit' }).status ?? 1;
555
+ if (!sessionExists(session)) {
556
+ tmux('new-session', '-d', '-s', session, '-c', process.cwd(), shellCommand);
557
+ tmux('set-option', '-t', `=${session}:`, COMMAND_OPTION, baseCommand);
558
+ if (role) tmux('set-option', '-t', `=${session}:`, ROLE_OPTION, role);
559
+ }
560
+ const callerSession = tmux(
561
+ 'display-message',
562
+ '-p',
563
+ '-t',
564
+ process.env.TMUX_PANE ?? '',
565
+ '#{session_id}',
566
+ ).stdout.trim();
567
+ const [callerClient] = callerSession
568
+ ? tmux('list-clients', '-t', callerSession, '-F', '#{client_tty}').stdout.split('\n').filter(Boolean)
569
+ : [];
570
+ process.exitCode = callerClient
571
+ ? (spawnSync('tmux', ['switch-client', '-c', callerClient, '-t', `=${session}`], { stdio: 'inherit' }).status ??
572
+ 1)
573
+ : 0;
302
574
  } else {
303
- process.exitCode =
304
- spawnSync('tmux', ['new-session', '-A', '-s', session, '-c', process.cwd(), shellCommand], { stdio: 'inherit' })
305
- .status ?? 1;
575
+ const created = sessionExists(session)
576
+ ? []
577
+ : ['new-session', '-d', '-s', session, '-c', process.cwd(), shellCommand];
578
+ if (created.length && tmux(...created).status === 0) {
579
+ tmux('set-option', '-t', `=${session}:`, COMMAND_OPTION, baseCommand);
580
+ if (role) tmux('set-option', '-t', `=${session}:`, ROLE_OPTION, role);
581
+ }
582
+ process.exitCode = spawnSync('tmux', ['attach-session', '-t', `=${session}`], { stdio: 'inherit' }).status ?? 1;
306
583
  }
307
584
  } else if (command === 'shell-init' || command === 'shell-install') {
308
585
  const agents = [sender, ...words].filter(Boolean);
@@ -357,33 +634,105 @@ if (command === 'send' && sender) {
357
634
  const own = process.env.TMUX_PANE
358
635
  ? tmux('display-message', '-p', '-t', process.env.TMUX_PANE, '#{session_name}').stdout.trim()
359
636
  : null;
637
+ const dropped = session && !now ? droppedQuestions(session, own, words.join(' ')) : [];
360
638
  if (!session) {
361
639
  process.stderr.write(`No tmux session for ${sender}.\n`);
362
640
  process.exitCode = 1;
363
- } else if (own && own !== session) {
641
+ } else if (own && own !== session && !arePaired(own, session)) {
364
642
  process.stderr.write(
365
643
  `Refused: ${session} is not your session. You run in ${own}, so pass ${own.replace(`@${repoSlug}`, '')}.\n`,
366
644
  );
367
645
  process.exitCode = 1;
646
+ } else if (role !== undefined && role !== 'builder' && role !== 'none') {
647
+ process.stderr.write(`Unknown role ${role}. Pass --role builder or --role none.\n`);
648
+ process.exitCode = 1;
649
+ } else if (newProcess && hasUnknownRole(session, words.join(' '))) {
650
+ process.stderr.write(
651
+ `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`,
652
+ );
653
+ process.exitCode = 1;
654
+ } else if (dropped.length) {
655
+ process.stderr.write(
656
+ `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`,
657
+ );
658
+ process.exitCode = 1;
368
659
  } else if (now) {
369
660
  const type = (...keys) => tmux('send-keys', '-t', `=${session}:`, ...keys);
370
661
  sleep(Number(afterSeconds ?? RESTART_AFTER_SECONDS) * 1000);
371
662
  if (!waitForQuiet(session)) {
663
+ restartNotice(`restart of ${session} gave up after ${RESTART_WAIT_MS / 1000}s, reason in restart.log`);
664
+ process.exitCode = 1;
665
+ } else if (!leavePanel(session)) {
666
+ restartNotice(
667
+ `restart of ${session} gave up, the focus did not leave the agent panel after ${PANEL_UP_LIMIT} Up`,
668
+ );
372
669
  process.exitCode = 1;
670
+ } else if (newProcess) {
671
+ const pane = `=${session}:`;
672
+ const restartRole = restartRoleOf(session, words.join(' '));
673
+ const stored = commandWithoutPrompt(agentCommandOf(session));
674
+ const base = withTempDir(restartRole ? commandWithRole(stored, restartRole) : stored);
675
+ if (restartRole) tmux('set-option', '-t', pane, ROLE_OPTION, restartRole);
676
+ tmux('set-option', '-p', '-t', pane, 'remain-on-exit', 'on');
677
+ type('-l', sender.startsWith('codex') ? '/quit' : '/exit');
678
+ sleep(ENTER_DELAY_MS);
679
+ type('Enter');
680
+ const end = Date.now() + RESTART_EXIT_WAIT_MS;
681
+ const dead = () => tmux('display-message', '-p', '-t', pane, '#{pane_dead}').stdout.trim() === '1';
682
+ const answerExitDialog = () => {
683
+ const lines = (tmux('capture-pane', '-p', '-t', pane).stdout ?? '').split('\n');
684
+ const start = lines.findIndex((line) => EXIT_DIALOG_JOBS.test(line));
685
+ const stop = lines.findIndex((line, index) => index > start && EXIT_AND_STOP.test(line));
686
+ if (start < 0 || stop < 0) return false;
687
+ const selected = lines.findIndex((line, index) => index > start && line.trim().startsWith('❯'));
688
+ const jobs = lines
689
+ .slice(start + 1, stop)
690
+ .map((line) => line.trim())
691
+ .filter(Boolean);
692
+ restartNotice(
693
+ `restart of ${session} stopped its background work, start it again: ${jobs.join('; ') || '(none listed)'}`,
694
+ );
695
+ const between = (from, to) => lines.slice(from, to).filter((line) => line.trim()).length;
696
+ const [key, steps] = selected > stop ? ['Up', between(stop, selected)] : ['Down', between(selected, stop)];
697
+ for (let step = 0; selected >= 0 && step < steps; step++) type(key);
698
+ type('Enter');
699
+ return true;
700
+ };
701
+ let answered = false;
702
+ while (!dead() && Date.now() < end) {
703
+ if (!answered) answered = answerExitDialog();
704
+ sleep(RESTART_POLL_MS / 4);
705
+ }
706
+ if (!dead()) restartLog(`${session} did not exit ${RESTART_EXIT_WAIT_MS / 1000}s after the exit command, killed`);
707
+ const shell = process.env.SHELL || 'sh';
708
+ tmux(
709
+ 'respawn-pane',
710
+ '-k',
711
+ '-t',
712
+ pane,
713
+ '-c',
714
+ root,
715
+ shell,
716
+ '-lic',
717
+ `${bypassingShellFunction(base)} ${quote(words.join(' '))}`,
718
+ );
719
+ tmux('set-option', '-p', '-t', pane, 'remain-on-exit', 'off');
720
+ tmux('set-option', '-t', pane, COMMAND_OPTION, base);
721
+ restartLog(`${session} started a new process: ${base}`);
373
722
  } else {
374
723
  type('-l', sender.startsWith('codex') ? '/new' : '/clear');
375
724
  sleep(ENTER_DELAY_MS);
376
725
  type('Enter');
377
726
  sleep(RESTART_CLEAR_MS);
378
- if (waitForQuiet(session, RESTART_CLEAR_WAIT_MS, true)) {
727
+ if (waitForQuiet(session, RESTART_CLEAR_WAIT_MS, true) && leavePanel(session)) {
379
728
  type('-l', words.join(' '));
380
729
  sleep(ENTER_DELAY_MS);
381
730
  type('Enter');
382
731
  } else {
383
732
  const saved = join(dirname(mailbox), `restart.prompt.${session}.txt`);
384
733
  writeFileSync(saved, `${words.join(' ')}\n`);
385
- restartLog(
386
- `${session} prompt not empty ${RESTART_CLEAR_WAIT_MS / 1000}s after the clear, prompt not typed, saved to ${saved}`,
734
+ restartNotice(
735
+ `restart of ${session} gave up: prompt not empty ${RESTART_CLEAR_WAIT_MS / 1000}s after the clear, prompt not typed, saved to ${saved}`,
387
736
  );
388
737
  tmux(
389
738
  'display-message',
@@ -395,13 +744,20 @@ if (command === 'send' && sender) {
395
744
  }
396
745
  }
397
746
  } else {
747
+ if (own && own !== session) restartLog(`peer restart: ${own} restarted ${session}`);
398
748
  const delay = Number(afterSeconds ?? RESTART_AFTER_SECONDS);
399
- spawn(process.execPath, [script, 'restart', sender, '--now', '--after', String(delay), ...words], {
400
- detached: true,
401
- stdio: 'ignore',
402
- }).unref();
749
+ const forward = notify ? ['--notify', notify] : [];
750
+ const mode = [...(newProcess ? ['--process'] : []), ...(role ? ['--role', role] : [])];
751
+ spawn(
752
+ process.execPath,
753
+ [script, 'restart', sender, '--now', '--after', String(delay), ...forward, ...mode, ...words],
754
+ {
755
+ detached: true,
756
+ stdio: 'ignore',
757
+ },
758
+ ).unref();
403
759
  process.stdout.write(
404
- `Restarting ${session} once its turn ended and its prompt is empty, ${delay} seconds at the earliest. End your turn now.\n`,
760
+ `${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`,
405
761
  );
406
762
  }
407
763
  } else if (command === 'down') {
@@ -427,6 +783,7 @@ if (command === 'send' && sender) {
427
783
  return;
428
784
  }
429
785
  waiting.delete(agent);
786
+ if (!leavePanel(session)) return process.stderr.write(`The focus of ${session} stays in the agent panel.\n`);
430
787
  spawnSync('tmux', ['send-keys', '-t', `=${session}:`, '-l', text]);
431
788
  sleep(ENTER_DELAY_MS);
432
789
  spawnSync('tmux', ['send-keys', '-t', `=${session}:`, 'Enter']);
@@ -74,8 +74,9 @@ rows = computed(() => this.items().map((item) => ({ ...item, createdAtLabel: for
74
74
 
75
75
  - Inline template/styles for small components; external `.html` / `.css` files
76
76
  for complex ones.
77
- - Component CSS is plain CSS wrapped in `@layer components`, with every primary colour
78
- value coming from the repository's theme tokens.
77
+ - Component CSS is plain CSS wrapped in `@layer components` (`@layer components.sdk` in
78
+ the Ethlete SDK itself), with every primary colour value coming from the repository's
79
+ theme tokens.
79
80
 
80
81
  ## Reactive state
81
82
 
@@ -92,8 +92,8 @@ product. They take no picks and no new variants.
92
92
  - Mark a sketch `ready` only when no change to it waits on anything; otherwise `sketch hold`.
93
93
  - Every write command takes `--by <model id>`. **Never guess your id**: use the one your prompt names, or ask
94
94
  the coordinator or the user before you write.
95
- - Run `et design accept` only after the user approved a direct edit. Remove a part only with
96
- `et design part remove`, never `git rm`.
95
+ - A direct edit of a merged part is never accepted by hand: `design check` opens an old/new edit sketch and the
96
+ user picks in Studio. Remove a part only with `et design part remove`, never `git rm`.
97
97
  - Studio takes no new calls: never run `et design new`. New work goes to a product.
98
98
  - Share code between variants in the sketch's `shared/` folder only; no shared parameter or branch for one
99
99
  variant. An asset is one file in `<product>/assets/`, never inlined.