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