@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.
package/dist/cli.js CHANGED
@@ -97,6 +97,13 @@ function getTokenStatsPath() {
97
97
  }
98
98
  return join(getDataRoot(), "agent_moss_token_stats.json");
99
99
  }
100
+ function getInstanceDir() {
101
+ const instance = getInstance();
102
+ return instance ? join(getDataRoot(), instance) : getDataRoot();
103
+ }
104
+ function getPortFilePath() {
105
+ return join(getInstanceDir(), "agent_moss_server.port.json");
106
+ }
100
107
  var ENV_DATA_ROOT, ENV_INSTANCE, DEFAULT_DATA_ROOT, ENV_RULES_ROOT, ID_MAX_LEN, ID_PATTERN;
101
108
  var init_paths = __esm({
102
109
  "src/infra/paths.ts"() {
@@ -1472,6 +1479,20 @@ var init_models = __esm({
1472
1479
  violation_chain: z.array(z.array(z.union([z.string(), z.number()]).nullable())).default([]),
1473
1480
  // 本次判定的能力降级说明(2026-11):正常为空;链状态触顶时说明 L2.2 未覆盖
1474
1481
  degraded: z.array(z.string()).default([]),
1482
+ // 本次 L3(LLM 语义分析)的实际结局(2026-11,稳定枚举,对齐 Python):
1483
+ // 让调用方不读日志就能区分「L3 认真判过的 Allow」和「L3 挂了 fail_open 放的」。
1484
+ l3_outcome: z.enum([
1485
+ "ok",
1486
+ "reasoning_fallback",
1487
+ "not_reached",
1488
+ "skipped",
1489
+ "fail_open",
1490
+ "fail_closed",
1491
+ "failed_but_blocked",
1492
+ "circuit_open",
1493
+ ""
1494
+ // 未算出(极端异常路径)
1495
+ ]).default(""),
1475
1496
  // 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
1476
1497
  violation_graph: z.object({
1477
1498
  // 性质元信息(前端展示"违反了哪条性质")
@@ -1932,6 +1953,22 @@ function historyCommandText(histDetailRaw) {
1932
1953
  }
1933
1954
  return histDetailRaw;
1934
1955
  }
1956
+ function isScriptGeneratedTarget(targetPath, writtenScripts, shellRuns) {
1957
+ const base = path2.basename(targetPath);
1958
+ if (base.length < 3) return false;
1959
+ const targetDir = path2.dirname(targetPath);
1960
+ if (!targetDir) return false;
1961
+ for (const script of writtenScripts) {
1962
+ if (path2.dirname(script.path) !== targetDir) continue;
1963
+ if (!script.detail.includes(base)) continue;
1964
+ const scriptName = path2.basename(script.path);
1965
+ if (!scriptName) continue;
1966
+ if (shellRuns.some((run) => run.index > script.index && run.command.includes(scriptName))) {
1967
+ return true;
1968
+ }
1969
+ }
1970
+ return false;
1971
+ }
1935
1972
  function parseHeadTailLimit(seg) {
1936
1973
  const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
1937
1974
  if (firstWord !== "head" && firstWord !== "tail") return null;
@@ -2451,7 +2488,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2451
2488
  const historyFullReadPaths = /* @__PURE__ */ new Set();
2452
2489
  const historyPartialRead = /* @__PURE__ */ new Map();
2453
2490
  const historyWrittenPaths = /* @__PURE__ */ new Set();
2454
- for (const action of actionHistory) {
2491
+ let historyWrittenScripts = [];
2492
+ const shellRunActions = [];
2493
+ for (let actionIndex = 0; actionIndex < actionHistory.length; actionIndex++) {
2494
+ const action = actionHistory[actionIndex];
2455
2495
  const histDetailRaw = action.actionDetail;
2456
2496
  const histType = action.actionType.toLowerCase();
2457
2497
  const traits = getPlatformTraits(osType);
@@ -2463,7 +2503,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2463
2503
  );
2464
2504
  for (const p of coverage.full) historyFullReadPaths.add(p);
2465
2505
  if (isFullOverwriteTool(histType, singleFileTools) && !APPEND_MODE_RE.test(histDetailRaw)) {
2466
- for (const p of declaredWritePaths(histDetailRaw, osType)) historyWrittenPaths.add(p);
2506
+ for (const p of declaredWritePaths(histDetailRaw, osType)) {
2507
+ historyWrittenPaths.add(p);
2508
+ if (SCRIPT_FILE_RE.test(p)) {
2509
+ historyWrittenScripts.push({ path: p, detail: histDetailRaw, index: actionIndex });
2510
+ }
2511
+ }
2512
+ }
2513
+ if (BASH_LIKE_ACTION_TYPES.includes(histType)) {
2514
+ shellRunActions.push({ index: actionIndex, command: historyCommandText(histDetailRaw) });
2467
2515
  }
2468
2516
  for (const [p, upto] of coverage.partial) {
2469
2517
  if (historyPartialRead.has(p)) {
@@ -2490,6 +2538,7 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2490
2538
  const normalizedWrittenPaths = new Set(
2491
2539
  [...historyWrittenPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2492
2540
  );
2541
+ historyWrittenScripts = historyWrittenScripts.map((s) => ({ ...s, path: normalizePathForCompare(s.path, cwd) })).filter((s) => s.path);
2493
2542
  const normalizedPartialReads = /* @__PURE__ */ new Map();
2494
2543
  for (const [p, upto] of historyPartialRead) {
2495
2544
  const np = normalizePathForCompare(p, cwd);
@@ -2519,6 +2568,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2519
2568
  )) {
2520
2569
  isFullRead = true;
2521
2570
  }
2571
+ if (!isFullRead && !isProtectedWritePath(path8) && isScriptGeneratedTarget(path8, historyWrittenScripts, shellRunActions)) {
2572
+ isFullRead = true;
2573
+ }
2522
2574
  let isPartialCovered = false;
2523
2575
  if (!isFullRead) {
2524
2576
  for (const [pp, upto] of normalizedPartialReads) {
@@ -2712,7 +2764,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2712
2764
  violatedLayers: ["L2.1"]
2713
2765
  };
2714
2766
  }
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;
2767
+ 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
2768
  var init_logic_rules = __esm({
2717
2769
  "src/engine/logic-rules.ts"() {
2718
2770
  "use strict";
@@ -2778,6 +2830,7 @@ var init_logic_rules = __esm({
2778
2830
  PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
2779
2831
  APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
2780
2832
  APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
2833
+ SCRIPT_FILE_RE = /\.(?:py|pyw|sh|bash|zsh|js|mjs|cjs|ts|pl|rb|php|ps1|bat|cmd)$/i;
2781
2834
  SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
2782
2835
  SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
2783
2836
  SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
@@ -2882,7 +2935,7 @@ var init_asset_dir = __esm({
2882
2935
 
2883
2936
  // src/engine/skill-loader.ts
2884
2937
  import { readFileSync as readFileSync5, readdirSync as readdirSync3, existsSync as existsSync6 } from "fs";
2885
- import { resolve as resolve4, dirname as dirname3 } from "path";
2938
+ import { resolve as resolve4, dirname as dirname4 } from "path";
2886
2939
  import { fileURLToPath as fileURLToPath3 } from "url";
2887
2940
  function loadAllSkills() {
2888
2941
  if (cachedSkills) return cachedSkills;
@@ -2996,7 +3049,7 @@ var init_skill_loader = __esm({
2996
3049
  init_asset_dir();
2997
3050
  init_runtime_config_bridge();
2998
3051
  __filename3 = fileURLToPath3(import.meta.url);
2999
- __dirname3 = dirname3(__filename3);
3052
+ __dirname3 = dirname4(__filename3);
3000
3053
  SKILL_KEYWORD_MAP = (() => {
3001
3054
  const map = {};
3002
3055
  const cats = loadL3();
@@ -3079,7 +3132,7 @@ __export(runtime_config_exports, {
3079
3132
  import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
3080
3133
  import { join as join7 } from "path";
3081
3134
  import { fileURLToPath as fileURLToPath4 } from "url";
3082
- import { dirname as dirname4 } from "path";
3135
+ import { dirname as dirname5 } from "path";
3083
3136
  function runtimeDir() {
3084
3137
  return getRuntimeConfigDir();
3085
3138
  }
@@ -4434,7 +4487,7 @@ var init_runtime_config = __esm({
4434
4487
  init_rules_loader();
4435
4488
  init_runtime_config_bridge();
4436
4489
  init_rules_mode();
4437
- __dirname4 = dirname4(fileURLToPath4(import.meta.url));
4490
+ __dirname4 = dirname5(fileURLToPath4(import.meta.url));
4438
4491
  ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
4439
4492
  RUNTIME_CONFIG_DIR = runtimeDir();
4440
4493
  RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
@@ -4809,7 +4862,7 @@ var init_config = __esm({
4809
4862
 
4810
4863
  // src/agents/index.ts
4811
4864
  import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
4812
- import { resolve as resolve5, dirname as dirname5, join as join8 } from "path";
4865
+ import { resolve as resolve5, dirname as dirname6, join as join8 } from "path";
4813
4866
  import { fileURLToPath as fileURLToPath6 } from "url";
4814
4867
  function resolveAgentsDir() {
4815
4868
  const root = getRulesRoot();
@@ -4886,7 +4939,7 @@ var init_agents = __esm({
4886
4939
  init_paths();
4887
4940
  init_runtime_config();
4888
4941
  __filename4 = fileURLToPath6(import.meta.url);
4889
- __dirname5 = dirname5(__filename4);
4942
+ __dirname5 = dirname6(__filename4);
4890
4943
  AGENTS_DIR_PROD = resolve5(__dirname5, "agents");
4891
4944
  AGENTS_DIR_DEV_FALLBACK = resolve5(__dirname5, "../../../agent_moss/agents");
4892
4945
  cache = /* @__PURE__ */ new Map();
@@ -4896,7 +4949,7 @@ var init_agents = __esm({
4896
4949
 
4897
4950
  // src/scenarios/index.ts
4898
4951
  import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
4899
- import { resolve as resolve6, dirname as dirname6, join as join9 } from "path";
4952
+ import { resolve as resolve6, dirname as dirname7, join as join9 } from "path";
4900
4953
  import { fileURLToPath as fileURLToPath7 } from "url";
4901
4954
  function resolveScenariosDir() {
4902
4955
  const root = getRulesRoot();
@@ -4992,7 +5045,7 @@ var init_scenarios = __esm({
4992
5045
  init_runtime_config();
4993
5046
  init_rules_loader();
4994
5047
  __filename5 = fileURLToPath7(import.meta.url);
4995
- __dirname6 = dirname6(__filename5);
5048
+ __dirname6 = dirname7(__filename5);
4996
5049
  SCENARIOS_DIR_PROD = resolve6(__dirname6, "scenarios");
4997
5050
  SCENARIOS_DIR_DEV_FALLBACK = resolve6(__dirname6, "../../../agent_moss/scenarios");
4998
5051
  cache2 = /* @__PURE__ */ new Map();
@@ -5983,7 +6036,8 @@ function checkDangerousPatterns(actionType, actionDetail) {
5983
6036
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
5984
6037
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
5985
6038
  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)) {
6039
+ const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
6040
+ if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
5987
6041
  return {
5988
6042
  allowed: false,
5989
6043
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -6180,7 +6234,7 @@ var init_heuristic = __esm({
6180
6234
 
6181
6235
  // src/engine/template-loader.ts
6182
6236
  import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
6183
- import { resolve as resolve7, dirname as dirname7 } from "path";
6237
+ import { resolve as resolve7, dirname as dirname8 } from "path";
6184
6238
  import { fileURLToPath as fileURLToPath8 } from "url";
6185
6239
  function loadTemplates() {
6186
6240
  if (cachedTemplates) return cachedTemplates;
@@ -6208,7 +6262,7 @@ var init_template_loader = __esm({
6208
6262
  init_esm_shims();
6209
6263
  init_asset_dir();
6210
6264
  __filename6 = fileURLToPath8(import.meta.url);
6211
- __dirname7 = dirname7(__filename6);
6265
+ __dirname7 = dirname8(__filename6);
6212
6266
  TEMPLATE_FILES = ["prompt1_template.txt", "prompt2_template.txt", "security_judge_template.txt"];
6213
6267
  cachedTemplates = null;
6214
6268
  }
@@ -7278,7 +7332,7 @@ function evalCondition2(cond, env2) {
7278
7332
  if (lv2 === null || rv2 === null) return null;
7279
7333
  return evalNumericCompare(op2, lv2, rv2);
7280
7334
  }
7281
- const sm = innerQ.match(/(.*?)\s*(==|=|!=|=~)\s*(.*)/);
7335
+ const sm = innerQ.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
7282
7336
  if (!sm) return null;
7283
7337
  const op = sm[2];
7284
7338
  let left = sm[1].trim();
@@ -7296,8 +7350,8 @@ function evalCondition2(cond, env2) {
7296
7350
  const lv = resolveVarSide(left, env2);
7297
7351
  const rv = resolveVarSide(right, env2);
7298
7352
  if (lv === null || rv === null) return null;
7299
- if (op === "!=") return lv !== rv;
7300
- return lv === rv;
7353
+ const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
7354
+ return op === "!=" ? !matched : matched;
7301
7355
  }
7302
7356
  function symbolicProcess(content, entryArgs) {
7303
7357
  if (!content) return null;
@@ -7305,6 +7359,7 @@ function symbolicProcess(content, entryArgs) {
7305
7359
  if (!stmts.some((s) => s.kind === "case" || s.kind === "if" || s.kind === "assign")) return null;
7306
7360
  if (stmts.some((s) => !s.modelable)) return null;
7307
7361
  const env2 = initEnv(entryArgs);
7362
+ if (env2.size > MAX_VARS) return null;
7308
7363
  let linesBudget = 0;
7309
7364
  let branchesBudget = 0;
7310
7365
  let modelable = false;
@@ -7314,7 +7369,7 @@ function symbolicProcess(content, entryArgs) {
7314
7369
  if (linesBudget > MAX_LINES2) return null;
7315
7370
  if (s.kind === "assign") {
7316
7371
  modelable = true;
7317
- if (env2.size >= MAX_VARS) return null;
7372
+ if (!env2.has(s.name) && env2.size >= MAX_VARS) return null;
7318
7373
  const v = evalExpr2(s.rhs, env2);
7319
7374
  env2.set(s.name, fold(v));
7320
7375
  out.push(s.line);
@@ -7541,24 +7596,34 @@ function splitNestedCaseBranches(bodyLines, selectorVal) {
7541
7596
  }
7542
7597
  function evalIfCondition(cond, args) {
7543
7598
  if (!args || !args.length) return null;
7544
- let inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
7545
- const m = inner.match(/(.*?)\s*(==|=)\s*(.*)/);
7599
+ const inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
7600
+ const m = inner.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
7546
7601
  if (!m) return null;
7602
+ const op = m[2];
7547
7603
  let left = m[1].trim();
7548
7604
  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;
7605
+ const resolve12 = (tok) => {
7606
+ const rm = tok.match(/^\$(\d+)$/);
7607
+ if (rm) {
7608
+ const idx = parseInt(rm[1], 10);
7609
+ return 1 <= idx && idx <= args.length ? args[idx - 1] : null;
7610
+ }
7611
+ return tok.startsWith("$") ? null : tok;
7612
+ };
7613
+ const lv = resolve12(left);
7614
+ const rv = resolve12(right);
7615
+ if (lv === null || rv === null) return null;
7616
+ if (op === "=~") {
7617
+ let re = rv;
7618
+ if (re.startsWith("/") && re.endsWith("/") && re.length > 1) re = re.slice(1, -1);
7619
+ try {
7620
+ return new RegExp(re).test(lv);
7621
+ } catch {
7622
+ return null;
7623
+ }
7624
+ }
7625
+ const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
7626
+ return op === "!=" ? !matched : matched;
7562
7627
  }
7563
7628
  function parseIf(content, args) {
7564
7629
  const m = content.match(/\bif\s+([^\n;]+?)\s*;\s*then/i);
@@ -8099,41 +8164,6 @@ function scanExtensionPatterns(ext, content) {
8099
8164
  }
8100
8165
  return null;
8101
8166
  }
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
8167
  function scanScriptChainWithL2(chain, input) {
8138
8168
  for (const node of chain.nodes) {
8139
8169
  if (node.error || !node.preprocessedContent) continue;
@@ -8199,6 +8229,16 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
8199
8229
  resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
8200
8230
  }
8201
8231
  const l1Adapter = (content) => {
8232
+ const extHit = scanExtensionPatterns(ext, content);
8233
+ if (extHit) {
8234
+ return {
8235
+ hit: true,
8236
+ riskLevel: extHit.riskLevel,
8237
+ riskType: extHit.riskType,
8238
+ reason: extHit.reason,
8239
+ matchedPatterns: []
8240
+ };
8241
+ }
8202
8242
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
8203
8243
  if (j && !j.allowed) {
8204
8244
  return {
@@ -8222,7 +8262,6 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
8222
8262
  );
8223
8263
  const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
8224
8264
  if (chain.nodes.length === 0) return chain;
8225
- scanScriptChainWithL1(chain, input, ext);
8226
8265
  scanScriptChainWithL2(chain, input);
8227
8266
  scanScriptChainKeywords(chain);
8228
8267
  return chain;
@@ -8710,8 +8749,8 @@ var init_metrics = __esm({
8710
8749
  };
8711
8750
  ANALYZE_TOTAL = new Counter(
8712
8751
  "agent_moss_analyze_total",
8713
- "Total analyze requests handled, by decision and risk level.",
8714
- ["decision", "risk_level"]
8752
+ "Total analyze requests handled, by decision, risk level and L3 outcome.",
8753
+ ["decision", "risk_level", "l3_outcome"]
8715
8754
  );
8716
8755
  ANALYZE_DURATION = new Histogram(
8717
8756
  "agent_moss_analyze_duration_seconds",
@@ -8994,6 +9033,42 @@ var init_token_stats = __esm({
8994
9033
  import { createHash as createHash3 } from "crypto";
8995
9034
  import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
8996
9035
  import OpenAI from "openai";
9036
+ function reasoningTextFallback(raw) {
9037
+ if (typeof raw !== "string") return "";
9038
+ let text = raw.trim();
9039
+ if (text.startsWith("```")) {
9040
+ text = text.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "").trim();
9041
+ }
9042
+ if (!(text.startsWith("{") && text.endsWith("}"))) return "";
9043
+ let parsed;
9044
+ try {
9045
+ parsed = JSON.parse(text);
9046
+ } catch {
9047
+ return "";
9048
+ }
9049
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
9050
+ if ("allowed" in parsed || "decision" in parsed || "risk_level" in parsed) {
9051
+ return text;
9052
+ }
9053
+ }
9054
+ return "";
9055
+ }
9056
+ function reasoningFallbackWithField(message) {
9057
+ if (!message || typeof message !== "object") return { text: "", field: "" };
9058
+ for (const key of ["reasoning", "reasoning_content", "thinking"]) {
9059
+ const got = reasoningTextFallback(message[key]);
9060
+ if (got) return { text: got, field: key };
9061
+ }
9062
+ return { text: "", field: "" };
9063
+ }
9064
+ function describeContentState(raw) {
9065
+ if (raw === null) return "null";
9066
+ if (raw === void 0) return "undefined";
9067
+ const text = typeof raw === "string" ? raw : String(raw);
9068
+ if (text === "") return "empty_string";
9069
+ if (!text.trim()) return `whitespace_only(${text.length})`;
9070
+ return `non_empty(${text.length})`;
9071
+ }
8997
9072
  function responseFieldLengths(message) {
8998
9073
  if (!message || typeof message !== "object") return {};
8999
9074
  const out = {};
@@ -9251,6 +9326,7 @@ function formatHints(previous) {
9251
9326
  async function analyzeWithLLM(prompt, config) {
9252
9327
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
9253
9328
  const _llmStart = performance.now();
9329
+ let usedReasoningFallback = false;
9254
9330
  const _recordLlm = (result) => {
9255
9331
  try {
9256
9332
  LLM_CALLS_TOTAL.inc(1, { result });
@@ -9286,7 +9362,7 @@ async function analyzeWithLLM(prompt, config) {
9286
9362
  } catch {
9287
9363
  }
9288
9364
  _recordLlm("error");
9289
- throw new Error(
9365
+ throw new LLMCircuitOpenError(
9290
9366
  "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
9367
  );
9292
9368
  }
@@ -9308,10 +9384,21 @@ async function analyzeWithLLM(prompt, config) {
9308
9384
  ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
9309
9385
  });
9310
9386
  const message = response.choices[0]?.message;
9311
- const content = message?.content ?? "";
9387
+ let content = message?.content ?? "";
9312
9388
  const finishReason = response.choices[0]?.finish_reason;
9313
9389
  const fieldLengths = responseFieldLengths(message);
9314
9390
  const usage = response.usage;
9391
+ if (!content) {
9392
+ const { text: fallback, field } = reasoningFallbackWithField(message);
9393
+ if (fallback) {
9394
+ const origState = describeContentState(message?.content);
9395
+ console.warn(
9396
+ `[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`
9397
+ );
9398
+ content = fallback;
9399
+ usedReasoningFallback = true;
9400
+ }
9401
+ }
9315
9402
  if (!content) {
9316
9403
  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
9404
  traceFull("l3.empty_response", {
@@ -9384,7 +9471,9 @@ async function analyzeWithLLM(prompt, config) {
9384
9471
  riskLevel: ["low", "medium", "high", "critical"].includes(riskLevel) ? riskLevel : "low",
9385
9472
  riskType: riskType || "",
9386
9473
  confidence: typeof parsed.confidence === "number" ? Math.min(100, Math.max(0, parsed.confidence)) : 70,
9387
- source: "llm",
9474
+ // 判定结果一样可用,但运维要能看出模型行为异常
9475
+ // (下游据此填 l3Outcome 与 degraded)。
9476
+ source: usedReasoningFallback ? "llm_reasoning_fallback" : "llm",
9388
9477
  violatedLayers: ["L3.1"]
9389
9478
  };
9390
9479
  } catch (err) {
@@ -9410,7 +9499,7 @@ async function analyzeWithLLM(prompt, config) {
9410
9499
  clearTimeout(totalTimeoutTimer);
9411
9500
  throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
9412
9501
  }
9413
- var llmCache, LLM_CACHE_MAX;
9502
+ var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
9414
9503
  var init_llm_analyzer = __esm({
9415
9504
  "src/engine/llm-analyzer.ts"() {
9416
9505
  "use strict";
@@ -9424,6 +9513,12 @@ var init_llm_analyzer = __esm({
9424
9513
  init_trace_log();
9425
9514
  init_metrics();
9426
9515
  init_circuit_breaker();
9516
+ LLMCircuitOpenError = class extends Error {
9517
+ constructor(message) {
9518
+ super(message);
9519
+ this.name = "LLMCircuitOpenError";
9520
+ }
9521
+ };
9427
9522
  llmCache = /* @__PURE__ */ new Map();
9428
9523
  LLM_CACHE_MAX = 200;
9429
9524
  }
@@ -10300,7 +10395,7 @@ import { mkdirSync as mkdirSync6, mkdtempSync, rmSync, writeFileSync as writeFil
10300
10395
  import { tmpdir as tmpdir2 } from "os";
10301
10396
  import { join as join15 } from "path";
10302
10397
  import { spawnSync } from "child_process";
10303
- import { dirname as dirname10 } from "path";
10398
+ import { dirname as dirname11 } from "path";
10304
10399
  import { fileURLToPath as fileURLToPath9 } from "url";
10305
10400
  function collectRules(store) {
10306
10401
  return store.getActiveRules().filter((r) => EXPORT_RULE_SOURCES.includes(r.source)).map((r) => ({
@@ -10541,7 +10636,7 @@ var init_contributor = __esm({
10541
10636
  init_rule_store();
10542
10637
  init_skill_manager();
10543
10638
  init_asset_dir();
10544
- __dirname8 = dirname10(fileURLToPath9(import.meta.url));
10639
+ __dirname8 = dirname11(fileURLToPath9(import.meta.url));
10545
10640
  DEFAULT_TARGET_REPO = "ssh://git@atomgit.com/kenhkl/AgentMoss.git";
10546
10641
  CONTACT_EMAIL = "kenhkl11@hotmail.com";
10547
10642
  TOKEN_ENV = "AGENT_MOSS_CONTRIBUTE_TOKEN";
@@ -12416,9 +12511,24 @@ import * as os3 from "os";
12416
12511
  import * as path6 from "path";
12417
12512
  import { createHash as createHash4 } from "crypto";
12418
12513
  function defaultStateDbPath() {
12419
- const dir = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
12514
+ const base = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
12515
+ const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
12516
+ const dir = instance ? path6.join(base, instance) : base;
12420
12517
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
12421
- return path6.join(dir, `stateful_chains_${tag}.json`);
12518
+ const target = path6.join(dir, `stateful_chains_${tag}.json`);
12519
+ if (instance) {
12520
+ const legacy = path6.join(base, `stateful_chains_${tag}.json`);
12521
+ if (!fs5.existsSync(target) && fs5.existsSync(legacy)) {
12522
+ try {
12523
+ fs5.mkdirSync(dir, { recursive: true });
12524
+ fs5.copyFileSync(legacy, target);
12525
+ console.warn(`[AgentMoss] \u94FE\u72B6\u6001\u6587\u4EF6\u6309 instance \u9694\u79BB\uFF1A\u5DF2\u4ECE\u65E7\u5171\u4EAB\u6587\u4EF6\u590D\u5236\u5230 ${target}`);
12526
+ } catch (err) {
12527
+ console.warn("[AgentMoss] \u8FC1\u79FB\u94FE\u72B6\u6001\u6587\u4EF6\u5931\u8D25\uFF08\u5C06\u4F7F\u7528\u65B0\u7A7A\u6587\u4EF6\uFF09:", err);
12528
+ }
12529
+ }
12530
+ }
12531
+ return target;
12422
12532
  }
12423
12533
  function registerExitFlush(store) {
12424
12534
  if (_exitHookRegistered) return;
@@ -13076,6 +13186,7 @@ async function runAnalysis(input) {
13076
13186
  pathContext
13077
13187
  });
13078
13188
  } catch (e) {
13189
+ const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
13079
13190
  const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
13080
13191
  if (getLLMFailMode2() === "fail_open") {
13081
13192
  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 +13196,7 @@ async function runAnalysis(input) {
13085
13196
  riskLevel: "low",
13086
13197
  riskType: "",
13087
13198
  confidence: 50,
13088
- source: "llm_failure_fallback",
13199
+ source: failSource,
13089
13200
  violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
13090
13201
  };
13091
13202
  }
@@ -13095,7 +13206,7 @@ async function runAnalysis(input) {
13095
13206
  riskLevel: "medium",
13096
13207
  riskType: "",
13097
13208
  confidence: 60,
13098
- source: "llm_failure_fallback",
13209
+ source: failSource,
13099
13210
  violatedLayers: ["L3.1"]
13100
13211
  };
13101
13212
  }
@@ -13154,6 +13265,24 @@ var init_coordinator = __esm({
13154
13265
  }
13155
13266
  });
13156
13267
 
13268
+ // src/engine/types.ts
13269
+ function deriveL3Outcome(j) {
13270
+ const src = (j.source || "").toLowerCase();
13271
+ if (src === "llm" || src === "llm_extracted") return "ok";
13272
+ if (src === "llm_reasoning_fallback") return "reasoning_fallback";
13273
+ if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
13274
+ if (src === "llm_circuit_open") return "circuit_open";
13275
+ if (src === "llm_failure_with_violation") return "failed_but_blocked";
13276
+ if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
13277
+ return "not_reached";
13278
+ }
13279
+ var init_types = __esm({
13280
+ "src/engine/types.ts"() {
13281
+ "use strict";
13282
+ init_esm_shims();
13283
+ }
13284
+ });
13285
+
13157
13286
  // src/infra/policy-cache.ts
13158
13287
  import { createHash as createHash5 } from "crypto";
13159
13288
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
@@ -13496,9 +13625,15 @@ function allowResult(policy, judgment) {
13496
13625
  violated_layers: judgment.violatedLayers || [],
13497
13626
  policy,
13498
13627
  violated_policy: "",
13499
- confidence: judgment.confidence
13628
+ confidence: judgment.confidence,
13629
+ // 判定成功算出时才推导(对齐 Python `_finalize`)
13630
+ ...judgment.source !== void 0 ? { l3_outcome: deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed ?? true }) } : {}
13500
13631
  };
13501
13632
  }
13633
+ function withL3(res, judgment) {
13634
+ res.l3_outcome = deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed });
13635
+ return res;
13636
+ }
13502
13637
  async function analyze(input) {
13503
13638
  const mossLog = new MossLogger(input.sessionId);
13504
13639
  try {
@@ -13525,7 +13660,7 @@ async function analyzeInner(input, mossLog) {
13525
13660
  const judgment = await runAnalysis(input);
13526
13661
  mossLog.endStep(
13527
13662
  "step1_security_judge",
13528
- `allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}`
13663
+ `allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}, l3_outcome=${deriveL3Outcome(judgment)}`
13529
13664
  );
13530
13665
  if (!judgment.allowed) {
13531
13666
  const denied = {
@@ -13541,7 +13676,7 @@ async function analyzeInner(input, mossLog) {
13541
13676
  violation_chain: judgment.violationChain ?? []
13542
13677
  };
13543
13678
  mossLog.logResult("Deny", denied.reason);
13544
- return denied;
13679
+ return withL3(denied, judgment);
13545
13680
  }
13546
13681
  const cache3 = getDefaultCache();
13547
13682
  mossLog.startStep("step2_cache_lookup");
@@ -13551,7 +13686,7 @@ async function analyzeInner(input, mossLog) {
13551
13686
  savePolicyToFile(input.sessionId, cached2);
13552
13687
  const res = allowResult(cached2, judgment);
13553
13688
  mossLog.logResult("Allow", res.reason, cached2);
13554
- return res;
13689
+ return withL3(res, judgment);
13555
13690
  }
13556
13691
  if (!isPolicyGenEnabled()) {
13557
13692
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0CPolicy \u751F\u6210\u5DF2\u7981\u7528");
@@ -13561,7 +13696,7 @@ async function analyzeInner(input, mossLog) {
13561
13696
  const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
13562
13697
  mossLog.endStep("step2_default_policy", "\u4F7F\u7528\u9ED8\u8BA4\u6700\u5C0F\u6743\u9650 Policy");
13563
13698
  mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
13564
- return res;
13699
+ return withL3(res, judgment);
13565
13700
  }
13566
13701
  if (judgment.source === "whitelist_bypass") {
13567
13702
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u767D\u540D\u5355\u5DE5\u5177");
@@ -13569,7 +13704,7 @@ async function analyzeInner(input, mossLog) {
13569
13704
  savePolicyToFile(input.sessionId, DEFAULT_READONLY_POLICY);
13570
13705
  const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
13571
13706
  mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
13572
- return res;
13707
+ return withL3(res, judgment);
13573
13708
  }
13574
13709
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u542F\u7528 LLM \u751F\u6210");
13575
13710
  mossLog.startStep("step2_generate_policy");
@@ -13580,7 +13715,7 @@ async function analyzeInner(input, mossLog) {
13580
13715
  mossLog.endStep("step2_generate_policy", "Policy \u751F\u6210\u5E76\u7F13\u5B58\u6210\u529F");
13581
13716
  const res = allowResult(policy, judgment);
13582
13717
  mossLog.logResult("Allow", res.reason, policy);
13583
- return res;
13718
+ return withL3(res, judgment);
13584
13719
  } catch (err) {
13585
13720
  mossLog.endStep("step2_generate_policy", `\u5931\u8D25: ${String(err)}`);
13586
13721
  mossLog.logError("step2_generate_policy", err);
@@ -13595,7 +13730,7 @@ async function analyzeInner(input, mossLog) {
13595
13730
  confidence: judgment.confidence
13596
13731
  };
13597
13732
  mossLog.logResult("Deny", failed.reason);
13598
- return failed;
13733
+ return withL3(failed, judgment);
13599
13734
  }
13600
13735
  }
13601
13736
  var POLICY_OUTPUT_DIR, policyOutputDirOverride, DEFAULT_READONLY_POLICY;
@@ -13605,6 +13740,7 @@ var init_analyzer = __esm({
13605
13740
  init_esm_shims();
13606
13741
  init_security_policy();
13607
13742
  init_coordinator();
13743
+ init_types();
13608
13744
  init_policy_cache();
13609
13745
  init_config();
13610
13746
  init_template_loader();
@@ -14081,7 +14217,7 @@ var init_runtime_stats = __esm({
14081
14217
 
14082
14218
  // src/routes.ts
14083
14219
  import { randomBytes as randomBytes2 } from "crypto";
14084
- import { join as join20, dirname as dirname12 } from "path";
14220
+ import { join as join20, dirname as dirname13 } from "path";
14085
14221
  import { fileURLToPath as fileURLToPath10 } from "url";
14086
14222
  async function healthRoute(c) {
14087
14223
  const metrics = {};
@@ -14232,6 +14368,24 @@ async function analyzeRoute(c) {
14232
14368
  llmLogPath: req.metadata?.llm_log_path
14233
14369
  });
14234
14370
  const durationMs = performance.now() - t0;
14371
+ const _l3FailMsg = String(result.reason || "").slice(0, 160);
14372
+ if (result.l3_outcome === "reasoning_fallback") {
14373
+ degradedNotes.push(
14374
+ "\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"
14375
+ );
14376
+ } else if (result.l3_outcome === "fail_open") {
14377
+ degradedNotes.push(
14378
+ `\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`
14379
+ );
14380
+ } else if (result.l3_outcome === "fail_closed") {
14381
+ degradedNotes.push(
14382
+ `\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`
14383
+ );
14384
+ } else if (result.l3_outcome === "circuit_open") {
14385
+ degradedNotes.push(
14386
+ `\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`
14387
+ );
14388
+ }
14235
14389
  const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
14236
14390
  if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
14237
14391
  console.warn(
@@ -14239,7 +14393,11 @@ async function analyzeRoute(c) {
14239
14393
  );
14240
14394
  }
14241
14395
  try {
14242
- ANALYZE_TOTAL.inc(1, { decision: result.decision, risk_level: result.risk_level });
14396
+ ANALYZE_TOTAL.inc(1, {
14397
+ decision: result.decision,
14398
+ risk_level: result.risk_level,
14399
+ l3_outcome: result.l3_outcome || ""
14400
+ });
14243
14401
  ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
14244
14402
  for (const layer of result.violated_layers || []) {
14245
14403
  LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
@@ -14253,7 +14411,9 @@ async function analyzeRoute(c) {
14253
14411
  risk_type: result.risk_type,
14254
14412
  reason: result.reason,
14255
14413
  violated_layers: result.violated_layers,
14256
- duration_ms: Math.round(durationMs * 10) / 10
14414
+ duration_ms: Math.round(durationMs * 10) / 10,
14415
+ // 2026-11:L3 结局(区分「L3 判过」与「L3 挂了放的」)
14416
+ l3_outcome: result.l3_outcome || ""
14257
14417
  });
14258
14418
  try {
14259
14419
  reportEnforcementEvent({
@@ -14344,7 +14504,10 @@ async function analyzeRoute(c) {
14344
14504
  violation_chain: result.violation_chain ?? [],
14345
14505
  violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
14346
14506
  // 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
14347
- degraded: degradedNotes
14507
+ degraded: degradedNotes,
14508
+ // L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
14509
+ // 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
14510
+ l3_outcome: result.l3_outcome || ""
14348
14511
  })
14349
14512
  );
14350
14513
  } catch (err) {
@@ -14594,7 +14757,7 @@ var init_routes = __esm({
14594
14757
  init_loop_monitor();
14595
14758
  init_runtime_stats();
14596
14759
  init_metrics();
14597
- __dirname9 = dirname12(fileURLToPath10(import.meta.url));
14760
+ __dirname9 = dirname13(fileURLToPath10(import.meta.url));
14598
14761
  }
14599
14762
  });
14600
14763
 
@@ -14602,7 +14765,7 @@ var init_routes = __esm({
14602
14765
  import { Hono } from "hono";
14603
14766
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
14604
14767
  import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
14605
- import { join as join21, dirname as dirname13 } from "path";
14768
+ import { join as join21, dirname as dirname14 } from "path";
14606
14769
  import { fileURLToPath as fileURLToPath11 } from "url";
14607
14770
  function getConsoleToken() {
14608
14771
  return process.env[CONSOLE_TOKEN_ENV] || "";
@@ -14841,7 +15004,7 @@ function createConsoleRouter() {
14841
15004
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
14842
15005
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
14843
15006
  }
14844
- const userPath = join21(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
15007
+ const userPath = join21(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14845
15008
  const builtinDir = resolveAssetDir(__dirname10, "skills");
14846
15009
  const candidates = [
14847
15010
  ...isRuntimeConfigDisabled() ? [] : [userPath],
@@ -14982,7 +15145,7 @@ var init_router = __esm({
14982
15145
  init_rules_loader();
14983
15146
  init_asset_dir();
14984
15147
  init_rules_mode();
14985
- __dirname10 = dirname13(fileURLToPath11(import.meta.url));
15148
+ __dirname10 = dirname14(fileURLToPath11(import.meta.url));
14986
15149
  STATIC_DIR = join21(__dirname10, "static");
14987
15150
  CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
14988
15151
  }
@@ -15011,8 +15174,8 @@ import { Hono as Hono2 } from "hono";
15011
15174
  import { cors } from "hono/cors";
15012
15175
  import { logger } from "hono/logger";
15013
15176
  import net from "net";
15014
- 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";
15177
+ import { existsSync as existsSync21, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync10 } from "fs";
15178
+ import { dirname as dirname15 } from "path";
15016
15179
  function logDeploymentSelfCheck() {
15017
15180
  try {
15018
15181
  const mode = getRulesMode();
@@ -15255,11 +15418,14 @@ async function warmUpEngine() {
15255
15418
  }
15256
15419
  function writePortFile(port) {
15257
15420
  try {
15258
- const path8 = join22(getDataRoot(), "agent_moss_server.port.json");
15259
- mkdirSync9(dirname14(path8), { recursive: true });
15421
+ const path8 = getPortFilePath();
15422
+ mkdirSync10(dirname15(path8), { recursive: true });
15260
15423
  const payload = JSON.stringify({
15261
15424
  port,
15262
15425
  pid: process.pid,
15426
+ // instance/version 供调用方校验,避免同机多实例端口文件串台
15427
+ instance: getInstance(),
15428
+ version,
15263
15429
  started_at: (/* @__PURE__ */ new Date()).toISOString()
15264
15430
  });
15265
15431
  const tmp = `${path8}.tmp`;
@@ -15306,12 +15472,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15306
15472
  },
15307
15473
  serve: async () => {
15308
15474
  failFastOnAuthError();
15309
- const { mkdirSync: mkdirSync11, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15310
- const { dirname: dirname16 } = await import("path");
15311
- const dir = dirname16(socketPath);
15475
+ const { mkdirSync: mkdirSync12, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15476
+ const { dirname: dirname17 } = await import("path");
15477
+ const dir = dirname17(socketPath);
15312
15478
  if (dir) {
15313
15479
  try {
15314
- mkdirSync11(dir, { recursive: true });
15480
+ mkdirSync12(dir, { recursive: true });
15315
15481
  } catch {
15316
15482
  }
15317
15483
  }
@@ -15372,6 +15538,7 @@ var init_server = __esm({
15372
15538
  init_rules_contract();
15373
15539
  init_security_policy();
15374
15540
  init_paths();
15541
+ init_package_json();
15375
15542
  init_routes();
15376
15543
  init_console();
15377
15544
  init_runtime_config();
@@ -15444,11 +15611,11 @@ __export(rules_tools_exports, {
15444
15611
  rulesStatusText: () => rulesStatusText,
15445
15612
  templateSourceDir: () => templateSourceDir
15446
15613
  });
15447
- 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";
15614
+ import { existsSync as existsSync22, mkdirSync as mkdirSync11, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync8 } from "fs";
15615
+ import { dirname as dirname16, join as join23 } from "path";
15449
15616
  import { fileURLToPath as fileURLToPath12 } from "url";
15450
15617
  function initRulesDir(targetDir, opts = {}) {
15451
- mkdirSync10(targetDir, { recursive: true });
15618
+ mkdirSync11(targetDir, { recursive: true });
15452
15619
  const written = [];
15453
15620
  const extraPath = join23(targetDir, EXTRA_FILENAME);
15454
15621
  if (opts.force || !existsSync22(extraPath)) {
@@ -15548,7 +15715,7 @@ var init_rules_tools = __esm({
15548
15715
  "use strict";
15549
15716
  init_esm_shims();
15550
15717
  init_rules_loader();
15551
- __dirname11 = dirname15(fileURLToPath12(import.meta.url));
15718
+ __dirname11 = dirname16(fileURLToPath12(import.meta.url));
15552
15719
  EXTRA_TEMPLATE = {
15553
15720
  _\u8BF4\u660E: [
15554
15721
  "\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",