angelia-gateway 0.4.4 → 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.
- package/dist/adapters/whatsapp/adapter.js +3 -1
- package/dist/brain/agy.js +1 -1
- package/dist/brain/api-error.js +39 -0
- package/dist/brain/argv.js +14 -3
- package/dist/brain/brain.js +47 -3
- package/dist/brain/canary.js +11 -10
- package/dist/brain/claude.js +86 -18
- package/dist/brain/connectors-check.js +149 -0
- package/dist/brain/tmux.js +9 -0
- package/dist/brain/tui-panes.js +131 -0
- package/dist/brain/tui-permissions.js +1 -1
- package/dist/brain/tui.js +330 -72
- package/dist/build.json +3 -3
- package/dist/capabilities/compile.js +370 -85
- package/dist/capabilities/resolve.js +26 -0
- package/dist/cli/cli-args.js +3 -3
- package/dist/cli/cli.js +4 -2
- package/dist/core/deliver/text.js +2 -0
- package/dist/core/orchestrator.js +260 -45
- package/dist/core/session/notes.js +147 -0
- package/dist/daemon/api/client.js +19 -7
- package/dist/daemon/api/deps.js +2 -2
- package/dist/daemon/api/routes.js +4 -3
- package/dist/daemon/api/server.js +30 -3
- package/dist/daemon/daemon.js +22 -4
- package/dist/daemon/health.js +6 -2
- package/dist/instance/accepted.js +1 -1
- package/dist/instance/config/load.js +15 -0
- package/dist/instance/config/schema.js +19 -2
- package/dist/instance/export.js +22 -0
- package/dist/instance/guide.js +16 -3
- package/dist/instance/instance.js +3 -2
- package/dist/jobs/jobs-cli.js +4 -4
- package/dist/jobs/jobs.js +4 -3
- package/package.json +1 -1
- package/scripts/turn-origin.mjs +6 -5
|
@@ -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
|
-
|
|
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', ['-
|
|
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
|
package/dist/brain/argv.js
CHANGED
|
@@ -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
|
-
|
|
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. */
|
package/dist/brain/brain.js
CHANGED
|
@@ -149,9 +149,41 @@ process.on('exit', () => { for (const g of groups)
|
|
|
149
149
|
/**
|
|
150
150
|
* stderr lines a healthy CLI prints, never a reason it died. Claude Code 2.1.332 prints the first at
|
|
151
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, ..."
|
|
152
|
+
* out): "Warning: claude.ai MCP servers blocked by enterprise policy: claude.ai Google Drive, ...", and
|
|
153
|
+
* with one connector left out (a deny list of one, connectors: all) "MCP server blocked" (measured).
|
|
153
154
|
*/
|
|
154
|
-
export const BENIGN_STDERR = [/^Warning: claude\.ai MCP servers blocked by enterprise policy:/];
|
|
155
|
+
export const BENIGN_STDERR = [/^Warning: claude\.ai MCP servers? blocked by enterprise policy:/];
|
|
156
|
+
/**
|
|
157
|
+
* The connectors one such line names as blocked, as Claude Code 2.1.332 prints it (its template, read
|
|
158
|
+
* in the binary: "Warning: " + "claude.ai MCP server" or "servers" + " blocked by enterprise policy: "
|
|
159
|
+
* + the names, joined by ", "): ["claude.ai Gmail", ...]. None for any other line.
|
|
160
|
+
*/
|
|
161
|
+
export function blockedConnectorNames(line) {
|
|
162
|
+
const m = /^Warning: claude\.ai MCP servers? blocked by enterprise policy:\s*(.*)$/.exec(line.trim());
|
|
163
|
+
return m ? m[1].split(/,\s*/).map((n) => n.trim()).filter(Boolean) : [];
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* The connectors a launch blocks in `connectors: all` (allLaunch): the serverUrl entries of its deny
|
|
167
|
+
* list, when it has no allow list. Zero for any other launch: a granted profile's allow list blocks
|
|
168
|
+
* every other connector of the account, so its warning names more than Angelia dropped.
|
|
169
|
+
*/
|
|
170
|
+
export function deniedConnectorCount(settings) {
|
|
171
|
+
if ('allowedMcpServers' in settings || !Array.isArray(settings.deniedMcpServers))
|
|
172
|
+
return 0;
|
|
173
|
+
return new Set(settings.deniedMcpServers.flatMap((e) => (e && typeof e === 'object' && typeof e.serverUrl === 'string' ? [e.serverUrl] : []))).size;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* The daemon's check of a deny list by address (connectors: all), which matches nothing when a pattern
|
|
177
|
+
* is wrong or a connector moved, and so fails open. Undefined when the start blocked at least as many
|
|
178
|
+
* connectors as it drops; else the log's warning. Not proof either way: a dropped connector the
|
|
179
|
+
* account does not have (never connected, or disconnected in the Claude app) is no line either, and
|
|
180
|
+
* one pattern that matches two connectors gives two names.
|
|
181
|
+
*/
|
|
182
|
+
export function blockedShort(denied, blocked) {
|
|
183
|
+
if (!denied || blocked.length >= denied)
|
|
184
|
+
return undefined;
|
|
185
|
+
return `connectors: all: this start dropped ${denied} connector${denied === 1 ? '' : 's'} by address, but Claude Code named ${blocked.length} as blocked${blocked.length ? ` (${blocked.join(', ')})` : ''}: a dropped connector may be loading (a wrong address in the table, or one the Claude app changed), or the account does not have it, or its connector list did not load`;
|
|
186
|
+
}
|
|
155
187
|
/**
|
|
156
188
|
* Why the child died, for the log and for the retry decision. Always starts with `exit`, because
|
|
157
189
|
* that prefix is what tells the orchestrator a brand-new session died before it ever answered.
|
|
@@ -213,9 +245,21 @@ export function wireChild(child, w) {
|
|
|
213
245
|
child.on('exit', w.exit);
|
|
214
246
|
child.on('error', (err) => { failure = err.message; w.failure(failure, 'error'); w.exit(null, null); });
|
|
215
247
|
child.stdin.on('error', () => { });
|
|
248
|
+
// Whole lines for `benign`: a chunk may end inside one.
|
|
249
|
+
let part = '';
|
|
250
|
+
const benign = (l) => { if (BENIGN_STDERR.some((re) => re.test(l.trim())))
|
|
251
|
+
w.benign?.(l.trim()); };
|
|
252
|
+
child.stderr.on('end', () => { if (part)
|
|
253
|
+
benign(part); part = ''; });
|
|
216
254
|
child.stderr.on('data', (b) => {
|
|
255
|
+
const chunk = b.toString('utf8');
|
|
256
|
+
if (w.benign) {
|
|
257
|
+
const lines = (part + chunk).split('\n');
|
|
258
|
+
part = lines.pop() ?? '';
|
|
259
|
+
lines.forEach(benign);
|
|
260
|
+
}
|
|
217
261
|
// A line a healthy CLI prints (BENIGN_STDERR) is no failure text: kept, it could be the reason given.
|
|
218
|
-
const text =
|
|
262
|
+
const text = chunk.split('\n').filter((l) => !BENIGN_STDERR.some((re) => re.test(l.trim()))).join('\n');
|
|
219
263
|
if (!text)
|
|
220
264
|
return;
|
|
221
265
|
failure = (failure + text).slice(-400);
|
package/dist/brain/canary.js
CHANGED
|
@@ -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,
|
|
74
|
-
* Any build ends such a turn the same way. Null: the result can be judged.
|
|
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
|
-
|
|
81
|
-
|
|
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. */
|
package/dist/brain/claude.js
CHANGED
|
@@ -1,14 +1,23 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { EventEmitter } from 'node:events';
|
|
3
3
|
import { claudeArgv, childEnv, versionAtLeast, CLAUDE_ENV, MIN_CLAUDE_VERSION } from './argv.js';
|
|
4
|
-
import { BrainExited, PermissionBook, exitReason, jsonLine,
|
|
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';
|
|
9
|
+
import { mcpLaunch } from '../capabilities/compile.js';
|
|
6
10
|
export { BrainExited, exitReason } from './brain.js';
|
|
11
|
+
/** How long after the spawn the connectors Claude Code named as blocked are counted (checkBlocked). */
|
|
12
|
+
export const BLOCKED_CHECK_MS = 30_000;
|
|
7
13
|
/** One long-lived `claude -p --input-format stream-json` child for one session key. */
|
|
8
14
|
export class ClaudeBrain extends EventEmitter {
|
|
9
15
|
profile;
|
|
10
16
|
session;
|
|
11
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();
|
|
12
21
|
child;
|
|
13
22
|
lines = new EventEmitter();
|
|
14
23
|
exited = false;
|
|
@@ -25,6 +34,11 @@ export class ClaudeBrain extends EventEmitter {
|
|
|
25
34
|
version = '';
|
|
26
35
|
/** Claude Code accepts the id Angelia mints, so the backend id is the session id. */
|
|
27
36
|
backendSessionId;
|
|
37
|
+
/** connectors: all: how many connectors this launch drops by address, and the ones Claude Code's
|
|
38
|
+
* stderr named as blocked (blockedShort, checked once, BLOCKED_CHECK_MS after the spawn). */
|
|
39
|
+
deniedConnectors = 0;
|
|
40
|
+
blocked = [];
|
|
41
|
+
blockedTimer;
|
|
28
42
|
constructor(profile, session, opts = {}) {
|
|
29
43
|
super();
|
|
30
44
|
this.profile = profile;
|
|
@@ -52,35 +66,73 @@ export class ClaudeBrain extends EventEmitter {
|
|
|
52
66
|
session = { ...session, started: false };
|
|
53
67
|
}
|
|
54
68
|
}
|
|
55
|
-
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);
|
|
70
|
+
this.deniedConnectors = deniedConnectorCount((this.opts.mcp ?? mcpLaunch(this.profile.cwd)).settings);
|
|
56
71
|
const child = spawn(bin, args, { cwd: this.profile.cwd, env: { ...childEnv(this.opts.env), ...CLAUDE_ENV }, stdio: ['pipe', 'pipe', 'pipe'], ...CHILD_GROUP });
|
|
57
72
|
this.child = child;
|
|
58
|
-
trackGroup(child);
|
|
59
73
|
const done = (code, signal) => {
|
|
60
74
|
if (this.exited)
|
|
61
75
|
return;
|
|
62
76
|
this.exited = true;
|
|
77
|
+
clearTimeout(this.blockedTimer); // a child gone before the check says nothing about its connectors
|
|
63
78
|
this.permissions.clear();
|
|
79
|
+
this.tasks.clear(); // the child's tasks go with it
|
|
64
80
|
this.lines.emit('exit', { code, signal });
|
|
65
81
|
this.emit('exit', { code, signal });
|
|
66
82
|
};
|
|
67
|
-
child
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
//
|
|
74
|
-
|
|
75
|
-
//
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
83
|
+
wireChild(child, {
|
|
84
|
+
exit: done,
|
|
85
|
+
failure: (t) => { this.failure = t; },
|
|
86
|
+
line: (obj) => { this.lastOutputAt = Date.now(); this.noteTasks(obj); this.lines.emit('line', obj); },
|
|
87
|
+
benign: (line) => { this.blocked.push(...blockedConnectorNames(line)); },
|
|
88
|
+
});
|
|
89
|
+
// Claude Code does not wait for the account's connector list before the first turn (docs/reference.md,
|
|
90
|
+
// "The first turn of a new session"), so its warning may come after that turn's result: the count
|
|
91
|
+
// is read once, well after both tries of that request (5 s each) are over.
|
|
92
|
+
if (this.deniedConnectors) {
|
|
93
|
+
this.blockedTimer = setTimeout(() => this.checkBlocked(), this.opts.blockedCheckMs ?? BLOCKED_CHECK_MS);
|
|
94
|
+
this.blockedTimer.unref();
|
|
95
|
+
}
|
|
80
96
|
// Without this handshake the CLI never sends can_use_tool over stdio: it silently denies the tool
|
|
81
97
|
// and the model tends to invent a result. Verified against claude 2.1.272.
|
|
82
98
|
this.send({ type: 'control_request', request_id: 'init-1', request: { subtype: 'initialize', hooks: {} } });
|
|
83
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
|
+
}
|
|
124
|
+
/** Once per start, while the child runs: a start that named fewer connectors as blocked than it
|
|
125
|
+
* drops says so in the log and as `connectors-short`, with the names it blocked. */
|
|
126
|
+
checkBlocked() {
|
|
127
|
+
if (this.exited)
|
|
128
|
+
return;
|
|
129
|
+
const blocked = [...new Set(this.blocked)];
|
|
130
|
+
const short = blockedShort(this.deniedConnectors, blocked);
|
|
131
|
+
if (!short)
|
|
132
|
+
return;
|
|
133
|
+
this.emit('log', `warning: ${short}`);
|
|
134
|
+
this.emit('connectors-short', short, blocked);
|
|
135
|
+
}
|
|
84
136
|
/** Returns an error string when the init line proves the child unusable. */
|
|
85
137
|
checkInit(init) {
|
|
86
138
|
if (init.apiKeySource && init.apiKeySource !== 'none')
|
|
@@ -109,6 +161,8 @@ export class ClaudeBrain extends EventEmitter {
|
|
|
109
161
|
this.lines.on('exit', onExit);
|
|
110
162
|
this.send({ type: 'user', message: { role: 'user', content: text }, parent_tool_use_id: null });
|
|
111
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;
|
|
112
166
|
try {
|
|
113
167
|
if (this.notice) {
|
|
114
168
|
yield { kind: 'notice', text: this.notice };
|
|
@@ -136,7 +190,15 @@ export class ClaudeBrain extends EventEmitter {
|
|
|
136
190
|
}
|
|
137
191
|
continue;
|
|
138
192
|
}
|
|
139
|
-
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;
|
|
140
202
|
const blocks = l.message?.content ?? [];
|
|
141
203
|
for (const b of blocks) {
|
|
142
204
|
if (b.type === 'text' && String(b.text ?? '').trim()) {
|
|
@@ -160,7 +222,13 @@ export class ClaudeBrain extends EventEmitter {
|
|
|
160
222
|
}
|
|
161
223
|
else if (l.type === 'result') {
|
|
162
224
|
this.lastUsedAt = Date.now();
|
|
163
|
-
|
|
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 };
|
|
164
232
|
return;
|
|
165
233
|
}
|
|
166
234
|
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { CLAUDE_ENV } from './argv.js';
|
|
5
|
+
import { deniedConnectorCount, trackGroup } from './brain.js';
|
|
6
|
+
/**
|
|
7
|
+
* tmux mode's count of the connectors a `connectors: all` launch blocks. A pane has no stderr for
|
|
8
|
+
* Angelia to read, and its screen shows no "blocked by enterprise policy" line (measured on Claude Code
|
|
9
|
+
* 2.1.332: not at the start, not in /mcp). `claude --settings <deny> mcp list` costs no model call and
|
|
10
|
+
* leaves the denied connectors out of its list, but does not name them either. So the list is read
|
|
11
|
+
* twice, with the launch's MCP keys and with them less the connector denies, in the profile's folder
|
|
12
|
+
* and with a minimal environment: the connectors only the second names are the ones the launch
|
|
13
|
+
* blocks, the same names the print-mode warning gives (blockedConnectorNames).
|
|
14
|
+
*/
|
|
15
|
+
/** How long one `claude mcp list` may take: it health-checks every server (measured: about 12 s). */
|
|
16
|
+
export const MCP_LIST_TIMEOUT_MS = 90_000;
|
|
17
|
+
/**
|
|
18
|
+
* The claude.ai connectors in the output of `claude mcp list` (2.1.332): one line per server,
|
|
19
|
+
* "<name>: <url or command> - <status>", a connector's name starting with "claude.ai " and its address
|
|
20
|
+
* with http. The first ": http" ends the name, since a name can hold a colon but no ": http".
|
|
21
|
+
*/
|
|
22
|
+
export function listedConnectors(out) {
|
|
23
|
+
return [...new Set(out.split('\n').flatMap((l) => { const m = /^(claude\.ai .+?): https?:\/\/\S+ - /.exec(l.trim()); return m ? [m[1]] : []; }))];
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* What a `claude mcp list` run gets of the profile's environment: only what claude needs to find its
|
|
27
|
+
* config and its sign-in, and to reach the network. No granted secret, no ANGELIA_SESSION_KEY, no
|
|
28
|
+
* chat's ANGELIA_API_TOKEN: every stdio server the run does not deny starts with this environment.
|
|
29
|
+
*/
|
|
30
|
+
export const MCP_LIST_ENV = [
|
|
31
|
+
'HOME', 'PATH', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM',
|
|
32
|
+
'CLAUDE_CONFIG_DIR', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME',
|
|
33
|
+
'HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY', 'https_proxy', 'http_proxy', 'no_proxy', 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE',
|
|
34
|
+
];
|
|
35
|
+
export function mcpListEnv(base, extra = {}) {
|
|
36
|
+
const env = {};
|
|
37
|
+
for (const k of MCP_LIST_ENV)
|
|
38
|
+
if (base[k] !== undefined)
|
|
39
|
+
env[k] = base[k];
|
|
40
|
+
return { ...env, ...extra };
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The launch's MCP keys less its connector denies (serverUrl entries): the plain run's settings. It
|
|
44
|
+
* still keeps the denied servers by name and the folder's .mcp.json out, so no server the launch
|
|
45
|
+
* denies starts in the plain run either; only the connectors it drops come back. Undefined when
|
|
46
|
+
* nothing is left.
|
|
47
|
+
*/
|
|
48
|
+
export function plainSettings(settings) {
|
|
49
|
+
const out = { ...settings };
|
|
50
|
+
if (Array.isArray(settings.deniedMcpServers)) {
|
|
51
|
+
const names = settings.deniedMcpServers.filter((e) => !(e && typeof e === 'object' && 'serverUrl' in e));
|
|
52
|
+
if (names.length)
|
|
53
|
+
out.deniedMcpServers = names;
|
|
54
|
+
else
|
|
55
|
+
delete out.deniedMcpServers;
|
|
56
|
+
}
|
|
57
|
+
return Object.keys(out).length ? out : undefined;
|
|
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 }); }
|
|
67
|
+
/** The most of a list's output that is read. */
|
|
68
|
+
const MCP_LIST_MAX = 4 << 20;
|
|
69
|
+
/**
|
|
70
|
+
* One `claude mcp list`, with these settings when given: its connectors, or null when it failed. It
|
|
71
|
+
* runs in its own process group under a timer of ours: at the timeout the whole group is killed and
|
|
72
|
+
* the answer is given at once, so a claude that does not exit, or a server it started that holds its
|
|
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.
|
|
76
|
+
*/
|
|
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
|
+
}
|
|
95
|
+
return new Promise((done) => {
|
|
96
|
+
const child = spawn(bin, args, { cwd, env, detached: true, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
97
|
+
trackGroup(child); // the daemon's exit ends it too
|
|
98
|
+
let out = '', over = false;
|
|
99
|
+
const end = (result) => {
|
|
100
|
+
if (over)
|
|
101
|
+
return;
|
|
102
|
+
over = true;
|
|
103
|
+
clearTimeout(timer);
|
|
104
|
+
// Whatever is left of the run (a server it started) goes with it.
|
|
105
|
+
if (child.pid)
|
|
106
|
+
try {
|
|
107
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
108
|
+
}
|
|
109
|
+
catch { /* the group is gone */ }
|
|
110
|
+
child.stdout.destroy();
|
|
111
|
+
if (dir)
|
|
112
|
+
rmSync(dir, { recursive: true, force: true });
|
|
113
|
+
done(result);
|
|
114
|
+
};
|
|
115
|
+
const timer = setTimeout(() => end(null), timeoutMs);
|
|
116
|
+
child.stdout.setEncoding('utf8');
|
|
117
|
+
child.stdout.on('data', (d) => { out += d; if (out.length > MCP_LIST_MAX)
|
|
118
|
+
end(null); });
|
|
119
|
+
child.on('error', () => end(null));
|
|
120
|
+
child.on('close', (code) => end(code === 0 ? listedConnectors(out) : null));
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
/** The checks run one profile at a time (two `claude mcp list` runs at once, not two per profile). */
|
|
124
|
+
let queue = Promise.resolve();
|
|
125
|
+
/**
|
|
126
|
+
* The connectors the launch's MCP keys (`settings`) block: listed without its connector denies, not
|
|
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
|
|
129
|
+
* list failed; the plain list names no connector (the account has none, or its connector list did not
|
|
130
|
+
* load), so a short count would say nothing about the addresses; or the list with the denies names no
|
|
131
|
+
* connector while the plain one names more than the denies have addresses (its connector list did not
|
|
132
|
+
* load either, and every connector would count as blocked).
|
|
133
|
+
*/
|
|
134
|
+
export function tuiBlockedConnectors(bin, cwd, env, settings, stateDir, timeoutMs = MCP_LIST_TIMEOUT_MS) {
|
|
135
|
+
const run = async () => {
|
|
136
|
+
const e = mcpListEnv(env, CLAUDE_ENV);
|
|
137
|
+
const [all, kept] = await Promise.all([mcpListConnectors(bin, cwd, e, stateDir, plainSettings(settings), timeoutMs), mcpListConnectors(bin, cwd, e, stateDir, settings, timeoutMs)]);
|
|
138
|
+
if (!all || !kept || !all.length)
|
|
139
|
+
return null;
|
|
140
|
+
if (!kept.length && all.length > deniedConnectorCount(settings))
|
|
141
|
+
return null;
|
|
142
|
+
const left = new Set(kept);
|
|
143
|
+
return all.filter((n) => !left.has(n));
|
|
144
|
+
};
|
|
145
|
+
const next = queue.then(run, run);
|
|
146
|
+
queue = next.catch(() => undefined);
|
|
147
|
+
return next;
|
|
148
|
+
}
|
|
149
|
+
//# sourceMappingURL=connectors-check.js.map
|
package/dist/brain/tmux.js
CHANGED
|
@@ -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.
|