@kenhkl/agent-moss 0.17.45 → 0.17.46

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
@@ -2092,7 +2092,8 @@ function getSensitivePathsForOs(osType) {
2092
2092
  credential: r.credential === true ? true : void 0,
2093
2093
  readOnly: r.readOnly === true ? true : void 0,
2094
2094
  denyMode: r.denyMode || void 0,
2095
- dirDelOnly: r.dirDelOnly === true ? true : void 0
2095
+ dirDelOnly: r.dirDelOnly === true ? true : void 0,
2096
+ askOnMatch: r.askOnMatch === true ? true : void 0
2096
2097
  };
2097
2098
  const scope = _scopeOf(r.os, r.path);
2098
2099
  if (scope === "home") home.push(entry);
@@ -2198,15 +2199,15 @@ function isScriptGeneratedTarget(targetPath, writtenScripts, shellRuns) {
2198
2199
  if (!script.detail.includes(base)) continue;
2199
2200
  const scriptName = path2.basename(script.path);
2200
2201
  if (!scriptName) continue;
2201
- if (shellRuns.some((run) => run.index > script.index && run.command.includes(scriptName))) {
2202
+ if (shellRuns.some((run2) => run2.index > script.index && run2.command.includes(scriptName))) {
2202
2203
  return true;
2203
2204
  }
2204
2205
  }
2205
2206
  return false;
2206
2207
  }
2207
2208
  function parseHeadTailLimit(seg) {
2208
- const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
2209
- if (firstWord !== "head" && firstWord !== "tail") return null;
2209
+ const firstWord2 = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
2210
+ if (firstWord2 !== "head" && firstWord2 !== "tail") return null;
2210
2211
  const m = seg.match(HEAD_TAIL_LIMIT_RE);
2211
2212
  return m ? Number(m[1]) : 10;
2212
2213
  }
