@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/cli.js CHANGED
@@ -1472,6 +1472,20 @@ var init_models = __esm({
1472
1472
  violation_chain: z.array(z.array(z.union([z.string(), z.number()]).nullable())).default([]),
1473
1473
  // 本次判定的能力降级说明(2026-11):正常为空;链状态触顶时说明 L2.2 未覆盖
1474
1474
  degraded: z.array(z.string()).default([]),
1475
+ // 本次 L3(LLM 语义分析)的实际结局(2026-11,稳定枚举,对齐 Python):
1476
+ // 让调用方不读日志就能区分「L3 认真判过的 Allow」和「L3 挂了 fail_open 放的」。
1477
+ l3_outcome: z.enum([
1478
+ "ok",
1479
+ "reasoning_fallback",
1480
+ "not_reached",
1481
+ "skipped",
1482
+ "fail_open",
1483
+ "fail_closed",
1484
+ "failed_but_blocked",
1485
+ "circuit_open",
1486
+ ""
1487
+ // 未算出(极端异常路径)
1488
+ ]).default(""),
1475
1489
  // 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
1476
1490
  violation_graph: z.object({
1477
1491
  // 性质元信息(前端展示"违反了哪条性质")
@@ -1932,6 +1946,22 @@ function historyCommandText(histDetailRaw) {
1932
1946
  }
1933
1947
  return histDetailRaw;
1934
1948
  }
1949
+ function isScriptGeneratedTarget(targetPath, writtenScripts, shellRuns) {
1950
+ const base = path2.basename(targetPath);
1951
+ if (base.length < 3) return false;
1952
+ const targetDir = path2.dirname(targetPath);
1953
+ if (!targetDir) return false;
1954
+ for (const script of writtenScripts) {
1955
+ if (path2.dirname(script.path) !== targetDir) continue;
1956
+ if (!script.detail.includes(base)) continue;
1957
+ const scriptName = path2.basename(script.path);
1958
+ if (!scriptName) continue;
1959
+ if (shellRuns.some((run) => run.index > script.index && run.command.includes(scriptName))) {
1960
+ return true;
1961
+ }
1962
+ }
1963
+ return false;
1964
+ }
1935
1965
  function parseHeadTailLimit(seg) {
1936
1966
  const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
1937
1967
  if (firstWord !== "head" && firstWord !== "tail") return null;
@@ -2451,7 +2481,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2451
2481
  const historyFullReadPaths = /* @__PURE__ */ new Set();
2452
2482
  const historyPartialRead = /* @__PURE__ */ new Map();
2453
2483
  const historyWrittenPaths = /* @__PURE__ */ new Set();
2454
- for (const action of actionHistory) {
2484
+ let historyWrittenScripts = [];
2485
+ const shellRunActions = [];
2486
+ for (let actionIndex = 0; actionIndex < actionHistory.length; actionIndex++) {
2487
+ const action = actionHistory[actionIndex];
2455
2488
  const histDetailRaw = action.actionDetail;
2456
2489
  const histType = action.actionType.toLowerCase();
2457
2490
  const traits = getPlatformTraits(osType);
@@ -2463,7 +2496,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2463
2496
  );
2464
2497
  for (const p of coverage.full) historyFullReadPaths.add(p);
2465
2498
  if (isFullOverwriteTool(histType, singleFileTools) && !APPEND_MODE_RE.test(histDetailRaw)) {
2466
- for (const p of declaredWritePaths(histDetailRaw, osType)) historyWrittenPaths.add(p);
2499
+ for (const p of declaredWritePaths(histDetailRaw, osType)) {
2500
+ historyWrittenPaths.add(p);
2501
+ if (SCRIPT_FILE_RE.test(p)) {
2502
+ historyWrittenScripts.push({ path: p, detail: histDetailRaw, index: actionIndex });
2503
+ }
2504
+ }
2505
+ }
2506
+ if (BASH_LIKE_ACTION_TYPES.includes(histType)) {
2507
+ shellRunActions.push({ index: actionIndex, command: historyCommandText(histDetailRaw) });
2467
2508
  }
2468
2509
  for (const [p, upto] of coverage.partial) {
2469
2510
  if (historyPartialRead.has(p)) {
@@ -2490,6 +2531,7 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2490
2531
  const normalizedWrittenPaths = new Set(
2491
2532
  [...historyWrittenPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2492
2533
  );
2534
+ historyWrittenScripts = historyWrittenScripts.map((s) => ({ ...s, path: normalizePathForCompare(s.path, cwd) })).filter((s) => s.path);
2493
2535
  const normalizedPartialReads = /* @__PURE__ */ new Map();
2494
2536
  for (const [p, upto] of historyPartialRead) {
2495
2537
  const np = normalizePathForCompare(p, cwd);
@@ -2519,6 +2561,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2519
2561
  )) {
2520
2562
  isFullRead = true;
2521
2563
  }
2564
+ if (!isFullRead && !isProtectedWritePath(path8) && isScriptGeneratedTarget(path8, historyWrittenScripts, shellRunActions)) {
2565
+ isFullRead = true;
2566
+ }
2522
2567
  let isPartialCovered = false;
2523
2568
  if (!isFullRead) {
2524
2569
  for (const [pp, upto] of normalizedPartialReads) {
@@ -2712,7 +2757,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2712
2757
  violatedLayers: ["L2.1"]
2713
2758
  };
2714
2759
  }
2715
- 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;
2760
+ 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;
2716
2761
  var init_logic_rules = __esm({
2717
2762
  "src/engine/logic-rules.ts"() {
2718
2763
  "use strict";
@@ -2778,6 +2823,7 @@ var init_logic_rules = __esm({
2778
2823
  PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
2779
2824
  APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
2780
2825
  APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
2826
+ SCRIPT_FILE_RE = /\.(?:py|pyw|sh|bash|zsh|js|mjs|cjs|ts|pl|rb|php|ps1|bat|cmd)$/i;
2781
2827
  SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
2782
2828
  SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
2783
2829
  SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
@@ -2882,7 +2928,7 @@ var init_asset_dir = __esm({
2882
2928
 
2883
2929
  // src/engine/skill-loader.ts
2884
2930
  import { readFileSync as readFileSync5, readdirSync as readdirSync3, existsSync as existsSync6 } from "fs";
2885
- import { resolve as resolve4, dirname as dirname3 } from "path";
2931
+ import { resolve as resolve4, dirname as dirname4 } from "path";
2886
2932
  import { fileURLToPath as fileURLToPath3 } from "url";
2887
2933
  function loadAllSkills() {
2888
2934
  if (cachedSkills) return cachedSkills;
@@ -2996,7 +3042,7 @@ var init_skill_loader = __esm({
2996
3042
  init_asset_dir();
2997
3043
  init_runtime_config_bridge();
2998
3044
  __filename3 = fileURLToPath3(import.meta.url);
2999
- __dirname3 = dirname3(__filename3);
3045
+ __dirname3 = dirname4(__filename3);
3000
3046
  SKILL_KEYWORD_MAP = (() => {
3001
3047
  const map = {};
3002
3048
  const cats = loadL3();
@@ -3079,7 +3125,7 @@ __export(runtime_config_exports, {
3079
3125
  import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
3080
3126
  import { join as join7 } from "path";
3081
3127
  import { fileURLToPath as fileURLToPath4 } from "url";
3082
- import { dirname as dirname4 } from "path";
3128
+ import { dirname as dirname5 } from "path";
3083
3129
  function runtimeDir() {
3084
3130
  return getRuntimeConfigDir();
3085
3131
  }
@@ -4434,7 +4480,7 @@ var init_runtime_config = __esm({
4434
4480
  init_rules_loader();
4435
4481
  init_runtime_config_bridge();
4436
4482
  init_rules_mode();
4437
- __dirname4 = dirname4(fileURLToPath4(import.meta.url));
4483
+ __dirname4 = dirname5(fileURLToPath4(import.meta.url));
4438
4484
  ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
4439
4485
  RUNTIME_CONFIG_DIR = runtimeDir();
4440
4486
  RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
@@ -4809,7 +4855,7 @@ var init_config = __esm({
4809
4855
 
4810
4856
  // src/agents/index.ts
4811
4857
  import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
4812
- import { resolve as resolve5, dirname as dirname5, join as join8 } from "path";
4858
+ import { resolve as resolve5, dirname as dirname6, join as join8 } from "path";
4813
4859
  import { fileURLToPath as fileURLToPath6 } from "url";
4814
4860
  function resolveAgentsDir() {
4815
4861
  const root = getRulesRoot();
@@ -4886,7 +4932,7 @@ var init_agents = __esm({
4886
4932
  init_paths();
4887
4933
  init_runtime_config();
4888
4934
  __filename4 = fileURLToPath6(import.meta.url);
4889
- __dirname5 = dirname5(__filename4);
4935
+ __dirname5 = dirname6(__filename4);
4890
4936
  AGENTS_DIR_PROD = resolve5(__dirname5, "agents");
4891
4937
  AGENTS_DIR_DEV_FALLBACK = resolve5(__dirname5, "../../../agent_moss/agents");
4892
4938
  cache = /* @__PURE__ */ new Map();
@@ -4896,7 +4942,7 @@ var init_agents = __esm({
4896
4942
 
4897
4943
  // src/scenarios/index.ts
4898
4944
  import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
4899
- import { resolve as resolve6, dirname as dirname6, join as join9 } from "path";
4945
+ import { resolve as resolve6, dirname as dirname7, join as join9 } from "path";
4900
4946
  import { fileURLToPath as fileURLToPath7 } from "url";
4901
4947
  function resolveScenariosDir() {
4902
4948
  const root = getRulesRoot();
@@ -4992,7 +5038,7 @@ var init_scenarios = __esm({
4992
5038
  init_runtime_config();
4993
5039
  init_rules_loader();
4994
5040
  __filename5 = fileURLToPath7(import.meta.url);
4995
- __dirname6 = dirname6(__filename5);
5041
+ __dirname6 = dirname7(__filename5);
4996
5042
  SCENARIOS_DIR_PROD = resolve6(__dirname6, "scenarios");
4997
5043
  SCENARIOS_DIR_DEV_FALLBACK = resolve6(__dirname6, "../../../agent_moss/scenarios");
4998
5044
  cache2 = /* @__PURE__ */ new Map();
@@ -5983,7 +6029,8 @@ function checkDangerousPatterns(actionType, actionDetail) {
5983
6029
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
5984
6030
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
5985
6031
  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;
5986
- if (!isTempPath && wildcardDeleteRe.test(scan)) {
6032
+ const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
6033
+ if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
5987
6034
  return {
5988
6035
  allowed: false,
5989
6036
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -6180,7 +6227,7 @@ var init_heuristic = __esm({
6180
6227
 
6181
6228
  // src/engine/template-loader.ts
6182
6229
  import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
6183
- import { resolve as resolve7, dirname as dirname7 } from "path";
6230
+ import { resolve as resolve7, dirname as dirname8 } from "path";
6184
6231
  import { fileURLToPath as fileURLToPath8 } from "url";
6185
6232
  function loadTemplates() {
6186
6233
  if (cachedTemplates) return cachedTemplates;
@@ -6208,7 +6255,7 @@ var init_template_loader = __esm({
6208
6255
  init_esm_shims();
6209
6256
  init_asset_dir();
6210
6257
  __filename6 = fileURLToPath8(import.meta.url);
6211
- __dirname7 = dirname7(__filename6);
6258
+ __dirname7 = dirname8(__filename6);
6212
6259
  TEMPLATE_FILES = ["prompt1_template.txt", "prompt2_template.txt", "security_judge_template.txt"];
6213
6260
  cachedTemplates = null;
6214
6261
  }
@@ -7278,7 +7325,7 @@ function evalCondition2(cond, env2) {
7278
7325
  if (lv2 === null || rv2 === null) return null;
7279
7326
  return evalNumericCompare(op2, lv2, rv2);
7280
7327
  }
7281
- const sm = innerQ.match(/(.*?)\s*(==|=|!=|=~)\s*(.*)/);
7328
+ const sm = innerQ.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
7282
7329
  if (!sm) return null;
7283
7330
  const op = sm[2];
7284
7331
  let left = sm[1].trim();
@@ -7296,8 +7343,8 @@ function evalCondition2(cond, env2) {
7296
7343
  const lv = resolveVarSide(left, env2);
7297
7344
  const rv = resolveVarSide(right, env2);
7298
7345
  if (lv === null || rv === null) return null;
7299
- if (op === "!=") return lv !== rv;
7300
- return lv === rv;
7346
+ const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
7347
+ return op === "!=" ? !matched : matched;
7301
7348
  }
7302
7349
  function symbolicProcess(content, entryArgs) {
7303
7350
  if (!content) return null;
@@ -7305,6 +7352,7 @@ function symbolicProcess(content, entryArgs) {
7305
7352
  if (!stmts.some((s) => s.kind === "case" || s.kind === "if" || s.kind === "assign")) return null;
7306
7353
  if (stmts.some((s) => !s.modelable)) return null;
7307
7354
  const env2 = initEnv(entryArgs);
7355
+ if (env2.size > MAX_VARS) return null;
7308
7356
  let linesBudget = 0;
7309
7357
  let branchesBudget = 0;
7310
7358
  let modelable = false;
@@ -7314,7 +7362,7 @@ function symbolicProcess(content, entryArgs) {
7314
7362
  if (linesBudget > MAX_LINES2) return null;
7315
7363
  if (s.kind === "assign") {
7316
7364
  modelable = true;
7317
- if (env2.size >= MAX_VARS) return null;
7365
+ if (!env2.has(s.name) && env2.size >= MAX_VARS) return null;
7318
7366
  const v = evalExpr2(s.rhs, env2);
7319
7367
  env2.set(s.name, fold(v));
7320
7368
  out.push(s.line);
@@ -7541,24 +7589,34 @@ function splitNestedCaseBranches(bodyLines, selectorVal) {
7541
7589
  }
7542
7590
  function evalIfCondition(cond, args) {
7543
7591
  if (!args || !args.length) return null;
7544
- let inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
7545
- const m = inner.match(/(.*?)\s*(==|=)\s*(.*)/);
7592
+ const inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
7593
+ const m = inner.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
7546
7594
  if (!m) return null;
7595
+ const op = m[2];
7547
7596
  let left = m[1].trim();
7548
7597
  let right = m[3].trim();
7549
- const lm = left.match(/^\$(\d+)$/);
7550
- if (lm) {
7551
- const idx = parseInt(lm[1], 10);
7552
- if (1 <= idx && idx <= args.length) left = args[idx - 1];
7553
- else return null;
7554
- } else if (left.startsWith("$")) return null;
7555
- const rm = right.match(/^\$(\d+)$/);
7556
- if (rm) {
7557
- const idx = parseInt(rm[1], 10);
7558
- if (1 <= idx && idx <= args.length) right = args[idx - 1];
7559
- else return null;
7560
- } else if (right.startsWith("$")) return null;
7561
- return left === right;
7598
+ const resolve12 = (tok) => {
7599
+ const rm = tok.match(/^\$(\d+)$/);
7600
+ if (rm) {
7601
+ const idx = parseInt(rm[1], 10);
7602
+ return 1 <= idx && idx <= args.length ? args[idx - 1] : null;
7603
+ }
7604
+ return tok.startsWith("$") ? null : tok;
7605
+ };
7606
+ const lv = resolve12(left);
7607
+ const rv = resolve12(right);
7608
+ if (lv === null || rv === null) return null;
7609
+ if (op === "=~") {
7610
+ let re = rv;
7611
+ if (re.startsWith("/") && re.endsWith("/") && re.length > 1) re = re.slice(1, -1);
7612
+ try {
7613
+ return new RegExp(re).test(lv);
7614
+ } catch {
7615
+ return null;
7616
+ }
7617
+ }
7618
+ const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
7619
+ return op === "!=" ? !matched : matched;
7562
7620
  }
7563
7621
  function parseIf(content, args) {
7564
7622
  const m = content.match(/\bif\s+([^\n;]+?)\s*;\s*then/i);
@@ -8099,41 +8157,6 @@ function scanExtensionPatterns(ext, content) {
8099
8157
  }
8100
8158
  return null;
8101
8159
  }
8102
- function scanScriptChainWithL1(chain, input, ext) {
8103
- for (const node of chain.nodes) {
8104
- if (node.error || !node.preprocessedContent || node.l1Hit) continue;
8105
- const virtualInput = {
8106
- ...input,
8107
- aNext: { actionType: "bash", actionDetail: node.preprocessedContent }
8108
- };
8109
- const l1 = scanDangerousCommandPatterns("bash", node.preprocessedContent, input.osType);
8110
- const extHit = scanExtensionPatterns(ext, node.preprocessedContent);
8111
- if (extHit) {
8112
- node.l1Hit = true;
8113
- node.l1RiskLevel = extHit.riskLevel;
8114
- node.l1RiskType = extHit.riskType;
8115
- node.l1Reason = extHit.reason;
8116
- if (extHit.riskLevel === "critical") {
8117
- chain.hasCritical = true;
8118
- chain.firstHitNode = node;
8119
- break;
8120
- }
8121
- continue;
8122
- }
8123
- if (l1 && !l1.allowed) {
8124
- node.l1Hit = true;
8125
- node.l1RiskLevel = l1.riskLevel;
8126
- node.l1RiskType = l1.riskType;
8127
- node.l1Reason = l1.reason;
8128
- if (l1.riskLevel === "critical") {
8129
- chain.hasCritical = true;
8130
- chain.firstHitNode = node;
8131
- break;
8132
- }
8133
- }
8134
- }
8135
- return chain;
8136
- }
8137
8160
  function scanScriptChainWithL2(chain, input) {
8138
8161
  for (const node of chain.nodes) {
8139
8162
  if (node.error || !node.preprocessedContent) continue;
@@ -8199,6 +8222,16 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
8199
8222
  resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
8200
8223
  }
8201
8224
  const l1Adapter = (content) => {
8225
+ const extHit = scanExtensionPatterns(ext, content);
8226
+ if (extHit) {
8227
+ return {
8228
+ hit: true,
8229
+ riskLevel: extHit.riskLevel,
8230
+ riskType: extHit.riskType,
8231
+ reason: extHit.reason,
8232
+ matchedPatterns: []
8233
+ };
8234
+ }
8202
8235
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
8203
8236
  if (j && !j.allowed) {
8204
8237
  return {
@@ -8222,7 +8255,6 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
8222
8255
  );
8223
8256
  const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
8224
8257
  if (chain.nodes.length === 0) return chain;
8225
- scanScriptChainWithL1(chain, input, ext);
8226
8258
  scanScriptChainWithL2(chain, input);
8227
8259
  scanScriptChainKeywords(chain);
8228
8260
  return chain;
@@ -8710,8 +8742,8 @@ var init_metrics = __esm({
8710
8742
  };
8711
8743
  ANALYZE_TOTAL = new Counter(
8712
8744
  "agent_moss_analyze_total",
8713
- "Total analyze requests handled, by decision and risk level.",
8714
- ["decision", "risk_level"]
8745
+ "Total analyze requests handled, by decision, risk level and L3 outcome.",
8746
+ ["decision", "risk_level", "l3_outcome"]
8715
8747
  );
8716
8748
  ANALYZE_DURATION = new Histogram(
8717
8749
  "agent_moss_analyze_duration_seconds",
@@ -8994,6 +9026,42 @@ var init_token_stats = __esm({
8994
9026
  import { createHash as createHash3 } from "crypto";
8995
9027
  import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
8996
9028
  import OpenAI from "openai";
9029
+ function reasoningTextFallback(raw) {
9030
+ if (typeof raw !== "string") return "";
9031
+ let text = raw.trim();
9032
+ if (text.startsWith("```")) {
9033
+ text = text.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "").trim();
9034
+ }
9035
+ if (!(text.startsWith("{") && text.endsWith("}"))) return "";
9036
+ let parsed;
9037
+ try {
9038
+ parsed = JSON.parse(text);
9039
+ } catch {
9040
+ return "";
9041
+ }
9042
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
9043
+ if ("allowed" in parsed || "decision" in parsed || "risk_level" in parsed) {
9044
+ return text;
9045
+ }
9046
+ }
9047
+ return "";
9048
+ }
9049
+ function reasoningFallbackWithField(message) {
9050
+ if (!message || typeof message !== "object") return { text: "", field: "" };
9051
+ for (const key of ["reasoning", "reasoning_content", "thinking"]) {
9052
+ const got = reasoningTextFallback(message[key]);
9053
+ if (got) return { text: got, field: key };
9054
+ }
9055
+ return { text: "", field: "" };
9056
+ }
9057
+ function describeContentState(raw) {
9058
+ if (raw === null) return "null";
9059
+ if (raw === void 0) return "undefined";
9060
+ const text = typeof raw === "string" ? raw : String(raw);
9061
+ if (text === "") return "empty_string";
9062
+ if (!text.trim()) return `whitespace_only(${text.length})`;
9063
+ return `non_empty(${text.length})`;
9064
+ }
8997
9065
  function responseFieldLengths(message) {
8998
9066
  if (!message || typeof message !== "object") return {};
8999
9067
  const out = {};
@@ -9251,6 +9319,7 @@ function formatHints(previous) {
9251
9319
  async function analyzeWithLLM(prompt, config) {
9252
9320
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
9253
9321
  const _llmStart = performance.now();
9322
+ let usedReasoningFallback = false;
9254
9323
  const _recordLlm = (result) => {
9255
9324
  try {
9256
9325
  LLM_CALLS_TOTAL.inc(1, { result });
@@ -9286,7 +9355,7 @@ async function analyzeWithLLM(prompt, config) {
9286
9355
  } catch {
9287
9356
  }
9288
9357
  _recordLlm("error");
9289
- throw new Error(
9358
+ throw new LLMCircuitOpenError(
9290
9359
  "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"
9291
9360
  );
9292
9361
  }
@@ -9308,10 +9377,21 @@ async function analyzeWithLLM(prompt, config) {
9308
9377
  ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
9309
9378
  });
9310
9379
  const message = response.choices[0]?.message;
9311
- const content = message?.content ?? "";
9380
+ let content = message?.content ?? "";
9312
9381
  const finishReason = response.choices[0]?.finish_reason;
9313
9382
  const fieldLengths = responseFieldLengths(message);
9314
9383
  const usage = response.usage;
9384
+ if (!content) {
9385
+ const { text: fallback, field } = reasoningFallbackWithField(message);
9386
+ if (fallback) {
9387
+ const origState = describeContentState(message?.content);
9388
+ console.warn(
9389
+ `[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`
9390
+ );
9391
+ content = fallback;
9392
+ usedReasoningFallback = true;
9393
+ }
9394
+ }
9315
9395
  if (!content) {
9316
9396
  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 ?? "?"}`;
9317
9397
  traceFull("l3.empty_response", {
@@ -9384,7 +9464,9 @@ async function analyzeWithLLM(prompt, config) {
9384
9464
  riskLevel: ["low", "medium", "high", "critical"].includes(riskLevel) ? riskLevel : "low",
9385
9465
  riskType: riskType || "",
9386
9466
  confidence: typeof parsed.confidence === "number" ? Math.min(100, Math.max(0, parsed.confidence)) : 70,
9387
- source: "llm",
9467
+ // 判定结果一样可用,但运维要能看出模型行为异常
9468
+ // (下游据此填 l3Outcome 与 degraded)。
9469
+ source: usedReasoningFallback ? "llm_reasoning_fallback" : "llm",
9388
9470
  violatedLayers: ["L3.1"]
9389
9471
  };
9390
9472
  } catch (err) {
@@ -9410,7 +9492,7 @@ async function analyzeWithLLM(prompt, config) {
9410
9492
  clearTimeout(totalTimeoutTimer);
9411
9493
  throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
9412
9494
  }
9413
- var llmCache, LLM_CACHE_MAX;
9495
+ var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
9414
9496
  var init_llm_analyzer = __esm({
9415
9497
  "src/engine/llm-analyzer.ts"() {
9416
9498
  "use strict";
@@ -9424,6 +9506,12 @@ var init_llm_analyzer = __esm({
9424
9506
  init_trace_log();
9425
9507
  init_metrics();
9426
9508
  init_circuit_breaker();
9509
+ LLMCircuitOpenError = class extends Error {
9510
+ constructor(message) {
9511
+ super(message);
9512
+ this.name = "LLMCircuitOpenError";
9513
+ }
9514
+ };
9427
9515
  llmCache = /* @__PURE__ */ new Map();
9428
9516
  LLM_CACHE_MAX = 200;
9429
9517
  }
@@ -10300,7 +10388,7 @@ import { mkdirSync as mkdirSync6, mkdtempSync, rmSync, writeFileSync as writeFil
10300
10388
  import { tmpdir as tmpdir2 } from "os";
10301
10389
  import { join as join15 } from "path";
10302
10390
  import { spawnSync } from "child_process";
10303
- import { dirname as dirname10 } from "path";
10391
+ import { dirname as dirname11 } from "path";
10304
10392
  import { fileURLToPath as fileURLToPath9 } from "url";
10305
10393
  function collectRules(store) {
10306
10394
  return store.getActiveRules().filter((r) => EXPORT_RULE_SOURCES.includes(r.source)).map((r) => ({
@@ -10541,7 +10629,7 @@ var init_contributor = __esm({
10541
10629
  init_rule_store();
10542
10630
  init_skill_manager();
10543
10631
  init_asset_dir();
10544
- __dirname8 = dirname10(fileURLToPath9(import.meta.url));
10632
+ __dirname8 = dirname11(fileURLToPath9(import.meta.url));
10545
10633
  DEFAULT_TARGET_REPO = "ssh://git@atomgit.com/kenhkl/AgentMoss.git";
10546
10634
  CONTACT_EMAIL = "kenhkl11@hotmail.com";
10547
10635
  TOKEN_ENV = "AGENT_MOSS_CONTRIBUTE_TOKEN";
@@ -13076,6 +13164,7 @@ async function runAnalysis(input) {
13076
13164
  pathContext
13077
13165
  });
13078
13166
  } catch (e) {
13167
+ const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
13079
13168
  const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
13080
13169
  if (getLLMFailMode2() === "fail_open") {
13081
13170
  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}`);
@@ -13085,7 +13174,7 @@ async function runAnalysis(input) {
13085
13174
  riskLevel: "low",
13086
13175
  riskType: "",
13087
13176
  confidence: 50,
13088
- source: "llm_failure_fallback",
13177
+ source: failSource,
13089
13178
  violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
13090
13179
  };
13091
13180
  }
@@ -13095,7 +13184,7 @@ async function runAnalysis(input) {
13095
13184
  riskLevel: "medium",
13096
13185
  riskType: "",
13097
13186
  confidence: 60,
13098
- source: "llm_failure_fallback",
13187
+ source: failSource,
13099
13188
  violatedLayers: ["L3.1"]
13100
13189
  };
13101
13190
  }
@@ -13154,6 +13243,24 @@ var init_coordinator = __esm({
13154
13243
  }
13155
13244
  });
13156
13245
 
13246
+ // src/engine/types.ts
13247
+ function deriveL3Outcome(j) {
13248
+ const src = (j.source || "").toLowerCase();
13249
+ if (src === "llm" || src === "llm_extracted") return "ok";
13250
+ if (src === "llm_reasoning_fallback") return "reasoning_fallback";
13251
+ if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
13252
+ if (src === "llm_circuit_open") return "circuit_open";
13253
+ if (src === "llm_failure_with_violation") return "failed_but_blocked";
13254
+ if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
13255
+ return "not_reached";
13256
+ }
13257
+ var init_types = __esm({
13258
+ "src/engine/types.ts"() {
13259
+ "use strict";
13260
+ init_esm_shims();
13261
+ }
13262
+ });
13263
+
13157
13264
  // src/infra/policy-cache.ts
13158
13265
  import { createHash as createHash5 } from "crypto";
13159
13266
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
@@ -13496,9 +13603,15 @@ function allowResult(policy, judgment) {
13496
13603
  violated_layers: judgment.violatedLayers || [],
13497
13604
  policy,
13498
13605
  violated_policy: "",
13499
- confidence: judgment.confidence
13606
+ confidence: judgment.confidence,
13607
+ // 判定成功算出时才推导(对齐 Python `_finalize`)
13608
+ ...judgment.source !== void 0 ? { l3_outcome: deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed ?? true }) } : {}
13500
13609
  };
13501
13610
  }
13611
+ function withL3(res, judgment) {
13612
+ res.l3_outcome = deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed });
13613
+ return res;
13614
+ }
13502
13615
  async function analyze(input) {
13503
13616
  const mossLog = new MossLogger(input.sessionId);
13504
13617
  try {
@@ -13525,7 +13638,7 @@ async function analyzeInner(input, mossLog) {
13525
13638
  const judgment = await runAnalysis(input);
13526
13639
  mossLog.endStep(
13527
13640
  "step1_security_judge",
13528
- `allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}`
13641
+ `allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}, l3_outcome=${deriveL3Outcome(judgment)}`
13529
13642
  );
13530
13643
  if (!judgment.allowed) {
13531
13644
  const denied = {
@@ -13541,7 +13654,7 @@ async function analyzeInner(input, mossLog) {
13541
13654
  violation_chain: judgment.violationChain ?? []
13542
13655
  };
13543
13656
  mossLog.logResult("Deny", denied.reason);
13544
- return denied;
13657
+ return withL3(denied, judgment);
13545
13658
  }
13546
13659
  const cache3 = getDefaultCache();
13547
13660
  mossLog.startStep("step2_cache_lookup");
@@ -13551,7 +13664,7 @@ async function analyzeInner(input, mossLog) {
13551
13664
  savePolicyToFile(input.sessionId, cached2);
13552
13665
  const res = allowResult(cached2, judgment);
13553
13666
  mossLog.logResult("Allow", res.reason, cached2);
13554
- return res;
13667
+ return withL3(res, judgment);
13555
13668
  }
13556
13669
  if (!isPolicyGenEnabled()) {
13557
13670
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0CPolicy \u751F\u6210\u5DF2\u7981\u7528");
@@ -13561,7 +13674,7 @@ async function analyzeInner(input, mossLog) {
13561
13674
  const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
13562
13675
  mossLog.endStep("step2_default_policy", "\u4F7F\u7528\u9ED8\u8BA4\u6700\u5C0F\u6743\u9650 Policy");
13563
13676
  mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
13564
- return res;
13677
+ return withL3(res, judgment);
13565
13678
  }
13566
13679
  if (judgment.source === "whitelist_bypass") {
13567
13680
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u767D\u540D\u5355\u5DE5\u5177");
@@ -13569,7 +13682,7 @@ async function analyzeInner(input, mossLog) {
13569
13682
  savePolicyToFile(input.sessionId, DEFAULT_READONLY_POLICY);
13570
13683
  const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
13571
13684
  mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
13572
- return res;
13685
+ return withL3(res, judgment);
13573
13686
  }
13574
13687
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u542F\u7528 LLM \u751F\u6210");
13575
13688
  mossLog.startStep("step2_generate_policy");
@@ -13580,7 +13693,7 @@ async function analyzeInner(input, mossLog) {
13580
13693
  mossLog.endStep("step2_generate_policy", "Policy \u751F\u6210\u5E76\u7F13\u5B58\u6210\u529F");
13581
13694
  const res = allowResult(policy, judgment);
13582
13695
  mossLog.logResult("Allow", res.reason, policy);
13583
- return res;
13696
+ return withL3(res, judgment);
13584
13697
  } catch (err) {
13585
13698
  mossLog.endStep("step2_generate_policy", `\u5931\u8D25: ${String(err)}`);
13586
13699
  mossLog.logError("step2_generate_policy", err);
@@ -13595,7 +13708,7 @@ async function analyzeInner(input, mossLog) {
13595
13708
  confidence: judgment.confidence
13596
13709
  };
13597
13710
  mossLog.logResult("Deny", failed.reason);
13598
- return failed;
13711
+ return withL3(failed, judgment);
13599
13712
  }
13600
13713
  }
13601
13714
  var POLICY_OUTPUT_DIR, policyOutputDirOverride, DEFAULT_READONLY_POLICY;
@@ -13605,6 +13718,7 @@ var init_analyzer = __esm({
13605
13718
  init_esm_shims();
13606
13719
  init_security_policy();
13607
13720
  init_coordinator();
13721
+ init_types();
13608
13722
  init_policy_cache();
13609
13723
  init_config();
13610
13724
  init_template_loader();
@@ -14081,7 +14195,7 @@ var init_runtime_stats = __esm({
14081
14195
 
14082
14196
  // src/routes.ts
14083
14197
  import { randomBytes as randomBytes2 } from "crypto";
14084
- import { join as join20, dirname as dirname12 } from "path";
14198
+ import { join as join20, dirname as dirname13 } from "path";
14085
14199
  import { fileURLToPath as fileURLToPath10 } from "url";
14086
14200
  async function healthRoute(c) {
14087
14201
  const metrics = {};
@@ -14232,6 +14346,24 @@ async function analyzeRoute(c) {
14232
14346
  llmLogPath: req.metadata?.llm_log_path
14233
14347
  });
14234
14348
  const durationMs = performance.now() - t0;
14349
+ const _l3FailMsg = String(result.reason || "").slice(0, 160);
14350
+ if (result.l3_outcome === "reasoning_fallback") {
14351
+ degradedNotes.push(
14352
+ "\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"
14353
+ );
14354
+ } else if (result.l3_outcome === "fail_open") {
14355
+ degradedNotes.push(
14356
+ `\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`
14357
+ );
14358
+ } else if (result.l3_outcome === "fail_closed") {
14359
+ degradedNotes.push(
14360
+ `\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`
14361
+ );
14362
+ } else if (result.l3_outcome === "circuit_open") {
14363
+ degradedNotes.push(
14364
+ `\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`
14365
+ );
14366
+ }
14235
14367
  const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
14236
14368
  if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
14237
14369
  console.warn(
@@ -14239,7 +14371,11 @@ async function analyzeRoute(c) {
14239
14371
  );
14240
14372
  }
14241
14373
  try {
14242
- ANALYZE_TOTAL.inc(1, { decision: result.decision, risk_level: result.risk_level });
14374
+ ANALYZE_TOTAL.inc(1, {
14375
+ decision: result.decision,
14376
+ risk_level: result.risk_level,
14377
+ l3_outcome: result.l3_outcome || ""
14378
+ });
14243
14379
  ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
14244
14380
  for (const layer of result.violated_layers || []) {
14245
14381
  LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
@@ -14253,7 +14389,9 @@ async function analyzeRoute(c) {
14253
14389
  risk_type: result.risk_type,
14254
14390
  reason: result.reason,
14255
14391
  violated_layers: result.violated_layers,
14256
- duration_ms: Math.round(durationMs * 10) / 10
14392
+ duration_ms: Math.round(durationMs * 10) / 10,
14393
+ // 2026-11:L3 结局(区分「L3 判过」与「L3 挂了放的」)
14394
+ l3_outcome: result.l3_outcome || ""
14257
14395
  });
14258
14396
  try {
14259
14397
  reportEnforcementEvent({
@@ -14344,7 +14482,10 @@ async function analyzeRoute(c) {
14344
14482
  violation_chain: result.violation_chain ?? [],
14345
14483
  violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
14346
14484
  // 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
14347
- degraded: degradedNotes
14485
+ degraded: degradedNotes,
14486
+ // L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
14487
+ // 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
14488
+ l3_outcome: result.l3_outcome || ""
14348
14489
  })
14349
14490
  );
14350
14491
  } catch (err) {
@@ -14594,7 +14735,7 @@ var init_routes = __esm({
14594
14735
  init_loop_monitor();
14595
14736
  init_runtime_stats();
14596
14737
  init_metrics();
14597
- __dirname9 = dirname12(fileURLToPath10(import.meta.url));
14738
+ __dirname9 = dirname13(fileURLToPath10(import.meta.url));
14598
14739
  }
14599
14740
  });
14600
14741
 
@@ -14602,7 +14743,7 @@ var init_routes = __esm({
14602
14743
  import { Hono } from "hono";
14603
14744
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
14604
14745
  import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
14605
- import { join as join21, dirname as dirname13 } from "path";
14746
+ import { join as join21, dirname as dirname14 } from "path";
14606
14747
  import { fileURLToPath as fileURLToPath11 } from "url";
14607
14748
  function getConsoleToken() {
14608
14749
  return process.env[CONSOLE_TOKEN_ENV] || "";
@@ -14841,7 +14982,7 @@ function createConsoleRouter() {
14841
14982
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
14842
14983
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
14843
14984
  }
14844
- const userPath = join21(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14985
+ const userPath = join21(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14845
14986
  const builtinDir = resolveAssetDir(__dirname10, "skills");
14846
14987
  const candidates = [
14847
14988
  ...isRuntimeConfigDisabled() ? [] : [userPath],
@@ -14982,7 +15123,7 @@ var init_router = __esm({
14982
15123
  init_rules_loader();
14983
15124
  init_asset_dir();
14984
15125
  init_rules_mode();
14985
- __dirname10 = dirname13(fileURLToPath11(import.meta.url));
15126
+ __dirname10 = dirname14(fileURLToPath11(import.meta.url));
14986
15127
  STATIC_DIR = join21(__dirname10, "static");
14987
15128
  CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
14988
15129
  }
@@ -15012,7 +15153,7 @@ import { cors } from "hono/cors";
15012
15153
  import { logger } from "hono/logger";
15013
15154
  import net from "net";
15014
15155
  import { existsSync as existsSync21, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync9 } from "fs";
15015
- import { dirname as dirname14, join as join22 } from "path";
15156
+ import { dirname as dirname15, join as join22 } from "path";
15016
15157
  function logDeploymentSelfCheck() {
15017
15158
  try {
15018
15159
  const mode = getRulesMode();
@@ -15256,7 +15397,7 @@ async function warmUpEngine() {
15256
15397
  function writePortFile(port) {
15257
15398
  try {
15258
15399
  const path8 = join22(getDataRoot(), "agent_moss_server.port.json");
15259
- mkdirSync9(dirname14(path8), { recursive: true });
15400
+ mkdirSync9(dirname15(path8), { recursive: true });
15260
15401
  const payload = JSON.stringify({
15261
15402
  port,
15262
15403
  pid: process.pid,
@@ -15307,8 +15448,8 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15307
15448
  serve: async () => {
15308
15449
  failFastOnAuthError();
15309
15450
  const { mkdirSync: mkdirSync11, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15310
- const { dirname: dirname16 } = await import("path");
15311
- const dir = dirname16(socketPath);
15451
+ const { dirname: dirname17 } = await import("path");
15452
+ const dir = dirname17(socketPath);
15312
15453
  if (dir) {
15313
15454
  try {
15314
15455
  mkdirSync11(dir, { recursive: true });
@@ -15445,7 +15586,7 @@ __export(rules_tools_exports, {
15445
15586
  templateSourceDir: () => templateSourceDir
15446
15587
  });
15447
15588
  import { existsSync as existsSync22, mkdirSync as mkdirSync10, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync8 } from "fs";
15448
- import { dirname as dirname15, join as join23 } from "path";
15589
+ import { dirname as dirname16, join as join23 } from "path";
15449
15590
  import { fileURLToPath as fileURLToPath12 } from "url";
15450
15591
  function initRulesDir(targetDir, opts = {}) {
15451
15592
  mkdirSync10(targetDir, { recursive: true });
@@ -15548,7 +15689,7 @@ var init_rules_tools = __esm({
15548
15689
  "use strict";
15549
15690
  init_esm_shims();
15550
15691
  init_rules_loader();
15551
- __dirname11 = dirname15(fileURLToPath12(import.meta.url));
15692
+ __dirname11 = dirname16(fileURLToPath12(import.meta.url));
15552
15693
  EXTRA_TEMPLATE = {
15553
15694
  _\u8BF4\u660E: [
15554
15695
  "\u8FFD\u52A0\u89C4\u5219\uFF1A\u5185\u7F6E\u89C4\u5219\u5168\u90E8\u4FDD\u7559\uFF0C\u4F60\u5199\u5728\u8FD9\u91CC\u7684\u89C4\u5219\u52A0\u5728\u5185\u7F6E\u4E4B\u540E\u4E00\u8D77\u5224\u5B9A\u3002",