@kenhkl/agent-gate 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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.1" : (() => {
53
+ _version = true ? "0.9.0" : (() => {
54
54
  try {
55
55
  const require2 = createRequire(importMetaUrl);
56
56
  const pkg = require2("../package.json");
@@ -817,9 +817,21 @@ var init_json_storage = __esm({
817
817
  if (params.agentType) {
818
818
  allRecords = allRecords.filter((r) => r.agent_type === params.agentType);
819
819
  }
820
+ if (params.agentId) {
821
+ allRecords = allRecords.filter((r) => `${r.agent_type}:${r.hostname}` === params.agentId);
822
+ }
820
823
  if (params.decision) {
821
824
  allRecords = allRecords.filter((r) => r.decision === params.decision);
822
825
  }
826
+ if (params.riskLevel) {
827
+ allRecords = allRecords.filter((r) => r.risk_level === params.riskLevel);
828
+ }
829
+ if (params.fromTime) {
830
+ allRecords = allRecords.filter((r) => r.called_at >= params.fromTime);
831
+ }
832
+ if (params.toTime) {
833
+ allRecords = allRecords.filter((r) => r.called_at <= params.toTime);
834
+ }
823
835
  allRecords.sort((a, b) => b.called_at.localeCompare(a.called_at));
824
836
  const offset = params.offset || 0;
825
837
  const limit = params.limit || 50;
@@ -837,6 +849,15 @@ var init_json_storage = __esm({
837
849
  }
838
850
  } catch {
839
851
  }
852
+ if (params.sessionId) {
853
+ allRecords = allRecords.filter((r) => r.session_id === params.sessionId);
854
+ }
855
+ if (params.agentId) {
856
+ const allowed = new Set(
857
+ [...sessions.values()].filter((s) => s.agent_id === params.agentId).map((s) => s.id)
858
+ );
859
+ allRecords = allRecords.filter((r) => allowed.has(r.session_id));
860
+ }
840
861
  if (params.agentType) {
841
862
  const allowed = new Set(
842
863
  [...sessions.values()].filter((s) => (agents.get(s.agent_id)?.agent_type || "") === params.agentType).map((s) => s.id)
@@ -846,6 +867,15 @@ var init_json_storage = __esm({
846
867
  if (params.decision) {
847
868
  allRecords = allRecords.filter((r) => r.decision === params.decision);
848
869
  }
870
+ if (params.riskLevel) {
871
+ allRecords = allRecords.filter((r) => r.risk_level === params.riskLevel);
872
+ }
873
+ if (params.fromTime) {
874
+ allRecords = allRecords.filter((r) => r.called_at >= params.fromTime);
875
+ }
876
+ if (params.toTime) {
877
+ allRecords = allRecords.filter((r) => r.called_at <= params.toTime);
878
+ }
849
879
  return allRecords.length;
850
880
  }
851
881
  getStorageStats() {
@@ -1102,6 +1132,10 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1102
1132
  conditions.push("tc.session_id = ?");
1103
1133
  values.push(params.sessionId);
1104
1134
  }
1135
+ if (params.agentId) {
1136
+ conditions.push("s.agent_id = ?");
1137
+ values.push(params.agentId);
1138
+ }
1105
1139
  if (params.agentType) {
1106
1140
  conditions.push("a.agent_type = ?");
1107
1141
  values.push(params.agentType);
@@ -1110,6 +1144,18 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1110
1144
  conditions.push("tc.decision = ?");
1111
1145
  values.push(params.decision);
1112
1146
  }
1147
+ if (params.riskLevel) {
1148
+ conditions.push("tc.risk_level = ?");
1149
+ values.push(params.riskLevel);
1150
+ }
1151
+ if (params.fromTime) {
1152
+ conditions.push("tc.called_at >= ?");
1153
+ values.push(params.fromTime);
1154
+ }
1155
+ if (params.toTime) {
1156
+ conditions.push("tc.called_at <= ?");
1157
+ values.push(params.toTime);
1158
+ }
1113
1159
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1114
1160
  const limit = params.limit || 50;
1115
1161
  const offset = params.offset || 0;
@@ -1124,14 +1170,34 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
1124
1170
  countToolCalls(params) {
1125
1171
  const conditions = [];
1126
1172
  const values = [];
1127
- if (params.decision) {
1128
- conditions.push("tc.decision = ?");
1129
- values.push(params.decision);
1173
+ if (params.sessionId) {
1174
+ conditions.push("tc.session_id = ?");
1175
+ values.push(params.sessionId);
1176
+ }
1177
+ if (params.agentId) {
1178
+ conditions.push("s.agent_id = ?");
1179
+ values.push(params.agentId);
1130
1180
  }
1131
1181
  if (params.agentType) {
1132
1182
  conditions.push("a.agent_type = ?");
1133
1183
  values.push(params.agentType);
1134
1184
  }
1185
+ if (params.decision) {
1186
+ conditions.push("tc.decision = ?");
1187
+ values.push(params.decision);
1188
+ }
1189
+ if (params.riskLevel) {
1190
+ conditions.push("tc.risk_level = ?");
1191
+ values.push(params.riskLevel);
1192
+ }
1193
+ if (params.fromTime) {
1194
+ conditions.push("tc.called_at >= ?");
1195
+ values.push(params.fromTime);
1196
+ }
1197
+ if (params.toTime) {
1198
+ conditions.push("tc.called_at <= ?");
1199
+ values.push(params.toTime);
1200
+ }
1135
1201
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1136
1202
  const row = this.db.prepare(
1137
1203
  `SELECT COUNT(*) as total FROM tool_calls tc
@@ -1494,18 +1560,23 @@ var init_models = __esm({
1494
1560
  text: import_zod.z.string().default(""),
1495
1561
  actions: import_zod.z.array(import_zod.z.object({
1496
1562
  action_type: import_zod.z.string(),
1497
- action_detail: import_zod.z.string()
1563
+ action_detail: import_zod.z.string(),
1564
+ 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
1565
  })).default([])
1499
1566
  })).default([]),
1500
1567
  action_history: import_zod.z.array(import_zod.z.object({
1501
1568
  action_type: import_zod.z.string(),
1502
- action_detail: import_zod.z.string()
1569
+ action_detail: import_zod.z.string(),
1570
+ // 授权类规则(改密码 / 删用户)靠 ask_user_question 的 output 判断用户是否已确认。
1571
+ // 此前 schema 里没有这个字段,Agent 传了也会被剥掉 → 必然判成「未授权」。
1572
+ 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
1573
  })).default([]),
1504
1574
  session_history: import_zod.z.array(import_zod.z.object({
1505
1575
  session_id: import_zod.z.string(),
1506
1576
  action_history: import_zod.z.array(import_zod.z.object({
1507
1577
  action_type: import_zod.z.string(),
1508
- action_detail: import_zod.z.string()
1578
+ action_detail: import_zod.z.string(),
1579
+ output: import_zod.z.string().optional()
1509
1580
  })).default([])
1510
1581
  })).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
1582
  metadata: import_zod.z.record(import_zod.z.unknown()).optional()
@@ -1550,20 +1621,23 @@ var init_models = __esm({
1550
1621
  function normalize(input, systemContext) {
1551
1622
  const actionHistory = input.action_history.map((h) => ({
1552
1623
  action_type: h.action_type,
1553
- action_detail: h.action_detail
1624
+ action_detail: h.action_detail,
1625
+ output: h.output ?? ""
1554
1626
  }));
1555
1627
  const sessionHistory = (input.session_history || []).map((s) => ({
1556
1628
  session_id: s.session_id,
1557
1629
  action_history: s.action_history.map((h) => ({
1558
1630
  action_type: h.action_type,
1559
- action_detail: h.action_detail
1631
+ action_detail: h.action_detail,
1632
+ output: h.output ?? ""
1560
1633
  }))
1561
1634
  }));
1562
1635
  const promptHistory = input.prompt_history.map((t) => ({
1563
1636
  text: t.text,
1564
1637
  actions: t.actions.map((a) => ({
1565
1638
  action_type: a.action_type,
1566
- action_detail: a.action_detail
1639
+ action_detail: a.action_detail,
1640
+ output: a.output ?? ""
1567
1641
  }))
1568
1642
  }));
1569
1643
  const toolName = input.tool_name || input.a_next?.action_type || "unknown";
@@ -1915,13 +1989,22 @@ async function sessionsRoute(c) {
1915
1989
  return c.json({ session_id: sessionId, tool_calls: rows });
1916
1990
  }
1917
1991
  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);
1992
+ const sessionId = c.req.query("session_id") || void 0;
1993
+ let agentId = c.req.query("agent_id") || void 0;
1994
+ const decision = c.req.query("decision") || void 0;
1995
+ const riskLevel = c.req.query("risk_level") || void 0;
1996
+ const fromTime = c.req.query("from") || void 0;
1997
+ const toTime = c.req.query("to") || void 0;
1998
+ const rawLimit = parseInt(c.req.query("limit") || "50", 10);
1999
+ const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 500) : 50;
2000
+ const rawOffset = parseInt(c.req.query("offset") || "0", 10);
2001
+ const offset = Number.isFinite(rawOffset) && rawOffset > 0 ? rawOffset : 0;
1921
2002
  const bound = boundAgentOf(c.get("principal") || "");
2003
+ if (bound) agentId = void 0;
1922
2004
  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 });
2005
+ const filter2 = { sessionId, agentId, agentType, decision, riskLevel, fromTime, toTime };
2006
+ const total = countToolCalls(filter2);
2007
+ const data = queryToolCalls({ ...filter2, limit, offset });
1925
2008
  return c.json({ total, data });
1926
2009
  }
1927
2010
  async function agentsRoute(c) {
@@ -1986,7 +2069,12 @@ function createApp() {
1986
2069
  allowMethods: ["GET", "POST", "OPTIONS", "DELETE"],
1987
2070
  allowHeaders: ["*"]
1988
2071
  }));
1989
- app.use("*", (0, import_logger.logger)());
2072
+ app.use(
2073
+ "*",
2074
+ (0, import_logger.logger)(
2075
+ (str, ...rest) => console.log(str.replace(/([?&]token=)[^&\s"']+/gi, "$1***"), ...rest)
2076
+ )
2077
+ );
1990
2078
  app.use("*", async (c, next) => {
1991
2079
  const path11 = new URL(c.req.url).pathname;
1992
2080
  const method = c.req.method.toUpperCase();
@@ -2105,13 +2193,13 @@ async function dashboardRoute(c) {
2105
2193
  }
2106
2194
  }
2107
2195
  const { readFileSync: readFileSync14, existsSync: existsSync12 } = await import("fs");
2108
- const { resolve: resolve3, dirname: dirname5 } = await import("path");
2196
+ const { resolve: resolve4, dirname: dirname5 } = await import("path");
2109
2197
  const { fileURLToPath } = await import("url");
2110
2198
  const __dirname2 = dirname5(fileURLToPath(importMetaUrl));
2111
2199
  const paths = [
2112
- resolve3(__dirname2, "dashboard.html"),
2113
- resolve3(__dirname2, "../dashboard.html"),
2114
- resolve3(__dirname2, "../src/v1/dashboard.html")
2200
+ resolve4(__dirname2, "dashboard.html"),
2201
+ resolve4(__dirname2, "../dashboard.html"),
2202
+ resolve4(__dirname2, "../src/v1/dashboard.html")
2115
2203
  ];
2116
2204
  const htmlPath = paths.find((p) => existsSync12(p)) || paths[0];
2117
2205
  const html = readFileSync14(htmlPath, "utf-8");
@@ -2343,10 +2431,10 @@ function awaitify(asyncFn, arity) {
2343
2431
  if (typeof args[arity - 1] === "function") {
2344
2432
  return asyncFn.apply(this, args);
2345
2433
  }
2346
- return new Promise((resolve3, reject2) => {
2434
+ return new Promise((resolve4, reject2) => {
2347
2435
  args[arity - 1] = (err, ...cbArgs) => {
2348
2436
  if (err) return reject2(err);
2349
- resolve3(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
2437
+ resolve4(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
2350
2438
  };
2351
2439
  asyncFn.apply(this, args);
2352
2440
  });
@@ -2528,13 +2616,13 @@ function mapSeries(coll, iteratee, callback) {
2528
2616
  return _asyncMap(eachOfSeries$1, coll, iteratee, callback);
2529
2617
  }
2530
2618
  function promiseCallback() {
2531
- let resolve3, reject2;
2619
+ let resolve4, reject2;
2532
2620
  function callback(err, ...args) {
2533
2621
  if (err) return reject2(err);
2534
- resolve3(args.length > 1 ? args : args[0]);
2622
+ resolve4(args.length > 1 ? args : args[0]);
2535
2623
  }
2536
2624
  callback[PROMISE_SYMBOL] = new Promise((res, rej) => {
2537
- resolve3 = res, reject2 = rej;
2625
+ resolve4 = res, reject2 = rej;
2538
2626
  });
2539
2627
  return callback;
2540
2628
  }
@@ -2807,8 +2895,8 @@ function queue$1(worker, concurrency, payload) {
2807
2895
  });
2808
2896
  }
2809
2897
  if (rejectOnError || !callback) {
2810
- return new Promise((resolve3, reject2) => {
2811
- res = resolve3;
2898
+ return new Promise((resolve4, reject2) => {
2899
+ res = resolve4;
2812
2900
  rej = reject2;
2813
2901
  });
2814
2902
  }
@@ -2847,10 +2935,10 @@ function queue$1(worker, concurrency, payload) {
2847
2935
  }
2848
2936
  const eventMethod = (name) => (handler) => {
2849
2937
  if (!handler) {
2850
- return new Promise((resolve3, reject2) => {
2938
+ return new Promise((resolve4, reject2) => {
2851
2939
  once2(name, (err, data) => {
2852
2940
  if (err) return reject2(err);
2853
- resolve3(data);
2941
+ resolve4(data);
2854
2942
  });
2855
2943
  });
2856
2944
  }
@@ -25773,7 +25861,7 @@ var require_path_arg = __commonJS({
25773
25861
  "use strict";
25774
25862
  init_cjs_shims();
25775
25863
  var platform2 = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform;
25776
- var { resolve: resolve3, parse: parse2 } = require("path");
25864
+ var { resolve: resolve4, parse: parse2 } = require("path");
25777
25865
  var pathArg = (path11) => {
25778
25866
  if (/\0/.test(path11)) {
25779
25867
  throw Object.assign(
@@ -25784,7 +25872,7 @@ var require_path_arg = __commonJS({
25784
25872
  }
25785
25873
  );
25786
25874
  }
25787
- path11 = resolve3(path11);
25875
+ path11 = resolve4(path11);
25788
25876
  if (platform2 === "win32") {
25789
25877
  const badWinChars = /[*|"<>?:]/;
25790
25878
  const { root } = parse2(path11);
@@ -28819,7 +28907,7 @@ load();setInterval(load,5000);
28819
28907
  });
28820
28908
  return callback(null);
28821
28909
  });
28822
- return new Promise((resolve3, reject2) => {
28910
+ return new Promise((resolve4, reject2) => {
28823
28911
  const proxy = this._mitmProxy;
28824
28912
  if (!proxy) {
28825
28913
  reject2(new Error("MITM proxy not initialized"));
@@ -28841,7 +28929,7 @@ load();setInterval(load,5000);
28841
28929
  console.log(`[AgentGate] SSL CA dir: ${caDir}`);
28842
28930
  console.log(`[AgentGate] Set HTTPS_PROXY=http://${this._options.host}:${this._options.port}`);
28843
28931
  this._startDashboard();
28844
- resolve3();
28932
+ resolve4();
28845
28933
  }
28846
28934
  );
28847
28935
  });
@@ -29275,7 +29363,7 @@ var init_coordinator = __esm({
29275
29363
  init_verdict();
29276
29364
  init_repository();
29277
29365
  init_multi_session();
29278
- PhaseCoordinator = class {
29366
+ PhaseCoordinator = class _PhaseCoordinator {
29279
29367
  level;
29280
29368
  mossClient;
29281
29369
  aggregator;
@@ -29294,10 +29382,22 @@ var init_coordinator = __esm({
29294
29382
  cleanupRunning = false;
29295
29383
  /** 低频回顾触发计数(每 N 条落库触发一次 /api/v1/review)。 */
29296
29384
  reviewCounter = 0;
29385
+ // L3 事件风暴护栏:harmony 后端(/proc + inotify)单机每秒可产出上百个事件,
29386
+ // 每个事件同步打一次 moss(有效并发≈1,moss 单进程无队列)。真机实测:
29387
+ // 不设护栏时事件堆积 + 每个 500 重试把 moss/daemon 拖到假死。三道护栏:
29388
+ // 1. 同签名 5s 内去重(同一进程反复 exec/同一文件反复写只分析一次)
29389
+ // 2. 在途上限(超过直接丢弃并计数,不排队)
29390
+ // 3. 丢弃/失败日志限频(每 10s 最多一条),避免日志本身成为 IO 风暴
29391
+ l3Recent = /* @__PURE__ */ new Map();
29392
+ l3Inflight = 0;
29393
+ l3Dropped = 0;
29394
+ l3LastDropLog = 0;
29395
+ static L3_DEDUP_WINDOW_MS = 5e3;
29396
+ static L3_MAX_INFLIGHT = 4;
29297
29397
  constructor(opts = {}) {
29298
29398
  this.level = opts.level ?? 1;
29299
- if (this.level !== 1 && this.level !== 2) {
29300
- throw new Error(`level must be 1 or 2, got ${this.level}`);
29399
+ if (this.level !== 1 && this.level !== 2 && this.level !== 3) {
29400
+ throw new Error(`level must be 1, 2 or 3, got ${this.level}`);
29301
29401
  }
29302
29402
  this.mossClient = opts.mossClient;
29303
29403
  this.aggregator = opts.sessionAggregator;
@@ -29473,21 +29573,57 @@ var init_coordinator = __esm({
29473
29573
  }
29474
29574
  // ── Public API: L3 side (fire-and-forget) ─────────────────────────────────
29475
29575
  async onL3Event(sessionId, event) {
29476
- console.log(
29477
- `[PhaseCoordinator][L3]: standalone L3 event session=${sessionId.slice(0, 8)}`
29478
- );
29479
- if (this.mossClient) {
29480
- try {
29481
- const report = this._buildL3Report(sessionId, event);
29482
- await this._sendToMoss(report);
29483
- console.log(
29484
- `[PhaseCoordinator][L3]: AgentMoss analysis sent (session=${sessionId.slice(0, 8)})`
29576
+ if (!this.mossClient) return;
29577
+ const sig = this._l3Signature(event);
29578
+ const now = Date.now();
29579
+ const last = this.l3Recent.get(sig);
29580
+ if (last !== void 0 && now - last < _PhaseCoordinator.L3_DEDUP_WINDOW_MS) {
29581
+ return;
29582
+ }
29583
+ this.l3Recent.set(sig, now);
29584
+ if (this.l3Recent.size > 2e3) {
29585
+ for (const [k, t] of this.l3Recent) {
29586
+ if (now - t >= _PhaseCoordinator.L3_DEDUP_WINDOW_MS) this.l3Recent.delete(k);
29587
+ }
29588
+ }
29589
+ if (this.l3Inflight >= _PhaseCoordinator.L3_MAX_INFLIGHT) {
29590
+ this.l3Dropped++;
29591
+ if (now - this.l3LastDropLog > 1e4) {
29592
+ this.l3LastDropLog = now;
29593
+ console.warn(
29594
+ `[PhaseCoordinator][L3]: inflight=${this.l3Inflight} \u5DF2\u8FBE\u4E0A\u9650\uFF0C\u4E22\u5F03\u4E8B\u4EF6\u7D2F\u8BA1 ${this.l3Dropped} \u6761`
29485
29595
  );
29486
- } catch (err) {
29596
+ }
29597
+ return;
29598
+ }
29599
+ this.l3Inflight++;
29600
+ try {
29601
+ const report = this._buildL3Report(sessionId, event);
29602
+ const decision = await this._sendToMoss(report);
29603
+ console.log(
29604
+ `[PhaseCoordinator][L3]: ${report.a_next.action_type} \u2192 ${decision} (session=${sessionId.slice(0, 16)})`
29605
+ );
29606
+ } catch (err) {
29607
+ if (Date.now() - this.l3LastDropLog > 1e4) {
29608
+ this.l3LastDropLog = Date.now();
29487
29609
  console.error("[PhaseCoordinator][L3]: AgentMoss request failed:", err);
29488
29610
  }
29611
+ } finally {
29612
+ this.l3Inflight--;
29489
29613
  }
29490
29614
  }
29615
+ /** L3 事件签名:同进程同一动作/同一文件在去重窗口内只分析一次。 */
29616
+ _l3Signature(event) {
29617
+ const p = event.process ?? {};
29618
+ const t = event.target ?? {};
29619
+ const a = event.action ?? {};
29620
+ return [
29621
+ String(event.event_type_name ?? event.event_type ?? ""),
29622
+ String(p.pid ?? event.pid ?? ""),
29623
+ String(a.tool_name ?? a.toolType ?? ""),
29624
+ String(t._command_clean ?? t.command ?? t.argv ?? event.argv ?? t.pathname ?? event.filename ?? "")
29625
+ ].join("|");
29626
+ }
29491
29627
  // ── Phase 2: AgentMoss submission ────────────────────────────────────────
29492
29628
  async executePhase2(sessionId, event, pendingAction) {
29493
29629
  try {
@@ -29504,7 +29640,7 @@ var init_coordinator = __esm({
29504
29640
  event = this.privacyFilter.apply(event);
29505
29641
  }
29506
29642
  if (this.mossClient) {
29507
- const report = this.buildMossReport(session, event, triggerMatches);
29643
+ const report = this.buildMossReport(sessionIdActual, session, event, triggerMatches);
29508
29644
  try {
29509
29645
  const response = await this.mossClient.analyzeSync(report);
29510
29646
  let decision = response.decision ?? "Allow";
@@ -29650,7 +29786,7 @@ var init_coordinator = __esm({
29650
29786
  return [];
29651
29787
  }
29652
29788
  }
29653
- buildMossReport(session, event, triggerMatches) {
29789
+ buildMossReport(sessionId, session, event, triggerMatches) {
29654
29790
  const actionHistory = [];
29655
29791
  if (session?.events) {
29656
29792
  for (const evt of session.events) {
@@ -29685,38 +29821,30 @@ var init_coordinator = __esm({
29685
29821
  const currentTarget = event.target ?? {};
29686
29822
  const currentPayload = event.payload ?? {};
29687
29823
  const match0 = triggerMatches[0];
29688
- const sessionDict = session ? {
29689
- id: session.id,
29690
- event_count: session.events.length,
29691
- prompt_count: session.prompts?.length ?? 0,
29692
- inferred_agent_type: event.agentType ?? "unknown"
29693
- } : {};
29824
+ const nextActionType = String(currentAction.toolName ?? currentAction.tool_name ?? "").trim() || "unknown";
29825
+ const nextActionDetail = String(
29826
+ currentTarget.command ?? currentAction.argumentsRaw ?? ""
29827
+ ).slice(0, 2e3);
29694
29828
  return {
29695
29829
  trigger_type: match0?.rule.name ?? "proxy",
29696
29830
  trigger_rule: match0?.rule.name ?? "",
29697
29831
  trigger_detail: match0?.detail ?? "",
29698
- session: sessionDict,
29832
+ session_id: session?.id || sessionId,
29833
+ prompt_session: currentPromptText,
29834
+ prompt_history: promptHistory.map((text) => ({ text, actions: [] })),
29699
29835
  behavior_sequence: [],
29700
29836
  payload_sequences: [],
29701
29837
  action_history: actionHistory,
29702
- session_history: this._buildSessionHistory(session?.id ?? ""),
29703
- prompt_history: promptHistory,
29704
- current_prompt: currentPromptText,
29705
- current_action: {
29706
- tool_name: currentAction.toolName ?? "",
29707
- arguments_raw: currentAction.argumentsRaw ?? "{}",
29708
- tool_call_id: currentAction.toolCallId ?? ""
29709
- },
29710
- current_target: {
29711
- command: currentTarget.command ?? "",
29712
- file_path: currentTarget.filePath ?? "",
29713
- arguments: currentTarget.arguments ?? {}
29714
- },
29715
- prompt: {
29716
- system_prompt: currentPayload.systemPrompt ?? "",
29717
- user_prompt: currentPromptText
29838
+ session_history: this._buildSessionHistory(session?.id || sessionId),
29839
+ a_next: { action_type: nextActionType, action_detail: nextActionDetail },
29840
+ reason: match0?.detail ?? "",
29841
+ os_type: "",
29842
+ cwd: "",
29843
+ agent_id: String(event.agentType ?? event.agent_type ?? ""),
29844
+ metadata: {
29845
+ stateful_incremental: true,
29846
+ ...currentPayload.systemPrompt ? { system_prompt: currentPayload.systemPrompt } : {}
29718
29847
  },
29719
- metadata: { stateful_incremental: true },
29720
29848
  source_layers: event.source_layers ?? ["l1"],
29721
29849
  level: this.level
29722
29850
  };
@@ -29732,7 +29860,7 @@ var init_coordinator = __esm({
29732
29860
  const response = await this.mossClient.analyzeSync(report);
29733
29861
  const decision = response.decision ?? "Allow";
29734
29862
  if (decision === "Deny" && this.onBlock) {
29735
- const shouldBlock = this.onBlock(report.session.id, []);
29863
+ const shouldBlock = this.onBlock(report.session_id, []);
29736
29864
  if (!shouldBlock) {
29737
29865
  return "Allow";
29738
29866
  }
@@ -29780,28 +29908,22 @@ var init_coordinator = __esm({
29780
29908
  trigger_type: "l2_standalone",
29781
29909
  trigger_rule: "l2_standalone",
29782
29910
  trigger_detail: `command: ${action.l2Command}`,
29783
- session: sessionDict,
29911
+ session_id: session?.id || sessionId,
29912
+ prompt_session: currentPromptText,
29913
+ prompt_history: promptHistory.map((text) => ({ text, actions: [] })),
29784
29914
  behavior_sequence: [],
29785
29915
  payload_sequences: [],
29786
29916
  action_history: actionHistory,
29787
- session_history: this._buildSessionHistory(sessionId),
29788
- prompt_history: promptHistory,
29789
- current_prompt: currentPromptText,
29790
- current_action: {
29791
- tool_name: action.toolName,
29792
- arguments_raw: JSON.stringify(action.l2Args ?? []),
29793
- tool_call_id: action.toolCallId
29794
- },
29795
- current_target: {
29796
- command: action.l2Command,
29797
- file_path: "",
29798
- arguments: {}
29917
+ session_history: this._buildSessionHistory(session?.id || sessionId),
29918
+ a_next: {
29919
+ action_type: action.toolName || "unknown",
29920
+ action_detail: String(action.l2Command ?? "").slice(0, 2e3)
29799
29921
  },
29800
- prompt: {
29801
- system_prompt: "",
29802
- user_prompt: currentPromptText
29803
- },
29804
- metadata: { stateful_incremental: true },
29922
+ reason: "",
29923
+ os_type: "",
29924
+ cwd: "",
29925
+ agent_id: "",
29926
+ metadata: { stateful_incremental: true, event_count: sessionDict.event_count ?? 0 },
29805
29927
  source_layers: ["l2"],
29806
29928
  level: this.level
29807
29929
  };
@@ -29843,37 +29965,30 @@ var init_coordinator = __esm({
29843
29965
  }
29844
29966
  const l3Action = event.action ?? {};
29845
29967
  const l3Target = event.target ?? {};
29846
- const sessionDict = session ? {
29847
- id: session.id,
29848
- event_count: session.events.length,
29849
- prompt_count: session.prompts?.length ?? 0,
29850
- inferred_agent_type: event.agentType ?? "unknown"
29851
- } : {};
29968
+ const l3ActionType = String(
29969
+ l3Action.tool_name ?? l3Action.toolName ?? event.event_type_name ?? event.event_type ?? ""
29970
+ ).trim() || "unknown";
29971
+ const l3ActionDetail = String(
29972
+ l3Target._command_clean ?? l3Target.command ?? l3Target.argv ?? event.argv ?? l3Target.pathname ?? event.filename ?? ""
29973
+ ).slice(0, 2e3);
29852
29974
  return {
29853
29975
  trigger_type: "l3_event",
29854
29976
  trigger_rule: "l3_event",
29855
29977
  trigger_detail: `l3: ${JSON.stringify(event).slice(0, 200)}`,
29856
- session: sessionDict,
29978
+ session_id: session?.id || sessionId,
29979
+ prompt_session: currentPromptText,
29980
+ prompt_history: promptHistory.map((text) => ({ text, actions: [] })),
29857
29981
  behavior_sequence: [],
29858
29982
  payload_sequences: [],
29859
29983
  action_history: actionHistory,
29860
- session_history: this._buildSessionHistory(sessionId),
29861
- prompt_history: promptHistory,
29862
- current_prompt: currentPromptText,
29863
- current_action: {
29864
- tool_name: String(l3Action.toolName ?? ""),
29865
- arguments_raw: String(l3Action.argumentsRaw ?? "{}"),
29866
- tool_call_id: String(l3Action.toolCallId ?? "")
29867
- },
29868
- current_target: {
29869
- command: String(l3Target.command ?? ""),
29870
- file_path: String(l3Target.filePath ?? ""),
29871
- arguments: l3Target.arguments ?? {}
29872
- },
29873
- prompt: {
29874
- system_prompt: "",
29875
- user_prompt: currentPromptText
29876
- },
29984
+ session_history: this._buildSessionHistory(session?.id || sessionId),
29985
+ a_next: { action_type: l3ActionType, action_detail: l3ActionDetail },
29986
+ reason: "",
29987
+ os_type: "",
29988
+ cwd: "",
29989
+ agent_id: String(
29990
+ event.process?.agent_type ?? event.agentType ?? event.agent_type ?? ""
29991
+ ),
29877
29992
  metadata: { stateful_incremental: true },
29878
29993
  source_layers: ["l3"],
29879
29994
  level: this.level
@@ -30197,13 +30312,13 @@ var init_server3 = __esm({
30197
30312
  });
30198
30313
  }
30199
30314
  start() {
30200
- return new Promise((resolve3) => {
30315
+ return new Promise((resolve4) => {
30201
30316
  this.server = import_node_http2.default.createServer((req, res) => this.handleRequest(req, res));
30202
30317
  this.server.listen(this.port, this.host, () => {
30203
30318
  console.log(`[Gateway] AgentGate API Gateway listening on ${this.host}:${this.port}`);
30204
30319
  console.log(`[Gateway] Routing: multi-provider (${this.router.routeCount} routes)`);
30205
30320
  console.log(`[Gateway] Dashboard: http://${this.host}:${this.port}`);
30206
- resolve3();
30321
+ resolve4();
30207
30322
  });
30208
30323
  });
30209
30324
  }
@@ -30289,7 +30404,7 @@ var init_server3 = __esm({
30289
30404
  }
30290
30405
  }
30291
30406
  forward(route, body, method, clientHeaders) {
30292
- return new Promise((resolve3, reject2) => {
30407
+ return new Promise((resolve4, reject2) => {
30293
30408
  const url = new import_node_url2.URL(route.upstreamUrl);
30294
30409
  const isHttps = url.protocol === "https:";
30295
30410
  const transport = isHttps ? import_node_https.default : import_node_http2.default;
@@ -30338,7 +30453,7 @@ var init_server3 = __esm({
30338
30453
  respHeaders[key] = Array.isArray(val) ? val.join(", ") : val;
30339
30454
  }
30340
30455
  }
30341
- resolve3({
30456
+ resolve4({
30342
30457
  statusCode: upstreamRes.statusCode ?? 502,
30343
30458
  headers: respHeaders,
30344
30459
  body: respBody
@@ -30431,11 +30546,11 @@ var init_server3 = __esm({
30431
30546
  }
30432
30547
  // ---- Dashboard & API ----
30433
30548
  readBody(req) {
30434
- return new Promise((resolve3) => {
30549
+ return new Promise((resolve4) => {
30435
30550
  const chunks = [];
30436
30551
  req.on("data", (chunk) => chunks.push(chunk));
30437
- req.on("end", () => resolve3(Buffer.concat(chunks)));
30438
- req.on("error", () => resolve3(Buffer.alloc(0)));
30552
+ req.on("end", () => resolve4(Buffer.concat(chunks)));
30553
+ req.on("error", () => resolve4(Buffer.alloc(0)));
30439
30554
  });
30440
30555
  }
30441
30556
  json(res, status, data) {
@@ -32376,7 +32491,7 @@ __export(http_proxy_exports, {
32376
32491
  createHttpProxy: () => createHttpProxy
32377
32492
  });
32378
32493
  function forwardToUpstream(upstreamUrl, msg) {
32379
- return new Promise((resolve3) => {
32494
+ return new Promise((resolve4) => {
32380
32495
  const url = new URL(upstreamUrl);
32381
32496
  const body = JSON.stringify(msg);
32382
32497
  const req = http3.request(
@@ -32396,12 +32511,12 @@ function forwardToUpstream(upstreamUrl, msg) {
32396
32511
  res.setEncoding("utf8");
32397
32512
  res.on("data", (c) => data += c);
32398
32513
  res.on("end", () => {
32399
- resolve3({ status: res.statusCode ?? 500, body: data, contentType: res.headers["content-type"] ?? "" });
32514
+ resolve4({ status: res.statusCode ?? 500, body: data, contentType: res.headers["content-type"] ?? "" });
32400
32515
  });
32401
32516
  }
32402
32517
  );
32403
32518
  req.on("error", () => {
32404
- resolve3({ status: 503, body: "", contentType: "" });
32519
+ resolve4({ status: 503, body: "", contentType: "" });
32405
32520
  });
32406
32521
  req.write(body);
32407
32522
  req.end();
@@ -32469,9 +32584,9 @@ function createHttpProxy(opts) {
32469
32584
  }
32470
32585
  }
32471
32586
  });
32472
- return new Promise((resolve3) => {
32587
+ return new Promise((resolve4) => {
32473
32588
  server.listen(listenPort, listenHost, () => {
32474
- resolve3({
32589
+ resolve4({
32475
32590
  server,
32476
32591
  close: () => new Promise((res) => {
32477
32592
  server.close(() => res());
@@ -32498,7 +32613,7 @@ __export(sse_proxy_exports, {
32498
32613
  rewriteEndpoint: () => rewriteEndpoint
32499
32614
  });
32500
32615
  function postToUpstream(upstreamUrl, msg) {
32501
- return new Promise((resolve3) => {
32616
+ return new Promise((resolve4) => {
32502
32617
  const url = new URL(upstreamUrl);
32503
32618
  const body = JSON.stringify(msg);
32504
32619
  const req = http4.request(
@@ -32517,10 +32632,10 @@ function postToUpstream(upstreamUrl, msg) {
32517
32632
  let data = "";
32518
32633
  res.setEncoding("utf8");
32519
32634
  res.on("data", (c) => data += c);
32520
- res.on("end", () => resolve3({ status: res.statusCode ?? 500, body: data }));
32635
+ res.on("end", () => resolve4({ status: res.statusCode ?? 500, body: data }));
32521
32636
  }
32522
32637
  );
32523
- req.on("error", () => resolve3({ status: 503, body: "" }));
32638
+ req.on("error", () => resolve4({ status: 503, body: "" }));
32524
32639
  req.write(body);
32525
32640
  req.end();
32526
32641
  });
@@ -32541,11 +32656,11 @@ function createSseProxy(opts) {
32541
32656
  Connection: "keep-alive"
32542
32657
  });
32543
32658
  try {
32544
- const upstreamRes = await new Promise((resolve3, reject2) => {
32659
+ const upstreamRes = await new Promise((resolve4, reject2) => {
32545
32660
  const url = new URL(upstreamUrl);
32546
32661
  const ureq = http4.get(
32547
32662
  { host: url.hostname, port: url.port || 80, path: url.pathname + (url.search ?? "") },
32548
- (r) => resolve3(r)
32663
+ (r) => resolve4(r)
32549
32664
  );
32550
32665
  ureq.on("error", reject2);
32551
32666
  });
@@ -32625,9 +32740,9 @@ function createSseProxy(opts) {
32625
32740
  res.writeHead(405);
32626
32741
  res.end("Method Not Allowed");
32627
32742
  });
32628
- return new Promise((resolve3) => {
32743
+ return new Promise((resolve4) => {
32629
32744
  server.listen(listenPort, listenHost, () => {
32630
- resolve3({
32745
+ resolve4({
32631
32746
  server,
32632
32747
  close: () => new Promise((res) => {
32633
32748
  server.close(() => res());
@@ -32793,10 +32908,10 @@ async function scanProcesses() {
32793
32908
  const args = isWin ? ["process", "get", "ProcessId,ParentProcessId,Name,CommandLine", "/format:csv"] : ["-eo", "pid,ppid,comm,args"];
32794
32909
  try {
32795
32910
  const { execFile } = await import("child_process");
32796
- return new Promise((resolve3) => {
32911
+ return new Promise((resolve4) => {
32797
32912
  execFile(cmd, args, { timeout: 5e3 }, (err, stdout) => {
32798
32913
  if (err || !stdout) {
32799
- resolve3([]);
32914
+ resolve4([]);
32800
32915
  return;
32801
32916
  }
32802
32917
  const procs = [];
@@ -32824,7 +32939,7 @@ async function scanProcesses() {
32824
32939
  }
32825
32940
  }
32826
32941
  }
32827
- resolve3(procs);
32942
+ resolve4(procs);
32828
32943
  });
32829
32944
  });
32830
32945
  } catch {
@@ -32850,7 +32965,7 @@ var init_wrapper = __esm({
32850
32965
  this.options = options;
32851
32966
  }
32852
32967
  async run(command, args = []) {
32853
- return new Promise((resolve3, reject2) => {
32968
+ return new Promise((resolve4, reject2) => {
32854
32969
  try {
32855
32970
  console.log(`[PTY] Starting: ${command} ${args.join(" ")}`);
32856
32971
  this.ptyProcess = pty.spawn(command, args, {
@@ -32878,7 +32993,7 @@ var init_wrapper = __esm({
32878
32993
  if (this.options.onExit) {
32879
32994
  this.options.onExit(exitCode, signal);
32880
32995
  }
32881
- resolve3(exitCode);
32996
+ resolve4(exitCode);
32882
32997
  });
32883
32998
  this.startProcessMonitor();
32884
32999
  } catch (error) {
@@ -33273,10 +33388,10 @@ var init_launcher = __esm({
33273
33388
  [AgentGate] CONFIRM: ${toolCall2.toolName} ${cmd}`);
33274
33389
  const readline2 = await import("readline");
33275
33390
  const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
33276
- return new Promise((resolve3) => {
33391
+ return new Promise((resolve4) => {
33277
33392
  rl.question(" Allow this action? [y/N] ", (answer) => {
33278
33393
  rl.close();
33279
- resolve3(answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes");
33394
+ resolve4(answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes");
33280
33395
  });
33281
33396
  });
33282
33397
  }
@@ -34076,6 +34191,19 @@ var path10 = __toESM(require("path"));
34076
34191
  var import_yaml3 = require("yaml");
34077
34192
  init_version();
34078
34193
  var import_node_fetch2 = __toESM(require("node-fetch"));
34194
+ function resolveRulesPath(explicit) {
34195
+ const candidates = [];
34196
+ if (explicit) candidates.push(explicit);
34197
+ const fromEnv = process.env.AGENT_GATE_RULES;
34198
+ if (fromEnv) candidates.push(fromEnv);
34199
+ candidates.push(path10.resolve(__dirname, "..", "config", "trigger_rules.yaml"));
34200
+ candidates.push(path10.resolve(__dirname, "..", "..", "..", "config", "trigger_rules.yaml"));
34201
+ candidates.push(path10.resolve(process.cwd(), "config", "trigger_rules.yaml"));
34202
+ for (const p of candidates) {
34203
+ if ((0, import_node_fs5.existsSync)(p)) return p;
34204
+ }
34205
+ return candidates[0];
34206
+ }
34079
34207
  async function main() {
34080
34208
  const args = process.argv.slice(2);
34081
34209
  const command = args[0];
@@ -34174,7 +34302,10 @@ Run options:
34174
34302
  const app = createApp2();
34175
34303
  console.log(`AgentGate HTTP server on ${host}:${port}`);
34176
34304
  if (authEnabled2() && authToken2()) {
34177
- console.log(`Dashboard: http://localhost:${port}/dashboard/?token=${authToken2()}`);
34305
+ const dash = `http://localhost:${port}/dashboard/?token=${authToken2()}`;
34306
+ console.log(
34307
+ `Dashboard: ${process.stdout.isTTY ? dash : dash.replace(/([?&]token=)[^&\s"']+/gi, "$1***")}`
34308
+ );
34178
34309
  }
34179
34310
  serve({ fetch: app.fetch, hostname: host, port }, (info) => {
34180
34311
  console.log(`Listening on http://${host}:${port}`);
@@ -34679,6 +34810,7 @@ Usage:
34679
34810
  let logLevel = "info";
34680
34811
  let denyAction = "inform";
34681
34812
  let securityUrl;
34813
+ let rulesPathArg;
34682
34814
  for (let i = 1; i < args.length; i++) {
34683
34815
  if (args[i] === "--level" && args[i + 1]) level = args[++i];
34684
34816
  else if (args[i] === "--upstream" && args[i + 1]) upstream = args[++i];
@@ -34688,6 +34820,7 @@ Usage:
34688
34820
  else if (args[i] === "--log-level" && args[i + 1]) logLevel = args[++i];
34689
34821
  else if (args[i] === "--deny-action" && args[i + 1]) denyAction = args[++i];
34690
34822
  else if (args[i] === "--security-url" && args[i + 1]) securityUrl = args[++i];
34823
+ else if (args[i] === "--rules" && args[i + 1]) rulesPathArg = args[++i];
34691
34824
  }
34692
34825
  const validLevels = ["l1", "l2", "l3", "l1+l2", "l1+l3", "l2+l3", "l1+l2+l3"];
34693
34826
  if (!validLevels.includes(level)) {
@@ -34712,7 +34845,7 @@ Usage:
34712
34845
  }
34713
34846
  }
34714
34847
  }
34715
- const mossUrl2 = process.env.AGENT_MOSS_URL || "http://127.0.0.1:9090";
34848
+ const mossUrl2 = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL || "http://127.0.0.1:9090";
34716
34849
  let mossConnected = false;
34717
34850
  try {
34718
34851
  const resp = await (0, import_node_fetch2.default)(`${mossUrl2}/api/v1/health`, { timeout: 3e3 });
@@ -34761,11 +34894,12 @@ Usage:
34761
34894
  const effectiveMossUrl = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL;
34762
34895
  if (effectiveMossUrl) setMossUrl2(effectiveMossUrl);
34763
34896
  const proxyLevel = hasL2 ? 2 : 1;
34764
- const rulesPath = "../config/trigger_rules.yaml";
34897
+ const rulesPath = resolveRulesPath(rulesPathArg);
34765
34898
  const aggregator = new ProxySessionAggregator2();
34766
34899
  const triggerEngine = new TriggerEngine2(rulesPath);
34767
34900
  const whitelistEngine = new WhitelistEngine2(rulesPath);
34768
34901
  const privacyFilter = new PrivacyFilter2();
34902
+ console.log(`[AgentGate] Trigger rules: ${triggerEngine.rules.length} (${rulesPath})`);
34769
34903
  const coordinator = new PhaseCoordinator2({
34770
34904
  level: proxyLevel,
34771
34905
  mossClient: {
@@ -34864,10 +34998,13 @@ Usage:
34864
34998
  const { TriggerEngine: TriggerEngine2 } = await Promise.resolve().then(() => (init_trigger(), trigger_exports));
34865
34999
  const { WhitelistEngine: WhitelistEngine2 } = await Promise.resolve().then(() => (init_whitelist(), whitelist_exports));
34866
35000
  const { callAgentMoss: callAgentMoss2, setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
34867
- if (securityUrl) setMossUrl2(securityUrl);
35001
+ const effectiveMossUrl = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL;
35002
+ if (effectiveMossUrl) setMossUrl2(effectiveMossUrl);
34868
35003
  const aggregator = new ProxySessionAggregator2();
34869
- const triggerEngine = new TriggerEngine2();
34870
- const whitelistEngine = new WhitelistEngine2();
35004
+ const rulesPath = resolveRulesPath(rulesPathArg);
35005
+ const triggerEngine = new TriggerEngine2(rulesPath);
35006
+ const whitelistEngine = new WhitelistEngine2(rulesPath);
35007
+ console.log(`[AgentGate] Trigger rules: ${triggerEngine.rules.length} (${rulesPath})`);
34871
35008
  const coordinator = new PhaseCoordinator2({
34872
35009
  level: 3,
34873
35010
  mossClient: { analyzeSync: async (report) => callAgentMoss2(report) },