@kenhkl/agent-moss 0.17.37 → 0.17.39

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/README.md CHANGED
@@ -64,6 +64,11 @@ const result = await resp.json();
64
64
  ├── 完全安全 (15 bash 模式 + 6 action types) → 跳过 L2+L3
65
65
  └── 只读敏感 (15 bash 模式 + 8 action types) → 跳过 L3
66
66
 
67
+ 专项引擎
68
+ ├── script-engine: Shell/Python 后端 → 可达内容切片 + 递归脚本链追踪
69
+ │ (深度/循环/字节预算;解析失败回退全文本,fail-closed)
70
+ └── formal-engine: 多 session 行为图 + 跨会话组合链/数据流验证 + 有状态增量
71
+
67
72
  层1: 特征匹配静态检测 (<1ms)
68
73
  ├── 危险命令正则: 48 个模式(rm 分级检测,sudo 只拦截危险命令,nmap/masscan/zmap 检测)
69
74
  ├── → high/critical → 直接 Deny
@@ -154,6 +159,8 @@ ts/src/
154
159
  ├── logic-rules.ts # 层2: 8 条规则 + 20 敏感路径
155
160
  ├── llm-analyzer.ts # 层3: LLM 分析 (缓存 + 重试 + fail-closed)
156
161
  ├── script-analyzer.ts # 脚本内容预扫描 (18 个可疑模式)
162
+ ├── script-engine/ # 脚本分析引擎 (Shell/Python → IR + 递归脚本链)
163
+ ├── formal-engine/ # 形式化引擎 (L2.2 组合链 + 有状态增量 + 链状态)
157
164
  ├── skill-loader.ts # Skill 加载与关键词匹配 (12 个 Skill)
158
165
  └── template-loader.ts # Prompt 模板加载 (3 个模板)
