@aerostack/gateway 0.11.4 → 0.11.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/hook-server.js +334 -0
- package/dist/index.js +6 -6
- package/package.json +1 -1
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local Hook Server — receives Claude Code PreToolUse hooks on localhost,
|
|
3
|
+
* batches events, and flushes to Aerostack gateway periodically.
|
|
4
|
+
*
|
|
5
|
+
* Architecture:
|
|
6
|
+
* Claude Code → PreToolUse hook → POST http://localhost:{port}/hook
|
|
7
|
+
* → batched in memory (30s window)
|
|
8
|
+
* → flush: single POST to gateway with guardian_report for each event
|
|
9
|
+
*
|
|
10
|
+
* Also manages ~/.claude/settings.json hook entries when enabled/disabled.
|
|
11
|
+
*/
|
|
12
|
+
import { createServer } from 'node:http';
|
|
13
|
+
import { readFile, writeFile, appendFile, stat } from 'node:fs/promises';
|
|
14
|
+
import { watch } from 'node:fs';
|
|
15
|
+
import { homedir } from 'node:os';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { info, warn, debug } from './logger.js';
|
|
18
|
+
// ─── Config ───────────────────────────────────────────────────────────────
|
|
19
|
+
const DEFAULT_PORT = 18321;
|
|
20
|
+
const BATCH_INTERVAL_MS = 30_000; // 30 seconds
|
|
21
|
+
const MAX_BATCH_SIZE = 200;
|
|
22
|
+
// Tools that are mutations (worth tracking)
|
|
23
|
+
const MUTATION_TOOLS = new Set([
|
|
24
|
+
'Bash', 'Write', 'Edit', 'NotebookEdit',
|
|
25
|
+
// MCP tools caught by bridge auto-report, but hook might see them too
|
|
26
|
+
]);
|
|
27
|
+
// Tools that are read-only (skip by default)
|
|
28
|
+
const READONLY_TOOLS = new Set([
|
|
29
|
+
'Read', 'Glob', 'Grep', 'LS', 'WebSearch', 'WebFetch',
|
|
30
|
+
'Agent', 'AskUserQuestion', 'TodoRead', 'TaskList', 'TaskGet',
|
|
31
|
+
]);
|
|
32
|
+
// ─── Category detection ───────────────────────────────────────────────────
|
|
33
|
+
function detectCategory(toolName, toolInput) {
|
|
34
|
+
if (toolName === 'Bash') {
|
|
35
|
+
const cmd = toolInput.command || '';
|
|
36
|
+
const lower = cmd.toLowerCase();
|
|
37
|
+
if (lower.includes('rm ') || lower.includes('rm\t') || lower.includes('rmdir') || lower.includes('unlink'))
|
|
38
|
+
return { category: 'file_delete', risk: 'high' };
|
|
39
|
+
if (lower.includes('git push') || lower.includes('git reset'))
|
|
40
|
+
return { category: 'deploy', risk: 'high' };
|
|
41
|
+
if (lower.includes('npm install') || lower.includes('pip install') || lower.includes('yarn add'))
|
|
42
|
+
return { category: 'package_install', risk: 'medium' };
|
|
43
|
+
if (lower.includes('curl ') || lower.includes('wget ') || lower.includes('fetch'))
|
|
44
|
+
return { category: 'api_call', risk: 'low' };
|
|
45
|
+
if (lower.includes('deploy') || lower.includes('wrangler'))
|
|
46
|
+
return { category: 'deploy', risk: 'high' };
|
|
47
|
+
return { category: 'exec_command', risk: 'low' };
|
|
48
|
+
}
|
|
49
|
+
if (toolName === 'Write')
|
|
50
|
+
return { category: 'file_write', risk: 'medium' };
|
|
51
|
+
if (toolName === 'Edit' || toolName === 'NotebookEdit')
|
|
52
|
+
return { category: 'file_write', risk: 'low' };
|
|
53
|
+
return { category: 'other', risk: 'low' };
|
|
54
|
+
}
|
|
55
|
+
function summarizeToolInput(toolName, toolInput) {
|
|
56
|
+
if (toolName === 'Bash')
|
|
57
|
+
return toolInput.command?.slice(0, 200) || '';
|
|
58
|
+
if (toolName === 'Write')
|
|
59
|
+
return toolInput.file_path || '';
|
|
60
|
+
if (toolName === 'Edit')
|
|
61
|
+
return toolInput.file_path || '';
|
|
62
|
+
// Generic
|
|
63
|
+
const keys = Object.keys(toolInput);
|
|
64
|
+
if (keys.length === 0)
|
|
65
|
+
return '';
|
|
66
|
+
const first = toolInput[keys[0]];
|
|
67
|
+
return typeof first === 'string' ? first.slice(0, 200) : JSON.stringify(toolInput).slice(0, 200);
|
|
68
|
+
}
|
|
69
|
+
// ─── Batch buffer ─────────────────────────────────────────────────────────
|
|
70
|
+
let eventBatch = [];
|
|
71
|
+
let flushTimer = null;
|
|
72
|
+
let batchFlushFn = null;
|
|
73
|
+
// Bridge config — updated from gateway response on each batch flush
|
|
74
|
+
let bridgeConfig = {
|
|
75
|
+
enabled: true,
|
|
76
|
+
tools: ['Bash', 'Write', 'Edit'],
|
|
77
|
+
batch_interval_seconds: 30,
|
|
78
|
+
categories: ['exec_command', 'file_write', 'file_delete', 'deploy', 'config_change'],
|
|
79
|
+
};
|
|
80
|
+
let currentBatchInterval = BATCH_INTERVAL_MS;
|
|
81
|
+
export function getBridgeConfig() { return bridgeConfig; }
|
|
82
|
+
function addToBatch(event) {
|
|
83
|
+
if (!bridgeConfig.enabled)
|
|
84
|
+
return; // tracking disabled from dashboard
|
|
85
|
+
if (eventBatch.length >= MAX_BATCH_SIZE) {
|
|
86
|
+
eventBatch.shift();
|
|
87
|
+
}
|
|
88
|
+
eventBatch.push(event);
|
|
89
|
+
}
|
|
90
|
+
async function flushBatch() {
|
|
91
|
+
if (eventBatch.length === 0 || !batchFlushFn)
|
|
92
|
+
return;
|
|
93
|
+
const batch = eventBatch.splice(0);
|
|
94
|
+
debug(`Flushing ${batch.length} hook events`);
|
|
95
|
+
const newConfig = await batchFlushFn(batch);
|
|
96
|
+
// Update bridge config from gateway response (live config sync)
|
|
97
|
+
if (newConfig) {
|
|
98
|
+
const changed = JSON.stringify(bridgeConfig) !== JSON.stringify(newConfig);
|
|
99
|
+
bridgeConfig = newConfig;
|
|
100
|
+
if (changed) {
|
|
101
|
+
info('Bridge config updated from gateway', { enabled: newConfig.enabled, tools: newConfig.tools });
|
|
102
|
+
// Update batch interval if changed
|
|
103
|
+
if (newConfig.batch_interval_seconds * 1000 !== currentBatchInterval) {
|
|
104
|
+
currentBatchInterval = newConfig.batch_interval_seconds * 1000;
|
|
105
|
+
if (flushTimer) {
|
|
106
|
+
clearInterval(flushTimer);
|
|
107
|
+
flushTimer = setInterval(() => { flushBatch().catch(() => { }); }, currentBatchInterval);
|
|
108
|
+
info('Batch interval updated', { seconds: newConfig.batch_interval_seconds });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
info(`Flushed ${batch.length} hook events to gateway`);
|
|
114
|
+
}
|
|
115
|
+
// ─── HTTP Server ──────────────────────────────────────────────────────────
|
|
116
|
+
let httpServer = null;
|
|
117
|
+
let serverPort = null;
|
|
118
|
+
function handleHookRequest(req, res) {
|
|
119
|
+
if (req.method !== 'POST' || !req.url?.startsWith('/hook')) {
|
|
120
|
+
res.writeHead(404);
|
|
121
|
+
res.end();
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const chunks = [];
|
|
125
|
+
req.on('data', (chunk) => chunks.push(chunk));
|
|
126
|
+
req.on('end', () => {
|
|
127
|
+
try {
|
|
128
|
+
const body = JSON.parse(Buffer.concat(chunks).toString());
|
|
129
|
+
const toolName = body.tool_name ?? '';
|
|
130
|
+
// Skip tools not in the configured tracking list
|
|
131
|
+
if (!bridgeConfig.tools.includes(toolName) && !MUTATION_TOOLS.has(toolName)) {
|
|
132
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
133
|
+
res.end('{"status":"skipped"}');
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
// Skip read-only tools unless explicitly configured
|
|
137
|
+
if (READONLY_TOOLS.has(toolName) && !bridgeConfig.tools.includes(toolName)) {
|
|
138
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
139
|
+
res.end('{"status":"skipped"}');
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const toolInput = body.tool_input ?? {};
|
|
143
|
+
const { category, risk } = detectCategory(toolName, toolInput);
|
|
144
|
+
const summary = summarizeToolInput(toolName, toolInput);
|
|
145
|
+
addToBatch({
|
|
146
|
+
action: `${toolName}: ${summary}`.slice(0, 500),
|
|
147
|
+
category,
|
|
148
|
+
risk_level: risk,
|
|
149
|
+
details: JSON.stringify({ tool: toolName, ...toolInput }).slice(0, 500),
|
|
150
|
+
});
|
|
151
|
+
debug(`Hook received: ${toolName}`, { category, risk });
|
|
152
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
153
|
+
res.end('{"status":"queued"}');
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
res.writeHead(400);
|
|
157
|
+
res.end('{"error":"invalid JSON"}');
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
// ─── Public API ───────────────────────────────────────────────────────────
|
|
162
|
+
let fileWatcher = null;
|
|
163
|
+
let lastFileSize = 0;
|
|
164
|
+
/** Process new lines appended to the JSONL events file. */
|
|
165
|
+
async function processNewEvents() {
|
|
166
|
+
try {
|
|
167
|
+
const st = await stat(HOOK_EVENTS_FILE).catch(() => null);
|
|
168
|
+
if (!st || st.size <= lastFileSize)
|
|
169
|
+
return;
|
|
170
|
+
const content = await readFile(HOOK_EVENTS_FILE, 'utf-8');
|
|
171
|
+
const lines = content.split('\n').filter(Boolean);
|
|
172
|
+
// Only process lines we haven't seen (based on byte offset)
|
|
173
|
+
const newContent = content.slice(lastFileSize);
|
|
174
|
+
lastFileSize = st.size;
|
|
175
|
+
const newLines = newContent.split('\n').filter(Boolean);
|
|
176
|
+
for (const line of newLines) {
|
|
177
|
+
try {
|
|
178
|
+
const data = JSON.parse(line);
|
|
179
|
+
const toolName = data.tool_name ?? '';
|
|
180
|
+
// Skip read-only tools
|
|
181
|
+
if (READONLY_TOOLS.has(toolName))
|
|
182
|
+
continue;
|
|
183
|
+
if (!MUTATION_TOOLS.has(toolName) && !bridgeConfig.tools.includes(toolName))
|
|
184
|
+
continue;
|
|
185
|
+
const toolInput = data.tool_input ?? {};
|
|
186
|
+
const { category, risk } = detectCategory(toolName, toolInput);
|
|
187
|
+
const summary = summarizeToolInput(toolName, toolInput);
|
|
188
|
+
addToBatch({
|
|
189
|
+
action: `${toolName}: ${summary}`.slice(0, 500),
|
|
190
|
+
category,
|
|
191
|
+
risk_level: risk,
|
|
192
|
+
details: JSON.stringify({ tool: toolName, ...toolInput }).slice(0, 500),
|
|
193
|
+
});
|
|
194
|
+
debug(`File hook event: ${toolName}`, { category });
|
|
195
|
+
}
|
|
196
|
+
catch { /* skip malformed lines */ }
|
|
197
|
+
}
|
|
198
|
+
// Truncate file if it gets too large (>1MB)
|
|
199
|
+
if (st.size > 1_048_576) {
|
|
200
|
+
await writeFile(HOOK_EVENTS_FILE, '', 'utf-8');
|
|
201
|
+
lastFileSize = 0;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
catch { /* file may not exist yet */ }
|
|
205
|
+
}
|
|
206
|
+
export async function startHookServer(flushFn, port = DEFAULT_PORT) {
|
|
207
|
+
batchFlushFn = flushFn;
|
|
208
|
+
// Start HTTP server (still useful for non-Claude clients)
|
|
209
|
+
const actualPort = await new Promise((resolve, reject) => {
|
|
210
|
+
httpServer = createServer(handleHookRequest);
|
|
211
|
+
httpServer.on('error', (err) => {
|
|
212
|
+
if (err.code === 'EADDRINUSE') {
|
|
213
|
+
info(`Port ${port} in use, trying ${port + 1}`);
|
|
214
|
+
httpServer.close();
|
|
215
|
+
startHookServer(flushFn, port + 1).then(resolve).catch(reject);
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
// Non-fatal — file-based hooks still work without HTTP server
|
|
219
|
+
warn('HTTP hook server failed, using file-based hooks only', { error: err.message });
|
|
220
|
+
resolve(0);
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
httpServer.listen(port, '127.0.0.1', () => {
|
|
224
|
+
serverPort = port;
|
|
225
|
+
info(`Hook server listening on http://127.0.0.1:${port}/hook`);
|
|
226
|
+
resolve(port);
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
// Start file watcher for JSONL events (primary hook mechanism — no port conflicts)
|
|
230
|
+
try {
|
|
231
|
+
// Touch file so watcher has something to watch
|
|
232
|
+
await appendFile(HOOK_EVENTS_FILE, '');
|
|
233
|
+
fileWatcher = watch(HOOK_EVENTS_FILE, () => {
|
|
234
|
+
processNewEvents().catch(() => { });
|
|
235
|
+
});
|
|
236
|
+
info('File watcher started', { path: HOOK_EVENTS_FILE });
|
|
237
|
+
}
|
|
238
|
+
catch (err) {
|
|
239
|
+
warn('File watcher failed', { error: err instanceof Error ? err.message : String(err) });
|
|
240
|
+
}
|
|
241
|
+
// Start batch flush timer — also polls JSONL file as safety net for fs.watch misses
|
|
242
|
+
flushTimer = setInterval(() => {
|
|
243
|
+
processNewEvents().catch(() => { });
|
|
244
|
+
flushBatch().catch(err => {
|
|
245
|
+
warn('Batch flush failed', { error: err instanceof Error ? err.message : String(err) });
|
|
246
|
+
});
|
|
247
|
+
}, BATCH_INTERVAL_MS);
|
|
248
|
+
return actualPort;
|
|
249
|
+
}
|
|
250
|
+
export function stopHookServer() {
|
|
251
|
+
if (flushTimer) {
|
|
252
|
+
clearInterval(flushTimer);
|
|
253
|
+
flushTimer = null;
|
|
254
|
+
}
|
|
255
|
+
// Final flush
|
|
256
|
+
flushBatch().catch(() => { });
|
|
257
|
+
if (fileWatcher) {
|
|
258
|
+
fileWatcher.close();
|
|
259
|
+
fileWatcher = null;
|
|
260
|
+
}
|
|
261
|
+
if (httpServer) {
|
|
262
|
+
httpServer.close();
|
|
263
|
+
httpServer = null;
|
|
264
|
+
}
|
|
265
|
+
serverPort = null;
|
|
266
|
+
}
|
|
267
|
+
// ─── Claude Code hook management ──────────────────────────────────────────
|
|
268
|
+
const HOOK_MARKER = '/* aerostack-guardian-hook */';
|
|
269
|
+
/** Path where hook events are written as JSONL (one JSON object per line).
|
|
270
|
+
* Use /tmp/ explicitly — macOS tmpdir() returns /var/folders/... which differs between processes. */
|
|
271
|
+
export const HOOK_EVENTS_FILE = '/tmp/aerostack-guardian-events.jsonl';
|
|
272
|
+
export async function installClaudeHook(_port) {
|
|
273
|
+
const settingsPath = join(homedir(), '.claude', 'settings.json');
|
|
274
|
+
try {
|
|
275
|
+
let settings = {};
|
|
276
|
+
try {
|
|
277
|
+
const raw = await readFile(settingsPath, 'utf-8');
|
|
278
|
+
settings = JSON.parse(raw);
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
// File doesn't exist or invalid — create fresh
|
|
282
|
+
}
|
|
283
|
+
const hooks = (settings.hooks ?? {});
|
|
284
|
+
const preToolUse = (hooks.PreToolUse ?? []);
|
|
285
|
+
// Remove any old HTTP-based aerostack hooks
|
|
286
|
+
const cleaned = preToolUse.filter(h => {
|
|
287
|
+
const innerHooks = (h.hooks ?? []);
|
|
288
|
+
return !innerHooks.some(ih => (ih.url?.includes('127.0.0.1') && ih.url?.includes('/hook')) ||
|
|
289
|
+
(ih.command?.includes('aerostack-guardian')));
|
|
290
|
+
});
|
|
291
|
+
// Command hook: reads stdin JSON, appends to JSONL file
|
|
292
|
+
// No HTTP, no port, no conflicts between sessions
|
|
293
|
+
const hookEntry = {
|
|
294
|
+
matcher: 'Bash|Write|Edit',
|
|
295
|
+
hooks: [{
|
|
296
|
+
type: 'command',
|
|
297
|
+
command: `cat >> ${HOOK_EVENTS_FILE}`,
|
|
298
|
+
}],
|
|
299
|
+
};
|
|
300
|
+
cleaned.push(hookEntry);
|
|
301
|
+
hooks.PreToolUse = cleaned;
|
|
302
|
+
settings.hooks = hooks;
|
|
303
|
+
await writeFile(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8');
|
|
304
|
+
info('Installed Claude Code hook (file-based)', { eventsFile: HOOK_EVENTS_FILE, path: settingsPath });
|
|
305
|
+
return true;
|
|
306
|
+
}
|
|
307
|
+
catch (err) {
|
|
308
|
+
warn('Failed to install Claude Code hook', { error: err instanceof Error ? err.message : String(err) });
|
|
309
|
+
return false;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
export async function uninstallClaudeHook() {
|
|
313
|
+
const settingsPath = join(homedir(), '.claude', 'settings.json');
|
|
314
|
+
try {
|
|
315
|
+
const raw = await readFile(settingsPath, 'utf-8');
|
|
316
|
+
const settings = JSON.parse(raw);
|
|
317
|
+
const hooks = (settings.hooks ?? {});
|
|
318
|
+
const preToolUse = (hooks.PreToolUse ?? []);
|
|
319
|
+
const filtered = preToolUse.filter(h => {
|
|
320
|
+
const innerHooks = (h.hooks ?? []);
|
|
321
|
+
return !innerHooks.some(ih => ih.url?.includes('127.0.0.1') && ih.url?.includes('/hook'));
|
|
322
|
+
});
|
|
323
|
+
if (filtered.length === preToolUse.length)
|
|
324
|
+
return false; // nothing to remove
|
|
325
|
+
hooks.PreToolUse = filtered;
|
|
326
|
+
settings.hooks = hooks;
|
|
327
|
+
await writeFile(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8');
|
|
328
|
+
info('Uninstalled Claude Code hook');
|
|
329
|
+
return true;
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
import{Server as
|
|
4
|
-
`),process.exit(1)),
|
|
5
|
-
`),process.exit(1));let
|
|
6
|
-
`),process.exit(1)}
|
|
7
|
-
`);const w
|
|
8
|
-
`);let
|
|
3
|
+
import{Server as T}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as A}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as v,CallToolRequestSchema as y,ListResourcesRequestSchema as P,ReadResourceRequestSchema as k,ListPromptsRequestSchema as C,GetPromptRequestSchema as K}from"@modelcontextprotocol/sdk/types.js";import{resolveApproval as R}from"./resolution.js";import{startHookServer as L,installClaudeHook as b,stopHookServer as h}from"./hook-server.js";import{info as p,warn as I,error as U}from"./logger.js";const w=process.env.AEROSTACK_WORKSPACE_URL,g=process.env.AEROSTACK_TOKEN;function _(t,s,r){const e=parseInt(t??String(s),10);return Number.isFinite(e)&&e>=r?e:s}const E=_(process.env.AEROSTACK_APPROVAL_POLL_MS,3e3,500),O=_(process.env.AEROSTACK_APPROVAL_TIMEOUT_MS,864e5,5e3),q=_(process.env.AEROSTACK_REQUEST_TIMEOUT_MS,3e4,1e3),j=process.env.AEROSTACK_HOOK_SERVER!=="false",x=_(process.env.AEROSTACK_HOOK_PORT,18321,1024),H=process.env.AEROSTACK_HOOK_AUTO_INSTALL!=="false";w||(process.stderr.write(`ERROR: AEROSTACK_WORKSPACE_URL is required
|
|
4
|
+
`),process.exit(1)),g||(process.stderr.write(`ERROR: AEROSTACK_TOKEN is required
|
|
5
|
+
`),process.exit(1));let f;try{if(f=new URL(w),f.protocol!=="https:"&&f.protocol!=="http:")throw new Error("must be http or https")}catch{process.stderr.write(`ERROR: AEROSTACK_WORKSPACE_URL must be a valid HTTP(S) URL
|
|
6
|
+
`),process.exit(1)}f.protocol==="http:"&&!f.hostname.match(/^(localhost|127\.0\.0\.1)$/)&&process.stderr.write(`WARNING: Using HTTP (not HTTPS) \u2014 token will be sent in plaintext
|
|
7
|
+
`);const d=w.replace(/\/+$/,"");async function c(t,s){const r={jsonrpc:"2.0",id:Date.now(),method:t,params:s??{}},e=new AbortController,n=setTimeout(()=>e.abort(),q);try{const o=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g}`,"User-Agent":"aerostack-gateway/0.12.0","X-Agent-Id":"aerostack-gateway"},body:JSON.stringify(r),signal:e.signal});if(clearTimeout(n),(o.headers.get("content-type")??"").includes("text/event-stream")){const i=await o.text();return N(i,r.id)}return await o.json()}catch(o){clearTimeout(n);const a=o instanceof Error?o.message:"Unknown error";return o instanceof Error&&o.name==="AbortError"?{jsonrpc:"2.0",id:r.id,error:{code:-32603,message:"Request timed out"}}:{jsonrpc:"2.0",id:r.id,error:{code:-32603,message:`HTTP error: ${a}`}}}}function N(t,s){const r=t.split(`
|
|
8
|
+
`);let e=null;for(const n of r)if(n.startsWith("data: "))try{e=JSON.parse(n.slice(6))}catch{}return e??{jsonrpc:"2.0",id:s,error:{code:-32603,message:"Empty SSE response"}}}const $=new Set(["aerostack__guardian_report","aerostack__check_approval","aerostack__guardian_check"]);function M(t,s){if($.has(t))return;let r="other";const e=t.toLowerCase();e.includes("exec")||e.includes("bash")||e.includes("shell")||e.includes("command")||e.includes("run")?r="exec_command":e.includes("write")||e.includes("edit")||e.includes("create")||e.includes("patch")?r="file_write":e.includes("delete")||e.includes("remove")||e.includes("trash")||e.includes("unlink")?r="file_delete":e.includes("fetch")||e.includes("http")||e.includes("request")||e.includes("api")||e.includes("get")||e.includes("post")?r="api_call":e.includes("install")||e.includes("package")||e.includes("npm")||e.includes("pip")?r="package_install":e.includes("config")||e.includes("setting")||e.includes("env")?r="config_change":e.includes("deploy")||e.includes("publish")||e.includes("release")?r="deploy":e.includes("send")||e.includes("message")||e.includes("email")||e.includes("notify")||e.includes("slack")||e.includes("telegram")?r="message_send":(e.includes("read")||e.includes("query")||e.includes("search")||e.includes("list")||e.includes("get"))&&(r="data_access");let n;try{const o=JSON.stringify(s);n=o.length>500?o.slice(0,500)+"...":o}catch{n="(unable to serialize)"}c("tools/call",{name:"aerostack__guardian_report",arguments:{action:`${t}(${Object.keys(s).join(", ")})`,category:r,risk_level:"low",details:n}}).catch(()=>{})}async function V(t,s){M(t,s);const r=await c("tools/call",{name:t,arguments:s});if(r.error?.code===-32050){const o=r.error.data,a=o?.approval_id;if(!a||!/^[a-zA-Z0-9_-]{4,128}$/.test(a))return{jsonrpc:"2.0",id:r.id,error:{code:-32603,message:"Approval required but no approval_id returned"}};p("Tool gate: waiting for approval",{approvalId:a,transport:o?.ws_url?"ws":"poll"});const l=o?.polling_url??`${d}/approval-status/${a}`,i=await R({approvalId:a,wsUrl:o?.ws_url,pollUrl:l,pollIntervalMs:E,timeoutMs:O});return i.status==="rejected"?{jsonrpc:"2.0",id:r.id,error:{code:-32603,message:`Tool call rejected: ${i.reviewer_note??"no reason given"}`}}:i.status==="expired"?{jsonrpc:"2.0",id:r.id,error:{code:-32603,message:"Approval request expired"}}:(p("Retrying tool call after approval",{approvalId:a,status:i.status}),c("tools/call",{name:t,arguments:s}))}const n=r.result?._meta;if(n?.approval_id&&n?.status==="pending"){const o=n.approval_id;p("Permission gate: waiting for approval",{approvalId:o,transport:n.ws_url?"ws":"poll"});const a=n.polling_url??`${d}/approval-status/${o}`,l=await R({approvalId:o,wsUrl:n.ws_url,pollUrl:a,pollIntervalMs:E,timeoutMs:O});let i;return l.status==="approved"||l.status==="executed"?i="APPROVED \u2014 Your request has been approved. You may proceed with the action.":l.status==="rejected"?i=`REJECTED \u2014 Your request was denied. Reason: ${l.reviewer_note??"No reason given."}. Do NOT proceed.`:i="EXPIRED \u2014 Your approval request timed out. Submit a new request if needed.",{jsonrpc:"2.0",id:r.id,result:{content:[{type:"text",text:i}]}}}return r}let S=null;async function m(){if(S)return;const t=await c("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"aerostack-gateway",version:"0.12.0"}});if(t.result){const s=t.result;S={protocolVersion:s.protocolVersion??"2024-11-05",instructions:s.instructions}}}const u=new T({name:"aerostack-gateway",version:"0.12.0"},{capabilities:{tools:{},resources:{},prompts:{}}});u.setRequestHandler(v,async()=>{await m();const t=await c("tools/list");if(t.error)throw new Error(t.error.message);return{tools:t.result.tools??[]}}),u.setRequestHandler(y,async t=>{await m();const{name:s,arguments:r}=t.params,e=await V(s,r??{});return e.error?{content:[{type:"text",text:`Error: ${e.error.message}`}],isError:!0}:{content:e.result.content??[{type:"text",text:JSON.stringify(e.result)}]}}),u.setRequestHandler(P,async()=>{await m();const t=await c("resources/list");if(t.error)throw new Error(t.error.message);return{resources:t.result.resources??[]}}),u.setRequestHandler(k,async t=>{await m();const s=await c("resources/read",{uri:t.params.uri});if(s.error)throw new Error(s.error.message);return{contents:s.result.contents??[]}}),u.setRequestHandler(C,async()=>{await m();const t=await c("prompts/list");if(t.error)throw new Error(t.error.message);return{prompts:t.result.prompts??[]}}),u.setRequestHandler(K,async t=>{await m();const s=await c("prompts/get",{name:t.params.name,arguments:t.params.arguments});if(s.error)throw new Error(s.error.message);return{messages:s.result.messages??[]}});async function D(){p("Connecting to workspace",{url:d});const t=new A;if(await u.connect(t),p("Ready",{url:d}),j)try{const r=await L(async e=>{try{const n=await fetch(`${d}/guardian-batch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g}`,"User-Agent":"aerostack-gateway/0.13.0","X-Agent-Id":"aerostack-gateway"},body:JSON.stringify({events:e})});return n.ok?(await n.json()).config?.hook_tracking??null:null}catch{return null}},x);H&&await b(r)&&p("Claude Code hook auto-installed",{port:r})}catch(s){I("Hook server failed to start (non-fatal)",{error:s instanceof Error?s.message:String(s)})}}process.on("SIGTERM",()=>{h(),process.exit(0)}),process.on("SIGINT",()=>{h(),process.exit(0)}),D().catch(t=>{U("Fatal error",{error:t instanceof Error?t.message:String(t)}),process.exit(1)});
|