@kenhkl/agent-moss 0.17.22 → 0.17.23
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 +1055 -211
- package/dist/engine/coordinator.js +642 -116
- package/dist/server.js +1004 -174
- package/package.json +1 -1
|
@@ -442,22 +442,22 @@ function loadToolRegistry() {
|
|
|
442
442
|
data.tools = tools;
|
|
443
443
|
return data;
|
|
444
444
|
}
|
|
445
|
-
function scanStructEntry(cat, value,
|
|
445
|
+
function scanStructEntry(cat, value, path6) {
|
|
446
446
|
if (cat === "skills") {
|
|
447
447
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
448
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
448
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
449
449
|
return null;
|
|
450
450
|
}
|
|
451
451
|
const out = {};
|
|
452
452
|
for (const [skCat, skills] of Object.entries(value)) {
|
|
453
453
|
if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
|
|
454
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
454
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
|
|
455
455
|
continue;
|
|
456
456
|
}
|
|
457
457
|
const keep = {};
|
|
458
458
|
for (const [name, kws] of Object.entries(skills)) {
|
|
459
459
|
if (Array.isArray(kws)) keep[name] = kws;
|
|
460
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
460
|
+
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
461
461
|
}
|
|
462
462
|
if (Object.keys(keep).length > 0) out[skCat] = keep;
|
|
463
463
|
}
|
|
@@ -465,37 +465,37 @@ function scanStructEntry(cat, value, path5) {
|
|
|
465
465
|
}
|
|
466
466
|
if (cat === "ltl_rules") {
|
|
467
467
|
if (!Array.isArray(value)) {
|
|
468
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
468
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
469
469
|
return null;
|
|
470
470
|
}
|
|
471
471
|
const keep = value.filter((r) => r && typeof r === "object" && r.id);
|
|
472
472
|
if (keep.length !== value.length) {
|
|
473
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
473
|
+
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
474
474
|
}
|
|
475
475
|
return keep.length > 0 ? keep : null;
|
|
476
476
|
}
|
|
477
477
|
if (cat === "tools") {
|
|
478
478
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
479
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
479
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
480
480
|
return null;
|
|
481
481
|
}
|
|
482
482
|
const keep = {};
|
|
483
483
|
for (const [k, v] of Object.entries(value)) {
|
|
484
484
|
if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
|
|
485
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
485
|
+
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
486
486
|
}
|
|
487
487
|
return Object.keys(keep).length > 0 ? keep : null;
|
|
488
488
|
}
|
|
489
489
|
return null;
|
|
490
490
|
}
|
|
491
|
-
function scanRulesFile(
|
|
491
|
+
function scanRulesFile(path6, kind) {
|
|
492
492
|
const out = {};
|
|
493
493
|
const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
|
|
494
494
|
let parsed;
|
|
495
495
|
try {
|
|
496
|
-
parsed = JSON.parse(readFileSync2(
|
|
496
|
+
parsed = JSON.parse(readFileSync2(path6, "utf-8"));
|
|
497
497
|
} catch (e) {
|
|
498
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
498
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
|
|
499
499
|
return out;
|
|
500
500
|
}
|
|
501
501
|
const classifyFlat = (r) => {
|
|
@@ -519,44 +519,44 @@ function scanRulesFile(path5, kind) {
|
|
|
519
519
|
}
|
|
520
520
|
if (flatBad > 0) {
|
|
521
521
|
console.warn(
|
|
522
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
522
|
+
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
|
|
523
523
|
);
|
|
524
524
|
}
|
|
525
525
|
} else {
|
|
526
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
526
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
|
|
527
527
|
return out;
|
|
528
528
|
}
|
|
529
529
|
for (const [cat, rules] of pairs) {
|
|
530
530
|
if (String(cat).startsWith("_")) continue;
|
|
531
531
|
if (STRUCT_KEYS.includes(cat)) {
|
|
532
|
-
const got = scanStructEntry(cat, rules,
|
|
532
|
+
const got = scanStructEntry(cat, rules, path6);
|
|
533
533
|
if (got !== null) out[cat] = got;
|
|
534
534
|
continue;
|
|
535
535
|
}
|
|
536
536
|
const required = EXTRA_CATEGORIES[cat];
|
|
537
537
|
if (!required) {
|
|
538
538
|
console.warn(
|
|
539
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
539
|
+
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
|
|
540
540
|
);
|
|
541
541
|
continue;
|
|
542
542
|
}
|
|
543
543
|
if (rules && typeof rules === "object" && !Array.isArray(rules)) {
|
|
544
544
|
console.error(
|
|
545
|
-
`[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${
|
|
545
|
+
`[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path6} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
|
|
546
546
|
\u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
|
|
547
547
|
\u4F60\u5199\u7684\u50CF\u662F runtime config \u7684\u683C\u5F0F\uFF08{"category_enabled": ..., "rules": [...]}\uFF09\u2014\u2014\u90A3\u662F ~/.config/agentmoss/agent_moss_runtime.json \u7684\u683C\u5F0F\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5F53\u89C4\u5219\u6587\u4EF6\u7528\u3002`
|
|
548
548
|
);
|
|
549
549
|
continue;
|
|
550
550
|
}
|
|
551
551
|
if (!Array.isArray(rules)) {
|
|
552
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
552
|
+
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
|
|
553
553
|
continue;
|
|
554
554
|
}
|
|
555
555
|
const items = [];
|
|
556
556
|
for (const r of rules) {
|
|
557
557
|
if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
|
|
558
558
|
console.warn(
|
|
559
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
559
|
+
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
|
|
560
560
|
);
|
|
561
561
|
continue;
|
|
562
562
|
}
|
|
@@ -566,7 +566,7 @@ function scanRulesFile(path5, kind) {
|
|
|
566
566
|
}
|
|
567
567
|
if (Object.keys(out).length > 0) {
|
|
568
568
|
console.info(
|
|
569
|
-
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${
|
|
569
|
+
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path6}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
|
|
570
570
|
);
|
|
571
571
|
}
|
|
572
572
|
return out;
|
|
@@ -967,7 +967,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
|
|
|
967
967
|
os: String(sp.os || "linux").toLowerCase()
|
|
968
968
|
}));
|
|
969
969
|
}
|
|
970
|
-
function _scopeOf(os3,
|
|
970
|
+
function _scopeOf(os3, path6) {
|
|
971
971
|
if (!_scopeIndex) {
|
|
972
972
|
_scopeIndex = /* @__PURE__ */ new Map();
|
|
973
973
|
for (const sp of loadL1().sensitive_path_access || []) {
|
|
@@ -975,7 +975,7 @@ function _scopeOf(os3, path5) {
|
|
|
975
975
|
if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
|
|
976
976
|
}
|
|
977
977
|
}
|
|
978
|
-
return _scopeIndex.get(`${String(os3 || "linux").toLowerCase()}|${
|
|
978
|
+
return _scopeIndex.get(`${String(os3 || "linux").toLowerCase()}|${path6}`) || "root";
|
|
979
979
|
}
|
|
980
980
|
function getSensitivePathsForOs(osType) {
|
|
981
981
|
const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
|
|
@@ -1326,17 +1326,17 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1326
1326
|
return null;
|
|
1327
1327
|
}
|
|
1328
1328
|
const unreadPaths = [];
|
|
1329
|
-
for (const
|
|
1329
|
+
for (const path6 of filteredPaths) {
|
|
1330
1330
|
const hasRead = [...historyReadPaths].some(
|
|
1331
|
-
(rp) =>
|
|
1331
|
+
(rp) => path6 === rp || path6.startsWith(rp) || rp.startsWith(path6)
|
|
1332
1332
|
);
|
|
1333
1333
|
if (!hasRead) {
|
|
1334
|
-
let isCreate = !fs.existsSync(
|
|
1334
|
+
let isCreate = !fs.existsSync(path6);
|
|
1335
1335
|
if (!isCreate) {
|
|
1336
1336
|
isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
|
|
1337
1337
|
}
|
|
1338
1338
|
if (!isCreate) {
|
|
1339
|
-
unreadPaths.push(
|
|
1339
|
+
unreadPaths.push(path6);
|
|
1340
1340
|
}
|
|
1341
1341
|
}
|
|
1342
1342
|
}
|
|
@@ -1530,16 +1530,16 @@ var init_logic_rules = __esm({
|
|
|
1530
1530
|
ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
|
|
1531
1531
|
ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
|
|
1532
1532
|
HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
|
|
1533
|
-
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path:
|
|
1533
|
+
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
|
|
1534
1534
|
ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
|
|
1535
1535
|
HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
|
|
1536
|
-
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path:
|
|
1536
|
+
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
|
|
1537
1537
|
ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
|
|
1538
1538
|
HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
|
|
1539
|
-
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path:
|
|
1539
|
+
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
|
|
1540
1540
|
ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
|
|
1541
1541
|
HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
|
|
1542
|
-
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path:
|
|
1542
|
+
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
|
|
1543
1543
|
_scopeIndex = null;
|
|
1544
1544
|
NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
|
|
1545
1545
|
"ask_user_question",
|
|
@@ -3308,7 +3308,9 @@ function loadLLMConfigFromFile(configPath) {
|
|
|
3308
3308
|
model: llm.model || "",
|
|
3309
3309
|
temperature: llm.temperature ?? 0.1,
|
|
3310
3310
|
maxTokens: llm.max_tokens ?? 4096,
|
|
3311
|
-
timeout: llm.timeout ?? 40
|
|
3311
|
+
timeout: llm.timeout ?? 40,
|
|
3312
|
+
// 部署级透传参数(关思考等)。非对象直接忽略:写错不能拖垮配置加载。
|
|
3313
|
+
...llm.extra_body && typeof llm.extra_body === "object" && !Array.isArray(llm.extra_body) ? { extraBody: llm.extra_body } : {}
|
|
3312
3314
|
};
|
|
3313
3315
|
}
|
|
3314
3316
|
function loadTimeoutRetryFromFile(configPath) {
|
|
@@ -4140,16 +4142,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4140
4142
|
if (String(osType || "").toLowerCase() === "windows") {
|
|
4141
4143
|
pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
|
|
4142
4144
|
}
|
|
4143
|
-
const pathMatches = (text,
|
|
4144
|
-
const parts =
|
|
4145
|
+
const pathMatches = (text, path6) => {
|
|
4146
|
+
const parts = path6.split(/(\(\?!.*?\))/);
|
|
4145
4147
|
const escaped = parts.map((part) => {
|
|
4146
4148
|
if (part.startsWith("(?!")) return part;
|
|
4147
4149
|
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4148
4150
|
}).join("");
|
|
4149
|
-
const re =
|
|
4151
|
+
const re = path6.startsWith(".") || path6.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
|
|
4150
4152
|
return re.test(text);
|
|
4151
4153
|
};
|
|
4152
|
-
const pathMatchesAny = (
|
|
4154
|
+
const pathMatchesAny = (path6) => pathScanTexts.some((t) => pathMatches(t, path6));
|
|
4153
4155
|
for (const sp of rootPaths) {
|
|
4154
4156
|
if (pathMatchesAny(sp.path.toLowerCase())) {
|
|
4155
4157
|
if (keygenGenerate) continue;
|
|
@@ -4292,8 +4294,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4292
4294
|
}
|
|
4293
4295
|
return null;
|
|
4294
4296
|
}
|
|
4295
|
-
function isHomeValue(
|
|
4296
|
-
let p =
|
|
4297
|
+
function isHomeValue(path6) {
|
|
4298
|
+
let p = path6.trim().toLowerCase();
|
|
4297
4299
|
if (p.startsWith("$(") && p.endsWith(")")) {
|
|
4298
4300
|
const inner = p.slice(2, -1).trim();
|
|
4299
4301
|
return HOME_TARGET_RE.test(" " + inner);
|
|
@@ -4349,15 +4351,15 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
4349
4351
|
}
|
|
4350
4352
|
const assigned = {};
|
|
4351
4353
|
for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
|
|
4352
|
-
for (const [varName,
|
|
4353
|
-
if (!isHomeValue(
|
|
4354
|
+
for (const [varName, path6] of Object.entries(assigned)) {
|
|
4355
|
+
if (!isHomeValue(path6)) continue;
|
|
4354
4356
|
const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
|
|
4355
4357
|
for (const seg of segs) {
|
|
4356
4358
|
if (!isDeleteCommand(seg)) continue;
|
|
4357
4359
|
if (varRefRe.test(seg)) {
|
|
4358
4360
|
return {
|
|
4359
4361
|
allowed: false,
|
|
4360
|
-
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${
|
|
4362
|
+
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path6}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
|
|
4361
4363
|
riskLevel: "high",
|
|
4362
4364
|
riskType: "script_execution",
|
|
4363
4365
|
confidence: 90,
|
|
@@ -4623,9 +4625,10 @@ __export(token_stats_exports, {
|
|
|
4623
4625
|
getTokenStats: () => getTokenStats,
|
|
4624
4626
|
getTokenTrend: () => getTokenTrend,
|
|
4625
4627
|
recordTokenUsage: () => recordTokenUsage,
|
|
4626
|
-
resetTokenStats: () => resetTokenStats
|
|
4628
|
+
resetTokenStats: () => resetTokenStats,
|
|
4629
|
+
resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
|
|
4627
4630
|
});
|
|
4628
|
-
import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2 } from "fs";
|
|
4631
|
+
import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync5 } from "fs";
|
|
4629
4632
|
function getStatsPath() {
|
|
4630
4633
|
const envPath = process.env[ENV_STATS_PATH];
|
|
4631
4634
|
if (envPath) return envPath;
|
|
@@ -4633,11 +4636,24 @@ function getStatsPath() {
|
|
|
4633
4636
|
}
|
|
4634
4637
|
function loadAllRecords(statsPath) {
|
|
4635
4638
|
if (!existsSync12(statsPath)) return [];
|
|
4639
|
+
let sig = "";
|
|
4636
4640
|
try {
|
|
4637
|
-
const
|
|
4638
|
-
|
|
4639
|
-
|
|
4641
|
+
const st = statSync5(statsPath);
|
|
4642
|
+
sig = `${st.mtimeMs}:${st.size}`;
|
|
4643
|
+
} catch {
|
|
4640
4644
|
return [];
|
|
4645
|
+
}
|
|
4646
|
+
if (_recordsCache && _recordsCache.path === statsPath && _recordsCache.sig === sig) {
|
|
4647
|
+
return _recordsCache.records.slice();
|
|
4648
|
+
}
|
|
4649
|
+
try {
|
|
4650
|
+
const data = JSON.parse(readFileSync12(statsPath, "utf-8"));
|
|
4651
|
+
let records;
|
|
4652
|
+
if (Array.isArray(data)) records = data;
|
|
4653
|
+
else if (data && Array.isArray(data.records)) records = data.records;
|
|
4654
|
+
else records = [];
|
|
4655
|
+
_recordsCache = { path: statsPath, sig, records };
|
|
4656
|
+
return records.slice();
|
|
4641
4657
|
} catch (e) {
|
|
4642
4658
|
return [];
|
|
4643
4659
|
}
|
|
@@ -4647,9 +4663,22 @@ function saveRecords(statsPath, records) {
|
|
|
4647
4663
|
const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
|
|
4648
4664
|
if (dir && !existsSync12(dir)) mkdirSync3(dir, { recursive: true });
|
|
4649
4665
|
writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
|
|
4666
|
+
try {
|
|
4667
|
+
const st = statSync5(statsPath);
|
|
4668
|
+
_recordsCache = {
|
|
4669
|
+
path: statsPath,
|
|
4670
|
+
sig: `${st.mtimeMs}:${st.size}`,
|
|
4671
|
+
records: records.slice()
|
|
4672
|
+
};
|
|
4673
|
+
} catch {
|
|
4674
|
+
_recordsCache = null;
|
|
4675
|
+
}
|
|
4650
4676
|
} catch (e) {
|
|
4651
4677
|
}
|
|
4652
4678
|
}
|
|
4679
|
+
function resetTokenStatsCacheForTests() {
|
|
4680
|
+
_recordsCache = null;
|
|
4681
|
+
}
|
|
4653
4682
|
function recordTokenUsage(record) {
|
|
4654
4683
|
const statsPath = getStatsPath();
|
|
4655
4684
|
const records = loadAllRecords(statsPath);
|
|
@@ -4778,8 +4807,9 @@ function resetTokenStats() {
|
|
|
4778
4807
|
} catch {
|
|
4779
4808
|
}
|
|
4780
4809
|
}
|
|
4810
|
+
_recordsCache = null;
|
|
4781
4811
|
}
|
|
4782
|
-
var ENV_STATS_PATH, MAX_RECORDS;
|
|
4812
|
+
var ENV_STATS_PATH, MAX_RECORDS, _recordsCache;
|
|
4783
4813
|
var init_token_stats = __esm({
|
|
4784
4814
|
"src/engine/token-stats.ts"() {
|
|
4785
4815
|
"use strict";
|
|
@@ -4787,6 +4817,7 @@ var init_token_stats = __esm({
|
|
|
4787
4817
|
init_paths();
|
|
4788
4818
|
ENV_STATS_PATH = "AGENT_MOSS_TOKEN_STATS_PATH";
|
|
4789
4819
|
MAX_RECORDS = 1e4;
|
|
4820
|
+
_recordsCache = null;
|
|
4790
4821
|
}
|
|
4791
4822
|
});
|
|
4792
4823
|
|
|
@@ -5506,15 +5537,15 @@ function parseShellString(s) {
|
|
|
5506
5537
|
let m;
|
|
5507
5538
|
while ((m = CHILD_CALL_RE.exec(s)) !== null) {
|
|
5508
5539
|
const interp = m[1];
|
|
5509
|
-
const
|
|
5540
|
+
const path6 = m[2].trim();
|
|
5510
5541
|
let rest = m[3].trim();
|
|
5511
|
-
if (
|
|
5542
|
+
if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
|
|
5512
5543
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5513
5544
|
const args = [];
|
|
5514
5545
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5515
5546
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5516
5547
|
}
|
|
5517
|
-
return { path:
|
|
5548
|
+
return { path: path6, args, interpreter: interp };
|
|
5518
5549
|
}
|
|
5519
5550
|
return null;
|
|
5520
5551
|
}
|
|
@@ -5560,9 +5591,9 @@ function extractCallsFromTree(tree, reachableLines) {
|
|
|
5560
5591
|
}
|
|
5561
5592
|
if (allStr && elts.length >= 2) {
|
|
5562
5593
|
const interp = elts[0];
|
|
5563
|
-
const
|
|
5564
|
-
if (!
|
|
5565
|
-
add({ path:
|
|
5594
|
+
const path6 = elts[1];
|
|
5595
|
+
if (!path6.startsWith("-") && !path6.startsWith("$") && !path6.includes("/dev/")) {
|
|
5596
|
+
add({ path: path6, args: elts.slice(2), interpreter: interp });
|
|
5566
5597
|
return true;
|
|
5567
5598
|
}
|
|
5568
5599
|
}
|
|
@@ -5602,15 +5633,15 @@ function extractCallsRegex(content) {
|
|
|
5602
5633
|
let m;
|
|
5603
5634
|
while ((m = CHILD_CALL_RE.exec(content)) !== null) {
|
|
5604
5635
|
const interp = m[1];
|
|
5605
|
-
const
|
|
5636
|
+
const path6 = m[2].trim();
|
|
5606
5637
|
let rest = m[3].trim();
|
|
5607
|
-
if (
|
|
5638
|
+
if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
|
|
5608
5639
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5609
5640
|
const args = [];
|
|
5610
5641
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5611
5642
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5612
5643
|
}
|
|
5613
|
-
calls.push({ path:
|
|
5644
|
+
calls.push({ path: path6, args, interpreter: interp });
|
|
5614
5645
|
}
|
|
5615
5646
|
return calls;
|
|
5616
5647
|
}
|
|
@@ -6340,15 +6371,15 @@ function extractCallsFromContent(content) {
|
|
|
6340
6371
|
CHILD_CALL_RE2.lastIndex = 0;
|
|
6341
6372
|
while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
|
|
6342
6373
|
const interp = m[1];
|
|
6343
|
-
const
|
|
6374
|
+
const path6 = m[2].trim();
|
|
6344
6375
|
let rest = m[3].trim();
|
|
6345
|
-
if (
|
|
6376
|
+
if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
|
|
6346
6377
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
6347
6378
|
const args = [];
|
|
6348
6379
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
6349
6380
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
6350
6381
|
}
|
|
6351
|
-
calls.push({ path:
|
|
6382
|
+
calls.push({ path: path6, args, interpreter: interp });
|
|
6352
6383
|
}
|
|
6353
6384
|
return calls;
|
|
6354
6385
|
}
|
|
@@ -6992,6 +7023,420 @@ ${contentPreview}
|
|
|
6992
7023
|
// src/engine/llm-analyzer.ts
|
|
6993
7024
|
import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
|
|
6994
7025
|
import OpenAI from "openai";
|
|
7026
|
+
|
|
7027
|
+
// src/infra/trace-log.ts
|
|
7028
|
+
init_esm_shims();
|
|
7029
|
+
init_paths();
|
|
7030
|
+
import fs4 from "fs";
|
|
7031
|
+
import path4 from "path";
|
|
7032
|
+
var LEVEL_OFF = 0;
|
|
7033
|
+
var LEVEL_SUMMARY = 1;
|
|
7034
|
+
var LEVEL_FULL = 2;
|
|
7035
|
+
var LEVEL_NAMES = {
|
|
7036
|
+
off: LEVEL_OFF,
|
|
7037
|
+
summary: LEVEL_SUMMARY,
|
|
7038
|
+
full: LEVEL_FULL
|
|
7039
|
+
};
|
|
7040
|
+
var MAX_FIELD_CHARS = 64 * 1024;
|
|
7041
|
+
var SECRET_KEYS = /* @__PURE__ */ new Set([
|
|
7042
|
+
"api_key",
|
|
7043
|
+
"apikey",
|
|
7044
|
+
"authorization",
|
|
7045
|
+
"auth_token",
|
|
7046
|
+
"token",
|
|
7047
|
+
"password"
|
|
7048
|
+
]);
|
|
7049
|
+
var MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
7050
|
+
var _levelCache = null;
|
|
7051
|
+
var _levelCacheRaw = null;
|
|
7052
|
+
var _warnedInvalid = false;
|
|
7053
|
+
function traceLevel() {
|
|
7054
|
+
if (_levelCache !== null) return _levelCache;
|
|
7055
|
+
const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
|
|
7056
|
+
let level;
|
|
7057
|
+
if (raw in LEVEL_NAMES) {
|
|
7058
|
+
level = LEVEL_NAMES[raw];
|
|
7059
|
+
} else {
|
|
7060
|
+
level = LEVEL_SUMMARY;
|
|
7061
|
+
if (!_warnedInvalid) {
|
|
7062
|
+
_warnedInvalid = true;
|
|
7063
|
+
console.warn(
|
|
7064
|
+
`[AgentMoss] AGENT_MOSS_TRACE_LEVEL=${JSON.stringify(raw)} \u975E\u6CD5\uFF0C\u6309 summary \u5904\u7406\uFF08\u53EF\u9009 off/summary/full\uFF09`
|
|
7065
|
+
);
|
|
7066
|
+
}
|
|
7067
|
+
}
|
|
7068
|
+
_levelCache = level;
|
|
7069
|
+
_levelCacheRaw = raw;
|
|
7070
|
+
return level;
|
|
7071
|
+
}
|
|
7072
|
+
function nowIso() {
|
|
7073
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
7074
|
+
}
|
|
7075
|
+
function tracePath() {
|
|
7076
|
+
const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
|
|
7077
|
+
if (explicit) return explicit;
|
|
7078
|
+
try {
|
|
7079
|
+
return path4.join(getDataRoot(), "agent_moss_trace.log");
|
|
7080
|
+
} catch {
|
|
7081
|
+
return "agent_moss_trace.log";
|
|
7082
|
+
}
|
|
7083
|
+
}
|
|
7084
|
+
function sanitize(key, value) {
|
|
7085
|
+
if (SECRET_KEYS.has(key.toLowerCase())) return "***";
|
|
7086
|
+
if (typeof value === "string") {
|
|
7087
|
+
let v = value;
|
|
7088
|
+
if (v.length > MAX_FIELD_CHARS) {
|
|
7089
|
+
const original = v.length;
|
|
7090
|
+
v = `${v.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
|
|
7091
|
+
}
|
|
7092
|
+
return v;
|
|
7093
|
+
}
|
|
7094
|
+
if (value === null || ["number", "boolean"].includes(typeof value)) return value;
|
|
7095
|
+
let text;
|
|
7096
|
+
try {
|
|
7097
|
+
text = JSON.stringify(value);
|
|
7098
|
+
} catch {
|
|
7099
|
+
return String(value);
|
|
7100
|
+
}
|
|
7101
|
+
if (text.length > MAX_FIELD_CHARS) {
|
|
7102
|
+
const original = text.length;
|
|
7103
|
+
return `${text.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
|
|
7104
|
+
}
|
|
7105
|
+
return value;
|
|
7106
|
+
}
|
|
7107
|
+
function trace(event, level = LEVEL_SUMMARY, fields = {}) {
|
|
7108
|
+
if (traceLevel() < level) return;
|
|
7109
|
+
try {
|
|
7110
|
+
const record = { ts: nowIso(), event };
|
|
7111
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
7112
|
+
record[key] = sanitize(key, value);
|
|
7113
|
+
}
|
|
7114
|
+
const line = `${JSON.stringify(record)}
|
|
7115
|
+
`;
|
|
7116
|
+
const file = tracePath();
|
|
7117
|
+
try {
|
|
7118
|
+
const dir = path4.dirname(file);
|
|
7119
|
+
if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
|
|
7120
|
+
try {
|
|
7121
|
+
const st = fs4.statSync(file);
|
|
7122
|
+
if (st.size > MAX_FILE_BYTES) fs4.renameSync(file, `${file}.1`);
|
|
7123
|
+
} catch {
|
|
7124
|
+
}
|
|
7125
|
+
fs4.appendFileSync(file, line, { encoding: "utf-8", mode: 384 });
|
|
7126
|
+
} catch {
|
|
7127
|
+
}
|
|
7128
|
+
} catch {
|
|
7129
|
+
}
|
|
7130
|
+
}
|
|
7131
|
+
function traceSummary(event, fields = {}) {
|
|
7132
|
+
trace(event, LEVEL_SUMMARY, fields);
|
|
7133
|
+
}
|
|
7134
|
+
function traceFull(event, fields = {}) {
|
|
7135
|
+
trace(event, LEVEL_FULL, fields);
|
|
7136
|
+
}
|
|
7137
|
+
|
|
7138
|
+
// src/infra/metrics.ts
|
|
7139
|
+
init_esm_shims();
|
|
7140
|
+
|
|
7141
|
+
// src/infra/circuit-breaker.ts
|
|
7142
|
+
init_esm_shims();
|
|
7143
|
+
var CLOSED = "closed";
|
|
7144
|
+
var OPEN = "open";
|
|
7145
|
+
var HALF_OPEN = "half_open";
|
|
7146
|
+
function envInt(name, fallback) {
|
|
7147
|
+
const raw = process.env[name];
|
|
7148
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
7149
|
+
const n = Number(raw);
|
|
7150
|
+
return Number.isFinite(n) ? n : fallback;
|
|
7151
|
+
}
|
|
7152
|
+
var CircuitBreaker = class {
|
|
7153
|
+
constructor(threshold = 5, cooldown = 30) {
|
|
7154
|
+
this.threshold = threshold;
|
|
7155
|
+
this.cooldown = cooldown;
|
|
7156
|
+
}
|
|
7157
|
+
threshold;
|
|
7158
|
+
cooldown;
|
|
7159
|
+
state = CLOSED;
|
|
7160
|
+
failures = 0;
|
|
7161
|
+
openedAt = 0;
|
|
7162
|
+
openCount = 0;
|
|
7163
|
+
shortCircuitCount = 0;
|
|
7164
|
+
get currentState() {
|
|
7165
|
+
return this.state;
|
|
7166
|
+
}
|
|
7167
|
+
allow() {
|
|
7168
|
+
if (this.threshold <= 0) return true;
|
|
7169
|
+
if (this.state === CLOSED) return true;
|
|
7170
|
+
if (this.state === OPEN) {
|
|
7171
|
+
if ((performance.now() - this.openedAt) / 1e3 >= this.cooldown) {
|
|
7172
|
+
this.state = HALF_OPEN;
|
|
7173
|
+
return true;
|
|
7174
|
+
}
|
|
7175
|
+
this.shortCircuitCount += 1;
|
|
7176
|
+
return false;
|
|
7177
|
+
}
|
|
7178
|
+
return true;
|
|
7179
|
+
}
|
|
7180
|
+
recordSuccess() {
|
|
7181
|
+
if (this.threshold <= 0) return;
|
|
7182
|
+
this.state = CLOSED;
|
|
7183
|
+
this.failures = 0;
|
|
7184
|
+
}
|
|
7185
|
+
recordFailure() {
|
|
7186
|
+
if (this.threshold <= 0) return;
|
|
7187
|
+
if (this.state === HALF_OPEN) {
|
|
7188
|
+
this.state = OPEN;
|
|
7189
|
+
this.openedAt = performance.now();
|
|
7190
|
+
this.openCount += 1;
|
|
7191
|
+
return;
|
|
7192
|
+
}
|
|
7193
|
+
this.failures += 1;
|
|
7194
|
+
if (this.failures >= this.threshold) {
|
|
7195
|
+
this.state = OPEN;
|
|
7196
|
+
this.openedAt = performance.now();
|
|
7197
|
+
this.openCount += 1;
|
|
7198
|
+
}
|
|
7199
|
+
}
|
|
7200
|
+
snapshot() {
|
|
7201
|
+
return {
|
|
7202
|
+
state: this.state,
|
|
7203
|
+
failures: this.failures,
|
|
7204
|
+
threshold: this.threshold,
|
|
7205
|
+
cooldown_sec: this.cooldown,
|
|
7206
|
+
open_count: this.openCount,
|
|
7207
|
+
short_circuit_count: this.shortCircuitCount
|
|
7208
|
+
};
|
|
7209
|
+
}
|
|
7210
|
+
reset() {
|
|
7211
|
+
this.state = CLOSED;
|
|
7212
|
+
this.failures = 0;
|
|
7213
|
+
this.openedAt = 0;
|
|
7214
|
+
}
|
|
7215
|
+
};
|
|
7216
|
+
var _breaker = null;
|
|
7217
|
+
function getBreaker() {
|
|
7218
|
+
if (_breaker === null) {
|
|
7219
|
+
_breaker = new CircuitBreaker(
|
|
7220
|
+
envInt("AGENT_MOSS_LLM_CIRCUIT_THRESHOLD", 5),
|
|
7221
|
+
envInt("AGENT_MOSS_LLM_CIRCUIT_COOLDOWN", 30)
|
|
7222
|
+
);
|
|
7223
|
+
}
|
|
7224
|
+
return _breaker;
|
|
7225
|
+
}
|
|
7226
|
+
|
|
7227
|
+
// src/infra/metrics.ts
|
|
7228
|
+
var DEFAULT_BUCKETS = [
|
|
7229
|
+
5e-3,
|
|
7230
|
+
0.01,
|
|
7231
|
+
0.025,
|
|
7232
|
+
0.05,
|
|
7233
|
+
0.1,
|
|
7234
|
+
0.25,
|
|
7235
|
+
0.5,
|
|
7236
|
+
1,
|
|
7237
|
+
2.5,
|
|
7238
|
+
5,
|
|
7239
|
+
10,
|
|
7240
|
+
30,
|
|
7241
|
+
60
|
|
7242
|
+
];
|
|
7243
|
+
var STARTED_AT = Date.now();
|
|
7244
|
+
function escapeLabel(value) {
|
|
7245
|
+
return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
|
|
7246
|
+
}
|
|
7247
|
+
function formatLabels(labels) {
|
|
7248
|
+
if (!labels) return "";
|
|
7249
|
+
const keys = Object.keys(labels).sort();
|
|
7250
|
+
if (!keys.length) return "";
|
|
7251
|
+
return `{${keys.map((k) => `${k}="${escapeLabel(labels[k])}"`).join(",")}}`;
|
|
7252
|
+
}
|
|
7253
|
+
function keyOf(labelnames, labels) {
|
|
7254
|
+
return labelnames.map((k) => String(labels[k] ?? "")).join("");
|
|
7255
|
+
}
|
|
7256
|
+
function decodeKey(labelnames, key) {
|
|
7257
|
+
if (!labelnames.length) return void 0;
|
|
7258
|
+
const parts = key.split("");
|
|
7259
|
+
const out = {};
|
|
7260
|
+
labelnames.forEach((k, i) => {
|
|
7261
|
+
out[k] = parts[i] ?? "";
|
|
7262
|
+
});
|
|
7263
|
+
return out;
|
|
7264
|
+
}
|
|
7265
|
+
var Counter = class {
|
|
7266
|
+
constructor(name, helpText, labelnames = []) {
|
|
7267
|
+
this.name = name;
|
|
7268
|
+
this.helpText = helpText;
|
|
7269
|
+
this.labelnames = labelnames;
|
|
7270
|
+
}
|
|
7271
|
+
name;
|
|
7272
|
+
helpText;
|
|
7273
|
+
labelnames;
|
|
7274
|
+
values = /* @__PURE__ */ new Map();
|
|
7275
|
+
inc(amount = 1, labels = {}) {
|
|
7276
|
+
const k = keyOf(this.labelnames, labels);
|
|
7277
|
+
this.values.set(k, (this.values.get(k) ?? 0) + amount);
|
|
7278
|
+
}
|
|
7279
|
+
render() {
|
|
7280
|
+
const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} counter`];
|
|
7281
|
+
if (!this.values.size) {
|
|
7282
|
+
const empty = this.labelnames.length ? Object.fromEntries(this.labelnames.map((k) => [k, ""])) : void 0;
|
|
7283
|
+
out.push(`${this.name}${formatLabels(empty)} 0`);
|
|
7284
|
+
return out;
|
|
7285
|
+
}
|
|
7286
|
+
for (const [k, v] of this.values) {
|
|
7287
|
+
out.push(`${this.name}${formatLabels(decodeKey(this.labelnames, k))} ${v}`);
|
|
7288
|
+
}
|
|
7289
|
+
return out;
|
|
7290
|
+
}
|
|
7291
|
+
};
|
|
7292
|
+
var Gauge = class {
|
|
7293
|
+
constructor(name, helpText, labelnames = []) {
|
|
7294
|
+
this.name = name;
|
|
7295
|
+
this.helpText = helpText;
|
|
7296
|
+
this.labelnames = labelnames;
|
|
7297
|
+
}
|
|
7298
|
+
name;
|
|
7299
|
+
helpText;
|
|
7300
|
+
labelnames;
|
|
7301
|
+
values = /* @__PURE__ */ new Map();
|
|
7302
|
+
set(value, labels = {}) {
|
|
7303
|
+
this.values.set(keyOf(this.labelnames, labels), Number(value));
|
|
7304
|
+
}
|
|
7305
|
+
clear() {
|
|
7306
|
+
this.values.clear();
|
|
7307
|
+
}
|
|
7308
|
+
render() {
|
|
7309
|
+
const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} gauge`];
|
|
7310
|
+
for (const [k, v] of this.values) {
|
|
7311
|
+
const labels = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : void 0;
|
|
7312
|
+
out.push(`${this.name}${formatLabels(labels)} ${v}`);
|
|
7313
|
+
}
|
|
7314
|
+
return out;
|
|
7315
|
+
}
|
|
7316
|
+
};
|
|
7317
|
+
var Histogram = class {
|
|
7318
|
+
constructor(name, helpText, buckets = DEFAULT_BUCKETS, labelnames = []) {
|
|
7319
|
+
this.name = name;
|
|
7320
|
+
this.helpText = helpText;
|
|
7321
|
+
this.buckets = buckets;
|
|
7322
|
+
this.labelnames = labelnames;
|
|
7323
|
+
}
|
|
7324
|
+
name;
|
|
7325
|
+
helpText;
|
|
7326
|
+
buckets;
|
|
7327
|
+
labelnames;
|
|
7328
|
+
values = /* @__PURE__ */ new Map();
|
|
7329
|
+
observe(value, labels = {}) {
|
|
7330
|
+
const k = keyOf(this.labelnames, labels);
|
|
7331
|
+
let slot = this.values.get(k);
|
|
7332
|
+
if (!slot) {
|
|
7333
|
+
slot = { buckets: this.buckets.map(() => 0), sum: 0, count: 0 };
|
|
7334
|
+
this.values.set(k, slot);
|
|
7335
|
+
}
|
|
7336
|
+
for (let i = 0; i < this.buckets.length; i++) {
|
|
7337
|
+
if (value <= this.buckets[i]) slot.buckets[i] += 1;
|
|
7338
|
+
}
|
|
7339
|
+
slot.sum += value;
|
|
7340
|
+
slot.count += 1;
|
|
7341
|
+
}
|
|
7342
|
+
render() {
|
|
7343
|
+
const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} histogram`];
|
|
7344
|
+
for (const [k, slot] of this.values) {
|
|
7345
|
+
const base = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : {};
|
|
7346
|
+
this.buckets.forEach((bound, i) => {
|
|
7347
|
+
out.push(`${this.name}_bucket${formatLabels({ ...base, le: String(bound) })} ${slot.buckets[i]}`);
|
|
7348
|
+
});
|
|
7349
|
+
out.push(`${this.name}_bucket${formatLabels({ ...base, le: "+Inf" })} ${slot.count}`);
|
|
7350
|
+
out.push(`${this.name}_sum${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.sum}`);
|
|
7351
|
+
out.push(`${this.name}_count${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.count}`);
|
|
7352
|
+
}
|
|
7353
|
+
return out;
|
|
7354
|
+
}
|
|
7355
|
+
};
|
|
7356
|
+
var ANALYZE_TOTAL = new Counter(
|
|
7357
|
+
"agent_moss_analyze_total",
|
|
7358
|
+
"Total analyze requests handled, by decision and risk level.",
|
|
7359
|
+
["decision", "risk_level"]
|
|
7360
|
+
);
|
|
7361
|
+
var ANALYZE_DURATION = new Histogram(
|
|
7362
|
+
"agent_moss_analyze_duration_seconds",
|
|
7363
|
+
"End-to-end analyze duration in seconds.",
|
|
7364
|
+
DEFAULT_BUCKETS,
|
|
7365
|
+
["decision"]
|
|
7366
|
+
);
|
|
7367
|
+
var LAYER_HIT_TOTAL = new Counter(
|
|
7368
|
+
"agent_moss_layer_hit_total",
|
|
7369
|
+
"Number of requests where a given defense layer produced the final verdict.",
|
|
7370
|
+
["layer"]
|
|
7371
|
+
);
|
|
7372
|
+
var REJECTED_TOTAL = new Counter(
|
|
7373
|
+
"agent_moss_rejected_total",
|
|
7374
|
+
"Requests rejected before analysis (concurrency / rate limit / auth).",
|
|
7375
|
+
["reason"]
|
|
7376
|
+
);
|
|
7377
|
+
var LLM_CALLS_TOTAL = new Counter(
|
|
7378
|
+
"agent_moss_llm_calls_total",
|
|
7379
|
+
"LLM API calls, by outcome.",
|
|
7380
|
+
["result"]
|
|
7381
|
+
);
|
|
7382
|
+
var LLM_DURATION = new Histogram(
|
|
7383
|
+
"agent_moss_llm_duration_seconds",
|
|
7384
|
+
"LLM API call duration in seconds.",
|
|
7385
|
+
DEFAULT_BUCKETS,
|
|
7386
|
+
["result"]
|
|
7387
|
+
);
|
|
7388
|
+
var POOL_INFLIGHT = new Gauge(
|
|
7389
|
+
"agent_moss_pool_inflight",
|
|
7390
|
+
"Current in-flight requests per concurrency pool.",
|
|
7391
|
+
["pool"]
|
|
7392
|
+
);
|
|
7393
|
+
var CHAIN_NODES = new Gauge(
|
|
7394
|
+
"agent_moss_chain_nodes",
|
|
7395
|
+
"Number of nodes in the stateful chain timeline.",
|
|
7396
|
+
["agent"]
|
|
7397
|
+
);
|
|
7398
|
+
var CHAIN_DB_BYTES = new Gauge(
|
|
7399
|
+
"agent_moss_chain_db_bytes",
|
|
7400
|
+
"Size of the chain state database in bytes."
|
|
7401
|
+
);
|
|
7402
|
+
var LOOP_LAG = new Gauge(
|
|
7403
|
+
"agent_moss_event_loop_lag_seconds",
|
|
7404
|
+
"Most recent event loop lag sample in seconds."
|
|
7405
|
+
);
|
|
7406
|
+
var LOOP_LAG_MAX = new Gauge(
|
|
7407
|
+
"agent_moss_event_loop_lag_max_seconds",
|
|
7408
|
+
"Maximum event loop lag observed since process start, in seconds."
|
|
7409
|
+
);
|
|
7410
|
+
var UPTIME = new Gauge(
|
|
7411
|
+
"agent_moss_uptime_seconds",
|
|
7412
|
+
"Seconds since process start."
|
|
7413
|
+
);
|
|
7414
|
+
var LLM_CIRCUIT_STATE = new Gauge(
|
|
7415
|
+
"agent_moss_llm_circuit_state",
|
|
7416
|
+
"LLM circuit breaker state (0=closed, 1=open, 2=half_open)."
|
|
7417
|
+
);
|
|
7418
|
+
var LLM_SHORT_CIRCUIT_TOTAL = new Counter(
|
|
7419
|
+
"agent_moss_llm_short_circuit_total",
|
|
7420
|
+
"LLM calls short-circuited by the breaker (no network request made)."
|
|
7421
|
+
);
|
|
7422
|
+
|
|
7423
|
+
// src/engine/llm-analyzer.ts
|
|
7424
|
+
function responseFieldLengths(message) {
|
|
7425
|
+
if (!message || typeof message !== "object") return {};
|
|
7426
|
+
const out = {};
|
|
7427
|
+
for (const [key, value] of Object.entries(message)) {
|
|
7428
|
+
if (value === null || value === void 0 || value === "") continue;
|
|
7429
|
+
if (Array.isArray(value) && value.length === 0) continue;
|
|
7430
|
+
if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) continue;
|
|
7431
|
+
if (typeof value === "boolean") continue;
|
|
7432
|
+
try {
|
|
7433
|
+
out[key] = typeof value === "string" ? value.length : String(JSON.stringify(value)).length;
|
|
7434
|
+
} catch {
|
|
7435
|
+
out[key] = -1;
|
|
7436
|
+
}
|
|
7437
|
+
}
|
|
7438
|
+
return out;
|
|
7439
|
+
}
|
|
6995
7440
|
var llmCache = /* @__PURE__ */ new Map();
|
|
6996
7441
|
var LLM_CACHE_MAX = 200;
|
|
6997
7442
|
async function runLLMAnalysis(input, previous) {
|
|
@@ -7076,7 +7521,23 @@ async function runLLMAnalysis(input, previous) {
|
|
|
7076
7521
|
);
|
|
7077
7522
|
}
|
|
7078
7523
|
logPrompt(prompt, input.aNext, previous.llmLogPath);
|
|
7524
|
+
traceFull("l3.prompt", {
|
|
7525
|
+
phase: "security_judge",
|
|
7526
|
+
model: config.model,
|
|
7527
|
+
base_url: config.baseUrl,
|
|
7528
|
+
action_type: input.aNext.actionType,
|
|
7529
|
+
action_detail: input.aNext.actionDetail,
|
|
7530
|
+
prompt,
|
|
7531
|
+
prompt_chars: prompt.length
|
|
7532
|
+
});
|
|
7079
7533
|
const result = await analyzeWithLLM(prompt, config);
|
|
7534
|
+
traceSummary("l3.verdict", {
|
|
7535
|
+
allowed: result.allowed,
|
|
7536
|
+
risk_level: result.riskLevel,
|
|
7537
|
+
risk_type: result.riskType,
|
|
7538
|
+
reason: result.reason,
|
|
7539
|
+
confidence: result.confidence
|
|
7540
|
+
});
|
|
7080
7541
|
if (llmCache.size >= LLM_CACHE_MAX) {
|
|
7081
7542
|
const firstKey = llmCache.keys().next().value;
|
|
7082
7543
|
if (firstKey) llmCache.delete(firstKey);
|
|
@@ -7218,6 +7679,14 @@ function formatHints(previous) {
|
|
|
7218
7679
|
}
|
|
7219
7680
|
async function analyzeWithLLM(prompt, config) {
|
|
7220
7681
|
console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
|
|
7682
|
+
const _llmStart = performance.now();
|
|
7683
|
+
const _recordLlm = (result) => {
|
|
7684
|
+
try {
|
|
7685
|
+
LLM_CALLS_TOTAL.inc(1, { result });
|
|
7686
|
+
LLM_DURATION.observe(Math.max(0, (performance.now() - _llmStart) / 1e3), { result });
|
|
7687
|
+
} catch {
|
|
7688
|
+
}
|
|
7689
|
+
};
|
|
7221
7690
|
const provider = detectProvider(config.baseUrl, config.provider);
|
|
7222
7691
|
const extraHeaders = getProviderHeaders(provider);
|
|
7223
7692
|
if (Object.keys(extraHeaders).length > 0) {
|
|
@@ -7239,6 +7708,17 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7239
7708
|
console.error(`[AgentMoss] totalTimeout (${timeoutCfg.totalTimeout}s) exceeded, aborting all LLM calls`);
|
|
7240
7709
|
abortController.abort();
|
|
7241
7710
|
}, totalTimeoutMs);
|
|
7711
|
+
const breaker = getBreaker();
|
|
7712
|
+
if (!breaker.allow()) {
|
|
7713
|
+
try {
|
|
7714
|
+
LLM_SHORT_CIRCUIT_TOTAL.inc(1);
|
|
7715
|
+
} catch {
|
|
7716
|
+
}
|
|
7717
|
+
_recordLlm("error");
|
|
7718
|
+
throw new Error(
|
|
7719
|
+
"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"
|
|
7720
|
+
);
|
|
7721
|
+
}
|
|
7242
7722
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
7243
7723
|
if (abortController.signal.aborted) {
|
|
7244
7724
|
break;
|
|
@@ -7252,22 +7732,49 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7252
7732
|
{ role: "system", content: "\u53EA\u8F93\u51FA\u7EAF JSON\uFF0C\u4E0D\u8981\u5305\u542B markdown \u6807\u8BB0\u3001\u4EE3\u7801\u5757\u6216\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002" },
|
|
7253
7733
|
{ role: "user", content: prompt }
|
|
7254
7734
|
],
|
|
7255
|
-
signal: abortController.signal
|
|
7735
|
+
signal: abortController.signal,
|
|
7736
|
+
// 私有化网关的额外参数(关思考等)原样透传;空则不传。
|
|
7737
|
+
...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
|
|
7256
7738
|
});
|
|
7257
7739
|
const message = response.choices[0]?.message;
|
|
7258
7740
|
const content = message?.content ?? "";
|
|
7259
7741
|
const finishReason = response.choices[0]?.finish_reason;
|
|
7260
|
-
const
|
|
7742
|
+
const fieldLengths = responseFieldLengths(message);
|
|
7261
7743
|
const usage = response.usage;
|
|
7262
7744
|
if (!content) {
|
|
7263
|
-
const detail = `model=${response.model || config.model} finish_reason=${finishReason}
|
|
7745
|
+
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 ?? "?"}`;
|
|
7746
|
+
traceFull("l3.empty_response", {
|
|
7747
|
+
model: response.model || config.model,
|
|
7748
|
+
finish_reason: finishReason,
|
|
7749
|
+
message,
|
|
7750
|
+
prompt_tokens: usage?.prompt_tokens ?? 0,
|
|
7751
|
+
completion_tokens: usage?.completion_tokens ?? 0
|
|
7752
|
+
});
|
|
7753
|
+
let fullMessage = "<empty>";
|
|
7754
|
+
try {
|
|
7755
|
+
fullMessage = JSON.stringify(message ?? {});
|
|
7756
|
+
if (fullMessage.length > 8e3) {
|
|
7757
|
+
fullMessage = `${fullMessage.slice(0, 8e3)}...[truncated ${fullMessage.length} chars]`;
|
|
7758
|
+
}
|
|
7759
|
+
} catch {
|
|
7760
|
+
fullMessage = "<\u65E0\u6CD5\u5E8F\u5217\u5316>";
|
|
7761
|
+
}
|
|
7264
7762
|
if (finishReason === "length") {
|
|
7265
|
-
console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
|
|
7763
|
+
console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
|
|
7266
7764
|
throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
|
|
7267
7765
|
}
|
|
7268
|
-
console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
|
|
7766
|
+
console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
|
|
7767
|
+
_recordLlm("empty");
|
|
7269
7768
|
throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
|
|
7270
7769
|
}
|
|
7770
|
+
traceFull("l3.response", {
|
|
7771
|
+
phase: "security_judge",
|
|
7772
|
+
attempt: attempt + 1,
|
|
7773
|
+
model: response.model || config.model,
|
|
7774
|
+
content,
|
|
7775
|
+
prompt_tokens: usage?.prompt_tokens ?? 0,
|
|
7776
|
+
completion_tokens: usage?.completion_tokens ?? 0
|
|
7777
|
+
});
|
|
7271
7778
|
console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
|
|
7272
7779
|
let jsonStr = content.trim();
|
|
7273
7780
|
if (jsonStr.startsWith("```")) {
|
|
@@ -7298,6 +7805,8 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7298
7805
|
clearTimeout(totalTimeoutTimer);
|
|
7299
7806
|
const riskLevel = parsed.riskLevel ?? parsed.risk_level;
|
|
7300
7807
|
const riskType = parsed.riskType ?? parsed.risk_type;
|
|
7808
|
+
breaker.recordSuccess();
|
|
7809
|
+
_recordLlm("success");
|
|
7301
7810
|
return {
|
|
7302
7811
|
allowed: parsed.allowed !== false,
|
|
7303
7812
|
reason: parsed.reason || "LLM \u5206\u6790\u5B8C\u6210",
|
|
@@ -7308,6 +7817,7 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7308
7817
|
violatedLayers: ["L3.1"]
|
|
7309
7818
|
};
|
|
7310
7819
|
} catch (err) {
|
|
7820
|
+
breaker.recordFailure();
|
|
7311
7821
|
if (abortController.signal.aborted) {
|
|
7312
7822
|
console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
|
|
7313
7823
|
break;
|
|
@@ -7368,8 +7878,8 @@ function uuid() {
|
|
|
7368
7878
|
var BrainRuleStore = class {
|
|
7369
7879
|
path;
|
|
7370
7880
|
data;
|
|
7371
|
-
constructor(
|
|
7372
|
-
this.path =
|
|
7881
|
+
constructor(path6) {
|
|
7882
|
+
this.path = path6 || getRulesPath();
|
|
7373
7883
|
this.data = this.load();
|
|
7374
7884
|
}
|
|
7375
7885
|
load() {
|
|
@@ -7815,10 +8325,10 @@ ${reason.slice(0, 500)}
|
|
|
7815
8325
|
const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
|
|
7816
8326
|
let mm;
|
|
7817
8327
|
while ((mm = pathRe.exec(src)) !== null) {
|
|
7818
|
-
const
|
|
7819
|
-
if (
|
|
7820
|
-
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(
|
|
7821
|
-
const gen = this.generalizePath(
|
|
8328
|
+
const path6 = mm[1];
|
|
8329
|
+
if (path6.split("/").length < 3) continue;
|
|
8330
|
+
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path6)) continue;
|
|
8331
|
+
const gen = this.generalizePath(path6);
|
|
7822
8332
|
if (seen.has(gen)) continue;
|
|
7823
8333
|
seen.add(gen);
|
|
7824
8334
|
patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
|
|
@@ -7837,8 +8347,8 @@ ${reason.slice(0, 500)}
|
|
|
7837
8347
|
}
|
|
7838
8348
|
return false;
|
|
7839
8349
|
}
|
|
7840
|
-
generalizePath(
|
|
7841
|
-
const p =
|
|
8350
|
+
generalizePath(path6) {
|
|
8351
|
+
const p = path6.toLowerCase();
|
|
7842
8352
|
if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
|
|
7843
8353
|
return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
|
|
7844
8354
|
}
|
|
@@ -8397,38 +8907,38 @@ function labelEvent(actionDetail) {
|
|
|
8397
8907
|
}
|
|
8398
8908
|
return hits;
|
|
8399
8909
|
}
|
|
8400
|
-
function evaluateLTL(formula,
|
|
8910
|
+
function evaluateLTL(formula, trace2, pos) {
|
|
8401
8911
|
const op = formula[0];
|
|
8402
8912
|
switch (op) {
|
|
8403
8913
|
case "ap":
|
|
8404
|
-
return
|
|
8914
|
+
return trace2[pos].has(formula[1]);
|
|
8405
8915
|
case "!":
|
|
8406
|
-
return !evaluateLTL(formula[1],
|
|
8916
|
+
return !evaluateLTL(formula[1], trace2, pos);
|
|
8407
8917
|
case "&":
|
|
8408
|
-
return evaluateLTL(formula[1],
|
|
8918
|
+
return evaluateLTL(formula[1], trace2, pos) && evaluateLTL(formula[2], trace2, pos);
|
|
8409
8919
|
case "|":
|
|
8410
|
-
return evaluateLTL(formula[1],
|
|
8920
|
+
return evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
|
|
8411
8921
|
case "->":
|
|
8412
|
-
return !evaluateLTL(formula[1],
|
|
8922
|
+
return !evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
|
|
8413
8923
|
case "X":
|
|
8414
|
-
return pos + 1 <
|
|
8924
|
+
return pos + 1 < trace2.length && evaluateLTL(formula[1], trace2, pos + 1);
|
|
8415
8925
|
case "G": {
|
|
8416
|
-
for (let j = pos; j <
|
|
8417
|
-
if (!evaluateLTL(formula[1],
|
|
8926
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
8927
|
+
if (!evaluateLTL(formula[1], trace2, j)) return false;
|
|
8418
8928
|
}
|
|
8419
8929
|
return true;
|
|
8420
8930
|
}
|
|
8421
8931
|
case "F": {
|
|
8422
|
-
for (let j = pos; j <
|
|
8423
|
-
if (evaluateLTL(formula[1],
|
|
8932
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
8933
|
+
if (evaluateLTL(formula[1], trace2, j)) return true;
|
|
8424
8934
|
}
|
|
8425
8935
|
return false;
|
|
8426
8936
|
}
|
|
8427
8937
|
case "U": {
|
|
8428
|
-
for (let j = pos; j <
|
|
8429
|
-
if (evaluateLTL(formula[2],
|
|
8938
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
8939
|
+
if (evaluateLTL(formula[2], trace2, j)) {
|
|
8430
8940
|
for (let k = pos; k < j; k++) {
|
|
8431
|
-
if (!evaluateLTL(formula[1],
|
|
8941
|
+
if (!evaluateLTL(formula[1], trace2, k)) return false;
|
|
8432
8942
|
}
|
|
8433
8943
|
return true;
|
|
8434
8944
|
}
|
|
@@ -8457,11 +8967,11 @@ function checkMCRules(graph) {
|
|
|
8457
8967
|
const mc = loadMC();
|
|
8458
8968
|
const rules = mc.rules || [];
|
|
8459
8969
|
if (rules.length === 0) return violations;
|
|
8460
|
-
const
|
|
8970
|
+
const trace2 = nodes.map((n) => labelEvent(n.actionDetail));
|
|
8461
8971
|
const witnessMode = graph.witnessIdx !== void 0;
|
|
8462
8972
|
for (const rule of rules) {
|
|
8463
8973
|
if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
|
|
8464
|
-
if (ruleViolates(rule,
|
|
8974
|
+
if (ruleViolates(rule, trace2, witnessMode)) {
|
|
8465
8975
|
violations.push({
|
|
8466
8976
|
propertyId: String(rule.id || "mc-ltl"),
|
|
8467
8977
|
reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
|
|
@@ -8633,12 +9143,12 @@ function allNodesFlat(mg) {
|
|
|
8633
9143
|
// src/engine/formal-engine/properties.ts
|
|
8634
9144
|
init_esm_shims();
|
|
8635
9145
|
init_rules_loader();
|
|
8636
|
-
function graphFromPath(nodes,
|
|
9146
|
+
function graphFromPath(nodes, path6, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
|
|
8637
9147
|
const byKey = /* @__PURE__ */ new Map();
|
|
8638
9148
|
for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
|
|
8639
9149
|
const gNodes = [];
|
|
8640
9150
|
const gEdges = [];
|
|
8641
|
-
for (const item of
|
|
9151
|
+
for (const item of path6) {
|
|
8642
9152
|
const n = byKey.get(`${item.sessionId}#${item.seq}`);
|
|
8643
9153
|
gNodes.push({
|
|
8644
9154
|
session_id: item.sessionId,
|
|
@@ -8707,22 +9217,22 @@ function checkCrossSessionChain(graph) {
|
|
|
8707
9217
|
if (witness !== void 0) {
|
|
8708
9218
|
if (nodes[witness].stage !== stages[stages.length - 1]) continue;
|
|
8709
9219
|
let matched = 0;
|
|
8710
|
-
const
|
|
9220
|
+
const path6 = [];
|
|
8711
9221
|
for (let k = 0; k < witness; k++) {
|
|
8712
9222
|
const n = nodes[k];
|
|
8713
9223
|
if (matched < stages.length - 1 && n.stage === stages[matched]) {
|
|
8714
9224
|
matched += 1;
|
|
8715
|
-
|
|
9225
|
+
path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
8716
9226
|
}
|
|
8717
9227
|
}
|
|
8718
9228
|
if (matched < stages.length - 1) continue;
|
|
8719
|
-
|
|
9229
|
+
path6.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
|
|
8720
9230
|
violations.push({
|
|
8721
9231
|
propertyId: "cross-" + chain.id,
|
|
8722
9232
|
reason: chain.reason,
|
|
8723
9233
|
riskLevel: chain.riskLevel,
|
|
8724
|
-
path:
|
|
8725
|
-
graph: graphFromPath(nodes,
|
|
9234
|
+
path: path6,
|
|
9235
|
+
graph: graphFromPath(nodes, path6, "next", {
|
|
8726
9236
|
property_id: "cross-" + chain.id,
|
|
8727
9237
|
property_short: "P1",
|
|
8728
9238
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -8732,11 +9242,11 @@ function checkCrossSessionChain(graph) {
|
|
|
8732
9242
|
} else {
|
|
8733
9243
|
let matched = 0;
|
|
8734
9244
|
let stageIdx = 0;
|
|
8735
|
-
const
|
|
9245
|
+
const path6 = [];
|
|
8736
9246
|
for (const n of nodes) {
|
|
8737
9247
|
if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
|
|
8738
9248
|
matched += 1;
|
|
8739
|
-
|
|
9249
|
+
path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
8740
9250
|
stageIdx += 1;
|
|
8741
9251
|
if (matched >= stages.length) break;
|
|
8742
9252
|
}
|
|
@@ -8746,8 +9256,8 @@ function checkCrossSessionChain(graph) {
|
|
|
8746
9256
|
propertyId: "cross-" + chain.id,
|
|
8747
9257
|
reason: chain.reason,
|
|
8748
9258
|
riskLevel: chain.riskLevel,
|
|
8749
|
-
path:
|
|
8750
|
-
graph: graphFromPath(nodes,
|
|
9259
|
+
path: path6,
|
|
9260
|
+
graph: graphFromPath(nodes, path6, "next", {
|
|
8751
9261
|
property_id: "cross-" + chain.id,
|
|
8752
9262
|
property_short: "P1",
|
|
8753
9263
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -8794,7 +9304,7 @@ function checkSensitiveDataFlow(graph) {
|
|
|
8794
9304
|
}
|
|
8795
9305
|
}
|
|
8796
9306
|
}
|
|
8797
|
-
const
|
|
9307
|
+
const tracePath2 = (idx) => {
|
|
8798
9308
|
const chain = [idx];
|
|
8799
9309
|
const seen = /* @__PURE__ */ new Set([idx]);
|
|
8800
9310
|
while (true) {
|
|
@@ -8853,7 +9363,7 @@ function checkSensitiveDataFlow(graph) {
|
|
|
8853
9363
|
for (const i of candidates) {
|
|
8854
9364
|
const n = nodes[i];
|
|
8855
9365
|
if (tainted.has(i) && EXFIL_RE.test(n.actionDetail)) {
|
|
8856
|
-
const chain =
|
|
9366
|
+
const chain = tracePath2(i);
|
|
8857
9367
|
violations.push({
|
|
8858
9368
|
propertyId: "sensitive-data-flow",
|
|
8859
9369
|
reason: `\u654F\u611F\u6570\u636E\u4F20\u64AD\u5916\u4F20\uFF1A${tainted.get(i).source} \u2192 ${n.sessionId}#${n.seq} \u7ECF\u5171\u4EAB\u8F7D\u4F53\u5916\u53D1`,
|
|
@@ -8976,7 +9486,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
8976
9486
|
if (candidates.length > 0) {
|
|
8977
9487
|
const pre = nodes[candidates[candidates.length - 1]];
|
|
8978
9488
|
const post = nodes[firstEv];
|
|
8979
|
-
const
|
|
9489
|
+
const path6 = [
|
|
8980
9490
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
8981
9491
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
8982
9492
|
];
|
|
@@ -8984,8 +9494,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
8984
9494
|
propertyId: "no-exfil-after-privesc",
|
|
8985
9495
|
reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
|
|
8986
9496
|
riskLevel: "critical",
|
|
8987
|
-
path:
|
|
8988
|
-
graph: graphFromPath(nodes,
|
|
9497
|
+
path: path6,
|
|
9498
|
+
graph: graphFromPath(nodes, path6, "next", {
|
|
8989
9499
|
property_id: "no-exfil-after-privesc",
|
|
8990
9500
|
property_short: "P4",
|
|
8991
9501
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9002,7 +9512,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
9002
9512
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
9003
9513
|
if (!isExfilNode(nodes[j])) continue;
|
|
9004
9514
|
if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
|
|
9005
|
-
const
|
|
9515
|
+
const path6 = [
|
|
9006
9516
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
9007
9517
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
9008
9518
|
];
|
|
@@ -9010,8 +9520,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
9010
9520
|
propertyId: "no-exfil-after-privesc",
|
|
9011
9521
|
reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
|
|
9012
9522
|
riskLevel: "critical",
|
|
9013
|
-
path:
|
|
9014
|
-
graph: graphFromPath(nodes,
|
|
9523
|
+
path: path6,
|
|
9524
|
+
graph: graphFromPath(nodes, path6, "next", {
|
|
9015
9525
|
property_id: "no-exfil-after-privesc",
|
|
9016
9526
|
property_short: "P4",
|
|
9017
9527
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9043,7 +9553,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9043
9553
|
}
|
|
9044
9554
|
if (pre) {
|
|
9045
9555
|
const post = nodes[firstEv];
|
|
9046
|
-
const
|
|
9556
|
+
const path6 = [
|
|
9047
9557
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
9048
9558
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
9049
9559
|
];
|
|
@@ -9051,8 +9561,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9051
9561
|
propertyId: "no-exfil-after-credential",
|
|
9052
9562
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
9053
9563
|
riskLevel: "critical",
|
|
9054
|
-
path:
|
|
9055
|
-
graph: graphFromPath(nodes,
|
|
9564
|
+
path: path6,
|
|
9565
|
+
graph: graphFromPath(nodes, path6, "data", {
|
|
9056
9566
|
property_id: "no-exfil-after-credential",
|
|
9057
9567
|
property_short: "P5",
|
|
9058
9568
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9068,7 +9578,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9068
9578
|
if (!isCredNode(nodes[i])) continue;
|
|
9069
9579
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
9070
9580
|
if (isExfilNode(nodes[j])) {
|
|
9071
|
-
const
|
|
9581
|
+
const path6 = [
|
|
9072
9582
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
9073
9583
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
9074
9584
|
];
|
|
@@ -9076,8 +9586,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9076
9586
|
propertyId: "no-exfil-after-credential",
|
|
9077
9587
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
9078
9588
|
riskLevel: "critical",
|
|
9079
|
-
path:
|
|
9080
|
-
graph: graphFromPath(nodes,
|
|
9589
|
+
path: path6,
|
|
9590
|
+
graph: graphFromPath(nodes, path6, "data", {
|
|
9081
9591
|
property_id: "no-exfil-after-credential",
|
|
9082
9592
|
property_short: "P5",
|
|
9083
9593
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9241,13 +9751,13 @@ function checkSensitiveDataAggregation(graph) {
|
|
|
9241
9751
|
if (!isExfilNode(n)) continue;
|
|
9242
9752
|
const srcs = sourcesFor(i);
|
|
9243
9753
|
if (srcs.size >= 2) {
|
|
9244
|
-
const
|
|
9754
|
+
const path6 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
9245
9755
|
violations.push({
|
|
9246
9756
|
propertyId: "sensitive-data-aggregation",
|
|
9247
9757
|
reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
|
|
9248
9758
|
riskLevel: "critical",
|
|
9249
|
-
path:
|
|
9250
|
-
graph: graphFromPath(nodes,
|
|
9759
|
+
path: path6,
|
|
9760
|
+
graph: graphFromPath(nodes, path6, "next", {
|
|
9251
9761
|
property_id: "sensitive-data-aggregation",
|
|
9252
9762
|
property_short: "P8",
|
|
9253
9763
|
property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
|
|
@@ -9337,9 +9847,9 @@ init_rules_loader();
|
|
|
9337
9847
|
|
|
9338
9848
|
// src/engine/formal-engine/chain_state.ts
|
|
9339
9849
|
init_esm_shims();
|
|
9340
|
-
import * as
|
|
9850
|
+
import * as fs5 from "fs";
|
|
9341
9851
|
import * as os2 from "os";
|
|
9342
|
-
import * as
|
|
9852
|
+
import * as path5 from "path";
|
|
9343
9853
|
import { createHash as createHash2 } from "crypto";
|
|
9344
9854
|
|
|
9345
9855
|
// src/engine/coordinator.ts
|
|
@@ -9431,6 +9941,14 @@ var formalEngine = new FormalEngine();
|
|
|
9431
9941
|
async function runAnalysis(input) {
|
|
9432
9942
|
const observedFormalLayers = [];
|
|
9433
9943
|
const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
|
|
9944
|
+
if (heuristicResult) {
|
|
9945
|
+
traceSummary("l1.result", {
|
|
9946
|
+
hit: !heuristicResult.allowed,
|
|
9947
|
+
risk_level: heuristicResult.riskLevel,
|
|
9948
|
+
risk_type: heuristicResult.riskType,
|
|
9949
|
+
reason: heuristicResult.reason
|
|
9950
|
+
});
|
|
9951
|
+
}
|
|
9434
9952
|
const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
|
|
9435
9953
|
const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
|
|
9436
9954
|
if (heuristicResult && !heuristicResult.allowed) {
|
|
@@ -9574,6 +10092,14 @@ async function runAnalysis(input) {
|
|
|
9574
10092
|
}
|
|
9575
10093
|
}
|
|
9576
10094
|
const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
|
|
10095
|
+
if (logicResult) {
|
|
10096
|
+
traceSummary("l2.result", {
|
|
10097
|
+
hit: !logicResult.allowed,
|
|
10098
|
+
risk_level: logicResult.riskLevel,
|
|
10099
|
+
risk_type: logicResult.riskType,
|
|
10100
|
+
reason: logicResult.reason
|
|
10101
|
+
});
|
|
10102
|
+
}
|
|
9577
10103
|
const l1FileAccessHit = !!(heuristicResult && !heuristicResult.allowed && heuristicResult.riskType === "file_access");
|
|
9578
10104
|
const effectiveResult = logicResult && !logicResult.allowed ? logicResult : l1FileAccessHit ? heuristicResult : null;
|
|
9579
10105
|
if (effectiveResult) {
|