@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/server.js CHANGED
@@ -96,6 +96,13 @@ function getTokenStatsPath() {
96
96
  }
97
97
  return join(getDataRoot(), "agent_moss_token_stats.json");
98
98
  }
99
+ function getInstanceDir() {
100
+ const instance = getInstance();
101
+ return instance ? join(getDataRoot(), instance) : getDataRoot();
102
+ }
103
+ function getPortFilePath() {
104
+ return join(getInstanceDir(), "agent_moss_server.port.json");
105
+ }
99
106
  var ENV_DATA_ROOT, ENV_INSTANCE, DEFAULT_DATA_ROOT, ENV_RULES_ROOT, ID_MAX_LEN, ID_PATTERN;
100
107
  var init_paths = __esm({
101
108
  "src/infra/paths.ts"() {
@@ -1622,6 +1629,22 @@ function historyCommandText(histDetailRaw) {
1622
1629
  }
1623
1630
  return histDetailRaw;
1624
1631
  }
1632
+ function isScriptGeneratedTarget(targetPath, writtenScripts, shellRuns) {
1633
+ const base = path2.basename(targetPath);
1634
+ if (base.length < 3) return false;
1635
+ const targetDir = path2.dirname(targetPath);
1636
+ if (!targetDir) return false;
1637
+ for (const script of writtenScripts) {
1638
+ if (path2.dirname(script.path) !== targetDir) continue;
1639
+ if (!script.detail.includes(base)) continue;
1640
+ const scriptName = path2.basename(script.path);
1641
+ if (!scriptName) continue;
1642
+ if (shellRuns.some((run) => run.index > script.index && run.command.includes(scriptName))) {
1643
+ return true;
1644
+ }
1645
+ }
1646
+ return false;
1647
+ }
1625
1648
  function parseHeadTailLimit(seg) {
1626
1649
  const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
1627
1650
  if (firstWord !== "head" && firstWord !== "tail") return null;
@@ -2141,7 +2164,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2141
2164
  const historyFullReadPaths = /* @__PURE__ */ new Set();
2142
2165
  const historyPartialRead = /* @__PURE__ */ new Map();
2143
2166
  const historyWrittenPaths = /* @__PURE__ */ new Set();
2144
- for (const action of actionHistory) {
2167
+ let historyWrittenScripts = [];
2168
+ const shellRunActions = [];
2169
+ for (let actionIndex = 0; actionIndex < actionHistory.length; actionIndex++) {
2170
+ const action = actionHistory[actionIndex];
2145
2171
  const histDetailRaw = action.actionDetail;
2146
2172
  const histType = action.actionType.toLowerCase();
2147
2173
  const traits = getPlatformTraits(osType);
@@ -2153,7 +2179,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2153
2179
  );
2154
2180
  for (const p of coverage.full) historyFullReadPaths.add(p);
2155
2181
  if (isFullOverwriteTool(histType, singleFileTools) && !APPEND_MODE_RE.test(histDetailRaw)) {
2156
- for (const p of declaredWritePaths(histDetailRaw, osType)) historyWrittenPaths.add(p);
2182
+ for (const p of declaredWritePaths(histDetailRaw, osType)) {
2183
+ historyWrittenPaths.add(p);
2184
+ if (SCRIPT_FILE_RE.test(p)) {
2185
+ historyWrittenScripts.push({ path: p, detail: histDetailRaw, index: actionIndex });
2186
+ }
2187
+ }
2188
+ }
2189
+ if (BASH_LIKE_ACTION_TYPES.includes(histType)) {
2190
+ shellRunActions.push({ index: actionIndex, command: historyCommandText(histDetailRaw) });
2157
2191
  }
2158
2192
  for (const [p, upto] of coverage.partial) {
2159
2193
  if (historyPartialRead.has(p)) {
@@ -2180,6 +2214,7 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2180
2214
  const normalizedWrittenPaths = new Set(
2181
2215
  [...historyWrittenPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2182
2216
  );
2217
+ historyWrittenScripts = historyWrittenScripts.map((s) => ({ ...s, path: normalizePathForCompare(s.path, cwd) })).filter((s) => s.path);
2183
2218
  const normalizedPartialReads = /* @__PURE__ */ new Map();
2184
2219
  for (const [p, upto] of historyPartialRead) {
2185
2220
  const np = normalizePathForCompare(p, cwd);
@@ -2209,6 +2244,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2209
2244
  )) {
2210
2245
  isFullRead = true;
2211
2246
  }
2247
+ if (!isFullRead && !isProtectedWritePath(path8) && isScriptGeneratedTarget(path8, historyWrittenScripts, shellRunActions)) {
2248
+ isFullRead = true;
2249
+ }
2212
2250
  let isPartialCovered = false;
2213
2251
  if (!isFullRead) {
2214
2252
  for (const [pp, upto] of normalizedPartialReads) {
@@ -2402,7 +2440,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2402
2440
  violatedLayers: ["L2.1"]
2403
2441
  };
2404
2442
  }
2405
- var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
2443
+ var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SCRIPT_FILE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
2406
2444
  var init_logic_rules = __esm({
2407
2445
  "src/engine/logic-rules.ts"() {
2408
2446
  "use strict";
@@ -2468,6 +2506,7 @@ var init_logic_rules = __esm({
2468
2506
  PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
2469
2507
  APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
2470
2508
  APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
2509
+ SCRIPT_FILE_RE = /\.(?:py|pyw|sh|bash|zsh|js|mjs|cjs|ts|pl|rb|php|ps1|bat|cmd)$/i;
2471
2510
  SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
2472
2511
  SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
2473
2512
  SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
@@ -2572,7 +2611,7 @@ var init_asset_dir = __esm({
2572
2611
 
2573
2612
  // src/engine/skill-loader.ts
2574
2613
  import { readFileSync as readFileSync5, readdirSync as readdirSync3, existsSync as existsSync6 } from "fs";
2575
- import { resolve as resolve4, dirname as dirname3 } from "path";
2614
+ import { resolve as resolve4, dirname as dirname4 } from "path";
2576
2615
  import { fileURLToPath as fileURLToPath3 } from "url";
2577
2616
  function loadAllSkills() {
2578
2617
  if (cachedSkills) return cachedSkills;
@@ -2686,7 +2725,7 @@ var init_skill_loader = __esm({
2686
2725
  init_asset_dir();
2687
2726
  init_runtime_config_bridge();
2688
2727
  __filename3 = fileURLToPath3(import.meta.url);
2689
- __dirname3 = dirname3(__filename3);
2728
+ __dirname3 = dirname4(__filename3);
2690
2729
  SKILL_KEYWORD_MAP = (() => {
2691
2730
  const map = {};
2692
2731
  const cats = loadL3();
@@ -2769,7 +2808,7 @@ __export(runtime_config_exports, {
2769
2808
  import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
2770
2809
  import { join as join7 } from "path";
2771
2810
  import { fileURLToPath as fileURLToPath4 } from "url";
2772
- import { dirname as dirname4 } from "path";
2811
+ import { dirname as dirname5 } from "path";
2773
2812
  function runtimeDir() {
2774
2813
  return getRuntimeConfigDir();
2775
2814
  }
@@ -4124,7 +4163,7 @@ var init_runtime_config = __esm({
4124
4163
  init_rules_loader();
4125
4164
  init_runtime_config_bridge();
4126
4165
  init_rules_mode();
4127
- __dirname4 = dirname4(fileURLToPath4(import.meta.url));
4166
+ __dirname4 = dirname5(fileURLToPath4(import.meta.url));
4128
4167
  ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
4129
4168
  RUNTIME_CONFIG_DIR = runtimeDir();
4130
4169
  RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
@@ -4499,7 +4538,7 @@ var init_config = __esm({
4499
4538
 
4500
4539
  // src/agents/index.ts
4501
4540
  import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
4502
- import { resolve as resolve5, dirname as dirname5, join as join8 } from "path";
4541
+ import { resolve as resolve5, dirname as dirname6, join as join8 } from "path";
4503
4542
  import { fileURLToPath as fileURLToPath6 } from "url";
4504
4543
  function resolveAgentsDir() {
4505
4544
  const root = getRulesRoot();
@@ -4576,7 +4615,7 @@ var init_agents = __esm({
4576
4615
  init_paths();
4577
4616
  init_runtime_config();
4578
4617
  __filename4 = fileURLToPath6(import.meta.url);
4579
- __dirname5 = dirname5(__filename4);
4618
+ __dirname5 = dirname6(__filename4);
4580
4619
  AGENTS_DIR_PROD = resolve5(__dirname5, "agents");
4581
4620
  AGENTS_DIR_DEV_FALLBACK = resolve5(__dirname5, "../../../agent_moss/agents");
4582
4621
  cache = /* @__PURE__ */ new Map();
@@ -4586,7 +4625,7 @@ var init_agents = __esm({
4586
4625
 
4587
4626
  // src/scenarios/index.ts
4588
4627
  import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
4589
- import { resolve as resolve6, dirname as dirname6, join as join9 } from "path";
4628
+ import { resolve as resolve6, dirname as dirname7, join as join9 } from "path";
4590
4629
  import { fileURLToPath as fileURLToPath7 } from "url";
4591
4630
  function resolveScenariosDir() {
4592
4631
  const root = getRulesRoot();
@@ -4682,7 +4721,7 @@ var init_scenarios = __esm({
4682
4721
  init_runtime_config();
4683
4722
  init_rules_loader();
4684
4723
  __filename5 = fileURLToPath7(import.meta.url);
4685
- __dirname6 = dirname6(__filename5);
4724
+ __dirname6 = dirname7(__filename5);
4686
4725
  SCENARIOS_DIR_PROD = resolve6(__dirname6, "scenarios");
4687
4726
  SCENARIOS_DIR_DEV_FALLBACK = resolve6(__dirname6, "../../../agent_moss/scenarios");
4688
4727
  cache2 = /* @__PURE__ */ new Map();
@@ -5673,7 +5712,8 @@ function checkDangerousPatterns(actionType, actionDetail) {
5673
5712
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
5674
5713
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
5675
5714
  const wildcardDeleteRe = /(?:\brm\b|\b(r?mdir|del|delete|remove|rmdir|unlink)\b|\b删除\b|\b移除\b)[\s\S]{0,40}?[*?]|[*?][\s\S]{0,40}?\b(?:rm|del|delete|remove|rmdir|unlink)\b|rm\s+-[a-zA-Z]*[rf][a-zA-Z]*\s+\S*[*?]/i;
5676
- if (!isTempPath && wildcardDeleteRe.test(scan)) {
5715
+ const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
5716
+ if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
5677
5717
  return {
5678
5718
  allowed: false,
5679
5719
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -5870,7 +5910,7 @@ var init_heuristic = __esm({
5870
5910
 
5871
5911
  // src/engine/template-loader.ts
5872
5912
  import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
5873
- import { resolve as resolve7, dirname as dirname7 } from "path";
5913
+ import { resolve as resolve7, dirname as dirname8 } from "path";
5874
5914
  import { fileURLToPath as fileURLToPath8 } from "url";
5875
5915
  function loadTemplates() {
5876
5916
  if (cachedTemplates) return cachedTemplates;
@@ -5898,7 +5938,7 @@ var init_template_loader = __esm({
5898
5938
  init_esm_shims();
5899
5939
  init_asset_dir();
5900
5940
  __filename6 = fileURLToPath8(import.meta.url);
5901
- __dirname7 = dirname7(__filename6);
5941
+ __dirname7 = dirname8(__filename6);
5902
5942
  TEMPLATE_FILES = ["prompt1_template.txt", "prompt2_template.txt", "security_judge_template.txt"];
5903
5943
  cachedTemplates = null;
5904
5944
  }
@@ -6968,7 +7008,7 @@ function evalCondition2(cond, env2) {
6968
7008
  if (lv2 === null || rv2 === null) return null;
6969
7009
  return evalNumericCompare(op2, lv2, rv2);
6970
7010
  }
6971
- const sm = innerQ.match(/(.*?)\s*(==|=|!=|=~)\s*(.*)/);
7011
+ const sm = innerQ.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
6972
7012
  if (!sm) return null;
6973
7013
  const op = sm[2];
6974
7014
  let left = sm[1].trim();
@@ -6986,8 +7026,8 @@ function evalCondition2(cond, env2) {
6986
7026
  const lv = resolveVarSide(left, env2);
6987
7027
  const rv = resolveVarSide(right, env2);
6988
7028
  if (lv === null || rv === null) return null;
6989
- if (op === "!=") return lv !== rv;
6990
- return lv === rv;
7029
+ const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
7030
+ return op === "!=" ? !matched : matched;
6991
7031
  }
6992
7032
  function symbolicProcess(content, entryArgs) {
6993
7033
  if (!content) return null;
@@ -6995,6 +7035,7 @@ function symbolicProcess(content, entryArgs) {
6995
7035
  if (!stmts.some((s) => s.kind === "case" || s.kind === "if" || s.kind === "assign")) return null;
6996
7036
  if (stmts.some((s) => !s.modelable)) return null;
6997
7037
  const env2 = initEnv(entryArgs);
7038
+ if (env2.size > MAX_VARS) return null;
6998
7039
  let linesBudget = 0;
6999
7040
  let branchesBudget = 0;
7000
7041
  let modelable = false;
@@ -7004,7 +7045,7 @@ function symbolicProcess(content, entryArgs) {
7004
7045
  if (linesBudget > MAX_LINES2) return null;
7005
7046
  if (s.kind === "assign") {
7006
7047
  modelable = true;
7007
- if (env2.size >= MAX_VARS) return null;
7048
+ if (!env2.has(s.name) && env2.size >= MAX_VARS) return null;
7008
7049
  const v = evalExpr2(s.rhs, env2);
7009
7050
  env2.set(s.name, fold(v));
7010
7051
  out.push(s.line);
@@ -7231,24 +7272,34 @@ function splitNestedCaseBranches(bodyLines, selectorVal) {
7231
7272
  }
7232
7273
  function evalIfCondition(cond, args) {
7233
7274
  if (!args || !args.length) return null;
7234
- let inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
7235
- const m = inner.match(/(.*?)\s*(==|=)\s*(.*)/);
7275
+ const inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
7276
+ const m = inner.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
7236
7277
  if (!m) return null;
7278
+ const op = m[2];
7237
7279
  let left = m[1].trim();
7238
7280
  let right = m[3].trim();
7239
- const lm = left.match(/^\$(\d+)$/);
7240
- if (lm) {
7241
- const idx = parseInt(lm[1], 10);
7242
- if (1 <= idx && idx <= args.length) left = args[idx - 1];
7243
- else return null;
7244
- } else if (left.startsWith("$")) return null;
7245
- const rm = right.match(/^\$(\d+)$/);
7246
- if (rm) {
7247
- const idx = parseInt(rm[1], 10);
7248
- if (1 <= idx && idx <= args.length) right = args[idx - 1];
7249
- else return null;
7250
- } else if (right.startsWith("$")) return null;
7251
- return left === right;
7281
+ const resolve12 = (tok) => {
7282
+ const rm = tok.match(/^\$(\d+)$/);
7283
+ if (rm) {
7284
+ const idx = parseInt(rm[1], 10);
7285
+ return 1 <= idx && idx <= args.length ? args[idx - 1] : null;
7286
+ }
7287
+ return tok.startsWith("$") ? null : tok;
7288
+ };
7289
+ const lv = resolve12(left);
7290
+ const rv = resolve12(right);
7291
+ if (lv === null || rv === null) return null;
7292
+ if (op === "=~") {
7293
+ let re = rv;
7294
+ if (re.startsWith("/") && re.endsWith("/") && re.length > 1) re = re.slice(1, -1);
7295
+ try {
7296
+ return new RegExp(re).test(lv);
7297
+ } catch {
7298
+ return null;
7299
+ }
7300
+ }
7301
+ const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
7302
+ return op === "!=" ? !matched : matched;
7252
7303
  }
7253
7304
  function parseIf(content, args) {
7254
7305
  const m = content.match(/\bif\s+([^\n;]+?)\s*;\s*then/i);
@@ -7789,41 +7840,6 @@ function scanExtensionPatterns(ext, content) {
7789
7840
  }
7790
7841
  return null;
7791
7842
  }
7792
- function scanScriptChainWithL1(chain, input, ext) {
7793
- for (const node of chain.nodes) {
7794
- if (node.error || !node.preprocessedContent || node.l1Hit) continue;
7795
- const virtualInput = {
7796
- ...input,
7797
- aNext: { actionType: "bash", actionDetail: node.preprocessedContent }
7798
- };
7799
- const l1 = scanDangerousCommandPatterns("bash", node.preprocessedContent, input.osType);
7800
- const extHit = scanExtensionPatterns(ext, node.preprocessedContent);
7801
- if (extHit) {
7802
- node.l1Hit = true;
7803
- node.l1RiskLevel = extHit.riskLevel;
7804
- node.l1RiskType = extHit.riskType;
7805
- node.l1Reason = extHit.reason;
7806
- if (extHit.riskLevel === "critical") {
7807
- chain.hasCritical = true;
7808
- chain.firstHitNode = node;
7809
- break;
7810
- }
7811
- continue;
7812
- }
7813
- if (l1 && !l1.allowed) {
7814
- node.l1Hit = true;
7815
- node.l1RiskLevel = l1.riskLevel;
7816
- node.l1RiskType = l1.riskType;
7817
- node.l1Reason = l1.reason;
7818
- if (l1.riskLevel === "critical") {
7819
- chain.hasCritical = true;
7820
- chain.firstHitNode = node;
7821
- break;
7822
- }
7823
- }
7824
- }
7825
- return chain;
7826
- }
7827
7843
  function scanScriptChainWithL2(chain, input) {
7828
7844
  for (const node of chain.nodes) {
7829
7845
  if (node.error || !node.preprocessedContent) continue;
@@ -7889,6 +7905,16 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
7889
7905
  resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
7890
7906
  }
7891
7907
  const l1Adapter = (content) => {
7908
+ const extHit = scanExtensionPatterns(ext, content);
7909
+ if (extHit) {
7910
+ return {
7911
+ hit: true,
7912
+ riskLevel: extHit.riskLevel,
7913
+ riskType: extHit.riskType,
7914
+ reason: extHit.reason,
7915
+ matchedPatterns: []
7916
+ };
7917
+ }
7892
7918
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
7893
7919
  if (j && !j.allowed) {
7894
7920
  return {
@@ -7912,7 +7938,6 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
7912
7938
  );
7913
7939
  const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
7914
7940
  if (chain.nodes.length === 0) return chain;
7915
- scanScriptChainWithL1(chain, input, ext);
7916
7941
  scanScriptChainWithL2(chain, input);
7917
7942
  scanScriptChainKeywords(chain);
7918
7943
  return chain;
@@ -8400,8 +8425,8 @@ var init_metrics = __esm({
8400
8425
  };
8401
8426
  ANALYZE_TOTAL = new Counter(
8402
8427
  "agent_moss_analyze_total",
8403
- "Total analyze requests handled, by decision and risk level.",
8404
- ["decision", "risk_level"]
8428
+ "Total analyze requests handled, by decision, risk level and L3 outcome.",
8429
+ ["decision", "risk_level", "l3_outcome"]
8405
8430
  );
8406
8431
  ANALYZE_DURATION = new Histogram(
8407
8432
  "agent_moss_analyze_duration_seconds",
@@ -8684,6 +8709,42 @@ var init_token_stats = __esm({
8684
8709
  import { createHash as createHash3 } from "crypto";
8685
8710
  import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
8686
8711
  import OpenAI from "openai";
8712
+ function reasoningTextFallback(raw) {
8713
+ if (typeof raw !== "string") return "";
8714
+ let text = raw.trim();
8715
+ if (text.startsWith("```")) {
8716
+ text = text.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "").trim();
8717
+ }
8718
+ if (!(text.startsWith("{") && text.endsWith("}"))) return "";
8719
+ let parsed;
8720
+ try {
8721
+ parsed = JSON.parse(text);
8722
+ } catch {
8723
+ return "";
8724
+ }
8725
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
8726
+ if ("allowed" in parsed || "decision" in parsed || "risk_level" in parsed) {
8727
+ return text;
8728
+ }
8729
+ }
8730
+ return "";
8731
+ }
8732
+ function reasoningFallbackWithField(message) {
8733
+ if (!message || typeof message !== "object") return { text: "", field: "" };
8734
+ for (const key of ["reasoning", "reasoning_content", "thinking"]) {
8735
+ const got = reasoningTextFallback(message[key]);
8736
+ if (got) return { text: got, field: key };
8737
+ }
8738
+ return { text: "", field: "" };
8739
+ }
8740
+ function describeContentState(raw) {
8741
+ if (raw === null) return "null";
8742
+ if (raw === void 0) return "undefined";
8743
+ const text = typeof raw === "string" ? raw : String(raw);
8744
+ if (text === "") return "empty_string";
8745
+ if (!text.trim()) return `whitespace_only(${text.length})`;
8746
+ return `non_empty(${text.length})`;
8747
+ }
8687
8748
  function responseFieldLengths(message) {
8688
8749
  if (!message || typeof message !== "object") return {};
8689
8750
  const out = {};
@@ -8941,6 +9002,7 @@ function formatHints(previous) {
8941
9002
  async function analyzeWithLLM(prompt, config) {
8942
9003
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
8943
9004
  const _llmStart = performance.now();
9005
+ let usedReasoningFallback = false;
8944
9006
  const _recordLlm = (result) => {
8945
9007
  try {
8946
9008
  LLM_CALLS_TOTAL.inc(1, { result });
@@ -8976,7 +9038,7 @@ async function analyzeWithLLM(prompt, config) {
8976
9038
  } catch {
8977
9039
  }
8978
9040
  _recordLlm("error");
8979
- throw new Error(
9041
+ throw new LLMCircuitOpenError(
8980
9042
  "LLM \u8C03\u7528\u5DF2\u7194\u65AD\uFF08\u8FDE\u7EED\u5931\u8D25\u8FC7\u591A\uFF09\uFF0C\u51B7\u5374\u671F\u5185\u4E0D\u518D\u53D1\u8D77\u8BF7\u6C42\uFF1B\u68C0\u67E5\u6A21\u578B\u670D\u52A1\u53EF\u7528\u6027\uFF0C\u6216\u8C03 AGENT_MOSS_LLM_CIRCUIT_COOLDOWN"
8981
9043
  );
8982
9044
  }
@@ -8998,10 +9060,21 @@ async function analyzeWithLLM(prompt, config) {
8998
9060
  ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
8999
9061
  });
9000
9062
  const message = response.choices[0]?.message;
9001
- const content = message?.content ?? "";
9063
+ let content = message?.content ?? "";
9002
9064
  const finishReason = response.choices[0]?.finish_reason;
9003
9065
  const fieldLengths = responseFieldLengths(message);
9004
9066
  const usage = response.usage;
9067
+ if (!content) {
9068
+ const { text: fallback, field } = reasoningFallbackWithField(message);
9069
+ if (fallback) {
9070
+ const origState = describeContentState(message?.content);
9071
+ console.warn(
9072
+ `[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`
9073
+ );
9074
+ content = fallback;
9075
+ usedReasoningFallback = true;
9076
+ }
9077
+ }
9005
9078
  if (!content) {
9006
9079
  const detail = `model=${response.model || config.model} finish_reason=${finishReason} ` + (Object.keys(fieldLengths).length ? Object.entries(fieldLengths).map(([k, v]) => `${k}_len=${v}`).join(" ") : `all_empty message_keys=${message ? Object.keys(message).join(",") : "(none)"}`) + ` tokens=${usage?.prompt_tokens ?? "?"}/${usage?.completion_tokens ?? "?"}`;
9007
9080
  traceFull("l3.empty_response", {
@@ -9074,7 +9147,9 @@ async function analyzeWithLLM(prompt, config) {
9074
9147
  riskLevel: ["low", "medium", "high", "critical"].includes(riskLevel) ? riskLevel : "low",
9075
9148
  riskType: riskType || "",
9076
9149
  confidence: typeof parsed.confidence === "number" ? Math.min(100, Math.max(0, parsed.confidence)) : 70,
9077
- source: "llm",
9150
+ // 判定结果一样可用,但运维要能看出模型行为异常
9151
+ // (下游据此填 l3Outcome 与 degraded)。
9152
+ source: usedReasoningFallback ? "llm_reasoning_fallback" : "llm",
9078
9153
  violatedLayers: ["L3.1"]
9079
9154
  };
9080
9155
  } catch (err) {
@@ -9100,7 +9175,7 @@ async function analyzeWithLLM(prompt, config) {
9100
9175
  clearTimeout(totalTimeoutTimer);
9101
9176
  throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
9102
9177
  }
9103
- var llmCache, LLM_CACHE_MAX;
9178
+ var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
9104
9179
  var init_llm_analyzer = __esm({
9105
9180
  "src/engine/llm-analyzer.ts"() {
9106
9181
  "use strict";
@@ -9114,6 +9189,12 @@ var init_llm_analyzer = __esm({
9114
9189
  init_trace_log();
9115
9190
  init_metrics();
9116
9191
  init_circuit_breaker();
9192
+ LLMCircuitOpenError = class extends Error {
9193
+ constructor(message) {
9194
+ super(message);
9195
+ this.name = "LLMCircuitOpenError";
9196
+ }
9197
+ };
9117
9198
  llmCache = /* @__PURE__ */ new Map();
9118
9199
  LLM_CACHE_MAX = 200;
9119
9200
  }
@@ -9963,7 +10044,7 @@ var init_curator = __esm({
9963
10044
  });
9964
10045
 
9965
10046
  // src/brain/contributor.ts
9966
- import { dirname as dirname10 } from "path";
10047
+ import { dirname as dirname11 } from "path";
9967
10048
  import { fileURLToPath as fileURLToPath9 } from "url";
9968
10049
  var __dirname8;
9969
10050
  var init_contributor = __esm({
@@ -9973,7 +10054,7 @@ var init_contributor = __esm({
9973
10054
  init_rule_store();
9974
10055
  init_skill_manager();
9975
10056
  init_asset_dir();
9976
- __dirname8 = dirname10(fileURLToPath9(import.meta.url));
10057
+ __dirname8 = dirname11(fileURLToPath9(import.meta.url));
9977
10058
  }
9978
10059
  });
9979
10060
 
@@ -11841,9 +11922,24 @@ import * as os3 from "os";
11841
11922
  import * as path6 from "path";
11842
11923
  import { createHash as createHash4 } from "crypto";
11843
11924
  function defaultStateDbPath() {
11844
- const dir = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
11925
+ const base = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
11926
+ const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
11927
+ const dir = instance ? path6.join(base, instance) : base;
11845
11928
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
11846
- return path6.join(dir, `stateful_chains_${tag}.json`);
11929
+ const target = path6.join(dir, `stateful_chains_${tag}.json`);
11930
+ if (instance) {
11931
+ const legacy = path6.join(base, `stateful_chains_${tag}.json`);
11932
+ if (!fs5.existsSync(target) && fs5.existsSync(legacy)) {
11933
+ try {
11934
+ fs5.mkdirSync(dir, { recursive: true });
11935
+ fs5.copyFileSync(legacy, target);
11936
+ console.warn(`[AgentMoss] \u94FE\u72B6\u6001\u6587\u4EF6\u6309 instance \u9694\u79BB\uFF1A\u5DF2\u4ECE\u65E7\u5171\u4EAB\u6587\u4EF6\u590D\u5236\u5230 ${target}`);
11937
+ } catch (err) {
11938
+ console.warn("[AgentMoss] \u8FC1\u79FB\u94FE\u72B6\u6001\u6587\u4EF6\u5931\u8D25\uFF08\u5C06\u4F7F\u7528\u65B0\u7A7A\u6587\u4EF6\uFF09:", err);
11939
+ }
11940
+ }
11941
+ }
11942
+ return target;
11847
11943
  }
11848
11944
  function registerExitFlush(store) {
11849
11945
  if (_exitHookRegistered) return;
@@ -12501,6 +12597,7 @@ async function runAnalysis(input) {
12501
12597
  pathContext
12502
12598
  });
12503
12599
  } catch (e) {
12600
+ const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
12504
12601
  const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
12505
12602
  if (getLLMFailMode2() === "fail_open") {
12506
12603
  console.warn(`[AgentMoss] LLM \u5206\u6790\u5931\u8D25\uFF0Cfail_open \u6A21\u5F0F\uFF1A\u5141\u8BB8\u6267\u884C\uFF08\u524D\u4E24\u5C42\u672A\u62E6\u622A\uFF09: ${e.message}`);
@@ -12510,7 +12607,7 @@ async function runAnalysis(input) {
12510
12607
  riskLevel: "low",
12511
12608
  riskType: "",
12512
12609
  confidence: 50,
12513
- source: "llm_failure_fallback",
12610
+ source: failSource,
12514
12611
  violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
12515
12612
  };
12516
12613
  }
@@ -12520,7 +12617,7 @@ async function runAnalysis(input) {
12520
12617
  riskLevel: "medium",
12521
12618
  riskType: "",
12522
12619
  confidence: 60,
12523
- source: "llm_failure_fallback",
12620
+ source: failSource,
12524
12621
  violatedLayers: ["L3.1"]
12525
12622
  };
12526
12623
  }
@@ -12727,17 +12824,8 @@ init_paths();
12727
12824
  import { cors } from "hono/cors";
12728
12825
  import { logger } from "hono/logger";
12729
12826
  import net from "net";
12730
- import { existsSync as existsSync21, writeFileSync as writeFileSync6, renameSync as renameSync3, mkdirSync as mkdirSync8 } from "fs";
12731
- import { dirname as dirname14, join as join21 } from "path";
12732
-
12733
- // src/routes.ts
12734
- init_esm_shims();
12735
- init_security_policy();
12736
- import { randomBytes as randomBytes2 } from "crypto";
12737
-
12738
- // src/models.ts
12739
- init_esm_shims();
12740
- import { z } from "zod";
12827
+ import { existsSync as existsSync21, writeFileSync as writeFileSync6, renameSync as renameSync3, mkdirSync as mkdirSync9 } from "fs";
12828
+ import { dirname as dirname15 } from "path";
12741
12829
 
12742
12830
  // src/package-json.ts
12743
12831
  init_esm_shims();
@@ -12746,7 +12834,14 @@ var require2 = createRequire(import.meta.url);
12746
12834
  var pkg = require2("../package.json");
12747
12835
  var version = pkg.version;
12748
12836
 
12837
+ // src/routes.ts
12838
+ init_esm_shims();
12839
+ init_security_policy();
12840
+ import { randomBytes as randomBytes2 } from "crypto";
12841
+
12749
12842
  // src/models.ts
12843
+ init_esm_shims();
12844
+ import { z } from "zod";
12750
12845
  var isNonEmptyNoControl = (v) => v.trim().length > 0 && ![...v].some((c) => {
12751
12846
  const n = c.codePointAt(0) ?? 0;
12752
12847
  return n < 32 || n >= 127 && n <= 159;
@@ -12805,6 +12900,20 @@ var AnalyzeResponseSchema = z.object({
12805
12900
  violation_chain: z.array(z.array(z.union([z.string(), z.number()]).nullable())).default([]),
12806
12901
  // 本次判定的能力降级说明(2026-11):正常为空;链状态触顶时说明 L2.2 未覆盖
12807
12902
  degraded: z.array(z.string()).default([]),
12903
+ // 本次 L3(LLM 语义分析)的实际结局(2026-11,稳定枚举,对齐 Python):
12904
+ // 让调用方不读日志就能区分「L3 认真判过的 Allow」和「L3 挂了 fail_open 放的」。
12905
+ l3_outcome: z.enum([
12906
+ "ok",
12907
+ "reasoning_fallback",
12908
+ "not_reached",
12909
+ "skipped",
12910
+ "fail_open",
12911
+ "fail_closed",
12912
+ "failed_but_blocked",
12913
+ "circuit_open",
12914
+ ""
12915
+ // 未算出(极端异常路径)
12916
+ ]).default(""),
12808
12917
  // 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
12809
12918
  violation_graph: z.object({
12810
12919
  // 性质元信息(前端展示"违反了哪条性质")
@@ -12888,6 +12997,19 @@ import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
12888
12997
  import { tmpdir as tmpdir3 } from "os";
12889
12998
  import { join as join17, resolve as resolve11 } from "path";
12890
12999
 
13000
+ // src/engine/types.ts
13001
+ init_esm_shims();
13002
+ function deriveL3Outcome(j) {
13003
+ const src = (j.source || "").toLowerCase();
13004
+ if (src === "llm" || src === "llm_extracted") return "ok";
13005
+ if (src === "llm_reasoning_fallback") return "reasoning_fallback";
13006
+ if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
13007
+ if (src === "llm_circuit_open") return "circuit_open";
13008
+ if (src === "llm_failure_with_violation") return "failed_but_blocked";
13009
+ if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
13010
+ return "not_reached";
13011
+ }
13012
+
12891
13013
  // src/infra/policy-cache.ts
12892
13014
  init_esm_shims();
12893
13015
  init_security_policy();
@@ -13233,9 +13355,15 @@ function allowResult(policy, judgment) {
13233
13355
  violated_layers: judgment.violatedLayers || [],
13234
13356
  policy,
13235
13357
  violated_policy: "",
13236
- confidence: judgment.confidence
13358
+ confidence: judgment.confidence,
13359
+ // 判定成功算出时才推导(对齐 Python `_finalize`)
13360
+ ...judgment.source !== void 0 ? { l3_outcome: deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed ?? true }) } : {}
13237
13361
  };
13238
13362
  }
13363
+ function withL3(res, judgment) {
13364
+ res.l3_outcome = deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed });
13365
+ return res;
13366
+ }
13239
13367
  async function analyze(input) {
13240
13368
  const mossLog = new MossLogger(input.sessionId);
13241
13369
  try {
@@ -13262,7 +13390,7 @@ async function analyzeInner(input, mossLog) {
13262
13390
  const judgment = await runAnalysis(input);
13263
13391
  mossLog.endStep(
13264
13392
  "step1_security_judge",
13265
- `allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}`
13393
+ `allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}, l3_outcome=${deriveL3Outcome(judgment)}`
13266
13394
  );
13267
13395
  if (!judgment.allowed) {
13268
13396
  const denied = {
@@ -13278,7 +13406,7 @@ async function analyzeInner(input, mossLog) {
13278
13406
  violation_chain: judgment.violationChain ?? []
13279
13407
  };
13280
13408
  mossLog.logResult("Deny", denied.reason);
13281
- return denied;
13409
+ return withL3(denied, judgment);
13282
13410
  }
13283
13411
  const cache3 = getDefaultCache();
13284
13412
  mossLog.startStep("step2_cache_lookup");
@@ -13288,7 +13416,7 @@ async function analyzeInner(input, mossLog) {
13288
13416
  savePolicyToFile(input.sessionId, cached2);
13289
13417
  const res = allowResult(cached2, judgment);
13290
13418
  mossLog.logResult("Allow", res.reason, cached2);
13291
- return res;
13419
+ return withL3(res, judgment);
13292
13420
  }
13293
13421
  if (!isPolicyGenEnabled()) {
13294
13422
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0CPolicy \u751F\u6210\u5DF2\u7981\u7528");
@@ -13298,7 +13426,7 @@ async function analyzeInner(input, mossLog) {
13298
13426
  const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
13299
13427
  mossLog.endStep("step2_default_policy", "\u4F7F\u7528\u9ED8\u8BA4\u6700\u5C0F\u6743\u9650 Policy");
13300
13428
  mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
13301
- return res;
13429
+ return withL3(res, judgment);
13302
13430
  }
13303
13431
  if (judgment.source === "whitelist_bypass") {
13304
13432
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u767D\u540D\u5355\u5DE5\u5177");
@@ -13306,7 +13434,7 @@ async function analyzeInner(input, mossLog) {
13306
13434
  savePolicyToFile(input.sessionId, DEFAULT_READONLY_POLICY);
13307
13435
  const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
13308
13436
  mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
13309
- return res;
13437
+ return withL3(res, judgment);
13310
13438
  }
13311
13439
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u542F\u7528 LLM \u751F\u6210");
13312
13440
  mossLog.startStep("step2_generate_policy");
@@ -13317,7 +13445,7 @@ async function analyzeInner(input, mossLog) {
13317
13445
  mossLog.endStep("step2_generate_policy", "Policy \u751F\u6210\u5E76\u7F13\u5B58\u6210\u529F");
13318
13446
  const res = allowResult(policy, judgment);
13319
13447
  mossLog.logResult("Allow", res.reason, policy);
13320
- return res;
13448
+ return withL3(res, judgment);
13321
13449
  } catch (err) {
13322
13450
  mossLog.endStep("step2_generate_policy", `\u5931\u8D25: ${String(err)}`);
13323
13451
  mossLog.logError("step2_generate_policy", err);
@@ -13332,7 +13460,7 @@ async function analyzeInner(input, mossLog) {
13332
13460
  confidence: judgment.confidence
13333
13461
  };
13334
13462
  mossLog.logResult("Deny", failed.reason);
13335
- return failed;
13463
+ return withL3(failed, judgment);
13336
13464
  }
13337
13465
  }
13338
13466
 
@@ -13746,9 +13874,9 @@ function poolsSnapshot() {
13746
13874
 
13747
13875
  // src/routes.ts
13748
13876
  init_metrics();
13749
- import { join as join19, dirname as dirname12 } from "path";
13877
+ import { join as join19, dirname as dirname13 } from "path";
13750
13878
  import { fileURLToPath as fileURLToPath10 } from "url";
13751
- var __dirname9 = dirname12(fileURLToPath10(import.meta.url));
13879
+ var __dirname9 = dirname13(fileURLToPath10(import.meta.url));
13752
13880
  async function healthRoute(c) {
13753
13881
  const metrics = {};
13754
13882
  try {
@@ -13898,6 +14026,24 @@ async function analyzeRoute(c) {
13898
14026
  llmLogPath: req.metadata?.llm_log_path
13899
14027
  });
13900
14028
  const durationMs = performance.now() - t0;
14029
+ const _l3FailMsg = String(result.reason || "").slice(0, 160);
14030
+ if (result.l3_outcome === "reasoning_fallback") {
14031
+ degradedNotes.push(
14032
+ "\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"
14033
+ );
14034
+ } else if (result.l3_outcome === "fail_open") {
14035
+ degradedNotes.push(
14036
+ `\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`
14037
+ );
14038
+ } else if (result.l3_outcome === "fail_closed") {
14039
+ degradedNotes.push(
14040
+ `\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`
14041
+ );
14042
+ } else if (result.l3_outcome === "circuit_open") {
14043
+ degradedNotes.push(
14044
+ `\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`
14045
+ );
14046
+ }
13901
14047
  const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
13902
14048
  if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
13903
14049
  console.warn(
@@ -13905,7 +14051,11 @@ async function analyzeRoute(c) {
13905
14051
  );
13906
14052
  }
13907
14053
  try {
13908
- ANALYZE_TOTAL.inc(1, { decision: result.decision, risk_level: result.risk_level });
14054
+ ANALYZE_TOTAL.inc(1, {
14055
+ decision: result.decision,
14056
+ risk_level: result.risk_level,
14057
+ l3_outcome: result.l3_outcome || ""
14058
+ });
13909
14059
  ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
13910
14060
  for (const layer of result.violated_layers || []) {
13911
14061
  LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
@@ -13919,7 +14069,9 @@ async function analyzeRoute(c) {
13919
14069
  risk_type: result.risk_type,
13920
14070
  reason: result.reason,
13921
14071
  violated_layers: result.violated_layers,
13922
- duration_ms: Math.round(durationMs * 10) / 10
14072
+ duration_ms: Math.round(durationMs * 10) / 10,
14073
+ // 2026-11:L3 结局(区分「L3 判过」与「L3 挂了放的」)
14074
+ l3_outcome: result.l3_outcome || ""
13923
14075
  });
13924
14076
  try {
13925
14077
  reportEnforcementEvent({
@@ -14010,7 +14162,10 @@ async function analyzeRoute(c) {
14010
14162
  violation_chain: result.violation_chain ?? [],
14011
14163
  violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
14012
14164
  // 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
14013
- degraded: degradedNotes
14165
+ degraded: degradedNotes,
14166
+ // L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
14167
+ // 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
14168
+ l3_outcome: result.l3_outcome || ""
14014
14169
  })
14015
14170
  );
14016
14171
  } catch (err) {
@@ -14253,9 +14408,9 @@ init_rules_mode();
14253
14408
  import { Hono } from "hono";
14254
14409
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
14255
14410
  import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
14256
- import { join as join20, dirname as dirname13 } from "path";
14411
+ import { join as join20, dirname as dirname14 } from "path";
14257
14412
  import { fileURLToPath as fileURLToPath11 } from "url";
14258
- var __dirname10 = dirname13(fileURLToPath11(import.meta.url));
14413
+ var __dirname10 = dirname14(fileURLToPath11(import.meta.url));
14259
14414
  var STATIC_DIR = join20(__dirname10, "static");
14260
14415
  var CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
14261
14416
  function getConsoleToken() {
@@ -14495,7 +14650,7 @@ function createConsoleRouter() {
14495
14650
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
14496
14651
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
14497
14652
  }
14498
- const userPath = join20(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14653
+ const userPath = join20(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14499
14654
  const builtinDir = resolveAssetDir(__dirname10, "skills");
14500
14655
  const candidates = [
14501
14656
  ...isRuntimeConfigDisabled() ? [] : [userPath],
@@ -14926,11 +15081,14 @@ async function warmUpEngine() {
14926
15081
  }
14927
15082
  function writePortFile(port) {
14928
15083
  try {
14929
- const path8 = join21(getDataRoot(), "agent_moss_server.port.json");
14930
- mkdirSync8(dirname14(path8), { recursive: true });
15084
+ const path8 = getPortFilePath();
15085
+ mkdirSync9(dirname15(path8), { recursive: true });
14931
15086
  const payload = JSON.stringify({
14932
15087
  port,
14933
15088
  pid: process.pid,
15089
+ // instance/version 供调用方校验,避免同机多实例端口文件串台
15090
+ instance: getInstance(),
15091
+ version,
14934
15092
  started_at: (/* @__PURE__ */ new Date()).toISOString()
14935
15093
  });
14936
15094
  const tmp = `${path8}.tmp`;
@@ -14977,12 +15135,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
14977
15135
  },
14978
15136
  serve: async () => {
14979
15137
  failFastOnAuthError();
14980
- const { mkdirSync: mkdirSync9, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
14981
- const { dirname: dirname15 } = await import("path");
14982
- const dir = dirname15(socketPath);
15138
+ const { mkdirSync: mkdirSync10, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
15139
+ const { dirname: dirname16 } = await import("path");
15140
+ const dir = dirname16(socketPath);
14983
15141
  if (dir) {
14984
15142
  try {
14985
- mkdirSync9(dir, { recursive: true });
15143
+ mkdirSync10(dir, { recursive: true });
14986
15144
  } catch {
14987
15145
  }
14988
15146
  }