@kenhkl/agent-moss 0.17.41 → 0.17.42

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.
@@ -1430,11 +1430,64 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
1430
1430
  }
1431
1431
  return false;
1432
1432
  }
1433
+ function intentKeywordNegated(text, index) {
1434
+ if (NEGATION_WORDS.length === 0 || index <= 0) return false;
1435
+ const prefix = text.slice(Math.max(0, index - NEGATION_WINDOW), index);
1436
+ return NEGATION_WORDS.some((neg) => prefix.includes(neg));
1437
+ }
1438
+ function isBuildArtifactCleanup(actionDetail) {
1439
+ const text = (actionDetail || "").trim();
1440
+ if (!text) return false;
1441
+ let foundRm = false;
1442
+ const targets = [];
1443
+ for (const raw of splitCommandSegments(text)) {
1444
+ const s = raw.trim();
1445
+ if (!s) continue;
1446
+ let parts = s.split(/\s+/);
1447
+ if (parts[0]?.toLowerCase() === "sudo" || parts[0]?.toLowerCase() === "command") {
1448
+ parts = parts.slice(1);
1449
+ }
1450
+ if (!parts.length || parts[0].toLowerCase() !== "rm") continue;
1451
+ foundRm = true;
1452
+ for (const rawTok of parts.slice(1)) {
1453
+ const tok = rawTok.replace(/^['"]+|['"]+$/g, "");
1454
+ if (!tok || tok.startsWith("-")) continue;
1455
+ targets.push(tok);
1456
+ }
1457
+ }
1458
+ if (!foundRm || targets.length === 0) return false;
1459
+ for (const target of targets) {
1460
+ let t = target.replace(/\\/g, "/");
1461
+ if (t.startsWith("/") || t.split("/").includes("..")) return false;
1462
+ while (t.startsWith("./")) t = t.slice(2);
1463
+ if (!t || [".", "*", "?"].includes(t)) return false;
1464
+ if (t.includes("*") || t.includes("?")) {
1465
+ if (!BUILD_ARTIFACT_GLOB_RE.test(t)) return false;
1466
+ continue;
1467
+ }
1468
+ const first = t.split("/")[0].toLowerCase();
1469
+ if (!BUILD_ARTIFACT_NAMES.has(first)) return false;
1470
+ }
1471
+ return true;
1472
+ }
1433
1473
  function intentCategories(text) {
1434
1474
  const t = (text || "").toLowerCase();
1435
1475
  const out = /* @__PURE__ */ new Set();
1436
1476
  for (const [cat, kws] of Object.entries(INTENT_CATEGORIES)) {
1437
- if (kws.some((kw) => t.includes(String(kw).toLowerCase()))) out.add(cat);
1477
+ for (const kw of kws) {
1478
+ const needle = String(kw).toLowerCase();
1479
+ let start = 0;
1480
+ while (true) {
1481
+ const idx = t.indexOf(needle, start);
1482
+ if (idx < 0) break;
1483
+ if (!intentKeywordNegated(t, idx)) {
1484
+ out.add(cat);
1485
+ break;
1486
+ }
1487
+ start = idx + needle.length;
1488
+ }
1489
+ if (out.has(cat)) break;
1490
+ }
1438
1491
  }
1439
1492
  return out;
1440
1493
  }
@@ -1537,6 +1590,52 @@ function checkIntentConsistency(input, agentExt) {
1537
1590
  }
1538
1591
  const actionCat = actionCategory(actionType, aNext.actionDetail, input.osType, extraWriteTools);
1539
1592
  const reasonKey = intentMatrixViolation(intents, actionCat);
1593
+ const isReferencePrompt = REFERENCE_PRIOR_RE.test((promptSession || "").trim().toLowerCase());
1594
+ if (reasonKey === "read->overwrite" && !EXPLICIT_READONLY_RE.test(intentText) && !isReferencePrompt) {
1595
+ console.debug(
1596
+ `[intent] \u8BFB\u610F\u56FE + \u8986\u76D6\u52A8\u4F5C\uFF0C\u7F3A\u5C11\u660E\u786E\u53EA\u8BFB\u7EA6\u675F\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
1597
+ );
1598
+ return {
1599
+ allowed: true,
1600
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
1601
+ riskLevel: "low",
1602
+ riskType: "",
1603
+ confidence: 50,
1604
+ source: "logic_rule",
1605
+ violatedLayers: [],
1606
+ l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u51FA\u73B0\u8BFB\u610F\u56FE\u8BCD\uFF0C\u4F46\u5F53\u524D\u52A8\u4F5C\u662F\u8986\u76D6\u5199\uFF0Cprompt \u6CA1\u6709\u660E\u786E\u201C\u53EA\u8BFB/\u4E0D\u8981\u4FEE\u6539\u201D\u7EA6\u675F\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
1607
+ };
1608
+ }
1609
+ if ((reasonKey === "read->delete" || reasonKey === "write->delete") && UPDATE_INTENT_RE.test(intentText) && !EXPLICIT_NO_DELETE_RE.test(intentText)) {
1610
+ console.debug(
1611
+ `[intent] \u66F4\u65B0\u7C7B\u610F\u56FE + \u5220\u9664\u52A8\u4F5C\uFF0C\u53EF\u80FD\u5305\u542B\u66FF\u6362\u6D41\u7A0B\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
1612
+ );
1613
+ return {
1614
+ allowed: true,
1615
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
1616
+ riskLevel: "low",
1617
+ riskType: "",
1618
+ confidence: 50,
1619
+ source: "logic_rule",
1620
+ violatedLayers: [],
1621
+ l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u51FA\u73B0\u66F4\u65B0/\u4FEE\u6539\u7C7B\u610F\u56FE\uFF0C\u4F46\u5F53\u524D\u52A8\u4F5C\u662F\u5220\u9664\uFF0C\u53EF\u80FD\u662F\u5148\u5220\u65E7\u518D\u5199\u65B0\u7684\u66FF\u6362\u6D41\u7A0B\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
1622
+ };
1623
+ }
1624
+ if ((reasonKey === "read->delete" || reasonKey === "write->delete") && !isReferencePrompt && INTENT_AMBIGUITY_RE.test(intentText)) {
1625
+ console.debug(
1626
+ `[intent] \u610F\u56FE\u8BCD\u5B58\u5728\u6B67\u4E49\u4E0A\u4E0B\u6587\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
1627
+ );
1628
+ return {
1629
+ allowed: true,
1630
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
1631
+ riskLevel: "low",
1632
+ riskType: "",
1633
+ confidence: 50,
1634
+ source: "logic_rule",
1635
+ violatedLayers: [],
1636
+ l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u610F\u56FE\u8BCD\u51FA\u73B0\u5728\u53EF\u80FD\u6539\u53D8\u542B\u4E49\u7684\u4E0A\u4E0B\u6587\uFF08\u5904\u7406/\u6761\u4EF6/\u793A\u4F8B/\u6309\u94AE/\u6307\u4EE3\u7B49\uFF09\u4E2D\uFF0C\u4E0D\u80FD\u4EC5\u51ED\u5173\u952E\u8BCD\u5224\u504F\u79BB\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
1637
+ };
1638
+ }
1540
1639
  if (reasonKey !== null) {
1541
1640
  return {
1542
1641
  allowed: false,
@@ -2053,7 +2152,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2053
2152
  violatedLayers: ["L2.1"]
2054
2153
  };
2055
2154
  }
2056
- var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SCRIPT_FILE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
2155
+ 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;
2057
2156
  var init_logic_rules = __esm({
2058
2157
  "src/engine/logic-rules.ts"() {
2059
2158
  "use strict";
@@ -2155,6 +2254,31 @@ var init_logic_rules = __esm({
2155
2254
  (INTENT_MATRIX.delete_action_words || []).map((w) => String(w).toLowerCase())
2156
2255
  );
2157
2256
  ALL_INTENT_KEYWORDS = Object.values(INTENT_CATEGORIES).flat();
2257
+ NEGATION_WORDS = (INTENT_MATRIX.negation_words || []).map((w) => String(w).toLowerCase());
2258
+ NEGATION_WINDOW = 8;
2259
+ EXPLICIT_READONLY_RE = /(?:只读|仅读|只看|仅看|只查看|仅查看|只分析|仅分析|只做分析|只查询|仅查询|不要(?:修改|写入|写|改动|动)|禁止(?:修改|写入|写|改动)|不得(?:修改|写入|写|改动)|别(?:修改|写入|写|动)|read[- ]only|do not (?:modify|write|change)|don't (?:modify|write|change))/i;
2260
+ UPDATE_INTENT_RE = /(?:更新|修改|编辑|替换|覆盖|改成|改到|rename|replace|update|modify|edit)/i;
2261
+ EXPLICIT_NO_DELETE_RE = /(?:不要|禁止|不得|别|切勿)\s*(?:删除|删掉|删|移除|remove|delete|rm)/i;
2262
+ INTENT_AMBIGUITY_RE = /(?:处理|整理|优化|调整|清掉|如果|假如|若|或者|还是|看情况|根据|按.{0,6}要求|继续|之前|上次|刚才|顺便|示例|例如|比如|按钮|接口|函数|字段|变量|代码里|可能|建议|评估|考虑)/i;
2263
+ BUILD_ARTIFACT_NAMES = /* @__PURE__ */ new Set([
2264
+ "build",
2265
+ "dist",
2266
+ "target",
2267
+ "out",
2268
+ "tmp",
2269
+ "temp",
2270
+ "cache",
2271
+ ".cache",
2272
+ "__pycache__",
2273
+ ".pytest_cache",
2274
+ ".mypy_cache",
2275
+ ".tox",
2276
+ "node_modules",
2277
+ "coverage",
2278
+ ".coverage",
2279
+ "htmlcov"
2280
+ ]);
2281
+ BUILD_ARTIFACT_GLOB_RE = /^\*\.(?:pyc|pyo|class|o|obj|d|egg-info)$/i;
2158
2282
  REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
2159
2283
  REFERENCE_LOOKBACK = 3;
2160
2284
  EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
@@ -3838,6 +3962,7 @@ __export(config_exports, {
3838
3962
  getAgentMossSetting: () => getAgentMossSetting,
3839
3963
  getCacheOptions: () => getCacheOptions,
3840
3964
  getCustomRules: () => getCustomRules,
3965
+ getDeployRole: () => getDeployRole,
3841
3966
  getLLMConfig: () => getLLMConfig,
3842
3967
  getLLMFailMode: () => getLLMFailMode,
3843
3968
  getProviderHeaders: () => getProviderHeaders,
@@ -4020,6 +4145,10 @@ function getLLMFailMode() {
4020
4145
  const val = (process.env.AGENT_MOSS_LLM_FAIL_MODE || "fail_open").toLowerCase();
4021
4146
  return val === "fail_closed" ? "fail_closed" : "fail_open";
4022
4147
  }
4148
+ function getDeployRole() {
4149
+ const val = String(process.env.AGENT_MOSS_DEPLOY_ROLE || "standalone").trim().toLowerCase();
4150
+ return val === "host" || val === "sandbox" ? val : "standalone";
4151
+ }
4023
4152
  function detectProvider(baseUrl, providerHint = "") {
4024
4153
  if (providerHint) {
4025
4154
  const hint = providerHint.toLowerCase();
@@ -4407,6 +4536,21 @@ function detectLanguage(path8, content) {
4407
4536
  }
4408
4537
  return "other";
4409
4538
  }
4539
+ function isInstructionTarget(path8) {
4540
+ const p = (path8 || "").replace(/\\/g, "/").toLowerCase();
4541
+ if (!p) return false;
4542
+ const base = p.split("/").pop() || "";
4543
+ if (["agents.md", "claude.md", "system.md", "prompt.md", "instructions.md", ".cursorrules"].includes(base)) {
4544
+ return true;
4545
+ }
4546
+ if (/(?:^|[-_.])(?:prompt|instruction|system)(?:[-_.]|$)/.test(base)) return true;
4547
+ return INSTRUCTION_TARGET_RE.test(p);
4548
+ }
4549
+ function isDataDocument(actionType, actionDetailRaw) {
4550
+ const payload = extractWritePayload(actionType, actionDetailRaw);
4551
+ if (payload === null) return false;
4552
+ return detectLanguage(payload.path, payload.content) === "data" && !isInstructionTarget(payload.path);
4553
+ }
4410
4554
  function stripShellComments(text) {
4411
4555
  const out = [];
4412
4556
  let heredocEnd = null;
@@ -4569,7 +4713,7 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
4569
4713
  }
4570
4714
  return snippets;
4571
4715
  }
4572
- var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE, HEREDOC_START_RE;
4716
+ var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE, INSTRUCTION_TARGET_RE, HEREDOC_START_RE;
4573
4717
  var init_written_content_analyzer = __esm({
4574
4718
  "src/engine/written-content-analyzer.ts"() {
4575
4719
  "use strict";
@@ -4592,7 +4736,12 @@ var init_written_content_analyzer = __esm({
4592
4736
  "file_edit",
4593
4737
  "editfile",
4594
4738
  "searchreplace",
4595
- "search_replace"
4739
+ "search_replace",
4740
+ // 通用 workspace 工具名(ClawPartner/QwenPaw 等宿主常用)
4741
+ "workspace_write_file",
4742
+ "workspace_edit_file",
4743
+ "workspace_writefile",
4744
+ "workspace_editfile"
4596
4745
  ]);
4597
4746
  WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
4598
4747
  APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
@@ -4601,6 +4750,7 @@ var init_written_content_analyzer = __esm({
4601
4750
  INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
4602
4751
  QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
4603
4752
  PY_DANGEROUS_CALL_RE = /(?:os\.(?:system|popen|remove|unlink|rmdir|chmod|chown|kill|spawn\w*)|subprocess\.\w+|pty\.\w+|ctypes\.\w+|eval|exec|compile|__import__|shutil\.(?:rmtree|move|copy\w*))\s*\(/g;
4753
+ INSTRUCTION_TARGET_RE = /(?:^|[/\\])(?:prompts?|instructions?|skills?|memories|memory|config|policies|policy|\.claude|\.cursor)(?:[/\\]|$)|(?:^|[/\\])(?:AGENTS?|CLAUDE|SYSTEM|PROMPT|INSTRUCTIONS?)(?:\.[^/\\]+)?$|(?:^|[/\\])\.cursorrules$/i;
4604
4754
  HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
4605
4755
  }
4606
4756
  });
@@ -4844,6 +4994,23 @@ function runHeuristicCheck(input) {
4844
4994
  deobfuscated
4845
4995
  );
4846
4996
  }
4997
+ const extraScanDetail = stripSearchPatternLiterals(scanDetail);
4998
+ const extraScanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => {
4999
+ const stripped = stripSearchPatternLiterals(sn);
5000
+ return [`${input.aNext.actionType}: ${stripped}`, stripped];
5001
+ }) : String(input.osType || "").toLowerCase() === "windows" ? [
5002
+ `${input.aNext.actionType}: ${extraScanDetail}`,
5003
+ extraScanDetail,
5004
+ `${input.aNext.actionType}: ${extraScanDetail.replace(/\//g, "\\")}`,
5005
+ extraScanDetail.replace(/\//g, "\\")
5006
+ ] : [`${input.aNext.actionType}: ${extraScanDetail}`, extraScanDetail];
5007
+ const extraDeobfuscated = normalizeShellObfuscation(extraScanDetail);
5008
+ if (extraDeobfuscated !== extraScanDetail) {
5009
+ extraScanCommands.push(
5010
+ `${input.aNext.actionType}: ${extraDeobfuscated}`,
5011
+ extraDeobfuscated
5012
+ );
5013
+ }
4847
5014
  let topRiskType = "";
4848
5015
  const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
4849
5016
  const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
@@ -4868,7 +5035,7 @@ function runHeuristicCheck(input) {
4868
5035
  for (const rule of agentExt.extra_command_patterns) {
4869
5036
  try {
4870
5037
  const re = new RegExp(rule.pattern, "i");
4871
- if (scanCommands.some((c) => re.test(c))) {
5038
+ if (extraScanCommands.some((c) => re.test(c))) {
4872
5039
  matched.push(`agent \u4E13\u5C5E\u89C4\u5219: ${rule.reason}`);
4873
5040
  if (severityRank(rule.risk_level) > severityRank(highestSeverity)) {
4874
5041
  highestSeverity = rule.risk_level;
@@ -4879,7 +5046,7 @@ function runHeuristicCheck(input) {
4879
5046
  }
4880
5047
  }
4881
5048
  }
4882
- const injectionText = isSearchActionType(input.aNext.actionType) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
5049
+ 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();
4883
5050
  let pythonWalkOnerrorOnly = false;
4884
5051
  if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
4885
5052
  pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
@@ -5130,16 +5297,83 @@ function splitCommandSegments2(actionDetail) {
5130
5297
  if (start < actionDetail.length) segments.push(actionDetail.slice(start));
5131
5298
  return segments;
5132
5299
  }
5300
+ function shellTokens(seg) {
5301
+ const tokens = [];
5302
+ let cur = "";
5303
+ let quote = "";
5304
+ for (let i = 0; i < seg.length; i++) {
5305
+ const ch = seg[i];
5306
+ if (quote) {
5307
+ if (ch === quote) quote = "";
5308
+ else cur += ch;
5309
+ continue;
5310
+ }
5311
+ if (ch === '"' || ch === "'") {
5312
+ quote = ch;
5313
+ continue;
5314
+ }
5315
+ if (/\s/.test(ch)) {
5316
+ if (cur) {
5317
+ tokens.push(cur);
5318
+ cur = "";
5319
+ }
5320
+ continue;
5321
+ }
5322
+ cur += ch;
5323
+ }
5324
+ if (quote) return null;
5325
+ if (cur) tokens.push(cur);
5326
+ return tokens;
5327
+ }
5328
+ function stripSearchPatternArgument(seg) {
5329
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) return seg;
5330
+ const tokens = shellTokens(seg);
5331
+ if (!tokens || tokens.length === 0) return seg;
5332
+ let idx = 0;
5333
+ while (idx < tokens.length && COMMAND_PREFIX_WORDS.has(tokens[idx])) idx++;
5334
+ if (idx >= tokens.length || !TEXT_SEARCH_COMMANDS.has(tokens[idx])) return seg;
5335
+ let patternIdx = null;
5336
+ let i = idx + 1;
5337
+ while (i < tokens.length) {
5338
+ const token = tokens[i];
5339
+ if (token === "--") {
5340
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
5341
+ break;
5342
+ }
5343
+ if (token === "-e" || token === "--regexp") {
5344
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
5345
+ break;
5346
+ }
5347
+ if (token.startsWith("--regexp=")) {
5348
+ patternIdx = i;
5349
+ break;
5350
+ }
5351
+ if (token === "-f" || token === "--file" || token.startsWith("--file=")) break;
5352
+ if (token.startsWith("-") && token !== "-") {
5353
+ i += SEARCH_OPTION_WITH_ARG.has(token) ? 2 : 1;
5354
+ continue;
5355
+ }
5356
+ patternIdx = i;
5357
+ break;
5358
+ }
5359
+ if (patternIdx === null || patternIdx >= tokens.length) return seg;
5360
+ tokens.splice(patternIdx, 1);
5361
+ return tokens.map((t) => /\s/.test(t) ? `'${t.replaceAll("'", "'\\''")}'` : t).join(" ");
5362
+ }
5133
5363
  function stripSearchPatternLiterals(actionDetail) {
5134
5364
  const parts = [];
5135
5365
  for (const seg of splitCommandSegments2(actionDetail)) {
5366
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) {
5367
+ parts.push(seg);
5368
+ continue;
5369
+ }
5136
5370
  const low = seg.trim().toLowerCase();
5137
5371
  const words = low.length ? low.split(/\s+/) : [];
5138
5372
  let idx = 0;
5139
5373
  while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
5140
5374
  const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
5141
5375
  if (isSearch && !low.includes("--pre")) {
5142
- parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
5376
+ parts.push(stripSearchPatternArgument(seg));
5143
5377
  } else {
5144
5378
  parts.push(seg);
5145
5379
  }
@@ -5464,7 +5698,7 @@ function checkDangerousPatterns(actionType, actionDetail) {
5464
5698
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
5465
5699
  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;
5466
5700
  const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
5467
- if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
5701
+ if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
5468
5702
  return {
5469
5703
  allowed: false,
5470
5704
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -5606,7 +5840,7 @@ function checkLateralMovement(actionDetail) {
5606
5840
  }
5607
5841
  return null;
5608
5842
  }
5609
- 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, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
5843
+ 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;
5610
5844
  var init_heuristic = __esm({
5611
5845
  "src/engine/heuristic.ts"() {
5612
5846
  "use strict";
@@ -5655,6 +5889,28 @@ var init_heuristic = __esm({
5655
5889
  COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
5656
5890
  TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
5657
5891
  COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
5892
+ SEARCH_OPTION_WITH_ARG = /* @__PURE__ */ new Set([
5893
+ "-m",
5894
+ "--max-count",
5895
+ "-A",
5896
+ "--after-context",
5897
+ "-B",
5898
+ "--before-context",
5899
+ "-C",
5900
+ "--context",
5901
+ "-d",
5902
+ "--directories",
5903
+ "-D",
5904
+ "--devices",
5905
+ "--include",
5906
+ "--exclude",
5907
+ "--exclude-dir",
5908
+ "--glob",
5909
+ "--iglob",
5910
+ "--type",
5911
+ "--type-add",
5912
+ "--type-not"
5913
+ ]);
5658
5914
  SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
5659
5915
  SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
5660
5916
  SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
@@ -8472,6 +8728,15 @@ var LLM_SHORT_CIRCUIT_TOTAL = new Counter(
8472
8728
  );
8473
8729
 
8474
8730
  // src/engine/llm-analyzer.ts
8731
+ var LLMPromptBudgetExceeded = class extends Error {
8732
+ code;
8733
+ constructor(code) {
8734
+ super(code);
8735
+ this.name = "LLMPromptBudgetExceeded";
8736
+ this.code = code;
8737
+ }
8738
+ };
8739
+ var HISTORY_AUTHORIZATION = "\u88AB\u7701\u7565\u6216\u88AB\u622A\u65AD\u7684\u5386\u53F2\u4E0D\u80FD\u4F5C\u4E3A\u6388\u6743\u4F9D\u636E\u3002\n\u201C\u7EE7\u7EED\u201D\u53EA\u6307\u4EE3\u53EF\u89C1\u7684\u524D\u6587\uFF1B\u5982\u679C\u53EF\u89C1\u524D\u6587\u4E0D\u8DB3\u4EE5\u786E\u8BA4\u6307\u4EE3\u76EE\u6807\u6216\u6388\u6743\u8303\u56F4\uFF0C\u5E94\u5728 reason \u4E2D\u8BF4\u660E\u4F9D\u636E\u4E0D\u8DB3\uFF0C\u5E76\u6309\u6700\u5C0F\u6743\u9650\u539F\u5219\u5224\u65AD\u9700\u8981\u8BE5\u6388\u6743\u7684\u52A8\u4F5C\u3002\n\u5F53\u524D\u7528\u6237\u8BF7\u6C42\u4E2D\u660E\u786E\u5199\u51FA\u7684\u6388\u6743\u4ECD\u7136\u6709\u6548\uFF0C\u6309\u5176\u53EF\u89C1\u7684\u76EE\u6807\u548C\u9650\u5236\u5224\u65AD\u3002";
8475
8740
  var LLMCircuitOpenError = class extends Error {
8476
8741
  constructor(message) {
8477
8742
  super(message);
@@ -8572,6 +8837,9 @@ async function runLLMAnalysis(input, previous) {
8572
8837
  scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
8573
8838
  }
8574
8839
  const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
8840
+ const budgetMode = getAgentMossSetting("AGENT_MOSS_LLM_BUDGET_MODE", "hard").trim().toLowerCase() === "soft" ? "soft" : "hard";
8841
+ const budgetActive = maxPromptTokens > 0;
8842
+ const tokenLimit = budgetActive && budgetMode === "hard" ? Math.floor(maxPromptTokens * 100 / 115) : maxPromptTokens;
8575
8843
  let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
8576
8844
  let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
8577
8845
  let prompt = "";
@@ -8588,13 +8856,14 @@ async function runLLMAnalysis(input, previous) {
8588
8856
  historyMaxItems,
8589
8857
  historyMaxChars
8590
8858
  );
8591
- if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
8859
+ if (!budgetActive || estimateTokens(prompt) <= tokenLimit) break;
8592
8860
  historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
8593
8861
  historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
8594
8862
  }
8595
- if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
8863
+ let budgetCode = "";
8864
+ if (budgetActive && estimateTokens(prompt) > tokenLimit) {
8596
8865
  const estimated = estimateTokens(prompt);
8597
- const ratio = estimated / maxPromptTokens;
8866
+ const ratio = tokenLimit > 0 ? estimated / tokenLimit : Number.POSITIVE_INFINITY;
8598
8867
  const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
8599
8868
  const truncated = truncateDetail(input.aNext.actionDetail, allowed);
8600
8869
  prompt = buildPrompt(
@@ -8610,8 +8879,14 @@ async function runLLMAnalysis(input, previous) {
8610
8879
  historyMaxChars
8611
8880
  );
8612
8881
  console.warn(
8613
- `[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${maxPromptTokens}\uFF09\uFF0C\u5F53\u524D\u52A8\u4F5C\u8BE6\u60C5\u622A\u65AD\u81F3 ${truncated.length} \u5B57\u7B26`
8882
+ `[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${tokenLimit}\uFF09\uFF0C\u5F53\u524D\u52A8\u4F5C\u8BE6\u60C5\u622A\u65AD\u81F3 ${truncated.length} \u5B57\u7B26`
8614
8883
  );
8884
+ if (estimateTokens(prompt) > tokenLimit) {
8885
+ if (budgetMode === "hard") {
8886
+ throw new LLMPromptBudgetExceeded("l3_budget_unreachable");
8887
+ }
8888
+ budgetCode = "l3_budget_unreachable";
8889
+ }
8615
8890
  }
8616
8891
  logPrompt(prompt, input.aNext, previous.llmLogPath);
8617
8892
  traceFull("l3.prompt", {
@@ -8624,6 +8899,7 @@ async function runLLMAnalysis(input, previous) {
8624
8899
  prompt_chars: prompt.length
8625
8900
  });
8626
8901
  const result = await analyzeWithLLM(prompt, config);
8902
+ if (budgetCode) result.degraded = [...result.degraded || [], budgetCode];
8627
8903
  traceSummary("l3.verdict", {
8628
8904
  allowed: result.allowed,
8629
8905
  risk_level: result.riskLevel,
@@ -8697,11 +8973,14 @@ function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis,
8697
8973
  const skillsText = formatSkillsForPrompt(matchedSkills);
8698
8974
  const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
8699
8975
  const promptHistoryText = formatPromptHistory(input.promptHistory);
8976
+ const historyAuthorization = /(因历史窗口上限省略|本段因长度上限已截断)/.test(promptHistoryText) ? `
8977
+
8978
+ ${HISTORY_AUTHORIZATION}` : "";
8700
8979
  const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
8701
8980
  const hintsText = formatHints(previous);
8702
8981
  const securityJudgeTemplate = templates["security_judge"];
8703
8982
  if (securityJudgeTemplate) {
8704
- return securityJudgeTemplate.replaceAll("{prompt_session}", input.promptSession || "\uFF08\u672A\u63D0\u4F9B\uFF09").replaceAll("{prompt_history_text}", promptHistoryText).replaceAll("{action_history}", historyStr).replaceAll("{action_type}", input.aNext.actionType).replaceAll("{action_detail}", input.aNext.actionDetail).replaceAll("{reason}", input.reason || "\u672A\u8BF4\u660E").replaceAll("{skills_text}", skillsText).replaceAll("{hints_text}", hintsText).replaceAll("{script_analysis_text}", scriptAnalysisText).replaceAll("{skip_l3_hints}", skipL3Hints).replaceAll("{path_context}", pathContext || "\uFF08\u672C\u547D\u4EE4\u65E0\u4E3B\u76EE\u5F55\u76F8\u5173\u8DEF\u5F84\u6BB5\uFF0C\u4E0D\u9002\u7528\uFF09").replaceAll("{{", "{").replaceAll("}}", "}");
8983
+ return securityJudgeTemplate.replaceAll("{prompt_session}", input.promptSession || "\uFF08\u672A\u63D0\u4F9B\uFF09").replaceAll("{prompt_history_text}", promptHistoryText).replaceAll("{history_authorization}", historyAuthorization).replaceAll("{action_history}", historyStr).replaceAll("{action_type}", input.aNext.actionType).replaceAll("{action_detail}", input.aNext.actionDetail).replaceAll("{reason}", input.reason || "\u672A\u8BF4\u660E").replaceAll("{skills_text}", skillsText).replaceAll("{hints_text}", hintsText).replaceAll("{script_analysis_text}", scriptAnalysisText).replaceAll("{skip_l3_hints}", skipL3Hints).replaceAll("{path_context}", pathContext || "\uFF08\u672C\u547D\u4EE4\u65E0\u4E3B\u76EE\u5F55\u76F8\u5173\u8DEF\u5F84\u6BB5\uFF0C\u4E0D\u9002\u7528\uFF09").replaceAll("{{", "{").replaceAll("}}", "}");
8705
8984
  }
8706
8985
  console.warn("[AgentMoss] security_judge template missing, using sparse fallback prompt");
8707
8986
  return `## \u5F53\u524D\u64CD\u4F5C\u4E0A\u4E0B\u6587
@@ -8737,21 +9016,28 @@ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNu
8737
9016
  }
8738
9017
  const limit = Math.max(0, Math.floor(maxTurns));
8739
9018
  const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
9019
+ let omitted = 0;
8740
9020
  const lines = [];
8741
- for (let i = firstTurnIndex; i < promptHistory.length; i++) {
9021
+ for (let i = 0; i < promptHistory.length; i++) {
8742
9022
  const turn = promptHistory[i];
8743
9023
  const text = (typeof turn === "string" ? turn : turn?.text || "").trim();
8744
- if (!text) continue;
8745
- let line = ` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${text.slice(0, maxTextChars)}`;
8746
9024
  const actions = typeof turn === "string" ? void 0 : turn?.actions;
8747
- if (actions && actions.length > 0) {
8748
- const types = actions.map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
8749
- if (types.length > 0) {
8750
- line += ` \u2192 \u52A8\u4F5C: ${types.join(", ")}`;
8751
- }
9025
+ const types = (actions || []).map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
9026
+ if (!text && types.length === 0) continue;
9027
+ if (i < firstTurnIndex) {
9028
+ omitted += 1;
9029
+ continue;
9030
+ }
9031
+ if (!text) {
9032
+ lines.push(` \u7B2C${i + 1}\u8F6E\u52A8\u4F5C: ${types.join(", ")}`);
9033
+ continue;
8752
9034
  }
8753
- lines.push(line);
9035
+ let shown = text.slice(0, maxTextChars);
9036
+ if (shown.length < text.length) shown += "\uFF08\u672C\u6BB5\u56E0\u957F\u5EA6\u4E0A\u9650\u5DF2\u622A\u65AD\uFF09";
9037
+ const suffix = types.length > 0 ? ` \u2192 \u52A8\u4F5C: ${types.join(", ")}` : "";
9038
+ lines.push(` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${shown}${suffix}`);
8754
9039
  }
9040
+ if (omitted) lines.unshift(`\uFF08\u56E0\u5386\u53F2\u7A97\u53E3\u4E0A\u9650\u7701\u7565 ${omitted} \u8F6E\u66F4\u65E9\u5386\u53F2\u610F\u56FE\uFF09`);
8755
9041
  return lines.length > 0 ? lines.join("\n") : "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
8756
9042
  }
8757
9043
  function formatHints(previous) {
@@ -8764,11 +9050,15 @@ function formatHints(previous) {
8764
9050
  );
8765
9051
  }
8766
9052
  if (previous.logic) {
8767
- hints.push(
8768
- `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
9053
+ if (previous.logic.l3Hint) {
9054
+ hints.push(`\u2139\uFE0F ${previous.logic.l3Hint}`);
9055
+ } else {
9056
+ hints.push(
9057
+ `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
8769
9058
  \u7C7B\u578B: ${previous.logic.riskType}
8770
9059
  \u539F\u56E0: ${previous.logic.reason}`
8771
- );
9060
+ );
9061
+ }
8772
9062
  }
8773
9063
  return hints.length > 0 ? hints.join("\n\n") : "\u7279\u5F81\u5339\u914D\u68C0\u6D4B\u548C\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u5747\u672A\u53D1\u73B0\u98CE\u9669\u3002";
8774
9064
  }
@@ -10113,11 +10403,35 @@ function checkMCRules(graph) {
10113
10403
  for (const rule of rules) {
10114
10404
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
10115
10405
  if (ruleViolates(rule, trace2, witnessMode)) {
10406
+ const pathNodes = nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3);
10407
+ const path8 = pathNodes.map((n) => ({
10408
+ sessionId: n.sessionId,
10409
+ seq: n.seq,
10410
+ detail: n.actionDetail.slice(0, 60)
10411
+ }));
10116
10412
  violations.push({
10117
10413
  propertyId: String(rule.id || "mc-ltl"),
10118
10414
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
10119
10415
  riskLevel: String(rule.risk_level || "high"),
10120
- path: nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3).map((n) => ({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }))
10416
+ path: path8,
10417
+ graph: {
10418
+ property_id: String(rule.id || "mc-ltl"),
10419
+ property_short: "P6",
10420
+ property_name: "LTL \u6A21\u578B\u68C0\u6D4B",
10421
+ nodes: pathNodes.map((n) => ({
10422
+ session_id: n.sessionId,
10423
+ seq: n.seq,
10424
+ stage: n.stage,
10425
+ action_detail: n.actionDetail,
10426
+ resources: [...n.resources].sort(),
10427
+ instance_id: n.instanceId || ""
10428
+ })),
10429
+ edges: pathNodes.slice(1).map((_, i) => ({
10430
+ from: i,
10431
+ to: i + 1,
10432
+ type: "next"
10433
+ }))
10434
+ }
10121
10435
  });
10122
10436
  if (witnessMode) return violations;
10123
10437
  }
@@ -10812,11 +11126,17 @@ function checkLowIntegrityCommandExec(graph) {
10812
11126
  for (const i of candidates) {
10813
11127
  const n = nodes[i];
10814
11128
  if (lowAt.has(i) && isComputeNode(n)) {
11129
+ const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10815
11130
  violations.push({
10816
11131
  propertyId: "low-integrity-command-exec",
10817
11132
  reason: `\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u63A7\u5236\u547D\u4EE4\u6267\u884C\uFF1A${lowAt.get(i)} \u2192 ${n.sessionId}#${n.seq} \u6267\u884C\u4E0D\u53EF\u4FE1\u5185\u5BB9`,
10818
11133
  riskLevel: "critical",
10819
- path: [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }]
11134
+ path: path8,
11135
+ graph: graphFromPath(nodes, path8, "next", {
11136
+ property_id: "low-integrity-command-exec",
11137
+ property_short: "P7",
11138
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u547D\u4EE4\u6267\u884C"
11139
+ }, ["sink"])
10820
11140
  });
10821
11141
  if (witness !== void 0) return violations;
10822
11142
  }
@@ -10859,11 +11179,21 @@ function checkCrossSessionReachability(graph) {
10859
11179
  if (reached.has(i)) {
10860
11180
  const srcIdx = Math.min(...sources);
10861
11181
  const srcDesc = nodes[srcIdx].actionDetail.slice(0, 40);
11182
+ const path8 = nodes.slice(-3).map((m) => ({
11183
+ sessionId: m.sessionId,
11184
+ seq: m.seq,
11185
+ detail: m.actionDetail.slice(0, 60)
11186
+ }));
10862
11187
  violations.push({
10863
11188
  propertyId: "low-integrity-reachability",
10864
11189
  reason: `\u4F4E\u5B8C\u6574\u6027\u6E90\u7ECF\u8DE8 session \u6570\u636E\u94FE\u591A\u8DF3\u5230\u8FBE\u5F53\u524D\u6267\u884C\uFF08\u6E90: ${srcDesc} \u2192 ${n.sessionId}#${n.seq}\uFF09`,
10865
11190
  riskLevel: "high",
10866
- path: nodes.slice(-3).map((m) => ({ sessionId: m.sessionId, seq: m.seq, detail: m.actionDetail.slice(0, 60) }))
11191
+ path: path8,
11192
+ graph: graphFromPath(nodes, path8, "data", {
11193
+ property_id: "low-integrity-reachability",
11194
+ property_short: "P3",
11195
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u6D41\u53EF\u8FBE"
11196
+ })
10867
11197
  });
10868
11198
  if (witness !== void 0) return violations;
10869
11199
  }
@@ -11160,9 +11490,19 @@ async function runAnalysis(input) {
11160
11490
  isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
11161
11491
  isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
11162
11492
  );
11493
+ const degradedNotes = [];
11163
11494
  let scriptChain = null;
11164
- if (input.aNext.actionType.toLowerCase() === "bash") {
11495
+ if (input.aNext.actionType.toLowerCase() === "bash" && getDeployRole() === "host") {
11496
+ degradedNotes.push("script_content_deferred_to_sandbox: AGENT_MOSS_DEPLOY_ROLE=host");
11497
+ } else if (input.aNext.actionType.toLowerCase() === "bash") {
11165
11498
  scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
11499
+ if (scriptChain.nodes.length > 0) {
11500
+ for (const node of scriptChain.nodes) {
11501
+ if (node.error && !node.unanalyzable) {
11502
+ degradedNotes.push(`script_content_unavailable: ${node.scriptPath} (${node.error})`);
11503
+ }
11504
+ }
11505
+ }
11166
11506
  if (heuristicEnabled && scriptChain.nodes.length > 0) {
11167
11507
  for (const node of scriptChain.nodes) {
11168
11508
  if (node.unanalyzable) {
@@ -11433,7 +11773,8 @@ async function runAnalysis(input) {
11433
11773
  riskType: "",
11434
11774
  confidence: 85,
11435
11775
  source: "heuristic_and_logic_only",
11436
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
11776
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
11777
+ degraded: degradedNotes
11437
11778
  };
11438
11779
  }
11439
11780
  let skipL3Hints = "\u65E0\uFF08\u5F53\u524D\u65E0\u7981\u7528\u89C4\u5219\u547D\u4E2D\uFF09";
@@ -11470,8 +11811,22 @@ async function runAnalysis(input) {
11470
11811
  pathContext
11471
11812
  });
11472
11813
  } catch (e) {
11473
- const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
11474
11814
  const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
11815
+ if (e instanceof LLMPromptBudgetExceeded) {
11816
+ const failMode = getLLMFailMode2();
11817
+ const allowed = failMode === "fail_open";
11818
+ return {
11819
+ allowed,
11820
+ reason: `L3 prompt \u8D85\u51FA\u786C\u9884\u7B97\uFF0C\u5DF2\u8DF3\u8FC7\u8BED\u4E49\u5206\u6790\uFF0C\u6309 ${failMode} ${allowed ? "\u653E\u884C" : "\u62D2\u7EDD"}`,
11821
+ riskLevel: allowed ? "low" : "medium",
11822
+ riskType: "",
11823
+ confidence: allowed ? 50 : 60,
11824
+ source: "llm_budget_skipped",
11825
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
11826
+ degraded: [...degradedNotes, e.code]
11827
+ };
11828
+ }
11829
+ const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
11475
11830
  if (getLLMFailMode2() === "fail_open") {
11476
11831
  console.warn(`[AgentMoss] LLM \u5206\u6790\u5931\u8D25\uFF0Cfail_open \u6A21\u5F0F\uFF1A\u5141\u8BB8\u6267\u884C\uFF08\u524D\u4E24\u5C42\u672A\u62E6\u622A\uFF09: ${e.message}`);
11477
11832
  return {
@@ -11481,7 +11836,8 @@ async function runAnalysis(input) {
11481
11836
  riskType: "",
11482
11837
  confidence: 50,
11483
11838
  source: failSource,
11484
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
11839
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
11840
+ degraded: degradedNotes
11485
11841
  };
11486
11842
  }
11487
11843
  return {
@@ -11491,7 +11847,10 @@ async function runAnalysis(input) {
11491
11847
  riskType: "",
11492
11848
  confidence: 60,
11493
11849
  source: failSource,
11494
- violatedLayers: ["L3.1"]
11850
+ violatedLayers: ["L3.1"],
11851
+ degraded: degradedNotes,
11852
+ ask_recommended: true,
11853
+ ask_reason: "L3 \u8BED\u4E49\u5206\u6790\u4E0D\u53EF\u7528\uFF0C\u6309 fail_closed \u62D2\u7EDD\uFF1B\u8FD9\u662F\u201C\u6CA1\u67E5\u5B8C\u201D\u800C\u975E\u201C\u786E\u8BA4\u6709\u98CE\u9669\u201D\uFF0C\u5EFA\u8BAE\u5411\u7528\u6237\u786E\u8BA4\u662F\u5426\u7EE7\u7EED\u3002"
11495
11854
  };
11496
11855
  }
11497
11856
  if (!llmResult.allowed && llmResult.confidence && llmResult.confidence >= 90 && _brainExtractor) {
@@ -11511,6 +11870,9 @@ async function runAnalysis(input) {
11511
11870
  if (observedFormalLayers.length > 0 && llmResult.allowed) {
11512
11871
  llmResult.violatedLayers = Array.from(/* @__PURE__ */ new Set([...observedFormalLayers, ...llmResult.violatedLayers || []]));
11513
11872
  }
11873
+ if (degradedNotes.length > 0) {
11874
+ llmResult.degraded = Array.from(/* @__PURE__ */ new Set([...llmResult.degraded || [], ...degradedNotes]));
11875
+ }
11514
11876
  return llmResult;
11515
11877
  }
11516
11878
  export {