@kenhkl/agent-moss 0.17.39 → 0.17.41

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.
@@ -42,6 +42,8 @@ interface SecurityJudgment {
42
42
  source: string;
43
43
  violatedLayers: string[];
44
44
  isCredential?: boolean;
45
+ /** 原命中的路径规则明确禁止读取时赋值,供内联读取确认复核 */
46
+ deniedReadPath?: string;
45
47
  /** 组合式拦截的结构化攻击链(前端可视化用) */
46
48
  violationGraph?: AttackChainGraph | null;
47
49
  /** 兼容旧调用方:反例路径数组 */
@@ -123,10 +125,17 @@ interface AnalysisInput {
123
125
  declare const TRUSTED_SKILLS_BASE: Set<string>;
124
126
 
125
127
  declare function whitelistTier(command: string, fullySafe: RegExp[], readonlySensitive: RegExp[]): 'full' | 'readonly' | '';
128
+ /**
129
+ * 仅复核和内联脚本并列的一条普通命令,复杂 shell 继续原暂缓流程。
130
+ *
131
+ * 镜像 Python `_independent_file_command`:`cat /etc/shadow && python3 -c ...`
132
+ * 这种「真实文件命令 + 内联脚本」不能因为后半段是内联脚本就整体豁免 L1。
133
+ */
134
+ declare function independentFileCommand(command: string, osType: string): string;
126
135
  /** 导出供白名单测试直接断言;正则都带 /i 且无 /g,test() 无 lastIndex 副作用 */
127
136
  declare function matchesAny(cmd: string, patterns: RegExp[]): boolean;
128
137
  /** 供测试隔离:重置 brain 单例 */
129
138
  declare function _resetBrainForTest(): void;
130
139
  declare function runAnalysis(input: AnalysisInput): Promise<SecurityJudgment>;
131
140
 
132
- export { type AnalysisInput, TRUSTED_SKILLS_BASE, _resetBrainForTest, extractFirstCommand, matchesAny, runAnalysis, splitCommandSegments, whitelistTier };
141
+ export { type AnalysisInput, TRUSTED_SKILLS_BASE, _resetBrainForTest, extractFirstCommand, independentFileCommand, matchesAny, runAnalysis, splitCommandSegments, whitelistTier };
@@ -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) {
@@ -4455,6 +4606,7 @@ var init_written_content_analyzer = __esm({
4455
4606
  });
4456
4607
 
4457
4608
  // src/engine/heuristic.ts
4609
+ import { posix } from "path";
4458
4610
  function _effectiveDangerousPatterns(osType) {
4459
4611
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
4460
4612
  }
@@ -4482,6 +4634,112 @@ function normalizeShellObfuscation(text) {
4482
4634
  t = t.replace(/\$\{IFS\}|\$IFS/gi, " ");
4483
4635
  return t;
4484
4636
  }
4637
+ function shlexSplitLite(s) {
4638
+ const out = [];
4639
+ let cur = "";
4640
+ let quote = null;
4641
+ let quoted = false;
4642
+ for (let i = 0; i < s.length; i++) {
4643
+ const ch = s[i];
4644
+ if (quote) {
4645
+ if (ch === quote) quote = null;
4646
+ else if (ch === "\\" && quote === '"' && i + 1 < s.length) cur += s[++i];
4647
+ else cur += ch;
4648
+ continue;
4649
+ }
4650
+ if (ch === "'" || ch === '"') {
4651
+ quote = ch;
4652
+ quoted = true;
4653
+ continue;
4654
+ }
4655
+ if (/\s/.test(ch)) {
4656
+ if (cur || quoted) {
4657
+ out.push(cur);
4658
+ cur = "";
4659
+ quoted = false;
4660
+ }
4661
+ continue;
4662
+ }
4663
+ if (ch === "\\" && i + 1 < s.length) {
4664
+ cur += s[++i];
4665
+ continue;
4666
+ }
4667
+ cur += ch;
4668
+ }
4669
+ if (cur || quoted) out.push(cur);
4670
+ return out;
4671
+ }
4672
+ function rmExpandVars(token, env2) {
4673
+ let current = token;
4674
+ for (let round = 0; round < 3; round++) {
4675
+ const next = current.replace(RM_VAR_RE, (whole, braced, bare) => {
4676
+ const name = String(braced || bare).toLowerCase();
4677
+ return env2.get(name) ?? whole;
4678
+ });
4679
+ if (next === current) break;
4680
+ current = next;
4681
+ }
4682
+ return current;
4683
+ }
4684
+ function rmResolvedDangerous(resolved) {
4685
+ if (resolved === "/" || resolved.startsWith("/.")) return true;
4686
+ const first = resolved.split("/")[1] || "";
4687
+ if (first === "home") {
4688
+ const parts = resolved.split("/").filter(Boolean);
4689
+ return parts.length <= 2;
4690
+ }
4691
+ if (RM_SENSITIVE_FIRST.has(first)) return true;
4692
+ if (first === "var" && !(resolved === "/var/tmp" || resolved.startsWith("/var/tmp/"))) {
4693
+ return true;
4694
+ }
4695
+ return false;
4696
+ }
4697
+ function checkRmResolvedTargets(text) {
4698
+ const env2 = /* @__PURE__ */ new Map();
4699
+ for (let segment of splitCommandSegments2(text)) {
4700
+ if (!segment) continue;
4701
+ while (true) {
4702
+ const m = segment.match(RM_ASSIGN_RE);
4703
+ if (!m) break;
4704
+ let value = m[2].trim();
4705
+ if (value.length >= 2 && value[0] === value[value.length - 1] && (value[0] === "'" || value[0] === '"')) {
4706
+ value = value.slice(1, -1);
4707
+ }
4708
+ env2.set(m[1].toLowerCase(), rmExpandVars(value, env2));
4709
+ segment = segment.slice(m[0].length);
4710
+ }
4711
+ const parts = shlexSplitLite(segment);
4712
+ if (parts.length === 0) continue;
4713
+ let idx = 0;
4714
+ while (idx < parts.length && RM_COMMAND_PREFIXES.has(parts[idx].toLowerCase())) idx++;
4715
+ if (idx >= parts.length) continue;
4716
+ const commandWord = parts[idx].split("/").pop().replace(/^\\/, "").toLowerCase();
4717
+ if (commandWord !== "rm") continue;
4718
+ let optionsDone = false;
4719
+ for (const token of parts.slice(idx + 1)) {
4720
+ if (token === "--") {
4721
+ optionsDone = true;
4722
+ continue;
4723
+ }
4724
+ if (!optionsDone && token.startsWith("-")) continue;
4725
+ const target = rmExpandVars(token, env2);
4726
+ if (!target.startsWith("/")) continue;
4727
+ const resolved = posix.normalize(target);
4728
+ if (rmResolvedDangerous(resolved)) {
4729
+ return {
4730
+ allowed: false,
4731
+ reason: `\u68C0\u6D4B\u5230\u5220\u9664\u6839\u76EE\u5F55/\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55\uFF08\u89E3\u6790\u540E\u76EE\u6807 ${resolved}\uFF09`,
4732
+ riskLevel: "critical",
4733
+ riskType: "script_execution",
4734
+ confidence: 95,
4735
+ source: "heuristic",
4736
+ violatedLayers: ["L1.1"]
4737
+ };
4738
+ }
4739
+ }
4740
+ }
4741
+ return null;
4742
+ }
4485
4743
  function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
4486
4744
  const scanDetail = normalizePathSegments(stripLiteralTextSegments(actionDetail));
4487
4745
  const scanCommands = String(osType || "").toLowerCase() === "windows" ? [
@@ -4500,16 +4758,19 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
4500
4758
  }
4501
4759
  }
4502
4760
  }
