@kenhkl/agent-moss 0.17.20 → 0.17.23

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.
@@ -33,10 +33,6 @@ function getRulesRoot() {
33
33
  const raw = (process.env[ENV_RULES_ROOT] ?? "").trim();
34
34
  return raw ? raw : null;
35
35
  }
36
- function isRoot() {
37
- const getuid = process.getuid;
38
- return typeof getuid === "function" && getuid() === 0;
39
- }
40
36
  function resolveExplicitOwnerHome() {
41
37
  for (const name of [process.env.SUDO_USER, process.env.LOGNAME, process.env.USER]) {
42
38
  if (name && name !== "root" && name !== "") {
@@ -64,12 +60,6 @@ function listOwnerHomes() {
64
60
  }
65
61
  return homes;
66
62
  }
67
- function resolveOwnerHome() {
68
- const explicit = resolveExplicitOwnerHome();
69
- if (explicit) return explicit;
70
- const owners = listOwnerHomes();
71
- return owners.length > 0 ? owners[0] : null;
72
- }
73
63
  function homeOf(name) {
74
64
  try {
75
65
  const passwd = readFileSync("/etc/passwd", "utf-8");
@@ -87,12 +77,6 @@ function homeOf(name) {
87
77
  function getDataRoot() {
88
78
  const envPath = process.env[ENV_DATA_ROOT];
89
79
  if (envPath) return envPath;
90
- if (isRoot()) {
91
- const ownerHome = resolveOwnerHome();
92
- if (ownerHome) {
93
- return join(ownerHome, ".config", "agentmoss");
94
- }
95
- }
96
80
  return DEFAULT_DATA_ROOT;
97
81
  }
98
82
  function getInstance() {
@@ -458,22 +442,22 @@ function loadToolRegistry() {
458
442
  data.tools = tools;
459
443
  return data;
460
444
  }
461
- function scanStructEntry(cat, value, path5) {
445
+ function scanStructEntry(cat, value, path6) {
462
446
  if (cat === "skills") {
463
447
  if (!value || typeof value !== "object" || Array.isArray(value)) {
464
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
448
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
465
449
  return null;
466
450
  }
467
451
  const out = {};
468
452
  for (const [skCat, skills] of Object.entries(value)) {
469
453
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
470
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
454
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
471
455
  continue;
472
456
  }
473
457
  const keep = {};
474
458
  for (const [name, kws] of Object.entries(skills)) {
475
459
  if (Array.isArray(kws)) keep[name] = kws;
476
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
460
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
477
461
  }
478
462
  if (Object.keys(keep).length > 0) out[skCat] = keep;
479
463
  }
@@ -481,37 +465,37 @@ function scanStructEntry(cat, value, path5) {
481
465
  }
482
466
  if (cat === "ltl_rules") {
483
467
  if (!Array.isArray(value)) {
484
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
468
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
485
469
  return null;
486
470
  }
487
471
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
488
472
  if (keep.length !== value.length) {
489
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
473
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
490
474
  }
491
475
  return keep.length > 0 ? keep : null;
492
476
  }
493
477
  if (cat === "tools") {
494
478
  if (!value || typeof value !== "object" || Array.isArray(value)) {
495
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
479
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
496
480
  return null;
497
481
  }
498
482
  const keep = {};
499
483
  for (const [k, v] of Object.entries(value)) {
500
484
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
501
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
485
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
502
486
  }
503
487
  return Object.keys(keep).length > 0 ? keep : null;
504
488
  }
505
489
  return null;
506
490
  }
507
- function scanRulesFile(path5, kind) {
491
+ function scanRulesFile(path6, kind) {
508
492
  const out = {};
509
493
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
510
494
  let parsed;
511
495
  try {
512
- parsed = JSON.parse(readFileSync2(path5, "utf-8"));
496
+ parsed = JSON.parse(readFileSync2(path6, "utf-8"));
513
497
  } catch (e) {
514
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
498
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
515
499
  return out;
516
500
  }
517
501
  const classifyFlat = (r) => {
@@ -535,44 +519,44 @@ function scanRulesFile(path5, kind) {
535
519
  }
536
520
  if (flatBad > 0) {
537
521
  console.warn(
538
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
522
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
539
523
  );
540
524
  }
541
525
  } else {
542
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
526
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
543
527
  return out;
544
528
  }
545
529
  for (const [cat, rules] of pairs) {
546
530
  if (String(cat).startsWith("_")) continue;
547
531
  if (STRUCT_KEYS.includes(cat)) {
548
- const got = scanStructEntry(cat, rules, path5);
532
+ const got = scanStructEntry(cat, rules, path6);
549
533
  if (got !== null) out[cat] = got;
550
534
  continue;
551
535
  }
552
536
  const required = EXTRA_CATEGORIES[cat];
553
537
  if (!required) {
554
538
  console.warn(
555
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
539
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
556
540
  );
557
541
  continue;
558
542
  }
559
543
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
560
544
  console.error(
561
- `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path5} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
545
+ `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path6} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
562
546
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
563
547
  \u4F60\u5199\u7684\u50CF\u662F runtime config \u7684\u683C\u5F0F\uFF08{"category_enabled": ..., "rules": [...]}\uFF09\u2014\u2014\u90A3\u662F ~/.config/agentmoss/agent_moss_runtime.json \u7684\u683C\u5F0F\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5F53\u89C4\u5219\u6587\u4EF6\u7528\u3002`
564
548
  );
565
549
  continue;
566
550
  }
567
551
  if (!Array.isArray(rules)) {
568
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
552
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
569
553
  continue;
570
554
  }
571
555
  const items = [];
572
556
  for (const r of rules) {
573
557
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
574
558
  console.warn(
575
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path5} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
559
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
576
560
  );
577
561
  continue;
578
562
  }
@@ -582,7 +566,7 @@ function scanRulesFile(path5, kind) {
582
566
  }
583
567
  if (Object.keys(out).length > 0) {
584
568
  console.info(
585
- `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path5}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
569
+ `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path6}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
586
570
  );
587
571
  }
588
572
  return out;
@@ -983,7 +967,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
983
967
  os: String(sp.os || "linux").toLowerCase()
984
968
  }));
985
969
  }
986
- function _scopeOf(os3, path5) {
970
+ function _scopeOf(os3, path6) {
987
971
  if (!_scopeIndex) {
988
972
  _scopeIndex = /* @__PURE__ */ new Map();
989
973
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -991,7 +975,7 @@ function _scopeOf(os3, path5) {
991
975
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
992
976
  }
993
977
  }
994
- return _scopeIndex.get(`${String(os3 || "linux").toLowerCase()}|${path5}`) || "root";
978
+ return _scopeIndex.get(`${String(os3 || "linux").toLowerCase()}|${path6}`) || "root";
995
979
  }
996
980
  function getSensitivePathsForOs(osType) {
997
981
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -1342,17 +1326,17 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
1342
1326
  return null;
1343
1327
  }
1344
1328
  const unreadPaths = [];
1345
- for (const path5 of filteredPaths) {
1329
+ for (const path6 of filteredPaths) {
1346
1330
  const hasRead = [...historyReadPaths].some(
1347
- (rp) => path5 === rp || path5.startsWith(rp) || rp.startsWith(path5)
1331
+ (rp) => path6 === rp || path6.startsWith(rp) || rp.startsWith(path6)
1348
1332
  );
1349
1333
  if (!hasRead) {
1350
- let isCreate = !fs.existsSync(path5);
1334
+ let isCreate = !fs.existsSync(path6);
1351
1335
  if (!isCreate) {
1352
1336
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
1353
1337
  }
1354
1338
  if (!isCreate) {
1355
- unreadPaths.push(path5);
1339
+ unreadPaths.push(path6);
1356
1340
  }
1357
1341
  }
1358
1342
  }
@@ -1546,16 +1530,16 @@ var init_logic_rules = __esm({
1546
1530
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
1547
1531
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
1548
1532
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
1549
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path5, riskLevel, desc, dirDelOnly }) => ({ path: path5, riskLevel, desc, credential: true, dirDelOnly }));
1533
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
1550
1534
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
1551
1535
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
1552
- CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path5, riskLevel, desc, dirDelOnly }) => ({ path: path5, riskLevel, desc, credential: true, dirDelOnly }));
1536
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
1553
1537
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
1554
1538
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
1555
- CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path5, riskLevel, desc, dirDelOnly }) => ({ path: path5, riskLevel, desc, credential: true, dirDelOnly }));
1539
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
1556
1540
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
1557
1541
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
1558
- CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path5, riskLevel, desc, dirDelOnly }) => ({ path: path5, riskLevel, desc, credential: true, dirDelOnly }));
1542
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
1559
1543
  _scopeIndex = null;
1560
1544
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
1561
1545
  "ask_user_question",
@@ -3324,7 +3308,9 @@ function loadLLMConfigFromFile(configPath) {
3324
3308
  model: llm.model || "",
3325
3309
  temperature: llm.temperature ?? 0.1,
3326
3310
  maxTokens: llm.max_tokens ?? 4096,
3327
- timeout: llm.timeout ?? 40
3311
+ timeout: llm.timeout ?? 40,
3312
+ // 部署级透传参数(关思考等)。非对象直接忽略:写错不能拖垮配置加载。
3313
+ ...llm.extra_body && typeof llm.extra_body === "object" && !Array.isArray(llm.extra_body) ? { extraBody: llm.extra_body } : {}
3328
3314
  };
3329
3315
  }
3330
3316
  function loadTimeoutRetryFromFile(configPath) {
@@ -4156,16 +4142,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4156
4142
  if (String(osType || "").toLowerCase() === "windows") {
4157
4143
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
4158
4144
  }
4159
- const pathMatches = (text, path5) => {
4160
- const parts = path5.split(/(\(\?!.*?\))/);
4145
+ const pathMatches = (text, path6) => {
4146
+ const parts = path6.split(/(\(\?!.*?\))/);
4161
4147
  const escaped = parts.map((part) => {
4162
4148
  if (part.startsWith("(?!")) return part;
4163
4149
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4164
4150
  }).join("");
4165
- const re = path5.startsWith(".") || path5.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4151
+ const re = path6.startsWith(".") || path6.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4166
4152
  return re.test(text);
4167
4153
  };
4168
- const pathMatchesAny = (path5) => pathScanTexts.some((t) => pathMatches(t, path5));
4154
+ const pathMatchesAny = (path6) => pathScanTexts.some((t) => pathMatches(t, path6));
4169
4155
  for (const sp of rootPaths) {
4170
4156
  if (pathMatchesAny(sp.path.toLowerCase())) {
4171
4157
  if (keygenGenerate) continue;
@@ -4308,8 +4294,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4308
4294
  }
4309
4295
  return null;
4310
4296
  }
4311
- function isHomeValue(path5) {
4312
- let p = path5.trim().toLowerCase();
4297
+ function isHomeValue(path6) {
4298
+ let p = path6.trim().toLowerCase();
4313
4299
  if (p.startsWith("$(") && p.endsWith(")")) {
4314
4300
  const inner = p.slice(2, -1).trim();
4315
4301
  return HOME_TARGET_RE.test(" " + inner);
@@ -4365,15 +4351,15 @@ function checkHomeDeletion(actionType, actionDetail) {
4365
4351
  }
4366
4352
  const assigned = {};
4367
4353
  for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
4368
- for (const [varName, path5] of Object.entries(assigned)) {
4369
- if (!isHomeValue(path5)) continue;
4354
+ for (const [varName, path6] of Object.entries(assigned)) {
4355
+ if (!isHomeValue(path6)) continue;
4370
4356
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
4371
4357
  for (const seg of segs) {
4372
4358
  if (!isDeleteCommand(seg)) continue;
4373
4359
  if (varRefRe.test(seg)) {
4374
4360
  return {
4375
4361
  allowed: false,
4376
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path5}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
4362
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path6}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
4377
4363
  riskLevel: "high",
4378
4364
  riskType: "script_execution",
4379
4365
  confidence: 90,
@@ -4639,9 +4625,10 @@ __export(token_stats_exports, {
4639
4625
  getTokenStats: () => getTokenStats,
4640
4626
  getTokenTrend: () => getTokenTrend,
4641
4627
  recordTokenUsage: () => recordTokenUsage,
4642
- resetTokenStats: () => resetTokenStats
4628
+ resetTokenStats: () => resetTokenStats,
4629
+ resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
4643
4630
  });
4644
- import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2 } from "fs";
4631
+ import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync5 } from "fs";
4645
4632
  function getStatsPath() {
4646
4633
  const envPath = process.env[ENV_STATS_PATH];
4647
4634
  if (envPath) return envPath;
@@ -4649,11 +4636,24 @@ function getStatsPath() {
4649
4636
  }
4650
4637
  function loadAllRecords(statsPath) {
4651
4638
  if (!existsSync12(statsPath)) return [];
4639
+ let sig = "";
4652
4640
  try {
4653
- const data = JSON.parse(readFileSync12(statsPath, "utf-8"));
4654
- if (Array.isArray(data)) return data;
4655
- if (data && Array.isArray(data.records)) return data.records;
4641
+ const st = statSync5(statsPath);
4642
+ sig = `${st.mtimeMs}:${st.size}`;
4643
+ } catch {
4656
4644
  return [];
4645
+ }
4646
+ if (_recordsCache && _recordsCache.path === statsPath && _recordsCache.sig === sig) {
4647
+ return _recordsCache.records.slice();
4648
+ }
4649
+ try {
4650
+ const data = JSON.parse(readFileSync12(statsPath, "utf-8"));
4651
+ let records;
4652
+ if (Array.isArray(data)) records = data;
4653
+ else if (data && Array.isArray(data.records)) records = data.records;
4654
+ else records = [];
4655
+ _recordsCache = { path: statsPath, sig, records };
4656
+ return records.slice();
4657
4657
  } catch (e) {
4658
4658
  return [];
4659
4659
  }
@@ -4663,9 +4663,22 @@ function saveRecords(statsPath, records) {
4663
4663
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
4664
4664
  if (dir && !existsSync12(dir)) mkdirSync3(dir, { recursive: true });
4665
4665
  writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
4666
+ try {
4667
+ const st = statSync5(statsPath);
4668
+ _recordsCache = {
4669
+ path: statsPath,
4670
+ sig: `${st.mtimeMs}:${st.size}`,
4671
+ records: records.slice()
4672
+ };
4673
+ } catch {
4674
+ _recordsCache = null;
4675
+ }
4666
4676
  } catch (e) {
4667
4677
  }
4668
4678
  }
4679
+ function resetTokenStatsCacheForTests() {
4680
+ _recordsCache = null;
4681
+ }
4669
4682
  function recordTokenUsage(record) {
4670
4683
  const statsPath = getStatsPath();
4671
4684
  const records = loadAllRecords(statsPath);
@@ -4794,8 +4807,9 @@ function resetTokenStats() {
4794
4807
  } catch {
4795
4808
  }
4796
4809
  }
4810
+ _recordsCache = null;
4797
4811
  }
4798
- var ENV_STATS_PATH, MAX_RECORDS;
4812
+ var ENV_STATS_PATH, MAX_RECORDS, _recordsCache;
4799
4813
  var init_token_stats = __esm({
4800
4814
  "src/engine/token-stats.ts"() {
4801
4815
  "use strict";
@@ -4803,6 +4817,7 @@ var init_token_stats = __esm({
4803
4817
  init_paths();
4804
4818
  ENV_STATS_PATH = "AGENT_MOSS_TOKEN_STATS_PATH";
4805
4819
  MAX_RECORDS = 1e4;
4820
+ _recordsCache = null;
4806
4821
  }
4807
4822
  });
4808
4823
 
@@ -5522,15 +5537,15 @@ function parseShellString(s) {
5522
5537
  let m;
5523
5538
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
5524
5539
  const interp = m[1];
5525
- const path5 = m[2].trim();
5540
+ const path6 = m[2].trim();
5526
5541
  let rest = m[3].trim();
5527
- if (path5.startsWith("-") || path5.startsWith("$") || path5.includes("/dev/")) continue;
5542
+ if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
5528
5543
  rest = rest.split(/[;|&<>]/)[0].trim();
5529
5544
  const args = [];
5530
5545
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
5531
5546
  args.push(tm[1] ? tm[2] : tm[3]);
5532
5547
  }
5533
- return { path: path5, args, interpreter: interp };
5548
+ return { path: path6, args, interpreter: interp };
5534
5549
  }
5535
5550
  return null;
5536
5551
  }
@@ -5576,9 +5591,9 @@ function extractCallsFromTree(tree, reachableLines) {
5576
5591
  }
5577
5592
  if (allStr && elts.length >= 2) {
5578
5593
  const interp = elts[0];
5579
- const path5 = elts[1];
5580
- if (!path5.startsWith("-") && !path5.startsWith("$") && !path5.includes("/dev/")) {
5581
- add({ path: path5, args: elts.slice(2), interpreter: interp });
5594
+ const path6 = elts[1];
5595
+ if (!path6.startsWith("-") && !path6.startsWith("$") && !path6.includes("/dev/")) {
5596
+ add({ path: path6, args: elts.slice(2), interpreter: interp });
5582
5597
  return true;
5583
5598
  }
5584
5599
  }
@@ -5618,15 +5633,15 @@ function extractCallsRegex(content) {
5618
5633
  let m;
5619
5634
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
5620
5635
  const interp = m[1];
5621
- const path5 = m[2].trim();
5636
+ const path6 = m[2].trim();
5622
5637
  let rest = m[3].trim();
5623
- if (path5.startsWith("-") || path5.startsWith("$") || path5.includes("/dev/")) continue;
5638
+ if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
5624
5639
  rest = rest.split(/[;|&<>]/)[0].trim();
5625
5640
  const args = [];
5626
5641
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
5627
5642
  args.push(tm[1] ? tm[2] : tm[3]);
5628
5643
  }
5629
- calls.push({ path: path5, args, interpreter: interp });
5644
+ calls.push({ path: path6, args, interpreter: interp });
5630
5645
  }
5631
5646
  return calls;
5632
5647
  }
@@ -6356,15 +6371,15 @@ function extractCallsFromContent(content) {
6356
6371
  CHILD_CALL_RE2.lastIndex = 0;
6357
6372
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
6358
6373
  const interp = m[1];
6359
- const path5 = m[2].trim();
6374
+ const path6 = m[2].trim();
6360
6375
  let rest = m[3].trim();
6361
- if (path5.startsWith("-") || path5.startsWith("$") || path5.includes("/dev/")) continue;
6376
+ if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
6362
6377
  rest = rest.split(/[;|&<>]/)[0].trim();
6363
6378
  const args = [];
6364
6379
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6365
6380
  args.push(tm[1] ? tm[2] : tm[3]);
6366
6381
  }
6367
- calls.push({ path: path5, args, interpreter: interp });
6382
+ calls.push({ path: path6, args, interpreter: interp });
6368
6383
  }
6369
6384
  return calls;
6370
6385
  }
@@ -7008,6 +7023,420 @@ ${contentPreview}
7008
7023
  // src/engine/llm-analyzer.ts
7009
7024
  import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
7010
7025
  import OpenAI from "openai";
7026
+
7027
+ // src/infra/trace-log.ts
7028
+ init_esm_shims();
7029
+ init_paths();
7030
+ import fs4 from "fs";
7031
+ import path4 from "path";
7032
+ var LEVEL_OFF = 0;
7033
+ var LEVEL_SUMMARY = 1;
7034
+ var LEVEL_FULL = 2;
7035
+ var LEVEL_NAMES = {
7036
+ off: LEVEL_OFF,
7037
+ summary: LEVEL_SUMMARY,
7038
+ full: LEVEL_FULL
7039
+ };
7040
+ var MAX_FIELD_CHARS = 64 * 1024;
7041
+ var SECRET_KEYS = /* @__PURE__ */ new Set([
7042
+ "api_key",
7043
+ "apikey",
7044
+ "authorization",
7045
+ "auth_token",
7046
+ "token",
7047
+ "password"
7048
+ ]);
7049
+ var MAX_FILE_BYTES = 20 * 1024 * 1024;
7050
+ var _levelCache = null;
7051
+ var _levelCacheRaw = null;
7052
+ var _warnedInvalid = false;
7053
+ function traceLevel() {
7054
+ if (_levelCache !== null) return _levelCache;
7055
+ const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
7056
+ let level;
7057
+ if (raw in LEVEL_NAMES) {
7058
+ level = LEVEL_NAMES[raw];
7059
+ } else {
7060
+ level = LEVEL_SUMMARY;
7061
+ if (!_warnedInvalid) {
7062
+ _warnedInvalid = true;
7063
+ console.warn(
7064
+ `[AgentMoss] AGENT_MOSS_TRACE_LEVEL=${JSON.stringify(raw)} \u975E\u6CD5\uFF0C\u6309 summary \u5904\u7406\uFF08\u53EF\u9009 off/summary/full\uFF09`
7065
+ );
7066
+ }
7067
+ }
7068
+ _levelCache = level;
7069
+ _levelCacheRaw = raw;
7070
+ return level;
7071
+ }
7072
+ function nowIso() {
7073
+ return (/* @__PURE__ */ new Date()).toISOString();
7074
+ }
7075
+ function tracePath() {
7076
+ const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
7077
+ if (explicit) return explicit;
7078
+ try {
7079
+ return path4.join(getDataRoot(), "agent_moss_trace.log");
7080
+ } catch {
7081
+ return "agent_moss_trace.log";
7082
+ }
7083
+ }
7084
+ function sanitize(key, value) {
7085
+ if (SECRET_KEYS.has(key.toLowerCase())) return "***";
7086
+ if (typeof value === "string") {
7087
+ let v = value;
7088
+ if (v.length > MAX_FIELD_CHARS) {
7089
+ const original = v.length;
7090
+ v = `${v.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
7091
+ }
7092
+ return v;
7093
+ }
7094
+ if (value === null || ["number", "boolean"].includes(typeof value)) return value;
7095
+ let text;
7096
+ try {
7097
+ text = JSON.stringify(value);
7098
+ } catch {
7099
+ return String(value);
7100
+ }
7101
+ if (text.length > MAX_FIELD_CHARS) {
7102
+ const original = text.length;
7103
+ return `${text.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
7104
+ }
7105
+ return value;
7106
+ }
7107
+ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
7108
+ if (traceLevel() < level) return;
7109
+ try {
7110
+ const record = { ts: nowIso(), event };
7111
+ for (const [key, value] of Object.entries(fields)) {
7112
+ record[key] = sanitize(key, value);
7113
+ }
7114
+ const line = `${JSON.stringify(record)}
7115
+ `;
7116
+ const file = tracePath();
7117
+ try {
7118
+ const dir = path4.dirname(file);
7119
+ if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
7120
+ try {
7121
+ const st = fs4.statSync(file);
7122
+ if (st.size > MAX_FILE_BYTES) fs4.renameSync(file, `${file}.1`);
7123
+ } catch {
7124
+ }
7125
+ fs4.appendFileSync(file, line, { encoding: "utf-8", mode: 384 });
7126
+ } catch {
7127
+ }
7128
+ } catch {
7129
+ }
7130
+ }
7131
+ function traceSummary(event, fields = {}) {
7132
+ trace(event, LEVEL_SUMMARY, fields);
7133
+ }
7134
+ function traceFull(event, fields = {}) {
7135
+ trace(event, LEVEL_FULL, fields);
7136
+ }
7137
+
7138
+ // src/infra/metrics.ts
7139
+ init_esm_shims();
7140
+
7141
+ // src/infra/circuit-breaker.ts
7142
+ init_esm_shims();
7143
+ var CLOSED = "closed";
7144
+ var OPEN = "open";
7145
+ var HALF_OPEN = "half_open";
7146
+ function envInt(name, fallback) {
7147
+ const raw = process.env[name];
7148
+ if (raw === void 0 || raw.trim() === "") return fallback;
7149
+ const n = Number(raw);
7150
+ return Number.isFinite(n) ? n : fallback;
7151
+ }
7152
+ var CircuitBreaker = class {
7153
+ constructor(threshold = 5, cooldown = 30) {
7154
+ this.threshold = threshold;
7155
+ this.cooldown = cooldown;
7156
+ }
7157
+ threshold;
7158
+ cooldown;
7159
+ state = CLOSED;
7160
+ failures = 0;
7161
+ openedAt = 0;
7162
+ openCount = 0;
7163
+ shortCircuitCount = 0;
7164
+ get currentState() {
7165
+ return this.state;
7166
+ }
7167
+ allow() {
7168
+ if (this.threshold <= 0) return true;
7169
+ if (this.state === CLOSED) return true;
7170
+ if (this.state === OPEN) {
7171
+ if ((performance.now() - this.openedAt) / 1e3 >= this.cooldown) {
7172
+ this.state = HALF_OPEN;
7173
+ return true;
7174
+ }
7175
+ this.shortCircuitCount += 1;
7176
+ return false;
7177
+ }
7178
+ return true;
7179
+ }
7180
+ recordSuccess() {
7181
+ if (this.threshold <= 0) return;
7182
+ this.state = CLOSED;
7183
+ this.failures = 0;
7184
+ }
7185
+ recordFailure() {
7186
+ if (this.threshold <= 0) return;
7187
+ if (this.state === HALF_OPEN) {
7188
+ this.state = OPEN;
7189
+ this.openedAt = performance.now();
7190
+ this.openCount += 1;
7191
+ return;
7192
+ }
7193
+ this.failures += 1;
7194
+ if (this.failures >= this.threshold) {
7195
+ this.state = OPEN;
7196
+ this.openedAt = performance.now();
7197
+ this.openCount += 1;
7198
+ }
7199
+ }
7200
+ snapshot() {
7201
+ return {
7202
+ state: this.state,
7203
+ failures: this.failures,
7204
+ threshold: this.threshold,
7205
+ cooldown_sec: this.cooldown,
7206
+ open_count: this.openCount,
7207
+ short_circuit_count: this.shortCircuitCount
7208
+ };
7209
+ }
7210
+ reset() {
7211
+ this.state = CLOSED;
7212
+ this.failures = 0;
7213
+ this.openedAt = 0;
7214
+ }
7215
+ };
7216
+ var _breaker = null;
7217
+ function getBreaker() {
7218
+ if (_breaker === null) {
7219
+ _breaker = new CircuitBreaker(
7220
+ envInt("AGENT_MOSS_LLM_CIRCUIT_THRESHOLD", 5),
7221
+ envInt("AGENT_MOSS_LLM_CIRCUIT_COOLDOWN", 30)
7222
+ );
7223
+ }
7224
+ return _breaker;
7225
+ }
7226
+
7227
+ // src/infra/metrics.ts
7228
+ var DEFAULT_BUCKETS = [
7229
+ 5e-3,
7230
+ 0.01,
7231
+ 0.025,
7232
+ 0.05,
7233
+ 0.1,
7234
+ 0.25,
7235
+ 0.5,
7236
+ 1,
7237
+ 2.5,
7238
+ 5,
7239
+ 10,
7240
+ 30,
7241
+ 60
7242
+ ];
7243
+ var STARTED_AT = Date.now();
7244
+ function escapeLabel(value) {
7245
+ return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
7246
+ }
7247
+ function formatLabels(labels) {
7248
+ if (!labels) return "";
7249
+ const keys = Object.keys(labels).sort();
7250
+ if (!keys.length) return "";
7251
+ return `{${keys.map((k) => `${k}="${escapeLabel(labels[k])}"`).join(",")}}`;
7252
+ }
7253
+ function keyOf(labelnames, labels) {
7254
+ return labelnames.map((k) => String(labels[k] ?? "")).join("");
7255
+ }
7256
+ function decodeKey(labelnames, key) {
7257
+ if (!labelnames.length) return void 0;
7258
+ const parts = key.split("");
7259
+ const out = {};
7260
+ labelnames.forEach((k, i) => {
7261
+ out[k] = parts[i] ?? "";
7262
+ });
7263
+ return out;
7264
+ }
7265
+ var Counter = class {
7266
+ constructor(name, helpText, labelnames = []) {
7267
+ this.name = name;
7268
+ this.helpText = helpText;
7269
+ this.labelnames = labelnames;
7270
+ }
7271
+ name;
7272
+ helpText;
7273
+ labelnames;
7274
+ values = /* @__PURE__ */ new Map();
7275
+ inc(amount = 1, labels = {}) {
7276
+ const k = keyOf(this.labelnames, labels);
7277
+ this.values.set(k, (this.values.get(k) ?? 0) + amount);
7278
+ }
7279
+ render() {
7280
+ const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} counter`];
7281
+ if (!this.values.size) {
7282
+ const empty = this.labelnames.length ? Object.fromEntries(this.labelnames.map((k) => [k, ""])) : void 0;
7283
+ out.push(`${this.name}${formatLabels(empty)} 0`);
7284
+ return out;
7285
+ }
7286
+ for (const [k, v] of this.values) {
7287
+ out.push(`${this.name}${formatLabels(decodeKey(this.labelnames, k))} ${v}`);
7288
+ }
7289
+ return out;
7290
+ }
7291
+ };
7292
+ var Gauge = class {
7293
+ constructor(name, helpText, labelnames = []) {
7294
+ this.name = name;
7295
+ this.helpText = helpText;
7296
+ this.labelnames = labelnames;
7297
+ }
7298
+ name;
7299
+ helpText;
7300
+ labelnames;
7301
+ values = /* @__PURE__ */ new Map();
7302
+ set(value, labels = {}) {
7303
+ this.values.set(keyOf(this.labelnames, labels), Number(value));
7304
+ }
7305
+ clear() {
7306
+ this.values.clear();
7307
+ }
7308
+ render() {
7309
+ const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} gauge`];
7310
+ for (const [k, v] of this.values) {
7311
+ const labels = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : void 0;
7312
+ out.push(`${this.name}${formatLabels(labels)} ${v}`);
7313
+ }
7314
+ return out;
7315
+ }
7316
+ };
7317
+ var Histogram = class {
7318
+ constructor(name, helpText, buckets = DEFAULT_BUCKETS, labelnames = []) {
7319
+ this.name = name;
7320
+ this.helpText = helpText;
7321
+ this.buckets = buckets;
7322
+ this.labelnames = labelnames;
7323
+ }
7324
+ name;
7325
+ helpText;
7326
+ buckets;
7327
+ labelnames;
7328
+ values = /* @__PURE__ */ new Map();
7329
+ observe(value, labels = {}) {
7330
+ const k = keyOf(this.labelnames, labels);
7331
+ let slot = this.values.get(k);
7332
+ if (!slot) {
7333
+ slot = { buckets: this.buckets.map(() => 0), sum: 0, count: 0 };
7334
+ this.values.set(k, slot);
7335
+ }
7336
+ for (let i = 0; i < this.buckets.length; i++) {
7337
+ if (value <= this.buckets[i]) slot.buckets[i] += 1;
7338
+ }
7339
+ slot.sum += value;
7340
+ slot.count += 1;
7341
+ }
7342
+ render() {
7343
+ const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} histogram`];
7344
+ for (const [k, slot] of this.values) {
7345
+ const base = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : {};
7346
+ this.buckets.forEach((bound, i) => {
7347
+ out.push(`${this.name}_bucket${formatLabels({ ...base, le: String(bound) })} ${slot.buckets[i]}`);
7348
+ });
7349
+ out.push(`${this.name}_bucket${formatLabels({ ...base, le: "+Inf" })} ${slot.count}`);
7350
+ out.push(`${this.name}_sum${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.sum}`);
7351
+ out.push(`${this.name}_count${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.count}`);
7352
+ }
7353
+ return out;
7354
+ }
7355
+ };
7356
+ var ANALYZE_TOTAL = new Counter(
7357
+ "agent_moss_analyze_total",
7358
+ "Total analyze requests handled, by decision and risk level.",
7359
+ ["decision", "risk_level"]
7360
+ );
7361
+ var ANALYZE_DURATION = new Histogram(
7362
+ "agent_moss_analyze_duration_seconds",
7363
+ "End-to-end analyze duration in seconds.",
7364
+ DEFAULT_BUCKETS,
7365
+ ["decision"]
7366
+ );
7367
+ var LAYER_HIT_TOTAL = new Counter(
7368
+ "agent_moss_layer_hit_total",
7369
+ "Number of requests where a given defense layer produced the final verdict.",
7370
+ ["layer"]
7371
+ );
7372
+ var REJECTED_TOTAL = new Counter(
7373
+ "agent_moss_rejected_total",
7374
+ "Requests rejected before analysis (concurrency / rate limit / auth).",
7375
+ ["reason"]
7376
+ );
7377
+ var LLM_CALLS_TOTAL = new Counter(
7378
+ "agent_moss_llm_calls_total",
7379
+ "LLM API calls, by outcome.",
7380
+ ["result"]
7381
+ );
7382
+ var LLM_DURATION = new Histogram(
7383
+ "agent_moss_llm_duration_seconds",
7384
+ "LLM API call duration in seconds.",
7385
+ DEFAULT_BUCKETS,
7386
+ ["result"]
7387
+ );
7388
+ var POOL_INFLIGHT = new Gauge(
7389
+ "agent_moss_pool_inflight",
7390
+ "Current in-flight requests per concurrency pool.",
7391
+ ["pool"]
7392
+ );
7393
+ var CHAIN_NODES = new Gauge(
7394
+ "agent_moss_chain_nodes",
7395
+ "Number of nodes in the stateful chain timeline.",
7396
+ ["agent"]
7397
+ );
7398
+ var CHAIN_DB_BYTES = new Gauge(
7399
+ "agent_moss_chain_db_bytes",
7400
+ "Size of the chain state database in bytes."
7401
+ );
7402
+ var LOOP_LAG = new Gauge(
7403
+ "agent_moss_event_loop_lag_seconds",
7404
+ "Most recent event loop lag sample in seconds."
7405
+ );
7406
+ var LOOP_LAG_MAX = new Gauge(
7407
+ "agent_moss_event_loop_lag_max_seconds",
7408
+ "Maximum event loop lag observed since process start, in seconds."
7409
+ );
7410
+ var UPTIME = new Gauge(
7411
+ "agent_moss_uptime_seconds",
7412
+ "Seconds since process start."
7413
+ );
7414
+ var LLM_CIRCUIT_STATE = new Gauge(
7415
+ "agent_moss_llm_circuit_state",
7416
+ "LLM circuit breaker state (0=closed, 1=open, 2=half_open)."
7417
+ );
7418
+ var LLM_SHORT_CIRCUIT_TOTAL = new Counter(
7419
+ "agent_moss_llm_short_circuit_total",
7420
+ "LLM calls short-circuited by the breaker (no network request made)."
7421
+ );
7422
+
7423
+ // src/engine/llm-analyzer.ts
7424
+ function responseFieldLengths(message) {
7425
+ if (!message || typeof message !== "object") return {};
7426
+ const out = {};
7427
+ for (const [key, value] of Object.entries(message)) {
7428
+ if (value === null || value === void 0 || value === "") continue;
7429
+ if (Array.isArray(value) && value.length === 0) continue;
7430
+ if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) continue;
7431
+ if (typeof value === "boolean") continue;
7432
+ try {
7433
+ out[key] = typeof value === "string" ? value.length : String(JSON.stringify(value)).length;
7434
+ } catch {
7435
+ out[key] = -1;
7436
+ }
7437
+ }
7438
+ return out;
7439
+ }
7011
7440
  var llmCache = /* @__PURE__ */ new Map();
7012
7441
  var LLM_CACHE_MAX = 200;
7013
7442
  async function runLLMAnalysis(input, previous) {
@@ -7092,7 +7521,23 @@ async function runLLMAnalysis(input, previous) {
7092
7521
  );
7093
7522
  }
7094
7523
  logPrompt(prompt, input.aNext, previous.llmLogPath);
7524
+ traceFull("l3.prompt", {
7525
+ phase: "security_judge",
7526
+ model: config.model,
7527
+ base_url: config.baseUrl,
7528
+ action_type: input.aNext.actionType,
7529
+ action_detail: input.aNext.actionDetail,
7530
+ prompt,
7531
+ prompt_chars: prompt.length
7532
+ });
7095
7533
  const result = await analyzeWithLLM(prompt, config);
7534
+ traceSummary("l3.verdict", {
7535
+ allowed: result.allowed,
7536
+ risk_level: result.riskLevel,
7537
+ risk_type: result.riskType,
7538
+ reason: result.reason,
7539
+ confidence: result.confidence
7540
+ });
7096
7541
  if (llmCache.size >= LLM_CACHE_MAX) {
7097
7542
  const firstKey = llmCache.keys().next().value;
7098
7543
  if (firstKey) llmCache.delete(firstKey);
@@ -7234,6 +7679,14 @@ function formatHints(previous) {
7234
7679
  }
7235
7680
  async function analyzeWithLLM(prompt, config) {
7236
7681
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
7682
+ const _llmStart = performance.now();
7683
+ const _recordLlm = (result) => {
7684
+ try {
7685
+ LLM_CALLS_TOTAL.inc(1, { result });
7686
+ LLM_DURATION.observe(Math.max(0, (performance.now() - _llmStart) / 1e3), { result });
7687
+ } catch {
7688
+ }
7689
+ };
7237
7690
  const provider = detectProvider(config.baseUrl, config.provider);
7238
7691
  const extraHeaders = getProviderHeaders(provider);
7239
7692
  if (Object.keys(extraHeaders).length > 0) {
@@ -7255,6 +7708,17 @@ async function analyzeWithLLM(prompt, config) {
7255
7708
  console.error(`[AgentMoss] totalTimeout (${timeoutCfg.totalTimeout}s) exceeded, aborting all LLM calls`);
7256
7709
  abortController.abort();
7257
7710
  }, totalTimeoutMs);
7711
+ const breaker = getBreaker();
7712
+ if (!breaker.allow()) {
7713
+ try {
7714
+ LLM_SHORT_CIRCUIT_TOTAL.inc(1);
7715
+ } catch {
7716
+ }
7717
+ _recordLlm("error");
7718
+ throw new Error(
7719
+ "LLM \u8C03\u7528\u5DF2\u7194\u65AD\uFF08\u8FDE\u7EED\u5931\u8D25\u8FC7\u591A\uFF09\uFF0C\u51B7\u5374\u671F\u5185\u4E0D\u518D\u53D1\u8D77\u8BF7\u6C42\uFF1B\u68C0\u67E5\u6A21\u578B\u670D\u52A1\u53EF\u7528\u6027\uFF0C\u6216\u8C03 AGENT_MOSS_LLM_CIRCUIT_COOLDOWN"
7720
+ );
7721
+ }
7258
7722
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
7259
7723
  if (abortController.signal.aborted) {
7260
7724
  break;
@@ -7268,22 +7732,49 @@ async function analyzeWithLLM(prompt, config) {
7268
7732
  { role: "system", content: "\u53EA\u8F93\u51FA\u7EAF JSON\uFF0C\u4E0D\u8981\u5305\u542B markdown \u6807\u8BB0\u3001\u4EE3\u7801\u5757\u6216\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002" },
7269
7733
  { role: "user", content: prompt }
7270
7734
  ],
7271
- signal: abortController.signal
7735
+ signal: abortController.signal,
7736
+ // 私有化网关的额外参数(关思考等)原样透传;空则不传。
7737
+ ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
7272
7738
  });
7273
7739
  const message = response.choices[0]?.message;
7274
7740
  const content = message?.content ?? "";
7275
7741
  const finishReason = response.choices[0]?.finish_reason;
7276
- const reasoningLen = typeof message?.reasoning_content === "string" ? message.reasoning_content.length : 0;
7742
+ const fieldLengths = responseFieldLengths(message);
7277
7743
  const usage = response.usage;
7278
7744
  if (!content) {
7279
- const detail = `model=${response.model || config.model} finish_reason=${finishReason} content_len=0 reasoning_len=${reasoningLen} message_keys=${message ? Object.keys(message).join(",") : "(none)"} tokens=${usage?.prompt_tokens ?? "?"}/${usage?.completion_tokens ?? "?"}`;
7745
+ const detail = `model=${response.model || config.model} finish_reason=${finishReason} ` + (Object.keys(fieldLengths).length ? Object.entries(fieldLengths).map(([k, v]) => `${k}_len=${v}`).join(" ") : `all_empty message_keys=${message ? Object.keys(message).join(",") : "(none)"}`) + ` tokens=${usage?.prompt_tokens ?? "?"}/${usage?.completion_tokens ?? "?"}`;
7746
+ traceFull("l3.empty_response", {
7747
+ model: response.model || config.model,
7748
+ finish_reason: finishReason,
7749
+ message,
7750
+ prompt_tokens: usage?.prompt_tokens ?? 0,
7751
+ completion_tokens: usage?.completion_tokens ?? 0
7752
+ });
7753
+ let fullMessage = "<empty>";
7754
+ try {
7755
+ fullMessage = JSON.stringify(message ?? {});
7756
+ if (fullMessage.length > 8e3) {
7757
+ fullMessage = `${fullMessage.slice(0, 8e3)}...[truncated ${fullMessage.length} chars]`;
7758
+ }
7759
+ } catch {
7760
+ fullMessage = "<\u65E0\u6CD5\u5E8F\u5217\u5316>";
7761
+ }
7280
7762
  if (finishReason === "length") {
7281
- console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
7763
+ console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
7282
7764
  throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
7283
7765
  }
7284
- console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
7766
+ console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
7767
+ _recordLlm("empty");
7285
7768
  throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
7286
7769
  }
7770
+ traceFull("l3.response", {
7771
+ phase: "security_judge",
7772
+ attempt: attempt + 1,
7773
+ model: response.model || config.model,
7774
+ content,
7775
+ prompt_tokens: usage?.prompt_tokens ?? 0,
7776
+ completion_tokens: usage?.completion_tokens ?? 0
7777
+ });
7287
7778
  console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
7288
7779
  let jsonStr = content.trim();
7289
7780
  if (jsonStr.startsWith("```")) {
@@ -7314,6 +7805,8 @@ async function analyzeWithLLM(prompt, config) {
7314
7805
  clearTimeout(totalTimeoutTimer);
7315
7806
  const riskLevel = parsed.riskLevel ?? parsed.risk_level;
7316
7807
  const riskType = parsed.riskType ?? parsed.risk_type;
7808
+ breaker.recordSuccess();
7809
+ _recordLlm("success");
7317
7810
  return {
7318
7811
  allowed: parsed.allowed !== false,
7319
7812
  reason: parsed.reason || "LLM \u5206\u6790\u5B8C\u6210",
@@ -7324,6 +7817,7 @@ async function analyzeWithLLM(prompt, config) {
7324
7817
  violatedLayers: ["L3.1"]
7325
7818
  };
7326
7819
  } catch (err) {
7820
+ breaker.recordFailure();
7327
7821
  if (abortController.signal.aborted) {
7328
7822
  console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
7329
7823
  break;
@@ -7384,8 +7878,8 @@ function uuid() {
7384
7878
  var BrainRuleStore = class {
7385
7879
  path;
7386
7880
  data;
7387
- constructor(path5) {
7388
- this.path = path5 || getRulesPath();
7881
+ constructor(path6) {
7882
+ this.path = path6 || getRulesPath();
7389
7883
  this.data = this.load();
7390
7884
  }
7391
7885
  load() {
@@ -7831,10 +8325,10 @@ ${reason.slice(0, 500)}
7831
8325
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
7832
8326
  let mm;
7833
8327
  while ((mm = pathRe.exec(src)) !== null) {
7834
- const path5 = mm[1];
7835
- if (path5.split("/").length < 3) continue;
7836
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path5)) continue;
7837
- const gen = this.generalizePath(path5);
8328
+ const path6 = mm[1];
8329
+ if (path6.split("/").length < 3) continue;
8330
+ if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path6)) continue;
8331
+ const gen = this.generalizePath(path6);
7838
8332
  if (seen.has(gen)) continue;
7839
8333
  seen.add(gen);
7840
8334
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -7853,8 +8347,8 @@ ${reason.slice(0, 500)}
7853
8347
  }
7854
8348
  return false;
7855
8349
  }
7856
- generalizePath(path5) {
7857
- const p = path5.toLowerCase();
8350
+ generalizePath(path6) {
8351
+ const p = path6.toLowerCase();
7858
8352
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
7859
8353
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
7860
8354
  }
@@ -8413,38 +8907,38 @@ function labelEvent(actionDetail) {
8413
8907
  }
8414
8908
  return hits;
8415
8909
  }
8416
- function evaluateLTL(formula, trace, pos) {
8910
+ function evaluateLTL(formula, trace2, pos) {
8417
8911
  const op = formula[0];
8418
8912
  switch (op) {
8419
8913
  case "ap":
8420
- return trace[pos].has(formula[1]);
8914
+ return trace2[pos].has(formula[1]);
8421
8915
  case "!":
8422
- return !evaluateLTL(formula[1], trace, pos);
8916
+ return !evaluateLTL(formula[1], trace2, pos);
8423
8917
  case "&":
8424
- return evaluateLTL(formula[1], trace, pos) && evaluateLTL(formula[2], trace, pos);
8918
+ return evaluateLTL(formula[1], trace2, pos) && evaluateLTL(formula[2], trace2, pos);
8425
8919
  case "|":
8426
- return evaluateLTL(formula[1], trace, pos) || evaluateLTL(formula[2], trace, pos);
8920
+ return evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
8427
8921
  case "->":
8428
- return !evaluateLTL(formula[1], trace, pos) || evaluateLTL(formula[2], trace, pos);
8922
+ return !evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
8429
8923
  case "X":
8430
- return pos + 1 < trace.length && evaluateLTL(formula[1], trace, pos + 1);
8924
+ return pos + 1 < trace2.length && evaluateLTL(formula[1], trace2, pos + 1);
8431
8925
  case "G": {
8432
- for (let j = pos; j < trace.length; j++) {
8433
- if (!evaluateLTL(formula[1], trace, j)) return false;
8926
+ for (let j = pos; j < trace2.length; j++) {
8927
+ if (!evaluateLTL(formula[1], trace2, j)) return false;
8434
8928
  }
8435
8929
  return true;
8436
8930
  }
8437
8931
  case "F": {
8438
- for (let j = pos; j < trace.length; j++) {
8439
- if (evaluateLTL(formula[1], trace, j)) return true;
8932
+ for (let j = pos; j < trace2.length; j++) {
8933
+ if (evaluateLTL(formula[1], trace2, j)) return true;
8440
8934
  }
8441
8935
  return false;
8442
8936
  }
8443
8937
  case "U": {
8444
- for (let j = pos; j < trace.length; j++) {
8445
- if (evaluateLTL(formula[2], trace, j)) {
8938
+ for (let j = pos; j < trace2.length; j++) {
8939
+ if (evaluateLTL(formula[2], trace2, j)) {
8446
8940
  for (let k = pos; k < j; k++) {
8447
- if (!evaluateLTL(formula[1], trace, k)) return false;
8941
+ if (!evaluateLTL(formula[1], trace2, k)) return false;
8448
8942
  }
8449
8943
  return true;
8450
8944
  }
@@ -8473,11 +8967,11 @@ function checkMCRules(graph) {
8473
8967
  const mc = loadMC();
8474
8968
  const rules = mc.rules || [];
8475
8969
  if (rules.length === 0) return violations;
8476
- const trace = nodes.map((n) => labelEvent(n.actionDetail));
8970
+ const trace2 = nodes.map((n) => labelEvent(n.actionDetail));
8477
8971
  const witnessMode = graph.witnessIdx !== void 0;
8478
8972
  for (const rule of rules) {
8479
8973
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
8480
- if (ruleViolates(rule, trace, witnessMode)) {
8974
+ if (ruleViolates(rule, trace2, witnessMode)) {
8481
8975
  violations.push({
8482
8976
  propertyId: String(rule.id || "mc-ltl"),
8483
8977
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
@@ -8649,12 +9143,12 @@ function allNodesFlat(mg) {
8649
9143
  // src/engine/formal-engine/properties.ts
8650
9144
  init_esm_shims();
8651
9145
  init_rules_loader();
8652
- function graphFromPath(nodes, path5, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
9146
+ function graphFromPath(nodes, path6, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
8653
9147
  const byKey = /* @__PURE__ */ new Map();
8654
9148
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
8655
9149
  const gNodes = [];
8656
9150
  const gEdges = [];
8657
- for (const item of path5) {
9151
+ for (const item of path6) {
8658
9152
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
8659
9153
  gNodes.push({
8660
9154
  session_id: item.sessionId,
@@ -8723,22 +9217,22 @@ function checkCrossSessionChain(graph) {
8723
9217
  if (witness !== void 0) {
8724
9218
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
8725
9219
  let matched = 0;
8726
- const path5 = [];
9220
+ const path6 = [];
8727
9221
  for (let k = 0; k < witness; k++) {
8728
9222
  const n = nodes[k];
8729
9223
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
8730
9224
  matched += 1;
8731
- path5.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9225
+ path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
8732
9226
  }
8733
9227
  }
8734
9228
  if (matched < stages.length - 1) continue;
8735
- path5.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
9229
+ path6.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
8736
9230
  violations.push({
8737
9231
  propertyId: "cross-" + chain.id,
8738
9232
  reason: chain.reason,
8739
9233
  riskLevel: chain.riskLevel,
8740
- path: path5,
8741
- graph: graphFromPath(nodes, path5, "next", {
9234
+ path: path6,
9235
+ graph: graphFromPath(nodes, path6, "next", {
8742
9236
  property_id: "cross-" + chain.id,
8743
9237
  property_short: "P1",
8744
9238
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -8748,11 +9242,11 @@ function checkCrossSessionChain(graph) {
8748
9242
  } else {
8749
9243
  let matched = 0;
8750
9244
  let stageIdx = 0;
8751
- const path5 = [];
9245
+ const path6 = [];
8752
9246
  for (const n of nodes) {
8753
9247
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
8754
9248
  matched += 1;
8755
- path5.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9249
+ path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
8756
9250
  stageIdx += 1;
8757
9251
  if (matched >= stages.length) break;
8758
9252
  }
@@ -8762,8 +9256,8 @@ function checkCrossSessionChain(graph) {
8762
9256
  propertyId: "cross-" + chain.id,
8763
9257
  reason: chain.reason,
8764
9258
  riskLevel: chain.riskLevel,
8765
- path: path5,
8766
- graph: graphFromPath(nodes, path5, "next", {
9259
+ path: path6,
9260
+ graph: graphFromPath(nodes, path6, "next", {
8767
9261
  property_id: "cross-" + chain.id,
8768
9262
  property_short: "P1",
8769
9263
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -8810,7 +9304,7 @@ function checkSensitiveDataFlow(graph) {
8810
9304
  }
8811
9305
  }
8812
9306
  }
8813
- const tracePath = (idx) => {
9307
+ const tracePath2 = (idx) => {
8814
9308
  const chain = [idx];
8815
9309
  const seen = /* @__PURE__ */ new Set([idx]);
8816
9310
  while (true) {
@@ -8869,7 +9363,7 @@ function checkSensitiveDataFlow(graph) {
8869
9363
  for (const i of candidates) {
8870
9364
  const n = nodes[i];
8871
9365
  if (tainted.has(i) && EXFIL_RE.test(n.actionDetail)) {
8872
- const chain = tracePath(i);
9366
+ const chain = tracePath2(i);
8873
9367
  violations.push({
8874
9368
  propertyId: "sensitive-data-flow",
8875
9369
  reason: `\u654F\u611F\u6570\u636E\u4F20\u64AD\u5916\u4F20\uFF1A${tainted.get(i).source} \u2192 ${n.sessionId}#${n.seq} \u7ECF\u5171\u4EAB\u8F7D\u4F53\u5916\u53D1`,
@@ -8992,7 +9486,7 @@ function checkNeverExfilAfterPrivesc(graph) {
8992
9486
  if (candidates.length > 0) {
8993
9487
  const pre = nodes[candidates[candidates.length - 1]];
8994
9488
  const post = nodes[firstEv];
8995
- const path5 = [
9489
+ const path6 = [
8996
9490
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
8997
9491
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
8998
9492
  ];
@@ -9000,8 +9494,8 @@ function checkNeverExfilAfterPrivesc(graph) {
9000
9494
  propertyId: "no-exfil-after-privesc",
9001
9495
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
9002
9496
  riskLevel: "critical",
9003
- path: path5,
9004
- graph: graphFromPath(nodes, path5, "next", {
9497
+ path: path6,
9498
+ graph: graphFromPath(nodes, path6, "next", {
9005
9499
  property_id: "no-exfil-after-privesc",
9006
9500
  property_short: "P4",
9007
9501
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -9018,7 +9512,7 @@ function checkNeverExfilAfterPrivesc(graph) {
9018
9512
  for (let j = i + 1; j < nodes.length; j++) {
9019
9513
  if (!isExfilNode(nodes[j])) continue;
9020
9514
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
9021
- const path5 = [
9515
+ const path6 = [
9022
9516
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
9023
9517
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
9024
9518
  ];
@@ -9026,8 +9520,8 @@ function checkNeverExfilAfterPrivesc(graph) {
9026
9520
  propertyId: "no-exfil-after-privesc",
9027
9521
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
9028
9522
  riskLevel: "critical",
9029
- path: path5,
9030
- graph: graphFromPath(nodes, path5, "next", {
9523
+ path: path6,
9524
+ graph: graphFromPath(nodes, path6, "next", {
9031
9525
  property_id: "no-exfil-after-privesc",
9032
9526
  property_short: "P4",
9033
9527
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -9059,7 +9553,7 @@ function checkNeverExfilAfterCred(graph) {
9059
9553
  }
9060
9554
  if (pre) {
9061
9555
  const post = nodes[firstEv];
9062
- const path5 = [
9556
+ const path6 = [
9063
9557
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
9064
9558
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
9065
9559
  ];
@@ -9067,8 +9561,8 @@ function checkNeverExfilAfterCred(graph) {
9067
9561
  propertyId: "no-exfil-after-credential",
9068
9562
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
9069
9563
  riskLevel: "critical",
9070
- path: path5,
9071
- graph: graphFromPath(nodes, path5, "data", {
9564
+ path: path6,
9565
+ graph: graphFromPath(nodes, path6, "data", {
9072
9566
  property_id: "no-exfil-after-credential",
9073
9567
  property_short: "P5",
9074
9568
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -9084,7 +9578,7 @@ function checkNeverExfilAfterCred(graph) {
9084
9578
  if (!isCredNode(nodes[i])) continue;
9085
9579
  for (let j = i + 1; j < nodes.length; j++) {
9086
9580
  if (isExfilNode(nodes[j])) {
9087
- const path5 = [
9581
+ const path6 = [
9088
9582
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
9089
9583
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
9090
9584
  ];
@@ -9092,8 +9586,8 @@ function checkNeverExfilAfterCred(graph) {
9092
9586
  propertyId: "no-exfil-after-credential",
9093
9587
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
9094
9588
  riskLevel: "critical",
9095
- path: path5,
9096
- graph: graphFromPath(nodes, path5, "data", {
9589
+ path: path6,
9590
+ graph: graphFromPath(nodes, path6, "data", {
9097
9591
  property_id: "no-exfil-after-credential",
9098
9592
  property_short: "P5",
9099
9593
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -9257,13 +9751,13 @@ function checkSensitiveDataAggregation(graph) {
9257
9751
  if (!isExfilNode(n)) continue;
9258
9752
  const srcs = sourcesFor(i);
9259
9753
  if (srcs.size >= 2) {
9260
- const path5 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
9754
+ const path6 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
9261
9755
  violations.push({
9262
9756
  propertyId: "sensitive-data-aggregation",
9263
9757
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
9264
9758
  riskLevel: "critical",
9265
- path: path5,
9266
- graph: graphFromPath(nodes, path5, "next", {
9759
+ path: path6,
9760
+ graph: graphFromPath(nodes, path6, "next", {
9267
9761
  property_id: "sensitive-data-aggregation",
9268
9762
  property_short: "P8",
9269
9763
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -9353,9 +9847,9 @@ init_rules_loader();
9353
9847
 
9354
9848
  // src/engine/formal-engine/chain_state.ts
9355
9849
  init_esm_shims();
9356
- import * as fs4 from "fs";
9850
+ import * as fs5 from "fs";
9357
9851
  import * as os2 from "os";
9358
- import * as path4 from "path";
9852
+ import * as path5 from "path";
9359
9853
  import { createHash as createHash2 } from "crypto";
9360
9854
 
9361
9855
  // src/engine/coordinator.ts
@@ -9447,6 +9941,14 @@ var formalEngine = new FormalEngine();
9447
9941
  async function runAnalysis(input) {
9448
9942
  const observedFormalLayers = [];
9449
9943
  const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
9944
+ if (heuristicResult) {
9945
+ traceSummary("l1.result", {
9946
+ hit: !heuristicResult.allowed,
9947
+ risk_level: heuristicResult.riskLevel,
9948
+ risk_type: heuristicResult.riskType,
9949
+ reason: heuristicResult.reason
9950
+ });
9951
+ }
9450
9952
  const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
9451
9953
  const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
9452
9954
  if (heuristicResult && !heuristicResult.allowed) {
@@ -9590,6 +10092,14 @@ async function runAnalysis(input) {
9590
10092
  }
9591
10093
  }
9592
10094
  const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
10095
+ if (logicResult) {
10096
+ traceSummary("l2.result", {
10097
+ hit: !logicResult.allowed,
10098
+ risk_level: logicResult.riskLevel,
10099
+ risk_type: logicResult.riskType,
10100
+ reason: logicResult.reason
10101
+ });
10102
+ }
9593
10103
  const l1FileAccessHit = !!(heuristicResult && !heuristicResult.allowed && heuristicResult.riskType === "file_access");
9594
10104
  const effectiveResult = logicResult && !logicResult.allowed ? logicResult : l1FileAccessHit ? heuristicResult : null;
9595
10105
  if (effectiveResult) {