@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/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, {
@@ -242,6 +376,35 @@ var init_json_storage = __esm({
242
376
  }
243
377
  return allRecords.length;
244
378
  }
379
+ getStorageStats() {
380
+ let toolCalls = 0;
381
+ let jsonFiles = 0;
382
+ let jsonBytes = 0;
383
+ try {
384
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
385
+ for (const file of files) {
386
+ const stat = (0, import_fs.statSync)((0, import_path.join)(this.toolCallsDir, file));
387
+ jsonFiles++;
388
+ jsonBytes += stat.size;
389
+ const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
390
+ toolCalls += records.length;
391
+ }
392
+ } catch {
393
+ }
394
+ return { dbBytes: 0, toolCalls, jsonFiles, jsonBytes };
395
+ }
396
+ clearToolCalls() {
397
+ let removed = 0;
398
+ try {
399
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
400
+ for (const file of files) {
401
+ (0, import_fs.unlinkSync)((0, import_path.join)(this.toolCallsDir, file));
402
+ removed++;
403
+ }
404
+ } catch {
405
+ }
406
+ return removed;
407
+ }
245
408
  enrichRecord(record, sessions, agents) {
246
409
  const session = sessions.get(record.session_id);
247
410
  const agentId = session?.agent_id;
@@ -372,6 +535,7 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
372
535
  `;
373
536
  SqliteStorage = class {
374
537
  db;
538
+ dbPath;
375
539
  constructor(dbPath) {
376
540
  let Database;
377
541
  try {
@@ -384,6 +548,7 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
384
548
  const path = dbPath || getDefaultDbPath();
385
549
  const dir = (0, import_path2.dirname)(path);
386
550
  if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true });
551
+ this.dbPath = path;
387
552
  this.db = new Database(path);
388
553
  this.db.pragma("journal_mode = WAL");
389
554
  this.db.exec(SCHEMA);
@@ -487,6 +652,28 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
487
652
  ).get(...values);
488
653
  return row?.total ?? 0;
489
654
  }
655
+ getStorageStats() {
656
+ const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
657
+ let dbBytes = 0;
658
+ try {
659
+ const { statSync: statSync2, existsSync: existsSync3 } = require("fs");
660
+ dbBytes = statSync2(this.dbPath).size;
661
+ for (const suffix of ["-wal", "-shm"]) {
662
+ const p = this.dbPath + suffix;
663
+ if (existsSync3(p)) dbBytes += statSync2(p).size;
664
+ }
665
+ } catch {
666
+ }
667
+ return { dbBytes, toolCalls: row?.total ?? 0, jsonFiles: 0, jsonBytes: 0 };
668
+ }
669
+ clearToolCalls() {
670
+ const result = this.db.transaction(() => {
671
+ const deleted = this.db.prepare("DELETE FROM tool_calls").run();
672
+ this.db.prepare("UPDATE sessions SET tool_call_count = 0").run();
673
+ return Number(deleted.changes);
674
+ })();
675
+ return result;
676
+ }
490
677
  getAgentsList() {
491
678
  return this.db.prepare(`
492
679
  SELECT a.agent_type, a.hostname, a.agent_version as version,
@@ -529,6 +716,94 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
529
716
  }
530
717
  });
531
718
 
