@kenhkl/agent-moss 0.17.30 → 0.17.34

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.
@@ -1091,6 +1091,22 @@ function historyCommandText(histDetailRaw) {
1091
1091
  }
1092
1092
  return histDetailRaw;
1093
1093
  }
1094
+ function isScriptGeneratedTarget(targetPath, writtenScripts, shellRuns) {
1095
+ const base = path2.basename(targetPath);
1096
+ if (base.length < 3) return false;
1097
+ const targetDir = path2.dirname(targetPath);
1098
+ if (!targetDir) return false;
1099
+ for (const script of writtenScripts) {
1100
+ if (path2.dirname(script.path) !== targetDir) continue;
1101
+ if (!script.detail.includes(base)) continue;
1102
+ const scriptName = path2.basename(script.path);
1103
+ if (!scriptName) continue;
1104
+ if (shellRuns.some((run) => run.index > script.index && run.command.includes(scriptName))) {
1105
+ return true;
1106
+ }
1107
+ }
1108
+ return false;
1109
+ }
1094
1110
  function parseHeadTailLimit(seg) {
1095
1111
  const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
1096
1112
  if (firstWord !== "head" && firstWord !== "tail") return null;
@@ -1610,7 +1626,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1610
1626
  const historyFullReadPaths = /* @__PURE__ */ new Set();
1611
1627
  const historyPartialRead = /* @__PURE__ */ new Map();
1612
1628
  const historyWrittenPaths = /* @__PURE__ */ new Set();
1613
- for (const action of actionHistory) {
1629
+ let historyWrittenScripts = [];
1630
+ const shellRunActions = [];
1631
+ for (let actionIndex = 0; actionIndex < actionHistory.length; actionIndex++) {
1632
+ const action = actionHistory[actionIndex];
1614
1633
  const histDetailRaw = action.actionDetail;
1615
1634
  const histType = action.actionType.toLowerCase();
1616
1635
  const traits = getPlatformTraits(osType);
@@ -1622,7 +1641,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1622
1641
  );
1623
1642
  for (const p of coverage.full) historyFullReadPaths.add(p);
1624
1643
  if (isFullOverwriteTool(histType, singleFileTools) && !APPEND_MODE_RE.test(histDetailRaw)) {
1625
- for (const p of declaredWritePaths(histDetailRaw, osType)) historyWrittenPaths.add(p);
1644
+ for (const p of declaredWritePaths(histDetailRaw, osType)) {
1645
+ historyWrittenPaths.add(p);
1646
+ if (SCRIPT_FILE_RE.test(p)) {
1647
+ historyWrittenScripts.push({ path: p, detail: histDetailRaw, index: actionIndex });
1648
+ }
1649
+ }
1650
+ }
1651
+ if (BASH_LIKE_ACTION_TYPES.includes(histType)) {
1652
+ shellRunActions.push({ index: actionIndex, command: historyCommandText(histDetailRaw) });
1626
1653
  }
1627
1654
  for (const [p, upto] of coverage.partial) {
1628
1655
  if (historyPartialRead.has(p)) {
@@ -1649,6 +1676,7 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1649
1676
  const normalizedWrittenPaths = new Set(
1650
1677
  [...historyWrittenPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
1651
1678
  );
1679
+ historyWrittenScripts = historyWrittenScripts.map((s) => ({ ...s, path: normalizePathForCompare(s.path, cwd) })).filter((s) => s.path);
1652
1680
  const normalizedPartialReads = /* @__PURE__ */ new Map();
1653
1681
  for (const [p, upto] of historyPartialRead) {
1654
1682
  const np = normalizePathForCompare(p, cwd);
@@ -1678,6 +1706,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1678
1706
  )) {
1679
1707
  isFullRead = true;
1680
1708
  }
1709
+ if (!isFullRead && !isProtectedWritePath(path7) && isScriptGeneratedTarget(path7, historyWrittenScripts, shellRunActions)) {
1710
+ isFullRead = true;
1711
+ }
1681
1712
  let isPartialCovered = false;
1682
1713
  if (!isFullRead) {
1683
1714
  for (const [pp, upto] of normalizedPartialReads) {
@@ -1871,7 +1902,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
1871
1902
  violatedLayers: ["L2.1"]
1872
1903
  };
1873
1904
  }
1874
- 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, 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, 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;
1905
+ 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, 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;
1875
1906
  var init_logic_rules = __esm({
1876
1907
  "src/engine/logic-rules.ts"() {
1877
1908
  "use strict";
@@ -1937,6 +1968,7 @@ var init_logic_rules = __esm({
1937
1968
  PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
1938
1969
  APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
1939
1970
  APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
1971
+ SCRIPT_FILE_RE = /\.(?:py|pyw|sh|bash|zsh|js|mjs|cjs|ts|pl|rb|php|ps1|bat|cmd)$/i;
1940
1972
  SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
1941
1973
  SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
1942
1974
  SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
@@ -2041,7 +2073,7 @@ var init_asset_dir = __esm({
2041
2073
 
2042
2074
  // src/engine/skill-loader.ts
2043
2075
  import { readFileSync as readFileSync3, readdirSync as readdirSync3, existsSync as existsSync4 } from "fs";
2044
- import { resolve as resolve3, dirname as dirname2 } from "path";
2076
+ import { resolve as resolve3, dirname as dirname3 } from "path";
2045
2077
  import { fileURLToPath as fileURLToPath3 } from "url";
2046
2078
  function loadAllSkills() {
2047
2079
  if (cachedSkills) return cachedSkills;
@@ -2155,7 +2187,7 @@ var init_skill_loader = __esm({
2155
2187
  init_asset_dir();
2156
2188
  init_runtime_config_bridge();
2157
2189
  __filename3 = fileURLToPath3(import.meta.url);
2158
- __dirname3 = dirname2(__filename3);
2190
+ __dirname3 = dirname3(__filename3);
2159
2191
  SKILL_KEYWORD_MAP = (() => {
2160
2192
  const map = {};
2161
2193
  const cats = loadL3();
@@ -2238,7 +2270,7 @@ __export(runtime_config_exports, {
2238
2270
  import { readFileSync as readFileSync4, writeFileSync, existsSync as existsSync5, mkdirSync, unlinkSync, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
2239
2271
  import { join as join5 } from "path";
2240
2272
  import { fileURLToPath as fileURLToPath4 } from "url";
2241
- import { dirname as dirname3 } from "path";
2273
+ import { dirname as dirname4 } from "path";
2242
2274
  function runtimeDir() {
2243
2275
  return getRuntimeConfigDir();
2244
2276
  }
@@ -3593,7 +3625,7 @@ var init_runtime_config = __esm({
3593
3625
  init_rules_loader();
3594
3626
  init_runtime_config_bridge();
3595
3627
  init_rules_mode();
3596
- __dirname4 = dirname3(fileURLToPath4(import.meta.url));
3628
+ __dirname4 = dirname4(fileURLToPath4(import.meta.url));
3597
3629
  ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
3598
3630
  RUNTIME_CONFIG_DIR = runtimeDir();
3599
3631
  RUNTIME_CONFIG_PATH = join5(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
@@ -3968,7 +4000,7 @@ var init_config = __esm({
3968
4000
 
3969
4001
  // src/agents/index.ts
3970
4002
  import { readFileSync as readFileSync5, existsSync as existsSync6 } from "fs";
3971
- import { resolve as resolve4, dirname as dirname4, join as join6 } from "path";
4003
+ import { resolve as resolve4, dirname as dirname5, join as join6 } from "path";
3972
4004
  import { fileURLToPath as fileURLToPath6 } from "url";
3973
4005
  function resolveAgentsDir() {
3974
4006
  const root = getRulesRoot();
@@ -4045,7 +4077,7 @@ var init_agents = __esm({
4045
4077
  init_paths();
4046
4078
  init_runtime_config();
4047
4079
  __filename4 = fileURLToPath6(import.meta.url);
4048
- __dirname5 = dirname4(__filename4);
4080
+ __dirname5 = dirname5(__filename4);
4049
4081
  AGENTS_DIR_PROD = resolve4(__dirname5, "agents");
4050
4082
  AGENTS_DIR_DEV_FALLBACK = resolve4(__dirname5, "../../../agent_moss/agents");
4051
4083
  cache = /* @__PURE__ */ new Map();
@@ -4055,7 +4087,7 @@ var init_agents = __esm({
4055
4087
 
4056
4088
  // src/scenarios/index.ts
4057
4089
  import { readFileSync as readFileSync6, existsSync as existsSync7 } from "fs";
4058
- import { resolve as resolve5, dirname as dirname5, join as join7 } from "path";
4090
+ import { resolve as resolve5, dirname as dirname6, join as join7 } from "path";
4059
4091
  import { fileURLToPath as fileURLToPath7 } from "url";
4060
4092
  function resolveScenariosDir() {
4061
4093
  const root = getRulesRoot();
@@ -4151,7 +4183,7 @@ var init_scenarios = __esm({
4151
4183
  init_runtime_config();
4152
4184
  init_rules_loader();
4153
4185
  __filename5 = fileURLToPath7(import.meta.url);
4154
- __dirname6 = dirname5(__filename5);
4186
+ __dirname6 = dirname6(__filename5);
4155
4187
  SCENARIOS_DIR_PROD = resolve5(__dirname6, "scenarios");
4156
4188
  SCENARIOS_DIR_DEV_FALLBACK = resolve5(__dirname6, "../../../agent_moss/scenarios");
4157
4189
  cache2 = /* @__PURE__ */ new Map();
@@ -5142,7 +5174,8 @@ function checkDangerousPatterns(actionType, actionDetail) {
5142
5174
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
5143
5175
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
5144
5176
  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;
5145
- if (!isTempPath && wildcardDeleteRe.test(scan)) {
5177
+ const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
5178
+ if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
5146
5179
  return {
5147
5180
  allowed: false,
5148
5181
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -5567,7 +5600,7 @@ init_esm_shims();
5567
5600
  init_paths();
5568
5601
  import { chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as existsSync8, lstatSync, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync7, readSync as readSync2, realpathSync, writeSync } from "fs";
5569
5602
  import { homedir as homedir3, tmpdir } from "os";
5570
- import { basename, isAbsolute as isAbsolute2, join as join8, relative, resolve as resolve6, dirname as dirname6 } from "path";
5603
+ import { basename as basename2, isAbsolute as isAbsolute2, join as join8, relative, resolve as resolve6, dirname as dirname7 } from "path";
5571
5604
  var TRUTHY2 = ["1", "true", "yes", "on"];
5572
5605
  function env(name, dflt = "") {
5573
5606
  return (process.env[name] ?? dflt).trim();
@@ -5603,9 +5636,9 @@ function realpathLoose(p) {
5603
5636
  const parts = [];
5604
5637
  let cur = abs;
5605
5638
  for (; ; ) {
5606
- const parent = dirname6(cur);
5639
+ const parent = dirname7(cur);
5607
5640
  if (parent === cur) return null;
5608
- parts.unshift(basename(cur));
5641
+ parts.unshift(basename2(cur));
5609
5642
  cur = parent;
5610
5643
  try {
5611
5644
  return join8(realpathSync(cur), ...parts);
@@ -5671,10 +5704,10 @@ init_skill_loader();
5671
5704
  init_esm_shims();
5672
5705
  init_asset_dir();
5673
5706
  import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
5674
- import { resolve as resolve7, dirname as dirname7 } from "path";
5707
+ import { resolve as resolve7, dirname as dirname8 } from "path";
5675
5708
  import { fileURLToPath as fileURLToPath8 } from "url";
5676
5709
  var __filename6 = fileURLToPath8(import.meta.url);
5677
- var __dirname7 = dirname7(__filename6);
5710
+ var __dirname7 = dirname8(__filename6);
5678
5711
  var TEMPLATE_FILES = ["prompt1_template.txt", "prompt2_template.txt", "security_judge_template.txt"];
5679
5712
  var cachedTemplates = null;
5680
5713
  function loadTemplates() {
@@ -6790,7 +6823,7 @@ function evalCondition2(cond, env2) {
6790
6823
  if (lv2 === null || rv2 === null) return null;
6791
6824
  return evalNumericCompare(op2, lv2, rv2);
6792
6825
  }
6793
- const sm = innerQ.match(/(.*?)\s*(==|=|!=|=~)\s*(.*)/);
6826
+ const sm = innerQ.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
6794
6827
  if (!sm) return null;
6795
6828
  const op = sm[2];
6796
6829
  let left = sm[1].trim();
@@ -6808,8 +6841,8 @@ function evalCondition2(cond, env2) {
6808
6841
  const lv = resolveVarSide(left, env2);
6809
6842
  const rv = resolveVarSide(right, env2);
6810
6843
  if (lv === null || rv === null) return null;
6811
- if (op === "!=") return lv !== rv;
6812
- return lv === rv;
6844
+ const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
6845
+ return op === "!=" ? !matched : matched;
6813
6846
  }
6814
6847
  function symbolicProcess(content, entryArgs) {
6815
6848
  if (!content) return null;
@@ -6817,6 +6850,7 @@ function symbolicProcess(content, entryArgs) {
6817
6850
  if (!stmts.some((s) => s.kind === "case" || s.kind === "if" || s.kind === "assign")) return null;
6818
6851
  if (stmts.some((s) => !s.modelable)) return null;
6819
6852
  const env2 = initEnv(entryArgs);
6853
+ if (env2.size > MAX_VARS) return null;
6820
6854
  let linesBudget = 0;
6821
6855
  let branchesBudget = 0;
6822
6856
  let modelable = false;
@@ -6826,7 +6860,7 @@ function symbolicProcess(content, entryArgs) {
6826
6860
  if (linesBudget > MAX_LINES2) return null;
6827
6861
  if (s.kind === "assign") {
6828
6862
  modelable = true;
6829
- if (env2.size >= MAX_VARS) return null;
6863
+ if (!env2.has(s.name) && env2.size >= MAX_VARS) return null;
6830
6864
  const v = evalExpr2(s.rhs, env2);
6831
6865
  env2.set(s.name, fold(v));
6832
6866
  out.push(s.line);
@@ -7028,24 +7062,34 @@ function splitNestedCaseBranches(bodyLines, selectorVal) {
7028
7062
  }
7029
7063
  function evalIfCondition(cond, args) {
7030
7064
  if (!args || !args.length) return null;
7031
- let inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
7032
- const m = inner.match(/(.*?)\s*(==|=)\s*(.*)/);
7065
+ const inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
7066
+ const m = inner.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
7033
7067
  if (!m) return null;
7068
+ const op = m[2];
7034
7069
  let left = m[1].trim();
7035
7070
  let right = m[3].trim();
7036
- const lm = left.match(/^\$(\d+)$/);
7037
- if (lm) {
7038
- const idx = parseInt(lm[1], 10);
7039
- if (1 <= idx && idx <= args.length) left = args[idx - 1];
7040
- else return null;
7041
- } else if (left.startsWith("$")) return null;
7042
- const rm = right.match(/^\$(\d+)$/);
7043
- if (rm) {
7044
- const idx = parseInt(rm[1], 10);
7045
- if (1 <= idx && idx <= args.length) right = args[idx - 1];
7046
- else return null;
7047
- } else if (right.startsWith("$")) return null;
7048
- return left === right;
7071
+ const resolve11 = (tok) => {
7072
+ const rm = tok.match(/^\$(\d+)$/);
7073
+ if (rm) {
7074
+ const idx = parseInt(rm[1], 10);
7075
+ return 1 <= idx && idx <= args.length ? args[idx - 1] : null;
7076
+ }
7077
+ return tok.startsWith("$") ? null : tok;
7078
+ };
7079
+ const lv = resolve11(left);
7080
+ const rv = resolve11(right);
7081
+ if (lv === null || rv === null) return null;
7082
+ if (op === "=~") {
7083
+ let re = rv;
7084
+ if (re.startsWith("/") && re.endsWith("/") && re.length > 1) re = re.slice(1, -1);
7085
+ try {
7086
+ return new RegExp(re).test(lv);
7087
+ } catch {
7088
+ return null;
7089
+ }
7090
+ }
7091
+ const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
7092
+ return op === "!=" ? !matched : matched;
7049
7093
  }
7050
7094
  function parseIf(content, args) {
7051
7095
  const m = content.match(/\bif\s+([^\n;]+?)\s*;\s*then/i);
@@ -7570,41 +7614,6 @@ function scanExtensionPatterns(ext, content) {
7570
7614
  }
7571
7615
  return null;
7572
7616
  }
7573
- function scanScriptChainWithL1(chain, input, ext) {
7574
- for (const node of chain.nodes) {
7575
- if (node.error || !node.preprocessedContent || node.l1Hit) continue;
7576
- const virtualInput = {
7577
- ...input,
7578
- aNext: { actionType: "bash", actionDetail: node.preprocessedContent }
7579
- };
7580
- const l1 = scanDangerousCommandPatterns("bash", node.preprocessedContent, input.osType);
7581
- const extHit = scanExtensionPatterns(ext, node.preprocessedContent);
7582
- if (extHit) {
7583
- node.l1Hit = true;
7584
- node.l1RiskLevel = extHit.riskLevel;
7585
- node.l1RiskType = extHit.riskType;
7586
- node.l1Reason = extHit.reason;
7587
- if (extHit.riskLevel === "critical") {
7588
- chain.hasCritical = true;
7589
- chain.firstHitNode = node;
7590
- break;
7591
- }
7592
- continue;
7593
- }
7594
- if (l1 && !l1.allowed) {
7595
- node.l1Hit = true;
7596
- node.l1RiskLevel = l1.riskLevel;
7597
- node.l1RiskType = l1.riskType;
7598
- node.l1Reason = l1.reason;
7599
- if (l1.riskLevel === "critical") {
7600
- chain.hasCritical = true;
7601
- chain.firstHitNode = node;
7602
- break;
7603
- }
7604
- }
7605
- }
7606
- return chain;
7607
- }
7608
7617
  function scanScriptChainWithL2(chain, input) {
7609
7618
  for (const node of chain.nodes) {
7610
7619
  if (node.error || !node.preprocessedContent) continue;
@@ -7670,6 +7679,16 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
7670
7679
  resolvedPath = join11(input.cwd || process.cwd(), resolvedPath);
7671
7680
  }
7672
7681
  const l1Adapter = (content) => {
7682
+ const extHit = scanExtensionPatterns(ext, content);
7683
+ if (extHit) {
7684
+ return {
7685
+ hit: true,
7686
+ riskLevel: extHit.riskLevel,
7687
+ riskType: extHit.riskType,
7688
+ reason: extHit.reason,
7689
+ matchedPatterns: []
7690
+ };
7691
+ }
7673
7692
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
7674
7693
  if (j && !j.allowed) {
7675
7694
  return {
@@ -7693,7 +7712,6 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
7693
7712
  );
7694
7713
  const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
7695
7714
  if (chain.nodes.length === 0) return chain;
7696
- scanScriptChainWithL1(chain, input, ext);
7697
7715
  scanScriptChainWithL2(chain, input);
7698
7716
  scanScriptChainKeywords(chain);
7699
7717
  return chain;
@@ -8095,8 +8113,8 @@ var Histogram = class {
8095
8113
  };
8096
8114
  var ANALYZE_TOTAL = new Counter(
8097
8115
  "agent_moss_analyze_total",
8098
- "Total analyze requests handled, by decision and risk level.",
8099
- ["decision", "risk_level"]
8116
+ "Total analyze requests handled, by decision, risk level and L3 outcome.",
8117
+ ["decision", "risk_level", "l3_outcome"]
8100
8118
  );
8101
8119
  var ANALYZE_DURATION = new Histogram(
8102
8120
  "agent_moss_analyze_duration_seconds",
@@ -8161,6 +8179,48 @@ var LLM_SHORT_CIRCUIT_TOTAL = new Counter(
8161
8179
  );
8162
8180
 
8163
8181
  // src/engine/llm-analyzer.ts
8182
+ var LLMCircuitOpenError = class extends Error {
8183
+ constructor(message) {
8184
+ super(message);
8185
+ this.name = "LLMCircuitOpenError";
8186
+ }
8187
+ };
8188
+ function reasoningTextFallback(raw) {
8189
+ if (typeof raw !== "string") return "";
8190
+ let text = raw.trim();
8191
+ if (text.startsWith("```")) {
8192
+ text = text.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "").trim();
8193
+ }
8194
+ if (!(text.startsWith("{") && text.endsWith("}"))) return "";
8195
+ let parsed;
8196
+ try {
8197
+ parsed = JSON.parse(text);
8198
+ } catch {
8199
+ return "";
8200
+ }
8201
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
8202
+ if ("allowed" in parsed || "decision" in parsed || "risk_level" in parsed) {
8203
+ return text;
8204
+ }
8205
+ }
8206
+ return "";
8207
+ }
8208
+ function reasoningFallbackWithField(message) {
8209
+ if (!message || typeof message !== "object") return { text: "", field: "" };
8210
+ for (const key of ["reasoning", "reasoning_content", "thinking"]) {
8211
+ const got = reasoningTextFallback(message[key]);
8212
+ if (got) return { text: got, field: key };
8213
+ }
8214
+ return { text: "", field: "" };
8215
+ }
8216
+ function describeContentState(raw) {
8217
+ if (raw === null) return "null";
8218
+ if (raw === void 0) return "undefined";
8219
+ const text = typeof raw === "string" ? raw : String(raw);
8220
+ if (text === "") return "empty_string";
8221
+ if (!text.trim()) return `whitespace_only(${text.length})`;
8222
+ return `non_empty(${text.length})`;
8223
+ }
8164
8224
  function responseFieldLengths(message) {
8165
8225
  if (!message || typeof message !== "object") return {};
8166
8226
  const out = {};
@@ -8420,6 +8480,7 @@ function formatHints(previous) {
8420
8480
  async function analyzeWithLLM(prompt, config) {
8421
8481
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
8422
8482
  const _llmStart = performance.now();
8483
+ let usedReasoningFallback = false;
8423
8484
  const _recordLlm = (result) => {
8424
8485
  try {
8425
8486
  LLM_CALLS_TOTAL.inc(1, { result });
@@ -8455,7 +8516,7 @@ async function analyzeWithLLM(prompt, config) {
8455
8516
  } catch {
8456
8517
  }
8457
8518
  _recordLlm("error");
8458
- throw new Error(
8519
+ throw new LLMCircuitOpenError(
8459
8520
  "LLM \u8C03\u7528\u5DF2\u7194\u65AD\uFF08\u8FDE\u7EED\u5931\u8D25\u8FC7\u591A\uFF09\uFF0C\u51B7\u5374\u671F\u5185\u4E0D\u518D\u53D1\u8D77\u8BF7\u6C42\uFF1B\u68C0\u67E5\u6A21\u578B\u670D\u52A1\u53EF\u7528\u6027\uFF0C\u6216\u8C03 AGENT_MOSS_LLM_CIRCUIT_COOLDOWN"
8460
8521
  );
8461
8522
  }
@@ -8477,10 +8538,21 @@ async function analyzeWithLLM(prompt, config) {
8477
8538
  ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
8478
8539
  });
8479
8540
  const message = response.choices[0]?.message;
8480
- const content = message?.content ?? "";
8541
+ let content = message?.content ?? "";
8481
8542
  const finishReason = response.choices[0]?.finish_reason;
8482
8543
  const fieldLengths = responseFieldLengths(message);
8483
8544
  const usage = response.usage;
8545
+ if (!content) {
8546
+ const { text: fallback, field } = reasoningFallbackWithField(message);
8547
+ if (fallback) {
8548
+ const origState = describeContentState(message?.content);
8549
+ console.warn(
8550
+ `[AgentMoss] LLM content \u4E3A\u7A7A\u4F46 ${field} \u542B\u5B8C\u6574\u5224\u5B9A JSON\uFF0C\u56DE\u9000\u4F7F\u7528\uFF08model=${config.model}\uFF0Clen=${fallback.length}\uFF0C\u539F\u59CB content=${origState}\uFF0Cfinish_reason=${finishReason}\uFF0Ctokens=${usage?.prompt_tokens ?? 0}/${usage?.completion_tokens ?? 0}\uFF09\u2014\u2014 \u672C\u6B21\u5224\u5B9A\u4ECD\u7136\u6709\u6548\uFF0C\u4F46\u8BF4\u660E\u6A21\u578B\u6CA1\u628A\u7B54\u6848\u5199\u8FDB content\uFF0C\u957F\u671F\u5E94\u901A\u8FC7 llm.extraBody \u5173\u601D\u8003\u6A21\u5F0F\u6839\u6CBB`
8551
+ );
8552
+ content = fallback;
8553
+ usedReasoningFallback = true;
8554
+ }
8555
+ }
8484
8556
  if (!content) {
8485
8557
  const detail = `model=${response.model || config.model} finish_reason=${finishReason} ` + (Object.keys(fieldLengths).length ? Object.entries(fieldLengths).map(([k, v]) => `${k}_len=${v}`).join(" ") : `all_empty message_keys=${message ? Object.keys(message).join(",") : "(none)"}`) + ` tokens=${usage?.prompt_tokens ?? "?"}/${usage?.completion_tokens ?? "?"}`;
8486
8558
  traceFull("l3.empty_response", {
@@ -8553,7 +8625,9 @@ async function analyzeWithLLM(prompt, config) {
8553
8625
  riskLevel: ["low", "medium", "high", "critical"].includes(riskLevel) ? riskLevel : "low",
8554
8626
  riskType: riskType || "",
8555
8627
  confidence: typeof parsed.confidence === "number" ? Math.min(100, Math.max(0, parsed.confidence)) : 70,
8556
- source: "llm",
8628
+ // 判定结果一样可用,但运维要能看出模型行为异常
8629
+ // (下游据此填 l3Outcome 与 degraded)。
8630
+ source: usedReasoningFallback ? "llm_reasoning_fallback" : "llm",
8557
8631
  violatedLayers: ["L3.1"]
8558
8632
  };
8559
8633
  } catch (err) {
@@ -9404,9 +9478,9 @@ var BrainCurator = class {
9404
9478
  // src/brain/contributor.ts
9405
9479
  init_esm_shims();
9406
9480
  init_asset_dir();
9407
- import { dirname as dirname10 } from "path";
9481
+ import { dirname as dirname11 } from "path";
9408
9482
  import { fileURLToPath as fileURLToPath9 } from "url";
9409
- var __dirname8 = dirname10(fileURLToPath9(import.meta.url));
9483
+ var __dirname8 = dirname11(fileURLToPath9(import.meta.url));
9410
9484
 
9411
9485
  // src/brain/index.ts
9412
9486
  function checkBrainRules(store, opts) {
@@ -11029,6 +11103,7 @@ async function runAnalysis(input) {
11029
11103
  pathContext
11030
11104
  });
11031
11105
  } catch (e) {
11106
+ const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
11032
11107
  const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
11033
11108
  if (getLLMFailMode2() === "fail_open") {
11034
11109
  console.warn(`[AgentMoss] LLM \u5206\u6790\u5931\u8D25\uFF0Cfail_open \u6A21\u5F0F\uFF1A\u5141\u8BB8\u6267\u884C\uFF08\u524D\u4E24\u5C42\u672A\u62E6\u622A\uFF09: ${e.message}`);
@@ -11038,7 +11113,7 @@ async function runAnalysis(input) {
11038
11113
  riskLevel: "low",
11039
11114
  riskType: "",
11040
11115
  confidence: 50,
11041
- source: "llm_failure_fallback",
11116
+ source: failSource,
11042
11117
  violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
11043
11118
  };
11044
11119
  }
@@ -11048,7 +11123,7 @@ async function runAnalysis(input) {
11048
11123
  riskLevel: "medium",
11049
11124
  riskType: "",
11050
11125
  confidence: 60,
11051
- source: "llm_failure_fallback",
11126
+ source: failSource,
11052
11127
  violatedLayers: ["L3.1"]
11053
11128
  };
11054
11129
  }