@kenhkl/agent-gate 0.5.7 → 0.6.0
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/shared/storage/db.d.ts +96 -0
- package/dist/shared/storage/db.js +602 -0
- package/dist/shared/storage/db.js.map +1 -0
- package/dist/v1/cli.js +1149 -0
- package/dist/v1/cli.js.map +1 -0
- package/dist/v1/server.d.ts +5 -0
- package/dist/v1/server.js +977 -0
- package/dist/v1/server.js.map +1 -0
- package/dist/v3/cli.d.ts +1 -0
- package/dist/{cli.js → v3/cli.js} +8 -5
- package/dist/v3/cli.js.map +1 -0
- package/package.json +20 -5
- package/dist/cli.js.map +0 -1
- /package/dist/{cli.d.ts → v1/cli.d.ts} +0 -0
|
@@ -0,0 +1,977 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __esm = (fn, res) => function __init() {
|
|
9
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
10
|
+
};
|
|
11
|
+
var __export = (target, all) => {
|
|
12
|
+
for (var name in all)
|
|
13
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
14
|
+
};
|
|
15
|
+
var __copyProps = (to, from, except, desc) => {
|
|
16
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
17
|
+
for (let key of __getOwnPropNames(from))
|
|
18
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
19
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
20
|
+
}
|
|
21
|
+
return to;
|
|
22
|
+
};
|
|
23
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
24
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
25
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
26
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
27
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
28
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
29
|
+
mod
|
|
30
|
+
));
|
|
31
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
|
+
|
|
33
|
+
// node_modules/tsup/assets/cjs_shims.js
|
|
34
|
+
var getImportMetaUrl, importMetaUrl;
|
|
35
|
+
var init_cjs_shims = __esm({
|
|
36
|
+
"node_modules/tsup/assets/cjs_shims.js"() {
|
|
37
|
+
"use strict";
|
|
38
|
+
getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
|
|
39
|
+
importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// src/shared/storage/json-storage.ts
|
|
44
|
+
var json_storage_exports = {};
|
|
45
|
+
__export(json_storage_exports, {
|
|
46
|
+
JsonStorage: () => JsonStorage
|
|
47
|
+
});
|
|
48
|
+
function nowISO() {
|
|
49
|
+
return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace(/\.\d+Z$/, "");
|
|
50
|
+
}
|
|
51
|
+
function getDefaultDataDir() {
|
|
52
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
53
|
+
const xdgData = process.env.XDG_DATA_HOME || (0, import_path.join)(home, ".local", "share");
|
|
54
|
+
return (0, import_path.join)(xdgData, "agent_gate", "storage");
|
|
55
|
+
}
|
|
56
|
+
var import_fs, import_path, JsonStorage;
|
|
57
|
+
var init_json_storage = __esm({
|
|
58
|
+
"src/shared/storage/json-storage.ts"() {
|
|
59
|
+
"use strict";
|
|
60
|
+
init_cjs_shims();
|
|
61
|
+
import_fs = require("fs");
|
|
62
|
+
import_path = require("path");
|
|
63
|
+
JsonStorage = class {
|
|
64
|
+
dataDir;
|
|
65
|
+
agentsPath;
|
|
66
|
+
sessionsPath;
|
|
67
|
+
toolCallsDir;
|
|
68
|
+
nextId;
|
|
69
|
+
/** per-session 互斥锁,保证同一 session 的 seq 生成 + 写入原子性 */
|
|
70
|
+
sessionLocks = /* @__PURE__ */ new Map();
|
|
71
|
+
constructor(dataDir) {
|
|
72
|
+
this.dataDir = dataDir || process.env.AGENT_GATE_DATA_DIR || getDefaultDataDir();
|
|
73
|
+
this.agentsPath = (0, import_path.join)(this.dataDir, "agents.json");
|
|
74
|
+
this.sessionsPath = (0, import_path.join)(this.dataDir, "sessions.json");
|
|
75
|
+
this.toolCallsDir = (0, import_path.join)(this.dataDir, "tool_calls");
|
|
76
|
+
if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true });
|
|
77
|
+
if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true });
|
|
78
|
+
this.nextId = this.recoverNextId();
|
|
79
|
+
}
|
|
80
|
+
/** 扫描所有 tool_calls 文件,找到最大 id + 1 */
|
|
81
|
+
recoverNextId() {
|
|
82
|
+
let maxId = 0;
|
|
83
|
+
try {
|
|
84
|
+
const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
85
|
+
for (const file of files) {
|
|
86
|
+
const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
|
|
87
|
+
for (const r of records) {
|
|
88
|
+
if (r.id > maxId) maxId = r.id;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
} catch {
|
|
92
|
+
}
|
|
93
|
+
return maxId + 1;
|
|
94
|
+
}
|
|
95
|
+
readJsonFile(path, fallback) {
|
|
96
|
+
try {
|
|
97
|
+
if (!(0, import_fs.existsSync)(path)) return fallback;
|
|
98
|
+
return JSON.parse((0, import_fs.readFileSync)(path, "utf-8"));
|
|
99
|
+
} catch {
|
|
100
|
+
return fallback;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** 原子写入:先写 .tmp 再 rename */
|
|
104
|
+
writeJsonFile(path, data) {
|
|
105
|
+
const dir = (0, import_path.dirname)(path);
|
|
106
|
+
if (!(0, import_fs.existsSync)(dir)) (0, import_fs.mkdirSync)(dir, { recursive: true });
|
|
107
|
+
const tmp = path + ".tmp";
|
|
108
|
+
(0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), "utf-8");
|
|
109
|
+
(0, import_fs.renameSync)(tmp, path);
|
|
110
|
+
}
|
|
111
|
+
loadAgents() {
|
|
112
|
+
const raw = this.readJsonFile(this.agentsPath, {});
|
|
113
|
+
return new Map(Object.entries(raw));
|
|
114
|
+
}
|
|
115
|
+
saveAgents(agents) {
|
|
116
|
+
this.writeJsonFile(this.agentsPath, Object.fromEntries(agents));
|
|
117
|
+
}
|
|
118
|
+
loadSessions() {
|
|
119
|
+
const raw = this.readJsonFile(this.sessionsPath, {});
|
|
120
|
+
return new Map(Object.entries(raw));
|
|
121
|
+
}
|
|
122
|
+
saveSessions(sessions) {
|
|
123
|
+
this.writeJsonFile(this.sessionsPath, Object.fromEntries(sessions));
|
|
124
|
+
}
|
|
125
|
+
loadToolCalls(sessionId) {
|
|
126
|
+
return this.readJsonFile(
|
|
127
|
+
(0, import_path.join)(this.toolCallsDir, `${sessionId}.json`),
|
|
128
|
+
[]
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
saveToolCalls(sessionId, records) {
|
|
132
|
+
this.writeJsonFile((0, import_path.join)(this.toolCallsDir, `${sessionId}.json`), records);
|
|
133
|
+
}
|
|
134
|
+
getOrCreateAgent(agentType, hostname, version2 = "") {
|
|
135
|
+
const agents = this.loadAgents();
|
|
136
|
+
const id = `${agentType}:${hostname}`;
|
|
137
|
+
const existing = agents.get(id);
|
|
138
|
+
if (existing) {
|
|
139
|
+
existing.last_seen_at = nowISO();
|
|
140
|
+
if (version2) existing.agent_version = version2;
|
|
141
|
+
} else {
|
|
142
|
+
agents.set(id, {
|
|
143
|
+
id,
|
|
144
|
+
agent_type: agentType,
|
|
145
|
+
agent_version: version2,
|
|
146
|
+
hostname,
|
|
147
|
+
registered_at: nowISO(),
|
|
148
|
+
last_seen_at: nowISO()
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
this.saveAgents(agents);
|
|
152
|
+
return id;
|
|
153
|
+
}
|
|
154
|
+
getOrCreateSession(sessionId, agentId, cwd = "", prompt = "", osType = "") {
|
|
155
|
+
const sessions = this.loadSessions();
|
|
156
|
+
if (!sessions.has(sessionId)) {
|
|
157
|
+
sessions.set(sessionId, {
|
|
158
|
+
id: sessionId,
|
|
159
|
+
agent_id: agentId,
|
|
160
|
+
cwd,
|
|
161
|
+
user_prompt: prompt,
|
|
162
|
+
os_type: osType,
|
|
163
|
+
status: "active",
|
|
164
|
+
created_at: nowISO(),
|
|
165
|
+
ended_at: null,
|
|
166
|
+
tool_call_count: 0
|
|
167
|
+
});
|
|
168
|
+
this.saveSessions(sessions);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
getNextSeq(sessionId) {
|
|
172
|
+
const records = this.loadToolCalls(sessionId);
|
|
173
|
+
if (records.length === 0) return 1;
|
|
174
|
+
return Math.max(...records.map((r) => r.seq)) + 1;
|
|
175
|
+
}
|
|
176
|
+
insertToolCall(record) {
|
|
177
|
+
const sessionId = record.session_id;
|
|
178
|
+
const prev = this.sessionLocks.get(sessionId) ?? Promise.resolve();
|
|
179
|
+
const next = prev.then(() => {
|
|
180
|
+
const records = this.loadToolCalls(sessionId);
|
|
181
|
+
const existingSeq = records.length === 0 ? 0 : Math.max(...records.map((r) => r.seq));
|
|
182
|
+
record.seq = existingSeq + 1;
|
|
183
|
+
const id = this.nextId++;
|
|
184
|
+
records.push({ ...record, id, called_at: nowISO() });
|
|
185
|
+
this.saveToolCalls(sessionId, records);
|
|
186
|
+
return id;
|
|
187
|
+
});
|
|
188
|
+
this.sessionLocks.set(sessionId, next.catch(() => {
|
|
189
|
+
}));
|
|
190
|
+
const cleanup = () => {
|
|
191
|
+
if (this.sessionLocks.get(sessionId) === next) {
|
|
192
|
+
this.sessionLocks.delete(sessionId);
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
next.then(cleanup, cleanup);
|
|
196
|
+
return 0;
|
|
197
|
+
}
|
|
198
|
+
getActionHistory(sessionId, limit = 100) {
|
|
199
|
+
const records = this.loadToolCalls(sessionId);
|
|
200
|
+
const sorted = [...records].sort((a, b) => a.seq - b.seq);
|
|
201
|
+
const slice = sorted.slice(-limit);
|
|
202
|
+
return slice.map((r) => ({ action_type: r.action_type, action_detail: r.action_detail }));
|
|
203
|
+
}
|
|
204
|
+
queryToolCalls(params) {
|
|
205
|
+
const sessions = this.loadSessions();
|
|
206
|
+
const agents = this.loadAgents();
|
|
207
|
+
let allRecords = [];
|
|
208
|
+
if (params.sessionId) {
|
|
209
|
+
const records = this.loadToolCalls(params.sessionId);
|
|
210
|
+
allRecords = records.map((r) => this.enrichRecord(r, sessions, agents));
|
|
211
|
+
} else {
|
|
212
|
+
try {
|
|
213
|
+
const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
214
|
+
for (const file of files) {
|
|
215
|
+
const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
|
|
216
|
+
allRecords.push(...records.map((r) => this.enrichRecord(r, sessions, agents)));
|
|
217
|
+
}
|
|
218
|
+
} catch {
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (params.decision) {
|
|
222
|
+
allRecords = allRecords.filter((r) => r.decision === params.decision);
|
|
223
|
+
}
|
|
224
|
+
allRecords.sort((a, b) => b.called_at.localeCompare(a.called_at));
|
|
225
|
+
const offset = params.offset || 0;
|
|
226
|
+
const limit = params.limit || 50;
|
|
227
|
+
return allRecords.slice(offset, offset + limit);
|
|
228
|
+
}
|
|
229
|
+
countToolCalls(params) {
|
|
230
|
+
const sessions = this.loadSessions();
|
|
231
|
+
let allRecords = [];
|
|
232
|
+
try {
|
|
233
|
+
const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
234
|
+
for (const file of files) {
|
|
235
|
+
const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
|
|
236
|
+
allRecords.push(...records);
|
|
237
|
+
}
|
|
238
|
+
} catch {
|
|
239
|
+
}
|
|
240
|
+
if (params.decision) {
|
|
241
|
+
allRecords = allRecords.filter((r) => r.decision === params.decision);
|
|
242
|
+
}
|
|
243
|
+
return allRecords.length;
|
|
244
|
+
}
|
|
245
|
+
enrichRecord(record, sessions, agents) {
|
|
246
|
+
const session = sessions.get(record.session_id);
|
|
247
|
+
const agentId = session?.agent_id;
|
|
248
|
+
const agent = agentId ? agents.get(agentId) : void 0;
|
|
249
|
+
return {
|
|
250
|
+
...record,
|
|
251
|
+
agent_type: agent?.agent_type || "",
|
|
252
|
+
agent_version: agent?.agent_version || "",
|
|
253
|
+
hostname: agent?.hostname || ""
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
getAgentsList() {
|
|
257
|
+
const agents = this.loadAgents();
|
|
258
|
+
const sessions = this.loadSessions();
|
|
259
|
+
const result = [];
|
|
260
|
+
for (const agent of agents.values()) {
|
|
261
|
+
let sessionCount = 0;
|
|
262
|
+
let callCount = 0;
|
|
263
|
+
for (const session of sessions.values()) {
|
|
264
|
+
if (session.agent_id === agent.id) {
|
|
265
|
+
sessionCount++;
|
|
266
|
+
const records = this.loadToolCalls(session.id);
|
|
267
|
+
callCount += records.length;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
result.push({
|
|
271
|
+
agent_type: agent.agent_type,
|
|
272
|
+
hostname: agent.hostname,
|
|
273
|
+
version: agent.agent_version,
|
|
274
|
+
session_count: sessionCount,
|
|
275
|
+
call_count: callCount
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
result.sort((a, b) => b.call_count - a.call_count);
|
|
279
|
+
return result.slice(0, 20);
|
|
280
|
+
}
|
|
281
|
+
getTimeline(limit = 100) {
|
|
282
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
283
|
+
try {
|
|
284
|
+
const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
285
|
+
for (const file of files) {
|
|
286
|
+
const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
|
|
287
|
+
for (const r of records) {
|
|
288
|
+
const minute = r.called_at.replace(/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}):\d{2}/, "$1T$2");
|
|
289
|
+
const bucket = buckets.get(minute) || { allow: 0, deny: 0 };
|
|
290
|
+
if (r.decision === "Allow") bucket.allow++;
|
|
291
|
+
else bucket.deny++;
|
|
292
|
+
buckets.set(minute, bucket);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
} catch {
|
|
296
|
+
}
|
|
297
|
+
const result = [];
|
|
298
|
+
for (const [time, counts] of buckets) {
|
|
299
|
+
result.push({ time, ...counts });
|
|
300
|
+
}
|
|
301
|
+
result.sort((a, b) => b.time.localeCompare(a.time));
|
|
302
|
+
return result.slice(0, limit);
|
|
303
|
+
}
|
|
304
|
+
close() {
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
// src/shared/storage/sqlite-storage.ts
|
|
311
|
+
var sqlite_storage_exports = {};
|
|
312
|
+
__export(sqlite_storage_exports, {
|
|
313
|
+
SqliteStorage: () => SqliteStorage
|
|
314
|
+
});
|
|
315
|
+
function getDefaultDbPath() {
|
|
316
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
317
|
+
const xdgData = process.env.XDG_DATA_HOME || (0, import_path2.join)(home, ".local", "share");
|
|
318
|
+
return (0, import_path2.join)(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
319
|
+
}
|
|
320
|
+
var import_fs2, import_path2, SCHEMA, SqliteStorage;
|
|
321
|
+
var init_sqlite_storage = __esm({
|
|
322
|
+
"src/shared/storage/sqlite-storage.ts"() {
|
|
323
|
+
"use strict";
|
|
324
|
+
init_cjs_shims();
|
|
325
|
+
import_fs2 = require("fs");
|
|
326
|
+
import_path2 = require("path");
|
|
327
|
+
SCHEMA = `
|
|
328
|
+
CREATE TABLE IF NOT EXISTS agents (
|
|
329
|
+
id TEXT PRIMARY KEY,
|
|
330
|
+
agent_type TEXT NOT NULL,
|
|
331
|
+
agent_version TEXT DEFAULT '',
|
|
332
|
+
hostname TEXT NOT NULL,
|
|
333
|
+
registered_at TEXT DEFAULT (datetime('now')),
|
|
334
|
+
last_seen_at TEXT DEFAULT (datetime('now'))
|
|
335
|
+
);
|
|
336
|
+
|
|
337
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
338
|
+
id TEXT PRIMARY KEY,
|
|
339
|
+
agent_id TEXT NOT NULL REFERENCES agents(id),
|
|
340
|
+
cwd TEXT DEFAULT '',
|
|
341
|
+
user_prompt TEXT DEFAULT '',
|
|
342
|
+
os_type TEXT DEFAULT '',
|
|
343
|
+
status TEXT DEFAULT 'active',
|
|
344
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
345
|
+
ended_at TEXT,
|
|
346
|
+
tool_call_count INTEGER DEFAULT 0
|
|
347
|
+
);
|
|
348
|
+
|
|
349
|
+
CREATE TABLE IF NOT EXISTS tool_calls (
|
|
350
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
351
|
+
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
352
|
+
seq INTEGER NOT NULL,
|
|
353
|
+
tool_name TEXT NOT NULL,
|
|
354
|
+
command TEXT NOT NULL,
|
|
355
|
+
description TEXT DEFAULT '',
|
|
356
|
+
cwd TEXT DEFAULT '',
|
|
357
|
+
action_type TEXT NOT NULL,
|
|
358
|
+
action_detail TEXT NOT NULL,
|
|
359
|
+
decision TEXT NOT NULL,
|
|
360
|
+
risk_level TEXT DEFAULT '',
|
|
361
|
+
risk_type TEXT DEFAULT '',
|
|
362
|
+
violated_layers TEXT DEFAULT '[]',
|
|
363
|
+
reason TEXT DEFAULT '',
|
|
364
|
+
confidence INTEGER DEFAULT 0,
|
|
365
|
+
analysis_duration_ms REAL DEFAULT 0,
|
|
366
|
+
called_at TEXT DEFAULT (datetime('now')),
|
|
367
|
+
UNIQUE(session_id, seq)
|
|
368
|
+
);
|
|
369
|
+
|
|
370
|
+
CREATE INDEX IF NOT EXISTS idx_tool_calls_session_seq ON tool_calls(session_id, seq);
|
|
371
|
+
CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, called_at);
|
|
372
|
+
`;
|
|
373
|
+
SqliteStorage = class {
|
|
374
|
+
db;
|
|
375
|
+
constructor(dbPath) {
|
|
376
|
+
let Database;
|
|
377
|
+
try {
|
|
378
|
+
Database = require("better-sqlite3");
|
|
379
|
+
} catch {
|
|
380
|
+
throw new Error(
|
|
381
|
+
"better-sqlite3 is not installed. Use AGENT_GATE_STORAGE=json for environments without native modules."
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
const path = dbPath || getDefaultDbPath();
|
|
385
|
+
const dir = (0, import_path2.dirname)(path);
|
|
386
|
+
if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true });
|
|
387
|
+
this.db = new Database(path);
|
|
388
|
+
this.db.pragma("journal_mode = WAL");
|
|
389
|
+
this.db.exec(SCHEMA);
|
|
390
|
+
}
|
|
391
|
+
static isAvailable() {
|
|
392
|
+
try {
|
|
393
|
+
require.resolve("better-sqlite3");
|
|
394
|
+
return true;
|
|
395
|
+
} catch {
|
|
396
|
+
return false;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
getOrCreateAgent(agentType, hostname, version2 = "") {
|
|
400
|
+
const id = `${agentType}:${hostname}`;
|
|
401
|
+
this.db.prepare(
|
|
402
|
+
"INSERT OR IGNORE INTO agents (id, agent_type, agent_version, hostname) VALUES (?, ?, ?, ?)"
|
|
403
|
+
).run(id, agentType, version2, hostname);
|
|
404
|
+
this.db.prepare("UPDATE agents SET last_seen_at = datetime('now') WHERE id = ?").run(id);
|
|
405
|
+
return id;
|
|
406
|
+
}
|
|
407
|
+
getOrCreateSession(sessionId, agentId, cwd = "", prompt = "", osType = "") {
|
|
408
|
+
this.db.prepare(
|
|
409
|
+
"INSERT OR IGNORE INTO sessions (id, agent_id, cwd, user_prompt, os_type) VALUES (?, ?, ?, ?, ?)"
|
|
410
|
+
).run(sessionId, agentId, cwd, prompt, osType);
|
|
411
|
+
}
|
|
412
|
+
getNextSeq(sessionId) {
|
|
413
|
+
const row = this.db.prepare(
|
|
414
|
+
"SELECT COALESCE(MAX(seq), 0) + 1 as next FROM tool_calls WHERE session_id = ?"
|
|
415
|
+
).get(sessionId);
|
|
416
|
+
return row.next;
|
|
417
|
+
}
|
|
418
|
+
insertToolCall(record) {
|
|
419
|
+
const result = this.db.transaction((rec) => {
|
|
420
|
+
const row = this.db.prepare(
|
|
421
|
+
"SELECT COALESCE(MAX(seq), 0) + 1 as next FROM tool_calls WHERE session_id = ?"
|
|
422
|
+
).get(rec.session_id);
|
|
423
|
+
const seq = row.next;
|
|
424
|
+
return this.db.prepare(`
|
|
425
|
+
INSERT INTO tool_calls (session_id, seq, tool_name, command, description, cwd,
|
|
426
|
+
action_type, action_detail, decision, risk_level, risk_type, violated_layers,
|
|
427
|
+
reason, confidence, analysis_duration_ms)
|
|
428
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
429
|
+
`).run(
|
|
430
|
+
rec.session_id,
|
|
431
|
+
seq,
|
|
432
|
+
rec.tool_name,
|
|
433
|
+
rec.command,
|
|
434
|
+
rec.description,
|
|
435
|
+
rec.cwd,
|
|
436
|
+
rec.action_type,
|
|
437
|
+
rec.action_detail,
|
|
438
|
+
rec.decision,
|
|
439
|
+
rec.risk_level,
|
|
440
|
+
rec.risk_type,
|
|
441
|
+
rec.violated_layers,
|
|
442
|
+
rec.reason,
|
|
443
|
+
rec.confidence,
|
|
444
|
+
rec.analysis_duration_ms
|
|
445
|
+
);
|
|
446
|
+
})(record);
|
|
447
|
+
return Number(result.lastInsertRowid);
|
|
448
|
+
}
|
|
449
|
+
getActionHistory(sessionId, limit = 100) {
|
|
450
|
+
const rows = this.db.prepare(
|
|
451
|
+
"SELECT action_type, action_detail FROM tool_calls WHERE session_id = ? ORDER BY seq DESC LIMIT ?"
|
|
452
|
+
).all(sessionId, limit);
|
|
453
|
+
return rows.reverse();
|
|
454
|
+
}
|
|
455
|
+
queryToolCalls(params) {
|
|
456
|
+
const conditions = [];
|
|
457
|
+
const values = [];
|
|
458
|
+
if (params.sessionId) {
|
|
459
|
+
conditions.push("tc.session_id = ?");
|
|
460
|
+
values.push(params.sessionId);
|
|
461
|
+
}
|
|
462
|
+
if (params.decision) {
|
|
463
|
+
conditions.push("tc.decision = ?");
|
|
464
|
+
values.push(params.decision);
|
|
465
|
+
}
|
|
466
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
467
|
+
const limit = params.limit || 50;
|
|
468
|
+
const offset = params.offset || 0;
|
|
469
|
+
return this.db.prepare(
|
|
470
|
+
`SELECT tc.*, a.agent_type, a.agent_version, a.hostname
|
|
471
|
+
FROM tool_calls tc
|
|
472
|
+
LEFT JOIN sessions s ON tc.session_id = s.id
|
|
473
|
+
LEFT JOIN agents a ON s.agent_id = a.id
|
|
474
|
+
${where} ORDER BY tc.called_at DESC LIMIT ? OFFSET ?`
|
|
475
|
+
).all(...values, limit, offset);
|
|
476
|
+
}
|
|
477
|
+
countToolCalls(params) {
|
|
478
|
+
const conditions = [];
|
|
479
|
+
const values = [];
|
|
480
|
+
if (params.decision) {
|
|
481
|
+
conditions.push("tc.decision = ?");
|
|
482
|
+
values.push(params.decision);
|
|
483
|
+
}
|
|
484
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
485
|
+
const row = this.db.prepare(
|
|
486
|
+
`SELECT COUNT(*) as total FROM tool_calls tc ${where}`
|
|
487
|
+
).get(...values);
|
|
488
|
+
return row?.total ?? 0;
|
|
489
|
+
}
|
|
490
|
+
getAgentsList() {
|
|
491
|
+
return this.db.prepare(`
|
|
492
|
+
SELECT a.agent_type, a.hostname, a.agent_version as version,
|
|
493
|
+
COUNT(DISTINCT s.id) as session_count,
|
|
494
|
+
COUNT(tc.id) as call_count
|
|
495
|
+
FROM agents a
|
|
496
|
+
LEFT JOIN sessions s ON s.agent_id = a.id
|
|
497
|
+
LEFT JOIN tool_calls tc ON tc.session_id = s.id
|
|
498
|
+
GROUP BY a.id
|
|
499
|
+
ORDER BY call_count DESC
|
|
500
|
+
LIMIT 20
|
|
501
|
+
`).all();
|
|
502
|
+
}
|
|
503
|
+
getTimeline(limit = 100) {
|
|
504
|
+
const rows = this.db.prepare(`
|
|
505
|
+
SELECT strftime('%Y-%m-%dT%H:%M', called_at) as time,
|
|
506
|
+
SUM(CASE WHEN decision='Allow' THEN 1 ELSE 0 END) as allow,
|
|
507
|
+
SUM(CASE WHEN decision='Deny' THEN 1 ELSE 0 END) as deny
|
|
508
|
+
FROM tool_calls
|
|
509
|
+
GROUP BY strftime('%Y-%m-%dT%H:%M', called_at)
|
|
510
|
+
ORDER BY time DESC
|
|
511
|
+
LIMIT ?
|
|
512
|
+
`).all(limit);
|
|
513
|
+
return rows.map((r) => {
|
|
514
|
+
const d = /* @__PURE__ */ new Date(r.time + ":00Z");
|
|
515
|
+
const year = d.getFullYear();
|
|
516
|
+
const month = String(d.getMonth() + 1).padStart(2, "0");
|
|
517
|
+
const day = String(d.getDate()).padStart(2, "0");
|
|
518
|
+
const hours = String(d.getHours()).padStart(2, "0");
|
|
519
|
+
const minutes = String(d.getMinutes()).padStart(2, "0");
|
|
520
|
+
return { ...r, time: `${year}-${month}-${day}T${hours}:${minutes}` };
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
close() {
|
|
524
|
+
if (this.db) {
|
|
525
|
+
this.db.close();
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
// src/v1/server.ts
|
|
533
|
+
var server_exports = {};
|
|
534
|
+
__export(server_exports, {
|
|
535
|
+
createApp: () => createApp
|
|
536
|
+
});
|
|
537
|
+
module.exports = __toCommonJS(server_exports);
|
|
538
|
+
init_cjs_shims();
|
|
539
|
+
var import_hono = require("hono");
|
|
540
|
+
var import_cors = require("hono/cors");
|
|
541
|
+
var import_logger = require("hono/logger");
|
|
542
|
+
|
|
543
|
+
// src/v1/routes.ts
|
|
544
|
+
init_cjs_shims();
|
|
545
|
+
|
|
546
|
+
// src/shared/models.ts
|
|
547
|
+
init_cjs_shims();
|
|
548
|
+
var import_zod = require("zod");
|
|
549
|
+
|
|
550
|
+
// src/version.ts
|
|
551
|
+
init_cjs_shims();
|
|
552
|
+
var _version = true ? "0.6.0" : (() => {
|
|
553
|
+
try {
|
|
554
|
+
const require2 = createRequire(importMetaUrl);
|
|
555
|
+
const pkg = require2("../package.json");
|
|
556
|
+
return pkg.version;
|
|
557
|
+
} catch {
|
|
558
|
+
return "unknown";
|
|
559
|
+
}
|
|
560
|
+
})();
|
|
561
|
+
var version = _version;
|
|
562
|
+
|
|
563
|
+
// src/shared/models.ts
|
|
564
|
+
var AgentGateInputSchema = import_zod.z.object({
|
|
565
|
+
agent_type: import_zod.z.string().describe("Agent identifier, e.g. opendesk, claude-code"),
|
|
566
|
+
agent_version: import_zod.z.string().default("0.1.0"),
|
|
567
|
+
session_id: import_zod.z.string().describe("Session unique identifier"),
|
|
568
|
+
tool_name: import_zod.z.string().optional().describe("Tool name, e.g. bash, file_write"),
|
|
569
|
+
command: import_zod.z.string().optional().describe("Tool command or description"),
|
|
570
|
+
a_next: import_zod.z.object({
|
|
571
|
+
action_type: import_zod.z.string(),
|
|
572
|
+
action_detail: import_zod.z.string()
|
|
573
|
+
}).optional().describe("Next action (Python API format)"),
|
|
574
|
+
cwd: import_zod.z.string().default(""),
|
|
575
|
+
description: import_zod.z.string().default(""),
|
|
576
|
+
user_prompt: import_zod.z.string().default(""),
|
|
577
|
+
action_history: import_zod.z.array(import_zod.z.object({
|
|
578
|
+
action_type: import_zod.z.string(),
|
|
579
|
+
action_detail: import_zod.z.string()
|
|
580
|
+
})).default([]),
|
|
581
|
+
metadata: import_zod.z.record(import_zod.z.unknown()).optional()
|
|
582
|
+
});
|
|
583
|
+
var AgentGateResponseSchema = import_zod.z.object({
|
|
584
|
+
decision: import_zod.z.enum(["Allow", "Deny"]),
|
|
585
|
+
reason: import_zod.z.string(),
|
|
586
|
+
risk_level: import_zod.z.enum(["low", "medium", "high", "critical"]).default("low"),
|
|
587
|
+
risk_type: import_zod.z.string().default(""),
|
|
588
|
+
violated_layers: import_zod.z.array(import_zod.z.string()).default([]),
|
|
589
|
+
confidence: import_zod.z.number().int().min(0).max(100).default(100),
|
|
590
|
+
analysis_duration_ms: import_zod.z.number().default(0),
|
|
591
|
+
collected_context: import_zod.z.object({
|
|
592
|
+
os: import_zod.z.object({
|
|
593
|
+
system: import_zod.z.string(),
|
|
594
|
+
distribution: import_zod.z.string().optional(),
|
|
595
|
+
hostname: import_zod.z.string().optional()
|
|
596
|
+
}).optional(),
|
|
597
|
+
process: import_zod.z.object({
|
|
598
|
+
pid: import_zod.z.number(),
|
|
599
|
+
name: import_zod.z.string().optional()
|
|
600
|
+
}).optional(),
|
|
601
|
+
user: import_zod.z.object({
|
|
602
|
+
uid: import_zod.z.number().optional(),
|
|
603
|
+
username: import_zod.z.string().optional()
|
|
604
|
+
}).optional()
|
|
605
|
+
}).optional()
|
|
606
|
+
});
|
|
607
|
+
var HealthResponseSchema = import_zod.z.object({
|
|
608
|
+
status: import_zod.z.string().default("healthy"),
|
|
609
|
+
version: import_zod.z.string().default(version),
|
|
610
|
+
moss_version: import_zod.z.string().default("N/A"),
|
|
611
|
+
moss_status: import_zod.z.string().default("unknown")
|
|
612
|
+
});
|
|
613
|
+
|
|
614
|
+
// src/shared/normalizer.ts
|
|
615
|
+
init_cjs_shims();
|
|
616
|
+
function normalize(input, systemContext) {
|
|
617
|
+
const actionHistory = input.action_history.map((h) => ({
|
|
618
|
+
action_type: h.action_type,
|
|
619
|
+
action_detail: h.action_detail
|
|
620
|
+
}));
|
|
621
|
+
const toolName = input.tool_name || input.a_next?.action_type || "unknown";
|
|
622
|
+
const command = input.command || input.a_next?.action_detail || "";
|
|
623
|
+
return {
|
|
624
|
+
session_id: input.session_id,
|
|
625
|
+
prompt_session: input.user_prompt || input.description || "",
|
|
626
|
+
action_history: actionHistory,
|
|
627
|
+
a_next: {
|
|
628
|
+
action_type: toolName,
|
|
629
|
+
action_detail: command
|
|
630
|
+
},
|
|
631
|
+
reason: input.description || "",
|
|
632
|
+
os_type: "",
|
|
633
|
+
// Will be auto-detected by AgentMoss
|
|
634
|
+
cwd: input.cwd || process.cwd(),
|
|
635
|
+
metadata: {
|
|
636
|
+
...input.metadata,
|
|
637
|
+
agent_type: input.agent_type,
|
|
638
|
+
agent_version: input.agent_version,
|
|
639
|
+
system_context: systemContext
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// src/shared/collector/index.ts
|
|
645
|
+
init_cjs_shims();
|
|
646
|
+
|
|
647
|
+
// src/shared/collector/system-info.ts
|
|
648
|
+
init_cjs_shims();
|
|
649
|
+
var import_os = __toESM(require("os"));
|
|
650
|
+
async function collectSystemInfo() {
|
|
651
|
+
try {
|
|
652
|
+
return {
|
|
653
|
+
system: process.platform,
|
|
654
|
+
distribution: `${import_os.default.type()} ${import_os.default.release()}`,
|
|
655
|
+
hostname: import_os.default.hostname(),
|
|
656
|
+
arch: import_os.default.arch(),
|
|
657
|
+
cpu_count: import_os.default.cpus().length,
|
|
658
|
+
memory_total_mb: Math.round(import_os.default.totalmem() / (1024 * 1024))
|
|
659
|
+
};
|
|
660
|
+
} catch {
|
|
661
|
+
return { system: "unknown" };
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// src/shared/collector/process-info.ts
|
|
666
|
+
init_cjs_shims();
|
|
667
|
+
async function collectProcessInfo() {
|
|
668
|
+
try {
|
|
669
|
+
return {
|
|
670
|
+
pid: process.pid,
|
|
671
|
+
ppid: process.ppid,
|
|
672
|
+
name: process.title || "node",
|
|
673
|
+
execPath: process.execPath
|
|
674
|
+
};
|
|
675
|
+
} catch {
|
|
676
|
+
return { pid: -1 };
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// src/shared/collector/user-info.ts
|
|
681
|
+
init_cjs_shims();
|
|
682
|
+
var import_os2 = __toESM(require("os"));
|
|
683
|
+
async function collectUserInfo() {
|
|
684
|
+
try {
|
|
685
|
+
const userInfo = import_os2.default.userInfo();
|
|
686
|
+
return {
|
|
687
|
+
uid: userInfo.uid,
|
|
688
|
+
gid: userInfo.gid,
|
|
689
|
+
username: userInfo.username,
|
|
690
|
+
homedir: userInfo.homedir
|
|
691
|
+
};
|
|
692
|
+
} catch {
|
|
693
|
+
return { uid: -1 };
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// src/shared/collector/index.ts
|
|
698
|
+
async function collectSystemContext() {
|
|
699
|
+
const [os3, proc, user] = await Promise.all([
|
|
700
|
+
collectSystemInfo(),
|
|
701
|
+
collectProcessInfo(),
|
|
702
|
+
collectUserInfo()
|
|
703
|
+
]);
|
|
704
|
+
return { os: os3, process: proc, user };
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// src/shared/moss-client.ts
|
|
708
|
+
init_cjs_shims();
|
|
709
|
+
var import_node_fetch = __toESM(require("node-fetch"));
|
|
710
|
+
var DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
|
|
711
|
+
var mossUrl = DEFAULT_MOSS_URL;
|
|
712
|
+
async function callAgentMoss(request) {
|
|
713
|
+
try {
|
|
714
|
+
const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
|
|
715
|
+
method: "POST",
|
|
716
|
+
headers: { "Content-Type": "application/json" },
|
|
717
|
+
body: JSON.stringify(request),
|
|
718
|
+
// 100s:覆盖 AgentMoss 总超时(90s)+ 余量,避免 AgentMoss 还在分析时
|
|
719
|
+
// 被 AgentGate 抢断后 fail-closed 误杀。AgentGate 这层不重试(AgentMoss 内部已重试)。
|
|
720
|
+
timeout: 1e5
|
|
721
|
+
});
|
|
722
|
+
if (!resp.ok) {
|
|
723
|
+
console.error(`[AgentGate] AgentMoss HTTP ${resp.status}: ${resp.statusText}`);
|
|
724
|
+
return failClosedResponse(`AgentMoss returned ${resp.status}`);
|
|
725
|
+
}
|
|
726
|
+
return await resp.json();
|
|
727
|
+
} catch (err) {
|
|
728
|
+
const errType = err?.type || "";
|
|
729
|
+
const errMsg = String(err?.message || err);
|
|
730
|
+
if (errType === "request-timeout" || errMsg.includes("timeout")) {
|
|
731
|
+
console.error(`[AgentGate] AgentMoss analysis timeout: ${errMsg}`);
|
|
732
|
+
return failClosedResponse("AgentMoss analysis timeout", "analysis_timeout");
|
|
733
|
+
}
|
|
734
|
+
console.error(`[AgentGate] AgentMoss unreachable: ${errMsg}`);
|
|
735
|
+
return failClosedResponse("AgentMoss service unavailable", "service_unavailable");
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
async function fetchMossHealth() {
|
|
739
|
+
try {
|
|
740
|
+
const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/health`, {
|
|
741
|
+
timeout: 3e3
|
|
742
|
+
});
|
|
743
|
+
if (!resp.ok) {
|
|
744
|
+
return { moss_version: "N/A", moss_status: "error" };
|
|
745
|
+
}
|
|
746
|
+
const data = await resp.json();
|
|
747
|
+
return {
|
|
748
|
+
moss_version: data.version || "unknown",
|
|
749
|
+
moss_status: data.status || "unknown"
|
|
750
|
+
};
|
|
751
|
+
} catch {
|
|
752
|
+
return { moss_version: "N/A", moss_status: "unreachable" };
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
function failClosedResponse(reason, riskType = "service_unavailable") {
|
|
756
|
+
return {
|
|
757
|
+
decision: "Deny",
|
|
758
|
+
reason,
|
|
759
|
+
risk_level: "high",
|
|
760
|
+
risk_type: riskType,
|
|
761
|
+
violated_layers: [],
|
|
762
|
+
confidence: 100
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
// src/shared/cache.ts
|
|
767
|
+
init_cjs_shims();
|
|
768
|
+
var MAX_SIZE = 500;
|
|
769
|
+
var TTL_MS = 3e5;
|
|
770
|
+
var cache = /* @__PURE__ */ new Map();
|
|
771
|
+
function cacheKey(sessionId, cwd, command) {
|
|
772
|
+
return `${sessionId}|${cwd}|${command}`;
|
|
773
|
+
}
|
|
774
|
+
function getCached(key) {
|
|
775
|
+
const entry = cache.get(key);
|
|
776
|
+
if (entry && Date.now() - entry.timestamp < TTL_MS) {
|
|
777
|
+
return entry.result;
|
|
778
|
+
}
|
|
779
|
+
if (entry) cache.delete(key);
|
|
780
|
+
return null;
|
|
781
|
+
}
|
|
782
|
+
function setCache(key, result) {
|
|
783
|
+
if (result.decision !== "Allow") return;
|
|
784
|
+
if (cache.size >= MAX_SIZE) {
|
|
785
|
+
const first = cache.keys().next().value;
|
|
786
|
+
if (first) cache.delete(first);
|
|
787
|
+
}
|
|
788
|
+
cache.set(key, { result, timestamp: Date.now() });
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// src/shared/storage/repository.ts
|
|
792
|
+
init_cjs_shims();
|
|
793
|
+
|
|
794
|
+
// src/shared/storage/db.ts
|
|
795
|
+
init_cjs_shims();
|
|
796
|
+
var storage = null;
|
|
797
|
+
function createStorage(opts) {
|
|
798
|
+
if (storage) return storage;
|
|
799
|
+
const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
|
|
800
|
+
if (backend === "json") {
|
|
801
|
+
const { JsonStorage: JsonStorage2 } = (init_json_storage(), __toCommonJS(json_storage_exports));
|
|
802
|
+
storage = new JsonStorage2(opts?.dataDir);
|
|
803
|
+
console.log("[AgentGate] Storage: JSON files");
|
|
804
|
+
} else {
|
|
805
|
+
try {
|
|
806
|
+
require.resolve("better-sqlite3");
|
|
807
|
+
} catch {
|
|
808
|
+
console.error(
|
|
809
|
+
"[AgentGate] better-sqlite3 is not installed. Set AGENT_GATE_STORAGE=json or install better-sqlite3."
|
|
810
|
+
);
|
|
811
|
+
process.exit(1);
|
|
812
|
+
}
|
|
813
|
+
const { SqliteStorage: SqliteStorage2 } = (init_sqlite_storage(), __toCommonJS(sqlite_storage_exports));
|
|
814
|
+
storage = new SqliteStorage2(opts?.dbPath);
|
|
815
|
+
console.log("[AgentGate] Storage: SQLite");
|
|
816
|
+
}
|
|
817
|
+
return storage;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// src/shared/storage/repository.ts
|
|
821
|
+
function store() {
|
|
822
|
+
return createStorage();
|
|
823
|
+
}
|
|
824
|
+
function getOrCreateAgent(agentType, hostname, version2) {
|
|
825
|
+
return store().getOrCreateAgent(agentType, hostname, version2);
|
|
826
|
+
}
|
|
827
|
+
function getOrCreateSession(sessionId, agentId, cwd, prompt, osType) {
|
|
828
|
+
store().getOrCreateSession(sessionId, agentId, cwd, prompt, osType);
|
|
829
|
+
}
|
|
830
|
+
function getNextSeq(sessionId) {
|
|
831
|
+
return store().getNextSeq(sessionId);
|
|
832
|
+
}
|
|
833
|
+
function insertToolCall(record) {
|
|
834
|
+
return store().insertToolCall(record);
|
|
835
|
+
}
|
|
836
|
+
function queryToolCalls(params) {
|
|
837
|
+
return store().queryToolCalls(params);
|
|
838
|
+
}
|
|
839
|
+
function countToolCalls(params) {
|
|
840
|
+
return store().countToolCalls(params);
|
|
841
|
+
}
|
|
842
|
+
function getAgentsList() {
|
|
843
|
+
return store().getAgentsList();
|
|
844
|
+
}
|
|
845
|
+
function getTimeline(limit) {
|
|
846
|
+
return store().getTimeline(limit);
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
// src/v1/routes.ts
|
|
850
|
+
async function healthRoute(c) {
|
|
851
|
+
const mossHealth = await fetchMossHealth();
|
|
852
|
+
return c.json({
|
|
853
|
+
status: "healthy",
|
|
854
|
+
version,
|
|
855
|
+
moss_version: mossHealth.moss_version,
|
|
856
|
+
moss_status: mossHealth.moss_status
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
async function analyzeRoute(c) {
|
|
860
|
+
const t0 = performance.now();
|
|
861
|
+
try {
|
|
862
|
+
const body = await c.req.json();
|
|
863
|
+
const input = AgentGateInputSchema.parse(body);
|
|
864
|
+
const toolName = input.tool_name || input.a_next?.action_type || "unknown";
|
|
865
|
+
const command = input.command || input.a_next?.action_detail || "";
|
|
866
|
+
const key = cacheKey(input.session_id, input.cwd, command);
|
|
867
|
+
const cached = getCached(key);
|
|
868
|
+
if (cached) {
|
|
869
|
+
return c.json({
|
|
870
|
+
...cached,
|
|
871
|
+
analysis_duration_ms: 0,
|
|
872
|
+
collected_context: {}
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
const context = await collectSystemContext();
|
|
876
|
+
const mossRequest = normalize(input, context);
|
|
877
|
+
const hostname = context.os?.hostname || "unknown";
|
|
878
|
+
const agentId = getOrCreateAgent(input.agent_type, hostname, input.agent_version);
|
|
879
|
+
getOrCreateSession(input.session_id, agentId, input.cwd, input.user_prompt, String(context.os?.system || ""));
|
|
880
|
+
const mossResult = await callAgentMoss(mossRequest);
|
|
881
|
+
insertToolCall({
|
|
882
|
+
session_id: input.session_id,
|
|
883
|
+
seq: getNextSeq(input.session_id),
|
|
884
|
+
tool_name: toolName,
|
|
885
|
+
command,
|
|
886
|
+
description: input.description,
|
|
887
|
+
cwd: input.cwd,
|
|
888
|
+
action_type: toolName,
|
|
889
|
+
action_detail: command,
|
|
890
|
+
decision: mossResult.decision,
|
|
891
|
+
risk_level: mossResult.risk_level,
|
|
892
|
+
risk_type: mossResult.risk_type,
|
|
893
|
+
violated_layers: JSON.stringify(mossResult.violated_layers),
|
|
894
|
+
reason: mossResult.reason,
|
|
895
|
+
confidence: mossResult.confidence,
|
|
896
|
+
analysis_duration_ms: performance.now() - t0
|
|
897
|
+
});
|
|
898
|
+
setCache(key, mossResult);
|
|
899
|
+
const durationMs = performance.now() - t0;
|
|
900
|
+
return c.json(
|
|
901
|
+
AgentGateResponseSchema.parse({
|
|
902
|
+
decision: mossResult.decision,
|
|
903
|
+
reason: mossResult.reason,
|
|
904
|
+
risk_level: mossResult.risk_level,
|
|
905
|
+
risk_type: mossResult.risk_type,
|
|
906
|
+
violated_layers: mossResult.violated_layers,
|
|
907
|
+
confidence: mossResult.confidence,
|
|
908
|
+
analysis_duration_ms: Math.round(durationMs * 10) / 10,
|
|
909
|
+
collected_context: {
|
|
910
|
+
os: context.os,
|
|
911
|
+
process: context.process,
|
|
912
|
+
user: context.user
|
|
913
|
+
}
|
|
914
|
+
})
|
|
915
|
+
);
|
|
916
|
+
} catch (err) {
|
|
917
|
+
console.error("[AgentGate] Error:", err);
|
|
918
|
+
return c.json({ error: "Internal error", detail: String(err) }, 500);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
async function sessionsRoute(c) {
|
|
922
|
+
const sessionId = c.req.param("id");
|
|
923
|
+
const rows = queryToolCalls({ sessionId, limit: 100 });
|
|
924
|
+
return c.json({ session_id: sessionId, tool_calls: rows });
|
|
925
|
+
}
|
|
926
|
+
async function toolCallsRoute(c) {
|
|
927
|
+
const decision = c.req.query("decision");
|
|
928
|
+
const limit = parseInt(c.req.query("limit") || "50", 10);
|
|
929
|
+
const offset = parseInt(c.req.query("offset") || "0", 10);
|
|
930
|
+
const total = countToolCalls({ decision });
|
|
931
|
+
const data = queryToolCalls({ decision, limit, offset });
|
|
932
|
+
return c.json({ total, data });
|
|
933
|
+
}
|
|
934
|
+
async function agentsRoute(c) {
|
|
935
|
+
const agents = getAgentsList();
|
|
936
|
+
return c.json(agents);
|
|
937
|
+
}
|
|
938
|
+
async function timelineRoute(c) {
|
|
939
|
+
const limit = parseInt(c.req.query("limit") || "100", 10);
|
|
940
|
+
const rows = getTimeline(limit);
|
|
941
|
+
return c.json(rows);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
// src/v1/server.ts
|
|
945
|
+
function createApp() {
|
|
946
|
+
const app = new import_hono.Hono();
|
|
947
|
+
app.use("*", (0, import_cors.cors)({ origin: "*", allowMethods: ["GET", "POST", "OPTIONS"], allowHeaders: ["*"] }));
|
|
948
|
+
app.use("*", (0, import_logger.logger)());
|
|
949
|
+
app.get("/api/v1/health", healthRoute);
|
|
950
|
+
app.post("/api/v1/analyze", analyzeRoute);
|
|
951
|
+
app.get("/api/v1/sessions/:id/traces", sessionsRoute);
|
|
952
|
+
app.get("/api/v1/tool_calls", toolCallsRoute);
|
|
953
|
+
app.get("/api/v1/agents", agentsRoute);
|
|
954
|
+
app.get("/api/v1/timeline", timelineRoute);
|
|
955
|
+
app.get("/dashboard/", dashboardRoute);
|
|
956
|
+
app.get("/dashboard", (c) => c.redirect("/dashboard/"));
|
|
957
|
+
return app;
|
|
958
|
+
}
|
|
959
|
+
async function dashboardRoute(c) {
|
|
960
|
+
const { readFileSync: readFileSync2, existsSync: existsSync3 } = await import("fs");
|
|
961
|
+
const { resolve, dirname: dirname3 } = await import("path");
|
|
962
|
+
const { fileURLToPath } = await import("url");
|
|
963
|
+
const __dirname = dirname3(fileURLToPath(importMetaUrl));
|
|
964
|
+
const paths = [
|
|
965
|
+
resolve(__dirname, "dashboard.html"),
|
|
966
|
+
resolve(__dirname, "../dashboard.html"),
|
|
967
|
+
resolve(__dirname, "../src/v1/dashboard.html")
|
|
968
|
+
];
|
|
969
|
+
const htmlPath = paths.find((p) => existsSync3(p)) || paths[0];
|
|
970
|
+
const html = readFileSync2(htmlPath, "utf-8");
|
|
971
|
+
return c.html(html);
|
|
972
|
+
}
|
|
973
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
974
|
+
0 && (module.exports = {
|
|
975
|
+
createApp
|
|
976
|
+
});
|
|
977
|
+
//# sourceMappingURL=server.js.map
|