@kenhkl/agent-gate 0.9.1 → 0.9.3

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,46 @@ var init_cjs_shims = __esm({
40
40
  }
41
41
  });
42
42
 
43
+ // src/shared/instance-id.ts
44
+ function getInstanceId() {
45
+ if (cached) return cached;
46
+ const env2 = (process.env.AGENT_GATE_INSTANCE_ID || "").trim();
47
+ if (env2) {
48
+ cached = env2;
49
+ return cached;
50
+ }
51
+ const filePath = process.env.AGENT_GATE_INSTANCE_ID_PATH || (0, import_path.join)((0, import_os.homedir)(), ".config", "agentgate", "instance_id");
52
+ try {
53
+ if ((0, import_fs.existsSync)(filePath)) {
54
+ const v2 = (0, import_fs.readFileSync)(filePath, "utf-8").trim();
55
+ if (v2) {
56
+ cached = v2;
57
+ return cached;
58
+ }
59
+ }
60
+ const v = (0, import_crypto.randomUUID)();
61
+ (0, import_fs.mkdirSync)((0, import_path.dirname)(filePath), { recursive: true });
62
+ (0, import_fs.writeFileSync)(filePath, v + "\n", { mode: 384 });
63
+ cached = v;
64
+ return cached;
65
+ } catch {
66
+ cached = `ephemeral-${(0, import_crypto.randomUUID)()}`;
67
+ return cached;
68
+ }
69
+ }
70
+ var import_fs, import_os, import_path, import_crypto, cached;
71
+ var init_instance_id = __esm({
72
+ "src/shared/instance-id.ts"() {
73
+ "use strict";
74
+ init_cjs_shims();
75
+ import_fs = require("fs");
76
+ import_os = require("os");
77
+ import_path = require("path");
78
+ import_crypto = require("crypto");
79
+ cached = "";
80
+ }
81
+ });
82
+
43
83
  // src/shared/multi-session.ts
