@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/server.js CHANGED
@@ -1550,6 +1550,46 @@ function getSensitivePathsForOsBuiltin(osType) {
1550
1550
  }
1551
1551
  return { root: ROOT_SENSITIVE_PATHS, home: HOME_SENSITIVE_PATHS, credential: CREDENTIAL_PATHS };
1552
1552
  }
1553
+ function isPreciseEditTool(actionType) {
1554
+ const at = (actionType || "").toLowerCase();
1555
+ if (PRECISE_EDIT_TOOLS.has(at)) return true;
1556
+ for (const s of PRECISE_EDIT_TOOLS) if (at.endsWith(s)) return true;
1557
+ return false;
1558
+ }
1559
+ function isFullOverwriteTool(actionType, extraTools) {
1560
+ const at = (actionType || "").toLowerCase();
1561
+ 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));
1562
+ if (!isWriteTool) return false;
1563
+ return !isPreciseEditTool(at);
1564
+ }
1565
+ function stripHeredocBody(text) {
1566
+ if (!text || INTERP_HEREDOC_HINT_RE.test(text)) return text;
1567
+ return text.replace(HEREDOC_BODY_RE, "<<heredoc>>\n");
1568
+ }
1569
+ function isDirectoryTarget(p) {
1570
+ if (!p) return false;
1571
+ if (p.endsWith("/")) return true;
1572
+ try {
1573
+ return fs.statSync(p).isDirectory();
1574
+ } catch {
1575
+ return false;
1576
+ }
1577
+ }
1578
+ function intentActionText(actionType, actionDetail) {
1579
+ let text = actionDetail || "";
1580
+ const at = (actionType || "").toLowerCase();
1581
+ if (at === "bash" || at === "executebash" || at === "terminal-executebash") {
1582
+ text = stripHeredocBody(text);
1583
+ text = text.replace(/(?<!\S)#[^\n]*/g, "");
1584
+ text = text.replace(/'[^']*'|"[^"]*"/g, "");
1585
+ return text;
1586
+ }
1587
+ const m = text.match(/^([\s\S]*?)\s*—\s*[\s\S]*$/);
1588
+ if (m) text = m[1];
1589
+ const m2 = text.match(/^(搜索|search|查找)\s*[::]\s*([\s\S]*?)\s+in\s+([\s\S]*)$/i);
1590
+ if (m2) text = `${m2[1]}: in ${m2[3]}`;
1591
+ return text;
1592
+ }
1553
1593
  function declaredWritePaths(actionDetailRaw, osType) {
1554
1594
  const m = actionDetailRaw.match(DECLARED_WRITE_PATH_RE);
1555
1595
  if (m) return [m[1]];
@@ -1821,11 +1861,12 @@ function checkIntentConsistency(input) {
1821
1861
  if (EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p))) return null;
1822
1862
  if (INLINE_SCRIPT_RE.test(actionDetail)) return null;
1823
1863
  const intentTexts = collectIntentTexts(promptSession, promptHistory);
1864
+ const dangerousText = intentActionText(actionType, actionDetail);
1824
1865
  for (const pattern of getIntentPatternsForOs(input.osType)) {
1825
1866
  const intentMatched = intentTexts.some(
1826
1867
  (text) => pattern.intentKeywords.some((kw) => text.includes(kw))
1827
1868
  );
1828
- const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(actionDetail, kw));
1869
+ const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(dangerousText, kw));
1829
1870
  if (intentMatched && dangerousMatched) {
1830
1871
  if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
1831
1872
  continue;
@@ -1963,11 +2004,15 @@ function extractFilePaths(text, osType) {
1963
2004
  return [...new Set(paths)];
1964
2005
  }
1965
2006
  function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason, cwd, osType, singleFileTools = SINGLE_FILE_WRITE_TOOLS) {
2007
+ actionDetailRaw = stripHeredocBody(actionDetailRaw);
1966
2008
  const actionDetail = actionDetailRaw.toLowerCase();
1967
2009
  if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
1968
2010
  if (NON_WRITE_TOOLS.has(actionType)) return null;
1969
2011
  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));
2012
+ let isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
2013
+ if (!isWrite && /\btar\b/.test(actionDetail) && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(actionDetail)) {
2014
+ isWrite = true;
2015
+ }
1971
2016
  if (!isWrite) return null;
