@kenhkl/agent-gate 0.5.7 → 0.6.1
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 +1154 -0
- package/dist/v1/cli.js.map +1 -0
- package/dist/v1/server.d.ts +5 -0
- package/dist/v1/server.js +982 -0
- package/dist/v1/server.js.map +1 -0
- package/dist/v3/cli.d.ts +1 -0
- package/dist/{cli.js → v3/cli.js} +13 -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,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* StorageAdapter — 统一存储接口。
|
|
3
|
+
*
|
|
4
|
+
* SQLite 和 JSON 文件存储各自实现此接口,
|
|
5
|
+
* 通过 AGENT_GATE_STORAGE 环境变量选择后端。
|
|
6
|
+
*/
|
|
7
|
+
interface ToolCallRecord {
|
|
8
|
+
session_id: string;
|
|
9
|
+
seq: number;
|
|
10
|
+
tool_name: string;
|
|
11
|
+
command: string;
|
|
12
|
+
description: string;
|
|
13
|
+
cwd: string;
|
|
14
|
+
action_type: string;
|
|
15
|
+
action_detail: string;
|
|
16
|
+
decision: string;
|
|
17
|
+
risk_level: string;
|
|
18
|
+
risk_type: string;
|
|
19
|
+
violated_layers: string;
|
|
20
|
+
reason: string;
|
|
21
|
+
confidence: number;
|
|
22
|
+
analysis_duration_ms: number;
|
|
23
|
+
}
|
|
24
|
+
interface ToolCallRich extends ToolCallRecord {
|
|
25
|
+
id: number;
|
|
26
|
+
called_at: string;
|
|
27
|
+
agent_type: string;
|
|
28
|
+
agent_version: string;
|
|
29
|
+
hostname: string;
|
|
30
|
+
}
|
|
31
|
+
interface AgentSummary {
|
|
32
|
+
agent_type: string;
|
|
33
|
+
hostname: string;
|
|
34
|
+
version: string;
|
|
35
|
+
session_count: number;
|
|
36
|
+
call_count: number;
|
|
37
|
+
}
|
|
38
|
+
interface TimelineEntry {
|
|
39
|
+
time: string;
|
|
40
|
+
allow: number;
|
|
41
|
+
deny: number;
|
|
42
|
+
}
|
|
43
|
+
interface ActionEntry {
|
|
44
|
+
action_type: string;
|
|
45
|
+
action_detail: string;
|
|
46
|
+
}
|
|
47
|
+
interface StorageAdapter {
|
|
48
|
+
getOrCreateAgent(agentType: string, hostname: string, version?: string): string;
|
|
49
|
+
getOrCreateSession(sessionId: string, agentId: string, cwd?: string, prompt?: string, osType?: string): void;
|
|
50
|
+
getNextSeq(sessionId: string): number;
|
|
51
|
+
insertToolCall(record: ToolCallRecord): number;
|
|
52
|
+
getActionHistory(sessionId: string, limit?: number): ActionEntry[];
|
|
53
|
+
queryToolCalls(params: {
|
|
54
|
+
sessionId?: string;
|
|
55
|
+
decision?: string;
|
|
56
|
+
limit?: number;
|
|
57
|
+
offset?: number;
|
|
58
|
+
}): ToolCallRich[];
|
|
59
|
+
countToolCalls(params: {
|
|
60
|
+
decision?: string;
|
|
61
|
+
}): number;
|
|
62
|
+
getAgentsList(): AgentSummary[];
|
|
63
|
+
getTimeline(limit?: number): TimelineEntry[];
|
|
64
|
+
close(): void;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 存储工厂 — 根据 AGENT_GATE_STORAGE 环境变量选择 SQLite 或 JSON 后端。
|
|
69
|
+
*
|
|
70
|
+
* 环境变量:
|
|
71
|
+
* AGENT_GATE_STORAGE=sqlite|json (默认 sqlite)
|
|
72
|
+
* AGENT_GATE_DATA_DIR=<path> JSON 模式的数据目录
|
|
73
|
+
*
|
|
74
|
+
* 为保持向后兼容,getDb()/closeDb() 仍然保留(proxy/gateway 子命令直接使用)。
|
|
75
|
+
*/
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 创建并返回全局 StorageAdapter 单例。
|
|
79
|
+
* 由 repository.ts 在首次调用时触发。
|
|
80
|
+
*/
|
|
81
|
+
declare function createStorage(opts?: {
|
|
82
|
+
dbPath?: string;
|
|
83
|
+
dataDir?: string;
|
|
84
|
+
}): StorageAdapter;
|
|
85
|
+
/**
|
|
86
|
+
* 获取当前 StorageAdapter(不创建新的,用于已初始化后的访问)。
|
|
87
|
+
*/
|
|
88
|
+
declare function getStorage(): StorageAdapter | null;
|
|
89
|
+
/**
|
|
90
|
+
* 获取原始 better-sqlite3 Database 实例(仅 SQLite 模式)。
|
|
91
|
+
* proxy/gateway 子命令需要直接操作 DB(如 initProxySchema)。
|
|
92
|
+
*/
|
|
93
|
+
declare function getDb(dbPath?: string): any;
|
|
94
|
+
declare function closeDb(): void;
|
|
95
|
+
|
|
96
|
+
export { closeDb, createStorage, getDb, getStorage };
|
|
@@ -0,0 +1,602 @@
|
|
|
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 init_cjs_shims = __esm({
|
|
35
|
+
"node_modules/tsup/assets/cjs_shims.js"() {
|
|
36
|
+
"use strict";
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// src/shared/storage/json-storage.ts
|
|
41
|
+
var json_storage_exports = {};
|
|
42
|
+
__export(json_storage_exports, {
|
|
43
|
+
JsonStorage: () => JsonStorage
|
|
44
|
+
});
|
|
45
|
+
function nowISO() {
|
|
46
|
+
return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace(/\.\d+Z$/, "");
|
|
47
|
+
}
|
|
48
|
+
function getDefaultDataDir() {
|
|
49
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
50
|
+
const xdgData = process.env.XDG_DATA_HOME || (0, import_path.join)(home, ".local", "share");
|
|
51
|
+
return (0, import_path.join)(xdgData, "agent_gate", "storage");
|
|
52
|
+
}
|
|
53
|
+
var import_fs, import_path, JsonStorage;
|
|
54
|
+
var init_json_storage = __esm({
|
|
55
|
+
"src/shared/storage/json-storage.ts"() {
|
|
56
|
+
"use strict";
|
|
57
|
+
init_cjs_shims();
|
|
58
|
+
import_fs = require("fs");
|
|
59
|
+
import_path = require("path");
|
|
60
|
+
JsonStorage = class {
|
|
61
|
+
dataDir;
|
|
62
|
+
agentsPath;
|
|
63
|
+
sessionsPath;
|
|
64
|
+
toolCallsDir;
|
|
65
|
+
nextId;
|
|
66
|
+
/** per-session 互斥锁,保证同一 session 的 seq 生成 + 写入原子性 */
|
|
67
|
+
sessionLocks = /* @__PURE__ */ new Map();
|
|
68
|
+
constructor(dataDir) {
|
|
69
|
+
this.dataDir = dataDir || process.env.AGENT_GATE_DATA_DIR || getDefaultDataDir();
|
|
70
|
+
this.agentsPath = (0, import_path.join)(this.dataDir, "agents.json");
|
|
71
|
+
this.sessionsPath = (0, import_path.join)(this.dataDir, "sessions.json");
|
|
72
|
+
this.toolCallsDir = (0, import_path.join)(this.dataDir, "tool_calls");
|
|
73
|
+
if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true });
|
|
74
|
+
if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true });
|
|
75
|
+
this.nextId = this.recoverNextId();
|
|
76
|
+
}
|
|
77
|
+
/** 扫描所有 tool_calls 文件,找到最大 id + 1 */
|
|
78
|
+
recoverNextId() {
|
|
79
|
+
let maxId = 0;
|
|
80
|
+
try {
|
|
81
|
+
const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
82
|
+
for (const file of files) {
|
|
83
|
+
const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
|
|
84
|
+
for (const r of records) {
|
|
85
|
+
if (r.id > maxId) maxId = r.id;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
} catch {
|
|
89
|
+
}
|
|
90
|
+
return maxId + 1;
|
|
91
|
+
}
|
|
92
|
+
readJsonFile(path, fallback) {
|
|
93
|
+
try {
|
|
94
|
+
if (!(0, import_fs.existsSync)(path)) return fallback;
|
|
95
|
+
return JSON.parse((0, import_fs.readFileSync)(path, "utf-8"));
|
|
96
|
+
} catch {
|
|
97
|
+
return fallback;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** 原子写入:先写 .tmp 再 rename */
|
|
101
|
+
writeJsonFile(path, data) {
|
|
102
|
+
const dir = (0, import_path.dirname)(path);
|
|
103
|
+
if (!(0, import_fs.existsSync)(dir)) (0, import_fs.mkdirSync)(dir, { recursive: true });
|
|
104
|
+
const tmp = path + ".tmp";
|
|
105
|
+
(0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), "utf-8");
|
|
106
|
+
(0, import_fs.renameSync)(tmp, path);
|
|
107
|
+
}
|
|
108
|
+
loadAgents() {
|
|
109
|
+
const raw = this.readJsonFile(this.agentsPath, {});
|
|
110
|
+
return new Map(Object.entries(raw));
|
|
111
|
+
}
|
|
112
|
+
saveAgents(agents) {
|
|
113
|
+
this.writeJsonFile(this.agentsPath, Object.fromEntries(agents));
|
|
114
|
+
}
|
|
115
|
+
loadSessions() {
|
|
116
|
+
const raw = this.readJsonFile(this.sessionsPath, {});
|
|
117
|
+
return new Map(Object.entries(raw));
|
|
118
|
+
}
|
|
119
|
+
saveSessions(sessions) {
|
|
120
|
+
this.writeJsonFile(this.sessionsPath, Object.fromEntries(sessions));
|
|
121
|
+
}
|
|
122
|
+
loadToolCalls(sessionId) {
|
|
123
|
+
return this.readJsonFile(
|
|
124
|
+
(0, import_path.join)(this.toolCallsDir, `${sessionId}.json`),
|
|
125
|
+
[]
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
saveToolCalls(sessionId, records) {
|
|
129
|
+
this.writeJsonFile((0, import_path.join)(this.toolCallsDir, `${sessionId}.json`), records);
|
|
130
|
+
}
|
|
131
|
+
getOrCreateAgent(agentType, hostname, version = "") {
|
|
132
|
+
const agents = this.loadAgents();
|
|
133
|
+
const id = `${agentType}:${hostname}`;
|
|
134
|
+
const existing = agents.get(id);
|
|
135
|
+
if (existing) {
|
|
136
|
+
existing.last_seen_at = nowISO();
|
|
137
|
+
if (version) existing.agent_version = version;
|
|
138
|
+
} else {
|
|
139
|
+
agents.set(id, {
|
|
140
|
+
id,
|
|
141
|
+
agent_type: agentType,
|
|
142
|
+
agent_version: version,
|
|
143
|
+
hostname,
|
|
144
|
+
registered_at: nowISO(),
|
|
145
|
+
last_seen_at: nowISO()
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
this.saveAgents(agents);
|
|
149
|
+
return id;
|
|
150
|
+
}
|
|
151
|
+
getOrCreateSession(sessionId, agentId, cwd = "", prompt = "", osType = "") {
|
|
152
|
+
const sessions = this.loadSessions();
|
|
153
|
+
if (!sessions.has(sessionId)) {
|
|
154
|
+
sessions.set(sessionId, {
|
|
155
|
+
id: sessionId,
|
|
156
|
+
agent_id: agentId,
|
|
157
|
+
cwd,
|
|
158
|
+
user_prompt: prompt,
|
|
159
|
+
os_type: osType,
|
|
160
|
+
status: "active",
|
|
161
|
+
created_at: nowISO(),
|
|
162
|
+
ended_at: null,
|
|
163
|
+
tool_call_count: 0
|
|
164
|
+
});
|
|
165
|
+
this.saveSessions(sessions);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
getNextSeq(sessionId) {
|
|
169
|
+
const records = this.loadToolCalls(sessionId);
|
|
170
|
+
if (records.length === 0) return 1;
|
|
171
|
+
return Math.max(...records.map((r) => r.seq)) + 1;
|
|
172
|
+
}
|
|
173
|
+
insertToolCall(record) {
|
|
174
|
+
const sessionId = record.session_id;
|
|
175
|
+
const prev = this.sessionLocks.get(sessionId) ?? Promise.resolve();
|
|
176
|
+
const next = prev.then(() => {
|
|
177
|
+
const records = this.loadToolCalls(sessionId);
|
|
178
|
+
const existingSeq = records.length === 0 ? 0 : Math.max(...records.map((r) => r.seq));
|
|
179
|
+
record.seq = existingSeq + 1;
|
|
180
|
+
const id = this.nextId++;
|
|
181
|
+
records.push({ ...record, id, called_at: nowISO() });
|
|
182
|
+
this.saveToolCalls(sessionId, records);
|
|
183
|
+
return id;
|
|
184
|
+
});
|
|
185
|
+
this.sessionLocks.set(sessionId, next.catch(() => {
|
|
186
|
+
}));
|
|
187
|
+
const cleanup = () => {
|
|
188
|
+
if (this.sessionLocks.get(sessionId) === next) {
|
|
189
|
+
this.sessionLocks.delete(sessionId);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
next.then(cleanup, cleanup);
|
|
193
|
+
return 0;
|
|
194
|
+
}
|
|
195
|
+
getActionHistory(sessionId, limit = 100) {
|
|
196
|
+
const records = this.loadToolCalls(sessionId);
|
|
197
|
+
const sorted = [...records].sort((a, b) => a.seq - b.seq);
|
|
198
|
+
const slice = sorted.slice(-limit);
|
|
199
|
+
return slice.map((r) => ({ action_type: r.action_type, action_detail: r.action_detail }));
|
|
200
|
+
}
|
|
201
|
+
queryToolCalls(params) {
|
|
202
|
+
const sessions = this.loadSessions();
|
|
203
|
+
const agents = this.loadAgents();
|
|
204
|
+
let allRecords = [];
|
|
205
|
+
if (params.sessionId) {
|
|
206
|
+
const records = this.loadToolCalls(params.sessionId);
|
|
207
|
+
allRecords = records.map((r) => this.enrichRecord(r, sessions, agents));
|
|
208
|
+
} else {
|
|
209
|
+
try {
|
|
210
|
+
const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
211
|
+
for (const file of files) {
|
|
212
|
+
const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
|
|
213
|
+
allRecords.push(...records.map((r) => this.enrichRecord(r, sessions, agents)));
|
|
214
|
+
}
|
|
215
|
+
} catch {
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (params.decision) {
|
|
219
|
+
allRecords = allRecords.filter((r) => r.decision === params.decision);
|
|
220
|
+
}
|
|
221
|
+
allRecords.sort((a, b) => b.called_at.localeCompare(a.called_at));
|
|
222
|
+
const offset = params.offset || 0;
|
|
223
|
+
const limit = params.limit || 50;
|
|
224
|
+
return allRecords.slice(offset, offset + limit);
|
|
225
|
+
}
|
|
226
|
+
countToolCalls(params) {
|
|
227
|
+
const sessions = this.loadSessions();
|
|
228
|
+
let allRecords = [];
|
|
229
|
+
try {
|
|
230
|
+
const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
231
|
+
for (const file of files) {
|
|
232
|
+
const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
|
|
233
|
+
allRecords.push(...records);
|
|
234
|
+
}
|
|
235
|
+
} catch {
|
|
236
|
+
}
|
|
237
|
+
if (params.decision) {
|
|
238
|
+
allRecords = allRecords.filter((r) => r.decision === params.decision);
|
|
239
|
+
}
|
|
240
|
+
return allRecords.length;
|
|
241
|
+
}
|
|
242
|
+
enrichRecord(record, sessions, agents) {
|
|
243
|
+
const session = sessions.get(record.session_id);
|
|
244
|
+
const agentId = session?.agent_id;
|
|
245
|
+
const agent = agentId ? agents.get(agentId) : void 0;
|
|
246
|
+
return {
|
|
247
|
+
...record,
|
|
248
|
+
agent_type: agent?.agent_type || "",
|
|
249
|
+
agent_version: agent?.agent_version || "",
|
|
250
|
+
hostname: agent?.hostname || ""
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
getAgentsList() {
|
|
254
|
+
const agents = this.loadAgents();
|
|
255
|
+
const sessions = this.loadSessions();
|
|
256
|
+
const result = [];
|
|
257
|
+
for (const agent of agents.values()) {
|
|
258
|
+
let sessionCount = 0;
|
|
259
|
+
let callCount = 0;
|
|
260
|
+
for (const session of sessions.values()) {
|
|
261
|
+
if (session.agent_id === agent.id) {
|
|
262
|
+
sessionCount++;
|
|
263
|
+
const records = this.loadToolCalls(session.id);
|
|
264
|
+
callCount += records.length;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
result.push({
|
|
268
|
+
agent_type: agent.agent_type,
|
|
269
|
+
hostname: agent.hostname,
|
|
270
|
+
version: agent.agent_version,
|
|
271
|
+
session_count: sessionCount,
|
|
272
|
+
call_count: callCount
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
result.sort((a, b) => b.call_count - a.call_count);
|
|
276
|
+
return result.slice(0, 20);
|
|
277
|
+
}
|
|
278
|
+
getTimeline(limit = 100) {
|
|
279
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
280
|
+
try {
|
|
281
|
+
const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
282
|
+
for (const file of files) {
|
|
283
|
+
const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
|
|
284
|
+
for (const r of records) {
|
|
285
|
+
const minute = r.called_at.replace(/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}):\d{2}/, "$1T$2");
|
|
286
|
+
const bucket = buckets.get(minute) || { allow: 0, deny: 0 };
|
|
287
|
+
if (r.decision === "Allow") bucket.allow++;
|
|
288
|
+
else bucket.deny++;
|
|
289
|
+
buckets.set(minute, bucket);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
} catch {
|
|
293
|
+
}
|
|
294
|
+
const result = [];
|
|
295
|
+
for (const [time, counts] of buckets) {
|
|
296
|
+
result.push({ time, ...counts });
|
|
297
|
+
}
|
|
298
|
+
result.sort((a, b) => b.time.localeCompare(a.time));
|
|
299
|
+
return result.slice(0, limit);
|
|
300
|
+
}
|
|
301
|
+
close() {
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
// src/shared/storage/sqlite-storage.ts
|
|
308
|
+
var sqlite_storage_exports = {};
|
|
309
|
+
__export(sqlite_storage_exports, {
|
|
310
|
+
SqliteStorage: () => SqliteStorage
|
|
311
|
+
});
|
|
312
|
+
function getDefaultDbPath() {
|
|
313
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
314
|
+
const xdgData = process.env.XDG_DATA_HOME || (0, import_path2.join)(home, ".local", "share");
|
|
315
|
+
return (0, import_path2.join)(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
316
|
+
}
|
|
317
|
+
var import_fs2, import_path2, SCHEMA, SqliteStorage;
|
|
318
|
+
var init_sqlite_storage = __esm({
|
|
319
|
+
"src/shared/storage/sqlite-storage.ts"() {
|
|
320
|
+
"use strict";
|
|
321
|
+
init_cjs_shims();
|
|
322
|
+
import_fs2 = require("fs");
|
|
323
|
+
import_path2 = require("path");
|
|
324
|
+
SCHEMA = `
|
|
325
|
+
CREATE TABLE IF NOT EXISTS agents (
|
|
326
|
+
id TEXT PRIMARY KEY,
|
|
327
|
+
agent_type TEXT NOT NULL,
|
|
328
|
+
agent_version TEXT DEFAULT '',
|
|
329
|
+
hostname TEXT NOT NULL,
|
|
330
|
+
registered_at TEXT DEFAULT (datetime('now')),
|
|
331
|
+
last_seen_at TEXT DEFAULT (datetime('now'))
|
|
332
|
+
);
|
|
333
|
+
|
|
334
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
335
|
+
id TEXT PRIMARY KEY,
|
|
336
|
+
agent_id TEXT NOT NULL REFERENCES agents(id),
|
|
337
|
+
cwd TEXT DEFAULT '',
|
|
338
|
+
user_prompt TEXT DEFAULT '',
|
|
339
|
+
os_type TEXT DEFAULT '',
|
|
340
|
+
status TEXT DEFAULT 'active',
|
|
341
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
342
|
+
ended_at TEXT,
|
|
343
|
+
tool_call_count INTEGER DEFAULT 0
|
|
344
|
+
);
|
|
345
|
+
|
|
346
|
+
CREATE TABLE IF NOT EXISTS tool_calls (
|
|
347
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
348
|
+
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
349
|
+
seq INTEGER NOT NULL,
|
|
350
|
+
tool_name TEXT NOT NULL,
|
|
351
|
+
command TEXT NOT NULL,
|
|
352
|
+
description TEXT DEFAULT '',
|
|
353
|
+
cwd TEXT DEFAULT '',
|
|
354
|
+
action_type TEXT NOT NULL,
|
|
355
|
+
action_detail TEXT NOT NULL,
|
|
356
|
+
decision TEXT NOT NULL,
|
|
357
|
+
risk_level TEXT DEFAULT '',
|
|
358
|
+
risk_type TEXT DEFAULT '',
|
|
359
|
+
violated_layers TEXT DEFAULT '[]',
|
|
360
|
+
reason TEXT DEFAULT '',
|
|
361
|
+
confidence INTEGER DEFAULT 0,
|
|
362
|
+
analysis_duration_ms REAL DEFAULT 0,
|
|
363
|
+
called_at TEXT DEFAULT (datetime('now')),
|
|
364
|
+
UNIQUE(session_id, seq)
|
|
365
|
+
);
|
|
366
|
+
|
|
367
|
+
CREATE INDEX IF NOT EXISTS idx_tool_calls_session_seq ON tool_calls(session_id, seq);
|
|
368
|
+
CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, called_at);
|
|
369
|
+
`;
|
|
370
|
+
SqliteStorage = class {
|
|
371
|
+
db;
|
|
372
|
+
constructor(dbPath) {
|
|
373
|
+
let Database;
|
|
374
|
+
try {
|
|
375
|
+
Database = require("better-sqlite3");
|
|
376
|
+
} catch {
|
|
377
|
+
throw new Error(
|
|
378
|
+
"better-sqlite3 is not installed. Use AGENT_GATE_STORAGE=json for environments without native modules."
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
const path = dbPath || getDefaultDbPath();
|
|
382
|
+
const dir = (0, import_path2.dirname)(path);
|
|
383
|
+
if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true });
|
|
384
|
+
this.db = new Database(path);
|
|
385
|
+
this.db.pragma("journal_mode = WAL");
|
|
386
|
+
this.db.exec(SCHEMA);
|
|
387
|
+
}
|
|
388
|
+
static isAvailable() {
|
|
389
|
+
try {
|
|
390
|
+
require.resolve("better-sqlite3");
|
|
391
|
+
return true;
|
|
392
|
+
} catch {
|
|
393
|
+
return false;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
getOrCreateAgent(agentType, hostname, version = "") {
|
|
397
|
+
const id = `${agentType}:${hostname}`;
|
|
398
|
+
this.db.prepare(
|
|
399
|
+
"INSERT OR IGNORE INTO agents (id, agent_type, agent_version, hostname) VALUES (?, ?, ?, ?)"
|
|
400
|
+
).run(id, agentType, version, hostname);
|
|
401
|
+
this.db.prepare("UPDATE agents SET last_seen_at = datetime('now') WHERE id = ?").run(id);
|
|
402
|
+
return id;
|
|
403
|
+
}
|
|
404
|
+
getOrCreateSession(sessionId, agentId, cwd = "", prompt = "", osType = "") {
|
|
405
|
+
this.db.prepare(
|
|
406
|
+
"INSERT OR IGNORE INTO sessions (id, agent_id, cwd, user_prompt, os_type) VALUES (?, ?, ?, ?, ?)"
|
|
407
|
+
).run(sessionId, agentId, cwd, prompt, osType);
|
|
408
|
+
}
|
|
409
|
+
getNextSeq(sessionId) {
|
|
410
|
+
const row = this.db.prepare(
|
|
411
|
+
"SELECT COALESCE(MAX(seq), 0) + 1 as next FROM tool_calls WHERE session_id = ?"
|
|
412
|
+
).get(sessionId);
|
|
413
|
+
return row.next;
|
|
414
|
+
}
|
|
415
|
+
insertToolCall(record) {
|
|
416
|
+
const result = this.db.transaction((rec) => {
|
|
417
|
+
const row = this.db.prepare(
|
|
418
|
+
"SELECT COALESCE(MAX(seq), 0) + 1 as next FROM tool_calls WHERE session_id = ?"
|
|
419
|
+
).get(rec.session_id);
|
|
420
|
+
const seq = row.next;
|
|
421
|
+
return this.db.prepare(`
|
|
422
|
+
INSERT INTO tool_calls (session_id, seq, tool_name, command, description, cwd,
|
|
423
|
+
action_type, action_detail, decision, risk_level, risk_type, violated_layers,
|
|
424
|
+
reason, confidence, analysis_duration_ms)
|
|
425
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
426
|
+
`).run(
|
|
427
|
+
rec.session_id,
|
|
428
|
+
seq,
|
|
429
|
+
rec.tool_name,
|
|
430
|
+
rec.command,
|
|
431
|
+
rec.description,
|
|
432
|
+
rec.cwd,
|
|
433
|
+
rec.action_type,
|
|
434
|
+
rec.action_detail,
|
|
435
|
+
rec.decision,
|
|
436
|
+
rec.risk_level,
|
|
437
|
+
rec.risk_type,
|
|
438
|
+
rec.violated_layers,
|
|
439
|
+
rec.reason,
|
|
440
|
+
rec.confidence,
|
|
441
|
+
rec.analysis_duration_ms
|
|
442
|
+
);
|
|
443
|
+
})(record);
|
|
444
|
+
return Number(result.lastInsertRowid);
|
|
445
|
+
}
|
|
446
|
+
getActionHistory(sessionId, limit = 100) {
|
|
447
|
+
const rows = this.db.prepare(
|
|
448
|
+
"SELECT action_type, action_detail FROM tool_calls WHERE session_id = ? ORDER BY seq DESC LIMIT ?"
|
|
449
|
+
).all(sessionId, limit);
|
|
450
|
+
return rows.reverse();
|
|
451
|
+
}
|
|
452
|
+
queryToolCalls(params) {
|
|
453
|
+
const conditions = [];
|
|
454
|
+
const values = [];
|
|
455
|
+
if (params.sessionId) {
|
|
456
|
+
conditions.push("tc.session_id = ?");
|
|
457
|
+
values.push(params.sessionId);
|
|
458
|
+
}
|
|
459
|
+
if (params.decision) {
|
|
460
|
+
conditions.push("tc.decision = ?");
|
|
461
|
+
values.push(params.decision);
|
|
462
|
+
}
|
|
463
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
464
|
+
const limit = params.limit || 50;
|
|
465
|
+
const offset = params.offset || 0;
|
|
466
|
+
return this.db.prepare(
|
|
467
|
+
`SELECT tc.*, a.agent_type, a.agent_version, a.hostname
|
|
468
|
+
FROM tool_calls tc
|
|
469
|
+
LEFT JOIN sessions s ON tc.session_id = s.id
|
|
470
|
+
LEFT JOIN agents a ON s.agent_id = a.id
|
|
471
|
+
${where} ORDER BY tc.called_at DESC LIMIT ? OFFSET ?`
|
|
472
|
+
).all(...values, limit, offset);
|
|
473
|
+
}
|
|
474
|
+
countToolCalls(params) {
|
|
475
|
+
const conditions = [];
|
|
476
|
+
const values = [];
|
|
477
|
+
if (params.decision) {
|
|
478
|
+
conditions.push("tc.decision = ?");
|
|
479
|
+
values.push(params.decision);
|
|
480
|
+
}
|
|
481
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
482
|
+
const row = this.db.prepare(
|
|
483
|
+
`SELECT COUNT(*) as total FROM tool_calls tc ${where}`
|
|
484
|
+
).get(...values);
|
|
485
|
+
return row?.total ?? 0;
|
|
486
|
+
}
|
|
487
|
+
getAgentsList() {
|
|
488
|
+
return this.db.prepare(`
|
|
489
|
+
SELECT a.agent_type, a.hostname, a.agent_version as version,
|
|
490
|
+
COUNT(DISTINCT s.id) as session_count,
|
|
491
|
+
COUNT(tc.id) as call_count
|
|
492
|
+
FROM agents a
|
|
493
|
+
LEFT JOIN sessions s ON s.agent_id = a.id
|
|
494
|
+
LEFT JOIN tool_calls tc ON tc.session_id = s.id
|
|
495
|
+
GROUP BY a.id
|
|
496
|
+
ORDER BY call_count DESC
|
|
497
|
+
LIMIT 20
|
|
498
|
+
`).all();
|
|
499
|
+
}
|
|
500
|
+
getTimeline(limit = 100) {
|
|
501
|
+
const rows = this.db.prepare(`
|
|
502
|
+
SELECT strftime('%Y-%m-%dT%H:%M', called_at) as time,
|
|
503
|
+
SUM(CASE WHEN decision='Allow' THEN 1 ELSE 0 END) as allow,
|
|
504
|
+
SUM(CASE WHEN decision='Deny' THEN 1 ELSE 0 END) as deny
|
|
505
|
+
FROM tool_calls
|
|
506
|
+
GROUP BY strftime('%Y-%m-%dT%H:%M', called_at)
|
|
507
|
+
ORDER BY time DESC
|
|
508
|
+
LIMIT ?
|
|
509
|
+
`).all(limit);
|
|
510
|
+
return rows.map((r) => {
|
|
511
|
+
const d = /* @__PURE__ */ new Date(r.time + ":00Z");
|
|
512
|
+
const year = d.getFullYear();
|
|
513
|
+
const month = String(d.getMonth() + 1).padStart(2, "0");
|
|
514
|
+
const day = String(d.getDate()).padStart(2, "0");
|
|
515
|
+
const hours = String(d.getHours()).padStart(2, "0");
|
|
516
|
+
const minutes = String(d.getMinutes()).padStart(2, "0");
|
|
517
|
+
return { ...r, time: `${year}-${month}-${day}T${hours}:${minutes}` };
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
close() {
|
|
521
|
+
if (this.db) {
|
|
522
|
+
this.db.close();
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
// src/shared/storage/db.ts
|
|
530
|
+
var db_exports = {};
|
|
531
|
+
__export(db_exports, {
|
|
532
|
+
closeDb: () => closeDb,
|
|
533
|
+
createStorage: () => createStorage,
|
|
534
|
+
getDb: () => getDb,
|
|
535
|
+
getStorage: () => getStorage
|
|
536
|
+
});
|
|
537
|
+
module.exports = __toCommonJS(db_exports);
|
|
538
|
+
init_cjs_shims();
|
|
539
|
+
var storage = null;
|
|
540
|
+
var rawDb = null;
|
|
541
|
+
function createStorage(opts) {
|
|
542
|
+
if (storage) return storage;
|
|
543
|
+
const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
|
|
544
|
+
if (backend === "json") {
|
|
545
|
+
const { JsonStorage: JsonStorage2 } = (init_json_storage(), __toCommonJS(json_storage_exports));
|
|
546
|
+
storage = new JsonStorage2(opts?.dataDir);
|
|
547
|
+
console.log("[AgentGate] Storage: JSON files");
|
|
548
|
+
} else {
|
|
549
|
+
try {
|
|
550
|
+
require.resolve("better-sqlite3");
|
|
551
|
+
} catch {
|
|
552
|
+
console.error(
|
|
553
|
+
"[AgentGate] better-sqlite3 is not installed. Set AGENT_GATE_STORAGE=json or install better-sqlite3."
|
|
554
|
+
);
|
|
555
|
+
process.exit(1);
|
|
556
|
+
}
|
|
557
|
+
const { SqliteStorage: SqliteStorage2 } = (init_sqlite_storage(), __toCommonJS(sqlite_storage_exports));
|
|
558
|
+
storage = new SqliteStorage2(opts?.dbPath);
|
|
559
|
+
console.log("[AgentGate] Storage: SQLite");
|
|
560
|
+
}
|
|
561
|
+
return storage;
|
|
562
|
+
}
|
|
563
|
+
function getStorage() {
|
|
564
|
+
return storage;
|
|
565
|
+
}
|
|
566
|
+
function getDb(dbPath) {
|
|
567
|
+
if (rawDb) return rawDb;
|
|
568
|
+
try {
|
|
569
|
+
const Database = require("better-sqlite3");
|
|
570
|
+
const { existsSync: existsSync3, mkdirSync: mkdirSync3 } = require("fs");
|
|
571
|
+
const { join: join3, dirname: dirname3 } = require("path");
|
|
572
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
573
|
+
const xdgData = process.env.XDG_DATA_HOME || join3(home, ".local", "share");
|
|
574
|
+
const defaultPath = join3(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
575
|
+
const path = dbPath || defaultPath;
|
|
576
|
+
const dir = dirname3(path);
|
|
577
|
+
if (!existsSync3(dir)) mkdirSync3(dir, { recursive: true });
|
|
578
|
+
rawDb = new Database(path);
|
|
579
|
+
rawDb.pragma("journal_mode = WAL");
|
|
580
|
+
return rawDb;
|
|
581
|
+
} catch {
|
|
582
|
+
throw new Error("better-sqlite3 is not available. Use AGENT_GATE_STORAGE=json.");
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
function closeDb() {
|
|
586
|
+
if (storage) {
|
|
587
|
+
storage.close();
|
|
588
|
+
storage = null;
|
|
589
|
+
}
|
|
590
|
+
if (rawDb) {
|
|
591
|
+
rawDb.close();
|
|
592
|
+
rawDb = null;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
596
|
+
0 && (module.exports = {
|
|
597
|
+
closeDb,
|
|
598
|
+
createStorage,
|
|
599
|
+
getDb,
|
|
600
|
+
getStorage
|
|
601
|
+
});
|
|
602
|
+
//# sourceMappingURL=db.js.map
|