719
+ // src/shared/storage/db.ts
720
+ var db_exports = {};
721
+ __export(db_exports, {
722
+ closeDb: () => closeDb,
723
+ createStorage: () => createStorage,
724
+ getAgentGateDbPath: () => getAgentGateDbPath,
725
+ getDb: () => getDb,
726
+ getStorage: () => getStorage
727
+ });
728
+ function createStorage(opts) {
729
+ if (storage) return storage;
730
+ const backend = (process.env.AGENT_GATE_STORAGE || "").toLowerCase() || (process.platform === "openharmony" ? "json" : "sqlite");
731
+ if (backend === "json") {
732
+ const { JsonStorage: JsonStorage2 } = (init_json_storage(), __toCommonJS(json_storage_exports));
733
+ storage = new JsonStorage2(opts?.dataDir);
734
+ console.log("[AgentGate] Storage: JSON files");
735
+ } else {
736
+ try {
737
+ require.resolve("better-sqlite3");
738
+ } catch {
739
+ console.error(
740
+ "[AgentGate] better-sqlite3 is not installed. Set AGENT_GATE_STORAGE=json or install better-sqlite3."
741
+ );
742
+ process.exit(1);
743
+ }
744
+ const { SqliteStorage: SqliteStorage2 } = (init_sqlite_storage(), __toCommonJS(sqlite_storage_exports));
745
+ storage = new SqliteStorage2(opts?.dbPath);
746
+ console.log("[AgentGate] Storage: SQLite");
747
+ }
748
+ return storage;
749
+ }
750
+ function getStorage() {
751
+ return storage;
752
+ }
753
+ function getDb(dbPath) {
754
+ if (rawDb) return rawDb;
755
+ try {
756
+ const Database = require("better-sqlite3");
757
+ const { existsSync: existsSync3, mkdirSync: mkdirSync3 } = require("fs");
758
+ const { join: join3, dirname: dirname3 } = require("path");
759
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
760
+ const xdgData = process.env.XDG_DATA_HOME || join3(home, ".local", "share");
761
+ const defaultPath = join3(xdgData, "agent_gate", "agent_gate_ts.db");
762
+ const path = dbPath || defaultPath;
763
+ const dir = dirname3(path);
764
+ if (!existsSync3(dir)) mkdirSync3(dir, { recursive: true });
765
+ rawDb = new Database(path);
766
+ rawDb.pragma("journal_mode = WAL");
767
+ return rawDb;
768
+ } catch {
769
+ throw new Error("better-sqlite3 is not available. Use AGENT_GATE_STORAGE=json.");
770
+ }
771
+ }
772
+ function getAgentGateDbPath() {
773
+ const envDb = process.env.AGENT_GATE_DB;
774
+ if (envDb) return envDb;
775
+ const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
776
+ if (backend === "json") {
777
+ const dataDir = process.env.AGENT_GATE_DATA_DIR || "";
778
+ if (dataDir) return dataDir;
779
+ const home2 = process.env.HOME || process.env.USERPROFILE || "/tmp";
780
+ const xdgData2 = process.env.XDG_DATA_HOME || require("path").join(home2, ".local", "share");
781
+ return require("path").join(xdgData2, "agent_gate", "tool_calls");
782
+ }
783
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
784
+ const xdgData = process.env.XDG_DATA_HOME || require("path").join(home, ".local", "share");
785
+ return require("path").join(xdgData, "agent_gate", "agent_gate_ts.db");
786
+ }
787
+ function closeDb() {
788
+ if (storage) {
789
+ storage.close();
790
+ storage = null;
791
+ }
792
+ if (rawDb) {
793
+ rawDb.close();
794
+ rawDb = null;
795
+ }
796
+ }
797
+ var storage, rawDb;
798
+ var init_db = __esm({
799
+ "src/shared/storage/db.ts"() {
800
+ "use strict";
801
+ init_cjs_shims();
802
+ storage = null;
803
+ rawDb = null;
804
+ }
805
+ });
806
+
532
807
  // src/v1/server.ts
533
808
  var server_exports = {};