159
166
  ```
package/dist/cli.js CHANGED
@@ -1130,7 +1130,7 @@ function logRoots() {
1130
1130
  }
1131
1131
  function reviewRoots() {
1132
1132
  const roots = [join4(homeDir(), ".local", "share", "agent_gate")];
1133
- for (const name of ["AGENT_GATE_DB", "AGENT_GATE_JSON_PATH"]) {
1133
+ for (const name of ["AGENT_GATE_DB", "AGENT_GATE_JSON_PATH", "AGENT_GATE_DATA_DIR"]) {
1134
1134
  const v = env(name);
1135
1135
  if (v) roots.push(existsSync3(v) && lstatSync(v).isDirectory() ? v : dirname2(v));
1136
1136
  }
@@ -5982,7 +5982,19 @@ function checkHomeDeletion(actionType, actionDetail) {
5982
5982
  }
5983
5983
  }
5984
5984
  const assigned = {};
5985
- for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
5985
+ const anchored = new RegExp(HOME_ASSIGN_RE.source, "iy");
5986
+ const nameRe = /[A-Za-z_][A-Za-z0-9_]*/gi;
5987
+ let nm;
5988
+ while ((nm = nameRe.exec(actionDetail)) !== null) {
5989
+ anchored.lastIndex = nm.index;
5990
+ const m = anchored.exec(actionDetail);
5991
+ if (m) {
5992
+ assigned[m[1]] = m[2];
5993
+ nameRe.lastIndex = anchored.lastIndex;
5994
+ } else {
5995
+ nameRe.lastIndex = nm.index + nm[0].length;
5996
+ }
5997
+ }
5986
5998
  for (const [varName, path9] of Object.entries(assigned)) {
5987
5999
  if (!isHomeValue(path9)) continue;
5988
6000
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
@@ -6249,7 +6261,7 @@ var init_heuristic = __esm({
6249
6261
  SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
6250
6262
  SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
6251
6263
  HOME_TARGET_RE = /(?:^|[\s="'($])(?:~|(?:\$home|\$\{home\}))(?:\/(?:\.\*|\*|\.)?)?(?=[\s"';}|&)]|$)/i;
6252
- HOME_ASSIGN_RE = /([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(~[A-Za-z0-9_./-]*|\$HOME[A-Za-z0-9_./-]*|\$\{HOME\}[A-Za-z0-9_./-]*|\/home\/[^\s;|&]+|\$\((?:[^()]|\([^()]*\))*\))(?=\s|;|$|\||&)/gi;
6264
+ HOME_ASSIGN_RE = /([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(~[A-Za-z0-9_./-]*|\$HOME[A-Za-z0-9_./-]*|\$\{HOME\}[A-Za-z0-9_./-]*|\/home\/[^\s;|&]+|\$\((?:[^()]|\([^()]*\))*\))(?=\s|;|$|\||&)/i;
6253
6265
  }
6254
6266
  });
6255
6267
 
@@ -12002,6 +12014,76 @@ function lifecycleFor(detail, stage, isError) {
12002
12014
  if (detail.includes(">>") || detail.includes(">")) return "alive";
12003
12015
  return "";
12004
12016
  }
12017
+ function resolveMaxNodes() {
12018
+ const n = Number.parseInt(process.env.AGENT_MOSS_CHAIN_MAX_NODES || "100000", 10);
12019
+ return Number.isFinite(n) && n > 0 ? n : 1e5;
12020
+ }
12021
+ function resolveRetainNodes() {
12022
+ const raw = process.env.AGENT_MOSS_CHAIN_RETAIN_NODES || "";
12023
+ const def = Math.max(1, Math.floor(MAX_NODES / 2));
12024
+ const n = raw ? Number.parseInt(raw, 10) : def;
12025
+ const safe2 = Number.isFinite(n) && n > 0 ? n : def;
12026
+ return Math.max(1, Math.min(safe2, MAX_NODES - 1));
12027
+ }
12028
+ function envInt3(name, def) {
12029
+ const n = Number.parseInt(process.env[name] || "", 10);
12030
+ return Number.isFinite(n) && n >= 0 ? n : def;
12031
+ }
12032
+ function cleanupChainArchives(dir, maxBytes = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_MAX_MB", 512) * 1024 * 1024, maxAgeDays = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_MAX_AGE_DAYS", 0)) {
12033
+ let files = [];
12034
+ try {
12035
+ files = fs5.readdirSync(dir).filter((f) => f.startsWith("chain-nodes-") && f.endsWith(".jsonl.gz")).map((f) => path6.join(dir, f)).sort((a, b) => fs5.statSync(a).mtimeMs - fs5.statSync(b).mtimeMs);
12036
+ } catch {
12037
+ return { deleted: 0, files: 0, bytes: 0 };
12038
+ }
12039
+ let removed = 0;
12040
+ if (maxAgeDays > 0) {
12041
+ const cutoff = Date.now() - maxAgeDays * 864e5;
12042
+ files = files.filter((p) => {
12043
+ try {
12044
+ if (fs5.statSync(p).mtimeMs < cutoff) {
12045
+ fs5.unlinkSync(p);
12046
+ removed += 1;
12047
+ return false;
12048
+ }
12049
+ } catch {
12050
+ }
12051
+ return true;
12052
+ });
12053
+ }
12054
+ let total = files.reduce((n, p) => {
12055
+ try {
12056
+ return n + fs5.statSync(p).size;
12057
+ } catch {
12058
+ return n;
12059
+ }
12060
+ }, 0);
12061
+ if (maxBytes > 0) {
12062
+ for (let i = 0; i < files.length; i++) {
12063
+ if (total <= maxBytes) break;
12064
+ if (i === files.length - 1) break;
12065
+ const p = files[i];
12066
+ try {
12067
+ const size = fs5.statSync(p).size;
12068
+ fs5.unlinkSync(p);
12069
+ total -= size;
12070
+ removed += 1;
12071
+ } catch {
12072
+ }
12073
+ }
12074
+ }
12075
+ let remainFiles = 0;
12076
+ let remainBytes = 0;
12077
+ try {
12078
+ for (const f of fs5.readdirSync(dir)) {
12079
+ if (!f.startsWith("chain-nodes-") || !f.endsWith(".jsonl.gz")) continue;
12080
+ remainFiles += 1;
12081
+ remainBytes += fs5.statSync(path6.join(dir, f)).size;
12082
+ }
12083
+ } catch {
12084
+ }
12085
+ return { deleted: removed, files: remainFiles, bytes: remainBytes };
12086
+ }
12005
12087
  var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, STAGES_PATTERNS, CHAINS, COMMON_DIR_RESOURCES2, MAX_NODES, StatefulChainTracker;
12006
12088
  var init_stateful = __esm({
12007
12089
  "src/engine/formal-engine/stateful.ts"() {
@@ -12033,7 +12115,7 @@ var init_stateful = __esm({
12033
12115
  "/data",
12034
12116
  "/storage"
12035
12117
  ]);
12036
- MAX_NODES = 1e5;
12118
+ MAX_NODES = resolveMaxNodes();
12037
12119
  StatefulChainTracker = class _StatefulChainTracker {
12038
12120
  /** 本地接收时刻(实时路径无 called_at 时的兜底时间戳,ISO)。 */
12039
12121
  static now() {
@@ -12140,7 +12222,7 @@ var init_stateful = __esm({
12140
12222
  * 派生缓存不是原始历史存储;归档失败抛异常,调用方不得丢状态。
12141
12223
  */
12142
12224
  rotate(archiveDir, retain) {
12143
- const keep = Math.max(1, Math.min(retain ?? Math.floor(MAX_NODES / 2), MAX_NODES - 1));
12225
+ const keep = Math.max(1, Math.min(retain ?? resolveRetainNodes(), MAX_NODES - 1));
12144
12226
  if (this.nodes_.length <= keep) return { archived: 0, file: "" };
12145
12227
  const old = this.nodes_.slice(0, this.nodes_.length - keep);
12146
12228
  const kept = this.nodes_.slice(-keep);
@@ -12150,6 +12232,16 @@ var init_stateful = __esm({
12150
12232
  const file = path6.join(dir, `chain-nodes-${safeAgent}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.jsonl.gz`);
12151
12233
  const payload = old.map((n) => JSON.stringify(n)).join("\n") + "\n";
12152
12234
  fs5.writeFileSync(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
12235
+ try {
12236
+ const c = cleanupChainArchives(dir);
12237
+ if (c.deleted > 0) {
12238
+ console.error(
12239
+ `[AgentMoss] chain-archive \u6E05\u7406: \u5220\u9664 ${c.deleted} \u4E2A\u65E7\u5F52\u6863\uFF08\u5269\u4F59 ${c.files} \u4E2A / ${c.bytes} \u5B57\u8282\uFF09`
12240
+ );
12241
+ }
12242
+ } catch (e) {
12243
+ console.error(`[AgentMoss] chain-archive \u6E05\u7406\u5931\u8D25\uFF08\u7EE7\u7EED\uFF09: ${e?.message ?? e}`);
12244
+ }
12153
12245
  this.nodes_ = [];
12154
12246
  this.ptr = {};
12155
12247
  this.tainted.clear();
@@ -13395,7 +13487,7 @@ var init_types = __esm({
13395
13487
 
13396
13488
  // src/infra/policy-cache.ts
13397
13489
  import { createHash as createHash5 } from "crypto";
13398
- import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
13490
+ import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
13399
13491
  import { tmpdir as tmpdir3 } from "os";
13400
13492
  import { join as join18 } from "path";
13401
13493
  function cacheDir() {
@@ -13489,7 +13581,7 @@ var init_policy_cache = __esm({
13489
13581
  invalidate(sessionId, promptSession) {
13490
13582
  this.memory.delete(this.cacheKey(sessionId, promptSession));
13491
13583
  try {
13492
- unlinkSync4(this.cacheFilePath(sessionId, promptSession));
13584
+ unlinkSync5(this.cacheFilePath(sessionId, promptSession));
13493
13585
  } catch {
13494
13586
  }
13495
13587
  }
@@ -13501,9 +13593,9 @@ var init_policy_cache = __esm({
13501
13593
  const dir = join18(cacheDir(), safeSessionId);
13502
13594
  try {
13503
13595
  if (existsSync17(dir)) {
13504
- for (const f of readdirSync5(dir)) {
13596
+ for (const f of readdirSync6(dir)) {
13505
13597
  try {
13506
- unlinkSync4(join18(dir, f));
13598
+ unlinkSync5(join18(dir, f));
13507
13599
  } catch {
13508
13600
  }
13509
13601
  }
@@ -13516,10 +13608,10 @@ var init_policy_cache = __esm({
13516
13608
  this.memory.clear();
13517
13609
  try {
13518
13610
  if (existsSync17(cacheDir())) {
13519
- for (const sessionDir of readdirSync5(cacheDir())) {
13611
+ for (const sessionDir of readdirSync6(cacheDir())) {
13520
13612
  const dir = join18(cacheDir(), sessionDir);
13521
13613
  try {
13522
- for (const f of readdirSync5(dir)) unlinkSync4(join18(dir, f));
13614
+ for (const f of readdirSync6(dir)) unlinkSync5(join18(dir, f));
13523
13615
  rmdirSync(dir);
13524
13616
  } catch {
13525
13617
  }
@@ -14506,8 +14598,10 @@ async function analyzeRoute(c) {
14506
14598
  }
14507
14599
  const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
14508
14600
  if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
14601
+ const recvAt = c.get?.("recvAt");
14602
+ const queueMs = typeof recvAt === "number" ? Math.max(0, t0 - recvAt) : 0;
14509
14603
  console.warn(
14510
- `[AgentMoss] \u6162\u8BF7\u6C42: ${Math.round(durationMs)}ms\uFF08\u9608\u503C ${slowMs}ms\uFF09 action_type=${req.a_next.action_type} agent=${agentId || "-"} decision=${result.decision}`
14604
+ `[AgentMoss] \u6162\u8BF7\u6C42: \u603B ${Math.round(durationMs)}ms = \u6392\u961F ${Math.round(queueMs)}ms + \u8BA1\u7B97 ${Math.round(durationMs - queueMs)}ms\uFF08\u9608\u503C ${slowMs}ms\uFF09 action_type=${req.a_next.action_type} agent=${agentId || "-"} decision=${result.decision}`
14511
14605
  );
14512
14606
  }
14513
14607
  try {
@@ -14882,7 +14976,7 @@ var init_routes = __esm({
14882
14976
  // src/console/router.ts
14883
14977
  import { Hono } from "hono";
14884
14978
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
14885
- import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
14979
+ import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync6 } from "fs";
14886
14980
  import { join as join22, dirname as dirname14 } from "path";
14887
14981
  import { fileURLToPath as fileURLToPath11 } from "url";
14888
14982
  function getConsoleToken() {
@@ -15227,7 +15321,7 @@ function createConsoleRouter() {
15227
15321
  const defaults = generateSourceDefaults();
15228
15322
  try {
15229
15323
  const p = getRuntimeConfigPath();
15230
- if (existsSync20(p)) unlinkSync5(p);
15324
+ if (existsSync20(p)) unlinkSync6(p);
15231
15325
  } catch {
15232
15326
  }
15233
15327
  return c.json(withL22View(defaults));
@@ -15369,6 +15463,10 @@ function createApp() {
15369
15463
  enforceRulesContract();
15370
15464
  hardenExistingPaths();
15371
15465
  const app = new Hono2();
15466
+ app.use("*", async (c, next) => {
15467
+ c.set("recvAt", performance.now());
15468
+ await next();
15469
+ });
15372
15470
  app.use("*", cors({
15373
15471
  origin: (o) => allowedOrigins().includes(o) ? o : null,
15374
15472
  allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
@@ -15590,7 +15688,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15590
15688
  },
15591
15689
  serve: async () => {
15592
15690
  failFastOnAuthError();
15593
- const { mkdirSync: mkdirSync13, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15691
+ const { mkdirSync: mkdirSync13, existsSync: existsSync23, unlinkSync: unlinkSync7 } = await import("fs");
15594
15692
  const { dirname: dirname17 } = await import("path");
15595
15693
  const dir = dirname17(socketPath);
15596
15694
  if (dir) {
@@ -15617,7 +15715,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15617
15715
  );
15618
15716
  } else {
15619
15717
  try {
15620
- unlinkSync6(socketPath);
15718
+ unlinkSync7(socketPath);
15621
15719
  console.log(`[AgentMoss] \u6E05\u7406\u6B8B\u7559 socket \u6587\u4EF6: ${socketPath}`);
15622
15720
  } catch {
15623
15721
  }
@@ -15729,7 +15827,7 @@ __export(rules_tools_exports, {
15729
15827
  rulesStatusText: () => rulesStatusText,
15730
15828
  templateSourceDir: () => templateSourceDir
15731
15829
  });
15732
- import { existsSync as existsSync22, mkdirSync as mkdirSync12, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync9 } from "fs";
15830
+ import { existsSync as existsSync22, mkdirSync as mkdirSync12, readdirSync as readdirSync8, readFileSync as readFileSync21, writeFileSync as writeFileSync9 } from "fs";
15733
15831
  import { dirname as dirname16, join as join24 } from "path";
15734
15832
  import { fileURLToPath as fileURLToPath12 } from "url";
15735
15833
  function initRulesDir(targetDir, opts = {}) {
@@ -15776,7 +15874,7 @@ function templateFiles(dirs) {
15776
15874
  const out = [];
15777
15875
  for (const d of dirs) {
15778
15876
  try {
15779
- for (const name of readdirSync7(d)) {
15877
+ for (const name of readdirSync8(d)) {
15780
15878
  if (name.endsWith(".json.\u793A\u4F8B")) out.push(join24(d, name));
15781
15879
  }
15782
15880
  } catch {
@@ -5103,7 +5103,19 @@ function checkHomeDeletion(actionType, actionDetail) {
5103
5103
  }
5104
5104
  }
5105
5105
  const assigned = {};
5106
- for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
5106
+ const anchored = new RegExp(HOME_ASSIGN_RE.source, "iy");
5107
+ const nameRe = /[A-Za-z_][A-Za-z0-9_]*/gi;
5108
+ let nm;
5109
+ while ((nm = nameRe.exec(actionDetail)) !== null) {
5110
+ anchored.lastIndex = nm.index;
5111
+ const m = anchored.exec(actionDetail);
5112
+ if (m) {
5113
+ assigned[m[1]] = m[2];
5114
+ nameRe.lastIndex = anchored.lastIndex;
5115
+ } else {
5116
+ nameRe.lastIndex = nm.index + nm[0].length;
5117
+ }
5118
+ }
5107
5119
  for (const [varName, path8] of Object.entries(assigned)) {
5108
5120
  if (!isHomeValue(path8)) continue;
5109
5121
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
@@ -5370,7 +5382,7 @@ var init_heuristic = __esm({
5370
5382
  SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
5371
5383
  SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
5372
5384
  HOME_TARGET_RE = /(?:^|[\s="'($])(?:~|(?:\$home|\$\{home\}))(?:\/(?:\.\*|\*|\.)?)?(?=[\s"';}|&)]|$)/i;
5373
- HOME_ASSIGN_RE = /([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(~[A-Za-z0-9_./-]*|\$HOME[A-Za-z0-9_./-]*|\$\{HOME\}[A-Za-z0-9_./-]*|\/home\/[^\s;|&]+|\$\((?:[^()]|\([^()]*\))*\))(?=\s|;|$|\||&)/gi;
5385
+ HOME_ASSIGN_RE = /([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(~[A-Za-z0-9_./-]*|\$HOME[A-Za-z0-9_./-]*|\$\{HOME\}[A-Za-z0-9_./-]*|\/home\/[^\s;|&]+|\$\((?:[^()]|\([^()]*\))*\))(?=\s|;|$|\||&)/i;
5374
5386
  }
5375
5387
  });
5376
5388
 
@@ -10712,6 +10724,11 @@ import * as fs5 from "fs";
10712
10724
  import * as os3 from "os";
10713
10725
  import * as path6 from "path";
10714
10726
  import { gzipSync } from "zlib";
10727
+ function resolveMaxNodes() {
10728
+ const n = Number.parseInt(process.env.AGENT_MOSS_CHAIN_MAX_NODES || "100000", 10);
10729
+ return Number.isFinite(n) && n > 0 ? n : 1e5;
10730
+ }
10731
+ var MAX_NODES = resolveMaxNodes();
10715
10732
 
10716
10733
  // src/engine/formal-engine/chain_state.ts
10717
10734
  init_esm_shims();
@@ -228,7 +228,7 @@
228
228
  "\\bcurl\\b[^;&|\\n]*(?:-X\\s+POST\\s+|-d\\s+|-F\\s+|--data|--upload-file|--data-binary)[^;&|\\n]*(?:/etc/shadow|/etc/passwd|id_rsa|credentials|[^\\s]*\\.db|secret[^\\s]*)[^;&|\\n]*https?://(?!127\\.\\d+\\.\\d+\\.\\d+|0\\.0\\.0\\.0|localhost|\\[?::1\\]?)",
229
229
  "\\bcurl\\b[^;&|\\n]*(?:-X\\s+POST\\s+|-d\\s+|-F\\s+|--data|--upload-file|--data-binary)[^;&|\\n]*https?://(?!127\\.\\d+\\.\\d+\\.\\d+|0\\.0\\.0\\.0|localhost|\\[?::1\\]?)",
230
230
  "\\b(?:curl|wget)\\b[^;&|\\n]*\\s(?:-T|--upload-file)\\s+[^;&|\\n]*https?://(?!localhost|127\\.0\\.0\\.1)",
231
- "[^;&|\\n]*\\|\\s*nc\\s+[^;&|\\n]*\\d{1,5}\\b",
231
+ "\\|\\s*nc\\s+[^;&|\\n]*\\d{1,5}\\b",
232
232
  "\\b(?:scp|sftp|rsync)\\s+[^;&|\\n]*(?:/etc/shadow|/etc/passwd|id_rsa|id_dsa|credentials|\\S*secret\\S*|\\.ssh/)[^;&|\\n]*\\S+@\\S+:",
233
233
  "\\bpython3?\\s+-c\\s+['\"][^'\"]*(?:requests|urllib(?:\\.request)?|aiohttp)\\.(?:post|put|request|send)\\s*\\([^'\"]*['\"]https?://(?!127\\.\\d+\\.\\d+\\.\\d+|0\\.0\\.0\\.0|localhost|\\[?::1\\]?)"
234
234
  ],
@@ -13,7 +13,7 @@
13
13
  "network_egress": [
14
14
  "\\bcurl\\b[^;&|\\n]*(?:-X\\s+POST\\s+|-d\\s+|-F\\s+|--data|--upload-file|--data-binary|-T\\s+)[^;&|\\n]*https?://(?!127\\.\\d+\\.\\d+\\.\\d+|0\\.0\\.0\\.0|localhost|\\[?::1\\]?)",
15
15
  "\\b(?:curl|wget|ftp)\\b[^;&|\\n]*\\s(?:-T|--upload-file|--post-file|--post-data|put)\\b[^;&|\\n]*https?://(?!localhost|127\\.0\\.0\\.1)",
16
- "[^;&|\\n]*\\|\\s*(?:nc|netcat)\\s+\\S+\\s+\\d{1,5}\\b",
16
+ "\\|\\s*(?:nc|netcat)\\s+\\S+\\s+\\d{1,5}\\b",
17
17
  "(?:requests|urllib(?:\\.request)?|aiohttp|httpx)\\.(?:post|put|request|send)\\s*\\(",
18
18
  "\\b(?:scp|sftp|rsync)\\s+[^;&|\\n]*(?:/etc/shadow|/etc/passwd|id_rsa|id_dsa|credentials|\\S*secret\\S*|\\.ssh/)[^;&|\\n]*\\S+@\\S+:",
19
19
  "\\b(?:smtplib|ftplib|paramiko)\\s*\\."
package/dist/server.js CHANGED
@@ -976,7 +976,7 @@ function logRoots() {
976
976
  }
977
977
  function reviewRoots() {
978
978
  const roots = [join4(homeDir(), ".local", "share", "agent_gate")];
979
- for (const name of ["AGENT_GATE_DB", "AGENT_GATE_JSON_PATH"]) {
979
+ for (const name of ["AGENT_GATE_DB", "AGENT_GATE_JSON_PATH", "AGENT_GATE_DATA_DIR"]) {
980
980
  const v = env(name);
981
981
  if (v) roots.push(existsSync3(v) && lstatSync(v).isDirectory() ? v : dirname2(v));
982
982
  }
@@ -5658,7 +5658,19 @@ function checkHomeDeletion(actionType, actionDetail) {
5658
5658
  }
5659
5659
  }
5660
5660
  const assigned = {};
5661
- for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
5661
+ const anchored = new RegExp(HOME_ASSIGN_RE.source, "iy");
5662
+ const nameRe = /[A-Za-z_][A-Za-z0-9_]*/gi;
5663
+ let nm;
5664
+ while ((nm = nameRe.exec(actionDetail)) !== null) {
5665
+ anchored.lastIndex = nm.index;
5666
+ const m = anchored.exec(actionDetail);
5667
+ if (m) {
5668
+ assigned[m[1]] = m[2];
5669
+ nameRe.lastIndex = anchored.lastIndex;
5670
+ } else {
5671
+ nameRe.lastIndex = nm.index + nm[0].length;
5672
+ }
5673
+ }
5662
5674
  for (const [varName, path9] of Object.entries(assigned)) {
5663
5675
  if (!isHomeValue(path9)) continue;
5664
5676
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
@@ -5925,7 +5937,7 @@ var init_heuristic = __esm({
5925
5937
  SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
5926
5938
  SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
5927
5939
  HOME_TARGET_RE = /(?:^|[\s="'($])(?:~|(?:\$home|\$\{home\}))(?:\/(?:\.\*|\*|\.)?)?(?=[\s"';}|&)]|$)/i;
5928
- HOME_ASSIGN_RE = /([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(~[A-Za-z0-9_./-]*|\$HOME[A-Za-z0-9_./-]*|\$\{HOME\}[A-Za-z0-9_./-]*|\/home\/[^\s;|&]+|\$\((?:[^()]|\([^()]*\))*\))(?=\s|;|$|\||&)/gi;
5940
+ HOME_ASSIGN_RE = /([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(~[A-Za-z0-9_./-]*|\$HOME[A-Za-z0-9_./-]*|\$\{HOME\}[A-Za-z0-9_./-]*|\/home\/[^\s;|&]+|\$\((?:[^()]|\([^()]*\))*\))(?=\s|;|$|\||&)/i;
5929
5941
  }
5930
5942
  });
5931
5943
 
@@ -11413,6 +11425,76 @@ function lifecycleFor(detail, stage, isError) {
11413
11425
  if (detail.includes(">>") || detail.includes(">")) return "alive";
11414
11426
  return "";
11415
11427
  }
11428
+ function resolveMaxNodes() {
11429
+ const n = Number.parseInt(process.env.AGENT_MOSS_CHAIN_MAX_NODES || "100000", 10);
11430
+ return Number.isFinite(n) && n > 0 ? n : 1e5;
11431
+ }
11432
+ function resolveRetainNodes() {
11433
+ const raw = process.env.AGENT_MOSS_CHAIN_RETAIN_NODES || "";
11434
+ const def = Math.max(1, Math.floor(MAX_NODES / 2));
11435
+ const n = raw ? Number.parseInt(raw, 10) : def;
11436
+ const safe2 = Number.isFinite(n) && n > 0 ? n : def;
11437
+ return Math.max(1, Math.min(safe2, MAX_NODES - 1));
11438
+ }
11439
+ function envInt3(name, def) {
11440
+ const n = Number.parseInt(process.env[name] || "", 10);
11441
+ return Number.isFinite(n) && n >= 0 ? n : def;
11442
+ }
11443
+ function cleanupChainArchives(dir, maxBytes = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_MAX_MB", 512) * 1024 * 1024, maxAgeDays = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_MAX_AGE_DAYS", 0)) {
11444
+ let files = [];
11445
+ try {
11446
+ files = fs5.readdirSync(dir).filter((f) => f.startsWith("chain-nodes-") && f.endsWith(".jsonl.gz")).map((f) => path6.join(dir, f)).sort((a, b) => fs5.statSync(a).mtimeMs - fs5.statSync(b).mtimeMs);
11447
+ } catch {
11448
+ return { deleted: 0, files: 0, bytes: 0 };
11449
+ }
11450
+ let removed = 0;
11451
+ if (maxAgeDays > 0) {
11452
+ const cutoff = Date.now() - maxAgeDays * 864e5;
11453
+ files = files.filter((p) => {
11454
+ try {
11455
+ if (fs5.statSync(p).mtimeMs < cutoff) {
11456
+ fs5.unlinkSync(p);
11457
+ removed += 1;
11458
+ return false;
11459
+ }
11460
+ } catch {
11461
+ }
11462
+ return true;
11463
+ });
11464
+ }
11465
+ let total = files.reduce((n, p) => {
11466
+ try {
11467
+ return n + fs5.statSync(p).size;
11468
+ } catch {
11469
+ return n;
11470
+ }
11471
+ }, 0);
11472
+ if (maxBytes > 0) {
11473
+ for (let i = 0; i < files.length; i++) {
11474
+ if (total <= maxBytes) break;
11475
+ if (i === files.length - 1) break;
11476
+ const p = files[i];
11477
+ try {
11478
+ const size = fs5.statSync(p).size;
11479
+ fs5.unlinkSync(p);
11480
+ total -= size;
11481
+ removed += 1;
11482
+ } catch {
11483
+ }
11484
+ }
11485
+ }
11486
+ let remainFiles = 0;
11487
+ let remainBytes = 0;
11488
+ try {
11489
+ for (const f of fs5.readdirSync(dir)) {
11490
+ if (!f.startsWith("chain-nodes-") || !f.endsWith(".jsonl.gz")) continue;
11491
+ remainFiles += 1;
11492
+ remainBytes += fs5.statSync(path6.join(dir, f)).size;
11493
+ }
11494
+ } catch {
11495
+ }
11496
+ return { deleted: removed, files: remainFiles, bytes: remainBytes };
11497
+ }
11416
11498
  var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, STAGES_PATTERNS, CHAINS, COMMON_DIR_RESOURCES2, MAX_NODES, StatefulChainTracker;
11417
11499
  var init_stateful = __esm({
11418
11500
  "src/engine/formal-engine/stateful.ts"() {
@@ -11444,7 +11526,7 @@ var init_stateful = __esm({
11444
11526
  "/data",
11445
11527
  "/storage"
11446
11528
  ]);
11447
- MAX_NODES = 1e5;
11529
+ MAX_NODES = resolveMaxNodes();
11448
11530
  StatefulChainTracker = class _StatefulChainTracker {
11449
11531
  /** 本地接收时刻(实时路径无 called_at 时的兜底时间戳,ISO)。 */
11450
11532
  static now() {
@@ -11551,7 +11633,7 @@ var init_stateful = __esm({
11551
11633
  * 派生缓存不是原始历史存储;归档失败抛异常,调用方不得丢状态。
11552
11634
  */
11553
11635
  rotate(archiveDir, retain) {
11554
- const keep = Math.max(1, Math.min(retain ?? Math.floor(MAX_NODES / 2), MAX_NODES - 1));
11636
+ const keep = Math.max(1, Math.min(retain ?? resolveRetainNodes(), MAX_NODES - 1));
11555
11637
  if (this.nodes_.length <= keep) return { archived: 0, file: "" };
11556
11638
  const old = this.nodes_.slice(0, this.nodes_.length - keep);
11557
11639
  const kept = this.nodes_.slice(-keep);
@@ -11561,6 +11643,16 @@ var init_stateful = __esm({
11561
11643
  const file = path6.join(dir, `chain-nodes-${safeAgent}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.jsonl.gz`);
11562
11644
  const payload = old.map((n) => JSON.stringify(n)).join("\n") + "\n";
11563
11645
  fs5.writeFileSync(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
11646
+ try {
11647
+ const c = cleanupChainArchives(dir);
11648
+ if (c.deleted > 0) {
11649
+ console.error(
11650
+ `[AgentMoss] chain-archive \u6E05\u7406: \u5220\u9664 ${c.deleted} \u4E2A\u65E7\u5F52\u6863\uFF08\u5269\u4F59 ${c.files} \u4E2A / ${c.bytes} \u5B57\u8282\uFF09`
11651
+ );
11652
+ }
11653
+ } catch (e) {
11654
+ console.error(`[AgentMoss] chain-archive \u6E05\u7406\u5931\u8D25\uFF08\u7EE7\u7EED\uFF09: ${e?.message ?? e}`);
11655
+ }
11564
11656
  this.nodes_ = [];
11565
11657
  this.ptr = {};
11566
11658
  this.tainted.clear();
@@ -13126,7 +13218,7 @@ init_security_policy();
13126
13218
  init_paths();
13127
13219
  init_config();
13128
13220
  import { createHash as createHash5 } from "crypto";
13129
- import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
13221
+ import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
13130
13222
  import { tmpdir as tmpdir2 } from "os";
13131
13223
  import { join as join17 } from "path";
13132
13224
  var CACHE_DIR = join17(tmpdir2(), "agent_moss_policy_cache");
@@ -13208,7 +13300,7 @@ var PolicyCache = class {
13208
13300
  invalidate(sessionId, promptSession) {
13209
13301
  this.memory.delete(this.cacheKey(sessionId, promptSession));
13210
13302
  try {
13211
- unlinkSync4(this.cacheFilePath(sessionId, promptSession));
13303
+ unlinkSync5(this.cacheFilePath(sessionId, promptSession));
13212
13304
  } catch {
13213
13305
  }
13214
13306
  }
@@ -13220,9 +13312,9 @@ var PolicyCache = class {
13220
13312
  const dir = join17(cacheDir(), safeSessionId);
13221
13313
  try {
13222
13314
  if (existsSync17(dir)) {
13223
- for (const f of readdirSync5(dir)) {
13315
+ for (const f of readdirSync6(dir)) {
13224
13316
  try {
13225
- unlinkSync4(join17(dir, f));
13317
+ unlinkSync5(join17(dir, f));
13226
13318
  } catch {
13227
13319
  }
13228
13320
  }
@@ -13235,10 +13327,10 @@ var PolicyCache = class {
13235
13327
  this.memory.clear();
13236
13328
  try {
13237
13329
  if (existsSync17(cacheDir())) {
13238
- for (const sessionDir of readdirSync5(cacheDir())) {
13330
+ for (const sessionDir of readdirSync6(cacheDir())) {
13239
13331
  const dir = join17(cacheDir(), sessionDir);
13240
13332
  try {
13241
- for (const f of readdirSync5(dir)) unlinkSync4(join17(dir, f));
13333
+ for (const f of readdirSync6(dir)) unlinkSync5(join17(dir, f));
13242
13334
  rmdirSync(dir);
13243
13335
  } catch {
13244
13336
  }
@@ -14164,8 +14256,10 @@ async function analyzeRoute(c) {
14164
14256
  }
14165
14257
  const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
14166
14258
  if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
14259
+ const recvAt = c.get?.("recvAt");
14260
+ const queueMs = typeof recvAt === "number" ? Math.max(0, t0 - recvAt) : 0;
14167
14261
  console.warn(
14168
- `[AgentMoss] \u6162\u8BF7\u6C42: ${Math.round(durationMs)}ms\uFF08\u9608\u503C ${slowMs}ms\uFF09 action_type=${req.a_next.action_type} agent=${agentId || "-"} decision=${result.decision}`
14262
+ `[AgentMoss] \u6162\u8BF7\u6C42: \u603B ${Math.round(durationMs)}ms = \u6392\u961F ${Math.round(queueMs)}ms + \u8BA1\u7B97 ${Math.round(durationMs - queueMs)}ms\uFF08\u9608\u503C ${slowMs}ms\uFF09 action_type=${req.a_next.action_type} agent=${agentId || "-"} decision=${result.decision}`
14169
14263
  );
14170
14264
  }
14171
14265
  try {
@@ -14525,7 +14619,7 @@ init_asset_dir();
14525
14619
  init_rules_mode();
14526
14620
  import { Hono } from "hono";
14527
14621
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
14528
- import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
14622
+ import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync6 } from "fs";
14529
14623
  import { join as join21, dirname as dirname14 } from "path";
14530
14624
  import { fileURLToPath as fileURLToPath11 } from "url";
14531
14625
  var __dirname10 = dirname14(fileURLToPath11(import.meta.url));
@@ -14873,7 +14967,7 @@ function createConsoleRouter() {
14873
14967
  const defaults = generateSourceDefaults();
14874
14968
  try {
14875
14969
  const p = getRuntimeConfigPath();
14876
- if (existsSync20(p)) unlinkSync5(p);
14970
+ if (existsSync20(p)) unlinkSync6(p);
14877
14971
  } catch {
14878
14972
  }
14879
14973
  return c.json(withL22View(defaults));
@@ -15026,6 +15120,10 @@ function createApp() {
15026
15120
  enforceRulesContract();
15027
15121
  hardenExistingPaths();
15028
15122
  const app = new Hono2();
15123
+ app.use("*", async (c, next) => {
15124
+ c.set("recvAt", performance.now());
15125
+ await next();
15126
+ });
15029
15127
  app.use("*", cors({
15030
15128
  origin: (o) => allowedOrigins().includes(o) ? o : null,
15031
15129
  allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
@@ -15253,7 +15351,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15253
15351
  },
15254
15352
  serve: async () => {
15255
15353
  failFastOnAuthError();
15256
- const { mkdirSync: mkdirSync11, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
15354
+ const { mkdirSync: mkdirSync11, existsSync: existsSync22, unlinkSync: unlinkSync7 } = await import("fs");
15257
15355
  const { dirname: dirname16 } = await import("path");
15258
15356
  const dir = dirname16(socketPath);
15259
15357
  if (dir) {
@@ -15280,7 +15378,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15280
15378
  );
15281
15379
  } else {
15282
15380
  try {
15283
- unlinkSync6(socketPath);
15381
+ unlinkSync7(socketPath);
15284
15382
  console.log(`[AgentMoss] \u6E05\u7406\u6B8B\u7559 socket \u6587\u4EF6: ${socketPath}`);
15285
15383
  } catch {
15286
15384
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kenhkl/agent-moss",
3
- "version": "0.17.37",
3
+ "version": "0.17.39",
4
4
  "description": "Multi-layer security analysis engine for AI agents (TypeScript)",
5
5
  "type": "module",
6
6
  "main": "dist/server.js",