@kenhkl/agent-gate 0.9.2 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/v1/server.js CHANGED
@@ -40,6 +40,46 @@ var init_cjs_shims = __esm({
40
40
  }
41
41
  });
42
42
 
43
+ // src/shared/instance-id.ts
44
+ function getInstanceId() {
45
+ if (cached) return cached;
46
+ const env2 = (process.env.AGENT_GATE_INSTANCE_ID || "").trim();
47
+ if (env2) {
48
+ cached = env2;
49
+ return cached;
50
+ }
51
+ const filePath = process.env.AGENT_GATE_INSTANCE_ID_PATH || (0, import_path.join)((0, import_os.homedir)(), ".config", "agentgate", "instance_id");
52
+ try {
53
+ if ((0, import_fs.existsSync)(filePath)) {
54
+ const v2 = (0, import_fs.readFileSync)(filePath, "utf-8").trim();
55
+ if (v2) {
56
+ cached = v2;
57
+ return cached;
58
+ }
59
+ }
60
+ const v = (0, import_crypto.randomUUID)();
61
+ (0, import_fs.mkdirSync)((0, import_path.dirname)(filePath), { recursive: true });
62
+ (0, import_fs.writeFileSync)(filePath, v + "\n", { mode: 384 });
63
+ cached = v;
64
+ return cached;
65
+ } catch {
66
+ cached = `ephemeral-${(0, import_crypto.randomUUID)()}`;
67
+ return cached;
68
+ }
69
+ }
70
+ var import_fs, import_os, import_path, import_crypto, cached;
71
+ var init_instance_id = __esm({
72
+ "src/shared/instance-id.ts"() {
73
+ "use strict";
74
+ init_cjs_shims();
75
+ import_fs = require("fs");
76
+ import_os = require("os");
77
+ import_path = require("path");
78
+ import_crypto = require("crypto");
79
+ cached = "";
80
+ }
81
+ });
82
+
43
83
  // src/shared/multi-session.ts
