@kenhkl/agent-gate 0.8.2 → 0.9.1

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/v3/cli.js CHANGED
@@ -50,7 +50,7 @@ var init_version = __esm({
50
50
  "src/version.ts"() {
51
51
  "use strict";
52
52
  init_cjs_shims();
53
- _version = true ? "0.8.2" : (() => {
53
+ _version = true ? "0.9.1" : (() => {
54
54
  try {
55
55
  const require2 = createRequire(importMetaUrl);
56
56
  const pkg = require2("../package.json");
@@ -76,6 +76,8 @@ __export(security_exports, {
76
76
  agentInflight: () => agentInflight,
77
77
  agentTokens: () => agentTokens,
78
78
  allowedOrigins: () => allowedOrigins,
79
+ archiveKeepRecords: () => archiveKeepRecords,
80
+ archiveThresholdRecords: () => archiveThresholdRecords,
79
81
  authConfigError: () => authConfigError,
80
82
  authEnabled: () => authEnabled,
81
83
  authMode: () => authMode,
@@ -88,6 +90,8 @@ __export(security_exports, {
88
90
  checkToken: () => checkToken,
89
91
  cookiePathAllowed: () => cookiePathAllowed,
90
92
  describe: () => describe,
93
+ diskDegradePercent: () => diskDegradePercent,
94
+ diskWarnPercent: () => diskWarnPercent,
91
95
  ensureAutoToken: () => ensureAutoToken,
92
96
  ensurePrivateDir: () => ensurePrivateDir,
93
97
  failFastOnAuthError: () => failFastOnAuthError,
@@ -100,6 +104,7 @@ __export(security_exports, {
100
104
  maxConnections: () => maxConnections,
101
105
  maxInflight: () => maxInflight,
102
106
  maxQueue: () => maxQueue,
107
+ maxRecordBytes: () => maxRecordBytes,
103
108
  normalizeOrigin: () => normalizeOrigin,
104
109
  noteQueueReject: () => noteQueueReject,
105
110
  noteSessionAccess: () => noteSessionAccess,
@@ -385,6 +390,21 @@ function bindAgent(principal, agentType) {
385
390
  function maxBodyBytes() {
386
391
  return envInt("AGENT_GATE_MAX_BODY_BYTES", 16 * 1024 * 1024);
387
392
  }
393
+ function maxRecordBytes() {
394
+ return envInt("AGENT_GATE_MAX_RECORD_BYTES", 1024 * 1024);
395
+ }
396
+ function archiveThresholdRecords() {
397
+ return envInt("AGENT_GATE_ARCHIVE_THRESHOLD", 1e5);
398
+ }
399
+ function archiveKeepRecords() {
400
+ return envInt("AGENT_GATE_ARCHIVE_KEEP", 5e4);
401
+ }
402
+ function diskWarnPercent() {
403
+ return envInt("AGENT_GATE_DISK_WARN_PERCENT", 5);
404
+ }
405
+ function diskDegradePercent() {
406
+ return envInt("AGENT_GATE_DISK_DEGRADE_PERCENT", 2);
407
+ }
388
408
  function maxInflight() {
389
409
  return poolLimit("biz");
390
410
  }
@@ -603,6 +623,66 @@ var init_security = __esm({
603
623
  }
604
624
  });
605
625
 
626
+ // src/shared/storage/record-guard.ts
627
+ function clipText(value, limit = maxRecordBytes()) {
628
+ const s = String(value ?? "");
629
+ if (limit <= 0 || s.length <= limit) return s;
630
+ const head = s.slice(0, limit);
631
+ const digest = (0, import_crypto.createHash)("sha256").update(s).digest("hex").slice(0, 16);
632
+ return `${head}\u2026[truncated ${s.length - limit}B sha256:${digest}]`;
633
+ }
634
+ function diskFreePercent(targetPath) {
635
+ try {
636
+ const st = (0, import_fs.statfsSync)((0, import_path.dirname)(targetPath));
637
+ const total = Number(st.blocks) || 0;
638
+ const avail = Number(st.bavail) || 0;
639
+ if (!total) return 100;
640
+ return avail / total * 100;
641
+ } catch {
642
+ return 100;
643
+ }
644
+ }
645
+ function shouldDegradeWrites(targetPath) {
646
+ const degrade = diskDegradePercent();
647
+ if (degrade <= 0) return false;
648
+ return diskFreePercent(targetPath) < degrade;
649
+ }
650
+ function degradeRecord(rec) {
651
+ const command = String(rec.command ?? "");
652
+ const clipped = command.length > DEGRADE_COMMAND_BYTES ? `${command.slice(0, DEGRADE_COMMAND_BYTES)}\u2026[degraded]` : command;
653
+ return {
654
+ ...rec,
655
+ command: clipped,
656
+ action_detail: String(rec.action_detail ?? "") > "" ? String(rec.action_detail).slice(0, DEGRADE_COMMAND_BYTES) : "",
657
+ description: "",
658
+ reason: String(rec.reason ?? "").slice(0, 256)
659
+ };
660
+ }
661
+ function prepareRecordForStorage(rec, targetPath) {
662
+ let out = {
663
+ ...rec,
664
+ command: clipText(rec.command),
665
+ action_detail: clipText(rec.action_detail),
666
+ reason: clipText(rec.reason, 4096),
667
+ description: clipText(rec.description, 4096)
668
+ };
669
+ const degraded = shouldDegradeWrites(targetPath);
670
+ if (degraded) out = degradeRecord(out);
671
+ return { record: out, degraded };
672
+ }
673
+ var import_crypto, import_fs, import_path, DEGRADE_COMMAND_BYTES;
674
+ var init_record_guard = __esm({
675
+ "src/shared/storage/record-guard.ts"() {
676
+ "use strict";
677
+ init_cjs_shims();
678
+ import_crypto = require("crypto");
679
+ import_fs = require("fs");
680
+ import_path = require("path");
681
+ init_security();
682
+ DEGRADE_COMMAND_BYTES = 512;
683
+ }
684
+ });
685
+
606
686
  // src/shared/storage/json-storage.ts
607
687
  var json_storage_exports = {};
608
688
  __export(json_storage_exports, {
@@ -613,17 +693,18 @@ function nowISO() {
613
693
  }
614
694
  function getDefaultDataDir() {
615
695
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
616
- const xdgData = process.env.XDG_DATA_HOME || (0, import_path.join)(home, ".local", "share");
617
- return (0, import_path.join)(xdgData, "agent_gate", "storage");
696
+ const xdgData = process.env.XDG_DATA_HOME || (0, import_path2.join)(home, ".local", "share");
697
+ return (0, import_path2.join)(xdgData, "agent_gate", "storage");
618
698
  }
619
- var import_fs, import_path, JsonStorage;
699
+ var import_fs2, import_path2, JsonStorage;
620
700
  var init_json_storage = __esm({
621
701
  "src/shared/storage/json-storage.ts"() {
622
702
  "use strict";
623
703
  init_cjs_shims();
624
- import_fs = require("fs");
625
- import_path = require("path");
704
+ import_fs2 = require("fs");
705
+ import_path2 = require("path");
626
706
  init_security();
707
+ init_record_guard();
627
708
  JsonStorage = class {
628
709
  dataDir;
629
710
  agentsPath;
@@ -636,11 +717,11 @@ var init_json_storage = __esm({
636
717
  sessionLocks = /* @__PURE__ */ new Map();
637
718
  constructor(dataDir) {
638
719
  this.dataDir = dataDir || process.env.AGENT_GATE_DATA_DIR || getDefaultDataDir();
639
- this.agentsPath = (0, import_path.join)(this.dataDir, "agents.json");
640
- this.sessionsPath = (0, import_path.join)(this.dataDir, "sessions.json");
641
- this.toolCallsDir = (0, import_path.join)(this.dataDir, "tool_calls");
642
- if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true, mode: 448 });
643
- if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true, mode: 448 });
720
+ this.agentsPath = (0, import_path2.join)(this.dataDir, "agents.json");
721
+ this.sessionsPath = (0, import_path2.join)(this.dataDir, "sessions.json");
722
+ this.toolCallsDir = (0, import_path2.join)(this.dataDir, "tool_calls");
723
+ if (!(0, import_fs2.existsSync)(this.dataDir)) (0, import_fs2.mkdirSync)(this.dataDir, { recursive: true, mode: 448 });
724
+ if (!(0, import_fs2.existsSync)(this.toolCallsDir)) (0, import_fs2.mkdirSync)(this.toolCallsDir, { recursive: true, mode: 448 });
644
725
  this.hardenStoragePermissions();
645
726
  this.nextId = this.recoverNextId();
646
727
  }
@@ -652,10 +733,10 @@ var init_json_storage = __esm({
652
733
  const uid = process.getuid?.();
653
734
  const tighten = (p, mode) => {
654
735
  try {
655
- const st = (0, import_fs.statSync)(p);
736
+ const st = (0, import_fs2.statSync)(p);
656
737
  if (st.isSymbolicLink()) return;
657
738
  if (uid !== void 0 && st.uid !== uid) return;
658
- if ((st.mode & 511) !== mode) (0, import_fs.chmodSync)(p, mode);
739
+ if ((st.mode & 511) !== mode) (0, import_fs2.chmodSync)(p, mode);
659
740
  } catch {
660
741
  }
661
742
  };
@@ -664,9 +745,9 @@ var init_json_storage = __esm({
664
745
  tighten(this.agentsPath, 384);
665
746
  tighten(this.sessionsPath, 384);
666
747
  try {
667
- for (const f of (0, import_fs.readdirSync)(this.toolCallsDir)) {
748
+ for (const f of (0, import_fs2.readdirSync)(this.toolCallsDir)) {
668
749
  if (f.endsWith(".json") || f.endsWith(".tmp")) {
669
- tighten((0, import_path.join)(this.toolCallsDir, f), 384);
750
+ tighten((0, import_path2.join)(this.toolCallsDir, f), 384);
670
751
  }
671
752
  }
672
753
  } catch {
@@ -676,9 +757,9 @@ var init_json_storage = __esm({
676
757
  recoverNextId() {
677
758
  let maxId = 0;
678
759
  try {
679
- const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
760
+ const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
680
761
  for (const file of files) {
681
- const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
762
+ const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
682
763
  for (const r of records) {
683
764
  if (r.id > maxId) maxId = r.id;
684
765
  }
@@ -689,19 +770,19 @@ var init_json_storage = __esm({
689
770
  }
690
771
  readJsonFile(path11, fallback2) {
691
772
  try {
692
- if (!(0, import_fs.existsSync)(path11)) return fallback2;
693
- return JSON.parse((0, import_fs.readFileSync)(path11, "utf-8"));
773
+ if (!(0, import_fs2.existsSync)(path11)) return fallback2;
774
+ return JSON.parse((0, import_fs2.readFileSync)(path11, "utf-8"));
694
775
  } catch {
695
776
  return fallback2;
696
777
  }
697
778
  }
698
779
  /** 原子写入:先写 .tmp 再 rename(rename 保留 tmp 的 0600 权限) */
699
780
  writeJsonFile(path11, data) {
700
- const dir2 = (0, import_path.dirname)(path11);
701
- if (!(0, import_fs.existsSync)(dir2)) (0, import_fs.mkdirSync)(dir2, { recursive: true, mode: 448 });
781
+ const dir2 = (0, import_path2.dirname)(path11);
782
+ if (!(0, import_fs2.existsSync)(dir2)) (0, import_fs2.mkdirSync)(dir2, { recursive: true, mode: 448 });
702
783
  const tmp = path11 + ".tmp";
703
- (0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
704
- (0, import_fs.renameSync)(tmp, path11);
784
+ (0, import_fs2.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
785
+ (0, import_fs2.renameSync)(tmp, path11);
705
786
  }
706
787
  loadAgents() {
707
788
  const raw = this.readJsonFile(this.agentsPath, {});
@@ -719,12 +800,12 @@ var init_json_storage = __esm({
719
800
  }
720
801
  loadToolCalls(sessionId) {
721
802
  return this.readJsonFile(
722
- (0, import_path.join)(this.toolCallsDir, `${sessionId}.json`),
803
+ (0, import_path2.join)(this.toolCallsDir, `${sessionId}.json`),
723
804
  []
724
805
  );
725
806
  }
726
807
  saveToolCalls(sessionId, records) {
727
- this.writeJsonFile((0, import_path.join)(this.toolCallsDir, `${sessionId}.json`), records);
808
+ this.writeJsonFile((0, import_path2.join)(this.toolCallsDir, `${sessionId}.json`), records);
728
809
  }
729
810
  getOrCreateAgent(agentType, hostname, version3 = "") {
730
811
  const agents = this.loadAgents();
@@ -769,6 +850,10 @@ var init_json_storage = __esm({
769
850
  return Math.max(...records.map((r) => r.seq)) + 1;
770
851
  }
771
852
  insertToolCall(record) {
853
+ record = prepareRecordForStorage(
854
+ record,
855
+ this.dataDir
856
+ ).record;
772
857
  const sessionId = record.session_id;
773
858
  const prev = this.sessionLocks.get(sessionId) ?? Promise.resolve();
774
859
  const next = prev.then(() => {
@@ -806,9 +891,9 @@ var init_json_storage = __esm({
806
891
  allRecords = records.map((r) => this.enrichRecord(r, sessions, agents));
807
892
  } else {
808
893
  try {
809
- const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
894
+ const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
810
895
  for (const file of files) {
811
- const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
896
+ const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
812
897
  allRecords.push(...records.map((r) => this.enrichRecord(r, sessions, agents)));
813
898
  }
814
899
  } catch {
@@ -817,9 +902,21 @@ var init_json_storage = __esm({
817
902
  if (params.agentType) {
818
903
  allRecords = allRecords.filter((r) => r.agent_type === params.agentType);
819
904
  }
905
+ if (params.agentId) {
906
+ allRecords = allRecords.filter((r) => `${r.agent_type}:${r.hostname}` === params.agentId);
907
+ }
820
908
  if (params.decision) {
821
909
  allRecords = allRecords.filter((r) => r.decision === params.decision);
822
910
  }
911
+ if (params.riskLevel) {
912
+ allRecords = allRecords.filter((r) => r.risk_level === params.riskLevel);
913
+ }
914
+ if (params.fromTime) {
915
+ allRecords = allRecords.filter((r) => r.called_at >= params.fromTime);
916
+ }
917
+ if (params.toTime) {
918
+ allRecords = allRecords.filter((r) => r.called_at <= params.toTime);
919
+ }
823
920
  allRecords.sort((a, b) => b.called_at.localeCompare(a.called_at));
824
921
  const offset = params.offset || 0;
825
922
  const limit = params.limit || 50;
@@ -830,13 +927,22 @@ var init_json_storage = __esm({
830
927
  const agents = this.loadAgents();
831
928
  let allRecords = [];
832
929
  try {
833
- const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
930
+ const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
834
931
  for (const file of files) {
835
- const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
932
+ const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
836
933
  allRecords.push(...records);
837
934
  }
838
935
  } catch {
839
936
  }
937
+ if (params.sessionId) {
938
+ allRecords = allRecords.filter((r) => r.session_id === params.sessionId);
939
+ }
940
+ if (params.agentId) {
941
+ const allowed = new Set(
942
+ [...sessions.values()].filter((s) => s.agent_id === params.agentId).map((s) => s.id)
943
+ );
944
+ allRecords = allRecords.filter((r) => allowed.has(r.session_id));
945
+ }
840
946
  if (params.agentType) {
841
947
  const allowed = new Set(
842
948
  [...sessions.values()].filter((s) => (agents.get(s.agent_id)?.agent_type || "") === params.agentType).map((s) => s.id)
@@ -846,6 +952,15 @@ var init_json_storage = __esm({
846
952
  if (params.decision) {
847
953
  allRecords = allRecords.filter((r) => r.decision === params.decision);
848
954
  }
955
+ if (params.riskLevel) {
956
+ allRecords = allRecords.filter((r) => r.risk_level === params.riskLevel);
957
+ }
958
+ if (params.fromTime) {
959
+ allRecords = allRecords.filter((r) => r.called_at >= params.fromTime);
960
+ }
961
+ if (params.toTime) {
962
+ allRecords = allRecords.filter((r) => r.called_at <= params.toTime);
963
+ }
849
964
  return allRecords.length;
850
965
  }
851
966
  getStorageStats() {
@@ -853,12 +968,12 @@ var init_json_storage = __esm({
853
968
  let jsonFiles = 0;
854
969
  let jsonBytes = 0;
855
970
  try {
856
- const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
971
+ const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
857
972
  for (const file of files) {
858
- const stat = (0, import_fs.statSync)((0, import_path.join)(this.toolCallsDir, file));
973
+ const stat = (0, import_fs2.statSync)((0, import_path2.join)(this.toolCallsDir, file));
859
974
  jsonFiles++;
860
975
  jsonBytes += stat.size;
861
- const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
976
+ const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
862
977
  toolCalls += records.length;
863
978
  }
864
979
  } catch {
@@ -868,9 +983,9 @@ var init_json_storage = __esm({
868
983
  clearToolCalls() {
869
984
  let removed = 0;
870
985
  try {
871
- const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
986
+ const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
872
987
  for (const file of files) {
873
- (0, import_fs.unlinkSync)((0, import_path.join)(this.toolCallsDir, file));
988
+ (0, import_fs2.unlinkSync)((0, import_path2.join)(this.toolCallsDir, file));
874
989
  removed++;
875
990
  }
876
991
  } catch {
@@ -888,6 +1003,49 @@ var init_json_storage = __esm({
888
1003
  hostname: agent?.hostname || ""
889
1004
  };
890
1005
  }
1006
+ /**
1007
+ * 归档最老的记录:JSON 模式下每个 session 一个文件,这里把所有 session 的记录
1008
+ * 汇总排序,最老的 (total - keep) 条写进 `<dataDir>/archive/*.jsonl.gz`,
1009
+ * 再从各自的 session 文件里移除。数据不丢,只是不在主目录了。
1010
+ */
1011
+ archiveOldRecords(keep) {
1012
+ if (keep <= 0 || !(0, import_fs2.existsSync)(this.toolCallsDir)) return { archived: 0, file: "" };
1013
+ const bySession = /* @__PURE__ */ new Map();
1014
+ let total = 0;
1015
+ for (const f of (0, import_fs2.readdirSync)(this.toolCallsDir)) {
1016
+ if (!f.endsWith(".json")) continue;
1017
+ const sid = f.slice(0, -".json".length);
1018
+ const recs = this.loadToolCalls(sid);
1019
+ if (recs.length) {
1020
+ bySession.set(sid, recs);
1021
+ total += recs.length;
1022
+ }
1023
+ }
1024
+ if (total <= keep) return { archived: 0, file: "" };
1025
+ const flat = [];
1026
+ for (const [sid, recs] of bySession) for (const rec of recs) flat.push({ sid, rec });
1027
+ flat.sort((a, b) => String(a.rec.called_at).localeCompare(String(b.rec.called_at)));
1028
+ const archiveCount = total - keep;
1029
+ const toArchive = flat.slice(0, archiveCount);
1030
+ const archiveIds = new Set(toArchive.map((x) => String(x.rec.id)));
1031
+ const { mkdirSync: mkdirSync5, writeFileSync: writeFileSync4 } = require("fs");
1032
+ const { join: join12 } = require("path");
1033
+ const { gzipSync } = require("zlib");
1034
+ const archiveDir = join12(this.dataDir, "archive");
1035
+ if (!(0, import_fs2.existsSync)(archiveDir)) mkdirSync5(archiveDir, { recursive: true, mode: 448 });
1036
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
1037
+ const file = join12(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
1038
+ const payload = toArchive.map((x) => JSON.stringify(x.rec)).join("\n") + "\n";
1039
+ writeFileSync4(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
1040
+ for (const [sid, recs] of bySession) {
1041
+ const remain = recs.filter((r) => !archiveIds.has(String(r.id)));
1042
+ if (remain.length !== recs.length) this.saveToolCalls(sid, remain);
1043
+ }
1044
+ return { archived: toArchive.length, file };
1045
+ }
1046
+ /** JSON 模式没有需要回收的数据库页,归档已把文件挪走。 */
1047
+ vacuum() {
1048
+ }
891
1049
  getAgentsList(agentType) {
892
1050
  const agents = this.loadAgents();
893
1051
  const sessions = this.loadSessions();
@@ -922,9 +1080,9 @@ var init_json_storage = __esm({
922
1080
  getTimeline(limit = 100) {
923
1081
  const buckets = /* @__PURE__ */ new Map();
924
1082
  try {
925
- const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
1083
+ const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
926
1084
  for (const file of files) {
927
- const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
1085
+ const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
928
1086
  for (const r of records) {
929
1087
  const minute = r.called_at.replace(/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}):\d{2}/, "$1T$2");
930
1088
  const bucket = buckets.get(minute) || { allow: 0, deny: 0 };
@@ -955,16 +1113,17 @@ __export(sqlite_storage_exports, {
955
1113
  });
956
1114
  function getDefaultDbPath() {
957
1115
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
958
- const xdgData = process.env.XDG_DATA_HOME || (0, import_path2.join)(home, ".local", "share");
959
- return (0, import_path2.join)(xdgData, "agent_gate", "agent_gate_ts.db");
1116
+ const xdgData = process.env.XDG_DATA_HOME || (0, import_path3.join)(home, ".local", "share");
1117
+ return (0, import_path3.join)(xdgData, "agent_gate", "agent_gate_ts.db");
960
1118
  }
961
- var import_fs2, import_path2, SCHEMA, SqliteStorage;
1119
+ var import_fs3, import_path3, SCHEMA, SqliteStorage;
962
1120
  var init_sqlite_storage = __esm({
963
1121
  "src/shared/storage/sqlite-storage.ts"() {
964
1122
  "use strict";
965
1123
  init_cjs_shims();
966
- import_fs2 = require("fs");
967
- import_path2 = require("path");
1124
+ import_fs3 = require("fs");
1125
+ import_path3 = require("path");
1126
+ init_record_guard();
968
1127
  SCHEMA = `
969
1128
  CREATE TABLE IF NOT EXISTS agents (
970
1129
  id TEXT PRIMARY KEY,
@@ -1024,8 +1183,8 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1024
1183
  );
1025
1184
  }
1026
1185
  const path11 = dbPath || getDefaultDbPath();
1027
- const dir2 = (0, import_path2.dirname)(path11);
1028
- if (!(0, import_fs2.existsSync)(dir2)) (0, import_fs2.mkdirSync)(dir2, { recursive: true });
1186
+ const dir2 = (0, import_path3.dirname)(path11);
1187
+ if (!(0, import_fs3.existsSync)(dir2)) (0, import_fs3.mkdirSync)(dir2, { recursive: true });
1029
1188
  this.dbPath = path11;
1030
1189
  this.db = new Database(path11);
1031
1190
  this.db.pragma("journal_mode = WAL");
@@ -1059,6 +1218,10 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1059
1218
  return row.next;
1060
1219
  }
1061
1220
  insertToolCall(record) {
1221
+ record = prepareRecordForStorage(
1222
+ record,
1223
+ this.dbPath
1224
+ ).record;
1062
1225
  const result = this.db.transaction((rec) => {
1063
1226
  const row = this.db.prepare(
1064
1227
  "SELECT COALESCE(MAX(seq), 0) + 1 as next FROM tool_calls WHERE session_id = ?"
@@ -1102,6 +1265,10 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1102
1265
  conditions.push("tc.session_id = ?");
1103
1266
  values.push(params.sessionId);
1104
1267
  }
1268
+ if (params.agentId) {
1269
+ conditions.push("s.agent_id = ?");
1270
+ values.push(params.agentId);
1271
+ }
1105
1272
  if (params.agentType) {
1106
1273
  conditions.push("a.agent_type = ?");
1107
1274
  values.push(params.agentType);
@@ -1110,6 +1277,18 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1110
1277
  conditions.push("tc.decision = ?");
1111
1278
  values.push(params.decision);
1112
1279
  }
1280
+ if (params.riskLevel) {
1281
+ conditions.push("tc.risk_level = ?");
1282
+ values.push(params.riskLevel);
1283
+ }
1284
+ if (params.fromTime) {
1285
+ conditions.push("tc.called_at >= ?");
1286
+ values.push(params.fromTime);
1287
+ }
1288
+ if (params.toTime) {
1289
+ conditions.push("tc.called_at <= ?");
1290
+ values.push(params.toTime);
1291
+ }
1113
1292
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1114
1293
  const limit = params.limit || 50;
1115
1294
  const offset = params.offset || 0;
@@ -1124,14 +1303,34 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1124
1303
  countToolCalls(params) {
1125
1304
  const conditions = [];
1126
1305
  const values = [];
1127
- if (params.decision) {
1128
- conditions.push("tc.decision = ?");
1129
- values.push(params.decision);
1306
+ if (params.sessionId) {
1307
+ conditions.push("tc.session_id = ?");
1308
+ values.push(params.sessionId);
1309
+ }
1310
+ if (params.agentId) {
1311
+ conditions.push("s.agent_id = ?");
1312
+ values.push(params.agentId);
1130
1313
  }
1131
1314
  if (params.agentType) {
1132
1315
  conditions.push("a.agent_type = ?");
1133
1316
  values.push(params.agentType);
1134
1317
  }
1318
+ if (params.decision) {
1319
+ conditions.push("tc.decision = ?");
1320
+ values.push(params.decision);
1321
+ }
1322
+ if (params.riskLevel) {
1323
+ conditions.push("tc.risk_level = ?");
1324
+ values.push(params.riskLevel);
1325
+ }
1326
+ if (params.fromTime) {
1327
+ conditions.push("tc.called_at >= ?");
1328
+ values.push(params.fromTime);
1329
+ }
1330
+ if (params.toTime) {
1331
+ conditions.push("tc.called_at <= ?");
1332
+ values.push(params.toTime);
1333
+ }
1135
1334
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1136
1335
  const row = this.db.prepare(
1137
1336
  `SELECT COUNT(*) as total FROM tool_calls tc
@@ -1163,6 +1362,49 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1163
1362
  })();
1164
1363
  return result;
1165
1364
  }
1365
+ /**
1366
+ * 把最老的记录归档到本地压缩文件,主库只保留最近 `keep` 条。
1367
+ *
1368
+ * 归档文件是 **JSONL + gzip**(一行一条记录),放在 `<数据库目录>/archive/` 下,
1369
+ * 需要翻旧账时用 `zcat archive/xxx.jsonl.gz | grep ...` 即可 —— 数据不丢,只是
1370
+ * 不在主库里了。写完文件、校验落盘后才删主库行,最后 VACUUM 真正释放磁盘。
1371
+ */
1372
+ archiveOldRecords(keep) {
1373
+ if (keep <= 0) return { archived: 0, file: "" };
1374
+ const total = this.db.prepare("SELECT COUNT(*) as n FROM tool_calls").get().n;
1375
+ if (total <= keep) return { archived: 0, file: "" };
1376
+ const cutoff = this.db.prepare(
1377
+ "SELECT id FROM tool_calls ORDER BY id LIMIT 1 OFFSET ?"
1378
+ ).get(total - keep - 1);
1379
+ if (!cutoff) return { archived: 0, file: "" };
1380
+ const rows = this.db.prepare(
1381
+ "SELECT * FROM tool_calls WHERE id <= ? ORDER BY id"
1382
+ ).all(cutoff.id);
1383
+ if (rows.length === 0) return { archived: 0, file: "" };
1384
+ const { writeFileSync: writeFileSync4, mkdirSync: mkdirSync5, existsSync: existsSync12 } = require("fs");
1385
+ const { dirname: dirname6, join: join12 } = require("path");
1386
+ const { gzipSync } = require("zlib");
1387
+ const archiveDir = join12(dirname6(this.dbPath), "archive");
1388
+ if (!existsSync12(archiveDir)) mkdirSync5(archiveDir, { recursive: true, mode: 448 });
1389
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
1390
+ const file = join12(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
1391
+ const payload = rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
1392
+ writeFileSync4(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
1393
+ const deleted = this.db.transaction(() => {
1394
+ const res = this.db.prepare("DELETE FROM tool_calls WHERE id <= ?").run(cutoff.id);
1395
+ this.db.prepare(`
1396
+ UPDATE sessions SET tool_call_count = (
1397
+ SELECT COUNT(*) FROM tool_calls WHERE tool_calls.session_id = sessions.id
1398
+ )
1399
+ `).run();
1400
+ return Number(res.changes);
1401
+ })();
1402
+ return { archived: deleted, file };
1403
+ }
1404
+ /** 真正释放磁盘空间:DELETE 后必须 VACUUM,否则文件不会变小。 */
1405
+ vacuum() {
1406
+ this.db.exec("VACUUM");
1407
+ }
1166
1408
  getAgentsList(agentType) {
1167
1409
  const where = agentType ? "WHERE a.agent_type = ?" : "";
1168
1410
  return this.db.prepare(`
@@ -1254,12 +1496,12 @@ function getDb(dbPath) {
1254
1496
  try {
1255
1497
  const Database = require("better-sqlite3");
1256
1498
  const { existsSync: existsSync12, mkdirSync: mkdirSync5 } = require("fs");
1257
- const { join: join12, dirname: dirname5 } = require("path");
1499
+ const { join: join12, dirname: dirname6 } = require("path");
1258
1500
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
1259
1501
  const xdgData = process.env.XDG_DATA_HOME || join12(home, ".local", "share");
1260
1502
  const defaultPath = join12(xdgData, "agent_gate", "agent_gate_ts.db");
1261
1503
  const path11 = dbPath || defaultPath;
1262
- const dir2 = dirname5(path11);
1504
+ const dir2 = dirname6(path11);
1263
1505
  if (!existsSync12(dir2)) mkdirSync5(dir2, { recursive: true });
1264
1506
  rawDb = new Database(path11);
1265
1507
  rawDb.pragma("journal_mode = WAL");
@@ -1315,15 +1557,29 @@ function sessionHistoryLimit() {
1315
1557
  const v = Number.isFinite(n) ? n : DEFAULT_MAX_SESSIONS;
1316
1558
  return Math.max(1, Math.min(v, 50));
1317
1559
  }
1318
- function buildSessionHistory(queryToolCalls2, sessionId) {
1560
+ function buildSessionHistory(queryToolCalls2, sessionId, listAgentTypes) {
1319
1561
  if (!isMultiSessionEnabled()) return [];
1320
1562
  const maxSessions = sessionHistoryLimit();
1321
1563
  try {
1322
1564
  const scanLimit = Math.max(DEFAULT_HISTORY_LIMIT, maxSessions * DEFAULT_ACTIONS_PER_SESSION);
1323
- const recent = queryToolCalls2({ limit: scanLimit });
1565
+ const agentTypes = listAgentTypes?.() ?? [];
1566
+ let recent;
1567
+ if (agentTypes.length > 1) {
1568
+ const perAgent = Math.max(
1569
+ DEFAULT_ACTIONS_PER_SESSION,
1570
+ Math.floor(DEFAULT_HISTORY_LIMIT / agentTypes.length)
1571
+ );
1572
+ recent = agentTypes.flatMap((a) => queryToolCalls2({ limit: perAgent, agentType: a }));
1573
+ } else {
1574
+ recent = queryToolCalls2({ limit: scanLimit });
1575
+ }
1324
1576
  const bySession = /* @__PURE__ */ new Map();
1577
+ const sessionAgent = /* @__PURE__ */ new Map();
1325
1578
  for (const tc of recent) {
1326
1579
  if (tc.session_id === sessionId) continue;
1580
+ if (tc.agent_type && !sessionAgent.has(tc.session_id)) {
1581
+ sessionAgent.set(tc.session_id, tc.agent_type);
1582
+ }
1327
1583
  const list = bySession.get(tc.session_id) || [];
1328
1584
  list.unshift({
1329
1585
  action_type: tc.action_type,
@@ -1334,6 +1590,7 @@ function buildSessionHistory(queryToolCalls2, sessionId) {
1334
1590
  }
1335
1591
  return [...bySession.entries()].slice(0, maxSessions).map(([sid, actions]) => ({
1336
1592
  session_id: sid,
1593
+ ...sessionAgent.get(sid) ? { agent_id: sessionAgent.get(sid) } : {},
1337
1594
  action_history: actions.slice(0, DEFAULT_ACTIONS_PER_SESSION)
1338
1595
  }));
1339
1596
  } catch {
@@ -1494,18 +1751,23 @@ var init_models = __esm({
1494
1751
  text: import_zod.z.string().default(""),
1495
1752
  actions: import_zod.z.array(import_zod.z.object({
1496
1753
  action_type: import_zod.z.string(),
1497
- action_detail: import_zod.z.string()
1754
+ action_detail: import_zod.z.string(),
1755
+ output: import_zod.z.string().optional().describe("\u5DE5\u5177\u8FD4\u56DE\u5185\u5BB9\uFF1Bask_user_question \u7684\u7528\u6237\u56DE\u7B54\u9760\u5B83\u4F20\u7ED9 AgentMoss \u5224\u6388\u6743")
1498
1756
  })).default([])
1499
1757
  })).default([]),
1500
1758
  action_history: import_zod.z.array(import_zod.z.object({
1501
1759
  action_type: import_zod.z.string(),
1502
- action_detail: import_zod.z.string()
1760
+ action_detail: import_zod.z.string(),
1761
+ // 授权类规则(改密码 / 删用户)靠 ask_user_question 的 output 判断用户是否已确认。
1762
+ // 此前 schema 里没有这个字段,Agent 传了也会被剥掉 → 必然判成「未授权」。
1763
+ output: import_zod.z.string().optional().describe("\u5DE5\u5177\u8FD4\u56DE\u5185\u5BB9\uFF1Bask_user_question \u7684\u7528\u6237\u56DE\u7B54\u9760\u5B83\u4F20\u7ED9 AgentMoss \u5224\u6388\u6743")
1503
1764
  })).default([]),
1504
1765
  session_history: import_zod.z.array(import_zod.z.object({
1505
1766
  session_id: import_zod.z.string(),
1506
1767
  action_history: import_zod.z.array(import_zod.z.object({
1507
1768
  action_type: import_zod.z.string(),
1508
- action_detail: import_zod.z.string()
1769
+ action_detail: import_zod.z.string(),
1770
+ output: import_zod.z.string().optional()
1509
1771
  })).default([])
1510
1772
  })).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"),
1511
1773
  metadata: import_zod.z.record(import_zod.z.unknown()).optional()
@@ -1550,20 +1812,23 @@ var init_models = __esm({
1550
1812
  function normalize(input, systemContext) {
1551
1813
  const actionHistory = input.action_history.map((h) => ({
1552
1814
  action_type: h.action_type,
1553
- action_detail: h.action_detail
1815
+ action_detail: h.action_detail,
1816
+ output: h.output ?? ""
1554
1817
  }));
1555
1818
  const sessionHistory = (input.session_history || []).map((s) => ({
1556
1819
  session_id: s.session_id,
1557
1820
  action_history: s.action_history.map((h) => ({
1558
1821
  action_type: h.action_type,
1559
- action_detail: h.action_detail
1822
+ action_detail: h.action_detail,
1823
+ output: h.output ?? ""
1560
1824
  }))
1561
1825
  }));
1562
1826
  const promptHistory = input.prompt_history.map((t) => ({
1563
1827
  text: t.text,
1564
1828
  actions: t.actions.map((a) => ({
1565
1829
  action_type: a.action_type,
1566
- action_detail: a.action_detail
1830
+ action_detail: a.action_detail,
1831
+ output: a.output ?? ""
1567
1832
  }))
1568
1833
  }));
1569
1834
  const toolName = input.tool_name || input.a_next?.action_type || "unknown";
@@ -1831,7 +2096,9 @@ async function analyzeRoute(c) {
1831
2096
  if (isMultiSessionEnabled()) {
1832
2097
  input.session_history = buildSessionHistory(
1833
2098
  (params) => queryToolCalls(params),
1834
- input.session_id
2099
+ input.session_id,
2100
+ // 多 agent 时按 agent 分组取历史,避免高频 agent 把别人的动作挤出窗口
2101
+ () => getAgentsList().map((a) => a.agent_type)
1835
2102
  );
1836
2103
  }
1837
2104
  const mossRequest = normalize(input, context);
@@ -1915,13 +2182,22 @@ async function sessionsRoute(c) {
1915
2182
  return c.json({ session_id: sessionId, tool_calls: rows });
1916
2183
  }
1917
2184
  async function toolCallsRoute(c) {
1918
- const decision = c.req.query("decision");
1919
- const limit = parseInt(c.req.query("limit") || "50", 10);
1920
- const offset = parseInt(c.req.query("offset") || "0", 10);
2185
+ const sessionId = c.req.query("session_id") || void 0;
2186
+ let agentId = c.req.query("agent_id") || void 0;
2187
+ const decision = c.req.query("decision") || void 0;
2188
+ const riskLevel = c.req.query("risk_level") || void 0;
2189
+ const fromTime = c.req.query("from") || void 0;
2190
+ const toTime = c.req.query("to") || void 0;
2191
+ const rawLimit = parseInt(c.req.query("limit") || "50", 10);
2192
+ const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 500) : 50;
2193
+ const rawOffset = parseInt(c.req.query("offset") || "0", 10);
2194
+ const offset = Number.isFinite(rawOffset) && rawOffset > 0 ? rawOffset : 0;
1921
2195
  const bound = boundAgentOf(c.get("principal") || "");
2196
+ if (bound) agentId = void 0;
1922
2197
  const agentType = bound || void 0;
1923
- const total = countToolCalls({ decision: decision ?? void 0, agentType });
1924
- const data = queryToolCalls({ decision: decision ?? void 0, agentType, limit, offset });
2198
+ const filter2 = { sessionId, agentId, agentType, decision, riskLevel, fromTime, toTime };
2199
+ const total = countToolCalls(filter2);
2200
+ const data = queryToolCalls({ ...filter2, limit, offset });
1925
2201
  return c.json({ total, data });
1926
2202
  }
1927
2203
  async function agentsRoute(c) {
@@ -2110,13 +2386,13 @@ async function dashboardRoute(c) {
2110
2386
  }
2111
2387
  }
2112
2388
  const { readFileSync: readFileSync14, existsSync: existsSync12 } = await import("fs");
2113
- const { resolve: resolve3, dirname: dirname5 } = await import("path");
2389
+ const { resolve: resolve4, dirname: dirname6 } = await import("path");
2114
2390
  const { fileURLToPath } = await import("url");
2115
- const __dirname2 = dirname5(fileURLToPath(importMetaUrl));
2391
+ const __dirname2 = dirname6(fileURLToPath(importMetaUrl));
2116
2392
  const paths = [
2117
- resolve3(__dirname2, "dashboard.html"),
2118
- resolve3(__dirname2, "../dashboard.html"),
2119
- resolve3(__dirname2, "../src/v1/dashboard.html")
2393
+ resolve4(__dirname2, "dashboard.html"),
2394
+ resolve4(__dirname2, "../dashboard.html"),
2395
+ resolve4(__dirname2, "../src/v1/dashboard.html")
2120
2396
  ];
2121
2397
  const htmlPath = paths.find((p) => existsSync12(p)) || paths[0];
2122
2398
  const html = readFileSync14(htmlPath, "utf-8");
@@ -2348,10 +2624,10 @@ function awaitify(asyncFn, arity) {
2348
2624
  if (typeof args[arity - 1] === "function") {
2349
2625
  return asyncFn.apply(this, args);
2350
2626
  }
2351
- return new Promise((resolve3, reject2) => {
2627
+ return new Promise((resolve4, reject2) => {
2352
2628
  args[arity - 1] = (err, ...cbArgs) => {
2353
2629
  if (err) return reject2(err);
2354
- resolve3(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
2630
+ resolve4(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
2355
2631
  };
2356
2632
  asyncFn.apply(this, args);
2357
2633
  });
@@ -2533,13 +2809,13 @@ function mapSeries(coll, iteratee, callback) {
2533
2809
  return _asyncMap(eachOfSeries$1, coll, iteratee, callback);
2534
2810
  }
2535
2811
  function promiseCallback() {
2536
- let resolve3, reject2;
2812
+ let resolve4, reject2;
2537
2813
  function callback(err, ...args) {
2538
2814
  if (err) return reject2(err);
2539
- resolve3(args.length > 1 ? args : args[0]);
2815
+ resolve4(args.length > 1 ? args : args[0]);
2540
2816
  }
2541
2817
  callback[PROMISE_SYMBOL] = new Promise((res, rej) => {
2542
- resolve3 = res, reject2 = rej;
2818
+ resolve4 = res, reject2 = rej;
2543
2819
  });
2544
2820
  return callback;
2545
2821
  }
@@ -2812,8 +3088,8 @@ function queue$1(worker, concurrency, payload) {
2812
3088
  });
2813
3089
  }
2814
3090
  if (rejectOnError || !callback) {
2815
- return new Promise((resolve3, reject2) => {
2816
- res = resolve3;
3091
+ return new Promise((resolve4, reject2) => {
3092
+ res = resolve4;
2817
3093
  rej = reject2;
2818
3094
  });
2819
3095
  }
@@ -2852,10 +3128,10 @@ function queue$1(worker, concurrency, payload) {
2852
3128
  }
2853
3129
  const eventMethod = (name) => (handler) => {
2854
3130
  if (!handler) {
2855
- return new Promise((resolve3, reject2) => {
3131
+ return new Promise((resolve4, reject2) => {
2856
3132
  once2(name, (err, data) => {
2857
3133
  if (err) return reject2(err);
2858
- resolve3(data);
3134
+ resolve4(data);
2859
3135
  });
2860
3136
  });
2861
3137
  }
@@ -6283,7 +6559,7 @@ var require_websocket = __commonJS({
6283
6559
  var http5 = require("http");
6284
6560
  var net2 = require("net");
6285
6561
  var tls = require("tls");
6286
- var { randomBytes: randomBytes2, createHash: createHash4 } = require("crypto");
6562
+ var { randomBytes: randomBytes2, createHash: createHash5 } = require("crypto");
6287
6563
  var { Duplex, Readable } = require("stream");
6288
6564
  var { URL: URL5 } = require("url");
6289
6565
  var PerMessageDeflate = require_permessage_deflate();
@@ -6951,7 +7227,7 @@ var require_websocket = __commonJS({
6951
7227
  abortHandshake(websocket, socket, "Invalid Upgrade header");
6952
7228
  return;
6953
7229
  }
6954
- const digest = createHash4("sha1").update(key + GUID).digest("base64");
7230
+ const digest = createHash5("sha1").update(key + GUID).digest("base64");
6955
7231
  if (res.headers["sec-websocket-accept"] !== digest) {
6956
7232
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
6957
7233
  return;
@@ -7323,7 +7599,7 @@ var require_websocket_server = __commonJS({
7323
7599
  var EventEmitter2 = require("events");
7324
7600
  var http5 = require("http");
7325
7601
  var { Duplex } = require("stream");
7326
- var { createHash: createHash4 } = require("crypto");
7602
+ var { createHash: createHash5 } = require("crypto");
7327
7603
  var extension = require_extension();
7328
7604
  var PerMessageDeflate = require_permessage_deflate();
7329
7605
  var subprotocol = require_subprotocol();
@@ -7630,7 +7906,7 @@ var require_websocket_server = __commonJS({
7630
7906
  );
7631
7907
  }
7632
7908
  if (this._state > RUNNING) return abortHandshake(socket, 503);
7633
- const digest = createHash4("sha1").update(key + GUID).digest("base64");
7909
+ const digest = createHash5("sha1").update(key + GUID).digest("base64");
7634
7910
  const headers = [
7635
7911
  "HTTP/1.1 101 Switching Protocols",
7636
7912
  "Upgrade: websocket",
@@ -25778,7 +26054,7 @@ var require_path_arg = __commonJS({
25778
26054
  "use strict";
25779
26055
  init_cjs_shims();
25780
26056
  var platform2 = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform;
25781
- var { resolve: resolve3, parse: parse2 } = require("path");
26057
+ var { resolve: resolve4, parse: parse2 } = require("path");
25782
26058
  var pathArg = (path11) => {
25783
26059
  if (/\0/.test(path11)) {
25784
26060
  throw Object.assign(
@@ -25789,7 +26065,7 @@ var require_path_arg = __commonJS({
25789
26065
  }
25790
26066
  );
25791
26067
  }
25792
- path11 = resolve3(path11);
26068
+ path11 = resolve4(path11);
25793
26069
  if (platform2 === "win32") {
25794
26070
  const badWinChars = /[*|"<>?:]/;
25795
26071
  const { root } = parse2(path11);
@@ -25811,14 +26087,14 @@ var require_find_made = __commonJS({
25811
26087
  "../node_modules/mkdirp/lib/find-made.js"(exports2, module2) {
25812
26088
  "use strict";
25813
26089
  init_cjs_shims();
25814
- var { dirname: dirname5 } = require("path");
26090
+ var { dirname: dirname6 } = require("path");
25815
26091
  var findMade = (opts, parent2, path11 = void 0) => {
25816
26092
  if (path11 === parent2)
25817
26093
  return Promise.resolve();
25818
26094
  return opts.statAsync(parent2).then(
25819
26095
  (st) => st.isDirectory() ? path11 : void 0,
25820
26096
  // will fail later
25821
- (er) => er.code === "ENOENT" ? findMade(opts, dirname5(parent2), parent2) : void 0
26097
+ (er) => er.code === "ENOENT" ? findMade(opts, dirname6(parent2), parent2) : void 0
25822
26098
  );
25823
26099
  };
25824
26100
  var findMadeSync = (opts, parent2, path11 = void 0) => {
@@ -25827,7 +26103,7 @@ var require_find_made = __commonJS({
25827
26103
  try {
25828
26104
  return opts.statSync(parent2).isDirectory() ? path11 : void 0;
25829
26105
  } catch (er) {
25830
- return er.code === "ENOENT" ? findMadeSync(opts, dirname5(parent2), parent2) : void 0;
26106
+ return er.code === "ENOENT" ? findMadeSync(opts, dirname6(parent2), parent2) : void 0;
25831
26107
  }
25832
26108
  };
25833
26109
  module2.exports = { findMade, findMadeSync };
@@ -25839,10 +26115,10 @@ var require_mkdirp_manual = __commonJS({
25839
26115
  "../node_modules/mkdirp/lib/mkdirp-manual.js"(exports2, module2) {
25840
26116
  "use strict";
25841
26117
  init_cjs_shims();
25842
- var { dirname: dirname5 } = require("path");
26118
+ var { dirname: dirname6 } = require("path");
25843
26119
  var mkdirpManual = (path11, opts, made) => {
25844
26120
  opts.recursive = false;
25845
- const parent2 = dirname5(path11);
26121
+ const parent2 = dirname6(path11);
25846
26122
  if (parent2 === path11) {
25847
26123
  return opts.mkdirAsync(path11, opts).catch((er) => {
25848
26124
  if (er.code !== "EISDIR")
@@ -25865,7 +26141,7 @@ var require_mkdirp_manual = __commonJS({
25865
26141
  });
25866
26142
  };
25867
26143
  var mkdirpManualSync = (path11, opts, made) => {
25868
- const parent2 = dirname5(path11);
26144
+ const parent2 = dirname6(path11);
25869
26145
  opts.recursive = false;
25870
26146
  if (parent2 === path11) {
25871
26147
  try {
@@ -25902,12 +26178,12 @@ var require_mkdirp_native = __commonJS({
25902
26178
  "../node_modules/mkdirp/lib/mkdirp-native.js"(exports2, module2) {
25903
26179
  "use strict";
25904
26180
  init_cjs_shims();
25905
- var { dirname: dirname5 } = require("path");
26181
+ var { dirname: dirname6 } = require("path");
25906
26182
  var { findMade, findMadeSync } = require_find_made();
25907
26183
  var { mkdirpManual, mkdirpManualSync } = require_mkdirp_manual();
25908
26184
  var mkdirpNative = (path11, opts) => {
25909
26185
  opts.recursive = true;
25910
- const parent2 = dirname5(path11);
26186
+ const parent2 = dirname6(path11);
25911
26187
  if (parent2 === path11)
25912
26188
  return opts.mkdirAsync(path11, opts);
25913
26189
  return findMade(opts, path11).then((made) => opts.mkdirAsync(path11, opts).then(() => made).catch((er) => {
@@ -25919,7 +26195,7 @@ var require_mkdirp_native = __commonJS({
25919
26195
  };
25920
26196
  var mkdirpNativeSync = (path11, opts) => {
25921
26197
  opts.recursive = true;
25922
- const parent2 = dirname5(path11);
26198
+ const parent2 = dirname6(path11);
25923
26199
  if (parent2 === path11)
25924
26200
  return opts.mkdirSync(path11, opts);
25925
26201
  const made = findMadeSync(opts, path11);
@@ -26375,17 +26651,17 @@ var require_ProxyFinalRequestFilter = __commonJS({
26375
26651
  // ../node_modules/uuid/dist/esm-node/rng.js
26376
26652
  function rng() {
26377
26653
  if (poolPtr > rnds8Pool.length - 16) {
26378
- import_crypto.default.randomFillSync(rnds8Pool);
26654
+ import_crypto2.default.randomFillSync(rnds8Pool);
26379
26655
  poolPtr = 0;
26380
26656
  }
26381
26657
  return rnds8Pool.slice(poolPtr, poolPtr += 16);
26382
26658
  }
26383
- var import_crypto, rnds8Pool, poolPtr;
26659
+ var import_crypto2, rnds8Pool, poolPtr;
26384
26660
  var init_rng = __esm({
26385
26661
  "../node_modules/uuid/dist/esm-node/rng.js"() {
26386
26662
  "use strict";
26387
26663
  init_cjs_shims();
26388
- import_crypto = __toESM(require("crypto"));
26664
+ import_crypto2 = __toESM(require("crypto"));
26389
26665
  rnds8Pool = new Uint8Array(256);
26390
26666
  poolPtr = rnds8Pool.length;
26391
26667
  }
@@ -26600,14 +26876,14 @@ function md5(bytes) {
26600
26876
  } else if (typeof bytes === "string") {
26601
26877
  bytes = Buffer.from(bytes, "utf8");
26602
26878
  }
26603
- return import_crypto2.default.createHash("md5").update(bytes).digest();
26879
+ return import_crypto3.default.createHash("md5").update(bytes).digest();
26604
26880
  }
26605
- var import_crypto2, md5_default;
26881
+ var import_crypto3, md5_default;
26606
26882
  var init_md5 = __esm({
26607
26883
  "../node_modules/uuid/dist/esm-node/md5.js"() {
26608
26884
  "use strict";
26609
26885
  init_cjs_shims();
26610
- import_crypto2 = __toESM(require("crypto"));
26886
+ import_crypto3 = __toESM(require("crypto"));
26611
26887
  md5_default = md5;
26612
26888
  }
26613
26889
  });
@@ -26626,14 +26902,14 @@ var init_v3 = __esm({
26626
26902
  });
26627
26903
 
26628
26904
  // ../node_modules/uuid/dist/esm-node/native.js
26629
- var import_crypto3, native_default;
26905
+ var import_crypto4, native_default;
26630
26906
  var init_native = __esm({
26631
26907
  "../node_modules/uuid/dist/esm-node/native.js"() {
26632
26908
  "use strict";
26633
26909
  init_cjs_shims();
26634
- import_crypto3 = __toESM(require("crypto"));
26910
+ import_crypto4 = __toESM(require("crypto"));
26635
26911
  native_default = {
26636
- randomUUID: import_crypto3.default.randomUUID
26912
+ randomUUID: import_crypto4.default.randomUUID
26637
26913
  };
26638
26914
  }
26639
26915
  });
@@ -26675,14 +26951,14 @@ function sha1(bytes) {
26675
26951
  } else if (typeof bytes === "string") {
26676
26952
  bytes = Buffer.from(bytes, "utf8");
26677
26953
  }
26678
- return import_crypto4.default.createHash("sha1").update(bytes).digest();
26954
+ return import_crypto5.default.createHash("sha1").update(bytes).digest();
26679
26955
  }
26680
- var import_crypto4, sha1_default;
26956
+ var import_crypto5, sha1_default;
26681
26957
  var init_sha1 = __esm({
26682
26958
  "../node_modules/uuid/dist/esm-node/sha1.js"() {
26683
26959
  "use strict";
26684
26960
  init_cjs_shims();
26685
- import_crypto4 = __toESM(require("crypto"));
26961
+ import_crypto5 = __toESM(require("crypto"));
26686
26962
  sha1_default = sha1;
26687
26963
  }
26688
26964
  });
@@ -28824,7 +29100,7 @@ load();setInterval(load,5000);
28824
29100
  });
28825
29101
  return callback(null);
28826
29102
  });
28827
- return new Promise((resolve3, reject2) => {
29103
+ return new Promise((resolve4, reject2) => {
28828
29104
  const proxy = this._mitmProxy;
28829
29105
  if (!proxy) {
28830
29106
  reject2(new Error("MITM proxy not initialized"));
@@ -28846,7 +29122,7 @@ load();setInterval(load,5000);
28846
29122
  console.log(`[AgentGate] SSL CA dir: ${caDir}`);
28847
29123
  console.log(`[AgentGate] Set HTTPS_PROXY=http://${this._options.host}:${this._options.port}`);
28848
29124
  this._startDashboard();
28849
- resolve3();
29125
+ resolve4();
28850
29126
  }
28851
29127
  );
28852
29128
  });
@@ -29280,7 +29556,7 @@ var init_coordinator = __esm({
29280
29556
  init_verdict();
29281
29557
  init_repository();
29282
29558
  init_multi_session();
29283
- PhaseCoordinator = class {
29559
+ PhaseCoordinator = class _PhaseCoordinator {
29284
29560
  level;
29285
29561
  mossClient;
29286
29562
  aggregator;
@@ -29299,10 +29575,22 @@ var init_coordinator = __esm({
29299
29575
  cleanupRunning = false;
29300
29576
  /** 低频回顾触发计数(每 N 条落库触发一次 /api/v1/review)。 */
29301
29577
  reviewCounter = 0;
29578
+ // L3 事件风暴护栏:harmony 后端(/proc + inotify)单机每秒可产出上百个事件,
29579
+ // 每个事件同步打一次 moss(有效并发≈1,moss 单进程无队列)。真机实测:
29580
+ // 不设护栏时事件堆积 + 每个 500 重试把 moss/daemon 拖到假死。三道护栏:
29581
+ // 1. 同签名 5s 内去重(同一进程反复 exec/同一文件反复写只分析一次)
29582
+ // 2. 在途上限(超过直接丢弃并计数,不排队)
29583
+ // 3. 丢弃/失败日志限频(每 10s 最多一条),避免日志本身成为 IO 风暴
29584
+ l3Recent = /* @__PURE__ */ new Map();
29585
+ l3Inflight = 0;
29586
+ l3Dropped = 0;
29587
+ l3LastDropLog = 0;
29588
+ static L3_DEDUP_WINDOW_MS = 5e3;
29589
+ static L3_MAX_INFLIGHT = 4;
29302
29590
  constructor(opts = {}) {
29303
29591
  this.level = opts.level ?? 1;
29304
- if (this.level !== 1 && this.level !== 2) {
29305
- throw new Error(`level must be 1 or 2, got ${this.level}`);
29592
+ if (this.level !== 1 && this.level !== 2 && this.level !== 3) {
29593
+ throw new Error(`level must be 1, 2 or 3, got ${this.level}`);
29306
29594
  }
29307
29595
  this.mossClient = opts.mossClient;
29308
29596
  this.aggregator = opts.sessionAggregator;
@@ -29478,21 +29766,57 @@ var init_coordinator = __esm({
29478
29766
  }
29479
29767
  // ── Public API: L3 side (fire-and-forget) ─────────────────────────────────
29480
29768
  async onL3Event(sessionId, event) {
29481
- console.log(
29482
- `[PhaseCoordinator][L3]: standalone L3 event session=${sessionId.slice(0, 8)}`
29483
- );
29484
- if (this.mossClient) {
29485
- try {
29486
- const report = this._buildL3Report(sessionId, event);
29487
- await this._sendToMoss(report);
29488
- console.log(
29489
- `[PhaseCoordinator][L3]: AgentMoss analysis sent (session=${sessionId.slice(0, 8)})`
29769
+ if (!this.mossClient) return;
29770
+ const sig = this._l3Signature(event);
29771
+ const now = Date.now();
29772
+ const last = this.l3Recent.get(sig);
29773
+ if (last !== void 0 && now - last < _PhaseCoordinator.L3_DEDUP_WINDOW_MS) {
29774
+ return;
29775
+ }
29776
+ this.l3Recent.set(sig, now);
29777
+ if (this.l3Recent.size > 2e3) {
29778
+ for (const [k, t] of this.l3Recent) {
29779
+ if (now - t >= _PhaseCoordinator.L3_DEDUP_WINDOW_MS) this.l3Recent.delete(k);
29780
+ }
29781
+ }
29782
+ if (this.l3Inflight >= _PhaseCoordinator.L3_MAX_INFLIGHT) {
29783
+ this.l3Dropped++;
29784
+ if (now - this.l3LastDropLog > 1e4) {
29785
+ this.l3LastDropLog = now;
29786
+ console.warn(
29787
+ `[PhaseCoordinator][L3]: inflight=${this.l3Inflight} \u5DF2\u8FBE\u4E0A\u9650\uFF0C\u4E22\u5F03\u4E8B\u4EF6\u7D2F\u8BA1 ${this.l3Dropped} \u6761`
29490
29788
  );
29491
- } catch (err) {
29789
+ }
29790
+ return;
29791
+ }
29792
+ this.l3Inflight++;
29793
+ try {
29794
+ const report = this._buildL3Report(sessionId, event);
29795
+ const decision = await this._sendToMoss(report);
29796
+ console.log(
29797
+ `[PhaseCoordinator][L3]: ${report.a_next.action_type} \u2192 ${decision} (session=${sessionId.slice(0, 16)})`
29798
+ );
29799
+ } catch (err) {
29800
+ if (Date.now() - this.l3LastDropLog > 1e4) {
29801
+ this.l3LastDropLog = Date.now();
29492
29802
  console.error("[PhaseCoordinator][L3]: AgentMoss request failed:", err);
29493
29803
  }
29804
+ } finally {
29805
+ this.l3Inflight--;
29494
29806
  }
29495
29807
  }
29808
+ /** L3 事件签名:同进程同一动作/同一文件在去重窗口内只分析一次。 */
29809
+ _l3Signature(event) {
29810
+ const p = event.process ?? {};
29811
+ const t = event.target ?? {};
29812
+ const a = event.action ?? {};
29813
+ return [
29814
+ String(event.event_type_name ?? event.event_type ?? ""),
29815
+ String(p.pid ?? event.pid ?? ""),
29816
+ String(a.tool_name ?? a.toolType ?? ""),
29817
+ String(t._command_clean ?? t.command ?? t.argv ?? event.argv ?? t.pathname ?? event.filename ?? "")
29818
+ ].join("|");
29819
+ }
29496
29820
  // ── Phase 2: AgentMoss submission ────────────────────────────────────────
29497
29821
  async executePhase2(sessionId, event, pendingAction) {
29498
29822
  try {
@@ -29509,7 +29833,7 @@ var init_coordinator = __esm({
29509
29833
  event = this.privacyFilter.apply(event);
29510
29834
  }
29511
29835
  if (this.mossClient) {
29512
- const report = this.buildMossReport(session, event, triggerMatches);
29836
+ const report = this.buildMossReport(sessionIdActual, session, event, triggerMatches);
29513
29837
  try {
29514
29838
  const response = await this.mossClient.analyzeSync(report);
29515
29839
  let decision = response.decision ?? "Allow";
@@ -29636,26 +29960,13 @@ var init_coordinator = __esm({
29636
29960
  }
29637
29961
  // ── AgentMoss report building ─────────────────────────────────────────────
29638
29962
  _buildSessionHistory(sessionId) {
29639
- if (!isMultiSessionEnabled()) return [];
29640
- try {
29641
- const recent = queryToolCalls({ limit: 500 });
29642
- const bySession = /* @__PURE__ */ new Map();
29643
- for (const tc of recent) {
29644
- if (tc.session_id === sessionId) continue;
29645
- const list = bySession.get(tc.session_id) || [];
29646
- list.unshift({ action_type: tc.action_type, action_detail: tc.action_detail });
29647
- bySession.set(tc.session_id, list);
29648
- }
29649
- const sessions = [...bySession.entries()].slice(0, 5);
29650
- return sessions.map(([sid, actions]) => ({
29651
- session_id: sid,
29652
- action_history: actions.slice(0, 100)
29653
- }));
29654
- } catch {
29655
- return [];
29656
- }
29963
+ return buildSessionHistory(
29964
+ (params) => queryToolCalls(params),
29965
+ sessionId,
29966
+ () => getAgentsList().map((a) => a.agent_type)
29967
+ );
29657
29968
  }
29658
- buildMossReport(session, event, triggerMatches) {
29969
+ buildMossReport(sessionId, session, event, triggerMatches) {
29659
29970
  const actionHistory = [];
29660
29971
  if (session?.events) {
29661
29972
  for (const evt of session.events) {
@@ -29690,38 +30001,30 @@ var init_coordinator = __esm({
29690
30001
  const currentTarget = event.target ?? {};
29691
30002
  const currentPayload = event.payload ?? {};
29692
30003
  const match0 = triggerMatches[0];
29693
- const sessionDict = session ? {
29694
- id: session.id,
29695
- event_count: session.events.length,
29696
- prompt_count: session.prompts?.length ?? 0,
29697
- inferred_agent_type: event.agentType ?? "unknown"
29698
- } : {};
30004
+ const nextActionType = String(currentAction.toolName ?? currentAction.tool_name ?? "").trim() || "unknown";
30005
+ const nextActionDetail = String(
30006
+ currentTarget.command ?? currentAction.argumentsRaw ?? ""
30007
+ ).slice(0, 2e3);
29699
30008
  return {
29700
30009
  trigger_type: match0?.rule.name ?? "proxy",
29701
30010
  trigger_rule: match0?.rule.name ?? "",
29702
30011
  trigger_detail: match0?.detail ?? "",
29703
- session: sessionDict,
30012
+ session_id: session?.id || sessionId,
30013
+ prompt_session: currentPromptText,
30014
+ prompt_history: promptHistory.map((text) => ({ text, actions: [] })),
29704
30015
  behavior_sequence: [],
29705
30016
  payload_sequences: [],
29706
30017
  action_history: actionHistory,
29707
- session_history: this._buildSessionHistory(session?.id ?? ""),
29708
- prompt_history: promptHistory,
29709
- current_prompt: currentPromptText,
29710
- current_action: {
29711
- tool_name: currentAction.toolName ?? "",
29712
- arguments_raw: currentAction.argumentsRaw ?? "{}",
29713
- tool_call_id: currentAction.toolCallId ?? ""
29714
- },
29715
- current_target: {
29716
- command: currentTarget.command ?? "",
29717
- file_path: currentTarget.filePath ?? "",
29718
- arguments: currentTarget.arguments ?? {}
29719
- },
29720
- prompt: {
29721
- system_prompt: currentPayload.systemPrompt ?? "",
29722
- user_prompt: currentPromptText
30018
+ session_history: this._buildSessionHistory(session?.id || sessionId),
30019
+ a_next: { action_type: nextActionType, action_detail: nextActionDetail },
30020
+ reason: match0?.detail ?? "",
30021
+ os_type: "",
30022
+ cwd: "",
30023
+ agent_id: String(event.agentType ?? event.agent_type ?? ""),
30024
+ metadata: {
30025
+ stateful_incremental: true,
30026
+ ...currentPayload.systemPrompt ? { system_prompt: currentPayload.systemPrompt } : {}
29723
30027
  },
29724
- metadata: { stateful_incremental: true },
29725
30028
  source_layers: event.source_layers ?? ["l1"],
29726
30029
  level: this.level
29727
30030
  };
@@ -29737,7 +30040,7 @@ var init_coordinator = __esm({
29737
30040
  const response = await this.mossClient.analyzeSync(report);
29738
30041
  const decision = response.decision ?? "Allow";
29739
30042
  if (decision === "Deny" && this.onBlock) {
29740
- const shouldBlock = this.onBlock(report.session.id, []);
30043
+ const shouldBlock = this.onBlock(report.session_id, []);
29741
30044
  if (!shouldBlock) {
29742
30045
  return "Allow";
29743
30046
  }
@@ -29785,28 +30088,22 @@ var init_coordinator = __esm({
29785
30088
  trigger_type: "l2_standalone",
29786
30089
  trigger_rule: "l2_standalone",
29787
30090
  trigger_detail: `command: ${action.l2Command}`,
29788
- session: sessionDict,
30091
+ session_id: session?.id || sessionId,
30092
+ prompt_session: currentPromptText,
30093
+ prompt_history: promptHistory.map((text) => ({ text, actions: [] })),
29789
30094
  behavior_sequence: [],
29790
30095
  payload_sequences: [],
29791
30096
  action_history: actionHistory,
29792
- session_history: this._buildSessionHistory(sessionId),
29793
- prompt_history: promptHistory,
29794
- current_prompt: currentPromptText,
29795
- current_action: {
29796
- tool_name: action.toolName,
29797
- arguments_raw: JSON.stringify(action.l2Args ?? []),
29798
- tool_call_id: action.toolCallId
29799
- },
29800
- current_target: {
29801
- command: action.l2Command,
29802
- file_path: "",
29803
- arguments: {}
30097
+ session_history: this._buildSessionHistory(session?.id || sessionId),
30098
+ a_next: {
30099
+ action_type: action.toolName || "unknown",
30100
+ action_detail: String(action.l2Command ?? "").slice(0, 2e3)
29804
30101
  },
29805
- prompt: {
29806
- system_prompt: "",
29807
- user_prompt: currentPromptText
29808
- },
29809
- metadata: { stateful_incremental: true },
30102
+ reason: "",
30103
+ os_type: "",
30104
+ cwd: "",
30105
+ agent_id: "",
30106
+ metadata: { stateful_incremental: true, event_count: sessionDict.event_count ?? 0 },
29810
30107
  source_layers: ["l2"],
29811
30108
  level: this.level
29812
30109
  };
@@ -29848,37 +30145,30 @@ var init_coordinator = __esm({
29848
30145
  }
29849
30146
  const l3Action = event.action ?? {};
29850
30147
  const l3Target = event.target ?? {};
29851
- const sessionDict = session ? {
29852
- id: session.id,
29853
- event_count: session.events.length,
29854
- prompt_count: session.prompts?.length ?? 0,
29855
- inferred_agent_type: event.agentType ?? "unknown"
29856
- } : {};
30148
+ const l3ActionType = String(
30149
+ l3Action.tool_name ?? l3Action.toolName ?? event.event_type_name ?? event.event_type ?? ""
30150
+ ).trim() || "unknown";
30151
+ const l3ActionDetail = String(
30152
+ l3Target._command_clean ?? l3Target.command ?? l3Target.argv ?? event.argv ?? l3Target.pathname ?? event.filename ?? ""
30153
+ ).slice(0, 2e3);
29857
30154
  return {
29858
30155
  trigger_type: "l3_event",
29859
30156
  trigger_rule: "l3_event",
29860
30157
  trigger_detail: `l3: ${JSON.stringify(event).slice(0, 200)}`,
29861
- session: sessionDict,
30158
+ session_id: session?.id || sessionId,
30159
+ prompt_session: currentPromptText,
30160
+ prompt_history: promptHistory.map((text) => ({ text, actions: [] })),
29862
30161
  behavior_sequence: [],
29863
30162
  payload_sequences: [],
29864
30163
  action_history: actionHistory,
29865
- session_history: this._buildSessionHistory(sessionId),
29866
- prompt_history: promptHistory,
29867
- current_prompt: currentPromptText,
29868
- current_action: {
29869
- tool_name: String(l3Action.toolName ?? ""),
29870
- arguments_raw: String(l3Action.argumentsRaw ?? "{}"),
29871
- tool_call_id: String(l3Action.toolCallId ?? "")
29872
- },
29873
- current_target: {
29874
- command: String(l3Target.command ?? ""),
29875
- file_path: String(l3Target.filePath ?? ""),
29876
- arguments: l3Target.arguments ?? {}
29877
- },
29878
- prompt: {
29879
- system_prompt: "",
29880
- user_prompt: currentPromptText
29881
- },
30164
+ session_history: this._buildSessionHistory(session?.id || sessionId),
30165
+ a_next: { action_type: l3ActionType, action_detail: l3ActionDetail },
30166
+ reason: "",
30167
+ os_type: "",
30168
+ cwd: "",
30169
+ agent_id: String(
30170
+ event.process?.agent_type ?? event.agentType ?? event.agent_type ?? ""
30171
+ ),
29882
30172
  metadata: { stateful_incremental: true },
29883
30173
  source_layers: ["l3"],
29884
30174
  level: this.level
@@ -30202,13 +30492,13 @@ var init_server3 = __esm({
30202
30492
  });
30203
30493
  }
30204
30494
  start() {
30205
- return new Promise((resolve3) => {
30495
+ return new Promise((resolve4) => {
30206
30496
  this.server = import_node_http2.default.createServer((req, res) => this.handleRequest(req, res));
30207
30497
  this.server.listen(this.port, this.host, () => {
30208
30498
  console.log(`[Gateway] AgentGate API Gateway listening on ${this.host}:${this.port}`);
30209
30499
  console.log(`[Gateway] Routing: multi-provider (${this.router.routeCount} routes)`);
30210
30500
  console.log(`[Gateway] Dashboard: http://${this.host}:${this.port}`);
30211
- resolve3();
30501
+ resolve4();
30212
30502
  });
30213
30503
  });
30214
30504
  }
@@ -30294,7 +30584,7 @@ var init_server3 = __esm({
30294
30584
  }
30295
30585
  }
30296
30586
  forward(route, body, method, clientHeaders) {
30297
- return new Promise((resolve3, reject2) => {
30587
+ return new Promise((resolve4, reject2) => {
30298
30588
  const url = new import_node_url2.URL(route.upstreamUrl);
30299
30589
  const isHttps = url.protocol === "https:";
30300
30590
  const transport = isHttps ? import_node_https.default : import_node_http2.default;
@@ -30343,7 +30633,7 @@ var init_server3 = __esm({
30343
30633
  respHeaders[key] = Array.isArray(val) ? val.join(", ") : val;
30344
30634
  }
30345
30635
  }
30346
- resolve3({
30636
+ resolve4({
30347
30637
  statusCode: upstreamRes.statusCode ?? 502,
30348
30638
  headers: respHeaders,
30349
30639
  body: respBody
@@ -30436,11 +30726,11 @@ var init_server3 = __esm({
30436
30726
  }
30437
30727
  // ---- Dashboard & API ----
30438
30728
  readBody(req) {
30439
- return new Promise((resolve3) => {
30729
+ return new Promise((resolve4) => {
30440
30730
  const chunks = [];
30441
30731
  req.on("data", (chunk) => chunks.push(chunk));
30442
- req.on("end", () => resolve3(Buffer.concat(chunks)));
30443
- req.on("error", () => resolve3(Buffer.alloc(0)));
30732
+ req.on("end", () => resolve4(Buffer.concat(chunks)));
30733
+ req.on("error", () => resolve4(Buffer.alloc(0)));
30444
30734
  });
30445
30735
  }
30446
30736
  json(res, status, data) {
@@ -32381,7 +32671,7 @@ __export(http_proxy_exports, {
32381
32671
  createHttpProxy: () => createHttpProxy
32382
32672
  });
32383
32673
  function forwardToUpstream(upstreamUrl, msg) {
32384
- return new Promise((resolve3) => {
32674
+ return new Promise((resolve4) => {
32385
32675
  const url = new URL(upstreamUrl);
32386
32676
  const body = JSON.stringify(msg);
32387
32677
  const req = http3.request(
@@ -32401,12 +32691,12 @@ function forwardToUpstream(upstreamUrl, msg) {
32401
32691
  res.setEncoding("utf8");
32402
32692
  res.on("data", (c) => data += c);
32403
32693
  res.on("end", () => {
32404
- resolve3({ status: res.statusCode ?? 500, body: data, contentType: res.headers["content-type"] ?? "" });
32694
+ resolve4({ status: res.statusCode ?? 500, body: data, contentType: res.headers["content-type"] ?? "" });
32405
32695
  });
32406
32696
  }
32407
32697
  );
32408
32698
  req.on("error", () => {
32409
- resolve3({ status: 503, body: "", contentType: "" });
32699
+ resolve4({ status: 503, body: "", contentType: "" });
32410
32700
  });
32411
32701
  req.write(body);
32412
32702
  req.end();
@@ -32474,9 +32764,9 @@ function createHttpProxy(opts) {
32474
32764
  }
32475
32765
  }
32476
32766
  });
32477
- return new Promise((resolve3) => {
32767
+ return new Promise((resolve4) => {
32478
32768
  server.listen(listenPort, listenHost, () => {
32479
- resolve3({
32769
+ resolve4({
32480
32770
  server,
32481
32771
  close: () => new Promise((res) => {
32482
32772
  server.close(() => res());
@@ -32503,7 +32793,7 @@ __export(sse_proxy_exports, {
32503
32793
  rewriteEndpoint: () => rewriteEndpoint
32504
32794
  });
32505
32795
  function postToUpstream(upstreamUrl, msg) {
32506
- return new Promise((resolve3) => {
32796
+ return new Promise((resolve4) => {
32507
32797
  const url = new URL(upstreamUrl);
32508
32798
  const body = JSON.stringify(msg);
32509
32799
  const req = http4.request(
@@ -32522,10 +32812,10 @@ function postToUpstream(upstreamUrl, msg) {
32522
32812
  let data = "";
32523
32813
  res.setEncoding("utf8");
32524
32814
  res.on("data", (c) => data += c);
32525
- res.on("end", () => resolve3({ status: res.statusCode ?? 500, body: data }));
32815
+ res.on("end", () => resolve4({ status: res.statusCode ?? 500, body: data }));
32526
32816
  }
32527
32817
  );
32528
- req.on("error", () => resolve3({ status: 503, body: "" }));
32818
+ req.on("error", () => resolve4({ status: 503, body: "" }));
32529
32819
  req.write(body);
32530
32820
  req.end();
32531
32821
  });
@@ -32546,11 +32836,11 @@ function createSseProxy(opts) {
32546
32836
  Connection: "keep-alive"
32547
32837
  });
32548
32838
  try {
32549
- const upstreamRes = await new Promise((resolve3, reject2) => {
32839
+ const upstreamRes = await new Promise((resolve4, reject2) => {
32550
32840
  const url = new URL(upstreamUrl);
32551
32841
  const ureq = http4.get(
32552
32842
  { host: url.hostname, port: url.port || 80, path: url.pathname + (url.search ?? "") },
32553
- (r) => resolve3(r)
32843
+ (r) => resolve4(r)
32554
32844
  );
32555
32845
  ureq.on("error", reject2);
32556
32846
  });
@@ -32630,9 +32920,9 @@ function createSseProxy(opts) {
32630
32920
  res.writeHead(405);
32631
32921
  res.end("Method Not Allowed");
32632
32922
  });
32633
- return new Promise((resolve3) => {
32923
+ return new Promise((resolve4) => {
32634
32924
  server.listen(listenPort, listenHost, () => {
32635
- resolve3({
32925
+ resolve4({
32636
32926
  server,
32637
32927
  close: () => new Promise((res) => {
32638
32928
  server.close(() => res());
@@ -32798,10 +33088,10 @@ async function scanProcesses() {
32798
33088
  const args = isWin ? ["process", "get", "ProcessId,ParentProcessId,Name,CommandLine", "/format:csv"] : ["-eo", "pid,ppid,comm,args"];
32799
33089
  try {
32800
33090
  const { execFile } = await import("child_process");
32801
- return new Promise((resolve3) => {
33091
+ return new Promise((resolve4) => {
32802
33092
  execFile(cmd, args, { timeout: 5e3 }, (err, stdout) => {
32803
33093
  if (err || !stdout) {
32804
- resolve3([]);
33094
+ resolve4([]);
32805
33095
  return;
32806
33096
  }
32807
33097
  const procs = [];
@@ -32829,7 +33119,7 @@ async function scanProcesses() {
32829
33119
  }
32830
33120
  }
32831
33121
  }
32832
- resolve3(procs);
33122
+ resolve4(procs);
32833
33123
  });
32834
33124
  });
32835
33125
  } catch {
@@ -32855,7 +33145,7 @@ var init_wrapper = __esm({
32855
33145
  this.options = options;
32856
33146
  }
32857
33147
  async run(command, args = []) {
32858
- return new Promise((resolve3, reject2) => {
33148
+ return new Promise((resolve4, reject2) => {
32859
33149
  try {
32860
33150
  console.log(`[PTY] Starting: ${command} ${args.join(" ")}`);
32861
33151
  this.ptyProcess = pty.spawn(command, args, {
@@ -32883,7 +33173,7 @@ var init_wrapper = __esm({
32883
33173
  if (this.options.onExit) {
32884
33174
  this.options.onExit(exitCode, signal);
32885
33175
  }
32886
- resolve3(exitCode);
33176
+ resolve4(exitCode);
32887
33177
  });
32888
33178
  this.startProcessMonitor();
32889
33179
  } catch (error) {
@@ -33278,10 +33568,10 @@ var init_launcher = __esm({
33278
33568
  [AgentGate] CONFIRM: ${toolCall2.toolName} ${cmd}`);
33279
33569
  const readline2 = await import("readline");
33280
33570
  const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
33281
- return new Promise((resolve3) => {
33571
+ return new Promise((resolve4) => {
33282
33572
  rl.question(" Allow this action? [y/N] ", (answer) => {
33283
33573
  rl.close();
33284
- resolve3(answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes");
33574
+ resolve4(answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes");
33285
33575
  });
33286
33576
  });
33287
33577
  }
@@ -34081,6 +34371,19 @@ var path10 = __toESM(require("path"));
34081
34371
  var import_yaml3 = require("yaml");
34082
34372
  init_version();
34083
34373
  var import_node_fetch2 = __toESM(require("node-fetch"));
34374
+ function resolveRulesPath(explicit) {
34375
+ const candidates = [];
34376
+ if (explicit) candidates.push(explicit);
34377
+ const fromEnv = process.env.AGENT_GATE_RULES;
34378
+ if (fromEnv) candidates.push(fromEnv);
34379
+ candidates.push(path10.resolve(__dirname, "..", "config", "trigger_rules.yaml"));
34380
+ candidates.push(path10.resolve(__dirname, "..", "..", "..", "config", "trigger_rules.yaml"));
34381
+ candidates.push(path10.resolve(process.cwd(), "config", "trigger_rules.yaml"));
34382
+ for (const p of candidates) {
34383
+ if ((0, import_node_fs5.existsSync)(p)) return p;
34384
+ }
34385
+ return candidates[0];
34386
+ }
34084
34387
  async function main() {
34085
34388
  const args = process.argv.slice(2);
34086
34389
  const command = args[0];
@@ -34687,6 +34990,7 @@ Usage:
34687
34990
  let logLevel = "info";
34688
34991
  let denyAction = "inform";
34689
34992
  let securityUrl;
34993
+ let rulesPathArg;
34690
34994
  for (let i = 1; i < args.length; i++) {
34691
34995
  if (args[i] === "--level" && args[i + 1]) level = args[++i];
34692
34996
  else if (args[i] === "--upstream" && args[i + 1]) upstream = args[++i];
@@ -34696,6 +35000,7 @@ Usage:
34696
35000
  else if (args[i] === "--log-level" && args[i + 1]) logLevel = args[++i];
34697
35001
  else if (args[i] === "--deny-action" && args[i + 1]) denyAction = args[++i];
34698
35002
  else if (args[i] === "--security-url" && args[i + 1]) securityUrl = args[++i];
35003
+ else if (args[i] === "--rules" && args[i + 1]) rulesPathArg = args[++i];
34699
35004
  }
34700
35005
  const validLevels = ["l1", "l2", "l3", "l1+l2", "l1+l3", "l2+l3", "l1+l2+l3"];
34701
35006
  if (!validLevels.includes(level)) {
@@ -34720,7 +35025,7 @@ Usage:
34720
35025
  }
34721
35026
  }
34722
35027
  }
34723
- const mossUrl2 = process.env.AGENT_MOSS_URL || "http://127.0.0.1:9090";
35028
+ const mossUrl2 = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL || "http://127.0.0.1:9090";
34724
35029
  let mossConnected = false;
34725
35030
  try {
34726
35031
  const resp = await (0, import_node_fetch2.default)(`${mossUrl2}/api/v1/health`, { timeout: 3e3 });
@@ -34769,11 +35074,12 @@ Usage:
34769
35074
  const effectiveMossUrl = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL;
34770
35075
  if (effectiveMossUrl) setMossUrl2(effectiveMossUrl);
34771
35076
  const proxyLevel = hasL2 ? 2 : 1;
34772
- const rulesPath = "../config/trigger_rules.yaml";
35077
+ const rulesPath = resolveRulesPath(rulesPathArg);
34773
35078
  const aggregator = new ProxySessionAggregator2();
34774
35079
  const triggerEngine = new TriggerEngine2(rulesPath);
34775
35080
  const whitelistEngine = new WhitelistEngine2(rulesPath);
34776
35081
  const privacyFilter = new PrivacyFilter2();
35082
+ console.log(`[AgentGate] Trigger rules: ${triggerEngine.rules.length} (${rulesPath})`);
34777
35083
  const coordinator = new PhaseCoordinator2({
34778
35084
  level: proxyLevel,
34779
35085
  mossClient: {
@@ -34872,10 +35178,13 @@ Usage:
34872
35178
  const { TriggerEngine: TriggerEngine2 } = await Promise.resolve().then(() => (init_trigger(), trigger_exports));
34873
35179
  const { WhitelistEngine: WhitelistEngine2 } = await Promise.resolve().then(() => (init_whitelist(), whitelist_exports));
34874
35180
  const { callAgentMoss: callAgentMoss2, setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
34875
- if (securityUrl) setMossUrl2(securityUrl);
35181
+ const effectiveMossUrl = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL;
35182
+ if (effectiveMossUrl) setMossUrl2(effectiveMossUrl);
34876
35183
  const aggregator = new ProxySessionAggregator2();
34877
- const triggerEngine = new TriggerEngine2();
34878
- const whitelistEngine = new WhitelistEngine2();
35184
+ const rulesPath = resolveRulesPath(rulesPathArg);
35185
+ const triggerEngine = new TriggerEngine2(rulesPath);
35186
+ const whitelistEngine = new WhitelistEngine2(rulesPath);
35187
+ console.log(`[AgentGate] Trigger rules: ${triggerEngine.rules.length} (${rulesPath})`);
34879
35188
  const coordinator = new PhaseCoordinator2({
34880
35189
  level: 3,
34881
35190
  mossClient: { analyzeSync: async (report) => callAgentMoss2(report) },