@kenhkl/agent-moss 0.17.25 → 0.17.27

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.
@@ -1019,6 +1019,46 @@ function getSensitivePathsForOsBuiltin(osType) {
1019
1019
  }
1020
1020
  return { root: ROOT_SENSITIVE_PATHS, home: HOME_SENSITIVE_PATHS, credential: CREDENTIAL_PATHS };
1021
1021
  }
1022
+ function isPreciseEditTool(actionType) {
1023
+ const at = (actionType || "").toLowerCase();
1024
+ if (PRECISE_EDIT_TOOLS.has(at)) return true;
1025
+ for (const s of PRECISE_EDIT_TOOLS) if (at.endsWith(s)) return true;
1026
+ return false;
1027
+ }
1028
+ function isFullOverwriteTool(actionType, extraTools) {
1029
+ const at = (actionType || "").toLowerCase();
1030
+ const isWriteTool = SINGLE_FILE_WRITE_TOOLS.has(at) || extraTools.has(at) || [...SINGLE_FILE_WRITE_TOOLS].some((s) => at.endsWith(s)) || [...extraTools].some((s) => at.endsWith(s));
1031
+ if (!isWriteTool) return false;
1032
+ return !isPreciseEditTool(at);
1033
+ }
1034
+ function stripHeredocBody(text) {
1035
+ if (!text || INTERP_HEREDOC_HINT_RE.test(text)) return text;
1036
+ return text.replace(HEREDOC_BODY_RE, "<<heredoc>>\n");
1037
+ }
1038
+ function isDirectoryTarget(p) {
1039
+ if (!p) return false;
1040
+ if (p.endsWith("/")) return true;
1041
+ try {
1042
+ return fs.statSync(p).isDirectory();
1043
+ } catch {
1044
+ return false;
1045
+ }
1046
+ }
1047
+ function intentActionText(actionType, actionDetail) {
1048
+ let text = actionDetail || "";
1049
+ const at = (actionType || "").toLowerCase();
1050
+ if (at === "bash" || at === "executebash" || at === "terminal-executebash") {
1051
+ text = stripHeredocBody(text);
1052
+ text = text.replace(/(?<!\S)#[^\n]*/g, "");
1053
+ text = text.replace(/'[^']*'|"[^"]*"/g, "");
1054
+ return text;
1055
+ }
1056
+ const m = text.match(/^([\s\S]*?)\s*—\s*[\s\S]*$/);
1057
+ if (m) text = m[1];
1058
+ const m2 = text.match(/^(搜索|search|查找)\s*[::]\s*([\s\S]*?)\s+in\s+([\s\S]*)$/i);
1059
+ if (m2) text = `${m2[1]}: in ${m2[3]}`;
1060
+ return text;
1061
+ }
1022
1062
  function declaredWritePaths(actionDetailRaw, osType) {
1023
1063
  const m = actionDetailRaw.match(DECLARED_WRITE_PATH_RE);
1024
1064
  if (m) return [m[1]];
@@ -1290,11 +1330,12 @@ function checkIntentConsistency(input) {
1290
1330
  if (EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p))) return null;
1291
1331
  if (INLINE_SCRIPT_RE.test(actionDetail)) return null;
1292
1332
  const intentTexts = collectIntentTexts(promptSession, promptHistory);
1333
+ const dangerousText = intentActionText(actionType, actionDetail);
1293
1334
  for (const pattern of getIntentPatternsForOs(input.osType)) {
1294
1335
  const intentMatched = intentTexts.some(
1295
1336
  (text) => pattern.intentKeywords.some((kw) => text.includes(kw))
1296
1337
  );
1297
- const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(actionDetail, kw));
1338
+ const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(dangerousText, kw));
1298
1339
  if (intentMatched && dangerousMatched) {
1299
1340
  if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
1300
1341
  continue;
@@ -1432,11 +1473,15 @@ function extractFilePaths(text, osType) {
1432
1473
  return [...new Set(paths)];
1433
1474
  }
1434
1475
  function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason, cwd, osType, singleFileTools = SINGLE_FILE_WRITE_TOOLS) {
1476
+ actionDetailRaw = stripHeredocBody(actionDetailRaw);
1435
1477
  const actionDetail = actionDetailRaw.toLowerCase();
1436
1478
  if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
1437
1479
  if (NON_WRITE_TOOLS.has(actionType)) return null;
1438
1480
  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));