44
84
  function isMultiSessionEnabled() {
45
85
  const raw = (process.env.AGENT_GATE_MULTI_SESSION ?? "").trim().toLowerCase();
@@ -86,6 +126,9 @@ function buildSessionHistory(queryToolCalls2, sessionId, listAgentTypes) {
86
126
  return [...bySession.entries()].slice(0, maxSessions).map(([sid, actions]) => ({
87
127
  session_id: sid,
88
128
  ...sessionAgent.get(sid) ? { agent_id: sessionAgent.get(sid) } : {},
129
+ // AgentGate 自己的存储属于本安装实例;带上实例 ID 让 AgentMoss 在
130
+ // 展示层按「同实例不隐藏」处理(否则用户自己的历史会话也会被脱敏)。
131
+ instance_id: getInstanceId(),
89
132
  action_history: actions.slice(0, DEFAULT_ACTIONS_PER_SESSION)
90
133
  }));
91
134
  } catch {
@@ -100,6 +143,7 @@ var init_multi_session = __esm({
100
143
  "src/shared/multi-session.ts"() {
101
144
  "use strict";
102
145
  init_cjs_shims();
146
+ init_instance_id();
103
147
  DEFAULT_HISTORY_LIMIT = 500;
104
148
  DEFAULT_MAX_SESSIONS = 5;
105
149
  DEFAULT_ACTIONS_PER_SESSION = 100;
@@ -186,8 +230,8 @@ function readFdToken() {
186
230
  if (!raw) return "";
187
231
  const fd = parseInt(raw, 10);
188
232
  if (!Number.isFinite(fd)) return "";
189
- const cached = fdTokenCache.get(fd);
190
- if (cached !== void 0) return cached;
233
+ const cached2 = fdTokenCache.get(fd);
234
+ if (cached2 !== void 0) return cached2;
191
235
  try {
192
236
  const buf = Buffer.alloc(8192);
193
237
  const n = (0, import_node_fs.readSync)(fd, buf, 0, buf.length, null);
@@ -392,7 +436,7 @@ function agentInflight() {
392
436
  return envInt("AGENT_GATE_MAX_AGENT_INFLIGHT", 8);
393
437
  }
394
438
  function bump(kind, key, windowSec, extra) {
395
- const now = Date.now() / 1e3;
439
+ const now = performance.now() / 1e3;
396
440
  const k = `${kind}|${key}`;
397
441
  let b = counters.get(k);
398
442
  if (!b || now - b.start >= windowSec) {
@@ -438,7 +482,7 @@ function mossTokenPath() {
438
482
  return (0, import_node_path.join)(home, ".config", "agentmoss", "auth_token");
439
483
  }
440
484
  function resolveMossToken(force = false) {
441
- const now = Date.now() / 1e3;
485
+ const now = performance.now() / 1e3;
442
486
  if (!force && mossTokenCache.expires > now) return mossTokenCache.value;
443
487
  let tok = env("AGENT_GATE_MOSS_TOKEN");
444
488
  if (!tok) tok = env("AGENT_MOSS_AUTH_TOKEN");
@@ -500,7 +544,7 @@ var init_security = __esm({
500
544
  return this.qps > 0;
501
545
  }
502
546
  allow(key) {
503
- const now = Date.now() / 1e3;
547
+ const now = performance.now() / 1e3;
504
548
  const cur = this.buckets.get(key) ?? { tokens: this.burst, last: now };
505
549
  const tokens = Math.min(this.burst, cur.tokens + (now - cur.last) * this.qps);
506
550
  if (tokens < 1) {
@@ -648,12 +692,12 @@ function clipText(value, limit = maxRecordBytes()) {
648
692
  const s = String(value ?? "");
649
693
  if (limit <= 0 || s.length <= limit) return s;
650
694
  const head = s.slice(0, limit);
651
- const digest = (0, import_crypto.createHash)("sha256").update(s).digest("hex").slice(0, 16);
695
+ const digest = (0, import_crypto2.createHash)("sha256").update(s).digest("hex").slice(0, 16);
652
696
  return `${head}\u2026[truncated ${s.length - limit}B sha256:${digest}]`;
653
697
  }
654
698
  function diskFreePercent(targetPath) {
655
699
  try {
656
- const st = (0, import_fs.statfsSync)((0, import_path.dirname)(targetPath));
700
+ const st = (0, import_fs2.statfsSync)((0, import_path2.dirname)(targetPath));
657
701
  const total = Number(st.blocks) || 0;
658
702
  const avail = Number(st.bavail) || 0;
659
703
  if (!total) return 100;
@@ -690,14 +734,14 @@ function prepareRecordForStorage(rec, targetPath) {
690
734
  if (degraded) out = degradeRecord(out);
691
735
  return { record: out, degraded };
692
736
  }
693
- var import_crypto, import_fs, import_path, DEGRADE_COMMAND_BYTES;
737
+ var import_crypto2, import_fs2, import_path2, DEGRADE_COMMAND_BYTES;
694
738
  var init_record_guard = __esm({
695
739
  "src/shared/storage/record-guard.ts"() {
696
740
  "use strict";
697
741
  init_cjs_shims();
698
- import_crypto = require("crypto");
699
- import_fs = require("fs");
700
- import_path = require("path");
742
+ import_crypto2 = require("crypto");
743
+ import_fs2 = require("fs");
744
+ import_path2 = require("path");
701
745
  init_security();
702
746
  DEGRADE_COMMAND_BYTES = 512;
703
747
  }
@@ -713,16 +757,16 @@ function nowISO() {
713
757
  }
714
758
  function getDefaultDataDir() {
715
759
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
716
- const xdgData = process.env.XDG_DATA_HOME || (0, import_path2.join)(home, ".local", "share");
717
- return (0, import_path2.join)(xdgData, "agent_gate", "storage");
760
+ const xdgData = process.env.XDG_DATA_HOME || (0, import_path3.join)(home, ".local", "share");
761
+ return (0, import_path3.join)(xdgData, "agent_gate", "storage");
718
762
  }
719
- var import_fs2, import_path2, JsonStorage;
763
+ var import_fs3, import_path3, JsonStorage;
720
764
  var init_json_storage = __esm({
721
765
  "src/shared/storage/json-storage.ts"() {
722
766
  "use strict";
723
767
  init_cjs_shims();
724
- import_fs2 = require("fs");
725
- import_path2 = require("path");
768
+ import_fs3 = require("fs");
769
+ import_path3 = require("path");
726
770
  init_security();
727
771
  init_record_guard();
728
772
  JsonStorage = class {
@@ -737,11 +781,11 @@ var init_json_storage = __esm({
737
781
  sessionLocks = /* @__PURE__ */ new Map();
738
782
  constructor(dataDir) {
739
783
  this.dataDir = dataDir || process.env.AGENT_GATE_DATA_DIR || getDefaultDataDir();
740
- this.agentsPath = (0, import_path2.join)(this.dataDir, "agents.json");
741
- this.sessionsPath = (0, import_path2.join)(this.dataDir, "sessions.json");
742
- this.toolCallsDir = (0, import_path2.join)(this.dataDir, "tool_calls");
743
- if (!(0, import_fs2.existsSync)(this.dataDir)) (0, import_fs2.mkdirSync)(this.dataDir, { recursive: true, mode: 448 });
744
- if (!(0, import_fs2.existsSync)(this.toolCallsDir)) (0, import_fs2.mkdirSync)(this.toolCallsDir, { recursive: true, mode: 448 });
784
+ this.agentsPath = (0, import_path3.join)(this.dataDir, "agents.json");
785
+ this.sessionsPath = (0, import_path3.join)(this.dataDir, "sessions.json");
786
+ this.toolCallsDir = (0, import_path3.join)(this.dataDir, "tool_calls");
787
+ if (!(0, import_fs3.existsSync)(this.dataDir)) (0, import_fs3.mkdirSync)(this.dataDir, { recursive: true, mode: 448 });
788
+ if (!(0, import_fs3.existsSync)(this.toolCallsDir)) (0, import_fs3.mkdirSync)(this.toolCallsDir, { recursive: true, mode: 448 });
745
789
  this.hardenStoragePermissions();
746
790
  this.nextId = this.recoverNextId();
747
791
  }
@@ -753,10 +797,10 @@ var init_json_storage = __esm({
753
797
  const uid = process.getuid?.();
754
798
  const tighten = (p, mode) => {
755
799
  try {
756
- const st = (0, import_fs2.statSync)(p);
800
+ const st = (0, import_fs3.statSync)(p);
757
801
  if (st.isSymbolicLink()) return;
758
802
  if (uid !== void 0 && st.uid !== uid) return;
759
- if ((st.mode & 511) !== mode) (0, import_fs2.chmodSync)(p, mode);
803
+ if ((st.mode & 511) !== mode) (0, import_fs3.chmodSync)(p, mode);
760
804
  } catch {
761
805
  }
762
806
  };
@@ -765,9 +809,9 @@ var init_json_storage = __esm({
765
809
  tighten(this.agentsPath, 384);
766
810
  tighten(this.sessionsPath, 384);
767
811
  try {
768
- for (const f of (0, import_fs2.readdirSync)(this.toolCallsDir)) {
812
+ for (const f of (0, import_fs3.readdirSync)(this.toolCallsDir)) {
769
813
  if (f.endsWith(".json") || f.endsWith(".tmp")) {
770
- tighten((0, import_path2.join)(this.toolCallsDir, f), 384);
814
+ tighten((0, import_path3.join)(this.toolCallsDir, f), 384);
771
815
  }
772
816
  }
773
817
  } catch {
@@ -777,9 +821,9 @@ var init_json_storage = __esm({
777
821
  recoverNextId() {
778
822
  let maxId = 0;
779
823
  try {
780
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
824
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
781
825
  for (const file of files) {
782
- const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
826
+ const records = this.readJsonFile((0, import_path3.join)(this.toolCallsDir, file), []);
783
827
  for (const r of records) {
784
828
  if (r.id > maxId) maxId = r.id;
785
829
  }
@@ -790,19 +834,19 @@ var init_json_storage = __esm({
790
834
  }
791
835
  readJsonFile(path, fallback) {
792
836
  try {
793
- if (!(0, import_fs2.existsSync)(path)) return fallback;
794
- return JSON.parse((0, import_fs2.readFileSync)(path, "utf-8"));
837
+ if (!(0, import_fs3.existsSync)(path)) return fallback;
838
+ return JSON.parse((0, import_fs3.readFileSync)(path, "utf-8"));
795
839
  } catch {
796
840
  return fallback;
797
841
  }
798
842
  }
799
843
  /** 原子写入:先写 .tmp 再 rename(rename 保留 tmp 的 0600 权限) */
800
844
  writeJsonFile(path, data) {
801
- const dir = (0, import_path2.dirname)(path);
802
- if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true, mode: 448 });
845
+ const dir = (0, import_path3.dirname)(path);
846
+ if (!(0, import_fs3.existsSync)(dir)) (0, import_fs3.mkdirSync)(dir, { recursive: true, mode: 448 });
803
847
  const tmp = path + ".tmp";
804
- (0, import_fs2.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
805
- (0, import_fs2.renameSync)(tmp, path);
848
+ (0, import_fs3.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
849
+ (0, import_fs3.renameSync)(tmp, path);
806
850
  }
807
851
  loadAgents() {
808
852
  const raw = this.readJsonFile(this.agentsPath, {});
@@ -820,12 +864,12 @@ var init_json_storage = __esm({
820
864
  }
821
865
  loadToolCalls(sessionId) {
822
866
  return this.readJsonFile(
823
- (0, import_path2.join)(this.toolCallsDir, `${sessionId}.json`),
867
+ (0, import_path3.join)(this.toolCallsDir, `${sessionId}.json`),
824
868
  []
825
869
  );
826
870
  }
827
871
  saveToolCalls(sessionId, records) {
828
- this.writeJsonFile((0, import_path2.join)(this.toolCallsDir, `${sessionId}.json`), records);
872
+ this.writeJsonFile((0, import_path3.join)(this.toolCallsDir, `${sessionId}.json`), records);
829
873
  }
830
874
  getOrCreateAgent(agentType, hostname, version2 = "") {
831
875
  const agents = this.loadAgents();
@@ -911,9 +955,9 @@ var init_json_storage = __esm({
911
955
  allRecords = records.map((r) => this.enrichRecord(r, sessions, agents));
912
956
  } else {
913
957
  try {
914
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
958
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
915
959
  for (const file of files) {
916
- const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
960
+ const records = this.readJsonFile((0, import_path3.join)(this.toolCallsDir, file), []);
917
961
  allRecords.push(...records.map((r) => this.enrichRecord(r, sessions, agents)));
918
962
  }
919
963
  } catch {
@@ -947,9 +991,9 @@ var init_json_storage = __esm({
947
991
  const agents = this.loadAgents();
948
992
  let allRecords = [];
949
993
  try {
950
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
994
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
951
995
  for (const file of files) {
952
- const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
996
+ const records = this.readJsonFile((0, import_path3.join)(this.toolCallsDir, file), []);
953
997
  allRecords.push(...records);
954
998
  }
955
999
  } catch {
@@ -988,12 +1032,12 @@ var init_json_storage = __esm({
988
1032
  let jsonFiles = 0;
989
1033
  let jsonBytes = 0;
990
1034
  try {
991
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
1035
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
992
1036
  for (const file of files) {
993
- const stat = (0, import_fs2.statSync)((0, import_path2.join)(this.toolCallsDir, file));
1037
+ const stat = (0, import_fs3.statSync)((0, import_path3.join)(this.toolCallsDir, file));
994
1038
  jsonFiles++;
995
1039
  jsonBytes += stat.size;
996
- const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
1040
+ const records = this.readJsonFile((0, import_path3.join)(this.toolCallsDir, file), []);
997
1041
  toolCalls += records.length;
998
1042
  }
999
1043
  } catch {
@@ -1003,9 +1047,9 @@ var init_json_storage = __esm({
1003
1047
  clearToolCalls() {
1004
1048
  let removed = 0;
1005
1049
  try {
1006
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
1050
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
1007
1051
  for (const file of files) {
1008
- (0, import_fs2.unlinkSync)((0, import_path2.join)(this.toolCallsDir, file));
1052
+ (0, import_fs3.unlinkSync)((0, import_path3.join)(this.toolCallsDir, file));
1009
1053
  removed++;
1010
1054
  }
1011
1055
  } catch {
@@ -1029,10 +1073,10 @@ var init_json_storage = __esm({
1029
1073
  * 再从各自的 session 文件里移除。数据不丢,只是不在主目录了。
1030
1074
  */
1031
1075
  archiveOldRecords(keep) {
1032
- if (keep <= 0 || !(0, import_fs2.existsSync)(this.toolCallsDir)) return { archived: 0, file: "" };
1076
+ if (keep <= 0 || !(0, import_fs3.existsSync)(this.toolCallsDir)) return { archived: 0, file: "" };
1033
1077
  const bySession = /* @__PURE__ */ new Map();
1034
1078
  let total = 0;
1035
- for (const f of (0, import_fs2.readdirSync)(this.toolCallsDir)) {
1079
+ for (const f of (0, import_fs3.readdirSync)(this.toolCallsDir)) {
1036
1080
  if (!f.endsWith(".json")) continue;
1037
1081
  const sid = f.slice(0, -".json".length);
1038
1082
  const recs = this.loadToolCalls(sid);
@@ -1048,15 +1092,15 @@ var init_json_storage = __esm({
1048
1092
  const archiveCount = total - keep;
1049
1093
  const toArchive = flat.slice(0, archiveCount);
1050
1094
  const archiveIds = new Set(toArchive.map((x) => String(x.rec.id)));
1051
- const { mkdirSync: mkdirSync4, writeFileSync: writeFileSync3 } = require("fs");
1052
- const { join: join4 } = require("path");
1095
+ const { mkdirSync: mkdirSync5, writeFileSync: writeFileSync4 } = require("fs");
1096
+ const { join: join5 } = require("path");
1053
1097
  const { gzipSync } = require("zlib");
1054
- const archiveDir = join4(this.dataDir, "archive");
1055
- if (!(0, import_fs2.existsSync)(archiveDir)) mkdirSync4(archiveDir, { recursive: true, mode: 448 });
1098
+ const archiveDir = join5(this.dataDir, "archive");
1099
+ if (!(0, import_fs3.existsSync)(archiveDir)) mkdirSync5(archiveDir, { recursive: true, mode: 448 });
1056
1100
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
1057
- const file = join4(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
1101
+ const file = join5(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
1058
1102
  const payload = toArchive.map((x) => JSON.stringify(x.rec)).join("\n") + "\n";
1059
- writeFileSync3(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
1103
+ writeFileSync4(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
1060
1104
  for (const [sid, recs] of bySession) {
1061
1105
  const remain = recs.filter((r) => !archiveIds.has(String(r.id)));
1062
1106
  if (remain.length !== recs.length) this.saveToolCalls(sid, remain);
@@ -1100,9 +1144,9 @@ var init_json_storage = __esm({
1100
1144
  getTimeline(limit = 100) {
1101
1145
  const buckets = /* @__PURE__ */ new Map();
1102
1146
  try {
1103
- const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
1147
+ const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
1104
1148
  for (const file of files) {
1105
- const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
1149
+ const records = this.readJsonFile((0, import_path3.join)(this.toolCallsDir, file), []);
1106
1150
  for (const r of records) {
1107
1151
  const minute = r.called_at.replace(/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}):\d{2}/, "$1T$2");
1108
1152
  const bucket = buckets.get(minute) || { allow: 0, deny: 0 };
@@ -1133,16 +1177,16 @@ __export(sqlite_storage_exports, {
1133
1177
  });
1134
1178
  function getDefaultDbPath() {
1135
1179
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
1136
- const xdgData = process.env.XDG_DATA_HOME || (0, import_path3.join)(home, ".local", "share");
1137
- return (0, import_path3.join)(xdgData, "agent_gate", "agent_gate_ts.db");
1180
+ const xdgData = process.env.XDG_DATA_HOME || (0, import_path4.join)(home, ".local", "share");
1181
+ return (0, import_path4.join)(xdgData, "agent_gate", "agent_gate_ts.db");
1138
1182
  }
1139
- var import_fs3, import_path3, SCHEMA, SqliteStorage;
1183
+ var import_fs4, import_path4, SCHEMA, SqliteStorage;
1140
1184
  var init_sqlite_storage = __esm({
1141
1185
  "src/shared/storage/sqlite-storage.ts"() {
1142
1186
  "use strict";
1143
1187
  init_cjs_shims();
1144
- import_fs3 = require("fs");
1145
- import_path3 = require("path");
1188
+ import_fs4 = require("fs");
1189
+ import_path4 = require("path");
1146
1190
  init_record_guard();
1147
1191
  SCHEMA = `
1148
1192
  CREATE TABLE IF NOT EXISTS agents (
@@ -1204,8 +1248,8 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1204
1248
  );
1205
1249
  }
1206
1250
  const path = dbPath || getDefaultDbPath();
1207
- const dir = (0, import_path3.dirname)(path);
1208
- if (!(0, import_fs3.existsSync)(dir)) (0, import_fs3.mkdirSync)(dir, { recursive: true });
1251
+ const dir = (0, import_path4.dirname)(path);
1252
+ if (!(0, import_fs4.existsSync)(dir)) (0, import_fs4.mkdirSync)(dir, { recursive: true });
1209
1253
  this.dbPath = path;
1210
1254
  this.db = new Database(path);
1211
1255
  this.db.pragma("journal_mode = WAL");
@@ -1377,11 +1421,11 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1377
1421
  const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
1378
1422
  let dbBytes = 0;
1379
1423
  try {
1380
- const { statSync: statSync3, existsSync: existsSync3 } = require("fs");
1424
+ const { statSync: statSync3, existsSync: existsSync4 } = require("fs");
1381
1425
  dbBytes = statSync3(this.dbPath).size;
1382
1426
  for (const suffix of ["-wal", "-shm"]) {
1383
1427
  const p = this.dbPath + suffix;
1384
- if (existsSync3(p)) dbBytes += statSync3(p).size;
1428
+ if (existsSync4(p)) dbBytes += statSync3(p).size;
1385
1429
  }
1386
1430
  } catch {
1387
1431
  }
@@ -1414,15 +1458,15 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1414
1458
  "SELECT * FROM tool_calls WHERE id <= ? ORDER BY id"
1415
1459
  ).all(cutoff.id);
1416
1460
  if (rows.length === 0) return { archived: 0, file: "" };
1417
- const { writeFileSync: writeFileSync3, mkdirSync: mkdirSync4, existsSync: existsSync3 } = require("fs");
1418
- const { dirname: dirname4, join: join4 } = require("path");
1461
+ const { writeFileSync: writeFileSync4, mkdirSync: mkdirSync5, existsSync: existsSync4 } = require("fs");
1462
+ const { dirname: dirname5, join: join5 } = require("path");
1419
1463
  const { gzipSync } = require("zlib");
1420
- const archiveDir = join4(dirname4(this.dbPath), "archive");
1421
- if (!existsSync3(archiveDir)) mkdirSync4(archiveDir, { recursive: true, mode: 448 });
1464
+ const archiveDir = join5(dirname5(this.dbPath), "archive");
1465
+ if (!existsSync4(archiveDir)) mkdirSync5(archiveDir, { recursive: true, mode: 448 });
1422
1466
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
1423
- const file = join4(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
1467
+ const file = join5(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
1424
1468
  const payload = rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
1425
- writeFileSync3(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
1469
+ writeFileSync4(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
1426
1470
  const deleted = this.db.transaction(() => {
1427
1471
  const res = this.db.prepare("DELETE FROM tool_calls WHERE id <= ?").run(cutoff.id);
1428
1472
  this.db.prepare(`
@@ -1528,14 +1572,14 @@ function getDb(dbPath) {
1528
1572
  if (rawDb) return rawDb;
1529
1573
  try {
1530
1574
  const Database = require("better-sqlite3");
1531
- const { existsSync: existsSync3, mkdirSync: mkdirSync4 } = require("fs");
1532
- const { join: join4, dirname: dirname4 } = require("path");
1575
+ const { existsSync: existsSync4, mkdirSync: mkdirSync5 } = require("fs");
1576
+ const { join: join5, dirname: dirname5 } = require("path");
1533
1577
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
1534
- const xdgData = process.env.XDG_DATA_HOME || join4(home, ".local", "share");
1535
- const defaultPath = join4(xdgData, "agent_gate", "agent_gate_ts.db");
1578
+ const xdgData = process.env.XDG_DATA_HOME || join5(home, ".local", "share");
1579
+ const defaultPath = join5(xdgData, "agent_gate", "agent_gate_ts.db");
1536
1580
  const path = dbPath || defaultPath;
1537
- const dir = dirname4(path);
1538
- if (!existsSync3(dir)) mkdirSync4(dir, { recursive: true });
1581
+ const dir = dirname5(path);
1582
+ if (!existsSync4(dir)) mkdirSync5(dir, { recursive: true });
1539
1583
  rawDb = new Database(path);
1540
1584
  rawDb.pragma("journal_mode = WAL");
1541
1585
  return rawDb;
@@ -1599,7 +1643,7 @@ var import_zod = require("zod");
1599
1643
 
1600
1644
  // src/version.ts
1601
1645
  init_cjs_shims();
1602
- var _version = true ? "0.9.2" : (() => {
1646
+ var _version = true ? "0.9.4" : (() => {
1603
1647
  try {
1604
1648
  const require2 = createRequire(importMetaUrl);
1605
1649
  const pkg = require2("../package.json");
@@ -1615,6 +1659,8 @@ var AgentGateInputSchema = import_zod.z.object({
1615
1659
  agent_type: import_zod.z.string().describe("Agent identifier, e.g. opendesk, claude-code"),
1616
1660
  agent_version: import_zod.z.string().default("0.1.0"),
1617
1661
  session_id: import_zod.z.string().describe("Session unique identifier"),
1662
+ /** 安装级实例 ID(仅展示层脱敏用;缺省由 AgentGate 自动生成)。 */
1663
+ instance_id: import_zod.z.string().optional(),
1618
1664
  tool_name: import_zod.z.string().optional().describe("Tool name, e.g. bash, file_write"),
1619
1665
  command: import_zod.z.string().optional().describe("Tool command or description"),
1620
1666
  a_next: import_zod.z.object({
@@ -1688,6 +1734,7 @@ var HealthResponseSchema = import_zod.z.object({
1688
1734
  // src/shared/normalizer.ts
1689
1735
  init_cjs_shims();
1690
1736
  init_multi_session();
1737
+ init_instance_id();
1691
1738
  function normalize(input, systemContext) {
1692
1739
  const actionHistory = input.action_history.map((h) => ({
1693
1740
  action_type: h.action_type,
@@ -1731,6 +1778,8 @@ function normalize(input, systemContext) {
1731
1778
  // 历史上只在 metadata.agent_type 里带,AgentMoss 读顶层 req.agent_id → 空 →
1732
1779
  // 定制规则从未生效(OpenDesk memory-* 操作走 L3 耗时 1~137s)。
1733
1780
  agent_id: input.agent_type || "",
1781
+ // 实例 ID:仅用于 AgentMoss 展示层脱敏(同实例不隐藏),不参与判定。
1782
+ instance_id: input.instance_id || getInstanceId(),
1734
1783
  metadata: {
1735
1784
  ...input.metadata,
1736
1785
  agent_type: input.agent_type,
@@ -1750,16 +1799,16 @@ init_cjs_shims();
1750
1799
 
1751
1800
  // src/shared/collector/system-info.ts
1752
1801
  init_cjs_shims();
1753
- var import_os = __toESM(require("os"));
1802
+ var import_os2 = __toESM(require("os"));
1754
1803
  async function collectSystemInfo() {
1755
1804
  try {
1756
1805
  return {
1757
1806
  system: process.platform,
1758
- distribution: `${import_os.default.type()} ${import_os.default.release()}`,
1759
- hostname: import_os.default.hostname(),
1760
- arch: import_os.default.arch(),
1761
- cpu_count: import_os.default.cpus().length,
1762
- memory_total_mb: Math.round(import_os.default.totalmem() / (1024 * 1024))
1807
+ distribution: `${import_os2.default.type()} ${import_os2.default.release()}`,
1808
+ hostname: import_os2.default.hostname(),
1809
+ arch: import_os2.default.arch(),
1810
+ cpu_count: import_os2.default.cpus().length,
1811
+ memory_total_mb: Math.round(import_os2.default.totalmem() / (1024 * 1024))
1763
1812
  };
1764
1813
  } catch {
1765
1814
  return { system: "unknown" };
@@ -1783,10 +1832,10 @@ async function collectProcessInfo() {
1783
1832
 
1784
1833
  // src/shared/collector/user-info.ts
1785
1834
  init_cjs_shims();
1786
- var import_os2 = __toESM(require("os"));
1835
+ var import_os3 = __toESM(require("os"));
1787
1836
  async function collectUserInfo() {
1788
1837
  try {
1789
- const userInfo = import_os2.default.userInfo();
1838
+ const userInfo = import_os3.default.userInfo();
1790
1839
  return {
1791
1840
  uid: userInfo.uid,
1792
1841
  gid: userInfo.gid,
@@ -1924,10 +1973,10 @@ async function analyzeRoute(c) {
1924
1973
  const toolName = input.tool_name || input.a_next?.action_type || "unknown";
1925
1974
  const command = input.command || input.a_next?.action_detail || "";
1926
1975
  const key = cacheKey(input.session_id, input.cwd, command);
1927
- const cached = getCached(key);
1928
- if (cached) {
1976
+ const cached2 = getCached(key);
1977
+ if (cached2) {
1929
1978
  return c.json({
1930
- ...cached,
1979
+ ...cached2,
1931
1980
  analysis_duration_ms: 0,
1932
1981
  collected_context: {},
1933
1982
  ...storageOversizeInfo()
@@ -2239,17 +2288,17 @@ async function dashboardRoute(c) {
2239
2288
  return c.html(UNAUTHORIZED_HTML, 401, DASHBOARD_SECURITY_HEADERS);
2240
2289
  }
2241
2290
  }
2242
- const { readFileSync: readFileSync3, existsSync: existsSync3 } = await import("fs");
2243
- const { resolve, dirname: dirname4 } = await import("path");
2291
+ const { readFileSync: readFileSync4, existsSync: existsSync4 } = await import("fs");
2292
+ const { resolve, dirname: dirname5 } = await import("path");
2244
2293
  const { fileURLToPath } = await import("url");
2245
- const __dirname = dirname4(fileURLToPath(importMetaUrl));
2294
+ const __dirname = dirname5(fileURLToPath(importMetaUrl));
2246
2295
  const paths = [
2247
2296
  resolve(__dirname, "dashboard.html"),
2248
2297
  resolve(__dirname, "../dashboard.html"),
2249
2298
  resolve(__dirname, "../src/v1/dashboard.html")
2250
2299
  ];
2251
- const htmlPath = paths.find((p) => existsSync3(p)) || paths[0];
2252
- const html = readFileSync3(htmlPath, "utf-8");
2300
+ const htmlPath = paths.find((p) => existsSync4(p)) || paths[0];
2301
+ const html = readFileSync4(htmlPath, "utf-8");
2253
2302
  return c.html(html, 200, DASHBOARD_SECURITY_HEADERS);
2254
2303
  }
2255
2304
  // Annotate the CommonJS export names for ESM import in node: