@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/server.js
CHANGED
|
@@ -356,18 +356,18 @@ function isGlobalToken(token) {
|
|
|
356
356
|
function boundAgentOf(principal) {
|
|
357
357
|
return principal.startsWith("agent:") ? principal.slice("agent:".length) : "";
|
|
358
358
|
}
|
|
359
|
-
function cookiePathAllowed(
|
|
360
|
-
if (
|
|
361
|
-
return
|
|
359
|
+
function cookiePathAllowed(path3) {
|
|
360
|
+
if (path3 === "/api/v1/analyze" || path3.startsWith("/api/v1/analyze/")) return false;
|
|
361
|
+
return path3 === "/dashboard" || path3.startsWith("/dashboard/") || path3.startsWith("/ws/") || path3.startsWith("/api/");
|
|
362
362
|
}
|
|
363
|
-
function checkRequestAuth(headers,
|
|
363
|
+
function checkRequestAuth(headers, path3, cookie = "", requireGlobal = false) {
|
|
364
364
|
if (authMode() === AUTH_MODE_OFF) return { ok: true, principal: "" };
|
|
365
|
-
const isHealth = PUBLIC_PATHS.includes(
|
|
365
|
+
const isHealth = PUBLIC_PATHS.includes(path3.replace(/\/+$/, ""));
|
|
366
366
|
const { token: globalTok, agents, error } = resolveAuth();
|
|
367
367
|
if (error) return { ok: isHealth, principal: "" };
|
|
368
368
|
if (!globalTok && Object.keys(agents).length === 0) return { ok: true, principal: "" };
|
|
369
369
|
if (isHealth) return { ok: true, principal: "" };
|
|
370
|
-
if (cookie && cookiePathAllowed(
|
|
370
|
+
if (cookie && cookiePathAllowed(path3) && checkToken(cookie)) {
|
|
371
371
|
const principal = principalOf(cookie);
|
|
372
372
|
if (requireGlobal && principal.startsWith("agent:")) {
|
|
373
373
|
return { ok: false, principal };
|
|
@@ -414,11 +414,11 @@ function diskDegradePercent() {
|
|
|
414
414
|
function rateLimitQps() {
|
|
415
415
|
return envInt("AGENT_GATE_RATE_LIMIT_QPS", 100);
|
|
416
416
|
}
|
|
417
|
-
function poolOf(
|
|
418
|
-
if (
|
|
419
|
-
if (
|
|
420
|
-
if (
|
|
421
|
-
if (
|
|
417
|
+
function poolOf(path3) {
|
|
418
|
+
if (path3 === "/api/v1/analyze" || path3.startsWith("/api/v1/analyze/")) return "biz";
|
|
419
|
+
if (path3.startsWith("/api/v1/sessions") || path3.startsWith("/api/v1/agents") || path3.startsWith("/api/v1/tool_calls")) return "read";
|
|
420
|
+
if (path3 === "/dashboard" || path3.startsWith("/dashboard/") || path3.startsWith("/ws/")) return "ops";
|
|
421
|
+
if (path3 === "/api/v1/health") return "health";
|
|
422
422
|
return "other";
|
|
423
423
|
}
|
|
424
424
|
function poolLimit(name) {
|
|
@@ -478,8 +478,7 @@ function hardenFilesEnabled() {
|
|
|
478
478
|
function mossTokenPath() {
|
|
479
479
|
const root = env("AGENT_MOSS_DATA_DIR");
|
|
480
480
|
if (root) return (0, import_node_path.join)(root, "auth_token");
|
|
481
|
-
|
|
482
|
-
return (0, import_node_path.join)(home, ".config", "agentmoss", "auth_token");
|
|
481
|
+
return (0, import_node_path.join)((0, import_node_os.homedir)(), ".config", "agentmoss", "auth_token");
|
|
483
482
|
}
|
|
484
483
|
function resolveMossToken(force = false) {
|
|
485
484
|
const now = performance.now() / 1e3;
|
|
@@ -497,9 +496,13 @@ function resolveMossToken(force = false) {
|
|
|
497
496
|
}
|
|
498
497
|
}
|
|
499
498
|
if (!tok) {
|
|
499
|
+
const tokenPath = mossTokenPath();
|
|
500
500
|
try {
|
|
501
|
-
tok = (0, import_node_fs.readFileSync)(
|
|
501
|
+
tok = (0, import_node_fs.readFileSync)(tokenPath, "utf-8").trim();
|
|
502
502
|
} catch {
|
|
503
|
+
console.warn(
|
|
504
|
+
`[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`
|
|
505
|
+
);
|
|
503
506
|
tok = "";
|
|
504
507
|
}
|
|
505
508
|
}
|
|
@@ -832,21 +835,21 @@ var init_json_storage = __esm({
|
|
|
832
835
|
}
|
|
833
836
|
return maxId + 1;
|
|
834
837
|
}
|
|
835
|
-
readJsonFile(
|
|
838
|
+
readJsonFile(path3, fallback) {
|
|
836
839
|
try {
|
|
837
|
-
if (!(0, import_fs3.existsSync)(
|
|
838
|
-
return JSON.parse((0, import_fs3.readFileSync)(
|
|
840
|
+
if (!(0, import_fs3.existsSync)(path3)) return fallback;
|
|
841
|
+
return JSON.parse((0, import_fs3.readFileSync)(path3, "utf-8"));
|
|
839
842
|
} catch {
|
|
840
843
|
return fallback;
|
|
841
844
|
}
|
|
842
845
|
}
|
|
843
846
|
/** 原子写入:先写 .tmp 再 rename(rename 保留 tmp 的 0600 权限) */
|
|
844
|
-
writeJsonFile(
|
|
845
|
-
const dir = (0, import_path3.dirname)(
|
|
847
|
+
writeJsonFile(path3, data) {
|
|
848
|
+
const dir = (0, import_path3.dirname)(path3);
|
|
846
849
|
if (!(0, import_fs3.existsSync)(dir)) (0, import_fs3.mkdirSync)(dir, { recursive: true, mode: 448 });
|
|
847
|
-
const tmp =
|
|
850
|
+
const tmp = path3 + ".tmp";
|
|
848
851
|
(0, import_fs3.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
|
|
849
|
-
(0, import_fs3.renameSync)(tmp,
|
|
852
|
+
(0, import_fs3.renameSync)(tmp, path3);
|
|
850
853
|
}
|
|
851
854
|
loadAgents() {
|
|
852
855
|
const raw = this.readJsonFile(this.agentsPath, {});
|
|
@@ -1092,15 +1095,15 @@ var init_json_storage = __esm({
|
|
|
1092
1095
|
const archiveCount = total - keep;
|
|
1093
1096
|
const toArchive = flat.slice(0, archiveCount);
|
|
1094
1097
|
const archiveIds = new Set(toArchive.map((x) => String(x.rec.id)));
|
|
1095
|
-
const { mkdirSync:
|
|
1096
|
-
const { join:
|
|
1098
|
+
const { mkdirSync: mkdirSync6, writeFileSync: writeFileSync5 } = require("fs");
|
|
1099
|
+
const { join: join6 } = require("path");
|
|
1097
1100
|
const { gzipSync } = require("zlib");
|
|
1098
|
-
const archiveDir =
|
|
1099
|
-
if (!(0, import_fs3.existsSync)(archiveDir))
|
|
1101
|
+
const archiveDir = join6(this.dataDir, "archive");
|
|
1102
|
+
if (!(0, import_fs3.existsSync)(archiveDir)) mkdirSync6(archiveDir, { recursive: true, mode: 448 });
|
|
1100
1103
|
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1101
|
-
const file =
|
|
1104
|
+
const file = join6(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1102
1105
|
const payload = toArchive.map((x) => JSON.stringify(x.rec)).join("\n") + "\n";
|
|
1103
|
-
|
|
1106
|
+
writeFileSync5(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1104
1107
|
for (const [sid, recs] of bySession) {
|
|
1105
1108
|
const remain = recs.filter((r) => !archiveIds.has(String(r.id)));
|
|
1106
1109
|
if (remain.length !== recs.length) this.saveToolCalls(sid, remain);
|
|
@@ -1141,6 +1144,21 @@ var init_json_storage = __esm({
|
|
|
1141
1144
|
if (!session) return void 0;
|
|
1142
1145
|
return this.loadAgents().get(session.agent_id)?.agent_type;
|
|
1143
1146
|
}
|
|
1147
|
+
getSessionInfo(sessionId) {
|
|
1148
|
+
const session = this.loadSessions().get(sessionId);
|
|
1149
|
+
if (!session) return void 0;
|
|
1150
|
+
const agent = this.loadAgents().get(session.agent_id);
|
|
1151
|
+
return {
|
|
1152
|
+
sessionId: session.id,
|
|
1153
|
+
agentType: agent?.agent_type ?? "",
|
|
1154
|
+
agentVersion: agent?.agent_version ?? "",
|
|
1155
|
+
status: session.status ?? "",
|
|
1156
|
+
cwd: session.cwd ?? "",
|
|
1157
|
+
userPrompt: session.user_prompt ?? "",
|
|
1158
|
+
createdAt: session.created_at ?? "",
|
|
1159
|
+
toolCallCount: Number(session.tool_call_count ?? 0)
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1144
1162
|
getTimeline(limit = 100) {
|
|
1145
1163
|
const buckets = /* @__PURE__ */ new Map();
|
|
1146
1164
|
try {
|
|
@@ -1247,11 +1265,11 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1247
1265
|
"better-sqlite3 is not installed. Use AGENT_GATE_STORAGE=json for environments without native modules."
|
|
1248
1266
|
);
|
|
1249
1267
|
}
|
|
1250
|
-
const
|
|
1251
|
-
const dir = (0, import_path4.dirname)(
|
|
1268
|
+
const path3 = dbPath || getDefaultDbPath();
|
|
1269
|
+
const dir = (0, import_path4.dirname)(path3);
|
|
1252
1270
|
if (!(0, import_fs4.existsSync)(dir)) (0, import_fs4.mkdirSync)(dir, { recursive: true });
|
|
1253
|
-
this.dbPath =
|
|
1254
|
-
this.db = new Database(
|
|
1271
|
+
this.dbPath = path3;
|
|
1272
|
+
this.db = new Database(path3);
|
|
1255
1273
|
this.db.pragma("journal_mode = WAL");
|
|
1256
1274
|
this.db.exec(SCHEMA);
|
|
1257
1275
|
this.ensureColumn("tool_calls", "violation_graph", "violation_graph TEXT DEFAULT '{}'");
|
|
@@ -1421,11 +1439,11 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1421
1439
|
const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
|
|
1422
1440
|
let dbBytes = 0;
|
|
1423
1441
|
try {
|
|
1424
|
-
const { statSync: statSync3, existsSync:
|
|
1442
|
+
const { statSync: statSync3, existsSync: existsSync5 } = require("fs");
|
|
1425
1443
|
dbBytes = statSync3(this.dbPath).size;
|
|
1426
1444
|
for (const suffix of ["-wal", "-shm"]) {
|
|
1427
1445
|
const p = this.dbPath + suffix;
|
|
1428
|
-
if (
|
|
1446
|
+
if (existsSync5(p)) dbBytes += statSync3(p).size;
|
|
1429
1447
|
}
|
|
1430
1448
|
} catch {
|
|
1431
1449
|
}
|
|
@@ -1458,15 +1476,15 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1458
1476
|
"SELECT * FROM tool_calls WHERE id <= ? ORDER BY id"
|
|
1459
1477
|
).all(cutoff.id);
|
|
1460
1478
|
if (rows.length === 0) return { archived: 0, file: "" };
|
|
1461
|
-
const { writeFileSync:
|
|
1462
|
-
const { dirname:
|
|
1479
|
+
const { writeFileSync: writeFileSync5, mkdirSync: mkdirSync6, existsSync: existsSync5 } = require("fs");
|
|
1480
|
+
const { dirname: dirname6, join: join6 } = require("path");
|
|
1463
1481
|
const { gzipSync } = require("zlib");
|
|
1464
|
-
const archiveDir =
|
|
1465
|
-
if (!
|
|
1482
|
+
const archiveDir = join6(dirname6(this.dbPath), "archive");
|
|
1483
|
+
if (!existsSync5(archiveDir)) mkdirSync6(archiveDir, { recursive: true, mode: 448 });
|
|
1466
1484
|
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1467
|
-
const file =
|
|
1485
|
+
const file = join6(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1468
1486
|
const payload = rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
|
|
1469
|
-
|
|
1487
|
+
writeFileSync5(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1470
1488
|
const deleted = this.db.transaction(() => {
|
|
1471
1489
|
const res = this.db.prepare("DELETE FROM tool_calls WHERE id <= ?").run(cutoff.id);
|
|
1472
1490
|
this.db.prepare(`
|
|
@@ -1505,6 +1523,27 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1505
1523
|
).get(sessionId);
|
|
1506
1524
|
return row?.agent_type;
|
|
1507
1525
|
}
|
|
1526
|
+
getSessionInfo(sessionId) {
|
|
1527
|
+
const row = this.db.prepare(
|
|
1528
|
+
`SELECT s.id as session_id, s.cwd, s.user_prompt, s.status, s.created_at,
|
|
1529
|
+
s.tool_call_count,
|
|
1530
|
+
COALESCE(a.agent_type, '') as agent_type,
|
|
1531
|
+
COALESCE(a.agent_version, '') as agent_version
|
|
1532
|
+
FROM sessions s LEFT JOIN agents a ON s.agent_id = a.id
|
|
1533
|
+
WHERE s.id = ?`
|
|
1534
|
+
).get(sessionId);
|
|
1535
|
+
if (!row) return void 0;
|
|
1536
|
+
return {
|
|
1537
|
+
sessionId: String(row.session_id ?? ""),
|
|
1538
|
+
agentType: String(row.agent_type ?? ""),
|
|
1539
|
+
agentVersion: String(row.agent_version ?? ""),
|
|
1540
|
+
status: String(row.status ?? ""),
|
|
1541
|
+
cwd: String(row.cwd ?? ""),
|
|
1542
|
+
userPrompt: String(row.user_prompt ?? ""),
|
|
1543
|
+
createdAt: String(row.created_at ?? ""),
|
|
1544
|
+
toolCallCount: Number(row.tool_call_count ?? 0)
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1508
1547
|
getTimeline(limit = 100) {
|
|
1509
1548
|
const rows = this.db.prepare(`
|
|
1510
1549
|
SELECT strftime('%Y-%m-%dT%H:%M', called_at) as time,
|
|
@@ -1572,15 +1611,15 @@ function getDb(dbPath) {
|
|
|
1572
1611
|
if (rawDb) return rawDb;
|
|
1573
1612
|
try {
|
|
1574
1613
|
const Database = require("better-sqlite3");
|
|
1575
|
-
const { existsSync:
|
|
1576
|
-
const { join:
|
|
1614
|
+
const { existsSync: existsSync5, mkdirSync: mkdirSync6 } = require("fs");
|
|
1615
|
+
const { join: join6, dirname: dirname6 } = require("path");
|
|
1577
1616
|
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
1578
|
-
const xdgData = process.env.XDG_DATA_HOME ||
|
|
1579
|
-
const defaultPath =
|
|
1580
|
-
const
|
|
1581
|
-
const dir =
|
|
1582
|
-
if (!
|
|
1583
|
-
rawDb = new Database(
|
|
1617
|
+
const xdgData = process.env.XDG_DATA_HOME || join6(home, ".local", "share");
|
|
1618
|
+
const defaultPath = join6(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
1619
|
+
const path3 = dbPath || defaultPath;
|
|
1620
|
+
const dir = dirname6(path3);
|
|
1621
|
+
if (!existsSync5(dir)) mkdirSync6(dir, { recursive: true });
|
|
1622
|
+
rawDb = new Database(path3);
|
|
1584
1623
|
rawDb.pragma("journal_mode = WAL");
|
|
1585
1624
|
return rawDb;
|
|
1586
1625
|
} catch {
|
|
@@ -1622,6 +1661,598 @@ var init_db = __esm({
|
|
|
1622
1661
|
}
|
|
1623
1662
|
});
|
|
1624
1663
|
|
|
1664
|
+
// src/v3/sessionlog/events.ts
|
|
1665
|
+
function eventToDict(e) {
|
|
1666
|
+
return {
|
|
1667
|
+
type: e.type,
|
|
1668
|
+
seq: e.seq,
|
|
1669
|
+
time: e.time,
|
|
1670
|
+
turn: e.turn,
|
|
1671
|
+
step: e.step,
|
|
1672
|
+
source: e.source,
|
|
1673
|
+
data: e.data
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
function eventFromDict(raw) {
|
|
1677
|
+
return {
|
|
1678
|
+
type: raw.type,
|
|
1679
|
+
seq: Number(raw.seq),
|
|
1680
|
+
time: Number(raw.time),
|
|
1681
|
+
turn: Number(raw.turn ?? 0),
|
|
1682
|
+
step: Number(raw.step ?? 0),
|
|
1683
|
+
source: String(raw.source ?? ""),
|
|
1684
|
+
data: raw.data ?? {}
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1687
|
+
function nowMs() {
|
|
1688
|
+
return Date.now();
|
|
1689
|
+
}
|
|
1690
|
+
function base(type, seq, timeMs, data, opts = {}) {
|
|
1691
|
+
return {
|
|
1692
|
+
type,
|
|
1693
|
+
seq,
|
|
1694
|
+
time: timeMs ?? nowMs(),
|
|
1695
|
+
turn: opts.turn ?? 0,
|
|
1696
|
+
step: opts.step ?? 0,
|
|
1697
|
+
source: opts.source ?? "",
|
|
1698
|
+
data
|
|
1699
|
+
};
|
|
1700
|
+
}
|
|
1701
|
+
function sessionStart(seq, opts = {}) {
|
|
1702
|
+
return base("session/start", seq, opts.timeMs, { session: opts.meta ?? {} }, { source: opts.source });
|
|
1703
|
+
}
|
|
1704
|
+
function sessionEnd(seq, reason = "", opts = {}) {
|
|
1705
|
+
return base("session/end", seq, opts.timeMs, { reason }, { source: opts.source });
|
|
1706
|
+
}
|
|
1707
|
+
function userPrompt(seq, content, opts = {}) {
|
|
1708
|
+
return base("user/prompt", seq, opts.timeMs, { content, role: "user" }, { turn: opts.turn, source: opts.source });
|
|
1709
|
+
}
|
|
1710
|
+
function llmRequest(seq, model, opts = {}) {
|
|
1711
|
+
return base("llm/request", seq, opts.timeMs, {
|
|
1712
|
+
model,
|
|
1713
|
+
messages_count: opts.messagesCount ?? 0,
|
|
1714
|
+
provider: opts.provider ?? "",
|
|
1715
|
+
request_meta: opts.requestMeta ?? {}
|
|
1716
|
+
}, { turn: opts.turn, source: opts.source });
|
|
1717
|
+
}
|
|
1718
|
+
function llmChunk(seq, chunk, opts = {}) {
|
|
1719
|
+
return base("llm/chunk", seq, opts.timeMs, { chunk }, { turn: opts.turn, step: opts.step, source: opts.source });
|
|
1720
|
+
}
|
|
1721
|
+
function llmResponse(seq, content, opts = {}) {
|
|
1722
|
+
return base("llm/response", seq, opts.timeMs, { content, model: opts.model ?? "", usage: opts.usage ?? {} }, { turn: opts.turn, step: opts.step, source: opts.source });
|
|
1723
|
+
}
|
|
1724
|
+
function toolCall(seq, name, argumentsRaw, callId, opts = {}) {
|
|
1725
|
+
return base("tool/call", seq, opts.timeMs, { name, arguments: argumentsRaw, callId }, { turn: opts.turn, step: opts.step, source: opts.source });
|
|
1726
|
+
}
|
|
1727
|
+
function toolResult(seq, callId, content, opts = {}) {
|
|
1728
|
+
return base("tool/result", seq, opts.timeMs, { callId, content, error: opts.error ?? {} }, { turn: opts.turn, step: opts.step, source: opts.source });
|
|
1729
|
+
}
|
|
1730
|
+
function processExec(seq, command, opts = {}) {
|
|
1731
|
+
return base("process/exec", seq, opts.timeMs, { command, argv: opts.argv ?? [], pid: opts.pid, cwd: opts.cwd ?? "" }, { turn: opts.turn, source: opts.source });
|
|
1732
|
+
}
|
|
1733
|
+
function processResult(seq, command, output, opts = {}) {
|
|
1734
|
+
return base("process/result", seq, opts.timeMs, { command, output, exit_code: opts.exitCode, pid: opts.pid }, { source: opts.source });
|
|
1735
|
+
}
|
|
1736
|
+
function syscallEvent(seq, syscall, opts = {}) {
|
|
1737
|
+
return base("syscall/event", seq, opts.timeMs, { syscall, argv: opts.argv ?? [], pid: opts.pid }, { source: opts.source });
|
|
1738
|
+
}
|
|
1739
|
+
function systemEvent(seq, kind, detail, opts = {}) {
|
|
1740
|
+
return base("system", seq, opts.timeMs, { kind, detail }, { source: opts.source });
|
|
1741
|
+
}
|
|
1742
|
+
var init_events = __esm({
|
|
1743
|
+
"src/v3/sessionlog/events.ts"() {
|
|
1744
|
+
"use strict";
|
|
1745
|
+
init_cjs_shims();
|
|
1746
|
+
}
|
|
1747
|
+
});
|
|
1748
|
+
|
|
1749
|
+
// src/v3/sessionlog/log.ts
|
|
1750
|
+
var SessionLog;
|
|
1751
|
+
var init_log = __esm({
|
|
1752
|
+
"src/v3/sessionlog/log.ts"() {
|
|
1753
|
+
"use strict";
|
|
1754
|
+
init_cjs_shims();
|
|
1755
|
+
init_events();
|
|
1756
|
+
SessionLog = class _SessionLog {
|
|
1757
|
+
sessionId;
|
|
1758
|
+
eventsList;
|
|
1759
|
+
constructor(sessionId = "", events = []) {
|
|
1760
|
+
this.sessionId = sessionId;
|
|
1761
|
+
this.eventsList = [...events];
|
|
1762
|
+
this.renumber();
|
|
1763
|
+
}
|
|
1764
|
+
append(event) {
|
|
1765
|
+
try {
|
|
1766
|
+
JSON.stringify(event.data);
|
|
1767
|
+
} catch {
|
|
1768
|
+
throw new Error(`SessionLog: event data not JSON-serializable: ${event.type}`);
|
|
1769
|
+
}
|
|
1770
|
+
event.seq = this.eventsList.length;
|
|
1771
|
+
this.eventsList.push(event);
|
|
1772
|
+
return event;
|
|
1773
|
+
}
|
|
1774
|
+
appendMany(events) {
|
|
1775
|
+
return events.map((e) => this.append(e));
|
|
1776
|
+
}
|
|
1777
|
+
get length() {
|
|
1778
|
+
return this.eventsList.length;
|
|
1779
|
+
}
|
|
1780
|
+
get nextSeq() {
|
|
1781
|
+
return this.eventsList.length;
|
|
1782
|
+
}
|
|
1783
|
+
get events() {
|
|
1784
|
+
return [...this.eventsList];
|
|
1785
|
+
}
|
|
1786
|
+
byType(type) {
|
|
1787
|
+
return this.eventsList.filter((e) => e.type === type);
|
|
1788
|
+
}
|
|
1789
|
+
toolCalls() {
|
|
1790
|
+
return this.byType("tool/call");
|
|
1791
|
+
}
|
|
1792
|
+
toolResults() {
|
|
1793
|
+
return this.byType("tool/result");
|
|
1794
|
+
}
|
|
1795
|
+
pairToolCalls() {
|
|
1796
|
+
const results = /* @__PURE__ */ new Map();
|
|
1797
|
+
for (const r of this.toolResults()) {
|
|
1798
|
+
results.set(String(r.data.callId), r);
|
|
1799
|
+
}
|
|
1800
|
+
return this.toolCalls().map((c) => [c, results.get(String(c.data.callId)) ?? null]);
|
|
1801
|
+
}
|
|
1802
|
+
/** Derive model-visible message history from the log (AgentGate semantics). */
|
|
1803
|
+
deriveMessages() {
|
|
1804
|
+
const messages = [];
|
|
1805
|
+
for (const e of this.eventsList) {
|
|
1806
|
+
if (e.type === "user/prompt") {
|
|
1807
|
+
messages.push({ role: "user", content: String(e.data.content ?? "") });
|
|
1808
|
+
} else if (e.type === "llm/response") {
|
|
1809
|
+
const content = String(e.data.content ?? "");
|
|
1810
|
+
const calls = this.toolCalls().filter((c) => c.turn === e.turn && c.step === e.step).map((c) => c.data);
|
|
1811
|
+
const msg = { role: "assistant", content };
|
|
1812
|
+
if (calls.length > 0) msg.tool_calls = calls;
|
|
1813
|
+
messages.push(msg);
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
return messages;
|
|
1817
|
+
}
|
|
1818
|
+
toDicts() {
|
|
1819
|
+
return this.eventsList.map((e) => eventToDict(e));
|
|
1820
|
+
}
|
|
1821
|
+
toJson(indent) {
|
|
1822
|
+
return JSON.stringify(this.toDicts(), null, indent);
|
|
1823
|
+
}
|
|
1824
|
+
static fromDicts(rawList, sessionId = "") {
|
|
1825
|
+
return new _SessionLog(sessionId, rawList.map((r) => eventFromDict(r)));
|
|
1826
|
+
}
|
|
1827
|
+
static fromJson(text, sessionId = "") {
|
|
1828
|
+
return _SessionLog.fromDicts(JSON.parse(text), sessionId);
|
|
1829
|
+
}
|
|
1830
|
+
replay(visitor) {
|
|
1831
|
+
for (const e of this.eventsList) visitor(e);
|
|
1832
|
+
}
|
|
1833
|
+
renumber() {
|
|
1834
|
+
this.eventsList.forEach((e, i) => {
|
|
1835
|
+
e.seq = i;
|
|
1836
|
+
});
|
|
1837
|
+
}
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
});
|
|
1841
|
+
|
|
1842
|
+
// src/v3/sessionlog/trajectory.ts
|
|
1843
|
+
function asText(value) {
|
|
1844
|
+
if (value === null || value === void 0) return "";
|
|
1845
|
+
if (typeof value === "string") return value;
|
|
1846
|
+
return JSON.stringify(value);
|
|
1847
|
+
}
|
|
1848
|
+
function buildTrajectory(log) {
|
|
1849
|
+
const records = [];
|
|
1850
|
+
const toolTimes = /* @__PURE__ */ new Map();
|
|
1851
|
+
const procTimes = /* @__PURE__ */ new Map();
|
|
1852
|
+
for (const e of log.events) {
|
|
1853
|
+
switch (e.type) {
|
|
1854
|
+
case "session/start":
|
|
1855
|
+
records.push({ kind: "system", seq: e.seq, time: e.time, detail: "session/start" });
|
|
1856
|
+
break;
|
|
1857
|
+
case "session/end":
|
|
1858
|
+
records.push({ kind: "system", seq: e.seq, time: e.time, detail: "session/end" });
|
|
1859
|
+
break;
|
|
1860
|
+
case "user/prompt":
|
|
1861
|
+
records.push({
|
|
1862
|
+
kind: "user",
|
|
1863
|
+
seq: e.seq,
|
|
1864
|
+
time: e.time,
|
|
1865
|
+
turn: e.turn,
|
|
1866
|
+
content: asText(e.data.content)
|
|
1867
|
+
});
|
|
1868
|
+
break;
|
|
1869
|
+
case "llm/response":
|
|
1870
|
+
records.push({
|
|
1871
|
+
kind: "llm",
|
|
1872
|
+
seq: e.seq,
|
|
1873
|
+
time: e.time,
|
|
1874
|
+
turn: e.turn,
|
|
1875
|
+
step: e.step,
|
|
1876
|
+
model: String(e.data.model ?? ""),
|
|
1877
|
+
content: asText(e.data.content),
|
|
1878
|
+
usage: e.data.usage ?? {}
|
|
1879
|
+
});
|
|
1880
|
+
break;
|
|
1881
|
+
case "tool/call":
|
|
1882
|
+
toolTimes.set(String(e.data.callId ?? ""), e.time);
|
|
1883
|
+
records.push({
|
|
1884
|
+
kind: "tool",
|
|
1885
|
+
seq: e.seq,
|
|
1886
|
+
time: e.time,
|
|
1887
|
+
turn: e.turn,
|
|
1888
|
+
step: e.step,
|
|
1889
|
+
call_id: String(e.data.callId ?? ""),
|
|
1890
|
+
name: String(e.data.name ?? ""),
|
|
1891
|
+
arguments: String(e.data.arguments ?? ""),
|
|
1892
|
+
result: null,
|
|
1893
|
+
error: null,
|
|
1894
|
+
duration_ms: null,
|
|
1895
|
+
source: e.source
|
|
1896
|
+
});
|
|
1897
|
+
break;
|
|
1898
|
+
case "tool/result": {
|
|
1899
|
+
const callId = String(e.data.callId ?? "");
|
|
1900
|
+
const start = toolTimes.get(callId);
|
|
1901
|
+
const duration = start !== void 0 ? e.time - start : null;
|
|
1902
|
+
const matches = records.filter((r) => r.kind === "tool" && r.call_id === callId);
|
|
1903
|
+
if (matches.length > 0) {
|
|
1904
|
+
const r = matches[matches.length - 1];
|
|
1905
|
+
r.result = e.data.content;
|
|
1906
|
+
r.error = e.data.error || null;
|
|
1907
|
+
r.duration_ms = duration;
|
|
1908
|
+
} else {
|
|
1909
|
+
records.push({
|
|
1910
|
+
kind: "tool",
|
|
1911
|
+
seq: e.seq,
|
|
1912
|
+
time: e.time,
|
|
1913
|
+
turn: e.turn,
|
|
1914
|
+
step: e.step,
|
|
1915
|
+
call_id: callId,
|
|
1916
|
+
name: "",
|
|
1917
|
+
arguments: "",
|
|
1918
|
+
result: e.data.content,
|
|
1919
|
+
error: e.data.error || null,
|
|
1920
|
+
duration_ms: duration,
|
|
1921
|
+
source: e.source
|
|
1922
|
+
});
|
|
1923
|
+
}
|
|
1924
|
+
break;
|
|
1925
|
+
}
|
|
1926
|
+
case "process/exec": {
|
|
1927
|
+
const key = String(e.data.pid ?? e.data.command ?? "");
|
|
1928
|
+
procTimes.set(key, e.time);
|
|
1929
|
+
records.push({
|
|
1930
|
+
kind: "process",
|
|
1931
|
+
seq: e.seq,
|
|
1932
|
+
time: e.time,
|
|
1933
|
+
turn: e.turn,
|
|
1934
|
+
command: String(e.data.command ?? ""),
|
|
1935
|
+
argv: e.data.argv ?? [],
|
|
1936
|
+
pid: e.data.pid,
|
|
1937
|
+
cwd: String(e.data.cwd ?? ""),
|
|
1938
|
+
output: null,
|
|
1939
|
+
exit_code: null,
|
|
1940
|
+
duration_ms: null
|
|
1941
|
+
});
|
|
1942
|
+
break;
|
|
1943
|
+
}
|
|
1944
|
+
case "process/result": {
|
|
1945
|
+
const key = String(e.data.pid ?? e.data.command ?? "");
|
|
1946
|
+
const start = procTimes.get(key);
|
|
1947
|
+
const duration = start !== void 0 ? e.time - start : null;
|
|
1948
|
+
const matches = records.filter((r) => r.kind === "process" && r.pid === e.data.pid);
|
|
1949
|
+
if (matches.length > 0) {
|
|
1950
|
+
const r = matches[matches.length - 1];
|
|
1951
|
+
r.output = asText(e.data.output);
|
|
1952
|
+
r.exit_code = e.data.exit_code;
|
|
1953
|
+
r.duration_ms = duration;
|
|
1954
|
+
} else {
|
|
1955
|
+
records.push({
|
|
1956
|
+
kind: "process",
|
|
1957
|
+
seq: e.seq,
|
|
1958
|
+
time: e.time,
|
|
1959
|
+
turn: e.turn,
|
|
1960
|
+
command: String(e.data.command ?? ""),
|
|
1961
|
+
argv: [],
|
|
1962
|
+
pid: e.data.pid,
|
|
1963
|
+
cwd: "",
|
|
1964
|
+
output: asText(e.data.output),
|
|
1965
|
+
exit_code: e.data.exit_code,
|
|
1966
|
+
duration_ms: duration
|
|
1967
|
+
});
|
|
1968
|
+
}
|
|
1969
|
+
break;
|
|
1970
|
+
}
|
|
1971
|
+
case "syscall/event":
|
|
1972
|
+
records.push({
|
|
1973
|
+
kind: "syscall",
|
|
1974
|
+
seq: e.seq,
|
|
1975
|
+
time: e.time,
|
|
1976
|
+
syscall: String(e.data.syscall ?? ""),
|
|
1977
|
+
argv: e.data.argv ?? [],
|
|
1978
|
+
pid: e.data.pid
|
|
1979
|
+
});
|
|
1980
|
+
break;
|
|
1981
|
+
case "system":
|
|
1982
|
+
records.push({
|
|
1983
|
+
kind: "system",
|
|
1984
|
+
seq: e.seq,
|
|
1985
|
+
time: e.time,
|
|
1986
|
+
detail: String(e.data.kind ?? ""),
|
|
1987
|
+
content: e.data.detail
|
|
1988
|
+
});
|
|
1989
|
+
break;
|
|
1990
|
+
default:
|
|
1991
|
+
break;
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
records.sort((a, b) => Number(a.seq) - Number(b.seq));
|
|
1995
|
+
return records;
|
|
1996
|
+
}
|
|
1997
|
+
function summarize(log) {
|
|
1998
|
+
const events = log.events;
|
|
1999
|
+
if (events.length === 0) {
|
|
2000
|
+
return {
|
|
2001
|
+
turns: 0,
|
|
2002
|
+
llm_calls: 0,
|
|
2003
|
+
tool_calls: 0,
|
|
2004
|
+
tool_errors: 0,
|
|
2005
|
+
process_execs: 0,
|
|
2006
|
+
syscalls: 0,
|
|
2007
|
+
input_tokens: 0,
|
|
2008
|
+
output_tokens: 0,
|
|
2009
|
+
start_time: null,
|
|
2010
|
+
end_time: null
|
|
2011
|
+
};
|
|
2012
|
+
}
|
|
2013
|
+
const times = events.map((e) => e.time);
|
|
2014
|
+
const start = Math.min(...times);
|
|
2015
|
+
const end = Math.max(...times);
|
|
2016
|
+
let usageIn = 0;
|
|
2017
|
+
let usageOut = 0;
|
|
2018
|
+
for (const e of events) {
|
|
2019
|
+
if (e.type === "llm/response") {
|
|
2020
|
+
const u = e.data.usage ?? {};
|
|
2021
|
+
usageIn += Number(u.input_tokens ?? u.prompt_tokens ?? 0) || 0;
|
|
2022
|
+
usageOut += Number(u.output_tokens ?? u.completion_tokens ?? 0) || 0;
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
return {
|
|
2026
|
+
turns: new Set(events.filter((e) => e.turn).map((e) => e.turn)).size,
|
|
2027
|
+
llm_calls: events.filter((e) => e.type === "llm/response").length,
|
|
2028
|
+
tool_calls: events.filter((e) => e.type === "tool/call").length,
|
|
2029
|
+
tool_errors: events.filter((e) => {
|
|
2030
|
+
if (e.type !== "tool/result") return false;
|
|
2031
|
+
const err = e.data.error;
|
|
2032
|
+
return !!err && Object.keys(err).length > 0;
|
|
2033
|
+
}).length,
|
|
2034
|
+
process_execs: events.filter((e) => e.type === "process/exec").length,
|
|
2035
|
+
syscalls: events.filter((e) => e.type === "syscall/event").length,
|
|
2036
|
+
input_tokens: usageIn,
|
|
2037
|
+
output_tokens: usageOut,
|
|
2038
|
+
start_time: start,
|
|
2039
|
+
end_time: end,
|
|
2040
|
+
duration_ms: end - start
|
|
2041
|
+
};
|
|
2042
|
+
}
|
|
2043
|
+
var init_trajectory = __esm({
|
|
2044
|
+
"src/v3/sessionlog/trajectory.ts"() {
|
|
2045
|
+
"use strict";
|
|
2046
|
+
init_cjs_shims();
|
|
2047
|
+
}
|
|
2048
|
+
});
|
|
2049
|
+
|
|
2050
|
+
// src/v3/sessionlog/persistence.ts
|
|
2051
|
+
function saveAppend(log, filePath) {
|
|
2052
|
+
fs.mkdirSync(path.dirname(path.resolve(filePath)), { recursive: true });
|
|
2053
|
+
const lines = log.events.map((e) => JSON.stringify(eventToDict2(e)));
|
|
2054
|
+
fs.appendFileSync(filePath, lines.map((l) => l + "\n").join(""), "utf-8");
|
|
2055
|
+
}
|
|
2056
|
+
function saveSnapshot(log, filePath) {
|
|
2057
|
+
fs.mkdirSync(path.dirname(path.resolve(filePath)), { recursive: true });
|
|
2058
|
+
const lines = log.events.map((e) => JSON.stringify(eventToDict2(e)));
|
|
2059
|
+
fs.writeFileSync(filePath, lines.map((l) => l + "\n").join(""), "utf-8");
|
|
2060
|
+
}
|
|
2061
|
+
function load(filePath, sessionId = "") {
|
|
2062
|
+
const events = [];
|
|
2063
|
+
if (!fs.existsSync(filePath)) return new SessionLog(sessionId);
|
|
2064
|
+
const text = fs.readFileSync(filePath, "utf-8");
|
|
2065
|
+
for (const line of text.split("\n")) {
|
|
2066
|
+
const trimmed = line.trim();
|
|
2067
|
+
if (!trimmed) continue;
|
|
2068
|
+
try {
|
|
2069
|
+
events.push(eventFromDict(JSON.parse(trimmed)));
|
|
2070
|
+
} catch {
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
return new SessionLog(sessionId, events);
|
|
2074
|
+
}
|
|
2075
|
+
function eventToDict2(e) {
|
|
2076
|
+
return {
|
|
2077
|
+
type: e.type,
|
|
2078
|
+
seq: e.seq,
|
|
2079
|
+
time: e.time,
|
|
2080
|
+
turn: e.turn,
|
|
2081
|
+
step: e.step,
|
|
2082
|
+
source: e.source,
|
|
2083
|
+
data: e.data
|
|
2084
|
+
};
|
|
2085
|
+
}
|
|
2086
|
+
var fs, path;
|
|
2087
|
+
var init_persistence = __esm({
|
|
2088
|
+
"src/v3/sessionlog/persistence.ts"() {
|
|
2089
|
+
"use strict";
|
|
2090
|
+
init_cjs_shims();
|
|
2091
|
+
fs = __toESM(require("fs"));
|
|
2092
|
+
path = __toESM(require("path"));
|
|
2093
|
+
init_events();
|
|
2094
|
+
init_log();
|
|
2095
|
+
}
|
|
2096
|
+
});
|
|
2097
|
+
|
|
2098
|
+
// src/v3/sessionlog/convert.ts
|
|
2099
|
+
function fromNormalized(event, opts = {}) {
|
|
2100
|
+
const collector = String(event.source_collector ?? "");
|
|
2101
|
+
const sid = opts.sessionId ?? String(event.session_id ?? "");
|
|
2102
|
+
const ts = opts.timeMs ?? Date.now();
|
|
2103
|
+
const action = event.action ?? {};
|
|
2104
|
+
const payload = event.payload ?? {};
|
|
2105
|
+
const toolName = String(action.tool_name ?? "");
|
|
2106
|
+
const callId = String(action.tool_call_id ?? "");
|
|
2107
|
+
const argumentsRaw = String(action.arguments_raw ?? "{}");
|
|
2108
|
+
if (collector === "llm_api_proxy") {
|
|
2109
|
+
const out = [];
|
|
2110
|
+
const userText = payload.user_prompt;
|
|
2111
|
+
if (userText) out.push(userPrompt(out.length, String(userText), { turn: opts.turn, timeMs: ts, source: "llm" }));
|
|
2112
|
+
if (toolName) {
|
|
2113
|
+
out.push(toolCall(out.length, toolName, argumentsRaw, callId, {
|
|
2114
|
+
turn: opts.turn,
|
|
2115
|
+
step: opts.step,
|
|
2116
|
+
timeMs: ts,
|
|
2117
|
+
source: "llm"
|
|
2118
|
+
}));
|
|
2119
|
+
}
|
|
2120
|
+
const response = payload.tool_response_content;
|
|
2121
|
+
if (response !== void 0 && response !== null) {
|
|
2122
|
+
out.push(toolResult(out.length, callId, response, { turn: opts.turn, step: opts.step, timeMs: ts, source: "llm" }));
|
|
2123
|
+
}
|
|
2124
|
+
return out;
|
|
2125
|
+
}
|
|
2126
|
+
if (collector === "mcp") {
|
|
2127
|
+
const out = [];
|
|
2128
|
+
if (toolName) {
|
|
2129
|
+
out.push(toolCall(out.length, toolName, argumentsRaw, callId, {
|
|
2130
|
+
turn: opts.turn,
|
|
2131
|
+
step: opts.step,
|
|
2132
|
+
timeMs: ts,
|
|
2133
|
+
source: "mcp"
|
|
2134
|
+
}));
|
|
2135
|
+
}
|
|
2136
|
+
const rawResp = payload.mcp_response ?? event.response;
|
|
2137
|
+
if (rawResp !== void 0 && rawResp !== null) {
|
|
2138
|
+
out.push(toolResult(out.length, callId, rawResp, { turn: opts.turn, step: opts.step, timeMs: ts, source: "mcp" }));
|
|
2139
|
+
}
|
|
2140
|
+
return out;
|
|
2141
|
+
}
|
|
2142
|
+
if (collector === "pty") {
|
|
2143
|
+
const command = String(action.command ?? event.command ?? "");
|
|
2144
|
+
const pid = event.process && typeof event.process === "object" ? Number(event.process.pid) : void 0;
|
|
2145
|
+
if (command) {
|
|
2146
|
+
return [processExec(0, command, { pid, cwd: String(event.cwd ?? ""), turn: opts.turn, timeMs: ts, source: "pty" })];
|
|
2147
|
+
}
|
|
2148
|
+
return [];
|
|
2149
|
+
}
|
|
2150
|
+
if (collector === "ebpf") {
|
|
2151
|
+
const syscall = String(action.syscall ?? action.syscall_type ?? toolName);
|
|
2152
|
+
const pid = event.process && typeof event.process === "object" ? Number(event.process.pid) : void 0;
|
|
2153
|
+
if (syscall) {
|
|
2154
|
+
return [syscallEvent(0, syscall, { pid, timeMs: ts, source: "ebpf" })];
|
|
2155
|
+
}
|
|
2156
|
+
return [];
|
|
2157
|
+
}
|
|
2158
|
+
return [];
|
|
2159
|
+
}
|
|
2160
|
+
var path2, DEFAULT_LOG_DIR, SessionLogRecorder, defaultRecorder;
|
|
2161
|
+
var init_convert = __esm({
|
|
2162
|
+
"src/v3/sessionlog/convert.ts"() {
|
|
2163
|
+
"use strict";
|
|
2164
|
+
init_cjs_shims();
|
|
2165
|
+
path2 = __toESM(require("path"));
|
|
2166
|
+
init_events();
|
|
2167
|
+
init_log();
|
|
2168
|
+
init_persistence();
|
|
2169
|
+
DEFAULT_LOG_DIR = path2.join(
|
|
2170
|
+
process.env.HOME || process.env.USERPROFILE || "~",
|
|
2171
|
+
".agentgate",
|
|
2172
|
+
"sessionlogs"
|
|
2173
|
+
);
|
|
2174
|
+
SessionLogRecorder = class {
|
|
2175
|
+
logDir;
|
|
2176
|
+
enabled;
|
|
2177
|
+
logs = /* @__PURE__ */ new Map();
|
|
2178
|
+
turns = /* @__PURE__ */ new Map();
|
|
2179
|
+
steps = /* @__PURE__ */ new Map();
|
|
2180
|
+
constructor(opts = {}) {
|
|
2181
|
+
this.logDir = opts.logDir ?? DEFAULT_LOG_DIR;
|
|
2182
|
+
this.enabled = opts.enabled ?? true;
|
|
2183
|
+
}
|
|
2184
|
+
record(event, sessionId = "") {
|
|
2185
|
+
if (!this.enabled) return;
|
|
2186
|
+
const sid = sessionId || String(event.session_id ?? "");
|
|
2187
|
+
if (!sid) return;
|
|
2188
|
+
try {
|
|
2189
|
+
let log = this.logs.get(sid);
|
|
2190
|
+
if (!log) {
|
|
2191
|
+
log = new SessionLog(sid);
|
|
2192
|
+
this.logs.set(sid, log);
|
|
2193
|
+
this.turns.set(sid, 0);
|
|
2194
|
+
this.steps.set(sid, 0);
|
|
2195
|
+
}
|
|
2196
|
+
const turn = this.turns.get(sid) ?? 0;
|
|
2197
|
+
const step = this.steps.get(sid) ?? 0;
|
|
2198
|
+
const events = fromNormalized(event, { sessionId: sid, turn, step });
|
|
2199
|
+
if (events.length === 0) return;
|
|
2200
|
+
for (const e of events) log.append(e);
|
|
2201
|
+
if (events.some((e) => e.type === "user/prompt")) this.turns.set(sid, turn + 1);
|
|
2202
|
+
if (events.some((e) => e.type === "tool/call")) this.steps.set(sid, step + 1);
|
|
2203
|
+
saveAppend(log, path2.join(this.logDir, `${sid}.jsonl`));
|
|
2204
|
+
} catch (e) {
|
|
2205
|
+
console.warn("sessionlog record failed:", e);
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
sessionLog(sessionId) {
|
|
2209
|
+
return this.logs.get(sessionId) ?? null;
|
|
2210
|
+
}
|
|
2211
|
+
};
|
|
2212
|
+
defaultRecorder = new SessionLogRecorder();
|
|
2213
|
+
}
|
|
2214
|
+
});
|
|
2215
|
+
|
|
2216
|
+
// src/v3/sessionlog/index.ts
|
|
2217
|
+
var sessionlog_exports = {};
|
|
2218
|
+
__export(sessionlog_exports, {
|
|
2219
|
+
DEFAULT_LOG_DIR: () => DEFAULT_LOG_DIR,
|
|
2220
|
+
SessionLog: () => SessionLog,
|
|
2221
|
+
SessionLogRecorder: () => SessionLogRecorder,
|
|
2222
|
+
buildTrajectory: () => buildTrajectory,
|
|
2223
|
+
defaultRecorder: () => defaultRecorder,
|
|
2224
|
+
eventFromDict: () => eventFromDict,
|
|
2225
|
+
eventToDict: () => eventToDict,
|
|
2226
|
+
fromNormalized: () => fromNormalized,
|
|
2227
|
+
llmChunk: () => llmChunk,
|
|
2228
|
+
llmRequest: () => llmRequest,
|
|
2229
|
+
llmResponse: () => llmResponse,
|
|
2230
|
+
load: () => load,
|
|
2231
|
+
processExec: () => processExec,
|
|
2232
|
+
processResult: () => processResult,
|
|
2233
|
+
saveAppend: () => saveAppend,
|
|
2234
|
+
saveSnapshot: () => saveSnapshot,
|
|
2235
|
+
sessionEnd: () => sessionEnd,
|
|
2236
|
+
sessionStart: () => sessionStart,
|
|
2237
|
+
summarize: () => summarize,
|
|
2238
|
+
syscallEvent: () => syscallEvent,
|
|
2239
|
+
systemEvent: () => systemEvent,
|
|
2240
|
+
toolCall: () => toolCall,
|
|
2241
|
+
toolResult: () => toolResult,
|
|
2242
|
+
userPrompt: () => userPrompt
|
|
2243
|
+
});
|
|
2244
|
+
var init_sessionlog = __esm({
|
|
2245
|
+
"src/v3/sessionlog/index.ts"() {
|
|
2246
|
+
"use strict";
|
|
2247
|
+
init_cjs_shims();
|
|
2248
|
+
init_events();
|
|
2249
|
+
init_log();
|
|
2250
|
+
init_trajectory();
|
|
2251
|
+
init_persistence();
|
|
2252
|
+
init_convert();
|
|
2253
|
+
}
|
|
2254
|
+
});
|
|
2255
|
+
|
|
1625
2256
|
// src/v1/server.ts
|
|
1626
2257
|
var server_exports = {};
|
|
1627
2258
|
__export(server_exports, {
|
|
@@ -1643,7 +2274,7 @@ var import_zod = require("zod");
|
|
|
1643
2274
|
|
|
1644
2275
|
// src/version.ts
|
|
1645
2276
|
init_cjs_shims();
|
|
1646
|
-
var _version = true ? "0.9.
|
|
2277
|
+
var _version = true ? "0.9.11" : (() => {
|
|
1647
2278
|
try {
|
|
1648
2279
|
const require2 = createRequire(importMetaUrl);
|
|
1649
2280
|
const pkg = require2("../package.json");
|
|
@@ -1711,6 +2342,10 @@ var AgentGateResponseSchema = import_zod.z.object({
|
|
|
1711
2342
|
analysis_duration_ms: import_zod.z.number().default(0),
|
|
1712
2343
|
// 结构化攻击链图(组合式拦截时非空;前端弹窗画图用)
|
|
1713
2344
|
violation_graph: import_zod.z.any().nullable().optional(),
|
|
2345
|
+
/** 命中的策略/性质描述(与 Python 版响应字段对齐) */
|
|
2346
|
+
policy: import_zod.z.string().default(""),
|
|
2347
|
+
/** 判定来源:agent_moss / cache(与 Python 版对齐) */
|
|
2348
|
+
source: import_zod.z.string().default("agent_moss"),
|
|
1714
2349
|
oversize: import_zod.z.boolean().optional().describe("\u672C\u5730\u5B58\u50A8\u662F\u5426\u8D85\u8FC7\u6E05\u7406\u9608\u503C\uFF08agg \u7528\uFF09"),
|
|
1715
2350
|
thresholdMB: import_zod.z.number().optional().describe("\u5B58\u50A8\u6E05\u7406\u9608\u503C MB\uFF08agg \u7528\uFF09"),
|
|
1716
2351
|
collected_context: import_zod.z.object({
|
|
@@ -1938,6 +2573,9 @@ function getTimeline(limit) {
|
|
|
1938
2573
|
function getSessionAgentType(sessionId) {
|
|
1939
2574
|
return store().getSessionAgentType(sessionId);
|
|
1940
2575
|
}
|
|
2576
|
+
function getSessionInfo(sessionId) {
|
|
2577
|
+
return store().getSessionInfo(sessionId);
|
|
2578
|
+
}
|
|
1941
2579
|
|
|
1942
2580
|
// src/v1/routes.ts
|
|
1943
2581
|
init_multi_session();
|
|
@@ -1992,6 +2630,7 @@ async function analyzeRoute(c) {
|
|
|
1992
2630
|
return c.json({
|
|
1993
2631
|
...cached2,
|
|
1994
2632
|
analysis_duration_ms: 0,
|
|
2633
|
+
source: "cache",
|
|
1995
2634
|
collected_context: {},
|
|
1996
2635
|
...storageOversizeInfo()
|
|
1997
2636
|
});
|
|
@@ -2055,6 +2694,9 @@ async function analyzeRoute(c) {
|
|
|
2055
2694
|
confidence: mossResult.confidence,
|
|
2056
2695
|
analysis_duration_ms: Math.round(durationMs * 10) / 10,
|
|
2057
2696
|
violation_graph: mossResult.violation_graph ?? null,
|
|
2697
|
+
// 与 Python 版响应字段对齐(policy / source)
|
|
2698
|
+
policy: mossResult.policy ?? "",
|
|
2699
|
+
source: "agent_moss",
|
|
2058
2700
|
...storageOversizeInfo(),
|
|
2059
2701
|
collected_context: {
|
|
2060
2702
|
os: context.os,
|
|
@@ -2086,7 +2728,18 @@ async function sessionsRoute(c) {
|
|
|
2086
2728
|
}
|
|
2087
2729
|
}
|
|
2088
2730
|
const rows = queryToolCalls({ sessionId, limit: 100 });
|
|
2089
|
-
|
|
2731
|
+
const info = getSessionInfo(sessionId);
|
|
2732
|
+
return c.json({
|
|
2733
|
+
session_id: sessionId,
|
|
2734
|
+
agent_type: info?.agentType ?? "",
|
|
2735
|
+
agent_version: info?.agentVersion ?? "",
|
|
2736
|
+
status: info?.status ?? "",
|
|
2737
|
+
cwd: info?.cwd ?? "",
|
|
2738
|
+
user_prompt: info?.userPrompt ?? "",
|
|
2739
|
+
created_at: info?.createdAt ?? "",
|
|
2740
|
+
tool_call_count: info?.toolCallCount ?? 0,
|
|
2741
|
+
tool_calls: rows
|
|
2742
|
+
});
|
|
2090
2743
|
}
|
|
2091
2744
|
async function toolCallsRoute(c) {
|
|
2092
2745
|
const sessionId = c.req.query("session_id") || void 0;
|
|
@@ -2136,6 +2789,61 @@ function deleteToolCallsRoute(c) {
|
|
|
2136
2789
|
const deleted = clearToolCalls();
|
|
2137
2790
|
return c.json({ deleted });
|
|
2138
2791
|
}
|
|
2792
|
+
async function sessionLogsRoute(c) {
|
|
2793
|
+
const { readdirSync: readdirSync2, statSync: statSync3 } = await import("fs");
|
|
2794
|
+
const { join: join6 } = await import("path");
|
|
2795
|
+
const { load: load2, summarize: summarize2, DEFAULT_LOG_DIR: DEFAULT_LOG_DIR2 } = await Promise.resolve().then(() => (init_sessionlog(), sessionlog_exports));
|
|
2796
|
+
const dir = DEFAULT_LOG_DIR2;
|
|
2797
|
+
let files = [];
|
|
2798
|
+
try {
|
|
2799
|
+
files = readdirSync2(dir).filter((f) => f.endsWith(".jsonl"));
|
|
2800
|
+
} catch {
|
|
2801
|
+
files = [];
|
|
2802
|
+
}
|
|
2803
|
+
const logs = files.map((f) => {
|
|
2804
|
+
const full = join6(dir, f);
|
|
2805
|
+
let mtime = 0;
|
|
2806
|
+
try {
|
|
2807
|
+
mtime = statSync3(full).mtimeMs;
|
|
2808
|
+
} catch {
|
|
2809
|
+
}
|
|
2810
|
+
return { full, mtime };
|
|
2811
|
+
}).sort((a, b) => b.mtime - a.mtime).slice(0, 50).map(({ full, mtime }) => {
|
|
2812
|
+
const sid = full.split(/[\\/]/).pop().replace(/\.jsonl$/, "");
|
|
2813
|
+
let summary = {};
|
|
2814
|
+
try {
|
|
2815
|
+
summary = summarize2(load2(full, sid));
|
|
2816
|
+
} catch {
|
|
2817
|
+
}
|
|
2818
|
+
return { session_id: sid, file: full, mtime: Math.round(mtime), summary };
|
|
2819
|
+
});
|
|
2820
|
+
return c.json({ total: logs.length, logs });
|
|
2821
|
+
}
|
|
2822
|
+
async function sessionLogDetailRoute(c) {
|
|
2823
|
+
const { existsSync: existsSync5 } = await import("fs");
|
|
2824
|
+
const { join: join6 } = await import("path");
|
|
2825
|
+
const { load: load2, summarize: summarize2, buildTrajectory: buildTrajectory2, DEFAULT_LOG_DIR: DEFAULT_LOG_DIR2 } = await Promise.resolve().then(() => (init_sessionlog(), sessionlog_exports));
|
|
2826
|
+
const sessionId = c.req.param("id") || "";
|
|
2827
|
+
const principal = c.get("principal") || "ip:unknown";
|
|
2828
|
+
const [n, hit] = noteSessionAccess(principal, sessionId);
|
|
2829
|
+
if (hit) {
|
|
2830
|
+
if (sessionSweepAction() === "deny") {
|
|
2831
|
+
return c.json({ detail: "\u4F1A\u8BDD\u8BBF\u95EE\u8FC7\u4E8E\u96C6\u4E2D\uFF0C\u7591\u4F3C\u6279\u91CF\u626B\u63CF" }, 429);
|
|
2832
|
+
}
|
|
2833
|
+
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`);
|
|
2834
|
+
}
|
|
2835
|
+
const path3 = join6(DEFAULT_LOG_DIR2, `${sessionId}.jsonl`);
|
|
2836
|
+
if (!existsSync5(path3)) {
|
|
2837
|
+
return c.json({ detail: `no session log for ${sessionId}` }, 404);
|
|
2838
|
+
}
|
|
2839
|
+
const log = load2(path3, sessionId);
|
|
2840
|
+
return c.json({
|
|
2841
|
+
session_id: sessionId,
|
|
2842
|
+
summary: summarize2(log),
|
|
2843
|
+
records: buildTrajectory2(log),
|
|
2844
|
+
events: log.events
|
|
2845
|
+
});
|
|
2846
|
+
}
|
|
2139
2847
|
|
|
2140
2848
|
// src/v1/server.ts
|
|
2141
2849
|
init_security();
|
|
@@ -2186,7 +2894,7 @@ function createApp() {
|
|
|
2186
2894
|
)
|
|
2187
2895
|
);
|
|
2188
2896
|
app.use("*", async (c, next) => {
|
|
2189
|
-
const
|
|
2897
|
+
const path3 = new URL(c.req.url).pathname;
|
|
2190
2898
|
const method = c.req.method.toUpperCase();
|
|
2191
2899
|
if (method === "OPTIONS") return next();
|
|
2192
2900
|
const cl = c.req.header("content-length");
|
|
@@ -2200,15 +2908,15 @@ function createApp() {
|
|
|
2200
2908
|
if (originCheckEnabled()) {
|
|
2201
2909
|
const origin = c.req.header("origin") || "";
|
|
2202
2910
|
if (origin && !originAllowed(origin, c.req.header("host") || "")) {
|
|
2203
|
-
console.warn(`[AgentGate] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${
|
|
2911
|
+
console.warn(`[AgentGate] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path3}`);
|
|
2204
2912
|
return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
|
|
2205
2913
|
}
|
|
2206
2914
|
}
|
|
2207
2915
|
const headers = { authorization: c.req.header("authorization") };
|
|
2208
2916
|
const cookie = (0, import_cookie.getCookie)(c, DASHBOARD_COOKIE) || "";
|
|
2209
|
-
const requireGlobal =
|
|
2210
|
-
const { ok, principal } = checkRequestAuth(headers,
|
|
2211
|
-
if (!ok && !PUBLIC_PAGE_PATHS.includes(
|
|
2917
|
+
const requireGlobal = path3.startsWith("/dashboard") || path3.startsWith("/ws/");
|
|
2918
|
+
const { ok, principal } = checkRequestAuth(headers, path3, cookie, requireGlobal);
|
|
2919
|
+
if (!ok && !PUBLIC_PAGE_PATHS.includes(path3)) {
|
|
2212
2920
|
if (boundAgentOf(principal)) {
|
|
2213
2921
|
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);
|
|
2214
2922
|
}
|
|
@@ -2251,7 +2959,7 @@ function createApp() {
|
|
|
2251
2959
|
return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
|
|
2252
2960
|
}
|
|
2253
2961
|
}
|
|
2254
|
-
const pool = poolOf(
|
|
2962
|
+
const pool = poolOf(path3);
|
|
2255
2963
|
if (!take(`pool:${pool}`, poolLimit(pool))) {
|
|
2256
2964
|
const qkey = principal || `ip:${ip}`;
|
|
2257
2965
|
const [n, abusive] = noteQueueReject(qkey);
|
|
@@ -2275,6 +2983,8 @@ function createApp() {
|
|
|
2275
2983
|
app.get("/api/v1/agents", agentsRoute);
|
|
2276
2984
|
app.get("/api/v1/timeline", timelineRoute);
|
|
2277
2985
|
app.get("/api/v1/storage_stats", storageStatsRoute);
|
|
2986
|
+
app.get("/api/v1/sessionlog", sessionLogsRoute);
|
|
2987
|
+
app.get("/api/v1/sessionlog/:id", sessionLogDetailRoute);
|
|
2278
2988
|
app.delete("/api/v1/tool_calls", deleteToolCallsRoute);
|
|
2279
2989
|
app.get("/dashboard/", dashboardRoute);
|
|
2280
2990
|
app.get("/dashboard", (c) => c.redirect("/dashboard/"));
|
|
@@ -2302,17 +3012,17 @@ async function dashboardRoute(c) {
|
|
|
2302
3012
|
return c.html(UNAUTHORIZED_HTML, 401, DASHBOARD_SECURITY_HEADERS);
|
|
2303
3013
|
}
|
|
2304
3014
|
}
|
|
2305
|
-
const { readFileSync:
|
|
2306
|
-
const { resolve, dirname:
|
|
3015
|
+
const { readFileSync: readFileSync5, existsSync: existsSync5 } = await import("fs");
|
|
3016
|
+
const { resolve: resolve2, dirname: dirname6 } = await import("path");
|
|
2307
3017
|
const { fileURLToPath } = await import("url");
|
|
2308
|
-
const __dirname =
|
|
3018
|
+
const __dirname = dirname6(fileURLToPath(importMetaUrl));
|
|
2309
3019
|
const paths = [
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
3020
|
+
resolve2(__dirname, "dashboard.html"),
|
|
3021
|
+
resolve2(__dirname, "../dashboard.html"),
|
|
3022
|
+
resolve2(__dirname, "../src/v1/dashboard.html")
|
|
2313
3023
|
];
|
|
2314
|
-
const htmlPath = paths.find((p) =>
|
|
2315
|
-
const html =
|
|
3024
|
+
const htmlPath = paths.find((p) => existsSync5(p)) || paths[0];
|
|
3025
|
+
const html = readFileSync5(htmlPath, "utf-8");
|
|
2316
3026
|
return c.html(html, 200, DASHBOARD_SECURITY_HEADERS);
|
|
2317
3027
|
}
|
|
2318
3028
|
// Annotate the CommonJS export names for ESM import in node:
|