4503
- if (!top) return null;
4504
- return {
4761
+ const toJudgment = (hit) => ({
4505
4762
  allowed: false,
4506
- reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${top.desc}`,
4507
- riskLevel: top.sev,
4508
- riskType: top.type,
4763
+ reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${hit.desc}`,
4764
+ riskLevel: hit.sev,
4765
+ riskType: hit.type,
4509
4766
  confidence: 95,
4510
4767
  source: "heuristic",
4511
4768
  violatedLayers: ["L1.1"]
4512
- };
4769
+ });
4770
+ if (top && severityRank(top.sev) >= severityRank("high")) return toJudgment(top);
4771
+ const rmResolved = checkRmResolvedTargets(scanDetail);
4772
+ if (rmResolved) return rmResolved;
4773
+ return top ? toJudgment(top) : null;
4513
4774
  }
4514
4775
  function allUrlsLoopback(actionDetail) {
4515
4776
  const hosts = actionDetail.match(new RegExp(LOOPBACK_URL_RE.source, "gi"));
@@ -4644,6 +4905,10 @@ function runHeuristicCheck(input) {
4644
4905
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
4645
4906
  const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
4646
4907
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
4908
+ if (isBashLike && !handledWrite && severityRank(highestSeverity) < severityRank("high") && !mergeResults.some((r) => severityRank(r.riskLevel) >= severityRank("high"))) {
4909
+ const rmResolved = checkRmResolvedTargets(scanDetail);
4910
+ if (rmResolved) mergeResults.push(rmResolved);
4911
+ }
4647
4912
  if (mergeResults.length > 0) {
4648
4913
  let best = mergeResults[0];
4649
4914
  for (const r of mergeResults) {
@@ -4660,6 +4925,9 @@ function runHeuristicCheck(input) {
4660
4925
  violatedLayers: ["L1.1"]
4661
4926
  };
4662
4927
  }
4928
+ if (best !== pathResult && pathResult?.deniedReadPath && best.riskType === "file_access" && best.riskLevel === pathResult.riskLevel) {
4929
+ best = { ...best, deniedReadPath: pathResult.deniedReadPath };
4930
+ }
4663
4931
  return best;
4664
4932
  }
4665
4933
  if (matched.length > 0) {
@@ -4919,7 +5187,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4919
5187
  riskType: "file_access",
4920
5188
  confidence: 90,
4921
5189
  source: "heuristic",
4922
- violatedLayers: ["L1.1"]
5190
+ violatedLayers: ["L1.1"],
5191
+ deniedReadPath: sp.path
4923
5192
  };
4924
5193
  }
4925
5194
  const denyMode = sp.denyMode || (sp.credential ? "deny_both" : sp.readOnly ? "deny_read" : "deny_write");
@@ -4933,7 +5202,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4933
5202
  confidence: 90,
4934
5203
  source: "heuristic",
4935
5204
  violatedLayers: ["L1.1"],
4936
- isCredential: !!sp.credential
5205
+ isCredential: !!sp.credential,
5206
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
4937
5207
  };
