@kenhkl/agent-moss 0.17.41 → 0.17.43
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/agents/clawpartner/rules.json +14 -0
- package/dist/cli.js +942 -267
- package/dist/engine/coordinator.d.ts +7 -0
- package/dist/engine/coordinator.js +543 -126
- package/dist/rules/l2_rules.json +57 -3
- package/dist/scenarios/cloud/rules.json +11 -0
- package/dist/scenarios/endpoint/rules.json +11 -0
- package/dist/server.js +877 -220
- package/dist/templates/security_judge_template.txt +1 -1
- package/package.json +1 -1
|
@@ -1430,11 +1430,64 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
|
|
|
1430
1430
|
}
|
|
1431
1431
|
return false;
|
|
1432
1432
|
}
|
|
1433
|
+
function intentKeywordNegated(text, index) {
|
|
1434
|
+
if (NEGATION_WORDS.length === 0 || index <= 0) return false;
|
|
1435
|
+
const prefix = text.slice(Math.max(0, index - NEGATION_WINDOW), index);
|
|
1436
|
+
return NEGATION_WORDS.some((neg) => prefix.includes(neg));
|
|
1437
|
+
}
|
|
1438
|
+
function isBuildArtifactCleanup(actionDetail) {
|
|
1439
|
+
const text = (actionDetail || "").trim();
|
|
1440
|
+
if (!text) return false;
|
|
1441
|
+
let foundRm = false;
|
|
1442
|
+
const targets = [];
|
|
1443
|
+
for (const raw of splitCommandSegments(text)) {
|
|
1444
|
+
const s = raw.trim();
|
|
1445
|
+
if (!s) continue;
|
|
1446
|
+
let parts = s.split(/\s+/);
|
|
1447
|
+
if (parts[0]?.toLowerCase() === "sudo" || parts[0]?.toLowerCase() === "command") {
|
|
1448
|
+
parts = parts.slice(1);
|
|
1449
|
+
}
|
|
1450
|
+
if (!parts.length || parts[0].toLowerCase() !== "rm") continue;
|
|
1451
|
+
foundRm = true;
|
|
1452
|
+
for (const rawTok of parts.slice(1)) {
|
|
1453
|
+
const tok = rawTok.replace(/^['"]+|['"]+$/g, "");
|
|
1454
|
+
if (!tok || tok.startsWith("-")) continue;
|
|
1455
|
+
targets.push(tok);
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
if (!foundRm || targets.length === 0) return false;
|
|
1459
|
+
for (const target of targets) {
|
|
1460
|
+
let t = target.replace(/\\/g, "/");
|
|
1461
|
+
if (t.startsWith("/") || t.split("/").includes("..")) return false;
|
|
1462
|
+
while (t.startsWith("./")) t = t.slice(2);
|
|
1463
|
+
if (!t || [".", "*", "?"].includes(t)) return false;
|
|
1464
|
+
if (t.includes("*") || t.includes("?")) {
|
|
1465
|
+
if (!BUILD_ARTIFACT_GLOB_RE.test(t)) return false;
|
|
1466
|
+
continue;
|
|
1467
|
+
}
|
|
1468
|
+
const first = t.split("/")[0].toLowerCase();
|
|
1469
|
+
if (!BUILD_ARTIFACT_NAMES.has(first)) return false;
|
|
1470
|
+
}
|
|
1471
|
+
return true;
|
|
1472
|
+
}
|
|
1433
1473
|
function intentCategories(text) {
|
|
1434
1474
|
const t = (text || "").toLowerCase();
|
|
1435
1475
|
const out = /* @__PURE__ */ new Set();
|
|
1436
1476
|
for (const [cat, kws] of Object.entries(INTENT_CATEGORIES)) {
|
|
1437
|
-
|
|
1477
|
+
for (const kw of kws) {
|
|
1478
|
+
const needle = String(kw).toLowerCase();
|
|
1479
|
+
let start = 0;
|
|
1480
|
+
while (true) {
|
|
1481
|
+
const idx = t.indexOf(needle, start);
|
|
1482
|
+
if (idx < 0) break;
|
|
1483
|
+
if (!intentKeywordNegated(t, idx)) {
|
|
1484
|
+
out.add(cat);
|
|
1485
|
+
break;
|
|
1486
|
+
}
|
|
1487
|
+
start = idx + needle.length;
|
|
1488
|
+
}
|
|
1489
|
+
if (out.has(cat)) break;
|
|
1490
|
+
}
|
|
1438
1491
|
}
|
|
1439
1492
|
return out;
|
|
1440
1493
|
}
|
|
@@ -1537,6 +1590,52 @@ function checkIntentConsistency(input, agentExt) {
|
|
|
1537
1590
|
}
|
|
1538
1591
|
const actionCat = actionCategory(actionType, aNext.actionDetail, input.osType, extraWriteTools);
|
|
1539
1592
|
const reasonKey = intentMatrixViolation(intents, actionCat);
|
|
1593
|
+
const isReferencePrompt = REFERENCE_PRIOR_RE.test((promptSession || "").trim().toLowerCase());
|
|
1594
|
+
if (reasonKey === "read->overwrite" && !EXPLICIT_READONLY_RE.test(intentText) && !isReferencePrompt) {
|
|
1595
|
+
console.debug(
|
|
1596
|
+
`[intent] \u8BFB\u610F\u56FE + \u8986\u76D6\u52A8\u4F5C\uFF0C\u7F3A\u5C11\u660E\u786E\u53EA\u8BFB\u7EA6\u675F\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
|
|
1597
|
+
);
|
|
1598
|
+
return {
|
|
1599
|
+
allowed: true,
|
|
1600
|
+
reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
|
|
1601
|
+
riskLevel: "low",
|
|
1602
|
+
riskType: "",
|
|
1603
|
+
confidence: 50,
|
|
1604
|
+
source: "logic_rule",
|
|
1605
|
+
violatedLayers: [],
|
|
1606
|
+
l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u51FA\u73B0\u8BFB\u610F\u56FE\u8BCD\uFF0C\u4F46\u5F53\u524D\u52A8\u4F5C\u662F\u8986\u76D6\u5199\uFF0Cprompt \u6CA1\u6709\u660E\u786E\u201C\u53EA\u8BFB/\u4E0D\u8981\u4FEE\u6539\u201D\u7EA6\u675F\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
if ((reasonKey === "read->delete" || reasonKey === "write->delete") && UPDATE_INTENT_RE.test(intentText) && !EXPLICIT_NO_DELETE_RE.test(intentText)) {
|
|
1610
|
+
console.debug(
|
|
1611
|
+
`[intent] \u66F4\u65B0\u7C7B\u610F\u56FE + \u5220\u9664\u52A8\u4F5C\uFF0C\u53EF\u80FD\u5305\u542B\u66FF\u6362\u6D41\u7A0B\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
|
|
1612
|
+
);
|
|
1613
|
+
return {
|
|
1614
|
+
allowed: true,
|
|
1615
|
+
reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
|
|
1616
|
+
riskLevel: "low",
|
|
1617
|
+
riskType: "",
|
|
1618
|
+
confidence: 50,
|
|
1619
|
+
source: "logic_rule",
|
|
1620
|
+
violatedLayers: [],
|
|
1621
|
+
l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u51FA\u73B0\u66F4\u65B0/\u4FEE\u6539\u7C7B\u610F\u56FE\uFF0C\u4F46\u5F53\u524D\u52A8\u4F5C\u662F\u5220\u9664\uFF0C\u53EF\u80FD\u662F\u5148\u5220\u65E7\u518D\u5199\u65B0\u7684\u66FF\u6362\u6D41\u7A0B\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
|
|
1622
|
+
};
|
|
1623
|
+
}
|
|
1624
|
+
if ((reasonKey === "read->delete" || reasonKey === "write->delete") && !isReferencePrompt && INTENT_AMBIGUITY_RE.test(intentText)) {
|
|
1625
|
+
console.debug(
|
|
1626
|
+
`[intent] \u610F\u56FE\u8BCD\u5B58\u5728\u6B67\u4E49\u4E0A\u4E0B\u6587\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
|
|
1627
|
+
);
|
|
1628
|
+
return {
|
|
1629
|
+
allowed: true,
|
|
1630
|
+
reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
|
|
1631
|
+
riskLevel: "low",
|
|
1632
|
+
riskType: "",
|
|
1633
|
+
confidence: 50,
|
|
1634
|
+
source: "logic_rule",
|
|
1635
|
+
violatedLayers: [],
|
|
1636
|
+
l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u610F\u56FE\u8BCD\u51FA\u73B0\u5728\u53EF\u80FD\u6539\u53D8\u542B\u4E49\u7684\u4E0A\u4E0B\u6587\uFF08\u5904\u7406/\u6761\u4EF6/\u793A\u4F8B/\u6309\u94AE/\u6307\u4EE3\u7B49\uFF09\u4E2D\uFF0C\u4E0D\u80FD\u4EC5\u51ED\u5173\u952E\u8BCD\u5224\u504F\u79BB\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
|
|
1637
|
+
};
|
|
1638
|
+
}
|
|
1540
1639
|
if (reasonKey !== null) {
|
|
1541
1640
|
return {
|
|
1542
1641
|
allowed: false,
|
|
@@ -2053,7 +2152,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
|
|
|
2053
2152
|
violatedLayers: ["L2.1"]
|
|
2054
2153
|
};
|
|
2055
2154
|
}
|
|
2056
|
-
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;
|
|
2155
|
+
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, NEGATION_WORDS, NEGATION_WINDOW, EXPLICIT_READONLY_RE, UPDATE_INTENT_RE, EXPLICIT_NO_DELETE_RE, INTENT_AMBIGUITY_RE, BUILD_ARTIFACT_NAMES, BUILD_ARTIFACT_GLOB_RE, 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;
|
|
2057
2156
|
var init_logic_rules = __esm({
|
|
2058
2157
|
"src/engine/logic-rules.ts"() {
|
|
2059
2158
|
"use strict";
|
|
@@ -2155,6 +2254,31 @@ var init_logic_rules = __esm({
|
|
|
2155
2254
|
(INTENT_MATRIX.delete_action_words || []).map((w) => String(w).toLowerCase())
|
|
2156
2255
|
);
|
|
2157
2256
|
ALL_INTENT_KEYWORDS = Object.values(INTENT_CATEGORIES).flat();
|
|
2257
|
+
NEGATION_WORDS = (INTENT_MATRIX.negation_words || []).map((w) => String(w).toLowerCase());
|
|
2258
|
+
NEGATION_WINDOW = 8;
|
|
2259
|
+
EXPLICIT_READONLY_RE = /(?:只读|仅读|只看|仅看|只查看|仅查看|只分析|仅分析|只做分析|只查询|仅查询|不要(?:修改|写入|写|改动|动)|禁止(?:修改|写入|写|改动)|不得(?:修改|写入|写|改动)|别(?:修改|写入|写|动)|read[- ]only|do not (?:modify|write|change)|don't (?:modify|write|change))/i;
|
|
2260
|
+
UPDATE_INTENT_RE = /(?:更新|修改|编辑|替换|覆盖|改成|改到|rename|replace|update|modify|edit)/i;
|
|
2261
|
+
EXPLICIT_NO_DELETE_RE = /(?:不要|禁止|不得|别|切勿)\s*(?:删除|删掉|删|移除|remove|delete|rm)/i;
|
|
2262
|
+
INTENT_AMBIGUITY_RE = /(?:处理|整理|优化|调整|清掉|如果|假如|若|或者|还是|看情况|根据|按.{0,6}要求|继续|之前|上次|刚才|顺便|示例|例如|比如|按钮|接口|函数|字段|变量|代码里|可能|建议|评估|考虑)/i;
|
|
2263
|
+
BUILD_ARTIFACT_NAMES = /* @__PURE__ */ new Set([
|
|
2264
|
+
"build",
|
|
2265
|
+
"dist",
|
|
2266
|
+
"target",
|
|
2267
|
+
"out",
|
|
2268
|
+
"tmp",
|
|
2269
|
+
"temp",
|
|
2270
|
+
"cache",
|
|
2271
|
+
".cache",
|
|
2272
|
+
"__pycache__",
|
|
2273
|
+
".pytest_cache",
|
|
2274
|
+
".mypy_cache",
|
|
2275
|
+
".tox",
|
|
2276
|
+
"node_modules",
|
|
2277
|
+
"coverage",
|
|
2278
|
+
".coverage",
|
|
2279
|
+
"htmlcov"
|
|
2280
|
+
]);
|
|
2281
|
+
BUILD_ARTIFACT_GLOB_RE = /^\*\.(?:pyc|pyo|class|o|obj|d|egg-info)$/i;
|
|
2158
2282
|
REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
|
|
2159
2283
|
REFERENCE_LOOKBACK = 3;
|
|
2160
2284
|
EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
|
|
@@ -2492,8 +2616,8 @@ function loadRuntimeConfig() {
|
|
|
2492
2616
|
}
|
|
2493
2617
|
try {
|
|
2494
2618
|
const st = statSync3(p);
|
|
2495
|
-
const
|
|
2496
|
-
if (runtimeConfigCache && runtimeConfigCache.key ===
|
|
2619
|
+
const cacheKey2 = `${p}|${st.mtimeMs}|${st.size}`;
|
|
2620
|
+
if (runtimeConfigCache && runtimeConfigCache.key === cacheKey2) {
|
|
2497
2621
|
return runtimeConfigCache.value;
|
|
2498
2622
|
}
|
|
2499
2623
|
const data = JSON.parse(readFileSync4(p, "utf-8"));
|
|
@@ -2518,7 +2642,7 @@ function loadRuntimeConfig() {
|
|
|
2518
2642
|
agent_rules: merged.agent_rules || {},
|
|
2519
2643
|
scenario_rules: merged.scenario_rules || {}
|
|
2520
2644
|
};
|
|
2521
|
-
runtimeConfigCache = { key:
|
|
2645
|
+
runtimeConfigCache = { key: cacheKey2, value: result };
|
|
2522
2646
|
return result;
|
|
2523
2647
|
} catch {
|
|
2524
2648
|
return emptyRuntimeConfig();
|
|
@@ -3838,6 +3962,7 @@ __export(config_exports, {
|
|
|
3838
3962
|
getAgentMossSetting: () => getAgentMossSetting,
|
|
3839
3963
|
getCacheOptions: () => getCacheOptions,
|
|
3840
3964
|
getCustomRules: () => getCustomRules,
|
|
3965
|
+
getDeployRole: () => getDeployRole,
|
|
3841
3966
|
getLLMConfig: () => getLLMConfig,
|
|
3842
3967
|
getLLMFailMode: () => getLLMFailMode,
|
|
3843
3968
|
getProviderHeaders: () => getProviderHeaders,
|
|
@@ -4020,6 +4145,10 @@ function getLLMFailMode() {
|
|
|
4020
4145
|
const val = (process.env.AGENT_MOSS_LLM_FAIL_MODE || "fail_open").toLowerCase();
|
|
4021
4146
|
return val === "fail_closed" ? "fail_closed" : "fail_open";
|
|
4022
4147
|
}
|
|
4148
|
+
function getDeployRole() {
|
|
4149
|
+
const val = String(process.env.AGENT_MOSS_DEPLOY_ROLE || "standalone").trim().toLowerCase();
|
|
4150
|
+
return val === "host" || val === "sandbox" ? val : "standalone";
|
|
4151
|
+
}
|
|
4023
4152
|
function detectProvider(baseUrl, providerHint = "") {
|
|
4024
4153
|
if (providerHint) {
|
|
4025
4154
|
const hint = providerHint.toLowerCase();
|
|
@@ -4153,15 +4282,66 @@ var init_config = __esm({
|
|
|
4153
4282
|
}
|
|
4154
4283
|
});
|
|
4155
4284
|
|
|
4156
|
-
// src/
|
|
4157
|
-
import { readFileSync as readFileSync5,
|
|
4158
|
-
import {
|
|
4285
|
+
// src/infra/edition-scope.ts
|
|
4286
|
+
import { existsSync as existsSync6, readFileSync as readFileSync5, statSync as statSync4 } from "fs";
|
|
4287
|
+
import { dirname as dirname5, join as join6, resolve as resolve4 } from "path";
|
|
4159
4288
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
4289
|
+
function scopePath(moduleDir) {
|
|
4290
|
+
const root = getRulesRoot();
|
|
4291
|
+
if (root) return join6(root, "edition_scope.json");
|
|
4292
|
+
const prod = resolve4(moduleDir, "..", "edition_scope.json");
|
|
4293
|
+
if (existsSync6(prod)) return prod;
|
|
4294
|
+
const dev = resolve4(moduleDir, "../../..", "agent_moss", "edition_scope.json");
|
|
4295
|
+
if (existsSync6(dev)) return dev;
|
|
4296
|
+
return prod;
|
|
4297
|
+
}
|
|
4298
|
+
function loadScope(moduleDir) {
|
|
4299
|
+
const file = scopePath(moduleDir);
|
|
4300
|
+
try {
|
|
4301
|
+
const st = statSync4(file);
|
|
4302
|
+
const key = `${file}:${st.mtimeMs}:${st.size}`;
|
|
4303
|
+
if (key === cacheKey) return cacheData;
|
|
4304
|
+
const parsed = JSON.parse(readFileSync5(file, "utf-8"));
|
|
4305
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
4306
|
+
throw new Error("\u6839\u8282\u70B9\u4E0D\u662F\u5BF9\u8C61");
|
|
4307
|
+
}
|
|
4308
|
+
cacheKey = key;
|
|
4309
|
+
cacheData = parsed;
|
|
4310
|
+
return cacheData;
|
|
4311
|
+
} catch {
|
|
4312
|
+
cacheKey = "";
|
|
4313
|
+
cacheData = null;
|
|
4314
|
+
return null;
|
|
4315
|
+
}
|
|
4316
|
+
}
|
|
4317
|
+
function isAllowed(kind, id, moduleDir = MODULE_DIR) {
|
|
4318
|
+
const scope = loadScope(moduleDir);
|
|
4319
|
+
if (!scope) return true;
|
|
4320
|
+
const allowed = scope[kind];
|
|
4321
|
+
if (!Array.isArray(allowed)) return true;
|
|
4322
|
+
return allowed.includes(id);
|
|
4323
|
+
}
|
|
4324
|
+
var MODULE_DIR, cacheKey, cacheData;
|
|
4325
|
+
var init_edition_scope = __esm({
|
|
4326
|
+
"src/infra/edition-scope.ts"() {
|
|
4327
|
+
"use strict";
|
|
4328
|
+
init_esm_shims();
|
|
4329
|
+
init_paths();
|
|
4330
|
+
MODULE_DIR = dirname5(fileURLToPath6(import.meta.url));
|
|
4331
|
+
cacheKey = "";
|
|
4332
|
+
cacheData = null;
|
|
4333
|
+
}
|
|
4334
|
+
});
|
|
4335
|
+
|
|
4336
|
+
// src/agents/index.ts
|
|
4337
|
+
import { readFileSync as readFileSync6, existsSync as existsSync7 } from "fs";
|
|
4338
|
+
import { resolve as resolve5, dirname as dirname6, join as join7 } from "path";
|
|
4339
|
+
import { fileURLToPath as fileURLToPath7 } from "url";
|
|
4160
4340
|
function resolveAgentsDir() {
|
|
4161
4341
|
const root = getRulesRoot();
|
|
4162
|
-
if (root) return
|
|
4163
|
-
if (
|
|
4164
|
-
if (
|
|
4342
|
+
if (root) return join7(root, "agents");
|
|
4343
|
+
if (existsSync7(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
|
|
4344
|
+
if (existsSync7(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
|
|
4165
4345
|
return AGENTS_DIR_PROD;
|
|
4166
4346
|
}
|
|
4167
4347
|
function getAgentExtensions(agentId) {
|
|
@@ -4170,6 +4350,7 @@ function getAgentExtensions(agentId) {
|
|
|
4170
4350
|
console.warn(`[AgentMoss agents] \u975E\u6CD5 agent_id \u5DF2\u5FFD\u7565\uFF08\u542B\u8DEF\u5F84\u5B57\u7B26\u6216\u8D85\u957F\uFF09: ${agentId.slice(0, 120)}`);
|
|
4171
4351
|
return null;
|
|
4172
4352
|
}
|
|
4353
|
+
if (!isAllowed("agents", agentId)) return null;
|
|
4173
4354
|
if (cache.size >= CACHE_MAX) cache.clear();
|
|
4174
4355
|
const fp = getRuleSourceFingerprint();
|
|
4175
4356
|
const cached2 = cache.get(agentId);
|
|
@@ -4183,13 +4364,13 @@ function getAgentExtensions(agentId) {
|
|
|
4183
4364
|
}
|
|
4184
4365
|
if (ext === null) {
|
|
4185
4366
|
const agentsDir = resolveAgentsDir();
|
|
4186
|
-
const rulesFile =
|
|
4187
|
-
if (!
|
|
4367
|
+
const rulesFile = resolve5(agentsDir, agentId, "rules.json");
|
|
4368
|
+
if (!existsSync7(rulesFile)) {
|
|
4188
4369
|
cache.set(agentId, { fp, ext: null });
|
|
4189
4370
|
return null;
|
|
4190
4371
|
}
|
|
4191
4372
|
try {
|
|
4192
|
-
const raw =
|
|
4373
|
+
const raw = readFileSync6(rulesFile, "utf-8");
|
|
4193
4374
|
ext = JSON.parse(raw);
|
|
4194
4375
|
if (!ext.agent_id) {
|
|
4195
4376
|
console.warn(`[AgentMoss agents] rules.json \u7F3A\u5C11 agent_id \u5B57\u6BB5: ${rulesFile}`);
|
|
@@ -4230,25 +4411,26 @@ var init_agents = __esm({
|
|
|
4230
4411
|
"use strict";
|
|
4231
4412
|
init_esm_shims();
|
|
4232
4413
|
init_paths();
|
|
4414
|
+
init_edition_scope();
|
|
4233
4415
|
init_runtime_config();
|
|
4234
|
-
__filename4 =
|
|
4235
|
-
__dirname5 =
|
|
4236
|
-
AGENTS_DIR_PROD =
|
|
4237
|
-
AGENTS_DIR_DEV_FALLBACK =
|
|
4416
|
+
__filename4 = fileURLToPath7(import.meta.url);
|
|
4417
|
+
__dirname5 = dirname6(__filename4);
|
|
4418
|
+
AGENTS_DIR_PROD = resolve5(__dirname5, "agents");
|
|
4419
|
+
AGENTS_DIR_DEV_FALLBACK = resolve5(__dirname5, "../../../agent_moss/agents");
|
|
4238
4420
|
cache = /* @__PURE__ */ new Map();
|
|
4239
4421
|
CACHE_MAX = 512;
|
|
4240
4422
|
}
|
|
4241
4423
|
});
|
|
4242
4424
|
|
|
4243
4425
|
// src/scenarios/index.ts
|
|
4244
|
-
import { readFileSync as
|
|
4245
|
-
import { resolve as
|
|
4246
|
-
import { fileURLToPath as
|
|
4426
|
+
import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
|
|
4427
|
+
import { resolve as resolve6, dirname as dirname7, join as join8 } from "path";
|
|
4428
|
+
import { fileURLToPath as fileURLToPath8 } from "url";
|
|
4247
4429
|
function resolveScenariosDir() {
|
|
4248
4430
|
const root = getRulesRoot();
|
|
4249
|
-
if (root) return
|
|
4250
|
-
if (
|
|
4251
|
-
if (
|
|
4431
|
+
if (root) return join8(root, "scenarios");
|
|
4432
|
+
if (existsSync8(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
|
|
4433
|
+
if (existsSync8(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
|
|
4252
4434
|
return SCENARIOS_DIR_PROD;
|
|
4253
4435
|
}
|
|
4254
4436
|
function getScenarioExtensions(scenarioId) {
|
|
@@ -4257,6 +4439,7 @@ function getScenarioExtensions(scenarioId) {
|
|
|
4257
4439
|
console.warn(`[AgentMoss scenarios] \u975E\u6CD5 scenario_id \u5DF2\u5FFD\u7565\uFF08\u542B\u8DEF\u5F84\u5B57\u7B26\u6216\u8D85\u957F\uFF09: ${scenarioId.slice(0, 120)}`);
|
|
4258
4440
|
return null;
|
|
4259
4441
|
}
|
|
4442
|
+
if (!isAllowed("scenarios", scenarioId)) return null;
|
|
4260
4443
|
if (cache2.size >= CACHE_MAX2) cache2.clear();
|
|
4261
4444
|
const fp = getRuleSourceFingerprint();
|
|
4262
4445
|
const cached2 = cache2.get(scenarioId);
|
|
@@ -4276,19 +4459,19 @@ function getScenarioExtensions(scenarioId) {
|
|
|
4276
4459
|
}
|
|
4277
4460
|
}
|
|
4278
4461
|
if (ext === null) {
|
|
4279
|
-
const builtinFile =
|
|
4462
|
+
const builtinFile = resolve6(resolveScenariosDir(), scenarioId, "rules.json");
|
|
4280
4463
|
const rulesFile = overrideHit ?? builtinFile;
|
|
4281
4464
|
if (overrideHit) {
|
|
4282
4465
|
console.warn(
|
|
4283
4466
|
`[AgentMoss] \u26A0\uFE0F \u573A\u666F ${scenarioId} \u89C4\u5219\u88AB\u8986\u76D6\u76EE\u5F55\u8986\u76D6: ${overrideHit}\uFF08\u5185\u7F6E\u9ED8\u8BA4 ${builtinFile} \u88AB\u5FFD\u7565\uFF09\u3002\u8BE5\u6587\u4EF6\u7531\u90E8\u7F72\u4FA7\u81EA\u884C\u7EF4\u62A4\uFF0C\u5185\u7F6E\u573A\u666F\u89C4\u5219\u66F4\u65B0\u4E0D\u4F1A\u53CD\u6620\u5230\u5B83\u4E0A\u9762\u3002`
|
|
4284
4467
|
);
|
|
4285
4468
|
}
|
|
4286
|
-
if (!
|
|
4469
|
+
if (!existsSync8(rulesFile)) {
|
|
4287
4470
|
cache2.set(scenarioId, { fp, ext: null });
|
|
4288
4471
|
return null;
|
|
4289
4472
|
}
|
|
4290
4473
|
try {
|
|
4291
|
-
const raw =
|
|
4474
|
+
const raw = readFileSync7(rulesFile, "utf-8");
|
|
4292
4475
|
const data = JSON.parse(raw);
|
|
4293
4476
|
const id = data.scenario_id || data.agent_id || "";
|
|
4294
4477
|
if (!id) {
|
|
@@ -4334,13 +4517,14 @@ var init_scenarios = __esm({
|
|
|
4334
4517
|
"use strict";
|
|
4335
4518
|
init_esm_shims();
|
|
4336
4519
|
init_paths();
|
|
4520
|
+
init_edition_scope();
|
|
4337
4521
|
init_agents();
|
|
4338
4522
|
init_runtime_config();
|
|
4339
4523
|
init_rules_loader();
|
|
4340
|
-
__filename5 =
|
|
4341
|
-
__dirname6 =
|
|
4342
|
-
SCENARIOS_DIR_PROD =
|
|
4343
|
-
SCENARIOS_DIR_DEV_FALLBACK =
|
|
4524
|
+
__filename5 = fileURLToPath8(import.meta.url);
|
|
4525
|
+
__dirname6 = dirname7(__filename5);
|
|
4526
|
+
SCENARIOS_DIR_PROD = resolve6(__dirname6, "scenarios");
|
|
4527
|
+
SCENARIOS_DIR_DEV_FALLBACK = resolve6(__dirname6, "../../../agent_moss/scenarios");
|
|
4344
4528
|
cache2 = /* @__PURE__ */ new Map();
|
|
4345
4529
|
CACHE_MAX2 = 512;
|
|
4346
4530
|
}
|
|
@@ -4407,6 +4591,21 @@ function detectLanguage(path8, content) {
|
|
|
4407
4591
|
}
|
|
4408
4592
|
return "other";
|
|
4409
4593
|
}
|
|
4594
|
+
function isInstructionTarget(path8) {
|
|
4595
|
+
const p = (path8 || "").replace(/\\/g, "/").toLowerCase();
|
|
4596
|
+
if (!p) return false;
|
|
4597
|
+
const base = p.split("/").pop() || "";
|
|
4598
|
+
if (["agents.md", "claude.md", "system.md", "prompt.md", "instructions.md", ".cursorrules"].includes(base)) {
|
|
4599
|
+
return true;
|
|
4600
|
+
}
|
|
4601
|
+
if (/(?:^|[-_.])(?:prompt|instruction|system)(?:[-_.]|$)/.test(base)) return true;
|
|
4602
|
+
return INSTRUCTION_TARGET_RE.test(p);
|
|
4603
|
+
}
|
|
4604
|
+
function isDataDocument(actionType, actionDetailRaw) {
|
|
4605
|
+
const payload = extractWritePayload(actionType, actionDetailRaw);
|
|
4606
|
+
if (payload === null) return false;
|
|
4607
|
+
return detectLanguage(payload.path, payload.content) === "data" && !isInstructionTarget(payload.path);
|
|
4608
|
+
}
|
|
4410
4609
|
function stripShellComments(text) {
|
|
4411
4610
|
const out = [];
|
|
4412
4611
|
let heredocEnd = null;
|
|
@@ -4569,7 +4768,7 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
|
|
|
4569
4768
|
}
|
|
4570
4769
|
return snippets;
|
|
4571
4770
|
}
|
|
4572
|
-
var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE, HEREDOC_START_RE;
|
|
4771
|
+
var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE, INSTRUCTION_TARGET_RE, HEREDOC_START_RE;
|
|
4573
4772
|
var init_written_content_analyzer = __esm({
|
|
4574
4773
|
"src/engine/written-content-analyzer.ts"() {
|
|
4575
4774
|
"use strict";
|
|
@@ -4592,7 +4791,12 @@ var init_written_content_analyzer = __esm({
|
|
|
4592
4791
|
"file_edit",
|
|
4593
4792
|
"editfile",
|
|
4594
4793
|
"searchreplace",
|
|
4595
|
-
"search_replace"
|
|
4794
|
+
"search_replace",
|
|
4795
|
+
// 通用 workspace 工具名(ClawPartner/QwenPaw 等宿主常用)
|
|
4796
|
+
"workspace_write_file",
|
|
4797
|
+
"workspace_edit_file",
|
|
4798
|
+
"workspace_writefile",
|
|
4799
|
+
"workspace_editfile"
|
|
4596
4800
|
]);
|
|
4597
4801
|
WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
|
|
4598
4802
|
APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
|
|
@@ -4601,6 +4805,7 @@ var init_written_content_analyzer = __esm({
|
|
|
4601
4805
|
INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
|
|
4602
4806
|
QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
|
|
4603
4807
|
PY_DANGEROUS_CALL_RE = /(?:os\.(?:system|popen|remove|unlink|rmdir|chmod|chown|kill|spawn\w*)|subprocess\.\w+|pty\.\w+|ctypes\.\w+|eval|exec|compile|__import__|shutil\.(?:rmtree|move|copy\w*))\s*\(/g;
|
|
4808
|
+
INSTRUCTION_TARGET_RE = /(?:^|[/\\])(?:prompts?|instructions?|skills?|memories|memory|config|policies|policy|\.claude|\.cursor)(?:[/\\]|$)|(?:^|[/\\])(?:AGENTS?|CLAUDE|SYSTEM|PROMPT|INSTRUCTIONS?)(?:\.[^/\\]+)?$|(?:^|[/\\])\.cursorrules$/i;
|
|
4604
4809
|
HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
|
|
4605
4810
|
}
|
|
4606
4811
|
});
|
|
@@ -4844,6 +5049,23 @@ function runHeuristicCheck(input) {
|
|
|
4844
5049
|
deobfuscated
|
|
4845
5050
|
);
|
|
4846
5051
|
}
|
|
5052
|
+
const extraScanDetail = stripSearchPatternLiterals(scanDetail);
|
|
5053
|
+
const extraScanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => {
|
|
5054
|
+
const stripped = stripSearchPatternLiterals(sn);
|
|
5055
|
+
return [`${input.aNext.actionType}: ${stripped}`, stripped];
|
|
5056
|
+
}) : String(input.osType || "").toLowerCase() === "windows" ? [
|
|
5057
|
+
`${input.aNext.actionType}: ${extraScanDetail}`,
|
|
5058
|
+
extraScanDetail,
|
|
5059
|
+
`${input.aNext.actionType}: ${extraScanDetail.replace(/\//g, "\\")}`,
|
|
5060
|
+
extraScanDetail.replace(/\//g, "\\")
|
|
5061
|
+
] : [`${input.aNext.actionType}: ${extraScanDetail}`, extraScanDetail];
|
|
5062
|
+
const extraDeobfuscated = normalizeShellObfuscation(extraScanDetail);
|
|
5063
|
+
if (extraDeobfuscated !== extraScanDetail) {
|
|
5064
|
+
extraScanCommands.push(
|
|
5065
|
+
`${input.aNext.actionType}: ${extraDeobfuscated}`,
|
|
5066
|
+
extraDeobfuscated
|
|
5067
|
+
);
|
|
5068
|
+
}
|
|
4847
5069
|
let topRiskType = "";
|
|
4848
5070
|
const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
|
|
4849
5071
|
const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
|
|
@@ -4868,7 +5090,7 @@ function runHeuristicCheck(input) {
|
|
|
4868
5090
|
for (const rule of agentExt.extra_command_patterns) {
|
|
4869
5091
|
try {
|
|
4870
5092
|
const re = new RegExp(rule.pattern, "i");
|
|
4871
|
-
if (
|
|
5093
|
+
if (extraScanCommands.some((c) => re.test(c))) {
|
|
4872
5094
|
matched.push(`agent \u4E13\u5C5E\u89C4\u5219: ${rule.reason}`);
|
|
4873
5095
|
if (severityRank(rule.risk_level) > severityRank(highestSeverity)) {
|
|
4874
5096
|
highestSeverity = rule.risk_level;
|
|
@@ -4879,7 +5101,7 @@ function runHeuristicCheck(input) {
|
|
|
4879
5101
|
}
|
|
4880
5102
|
}
|
|
4881
5103
|
}
|
|
4882
|
-
const injectionText = isSearchActionType(input.aNext.actionType) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
|
|
5104
|
+
const injectionText = isSearchActionType(input.aNext.actionType) || handledWrite && isDataDocument(input.aNext.actionType, input.aNext.actionDetail) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
|
|
4883
5105
|
let pythonWalkOnerrorOnly = false;
|
|
4884
5106
|
if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
|
|
4885
5107
|
pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
|
|
@@ -5130,16 +5352,83 @@ function splitCommandSegments2(actionDetail) {
|
|
|
5130
5352
|
if (start < actionDetail.length) segments.push(actionDetail.slice(start));
|
|
5131
5353
|
return segments;
|
|
5132
5354
|
}
|
|
5355
|
+
function shellTokens(seg) {
|
|
5356
|
+
const tokens = [];
|
|
5357
|
+
let cur = "";
|
|
5358
|
+
let quote = "";
|
|
5359
|
+
for (let i = 0; i < seg.length; i++) {
|
|
5360
|
+
const ch = seg[i];
|
|
5361
|
+
if (quote) {
|
|
5362
|
+
if (ch === quote) quote = "";
|
|
5363
|
+
else cur += ch;
|
|
5364
|
+
continue;
|
|
5365
|
+
}
|
|
5366
|
+
if (ch === '"' || ch === "'") {
|
|
5367
|
+
quote = ch;
|
|
5368
|
+
continue;
|
|
5369
|
+
}
|
|
5370
|
+
if (/\s/.test(ch)) {
|
|
5371
|
+
if (cur) {
|
|
5372
|
+
tokens.push(cur);
|
|
5373
|
+
cur = "";
|
|
5374
|
+
}
|
|
5375
|
+
continue;
|
|
5376
|
+
}
|
|
5377
|
+
cur += ch;
|
|
5378
|
+
}
|
|
5379
|
+
if (quote) return null;
|
|
5380
|
+
if (cur) tokens.push(cur);
|
|
5381
|
+
return tokens;
|
|
5382
|
+
}
|
|
5383
|
+
function stripSearchPatternArgument(seg) {
|
|
5384
|
+
if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) return seg;
|
|
5385
|
+
const tokens = shellTokens(seg);
|
|
5386
|
+
if (!tokens || tokens.length === 0) return seg;
|
|
5387
|
+
let idx = 0;
|
|
5388
|
+
while (idx < tokens.length && COMMAND_PREFIX_WORDS.has(tokens[idx])) idx++;
|
|
5389
|
+
if (idx >= tokens.length || !TEXT_SEARCH_COMMANDS.has(tokens[idx])) return seg;
|
|
5390
|
+
let patternIdx = null;
|
|
5391
|
+
let i = idx + 1;
|
|
5392
|
+
while (i < tokens.length) {
|
|
5393
|
+
const token = tokens[i];
|
|
5394
|
+
if (token === "--") {
|
|
5395
|
+
patternIdx = i + 1 < tokens.length ? i + 1 : null;
|
|
5396
|
+
break;
|
|
5397
|
+
}
|
|
5398
|
+
if (token === "-e" || token === "--regexp") {
|
|
5399
|
+
patternIdx = i + 1 < tokens.length ? i + 1 : null;
|
|
5400
|
+
break;
|
|
5401
|
+
}
|
|
5402
|
+
if (token.startsWith("--regexp=")) {
|
|
5403
|
+
patternIdx = i;
|
|
5404
|
+
break;
|
|
5405
|
+
}
|
|
5406
|
+
if (token === "-f" || token === "--file" || token.startsWith("--file=")) break;
|
|
5407
|
+
if (token.startsWith("-") && token !== "-") {
|
|
5408
|
+
i += SEARCH_OPTION_WITH_ARG.has(token) ? 2 : 1;
|
|
5409
|
+
continue;
|
|
5410
|
+
}
|
|
5411
|
+
patternIdx = i;
|
|
5412
|
+
break;
|
|
5413
|
+
}
|
|
5414
|
+
if (patternIdx === null || patternIdx >= tokens.length) return seg;
|
|
5415
|
+
tokens.splice(patternIdx, 1);
|
|
5416
|
+
return tokens.map((t) => /\s/.test(t) ? `'${t.replaceAll("'", "'\\''")}'` : t).join(" ");
|
|
5417
|
+
}
|
|
5133
5418
|
function stripSearchPatternLiterals(actionDetail) {
|
|
5134
5419
|
const parts = [];
|
|
5135
5420
|
for (const seg of splitCommandSegments2(actionDetail)) {
|
|
5421
|
+
if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) {
|
|
5422
|
+
parts.push(seg);
|
|
5423
|
+
continue;
|
|
5424
|
+
}
|
|
5136
5425
|
const low = seg.trim().toLowerCase();
|
|
5137
5426
|
const words = low.length ? low.split(/\s+/) : [];
|
|
5138
5427
|
let idx = 0;
|
|
5139
5428
|
while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
|
|
5140
5429
|
const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
|
|
5141
5430
|
if (isSearch && !low.includes("--pre")) {
|
|
5142
|
-
parts.push(seg
|
|
5431
|
+
parts.push(stripSearchPatternArgument(seg));
|
|
5143
5432
|
} else {
|
|
5144
5433
|
parts.push(seg);
|
|
5145
5434
|
}
|
|
@@ -5464,7 +5753,7 @@ function checkDangerousPatterns(actionType, actionDetail) {
|
|
|
5464
5753
|
) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
|
|
5465
5754
|
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;
|
|
5466
5755
|
const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
|
|
5467
|
-
if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
|
|
5756
|
+
if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
|
|
5468
5757
|
return {
|
|
5469
5758
|
allowed: false,
|
|
5470
5759
|
reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
|
|
@@ -5606,7 +5895,7 @@ function checkLateralMovement(actionDetail) {
|
|
|
5606
5895
|
}
|
|
5607
5896
|
return null;
|
|
5608
5897
|
}
|
|
5609
|
-
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, 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;
|
|
5898
|
+
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, 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, SEARCH_OPTION_WITH_ARG, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
5610
5899
|
var init_heuristic = __esm({
|
|
5611
5900
|
"src/engine/heuristic.ts"() {
|
|
5612
5901
|
"use strict";
|
|
@@ -5655,6 +5944,28 @@ var init_heuristic = __esm({
|
|
|
5655
5944
|
COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
|
|
5656
5945
|
TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
|
|
5657
5946
|
COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
|
|
5947
|
+
SEARCH_OPTION_WITH_ARG = /* @__PURE__ */ new Set([
|
|
5948
|
+
"-m",
|
|
5949
|
+
"--max-count",
|
|
5950
|
+
"-A",
|
|
5951
|
+
"--after-context",
|
|
5952
|
+
"-B",
|
|
5953
|
+
"--before-context",
|
|
5954
|
+
"-C",
|
|
5955
|
+
"--context",
|
|
5956
|
+
"-d",
|
|
5957
|
+
"--directories",
|
|
5958
|
+
"-D",
|
|
5959
|
+
"--devices",
|
|
5960
|
+
"--include",
|
|
5961
|
+
"--exclude",
|
|
5962
|
+
"--exclude-dir",
|
|
5963
|
+
"--glob",
|
|
5964
|
+
"--iglob",
|
|
5965
|
+
"--type",
|
|
5966
|
+
"--type-add",
|
|
5967
|
+
"--type-not"
|
|
5968
|
+
]);
|
|
5658
5969
|
SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
|
|
5659
5970
|
SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
|
|
5660
5971
|
SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
|
|
@@ -5674,17 +5985,17 @@ __export(token_stats_exports, {
|
|
|
5674
5985
|
resetTokenStats: () => resetTokenStats,
|
|
5675
5986
|
resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
|
|
5676
5987
|
});
|
|
5677
|
-
import { readFileSync as
|
|
5988
|
+
import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync7 } from "fs";
|
|
5678
5989
|
function getStatsPath() {
|
|
5679
5990
|
const envPath = process.env[ENV_STATS_PATH];
|
|
5680
5991
|
if (envPath) return envPath;
|
|
5681
5992
|
return getTokenStatsPath();
|
|
5682
5993
|
}
|
|
5683
5994
|
function loadAllRecords(statsPath) {
|
|
5684
|
-
if (!
|
|
5995
|
+
if (!existsSync13(statsPath)) return [];
|
|
5685
5996
|
let sig = "";
|
|
5686
5997
|
try {
|
|
5687
|
-
const st =
|
|
5998
|
+
const st = statSync7(statsPath);
|
|
5688
5999
|
sig = `${st.mtimeMs}:${st.size}`;
|
|
5689
6000
|
} catch {
|
|
5690
6001
|
return [];
|
|
@@ -5693,7 +6004,7 @@ function loadAllRecords(statsPath) {
|
|
|
5693
6004
|
return _recordsCache.records.slice();
|
|
5694
6005
|
}
|
|
5695
6006
|
try {
|
|
5696
|
-
const data = JSON.parse(
|
|
6007
|
+
const data = JSON.parse(readFileSync13(statsPath, "utf-8"));
|
|
5697
6008
|
let records;
|
|
5698
6009
|
if (Array.isArray(data)) records = data;
|
|
5699
6010
|
else if (data && Array.isArray(data.records)) records = data.records;
|
|
@@ -5707,7 +6018,7 @@ function loadAllRecords(statsPath) {
|
|
|
5707
6018
|
function saveRecords(statsPath, records) {
|
|
5708
6019
|
try {
|
|
5709
6020
|
const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
|
|
5710
|
-
if (dir && !
|
|
6021
|
+
if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
|
|
5711
6022
|
const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
|
|
5712
6023
|
try {
|
|
5713
6024
|
writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
|
|
@@ -5719,7 +6030,7 @@ function saveRecords(statsPath, records) {
|
|
|
5719
6030
|
}
|
|
5720
6031
|
}
|
|
5721
6032
|
try {
|
|
5722
|
-
const st =
|
|
6033
|
+
const st = statSync7(statsPath);
|
|
5723
6034
|
_recordsCache = {
|
|
5724
6035
|
path: statsPath,
|
|
5725
6036
|
sig: `${st.mtimeMs}:${st.size}`,
|
|
@@ -5856,7 +6167,7 @@ function getTokenTrend(days = 0, startDate, endDate) {
|
|
|
5856
6167
|
}
|
|
5857
6168
|
function resetTokenStats() {
|
|
5858
6169
|
const statsPath = getStatsPath();
|
|
5859
|
-
if (
|
|
6170
|
+
if (existsSync13(statsPath)) {
|
|
5860
6171
|
try {
|
|
5861
6172
|
unlinkSync2(statsPath);
|
|
5862
6173
|
} catch {
|
|
@@ -5891,9 +6202,9 @@ import { createHash } from "crypto";
|
|
|
5891
6202
|
// src/infra/security-policy.ts
|
|
5892
6203
|
init_esm_shims();
|
|
5893
6204
|
init_paths();
|
|
5894
|
-
import { chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as
|
|
6205
|
+
import { chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as existsSync9, lstatSync, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync8, readSync as readSync2, realpathSync, writeSync } from "fs";
|
|
5895
6206
|
import { homedir as homedir3, tmpdir } from "os";
|
|
5896
|
-
import { basename as basename2, isAbsolute as isAbsolute2, join as
|
|
6207
|
+
import { basename as basename2, isAbsolute as isAbsolute2, join as join9, relative, resolve as resolve7, dirname as dirname8 } from "path";
|
|
5897
6208
|
var TRUTHY2 = ["1", "true", "yes", "on"];
|
|
5898
6209
|
function env(name, dflt = "") {
|
|
5899
6210
|
return (process.env[name] ?? dflt).trim();
|
|
@@ -5921,7 +6232,7 @@ function logRoots() {
|
|
|
5921
6232
|
return [.../* @__PURE__ */ new Set([homeDir(), "/tmp", tmpdir()])];
|
|
5922
6233
|
}
|
|
5923
6234
|
function realpathLoose(p) {
|
|
5924
|
-
const abs =
|
|
6235
|
+
const abs = resolve7(p.replace(/^~(?=$|\/)/, homeDir()));
|
|
5925
6236
|
try {
|
|
5926
6237
|
return realpathSync(abs);
|
|
5927
6238
|
} catch {
|
|
@@ -5929,12 +6240,12 @@ function realpathLoose(p) {
|
|
|
5929
6240
|
const parts = [];
|
|
5930
6241
|
let cur = abs;
|
|
5931
6242
|
for (; ; ) {
|
|
5932
|
-
const parent =
|
|
6243
|
+
const parent = dirname8(cur);
|
|
5933
6244
|
if (parent === cur) return null;
|
|
5934
6245
|
parts.unshift(basename2(cur));
|
|
5935
6246
|
cur = parent;
|
|
5936
6247
|
try {
|
|
5937
|
-
return
|
|
6248
|
+
return join9(realpathSync(cur), ...parts);
|
|
5938
6249
|
} catch {
|
|
5939
6250
|
}
|
|
5940
6251
|
}
|
|
@@ -5996,11 +6307,11 @@ init_skill_loader();
|
|
|
5996
6307
|
// src/engine/template-loader.ts
|
|
5997
6308
|
init_esm_shims();
|
|
5998
6309
|
init_asset_dir();
|
|
5999
|
-
import { readFileSync as
|
|
6000
|
-
import { resolve as
|
|
6001
|
-
import { fileURLToPath as
|
|
6002
|
-
var __filename6 =
|
|
6003
|
-
var __dirname7 =
|
|
6310
|
+
import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
|
|
6311
|
+
import { resolve as resolve8, dirname as dirname9 } from "path";
|
|
6312
|
+
import { fileURLToPath as fileURLToPath9 } from "url";
|
|
6313
|
+
var __filename6 = fileURLToPath9(import.meta.url);
|
|
6314
|
+
var __dirname7 = dirname9(__filename6);
|
|
6004
6315
|
var TEMPLATE_FILES = ["prompt1_template.txt", "prompt2_template.txt", "security_judge_template.txt"];
|
|
6005
6316
|
var cachedTemplates = null;
|
|
6006
6317
|
function loadTemplates() {
|
|
@@ -6013,10 +6324,10 @@ function loadTemplates() {
|
|
|
6013
6324
|
return cachedTemplates;
|
|
6014
6325
|
}
|
|
6015
6326
|
for (const file of TEMPLATE_FILES) {
|
|
6016
|
-
const filePath =
|
|
6017
|
-
if (
|
|
6327
|
+
const filePath = resolve8(dir, file);
|
|
6328
|
+
if (existsSync10(filePath)) {
|
|
6018
6329
|
const key = file.replace(".txt", "").replace("_template", "");
|
|
6019
|
-
cachedTemplates[key] =
|
|
6330
|
+
cachedTemplates[key] = readFileSync9(filePath, "utf-8");
|
|
6020
6331
|
}
|
|
6021
6332
|
}
|
|
6022
6333
|
console.log(`[AgentMoss] Loaded ${Object.keys(cachedTemplates).length} templates from ${dir}`);
|
|
@@ -6026,8 +6337,8 @@ function loadTemplates() {
|
|
|
6026
6337
|
// src/engine/script-analyzer.ts
|
|
6027
6338
|
init_esm_shims();
|
|
6028
6339
|
init_rules_loader();
|
|
6029
|
-
import { readFileSync as
|
|
6030
|
-
import { resolve as
|
|
6340
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
6341
|
+
import { resolve as resolve9, join as join10 } from "path";
|
|
6031
6342
|
var SCRIPT_RULES = loadScriptRules();
|
|
6032
6343
|
if (!SCRIPT_RULES || Object.keys(SCRIPT_RULES).length === 0) {
|
|
6033
6344
|
console.error(
|
|
@@ -6097,8 +6408,8 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
|
|
|
6097
6408
|
}
|
|
6098
6409
|
function readScriptContent(scriptPath, maxLines = 500) {
|
|
6099
6410
|
try {
|
|
6100
|
-
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ?
|
|
6101
|
-
const raw =
|
|
6411
|
+
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join10(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve9(scriptPath);
|
|
6412
|
+
const raw = readFileSync10(expandedPath, "utf-8");
|
|
6102
6413
|
const lines = raw.split("\n").slice(0, maxLines);
|
|
6103
6414
|
return { content: lines.join("\n"), lineCount: lines.length, error: "" };
|
|
6104
6415
|
} catch (e) {
|
|
@@ -6154,8 +6465,8 @@ init_heuristic();
|
|
|
6154
6465
|
init_config();
|
|
6155
6466
|
init_logic_rules();
|
|
6156
6467
|
init_inline_analyzer();
|
|
6157
|
-
import { statSync as
|
|
6158
|
-
import { resolve as
|
|
6468
|
+
import { statSync as statSync6, existsSync as existsSync12 } from "fs";
|
|
6469
|
+
import { resolve as resolve11, join as join12, isAbsolute as isAbsolute4 } from "path";
|
|
6159
6470
|
import { homedir as homedir5 } from "os";
|
|
6160
6471
|
|
|
6161
6472
|
// src/engine/script-engine/tracker.ts
|
|
@@ -7361,7 +7672,7 @@ function evalIfCondition(cond, args) {
|
|
|
7361
7672
|
const op = m[2];
|
|
7362
7673
|
let left = m[1].trim();
|
|
7363
7674
|
let right = m[3].trim();
|
|
7364
|
-
const
|
|
7675
|
+
const resolve12 = (tok) => {
|
|
7365
7676
|
const rm = tok.match(/^\$(\d+)$/);
|
|
7366
7677
|
if (rm) {
|
|
7367
7678
|
const idx = parseInt(rm[1], 10);
|
|
@@ -7369,8 +7680,8 @@ function evalIfCondition(cond, args) {
|
|
|
7369
7680
|
}
|
|
7370
7681
|
return tok.startsWith("$") ? null : tok;
|
|
7371
7682
|
};
|
|
7372
|
-
const lv =
|
|
7373
|
-
const rv =
|
|
7683
|
+
const lv = resolve12(left);
|
|
7684
|
+
const rv = resolve12(right);
|
|
7374
7685
|
if (lv === null || rv === null) return null;
|
|
7375
7686
|
if (op === "=~") {
|
|
7376
7687
|
let re = rv;
|
|
@@ -7809,8 +8120,8 @@ function extractInlineScriptPath(actionDetail) {
|
|
|
7809
8120
|
if (looksLikeScriptPath(tok)) {
|
|
7810
8121
|
try {
|
|
7811
8122
|
const resolved = resolvePath2(tok.replace(/^['"]|['"]$/g, ""));
|
|
7812
|
-
if (
|
|
7813
|
-
const stat =
|
|
8123
|
+
if (existsSync12(resolved)) {
|
|
8124
|
+
const stat = statSync6(resolved);
|
|
7814
8125
|
if (stat.isFile()) return resolved;
|
|
7815
8126
|
}
|
|
7816
8127
|
} catch {
|
|
@@ -7823,8 +8134,8 @@ function extractInlineScriptPath(actionDetail) {
|
|
|
7823
8134
|
const p = m[1];
|
|
7824
8135
|
try {
|
|
7825
8136
|
const resolved = resolvePath2(p);
|
|
7826
|
-
if (
|
|
7827
|
-
const stat =
|
|
8137
|
+
if (existsSync12(resolved)) {
|
|
8138
|
+
const stat = statSync6(resolved);
|
|
7828
8139
|
if (stat.isFile()) return resolved;
|
|
7829
8140
|
}
|
|
7830
8141
|
} catch {
|
|
@@ -7839,8 +8150,8 @@ function extractInlineScriptPath(actionDetail) {
|
|
|
7839
8150
|
let resolved;
|
|
7840
8151
|
try {
|
|
7841
8152
|
resolved = resolvePath2(p);
|
|
7842
|
-
if (
|
|
7843
|
-
const stat =
|
|
8153
|
+
if (existsSync12(resolved)) {
|
|
8154
|
+
const stat = statSync6(resolved);
|
|
7844
8155
|
if (stat.isFile()) return resolved;
|
|
7845
8156
|
}
|
|
7846
8157
|
} catch {
|
|
@@ -7880,9 +8191,9 @@ function shlexSplit(s) {
|
|
|
7880
8191
|
function resolvePath2(p) {
|
|
7881
8192
|
let expanded = p;
|
|
7882
8193
|
if (expanded.startsWith("~/") || expanded === "~") {
|
|
7883
|
-
expanded =
|
|
8194
|
+
expanded = join12(homedir5(), expanded.slice(1));
|
|
7884
8195
|
}
|
|
7885
|
-
return
|
|
8196
|
+
return resolve11(expanded);
|
|
7886
8197
|
}
|
|
7887
8198
|
function scanExtensionPatterns(ext, content) {
|
|
7888
8199
|
const pats = ext?.extra_command_patterns;
|
|
@@ -7969,7 +8280,7 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
|
7969
8280
|
isInline = true;
|
|
7970
8281
|
}
|
|
7971
8282
|
if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
|
|
7972
|
-
resolvedPath =
|
|
8283
|
+
resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
|
|
7973
8284
|
}
|
|
7974
8285
|
const l1Adapter = (content) => {
|
|
7975
8286
|
const extHit = scanExtensionPatterns(ext, content);
|
|
@@ -8472,6 +8783,15 @@ var LLM_SHORT_CIRCUIT_TOTAL = new Counter(
|
|
|
8472
8783
|
);
|
|
8473
8784
|
|
|
8474
8785
|
// src/engine/llm-analyzer.ts
|
|
8786
|
+
var LLMPromptBudgetExceeded = class extends Error {
|
|
8787
|
+
code;
|
|
8788
|
+
constructor(code) {
|
|
8789
|
+
super(code);
|
|
8790
|
+
this.name = "LLMPromptBudgetExceeded";
|
|
8791
|
+
this.code = code;
|
|
8792
|
+
}
|
|
8793
|
+
};
|
|
8794
|
+
var HISTORY_AUTHORIZATION = "\u88AB\u7701\u7565\u6216\u88AB\u622A\u65AD\u7684\u5386\u53F2\u4E0D\u80FD\u4F5C\u4E3A\u6388\u6743\u4F9D\u636E\u3002\n\u201C\u7EE7\u7EED\u201D\u53EA\u6307\u4EE3\u53EF\u89C1\u7684\u524D\u6587\uFF1B\u5982\u679C\u53EF\u89C1\u524D\u6587\u4E0D\u8DB3\u4EE5\u786E\u8BA4\u6307\u4EE3\u76EE\u6807\u6216\u6388\u6743\u8303\u56F4\uFF0C\u5E94\u5728 reason \u4E2D\u8BF4\u660E\u4F9D\u636E\u4E0D\u8DB3\uFF0C\u5E76\u6309\u6700\u5C0F\u6743\u9650\u539F\u5219\u5224\u65AD\u9700\u8981\u8BE5\u6388\u6743\u7684\u52A8\u4F5C\u3002\n\u5F53\u524D\u7528\u6237\u8BF7\u6C42\u4E2D\u660E\u786E\u5199\u51FA\u7684\u6388\u6743\u4ECD\u7136\u6709\u6548\uFF0C\u6309\u5176\u53EF\u89C1\u7684\u76EE\u6807\u548C\u9650\u5236\u5224\u65AD\u3002";
|
|
8475
8795
|
var LLMCircuitOpenError = class extends Error {
|
|
8476
8796
|
constructor(message) {
|
|
8477
8797
|
super(message);
|
|
@@ -8556,8 +8876,8 @@ async function runLLMAnalysis(input, previous) {
|
|
|
8556
8876
|
}
|
|
8557
8877
|
const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
|
|
8558
8878
|
const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
|
|
8559
|
-
const
|
|
8560
|
-
const cached2 = llmCache.get(
|
|
8879
|
+
const cacheKey2 = `${input.aNext.actionType}:${createHash("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
|
|
8880
|
+
const cached2 = llmCache.get(cacheKey2);
|
|
8561
8881
|
if (cached2) {
|
|
8562
8882
|
console.log("[AgentMoss] LLM cache hit");
|
|
8563
8883
|
return cached2;
|
|
@@ -8572,6 +8892,9 @@ async function runLLMAnalysis(input, previous) {
|
|
|
8572
8892
|
scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
|
|
8573
8893
|
}
|
|
8574
8894
|
const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
|
|
8895
|
+
const budgetMode = getAgentMossSetting("AGENT_MOSS_LLM_BUDGET_MODE", "hard").trim().toLowerCase() === "soft" ? "soft" : "hard";
|
|
8896
|
+
const budgetActive = maxPromptTokens > 0;
|
|
8897
|
+
const tokenLimit = budgetActive && budgetMode === "hard" ? Math.floor(maxPromptTokens * 100 / 115) : maxPromptTokens;
|
|
8575
8898
|
let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
|
|
8576
8899
|
let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
|
|
8577
8900
|
let prompt = "";
|
|
@@ -8588,13 +8911,14 @@ async function runLLMAnalysis(input, previous) {
|
|
|
8588
8911
|
historyMaxItems,
|
|
8589
8912
|
historyMaxChars
|
|
8590
8913
|
);
|
|
8591
|
-
if (
|
|
8914
|
+
if (!budgetActive || estimateTokens(prompt) <= tokenLimit) break;
|
|
8592
8915
|
historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
|
|
8593
8916
|
historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
|
|
8594
8917
|
}
|
|
8595
|
-
|
|
8918
|
+
let budgetCode = "";
|
|
8919
|
+
if (budgetActive && estimateTokens(prompt) > tokenLimit) {
|
|
8596
8920
|
const estimated = estimateTokens(prompt);
|
|
8597
|
-
const ratio = estimated /
|
|
8921
|
+
const ratio = tokenLimit > 0 ? estimated / tokenLimit : Number.POSITIVE_INFINITY;
|
|
8598
8922
|
const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
|
|
8599
8923
|
const truncated = truncateDetail(input.aNext.actionDetail, allowed);
|
|
8600
8924
|
prompt = buildPrompt(
|
|
@@ -8610,8 +8934,14 @@ async function runLLMAnalysis(input, previous) {
|
|
|
8610
8934
|
historyMaxChars
|
|
8611
8935
|
);
|
|
8612
8936
|
console.warn(
|
|
8613
|
-
`[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${
|
|
8937
|
+
`[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${tokenLimit}\uFF09\uFF0C\u5F53\u524D\u52A8\u4F5C\u8BE6\u60C5\u622A\u65AD\u81F3 ${truncated.length} \u5B57\u7B26`
|
|
8614
8938
|
);
|
|
8939
|
+
if (estimateTokens(prompt) > tokenLimit) {
|
|
8940
|
+
if (budgetMode === "hard") {
|
|
8941
|
+
throw new LLMPromptBudgetExceeded("l3_budget_unreachable");
|
|
8942
|
+
}
|
|
8943
|
+
budgetCode = "l3_budget_unreachable";
|
|
8944
|
+
}
|
|
8615
8945
|
}
|
|
8616
8946
|
logPrompt(prompt, input.aNext, previous.llmLogPath);
|
|
8617
8947
|
traceFull("l3.prompt", {
|
|
@@ -8624,6 +8954,7 @@ async function runLLMAnalysis(input, previous) {
|
|
|
8624
8954
|
prompt_chars: prompt.length
|
|
8625
8955
|
});
|
|
8626
8956
|
const result = await analyzeWithLLM(prompt, config);
|
|
8957
|
+
if (budgetCode) result.degraded = [...result.degraded || [], budgetCode];
|
|
8627
8958
|
traceSummary("l3.verdict", {
|
|
8628
8959
|
allowed: result.allowed,
|
|
8629
8960
|
risk_level: result.riskLevel,
|
|
@@ -8635,7 +8966,7 @@ async function runLLMAnalysis(input, previous) {
|
|
|
8635
8966
|
const firstKey = llmCache.keys().next().value;
|
|
8636
8967
|
if (firstKey) llmCache.delete(firstKey);
|
|
8637
8968
|
}
|
|
8638
|
-
llmCache.set(
|
|
8969
|
+
llmCache.set(cacheKey2, result);
|
|
8639
8970
|
return result;
|
|
8640
8971
|
}
|
|
8641
8972
|
function logPrompt(prompt, aNext, logPath) {
|
|
@@ -8697,11 +9028,14 @@ function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis,
|
|
|
8697
9028
|
const skillsText = formatSkillsForPrompt(matchedSkills);
|
|
8698
9029
|
const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
|
|
8699
9030
|
const promptHistoryText = formatPromptHistory(input.promptHistory);
|
|
9031
|
+
const historyAuthorization = /(因历史窗口上限省略|本段因长度上限已截断)/.test(promptHistoryText) ? `
|
|
9032
|
+
|
|
9033
|
+
${HISTORY_AUTHORIZATION}` : "";
|
|
8700
9034
|
const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
|
|
8701
9035
|
const hintsText = formatHints(previous);
|
|
8702
9036
|
const securityJudgeTemplate = templates["security_judge"];
|
|
8703
9037
|
if (securityJudgeTemplate) {
|
|
8704
|
-
return securityJudgeTemplate.replaceAll("{prompt_session}", input.promptSession || "\uFF08\u672A\u63D0\u4F9B\uFF09").replaceAll("{prompt_history_text}", promptHistoryText).replaceAll("{action_history}", historyStr).replaceAll("{action_type}", input.aNext.actionType).replaceAll("{action_detail}", input.aNext.actionDetail).replaceAll("{reason}", input.reason || "\u672A\u8BF4\u660E").replaceAll("{skills_text}", skillsText).replaceAll("{hints_text}", hintsText).replaceAll("{script_analysis_text}", scriptAnalysisText).replaceAll("{skip_l3_hints}", skipL3Hints).replaceAll("{path_context}", pathContext || "\uFF08\u672C\u547D\u4EE4\u65E0\u4E3B\u76EE\u5F55\u76F8\u5173\u8DEF\u5F84\u6BB5\uFF0C\u4E0D\u9002\u7528\uFF09").replaceAll("{{", "{").replaceAll("}}", "}");
|
|
9038
|
+
return securityJudgeTemplate.replaceAll("{prompt_session}", input.promptSession || "\uFF08\u672A\u63D0\u4F9B\uFF09").replaceAll("{prompt_history_text}", promptHistoryText).replaceAll("{history_authorization}", historyAuthorization).replaceAll("{action_history}", historyStr).replaceAll("{action_type}", input.aNext.actionType).replaceAll("{action_detail}", input.aNext.actionDetail).replaceAll("{reason}", input.reason || "\u672A\u8BF4\u660E").replaceAll("{skills_text}", skillsText).replaceAll("{hints_text}", hintsText).replaceAll("{script_analysis_text}", scriptAnalysisText).replaceAll("{skip_l3_hints}", skipL3Hints).replaceAll("{path_context}", pathContext || "\uFF08\u672C\u547D\u4EE4\u65E0\u4E3B\u76EE\u5F55\u76F8\u5173\u8DEF\u5F84\u6BB5\uFF0C\u4E0D\u9002\u7528\uFF09").replaceAll("{{", "{").replaceAll("}}", "}");
|
|
8705
9039
|
}
|
|
8706
9040
|
console.warn("[AgentMoss] security_judge template missing, using sparse fallback prompt");
|
|
8707
9041
|
return `## \u5F53\u524D\u64CD\u4F5C\u4E0A\u4E0B\u6587
|
|
@@ -8737,21 +9071,28 @@ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNu
|
|
|
8737
9071
|
}
|
|
8738
9072
|
const limit = Math.max(0, Math.floor(maxTurns));
|
|
8739
9073
|
const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
|
|
9074
|
+
let omitted = 0;
|
|
8740
9075
|
const lines = [];
|
|
8741
|
-
for (let i =
|
|
9076
|
+
for (let i = 0; i < promptHistory.length; i++) {
|
|
8742
9077
|
const turn = promptHistory[i];
|
|
8743
9078
|
const text = (typeof turn === "string" ? turn : turn?.text || "").trim();
|
|
8744
|
-
if (!text) continue;
|
|
8745
|
-
let line = ` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${text.slice(0, maxTextChars)}`;
|
|
8746
9079
|
const actions = typeof turn === "string" ? void 0 : turn?.actions;
|
|
8747
|
-
|
|
8748
|
-
|
|
8749
|
-
|
|
8750
|
-
|
|
8751
|
-
|
|
9080
|
+
const types = (actions || []).map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
|
|
9081
|
+
if (!text && types.length === 0) continue;
|
|
9082
|
+
if (i < firstTurnIndex) {
|
|
9083
|
+
omitted += 1;
|
|
9084
|
+
continue;
|
|
9085
|
+
}
|
|
9086
|
+
if (!text) {
|
|
9087
|
+
lines.push(` \u7B2C${i + 1}\u8F6E\u52A8\u4F5C: ${types.join(", ")}`);
|
|
9088
|
+
continue;
|
|
8752
9089
|
}
|
|
8753
|
-
|
|
9090
|
+
let shown = text.slice(0, maxTextChars);
|
|
9091
|
+
if (shown.length < text.length) shown += "\uFF08\u672C\u6BB5\u56E0\u957F\u5EA6\u4E0A\u9650\u5DF2\u622A\u65AD\uFF09";
|
|
9092
|
+
const suffix = types.length > 0 ? ` \u2192 \u52A8\u4F5C: ${types.join(", ")}` : "";
|
|
9093
|
+
lines.push(` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${shown}${suffix}`);
|
|
8754
9094
|
}
|
|
9095
|
+
if (omitted) lines.unshift(`\uFF08\u56E0\u5386\u53F2\u7A97\u53E3\u4E0A\u9650\u7701\u7565 ${omitted} \u8F6E\u66F4\u65E9\u5386\u53F2\u610F\u56FE\uFF09`);
|
|
8755
9096
|
return lines.length > 0 ? lines.join("\n") : "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
|
|
8756
9097
|
}
|
|
8757
9098
|
function formatHints(previous) {
|
|
@@ -8764,11 +9105,15 @@ function formatHints(previous) {
|
|
|
8764
9105
|
);
|
|
8765
9106
|
}
|
|
8766
9107
|
if (previous.logic) {
|
|
8767
|
-
|
|
8768
|
-
`\
|
|
9108
|
+
if (previous.logic.l3Hint) {
|
|
9109
|
+
hints.push(`\u2139\uFE0F ${previous.logic.l3Hint}`);
|
|
9110
|
+
} else {
|
|
9111
|
+
hints.push(
|
|
9112
|
+
`\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
|
|
8769
9113
|
\u7C7B\u578B: ${previous.logic.riskType}
|
|
8770
9114
|
\u539F\u56E0: ${previous.logic.reason}`
|
|
8771
|
-
|
|
9115
|
+
);
|
|
9116
|
+
}
|
|
8772
9117
|
}
|
|
8773
9118
|
return hints.length > 0 ? hints.join("\n\n") : "\u7279\u5F81\u5339\u914D\u68C0\u6D4B\u548C\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u5747\u672A\u53D1\u73B0\u98CE\u9669\u3002";
|
|
8774
9119
|
}
|
|
@@ -8969,7 +9314,7 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
8969
9314
|
)}`;
|
|
8970
9315
|
if (attempt < maxRetries) {
|
|
8971
9316
|
console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
|
|
8972
|
-
await new Promise((
|
|
9317
|
+
await new Promise((resolve12) => setTimeout(resolve12, retryCfg.retryInterval * 1e3));
|
|
8973
9318
|
} else {
|
|
8974
9319
|
clearTimeout(totalTimeoutTimer);
|
|
8975
9320
|
console.error(`[AgentMoss] LLM call failed after all retries: ${detail}`);
|
|
@@ -8992,10 +9337,10 @@ init_esm_shims();
|
|
|
8992
9337
|
|
|
8993
9338
|
// src/brain/rule-store.ts
|
|
8994
9339
|
init_esm_shims();
|
|
8995
|
-
import { existsSync as
|
|
8996
|
-
import { join as
|
|
9340
|
+
import { existsSync as existsSync14, readFileSync as readFileSync14, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
|
|
9341
|
+
import { join as join13 } from "path";
|
|
8997
9342
|
import { homedir as homedir6 } from "os";
|
|
8998
|
-
var DEFAULT_RULES_PATH =
|
|
9343
|
+
var DEFAULT_RULES_PATH = join13(homedir6(), ".agentmoss", "brain", "rules.json");
|
|
8999
9344
|
var ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
|
|
9000
9345
|
var STATUS_DRAFT = "draft";
|
|
9001
9346
|
var STATUS_APPROVED = "approved";
|
|
@@ -9024,11 +9369,11 @@ var BrainRuleStore = class {
|
|
|
9024
9369
|
this.data = this.load();
|
|
9025
9370
|
}
|
|
9026
9371
|
load() {
|
|
9027
|
-
if (!
|
|
9372
|
+
if (!existsSync14(this.path)) {
|
|
9028
9373
|
return { version: 1, rules: [], pattern_candidates: [] };
|
|
9029
9374
|
}
|
|
9030
9375
|
try {
|
|
9031
|
-
const raw = JSON.parse(
|
|
9376
|
+
const raw = JSON.parse(readFileSync14(this.path, "utf-8"));
|
|
9032
9377
|
return {
|
|
9033
9378
|
version: raw.version || 1,
|
|
9034
9379
|
rules: raw.rules || [],
|
|
@@ -9608,11 +9953,11 @@ function parseReview(content) {
|
|
|
9608
9953
|
|
|
9609
9954
|
// src/brain/skill-manager.ts
|
|
9610
9955
|
init_esm_shims();
|
|
9611
|
-
import { existsSync as
|
|
9956
|
+
import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
9612
9957
|
import { homedir as homedir7 } from "os";
|
|
9613
|
-
import { join as
|
|
9958
|
+
import { join as join14 } from "path";
|
|
9614
9959
|
import { randomUUID } from "crypto";
|
|
9615
|
-
var DEFAULT_SKILL_META_PATH =
|
|
9960
|
+
var DEFAULT_SKILL_META_PATH = join14(homedir7(), ".agentmoss", "brain", "skill_meta.json");
|
|
9616
9961
|
var ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
|
|
9617
9962
|
function getMetaPath(override) {
|
|
9618
9963
|
return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
|
|
@@ -9622,7 +9967,7 @@ var BrainSkillManager = class {
|
|
|
9622
9967
|
this.skillsDir = skillsDir;
|
|
9623
9968
|
this.metaPath = getMetaPath(metaPath);
|
|
9624
9969
|
try {
|
|
9625
|
-
mkdirSync5(
|
|
9970
|
+
mkdirSync5(join14(this.metaPath, ".."), { recursive: true });
|
|
9626
9971
|
} catch {
|
|
9627
9972
|
}
|
|
9628
9973
|
this.load();
|
|
@@ -9632,9 +9977,9 @@ var BrainSkillManager = class {
|
|
|
9632
9977
|
skills = [];
|
|
9633
9978
|
metaPath;
|
|
9634
9979
|
load() {
|
|
9635
|
-
if (!
|
|
9980
|
+
if (!existsSync15(this.metaPath)) return;
|
|
9636
9981
|
try {
|
|
9637
|
-
const data = JSON.parse(
|
|
9982
|
+
const data = JSON.parse(readFileSync15(this.metaPath, "utf-8"));
|
|
9638
9983
|
this.skills = data.skills || [];
|
|
9639
9984
|
} catch {
|
|
9640
9985
|
this.skills = [];
|
|
@@ -9657,7 +10002,7 @@ var BrainSkillManager = class {
|
|
|
9657
10002
|
let changed = false;
|
|
9658
10003
|
for (const sk of this.skills) {
|
|
9659
10004
|
if (sk.status !== "active") continue;
|
|
9660
|
-
if (!
|
|
10005
|
+
if (!existsSync15(join14(this.skillsDir, `${sk.name}.md`))) {
|
|
9661
10006
|
sk.status = "stale";
|
|
9662
10007
|
changed = true;
|
|
9663
10008
|
}
|
|
@@ -9668,9 +10013,9 @@ var BrainSkillManager = class {
|
|
|
9668
10013
|
addSkill(skill) {
|
|
9669
10014
|
const id = skill.id || randomUUID();
|
|
9670
10015
|
const name = skill.name || `brain_${id.slice(0, 8)}`;
|
|
9671
|
-
if (!
|
|
9672
|
-
const mdPath =
|
|
9673
|
-
if (
|
|
10016
|
+
if (!existsSync15(this.skillsDir)) return "";
|
|
10017
|
+
const mdPath = join14(this.skillsDir, `${name}.md`);
|
|
10018
|
+
if (existsSync15(mdPath)) return "";
|
|
9674
10019
|
try {
|
|
9675
10020
|
writeFileSync4(mdPath, skill.content, "utf-8");
|
|
9676
10021
|
} catch {
|
|
@@ -9719,12 +10064,12 @@ var BrainSkillManager = class {
|
|
|
9719
10064
|
const out = [];
|
|
9720
10065
|
for (const sk of this.skills) {
|
|
9721
10066
|
if (sk.origin_node !== "local" || sk.status !== "active") continue;
|
|
9722
|
-
const mdPath =
|
|
9723
|
-
if (!
|
|
10067
|
+
const mdPath = join14(this.skillsDir, `${sk.name}.md`);
|
|
10068
|
+
if (!existsSync15(mdPath)) continue;
|
|
9724
10069
|
out.push({
|
|
9725
10070
|
name: sk.name,
|
|
9726
10071
|
category: sk.category || "",
|
|
9727
|
-
content:
|
|
10072
|
+
content: readFileSync15(mdPath, "utf-8"),
|
|
9728
10073
|
keywords: sk.keywords || []
|
|
9729
10074
|
});
|
|
9730
10075
|
}
|
|
@@ -9805,9 +10150,9 @@ var BrainCurator = class {
|
|
|
9805
10150
|
// src/brain/contributor.ts
|
|
9806
10151
|
init_esm_shims();
|
|
9807
10152
|
init_asset_dir();
|
|
9808
|
-
import { dirname as
|
|
9809
|
-
import { fileURLToPath as
|
|
9810
|
-
var __dirname8 =
|
|
10153
|
+
import { dirname as dirname12 } from "path";
|
|
10154
|
+
import { fileURLToPath as fileURLToPath10 } from "url";
|
|
10155
|
+
var __dirname8 = dirname12(fileURLToPath10(import.meta.url));
|
|
9811
10156
|
|
|
9812
10157
|
// src/brain/index.ts
|
|
9813
10158
|
function checkBrainRules(store, opts) {
|
|
@@ -10113,11 +10458,35 @@ function checkMCRules(graph) {
|
|
|
10113
10458
|
for (const rule of rules) {
|
|
10114
10459
|
if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
|
|
10115
10460
|
if (ruleViolates(rule, trace2, witnessMode)) {
|
|
10461
|
+
const pathNodes = nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3);
|
|
10462
|
+
const path8 = pathNodes.map((n) => ({
|
|
10463
|
+
sessionId: n.sessionId,
|
|
10464
|
+
seq: n.seq,
|
|
10465
|
+
detail: n.actionDetail.slice(0, 60)
|
|
10466
|
+
}));
|
|
10116
10467
|
violations.push({
|
|
10117
10468
|
propertyId: String(rule.id || "mc-ltl"),
|
|
10118
10469
|
reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
|
|
10119
10470
|
riskLevel: String(rule.risk_level || "high"),
|
|
10120
|
-
path:
|
|
10471
|
+
path: path8,
|
|
10472
|
+
graph: {
|
|
10473
|
+
property_id: String(rule.id || "mc-ltl"),
|
|
10474
|
+
property_short: "P6",
|
|
10475
|
+
property_name: "LTL \u6A21\u578B\u68C0\u6D4B",
|
|
10476
|
+
nodes: pathNodes.map((n) => ({
|
|
10477
|
+
session_id: n.sessionId,
|
|
10478
|
+
seq: n.seq,
|
|
10479
|
+
stage: n.stage,
|
|
10480
|
+
action_detail: n.actionDetail,
|
|
10481
|
+
resources: [...n.resources].sort(),
|
|
10482
|
+
instance_id: n.instanceId || ""
|
|
10483
|
+
})),
|
|
10484
|
+
edges: pathNodes.slice(1).map((_, i) => ({
|
|
10485
|
+
from: i,
|
|
10486
|
+
to: i + 1,
|
|
10487
|
+
type: "next"
|
|
10488
|
+
}))
|
|
10489
|
+
}
|
|
10121
10490
|
});
|
|
10122
10491
|
if (witnessMode) return violations;
|
|
10123
10492
|
}
|
|
@@ -10812,11 +11181,17 @@ function checkLowIntegrityCommandExec(graph) {
|
|
|
10812
11181
|
for (const i of candidates) {
|
|
10813
11182
|
const n = nodes[i];
|
|
10814
11183
|
if (lowAt.has(i) && isComputeNode(n)) {
|
|
11184
|
+
const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
10815
11185
|
violations.push({
|
|
10816
11186
|
propertyId: "low-integrity-command-exec",
|
|
10817
11187
|
reason: `\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u63A7\u5236\u547D\u4EE4\u6267\u884C\uFF1A${lowAt.get(i)} \u2192 ${n.sessionId}#${n.seq} \u6267\u884C\u4E0D\u53EF\u4FE1\u5185\u5BB9`,
|
|
10818
11188
|
riskLevel: "critical",
|
|
10819
|
-
path:
|
|
11189
|
+
path: path8,
|
|
11190
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
11191
|
+
property_id: "low-integrity-command-exec",
|
|
11192
|
+
property_short: "P7",
|
|
11193
|
+
property_name: "\u4F4E\u5B8C\u6574\u6027\u547D\u4EE4\u6267\u884C"
|
|
11194
|
+
}, ["sink"])
|
|
10820
11195
|
});
|
|
10821
11196
|
if (witness !== void 0) return violations;
|
|
10822
11197
|
}
|
|
@@ -10859,11 +11234,21 @@ function checkCrossSessionReachability(graph) {
|
|
|
10859
11234
|
if (reached.has(i)) {
|
|
10860
11235
|
const srcIdx = Math.min(...sources);
|
|
10861
11236
|
const srcDesc = nodes[srcIdx].actionDetail.slice(0, 40);
|
|
11237
|
+
const path8 = nodes.slice(-3).map((m) => ({
|
|
11238
|
+
sessionId: m.sessionId,
|
|
11239
|
+
seq: m.seq,
|
|
11240
|
+
detail: m.actionDetail.slice(0, 60)
|
|
11241
|
+
}));
|
|
10862
11242
|
violations.push({
|
|
10863
11243
|
propertyId: "low-integrity-reachability",
|
|
10864
11244
|
reason: `\u4F4E\u5B8C\u6574\u6027\u6E90\u7ECF\u8DE8 session \u6570\u636E\u94FE\u591A\u8DF3\u5230\u8FBE\u5F53\u524D\u6267\u884C\uFF08\u6E90: ${srcDesc} \u2192 ${n.sessionId}#${n.seq}\uFF09`,
|
|
10865
11245
|
riskLevel: "high",
|
|
10866
|
-
path:
|
|
11246
|
+
path: path8,
|
|
11247
|
+
graph: graphFromPath(nodes, path8, "data", {
|
|
11248
|
+
property_id: "low-integrity-reachability",
|
|
11249
|
+
property_short: "P3",
|
|
11250
|
+
property_name: "\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u6D41\u53EF\u8FBE"
|
|
11251
|
+
})
|
|
10867
11252
|
});
|
|
10868
11253
|
if (witness !== void 0) return violations;
|
|
10869
11254
|
}
|
|
@@ -11160,9 +11545,19 @@ async function runAnalysis(input) {
|
|
|
11160
11545
|
isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
|
|
11161
11546
|
isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
|
|
11162
11547
|
);
|
|
11548
|
+
const degradedNotes = [];
|
|
11163
11549
|
let scriptChain = null;
|
|
11164
|
-
if (input.aNext.actionType.toLowerCase() === "bash") {
|
|
11550
|
+
if (input.aNext.actionType.toLowerCase() === "bash" && getDeployRole() === "host") {
|
|
11551
|
+
degradedNotes.push("script_content_deferred_to_sandbox: AGENT_MOSS_DEPLOY_ROLE=host");
|
|
11552
|
+
} else if (input.aNext.actionType.toLowerCase() === "bash") {
|
|
11165
11553
|
scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
|
|
11554
|
+
if (scriptChain.nodes.length > 0) {
|
|
11555
|
+
for (const node of scriptChain.nodes) {
|
|
11556
|
+
if (node.error && !node.unanalyzable) {
|
|
11557
|
+
degradedNotes.push(`script_content_unavailable: ${node.scriptPath} (${node.error})`);
|
|
11558
|
+
}
|
|
11559
|
+
}
|
|
11560
|
+
}
|
|
11166
11561
|
if (heuristicEnabled && scriptChain.nodes.length > 0) {
|
|
11167
11562
|
for (const node of scriptChain.nodes) {
|
|
11168
11563
|
if (node.unanalyzable) {
|
|
@@ -11433,7 +11828,8 @@ async function runAnalysis(input) {
|
|
|
11433
11828
|
riskType: "",
|
|
11434
11829
|
confidence: 85,
|
|
11435
11830
|
source: "heuristic_and_logic_only",
|
|
11436
|
-
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
|
|
11831
|
+
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
|
|
11832
|
+
degraded: degradedNotes
|
|
11437
11833
|
};
|
|
11438
11834
|
}
|
|
11439
11835
|
let skipL3Hints = "\u65E0\uFF08\u5F53\u524D\u65E0\u7981\u7528\u89C4\u5219\u547D\u4E2D\uFF09";
|
|
@@ -11470,8 +11866,22 @@ async function runAnalysis(input) {
|
|
|
11470
11866
|
pathContext
|
|
11471
11867
|
});
|
|
11472
11868
|
} catch (e) {
|
|
11473
|
-
const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
|
|
11474
11869
|
const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
|
|
11870
|
+
if (e instanceof LLMPromptBudgetExceeded) {
|
|
11871
|
+
const failMode = getLLMFailMode2();
|
|
11872
|
+
const allowed = failMode === "fail_open";
|
|
11873
|
+
return {
|
|
11874
|
+
allowed,
|
|
11875
|
+
reason: `L3 prompt \u8D85\u51FA\u786C\u9884\u7B97\uFF0C\u5DF2\u8DF3\u8FC7\u8BED\u4E49\u5206\u6790\uFF0C\u6309 ${failMode} ${allowed ? "\u653E\u884C" : "\u62D2\u7EDD"}`,
|
|
11876
|
+
riskLevel: allowed ? "low" : "medium",
|
|
11877
|
+
riskType: "",
|
|
11878
|
+
confidence: allowed ? 50 : 60,
|
|
11879
|
+
source: "llm_budget_skipped",
|
|
11880
|
+
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
|
|
11881
|
+
degraded: [...degradedNotes, e.code]
|
|
11882
|
+
};
|
|
11883
|
+
}
|
|
11884
|
+
const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
|
|
11475
11885
|
if (getLLMFailMode2() === "fail_open") {
|
|
11476
11886
|
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}`);
|
|
11477
11887
|
return {
|
|
@@ -11481,7 +11891,8 @@ async function runAnalysis(input) {
|
|
|
11481
11891
|
riskType: "",
|
|
11482
11892
|
confidence: 50,
|
|
11483
11893
|
source: failSource,
|
|
11484
|
-
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
|
|
11894
|
+
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
|
|
11895
|
+
degraded: degradedNotes
|
|
11485
11896
|
};
|
|
11486
11897
|
}
|
|
11487
11898
|
return {
|
|
@@ -11491,7 +11902,10 @@ async function runAnalysis(input) {
|
|
|
11491
11902
|
riskType: "",
|
|
11492
11903
|
confidence: 60,
|
|
11493
11904
|
source: failSource,
|
|
11494
|
-
violatedLayers: ["L3.1"]
|
|
11905
|
+
violatedLayers: ["L3.1"],
|
|
11906
|
+
degraded: degradedNotes,
|
|
11907
|
+
ask_recommended: true,
|
|
11908
|
+
ask_reason: "L3 \u8BED\u4E49\u5206\u6790\u4E0D\u53EF\u7528\uFF0C\u6309 fail_closed \u62D2\u7EDD\uFF1B\u8FD9\u662F\u201C\u6CA1\u67E5\u5B8C\u201D\u800C\u975E\u201C\u786E\u8BA4\u6709\u98CE\u9669\u201D\uFF0C\u5EFA\u8BAE\u5411\u7528\u6237\u786E\u8BA4\u662F\u5426\u7EE7\u7EED\u3002"
|
|
11495
11909
|
};
|
|
11496
11910
|
}
|
|
11497
11911
|
if (!llmResult.allowed && llmResult.confidence && llmResult.confidence >= 90 && _brainExtractor) {
|
|
@@ -11511,6 +11925,9 @@ async function runAnalysis(input) {
|
|
|
11511
11925
|
if (observedFormalLayers.length > 0 && llmResult.allowed) {
|
|
11512
11926
|
llmResult.violatedLayers = Array.from(/* @__PURE__ */ new Set([...observedFormalLayers, ...llmResult.violatedLayers || []]));
|
|
11513
11927
|
}
|
|
11928
|
+
if (degradedNotes.length > 0) {
|
|
11929
|
+
llmResult.degraded = Array.from(/* @__PURE__ */ new Set([...llmResult.degraded || [], ...degradedNotes]));
|
|
11930
|
+
}
|
|
11514
11931
|
return llmResult;
|
|
11515
11932
|
}
|
|
11516
11933
|
export {
|