1972
2017
  const WRITE_CMDS = new Set(_LOGIC.write_commands ?? []);
1973
2018
  if (isBashLike) {
@@ -1989,6 +2034,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1989
2034
  hasWriteSeg = true;
1990
2035
  break;
1991
2036
  }
2037
+ 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)) {
2038
+ hasWriteSeg = true;
2039
+ break;
2040
+ }
1992
2041
  if ((fw === "wget" || fw === "curl") && (/\s(?:-O|--output-document|--output)(?:=|\s|$)/i.test(trimmed) || /\s-O\S/.test(trimmed))) {
1993
2042
  hasWriteSeg = true;
1994
2043
  break;
@@ -2015,6 +2064,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2015
2064
  if (firstWord === "cd") {
2016
2065
  continue;
2017
2066
  }
2067
+ if (SHELL_ASSIGN_RE.test(trimmed)) {
2068
+ continue;
2069
+ }
2018
2070
  if (firstWord === "sed" && SED_INPLACE_RE.test(trimmed)) {
2019
2071
  } else if (getPlatformTraits(osType).readOnlyCommands.has(firstWord)) {
2020
2072
  const segUnquoted = trimmed.replace(new RegExp(`>{1,2}\\s*(['"])([~./][^'"]+)\\1`, "g"), (_m, _q, p) => ">" + p);
@@ -2028,6 +2080,11 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2028
2080
  const segPathsFiltered = firstWord === "wget" || firstWord === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
2029
2081
  if (SOURCE_ARG_CMDS.has(firstWord)) {
2030
2082
  if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
2083
+ } else if (firstWord === "tar") {
2084
+ if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
2085
+ const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
2086
+ if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
2087
+ }
2031
2088
  } else if (firstWord === "dd") {
2032
2089
  const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
2033
2090
  const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
@@ -2048,6 +2105,7 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2048
2105
  if (uniqueTargetPaths.length === 0) return null;
2049
2106
  const historyFullReadPaths = /* @__PURE__ */ new Set();
2050
2107
  const historyPartialRead = /* @__PURE__ */ new Map();
2108
+ const historyWrittenPaths = /* @__PURE__ */ new Set();
2051
2109
  for (const action of actionHistory) {
2052
2110
  const histDetailRaw = action.actionDetail;
2053
2111
  const histType = action.actionType.toLowerCase();
@@ -2059,6 +2117,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2059
2117
  traits.writeKeywords
2060
2118
  );
2061
2119
  for (const p of coverage.full) historyFullReadPaths.add(p);
2120
+ if (isFullOverwriteTool(histType, singleFileTools) && !APPEND_MODE_RE.test(histDetailRaw)) {
2121
+ for (const p of declaredWritePaths(histDetailRaw, osType)) historyWrittenPaths.add(p);
2122
+ }
2062
2123
  for (const [p, upto] of coverage.partial) {
2063
2124
  if (historyPartialRead.has(p)) {
2064
2125
  const old = historyPartialRead.get(p);
@@ -2081,6 +2142,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2081
2142
  const normalizedFullReads = new Set(
2082
2143
  [...historyFullReadPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2083
2144
  );
2145
+ const normalizedWrittenPaths = new Set(
2146
+ [...historyWrittenPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2147
+ );
2084
2148
  const normalizedPartialReads = /* @__PURE__ */ new Map();
2085
2149
  for (const [p, upto] of historyPartialRead) {
2086
2150
  const np = normalizePathForCompare(p, cwd);
@@ -2098,16 +2162,23 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2098
2162
  checkTargets = normalizedTargets.filter((p) => !([...appendNorm].some((ap) => pathIsSameOrUnder(p, ap) || pathIsSameOrUnder(ap, p)) && !isProtectedWritePath(p)));
2099
2163
  if (checkTargets.length === 0) return null;
2100
2164
  }
2165
+ const preciseEdit = isPreciseEditTool(actionType);
2101
2166
  const unreadPaths = [];
2102
2167
  for (const path8 of checkTargets) {
2103
- const isFullRead = [...normalizedFullReads].some(
2168
+ if (isDirectoryTarget(path8)) continue;
2169
+ let isFullRead = [...normalizedFullReads].some(
2104
2170
  (rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
2105
2171
  );
2172
+ if (!isFullRead && preciseEdit && [...normalizedWrittenPaths].some(
2173
+ (wp) => pathIsSameOrUnder(path8, wp) || pathIsSameOrUnder(wp, path8)
2174
+ )) {
2175
+ isFullRead = true;
2176
+ }
2106
2177
  let isPartialCovered = false;
2107
2178
  if (!isFullRead) {
2108
2179
  for (const [pp, upto] of normalizedPartialReads) {
2109
2180
  if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
2110
- if (upto != null && fileHasAtMostLines(path8, upto)) {
2181
+ if (preciseEdit || upto != null && fileHasAtMostLines(path8, upto)) {
2111
2182
  isPartialCovered = true;
2112
2183
  break;
2113
2184
  }
@@ -2296,7 +2367,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2296
2367
  violatedLayers: ["L2.1"]
2297
2368
  };
2298
2369
  }
2299
- 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;
2370
+ 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;
2300
2371
  var init_logic_rules = __esm({
2301
2372
  "src/engine/logic-rules.ts"() {
2302
2373
  "use strict";
@@ -2348,6 +2419,12 @@ var init_logic_rules = __esm({
2348
2419
  SINGLE_FILE_WRITE_TOOLS = new Set(
2349
2420
  _LOGIC.single_file_write_tools ?? []
2350
2421
  );
2422
+ PRECISE_EDIT_TOOLS = new Set(
2423
+ _LOGIC.precise_edit_write_tools ?? []
2424
+ );
2425
+ 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;
2426
+ HEREDOC_BODY_RE = /<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n[\s\S]*?\n\s*\2\s*(?:\n|$)/g;
2427
+ SHELL_ASSIGN_RE = /^(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=/;
2351
2428
  WRITE_INTENT_KEYWORDS = _LOGIC.write_intent_keywords ?? [];
2352
2429
  MISSING_WRITE_PATH_RE = /(?:写入文件|编辑文件|写入|编辑)\s*[::]\s*\?/;
2353
2430
  DECLARED_WRITE_PATH_RE = /(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*([~./][^\s—|,;]+)/;
@@ -2644,7 +2721,7 @@ __export(runtime_config_exports, {
2644
2721
  updateSkillCategoryEnabled: () => updateSkillCategoryEnabled,
2645
2722
  updateSkillEnabled: () => updateSkillEnabled
2646
2723
  });
2647
- import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
2724
+ import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
2648
2725
  import { join as join7 } from "path";
2649
2726
  import { fileURLToPath as fileURLToPath4 } from "url";
2650
2727
  import { dirname as dirname4 } from "path";
@@ -2660,7 +2737,7 @@ function getRuleSourceFingerprint() {
2660
2737
  if (isRuntimeConfigDisabled()) return `mode:${getRulesMode()}`;
2661
2738
  const p = getRuntimeConfigPath();
2662
2739
  try {
2663
- const st = statSync2(p);
2740
+ const st = statSync3(p);
2664
2741
  return `${p}|${st.mtimeMs}|${st.size}`;
2665
2742
  } catch {
2666
2743
  return `${p}|absent`;
@@ -2717,7 +2794,7 @@ function loadRuntimeConfig() {
2717
2794
  return seeded;
2718
2795
  }
2719
2796
  try {
2720
- const st = statSync2(p);
2797
+ const st = statSync3(p);
2721
2798
  const cacheKey = `${p}|${st.mtimeMs}|${st.size}`;
2722
2799
  if (runtimeConfigCache && runtimeConfigCache.key === cacheKey) {
2723
2800
  return runtimeConfigCache.value;
@@ -2861,7 +2938,7 @@ function hasRuntimeConfig() {
2861
2938
  const p = getRuntimeConfigPath();
2862
2939
  let key;
2863
2940
  try {
2864
- const st = statSync2(p);
2941
+ const st = statSync3(p);
2865
2942
  key = `${p}|${st.mtimeMs}|${st.size}`;
2866
2943
  } catch {
2867
2944
  return false;
@@ -3495,7 +3572,9 @@ function getEnabledL2IntentPatterns(runtime, osType) {
3495
3572
  return rules.map((r) => ({
3496
3573
  intent_keywords: r.intent_keywords || [],
3497
3574
  dangerous_actions: r.dangerous_actions || [],
3498
- reason: r.reason || ""
3575
+ reason: r.reason || "",
3576
+ allow_if_write_intent: r.allow_if_write_intent === true,
3577
+ os: r.os
3499
3578
  }));
3500
3579
  }
3501
3580
  function getEnabledL2PasswordPatterns(runtime) {
@@ -4566,6 +4645,265 @@ var init_scenarios = __esm({
4566
4645
  }
4567
4646
  });
4568
4647
 
4648
+ // src/engine/written-content-analyzer.ts
4649
+ function isFileWriteAction(actionType) {
4650
+ const at = (actionType || "").toLowerCase();
4651
+ if (WRITE_TOOL_EXACT.has(at)) return true;
4652
+ if (WRITE_TOOL_SUFFIXES.some((s) => at.endsWith(s))) return true;
4653
+ return false;
4654
+ }
4655
+ function isApplyPatch(actionType) {
4656
+ const at = (actionType || "").toLowerCase();
4657
+ return APPLY_PATCH_SUFFIXES.some((s) => at.endsWith(s));
4658
+ }
4659
+ function extractWritePayload(actionType, actionDetailRaw) {
4660
+ if (isApplyPatch(actionType)) return null;
4661
+ const detail = actionDetailRaw || "";
4662
+ const m = detail.match(WRITE_PREFIX_RE);
4663
+ if (m) {
4664
+ const path8 = m[1];
4665
+ let content = m[2] || "";
4666
+ if (!path8 || path8 === "?" || path8 === "-" || !content.trim()) return null;
4667
+ if ((actionType || "").toLowerCase().includes("editfile")) {
4668
+ const nm = content.match(EDIT_NEW_RE);
4669
+ if (nm) content = nm[1];
4670
+ }
4671
+ return { path: path8, content };
4672
+ }
4673
+ const stripped = detail.trim();
4674
+ if (stripped.startsWith("{")) {
4675
+ try {
4676
+ const obj = JSON.parse(stripped);
4677
+ if (obj && typeof obj === "object") {
4678
+ const path8 = obj.path || obj.file_path || obj.filePath;
4679
+ const content = obj.content || obj.newString || obj.new_string;
4680
+ if (typeof path8 === "string" && path8 !== "" && path8 !== "?" && path8 !== "-" && typeof content === "string" && content.trim()) {
4681
+ return { path: path8, content };
4682
+ }
4683
+ }
4684
+ } catch {
4685
+ }
4686
+ }
4687
+ return null;
4688
+ }
4689
+ function handlesWrittenContent(actionType, actionDetailRaw) {
4690
+ if (!isFileWriteAction(actionType)) return false;
4691
+ if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
4692
+ return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
4693
+ }
4694
+ function detectLanguage(path8, content) {
4695
+ const ext = path8.slice(path8.lastIndexOf(".") >= 0 ? path8.lastIndexOf(".") : path8.length).toLowerCase();
4696
+ if (SHELL_EXTS.has(ext)) return "shell";
4697
+ if (PY_EXTS.has(ext)) return "python";
4698
+ if (DATA_EXTS.has(ext)) return "data";
4699
+ if (!ext) {
4700
+ const first = content.trim() ? content.trim().split(/\r?\n/)[0] : "";
4701
+ if (first.startsWith("#!")) {
4702
+ if (/\b(?:ba|z|k|da)?sh\b/.test(first)) return "shell";
4703
+ if (first.includes("python")) return "python";
4704
+ }
4705
+ return "data";
4706
+ }
4707
+ return "other";
4708
+ }
4709
+ function stripShellComments(text) {
4710
+ const out = [];
4711
+ let heredocEnd = null;
4712
+ for (const line of text.split(/\r?\n/)) {
4713
+ if (heredocEnd !== null) {
4714
+ out.push(line);
4715
+ if (line.trim() === heredocEnd) heredocEnd = null;
4716
+ continue;
4717
+ }
4718
+ const hm = line.match(HEREDOC_START_RE);
4719
+ if (hm) heredocEnd = hm[1];
4720
+ const res = [];
4721
+ let quote = null;
4722
+ for (let i = 0; i < line.length; i++) {
4723
+ const ch = line[i];
4724
+ if (quote) {
4725
+ res.push(ch);
4726
+ if (ch === quote) quote = null;
4727
+ continue;
4728
+ }
4729
+ if (ch === "'" || ch === '"') {
4730
+ quote = ch;
4731
+ res.push(ch);
4732
+ continue;
4733
+ }
4734
+ if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) break;
4735
+ res.push(ch);
4736
+ }
4737
+ out.push(res.join(""));
4738
+ }
4739
+ return out.join("\n");
4740
+ }
4741
+ function stripShellDocsOnly(content) {
4742
+ if (!content) return content;
4743
+ if (INTERP_HEREDOC_RE.test(content)) return content;
4744
+ const withoutHeredoc = content.replace(QUOTED_HEREDOC_RE, "<<quoted-heredoc>>\n");
4745
+ return stripShellComments(withoutHeredoc);
4746
+ }
4747
+ function lineSnippets(content, precheck) {
4748
+ const lines = content.split(/\r?\n/);
4749
+ const picked = /* @__PURE__ */ new Set();
4750
+ for (let i = 0; i < lines.length; i++) {
4751
+ precheck.lastIndex = 0;
4752
+ if (precheck.test(lines[i])) {
4753
+ picked.add(i - 1);
4754
+ picked.add(i);
4755
+ picked.add(i + 1);
4756
+ }
4757
+ }
4758
+ const snippets = [];
4759
+ let total = 0;
4760
+ for (const i of [...picked].sort((a, b) => a - b)) {
4761
+ if (i < 0 || i >= lines.length) continue;
4762
+ const s = lines[i];
4763
+ if (total + s.length > MAX_SCAN) break;
4764
+ snippets.push(s);
4765
+ total += s.length + 1;
4766
+ }
4767
+ return snippets;
4768
+ }
4769
+ function stripPythonLiterals(content) {
4770
+ const chars = content.split("");
4771
+ let i = 0;
4772
+ const n = chars.length;
4773
+ while (i < n) {
4774
+ const ch = chars[i];
4775
+ if (ch === "#") {
4776
+ while (i < n && chars[i] !== "\n") {
4777
+ chars[i] = " ";
4778
+ i++;
4779
+ }
4780
+ continue;
4781
+ }
4782
+ if (ch === "'" || ch === '"') {
4783
+ const triple = chars[i + 1] === ch && chars[i + 2] === ch;
4784
+ const quoteLen = triple ? 3 : 1;
4785
+ const q = ch;
4786
+ i += quoteLen;
4787
+ while (i < n) {
4788
+ if (chars[i] === "\\") {
4789
+ chars[i] = " ";
4790
+ if (i + 1 < n) chars[i + 1] = " ";
4791
+ i += 2;
4792
+ continue;
4793
+ }
4794
+ if (chars[i] === q && (!triple || chars[i + 1] === q && chars[i + 2] === q)) {
4795
+ for (let k = 0; k < quoteLen; k++) {
4796
+ chars[i + k] = " ";
4797
+ }
4798
+ i += quoteLen;
4799
+ break;
4800
+ }
4801
+ chars[i] = " ";
4802
+ i++;
4803
+ }
4804
+ continue;
4805
+ }
4806
+ i++;
4807
+ }
4808
+ return chars.join("");
4809
+ }
4810
+ function balancedArgs(original, openIndex) {
4811
+ let depth = 0;
4812
+ let quote = null;
4813
+ for (let i = openIndex; i < original.length && i < openIndex + 8e3; i++) {
4814
+ const ch = original[i];
4815
+ if (quote) {
4816
+ if (ch === "\\") {
4817
+ i++;
4818
+ continue;
4819
+ }
4820
+ if (ch === quote) quote = null;
4821
+ continue;
4822
+ }
4823
+ if (ch === "'" || ch === '"') {
4824
+ quote = ch;
4825
+ continue;
4826
+ }
4827
+ if (ch === "(") depth++;
4828
+ else if (ch === ")") {
4829
+ depth--;
4830
+ if (depth === 0) return original.slice(openIndex + 1, i);
4831
+ }
4832
+ }
4833
+ return original.slice(openIndex + 1, Math.min(original.length, openIndex + 2e3));
4834
+ }
4835
+ function pythonSnippets(content) {
4836
+ const stripped = stripPythonLiterals(content);
4837
+ const snippets = [];
4838
+ PY_DANGEROUS_CALL_RE.lastIndex = 0;
4839
+ let m;
4840
+ while ((m = PY_DANGEROUS_CALL_RE.exec(stripped)) !== null) {
4841
+ const callName = m[0].replace(/\s*\($/, "").trim();
4842
+ const openIndex = m.index + m[0].length - 1;
4843
+ const args = balancedArgs(content, openIndex);
4844
+ snippets.push(`${callName}(${args})`);
4845
+ if (snippets.length >= 200) break;
4846
+ }
4847
+ return snippets;
4848
+ }
4849
+ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper) {
4850
+ if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
4851
+ const payload = extractWritePayload(actionType, actionDetailRaw);
4852
+ if (!payload) return [];
4853
+ const { path: path8, content: rawContent } = payload;
4854
+ const language = detectLanguage(path8, rawContent);
4855
+ if (language === "data") return [];
4856
+ let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
4857
+ const started = Date.now();
4858
+ if (language === "python") {
4859
+ if (!PY_PRECHECK.test(content)) return [];
4860
+ return pythonSnippets(content);
4861
+ }
4862
+ content = stripShellDocsOnly(content);
4863
+ if (literalStripper) content = literalStripper(content);
4864
+ if (!SHELL_PRECHECK.test(content)) return [];
4865
+ const snippets = lineSnippets(content, SHELL_PRECHECK);
4866
+ if (Date.now() - started > MAX_MS) {
4867
+ return snippets;
4868
+ }
4869
+ return snippets;
4870
+ }
4871
+ 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;
4872
+ var init_written_content_analyzer = __esm({
4873
+ "src/engine/written-content-analyzer.ts"() {
4874
+ "use strict";
4875
+ init_esm_shims();
4876
+ init_rules_loader();
4877
+ CFG = loadHeuristicRules().write_content_analysis || {};
4878
+ DATA_EXTS = new Set((CFG.data_exts || []).map((e) => e.toLowerCase()));
4879
+ SHELL_EXTS = new Set((CFG.shell_exts || []).map((e) => e.toLowerCase()));
4880
+ PY_EXTS = new Set((CFG.python_exts || []).map((e) => e.toLowerCase()));
4881
+ SHELL_PRECHECK = new RegExp(CFG.shell_precheck || "$^");
4882
+ PY_PRECHECK = new RegExp(CFG.python_precheck || "$^");
4883
+ MAX_CONTENT = Number(CFG.max_content_bytes || 262144);
4884
+ MAX_SCAN = Number(CFG.max_scan_bytes || 65536);
4885
+ MAX_MS = Number(CFG.max_scan_ms || 100);
4886
+ WRITE_TOOL_EXACT = /* @__PURE__ */ new Set([
4887
+ "write",
4888
+ "file_write",
4889
+ "writefile",
4890
+ "edit",
4891
+ "file_edit",
4892
+ "editfile",
4893
+ "searchreplace",
4894
+ "search_replace"
4895
+ ]);
4896
+ WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
4897
+ APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
4898
+ WRITE_PREFIX_RE = /^(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*(.+?)\s*(?:\(\s*追加\s*\))?\s*—\s*([\s\S]*)$/;
4899
+ EDIT_NEW_RE = /\|\s*new:\s*([\s\S]*)$/i;
4900
+ INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
4901
+ QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
4902
+ 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;
4903
+ HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
4904
+ }
4905
+ });
4906
+
4569
4907
  // src/engine/heuristic.ts
4570
4908
  function _effectiveDangerousPatterns(osType) {
4571
4909
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
@@ -4673,8 +5011,16 @@ function runHeuristicCheck(input) {
4673
5011
  } catch {
4674
5012
  }
4675
5013
  }
4676
- const scanDetail = normalizePathSegments(stripLiteralTextSegments(input.aNext.actionDetail));
4677
- const scanCommands = String(input.osType || "").toLowerCase() === "windows" ? [
5014
+ const scanDetail = normalizePathSegments(
5015
+ stripLiteralTextSegments(stripShellDocsOnly(input.aNext.actionDetail))
5016
+ );
5017
+ const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
5018
+ const writeSnippets = extractDangerousSnippets(
5019
+ input.aNext.actionType,
5020
+ input.aNext.actionDetail,
5021
+ stripLiteralTextSegments
5022
+ );
5023
+ const scanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => [`${input.aNext.actionType}: ${sn}`, sn]) : String(input.osType || "").toLowerCase() === "windows" ? [
4678
5024
  `${input.aNext.actionType}: ${scanDetail}`,
4679
5025
  scanDetail,
4680
5026
  `${input.aNext.actionType}: ${scanDetail.replace(/\//g, "\\")}`,
@@ -4735,9 +5081,9 @@ function runHeuristicCheck(input) {
4735
5081
  const actionTypeL = input.aNext.actionType.toLowerCase();
4736
5082
  const detailL = input.aNext.actionDetail.toLowerCase();
4737
5083
  const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
4738
- const dangerousResult = checkDangerousPatterns(actionTypeL, detailL);
5084
+ const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
4739
5085
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
4740
- const homeResult = checkHomeDeletion(actionTypeL, detailL);
5086
+ const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
4741
5087
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
4742
5088
  if (mergeResults.length > 0) {
4743
5089
  let best = mergeResults[0];
@@ -5235,7 +5581,7 @@ function isSshKeygenGenerate(command) {
5235
5581
  }
5236
5582
  function checkDangerousPatterns(actionType, actionDetail) {
5237
5583
  if (actionType === "file_write" || actionType === "file_edit") return null;
5238
- const scan = stripHeredocContent(actionDetail);
5584
+ const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
5239
5585
  const isTempPath = TEMP_DIRS2.some(
5240
5586
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
5241
5587
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
@@ -5393,6 +5739,7 @@ var init_heuristic = __esm({
5393
5739
  init_runtime_config();
5394
5740
  init_runtime_config_bridge();
5395
5741
  init_rules_loader();
5742
+ init_written_content_analyzer();
5396
5743
  init_logic_rules();
5397
5744
  INJECTION_KEYWORDS = (() => {
5398
5745
  const kws = loadL1().injection_detection || [];
@@ -7138,7 +7485,7 @@ var init_tracker = __esm({
7138
7485
  });
7139
7486
 
7140
7487
  // src/engine/script-content-analyzer.ts
7141
- import { statSync as statSync4, existsSync as existsSync12 } from "fs";
7488
+ import { statSync as statSync5, existsSync as existsSync12 } from "fs";
7142
7489
  import { resolve as resolve10, join as join12, isAbsolute as isAbsolute4 } from "path";
7143
7490
  import { homedir as homedir5 } from "os";
7144
7491
  function emptyChain() {
@@ -7252,7 +7599,7 @@ function extractInlineScriptPath(actionDetail) {
7252
7599
  try {
7253
7600
  const resolved = resolvePath2(tok.replace(/^['"]|['"]$/g, ""));
7254
7601
  if (existsSync12(resolved)) {
7255
- const stat = statSync4(resolved);
7602
+ const stat = statSync5(resolved);
7256
7603
  if (stat.isFile()) return resolved;
7257
7604
  }
7258
7605
  } catch {
@@ -7266,7 +7613,7 @@ function extractInlineScriptPath(actionDetail) {
7266
7613
  try {
7267
7614
  const resolved = resolvePath2(p);
7268
7615
  if (existsSync12(resolved)) {
7269
- const stat = statSync4(resolved);
7616
+ const stat = statSync5(resolved);
7270
7617
  if (stat.isFile()) return resolved;
7271
7618
  }
7272
7619
  } catch {
@@ -7282,7 +7629,7 @@ function extractInlineScriptPath(actionDetail) {
7282
7629
  try {
7283
7630
  resolved = resolvePath2(p);
7284
7631
  if (existsSync12(resolved)) {
7285
- const stat = statSync4(resolved);
7632
+ const stat = statSync5(resolved);
7286
7633
  if (stat.isFile()) return resolved;
7287
7634
  }
7288
7635
  } catch {
@@ -8031,7 +8378,7 @@ __export(token_stats_exports, {
8031
8378
  resetTokenStats: () => resetTokenStats,
8032
8379
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
8033
8380
  });
8034
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync5 } from "fs";
8381
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
8035
8382
  function getStatsPath() {
8036
8383
  const envPath = process.env[ENV_STATS_PATH];
8037
8384
  if (envPath) return envPath;
@@ -8041,7 +8388,7 @@ function loadAllRecords(statsPath) {
8041
8388
  if (!existsSync13(statsPath)) return [];
8042
8389
  let sig = "";
8043
8390
  try {
8044
- const st = statSync5(statsPath);
8391
+ const st = statSync6(statsPath);
8045
8392
  sig = `${st.mtimeMs}:${st.size}`;
8046
8393
  } catch {
8047
8394
  return [];
@@ -8067,7 +8414,7 @@ function saveRecords(statsPath, records) {
8067
8414
  if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
8068
8415
  writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
8069
8416
  try {
8070
- const st = statSync5(statsPath);
8417
+ const st = statSync6(statsPath);
8071
8418
  _recordsCache = {
8072
8419
  path: statsPath,
8073
8420
  sig: `${st.mtimeMs}:${st.size}`,
@@ -9871,6 +10218,7 @@ function extractResources(actionDetail) {
9871
10218
  while ((m = PATH_RE.exec(text)) !== null) {
9872
10219
  const p = m[1];
9873
10220
  if (p.startsWith("/dev/") || p.includes("://")) continue;
10221
+ if (COMMON_DIR_RESOURCES.has(p) || p.endsWith("/")) continue;
9874
10222
  resources.add(p);
9875
10223
  }
9876
10224
  return resources;
@@ -10005,7 +10353,7 @@ function allNodesFlat(mg) {
10005
10353
  for (const s of mg.sessions) out.push(...s.nodes);
10006
10354
  return out;
10007
10355
  }
10008
- var COMBO_STAGES2, PATH_RE;
10356
+ var COMBO_STAGES2, PATH_RE, COMMON_DIR_RESOURCES;
10009
10357
  var init_builder = __esm({
10010
10358
  "src/engine/formal-engine/builder.ts"() {
10011
10359
  "use strict";
@@ -10015,6 +10363,19 @@ var init_builder = __esm({
10015
10363
  init_ltl();
10016
10364
  COMBO_STAGES2 = null;
10017
10365
  PATH_RE = /(?:^|\s|[@=])((?:\/|~\/)[\w./~-]+)/g;
10366
+ COMMON_DIR_RESOURCES = /* @__PURE__ */ new Set([
10367
+ "/",
10368
+ "/tmp",
10369
+ "/var/tmp",
10370
+ "/dev/shm",
10371
+ "/home",
10372
+ "/root",
10373
+ "/usr",
10374
+ "/etc",
10375
+ "/var",
10376
+ "/data",
10377
+ "/storage"
10378
+ ]);
10018
10379
  }
10019
10380
  });
10020
10381
 
@@ -10791,6 +11152,7 @@ function extractResources2(actionDetail) {
10791
11152
  while ((m = re.exec(text)) !== null) {
10792
11153
  const p = m[1];
10793
11154
  if (p.startsWith("/dev/") || p.includes("://")) continue;
11155
+ if (COMMON_DIR_RESOURCES2.has(p) || p.endsWith("/")) continue;
10794
11156
  if (!out.includes(p)) out.push(p);
10795
11157
  }
10796
11158
  return out;
@@ -10804,7 +11166,7 @@ function lifecycleFor(detail, stage, isError) {
10804
11166
  if (detail.includes(">>") || detail.includes(">")) return "alive";
10805
11167
  return "";
10806
11168
  }
10807
- 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;
11169
+ 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;
10808
11170
  var init_stateful = __esm({
10809
11171
  "src/engine/formal-engine/stateful.ts"() {
10810
11172
  "use strict";
@@ -10822,6 +11184,19 @@ var init_stateful = __esm({
10822
11184
  PORT_STAGE_RE = /LISTEN|PERSIST|SCAN/;
10823
11185
  STAGES_PATTERNS = null;
10824
11186
  CHAINS = null;
11187
+ COMMON_DIR_RESOURCES2 = /* @__PURE__ */ new Set([
11188
+ "/",
11189
+ "/tmp",
11190
+ "/var/tmp",
11191
+ "/dev/shm",
11192
+ "/home",
11193
+ "/root",
11194
+ "/usr",
11195
+ "/etc",
11196
+ "/var",
11197
+ "/data",
11198
+ "/storage"
11199
+ ]);
10825
11200
  MAX_NODES = 1e5;
10826
11201
  StatefulChainTracker = class _StatefulChainTracker {
10827
11202
  /** 本地接收时刻(实时路径无 called_at 时的兜底时间戳,ISO)。 */
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.27",
4
4
  "description": "Multi-layer security analysis engine for AI agents (TypeScript)",
5
5
  "type": "module",
6
6
  "main": "dist/server.js",