@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.
package/dist/cli.js CHANGED
@@ -1850,6 +1850,46 @@ function getSensitivePathsForOsBuiltin(osType) {
1850
1850
  }
1851
1851
  return { root: ROOT_SENSITIVE_PATHS, home: HOME_SENSITIVE_PATHS, credential: CREDENTIAL_PATHS };
1852
1852
  }
1853
+ function isPreciseEditTool(actionType) {
1854
+ const at = (actionType || "").toLowerCase();
1855
+ if (PRECISE_EDIT_TOOLS.has(at)) return true;
1856
+ for (const s of PRECISE_EDIT_TOOLS) if (at.endsWith(s)) return true;
1857
+ return false;
1858
+ }
1859
+ function isFullOverwriteTool(actionType, extraTools) {
1860
+ const at = (actionType || "").toLowerCase();
1861
+ 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));
1862
+ if (!isWriteTool) return false;
1863
+ return !isPreciseEditTool(at);
1864
+ }
1865
+ function stripHeredocBody(text) {
1866
+ if (!text || INTERP_HEREDOC_HINT_RE.test(text)) return text;
1867
+ return text.replace(HEREDOC_BODY_RE, "<<heredoc>>\n");
1868
+ }
1869
+ function isDirectoryTarget(p) {
1870
+ if (!p) return false;
1871
+ if (p.endsWith("/")) return true;
1872
+ try {
1873
+ return fs.statSync(p).isDirectory();
1874
+ } catch {
1875
+ return false;
1876
+ }
1877
+ }
1878
+ function intentActionText(actionType, actionDetail) {
1879
+ let text = actionDetail || "";
1880
+ const at = (actionType || "").toLowerCase();
1881
+ if (at === "bash" || at === "executebash" || at === "terminal-executebash") {
1882
+ text = stripHeredocBody(text);
1883
+ text = text.replace(/(?<!\S)#[^\n]*/g, "");
1884
+ text = text.replace(/'[^']*'|"[^"]*"/g, "");
1885
+ return text;
1886
+ }
1887
+ const m = text.match(/^([\s\S]*?)\s*—\s*[\s\S]*$/);
1888
+ if (m) text = m[1];
1889
+ const m2 = text.match(/^(搜索|search|查找)\s*[::]\s*([\s\S]*?)\s+in\s+([\s\S]*)$/i);
1890
+ if (m2) text = `${m2[1]}: in ${m2[3]}`;
1891
+ return text;
1892
+ }
1853
1893
  function declaredWritePaths(actionDetailRaw, osType) {
1854
1894
  const m = actionDetailRaw.match(DECLARED_WRITE_PATH_RE);
1855
1895
  if (m) return [m[1]];
@@ -2121,11 +2161,12 @@ function checkIntentConsistency(input) {
2121
2161
  if (EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p))) return null;
2122
2162
  if (INLINE_SCRIPT_RE.test(actionDetail)) return null;
2123
2163
  const intentTexts = collectIntentTexts(promptSession, promptHistory);
2164
+ const dangerousText = intentActionText(actionType, actionDetail);
2124
2165
  for (const pattern of getIntentPatternsForOs(input.osType)) {
2125
2166
  const intentMatched = intentTexts.some(
2126
2167
  (text) => pattern.intentKeywords.some((kw) => text.includes(kw))
2127
2168
  );
2128
- const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(actionDetail, kw));
2169
+ const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(dangerousText, kw));
2129
2170
  if (intentMatched && dangerousMatched) {
2130
2171
  if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
2131
2172
  continue;
@@ -2263,11 +2304,15 @@ function extractFilePaths(text, osType) {
2263
2304
  return [...new Set(paths)];
2264
2305
  }
2265
2306
  function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason, cwd, osType, singleFileTools = SINGLE_FILE_WRITE_TOOLS) {
2307
+ actionDetailRaw = stripHeredocBody(actionDetailRaw);
2266
2308
  const actionDetail = actionDetailRaw.toLowerCase();
2267
2309
  if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
2268
2310
  if (NON_WRITE_TOOLS.has(actionType)) return null;
2269
2311
  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));
2312
+ let isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
2313
+ if (!isWrite && /\btar\b/.test(actionDetail) && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(actionDetail)) {
2314
+ isWrite = true;
2315
+ }
2271
2316
  if (!isWrite) return null;