44
84
  function isMultiSessionEnabled() {
45
85
  const raw = (process.env.AGENT_GATE_MULTI_SESSION ?? "").trim().toLowerCase();
@@ -86,6 +126,9 @@ function buildSessionHistory(queryToolCalls2, sessionId, listAgentTypes) {
86
126
  return [...bySession.entries()].slice(0, maxSessions).map(([sid, actions]) => ({
87
127
  session_id: sid,
88
128
  ...sessionAgent.get(sid) ? { agent_id: sessionAgent.get(sid) } : {},
129
+ // AgentGate 自己的存储属于本安装实例;带上实例 ID 让 AgentMoss 在
130
+ // 展示层按「同实例不隐藏」处理(否则用户自己的历史会话也会被脱敏)。
131
+ instance_id: getInstanceId(),
89
132
  action_history: actions.slice(0, DEFAULT_ACTIONS_PER_SESSION)
90
133
  }));
91
134
  } catch {
@@ -100,6 +143,7 @@ var init_multi_session = __esm({
100
143
  "src/shared/multi-session.ts"() {
101
144
  "use strict";
102
145
  init_cjs_shims();
146
+ init_instance_id();
103
147
  DEFAULT_HISTORY_LIMIT = 500;
104
148
  DEFAULT_MAX_SESSIONS = 5;
105
149
  DEFAULT_ACTIONS_PER_SESSION = 100;
@@ -186,8 +230,8 @@ function readFdToken() {
186
230
  if (!raw) return "";
187
231
  const fd = parseInt(raw, 10);
188
232
  if (!Number.isFinite(fd)) return "";
189
- const cached = fdTokenCache.get(fd);
190
- if (cached !== void 0) return cached;
233
+ const cached2 = fdTokenCache.get(fd);
234
+ if (cached2 !== void 0) return cached2;
191
235
  try {
192
236
  const buf = Buffer.alloc(8192);
193
237
  const n = (0, import_node_fs.readSync)(fd, buf, 0, buf.length, null);
@@ -648,12 +692,12 @@ function clipText(value, limit = maxRecordBytes()) {
648
692
  const s = String(value ?? "");
649
693
  if (limit <= 0 || s.length <= limit) return s;
650
694
  const head = s.slice(0, limit);
651
- const digest = (0, import_crypto.createHash)("sha256").update(s).digest("hex").slice(0, 16);
695
+ const digest = (0, import_crypto2.createHash)("sha256").update(s).digest("hex").slice(0, 16);
652
696
  return `${head}\u2026[truncated ${s.length - limit}B sha256:${digest}]`;
653
697
  }
654
698
  function diskFreePercent(targetPath) {
655
699
  try {
656
- const st = (0, import_fs.statfsSync)((0, import_path.dirname)(targetPath));
700
+ const st = (0, import_fs2.statfsSync)((0, import_path2.dirname)(targetPath));
657
701
  const total = Number(st.blocks) || 0;
658
702
  const avail = Number(st.bavail) || 0;
659
703
  if (!total) return 100;
@@ -690,14 +734,14 @@ function prepareRecordForStorage(rec, targetPath) {
690
734
  if (degraded) out = degradeRecord(out);
691
735
  return { record: out, degraded };
692
736
  }
693
- var import_crypto, import_fs, import_path, DEGRADE_COMMAND_BYTES;
737
+ var import_crypto2, import_fs2, import_path2, DEGRADE_COMMAND_BYTES;
694
738
  var init_record_guard = __esm({
695
739
  "src/shared/storage/record-guard.ts"() {
696
740
  "use strict";
697
741
  init_cjs_shims();
698
- import_crypto = require("crypto");
699
- import_fs = require("fs");
700
- import_path = require("path");
742
+ import_crypto2 = require("crypto");
743
+ import_fs2 = require("fs");
744
+ import_path2 = require("path");
701
745
  init_security();
702
746
  DEGRADE_COMMAND_BYTES = 512;
703
747
  }
@@ -713,16 +757,16 @@ function nowISO() {
713
757
  }
714
758
  function getDefaultDataDir() {
715
759
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
716
- const xdgData = process.env.XDG_DATA_HOME || (0, import_path2.join)(home, ".local", "share");
717
- return (0, import_path2.join)(xdgData, "agent_gate", "storage");
760
+ const xdgData = process.env.XDG_DATA_HOME || (0, import_path3.join)(home, ".local", "share");
761
+ return (0, import_path3.join)(xdgData, "agent_gate", "storage");
718
762
  }
719
- var import_fs2, import_path2, JsonStorage;
763
+ var import_fs3, import_path3, JsonStorage;
720
764
  var init_json_storage = __esm({
721
765
  "src/shared/storage/json-storage.ts"() {
722
766
  "use strict";
723
767
  init_cjs_shims();
724
- import_fs2 = require("fs");
725
- import_path2 = require("path");
768
+ import_fs3 = require("fs");
769
+ import_path3 = require("path");
726
770
  init_security();
727
771
  init_record_guard();
728
772
  JsonStorage = class {
@@ -737,11 +781,11 @@ var init_json_storage = __esm({
737
781
  sessionLocks = /* @__PURE__ */ new Map();
738
782
  constructor(dataDir) {
739
783
  this.dataDir = dataDir || process.env.AGENT_GATE_DATA_DIR || getDefaultDataDir();
740
- this.agentsPath = (0, import_path2.join)(this.dataDir, "agents.json");
741
- this.sessionsPath = (0, import_path2.join)(this.dataDir, "sessions.json");
742
- this.toolCallsDir = (0, import_path2.join)(this.dataDir, "tool_calls");
743
- if (!(0, import_fs2.existsSync)(this.dataDir)) (0, import_fs2.mkdirSync)(this.dataDir, { recursive: true, mode: 448 });
744
- if (!(0, import_fs2.existsSync)(this.toolCallsDir)) (0, import_fs2.mkdirSync)(this.toolCallsDir, { recursive: true, mode: 448 });
784
+ this.agentsPath = (0, import_path3.join)(this.dataDir, "agents.json");
785
+ this.sessionsPath = (0, import_path3.join)(this.dataDir, "sessions.json");
786
+ this.toolCallsDir = (0, import_path3.join)(this.dataDir, "tool_calls");
787
+ if (!(0, import_fs3.existsSync)(this.dataDir)) (0, import_fs3.mkdirSync)(this.dataDir, { recursive: true, mode: 448 });
788
+ if (!(0, import_fs3.existsSync)(this.toolCallsDir)) (0, import_fs3.mkdirSync)(this.toolCallsDir, { recursive: true, mode: 448 });
745
789
  this.hardenStoragePermissions();
746
790
  this.nextId = this.recoverNextId();
747
791
  }
@@ -753,10 +797,10 @@ var init_json_storage = __esm({
753
797
  const uid = process.getuid?.();
754
798
  const tighten = (p, mode) => {
755
799
  try {
756
- const st = (0, import_fs2.statSync)(p);
800
+ const st = (0, import_fs3.statSync)(p);
757
801
  if (st.isSymbolicLink()) return;
758
802
  if (uid !== void 0 && st.uid !== uid) return;
759
- if ((st.mode & 511) !== mode) (0, import_fs2.chmodSync)(p, mode);
803
+ if ((st.mode & 511) !== mode) (0, import_fs3.chmodSync)(p, mode);
760
804
  } catch {
761
805
  }
762
806
  };
@@ -765,9 +809,9 @@ var init_json_storage = __esm({
765
809
  tighten(this.agentsPath, 384);
766
810
  tighten(this.sessionsPath, 384);
767
811
  try {
768
- for (const f of (0, import_fs2.readdirSync)(this.toolCallsDir)) {
812
+ for (const f of (0, import_fs3.readdirSync)(this.toolCallsDir)) {
769
813
  if (f.endsWith(".json") || f.endsWith(".tmp")) {
770
- tighten((0, import_path2.join)(this.toolCallsDir, f), 384);
814
+ tighten((0, import_path3.join)(this.toolCallsDir, f), 384);
771
815
  }
772
816
  }
773
817
  } catch {
@@ -777,9 +821,9 @@ var init_json_storage = __esm({
777
821
  recoverNextId() {
778
822
  let maxId = 0;
779
823
  try {
780
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
824
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
781
825
  for (const file of files) {
782
- const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
826
+ const records = this.readJsonFile((0, import_path3.join)(this.toolCallsDir, file), []);
783
827
  for (const r of records) {
784
828
  if (r.id > maxId) maxId = r.id;
785
829
  }
@@ -790,19 +834,19 @@ var init_json_storage = __esm({
790
834
  }
791
835
  readJsonFile(path, fallback) {
792
836
  try {
793
- if (!(0, import_fs2.existsSync)(path)) return fallback;
794
- return JSON.parse((0, import_fs2.readFileSync)(path, "utf-8"));
837
+ if (!(0, import_fs3.existsSync)(path)) return fallback;
838
+ return JSON.parse((0, import_fs3.readFileSync)(path, "utf-8"));
795
839
  } catch {
796
840
  return fallback;
797
841
  }
798
842
  }
799
843
  /** 原子写入:先写 .tmp 再 rename(rename 保留 tmp 的 0600 权限) */
800
844
  writeJsonFile(path, data) {
801
- const dir = (0, import_path2.dirname)(path);
802
- if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true, mode: 448 });
845
+ const dir = (0, import_path3.dirname)(path);
846
+ if (!(0, import_fs3.existsSync)(dir)) (0, import_fs3.mkdirSync)(dir, { recursive: true, mode: 448 });
803
847
  const tmp = path + ".tmp";
804
- (0, import_fs2.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
805
- (0, import_fs2.renameSync)(tmp, path);
848
+ (0, import_fs3.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
849
+ (0, import_fs3.renameSync)(tmp, path);
806
850
  }
807
851
  loadAgents() {
808
852
  const raw = this.readJsonFile(this.agentsPath, {});
@@ -820,12 +864,12 @@ var init_json_storage = __esm({
820
864
  }
821
865
  loadToolCalls(sessionId) {
822
866
  return this.readJsonFile(
823
- (0, import_path2.join)(this.toolCallsDir, `${sessionId}.json`),
867
+ (0, import_path3.join)(this.toolCallsDir, `${sessionId}.json`),
824
868
  []
825
869
  );
826
870
  }
827
871
  saveToolCalls(sessionId, records) {
828
- this.writeJsonFile((0, import_path2.join)(this.toolCallsDir, `${sessionId}.json`), records);
872
+ this.writeJsonFile((0, import_path3.join)(this.toolCallsDir, `${sessionId}.json`), records);
829
873
  }
830
874
  getOrCreateAgent(agentType, hostname, version2 = "") {
831
875
  const agents = this.loadAgents();
@@ -911,9 +955,9 @@ var init_json_storage = __esm({
911
955
  allRecords = records.map((r) => this.enrichRecord(r, sessions, agents));
912
956
  } else {
913
957
  try {
914
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
958
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
915
959
  for (const file of files) {
916
- const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
960
+ const records = this.readJsonFile((0, import_path3.join)(this.toolCallsDir, file), []);
917
961
  allRecords.push(...records.map((r) => this.enrichRecord(r, sessions, agents)));
918
962
  }
919
963
  } catch {
@@ -947,9 +991,9 @@ var init_json_storage = __esm({
947
991
  const agents = this.loadAgents();
948
992
  let allRecords = [];
949
993
  try {
950
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
994
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
951
995
  for (const file of files) {
952
- const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
996
+ const records = this.readJsonFile((0, import_path3.join)(this.toolCallsDir, file), []);
953
997
  allRecords.push(...records);
954
998
  }
955
999
  } catch {
@@ -988,12 +1032,12 @@ var init_json_storage = __esm({
988
1032
  let jsonFiles = 0;
989
1033
  let jsonBytes = 0;
990
1034
  try {
991
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
1035
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
992
1036
  for (const file of files) {
993
- const stat = (0, import_fs2.statSync)((0, import_path2.join)(this.toolCallsDir, file));
1037
+ const stat = (0, import_fs3.statSync)((0, import_path3.join)(this.toolCallsDir, file));
994
1038
  jsonFiles++;
995
1039
  jsonBytes += stat.size;
996
- const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
1040
+ const records = this.readJsonFile((0, import_path3.join)(this.toolCallsDir, file), []);
997
1041
  toolCalls += records.length;
998
1042
  }
999
1043
  } catch {
@@ -1003,9 +1047,9 @@ var init_json_storage = __esm({
1003
1047
  clearToolCalls() {
1004
1048
  let removed = 0;
1005
1049
  try {
1006
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
1050
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
1007
1051
  for (const file of files) {
1008
- (0, import_fs2.unlinkSync)((0, import_path2.join)(this.toolCallsDir, file));
1052
+ (0, import_fs3.unlinkSync)((0, import_path3.join)(this.toolCallsDir, file));
1009
1053
  removed++;
1010
1054
  }
1011
1055
  } catch {
@@ -1029,10 +1073,10 @@ var init_json_storage = __esm({
1029
1073
  * 再从各自的 session 文件里移除。数据不丢,只是不在主目录了。
1030
1074
  */
1031
1075
  archiveOldRecords(keep) {
1032
- if (keep <= 0 || !(0, import_fs2.existsSync)(this.toolCallsDir)) return { archived: 0, file: "" };
1076
+ if (keep <= 0 || !(0, import_fs3.existsSync)(this.toolCallsDir)) return { archived: 0, file: "" };
1033
1077
  const bySession = /* @__PURE__ */ new Map();
1034
1078
  let total = 0;
1035
- for (const f of (0, import_fs2.readdirSync)(this.toolCallsDir)) {
1079
+ for (const f of (0, import_fs3.readdirSync)(this.toolCallsDir)) {
1036
1080
  if (!f.endsWith(".json")) continue;
1037
1081
  const sid = f.slice(0, -".json".length);
1038
1082
  const recs = this.loadToolCalls(sid);
@@ -1048,15 +1092,15 @@ var init_json_storage = __esm({
1048
1092
  const archiveCount = total - keep;
1049
1093
  const toArchive = flat.slice(0, archiveCount);
1050
1094
  const archiveIds = new Set(toArchive.map((x) => String(x.rec.id)));
1051
- const { mkdirSync: mkdirSync4, writeFileSync: writeFileSync3 } = require("fs");
1052
- const { join: join4 } = require("path");
1095
+ const { mkdirSync: mkdirSync5, writeFileSync: writeFileSync4 } = require("fs");
1096
+ const { join: join5 } = require("path");
1053
1097
  const { gzipSync } = require("zlib");
1054
- const archiveDir = join4(this.dataDir, "archive");
1055
- if (!(0, import_fs2.existsSync)(archiveDir)) mkdirSync4(archiveDir, { recursive: true, mode: 448 });
1098
+ const archiveDir = join5(this.dataDir, "archive");
1099
+ if (!(0, import_fs3.existsSync)(archiveDir)) mkdirSync5(archiveDir, { recursive: true, mode: 448 });
1056
1100
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
1057
- const file = join4(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
1101
+ const file = join5(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
1058
1102
  const payload = toArchive.map((x) => JSON.stringify(x.rec)).join("\n") + "\n";
1059
- writeFileSync3(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
1103
+ writeFileSync4(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
1060
1104
  for (const [sid, recs] of bySession) {
1061
1105
  const remain = recs.filter((r) => !archiveIds.has(String(r.id)));
1062
1106
  if (remain.length !== recs.length) this.saveToolCalls(sid, remain);
@@ -1100,9 +1144,9 @@ var init_json_storage = __esm({
1100
1144
  getTimeline(limit = 100) {
1101
1145
  const buckets = /* @__PURE__ */ new Map();
1102
1146
  try {
1103
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
1147
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
1104
1148
  for (const file of files) {
1105
- const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
1149
+ const records = this.readJsonFile((0, import_path3.join)(this.toolCallsDir, file), []);
1106
1150
  for (const r of records) {
1107
1151
  const minute = r.called_at.replace(/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}):\d{2}/, "$1T$2");
1108
1152
  const bucket = buckets.get(minute) || { allow: 0, deny: 0 };
@@ -1133,16 +1177,16 @@ __export(sqlite_storage_exports, {
1133
1177
  });
1134
1178
  function getDefaultDbPath() {
1135
1179
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
1136
- const xdgData = process.env.XDG_DATA_HOME || (0, import_path3.join)(home, ".local", "share");
1137
- return (0, import_path3.join)(xdgData, "agent_gate", "agent_gate_ts.db");
1180
+ const xdgData = process.env.XDG_DATA_HOME || (0, import_path4.join)(home, ".local", "share");
1181
+ return (0, import_path4.join)(xdgData, "agent_gate", "agent_gate_ts.db");
1138
1182
  }
1139
- var import_fs3, import_path3, SCHEMA, SqliteStorage;
1183
+ var import_fs4, import_path4, SCHEMA, SqliteStorage;
1140
1184
  var init_sqlite_storage = __esm({
1141
1185
  "src/shared/storage/sqlite-storage.ts"() {
1142
1186
  "use strict";
1143
1187
  init_cjs_shims();
1144
- import_fs3 = require("fs");
1145
- import_path3 = require("path");
1188
+ import_fs4 = require("fs");
1189
+ import_path4 = require("path");
1146
1190
  init_record_guard();
1147
1191
  SCHEMA = `
1148
1192
  CREATE TABLE IF NOT EXISTS agents (
@@ -1183,6 +1227,7 @@ CREATE TABLE IF NOT EXISTS tool_calls (
1183
1227
  reason TEXT DEFAULT '',
1184
1228
  confidence INTEGER DEFAULT 0,
1185
1229
  analysis_duration_ms REAL DEFAULT 0,
1230
+ violation_graph TEXT DEFAULT '{}',
1186
1231
  called_at TEXT DEFAULT (datetime('now')),
1187
1232
  UNIQUE(session_id, seq)
1188
1233
  );
@@ -1203,12 +1248,23 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1203
1248
  );
1204
1249
  }
1205
1250
  const path = dbPath || getDefaultDbPath();
1206
- const dir = (0, import_path3.dirname)(path);
1207
- if (!(0, import_fs3.existsSync)(dir)) (0, import_fs3.mkdirSync)(dir, { recursive: true });
1251
+ const dir = (0, import_path4.dirname)(path);
1252
+ if (!(0, import_fs4.existsSync)(dir)) (0, import_fs4.mkdirSync)(dir, { recursive: true });
1208
1253
  this.dbPath = path;
1209
1254
  this.db = new Database(path);
1210
1255
  this.db.pragma("journal_mode = WAL");
1211
1256
  this.db.exec(SCHEMA);
1257
+ this.ensureColumn("tool_calls", "violation_graph", "violation_graph TEXT DEFAULT '{}'");
1258
+ }
1259
+ /** 幂等补列(旧数据库平滑升级,失败不阻断启动)。 */
1260
+ ensureColumn(table, column, ddl) {
1261
+ try {
1262
+ const cols = this.db.prepare(`PRAGMA table_info(${table})`).all();
1263
+ if (!cols.some((c) => c.name === column)) {
1264
+ this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${ddl}`);
1265
+ }
1266
+ } catch {
1267
+ }
1212
1268
  }
1213
1269
  static isAvailable() {
1214
1270
  try {
@@ -1250,8 +1306,8 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1250
1306
  return this.db.prepare(`
1251
1307
  INSERT INTO tool_calls (session_id, seq, tool_name, command, description, cwd,
1252
1308
  action_type, action_detail, decision, risk_level, risk_type, violated_layers,
1253
- reason, confidence, analysis_duration_ms)
1254
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1309
+ reason, confidence, analysis_duration_ms, violation_graph)
1310
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1255
1311
  `).run(
1256
1312
  rec.session_id,
1257
1313
  seq,
@@ -1267,7 +1323,8 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1267
1323
  rec.violated_layers,
1268
1324
  rec.reason,
1269
1325
  rec.confidence,
1270
- rec.analysis_duration_ms
1326
+ rec.analysis_duration_ms,
1327
+ rec.violation_graph || "{}"
1271
1328
  );
1272
1329
  })(record);
1273
1330
  return Number(result.lastInsertRowid);
@@ -1364,11 +1421,11 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1364
1421
  const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
1365
1422
  let dbBytes = 0;
1366
1423
  try {
1367
- const { statSync: statSync3, existsSync: existsSync3 } = require("fs");
1424
+ const { statSync: statSync3, existsSync: existsSync4 } = require("fs");
1368
1425
  dbBytes = statSync3(this.dbPath).size;
1369
1426
  for (const suffix of ["-wal", "-shm"]) {
1370
1427
  const p = this.dbPath + suffix;
1371
- if (existsSync3(p)) dbBytes += statSync3(p).size;
1428
+ if (existsSync4(p)) dbBytes += statSync3(p).size;
1372
1429
  }
1373
1430
  } catch {
1374
1431
  }
@@ -1401,15 +1458,15 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1401
1458
  "SELECT * FROM tool_calls WHERE id <= ? ORDER BY id"
1402
1459
  ).all(cutoff.id);
1403
1460
  if (rows.length === 0) return { archived: 0, file: "" };
1404
- const { writeFileSync: writeFileSync3, mkdirSync: mkdirSync4, existsSync: existsSync3 } = require("fs");
1405
- const { dirname: dirname4, join: join4 } = require("path");
1461
+ const { writeFileSync: writeFileSync4, mkdirSync: mkdirSync5, existsSync: existsSync4 } = require("fs");
1462
+ const { dirname: dirname5, join: join5 } = require("path");
1406
1463
  const { gzipSync } = require("zlib");
1407
- const archiveDir = join4(dirname4(this.dbPath), "archive");
1408
- if (!existsSync3(archiveDir)) mkdirSync4(archiveDir, { recursive: true, mode: 448 });
1464
+ const archiveDir = join5(dirname5(this.dbPath), "archive");
1465
+ if (!existsSync4(archiveDir)) mkdirSync5(archiveDir, { recursive: true, mode: 448 });
1409
1466
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
1410
- const file = join4(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
1467
+ const file = join5(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
1411
1468
  const payload = rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
1412
- writeFileSync3(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
1469
+ writeFileSync4(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
1413
1470
  const deleted = this.db.transaction(() => {
1414
1471
  const res = this.db.prepare("DELETE FROM tool_calls WHERE id <= ?").run(cutoff.id);
1415
1472
  this.db.prepare(`
@@ -1515,14 +1572,14 @@ function getDb(dbPath) {
1515
1572
  if (rawDb) return rawDb;
1516
1573
  try {
1517
1574
  const Database = require("better-sqlite3");
1518
- const { existsSync: existsSync3, mkdirSync: mkdirSync4 } = require("fs");
1519
- const { join: join4, dirname: dirname4 } = require("path");
1575
+ const { existsSync: existsSync4, mkdirSync: mkdirSync5 } = require("fs");
1576
+ const { join: join5, dirname: dirname5 } = require("path");
1520
1577
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
1521
- const xdgData = process.env.XDG_DATA_HOME || join4(home, ".local", "share");
1522
- const defaultPath = join4(xdgData, "agent_gate", "agent_gate_ts.db");
1578
+ const xdgData = process.env.XDG_DATA_HOME || join5(home, ".local", "share");
1579
+ const defaultPath = join5(xdgData, "agent_gate", "agent_gate_ts.db");
1523
1580
  const path = dbPath || defaultPath;
1524
- const dir = dirname4(path);
1525
- if (!existsSync3(dir)) mkdirSync4(dir, { recursive: true });
1581
+ const dir = dirname5(path);
1582
+ if (!existsSync4(dir)) mkdirSync5(dir, { recursive: true });
1526
1583
  rawDb = new Database(path);
1527
1584
  rawDb.pragma("journal_mode = WAL");
1528
1585
  return rawDb;
@@ -1586,7 +1643,7 @@ var import_zod = require("zod");
1586
1643
 
1587
1644
  // src/version.ts
1588
1645
  init_cjs_shims();
1589
- var _version = true ? "0.9.1" : (() => {
1646
+ var _version = true ? "0.9.3" : (() => {
1590
1647
  try {
1591
1648
  const require2 = createRequire(importMetaUrl);
1592
1649
  const pkg = require2("../package.json");
@@ -1602,6 +1659,8 @@ var AgentGateInputSchema = import_zod.z.object({
1602
1659
  agent_type: import_zod.z.string().describe("Agent identifier, e.g. opendesk, claude-code"),
1603
1660
  agent_version: import_zod.z.string().default("0.1.0"),
1604
1661
  session_id: import_zod.z.string().describe("Session unique identifier"),
1662
+ /** 安装级实例 ID(仅展示层脱敏用;缺省由 AgentGate 自动生成)。 */
1663
+ instance_id: import_zod.z.string().optional(),
1605
1664
  tool_name: import_zod.z.string().optional().describe("Tool name, e.g. bash, file_write"),
1606
1665
  command: import_zod.z.string().optional().describe("Tool command or description"),
1607
1666
  a_next: import_zod.z.object({
@@ -1644,6 +1703,8 @@ var AgentGateResponseSchema = import_zod.z.object({
1644
1703
  violated_layers: import_zod.z.array(import_zod.z.string()).default([]),
1645
1704
  confidence: import_zod.z.number().int().min(0).max(100).default(100),
1646
1705
  analysis_duration_ms: import_zod.z.number().default(0),
1706
+ // 结构化攻击链图(组合式拦截时非空;前端弹窗画图用)
1707
+ violation_graph: import_zod.z.any().nullable().optional(),
1647
1708
  oversize: import_zod.z.boolean().optional().describe("\u672C\u5730\u5B58\u50A8\u662F\u5426\u8D85\u8FC7\u6E05\u7406\u9608\u503C\uFF08agg \u7528\uFF09"),
1648
1709
  thresholdMB: import_zod.z.number().optional().describe("\u5B58\u50A8\u6E05\u7406\u9608\u503C MB\uFF08agg \u7528\uFF09"),
1649
1710
  collected_context: import_zod.z.object({
@@ -1673,6 +1734,7 @@ var HealthResponseSchema = import_zod.z.object({
1673
1734
  // src/shared/normalizer.ts
1674
1735
  init_cjs_shims();
1675
1736
  init_multi_session();
1737
+ init_instance_id();
1676
1738
  function normalize(input, systemContext) {
1677
1739
  const actionHistory = input.action_history.map((h) => ({
1678
1740
  action_type: h.action_type,
@@ -1716,6 +1778,8 @@ function normalize(input, systemContext) {
1716
1778
  // 历史上只在 metadata.agent_type 里带,AgentMoss 读顶层 req.agent_id → 空 →
1717
1779
  // 定制规则从未生效(OpenDesk memory-* 操作走 L3 耗时 1~137s)。
1718
1780
  agent_id: input.agent_type || "",
1781
+ // 实例 ID:仅用于 AgentMoss 展示层脱敏(同实例不隐藏),不参与判定。
1782
+ instance_id: input.instance_id || getInstanceId(),
1719
1783
  metadata: {
1720
1784
  ...input.metadata,
1721
1785
  agent_type: input.agent_type,
@@ -1735,16 +1799,16 @@ init_cjs_shims();
1735
1799
 
1736
1800
  // src/shared/collector/system-info.ts
1737
1801
  init_cjs_shims();
1738
- var import_os = __toESM(require("os"));
1802
+ var import_os2 = __toESM(require("os"));
1739
1803
  async function collectSystemInfo() {
1740
1804
  try {
1741
1805
  return {
1742
1806
  system: process.platform,
1743
- distribution: `${import_os.default.type()} ${import_os.default.release()}`,
1744
- hostname: import_os.default.hostname(),
1745
- arch: import_os.default.arch(),
1746
- cpu_count: import_os.default.cpus().length,
1747
- memory_total_mb: Math.round(import_os.default.totalmem() / (1024 * 1024))
1807
+ distribution: `${import_os2.default.type()} ${import_os2.default.release()}`,
1808
+ hostname: import_os2.default.hostname(),
1809
+ arch: import_os2.default.arch(),
1810
+ cpu_count: import_os2.default.cpus().length,
1811
+ memory_total_mb: Math.round(import_os2.default.totalmem() / (1024 * 1024))
1748
1812
  };
1749
1813
  } catch {
1750
1814
  return { system: "unknown" };
@@ -1768,10 +1832,10 @@ async function collectProcessInfo() {
1768
1832
 
1769
1833
  // src/shared/collector/user-info.ts
1770
1834
  init_cjs_shims();
1771
- var import_os2 = __toESM(require("os"));
1835
+ var import_os3 = __toESM(require("os"));
1772
1836
  async function collectUserInfo() {
1773
1837
  try {
1774
- const userInfo = import_os2.default.userInfo();
1838
+ const userInfo = import_os3.default.userInfo();
1775
1839
  return {
1776
1840
  uid: userInfo.uid,
1777
1841
  gid: userInfo.gid,
@@ -1909,10 +1973,10 @@ async function analyzeRoute(c) {
1909
1973
  const toolName = input.tool_name || input.a_next?.action_type || "unknown";
1910
1974
  const command = input.command || input.a_next?.action_detail || "";
1911
1975
  const key = cacheKey(input.session_id, input.cwd, command);
1912
- const cached = getCached(key);
1913
- if (cached) {
1976
+ const cached2 = getCached(key);
1977
+ if (cached2) {
1914
1978
  return c.json({
1915
- ...cached,
1979
+ ...cached2,
1916
1980
  analysis_duration_ms: 0,
1917
1981
  collected_context: {},
1918
1982
  ...storageOversizeInfo()
@@ -1950,7 +2014,9 @@ async function analyzeRoute(c) {
1950
2014
  violated_layers: JSON.stringify(mossResult.violated_layers),
1951
2015
  reason: mossResult.reason,
1952
2016
  confidence: mossResult.confidence,
1953
- analysis_duration_ms: performance.now() - t0
2017
+ analysis_duration_ms: performance.now() - t0,
2018
+ // 结构化攻击链图(组合式拦截才有;前端弹窗画图用)
2019
+ violation_graph: JSON.stringify(mossResult.violation_graph || null)
1954
2020
  });
1955
2021
  setCache(key, mossResult);
1956
2022
  if (isMultiSessionEnabled()) {
@@ -1974,6 +2040,7 @@ async function analyzeRoute(c) {
1974
2040
  violated_layers: mossResult.violated_layers,
1975
2041
  confidence: mossResult.confidence,
1976
2042
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
2043
+ violation_graph: mossResult.violation_graph ?? null,
1977
2044
  ...storageOversizeInfo(),
1978
2045
  collected_context: {
1979
2046
  os: context.os,
@@ -2221,17 +2288,17 @@ async function dashboardRoute(c) {
2221
2288
  return c.html(UNAUTHORIZED_HTML, 401, DASHBOARD_SECURITY_HEADERS);
2222
2289
  }
2223
2290
  }
2224
- const { readFileSync: readFileSync3, existsSync: existsSync3 } = await import("fs");
2225
- const { resolve, dirname: dirname4 } = await import("path");
2291
+ const { readFileSync: readFileSync4, existsSync: existsSync4 } = await import("fs");
2292
+ const { resolve, dirname: dirname5 } = await import("path");
2226
2293
  const { fileURLToPath } = await import("url");
2227
- const __dirname = dirname4(fileURLToPath(importMetaUrl));
2294
+ const __dirname = dirname5(fileURLToPath(importMetaUrl));
2228
2295
  const paths = [
2229
2296
  resolve(__dirname, "dashboard.html"),
2230
2297
  resolve(__dirname, "../dashboard.html"),
2231
2298
  resolve(__dirname, "../src/v1/dashboard.html")
2232
2299
  ];
2233
- const htmlPath = paths.find((p) => existsSync3(p)) || paths[0];
2234
- const html = readFileSync3(htmlPath, "utf-8");
2300
+ const htmlPath = paths.find((p) => existsSync4(p)) || paths[0];
2301
+ const html = readFileSync4(htmlPath, "utf-8");
2235
2302
  return c.html(html, 200, DASHBOARD_SECURITY_HEADERS);
2236
2303
  }
2237
2304
  // Annotate the CommonJS export names for ESM import in node: