@kenhkl/agent-gate 0.9.6 → 0.9.10
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/dashboard.html +164 -6
- package/dist/shared/storage/db.d.ts +13 -0
- package/dist/shared/storage/db.js +36 -0
- package/dist/v1/cli.js +767 -60
- package/dist/v1/server.js +767 -60
- package/dist/v3/cli.js +28861 -28739
- package/package.json +1 -1
package/dist/v1/cli.js
CHANGED
|
@@ -319,18 +319,18 @@ function isGlobalToken(token) {
|
|
|
319
319
|
function boundAgentOf(principal) {
|
|
320
320
|
return principal.startsWith("agent:") ? principal.slice("agent:".length) : "";
|
|
321
321
|
}
|
|
322
|
-
function cookiePathAllowed(
|
|
323
|
-
if (
|
|
324
|
-
return
|
|
322
|
+
function cookiePathAllowed(path3) {
|
|
323
|
+
if (path3 === "/api/v1/analyze" || path3.startsWith("/api/v1/analyze/")) return false;
|
|
324
|
+
return path3 === "/dashboard" || path3.startsWith("/dashboard/") || path3.startsWith("/ws/") || path3.startsWith("/api/");
|
|
325
325
|
}
|
|
326
|
-
function checkRequestAuth(headers,
|
|
326
|
+
function checkRequestAuth(headers, path3, cookie = "", requireGlobal = false) {
|
|
327
327
|
if (authMode() === AUTH_MODE_OFF) return { ok: true, principal: "" };
|
|
328
|
-
const isHealth = PUBLIC_PATHS.includes(
|
|
328
|
+
const isHealth = PUBLIC_PATHS.includes(path3.replace(/\/+$/, ""));
|
|
329
329
|
const { token: globalTok, agents, error } = resolveAuth();
|
|
330
330
|
if (error) return { ok: isHealth, principal: "" };
|
|
331
331
|
if (!globalTok && Object.keys(agents).length === 0) return { ok: true, principal: "" };
|
|
332
332
|
if (isHealth) return { ok: true, principal: "" };
|
|
333
|
-
if (cookie && cookiePathAllowed(
|
|
333
|
+
if (cookie && cookiePathAllowed(path3) && checkToken(cookie)) {
|
|
334
334
|
const principal = principalOf(cookie);
|
|
335
335
|
if (requireGlobal && principal.startsWith("agent:")) {
|
|
336
336
|
return { ok: false, principal };
|
|
@@ -398,11 +398,11 @@ function keepAliveSec() {
|
|
|
398
398
|
function rateLimitQps() {
|
|
399
399
|
return envInt("AGENT_GATE_RATE_LIMIT_QPS", 100);
|
|
400
400
|
}
|
|
401
|
-
function poolOf(
|
|
402
|
-
if (
|
|
403
|
-
if (
|
|
404
|
-
if (
|
|
405
|
-
if (
|
|
401
|
+
function poolOf(path3) {
|
|
402
|
+
if (path3 === "/api/v1/analyze" || path3.startsWith("/api/v1/analyze/")) return "biz";
|
|
403
|
+
if (path3.startsWith("/api/v1/sessions") || path3.startsWith("/api/v1/agents") || path3.startsWith("/api/v1/tool_calls")) return "read";
|
|
404
|
+
if (path3 === "/dashboard" || path3.startsWith("/dashboard/") || path3.startsWith("/ws/")) return "ops";
|
|
405
|
+
if (path3 === "/api/v1/health") return "health";
|
|
406
406
|
return "other";
|
|
407
407
|
}
|
|
408
408
|
function poolLimit(name) {
|
|
@@ -746,21 +746,21 @@ var init_json_storage = __esm({
|
|
|
746
746
|
}
|
|
747
747
|
return maxId + 1;
|
|
748
748
|
}
|
|
749
|
-
readJsonFile(
|
|
749
|
+
readJsonFile(path3, fallback) {
|
|
750
750
|
try {
|
|
751
|
-
if (!(0, import_fs2.existsSync)(
|
|
752
|
-
return JSON.parse((0, import_fs2.readFileSync)(
|
|
751
|
+
if (!(0, import_fs2.existsSync)(path3)) return fallback;
|
|
752
|
+
return JSON.parse((0, import_fs2.readFileSync)(path3, "utf-8"));
|
|
753
753
|
} catch {
|
|
754
754
|
return fallback;
|
|
755
755
|
}
|
|
756
756
|
}
|
|
757
757
|
/** 原子写入:先写 .tmp 再 rename(rename 保留 tmp 的 0600 权限) */
|
|
758
|
-
writeJsonFile(
|
|
759
|
-
const dir = (0, import_path2.dirname)(
|
|
758
|
+
writeJsonFile(path3, data) {
|
|
759
|
+
const dir = (0, import_path2.dirname)(path3);
|
|
760
760
|
if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true, mode: 448 });
|
|
761
|
-
const tmp =
|
|
761
|
+
const tmp = path3 + ".tmp";
|
|
762
762
|
(0, import_fs2.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
|
|
763
|
-
(0, import_fs2.renameSync)(tmp,
|
|
763
|
+
(0, import_fs2.renameSync)(tmp, path3);
|
|
764
764
|
}
|
|
765
765
|
loadAgents() {
|
|
766
766
|
const raw = this.readJsonFile(this.agentsPath, {});
|
|
@@ -1006,15 +1006,15 @@ var init_json_storage = __esm({
|
|
|
1006
1006
|
const archiveCount = total - keep;
|
|
1007
1007
|
const toArchive = flat.slice(0, archiveCount);
|
|
1008
1008
|
const archiveIds = new Set(toArchive.map((x) => String(x.rec.id)));
|
|
1009
|
-
const { mkdirSync:
|
|
1010
|
-
const { join:
|
|
1009
|
+
const { mkdirSync: mkdirSync6, writeFileSync: writeFileSync5 } = require("fs");
|
|
1010
|
+
const { join: join6 } = require("path");
|
|
1011
1011
|
const { gzipSync } = require("zlib");
|
|
1012
|
-
const archiveDir =
|
|
1013
|
-
if (!(0, import_fs2.existsSync)(archiveDir))
|
|
1012
|
+
const archiveDir = join6(this.dataDir, "archive");
|
|
1013
|
+
if (!(0, import_fs2.existsSync)(archiveDir)) mkdirSync6(archiveDir, { recursive: true, mode: 448 });
|
|
1014
1014
|
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1015
|
-
const file =
|
|
1015
|
+
const file = join6(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1016
1016
|
const payload = toArchive.map((x) => JSON.stringify(x.rec)).join("\n") + "\n";
|
|
1017
|
-
|
|
1017
|
+
writeFileSync5(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1018
1018
|
for (const [sid, recs] of bySession) {
|
|
1019
1019
|
const remain = recs.filter((r) => !archiveIds.has(String(r.id)));
|
|
1020
1020
|
if (remain.length !== recs.length) this.saveToolCalls(sid, remain);
|
|
@@ -1055,6 +1055,21 @@ var init_json_storage = __esm({
|
|
|
1055
1055
|
if (!session) return void 0;
|
|
1056
1056
|
return this.loadAgents().get(session.agent_id)?.agent_type;
|
|
1057
1057
|
}
|
|
1058
|
+
getSessionInfo(sessionId) {
|
|
1059
|
+
const session = this.loadSessions().get(sessionId);
|
|
1060
|
+
if (!session) return void 0;
|
|
1061
|
+
const agent = this.loadAgents().get(session.agent_id);
|
|
1062
|
+
return {
|
|
1063
|
+
sessionId: session.id,
|
|
1064
|
+
agentType: agent?.agent_type ?? "",
|
|
1065
|
+
agentVersion: agent?.agent_version ?? "",
|
|
1066
|
+
status: session.status ?? "",
|
|
1067
|
+
cwd: session.cwd ?? "",
|
|
1068
|
+
userPrompt: session.user_prompt ?? "",
|
|
1069
|
+
createdAt: session.created_at ?? "",
|
|
1070
|
+
toolCallCount: Number(session.tool_call_count ?? 0)
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1058
1073
|
getTimeline(limit = 100) {
|
|
1059
1074
|
const buckets = /* @__PURE__ */ new Map();
|
|
1060
1075
|
try {
|
|
@@ -1161,11 +1176,11 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1161
1176
|
"better-sqlite3 is not installed. Use AGENT_GATE_STORAGE=json for environments without native modules."
|
|
1162
1177
|
);
|
|
1163
1178
|
}
|
|
1164
|
-
const
|
|
1165
|
-
const dir = (0, import_path3.dirname)(
|
|
1179
|
+
const path3 = dbPath || getDefaultDbPath();
|
|
1180
|
+
const dir = (0, import_path3.dirname)(path3);
|
|
1166
1181
|
if (!(0, import_fs3.existsSync)(dir)) (0, import_fs3.mkdirSync)(dir, { recursive: true });
|
|
1167
|
-
this.dbPath =
|
|
1168
|
-
this.db = new Database(
|
|
1182
|
+
this.dbPath = path3;
|
|
1183
|
+
this.db = new Database(path3);
|
|
1169
1184
|
this.db.pragma("journal_mode = WAL");
|
|
1170
1185
|
this.db.exec(SCHEMA);
|
|
1171
1186
|
this.ensureColumn("tool_calls", "violation_graph", "violation_graph TEXT DEFAULT '{}'");
|
|
@@ -1335,11 +1350,11 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1335
1350
|
const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
|
|
1336
1351
|
let dbBytes = 0;
|
|
1337
1352
|
try {
|
|
1338
|
-
const { statSync: statSync3, existsSync:
|
|
1353
|
+
const { statSync: statSync3, existsSync: existsSync5 } = require("fs");
|
|
1339
1354
|
dbBytes = statSync3(this.dbPath).size;
|
|
1340
1355
|
for (const suffix of ["-wal", "-shm"]) {
|
|
1341
1356
|
const p = this.dbPath + suffix;
|
|
1342
|
-
if (
|
|
1357
|
+
if (existsSync5(p)) dbBytes += statSync3(p).size;
|
|
1343
1358
|
}
|
|
1344
1359
|
} catch {
|
|
1345
1360
|
}
|
|
@@ -1372,15 +1387,15 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1372
1387
|
"SELECT * FROM tool_calls WHERE id <= ? ORDER BY id"
|
|
1373
1388
|
).all(cutoff.id);
|
|
1374
1389
|
if (rows.length === 0) return { archived: 0, file: "" };
|
|
1375
|
-
const { writeFileSync:
|
|
1376
|
-
const { dirname:
|
|
1390
|
+
const { writeFileSync: writeFileSync5, mkdirSync: mkdirSync6, existsSync: existsSync5 } = require("fs");
|
|
1391
|
+
const { dirname: dirname6, join: join6 } = require("path");
|
|
1377
1392
|
const { gzipSync } = require("zlib");
|
|
1378
|
-
const archiveDir =
|
|
1379
|
-
if (!
|
|
1393
|
+
const archiveDir = join6(dirname6(this.dbPath), "archive");
|
|
1394
|
+
if (!existsSync5(archiveDir)) mkdirSync6(archiveDir, { recursive: true, mode: 448 });
|
|
1380
1395
|
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1381
|
-
const file =
|
|
1396
|
+
const file = join6(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1382
1397
|
const payload = rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
|
|
1383
|
-
|
|
1398
|
+
writeFileSync5(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1384
1399
|
const deleted = this.db.transaction(() => {
|
|
1385
1400
|
const res = this.db.prepare("DELETE FROM tool_calls WHERE id <= ?").run(cutoff.id);
|
|
1386
1401
|
this.db.prepare(`
|
|
@@ -1419,6 +1434,27 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1419
1434
|
).get(sessionId);
|
|
1420
1435
|
return row?.agent_type;
|
|
1421
1436
|
}
|
|
1437
|
+
getSessionInfo(sessionId) {
|
|
1438
|
+
const row = this.db.prepare(
|
|
1439
|
+
`SELECT s.id as session_id, s.cwd, s.user_prompt, s.status, s.created_at,
|
|
1440
|
+
s.tool_call_count,
|
|
1441
|
+
COALESCE(a.agent_type, '') as agent_type,
|
|
1442
|
+
COALESCE(a.agent_version, '') as agent_version
|
|
1443
|
+
FROM sessions s LEFT JOIN agents a ON s.agent_id = a.id
|
|
1444
|
+
WHERE s.id = ?`
|
|
1445
|
+
).get(sessionId);
|
|
1446
|
+
if (!row) return void 0;
|
|
1447
|
+
return {
|
|
1448
|
+
sessionId: String(row.session_id ?? ""),
|
|
1449
|
+
agentType: String(row.agent_type ?? ""),
|
|
1450
|
+
agentVersion: String(row.agent_version ?? ""),
|
|
1451
|
+
status: String(row.status ?? ""),
|
|
1452
|
+
cwd: String(row.cwd ?? ""),
|
|
1453
|
+
userPrompt: String(row.user_prompt ?? ""),
|
|
1454
|
+
createdAt: String(row.created_at ?? ""),
|
|
1455
|
+
toolCallCount: Number(row.tool_call_count ?? 0)
|
|
1456
|
+
};
|
|
1457
|
+
}
|
|
1422
1458
|
getTimeline(limit = 100) {
|
|
1423
1459
|
const rows = this.db.prepare(`
|
|
1424
1460
|
SELECT strftime('%Y-%m-%dT%H:%M', called_at) as time,
|
|
@@ -1486,15 +1522,15 @@ function getDb(dbPath) {
|
|
|
1486
1522
|
if (rawDb) return rawDb;
|
|
1487
1523
|
try {
|
|
1488
1524
|
const Database = require("better-sqlite3");
|
|
1489
|
-
const { existsSync:
|
|
1490
|
-
const { join:
|
|
1525
|
+
const { existsSync: existsSync5, mkdirSync: mkdirSync6 } = require("fs");
|
|
1526
|
+
const { join: join6, dirname: dirname6 } = require("path");
|
|
1491
1527
|
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
1492
|
-
const xdgData = process.env.XDG_DATA_HOME ||
|
|
1493
|
-
const defaultPath =
|
|
1494
|
-
const
|
|
1495
|
-
const dir =
|
|
1496
|
-
if (!
|
|
1497
|
-
rawDb = new Database(
|
|
1528
|
+
const xdgData = process.env.XDG_DATA_HOME || join6(home, ".local", "share");
|
|
1529
|
+
const defaultPath = join6(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
1530
|
+
const path3 = dbPath || defaultPath;
|
|
1531
|
+
const dir = dirname6(path3);
|
|
1532
|
+
if (!existsSync5(dir)) mkdirSync6(dir, { recursive: true });
|
|
1533
|
+
rawDb = new Database(path3);
|
|
1498
1534
|
rawDb.pragma("journal_mode = WAL");
|
|
1499
1535
|
return rawDb;
|
|
1500
1536
|
} catch {
|
|
@@ -1767,7 +1803,7 @@ var init_version = __esm({
|
|
|
1767
1803
|
"src/version.ts"() {
|
|
1768
1804
|
"use strict";
|
|
1769
1805
|
init_cjs_shims();
|
|
1770
|
-
_version = true ? "0.9.
|
|
1806
|
+
_version = true ? "0.9.10" : (() => {
|
|
1771
1807
|
try {
|
|
1772
1808
|
const require2 = createRequire(importMetaUrl);
|
|
1773
1809
|
const pkg = require2("../package.json");
|
|
@@ -1844,6 +1880,10 @@ var init_models = __esm({
|
|
|
1844
1880
|
analysis_duration_ms: import_zod.z.number().default(0),
|
|
1845
1881
|
// 结构化攻击链图(组合式拦截时非空;前端弹窗画图用)
|
|
1846
1882
|
violation_graph: import_zod.z.any().nullable().optional(),
|
|
1883
|
+
/** 命中的策略/性质描述(与 Python 版响应字段对齐) */
|
|
1884
|
+
policy: import_zod.z.string().default(""),
|
|
1885
|
+
/** 判定来源:agent_moss / cache(与 Python 版对齐) */
|
|
1886
|
+
source: import_zod.z.string().default("agent_moss"),
|
|
1847
1887
|
oversize: import_zod.z.boolean().optional().describe("\u672C\u5730\u5B58\u50A8\u662F\u5426\u8D85\u8FC7\u6E05\u7406\u9608\u503C\uFF08agg \u7528\uFF09"),
|
|
1848
1888
|
thresholdMB: import_zod.z.number().optional().describe("\u5B58\u50A8\u6E05\u7406\u9608\u503C MB\uFF08agg \u7528\uFF09"),
|
|
1849
1889
|
collected_context: import_zod.z.object({
|
|
@@ -2108,6 +2148,9 @@ function getTimeline(limit) {
|
|
|
2108
2148
|
function getSessionAgentType(sessionId) {
|
|
2109
2149
|
return store().getSessionAgentType(sessionId);
|
|
2110
2150
|
}
|
|
2151
|
+
function getSessionInfo(sessionId) {
|
|
2152
|
+
return store().getSessionInfo(sessionId);
|
|
2153
|
+
}
|
|
2111
2154
|
var init_repository = __esm({
|
|
2112
2155
|
"src/shared/storage/repository.ts"() {
|
|
2113
2156
|
"use strict";
|
|
@@ -2130,6 +2173,598 @@ var init_agent_identity = __esm({
|
|
|
2130
2173
|
}
|
|
2131
2174
|
});
|
|
2132
2175
|
|
|
2176
|
+
// src/v3/sessionlog/events.ts
|
|
2177
|
+
function eventToDict(e) {
|
|
2178
|
+
return {
|
|
2179
|
+
type: e.type,
|
|
2180
|
+
seq: e.seq,
|
|
2181
|
+
time: e.time,
|
|
2182
|
+
turn: e.turn,
|
|
2183
|
+
step: e.step,
|
|
2184
|
+
source: e.source,
|
|
2185
|
+
data: e.data
|
|
2186
|
+
};
|
|
2187
|
+
}
|
|
2188
|
+
function eventFromDict(raw) {
|
|
2189
|
+
return {
|
|
2190
|
+
type: raw.type,
|
|
2191
|
+
seq: Number(raw.seq),
|
|
2192
|
+
time: Number(raw.time),
|
|
2193
|
+
turn: Number(raw.turn ?? 0),
|
|
2194
|
+
step: Number(raw.step ?? 0),
|
|
2195
|
+
source: String(raw.source ?? ""),
|
|
2196
|
+
data: raw.data ?? {}
|
|
2197
|
+
};
|
|
2198
|
+
}
|
|
2199
|
+
function nowMs() {
|
|
2200
|
+
return Date.now();
|
|
2201
|
+
}
|
|
2202
|
+
function base(type, seq, timeMs, data, opts = {}) {
|
|
2203
|
+
return {
|
|
2204
|
+
type,
|
|
2205
|
+
seq,
|
|
2206
|
+
time: timeMs ?? nowMs(),
|
|
2207
|
+
turn: opts.turn ?? 0,
|
|
2208
|
+
step: opts.step ?? 0,
|
|
2209
|
+
source: opts.source ?? "",
|
|
2210
|
+
data
|
|
2211
|
+
};
|
|
2212
|
+
}
|
|
2213
|
+
function sessionStart(seq, opts = {}) {
|
|
2214
|
+
return base("session/start", seq, opts.timeMs, { session: opts.meta ?? {} }, { source: opts.source });
|
|
2215
|
+
}
|
|
2216
|
+
function sessionEnd(seq, reason = "", opts = {}) {
|
|
2217
|
+
return base("session/end", seq, opts.timeMs, { reason }, { source: opts.source });
|
|
2218
|
+
}
|
|
2219
|
+
function userPrompt(seq, content, opts = {}) {
|
|
2220
|
+
return base("user/prompt", seq, opts.timeMs, { content, role: "user" }, { turn: opts.turn, source: opts.source });
|
|
2221
|
+
}
|
|
2222
|
+
function llmRequest(seq, model, opts = {}) {
|
|
2223
|
+
return base("llm/request", seq, opts.timeMs, {
|
|
2224
|
+
model,
|
|
2225
|
+
messages_count: opts.messagesCount ?? 0,
|
|
2226
|
+
provider: opts.provider ?? "",
|
|
2227
|
+
request_meta: opts.requestMeta ?? {}
|
|
2228
|
+
}, { turn: opts.turn, source: opts.source });
|
|
2229
|
+
}
|
|
2230
|
+
function llmChunk(seq, chunk, opts = {}) {
|
|
2231
|
+
return base("llm/chunk", seq, opts.timeMs, { chunk }, { turn: opts.turn, step: opts.step, source: opts.source });
|
|
2232
|
+
}
|
|
2233
|
+
function llmResponse(seq, content, opts = {}) {
|
|
2234
|
+
return base("llm/response", seq, opts.timeMs, { content, model: opts.model ?? "", usage: opts.usage ?? {} }, { turn: opts.turn, step: opts.step, source: opts.source });
|
|
2235
|
+
}
|
|
2236
|
+
function toolCall(seq, name, argumentsRaw, callId, opts = {}) {
|
|
2237
|
+
return base("tool/call", seq, opts.timeMs, { name, arguments: argumentsRaw, callId }, { turn: opts.turn, step: opts.step, source: opts.source });
|
|
2238
|
+
}
|
|
2239
|
+
function toolResult(seq, callId, content, opts = {}) {
|
|
2240
|
+
return base("tool/result", seq, opts.timeMs, { callId, content, error: opts.error ?? {} }, { turn: opts.turn, step: opts.step, source: opts.source });
|
|
2241
|
+
}
|
|
2242
|
+
function processExec(seq, command, opts = {}) {
|
|
2243
|
+
return base("process/exec", seq, opts.timeMs, { command, argv: opts.argv ?? [], pid: opts.pid, cwd: opts.cwd ?? "" }, { turn: opts.turn, source: opts.source });
|
|
2244
|
+
}
|
|
2245
|
+
function processResult(seq, command, output, opts = {}) {
|
|
2246
|
+
return base("process/result", seq, opts.timeMs, { command, output, exit_code: opts.exitCode, pid: opts.pid }, { source: opts.source });
|
|
2247
|
+
}
|
|
2248
|
+
function syscallEvent(seq, syscall, opts = {}) {
|
|
2249
|
+
return base("syscall/event", seq, opts.timeMs, { syscall, argv: opts.argv ?? [], pid: opts.pid }, { source: opts.source });
|
|
2250
|
+
}
|
|
2251
|
+
function systemEvent(seq, kind, detail, opts = {}) {
|
|
2252
|
+
return base("system", seq, opts.timeMs, { kind, detail }, { source: opts.source });
|
|
2253
|
+
}
|
|
2254
|
+
var init_events = __esm({
|
|
2255
|
+
"src/v3/sessionlog/events.ts"() {
|
|
2256
|
+
"use strict";
|
|
2257
|
+
init_cjs_shims();
|
|
2258
|
+
}
|
|
2259
|
+
});
|
|
2260
|
+
|
|
2261
|
+
// src/v3/sessionlog/log.ts
|
|
2262
|
+
var SessionLog;
|
|
2263
|
+
var init_log = __esm({
|
|
2264
|
+
"src/v3/sessionlog/log.ts"() {
|
|
2265
|
+
"use strict";
|
|
2266
|
+
init_cjs_shims();
|
|
2267
|
+
init_events();
|
|
2268
|
+
SessionLog = class _SessionLog {
|
|
2269
|
+
sessionId;
|
|
2270
|
+
eventsList;
|
|
2271
|
+
constructor(sessionId = "", events = []) {
|
|
2272
|
+
this.sessionId = sessionId;
|
|
2273
|
+
this.eventsList = [...events];
|
|
2274
|
+
this.renumber();
|
|
2275
|
+
}
|
|
2276
|
+
append(event) {
|
|
2277
|
+
try {
|
|
2278
|
+
JSON.stringify(event.data);
|
|
2279
|
+
} catch {
|
|
2280
|
+
throw new Error(`SessionLog: event data not JSON-serializable: ${event.type}`);
|
|
2281
|
+
}
|
|
2282
|
+
event.seq = this.eventsList.length;
|
|
2283
|
+
this.eventsList.push(event);
|
|
2284
|
+
return event;
|
|
2285
|
+
}
|
|
2286
|
+
appendMany(events) {
|
|
2287
|
+
return events.map((e) => this.append(e));
|
|
2288
|
+
}
|
|
2289
|
+
get length() {
|
|
2290
|
+
return this.eventsList.length;
|
|
2291
|
+
}
|
|
2292
|
+
get nextSeq() {
|
|
2293
|
+
return this.eventsList.length;
|
|
2294
|
+
}
|
|
2295
|
+
get events() {
|
|
2296
|
+
return [...this.eventsList];
|
|
2297
|
+
}
|
|
2298
|
+
byType(type) {
|
|
2299
|
+
return this.eventsList.filter((e) => e.type === type);
|
|
2300
|
+
}
|
|
2301
|
+
toolCalls() {
|
|
2302
|
+
return this.byType("tool/call");
|
|
2303
|
+
}
|
|
2304
|
+
toolResults() {
|
|
2305
|
+
return this.byType("tool/result");
|
|
2306
|
+
}
|
|
2307
|
+
pairToolCalls() {
|
|
2308
|
+
const results = /* @__PURE__ */ new Map();
|
|
2309
|
+
for (const r of this.toolResults()) {
|
|
2310
|
+
results.set(String(r.data.callId), r);
|
|
2311
|
+
}
|
|
2312
|
+
return this.toolCalls().map((c) => [c, results.get(String(c.data.callId)) ?? null]);
|
|
2313
|
+
}
|
|
2314
|
+
/** Derive model-visible message history from the log (AgentGate semantics). */
|
|
2315
|
+
deriveMessages() {
|
|
2316
|
+
const messages = [];
|
|
2317
|
+
for (const e of this.eventsList) {
|
|
2318
|
+
if (e.type === "user/prompt") {
|
|
2319
|
+
messages.push({ role: "user", content: String(e.data.content ?? "") });
|
|
2320
|
+
} else if (e.type === "llm/response") {
|
|
2321
|
+
const content = String(e.data.content ?? "");
|
|
2322
|
+
const calls = this.toolCalls().filter((c) => c.turn === e.turn && c.step === e.step).map((c) => c.data);
|
|
2323
|
+
const msg = { role: "assistant", content };
|
|
2324
|
+
if (calls.length > 0) msg.tool_calls = calls;
|
|
2325
|
+
messages.push(msg);
|
|
2326
|
+
}
|
|
2327
|
+
}
|
|
2328
|
+
return messages;
|
|
2329
|
+
}
|
|
2330
|
+
toDicts() {
|
|
2331
|
+
return this.eventsList.map((e) => eventToDict(e));
|
|
2332
|
+
}
|
|
2333
|
+
toJson(indent) {
|
|
2334
|
+
return JSON.stringify(this.toDicts(), null, indent);
|
|
2335
|
+
}
|
|
2336
|
+
static fromDicts(rawList, sessionId = "") {
|
|
2337
|
+
return new _SessionLog(sessionId, rawList.map((r) => eventFromDict(r)));
|
|
2338
|
+
}
|
|
2339
|
+
static fromJson(text, sessionId = "") {
|
|
2340
|
+
return _SessionLog.fromDicts(JSON.parse(text), sessionId);
|
|
2341
|
+
}
|
|
2342
|
+
replay(visitor) {
|
|
2343
|
+
for (const e of this.eventsList) visitor(e);
|
|
2344
|
+
}
|
|
2345
|
+
renumber() {
|
|
2346
|
+
this.eventsList.forEach((e, i) => {
|
|
2347
|
+
e.seq = i;
|
|
2348
|
+
});
|
|
2349
|
+
}
|
|
2350
|
+
};
|
|
2351
|
+
}
|
|
2352
|
+
});
|
|
2353
|
+
|
|
2354
|
+
// src/v3/sessionlog/trajectory.ts
|
|
2355
|
+
function asText(value) {
|
|
2356
|
+
if (value === null || value === void 0) return "";
|
|
2357
|
+
if (typeof value === "string") return value;
|
|
2358
|
+
return JSON.stringify(value);
|
|
2359
|
+
}
|
|
2360
|
+
function buildTrajectory(log) {
|
|
2361
|
+
const records = [];
|
|
2362
|
+
const toolTimes = /* @__PURE__ */ new Map();
|
|
2363
|
+
const procTimes = /* @__PURE__ */ new Map();
|
|
2364
|
+
for (const e of log.events) {
|
|
2365
|
+
switch (e.type) {
|
|
2366
|
+
case "session/start":
|
|
2367
|
+
records.push({ kind: "system", seq: e.seq, time: e.time, detail: "session/start" });
|
|
2368
|
+
break;
|
|
2369
|
+
case "session/end":
|
|
2370
|
+
records.push({ kind: "system", seq: e.seq, time: e.time, detail: "session/end" });
|
|
2371
|
+
break;
|
|
2372
|
+
case "user/prompt":
|
|
2373
|
+
records.push({
|
|
2374
|
+
kind: "user",
|
|
2375
|
+
seq: e.seq,
|
|
2376
|
+
time: e.time,
|
|
2377
|
+
turn: e.turn,
|
|
2378
|
+
content: asText(e.data.content)
|
|
2379
|
+
});
|
|
2380
|
+
break;
|
|
2381
|
+
case "llm/response":
|
|
2382
|
+
records.push({
|
|
2383
|
+
kind: "llm",
|
|
2384
|
+
seq: e.seq,
|
|
2385
|
+
time: e.time,
|
|
2386
|
+
turn: e.turn,
|
|
2387
|
+
step: e.step,
|
|
2388
|
+
model: String(e.data.model ?? ""),
|
|
2389
|
+
content: asText(e.data.content),
|
|
2390
|
+
usage: e.data.usage ?? {}
|
|
2391
|
+
});
|
|
2392
|
+
break;
|
|
2393
|
+
case "tool/call":
|
|
2394
|
+
toolTimes.set(String(e.data.callId ?? ""), e.time);
|
|
2395
|
+
records.push({
|
|
2396
|
+
kind: "tool",
|
|
2397
|
+
seq: e.seq,
|
|
2398
|
+
time: e.time,
|
|
2399
|
+
turn: e.turn,
|
|
2400
|
+
step: e.step,
|
|
2401
|
+
call_id: String(e.data.callId ?? ""),
|
|
2402
|
+
name: String(e.data.name ?? ""),
|
|
2403
|
+
arguments: String(e.data.arguments ?? ""),
|
|
2404
|
+
result: null,
|
|
2405
|
+
error: null,
|
|
2406
|
+
duration_ms: null,
|
|
2407
|
+
source: e.source
|
|
2408
|
+
});
|
|
2409
|
+
break;
|
|
2410
|
+
case "tool/result": {
|
|
2411
|
+
const callId = String(e.data.callId ?? "");
|
|
2412
|
+
const start = toolTimes.get(callId);
|
|
2413
|
+
const duration = start !== void 0 ? e.time - start : null;
|
|
2414
|
+
const matches = records.filter((r) => r.kind === "tool" && r.call_id === callId);
|
|
2415
|
+
if (matches.length > 0) {
|
|
2416
|
+
const r = matches[matches.length - 1];
|
|
2417
|
+
r.result = e.data.content;
|
|
2418
|
+
r.error = e.data.error || null;
|
|
2419
|
+
r.duration_ms = duration;
|
|
2420
|
+
} else {
|
|
2421
|
+
records.push({
|
|
2422
|
+
kind: "tool",
|
|
2423
|
+
seq: e.seq,
|
|
2424
|
+
time: e.time,
|
|
2425
|
+
turn: e.turn,
|
|
2426
|
+
step: e.step,
|
|
2427
|
+
call_id: callId,
|
|
2428
|
+
name: "",
|
|
2429
|
+
arguments: "",
|
|
2430
|
+
result: e.data.content,
|
|
2431
|
+
error: e.data.error || null,
|
|
2432
|
+
duration_ms: duration,
|
|
2433
|
+
source: e.source
|
|
2434
|
+
});
|
|
2435
|
+
}
|
|
2436
|
+
break;
|
|
2437
|
+
}
|
|
2438
|
+
case "process/exec": {
|
|
2439
|
+
const key = String(e.data.pid ?? e.data.command ?? "");
|
|
2440
|
+
procTimes.set(key, e.time);
|
|
2441
|
+
records.push({
|
|
2442
|
+
kind: "process",
|
|
2443
|
+
seq: e.seq,
|
|
2444
|
+
time: e.time,
|
|
2445
|
+
turn: e.turn,
|
|
2446
|
+
command: String(e.data.command ?? ""),
|
|
2447
|
+
argv: e.data.argv ?? [],
|
|
2448
|
+
pid: e.data.pid,
|
|
2449
|
+
cwd: String(e.data.cwd ?? ""),
|
|
2450
|
+
output: null,
|
|
2451
|
+
exit_code: null,
|
|
2452
|
+
duration_ms: null
|
|
2453
|
+
});
|
|
2454
|
+
break;
|
|
2455
|
+
}
|
|
2456
|
+
case "process/result": {
|
|
2457
|
+
const key = String(e.data.pid ?? e.data.command ?? "");
|
|
2458
|
+
const start = procTimes.get(key);
|
|
2459
|
+
const duration = start !== void 0 ? e.time - start : null;
|
|
2460
|
+
const matches = records.filter((r) => r.kind === "process" && r.pid === e.data.pid);
|
|
2461
|
+
if (matches.length > 0) {
|
|
2462
|
+
const r = matches[matches.length - 1];
|
|
2463
|
+
r.output = asText(e.data.output);
|
|
2464
|
+
r.exit_code = e.data.exit_code;
|
|
2465
|
+
r.duration_ms = duration;
|
|
2466
|
+
} else {
|
|
2467
|
+
records.push({
|
|
2468
|
+
kind: "process",
|
|
2469
|
+
seq: e.seq,
|
|
2470
|
+
time: e.time,
|
|
2471
|
+
turn: e.turn,
|
|
2472
|
+
command: String(e.data.command ?? ""),
|
|
2473
|
+
argv: [],
|
|
2474
|
+
pid: e.data.pid,
|
|
2475
|
+
cwd: "",
|
|
2476
|
+
output: asText(e.data.output),
|
|
2477
|
+
exit_code: e.data.exit_code,
|
|
2478
|
+
duration_ms: duration
|
|
2479
|
+
});
|
|
2480
|
+
}
|
|
2481
|
+
break;
|
|
2482
|
+
}
|
|
2483
|
+
case "syscall/event":
|
|
2484
|
+
records.push({
|
|
2485
|
+
kind: "syscall",
|
|
2486
|
+
seq: e.seq,
|
|
2487
|
+
time: e.time,
|
|
2488
|
+
syscall: String(e.data.syscall ?? ""),
|
|
2489
|
+
argv: e.data.argv ?? [],
|
|
2490
|
+
pid: e.data.pid
|
|
2491
|
+
});
|
|
2492
|
+
break;
|
|
2493
|
+
case "system":
|
|
2494
|
+
records.push({
|
|
2495
|
+
kind: "system",
|
|
2496
|
+
seq: e.seq,
|
|
2497
|
+
time: e.time,
|
|
2498
|
+
detail: String(e.data.kind ?? ""),
|
|
2499
|
+
content: e.data.detail
|
|
2500
|
+
});
|
|
2501
|
+
break;
|
|
2502
|
+
default:
|
|
2503
|
+
break;
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
records.sort((a, b) => Number(a.seq) - Number(b.seq));
|
|
2507
|
+
return records;
|
|
2508
|
+
}
|
|
2509
|
+
function summarize(log) {
|
|
2510
|
+
const events = log.events;
|
|
2511
|
+
if (events.length === 0) {
|
|
2512
|
+
return {
|
|
2513
|
+
turns: 0,
|
|
2514
|
+
llm_calls: 0,
|
|
2515
|
+
tool_calls: 0,
|
|
2516
|
+
tool_errors: 0,
|
|
2517
|
+
process_execs: 0,
|
|
2518
|
+
syscalls: 0,
|
|
2519
|
+
input_tokens: 0,
|
|
2520
|
+
output_tokens: 0,
|
|
2521
|
+
start_time: null,
|
|
2522
|
+
end_time: null
|
|
2523
|
+
};
|
|
2524
|
+
}
|
|
2525
|
+
const times = events.map((e) => e.time);
|
|
2526
|
+
const start = Math.min(...times);
|
|
2527
|
+
const end = Math.max(...times);
|
|
2528
|
+
let usageIn = 0;
|
|
2529
|
+
let usageOut = 0;
|
|
2530
|
+
for (const e of events) {
|
|
2531
|
+
if (e.type === "llm/response") {
|
|
2532
|
+
const u = e.data.usage ?? {};
|
|
2533
|
+
usageIn += Number(u.input_tokens ?? u.prompt_tokens ?? 0) || 0;
|
|
2534
|
+
usageOut += Number(u.output_tokens ?? u.completion_tokens ?? 0) || 0;
|
|
2535
|
+
}
|
|
2536
|
+
}
|
|
2537
|
+
return {
|
|
2538
|
+
turns: new Set(events.filter((e) => e.turn).map((e) => e.turn)).size,
|
|
2539
|
+
llm_calls: events.filter((e) => e.type === "llm/response").length,
|
|
2540
|
+
tool_calls: events.filter((e) => e.type === "tool/call").length,
|
|
2541
|
+
tool_errors: events.filter((e) => {
|
|
2542
|
+
if (e.type !== "tool/result") return false;
|
|
2543
|
+
const err = e.data.error;
|
|
2544
|
+
return !!err && Object.keys(err).length > 0;
|
|
2545
|
+
}).length,
|
|
2546
|
+
process_execs: events.filter((e) => e.type === "process/exec").length,
|
|
2547
|
+
syscalls: events.filter((e) => e.type === "syscall/event").length,
|
|
2548
|
+
input_tokens: usageIn,
|
|
2549
|
+
output_tokens: usageOut,
|
|
2550
|
+
start_time: start,
|
|
2551
|
+
end_time: end,
|
|
2552
|
+
duration_ms: end - start
|
|
2553
|
+
};
|
|
2554
|
+
}
|
|
2555
|
+
var init_trajectory = __esm({
|
|
2556
|
+
"src/v3/sessionlog/trajectory.ts"() {
|
|
2557
|
+
"use strict";
|
|
2558
|
+
init_cjs_shims();
|
|
2559
|
+
}
|
|
2560
|
+
});
|
|
2561
|
+
|
|
2562
|
+
// src/v3/sessionlog/persistence.ts
|
|
2563
|
+
function saveAppend(log, filePath) {
|
|
2564
|
+
fs.mkdirSync(path.dirname(path.resolve(filePath)), { recursive: true });
|
|
2565
|
+
const lines = log.events.map((e) => JSON.stringify(eventToDict2(e)));
|
|
2566
|
+
fs.appendFileSync(filePath, lines.map((l) => l + "\n").join(""), "utf-8");
|
|
2567
|
+
}
|
|
2568
|
+
function saveSnapshot(log, filePath) {
|
|
2569
|
+
fs.mkdirSync(path.dirname(path.resolve(filePath)), { recursive: true });
|
|
2570
|
+
const lines = log.events.map((e) => JSON.stringify(eventToDict2(e)));
|
|
2571
|
+
fs.writeFileSync(filePath, lines.map((l) => l + "\n").join(""), "utf-8");
|
|
2572
|
+
}
|
|
2573
|
+
function load(filePath, sessionId = "") {
|
|
2574
|
+
const events = [];
|
|
2575
|
+
if (!fs.existsSync(filePath)) return new SessionLog(sessionId);
|
|
2576
|
+
const text = fs.readFileSync(filePath, "utf-8");
|
|
2577
|
+
for (const line of text.split("\n")) {
|
|
2578
|
+
const trimmed = line.trim();
|
|
2579
|
+
if (!trimmed) continue;
|
|
2580
|
+
try {
|
|
2581
|
+
events.push(eventFromDict(JSON.parse(trimmed)));
|
|
2582
|
+
} catch {
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
return new SessionLog(sessionId, events);
|
|
2586
|
+
}
|
|
2587
|
+
function eventToDict2(e) {
|
|
2588
|
+
return {
|
|
2589
|
+
type: e.type,
|
|
2590
|
+
seq: e.seq,
|
|
2591
|
+
time: e.time,
|
|
2592
|
+
turn: e.turn,
|
|
2593
|
+
step: e.step,
|
|
2594
|
+
source: e.source,
|
|
2595
|
+
data: e.data
|
|
2596
|
+
};
|
|
2597
|
+
}
|
|
2598
|
+
var fs, path;
|
|
2599
|
+
var init_persistence = __esm({
|
|
2600
|
+
"src/v3/sessionlog/persistence.ts"() {
|
|
2601
|
+
"use strict";
|
|
2602
|
+
init_cjs_shims();
|
|
2603
|
+
fs = __toESM(require("fs"));
|
|
2604
|
+
path = __toESM(require("path"));
|
|
2605
|
+
init_events();
|
|
2606
|
+
init_log();
|
|
2607
|
+
}
|
|
2608
|
+
});
|
|
2609
|
+
|
|
2610
|
+
// src/v3/sessionlog/convert.ts
|
|
2611
|
+
function fromNormalized(event, opts = {}) {
|
|
2612
|
+
const collector = String(event.source_collector ?? "");
|
|
2613
|
+
const sid = opts.sessionId ?? String(event.session_id ?? "");
|
|
2614
|
+
const ts = opts.timeMs ?? Date.now();
|
|
2615
|
+
const action = event.action ?? {};
|
|
2616
|
+
const payload = event.payload ?? {};
|
|
2617
|
+
const toolName = String(action.tool_name ?? "");
|
|
2618
|
+
const callId = String(action.tool_call_id ?? "");
|
|
2619
|
+
const argumentsRaw = String(action.arguments_raw ?? "{}");
|
|
2620
|
+
if (collector === "llm_api_proxy") {
|
|
2621
|
+
const out = [];
|
|
2622
|
+
const userText = payload.user_prompt;
|
|
2623
|
+
if (userText) out.push(userPrompt(out.length, String(userText), { turn: opts.turn, timeMs: ts, source: "llm" }));
|
|
2624
|
+
if (toolName) {
|
|
2625
|
+
out.push(toolCall(out.length, toolName, argumentsRaw, callId, {
|
|
2626
|
+
turn: opts.turn,
|
|
2627
|
+
step: opts.step,
|
|
2628
|
+
timeMs: ts,
|
|
2629
|
+
source: "llm"
|
|
2630
|
+
}));
|
|
2631
|
+
}
|
|
2632
|
+
const response = payload.tool_response_content;
|
|
2633
|
+
if (response !== void 0 && response !== null) {
|
|
2634
|
+
out.push(toolResult(out.length, callId, response, { turn: opts.turn, step: opts.step, timeMs: ts, source: "llm" }));
|
|
2635
|
+
}
|
|
2636
|
+
return out;
|
|
2637
|
+
}
|
|
2638
|
+
if (collector === "mcp") {
|
|
2639
|
+
const out = [];
|
|
2640
|
+
if (toolName) {
|
|
2641
|
+
out.push(toolCall(out.length, toolName, argumentsRaw, callId, {
|
|
2642
|
+
turn: opts.turn,
|
|
2643
|
+
step: opts.step,
|
|
2644
|
+
timeMs: ts,
|
|
2645
|
+
source: "mcp"
|
|
2646
|
+
}));
|
|
2647
|
+
}
|
|
2648
|
+
const rawResp = payload.mcp_response ?? event.response;
|
|
2649
|
+
if (rawResp !== void 0 && rawResp !== null) {
|
|
2650
|
+
out.push(toolResult(out.length, callId, rawResp, { turn: opts.turn, step: opts.step, timeMs: ts, source: "mcp" }));
|
|
2651
|
+
}
|
|
2652
|
+
return out;
|
|
2653
|
+
}
|
|
2654
|
+
if (collector === "pty") {
|
|
2655
|
+
const command = String(action.command ?? event.command ?? "");
|
|
2656
|
+
const pid = event.process && typeof event.process === "object" ? Number(event.process.pid) : void 0;
|
|
2657
|
+
if (command) {
|
|
2658
|
+
return [processExec(0, command, { pid, cwd: String(event.cwd ?? ""), turn: opts.turn, timeMs: ts, source: "pty" })];
|
|
2659
|
+
}
|
|
2660
|
+
return [];
|
|
2661
|
+
}
|
|
2662
|
+
if (collector === "ebpf") {
|
|
2663
|
+
const syscall = String(action.syscall ?? action.syscall_type ?? toolName);
|
|
2664
|
+
const pid = event.process && typeof event.process === "object" ? Number(event.process.pid) : void 0;
|
|
2665
|
+
if (syscall) {
|
|
2666
|
+
return [syscallEvent(0, syscall, { pid, timeMs: ts, source: "ebpf" })];
|
|
2667
|
+
}
|
|
2668
|
+
return [];
|
|
2669
|
+
}
|
|
2670
|
+
return [];
|
|
2671
|
+
}
|
|
2672
|
+
var path2, DEFAULT_LOG_DIR, SessionLogRecorder, defaultRecorder;
|
|
2673
|
+
var init_convert = __esm({
|
|
2674
|
+
"src/v3/sessionlog/convert.ts"() {
|
|
2675
|
+
"use strict";
|
|
2676
|
+
init_cjs_shims();
|
|
2677
|
+
path2 = __toESM(require("path"));
|
|
2678
|
+
init_events();
|
|
2679
|
+
init_log();
|
|
2680
|
+
init_persistence();
|
|
2681
|
+
DEFAULT_LOG_DIR = path2.join(
|
|
2682
|
+
process.env.HOME || process.env.USERPROFILE || "~",
|
|
2683
|
+
".agentgate",
|
|
2684
|
+
"sessionlogs"
|
|
2685
|
+
);
|
|
2686
|
+
SessionLogRecorder = class {
|
|
2687
|
+
logDir;
|
|
2688
|
+
enabled;
|
|
2689
|
+
logs = /* @__PURE__ */ new Map();
|
|
2690
|
+
turns = /* @__PURE__ */ new Map();
|
|
2691
|
+
steps = /* @__PURE__ */ new Map();
|
|
2692
|
+
constructor(opts = {}) {
|
|
2693
|
+
this.logDir = opts.logDir ?? DEFAULT_LOG_DIR;
|
|
2694
|
+
this.enabled = opts.enabled ?? true;
|
|
2695
|
+
}
|
|
2696
|
+
record(event, sessionId = "") {
|
|
2697
|
+
if (!this.enabled) return;
|
|
2698
|
+
const sid = sessionId || String(event.session_id ?? "");
|
|
2699
|
+
if (!sid) return;
|
|
2700
|
+
try {
|
|
2701
|
+
let log = this.logs.get(sid);
|
|
2702
|
+
if (!log) {
|
|
2703
|
+
log = new SessionLog(sid);
|
|
2704
|
+
this.logs.set(sid, log);
|
|
2705
|
+
this.turns.set(sid, 0);
|
|
2706
|
+
this.steps.set(sid, 0);
|
|
2707
|
+
}
|
|
2708
|
+
const turn = this.turns.get(sid) ?? 0;
|
|
2709
|
+
const step = this.steps.get(sid) ?? 0;
|
|
2710
|
+
const events = fromNormalized(event, { sessionId: sid, turn, step });
|
|
2711
|
+
if (events.length === 0) return;
|
|
2712
|
+
for (const e of events) log.append(e);
|
|
2713
|
+
if (events.some((e) => e.type === "user/prompt")) this.turns.set(sid, turn + 1);
|
|
2714
|
+
if (events.some((e) => e.type === "tool/call")) this.steps.set(sid, step + 1);
|
|
2715
|
+
saveAppend(log, path2.join(this.logDir, `${sid}.jsonl`));
|
|
2716
|
+
} catch (e) {
|
|
2717
|
+
console.warn("sessionlog record failed:", e);
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
sessionLog(sessionId) {
|
|
2721
|
+
return this.logs.get(sessionId) ?? null;
|
|
2722
|
+
}
|
|
2723
|
+
};
|
|
2724
|
+
defaultRecorder = new SessionLogRecorder();
|
|
2725
|
+
}
|
|
2726
|
+
});
|
|
2727
|
+
|
|
2728
|
+
// src/v3/sessionlog/index.ts
|
|
2729
|
+
var sessionlog_exports = {};
|
|
2730
|
+
__export(sessionlog_exports, {
|
|
2731
|
+
DEFAULT_LOG_DIR: () => DEFAULT_LOG_DIR,
|
|
2732
|
+
SessionLog: () => SessionLog,
|
|
2733
|
+
SessionLogRecorder: () => SessionLogRecorder,
|
|
2734
|
+
buildTrajectory: () => buildTrajectory,
|
|
2735
|
+
defaultRecorder: () => defaultRecorder,
|
|
2736
|
+
eventFromDict: () => eventFromDict,
|
|
2737
|
+
eventToDict: () => eventToDict,
|
|
2738
|
+
fromNormalized: () => fromNormalized,
|
|
2739
|
+
llmChunk: () => llmChunk,
|
|
2740
|
+
llmRequest: () => llmRequest,
|
|
2741
|
+
llmResponse: () => llmResponse,
|
|
2742
|
+
load: () => load,
|
|
2743
|
+
processExec: () => processExec,
|
|
2744
|
+
processResult: () => processResult,
|
|
2745
|
+
saveAppend: () => saveAppend,
|
|
2746
|
+
saveSnapshot: () => saveSnapshot,
|
|
2747
|
+
sessionEnd: () => sessionEnd,
|
|
2748
|
+
sessionStart: () => sessionStart,
|
|
2749
|
+
summarize: () => summarize,
|
|
2750
|
+
syscallEvent: () => syscallEvent,
|
|
2751
|
+
systemEvent: () => systemEvent,
|
|
2752
|
+
toolCall: () => toolCall,
|
|
2753
|
+
toolResult: () => toolResult,
|
|
2754
|
+
userPrompt: () => userPrompt
|
|
2755
|
+
});
|
|
2756
|
+
var init_sessionlog = __esm({
|
|
2757
|
+
"src/v3/sessionlog/index.ts"() {
|
|
2758
|
+
"use strict";
|
|
2759
|
+
init_cjs_shims();
|
|
2760
|
+
init_events();
|
|
2761
|
+
init_log();
|
|
2762
|
+
init_trajectory();
|
|
2763
|
+
init_persistence();
|
|
2764
|
+
init_convert();
|
|
2765
|
+
}
|
|
2766
|
+
});
|
|
2767
|
+
|
|
2133
2768
|
// src/v1/routes.ts
|
|
2134
2769
|
async function healthRoute(c) {
|
|
2135
2770
|
const mossHealth = await fetchMossHealth();
|
|
@@ -2169,6 +2804,7 @@ async function analyzeRoute(c) {
|
|
|
2169
2804
|
return c.json({
|
|
2170
2805
|
...cached2,
|
|
2171
2806
|
analysis_duration_ms: 0,
|
|
2807
|
+
source: "cache",
|
|
2172
2808
|
collected_context: {},
|
|
2173
2809
|
...storageOversizeInfo()
|
|
2174
2810
|
});
|
|
@@ -2232,6 +2868,9 @@ async function analyzeRoute(c) {
|
|
|
2232
2868
|
confidence: mossResult.confidence,
|
|
2233
2869
|
analysis_duration_ms: Math.round(durationMs * 10) / 10,
|
|
2234
2870
|
violation_graph: mossResult.violation_graph ?? null,
|
|
2871
|
+
// 与 Python 版响应字段对齐(policy / source)
|
|
2872
|
+
policy: mossResult.policy ?? "",
|
|
2873
|
+
source: "agent_moss",
|
|
2235
2874
|
...storageOversizeInfo(),
|
|
2236
2875
|
collected_context: {
|
|
2237
2876
|
os: context.os,
|
|
@@ -2263,7 +2902,18 @@ async function sessionsRoute(c) {
|
|
|
2263
2902
|
}
|
|
2264
2903
|
}
|
|
2265
2904
|
const rows = queryToolCalls({ sessionId, limit: 100 });
|
|
2266
|
-
|
|
2905
|
+
const info = getSessionInfo(sessionId);
|
|
2906
|
+
return c.json({
|
|
2907
|
+
session_id: sessionId,
|
|
2908
|
+
agent_type: info?.agentType ?? "",
|
|
2909
|
+
agent_version: info?.agentVersion ?? "",
|
|
2910
|
+
status: info?.status ?? "",
|
|
2911
|
+
cwd: info?.cwd ?? "",
|
|
2912
|
+
user_prompt: info?.userPrompt ?? "",
|
|
2913
|
+
created_at: info?.createdAt ?? "",
|
|
2914
|
+
tool_call_count: info?.toolCallCount ?? 0,
|
|
2915
|
+
tool_calls: rows
|
|
2916
|
+
});
|
|
2267
2917
|
}
|
|
2268
2918
|
async function toolCallsRoute(c) {
|
|
2269
2919
|
const sessionId = c.req.query("session_id") || void 0;
|
|
@@ -2313,6 +2963,61 @@ function deleteToolCallsRoute(c) {
|
|
|
2313
2963
|
const deleted = clearToolCalls();
|
|
2314
2964
|
return c.json({ deleted });
|
|
2315
2965
|
}
|
|
2966
|
+
async function sessionLogsRoute(c) {
|
|
2967
|
+
const { readdirSync: readdirSync2, statSync: statSync3 } = await import("fs");
|
|
2968
|
+
const { join: join6 } = await import("path");
|
|
2969
|
+
const { load: load2, summarize: summarize2, DEFAULT_LOG_DIR: DEFAULT_LOG_DIR2 } = await Promise.resolve().then(() => (init_sessionlog(), sessionlog_exports));
|
|
2970
|
+
const dir = DEFAULT_LOG_DIR2;
|
|
2971
|
+
let files = [];
|
|
2972
|
+
try {
|
|
2973
|
+
files = readdirSync2(dir).filter((f) => f.endsWith(".jsonl"));
|
|
2974
|
+
} catch {
|
|
2975
|
+
files = [];
|
|
2976
|
+
}
|
|
2977
|
+
const logs = files.map((f) => {
|
|
2978
|
+
const full = join6(dir, f);
|
|
2979
|
+
let mtime = 0;
|
|
2980
|
+
try {
|
|
2981
|
+
mtime = statSync3(full).mtimeMs;
|
|
2982
|
+
} catch {
|
|
2983
|
+
}
|
|
2984
|
+
return { full, mtime };
|
|
2985
|
+
}).sort((a, b) => b.mtime - a.mtime).slice(0, 50).map(({ full, mtime }) => {
|
|
2986
|
+
const sid = full.split(/[\\/]/).pop().replace(/\.jsonl$/, "");
|
|
2987
|
+
let summary = {};
|
|
2988
|
+
try {
|
|
2989
|
+
summary = summarize2(load2(full, sid));
|
|
2990
|
+
} catch {
|
|
2991
|
+
}
|
|
2992
|
+
return { session_id: sid, file: full, mtime: Math.round(mtime), summary };
|
|
2993
|
+
});
|
|
2994
|
+
return c.json({ total: logs.length, logs });
|
|
2995
|
+
}
|
|
2996
|
+
async function sessionLogDetailRoute(c) {
|
|
2997
|
+
const { existsSync: existsSync5 } = await import("fs");
|
|
2998
|
+
const { join: join6 } = await import("path");
|
|
2999
|
+
const { load: load2, summarize: summarize2, buildTrajectory: buildTrajectory2, DEFAULT_LOG_DIR: DEFAULT_LOG_DIR2 } = await Promise.resolve().then(() => (init_sessionlog(), sessionlog_exports));
|
|
3000
|
+
const sessionId = c.req.param("id") || "";
|
|
3001
|
+
const principal = c.get("principal") || "ip:unknown";
|
|
3002
|
+
const [n, hit] = noteSessionAccess(principal, sessionId);
|
|
3003
|
+
if (hit) {
|
|
3004
|
+
if (sessionSweepAction() === "deny") {
|
|
3005
|
+
return c.json({ detail: "\u4F1A\u8BDD\u8BBF\u95EE\u8FC7\u4E8E\u96C6\u4E2D\uFF0C\u7591\u4F3C\u6279\u91CF\u626B\u63CF" }, 429);
|
|
3006
|
+
}
|
|
3007
|
+
console.warn(`[AgentGate] \u26A0\uFE0F \u7591\u4F3C\u8DE8\u4F1A\u8BDD\u626B\u63CF: key=${principal} \u7A97\u53E3\u5185\u8BBF\u95EE\u4E86 ${n} \u4E2A\u4E0D\u540C session`);
|
|
3008
|
+
}
|
|
3009
|
+
const path3 = join6(DEFAULT_LOG_DIR2, `${sessionId}.jsonl`);
|
|
3010
|
+
if (!existsSync5(path3)) {
|
|
3011
|
+
return c.json({ detail: `no session log for ${sessionId}` }, 404);
|
|
3012
|
+
}
|
|
3013
|
+
const log = load2(path3, sessionId);
|
|
3014
|
+
return c.json({
|
|
3015
|
+
session_id: sessionId,
|
|
3016
|
+
summary: summarize2(log),
|
|
3017
|
+
records: buildTrajectory2(log),
|
|
3018
|
+
events: log.events
|
|
3019
|
+
});
|
|
3020
|
+
}
|
|
2316
3021
|
var v1ReviewCounter;
|
|
2317
3022
|
var init_routes = __esm({
|
|
2318
3023
|
"src/v1/routes.ts"() {
|
|
@@ -2353,7 +3058,7 @@ function createApp() {
|
|
|
2353
3058
|
)
|
|
2354
3059
|
);
|
|
2355
3060
|
app.use("*", async (c, next) => {
|
|
2356
|
-
const
|
|
3061
|
+
const path3 = new URL(c.req.url).pathname;
|
|
2357
3062
|
const method = c.req.method.toUpperCase();
|
|
2358
3063
|
if (method === "OPTIONS") return next();
|
|
2359
3064
|
const cl = c.req.header("content-length");
|
|
@@ -2367,15 +3072,15 @@ function createApp() {
|
|
|
2367
3072
|
if (originCheckEnabled()) {
|
|
2368
3073
|
const origin = c.req.header("origin") || "";
|
|
2369
3074
|
if (origin && !originAllowed(origin, c.req.header("host") || "")) {
|
|
2370
|
-
console.warn(`[AgentGate] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${
|
|
3075
|
+
console.warn(`[AgentGate] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path3}`);
|
|
2371
3076
|
return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
|
|
2372
3077
|
}
|
|
2373
3078
|
}
|
|
2374
3079
|
const headers = { authorization: c.req.header("authorization") };
|
|
2375
3080
|
const cookie = (0, import_cookie.getCookie)(c, DASHBOARD_COOKIE) || "";
|
|
2376
|
-
const requireGlobal =
|
|
2377
|
-
const { ok, principal } = checkRequestAuth(headers,
|
|
2378
|
-
if (!ok && !PUBLIC_PAGE_PATHS.includes(
|
|
3081
|
+
const requireGlobal = path3.startsWith("/dashboard") || path3.startsWith("/ws/");
|
|
3082
|
+
const { ok, principal } = checkRequestAuth(headers, path3, cookie, requireGlobal);
|
|
3083
|
+
if (!ok && !PUBLIC_PAGE_PATHS.includes(path3)) {
|
|
2379
3084
|
if (boundAgentOf(principal)) {
|
|
2380
3085
|
return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u8BBF\u95EE\u770B\u677F\uFF1B\u8BF7\u4F7F\u7528\u5168\u5C40 token" }, 403);
|
|
2381
3086
|
}
|
|
@@ -2418,7 +3123,7 @@ function createApp() {
|
|
|
2418
3123
|
return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
|
|
2419
3124
|
}
|
|
2420
3125
|
}
|
|
2421
|
-
const pool = poolOf(
|
|
3126
|
+
const pool = poolOf(path3);
|
|
2422
3127
|
if (!take(`pool:${pool}`, poolLimit(pool))) {
|
|
2423
3128
|
const qkey = principal || `ip:${ip}`;
|
|
2424
3129
|
const [n, abusive] = noteQueueReject(qkey);
|
|
@@ -2442,6 +3147,8 @@ function createApp() {
|
|
|
2442
3147
|
app.get("/api/v1/agents", agentsRoute);
|
|
2443
3148
|
app.get("/api/v1/timeline", timelineRoute);
|
|
2444
3149
|
app.get("/api/v1/storage_stats", storageStatsRoute);
|
|
3150
|
+
app.get("/api/v1/sessionlog", sessionLogsRoute);
|
|
3151
|
+
app.get("/api/v1/sessionlog/:id", sessionLogDetailRoute);
|
|
2445
3152
|
app.delete("/api/v1/tool_calls", deleteToolCallsRoute);
|
|
2446
3153
|
app.get("/dashboard/", dashboardRoute);
|
|
2447
3154
|
app.get("/dashboard", (c) => c.redirect("/dashboard/"));
|
|
@@ -2469,17 +3176,17 @@ async function dashboardRoute(c) {
|
|
|
2469
3176
|
return c.html(UNAUTHORIZED_HTML, 401, DASHBOARD_SECURITY_HEADERS);
|
|
2470
3177
|
}
|
|
2471
3178
|
}
|
|
2472
|
-
const { readFileSync:
|
|
2473
|
-
const { resolve, dirname:
|
|
3179
|
+
const { readFileSync: readFileSync5, existsSync: existsSync5 } = await import("fs");
|
|
3180
|
+
const { resolve: resolve2, dirname: dirname6 } = await import("path");
|
|
2474
3181
|
const { fileURLToPath } = await import("url");
|
|
2475
|
-
const __dirname =
|
|
3182
|
+
const __dirname = dirname6(fileURLToPath(importMetaUrl));
|
|
2476
3183
|
const paths = [
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
3184
|
+
resolve2(__dirname, "dashboard.html"),
|
|
3185
|
+
resolve2(__dirname, "../dashboard.html"),
|
|
3186
|
+
resolve2(__dirname, "../src/v1/dashboard.html")
|
|
2480
3187
|
];
|
|
2481
|
-
const htmlPath = paths.find((p) =>
|
|
2482
|
-
const html =
|
|
3188
|
+
const htmlPath = paths.find((p) => existsSync5(p)) || paths[0];
|
|
3189
|
+
const html = readFileSync5(htmlPath, "utf-8");
|
|
2483
3190
|
return c.html(html, 200, DASHBOARD_SECURITY_HEADERS);
|
|
2484
3191
|
}
|
|
2485
3192
|
var import_hono, import_cors, import_logger, import_cookie, PUBLIC_PAGE_PATHS, UNAUTHORIZED_HTML, AGENT_FORBIDDEN_HTML;
|