@kenhkl/agent-moss 0.17.27 → 0.17.29

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
@@ -1575,21 +1575,6 @@ function isDirectoryTarget(p) {
1575
1575
  return false;
1576
1576
  }
1577
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
- }
1593
1578
  function declaredWritePaths(actionDetailRaw, osType) {
1594
1579
  const m = actionDetailRaw.match(DECLARED_WRITE_PATH_RE);
1595
1580
  if (m) return [m[1]];
@@ -1809,78 +1794,128 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
1809
1794
  }
1810
1795
  return false;
1811
1796
  }
1812
- function getIntentPatternsForOs(osType) {
1813
- const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
1814
- if (effective) {
1815
- return effective.map((p) => ({
1816
- ...p,
1817
- allowIfWriteIntent: p.allowIfWriteIntent ?? INTENT_DEVIATION_PATTERNS.find((d) => d.reason === p.reason)?.allowIfWriteIntent ?? false
1818
- }));
1797
+ function intentCategories(text) {
1798
+ const t = (text || "").toLowerCase();
1799
+ const out = /* @__PURE__ */ new Set();
1800
+ for (const [cat, kws] of Object.entries(INTENT_CATEGORIES)) {
1801
+ if (kws.some((kw) => t.includes(String(kw).toLowerCase()))) out.add(cat);
1819
1802
  }
1820
- const accepted = acceptedOsValues(osType);
1821
- return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
1803
+ return out;
1822
1804
  }
1823
- function matchDangerousAction(actionDetail, action) {
1824
- if (/[^\x00-\x7f]/.test(action)) {
1825
- return actionDetail.includes(action);
1805
+ function actionCategory(actionType, actionDetailRaw, osType, extraWriteTools = /* @__PURE__ */ new Set()) {
1806
+ const at = (actionType || "").toLowerCase();
1807
+ const text = (actionDetailRaw || "").replace(DEVNULL_REDIRECT_RE, "");
1808
+ if (["delete", "remove", "rmdir", "unlink"].some((w) => at.includes(w))) return "delete";
1809
+ if (APPEND_MODE_RE.test(text)) return "append";
1810
+ if (/^(?:编辑文件|应用补丁)\s*[::]/.test(text)) return "overwrite";
1811
+ if (/^写入文件\s*[::]/.test(text)) {
1812
+ const paths = declaredWritePaths(text, osType);
1813
+ if (paths.length === 0) return "overwrite";
1814
+ const exists = paths.some((p) => {
1815
+ try {
1816
+ return fs.existsSync(p);
1817
+ } catch {
1818
+ return false;
1819
+ }
1820
+ });
1821
+ return exists ? "overwrite" : "create";
1826
1822
  }
1827
- const escaped = action.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1828
- const re = new RegExp(`(?<![-\\w])${escaped}\\b`, "i");
1829
- return re.test(actionDetail);
1830
- }
1831
- function collectIntentTexts(promptSession, promptHistory) {
1832
- const texts = [];
1833
- if (promptHistory) {
1834
- for (const turn of promptHistory) {
1835
- if (typeof turn === "string") {
1836
- const t2 = turn.trim();
1837
- if (t2) texts.push(t2.toLowerCase());
1838
- continue;
1823
+ if (isPreciseEditTool(at)) return "overwrite";
1824
+ if (isFullOverwriteTool(at, extraWriteTools)) {
1825
+ const paths = declaredWritePaths(text, osType);
1826
+ if (paths.length === 0) return "overwrite";
1827
+ const exists = paths.some((p) => {
1828
+ try {
1829
+ return fs.existsSync(p);
1830
+ } catch {
1831
+ return false;
1839
1832
  }
1840
- const t = (turn?.text || "").trim();
1841
- if (t) texts.push(t.toLowerCase());
1842
- }
1833
+ });
1834
+ return exists ? "overwrite" : "create";
1843
1835
  }
1844
- if (promptSession && promptSession.trim()) {
1845
- texts.push(promptSession.toLowerCase());
1836
+ for (const raw of splitCommandSegments(text)) {
1837
+ const s = raw.trim();
1838
+ if (!s) continue;
1839
+ const fw = (s.split(/\s+/)[0] || "").toLowerCase();
1840
+ if (DELETE_ACTION_WORDS.has(fw)) return "delete";
1841
+ if (fw === "sed" && SED_INPLACE_RE.test(s)) return "overwrite";
1842
+ if (["cp", "mv", "install", "rsync"].includes(fw)) return "overwrite";
1843
+ }
1844
+ if (text.includes(">>")) return "append";
1845
+ if (/(?<![/\-=<>])>\s*(?!&)\S/.test(text)) return "overwrite";
1846
+ return "read";
1847
+ }
1848
+ function intentMatrixViolation(intents, actionCat) {
1849
+ if (intents.size === 0) return null;
1850
+ if (actionCat === "overwrite") {
1851
+ if (intents.has("write")) return null;
1852
+ if (intents.has("delete") && !intents.has("read")) return "delete->overwrite";
1853
+ return "read->overwrite";
1854
+ }
1855
+ if (actionCat === "delete") {
1856
+ if (intents.has("delete")) return null;
1857
+ if (intents.has("write") && !intents.has("read")) return "write->delete";
1858
+ return "read->delete";
1846
1859
  }
1847
- const seen = /* @__PURE__ */ new Set();
1848
- const deduped = [];
1849
- for (const t of texts) {
1850
- if (!seen.has(t)) {
1851
- seen.add(t);
1852
- deduped.push(t);
1860
+ return null;
1861
+ }
1862
+ function resolveIntentText(promptSession, promptHistory, intentKeywords) {
1863
+ const cur = (promptSession || "").trim().toLowerCase();
1864
+ if (intentKeywords.some((kw) => cur.includes(kw))) return cur;
1865
+ if (!REFERENCE_PRIOR_RE.test(cur)) return cur;
1866
+ const turns = (promptHistory || []).slice(-REFERENCE_LOOKBACK);
1867
+ const candidates = [];
1868
+ for (let i = turns.length - 1; i >= 0; i--) {
1869
+ const turn = turns[i];
1870
+ const text = typeof turn === "string" ? turn.trim().toLowerCase() : (turn?.text || "").trim().toLowerCase();
1871
+ if (text && intentKeywords.some((kw) => text.includes(kw))) candidates.push(text);
1872
+ }
1873
+ if (candidates.length === 0) return cur;
1874
+ const firstCats = intentCategories(candidates[0]);
1875
+ for (const other of candidates.slice(1)) {
1876
+ const otherCats = intentCategories(other);
1877
+ const same = otherCats.size === firstCats.size && [...otherCats].every((c) => firstCats.has(c));
1878
+ if (!same) {
1879
+ console.debug(
1880
+ `[intent] \u6307\u4EE3\u524D\u6587\u7684\u56DE\u9000\u7ED3\u679C\u6709\u6B67\u4E49\uFF08\u591A\u6761\u5386\u53F2\u610F\u56FE\u7C7B\u522B\u4E0D\u4E00\u81F4\uFF09\uFF0C\u653E\u884C\u4EA4 L3\uFF1A\u5019\u9009=${candidates.map((c) => c.slice(0, 40)).join(" | ")}`
1881
+ );
1882
+ return cur;
1853
1883
  }
1854
1884
  }
1855
- return deduped;
1885
+ return candidates[0];
1856
1886
  }
1857
- function checkIntentConsistency(input) {
1887
+ function checkIntentConsistency(input, agentExt) {
1858
1888
  const { aNext, promptSession, promptHistory } = input;
1859
1889
  const actionDetail = aNext.actionDetail.toLowerCase();
1860
1890
  const actionType = aNext.actionType.toLowerCase();
1861
1891
  if (EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p))) return null;
1862
1892
  if (INLINE_SCRIPT_RE.test(actionDetail)) return null;
1863
- const intentTexts = collectIntentTexts(promptSession, promptHistory);
1864
- const dangerousText = intentActionText(actionType, actionDetail);
1865
- for (const pattern of getIntentPatternsForOs(input.osType)) {
1866
- const intentMatched = intentTexts.some(
1867
- (text) => pattern.intentKeywords.some((kw) => text.includes(kw))
1893
+ const extraWriteTools = new Set(agentExt?.extra_single_file_write_tools || []);
1894
+ const intentText = resolveIntentText(promptSession, promptHistory, ALL_INTENT_KEYWORDS);
1895
+ let intents = intentCategories(intentText);
1896
+ if (intents.size > 0 && EXEC_REFERENCE_RE.test(intentText) && !intents.has("delete")) {
1897
+ console.debug(
1898
+ `[intent] \u6307\u4EE4\u6307\u5411\u5916\u90E8\u6587\u4EF6/\u8981\u6C42\uFF08\u6267\u884C\u7C7B\u8868\u8FBE\uFF09\uFF0C\u610F\u56FE\u4E0D\u660E\u786E\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
1899
+ );
1900
+ intents = /* @__PURE__ */ new Set();
1901
+ }
1902
+ const actionCat = actionCategory(actionType, aNext.actionDetail, input.osType, extraWriteTools);
1903
+ const reasonKey = intentMatrixViolation(intents, actionCat);
1904
+ if (reasonKey !== null) {
1905
+ return {
1906
+ allowed: false,
1907
+ reason: INTENT_REASONS[reasonKey] || "\u539F\u59CB\u610F\u56FE\u4E0E\u6267\u884C\u52A8\u4F5C\u4E0D\u4E00\u81F4",
1908
+ riskLevel: "high",
1909
+ riskType: "intent_deviation",
1910
+ confidence: 85,
1911
+ source: "logic_rule",
1912
+ violatedLayers: ["L2.1"]
1913
+ };
1914
+ }
1915
+ if ((actionCat === "overwrite" || actionCat === "delete") && intents.size === 0) {
1916
+ console.debug(
1917
+ `[intent] \u610F\u56FE\u4E0D\u660E\u786E\uFF0C\u8DF3\u8FC7\u610F\u56FE\u504F\u79BB\u5224\u5B9A\u5E76\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)} \u52A8\u4F5C=${actionCat}(${actionDetail.slice(0, 80)})`
1868
1918
  );
1869
- const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(dangerousText, kw));
1870
- if (intentMatched && dangerousMatched) {
1871
- if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
1872
- continue;
1873
- }
1874
- return {
1875
- allowed: false,
1876
- reason: pattern.reason,
1877
- riskLevel: "high",
1878
- riskType: "intent_deviation",
1879
- confidence: 85,
1880
- source: "logic_rule",
1881
- violatedLayers: ["L2.1"]
1882
- };
1883
- }
1884
1919
  }
1885
1920
  return null;
1886
1921
  }
@@ -1903,7 +1938,7 @@ function runLogicCheck(input, opts) {
1903
1938
  );
1904
1939
  if (rbwResult) return rbwResult;
1905
1940
  }
1906
- const intentResult = checkIntentConsistency(input);
1941
+ const intentResult = checkIntentConsistency(input, opts?.agentExt);
1907
1942
  if (intentResult) return intentResult;
1908
1943
  const indirectResult = checkIndirectFileAccess(actionType, actionDetail, resolvedCwd, input.osType);
1909
1944
  if (indirectResult) return indirectResult;
@@ -2367,7 +2402,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2367
2402
  violatedLayers: ["L2.1"]
2368
2403
  };
2369
2404
  }
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;
2405
+ 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, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, 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;
2371
2406
  var init_logic_rules = __esm({
2372
2407
  "src/engine/logic-rules.ts"() {
2373
2408
  "use strict";
@@ -2461,6 +2496,16 @@ var init_logic_rules = __esm({
2461
2496
  allowIfWriteIntent: p.allow_if_write_intent === true
2462
2497
  }));
2463
2498
  })();
2499
+ INTENT_MATRIX = loadL2().intent_matrix || {};
2500
+ INTENT_CATEGORIES = INTENT_MATRIX.categories || {};
2501
+ INTENT_REASONS = INTENT_MATRIX.reasons || {};
2502
+ DELETE_ACTION_WORDS = new Set(
2503
+ (INTENT_MATRIX.delete_action_words || []).map((w) => String(w).toLowerCase())
2504
+ );
2505
+ ALL_INTENT_KEYWORDS = Object.values(INTENT_CATEGORIES).flat();
2506
+ REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
2507
+ REFERENCE_LOOKBACK = 3;
2508
+ EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
2464
2509
  COMBO_STAGES = (() => {
2465
2510
  const combo = loadL2().combo_chains || {};
2466
2511
  const stages = {};
@@ -5069,7 +5114,16 @@ function runHeuristicCheck(input) {
5069
5114
  }
5070
5115
  }
5071
5116
  const injectionText = isSearchActionType(input.aNext.actionType) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
5072
- const injectionHits = checkInjectionKeywords(injectionText, agentExt?.extra_injection_keywords, input.osType);
5117
+ let pythonWalkOnerrorOnly = false;
5118
+ if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
5119
+ pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
5120
+ }
5121
+ const injectionHits = checkInjectionKeywords(
5122
+ injectionText,
5123
+ agentExt?.extra_injection_keywords,
5124
+ input.osType,
5125
+ pythonWalkOnerrorOnly
5126
+ );
5073
5127
  if (injectionHits.length > 0) {
5074
5128
  const topHit = injectionHits.reduce((a, b) => severityRank(a.riskLevel) >= severityRank(b.riskLevel) ? a : b);
5075
5129
  matched.push(...injectionHits.map((h) => `\u6CE8\u5165\u5173\u952E\u8BCD [${h.lang}]: ${h.keyword}`));
@@ -5118,10 +5172,27 @@ function runHeuristicCheck(input) {
5118
5172
  if (lateralResult) return lateralResult;
5119
5173
  return null;
5120
5174
  }
5121
- function checkInjectionKeywords(text, extraKeywords, osType) {
5175
+ function onlyPythonWalkOnerrorKeywords(command) {
5176
+ const lower = command.toLowerCase();
5177
+ const occurrences = (lower.match(/onerror=/g) || []).length;
5178
+ if (!occurrences || command.length > 128 * 1024) return false;
5179
+ if (command.includes("$") || command.includes("`")) return false;
5180
+ const m = command.match(/^\s*python(?:3(?:\.\d+)?)?\s+-c\s+(['"])([\s\S]*)\1\s*(?:2>&1\s*)?$/i);
5181
+ if (!m) return false;
5182
+ const code = m[2];
5183
+ if ((code.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
5184
+ const noStr = code.replace(/(['"])(?:\\.|(?!\1)[^\\])*\1/g, "");
5185
+ if ((noStr.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
5186
+ const named = noStr.match(/onerror=\s*[A-Za-z_][\w.]*/g) || [];
5187
+ if (named.length !== occurrences) return false;
5188
+ const walkKws = noStr.match(/os\.walk\s*\([^)]*\bonerror\s*=/g) || [];
5189
+ return walkKws.length > 0;
5190
+ }
5191
+ function checkInjectionKeywords(text, extraKeywords, osType, pythonWalkOnerrorOnly = false) {
5122
5192
  const hits = [];
5123
5193
  const baseKeywords = runtimeConfigBridge.current?.effectiveInjectionKeywords(osType) ?? INJECTION_KEYWORDS;
5124
5194
  for (const entry of baseKeywords) {
5195
+ if (pythonWalkOnerrorOnly && entry.keyword.toLowerCase() === "onerror=") continue;
5125
5196
  if (text.includes(entry.keyword.toLowerCase())) {
5126
5197
  hits.push(entry);
5127
5198
  }
@@ -7374,11 +7445,12 @@ var init_tracker = __esm({
7374
7445
  };
7375
7446
  DEFAULT_BACKEND = new ShellBackend();
7376
7447
  RecursiveTracker = class {
7377
- constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE) {
7448
+ constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
7378
7449
  this.maxDepth = maxDepth;
7379
7450
  this.maxNodes = maxNodes;
7380
7451
  this.maxFileSize = maxFileSize;
7381
7452
  this.maxTotalSize = maxTotalSize;
7453
+ this.stopOnCritical = stopOnCritical;
7382
7454
  this._scanner = commandScanner;
7383
7455
  this.result = {
7384
7456
  nodes: [],
@@ -7399,6 +7471,7 @@ var init_tracker = __esm({
7399
7471
  maxNodes;
7400
7472
  maxFileSize;
7401
7473
  maxTotalSize;
7474
+ stopOnCritical;
7402
7475
  result;
7403
7476
  visiting = /* @__PURE__ */ new Set();
7404
7477
  visitedPaths = /* @__PURE__ */ new Set();
@@ -7463,9 +7536,11 @@ var init_tracker = __esm({
7463
7536
  node.l1MatchedPatterns = l1.matchedPatterns || [];
7464
7537
  if (l1.riskLevel === "critical") {
7465
7538
  this.result.hasCritical = true;
7466
- this.result.firstHitNode = node;
7467
- this.visiting.delete(pathStr);
7468
- return;
7539
+ if (!this.result.firstHitNode) this.result.firstHitNode = node;
7540
+ if (this.stopOnCritical) {
7541
+ this.visiting.delete(pathStr);
7542
+ return;
7543
+ }
7469
7544
  }
7470
7545
  }
7471
7546
  }
@@ -7475,7 +7550,7 @@ var init_tracker = __esm({
7475
7550
  const child = resolvePath(call.path, parentDir);
7476
7551
  childPaths.push(child);
7477
7552
  this.visitScript(child, depth + 1, path4.dirname(child), call.args);
7478
- if (this.result.hasCritical) break;
7553
+ if (this.stopOnCritical && this.result.hasCritical) break;
7479
7554
  }
7480
7555
  node.childPaths = childPaths;
7481
7556
  this.visiting.delete(pathStr);
@@ -7780,7 +7855,7 @@ function scanScriptChainKeywords(chain) {
7780
7855
  }
7781
7856
  return chain;
7782
7857
  }
7783
- function analyzeScriptContent2(input, ext) {
7858
+ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
7784
7859
  const actionType = input.aNext.actionType.toLowerCase();
7785
7860
  if (actionType !== "bash") return emptyChain();
7786
7861
  const { path: scriptPath, args: scriptArgs } = extractScriptPathWithArgs(input.aNext.actionDetail);
@@ -7809,7 +7884,14 @@ function analyzeScriptContent2(input, ext) {
7809
7884
  }
7810
7885
  return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
7811
7886
  };
7812
- const tracker = new RecursiveTracker(l1Adapter);
7887
+ const tracker = new RecursiveTracker(
7888
+ l1Adapter,
7889
+ void 0,
7890
+ void 0,
7891
+ void 0,
7892
+ void 0,
7893
+ stopOnCritical
7894
+ );
7813
7895
  const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
7814
7896
  if (chain.nodes.length === 0) return chain;
7815
7897
  scanScriptChainWithL1(chain, input, ext);
@@ -8378,7 +8460,7 @@ __export(token_stats_exports, {
8378
8460
  resetTokenStats: () => resetTokenStats,
8379
8461
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
8380
8462
  });
8381
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
8463
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
8382
8464
  function getStatsPath() {
8383
8465
  const envPath = process.env[ENV_STATS_PATH];
8384
8466
  if (envPath) return envPath;
@@ -8412,7 +8494,16 @@ function saveRecords(statsPath, records) {
8412
8494
  try {
8413
8495
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
8414
8496
  if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
8415
- writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
8497
+ const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
8498
+ try {
8499
+ writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
8500
+ renameSync(tmp, statsPath);
8501
+ } finally {
8502
+ try {
8503
+ unlinkSync2(tmp);
8504
+ } catch {
8505
+ }
8506
+ }
8416
8507
  try {
8417
8508
  const st = statSync6(statsPath);
8418
8509
  _recordsCache = {
@@ -9646,7 +9737,7 @@ var init_reviewer = __esm({
9646
9737
  });
9647
9738
 
9648
9739
  // src/brain/skill-manager.ts
9649
- import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync, writeFileSync as writeFileSync4 } from "fs";
9740
+ import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
9650
9741
  import { homedir as homedir7 } from "os";
9651
9742
  import { join as join14 } from "path";
9652
9743
  import { randomUUID } from "crypto";
@@ -9688,7 +9779,7 @@ var init_skill_manager = __esm({
9688
9779
  const tmp = `${this.metaPath}.tmp`;
9689
9780
  try {
9690
9781
  writeFileSync4(tmp, JSON.stringify(out, null, 2), "utf-8");
9691
- renameSync(tmp, this.metaPath);
9782
+ renameSync2(tmp, this.metaPath);
9692
9783
  } catch {
9693
9784
  }
9694
9785
  }
@@ -12057,7 +12148,8 @@ function _resetBrainForTest() {
12057
12148
  }
12058
12149
  async function runAnalysis(input) {
12059
12150
  const observedFormalLayers = [];
12060
- const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
12151
+ const heuristicEnabled = isHeuristicEnabled();
12152
+ const heuristicResult = heuristicEnabled ? runHeuristicCheck(input) : null;
12061
12153
  if (heuristicResult) {
12062
12154
  traceSummary("l1.result", {
12063
12155
  hit: !heuristicResult.allowed,
@@ -12083,8 +12175,8 @@ async function runAnalysis(input) {
12083
12175
  );
12084
12176
  let scriptChain = null;
12085
12177
  if (input.aNext.actionType.toLowerCase() === "bash") {
12086
- scriptChain = analyzeScriptContent2(input, agentExt);
12087
- if (scriptChain.nodes.length > 0) {
12178
+ scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
12179
+ if (heuristicEnabled && scriptChain.nodes.length > 0) {
12088
12180
  for (const node of scriptChain.nodes) {
12089
12181
  if (node.unanalyzable) {
12090
12182
  return {
@@ -12613,10 +12705,12 @@ function enforceRulesContract() {
12613
12705
 
12614
12706
  // src/server.ts
12615
12707
  init_security_policy();
12708
+ init_paths();
12616
12709
  import { cors } from "hono/cors";
12617
12710
  import { logger } from "hono/logger";
12618
12711
  import net from "net";
12619
- import { existsSync as existsSync21 } from "fs";
12712
+ import { existsSync as existsSync21, writeFileSync as writeFileSync6, renameSync as renameSync3, mkdirSync as mkdirSync8 } from "fs";
12713
+ import { dirname as dirname14, join as join21 } from "path";
12620
12714
 
12621
12715
  // src/routes.ts
12622
12716
  init_esm_shims();
@@ -12635,9 +12729,17 @@ var pkg = require2("../package.json");
12635
12729
  var version = pkg.version;
12636
12730
 
12637
12731
  // src/models.ts
12732
+ var isNonEmptyNoControl = (v) => v.trim().length > 0 && ![...v].some((c) => {
12733
+ const n = c.codePointAt(0) ?? 0;
12734
+ return n < 32 || n >= 127 && n <= 159;
12735
+ });
12638
12736
  var ActionItemSchema = z.object({
12639
- action_type: z.string().describe("Action type, e.g. bash, file_read, file_write"),
12640
- action_detail: z.string().describe("Action detail / command content"),
12737
+ action_type: z.string().refine(isNonEmptyNoControl, {
12738
+ message: "action_type must be nonempty and contain no control characters"
12739
+ }).describe("Action type, e.g. bash, file_read, file_write"),
12740
+ action_detail: z.string().refine((v) => !v.includes("\0"), {
12741
+ message: "action_detail must not contain NUL characters"
12742
+ }).describe("Action detail / command content"),
12641
12743
  // 工具返回给 agent 的内容。仅 L2 的授权(consent)判定用:判断「用户是否已授权」
12642
12744
  // 看的是 ask_user_question 的**回答**,不是提问正文。历史 bug:模型里没有这个字段、
12643
12745
  // 路由也没透传,TS 的授权判定退化成「提问正文非空」,等于问过任何问题即已授权。
@@ -12730,6 +12832,8 @@ var HealthResponseSchema = z.object({
12730
12832
  // 降级原因(status=degraded 时非空)
12731
12833
  degraded: z.array(z.string()).default([]),
12732
12834
  version: z.string().default(version),
12835
+ // 实际监听端口(端口被占用自动漂移后,调用方从这里得知新端口)。
12836
+ port: z.number().default(0),
12733
12837
  // 归属实例标识:值来自 env AGENT_MOSS_INSTANCE(spawn/systemd 注入),默认空串。
12734
12838
  // 多个 agentmoss 同机并存时,调用方按 instance 过滤避免连到别人的进程。
12735
12839
  // 空=未配置(独立部署或旧版),调用方可选择兼容或严格过滤。
@@ -13668,6 +13772,8 @@ async function healthRoute(c) {
13668
13772
  status: degraded.length ? "degraded" : "healthy",
13669
13773
  degraded,
13670
13774
  instance: process.env.AGENT_MOSS_INSTANCE || "",
13775
+ // 实际监听端口(端口漂移后调用方靠它发现)
13776
+ port: parseInt(process.env.AGENT_MOSS_ACTUAL_PORT || "0", 10) || 0,
13671
13777
  metrics
13672
13778
  }));
13673
13779
  }
@@ -14800,9 +14906,28 @@ async function warmUpEngine() {
14800
14906
  else process.env.AGENT_MOSS_SAVE_POLICY = prevSavePolicy;
14801
14907
  }
14802
14908
  }
14909
+ function writePortFile(port) {
14910
+ try {
14911
+ const path8 = join21(getDataRoot(), "agent_moss_server.port.json");
14912
+ mkdirSync8(dirname14(path8), { recursive: true });
14913
+ const payload = JSON.stringify({
14914
+ port,
14915
+ pid: process.pid,
14916
+ started_at: (/* @__PURE__ */ new Date()).toISOString()
14917
+ });
14918
+ const tmp = `${path8}.tmp`;
14919
+ writeFileSync6(tmp, payload, "utf-8");
14920
+ renameSync3(tmp, path8);
14921
+ console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path8} (port=${port})`);
14922
+ } catch (err) {
14923
+ console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
14924
+ }
14925
+ }
14803
14926
  async function startServer(host = "127.0.0.1", port = 9090) {
14804
14927
  failFastOnAuthError();
14805
14928
  const actualPort = await findFreePort(port, host);
14929
+ process.env.AGENT_MOSS_ACTUAL_PORT = String(actualPort);
14930
+ writePortFile(actualPort);
14806
14931
  const app = createApp();
14807
14932
  return {
14808
14933
  port: actualPort,
@@ -14834,12 +14959,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
14834
14959
  },
14835
14960
  serve: async () => {
14836
14961
  failFastOnAuthError();
14837
- const { mkdirSync: mkdirSync8, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
14838
- const { dirname: dirname14 } = await import("path");
14839
- const dir = dirname14(socketPath);
14962
+ const { mkdirSync: mkdirSync9, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
14963
+ const { dirname: dirname15 } = await import("path");
14964
+ const dir = dirname15(socketPath);
14840
14965
  if (dir) {
14841
14966
  try {
14842
- mkdirSync8(dir, { recursive: true });
14967
+ mkdirSync9(dir, { recursive: true });
14843
14968
  } catch {
14844
14969
  }
14845
14970
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kenhkl/agent-moss",
3
- "version": "0.17.27",
3
+ "version": "0.17.29",
4
4
  "description": "Multi-layer security analysis engine for AI agents (TypeScript)",
5
5
  "type": "module",
6
6
  "main": "dist/server.js",