@kenhkl/agent-moss 0.17.45 → 0.17.46

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.
@@ -1146,7 +1146,8 @@ function getSensitivePathsForOs(osType) {
1146
1146
  credential: r.credential === true ? true : void 0,
1147
1147
  readOnly: r.readOnly === true ? true : void 0,
1148
1148
  denyMode: r.denyMode || void 0,
1149
- dirDelOnly: r.dirDelOnly === true ? true : void 0
1149
+ dirDelOnly: r.dirDelOnly === true ? true : void 0,
1150
+ askOnMatch: r.askOnMatch === true ? true : void 0
1150
1151
  };
1151
1152
  const scope = _scopeOf(r.os, r.path);
1152
1153
  if (scope === "home") home.push(entry);
@@ -1252,15 +1253,15 @@ function isScriptGeneratedTarget(targetPath, writtenScripts, shellRuns) {
1252
1253
  if (!script.detail.includes(base)) continue;
1253
1254
  const scriptName = path2.basename(script.path);
1254
1255
  if (!scriptName) continue;
1255
- if (shellRuns.some((run) => run.index > script.index && run.command.includes(scriptName))) {
1256
+ if (shellRuns.some((run2) => run2.index > script.index && run2.command.includes(scriptName))) {
1256
1257
  return true;
1257
1258
  }
1258
1259
  }
1259
1260
  return false;
1260
1261
  }
1261
1262
  function parseHeadTailLimit(seg) {
1262
- const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
1263
- if (firstWord !== "head" && firstWord !== "tail") return null;
1263
+ const firstWord2 = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
1264
+ if (firstWord2 !== "head" && firstWord2 !== "tail") return null;
1264
1265
  const m = seg.match(HEAD_TAIL_LIMIT_RE);
1265
1266
  return m ? Number(m[1]) : 10;
1266
1267
  }
