@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/cli.js CHANGED
@@ -1408,15 +1408,23 @@ var init_package_json = __esm({
1408
1408
 
1409
1409
  // src/models.ts
1410
1410
  import { z } from "zod";
1411
- var ActionItemSchema, PromptTurnSchema, AnalyzeRequestSchema, AnalyzeResponseSchema, HealthResponseSchema, ReviewRequestSchema, ReviewResponseSchema;
1411
+ var isNonEmptyNoControl, ActionItemSchema, PromptTurnSchema, AnalyzeRequestSchema, AnalyzeResponseSchema, HealthResponseSchema, ReviewRequestSchema, ReviewResponseSchema;
1412
1412
  var init_models = __esm({
1413
1413
  "src/models.ts"() {
1414
1414
  "use strict";
1415
1415
  init_esm_shims();
1416
1416
  init_package_json();
1417
+ isNonEmptyNoControl = (v) => v.trim().length > 0 && ![...v].some((c) => {
1418
+ const n = c.codePointAt(0) ?? 0;
1419
+ return n < 32 || n >= 127 && n <= 159;
1420
+ });
1417
1421
  ActionItemSchema = z.object({
1418
- action_type: z.string().describe("Action type, e.g. bash, file_read, file_write"),
1419
- action_detail: z.string().describe("Action detail / command content"),
1422
+ action_type: z.string().refine(isNonEmptyNoControl, {
1423
+ message: "action_type must be nonempty and contain no control characters"
1424
+ }).describe("Action type, e.g. bash, file_read, file_write"),
1425
+ action_detail: z.string().refine((v) => !v.includes("\0"), {
1426
+ message: "action_detail must not contain NUL characters"
1427
+ }).describe("Action detail / command content"),
1420
1428
  // 工具返回给 agent 的内容。仅 L2 的授权(consent)判定用:判断「用户是否已授权」
1421
1429
  // 看的是 ask_user_question 的**回答**,不是提问正文。历史 bug:模型里没有这个字段、
1422
1430
  // 路由也没透传,TS 的授权判定退化成「提问正文非空」,等于问过任何问题即已授权。
@@ -1509,6 +1517,8 @@ var init_models = __esm({
1509
1517
  // 降级原因(status=degraded 时非空)
1510
1518
  degraded: z.array(z.string()).default([]),
1511
1519
  version: z.string().default(version),
1520
+ // 实际监听端口(端口被占用自动漂移后,调用方从这里得知新端口)。
1521
+ port: z.number().default(0),
1512
1522
  // 归属实例标识:值来自 env AGENT_MOSS_INSTANCE(spawn/systemd 注入),默认空串。
1513
1523
  // 多个 agentmoss 同机并存时,调用方按 instance 过滤避免连到别人的进程。
1514
1524
  // 空=未配置(独立部署或旧版),调用方可选择兼容或严格过滤。
@@ -1875,21 +1885,6 @@ function isDirectoryTarget(p) {
1875
1885
  return false;
1876
1886
  }
1877
1887
  }
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
- }
1893
1888
  function declaredWritePaths(actionDetailRaw, osType) {
1894
1889
  const m = actionDetailRaw.match(DECLARED_WRITE_PATH_RE);
1895
1890
  if (m) return [m[1]];
@@ -2109,78 +2104,128 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
2109
2104
  }
2110
2105
  return false;
2111
2106
  }
2112
- function getIntentPatternsForOs(osType) {
2113
- const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
2114
- if (effective) {
2115
- return effective.map((p) => ({
2116
- ...p,
2117
- allowIfWriteIntent: p.allowIfWriteIntent ?? INTENT_DEVIATION_PATTERNS.find((d) => d.reason === p.reason)?.allowIfWriteIntent ?? false
2118
- }));
2107
+ function intentCategories(text) {
2108
+ const t = (text || "").toLowerCase();
2109
+ const out = /* @__PURE__ */ new Set();
2110
+ for (const [cat, kws] of Object.entries(INTENT_CATEGORIES)) {
2111
+ if (kws.some((kw) => t.includes(String(kw).toLowerCase()))) out.add(cat);
2119
2112
  }
2120
- const accepted = acceptedOsValues(osType);
2121
- return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
2113
+ return out;
2122
2114
  }
2123
- function matchDangerousAction(actionDetail, action) {
2124
- if (/[^\x00-\x7f]/.test(action)) {
2125
- return actionDetail.includes(action);
2115
+ function actionCategory(actionType, actionDetailRaw, osType, extraWriteTools = /* @__PURE__ */ new Set()) {
2116
+ const at = (actionType || "").toLowerCase();
2117
+ const text = (actionDetailRaw || "").replace(DEVNULL_REDIRECT_RE, "");
2118
+ if (["delete", "remove", "rmdir", "unlink"].some((w) => at.includes(w))) return "delete";
2119
+ if (APPEND_MODE_RE.test(text)) return "append";
2120
+ if (/^(?:编辑文件|应用补丁)\s*[::]/.test(text)) return "overwrite";
2121
+ if (/^写入文件\s*[::]/.test(text)) {
2122
+ const paths = declaredWritePaths(text, osType);
2123
+ if (paths.length === 0) return "overwrite";
2124
+ const exists = paths.some((p) => {
2125
+ try {
2126
+ return fs.existsSync(p);
2127
+ } catch {
2128
+ return false;
2129
+ }
2130
+ });
2131
+ return exists ? "overwrite" : "create";
2126
2132
  }
2127
- const escaped = action.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2128
- const re = new RegExp(`(?<![-\\w])${escaped}\\b`, "i");
2129
- return re.test(actionDetail);
2130
- }
2131
- function collectIntentTexts(promptSession, promptHistory) {
2132
- const texts = [];
2133
- if (promptHistory) {
2134
- for (const turn of promptHistory) {
2135
- if (typeof turn === "string") {
2136
- const t2 = turn.trim();
2137
- if (t2) texts.push(t2.toLowerCase());
2138
- continue;
2133
+ if (isPreciseEditTool(at)) return "overwrite";
2134
+ if (isFullOverwriteTool(at, extraWriteTools)) {
2135
+ const paths = declaredWritePaths(text, osType);
2136
+ if (paths.length === 0) return "overwrite";
2137
+ const exists = paths.some((p) => {
2138
+ try {
2139
+ return fs.existsSync(p);
2140
+ } catch {
2141
+ return false;
2139
2142
  }
2140
- const t = (turn?.text || "").trim();
2141
- if (t) texts.push(t.toLowerCase());
2142
- }
2143
+ });
2144
+ return exists ? "overwrite" : "create";
2143
2145
  }
2144
- if (promptSession && promptSession.trim()) {
2145
- texts.push(promptSession.toLowerCase());
2146
+ for (const raw of splitCommandSegments(text)) {
2147
+ const s = raw.trim();
2148
+ if (!s) continue;
2149
+ const fw = (s.split(/\s+/)[0] || "").toLowerCase();
2150
+ if (DELETE_ACTION_WORDS.has(fw)) return "delete";
2151
+ if (fw === "sed" && SED_INPLACE_RE.test(s)) return "overwrite";
2152
+ if (["cp", "mv", "install", "rsync"].includes(fw)) return "overwrite";
2153
+ }
2154
+ if (text.includes(">>")) return "append";
2155
+ if (/(?<![/\-=<>])>\s*(?!&)\S/.test(text)) return "overwrite";
2156
+ return "read";
2157
+ }
2158
+ function intentMatrixViolation(intents, actionCat) {
2159
+ if (intents.size === 0) return null;
2160
+ if (actionCat === "overwrite") {
2161
+ if (intents.has("write")) return null;
2162
+ if (intents.has("delete") && !intents.has("read")) return "delete->overwrite";
2163
+ return "read->overwrite";
2164
+ }
2165
+ if (actionCat === "delete") {
2166
+ if (intents.has("delete")) return null;
2167
+ if (intents.has("write") && !intents.has("read")) return "write->delete";
2168
+ return "read->delete";
2146
2169
  }
2147
- const seen = /* @__PURE__ */ new Set();
2148
- const deduped = [];
2149
- for (const t of texts) {
2150
- if (!seen.has(t)) {
2151
- seen.add(t);
2152
- deduped.push(t);
2170
+ return null;
2171
+ }
2172
+ function resolveIntentText(promptSession, promptHistory, intentKeywords) {
2173
+ const cur = (promptSession || "").trim().toLowerCase();
2174
+ if (intentKeywords.some((kw) => cur.includes(kw))) return cur;
2175
+ if (!REFERENCE_PRIOR_RE.test(cur)) return cur;
2176
+ const turns = (promptHistory || []).slice(-REFERENCE_LOOKBACK);
2177
+ const candidates = [];
2178
+ for (let i = turns.length - 1; i >= 0; i--) {
2179
+ const turn = turns[i];
2180
+ const text = typeof turn === "string" ? turn.trim().toLowerCase() : (turn?.text || "").trim().toLowerCase();
2181
+ if (text && intentKeywords.some((kw) => text.includes(kw))) candidates.push(text);
2182
+ }
2183
+ if (candidates.length === 0) return cur;
2184
+ const firstCats = intentCategories(candidates[0]);
2185
+ for (const other of candidates.slice(1)) {
2186
+ const otherCats = intentCategories(other);
2187
+ const same = otherCats.size === firstCats.size && [...otherCats].every((c) => firstCats.has(c));
2188
+ if (!same) {
2189
+ console.debug(
2190
+ `[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(" | ")}`
2191
+ );
2192
+ return cur;
2153
2193
  }
2154
2194
  }
2155
- return deduped;
2195
+ return candidates[0];
2156
2196
  }
2157
- function checkIntentConsistency(input) {
2197
+ function checkIntentConsistency(input, agentExt) {
2158
2198
  const { aNext, promptSession, promptHistory } = input;
2159
2199
  const actionDetail = aNext.actionDetail.toLowerCase();
2160
2200
  const actionType = aNext.actionType.toLowerCase();
2161
2201
  if (EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p))) return null;
2162
2202
  if (INLINE_SCRIPT_RE.test(actionDetail)) return null;
2163
- const intentTexts = collectIntentTexts(promptSession, promptHistory);
2164
- const dangerousText = intentActionText(actionType, actionDetail);
2165
- for (const pattern of getIntentPatternsForOs(input.osType)) {
2166
- const intentMatched = intentTexts.some(
2167
- (text) => pattern.intentKeywords.some((kw) => text.includes(kw))
2203
+ const extraWriteTools = new Set(agentExt?.extra_single_file_write_tools || []);
2204
+ const intentText = resolveIntentText(promptSession, promptHistory, ALL_INTENT_KEYWORDS);
2205
+ let intents = intentCategories(intentText);
2206
+ if (intents.size > 0 && EXEC_REFERENCE_RE.test(intentText) && !intents.has("delete")) {
2207
+ console.debug(
2208
+ `[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)}`
2209
+ );
2210
+ intents = /* @__PURE__ */ new Set();
2211
+ }
2212
+ const actionCat = actionCategory(actionType, aNext.actionDetail, input.osType, extraWriteTools);
2213
+ const reasonKey = intentMatrixViolation(intents, actionCat);
2214
+ if (reasonKey !== null) {
2215
+ return {
2216
+ allowed: false,
2217
+ reason: INTENT_REASONS[reasonKey] || "\u539F\u59CB\u610F\u56FE\u4E0E\u6267\u884C\u52A8\u4F5C\u4E0D\u4E00\u81F4",
2218
+ riskLevel: "high",
2219
+ riskType: "intent_deviation",
2220
+ confidence: 85,
2221
+ source: "logic_rule",
2222
+ violatedLayers: ["L2.1"]
2223
+ };
2224
+ }
2225
+ if ((actionCat === "overwrite" || actionCat === "delete") && intents.size === 0) {
2226
+ console.debug(
2227
+ `[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)})`
2168
2228
  );
2169
- const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(dangerousText, kw));
2170
- if (intentMatched && dangerousMatched) {
2171
- if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
2172
- continue;
2173
- }
2174
- return {
2175
- allowed: false,
2176
- reason: pattern.reason,
2177
- riskLevel: "high",
2178
- riskType: "intent_deviation",
2179
- confidence: 85,
2180
- source: "logic_rule",
2181
- violatedLayers: ["L2.1"]
2182
- };
2183
- }
2184
2229
  }
2185
2230
  return null;
2186
2231
  }
@@ -2203,7 +2248,7 @@ function runLogicCheck(input, opts) {
2203
2248
  );
2204
2249
  if (rbwResult) return rbwResult;
2205
2250
  }
2206
- const intentResult = checkIntentConsistency(input);
2251
+ const intentResult = checkIntentConsistency(input, opts?.agentExt);
2207
2252
  if (intentResult) return intentResult;
2208
2253
  const indirectResult = checkIndirectFileAccess(actionType, actionDetail, resolvedCwd, input.osType);
2209
2254
  if (indirectResult) return indirectResult;
@@ -2667,7 +2712,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2667
2712
  violatedLayers: ["L2.1"]
2668
2713
  };
2669
2714
  }
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;
2715
+ 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;
2671
2716
  var init_logic_rules = __esm({
2672
2717
  "src/engine/logic-rules.ts"() {
2673
2718
  "use strict";
@@ -2761,6 +2806,16 @@ var init_logic_rules = __esm({
2761
2806
  allowIfWriteIntent: p.allow_if_write_intent === true
2762
2807
  }));
2763
2808
  })();
2809
+ INTENT_MATRIX = loadL2().intent_matrix || {};
2810
+ INTENT_CATEGORIES = INTENT_MATRIX.categories || {};
2811
+ INTENT_REASONS = INTENT_MATRIX.reasons || {};
2812
+ DELETE_ACTION_WORDS = new Set(
2813
+ (INTENT_MATRIX.delete_action_words || []).map((w) => String(w).toLowerCase())
2814
+ );
2815
+ ALL_INTENT_KEYWORDS = Object.values(INTENT_CATEGORIES).flat();
2816
+ REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
2817
+ REFERENCE_LOOKBACK = 3;
2818
+ EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
2764
2819
  COMBO_STAGES = (() => {
2765
2820
  const combo = loadL2().combo_chains || {};
2766
2821
  const stages = {};
@@ -5369,7 +5424,16 @@ function runHeuristicCheck(input) {
5369
5424
  }
5370
5425
  }
5371
5426
  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();
5372
- const injectionHits = checkInjectionKeywords(injectionText, agentExt?.extra_injection_keywords, input.osType);
5427
+ let pythonWalkOnerrorOnly = false;
5428
+ if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
5429
+ pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
5430
+ }
5431
+ const injectionHits = checkInjectionKeywords(
5432
+ injectionText,
5433
+ agentExt?.extra_injection_keywords,
5434
+ input.osType,
5435
+ pythonWalkOnerrorOnly
5436
+ );
5373
5437
  if (injectionHits.length > 0) {
5374
5438
  const topHit = injectionHits.reduce((a, b) => severityRank(a.riskLevel) >= severityRank(b.riskLevel) ? a : b);
5375
5439
  matched.push(...injectionHits.map((h) => `\u6CE8\u5165\u5173\u952E\u8BCD [${h.lang}]: ${h.keyword}`));
@@ -5418,10 +5482,27 @@ function runHeuristicCheck(input) {
5418
5482
  if (lateralResult) return lateralResult;
5419
5483
  return null;
5420
5484
  }
5421
- function checkInjectionKeywords(text, extraKeywords, osType) {
5485
+ function onlyPythonWalkOnerrorKeywords(command) {
5486
+ const lower = command.toLowerCase();
5487
+ const occurrences = (lower.match(/onerror=/g) || []).length;
5488
+ if (!occurrences || command.length > 128 * 1024) return false;
5489
+ if (command.includes("$") || command.includes("`")) return false;
5490
+ const m = command.match(/^\s*python(?:3(?:\.\d+)?)?\s+-c\s+(['"])([\s\S]*)\1\s*(?:2>&1\s*)?$/i);
5491
+ if (!m) return false;
5492
+ const code = m[2];
5493
+ if ((code.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
5494
+ const noStr = code.replace(/(['"])(?:\\.|(?!\1)[^\\])*\1/g, "");
5495
+ if ((noStr.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
5496
+ const named = noStr.match(/onerror=\s*[A-Za-z_][\w.]*/g) || [];
5497
+ if (named.length !== occurrences) return false;
5498
+ const walkKws = noStr.match(/os\.walk\s*\([^)]*\bonerror\s*=/g) || [];
5499
+ return walkKws.length > 0;
5500
+ }
5501
+ function checkInjectionKeywords(text, extraKeywords, osType, pythonWalkOnerrorOnly = false) {
5422
5502
  const hits = [];
5423
5503
  const baseKeywords = runtimeConfigBridge.current?.effectiveInjectionKeywords(osType) ?? INJECTION_KEYWORDS;
5424
5504
  for (const entry of baseKeywords) {
5505
+ if (pythonWalkOnerrorOnly && entry.keyword.toLowerCase() === "onerror=") continue;
5425
5506
  if (text.includes(entry.keyword.toLowerCase())) {
5426
5507
  hits.push(entry);
5427
5508
  }
@@ -7674,11 +7755,12 @@ var init_tracker = __esm({
7674
7755
  };
7675
7756
  DEFAULT_BACKEND = new ShellBackend();
7676
7757
  RecursiveTracker = class {
7677
- constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE) {
7758
+ constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
7678
7759
  this.maxDepth = maxDepth;
7679
7760
  this.maxNodes = maxNodes;
7680
7761
  this.maxFileSize = maxFileSize;
7681
7762
  this.maxTotalSize = maxTotalSize;
7763
+ this.stopOnCritical = stopOnCritical;
7682
7764
  this._scanner = commandScanner;
7683
7765
  this.result = {
7684
7766
  nodes: [],
@@ -7699,6 +7781,7 @@ var init_tracker = __esm({
7699
7781
  maxNodes;
7700
7782
  maxFileSize;
7701
7783
  maxTotalSize;
7784
+ stopOnCritical;
7702
7785
  result;
7703
7786
  visiting = /* @__PURE__ */ new Set();
7704
7787
  visitedPaths = /* @__PURE__ */ new Set();
@@ -7763,9 +7846,11 @@ var init_tracker = __esm({
7763
7846
  node.l1MatchedPatterns = l1.matchedPatterns || [];
7764
7847
  if (l1.riskLevel === "critical") {
7765
7848
  this.result.hasCritical = true;
7766
- this.result.firstHitNode = node;
7767
- this.visiting.delete(pathStr);
7768
- return;
7849
+ if (!this.result.firstHitNode) this.result.firstHitNode = node;
7850
+ if (this.stopOnCritical) {
7851
+ this.visiting.delete(pathStr);
7852
+ return;
7853
+ }
7769
7854
  }
7770
7855
  }
7771
7856
  }
@@ -7775,7 +7860,7 @@ var init_tracker = __esm({
7775
7860
  const child = resolvePath(call.path, parentDir);
7776
7861
  childPaths.push(child);
7777
7862
  this.visitScript(child, depth + 1, path4.dirname(child), call.args);
7778
- if (this.result.hasCritical) break;
7863
+ if (this.stopOnCritical && this.result.hasCritical) break;
7779
7864
  }
7780
7865
  node.childPaths = childPaths;
7781
7866
  this.visiting.delete(pathStr);
@@ -8080,7 +8165,7 @@ function scanScriptChainKeywords(chain) {
8080
8165
  }
8081
8166
  return chain;
8082
8167
  }
8083
- function analyzeScriptContent2(input, ext) {
8168
+ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
8084
8169
  const actionType = input.aNext.actionType.toLowerCase();
8085
8170
  if (actionType !== "bash") return emptyChain();
8086
8171
  const { path: scriptPath, args: scriptArgs } = extractScriptPathWithArgs(input.aNext.actionDetail);
@@ -8109,7 +8194,14 @@ function analyzeScriptContent2(input, ext) {
8109
8194
  }
8110
8195
  return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
8111
8196
  };
8112
- const tracker = new RecursiveTracker(l1Adapter);
8197
+ const tracker = new RecursiveTracker(
8198
+ l1Adapter,
8199
+ void 0,
8200
+ void 0,
8201
+ void 0,
8202
+ void 0,
8203
+ stopOnCritical
8204
+ );
8113
8205
  const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
8114
8206
  if (chain.nodes.length === 0) return chain;
8115
8207
  scanScriptChainWithL1(chain, input, ext);
@@ -8678,7 +8770,7 @@ __export(token_stats_exports, {
8678
8770
  resetTokenStats: () => resetTokenStats,
8679
8771
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
8680
8772
  });
8681
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
8773
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
8682
8774
  function getStatsPath() {
8683
8775
  const envPath = process.env[ENV_STATS_PATH];
8684
8776
  if (envPath) return envPath;
@@ -8712,7 +8804,16 @@ function saveRecords(statsPath, records) {
8712
8804
  try {
8713
8805
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
8714
8806
  if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
8715
- writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
8807
+ const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
8808
+ try {
8809
+ writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
8810
+ renameSync(tmp, statsPath);
8811
+ } finally {
8812
+ try {
8813
+ unlinkSync2(tmp);
8814
+ } catch {
8815
+ }
8816
+ }
8716
8817
  try {
8717
8818
  const st = statSync6(statsPath);
8718
8819
  _recordsCache = {
@@ -9946,7 +10047,7 @@ var init_reviewer = __esm({
9946
10047
  });
9947
10048
 
9948
10049
  // src/brain/skill-manager.ts
9949
- import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync, writeFileSync as writeFileSync4 } from "fs";
10050
+ import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
9950
10051
  import { homedir as homedir7 } from "os";
9951
10052
  import { join as join14 } from "path";
9952
10053
  import { randomUUID } from "crypto";
@@ -9988,7 +10089,7 @@ var init_skill_manager = __esm({
9988
10089
  const tmp = `${this.metaPath}.tmp`;
9989
10090
  try {
9990
10091
  writeFileSync4(tmp, JSON.stringify(out, null, 2), "utf-8");
9991
- renameSync(tmp, this.metaPath);
10092
+ renameSync2(tmp, this.metaPath);
9992
10093
  } catch {
9993
10094
  }
9994
10095
  }
@@ -12622,7 +12723,8 @@ function _resetBrainForTest() {
12622
12723
  }
12623
12724
  async function runAnalysis(input) {
12624
12725
  const observedFormalLayers = [];
12625
- const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
12726
+ const heuristicEnabled = isHeuristicEnabled();
12727
+ const heuristicResult = heuristicEnabled ? runHeuristicCheck(input) : null;
12626
12728
  if (heuristicResult) {
12627
12729
  traceSummary("l1.result", {
12628
12730
  hit: !heuristicResult.allowed,
@@ -12648,8 +12750,8 @@ async function runAnalysis(input) {
12648
12750
  );
12649
12751
  let scriptChain = null;
12650
12752
  if (input.aNext.actionType.toLowerCase() === "bash") {
12651
- scriptChain = analyzeScriptContent2(input, agentExt);
12652
- if (scriptChain.nodes.length > 0) {
12753
+ scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
12754
+ if (heuristicEnabled && scriptChain.nodes.length > 0) {
12653
12755
  for (const node of scriptChain.nodes) {
12654
12756
  if (node.unanalyzable) {
12655
12757
  return {
@@ -14004,6 +14106,8 @@ async function healthRoute(c) {
14004
14106
  status: degraded.length ? "degraded" : "healthy",
14005
14107
  degraded,
14006
14108
  instance: process.env.AGENT_MOSS_INSTANCE || "",
14109
+ // 实际监听端口(端口漂移后调用方靠它发现)
14110
+ port: parseInt(process.env.AGENT_MOSS_ACTUAL_PORT || "0", 10) || 0,
14007
14111
  metrics
14008
14112
  }));
14009
14113
  }
@@ -14889,7 +14993,8 @@ import { Hono as Hono2 } from "hono";
14889
14993
  import { cors } from "hono/cors";
14890
14994
  import { logger } from "hono/logger";
14891
14995
  import net from "net";
14892
- import { existsSync as existsSync21 } from "fs";
14996
+ import { existsSync as existsSync21, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync9 } from "fs";
14997
+ import { dirname as dirname14, join as join22 } from "path";
14893
14998
  function logDeploymentSelfCheck() {
14894
14999
  try {
14895
15000
  const mode = getRulesMode();
@@ -15130,9 +15235,28 @@ async function warmUpEngine() {
15130
15235
  else process.env.AGENT_MOSS_SAVE_POLICY = prevSavePolicy;
15131
15236
  }
15132
15237
  }
15238
+ function writePortFile(port) {
15239
+ try {
15240
+ const path8 = join22(getDataRoot(), "agent_moss_server.port.json");
15241
+ mkdirSync9(dirname14(path8), { recursive: true });
15242
+ const payload = JSON.stringify({
15243
+ port,
15244
+ pid: process.pid,
15245
+ started_at: (/* @__PURE__ */ new Date()).toISOString()
15246
+ });
15247
+ const tmp = `${path8}.tmp`;
15248
+ writeFileSync7(tmp, payload, "utf-8");
15249
+ renameSync3(tmp, path8);
15250
+ console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path8} (port=${port})`);
15251
+ } catch (err) {
15252
+ console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
15253
+ }
15254
+ }
15133
15255
  async function startServer(host = "127.0.0.1", port = 9090) {
15134
15256
  failFastOnAuthError();
15135
15257
  const actualPort = await findFreePort(port, host);
15258
+ process.env.AGENT_MOSS_ACTUAL_PORT = String(actualPort);
15259
+ writePortFile(actualPort);
15136
15260
  const app = createApp();
15137
15261
  return {
15138
15262
  port: actualPort,
@@ -15164,12 +15288,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15164
15288
  },
15165
15289
  serve: async () => {
15166
15290
  failFastOnAuthError();
15167
- const { mkdirSync: mkdirSync10, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15168
- const { dirname: dirname15 } = await import("path");
15169
- const dir = dirname15(socketPath);
15291
+ const { mkdirSync: mkdirSync11, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15292
+ const { dirname: dirname16 } = await import("path");
15293
+ const dir = dirname16(socketPath);
15170
15294
  if (dir) {
15171
15295
  try {
15172
- mkdirSync10(dir, { recursive: true });
15296
+ mkdirSync11(dir, { recursive: true });
15173
15297
  } catch {
15174
15298
  }
15175
15299
  }
@@ -15229,6 +15353,7 @@ var init_server = __esm({
15229
15353
  init_esm_shims();
15230
15354
  init_rules_contract();
15231
15355
  init_security_policy();
15356
+ init_paths();
15232
15357
  init_routes();
15233
15358
  init_console();
15234
15359
  init_runtime_config();
@@ -15301,18 +15426,18 @@ __export(rules_tools_exports, {
15301
15426
  rulesStatusText: () => rulesStatusText,
15302
15427
  templateSourceDir: () => templateSourceDir
15303
15428
  });
15304
- import { existsSync as existsSync22, mkdirSync as mkdirSync9, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync7 } from "fs";
15305
- import { dirname as dirname14, join as join22 } from "path";
15429
+ import { existsSync as existsSync22, mkdirSync as mkdirSync10, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync8 } from "fs";
15430
+ import { dirname as dirname15, join as join23 } from "path";
15306
15431
  import { fileURLToPath as fileURLToPath12 } from "url";
15307
15432
  function initRulesDir(targetDir, opts = {}) {
15308
- mkdirSync9(targetDir, { recursive: true });
15433
+ mkdirSync10(targetDir, { recursive: true });
15309
15434
  const written = [];
15310
- const extraPath = join22(targetDir, EXTRA_FILENAME);
15435
+ const extraPath = join23(targetDir, EXTRA_FILENAME);
15311
15436
  if (opts.force || !existsSync22(extraPath)) {
15312
- writeFileSync7(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
15437
+ writeFileSync8(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
15313
15438
  written.push(extraPath);
15314
15439
  }
15315
- const samplePath = join22(targetDir, OVERRIDE_FILENAME);
15440
+ const samplePath = join23(targetDir, OVERRIDE_FILENAME);
15316
15441
  if (opts.force || !existsSync22(samplePath)) {
15317
15442
  let payload = OVERRIDE_TEMPLATE;
15318
15443
  if (opts.withBuiltin) {
@@ -15328,19 +15453,19 @@ function initRulesDir(targetDir, opts = {}) {
15328
15453
  payload = { _\u8BF4\u660E: OVERRIDE_BUILTIN_NOTE };
15329
15454
  for (const k of L1_KEYS) payload[k] = data[k] || [];
15330
15455
  }
15331
- writeFileSync7(samplePath, JSON.stringify(payload, null, 2), "utf-8");
15456
+ writeFileSync8(samplePath, JSON.stringify(payload, null, 2), "utf-8");
15332
15457
  written.push(samplePath);
15333
15458
  }
15334
- const readmeSrc = join22(templateSourceDir(), "README.md");
15335
- const readmeDst = join22(targetDir, "README.md");
15459
+ const readmeSrc = join23(templateSourceDir(), "README.md");
15460
+ const readmeDst = join23(targetDir, "README.md");
15336
15461
  if (existsSync22(readmeSrc) && (opts.force || !existsSync22(readmeDst))) {
15337
- writeFileSync7(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
15462
+ writeFileSync8(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
15338
15463
  written.push(readmeDst);
15339
15464
  }
15340
15465
  return written;
15341
15466
  }
15342
15467
  function templateSourceDir() {
15343
- const cands = [join22(__dirname11, "data", "rules_template"), join22(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
15468
+ const cands = [join23(__dirname11, "data", "rules_template"), join23(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
15344
15469
  for (const c of cands) if (existsSync22(c)) return c;
15345
15470
  return cands[0];
15346
15471
  }
@@ -15349,7 +15474,7 @@ function templateFiles(dirs) {
15349
15474
  for (const d of dirs) {
15350
15475
  try {
15351
15476
  for (const name of readdirSync7(d)) {
15352
- if (name.endsWith(".json.\u793A\u4F8B")) out.push(join22(d, name));
15477
+ if (name.endsWith(".json.\u793A\u4F8B")) out.push(join23(d, name));
15353
15478
  }
15354
15479
  } catch {
15355
15480
  }
@@ -15405,7 +15530,7 @@ var init_rules_tools = __esm({
15405
15530
  "use strict";
15406
15531
  init_esm_shims();
15407
15532
  init_rules_loader();
15408
- __dirname11 = dirname14(fileURLToPath12(import.meta.url));
15533
+ __dirname11 = dirname15(fileURLToPath12(import.meta.url));
15409
15534
  EXTRA_TEMPLATE = {
15410
15535
  _\u8BF4\u660E: [
15411
15536
  "\u8FFD\u52A0\u89C4\u5219\uFF1A\u5185\u7F6E\u89C4\u5219\u5168\u90E8\u4FDD\u7559\uFF0C\u4F60\u5199\u5728\u8FD9\u91CC\u7684\u89C4\u5219\u52A0\u5728\u5185\u7F6E\u4E4B\u540E\u4E00\u8D77\u5224\u5B9A\u3002",