1481
+ let isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
1482
+ if (!isWrite && /\btar\b/.test(actionDetail) && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(actionDetail)) {
1483
+ isWrite = true;
1484
+ }
1440
1485
  if (!isWrite) return null;
1441
1486
  const WRITE_CMDS = new Set(_LOGIC.write_commands ?? []);
1442
1487
  if (isBashLike) {
@@ -1458,6 +1503,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1458
1503
  hasWriteSeg = true;
1459
1504
  break;
1460
1505
  }
1506
+ 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)) {
1507
+ hasWriteSeg = true;
1508
+ break;
1509
+ }
1461
1510
  if ((fw === "wget" || fw === "curl") && (/\s(?:-O|--output-document|--output)(?:=|\s|$)/i.test(trimmed) || /\s-O\S/.test(trimmed))) {
1462
1511
  hasWriteSeg = true;
1463
1512
  break;
@@ -1484,6 +1533,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1484
1533
  if (firstWord === "cd") {
1485
1534
  continue;
1486
1535
  }
1536
+ if (SHELL_ASSIGN_RE.test(trimmed)) {
1537
+ continue;
1538
+ }
1487
1539
  if (firstWord === "sed" && SED_INPLACE_RE.test(trimmed)) {
1488
1540
  } else if (getPlatformTraits(osType).readOnlyCommands.has(firstWord)) {
1489
1541
  const segUnquoted = trimmed.replace(new RegExp(`>{1,2}\\s*(['"])([~./][^'"]+)\\1`, "g"), (_m, _q, p) => ">" + p);
@@ -1497,6 +1549,11 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1497
1549
  const segPathsFiltered = firstWord === "wget" || firstWord === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
1498
1550
  if (SOURCE_ARG_CMDS.has(firstWord)) {
1499
1551
  if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
1552
+ } else if (firstWord === "tar") {
1553
+ if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
1554
+ const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
1555
+ if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
1556
+ }
1500
1557
  } else if (firstWord === "dd") {
1501
1558
  const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
1502
1559
  const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
@@ -1517,6 +1574,7 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1517
1574
  if (uniqueTargetPaths.length === 0) return null;
1518
1575
  const historyFullReadPaths = /* @__PURE__ */ new Set();
1519
1576
  const historyPartialRead = /* @__PURE__ */ new Map();
1577
+ const historyWrittenPaths = /* @__PURE__ */ new Set();
1520
1578
  for (const action of actionHistory) {
1521
1579
  const histDetailRaw = action.actionDetail;
1522
1580
  const histType = action.actionType.toLowerCase();
@@ -1528,6 +1586,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1528
1586
  traits.writeKeywords
1529
1587
  );
1530
1588
  for (const p of coverage.full) historyFullReadPaths.add(p);
1589
+ if (isFullOverwriteTool(histType, singleFileTools) && !APPEND_MODE_RE.test(histDetailRaw)) {
1590
+ for (const p of declaredWritePaths(histDetailRaw, osType)) historyWrittenPaths.add(p);
1591
+ }
1531
1592
  for (const [p, upto] of coverage.partial) {
1532
1593
  if (historyPartialRead.has(p)) {
1533
1594
  const old = historyPartialRead.get(p);
@@ -1550,6 +1611,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1550
1611
  const normalizedFullReads = new Set(
1551
1612
  [...historyFullReadPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
1552
1613
  );
1614
+ const normalizedWrittenPaths = new Set(
1615
+ [...historyWrittenPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
1616
+ );
1553
1617
  const normalizedPartialReads = /* @__PURE__ */ new Map();
1554
1618
  for (const [p, upto] of historyPartialRead) {
1555
1619
  const np = normalizePathForCompare(p, cwd);
@@ -1567,16 +1631,23 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1567
1631
  checkTargets = normalizedTargets.filter((p) => !([...appendNorm].some((ap) => pathIsSameOrUnder(p, ap) || pathIsSameOrUnder(ap, p)) && !isProtectedWritePath(p)));
1568
1632
  if (checkTargets.length === 0) return null;
1569
1633
  }
1634
+ const preciseEdit = isPreciseEditTool(actionType);
1570
1635
  const unreadPaths = [];
1571
1636
  for (const path7 of checkTargets) {
1572
- const isFullRead = [...normalizedFullReads].some(
1637
+ if (isDirectoryTarget(path7)) continue;
1638
+ let isFullRead = [...normalizedFullReads].some(
1573
1639
  (rp) => pathIsSameOrUnder(path7, rp) || pathIsSameOrUnder(rp, path7)
1574
1640
  );
1641
+ if (!isFullRead && preciseEdit && [...normalizedWrittenPaths].some(
1642
+ (wp) => pathIsSameOrUnder(path7, wp) || pathIsSameOrUnder(wp, path7)
1643
+ )) {
1644
+ isFullRead = true;
1645
+ }
1575
1646
  let isPartialCovered = false;
1576
1647
  if (!isFullRead) {
1577
1648
  for (const [pp, upto] of normalizedPartialReads) {
1578
1649
  if (!(pathIsSameOrUnder(path7, pp) || pathIsSameOrUnder(pp, path7))) continue;
1579
- if (upto != null && fileHasAtMostLines(path7, upto)) {
1650
+ if (preciseEdit || upto != null && fileHasAtMostLines(path7, upto)) {
1580
1651
  isPartialCovered = true;
1581
1652
  break;
1582
1653
  }
@@ -1765,7 +1836,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
1765
1836
  violatedLayers: ["L2.1"]
1766
1837
  };
1767
1838
  }
1768
- 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, 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, 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, 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;
1839
+ 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, 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, 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;
1769
1840
  var init_logic_rules = __esm({
1770
1841
  "src/engine/logic-rules.ts"() {
1771
1842
  "use strict";
@@ -1817,6 +1888,12 @@ var init_logic_rules = __esm({
1817
1888
  SINGLE_FILE_WRITE_TOOLS = new Set(
1818
1889
  _LOGIC.single_file_write_tools ?? []
1819
1890
  );
1891
+ PRECISE_EDIT_TOOLS = new Set(
1892
+ _LOGIC.precise_edit_write_tools ?? []
1893
+ );
1894
+ INTERP_HEREDOC_HINT_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s+(?:-\S*\s+)?<<-?\s*['"]?[A-Za-z_]/i;
1895
+ HEREDOC_BODY_RE = /<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n[\s\S]*?\n\s*\2\s*(?:\n|$)/g;
1896
+ SHELL_ASSIGN_RE = /^(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=/;
1820
1897
  WRITE_INTENT_KEYWORDS = _LOGIC.write_intent_keywords ?? [];
1821
1898
  MISSING_WRITE_PATH_RE = /(?:写入文件|编辑文件|写入|编辑)\s*[::]\s*\?/;
1822
1899
  DECLARED_WRITE_PATH_RE = /(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*([~./][^\s—|,;]+)/;
@@ -2113,7 +2190,7 @@ __export(runtime_config_exports, {
2113
2190
  updateSkillCategoryEnabled: () => updateSkillCategoryEnabled,
2114
2191
  updateSkillEnabled: () => updateSkillEnabled
2115
2192
  });
2116
- import { readFileSync as readFileSync4, writeFileSync, existsSync as existsSync5, mkdirSync, unlinkSync, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
2193
+ import { readFileSync as readFileSync4, writeFileSync, existsSync as existsSync5, mkdirSync, unlinkSync, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
2117
2194
  import { join as join5 } from "path";
2118
2195
  import { fileURLToPath as fileURLToPath4 } from "url";
2119
2196
  import { dirname as dirname3 } from "path";
@@ -2129,7 +2206,7 @@ function getRuleSourceFingerprint() {
2129
2206
  if (isRuntimeConfigDisabled()) return `mode:${getRulesMode()}`;
2130
2207
  const p = getRuntimeConfigPath();
2131
2208
  try {
2132
- const st = statSync2(p);
2209
+ const st = statSync3(p);
2133
2210
  return `${p}|${st.mtimeMs}|${st.size}`;
2134
2211
  } catch {
2135
2212
  return `${p}|absent`;
@@ -2186,7 +2263,7 @@ function loadRuntimeConfig() {
2186
2263
  return seeded;
2187
2264
  }
2188
2265
  try {
2189
- const st = statSync2(p);
2266
+ const st = statSync3(p);
2190
2267
  const cacheKey = `${p}|${st.mtimeMs}|${st.size}`;
2191
2268
  if (runtimeConfigCache && runtimeConfigCache.key === cacheKey) {
2192
2269
  return runtimeConfigCache.value;
@@ -2330,7 +2407,7 @@ function hasRuntimeConfig() {
2330
2407
  const p = getRuntimeConfigPath();
2331
2408
  let key;
2332
2409
  try {
2333
- const st = statSync2(p);
2410
+ const st = statSync3(p);
2334
2411
  key = `${p}|${st.mtimeMs}|${st.size}`;
2335
2412
  } catch {
2336
2413
  return false;
@@ -2964,7 +3041,9 @@ function getEnabledL2IntentPatterns(runtime, osType) {
2964
3041
  return rules.map((r) => ({
2965
3042
  intent_keywords: r.intent_keywords || [],
2966
3043
  dangerous_actions: r.dangerous_actions || [],
2967
- reason: r.reason || ""
3044
+ reason: r.reason || "",
3045
+ allow_if_write_intent: r.allow_if_write_intent === true,
3046
+ os: r.os
2968
3047
  }));
2969
3048
  }
2970
3049
  function getEnabledL2PasswordPatterns(runtime) {
@@ -4035,6 +4114,265 @@ var init_scenarios = __esm({
4035
4114
  }
4036
4115
  });
4037
4116
 
4117
+ // src/engine/written-content-analyzer.ts
4118
+ function isFileWriteAction(actionType) {
4119
+ const at = (actionType || "").toLowerCase();
4120
+ if (WRITE_TOOL_EXACT.has(at)) return true;
4121
+ if (WRITE_TOOL_SUFFIXES.some((s) => at.endsWith(s))) return true;
4122
+ return false;
4123
+ }
4124
+ function isApplyPatch(actionType) {
4125
+ const at = (actionType || "").toLowerCase();
4126
+ return APPLY_PATCH_SUFFIXES.some((s) => at.endsWith(s));
4127
+ }
4128
+ function extractWritePayload(actionType, actionDetailRaw) {
4129
+ if (isApplyPatch(actionType)) return null;
4130
+ const detail = actionDetailRaw || "";
4131
+ const m = detail.match(WRITE_PREFIX_RE);
4132
+ if (m) {
4133
+ const path7 = m[1];
4134
+ let content = m[2] || "";
4135
+ if (!path7 || path7 === "?" || path7 === "-" || !content.trim()) return null;
4136
+ if ((actionType || "").toLowerCase().includes("editfile")) {
4137
+ const nm = content.match(EDIT_NEW_RE);
4138
+ if (nm) content = nm[1];
4139
+ }
4140
+ return { path: path7, content };
4141
+ }
4142
+ const stripped = detail.trim();
4143
+ if (stripped.startsWith("{")) {
4144
+ try {
4145
+ const obj = JSON.parse(stripped);
4146
+ if (obj && typeof obj === "object") {
4147
+ const path7 = obj.path || obj.file_path || obj.filePath;
4148
+ const content = obj.content || obj.newString || obj.new_string;
4149
+ if (typeof path7 === "string" && path7 !== "" && path7 !== "?" && path7 !== "-" && typeof content === "string" && content.trim()) {
4150
+ return { path: path7, content };
4151
+ }
4152
+ }
4153
+ } catch {
4154
+ }
4155
+ }
4156
+ return null;
4157
+ }
4158
+ function handlesWrittenContent(actionType, actionDetailRaw) {
4159
+ if (!isFileWriteAction(actionType)) return false;
4160
+ if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
4161
+ return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
4162
+ }
4163
+ function detectLanguage(path7, content) {
4164
+ const ext = path7.slice(path7.lastIndexOf(".") >= 0 ? path7.lastIndexOf(".") : path7.length).toLowerCase();
4165
+ if (SHELL_EXTS.has(ext)) return "shell";
4166
+ if (PY_EXTS.has(ext)) return "python";
4167
+ if (DATA_EXTS.has(ext)) return "data";
4168
+ if (!ext) {
4169
+ const first = content.trim() ? content.trim().split(/\r?\n/)[0] : "";
4170
+ if (first.startsWith("#!")) {
4171
+ if (/\b(?:ba|z|k|da)?sh\b/.test(first)) return "shell";
4172
+ if (first.includes("python")) return "python";
4173
+ }
4174
+ return "data";
4175
+ }
4176
+ return "other";
4177
+ }
4178
+ function stripShellComments(text) {
4179
+ const out = [];
4180
+ let heredocEnd = null;
4181
+ for (const line of text.split(/\r?\n/)) {
4182
+ if (heredocEnd !== null) {
4183
+ out.push(line);
4184
+ if (line.trim() === heredocEnd) heredocEnd = null;
4185
+ continue;
4186
+ }
4187
+ const hm = line.match(HEREDOC_START_RE);
4188
+ if (hm) heredocEnd = hm[1];
4189
+ const res = [];
4190
+ let quote = null;
4191
+ for (let i = 0; i < line.length; i++) {
4192
+ const ch = line[i];
4193
+ if (quote) {
4194
+ res.push(ch);
4195
+ if (ch === quote) quote = null;
4196
+ continue;
4197
+ }
4198
+ if (ch === "'" || ch === '"') {
4199
+ quote = ch;
4200
+ res.push(ch);
4201
+ continue;
4202
+ }
4203
+ if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) break;
4204
+ res.push(ch);
4205
+ }
4206
+ out.push(res.join(""));
4207
+ }
4208
+ return out.join("\n");
4209
+ }
4210
+ function stripShellDocsOnly(content) {
4211
+ if (!content) return content;
4212
+ if (INTERP_HEREDOC_RE.test(content)) return content;
4213
+ const withoutHeredoc = content.replace(QUOTED_HEREDOC_RE, "<<quoted-heredoc>>\n");
4214
+ return stripShellComments(withoutHeredoc);
4215
+ }
4216
+ function lineSnippets(content, precheck) {
4217
+ const lines = content.split(/\r?\n/);
4218
+ const picked = /* @__PURE__ */ new Set();
4219
+ for (let i = 0; i < lines.length; i++) {
4220
+ precheck.lastIndex = 0;
4221
+ if (precheck.test(lines[i])) {
4222
+ picked.add(i - 1);
4223
+ picked.add(i);
4224
+ picked.add(i + 1);
4225
+ }
4226
+ }
4227
+ const snippets = [];
4228
+ let total = 0;
4229
+ for (const i of [...picked].sort((a, b) => a - b)) {
4230
+ if (i < 0 || i >= lines.length) continue;
4231
+ const s = lines[i];
4232
+ if (total + s.length > MAX_SCAN) break;
4233
+ snippets.push(s);
4234
+ total += s.length + 1;
4235
+ }
4236
+ return snippets;
4237
+ }
4238
+ function stripPythonLiterals(content) {
4239
+ const chars = content.split("");
4240
+ let i = 0;
4241
+ const n = chars.length;
4242
+ while (i < n) {
4243
+ const ch = chars[i];
4244
+ if (ch === "#") {
4245
+ while (i < n && chars[i] !== "\n") {
4246
+ chars[i] = " ";
4247
+ i++;
4248
+ }
4249
+ continue;
4250
+ }
4251
+ if (ch === "'" || ch === '"') {
4252
+ const triple = chars[i + 1] === ch && chars[i + 2] === ch;
4253
+ const quoteLen = triple ? 3 : 1;
4254
+ const q = ch;
4255
+ i += quoteLen;
4256
+ while (i < n) {
4257
+ if (chars[i] === "\\") {
4258
+ chars[i] = " ";
4259
+ if (i + 1 < n) chars[i + 1] = " ";
4260
+ i += 2;
4261
+ continue;
4262
+ }
4263
+ if (chars[i] === q && (!triple || chars[i + 1] === q && chars[i + 2] === q)) {
4264
+ for (let k = 0; k < quoteLen; k++) {
4265
+ chars[i + k] = " ";
4266
+ }
4267
+ i += quoteLen;
4268
+ break;
4269
+ }
4270
+ chars[i] = " ";
4271
+ i++;
4272
+ }
4273
+ continue;
4274
+ }
4275
+ i++;
4276
+ }
4277
+ return chars.join("");
4278
+ }
4279
+ function balancedArgs(original, openIndex) {
4280
+ let depth = 0;
4281
+ let quote = null;
4282
+ for (let i = openIndex; i < original.length && i < openIndex + 8e3; i++) {
4283
+ const ch = original[i];
4284
+ if (quote) {
4285
+ if (ch === "\\") {
4286
+ i++;
4287
+ continue;
4288
+ }
4289
+ if (ch === quote) quote = null;
4290
+ continue;
4291
+ }
4292
+ if (ch === "'" || ch === '"') {
4293
+ quote = ch;
4294
+ continue;
4295
+ }
4296
+ if (ch === "(") depth++;
4297
+ else if (ch === ")") {
4298
+ depth--;
4299
+ if (depth === 0) return original.slice(openIndex + 1, i);
4300
+ }
4301
+ }
4302
+ return original.slice(openIndex + 1, Math.min(original.length, openIndex + 2e3));
4303
+ }
4304
+ function pythonSnippets(content) {
4305
+ const stripped = stripPythonLiterals(content);
4306
+ const snippets = [];
4307
+ PY_DANGEROUS_CALL_RE.lastIndex = 0;
4308
+ let m;
4309
+ while ((m = PY_DANGEROUS_CALL_RE.exec(stripped)) !== null) {
4310
+ const callName = m[0].replace(/\s*\($/, "").trim();
4311
+ const openIndex = m.index + m[0].length - 1;
4312
+ const args = balancedArgs(content, openIndex);
4313
+ snippets.push(`${callName}(${args})`);
4314
+ if (snippets.length >= 200) break;
4315
+ }
4316
+ return snippets;
4317
+ }
4318
+ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper) {
4319
+ if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
4320
+ const payload = extractWritePayload(actionType, actionDetailRaw);
4321
+ if (!payload) return [];
4322
+ const { path: path7, content: rawContent } = payload;
4323
+ const language = detectLanguage(path7, rawContent);
4324
+ if (language === "data") return [];
4325
+ let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
4326
+ const started = Date.now();
4327
+ if (language === "python") {
4328
+ if (!PY_PRECHECK.test(content)) return [];
4329
+ return pythonSnippets(content);
4330
+ }
4331
+ content = stripShellDocsOnly(content);
4332
+ if (literalStripper) content = literalStripper(content);
4333
+ if (!SHELL_PRECHECK.test(content)) return [];
4334
+ const snippets = lineSnippets(content, SHELL_PRECHECK);
4335
+ if (Date.now() - started > MAX_MS) {
4336
+ return snippets;
4337
+ }
4338
+ return snippets;
4339
+ }
4340
+ 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;
4341
+ var init_written_content_analyzer = __esm({
4342
+ "src/engine/written-content-analyzer.ts"() {
4343
+ "use strict";
4344
+ init_esm_shims();
4345
+ init_rules_loader();
4346
+ CFG = loadHeuristicRules().write_content_analysis || {};
4347
+ DATA_EXTS = new Set((CFG.data_exts || []).map((e) => e.toLowerCase()));
4348
+ SHELL_EXTS = new Set((CFG.shell_exts || []).map((e) => e.toLowerCase()));
4349
+ PY_EXTS = new Set((CFG.python_exts || []).map((e) => e.toLowerCase()));
4350
+ SHELL_PRECHECK = new RegExp(CFG.shell_precheck || "$^");
4351
+ PY_PRECHECK = new RegExp(CFG.python_precheck || "$^");
4352
+ MAX_CONTENT = Number(CFG.max_content_bytes || 262144);
4353
+ MAX_SCAN = Number(CFG.max_scan_bytes || 65536);
4354
+ MAX_MS = Number(CFG.max_scan_ms || 100);
4355
+ WRITE_TOOL_EXACT = /* @__PURE__ */ new Set([
4356
+ "write",
4357
+ "file_write",
4358
+ "writefile",
4359
+ "edit",
4360
+ "file_edit",
4361
+ "editfile",
4362
+ "searchreplace",
4363
+ "search_replace"
4364
+ ]);
4365
+ WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
4366
+ APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
4367
+ WRITE_PREFIX_RE = /^(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*(.+?)\s*(?:\(\s*追加\s*\))?\s*—\s*([\s\S]*)$/;
4368
+ EDIT_NEW_RE = /\|\s*new:\s*([\s\S]*)$/i;
4369
+ INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
4370
+ QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
4371
+ 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;
4372
+ HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
4373
+ }
4374
+ });
4375
+
4038
4376
  // src/engine/heuristic.ts
4039
4377
  function _effectiveDangerousPatterns(osType) {
4040
4378
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
@@ -4142,8 +4480,16 @@ function runHeuristicCheck(input) {
4142
4480
  } catch {
4143
4481
  }
4144
4482
  }
4145
- const scanDetail = normalizePathSegments(stripLiteralTextSegments(input.aNext.actionDetail));
4146
- const scanCommands = String(input.osType || "").toLowerCase() === "windows" ? [
4483
+ const scanDetail = normalizePathSegments(
4484
+ stripLiteralTextSegments(stripShellDocsOnly(input.aNext.actionDetail))
4485
+ );
4486
+ const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
4487
+ const writeSnippets = extractDangerousSnippets(
4488
+ input.aNext.actionType,
4489
+ input.aNext.actionDetail,
4490
+ stripLiteralTextSegments
4491
+ );
4492
+ const scanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => [`${input.aNext.actionType}: ${sn}`, sn]) : String(input.osType || "").toLowerCase() === "windows" ? [
4147
4493
  `${input.aNext.actionType}: ${scanDetail}`,
4148
4494
  scanDetail,
4149
4495
  `${input.aNext.actionType}: ${scanDetail.replace(/\//g, "\\")}`,
@@ -4204,9 +4550,9 @@ function runHeuristicCheck(input) {
4204
4550
  const actionTypeL = input.aNext.actionType.toLowerCase();
4205
4551
  const detailL = input.aNext.actionDetail.toLowerCase();
4206
4552
  const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
4207
- const dangerousResult = checkDangerousPatterns(actionTypeL, detailL);
4553
+ const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
4208
4554
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
4209
- const homeResult = checkHomeDeletion(actionTypeL, detailL);
4555
+ const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
4210
4556
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
4211
4557
  if (mergeResults.length > 0) {
4212
4558
  let best = mergeResults[0];
@@ -4704,7 +5050,7 @@ function isSshKeygenGenerate(command) {
4704
5050
  }
4705
5051
  function checkDangerousPatterns(actionType, actionDetail) {
4706
5052
  if (actionType === "file_write" || actionType === "file_edit") return null;
4707
- const scan = stripHeredocContent(actionDetail);
5053
+ const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
4708
5054
  const isTempPath = TEMP_DIRS2.some(
4709
5055
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
4710
5056
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
@@ -4862,6 +5208,7 @@ var init_heuristic = __esm({
4862
5208
  init_runtime_config();
4863
5209
  init_runtime_config_bridge();
4864
5210
  init_rules_loader();
5211
+ init_written_content_analyzer();
4865
5212
  init_logic_rules();
4866
5213
  INJECTION_KEYWORDS = (() => {
4867
5214
  const kws = loadL1().injection_detection || [];
@@ -4912,7 +5259,7 @@ __export(token_stats_exports, {
4912
5259
  resetTokenStats: () => resetTokenStats,
4913
5260
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
4914
5261
  });
4915
- import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync5 } from "fs";
5262
+ import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
4916
5263
  function getStatsPath() {
4917
5264
  const envPath = process.env[ENV_STATS_PATH];
4918
5265
  if (envPath) return envPath;
@@ -4922,7 +5269,7 @@ function loadAllRecords(statsPath) {
4922
5269
  if (!existsSync12(statsPath)) return [];
4923
5270
  let sig = "";
4924
5271
  try {
4925
- const st = statSync5(statsPath);
5272
+ const st = statSync6(statsPath);
4926
5273
  sig = `${st.mtimeMs}:${st.size}`;
4927
5274
  } catch {
4928
5275
  return [];
@@ -4948,7 +5295,7 @@ function saveRecords(statsPath, records) {
4948
5295
  if (dir && !existsSync12(dir)) mkdirSync3(dir, { recursive: true });
4949
5296
  writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
4950
5297
  try {
4951
- const st = statSync5(statsPath);
5298
+ const st = statSync6(statsPath);
4952
5299
  _recordsCache = {
4953
5300
  path: statsPath,
4954
5301
  sig: `${st.mtimeMs}:${st.size}`,
@@ -5383,7 +5730,7 @@ init_heuristic();
5383
5730
  init_config();
5384
5731
  init_logic_rules();
5385
5732
  init_inline_analyzer();
5386
- import { statSync as statSync4, existsSync as existsSync11 } from "fs";
5733
+ import { statSync as statSync5, existsSync as existsSync11 } from "fs";
5387
5734
  import { resolve as resolve10, join as join11, isAbsolute as isAbsolute4 } from "path";
5388
5735
  import { homedir as homedir5 } from "os";
5389
5736
 
@@ -7024,7 +7371,7 @@ function extractInlineScriptPath(actionDetail) {
7024
7371
  try {
7025
7372
  const resolved = resolvePath2(tok.replace(/^['"]|['"]$/g, ""));
7026
7373
  if (existsSync11(resolved)) {
7027
- const stat = statSync4(resolved);
7374
+ const stat = statSync5(resolved);
7028
7375
  if (stat.isFile()) return resolved;
7029
7376
  }
7030
7377
  } catch {
@@ -7038,7 +7385,7 @@ function extractInlineScriptPath(actionDetail) {
7038
7385
  try {
7039
7386
  const resolved = resolvePath2(p);
7040
7387
  if (existsSync11(resolved)) {
7041
- const stat = statSync4(resolved);
7388
+ const stat = statSync5(resolved);
7042
7389
  if (stat.isFile()) return resolved;
7043
7390
  }
7044
7391
  } catch {
@@ -7054,7 +7401,7 @@ function extractInlineScriptPath(actionDetail) {
7054
7401
  try {
7055
7402
  resolved = resolvePath2(p);
7056
7403
  if (existsSync11(resolved)) {
7057
- const stat = statSync4(resolved);
7404
+ const stat = statSync5(resolved);
7058
7405
  if (stat.isFile()) return resolved;
7059
7406
  }
7060
7407
  } catch {
@@ -9281,6 +9628,19 @@ function loadStages() {
9281
9628
  return stages;
9282
9629
  }
9283
9630
  var PATH_RE = /(?:^|\s|[@=])((?:\/|~\/)[\w./~-]+)/g;
9631
+ var COMMON_DIR_RESOURCES = /* @__PURE__ */ new Set([
9632
+ "/",
9633
+ "/tmp",
9634
+ "/var/tmp",
9635
+ "/dev/shm",
9636
+ "/home",
9637
+ "/root",
9638
+ "/usr",
9639
+ "/etc",
9640
+ "/var",
9641
+ "/data",
9642
+ "/storage"
9643
+ ]);
9284
9644
  function extractResources(actionDetail) {
9285
9645
  const resources = /* @__PURE__ */ new Set();
9286
9646
  const text = actionDetail.replace(/'[^']*'|"[^"]*"/g, "");
@@ -9289,6 +9649,7 @@ function extractResources(actionDetail) {
9289
9649
  while ((m = PATH_RE.exec(text)) !== null) {
9290
9650
  const p = m[1];
9291
9651
  if (p.startsWith("/dev/") || p.includes("://")) continue;
9652
+ if (COMMON_DIR_RESOURCES.has(p) || p.endsWith("/")) continue;
9292
9653
  resources.add(p);
9293
9654
  }
9294
9655
  return resources;
@@ -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
  }