@kenhkl/agent-gate 0.8.2 → 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.2" : (() => {
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) {
@@ -2110,13 +2193,13 @@ async function dashboardRoute(c) {
2110
2193
  }
2111
2194
  }
2112
2195
  const { readFileSync: readFileSync14, existsSync: existsSync12 } = await import("fs");
2113
- const { resolve: resolve3, dirname: dirname5 } = await import("path");
2196
+ const { resolve: resolve4, dirname: dirname5 } = await import("path");
2114
2197
  const { fileURLToPath } = await import("url");
2115
2198
  const __dirname2 = dirname5(fileURLToPath(importMetaUrl));
2116
2199
  const paths = [
2117
- resolve3(__dirname2, "dashboard.html"),
2118
- resolve3(__dirname2, "../dashboard.html"),
2119
- resolve3(__dirname2, "../src/v1/dashboard.html")
2200
+ resolve4(__dirname2, "dashboard.html"),
2201
+ resolve4(__dirname2, "../dashboard.html"),
2202
+ resolve4(__dirname2, "../src/v1/dashboard.html")
2120
2203
  ];
2121
2204
  const htmlPath = paths.find((p) => existsSync12(p)) || paths[0];
2122
2205
  const html = readFileSync14(htmlPath, "utf-8");
@@ -2348,10 +2431,10 @@ function awaitify(asyncFn, arity) {
2348
2431
  if (typeof args[arity - 1] === "function") {
2349
2432
  return asyncFn.apply(this, args);
2350
2433
  }
2351
- return new Promise((resolve3, reject2) => {
2434
+ return new Promise((resolve4, reject2) => {
2352
2435
  args[arity - 1] = (err, ...cbArgs) => {
2353
2436
  if (err) return reject2(err);
2354
- resolve3(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
2437
+ resolve4(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
2355
2438
  };
2356
2439
  asyncFn.apply(this, args);
2357
2440
  });
@@ -2533,13 +2616,13 @@ function mapSeries(coll, iteratee, callback) {
2533
2616
  return _asyncMap(eachOfSeries$1, coll, iteratee, callback);
2534
2617
  }
2535
2618
  function promiseCallback() {
2536
- let resolve3, reject2;
2619
+ let resolve4, reject2;
2537
2620
  function callback(err, ...args) {
2538
2621
  if (err) return reject2(err);
2539
- resolve3(args.length > 1 ? args : args[0]);
2622
+ resolve4(args.length > 1 ? args : args[0]);
2540
2623
  }
2541
2624
  callback[PROMISE_SYMBOL] = new Promise((res, rej) => {
2542
- resolve3 = res, reject2 = rej;
2625
+ resolve4 = res, reject2 = rej;
2543
2626
  });
2544
2627
  return callback;
2545
2628
  }
@@ -2812,8 +2895,8 @@ function queue$1(worker, concurrency, payload) {
2812
2895
  });
2813
2896
  }
2814
2897
  if (rejectOnError || !callback) {
2815
- return new Promise((resolve3, reject2) => {
2816
- res = resolve3;
2898
+ return new Promise((resolve4, reject2) => {
2899
+ res = resolve4;
2817
2900
  rej = reject2;
2818
2901
  });
2819
2902
  }
@@ -2852,10 +2935,10 @@ function queue$1(worker, concurrency, payload) {
2852
2935
  }
2853
2936
  const eventMethod = (name) => (handler) => {
2854
2937
  if (!handler) {
2855
- return new Promise((resolve3, reject2) => {
2938
+ return new Promise((resolve4, reject2) => {
2856
2939
  once2(name, (err, data) => {
2857
2940
  if (err) return reject2(err);
2858
- resolve3(data);
2941
+ resolve4(data);
2859
2942
  });
2860
2943
  });
2861
2944
  }
@@ -25778,7 +25861,7 @@ var require_path_arg = __commonJS({
25778
25861
  "use strict";
25779
25862
  init_cjs_shims();
25780
25863
  var platform2 = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform;
25781
- var { resolve: resolve3, parse: parse2 } = require("path");
25864
+ var { resolve: resolve4, parse: parse2 } = require("path");
25782
25865
  var pathArg = (path11) => {
25783
25866
  if (/\0/.test(path11)) {
25784
25867
  throw Object.assign(
@@ -25789,7 +25872,7 @@ var require_path_arg = __commonJS({
25789
25872
  }
25790
25873
  );
25791
25874
  }
25792
- path11 = resolve3(path11);
25875
+ path11 = resolve4(path11);
25793
25876
  if (platform2 === "win32") {
25794
25877
  const badWinChars = /[*|"<>?:]/;
25795
25878
  const { root } = parse2(path11);
@@ -28824,7 +28907,7 @@ load();setInterval(load,5000);
28824
28907
  });
28825
28908
  return callback(null);
28826
28909
  });
28827
- return new Promise((resolve3, reject2) => {
28910
+ return new Promise((resolve4, reject2) => {
28828
28911
  const proxy = this._mitmProxy;
28829
28912
  if (!proxy) {
28830
28913
  reject2(new Error("MITM proxy not initialized"));
@@ -28846,7 +28929,7 @@ load();setInterval(load,5000);
28846
28929
  console.log(`[AgentGate] SSL CA dir: ${caDir}`);
28847
28930
  console.log(`[AgentGate] Set HTTPS_PROXY=http://${this._options.host}:${this._options.port}`);
28848
28931
  this._startDashboard();
28849
- resolve3();
28932
+ resolve4();
28850
28933
  }
28851
28934
  );
28852
28935
  });
@@ -29280,7 +29363,7 @@ var init_coordinator = __esm({
29280
29363
  init_verdict();
29281
29364
  init_repository();
29282
29365
  init_multi_session();
29283
- PhaseCoordinator = class {
29366
+ PhaseCoordinator = class _PhaseCoordinator {
29284
29367
  level;
29285
29368
  mossClient;
29286
29369
  aggregator;
@@ -29299,10 +29382,22 @@ var init_coordinator = __esm({
29299
29382
  cleanupRunning = false;
29300
29383
  /** 低频回顾触发计数(每 N 条落库触发一次 /api/v1/review)。 */
29301
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;
29302
29397
  constructor(opts = {}) {
29303
29398
  this.level = opts.level ?? 1;
29304
- if (this.level !== 1 && this.level !== 2) {
29305
- throw new Error(`level must be 1 or 2, got ${this.level}`);
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}`);
29306
29401
  }
29307
29402
  this.mossClient = opts.mossClient;
29308
29403
  this.aggregator = opts.sessionAggregator;
@@ -29478,21 +29573,57 @@ var init_coordinator = __esm({
29478
29573
  }
29479
29574
  // ── Public API: L3 side (fire-and-forget) ─────────────────────────────────
29480
29575
  async onL3Event(sessionId, event) {
29481
- console.log(
29482
- `[PhaseCoordinator][L3]: standalone L3 event session=${sessionId.slice(0, 8)}`
29483
- );
29484
- if (this.mossClient) {
29485
- try {
29486
- const report = this._buildL3Report(sessionId, event);
29487
- await this._sendToMoss(report);
29488
- console.log(
29489
- `[PhaseCoordinator][L3]: AgentMoss analysis sent (session=${sessionId.slice(0, 8)})`
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`
29490
29595
  );
29491
- } 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();
29492
29609
  console.error("[PhaseCoordinator][L3]: AgentMoss request failed:", err);
29493
29610
  }
29611
+ } finally {
29612
+ this.l3Inflight--;
29494
29613
  }
29495
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
+ }
29496
29627
  // ── Phase 2: AgentMoss submission ────────────────────────────────────────
29497
29628
  async executePhase2(sessionId, event, pendingAction) {
29498
29629
  try {
@@ -29509,7 +29640,7 @@ var init_coordinator = __esm({
29509
29640
  event = this.privacyFilter.apply(event);
29510
29641
  }
29511
29642
  if (this.mossClient) {
29512
- const report = this.buildMossReport(session, event, triggerMatches);
29643
+ const report = this.buildMossReport(sessionIdActual, session, event, triggerMatches);
29513
29644
  try {
29514
29645
  const response = await this.mossClient.analyzeSync(report);
29515
29646
  let decision = response.decision ?? "Allow";
@@ -29655,7 +29786,7 @@ var init_coordinator = __esm({
29655
29786
  return [];
29656
29787
  }
29657
29788
  }
29658
- buildMossReport(session, event, triggerMatches) {
29789
+ buildMossReport(sessionId, session, event, triggerMatches) {
29659
29790
  const actionHistory = [];
29660
29791
  if (session?.events) {
29661
29792
  for (const evt of session.events) {
@@ -29690,38 +29821,30 @@ var init_coordinator = __esm({
29690
29821
  const currentTarget = event.target ?? {};
29691
29822
  const currentPayload = event.payload ?? {};
29692
29823
  const match0 = triggerMatches[0];
29693
- const sessionDict = session ? {
29694
- id: session.id,
29695
- event_count: session.events.length,
29696
- prompt_count: session.prompts?.length ?? 0,
29697
- inferred_agent_type: event.agentType ?? "unknown"
29698
- } : {};
29824
+ const nextActionType = String(currentAction.toolName ?? currentAction.tool_name ?? "").trim() || "unknown";
29825
+ const nextActionDetail = String(
29826
+ currentTarget.command ?? currentAction.argumentsRaw ?? ""
29827
+ ).slice(0, 2e3);
29699
29828
  return {
29700
29829
  trigger_type: match0?.rule.name ?? "proxy",
29701
29830
  trigger_rule: match0?.rule.name ?? "",
29702
29831
  trigger_detail: match0?.detail ?? "",
29703
- session: sessionDict,
29832
+ session_id: session?.id || sessionId,
29833
+ prompt_session: currentPromptText,
29834
+ prompt_history: promptHistory.map((text) => ({ text, actions: [] })),
29704
29835
  behavior_sequence: [],
29705
29836
  payload_sequences: [],
29706
29837
  action_history: actionHistory,
29707
- session_history: this._buildSessionHistory(session?.id ?? ""),
29708
- prompt_history: promptHistory,
29709
- current_prompt: currentPromptText,
29710
- current_action: {
29711
- tool_name: currentAction.toolName ?? "",
29712
- arguments_raw: currentAction.argumentsRaw ?? "{}",
29713
- tool_call_id: currentAction.toolCallId ?? ""
29714
- },
29715
- current_target: {
29716
- command: currentTarget.command ?? "",
29717
- file_path: currentTarget.filePath ?? "",
29718
- arguments: currentTarget.arguments ?? {}
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 } : {}
29719
29847
  },
29720
- prompt: {
29721
- system_prompt: currentPayload.systemPrompt ?? "",
29722
- user_prompt: currentPromptText
29723
- },
29724
- metadata: { stateful_incremental: true },
29725
29848
  source_layers: event.source_layers ?? ["l1"],
29726
29849
  level: this.level
29727
29850
  };
@@ -29737,7 +29860,7 @@ var init_coordinator = __esm({
29737
29860
  const response = await this.mossClient.analyzeSync(report);
29738
29861
  const decision = response.decision ?? "Allow";
29739
29862
  if (decision === "Deny" && this.onBlock) {
29740
- const shouldBlock = this.onBlock(report.session.id, []);
29863
+ const shouldBlock = this.onBlock(report.session_id, []);
29741
29864
  if (!shouldBlock) {
29742
29865
  return "Allow";
29743
29866
  }
@@ -29785,28 +29908,22 @@ var init_coordinator = __esm({
29785
29908
  trigger_type: "l2_standalone",
29786
29909
  trigger_rule: "l2_standalone",
29787
29910
  trigger_detail: `command: ${action.l2Command}`,
29788
- session: sessionDict,
29911
+ session_id: session?.id || sessionId,
29912
+ prompt_session: currentPromptText,
29913
+ prompt_history: promptHistory.map((text) => ({ text, actions: [] })),
29789
29914
  behavior_sequence: [],
29790
29915
  payload_sequences: [],
29791
29916
  action_history: actionHistory,
29792
- session_history: this._buildSessionHistory(sessionId),
29793
- prompt_history: promptHistory,
29794
- current_prompt: currentPromptText,
29795
- current_action: {
29796
- tool_name: action.toolName,
29797
- arguments_raw: JSON.stringify(action.l2Args ?? []),
29798
- tool_call_id: action.toolCallId
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
- current_target: {
29801
- command: action.l2Command,
29802
- file_path: "",
29803
- arguments: {}
29804
- },
29805
- prompt: {
29806
- system_prompt: "",
29807
- user_prompt: currentPromptText
29808
- },
29809
- 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 },
29810
29927
  source_layers: ["l2"],
29811
29928
  level: this.level
29812
29929
  };
@@ -29848,37 +29965,30 @@ var init_coordinator = __esm({
29848
29965
  }
29849
29966
  const l3Action = event.action ?? {};
29850
29967
  const l3Target = event.target ?? {};
29851
- const sessionDict = session ? {
29852
- id: session.id,
29853
- event_count: session.events.length,
29854
- prompt_count: session.prompts?.length ?? 0,
29855
- inferred_agent_type: event.agentType ?? "unknown"
29856
- } : {};
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);
29857
29974
  return {
29858
29975
  trigger_type: "l3_event",
29859
29976
  trigger_rule: "l3_event",
29860
29977
  trigger_detail: `l3: ${JSON.stringify(event).slice(0, 200)}`,
29861
- session: sessionDict,
29978
+ session_id: session?.id || sessionId,
29979
+ prompt_session: currentPromptText,
29980
+ prompt_history: promptHistory.map((text) => ({ text, actions: [] })),
29862
29981
  behavior_sequence: [],
29863
29982
  payload_sequences: [],
29864
29983
  action_history: actionHistory,
29865
- session_history: this._buildSessionHistory(sessionId),
29866
- prompt_history: promptHistory,
29867
- current_prompt: currentPromptText,
29868
- current_action: {
29869
- tool_name: String(l3Action.toolName ?? ""),
29870
- arguments_raw: String(l3Action.argumentsRaw ?? "{}"),
29871
- tool_call_id: String(l3Action.toolCallId ?? "")
29872
- },
29873
- current_target: {
29874
- command: String(l3Target.command ?? ""),
29875
- file_path: String(l3Target.filePath ?? ""),
29876
- arguments: l3Target.arguments ?? {}
29877
- },
29878
- prompt: {
29879
- system_prompt: "",
29880
- user_prompt: currentPromptText
29881
- },
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
+ ),
29882
29992
  metadata: { stateful_incremental: true },
29883
29993
  source_layers: ["l3"],
29884
29994
  level: this.level
@@ -30202,13 +30312,13 @@ var init_server3 = __esm({
30202
30312
  });
30203
30313
  }
30204
30314
  start() {
30205
- return new Promise((resolve3) => {
30315
+ return new Promise((resolve4) => {
30206
30316
  this.server = import_node_http2.default.createServer((req, res) => this.handleRequest(req, res));
30207
30317
  this.server.listen(this.port, this.host, () => {
30208
30318
  console.log(`[Gateway] AgentGate API Gateway listening on ${this.host}:${this.port}`);
30209
30319
  console.log(`[Gateway] Routing: multi-provider (${this.router.routeCount} routes)`);
30210
30320
  console.log(`[Gateway] Dashboard: http://${this.host}:${this.port}`);
30211
- resolve3();
30321
+ resolve4();
30212
30322
  });
30213
30323
  });
30214
30324
  }
@@ -30294,7 +30404,7 @@ var init_server3 = __esm({
30294
30404
  }
30295
30405
  }
30296
30406
  forward(route, body, method, clientHeaders) {
30297
- return new Promise((resolve3, reject2) => {
30407
+ return new Promise((resolve4, reject2) => {
30298
30408
  const url = new import_node_url2.URL(route.upstreamUrl);
30299
30409
  const isHttps = url.protocol === "https:";
30300
30410
  const transport = isHttps ? import_node_https.default : import_node_http2.default;
@@ -30343,7 +30453,7 @@ var init_server3 = __esm({
30343
30453
  respHeaders[key] = Array.isArray(val) ? val.join(", ") : val;
30344
30454
  }
30345
30455
  }
30346
- resolve3({
30456
+ resolve4({
30347
30457
  statusCode: upstreamRes.statusCode ?? 502,
30348
30458
  headers: respHeaders,
30349
30459
  body: respBody
@@ -30436,11 +30546,11 @@ var init_server3 = __esm({
30436
30546
  }
30437
30547
  // ---- Dashboard & API ----
30438
30548
  readBody(req) {
30439
- return new Promise((resolve3) => {
30549
+ return new Promise((resolve4) => {
30440
30550
  const chunks = [];
30441
30551
  req.on("data", (chunk) => chunks.push(chunk));
30442
- req.on("end", () => resolve3(Buffer.concat(chunks)));
30443
- req.on("error", () => resolve3(Buffer.alloc(0)));
30552
+ req.on("end", () => resolve4(Buffer.concat(chunks)));
30553
+ req.on("error", () => resolve4(Buffer.alloc(0)));
30444
30554
  });
30445
30555
  }
30446
30556
  json(res, status, data) {
@@ -32381,7 +32491,7 @@ __export(http_proxy_exports, {
32381
32491
  createHttpProxy: () => createHttpProxy
32382
32492
  });
32383
32493
  function forwardToUpstream(upstreamUrl, msg) {
32384
- return new Promise((resolve3) => {
32494
+ return new Promise((resolve4) => {
32385
32495
  const url = new URL(upstreamUrl);
32386
32496
  const body = JSON.stringify(msg);
32387
32497
  const req = http3.request(
@@ -32401,12 +32511,12 @@ function forwardToUpstream(upstreamUrl, msg) {
32401
32511
  res.setEncoding("utf8");
32402
32512
  res.on("data", (c) => data += c);
32403
32513
  res.on("end", () => {
32404
- 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"] ?? "" });
32405
32515
  });
32406
32516
  }
32407
32517
  );
32408
32518
  req.on("error", () => {
32409
- resolve3({ status: 503, body: "", contentType: "" });
32519
+ resolve4({ status: 503, body: "", contentType: "" });
32410
32520
  });
32411
32521
  req.write(body);
32412
32522
  req.end();
@@ -32474,9 +32584,9 @@ function createHttpProxy(opts) {
32474
32584
  }
32475
32585
  }
32476
32586
  });
32477
- return new Promise((resolve3) => {
32587
+ return new Promise((resolve4) => {
32478
32588
  server.listen(listenPort, listenHost, () => {
32479
- resolve3({
32589
+ resolve4({
32480
32590
  server,
32481
32591
  close: () => new Promise((res) => {
32482
32592
  server.close(() => res());
@@ -32503,7 +32613,7 @@ __export(sse_proxy_exports, {
32503
32613
  rewriteEndpoint: () => rewriteEndpoint
32504
32614
  });
32505
32615
  function postToUpstream(upstreamUrl, msg) {
32506
- return new Promise((resolve3) => {
32616
+ return new Promise((resolve4) => {
32507
32617
  const url = new URL(upstreamUrl);
32508
32618
  const body = JSON.stringify(msg);
32509
32619
  const req = http4.request(
@@ -32522,10 +32632,10 @@ function postToUpstream(upstreamUrl, msg) {
32522
32632
  let data = "";
32523
32633
  res.setEncoding("utf8");
32524
32634
  res.on("data", (c) => data += c);
32525
- res.on("end", () => resolve3({ status: res.statusCode ?? 500, body: data }));
32635
+ res.on("end", () => resolve4({ status: res.statusCode ?? 500, body: data }));
32526
32636
  }
32527
32637
  );
32528
- req.on("error", () => resolve3({ status: 503, body: "" }));
32638
+ req.on("error", () => resolve4({ status: 503, body: "" }));
32529
32639
  req.write(body);
32530
32640
  req.end();
32531
32641
  });
@@ -32546,11 +32656,11 @@ function createSseProxy(opts) {
32546
32656
  Connection: "keep-alive"
32547
32657
  });
32548
32658
  try {
32549
- const upstreamRes = await new Promise((resolve3, reject2) => {
32659
+ const upstreamRes = await new Promise((resolve4, reject2) => {
32550
32660
  const url = new URL(upstreamUrl);
32551
32661
  const ureq = http4.get(
32552
32662
  { host: url.hostname, port: url.port || 80, path: url.pathname + (url.search ?? "") },
32553
- (r) => resolve3(r)
32663
+ (r) => resolve4(r)
32554
32664
  );
32555
32665
  ureq.on("error", reject2);
32556
32666
  });
@@ -32630,9 +32740,9 @@ function createSseProxy(opts) {
32630
32740
  res.writeHead(405);
32631
32741
  res.end("Method Not Allowed");
32632
32742
  });
32633
- return new Promise((resolve3) => {
32743
+ return new Promise((resolve4) => {
32634
32744
  server.listen(listenPort, listenHost, () => {
32635
- resolve3({
32745
+ resolve4({
32636
32746
  server,
32637
32747
  close: () => new Promise((res) => {
32638
32748
  server.close(() => res());
@@ -32798,10 +32908,10 @@ async function scanProcesses() {
32798
32908
  const args = isWin ? ["process", "get", "ProcessId,ParentProcessId,Name,CommandLine", "/format:csv"] : ["-eo", "pid,ppid,comm,args"];
32799
32909
  try {
32800
32910
  const { execFile } = await import("child_process");
32801
- return new Promise((resolve3) => {
32911
+ return new Promise((resolve4) => {
32802
32912
  execFile(cmd, args, { timeout: 5e3 }, (err, stdout) => {
32803
32913
  if (err || !stdout) {
32804
- resolve3([]);
32914
+ resolve4([]);
32805
32915
  return;
32806
32916
  }
32807
32917
  const procs = [];
@@ -32829,7 +32939,7 @@ async function scanProcesses() {
32829
32939
  }
32830
32940
  }
32831
32941
  }
32832
- resolve3(procs);
32942
+ resolve4(procs);
32833
32943
  });
32834
32944
  });
32835
32945
  } catch {
@@ -32855,7 +32965,7 @@ var init_wrapper = __esm({
32855
32965
  this.options = options;
32856
32966
  }
32857
32967
  async run(command, args = []) {
32858
- return new Promise((resolve3, reject2) => {
32968
+ return new Promise((resolve4, reject2) => {
32859
32969
  try {
32860
32970
  console.log(`[PTY] Starting: ${command} ${args.join(" ")}`);
32861
32971
  this.ptyProcess = pty.spawn(command, args, {
@@ -32883,7 +32993,7 @@ var init_wrapper = __esm({
32883
32993
  if (this.options.onExit) {
32884
32994
  this.options.onExit(exitCode, signal);
32885
32995
  }
32886
- resolve3(exitCode);
32996
+ resolve4(exitCode);
32887
32997
  });
32888
32998
  this.startProcessMonitor();
32889
32999
  } catch (error) {
@@ -33278,10 +33388,10 @@ var init_launcher = __esm({
33278
33388
  [AgentGate] CONFIRM: ${toolCall2.toolName} ${cmd}`);
33279
33389
  const readline2 = await import("readline");
33280
33390
  const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
33281
- return new Promise((resolve3) => {
33391
+ return new Promise((resolve4) => {
33282
33392
  rl.question(" Allow this action? [y/N] ", (answer) => {
33283
33393
  rl.close();
33284
- resolve3(answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes");
33394
+ resolve4(answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes");
33285
33395
  });
33286
33396
  });
33287
33397
  }
@@ -34081,6 +34191,19 @@ var path10 = __toESM(require("path"));
34081
34191
  var import_yaml3 = require("yaml");
34082
34192
  init_version();
34083
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
+ }
34084
34207
  async function main() {
34085
34208
  const args = process.argv.slice(2);
34086
34209
  const command = args[0];
@@ -34687,6 +34810,7 @@ Usage:
34687
34810
  let logLevel = "info";
34688
34811
  let denyAction = "inform";
34689
34812
  let securityUrl;
34813
+ let rulesPathArg;
34690
34814
  for (let i = 1; i < args.length; i++) {
34691
34815
  if (args[i] === "--level" && args[i + 1]) level = args[++i];
34692
34816
  else if (args[i] === "--upstream" && args[i + 1]) upstream = args[++i];
@@ -34696,6 +34820,7 @@ Usage:
34696
34820
  else if (args[i] === "--log-level" && args[i + 1]) logLevel = args[++i];
34697
34821
  else if (args[i] === "--deny-action" && args[i + 1]) denyAction = args[++i];
34698
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];
34699
34824
  }
34700
34825
  const validLevels = ["l1", "l2", "l3", "l1+l2", "l1+l3", "l2+l3", "l1+l2+l3"];
34701
34826
  if (!validLevels.includes(level)) {
@@ -34720,7 +34845,7 @@ Usage:
34720
34845
  }
34721
34846
  }
34722
34847
  }
34723
- 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";
34724
34849
  let mossConnected = false;
34725
34850
  try {
34726
34851
  const resp = await (0, import_node_fetch2.default)(`${mossUrl2}/api/v1/health`, { timeout: 3e3 });
@@ -34769,11 +34894,12 @@ Usage:
34769
34894
  const effectiveMossUrl = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL;
34770
34895
  if (effectiveMossUrl) setMossUrl2(effectiveMossUrl);
34771
34896
  const proxyLevel = hasL2 ? 2 : 1;
34772
- const rulesPath = "../config/trigger_rules.yaml";
34897
+ const rulesPath = resolveRulesPath(rulesPathArg);
34773
34898
  const aggregator = new ProxySessionAggregator2();
34774
34899
  const triggerEngine = new TriggerEngine2(rulesPath);
34775
34900
  const whitelistEngine = new WhitelistEngine2(rulesPath);
34776
34901
  const privacyFilter = new PrivacyFilter2();
34902
+ console.log(`[AgentGate] Trigger rules: ${triggerEngine.rules.length} (${rulesPath})`);
34777
34903
  const coordinator = new PhaseCoordinator2({
34778
34904
  level: proxyLevel,
34779
34905
  mossClient: {
@@ -34872,10 +34998,13 @@ Usage:
34872
34998
  const { TriggerEngine: TriggerEngine2 } = await Promise.resolve().then(() => (init_trigger(), trigger_exports));
34873
34999
  const { WhitelistEngine: WhitelistEngine2 } = await Promise.resolve().then(() => (init_whitelist(), whitelist_exports));
34874
35000
  const { callAgentMoss: callAgentMoss2, setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
34875
- if (securityUrl) setMossUrl2(securityUrl);
35001
+ const effectiveMossUrl = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL;
35002
+ if (effectiveMossUrl) setMossUrl2(effectiveMossUrl);
34876
35003
  const aggregator = new ProxySessionAggregator2();
34877
- const triggerEngine = new TriggerEngine2();
34878
- 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})`);
34879
35008
  const coordinator = new PhaseCoordinator2({
34880
35009
  level: 3,
34881
35010
  mossClient: { analyzeSync: async (report) => callAgentMoss2(report) },