@kenhkl/agent-moss 0.17.40 → 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.
@@ -816,6 +816,157 @@ function hasInlineDangerEvidence(command) {
816
816
  for (const re of DANGER_EVIDENCE_RES) if (re.test(code)) return true;
817
817
  return false;
818
818
  }
819
+ function literalShellWord(raw) {
820
+ if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) {
821
+ const inner = raw.slice(1, -1);
822
+ return inner.includes("'") ? null : inner;
823
+ }
824
+ if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) {
825
+ const inner = raw.slice(1, -1);
826
+ return /["\\$`]/.test(inner) ? null : inner;
827
+ }
828
+ if (!raw || /\s/.test(raw) || !/^[A-Za-z0-9_@%+=:,./-]+$/.test(raw)) return null;
829
+ return raw;
830
+ }
831
+ function pythonStringLiteral(raw) {
832
+ const text = raw.trim();
833
+ if (text.length < 2) return null;
834
+ const quote = text[0];
835
+ if (quote !== "'" && quote !== '"' || text[text.length - 1] !== quote) return null;
836
+ const inner = text.slice(1, -1);
837
+ if (inner.includes(quote) || inner.includes("\\") || inner.includes("\n")) return null;
838
+ return inner;
839
+ }
840
+ function splitPythonArgs(raw) {
841
+ const parts = [];
842
+ let current = "";
843
+ let depth = 0;
844
+ let quote = null;
845
+ for (const ch of raw) {
846
+ if (quote) {
847
+ current += ch;
848
+ if (ch === quote) quote = null;
849
+ continue;
850
+ }
851
+ if (ch === "'" || ch === '"') {
852
+ quote = ch;
853
+ current += ch;
854
+ continue;
855
+ }
856
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
857
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
858
+ if (ch === "," && depth === 0) {
859
+ parts.push(current.trim());
860
+ current = "";
861
+ continue;
862
+ }
863
+ current += ch;
864
+ }
865
+ if (quote || depth !== 0) return null;
866
+ parts.push(current.trim());
867
+ return parts;
868
+ }
869
+ function hasTopLevelChar(raw, target) {
870
+ let depth = 0;
871
+ let quote = null;
872
+ for (const ch of raw) {
873
+ if (quote) {
874
+ if (ch === quote) quote = null;
875
+ continue;
876
+ }
877
+ if (ch === "'" || ch === '"') quote = ch;
878
+ else if (ch === "(" || ch === "[" || ch === "{") depth++;
879
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
880
+ else if (ch === target && depth === 0) return true;
881
+ }
882
+ return false;
883
+ }
884
+ function splitPythonStatements(code) {
885
+ const parts = [];
886
+ let current = "";
887
+ let depth = 0;
888
+ let quote = null;
889
+ for (const ch of code) {
890
+ if (quote) {
891
+ current += ch;
892
+ if (ch === quote) quote = null;
893
+ continue;
894
+ }
895
+ if (ch === "'" || ch === '"') {
896
+ quote = ch;
897
+ current += ch;
898
+ continue;
899
+ }
900
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
901
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
902
+ if ((ch === ";" || ch === "\n") && depth === 0) {
903
+ parts.push(current);
904
+ current = "";
905
+ continue;
906
+ }
907
+ current += ch;
908
+ }
909
+ if (quote || depth !== 0) return null;
910
+ parts.push(current);
911
+ return parts.map((s) => s.trim()).filter((s) => s.length > 0);
912
+ }
913
+ function isSimpleOpenCall(expr, path8, binding) {
914
+ const m = expr.match(/^open\s*\(([\s\S]*)\)$/);
915
+ if (!m || hasTopLevelChar(m[1], "=")) return false;
916
+ const args = splitPythonArgs(m[1]);
917
+ if (!args || args.length !== 1 && args.length !== 2) return false;
918
+ if (args.length === 2 && !["r", "rt", "rb"].includes(pythonStringLiteral(args[1]) ?? "")) {
919
+ return false;
920
+ }
921
+ const target = args[0].trim();
922
+ const literal = pythonStringLiteral(target);
923
+ if (literal !== null) return literal === path8;
924
+ return !!binding && target === binding;
925
+ }
926
+ function confirmsInlineRead(command, path8) {
927
+ if (command.length > 8192 || !path8 || path8.startsWith("~")) return false;
928
+ if (path8.includes("/") && !path8.startsWith("/")) return false;
929
+ const wrapper = command.trim().match(/^python3?[ \t]+-c[ \t]+([\s\S]+)$/);
930
+ if (!wrapper) return false;
931
+ const code = literalShellWord(wrapper[1]);
932
+ if (code === null) return false;
933
+ const statements = splitPythonStatements(code);
934
+ if (!statements || statements.length !== 1 && statements.length !== 2) return false;
935
+ let expr;
936
+ let binding = null;
937
+ if (statements.length === 2) {
938
+ const first = statements[0];
939
+ if (first === "import os") {
940
+ const sys = statements[1].match(/^os\.system\s*\(([\s\S]*)\)$/);
941
+ if (!sys || hasTopLevelChar(sys[1], "=")) return false;
942
+ const args = splitPythonArgs(sys[1]);
943
+ if (!args || args.length !== 1) return false;
944
+ const child = pythonStringLiteral(args[0]);
945
+ if (child === null) return false;
946
+ const cat = child.trim().match(/^cat[ \t]+([\s\S]+)$/);
947
+ return !!cat && !path8.startsWith("-") && literalShellWord(cat[1].trim()) === path8;
948
+ }
949
+ const assign = first.match(/^([A-Za-z_]\w*)\s*=\s*([\s\S]+)$/);
950
+ if (!assign) return false;
951
+ const name = assign[1];
952
+ const value = pythonStringLiteral(assign[2]);
953
+ if (value !== path8 || ["open", "print", "__debug__"].includes(name)) return false;
954
+ binding = name;
955
+ expr = statements[1];
956
+ } else {
957
+ expr = statements[0];
958
+ }
959
+ const printCall = expr.match(/^print\s*\(([\s\S]*)\)$/);
960
+ if (printCall) {
961
+ if (hasTopLevelChar(printCall[1], "=")) return false;
962
+ const args = splitPythonArgs(printCall[1]);
963
+ if (!args || args.length !== 1) return false;
964
+ expr = args[0];
965
+ }
966
+ const readCall = expr.match(/^([\s\S]+)\.read\s*\(\s*\)$/);
967
+ if (readCall) expr = readCall[1];
968
+ return isSimpleOpenCall(expr, path8, binding);
969
+ }
819
970
  function analyzeInlineScript(command) {
820
971
  const code = extractInlineCode(command);
821
972
  if (!code) {
@@ -1279,11 +1430,64 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
1279
1430
  }
1280
1431
  return false;
1281
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
+ }
1282
1473
  function intentCategories(text) {
1283
1474
  const t = (text || "").toLowerCase();
1284
1475
  const out = /* @__PURE__ */ new Set();
1285
1476
  for (const [cat, kws] of Object.entries(INTENT_CATEGORIES)) {
1286
- 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
+ }
1287
1491
  }