534
809
  __export(server_exports, {
@@ -549,7 +824,7 @@ var import_zod = require("zod");
549
824
 
550
825
  // src/version.ts
551
826
  init_cjs_shims();
552
- var _version = true ? "0.6.2" : (() => {
827
+ var _version = true ? "0.7.0" : (() => {
553
828
  try {
554
829
  const require2 = createRequire(importMetaUrl);
555
830
  const pkg = require2("../package.json");
@@ -574,10 +849,24 @@ var AgentGateInputSchema = import_zod.z.object({
574
849
  cwd: import_zod.z.string().default(""),
575
850
  description: import_zod.z.string().default(""),
576
851
  user_prompt: import_zod.z.string().default(""),
852
+ prompt_history: import_zod.z.array(import_zod.z.object({
853
+ text: import_zod.z.string().default(""),
854
+ actions: import_zod.z.array(import_zod.z.object({
855
+ action_type: import_zod.z.string(),
856
+ action_detail: import_zod.z.string()
857
+ })).default([])
858
+ })).default([]),
577
859
  action_history: import_zod.z.array(import_zod.z.object({
578
860
  action_type: import_zod.z.string(),
579
861
  action_detail: import_zod.z.string()
580
862
  })).default([]),
863
+ session_history: import_zod.z.array(import_zod.z.object({
864
+ session_id: import_zod.z.string(),
865
+ action_history: import_zod.z.array(import_zod.z.object({
866
+ action_type: import_zod.z.string(),
867
+ action_detail: import_zod.z.string()
868
+ })).default([])
869
+ })).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"),
581
870
  metadata: import_zod.z.record(import_zod.z.unknown()).optional()
582
871
  });
583
872
  var AgentGateResponseSchema = import_zod.z.object({
@@ -588,6 +877,8 @@ var AgentGateResponseSchema = import_zod.z.object({
588
877
  violated_layers: import_zod.z.array(import_zod.z.string()).default([]),
589
878
  confidence: import_zod.z.number().int().min(0).max(100).default(100),
590
879
  analysis_duration_ms: import_zod.z.number().default(0),
880
+ oversize: import_zod.z.boolean().optional().describe("\u672C\u5730\u5B58\u50A8\u662F\u5426\u8D85\u8FC7\u6E05\u7406\u9608\u503C\uFF08agg \u7528\uFF09"),
881
+ thresholdMB: import_zod.z.number().optional().describe("\u5B58\u50A8\u6E05\u7406\u9608\u503C MB\uFF08agg \u7528\uFF09"),
591
882
  collected_context: import_zod.z.object({
592
883
  os: import_zod.z.object({
593
884
  system: import_zod.z.string(),
@@ -613,17 +904,34 @@ var HealthResponseSchema = import_zod.z.object({
613
904
 
614
905
  // src/shared/normalizer.ts
615
906
  init_cjs_shims();
907
+ init_multi_session();
616
908
  function normalize(input, systemContext) {
617
909
  const actionHistory = input.action_history.map((h) => ({
618
910
  action_type: h.action_type,
619
911
  action_detail: h.action_detail
620
912
  }));
913
+ const sessionHistory = (input.session_history || []).map((s) => ({
914
+ session_id: s.session_id,
915
+ action_history: s.action_history.map((h) => ({
916
+ action_type: h.action_type,
917
+ action_detail: h.action_detail
918
+ }))
919
+ }));
920
+ const promptHistory = input.prompt_history.map((t) => ({
921
+ text: t.text,
922
+ actions: t.actions.map((a) => ({
923
+ action_type: a.action_type,
924
+ action_detail: a.action_detail
925
+ }))
926
+ }));
621
927
  const toolName = input.tool_name || input.a_next?.action_type || "unknown";
622
928
  const command = input.command || input.a_next?.action_detail || "";
623
929
  return {
624
930
  session_id: input.session_id,
625
931
  prompt_session: input.user_prompt || input.description || "",
932
+ prompt_history: promptHistory,
626
933
  action_history: actionHistory,
934
+ session_history: sessionHistory,
627
935
  a_next: {
628
936
  action_type: toolName,
629
937
  action_detail: command
@@ -641,7 +949,12 @@ function normalize(input, systemContext) {
641
949
  ...input.metadata,
642
950
  agent_type: input.agent_type,
643
951
  agent_version: input.agent_version,
644
- system_context: systemContext
952
+ system_context: systemContext,
953
+ // L2.4 stateful incremental:让 AgentMoss 把每条 tool call 计入该 agent 的
954
+ // 持久化时间线并即时推进链指针(跨 session/长时距组合链的最后一步当场 Deny)。
955
+ // 由 AGENT_GATE_MULTI_SESSION=1(OpenDesk 设置页"多 session 分析"开关)门控;
956
+ // 关闭时不注入,回到纯单 session 行为,零跨会话开销。
957
+ ...isStatefulIncrementalEnabled() ? { stateful_incremental: true } : {}
645
958
  }
646
959
  };
647
960
  }
@@ -709,64 +1022,8 @@ async function collectSystemContext() {
709
1022
  return { os: os3, process: proc, user };
710
1023
  }
711
1024
 
712
- // src/shared/moss-client.ts
713
- init_cjs_shims();
714
- var import_node_fetch = __toESM(require("node-fetch"));
715
- var DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
716
- var mossUrl = DEFAULT_MOSS_URL;
717
- async function callAgentMoss(request) {
718
- try {
719
- const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
720
- method: "POST",
721
- headers: { "Content-Type": "application/json" },
722
- body: JSON.stringify(request),
723
- // 100s:覆盖 AgentMoss 总超时(90s)+ 余量,避免 AgentMoss 还在分析时
724
- // 被 AgentGate 抢断后 fail-closed 误杀。AgentGate 这层不重试(AgentMoss 内部已重试)。
725
- timeout: 1e5
726
- });
727
- if (!resp.ok) {
728
- console.error(`[AgentGate] AgentMoss HTTP ${resp.status}: ${resp.statusText}`);
729
- return failClosedResponse(`AgentMoss returned ${resp.status}`);
730
- }
731
- return await resp.json();
732
- } catch (err) {
733
- const errType = err?.type || "";
734
- const errMsg = String(err?.message || err);
735
- if (errType === "request-timeout" || errMsg.includes("timeout")) {
736
- console.error(`[AgentGate] AgentMoss analysis timeout: ${errMsg}`);
737
- return failClosedResponse("AgentMoss analysis timeout", "analysis_timeout");
738
- }
739
- console.error(`[AgentGate] AgentMoss unreachable: ${errMsg}`);
740
- return failClosedResponse("AgentMoss service unavailable", "service_unavailable");
741
- }
742
- }
743
- async function fetchMossHealth() {
744
- try {
745
- const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/health`, {
746
- timeout: 3e3
747
- });
748
- if (!resp.ok) {
749
- return { moss_version: "N/A", moss_status: "error" };
750
- }
751
- const data = await resp.json();
752
- return {
753
- moss_version: data.version || "unknown",
754
- moss_status: data.status || "unknown"
755
- };
756
- } catch {
757
- return { moss_version: "N/A", moss_status: "unreachable" };
758
- }
759
- }
760
- function failClosedResponse(reason, riskType = "service_unavailable") {
761
- return {
762
- decision: "Deny",
763
- reason,
764
- risk_level: "high",
765
- risk_type: riskType,
766
- violated_layers: [],
767
- confidence: 100
768
- };
769
- }
1025
+ // src/v1/routes.ts
1026
+ init_moss_client();
770
1027
 
771
1028
  // src/shared/cache.ts
772
1029
  init_cjs_shims();
@@ -795,34 +1052,7 @@ function setCache(key, result) {
795
1052
 
796
1053
  // src/shared/storage/repository.ts
797
1054
  init_cjs_shims();
798
-
799
- // src/shared/storage/db.ts
800
- init_cjs_shims();
801
- var storage = null;
802
- function createStorage(opts) {
803
- if (storage) return storage;
804
- const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
805
- if (backend === "json") {
806
- const { JsonStorage: JsonStorage2 } = (init_json_storage(), __toCommonJS(json_storage_exports));
807
- storage = new JsonStorage2(opts?.dataDir);
808
- console.log("[AgentGate] Storage: JSON files");
809
- } else {
810
- try {
811
- require.resolve("better-sqlite3");
812
- } catch {
813
- console.error(
814
- "[AgentGate] better-sqlite3 is not installed. Set AGENT_GATE_STORAGE=json or install better-sqlite3."
815
- );
816
- process.exit(1);
817
- }
818
- const { SqliteStorage: SqliteStorage2 } = (init_sqlite_storage(), __toCommonJS(sqlite_storage_exports));
819
- storage = new SqliteStorage2(opts?.dbPath);
820
- console.log("[AgentGate] Storage: SQLite");
821
- }
822
- return storage;
823
- }
824
-
825
- // src/shared/storage/repository.ts
1055
+ init_db();
826
1056
  function store() {
827
1057
  return createStorage();
828
1058
  }
@@ -844,6 +1074,12 @@ function queryToolCalls(params) {
844
1074
  function countToolCalls(params) {
845
1075
  return store().countToolCalls(params);
846
1076
  }
1077
+ function getStorageStats() {
1078
+ return store().getStorageStats();
1079
+ }
1080
+ function clearToolCalls() {
1081
+ return store().clearToolCalls();
1082
+ }
847
1083
  function getAgentsList() {
848
1084
  return store().getAgentsList();
849
1085
  }
@@ -852,6 +1088,8 @@ function getTimeline(limit) {
852
1088
  }
853
1089
 
854
1090
  // src/v1/routes.ts
1091
+ init_multi_session();
1092
+ var v1ReviewCounter = 0;
855
1093
  async function healthRoute(c) {
856
1094
  const mossHealth = await fetchMossHealth();
857
1095
  return c.json({
@@ -861,6 +1099,12 @@ async function healthRoute(c) {
861
1099
  moss_status: mossHealth.moss_status
862
1100
  });
863
1101
  }
1102
+ function storageOversizeInfo() {
1103
+ const stats = getStorageStats();
1104
+ const thresholdMB = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
1105
+ const totalMB = (stats.dbBytes + stats.jsonBytes) / 1024 / 1024;
1106
+ return { oversize: totalMB > thresholdMB, thresholdMB };
1107
+ }
864
1108
  async function analyzeRoute(c) {
865
1109
  const t0 = performance.now();
866
1110
  try {
@@ -874,10 +1118,17 @@ async function analyzeRoute(c) {
874
1118
  return c.json({
875
1119
  ...cached,
876
1120
  analysis_duration_ms: 0,
877
- collected_context: {}
1121
+ collected_context: {},
1122
+ ...storageOversizeInfo()
878
1123
  });
879
1124
  }
880
1125
  const context = await collectSystemContext();
1126
+ if (isMultiSessionEnabled()) {
1127
+ input.session_history = buildSessionHistory(
1128
+ (params) => queryToolCalls(params),
1129
+ input.session_id
1130
+ );
1131
+ }
881
1132
  const mossRequest = normalize(input, context);
882
1133
  const hostname = context.os?.hostname || "unknown";
883
1134
  const agentId = getOrCreateAgent(input.agent_type, hostname, input.agent_version);
@@ -901,6 +1152,17 @@ async function analyzeRoute(c) {
901
1152
  analysis_duration_ms: performance.now() - t0
902
1153
  });
903
1154
  setCache(key, mossResult);
1155
+ if (isMultiSessionEnabled()) {
1156
+ v1ReviewCounter++;
1157
+ if (v1ReviewCounter % 100 === 0) {
1158
+ try {
1159
+ const { getAgentGateDbPath: getAgentGateDbPath2 } = (init_db(), __toCommonJS(db_exports));
1160
+ const { callAgentMossReview: callAgentMossReview2 } = (init_moss_client(), __toCommonJS(moss_client_exports));
1161
+ void callAgentMossReview2({ agentId, dbPath: getAgentGateDbPath2() });
1162
+ } catch {
1163
+ }
1164
+ }
1165
+ }
904
1166
  const durationMs = performance.now() - t0;
905
1167
  return c.json(
906
1168
  AgentGateResponseSchema.parse({
@@ -911,6 +1173,7 @@ async function analyzeRoute(c) {
911
1173
  violated_layers: mossResult.violated_layers,
912
1174
  confidence: mossResult.confidence,
913
1175
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
1176
+ ...storageOversizeInfo(),
914
1177
  collected_context: {
915
1178
  os: context.os,
916
1179
  process: context.process,
@@ -945,11 +1208,21 @@ async function timelineRoute(c) {
945
1208
  const rows = getTimeline(limit);
946
1209
  return c.json(rows);
947
1210
  }
1211
+ function storageStatsRoute(c) {
1212
+ const storageStats = getStorageStats();
1213
+ const defaultThreshold = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
1214
+ const totalMB = (storageStats.dbBytes + storageStats.jsonBytes) / 1024 / 1024;
1215
+ return c.json({ stats: storageStats, oversize: totalMB > defaultThreshold, thresholdMB: defaultThreshold });
1216
+ }
1217
+ function deleteToolCallsRoute(c) {
1218
+ const deleted = clearToolCalls();
1219
+ return c.json({ deleted });
1220
+ }
948
1221
 
949
1222
  // src/v1/server.ts
950
1223
  function createApp() {
951
1224
  const app = new import_hono.Hono();
952
- app.use("*", (0, import_cors.cors)({ origin: "*", allowMethods: ["GET", "POST", "OPTIONS"], allowHeaders: ["*"] }));
1225
+ app.use("*", (0, import_cors.cors)({ origin: "*", allowMethods: ["GET", "POST", "OPTIONS", "DELETE"], allowHeaders: ["*"] }));
953
1226
  app.use("*", (0, import_logger.logger)());
954
1227
  app.get("/api/v1/health", healthRoute);
955
1228
  app.post("/api/v1/analyze", analyzeRoute);
@@ -957,6 +1230,8 @@ function createApp() {
957
1230
  app.get("/api/v1/tool_calls", toolCallsRoute);
958
1231
  app.get("/api/v1/agents", agentsRoute);
959
1232
  app.get("/api/v1/timeline", timelineRoute);
1233
+ app.get("/api/v1/storage_stats", storageStatsRoute);
1234
+ app.delete("/api/v1/tool_calls", deleteToolCallsRoute);
960
1235
  app.get("/dashboard/", dashboardRoute);
961
1236
  app.get("/dashboard", (c) => c.redirect("/dashboard/"));
962
1237
  return app;