@kenhkl/agent-moss 0.17.30 → 0.17.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1622,6 +1622,22 @@ function historyCommandText(histDetailRaw) {
1622
1622
  }
1623
1623
  return histDetailRaw;
1624
1624
  }
1625
+ function isScriptGeneratedTarget(targetPath, writtenScripts, shellRuns) {
1626
+ const base = path2.basename(targetPath);
1627
+ if (base.length < 3) return false;
1628
+ const targetDir = path2.dirname(targetPath);
1629
+ if (!targetDir) return false;
1630
+ for (const script of writtenScripts) {
1631
+ if (path2.dirname(script.path) !== targetDir) continue;
1632
+ if (!script.detail.includes(base)) continue;
1633
+ const scriptName = path2.basename(script.path);
1634
+ if (!scriptName) continue;
1635
+ if (shellRuns.some((run) => run.index > script.index && run.command.includes(scriptName))) {
1636
+ return true;
1637
+ }
1638
+ }
1639
+ return false;
1640
+ }
1625
1641
  function parseHeadTailLimit(seg) {
1626
1642
  const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
1627
1643
  if (firstWord !== "head" && firstWord !== "tail") return null;
@@ -2141,7 +2157,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2141
2157
  const historyFullReadPaths = /* @__PURE__ */ new Set();
2142
2158
  const historyPartialRead = /* @__PURE__ */ new Map();
2143
2159
  const historyWrittenPaths = /* @__PURE__ */ new Set();
2144
- for (const action of actionHistory) {
2160
+ let historyWrittenScripts = [];
2161
+ const shellRunActions = [];
2162
+ for (let actionIndex = 0; actionIndex < actionHistory.length; actionIndex++) {
2163
+ const action = actionHistory[actionIndex];
2145
2164
  const histDetailRaw = action.actionDetail;
2146
2165
  const histType = action.actionType.toLowerCase();
2147
2166
  const traits = getPlatformTraits(osType);
@@ -2153,7 +2172,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2153
2172
  );
2154
2173
  for (const p of coverage.full) historyFullReadPaths.add(p);
2155
2174
  if (isFullOverwriteTool(histType, singleFileTools) && !APPEND_MODE_RE.test(histDetailRaw)) {
2156
- for (const p of declaredWritePaths(histDetailRaw, osType)) historyWrittenPaths.add(p);
2175
+ for (const p of declaredWritePaths(histDetailRaw, osType)) {
2176
+ historyWrittenPaths.add(p);
2177
+ if (SCRIPT_FILE_RE.test(p)) {
2178
+ historyWrittenScripts.push({ path: p, detail: histDetailRaw, index: actionIndex });
2179
+ }
2180
+ }
2181
+ }
2182
+ if (BASH_LIKE_ACTION_TYPES.includes(histType)) {
2183
+ shellRunActions.push({ index: actionIndex, command: historyCommandText(histDetailRaw) });
2157
2184
  }
2158
2185
  for (const [p, upto] of coverage.partial) {
2159
2186
  if (historyPartialRead.has(p)) {
@@ -2180,6 +2207,7 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2180
2207
  const normalizedWrittenPaths = new Set(
2181
2208
  [...historyWrittenPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2182
2209
  );
2210
+ historyWrittenScripts = historyWrittenScripts.map((s) => ({ ...s, path: normalizePathForCompare(s.path, cwd) })).filter((s) => s.path);
2183
2211
  const normalizedPartialReads = /* @__PURE__ */ new Map();
2184
2212
  for (const [p, upto] of historyPartialRead) {
2185
2213
  const np = normalizePathForCompare(p, cwd);
@@ -2209,6 +2237,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2209
2237
  )) {
2210
2238
  isFullRead = true;
2211
2239
  }
2240
+ if (!isFullRead && !isProtectedWritePath(path8) && isScriptGeneratedTarget(path8, historyWrittenScripts, shellRunActions)) {
2241
+ isFullRead = true;
2242
+ }
2212
2243
  let isPartialCovered = false;
2213
2244
  if (!isFullRead) {
2214
2245
  for (const [pp, upto] of normalizedPartialReads) {
@@ -2402,7 +2433,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2402
2433
  violatedLayers: ["L2.1"]
2403
2434
  };
2404
2435
  }
2405
- 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;
2436
+ 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;
2406
2437
  var init_logic_rules = __esm({
2407
2438
  "src/engine/logic-rules.ts"() {
2408
2439
  "use strict";
@@ -2468,6 +2499,7 @@ var init_logic_rules = __esm({
2468
2499
  PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
2469
2500
  APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
2470
2501
  APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
2502
+ SCRIPT_FILE_RE = /\.(?:py|pyw|sh|bash|zsh|js|mjs|cjs|ts|pl|rb|php|ps1|bat|cmd)$/i;
2471
2503
  SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
2472
2504
  SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
2473
2505
  SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
@@ -2572,7 +2604,7 @@ var init_asset_dir = __esm({
2572
2604
 
2573
2605
  // src/engine/skill-loader.ts
2574
2606
  import { readFileSync as readFileSync5, readdirSync as readdirSync3, existsSync as existsSync6 } from "fs";
2575
- import { resolve as resolve4, dirname as dirname3 } from "path";
2607
+ import { resolve as resolve4, dirname as dirname4 } from "path";
2576
2608
  import { fileURLToPath as fileURLToPath3 } from "url";
2577
2609
  function loadAllSkills() {
2578
2610
  if (cachedSkills) return cachedSkills;
@@ -2686,7 +2718,7 @@ var init_skill_loader = __esm({
2686
2718
  init_asset_dir();
2687
2719
  init_runtime_config_bridge();
2688
2720
  __filename3 = fileURLToPath3(import.meta.url);
2689
- __dirname3 = dirname3(__filename3);
2721
+ __dirname3 = dirname4(__filename3);
2690
2722
  SKILL_KEYWORD_MAP = (() => {
2691
2723
  const map = {};
2692
2724
  const cats = loadL3();
@@ -2769,7 +2801,7 @@ __export(runtime_config_exports, {
2769
2801
  import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
2770
2802
  import { join as join7 } from "path";
2771
2803
  import { fileURLToPath as fileURLToPath4 } from "url";
2772
- import { dirname as dirname4 } from "path";
2804
+ import { dirname as dirname5 } from "path";
2773
2805
  function runtimeDir() {
2774
2806
  return getRuntimeConfigDir();
2775
2807
  }
@@ -4124,7 +4156,7 @@ var init_runtime_config = __esm({
4124
4156
  init_rules_loader();
4125
4157
  init_runtime_config_bridge();
4126
4158
  init_rules_mode();
4127
- __dirname4 = dirname4(fileURLToPath4(import.meta.url));
4159
+ __dirname4 = dirname5(fileURLToPath4(import.meta.url));
4128
4160
  ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
4129
4161
  RUNTIME_CONFIG_DIR = runtimeDir();
4130
4162
  RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
@@ -4499,7 +4531,7 @@ var init_config = __esm({
4499
4531
 
4500
4532
  // src/agents/index.ts
4501
4533
  import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
4502
- import { resolve as resolve5, dirname as dirname5, join as join8 } from "path";
4534
+ import { resolve as resolve5, dirname as dirname6, join as join8 } from "path";
4503
4535
  import { fileURLToPath as fileURLToPath6 } from "url";
4504
4536
  function resolveAgentsDir() {
4505
4537
  const root = getRulesRoot();
@@ -4576,7 +4608,7 @@ var init_agents = __esm({
4576
4608
  init_paths();
4577
4609
  init_runtime_config();
4578
4610
  __filename4 = fileURLToPath6(import.meta.url);
4579
- __dirname5 = dirname5(__filename4);
4611
+ __dirname5 = dirname6(__filename4);
4580
4612
  AGENTS_DIR_PROD = resolve5(__dirname5, "agents");
4581
4613
  AGENTS_DIR_DEV_FALLBACK = resolve5(__dirname5, "../../../agent_moss/agents");
4582
4614
  cache = /* @__PURE__ */ new Map();
@@ -4586,7 +4618,7 @@ var init_agents = __esm({
4586
4618
 
4587
4619
  // src/scenarios/index.ts
4588
4620
  import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
4589
- import { resolve as resolve6, dirname as dirname6, join as join9 } from "path";
4621
+ import { resolve as resolve6, dirname as dirname7, join as join9 } from "path";
4590
4622
  import { fileURLToPath as fileURLToPath7 } from "url";
4591
4623
  function resolveScenariosDir() {
4592
4624
  const root = getRulesRoot();
@@ -4682,7 +4714,7 @@ var init_scenarios = __esm({
4682
4714
  init_runtime_config();
4683
4715
  init_rules_loader();
4684
4716
  __filename5 = fileURLToPath7(import.meta.url);
4685
- __dirname6 = dirname6(__filename5);
4717
+ __dirname6 = dirname7(__filename5);
4686
4718
  SCENARIOS_DIR_PROD = resolve6(__dirname6, "scenarios");
4687
4719
  SCENARIOS_DIR_DEV_FALLBACK = resolve6(__dirname6, "../../../agent_moss/scenarios");
4688
4720
  cache2 = /* @__PURE__ */ new Map();
@@ -5673,7 +5705,8 @@ function checkDangerousPatterns(actionType, actionDetail) {
5673
5705
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
5674
5706
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
5675
5707
  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;
5676
- if (!isTempPath && wildcardDeleteRe.test(scan)) {
5708
+ const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
5709
+ if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
5677
5710
  return {
5678
5711
  allowed: false,
5679
5712
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -5870,7 +5903,7 @@ var init_heuristic = __esm({
5870
5903
 
5871
5904
  // src/engine/template-loader.ts
5872
5905
  import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
5873
- import { resolve as resolve7, dirname as dirname7 } from "path";
5906
+ import { resolve as resolve7, dirname as dirname8 } from "path";
5874
5907
  import { fileURLToPath as fileURLToPath8 } from "url";
5875
5908
  function loadTemplates() {
5876
5909
  if (cachedTemplates) return cachedTemplates;
@@ -5898,7 +5931,7 @@ var init_template_loader = __esm({
5898
5931
  init_esm_shims();
5899
5932
  init_asset_dir();
5900
5933
  __filename6 = fileURLToPath8(import.meta.url);
5901
- __dirname7 = dirname7(__filename6);
5934
+ __dirname7 = dirname8(__filename6);
5902
5935
  TEMPLATE_FILES = ["prompt1_template.txt", "prompt2_template.txt", "security_judge_template.txt"];
5903
5936
  cachedTemplates = null;
5904
5937
  }
@@ -6968,7 +7001,7 @@ function evalCondition2(cond, env2) {
6968
7001
  if (lv2 === null || rv2 === null) return null;
6969
7002
  return evalNumericCompare(op2, lv2, rv2);
6970
7003
  }
6971
- const sm = innerQ.match(/(.*?)\s*(==|=|!=|=~)\s*(.*)/);
7004
+ const sm = innerQ.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
6972
7005
  if (!sm) return null;
6973
7006
  const op = sm[2];
6974
7007
  let left = sm[1].trim();
@@ -6986,8 +7019,8 @@ function evalCondition2(cond, env2) {
6986
7019
  const lv = resolveVarSide(left, env2);
6987
7020
  const rv = resolveVarSide(right, env2);
6988
7021
  if (lv === null || rv === null) return null;
6989
- if (op === "!=") return lv !== rv;
6990
- return lv === rv;
7022
+ const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
7023
+ return op === "!=" ? !matched : matched;
6991
7024
  }
6992
7025
  function symbolicProcess(content, entryArgs) {
6993
7026
  if (!content) return null;
@@ -6995,6 +7028,7 @@ function symbolicProcess(content, entryArgs) {
6995
7028
  if (!stmts.some((s) => s.kind === "case" || s.kind === "if" || s.kind === "assign")) return null;
6996
7029
  if (stmts.some((s) => !s.modelable)) return null;
6997
7030
  const env2 = initEnv(entryArgs);
7031
+ if (env2.size > MAX_VARS) return null;
6998
7032
  let linesBudget = 0;
6999
7033
  let branchesBudget = 0;
7000
7034
  let modelable = false;
@@ -7004,7 +7038,7 @@ function symbolicProcess(content, entryArgs) {
7004
7038
  if (linesBudget > MAX_LINES2) return null;
7005
7039
  if (s.kind === "assign") {
7006
7040
  modelable = true;
7007
- if (env2.size >= MAX_VARS) return null;
7041
+ if (!env2.has(s.name) && env2.size >= MAX_VARS) return null;
7008
7042
  const v = evalExpr2(s.rhs, env2);
7009
7043
  env2.set(s.name, fold(v));
7010
7044
  out.push(s.line);
@@ -7231,24 +7265,34 @@ function splitNestedCaseBranches(bodyLines, selectorVal) {
7231
7265
  }
7232
7266
  function evalIfCondition(cond, args) {
7233
7267
  if (!args || !args.length) return null;
7234
- let inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
7235
- const m = inner.match(/(.*?)\s*(==|=)\s*(.*)/);
7268
+ const inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
7269
+ const m = inner.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
7236
7270
  if (!m) return null;
7271
+ const op = m[2];
7237
7272
  let left = m[1].trim();
7238
7273
  let right = m[3].trim();
7239
- const lm = left.match(/^\$(\d+)$/);
7240
- if (lm) {
7241
- const idx = parseInt(lm[1], 10);
7242
- if (1 <= idx && idx <= args.length) left = args[idx - 1];
7243
- else return null;
7244
- } else if (left.startsWith("$")) return null;
7245
- const rm = right.match(/^\$(\d+)$/);
7246
- if (rm) {
7247
- const idx = parseInt(rm[1], 10);
7248
- if (1 <= idx && idx <= args.length) right = args[idx - 1];
7249
- else return null;
7250
- } else if (right.startsWith("$")) return null;
7251
- return left === right;
7274
+ const resolve12 = (tok) => {
7275
+ const rm = tok.match(/^\$(\d+)$/);
7276
+ if (rm) {
7277
+ const idx = parseInt(rm[1], 10);
7278
+ return 1 <= idx && idx <= args.length ? args[idx - 1] : null;
7279
+ }
7280
+ return tok.startsWith("$") ? null : tok;
7281
+ };
7282
+ const lv = resolve12(left);
7283
+ const rv = resolve12(right);
7284
+ if (lv === null || rv === null) return null;
7285
+ if (op === "=~") {
7286
+ let re = rv;
7287
+ if (re.startsWith("/") && re.endsWith("/") && re.length > 1) re = re.slice(1, -1);
7288
+ try {
7289
+ return new RegExp(re).test(lv);
7290
+ } catch {
7291
+ return null;
7292
+ }
7293
+ }
7294
+ const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
7295
+ return op === "!=" ? !matched : matched;
7252
7296
  }
7253
7297
  function parseIf(content, args) {
7254
7298
  const m = content.match(/\bif\s+([^\n;]+?)\s*;\s*then/i);
@@ -7789,41 +7833,6 @@ function scanExtensionPatterns(ext, content) {
7789
7833
  }
7790
7834
  return null;
7791
7835
  }
7792
- function scanScriptChainWithL1(chain, input, ext) {
7793
- for (const node of chain.nodes) {
7794
- if (node.error || !node.preprocessedContent || node.l1Hit) continue;
7795
- const virtualInput = {
7796
- ...input,
7797
- aNext: { actionType: "bash", actionDetail: node.preprocessedContent }
7798
- };
7799
- const l1 = scanDangerousCommandPatterns("bash", node.preprocessedContent, input.osType);
7800
- const extHit = scanExtensionPatterns(ext, node.preprocessedContent);
7801
- if (extHit) {
7802
- node.l1Hit = true;
7803
- node.l1RiskLevel = extHit.riskLevel;
7804
- node.l1RiskType = extHit.riskType;
7805
- node.l1Reason = extHit.reason;
7806
- if (extHit.riskLevel === "critical") {
7807
- chain.hasCritical = true;
7808
- chain.firstHitNode = node;
7809
- break;
7810
- }
7811
- continue;
7812
- }
7813
- if (l1 && !l1.allowed) {
7814
- node.l1Hit = true;
7815
- node.l1RiskLevel = l1.riskLevel;
7816
- node.l1RiskType = l1.riskType;
7817
- node.l1Reason = l1.reason;
7818
- if (l1.riskLevel === "critical") {
7819
- chain.hasCritical = true;
7820
- chain.firstHitNode = node;
7821
- break;
7822
- }
7823
- }
7824
- }
7825
- return chain;
7826
- }
7827
7836
  function scanScriptChainWithL2(chain, input) {
7828
7837
  for (const node of chain.nodes) {
7829
7838
  if (node.error || !node.preprocessedContent) continue;
@@ -7889,6 +7898,16 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
7889
7898
  resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
7890
7899
  }
7891
7900
  const l1Adapter = (content) => {
7901
+ const extHit = scanExtensionPatterns(ext, content);
7902
+ if (extHit) {
7903
+ return {
7904
+ hit: true,
7905
+ riskLevel: extHit.riskLevel,
7906
+ riskType: extHit.riskType,
7907
+ reason: extHit.reason,
7908
+ matchedPatterns: []
7909
+ };
7910
+ }
7892
7911
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
7893
7912
  if (j && !j.allowed) {
7894
7913
  return {
@@ -7912,7 +7931,6 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
7912
7931
  );
7913
7932
  const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
7914
7933
  if (chain.nodes.length === 0) return chain;
7915
- scanScriptChainWithL1(chain, input, ext);
7916
7934
  scanScriptChainWithL2(chain, input);
7917
7935
  scanScriptChainKeywords(chain);
7918
7936
  return chain;
@@ -8400,8 +8418,8 @@ var init_metrics = __esm({
8400
8418
  };
8401
8419
  ANALYZE_TOTAL = new Counter(
8402
8420
  "agent_moss_analyze_total",
8403
- "Total analyze requests handled, by decision and risk level.",
8404
- ["decision", "risk_level"]
8421
+ "Total analyze requests handled, by decision, risk level and L3 outcome.",
8422
+ ["decision", "risk_level", "l3_outcome"]
8405
8423
  );
8406
8424
  ANALYZE_DURATION = new Histogram(
8407
8425
  "agent_moss_analyze_duration_seconds",
@@ -8684,6 +8702,42 @@ var init_token_stats = __esm({
8684
8702
  import { createHash as createHash3 } from "crypto";
8685
8703
  import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
8686
8704
  import OpenAI from "openai";
8705
+ function reasoningTextFallback(raw) {
8706
+ if (typeof raw !== "string") return "";
8707
+ let text = raw.trim();
8708
+ if (text.startsWith("```")) {
8709
+ text = text.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "").trim();
8710
+ }
8711
+ if (!(text.startsWith("{") && text.endsWith("}"))) return "";
8712
+ let parsed;
8713
+ try {
8714
+ parsed = JSON.parse(text);
8715
+ } catch {
8716
+ return "";
8717
+ }
8718
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
8719
+ if ("allowed" in parsed || "decision" in parsed || "risk_level" in parsed) {
8720
+ return text;
8721
+ }
8722
+ }
8723
+ return "";
8724
+ }
8725
+ function reasoningFallbackWithField(message) {
8726
+ if (!message || typeof message !== "object") return { text: "", field: "" };
8727
+ for (const key of ["reasoning", "reasoning_content", "thinking"]) {
8728
+ const got = reasoningTextFallback(message[key]);
8729
+ if (got) return { text: got, field: key };
8730
+ }
8731
+ return { text: "", field: "" };
8732
+ }
8733
+ function describeContentState(raw) {
8734
+ if (raw === null) return "null";
8735
+ if (raw === void 0) return "undefined";
8736
+ const text = typeof raw === "string" ? raw : String(raw);
8737
+ if (text === "") return "empty_string";
8738
+ if (!text.trim()) return `whitespace_only(${text.length})`;
8739
+ return `non_empty(${text.length})`;
8740
+ }
8687
8741
  function responseFieldLengths(message) {
8688
8742
  if (!message || typeof message !== "object") return {};
8689
8743
  const out = {};
@@ -8941,6 +8995,7 @@ function formatHints(previous) {
8941
8995
  async function analyzeWithLLM(prompt, config) {
8942
8996
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
8943
8997
  const _llmStart = performance.now();
8998
+ let usedReasoningFallback = false;
8944
8999
  const _recordLlm = (result) => {
8945
9000
  try {
8946
9001
  LLM_CALLS_TOTAL.inc(1, { result });
@@ -8976,7 +9031,7 @@ async function analyzeWithLLM(prompt, config) {
8976
9031
  } catch {
8977
9032
  }
8978
9033
  _recordLlm("error");
8979
- throw new Error(
9034
+ throw new LLMCircuitOpenError(
8980
9035
  "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"
8981
9036
  );
8982
9037
  }
@@ -8998,10 +9053,21 @@ async function analyzeWithLLM(prompt, config) {
8998
9053
  ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
8999
9054
  });
9000
9055
  const message = response.choices[0]?.message;
9001
- const content = message?.content ?? "";
9056
+ let content = message?.content ?? "";
9002
9057
  const finishReason = response.choices[0]?.finish_reason;
9003
9058
  const fieldLengths = responseFieldLengths(message);
9004
9059
  const usage = response.usage;
9060
+ if (!content) {
9061
+ const { text: fallback, field } = reasoningFallbackWithField(message);
9062
+ if (fallback) {
9063
+ const origState = describeContentState(message?.content);
9064
+ console.warn(
9065
+ `[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`
9066
+ );
9067
+ content = fallback;
9068
+ usedReasoningFallback = true;
9069
+ }
9070
+ }
9005
9071
  if (!content) {
9006
9072
  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 ?? "?"}`;
9007
9073
  traceFull("l3.empty_response", {
@@ -9074,7 +9140,9 @@ async function analyzeWithLLM(prompt, config) {
9074
9140
  riskLevel: ["low", "medium", "high", "critical"].includes(riskLevel) ? riskLevel : "low",
9075
9141
  riskType: riskType || "",
9076
9142
  confidence: typeof parsed.confidence === "number" ? Math.min(100, Math.max(0, parsed.confidence)) : 70,
9077
- source: "llm",
9143
+ // 判定结果一样可用,但运维要能看出模型行为异常
9144
+ // (下游据此填 l3Outcome 与 degraded)。
9145
+ source: usedReasoningFallback ? "llm_reasoning_fallback" : "llm",
9078
9146
  violatedLayers: ["L3.1"]
9079
9147
  };
9080
9148
  } catch (err) {
@@ -9100,7 +9168,7 @@ async function analyzeWithLLM(prompt, config) {
9100
9168
  clearTimeout(totalTimeoutTimer);
9101
9169
  throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
9102
9170
  }
9103
- var llmCache, LLM_CACHE_MAX;
9171
+ var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
9104
9172
  var init_llm_analyzer = __esm({
9105
9173
  "src/engine/llm-analyzer.ts"() {
9106
9174
  "use strict";
@@ -9114,6 +9182,12 @@ var init_llm_analyzer = __esm({
9114
9182
  init_trace_log();
9115
9183
  init_metrics();
9116
9184
  init_circuit_breaker();
9185
+ LLMCircuitOpenError = class extends Error {
9186
+ constructor(message) {
9187
+ super(message);
9188
+ this.name = "LLMCircuitOpenError";
9189
+ }
9190
+ };
9117
9191
  llmCache = /* @__PURE__ */ new Map();
9118
9192
  LLM_CACHE_MAX = 200;
9119
9193
  }
@@ -9963,7 +10037,7 @@ var init_curator = __esm({
9963
10037
  });
9964
10038
 
9965
10039
  // src/brain/contributor.ts
9966
- import { dirname as dirname10 } from "path";
10040
+ import { dirname as dirname11 } from "path";
9967
10041
  import { fileURLToPath as fileURLToPath9 } from "url";
9968
10042
  var __dirname8;
9969
10043
  var init_contributor = __esm({
@@ -9973,7 +10047,7 @@ var init_contributor = __esm({
9973
10047
  init_rule_store();
9974
10048
  init_skill_manager();
9975
10049
  init_asset_dir();
9976
- __dirname8 = dirname10(fileURLToPath9(import.meta.url));
10050
+ __dirname8 = dirname11(fileURLToPath9(import.meta.url));
9977
10051
  }
9978
10052
  });
9979
10053
 
@@ -12501,6 +12575,7 @@ async function runAnalysis(input) {
12501
12575
  pathContext
12502
12576
  });
12503
12577
  } catch (e) {
12578
+ const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
12504
12579
  const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
12505
12580
  if (getLLMFailMode2() === "fail_open") {
12506
12581
  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}`);
@@ -12510,7 +12585,7 @@ async function runAnalysis(input) {
12510
12585
  riskLevel: "low",
12511
12586
  riskType: "",
12512
12587
  confidence: 50,
12513
- source: "llm_failure_fallback",
12588
+ source: failSource,
12514
12589
  violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
12515
12590
  };
12516
12591
  }
@@ -12520,7 +12595,7 @@ async function runAnalysis(input) {
12520
12595
  riskLevel: "medium",
12521
12596
  riskType: "",
12522
12597
  confidence: 60,
12523
- source: "llm_failure_fallback",
12598
+ source: failSource,
12524
12599
  violatedLayers: ["L3.1"]
12525
12600
  };
12526
12601
  }
@@ -12728,7 +12803,7 @@ import { cors } from "hono/cors";
12728
12803
  import { logger } from "hono/logger";
12729
12804
  import net from "net";
12730
12805
  import { existsSync as existsSync21, writeFileSync as writeFileSync6, renameSync as renameSync3, mkdirSync as mkdirSync8 } from "fs";
12731
- import { dirname as dirname14, join as join21 } from "path";
12806
+ import { dirname as dirname15, join as join21 } from "path";
12732
12807
 
12733
12808
  // src/routes.ts
12734
12809
  init_esm_shims();
@@ -12805,6 +12880,20 @@ var AnalyzeResponseSchema = z.object({
12805
12880
  violation_chain: z.array(z.array(z.union([z.string(), z.number()]).nullable())).default([]),
12806
12881
  // 本次判定的能力降级说明(2026-11):正常为空;链状态触顶时说明 L2.2 未覆盖
12807
12882
  degraded: z.array(z.string()).default([]),
12883
+ // 本次 L3(LLM 语义分析)的实际结局(2026-11,稳定枚举,对齐 Python):
12884
+ // 让调用方不读日志就能区分「L3 认真判过的 Allow」和「L3 挂了 fail_open 放的」。
12885
+ l3_outcome: z.enum([
12886
+ "ok",
12887
+ "reasoning_fallback",
12888
+ "not_reached",
12889
+ "skipped",
12890
+ "fail_open",
12891
+ "fail_closed",
12892
+ "failed_but_blocked",
12893
+ "circuit_open",
12894
+ ""
12895
+ // 未算出(极端异常路径)
12896
+ ]).default(""),
12808
12897
  // 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
12809
12898
  violation_graph: z.object({
12810
12899
  // 性质元信息(前端展示"违反了哪条性质")
@@ -12888,6 +12977,19 @@ import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
12888
12977
  import { tmpdir as tmpdir3 } from "os";
12889
12978
  import { join as join17, resolve as resolve11 } from "path";
12890
12979
 
12980
+ // src/engine/types.ts
12981
+ init_esm_shims();
12982
+ function deriveL3Outcome(j) {
12983
+ const src = (j.source || "").toLowerCase();
12984
+ if (src === "llm" || src === "llm_extracted") return "ok";
12985
+ if (src === "llm_reasoning_fallback") return "reasoning_fallback";
12986
+ if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
12987
+ if (src === "llm_circuit_open") return "circuit_open";
12988
+ if (src === "llm_failure_with_violation") return "failed_but_blocked";
12989
+ if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
12990
+ return "not_reached";
12991
+ }
12992
+
12891
12993
  // src/infra/policy-cache.ts
12892
12994
  init_esm_shims();
12893
12995
  init_security_policy();
@@ -13233,9 +13335,15 @@ function allowResult(policy, judgment) {
13233
13335
  violated_layers: judgment.violatedLayers || [],
13234
13336
  policy,
13235
13337
  violated_policy: "",
13236
- confidence: judgment.confidence
13338
+ confidence: judgment.confidence,
13339
+ // 判定成功算出时才推导(对齐 Python `_finalize`)
13340
+ ...judgment.source !== void 0 ? { l3_outcome: deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed ?? true }) } : {}
13237
13341
  };
13238
13342
  }
13343
+ function withL3(res, judgment) {
13344
+ res.l3_outcome = deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed });
13345
+ return res;
13346
+ }
13239
13347
  async function analyze(input) {
13240
13348
  const mossLog = new MossLogger(input.sessionId);
13241
13349
  try {
@@ -13262,7 +13370,7 @@ async function analyzeInner(input, mossLog) {
13262
13370
  const judgment = await runAnalysis(input);
13263
13371
  mossLog.endStep(
13264
13372
  "step1_security_judge",
13265
- `allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}`
13373
+ `allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}, l3_outcome=${deriveL3Outcome(judgment)}`
13266
13374
  );
13267
13375
  if (!judgment.allowed) {
13268
13376
  const denied = {
@@ -13278,7 +13386,7 @@ async function analyzeInner(input, mossLog) {
13278
13386
  violation_chain: judgment.violationChain ?? []
13279
13387
  };
13280
13388
  mossLog.logResult("Deny", denied.reason);
13281
- return denied;
13389
+ return withL3(denied, judgment);
13282
13390
  }
13283
13391
  const cache3 = getDefaultCache();
13284
13392
  mossLog.startStep("step2_cache_lookup");
@@ -13288,7 +13396,7 @@ async function analyzeInner(input, mossLog) {
13288
13396
  savePolicyToFile(input.sessionId, cached2);
13289
13397
  const res = allowResult(cached2, judgment);
13290
13398
  mossLog.logResult("Allow", res.reason, cached2);
13291
- return res;
13399
+ return withL3(res, judgment);
13292
13400
  }
13293
13401
  if (!isPolicyGenEnabled()) {
13294
13402
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0CPolicy \u751F\u6210\u5DF2\u7981\u7528");
@@ -13298,7 +13406,7 @@ async function analyzeInner(input, mossLog) {
13298
13406
  const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
13299
13407
  mossLog.endStep("step2_default_policy", "\u4F7F\u7528\u9ED8\u8BA4\u6700\u5C0F\u6743\u9650 Policy");
13300
13408
  mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
13301
- return res;
13409
+ return withL3(res, judgment);
13302
13410
  }
13303
13411
  if (judgment.source === "whitelist_bypass") {
13304
13412
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u767D\u540D\u5355\u5DE5\u5177");
@@ -13306,7 +13414,7 @@ async function analyzeInner(input, mossLog) {
13306
13414
  savePolicyToFile(input.sessionId, DEFAULT_READONLY_POLICY);
13307
13415
  const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
13308
13416
  mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
13309
- return res;
13417
+ return withL3(res, judgment);
13310
13418
  }
13311
13419
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u542F\u7528 LLM \u751F\u6210");
13312
13420
  mossLog.startStep("step2_generate_policy");
@@ -13317,7 +13425,7 @@ async function analyzeInner(input, mossLog) {
13317
13425
  mossLog.endStep("step2_generate_policy", "Policy \u751F\u6210\u5E76\u7F13\u5B58\u6210\u529F");
13318
13426
  const res = allowResult(policy, judgment);
13319
13427
  mossLog.logResult("Allow", res.reason, policy);
13320
- return res;
13428
+ return withL3(res, judgment);
13321
13429
  } catch (err) {
13322
13430
  mossLog.endStep("step2_generate_policy", `\u5931\u8D25: ${String(err)}`);
13323
13431
  mossLog.logError("step2_generate_policy", err);
@@ -13332,7 +13440,7 @@ async function analyzeInner(input, mossLog) {
13332
13440
  confidence: judgment.confidence
13333
13441
  };
13334
13442
  mossLog.logResult("Deny", failed.reason);
13335
- return failed;
13443
+ return withL3(failed, judgment);
13336
13444
  }
13337
13445
  }
13338
13446
 
@@ -13746,9 +13854,9 @@ function poolsSnapshot() {
13746
13854
 
13747
13855
  // src/routes.ts
13748
13856
  init_metrics();
13749
- import { join as join19, dirname as dirname12 } from "path";
13857
+ import { join as join19, dirname as dirname13 } from "path";
13750
13858
  import { fileURLToPath as fileURLToPath10 } from "url";
13751
- var __dirname9 = dirname12(fileURLToPath10(import.meta.url));
13859
+ var __dirname9 = dirname13(fileURLToPath10(import.meta.url));
13752
13860
  async function healthRoute(c) {
13753
13861
  const metrics = {};
13754
13862
  try {
@@ -13898,6 +14006,24 @@ async function analyzeRoute(c) {
13898
14006
  llmLogPath: req.metadata?.llm_log_path
13899
14007
  });
13900
14008
  const durationMs = performance.now() - t0;
14009
+ const _l3FailMsg = String(result.reason || "").slice(0, 160);
14010
+ if (result.l3_outcome === "reasoning_fallback") {
14011
+ degradedNotes.push(
14012
+ "\u3010\u63D0\u793A\u3011\u672C\u6B21 L3 \u5224\u5B9A\u53D6\u81EA\u6A21\u578B\u7684 reasoning \u5B57\u6BB5\uFF08content \u4E3A\u7A7A\uFF09\uFF1A**\u5224\u5B9A\u7ED3\u679C\u6709\u6548**\uFF0C\u4F46\u8BF4\u660E\u6A21\u578B\u6CA1\u628A\u7B54\u6848\u5199\u8FDB content\u3002\u9891\u7E41\u51FA\u73B0\u65F6\u8BF7\u5728 config \u7684 llm.extra_body \u914D\u7F6E\u5173\u601D\u8003\u53C2\u6570\u6839\u6CBB\u3002"
14013
+ );
14014
+ } else if (result.l3_outcome === "fail_open") {
14015
+ degradedNotes.push(
14016
+ `\u3010\u5DF2\u964D\u7EA7\u3011L3 \u8BED\u4E49\u5206\u6790\u672A\u5B8C\u6210\uFF08${_l3FailMsg}\uFF09\uFF0C\u672C\u6B21\u6309 fail_open \u653E\u884C\uFF1A**\u4EC5 L1/L2 \u751F\u6548\uFF0C\u672A\u505A\u8BED\u4E49\u5C42\u68C0\u67E5**\u3002\u8C03\u7528\u65B9\u53EF\u636E\u6B64\u6536\u7D27\u4E1A\u52A1\u6743\u9650\u3002`
14017
+ );
14018
+ } else if (result.l3_outcome === "fail_closed") {
14019
+ degradedNotes.push(
14020
+ `\u3010\u5DF2\u964D\u7EA7\u3011L3 \u8BED\u4E49\u5206\u6790\u672A\u5B8C\u6210\uFF08${_l3FailMsg}\uFF09\uFF0C\u672C\u6B21\u6309 fail_closed \u62D2\u7EDD\uFF1A\u62E6\u622A\u539F\u56E0\u662F\u300C\u5206\u6790\u4E0D\u53EF\u7528\u300D\u800C\u975E\u300C\u786E\u8BA4\u6709\u98CE\u9669\u300D\u3002\u4FEE\u590D\u6A21\u578B\u670D\u52A1\u540E\u91CD\u8BD5\u53EF\u80FD\u653E\u884C\u3002`
14021
+ );
14022
+ } else if (result.l3_outcome === "circuit_open") {
14023
+ degradedNotes.push(
14024
+ `\u3010\u5DF2\u964D\u7EA7\u3011LLM \u7194\u65AD\u5668\u6253\u5F00\uFF0C\u672C\u6B21**\u672A\u53D1\u8D77 L3 \u8BF7\u6C42**\uFF08${_l3FailMsg}\uFF09\uFF1AL1/L2 \u6B63\u5E38\uFF0C\u8BED\u4E49\u5C42\u7F3A\u5931\u3002\u68C0\u67E5\u6A21\u578B\u670D\u52A1\u4E0E\u7F51\u7EDC\uFF0C\u51B7\u5374\u540E\u81EA\u52A8\u8BD5\u63A2\u6062\u590D\u3002`
14025
+ );
14026
+ }
13901
14027
  const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
13902
14028
  if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
13903
14029
  console.warn(
@@ -13905,7 +14031,11 @@ async function analyzeRoute(c) {
13905
14031
  );
13906
14032
  }
13907
14033
  try {
13908
- ANALYZE_TOTAL.inc(1, { decision: result.decision, risk_level: result.risk_level });
14034
+ ANALYZE_TOTAL.inc(1, {
14035
+ decision: result.decision,
14036
+ risk_level: result.risk_level,
14037
+ l3_outcome: result.l3_outcome || ""
14038
+ });
13909
14039
  ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
13910
14040
  for (const layer of result.violated_layers || []) {
13911
14041
  LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
@@ -13919,7 +14049,9 @@ async function analyzeRoute(c) {
13919
14049
  risk_type: result.risk_type,
13920
14050
  reason: result.reason,
13921
14051
  violated_layers: result.violated_layers,
13922
- duration_ms: Math.round(durationMs * 10) / 10
14052
+ duration_ms: Math.round(durationMs * 10) / 10,
14053
+ // 2026-11:L3 结局(区分「L3 判过」与「L3 挂了放的」)
14054
+ l3_outcome: result.l3_outcome || ""
13923
14055
  });
13924
14056
  try {
13925
14057
  reportEnforcementEvent({
@@ -14010,7 +14142,10 @@ async function analyzeRoute(c) {
14010
14142
  violation_chain: result.violation_chain ?? [],
14011
14143
  violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
14012
14144
  // 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
14013
- degraded: degradedNotes
14145
+ degraded: degradedNotes,
14146
+ // L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
14147
+ // 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
14148
+ l3_outcome: result.l3_outcome || ""
14014
14149
  })
14015
14150
  );
14016
14151
  } catch (err) {
@@ -14253,9 +14388,9 @@ init_rules_mode();
14253
14388
  import { Hono } from "hono";
14254
14389
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
14255
14390
  import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
14256
- import { join as join20, dirname as dirname13 } from "path";
14391
+ import { join as join20, dirname as dirname14 } from "path";
14257
14392
  import { fileURLToPath as fileURLToPath11 } from "url";
14258
- var __dirname10 = dirname13(fileURLToPath11(import.meta.url));
14393
+ var __dirname10 = dirname14(fileURLToPath11(import.meta.url));
14259
14394
  var STATIC_DIR = join20(__dirname10, "static");
14260
14395
  var CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
14261
14396
  function getConsoleToken() {
@@ -14495,7 +14630,7 @@ function createConsoleRouter() {
14495
14630
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
14496
14631
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
14497
14632
  }
14498
- const userPath = join20(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14633
+ const userPath = join20(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14499
14634
  const builtinDir = resolveAssetDir(__dirname10, "skills");
14500
14635
  const candidates = [
14501
14636
  ...isRuntimeConfigDisabled() ? [] : [userPath],
@@ -14927,7 +15062,7 @@ async function warmUpEngine() {
14927
15062
  function writePortFile(port) {
14928
15063
  try {
14929
15064
  const path8 = join21(getDataRoot(), "agent_moss_server.port.json");
14930
- mkdirSync8(dirname14(path8), { recursive: true });
15065
+ mkdirSync8(dirname15(path8), { recursive: true });
14931
15066
  const payload = JSON.stringify({
14932
15067
  port,
14933
15068
  pid: process.pid,
@@ -14978,8 +15113,8 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
14978
15113
  serve: async () => {
14979
15114
  failFastOnAuthError();
14980
15115
  const { mkdirSync: mkdirSync9, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
14981
- const { dirname: dirname15 } = await import("path");
14982
- const dir = dirname15(socketPath);
15116
+ const { dirname: dirname16 } = await import("path");
15117
+ const dir = dirname16(socketPath);
14983
15118
  if (dir) {
14984
15119
  try {
14985
15120
  mkdirSync9(dir, { recursive: true });