1288
1492
  return out;
1289
1493
  }
@@ -1386,6 +1590,52 @@ function checkIntentConsistency(input, agentExt) {
1386
1590
  }
1387
1591
  const actionCat = actionCategory(actionType, aNext.actionDetail, input.osType, extraWriteTools);
1388
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
+ }
1389
1639
  if (reasonKey !== null) {
1390
1640
  return {
1391
1641
  allowed: false,
@@ -1902,7 +2152,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
1902
2152
  violatedLayers: ["L2.1"]
1903
2153
  };
1904
2154
  }
1905
- 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;
1906
2156
  var init_logic_rules = __esm({
1907
2157
  "src/engine/logic-rules.ts"() {
1908
2158
  "use strict";
@@ -2004,6 +2254,31 @@ var init_logic_rules = __esm({
2004
2254
  (INTENT_MATRIX.delete_action_words || []).map((w) => String(w).toLowerCase())
2005
2255
  );
2006
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;
2007
2282
  REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
2008
2283
  REFERENCE_LOOKBACK = 3;
2009
2284
  EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
@@ -3687,6 +3962,7 @@ __export(config_exports, {
3687
3962
  getAgentMossSetting: () => getAgentMossSetting,
3688
3963
  getCacheOptions: () => getCacheOptions,
3689
3964
  getCustomRules: () => getCustomRules,
3965
+ getDeployRole: () => getDeployRole,
3690
3966
  getLLMConfig: () => getLLMConfig,
3691
3967
  getLLMFailMode: () => getLLMFailMode,
3692
3968
  getProviderHeaders: () => getProviderHeaders,
@@ -3869,6 +4145,10 @@ function getLLMFailMode() {
3869
4145
  const val = (process.env.AGENT_MOSS_LLM_FAIL_MODE || "fail_open").toLowerCase();
3870
4146
  return val === "fail_closed" ? "fail_closed" : "fail_open";
3871
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
+ }
3872
4152
  function detectProvider(baseUrl, providerHint = "") {
3873
4153
  if (providerHint) {
3874
4154
  const hint = providerHint.toLowerCase();
@@ -4256,6 +4536,21 @@ function detectLanguage(path8, content) {
4256
4536
  }
4257
4537
  return "other";
4258
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
+ }
4259
4554
  function stripShellComments(text) {
4260
4555
  const out = [];
4261
4556
  let heredocEnd = null;
@@ -4418,7 +4713,7 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
4418
4713
  }
4419
4714
  return snippets;
4420
4715
  }
4421
- 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;
4422
4717
  var init_written_content_analyzer = __esm({
4423
4718
  "src/engine/written-content-analyzer.ts"() {
4424
4719
  "use strict";
@@ -4441,7 +4736,12 @@ var init_written_content_analyzer = __esm({
4441
4736
  "file_edit",
4442
4737
  "editfile",
4443
4738
  "searchreplace",
4444
- "search_replace"
4739
+ "search_replace",
4740
+ // 通用 workspace 工具名(ClawPartner/QwenPaw 等宿主常用)
4741
+ "workspace_write_file",
4742
+ "workspace_edit_file",
4743
+ "workspace_writefile",
4744
+ "workspace_editfile"
4445
4745
  ]);
4446
4746
  WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
4447
4747
  APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
@@ -4450,11 +4750,13 @@ var init_written_content_analyzer = __esm({
4450
4750
  INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
4451
4751
  QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
4452
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;
4453
4754
  HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
4454
4755
  }
4455
4756
  });
4456
4757
 
4457
4758
  // src/engine/heuristic.ts
4759
+ import { posix } from "path";
4458
4760
  function _effectiveDangerousPatterns(osType) {
4459
4761
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
4460
4762
  }
@@ -4482,6 +4784,112 @@ function normalizeShellObfuscation(text) {
4482
4784
  t = t.replace(/\$\{IFS\}|\$IFS/gi, " ");
4483
4785
  return t;
4484
4786
  }
4787
+ function shlexSplitLite(s) {
4788
+ const out = [];
4789
+ let cur = "";
4790
+ let quote = null;
4791
+ let quoted = false;
4792
+ for (let i = 0; i < s.length; i++) {
4793
+ const ch = s[i];
4794
+ if (quote) {
4795
+ if (ch === quote) quote = null;
4796
+ else if (ch === "\\" && quote === '"' && i + 1 < s.length) cur += s[++i];
4797
+ else cur += ch;
4798
+ continue;
4799
+ }
4800
+ if (ch === "'" || ch === '"') {
4801
+ quote = ch;
4802
+ quoted = true;
4803
+ continue;
4804
+ }
4805
+ if (/\s/.test(ch)) {
4806
+ if (cur || quoted) {
4807
+ out.push(cur);
4808
+ cur = "";
4809
+ quoted = false;
4810
+ }
4811
+ continue;
4812
+ }
4813
+ if (ch === "\\" && i + 1 < s.length) {
4814
+ cur += s[++i];
4815
+ continue;
4816
+ }
4817
+ cur += ch;
4818
+ }
4819
+ if (cur || quoted) out.push(cur);
4820
+ return out;
4821
+ }
4822
+ function rmExpandVars(token, env2) {
4823
+ let current = token;
4824
+ for (let round = 0; round < 3; round++) {
4825
+ const next = current.replace(RM_VAR_RE, (whole, braced, bare) => {
4826
+ const name = String(braced || bare).toLowerCase();
4827
+ return env2.get(name) ?? whole;
4828
+ });
4829
+ if (next === current) break;
4830
+ current = next;
4831
+ }
4832
+ return current;
4833
+ }
4834
+ function rmResolvedDangerous(resolved) {
4835
+ if (resolved === "/" || resolved.startsWith("/.")) return true;
4836
+ const first = resolved.split("/")[1] || "";
4837
+ if (first === "home") {
4838
+ const parts = resolved.split("/").filter(Boolean);
4839
+ return parts.length <= 2;
4840
+ }
4841
+ if (RM_SENSITIVE_FIRST.has(first)) return true;
4842
+ if (first === "var" && !(resolved === "/var/tmp" || resolved.startsWith("/var/tmp/"))) {
4843
+ return true;
4844
+ }
4845
+ return false;
4846
+ }
4847
+ function checkRmResolvedTargets(text) {
4848
+ const env2 = /* @__PURE__ */ new Map();
4849
+ for (let segment of splitCommandSegments2(text)) {
4850
+ if (!segment) continue;
4851
+ while (true) {
4852
+ const m = segment.match(RM_ASSIGN_RE);
4853
+ if (!m) break;
4854
+ let value = m[2].trim();
4855
+ if (value.length >= 2 && value[0] === value[value.length - 1] && (value[0] === "'" || value[0] === '"')) {
4856
+ value = value.slice(1, -1);
4857
+ }
4858
+ env2.set(m[1].toLowerCase(), rmExpandVars(value, env2));
4859
+ segment = segment.slice(m[0].length);
4860
+ }
4861
+ const parts = shlexSplitLite(segment);
4862
+ if (parts.length === 0) continue;
4863
+ let idx = 0;
4864
+ while (idx < parts.length && RM_COMMAND_PREFIXES.has(parts[idx].toLowerCase())) idx++;
4865
+ if (idx >= parts.length) continue;
4866
+ const commandWord = parts[idx].split("/").pop().replace(/^\\/, "").toLowerCase();
4867
+ if (commandWord !== "rm") continue;
4868
+ let optionsDone = false;
4869
+ for (const token of parts.slice(idx + 1)) {
4870
+ if (token === "--") {
4871
+ optionsDone = true;
4872
+ continue;
4873
+ }
4874
+ if (!optionsDone && token.startsWith("-")) continue;
4875
+ const target = rmExpandVars(token, env2);
4876
+ if (!target.startsWith("/")) continue;
4877
+ const resolved = posix.normalize(target);
4878
+ if (rmResolvedDangerous(resolved)) {
4879
+ return {
4880
+ allowed: false,
4881
+ reason: `\u68C0\u6D4B\u5230\u5220\u9664\u6839\u76EE\u5F55/\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55\uFF08\u89E3\u6790\u540E\u76EE\u6807 ${resolved}\uFF09`,
4882
+ riskLevel: "critical",
4883
+ riskType: "script_execution",
4884
+ confidence: 95,
4885
+ source: "heuristic",
4886
+ violatedLayers: ["L1.1"]
4887
+ };
4888
+ }
4889
+ }
4890
+ }
4891
+ return null;
4892
+ }
4485
4893
  function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
4486
4894
  const scanDetail = normalizePathSegments(stripLiteralTextSegments(actionDetail));
4487
4895
  const scanCommands = String(osType || "").toLowerCase() === "windows" ? [
@@ -4500,16 +4908,19 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
4500
4908
  }
4501
4909
  }
4502
4910
  }
4503
- if (!top) return null;
4504
- return {
4911
+ const toJudgment = (hit) => ({
4505
4912
  allowed: false,
4506
- reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${top.desc}`,
4507
- riskLevel: top.sev,
4508
- riskType: top.type,
4913
+ reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${hit.desc}`,
4914
+ riskLevel: hit.sev,
4915
+ riskType: hit.type,
4509
4916
  confidence: 95,
4510
4917
  source: "heuristic",
4511
4918
  violatedLayers: ["L1.1"]
4512
- };
4919
+ });
4920
+ if (top && severityRank(top.sev) >= severityRank("high")) return toJudgment(top);
4921
+ const rmResolved = checkRmResolvedTargets(scanDetail);
4922
+ if (rmResolved) return rmResolved;
4923
+ return top ? toJudgment(top) : null;
4513
4924
  }
4514
4925
  function allUrlsLoopback(actionDetail) {
4515
4926
  const hosts = actionDetail.match(new RegExp(LOOPBACK_URL_RE.source, "gi"));
@@ -4583,6 +4994,23 @@ function runHeuristicCheck(input) {
4583
4994
  deobfuscated
4584
4995
  );
4585
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
+ }
4586
5014
  let topRiskType = "";
4587
5015
  const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
4588
5016
  const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
@@ -4607,7 +5035,7 @@ function runHeuristicCheck(input) {
4607
5035
  for (const rule of agentExt.extra_command_patterns) {
4608
5036
  try {
4609
5037
  const re = new RegExp(rule.pattern, "i");
4610
- if (scanCommands.some((c) => re.test(c))) {
5038
+ if (extraScanCommands.some((c) => re.test(c))) {
4611
5039
  matched.push(`agent \u4E13\u5C5E\u89C4\u5219: ${rule.reason}`);
4612
5040
  if (severityRank(rule.risk_level) > severityRank(highestSeverity)) {
4613
5041
  highestSeverity = rule.risk_level;
@@ -4618,7 +5046,7 @@ function runHeuristicCheck(input) {
4618
5046
  }
4619
5047
  }
4620
5048
  }
4621
- 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();
4622
5050
  let pythonWalkOnerrorOnly = false;
4623
5051
  if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
4624
5052
  pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
@@ -4644,6 +5072,10 @@ function runHeuristicCheck(input) {
4644
5072
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
4645
5073
  const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
4646
5074
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
5075
+ if (isBashLike && !handledWrite && severityRank(highestSeverity) < severityRank("high") && !mergeResults.some((r) => severityRank(r.riskLevel) >= severityRank("high"))) {
5076
+ const rmResolved = checkRmResolvedTargets(scanDetail);
5077
+ if (rmResolved) mergeResults.push(rmResolved);
5078
+ }
4647
5079
  if (mergeResults.length > 0) {
4648
5080
  let best = mergeResults[0];
4649
5081
  for (const r of mergeResults) {
@@ -4660,6 +5092,9 @@ function runHeuristicCheck(input) {
4660
5092
  violatedLayers: ["L1.1"]
4661
5093
  };
4662
5094
  }
5095
+ if (best !== pathResult && pathResult?.deniedReadPath && best.riskType === "file_access" && best.riskLevel === pathResult.riskLevel) {
5096
+ best = { ...best, deniedReadPath: pathResult.deniedReadPath };
5097
+ }
4663
5098
  return best;
4664
5099
  }
4665
5100
  if (matched.length > 0) {
@@ -4862,16 +5297,83 @@ function splitCommandSegments2(actionDetail) {
4862
5297
  if (start < actionDetail.length) segments.push(actionDetail.slice(start));
4863
5298
  return segments;
4864
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
+ }
4865
5363
  function stripSearchPatternLiterals(actionDetail) {
4866
5364
  const parts = [];
4867
5365
  for (const seg of splitCommandSegments2(actionDetail)) {
5366
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) {
5367
+ parts.push(seg);
5368
+ continue;
5369
+ }
4868
5370
  const low = seg.trim().toLowerCase();
4869
5371
  const words = low.length ? low.split(/\s+/) : [];
4870
5372
  let idx = 0;
4871
5373
  while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
4872
5374
  const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
4873
5375
  if (isSearch && !low.includes("--pre")) {
4874
- parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
5376
+ parts.push(stripSearchPatternArgument(seg));
4875
5377
  } else {
4876
5378
  parts.push(seg);
4877
5379
  }
@@ -4919,7 +5421,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4919
5421
  riskType: "file_access",
4920
5422
  confidence: 90,
4921
5423
  source: "heuristic",
4922
- violatedLayers: ["L1.1"]
5424
+ violatedLayers: ["L1.1"],
5425
+ deniedReadPath: sp.path
4923
5426
  };
4924
5427
  }
4925
5428
  const denyMode = sp.denyMode || (sp.credential ? "deny_both" : sp.readOnly ? "deny_read" : "deny_write");
@@ -4933,7 +5436,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4933
5436
  confidence: 90,
4934
5437
  source: "heuristic",
4935
5438
  violatedLayers: ["L1.1"],
4936
- isCredential: !!sp.credential
5439
+ isCredential: !!sp.credential,
5440
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
4937
5441
  };
4938
5442
  }
4939
5443
  }
@@ -4990,7 +5494,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4990
5494
  confidence: 90,
4991
5495
  source: "heuristic",
4992
5496
  violatedLayers: ["L1.1"],
4993
- isCredential: !!sp.credential
5497
+ isCredential: !!sp.credential,
5498
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
4994
5499
  };
4995
5500
  }
4996
5501
  }
@@ -5013,7 +5518,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5013
5518
  confidence: 90,
5014
5519
  source: "heuristic",
5015
5520
  violatedLayers: ["L1.1"],
5016
- isCredential: !!sp.credential
5521
+ isCredential: !!sp.credential,
5522
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5017
5523
  };
5018
5524
  }
5019
5525
  }
@@ -5030,7 +5536,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5030
5536
  confidence: 90,
5031
5537
  source: "heuristic",
5032
5538
  violatedLayers: ["L1.1"],
5033
- isCredential: true
5539
+ isCredential: true,
5540
+ deniedReadPath: cp.path
5034
5541
  };
