@kenhkl/agent-moss 0.17.29 → 0.17.33
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 +262 -103
- package/dist/engine/coordinator.js +176 -83
- package/dist/server.js +254 -101
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1472,6 +1472,20 @@ var init_models = __esm({
|
|
|
1472
1472
|
violation_chain: z.array(z.array(z.union([z.string(), z.number()]).nullable())).default([]),
|
|
1473
1473
|
// 本次判定的能力降级说明(2026-11):正常为空;链状态触顶时说明 L2.2 未覆盖
|
|
1474
1474
|
degraded: z.array(z.string()).default([]),
|
|
1475
|
+
// 本次 L3(LLM 语义分析)的实际结局(2026-11,稳定枚举,对齐 Python):
|
|
1476
|
+
// 让调用方不读日志就能区分「L3 认真判过的 Allow」和「L3 挂了 fail_open 放的」。
|
|
1477
|
+
l3_outcome: z.enum([
|
|
1478
|
+
"ok",
|
|
1479
|
+
"reasoning_fallback",
|
|
1480
|
+
"not_reached",
|
|
1481
|
+
"skipped",
|
|
1482
|
+
"fail_open",
|
|
1483
|
+
"fail_closed",
|
|
1484
|
+
"failed_but_blocked",
|
|
1485
|
+
"circuit_open",
|
|
1486
|
+
""
|
|
1487
|
+
// 未算出(极端异常路径)
|
|
1488
|
+
]).default(""),
|
|
1475
1489
|
// 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
|
|
1476
1490
|
violation_graph: z.object({
|
|
1477
1491
|
// 性质元信息(前端展示"违反了哪条性质")
|
|
@@ -1932,6 +1946,22 @@ function historyCommandText(histDetailRaw) {
|
|
|
1932
1946
|
}
|
|
1933
1947
|
return histDetailRaw;
|
|
1934
1948
|
}
|
|
1949
|
+
function isScriptGeneratedTarget(targetPath, writtenScripts, shellRuns) {
|
|
1950
|
+
const base = path2.basename(targetPath);
|
|
1951
|
+
if (base.length < 3) return false;
|
|
1952
|
+
const targetDir = path2.dirname(targetPath);
|
|
1953
|
+
if (!targetDir) return false;
|
|
1954
|
+
for (const script of writtenScripts) {
|
|
1955
|
+
if (path2.dirname(script.path) !== targetDir) continue;
|
|
1956
|
+
if (!script.detail.includes(base)) continue;
|
|
1957
|
+
const scriptName = path2.basename(script.path);
|
|
1958
|
+
if (!scriptName) continue;
|
|
1959
|
+
if (shellRuns.some((run) => run.index > script.index && run.command.includes(scriptName))) {
|
|
1960
|
+
return true;
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
return false;
|
|
1964
|
+
}
|
|
1935
1965
|
function parseHeadTailLimit(seg) {
|
|
1936
1966
|
const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
|
|
1937
1967
|
if (firstWord !== "head" && firstWord !== "tail") return null;
|
|
@@ -2451,7 +2481,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2451
2481
|
const historyFullReadPaths = /* @__PURE__ */ new Set();
|
|
2452
2482
|
const historyPartialRead = /* @__PURE__ */ new Map();
|
|
2453
2483
|
const historyWrittenPaths = /* @__PURE__ */ new Set();
|
|
2454
|
-
|
|
2484
|
+
let historyWrittenScripts = [];
|
|
2485
|
+
const shellRunActions = [];
|
|
2486
|
+
for (let actionIndex = 0; actionIndex < actionHistory.length; actionIndex++) {
|
|
2487
|
+
const action = actionHistory[actionIndex];
|
|
2455
2488
|
const histDetailRaw = action.actionDetail;
|
|
2456
2489
|
const histType = action.actionType.toLowerCase();
|
|
2457
2490
|
const traits = getPlatformTraits(osType);
|
|
@@ -2463,7 +2496,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2463
2496
|
);
|
|
2464
2497
|
for (const p of coverage.full) historyFullReadPaths.add(p);
|
|
2465
2498
|
if (isFullOverwriteTool(histType, singleFileTools) && !APPEND_MODE_RE.test(histDetailRaw)) {
|
|
2466
|
-
for (const p of declaredWritePaths(histDetailRaw, osType))
|
|
2499
|
+
for (const p of declaredWritePaths(histDetailRaw, osType)) {
|
|
2500
|
+
historyWrittenPaths.add(p);
|
|
2501
|
+
if (SCRIPT_FILE_RE.test(p)) {
|
|
2502
|
+
historyWrittenScripts.push({ path: p, detail: histDetailRaw, index: actionIndex });
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
if (BASH_LIKE_ACTION_TYPES.includes(histType)) {
|
|
2507
|
+
shellRunActions.push({ index: actionIndex, command: historyCommandText(histDetailRaw) });
|
|
2467
2508
|
}
|
|
2468
2509
|
for (const [p, upto] of coverage.partial) {
|
|
2469
2510
|
if (historyPartialRead.has(p)) {
|
|
@@ -2490,6 +2531,7 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2490
2531
|
const normalizedWrittenPaths = new Set(
|
|
2491
2532
|
[...historyWrittenPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
|
|
2492
2533
|
);
|
|
2534
|
+
historyWrittenScripts = historyWrittenScripts.map((s) => ({ ...s, path: normalizePathForCompare(s.path, cwd) })).filter((s) => s.path);
|
|
2493
2535
|
const normalizedPartialReads = /* @__PURE__ */ new Map();
|
|
2494
2536
|
for (const [p, upto] of historyPartialRead) {
|
|
2495
2537
|
const np = normalizePathForCompare(p, cwd);
|
|
@@ -2519,6 +2561,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2519
2561
|
)) {
|
|
2520
2562
|
isFullRead = true;
|
|
2521
2563
|
}
|
|
2564
|
+
if (!isFullRead && !isProtectedWritePath(path8) && isScriptGeneratedTarget(path8, historyWrittenScripts, shellRunActions)) {
|
|
2565
|
+
isFullRead = true;
|
|
2566
|
+
}
|
|
2522
2567
|
let isPartialCovered = false;
|
|
2523
2568
|
if (!isFullRead) {
|
|
2524
2569
|
for (const [pp, upto] of normalizedPartialReads) {
|
|
@@ -2712,7 +2757,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
|
|
|
2712
2757
|
violatedLayers: ["L2.1"]
|
|
2713
2758
|
};
|
|
2714
2759
|
}
|
|
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;
|
|
2760
|
+
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, SCRIPT_FILE_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;
|
|
2716
2761
|
var init_logic_rules = __esm({
|
|
2717
2762
|
"src/engine/logic-rules.ts"() {
|
|
2718
2763
|
"use strict";
|
|
@@ -2778,6 +2823,7 @@ var init_logic_rules = __esm({
|
|
|
2778
2823
|
PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
|
|
2779
2824
|
APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
|
|
2780
2825
|
APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
|
|
2826
|
+
SCRIPT_FILE_RE = /\.(?:py|pyw|sh|bash|zsh|js|mjs|cjs|ts|pl|rb|php|ps1|bat|cmd)$/i;
|
|
2781
2827
|
SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
|
|
2782
2828
|
SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
|
|
2783
2829
|
SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
|
|
@@ -2882,7 +2928,7 @@ var init_asset_dir = __esm({
|
|
|
2882
2928
|
|
|
2883
2929
|
// src/engine/skill-loader.ts
|
|
2884
2930
|
import { readFileSync as readFileSync5, readdirSync as readdirSync3, existsSync as existsSync6 } from "fs";
|
|
2885
|
-
import { resolve as resolve4, dirname as
|
|
2931
|
+
import { resolve as resolve4, dirname as dirname4 } from "path";
|
|
2886
2932
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
2887
2933
|
function loadAllSkills() {
|
|
2888
2934
|
if (cachedSkills) return cachedSkills;
|
|
@@ -2996,7 +3042,7 @@ var init_skill_loader = __esm({
|
|
|
2996
3042
|
init_asset_dir();
|
|
2997
3043
|
init_runtime_config_bridge();
|
|
2998
3044
|
__filename3 = fileURLToPath3(import.meta.url);
|
|
2999
|
-
__dirname3 =
|
|
3045
|
+
__dirname3 = dirname4(__filename3);
|
|
3000
3046
|
SKILL_KEYWORD_MAP = (() => {
|
|
3001
3047
|
const map = {};
|
|
3002
3048
|
const cats = loadL3();
|
|
@@ -3079,7 +3125,7 @@ __export(runtime_config_exports, {
|
|
|
3079
3125
|
import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
|
|
3080
3126
|
import { join as join7 } from "path";
|
|
3081
3127
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
3082
|
-
import { dirname as
|
|
3128
|
+
import { dirname as dirname5 } from "path";
|
|
3083
3129
|
function runtimeDir() {
|
|
3084
3130
|
return getRuntimeConfigDir();
|
|
3085
3131
|
}
|
|
@@ -4434,7 +4480,7 @@ var init_runtime_config = __esm({
|
|
|
4434
4480
|
init_rules_loader();
|
|
4435
4481
|
init_runtime_config_bridge();
|
|
4436
4482
|
init_rules_mode();
|
|
4437
|
-
__dirname4 =
|
|
4483
|
+
__dirname4 = dirname5(fileURLToPath4(import.meta.url));
|
|
4438
4484
|
ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
|
|
4439
4485
|
RUNTIME_CONFIG_DIR = runtimeDir();
|
|
4440
4486
|
RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
|
|
@@ -4809,7 +4855,7 @@ var init_config = __esm({
|
|
|
4809
4855
|
|
|
4810
4856
|
// src/agents/index.ts
|
|
4811
4857
|
import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
|
|
4812
|
-
import { resolve as resolve5, dirname as
|
|
4858
|
+
import { resolve as resolve5, dirname as dirname6, join as join8 } from "path";
|
|
4813
4859
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
4814
4860
|
function resolveAgentsDir() {
|
|
4815
4861
|
const root = getRulesRoot();
|
|
@@ -4886,7 +4932,7 @@ var init_agents = __esm({
|
|
|
4886
4932
|
init_paths();
|
|
4887
4933
|
init_runtime_config();
|
|
4888
4934
|
__filename4 = fileURLToPath6(import.meta.url);
|
|
4889
|
-
__dirname5 =
|
|
4935
|
+
__dirname5 = dirname6(__filename4);
|
|
4890
4936
|
AGENTS_DIR_PROD = resolve5(__dirname5, "agents");
|
|
4891
4937
|
AGENTS_DIR_DEV_FALLBACK = resolve5(__dirname5, "../../../agent_moss/agents");
|
|
4892
4938
|
cache = /* @__PURE__ */ new Map();
|
|
@@ -4896,7 +4942,7 @@ var init_agents = __esm({
|
|
|
4896
4942
|
|
|
4897
4943
|
// src/scenarios/index.ts
|
|
4898
4944
|
import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
|
|
4899
|
-
import { resolve as resolve6, dirname as
|
|
4945
|
+
import { resolve as resolve6, dirname as dirname7, join as join9 } from "path";
|
|
4900
4946
|
import { fileURLToPath as fileURLToPath7 } from "url";
|
|
4901
4947
|
function resolveScenariosDir() {
|
|
4902
4948
|
const root = getRulesRoot();
|
|
@@ -4992,7 +5038,7 @@ var init_scenarios = __esm({
|
|
|
4992
5038
|
init_runtime_config();
|
|
4993
5039
|
init_rules_loader();
|
|
4994
5040
|
__filename5 = fileURLToPath7(import.meta.url);
|
|
4995
|
-
__dirname6 =
|
|
5041
|
+
__dirname6 = dirname7(__filename5);
|
|
4996
5042
|
SCENARIOS_DIR_PROD = resolve6(__dirname6, "scenarios");
|
|
4997
5043
|
SCENARIOS_DIR_DEV_FALLBACK = resolve6(__dirname6, "../../../agent_moss/scenarios");
|
|
4998
5044
|
cache2 = /* @__PURE__ */ new Map();
|
|
@@ -5667,6 +5713,22 @@ function splitCommandSegments2(actionDetail) {
|
|
|
5667
5713
|
if (start < actionDetail.length) segments.push(actionDetail.slice(start));
|
|
5668
5714
|
return segments;
|
|
5669
5715
|
}
|
|
5716
|
+
function stripSearchPatternLiterals(actionDetail) {
|
|
5717
|
+
const parts = [];
|
|
5718
|
+
for (const seg of splitCommandSegments2(actionDetail)) {
|
|
5719
|
+
const low = seg.trim().toLowerCase();
|
|
5720
|
+
const words = low.length ? low.split(/\s+/) : [];
|
|
5721
|
+
let idx = 0;
|
|
5722
|
+
while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
|
|
5723
|
+
const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
|
|
5724
|
+
if (isSearch && !low.includes("--pre")) {
|
|
5725
|
+
parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
|
|
5726
|
+
} else {
|
|
5727
|
+
parts.push(seg);
|
|
5728
|
+
}
|
|
5729
|
+
}
|
|
5730
|
+
return parts.join("");
|
|
5731
|
+
}
|
|
5670
5732
|
function severityRank(s) {
|
|
5671
5733
|
const ranks = { low: 1, medium: 2, high: 3, critical: 4 };
|
|
5672
5734
|
return ranks[s] || 0;
|
|
@@ -5962,12 +6024,13 @@ function isSshKeygenGenerate(command) {
|
|
|
5962
6024
|
}
|
|
5963
6025
|
function checkDangerousPatterns(actionType, actionDetail) {
|
|
5964
6026
|
if (actionType === "file_write" || actionType === "file_edit") return null;
|
|
5965
|
-
const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
|
|
6027
|
+
const scan = stripSearchPatternLiterals(stripHeredocContent(stripShellDocsOnly(actionDetail)));
|
|
5966
6028
|
const isTempPath = TEMP_DIRS2.some(
|
|
5967
6029
|
(td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
|
|
5968
6030
|
) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
|
|
5969
6031
|
const wildcardDeleteRe = /(?:\brm\b|\b(r?mdir|del|delete|remove|rmdir|unlink)\b|\b删除\b|\b移除\b)[\s\S]{0,40}?[*?]|[*?][\s\S]{0,40}?\b(?:rm|del|delete|remove|rmdir|unlink)\b|rm\s+-[a-zA-Z]*[rf][a-zA-Z]*\s+\S*[*?]/i;
|
|
5970
|
-
|
|
6032
|
+
const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
|
|
6033
|
+
if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
|
|
5971
6034
|
return {
|
|
5972
6035
|
allowed: false,
|
|
5973
6036
|
reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
|
|
@@ -6109,7 +6172,7 @@ function checkLateralMovement(actionDetail) {
|
|
|
6109
6172
|
}
|
|
6110
6173
|
return null;
|
|
6111
6174
|
}
|
|
6112
|
-
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
6175
|
+
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
6113
6176
|
var init_heuristic = __esm({
|
|
6114
6177
|
"src/engine/heuristic.ts"() {
|
|
6115
6178
|
"use strict";
|
|
@@ -6152,6 +6215,8 @@ var init_heuristic = __esm({
|
|
|
6152
6215
|
"\\bchpasswd\\b"
|
|
6153
6216
|
]);
|
|
6154
6217
|
COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
|
|
6218
|
+
TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
|
|
6219
|
+
COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
|
|
6155
6220
|
SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
|
|
6156
6221
|
SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
|
|
6157
6222
|
SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
|
|
@@ -6162,7 +6227,7 @@ var init_heuristic = __esm({
|
|
|
6162
6227
|
|
|
6163
6228
|
// src/engine/template-loader.ts
|
|
6164
6229
|
import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
|
|
6165
|
-
import { resolve as resolve7, dirname as
|
|
6230
|
+
import { resolve as resolve7, dirname as dirname8 } from "path";
|
|
6166
6231
|
import { fileURLToPath as fileURLToPath8 } from "url";
|
|
6167
6232
|
function loadTemplates() {
|
|
6168
6233
|
if (cachedTemplates) return cachedTemplates;
|
|
@@ -6190,7 +6255,7 @@ var init_template_loader = __esm({
|
|
|
6190
6255
|
init_esm_shims();
|
|
6191
6256
|
init_asset_dir();
|
|
6192
6257
|
__filename6 = fileURLToPath8(import.meta.url);
|
|
6193
|
-
__dirname7 =
|
|
6258
|
+
__dirname7 = dirname8(__filename6);
|
|
6194
6259
|
TEMPLATE_FILES = ["prompt1_template.txt", "prompt2_template.txt", "security_judge_template.txt"];
|
|
6195
6260
|
cachedTemplates = null;
|
|
6196
6261
|
}
|
|
@@ -7260,7 +7325,7 @@ function evalCondition2(cond, env2) {
|
|
|
7260
7325
|
if (lv2 === null || rv2 === null) return null;
|
|
7261
7326
|
return evalNumericCompare(op2, lv2, rv2);
|
|
7262
7327
|
}
|
|
7263
|
-
const sm = innerQ.match(/(.*?)\s*(
|
|
7328
|
+
const sm = innerQ.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
|
|
7264
7329
|
if (!sm) return null;
|
|
7265
7330
|
const op = sm[2];
|
|
7266
7331
|
let left = sm[1].trim();
|
|
@@ -7278,8 +7343,8 @@ function evalCondition2(cond, env2) {
|
|
|
7278
7343
|
const lv = resolveVarSide(left, env2);
|
|
7279
7344
|
const rv = resolveVarSide(right, env2);
|
|
7280
7345
|
if (lv === null || rv === null) return null;
|
|
7281
|
-
|
|
7282
|
-
return
|
|
7346
|
+
const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
|
|
7347
|
+
return op === "!=" ? !matched : matched;
|
|
7283
7348
|
}
|
|
7284
7349
|
function symbolicProcess(content, entryArgs) {
|
|
7285
7350
|
if (!content) return null;
|
|
@@ -7287,6 +7352,7 @@ function symbolicProcess(content, entryArgs) {
|
|
|
7287
7352
|
if (!stmts.some((s) => s.kind === "case" || s.kind === "if" || s.kind === "assign")) return null;
|
|
7288
7353
|
if (stmts.some((s) => !s.modelable)) return null;
|
|
7289
7354
|
const env2 = initEnv(entryArgs);
|
|
7355
|
+
if (env2.size > MAX_VARS) return null;
|
|
7290
7356
|
let linesBudget = 0;
|
|
7291
7357
|
let branchesBudget = 0;
|
|
7292
7358
|
let modelable = false;
|
|
@@ -7296,7 +7362,7 @@ function symbolicProcess(content, entryArgs) {
|
|
|
7296
7362
|
if (linesBudget > MAX_LINES2) return null;
|
|
7297
7363
|
if (s.kind === "assign") {
|
|
7298
7364
|
modelable = true;
|
|
7299
|
-
if (env2.size >= MAX_VARS) return null;
|
|
7365
|
+
if (!env2.has(s.name) && env2.size >= MAX_VARS) return null;
|
|
7300
7366
|
const v = evalExpr2(s.rhs, env2);
|
|
7301
7367
|
env2.set(s.name, fold(v));
|
|
7302
7368
|
out.push(s.line);
|
|
@@ -7523,24 +7589,34 @@ function splitNestedCaseBranches(bodyLines, selectorVal) {
|
|
|
7523
7589
|
}
|
|
7524
7590
|
function evalIfCondition(cond, args) {
|
|
7525
7591
|
if (!args || !args.length) return null;
|
|
7526
|
-
|
|
7527
|
-
const m = inner.match(/(.*?)\s*(
|
|
7592
|
+
const inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
|
|
7593
|
+
const m = inner.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
|
|
7528
7594
|
if (!m) return null;
|
|
7595
|
+
const op = m[2];
|
|
7529
7596
|
let left = m[1].trim();
|
|
7530
7597
|
let right = m[3].trim();
|
|
7531
|
-
const
|
|
7532
|
-
|
|
7533
|
-
|
|
7534
|
-
|
|
7535
|
-
|
|
7536
|
-
|
|
7537
|
-
|
|
7538
|
-
|
|
7539
|
-
|
|
7540
|
-
|
|
7541
|
-
|
|
7542
|
-
|
|
7543
|
-
|
|
7598
|
+
const resolve12 = (tok) => {
|
|
7599
|
+
const rm = tok.match(/^\$(\d+)$/);
|
|
7600
|
+
if (rm) {
|
|
7601
|
+
const idx = parseInt(rm[1], 10);
|
|
7602
|
+
return 1 <= idx && idx <= args.length ? args[idx - 1] : null;
|
|
7603
|
+
}
|
|
7604
|
+
return tok.startsWith("$") ? null : tok;
|
|
7605
|
+
};
|
|
7606
|
+
const lv = resolve12(left);
|
|
7607
|
+
const rv = resolve12(right);
|
|
7608
|
+
if (lv === null || rv === null) return null;
|
|
7609
|
+
if (op === "=~") {
|
|
7610
|
+
let re = rv;
|
|
7611
|
+
if (re.startsWith("/") && re.endsWith("/") && re.length > 1) re = re.slice(1, -1);
|
|
7612
|
+
try {
|
|
7613
|
+
return new RegExp(re).test(lv);
|
|
7614
|
+
} catch {
|
|
7615
|
+
return null;
|
|
7616
|
+
}
|
|
7617
|
+
}
|
|
7618
|
+
const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
|
|
7619
|
+
return op === "!=" ? !matched : matched;
|
|
7544
7620
|
}
|
|
7545
7621
|
function parseIf(content, args) {
|
|
7546
7622
|
const m = content.match(/\bif\s+([^\n;]+?)\s*;\s*then/i);
|
|
@@ -8081,41 +8157,6 @@ function scanExtensionPatterns(ext, content) {
|
|
|
8081
8157
|
}
|
|
8082
8158
|
return null;
|
|
8083
8159
|
}
|
|
8084
|
-
function scanScriptChainWithL1(chain, input, ext) {
|
|
8085
|
-
for (const node of chain.nodes) {
|
|
8086
|
-
if (node.error || !node.preprocessedContent || node.l1Hit) continue;
|
|
8087
|
-
const virtualInput = {
|
|
8088
|
-
...input,
|
|
8089
|
-
aNext: { actionType: "bash", actionDetail: node.preprocessedContent }
|
|
8090
|
-
};
|
|
8091
|
-
const l1 = scanDangerousCommandPatterns("bash", node.preprocessedContent, input.osType);
|
|
8092
|
-
const extHit = scanExtensionPatterns(ext, node.preprocessedContent);
|
|
8093
|
-
if (extHit) {
|
|
8094
|
-
node.l1Hit = true;
|
|
8095
|
-
node.l1RiskLevel = extHit.riskLevel;
|
|
8096
|
-
node.l1RiskType = extHit.riskType;
|
|
8097
|
-
node.l1Reason = extHit.reason;
|
|
8098
|
-
if (extHit.riskLevel === "critical") {
|
|
8099
|
-
chain.hasCritical = true;
|
|
8100
|
-
chain.firstHitNode = node;
|
|
8101
|
-
break;
|
|
8102
|
-
}
|
|
8103
|
-
continue;
|
|
8104
|
-
}
|
|
8105
|
-
if (l1 && !l1.allowed) {
|
|
8106
|
-
node.l1Hit = true;
|
|
8107
|
-
node.l1RiskLevel = l1.riskLevel;
|
|
8108
|
-
node.l1RiskType = l1.riskType;
|
|
8109
|
-
node.l1Reason = l1.reason;
|
|
8110
|
-
if (l1.riskLevel === "critical") {
|
|
8111
|
-
chain.hasCritical = true;
|
|
8112
|
-
chain.firstHitNode = node;
|
|
8113
|
-
break;
|
|
8114
|
-
}
|
|
8115
|
-
}
|
|
8116
|
-
}
|
|
8117
|
-
return chain;
|
|
8118
|
-
}
|
|
8119
8160
|
function scanScriptChainWithL2(chain, input) {
|
|
8120
8161
|
for (const node of chain.nodes) {
|
|
8121
8162
|
if (node.error || !node.preprocessedContent) continue;
|
|
@@ -8181,6 +8222,16 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
|
8181
8222
|
resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
|
|
8182
8223
|
}
|
|
8183
8224
|
const l1Adapter = (content) => {
|
|
8225
|
+
const extHit = scanExtensionPatterns(ext, content);
|
|
8226
|
+
if (extHit) {
|
|
8227
|
+
return {
|
|
8228
|
+
hit: true,
|
|
8229
|
+
riskLevel: extHit.riskLevel,
|
|
8230
|
+
riskType: extHit.riskType,
|
|
8231
|
+
reason: extHit.reason,
|
|
8232
|
+
matchedPatterns: []
|
|
8233
|
+
};
|
|
8234
|
+
}
|
|
8184
8235
|
const j = scanDangerousCommandPatterns("bash", content, input.osType);
|
|
8185
8236
|
if (j && !j.allowed) {
|
|
8186
8237
|
return {
|
|
@@ -8204,7 +8255,6 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
|
8204
8255
|
);
|
|
8205
8256
|
const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
|
|
8206
8257
|
if (chain.nodes.length === 0) return chain;
|
|
8207
|
-
scanScriptChainWithL1(chain, input, ext);
|
|
8208
8258
|
scanScriptChainWithL2(chain, input);
|
|
8209
8259
|
scanScriptChainKeywords(chain);
|
|
8210
8260
|
return chain;
|
|
@@ -8692,8 +8742,8 @@ var init_metrics = __esm({
|
|
|
8692
8742
|
};
|
|
8693
8743
|
ANALYZE_TOTAL = new Counter(
|
|
8694
8744
|
"agent_moss_analyze_total",
|
|
8695
|
-
"Total analyze requests handled, by decision and
|
|
8696
|
-
["decision", "risk_level"]
|
|
8745
|
+
"Total analyze requests handled, by decision, risk level and L3 outcome.",
|
|
8746
|
+
["decision", "risk_level", "l3_outcome"]
|
|
8697
8747
|
);
|
|
8698
8748
|
ANALYZE_DURATION = new Histogram(
|
|
8699
8749
|
"agent_moss_analyze_duration_seconds",
|
|
@@ -8976,6 +9026,42 @@ var init_token_stats = __esm({
|
|
|
8976
9026
|
import { createHash as createHash3 } from "crypto";
|
|
8977
9027
|
import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
|
|
8978
9028
|
import OpenAI from "openai";
|
|
9029
|
+
function reasoningTextFallback(raw) {
|
|
9030
|
+
if (typeof raw !== "string") return "";
|
|
9031
|
+
let text = raw.trim();
|
|
9032
|
+
if (text.startsWith("```")) {
|
|
9033
|
+
text = text.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "").trim();
|
|
9034
|
+
}
|
|
9035
|
+
if (!(text.startsWith("{") && text.endsWith("}"))) return "";
|
|
9036
|
+
let parsed;
|
|
9037
|
+
try {
|
|
9038
|
+
parsed = JSON.parse(text);
|
|
9039
|
+
} catch {
|
|
9040
|
+
return "";
|
|
9041
|
+
}
|
|
9042
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
9043
|
+
if ("allowed" in parsed || "decision" in parsed || "risk_level" in parsed) {
|
|
9044
|
+
return text;
|
|
9045
|
+
}
|
|
9046
|
+
}
|
|
9047
|
+
return "";
|
|
9048
|
+
}
|
|
9049
|
+
function reasoningFallbackWithField(message) {
|
|
9050
|
+
if (!message || typeof message !== "object") return { text: "", field: "" };
|
|
9051
|
+
for (const key of ["reasoning", "reasoning_content", "thinking"]) {
|
|
9052
|
+
const got = reasoningTextFallback(message[key]);
|
|
9053
|
+
if (got) return { text: got, field: key };
|
|
9054
|
+
}
|
|
9055
|
+
return { text: "", field: "" };
|
|
9056
|
+
}
|
|
9057
|
+
function describeContentState(raw) {
|
|
9058
|
+
if (raw === null) return "null";
|
|
9059
|
+
if (raw === void 0) return "undefined";
|
|
9060
|
+
const text = typeof raw === "string" ? raw : String(raw);
|
|
9061
|
+
if (text === "") return "empty_string";
|
|
9062
|
+
if (!text.trim()) return `whitespace_only(${text.length})`;
|
|
9063
|
+
return `non_empty(${text.length})`;
|
|
9064
|
+
}
|
|
8979
9065
|
function responseFieldLengths(message) {
|
|
8980
9066
|
if (!message || typeof message !== "object") return {};
|
|
8981
9067
|
const out = {};
|
|
@@ -9233,6 +9319,7 @@ function formatHints(previous) {
|
|
|
9233
9319
|
async function analyzeWithLLM(prompt, config) {
|
|
9234
9320
|
console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
|
|
9235
9321
|
const _llmStart = performance.now();
|
|
9322
|
+
let usedReasoningFallback = false;
|
|
9236
9323
|
const _recordLlm = (result) => {
|
|
9237
9324
|
try {
|
|
9238
9325
|
LLM_CALLS_TOTAL.inc(1, { result });
|
|
@@ -9268,7 +9355,7 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
9268
9355
|
} catch {
|
|
9269
9356
|
}
|
|
9270
9357
|
_recordLlm("error");
|
|
9271
|
-
throw new
|
|
9358
|
+
throw new LLMCircuitOpenError(
|
|
9272
9359
|
"LLM \u8C03\u7528\u5DF2\u7194\u65AD\uFF08\u8FDE\u7EED\u5931\u8D25\u8FC7\u591A\uFF09\uFF0C\u51B7\u5374\u671F\u5185\u4E0D\u518D\u53D1\u8D77\u8BF7\u6C42\uFF1B\u68C0\u67E5\u6A21\u578B\u670D\u52A1\u53EF\u7528\u6027\uFF0C\u6216\u8C03 AGENT_MOSS_LLM_CIRCUIT_COOLDOWN"
|
|
9273
9360
|
);
|
|
9274
9361
|
}
|
|
@@ -9290,10 +9377,21 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
9290
9377
|
...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
|
|
9291
9378
|
});
|
|
9292
9379
|
const message = response.choices[0]?.message;
|
|
9293
|
-
|
|
9380
|
+
let content = message?.content ?? "";
|
|
9294
9381
|
const finishReason = response.choices[0]?.finish_reason;
|
|
9295
9382
|
const fieldLengths = responseFieldLengths(message);
|
|
9296
9383
|
const usage = response.usage;
|
|
9384
|
+
if (!content) {
|
|
9385
|
+
const { text: fallback, field } = reasoningFallbackWithField(message);
|
|
9386
|
+
if (fallback) {
|
|
9387
|
+
const origState = describeContentState(message?.content);
|
|
9388
|
+
console.warn(
|
|
9389
|
+
`[AgentMoss] LLM content \u4E3A\u7A7A\u4F46 ${field} \u542B\u5B8C\u6574\u5224\u5B9A JSON\uFF0C\u56DE\u9000\u4F7F\u7528\uFF08model=${config.model}\uFF0Clen=${fallback.length}\uFF0C\u539F\u59CB content=${origState}\uFF0Cfinish_reason=${finishReason}\uFF0Ctokens=${usage?.prompt_tokens ?? 0}/${usage?.completion_tokens ?? 0}\uFF09\u2014\u2014 \u672C\u6B21\u5224\u5B9A\u4ECD\u7136\u6709\u6548\uFF0C\u4F46\u8BF4\u660E\u6A21\u578B\u6CA1\u628A\u7B54\u6848\u5199\u8FDB content\uFF0C\u957F\u671F\u5E94\u901A\u8FC7 llm.extraBody \u5173\u601D\u8003\u6A21\u5F0F\u6839\u6CBB`
|
|
9390
|
+
);
|
|
9391
|
+
content = fallback;
|
|
9392
|
+
usedReasoningFallback = true;
|
|
9393
|
+
}
|
|
9394
|
+
}
|
|
9297
9395
|
if (!content) {
|
|
9298
9396
|
const detail = `model=${response.model || config.model} finish_reason=${finishReason} ` + (Object.keys(fieldLengths).length ? Object.entries(fieldLengths).map(([k, v]) => `${k}_len=${v}`).join(" ") : `all_empty message_keys=${message ? Object.keys(message).join(",") : "(none)"}`) + ` tokens=${usage?.prompt_tokens ?? "?"}/${usage?.completion_tokens ?? "?"}`;
|
|
9299
9397
|
traceFull("l3.empty_response", {
|
|
@@ -9366,7 +9464,9 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
9366
9464
|
riskLevel: ["low", "medium", "high", "critical"].includes(riskLevel) ? riskLevel : "low",
|
|
9367
9465
|
riskType: riskType || "",
|
|
9368
9466
|
confidence: typeof parsed.confidence === "number" ? Math.min(100, Math.max(0, parsed.confidence)) : 70,
|
|
9369
|
-
|
|
9467
|
+
// 判定结果一样可用,但运维要能看出模型行为异常
|
|
9468
|
+
// (下游据此填 l3Outcome 与 degraded)。
|
|
9469
|
+
source: usedReasoningFallback ? "llm_reasoning_fallback" : "llm",
|
|
9370
9470
|
violatedLayers: ["L3.1"]
|
|
9371
9471
|
};
|
|
9372
9472
|
} catch (err) {
|
|
@@ -9392,7 +9492,7 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
9392
9492
|
clearTimeout(totalTimeoutTimer);
|
|
9393
9493
|
throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
|
|
9394
9494
|
}
|
|
9395
|
-
var llmCache, LLM_CACHE_MAX;
|
|
9495
|
+
var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
|
|
9396
9496
|
var init_llm_analyzer = __esm({
|
|
9397
9497
|
"src/engine/llm-analyzer.ts"() {
|
|
9398
9498
|
"use strict";
|
|
@@ -9406,6 +9506,12 @@ var init_llm_analyzer = __esm({
|
|
|
9406
9506
|
init_trace_log();
|
|
9407
9507
|
init_metrics();
|
|
9408
9508
|
init_circuit_breaker();
|
|
9509
|
+
LLMCircuitOpenError = class extends Error {
|
|
9510
|
+
constructor(message) {
|
|
9511
|
+
super(message);
|
|
9512
|
+
this.name = "LLMCircuitOpenError";
|
|
9513
|
+
}
|
|
9514
|
+
};
|
|
9409
9515
|
llmCache = /* @__PURE__ */ new Map();
|
|
9410
9516
|
LLM_CACHE_MAX = 200;
|
|
9411
9517
|
}
|
|
@@ -10282,7 +10388,7 @@ import { mkdirSync as mkdirSync6, mkdtempSync, rmSync, writeFileSync as writeFil
|
|
|
10282
10388
|
import { tmpdir as tmpdir2 } from "os";
|
|
10283
10389
|
import { join as join15 } from "path";
|
|
10284
10390
|
import { spawnSync } from "child_process";
|
|
10285
|
-
import { dirname as
|
|
10391
|
+
import { dirname as dirname11 } from "path";
|
|
10286
10392
|
import { fileURLToPath as fileURLToPath9 } from "url";
|
|
10287
10393
|
function collectRules(store) {
|
|
10288
10394
|
return store.getActiveRules().filter((r) => EXPORT_RULE_SOURCES.includes(r.source)).map((r) => ({
|
|
@@ -10523,7 +10629,7 @@ var init_contributor = __esm({
|
|
|
10523
10629
|
init_rule_store();
|
|
10524
10630
|
init_skill_manager();
|
|
10525
10631
|
init_asset_dir();
|
|
10526
|
-
__dirname8 =
|
|
10632
|
+
__dirname8 = dirname11(fileURLToPath9(import.meta.url));
|
|
10527
10633
|
DEFAULT_TARGET_REPO = "ssh://git@atomgit.com/kenhkl/AgentMoss.git";
|
|
10528
10634
|
CONTACT_EMAIL = "kenhkl11@hotmail.com";
|
|
10529
10635
|
TOKEN_ENV = "AGENT_MOSS_CONTRIBUTE_TOKEN";
|
|
@@ -13058,6 +13164,7 @@ async function runAnalysis(input) {
|
|
|
13058
13164
|
pathContext
|
|
13059
13165
|
});
|
|
13060
13166
|
} catch (e) {
|
|
13167
|
+
const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
|
|
13061
13168
|
const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
|
|
13062
13169
|
if (getLLMFailMode2() === "fail_open") {
|
|
13063
13170
|
console.warn(`[AgentMoss] LLM \u5206\u6790\u5931\u8D25\uFF0Cfail_open \u6A21\u5F0F\uFF1A\u5141\u8BB8\u6267\u884C\uFF08\u524D\u4E24\u5C42\u672A\u62E6\u622A\uFF09: ${e.message}`);
|
|
@@ -13067,7 +13174,7 @@ async function runAnalysis(input) {
|
|
|
13067
13174
|
riskLevel: "low",
|
|
13068
13175
|
riskType: "",
|
|
13069
13176
|
confidence: 50,
|
|
13070
|
-
source:
|
|
13177
|
+
source: failSource,
|
|
13071
13178
|
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
|
|
13072
13179
|
};
|
|
13073
13180
|
}
|
|
@@ -13077,7 +13184,7 @@ async function runAnalysis(input) {
|
|
|
13077
13184
|
riskLevel: "medium",
|
|
13078
13185
|
riskType: "",
|
|
13079
13186
|
confidence: 60,
|
|
13080
|
-
source:
|
|
13187
|
+
source: failSource,
|
|
13081
13188
|
violatedLayers: ["L3.1"]
|
|
13082
13189
|
};
|
|
13083
13190
|
}
|
|
@@ -13136,6 +13243,24 @@ var init_coordinator = __esm({
|
|
|
13136
13243
|
}
|
|
13137
13244
|
});
|
|
13138
13245
|
|
|
13246
|
+
// src/engine/types.ts
|
|
13247
|
+
function deriveL3Outcome(j) {
|
|
13248
|
+
const src = (j.source || "").toLowerCase();
|
|
13249
|
+
if (src === "llm" || src === "llm_extracted") return "ok";
|
|
13250
|
+
if (src === "llm_reasoning_fallback") return "reasoning_fallback";
|
|
13251
|
+
if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
|
|
13252
|
+
if (src === "llm_circuit_open") return "circuit_open";
|
|
13253
|
+
if (src === "llm_failure_with_violation") return "failed_but_blocked";
|
|
13254
|
+
if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
|
|
13255
|
+
return "not_reached";
|
|
13256
|
+
}
|
|
13257
|
+
var init_types = __esm({
|
|
13258
|
+
"src/engine/types.ts"() {
|
|
13259
|
+
"use strict";
|
|
13260
|
+
init_esm_shims();
|
|
13261
|
+
}
|
|
13262
|
+
});
|
|
13263
|
+
|
|
13139
13264
|
// src/infra/policy-cache.ts
|
|
13140
13265
|
import { createHash as createHash5 } from "crypto";
|
|
13141
13266
|
import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
|
|
@@ -13478,9 +13603,15 @@ function allowResult(policy, judgment) {
|
|
|
13478
13603
|
violated_layers: judgment.violatedLayers || [],
|
|
13479
13604
|
policy,
|
|
13480
13605
|
violated_policy: "",
|
|
13481
|
-
confidence: judgment.confidence
|
|
13606
|
+
confidence: judgment.confidence,
|
|
13607
|
+
// 判定成功算出时才推导(对齐 Python `_finalize`)
|
|
13608
|
+
...judgment.source !== void 0 ? { l3_outcome: deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed ?? true }) } : {}
|
|
13482
13609
|
};
|
|
13483
13610
|
}
|
|
13611
|
+
function withL3(res, judgment) {
|
|
13612
|
+
res.l3_outcome = deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed });
|
|
13613
|
+
return res;
|
|
13614
|
+
}
|
|
13484
13615
|
async function analyze(input) {
|
|
13485
13616
|
const mossLog = new MossLogger(input.sessionId);
|
|
13486
13617
|
try {
|
|
@@ -13507,7 +13638,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13507
13638
|
const judgment = await runAnalysis(input);
|
|
13508
13639
|
mossLog.endStep(
|
|
13509
13640
|
"step1_security_judge",
|
|
13510
|
-
`allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}`
|
|
13641
|
+
`allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}, l3_outcome=${deriveL3Outcome(judgment)}`
|
|
13511
13642
|
);
|
|
13512
13643
|
if (!judgment.allowed) {
|
|
13513
13644
|
const denied = {
|
|
@@ -13523,7 +13654,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13523
13654
|
violation_chain: judgment.violationChain ?? []
|
|
13524
13655
|
};
|
|
13525
13656
|
mossLog.logResult("Deny", denied.reason);
|
|
13526
|
-
return denied;
|
|
13657
|
+
return withL3(denied, judgment);
|
|
13527
13658
|
}
|
|
13528
13659
|
const cache3 = getDefaultCache();
|
|
13529
13660
|
mossLog.startStep("step2_cache_lookup");
|
|
@@ -13533,7 +13664,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13533
13664
|
savePolicyToFile(input.sessionId, cached2);
|
|
13534
13665
|
const res = allowResult(cached2, judgment);
|
|
13535
13666
|
mossLog.logResult("Allow", res.reason, cached2);
|
|
13536
|
-
return res;
|
|
13667
|
+
return withL3(res, judgment);
|
|
13537
13668
|
}
|
|
13538
13669
|
if (!isPolicyGenEnabled()) {
|
|
13539
13670
|
mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0CPolicy \u751F\u6210\u5DF2\u7981\u7528");
|
|
@@ -13543,7 +13674,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13543
13674
|
const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
|
|
13544
13675
|
mossLog.endStep("step2_default_policy", "\u4F7F\u7528\u9ED8\u8BA4\u6700\u5C0F\u6743\u9650 Policy");
|
|
13545
13676
|
mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
|
|
13546
|
-
return res;
|
|
13677
|
+
return withL3(res, judgment);
|
|
13547
13678
|
}
|
|
13548
13679
|
if (judgment.source === "whitelist_bypass") {
|
|
13549
13680
|
mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u767D\u540D\u5355\u5DE5\u5177");
|
|
@@ -13551,7 +13682,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13551
13682
|
savePolicyToFile(input.sessionId, DEFAULT_READONLY_POLICY);
|
|
13552
13683
|
const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
|
|
13553
13684
|
mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
|
|
13554
|
-
return res;
|
|
13685
|
+
return withL3(res, judgment);
|
|
13555
13686
|
}
|
|
13556
13687
|
mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u542F\u7528 LLM \u751F\u6210");
|
|
13557
13688
|
mossLog.startStep("step2_generate_policy");
|
|
@@ -13562,7 +13693,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13562
13693
|
mossLog.endStep("step2_generate_policy", "Policy \u751F\u6210\u5E76\u7F13\u5B58\u6210\u529F");
|
|
13563
13694
|
const res = allowResult(policy, judgment);
|
|
13564
13695
|
mossLog.logResult("Allow", res.reason, policy);
|
|
13565
|
-
return res;
|
|
13696
|
+
return withL3(res, judgment);
|
|
13566
13697
|
} catch (err) {
|
|
13567
13698
|
mossLog.endStep("step2_generate_policy", `\u5931\u8D25: ${String(err)}`);
|
|
13568
13699
|
mossLog.logError("step2_generate_policy", err);
|
|
@@ -13577,7 +13708,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13577
13708
|
confidence: judgment.confidence
|
|
13578
13709
|
};
|
|
13579
13710
|
mossLog.logResult("Deny", failed.reason);
|
|
13580
|
-
return failed;
|
|
13711
|
+
return withL3(failed, judgment);
|
|
13581
13712
|
}
|
|
13582
13713
|
}
|
|
13583
13714
|
var POLICY_OUTPUT_DIR, policyOutputDirOverride, DEFAULT_READONLY_POLICY;
|
|
@@ -13587,6 +13718,7 @@ var init_analyzer = __esm({
|
|
|
13587
13718
|
init_esm_shims();
|
|
13588
13719
|
init_security_policy();
|
|
13589
13720
|
init_coordinator();
|
|
13721
|
+
init_types();
|
|
13590
13722
|
init_policy_cache();
|
|
13591
13723
|
init_config();
|
|
13592
13724
|
init_template_loader();
|
|
@@ -14063,7 +14195,7 @@ var init_runtime_stats = __esm({
|
|
|
14063
14195
|
|
|
14064
14196
|
// src/routes.ts
|
|
14065
14197
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
14066
|
-
import { join as join20, dirname as
|
|
14198
|
+
import { join as join20, dirname as dirname13 } from "path";
|
|
14067
14199
|
import { fileURLToPath as fileURLToPath10 } from "url";
|
|
14068
14200
|
async function healthRoute(c) {
|
|
14069
14201
|
const metrics = {};
|
|
@@ -14214,6 +14346,24 @@ async function analyzeRoute(c) {
|
|
|
14214
14346
|
llmLogPath: req.metadata?.llm_log_path
|
|
14215
14347
|
});
|
|
14216
14348
|
const durationMs = performance.now() - t0;
|
|
14349
|
+
const _l3FailMsg = String(result.reason || "").slice(0, 160);
|
|
14350
|
+
if (result.l3_outcome === "reasoning_fallback") {
|
|
14351
|
+
degradedNotes.push(
|
|
14352
|
+
"\u3010\u63D0\u793A\u3011\u672C\u6B21 L3 \u5224\u5B9A\u53D6\u81EA\u6A21\u578B\u7684 reasoning \u5B57\u6BB5\uFF08content \u4E3A\u7A7A\uFF09\uFF1A**\u5224\u5B9A\u7ED3\u679C\u6709\u6548**\uFF0C\u4F46\u8BF4\u660E\u6A21\u578B\u6CA1\u628A\u7B54\u6848\u5199\u8FDB content\u3002\u9891\u7E41\u51FA\u73B0\u65F6\u8BF7\u5728 config \u7684 llm.extra_body \u914D\u7F6E\u5173\u601D\u8003\u53C2\u6570\u6839\u6CBB\u3002"
|
|
14353
|
+
);
|
|
14354
|
+
} else if (result.l3_outcome === "fail_open") {
|
|
14355
|
+
degradedNotes.push(
|
|
14356
|
+
`\u3010\u5DF2\u964D\u7EA7\u3011L3 \u8BED\u4E49\u5206\u6790\u672A\u5B8C\u6210\uFF08${_l3FailMsg}\uFF09\uFF0C\u672C\u6B21\u6309 fail_open \u653E\u884C\uFF1A**\u4EC5 L1/L2 \u751F\u6548\uFF0C\u672A\u505A\u8BED\u4E49\u5C42\u68C0\u67E5**\u3002\u8C03\u7528\u65B9\u53EF\u636E\u6B64\u6536\u7D27\u4E1A\u52A1\u6743\u9650\u3002`
|
|
14357
|
+
);
|
|
14358
|
+
} else if (result.l3_outcome === "fail_closed") {
|
|
14359
|
+
degradedNotes.push(
|
|
14360
|
+
`\u3010\u5DF2\u964D\u7EA7\u3011L3 \u8BED\u4E49\u5206\u6790\u672A\u5B8C\u6210\uFF08${_l3FailMsg}\uFF09\uFF0C\u672C\u6B21\u6309 fail_closed \u62D2\u7EDD\uFF1A\u62E6\u622A\u539F\u56E0\u662F\u300C\u5206\u6790\u4E0D\u53EF\u7528\u300D\u800C\u975E\u300C\u786E\u8BA4\u6709\u98CE\u9669\u300D\u3002\u4FEE\u590D\u6A21\u578B\u670D\u52A1\u540E\u91CD\u8BD5\u53EF\u80FD\u653E\u884C\u3002`
|
|
14361
|
+
);
|
|
14362
|
+
} else if (result.l3_outcome === "circuit_open") {
|
|
14363
|
+
degradedNotes.push(
|
|
14364
|
+
`\u3010\u5DF2\u964D\u7EA7\u3011LLM \u7194\u65AD\u5668\u6253\u5F00\uFF0C\u672C\u6B21**\u672A\u53D1\u8D77 L3 \u8BF7\u6C42**\uFF08${_l3FailMsg}\uFF09\uFF1AL1/L2 \u6B63\u5E38\uFF0C\u8BED\u4E49\u5C42\u7F3A\u5931\u3002\u68C0\u67E5\u6A21\u578B\u670D\u52A1\u4E0E\u7F51\u7EDC\uFF0C\u51B7\u5374\u540E\u81EA\u52A8\u8BD5\u63A2\u6062\u590D\u3002`
|
|
14365
|
+
);
|
|
14366
|
+
}
|
|
14217
14367
|
const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
|
|
14218
14368
|
if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
|
|
14219
14369
|
console.warn(
|
|
@@ -14221,7 +14371,11 @@ async function analyzeRoute(c) {
|
|
|
14221
14371
|
);
|
|
14222
14372
|
}
|
|
14223
14373
|
try {
|
|
14224
|
-
ANALYZE_TOTAL.inc(1, {
|
|
14374
|
+
ANALYZE_TOTAL.inc(1, {
|
|
14375
|
+
decision: result.decision,
|
|
14376
|
+
risk_level: result.risk_level,
|
|
14377
|
+
l3_outcome: result.l3_outcome || ""
|
|
14378
|
+
});
|
|
14225
14379
|
ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
|
|
14226
14380
|
for (const layer of result.violated_layers || []) {
|
|
14227
14381
|
LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
|
|
@@ -14235,7 +14389,9 @@ async function analyzeRoute(c) {
|
|
|
14235
14389
|
risk_type: result.risk_type,
|
|
14236
14390
|
reason: result.reason,
|
|
14237
14391
|
violated_layers: result.violated_layers,
|
|
14238
|
-
duration_ms: Math.round(durationMs * 10) / 10
|
|
14392
|
+
duration_ms: Math.round(durationMs * 10) / 10,
|
|
14393
|
+
// 2026-11:L3 结局(区分「L3 判过」与「L3 挂了放的」)
|
|
14394
|
+
l3_outcome: result.l3_outcome || ""
|
|
14239
14395
|
});
|
|
14240
14396
|
try {
|
|
14241
14397
|
reportEnforcementEvent({
|
|
@@ -14326,7 +14482,10 @@ async function analyzeRoute(c) {
|
|
|
14326
14482
|
violation_chain: result.violation_chain ?? [],
|
|
14327
14483
|
violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
|
|
14328
14484
|
// 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
|
|
14329
|
-
degraded: degradedNotes
|
|
14485
|
+
degraded: degradedNotes,
|
|
14486
|
+
// L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
|
|
14487
|
+
// 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
|
|
14488
|
+
l3_outcome: result.l3_outcome || ""
|
|
14330
14489
|
})
|
|
14331
14490
|
);
|
|
14332
14491
|
} catch (err) {
|
|
@@ -14576,7 +14735,7 @@ var init_routes = __esm({
|
|
|
14576
14735
|
init_loop_monitor();
|
|
14577
14736
|
init_runtime_stats();
|
|
14578
14737
|
init_metrics();
|
|
14579
|
-
__dirname9 =
|
|
14738
|
+
__dirname9 = dirname13(fileURLToPath10(import.meta.url));
|
|
14580
14739
|
}
|
|
14581
14740
|
});
|
|
14582
14741
|
|
|
@@ -14584,7 +14743,7 @@ var init_routes = __esm({
|
|
|
14584
14743
|
import { Hono } from "hono";
|
|
14585
14744
|
import { timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
14586
14745
|
import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
|
|
14587
|
-
import { join as join21, dirname as
|
|
14746
|
+
import { join as join21, dirname as dirname14 } from "path";
|
|
14588
14747
|
import { fileURLToPath as fileURLToPath11 } from "url";
|
|
14589
14748
|
function getConsoleToken() {
|
|
14590
14749
|
return process.env[CONSOLE_TOKEN_ENV] || "";
|
|
@@ -14823,7 +14982,7 @@ function createConsoleRouter() {
|
|
|
14823
14982
|
if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
|
|
14824
14983
|
return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
|
|
14825
14984
|
}
|
|
14826
|
-
const userPath = join21(
|
|
14985
|
+
const userPath = join21(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
|
|
14827
14986
|
const builtinDir = resolveAssetDir(__dirname10, "skills");
|
|
14828
14987
|
const candidates = [
|
|
14829
14988
|
...isRuntimeConfigDisabled() ? [] : [userPath],
|
|
@@ -14964,7 +15123,7 @@ var init_router = __esm({
|
|
|
14964
15123
|
init_rules_loader();
|
|
14965
15124
|
init_asset_dir();
|
|
14966
15125
|
init_rules_mode();
|
|
14967
|
-
__dirname10 =
|
|
15126
|
+
__dirname10 = dirname14(fileURLToPath11(import.meta.url));
|
|
14968
15127
|
STATIC_DIR = join21(__dirname10, "static");
|
|
14969
15128
|
CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
|
|
14970
15129
|
}
|
|
@@ -14994,7 +15153,7 @@ import { cors } from "hono/cors";
|
|
|
14994
15153
|
import { logger } from "hono/logger";
|
|
14995
15154
|
import net from "net";
|
|
14996
15155
|
import { existsSync as existsSync21, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync9 } from "fs";
|
|
14997
|
-
import { dirname as
|
|
15156
|
+
import { dirname as dirname15, join as join22 } from "path";
|
|
14998
15157
|
function logDeploymentSelfCheck() {
|
|
14999
15158
|
try {
|
|
15000
15159
|
const mode = getRulesMode();
|
|
@@ -15238,7 +15397,7 @@ async function warmUpEngine() {
|
|
|
15238
15397
|
function writePortFile(port) {
|
|
15239
15398
|
try {
|
|
15240
15399
|
const path8 = join22(getDataRoot(), "agent_moss_server.port.json");
|
|
15241
|
-
mkdirSync9(
|
|
15400
|
+
mkdirSync9(dirname15(path8), { recursive: true });
|
|
15242
15401
|
const payload = JSON.stringify({
|
|
15243
15402
|
port,
|
|
15244
15403
|
pid: process.pid,
|
|
@@ -15289,8 +15448,8 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
|
|
|
15289
15448
|
serve: async () => {
|
|
15290
15449
|
failFastOnAuthError();
|
|
15291
15450
|
const { mkdirSync: mkdirSync11, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
|
|
15292
|
-
const { dirname:
|
|
15293
|
-
const dir =
|
|
15451
|
+
const { dirname: dirname17 } = await import("path");
|
|
15452
|
+
const dir = dirname17(socketPath);
|
|
15294
15453
|
if (dir) {
|
|
15295
15454
|
try {
|
|
15296
15455
|
mkdirSync11(dir, { recursive: true });
|
|
@@ -15427,7 +15586,7 @@ __export(rules_tools_exports, {
|
|
|
15427
15586
|
templateSourceDir: () => templateSourceDir
|
|
15428
15587
|
});
|
|
15429
15588
|
import { existsSync as existsSync22, mkdirSync as mkdirSync10, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync8 } from "fs";
|
|
15430
|
-
import { dirname as
|
|
15589
|
+
import { dirname as dirname16, join as join23 } from "path";
|
|
15431
15590
|
import { fileURLToPath as fileURLToPath12 } from "url";
|
|
15432
15591
|
function initRulesDir(targetDir, opts = {}) {
|
|
15433
15592
|
mkdirSync10(targetDir, { recursive: true });
|
|
@@ -15530,7 +15689,7 @@ var init_rules_tools = __esm({
|
|
|
15530
15689
|
"use strict";
|
|
15531
15690
|
init_esm_shims();
|
|
15532
15691
|
init_rules_loader();
|
|
15533
|
-
__dirname11 =
|
|
15692
|
+
__dirname11 = dirname16(fileURLToPath12(import.meta.url));
|
|
15534
15693
|
EXTRA_TEMPLATE = {
|
|
15535
15694
|
_\u8BF4\u660E: [
|
|
15536
15695
|
"\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",
|