@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/server.js CHANGED
@@ -40,6 +40,140 @@ var init_cjs_shims = __esm({
40
40
  }
41
41
  });
42
42
 
43
+ // src/shared/multi-session.ts
44
+ function isMultiSessionEnabled() {
45
+ return process.env.AGENT_GATE_MULTI_SESSION === "1";
46
+ }
47
+ function buildSessionHistory(queryToolCalls2, sessionId) {
48
+ if (!isMultiSessionEnabled()) return [];
49
+ try {
50
+ const recent = queryToolCalls2({ limit: DEFAULT_HISTORY_LIMIT });
51
+ const bySession = /* @__PURE__ */ new Map();
52
+ for (const tc of recent) {
53
+ if (tc.session_id === sessionId) continue;
54
+ const list = bySession.get(tc.session_id) || [];
55
+ list.unshift({ action_type: tc.action_type, action_detail: tc.action_detail });
56
+ bySession.set(tc.session_id, list);
57
+ }
58
+ return [...bySession.entries()].slice(0, DEFAULT_MAX_SESSIONS).map(([sid, actions]) => ({
59
+ session_id: sid,
60
+ action_history: actions.slice(0, DEFAULT_ACTIONS_PER_SESSION)
61
+ }));
62
+ } catch {
63
+ return [];
64
+ }
65
+ }
66
+ function isStatefulIncrementalEnabled() {
67
+ return isMultiSessionEnabled();
68
+ }
69
+ var DEFAULT_HISTORY_LIMIT, DEFAULT_MAX_SESSIONS, DEFAULT_ACTIONS_PER_SESSION;
70
+ var init_multi_session = __esm({
71
+ "src/shared/multi-session.ts"() {
72
+ "use strict";
73
+ init_cjs_shims();
74
+ DEFAULT_HISTORY_LIMIT = 500;
75
+ DEFAULT_MAX_SESSIONS = 5;
76
+ DEFAULT_ACTIONS_PER_SESSION = 100;
77
+ }
78
+ });
79
+
80
+ // src/shared/moss-client.ts
81
+ var moss_client_exports = {};
82
+ __export(moss_client_exports, {
83
+ callAgentMoss: () => callAgentMoss,
84
+ callAgentMossReview: () => callAgentMossReview,
85
+ fetchMossHealth: () => fetchMossHealth,
86
+ setMossUrl: () => setMossUrl
87
+ });
88
+ function setMossUrl(url) {
89
+ mossUrl = url;
90
+ }
91
+ async function callAgentMoss(request) {
92
+ try {
93
+ const req = request;
94
+ if (isStatefulIncrementalEnabled() && req && typeof req === "object" && req.metadata === void 0) {
95
+ req.metadata = { stateful_incremental: true };
96
+ }
97
+ const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
98
+ method: "POST",
99
+ headers: { "Content-Type": "application/json" },
100
+ body: JSON.stringify(req),
101
+ // 100s:覆盖 AgentMoss 总超时(90s)+ 余量,避免 AgentMoss 还在分析时
102
+ // 被 AgentGate 抢断后 fail-closed 误杀。AgentGate 这层不重试(AgentMoss 内部已重试)。
103
+ timeout: 1e5
104
+ });
105
+ if (!resp.ok) {
106
+ console.error(`[AgentGate] AgentMoss HTTP ${resp.status}: ${resp.statusText}`);
107
+ return failClosedResponse(`AgentMoss returned ${resp.status}`);
108
+ }
109
+ return await resp.json();
110
+ } catch (err) {
111
+ const errType = err?.type || "";
112
+ const errMsg = String(err?.message || err);
113
+ if (errType === "request-timeout" || errMsg.includes("timeout")) {
114
+ console.error(`[AgentGate] AgentMoss analysis timeout: ${errMsg}`);
115
+ return failClosedResponse("AgentMoss analysis timeout", "analysis_timeout");
116
+ }
117
+ console.error(`[AgentGate] AgentMoss unreachable: ${errMsg}`);
118
+ return failClosedResponse("AgentMoss service unavailable", "service_unavailable");
119
+ }
120
+ }
121
+ async function fetchMossHealth() {
122
+ try {
123
+ const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/health`, {
124
+ timeout: 3e3
125
+ });
126
+ if (!resp.ok) {
127
+ return { moss_version: "N/A", moss_status: "error" };
128
+ }
129
+ const data = await resp.json();
130
+ return {
131
+ moss_version: data.version || "unknown",
132
+ moss_status: data.status || "unknown"
133
+ };
134
+ } catch {
135
+ return { moss_version: "N/A", moss_status: "unreachable" };
136
+ }
137
+ }
138
+ async function callAgentMossReview(options) {
139
+ const { agentId = "", dbPath = "" } = options;
140
+ if (!dbPath) return;
141
+ try {
142
+ const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/review`, {
143
+ method: "POST",
144
+ headers: { "Content-Type": "application/json" },
145
+ body: JSON.stringify({ agent_id: agentId, db_path: dbPath }),
146
+ timeout: 3e4
147
+ });
148
+ if (!resp.ok) {
149
+ console.error(`[AgentGate] AgentMoss review HTTP ${resp.status}: ${resp.statusText}`);
150
+ }
151
+ } catch (err) {
152
+ console.error(`[AgentGate] AgentMoss review unreachable: ${String(err?.message || err)}`);
153
+ }
154
+ }
155
+ function failClosedResponse(reason, riskType = "service_unavailable") {
156
+ return {
157
+ decision: "Deny",
158
+ reason,
159
+ risk_level: "high",
160
+ risk_type: riskType,
161
+ violated_layers: [],
162
+ confidence: 100
163
+ };
164
+ }
165
+ var import_node_fetch, DEFAULT_MOSS_URL, mossUrl;
166
+ var init_moss_client = __esm({
167
+ "src/shared/moss-client.ts"() {
168
+ "use strict";
169
+ init_cjs_shims();
170
+ import_node_fetch = __toESM(require("node-fetch"));
171
+ init_multi_session();
172
+ DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
173
+ mossUrl = DEFAULT_MOSS_URL;
174
+ }
175
+ });
176
+
43
177
  // src/shared/storage/json-storage.ts
