@kenhkl/agent-gate 0.6.3 → 0.7.2

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
@@ -67,7 +67,9 @@ var init_json_storage = __esm({
67
67
  sessionsPath;
68
68
  toolCallsDir;
69
69
  nextId;
70
- /** per-session 互斥锁,保证同一 session 的 seq 生成 + 写入原子性 */
70
+ /** per-session 互斥锁,保证同一 session 的 seq 生成 + 写入原子性。
71
+ * 值只用来做 Promise 链式串联,其 resolve 值无人使用,故用 Promise<unknown>
72
+ * (锁链上的 then 会返回 seq 等值,标成 Promise<void> 会对不上)。 */
71
73
  sessionLocks = /* @__PURE__ */ new Map();
72
74
  constructor(dataDir) {
73
75
  this.dataDir = dataDir || process.env.AGENT_GATE_DATA_DIR || getDefaultDataDir();
@@ -186,10 +188,11 @@ var init_json_storage = __esm({
186
188
  this.saveToolCalls(sessionId, records);
187
189
  return id;
188
190
  });
189
- this.sessionLocks.set(sessionId, next.catch(() => {
190
- }));
191
+ const guarded = next.catch(() => {
192
+ });
193
+ this.sessionLocks.set(sessionId, guarded);
191
194
  const cleanup = () => {
192
- if (this.sessionLocks.get(sessionId) === next) {
195
+ if (this.sessionLocks.get(sessionId) === guarded) {
193
196
  this.sessionLocks.delete(sessionId);
194
197
  }
195
198
  };
@@ -243,6 +246,35 @@ var init_json_storage = __esm({
243
246
  }
244
247
  return allRecords.length;
245
248
  }
249
+ getStorageStats() {
250
+ let toolCalls = 0;
251
+ let jsonFiles = 0;
252
+ let jsonBytes = 0;
253
+ try {
254
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
255
+ for (const file of files) {
256
+ const stat = (0, import_fs.statSync)((0, import_path.join)(this.toolCallsDir, file));
257
+ jsonFiles++;
258
+ jsonBytes += stat.size;
259
+ const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
260
+ toolCalls += records.length;
261
+ }
262
+ } catch {
263
+ }
264
+ return { dbBytes: 0, toolCalls, jsonFiles, jsonBytes };
265
+ }
266
+ clearToolCalls() {
267
+ let removed = 0;
268
+ try {
269
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
270
+ for (const file of files) {
271
+ (0, import_fs.unlinkSync)((0, import_path.join)(this.toolCallsDir, file));
272
+ removed++;
273
+ }
274
+ } catch {
275
+ }
276
+ return removed;
277
+ }
246
278
  enrichRecord(record, sessions, agents) {
247
279
  const session = sessions.get(record.session_id);
248
280
  const agentId = session?.agent_id;
@@ -373,6 +405,7 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
373
405
  `;
374
406
  SqliteStorage = class {
375
407
  db;
408
+ dbPath;
376
409
  constructor(dbPath) {
377
410
  let Database;
378
411
  try {
@@ -385,6 +418,7 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
385
418
  const path = dbPath || getDefaultDbPath();
386
419
  const dir = (0, import_path2.dirname)(path);
387
420
  if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true });
421
+ this.dbPath = path;
388
422
  this.db = new Database(path);
389
423
  this.db.pragma("journal_mode = WAL");
390
424
  this.db.exec(SCHEMA);
@@ -488,6 +522,28 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
488
522
  ).get(...values);
489
523
  return row?.total ?? 0;
490
524
  }
525
+ getStorageStats() {
526
+ const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
527
+ let dbBytes = 0;
528
+ try {
529
+ const { statSync: statSync2, existsSync: existsSync3 } = require("fs");
530
+ dbBytes = statSync2(this.dbPath).size;
531
+ for (const suffix of ["-wal", "-shm"]) {
532
+ const p = this.dbPath + suffix;
533
+ if (existsSync3(p)) dbBytes += statSync2(p).size;
534
+ }
535
+ } catch {
536
+ }
537
+ return { dbBytes, toolCalls: row?.total ?? 0, jsonFiles: 0, jsonBytes: 0 };
538
+ }
539
+ clearToolCalls() {
540
+ const result = this.db.transaction(() => {
541
+ const deleted = this.db.prepare("DELETE FROM tool_calls").run();
542
+ this.db.prepare("UPDATE sessions SET tool_call_count = 0").run();
543
+ return Number(deleted.changes);
544
+ })();
545
+ return result;
546
+ }
491
547
  getAgentsList() {
492
548
  return this.db.prepare(`
493
549
  SELECT a.agent_type, a.hostname, a.agent_version as version,
@@ -535,12 +591,13 @@ var db_exports = {};
535
591
  __export(db_exports, {
536
592
  closeDb: () => closeDb,
537
593
  createStorage: () => createStorage,
594
+ getAgentGateDbPath: () => getAgentGateDbPath,
538
595
  getDb: () => getDb,
539
596
  getStorage: () => getStorage
540
597
  });
541
598
  function createStorage(opts) {
542
599
  if (storage) return storage;
543
- const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
600
+ const backend = (process.env.AGENT_GATE_STORAGE || "").toLowerCase() || (process.platform === "openharmony" ? "json" : "sqlite");
544
601
  if (backend === "json") {
545
602
  const { JsonStorage: JsonStorage2 } = (init_json_storage(), __toCommonJS(json_storage_exports));
546
603
  storage = new JsonStorage2(opts?.dataDir);
@@ -582,6 +639,21 @@ function getDb(dbPath) {
582
639
  throw new Error("better-sqlite3 is not available. Use AGENT_GATE_STORAGE=json.");
583
640
  }
584
641
  }
642
+ function getAgentGateDbPath() {
643
+ const envDb = process.env.AGENT_GATE_DB;
644
+ if (envDb) return envDb;
645
+ const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
646
+ if (backend === "json") {
647
+ const dataDir = process.env.AGENT_GATE_DATA_DIR || "";
648
+ if (dataDir) return dataDir;
649
+ const home2 = process.env.HOME || process.env.USERPROFILE || "/tmp";
650
+ const xdgData2 = process.env.XDG_DATA_HOME || require("path").join(home2, ".local", "share");
651
+ return require("path").join(xdgData2, "agent_gate", "tool_calls");
652
+ }
653
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
654
+ const xdgData = process.env.XDG_DATA_HOME || require("path").join(home, ".local", "share");
655
+ return require("path").join(xdgData, "agent_gate", "agent_gate_ts.db");
656
+ }
585
657
  function closeDb() {
586
658
  if (storage) {
587
659
  storage.close();
@@ -602,10 +674,48 @@ var init_db = __esm({
602
674
  }
603
675
  });
604
676
 
677
+ // src/shared/multi-session.ts
678
+ function isMultiSessionEnabled() {
679
+ return process.env.AGENT_GATE_MULTI_SESSION === "1";
680
+ }
681
+ function buildSessionHistory(queryToolCalls2, sessionId) {
682
+ if (!isMultiSessionEnabled()) return [];
683
+ try {
684
+ const recent = queryToolCalls2({ limit: DEFAULT_HISTORY_LIMIT });
685
+ const bySession = /* @__PURE__ */ new Map();
686
+ for (const tc of recent) {
687
+ if (tc.session_id === sessionId) continue;
688
+ const list = bySession.get(tc.session_id) || [];
689
+ list.unshift({ action_type: tc.action_type, action_detail: tc.action_detail });
690
+ bySession.set(tc.session_id, list);
691
+ }
692
+ return [...bySession.entries()].slice(0, DEFAULT_MAX_SESSIONS).map(([sid, actions]) => ({
693
+ session_id: sid,
694
+ action_history: actions.slice(0, DEFAULT_ACTIONS_PER_SESSION)
695
+ }));
696
+ } catch {
697
+ return [];
698
+ }
699
+ }
700
+ function isStatefulIncrementalEnabled() {
701
+ return isMultiSessionEnabled();
702
+ }
703
+ var DEFAULT_HISTORY_LIMIT, DEFAULT_MAX_SESSIONS, DEFAULT_ACTIONS_PER_SESSION;
704
+ var init_multi_session = __esm({
705
+ "src/shared/multi-session.ts"() {
706
+ "use strict";
707
+ init_cjs_shims();
708
+ DEFAULT_HISTORY_LIMIT = 500;
709
+ DEFAULT_MAX_SESSIONS = 5;
710
+ DEFAULT_ACTIONS_PER_SESSION = 100;
711
+ }
712
+ });
713
+
605
714
  // src/shared/moss-client.ts
606
715
  var moss_client_exports = {};
607
716
  __export(moss_client_exports, {
608
717
  callAgentMoss: () => callAgentMoss,
718
+ callAgentMossReview: () => callAgentMossReview,
609
719
  fetchMossHealth: () => fetchMossHealth,
610
720
  setMossUrl: () => setMossUrl
611
721
  });
@@ -614,10 +724,14 @@ function setMossUrl(url) {
614
724
  }
615
725
  async function callAgentMoss(request) {
616
726
  try {
727
+ const req = request;
728
+ if (isStatefulIncrementalEnabled() && req && typeof req === "object" && req.metadata === void 0) {
729
+ req.metadata = { stateful_incremental: true };
730
+ }
617
731
  const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
618
732
  method: "POST",
619
733
  headers: { "Content-Type": "application/json" },
620
- body: JSON.stringify(request),
734
+ body: JSON.stringify(req),
621
735
  // 100s:覆盖 AgentMoss 总超时(90s)+ 余量,避免 AgentMoss 还在分析时
622
736
  // 被 AgentGate 抢断后 fail-closed 误杀。AgentGate 这层不重试(AgentMoss 内部已重试)。
623
737
  timeout: 1e5
@@ -655,6 +769,23 @@ async function fetchMossHealth() {
655
769
  return { moss_version: "N/A", moss_status: "unreachable" };
656
770
  }
657
771
  }
772
+ async function callAgentMossReview(options) {
773
+ const { agentId = "", dbPath = "" } = options;
774
+ if (!dbPath) return;
775
+ try {
776
+ const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/review`, {
777
+ method: "POST",
778
+ headers: { "Content-Type": "application/json" },
779
+ body: JSON.stringify({ agent_id: agentId, db_path: dbPath }),
780
+ timeout: 3e4
781
+ });
782
+ if (!resp.ok) {
783
+ console.error(`[AgentGate] AgentMoss review HTTP ${resp.status}: ${resp.statusText}`);
784
+ }
785
+ } catch (err) {
786
+ console.error(`[AgentGate] AgentMoss review unreachable: ${String(err?.message || err)}`);
787
+ }
788
+ }
658
789
  function failClosedResponse(reason, riskType = "service_unavailable") {
659
790
  return {
660
791
  decision: "Deny",
@@ -671,6 +802,7 @@ var init_moss_client = __esm({
671
802
  "use strict";
672
803
  init_cjs_shims();
673
804
  import_node_fetch = __toESM(require("node-fetch"));
805
+ init_multi_session();
674
806
  DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
675
807
  mossUrl = DEFAULT_MOSS_URL;
676
808
  }
@@ -682,7 +814,7 @@ var init_version = __esm({
682
814
  "src/version.ts"() {
683
815
  "use strict";
684
816
  init_cjs_shims();
685
- _version = true ? "0.6.3" : (() => {
817
+ _version = true ? "0.7.2" : (() => {
686
818
  try {
687
819
  const require2 = createRequire(importMetaUrl);
688
820
  const pkg = require2("../package.json");
@@ -727,6 +859,13 @@ var init_models = __esm({
727
859
  action_type: import_zod.z.string(),
728
860
  action_detail: import_zod.z.string()
729
861
  })).default([]),
862
+ session_history: import_zod.z.array(import_zod.z.object({
863
+ session_id: import_zod.z.string(),
864
+ action_history: import_zod.z.array(import_zod.z.object({
865
+ action_type: import_zod.z.string(),
866
+ action_detail: import_zod.z.string()
867
+ })).default([])
868
+ })).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"),
730
869
  metadata: import_zod.z.record(import_zod.z.unknown()).optional()
731
870
  });
732
871
  AgentGateResponseSchema = import_zod.z.object({
@@ -737,6 +876,8 @@ var init_models = __esm({
737
876
  violated_layers: import_zod.z.array(import_zod.z.string()).default([]),
738
877
  confidence: import_zod.z.number().int().min(0).max(100).default(100),
739
878
  analysis_duration_ms: import_zod.z.number().default(0),
879
+ oversize: import_zod.z.boolean().optional().describe("\u672C\u5730\u5B58\u50A8\u662F\u5426\u8D85\u8FC7\u6E05\u7406\u9608\u503C\uFF08agg \u7528\uFF09"),
880
+ thresholdMB: import_zod.z.number().optional().describe("\u5B58\u50A8\u6E05\u7406\u9608\u503C MB\uFF08agg \u7528\uFF09"),
740
881
  collected_context: import_zod.z.object({
741
882
  os: import_zod.z.object({
742
883
  system: import_zod.z.string(),
@@ -768,6 +909,13 @@ function normalize(input, systemContext) {
768
909
  action_type: h.action_type,
769
910
  action_detail: h.action_detail
770
911
  }));
912
+ const sessionHistory = (input.session_history || []).map((s) => ({
913
+ session_id: s.session_id,
914
+ action_history: s.action_history.map((h) => ({
915
+ action_type: h.action_type,
916
+ action_detail: h.action_detail
917
+ }))
918
+ }));
771
919
  const promptHistory = input.prompt_history.map((t) => ({
772
920
  text: t.text,
773
921
  actions: t.actions.map((a) => ({
@@ -782,6 +930,7 @@ function normalize(input, systemContext) {
782
930
  prompt_session: input.user_prompt || input.description || "",
783
931
  prompt_history: promptHistory,
784
932
  action_history: actionHistory,
933
+ session_history: sessionHistory,
785
934
  a_next: {
786
935
  action_type: toolName,
787
936
  action_detail: command
@@ -799,7 +948,12 @@ function normalize(input, systemContext) {
799
948
  ...input.metadata,
800
949
  agent_type: input.agent_type,
801
950
  agent_version: input.agent_version,
802
- system_context: systemContext
951
+ system_context: systemContext,
952
+ // L2.4 stateful incremental:让 AgentMoss 把每条 tool call 计入该 agent 的
953
+ // 持久化时间线并即时推进链指针(跨 session/长时距组合链的最后一步当场 Deny)。
954
+ // 由 AGENT_GATE_MULTI_SESSION=1(OpenDesk 设置页"多 session 分析"开关)门控;
955
+ // 关闭时不注入,回到纯单 session 行为,零跨会话开销。
956
+ ...isStatefulIncrementalEnabled() ? { stateful_incremental: true } : {}
803
957
  }
804
958
  };
805
959
  }
@@ -807,6 +961,7 @@ var init_normalizer = __esm({
807
961
  "src/shared/normalizer.ts"() {
808
962
  "use strict";
809
963
  init_cjs_shims();
964
+ init_multi_session();
810
965
  }
811
966
  });
812
967
 
@@ -949,6 +1104,12 @@ function queryToolCalls(params) {
949
1104
  function countToolCalls(params) {
950
1105
  return store().countToolCalls(params);
951
1106
  }
1107
+ function getStorageStats() {
1108
+ return store().getStorageStats();
1109
+ }
1110
+ function clearToolCalls() {
1111
+ return store().clearToolCalls();
1112
+ }
952
1113
  function getAgentsList() {
953
1114
  return store().getAgentsList();
954
1115
  }
@@ -963,6 +1124,20 @@ var init_repository = __esm({
963
1124
  }
964
1125
  });
965
1126
 
1127
+ // src/shared/agent-identity.ts
1128
+ function resolveAgentIdentity(metadata, collected) {
1129
+ return {
1130
+ hostname: String(metadata?.hostname || "") || String(collected?.hostname || "") || "unknown",
1131
+ osType: String(metadata?.os_type || "") || String(collected?.system || "")
1132
+ };
1133
+ }
1134
+ var init_agent_identity = __esm({
1135
+ "src/shared/agent-identity.ts"() {
1136
+ "use strict";
1137
+ init_cjs_shims();
1138
+ }
1139
+ });
1140
+
966
1141
  // src/v1/routes.ts
967
1142
  async function healthRoute(c) {
968
1143
  const mossHealth = await fetchMossHealth();
@@ -973,6 +1148,12 @@ async function healthRoute(c) {
973
1148
  moss_status: mossHealth.moss_status
974
1149
  });
975
1150
  }
1151
+ function storageOversizeInfo() {
1152
+ const stats = getStorageStats();
1153
+ const thresholdMB = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
1154
+ const totalMB = (stats.dbBytes + stats.jsonBytes) / 1024 / 1024;
1155
+ return { oversize: totalMB > thresholdMB, thresholdMB };
1156
+ }
976
1157
  async function analyzeRoute(c) {
977
1158
  const t0 = performance.now();
978
1159
  try {
@@ -986,14 +1167,24 @@ async function analyzeRoute(c) {
986
1167
  return c.json({
987
1168
  ...cached,
988
1169
  analysis_duration_ms: 0,
989
- collected_context: {}
1170
+ collected_context: {},
1171
+ ...storageOversizeInfo()
990
1172
  });
991
1173
  }
992
1174
  const context = await collectSystemContext();
1175
+ if (isMultiSessionEnabled()) {
1176
+ input.session_history = buildSessionHistory(
1177
+ (params) => queryToolCalls(params),
1178
+ input.session_id
1179
+ );
1180
+ }
993
1181
  const mossRequest = normalize(input, context);
994
- const hostname = context.os?.hostname || "unknown";
1182
+ const { hostname, osType } = resolveAgentIdentity(
1183
+ input.metadata,
1184
+ context.os
1185
+ );
995
1186
  const agentId = getOrCreateAgent(input.agent_type, hostname, input.agent_version);
996
- getOrCreateSession(input.session_id, agentId, input.cwd, input.user_prompt, String(context.os?.system || ""));
1187
+ getOrCreateSession(input.session_id, agentId, input.cwd, input.user_prompt, osType);
997
1188
  const mossResult = await callAgentMoss(mossRequest);
998
1189
  insertToolCall({
999
1190
  session_id: input.session_id,
@@ -1013,6 +1204,17 @@ async function analyzeRoute(c) {
1013
1204
  analysis_duration_ms: performance.now() - t0
1014
1205
  });
1015
1206
  setCache(key, mossResult);
1207
+ if (isMultiSessionEnabled()) {
1208
+ v1ReviewCounter++;
1209
+ if (v1ReviewCounter % 100 === 0) {
1210
+ try {
1211
+ const { getAgentGateDbPath: getAgentGateDbPath2 } = (init_db(), __toCommonJS(db_exports));
1212
+ const { callAgentMossReview: callAgentMossReview2 } = (init_moss_client(), __toCommonJS(moss_client_exports));
1213
+ void callAgentMossReview2({ agentId, dbPath: getAgentGateDbPath2() });
1214
+ } catch {
1215
+ }
1216
+ }
1217
+ }
1016
1218
  const durationMs = performance.now() - t0;
1017
1219
  return c.json(
1018
1220
  AgentGateResponseSchema.parse({
@@ -1023,6 +1225,7 @@ async function analyzeRoute(c) {
1023
1225
  violated_layers: mossResult.violated_layers,
1024
1226
  confidence: mossResult.confidence,
1025
1227
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
1228
+ ...storageOversizeInfo(),
1026
1229
  collected_context: {
1027
1230
  os: context.os,
1028
1231
  process: context.process,
@@ -1057,6 +1260,17 @@ async function timelineRoute(c) {
1057
1260
  const rows = getTimeline(limit);
1058
1261
  return c.json(rows);
1059
1262
  }
1263
+ function storageStatsRoute(c) {
1264
+ const storageStats = getStorageStats();
1265
+ const defaultThreshold = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
1266
+ const totalMB = (storageStats.dbBytes + storageStats.jsonBytes) / 1024 / 1024;
1267
+ return c.json({ stats: storageStats, oversize: totalMB > defaultThreshold, thresholdMB: defaultThreshold });
1268
+ }
1269
+ function deleteToolCallsRoute(c) {
1270
+ const deleted = clearToolCalls();
1271
+ return c.json({ deleted });
1272
+ }
1273
+ var v1ReviewCounter;
1060
1274
  var init_routes = __esm({
1061
1275
  "src/v1/routes.ts"() {
1062
1276
  "use strict";
@@ -1067,7 +1281,10 @@ var init_routes = __esm({
1067
1281
  init_moss_client();
1068
1282
  init_cache();
1069
1283
  init_repository();
1284
+ init_multi_session();
1285
+ init_agent_identity();
1070
1286
  init_version();
1287
+ v1ReviewCounter = 0;
1071
1288
  }
1072
1289
  });
1073
1290
 
@@ -1078,7 +1295,7 @@ __export(server_exports, {
1078
1295
  });
1079
1296
  function createApp() {
1080
1297
  const app = new import_hono.Hono();
1081
- app.use("*", (0, import_cors.cors)({ origin: "*", allowMethods: ["GET", "POST", "OPTIONS"], allowHeaders: ["*"] }));
1298
+ app.use("*", (0, import_cors.cors)({ origin: "*", allowMethods: ["GET", "POST", "OPTIONS", "DELETE"], allowHeaders: ["*"] }));
1082
1299
  app.use("*", (0, import_logger.logger)());
1083
1300
  app.get("/api/v1/health", healthRoute);
1084
1301
  app.post("/api/v1/analyze", analyzeRoute);
@@ -1086,6 +1303,8 @@ function createApp() {
1086
1303
  app.get("/api/v1/tool_calls", toolCallsRoute);
1087
1304
  app.get("/api/v1/agents", agentsRoute);
1088
1305
  app.get("/api/v1/timeline", timelineRoute);
1306
+ app.get("/api/v1/storage_stats", storageStatsRoute);
1307
+ app.delete("/api/v1/tool_calls", deleteToolCallsRoute);
1089
1308
  app.get("/dashboard/", dashboardRoute);
1090
1309
  app.get("/dashboard", (c) => c.redirect("/dashboard/"));
1091
1310
  return app;
@@ -1166,4 +1385,3 @@ main().catch((err) => {
1166
1385
  console.error("Fatal error:", err);
1167
1386
  process.exit(1);
1168
1387
  });
1169
- //# sourceMappingURL=cli.js.map