@@ -1293,17 +1294,17 @@ function historyReadCoverage(histType, histDetailRaw, readKeywords, writeKeyword
1293
1294
  for (const rawSeg of segments) {
1294
1295
  const seg = rawSeg.trim();
1295
1296
  if (!seg) continue;
1296
- const firstWord = seg.split(/\s+/)[0]?.toLowerCase() || "";
1297
+ const firstWord2 = seg.split(/\s+/)[0]?.toLowerCase() || "";
1297
1298
  const paths = extractFilePaths(seg);
1298
1299
  if (paths.length === 0) continue;
1299
- if (SHELL_FULL_READ_CMDS.includes(firstWord)) {
1300
+ if (SHELL_FULL_READ_CMDS.includes(firstWord2)) {
1300
1301
  if (hasTruncatingPipe) addPartial(paths, parseHeadTailLimitForPipeline(segments));
1301
1302
  else for (const p of paths) full.add(p);
1302
- } else if (firstWord === "head" || firstWord === "tail") {
1303
+ } else if (firstWord2 === "head" || firstWord2 === "tail") {
1303
1304
  addPartial(paths, parseHeadTailLimit(seg));
1304
- } else if (SHELL_PARTIAL_READ_CMDS.includes(firstWord)) {
1305
+ } else if (SHELL_PARTIAL_READ_CMDS.includes(firstWord2)) {
1305
1306
  addPartial(paths, null);
1306
- } else if (firstWord === "sed") {
1307
+ } else if (firstWord2 === "sed") {
1307
1308
  if (SED_INPLACE_RE.test(seg)) continue;
1308
1309
  const m = seg.match(SED_RANGE_RE);
1309
1310
  if (m) {
@@ -1386,8 +1387,8 @@ function appendOnlyTargets(actionDetailRaw, osType) {
1386
1387
  const p = m[1] || m[2] || m[3];
1387
1388
  if (p) out.add(p);
1388
1389
  }
1389
- const firstWord = seg.split(/\s+/)[0]?.toLowerCase() || "";
1390
- if (firstWord === "tee" && /(?:^|\s)(?:-a|--append)(?:\s|$)/.test(seg)) {
1390
+ const firstWord2 = seg.split(/\s+/)[0]?.toLowerCase() || "";
1391
+ if (firstWord2 === "tee" && /(?:^|\s)(?:-a|--append)(?:\s|$)/.test(seg)) {
1391
1392
  for (const p of extractFilePaths(seg, osType)) out.add(p);
1392
1393
  }
1393
1394
  }
@@ -1435,9 +1436,44 @@ function intentKeywordNegated(text, index) {
1435
1436
  const prefix = text.slice(Math.max(0, index - NEGATION_WINDOW), index);
1436
1437
  return NEGATION_WORDS.some((neg) => prefix.includes(neg));
1437
1438
  }
1439
+ function isMediaCleanupInWorkdir(text) {
1440
+ const segs = splitCommandSegments(text).map((s) => s.trim()).filter(Boolean);
1441
+ let cdTarget = "";
1442
+ let found = false;
1443
+ for (const seg of segs) {
1444
+ const parts = seg.split(/\s+/);
1445
+ if (!parts.length) continue;
1446
+ const head = parts[0].toLowerCase();
1447
+ if (head === "cd" || head === "pushd") {
1448
+ const target = (parts[1] || "").replace(/^['"]+|['"]+$/g, "");
1449
+ const segPaths = target.split("/").filter(Boolean);
1450
+ cdTarget = target.startsWith("/") && segPaths.length > 0 && !SYSTEM_PATH_FIRST.has(segPaths[0].toLowerCase()) && segPaths.some((p) => WORKDIR_SEGMENTS.has(p.toLowerCase())) ? target : "";
1451
+ continue;
1452
+ }
1453
+ if (head !== "rm" || !cdTarget) continue;
1454
+ const flagStr = parts.slice(1).filter((t) => t.startsWith("-")).join("").toLowerCase();
1455
+ if (flagStr.includes("r") || !flagStr.includes("f")) return false;
1456
+ const targets = parts.slice(1).filter((t) => !t.startsWith("-")).map((t) => t.replace(/^['"]+|['"]+$/g, ""));
1457
+ if (!targets.length) return false;
1458
+ for (let t of targets) {
1459
+ t = t.replace(/\\/g, "/");
1460
+ while (t.startsWith("./")) t = t.slice(2);
1461
+ if (!t || [".", "*", "?"].includes(t)) return false;
1462
+ if (t.startsWith("/") || t.split("/").includes("..")) return false;
1463
+ if (t.includes("*") || t.includes("?")) {
1464
+ if (!MEDIA_GLOB_RE.test(t)) return false;
1465
+ } else if (!MEDIA_FILE_RE.test(t)) {
1466
+ return false;
1467
+ }
1468
+ found = true;
1469
+ }
1470
+ }
1471
+ return found;
1472
+ }
1438
1473
  function isBuildArtifactCleanup(actionDetail) {
1439
1474
  const text = (actionDetail || "").trim();
1440
1475
  if (!text) return false;
1476
+ if (isMediaCleanupInWorkdir(text)) return true;
1441
1477
  let foundRm = false;
1442
1478
  const targets = [];
1443
1479
  for (const raw of splitCommandSegments(text)) {
@@ -1548,6 +1584,17 @@ function intentMatrixViolation(intents, actionCat) {
1548
1584
  }
1549
1585
  return null;
1550
1586
  }
1587
+ function getIntentPatternsForOs(osType) {
1588
+ const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
1589
+ if (effective) {
1590
+ return effective.map((p) => ({
1591
+ ...p,
1592
+ allowIfWriteIntent: p.allowIfWriteIntent ?? INTENT_DEVIATION_PATTERNS.find((d) => d.reason === p.reason)?.allowIfWriteIntent ?? false
1593
+ }));
1594
+ }
1595
+ const accepted = acceptedOsValues(osType);
1596
+ return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
1597
+ }
1551
1598
  function resolveIntentText(promptSession, promptHistory, intentKeywords) {
1552
1599
  const cur = (promptSession || "").trim().toLowerCase();
1553
1600
  if (intentKeywords.some((kw) => cur.includes(kw))) return cur;
@@ -1637,6 +1684,14 @@ function checkIntentConsistency(input, agentExt) {
1637
1684
  };
1638
1685
  }
1639
1686
  if (reasonKey !== null) {
1687
+ let askReason = "";
1688
+ for (const pat of getIntentPatternsForOs(input.osType)) {
1689
+ if (!pat.askOnMatch) continue;
1690
+ if ((pat.intentKeywords || []).some((k) => intentText.includes(String(k).toLowerCase())) && (pat.dangerousActions || []).some((a) => actionDetail.includes(String(a).toLowerCase()))) {
1691
+ askReason = `\u89C4\u5219\u300C${pat.reason}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237`;
1692
+ break;
1693
+ }
1694
+ }
1640
1695
  return {
1641
1696
  allowed: false,
1642
1697
  reason: INTENT_REASONS[reasonKey] || "\u539F\u59CB\u610F\u56FE\u4E0E\u6267\u884C\u52A8\u4F5C\u4E0D\u4E00\u81F4",
@@ -1644,7 +1699,8 @@ function checkIntentConsistency(input, agentExt) {
1644
1699
  riskType: "intent_deviation",
1645
1700
  confidence: 85,
1646
1701
  source: "logic_rule",
1647
- violatedLayers: ["L2.1"]
1702
+ violatedLayers: ["L2.1"],
1703
+ ...askReason ? { ask_recommended: true, ask_reason: askReason } : {}
1648
1704
  };
1649
1705
  }
1650
1706
  if ((actionCat === "overwrite" || actionCat === "delete") && intents.size === 0) {
@@ -1706,6 +1762,25 @@ function runLogicCheck(input, opts) {
1706
1762
  if (comboResult) return comboResult;
1707
1763
  return null;
1708
1764
  }
1765
+ function computeComboStageHits(detail) {
1766
+ const hits = /* @__PURE__ */ new Set();
1767
+ for (const [stage, pats] of Object.entries(COMBO_STAGES)) {
1768
+ if (pats.some((p) => {
1769
+ p.lastIndex = 0;
1770
+ return p.test(detail);
1771
+ })) hits.add(stage);
1772
+ }
1773
+ return hits;
1774
+ }
1775
+ function comboStageHits(detail) {
1776
+ if (detail.length > 2048) return computeComboStageHits(detail);
1777
+ const cached2 = comboStageHitsCache.get(detail);
1778
+ if (cached2) return cached2;
1779
+ const value = computeComboStageHits(detail);
1780
+ if (comboStageHitsCache.size >= COMBO_STAGE_CACHE_MAX) comboStageHitsCache.clear();
1781
+ comboStageHitsCache.set(detail, value);
1782
+ return value;
1783
+ }
1709
1784
  function checkComboChain(actionHistory, actionDetailRaw) {
1710
1785
  INLINE_SCRIPT_RE.lastIndex = 0;
1711
1786
  if (INLINE_SCRIPT_RE.test(actionDetailRaw)) return null;
@@ -1714,16 +1789,7 @@ function checkComboChain(actionHistory, actionDetailRaw) {
1714
1789
  if (h.actionDetail) details.push(h.actionDetail.toLowerCase());
1715
1790
  }
1716
1791
  details.push(actionDetailRaw.toLowerCase());
1717
- const seq = details.map((d) => {
1718
- const hits = /* @__PURE__ */ new Set();
1719
- for (const [stage, pats] of Object.entries(COMBO_STAGES)) {
1720
- if (pats.some((p) => {
1721
- p.lastIndex = 0;
1722
- return p.test(d);
1723
- })) hits.add(stage);
1724
- }
1725
- return hits;
1726
- });
1792
+ const seq = details.map((d) => comboStageHits(d));
1727
1793
  for (const chain of COMBO_CHAINS) {
1728
1794
  const chainStages = chain.stages;
1729
1795
  if (!chainStages.length || chain.min_stages <= 0) continue;
@@ -1830,15 +1896,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1830
1896
  for (const seg of singleFileTool ? [] : splitCommandSegments(actionDetailRaw)) {
1831
1897
  const trimmed = seg.trim();
1832
1898
  if (!trimmed) continue;
1833
- const firstWord = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
1834
- if (firstWord === "cd") {
1899
+ const firstWord2 = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
1900
+ if (firstWord2 === "cd") {
1835
1901
  continue;
1836
1902
  }
1837
1903
  if (SHELL_ASSIGN_RE.test(trimmed)) {
1838
1904
  continue;
1839
1905
  }
1840
- if (firstWord === "sed" && SED_INPLACE_RE.test(trimmed)) {
1841
- } else if (getPlatformTraits(osType).readOnlyCommands.has(firstWord)) {
1906
+ if (firstWord2 === "sed" && SED_INPLACE_RE.test(trimmed)) {
1907
+ } else if (getPlatformTraits(osType).readOnlyCommands.has(firstWord2)) {
1842
1908
  const segUnquoted = trimmed.replace(new RegExp(`>{1,2}\\s*(['"])([~./][^'"]+)\\1`, "g"), (_m, _q, p) => ">" + p);
1843
1909
  const segNoDevnull = segUnquoted.replace(DEVNULL_REDIRECT_RE, "");
1844
1910
  const segNoQuotes = segNoDevnull.replace(/'[^']*'|"[^"]*"/g, "");
@@ -1847,15 +1913,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1847
1913
  continue;
1848
1914
  }
1849
1915
  const segPaths = extractFilePaths(trimmed, osType);
1850
- const segPathsFiltered = firstWord === "wget" || firstWord === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
1851
- if (SOURCE_ARG_CMDS.has(firstWord)) {
1916
+ const segPathsFiltered = firstWord2 === "wget" || firstWord2 === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
1917
+ if (SOURCE_ARG_CMDS.has(firstWord2)) {
1852
1918
  if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
1853
- } else if (firstWord === "tar") {
1919
+ } else if (firstWord2 === "tar") {
1854
1920
  if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
1855
1921
  const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
1856
1922
  if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
1857
1923
  }
1858
- } else if (firstWord === "dd") {
1924
+ } else if (firstWord2 === "dd") {
1859
1925
  const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
1860
1926
  const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
1861
1927
  const devNullMatches = trimmed.match(/\bof=(\/dev\/\S+)/g);
@@ -2027,7 +2093,8 @@ function hasValidConsent(actionHistory, aNext) {
2027
2093
  }
2028
2094
  function checkPasswordConsent(actionType, actionDetail, actionHistory, osType, aNext) {
2029
2095
  if (!BASH_LIKE_ACTION_TYPES.includes(actionType)) return null;
2030
- const pwdPatterns = runtimeConfigBridge.current?.effectivePasswordPatterns(osType) ?? PASSWORD_MODIFY_PATTERNS;
2096
+ const pwdRules = runtimeConfigBridge.current?.effectivePasswordRules(osType) ?? PASSWORD_MODIFY_PATTERNS.map((p) => ({ pattern: p, askOnMatch: false }));
2097
+ const pwdPatterns = pwdRules.map((r) => r.pattern);
2031
2098
  let isPasswordModify = pwdPatterns.some((p) => p.test(actionDetail));
2032
2099
  if (isPasswordModify && !hasExecBypassChain(actionDetail)) {
2033
2100
  const noQuotes = actionDetail.replace(ALL_QUOTES_RE, " ");
@@ -2035,6 +2102,7 @@ function checkPasswordConsent(actionType, actionDetail, actionHistory, osType, a
2035
2102
  }
2036
2103
  if (!isPasswordModify) return null;
2037
2104
  if (hasValidConsent(actionHistory, aNext)) return null;
2105
+ const askRule = pwdRules.find((r) => r.askOnMatch && r.pattern.test(actionDetail));
2038
2106
  return {
2039
2107
  allowed: false,
2040
2108
  reason: "\u6267\u884C\u975E\u4EA4\u4E92\u5F0F\u5BC6\u7801\u4FEE\u6539\u547D\u4EE4\uFF0C\u4F46\u5386\u53F2\u6267\u884C\u5E8F\u5217\u4E2D\u672A\u53D1\u73B0\u7528\u6237\u660E\u786E\u6388\u6743\u7684 ask_user_question\uFF08\u987B\u7528\u6237\u6B63\u9762\u56DE\u7B54\u4E14\u4E0E\u672C\u6B21\u64CD\u4F5C\u76F8\u5173\uFF09\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6388\u6743\u7684\u5BC6\u7801\u4FEE\u6539\u98CE\u9669",
@@ -2042,15 +2110,18 @@ function checkPasswordConsent(actionType, actionDetail, actionHistory, osType, a
2042
2110
  riskType: "consent_missing",
2043
2111
  confidence: 85,
2044
2112
  source: "logic_rule",
2045
- violatedLayers: ["L2.1"]
2113
+ violatedLayers: ["L2.1"],
2114
+ ...askRule ? { ask_recommended: true, ask_reason: "\u5BC6\u7801\u4FEE\u6539\u89C4\u5219\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237" } : {}
2046
2115
  };
2047
2116
  }
2048
2117
  function checkUserDeletionConsent(actionType, actionDetail, actionHistory, osType, aNext) {
2049
2118
  if (!BASH_LIKE_ACTION_TYPES.includes(actionType)) return null;
2050
- const udPatterns = runtimeConfigBridge.current?.effectiveUserDeletionPatterns(osType) ?? USER_DELETION_PATTERNS;
2119
+ const udRules = runtimeConfigBridge.current?.effectiveUserDeletionRules(osType) ?? USER_DELETION_PATTERNS.map((p) => ({ pattern: p, askOnMatch: false }));
2120
+ const udPatterns = udRules.map((r) => r.pattern);
2051
2121
  const isUserDeletion = udPatterns.some((p) => p.test(actionDetail));
2052
2122
  if (!isUserDeletion) return null;
2053
2123
  if (hasValidConsent(actionHistory, aNext)) return null;
2124
+ const askRule = udRules.find((r) => r.askOnMatch && r.pattern.test(actionDetail));
2054
2125
  return {
2055
2126
  allowed: false,
2056
2127
  reason: "\u6267\u884C\u5220\u9664\u7CFB\u7EDF\u7528\u6237\u547D\u4EE4\uFF0C\u4F46\u5386\u53F2\u6267\u884C\u5E8F\u5217\u4E2D\u672A\u53D1\u73B0\u7528\u6237\u660E\u786E\u6388\u6743\u7684 ask_user_question\uFF08\u987B\u7528\u6237\u6B63\u9762\u56DE\u7B54\u4E14\u4E0E\u672C\u6B21\u64CD\u4F5C\u76F8\u5173\uFF09\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6388\u6743\u7684\u7528\u6237\u5220\u9664\u98CE\u9669",
@@ -2058,7 +2129,8 @@ function checkUserDeletionConsent(actionType, actionDetail, actionHistory, osTyp
2058
2129
  riskType: "consent_missing",
2059
2130
  confidence: 85,
2060
2131
  source: "logic_rule",
2061
- violatedLayers: ["L2.1"]
2132
+ violatedLayers: ["L2.1"],
2133
+ ...askRule ? { ask_recommended: true, ask_reason: "\u7528\u6237\u5220\u9664\u89C4\u5219\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237" } : {}
2062
2134
  };
2063
2135
  }
2064
2136
  function containsPrivilegeEscalation(actionDetail) {
@@ -2152,7 +2224,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2152
2224
  violatedLayers: ["L2.1"]
2153
2225
  };
2154
2226
  }
2155
- var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SCRIPT_FILE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, NEGATION_WORDS, NEGATION_WINDOW, EXPLICIT_READONLY_RE, UPDATE_INTENT_RE, EXPLICIT_NO_DELETE_RE, INTENT_AMBIGUITY_RE, BUILD_ARTIFACT_NAMES, BUILD_ARTIFACT_GLOB_RE, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
2227
+ var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SCRIPT_FILE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, NEGATION_WORDS, NEGATION_WINDOW, EXPLICIT_READONLY_RE, UPDATE_INTENT_RE, EXPLICIT_NO_DELETE_RE, INTENT_AMBIGUITY_RE, BUILD_ARTIFACT_NAMES, BUILD_ARTIFACT_GLOB_RE, MEDIA_TEMP_EXTS, MEDIA_GLOB_RE, MEDIA_FILE_RE, WORKDIR_SEGMENTS, SYSTEM_PATH_FIRST, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, COMBO_STAGE_CACHE_MAX, comboStageHitsCache, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
2156
2228
  var init_logic_rules = __esm({
2157
2229
  "src/engine/logic-rules.ts"() {
2158
2230
  "use strict";
@@ -2279,6 +2351,48 @@ var init_logic_rules = __esm({
2279
2351
  "htmlcov"
2280
2352
  ]);
2281
2353
  BUILD_ARTIFACT_GLOB_RE = /^\*\.(?:pyc|pyo|class|o|obj|d|egg-info)$/i;
2354
+ MEDIA_TEMP_EXTS = "mp4|mov|avi|mkv|webm|flv|wmv|m4v|jpg|jpeg|png|gif|webp|bmp|tif|tiff|wav|mp3|m4a|aac|flac|ogg|tmp|part|log";
2355
+ MEDIA_GLOB_RE = new RegExp(`^[A-Za-z0-9_.-]+\\*\\.(?:${MEDIA_TEMP_EXTS})$`, "i");
2356
+ MEDIA_FILE_RE = new RegExp(`^[A-Za-z0-9_.-]+\\.(?:${MEDIA_TEMP_EXTS})$`, "i");
2357
+ WORKDIR_SEGMENTS = /* @__PURE__ */ new Set([
2358
+ "result",
2359
+ "results",
2360
+ "output",
2361
+ "outputs",
2362
+ "out",
2363
+ "work",
2364
+ "workdir",
2365
+ "work_extract",
2366
+ "tmp",
2367
+ "temp",
2368
+ "cache",
2369
+ ".cache",
2370
+ "build",
2371
+ "dist",
2372
+ "target",
2373
+ "extract",
2374
+ "extracted",
2375
+ "clips",
2376
+ "artifacts",
2377
+ "__pycache__"
2378
+ ]);
2379
+ SYSTEM_PATH_FIRST = /* @__PURE__ */ new Set([
2380
+ "etc",
2381
+ "usr",
2382
+ "bin",
2383
+ "sbin",
2384
+ "lib",
2385
+ "lib64",
2386
+ "boot",
2387
+ "root",
2388
+ "sys",
2389
+ "proc",
2390
+ "dev",
2391
+ "run",
2392
+ "srv",
2393
+ "home",
2394
+ "var"
2395
+ ]);
2282
2396
  REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
2283
2397
  REFERENCE_LOOKBACK = 3;
2284
2398
  EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
@@ -2300,6 +2414,8 @@ var init_logic_rules = __esm({
2300
2414
  reason: String(c.reason || "\u68C0\u6D4B\u5230\u7EC4\u5408\u653B\u51FB\u94FE")
2301
2415
  }));
2302
2416
  })();
2417
+ COMBO_STAGE_CACHE_MAX = 8192;
2418
+ comboStageHitsCache = /* @__PURE__ */ new Map();
2303
2419
  CONSENT_TOPIC = /密码|口令|passwd|password|凭据|凭证|用户|账户|账号|userdel|deluser|groupdel/i;
2304
2420
  CONSENT_NEGATIVE = /(?:否|不|别|取消|拒绝|停止|终止|算了|\bno\b|\bnope\b|\bcancel\b|\babort\b|\bstop\b|\bdeny\b|\breject\b|\bdecline\b|\bdon'?t\b|\bdo\s+not\b)/i;
2305
2421
  CONSENT_AFFIRMATIVE = /(?:是|好|可以|行|嗯|对|确认|同意|继续|执行|删除|删掉|移除|修改|重置|改密|\byes\b|\by\b|\byep\b|\byeah\b|\bok\b|\bokay\b|\bconfirm(?:ed)?\b|\bproceed\b|\bcontinue\b|\bsure\b|\bapprove\b|\baccept\b|\bagree\b|\bdo\s+it\b|\bgo\s+ahead\b)/i;
@@ -2482,6 +2598,7 @@ var init_skill_loader = __esm({
2482
2598
  // src/infra/runtime-config.ts
2483
2599
  var runtime_config_exports = {};
2484
2600
  __export(runtime_config_exports, {
2601
+ BUILTIN_DETECTOR_DEFAULTS: () => BUILTIN_DETECTOR_DEFAULTS,
2485
2602
  DEFAULT_LAYERS: () => DEFAULT_LAYERS,
2486
2603
  DENY_MODE_LABELS: () => DENY_MODE_LABELS,
2487
2604
  addAgentRule: () => addAgentRule,
@@ -2496,14 +2613,19 @@ __export(runtime_config_exports, {
2496
2613
  effectiveInjectionKeywords: () => effectiveInjectionKeywords,
2497
2614
  effectiveIntentPatterns: () => effectiveIntentPatterns,
2498
2615
  effectivePasswordPatterns: () => effectivePasswordPatterns,
2616
+ effectivePasswordRules: () => effectivePasswordRules,
2499
2617
  effectiveSensitivePaths: () => effectiveSensitivePaths,
2500
2618
  effectiveUserDeletionPatterns: () => effectiveUserDeletionPatterns,
2619
+ effectiveUserDeletionRules: () => effectiveUserDeletionRules,
2501
2620
  filterEnabledRules: () => filterEnabledRules,
2502
2621
  generateSourceDefaults: () => generateSourceDefaults,
2503
2622
  getAgentRules: () => getAgentRules,
2623
+ getBuiltinAskMap: () => getBuiltinAskMap,
2504
2624
  getDisabledL2RulesWithSkipL3: () => getDisabledL2RulesWithSkipL3,
2505
2625
  getDisabledSkillIds: () => getDisabledSkillIds,
2506
2626
  getEnabledAgentExtensions: () => getEnabledAgentExtensions,
2627
+ getEnabledBuiltinDetectors: () => getEnabledBuiltinDetectors,
2628
+ getEnabledBuiltinDetectorsOrCurrent: () => getEnabledBuiltinDetectorsOrCurrent,
2507
2629
  getEnabledL1CommandPatterns: () => getEnabledL1CommandPatterns,
2508
2630
  getEnabledL1CommandPatternsOrDefault: () => getEnabledL1CommandPatternsOrDefault,
2509
2631
  getEnabledL1InjectionKeywords: () => getEnabledL1InjectionKeywords,
@@ -2512,10 +2634,12 @@ __export(runtime_config_exports, {
2512
2634
  getEnabledL2IntentPatternsOrDefault: () => getEnabledL2IntentPatternsOrDefault,
2513
2635
  getEnabledL2PasswordPatterns: () => getEnabledL2PasswordPatterns,
2514
2636
  getEnabledL2PasswordPatternsOrDefault: () => getEnabledL2PasswordPatternsOrDefault,
2637
+ getEnabledL2PasswordRules: () => getEnabledL2PasswordRules,
2515
2638
  getEnabledL2SensitivePaths: () => getEnabledL2SensitivePaths,
2516
2639
  getEnabledL2SensitivePathsOrDefault: () => getEnabledL2SensitivePathsOrDefault,
2517
2640
  getEnabledL2UserDeletionPatterns: () => getEnabledL2UserDeletionPatterns,
2518
2641
  getEnabledL2UserDeletionPatternsOrDefault: () => getEnabledL2UserDeletionPatternsOrDefault,
2642
+ getEnabledL2UserDeletionRules: () => getEnabledL2UserDeletionRules,
2519
2643
  getEnabledScenarioExtensions: () => getEnabledScenarioExtensions,
2520
2644
  getEnvOverrides: () => getEnvOverrides,
2521
2645
  getProfileOrDetect: () => getProfileOrDetect,
@@ -2532,8 +2656,11 @@ __export(runtime_config_exports, {
2532
2656
  saveRuntimeConfig: () => saveRuntimeConfig,
2533
2657
  updateAgentCategoryEnabled: () => updateAgentCategoryEnabled,
2534
2658
  updateAgentRuleEnabled: () => updateAgentRuleEnabled,
2659
+ updateCategoryAsk: () => updateCategoryAsk,
2535
2660
  updateCategoryEnabled: () => updateCategoryEnabled,
2661
+ updateInjectionTierEnabled: () => updateInjectionTierEnabled,
2536
2662
  updateLayerEnabled: () => updateLayerEnabled,
2663
+ updateRuleAsk: () => updateRuleAsk,
2537
2664
  updateRuleDenyMode: () => updateRuleDenyMode,
2538
2665
  updateRuleEnabled: () => updateRuleEnabled,
2539
2666
  updateRuleSkipL3: () => updateRuleSkipL3,
@@ -2731,23 +2858,22 @@ function getEnabledL1CommandPatterns(runtime, osType) {
2731
2858
  rules = _mergeUserCustom(rules, runtime, "L1_rules", "pattern");
2732
2859
  if (osType) rules = _filterRulesByOs(rules, osType);
2733
2860
  return rules.map((r) => ({
2861
+ id: r.id || "",
2734
2862
  pattern: r.pattern || "",
2735
2863
  risk_level: r.risk_level || "",
2736
2864
  risk_type: r.risk_type || "",
2737
- reason: r.reason || ""
2865
+ reason: r.reason || "",
2866
+ ask_on_match: r.ask_on_match === true
2738
2867
  }));
2739
2868
  }
2740
2869
  function getEnabledL2SensitivePaths(runtime, osType) {
2741
- let cat = runtime.L1_rules?.sensitive_path_access;
2742
- if (!cat || !cat.rules || cat.rules.length === 0) {
2743
- cat = runtime.L2_rules?.sensitive_path_access || { category_enabled: true, rules: [] };
2744
- }
2870
+ const cat = _sensitivePathCategoryOf(runtime) || { category_enabled: true, rules: [] };
2745
2871
  let rules = filterEnabledRules(cat.rules || [], cat.category_enabled);
2746
2872
  rules = _mergeRulesFromDirs(rules, "sensitive_path_access");
2747
2873
  rules = _mergeUserCustom(rules, runtime, ["L1_rules", "L2_rules"], "path");
2748
2874
  if (osType) rules = _filterRulesByOs(rules, osType);
2749
2875
  return rules.map((r) => {
2750
- const out = { path: r.path || "", risk_level: r.risk_level || "", desc: r.desc || "", deny_mode: r.deny_mode || "deny_write" };
2876
+ const out = { id: r.id || "", path: r.path || "", risk_level: r.risk_level || "", desc: r.desc || "", deny_mode: r.deny_mode || "deny_write", ask_on_match: r.ask_on_match === true };
2751
2877
  if (r.credential) out.credential = true;
2752
2878
  if (r.read_only) out.read_only = true;
2753
2879
  if (r.dir_del_only) out.dir_del_only = true;
@@ -2852,7 +2978,8 @@ function _l1CommandPatternsToRules() {
2852
2978
  reason: p.description,
2853
2979
  enabled: true,
2854
2980
  builtin: true,
2855
- os: p.os || "linux"
2981
+ os: p.os || "linux",
2982
+ ask_on_match: p.ask_on_match === true
2856
2983
  };
2857
2984
  const fp = _ruleFingerprint(rule);
2858
2985
  if (seen.has(fp)) continue;
@@ -2868,6 +2995,7 @@ function _l1InjectionKeywordsToRules() {
2868
2995
  keyword: kw.keyword,
2869
2996
  risk_level: kw.riskLevel,
2870
2997
  lang: kw.lang || "en",
2998
+ tier: kw.tier || "",
2871
2999
  // 带上条目自己的 os(`all` = 全平台通用),别丢 —— 丢了 Windows 会拿到
2872
3000
  // 本不该给它的条目。与 Python `_l1_injection_keywords_to_rules` 对齐。
2873
3001
  os: kw.os,
@@ -2901,7 +3029,8 @@ function _l2SensitivePathsToRules() {
2901
3029
  skip_l3_on_disabled: true,
2902
3030
  enabled: true,
2903
3031
  builtin: true,
2904
- os: os5
3032
+ os: os5,
3033
+ ask_on_match: sp.ask_on_match === true
2905
3034
  };
2906
3035
  _syncDenyModeFields(rule);
2907
3036
  if (sp.dirDelOnly) rule.dir_del_only = true;
@@ -2924,7 +3053,8 @@ function _l2IntentPatternsToRules() {
2924
3053
  allow_if_write_intent: pat.allowIfWriteIntent,
2925
3054
  skip_l3_on_disabled: true,
2926
3055
  enabled: true,
2927
- builtin: true
3056
+ builtin: true,
3057
+ ask_on_match: pat.askOnMatch === true
2928
3058
  }));
2929
3059
  }
2930
3060
  function _l2PasswordPatternsToRules() {
@@ -3094,6 +3224,19 @@ function _agentRulesToDefaults() {
3094
3224
  }
3095
3225
  return out;
3096
3226
  }
3227
+ function getEnabledBuiltinDetectors(runtime) {
3228
+ const cat = runtime?.L1_rules?.builtin_detectors;
3229
+ if (!cat || typeof cat !== "object") {
3230
+ return new Set(BUILTIN_DETECTOR_DEFAULTS.map((r) => r.id));
3231
+ }
3232
+ if (cat.category_enabled === false) return /* @__PURE__ */ new Set();
3233
+ return new Set(
3234
+ (cat.rules || []).filter((r) => r && r.id && r.enabled !== false && !r.source_removed).map((r) => String(r.id))
3235
+ );
3236
+ }
3237
+ function getEnabledBuiltinDetectorsOrCurrent() {
3238
+ return getEnabledBuiltinDetectors(loadRuntimeConfig());
3239
+ }
3097
3240
  function generateSourceDefaults() {
3098
3241
  return {
3099
3242
  version: 1,
@@ -3106,7 +3249,8 @@ function generateSourceDefaults() {
3106
3249
  },
3107
3250
  injection_detection: {
3108
3251
  category_enabled: true,
3109
- category_desc: "Prompt \u6CE8\u5165\u653B\u51FB\u68C0\u6D4B",
3252
+ tier_enabled: { strong: true, weak: true },
3253
+ category_desc: "\u53EF\u7591\u6CE8\u5165\u7279\u5F81\uFF08\u53EA\u4F5C\u4E3A L3 \u7EBF\u7D22\uFF0C\u4E0D\u76F4\u63A5\u62E6\u622A\uFF09",
3110
3254
  rules: _l1InjectionKeywordsToRules()
3111
3255
  },
3112
3256
  sensitive_path_access: {
@@ -3114,6 +3258,11 @@ function generateSourceDefaults() {
3114
3258
  category_desc: "\u654F\u611F\u8DEF\u5F84\u8BBF\u95EE\u68C0\u6D4B\uFF08deny_both/deny_read/deny_write\uFF09",
3115
3259
  rules: _l2SensitivePathsToRules()
3116
3260
  },
3261
+ builtin_detectors: {
3262
+ category_enabled: true,
3263
+ category_desc: "\u4EE3\u7801\u5185\u7F6E\u68C0\u6D4B\uFF08\u5371\u9669\u6A21\u5F0F / \u4E3B\u76EE\u5F55\u5220\u9664 / \u6A2A\u5411\u79FB\u52A8 / \u89E3\u7801\u5206\u6790\uFF09",
3264
+ rules: BUILTIN_DETECTOR_DEFAULTS.map((r) => ({ ...r }))
3265
+ },
3117
3266
  user_custom: { category_enabled: true, category_desc: "\u7528\u6237\u81EA\u5B9A\u4E49\u547D\u4EE4\u89C4\u5219", rules: [] }
3118
3267
  },
3119
3268
  L2_rules: {
@@ -3213,6 +3362,7 @@ function _mergeRuleCategories(userCfg, srcDefaults, layerKey) {
3213
3362
  const existing = userByFp.get(fp);
3214
3363
  const userDisabled = existing.user_disabled === true;
3215
3364
  const userSkipL3 = existing.skip_l3_on_disabled;
3365
+ const userAsk = existing.ask_on_match;
3216
3366
  const userDenyMode = existing.deny_mode;
3217
3367
  const userSourceDeny = existing.source_deny_mode;
3218
3368
  Object.keys(existing).forEach((k) => delete existing[k]);
@@ -3220,6 +3370,7 @@ function _mergeRuleCategories(userCfg, srcDefaults, layerKey) {
3220
3370
  existing.enabled = !userDisabled;
3221
3371
  if (userDisabled) existing.user_disabled = true;
3222
3372
  if (userSkipL3 !== void 0) existing.skip_l3_on_disabled = userSkipL3;
3373
+ if (userAsk !== void 0) existing.ask_on_match = userAsk === true;
3223
3374
  if (userDenyMode && userSourceDeny && userDenyMode !== userSourceDeny) {
3224
3375
  existing.deny_mode = userDenyMode;
3225
3376
  }
@@ -3359,6 +3510,7 @@ function _migrateCategoriesAcrossLayers(cfg, srcLayer, dstLayer, catNames) {
3359
3510
  const dstCat = dst[catName];
3360
3511
  if (!dstCat.category_desc && srcCat.category_desc) dstCat.category_desc = srcCat.category_desc;
3361
3512
  if (dstCat.category_enabled === void 0) dstCat.category_enabled = srcCat.category_enabled;
3513
+ if (dstCat.tier_enabled === void 0) dstCat.tier_enabled = { ...srcCat.tier_enabled || {} };
3362
3514
  if (srcCat.rules && srcCat.rules.length > 0) {
3363
3515
  const dstFps = new Set((dstCat.rules || []).map((r) => _ruleFingerprint(r)));
3364
3516
  for (const r of srcCat.rules) {
@@ -3375,13 +3527,16 @@ function _migrateCategoriesAcrossLayers(cfg, srcLayer, dstLayer, catNames) {
3375
3527
  function getEnabledL1InjectionKeywords(runtime, osType) {
3376
3528
  const cat = runtime.L1_rules?.injection_detection || { category_enabled: true, rules: [] };
3377
3529
  let rules = filterEnabledRules(cat.rules || [], cat.category_enabled);
3530
+ const tierEnabled = cat.tier_enabled || {};
3531
+ rules = rules.filter((r) => !r.tier || tierEnabled[r.tier] !== false);
3378
3532
  rules = _mergeRulesFromDirs(rules, "injection_detection");
3379
3533
  rules = _mergeUserCustom(rules, runtime, "L1_rules", "keyword");
3380
3534
  if (osType) rules = _filterRulesByOs(rules, osType);
3381
3535
  return rules.map((r) => ({
3382
3536
  keyword: r.keyword || "",
3383
3537
  risk_level: r.risk_level || "",
3384
- lang: r.lang || "en"
3538
+ lang: r.lang || "en",
3539
+ tier: String(r.tier || "")
3385
3540
  }));
3386
3541
  }
3387
3542
  function getEnabledL2IntentPatterns(runtime, osType) {
@@ -3395,9 +3550,40 @@ function getEnabledL2IntentPatterns(runtime, osType) {
3395
3550
  dangerous_actions: r.dangerous_actions || [],
3396
3551
  reason: r.reason || "",
3397
3552
  allow_if_write_intent: r.allow_if_write_intent === true,
3398
- os: r.os
3553
+ os: r.os,
3554
+ id: r.id || "",
3555
+ ask_on_match: r.ask_on_match === true
3399
3556
  }));
3400
3557
  }
3558
+ function getEnabledL2PasswordRules(runtime) {
3559
+ const cat = runtime.L2_rules?.password_modify_consent || { category_enabled: true, rules: [] };
3560
+ return _mergeUserCustom(
3561
+ _mergeRulesFromDirs(filterEnabledRules(cat.rules || [], cat.category_enabled), "password_modify_consent"),
3562
+ runtime,
3563
+ "L2_rules",
3564
+ "pattern"
3565
+ );
3566
+ }
3567
+ function getEnabledL2UserDeletionRules(runtime) {
3568
+ const cat = runtime.L2_rules?.user_deletion_consent || { category_enabled: true, rules: [] };
3569
+ return _mergeUserCustom(
3570
+ _mergeRulesFromDirs(filterEnabledRules(cat.rules || [], cat.category_enabled), "user_deletion_consent"),
3571
+ runtime,
3572
+ "L2_rules",
3573
+ "pattern"
3574
+ );
3575
+ }
3576
+ function getBuiltinAskMap(runtime) {
3577
+ const cat = runtime?.L1_rules?.builtin_detectors;
3578
+ const out = {};
3579
+ if (!cat || typeof cat !== "object") return out;
3580
+ for (const r of cat.rules || []) {
3581
+ const rid = String(r?.id || "");
3582
+ if (!rid) continue;
3583
+ out[rid] = r.ask_on_match && r.enabled !== false ? `\u89C4\u5219\u300C${r.reason || rid}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237` : "";
3584
+ }
3585
+ return out;
3586
+ }
3401
3587
  function getEnabledL2PasswordPatterns(runtime) {
3402
3588
  const cat = runtime.L2_rules?.password_modify_consent || { category_enabled: true, rules: [] };
3403
3589
  const rules = _mergeUserCustom(
@@ -3529,7 +3715,8 @@ function effectiveDangerousPatterns(osType) {
3529
3715
  severity: String(r.risk_level || "medium"),
3530
3716
  riskType: String(r.risk_type || ""),
3531
3717
  description: String(r.reason || ""),
3532
- os: String(r.os || "linux").toLowerCase()
3718
+ os: String(r.os || "linux").toLowerCase(),
3719
+ askOnMatch: r.ask_on_match === true
3533
3720
  }));
3534
3721
  });
3535
3722
  }
@@ -3539,7 +3726,8 @@ function effectiveInjectionKeywords(osType) {
3539
3726
  return rules.map((r) => ({
3540
3727
  keyword: String(r.keyword || ""),
3541
3728
  riskLevel: String(r.risk_level || ""),
3542
- lang: String(r.lang || "en")
3729
+ lang: String(r.lang || "en"),
3730
+ tier: String(r.tier || "")
3543
3731
  })).filter((r) => r.keyword);
3544
3732
  });
3545
3733
  }
@@ -3554,10 +3742,23 @@ function effectiveSensitivePaths(osType) {
3554
3742
  readOnly: r.read_only === true ? true : void 0,
3555
3743
  dirDelOnly: r.dir_del_only === true ? true : void 0,
3556
3744
  denyMode: String(r.deny_mode || ""),
3557
- os: String(r.os || "linux").toLowerCase()
3745
+ os: String(r.os || "linux").toLowerCase(),
3746
+ askOnMatch: r.ask_on_match === true
3558
3747
  }));
3559
3748
  });
3560
3749
  }
3750
+ function effectivePasswordRules(osType) {
3751
+ return _effective(osType, "password_rules", (rt) => getEnabledL2PasswordRules(rt).map((r) => ({
3752
+ pattern: new RegExp(String(r.pattern || ""), "i"),
3753
+ askOnMatch: r.ask_on_match === true
3754
+ })));
3755
+ }
3756
+ function effectiveUserDeletionRules(osType) {
3757
+ return _effective(osType, "user_deletion_rules", (rt) => getEnabledL2UserDeletionRules(rt).map((r) => ({
3758
+ pattern: new RegExp(String(r.pattern || ""), "i"),
3759
+ askOnMatch: r.ask_on_match === true
3760
+ })));
3761
+ }
3561
3762
  function effectiveIntentPatterns(osType) {
3562
3763
  return _effective(osType, "intent", (rt) => {
3563
3764
  const rules = getEnabledL2IntentPatternsOrDefault(rt, osType);
@@ -3566,7 +3767,8 @@ function effectiveIntentPatterns(osType) {
3566
3767
  dangerousActions: r.dangerous_actions || [],
3567
3768
  reason: String(r.reason || ""),
3568
3769
  os: String(r.os || "linux").toLowerCase(),
3569
- allowIfWriteIntent: r.allow_if_write_intent === true
3770
+ allowIfWriteIntent: r.allow_if_write_intent === true,
3771
+ askOnMatch: r.ask_on_match === true
3570
3772
  }));
3571
3773
  });
3572
3774
  }
@@ -3578,8 +3780,15 @@ function effectiveUserDeletionPatterns(osType) {
3578
3780
  }
3579
3781
  function _sensitivePathCategoryOf(runtime) {
3580
3782
  const l1 = runtime.L1_rules?.sensitive_path_access;
3581
- if (l1 && (l1.rules || []).length > 0) return l1;
3582
- return runtime.L2_rules?.sensitive_path_access;
3783
+ const l2 = runtime.L2_rules?.sensitive_path_access;
3784
+ const l1Rules = l1?.rules || [];
3785
+ const l2Rules = l2?.rules || [];
3786
+ if (l2Rules.length === 0) return l1;
3787
+ if (l1Rules.length === 0) return l2;
3788
+ const seen = new Set(l1Rules.map((r) => _ruleFingerprint(r)));
3789
+ const merged = { ...l1 };
3790
+ merged.rules = [...l1Rules, ...l2Rules.filter((r) => !seen.has(_ruleFingerprint(r)))];
3791
+ return merged;
3583
3792
  }
3584
3793
  function _validateSkillId(skillId) {
3585
3794
  if (!skillId || !SKILL_ID_RE.test(skillId)) {
@@ -3615,6 +3824,23 @@ function updateRuleDenyMode(layer, category, ruleId, denyMode) {
3615
3824
  saveRuntimeConfig(runtime);
3616
3825
  return runtime;
3617
3826
  }
3827
+ function updateRuleAsk(layer, category, ruleId, askOnMatch) {
3828
+ const runtime = loadRuntimeConfig();
3829
+ const rules = runtime[layer]?.[category]?.rules || [];
3830
+ const r = rules.find((x) => x.id === ruleId);
3831
+ if (r) r.ask_on_match = !!askOnMatch;
3832
+ saveRuntimeConfig(runtime);
3833
+ return runtime;
3834
+ }
3835
+ function updateCategoryAsk(layer, category, askOnMatch) {
3836
+ const runtime = loadRuntimeConfig();
3837
+ const cat = runtime[layer]?.[category];
3838
+ if (cat && typeof cat === "object") {
3839
+ for (const r of cat.rules || []) r.ask_on_match = !!askOnMatch;
3840
+ saveRuntimeConfig(runtime);
3841
+ }
3842
+ return runtime;
3843
+ }
3618
3844
  function updateRuleSkipL3(layer, category, ruleId, skipL3) {
3619
3845
  const runtime = loadRuntimeConfig();
3620
3846
  for (const r of runtime[layer]?.[category]?.rules || []) {
@@ -3626,6 +3852,13 @@ function updateRuleSkipL3(layer, category, ruleId, skipL3) {
3626
3852
  saveRuntimeConfig(runtime);
3627
3853
  return runtime;
3628
3854
  }
3855
+ function updateInjectionTierEnabled(tier, enabled) {
3856
+ const runtime = loadRuntimeConfig();
3857
+ const cat = (runtime.L1_rules ??= {}).injection_detection ??= { category_enabled: true, rules: [] };
3858
+ cat.tier_enabled = { ...cat.tier_enabled || {}, [tier]: enabled };
3859
+ saveRuntimeConfig(runtime);
3860
+ return runtime;
3861
+ }
3629
3862
  function updateCategoryEnabled(layer, category, enabled) {
3630
3863
  const runtime = loadRuntimeConfig();
3631
3864
  const cat = runtime[layer]?.[category];
@@ -3888,7 +4121,7 @@ function updateScenarioCategoryEnabled(scenarioId, category, enabled) {
3888
4121
  saveRuntimeConfig(runtime);
3889
4122
  return runtime;
3890
4123
  }
3891
- var __dirname4, ENV_RUNTIME_CONFIG_PATH, RUNTIME_CONFIG_DIR, RUNTIME_CONFIG_PATH, LAYER_DISABLE_ENV, DEFAULT_LAYERS, DENY_MODE_LABELS, runtimeConfigCache, _DEDUP_KEYS, hasRuntimeConfigCache, _AGENTS_DIR_PROD, _AGENTS_DIR_DEV, _SCENARIOS_DIR_PROD, _SCENARIOS_DIR_DEV, _effectiveCache, SKILL_ID_RE;
4124
+ var __dirname4, ENV_RUNTIME_CONFIG_PATH, RUNTIME_CONFIG_DIR, RUNTIME_CONFIG_PATH, LAYER_DISABLE_ENV, DEFAULT_LAYERS, DENY_MODE_LABELS, runtimeConfigCache, _DEDUP_KEYS, hasRuntimeConfigCache, _AGENTS_DIR_PROD, _AGENTS_DIR_DEV, _SCENARIOS_DIR_PROD, _SCENARIOS_DIR_DEV, BUILTIN_DETECTOR_DEFAULTS, _effectiveCache, SKILL_ID_RE;
3892
4125
  var init_runtime_config = __esm({
3893
4126
  "src/infra/runtime-config.ts"() {
3894
4127
  "use strict";
@@ -3939,6 +4172,17 @@ var init_runtime_config = __esm({
3939
4172
  _AGENTS_DIR_DEV = join5(__dirname4, "..", "..", "..", "agent_moss", "agents");
3940
4173
  _SCENARIOS_DIR_PROD = join5(__dirname4, "scenarios");
3941
4174
  _SCENARIOS_DIR_DEV = join5(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
4175
+ BUILTIN_DETECTOR_DEFAULTS = [
4176
+ { id: "builtin_wildcard_delete", reason: "\u901A\u914D\u7B26 + \u6279\u91CF\u5220\u9664\uFF08rm \u914D\u901A\u914D\u7B26\uFF0C\u6392\u9664 /tmp \u7B49\u4E34\u65F6\u76EE\u5F55\u6E05\u7406\uFF09", risk_level: "high", risk_type: "script_execution", enabled: true, builtin: true, os: "all", ask_on_match: false },
4177
+ { id: "builtin_find_exec_write", reason: "find \u6279\u91CF\u6267\u884C\u5199\u64CD\u4F5C\uFF08find -exec / | xargs \u540E\u63A5 chmod/cp/mv/rm \u7B49\uFF09", risk_level: "high", risk_type: "script_execution", enabled: true, builtin: true, os: "all", ask_on_match: false },
4178
+ { id: "builtin_redirect_system", reason: "\u91CD\u5B9A\u5411\u8986\u76D6\u5199\u5165\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55\uFF08/etc\u3001/boot\u3001/proc\uFF09", risk_level: "critical", risk_type: "file_access", enabled: true, builtin: true, os: "all", ask_on_match: false },
4179
+ { id: "builtin_home_deletion", reason: "\u4E3B\u76EE\u5F55\u9012\u5F52\u5220\u9664\uFF08rm -rf ~ / $HOME \u53CA\u53D8\u91CF\u95F4\u63A5\u5F15\u7528\uFF09", risk_level: "high", risk_type: "home_deletion", enabled: true, builtin: true, os: "all", ask_on_match: false },
4180
+ { id: "structural_hidden_payload", reason: "\u89E3\u7801\u5206\u6790\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u53EF\u89E3\u7801\u7684\u9690\u85CF\u8F7D\u8377\uFF08Tag/base64/hex/URL\uFF09", risk_level: "high", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
4181
+ { id: "structural_bidi_override", reason: "\u89E3\u7801\u5206\u6790\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u53CC\u5411\u63A7\u5236\u7B26\uFF08\u53EF\u80FD\u906E\u6321\u6587\u672C\uFF09", risk_level: "medium", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
4182
+ { id: "structural_external_media", reason: "\u7ED3\u6784\u7279\u5F81\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u5916\u90E8\u56FE\u7247\u94FE\u63A5", risk_level: "medium", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
4183
+ { id: "structural_persistence", reason: "\u7ED3\u6784\u7279\u5F81\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u6301\u4E45\u5316\u6307\u4EE4\u53E5\u5F0F\uFF08\u6BCF\u5F53\u7528\u6237\u2026\uFF09", risk_level: "medium", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
4184
+ { id: "builtin_lateral_movement", reason: "\u6A2A\u5411\u79FB\u52A8\uFF08ssh/scp/rsync \u5230\u975E\u672C\u673A\u4E3B\u673A\uFF09", risk_level: "high", risk_type: "lateral_movement", enabled: true, builtin: true, os: "all", ask_on_match: false }
4185
+ ];
3942
4186
  _effectiveCache = /* @__PURE__ */ new WeakMap();
3943
4187
  SKILL_ID_RE = /^[A-Za-z0-9_-]+$/;
3944
4188
  registerRuntimeConfigBridge({
@@ -3950,6 +4194,9 @@ var init_runtime_config = __esm({
3950
4194
  effectiveIntentPatterns,
3951
4195
  effectivePasswordPatterns,
3952
4196
  effectiveUserDeletionPatterns,
4197
+ effectivePasswordRules,
4198
+ effectiveUserDeletionRules,
4199
+ builtinAskMap: () => getBuiltinAskMap(loadRuntimeConfig()),
3953
4200
  disabledSkillIds: () => getDisabledSkillIds(loadRuntimeConfig())
3954
4201
  });
3955
4202
  }
@@ -4211,10 +4458,10 @@ function getCacheOptions() {
4211
4458
  let enabled = true;
4212
4459
  let maxSize = 1e3;
4213
4460
  const cfg = loadConfigFile(resolveConfigPath());
4214
- const cache3 = cfg?.cache;
4215
- if (cache3 && typeof cache3 === "object") {
4216
- if (typeof cache3.enabled === "boolean") enabled = cache3.enabled;
4217
- if (typeof cache3.max_size === "number" && cache3.max_size > 0) maxSize = cache3.max_size;
4461
+ const cache4 = cfg?.cache;
4462
+ if (cache4 && typeof cache4 === "object") {
4463
+ if (typeof cache4.enabled === "boolean") enabled = cache4.enabled;
4464
+ if (typeof cache4.max_size === "number" && cache4.max_size > 0) maxSize = cache4.max_size;
4218
4465
  }
4219
4466
  if (process.env.AGENT_MOSS_DISABLE_CACHE === "1") enabled = false;
4220
4467
  return { enabled, maxSize };
@@ -4810,6 +5057,194 @@ var init_written_content_analyzer = __esm({
4810
5057
  }
4811
5058
  });
4812
5059
 
5060
+ // src/engine/structural-analyzer.ts
5061
+ function decodeTagPayload(text) {
5062
+ const payloads = [];
5063
+ let current = [];
5064
+ let afterFlag = false;
5065
+ let prevCp = 0;
5066
+ const flush = () => {
5067
+ if (current.length && !afterFlag) payloads.push(current.join(""));
5068
+ current = [];
5069
+ afterFlag = false;
5070
+ };
5071
+ for (const ch of text || "") {
5072
+ const cp = ch.codePointAt(0);
5073
+ if (cp >= TAG_MIN && cp <= TAG_MAX) {
5074
+ if (!current.length) afterFlag = prevCp === 127988;
5075
+ current.push(String.fromCharCode(cp - 917504));
5076
+ } else if (cp === TAG_CANCEL) {
5077
+ flush();
5078
+ } else {
5079
+ flush();
5080
+ }
5081
+ prevCp = cp;
5082
+ }
5083
+ flush();
5084
+ return payloads;
5085
+ }
5086
+ function decodeBase32(value) {
5087
+ const clean = value.replace(/=+$/, "").toUpperCase();
5088
+ let bits = 0;
5089
+ let acc = 0;
5090
+ const out = [];
5091
+ for (const ch of clean) {
5092
+ const idx = B32_ALPHABET.indexOf(ch);
5093
+ if (idx < 0) return "";
5094
+ acc = acc << 5 | idx;
5095
+ bits += 5;
5096
+ if (bits >= 8) {
5097
+ bits -= 8;
5098
+ out.push(acc >> bits & 255);
5099
+ }
5100
+ }
5101
+ return Buffer.from(out).toString("utf8");
5102
+ }
5103
+ function decodeHexDump(text) {
5104
+ const out = [];
5105
+ for (const m of text.matchAll(XXD_LINE_RE)) {
5106
+ const hex = m[1].replace(/\s+/g, "");
5107
+ try {
5108
+ out.push(Buffer.from(hex, "hex").toString("utf8"));
5109
+ } catch {
5110
+ }
5111
+ }
5112
+ for (const m of text.match(OD_HEX_RE) || []) {
5113
+ const hex = m.replace(/\s+/g, "");
5114
+ if (hex.length % 2) continue;
5115
+ try {
5116
+ out.push(Buffer.from(hex, "hex").toString("utf8"));
5117
+ } catch {
5118
+ }
5119
+ }
5120
+ return out;
5121
+ }
5122
+ function decodeUnicodeEscapes(value) {
5123
+ return value.replace(
5124
+ /\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{8})/g,
5125
+ (_all, a, b) => String.fromCodePoint(parseInt(a || b, 16))
5126
+ );
5127
+ }
5128
+ function decodeHtmlEntities(value) {
5129
+ return value.replace(
5130
+ /&#(x?)([0-9a-fA-F]+);/g,
5131
+ (_all, x, n) => String.fromCodePoint(parseInt(n, x ? 16 : 10))
5132
+ );
5133
+ }
5134
+ function looksText(value) {
5135
+ if (value.trim().length < 4) return false;
5136
+ let printable = 0;
5137
+ for (const c of value) {
5138
+ if (c >= " " && c !== "\x7F") printable++;
5139
+ else if (c === "\r" || c === "\n" || c === " ") printable++;
5140
+ }
5141
+ return printable / Math.max(value.length, 1) >= 0.9;
5142
+ }
5143
+ function decodePayloads(text, opts = {}) {
5144
+ const out = [];
5145
+ const seen = /* @__PURE__ */ new Set();
5146
+ const add = (encoding, value) => {
5147
+ if (looksText(value) && !seen.has(value)) {
5148
+ seen.add(value);
5149
+ out.push({ encoding, decoded: value });
5150
+ }
5151
+ };
5152
+ for (const p of decodeTagPayload(text)) add("tag", p);
5153
+ for (const m of text.match(HEX_ESC_RE) || []) {
5154
+ try {
5155
+ const bytes = m.replace(/\\x/g, "").match(/../g).map((h) => parseInt(h, 16));
5156
+ add("hex", Buffer.from(bytes).toString("utf8"));
5157
+ } catch {
5158
+ }
5159
+ }
5160
+ for (const m of text.match(UNICODE_ESC_RE) || []) {
5161
+ try {
5162
+ add("unicode_escape", decodeUnicodeEscapes(m));
5163
+ } catch {
5164
+ }
5165
+ }
5166
+ for (const m of text.match(PCT_RE) || []) {
5167
+ try {
5168
+ add("url", decodeURIComponent(m));
5169
+ } catch {
5170
+ }
5171
+ }
5172
+ for (const m of text.match(B64_RE) || []) {
5173
+ try {
5174
+ const raw = Buffer.from(m + "=".repeat((4 - m.length % 4) % 4), "base64");
5175
+ add("base64", raw.toString("utf8"));
5176
+ } catch {
5177
+ }
5178
+ }
5179
+ for (const m of text.match(B64URL_RE) || []) {
5180
+ try {
5181
+ const norm = m.replace(/-/g, "+").replace(/_/g, "/");
5182
+ const raw = Buffer.from(norm + "=".repeat((4 - norm.length % 4) % 4), "base64");
5183
+ add("base64url", raw.toString("utf8"));
5184
+ } catch {
5185
+ }
5186
+ }
5187
+ for (const m of text.match(B32_RE) || []) add("base32", decodeBase32(m));
5188
+ for (const v of decodeHexDump(text)) add("hex_dump", v);
5189
+ if (opts.includeHtml) {
5190
+ for (const m of text.match(HTML_ENTITY_RE) || []) {
5191
+ try {
5192
+ add("html_entity", decodeHtmlEntities(m));
5193
+ } catch {
5194
+ }
5195
+ }
5196
+ }
5197
+ return out;
5198
+ }
5199
+ function findStructuralSignals(content) {
5200
+ const text = content || "";
5201
+ const findings = [];
5202
+ for (const p of decodePayloads(text)) {
5203
+ findings.push({
5204
+ kind: "hidden_payload",
5205
+ sample: `[${p.encoding}] ${p.decoded.slice(0, 120)}`,
5206
+ riskLevel: "medium",
5207
+ decoded: p.decoded
5208
+ });
5209
+ }
5210
+ const bidi = text.match(BIDI_RE);
5211
+ if (bidi) findings.push({ kind: "bidi_override", sample: JSON.stringify(bidi[0]), riskLevel: "medium" });
5212
+ const media = text.match(EXTERNAL_MEDIA_RE);
5213
+ if (media) findings.push({ kind: "external_media", sample: media[0].slice(0, 120), riskLevel: "medium" });
5214
+ const persist = text.match(PERSISTENCE_RE);
5215
+ if (persist) findings.push({ kind: "persistence_phrase", sample: persist[0].slice(0, 120), riskLevel: "medium" });
5216
+ return findings;
5217
+ }
5218
+ var TAG_MIN, TAG_MAX, TAG_CANCEL, BIDI_RE, EXTERNAL_MEDIA_RE, PERSISTENCE_RE, B64_RE, B64URL_RE, B32_RE, HEX_ESC_RE, UNICODE_ESC_RE, PCT_RE, XXD_LINE_RE, OD_HEX_RE, HTML_ENTITY_RE, B32_ALPHABET, SIGNAL_TO_DETECTOR;
5219
+ var init_structural_analyzer = __esm({
5220
+ "src/engine/structural-analyzer.ts"() {
5221
+ "use strict";
5222
+ init_esm_shims();
5223
+ TAG_MIN = 917536;
5224
+ TAG_MAX = 917630;
5225
+ TAG_CANCEL = 917631;
5226
+ BIDI_RE = /[\u202a-\u202e]/;
5227
+ EXTERNAL_MEDIA_RE = /!\[[^\]]*\]\(\s*(?:https?:)?\/\/[^)\s]+|<img\b[^>]*\bsrc\s*=\s*["']?(?:https?:)?\/\//i;
5228
+ PERSISTENCE_RE = /(?:每当|每次|以后每次|今后每次|从现在起每次)[^。\n]{0,20}(?:用户|你)|from now on,?\s*(?:whenever|each time|every time)|whenever the user|each time the user/i;
5229
+ B64_RE = /[A-Za-z0-9+/]{8,}={0,2}/g;
5230
+ B64URL_RE = /[A-Za-z0-9_-]{16,}={0,2}/g;
5231
+ B32_RE = /[A-Z2-7]{12,}={0,6}/g;
5232
+ HEX_ESC_RE = /(?:\\x[0-9a-fA-F]{2}){4,}/g;
5233
+ UNICODE_ESC_RE = /(?:\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}){4,}/g;
5234
+ PCT_RE = /(?:%[0-9A-Fa-f]{2}){4,}/g;
5235
+ XXD_LINE_RE = /^\s*[0-9a-fA-F]{4,8}:\s+([0-9a-fA-F]{2,4}(?:[ ]+[0-9a-fA-F]{2,4})*)/gm;
5236
+ OD_HEX_RE = /(?:(?<![0-9a-fA-F])[0-9a-fA-F]{2}[ \t]+){15,}[0-9a-fA-F]{2}/g;
5237
+ HTML_ENTITY_RE = /(?:&#x?[0-9a-fA-F]+;){4,}/g;
5238
+ B32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
5239
+ SIGNAL_TO_DETECTOR = {
5240
+ hidden_payload: "structural_hidden_payload",
5241
+ bidi_override: "structural_bidi_override",
5242
+ external_media: "structural_external_media",
5243
+ persistence_phrase: "structural_persistence"
5244
+ };
5245
+ }
5246
+ });
5247
+
4813
5248
  // src/engine/heuristic.ts
4814
5249
  import { posix } from "path";
4815
5250
  function _effectiveDangerousPatterns(osType) {
@@ -4956,11 +5391,18 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
4956
5391
  const deob = normalizeShellObfuscation(scanDetail);
4957
5392
  if (deob !== scanDetail) scanCommands.push(`${actionType}: ${deob}`, deob);
4958
5393
  let top = null;
5394
+ const loopbackOnly = allUrlsLoopback(actionDetail) && !LOOPBACK_DATA_GUARD_RE.test(actionDetail);
5395
+ const boundedLoop = isBoundedLoop(scanDetail);
4959
5396
  for (const rule of _effectiveDangerousPatterns(osType)) {
4960
5397
  if (scanCommands.some((c) => rule.pattern.test(c))) {
5398
+ if (loopbackOnly && rule.riskType === "data_exfiltration") continue;
5399
+ if (boundedLoop && rule.riskType === "resource_exhaustion" && (rule.description || "").includes("\u65E0\u9650\u5FAA\u73AF")) continue;
4961
5400
  if (!top || severityRank(rule.severity) > severityRank(top.sev)) {
4962
5401
  top = { sev: rule.severity, type: rule.riskType, desc: rule.description };
4963
5402
  }
5403
+ if (rule.askOnMatch && !top.ask) {
5404
+ top.ask = `\u89C4\u5219\u300C${rule.description}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237`;
5405
+ }
4964
5406
  }
4965
5407
  }
4966
5408
  const toJudgment = (hit) => ({
@@ -4970,13 +5412,22 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
4970
5412
  riskType: hit.type,
4971
5413
  confidence: 95,
4972
5414
  source: "heuristic",
4973
- violatedLayers: ["L1.1"]
5415
+ violatedLayers: ["L1.1"],
5416
+ ...hit.ask ? { ask_recommended: true, ask_reason: hit.ask } : {}
4974
5417
  });
4975
5418
  if (top && severityRank(top.sev) >= severityRank("high")) return toJudgment(top);
4976
5419
  const rmResolved = checkRmResolvedTargets(scanDetail);
4977
5420
  if (rmResolved) return rmResolved;
4978
5421
  return top ? toJudgment(top) : null;
4979
5422
  }
5423
+ function isBoundedLoop(text) {
5424
+ const loops = (text.match(LOOP_START_RE) || []).length;
5425
+ const breaks = (text.match(LOOP_EXIT_RE) || []).length;
5426
+ return loops > 0 && breaks >= loops && !LOOP_SIDE_EFFECT_RE.test(text);
5427
+ }
5428
+ function isDbQueryCommand(text) {
5429
+ return DB_QUERY_CMD_RE.test(text || "");
5430
+ }
4980
5431
  function allUrlsLoopback(actionDetail) {
4981
5432
  const hosts = actionDetail.match(new RegExp(LOOPBACK_URL_RE.source, "gi"));
4982
5433
  if (!hosts || hosts.length === 0) return false;
@@ -4996,6 +5447,49 @@ function stripEchoParamsForUserRules(actionDetail) {
4996
5447
  return `${head} ` + (cut >= 0 ? rest.slice(cut) : "");
4997
5448
  }).join(" ");
4998
5449
  }
5450
+ function extractDecodedPayloads(actionType, detail, handledWrite) {
5451
+ if (!getEnabledBuiltinDetectorsOrCurrent().has("structural_hidden_payload")) return [];
5452
+ const source = injectionScanSource(actionType, detail, handledWrite);
5453
+ if (!source) return [];
5454
+ let content = detail || "";
5455
+ if (handledWrite) {
5456
+ const payload = extractWritePayload(actionType, content);
5457
+ if (payload) content = payload.content;
5458
+ }
5459
+ return decodePayloads(content, { includeHtml: source === "instruction" }).map((p) => ({ source, encoding: p.encoding, decoded: p.decoded }));
5460
+ }
5461
+ function detectDecoded(payload) {
5462
+ const enabled = getEnabledBuiltinDetectorsOrCurrent();
5463
+ const hits = [];
5464
+ const cmd = scanDangerousCommandPatterns("bash", payload);
5465
+ if (cmd) hits.push(cmd);
5466
+ const pat = checkDangerousPatterns("bash", payload, enabled);
5467
+ if (pat) hits.push(pat);
5468
+ if (enabled.has("builtin_home_deletion")) {
5469
+ const home = checkHomeDeletion("bash", payload);
5470
+ if (home) hits.push(home);
5471
+ }
5472
+ if (enabled.has("builtin_lateral_movement")) {
5473
+ const lateral = checkLateralMovement(payload);
5474
+ if (lateral) hits.push(lateral);
5475
+ }
5476
+ const path9 = checkSensitivePath(payload, "/", null, void 0);
5477
+ if (path9) hits.push(path9);
5478
+ const inj = checkInjectionKeywords(payload.toLowerCase());
5479
+ if (inj.length) {
5480
+ hits.push({
5481
+ allowed: false,
5482
+ reason: `\u89E3\u7801\u5185\u5BB9\u542B\u6CE8\u5165\u5173\u952E\u8BCD: ${inj.map((h) => h.keyword).join(", ")}`,
5483
+ riskLevel: "medium",
5484
+ riskType: "prompt_injection",
5485
+ confidence: 90,
5486
+ source: "heuristic",
5487
+ violatedLayers: ["L1.1"]
5488
+ });
5489
+ }
5490
+ if (!hits.length) return null;
5491
+ return hits.reduce((a, b) => severityRank(b.riskLevel) > severityRank(a.riskLevel) ? b : a);
5492
+ }
4999
5493
  function runHeuristicCheck(input) {
5000
5494
  const command = `${input.aNext.actionType}: ${input.aNext.actionDetail}`;
5001
5495
  const matched = [];
@@ -5070,11 +5564,22 @@ function runHeuristicCheck(input) {
5070
5564
  const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
5071
5565
  const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
5072
5566
  const noQuotes = pwGuardOff ? null : input.aNext.actionDetail.replace(ALL_QUOTES_RE, " ");
5567
+ const boundedLoop = isBoundedLoop(scanDetail);
5568
+ const loopbackExfilSkip = urlsAllLoopback && !LOOPBACK_DATA_GUARD_RE.test(input.aNext.actionDetail);
5569
+ let askReason = "";
5073
5570
  for (const rule of _effectiveDangerousPatterns(input.osType)) {
5074
5571
  if (scanCommands.some((c) => rule.pattern.test(c))) {
5572
+ if (loopbackExfilSkip && rule.riskType === "data_exfiltration") continue;
5075
5573
  if (exemptKeygen && rule.riskType === "file_access") continue;
5574
+ if (boundedLoop && rule.riskType === "resource_exhaustion" && (rule.description || "").includes("\u65E0\u9650\u5FAA\u73AF")) {
5575
+ matched.push("\u68C0\u6D4B\u5230\u5FAA\u73AF\u4F46\u5B58\u5728\u7EC8\u6B62\u6761\u4EF6\uFF08break/return\uFF09\uFF0C\u964D\u7EA7\u4EA4 L2/L3");
5576
+ continue;
5577
+ }
5076
5578
  if (noQuotes !== null && QUOTED_SAFE_PASSWORD_PATTERN_SOURCES.has(rule.pattern.source) && !rule.pattern.test(noQuotes)) continue;
5077
5579
  matched.push(rule.description);
5580
+ if (rule.askOnMatch && !askReason) {
5581
+ askReason = `\u89C4\u5219\u300C${rule.description}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237`;
5582
+ }
5078
5583
  if (severityRank(rule.severity) > severityRank(highestSeverity)) {
5079
5584
  highestSeverity = rule.severity;
5080
5585
  topRiskType = rule.riskType;
@@ -5101,9 +5606,15 @@ function runHeuristicCheck(input) {
5101
5606
  }
5102
5607
  }
5103
5608
  }
5104
- const injectionText = isSearchActionType(input.aNext.actionType) || handledWrite && isDataDocument(input.aNext.actionType, input.aNext.actionDetail) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
5609
+ const enabledBuiltin = getEnabledBuiltinDetectorsOrCurrent();
5610
+ const injectionSource = injectionScanSource(
5611
+ input.aNext.actionType,
5612
+ input.aNext.actionDetail,
5613
+ handledWrite
5614
+ );
5615
+ const injectionText = injectionSource ? input.aNext.actionDetail.toLowerCase() : "";
5105
5616
  let pythonWalkOnerrorOnly = false;
5106
- if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
5617
+ if (injectionSource === "output" && isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=")) {
5107
5618
  pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
5108
5619
  }
5109
5620
  const injectionHits = checkInjectionKeywords(
@@ -5112,6 +5623,9 @@ function runHeuristicCheck(input) {
5112
5623
  input.osType,
5113
5624
  pythonWalkOnerrorOnly
5114
5625
  );
5626
+ for (const h of injectionHits) {
5627
+ if (h.riskLevel === "high" || h.riskLevel === "critical") h.riskLevel = "medium";
5628
+ }
5115
5629
  if (injectionHits.length > 0) {
5116
5630
  const topHit = injectionHits.reduce((a, b) => severityRank(a.riskLevel) >= severityRank(b.riskLevel) ? a : b);
5117
5631
  matched.push(...injectionHits.map((h) => `\u6CE8\u5165\u5173\u952E\u8BCD [${h.lang}]: ${h.keyword}`));
@@ -5120,12 +5634,28 @@ function runHeuristicCheck(input) {
5120
5634
  highestRiskType = "prompt_injection";
5121
5635
  }
5122
5636
  }
5637
+ if (injectionSource) {
5638
+ const payload = handledWrite ? extractWritePayload(input.aNext.actionType, input.aNext.actionDetail) : null;
5639
+ const content = payload ? payload.content : input.aNext.actionDetail;
5640
+ for (const finding of findStructuralSignals(content)) {
5641
+ const det = SIGNAL_TO_DETECTOR[finding.kind];
5642
+ if (!det || !enabledBuiltin.has(det)) continue;
5643
+ if (finding.kind === "hidden_payload") continue;
5644
+ if (injectionSource !== "instruction") continue;
5645
+ const level = finding.riskLevel;
5646
+ matched.push(`\u7ED3\u6784\u7279\u5F81: ${finding.kind}`);
5647
+ if (severityRank(level) > severityRank(highestSeverity)) {
5648
+ highestSeverity = level;
5649
+ highestRiskType = "prompt_injection";
5650
+ }
5651
+ }
5652
+ }
5123
5653
  const actionTypeL = input.aNext.actionType.toLowerCase();
5124
5654
  const detailL = input.aNext.actionDetail.toLowerCase();
5125
5655
  const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
5126
- const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
5656
+ const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL, enabledBuiltin);
5127
5657
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
5128
- const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
5658
+ const homeResult = handledWrite || !enabledBuiltin.has("builtin_home_deletion") ? null : checkHomeDeletion(actionTypeL, detailL);
5129
5659
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
5130
5660
  if (isBashLike && !handledWrite && severityRank(highestSeverity) < severityRank("high") && !mergeResults.some((r) => severityRank(r.riskLevel) >= severityRank("high"))) {
5131
5661
  const rmResolved = checkRmResolvedTargets(scanDetail);
@@ -5136,16 +5666,22 @@ function runHeuristicCheck(input) {
5136
5666
  for (const r of mergeResults) {
5137
5667
  if (severityRank(r.riskLevel) > severityRank(best.riskLevel)) best = r;
5138
5668
  }
5139
- if (severityRank(highestSeverity) > severityRank(best.riskLevel)) {
5140
- return {
5669
+ if (highestRiskType && severityRank(highestSeverity) >= severityRank(best.riskLevel)) {
5670
+ const out = {
5141
5671
  allowed: false,
5142
5672
  reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${matched.join(", ")}`,
5143
5673
  riskLevel: highestSeverity,
5144
5674
  riskType: highestRiskType,
5145
5675
  confidence: 95,
5146
5676
  source: "heuristic",
5147
- violatedLayers: ["L1.1"]
5677
+ violatedLayers: ["L1.1"],
5678
+ ...askReason ? { ask_recommended: true, ask_reason: askReason } : {}
5148
5679
  };
5680
+ if (best === pathResult && pathResult?.deniedReadPath) {
5681
+ out.deniedReadPath = pathResult.deniedReadPath;
5682
+ if (pathResult.isCredential) out.isCredential = true;
5683
+ }
5684
+ return out;
5149
5685
  }
5150
5686
  if (best !== pathResult && pathResult?.deniedReadPath && best.riskType === "file_access" && best.riskLevel === pathResult.riskLevel) {
5151
5687
  best = { ...best, deniedReadPath: pathResult.deniedReadPath };
@@ -5160,11 +5696,14 @@ function runHeuristicCheck(input) {
5160
5696
  riskType: highestRiskType,
5161
5697
  confidence: 95,
5162
5698
  source: "heuristic",
5163
- violatedLayers: ["L1.1"]
5699
+ violatedLayers: ["L1.1"],
5700
+ ...askReason ? { ask_recommended: true, ask_reason: askReason } : {}
5164
5701
  };
5165
5702
  }
5166
- const lateralResult = checkLateralMovement(detailL);
5167
- if (lateralResult) return lateralResult;
5703
+ if (enabledBuiltin.has("builtin_lateral_movement")) {
5704
+ const lateralResult = checkLateralMovement(detailL);
5705
+ if (lateralResult) return lateralResult;
5706
+ }
5168
5707
  return null;
5169
5708
  }
5170
5709
  function onlyPythonWalkOnerrorKeywords(command) {
@@ -5183,6 +5722,52 @@ function onlyPythonWalkOnerrorKeywords(command) {
5183
5722
  const walkKws = noStr.match(/os\.walk\s*\([^)]*\bonerror\s*=/g) || [];
5184
5723
  return walkKws.length > 0;
5185
5724
  }
5725
+ function shellWriteTargets(command) {
5726
+ const out = [];
5727
+ INSTRUCTION_WRITE_RE.lastIndex = 0;
5728
+ let m;
5729
+ while ((m = INSTRUCTION_WRITE_RE.exec(command || "")) !== null) out.push(m[2]);
5730
+ return out;
5731
+ }
5732
+ function isDataDocPath(path9) {
5733
+ const i = String(path9 || "").lastIndexOf(".");
5734
+ return i >= 0 && DATA_DOC_EXTS.has(String(path9).slice(i).toLowerCase());
5735
+ }
5736
+ function isTextOutputCommand(command) {
5737
+ const text = command || "";
5738
+ if (isLiteralTextCommand(text)) return true;
5739
+ if (/\b(?:python3?|perl|ruby|node|php|lua)\b[^;|&\n]*\s-(?:c|e)\b/i.test(text)) return true;
5740
+ for (const seg of splitCommandSegments2(text)) {
5741
+ const parts = seg.trim().split(/\s+/);
5742
+ if (!parts.length) continue;
5743
+ const head = parts[0].toLowerCase();
5744
+ if (head === "echo" || head === "printf") return true;
5745
+ if (head === "cat" && seg.includes("<<")) return true;
5746
+ if (head === "tee" && shellWriteTargets(seg).length === 0) return true;
5747
+ }
5748
+ return false;
5749
+ }
5750
+ function injectionScanSource(actionType, raw, handledWrite) {
5751
+ const at = (actionType || "").toLowerCase();
5752
+ const text = raw || "";
5753
+ if (isSearchActionType(at)) return "";
5754
+ if (isDbQueryCommand(text)) return "";
5755
+ if (handledWrite) {
5756
+ const payload = extractWritePayload(at, text);
5757
+ const path9 = payload ? payload.path : "";
5758
+ if (path9 && isInstructionTarget(path9)) return "instruction";
5759
+ if (isDataDocument(at, text)) return "";
5760
+ return "output";
5761
+ }
5762
+ if (["bash", "executebash", "terminal-executebash"].includes(at)) {
5763
+ const targets = shellWriteTargets(text);
5764
+ if (targets.some((t) => isInstructionTarget(t))) return "instruction";
5765
+ if (targets.length > 0 && targets.every(isDataDocPath)) return "";
5766
+ if (isTextOutputCommand(text)) return "output";
5767
+ return "";
5768
+ }
5769
+ return "";
5770
+ }
5186
5771
  function checkInjectionKeywords(text, extraKeywords, osType, pythonWalkOnerrorOnly = false) {
5187
5772
  const hits = [];
5188
5773
  const baseKeywords = runtimeConfigBridge.current?.effectiveInjectionKeywords(osType) ?? INJECTION_KEYWORDS;
@@ -5443,6 +6028,9 @@ function isSearchActionType(actionType) {
5443
6028
  const at = actionType.toLowerCase();
5444
6029
  return SEARCH_ACTION_PREFIXES.some((p) => at.startsWith(p)) || SEARCH_ACTION_EXACT.includes(at);
5445
6030
  }
6031
+ function askMeta(on, desc) {
6032
+ return on ? { ask_recommended: true, ask_reason: `\u89C4\u5219\u300C${desc || ""}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237` } : {};
6033
+ }
5446
6034
  function checkSensitivePath(command, cwd, agentExt, osType) {
5447
6035
  const expandedCwd = cwd.replace(/^~/, process.env.HOME || "/home/user");
5448
6036
  const { root: rootPaths, home: homePaths, credential: credentialPaths } = getSensitivePathsForOs(osType);
@@ -5458,7 +6046,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5458
6046
  if (part.startsWith("(?!")) return part;
5459
6047
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5460
6048
  }).join("");
5461
- const re = path9.startsWith(".") || path9.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
6049
+ const re = path9.startsWith(".") || path9.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}${TEMPLATE_SUFFIX_LA}\\b`, "i") : new RegExp(`\\b${escaped}${TEMPLATE_SUFFIX_LA}\\b`, "i");
5462
6050
  return re.test(text);
5463
6051
  };
5464
6052
  const pathMatchesAny = (path9) => pathScanTexts.some((t) => pathMatches(t, path9));
@@ -5477,6 +6065,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5477
6065
  confidence: 90,
5478
6066
  source: "heuristic",
5479
6067
  violatedLayers: ["L1.1"],
6068
+ ...askMeta(sp.askOnMatch === true, sp.desc),
5480
6069
  deniedReadPath: sp.path
5481
6070
  };
5482
6071
  }
@@ -5491,6 +6080,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5491
6080
  confidence: 90,
5492
6081
  source: "heuristic",
5493
6082
  violatedLayers: ["L1.1"],
6083
+ ...askMeta(sp.askOnMatch === true, sp.desc),
5494
6084
  isCredential: !!sp.credential,
5495
6085
  deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5496
6086
  };
@@ -5521,6 +6111,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5521
6111
  confidence: 90,
5522
6112
  source: "heuristic",
5523
6113
  violatedLayers: ["L1.1"],
6114
+ ...askMeta(sp.askOnMatch === true, sp.desc),
5524
6115
  isCredential: !!sp.credential
5525
6116
  };
5526
6117
  }
@@ -5533,6 +6124,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5533
6124
  confidence: 90,
5534
6125
  source: "heuristic",
5535
6126
  violatedLayers: ["L1.1"],
6127
+ ...askMeta(sp.askOnMatch === true, sp.desc),
5536
6128
  isCredential: !!sp.credential
5537
6129
  };
5538
6130
  }
@@ -5549,6 +6141,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5549
6141
  confidence: 90,
5550
6142
  source: "heuristic",
5551
6143
  violatedLayers: ["L1.1"],
6144
+ ...askMeta(sp.askOnMatch === true, sp.desc),
5552
6145
  isCredential: !!sp.credential,
5553
6146
  deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5554
6147
  };
@@ -5579,9 +6172,10 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5579
6172
  }
5580
6173
  }
5581
6174
  }
6175
+ const templateSuffix = TEMPLATE_SUFFIX_LA;
5582
6176
  for (const cp of credentialPaths) {
5583
6177
  const escaped = cp.path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5584
- const re = cp.path.startsWith(".") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`) : new RegExp(`\\b${escaped}\\b`);
6178
+ const re = cp.path.startsWith(".") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}${templateSuffix}\\b`) : new RegExp(`\\b${escaped}${templateSuffix}\\b`);
5585
6179
  if (re.test(command)) {
5586
6180
  return {
5587
6181
  allowed: false,
@@ -5591,6 +6185,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5591
6185
  confidence: 90,
5592
6186
  source: "heuristic",
5593
6187
  violatedLayers: ["L1.1"],
6188
+ ...askMeta(cp.askOnMatch === true, cp.desc),
5594
6189
  isCredential: true,
5595
6190
  deniedReadPath: cp.path
5596
6191
  };
@@ -5647,6 +6242,14 @@ function homeEscapeTarget(seg) {
5647
6242
  }
5648
6243
  return false;
5649
6244
  }
6245
+ function builtinAsk(ruleId) {
6246
+ try {
6247
+ const reason = runtimeConfigBridge.current?.builtinAskMap()?.[ruleId];
6248
+ return reason ? { ask_recommended: true, ask_reason: reason } : {};
6249
+ } catch {
6250
+ return {};
6251
+ }
6252
+ }
5650
6253
  function checkHomeDeletion(actionType, actionDetail) {
5651
6254
  if (actionType !== "bash" && actionType !== "executebash" && actionType !== "terminal-executebash") return null;
5652
6255
  const segs = actionDetail.split(/&&|\|\||;|\n/).map((s) => s.trim()).filter(Boolean);
@@ -5660,7 +6263,8 @@ function checkHomeDeletion(actionType, actionDetail) {
5660
6263
  riskType: "script_execution",
5661
6264
  confidence: 90,
5662
6265
  source: "heuristic",
5663
- violatedLayers: ["L1.1"]
6266
+ violatedLayers: ["L1.1"],
6267
+ ...builtinAsk("builtin_home_deletion")
5664
6268
  };
5665
6269
  }
5666
6270
  }
@@ -5691,7 +6295,8 @@ function checkHomeDeletion(actionType, actionDetail) {
5691
6295
  riskType: "script_execution",
5692
6296
  confidence: 90,
5693
6297
  source: "heuristic",
5694
- violatedLayers: ["L1.1"]
6298
+ violatedLayers: ["L1.1"],
6299
+ ...builtinAsk("builtin_home_deletion")
5695
6300
  };
5696
6301
  }
5697
6302
  }
@@ -5701,18 +6306,34 @@ function checkHomeDeletion(actionType, actionDetail) {
5701
6306
  function escapeRegExp(s) {
5702
6307
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5703
6308
  }
6309
+ function dirTargetIsDirectory(text, dirPath) {
6310
+ const low = text.toLowerCase();
6311
+ const dpath = dirPath.toLowerCase();
6312
+ let idx = low.indexOf(dpath);
6313
+ while (idx >= 0) {
6314
+ const tail = low.slice(idx + dpath.length);
6315
+ if (!tail || /^[\s'"\\);|&)>]/.test(tail)) return true;
6316
+ if (tail.startsWith("/*") || tail.startsWith("/.")) return true;
6317
+ if (tail.startsWith("/")) {
6318
+ const rest = tail.slice(1);
6319
+ if (!rest || /^[\s'"\\);|&)>]/.test(rest)) return true;
6320
+ }
6321
+ idx = low.indexOf(dpath, idx + 1);
6322
+ }
6323
+ return false;
6324
+ }
5704
6325
  function isDeleteActionForDir(command, dirPath) {
5705
6326
  const low = command.toLowerCase();
5706
6327
  const dpath = dirPath.toLowerCase();
5707
- if (new RegExp(`\\b(?:rm|unlink|rmdir)\\b[^&|;]*?${escapeRegExp(dpath)}`, "i").test(low)) {
6328
+ if (new RegExp(`\\b(?:rm|unlink|rmdir)\\b[^&|;]*?${escapeRegExp(dpath)}`, "i").test(low) && dirTargetIsDirectory(low, dpath)) {
5708
6329
  return true;
5709
6330
  }
5710
- if (new RegExp(`(?:\u5220\u9664|\u79FB\u9664)[^\\n;|&]*?${escapeRegExp(dpath)}`).test(low)) {
6331
+ if (new RegExp(`(?:\u5220\u9664|\u79FB\u9664)[^\\n;|&]*?${escapeRegExp(dpath)}`).test(low) && dirTargetIsDirectory(low, dpath)) {
5711
6332
  return true;
5712
6333
  }
5713
6334
  for (const seg of low.split(/&&|\|\||;|\n/)) {
5714
6335
  const fw = (seg.trim().split(/\s+/)[0] || "").toLowerCase();
5715
- if ((fw === "rm" || fw === "unlink" || fw === "rmdir") && seg.includes(dpath)) {
6336
+ if ((fw === "rm" || fw === "unlink" || fw === "rmdir") && dirTargetIsDirectory(seg, dpath)) {
5716
6337
  return true;
5717
6338
  }
5718
6339
  }
@@ -5723,7 +6344,7 @@ function isArchiveReadOfDir(command, dirPath) {
5723
6344
  const dpath = dirPath.toLowerCase();
5724
6345
  for (const seg of low.split(/&&|\|\||;|\n/)) {
5725
6346
  const s = seg.trim();
5726
- if (!s || !s.includes(dpath)) continue;
6347
+ if (!s || !dirTargetIsDirectory(s, dpath)) continue;
5727
6348
  const parts = s.split(/\s+/);
5728
6349
  const fw = parts[0] || "";
5729
6350
  if (fw === "zip") return true;
@@ -5733,7 +6354,7 @@ function isArchiveReadOfDir(command, dirPath) {
5733
6354
  }
5734
6355
  if (fw === "cp" || fw === "rsync") {
5735
6356
  const segPaths = s.match(/[/~][^\s;|&><'"]*/g) || [];
5736
- if (segPaths[0]?.includes(dpath)) return true;
6357
+ if (segPaths[0] && dirTargetIsDirectory(segPaths[0], dpath)) return true;
5737
6358
  }
5738
6359
  }
5739
6360
  return false;
@@ -5745,15 +6366,16 @@ function isSshKeygenGenerate(command) {
5745
6366
  if (/(?:^|\s)-\S*[ylpB]\S*/.test(low)) return false;
5746
6367
  return true;
5747
6368
  }
5748
- function checkDangerousPatterns(actionType, actionDetail) {
6369
+ function checkDangerousPatterns(actionType, actionDetail, enabledBuiltin) {
5749
6370
  if (actionType === "file_write" || actionType === "file_edit") return null;
6371
+ const on = (id) => !enabledBuiltin || enabledBuiltin.has(id);
5750
6372
  const scan = stripSearchPatternLiterals(stripHeredocContent(stripShellDocsOnly(actionDetail)));
5751
6373
  const isTempPath = TEMP_DIRS2.some(
5752
6374
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
5753
6375
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
5754
6376
  const wildcardDeleteRe = /(?:\brm\b|\b(r?mdir|del|delete|remove|rmdir|unlink)\b|\b删除\b|\b移除\b)[\s\S]{0,40}?[*?]|[*?][\s\S]{0,40}?\b(?:rm|del|delete|remove|rmdir|unlink)\b|rm\s+-[a-zA-Z]*[rf][a-zA-Z]*\s+\S*[*?]/i;
5755
6377
  const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
5756
- if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
6378
+ if (on("builtin_wildcard_delete") && !isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
5757
6379
  return {
5758
6380
  allowed: false,
5759
6381
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -5761,12 +6383,13 @@ function checkDangerousPatterns(actionType, actionDetail) {
5761
6383
  riskType: "script_execution",
5762
6384
  confidence: 90,
5763
6385
  source: "heuristic",
5764
- violatedLayers: ["L1.1"]
6386
+ violatedLayers: ["L1.1"],
6387
+ ...builtinAsk("builtin_wildcard_delete")
5765
6388
  };
5766
6389
  }
5767
- const findWriteMatch = actionDetail.match(
6390
+ const findWriteMatch = on("builtin_find_exec_write") ? actionDetail.match(
5768
6391
  /\bfind\b.*?(?:(?:^|\s)-exec(?:dir)?\s+(chmod|chown|cp|mv|rm|dd|tee|truncate|mkfs|shred|rmdir|unlink)\b|(?:^|\s)\|\s*xargs\s+(?:sed\s+-[a-zA-Z]*i|chmod|chown|cp|mv|rm|dd|tee|truncate|mkfs|shred|rmdir|unlink)\b)/i
5769
- );
6392
+ ) : null;
5770
6393
  if (findWriteMatch) {
5771
6394
  const cmdHit = findWriteMatch[1] || "xargs";
5772
6395
  return {
@@ -5776,10 +6399,11 @@ function checkDangerousPatterns(actionType, actionDetail) {
5776
6399
  riskType: "script_execution",
5777
6400
  confidence: 90,
5778
6401
  source: "heuristic",
5779
- violatedLayers: ["L1.1"]
6402
+ violatedLayers: ["L1.1"],
6403
+ ...builtinAsk("builtin_find_exec_write")
5780
6404
  };
5781
6405
  }
5782
- if (/>\s*['"]?\/etc\//.test(actionDetail) || />\s*['"]?\/boot\//.test(actionDetail) || />\s*['"]?\/proc\//.test(actionDetail)) {
6406
+ if (on("builtin_redirect_system") && (/>\s*['"]?\/etc\//.test(actionDetail) || />\s*['"]?\/boot\//.test(actionDetail) || />\s*['"]?\/proc\//.test(actionDetail))) {
5783
6407
  return {
5784
6408
  allowed: false,
5785
6409
  reason: "\u68C0\u6D4B\u5230\u91CD\u5B9A\u5411\u8986\u76D6\u5199\u5165\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55",
@@ -5787,7 +6411,8 @@ function checkDangerousPatterns(actionType, actionDetail) {
5787
6411
  riskType: "file_access",
5788
6412
  confidence: 95,
5789
6413
  source: "heuristic",
5790
- violatedLayers: ["L1.1"]
6414
+ violatedLayers: ["L1.1"],
6415
+ ...builtinAsk("builtin_redirect_system")
5791
6416
  };
5792
6417
  }
5793
6418
  if (/>\s*\/dev\/(sd|hd|nvme|vd|loop|mem|kmsg|port|zero|random|urandom|full|core)/i.test(actionDetail)) {
@@ -5889,13 +6514,14 @@ function checkLateralMovement(actionDetail) {
5889
6514
  riskType: "lateral_movement",
5890
6515
  confidence: 80,
5891
6516
  source: "heuristic",
5892
- violatedLayers: ["L1.1"]
6517
+ violatedLayers: ["L1.1"],
6518
+ ...builtinAsk("builtin_lateral_movement")
5893
6519
  };
5894
6520
  }
5895
6521
  }
5896
6522
  return null;
5897
6523
  }
5898
- var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SEARCH_OPTION_WITH_ARG, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
6524
+ var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, LOOP_EXIT_RE, LOOP_START_RE, DB_QUERY_CMD_RE, LOOP_SIDE_EFFECT_RE, LOOPBACK_DATA_GUARD_RE, TEMPLATE_SUFFIX_LA, INSTRUCTION_WRITE_RE, DATA_DOC_EXTS, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SEARCH_OPTION_WITH_ARG, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
5899
6525
  var init_heuristic = __esm({
5900
6526
  "src/engine/heuristic.ts"() {
5901
6527
  "use strict";
@@ -5907,6 +6533,8 @@ var init_heuristic = __esm({
5907
6533
  init_runtime_config_bridge();
5908
6534
  init_rules_loader();
5909
6535
  init_written_content_analyzer();
6536
+ init_inline_analyzer();
6537
+ init_structural_analyzer();
5910
6538
  init_logic_rules();
5911
6539
  INJECTION_KEYWORDS = (() => {
5912
6540
  const kws = loadL1().injection_detection || [];
@@ -5929,6 +6557,30 @@ var init_heuristic = __esm({
5929
6557
  HEURISTIC_RULES = loadHeuristicRules();
5930
6558
  LOOPBACK_HOSTS = new Set(HEURISTIC_RULES.loopback_hosts ?? []);
5931
6559
  TEMP_DIRS2 = HEURISTIC_RULES.temp_dirs ?? [];
6560
+ LOOP_EXIT_RE = /\bbreak\b/gi;
6561
+ LOOP_START_RE = /\bwhile\s+(?:true\b|1\b|:)|until\s+false\b|\bfor\s*\(\s*;/gi;
6562
+ DB_QUERY_CMD_RE = /\b(?:sqlite3|psql|mysql|mariadb|sqlplus)\b|\bpython(?:3(?:\.\d+)?)?\s+-c\b[\s\S]{0,4096}?\b(?:execute|executemany)\s*\(/i;
6563
+ LOOP_SIDE_EFFECT_RE = /\b(?:rm|rmdir|unlink|shred|dd|mkfs\w*|chmod|chown|curl|wget|nc|ncat|socat|ssh|scp|rsync|kill|pkill|killall|shutdown|reboot|systemctl|sudo|mount)\b|\/dev\/tcp|\bos\.(?:system|popen|fork|exec\w*)\b|\bsubprocess\b|>\s*\/(?:etc|dev|proc|sys|boot)\//i;
6564
+ LOOPBACK_DATA_GUARD_RE = /\$|`|\bcat\b|@|-[TF]\b/;
6565
+ TEMPLATE_SUFFIX_LA = "(?!\\.(?:example|template|sample|dist)(?![A-Za-z0-9_-]))";
6566
+ INSTRUCTION_WRITE_RE = /(?:>>?|\btee\b(?:\s+-a)?)\s*(['"]?)([^\s;|&'"<>]+)/gi;
6567
+ DATA_DOC_EXTS = /* @__PURE__ */ new Set([
6568
+ ".md",
6569
+ ".txt",
6570
+ ".rst",
6571
+ ".html",
6572
+ ".htm",
6573
+ ".json",
6574
+ ".yaml",
6575
+ ".yml",
6576
+ ".csv",
6577
+ ".xml",
6578
+ ".css",
6579
+ ".ini",
6580
+ ".conf",
6581
+ ".log",
6582
+ ".sql"
6583
+ ]);
5932
6584
  PATH_CONTEXT_TRIGGER_RE = /(?:^|[;&|]\s*)(?:rm|rmdir|unlink|ln|mv|cp|dd|truncate|shred|chmod|chown)\b/i;
5933
6585
  HOME_PREFIX_RE = /(?:~|~(?=\/)|\$HOME\b|\$\{HOME\}|\/home\/[a-z0-9_.-]+)/gi;
5934
6586
  PY_EXEC_IO_RE = /os\.system|os\.popen|subprocess|eval\s*\(|exec\s*\(|__import__|open\s*\(|socket|urllib|requests\.|shutil|os\.(?:remove|unlink|rename|makedirs?|listdir|scandir|walk|chmod|chown|kill|environ)|iterdir|glob\s*\(|path\(/i;
@@ -5985,17 +6637,17 @@ __export(token_stats_exports, {
5985
6637
  resetTokenStats: () => resetTokenStats,
5986
6638
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
5987
6639
  });
5988
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync7 } from "fs";
6640
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync14, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync8 } from "fs";
5989
6641
  function getStatsPath() {
5990
6642
  const envPath = process.env[ENV_STATS_PATH];
5991
6643
  if (envPath) return envPath;
5992
6644
  return getTokenStatsPath();
5993
6645
  }
5994
6646
  function loadAllRecords(statsPath) {
5995
- if (!existsSync13(statsPath)) return [];
6647
+ if (!existsSync14(statsPath)) return [];
5996
6648
  let sig = "";
5997
6649
  try {
5998
- const st = statSync7(statsPath);
6650
+ const st = statSync8(statsPath);
5999
6651
  sig = `${st.mtimeMs}:${st.size}`;
6000
6652
  } catch {
6001
6653
  return [];
@@ -6018,7 +6670,7 @@ function loadAllRecords(statsPath) {
6018
6670
  function saveRecords(statsPath, records) {
6019
6671
  try {
6020
6672
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
6021
- if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
6673
+ if (dir && !existsSync14(dir)) mkdirSync3(dir, { recursive: true });
6022
6674
  const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
6023
6675
  try {
6024
6676
  writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
@@ -6030,7 +6682,7 @@ function saveRecords(statsPath, records) {
6030
6682
  }
6031
6683
  }
6032
6684
  try {
6033
- const st = statSync7(statsPath);
6685
+ const st = statSync8(statsPath);
6034
6686
  _recordsCache = {
6035
6687
  path: statsPath,
6036
6688
  sig: `${st.mtimeMs}:${st.size}`,
@@ -6167,7 +6819,7 @@ function getTokenTrend(days = 0, startDate, endDate) {
6167
6819
  }
6168
6820
  function resetTokenStats() {
6169
6821
  const statsPath = getStatsPath();
6170
- if (existsSync13(statsPath)) {
6822
+ if (existsSync14(statsPath)) {
6171
6823
  try {
6172
6824
  unlinkSync2(statsPath);
6173
6825
  } catch {
@@ -6190,6 +6842,94 @@ var init_token_stats = __esm({
6190
6842
  // src/engine/coordinator.ts
6191
6843
  init_esm_shims();
6192
6844
  init_heuristic();
6845
+ init_written_content_analyzer();
6846
+
6847
+ // src/engine/shell-alias-resolver.ts
6848
+ init_esm_shims();
6849
+ import { spawnSync } from "child_process";
6850
+ import { existsSync as existsSync9, statSync as statSync5 } from "fs";
6851
+ import { homedir as homedir3 } from "os";
6852
+ import { join as join9 } from "path";
6853
+ var PROBE_TIMEOUT_MS = 2e3;
6854
+ function rcFiles() {
6855
+ return [
6856
+ join9(homedir3(), ".bashrc"),
6857
+ join9(homedir3(), ".bash_profile"),
6858
+ join9(homedir3(), ".profile"),
6859
+ "/etc/bash.bashrc",
6860
+ "/etc/profile"
6861
+ ];
6862
+ }
6863
+ var FIRST_WORD_RE = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*([^\s;|&()]+)/;
6864
+ var cache3 = /* @__PURE__ */ new Map();
6865
+ function rcSignature() {
6866
+ return rcFiles().map((p) => {
6867
+ try {
6868
+ return String(statSync5(p).mtimeMs);
6869
+ } catch {
6870
+ return "0";
6871
+ }
6872
+ }).join("|");
6873
+ }
6874
+ function minimalEnv() {
6875
+ const keep = ["HOME", "USER", "LOGNAME", "SHELL", "PATH", "LANG", "LC_ALL", "TERM"];
6876
+ const env2 = {};
6877
+ for (const k of keep) if (process.env[k] !== void 0) env2[k] = process.env[k];
6878
+ env2.TERM = env2.TERM || "dumb";
6879
+ return env2;
6880
+ }
6881
+ function firstWord(command) {
6882
+ const m = (command || "").match(FIRST_WORD_RE);
6883
+ return m ? m[1] : "";
6884
+ }
6885
+ function run(shell, script, word, cwd) {
6886
+ try {
6887
+ const r = spawnSync(shell, ["-ic", script, "_", word], {
6888
+ timeout: PROBE_TIMEOUT_MS,
6889
+ cwd: cwd || void 0,
6890
+ env: minimalEnv(),
6891
+ stdio: ["ignore", "pipe", "ignore"],
6892
+ encoding: "utf8"
6893
+ });
6894
+ return r.stdout || "";
6895
+ } catch {
6896
+ return "";
6897
+ }
6898
+ }
6899
+ function resolveCommandPrefix(command, cwd = "") {
6900
+ if (process.env.AGENT_MOSS_SHELL_ALIAS_RESOLVE !== "1") return null;
6901
+ if (process.platform === "win32") return null;
6902
+ const word = firstWord(command);
6903
+ if (!word || word.includes("/")) return null;
6904
+ let shell = process.env.SHELL || "/bin/bash";
6905
+ if (!existsSync9(shell)) shell = "/bin/bash";
6906
+ const key = `${process.env.HOME || ""}|${shell}|${word}`;
6907
+ const sig = rcSignature();
6908
+ const cached2 = cache3.get(key);
6909
+ if (cached2 && cached2.sig === sig) return cached2.value;
6910
+ const out = run(shell, 'alias -- "$1" 2>/dev/null; type -a -- "$1" 2>/dev/null', word, cwd);
6911
+ let resolution = null;
6912
+ for (const raw of out.split("\n")) {
6913
+ const line = raw.trim();
6914
+ const m = line.match(/^alias\s+\S+=(.*)$/);
6915
+ if (m) {
6916
+ const value = m[1].trim().replace(/^['"]|['"]$/g, "");
6917
+ const rest = command.trim().slice(word.length).trim();
6918
+ resolution = { word, kind: "alias", expansion: `${value} ${rest}`.trim() };
6919
+ break;
6920
+ }
6921
+ if (new RegExp(`\\b${word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s+is\\s+a\\s+(?:shell\\s+)?function\\b`).test(line)) {
6922
+ const body = run(shell, 'declare -f -- "$1" 2>/dev/null', word, cwd).trim();
6923
+ if (body) resolution = { word, kind: "function", expansion: `${body}
6924
+ ${command}` };
6925
+ break;
6926
+ }
6927
+ }
6928
+ cache3.set(key, { sig, value: resolution });
6929
+ return resolution;
6930
+ }
6931
+
6932
+ // src/engine/coordinator.ts
6193
6933
  init_logic_rules();
6194
6934
  init_platform_traits();
6195
6935
  init_shell_split();
@@ -6202,9 +6942,9 @@ import { createHash as createHash2 } from "crypto";
6202
6942
  // src/infra/security-policy.ts
6203
6943
  init_esm_shims();
6204
6944
  init_paths();
6205
- import { chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as existsSync9, lstatSync, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync8, readSync as readSync2, realpathSync, writeSync } from "fs";
6206
- import { homedir as homedir3, tmpdir } from "os";
6207
- import { basename as basename2, isAbsolute as isAbsolute2, join as join9, relative, resolve as resolve7, dirname as dirname8 } from "path";
6945
+ import { chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as existsSync10, lstatSync, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync8, readSync as readSync2, realpathSync, writeSync } from "fs";
6946
+ import { homedir as homedir4, tmpdir } from "os";
6947
+ import { basename as basename2, isAbsolute as isAbsolute2, join as join10, relative, resolve as resolve7, dirname as dirname8 } from "path";
6208
6948
  var TRUTHY2 = ["1", "true", "yes", "on"];
6209
6949
  function env(name, dflt = "") {
6210
6950
  return (process.env[name] ?? dflt).trim();
@@ -6214,7 +6954,7 @@ function splitList(raw) {
6214
6954
  }
6215
6955
  function homeDir() {
6216
6956
  try {
6217
- const home = homedir3();
6957
+ const home = homedir4();
6218
6958
  if (process.getuid?.() === 0) {
6219
6959
  const explicit = resolveExplicitOwnerHome();
6220
6960
  if (explicit) return explicit;
@@ -6245,7 +6985,7 @@ function realpathLoose(p) {
6245
6985
  parts.unshift(basename2(cur));
6246
6986
  cur = parent;
6247
6987
  try {
6248
- return join9(realpathSync(cur), ...parts);
6988
+ return join10(realpathSync(cur), ...parts);
6249
6989
  } catch {
6250
6990
  }
6251
6991
  }
@@ -6307,7 +7047,7 @@ init_skill_loader();
6307
7047
  // src/engine/template-loader.ts
6308
7048
  init_esm_shims();
6309
7049
  init_asset_dir();
6310
- import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
7050
+ import { readFileSync as readFileSync9, existsSync as existsSync11 } from "fs";
6311
7051
  import { resolve as resolve8, dirname as dirname9 } from "path";
6312
7052
  import { fileURLToPath as fileURLToPath9 } from "url";
6313
7053
  var __filename6 = fileURLToPath9(import.meta.url);
@@ -6325,7 +7065,7 @@ function loadTemplates() {
6325
7065
  }
6326
7066
  for (const file of TEMPLATE_FILES) {
6327
7067
  const filePath = resolve8(dir, file);
6328
- if (existsSync10(filePath)) {
7068
+ if (existsSync11(filePath)) {
6329
7069
  const key = file.replace(".txt", "").replace("_template", "");
6330
7070
  cachedTemplates[key] = readFileSync9(filePath, "utf-8");
6331
7071
  }
@@ -6338,7 +7078,7 @@ function loadTemplates() {
6338
7078
  init_esm_shims();
6339
7079
  init_rules_loader();
6340
7080
  import { readFileSync as readFileSync10 } from "fs";
6341
- import { resolve as resolve9, join as join10 } from "path";
7081
+ import { resolve as resolve9, join as join11 } from "path";
6342
7082
  var SCRIPT_RULES = loadScriptRules();
6343
7083
  if (!SCRIPT_RULES || Object.keys(SCRIPT_RULES).length === 0) {
6344
7084
  console.error(
@@ -6408,7 +7148,7 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
6408
7148
  }
6409
7149
  function readScriptContent(scriptPath, maxLines = 500) {
6410
7150
  try {
6411
- const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join10(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve9(scriptPath);
7151
+ const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join11(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve9(scriptPath);
6412
7152
  const raw = readFileSync10(expandedPath, "utf-8");
6413
7153
  const lines = raw.split("\n").slice(0, maxLines);
6414
7154
  return { content: lines.join("\n"), lineCount: lines.length, error: "" };
@@ -6465,9 +7205,9 @@ init_heuristic();
6465
7205
  init_config();
6466
7206
  init_logic_rules();
6467
7207
  init_inline_analyzer();
6468
- import { statSync as statSync6, existsSync as existsSync12 } from "fs";
6469
- import { resolve as resolve11, join as join12, isAbsolute as isAbsolute5 } from "path";
6470
- import { homedir as homedir5 } from "os";
7208
+ import { statSync as statSync7, existsSync as existsSync13 } from "fs";
7209
+ import { resolve as resolve11, join as join13, isAbsolute as isAbsolute5 } from "path";
7210
+ import { homedir as homedir6 } from "os";
6471
7211
 
6472
7212
  // src/engine/script-engine/tracker.ts
6473
7213
  init_esm_shims();
@@ -9810,6 +10550,7 @@ function emptyNode(pathStr, depth) {
9810
10550
  l1RiskType: "",
9811
10551
  l1Reason: "",
9812
10552
  l1MatchedPatterns: [],
10553
+ l1AskReason: "",
9813
10554
  l2Hit: false,
9814
10555
  l2ViolatedRule: "",
9815
10556
  l2RiskLevel: "",
@@ -9983,6 +10724,7 @@ var RecursiveTracker = class {
9983
10724
  node.l1RiskType = l1.riskType;
9984
10725
  node.l1Reason = l1.reason;
9985
10726
  node.l1MatchedPatterns = l1.matchedPatterns || [];
10727
+ node.l1AskReason = l1.askReason || "";
9986
10728
  if (l1.riskLevel === "critical") {
9987
10729
  this.result.hasCritical = true;
9988
10730
  if (!this.result.firstHitNode) this.result.firstHitNode = node;
@@ -10161,8 +10903,8 @@ function extractInlineScriptPath(actionDetail) {
10161
10903
  if (looksLikeScriptPath(tok)) {
10162
10904
  try {
10163
10905
  const resolved = resolvePath2(tok.replace(/^['"]|['"]$/g, ""));
10164
- if (existsSync12(resolved)) {
10165
- const stat = statSync6(resolved);
10906
+ if (existsSync13(resolved)) {
10907
+ const stat = statSync7(resolved);
10166
10908
  if (stat.isFile()) return resolved;
10167
10909
  }
10168
10910
  } catch {
@@ -10175,8 +10917,8 @@ function extractInlineScriptPath(actionDetail) {
10175
10917
  const p = m[1];
10176
10918
  try {
10177
10919
  const resolved = resolvePath2(p);
10178
- if (existsSync12(resolved)) {
10179
- const stat = statSync6(resolved);
10920
+ if (existsSync13(resolved)) {
10921
+ const stat = statSync7(resolved);
10180
10922
  if (stat.isFile()) return resolved;
10181
10923
  }
10182
10924
  } catch {
@@ -10191,8 +10933,8 @@ function extractInlineScriptPath(actionDetail) {
10191
10933
  let resolved;
10192
10934
  try {
10193
10935
  resolved = resolvePath2(p);
10194
- if (existsSync12(resolved)) {
10195
- const stat = statSync6(resolved);
10936
+ if (existsSync13(resolved)) {
10937
+ const stat = statSync7(resolved);
10196
10938
  if (stat.isFile()) return resolved;
10197
10939
  }
10198
10940
  } catch {
@@ -10232,7 +10974,7 @@ function shlexSplit(s) {
10232
10974
  function resolvePath2(p) {
10233
10975
  let expanded = p;
10234
10976
  if (expanded.startsWith("~/") || expanded === "~") {
10235
- expanded = join12(homedir5(), expanded.slice(1));
10977
+ expanded = join13(homedir6(), expanded.slice(1));
10236
10978
  }
10237
10979
  return resolve11(expanded);
10238
10980
  }
@@ -10259,6 +11001,31 @@ function scanExtensionPatterns(ext, content) {
10259
11001
  }
10260
11002
  return null;
10261
11003
  }
11004
+ function scanSensitiveSegments(content, cwd, ext, osType) {
11005
+ let prefilter = null;
11006
+ try {
11007
+ const { root, home, credential } = getSensitivePathsForOs(osType);
11008
+ const prefixes = [];
11009
+ for (const sp of [...root, ...home, ...credential]) {
11010
+ const prefix = String(sp.path || "").split("(")[0].trim();
11011
+ if (prefix) prefixes.push(prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
11012
+ }
11013
+ if (prefixes.length) prefilter = new RegExp(prefixes.join("|"), "i");
11014
+ } catch {
11015
+ }
11016
+ let best = null;
11017
+ for (const raw of content.split(/&&|\|\||;|\n/)) {
11018
+ const seg = raw.trim();
11019
+ if (!seg) continue;
11020
+ if (prefilter && !prefilter.test(seg)) continue;
11021
+ const j = checkSensitivePath(seg, cwd, ext, osType);
11022
+ if (!j || j.allowed) continue;
11023
+ if (!best || (LEVEL_ORDER2[j.riskLevel] || 0) > (LEVEL_ORDER2[best.riskLevel] || 0)) {
11024
+ best = { riskLevel: j.riskLevel, riskType: j.riskType, reason: j.reason, askReason: j.ask_reason };
11025
+ }
11026
+ }
11027
+ return best;
11028
+ }
10262
11029
  function scanScriptChainWithL2(chain, input) {
10263
11030
  for (const node of chain.nodes) {
10264
11031
  if (node.error || !node.preprocessedContent) continue;
@@ -10321,31 +11088,21 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
10321
11088
  isInline = true;
10322
11089
  }
10323
11090
  if (resolvedPath && !isAbsolute5(resolvedPath) && !resolvedPath.startsWith("~/")) {
10324
- resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
11091
+ resolvedPath = join13(input.cwd || process.cwd(), resolvedPath);
10325
11092
  }
10326
11093
  const l1Adapter = (content) => {
11094
+ const candidates = [];
10327
11095
  const extHit = scanExtensionPatterns(ext, content);
10328
- if (extHit) {
10329
- return {
10330
- hit: true,
10331
- riskLevel: extHit.riskLevel,
10332
- riskType: extHit.riskType,
10333
- reason: extHit.reason,
10334
- matchedPatterns: []
10335
- };
10336
- }
11096
+ if (extHit) candidates.push({ riskLevel: extHit.riskLevel, riskType: extHit.riskType, reason: extHit.reason });
10337
11097
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
10338
- if (j && !j.allowed) {
10339
- return {
10340
- hit: true,
10341
- riskLevel: j.riskLevel,
10342
- riskType: j.riskType,
10343
- reason: j.reason,
10344
- matchedPatterns: []
10345
- // SecurityJudgment 不带模式列表(见 types.ts);留空即可
10346
- };
10347
- }
10348
- return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
11098
+ if (j && !j.allowed) candidates.push({ riskLevel: j.riskLevel, riskType: j.riskType, reason: j.reason, askReason: j.ask_reason });
11099
+ const spHit = scanSensitiveSegments(content, input.cwd || process.cwd(), ext, input.osType);
11100
+ if (spHit) candidates.push(spHit);
11101
+ if (candidates.length === 0) {
11102
+ return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
11103
+ }
11104
+ const best = candidates.reduce((a, b) => (LEVEL_ORDER2[b.riskLevel] || 0) > (LEVEL_ORDER2[a.riskLevel] || 0) ? b : a);
11105
+ return { hit: true, riskLevel: best.riskLevel, riskType: best.riskType, reason: best.reason, matchedPatterns: [], askReason: best.askReason };
10349
11106
  };
10350
11107
  const tracker = new RecursiveTracker(
10351
11108
  l1Adapter,
@@ -11233,23 +11990,37 @@ async function analyzeWithLLM(prompt, config) {
11233
11990
  }
11234
11991
  const attemptStart = performance.now();
11235
11992
  try {
11236
- const response = await client.chat.completions.create({
11237
- model: config.model,
11238
- temperature: config.temperature || 0.1,
11239
- max_tokens: config.maxTokens || 1024,
11240
- messages: [
11241
- { 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" },
11242
- { role: "user", content: prompt }
11243
- ],
11244
- signal: abortController.signal,
11245
- // 私有化网关的额外参数(关思考等)原样透传;空则不传。
11246
- ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
11247
- });
11993
+ const baseBudget = config.maxTokens || 1024;
11994
+ const escalatedBudget = Math.min(Math.max(baseBudget * 4, 16384), 32768);
11995
+ let response = null;
11996
+ let content = "";
11997
+ let finishReason;
11998
+ let usage = null;
11999
+ for (const budget of Array.from(/* @__PURE__ */ new Set([baseBudget, escalatedBudget]))) {
12000
+ response = await client.chat.completions.create({
12001
+ model: config.model,
12002
+ temperature: config.temperature || 0.1,
12003
+ max_tokens: budget,
12004
+ messages: [
12005
+ { 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" },
12006
+ { role: "user", content: prompt }
12007
+ ],
12008
+ signal: abortController.signal,
12009
+ // 私有化网关的额外参数(关思考等)原样透传;空则不传。
12010
+ ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
12011
+ });
12012
+ const msg = response.choices[0]?.message;
12013
+ content = msg?.content ?? "";
12014
+ finishReason = response.choices[0]?.finish_reason;
12015
+ usage = response.usage;
12016
+ const hasReasoning = ["reasoning", "reasoning_content", "thinking"].some((k) => typeof msg?.[k] === "string" && msg[k].length > 0);
12017
+ if (content || finishReason !== "length" || budget === escalatedBudget || !hasReasoning) break;
12018
+ console.warn(
12019
+ `[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08max_tokens=${budget}\uFF09\uFF0C\u6309\u63A8\u7406\u6A21\u578B\u7B56\u7565\u63D0\u5347\u5230 ${escalatedBudget} \u91CD\u8BD5\u4E00\u6B21\uFF08model=${config.model}\uFF09\u2014\u2014\u975E\u63A8\u7406\u6A21\u578B\u4E0D\u4F1A\u89E6\u53D1\u6B64\u8DEF\u5F84`
12020
+ );
12021
+ }
11248
12022
  const message = response.choices[0]?.message;
11249
- let content = message?.content ?? "";
11250
- const finishReason = response.choices[0]?.finish_reason;
11251
12023
  const fieldLengths = responseFieldLengths(message);
11252
- const usage = response.usage;
11253
12024
  if (!content) {
11254
12025
  const { text: fallback, field } = reasoningFallbackWithField(message);
11255
12026
  if (fallback) {
@@ -11382,10 +12153,10 @@ init_esm_shims();
11382
12153
 
11383
12154
  // src/brain/rule-store.ts
11384
12155
  init_esm_shims();
11385
- import { existsSync as existsSync14, readFileSync as readFileSync14, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
11386
- import { join as join13 } from "path";
11387
- import { homedir as homedir6 } from "os";
11388
- var DEFAULT_RULES_PATH = join13(homedir6(), ".agentmoss", "brain", "rules.json");
12156
+ import { existsSync as existsSync15, readFileSync as readFileSync14, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
12157
+ import { join as join14 } from "path";
12158
+ import { homedir as homedir7 } from "os";
12159
+ var DEFAULT_RULES_PATH = join14(homedir7(), ".agentmoss", "brain", "rules.json");
11389
12160
  var ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
11390
12161
  var STATUS_DRAFT = "draft";
11391
12162
  var STATUS_APPROVED = "approved";
@@ -11414,7 +12185,7 @@ var BrainRuleStore = class {
11414
12185
  this.data = this.load();
11415
12186
  }
11416
12187
  load() {
11417
- if (!existsSync14(this.path)) {
12188
+ if (!existsSync15(this.path)) {
11418
12189
  return { version: 1, rules: [], pattern_candidates: [] };
11419
12190
  }
11420
12191
  try {
@@ -11998,11 +12769,11 @@ function parseReview(content) {
11998
12769
 
11999
12770
  // src/brain/skill-manager.ts
12000
12771
  init_esm_shims();
12001
- import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
12002
- import { homedir as homedir7 } from "os";
12003
- import { join as join14 } from "path";
12772
+ import { existsSync as existsSync16, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
12773
+ import { homedir as homedir8 } from "os";
12774
+ import { join as join15 } from "path";
12004
12775
  import { randomUUID } from "crypto";
12005
- var DEFAULT_SKILL_META_PATH = join14(homedir7(), ".agentmoss", "brain", "skill_meta.json");
12776
+ var DEFAULT_SKILL_META_PATH = join15(homedir8(), ".agentmoss", "brain", "skill_meta.json");
12006
12777
  var ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
12007
12778
  function getMetaPath(override) {
12008
12779
  return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
@@ -12012,7 +12783,7 @@ var BrainSkillManager = class {
12012
12783
  this.skillsDir = skillsDir;
12013
12784
  this.metaPath = getMetaPath(metaPath);
12014
12785
  try {
12015
- mkdirSync5(join14(this.metaPath, ".."), { recursive: true });
12786
+ mkdirSync5(join15(this.metaPath, ".."), { recursive: true });
12016
12787
  } catch {
12017
12788
  }
12018
12789
  this.load();
@@ -12022,7 +12793,7 @@ var BrainSkillManager = class {
12022
12793
  skills = [];
12023
12794
  metaPath;
12024
12795
  load() {
12025
- if (!existsSync15(this.metaPath)) return;
12796
+ if (!existsSync16(this.metaPath)) return;
12026
12797
  try {
12027
12798
  const data = JSON.parse(readFileSync15(this.metaPath, "utf-8"));
12028
12799
  this.skills = data.skills || [];
@@ -12047,7 +12818,7 @@ var BrainSkillManager = class {
12047
12818
  let changed = false;
12048
12819
  for (const sk of this.skills) {
12049
12820
  if (sk.status !== "active") continue;
12050
- if (!existsSync15(join14(this.skillsDir, `${sk.name}.md`))) {
12821
+ if (!existsSync16(join15(this.skillsDir, `${sk.name}.md`))) {
12051
12822
  sk.status = "stale";
12052
12823
  changed = true;
12053
12824
  }
@@ -12058,9 +12829,9 @@ var BrainSkillManager = class {
12058
12829
  addSkill(skill) {
12059
12830
  const id = skill.id || randomUUID();
12060
12831
  const name = skill.name || `brain_${id.slice(0, 8)}`;
12061
- if (!existsSync15(this.skillsDir)) return "";
12062
- const mdPath = join14(this.skillsDir, `${name}.md`);
12063
- if (existsSync15(mdPath)) return "";
12832
+ if (!existsSync16(this.skillsDir)) return "";
12833
+ const mdPath = join15(this.skillsDir, `${name}.md`);
12834
+ if (existsSync16(mdPath)) return "";
12064
12835
  try {
12065
12836
  writeFileSync4(mdPath, skill.content, "utf-8");
12066
12837
  } catch {
@@ -12109,8 +12880,8 @@ var BrainSkillManager = class {
12109
12880
  const out = [];
12110
12881
  for (const sk of this.skills) {
12111
12882
  if (sk.origin_node !== "local" || sk.status !== "active") continue;
12112
- const mdPath = join14(this.skillsDir, `${sk.name}.md`);
12113
- if (!existsSync15(mdPath)) continue;
12883
+ const mdPath = join15(this.skillsDir, `${sk.name}.md`);
12884
+ if (!existsSync16(mdPath)) continue;
12114
12885
  out.push({
12115
12886
  name: sk.name,
12116
12887
  category: sk.category || "",
@@ -12565,9 +13336,10 @@ var COMMON_DIR_RESOURCES = /* @__PURE__ */ new Set([
12565
13336
  "/data",
12566
13337
  "/storage"
12567
13338
  ]);
13339
+ var WORKDIR_CMD_RE = /\b(?:cd|pushd|mkdir)\s+(?:-[^\s;&|]+\s+)*[^\s;&|]+/gi;
12568
13340
  function extractResources(actionDetail) {
12569
13341
  const resources = /* @__PURE__ */ new Set();
12570
- const text = actionDetail.replace(/'[^']*'|"[^"]*"/g, "");
13342
+ const text = actionDetail.replace(/'[^']*'|"[^"]*"/g, "").replace(WORKDIR_CMD_RE, " ");
12571
13343
  PATH_RE.lastIndex = 0;
12572
13344
  let m;
12573
13345
  while ((m = PATH_RE.exec(text)) !== null) {
@@ -12583,7 +13355,7 @@ function markStage(actionDetail) {
12583
13355
  }
12584
13356
  function markIntegrity(actionDetail) {
12585
13357
  const aps = labelEvent(actionDetail);
12586
- if (aps.has("download_file") || aps.has("prompt_injection")) {
13358
+ if (aps.has("download_file")) {
12587
13359
  return { integrity: "low", isLowSource: true };
12588
13360
  }
12589
13361
  return { integrity: "medium", isLowSource: false };
@@ -13243,7 +14015,7 @@ function checkLowIntegrityCommandExec(graph) {
13243
14015
  }
13244
14016
  return violations;
13245
14017
  }
13246
- var DL_OR_LOW_RE = /curl\s+.*-o\b|wget\s+.*\s+-O\b|curl\s+.*\|\s*(bash|sh|python)|wget\s+.*\|\s*(bash|sh|python)|git\s+clone|docker\s+pull|pip\s+install|npm\s+install|base64\s+-d/i;
14018
+ var DL_OR_LOW_RE = /curl\s+.*-o\b|wget\s+.*\s+-O\b|curl\s+.*\|\s*(bash|sh|python)|wget\s+.*\|\s*(bash|sh|python)|git\s+clone|docker\s+pull|(?:pip3?(?:\.\d+)?|python[0-9.]*\s+-m\s+pip)\s+install|(?:npm|yarn|pnpm)\s+(?:i|install|add)|(?:base64|base32)\s+-d|openssl\s+base64\s+-d/i;
13247
14019
  function checkCrossSessionReachability(graph) {
13248
14020
  const violations = [];
13249
14021
  const nodes = allNodes(graph);
@@ -13591,6 +14363,9 @@ async function runAnalysis(input) {
13591
14363
  isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
13592
14364
  );
13593
14365
  const degradedNotes = [];
14366
+ let decodedPayloads = [];
14367
+ let aliasResolution = null;
14368
+ const decodeHints = [];
13594
14369
  let scriptChain = null;
13595
14370
  if (input.aNext.actionType.toLowerCase() === "bash" && getDeployRole() === "host") {
13596
14371
  degradedNotes.push("script_content_deferred_to_sandbox: AGENT_MOSS_DEPLOY_ROLE=host");
@@ -13626,11 +14401,63 @@ async function runAnalysis(input) {
13626
14401
  riskType: node.l1RiskType,
13627
14402
  confidence: 90,
13628
14403
  source: "heuristic_script_scan",
13629
- violatedLayers: ["L1.2"]
14404
+ violatedLayers: ["L1.2"],
14405
+ ...node.l1AskReason ? { ask_recommended: true, ask_reason: node.l1AskReason } : {}
14406
+ };
14407
+ }
14408
+ }
14409
+ }
14410
+ }
14411
+ try {
14412
+ const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
14413
+ decodedPayloads = extractDecodedPayloads(
14414
+ input.aNext.actionType,
14415
+ input.aNext.actionDetail,
14416
+ handledWrite
14417
+ );
14418
+ if (input.aNext.actionType.toLowerCase() === "bash") {
14419
+ aliasResolution = resolveCommandPrefix(input.aNext.actionDetail, input.cwd || "");
14420
+ }
14421
+ if (heuristicEnabled) {
14422
+ for (const p of decodedPayloads) {
14423
+ const l1 = detectDecoded(p.decoded);
14424
+ if (!l1) continue;
14425
+ if (l1.allowed !== false) continue;
14426
+ const level = p.source === "instruction" ? l1.riskLevel : "medium";
14427
+ if (level === "high" || level === "critical") {
14428
+ return {
14429
+ allowed: false,
14430
+ reason: `\u89E3\u7801\u5206\u6790\uFF08${p.encoding} \u7F16\u7801\uFF09\uFF1A${l1.reason}`,
14431
+ riskLevel: level,
14432
+ riskType: l1.riskType,
14433
+ confidence: 95,
14434
+ source: "decode_engine",
14435
+ violatedLayers: ["L1.3"],
14436
+ ...l1.ask_reason ? { ask_recommended: true, ask_reason: l1.ask_reason } : {}
13630
14437
  };
13631
14438
  }
14439
+ decodeHints.push(`[${p.encoding}/${p.source}] ${l1.reason}`);
13632
14440
  }
13633
14441
  }
14442
+ } catch {
14443
+ }
14444
+ if (heuristicEnabled && aliasResolution) {
14445
+ const l1 = detectDecoded(aliasResolution.expansion);
14446
+ if (l1 && l1.allowed === false && (l1.riskLevel === "high" || l1.riskLevel === "critical")) {
14447
+ return {
14448
+ allowed: false,
14449
+ reason: `\u522B\u540D/\u51FD\u6570\u5C55\u5F00\uFF08${aliasResolution.word}\uFF09\uFF1A${l1.reason}`,
14450
+ riskLevel: l1.riskLevel,
14451
+ riskType: l1.riskType,
14452
+ confidence: 90,
14453
+ source: "alias_engine",
14454
+ violatedLayers: ["L1.4"],
14455
+ ...l1.ask_reason ? { ask_recommended: true, ask_reason: l1.ask_reason } : {}
14456
+ };
14457
+ }
14458
+ if (l1 && l1.allowed === false) {
14459
+ decodeHints.push(`[alias/${aliasResolution.kind}] ${l1.reason}`);
14460
+ }
13634
14461
  }
13635
14462
  const brainStore = getBrainStore(input.osType);
13636
14463
  if (brainStore) {
@@ -13846,6 +14673,48 @@ async function runAnalysis(input) {
13846
14673
  }
13847
14674
  }
13848
14675
  }
14676
+ if (decodedPayloads.length > 0 && isLogicRulesEnabled()) {
14677
+ for (const p of decodedPayloads) {
14678
+ const l2 = runLogicCheck(
14679
+ { ...input, aNext: { actionType: "bash", actionDetail: p.decoded } },
14680
+ { agentExt }
14681
+ );
14682
+ if (!l2 || l2.allowed !== false) continue;
14683
+ const level = p.source === "instruction" ? l2.riskLevel : "medium";
14684
+ if (level === "high" || level === "critical") {
14685
+ return {
14686
+ allowed: false,
14687
+ reason: `\u89E3\u7801\u5206\u6790\uFF08${p.encoding} \u7F16\u7801\uFF09\uFF1A${l2.reason}`,
14688
+ riskLevel: level,
14689
+ riskType: l2.riskType,
14690
+ confidence: 90,
14691
+ source: "decode_engine",
14692
+ violatedLayers: ["L2.4"]
14693
+ };
14694
+ }
14695
+ decodeHints.push(`[${p.encoding}/${p.source}] ${l2.reason}`);
14696
+ }
14697
+ }
14698
+ if (isLogicRulesEnabled() && aliasResolution) {
14699
+ const l2 = runLogicCheck(
14700
+ { ...input, aNext: { actionType: "bash", actionDetail: aliasResolution.expansion } },
14701
+ { agentExt }
14702
+ );
14703
+ if (l2 && l2.allowed === false && (l2.riskLevel === "high" || l2.riskLevel === "critical")) {
14704
+ return {
14705
+ allowed: false,
14706
+ reason: `\u522B\u540D/\u51FD\u6570\u5C55\u5F00\uFF08${aliasResolution.word}\uFF09\uFF1A${l2.reason}`,
14707
+ riskLevel: l2.riskLevel,
14708
+ riskType: l2.riskType,
14709
+ confidence: 90,
14710
+ source: "alias_engine",
14711
+ violatedLayers: ["L2.5"]
14712
+ };
14713
+ }
14714
+ if (l2 && l2.allowed === false) {
14715
+ decodeHints.push(`[alias/${aliasResolution.kind}] ${l2.reason}`);
14716
+ }
14717
+ }
13849
14718
  if (brainStore) {
13850
14719
  const brainL2 = checkBrainRules(brainStore, {
13851
14720
  layer: 2,
@@ -13899,6 +14768,9 @@ async function runAnalysis(input) {
13899
14768
  }
13900
14769
  } catch {
13901
14770
  }
14771
+ if (decodeHints.length > 0) {
14772
+ skipL3Hints += "\n\u89E3\u7801\u5206\u6790\u7EBF\u7D22\uFF1A\n- " + decodeHints.join("\n- ");
14773
+ }
13902
14774
  let llmResult;
13903
14775
  try {
13904
14776
  const pathContext = buildPathContext(input.aNext.actionDetail);