angelia-gateway 0.4.3 → 0.4.5
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/brain/brain.js +47 -3
- package/dist/brain/claude.js +36 -15
- package/dist/brain/connectors-check.js +118 -0
- package/dist/brain/tmux.js +6 -1
- package/dist/brain/tui-permissions.js +63 -6
- package/dist/brain/tui.js +711 -81
- package/dist/build.json +3 -3
- package/dist/capabilities/compile.js +354 -85
- package/dist/capabilities/resolve.js +25 -0
- package/dist/cli/cli.js +3 -1
- package/dist/core/deliver/text.js +11 -0
- package/dist/core/orchestrator.js +220 -28
- package/dist/core/screen-asks.js +27 -5
- package/dist/daemon/daemon.js +16 -7
- package/dist/instance/config/load.js +15 -0
- package/dist/instance/config/schema.js +13 -1
- package/dist/instance/guide.js +14 -3
- package/package.json +1 -1
- package/scripts/tui-permission-hook.mjs +29 -3
- package/scripts/tui-stop-hook.mjs +1 -1
- package/scripts/turn-origin.mjs +140 -30
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/claude.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
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 { mcpLaunch } from '../capabilities/compile.js';
|
|
6
7
|
export { BrainExited, exitReason } from './brain.js';
|
|
8
|
+
/** How long after the spawn the connectors Claude Code named as blocked are counted (checkBlocked). */
|
|
9
|
+
export const BLOCKED_CHECK_MS = 30_000;
|
|
7
10
|
/** One long-lived `claude -p --input-format stream-json` child for one session key. */
|
|
8
11
|
export class ClaudeBrain extends EventEmitter {
|
|
9
12
|
profile;
|
|
@@ -25,6 +28,11 @@ export class ClaudeBrain extends EventEmitter {
|
|
|
25
28
|
version = '';
|
|
26
29
|
/** Claude Code accepts the id Angelia mints, so the backend id is the session id. */
|
|
27
30
|
backendSessionId;
|
|
31
|
+
/** connectors: all: how many connectors this launch drops by address, and the ones Claude Code's
|
|
32
|
+
* stderr named as blocked (blockedShort, checked once, BLOCKED_CHECK_MS after the spawn). */
|
|
33
|
+
deniedConnectors = 0;
|
|
34
|
+
blocked = [];
|
|
35
|
+
blockedTimer;
|
|
28
36
|
constructor(profile, session, opts = {}) {
|
|
29
37
|
super();
|
|
30
38
|
this.profile = profile;
|
|
@@ -53,34 +61,47 @@ export class ClaudeBrain extends EventEmitter {
|
|
|
53
61
|
}
|
|
54
62
|
}
|
|
55
63
|
const [bin, ...args] = claudeArgv(this.profile, session, this.opts.bin ?? 'claude', this.opts.system, this.opts.mcp);
|
|
64
|
+
this.deniedConnectors = deniedConnectorCount((this.opts.mcp ?? mcpLaunch(this.profile.cwd)).settings);
|
|
56
65
|
const child = spawn(bin, args, { cwd: this.profile.cwd, env: { ...childEnv(this.opts.env), ...CLAUDE_ENV }, stdio: ['pipe', 'pipe', 'pipe'], ...CHILD_GROUP });
|
|
57
66
|
this.child = child;
|
|
58
|
-
trackGroup(child);
|
|
59
67
|
const done = (code, signal) => {
|
|
60
68
|
if (this.exited)
|
|
61
69
|
return;
|
|
62
70
|
this.exited = true;
|
|
71
|
+
clearTimeout(this.blockedTimer); // a child gone before the check says nothing about its connectors
|
|
63
72
|
this.permissions.clear();
|
|
64
73
|
this.lines.emit('exit', { code, signal });
|
|
65
74
|
this.emit('exit', { code, signal });
|
|
66
75
|
};
|
|
67
|
-
child
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
//
|
|
74
|
-
|
|
75
|
-
//
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
76
|
+
wireChild(child, {
|
|
77
|
+
exit: done,
|
|
78
|
+
failure: (t) => { this.failure = t; },
|
|
79
|
+
line: (obj) => { this.lastOutputAt = Date.now(); this.lines.emit('line', obj); },
|
|
80
|
+
benign: (line) => { this.blocked.push(...blockedConnectorNames(line)); },
|
|
81
|
+
});
|
|
82
|
+
// Claude Code does not wait for the account's connector list before the first turn (docs/reference.md,
|
|
83
|
+
// "The first turn of a new session"), so its warning may come after that turn's result: the count
|
|
84
|
+
// is read once, well after both tries of that request (5 s each) are over.
|
|
85
|
+
if (this.deniedConnectors) {
|
|
86
|
+
this.blockedTimer = setTimeout(() => this.checkBlocked(), this.opts.blockedCheckMs ?? BLOCKED_CHECK_MS);
|
|
87
|
+
this.blockedTimer.unref();
|
|
88
|
+
}
|
|
80
89
|
// Without this handshake the CLI never sends can_use_tool over stdio: it silently denies the tool
|
|
81
90
|
// and the model tends to invent a result. Verified against claude 2.1.272.
|
|
82
91
|
this.send({ type: 'control_request', request_id: 'init-1', request: { subtype: 'initialize', hooks: {} } });
|
|
83
92
|
}
|
|
93
|
+
/** Once per start, while the child runs: a start that named fewer connectors as blocked than it
|
|
94
|
+
* drops says so in the log and as `connectors-short`, with the names it blocked. */
|
|
95
|
+
checkBlocked() {
|
|
96
|
+
if (this.exited)
|
|
97
|
+
return;
|
|
98
|
+
const blocked = [...new Set(this.blocked)];
|
|
99
|
+
const short = blockedShort(this.deniedConnectors, blocked);
|
|
100
|
+
if (!short)
|
|
101
|
+
return;
|
|
102
|
+
this.emit('log', `warning: ${short}`);
|
|
103
|
+
this.emit('connectors-short', short, blocked);
|
|
104
|
+
}
|
|
84
105
|
/** Returns an error string when the init line proves the child unusable. */
|
|
85
106
|
checkInit(init) {
|
|
86
107
|
if (init.apiKeySource && init.apiKeySource !== 'none')
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { CLAUDE_ENV } from './argv.js';
|
|
3
|
+
import { deniedConnectorCount, trackGroup } from './brain.js';
|
|
4
|
+
/**
|
|
5
|
+
* tmux mode's count of the connectors a `connectors: all` launch blocks. A pane has no stderr for
|
|
6
|
+
* Angelia to read, and its screen shows no "blocked by enterprise policy" line (measured on Claude Code
|
|
7
|
+
* 2.1.332: not at the start, not in /mcp). `claude --settings <deny> mcp list` costs no model call and
|
|
8
|
+
* leaves the denied connectors out of its list, but does not name them either. So the list is read
|
|
9
|
+
* twice, with the launch's MCP keys and with them less the connector denies, in the profile's folder
|
|
10
|
+
* and with a minimal environment: the connectors only the second names are the ones the launch
|
|
11
|
+
* blocks, the same names the print-mode warning gives (blockedConnectorNames).
|
|
12
|
+
*/
|
|
13
|
+
/** How long one `claude mcp list` may take: it health-checks every server (measured: about 12 s). */
|
|
14
|
+
export const MCP_LIST_TIMEOUT_MS = 90_000;
|
|
15
|
+
/**
|
|
16
|
+
* The claude.ai connectors in the output of `claude mcp list` (2.1.332): one line per server,
|
|
17
|
+
* "<name>: <url or command> - <status>", a connector's name starting with "claude.ai " and its address
|
|
18
|
+
* with http. The first ": http" ends the name, since a name can hold a colon but no ": http".
|
|
19
|
+
*/
|
|
20
|
+
export function listedConnectors(out) {
|
|
21
|
+
return [...new Set(out.split('\n').flatMap((l) => { const m = /^(claude\.ai .+?): https?:\/\/\S+ - /.exec(l.trim()); return m ? [m[1]] : []; }))];
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* What a `claude mcp list` run gets of the profile's environment: only what claude needs to find its
|
|
25
|
+
* config and its sign-in, and to reach the network. No granted secret, no ANGELIA_SESSION_KEY, no
|
|
26
|
+
* chat's ANGELIA_API_TOKEN: every stdio server the run does not deny starts with this environment.
|
|
27
|
+
*/
|
|
28
|
+
export const MCP_LIST_ENV = [
|
|
29
|
+
'HOME', 'PATH', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM',
|
|
30
|
+
'CLAUDE_CONFIG_DIR', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME',
|
|
31
|
+
'HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY', 'https_proxy', 'http_proxy', 'no_proxy', 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE',
|
|
32
|
+
];
|
|
33
|
+
export function mcpListEnv(base, extra = {}) {
|
|
34
|
+
const env = {};
|
|
35
|
+
for (const k of MCP_LIST_ENV)
|
|
36
|
+
if (base[k] !== undefined)
|
|
37
|
+
env[k] = base[k];
|
|
38
|
+
return { ...env, ...extra };
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The launch's MCP keys less its connector denies (serverUrl entries): the plain run's settings. It
|
|
42
|
+
* still keeps the denied servers by name and the folder's .mcp.json out, so no server the launch
|
|
43
|
+
* denies starts in the plain run either; only the connectors it drops come back. Undefined when
|
|
44
|
+
* nothing is left.
|
|
45
|
+
*/
|
|
46
|
+
export function plainSettings(settings) {
|
|
47
|
+
const out = { ...settings };
|
|
48
|
+
if (Array.isArray(settings.deniedMcpServers)) {
|
|
49
|
+
const names = settings.deniedMcpServers.filter((e) => !(e && typeof e === 'object' && 'serverUrl' in e));
|
|
50
|
+
if (names.length)
|
|
51
|
+
out.deniedMcpServers = names;
|
|
52
|
+
else
|
|
53
|
+
delete out.deniedMcpServers;
|
|
54
|
+
}
|
|
55
|
+
return Object.keys(out).length ? out : undefined;
|
|
56
|
+
}
|
|
57
|
+
/** The most of a list's output that is read. */
|
|
58
|
+
const MCP_LIST_MAX = 4 << 20;
|
|
59
|
+
/**
|
|
60
|
+
* One `claude mcp list`, with these settings when given: its connectors, or null when it failed. It
|
|
61
|
+
* runs in its own process group under a timer of ours: at the timeout the whole group is killed and
|
|
62
|
+
* 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.
|
|
64
|
+
*/
|
|
65
|
+
export function mcpListConnectors(bin, cwd, env, settings, timeoutMs = MCP_LIST_TIMEOUT_MS) {
|
|
66
|
+
const args = [...(settings ? ['--settings', JSON.stringify(settings)] : []), 'mcp', 'list'];
|
|
67
|
+
return new Promise((done) => {
|
|
68
|
+
const child = spawn(bin, args, { cwd, env, detached: true, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
69
|
+
trackGroup(child); // the daemon's exit ends it too
|
|
70
|
+
let out = '', over = false;
|
|
71
|
+
const end = (result) => {
|
|
72
|
+
if (over)
|
|
73
|
+
return;
|
|
74
|
+
over = true;
|
|
75
|
+
clearTimeout(timer);
|
|
76
|
+
// Whatever is left of the run (a server it started) goes with it.
|
|
77
|
+
if (child.pid)
|
|
78
|
+
try {
|
|
79
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
80
|
+
}
|
|
81
|
+
catch { /* the group is gone */ }
|
|
82
|
+
child.stdout.destroy();
|
|
83
|
+
done(result);
|
|
84
|
+
};
|
|
85
|
+
const timer = setTimeout(() => end(null), timeoutMs);
|
|
86
|
+
child.stdout.setEncoding('utf8');
|
|
87
|
+
child.stdout.on('data', (d) => { out += d; if (out.length > MCP_LIST_MAX)
|
|
88
|
+
end(null); });
|
|
89
|
+
child.on('error', () => end(null));
|
|
90
|
+
child.on('close', (code) => end(code === 0 ? listedConnectors(out) : null));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
/** The checks run one profile at a time (two `claude mcp list` runs at once, not two per profile). */
|
|
94
|
+
let queue = Promise.resolve();
|
|
95
|
+
/**
|
|
96
|
+
* 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
|
|
98
|
+
* list failed; the plain list names no connector (the account has none, or its connector list did not
|
|
99
|
+
* load), so a short count would say nothing about the addresses; or the list with the denies names no
|
|
100
|
+
* connector while the plain one names more than the denies have addresses (its connector list did not
|
|
101
|
+
* load either, and every connector would count as blocked).
|
|
102
|
+
*/
|
|
103
|
+
export function tuiBlockedConnectors(bin, cwd, env, settings, timeoutMs = MCP_LIST_TIMEOUT_MS) {
|
|
104
|
+
const run = async () => {
|
|
105
|
+
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)]);
|
|
107
|
+
if (!all || !kept || !all.length)
|
|
108
|
+
return null;
|
|
109
|
+
if (!kept.length && all.length > deniedConnectorCount(settings))
|
|
110
|
+
return null;
|
|
111
|
+
const left = new Set(kept);
|
|
112
|
+
return all.filter((n) => !left.has(n));
|
|
113
|
+
};
|
|
114
|
+
const next = queue.then(run, run);
|
|
115
|
+
queue = next.catch(() => undefined);
|
|
116
|
+
return next;
|
|
117
|
+
}
|
|
118
|
+
//# sourceMappingURL=connectors-check.js.map
|
package/dist/brain/tmux.js
CHANGED
|
@@ -198,7 +198,12 @@ export function permissionDialog(pane) {
|
|
|
198
198
|
const body = raw.slice(top >= 0 ? top + 1 : Math.max(0, at - 6), at).map(clean).filter((l) => l && !/^[\s╌─━┄┈]+$/.test(l));
|
|
199
199
|
if (!body.length)
|
|
200
200
|
return { tool: 'tool', preview: 'a permission prompt is open' };
|
|
201
|
-
|
|
201
|
+
// A teammate's request names it after the title: "Bash command · from the restart-relay agent"
|
|
202
|
+
// (claude 2.1.332, seen in a chat's pane 2026-11-25).
|
|
203
|
+
// Only that shape: a title with a "·" of its own says nothing of who asks.
|
|
204
|
+
const asker = /^(.+?)\s*·\s*from\s+((?:the\s+)?[A-Za-z0-9_.-]{1,64}\s+agent)$/.exec(body[0]);
|
|
205
|
+
const tool = (asker ? asker[1] : body[0]).slice(0, 40);
|
|
206
|
+
return { tool, preview: (body.slice(1).join(' · ') || body[0]).slice(0, 300), ...(asker ? { from: asker[2].slice(0, 60) } : {}) };
|
|
202
207
|
}
|
|
203
208
|
/** A directory Claude Code has not been run in before opens a trust dialog before the first
|
|
204
209
|
* prompt, with "No, exit" preselected. Print mode never shows it. */
|
|
@@ -9,8 +9,12 @@ import { permissionPreview } from './brain.js';
|
|
|
9
9
|
* A dialog on the screen is text a command can shape (a line of `─` in a command reads as the dialog's
|
|
10
10
|
* top edge), and a key press answers whichever dialog is open by then; neither is used to approve.
|
|
11
11
|
*
|
|
12
|
-
* The hook relays
|
|
13
|
-
*
|
|
12
|
+
* The hook relays while a turn from the chat is being read, which `beat` says on every poll, and
|
|
13
|
+
* between the chat's turns while the daemon holds the pane (`beat` with `idle`): then the hook adds
|
|
14
|
+
* what started the turn that asks (turnOrigin, as the Stop hook reads it), and the daemon either
|
|
15
|
+
* takes the request (a turn the agent started by itself: the profile's `permissions` decide) or tells
|
|
16
|
+
* the hook to step aside (`pass`: a turn a person typed in the Claude app or the pane). With no
|
|
17
|
+
* heartbeat at all it steps aside at once, and Claude opens its own dialog in the pane and the app.
|
|
14
18
|
*/
|
|
15
19
|
/** A heartbeat older than this means nobody reads the chat. The hook has the same number. Only a
|
|
16
20
|
* daemon that died or stopped for a restart leaves one to go stale (every other end of a turn removes
|
|
@@ -40,8 +44,9 @@ export class PermissionRelay {
|
|
|
40
44
|
this.open.clear();
|
|
41
45
|
this.seen.clear();
|
|
42
46
|
}
|
|
43
|
-
/** While a turn is read from the chat, every RELAY_BEAT_MS.
|
|
44
|
-
|
|
47
|
+
/** While a turn is read from the chat, every RELAY_BEAT_MS. `idle`: between the chat's turns, while
|
|
48
|
+
* the daemon holds the pane: the hook then says what started the turn that asks. */
|
|
49
|
+
beat(now = Date.now(), idle = false) { this.put('relay.json', idle ? { at: now, idle: true } : { at: now }); }
|
|
45
50
|
/** Nobody reads the chat now: a hook waiting, or asking next, lets Claude open its own dialog. */
|
|
46
51
|
quiet() { rmSync(join(this.dir, 'relay.json'), { force: true }); }
|
|
47
52
|
/** Requests the hook wrote since the last call, oldest first. */
|
|
@@ -71,9 +76,10 @@ export class PermissionRelay {
|
|
|
71
76
|
}
|
|
72
77
|
this.seen.add(id);
|
|
73
78
|
this.open.add(id);
|
|
74
|
-
|
|
79
|
+
const origin = originOf(row.origin);
|
|
80
|
+
out.push({ id, tool: typeof row.tool_name === 'string' && row.tool_name ? row.tool_name : '?', input: row.tool_input, at: Number(row.at) || 0, ...(origin ? { origin } : {}) });
|
|
75
81
|
}
|
|
76
|
-
return out.sort((a, b) => a.at - b.at).map(({
|
|
82
|
+
return out.sort((a, b) => a.at - b.at).map(({ at, ...r }) => ({ ...r, ...(at ? { at } : {}) }));
|
|
77
83
|
}
|
|
78
84
|
/** A hook waits on a request now, taken or not: Claude Code draws its own dialog while the hook
|
|
79
85
|
* runs (measured on claude 2.1.332), so Enter must not be pressed for a message into the turn. */
|
|
@@ -107,6 +113,17 @@ export class PermissionRelay {
|
|
|
107
113
|
rmSync(join(this.dir, `${id}.answer.json`), { force: true });
|
|
108
114
|
return false;
|
|
109
115
|
}
|
|
116
|
+
/** Not the chat's to answer (a turn a person typed, between the chat's turns): the hook steps aside
|
|
117
|
+
* and Claude asks in its own dialog, as with no daemon. False when no hook waits for it any more. */
|
|
118
|
+
pass(id) {
|
|
119
|
+
if (!this.open.delete(id))
|
|
120
|
+
return false;
|
|
121
|
+
const request = join(this.dir, `${id}.request.json`);
|
|
122
|
+
if (!existsSync(request))
|
|
123
|
+
return false;
|
|
124
|
+
this.put(`${id}.answer.json`, { pass: true });
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
110
127
|
put(name, value) {
|
|
111
128
|
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
112
129
|
const tmp = join(this.dir, `${name}.tmp`);
|
|
@@ -114,6 +131,46 @@ export class PermissionRelay {
|
|
|
114
131
|
renameSync(tmp, join(this.dir, name));
|
|
115
132
|
}
|
|
116
133
|
}
|
|
134
|
+
/** The hook's `origin` field, kept only in its own shape: plain words, keys, a time, a count. */
|
|
135
|
+
function originOf(v) {
|
|
136
|
+
if (!v || typeof v !== 'object')
|
|
137
|
+
return undefined;
|
|
138
|
+
const o = v;
|
|
139
|
+
const keys = Array.isArray(o.prompt_keys) && o.prompt_keys.length <= 20 && o.prompt_keys.every((k) => typeof k === 'string' && /^[0-9a-f]{1,128}$/.test(k)) ? o.prompt_keys : undefined;
|
|
140
|
+
if (typeof o.origin !== 'string' || !/^[a-z]{1,20}$/.test(o.origin))
|
|
141
|
+
return undefined;
|
|
142
|
+
return {
|
|
143
|
+
origin: o.origin,
|
|
144
|
+
...(typeof o.origin_why === 'string' ? { why: o.origin_why.replace(/[^\w <>(),-]/g, '').slice(0, 120) } : {}),
|
|
145
|
+
...(typeof o.prompt_key === 'string' && o.prompt_key.length <= 128 ? { promptKey: o.prompt_key } : {}),
|
|
146
|
+
...(typeof o.prompts === 'number' && Number.isInteger(o.prompts) ? { prompts: o.prompts } : {}),
|
|
147
|
+
...(keys ? { promptKeys: keys } : {}),
|
|
148
|
+
...(typeof o.prompt_at === 'number' && Number.isFinite(o.prompt_at) ? { promptAt: o.prompt_at } : {}),
|
|
149
|
+
...(typeof o.opened_by === 'string' && /^[a-z]{1,20}$/.test(o.opened_by) ? { openedBy: o.opened_by } : {}),
|
|
150
|
+
...(words(o.origin_ids) ? { ids: words(o.origin_ids) } : {}),
|
|
151
|
+
...(words(o.origin_teammates) ? { teammates: words(o.origin_teammates) } : {}),
|
|
152
|
+
...(typeof o.joins === 'number' && Number.isInteger(o.joins) && o.joins >= 0 ? { joins: o.joins } : {}),
|
|
153
|
+
...(Array.isArray(o.joined) && o.joined.length <= 20 ? { joined: o.joined.map(joinedOf) } : {}),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/** One entry of the hook's `joined`, in its own shape; anything else reads `other` (ties nothing). */
|
|
157
|
+
function joinedOf(v) {
|
|
158
|
+
const j = v && typeof v === 'object' ? v : {};
|
|
159
|
+
const ids = words(j.ids), mates = words(j.teammates);
|
|
160
|
+
if (typeof j.kind !== 'string' || !/^[a-z]{1,20}$/.test(j.kind))
|
|
161
|
+
return { kind: 'other' };
|
|
162
|
+
// A list that is there but not in its shape: the row is not known for anyone's work.
|
|
163
|
+
if ((j.ids !== undefined && !ids) || (j.teammates !== undefined && !mates))
|
|
164
|
+
return { kind: 'other' };
|
|
165
|
+
return { kind: j.kind, ...(ids ? { ids } : {}), ...(mates ? { teammates: mates } : {}) };
|
|
166
|
+
}
|
|
167
|
+
/** A list of ids or names as the hook writes them (turn-origin.mjs: TOOL_USE_ID, TEAMMATE_ID): plain
|
|
168
|
+
* words, at most 20. Anything else is no list, and ties the request to nothing. */
|
|
169
|
+
function words(v) {
|
|
170
|
+
if (!Array.isArray(v) || !v.length || v.length > 20)
|
|
171
|
+
return undefined;
|
|
172
|
+
return v.every((x) => typeof x === 'string' && /^[A-Za-z0-9_.-]{1,100}(@[^"\s]{0,128})?$/.test(x)) ? v : undefined;
|
|
173
|
+
}
|
|
117
174
|
/** What Claude Code writes as the result of a tool use a person refused in its dialog (No or Esc).
|
|
118
175
|
* Seen on 2.1.287: `toolUseResult` is this string, and the tool_result has `is_error: true`. */
|
|
119
176
|
export const REJECTED = 'User rejected tool use';
|