@kenhkl/agent-gate 0.6.2 → 0.7.0

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/v1/cli.js CHANGED
@@ -243,6 +243,35 @@ var init_json_storage = __esm({
243
243
  }
244
244
  return allRecords.length;
245
245
  }
246
+ getStorageStats() {
247
+ let toolCalls = 0;
248
+ let jsonFiles = 0;
249
+ let jsonBytes = 0;
250
+ try {
251
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
252
+ for (const file of files) {
253
+ const stat = (0, import_fs.statSync)((0, import_path.join)(this.toolCallsDir, file));
254
+ jsonFiles++;
255
+ jsonBytes += stat.size;
256
+ const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
257
+ toolCalls += records.length;
258
+ }
259
+ } catch {
260
+ }
261
+ return { dbBytes: 0, toolCalls, jsonFiles, jsonBytes };
262
+ }
263
+ clearToolCalls() {
264
+ let removed = 0;
265
+ try {
266
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
267
+ for (const file of files) {
268
+ (0, import_fs.unlinkSync)((0, import_path.join)(this.toolCallsDir, file));
269
+ removed++;
270
+ }
271
+ } catch {
272
+ }
273
+ return removed;
274
+ }
246
275
  enrichRecord(record, sessions, agents) {
247
276
  const session = sessions.get(record.session_id);
248
277
  const agentId = session?.agent_id;
@@ -373,6 +402,7 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
373
402
  `;
374
403
  SqliteStorage = class {
375
404
  db;
405
+ dbPath;
376
406
  constructor(dbPath) {
377
407
  let Database;
378
408
  try {
@@ -385,6 +415,7 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
385
415
  const path = dbPath || getDefaultDbPath();
386
416
  const dir = (0, import_path2.dirname)(path);
387
417
  if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true });
418
+ this.dbPath = path;
388
419
  this.db = new Database(path);
389
420
  this.db.pragma("journal_mode = WAL");
390
421
  this.db.exec(SCHEMA);
@@ -488,6 +519,28 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
488
519
  ).get(...values);
489
520
  return row?.total ?? 0;
490
521
  }
522
+ getStorageStats() {
523
+ const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
524
+ let dbBytes = 0;
525
+ try {
526
+ const { statSync: statSync2, existsSync: existsSync3 } = require("fs");
527
+ dbBytes = statSync2(this.dbPath).size;
528
+ for (const suffix of ["-wal", "-shm"]) {
529
+ const p = this.dbPath + suffix;
530
+ if (existsSync3(p)) dbBytes += statSync2(p).size;
531
+ }
532
+ } catch {
533
+ }
534
+ return { dbBytes, toolCalls: row?.total ?? 0, jsonFiles: 0, jsonBytes: 0 };
535
+ }
536
+ clearToolCalls() {
537
+ const result = this.db.transaction(() => {
538
+ const deleted = this.db.prepare("DELETE FROM tool_calls").run();
539
+ this.db.prepare("UPDATE sessions SET tool_call_count = 0").run();
540
+ return Number(deleted.changes);
541
+ })();
542
+ return result;
543
+ }
491
544
  getAgentsList() {
492
545
  return this.db.prepare(`
493
546
  SELECT a.agent_type, a.hostname, a.agent_version as version,
@@ -535,12 +588,13 @@ var db_exports = {};
535
588
  __export(db_exports, {
536
589
  closeDb: () => closeDb,
537
590
  createStorage: () => createStorage,
591
+ getAgentGateDbPath: () => getAgentGateDbPath,
538
592
  getDb: () => getDb,
539
593
  getStorage: () => getStorage
540
594
  });
541
595
  function createStorage(opts) {
542
596
  if (storage) return storage;
543
- const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
597
+ const backend = (process.env.AGENT_GATE_STORAGE || "").toLowerCase() || (process.platform === "openharmony" ? "json" : "sqlite");
544
598
  if (backend === "json") {
545
599
  const { JsonStorage: JsonStorage2 } = (init_json_storage(), __toCommonJS(json_storage_exports));
546
600
  storage = new JsonStorage2(opts?.dataDir);
@@ -582,6 +636,21 @@ function getDb(dbPath) {
582
636
  throw new Error("better-sqlite3 is not available. Use AGENT_GATE_STORAGE=json.");
583
637
  }
584
638
  }
639
+ function getAgentGateDbPath() {
640
+ const envDb = process.env.AGENT_GATE_DB;
641
+ if (envDb) return envDb;
642
+ const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
643
+ if (backend === "json") {
644
+ const dataDir = process.env.AGENT_GATE_DATA_DIR || "";
645
+ if (dataDir) return dataDir;
646
+ const home2 = process.env.HOME || process.env.USERPROFILE || "/tmp";
647
+ const xdgData2 = process.env.XDG_DATA_HOME || require("path").join(home2, ".local", "share");
648
+ return require("path").join(xdgData2, "agent_gate", "tool_calls");
649
+ }
650
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
651
+ const xdgData = process.env.XDG_DATA_HOME || require("path").join(home, ".local", "share");
652
+ return require("path").join(xdgData, "agent_gate", "agent_gate_ts.db");
653
+ }
585
654
  function closeDb() {
586
655
  if (storage) {
587
656
  storage.close();
@@ -602,10 +671,48 @@ var init_db = __esm({
602
671
  }
603
672
  });
604
673
 
674
+ // src/shared/multi-session.ts
675
+ function isMultiSessionEnabled() {
676
+ return process.env.AGENT_GATE_MULTI_SESSION === "1";
677
+ }
678
+ function buildSessionHistory(queryToolCalls2, sessionId) {
679
+ if (!isMultiSessionEnabled()) return [];
680
+ try {
681
+ const recent = queryToolCalls2({ limit: DEFAULT_HISTORY_LIMIT });
682
+ const bySession = /* @__PURE__ */ new Map();
683
+ for (const tc of recent) {
684
+ if (tc.session_id === sessionId) continue;
685
+ const list = bySession.get(tc.session_id) || [];
686
+ list.unshift({ action_type: tc.action_type, action_detail: tc.action_detail });
687
+ bySession.set(tc.session_id, list);
688
+ }
689
+ return [...bySession.entries()].slice(0, DEFAULT_MAX_SESSIONS).map(([sid, actions]) => ({
690
+ session_id: sid,
691
+ action_history: actions.slice(0, DEFAULT_ACTIONS_PER_SESSION)
692
+ }));
693
+ } catch {
694
+ return [];
695
+ }
696
+ }
697
+ function isStatefulIncrementalEnabled() {
698
+ return isMultiSessionEnabled();
699
+ }
700
+ var DEFAULT_HISTORY_LIMIT, DEFAULT_MAX_SESSIONS, DEFAULT_ACTIONS_PER_SESSION;
701
+ var init_multi_session = __esm({
702
+ "src/shared/multi-session.ts"() {
703
+ "use strict";
704
+ init_cjs_shims();
705
+ DEFAULT_HISTORY_LIMIT = 500;
706
+ DEFAULT_MAX_SESSIONS = 5;
707
+ DEFAULT_ACTIONS_PER_SESSION = 100;
708
+ }
709
+ });
710
+
605
711
  // src/shared/moss-client.ts
606
712
  var moss_client_exports = {};
607
713
  __export(moss_client_exports, {
608
714
  callAgentMoss: () => callAgentMoss,
715
+ callAgentMossReview: () => callAgentMossReview,
609
716
  fetchMossHealth: () => fetchMossHealth,
610
717
  setMossUrl: () => setMossUrl
611
718
  });
@@ -614,10 +721,14 @@ function setMossUrl(url) {
614
721
  }
615
722
  async function callAgentMoss(request) {
616
723
  try {
724
+ const req = request;
725
+ if (isStatefulIncrementalEnabled() && req && typeof req === "object" && req.metadata === void 0) {
726
+ req.metadata = { stateful_incremental: true };
727
+ }
617
728
  const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
618
729
  method: "POST",
619
730
  headers: { "Content-Type": "application/json" },
620
- body: JSON.stringify(request),
731
+ body: JSON.stringify(req),
621
732
  // 100s:覆盖 AgentMoss 总超时(90s)+ 余量,避免 AgentMoss 还在分析时
622
733
  // 被 AgentGate 抢断后 fail-closed 误杀。AgentGate 这层不重试(AgentMoss 内部已重试)。
623
734
  timeout: 1e5
@@ -655,6 +766,23 @@ async function fetchMossHealth() {
655
766
  return { moss_version: "N/A", moss_status: "unreachable" };
656
767
  }
657
768
  }
769
+ async function callAgentMossReview(options) {
770
+ const { agentId = "", dbPath = "" } = options;
771
+ if (!dbPath) return;
772
+ try {
773
+ const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/review`, {
774
+ method: "POST",
775
+ headers: { "Content-Type": "application/json" },
776
+ body: JSON.stringify({ agent_id: agentId, db_path: dbPath }),
777
+ timeout: 3e4
778
+ });
779
+ if (!resp.ok) {
780
+ console.error(`[AgentGate] AgentMoss review HTTP ${resp.status}: ${resp.statusText}`);
781
+ }
782
+ } catch (err) {
783
+ console.error(`[AgentGate] AgentMoss review unreachable: ${String(err?.message || err)}`);
784
+ }
785
+ }
658
786
  function failClosedResponse(reason, riskType = "service_unavailable") {
659
787
  return {
660
788
  decision: "Deny",
@@ -671,6 +799,7 @@ var init_moss_client = __esm({
671
799
  "use strict";
672
800
  init_cjs_shims();
673
801
  import_node_fetch = __toESM(require("node-fetch"));
802
+ init_multi_session();
674
803
  DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
675
804
  mossUrl = DEFAULT_MOSS_URL;
676
805
  }
@@ -682,7 +811,7 @@ var init_version = __esm({
682
811
  "src/version.ts"() {
683
812
  "use strict";
684
813
  init_cjs_shims();
685
- _version = true ? "0.6.2" : (() => {
814
+ _version = true ? "0.7.0" : (() => {
686
815
  try {
687
816
  const require2 = createRequire(importMetaUrl);
688
817
  const pkg = require2("../package.json");
@@ -716,10 +845,24 @@ var init_models = __esm({
716
845
  cwd: import_zod.z.string().default(""),
717
846
  description: import_zod.z.string().default(""),
718
847
  user_prompt: import_zod.z.string().default(""),
848
+ prompt_history: import_zod.z.array(import_zod.z.object({
849
+ text: import_zod.z.string().default(""),
850
+ actions: import_zod.z.array(import_zod.z.object({
851
+ action_type: import_zod.z.string(),
852
+ action_detail: import_zod.z.string()
853
+ })).default([])
854
+ })).default([]),
719
855
  action_history: import_zod.z.array(import_zod.z.object({
720
856
  action_type: import_zod.z.string(),
721
857
  action_detail: import_zod.z.string()
722
858
  })).default([]),
859
+ session_history: import_zod.z.array(import_zod.z.object({
860
+ session_id: import_zod.z.string(),
861
+ action_history: import_zod.z.array(import_zod.z.object({
862
+ action_type: import_zod.z.string(),
863
+ action_detail: import_zod.z.string()
864
+ })).default([])
865
+ })).default([]).describe("\u591A session \u5386\u53F2\u52A8\u4F5C\uFF08\u53EF\u9009\uFF09\uFF1A\u4F9B AgentMoss L2.4 \u5F62\u5F0F\u5316\u5F15\u64CE\u8DE8\u4F1A\u8BDD\u9A8C\u8BC1"),
723
866
  metadata: import_zod.z.record(import_zod.z.unknown()).optional()
724
867
  });
725
868
  AgentGateResponseSchema = import_zod.z.object({
@@ -730,6 +873,8 @@ var init_models = __esm({
730
873
  violated_layers: import_zod.z.array(import_zod.z.string()).default([]),
731
874
  confidence: import_zod.z.number().int().min(0).max(100).default(100),
732
875
  analysis_duration_ms: import_zod.z.number().default(0),
876
+ oversize: import_zod.z.boolean().optional().describe("\u672C\u5730\u5B58\u50A8\u662F\u5426\u8D85\u8FC7\u6E05\u7406\u9608\u503C\uFF08agg \u7528\uFF09"),
877
+ thresholdMB: import_zod.z.number().optional().describe("\u5B58\u50A8\u6E05\u7406\u9608\u503C MB\uFF08agg \u7528\uFF09"),
733
878
  collected_context: import_zod.z.object({
734
879
  os: import_zod.z.object({
735
880
  system: import_zod.z.string(),
@@ -761,12 +906,28 @@ function normalize(input, systemContext) {
761
906
  action_type: h.action_type,
762
907
  action_detail: h.action_detail
763
908
  }));
909
+ const sessionHistory = (input.session_history || []).map((s) => ({
910
+ session_id: s.session_id,
911
+ action_history: s.action_history.map((h) => ({
912
+ action_type: h.action_type,
913
+ action_detail: h.action_detail
914
+ }))
915
+ }));
916
+ const promptHistory = input.prompt_history.map((t) => ({
917
+ text: t.text,
918
+ actions: t.actions.map((a) => ({
919
+ action_type: a.action_type,
920
+ action_detail: a.action_detail
921
+ }))
922
+ }));
764
923
  const toolName = input.tool_name || input.a_next?.action_type || "unknown";
765
924
  const command = input.command || input.a_next?.action_detail || "";
766
925
  return {
767
926
  session_id: input.session_id,
768
927
  prompt_session: input.user_prompt || input.description || "",
928
+ prompt_history: promptHistory,
769
929
  action_history: actionHistory,
930
+ session_history: sessionHistory,
770
931
  a_next: {
771
932
  action_type: toolName,
772
933
  action_detail: command
@@ -784,7 +945,12 @@ function normalize(input, systemContext) {
784
945
  ...input.metadata,
785
946
  agent_type: input.agent_type,
786
947
  agent_version: input.agent_version,
787
- system_context: systemContext
948
+ system_context: systemContext,
949
+ // L2.4 stateful incremental:让 AgentMoss 把每条 tool call 计入该 agent 的
950
+ // 持久化时间线并即时推进链指针(跨 session/长时距组合链的最后一步当场 Deny)。
951
+ // 由 AGENT_GATE_MULTI_SESSION=1(OpenDesk 设置页"多 session 分析"开关)门控;
952
+ // 关闭时不注入,回到纯单 session 行为,零跨会话开销。
953
+ ...isStatefulIncrementalEnabled() ? { stateful_incremental: true } : {}
788
954
  }
789
955
  };
790
956
  }
@@ -792,6 +958,7 @@ var init_normalizer = __esm({
792
958
  "src/shared/normalizer.ts"() {
793
959
  "use strict";
794
960
  init_cjs_shims();
961
+ init_multi_session();
795
962
  }
796
963
  });
797
964
 
@@ -934,6 +1101,12 @@ function queryToolCalls(params) {
934
1101
  function countToolCalls(params) {
935
1102
  return store().countToolCalls(params);
936
1103
  }
1104
+ function getStorageStats() {
1105
+ return store().getStorageStats();
1106
+ }
1107
+ function clearToolCalls() {
1108
+ return store().clearToolCalls();
1109
+ }
937
1110
  function getAgentsList() {
938
1111
  return store().getAgentsList();
939
1112
  }
@@ -958,6 +1131,12 @@ async function healthRoute(c) {
958
1131
  moss_status: mossHealth.moss_status
959
1132
  });
960
1133
  }
1134
+ function storageOversizeInfo() {
1135
+ const stats = getStorageStats();
1136
+ const thresholdMB = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
1137
+ const totalMB = (stats.dbBytes + stats.jsonBytes) / 1024 / 1024;
1138
+ return { oversize: totalMB > thresholdMB, thresholdMB };
1139
+ }
961
1140
  async function analyzeRoute(c) {
962
1141
  const t0 = performance.now();
963
1142
  try {
@@ -971,10 +1150,17 @@ async function analyzeRoute(c) {
971
1150
  return c.json({
972
1151
  ...cached,
973
1152
  analysis_duration_ms: 0,
974
- collected_context: {}
1153
+ collected_context: {},
1154
+ ...storageOversizeInfo()
975
1155
  });
976
1156
  }
977
1157
  const context = await collectSystemContext();
1158
+ if (isMultiSessionEnabled()) {
1159
+ input.session_history = buildSessionHistory(
1160
+ (params) => queryToolCalls(params),
1161
+ input.session_id
1162
+ );
1163
+ }
978
1164
  const mossRequest = normalize(input, context);
979
1165
  const hostname = context.os?.hostname || "unknown";
980
1166
  const agentId = getOrCreateAgent(input.agent_type, hostname, input.agent_version);
@@ -998,6 +1184,17 @@ async function analyzeRoute(c) {
998
1184
  analysis_duration_ms: performance.now() - t0
999
1185
  });
1000
1186
  setCache(key, mossResult);
1187
+ if (isMultiSessionEnabled()) {
1188
+ v1ReviewCounter++;
1189
+ if (v1ReviewCounter % 100 === 0) {
1190
+ try {
1191
+ const { getAgentGateDbPath: getAgentGateDbPath2 } = (init_db(), __toCommonJS(db_exports));
1192
+ const { callAgentMossReview: callAgentMossReview2 } = (init_moss_client(), __toCommonJS(moss_client_exports));
1193
+ void callAgentMossReview2({ agentId, dbPath: getAgentGateDbPath2() });
1194
+ } catch {
1195
+ }
1196
+ }
1197
+ }
1001
1198
  const durationMs = performance.now() - t0;
1002
1199
  return c.json(
1003
1200
  AgentGateResponseSchema.parse({
@@ -1008,6 +1205,7 @@ async function analyzeRoute(c) {
1008
1205
  violated_layers: mossResult.violated_layers,
1009
1206
  confidence: mossResult.confidence,
1010
1207
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
1208
+ ...storageOversizeInfo(),
1011
1209
  collected_context: {
1012
1210
  os: context.os,
1013
1211
  process: context.process,
@@ -1042,6 +1240,17 @@ async function timelineRoute(c) {
1042
1240
  const rows = getTimeline(limit);
1043
1241
  return c.json(rows);
1044
1242
  }
1243
+ function storageStatsRoute(c) {
1244
+ const storageStats = getStorageStats();
1245
+ const defaultThreshold = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
1246
+ const totalMB = (storageStats.dbBytes + storageStats.jsonBytes) / 1024 / 1024;
1247
+ return c.json({ stats: storageStats, oversize: totalMB > defaultThreshold, thresholdMB: defaultThreshold });
1248
+ }
1249
+ function deleteToolCallsRoute(c) {
1250
+ const deleted = clearToolCalls();
1251
+ return c.json({ deleted });
1252
+ }
1253
+ var v1ReviewCounter;
1045
1254
  var init_routes = __esm({
1046
1255
  "src/v1/routes.ts"() {
1047
1256
  "use strict";
@@ -1052,7 +1261,9 @@ var init_routes = __esm({
1052
1261
  init_moss_client();
1053
1262
  init_cache();
1054
1263
  init_repository();
1264
+ init_multi_session();
1055
1265
  init_version();
1266
+ v1ReviewCounter = 0;
1056
1267
  }
1057
1268
  });
1058
1269
 
@@ -1063,7 +1274,7 @@ __export(server_exports, {
1063
1274
  });
1064
1275
  function createApp() {
1065
1276
  const app = new import_hono.Hono();
1066
- app.use("*", (0, import_cors.cors)({ origin: "*", allowMethods: ["GET", "POST", "OPTIONS"], allowHeaders: ["*"] }));
1277
+ app.use("*", (0, import_cors.cors)({ origin: "*", allowMethods: ["GET", "POST", "OPTIONS", "DELETE"], allowHeaders: ["*"] }));
1067
1278
  app.use("*", (0, import_logger.logger)());
1068
1279
  app.get("/api/v1/health", healthRoute);
1069
1280
  app.post("/api/v1/analyze", analyzeRoute);
@@ -1071,6 +1282,8 @@ function createApp() {
1071
1282
  app.get("/api/v1/tool_calls", toolCallsRoute);
1072
1283
  app.get("/api/v1/agents", agentsRoute);
1073
1284
  app.get("/api/v1/timeline", timelineRoute);
1285
+ app.get("/api/v1/storage_stats", storageStatsRoute);
1286
+ app.delete("/api/v1/tool_calls", deleteToolCallsRoute);
1074
1287
  app.get("/dashboard/", dashboardRoute);
1075
1288
  app.get("/dashboard", (c) => c.redirect("/dashboard/"));
1076
1289
  return app;