@kenhkl/agent-gate 0.6.3 → 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/dashboard.html +54 -1
- package/dist/shared/storage/db.d.ts +20 -1
- package/dist/shared/storage/db.js +71 -1
- package/dist/shared/storage/db.js.map +1 -1
- package/dist/v1/cli.js +204 -6
- package/dist/v1/cli.js.map +1 -1
- package/dist/v1/server.js +350 -90
- package/dist/v1/server.js.map +1 -1
- package/dist/v3/cli.js +4274 -401
- package/dist/v3/cli.js.map +1 -1
- package/package.json +1 -1
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.
|
|
827
|
+
var _version = true ? "0.7.0" : (() => {
|
|
553
828
|
try {
|
|
554
829
|
const require2 = createRequire(importMetaUrl);
|
|
555
830
|
const pkg = require2("../package.json");
|
|
@@ -585,6 +860,13 @@ var AgentGateInputSchema = import_zod.z.object({
|
|
|
585
860
|
action_type: import_zod.z.string(),
|
|
586
861
|
action_detail: import_zod.z.string()
|
|
587
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"),
|
|
588
870
|
metadata: import_zod.z.record(import_zod.z.unknown()).optional()
|
|
589
871
|
});
|
|
590
872
|
var AgentGateResponseSchema = import_zod.z.object({
|
|
@@ -595,6 +877,8 @@ var AgentGateResponseSchema = import_zod.z.object({
|
|
|
595
877
|
violated_layers: import_zod.z.array(import_zod.z.string()).default([]),
|
|
596
878
|
confidence: import_zod.z.number().int().min(0).max(100).default(100),
|
|
597
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"),
|
|
598
882
|
collected_context: import_zod.z.object({
|
|
599
883
|
os: import_zod.z.object({
|
|
600
884
|
system: import_zod.z.string(),
|
|
@@ -620,11 +904,19 @@ var HealthResponseSchema = import_zod.z.object({
|
|
|
620
904
|
|
|
621
905
|
// src/shared/normalizer.ts
|
|
622
906
|
init_cjs_shims();
|
|
907
|
+
init_multi_session();
|
|
623
908
|
function normalize(input, systemContext) {
|
|
624
909
|
const actionHistory = input.action_history.map((h) => ({
|
|
625
910
|
action_type: h.action_type,
|
|
626
911
|
action_detail: h.action_detail
|
|
627
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
|
+
}));
|
|
628
920
|
const promptHistory = input.prompt_history.map((t) => ({
|
|
629
921
|
text: t.text,
|
|
630
922
|
actions: t.actions.map((a) => ({
|
|
@@ -639,6 +931,7 @@ function normalize(input, systemContext) {
|
|
|
639
931
|
prompt_session: input.user_prompt || input.description || "",
|
|
640
932
|
prompt_history: promptHistory,
|
|
641
933
|
action_history: actionHistory,
|
|
934
|
+
session_history: sessionHistory,
|
|
642
935
|
a_next: {
|
|
643
936
|
action_type: toolName,
|
|
644
937
|
action_detail: command
|
|
@@ -656,7 +949,12 @@ function normalize(input, systemContext) {
|
|
|
656
949
|
...input.metadata,
|
|
657
950
|
agent_type: input.agent_type,
|
|
658
951
|
agent_version: input.agent_version,
|
|
659
|
-
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 } : {}
|
|
660
958
|
}
|
|
661
959
|
};
|
|
662
960
|
}
|
|
@@ -724,64 +1022,8 @@ async function collectSystemContext() {
|
|
|
724
1022
|
return { os: os3, process: proc, user };
|
|
725
1023
|
}
|
|
726
1024
|
|
|
727
|
-
// src/
|
|
728
|
-
|
|
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
|
-
}
|
|
1025
|
+
// src/v1/routes.ts
|
|
1026
|
+
init_moss_client();
|
|
785
1027
|
|
|
786
1028
|
// src/shared/cache.ts
|
|
787
1029
|
init_cjs_shims();
|
|
@@ -810,34 +1052,7 @@ function setCache(key, result) {
|
|
|
810
1052
|
|
|
811
1053
|
// src/shared/storage/repository.ts
|
|
812
1054
|
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
|
|
1055
|
+
init_db();
|
|
841
1056
|
function store() {
|
|
842
1057
|
return createStorage();
|
|
843
1058
|
}
|
|
@@ -859,6 +1074,12 @@ function queryToolCalls(params) {
|
|
|
859
1074
|
function countToolCalls(params) {
|
|
860
1075
|
return store().countToolCalls(params);
|
|
861
1076
|
}
|
|
1077
|
+
function getStorageStats() {
|
|
1078
|
+
return store().getStorageStats();
|
|
1079
|
+
}
|
|
1080
|
+
function clearToolCalls() {
|
|
1081
|
+
return store().clearToolCalls();
|
|
1082
|
+
}
|
|
862
1083
|
function getAgentsList() {
|
|
863
1084
|
return store().getAgentsList();
|
|
864
1085
|
}
|
|
@@ -867,6 +1088,8 @@ function getTimeline(limit) {
|
|
|
867
1088
|
}
|
|
868
1089
|
|
|
869
1090
|
// src/v1/routes.ts
|
|
1091
|
+
init_multi_session();
|
|
1092
|
+
var v1ReviewCounter = 0;
|
|
870
1093
|
async function healthRoute(c) {
|
|
871
1094
|
const mossHealth = await fetchMossHealth();
|
|
872
1095
|
return c.json({
|
|
@@ -876,6 +1099,12 @@ async function healthRoute(c) {
|
|
|
876
1099
|
moss_status: mossHealth.moss_status
|
|
877
1100
|
});
|
|
878
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
|
+
}
|
|
879
1108
|
async function analyzeRoute(c) {
|
|
880
1109
|
const t0 = performance.now();
|
|
881
1110
|
try {
|
|
@@ -889,10 +1118,17 @@ async function analyzeRoute(c) {
|
|
|
889
1118
|
return c.json({
|
|
890
1119
|
...cached,
|
|
891
1120
|
analysis_duration_ms: 0,
|
|
892
|
-
collected_context: {}
|
|
1121
|
+
collected_context: {},
|
|
1122
|
+
...storageOversizeInfo()
|
|
893
1123
|
});
|
|
894
1124
|
}
|
|
895
1125
|
const context = await collectSystemContext();
|
|
1126
|
+
if (isMultiSessionEnabled()) {
|
|
1127
|
+
input.session_history = buildSessionHistory(
|
|
1128
|
+
(params) => queryToolCalls(params),
|
|
1129
|
+
input.session_id
|
|
1130
|
+
);
|
|
1131
|
+
}
|
|
896
1132
|
const mossRequest = normalize(input, context);
|
|
897
1133
|
const hostname = context.os?.hostname || "unknown";
|
|
898
1134
|
const agentId = getOrCreateAgent(input.agent_type, hostname, input.agent_version);
|
|
@@ -916,6 +1152,17 @@ async function analyzeRoute(c) {
|
|
|
916
1152
|
analysis_duration_ms: performance.now() - t0
|
|
917
1153
|
});
|
|
918
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
|
+
}
|
|
919
1166
|
const durationMs = performance.now() - t0;
|
|
920
1167
|
return c.json(
|
|
921
1168
|
AgentGateResponseSchema.parse({
|
|
@@ -926,6 +1173,7 @@ async function analyzeRoute(c) {
|
|
|
926
1173
|
violated_layers: mossResult.violated_layers,
|
|
927
1174
|
confidence: mossResult.confidence,
|
|
928
1175
|
analysis_duration_ms: Math.round(durationMs * 10) / 10,
|
|
1176
|
+
...storageOversizeInfo(),
|
|
929
1177
|
collected_context: {
|
|
930
1178
|
os: context.os,
|
|
931
1179
|
process: context.process,
|
|
@@ -960,11 +1208,21 @@ async function timelineRoute(c) {
|
|
|
960
1208
|
const rows = getTimeline(limit);
|
|
961
1209
|
return c.json(rows);
|
|
962
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
|
+
}
|
|
963
1221
|
|
|
964
1222
|
// src/v1/server.ts
|
|
965
1223
|
function createApp() {
|
|
966
1224
|
const app = new import_hono.Hono();
|
|
967
|
-
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: ["*"] }));
|
|
968
1226
|
app.use("*", (0, import_logger.logger)());
|
|
969
1227
|
app.get("/api/v1/health", healthRoute);
|
|
970
1228
|
app.post("/api/v1/analyze", analyzeRoute);
|
|
@@ -972,6 +1230,8 @@ function createApp() {
|
|
|
972
1230
|
app.get("/api/v1/tool_calls", toolCallsRoute);
|
|
973
1231
|
app.get("/api/v1/agents", agentsRoute);
|
|
974
1232
|
app.get("/api/v1/timeline", timelineRoute);
|
|
1233
|
+
app.get("/api/v1/storage_stats", storageStatsRoute);
|
|
1234
|
+
app.delete("/api/v1/tool_calls", deleteToolCallsRoute);
|
|
975
1235
|
app.get("/dashboard/", dashboardRoute);
|
|
976
1236
|
app.get("/dashboard", (c) => c.redirect("/dashboard/"));
|
|
977
1237
|
return app;
|