@kenhkl/agent-moss 0.17.25 → 0.17.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2267,7 +2267,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2267
2267
  if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
2268
2268
  if (NON_WRITE_TOOLS.has(actionType)) return null;
2269
2269
  const isBashLike = actionType === "bash" || actionType === "executebash" || actionType === "terminal-executebash";
2270
- const isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
2270
+ let isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
2271
+ if (!isWrite && /\btar\b/.test(actionDetail) && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(actionDetail)) {
2272
+ isWrite = true;
2273
+ }
2271
2274
  if (!isWrite) return null;
2272
2275
  const WRITE_CMDS = new Set(_LOGIC.write_commands ?? []);
2273
2276
  if (isBashLike) {
@@ -2289,6 +2292,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2289
2292
  hasWriteSeg = true;
2290
2293
  break;
2291
2294
  }
2295
+ if (fw === "tar" && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed) && /(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)\S+/.test(trimmed)) {
2296
+ hasWriteSeg = true;
2297
+ break;
2298
+ }
2292
2299
  if ((fw === "wget" || fw === "curl") && (/\s(?:-O|--output-document|--output)(?:=|\s|$)/i.test(trimmed) || /\s-O\S/.test(trimmed))) {
2293
2300
  hasWriteSeg = true;
2294
2301
  break;
@@ -2328,6 +2335,11 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2328
2335
  const segPathsFiltered = firstWord === "wget" || firstWord === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
2329
2336
  if (SOURCE_ARG_CMDS.has(firstWord)) {
2330
2337
  if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
2338
+ } else if (firstWord === "tar") {
2339
+ if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
2340
+ const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
2341
+ if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
2342
+ }
2331
2343
  } else if (firstWord === "dd") {
2332
2344
  const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
2333
2345
  const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
@@ -3795,7 +3807,9 @@ function getEnabledL2IntentPatterns(runtime, osType) {
3795
3807
  return rules.map((r) => ({
3796
3808
  intent_keywords: r.intent_keywords || [],
3797
3809
  dangerous_actions: r.dangerous_actions || [],
3798
- reason: r.reason || ""
3810
+ reason: r.reason || "",
3811
+ allow_if_write_intent: r.allow_if_write_intent === true,
3812
+ os: r.os
3799
3813
  }));
3800
3814
  }
3801
3815
  function getEnabledL2PasswordPatterns(runtime) {
@@ -4866,6 +4880,256 @@ var init_scenarios = __esm({
4866
4880
  }
4867
4881
  });
4868
4882
 
4883
+ // src/engine/written-content-analyzer.ts
4884
+ function isFileWriteAction(actionType) {
4885
+ const at = (actionType || "").toLowerCase();
4886
+ if (WRITE_TOOL_EXACT.has(at)) return true;
4887
+ if (WRITE_TOOL_SUFFIXES.some((s) => at.endsWith(s))) return true;
4888
+ return false;
4889
+ }
4890
+ function isApplyPatch(actionType) {
4891
+ const at = (actionType || "").toLowerCase();
4892
+ return APPLY_PATCH_SUFFIXES.some((s) => at.endsWith(s));
4893
+ }
4894
+ function extractWritePayload(actionType, actionDetailRaw) {
4895
+ if (isApplyPatch(actionType)) return null;
4896
+ const detail = actionDetailRaw || "";
4897
+ const m = detail.match(WRITE_PREFIX_RE);
4898
+ if (m) {
4899
+ const path8 = m[1];
4900
+ let content = m[2] || "";
4901
+ if (!path8 || path8 === "?" || path8 === "-" || !content.trim()) return null;
4902
+ if ((actionType || "").toLowerCase().includes("editfile")) {
4903
+ const nm = content.match(EDIT_NEW_RE);
4904
+ if (nm) content = nm[1];
4905
+ }
4906
+ return { path: path8, content };
4907
+ }
4908
+ const stripped = detail.trim();
4909
+ if (stripped.startsWith("{")) {
4910
+ try {
4911
+ const obj = JSON.parse(stripped);
4912
+ if (obj && typeof obj === "object") {
4913
+ const path8 = obj.path || obj.file_path || obj.filePath;
4914
+ const content = obj.content || obj.newString || obj.new_string;
4915
+ if (typeof path8 === "string" && path8 !== "" && path8 !== "?" && path8 !== "-" && typeof content === "string" && content.trim()) {
4916
+ return { path: path8, content };
4917
+ }
4918
+ }
4919
+ } catch {
4920
+ }
4921
+ }
4922
+ return null;
4923
+ }
4924
+ function handlesWrittenContent(actionType, actionDetailRaw) {
4925
+ if (!isFileWriteAction(actionType)) return false;
4926
+ if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
4927
+ return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
4928
+ }
4929
+ function detectLanguage(path8, content) {
4930
+ const ext = path8.slice(path8.lastIndexOf(".") >= 0 ? path8.lastIndexOf(".") : path8.length).toLowerCase();
4931
+ if (SHELL_EXTS.has(ext)) return "shell";
4932
+ if (PY_EXTS.has(ext)) return "python";
4933
+ if (DATA_EXTS.has(ext)) return "data";
4934
+ if (!ext) {
4935
+ const first = content.trim() ? content.trim().split(/\r?\n/)[0] : "";
4936
+ if (first.startsWith("#!")) {
4937
+ if (/\b(?:ba|z|k|da)?sh\b/.test(first)) return "shell";
4938
+ if (first.includes("python")) return "python";
4939
+ }
4940
+ return "data";
4941
+ }
4942
+ return "other";
4943
+ }
4944
+ function stripShellComments(text) {
4945
+ const out = [];
4946
+ for (const line of text.split(/\r?\n/)) {
4947
+ const res = [];
4948
+ let quote = null;
4949
+ for (let i = 0; i < line.length; i++) {
4950
+ const ch = line[i];
4951
+ if (quote) {
4952
+ res.push(ch);
4953
+ if (ch === quote) quote = null;
4954
+ continue;
4955
+ }
4956
+ if (ch === "'" || ch === '"') {
4957
+ quote = ch;
4958
+ res.push(ch);
4959
+ continue;
4960
+ }
4961
+ if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) break;
4962
+ res.push(ch);
4963
+ }
4964
+ out.push(res.join(""));
4965
+ }
4966
+ return out.join("\n");
4967
+ }
4968
+ function stripShellDocsOnly(content) {
4969
+ if (!content) return content;
4970
+ if (INTERP_HEREDOC_RE.test(content)) return content;
4971
+ const withoutHeredoc = content.replace(QUOTED_HEREDOC_RE, "<<quoted-heredoc>>\n");
4972
+ return stripShellComments(withoutHeredoc);
4973
+ }
4974
+ function lineSnippets(content, precheck) {
4975
+ const lines = content.split(/\r?\n/);
4976
+ const picked = /* @__PURE__ */ new Set();
4977
+ for (let i = 0; i < lines.length; i++) {
4978
+ precheck.lastIndex = 0;
4979
+ if (precheck.test(lines[i])) {
4980
+ picked.add(i - 1);
4981
+ picked.add(i);
4982
+ picked.add(i + 1);
4983
+ }
4984
+ }
4985
+ const snippets = [];
4986
+ let total = 0;
4987
+ for (const i of [...picked].sort((a, b) => a - b)) {
4988
+ if (i < 0 || i >= lines.length) continue;
4989
+ const s = lines[i];
4990
+ if (total + s.length > MAX_SCAN) break;
4991
+ snippets.push(s);
4992
+ total += s.length + 1;
4993
+ }
4994
+ return snippets;
4995
+ }
4996
+ function stripPythonLiterals(content) {
4997
+ const chars = content.split("");
4998
+ let i = 0;
4999
+ const n = chars.length;
5000
+ while (i < n) {
5001
+ const ch = chars[i];
5002
+ if (ch === "#") {
5003
+ while (i < n && chars[i] !== "\n") {
5004
+ chars[i] = " ";
5005
+ i++;
5006
+ }
5007
+ continue;
5008
+ }
5009
+ if (ch === "'" || ch === '"') {
5010
+ const triple = chars[i + 1] === ch && chars[i + 2] === ch;
5011
+ const quoteLen = triple ? 3 : 1;
5012
+ const q = ch;
5013
+ i += quoteLen;
5014
+ while (i < n) {
5015
+ if (chars[i] === "\\") {
5016
+ chars[i] = " ";
5017
+ if (i + 1 < n) chars[i + 1] = " ";
5018
+ i += 2;
5019
+ continue;
5020
+ }
5021
+ if (chars[i] === q && (!triple || chars[i + 1] === q && chars[i + 2] === q)) {
5022
+ for (let k = 0; k < quoteLen; k++) {
5023
+ chars[i + k] = " ";
5024
+ }
5025
+ i += quoteLen;
5026
+ break;
5027
+ }
5028
+ chars[i] = " ";
5029
+ i++;
5030
+ }
5031
+ continue;
5032
+ }
5033
+ i++;
5034
+ }
5035
+ return chars.join("");
5036
+ }
5037
+ function balancedArgs(original, openIndex) {
5038
+ let depth = 0;
5039
+ let quote = null;
5040
+ for (let i = openIndex; i < original.length && i < openIndex + 8e3; i++) {
5041
+ const ch = original[i];
5042
+ if (quote) {
5043
+ if (ch === "\\") {
5044
+ i++;
5045
+ continue;
5046
+ }
5047
+ if (ch === quote) quote = null;
5048
+ continue;
5049
+ }
5050
+ if (ch === "'" || ch === '"') {
5051
+ quote = ch;
5052
+ continue;
5053
+ }
5054
+ if (ch === "(") depth++;
5055
+ else if (ch === ")") {
5056
+ depth--;
5057
+ if (depth === 0) return original.slice(openIndex + 1, i);
5058
+ }
5059
+ }
5060
+ return original.slice(openIndex + 1, Math.min(original.length, openIndex + 2e3));
5061
+ }
5062
+ function pythonSnippets(content) {
5063
+ const stripped = stripPythonLiterals(content);
5064
+ const snippets = [];
5065
+ PY_DANGEROUS_CALL_RE.lastIndex = 0;
5066
+ let m;
5067
+ while ((m = PY_DANGEROUS_CALL_RE.exec(stripped)) !== null) {
5068
+ const callName = m[0].replace(/\s*\($/, "").trim();
5069
+ const openIndex = m.index + m[0].length - 1;
5070
+ const args = balancedArgs(content, openIndex);
5071
+ snippets.push(`${callName}(${args})`);
5072
+ if (snippets.length >= 200) break;
5073
+ }
5074
+ return snippets;
5075
+ }
5076
+ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper) {
5077
+ if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
5078
+ const payload = extractWritePayload(actionType, actionDetailRaw);
5079
+ if (!payload) return [];
5080
+ const { path: path8, content: rawContent } = payload;
5081
+ const language = detectLanguage(path8, rawContent);
5082
+ if (language === "data") return [];
5083
+ let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
5084
+ const started = Date.now();
5085
+ if (language === "python") {
5086
+ if (!PY_PRECHECK.test(content)) return [];
5087
+ return pythonSnippets(content);
5088
+ }
5089
+ content = stripShellDocsOnly(content);
5090
+ if (literalStripper) content = literalStripper(content);
5091
+ if (!SHELL_PRECHECK.test(content)) return [];
5092
+ const snippets = lineSnippets(content, SHELL_PRECHECK);
5093
+ if (Date.now() - started > MAX_MS) {
5094
+ return snippets;
5095
+ }
5096
+ return snippets;
5097
+ }
5098
+ 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;
5099
+ var init_written_content_analyzer = __esm({
5100
+ "src/engine/written-content-analyzer.ts"() {
5101
+ "use strict";
5102
+ init_esm_shims();
5103
+ init_rules_loader();
5104
+ CFG = loadHeuristicRules().write_content_analysis || {};
5105
+ DATA_EXTS = new Set((CFG.data_exts || []).map((e) => e.toLowerCase()));
5106
+ SHELL_EXTS = new Set((CFG.shell_exts || []).map((e) => e.toLowerCase()));
5107
+ PY_EXTS = new Set((CFG.python_exts || []).map((e) => e.toLowerCase()));
5108
+ SHELL_PRECHECK = new RegExp(CFG.shell_precheck || "$^");
5109
+ PY_PRECHECK = new RegExp(CFG.python_precheck || "$^");
5110
+ MAX_CONTENT = Number(CFG.max_content_bytes || 262144);
5111
+ MAX_SCAN = Number(CFG.max_scan_bytes || 65536);
5112
+ MAX_MS = Number(CFG.max_scan_ms || 100);
5113
+ WRITE_TOOL_EXACT = /* @__PURE__ */ new Set([
5114
+ "write",
5115
+ "file_write",
5116
+ "writefile",
5117
+ "edit",
5118
+ "file_edit",
5119
+ "editfile",
5120
+ "searchreplace",
5121
+ "search_replace"
5122
+ ]);
5123
+ WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
5124
+ APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
5125
+ WRITE_PREFIX_RE = /^(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*(.+?)\s*(?:\(\s*追加\s*\))?\s*—\s*([\s\S]*)$/;
5126
+ EDIT_NEW_RE = /\|\s*new:\s*([\s\S]*)$/i;
5127
+ INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
5128
+ QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
5129
+ 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;
5130
+ }
5131
+ });
5132
+
4869
5133
  // src/engine/heuristic.ts
4870
5134
  function _effectiveDangerousPatterns(osType) {
4871
5135
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
@@ -4973,8 +5237,16 @@ function runHeuristicCheck(input) {
4973
5237
  } catch {
4974
5238
  }
4975
5239
  }
4976
- const scanDetail = normalizePathSegments(stripLiteralTextSegments(input.aNext.actionDetail));
4977
- const scanCommands = String(input.osType || "").toLowerCase() === "windows" ? [
5240
+ const scanDetail = normalizePathSegments(
5241
+ stripLiteralTextSegments(stripShellDocsOnly(input.aNext.actionDetail))
5242
+ );
5243
+ const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
5244
+ const writeSnippets = extractDangerousSnippets(
5245
+ input.aNext.actionType,
5246
+ input.aNext.actionDetail,
5247
+ stripLiteralTextSegments
5248
+ );
5249
+ const scanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => [`${input.aNext.actionType}: ${sn}`, sn]) : String(input.osType || "").toLowerCase() === "windows" ? [
4978
5250
  `${input.aNext.actionType}: ${scanDetail}`,
4979
5251
  scanDetail,
4980
5252
  `${input.aNext.actionType}: ${scanDetail.replace(/\//g, "\\")}`,
@@ -5035,9 +5307,9 @@ function runHeuristicCheck(input) {
5035
5307
  const actionTypeL = input.aNext.actionType.toLowerCase();
5036
5308
  const detailL = input.aNext.actionDetail.toLowerCase();
5037
5309
  const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
5038
- const dangerousResult = checkDangerousPatterns(actionTypeL, detailL);
5310
+ const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
5039
5311
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
5040
- const homeResult = checkHomeDeletion(actionTypeL, detailL);
5312
+ const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
5041
5313
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
5042
5314
  if (mergeResults.length > 0) {
5043
5315
  let best = mergeResults[0];
@@ -5535,7 +5807,7 @@ function isSshKeygenGenerate(command) {
5535
5807
  }
5536
5808
  function checkDangerousPatterns(actionType, actionDetail) {
5537
5809
  if (actionType === "file_write" || actionType === "file_edit") return null;
5538
- const scan = stripHeredocContent(actionDetail);
5810
+ const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
5539
5811
  const isTempPath = TEMP_DIRS2.some(
5540
5812
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
5541
5813
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
@@ -5693,6 +5965,7 @@ var init_heuristic = __esm({
5693
5965
  init_runtime_config();
5694
5966
  init_runtime_config_bridge();
5695
5967
  init_rules_loader();
5968
+ init_written_content_analyzer();
5696
5969
  init_logic_rules();
5697
5970
  INJECTION_KEYWORDS = (() => {
5698
5971
  const kws = loadL1().injection_detection || [];
@@ -1436,7 +1436,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1436
1436
  if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
1437
1437
  if (NON_WRITE_TOOLS.has(actionType)) return null;
1438
1438
  const isBashLike = actionType === "bash" || actionType === "executebash" || actionType === "terminal-executebash";
1439
- const isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
1439
+ let isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
1440
+ if (!isWrite && /\btar\b/.test(actionDetail) && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(actionDetail)) {
1441
+ isWrite = true;
1442
+ }
1440
1443
  if (!isWrite) return null;
1441
1444
  const WRITE_CMDS = new Set(_LOGIC.write_commands ?? []);
1442
1445
  if (isBashLike) {
@@ -1458,6 +1461,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1458
1461
  hasWriteSeg = true;
1459
1462
  break;
1460
1463
  }
1464
+ if (fw === "tar" && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed) && /(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)\S+/.test(trimmed)) {
1465
+ hasWriteSeg = true;
1466
+ break;
1467
+ }
1461
1468
  if ((fw === "wget" || fw === "curl") && (/\s(?:-O|--output-document|--output)(?:=|\s|$)/i.test(trimmed) || /\s-O\S/.test(trimmed))) {
1462
1469
  hasWriteSeg = true;
1463
1470
  break;
@@ -1497,6 +1504,11 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1497
1504
  const segPathsFiltered = firstWord === "wget" || firstWord === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
1498
1505
  if (SOURCE_ARG_CMDS.has(firstWord)) {
1499
1506
  if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
1507
+ } else if (firstWord === "tar") {
1508
+ if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
1509
+ const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
1510
+ if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
1511
+ }
1500
1512
  } else if (firstWord === "dd") {
1501
1513
  const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
1502
1514
  const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
@@ -2964,7 +2976,9 @@ function getEnabledL2IntentPatterns(runtime, osType) {
2964
2976
  return rules.map((r) => ({
2965
2977
  intent_keywords: r.intent_keywords || [],
2966
2978
  dangerous_actions: r.dangerous_actions || [],
2967
- reason: r.reason || ""
2979
+ reason: r.reason || "",
2980
+ allow_if_write_intent: r.allow_if_write_intent === true,
2981
+ os: r.os
2968
2982
  }));
2969
2983
  }
2970
2984
  function getEnabledL2PasswordPatterns(runtime) {
@@ -4035,6 +4049,256 @@ var init_scenarios = __esm({
4035
4049
  }
4036
4050
  });
4037
4051
 
4052
+ // src/engine/written-content-analyzer.ts
4053
+ function isFileWriteAction(actionType) {
4054
+ const at = (actionType || "").toLowerCase();
4055
+ if (WRITE_TOOL_EXACT.has(at)) return true;
4056
+ if (WRITE_TOOL_SUFFIXES.some((s) => at.endsWith(s))) return true;
4057
+ return false;
4058
+ }
4059
+ function isApplyPatch(actionType) {
4060
+ const at = (actionType || "").toLowerCase();
4061
+ return APPLY_PATCH_SUFFIXES.some((s) => at.endsWith(s));
4062
+ }
4063
+ function extractWritePayload(actionType, actionDetailRaw) {
4064
+ if (isApplyPatch(actionType)) return null;
4065
+ const detail = actionDetailRaw || "";
4066
+ const m = detail.match(WRITE_PREFIX_RE);
4067
+ if (m) {
4068
+ const path7 = m[1];
4069
+ let content = m[2] || "";
4070
+ if (!path7 || path7 === "?" || path7 === "-" || !content.trim()) return null;
4071
+ if ((actionType || "").toLowerCase().includes("editfile")) {
4072
+ const nm = content.match(EDIT_NEW_RE);
4073
+ if (nm) content = nm[1];
4074
+ }
4075
+ return { path: path7, content };
4076
+ }
4077
+ const stripped = detail.trim();
4078
+ if (stripped.startsWith("{")) {
4079
+ try {
4080
+ const obj = JSON.parse(stripped);
4081
+ if (obj && typeof obj === "object") {
4082
+ const path7 = obj.path || obj.file_path || obj.filePath;
4083
+ const content = obj.content || obj.newString || obj.new_string;
4084
+ if (typeof path7 === "string" && path7 !== "" && path7 !== "?" && path7 !== "-" && typeof content === "string" && content.trim()) {
4085
+ return { path: path7, content };
4086
+ }
4087
+ }
4088
+ } catch {
4089
+ }
4090
+ }
4091
+ return null;
4092
+ }
4093
+ function handlesWrittenContent(actionType, actionDetailRaw) {
4094
+ if (!isFileWriteAction(actionType)) return false;
4095
+ if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
4096
+ return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
4097
+ }
4098
+ function detectLanguage(path7, content) {
4099
+ const ext = path7.slice(path7.lastIndexOf(".") >= 0 ? path7.lastIndexOf(".") : path7.length).toLowerCase();
4100
+ if (SHELL_EXTS.has(ext)) return "shell";
4101
+ if (PY_EXTS.has(ext)) return "python";
4102
+ if (DATA_EXTS.has(ext)) return "data";
4103
+ if (!ext) {
4104
+ const first = content.trim() ? content.trim().split(/\r?\n/)[0] : "";
4105
+ if (first.startsWith("#!")) {
4106
+ if (/\b(?:ba|z|k|da)?sh\b/.test(first)) return "shell";
4107
+ if (first.includes("python")) return "python";
4108
+ }
4109
+ return "data";
4110
+ }
4111
+ return "other";
4112
+ }
4113
+ function stripShellComments(text) {
4114
+ const out = [];
4115
+ for (const line of text.split(/\r?\n/)) {
4116
+ const res = [];
4117
+ let quote = null;
4118
+ for (let i = 0; i < line.length; i++) {
4119
+ const ch = line[i];
4120
+ if (quote) {
4121
+ res.push(ch);
4122
+ if (ch === quote) quote = null;
4123
+ continue;
4124
+ }
4125
+ if (ch === "'" || ch === '"') {
4126
+ quote = ch;
4127
+ res.push(ch);
4128
+ continue;
4129
+ }
4130
+ if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) break;
4131
+ res.push(ch);
4132
+ }
4133
+ out.push(res.join(""));
4134
+ }
4135
+ return out.join("\n");
4136
+ }
4137
+ function stripShellDocsOnly(content) {
4138
+ if (!content) return content;
4139
+ if (INTERP_HEREDOC_RE.test(content)) return content;
4140
+ const withoutHeredoc = content.replace(QUOTED_HEREDOC_RE, "<<quoted-heredoc>>\n");
4141
+ return stripShellComments(withoutHeredoc);
4142
+ }
4143
+ function lineSnippets(content, precheck) {
4144
+ const lines = content.split(/\r?\n/);
4145
+ const picked = /* @__PURE__ */ new Set();
4146
+ for (let i = 0; i < lines.length; i++) {
4147
+ precheck.lastIndex = 0;
4148
+ if (precheck.test(lines[i])) {
4149
+ picked.add(i - 1);
4150
+ picked.add(i);
4151
+ picked.add(i + 1);
4152
+ }
4153
+ }
4154
+ const snippets = [];
4155
+ let total = 0;
4156
+ for (const i of [...picked].sort((a, b) => a - b)) {
4157
+ if (i < 0 || i >= lines.length) continue;
4158
+ const s = lines[i];
4159
+ if (total + s.length > MAX_SCAN) break;
4160
+ snippets.push(s);
4161
+ total += s.length + 1;
4162
+ }
4163
+ return snippets;
4164
+ }
4165
+ function stripPythonLiterals(content) {
4166
+ const chars = content.split("");
4167
+ let i = 0;
4168
+ const n = chars.length;
4169
+ while (i < n) {
4170
+ const ch = chars[i];
4171
+ if (ch === "#") {
4172
+ while (i < n && chars[i] !== "\n") {
4173
+ chars[i] = " ";
4174
+ i++;
4175
+ }
4176
+ continue;
4177
+ }
4178
+ if (ch === "'" || ch === '"') {
4179
+ const triple = chars[i + 1] === ch && chars[i + 2] === ch;
4180
+ const quoteLen = triple ? 3 : 1;
4181
+ const q = ch;
4182
+ i += quoteLen;
4183
+ while (i < n) {
4184
+ if (chars[i] === "\\") {
4185
+ chars[i] = " ";
4186
+ if (i + 1 < n) chars[i + 1] = " ";
4187
+ i += 2;
4188
+ continue;
4189
+ }
4190
+ if (chars[i] === q && (!triple || chars[i + 1] === q && chars[i + 2] === q)) {
4191
+ for (let k = 0; k < quoteLen; k++) {
4192
+ chars[i + k] = " ";
4193
+ }
4194
+ i += quoteLen;
4195
+ break;
4196
+ }
4197
+ chars[i] = " ";
4198
+ i++;
4199
+ }
4200
+ continue;
4201
+ }
4202
+ i++;
4203
+ }
4204
+ return chars.join("");
4205
+ }
4206
+ function balancedArgs(original, openIndex) {
4207
+ let depth = 0;
4208
+ let quote = null;
4209
+ for (let i = openIndex; i < original.length && i < openIndex + 8e3; i++) {
4210
+ const ch = original[i];
4211
+ if (quote) {
4212
+ if (ch === "\\") {
4213
+ i++;
4214
+ continue;
4215
+ }
4216
+ if (ch === quote) quote = null;
4217
+ continue;
4218
+ }
4219
+ if (ch === "'" || ch === '"') {
4220
+ quote = ch;
4221
+ continue;
4222
+ }
4223
+ if (ch === "(") depth++;
4224
+ else if (ch === ")") {
4225
+ depth--;
4226
+ if (depth === 0) return original.slice(openIndex + 1, i);
4227
+ }
4228
+ }
4229
+ return original.slice(openIndex + 1, Math.min(original.length, openIndex + 2e3));
4230
+ }
4231
+ function pythonSnippets(content) {
4232
+ const stripped = stripPythonLiterals(content);
4233
+ const snippets = [];
4234
+ PY_DANGEROUS_CALL_RE.lastIndex = 0;
4235
+ let m;
4236
+ while ((m = PY_DANGEROUS_CALL_RE.exec(stripped)) !== null) {
4237
+ const callName = m[0].replace(/\s*\($/, "").trim();
4238
+ const openIndex = m.index + m[0].length - 1;
4239
+ const args = balancedArgs(content, openIndex);
4240
+ snippets.push(`${callName}(${args})`);
4241
+ if (snippets.length >= 200) break;
4242
+ }
4243
+ return snippets;
4244
+ }
4245
+ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper) {
4246
+ if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
4247
+ const payload = extractWritePayload(actionType, actionDetailRaw);
4248
+ if (!payload) return [];
4249
+ const { path: path7, content: rawContent } = payload;
4250
+ const language = detectLanguage(path7, rawContent);
4251
+ if (language === "data") return [];
4252
+ let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
4253
+ const started = Date.now();
4254
+ if (language === "python") {
4255
+ if (!PY_PRECHECK.test(content)) return [];
4256
+ return pythonSnippets(content);
4257
+ }
4258
+ content = stripShellDocsOnly(content);
4259
+ if (literalStripper) content = literalStripper(content);
4260
+ if (!SHELL_PRECHECK.test(content)) return [];
4261
+ const snippets = lineSnippets(content, SHELL_PRECHECK);
4262
+ if (Date.now() - started > MAX_MS) {
4263
+ return snippets;
4264
+ }
4265
+ return snippets;
4266
+ }
4267
+ 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;
4268
+ var init_written_content_analyzer = __esm({
4269
+ "src/engine/written-content-analyzer.ts"() {
4270
+ "use strict";
4271
+ init_esm_shims();
4272
+ init_rules_loader();
4273
+ CFG = loadHeuristicRules().write_content_analysis || {};
4274
+ DATA_EXTS = new Set((CFG.data_exts || []).map((e) => e.toLowerCase()));
4275
+ SHELL_EXTS = new Set((CFG.shell_exts || []).map((e) => e.toLowerCase()));
4276
+ PY_EXTS = new Set((CFG.python_exts || []).map((e) => e.toLowerCase()));
4277
+ SHELL_PRECHECK = new RegExp(CFG.shell_precheck || "$^");
4278
+ PY_PRECHECK = new RegExp(CFG.python_precheck || "$^");
4279
+ MAX_CONTENT = Number(CFG.max_content_bytes || 262144);
4280
+ MAX_SCAN = Number(CFG.max_scan_bytes || 65536);
4281
+ MAX_MS = Number(CFG.max_scan_ms || 100);
4282
+ WRITE_TOOL_EXACT = /* @__PURE__ */ new Set([
4283
+ "write",
4284
+ "file_write",
4285
+ "writefile",
4286
+ "edit",
4287
+ "file_edit",
4288
+ "editfile",
4289
+ "searchreplace",
4290
+ "search_replace"
4291
+ ]);
4292
+ WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
4293
+ APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
4294
+ WRITE_PREFIX_RE = /^(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*(.+?)\s*(?:\(\s*追加\s*\))?\s*—\s*([\s\S]*)$/;
4295
+ EDIT_NEW_RE = /\|\s*new:\s*([\s\S]*)$/i;
4296
+ INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
4297
+ QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
4298
+ 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;
4299
+ }
4300
+ });
4301
+
4038
4302
  // src/engine/heuristic.ts
4039
4303
  function _effectiveDangerousPatterns(osType) {
4040
4304
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
@@ -4142,8 +4406,16 @@ function runHeuristicCheck(input) {
4142
4406
  } catch {
4143
4407
  }
4144
4408
  }
4145
- const scanDetail = normalizePathSegments(stripLiteralTextSegments(input.aNext.actionDetail));
4146
- const scanCommands = String(input.osType || "").toLowerCase() === "windows" ? [
4409
+ const scanDetail = normalizePathSegments(
4410
+ stripLiteralTextSegments(stripShellDocsOnly(input.aNext.actionDetail))
4411
+ );
4412
+ const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
4413
+ const writeSnippets = extractDangerousSnippets(
4414
+ input.aNext.actionType,
4415
+ input.aNext.actionDetail,
4416
+ stripLiteralTextSegments
4417
+ );
4418
+ const scanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => [`${input.aNext.actionType}: ${sn}`, sn]) : String(input.osType || "").toLowerCase() === "windows" ? [
4147
4419
  `${input.aNext.actionType}: ${scanDetail}`,
4148
4420
  scanDetail,
4149
4421
  `${input.aNext.actionType}: ${scanDetail.replace(/\//g, "\\")}`,
@@ -4204,9 +4476,9 @@ function runHeuristicCheck(input) {
4204
4476
  const actionTypeL = input.aNext.actionType.toLowerCase();
4205
4477
  const detailL = input.aNext.actionDetail.toLowerCase();
4206
4478
  const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
4207
- const dangerousResult = checkDangerousPatterns(actionTypeL, detailL);
4479
+ const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
4208
4480
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
4209
- const homeResult = checkHomeDeletion(actionTypeL, detailL);
4481
+ const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
4210
4482
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
4211
4483
  if (mergeResults.length > 0) {
4212
4484
  let best = mergeResults[0];
@@ -4704,7 +4976,7 @@ function isSshKeygenGenerate(command) {
4704
4976
  }
4705
4977
  function checkDangerousPatterns(actionType, actionDetail) {
4706
4978
  if (actionType === "file_write" || actionType === "file_edit") return null;
4707
- const scan = stripHeredocContent(actionDetail);
4979
+ const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
4708
4980
  const isTempPath = TEMP_DIRS2.some(
4709
4981
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
4710
4982
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
@@ -4862,6 +5134,7 @@ var init_heuristic = __esm({
4862
5134
  init_runtime_config();
4863
5135
  init_runtime_config_bridge();
4864
5136
  init_rules_loader();
5137
+ init_written_content_analyzer();
4865
5138
  init_logic_rules();
4866
5139
  INJECTION_KEYWORDS = (() => {
4867
5140
  const kws = loadL1().injection_detection || [];
@@ -36,5 +36,48 @@
36
36
  "/run",
37
37
  "/dev/shm"
38
38
  ],
39
- "_temp_dirs_comment": "临时目录(批量删除豁免)。L1 的 _check_dangerous_patterns 与 L2 的 read_before_write 共用这一份;调用方按需拼尾随斜杠做 startswith。"
39
+ "_temp_dirs_comment": "临时目录(批量删除豁免)。L1 的 _check_dangerous_patterns 与 L2 的 read_before_write 共用这一份;调用方按需拼尾随斜杠做 startswith。",
40
+ "write_content_analysis": {
41
+ "_comment": "写入内容的按语言静态分析(writeFile/editFile)。文档/数据不做命令执行检测;shell/python 按语言解析后只扫危险片段;预筛 + 片段/大小/时间预算控制性能。",
42
+ "data_exts": [
43
+ ".md",
44
+ ".markdown",
45
+ ".txt",
46
+ ".rst",
47
+ ".html",
48
+ ".htm",
49
+ ".json",
50
+ ".jsonl",
51
+ ".yaml",
52
+ ".yml",
53
+ ".xml",
54
+ ".csv",
55
+ ".tsv",
56
+ ".css",
57
+ ".scss",
58
+ ".ini",
59
+ ".conf",
60
+ ".cfg",
61
+ ".log",
62
+ ".toml",
63
+ ".properties",
64
+ ".sql"
65
+ ],
66
+ "shell_exts": [
67
+ ".sh",
68
+ ".bash",
69
+ ".zsh",
70
+ ".ksh",
71
+ ".dash"
72
+ ],
73
+ "python_exts": [
74
+ ".py",
75
+ ".pyw"
76
+ ],
77
+ "shell_precheck": "\\$\\(|`|\\b(?:rm|rmdir|unlink|shred|curl|wget|nc|ncat|socat|chmod|chown|dd|tee|truncate|mkfs|fdisk|parted|bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua|eval|exec|base64|sudo|su)\\b",
78
+ "python_precheck": "os\\.(?:system|popen|remove|unlink|rmdir|chmod|chown|kill)|subprocess|pty\\.|ctypes|eval\\s*\\(|exec\\s*\\(|__import__|compile\\s*\\(|open\\s*\\(|shutil\\.(?:rmtree|move|copy)|socket|urllib|requests\\.",
79
+ "max_content_bytes": 262144,
80
+ "max_scan_bytes": 65536,
81
+ "max_scan_ms": 100
82
+ }
40
83
  }
package/dist/server.js CHANGED
@@ -1967,7 +1967,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1967
1967
  if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
1968
1968
  if (NON_WRITE_TOOLS.has(actionType)) return null;
1969
1969
  const isBashLike = actionType === "bash" || actionType === "executebash" || actionType === "terminal-executebash";
1970
- const isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
1970
+ let isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
1971
+ if (!isWrite && /\btar\b/.test(actionDetail) && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(actionDetail)) {
1972
+ isWrite = true;
1973
+ }
1971
1974
  if (!isWrite) return null;
1972
1975
  const WRITE_CMDS = new Set(_LOGIC.write_commands ?? []);
1973
1976
  if (isBashLike) {
@@ -1989,6 +1992,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1989
1992
  hasWriteSeg = true;
1990
1993
  break;
1991
1994
  }
1995
+ if (fw === "tar" && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed) && /(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)\S+/.test(trimmed)) {
1996
+ hasWriteSeg = true;
1997
+ break;
1998
+ }
1992
1999
  if ((fw === "wget" || fw === "curl") && (/\s(?:-O|--output-document|--output)(?:=|\s|$)/i.test(trimmed) || /\s-O\S/.test(trimmed))) {
1993
2000
  hasWriteSeg = true;
1994
2001
  break;
@@ -2028,6 +2035,11 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2028
2035
  const segPathsFiltered = firstWord === "wget" || firstWord === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
2029
2036
  if (SOURCE_ARG_CMDS.has(firstWord)) {
2030
2037
  if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
2038
+ } else if (firstWord === "tar") {
2039
+ if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
2040
+ const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
2041
+ if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
2042
+ }
2031
2043
  } else if (firstWord === "dd") {
2032
2044
  const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
2033
2045
  const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
@@ -3495,7 +3507,9 @@ function getEnabledL2IntentPatterns(runtime, osType) {
3495
3507
  return rules.map((r) => ({
3496
3508
  intent_keywords: r.intent_keywords || [],
3497
3509
  dangerous_actions: r.dangerous_actions || [],
3498
- reason: r.reason || ""
3510
+ reason: r.reason || "",
3511
+ allow_if_write_intent: r.allow_if_write_intent === true,
3512
+ os: r.os
3499
3513
  }));
3500
3514
  }
3501
3515
  function getEnabledL2PasswordPatterns(runtime) {
@@ -4566,6 +4580,256 @@ var init_scenarios = __esm({
4566
4580
  }
4567
4581
  });
4568
4582
 
4583
+ // src/engine/written-content-analyzer.ts
4584
+ function isFileWriteAction(actionType) {
4585
+ const at = (actionType || "").toLowerCase();
4586
+ if (WRITE_TOOL_EXACT.has(at)) return true;
4587
+ if (WRITE_TOOL_SUFFIXES.some((s) => at.endsWith(s))) return true;
4588
+ return false;
4589
+ }
4590
+ function isApplyPatch(actionType) {
4591
+ const at = (actionType || "").toLowerCase();
4592
+ return APPLY_PATCH_SUFFIXES.some((s) => at.endsWith(s));
4593
+ }
4594
+ function extractWritePayload(actionType, actionDetailRaw) {
4595
+ if (isApplyPatch(actionType)) return null;
4596
+ const detail = actionDetailRaw || "";
4597
+ const m = detail.match(WRITE_PREFIX_RE);
4598
+ if (m) {
4599
+ const path8 = m[1];
4600
+ let content = m[2] || "";
4601
+ if (!path8 || path8 === "?" || path8 === "-" || !content.trim()) return null;
4602
+ if ((actionType || "").toLowerCase().includes("editfile")) {
4603
+ const nm = content.match(EDIT_NEW_RE);
4604
+ if (nm) content = nm[1];
4605
+ }
4606
+ return { path: path8, content };
4607
+ }
4608
+ const stripped = detail.trim();
4609
+ if (stripped.startsWith("{")) {
4610
+ try {
4611
+ const obj = JSON.parse(stripped);
4612
+ if (obj && typeof obj === "object") {
4613
+ const path8 = obj.path || obj.file_path || obj.filePath;
4614
+ const content = obj.content || obj.newString || obj.new_string;
4615
+ if (typeof path8 === "string" && path8 !== "" && path8 !== "?" && path8 !== "-" && typeof content === "string" && content.trim()) {
4616
+ return { path: path8, content };
4617
+ }
4618
+ }
4619
+ } catch {
4620
+ }
4621
+ }
4622
+ return null;
4623
+ }
4624
+ function handlesWrittenContent(actionType, actionDetailRaw) {
4625
+ if (!isFileWriteAction(actionType)) return false;
4626
+ if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
4627
+ return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
4628
+ }
4629
+ function detectLanguage(path8, content) {
4630
+ const ext = path8.slice(path8.lastIndexOf(".") >= 0 ? path8.lastIndexOf(".") : path8.length).toLowerCase();
4631
+ if (SHELL_EXTS.has(ext)) return "shell";
4632
+ if (PY_EXTS.has(ext)) return "python";
4633
+ if (DATA_EXTS.has(ext)) return "data";
4634
+ if (!ext) {
4635
+ const first = content.trim() ? content.trim().split(/\r?\n/)[0] : "";
4636
+ if (first.startsWith("#!")) {
4637
+ if (/\b(?:ba|z|k|da)?sh\b/.test(first)) return "shell";
4638
+ if (first.includes("python")) return "python";
4639
+ }
4640
+ return "data";
4641
+ }
4642
+ return "other";
4643
+ }
4644
+ function stripShellComments(text) {
4645
+ const out = [];
4646
+ for (const line of text.split(/\r?\n/)) {
4647
+ const res = [];
4648
+ let quote = null;
4649
+ for (let i = 0; i < line.length; i++) {
4650
+ const ch = line[i];
4651
+ if (quote) {
4652
+ res.push(ch);
4653
+ if (ch === quote) quote = null;
4654
+ continue;
4655
+ }
4656
+ if (ch === "'" || ch === '"') {
4657
+ quote = ch;
4658
+ res.push(ch);
4659
+ continue;
4660
+ }
4661
+ if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) break;
4662
+ res.push(ch);
4663
+ }
4664
+ out.push(res.join(""));
4665
+ }
4666
+ return out.join("\n");
4667
+ }
4668
+ function stripShellDocsOnly(content) {
4669
+ if (!content) return content;
4670
+ if (INTERP_HEREDOC_RE.test(content)) return content;
4671
+ const withoutHeredoc = content.replace(QUOTED_HEREDOC_RE, "<<quoted-heredoc>>\n");
4672
+ return stripShellComments(withoutHeredoc);
4673
+ }
4674
+ function lineSnippets(content, precheck) {
4675
+ const lines = content.split(/\r?\n/);
4676
+ const picked = /* @__PURE__ */ new Set();
4677
+ for (let i = 0; i < lines.length; i++) {
4678
+ precheck.lastIndex = 0;
4679
+ if (precheck.test(lines[i])) {
4680
+ picked.add(i - 1);
4681
+ picked.add(i);
4682
+ picked.add(i + 1);
4683
+ }
4684
+ }
4685
+ const snippets = [];
4686
+ let total = 0;
4687
+ for (const i of [...picked].sort((a, b) => a - b)) {
4688
+ if (i < 0 || i >= lines.length) continue;
4689
+ const s = lines[i];
4690
+ if (total + s.length > MAX_SCAN) break;
4691
+ snippets.push(s);
4692
+ total += s.length + 1;
4693
+ }
4694
+ return snippets;
4695
+ }
4696
+ function stripPythonLiterals(content) {
4697
+ const chars = content.split("");
4698
+ let i = 0;
4699
+ const n = chars.length;
4700
+ while (i < n) {
4701
+ const ch = chars[i];
4702
+ if (ch === "#") {
4703
+ while (i < n && chars[i] !== "\n") {
4704
+ chars[i] = " ";
4705
+ i++;
4706
+ }
4707
+ continue;
4708
+ }
4709
+ if (ch === "'" || ch === '"') {
4710
+ const triple = chars[i + 1] === ch && chars[i + 2] === ch;
4711
+ const quoteLen = triple ? 3 : 1;
4712
+ const q = ch;
4713
+ i += quoteLen;
4714
+ while (i < n) {
4715
+ if (chars[i] === "\\") {
4716
+ chars[i] = " ";
4717
+ if (i + 1 < n) chars[i + 1] = " ";
4718
+ i += 2;
4719
+ continue;
4720
+ }
4721
+ if (chars[i] === q && (!triple || chars[i + 1] === q && chars[i + 2] === q)) {
4722
+ for (let k = 0; k < quoteLen; k++) {
4723
+ chars[i + k] = " ";
4724
+ }
4725
+ i += quoteLen;
4726
+ break;
4727
+ }
4728
+ chars[i] = " ";
4729
+ i++;
4730
+ }
4731
+ continue;
4732
+ }
4733
+ i++;
4734
+ }
4735
+ return chars.join("");
4736
+ }
4737
+ function balancedArgs(original, openIndex) {
4738
+ let depth = 0;
4739
+ let quote = null;
4740
+ for (let i = openIndex; i < original.length && i < openIndex + 8e3; i++) {
4741
+ const ch = original[i];
4742
+ if (quote) {
4743
+ if (ch === "\\") {
4744
+ i++;
4745
+ continue;
4746
+ }
4747
+ if (ch === quote) quote = null;
4748
+ continue;
4749
+ }
4750
+ if (ch === "'" || ch === '"') {
4751
+ quote = ch;
4752
+ continue;
4753
+ }
4754
+ if (ch === "(") depth++;
4755
+ else if (ch === ")") {
4756
+ depth--;
4757
+ if (depth === 0) return original.slice(openIndex + 1, i);
4758
+ }
4759
+ }
4760
+ return original.slice(openIndex + 1, Math.min(original.length, openIndex + 2e3));
4761
+ }
4762
+ function pythonSnippets(content) {
4763
+ const stripped = stripPythonLiterals(content);
4764
+ const snippets = [];
4765
+ PY_DANGEROUS_CALL_RE.lastIndex = 0;
4766
+ let m;
4767
+ while ((m = PY_DANGEROUS_CALL_RE.exec(stripped)) !== null) {
4768
+ const callName = m[0].replace(/\s*\($/, "").trim();
4769
+ const openIndex = m.index + m[0].length - 1;
4770
+ const args = balancedArgs(content, openIndex);
4771
+ snippets.push(`${callName}(${args})`);
4772
+ if (snippets.length >= 200) break;
4773
+ }
4774
+ return snippets;
4775
+ }
4776
+ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper) {
4777
+ if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
4778
+ const payload = extractWritePayload(actionType, actionDetailRaw);
4779
+ if (!payload) return [];
4780
+ const { path: path8, content: rawContent } = payload;
4781
+ const language = detectLanguage(path8, rawContent);
4782
+ if (language === "data") return [];
4783
+ let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
4784
+ const started = Date.now();
4785
+ if (language === "python") {
4786
+ if (!PY_PRECHECK.test(content)) return [];
4787
+ return pythonSnippets(content);
4788
+ }
4789
+ content = stripShellDocsOnly(content);
4790
+ if (literalStripper) content = literalStripper(content);
4791
+ if (!SHELL_PRECHECK.test(content)) return [];
4792
+ const snippets = lineSnippets(content, SHELL_PRECHECK);
4793
+ if (Date.now() - started > MAX_MS) {
4794
+ return snippets;
4795
+ }
4796
+ return snippets;
4797
+ }
4798
+ 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;
4799
+ var init_written_content_analyzer = __esm({
4800
+ "src/engine/written-content-analyzer.ts"() {
4801
+ "use strict";
4802
+ init_esm_shims();
4803
+ init_rules_loader();
4804
+ CFG = loadHeuristicRules().write_content_analysis || {};
4805
+ DATA_EXTS = new Set((CFG.data_exts || []).map((e) => e.toLowerCase()));
4806
+ SHELL_EXTS = new Set((CFG.shell_exts || []).map((e) => e.toLowerCase()));
4807
+ PY_EXTS = new Set((CFG.python_exts || []).map((e) => e.toLowerCase()));
4808
+ SHELL_PRECHECK = new RegExp(CFG.shell_precheck || "$^");
4809
+ PY_PRECHECK = new RegExp(CFG.python_precheck || "$^");
4810
+ MAX_CONTENT = Number(CFG.max_content_bytes || 262144);
4811
+ MAX_SCAN = Number(CFG.max_scan_bytes || 65536);
4812
+ MAX_MS = Number(CFG.max_scan_ms || 100);
4813
+ WRITE_TOOL_EXACT = /* @__PURE__ */ new Set([
4814
+ "write",
4815
+ "file_write",
4816
+ "writefile",
4817
+ "edit",
4818
+ "file_edit",
4819
+ "editfile",
4820
+ "searchreplace",
4821
+ "search_replace"
4822
+ ]);
4823
+ WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
4824
+ APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
4825
+ WRITE_PREFIX_RE = /^(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*(.+?)\s*(?:\(\s*追加\s*\))?\s*—\s*([\s\S]*)$/;
4826
+ EDIT_NEW_RE = /\|\s*new:\s*([\s\S]*)$/i;
4827
+ INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
4828
+ QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
4829
+ 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;
4830
+ }
4831
+ });
4832
+
4569
4833
  // src/engine/heuristic.ts
4570
4834
  function _effectiveDangerousPatterns(osType) {
4571
4835
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
@@ -4673,8 +4937,16 @@ function runHeuristicCheck(input) {
4673
4937
  } catch {
4674
4938
  }
4675
4939
  }
4676
- const scanDetail = normalizePathSegments(stripLiteralTextSegments(input.aNext.actionDetail));
4677
- const scanCommands = String(input.osType || "").toLowerCase() === "windows" ? [
4940
+ const scanDetail = normalizePathSegments(
4941
+ stripLiteralTextSegments(stripShellDocsOnly(input.aNext.actionDetail))
4942
+ );
4943
+ const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
4944
+ const writeSnippets = extractDangerousSnippets(
4945
+ input.aNext.actionType,
4946
+ input.aNext.actionDetail,
4947
+ stripLiteralTextSegments
4948
+ );
4949
+ const scanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => [`${input.aNext.actionType}: ${sn}`, sn]) : String(input.osType || "").toLowerCase() === "windows" ? [
4678
4950
  `${input.aNext.actionType}: ${scanDetail}`,
4679
4951
  scanDetail,
4680
4952
  `${input.aNext.actionType}: ${scanDetail.replace(/\//g, "\\")}`,
@@ -4735,9 +5007,9 @@ function runHeuristicCheck(input) {
4735
5007
  const actionTypeL = input.aNext.actionType.toLowerCase();
4736
5008
  const detailL = input.aNext.actionDetail.toLowerCase();
4737
5009
  const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
4738
- const dangerousResult = checkDangerousPatterns(actionTypeL, detailL);
5010
+ const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
4739
5011
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
4740
- const homeResult = checkHomeDeletion(actionTypeL, detailL);
5012
+ const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
4741
5013
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
4742
5014
  if (mergeResults.length > 0) {
4743
5015
  let best = mergeResults[0];
@@ -5235,7 +5507,7 @@ function isSshKeygenGenerate(command) {
5235
5507
  }
5236
5508
  function checkDangerousPatterns(actionType, actionDetail) {
5237
5509
  if (actionType === "file_write" || actionType === "file_edit") return null;
5238
- const scan = stripHeredocContent(actionDetail);
5510
+ const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
5239
5511
  const isTempPath = TEMP_DIRS2.some(
5240
5512
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
5241
5513
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
@@ -5393,6 +5665,7 @@ var init_heuristic = __esm({
5393
5665
  init_runtime_config();
5394
5666
  init_runtime_config_bridge();
5395
5667
  init_rules_loader();
5668
+ init_written_content_analyzer();
5396
5669
  init_logic_rules();
5397
5670
  INJECTION_KEYWORDS = (() => {
5398
5671
  const kws = loadL1().injection_detection || [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kenhkl/agent-moss",
3
- "version": "0.17.25",
3
+ "version": "0.17.26",
4
4
  "description": "Multi-layer security analysis engine for AI agents (TypeScript)",
5
5
  "type": "module",
6
6
  "main": "dist/server.js",