angelia-gateway 0.4.1 → 0.4.3

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.
@@ -1,5 +1,5 @@
1
1
  import { homedir } from 'node:os';
2
- import { readRecord, strictMcpArgs } from '../capabilities/compile.js';
2
+ import { mcpLaunch, readRecord } from '../capabilities/compile.js';
3
3
  /** Variables that switch a CLI from the user's subscription to per-token API billing, or send it
4
4
  * to another endpoint. None of them reaches any agent, whatever its backend: a grok profile's shell
5
5
  * could run `claude`, and a key in the daemon's environment was never meant for the agents.
@@ -17,7 +17,15 @@ export const MIN_CLAUDE_VERSION = '2.1.270';
17
17
  * the agent asks in its reply, which reaches the chat. The `=` form keeps the variadic flag from
18
18
  * eating the next argument. */
19
19
  export const NO_SCREEN_TOOLS = '--disallowed-tools=AskUserQuestion';
20
- export function claudeArgv(p, s, bin = 'claude', system) {
20
+ /** tmux mode's settings file: the hooks the pane runs (tui.ts) and the profile's MCP keys (mcpLaunch),
21
+ * in the one --settings the pane is started with. Of two --settings flags only the last counts
22
+ * (measured on claude 2.1.332: an allow list in the first was dropped). */
23
+ export function tuiSettings(p, hooks, mcp = mcpLaunch(p.cwd)) {
24
+ return { ...mcp.settings, ...hooks };
25
+ }
26
+ /** `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)) {
21
29
  const a = [bin, '-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--permission-prompt-tool', 'stdio'];
22
30
  if (p.permission_mode === 'bypassPermissions')
23
31
  a.push('--dangerously-skip-permissions');
@@ -33,7 +41,11 @@ export function claudeArgv(p, s, bin = 'claude', system) {
33
41
  if (p.chrome)
34
42
  a.push('--chrome');
35
43
  a.push(NO_SCREEN_TOOLS);
36
- a.push(...strictMcpArgs(p.cwd));
44
+ // Print mode passes no other --settings: the MCP keys get one of their own, only when there are any,
45
+ // so a launch with none (a strict profile with no connector) is the exact argv it was.
46
+ a.push(...mcp.args);
47
+ if (Object.keys(mcp.settings).length)
48
+ a.push('--settings', JSON.stringify(mcp.settings));
37
49
  if (system)
38
50
  a.push('--append-system-prompt', system);
39
51
  return a;
@@ -49,7 +61,7 @@ export function remoteControlName(p, s) {
49
61
  * session is the only kind Remote Control registers, so this is what puts a chat in the Claude
50
62
  * app; it also keeps MCP servers warm between turns and lets background tasks outlive a turn.
51
63
  * The answer comes back through the Stop hook in `settings`, not through stdout. */
52
- export function claudeTuiArgv(p, s, bin, settings, name, system) {
64
+ export function claudeTuiArgv(p, s, bin, settings, name, system, mcp = mcpLaunch(p.cwd)) {
53
65
  const a = [bin];
54
66
  if (p.permission_mode === 'bypassPermissions')
55
67
  a.push('--dangerously-skip-permissions');
@@ -67,7 +79,8 @@ export function claudeTuiArgv(p, s, bin, settings, name, system) {
67
79
  a.push('--chrome');
68
80
  a.push(NO_SCREEN_TOOLS);
69
81
  a.push('--remote-control', name);
70
- a.push(...strictMcpArgs(p.cwd));
82
+ // The MCP keys are in the settings file (tuiSettings); the flags here.
83
+ a.push(...mcp.args);
71
84
  if (system)
72
85
  a.push('--append-system-prompt', system);
73
86
  return a;
@@ -80,9 +93,11 @@ function shellWord(v, home) {
80
93
  }
81
94
  /** The chat's Claude Code session, for the owner at a terminal: `/status` prints it, so the work goes
82
95
  * on at the desk. What the chat runs comes along (its folder, permissions, model, effort, extra
83
- * folders, MCP servers, no auto memory); what only a chat needs stays out (print mode, the self
96
+ * folders, MCP servers and connectors, no auto memory); what only a chat needs stays out (print mode, the self
84
97
  * prompt, the Stop hook, Remote Control, the screen tools refused). */
85
- export function claudeTerminalLine(p, id, home = homedir()) {
98
+ /** `o.mcp`: the launch from the guard; `o.settingsFile`: the compile's copy of its MCP keys
99
+ * (mcpSettingsFile), passed by path so the line names no address. Without a file the keys go inline. */
100
+ export function claudeTerminalLine(p, id, home = homedir(), o = {}) {
86
101
  const w = (v) => shellWord(v, home);
87
102
  const a = [`cd ${w(p.cwd)}`, '&&', ...Object.entries(CLAUDE_ENV).map(([k, v]) => `${k}=${v}`), w(p.bin ?? 'claude')];
88
103
  if (p.permission_mode === 'bypassPermissions')
@@ -98,7 +113,10 @@ export function claudeTerminalLine(p, id, home = homedir()) {
98
113
  a.push('--add-dir', w(d));
99
114
  if (p.chrome)
100
115
  a.push('--chrome');
101
- a.push(...strictMcpArgs(p.cwd).map(w));
116
+ const mcp = o.mcp ?? mcpLaunch(p.cwd);
117
+ a.push(...mcp.args.map(w));
118
+ if (Object.keys(mcp.settings).length)
119
+ a.push('--settings', w(o.settingsFile ?? JSON.stringify(mcp.settings)));
102
120
  return a.join(' ');
103
121
  }
104
122
  /** Set for every Claude Code session Angelia starts, in print and tmux mode alike. Claude's auto
@@ -9,8 +9,9 @@ export class PermissionBook {
9
9
  this.timeoutMs = timeoutMs;
10
10
  this.onTimeout = onTimeout;
11
11
  }
12
- add(id) {
13
- this.pending.set(id, setTimeout(() => this.onTimeout(id), this.timeoutMs));
12
+ /** `ms`: a shorter wait for this one request (a tmux hook's own time left, tui.ts). */
13
+ add(id, ms = this.timeoutMs) {
14
+ this.pending.set(id, setTimeout(() => this.onTimeout(id), Math.min(ms, this.timeoutMs)));
14
15
  }
15
16
  /** Clears and returns the full id for a prefix, or null when it matches none or several. */
16
17
  take(prefix) {
@@ -145,12 +146,18 @@ process.on('exit', () => { for (const g of groups)
145
146
  process.kill(-g, 'SIGKILL');
146
147
  }
147
148
  catch { /* gone */ } });
149
+ /**
150
+ * stderr lines a healthy CLI prints, never a reason it died. Claude Code 2.1.332 prints the first at
151
+ * every start of a profile given a connector (the allow list leaves the account's other connectors
152
+ * out): "Warning: claude.ai MCP servers blocked by enterprise policy: claude.ai Google Drive, ...".
153
+ */
154
+ export const BENIGN_STDERR = [/^Warning: claude\.ai MCP servers blocked by enterprise policy:/];
148
155
  /**
149
156
  * Why the child died, for the log and for the retry decision. Always starts with `exit`, because
150
157
  * that prefix is what tells the orchestrator a brand-new session died before it ever answered.
151
158
  */
152
159
  export function exitReason(failure) {
153
- const line = failure.split('\n').map((l) => l.trim()).filter(Boolean).pop();
160
+ const line = failure.split('\n').map((l) => l.trim()).filter((l) => l && !BENIGN_STDERR.some((re) => re.test(l))).pop();
154
161
  return line ? `exit: ${line.slice(0, 200)}` : 'exit';
155
162
  }
156
163
  /**
@@ -206,7 +213,14 @@ export function wireChild(child, w) {
206
213
  child.on('exit', w.exit);
207
214
  child.on('error', (err) => { failure = err.message; w.failure(failure, 'error'); w.exit(null, null); });
208
215
  child.stdin.on('error', () => { });
209
- child.stderr.on('data', (b) => { failure = (failure + b.toString('utf8')).slice(-400); w.failure(failure, 'stderr'); });
216
+ child.stderr.on('data', (b) => {
217
+ // A line a healthy CLI prints (BENIGN_STDERR) is no failure text: kept, it could be the reason given.
218
+ const text = b.toString('utf8').split('\n').filter((l) => !BENIGN_STDERR.some((re) => re.test(l.trim()))).join('\n');
219
+ if (!text)
220
+ return;
221
+ failure = (failure + text).slice(-400);
222
+ w.failure(failure, 'stderr');
223
+ });
210
224
  onJsonLines(child.stdout, w.line);
211
225
  }
212
226
  /** One JSON line for a CLI's stdin, with U+2028 and U+2029 escaped: JSON.stringify leaves them raw,
@@ -365,7 +365,7 @@ export async function sweepOrphans(env, o = {}) {
365
365
  * a second one passed as an extra folder (so the add-dir dialog is one of the start dialogs), the
366
366
  * cheapest model. The pane is held as a chat's pane is: permission mode `default`, and the compiled
367
367
  * record and empty .mcp.json of a profile that is given no MCP server, so Claude Code is started with
368
- * `--strict-mcp-config` and loads none, the owner's own included (argv.ts, strictMcpArgs). The owner's
368
+ * `--strict-mcp-config` and loads none, the owner's own included (argv.ts, mcpLaunch). The owner's
369
369
  * hooks, settings and CLAUDE.md still load: that is how a chat's pane starts too. The pane, the
370
370
  * server, the folders and the session's transcript are removed at the end, whatever happened.
371
371
  */
@@ -52,7 +52,7 @@ export class ClaudeBrain extends EventEmitter {
52
52
  session = { ...session, started: false };
53
53
  }
54
54
  }
55
- const [bin, ...args] = claudeArgv(this.profile, session, this.opts.bin ?? 'claude', this.opts.system);
55
+ const [bin, ...args] = claudeArgv(this.profile, session, this.opts.bin ?? 'claude', this.opts.system, this.opts.mcp);
56
56
  const child = spawn(bin, args, { cwd: this.profile.cwd, env: { ...childEnv(this.opts.env), ...CLAUDE_ENV }, stdio: ['pipe', 'pipe', 'pipe'], ...CHILD_GROUP });
57
57
  this.child = child;
58
58
  trackGroup(child);
@@ -16,6 +16,8 @@ export function tmuxSocketPath(env = process.env) {
16
16
  catch { /* not there: tmux makes it */ }
17
17
  return join(base, `tmux-${process.getuid?.() ?? 0}`, TMUX_SOCKET);
18
18
  }
19
+ /** The longest one tmux client call may take (tmux(), `timeoutMs`). */
20
+ export const TMUX_TIMEOUT_MS = 30_000;
19
21
  /** The call run in a transient scope of its own: under systemd the service's KillMode kills every
20
22
  * process in its cgroup, and the tmux server must outlive the daemon. */
21
23
  export function scopedArgv(bin, args) {
@@ -27,9 +29,12 @@ export function scopedArgv(bin, args) {
27
29
  export function tmux(args, opts = {}) {
28
30
  const full = ['-L', opts.socket ?? TMUX_SOCKET, ...args];
29
31
  const run = (bin, argv) => new Promise((resolve) => {
30
- execFile(bin, argv, { env: opts.env, maxBuffer: 8 << 20 }, (err, stdout, stderr) => {
32
+ // A tmux server that does not answer must not hold a caller for ever (a restart's adoption runs before
33
+ // the daemon listens): every call is a short one, so past TMUX_TIMEOUT_MS the client is killed and the
34
+ // call fails.
35
+ execFile(bin, argv, { env: opts.env, maxBuffer: 8 << 20, timeout: opts.timeoutMs ?? TMUX_TIMEOUT_MS, killSignal: 'SIGKILL' }, (err, stdout, stderr) => {
31
36
  const e = err;
32
- resolve({ code: e ? Number(e.code ?? 1) : 0, out: stdout ?? '', err: stderr ?? '', missing: e?.code === 'ENOENT' });
37
+ resolve({ code: e ? Number(e.code ?? 1) : 0, out: stdout ?? '', err: stderr ?? '', missing: e?.code === 'ENOENT', ...(e?.killed ? { timedOut: true } : {}) });
33
38
  });
34
39
  });
35
40
  const plain = () => run(opts.bin ?? 'tmux', full);
@@ -122,6 +127,44 @@ export function paneIdle(pane) {
122
127
  const box = inputBoxStrict(pane);
123
128
  return box !== null && PROMPT_MARKERS.some((m) => `\n${box}`.includes(m));
124
129
  }
130
+ /** Safe to paste into a running turn: a turn runs, its input box is on screen with the prompt and
131
+ * holds nothing, and no dialog is open. Claude Code then queues what is submitted and gives it to the
132
+ * model at the next tool boundary of the same turn, or as the next turn when none comes (measured on
133
+ * claude 2.1.332, 2026-11-25: fixtures pane-busy-box-332 and pane-busy-queued-332). Never over text
134
+ * someone half typed in the box (pane-busy-halftyped-332): Enter would send theirs with ours. The
135
+ * hint "Press up to edit queued messages" is no text. A permission dialog replaces the box
136
+ * (pane-permission-332), so a capture with one is never safe; the caller still checks the
137
+ * transcript and the relay, since a dialog opened a moment ago may not be drawn yet. */
138
+ /** What sits in the input box: its lines without the prompt marker, or '' for an empty box or a
139
+ * screen with none. Claude Code's own hint in an empty box (`Try "write a test for <filepath>"`,
140
+ * `Press up to edit queued messages`) is not text that Enter would send, so it reads as empty. */
141
+ export function boxText(pane) {
142
+ const box = inputBoxStrict(pane);
143
+ if (box === null)
144
+ return '';
145
+ const t = box.split('\n').map((l) => l.replace(/^\s*(❯|>)\s?/, '').trim()).join('\n').trim();
146
+ if (t.startsWith('Try "') || t.startsWith('Press up to edit queued messages'))
147
+ return '';
148
+ return t;
149
+ }
150
+ export function paneMidTurn(pane, text) {
151
+ if (!pane || !paneBusy(pane) || permissionDialog(pane))
152
+ return false;
153
+ const box = inputBoxStrict(pane);
154
+ if (box === null || !PROMPT_MARKERS.some((m) => `\n${box}`.includes(m)))
155
+ return false;
156
+ // With `text`: the same screen, with that text in the box and nothing else (right before its Enter).
157
+ return text === undefined ? boxText(pane) === '' : boxHoldsOnly(pane, text);
158
+ }
159
+ /** The box holds `text` and nothing else: its collapsed chip (one paste), or the text itself, as the
160
+ * box wraps it. Not text someone typed before or after it. */
161
+ export function boxHoldsOnly(pane, text) {
162
+ const shown = boxText(pane);
163
+ if (/^\[Pasted text #\d+(?: \+\d+ lines?)?\]$/.test(shown))
164
+ return true;
165
+ const flat = (s) => s.replace(/\s+/g, '');
166
+ return !!flat(text) && flat(shown) === flat(text);
167
+ }
125
168
  const clean = (l) => l.replace(/[│╭╮╰╯┃]/g, ' ').replace(/\s+/g, ' ').trim();
126
169
  /** The open permission dialog as a chat line, or null when none is open. The dialog is drawn under
127
170
  * a full-width rule: the title, why the command runs, then the command between dashed rules:
@@ -13,8 +13,8 @@ import { permissionPreview } from './brain.js';
13
13
  * Otherwise it steps aside at once, and Claude opens its own dialog in the pane and the Claude app.
14
14
  */
15
15
  /** A heartbeat older than this means nobody reads the chat. The hook has the same number. Only a
16
- * daemon that died leaves one to go stale (every other end of a turn removes it at once), so this is
17
- * how long a hook waits after a crash, and how long a stalled daemon may stall. */
16
+ * daemon that died or stopped for a restart leaves one to go stale (every other end of a turn removes
17
+ * it at once); the hook then waits a minute more for the next daemon's (its RESTART_WAIT_MS). */
18
18
  export const RELAY_STALE_MS = 30_000;
19
19
  /** How often the heartbeat is written while a turn is read from the chat: on a timer of its own, so a
20
20
  * reader waiting on a slow chat send does not look like a daemon that stopped. */
@@ -22,6 +22,9 @@ export const RELAY_BEAT_MS = 1000;
22
22
  /** How long a dialog must stay on the pane, with no request from the hook, before the chat hears of it. */
23
23
  export const SCREEN_ONLY_MS = 1500;
24
24
  const REQUEST = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/;
25
+ /** How long the hook waits for an answer once it wrote its request (scripts/tui-permission-hook.mjs,
26
+ * GIVE_UP_MS). A request offered again after a restart has only what is left of it. */
27
+ export const HOOK_GIVE_UP_MS = 11 * 60_000;
25
28
  export class PermissionRelay {
26
29
  dir;
27
30
  /** Given to the chat and not answered from it. */
@@ -70,7 +73,17 @@ export class PermissionRelay {
70
73
  this.open.add(id);
71
74
  out.push({ id, tool: typeof row.tool_name === 'string' && row.tool_name ? row.tool_name : '?', input: row.tool_input, at: Number(row.at) || 0 });
72
75
  }
73
- return out.sort((a, b) => a.at - b.at).map(({ id, tool, input }) => ({ id, tool, input }));
76
+ return out.sort((a, b) => a.at - b.at).map(({ id, tool, input, at }) => ({ id, tool, input, ...(at ? { at } : {}) }));
77
+ }
78
+ /** A hook waits on a request now, taken or not: Claude Code draws its own dialog while the hook
79
+ * runs (measured on claude 2.1.332), so Enter must not be pressed for a message into the turn. */
80
+ waiting() {
81
+ try {
82
+ return readdirSync(this.dir).some((n) => REQUEST.test(n));
83
+ }
84
+ catch {
85
+ return false;
86
+ }
74
87
  }
75
88
  /** Requests given to the chat whose hook no longer waits: answered in the pane or the app, or it stepped aside. */
76
89
  gone() {