@@ -2239,17 +2240,17 @@ function historyReadCoverage(histType, histDetailRaw, readKeywords, writeKeyword
2239
2240
  for (const rawSeg of segments) {
2240
2241
  const seg = rawSeg.trim();
2241
2242
  if (!seg) continue;
2242
- const firstWord = seg.split(/\s+/)[0]?.toLowerCase() || "";
2243
+ const firstWord2 = seg.split(/\s+/)[0]?.toLowerCase() || "";
2243
2244
  const paths = extractFilePaths(seg);
2244
2245
  if (paths.length === 0) continue;
2245
- if (SHELL_FULL_READ_CMDS.includes(firstWord)) {
2246
+ if (SHELL_FULL_READ_CMDS.includes(firstWord2)) {
2246
2247
  if (hasTruncatingPipe) addPartial(paths, parseHeadTailLimitForPipeline(segments));
2247
2248
  else for (const p of paths) full.add(p);
2248
- } else if (firstWord === "head" || firstWord === "tail") {
2249
+ } else if (firstWord2 === "head" || firstWord2 === "tail") {
2249
2250
  addPartial(paths, parseHeadTailLimit(seg));
2250
- } else if (SHELL_PARTIAL_READ_CMDS.includes(firstWord)) {
2251
+ } else if (SHELL_PARTIAL_READ_CMDS.includes(firstWord2)) {
2251
2252
  addPartial(paths, null);
2252
- } else if (firstWord === "sed") {
2253
+ } else if (firstWord2 === "sed") {
2253
2254
  if (SED_INPLACE_RE.test(seg)) continue;
2254
2255
  const m = seg.match(SED_RANGE_RE);
2255
2256
  if (m) {
@@ -2332,8 +2333,8 @@ function appendOnlyTargets(actionDetailRaw, osType) {
2332
2333
  const p = m[1] || m[2] || m[3];
2333
2334
  if (p) out.add(p);
2334
2335
  }
2335
- const firstWord = seg.split(/\s+/)[0]?.toLowerCase() || "";
2336
- if (firstWord === "tee" && /(?:^|\s)(?:-a|--append)(?:\s|$)/.test(seg)) {
2336
+ const firstWord2 = seg.split(/\s+/)[0]?.toLowerCase() || "";
2337
+ if (firstWord2 === "tee" && /(?:^|\s)(?:-a|--append)(?:\s|$)/.test(seg)) {
2337
2338
  for (const p of extractFilePaths(seg, osType)) out.add(p);
2338
2339
  }
2339
2340
  }
@@ -2381,9 +2382,44 @@ function intentKeywordNegated(text, index) {
2381
2382
  const prefix = text.slice(Math.max(0, index - NEGATION_WINDOW), index);
2382
2383
  return NEGATION_WORDS.some((neg) => prefix.includes(neg));
2383
2384
  }
2385
+ function isMediaCleanupInWorkdir(text) {
2386
+ const segs = splitCommandSegments(text).map((s) => s.trim()).filter(Boolean);
2387
+ let cdTarget = "";
2388
+ let found = false;
2389
+ for (const seg of segs) {
2390
+ const parts = seg.split(/\s+/);
2391
+ if (!parts.length) continue;
2392
+ const head = parts[0].toLowerCase();
2393
+ if (head === "cd" || head === "pushd") {
2394
+ const target = (parts[1] || "").replace(/^['"]+|['"]+$/g, "");
2395
+ const segPaths = target.split("/").filter(Boolean);
2396
+ cdTarget = target.startsWith("/") && segPaths.length > 0 && !SYSTEM_PATH_FIRST.has(segPaths[0].toLowerCase()) && segPaths.some((p) => WORKDIR_SEGMENTS.has(p.toLowerCase())) ? target : "";
2397
+ continue;
2398
+ }
2399
+ if (head !== "rm" || !cdTarget) continue;
2400
+ const flagStr = parts.slice(1).filter((t) => t.startsWith("-")).join("").toLowerCase();
2401
+ if (flagStr.includes("r") || !flagStr.includes("f")) return false;
2402
+ const targets = parts.slice(1).filter((t) => !t.startsWith("-")).map((t) => t.replace(/^['"]+|['"]+$/g, ""));
2403
+ if (!targets.length) return false;
2404
+ for (let t of targets) {
2405
+ t = t.replace(/\\/g, "/");
2406
+ while (t.startsWith("./")) t = t.slice(2);
2407
+ if (!t || [".", "*", "?"].includes(t)) return false;
2408
+ if (t.startsWith("/") || t.split("/").includes("..")) return false;
2409
+ if (t.includes("*") || t.includes("?")) {
2410
+ if (!MEDIA_GLOB_RE.test(t)) return false;
2411
+ } else if (!MEDIA_FILE_RE.test(t)) {
2412
+ return false;
2413
+ }
2414
+ found = true;
2415
+ }
2416
+ }
2417
+ return found;
2418
+ }
2384
2419
  function isBuildArtifactCleanup(actionDetail) {
2385
2420
  const text = (actionDetail || "").trim();
2386
2421
  if (!text) return false;
2422
+ if (isMediaCleanupInWorkdir(text)) return true;
2387
2423
  let foundRm = false;
2388
2424
  const targets = [];
2389
2425
  for (const raw of splitCommandSegments(text)) {
@@ -2494,6 +2530,17 @@ function intentMatrixViolation(intents, actionCat) {
2494
2530
  }
2495
2531
  return null;
2496
2532
  }
2533
+ function getIntentPatternsForOs(osType) {
2534
+ const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
2535
+ if (effective) {
2536
+ return effective.map((p) => ({
2537
+ ...p,
2538
+ allowIfWriteIntent: p.allowIfWriteIntent ?? INTENT_DEVIATION_PATTERNS.find((d) => d.reason === p.reason)?.allowIfWriteIntent ?? false
2539
+ }));
2540
+ }
2541
+ const accepted = acceptedOsValues(osType);
2542
+ return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
2543
+ }
2497
2544
  function resolveIntentText(promptSession, promptHistory, intentKeywords) {
2498
2545
  const cur = (promptSession || "").trim().toLowerCase();
2499
2546
  if (intentKeywords.some((kw) => cur.includes(kw))) return cur;
@@ -2583,6 +2630,14 @@ function checkIntentConsistency(input, agentExt) {
2583
2630
  };
2584
2631
  }
2585
2632
  if (reasonKey !== null) {
2633
+ let askReason = "";
2634
+ for (const pat of getIntentPatternsForOs(input.osType)) {
2635
+ if (!pat.askOnMatch) continue;
2636
+ if ((pat.intentKeywords || []).some((k) => intentText.includes(String(k).toLowerCase())) && (pat.dangerousActions || []).some((a) => actionDetail.includes(String(a).toLowerCase()))) {
2637
+ askReason = `\u89C4\u5219\u300C${pat.reason}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237`;
2638
+ break;
2639
+ }
2640
+ }
2586
2641
  return {
2587
2642
  allowed: false,
2588
2643
  reason: INTENT_REASONS[reasonKey] || "\u539F\u59CB\u610F\u56FE\u4E0E\u6267\u884C\u52A8\u4F5C\u4E0D\u4E00\u81F4",
@@ -2590,7 +2645,8 @@ function checkIntentConsistency(input, agentExt) {
2590
2645
  riskType: "intent_deviation",
2591
2646
  confidence: 85,
2592
2647
  source: "logic_rule",
2593
- violatedLayers: ["L2.1"]
2648
+ violatedLayers: ["L2.1"],
2649
+ ...askReason ? { ask_recommended: true, ask_reason: askReason } : {}
2594
2650
  };
2595
2651
  }
2596
2652
  if ((actionCat === "overwrite" || actionCat === "delete") && intents.size === 0) {
@@ -2652,6 +2708,25 @@ function runLogicCheck(input, opts) {
2652
2708
  if (comboResult) return comboResult;
2653
2709
  return null;
2654
2710
  }
2711
+ function computeComboStageHits(detail) {
2712
+ const hits = /* @__PURE__ */ new Set();
2713
+ for (const [stage, pats] of Object.entries(COMBO_STAGES)) {
2714
+ if (pats.some((p) => {
2715
+ p.lastIndex = 0;
2716
+ return p.test(detail);
2717
+ })) hits.add(stage);
2718
+ }
2719
+ return hits;
2720
+ }
2721
+ function comboStageHits(detail) {
2722
+ if (detail.length > 2048) return computeComboStageHits(detail);
2723
+ const cached2 = comboStageHitsCache.get(detail);
2724
+ if (cached2) return cached2;
2725
+ const value = computeComboStageHits(detail);
2726
+ if (comboStageHitsCache.size >= COMBO_STAGE_CACHE_MAX) comboStageHitsCache.clear();
2727
+ comboStageHitsCache.set(detail, value);
2728
+ return value;
2729
+ }
2655
2730
  function checkComboChain(actionHistory, actionDetailRaw) {
2656
2731
  INLINE_SCRIPT_RE.lastIndex = 0;
2657
2732
  if (INLINE_SCRIPT_RE.test(actionDetailRaw)) return null;
@@ -2660,16 +2735,7 @@ function checkComboChain(actionHistory, actionDetailRaw) {
2660
2735
  if (h.actionDetail) details.push(h.actionDetail.toLowerCase());
2661
2736
  }
2662
2737
  details.push(actionDetailRaw.toLowerCase());
2663
- const seq = details.map((d) => {
2664
- const hits = /* @__PURE__ */ new Set();
2665
- for (const [stage, pats] of Object.entries(COMBO_STAGES)) {
2666
- if (pats.some((p) => {
2667
- p.lastIndex = 0;
2668
- return p.test(d);
2669
- })) hits.add(stage);
2670
- }
2671
- return hits;
2672
- });
2738
+ const seq = details.map((d) => comboStageHits(d));
2673
2739
  for (const chain of COMBO_CHAINS) {
2674
2740
  const chainStages = chain.stages;
2675
2741
  if (!chainStages.length || chain.min_stages <= 0) continue;
@@ -2776,15 +2842,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2776
2842
  for (const seg of singleFileTool ? [] : splitCommandSegments(actionDetailRaw)) {
2777
2843
  const trimmed = seg.trim();
2778
2844
  if (!trimmed) continue;
2779
- const firstWord = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
2780
- if (firstWord === "cd") {
2845
+ const firstWord2 = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
2846
+ if (firstWord2 === "cd") {
2781
2847
  continue;
2782
2848
  }
2783
2849
  if (SHELL_ASSIGN_RE.test(trimmed)) {
2784
2850
  continue;
2785
2851
  }
2786
- if (firstWord === "sed" && SED_INPLACE_RE.test(trimmed)) {
2787
- } else if (getPlatformTraits(osType).readOnlyCommands.has(firstWord)) {
2852
+ if (firstWord2 === "sed" && SED_INPLACE_RE.test(trimmed)) {
2853
+ } else if (getPlatformTraits(osType).readOnlyCommands.has(firstWord2)) {
2788
2854
  const segUnquoted = trimmed.replace(new RegExp(`>{1,2}\\s*(['"])([~./][^'"]+)\\1`, "g"), (_m, _q, p) => ">" + p);
2789
2855
  const segNoDevnull = segUnquoted.replace(DEVNULL_REDIRECT_RE, "");
2790
2856
  const segNoQuotes = segNoDevnull.replace(/'[^']*'|"[^"]*"/g, "");
@@ -2793,15 +2859,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2793
2859
  continue;
2794
2860
  }
2795
2861
  const segPaths = extractFilePaths(trimmed, osType);
2796
- const segPathsFiltered = firstWord === "wget" || firstWord === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
2797
- if (SOURCE_ARG_CMDS.has(firstWord)) {
2862
+ const segPathsFiltered = firstWord2 === "wget" || firstWord2 === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
2863
+ if (SOURCE_ARG_CMDS.has(firstWord2)) {
2798
2864
  if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
2799
- } else if (firstWord === "tar") {
2865
+ } else if (firstWord2 === "tar") {
2800
2866
  if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
2801
2867
  const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
2802
2868
  if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
2803
2869
  }
2804
- } else if (firstWord === "dd") {
2870
+ } else if (firstWord2 === "dd") {
2805
2871
  const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
2806
2872
  const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
2807
2873
  const devNullMatches = trimmed.match(/\bof=(\/dev\/\S+)/g);
@@ -2973,7 +3039,8 @@ function hasValidConsent(actionHistory, aNext) {
2973
3039
  }
2974
3040
  function checkPasswordConsent(actionType, actionDetail, actionHistory, osType, aNext) {
2975
3041
  if (!BASH_LIKE_ACTION_TYPES.includes(actionType)) return null;
2976
- const pwdPatterns = runtimeConfigBridge.current?.effectivePasswordPatterns(osType) ?? PASSWORD_MODIFY_PATTERNS;
3042
+ const pwdRules = runtimeConfigBridge.current?.effectivePasswordRules(osType) ?? PASSWORD_MODIFY_PATTERNS.map((p) => ({ pattern: p, askOnMatch: false }));
3043
+ const pwdPatterns = pwdRules.map((r) => r.pattern);
2977
3044
  let isPasswordModify = pwdPatterns.some((p) => p.test(actionDetail));
2978
3045
  if (isPasswordModify && !hasExecBypassChain(actionDetail)) {
2979
3046
  const noQuotes = actionDetail.replace(ALL_QUOTES_RE, " ");
@@ -2981,6 +3048,7 @@ function checkPasswordConsent(actionType, actionDetail, actionHistory, osType, a
2981
3048
  }
2982
3049
  if (!isPasswordModify) return null;
2983
3050
  if (hasValidConsent(actionHistory, aNext)) return null;
3051
+ const askRule = pwdRules.find((r) => r.askOnMatch && r.pattern.test(actionDetail));
2984
3052
  return {
2985
3053
  allowed: false,
2986
3054
  reason: "\u6267\u884C\u975E\u4EA4\u4E92\u5F0F\u5BC6\u7801\u4FEE\u6539\u547D\u4EE4\uFF0C\u4F46\u5386\u53F2\u6267\u884C\u5E8F\u5217\u4E2D\u672A\u53D1\u73B0\u7528\u6237\u660E\u786E\u6388\u6743\u7684 ask_user_question\uFF08\u987B\u7528\u6237\u6B63\u9762\u56DE\u7B54\u4E14\u4E0E\u672C\u6B21\u64CD\u4F5C\u76F8\u5173\uFF09\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6388\u6743\u7684\u5BC6\u7801\u4FEE\u6539\u98CE\u9669",
@@ -2988,15 +3056,18 @@ function checkPasswordConsent(actionType, actionDetail, actionHistory, osType, a
2988
3056
  riskType: "consent_missing",
2989
3057
  confidence: 85,
2990
3058
  source: "logic_rule",
2991
- violatedLayers: ["L2.1"]
3059
+ violatedLayers: ["L2.1"],
3060
+ ...askRule ? { ask_recommended: true, ask_reason: "\u5BC6\u7801\u4FEE\u6539\u89C4\u5219\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237" } : {}
2992
3061
  };
2993
3062
  }
2994
3063
  function checkUserDeletionConsent(actionType, actionDetail, actionHistory, osType, aNext) {
2995
3064
  if (!BASH_LIKE_ACTION_TYPES.includes(actionType)) return null;
2996
- const udPatterns = runtimeConfigBridge.current?.effectiveUserDeletionPatterns(osType) ?? USER_DELETION_PATTERNS;
3065
+ const udRules = runtimeConfigBridge.current?.effectiveUserDeletionRules(osType) ?? USER_DELETION_PATTERNS.map((p) => ({ pattern: p, askOnMatch: false }));
3066
+ const udPatterns = udRules.map((r) => r.pattern);
2997
3067
  const isUserDeletion = udPatterns.some((p) => p.test(actionDetail));
2998
3068
  if (!isUserDeletion) return null;
2999
3069
  if (hasValidConsent(actionHistory, aNext)) return null;
3070
+ const askRule = udRules.find((r) => r.askOnMatch && r.pattern.test(actionDetail));
3000
3071
  return {
3001
3072
  allowed: false,
3002
3073
  reason: "\u6267\u884C\u5220\u9664\u7CFB\u7EDF\u7528\u6237\u547D\u4EE4\uFF0C\u4F46\u5386\u53F2\u6267\u884C\u5E8F\u5217\u4E2D\u672A\u53D1\u73B0\u7528\u6237\u660E\u786E\u6388\u6743\u7684 ask_user_question\uFF08\u987B\u7528\u6237\u6B63\u9762\u56DE\u7B54\u4E14\u4E0E\u672C\u6B21\u64CD\u4F5C\u76F8\u5173\uFF09\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6388\u6743\u7684\u7528\u6237\u5220\u9664\u98CE\u9669",
@@ -3004,7 +3075,8 @@ function checkUserDeletionConsent(actionType, actionDetail, actionHistory, osTyp
3004
3075
  riskType: "consent_missing",
3005
3076
  confidence: 85,
3006
3077
  source: "logic_rule",
3007
- violatedLayers: ["L2.1"]
3078
+ violatedLayers: ["L2.1"],
3079
+ ...askRule ? { ask_recommended: true, ask_reason: "\u7528\u6237\u5220\u9664\u89C4\u5219\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237" } : {}
3008
3080
  };
3009
3081
  }
3010
3082
  function containsPrivilegeEscalation(actionDetail) {
@@ -3098,7 +3170,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
3098
3170
  violatedLayers: ["L2.1"]
3099
3171
  };
3100
3172
  }
3101
- 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, NEGATION_WORDS, NEGATION_WINDOW, EXPLICIT_READONLY_RE, UPDATE_INTENT_RE, EXPLICIT_NO_DELETE_RE, INTENT_AMBIGUITY_RE, BUILD_ARTIFACT_NAMES, BUILD_ARTIFACT_GLOB_RE, 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;
3173
+ 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, NEGATION_WORDS, NEGATION_WINDOW, EXPLICIT_READONLY_RE, UPDATE_INTENT_RE, EXPLICIT_NO_DELETE_RE, INTENT_AMBIGUITY_RE, BUILD_ARTIFACT_NAMES, BUILD_ARTIFACT_GLOB_RE, MEDIA_TEMP_EXTS, MEDIA_GLOB_RE, MEDIA_FILE_RE, WORKDIR_SEGMENTS, SYSTEM_PATH_FIRST, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, COMBO_STAGE_CACHE_MAX, comboStageHitsCache, 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;
3102
3174
  var init_logic_rules = __esm({
3103
3175
  "src/engine/logic-rules.ts"() {
3104
3176
  "use strict";
@@ -3225,6 +3297,48 @@ var init_logic_rules = __esm({
3225
3297
  "htmlcov"
3226
3298
  ]);
3227
3299
  BUILD_ARTIFACT_GLOB_RE = /^\*\.(?:pyc|pyo|class|o|obj|d|egg-info)$/i;
3300
+ MEDIA_TEMP_EXTS = "mp4|mov|avi|mkv|webm|flv|wmv|m4v|jpg|jpeg|png|gif|webp|bmp|tif|tiff|wav|mp3|m4a|aac|flac|ogg|tmp|part|log";
3301
+ MEDIA_GLOB_RE = new RegExp(`^[A-Za-z0-9_.-]+\\*\\.(?:${MEDIA_TEMP_EXTS})$`, "i");
3302
+ MEDIA_FILE_RE = new RegExp(`^[A-Za-z0-9_.-]+\\.(?:${MEDIA_TEMP_EXTS})$`, "i");
3303
+ WORKDIR_SEGMENTS = /* @__PURE__ */ new Set([
3304
+ "result",
3305
+ "results",
3306
+ "output",
3307
+ "outputs",
3308
+ "out",
3309
+ "work",
3310
+ "workdir",
3311
+ "work_extract",
3312
+ "tmp",
3313
+ "temp",
3314
+ "cache",
3315
+ ".cache",
3316
+ "build",
3317
+ "dist",
3318
+ "target",
3319
+ "extract",
3320
+ "extracted",
3321
+ "clips",
3322
+ "artifacts",
3323
+ "__pycache__"
3324
+ ]);
3325
+ SYSTEM_PATH_FIRST = /* @__PURE__ */ new Set([
3326
+ "etc",
3327
+ "usr",
3328
+ "bin",
3329
+ "sbin",
3330
+ "lib",
3331
+ "lib64",
3332
+ "boot",
3333
+ "root",
3334
+ "sys",
3335
+ "proc",
3336
+ "dev",
3337
+ "run",
3338
+ "srv",
3339
+ "home",
3340
+ "var"
3341
+ ]);
3228
3342
  REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
3229
3343
  REFERENCE_LOOKBACK = 3;
3230
3344
  EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
@@ -3246,6 +3360,8 @@ var init_logic_rules = __esm({
3246
3360
  reason: String(c.reason || "\u68C0\u6D4B\u5230\u7EC4\u5408\u653B\u51FB\u94FE")
3247
3361
  }));
3248
3362
  })();
3363
+ COMBO_STAGE_CACHE_MAX = 8192;
3364
+ comboStageHitsCache = /* @__PURE__ */ new Map();
3249
3365
  CONSENT_TOPIC = /密码|口令|passwd|password|凭据|凭证|用户|账户|账号|userdel|deluser|groupdel/i;
3250
3366
  CONSENT_NEGATIVE = /(?:否|不|别|取消|拒绝|停止|终止|算了|\bno\b|\bnope\b|\bcancel\b|\babort\b|\bstop\b|\bdeny\b|\breject\b|\bdecline\b|\bdon'?t\b|\bdo\s+not\b)/i;
3251
3367
  CONSENT_AFFIRMATIVE = /(?:是|好|可以|行|嗯|对|确认|同意|继续|执行|删除|删掉|移除|修改|重置|改密|\byes\b|\by\b|\byep\b|\byeah\b|\bok\b|\bokay\b|\bconfirm(?:ed)?\b|\bproceed\b|\bcontinue\b|\bsure\b|\bapprove\b|\baccept\b|\bagree\b|\bdo\s+it\b|\bgo\s+ahead\b)/i;
@@ -3428,6 +3544,7 @@ var init_skill_loader = __esm({
3428
3544
  // src/infra/runtime-config.ts
3429
3545
  var runtime_config_exports = {};
3430
3546
  __export(runtime_config_exports, {
3547
+ BUILTIN_DETECTOR_DEFAULTS: () => BUILTIN_DETECTOR_DEFAULTS,
3431
3548
  DEFAULT_LAYERS: () => DEFAULT_LAYERS,
3432
3549
  DENY_MODE_LABELS: () => DENY_MODE_LABELS,
3433
3550
  addAgentRule: () => addAgentRule,
@@ -3442,14 +3559,19 @@ __export(runtime_config_exports, {
3442
3559
  effectiveInjectionKeywords: () => effectiveInjectionKeywords,
3443
3560
  effectiveIntentPatterns: () => effectiveIntentPatterns,
3444
3561
  effectivePasswordPatterns: () => effectivePasswordPatterns,
3562
+ effectivePasswordRules: () => effectivePasswordRules,
3445
3563
  effectiveSensitivePaths: () => effectiveSensitivePaths,
3446
3564
  effectiveUserDeletionPatterns: () => effectiveUserDeletionPatterns,
3565
+ effectiveUserDeletionRules: () => effectiveUserDeletionRules,
3447
3566
  filterEnabledRules: () => filterEnabledRules,
3448
3567
  generateSourceDefaults: () => generateSourceDefaults,
3449
3568
  getAgentRules: () => getAgentRules,
3569
+ getBuiltinAskMap: () => getBuiltinAskMap,
3450
3570
  getDisabledL2RulesWithSkipL3: () => getDisabledL2RulesWithSkipL3,
3451
3571
  getDisabledSkillIds: () => getDisabledSkillIds,
3452
3572
  getEnabledAgentExtensions: () => getEnabledAgentExtensions,
3573
+ getEnabledBuiltinDetectors: () => getEnabledBuiltinDetectors,
3574
+ getEnabledBuiltinDetectorsOrCurrent: () => getEnabledBuiltinDetectorsOrCurrent,
3453
3575
  getEnabledL1CommandPatterns: () => getEnabledL1CommandPatterns,
3454
3576
  getEnabledL1CommandPatternsOrDefault: () => getEnabledL1CommandPatternsOrDefault,
3455
3577
  getEnabledL1InjectionKeywords: () => getEnabledL1InjectionKeywords,
@@ -3458,10 +3580,12 @@ __export(runtime_config_exports, {
3458
3580
  getEnabledL2IntentPatternsOrDefault: () => getEnabledL2IntentPatternsOrDefault,
3459
3581
  getEnabledL2PasswordPatterns: () => getEnabledL2PasswordPatterns,
3460
3582
  getEnabledL2PasswordPatternsOrDefault: () => getEnabledL2PasswordPatternsOrDefault,
3583
+ getEnabledL2PasswordRules: () => getEnabledL2PasswordRules,
3461
3584
  getEnabledL2SensitivePaths: () => getEnabledL2SensitivePaths,
3462
3585
  getEnabledL2SensitivePathsOrDefault: () => getEnabledL2SensitivePathsOrDefault,
3463
3586
  getEnabledL2UserDeletionPatterns: () => getEnabledL2UserDeletionPatterns,
3464
3587
  getEnabledL2UserDeletionPatternsOrDefault: () => getEnabledL2UserDeletionPatternsOrDefault,
3588
+ getEnabledL2UserDeletionRules: () => getEnabledL2UserDeletionRules,
3465
3589
  getEnabledScenarioExtensions: () => getEnabledScenarioExtensions,
3466
3590
  getEnvOverrides: () => getEnvOverrides,
3467
3591
  getProfileOrDetect: () => getProfileOrDetect,
@@ -3478,8 +3602,11 @@ __export(runtime_config_exports, {
3478
3602
  saveRuntimeConfig: () => saveRuntimeConfig,
3479
3603
  updateAgentCategoryEnabled: () => updateAgentCategoryEnabled,
3480
3604
  updateAgentRuleEnabled: () => updateAgentRuleEnabled,
3605
+ updateCategoryAsk: () => updateCategoryAsk,
3481
3606
  updateCategoryEnabled: () => updateCategoryEnabled,
3607
+ updateInjectionTierEnabled: () => updateInjectionTierEnabled,
3482
3608
  updateLayerEnabled: () => updateLayerEnabled,
3609
+ updateRuleAsk: () => updateRuleAsk,
3483
3610
  updateRuleDenyMode: () => updateRuleDenyMode,
3484
3611
  updateRuleEnabled: () => updateRuleEnabled,
3485
3612
  updateRuleSkipL3: () => updateRuleSkipL3,
@@ -3677,23 +3804,22 @@ function getEnabledL1CommandPatterns(runtime, osType) {
3677
3804
  rules = _mergeUserCustom(rules, runtime, "L1_rules", "pattern");
3678
3805
  if (osType) rules = _filterRulesByOs(rules, osType);
3679
3806
  return rules.map((r) => ({
3807
+ id: r.id || "",
3680
3808
  pattern: r.pattern || "",
3681
3809
  risk_level: r.risk_level || "",
3682
3810
  risk_type: r.risk_type || "",
3683
- reason: r.reason || ""
3811
+ reason: r.reason || "",
3812
+ ask_on_match: r.ask_on_match === true
3684
3813
  }));
3685
3814
  }
3686
3815
  function getEnabledL2SensitivePaths(runtime, osType) {
3687
- let cat = runtime.L1_rules?.sensitive_path_access;
3688
- if (!cat || !cat.rules || cat.rules.length === 0) {
3689
- cat = runtime.L2_rules?.sensitive_path_access || { category_enabled: true, rules: [] };
3690
- }
3816
+ const cat = _sensitivePathCategoryOf(runtime) || { category_enabled: true, rules: [] };
3691
3817
  let rules = filterEnabledRules(cat.rules || [], cat.category_enabled);
3692
3818
  rules = _mergeRulesFromDirs(rules, "sensitive_path_access");
3693
3819
  rules = _mergeUserCustom(rules, runtime, ["L1_rules", "L2_rules"], "path");
3694
3820
  if (osType) rules = _filterRulesByOs(rules, osType);
3695
3821
  return rules.map((r) => {
3696
- const out = { path: r.path || "", risk_level: r.risk_level || "", desc: r.desc || "", deny_mode: r.deny_mode || "deny_write" };
3822
+ const out = { id: r.id || "", path: r.path || "", risk_level: r.risk_level || "", desc: r.desc || "", deny_mode: r.deny_mode || "deny_write", ask_on_match: r.ask_on_match === true };
3697
3823
  if (r.credential) out.credential = true;
3698
3824
  if (r.read_only) out.read_only = true;
3699
3825
  if (r.dir_del_only) out.dir_del_only = true;
@@ -3798,7 +3924,8 @@ function _l1CommandPatternsToRules() {
3798
3924
  reason: p.description,
3799
3925
  enabled: true,
3800
3926
  builtin: true,
3801
- os: p.os || "linux"
3927
+ os: p.os || "linux",
3928
+ ask_on_match: p.ask_on_match === true
3802
3929
  };
3803
3930
  const fp = _ruleFingerprint(rule);
3804
3931
  if (seen.has(fp)) continue;
@@ -3814,6 +3941,7 @@ function _l1InjectionKeywordsToRules() {
3814
3941
  keyword: kw.keyword,
3815
3942
  risk_level: kw.riskLevel,
3816
3943
  lang: kw.lang || "en",
3944
+ tier: kw.tier || "",
3817
3945
  // 带上条目自己的 os(`all` = 全平台通用),别丢 —— 丢了 Windows 会拿到
3818
3946
  // 本不该给它的条目。与 Python `_l1_injection_keywords_to_rules` 对齐。
3819
3947
  os: kw.os,
@@ -3847,7 +3975,8 @@ function _l2SensitivePathsToRules() {
3847
3975
  skip_l3_on_disabled: true,
3848
3976
  enabled: true,
3849
3977
  builtin: true,
3850
- os: os6
3978
+ os: os6,
3979
+ ask_on_match: sp.ask_on_match === true
3851
3980
  };
3852
3981
  _syncDenyModeFields(rule);
3853
3982
  if (sp.dirDelOnly) rule.dir_del_only = true;
@@ -3870,7 +3999,8 @@ function _l2IntentPatternsToRules() {
3870
3999
  allow_if_write_intent: pat.allowIfWriteIntent,
3871
4000
  skip_l3_on_disabled: true,
3872
4001
  enabled: true,
3873
- builtin: true
4002
+ builtin: true,
4003
+ ask_on_match: pat.askOnMatch === true
3874
4004
  }));
3875
4005
  }
3876
4006
  function _l2PasswordPatternsToRules() {
@@ -4040,6 +4170,19 @@ function _agentRulesToDefaults() {
4040
4170
  }
4041
4171
  return out;
4042
4172
  }
4173
+ function getEnabledBuiltinDetectors(runtime) {
4174
+ const cat = runtime?.L1_rules?.builtin_detectors;
4175
+ if (!cat || typeof cat !== "object") {
4176
+ return new Set(BUILTIN_DETECTOR_DEFAULTS.map((r) => r.id));
4177
+ }
4178
+ if (cat.category_enabled === false) return /* @__PURE__ */ new Set();
4179
+ return new Set(
4180
+ (cat.rules || []).filter((r) => r && r.id && r.enabled !== false && !r.source_removed).map((r) => String(r.id))
4181
+ );
4182
+ }
4183
+ function getEnabledBuiltinDetectorsOrCurrent() {
4184
+ return getEnabledBuiltinDetectors(loadRuntimeConfig());
4185
+ }
4043
4186
  function generateSourceDefaults() {
4044
4187
  return {
4045
4188
  version: 1,
@@ -4052,7 +4195,8 @@ function generateSourceDefaults() {
4052
4195
  },
4053
4196
  injection_detection: {
4054
4197
  category_enabled: true,
4055
- category_desc: "Prompt \u6CE8\u5165\u653B\u51FB\u68C0\u6D4B",
4198
+ tier_enabled: { strong: true, weak: true },
4199
+ category_desc: "\u53EF\u7591\u6CE8\u5165\u7279\u5F81\uFF08\u53EA\u4F5C\u4E3A L3 \u7EBF\u7D22\uFF0C\u4E0D\u76F4\u63A5\u62E6\u622A\uFF09",
4056
4200
  rules: _l1InjectionKeywordsToRules()
4057
4201
  },
4058
4202
  sensitive_path_access: {
@@ -4060,6 +4204,11 @@ function generateSourceDefaults() {
4060
4204
  category_desc: "\u654F\u611F\u8DEF\u5F84\u8BBF\u95EE\u68C0\u6D4B\uFF08deny_both/deny_read/deny_write\uFF09",
4061
4205
  rules: _l2SensitivePathsToRules()
4062
4206
  },
4207
+ builtin_detectors: {
4208
+ category_enabled: true,
4209
+ category_desc: "\u4EE3\u7801\u5185\u7F6E\u68C0\u6D4B\uFF08\u5371\u9669\u6A21\u5F0F / \u4E3B\u76EE\u5F55\u5220\u9664 / \u6A2A\u5411\u79FB\u52A8 / \u89E3\u7801\u5206\u6790\uFF09",
4210
+ rules: BUILTIN_DETECTOR_DEFAULTS.map((r) => ({ ...r }))
4211
+ },
4063
4212
  user_custom: { category_enabled: true, category_desc: "\u7528\u6237\u81EA\u5B9A\u4E49\u547D\u4EE4\u89C4\u5219", rules: [] }
4064
4213
  },
4065
4214
  L2_rules: {
@@ -4159,6 +4308,7 @@ function _mergeRuleCategories(userCfg, srcDefaults, layerKey) {
4159
4308
  const existing = userByFp.get(fp);
4160
4309
  const userDisabled = existing.user_disabled === true;
4161
4310
  const userSkipL3 = existing.skip_l3_on_disabled;
4311
+ const userAsk = existing.ask_on_match;
4162
4312
  const userDenyMode = existing.deny_mode;
4163
4313
  const userSourceDeny = existing.source_deny_mode;
4164
4314
  Object.keys(existing).forEach((k) => delete existing[k]);
@@ -4166,6 +4316,7 @@ function _mergeRuleCategories(userCfg, srcDefaults, layerKey) {
4166
4316
  existing.enabled = !userDisabled;
4167
4317
  if (userDisabled) existing.user_disabled = true;
4168
4318
  if (userSkipL3 !== void 0) existing.skip_l3_on_disabled = userSkipL3;
4319
+ if (userAsk !== void 0) existing.ask_on_match = userAsk === true;
4169
4320
  if (userDenyMode && userSourceDeny && userDenyMode !== userSourceDeny) {
4170
4321
  existing.deny_mode = userDenyMode;
4171
4322
  }
@@ -4305,6 +4456,7 @@ function _migrateCategoriesAcrossLayers(cfg, srcLayer, dstLayer, catNames) {
4305
4456
  const dstCat = dst[catName];
4306
4457
  if (!dstCat.category_desc && srcCat.category_desc) dstCat.category_desc = srcCat.category_desc;
4307
4458
  if (dstCat.category_enabled === void 0) dstCat.category_enabled = srcCat.category_enabled;
4459
+ if (dstCat.tier_enabled === void 0) dstCat.tier_enabled = { ...srcCat.tier_enabled || {} };
4308
4460
  if (srcCat.rules && srcCat.rules.length > 0) {
4309
4461
  const dstFps = new Set((dstCat.rules || []).map((r) => _ruleFingerprint(r)));
4310
4462
  for (const r of srcCat.rules) {
@@ -4321,13 +4473,16 @@ function _migrateCategoriesAcrossLayers(cfg, srcLayer, dstLayer, catNames) {
4321
4473
  function getEnabledL1InjectionKeywords(runtime, osType) {
4322
4474
  const cat = runtime.L1_rules?.injection_detection || { category_enabled: true, rules: [] };
4323
4475
  let rules = filterEnabledRules(cat.rules || [], cat.category_enabled);
4476
+ const tierEnabled = cat.tier_enabled || {};
4477
+ rules = rules.filter((r) => !r.tier || tierEnabled[r.tier] !== false);
4324
4478
  rules = _mergeRulesFromDirs(rules, "injection_detection");
4325
4479
  rules = _mergeUserCustom(rules, runtime, "L1_rules", "keyword");
4326
4480
  if (osType) rules = _filterRulesByOs(rules, osType);
4327
4481
  return rules.map((r) => ({
4328
4482
  keyword: r.keyword || "",
4329
4483
  risk_level: r.risk_level || "",
4330
- lang: r.lang || "en"
4484
+ lang: r.lang || "en",
4485
+ tier: String(r.tier || "")
4331
4486
  }));
4332
4487
  }
4333
4488
  function getEnabledL2IntentPatterns(runtime, osType) {
@@ -4341,9 +4496,40 @@ function getEnabledL2IntentPatterns(runtime, osType) {
4341
4496
  dangerous_actions: r.dangerous_actions || [],
4342
4497
  reason: r.reason || "",
4343
4498
  allow_if_write_intent: r.allow_if_write_intent === true,
4344
- os: r.os
4499
+ os: r.os,
4500
+ id: r.id || "",
4501
+ ask_on_match: r.ask_on_match === true
4345
4502
  }));
4346
4503
  }
4504
+ function getEnabledL2PasswordRules(runtime) {
4505
+ const cat = runtime.L2_rules?.password_modify_consent || { category_enabled: true, rules: [] };
4506
+ return _mergeUserCustom(
4507
+ _mergeRulesFromDirs(filterEnabledRules(cat.rules || [], cat.category_enabled), "password_modify_consent"),
4508
+ runtime,
4509
+ "L2_rules",
4510
+ "pattern"
4511
+ );
4512
+ }
4513
+ function getEnabledL2UserDeletionRules(runtime) {
4514
+ const cat = runtime.L2_rules?.user_deletion_consent || { category_enabled: true, rules: [] };
4515
+ return _mergeUserCustom(
4516
+ _mergeRulesFromDirs(filterEnabledRules(cat.rules || [], cat.category_enabled), "user_deletion_consent"),
4517
+ runtime,
4518
+ "L2_rules",
4519
+ "pattern"
4520
+ );
4521
+ }
4522
+ function getBuiltinAskMap(runtime) {
4523
+ const cat = runtime?.L1_rules?.builtin_detectors;
4524
+ const out = {};
4525
+ if (!cat || typeof cat !== "object") return out;
4526
+ for (const r of cat.rules || []) {
4527
+ const rid = String(r?.id || "");
4528
+ if (!rid) continue;
4529
+ out[rid] = r.ask_on_match && r.enabled !== false ? `\u89C4\u5219\u300C${r.reason || rid}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237` : "";
4530
+ }
4531
+ return out;
4532
+ }
4347
4533
  function getEnabledL2PasswordPatterns(runtime) {
4348
4534
  const cat = runtime.L2_rules?.password_modify_consent || { category_enabled: true, rules: [] };
4349
4535
  const rules = _mergeUserCustom(
@@ -4475,7 +4661,8 @@ function effectiveDangerousPatterns(osType) {
4475
4661
  severity: String(r.risk_level || "medium"),
4476
4662
  riskType: String(r.risk_type || ""),
4477
4663
  description: String(r.reason || ""),
4478
- os: String(r.os || "linux").toLowerCase()
4664
+ os: String(r.os || "linux").toLowerCase(),
4665
+ askOnMatch: r.ask_on_match === true
4479
4666
  }));
4480
4667
  });
4481
4668
  }
@@ -4485,7 +4672,8 @@ function effectiveInjectionKeywords(osType) {
4485
4672
  return rules.map((r) => ({
4486
4673
  keyword: String(r.keyword || ""),
4487
4674
  riskLevel: String(r.risk_level || ""),
4488
- lang: String(r.lang || "en")
4675
+ lang: String(r.lang || "en"),
4676
+ tier: String(r.tier || "")
4489
4677
  })).filter((r) => r.keyword);
4490
4678
  });
4491
4679
  }
@@ -4500,10 +4688,23 @@ function effectiveSensitivePaths(osType) {
4500
4688
  readOnly: r.read_only === true ? true : void 0,
4501
4689
  dirDelOnly: r.dir_del_only === true ? true : void 0,
4502
4690
  denyMode: String(r.deny_mode || ""),
4503
- os: String(r.os || "linux").toLowerCase()
4691
+ os: String(r.os || "linux").toLowerCase(),
4692
+ askOnMatch: r.ask_on_match === true
4504
4693
  }));
4505
4694
  });
4506
4695
  }
4696
+ function effectivePasswordRules(osType) {
4697
+ return _effective(osType, "password_rules", (rt) => getEnabledL2PasswordRules(rt).map((r) => ({
4698
+ pattern: new RegExp(String(r.pattern || ""), "i"),
4699
+ askOnMatch: r.ask_on_match === true
4700
+ })));
4701
+ }
4702
+ function effectiveUserDeletionRules(osType) {
4703
+ return _effective(osType, "user_deletion_rules", (rt) => getEnabledL2UserDeletionRules(rt).map((r) => ({
4704
+ pattern: new RegExp(String(r.pattern || ""), "i"),
4705
+ askOnMatch: r.ask_on_match === true
4706
+ })));
4707
+ }
4507
4708
  function effectiveIntentPatterns(osType) {
4508
4709
  return _effective(osType, "intent", (rt) => {
4509
4710
  const rules = getEnabledL2IntentPatternsOrDefault(rt, osType);
@@ -4512,7 +4713,8 @@ function effectiveIntentPatterns(osType) {
4512
4713
  dangerousActions: r.dangerous_actions || [],
4513
4714
  reason: String(r.reason || ""),
4514
4715
  os: String(r.os || "linux").toLowerCase(),
4515
- allowIfWriteIntent: r.allow_if_write_intent === true
4716
+ allowIfWriteIntent: r.allow_if_write_intent === true,
4717
+ askOnMatch: r.ask_on_match === true
4516
4718
  }));
4517
4719
  });
4518
4720
  }
@@ -4524,8 +4726,15 @@ function effectiveUserDeletionPatterns(osType) {
4524
4726
  }
4525
4727
  function _sensitivePathCategoryOf(runtime) {
4526
4728
  const l1 = runtime.L1_rules?.sensitive_path_access;
4527
- if (l1 && (l1.rules || []).length > 0) return l1;
4528
- return runtime.L2_rules?.sensitive_path_access;
4729
+ const l2 = runtime.L2_rules?.sensitive_path_access;
4730
+ const l1Rules = l1?.rules || [];
4731
+ const l2Rules = l2?.rules || [];
4732
+ if (l2Rules.length === 0) return l1;
4733
+ if (l1Rules.length === 0) return l2;
4734
+ const seen = new Set(l1Rules.map((r) => _ruleFingerprint(r)));
4735
+ const merged = { ...l1 };
4736
+ merged.rules = [...l1Rules, ...l2Rules.filter((r) => !seen.has(_ruleFingerprint(r)))];
4737
+ return merged;
4529
4738
  }
4530
4739
  function _validateSkillId(skillId) {
4531
4740
  if (!skillId || !SKILL_ID_RE.test(skillId)) {
@@ -4561,6 +4770,23 @@ function updateRuleDenyMode(layer, category, ruleId, denyMode) {
4561
4770
  saveRuntimeConfig(runtime);
4562
4771
  return runtime;
4563
4772
  }
4773
+ function updateRuleAsk(layer, category, ruleId, askOnMatch) {
4774
+ const runtime = loadRuntimeConfig();
4775
+ const rules = runtime[layer]?.[category]?.rules || [];
4776
+ const r = rules.find((x) => x.id === ruleId);
4777
+ if (r) r.ask_on_match = !!askOnMatch;
4778
+ saveRuntimeConfig(runtime);
4779
+ return runtime;
4780
+ }
4781
+ function updateCategoryAsk(layer, category, askOnMatch) {
4782
+ const runtime = loadRuntimeConfig();
4783
+ const cat = runtime[layer]?.[category];
4784
+ if (cat && typeof cat === "object") {
4785
+ for (const r of cat.rules || []) r.ask_on_match = !!askOnMatch;
4786
+ saveRuntimeConfig(runtime);
4787
+ }
4788
+ return runtime;
4789
+ }
4564
4790
  function updateRuleSkipL3(layer, category, ruleId, skipL3) {
4565
4791
  const runtime = loadRuntimeConfig();
4566
4792
  for (const r of runtime[layer]?.[category]?.rules || []) {
@@ -4572,6 +4798,13 @@ function updateRuleSkipL3(layer, category, ruleId, skipL3) {
4572
4798
  saveRuntimeConfig(runtime);
4573
4799
  return runtime;
4574
4800
  }
4801
+ function updateInjectionTierEnabled(tier, enabled) {
4802
+ const runtime = loadRuntimeConfig();
4803
+ const cat = (runtime.L1_rules ??= {}).injection_detection ??= { category_enabled: true, rules: [] };
4804
+ cat.tier_enabled = { ...cat.tier_enabled || {}, [tier]: enabled };
4805
+ saveRuntimeConfig(runtime);
4806
+ return runtime;
4807
+ }
4575
4808
  function updateCategoryEnabled(layer, category, enabled) {
4576
4809
  const runtime = loadRuntimeConfig();
4577
4810
  const cat = runtime[layer]?.[category];
@@ -4834,7 +5067,7 @@ function updateScenarioCategoryEnabled(scenarioId, category, enabled) {
4834
5067
  saveRuntimeConfig(runtime);
4835
5068
  return runtime;
4836
5069
  }
4837
- var __dirname4, ENV_RUNTIME_CONFIG_PATH, RUNTIME_CONFIG_DIR, RUNTIME_CONFIG_PATH, LAYER_DISABLE_ENV, DEFAULT_LAYERS, DENY_MODE_LABELS, runtimeConfigCache, _DEDUP_KEYS, hasRuntimeConfigCache, _AGENTS_DIR_PROD, _AGENTS_DIR_DEV, _SCENARIOS_DIR_PROD, _SCENARIOS_DIR_DEV, _effectiveCache, SKILL_ID_RE;
5070
+ var __dirname4, ENV_RUNTIME_CONFIG_PATH, RUNTIME_CONFIG_DIR, RUNTIME_CONFIG_PATH, LAYER_DISABLE_ENV, DEFAULT_LAYERS, DENY_MODE_LABELS, runtimeConfigCache, _DEDUP_KEYS, hasRuntimeConfigCache, _AGENTS_DIR_PROD, _AGENTS_DIR_DEV, _SCENARIOS_DIR_PROD, _SCENARIOS_DIR_DEV, BUILTIN_DETECTOR_DEFAULTS, _effectiveCache, SKILL_ID_RE;
4838
5071
  var init_runtime_config = __esm({
4839
5072
  "src/infra/runtime-config.ts"() {
4840
5073
  "use strict";
@@ -4885,6 +5118,17 @@ var init_runtime_config = __esm({
4885
5118
  _AGENTS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "agents");
4886
5119
  _SCENARIOS_DIR_PROD = join7(__dirname4, "scenarios");
4887
5120
  _SCENARIOS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
5121
+ BUILTIN_DETECTOR_DEFAULTS = [
5122
+ { id: "builtin_wildcard_delete", reason: "\u901A\u914D\u7B26 + \u6279\u91CF\u5220\u9664\uFF08rm \u914D\u901A\u914D\u7B26\uFF0C\u6392\u9664 /tmp \u7B49\u4E34\u65F6\u76EE\u5F55\u6E05\u7406\uFF09", risk_level: "high", risk_type: "script_execution", enabled: true, builtin: true, os: "all", ask_on_match: false },
5123
+ { id: "builtin_find_exec_write", reason: "find \u6279\u91CF\u6267\u884C\u5199\u64CD\u4F5C\uFF08find -exec / | xargs \u540E\u63A5 chmod/cp/mv/rm \u7B49\uFF09", risk_level: "high", risk_type: "script_execution", enabled: true, builtin: true, os: "all", ask_on_match: false },
5124
+ { id: "builtin_redirect_system", reason: "\u91CD\u5B9A\u5411\u8986\u76D6\u5199\u5165\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55\uFF08/etc\u3001/boot\u3001/proc\uFF09", risk_level: "critical", risk_type: "file_access", enabled: true, builtin: true, os: "all", ask_on_match: false },
5125
+ { id: "builtin_home_deletion", reason: "\u4E3B\u76EE\u5F55\u9012\u5F52\u5220\u9664\uFF08rm -rf ~ / $HOME \u53CA\u53D8\u91CF\u95F4\u63A5\u5F15\u7528\uFF09", risk_level: "high", risk_type: "home_deletion", enabled: true, builtin: true, os: "all", ask_on_match: false },
5126
+ { id: "structural_hidden_payload", reason: "\u89E3\u7801\u5206\u6790\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u53EF\u89E3\u7801\u7684\u9690\u85CF\u8F7D\u8377\uFF08Tag/base64/hex/URL\uFF09", risk_level: "high", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
5127
+ { id: "structural_bidi_override", reason: "\u89E3\u7801\u5206\u6790\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u53CC\u5411\u63A7\u5236\u7B26\uFF08\u53EF\u80FD\u906E\u6321\u6587\u672C\uFF09", risk_level: "medium", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
5128
+ { id: "structural_external_media", reason: "\u7ED3\u6784\u7279\u5F81\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u5916\u90E8\u56FE\u7247\u94FE\u63A5", risk_level: "medium", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
5129
+ { id: "structural_persistence", reason: "\u7ED3\u6784\u7279\u5F81\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u6301\u4E45\u5316\u6307\u4EE4\u53E5\u5F0F\uFF08\u6BCF\u5F53\u7528\u6237\u2026\uFF09", risk_level: "medium", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
5130
+ { id: "builtin_lateral_movement", reason: "\u6A2A\u5411\u79FB\u52A8\uFF08ssh/scp/rsync \u5230\u975E\u672C\u673A\u4E3B\u673A\uFF09", risk_level: "high", risk_type: "lateral_movement", enabled: true, builtin: true, os: "all", ask_on_match: false }
5131
+ ];
4888
5132
  _effectiveCache = /* @__PURE__ */ new WeakMap();
4889
5133
  SKILL_ID_RE = /^[A-Za-z0-9_-]+$/;
4890
5134
  registerRuntimeConfigBridge({
@@ -4896,6 +5140,9 @@ var init_runtime_config = __esm({
4896
5140
  effectiveIntentPatterns,
4897
5141
  effectivePasswordPatterns,
4898
5142
  effectiveUserDeletionPatterns,
5143
+ effectivePasswordRules,
5144
+ effectiveUserDeletionRules,
5145
+ builtinAskMap: () => getBuiltinAskMap(loadRuntimeConfig()),
4899
5146
  disabledSkillIds: () => getDisabledSkillIds(loadRuntimeConfig())
4900
5147
  });
4901
5148
  }
@@ -5157,10 +5404,10 @@ function getCacheOptions() {
5157
5404
  let enabled = true;
5158
5405
  let maxSize = 1e3;
5159
5406
  const cfg = loadConfigFile(resolveConfigPath());
5160
- const cache3 = cfg?.cache;
5161
- if (cache3 && typeof cache3 === "object") {
5162
- if (typeof cache3.enabled === "boolean") enabled = cache3.enabled;
5163
- if (typeof cache3.max_size === "number" && cache3.max_size > 0) maxSize = cache3.max_size;
5407
+ const cache4 = cfg?.cache;
5408
+ if (cache4 && typeof cache4 === "object") {
5409
+ if (typeof cache4.enabled === "boolean") enabled = cache4.enabled;
5410
+ if (typeof cache4.max_size === "number" && cache4.max_size > 0) maxSize = cache4.max_size;
5164
5411
  }
5165
5412
  if (process.env.AGENT_MOSS_DISABLE_CACHE === "1") enabled = false;
5166
5413
  return { enabled, maxSize };
@@ -5756,6 +6003,194 @@ var init_written_content_analyzer = __esm({
5756
6003
  }
5757
6004
  });
5758
6005
 
6006
+ // src/engine/structural-analyzer.ts
6007
+ function decodeTagPayload(text) {
6008
+ const payloads = [];
6009
+ let current = [];
6010
+ let afterFlag = false;
6011
+ let prevCp = 0;
6012
+ const flush = () => {
6013
+ if (current.length && !afterFlag) payloads.push(current.join(""));
6014
+ current = [];
6015
+ afterFlag = false;
6016
+ };
6017
+ for (const ch of text || "") {
6018
+ const cp = ch.codePointAt(0);
6019
+ if (cp >= TAG_MIN && cp <= TAG_MAX) {
6020
+ if (!current.length) afterFlag = prevCp === 127988;
6021
+ current.push(String.fromCharCode(cp - 917504));
6022
+ } else if (cp === TAG_CANCEL) {
6023
+ flush();
6024
+ } else {
6025
+ flush();
6026
+ }
6027
+ prevCp = cp;
6028
+ }
6029
+ flush();
6030
+ return payloads;
6031
+ }
6032
+ function decodeBase32(value) {
6033
+ const clean = value.replace(/=+$/, "").toUpperCase();
6034
+ let bits = 0;
6035
+ let acc = 0;
6036
+ const out = [];
6037
+ for (const ch of clean) {
6038
+ const idx = B32_ALPHABET.indexOf(ch);
6039
+ if (idx < 0) return "";
6040
+ acc = acc << 5 | idx;
6041
+ bits += 5;
6042
+ if (bits >= 8) {
6043
+ bits -= 8;
6044
+ out.push(acc >> bits & 255);
6045
+ }
6046
+ }
6047
+ return Buffer.from(out).toString("utf8");
6048
+ }
6049
+ function decodeHexDump(text) {
6050
+ const out = [];
6051
+ for (const m of text.matchAll(XXD_LINE_RE)) {
6052
+ const hex = m[1].replace(/\s+/g, "");
6053
+ try {
6054
+ out.push(Buffer.from(hex, "hex").toString("utf8"));
6055
+ } catch {
6056
+ }
6057
+ }
6058
+ for (const m of text.match(OD_HEX_RE) || []) {
6059
+ const hex = m.replace(/\s+/g, "");
6060
+ if (hex.length % 2) continue;
6061
+ try {
6062
+ out.push(Buffer.from(hex, "hex").toString("utf8"));
6063
+ } catch {
6064
+ }
6065
+ }
6066
+ return out;
6067
+ }
6068
+ function decodeUnicodeEscapes(value) {
6069
+ return value.replace(
6070
+ /\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{8})/g,
6071
+ (_all, a, b) => String.fromCodePoint(parseInt(a || b, 16))
6072
+ );
6073
+ }
6074
+ function decodeHtmlEntities(value) {
6075
+ return value.replace(
6076
+ /&#(x?)([0-9a-fA-F]+);/g,
6077
+ (_all, x, n) => String.fromCodePoint(parseInt(n, x ? 16 : 10))
6078
+ );
6079
+ }
6080
+ function looksText(value) {
6081
+ if (value.trim().length < 4) return false;
6082
+ let printable = 0;
6083
+ for (const c of value) {
6084
+ if (c >= " " && c !== "\x7F") printable++;
6085
+ else if (c === "\r" || c === "\n" || c === " ") printable++;
6086
+ }
6087
+ return printable / Math.max(value.length, 1) >= 0.9;
6088
+ }
6089
+ function decodePayloads(text, opts = {}) {
6090
+ const out = [];
6091
+ const seen = /* @__PURE__ */ new Set();
6092
+ const add = (encoding, value) => {
6093
+ if (looksText(value) && !seen.has(value)) {
6094
+ seen.add(value);
6095
+ out.push({ encoding, decoded: value });
6096
+ }
6097
+ };
6098
+ for (const p of decodeTagPayload(text)) add("tag", p);
6099
+ for (const m of text.match(HEX_ESC_RE) || []) {
6100
+ try {
6101
+ const bytes = m.replace(/\\x/g, "").match(/../g).map((h) => parseInt(h, 16));
6102
+ add("hex", Buffer.from(bytes).toString("utf8"));
6103
+ } catch {
6104
+ }
6105
+ }
6106
+ for (const m of text.match(UNICODE_ESC_RE) || []) {
6107
+ try {
6108
+ add("unicode_escape", decodeUnicodeEscapes(m));
6109
+ } catch {
6110
+ }
6111
+ }
6112
+ for (const m of text.match(PCT_RE) || []) {
6113
+ try {
6114
+ add("url", decodeURIComponent(m));
6115
+ } catch {
6116
+ }
6117
+ }
6118
+ for (const m of text.match(B64_RE) || []) {
6119
+ try {
6120
+ const raw = Buffer.from(m + "=".repeat((4 - m.length % 4) % 4), "base64");
6121
+ add("base64", raw.toString("utf8"));
6122
+ } catch {
6123
+ }
6124
+ }
6125
+ for (const m of text.match(B64URL_RE) || []) {
6126
+ try {
6127
+ const norm = m.replace(/-/g, "+").replace(/_/g, "/");
6128
+ const raw = Buffer.from(norm + "=".repeat((4 - norm.length % 4) % 4), "base64");
6129
+ add("base64url", raw.toString("utf8"));
6130
+ } catch {
6131
+ }
6132
+ }
6133
+ for (const m of text.match(B32_RE) || []) add("base32", decodeBase32(m));
6134
+ for (const v of decodeHexDump(text)) add("hex_dump", v);
6135
+ if (opts.includeHtml) {
6136
+ for (const m of text.match(HTML_ENTITY_RE) || []) {
6137
+ try {
6138
+ add("html_entity", decodeHtmlEntities(m));
6139
+ } catch {
6140
+ }
6141
+ }
6142
+ }
6143
+ return out;
6144
+ }
6145
+ function findStructuralSignals(content) {
6146
+ const text = content || "";
6147
+ const findings = [];
6148
+ for (const p of decodePayloads(text)) {
6149
+ findings.push({
6150
+ kind: "hidden_payload",
6151
+ sample: `[${p.encoding}] ${p.decoded.slice(0, 120)}`,
6152
+ riskLevel: "medium",
6153
+ decoded: p.decoded
6154
+ });
6155
+ }
6156
+ const bidi = text.match(BIDI_RE);
6157
+ if (bidi) findings.push({ kind: "bidi_override", sample: JSON.stringify(bidi[0]), riskLevel: "medium" });
6158
+ const media = text.match(EXTERNAL_MEDIA_RE);
6159
+ if (media) findings.push({ kind: "external_media", sample: media[0].slice(0, 120), riskLevel: "medium" });
6160
+ const persist = text.match(PERSISTENCE_RE);
6161
+ if (persist) findings.push({ kind: "persistence_phrase", sample: persist[0].slice(0, 120), riskLevel: "medium" });
6162
+ return findings;
6163
+ }
6164
+ var TAG_MIN, TAG_MAX, TAG_CANCEL, BIDI_RE, EXTERNAL_MEDIA_RE, PERSISTENCE_RE, B64_RE, B64URL_RE, B32_RE, HEX_ESC_RE, UNICODE_ESC_RE, PCT_RE, XXD_LINE_RE, OD_HEX_RE, HTML_ENTITY_RE, B32_ALPHABET, SIGNAL_TO_DETECTOR;
6165
+ var init_structural_analyzer = __esm({
6166
+ "src/engine/structural-analyzer.ts"() {
6167
+ "use strict";
6168
+ init_esm_shims();
6169
+ TAG_MIN = 917536;
6170
+ TAG_MAX = 917630;
6171
+ TAG_CANCEL = 917631;
6172
+ BIDI_RE = /[\u202a-\u202e]/;
6173
+ EXTERNAL_MEDIA_RE = /!\[[^\]]*\]\(\s*(?:https?:)?\/\/[^)\s]+|<img\b[^>]*\bsrc\s*=\s*["']?(?:https?:)?\/\//i;
6174
+ PERSISTENCE_RE = /(?:每当|每次|以后每次|今后每次|从现在起每次)[^。\n]{0,20}(?:用户|你)|from now on,?\s*(?:whenever|each time|every time)|whenever the user|each time the user/i;
6175
+ B64_RE = /[A-Za-z0-9+/]{8,}={0,2}/g;
6176
+ B64URL_RE = /[A-Za-z0-9_-]{16,}={0,2}/g;
6177
+ B32_RE = /[A-Z2-7]{12,}={0,6}/g;
6178
+ HEX_ESC_RE = /(?:\\x[0-9a-fA-F]{2}){4,}/g;
6179
+ UNICODE_ESC_RE = /(?:\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}){4,}/g;
6180
+ PCT_RE = /(?:%[0-9A-Fa-f]{2}){4,}/g;
6181
+ XXD_LINE_RE = /^\s*[0-9a-fA-F]{4,8}:\s+([0-9a-fA-F]{2,4}(?:[ ]+[0-9a-fA-F]{2,4})*)/gm;
6182
+ OD_HEX_RE = /(?:(?<![0-9a-fA-F])[0-9a-fA-F]{2}[ \t]+){15,}[0-9a-fA-F]{2}/g;
6183
+ HTML_ENTITY_RE = /(?:&#x?[0-9a-fA-F]+;){4,}/g;
6184
+ B32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
6185
+ SIGNAL_TO_DETECTOR = {
6186
+ hidden_payload: "structural_hidden_payload",
6187
+ bidi_override: "structural_bidi_override",
6188
+ external_media: "structural_external_media",
6189
+ persistence_phrase: "structural_persistence"
6190
+ };
6191
+ }
6192
+ });
6193
+
5759
6194
  // src/engine/heuristic.ts
5760
6195
  import { posix } from "path";
5761
6196
  function _effectiveDangerousPatterns(osType) {
@@ -5902,11 +6337,18 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
5902
6337
  const deob = normalizeShellObfuscation(scanDetail);
5903
6338
  if (deob !== scanDetail) scanCommands.push(`${actionType}: ${deob}`, deob);
5904
6339
  let top = null;
6340
+ const loopbackOnly = allUrlsLoopback(actionDetail) && !LOOPBACK_DATA_GUARD_RE.test(actionDetail);
6341
+ const boundedLoop = isBoundedLoop(scanDetail);
5905
6342
  for (const rule of _effectiveDangerousPatterns(osType)) {
5906
6343
  if (scanCommands.some((c) => rule.pattern.test(c))) {
6344
+ if (loopbackOnly && rule.riskType === "data_exfiltration") continue;
6345
+ if (boundedLoop && rule.riskType === "resource_exhaustion" && (rule.description || "").includes("\u65E0\u9650\u5FAA\u73AF")) continue;
5907
6346
  if (!top || severityRank(rule.severity) > severityRank(top.sev)) {
5908
6347
  top = { sev: rule.severity, type: rule.riskType, desc: rule.description };
5909
6348
  }
6349
+ if (rule.askOnMatch && !top.ask) {
6350
+ top.ask = `\u89C4\u5219\u300C${rule.description}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237`;
6351
+ }
5910
6352
  }
5911
6353
  }
5912
6354
  const toJudgment = (hit) => ({
@@ -5916,13 +6358,22 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
5916
6358
  riskType: hit.type,
5917
6359
  confidence: 95,
5918
6360
  source: "heuristic",
5919
- violatedLayers: ["L1.1"]
6361
+ violatedLayers: ["L1.1"],
6362
+ ...hit.ask ? { ask_recommended: true, ask_reason: hit.ask } : {}
5920
6363
  });
5921
6364
  if (top && severityRank(top.sev) >= severityRank("high")) return toJudgment(top);
5922
6365
  const rmResolved = checkRmResolvedTargets(scanDetail);
5923
6366
  if (rmResolved) return rmResolved;
5924
6367
  return top ? toJudgment(top) : null;
5925
6368
  }
6369
+ function isBoundedLoop(text) {
6370
+ const loops = (text.match(LOOP_START_RE) || []).length;
6371
+ const breaks = (text.match(LOOP_EXIT_RE) || []).length;
6372
+ return loops > 0 && breaks >= loops && !LOOP_SIDE_EFFECT_RE.test(text);
6373
+ }
6374
+ function isDbQueryCommand(text) {
6375
+ return DB_QUERY_CMD_RE.test(text || "");
6376
+ }
5926
6377
  function allUrlsLoopback(actionDetail) {
5927
6378
  const hosts = actionDetail.match(new RegExp(LOOPBACK_URL_RE.source, "gi"));
5928
6379
  if (!hosts || hosts.length === 0) return false;
@@ -5942,6 +6393,49 @@ function stripEchoParamsForUserRules(actionDetail) {
5942
6393
  return `${head} ` + (cut >= 0 ? rest.slice(cut) : "");
5943
6394
  }).join(" ");
5944
6395
  }
6396
+ function extractDecodedPayloads(actionType, detail, handledWrite) {
6397
+ if (!getEnabledBuiltinDetectorsOrCurrent().has("structural_hidden_payload")) return [];
6398
+ const source = injectionScanSource(actionType, detail, handledWrite);
6399
+ if (!source) return [];
6400
+ let content = detail || "";
6401
+ if (handledWrite) {
6402
+ const payload = extractWritePayload(actionType, content);
6403
+ if (payload) content = payload.content;
6404
+ }
6405
+ return decodePayloads(content, { includeHtml: source === "instruction" }).map((p) => ({ source, encoding: p.encoding, decoded: p.decoded }));
6406
+ }
6407
+ function detectDecoded(payload) {
6408
+ const enabled = getEnabledBuiltinDetectorsOrCurrent();
6409
+ const hits = [];
6410
+ const cmd = scanDangerousCommandPatterns("bash", payload);
6411
+ if (cmd) hits.push(cmd);
6412
+ const pat = checkDangerousPatterns("bash", payload, enabled);
6413
+ if (pat) hits.push(pat);
6414
+ if (enabled.has("builtin_home_deletion")) {
6415
+ const home = checkHomeDeletion("bash", payload);
6416
+ if (home) hits.push(home);
6417
+ }
6418
+ if (enabled.has("builtin_lateral_movement")) {
6419
+ const lateral = checkLateralMovement(payload);
6420
+ if (lateral) hits.push(lateral);
6421
+ }
6422
+ const path10 = checkSensitivePath(payload, "/", null, void 0);
6423
+ if (path10) hits.push(path10);
6424
+ const inj = checkInjectionKeywords(payload.toLowerCase());
6425
+ if (inj.length) {
6426
+ hits.push({
6427
+ allowed: false,
6428
+ reason: `\u89E3\u7801\u5185\u5BB9\u542B\u6CE8\u5165\u5173\u952E\u8BCD: ${inj.map((h) => h.keyword).join(", ")}`,
6429
+ riskLevel: "medium",
6430
+ riskType: "prompt_injection",
6431
+ confidence: 90,
6432
+ source: "heuristic",
6433
+ violatedLayers: ["L1.1"]
6434
+ });
6435
+ }
6436
+ if (!hits.length) return null;
6437
+ return hits.reduce((a, b) => severityRank(b.riskLevel) > severityRank(a.riskLevel) ? b : a);
6438
+ }
5945
6439
  function runHeuristicCheck(input) {
5946
6440
  const command = `${input.aNext.actionType}: ${input.aNext.actionDetail}`;
5947
6441
  const matched = [];
@@ -6016,11 +6510,22 @@ function runHeuristicCheck(input) {
6016
6510
  const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
6017
6511
  const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
6018
6512
  const noQuotes = pwGuardOff ? null : input.aNext.actionDetail.replace(ALL_QUOTES_RE, " ");
6513
+ const boundedLoop = isBoundedLoop(scanDetail);
6514
+ const loopbackExfilSkip = urlsAllLoopback && !LOOPBACK_DATA_GUARD_RE.test(input.aNext.actionDetail);
6515
+ let askReason = "";
6019
6516
  for (const rule of _effectiveDangerousPatterns(input.osType)) {
6020
6517
  if (scanCommands.some((c) => rule.pattern.test(c))) {
6518
+ if (loopbackExfilSkip && rule.riskType === "data_exfiltration") continue;
6021
6519
  if (exemptKeygen && rule.riskType === "file_access") continue;
6520
+ if (boundedLoop && rule.riskType === "resource_exhaustion" && (rule.description || "").includes("\u65E0\u9650\u5FAA\u73AF")) {
6521
+ matched.push("\u68C0\u6D4B\u5230\u5FAA\u73AF\u4F46\u5B58\u5728\u7EC8\u6B62\u6761\u4EF6\uFF08break/return\uFF09\uFF0C\u964D\u7EA7\u4EA4 L2/L3");
6522
+ continue;
6523
+ }
6022
6524
  if (noQuotes !== null && QUOTED_SAFE_PASSWORD_PATTERN_SOURCES.has(rule.pattern.source) && !rule.pattern.test(noQuotes)) continue;
6023
6525
  matched.push(rule.description);
6526
+ if (rule.askOnMatch && !askReason) {
6527
+ askReason = `\u89C4\u5219\u300C${rule.description}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237`;
6528
+ }
6024
6529
  if (severityRank(rule.severity) > severityRank(highestSeverity)) {
6025
6530
  highestSeverity = rule.severity;
6026
6531
  topRiskType = rule.riskType;
@@ -6047,9 +6552,15 @@ function runHeuristicCheck(input) {
6047
6552
  }
6048
6553
  }
6049
6554
  }
6050
- const injectionText = isSearchActionType(input.aNext.actionType) || handledWrite && isDataDocument(input.aNext.actionType, input.aNext.actionDetail) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
6555
+ const enabledBuiltin = getEnabledBuiltinDetectorsOrCurrent();
6556
+ const injectionSource = injectionScanSource(
6557
+ input.aNext.actionType,
6558
+ input.aNext.actionDetail,
6559
+ handledWrite
6560
+ );
6561
+ const injectionText = injectionSource ? input.aNext.actionDetail.toLowerCase() : "";
6051
6562
  let pythonWalkOnerrorOnly = false;
6052
- if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
6563
+ if (injectionSource === "output" && isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=")) {
6053
6564
  pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
6054
6565
  }
6055
6566
  const injectionHits = checkInjectionKeywords(
@@ -6058,6 +6569,9 @@ function runHeuristicCheck(input) {
6058
6569
  input.osType,
6059
6570
  pythonWalkOnerrorOnly
6060
6571
  );
6572
+ for (const h of injectionHits) {
6573
+ if (h.riskLevel === "high" || h.riskLevel === "critical") h.riskLevel = "medium";
6574
+ }
6061
6575
  if (injectionHits.length > 0) {
6062
6576
  const topHit = injectionHits.reduce((a, b) => severityRank(a.riskLevel) >= severityRank(b.riskLevel) ? a : b);
6063
6577
  matched.push(...injectionHits.map((h) => `\u6CE8\u5165\u5173\u952E\u8BCD [${h.lang}]: ${h.keyword}`));
@@ -6066,12 +6580,28 @@ function runHeuristicCheck(input) {
6066
6580
  highestRiskType = "prompt_injection";
6067
6581
  }
6068
6582
  }
6583
+ if (injectionSource) {
6584
+ const payload = handledWrite ? extractWritePayload(input.aNext.actionType, input.aNext.actionDetail) : null;
6585
+ const content = payload ? payload.content : input.aNext.actionDetail;
6586
+ for (const finding of findStructuralSignals(content)) {
6587
+ const det = SIGNAL_TO_DETECTOR[finding.kind];
6588
+ if (!det || !enabledBuiltin.has(det)) continue;
6589
+ if (finding.kind === "hidden_payload") continue;
6590
+ if (injectionSource !== "instruction") continue;
6591
+ const level = finding.riskLevel;
6592
+ matched.push(`\u7ED3\u6784\u7279\u5F81: ${finding.kind}`);
6593
+ if (severityRank(level) > severityRank(highestSeverity)) {
6594
+ highestSeverity = level;
6595
+ highestRiskType = "prompt_injection";
6596
+ }
6597
+ }
6598
+ }
6069
6599
  const actionTypeL = input.aNext.actionType.toLowerCase();
6070
6600
  const detailL = input.aNext.actionDetail.toLowerCase();
6071
6601
  const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
6072
- const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
6602
+ const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL, enabledBuiltin);
6073
6603
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
6074
- const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
6604
+ const homeResult = handledWrite || !enabledBuiltin.has("builtin_home_deletion") ? null : checkHomeDeletion(actionTypeL, detailL);
6075
6605
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
6076
6606
  if (isBashLike && !handledWrite && severityRank(highestSeverity) < severityRank("high") && !mergeResults.some((r) => severityRank(r.riskLevel) >= severityRank("high"))) {
6077
6607
  const rmResolved = checkRmResolvedTargets(scanDetail);
@@ -6082,16 +6612,22 @@ function runHeuristicCheck(input) {
6082
6612
  for (const r of mergeResults) {
6083
6613
  if (severityRank(r.riskLevel) > severityRank(best.riskLevel)) best = r;
6084
6614
  }
6085
- if (severityRank(highestSeverity) > severityRank(best.riskLevel)) {
6086
- return {
6615
+ if (highestRiskType && severityRank(highestSeverity) >= severityRank(best.riskLevel)) {
6616
+ const out = {
6087
6617
  allowed: false,
6088
6618
  reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${matched.join(", ")}`,
6089
6619
  riskLevel: highestSeverity,
6090
6620
  riskType: highestRiskType,
6091
6621
  confidence: 95,
6092
6622
  source: "heuristic",
6093
- violatedLayers: ["L1.1"]
6623
+ violatedLayers: ["L1.1"],
6624
+ ...askReason ? { ask_recommended: true, ask_reason: askReason } : {}
6094
6625
  };
6626
+ if (best === pathResult && pathResult?.deniedReadPath) {
6627
+ out.deniedReadPath = pathResult.deniedReadPath;
6628
+ if (pathResult.isCredential) out.isCredential = true;
6629
+ }
6630
+ return out;
6095
6631
  }
6096
6632
  if (best !== pathResult && pathResult?.deniedReadPath && best.riskType === "file_access" && best.riskLevel === pathResult.riskLevel) {
6097
6633
  best = { ...best, deniedReadPath: pathResult.deniedReadPath };
@@ -6106,11 +6642,14 @@ function runHeuristicCheck(input) {
6106
6642
  riskType: highestRiskType,
6107
6643
  confidence: 95,
6108
6644
  source: "heuristic",
6109
- violatedLayers: ["L1.1"]
6645
+ violatedLayers: ["L1.1"],
6646
+ ...askReason ? { ask_recommended: true, ask_reason: askReason } : {}
6110
6647
  };
6111
6648
  }
6112
- const lateralResult = checkLateralMovement(detailL);
6113
- if (lateralResult) return lateralResult;
6649
+ if (enabledBuiltin.has("builtin_lateral_movement")) {
6650
+ const lateralResult = checkLateralMovement(detailL);
6651
+ if (lateralResult) return lateralResult;
6652
+ }
6114
6653
  return null;
6115
6654
  }
6116
6655
  function onlyPythonWalkOnerrorKeywords(command) {
@@ -6129,6 +6668,52 @@ function onlyPythonWalkOnerrorKeywords(command) {
6129
6668
  const walkKws = noStr.match(/os\.walk\s*\([^)]*\bonerror\s*=/g) || [];
6130
6669
  return walkKws.length > 0;
6131
6670
  }
6671
+ function shellWriteTargets(command) {
6672
+ const out = [];
6673
+ INSTRUCTION_WRITE_RE.lastIndex = 0;
6674
+ let m;
6675
+ while ((m = INSTRUCTION_WRITE_RE.exec(command || "")) !== null) out.push(m[2]);
6676
+ return out;
6677
+ }
6678
+ function isDataDocPath(path10) {
6679
+ const i = String(path10 || "").lastIndexOf(".");
6680
+ return i >= 0 && DATA_DOC_EXTS.has(String(path10).slice(i).toLowerCase());
6681
+ }
6682
+ function isTextOutputCommand(command) {
6683
+ const text = command || "";
6684
+ if (isLiteralTextCommand(text)) return true;
6685
+ if (/\b(?:python3?|perl|ruby|node|php|lua)\b[^;|&\n]*\s-(?:c|e)\b/i.test(text)) return true;
6686
+ for (const seg of splitCommandSegments2(text)) {
6687
+ const parts = seg.trim().split(/\s+/);
6688
+ if (!parts.length) continue;
6689
+ const head = parts[0].toLowerCase();
6690
+ if (head === "echo" || head === "printf") return true;
6691
+ if (head === "cat" && seg.includes("<<")) return true;
6692
+ if (head === "tee" && shellWriteTargets(seg).length === 0) return true;
6693
+ }
6694
+ return false;
6695
+ }
6696
+ function injectionScanSource(actionType, raw, handledWrite) {
6697
+ const at = (actionType || "").toLowerCase();
6698
+ const text = raw || "";
6699
+ if (isSearchActionType(at)) return "";
6700
+ if (isDbQueryCommand(text)) return "";
6701
+ if (handledWrite) {
6702
+ const payload = extractWritePayload(at, text);
6703
+ const path10 = payload ? payload.path : "";
6704
+ if (path10 && isInstructionTarget(path10)) return "instruction";
6705
+ if (isDataDocument(at, text)) return "";
6706
+ return "output";
6707
+ }
6708
+ if (["bash", "executebash", "terminal-executebash"].includes(at)) {
6709
+ const targets = shellWriteTargets(text);
6710
+ if (targets.some((t) => isInstructionTarget(t))) return "instruction";
6711
+ if (targets.length > 0 && targets.every(isDataDocPath)) return "";
6712
+ if (isTextOutputCommand(text)) return "output";
6713
+ return "";
6714
+ }
6715
+ return "";
6716
+ }
6132
6717
  function checkInjectionKeywords(text, extraKeywords, osType, pythonWalkOnerrorOnly = false) {
6133
6718
  const hits = [];
6134
6719
  const baseKeywords = runtimeConfigBridge.current?.effectiveInjectionKeywords(osType) ?? INJECTION_KEYWORDS;
@@ -6389,6 +6974,9 @@ function isSearchActionType(actionType) {
6389
6974
  const at = actionType.toLowerCase();
6390
6975
  return SEARCH_ACTION_PREFIXES.some((p) => at.startsWith(p)) || SEARCH_ACTION_EXACT.includes(at);
6391
6976
  }
6977
+ function askMeta(on, desc) {
6978
+ return on ? { ask_recommended: true, ask_reason: `\u89C4\u5219\u300C${desc || ""}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237` } : {};
6979
+ }
6392
6980
  function checkSensitivePath(command, cwd, agentExt, osType) {
6393
6981
  const expandedCwd = cwd.replace(/^~/, process.env.HOME || "/home/user");
6394
6982
  const { root: rootPaths, home: homePaths, credential: credentialPaths } = getSensitivePathsForOs(osType);
@@ -6404,7 +6992,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
6404
6992
  if (part.startsWith("(?!")) return part;
6405
6993
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6406
6994
  }).join("");
6407
- const re = path10.startsWith(".") || path10.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
6995
+ const re = path10.startsWith(".") || path10.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}${TEMPLATE_SUFFIX_LA}\\b`, "i") : new RegExp(`\\b${escaped}${TEMPLATE_SUFFIX_LA}\\b`, "i");
6408
6996
  return re.test(text);
6409
6997
  };
6410
6998
  const pathMatchesAny = (path10) => pathScanTexts.some((t) => pathMatches(t, path10));
@@ -6423,6 +7011,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
6423
7011
  confidence: 90,
6424
7012
  source: "heuristic",
6425
7013
  violatedLayers: ["L1.1"],
7014
+ ...askMeta(sp.askOnMatch === true, sp.desc),
6426
7015
  deniedReadPath: sp.path
6427
7016
  };
6428
7017
  }
@@ -6437,6 +7026,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
6437
7026
  confidence: 90,
6438
7027
  source: "heuristic",
6439
7028
  violatedLayers: ["L1.1"],
7029
+ ...askMeta(sp.askOnMatch === true, sp.desc),
6440
7030
  isCredential: !!sp.credential,
6441
7031
  deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
6442
7032
  };
@@ -6467,6 +7057,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
6467
7057
  confidence: 90,
6468
7058
  source: "heuristic",
6469
7059
  violatedLayers: ["L1.1"],
7060
+ ...askMeta(sp.askOnMatch === true, sp.desc),
6470
7061
  isCredential: !!sp.credential
6471
7062
  };
6472
7063
  }
@@ -6479,6 +7070,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
6479
7070
  confidence: 90,
6480
7071
  source: "heuristic",
6481
7072
  violatedLayers: ["L1.1"],
7073
+ ...askMeta(sp.askOnMatch === true, sp.desc),
6482
7074
  isCredential: !!sp.credential
6483
7075
  };
6484
7076
  }
@@ -6495,6 +7087,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
6495
7087
  confidence: 90,
6496
7088
  source: "heuristic",
6497
7089
  violatedLayers: ["L1.1"],
7090
+ ...askMeta(sp.askOnMatch === true, sp.desc),
6498
7091
  isCredential: !!sp.credential,
6499
7092
  deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
6500
7093
  };
@@ -6525,9 +7118,10 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
6525
7118
  }
6526
7119
  }
6527
7120
  }
7121
+ const templateSuffix = TEMPLATE_SUFFIX_LA;
6528
7122
  for (const cp of credentialPaths) {
6529
7123
  const escaped = cp.path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6530
- const re = cp.path.startsWith(".") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`) : new RegExp(`\\b${escaped}\\b`);
7124
+ const re = cp.path.startsWith(".") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}${templateSuffix}\\b`) : new RegExp(`\\b${escaped}${templateSuffix}\\b`);
6531
7125
  if (re.test(command)) {
6532
7126
  return {
6533
7127
  allowed: false,
@@ -6537,6 +7131,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
6537
7131
  confidence: 90,
6538
7132
  source: "heuristic",
6539
7133
  violatedLayers: ["L1.1"],
7134
+ ...askMeta(cp.askOnMatch === true, cp.desc),
6540
7135
  isCredential: true,
6541
7136
  deniedReadPath: cp.path
6542
7137
  };
@@ -6593,6 +7188,14 @@ function homeEscapeTarget(seg) {
6593
7188
  }
6594
7189
  return false;
6595
7190
  }
7191
+ function builtinAsk(ruleId) {
7192
+ try {
7193
+ const reason = runtimeConfigBridge.current?.builtinAskMap()?.[ruleId];
7194
+ return reason ? { ask_recommended: true, ask_reason: reason } : {};
7195
+ } catch {
7196
+ return {};
7197
+ }
7198
+ }
6596
7199
  function checkHomeDeletion(actionType, actionDetail) {
6597
7200
  if (actionType !== "bash" && actionType !== "executebash" && actionType !== "terminal-executebash") return null;
6598
7201
  const segs = actionDetail.split(/&&|\|\||;|\n/).map((s) => s.trim()).filter(Boolean);
@@ -6606,7 +7209,8 @@ function checkHomeDeletion(actionType, actionDetail) {
6606
7209
  riskType: "script_execution",
6607
7210
  confidence: 90,
6608
7211
  source: "heuristic",
6609
- violatedLayers: ["L1.1"]
7212
+ violatedLayers: ["L1.1"],
7213
+ ...builtinAsk("builtin_home_deletion")
6610
7214
  };
6611
7215
  }
6612
7216
  }
@@ -6637,7 +7241,8 @@ function checkHomeDeletion(actionType, actionDetail) {
6637
7241
  riskType: "script_execution",
6638
7242
  confidence: 90,
6639
7243
  source: "heuristic",
6640
- violatedLayers: ["L1.1"]
7244
+ violatedLayers: ["L1.1"],
7245
+ ...builtinAsk("builtin_home_deletion")
6641
7246
  };
6642
7247
  }
6643
7248
  }
@@ -6647,18 +7252,34 @@ function checkHomeDeletion(actionType, actionDetail) {
6647
7252
  function escapeRegExp(s) {
6648
7253
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6649
7254
  }
7255
+ function dirTargetIsDirectory(text, dirPath) {
7256
+ const low = text.toLowerCase();
7257
+ const dpath = dirPath.toLowerCase();
7258
+ let idx = low.indexOf(dpath);
7259
+ while (idx >= 0) {
7260
+ const tail = low.slice(idx + dpath.length);
7261
+ if (!tail || /^[\s'"\\);|&)>]/.test(tail)) return true;
7262
+ if (tail.startsWith("/*") || tail.startsWith("/.")) return true;
7263
+ if (tail.startsWith("/")) {
7264
+ const rest = tail.slice(1);
7265
+ if (!rest || /^[\s'"\\);|&)>]/.test(rest)) return true;
7266
+ }
7267
+ idx = low.indexOf(dpath, idx + 1);
7268
+ }
7269
+ return false;
7270
+ }
6650
7271
  function isDeleteActionForDir(command, dirPath) {
6651
7272
  const low = command.toLowerCase();
6652
7273
  const dpath = dirPath.toLowerCase();
6653
- if (new RegExp(`\\b(?:rm|unlink|rmdir)\\b[^&|;]*?${escapeRegExp(dpath)}`, "i").test(low)) {
7274
+ if (new RegExp(`\\b(?:rm|unlink|rmdir)\\b[^&|;]*?${escapeRegExp(dpath)}`, "i").test(low) && dirTargetIsDirectory(low, dpath)) {
6654
7275
  return true;
6655
7276
  }
6656
- if (new RegExp(`(?:\u5220\u9664|\u79FB\u9664)[^\\n;|&]*?${escapeRegExp(dpath)}`).test(low)) {
7277
+ if (new RegExp(`(?:\u5220\u9664|\u79FB\u9664)[^\\n;|&]*?${escapeRegExp(dpath)}`).test(low) && dirTargetIsDirectory(low, dpath)) {
6657
7278
  return true;
6658
7279
  }
6659
7280
  for (const seg of low.split(/&&|\|\||;|\n/)) {
6660
7281
  const fw = (seg.trim().split(/\s+/)[0] || "").toLowerCase();
6661
- if ((fw === "rm" || fw === "unlink" || fw === "rmdir") && seg.includes(dpath)) {
7282
+ if ((fw === "rm" || fw === "unlink" || fw === "rmdir") && dirTargetIsDirectory(seg, dpath)) {
6662
7283
  return true;
6663
7284
  }
6664
7285
  }
@@ -6669,7 +7290,7 @@ function isArchiveReadOfDir(command, dirPath) {
6669
7290
  const dpath = dirPath.toLowerCase();
6670
7291
  for (const seg of low.split(/&&|\|\||;|\n/)) {
6671
7292
  const s = seg.trim();
6672
- if (!s || !s.includes(dpath)) continue;
7293
+ if (!s || !dirTargetIsDirectory(s, dpath)) continue;
6673
7294
  const parts = s.split(/\s+/);
6674
7295
  const fw = parts[0] || "";
6675
7296
  if (fw === "zip") return true;
@@ -6679,7 +7300,7 @@ function isArchiveReadOfDir(command, dirPath) {
6679
7300
  }
6680
7301
  if (fw === "cp" || fw === "rsync") {
6681
7302
  const segPaths = s.match(/[/~][^\s;|&><'"]*/g) || [];
6682
- if (segPaths[0]?.includes(dpath)) return true;
7303
+ if (segPaths[0] && dirTargetIsDirectory(segPaths[0], dpath)) return true;
6683
7304
  }
6684
7305
  }
6685
7306
  return false;
@@ -6691,15 +7312,16 @@ function isSshKeygenGenerate(command) {
6691
7312
  if (/(?:^|\s)-\S*[ylpB]\S*/.test(low)) return false;
6692
7313
  return true;
6693
7314
  }
6694
- function checkDangerousPatterns(actionType, actionDetail) {
7315
+ function checkDangerousPatterns(actionType, actionDetail, enabledBuiltin) {
6695
7316
  if (actionType === "file_write" || actionType === "file_edit") return null;
7317
+ const on = (id) => !enabledBuiltin || enabledBuiltin.has(id);
6696
7318
  const scan = stripSearchPatternLiterals(stripHeredocContent(stripShellDocsOnly(actionDetail)));
6697
7319
  const isTempPath = TEMP_DIRS2.some(
6698
7320
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
6699
7321
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
6700
7322
  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;
6701
7323
  const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
6702
- if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
7324
+ if (on("builtin_wildcard_delete") && !isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
6703
7325
  return {
6704
7326
  allowed: false,
6705
7327
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -6707,12 +7329,13 @@ function checkDangerousPatterns(actionType, actionDetail) {
6707
7329
  riskType: "script_execution",
6708
7330
  confidence: 90,
6709
7331
  source: "heuristic",
6710
- violatedLayers: ["L1.1"]
7332
+ violatedLayers: ["L1.1"],
7333
+ ...builtinAsk("builtin_wildcard_delete")
6711
7334
  };
6712
7335
  }
6713
- const findWriteMatch = actionDetail.match(
7336
+ const findWriteMatch = on("builtin_find_exec_write") ? actionDetail.match(
6714
7337
  /\bfind\b.*?(?:(?:^|\s)-exec(?:dir)?\s+(chmod|chown|cp|mv|rm|dd|tee|truncate|mkfs|shred|rmdir|unlink)\b|(?:^|\s)\|\s*xargs\s+(?:sed\s+-[a-zA-Z]*i|chmod|chown|cp|mv|rm|dd|tee|truncate|mkfs|shred|rmdir|unlink)\b)/i
6715
- );
7338
+ ) : null;
6716
7339
  if (findWriteMatch) {
6717
7340
  const cmdHit = findWriteMatch[1] || "xargs";
6718
7341
  return {
@@ -6722,10 +7345,11 @@ function checkDangerousPatterns(actionType, actionDetail) {
6722
7345
  riskType: "script_execution",
6723
7346
  confidence: 90,
6724
7347
  source: "heuristic",
6725
- violatedLayers: ["L1.1"]
7348
+ violatedLayers: ["L1.1"],
7349
+ ...builtinAsk("builtin_find_exec_write")
6726
7350
  };
6727
7351
  }
6728
- if (/>\s*['"]?\/etc\//.test(actionDetail) || />\s*['"]?\/boot\//.test(actionDetail) || />\s*['"]?\/proc\//.test(actionDetail)) {
7352
+ if (on("builtin_redirect_system") && (/>\s*['"]?\/etc\//.test(actionDetail) || />\s*['"]?\/boot\//.test(actionDetail) || />\s*['"]?\/proc\//.test(actionDetail))) {
6729
7353
  return {
6730
7354
  allowed: false,
6731
7355
  reason: "\u68C0\u6D4B\u5230\u91CD\u5B9A\u5411\u8986\u76D6\u5199\u5165\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55",
@@ -6733,7 +7357,8 @@ function checkDangerousPatterns(actionType, actionDetail) {
6733
7357
  riskType: "file_access",
6734
7358
  confidence: 95,
6735
7359
  source: "heuristic",
6736
- violatedLayers: ["L1.1"]
7360
+ violatedLayers: ["L1.1"],
7361
+ ...builtinAsk("builtin_redirect_system")
6737
7362
  };
6738
7363
  }
6739
7364
  if (/>\s*\/dev\/(sd|hd|nvme|vd|loop|mem|kmsg|port|zero|random|urandom|full|core)/i.test(actionDetail)) {
@@ -6835,13 +7460,14 @@ function checkLateralMovement(actionDetail) {
6835
7460
  riskType: "lateral_movement",
6836
7461
  confidence: 80,
6837
7462
  source: "heuristic",
6838
- violatedLayers: ["L1.1"]
7463
+ violatedLayers: ["L1.1"],
7464
+ ...builtinAsk("builtin_lateral_movement")
6839
7465
  };
6840
7466
  }
6841
7467
  }
6842
7468
  return null;
6843
7469
  }
6844
- var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SEARCH_OPTION_WITH_ARG, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
7470
+ var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, LOOP_EXIT_RE, LOOP_START_RE, DB_QUERY_CMD_RE, LOOP_SIDE_EFFECT_RE, LOOPBACK_DATA_GUARD_RE, TEMPLATE_SUFFIX_LA, INSTRUCTION_WRITE_RE, DATA_DOC_EXTS, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SEARCH_OPTION_WITH_ARG, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
6845
7471
  var init_heuristic = __esm({
6846
7472
  "src/engine/heuristic.ts"() {
6847
7473
  "use strict";
@@ -6853,6 +7479,8 @@ var init_heuristic = __esm({
6853
7479
  init_runtime_config_bridge();
6854
7480
  init_rules_loader();
6855
7481
  init_written_content_analyzer();
7482
+ init_inline_analyzer();
7483
+ init_structural_analyzer();
6856
7484
  init_logic_rules();
6857
7485
  INJECTION_KEYWORDS = (() => {
6858
7486
  const kws = loadL1().injection_detection || [];
@@ -6875,6 +7503,30 @@ var init_heuristic = __esm({
6875
7503
  HEURISTIC_RULES = loadHeuristicRules();
6876
7504
  LOOPBACK_HOSTS = new Set(HEURISTIC_RULES.loopback_hosts ?? []);
6877
7505
  TEMP_DIRS2 = HEURISTIC_RULES.temp_dirs ?? [];
7506
+ LOOP_EXIT_RE = /\bbreak\b/gi;
7507
+ LOOP_START_RE = /\bwhile\s+(?:true\b|1\b|:)|until\s+false\b|\bfor\s*\(\s*;/gi;
7508
+ DB_QUERY_CMD_RE = /\b(?:sqlite3|psql|mysql|mariadb|sqlplus)\b|\bpython(?:3(?:\.\d+)?)?\s+-c\b[\s\S]{0,4096}?\b(?:execute|executemany)\s*\(/i;
7509
+ LOOP_SIDE_EFFECT_RE = /\b(?:rm|rmdir|unlink|shred|dd|mkfs\w*|chmod|chown|curl|wget|nc|ncat|socat|ssh|scp|rsync|kill|pkill|killall|shutdown|reboot|systemctl|sudo|mount)\b|\/dev\/tcp|\bos\.(?:system|popen|fork|exec\w*)\b|\bsubprocess\b|>\s*\/(?:etc|dev|proc|sys|boot)\//i;
7510
+ LOOPBACK_DATA_GUARD_RE = /\$|`|\bcat\b|@|-[TF]\b/;
7511
+ TEMPLATE_SUFFIX_LA = "(?!\\.(?:example|template|sample|dist)(?![A-Za-z0-9_-]))";
7512
+ INSTRUCTION_WRITE_RE = /(?:>>?|\btee\b(?:\s+-a)?)\s*(['"]?)([^\s;|&'"<>]+)/gi;
7513
+ DATA_DOC_EXTS = /* @__PURE__ */ new Set([
7514
+ ".md",
7515
+ ".txt",
7516
+ ".rst",
7517
+ ".html",
7518
+ ".htm",
7519
+ ".json",
7520
+ ".yaml",
7521
+ ".yml",
7522
+ ".csv",
7523
+ ".xml",
7524
+ ".css",
7525
+ ".ini",
7526
+ ".conf",
7527
+ ".log",
7528
+ ".sql"
7529
+ ]);
6878
7530
  PATH_CONTEXT_TRIGGER_RE = /(?:^|[;&|]\s*)(?:rm|rmdir|unlink|ln|mv|cp|dd|truncate|shred|chmod|chown)\b/i;
6879
7531
  HOME_PREFIX_RE = /(?:~|~(?=\/)|\$HOME\b|\$\{HOME\}|\/home\/[a-z0-9_.-]+)/gi;
6880
7532
  PY_EXEC_IO_RE = /os\.system|os\.popen|subprocess|eval\s*\(|exec\s*\(|__import__|open\s*\(|socket|urllib|requests\.|shutil|os\.(?:remove|unlink|rename|makedirs?|listdir|scandir|walk|chmod|chown|kill|environ)|iterdir|glob\s*\(|path\(/i;
@@ -6920,8 +7572,99 @@ var init_heuristic = __esm({
6920
7572
  }
6921
7573
  });
6922
7574
 
7575
+ // src/engine/shell-alias-resolver.ts
7576
+ import { spawnSync } from "child_process";
7577
+ import { existsSync as existsSync11, statSync as statSync5 } from "fs";
7578
+ import { homedir as homedir4 } from "os";
7579
+ import { join as join11 } from "path";
7580
+ function rcFiles() {
7581
+ return [
7582
+ join11(homedir4(), ".bashrc"),
7583
+ join11(homedir4(), ".bash_profile"),
7584
+ join11(homedir4(), ".profile"),
7585
+ "/etc/bash.bashrc",
7586
+ "/etc/profile"
7587
+ ];
7588
+ }
7589
+ function rcSignature() {
7590
+ return rcFiles().map((p) => {
7591
+ try {
7592
+ return String(statSync5(p).mtimeMs);
7593
+ } catch {
7594
+ return "0";
7595
+ }
7596
+ }).join("|");
7597
+ }
7598
+ function minimalEnv() {
7599
+ const keep = ["HOME", "USER", "LOGNAME", "SHELL", "PATH", "LANG", "LC_ALL", "TERM"];
7600
+ const env2 = {};
7601
+ for (const k of keep) if (process.env[k] !== void 0) env2[k] = process.env[k];
7602
+ env2.TERM = env2.TERM || "dumb";
7603
+ return env2;
7604
+ }
7605
+ function firstWord(command) {
7606
+ const m = (command || "").match(FIRST_WORD_RE);
7607
+ return m ? m[1] : "";
7608
+ }
7609
+ function run(shell, script, word, cwd) {
7610
+ try {
7611
+ const r = spawnSync(shell, ["-ic", script, "_", word], {
7612
+ timeout: PROBE_TIMEOUT_MS,
7613
+ cwd: cwd || void 0,
7614
+ env: minimalEnv(),
7615
+ stdio: ["ignore", "pipe", "ignore"],
7616
+ encoding: "utf8"
7617
+ });
7618
+ return r.stdout || "";
7619
+ } catch {
7620
+ return "";
7621
+ }
7622
+ }
7623
+ function resolveCommandPrefix(command, cwd = "") {
7624
+ if (process.env.AGENT_MOSS_SHELL_ALIAS_RESOLVE !== "1") return null;
7625
+ if (process.platform === "win32") return null;
7626
+ const word = firstWord(command);
7627
+ if (!word || word.includes("/")) return null;
7628
+ let shell = process.env.SHELL || "/bin/bash";
7629
+ if (!existsSync11(shell)) shell = "/bin/bash";
7630
+ const key = `${process.env.HOME || ""}|${shell}|${word}`;
7631
+ const sig = rcSignature();
7632
+ const cached2 = cache3.get(key);
7633
+ if (cached2 && cached2.sig === sig) return cached2.value;
7634
+ const out = run(shell, 'alias -- "$1" 2>/dev/null; type -a -- "$1" 2>/dev/null', word, cwd);
7635
+ let resolution = null;
7636
+ for (const raw of out.split("\n")) {
7637
+ const line = raw.trim();
7638
+ const m = line.match(/^alias\s+\S+=(.*)$/);
7639
+ if (m) {
7640
+ const value = m[1].trim().replace(/^['"]|['"]$/g, "");
7641
+ const rest = command.trim().slice(word.length).trim();
7642
+ resolution = { word, kind: "alias", expansion: `${value} ${rest}`.trim() };
7643
+ break;
7644
+ }
7645
+ if (new RegExp(`\\b${word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s+is\\s+a\\s+(?:shell\\s+)?function\\b`).test(line)) {
7646
+ const body = run(shell, 'declare -f -- "$1" 2>/dev/null', word, cwd).trim();
7647
+ if (body) resolution = { word, kind: "function", expansion: `${body}
7648
+ ${command}` };
7649
+ break;
7650
+ }
7651
+ }
7652
+ cache3.set(key, { sig, value: resolution });
7653
+ return resolution;
7654
+ }
7655
+ var PROBE_TIMEOUT_MS, FIRST_WORD_RE, cache3;
7656
+ var init_shell_alias_resolver = __esm({
7657
+ "src/engine/shell-alias-resolver.ts"() {
7658
+ "use strict";
7659
+ init_esm_shims();
7660
+ PROBE_TIMEOUT_MS = 2e3;
7661
+ FIRST_WORD_RE = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*([^\s;|&()]+)/;
7662
+ cache3 = /* @__PURE__ */ new Map();
7663
+ }
7664
+ });
7665
+
6923
7666
  // src/engine/template-loader.ts
6924
- import { readFileSync as readFileSync10, existsSync as existsSync11 } from "fs";
7667
+ import { readFileSync as readFileSync10, existsSync as existsSync12 } from "fs";
6925
7668
  import { resolve as resolve8, dirname as dirname9 } from "path";
6926
7669
  import { fileURLToPath as fileURLToPath9 } from "url";
6927
7670
  function loadTemplates() {
@@ -6935,7 +7678,7 @@ function loadTemplates() {
6935
7678
  }
6936
7679
  for (const file of TEMPLATE_FILES) {
6937
7680
  const filePath = resolve8(dir, file);
6938
- if (existsSync11(filePath)) {
7681
+ if (existsSync12(filePath)) {
6939
7682
  const key = file.replace(".txt", "").replace("_template", "");
6940
7683
  cachedTemplates[key] = readFileSync10(filePath, "utf-8");
6941
7684
  }
@@ -6958,7 +7701,7 @@ var init_template_loader = __esm({
6958
7701
 
6959
7702
  // src/engine/script-analyzer.ts
6960
7703
  import { readFileSync as readFileSync11 } from "fs";
6961
- import { resolve as resolve9, join as join11 } from "path";
7704
+ import { resolve as resolve9, join as join12 } from "path";
6962
7705
  function emptyResult() {
6963
7706
  return { scriptPath: "", scriptContent: "", matchedKeywords: [], lineCount: 0, isSuspicious: false, error: "", riskLevel: "", riskReason: "" };
6964
7707
  }
@@ -7011,7 +7754,7 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
7011
7754
  }
7012
7755
  function readScriptContent(scriptPath, maxLines = 500) {
7013
7756
  try {
7014
- const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join11(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve9(scriptPath);
7757
+ const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join12(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve9(scriptPath);
7015
7758
  const raw = readFileSync11(expandedPath, "utf-8");
7016
7759
  const lines = raw.split("\n").slice(0, maxLines);
7017
7760
  return { content: lines.join("\n"), lineCount: lines.length, error: "" };
@@ -10447,6 +11190,7 @@ function emptyNode(pathStr, depth) {
10447
11190
  l1RiskType: "",
10448
11191
  l1Reason: "",
10449
11192
  l1MatchedPatterns: [],
11193
+ l1AskReason: "",
10450
11194
  l2Hit: false,
10451
11195
  l2ViolatedRule: "",
10452
11196
  l2RiskLevel: "",
@@ -10639,6 +11383,7 @@ var init_tracker = __esm({
10639
11383
  node.l1RiskType = l1.riskType;
10640
11384
  node.l1Reason = l1.reason;
10641
11385
  node.l1MatchedPatterns = l1.matchedPatterns || [];
11386
+ node.l1AskReason = l1.askReason || "";
10642
11387
  if (l1.riskLevel === "critical") {
10643
11388
  this.result.hasCritical = true;
10644
11389
  if (!this.result.firstHitNode) this.result.firstHitNode = node;
@@ -10691,9 +11436,9 @@ var init_tracker = __esm({
10691
11436
  });
10692
11437
 
10693
11438
  // src/engine/script-content-analyzer.ts
10694
- import { statSync as statSync6, existsSync as existsSync13 } from "fs";
10695
- import { resolve as resolve11, join as join13, isAbsolute as isAbsolute5 } from "path";
10696
- import { homedir as homedir5 } from "os";
11439
+ import { statSync as statSync7, existsSync as existsSync14 } from "fs";
11440
+ import { resolve as resolve11, join as join14, isAbsolute as isAbsolute5 } from "path";
11441
+ import { homedir as homedir6 } from "os";
10697
11442
  function emptyChain() {
10698
11443
  return {
10699
11444
  nodes: [],
@@ -10804,8 +11549,8 @@ function extractInlineScriptPath(actionDetail) {
10804
11549
  if (looksLikeScriptPath(tok)) {
10805
11550
  try {
10806
11551
  const resolved = resolvePath2(tok.replace(/^['"]|['"]$/g, ""));
10807
- if (existsSync13(resolved)) {
10808
- const stat = statSync6(resolved);
11552
+ if (existsSync14(resolved)) {
11553
+ const stat = statSync7(resolved);
10809
11554
  if (stat.isFile()) return resolved;
10810
11555
  }
10811
11556
  } catch {
@@ -10818,8 +11563,8 @@ function extractInlineScriptPath(actionDetail) {
10818
11563
  const p = m[1];
10819
11564
  try {
10820
11565
  const resolved = resolvePath2(p);
10821
- if (existsSync13(resolved)) {
10822
- const stat = statSync6(resolved);
11566
+ if (existsSync14(resolved)) {
11567
+ const stat = statSync7(resolved);
10823
11568
  if (stat.isFile()) return resolved;
10824
11569
  }
10825
11570
  } catch {
@@ -10834,8 +11579,8 @@ function extractInlineScriptPath(actionDetail) {
10834
11579
  let resolved;
10835
11580
  try {
10836
11581
  resolved = resolvePath2(p);
10837
- if (existsSync13(resolved)) {
10838
- const stat = statSync6(resolved);
11582
+ if (existsSync14(resolved)) {
11583
+ const stat = statSync7(resolved);
10839
11584
  if (stat.isFile()) return resolved;
10840
11585
  }
10841
11586
  } catch {
@@ -10875,7 +11620,7 @@ function shlexSplit(s) {
10875
11620
  function resolvePath2(p) {
10876
11621
  let expanded = p;
10877
11622
  if (expanded.startsWith("~/") || expanded === "~") {
10878
- expanded = join13(homedir5(), expanded.slice(1));
11623
+ expanded = join14(homedir6(), expanded.slice(1));
10879
11624
  }
10880
11625
  return resolve11(expanded);
10881
11626
  }
@@ -10902,6 +11647,31 @@ function scanExtensionPatterns(ext, content) {
10902
11647
  }
10903
11648
  return null;
10904
11649
  }
11650
+ function scanSensitiveSegments(content, cwd, ext, osType) {
11651
+ let prefilter = null;
11652
+ try {
11653
+ const { root, home, credential } = getSensitivePathsForOs(osType);
11654
+ const prefixes = [];
11655
+ for (const sp of [...root, ...home, ...credential]) {
11656
+ const prefix = String(sp.path || "").split("(")[0].trim();
11657
+ if (prefix) prefixes.push(prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
11658
+ }
11659
+ if (prefixes.length) prefilter = new RegExp(prefixes.join("|"), "i");
11660
+ } catch {
11661
+ }
11662
+ let best = null;
11663
+ for (const raw of content.split(/&&|\|\||;|\n/)) {
11664
+ const seg = raw.trim();
11665
+ if (!seg) continue;
11666
+ if (prefilter && !prefilter.test(seg)) continue;
11667
+ const j = checkSensitivePath(seg, cwd, ext, osType);
11668
+ if (!j || j.allowed) continue;
11669
+ if (!best || (LEVEL_ORDER2[j.riskLevel] || 0) > (LEVEL_ORDER2[best.riskLevel] || 0)) {
11670
+ best = { riskLevel: j.riskLevel, riskType: j.riskType, reason: j.reason, askReason: j.ask_reason };
11671
+ }
11672
+ }
11673
+ return best;
11674
+ }
10905
11675
  function scanScriptChainWithL2(chain, input) {
10906
11676
  for (const node of chain.nodes) {
10907
11677
  if (node.error || !node.preprocessedContent) continue;
@@ -10964,31 +11734,21 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
10964
11734
  isInline = true;
10965
11735
  }
10966
11736
  if (resolvedPath && !isAbsolute5(resolvedPath) && !resolvedPath.startsWith("~/")) {
10967
- resolvedPath = join13(input.cwd || process.cwd(), resolvedPath);
11737
+ resolvedPath = join14(input.cwd || process.cwd(), resolvedPath);
10968
11738
  }
10969
11739
  const l1Adapter = (content) => {
11740
+ const candidates = [];
10970
11741
  const extHit = scanExtensionPatterns(ext, content);
10971
- if (extHit) {
10972
- return {
10973
- hit: true,
10974
- riskLevel: extHit.riskLevel,
10975
- riskType: extHit.riskType,
10976
- reason: extHit.reason,
10977
- matchedPatterns: []
10978
- };
10979
- }
11742
+ if (extHit) candidates.push({ riskLevel: extHit.riskLevel, riskType: extHit.riskType, reason: extHit.reason });
10980
11743
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
10981
- if (j && !j.allowed) {
10982
- return {
10983
- hit: true,
10984
- riskLevel: j.riskLevel,
10985
- riskType: j.riskType,
10986
- reason: j.reason,
10987
- matchedPatterns: []
10988
- // SecurityJudgment 不带模式列表(见 types.ts);留空即可
10989
- };
10990
- }
10991
- return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
11744
+ if (j && !j.allowed) candidates.push({ riskLevel: j.riskLevel, riskType: j.riskType, reason: j.reason, askReason: j.ask_reason });
11745
+ const spHit = scanSensitiveSegments(content, input.cwd || process.cwd(), ext, input.osType);
11746
+ if (spHit) candidates.push(spHit);
11747
+ if (candidates.length === 0) {
11748
+ return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
11749
+ }
11750
+ const best = candidates.reduce((a, b) => (LEVEL_ORDER2[b.riskLevel] || 0) > (LEVEL_ORDER2[a.riskLevel] || 0) ? b : a);
11751
+ return { hit: true, riskLevel: best.riskLevel, riskType: best.riskType, reason: best.reason, matchedPatterns: [], askReason: best.askReason };
10992
11752
  };
10993
11753
  const tracker = new RecursiveTracker(
10994
11754
  l1Adapter,
@@ -11565,17 +12325,17 @@ __export(token_stats_exports, {
11565
12325
  resetTokenStats: () => resetTokenStats,
11566
12326
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
11567
12327
  });
11568
- import { readFileSync as readFileSync14, writeFileSync as writeFileSync2, existsSync as existsSync14, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync7 } from "fs";
12328
+ import { readFileSync as readFileSync14, writeFileSync as writeFileSync2, existsSync as existsSync15, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync8 } from "fs";
11569
12329
  function getStatsPath() {
11570
12330
  const envPath = process.env[ENV_STATS_PATH];
11571
12331
  if (envPath) return envPath;
11572
12332
  return getTokenStatsPath();
11573
12333
  }
11574
12334
  function loadAllRecords(statsPath) {
11575
- if (!existsSync14(statsPath)) return [];
12335
+ if (!existsSync15(statsPath)) return [];
11576
12336
  let sig = "";
11577
12337
  try {
11578
- const st = statSync7(statsPath);
12338
+ const st = statSync8(statsPath);
11579
12339
  sig = `${st.mtimeMs}:${st.size}`;
11580
12340
  } catch {
11581
12341
  return [];
@@ -11598,7 +12358,7 @@ function loadAllRecords(statsPath) {
11598
12358
  function saveRecords(statsPath, records) {
11599
12359
  try {
11600
12360
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
11601
- if (dir && !existsSync14(dir)) mkdirSync3(dir, { recursive: true });
12361
+ if (dir && !existsSync15(dir)) mkdirSync3(dir, { recursive: true });
11602
12362
  const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
11603
12363
  try {
11604
12364
  writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
@@ -11610,7 +12370,7 @@ function saveRecords(statsPath, records) {
11610
12370
  }
11611
12371
  }
11612
12372
  try {
11613
- const st = statSync7(statsPath);
12373
+ const st = statSync8(statsPath);
11614
12374
  _recordsCache = {
11615
12375
  path: statsPath,
11616
12376
  sig: `${st.mtimeMs}:${st.size}`,
@@ -11747,7 +12507,7 @@ function getTokenTrend(days = 0, startDate, endDate) {
11747
12507
  }
11748
12508
  function resetTokenStats() {
11749
12509
  const statsPath = getStatsPath();
11750
- if (existsSync14(statsPath)) {
12510
+ if (existsSync15(statsPath)) {
11751
12511
  try {
11752
12512
  unlinkSync2(statsPath);
11753
12513
  } catch {
@@ -12163,23 +12923,37 @@ async function analyzeWithLLM(prompt, config) {
12163
12923
  }
12164
12924
  const attemptStart = performance.now();
12165
12925
  try {
12166
- const response = await client.chat.completions.create({
12167
- model: config.model,
12168
- temperature: config.temperature || 0.1,
12169
- max_tokens: config.maxTokens || 1024,
12170
- messages: [
12171
- { role: "system", content: "\u53EA\u8F93\u51FA\u7EAF JSON\uFF0C\u4E0D\u8981\u5305\u542B markdown \u6807\u8BB0\u3001\u4EE3\u7801\u5757\u6216\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002" },
12172
- { role: "user", content: prompt }
12173
- ],
12174
- signal: abortController.signal,
12175
- // 私有化网关的额外参数(关思考等)原样透传;空则不传。
12176
- ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
12177
- });
12926
+ const baseBudget = config.maxTokens || 1024;
12927
+ const escalatedBudget = Math.min(Math.max(baseBudget * 4, 16384), 32768);
12928
+ let response = null;
12929
+ let content = "";
12930
+ let finishReason;
12931
+ let usage = null;
12932
+ for (const budget of Array.from(/* @__PURE__ */ new Set([baseBudget, escalatedBudget]))) {
12933
+ response = await client.chat.completions.create({
12934
+ model: config.model,
12935
+ temperature: config.temperature || 0.1,
12936
+ max_tokens: budget,
12937
+ messages: [
12938
+ { role: "system", content: "\u53EA\u8F93\u51FA\u7EAF JSON\uFF0C\u4E0D\u8981\u5305\u542B markdown \u6807\u8BB0\u3001\u4EE3\u7801\u5757\u6216\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002" },
12939
+ { role: "user", content: prompt }
12940
+ ],
12941
+ signal: abortController.signal,
12942
+ // 私有化网关的额外参数(关思考等)原样透传;空则不传。
12943
+ ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
12944
+ });
12945
+ const msg = response.choices[0]?.message;
12946
+ content = msg?.content ?? "";
12947
+ finishReason = response.choices[0]?.finish_reason;
12948
+ usage = response.usage;
12949
+ const hasReasoning = ["reasoning", "reasoning_content", "thinking"].some((k) => typeof msg?.[k] === "string" && msg[k].length > 0);
12950
+ if (content || finishReason !== "length" || budget === escalatedBudget || !hasReasoning) break;
12951
+ console.warn(
12952
+ `[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08max_tokens=${budget}\uFF09\uFF0C\u6309\u63A8\u7406\u6A21\u578B\u7B56\u7565\u63D0\u5347\u5230 ${escalatedBudget} \u91CD\u8BD5\u4E00\u6B21\uFF08model=${config.model}\uFF09\u2014\u2014\u975E\u63A8\u7406\u6A21\u578B\u4E0D\u4F1A\u89E6\u53D1\u6B64\u8DEF\u5F84`
12953
+ );
12954
+ }
12178
12955
  const message = response.choices[0]?.message;
12179
- let content = message?.content ?? "";
12180
- const finishReason = response.choices[0]?.finish_reason;
12181
12956
  const fieldLengths = responseFieldLengths(message);
12182
- const usage = response.usage;
12183
12957
  if (!content) {
12184
12958
  const { text: fallback, field } = reasoningFallbackWithField(message);
12185
12959
  if (fallback) {
@@ -12335,9 +13109,9 @@ var init_llm_analyzer = __esm({
12335
13109
  });
12336
13110
 
12337
13111
  // src/brain/rule-store.ts
12338
- import { existsSync as existsSync15, readFileSync as readFileSync15, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
12339
- import { join as join14 } from "path";
12340
- import { homedir as homedir6 } from "os";
13112
+ import { existsSync as existsSync16, readFileSync as readFileSync15, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
13113
+ import { join as join15 } from "path";
13114
+ import { homedir as homedir7 } from "os";
12341
13115
  function getRulesPath() {
12342
13116
  const envPath = process.env[ENV_RULES_PATH];
12343
13117
  if (envPath) return envPath;
@@ -12355,7 +13129,7 @@ var init_rule_store = __esm({
12355
13129
  "src/brain/rule-store.ts"() {
12356
13130
  "use strict";
12357
13131
  init_esm_shims();
12358
- DEFAULT_RULES_PATH = join14(homedir6(), ".agentmoss", "brain", "rules.json");
13132
+ DEFAULT_RULES_PATH = join15(homedir7(), ".agentmoss", "brain", "rules.json");
12359
13133
  ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
12360
13134
  STATUS_DRAFT = "draft";
12361
13135
  STATUS_APPROVED = "approved";
@@ -12372,7 +13146,7 @@ var init_rule_store = __esm({
12372
13146
  this.data = this.load();
12373
13147
  }
12374
13148
  load() {
12375
- if (!existsSync15(this.path)) {
13149
+ if (!existsSync16(this.path)) {
12376
13150
  return { version: 1, rules: [], pattern_candidates: [] };
12377
13151
  }
12378
13152
  try {
@@ -12970,9 +13744,9 @@ var init_reviewer = __esm({
12970
13744
  });
12971
13745
 
12972
13746
  // src/brain/skill-manager.ts
12973
- import { existsSync as existsSync16, mkdirSync as mkdirSync5, readFileSync as readFileSync16, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
12974
- import { homedir as homedir7 } from "os";
12975
- import { join as join15 } from "path";
13747
+ import { existsSync as existsSync17, mkdirSync as mkdirSync5, readFileSync as readFileSync16, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
13748
+ import { homedir as homedir8 } from "os";
13749
+ import { join as join16 } from "path";
12976
13750
  import { randomUUID } from "crypto";
12977
13751
  function getMetaPath(override) {
12978
13752
  return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
@@ -12982,14 +13756,14 @@ var init_skill_manager = __esm({
12982
13756
  "src/brain/skill-manager.ts"() {
12983
13757
  "use strict";
12984
13758
  init_esm_shims();
12985
- DEFAULT_SKILL_META_PATH = join15(homedir7(), ".agentmoss", "brain", "skill_meta.json");
13759
+ DEFAULT_SKILL_META_PATH = join16(homedir8(), ".agentmoss", "brain", "skill_meta.json");
12986
13760
  ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
12987
13761
  BrainSkillManager = class {
12988
13762
  constructor(skillsDir, metaPath) {
12989
13763
  this.skillsDir = skillsDir;
12990
13764
  this.metaPath = getMetaPath(metaPath);
12991
13765
  try {
12992
- mkdirSync5(join15(this.metaPath, ".."), { recursive: true });
13766
+ mkdirSync5(join16(this.metaPath, ".."), { recursive: true });
12993
13767
  } catch {
12994
13768
  }
12995
13769
  this.load();
@@ -12999,7 +13773,7 @@ var init_skill_manager = __esm({
12999
13773
  skills = [];
13000
13774
  metaPath;
13001
13775
  load() {
13002
- if (!existsSync16(this.metaPath)) return;
13776
+ if (!existsSync17(this.metaPath)) return;
13003
13777
  try {
13004
13778
  const data = JSON.parse(readFileSync16(this.metaPath, "utf-8"));
13005
13779
  this.skills = data.skills || [];
@@ -13024,7 +13798,7 @@ var init_skill_manager = __esm({
13024
13798
  let changed = false;
13025
13799
  for (const sk of this.skills) {
13026
13800
  if (sk.status !== "active") continue;
13027
- if (!existsSync16(join15(this.skillsDir, `${sk.name}.md`))) {
13801
+ if (!existsSync17(join16(this.skillsDir, `${sk.name}.md`))) {
13028
13802
  sk.status = "stale";
13029
13803
  changed = true;
13030
13804
  }
@@ -13035,9 +13809,9 @@ var init_skill_manager = __esm({
13035
13809
  addSkill(skill) {
13036
13810
  const id = skill.id || randomUUID();
13037
13811
  const name = skill.name || `brain_${id.slice(0, 8)}`;
13038
- if (!existsSync16(this.skillsDir)) return "";
13039
- const mdPath = join15(this.skillsDir, `${name}.md`);
13040
- if (existsSync16(mdPath)) return "";
13812
+ if (!existsSync17(this.skillsDir)) return "";
13813
+ const mdPath = join16(this.skillsDir, `${name}.md`);
13814
+ if (existsSync17(mdPath)) return "";
13041
13815
  try {
13042
13816
  writeFileSync4(mdPath, skill.content, "utf-8");
13043
13817
  } catch {
@@ -13086,8 +13860,8 @@ var init_skill_manager = __esm({
13086
13860
  const out = [];
13087
13861
  for (const sk of this.skills) {
13088
13862
  if (sk.origin_node !== "local" || sk.status !== "active") continue;
13089
- const mdPath = join15(this.skillsDir, `${sk.name}.md`);
13090
- if (!existsSync16(mdPath)) continue;
13863
+ const mdPath = join16(this.skillsDir, `${sk.name}.md`);
13864
+ if (!existsSync17(mdPath)) continue;
13091
13865
  out.push({
13092
13866
  name: sk.name,
13093
13867
  category: sk.category || "",
@@ -13203,8 +13977,8 @@ __export(contributor_exports, {
13203
13977
  });
13204
13978
  import { mkdirSync as mkdirSync6, mkdtempSync, rmSync, writeFileSync as writeFileSync5 } from "fs";
13205
13979
  import { tmpdir as tmpdir2 } from "os";
13206
- import { join as join16 } from "path";
13207
- import { spawnSync } from "child_process";
13980
+ import { join as join17 } from "path";
13981
+ import { spawnSync as spawnSync2 } from "child_process";
13208
13982
  import { dirname as dirname12 } from "path";
13209
13983
  import { fileURLToPath as fileURLToPath10 } from "url";
13210
13984
  function collectRules(store) {
@@ -13224,7 +13998,7 @@ function collectSkills(skillMgr) {
13224
13998
  }
13225
13999
  function writeExportFiles(outDir, rules, skills) {
13226
14000
  const written = [];
13227
- const rulesDir2 = join16(outDir, "rules");
14001
+ const rulesDir2 = join17(outDir, "rules");
13228
14002
  mkdirSync6(rulesDir2, { recursive: true });
13229
14003
  const byLayer = /* @__PURE__ */ new Map();
13230
14004
  for (const r of rules) {
@@ -13232,31 +14006,31 @@ function writeExportFiles(outDir, rules, skills) {
13232
14006
  byLayer.get(r.layer).push(r);
13233
14007
  }
13234
14008
  for (const layer of [...byLayer.keys()].sort((a, b) => a - b)) {
13235
- const path10 = join16(rulesDir2, `l${layer}_brain_rules.json`);
14009
+ const path10 = join17(rulesDir2, `l${layer}_brain_rules.json`);
13236
14010
  writeFileSync5(path10, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
13237
14011
  written.push(path10);
13238
14012
  }
13239
14013
  if (rules.length === 0) {
13240
- const path10 = join16(rulesDir2, "empty.txt");
14014
+ const path10 = join17(rulesDir2, "empty.txt");
13241
14015
  writeFileSync5(path10, "(no brain rules to contribute)", "utf-8");
13242
14016
  written.push(path10);
13243
14017
  }
13244
- const skillsDir = join16(outDir, "skills");
14018
+ const skillsDir = join17(outDir, "skills");
13245
14019
  mkdirSync6(skillsDir, { recursive: true });
13246
14020
  for (const sk of skills) {
13247
- const path10 = join16(skillsDir, `${sk.name}.md`);
14021
+ const path10 = join17(skillsDir, `${sk.name}.md`);
13248
14022
  writeFileSync5(path10, sk.content || "", "utf-8");
13249
14023
  written.push(path10);
13250
14024
  }
13251
14025
  if (skills.length === 0) {
13252
- const path10 = join16(skillsDir, "empty.txt");
14026
+ const path10 = join17(skillsDir, "empty.txt");
13253
14027
  writeFileSync5(path10, "(no brain skills to contribute)", "utf-8");
13254
14028
  written.push(path10);
13255
14029
  }
13256
14030
  return written;
13257
14031
  }
13258
14032
  function runGit(args, cwd) {
13259
- const res = spawnSync("git", args, { cwd, encoding: "utf-8", timeout: 6e4 });
14033
+ const res = spawnSync2("git", args, { cwd, encoding: "utf-8", timeout: 6e4 });
13260
14034
  return {
13261
14035
  code: res.status ?? 1,
13262
14036
  stdout: res.stdout ?? "",
@@ -13379,7 +14153,7 @@ async function contribute(opts = {}) {
13379
14153
  console.log(`[Brain] push \u76EE\u6807: ${pushTarget}`);
13380
14154
  console.log(`[Brain] MR \u6307\u5411: ${DEFAULT_TARGET_REPO}`);
13381
14155
  const store = new BrainRuleStore();
13382
- const skillsDir = resolveAssetDir(__dirname8, "skills") ?? join16(__dirname8, "..", "..", "agent_moss", "skills");
14156
+ const skillsDir = resolveAssetDir(__dirname8, "skills") ?? join17(__dirname8, "..", "..", "agent_moss", "skills");
13383
14157
  const skillMgr = new BrainSkillManager(skillsDir);
13384
14158
  let rules;
13385
14159
  let skills;
@@ -13394,9 +14168,9 @@ async function contribute(opts = {}) {
13394
14168
  return 0;
13395
14169
  }
13396
14170
  console.log(`[Brain] \u5BFC\u51FA: ${rules.length} \u6761\u89C4\u5219, ${skills.length} \u4E2A Skill`);
13397
- const workdir = mkdtempSync(join16(tmpdir2(), "agentmoss-contrib-"));
14171
+ const workdir = mkdtempSync(join17(tmpdir2(), "agentmoss-contrib-"));
13398
14172
  try {
13399
- writeExportFiles(join16(workdir, "agent_moss", "brain_contrib"), rules, skills);
14173
+ writeExportFiles(join17(workdir, "agent_moss", "brain_contrib"), rules, skills);
13400
14174
  console.log(`[Brain] \u63A2\u6D4B ${pushTarget} \u8BBF\u95EE\u6743\u9650 ...`);
13401
14175
  if (!probeAccess(pushTarget)) {
13402
14176
  const username = getCurrentUsername();
@@ -13825,7 +14599,7 @@ function loadStages() {
13825
14599
  }
13826
14600
  function extractResources(actionDetail) {
13827
14601
  const resources = /* @__PURE__ */ new Set();
13828
- const text = actionDetail.replace(/'[^']*'|"[^"]*"/g, "");
14602
+ const text = actionDetail.replace(/'[^']*'|"[^"]*"/g, "").replace(WORKDIR_CMD_RE, " ");
13829
14603
  PATH_RE.lastIndex = 0;
13830
14604
  let m;
13831
14605
  while ((m = PATH_RE.exec(text)) !== null) {
@@ -13841,7 +14615,7 @@ function markStage(actionDetail) {
13841
14615
  }
13842
14616
  function markIntegrity(actionDetail) {
13843
14617
  const aps = labelEvent(actionDetail);
13844
- if (aps.has("download_file") || aps.has("prompt_injection")) {
14618
+ if (aps.has("download_file")) {
13845
14619
  return { integrity: "low", isLowSource: true };
13846
14620
  }
13847
14621
  return { integrity: "medium", isLowSource: false };
@@ -13966,7 +14740,7 @@ function allNodesFlat(mg) {
13966
14740
  for (const s of mg.sessions) out.push(...s.nodes);
13967
14741
  return out;
13968
14742
  }
13969
- var COMBO_STAGES2, PATH_RE, COMMON_DIR_RESOURCES;
14743
+ var COMBO_STAGES2, PATH_RE, COMMON_DIR_RESOURCES, WORKDIR_CMD_RE;
13970
14744
  var init_builder = __esm({
13971
14745
  "src/engine/formal-engine/builder.ts"() {
13972
14746
  "use strict";
@@ -13989,6 +14763,7 @@ var init_builder = __esm({
13989
14763
  "/data",
13990
14764
  "/storage"
13991
14765
  ]);
14766
+ WORKDIR_CMD_RE = /\b(?:cd|pushd|mkdir)\s+(?:-[^\s;&|]+\s+)*[^\s;&|]+/gi;
13992
14767
  }
13993
14768
  });
13994
14769
 
@@ -14643,7 +15418,7 @@ var init_properties = __esm({
14643
15418
  TOOL_REGISTRY = null;
14644
15419
  COMPUTE_RE = /subprocess|os\.system|shell\s*=\s*True|\beval\(|\bexec\(|bash\s+[^\s]|sh\s+-c|python3?\s+|node\s+|\btimeout\s+|nohup\s+|\b\.\/[\w./-]+/i;
14645
15420
  STRONG_COMPUTE_TYPES = new Set(FORMAL_RULES.compute_action_types ?? []);
14646
- DL_OR_LOW_RE = /curl\s+.*-o\b|wget\s+.*\s+-O\b|curl\s+.*\|\s*(bash|sh|python)|wget\s+.*\|\s*(bash|sh|python)|git\s+clone|docker\s+pull|pip\s+install|npm\s+install|base64\s+-d/i;
15421
+ DL_OR_LOW_RE = /curl\s+.*-o\b|wget\s+.*\s+-O\b|curl\s+.*\|\s*(bash|sh|python)|wget\s+.*\|\s*(bash|sh|python)|git\s+clone|docker\s+pull|(?:pip3?(?:\.\d+)?|python[0-9.]*\s+-m\s+pip)\s+install|(?:npm|yarn|pnpm)\s+(?:i|install|add)|(?:base64|base32)\s+-d|openssl\s+base64\s+-d/i;
14647
15422
  DATA_SOURCE_READ_RE = /\b(?:cat|head|tail|less|more|sed|awk|grep|strings|base64|xxd|od|dd)\b|\b(?:open|read_text|read_bytes)\s*\(/i;
14648
15423
  ALL_PROPERTIES = [
14649
15424
  { id: "cross-session-chain", check: checkCrossSessionChain, shortName: "P1" },
@@ -16039,6 +16814,9 @@ async function runAnalysis(input) {
16039
16814
  isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
16040
16815
  );
16041
16816
  const degradedNotes = [];
16817
+ let decodedPayloads = [];
16818
+ let aliasResolution = null;
16819
+ const decodeHints = [];
16042
16820
  let scriptChain = null;
16043
16821
  if (input.aNext.actionType.toLowerCase() === "bash" && getDeployRole() === "host") {
16044
16822
  degradedNotes.push("script_content_deferred_to_sandbox: AGENT_MOSS_DEPLOY_ROLE=host");
@@ -16074,11 +16852,63 @@ async function runAnalysis(input) {
16074
16852
  riskType: node.l1RiskType,
16075
16853
  confidence: 90,
16076
16854
  source: "heuristic_script_scan",
16077
- violatedLayers: ["L1.2"]
16855
+ violatedLayers: ["L1.2"],
16856
+ ...node.l1AskReason ? { ask_recommended: true, ask_reason: node.l1AskReason } : {}
16857
+ };
16858
+ }
16859
+ }
16860
+ }
16861
+ }
16862
+ try {
16863
+ const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
16864
+ decodedPayloads = extractDecodedPayloads(
16865
+ input.aNext.actionType,
16866
+ input.aNext.actionDetail,
16867
+ handledWrite
16868
+ );
16869
+ if (input.aNext.actionType.toLowerCase() === "bash") {
16870
+ aliasResolution = resolveCommandPrefix(input.aNext.actionDetail, input.cwd || "");
16871
+ }
16872
+ if (heuristicEnabled) {
16873
+ for (const p of decodedPayloads) {
16874
+ const l1 = detectDecoded(p.decoded);
16875
+ if (!l1) continue;
16876
+ if (l1.allowed !== false) continue;
16877
+ const level = p.source === "instruction" ? l1.riskLevel : "medium";
16878
+ if (level === "high" || level === "critical") {
16879
+ return {
16880
+ allowed: false,
16881
+ reason: `\u89E3\u7801\u5206\u6790\uFF08${p.encoding} \u7F16\u7801\uFF09\uFF1A${l1.reason}`,
16882
+ riskLevel: level,
16883
+ riskType: l1.riskType,
16884
+ confidence: 95,
16885
+ source: "decode_engine",
16886
+ violatedLayers: ["L1.3"],
16887
+ ...l1.ask_reason ? { ask_recommended: true, ask_reason: l1.ask_reason } : {}
16078
16888
  };
16079
16889
  }
16890
+ decodeHints.push(`[${p.encoding}/${p.source}] ${l1.reason}`);
16080
16891
  }
16081
16892
  }
16893
+ } catch {
16894
+ }
16895
+ if (heuristicEnabled && aliasResolution) {
16896
+ const l1 = detectDecoded(aliasResolution.expansion);
16897
+ if (l1 && l1.allowed === false && (l1.riskLevel === "high" || l1.riskLevel === "critical")) {
16898
+ return {
16899
+ allowed: false,
16900
+ reason: `\u522B\u540D/\u51FD\u6570\u5C55\u5F00\uFF08${aliasResolution.word}\uFF09\uFF1A${l1.reason}`,
16901
+ riskLevel: l1.riskLevel,
16902
+ riskType: l1.riskType,
16903
+ confidence: 90,
16904
+ source: "alias_engine",
16905
+ violatedLayers: ["L1.4"],
16906
+ ...l1.ask_reason ? { ask_recommended: true, ask_reason: l1.ask_reason } : {}
16907
+ };
16908
+ }
16909
+ if (l1 && l1.allowed === false) {
16910
+ decodeHints.push(`[alias/${aliasResolution.kind}] ${l1.reason}`);
16911
+ }
16082
16912
  }
16083
16913
  const brainStore = getBrainStore(input.osType);
16084
16914
  if (brainStore) {
@@ -16294,6 +17124,48 @@ async function runAnalysis(input) {
16294
17124
  }
16295
17125
  }
16296
17126
  }
17127
+ if (decodedPayloads.length > 0 && isLogicRulesEnabled()) {
17128
+ for (const p of decodedPayloads) {
17129
+ const l2 = runLogicCheck(
17130
+ { ...input, aNext: { actionType: "bash", actionDetail: p.decoded } },
17131
+ { agentExt }
17132
+ );
17133
+ if (!l2 || l2.allowed !== false) continue;
17134
+ const level = p.source === "instruction" ? l2.riskLevel : "medium";
17135
+ if (level === "high" || level === "critical") {
17136
+ return {
17137
+ allowed: false,
17138
+ reason: `\u89E3\u7801\u5206\u6790\uFF08${p.encoding} \u7F16\u7801\uFF09\uFF1A${l2.reason}`,
17139
+ riskLevel: level,
17140
+ riskType: l2.riskType,
17141
+ confidence: 90,
17142
+ source: "decode_engine",
17143
+ violatedLayers: ["L2.4"]
17144
+ };
17145
+ }
17146
+ decodeHints.push(`[${p.encoding}/${p.source}] ${l2.reason}`);
17147
+ }
17148
+ }
17149
+ if (isLogicRulesEnabled() && aliasResolution) {
17150
+ const l2 = runLogicCheck(
17151
+ { ...input, aNext: { actionType: "bash", actionDetail: aliasResolution.expansion } },
17152
+ { agentExt }
17153
+ );
17154
+ if (l2 && l2.allowed === false && (l2.riskLevel === "high" || l2.riskLevel === "critical")) {
17155
+ return {
17156
+ allowed: false,
17157
+ reason: `\u522B\u540D/\u51FD\u6570\u5C55\u5F00\uFF08${aliasResolution.word}\uFF09\uFF1A${l2.reason}`,
17158
+ riskLevel: l2.riskLevel,
17159
+ riskType: l2.riskType,
17160
+ confidence: 90,
17161
+ source: "alias_engine",
17162
+ violatedLayers: ["L2.5"]
17163
+ };
17164
+ }
17165
+ if (l2 && l2.allowed === false) {
17166
+ decodeHints.push(`[alias/${aliasResolution.kind}] ${l2.reason}`);
17167
+ }
17168
+ }
16297
17169
  if (brainStore) {
16298
17170
  const brainL2 = checkBrainRules(brainStore, {
16299
17171
  layer: 2,
@@ -16347,6 +17219,9 @@ async function runAnalysis(input) {
16347
17219
  }
16348
17220
  } catch {
16349
17221
  }
17222
+ if (decodeHints.length > 0) {
17223
+ skipL3Hints += "\n\u89E3\u7801\u5206\u6790\u7EBF\u7D22\uFF1A\n- " + decodeHints.join("\n- ");
17224
+ }
16350
17225
  let llmResult;
16351
17226
  try {
16352
17227
  const pathContext = buildPathContext(input.aNext.actionDetail);
@@ -16429,6 +17304,8 @@ var init_coordinator = __esm({
16429
17304
  "use strict";
16430
17305
  init_esm_shims();
16431
17306
  init_heuristic();
17307
+ init_written_content_analyzer();
17308
+ init_shell_alias_resolver();
16432
17309
  init_logic_rules();
16433
17310
  init_platform_traits();
16434
17311
  init_shell_split();
@@ -16479,9 +17356,9 @@ var init_types = __esm({
16479
17356
 
16480
17357
  // src/infra/policy-cache.ts
16481
17358
  import { createHash as createHash7 } from "crypto";
16482
- import { existsSync as existsSync18, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync18, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
17359
+ import { existsSync as existsSync19, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync18, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
16483
17360
  import { tmpdir as tmpdir3 } from "os";
16484
- import { join as join19 } from "path";
17361
+ import { join as join20 } from "path";
16485
17362
  function cacheDir() {
16486
17363
  return cacheDirOverride ?? CACHE_DIR;
16487
17364
  }
@@ -16489,7 +17366,7 @@ function safeCacheDir() {
16489
17366
  const dir = cacheDir();
16490
17367
  if (ensurePrivateDir(dir)) return dir;
16491
17368
  try {
16492
- const fallback = join19(getDataRoot(), "policy_cache");
17369
+ const fallback = join20(getDataRoot(), "policy_cache");
16493
17370
  if (ensurePrivateDir(fallback)) {
16494
17371
  console.warn(`[AgentMoss] \u7F13\u5B58\u76EE\u5F55 ${dir} \u4E0D\u5B89\u5168\uFF08\u88AB\u5176\u4ED6\u7528\u6237\u62E5\u6709\u6216\u4E3A\u7B26\u53F7\u94FE\u63A5\uFF09\uFF0C\u5DF2\u56DE\u9000\u5230 ${fallback}`);
16495
17372
  return fallback;
@@ -16510,7 +17387,7 @@ var init_policy_cache = __esm({
16510
17387
  init_security_policy();
16511
17388
  init_paths();
16512
17389
  init_config();
16513
- CACHE_DIR = join19(tmpdir3(), "agent_moss_policy_cache");
17390
+ CACHE_DIR = join20(tmpdir3(), "agent_moss_policy_cache");
16514
17391
  cacheDirOverride = null;
16515
17392
  PolicyCache = class {
16516
17393
  // Map 的插入序即 LRU 序(get 时重新 set 到末尾)
@@ -16525,7 +17402,7 @@ var init_policy_cache = __esm({
16525
17402
  cacheFilePath(sessionId, promptSession) {
16526
17403
  const promptHash = createHash7("md5").update(promptSession).digest("hex").slice(0, 12);
16527
17404
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
16528
- return join19(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
17405
+ return join20(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
16529
17406
  }
16530
17407
  /** 取缓存:内存 → 文件;未命中返回 null。 */
16531
17408
  get(sessionId, promptSession) {
@@ -16538,7 +17415,7 @@ var init_policy_cache = __esm({
16538
17415
  return hit;
16539
17416
  }
16540
17417
  const file = this.cacheFilePath(sessionId, promptSession);
16541
- if (existsSync18(file) && !lstatSync2(file).isSymbolicLink()) {
17418
+ if (existsSync19(file) && !lstatSync2(file).isSymbolicLink()) {
16542
17419
  try {
16543
17420
  const policy = readFileSync18(file, "utf-8");
16544
17421
  this.remember(key, policy);
@@ -16556,7 +17433,7 @@ var init_policy_cache = __esm({
16556
17433
  try {
16557
17434
  const dir = safeCacheDir();
16558
17435
  const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
16559
- if (!ensurePrivateDir(join19(dir, sub))) return;
17436
+ if (!ensurePrivateDir(join20(dir, sub))) return;
16560
17437
  writePrivateText(file, policy);
16561
17438
  } catch {
16562
17439
  }
@@ -16582,12 +17459,12 @@ var init_policy_cache = __esm({
16582
17459
  if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
16583
17460
  }
16584
17461
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
16585
- const dir = join19(cacheDir(), safeSessionId);
17462
+ const dir = join20(cacheDir(), safeSessionId);
16586
17463
  try {
16587
- if (existsSync18(dir)) {
17464
+ if (existsSync19(dir)) {
16588
17465
  for (const f of readdirSync6(dir)) {
16589
17466
  try {
16590
- unlinkSync5(join19(dir, f));
17467
+ unlinkSync5(join20(dir, f));
16591
17468
  } catch {
16592
17469
  }
16593
17470
  }
@@ -16599,11 +17476,11 @@ var init_policy_cache = __esm({
16599
17476
  clear() {
16600
17477
  this.memory.clear();
16601
17478
  try {
16602
- if (existsSync18(cacheDir())) {
17479
+ if (existsSync19(cacheDir())) {
16603
17480
  for (const sessionDir of readdirSync6(cacheDir())) {
16604
- const dir = join19(cacheDir(), sessionDir);
17481
+ const dir = join20(cacheDir(), sessionDir);
16605
17482
  try {
16606
- for (const f of readdirSync6(dir)) unlinkSync5(join19(dir, f));
17483
+ for (const f of readdirSync6(dir)) unlinkSync5(join20(dir, f));
16607
17484
  rmdirSync(dir);
16608
17485
  } catch {
16609
17486
  }
@@ -16699,9 +17576,9 @@ __export(analyzer_exports, {
16699
17576
  savePolicyToFile: () => savePolicyToFile,
16700
17577
  validateToml: () => validateToml
16701
17578
  });
16702
- import { existsSync as existsSync19, readFileSync as readFileSync19 } from "fs";
17579
+ import { existsSync as existsSync20, readFileSync as readFileSync19 } from "fs";
16703
17580
  import { tmpdir as tmpdir4 } from "os";
16704
- import { join as join20, resolve as resolve12 } from "path";
17581
+ import { join as join21, resolve as resolve12 } from "path";
16705
17582
  import { parse as parseToml } from "smol-toml";
16706
17583
  function _setPolicyOutputDirForTest(dir) {
16707
17584
  policyOutputDirOverride = dir;
@@ -16718,7 +17595,7 @@ function savePolicyToFile(sessionId, policyToml) {
16718
17595
  return null;
16719
17596
  }
16720
17597
  const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
16721
- const filepath = join20(outDir, `${safeName}.toml`);
17598
+ const filepath = join21(outDir, `${safeName}.toml`);
16722
17599
  writePrivateText(filepath, policyToml);
16723
17600
  return filepath;
16724
17601
  } catch (err) {
@@ -16757,11 +17634,11 @@ function loadPolicyMappingDoc() {
16757
17634
  const dir = resolveAssetDir(__dirname, "templates");
16758
17635
  if (dir) {
16759
17636
  const p = resolve12(dir, "policy_mapping.md");
16760
- if (existsSync19(p)) return readFileSync19(p, "utf-8");
17637
+ if (existsSync20(p)) return readFileSync19(p, "utf-8");
16761
17638
  }
16762
17639
  for (const cand of assetDirCandidates(__dirname, "templates")) {
16763
17640
  const p = resolve12(cand, "policy_mapping.md");
16764
- if (existsSync19(p)) return readFileSync19(p, "utf-8");
17641
+ if (existsSync20(p)) return readFileSync19(p, "utf-8");
16765
17642
  }
16766
17643
  return "";
16767
17644
  }
@@ -16872,9 +17749,9 @@ async function analyzeInner(input, mossLog) {
16872
17749
  mossLog.logResult("Deny", denied.reason);
16873
17750
  return withL3(denied, judgment);
16874
17751
  }
16875
- const cache3 = getDefaultCache();
17752
+ const cache4 = getDefaultCache();
16876
17753
  mossLog.startStep("step2_cache_lookup");
16877
- const cached2 = cache3.get(input.sessionId, input.promptSession);
17754
+ const cached2 = cache4.get(input.sessionId, input.promptSession);
16878
17755
  if (cached2 !== null) {
16879
17756
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u547D\u4E2D");
16880
17757
  savePolicyToFile(input.sessionId, cached2);
@@ -16885,7 +17762,7 @@ async function analyzeInner(input, mossLog) {
16885
17762
  if (!isPolicyGenEnabled()) {
16886
17763
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0CPolicy \u751F\u6210\u5DF2\u7981\u7528");
16887
17764
  mossLog.startStep("step2_default_policy");
16888
- cache3.put(input.sessionId, input.promptSession, DEFAULT_READONLY_POLICY);
17765
+ cache4.put(input.sessionId, input.promptSession, DEFAULT_READONLY_POLICY);
16889
17766
  savePolicyToFile(input.sessionId, DEFAULT_READONLY_POLICY);
16890
17767
  const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
16891
17768
  mossLog.endStep("step2_default_policy", "\u4F7F\u7528\u9ED8\u8BA4\u6700\u5C0F\u6743\u9650 Policy");
@@ -16894,7 +17771,7 @@ async function analyzeInner(input, mossLog) {
16894
17771
  }
16895
17772
  if (judgment.source === "whitelist_bypass") {
16896
17773
  mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u767D\u540D\u5355\u5DE5\u5177");
16897
- cache3.put(input.sessionId, input.promptSession, DEFAULT_READONLY_POLICY);
17774
+ cache4.put(input.sessionId, input.promptSession, DEFAULT_READONLY_POLICY);
16898
17775
  savePolicyToFile(input.sessionId, DEFAULT_READONLY_POLICY);
16899
17776
  const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
16900
17777
  mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
@@ -16904,7 +17781,7 @@ async function analyzeInner(input, mossLog) {
16904
17781
  mossLog.startStep("step2_generate_policy");
16905
17782
  try {
16906
17783
  const policy = await generatePolicyWithLLM(input.sessionId, input.promptSession);
16907
- cache3.put(input.sessionId, input.promptSession, policy);
17784
+ cache4.put(input.sessionId, input.promptSession, policy);
16908
17785
  savePolicyToFile(input.sessionId, policy);
16909
17786
  mossLog.endStep("step2_generate_policy", "Policy \u751F\u6210\u5E76\u7F13\u5B58\u6210\u529F");
16910
17787
  const res = allowResult(policy, judgment);
@@ -16941,7 +17818,7 @@ var init_analyzer = __esm({
16941
17818
  init_asset_dir();
16942
17819
  init_token_stats();
16943
17820
  init_logging();
16944
- POLICY_OUTPUT_DIR = join20(tmpdir4(), "agent_moss");
17821
+ POLICY_OUTPUT_DIR = join21(tmpdir4(), "agent_moss");
16945
17822
  policyOutputDirOverride = null;
16946
17823
  DEFAULT_READONLY_POLICY = `landlock_optional = false
16947
17824
  mount_isolation_fallback = false
@@ -17092,6 +17969,26 @@ var init_actrail = __esm({
17092
17969
  }
17093
17970
  });
17094
17971
 
17972
+ // src/infra/os-type.ts
17973
+ function currentOsType() {
17974
+ const env2 = String(process.env.AGENT_MOSS_OS_TYPE || "").trim().toLowerCase();
17975
+ if (env2) {
17976
+ if (["hmos", "openharmony", "hongmeng", "harmony"].includes(env2)) return "harmony";
17977
+ if (["darwin", "mac", "macosx", "osx", "macos"].includes(env2)) return "macos";
17978
+ if (env2 === "windows") return "windows";
17979
+ return "linux";
17980
+ }
17981
+ if (process.platform === "win32") return "windows";
17982
+ if (process.platform === "darwin") return "macos";
17983
+ return "linux";
17984
+ }
17985
+ var init_os_type = __esm({
17986
+ "src/infra/os-type.ts"() {
17987
+ "use strict";
17988
+ init_esm_shims();
17989
+ }
17990
+ });
17991
+
17095
17992
  // src/engine/formal-engine/pattern_miner.ts
17096
17993
  function projectStages(actionHistory) {
17097
17994
  const stages = [];
@@ -17429,7 +18326,7 @@ var init_runtime_stats = __esm({
17429
18326
 
17430
18327
  // src/routes.ts
17431
18328
  import { randomBytes as randomBytes2 } from "crypto";
17432
- import { join as join22, dirname as dirname14 } from "path";
18329
+ import { join as join23, dirname as dirname14 } from "path";
17433
18330
  import { fileURLToPath as fileURLToPath11 } from "url";
17434
18331
  async function healthRoute(c) {
17435
18332
  const metrics = {};
@@ -17497,7 +18394,7 @@ async function analyzeRoute(c) {
17497
18394
  }
17498
18395
  let osType = req.os_type;
17499
18396
  if (!osType) {
17500
- osType = process.platform === "win32" ? "windows" : "linux";
18397
+ osType = currentOsType();
17501
18398
  }
17502
18399
  const _principal = principalOf(c.req.raw.headers, new URL(c.req.url).pathname);
17503
18400
  const [_boundOk, agentId] = bindAgent(_principal, req.agent_id || req.metadata?.agent_type || "");
@@ -17987,7 +18884,7 @@ function getBrainRuleStore() {
17987
18884
  return new BrainRuleStore();
17988
18885
  }
17989
18886
  function getBrainSkillManager() {
17990
- const dir = resolveAssetDir(__dirname9, "skills") ?? join22(__dirname9, "..", "..", "agent_moss", "skills");
18887
+ const dir = resolveAssetDir(__dirname9, "skills") ?? join23(__dirname9, "..", "..", "agent_moss", "skills");
17991
18888
  return new BrainSkillManager(dir);
17992
18889
  }
17993
18890
  async function brainRulesRoute(c) {
@@ -18090,6 +18987,7 @@ var init_routes = __esm({
18090
18987
  init_formal_engine();
18091
18988
  init_stateful();
18092
18989
  init_circuit_breaker();
18990
+ init_os_type();
18093
18991
  init_pattern_miner();
18094
18992
  init_agent_gate_reader();
18095
18993
  init_observable();
@@ -18108,8 +19006,8 @@ var init_routes = __esm({
18108
19006
  // src/console/router.ts
18109
19007
  import { Hono } from "hono";
18110
19008
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
18111
- import { readFileSync as readFileSync21, existsSync as existsSync21, unlinkSync as unlinkSync6 } from "fs";
18112
- import { join as join23, dirname as dirname15 } from "path";
19009
+ import { readFileSync as readFileSync21, existsSync as existsSync22, unlinkSync as unlinkSync6 } from "fs";
19010
+ import { join as join24, dirname as dirname15 } from "path";
18113
19011
  import { fileURLToPath as fileURLToPath12 } from "url";
18114
19012
  function getConsoleToken() {
18115
19013
  return process.env[CONSOLE_TOKEN_ENV] || "";
@@ -18161,8 +19059,8 @@ function createConsoleRouter() {
18161
19059
  console2.use("/api/*", authMiddleware());
18162
19060
  console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
18163
19061
  const serveIndex = (c) => {
18164
- const indexFile = join23(STATIC_DIR, "index.html");
18165
- if (existsSync21(indexFile)) {
19062
+ const indexFile = join24(STATIC_DIR, "index.html");
19063
+ if (existsSync22(indexFile)) {
18166
19064
  return c.html(readFileSync21(indexFile, "utf-8"));
18167
19065
  }
18168
19066
  return c.html("<h1>AgentMoss Policy Console</h1><p>Frontend not built. Use /console/api/* endpoints.</p>");
@@ -18193,7 +19091,6 @@ function createConsoleRouter() {
18193
19091
  "mc-ltl-001": "\u5148\u8BFB\u53D6\u4E86\u51ED\u636E/\u5BC6\u94A5\uFF0C\u4E4B\u540E\u51FA\u73B0\u7F51\u7EDC\u5916\u4F20",
18194
19092
  "mc-ltl-002": "\u5148\u4E0B\u8F7D/\u83B7\u53D6\u4E86\u6587\u4EF6\uFF0C\u4E4B\u540E\u6267\u884C\u4E86\u6587\u4EF6",
18195
19093
  "mc-ltl-003": "\u5148\u7981\u7528\u4E86\u5B89\u5168\u9632\u62A4\uFF0C\u4E4B\u540E\u51FA\u73B0\u7834\u574F\u6027\u64CD\u4F5C\uFF08\u6267\u884C/\u5220\u9664/\u63D0\u6743\uFF09",
18196
- "mc-ltl-004": "\u5148\u51FA\u73B0\u63D0\u793A\u8BCD\u6CE8\u5165\uFF0C\u4E4B\u540E\u51FA\u73B0\u654F\u611F\u64CD\u4F5C\uFF08\u5916\u4F20/\u5199\u6587\u4EF6/\u6267\u884C\uFF09",
18197
19094
  "mc-ltl-005": "\u5148\u8BFB\u53D6\u51ED\u636E\uFF0C\u4E4B\u540E\u51FA\u73B0\u6A2A\u5411\u79FB\u52A8\uFF08ssh/scp \u5230\u8FDC\u7A0B\uFF09",
18198
19095
  "mc-ltl-006": "\u5148\u63A5\u89E6\u654F\u611F\u6570\u636E\uFF0C\u4E4B\u540E\u6E05\u9664\u65E5\u5FD7",
18199
19096
  "mc-ltl-007": "\u5148\u63D0\u6743\uFF0C\u4E4B\u540E\u5B89\u88C5\u6301\u4E45\u5316\u540E\u95E8",
@@ -18234,7 +19131,6 @@ function createConsoleRouter() {
18234
19131
  "mc-ltl-001": "\u5148\u8BFB\u53D6\u4E86\u51ED\u636E/\u5BC6\u94A5\uFF0C\u4E4B\u540E\u51FA\u73B0\u7F51\u7EDC\u5916\u4F20",
18235
19132
  "mc-ltl-002": "\u5148\u4E0B\u8F7D/\u83B7\u53D6\u4E86\u6587\u4EF6\uFF0C\u4E4B\u540E\u6267\u884C\u4E86\u6587\u4EF6",
18236
19133
  "mc-ltl-003": "\u5148\u7981\u7528\u4E86\u5B89\u5168\u9632\u62A4\uFF0C\u4E4B\u540E\u51FA\u73B0\u7834\u574F\u6027\u64CD\u4F5C\uFF08\u6267\u884C/\u5220\u9664/\u63D0\u6743\uFF09",
18237
- "mc-ltl-004": "\u5148\u51FA\u73B0\u63D0\u793A\u8BCD\u6CE8\u5165\uFF0C\u4E4B\u540E\u51FA\u73B0\u654F\u611F\u64CD\u4F5C\uFF08\u5916\u4F20/\u5199\u6587\u4EF6/\u6267\u884C\uFF09",
18238
19134
  "mc-ltl-005": "\u5148\u8BFB\u53D6\u51ED\u636E\uFF0C\u4E4B\u540E\u51FA\u73B0\u6A2A\u5411\u79FB\u52A8\uFF08ssh/scp \u5230\u8FDC\u7A0B\uFF09",
18239
19135
  "mc-ltl-006": "\u5148\u63A5\u89E6\u654F\u611F\u6570\u636E\uFF0C\u4E4B\u540E\u6E05\u9664\u65E5\u5FD7",
18240
19136
  "mc-ltl-007": "\u5148\u63D0\u6743\uFF0C\u4E4B\u540E\u5B89\u88C5\u6301\u4E45\u5316\u540E\u95E8",
@@ -18284,6 +19180,14 @@ function createConsoleRouter() {
18284
19180
  const rc = updateRuleEnabled(b.layer, b.category, b.rule_id, b.enabled);
18285
19181
  return c.json(withL22View(rc));
18286
19182
  });
19183
+ console2.put("/api/rules/tier_enabled", async (c) => {
19184
+ const b = await c.req.json();
19185
+ if (!["strong", "weak"].includes(b.tier)) {
19186
+ return c.json({ detail: `\u65E0\u6548\u7684 tier: ${b.tier}` }, 400);
19187
+ }
19188
+ const rc = updateInjectionTierEnabled(b.tier, b.enabled);
19189
+ return c.json(withL22View(rc));
19190
+ });
18287
19191
  console2.put("/api/rules/deny_mode", async (c) => {
18288
19192
  const b = await c.req.json();
18289
19193
  if (!["deny_write", "deny_read", "deny_both"].includes(b.deny_mode)) {
@@ -18292,6 +19196,16 @@ function createConsoleRouter() {
18292
19196
  const rc = updateRuleDenyMode(b.layer, b.category, b.rule_id, b.deny_mode);
18293
19197
  return c.json(withL22View(rc));
18294
19198
  });
19199
+ console2.put("/api/rules/ask", async (c) => {
19200
+ const b = await c.req.json();
19201
+ const rc = updateRuleAsk(b.layer, b.category, b.rule_id, b.ask_on_match === true);
19202
+ return c.json(withL22View(rc));
19203
+ });
19204
+ console2.put("/api/categories/ask", async (c) => {
19205
+ const b = await c.req.json();
19206
+ const rc = updateCategoryAsk(b.layer, b.category, b.ask_on_match === true);
19207
+ return c.json(withL22View(rc));
19208
+ });
18295
19209
  console2.put("/api/rules/skip_l3", async (c) => {
18296
19210
  const b = await c.req.json();
18297
19211
  const rc = updateRuleSkipL3(b.layer, b.category, b.rule_id, b.skip_l3_on_disabled);
@@ -18304,7 +19218,8 @@ function createConsoleRouter() {
18304
19218
  });
18305
19219
  console2.post("/api/rules", async (c) => {
18306
19220
  const b = await c.req.json();
18307
- const rc = addCustomRule(b.layer, b.category, {
19221
+ const layer = b.category === "sensitive_path_access" ? "L1_rules" : b.layer;
19222
+ const rc = addCustomRule(layer, b.category, {
18308
19223
  pattern: b.pattern,
18309
19224
  risk_level: b.risk_level,
18310
19225
  risk_type: b.risk_type,
@@ -18358,14 +19273,14 @@ function createConsoleRouter() {
18358
19273
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
18359
19274
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
18360
19275
  }
18361
- const userPath = join23(dirname15(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
19276
+ const userPath = join24(dirname15(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
18362
19277
  const builtinDir = resolveAssetDir(__dirname10, "skills");
18363
19278
  const candidates = [
18364
19279
  ...isRuntimeConfigDisabled() ? [] : [userPath],
18365
- builtinDir ? join23(builtinDir, `${skillId}.md`) : ""
19280
+ builtinDir ? join24(builtinDir, `${skillId}.md`) : ""
18366
19281
  ].filter(Boolean);
18367
19282
  for (const p of candidates) {
18368
- if (existsSync21(p)) {
19283
+ if (existsSync22(p)) {
18369
19284
  return c.json({ skill_id: skillId, path: p, content: readFileSync21(p, "utf-8") });
18370
19285
  }
18371
19286
  }
@@ -18462,7 +19377,14 @@ function createConsoleRouter() {
18462
19377
  });
18463
19378
  console2.get("/api/config", (c) => {
18464
19379
  const rc = displayRuntimeConfig();
18465
- return c.json({ ...rc, L2_2: getL22View(), builtin_only: isBuiltinOnly(), rules_mode: getRulesMode() });
19380
+ const osType = currentOsType();
19381
+ return c.json({
19382
+ ...rc,
19383
+ L2_2: getL22View(),
19384
+ builtin_only: isBuiltinOnly(),
19385
+ rules_mode: getRulesMode(),
19386
+ platform: { os_type: osType, accepted_os: acceptedOsValues(osType) }
19387
+ });
18466
19388
  });
18467
19389
  console2.get("/api/env-overrides", (c) => {
18468
19390
  return c.json({ overrides: getEnvOverrides() });
@@ -18471,7 +19393,7 @@ function createConsoleRouter() {
18471
19393
  const defaults = generateSourceDefaults();
18472
19394
  try {
18473
19395
  const p = getRuntimeConfigPath();
18474
- if (existsSync21(p)) unlinkSync6(p);
19396
+ if (existsSync22(p)) unlinkSync6(p);
18475
19397
  } catch {
18476
19398
  }
18477
19399
  return c.json(withL22View(defaults));
@@ -18508,8 +19430,10 @@ var init_router = __esm({
18508
19430
  init_asset_dir();
18509
19431
  init_rules_mode();
18510
19432
  init_edition_scope();
19433
+ init_logic_rules();
19434
+ init_os_type();
18511
19435
  __dirname10 = dirname15(fileURLToPath12(import.meta.url));
18512
- STATIC_DIR = join23(__dirname10, "static");
19436
+ STATIC_DIR = join24(__dirname10, "static");
18513
19437
  CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
18514
19438
  }
18515
19439
  });
@@ -18537,7 +19461,7 @@ import { Hono as Hono2 } from "hono";
18537
19461
  import { cors } from "hono/cors";
18538
19462
  import { logger } from "hono/logger";
18539
19463
  import net from "net";
18540
- import { existsSync as existsSync22, writeFileSync as writeFileSync8, renameSync as renameSync3, mkdirSync as mkdirSync11 } from "fs";
19464
+ import { existsSync as existsSync23, writeFileSync as writeFileSync8, renameSync as renameSync3, mkdirSync as mkdirSync11 } from "fs";
18541
19465
  import { dirname as dirname16 } from "path";
18542
19466
  function logDeploymentSelfCheck() {
18543
19467
  try {
@@ -18565,7 +19489,7 @@ function logDeploymentSelfCheck() {
18565
19489
  console.log("\u5C42\u7EA7\u5F00\u5173: " + layerKeys.map((k) => `${k}=${isLayerEnabled(k) ? "on" : "OFF"}`).join(" "));
18566
19490
  if (!builtinOnly) {
18567
19491
  try {
18568
- const dirs = rulesDirs().filter((d) => existsSync22(d));
19492
+ const dirs = rulesDirs().filter((d) => existsSync23(d));
18569
19493
  if (dirs.length > 0) {
18570
19494
  console.log(`\u89C4\u5219\u76EE\u5F55: ${dirs.join(", ")}\uFF08\u53EA\u8BFB\u5176\u4E2D ${OVERRIDE_FILENAME} / ${EXTRA_FILENAME}\uFF09`);
18571
19495
  }
@@ -18860,7 +19784,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
18860
19784
  },
18861
19785
  serve: async () => {
18862
19786
  failFastOnAuthError();
18863
- const { mkdirSync: mkdirSync13, existsSync: existsSync24, unlinkSync: unlinkSync7 } = await import("fs");
19787
+ const { mkdirSync: mkdirSync13, existsSync: existsSync25, unlinkSync: unlinkSync7 } = await import("fs");
18864
19788
  const { dirname: dirname18 } = await import("path");
18865
19789
  const dir = dirname18(socketPath);
18866
19790
  if (dir) {
@@ -18869,7 +19793,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
18869
19793
  } catch {
18870
19794
  }
18871
19795
  }
18872
- if (existsSync24(socketPath)) {
19796
+ if (existsSync25(socketPath)) {
18873
19797
  const { connect } = await import("net");
18874
19798
  const inUse = await new Promise((resolve13) => {
18875
19799
  const probe = connect(socketPath);
@@ -18999,24 +19923,24 @@ __export(rules_tools_exports, {
18999
19923
  rulesStatusText: () => rulesStatusText,
19000
19924
  templateSourceDir: () => templateSourceDir
19001
19925
  });
19002
- import { existsSync as existsSync23, mkdirSync as mkdirSync12, readdirSync as readdirSync8, readFileSync as readFileSync22, writeFileSync as writeFileSync9 } from "fs";
19003
- import { dirname as dirname17, join as join25 } from "path";
19926
+ import { existsSync as existsSync24, mkdirSync as mkdirSync12, readdirSync as readdirSync8, readFileSync as readFileSync22, writeFileSync as writeFileSync9 } from "fs";
19927
+ import { dirname as dirname17, join as join26 } from "path";
19004
19928
  import { fileURLToPath as fileURLToPath13 } from "url";
19005
19929
  function initRulesDir(targetDir, opts = {}) {
19006
19930
  mkdirSync12(targetDir, { recursive: true });
19007
19931
  const written = [];
19008
- const extraPath = join25(targetDir, EXTRA_FILENAME);
19009
- if (opts.force || !existsSync23(extraPath)) {
19932
+ const extraPath = join26(targetDir, EXTRA_FILENAME);
19933
+ if (opts.force || !existsSync24(extraPath)) {
19010
19934
  writeFileSync9(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
19011
19935
  written.push(extraPath);
19012
19936
  }
19013
- const samplePath = join25(targetDir, OVERRIDE_FILENAME);
19014
- if (opts.force || !existsSync23(samplePath)) {
19937
+ const samplePath = join26(targetDir, OVERRIDE_FILENAME);
19938
+ if (opts.force || !existsSync24(samplePath)) {
19015
19939
  let payload = OVERRIDE_TEMPLATE;
19016
19940
  if (opts.withBuiltin) {
19017
19941
  let data = {};
19018
19942
  const builtin = resolveRulesFile("l1_rules.json");
19019
- if (builtin && existsSync23(builtin)) {
19943
+ if (builtin && existsSync24(builtin)) {
19020
19944
  try {
19021
19945
  data = JSON.parse(readFileSync22(builtin, "utf-8")) || {};
19022
19946
  } catch {
@@ -19029,17 +19953,17 @@ function initRulesDir(targetDir, opts = {}) {
19029
19953
  writeFileSync9(samplePath, JSON.stringify(payload, null, 2), "utf-8");
19030
19954
  written.push(samplePath);
19031
19955
  }
19032
- const readmeSrc = join25(templateSourceDir(), "README.md");
19033
- const readmeDst = join25(targetDir, "README.md");
19034
- if (existsSync23(readmeSrc) && (opts.force || !existsSync23(readmeDst))) {
19956
+ const readmeSrc = join26(templateSourceDir(), "README.md");
19957
+ const readmeDst = join26(targetDir, "README.md");
19958
+ if (existsSync24(readmeSrc) && (opts.force || !existsSync24(readmeDst))) {
19035
19959
  writeFileSync9(readmeDst, readFileSync22(readmeSrc, "utf-8"), "utf-8");
19036
19960
  written.push(readmeDst);
19037
19961
  }
19038
19962
  return written;
19039
19963
  }
19040
19964
  function templateSourceDir() {
19041
- const cands = [join25(__dirname11, "data", "rules_template"), join25(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
19042
- for (const c of cands) if (existsSync23(c)) return c;
19965
+ const cands = [join26(__dirname11, "data", "rules_template"), join26(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
19966
+ for (const c of cands) if (existsSync24(c)) return c;
19043
19967
  return cands[0];
19044
19968
  }
19045
19969
  function templateFiles(dirs) {
@@ -19047,7 +19971,7 @@ function templateFiles(dirs) {
19047
19971
  for (const d of dirs) {
19048
19972
  try {
19049
19973
  for (const name of readdirSync8(d)) {
19050
- if (name.endsWith(".json.\u793A\u4F8B")) out.push(join25(d, name));
19974
+ if (name.endsWith(".json.\u793A\u4F8B")) out.push(join26(d, name));
19051
19975
  }
19052
19976
  } catch {
19053
19977
  }
@@ -19056,7 +19980,7 @@ function templateFiles(dirs) {
19056
19980
  }
19057
19981
  function rulesStatusText() {
19058
19982
  const lines = [];
19059
- const existing = rulesDirs().filter((d) => existsSync23(d));
19983
+ const existing = rulesDirs().filter((d) => existsSync24(d));
19060
19984
  lines.push("\u89C4\u5219\u76EE\u5F55: " + (existing.length > 0 ? existing.join(", ") : "\uFF08\u672A\u8BBE\u7F6E / \u4E0D\u5B58\u5728\uFF09"));
19061
19985
  if (existing.length > 0) {
19062
19986
  lines.push(` \uFF08\u53EA\u8BFB\u5176\u4E2D\u7684 ${OVERRIDE_FILENAME} \u4E0E ${EXTRA_FILENAME}\uFF1B\u5176\u4ED6\u6587\u4EF6\u540D\u4E00\u5F8B\u4E0D\u8BFB\uFF09`);
@@ -19146,6 +20070,7 @@ var init_rules_tools = __esm({
19146
20070
  init_esm_shims();
19147
20071
  init_server();
19148
20072
  init_package_json();
20073
+ init_os_type();
19149
20074
  import { fileURLToPath as fileURLToPath14 } from "url";
19150
20075
  import { realpathSync as realpathSync3 } from "fs";
19151
20076
  function printHelp() {
@@ -19183,7 +20108,7 @@ function buildAnalysisInputFromFile(data) {
19183
20108
  actionDetail: data.a_next?.action_detail || ""
19184
20109
  },
19185
20110
  reason: data.reason || "",
19186
- osType: data.os_type || (process.platform === "win32" ? "windows" : "linux"),
20111
+ osType: data.os_type || currentOsType(),
19187
20112
  cwd: data.cwd || process.cwd(),
19188
20113
  agentId: data.agent_id || "",
19189
20114
  scenarioId: data.scenario_id || ""
@@ -19197,7 +20122,7 @@ async function analyzeRawCommand(command, useJson = false) {
19197
20122
  actionHistory: [],
19198
20123
  aNext: { actionType: "bash", actionDetail: command },
19199
20124
  reason: "",
19200
- osType: process.platform === "win32" ? "windows" : "linux",
20125
+ osType: currentOsType(),
19201
20126
  cwd: process.cwd(),
19202
20127
  agentId: ""
19203
20128
  });
@@ -19254,7 +20179,7 @@ async function main() {
19254
20179
  const fs9 = await import("fs");
19255
20180
  const path10 = await import("path");
19256
20181
  const useJson = args.includes("--json");
19257
- const osType = process.platform === "win32" ? "windows" : "linux";
20182
+ const osType = currentOsType();
19258
20183
  const isFile = fs9.existsSync(target) && fs9.statSync(target).isFile();
19259
20184
  if (!isFile) {
19260
20185
  if (fs9.existsSync(target)) {