44
178
  var json_storage_exports = {};
45
179
  __export(json_storage_exports, {
@@ -66,7 +200,9 @@ var init_json_storage = __esm({
66
200
  sessionsPath;
67
201
  toolCallsDir;
68
202
  nextId;
69
- /** per-session 互斥锁,保证同一 session 的 seq 生成 + 写入原子性 */
203
+ /** per-session 互斥锁,保证同一 session 的 seq 生成 + 写入原子性。
204
+ * 值只用来做 Promise 链式串联,其 resolve 值无人使用,故用 Promise<unknown>
205
+ * (锁链上的 then 会返回 seq 等值,标成 Promise<void> 会对不上)。 */
70
206
  sessionLocks = /* @__PURE__ */ new Map();
71
207
  constructor(dataDir) {
72
208
  this.dataDir = dataDir || process.env.AGENT_GATE_DATA_DIR || getDefaultDataDir();
@@ -185,10 +321,11 @@ var init_json_storage = __esm({
185
321
  this.saveToolCalls(sessionId, records);
186
322
  return id;
187
323
  });
188
- this.sessionLocks.set(sessionId, next.catch(() => {
189
- }));
324
+ const guarded = next.catch(() => {
325
+ });
326
+ this.sessionLocks.set(sessionId, guarded);
190
327
  const cleanup = () => {
191
- if (this.sessionLocks.get(sessionId) === next) {
328
+ if (this.sessionLocks.get(sessionId) === guarded) {
192
329
  this.sessionLocks.delete(sessionId);
193
330
  }
194
331
  };
@@ -242,6 +379,35 @@ var init_json_storage = __esm({
242
379
  }
243
380
  return allRecords.length;
244
381
  }
382
+ getStorageStats() {
383
+ let toolCalls = 0;
384
+ let jsonFiles = 0;
385
+ let jsonBytes = 0;
386
+ try {
387
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
388
+ for (const file of files) {
389
+ const stat = (0, import_fs.statSync)((0, import_path.join)(this.toolCallsDir, file));
390
+ jsonFiles++;
391
+ jsonBytes += stat.size;
392
+ const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
393
+ toolCalls += records.length;
394
+ }
395
+ } catch {
396
+ }
397
+ return { dbBytes: 0, toolCalls, jsonFiles, jsonBytes };
398
+ }
399
+ clearToolCalls() {
400
+ let removed = 0;
401
+ try {
402
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
403
+ for (const file of files) {
404
+ (0, import_fs.unlinkSync)((0, import_path.join)(this.toolCallsDir, file));
405
+ removed++;
406
+ }
407
+ } catch {
408
+ }
409
+ return removed;
410
+ }
245
411
  enrichRecord(record, sessions, agents) {
246
412
  const session = sessions.get(record.session_id);
247
413
  const agentId = session?.agent_id;
@@ -372,6 +538,7 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
372
538
  `;
373
539
  SqliteStorage = class {
374
540
  db;
541
+ dbPath;
375
542
  constructor(dbPath) {
376
543
  let Database;
377
544
  try {
@@ -384,6 +551,7 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
384
551
  const path = dbPath || getDefaultDbPath();
385
552
  const dir = (0, import_path2.dirname)(path);
386
553
  if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true });
554
+ this.dbPath = path;
387
555
  this.db = new Database(path);
388
556
  this.db.pragma("journal_mode = WAL");
389
557
  this.db.exec(SCHEMA);
@@ -487,6 +655,28 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
487
655
  ).get(...values);
488
656
  return row?.total ?? 0;
489
657
  }
658
+ getStorageStats() {
659
+ const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
660
+ let dbBytes = 0;
661
+ try {
662
+ const { statSync: statSync2, existsSync: existsSync3 } = require("fs");
663
+ dbBytes = statSync2(this.dbPath).size;
664
+ for (const suffix of ["-wal", "-shm"]) {
665
+ const p = this.dbPath + suffix;
666
+ if (existsSync3(p)) dbBytes += statSync2(p).size;
667
+ }
668
+ } catch {
669
+ }
670
+ return { dbBytes, toolCalls: row?.total ?? 0, jsonFiles: 0, jsonBytes: 0 };
671
+ }
672
+ clearToolCalls() {
673
+ const result = this.db.transaction(() => {
674
+ const deleted = this.db.prepare("DELETE FROM tool_calls").run();
675
+ this.db.prepare("UPDATE sessions SET tool_call_count = 0").run();
676
+ return Number(deleted.changes);
677
+ })();
678
+ return result;
679
+ }
490
680
  getAgentsList() {
491
681
  return this.db.prepare(`
492
682
  SELECT a.agent_type, a.hostname, a.agent_version as version,
@@ -529,6 +719,94 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
529
719
  }
530
720
  });
531
721
 
722
+ // src/shared/storage/db.ts
723
+ var db_exports = {};
724
+ __export(db_exports, {
725
+ closeDb: () => closeDb,
726
+ createStorage: () => createStorage,
727
+ getAgentGateDbPath: () => getAgentGateDbPath,
728
+ getDb: () => getDb,
729
+ getStorage: () => getStorage
730
+ });
731
+ function createStorage(opts) {
732
+ if (storage) return storage;
733
+ const backend = (process.env.AGENT_GATE_STORAGE || "").toLowerCase() || (process.platform === "openharmony" ? "json" : "sqlite");
734
+ if (backend === "json") {
735
+ const { JsonStorage: JsonStorage2 } = (init_json_storage(), __toCommonJS(json_storage_exports));
736
+ storage = new JsonStorage2(opts?.dataDir);
737
+ console.log("[AgentGate] Storage: JSON files");
738
+ } else {
739
+ try {
740
+ require.resolve("better-sqlite3");
741
+ } catch {
742
+ console.error(
743
+ "[AgentGate] better-sqlite3 is not installed. Set AGENT_GATE_STORAGE=json or install better-sqlite3."
744
+ );
745
+ process.exit(1);
746
+ }
747
+ const { SqliteStorage: SqliteStorage2 } = (init_sqlite_storage(), __toCommonJS(sqlite_storage_exports));
748
+ storage = new SqliteStorage2(opts?.dbPath);
749
+ console.log("[AgentGate] Storage: SQLite");
750
+ }
751
+ return storage;
752
+ }
753
+ function getStorage() {
754
+ return storage;
755
+ }
756
+ function getDb(dbPath) {
757
+ if (rawDb) return rawDb;
758
+ try {
759
+ const Database = require("better-sqlite3");
760
+ const { existsSync: existsSync3, mkdirSync: mkdirSync3 } = require("fs");
761
+ const { join: join3, dirname: dirname3 } = require("path");
762
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
763
+ const xdgData = process.env.XDG_DATA_HOME || join3(home, ".local", "share");
764
+ const defaultPath = join3(xdgData, "agent_gate", "agent_gate_ts.db");
765
+ const path = dbPath || defaultPath;
766
+ const dir = dirname3(path);
767
+ if (!existsSync3(dir)) mkdirSync3(dir, { recursive: true });
768
+ rawDb = new Database(path);
769
+ rawDb.pragma("journal_mode = WAL");
770
+ return rawDb;
771
+ } catch {
772
+ throw new Error("better-sqlite3 is not available. Use AGENT_GATE_STORAGE=json.");
773
+ }
774
+ }
775
+ function getAgentGateDbPath() {
776
+ const envDb = process.env.AGENT_GATE_DB;
777
+ if (envDb) return envDb;
778
+ const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
779
+ if (backend === "json") {
780
+ const dataDir = process.env.AGENT_GATE_DATA_DIR || "";
781
+ if (dataDir) return dataDir;
782
+ const home2 = process.env.HOME || process.env.USERPROFILE || "/tmp";
783
+ const xdgData2 = process.env.XDG_DATA_HOME || require("path").join(home2, ".local", "share");
784
+ return require("path").join(xdgData2, "agent_gate", "tool_calls");
785
+ }
786
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
787
+ const xdgData = process.env.XDG_DATA_HOME || require("path").join(home, ".local", "share");
788
+ return require("path").join(xdgData, "agent_gate", "agent_gate_ts.db");
789
+ }
790
+ function closeDb() {
791
+ if (storage) {
792
+ storage.close();
793
+ storage = null;
794
+ }
795
+ if (rawDb) {
796
+ rawDb.close();
797
+ rawDb = null;
798
+ }
799
+ }
800
+ var storage, rawDb;
801
+ var init_db = __esm({
802
+ "src/shared/storage/db.ts"() {
803
+ "use strict";
804
+ init_cjs_shims();
805
+ storage = null;
806
+ rawDb = null;
807
+ }
808
+ });
809
+
532
810
  // src/v1/server.ts
533
811
  var server_exports = {};
534
812
  __export(server_exports, {
@@ -549,7 +827,7 @@ var import_zod = require("zod");
549
827
 
550
828
  // src/version.ts
551
829
  init_cjs_shims();
552
- var _version = true ? "0.6.3" : (() => {
830
+ var _version = true ? "0.7.2" : (() => {
553
831
  try {
554
832
  const require2 = createRequire(importMetaUrl);
555
833
  const pkg = require2("../package.json");
@@ -585,6 +863,13 @@ var AgentGateInputSchema = import_zod.z.object({
585
863
  action_type: import_zod.z.string(),
586
864
  action_detail: import_zod.z.string()
587
865
  })).default([]),
866
+ session_history: import_zod.z.array(import_zod.z.object({
867
+ session_id: import_zod.z.string(),
868
+ action_history: import_zod.z.array(import_zod.z.object({
869
+ action_type: import_zod.z.string(),
870
+ action_detail: import_zod.z.string()
871
+ })).default([])
872
+ })).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"),
588
873
  metadata: import_zod.z.record(import_zod.z.unknown()).optional()
589
874
  });
590
875
  var AgentGateResponseSchema = import_zod.z.object({
@@ -595,6 +880,8 @@ var AgentGateResponseSchema = import_zod.z.object({
595
880
  violated_layers: import_zod.z.array(import_zod.z.string()).default([]),
596
881
  confidence: import_zod.z.number().int().min(0).max(100).default(100),
597
882
  analysis_duration_ms: import_zod.z.number().default(0),
883
+ oversize: import_zod.z.boolean().optional().describe("\u672C\u5730\u5B58\u50A8\u662F\u5426\u8D85\u8FC7\u6E05\u7406\u9608\u503C\uFF08agg \u7528\uFF09"),
884
+ thresholdMB: import_zod.z.number().optional().describe("\u5B58\u50A8\u6E05\u7406\u9608\u503C MB\uFF08agg \u7528\uFF09"),
598
885
  collected_context: import_zod.z.object({
599
886
  os: import_zod.z.object({
600
887
  system: import_zod.z.string(),
@@ -620,11 +907,19 @@ var HealthResponseSchema = import_zod.z.object({
620
907
 
621
908
  // src/shared/normalizer.ts
622
909
  init_cjs_shims();
910
+ init_multi_session();
623
911
  function normalize(input, systemContext) {
624
912
  const actionHistory = input.action_history.map((h) => ({
625
913
  action_type: h.action_type,
626
914
  action_detail: h.action_detail
627
915
  }));
916
+ const sessionHistory = (input.session_history || []).map((s) => ({
917
+ session_id: s.session_id,
918
+ action_history: s.action_history.map((h) => ({
919
+ action_type: h.action_type,
920
+ action_detail: h.action_detail
921
+ }))
922
+ }));
628
923
  const promptHistory = input.prompt_history.map((t) => ({
629
924
  text: t.text,
630
925
  actions: t.actions.map((a) => ({
@@ -639,6 +934,7 @@ function normalize(input, systemContext) {
639
934
  prompt_session: input.user_prompt || input.description || "",
640
935
  prompt_history: promptHistory,
641
936
  action_history: actionHistory,
937
+ session_history: sessionHistory,
642
938
  a_next: {
643
939
  action_type: toolName,
644
940
  action_detail: command
@@ -656,7 +952,12 @@ function normalize(input, systemContext) {
656
952
  ...input.metadata,
657
953
  agent_type: input.agent_type,
658
954
  agent_version: input.agent_version,
659
- system_context: systemContext
955
+ system_context: systemContext,
956
+ // L2.4 stateful incremental:让 AgentMoss 把每条 tool call 计入该 agent 的
957
+ // 持久化时间线并即时推进链指针(跨 session/长时距组合链的最后一步当场 Deny)。
958
+ // 由 AGENT_GATE_MULTI_SESSION=1(OpenDesk 设置页"多 session 分析"开关)门控;
959
+ // 关闭时不注入,回到纯单 session 行为,零跨会话开销。
960
+ ...isStatefulIncrementalEnabled() ? { stateful_incremental: true } : {}
660
961
  }
661
962
  };
662
963
  }
@@ -724,64 +1025,8 @@ async function collectSystemContext() {
724
1025
  return { os: os3, process: proc, user };
725
1026
  }
726
1027
 
727
- // src/shared/moss-client.ts
728
- init_cjs_shims();
729
- var import_node_fetch = __toESM(require("node-fetch"));
730
- var DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
731
- var mossUrl = DEFAULT_MOSS_URL;
732
- async function callAgentMoss(request) {
733
- try {
734
- const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
735
- method: "POST",
736
- headers: { "Content-Type": "application/json" },
737
- body: JSON.stringify(request),
738
- // 100s:覆盖 AgentMoss 总超时(90s)+ 余量,避免 AgentMoss 还在分析时
739
- // 被 AgentGate 抢断后 fail-closed 误杀。AgentGate 这层不重试(AgentMoss 内部已重试)。
740
- timeout: 1e5
741
- });
742
- if (!resp.ok) {
743
- console.error(`[AgentGate] AgentMoss HTTP ${resp.status}: ${resp.statusText}`);
744
- return failClosedResponse(`AgentMoss returned ${resp.status}`);
745
- }
746
- return await resp.json();
747
- } catch (err) {
748
- const errType = err?.type || "";
749
- const errMsg = String(err?.message || err);
750
- if (errType === "request-timeout" || errMsg.includes("timeout")) {
751
- console.error(`[AgentGate] AgentMoss analysis timeout: ${errMsg}`);
752
- return failClosedResponse("AgentMoss analysis timeout", "analysis_timeout");
753
- }
754
- console.error(`[AgentGate] AgentMoss unreachable: ${errMsg}`);
755
- return failClosedResponse("AgentMoss service unavailable", "service_unavailable");
756
- }
757
- }
758
- async function fetchMossHealth() {
759
- try {
760
- const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/health`, {
761
- timeout: 3e3
762
- });
763
- if (!resp.ok) {
764
- return { moss_version: "N/A", moss_status: "error" };
765
- }
766
- const data = await resp.json();
767
- return {
768
- moss_version: data.version || "unknown",
769
- moss_status: data.status || "unknown"
770
- };
771
- } catch {
772
- return { moss_version: "N/A", moss_status: "unreachable" };
773
- }
774
- }
775
- function failClosedResponse(reason, riskType = "service_unavailable") {
776
- return {
777
- decision: "Deny",
778
- reason,
779
- risk_level: "high",
780
- risk_type: riskType,
781
- violated_layers: [],
782
- confidence: 100
783
- };
784
- }
1028
+ // src/v1/routes.ts
1029
+ init_moss_client();
785
1030
 
786
1031
  // src/shared/cache.ts
787
1032
  init_cjs_shims();
@@ -810,34 +1055,7 @@ function setCache(key, result) {
810
1055
 
811
1056
  // src/shared/storage/repository.ts
812
1057
  init_cjs_shims();
813
-
814
- // src/shared/storage/db.ts
815
- init_cjs_shims();
816
- var storage = null;
817
- function createStorage(opts) {
818
- if (storage) return storage;
819
- const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
820
- if (backend === "json") {
821
- const { JsonStorage: JsonStorage2 } = (init_json_storage(), __toCommonJS(json_storage_exports));
822
- storage = new JsonStorage2(opts?.dataDir);
823
- console.log("[AgentGate] Storage: JSON files");
824
- } else {
825
- try {
826
- require.resolve("better-sqlite3");
827
- } catch {
828
- console.error(
829
- "[AgentGate] better-sqlite3 is not installed. Set AGENT_GATE_STORAGE=json or install better-sqlite3."
830
- );
831
- process.exit(1);
832
- }
833
- const { SqliteStorage: SqliteStorage2 } = (init_sqlite_storage(), __toCommonJS(sqlite_storage_exports));
834
- storage = new SqliteStorage2(opts?.dbPath);
835
- console.log("[AgentGate] Storage: SQLite");
836
- }
837
- return storage;
838
- }
839
-
840
- // src/shared/storage/repository.ts
1058
+ init_db();
841
1059
  function store() {
842
1060
  return createStorage();
843
1061
  }
@@ -859,6 +1077,12 @@ function queryToolCalls(params) {
859
1077
  function countToolCalls(params) {
860
1078
  return store().countToolCalls(params);
861
1079
  }
1080
+ function getStorageStats() {
1081
+ return store().getStorageStats();
1082
+ }
1083
+ function clearToolCalls() {
1084
+ return store().clearToolCalls();
1085
+ }
862
1086
  function getAgentsList() {
863
1087
  return store().getAgentsList();
864
1088
  }
@@ -867,6 +1091,19 @@ function getTimeline(limit) {
867
1091
  }
868
1092
 
869
1093
  // src/v1/routes.ts
1094
+ init_multi_session();
1095
+
1096
+ // src/shared/agent-identity.ts
1097
+ init_cjs_shims();
1098
+ function resolveAgentIdentity(metadata, collected) {
1099
+ return {
1100
+ hostname: String(metadata?.hostname || "") || String(collected?.hostname || "") || "unknown",
1101
+ osType: String(metadata?.os_type || "") || String(collected?.system || "")
1102
+ };
1103
+ }
1104
+
1105
+ // src/v1/routes.ts
1106
+ var v1ReviewCounter = 0;
870
1107
  async function healthRoute(c) {
871
1108
  const mossHealth = await fetchMossHealth();
872
1109
  return c.json({
@@ -876,6 +1113,12 @@ async function healthRoute(c) {
876
1113
  moss_status: mossHealth.moss_status
877
1114
  });
878
1115
  }
1116
+ function storageOversizeInfo() {
1117
+ const stats = getStorageStats();
1118
+ const thresholdMB = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
1119
+ const totalMB = (stats.dbBytes + stats.jsonBytes) / 1024 / 1024;
1120
+ return { oversize: totalMB > thresholdMB, thresholdMB };
1121
+ }
879
1122
  async function analyzeRoute(c) {
880
1123
  const t0 = performance.now();
881
1124
  try {
@@ -889,14 +1132,24 @@ async function analyzeRoute(c) {
889
1132
  return c.json({
890
1133
  ...cached,
891
1134
  analysis_duration_ms: 0,
892
- collected_context: {}
1135
+ collected_context: {},
1136
+ ...storageOversizeInfo()
893
1137
  });
894
1138
  }
895
1139
  const context = await collectSystemContext();
1140
+ if (isMultiSessionEnabled()) {
1141
+ input.session_history = buildSessionHistory(
1142
+ (params) => queryToolCalls(params),
1143
+ input.session_id
1144
+ );
1145
+ }
896
1146
  const mossRequest = normalize(input, context);
897
- const hostname = context.os?.hostname || "unknown";
1147
+ const { hostname, osType } = resolveAgentIdentity(
1148
+ input.metadata,
1149
+ context.os
1150
+ );
898
1151
  const agentId = getOrCreateAgent(input.agent_type, hostname, input.agent_version);
899
- getOrCreateSession(input.session_id, agentId, input.cwd, input.user_prompt, String(context.os?.system || ""));
1152
+ getOrCreateSession(input.session_id, agentId, input.cwd, input.user_prompt, osType);
900
1153
  const mossResult = await callAgentMoss(mossRequest);
901
1154
  insertToolCall({
902
1155
  session_id: input.session_id,
@@ -916,6 +1169,17 @@ async function analyzeRoute(c) {
916
1169
  analysis_duration_ms: performance.now() - t0
917
1170
  });
918
1171
  setCache(key, mossResult);
1172
+ if (isMultiSessionEnabled()) {
1173
+ v1ReviewCounter++;
1174
+ if (v1ReviewCounter % 100 === 0) {
1175
+ try {
1176
+ const { getAgentGateDbPath: getAgentGateDbPath2 } = (init_db(), __toCommonJS(db_exports));
1177
+ const { callAgentMossReview: callAgentMossReview2 } = (init_moss_client(), __toCommonJS(moss_client_exports));
1178
+ void callAgentMossReview2({ agentId, dbPath: getAgentGateDbPath2() });
1179
+ } catch {
1180
+ }
1181
+ }
1182
+ }
919
1183
  const durationMs = performance.now() - t0;
920
1184
  return c.json(
921
1185
  AgentGateResponseSchema.parse({
@@ -926,6 +1190,7 @@ async function analyzeRoute(c) {
926
1190
  violated_layers: mossResult.violated_layers,
927
1191
  confidence: mossResult.confidence,
928
1192
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
1193
+ ...storageOversizeInfo(),
929
1194
  collected_context: {
930
1195
  os: context.os,
931
1196
  process: context.process,
@@ -960,11 +1225,21 @@ async function timelineRoute(c) {
960
1225
  const rows = getTimeline(limit);
961
1226
  return c.json(rows);
962
1227
  }
1228
+ function storageStatsRoute(c) {
1229
+ const storageStats = getStorageStats();
1230
+ const defaultThreshold = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
1231
+ const totalMB = (storageStats.dbBytes + storageStats.jsonBytes) / 1024 / 1024;
1232
+ return c.json({ stats: storageStats, oversize: totalMB > defaultThreshold, thresholdMB: defaultThreshold });
1233
+ }
1234
+ function deleteToolCallsRoute(c) {
1235
+ const deleted = clearToolCalls();
1236
+ return c.json({ deleted });
1237
+ }
963
1238
 
964
1239
  // src/v1/server.ts
965
1240
  function createApp() {
966
1241
  const app = new import_hono.Hono();
967
- app.use("*", (0, import_cors.cors)({ origin: "*", allowMethods: ["GET", "POST", "OPTIONS"], allowHeaders: ["*"] }));
1242
+ app.use("*", (0, import_cors.cors)({ origin: "*", allowMethods: ["GET", "POST", "OPTIONS", "DELETE"], allowHeaders: ["*"] }));
968
1243
  app.use("*", (0, import_logger.logger)());
969
1244
  app.get("/api/v1/health", healthRoute);
970
1245
  app.post("/api/v1/analyze", analyzeRoute);
@@ -972,6 +1247,8 @@ function createApp() {
972
1247
  app.get("/api/v1/tool_calls", toolCallsRoute);
973
1248
  app.get("/api/v1/agents", agentsRoute);
974
1249
  app.get("/api/v1/timeline", timelineRoute);
1250
+ app.get("/api/v1/storage_stats", storageStatsRoute);
1251
+ app.delete("/api/v1/tool_calls", deleteToolCallsRoute);
975
1252
  app.get("/dashboard/", dashboardRoute);
976
1253
  app.get("/dashboard", (c) => c.redirect("/dashboard/"));
977
1254
  return app;
@@ -994,4 +1271,3 @@ async function dashboardRoute(c) {
994
1271
  0 && (module.exports = {
995
1272
  createApp
996
1273
  });
997
- //# sourceMappingURL=server.js.map