@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/server.js
CHANGED
|
@@ -1622,6 +1622,22 @@ function historyCommandText(histDetailRaw) {
|
|
|
1622
1622
|
}
|
|
1623
1623
|
return histDetailRaw;
|
|
1624
1624
|
}
|
|
1625
|
+
function isScriptGeneratedTarget(targetPath, writtenScripts, shellRuns) {
|
|
1626
|
+
const base = path2.basename(targetPath);
|
|
1627
|
+
if (base.length < 3) return false;
|
|
1628
|
+
const targetDir = path2.dirname(targetPath);
|
|
1629
|
+
if (!targetDir) return false;
|
|
1630
|
+
for (const script of writtenScripts) {
|
|
1631
|
+
if (path2.dirname(script.path) !== targetDir) continue;
|
|
1632
|
+
if (!script.detail.includes(base)) continue;
|
|
1633
|
+
const scriptName = path2.basename(script.path);
|
|
1634
|
+
if (!scriptName) continue;
|
|
1635
|
+
if (shellRuns.some((run) => run.index > script.index && run.command.includes(scriptName))) {
|
|
1636
|
+
return true;
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
return false;
|
|
1640
|
+
}
|
|
1625
1641
|
function parseHeadTailLimit(seg) {
|
|
1626
1642
|
const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
|
|
1627
1643
|
if (firstWord !== "head" && firstWord !== "tail") return null;
|
|
@@ -2141,7 +2157,10 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2141
2157
|
const historyFullReadPaths = /* @__PURE__ */ new Set();
|
|
2142
2158
|
const historyPartialRead = /* @__PURE__ */ new Map();
|
|
2143
2159
|
const historyWrittenPaths = /* @__PURE__ */ new Set();
|
|
2144
|
-
|
|
2160
|
+
let historyWrittenScripts = [];
|
|
2161
|
+
const shellRunActions = [];
|
|
2162
|
+
for (let actionIndex = 0; actionIndex < actionHistory.length; actionIndex++) {
|
|
2163
|
+
const action = actionHistory[actionIndex];
|
|
2145
2164
|
const histDetailRaw = action.actionDetail;
|
|
2146
2165
|
const histType = action.actionType.toLowerCase();
|
|
2147
2166
|
const traits = getPlatformTraits(osType);
|
|
@@ -2153,7 +2172,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2153
2172
|
);
|
|
2154
2173
|
for (const p of coverage.full) historyFullReadPaths.add(p);
|
|
2155
2174
|
if (isFullOverwriteTool(histType, singleFileTools) && !APPEND_MODE_RE.test(histDetailRaw)) {
|
|
2156
|
-
for (const p of declaredWritePaths(histDetailRaw, osType))
|
|
2175
|
+
for (const p of declaredWritePaths(histDetailRaw, osType)) {
|
|
2176
|
+
historyWrittenPaths.add(p);
|
|
2177
|
+
if (SCRIPT_FILE_RE.test(p)) {
|
|
2178
|
+
historyWrittenScripts.push({ path: p, detail: histDetailRaw, index: actionIndex });
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
}
|
|
2182
|
+
if (BASH_LIKE_ACTION_TYPES.includes(histType)) {
|
|
2183
|
+
shellRunActions.push({ index: actionIndex, command: historyCommandText(histDetailRaw) });
|
|
2157
2184
|
}
|
|
2158
2185
|
for (const [p, upto] of coverage.partial) {
|
|
2159
2186
|
if (historyPartialRead.has(p)) {
|
|
@@ -2180,6 +2207,7 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2180
2207
|
const normalizedWrittenPaths = new Set(
|
|
2181
2208
|
[...historyWrittenPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
|
|
2182
2209
|
);
|
|
2210
|
+
historyWrittenScripts = historyWrittenScripts.map((s) => ({ ...s, path: normalizePathForCompare(s.path, cwd) })).filter((s) => s.path);
|
|
2183
2211
|
const normalizedPartialReads = /* @__PURE__ */ new Map();
|
|
2184
2212
|
for (const [p, upto] of historyPartialRead) {
|
|
2185
2213
|
const np = normalizePathForCompare(p, cwd);
|
|
@@ -2209,6 +2237,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2209
2237
|
)) {
|
|
2210
2238
|
isFullRead = true;
|
|
2211
2239
|
}
|
|
2240
|
+
if (!isFullRead && !isProtectedWritePath(path8) && isScriptGeneratedTarget(path8, historyWrittenScripts, shellRunActions)) {
|
|
2241
|
+
isFullRead = true;
|
|
2242
|
+
}
|
|
2212
2243
|
let isPartialCovered = false;
|
|
2213
2244
|
if (!isFullRead) {
|
|
2214
2245
|
for (const [pp, upto] of normalizedPartialReads) {
|
|
@@ -2402,7 +2433,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
|
|
|
2402
2433
|
violatedLayers: ["L2.1"]
|
|
2403
2434
|
};
|
|
2404
2435
|
}
|
|
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;
|
|
2436
|
+
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;
|
|
2406
2437
|
var init_logic_rules = __esm({
|
|
2407
2438
|
"src/engine/logic-rules.ts"() {
|
|
2408
2439
|
"use strict";
|
|
@@ -2468,6 +2499,7 @@ var init_logic_rules = __esm({
|
|
|
2468
2499
|
PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
|
|
2469
2500
|
APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
|
|
2470
2501
|
APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
|
|
2502
|
+
SCRIPT_FILE_RE = /\.(?:py|pyw|sh|bash|zsh|js|mjs|cjs|ts|pl|rb|php|ps1|bat|cmd)$/i;
|
|
2471
2503
|
SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
|
|
2472
2504
|
SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
|
|
2473
2505
|
SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
|
|
@@ -2572,7 +2604,7 @@ var init_asset_dir = __esm({
|
|
|
2572
2604
|
|
|
2573
2605
|
// src/engine/skill-loader.ts
|
|
2574
2606
|
import { readFileSync as readFileSync5, readdirSync as readdirSync3, existsSync as existsSync6 } from "fs";
|
|
2575
|
-
import { resolve as resolve4, dirname as
|
|
2607
|
+
import { resolve as resolve4, dirname as dirname4 } from "path";
|
|
2576
2608
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
2577
2609
|
function loadAllSkills() {
|
|
2578
2610
|
if (cachedSkills) return cachedSkills;
|
|
@@ -2686,7 +2718,7 @@ var init_skill_loader = __esm({
|
|
|
2686
2718
|
init_asset_dir();
|
|
2687
2719
|
init_runtime_config_bridge();
|
|
2688
2720
|
__filename3 = fileURLToPath3(import.meta.url);
|
|
2689
|
-
__dirname3 =
|
|
2721
|
+
__dirname3 = dirname4(__filename3);
|
|
2690
2722
|
SKILL_KEYWORD_MAP = (() => {
|
|
2691
2723
|
const map = {};
|
|
2692
2724
|
const cats = loadL3();
|
|
@@ -2769,7 +2801,7 @@ __export(runtime_config_exports, {
|
|
|
2769
2801
|
import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
|
|
2770
2802
|
import { join as join7 } from "path";
|
|
2771
2803
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
2772
|
-
import { dirname as
|
|
2804
|
+
import { dirname as dirname5 } from "path";
|
|
2773
2805
|
function runtimeDir() {
|
|
2774
2806
|
return getRuntimeConfigDir();
|
|
2775
2807
|
}
|
|
@@ -4124,7 +4156,7 @@ var init_runtime_config = __esm({
|
|
|
4124
4156
|
init_rules_loader();
|
|
4125
4157
|
init_runtime_config_bridge();
|
|
4126
4158
|
init_rules_mode();
|
|
4127
|
-
__dirname4 =
|
|
4159
|
+
__dirname4 = dirname5(fileURLToPath4(import.meta.url));
|
|
4128
4160
|
ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
|
|
4129
4161
|
RUNTIME_CONFIG_DIR = runtimeDir();
|
|
4130
4162
|
RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
|
|
@@ -4499,7 +4531,7 @@ var init_config = __esm({
|
|
|
4499
4531
|
|
|
4500
4532
|
// src/agents/index.ts
|
|
4501
4533
|
import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
|
|
4502
|
-
import { resolve as resolve5, dirname as
|
|
4534
|
+
import { resolve as resolve5, dirname as dirname6, join as join8 } from "path";
|
|
4503
4535
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
4504
4536
|
function resolveAgentsDir() {
|
|
4505
4537
|
const root = getRulesRoot();
|
|
@@ -4576,7 +4608,7 @@ var init_agents = __esm({
|
|
|
4576
4608
|
init_paths();
|
|
4577
4609
|
init_runtime_config();
|
|
4578
4610
|
__filename4 = fileURLToPath6(import.meta.url);
|
|
4579
|
-
__dirname5 =
|
|
4611
|
+
__dirname5 = dirname6(__filename4);
|
|
4580
4612
|
AGENTS_DIR_PROD = resolve5(__dirname5, "agents");
|
|
4581
4613
|
AGENTS_DIR_DEV_FALLBACK = resolve5(__dirname5, "../../../agent_moss/agents");
|
|
4582
4614
|
cache = /* @__PURE__ */ new Map();
|
|
@@ -4586,7 +4618,7 @@ var init_agents = __esm({
|
|
|
4586
4618
|
|
|
4587
4619
|
// src/scenarios/index.ts
|
|
4588
4620
|
import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
|
|
4589
|
-
import { resolve as resolve6, dirname as
|
|
4621
|
+
import { resolve as resolve6, dirname as dirname7, join as join9 } from "path";
|
|
4590
4622
|
import { fileURLToPath as fileURLToPath7 } from "url";
|
|
4591
4623
|
function resolveScenariosDir() {
|
|
4592
4624
|
const root = getRulesRoot();
|
|
@@ -4682,7 +4714,7 @@ var init_scenarios = __esm({
|
|
|
4682
4714
|
init_runtime_config();
|
|
4683
4715
|
init_rules_loader();
|
|
4684
4716
|
__filename5 = fileURLToPath7(import.meta.url);
|
|
4685
|
-
__dirname6 =
|
|
4717
|
+
__dirname6 = dirname7(__filename5);
|
|
4686
4718
|
SCENARIOS_DIR_PROD = resolve6(__dirname6, "scenarios");
|
|
4687
4719
|
SCENARIOS_DIR_DEV_FALLBACK = resolve6(__dirname6, "../../../agent_moss/scenarios");
|
|
4688
4720
|
cache2 = /* @__PURE__ */ new Map();
|
|
@@ -5357,6 +5389,22 @@ function splitCommandSegments2(actionDetail) {
|
|
|
5357
5389
|
if (start < actionDetail.length) segments.push(actionDetail.slice(start));
|
|
5358
5390
|
return segments;
|
|
5359
5391
|
}
|
|
5392
|
+
function stripSearchPatternLiterals(actionDetail) {
|
|
5393
|
+
const parts = [];
|
|
5394
|
+
for (const seg of splitCommandSegments2(actionDetail)) {
|
|
5395
|
+
const low = seg.trim().toLowerCase();
|
|
5396
|
+
const words = low.length ? low.split(/\s+/) : [];
|
|
5397
|
+
let idx = 0;
|
|
5398
|
+
while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
|
|
5399
|
+
const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
|
|
5400
|
+
if (isSearch && !low.includes("--pre")) {
|
|
5401
|
+
parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
|
|
5402
|
+
} else {
|
|
5403
|
+
parts.push(seg);
|
|
5404
|
+
}
|
|
5405
|
+
}
|
|
5406
|
+
return parts.join("");
|
|
5407
|
+
}
|
|
5360
5408
|
function severityRank(s) {
|
|
5361
5409
|
const ranks = { low: 1, medium: 2, high: 3, critical: 4 };
|
|
5362
5410
|
return ranks[s] || 0;
|
|
@@ -5652,12 +5700,13 @@ function isSshKeygenGenerate(command) {
|
|
|
5652
5700
|
}
|
|
5653
5701
|
function checkDangerousPatterns(actionType, actionDetail) {
|
|
5654
5702
|
if (actionType === "file_write" || actionType === "file_edit") return null;
|
|
5655
|
-
const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
|
|
5703
|
+
const scan = stripSearchPatternLiterals(stripHeredocContent(stripShellDocsOnly(actionDetail)));
|
|
5656
5704
|
const isTempPath = TEMP_DIRS2.some(
|
|
5657
5705
|
(td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
|
|
5658
5706
|
) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
|
|
5659
5707
|
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;
|
|
5660
|
-
|
|
5708
|
+
const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
|
|
5709
|
+
if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
|
|
5661
5710
|
return {
|
|
5662
5711
|
allowed: false,
|
|
5663
5712
|
reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
|
|
@@ -5799,7 +5848,7 @@ function checkLateralMovement(actionDetail) {
|
|
|
5799
5848
|
}
|
|
5800
5849
|
return null;
|
|
5801
5850
|
}
|
|
5802
|
-
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;
|
|
5851
|
+
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;
|
|
5803
5852
|
var init_heuristic = __esm({
|
|
5804
5853
|
"src/engine/heuristic.ts"() {
|
|
5805
5854
|
"use strict";
|
|
@@ -5842,6 +5891,8 @@ var init_heuristic = __esm({
|
|
|
5842
5891
|
"\\bchpasswd\\b"
|
|
5843
5892
|
]);
|
|
5844
5893
|
COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
|
|
5894
|
+
TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
|
|
5895
|
+
COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
|
|
5845
5896
|
SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
|
|
5846
5897
|
SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
|
|
5847
5898
|
SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
|
|
@@ -5852,7 +5903,7 @@ var init_heuristic = __esm({
|
|
|
5852
5903
|
|
|
5853
5904
|
// src/engine/template-loader.ts
|
|
5854
5905
|
import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
|
|
5855
|
-
import { resolve as resolve7, dirname as
|
|
5906
|
+
import { resolve as resolve7, dirname as dirname8 } from "path";
|
|
5856
5907
|
import { fileURLToPath as fileURLToPath8 } from "url";
|
|
5857
5908
|
function loadTemplates() {
|
|
5858
5909
|
if (cachedTemplates) return cachedTemplates;
|
|
@@ -5880,7 +5931,7 @@ var init_template_loader = __esm({
|
|
|
5880
5931
|
init_esm_shims();
|
|
5881
5932
|
init_asset_dir();
|
|
5882
5933
|
__filename6 = fileURLToPath8(import.meta.url);
|
|
5883
|
-
__dirname7 =
|
|
5934
|
+
__dirname7 = dirname8(__filename6);
|
|
5884
5935
|
TEMPLATE_FILES = ["prompt1_template.txt", "prompt2_template.txt", "security_judge_template.txt"];
|
|
5885
5936
|
cachedTemplates = null;
|
|
5886
5937
|
}
|
|
@@ -6950,7 +7001,7 @@ function evalCondition2(cond, env2) {
|
|
|
6950
7001
|
if (lv2 === null || rv2 === null) return null;
|
|
6951
7002
|
return evalNumericCompare(op2, lv2, rv2);
|
|
6952
7003
|
}
|
|
6953
|
-
const sm = innerQ.match(/(.*?)\s*(
|
|
7004
|
+
const sm = innerQ.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
|
|
6954
7005
|
if (!sm) return null;
|
|
6955
7006
|
const op = sm[2];
|
|
6956
7007
|
let left = sm[1].trim();
|
|
@@ -6968,8 +7019,8 @@ function evalCondition2(cond, env2) {
|
|
|
6968
7019
|
const lv = resolveVarSide(left, env2);
|
|
6969
7020
|
const rv = resolveVarSide(right, env2);
|
|
6970
7021
|
if (lv === null || rv === null) return null;
|
|
6971
|
-
|
|
6972
|
-
return
|
|
7022
|
+
const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
|
|
7023
|
+
return op === "!=" ? !matched : matched;
|
|
6973
7024
|
}
|
|
6974
7025
|
function symbolicProcess(content, entryArgs) {
|
|
6975
7026
|
if (!content) return null;
|
|
@@ -6977,6 +7028,7 @@ function symbolicProcess(content, entryArgs) {
|
|
|
6977
7028
|
if (!stmts.some((s) => s.kind === "case" || s.kind === "if" || s.kind === "assign")) return null;
|
|
6978
7029
|
if (stmts.some((s) => !s.modelable)) return null;
|
|
6979
7030
|
const env2 = initEnv(entryArgs);
|
|
7031
|
+
if (env2.size > MAX_VARS) return null;
|
|
6980
7032
|
let linesBudget = 0;
|
|
6981
7033
|
let branchesBudget = 0;
|
|
6982
7034
|
let modelable = false;
|
|
@@ -6986,7 +7038,7 @@ function symbolicProcess(content, entryArgs) {
|
|
|
6986
7038
|
if (linesBudget > MAX_LINES2) return null;
|
|
6987
7039
|
if (s.kind === "assign") {
|
|
6988
7040
|
modelable = true;
|
|
6989
|
-
if (env2.size >= MAX_VARS) return null;
|
|
7041
|
+
if (!env2.has(s.name) && env2.size >= MAX_VARS) return null;
|
|
6990
7042
|
const v = evalExpr2(s.rhs, env2);
|
|
6991
7043
|
env2.set(s.name, fold(v));
|
|
6992
7044
|
out.push(s.line);
|
|
@@ -7213,24 +7265,34 @@ function splitNestedCaseBranches(bodyLines, selectorVal) {
|
|
|
7213
7265
|
}
|
|
7214
7266
|
function evalIfCondition(cond, args) {
|
|
7215
7267
|
if (!args || !args.length) return null;
|
|
7216
|
-
|
|
7217
|
-
const m = inner.match(/(.*?)\s*(
|
|
7268
|
+
const inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
|
|
7269
|
+
const m = inner.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
|
|
7218
7270
|
if (!m) return null;
|
|
7271
|
+
const op = m[2];
|
|
7219
7272
|
let left = m[1].trim();
|
|
7220
7273
|
let right = m[3].trim();
|
|
7221
|
-
const
|
|
7222
|
-
|
|
7223
|
-
|
|
7224
|
-
|
|
7225
|
-
|
|
7226
|
-
|
|
7227
|
-
|
|
7228
|
-
|
|
7229
|
-
|
|
7230
|
-
|
|
7231
|
-
|
|
7232
|
-
|
|
7233
|
-
|
|
7274
|
+
const resolve12 = (tok) => {
|
|
7275
|
+
const rm = tok.match(/^\$(\d+)$/);
|
|
7276
|
+
if (rm) {
|
|
7277
|
+
const idx = parseInt(rm[1], 10);
|
|
7278
|
+
return 1 <= idx && idx <= args.length ? args[idx - 1] : null;
|
|
7279
|
+
}
|
|
7280
|
+
return tok.startsWith("$") ? null : tok;
|
|
7281
|
+
};
|
|
7282
|
+
const lv = resolve12(left);
|
|
7283
|
+
const rv = resolve12(right);
|
|
7284
|
+
if (lv === null || rv === null) return null;
|
|
7285
|
+
if (op === "=~") {
|
|
7286
|
+
let re = rv;
|
|
7287
|
+
if (re.startsWith("/") && re.endsWith("/") && re.length > 1) re = re.slice(1, -1);
|
|
7288
|
+
try {
|
|
7289
|
+
return new RegExp(re).test(lv);
|
|
7290
|
+
} catch {
|
|
7291
|
+
return null;
|
|
7292
|
+
}
|
|
7293
|
+
}
|
|
7294
|
+
const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
|
|
7295
|
+
return op === "!=" ? !matched : matched;
|
|
7234
7296
|
}
|
|
7235
7297
|
function parseIf(content, args) {
|
|
7236
7298
|
const m = content.match(/\bif\s+([^\n;]+?)\s*;\s*then/i);
|
|
@@ -7771,41 +7833,6 @@ function scanExtensionPatterns(ext, content) {
|
|
|
7771
7833
|
}
|
|
7772
7834
|
return null;
|
|
7773
7835
|
}
|
|
7774
|
-
function scanScriptChainWithL1(chain, input, ext) {
|
|
7775
|
-
for (const node of chain.nodes) {
|
|
7776
|
-
if (node.error || !node.preprocessedContent || node.l1Hit) continue;
|
|
7777
|
-
const virtualInput = {
|
|
7778
|
-
...input,
|
|
7779
|
-
aNext: { actionType: "bash", actionDetail: node.preprocessedContent }
|
|
7780
|
-
};
|
|
7781
|
-
const l1 = scanDangerousCommandPatterns("bash", node.preprocessedContent, input.osType);
|
|
7782
|
-
const extHit = scanExtensionPatterns(ext, node.preprocessedContent);
|
|
7783
|
-
if (extHit) {
|
|
7784
|
-
node.l1Hit = true;
|
|
7785
|
-
node.l1RiskLevel = extHit.riskLevel;
|
|
7786
|
-
node.l1RiskType = extHit.riskType;
|
|
7787
|
-
node.l1Reason = extHit.reason;
|
|
7788
|
-
if (extHit.riskLevel === "critical") {
|
|
7789
|
-
chain.hasCritical = true;
|
|
7790
|
-
chain.firstHitNode = node;
|
|
7791
|
-
break;
|
|
7792
|
-
}
|
|
7793
|
-
continue;
|
|
7794
|
-
}
|
|
7795
|
-
if (l1 && !l1.allowed) {
|
|
7796
|
-
node.l1Hit = true;
|
|
7797
|
-
node.l1RiskLevel = l1.riskLevel;
|
|
7798
|
-
node.l1RiskType = l1.riskType;
|
|
7799
|
-
node.l1Reason = l1.reason;
|
|
7800
|
-
if (l1.riskLevel === "critical") {
|
|
7801
|
-
chain.hasCritical = true;
|
|
7802
|
-
chain.firstHitNode = node;
|
|
7803
|
-
break;
|
|
7804
|
-
}
|
|
7805
|
-
}
|
|
7806
|
-
}
|
|
7807
|
-
return chain;
|
|
7808
|
-
}
|
|
7809
7836
|
function scanScriptChainWithL2(chain, input) {
|
|
7810
7837
|
for (const node of chain.nodes) {
|
|
7811
7838
|
if (node.error || !node.preprocessedContent) continue;
|
|
@@ -7871,6 +7898,16 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
|
7871
7898
|
resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
|
|
7872
7899
|
}
|
|
7873
7900
|
const l1Adapter = (content) => {
|
|
7901
|
+
const extHit = scanExtensionPatterns(ext, content);
|
|
7902
|
+
if (extHit) {
|
|
7903
|
+
return {
|
|
7904
|
+
hit: true,
|
|
7905
|
+
riskLevel: extHit.riskLevel,
|
|
7906
|
+
riskType: extHit.riskType,
|
|
7907
|
+
reason: extHit.reason,
|
|
7908
|
+
matchedPatterns: []
|
|
7909
|
+
};
|
|
7910
|
+
}
|
|
7874
7911
|
const j = scanDangerousCommandPatterns("bash", content, input.osType);
|
|
7875
7912
|
if (j && !j.allowed) {
|
|
7876
7913
|
return {
|
|
@@ -7894,7 +7931,6 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
|
7894
7931
|
);
|
|
7895
7932
|
const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
|
|
7896
7933
|
if (chain.nodes.length === 0) return chain;
|
|
7897
|
-
scanScriptChainWithL1(chain, input, ext);
|
|
7898
7934
|
scanScriptChainWithL2(chain, input);
|
|
7899
7935
|
scanScriptChainKeywords(chain);
|
|
7900
7936
|
return chain;
|
|
@@ -8382,8 +8418,8 @@ var init_metrics = __esm({
|
|
|
8382
8418
|
};
|
|
8383
8419
|
ANALYZE_TOTAL = new Counter(
|
|
8384
8420
|
"agent_moss_analyze_total",
|
|
8385
|
-
"Total analyze requests handled, by decision and
|
|
8386
|
-
["decision", "risk_level"]
|
|
8421
|
+
"Total analyze requests handled, by decision, risk level and L3 outcome.",
|
|
8422
|
+
["decision", "risk_level", "l3_outcome"]
|
|
8387
8423
|
);
|
|
8388
8424
|
ANALYZE_DURATION = new Histogram(
|
|
8389
8425
|
"agent_moss_analyze_duration_seconds",
|
|
@@ -8666,6 +8702,42 @@ var init_token_stats = __esm({
|
|
|
8666
8702
|
import { createHash as createHash3 } from "crypto";
|
|
8667
8703
|
import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
|
|
8668
8704
|
import OpenAI from "openai";
|
|
8705
|
+
function reasoningTextFallback(raw) {
|
|
8706
|
+
if (typeof raw !== "string") return "";
|
|
8707
|
+
let text = raw.trim();
|
|
8708
|
+
if (text.startsWith("```")) {
|
|
8709
|
+
text = text.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "").trim();
|
|
8710
|
+
}
|
|
8711
|
+
if (!(text.startsWith("{") && text.endsWith("}"))) return "";
|
|
8712
|
+
let parsed;
|
|
8713
|
+
try {
|
|
8714
|
+
parsed = JSON.parse(text);
|
|
8715
|
+
} catch {
|
|
8716
|
+
return "";
|
|
8717
|
+
}
|
|
8718
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
8719
|
+
if ("allowed" in parsed || "decision" in parsed || "risk_level" in parsed) {
|
|
8720
|
+
return text;
|
|
8721
|
+
}
|
|
8722
|
+
}
|
|
8723
|
+
return "";
|
|
8724
|
+
}
|
|
8725
|
+
function reasoningFallbackWithField(message) {
|
|
8726
|
+
if (!message || typeof message !== "object") return { text: "", field: "" };
|
|
8727
|
+
for (const key of ["reasoning", "reasoning_content", "thinking"]) {
|
|
8728
|
+
const got = reasoningTextFallback(message[key]);
|
|
8729
|
+
if (got) return { text: got, field: key };
|
|
8730
|
+
}
|
|
8731
|
+
return { text: "", field: "" };
|
|
8732
|
+
}
|
|
8733
|
+
function describeContentState(raw) {
|
|
8734
|
+
if (raw === null) return "null";
|
|
8735
|
+
if (raw === void 0) return "undefined";
|
|
8736
|
+
const text = typeof raw === "string" ? raw : String(raw);
|
|
8737
|
+
if (text === "") return "empty_string";
|
|
8738
|
+
if (!text.trim()) return `whitespace_only(${text.length})`;
|
|
8739
|
+
return `non_empty(${text.length})`;
|
|
8740
|
+
}
|
|
8669
8741
|
function responseFieldLengths(message) {
|
|
8670
8742
|
if (!message || typeof message !== "object") return {};
|
|
8671
8743
|
const out = {};
|
|
@@ -8923,6 +8995,7 @@ function formatHints(previous) {
|
|
|
8923
8995
|
async function analyzeWithLLM(prompt, config) {
|
|
8924
8996
|
console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
|
|
8925
8997
|
const _llmStart = performance.now();
|
|
8998
|
+
let usedReasoningFallback = false;
|
|
8926
8999
|
const _recordLlm = (result) => {
|
|
8927
9000
|
try {
|
|
8928
9001
|
LLM_CALLS_TOTAL.inc(1, { result });
|
|
@@ -8958,7 +9031,7 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
8958
9031
|
} catch {
|
|
8959
9032
|
}
|
|
8960
9033
|
_recordLlm("error");
|
|
8961
|
-
throw new
|
|
9034
|
+
throw new LLMCircuitOpenError(
|
|
8962
9035
|
"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"
|
|
8963
9036
|
);
|
|
8964
9037
|
}
|
|
@@ -8980,10 +9053,21 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
8980
9053
|
...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
|
|
8981
9054
|
});
|
|
8982
9055
|
const message = response.choices[0]?.message;
|
|
8983
|
-
|
|
9056
|
+
let content = message?.content ?? "";
|
|
8984
9057
|
const finishReason = response.choices[0]?.finish_reason;
|
|
8985
9058
|
const fieldLengths = responseFieldLengths(message);
|
|
8986
9059
|
const usage = response.usage;
|
|
9060
|
+
if (!content) {
|
|
9061
|
+
const { text: fallback, field } = reasoningFallbackWithField(message);
|
|
9062
|
+
if (fallback) {
|
|
9063
|
+
const origState = describeContentState(message?.content);
|
|
9064
|
+
console.warn(
|
|
9065
|
+
`[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`
|
|
9066
|
+
);
|
|
9067
|
+
content = fallback;
|
|
9068
|
+
usedReasoningFallback = true;
|
|
9069
|
+
}
|
|
9070
|
+
}
|
|
8987
9071
|
if (!content) {
|
|
8988
9072
|
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 ?? "?"}`;
|
|
8989
9073
|
traceFull("l3.empty_response", {
|
|
@@ -9056,7 +9140,9 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
9056
9140
|
riskLevel: ["low", "medium", "high", "critical"].includes(riskLevel) ? riskLevel : "low",
|
|
9057
9141
|
riskType: riskType || "",
|
|
9058
9142
|
confidence: typeof parsed.confidence === "number" ? Math.min(100, Math.max(0, parsed.confidence)) : 70,
|
|
9059
|
-
|
|
9143
|
+
// 判定结果一样可用,但运维要能看出模型行为异常
|
|
9144
|
+
// (下游据此填 l3Outcome 与 degraded)。
|
|
9145
|
+
source: usedReasoningFallback ? "llm_reasoning_fallback" : "llm",
|
|
9060
9146
|
violatedLayers: ["L3.1"]
|
|
9061
9147
|
};
|
|
9062
9148
|
} catch (err) {
|
|
@@ -9082,7 +9168,7 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
9082
9168
|
clearTimeout(totalTimeoutTimer);
|
|
9083
9169
|
throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
|
|
9084
9170
|
}
|
|
9085
|
-
var llmCache, LLM_CACHE_MAX;
|
|
9171
|
+
var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
|
|
9086
9172
|
var init_llm_analyzer = __esm({
|
|
9087
9173
|
"src/engine/llm-analyzer.ts"() {
|
|
9088
9174
|
"use strict";
|
|
@@ -9096,6 +9182,12 @@ var init_llm_analyzer = __esm({
|
|
|
9096
9182
|
init_trace_log();
|
|
9097
9183
|
init_metrics();
|
|
9098
9184
|
init_circuit_breaker();
|
|
9185
|
+
LLMCircuitOpenError = class extends Error {
|
|
9186
|
+
constructor(message) {
|
|
9187
|
+
super(message);
|
|
9188
|
+
this.name = "LLMCircuitOpenError";
|
|
9189
|
+
}
|
|
9190
|
+
};
|
|
9099
9191
|
llmCache = /* @__PURE__ */ new Map();
|
|
9100
9192
|
LLM_CACHE_MAX = 200;
|
|
9101
9193
|
}
|
|
@@ -9945,7 +10037,7 @@ var init_curator = __esm({
|
|
|
9945
10037
|
});
|
|
9946
10038
|
|
|
9947
10039
|
// src/brain/contributor.ts
|
|
9948
|
-
import { dirname as
|
|
10040
|
+
import { dirname as dirname11 } from "path";
|
|
9949
10041
|
import { fileURLToPath as fileURLToPath9 } from "url";
|
|
9950
10042
|
var __dirname8;
|
|
9951
10043
|
var init_contributor = __esm({
|
|
@@ -9955,7 +10047,7 @@ var init_contributor = __esm({
|
|
|
9955
10047
|
init_rule_store();
|
|
9956
10048
|
init_skill_manager();
|
|
9957
10049
|
init_asset_dir();
|
|
9958
|
-
__dirname8 =
|
|
10050
|
+
__dirname8 = dirname11(fileURLToPath9(import.meta.url));
|
|
9959
10051
|
}
|
|
9960
10052
|
});
|
|
9961
10053
|
|
|
@@ -12483,6 +12575,7 @@ async function runAnalysis(input) {
|
|
|
12483
12575
|
pathContext
|
|
12484
12576
|
});
|
|
12485
12577
|
} catch (e) {
|
|
12578
|
+
const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
|
|
12486
12579
|
const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
|
|
12487
12580
|
if (getLLMFailMode2() === "fail_open") {
|
|
12488
12581
|
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}`);
|
|
@@ -12492,7 +12585,7 @@ async function runAnalysis(input) {
|
|
|
12492
12585
|
riskLevel: "low",
|
|
12493
12586
|
riskType: "",
|
|
12494
12587
|
confidence: 50,
|
|
12495
|
-
source:
|
|
12588
|
+
source: failSource,
|
|
12496
12589
|
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
|
|
12497
12590
|
};
|
|
12498
12591
|
}
|
|
@@ -12502,7 +12595,7 @@ async function runAnalysis(input) {
|
|
|
12502
12595
|
riskLevel: "medium",
|
|
12503
12596
|
riskType: "",
|
|
12504
12597
|
confidence: 60,
|
|
12505
|
-
source:
|
|
12598
|
+
source: failSource,
|
|
12506
12599
|
violatedLayers: ["L3.1"]
|
|
12507
12600
|
};
|
|
12508
12601
|
}
|
|
@@ -12710,7 +12803,7 @@ import { cors } from "hono/cors";
|
|
|
12710
12803
|
import { logger } from "hono/logger";
|
|
12711
12804
|
import net from "net";
|
|
12712
12805
|
import { existsSync as existsSync21, writeFileSync as writeFileSync6, renameSync as renameSync3, mkdirSync as mkdirSync8 } from "fs";
|
|
12713
|
-
import { dirname as
|
|
12806
|
+
import { dirname as dirname15, join as join21 } from "path";
|
|
12714
12807
|
|
|
12715
12808
|
// src/routes.ts
|
|
12716
12809
|
init_esm_shims();
|
|
@@ -12787,6 +12880,20 @@ var AnalyzeResponseSchema = z.object({
|
|
|
12787
12880
|
violation_chain: z.array(z.array(z.union([z.string(), z.number()]).nullable())).default([]),
|
|
12788
12881
|
// 本次判定的能力降级说明(2026-11):正常为空;链状态触顶时说明 L2.2 未覆盖
|
|
12789
12882
|
degraded: z.array(z.string()).default([]),
|
|
12883
|
+
// 本次 L3(LLM 语义分析)的实际结局(2026-11,稳定枚举,对齐 Python):
|
|
12884
|
+
// 让调用方不读日志就能区分「L3 认真判过的 Allow」和「L3 挂了 fail_open 放的」。
|
|
12885
|
+
l3_outcome: z.enum([
|
|
12886
|
+
"ok",
|
|
12887
|
+
"reasoning_fallback",
|
|
12888
|
+
"not_reached",
|
|
12889
|
+
"skipped",
|
|
12890
|
+
"fail_open",
|
|
12891
|
+
"fail_closed",
|
|
12892
|
+
"failed_but_blocked",
|
|
12893
|
+
"circuit_open",
|
|
12894
|
+
""
|
|
12895
|
+
// 未算出(极端异常路径)
|
|
12896
|
+
]).default(""),
|
|
12790
12897
|
// 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
|
|
12791
12898
|
violation_graph: z.object({
|
|
12792
12899
|
// 性质元信息(前端展示"违反了哪条性质")
|
|
@@ -12870,6 +12977,19 @@ import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
|
|
|
12870
12977
|
import { tmpdir as tmpdir3 } from "os";
|
|
12871
12978
|
import { join as join17, resolve as resolve11 } from "path";
|
|
12872
12979
|
|
|
12980
|
+
// src/engine/types.ts
|
|
12981
|
+
init_esm_shims();
|
|
12982
|
+
function deriveL3Outcome(j) {
|
|
12983
|
+
const src = (j.source || "").toLowerCase();
|
|
12984
|
+
if (src === "llm" || src === "llm_extracted") return "ok";
|
|
12985
|
+
if (src === "llm_reasoning_fallback") return "reasoning_fallback";
|
|
12986
|
+
if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
|
|
12987
|
+
if (src === "llm_circuit_open") return "circuit_open";
|
|
12988
|
+
if (src === "llm_failure_with_violation") return "failed_but_blocked";
|
|
12989
|
+
if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
|
|
12990
|
+
return "not_reached";
|
|
12991
|
+
}
|
|
12992
|
+
|
|
12873
12993
|
// src/infra/policy-cache.ts
|
|
12874
12994
|
init_esm_shims();
|
|
12875
12995
|
init_security_policy();
|
|
@@ -13215,9 +13335,15 @@ function allowResult(policy, judgment) {
|
|
|
13215
13335
|
violated_layers: judgment.violatedLayers || [],
|
|
13216
13336
|
policy,
|
|
13217
13337
|
violated_policy: "",
|
|
13218
|
-
confidence: judgment.confidence
|
|
13338
|
+
confidence: judgment.confidence,
|
|
13339
|
+
// 判定成功算出时才推导(对齐 Python `_finalize`)
|
|
13340
|
+
...judgment.source !== void 0 ? { l3_outcome: deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed ?? true }) } : {}
|
|
13219
13341
|
};
|
|
13220
13342
|
}
|
|
13343
|
+
function withL3(res, judgment) {
|
|
13344
|
+
res.l3_outcome = deriveL3Outcome({ source: judgment.source, allowed: judgment.allowed });
|
|
13345
|
+
return res;
|
|
13346
|
+
}
|
|
13221
13347
|
async function analyze(input) {
|
|
13222
13348
|
const mossLog = new MossLogger(input.sessionId);
|
|
13223
13349
|
try {
|
|
@@ -13244,7 +13370,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13244
13370
|
const judgment = await runAnalysis(input);
|
|
13245
13371
|
mossLog.endStep(
|
|
13246
13372
|
"step1_security_judge",
|
|
13247
|
-
`allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}`
|
|
13373
|
+
`allowed=${judgment.allowed}, risk_level=${judgment.riskLevel}, source=${judgment.source}, l3_outcome=${deriveL3Outcome(judgment)}`
|
|
13248
13374
|
);
|
|
13249
13375
|
if (!judgment.allowed) {
|
|
13250
13376
|
const denied = {
|
|
@@ -13260,7 +13386,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13260
13386
|
violation_chain: judgment.violationChain ?? []
|
|
13261
13387
|
};
|
|
13262
13388
|
mossLog.logResult("Deny", denied.reason);
|
|
13263
|
-
return denied;
|
|
13389
|
+
return withL3(denied, judgment);
|
|
13264
13390
|
}
|
|
13265
13391
|
const cache3 = getDefaultCache();
|
|
13266
13392
|
mossLog.startStep("step2_cache_lookup");
|
|
@@ -13270,7 +13396,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13270
13396
|
savePolicyToFile(input.sessionId, cached2);
|
|
13271
13397
|
const res = allowResult(cached2, judgment);
|
|
13272
13398
|
mossLog.logResult("Allow", res.reason, cached2);
|
|
13273
|
-
return res;
|
|
13399
|
+
return withL3(res, judgment);
|
|
13274
13400
|
}
|
|
13275
13401
|
if (!isPolicyGenEnabled()) {
|
|
13276
13402
|
mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0CPolicy \u751F\u6210\u5DF2\u7981\u7528");
|
|
@@ -13280,7 +13406,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13280
13406
|
const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
|
|
13281
13407
|
mossLog.endStep("step2_default_policy", "\u4F7F\u7528\u9ED8\u8BA4\u6700\u5C0F\u6743\u9650 Policy");
|
|
13282
13408
|
mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
|
|
13283
|
-
return res;
|
|
13409
|
+
return withL3(res, judgment);
|
|
13284
13410
|
}
|
|
13285
13411
|
if (judgment.source === "whitelist_bypass") {
|
|
13286
13412
|
mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u767D\u540D\u5355\u5DE5\u5177");
|
|
@@ -13288,7 +13414,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13288
13414
|
savePolicyToFile(input.sessionId, DEFAULT_READONLY_POLICY);
|
|
13289
13415
|
const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
|
|
13290
13416
|
mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
|
|
13291
|
-
return res;
|
|
13417
|
+
return withL3(res, judgment);
|
|
13292
13418
|
}
|
|
13293
13419
|
mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u542F\u7528 LLM \u751F\u6210");
|
|
13294
13420
|
mossLog.startStep("step2_generate_policy");
|
|
@@ -13299,7 +13425,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13299
13425
|
mossLog.endStep("step2_generate_policy", "Policy \u751F\u6210\u5E76\u7F13\u5B58\u6210\u529F");
|
|
13300
13426
|
const res = allowResult(policy, judgment);
|
|
13301
13427
|
mossLog.logResult("Allow", res.reason, policy);
|
|
13302
|
-
return res;
|
|
13428
|
+
return withL3(res, judgment);
|
|
13303
13429
|
} catch (err) {
|
|
13304
13430
|
mossLog.endStep("step2_generate_policy", `\u5931\u8D25: ${String(err)}`);
|
|
13305
13431
|
mossLog.logError("step2_generate_policy", err);
|
|
@@ -13314,7 +13440,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
13314
13440
|
confidence: judgment.confidence
|
|
13315
13441
|
};
|
|
13316
13442
|
mossLog.logResult("Deny", failed.reason);
|
|
13317
|
-
return failed;
|
|
13443
|
+
return withL3(failed, judgment);
|
|
13318
13444
|
}
|
|
13319
13445
|
}
|
|
13320
13446
|
|
|
@@ -13728,9 +13854,9 @@ function poolsSnapshot() {
|
|
|
13728
13854
|
|
|
13729
13855
|
// src/routes.ts
|
|
13730
13856
|
init_metrics();
|
|
13731
|
-
import { join as join19, dirname as
|
|
13857
|
+
import { join as join19, dirname as dirname13 } from "path";
|
|
13732
13858
|
import { fileURLToPath as fileURLToPath10 } from "url";
|
|
13733
|
-
var __dirname9 =
|
|
13859
|
+
var __dirname9 = dirname13(fileURLToPath10(import.meta.url));
|
|
13734
13860
|
async function healthRoute(c) {
|
|
13735
13861
|
const metrics = {};
|
|
13736
13862
|
try {
|
|
@@ -13880,6 +14006,24 @@ async function analyzeRoute(c) {
|
|
|
13880
14006
|
llmLogPath: req.metadata?.llm_log_path
|
|
13881
14007
|
});
|
|
13882
14008
|
const durationMs = performance.now() - t0;
|
|
14009
|
+
const _l3FailMsg = String(result.reason || "").slice(0, 160);
|
|
14010
|
+
if (result.l3_outcome === "reasoning_fallback") {
|
|
14011
|
+
degradedNotes.push(
|
|
14012
|
+
"\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"
|
|
14013
|
+
);
|
|
14014
|
+
} else if (result.l3_outcome === "fail_open") {
|
|
14015
|
+
degradedNotes.push(
|
|
14016
|
+
`\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`
|
|
14017
|
+
);
|
|
14018
|
+
} else if (result.l3_outcome === "fail_closed") {
|
|
14019
|
+
degradedNotes.push(
|
|
14020
|
+
`\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`
|
|
14021
|
+
);
|
|
14022
|
+
} else if (result.l3_outcome === "circuit_open") {
|
|
14023
|
+
degradedNotes.push(
|
|
14024
|
+
`\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`
|
|
14025
|
+
);
|
|
14026
|
+
}
|
|
13883
14027
|
const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
|
|
13884
14028
|
if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
|
|
13885
14029
|
console.warn(
|
|
@@ -13887,7 +14031,11 @@ async function analyzeRoute(c) {
|
|
|
13887
14031
|
);
|
|
13888
14032
|
}
|
|
13889
14033
|
try {
|
|
13890
|
-
ANALYZE_TOTAL.inc(1, {
|
|
14034
|
+
ANALYZE_TOTAL.inc(1, {
|
|
14035
|
+
decision: result.decision,
|
|
14036
|
+
risk_level: result.risk_level,
|
|
14037
|
+
l3_outcome: result.l3_outcome || ""
|
|
14038
|
+
});
|
|
13891
14039
|
ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
|
|
13892
14040
|
for (const layer of result.violated_layers || []) {
|
|
13893
14041
|
LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
|
|
@@ -13901,7 +14049,9 @@ async function analyzeRoute(c) {
|
|
|
13901
14049
|
risk_type: result.risk_type,
|
|
13902
14050
|
reason: result.reason,
|
|
13903
14051
|
violated_layers: result.violated_layers,
|
|
13904
|
-
duration_ms: Math.round(durationMs * 10) / 10
|
|
14052
|
+
duration_ms: Math.round(durationMs * 10) / 10,
|
|
14053
|
+
// 2026-11:L3 结局(区分「L3 判过」与「L3 挂了放的」)
|
|
14054
|
+
l3_outcome: result.l3_outcome || ""
|
|
13905
14055
|
});
|
|
13906
14056
|
try {
|
|
13907
14057
|
reportEnforcementEvent({
|
|
@@ -13992,7 +14142,10 @@ async function analyzeRoute(c) {
|
|
|
13992
14142
|
violation_chain: result.violation_chain ?? [],
|
|
13993
14143
|
violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
|
|
13994
14144
|
// 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
|
|
13995
|
-
degraded: degradedNotes
|
|
14145
|
+
degraded: degradedNotes,
|
|
14146
|
+
// L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
|
|
14147
|
+
// 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
|
|
14148
|
+
l3_outcome: result.l3_outcome || ""
|
|
13996
14149
|
})
|
|
13997
14150
|
);
|
|
13998
14151
|
} catch (err) {
|
|
@@ -14235,9 +14388,9 @@ init_rules_mode();
|
|
|
14235
14388
|
import { Hono } from "hono";
|
|
14236
14389
|
import { timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
14237
14390
|
import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
|
|
14238
|
-
import { join as join20, dirname as
|
|
14391
|
+
import { join as join20, dirname as dirname14 } from "path";
|
|
14239
14392
|
import { fileURLToPath as fileURLToPath11 } from "url";
|
|
14240
|
-
var __dirname10 =
|
|
14393
|
+
var __dirname10 = dirname14(fileURLToPath11(import.meta.url));
|
|
14241
14394
|
var STATIC_DIR = join20(__dirname10, "static");
|
|
14242
14395
|
var CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
|
|
14243
14396
|
function getConsoleToken() {
|
|
@@ -14477,7 +14630,7 @@ function createConsoleRouter() {
|
|
|
14477
14630
|
if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
|
|
14478
14631
|
return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
|
|
14479
14632
|
}
|
|
14480
|
-
const userPath = join20(
|
|
14633
|
+
const userPath = join20(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
|
|
14481
14634
|
const builtinDir = resolveAssetDir(__dirname10, "skills");
|
|
14482
14635
|
const candidates = [
|
|
14483
14636
|
...isRuntimeConfigDisabled() ? [] : [userPath],
|
|
@@ -14909,7 +15062,7 @@ async function warmUpEngine() {
|
|
|
14909
15062
|
function writePortFile(port) {
|
|
14910
15063
|
try {
|
|
14911
15064
|
const path8 = join21(getDataRoot(), "agent_moss_server.port.json");
|
|
14912
|
-
mkdirSync8(
|
|
15065
|
+
mkdirSync8(dirname15(path8), { recursive: true });
|
|
14913
15066
|
const payload = JSON.stringify({
|
|
14914
15067
|
port,
|
|
14915
15068
|
pid: process.pid,
|
|
@@ -14960,8 +15113,8 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
|
|
|
14960
15113
|
serve: async () => {
|
|
14961
15114
|
failFastOnAuthError();
|
|
14962
15115
|
const { mkdirSync: mkdirSync9, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
|
|
14963
|
-
const { dirname:
|
|
14964
|
-
const dir =
|
|
15116
|
+
const { dirname: dirname16 } = await import("path");
|
|
15117
|
+
const dir = dirname16(socketPath);
|
|
14965
15118
|
if (dir) {
|
|
14966
15119
|
try {
|
|
14967
15120
|
mkdirSync9(dir, { recursive: true });
|