5035
5542
  }
5036
5543
  }
@@ -5191,7 +5698,7 @@ function checkDangerousPatterns(actionType, actionDetail) {
5191
5698
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
5192
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;
5193
5700
  const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
5194
- if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
5701
+ if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
5195
5702
  return {
5196
5703
  allowed: false,
5197
5704
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -5333,7 +5840,7 @@ function checkLateralMovement(actionDetail) {
5333
5840
  }
5334
5841
  return null;
5335
5842
  }
5336
- var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, 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;
5337
5844
  var init_heuristic = __esm({
5338
5845
  "src/engine/heuristic.ts"() {
5339
5846
  "use strict";
@@ -5359,6 +5866,10 @@ var init_heuristic = __esm({
5359
5866
  DANGEROUS_PATTERNS_WINDOWS = _loadDangerousPatterns("windows");
5360
5867
  DANGEROUS_PATTERNS_MACOS = _loadDangerousPatterns("macos");
5361
5868
  DANGEROUS_PATTERNS_HARMONY = _loadDangerousPatterns("harmony");
5869
+ RM_ASSIGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|]+)\s*/;
5870
+ RM_VAR_RE = /\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;
5871
+ RM_COMMAND_PREFIXES = /* @__PURE__ */ new Set(["sudo", "env", "command", "builtin", "exec", "nohup", "time"]);
5872
+ RM_SENSITIVE_FIRST = /* @__PURE__ */ new Set(["etc", "usr", "boot", "root", "opt", "srv", "sys", "proc", "home"]);
5362
5873
  LOOPBACK_URL_RE = /https?:\/\/([^\/\s;'"|&)]+)/i;
5363
5874
  HEURISTIC_RULES = loadHeuristicRules();
5364
5875
  LOOPBACK_HOSTS = new Set(HEURISTIC_RULES.loopback_hosts ?? []);
@@ -5378,6 +5889,28 @@ var init_heuristic = __esm({
5378
5889
  COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
5379
5890
  TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
5380
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
+ ]);
5381
5914
  SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
5382
5915
  SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
5383
5916
  SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
@@ -8195,6 +8728,15 @@ var LLM_SHORT_CIRCUIT_TOTAL = new Counter(
8195
8728
  );
8196
8729
 
8197
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";
8198
8740
  var LLMCircuitOpenError = class extends Error {
8199
8741
  constructor(message) {
8200
8742
  super(message);
@@ -8295,6 +8837,9 @@ async function runLLMAnalysis(input, previous) {
8295
8837
  scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
8296
8838
  }
8297
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;
8298
8843
  let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
8299
8844
  let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
8300
8845
  let prompt = "";
@@ -8311,13 +8856,14 @@ async function runLLMAnalysis(input, previous) {
8311
8856
  historyMaxItems,
8312
8857
  historyMaxChars
8313
8858
  );
8314
- if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
8859
+ if (!budgetActive || estimateTokens(prompt) <= tokenLimit) break;
8315
8860
  historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
8316
8861
  historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
8317
8862
  }
8318
- if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
8863
+ let budgetCode = "";
8864
+ if (budgetActive && estimateTokens(prompt) > tokenLimit) {
8319
8865
  const estimated = estimateTokens(prompt);
8320
- const ratio = estimated / maxPromptTokens;
8866
+ const ratio = tokenLimit > 0 ? estimated / tokenLimit : Number.POSITIVE_INFINITY;
8321
8867
  const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
8322
8868
  const truncated = truncateDetail(input.aNext.actionDetail, allowed);
8323
8869
  prompt = buildPrompt(
@@ -8333,8 +8879,14 @@ async function runLLMAnalysis(input, previous) {
8333
8879
  historyMaxChars
8334
8880
  );
8335
8881
  console.warn(
8336
- `[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`
8337
8883
  );
8884
+ if (estimateTokens(prompt) > tokenLimit) {
8885
+ if (budgetMode === "hard") {
8886
+ throw new LLMPromptBudgetExceeded("l3_budget_unreachable");
8887
+ }
8888
+ budgetCode = "l3_budget_unreachable";
8889
+ }
8338
8890
  }
8339
8891
  logPrompt(prompt, input.aNext, previous.llmLogPath);
8340
8892
  traceFull("l3.prompt", {
@@ -8347,6 +8899,7 @@ async function runLLMAnalysis(input, previous) {
8347
8899
  prompt_chars: prompt.length
8348
8900
  });
8349
8901
  const result = await analyzeWithLLM(prompt, config);
8902
+ if (budgetCode) result.degraded = [...result.degraded || [], budgetCode];
8350
8903
  traceSummary("l3.verdict", {
8351
8904
  allowed: result.allowed,
8352
8905
  risk_level: result.riskLevel,
@@ -8420,11 +8973,14 @@ function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis,
8420
8973
  const skillsText = formatSkillsForPrompt(matchedSkills);
8421
8974
  const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
8422
8975
  const promptHistoryText = formatPromptHistory(input.promptHistory);
8976
+ const historyAuthorization = /(因历史窗口上限省略|本段因长度上限已截断)/.test(promptHistoryText) ? `
8977
+
8978
+ ${HISTORY_AUTHORIZATION}` : "";
8423
8979
  const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
8424
8980
  const hintsText = formatHints(previous);
8425
8981
  const securityJudgeTemplate = templates["security_judge"];
8426
8982
  if (securityJudgeTemplate) {
8427
- 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("}}", "}");
8428
8984
  }
8429
8985
  console.warn("[AgentMoss] security_judge template missing, using sparse fallback prompt");
8430
8986
  return `## \u5F53\u524D\u64CD\u4F5C\u4E0A\u4E0B\u6587
@@ -8454,25 +9010,34 @@ ${scriptAnalysisText}` : ""}
8454
9010
  \u8F93\u51FA\u683C\u5F0F:
8455
9011
  {"allowed": true/false, "reason": "\u5224\u65AD\u7406\u7531", "riskLevel": "low|medium|high|critical", "riskType": "\u98CE\u9669\u7C7B\u578B", "confidence": 0-100}`;
8456
9012
  }
8457
- function formatPromptHistory(promptHistory, maxTextChars = 500) {
9013
+ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNumSetting("AGENT_MOSS_LLM_PROMPT_HISTORY_MAX_TURNS", 20)) {
8458
9014
  if (!promptHistory || promptHistory.length === 0) {
8459
9015
  return "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
8460
9016
  }
9017
+ const limit = Math.max(0, Math.floor(maxTurns));
9018
+ const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
9019
+ let omitted = 0;
8461
9020
  const lines = [];
8462
9021
  for (let i = 0; i < promptHistory.length; i++) {
8463
9022
  const turn = promptHistory[i];
8464
9023
  const text = (typeof turn === "string" ? turn : turn?.text || "").trim();
8465
- if (!text) continue;
8466
- let line = ` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${text.slice(0, maxTextChars)}`;
8467
9024
  const actions = typeof turn === "string" ? void 0 : turn?.actions;
8468
- if (actions && actions.length > 0) {
8469
- const types = actions.map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
8470
- if (types.length > 0) {
8471
- line += ` \u2192 \u52A8\u4F5C: ${types.join(", ")}`;
8472
- }
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;
8473
9030
  }
8474
- lines.push(line);
9031
+ if (!text) {
9032
+ lines.push(` \u7B2C${i + 1}\u8F6E\u52A8\u4F5C: ${types.join(", ")}`);
9033
+ continue;
9034
+ }
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}`);
8475
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`);
8476
9041
  return lines.length > 0 ? lines.join("\n") : "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
8477
9042
  }
8478
9043
  function formatHints(previous) {
@@ -8485,11 +9050,15 @@ function formatHints(previous) {
8485
9050
  );
8486
9051
  }
8487
9052
  if (previous.logic) {
8488
- hints.push(
8489
- `\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}]:
8490
9058
  \u7C7B\u578B: ${previous.logic.riskType}
8491
9059
  \u539F\u56E0: ${previous.logic.reason}`
8492
- );
9060
+ );
9061
+ }
8493
9062
  }
8494
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";
8495
9064
  }
@@ -9834,11 +10403,35 @@ function checkMCRules(graph) {
9834
10403
  for (const rule of rules) {
9835
10404
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
9836
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
+ }));
9837
10412
  violations.push({
9838
10413
  propertyId: String(rule.id || "mc-ltl"),
9839
10414
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
9840
10415
  riskLevel: String(rule.risk_level || "high"),
9841
- 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
+ }
9842
10435
  });
9843
10436
  if (witnessMode) return violations;
9844
10437
  }
@@ -10533,11 +11126,17 @@ function checkLowIntegrityCommandExec(graph) {
10533
11126
  for (const i of candidates) {
10534
11127
  const n = nodes[i];
10535
11128
  if (lowAt.has(i) && isComputeNode(n)) {
11129
+ const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10536
11130
  violations.push({
10537
11131
  propertyId: "low-integrity-command-exec",
10538
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`,
10539
11133
  riskLevel: "critical",
10540
- 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"])
10541
11140
  });
10542
11141
  if (witness !== void 0) return violations;
10543
11142
  }
@@ -10580,11 +11179,21 @@ function checkCrossSessionReachability(graph) {
10580
11179
  if (reached.has(i)) {
10581
11180
  const srcIdx = Math.min(...sources);
10582
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
+ }));
10583
11187
  violations.push({
10584
11188
  propertyId: "low-integrity-reachability",
10585
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`,
10586
11190
  riskLevel: "high",
10587
- 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
+ })
10588
11197
  });
10589
11198
  if (witness !== void 0) return violations;
10590
11199
  }
@@ -10720,6 +11329,7 @@ var FormalEngine = class {
10720
11329
  // src/engine/formal-engine/stateful.ts
10721
11330
  init_esm_shims();
10722
11331
  init_rules_loader();
11332
+ import { createHash as createHash2 } from "crypto";
10723
11333
  import * as fs5 from "fs";
10724
11334
  import * as os3 from "os";
10725
11335
  import * as path6 from "path";
@@ -10735,7 +11345,7 @@ init_esm_shims();
10735
11345
  import * as fs6 from "fs";
10736
11346
  import * as os4 from "os";
10737
11347
  import * as path7 from "path";
10738
- import { createHash as createHash2 } from "crypto";
11348
+ import { createHash as createHash3 } from "crypto";
10739
11349
 
10740
11350
  // src/engine/coordinator.ts
10741
11351
  var TRUSTED_SKILLS_BASE = /* @__PURE__ */ new Set([]);
@@ -10753,6 +11363,25 @@ function extractRawCommand(detail) {
10753
11363
  const m = detail.match(/command=([^,]+)/);
10754
11364
  return m ? m[1].trim() : detail;
10755
11365
  }
11366
+ function independentFileCommand(command, osType) {
11367
+ if (String(osType).toLowerCase() === "windows") return "";
11368
+ if (["\\", "#", "<<", "<(", ">(", "`", "$"].some((mark) => command.includes(mark))) return "";
11369
+ const parts = splitCommandSegments(command);
11370
+ if (parts.length !== 2) return "";
11371
+ const ordinary = parts.filter((part2) => !isInlineScriptCommand(part2.toLowerCase()));
11372
+ if (ordinary.length !== 1) return "";
11373
+ const part = ordinary[0];
11374
+ const name = part.trim().split(/\s+/)[0] || "";
11375
+ const { writeCommandRes } = getPlatformTraits(osType);
11376
+ const isWriteCommandName = writeCommandRes.some((rx) => {
11377
+ const flags = rx.flags.replace("g", "");
11378
+ return new RegExp(`^(?:${rx.source})$`, flags).test(name);
11379
+ });
11380
+ if (SHELL_FULL_READ_CMDS.includes(name) || isWriteCommandName) {
11381
+ return part;
11382
+ }
11383
+ return "";
11384
+ }
10756
11385
  function matchesAny(cmd, patterns) {
10757
11386
  return patterns.some((p) => p.test(cmd));
10758
11387
  }
@@ -10838,21 +11467,42 @@ async function runAnalysis(input) {
10838
11467
  const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
10839
11468
  const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
10840
11469
  if (heuristicResult && !heuristicResult.allowed) {
10841
- const skipInlineFileAccess = (isInlineScriptCmd || isLiteralTextCmd) && heuristicResult.riskType === "file_access";
10842
- if (!skipInlineFileAccess) {
10843
- const shouldDenyL1 = heuristicResult.riskLevel === "high" || heuristicResult.riskLevel === "critical" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "file_access" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "resource_exhaustion";
10844
- if (shouldDenyL1) {
10845
- return heuristicResult;
11470
+ let skipInlineFileAccess = (isInlineScriptCmd || isLiteralTextCmd) && heuristicResult.riskType === "file_access";
11471
+ const shouldDenyL1 = heuristicResult.riskLevel === "high" || heuristicResult.riskLevel === "critical" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "file_access" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "resource_exhaustion";
11472
+ const bashLike = ["bash", "executebash", "terminal-executebash"].includes(input.aNext.actionType.toLowerCase());
11473
+ if (skipInlineFileAccess && shouldDenyL1 && isInlineScriptCmd && bashLike) {
11474
+ const detail = input.aNext.actionDetail;
11475
+ const command = independentFileCommand(detail, input.osType);
11476
+ if (command) {
11477
+ const hit = runHeuristicCheck({ ...input, aNext: { ...input.aNext, actionDetail: command } });
11478
+ if (hit && !hit.allowed && hit.riskType === "file_access" && ["medium", "high", "critical"].includes(hit.riskLevel)) {
11479
+ return hit;
11480
+ }
11481
+ } else if (String(input.osType || "").toLowerCase() !== "windows" && heuristicResult.deniedReadPath) {
11482
+ skipInlineFileAccess = !confirmsInlineRead(detail, heuristicResult.deniedReadPath);
10846
11483
  }
10847
11484
  }
11485
+ if (!skipInlineFileAccess && shouldDenyL1) {
11486
+ return heuristicResult;
11487
+ }
10848
11488
  }
10849
11489
  const agentExt = mergeAgentExtensions(
10850
11490
  isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
10851
11491
  isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
10852
11492
  );
11493
+ const degradedNotes = [];
10853
11494
  let scriptChain = null;
10854
- 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") {
10855
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
+ }
10856
11506
  if (heuristicEnabled && scriptChain.nodes.length > 0) {
10857
11507
  for (const node of scriptChain.nodes) {
10858
11508
  if (node.unanalyzable) {
@@ -11123,7 +11773,8 @@ async function runAnalysis(input) {
11123
11773
  riskType: "",
11124
11774
  confidence: 85,
11125
11775
  source: "heuristic_and_logic_only",
11126
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
11776
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
11777
+ degraded: degradedNotes
11127
11778
  };
11128
11779
  }
11129
11780
  let skipL3Hints = "\u65E0\uFF08\u5F53\u524D\u65E0\u7981\u7528\u89C4\u5219\u547D\u4E2D\uFF09";
@@ -11160,8 +11811,22 @@ async function runAnalysis(input) {
11160
11811
  pathContext
11161
11812
  });
11162
11813
  } catch (e) {
11163
- const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
11164
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";
11165
11830
  if (getLLMFailMode2() === "fail_open") {
11166
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}`);
11167
11832
  return {
@@ -11171,7 +11836,8 @@ async function runAnalysis(input) {
11171
11836
  riskType: "",
11172
11837
  confidence: 50,
11173
11838
  source: failSource,
11174
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
11839
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
11840
+ degraded: degradedNotes
11175
11841
  };
11176
11842
  }
11177
11843
  return {
@@ -11181,7 +11847,10 @@ async function runAnalysis(input) {
11181
11847
  riskType: "",
11182
11848
  confidence: 60,
11183
11849
  source: failSource,
11184
- 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"
11185
11854
  };
11186
11855
  }
11187
11856
  if (!llmResult.allowed && llmResult.confidence && llmResult.confidence >= 90 && _brainExtractor) {
@@ -11201,12 +11870,16 @@ async function runAnalysis(input) {
11201
11870
  if (observedFormalLayers.length > 0 && llmResult.allowed) {
11202
11871
  llmResult.violatedLayers = Array.from(/* @__PURE__ */ new Set([...observedFormalLayers, ...llmResult.violatedLayers || []]));
11203
11872
  }
11873
+ if (degradedNotes.length > 0) {
11874
+ llmResult.degraded = Array.from(/* @__PURE__ */ new Set([...llmResult.degraded || [], ...degradedNotes]));
11875
+ }
11204
11876
  return llmResult;
11205
11877
  }
11206
11878
  export {
11207
11879
  TRUSTED_SKILLS_BASE,
11208
11880
  _resetBrainForTest,
11209
11881
  extractFirstCommand,
11882
+ independentFileCommand,
11210
11883
  matchesAny,
11211
11884
  runAnalysis,
11212
11885
  splitCommandSegments,