angelia-gateway 0.4.5 → 0.4.6

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.
@@ -495,7 +495,9 @@ export class WhatsAppAdapter extends EventEmitter {
495
495
  async sendMedia(chat, m) {
496
496
  if (!this.sock || !this.connected)
497
497
  throw new Error('whatsapp: not connected');
498
- const caption = m.caption || undefined;
498
+ // A caption in a group gets the same rewrite as a text: a phone the group hides goes out as its
499
+ // lid. No tags on a caption: it needs no member fetch, and a file is rarely where a tag belongs.
500
+ const caption = (m.caption && chat.endsWith('@g.us') ? withMentions(m.caption, undefined, { lidFor: (n) => this.lids.lidFor(n) }).text : m.caption) || undefined;
499
501
  if (m.kind === 'image') {
500
502
  await this.post(chat, { image: { url: m.path }, caption, mimetype: m.mime });
501
503
  return;
package/dist/brain/agy.js CHANGED
@@ -134,7 +134,7 @@ export function createOnly(path, text, mode) {
134
134
  /** Every process below `root`, whatever its process group or session: agy runs each command in a
135
135
  * shell of its own on a PTY, a new session, which a kill of agy's group does not reach (red team
136
136
  * round 2). Read from `ps` before anything is killed, while they are still below it. */
137
- export function descendants(root, table = () => spawnSync('/bin/ps', ['-axo', 'pid=,ppid='], { encoding: 'utf8', timeout: 5000 }).stdout ?? '') {
137
+ export function descendants(root, table = () => spawnSync('/bin/ps', ['-Ao', 'pid=,ppid='], { encoding: 'utf8', timeout: 5000 }).stdout ?? '') {
138
138
  const kids = new Map();
139
139
  for (const line of table().split('\n')) {
140
140
  const [pid, ppid] = line.trim().split(/\s+/).map(Number);
@@ -0,0 +1,39 @@
1
+ /**
2
+ * A failed call to the model, as Claude Code reports it. It writes the failure as an assistant row of
3
+ * its own ("Not logged in · Please run /login", "API Error: 500 …"), marked `isApiErrorMessage` in the
4
+ * transcript, so a reader that takes the last assistant text as the answer posts the error to the chat
5
+ * as if the agent had said it (2026-10-24). The mark, not the words, decides: an answer that quotes
6
+ * "please run /login" in a code sample is still an answer.
7
+ *
8
+ * A usage limit is left out on purpose: it comes the same way, and the orchestrator already answers
9
+ * it with how to switch model (deliver/text.ts, isLimitText), which a retry a minute later would not.
10
+ */
11
+ import { isLimitText } from '../core/deliver/text.js';
12
+ /** The start of a result's reason when the answer was an API error row. */
13
+ export const API_ERROR = 'api-error: ';
14
+ /** True for a row Claude Code wrote for a failed API call: `isApiErrorMessage` in the transcript, an
15
+ * `error` on the assistant message in the print-mode stream. */
16
+ export function isApiErrorRow(row) {
17
+ const r = row;
18
+ if (r?.type !== 'assistant')
19
+ return false;
20
+ return r.isApiErrorMessage === true || (typeof r.error === 'string' && r.error.length > 0);
21
+ }
22
+ /** The error text to hold back from the chat, or null when it is no error or a usage limit. */
23
+ export function apiErrorText(row) {
24
+ if (!isApiErrorRow(row))
25
+ return null;
26
+ const c = row.message?.content;
27
+ const text = typeof c === 'string' ? c.trim()
28
+ : Array.isArray(c) ? c.map((b) => (b?.type === 'text' ? String(b.text ?? '') : '')).join('\n').trim() : '';
29
+ return isLimitText(text) ? null : text;
30
+ }
31
+ export const apiErrorReason = (text) => `${API_ERROR}${text.replace(/\s+/g, ' ').trim().slice(0, 300)}`;
32
+ export const isApiErrorReason = (reason) => String(reason ?? '').startsWith(API_ERROR);
33
+ /** The CLI lost its login: only `claude` then `/login` on the host helps, and a retry a minute later
34
+ * only when someone did that in between. Kept to what Claude Code and the API say for it. */
35
+ const LOGIN = /not logged in|please run \/login|invalid api key|oauth token (has )?expired|authentication_error/i;
36
+ export function loginLost(text) {
37
+ return LOGIN.test(text);
38
+ }
39
+ //# sourceMappingURL=api-error.js.map
@@ -1,4 +1,5 @@
1
1
  import { homedir } from 'node:os';
2
+ import { readFileSync } from 'node:fs';
2
3
  import { mcpLaunch, readRecord } from '../capabilities/compile.js';
3
4
  /** Variables that switch a CLI from the user's subscription to per-token API billing, or send it
4
5
  * to another endpoint. None of them reaches any agent, whatever its backend: a grok profile's shell
@@ -24,8 +25,9 @@ export function tuiSettings(p, hooks, mcp = mcpLaunch(p.cwd)) {
24
25
  return { ...mcp.settings, ...hooks };
25
26
  }
26
27
  /** `mcp`: the MCP launch the daemon took from the profile's guard (guardMcpLaunch); unset, it is read
27
- * from the record in the profile's folder (mcpLaunch). */
28
- export function claudeArgv(p, s, bin = 'claude', system, mcp = mcpLaunch(p.cwd)) {
28
+ * from the record in the profile's folder (mcpLaunch). `settingsFile`: the compile's copy of its keys
29
+ * (BrainOptions.mcpSettingsFile), passed by path when it holds exactly them; else they go inline. */
30
+ export function claudeArgv(p, s, bin = 'claude', system, mcp = mcpLaunch(p.cwd), settingsFile) {
29
31
  const a = [bin, '-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--permission-prompt-tool', 'stdio'];
30
32
  if (p.permission_mode === 'bypassPermissions')
31
33
  a.push('--dangerously-skip-permissions');
@@ -45,11 +47,20 @@ export function claudeArgv(p, s, bin = 'claude', system, mcp = mcpLaunch(p.cwd))
45
47
  // so a launch with none (a strict profile with no connector) is the exact argv it was.
46
48
  a.push(...mcp.args);
47
49
  if (Object.keys(mcp.settings).length)
48
- a.push('--settings', JSON.stringify(mcp.settings));
50
+ a.push('--settings', settingsFile && sameKeys(settingsFile, mcp.settings) ? settingsFile : JSON.stringify(mcp.settings));
49
51
  if (system)
50
52
  a.push('--append-system-prompt', system);
51
53
  return a;
52
54
  }
55
+ /** The settings file holds these keys and no others (compared as JSON). */
56
+ function sameKeys(file, settings) {
57
+ try {
58
+ return JSON.stringify(JSON.parse(readFileSync(file, 'utf8'))) === JSON.stringify(settings);
59
+ }
60
+ catch {
61
+ return false;
62
+ }
63
+ }
53
64
  /** A stable, readable name per profile and session: the tmux session and the Remote Control name.
54
65
  * Only an interactive session joins Remote Control (measured 2026-09-19 against claude 2.1.278: in
55
66
  * print mode the flag is accepted and ignored), so print mode never passes it; tui mode always does. */
@@ -7,6 +7,7 @@ import { RECORD } from '../capabilities/compile.js';
7
7
  import { isLimitText } from '../core/deliver/text.js';
8
8
  import { Config } from '../instance/config/schema.js';
9
9
  import { INSTANCE_DIR } from '../instance/instance.js';
10
+ import { API_ERROR, isApiErrorReason, loginLost } from './api-error.js';
10
11
  import { childEnv } from './argv.js';
11
12
  import { catalog } from './catalog.js';
12
13
  import { DEFAULT_BIN, locateBin } from './locate.js';
@@ -62,23 +63,23 @@ export function turnEnd(logs) {
62
63
  const m = line && /^tmux: turn ended by (.*) after (\d+) s, answer \d+ chars/.exec(line);
63
64
  if (!m)
64
65
  return null;
65
- const by = m[1].startsWith('the Stop marker') ? 'stop' : 'quiet';
66
+ const by = m[1].endsWith('as an API error') ? 'api-error' : m[1].startsWith('the Stop marker') ? 'stop' : 'quiet';
66
67
  return { by, seconds: Number(m[2]) };
67
68
  }
68
- /** The CLI lost its login: only `claude` then `/login` on the host helps. Kept to what Claude Code
69
- * and the API say for it. */
70
- const LOGIN = /not logged in|please run \/login|invalid api key|oauth token (has )?expired|authentication_error/i;
71
- export const loginLost = (text) => LOGIN.test(text);
72
69
  const cut = (text, max = 120) => { const t = text.replace(/\s+/g, ' ').trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; };
73
- /** Why a turn's result says nothing about the build: the plan ran out, or the CLI lost its login.
74
- * Any build ends such a turn the same way. Null: the result can be judged. A short answer that is
75
- * the CLI's own login line (it comes as the turn's text) counts as a lost login. */
70
+ /** Why a turn's result says nothing about the build: the plan ran out, the API call failed, or the
71
+ * CLI lost its login. Any build ends such a turn the same way. Null: the result can be judged. */
76
72
  export function cannotJudge(r) {
77
73
  if (isLimitText(r.text))
78
74
  return `the plan's usage limit was reached ("${cut(r.text)}")`;
75
+ if (!r.isError)
76
+ return null;
79
77
  const reason = r.reason ?? '';
80
- if ((r.isError && loginLost(reason)) || (r.text.length < 200 && loginLost(r.text)))
81
- return `Claude Code lost its login ("${cut(r.text || reason)}")`;
78
+ const said = isApiErrorReason(reason) ? reason.slice(API_ERROR.length) : reason;
79
+ if (loginLost(reason) || loginLost(r.text))
80
+ return `Claude Code lost its login ("${cut(said || r.text)}")`;
81
+ if (isApiErrorReason(reason))
82
+ return isLimitText(said) ? `the plan's usage limit was reached ("${cut(said)}")` : `the model's API call failed ("${cut(said)}")`;
82
83
  return null;
83
84
  }
84
85
  /** An answer as one bare word: no quotes, stars or full stop around it. */
@@ -3,6 +3,9 @@ import { EventEmitter } from 'node:events';
3
3
  import { claudeArgv, childEnv, versionAtLeast, CLAUDE_ENV, MIN_CLAUDE_VERSION } from './argv.js';
4
4
  import { BrainExited, PermissionBook, blockedConnectorNames, blockedShort, deniedConnectorCount, exitReason, jsonLine, permissionPreview, stopChild, wireChild, CHILD_GROUP, signalGroup } from './brain.js';
5
5
  import { LOST_SESSION_LINE, placeTranscript } from './transcripts.js';
6
+ import { apiErrorReason, apiErrorText } from './api-error.js';
7
+ import { backgroundRows, TEAMMATE_MAX_MS } from './tui.js';
8
+ import { isLimitText } from '../core/deliver/text.js';
6
9
  import { mcpLaunch } from '../capabilities/compile.js';
7
10
  export { BrainExited, exitReason } from './brain.js';
8
11
  /** How long after the spawn the connectors Claude Code named as blocked are counted (checkBlocked). */
@@ -12,6 +15,9 @@ export class ClaudeBrain extends EventEmitter {
12
15
  profile;
13
16
  session;
14
17
  opts;
18
+ /** Background tasks open in the child (a shell command, a subagent), by tool_use id, and when. */
19
+ tasks = new Map();
20
+ calls = new Map();
15
21
  child;
16
22
  lines = new EventEmitter();
17
23
  exited = false;
@@ -60,7 +66,7 @@ export class ClaudeBrain extends EventEmitter {
60
66
  session = { ...session, started: false };
61
67
  }
62
68
  }
63
- const [bin, ...args] = claudeArgv(this.profile, session, this.opts.bin ?? 'claude', this.opts.system, this.opts.mcp);
69
+ const [bin, ...args] = claudeArgv(this.profile, session, this.opts.bin ?? 'claude', this.opts.system, this.opts.mcp, this.opts.mcpSettingsFile);
64
70
  this.deniedConnectors = deniedConnectorCount((this.opts.mcp ?? mcpLaunch(this.profile.cwd)).settings);
65
71
  const child = spawn(bin, args, { cwd: this.profile.cwd, env: { ...childEnv(this.opts.env), ...CLAUDE_ENV }, stdio: ['pipe', 'pipe', 'pipe'], ...CHILD_GROUP });
66
72
  this.child = child;
@@ -70,13 +76,14 @@ export class ClaudeBrain extends EventEmitter {
70
76
  this.exited = true;
71
77
  clearTimeout(this.blockedTimer); // a child gone before the check says nothing about its connectors
72
78
  this.permissions.clear();
79
+ this.tasks.clear(); // the child's tasks go with it
73
80
  this.lines.emit('exit', { code, signal });
74
81
  this.emit('exit', { code, signal });
75
82
  };
76
83
  wireChild(child, {
77
84
  exit: done,
78
85
  failure: (t) => { this.failure = t; },
79
- line: (obj) => { this.lastOutputAt = Date.now(); this.lines.emit('line', obj); },
86
+ line: (obj) => { this.lastOutputAt = Date.now(); this.noteTasks(obj); this.lines.emit('line', obj); },
80
87
  benign: (line) => { this.blocked.push(...blockedConnectorNames(line)); },
81
88
  });
82
89
  // Claude Code does not wait for the account's connector list before the first turn (docs/reference.md,
@@ -90,6 +97,30 @@ export class ClaudeBrain extends EventEmitter {
90
97
  // and the model tends to invent a result. Verified against claude 2.1.272.
91
98
  this.send({ type: 'control_request', request_id: 'init-1', request: { subtype: 'initialize', hooks: {} } });
92
99
  }
100
+ /** What a line of the stream says of background work: a start in a call's result (the transcript's
101
+ * shape, backgroundRows, with `tool_use_result` for `toolUseResult`) or in `task_started`, an end
102
+ * in `task_notification`. */
103
+ noteTasks(l) {
104
+ if (l.type === 'system' && typeof l.tool_use_id === 'string') {
105
+ if (l.subtype === 'task_started' && l.is_backgrounded === true)
106
+ this.tasks.set(l.tool_use_id, Date.now());
107
+ else if (l.subtype === 'task_notification')
108
+ this.tasks.delete(l.tool_use_id);
109
+ }
110
+ else if (l.type === 'assistant' || l.type === 'user') {
111
+ const { starts, ends } = backgroundRows(JSON.stringify({ ...l, toolUseResult: l.toolUseResult ?? l.tool_use_result }), this.calls);
112
+ for (const s of starts)
113
+ this.tasks.set(s.id, Date.now());
114
+ for (const id of ends)
115
+ this.tasks.delete(id);
116
+ }
117
+ }
118
+ openTaskCount() {
119
+ for (const [id, at] of this.tasks)
120
+ if (Date.now() - at >= TEAMMATE_MAX_MS)
121
+ this.tasks.delete(id);
122
+ return this.tasks.size;
123
+ }
93
124
  /** Once per start, while the child runs: a start that named fewer connectors as blocked than it
94
125
  * drops says so in the log and as `connectors-short`, with the names it blocked. */
95
126
  checkBlocked() {
@@ -130,6 +161,8 @@ export class ClaudeBrain extends EventEmitter {
130
161
  this.lines.on('exit', onExit);
131
162
  this.send({ type: 'user', message: { role: 'user', content: text }, parent_tool_use_id: null });
132
163
  let pendingText = null;
164
+ // The text of an API error row (api-error.ts): a result that only repeats it is no answer.
165
+ let failed = null;
133
166
  try {
134
167
  if (this.notice) {
135
168
  yield { kind: 'notice', text: this.notice };
@@ -157,7 +190,15 @@ export class ClaudeBrain extends EventEmitter {
157
190
  }
158
191
  continue;
159
192
  }
160
- if (l.type === 'assistant') {
193
+ if (l.type === 'assistant' && apiErrorText(l) !== null) {
194
+ if (pendingText) {
195
+ yield { kind: 'progress', text: pendingText };
196
+ pendingText = null;
197
+ }
198
+ failed = apiErrorText(l);
199
+ }
200
+ else if (l.type === 'assistant') {
201
+ failed = null;
161
202
  const blocks = l.message?.content ?? [];
162
203
  for (const b of blocks) {
163
204
  if (b.type === 'text' && String(b.text ?? '').trim()) {
@@ -181,7 +222,13 @@ export class ClaudeBrain extends EventEmitter {
181
222
  }
182
223
  else if (l.type === 'result') {
183
224
  this.lastUsedAt = Date.now();
184
- yield { kind: 'result', text: String(l.result ?? '').trim(), isError: !!l.is_error };
225
+ const text = String(l.result ?? '').trim();
226
+ // An error result with words is the API's failure, said as the answer; a usage limit keeps its own path.
227
+ if (text && !isLimitText(text) && (l.is_error || text === failed)) {
228
+ yield { kind: 'result', text, isError: true, reason: apiErrorReason(text) };
229
+ return;
230
+ }
231
+ yield { kind: 'result', text, isError: !!l.is_error };
185
232
  return;
186
233
  }
187
234
  }
@@ -1,4 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
2
4
  import { CLAUDE_ENV } from './argv.js';
3
5
  import { deniedConnectorCount, trackGroup } from './brain.js';
4
6
  /**
@@ -54,16 +56,42 @@ export function plainSettings(settings) {
54
56
  }
55
57
  return Object.keys(out).length ? out : undefined;
56
58
  }
59
+ /**
60
+ * Where the settings files of the list runs go: under the state folder's compiled/, which every
61
+ * profile's deny floor closes, never the temp folder, which the agent's Bash can read (it runs as
62
+ * the same user, and mode 0600 does not keep it out). Each run's file is removed when it ends.
63
+ */
64
+ export const mcpListRoot = (stateDir) => join(stateDir, 'compiled', 'mcp-list');
65
+ /** The files a daemon that died mid-check left: removed at daemon start (daemon.ts). */
66
+ export function clearMcpListFiles(stateDir) { rmSync(mcpListRoot(stateDir), { recursive: true, force: true }); }
57
67
  /** The most of a list's output that is read. */
58
68
  const MCP_LIST_MAX = 4 << 20;
59
69
  /**
60
70
  * One `claude mcp list`, with these settings when given: its connectors, or null when it failed. It
61
71
  * runs in its own process group under a timer of ours: at the timeout the whole group is killed and
62
72
  * the answer is given at once, so a claude that does not exit, or a server it started that holds its
63
- * output open, never holds the queue of checks.
73
+ * output open, never holds the queue of checks. The settings go by a private file under mcpListRoot of
74
+ * `stateDir`, never on the command line: they name the dropped connectors' addresses, and any process
75
+ * of the user (the agent's too) can list a command line.
64
76
  */
65
- export function mcpListConnectors(bin, cwd, env, settings, timeoutMs = MCP_LIST_TIMEOUT_MS) {
66
- const args = [...(settings ? ['--settings', JSON.stringify(settings)] : []), 'mcp', 'list'];
77
+ export function mcpListConnectors(bin, cwd, env, stateDir, settings, timeoutMs = MCP_LIST_TIMEOUT_MS) {
78
+ let dir;
79
+ const args = ['mcp', 'list'];
80
+ if (settings) {
81
+ try {
82
+ const root = mcpListRoot(stateDir);
83
+ mkdirSync(root, { recursive: true, mode: 0o700 });
84
+ dir = mkdtempSync(join(root, 'run-'));
85
+ const file = join(dir, 'settings.json');
86
+ writeFileSync(file, JSON.stringify(settings), { mode: 0o600 });
87
+ args.unshift('--settings', file);
88
+ }
89
+ catch {
90
+ if (dir)
91
+ rmSync(dir, { recursive: true, force: true });
92
+ return Promise.resolve(null);
93
+ }
94
+ }
67
95
  return new Promise((done) => {
68
96
  const child = spawn(bin, args, { cwd, env, detached: true, stdio: ['ignore', 'pipe', 'ignore'] });
69
97
  trackGroup(child); // the daemon's exit ends it too
@@ -80,6 +108,8 @@ export function mcpListConnectors(bin, cwd, env, settings, timeoutMs = MCP_LIST_
80
108
  }
81
109
  catch { /* the group is gone */ }
82
110
  child.stdout.destroy();
111
+ if (dir)
112
+ rmSync(dir, { recursive: true, force: true });
83
113
  done(result);
84
114
  };
85
115
  const timer = setTimeout(() => end(null), timeoutMs);
@@ -94,16 +124,17 @@ export function mcpListConnectors(bin, cwd, env, settings, timeoutMs = MCP_LIST_
94
124
  let queue = Promise.resolve();
95
125
  /**
96
126
  * The connectors the launch's MCP keys (`settings`) block: listed without its connector denies, not
97
- * with them. `env` is the profile's; the runs get only mcpListEnv of it. Null when it cannot tell: a
127
+ * with them. `env` is the profile's; the runs get only mcpListEnv of it. `stateDir`: the daemon's state
128
+ * folder, where the runs' settings files go (mcpListRoot). Null when it cannot tell: a
98
129
  * list failed; the plain list names no connector (the account has none, or its connector list did not
99
130
  * load), so a short count would say nothing about the addresses; or the list with the denies names no
100
131
  * connector while the plain one names more than the denies have addresses (its connector list did not
101
132
  * load either, and every connector would count as blocked).
102
133
  */
103
- export function tuiBlockedConnectors(bin, cwd, env, settings, timeoutMs = MCP_LIST_TIMEOUT_MS) {
134
+ export function tuiBlockedConnectors(bin, cwd, env, settings, stateDir, timeoutMs = MCP_LIST_TIMEOUT_MS) {
104
135
  const run = async () => {
105
136
  const e = mcpListEnv(env, CLAUDE_ENV);
106
- const [all, kept] = await Promise.all([mcpListConnectors(bin, cwd, e, plainSettings(settings), timeoutMs), mcpListConnectors(bin, cwd, e, settings, timeoutMs)]);
137
+ const [all, kept] = await Promise.all([mcpListConnectors(bin, cwd, e, stateDir, plainSettings(settings), timeoutMs), mcpListConnectors(bin, cwd, e, stateDir, settings, timeoutMs)]);
107
138
  if (!all || !kept || !all.length)
108
139
  return null;
109
140
  if (!kept.length && all.length > deniedConnectorCount(settings))
@@ -111,6 +111,15 @@ export function paneBusy(pane) {
111
111
  }
112
112
  return busy;
113
113
  }
114
+ /** A teammate's row in the list under the input box: `◯ <name> <what it does> 21s · ↓ 87.0k tokens`
115
+ * (claude 2.1.329, fixture pane-busy-teammates.txt). */
116
+ const TEAMMATE_ROW = /^\s*◯\s+\S+\s{2,}.*\d+s\s+·\s+[↓↑]/;
117
+ /** True when the foot of the pane, under the input box, lists a teammate. */
118
+ export function listsTeammates(pane) {
119
+ const lines = pane.replace(/\n+$/, '').split('\n');
120
+ const box = boxSpan(lines);
121
+ return box !== null && lines.slice(box.bottom + 1).some((l) => TEAMMATE_ROW.test(l));
122
+ }
114
123
  /** Safe to paste: the input box is on screen with its prompt, and no turn is running. Pasting into a
115
124
  * dialog would answer it (Enter takes the highlighted option) and pasting mid-turn is dropped
116
125
  * or queued, so both have to be excluded, not just waited out.
@@ -0,0 +1,131 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { readlink } from 'node:fs/promises';
3
+ import { versionAtLeast } from './argv.js';
4
+ import { listsTeammates, paneIdle, tmux } from './tmux.js';
5
+ /**
6
+ * End the panes on Angelia's tmux server that no chat will reach again: a name with one of this
7
+ * table's tui prefixes that is not in `keep`, sitting idle. A daemon restart forgets which panes it
8
+ * released, and a /new after that would otherwise leave the old one running for good, with its MCP
9
+ * servers, its permissions and its Remote Control registration. A busy pane is left alone.
10
+ */
11
+ export async function sweepPanes(keep, prefixes, env) {
12
+ if (!prefixes.length)
13
+ return [];
14
+ const list = await tmux(['list-sessions', '-F', '#{session_name}'], { env });
15
+ if (list.code !== 0)
16
+ return [];
17
+ const gone = [];
18
+ for (const name of list.out.split('\n').filter(Boolean)) {
19
+ if (keep.has(name) || !prefixes.some((p) => name.startsWith(p)))
20
+ continue;
21
+ const pane = await tmux(['capture-pane', '-p', '-t', name, '-S', '-30'], { env });
22
+ if (pane.code !== 0 || !paneIdle(pane.out))
23
+ continue;
24
+ if ((await tmux(['kill-session', '-t', name], { env })).code === 0)
25
+ gone.push(name);
26
+ }
27
+ return gone;
28
+ }
29
+ /** The x.y.z of a native Claude Code install in a path or command line (`…/claude/versions/2.1.310`).
30
+ * `claude/` is part of it: an MCP server under `~/.pyenv/versions/1.2.3` is no build of Claude's. */
31
+ export function buildIn(s) {
32
+ return /\bclaude\/versions\/(\d+\.\d+\.\d+)(?=$|[/\s])/.exec(s)?.[1] ?? null;
33
+ }
34
+ /**
35
+ * Each session on Angelia's tmux server: when its window last saw input or output, in epoch seconds,
36
+ * and its pane's process. `window_activity`, not `session_activity`: on tmux 3.7c the session's stays
37
+ * at the time it was made, through send-keys, paste-buffer and pane output, so "idle 12h" would mean
38
+ * "made 12h ago" (measured 2026-11-26). Undefined when tmux could not be read.
39
+ */
40
+ export async function paneActivity(env) {
41
+ const list = await tmux(['list-sessions', '-F', '#{session_name}\t#{window_activity}\t#{pane_pid}'], { env });
42
+ if (list.code !== 0)
43
+ return undefined;
44
+ return new Map(list.out.split('\n').filter(Boolean).map((l) => { const [n, a, p] = l.split('\t'); return [n, { activity: Number(a) || 0, pid: Number(p) || 0 }]; }));
45
+ }
46
+ /** Why an idle pane is ended, or null to keep it. `activity`: tmux's `window_activity`, in epoch
47
+ * seconds. `running` / `installed`: the builds, when both could be read; compared by number, so
48
+ * 2.1.310 is newer than 2.1.287. */
49
+ export function paneEndReason(o) {
50
+ const hours = (o.now / 1000 - o.activity) / 3600;
51
+ if (o.activity > 0 && hours >= o.idleHours)
52
+ return `idle ${Math.floor(hours)}h`;
53
+ if (o.running && o.installed && !versionAtLeast(o.running, o.installed))
54
+ return `old build ${o.running} -> ${o.installed}`;
55
+ return null;
56
+ }
57
+ const run = (cmd, args, env) => new Promise((done) => execFile(cmd, args, { env, timeout: 15_000 }, (_e, stdout) => done(String(stdout ?? ''))));
58
+ /** The build a pane runs, from its process and the processes it started: the command line when it
59
+ * names a versions folder, else the executable itself, which lsof names with the symlink resolved
60
+ * (`~/.local/bin/claude` points into `versions/`, and the command line shows only the link). Null
61
+ * when neither says, an npm install for one. `table`: `ps -axo pid=,ppid=,args=` already read. */
62
+ export async function paneBuild(pid, table) {
63
+ const procs = (await (table ?? run('ps', ['-Ao', 'pid=,ppid=,args=']))).split('\n').map((l) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(l)).filter((m) => m !== null);
64
+ // The pane's own process first (the CLI, exec'd by env), then what it started.
65
+ const mine = [...procs.filter((m) => Number(m[1]) === pid), ...procs.filter((m) => Number(m[2]) === pid)];
66
+ for (const m of mine) {
67
+ const exe = buildIn(m[3]) ? '' : await exeOf(m[1]);
68
+ const v = buildIn(m[3]) ?? buildIn(exe);
69
+ if (v)
70
+ return v;
71
+ }
72
+ return null;
73
+ }
74
+ /** The file a process runs. Linux: /proc/<pid>/exe (lsof there may not list a txt row for it); else lsof. */
75
+ async function exeOf(pid) {
76
+ if (process.platform === 'linux') {
77
+ try {
78
+ return await readlink(`/proc/${pid}/exe`);
79
+ }
80
+ catch {
81
+ return '';
82
+ }
83
+ }
84
+ return (await run('lsof', ['-a', '-p', pid, '-d', 'txt', '-Fn'])).split('\n').find((l) => l.startsWith('n'))?.slice(1) ?? '';
85
+ }
86
+ /** The build `bin --version` reports, or null. */
87
+ export async function installedBuild(bin, env) {
88
+ return /(\d+\.\d+\.\d+)/.exec(await run(bin, ['--version'], env))?.[1] ?? null;
89
+ }
90
+ /**
91
+ * End the panes no chat is reading that have sat idle `idleHours`, or that run an older Claude Code
92
+ * than the one installed. `release()` keeps a pane for good, and the orphan sweep spares every parked
93
+ * and active one, so without this panes piled up: 19 of them on 9 builds, some idle three weeks, whose
94
+ * MCP servers filled swap (2026-10-24). The next message starts the pane again with --resume. Only a
95
+ * pane idle on screen goes (never mid-turn, never with a dialog open or a teammate listed), and
96
+ * `mayEnd` is asked last, at the kill, so a message that came in meanwhile keeps it. Returns what was ended, and why.
97
+ */
98
+ export async function reapPanes(panes, env, o) {
99
+ if (!panes.length)
100
+ return [];
101
+ const live = await paneActivity(env);
102
+ if (!live)
103
+ return [];
104
+ const builds = new Map(); // one --version per CLI per sweep
105
+ const installed = (bin) => { let v = builds.get(bin); if (!v)
106
+ builds.set(bin, v = (o.installed ?? ((b) => installedBuild(b, env)))(bin)); return v; };
107
+ let table; // one process list per sweep, read only when a build is asked
108
+ const build = o.build ?? ((pid) => paneBuild(pid, table ??= run('ps', ['-Ao', 'pid=,ppid=,args='])));
109
+ const gone = [];
110
+ for (const p of panes) {
111
+ const t = live.get(p.name);
112
+ if (!t)
113
+ continue;
114
+ const pane = await tmux(['capture-pane', '-p', '-t', p.name, '-S', '-30'], { env });
115
+ // Never one that still lists a teammate: ending it would end the teammate and lose its report.
116
+ if (pane.code !== 0 || !paneIdle(pane.out) || listsTeammates(pane.out))
117
+ continue;
118
+ const now = o.now ?? Date.now();
119
+ let why = paneEndReason({ activity: t.activity, now, idleHours: o.idleHours, running: null, installed: null });
120
+ if (!why && p.bin && t.pid) {
121
+ const running = await build(t.pid);
122
+ why = running ? paneEndReason({ activity: t.activity, now, idleHours: o.idleHours, running, installed: await installed(p.bin) }) : null;
123
+ }
124
+ if (!why || !o.mayEnd(p))
125
+ continue;
126
+ if ((await tmux(['kill-session', '-t', p.name], { env })).code === 0)
127
+ gone.push({ name: p.name, key: p.key, why });
128
+ }
129
+ return gone;
130
+ }
131
+ //# sourceMappingURL=tui-panes.js.map