@kenhkl/agent-gate 0.9.0 → 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.9.0" : (() => {
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 {
@@ -842,9 +927,9 @@ var init_json_storage = __esm({
842
927
  const agents = this.loadAgents();
843
928
  let allRecords = [];
844
929
  try {
845
- 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"));
846
931
  for (const file of files) {
847
- const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
932
+ const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
848
933
  allRecords.push(...records);
849
934
  }
850
935
  } catch {
@@ -883,12 +968,12 @@ var init_json_storage = __esm({
883
968
  let jsonFiles = 0;
884
969
  let jsonBytes = 0;
885
970
  try {
886
- 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"));
887
972
  for (const file of files) {
888
- 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));
889
974
  jsonFiles++;
890
975
  jsonBytes += stat.size;
891
- const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
976
+ const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
892
977
  toolCalls += records.length;
893
978
  }
894
979
  } catch {
@@ -898,9 +983,9 @@ var init_json_storage = __esm({
898
983
  clearToolCalls() {
899
984
  let removed = 0;
900
985
  try {
901
- 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"));
902
987
  for (const file of files) {
903
- (0, import_fs.unlinkSync)((0, import_path.join)(this.toolCallsDir, file));
988
+ (0, import_fs2.unlinkSync)((0, import_path2.join)(this.toolCallsDir, file));
904
989
  removed++;
905
990
  }
906
991
  } catch {
@@ -918,6 +1003,49 @@ var init_json_storage = __esm({
918
1003
  hostname: agent?.hostname || ""
919
1004
  };
920
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
+ }
921
1049
  getAgentsList(agentType) {
922
1050
  const agents = this.loadAgents();
923
1051
  const sessions = this.loadSessions();
@@ -952,9 +1080,9 @@ var init_json_storage = __esm({
952
1080
  getTimeline(limit = 100) {
953
1081
  const buckets = /* @__PURE__ */ new Map();
954
1082
  try {
955
- 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"));
956
1084
  for (const file of files) {
957
- const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
1085
+ const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
958
1086
  for (const r of records) {
959
1087
  const minute = r.called_at.replace(/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}):\d{2}/, "$1T$2");
960
1088
  const bucket = buckets.get(minute) || { allow: 0, deny: 0 };
@@ -985,16 +1113,17 @@ __export(sqlite_storage_exports, {
985
1113
  });
986
1114
  function getDefaultDbPath() {
987
1115
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
988
- const xdgData = process.env.XDG_DATA_HOME || (0, import_path2.join)(home, ".local", "share");
989
- 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");
990
1118
  }
991
- var import_fs2, import_path2, SCHEMA, SqliteStorage;
1119
+ var import_fs3, import_path3, SCHEMA, SqliteStorage;
992
1120
  var init_sqlite_storage = __esm({
993
1121
  "src/shared/storage/sqlite-storage.ts"() {
994
1122
  "use strict";
995
1123
  init_cjs_shims();
996
- import_fs2 = require("fs");
997
- import_path2 = require("path");
1124
+ import_fs3 = require("fs");
1125
+ import_path3 = require("path");
1126
+ init_record_guard();
998
1127
  SCHEMA = `
999
1128
  CREATE TABLE IF NOT EXISTS agents (
1000
1129
  id TEXT PRIMARY KEY,
@@ -1054,8 +1183,8 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1054
1183
  );
1055
1184
  }
1056
1185
  const path11 = dbPath || getDefaultDbPath();
1057
- const dir2 = (0, import_path2.dirname)(path11);
1058
- 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 });
1059
1188
  this.dbPath = path11;
1060
1189
  this.db = new Database(path11);
1061
1190
  this.db.pragma("journal_mode = WAL");
@@ -1089,6 +1218,10 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1089
1218
  return row.next;
1090
1219
  }
1091
1220
  insertToolCall(record) {
1221
+ record = prepareRecordForStorage(
1222
+ record,
1223
+ this.dbPath
1224
+ ).record;
1092
1225
  const result = this.db.transaction((rec) => {
1093
1226
  const row = this.db.prepare(
1094
1227
  "SELECT COALESCE(MAX(seq), 0) + 1 as next FROM tool_calls WHERE session_id = ?"
@@ -1229,6 +1362,49 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1229
1362
  })();
1230
1363
  return result;
1231
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
+ }
1232
1408
  getAgentsList(agentType) {
1233
1409
  const where = agentType ? "WHERE a.agent_type = ?" : "";
1234
1410
  return this.db.prepare(`
@@ -1320,12 +1496,12 @@ function getDb(dbPath) {
1320
1496
  try {
1321
1497
  const Database = require("better-sqlite3");
1322
1498
  const { existsSync: existsSync12, mkdirSync: mkdirSync5 } = require("fs");
1323
- const { join: join12, dirname: dirname5 } = require("path");
1499
+ const { join: join12, dirname: dirname6 } = require("path");
1324
1500
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
1325
1501
  const xdgData = process.env.XDG_DATA_HOME || join12(home, ".local", "share");
1326
1502
  const defaultPath = join12(xdgData, "agent_gate", "agent_gate_ts.db");
1327
1503
  const path11 = dbPath || defaultPath;
1328
- const dir2 = dirname5(path11);
1504
+ const dir2 = dirname6(path11);
1329
1505
  if (!existsSync12(dir2)) mkdirSync5(dir2, { recursive: true });
1330
1506
  rawDb = new Database(path11);
1331
1507
  rawDb.pragma("journal_mode = WAL");
@@ -1381,15 +1557,29 @@ function sessionHistoryLimit() {
1381
1557
  const v = Number.isFinite(n) ? n : DEFAULT_MAX_SESSIONS;
1382
1558
  return Math.max(1, Math.min(v, 50));
1383
1559
  }
1384
- function buildSessionHistory(queryToolCalls2, sessionId) {
1560
+ function buildSessionHistory(queryToolCalls2, sessionId, listAgentTypes) {
1385
1561
  if (!isMultiSessionEnabled()) return [];
1386
1562
  const maxSessions = sessionHistoryLimit();
1387
1563
  try {
1388
1564
  const scanLimit = Math.max(DEFAULT_HISTORY_LIMIT, maxSessions * DEFAULT_ACTIONS_PER_SESSION);
1389
- 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
+ }
1390
1576
  const bySession = /* @__PURE__ */ new Map();
1577
+ const sessionAgent = /* @__PURE__ */ new Map();
1391
1578
  for (const tc of recent) {
1392
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
+ }
1393
1583
  const list = bySession.get(tc.session_id) || [];
1394
1584
  list.unshift({
1395
1585
  action_type: tc.action_type,
@@ -1400,6 +1590,7 @@ function buildSessionHistory(queryToolCalls2, sessionId) {
1400
1590
  }
1401
1591
  return [...bySession.entries()].slice(0, maxSessions).map(([sid, actions]) => ({
1402
1592
  session_id: sid,
1593
+ ...sessionAgent.get(sid) ? { agent_id: sessionAgent.get(sid) } : {},
1403
1594
  action_history: actions.slice(0, DEFAULT_ACTIONS_PER_SESSION)
1404
1595
  }));
1405
1596
  } catch {
@@ -1905,7 +2096,9 @@ async function analyzeRoute(c) {
1905
2096
  if (isMultiSessionEnabled()) {
1906
2097
  input.session_history = buildSessionHistory(
1907
2098
  (params) => queryToolCalls(params),
1908
- input.session_id
2099
+ input.session_id,
2100
+ // 多 agent 时按 agent 分组取历史,避免高频 agent 把别人的动作挤出窗口
2101
+ () => getAgentsList().map((a) => a.agent_type)
1909
2102
  );
1910
2103
  }
1911
2104
  const mossRequest = normalize(input, context);
@@ -2193,9 +2386,9 @@ async function dashboardRoute(c) {
2193
2386
  }
2194
2387
  }
2195
2388
  const { readFileSync: readFileSync14, existsSync: existsSync12 } = await import("fs");
2196
- const { resolve: resolve4, dirname: dirname5 } = await import("path");
2389
+ const { resolve: resolve4, dirname: dirname6 } = await import("path");
2197
2390
  const { fileURLToPath } = await import("url");
2198
- const __dirname2 = dirname5(fileURLToPath(importMetaUrl));
2391
+ const __dirname2 = dirname6(fileURLToPath(importMetaUrl));
2199
2392
  const paths = [
2200
2393
  resolve4(__dirname2, "dashboard.html"),
2201
2394
  resolve4(__dirname2, "../dashboard.html"),
@@ -6366,7 +6559,7 @@ var require_websocket = __commonJS({
6366
6559
  var http5 = require("http");
6367
6560
  var net2 = require("net");
6368
6561
  var tls = require("tls");
6369
- var { randomBytes: randomBytes2, createHash: createHash4 } = require("crypto");
6562
+ var { randomBytes: randomBytes2, createHash: createHash5 } = require("crypto");
6370
6563
  var { Duplex, Readable } = require("stream");
6371
6564
  var { URL: URL5 } = require("url");
6372
6565
  var PerMessageDeflate = require_permessage_deflate();
@@ -7034,7 +7227,7 @@ var require_websocket = __commonJS({
7034
7227
  abortHandshake(websocket, socket, "Invalid Upgrade header");
7035
7228
  return;
7036
7229
  }
7037
- const digest = createHash4("sha1").update(key + GUID).digest("base64");
7230
+ const digest = createHash5("sha1").update(key + GUID).digest("base64");
7038
7231
  if (res.headers["sec-websocket-accept"] !== digest) {
7039
7232
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
7040
7233
  return;
@@ -7406,7 +7599,7 @@ var require_websocket_server = __commonJS({
7406
7599
  var EventEmitter2 = require("events");
7407
7600
  var http5 = require("http");
7408
7601
  var { Duplex } = require("stream");
7409
- var { createHash: createHash4 } = require("crypto");
7602
+ var { createHash: createHash5 } = require("crypto");
7410
7603
  var extension = require_extension();
7411
7604
  var PerMessageDeflate = require_permessage_deflate();
7412
7605
  var subprotocol = require_subprotocol();
@@ -7713,7 +7906,7 @@ var require_websocket_server = __commonJS({
7713
7906
  );
7714
7907
  }
7715
7908
  if (this._state > RUNNING) return abortHandshake(socket, 503);
7716
- const digest = createHash4("sha1").update(key + GUID).digest("base64");
7909
+ const digest = createHash5("sha1").update(key + GUID).digest("base64");
7717
7910
  const headers = [
7718
7911
  "HTTP/1.1 101 Switching Protocols",
7719
7912
  "Upgrade: websocket",
@@ -25894,14 +26087,14 @@ var require_find_made = __commonJS({
25894
26087
  "../node_modules/mkdirp/lib/find-made.js"(exports2, module2) {
25895
26088
  "use strict";
25896
26089
  init_cjs_shims();
25897
- var { dirname: dirname5 } = require("path");
26090
+ var { dirname: dirname6 } = require("path");
25898
26091
  var findMade = (opts, parent2, path11 = void 0) => {
25899
26092
  if (path11 === parent2)
25900
26093
  return Promise.resolve();
25901
26094
  return opts.statAsync(parent2).then(
25902
26095
  (st) => st.isDirectory() ? path11 : void 0,
25903
26096
  // will fail later
25904
- (er) => er.code === "ENOENT" ? findMade(opts, dirname5(parent2), parent2) : void 0
26097
+ (er) => er.code === "ENOENT" ? findMade(opts, dirname6(parent2), parent2) : void 0
25905
26098
  );
25906
26099
  };
25907
26100
  var findMadeSync = (opts, parent2, path11 = void 0) => {
@@ -25910,7 +26103,7 @@ var require_find_made = __commonJS({
25910
26103
  try {
25911
26104
  return opts.statSync(parent2).isDirectory() ? path11 : void 0;
25912
26105
  } catch (er) {
25913
- return er.code === "ENOENT" ? findMadeSync(opts, dirname5(parent2), parent2) : void 0;
26106
+ return er.code === "ENOENT" ? findMadeSync(opts, dirname6(parent2), parent2) : void 0;
25914
26107
  }
25915
26108
  };
25916
26109
  module2.exports = { findMade, findMadeSync };
@@ -25922,10 +26115,10 @@ var require_mkdirp_manual = __commonJS({
25922
26115
  "../node_modules/mkdirp/lib/mkdirp-manual.js"(exports2, module2) {
25923
26116
  "use strict";
25924
26117
  init_cjs_shims();
25925
- var { dirname: dirname5 } = require("path");
26118
+ var { dirname: dirname6 } = require("path");
25926
26119
  var mkdirpManual = (path11, opts, made) => {
25927
26120
  opts.recursive = false;
25928
- const parent2 = dirname5(path11);
26121
+ const parent2 = dirname6(path11);
25929
26122
  if (parent2 === path11) {
25930
26123
  return opts.mkdirAsync(path11, opts).catch((er) => {
25931
26124
  if (er.code !== "EISDIR")
@@ -25948,7 +26141,7 @@ var require_mkdirp_manual = __commonJS({
25948
26141
  });
25949
26142
  };
25950
26143
  var mkdirpManualSync = (path11, opts, made) => {
25951
- const parent2 = dirname5(path11);
26144
+ const parent2 = dirname6(path11);
25952
26145
  opts.recursive = false;
25953
26146
  if (parent2 === path11) {
25954
26147
  try {
@@ -25985,12 +26178,12 @@ var require_mkdirp_native = __commonJS({
25985
26178
  "../node_modules/mkdirp/lib/mkdirp-native.js"(exports2, module2) {
25986
26179
  "use strict";
25987
26180
  init_cjs_shims();
25988
- var { dirname: dirname5 } = require("path");
26181
+ var { dirname: dirname6 } = require("path");
25989
26182
  var { findMade, findMadeSync } = require_find_made();
25990
26183
  var { mkdirpManual, mkdirpManualSync } = require_mkdirp_manual();
25991
26184
  var mkdirpNative = (path11, opts) => {
25992
26185
  opts.recursive = true;
25993
- const parent2 = dirname5(path11);
26186
+ const parent2 = dirname6(path11);
25994
26187
  if (parent2 === path11)
25995
26188
  return opts.mkdirAsync(path11, opts);
25996
26189
  return findMade(opts, path11).then((made) => opts.mkdirAsync(path11, opts).then(() => made).catch((er) => {
@@ -26002,7 +26195,7 @@ var require_mkdirp_native = __commonJS({
26002
26195
  };
26003
26196
  var mkdirpNativeSync = (path11, opts) => {
26004
26197
  opts.recursive = true;
26005
- const parent2 = dirname5(path11);
26198
+ const parent2 = dirname6(path11);
26006
26199
  if (parent2 === path11)
26007
26200
  return opts.mkdirSync(path11, opts);
26008
26201
  const made = findMadeSync(opts, path11);
@@ -26458,17 +26651,17 @@ var require_ProxyFinalRequestFilter = __commonJS({
26458
26651
  // ../node_modules/uuid/dist/esm-node/rng.js
26459
26652
  function rng() {
26460
26653
  if (poolPtr > rnds8Pool.length - 16) {
26461
- import_crypto.default.randomFillSync(rnds8Pool);
26654
+ import_crypto2.default.randomFillSync(rnds8Pool);
26462
26655
  poolPtr = 0;
26463
26656
  }
26464
26657
  return rnds8Pool.slice(poolPtr, poolPtr += 16);
26465
26658
  }
26466
- var import_crypto, rnds8Pool, poolPtr;
26659
+ var import_crypto2, rnds8Pool, poolPtr;
26467
26660
  var init_rng = __esm({
26468
26661
  "../node_modules/uuid/dist/esm-node/rng.js"() {
26469
26662
  "use strict";
26470
26663
  init_cjs_shims();
26471
- import_crypto = __toESM(require("crypto"));
26664
+ import_crypto2 = __toESM(require("crypto"));
26472
26665
  rnds8Pool = new Uint8Array(256);
26473
26666
  poolPtr = rnds8Pool.length;
26474
26667
  }
@@ -26683,14 +26876,14 @@ function md5(bytes) {
26683
26876
  } else if (typeof bytes === "string") {
26684
26877
  bytes = Buffer.from(bytes, "utf8");
26685
26878
  }
26686
- return import_crypto2.default.createHash("md5").update(bytes).digest();
26879
+ return import_crypto3.default.createHash("md5").update(bytes).digest();
26687
26880
  }
26688
- var import_crypto2, md5_default;
26881
+ var import_crypto3, md5_default;
26689
26882
  var init_md5 = __esm({
26690
26883
  "../node_modules/uuid/dist/esm-node/md5.js"() {
26691
26884
  "use strict";
26692
26885
  init_cjs_shims();
26693
- import_crypto2 = __toESM(require("crypto"));
26886
+ import_crypto3 = __toESM(require("crypto"));
26694
26887
  md5_default = md5;
26695
26888
  }
26696
26889
  });
@@ -26709,14 +26902,14 @@ var init_v3 = __esm({
26709
26902
  });
26710
26903
 
26711
26904
  // ../node_modules/uuid/dist/esm-node/native.js
26712
- var import_crypto3, native_default;
26905
+ var import_crypto4, native_default;
26713
26906
  var init_native = __esm({
26714
26907
  "../node_modules/uuid/dist/esm-node/native.js"() {
26715
26908
  "use strict";
26716
26909
  init_cjs_shims();
26717
- import_crypto3 = __toESM(require("crypto"));
26910
+ import_crypto4 = __toESM(require("crypto"));
26718
26911
  native_default = {
26719
- randomUUID: import_crypto3.default.randomUUID
26912
+ randomUUID: import_crypto4.default.randomUUID
26720
26913
  };
26721
26914
  }
26722
26915
  });
@@ -26758,14 +26951,14 @@ function sha1(bytes) {
26758
26951
  } else if (typeof bytes === "string") {
26759
26952
  bytes = Buffer.from(bytes, "utf8");
26760
26953
  }
26761
- return import_crypto4.default.createHash("sha1").update(bytes).digest();
26954
+ return import_crypto5.default.createHash("sha1").update(bytes).digest();
26762
26955
  }
26763
- var import_crypto4, sha1_default;
26956
+ var import_crypto5, sha1_default;
26764
26957
  var init_sha1 = __esm({
26765
26958
  "../node_modules/uuid/dist/esm-node/sha1.js"() {
26766
26959
  "use strict";
26767
26960
  init_cjs_shims();
26768
- import_crypto4 = __toESM(require("crypto"));
26961
+ import_crypto5 = __toESM(require("crypto"));
26769
26962
  sha1_default = sha1;
26770
26963
  }
26771
26964
  });
@@ -29767,24 +29960,11 @@ var init_coordinator = __esm({
29767
29960
  }
29768
29961
  // ── AgentMoss report building ─────────────────────────────────────────────
29769
29962
  _buildSessionHistory(sessionId) {
29770
- if (!isMultiSessionEnabled()) return [];
29771
- try {
29772
- const recent = queryToolCalls({ limit: 500 });
29773
- const bySession = /* @__PURE__ */ new Map();
29774
- for (const tc of recent) {
29775
- if (tc.session_id === sessionId) continue;
29776
- const list = bySession.get(tc.session_id) || [];
29777
- list.unshift({ action_type: tc.action_type, action_detail: tc.action_detail });
29778
- bySession.set(tc.session_id, list);
29779
- }
29780
- const sessions = [...bySession.entries()].slice(0, 5);
29781
- return sessions.map(([sid, actions]) => ({
29782
- session_id: sid,
29783
- action_history: actions.slice(0, 100)
29784
- }));
29785
- } catch {
29786
- return [];
29787
- }
29963
+ return buildSessionHistory(
29964
+ (params) => queryToolCalls(params),
29965
+ sessionId,
29966
+ () => getAgentsList().map((a) => a.agent_type)
29967
+ );
29788
29968
  }
29789
29969
  buildMossReport(sessionId, session, event, triggerMatches) {
29790
29970
  const actionHistory = [];