2272
2317
  const WRITE_CMDS = new Set(_LOGIC.write_commands ?? []);
2273
2318
  if (isBashLike) {
@@ -2289,6 +2334,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2289
2334
  hasWriteSeg = true;
2290
2335
  break;
2291
2336
  }
2337
+ 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)) {
2338
+ hasWriteSeg = true;
2339
+ break;
2340
+ }
2292
2341
  if ((fw === "wget" || fw === "curl") && (/\s(?:-O|--output-document|--output)(?:=|\s|$)/i.test(trimmed) || /\s-O\S/.test(trimmed))) {
2293
2342
  hasWriteSeg = true;
2294
2343
  break;
@@ -2315,6 +2364,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2315
2364
  if (firstWord === "cd") {
2316
2365
  continue;
2317
2366
  }
2367
+ if (SHELL_ASSIGN_RE.test(trimmed)) {
2368
+ continue;
2369
+ }
2318
2370
  if (firstWord === "sed" && SED_INPLACE_RE.test(trimmed)) {
2319
2371
  } else if (getPlatformTraits(osType).readOnlyCommands.has(firstWord)) {
2320
2372
  const segUnquoted = trimmed.replace(new RegExp(`>{1,2}\\s*(['"])([~./][^'"]+)\\1`, "g"), (_m, _q, p) => ">" + p);
@@ -2328,6 +2380,11 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2328
2380
  const segPathsFiltered = firstWord === "wget" || firstWord === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
2329
2381
  if (SOURCE_ARG_CMDS.has(firstWord)) {
2330
2382
  if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
2383
+ } else if (firstWord === "tar") {
2384
+ if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
2385
+ const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
2386
+ if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
2387
+ }
2331
2388
  } else if (firstWord === "dd") {
2332
2389
  const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
2333
2390
  const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
@@ -2348,6 +2405,7 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2348
2405
  if (uniqueTargetPaths.length === 0) return null;
2349
2406
  const historyFullReadPaths = /* @__PURE__ */ new Set();
2350
2407
  const historyPartialRead = /* @__PURE__ */ new Map();
2408
+ const historyWrittenPaths = /* @__PURE__ */ new Set();
2351
2409
  for (const action of actionHistory) {
2352
2410
  const histDetailRaw = action.actionDetail;
2353
2411
  const histType = action.actionType.toLowerCase();
@@ -2359,6 +2417,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2359
2417
  traits.writeKeywords
2360
2418
  );
2361
2419
  for (const p of coverage.full) historyFullReadPaths.add(p);
2420
+ if (isFullOverwriteTool(histType, singleFileTools) && !APPEND_MODE_RE.test(histDetailRaw)) {
2421
+ for (const p of declaredWritePaths(histDetailRaw, osType)) historyWrittenPaths.add(p);
2422
+ }
2362
2423
  for (const [p, upto] of coverage.partial) {
2363
2424
  if (historyPartialRead.has(p)) {
2364
2425
  const old = historyPartialRead.get(p);
@@ -2381,6 +2442,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2381
2442
  const normalizedFullReads = new Set(
2382
2443
  [...historyFullReadPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2383
2444
  );
2445
+ const normalizedWrittenPaths = new Set(
2446
+ [...historyWrittenPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2447
+ );
2384
2448
  const normalizedPartialReads = /* @__PURE__ */ new Map();
2385
2449
  for (const [p, upto] of historyPartialRead) {
2386
2450
  const np = normalizePathForCompare(p, cwd);
@@ -2398,16 +2462,23 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2398
2462
  checkTargets = normalizedTargets.filter((p) => !([...appendNorm].some((ap) => pathIsSameOrUnder(p, ap) || pathIsSameOrUnder(ap, p)) && !isProtectedWritePath(p)));
2399
2463
  if (checkTargets.length === 0) return null;
2400
2464
  }
2465
+ const preciseEdit = isPreciseEditTool(actionType);
2401
2466
  const unreadPaths = [];
2402
2467
  for (const path8 of checkTargets) {
2403
- const isFullRead = [...normalizedFullReads].some(
2468
+ if (isDirectoryTarget(path8)) continue;
2469
+ let isFullRead = [...normalizedFullReads].some(
2404
2470
  (rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
2405
2471
  );
2472
+ if (!isFullRead && preciseEdit && [...normalizedWrittenPaths].some(
2473
+ (wp) => pathIsSameOrUnder(path8, wp) || pathIsSameOrUnder(wp, path8)
2474
+ )) {
2475
+ isFullRead = true;
2476
+ }
2406
2477
  let isPartialCovered = false;
2407
2478
  if (!isFullRead) {
2408
2479
  for (const [pp, upto] of normalizedPartialReads) {
2409
2480
  if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
2410
- if (upto != null && fileHasAtMostLines(path8, upto)) {
2481
+ if (preciseEdit || upto != null && fileHasAtMostLines(path8, upto)) {
2411
2482
  isPartialCovered = true;
2412
2483
  break;
2413
2484
  }
@@ -2596,7 +2667,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2596
2667
  violatedLayers: ["L2.1"]
2597
2668
  };
2598
2669
  }
2599
- 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;
2670
+ 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;
2600
2671
  var init_logic_rules = __esm({
2601
2672
  "src/engine/logic-rules.ts"() {
2602
2673
  "use strict";
@@ -2648,6 +2719,12 @@ var init_logic_rules = __esm({
2648
2719
  SINGLE_FILE_WRITE_TOOLS = new Set(
2649
2720
  _LOGIC.single_file_write_tools ?? []
2650
2721
  );
2722
+ PRECISE_EDIT_TOOLS = new Set(
2723
+ _LOGIC.precise_edit_write_tools ?? []
2724
+ );
2725
+ 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;
2726
+ HEREDOC_BODY_RE = /<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n[\s\S]*?\n\s*\2\s*(?:\n|$)/g;
2727
+ SHELL_ASSIGN_RE = /^(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=/;
2651
2728
  WRITE_INTENT_KEYWORDS = _LOGIC.write_intent_keywords ?? [];
2652
2729
  MISSING_WRITE_PATH_RE = /(?:写入文件|编辑文件|写入|编辑)\s*[::]\s*\?/;
2653
2730
  DECLARED_WRITE_PATH_RE = /(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*([~./][^\s—|,;]+)/;
@@ -2944,7 +3021,7 @@ __export(runtime_config_exports, {
2944
3021
  updateSkillCategoryEnabled: () => updateSkillCategoryEnabled,
2945
3022
  updateSkillEnabled: () => updateSkillEnabled
2946
3023
  });
2947
- import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
3024
+ import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
2948
3025
  import { join as join7 } from "path";
2949
3026
  import { fileURLToPath as fileURLToPath4 } from "url";
2950
3027
  import { dirname as dirname4 } from "path";
@@ -2960,7 +3037,7 @@ function getRuleSourceFingerprint() {
2960
3037
  if (isRuntimeConfigDisabled()) return `mode:${getRulesMode()}`;
2961
3038
  const p = getRuntimeConfigPath();
2962
3039
  try {
2963
- const st = statSync2(p);
3040
+ const st = statSync3(p);
2964
3041
  return `${p}|${st.mtimeMs}|${st.size}`;
2965
3042
  } catch {
2966
3043
  return `${p}|absent`;
@@ -3017,7 +3094,7 @@ function loadRuntimeConfig() {
3017
3094
  return seeded;
3018
3095
  }
3019
3096
  try {
3020
- const st = statSync2(p);
3097
+ const st = statSync3(p);
3021
3098
  const cacheKey = `${p}|${st.mtimeMs}|${st.size}`;
3022
3099
  if (runtimeConfigCache && runtimeConfigCache.key === cacheKey) {
3023
3100
  return runtimeConfigCache.value;
@@ -3161,7 +3238,7 @@ function hasRuntimeConfig() {
3161
3238
  const p = getRuntimeConfigPath();
3162
3239
  let key;
3163
3240
  try {
3164
- const st = statSync2(p);
3241
+ const st = statSync3(p);
3165
3242
  key = `${p}|${st.mtimeMs}|${st.size}`;
3166
3243
  } catch {
3167
3244
  return false;
@@ -3795,7 +3872,9 @@ function getEnabledL2IntentPatterns(runtime, osType) {
3795
3872
  return rules.map((r) => ({
3796
3873
  intent_keywords: r.intent_keywords || [],
3797
3874
  dangerous_actions: r.dangerous_actions || [],
3798
- reason: r.reason || ""
3875
+ reason: r.reason || "",
3876
+ allow_if_write_intent: r.allow_if_write_intent === true,
3877
+ os: r.os
3799
3878
  }));
3800
3879
  }
3801
3880
  function getEnabledL2PasswordPatterns(runtime) {
@@ -4866,6 +4945,265 @@ var init_scenarios = __esm({
4866
4945
  }
4867
4946
  });
4868
4947
 
4948
+ // src/engine/written-content-analyzer.ts
4949
+ function isFileWriteAction(actionType) {
4950
+ const at = (actionType || "").toLowerCase();
4951
+ if (WRITE_TOOL_EXACT.has(at)) return true;
4952
+ if (WRITE_TOOL_SUFFIXES.some((s) => at.endsWith(s))) return true;
4953
+ return false;
4954
+ }
4955
+ function isApplyPatch(actionType) {
4956
+ const at = (actionType || "").toLowerCase();
4957
+ return APPLY_PATCH_SUFFIXES.some((s) => at.endsWith(s));
4958
+ }
4959
+ function extractWritePayload(actionType, actionDetailRaw) {
4960
+ if (isApplyPatch(actionType)) return null;
4961
+ const detail = actionDetailRaw || "";
4962
+ const m = detail.match(WRITE_PREFIX_RE);
4963
+ if (m) {
4964
+ const path8 = m[1];
4965
+ let content = m[2] || "";
4966
+ if (!path8 || path8 === "?" || path8 === "-" || !content.trim()) return null;
4967
+ if ((actionType || "").toLowerCase().includes("editfile")) {
4968
+ const nm = content.match(EDIT_NEW_RE);
4969
+ if (nm) content = nm[1];
4970
+ }
4971
+ return { path: path8, content };
4972
+ }
4973
+ const stripped = detail.trim();
4974
+ if (stripped.startsWith("{")) {
4975
+ try {
4976
+ const obj = JSON.parse(stripped);
4977
+ if (obj && typeof obj === "object") {
4978
+ const path8 = obj.path || obj.file_path || obj.filePath;
4979
+ const content = obj.content || obj.newString || obj.new_string;
4980
+ if (typeof path8 === "string" && path8 !== "" && path8 !== "?" && path8 !== "-" && typeof content === "string" && content.trim()) {
4981
+ return { path: path8, content };
4982
+ }
4983
+ }
4984
+ } catch {
4985
+ }
4986
+ }
4987
+ return null;
4988
+ }
4989
+ function handlesWrittenContent(actionType, actionDetailRaw) {
4990
+ if (!isFileWriteAction(actionType)) return false;
4991
+ if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
4992
+ return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
4993
+ }
4994
+ function detectLanguage(path8, content) {
4995
+ const ext = path8.slice(path8.lastIndexOf(".") >= 0 ? path8.lastIndexOf(".") : path8.length).toLowerCase();
4996
+ if (SHELL_EXTS.has(ext)) return "shell";
4997
+ if (PY_EXTS.has(ext)) return "python";
4998
+ if (DATA_EXTS.has(ext)) return "data";
4999
+ if (!ext) {
5000
+ const first = content.trim() ? content.trim().split(/\r?\n/)[0] : "";
5001
+ if (first.startsWith("#!")) {
5002
+ if (/\b(?:ba|z|k|da)?sh\b/.test(first)) return "shell";
5003
+ if (first.includes("python")) return "python";
5004
+ }
5005
+ return "data";
5006
+ }
5007
+ return "other";
5008
+ }
5009
+ function stripShellComments(text) {
5010
+ const out = [];
5011
+ let heredocEnd = null;
5012
+ for (const line of text.split(/\r?\n/)) {
5013
+ if (heredocEnd !== null) {
5014
+ out.push(line);
5015
+ if (line.trim() === heredocEnd) heredocEnd = null;
5016
+ continue;
5017
+ }
5018
+ const hm = line.match(HEREDOC_START_RE);
5019
+ if (hm) heredocEnd = hm[1];
5020
+ const res = [];
5021
+ let quote = null;
5022
+ for (let i = 0; i < line.length; i++) {
5023
+ const ch = line[i];
5024
+ if (quote) {
5025
+ res.push(ch);
5026
+ if (ch === quote) quote = null;
5027
+ continue;
5028
+ }
5029
+ if (ch === "'" || ch === '"') {
5030
+ quote = ch;
5031
+ res.push(ch);
5032
+ continue;
5033
+ }
5034
+ if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) break;
5035
+ res.push(ch);
5036
+ }
5037
+ out.push(res.join(""));
5038
+ }
5039
+ return out.join("\n");
5040
+ }
5041
+ function stripShellDocsOnly(content) {
5042
+ if (!content) return content;
5043
+ if (INTERP_HEREDOC_RE.test(content)) return content;
5044
+ const withoutHeredoc = content.replace(QUOTED_HEREDOC_RE, "<<quoted-heredoc>>\n");
5045
+ return stripShellComments(withoutHeredoc);
5046
+ }
5047
+ function lineSnippets(content, precheck) {
5048
+ const lines = content.split(/\r?\n/);
5049
+ const picked = /* @__PURE__ */ new Set();
5050
+ for (let i = 0; i < lines.length; i++) {
5051
+ precheck.lastIndex = 0;
5052
+ if (precheck.test(lines[i])) {
5053
+ picked.add(i - 1);
5054
+ picked.add(i);
5055
+ picked.add(i + 1);
5056
+ }
5057
+ }
5058
+ const snippets = [];
5059
+ let total = 0;
5060
+ for (const i of [...picked].sort((a, b) => a - b)) {
5061
+ if (i < 0 || i >= lines.length) continue;
5062
+ const s = lines[i];
5063
+ if (total + s.length > MAX_SCAN) break;
5064
+ snippets.push(s);
5065
+ total += s.length + 1;
5066
+ }
5067
+ return snippets;
5068
+ }
5069
+ function stripPythonLiterals(content) {
5070
+ const chars = content.split("");
5071
+ let i = 0;
5072
+ const n = chars.length;
5073
+ while (i < n) {
5074
+ const ch = chars[i];
5075
+ if (ch === "#") {
5076
+ while (i < n && chars[i] !== "\n") {
5077
+ chars[i] = " ";
5078
+ i++;
5079
+ }
5080
+ continue;
5081
+ }
5082
+ if (ch === "'" || ch === '"') {
5083
+ const triple = chars[i + 1] === ch && chars[i + 2] === ch;
5084
+ const quoteLen = triple ? 3 : 1;
5085
+ const q = ch;
5086
+ i += quoteLen;
5087
+ while (i < n) {
5088
+ if (chars[i] === "\\") {
5089
+ chars[i] = " ";
5090
+ if (i + 1 < n) chars[i + 1] = " ";
5091
+ i += 2;
5092
+ continue;
5093
+ }
5094
+ if (chars[i] === q && (!triple || chars[i + 1] === q && chars[i + 2] === q)) {
5095
+ for (let k = 0; k < quoteLen; k++) {
5096
+ chars[i + k] = " ";
5097
+ }
5098
+ i += quoteLen;
5099
+ break;
5100
+ }
5101
+ chars[i] = " ";
5102
+ i++;
5103
+ }
5104
+ continue;
5105
+ }
5106
+ i++;
5107
+ }
5108
+ return chars.join("");
5109
+ }
5110
+ function balancedArgs(original, openIndex) {
5111
+ let depth = 0;
5112
+ let quote = null;
5113
+ for (let i = openIndex; i < original.length && i < openIndex + 8e3; i++) {
5114
+ const ch = original[i];
5115
+ if (quote) {
5116
+ if (ch === "\\") {
5117
+ i++;
5118
+ continue;
5119
+ }
5120
+ if (ch === quote) quote = null;
5121
+ continue;
5122
+ }
5123
+ if (ch === "'" || ch === '"') {
5124
+ quote = ch;
5125
+ continue;
5126
+ }
5127
+ if (ch === "(") depth++;
5128
+ else if (ch === ")") {
5129
+ depth--;
5130
+ if (depth === 0) return original.slice(openIndex + 1, i);
5131
+ }
5132
+ }
5133
+ return original.slice(openIndex + 1, Math.min(original.length, openIndex + 2e3));
5134
+ }
5135
+ function pythonSnippets(content) {
5136
+ const stripped = stripPythonLiterals(content);
5137
+ const snippets = [];
5138
+ PY_DANGEROUS_CALL_RE.lastIndex = 0;
5139
+ let m;
5140
+ while ((m = PY_DANGEROUS_CALL_RE.exec(stripped)) !== null) {
5141
+ const callName = m[0].replace(/\s*\($/, "").trim();
5142
+ const openIndex = m.index + m[0].length - 1;
5143
+ const args = balancedArgs(content, openIndex);
5144
+ snippets.push(`${callName}(${args})`);
5145
+ if (snippets.length >= 200) break;
5146
+ }
5147
+ return snippets;
5148
+ }
5149
+ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper) {
5150
+ if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
5151
+ const payload = extractWritePayload(actionType, actionDetailRaw);
5152
+ if (!payload) return [];
5153
+ const { path: path8, content: rawContent } = payload;
5154
+ const language = detectLanguage(path8, rawContent);
5155
+ if (language === "data") return [];
5156
+ let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
5157
+ const started = Date.now();
5158
+ if (language === "python") {
5159
+ if (!PY_PRECHECK.test(content)) return [];
5160
+ return pythonSnippets(content);
5161
+ }
5162
+ content = stripShellDocsOnly(content);
5163
+ if (literalStripper) content = literalStripper(content);
5164
+ if (!SHELL_PRECHECK.test(content)) return [];
5165
+ const snippets = lineSnippets(content, SHELL_PRECHECK);
5166
+ if (Date.now() - started > MAX_MS) {
5167
+ return snippets;
5168
+ }
5169
+ return snippets;
5170
+ }
5171
+ 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;
5172
+ var init_written_content_analyzer = __esm({
5173
+ "src/engine/written-content-analyzer.ts"() {
5174
+ "use strict";
5175
+ init_esm_shims();
5176
+ init_rules_loader();
5177
+ CFG = loadHeuristicRules().write_content_analysis || {};
5178
+ DATA_EXTS = new Set((CFG.data_exts || []).map((e) => e.toLowerCase()));
5179
+ SHELL_EXTS = new Set((CFG.shell_exts || []).map((e) => e.toLowerCase()));
5180
+ PY_EXTS = new Set((CFG.python_exts || []).map((e) => e.toLowerCase()));
5181
+ SHELL_PRECHECK = new RegExp(CFG.shell_precheck || "$^");
5182
+ PY_PRECHECK = new RegExp(CFG.python_precheck || "$^");
5183
+ MAX_CONTENT = Number(CFG.max_content_bytes || 262144);
5184
+ MAX_SCAN = Number(CFG.max_scan_bytes || 65536);
5185
+ MAX_MS = Number(CFG.max_scan_ms || 100);
5186
+ WRITE_TOOL_EXACT = /* @__PURE__ */ new Set([
5187
+ "write",
5188
+ "file_write",
5189
+ "writefile",
5190
+ "edit",
5191
+ "file_edit",
5192
+ "editfile",
5193
+ "searchreplace",
5194
+ "search_replace"
5195
+ ]);
5196
+ WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
5197
+ APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
5198
+ WRITE_PREFIX_RE = /^(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*(.+?)\s*(?:\(\s*追加\s*\))?\s*—\s*([\s\S]*)$/;
5199
+ EDIT_NEW_RE = /\|\s*new:\s*([\s\S]*)$/i;
5200
+ INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
5201
+ QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
5202
+ 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;
5203
+ HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
5204
+ }
5205
+ });
5206
+
4869
5207
  // src/engine/heuristic.ts
4870
5208
  function _effectiveDangerousPatterns(osType) {
4871
5209
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
@@ -4973,8 +5311,16 @@ function runHeuristicCheck(input) {
4973
5311
  } catch {
4974
5312
  }
4975
5313
  }
4976
- const scanDetail = normalizePathSegments(stripLiteralTextSegments(input.aNext.actionDetail));
4977
- const scanCommands = String(input.osType || "").toLowerCase() === "windows" ? [
5314
+ const scanDetail = normalizePathSegments(
5315
+ stripLiteralTextSegments(stripShellDocsOnly(input.aNext.actionDetail))
5316
+ );
5317
+ const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
5318
+ const writeSnippets = extractDangerousSnippets(
5319
+ input.aNext.actionType,
5320
+ input.aNext.actionDetail,
5321
+ stripLiteralTextSegments
5322
+ );
5323
+ const scanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => [`${input.aNext.actionType}: ${sn}`, sn]) : String(input.osType || "").toLowerCase() === "windows" ? [
4978
5324
  `${input.aNext.actionType}: ${scanDetail}`,
4979
5325
  scanDetail,
4980
5326
  `${input.aNext.actionType}: ${scanDetail.replace(/\//g, "\\")}`,
@@ -5035,9 +5381,9 @@ function runHeuristicCheck(input) {
5035
5381
  const actionTypeL = input.aNext.actionType.toLowerCase();
5036
5382
  const detailL = input.aNext.actionDetail.toLowerCase();
5037
5383
  const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
5038
- const dangerousResult = checkDangerousPatterns(actionTypeL, detailL);
5384
+ const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
5039
5385
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
5040
- const homeResult = checkHomeDeletion(actionTypeL, detailL);
5386
+ const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
5041
5387
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
5042
5388
  if (mergeResults.length > 0) {
5043
5389
  let best = mergeResults[0];
@@ -5535,7 +5881,7 @@ function isSshKeygenGenerate(command) {
5535
5881
  }
5536
5882
  function checkDangerousPatterns(actionType, actionDetail) {
5537
5883
  if (actionType === "file_write" || actionType === "file_edit") return null;
5538
- const scan = stripHeredocContent(actionDetail);
5884
+ const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
5539
5885
  const isTempPath = TEMP_DIRS2.some(
5540
5886
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
5541
5887
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
@@ -5693,6 +6039,7 @@ var init_heuristic = __esm({
5693
6039
  init_runtime_config();
5694
6040
  init_runtime_config_bridge();
5695
6041
  init_rules_loader();
6042
+ init_written_content_analyzer();
5696
6043
  init_logic_rules();
5697
6044
  INJECTION_KEYWORDS = (() => {
5698
6045
  const kws = loadL1().injection_detection || [];
@@ -7438,7 +7785,7 @@ var init_tracker = __esm({
7438
7785
  });
7439
7786
 
7440
7787
  // src/engine/script-content-analyzer.ts
7441
- import { statSync as statSync4, existsSync as existsSync12 } from "fs";
7788
+ import { statSync as statSync5, existsSync as existsSync12 } from "fs";
7442
7789
  import { resolve as resolve10, join as join12, isAbsolute as isAbsolute4 } from "path";
7443
7790
  import { homedir as homedir5 } from "os";
7444
7791
  function emptyChain() {
@@ -7552,7 +7899,7 @@ function extractInlineScriptPath(actionDetail) {
7552
7899
  try {
7553
7900
  const resolved = resolvePath2(tok.replace(/^['"]|['"]$/g, ""));
7554
7901
  if (existsSync12(resolved)) {
7555
- const stat = statSync4(resolved);
7902
+ const stat = statSync5(resolved);
7556
7903
  if (stat.isFile()) return resolved;
7557
7904
  }
7558
7905
  } catch {
@@ -7566,7 +7913,7 @@ function extractInlineScriptPath(actionDetail) {
7566
7913
  try {
7567
7914
  const resolved = resolvePath2(p);
7568
7915
  if (existsSync12(resolved)) {
7569
- const stat = statSync4(resolved);
7916
+ const stat = statSync5(resolved);
7570
7917
  if (stat.isFile()) return resolved;
7571
7918
  }
7572
7919
  } catch {
@@ -7582,7 +7929,7 @@ function extractInlineScriptPath(actionDetail) {
7582
7929
  try {
7583
7930
  resolved = resolvePath2(p);
7584
7931
  if (existsSync12(resolved)) {
7585
- const stat = statSync4(resolved);
7932
+ const stat = statSync5(resolved);
7586
7933
  if (stat.isFile()) return resolved;
7587
7934
  }
7588
7935
  } catch {
@@ -8331,7 +8678,7 @@ __export(token_stats_exports, {
8331
8678
  resetTokenStats: () => resetTokenStats,
8332
8679
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
8333
8680
  });
8334
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync5 } from "fs";
8681
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
8335
8682
  function getStatsPath() {
8336
8683
  const envPath = process.env[ENV_STATS_PATH];
8337
8684
  if (envPath) return envPath;
@@ -8341,7 +8688,7 @@ function loadAllRecords(statsPath) {
8341
8688
  if (!existsSync13(statsPath)) return [];
8342
8689
  let sig = "";
8343
8690
  try {
8344
- const st = statSync5(statsPath);
8691
+ const st = statSync6(statsPath);
8345
8692
  sig = `${st.mtimeMs}:${st.size}`;
8346
8693
  } catch {
8347
8694
  return [];
@@ -8367,7 +8714,7 @@ function saveRecords(statsPath, records) {
8367
8714
  if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
8368
8715
  writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
8369
8716
  try {
8370
- const st = statSync5(statsPath);
8717
+ const st = statSync6(statsPath);
8371
8718
  _recordsCache = {
8372
8719
  path: statsPath,
8373
8720
  sig: `${st.mtimeMs}:${st.size}`,
@@ -10436,6 +10783,7 @@ function extractResources(actionDetail) {
10436
10783
  while ((m = PATH_RE.exec(text)) !== null) {
10437
10784
  const p = m[1];
10438
10785
  if (p.startsWith("/dev/") || p.includes("://")) continue;
10786
+ if (COMMON_DIR_RESOURCES.has(p) || p.endsWith("/")) continue;
10439
10787
  resources.add(p);
10440
10788
  }
10441
10789
  return resources;
@@ -10570,7 +10918,7 @@ function allNodesFlat(mg) {
10570
10918
  for (const s of mg.sessions) out.push(...s.nodes);
10571
10919
  return out;
10572
10920
  }
10573
- var COMBO_STAGES2, PATH_RE;
10921
+ var COMBO_STAGES2, PATH_RE, COMMON_DIR_RESOURCES;
10574
10922
  var init_builder = __esm({
10575
10923
  "src/engine/formal-engine/builder.ts"() {
10576
10924
  "use strict";
@@ -10580,6 +10928,19 @@ var init_builder = __esm({
10580
10928
  init_ltl();
10581
10929
  COMBO_STAGES2 = null;
10582
10930
  PATH_RE = /(?:^|\s|[@=])((?:\/|~\/)[\w./~-]+)/g;
10931
+ COMMON_DIR_RESOURCES = /* @__PURE__ */ new Set([
10932
+ "/",
10933
+ "/tmp",
10934
+ "/var/tmp",
10935
+ "/dev/shm",
10936
+ "/home",
10937
+ "/root",
10938
+ "/usr",
10939
+ "/etc",
10940
+ "/var",
10941
+ "/data",
10942
+ "/storage"
10943
+ ]);
10583
10944
  }
10584
10945
  });
10585
10946
 
@@ -11356,6 +11717,7 @@ function extractResources2(actionDetail) {
11356
11717
  while ((m = re.exec(text)) !== null) {
11357
11718
  const p = m[1];
11358
11719
  if (p.startsWith("/dev/") || p.includes("://")) continue;
11720
+ if (COMMON_DIR_RESOURCES2.has(p) || p.endsWith("/")) continue;
11359
11721
  if (!out.includes(p)) out.push(p);
11360
11722
  }
11361
11723
  return out;
@@ -11369,7 +11731,7 @@ function lifecycleFor(detail, stage, isError) {
11369
11731
  if (detail.includes(">>") || detail.includes(">")) return "alive";
11370
11732
  return "";
11371
11733
  }
11372
- var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, STAGES_PATTERNS, CHAINS, MAX_NODES, StatefulChainTracker;
11734
+ var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, STAGES_PATTERNS, CHAINS, COMMON_DIR_RESOURCES2, MAX_NODES, StatefulChainTracker;
11373
11735
  var init_stateful = __esm({
11374
11736
  "src/engine/formal-engine/stateful.ts"() {
11375
11737
  "use strict";
@@ -11387,6 +11749,19 @@ var init_stateful = __esm({
11387
11749
  PORT_STAGE_RE = /LISTEN|PERSIST|SCAN/;
11388
11750
  STAGES_PATTERNS = null;
11389
11751
  CHAINS = null;
11752
+ COMMON_DIR_RESOURCES2 = /* @__PURE__ */ new Set([
11753
+ "/",
11754
+ "/tmp",
11755
+ "/var/tmp",
11756
+ "/dev/shm",
11757
+ "/home",
11758
+ "/root",
11759
+ "/usr",
11760
+ "/etc",
11761
+ "/var",
11762
+ "/data",
11763
+ "/storage"
11764
+ ]);
11390
11765
  MAX_NODES = 1e5;
11391
11766
  StatefulChainTracker = class _StatefulChainTracker {
11392
11767
  /** 本地接收时刻(实时路径无 called_at 时的兜底时间戳,ISO)。 */