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