4938
5208
  }
4939
5209
  }
@@ -4990,7 +5260,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4990
5260
  confidence: 90,
4991
5261
  source: "heuristic",
4992
5262
  violatedLayers: ["L1.1"],
4993
- isCredential: !!sp.credential
5263
+ isCredential: !!sp.credential,
5264
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
4994
5265
  };
4995
5266
  }
4996
5267
  }
@@ -5013,7 +5284,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5013
5284
  confidence: 90,
5014
5285
  source: "heuristic",
5015
5286
  violatedLayers: ["L1.1"],
5016
- isCredential: !!sp.credential
5287
+ isCredential: !!sp.credential,
5288
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5017
5289
  };
5018
5290
  }
5019
5291
  }
@@ -5030,7 +5302,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5030
5302
  confidence: 90,
5031
5303
  source: "heuristic",
5032
5304
  violatedLayers: ["L1.1"],
5033
- isCredential: true
5305
+ isCredential: true,
5306
+ deniedReadPath: cp.path
5034
5307
  };
5035
5308
  }
5036
5309
  }
@@ -5333,7 +5606,7 @@ function checkLateralMovement(actionDetail) {
5333
5606
  }
5334
5607
  return null;
5335
5608
  }
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;
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;
5337
5610
  var init_heuristic = __esm({
5338
5611
  "src/engine/heuristic.ts"() {
5339
5612
  "use strict";
@@ -5359,6 +5632,10 @@ var init_heuristic = __esm({
5359
5632
  DANGEROUS_PATTERNS_WINDOWS = _loadDangerousPatterns("windows");
5360
5633
  DANGEROUS_PATTERNS_MACOS = _loadDangerousPatterns("macos");
5361
5634
  DANGEROUS_PATTERNS_HARMONY = _loadDangerousPatterns("harmony");
5635
+ RM_ASSIGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|]+)\s*/;
5636
+ RM_VAR_RE = /\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;
5637
+ RM_COMMAND_PREFIXES = /* @__PURE__ */ new Set(["sudo", "env", "command", "builtin", "exec", "nohup", "time"]);
5638
+ RM_SENSITIVE_FIRST = /* @__PURE__ */ new Set(["etc", "usr", "boot", "root", "opt", "srv", "sys", "proc", "home"]);
5362
5639
  LOOPBACK_URL_RE = /https?:\/\/([^\/\s;'"|&)]+)/i;
5363
5640
  HEURISTIC_RULES = loadHeuristicRules();
5364
5641
  LOOPBACK_HOSTS = new Set(HEURISTIC_RULES.loopback_hosts ?? []);
@@ -8454,12 +8731,14 @@ ${scriptAnalysisText}` : ""}
8454
8731
  \u8F93\u51FA\u683C\u5F0F:
8455
8732
  {"allowed": true/false, "reason": "\u5224\u65AD\u7406\u7531", "riskLevel": "low|medium|high|critical", "riskType": "\u98CE\u9669\u7C7B\u578B", "confidence": 0-100}`;
8456
8733
  }
8457
- function formatPromptHistory(promptHistory, maxTextChars = 500) {
8734
+ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNumSetting("AGENT_MOSS_LLM_PROMPT_HISTORY_MAX_TURNS", 20)) {
8458
8735
  if (!promptHistory || promptHistory.length === 0) {
8459
8736
  return "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
8460
8737
  }
8738
+ const limit = Math.max(0, Math.floor(maxTurns));
8739
+ const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
8461
8740
  const lines = [];
8462
- for (let i = 0; i < promptHistory.length; i++) {
8741
+ for (let i = firstTurnIndex; i < promptHistory.length; i++) {
8463
8742
  const turn = promptHistory[i];
8464
8743
  const text = (typeof turn === "string" ? turn : turn?.text || "").trim();
8465
8744
  if (!text) continue;
@@ -10720,6 +10999,7 @@ var FormalEngine = class {
10720
10999
  // src/engine/formal-engine/stateful.ts
10721
11000
  init_esm_shims();
10722
11001
  init_rules_loader();
11002
+ import { createHash as createHash2 } from "crypto";
10723
11003
  import * as fs5 from "fs";
10724
11004
  import * as os3 from "os";
10725
11005
  import * as path6 from "path";
@@ -10735,7 +11015,7 @@ init_esm_shims();
10735
11015
  import * as fs6 from "fs";
10736
11016
  import * as os4 from "os";
10737
11017
  import * as path7 from "path";
10738
- import { createHash as createHash2 } from "crypto";
11018
+ import { createHash as createHash3 } from "crypto";
10739
11019
 
10740
11020
  // src/engine/coordinator.ts
10741
11021
  var TRUSTED_SKILLS_BASE = /* @__PURE__ */ new Set([]);
@@ -10753,6 +11033,25 @@ function extractRawCommand(detail) {
10753
11033
  const m = detail.match(/command=([^,]+)/);
10754
11034
  return m ? m[1].trim() : detail;
10755
11035
  }
11036
+ function independentFileCommand(command, osType) {
11037
+ if (String(osType).toLowerCase() === "windows") return "";
11038
+ if (["\\", "#", "<<", "<(", ">(", "`", "$"].some((mark) => command.includes(mark))) return "";
11039
+ const parts = splitCommandSegments(command);
11040
+ if (parts.length !== 2) return "";
11041
+ const ordinary = parts.filter((part2) => !isInlineScriptCommand(part2.toLowerCase()));
11042
+ if (ordinary.length !== 1) return "";
11043
+ const part = ordinary[0];
11044
+ const name = part.trim().split(/\s+/)[0] || "";
11045
+ const { writeCommandRes } = getPlatformTraits(osType);
11046
+ const isWriteCommandName = writeCommandRes.some((rx) => {
11047
+ const flags = rx.flags.replace("g", "");
11048
+ return new RegExp(`^(?:${rx.source})$`, flags).test(name);
11049
+ });
11050
+ if (SHELL_FULL_READ_CMDS.includes(name) || isWriteCommandName) {
11051
+ return part;
11052
+ }
11053
+ return "";
11054
+ }
10756
11055
  function matchesAny(cmd, patterns) {
10757
11056
  return patterns.some((p) => p.test(cmd));
10758
11057
  }
@@ -10838,13 +11137,24 @@ async function runAnalysis(input) {
10838
11137
  const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
10839
11138
  const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
10840
11139
  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;
11140
+ let skipInlineFileAccess = (isInlineScriptCmd || isLiteralTextCmd) && heuristicResult.riskType === "file_access";
11141
+ const shouldDenyL1 = heuristicResult.riskLevel === "high" || heuristicResult.riskLevel === "critical" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "file_access" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "resource_exhaustion";
11142
+ const bashLike = ["bash", "executebash", "terminal-executebash"].includes(input.aNext.actionType.toLowerCase());
11143
+ if (skipInlineFileAccess && shouldDenyL1 && isInlineScriptCmd && bashLike) {
11144
+ const detail = input.aNext.actionDetail;
11145
+ const command = independentFileCommand(detail, input.osType);
11146
+ if (command) {
11147
+ const hit = runHeuristicCheck({ ...input, aNext: { ...input.aNext, actionDetail: command } });
11148
+ if (hit && !hit.allowed && hit.riskType === "file_access" && ["medium", "high", "critical"].includes(hit.riskLevel)) {
11149
+ return hit;
11150
+ }
11151
+ } else if (String(input.osType || "").toLowerCase() !== "windows" && heuristicResult.deniedReadPath) {
11152
+ skipInlineFileAccess = !confirmsInlineRead(detail, heuristicResult.deniedReadPath);
10846
11153
  }
10847
11154
  }
11155
+ if (!skipInlineFileAccess && shouldDenyL1) {
11156
+ return heuristicResult;
11157
+ }
10848
11158
  }
10849
11159
  const agentExt = mergeAgentExtensions(
10850
11160
  isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
@@ -11207,6 +11517,7 @@ export {
11207
11517
  TRUSTED_SKILLS_BASE,
11208
11518
  _resetBrainForTest,
11209
11519
  extractFirstCommand,
11520
+ independentFileCommand,
11210
11521
  matchesAny,
11211
11522
  runAnalysis,
11212
11523
  splitCommandSegments,
@@ -1,29 +1,35 @@
1
1
  {
2
2
  "dangerous_commands": [
3
3
  {
4
- "pattern": "\\brm\\s+-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\\s+/(?!\\w)",
4
+ "pattern": "\\brm[ \\t]+-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*(?:[ \\t]+(?:-[a-zA-Z]+|--[\\w=-]*))*[ \\t]+[\\\"']?/(?!\\w)",
5
5
  "risk_level": "critical",
6
6
  "risk_type": "script_execution",
7
7
  "reason": "检测到递归强制删除根目录 (rm -rf /)"
8
8
  },
9
9
  {
10
- "pattern": "\\brm\\s+-[a-zA-Z]*[rf][a-zA-Z]*\\s+/(?:etc|var(?!/tmp)|usr|boot|root|opt|srv|sys|proc|home(?:/|/[A-Za-z0-9_.-]+/?)?(?=[\\s;|&\\\"']|$))",
10
+ "pattern": "\\brm[ \\t]+-[a-zA-Z]*[rf][a-zA-Z]*(?:[ \\t]+(?:-[a-zA-Z]+|--[\\w=-]*))*[ \\t]+[\\\"']?/(?:etc|var(?!/tmp)|usr|boot|root|opt|srv|sys|proc|home(?:/|/[A-Za-z0-9_.-]+/?)?(?=[\\s;|&\\\"']|$))",
11
11
  "risk_level": "critical",
12
12
  "risk_type": "script_execution",
13
13
  "reason": "检测到删除关键系统目录"
14
14
  },
15
15
  {
16
- "pattern": "\\brm\\s+-[a-zA-Z]*r[a-zA-Z]*\\s+/(?!tmp|var/tmp|run|dev/shm|mnt|media)(?:/|\\b)",
16
+ "pattern": "\\brm[ \\t]+-[a-zA-Z]*r[a-zA-Z]*(?:[ \\t]+(?:-[a-zA-Z]+|--[\\w=-]*))*[ \\t]+[\\\"']?/(?!tmp|var/tmp|run|dev/shm|mnt|media)(?:/|\\b)",
17
17
  "risk_level": "medium",
18
18
  "risk_type": "script_execution",
19
19
  "reason": "检测到递归删除操作 (rm -r /...)"
20
20
  },
21
21
  {
22
- "pattern": "\\brm\\s+-[a-zA-Z]*f[a-zA-Z]*\\s+/(?!tmp/|var/tmp/|run/|dev/shm/)",
22
+ "pattern": "\\brm[ \\t]+-[a-zA-Z]*f[a-zA-Z]*(?:[ \\t]+(?:-[a-zA-Z]+|--[\\w=-]*))*[ \\t]+[\\\"']?/(?!tmp/|var/tmp/|run/|dev/shm/)",
23
23
  "risk_level": "medium",
24
24
  "risk_type": "script_execution",
25
25
  "reason": "检测到强制删除文件 (rm -f /...)"
26
26
  },
27
+ {
28
+ "pattern": "\\brm(?:[ \\t]+(?:-[a-zA-Z]+|--[\\w=-]*))*[ \\t]+[\\\"']?/(?=$|[\\s\\\"'*?;|&]|\\.)",
29
+ "risk_level": "critical",
30
+ "risk_type": "script_execution",
31
+ "reason": "检测到删除根目录(选项顺序/引号/隐藏路径均不能绕过)"
32
+ },
27
33
  {
28
34
  "pattern": "\\bln\\s+(-[a-zA-Z]+\\s+)*(?:--\\s+)?-s[a-zA-Z]*\\s+(?:--\\s+)?(/(?![a-zA-Z0-9._~])|~/\\.\\.(?:\\s|$|\\\"|'|;|&|\\)|\\]|/)|~/(?![.a-zA-Z0-9_~-])|~/$|~(?:\\s|$|\\\"|'|;|&|\\)|\\])|\\$HOME/\\.\\.(?:\\s|$|\\\"|'|;|&|\\)|\\]|/)|\\$HOME/(?![.a-zA-Z0-9_~-])|\\$HOME/$|\\$HOME(?:\\s|$|\\\"|'|;|&|\\)|\\]))",
29
35
  "risk_level": "high",