@kenhkl/agent-moss 0.17.20 → 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 -227
- package/dist/engine/coordinator.js +642 -132
- package/dist/server.js +1004 -190
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -39,10 +39,6 @@ function getRulesRoot() {
|
|
|
39
39
|
const raw = (process.env[ENV_RULES_ROOT] ?? "").trim();
|
|
40
40
|
return raw ? raw : null;
|
|
41
41
|
}
|
|
42
|
-
function isRoot() {
|
|
43
|
-
const getuid = process.getuid;
|
|
44
|
-
return typeof getuid === "function" && getuid() === 0;
|
|
45
|
-
}
|
|
46
42
|
function resolveExplicitOwnerHome() {
|
|
47
43
|
for (const name of [process.env.SUDO_USER, process.env.LOGNAME, process.env.USER]) {
|
|
48
44
|
if (name && name !== "root" && name !== "") {
|
|
@@ -70,12 +66,6 @@ function listOwnerHomes() {
|
|
|
70
66
|
}
|
|
71
67
|
return homes;
|
|
72
68
|
}
|
|
73
|
-
function resolveOwnerHome() {
|
|
74
|
-
const explicit = resolveExplicitOwnerHome();
|
|
75
|
-
if (explicit) return explicit;
|
|
76
|
-
const owners = listOwnerHomes();
|
|
77
|
-
return owners.length > 0 ? owners[0] : null;
|
|
78
|
-
}
|
|
79
69
|
function homeOf(name) {
|
|
80
70
|
try {
|
|
81
71
|
const passwd = readFileSync("/etc/passwd", "utf-8");
|
|
@@ -93,12 +83,6 @@ function homeOf(name) {
|
|
|
93
83
|
function getDataRoot() {
|
|
94
84
|
const envPath = process.env[ENV_DATA_ROOT];
|
|
95
85
|
if (envPath) return envPath;
|
|
96
|
-
if (isRoot()) {
|
|
97
|
-
const ownerHome = resolveOwnerHome();
|
|
98
|
-
if (ownerHome) {
|
|
99
|
-
return join(ownerHome, ".config", "agentmoss");
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
86
|
return DEFAULT_DATA_ROOT;
|
|
103
87
|
}
|
|
104
88
|
function getInstance() {
|
|
@@ -423,22 +407,22 @@ function loadToolRegistry() {
|
|
|
423
407
|
data.tools = tools;
|
|
424
408
|
return data;
|
|
425
409
|
}
|
|
426
|
-
function scanStructEntry(cat, value,
|
|
410
|
+
function scanStructEntry(cat, value, path7) {
|
|
427
411
|
if (cat === "skills") {
|
|
428
412
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
429
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
413
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
430
414
|
return null;
|
|
431
415
|
}
|
|
432
416
|
const out = {};
|
|
433
417
|
for (const [skCat, skills] of Object.entries(value)) {
|
|
434
418
|
if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
|
|
435
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
419
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \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`);
|
|
436
420
|
continue;
|
|
437
421
|
}
|
|
438
422
|
const keep = {};
|
|
439
423
|
for (const [name, kws] of Object.entries(skills)) {
|
|
440
424
|
if (Array.isArray(kws)) keep[name] = kws;
|
|
441
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
425
|
+
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
442
426
|
}
|
|
443
427
|
if (Object.keys(keep).length > 0) out[skCat] = keep;
|
|
444
428
|
}
|
|
@@ -446,37 +430,37 @@ function scanStructEntry(cat, value, path6) {
|
|
|
446
430
|
}
|
|
447
431
|
if (cat === "ltl_rules") {
|
|
448
432
|
if (!Array.isArray(value)) {
|
|
449
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
433
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
450
434
|
return null;
|
|
451
435
|
}
|
|
452
436
|
const keep = value.filter((r) => r && typeof r === "object" && r.id);
|
|
453
437
|
if (keep.length !== value.length) {
|
|
454
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
438
|
+
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
455
439
|
}
|
|
456
440
|
return keep.length > 0 ? keep : null;
|
|
457
441
|
}
|
|
458
442
|
if (cat === "tools") {
|
|
459
443
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
460
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
444
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
461
445
|
return null;
|
|
462
446
|
}
|
|
463
447
|
const keep = {};
|
|
464
448
|
for (const [k, v] of Object.entries(value)) {
|
|
465
449
|
if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
|
|
466
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
450
|
+
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
467
451
|
}
|
|
468
452
|
return Object.keys(keep).length > 0 ? keep : null;
|
|
469
453
|
}
|
|
470
454
|
return null;
|
|
471
455
|
}
|
|
472
|
-
function scanRulesFile(
|
|
456
|
+
function scanRulesFile(path7, kind) {
|
|
473
457
|
const out = {};
|
|
474
458
|
const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
|
|
475
459
|
let parsed;
|
|
476
460
|
try {
|
|
477
|
-
parsed = JSON.parse(readFileSync2(
|
|
461
|
+
parsed = JSON.parse(readFileSync2(path7, "utf-8"));
|
|
478
462
|
} catch (e) {
|
|
479
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
463
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
|
|
480
464
|
return out;
|
|
481
465
|
}
|
|
482
466
|
const classifyFlat = (r) => {
|
|
@@ -500,44 +484,44 @@ function scanRulesFile(path6, kind) {
|
|
|
500
484
|
}
|
|
501
485
|
if (flatBad > 0) {
|
|
502
486
|
console.warn(
|
|
503
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
487
|
+
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \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`
|
|
504
488
|
);
|
|
505
489
|
}
|
|
506
490
|
} else {
|
|
507
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
491
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
|
|
508
492
|
return out;
|
|
509
493
|
}
|
|
510
494
|
for (const [cat, rules] of pairs) {
|
|
511
495
|
if (String(cat).startsWith("_")) continue;
|
|
512
496
|
if (STRUCT_KEYS.includes(cat)) {
|
|
513
|
-
const got = scanStructEntry(cat, rules,
|
|
497
|
+
const got = scanStructEntry(cat, rules, path7);
|
|
514
498
|
if (got !== null) out[cat] = got;
|
|
515
499
|
continue;
|
|
516
500
|
}
|
|
517
501
|
const required = EXTRA_CATEGORIES[cat];
|
|
518
502
|
if (!required) {
|
|
519
503
|
console.warn(
|
|
520
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
504
|
+
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \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`
|
|
521
505
|
);
|
|
522
506
|
continue;
|
|
523
507
|
}
|
|
524
508
|
if (rules && typeof rules === "object" && !Array.isArray(rules)) {
|
|
525
509
|
console.error(
|
|
526
|
-
`[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${
|
|
510
|
+
`[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path7} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
|
|
527
511
|
\u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
|
|
528
512
|
\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`
|
|
529
513
|
);
|
|
530
514
|
continue;
|
|
531
515
|
}
|
|
532
516
|
if (!Array.isArray(rules)) {
|
|
533
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
517
|
+
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
|
|
534
518
|
continue;
|
|
535
519
|
}
|
|
536
520
|
const items = [];
|
|
537
521
|
for (const r of rules) {
|
|
538
522
|
if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
|
|
539
523
|
console.warn(
|
|
540
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
524
|
+
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
|
|
541
525
|
);
|
|
542
526
|
continue;
|
|
543
527
|
}
|
|
@@ -547,7 +531,7 @@ function scanRulesFile(path6, kind) {
|
|
|
547
531
|
}
|
|
548
532
|
if (Object.keys(out).length > 0) {
|
|
549
533
|
console.info(
|
|
550
|
-
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${
|
|
534
|
+
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path7}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
|
|
551
535
|
);
|
|
552
536
|
}
|
|
553
537
|
return out;
|
|
@@ -817,10 +801,10 @@ function readExplicitToken() {
|
|
|
817
801
|
if (tok) return tok;
|
|
818
802
|
const fdTok = readFdToken();
|
|
819
803
|
if (fdTok) return fdTok;
|
|
820
|
-
const
|
|
821
|
-
if (
|
|
804
|
+
const path7 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
|
|
805
|
+
if (path7) {
|
|
822
806
|
try {
|
|
823
|
-
return readFileSync4(
|
|
807
|
+
return readFileSync4(path7, "utf-8").trim();
|
|
824
808
|
} catch {
|
|
825
809
|
return "";
|
|
826
810
|
}
|
|
@@ -828,23 +812,23 @@ function readExplicitToken() {
|
|
|
828
812
|
return "";
|
|
829
813
|
}
|
|
830
814
|
function ensureAutoToken() {
|
|
831
|
-
const
|
|
815
|
+
const path7 = autoTokenPath();
|
|
832
816
|
try {
|
|
833
|
-
if (existsSync3(
|
|
834
|
-
const tok2 = readFileSync4(
|
|
817
|
+
if (existsSync3(path7) && !lstatSync(path7).isSymbolicLink()) {
|
|
818
|
+
const tok2 = readFileSync4(path7, "utf-8").trim();
|
|
835
819
|
if (tok2) {
|
|
836
820
|
try {
|
|
837
|
-
chmodSync(
|
|
821
|
+
chmodSync(path7, 384);
|
|
838
822
|
} catch {
|
|
839
823
|
}
|
|
840
824
|
return tok2;
|
|
841
825
|
}
|
|
842
826
|
}
|
|
843
827
|
const tok = randomBytes(32).toString("base64url");
|
|
844
|
-
ensurePrivateDir(dirname2(
|
|
845
|
-
if (!writePrivateText(
|
|
828
|
+
ensurePrivateDir(dirname2(path7));
|
|
829
|
+
if (!writePrivateText(path7, tok + "\n")) return "";
|
|
846
830
|
console.warn(
|
|
847
|
-
`[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${
|
|
831
|
+
`[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${path7}\uFF080600\uFF09\u3002\u5BA2\u6237\u7AEF\u9700\u5E26 \`Authorization: Bearer <token>\`\uFF1B\u67E5\u770B\uFF1Acat ${path7}\uFF1B\u5982\u9700\u5173\u95ED\u9274\u6743\uFF1AAGENT_MOSS_AUTH_MODE=off`
|
|
848
832
|
);
|
|
849
833
|
return tok;
|
|
850
834
|
} catch (e) {
|
|
@@ -917,16 +901,16 @@ function constEq(a, b) {
|
|
|
917
901
|
if (ba.length !== bb.length) return false;
|
|
918
902
|
return timingSafeEqual(ba, bb);
|
|
919
903
|
}
|
|
920
|
-
function checkRequestAuth(headers,
|
|
904
|
+
function checkRequestAuth(headers, path7) {
|
|
921
905
|
if (authMode() === AUTH_MODE_OFF) return [true, ""];
|
|
922
|
-
const isHealth = HEALTH_PATHS.includes(
|
|
906
|
+
const isHealth = HEALTH_PATHS.includes(path7.replace(/\/+$/, ""));
|
|
923
907
|
const [gt0, agents, err] = resolveAuth();
|
|
924
908
|
if (err) return isHealth ? [true, ""] : [false, ""];
|
|
925
909
|
if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
|
|
926
910
|
if (isHealth) return [true, ""];
|
|
927
911
|
const tok = bearer(headers);
|
|
928
912
|
if (!tok) return [false, ""];
|
|
929
|
-
if (
|
|
913
|
+
if (path7.startsWith("/console/api")) {
|
|
930
914
|
const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
|
|
931
915
|
if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
|
|
932
916
|
}
|
|
@@ -945,8 +929,8 @@ function bindAgent(principal, agentId) {
|
|
|
945
929
|
if (!agentId) return [true, bound];
|
|
946
930
|
return [bound === agentId, bound];
|
|
947
931
|
}
|
|
948
|
-
function principalOf(headers,
|
|
949
|
-
const [ok, principal] = checkRequestAuth(headers,
|
|
932
|
+
function principalOf(headers, path7 = "") {
|
|
933
|
+
const [ok, principal] = checkRequestAuth(headers, path7);
|
|
950
934
|
return ok ? principal : "";
|
|
951
935
|
}
|
|
952
936
|
function principalHash(principal) {
|
|
@@ -1204,11 +1188,11 @@ function errorDetailMode() {
|
|
|
1204
1188
|
function maxBodyBytes() {
|
|
1205
1189
|
return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
|
|
1206
1190
|
}
|
|
1207
|
-
function poolOf(
|
|
1208
|
-
if (
|
|
1209
|
-
if (
|
|
1210
|
-
if (
|
|
1211
|
-
if (
|
|
1191
|
+
function poolOf(path7) {
|
|
1192
|
+
if (path7 === "/api/v1/analyze" || path7.startsWith("/api/v1/analyze/")) return "biz";
|
|
1193
|
+
if (path7 === "/api/v1/review" || path7.startsWith("/api/v1/review/")) return "review";
|
|
1194
|
+
if (path7 === "/console" || path7.startsWith("/console/") || path7.startsWith("/api/v1/brain")) return "ops";
|
|
1195
|
+
if (path7 === "/api/v1/health") return "health";
|
|
1212
1196
|
return "other";
|
|
1213
1197
|
}
|
|
1214
1198
|
function poolLimit(name) {
|
|
@@ -1521,7 +1505,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
|
|
|
1521
1505
|
os: String(sp.os || "linux").toLowerCase()
|
|
1522
1506
|
}));
|
|
1523
1507
|
}
|
|
1524
|
-
function _scopeOf(os4,
|
|
1508
|
+
function _scopeOf(os4, path7) {
|
|
1525
1509
|
if (!_scopeIndex) {
|
|
1526
1510
|
_scopeIndex = /* @__PURE__ */ new Map();
|
|
1527
1511
|
for (const sp of loadL1().sensitive_path_access || []) {
|
|
@@ -1529,7 +1513,7 @@ function _scopeOf(os4, path6) {
|
|
|
1529
1513
|
if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
|
|
1530
1514
|
}
|
|
1531
1515
|
}
|
|
1532
|
-
return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${
|
|
1516
|
+
return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path7}`) || "root";
|
|
1533
1517
|
}
|
|
1534
1518
|
function getSensitivePathsForOs(osType) {
|
|
1535
1519
|
const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
|
|
@@ -1880,17 +1864,17 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1880
1864
|
return null;
|
|
1881
1865
|
}
|
|
1882
1866
|
const unreadPaths = [];
|
|
1883
|
-
for (const
|
|
1867
|
+
for (const path7 of filteredPaths) {
|
|
1884
1868
|
const hasRead = [...historyReadPaths].some(
|
|
1885
|
-
(rp) =>
|
|
1869
|
+
(rp) => path7 === rp || path7.startsWith(rp) || rp.startsWith(path7)
|
|
1886
1870
|
);
|
|
1887
1871
|
if (!hasRead) {
|
|
1888
|
-
let isCreate = !fs.existsSync(
|
|
1872
|
+
let isCreate = !fs.existsSync(path7);
|
|
1889
1873
|
if (!isCreate) {
|
|
1890
1874
|
isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
|
|
1891
1875
|
}
|
|
1892
1876
|
if (!isCreate) {
|
|
1893
|
-
unreadPaths.push(
|
|
1877
|
+
unreadPaths.push(path7);
|
|
1894
1878
|
}
|
|
1895
1879
|
}
|
|
1896
1880
|
}
|
|
@@ -2084,16 +2068,16 @@ var init_logic_rules = __esm({
|
|
|
2084
2068
|
ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
|
|
2085
2069
|
ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
|
|
2086
2070
|
HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
|
|
2087
|
-
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path:
|
|
2071
|
+
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2088
2072
|
ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
|
|
2089
2073
|
HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
|
|
2090
|
-
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path:
|
|
2074
|
+
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2091
2075
|
ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
|
|
2092
2076
|
HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
|
|
2093
|
-
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path:
|
|
2077
|
+
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2094
2078
|
ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
|
|
2095
2079
|
HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
|
|
2096
|
-
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path:
|
|
2080
|
+
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2097
2081
|
_scopeIndex = null;
|
|
2098
2082
|
NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
|
|
2099
2083
|
"ask_user_question",
|
|
@@ -3862,7 +3846,9 @@ function loadLLMConfigFromFile(configPath) {
|
|
|
3862
3846
|
model: llm.model || "",
|
|
3863
3847
|
temperature: llm.temperature ?? 0.1,
|
|
3864
3848
|
maxTokens: llm.max_tokens ?? 4096,
|
|
3865
|
-
timeout: llm.timeout ?? 40
|
|
3849
|
+
timeout: llm.timeout ?? 40,
|
|
3850
|
+
// 部署级透传参数(关思考等)。非对象直接忽略:写错不能拖垮配置加载。
|
|
3851
|
+
...llm.extra_body && typeof llm.extra_body === "object" && !Array.isArray(llm.extra_body) ? { extraBody: llm.extra_body } : {}
|
|
3866
3852
|
};
|
|
3867
3853
|
}
|
|
3868
3854
|
function loadTimeoutRetryFromFile(configPath) {
|
|
@@ -4694,16 +4680,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4694
4680
|
if (String(osType || "").toLowerCase() === "windows") {
|
|
4695
4681
|
pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
|
|
4696
4682
|
}
|
|
4697
|
-
const pathMatches = (text,
|
|
4698
|
-
const parts =
|
|
4683
|
+
const pathMatches = (text, path7) => {
|
|
4684
|
+
const parts = path7.split(/(\(\?!.*?\))/);
|
|
4699
4685
|
const escaped = parts.map((part) => {
|
|
4700
4686
|
if (part.startsWith("(?!")) return part;
|
|
4701
4687
|
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4702
4688
|
}).join("");
|
|
4703
|
-
const re =
|
|
4689
|
+
const re = path7.startsWith(".") || path7.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
|
|
4704
4690
|
return re.test(text);
|
|
4705
4691
|
};
|
|
4706
|
-
const pathMatchesAny = (
|
|
4692
|
+
const pathMatchesAny = (path7) => pathScanTexts.some((t) => pathMatches(t, path7));
|
|
4707
4693
|
for (const sp of rootPaths) {
|
|
4708
4694
|
if (pathMatchesAny(sp.path.toLowerCase())) {
|
|
4709
4695
|
if (keygenGenerate) continue;
|
|
@@ -4846,8 +4832,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4846
4832
|
}
|
|
4847
4833
|
return null;
|
|
4848
4834
|
}
|
|
4849
|
-
function isHomeValue(
|
|
4850
|
-
let p =
|
|
4835
|
+
function isHomeValue(path7) {
|
|
4836
|
+
let p = path7.trim().toLowerCase();
|
|
4851
4837
|
if (p.startsWith("$(") && p.endsWith(")")) {
|
|
4852
4838
|
const inner = p.slice(2, -1).trim();
|
|
4853
4839
|
return HOME_TARGET_RE.test(" " + inner);
|
|
@@ -4903,15 +4889,15 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
4903
4889
|
}
|
|
4904
4890
|
const assigned = {};
|
|
4905
4891
|
for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
|
|
4906
|
-
for (const [varName,
|
|
4907
|
-
if (!isHomeValue(
|
|
4892
|
+
for (const [varName, path7] of Object.entries(assigned)) {
|
|
4893
|
+
if (!isHomeValue(path7)) continue;
|
|
4908
4894
|
const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
|
|
4909
4895
|
for (const seg of segs) {
|
|
4910
4896
|
if (!isDeleteCommand(seg)) continue;
|
|
4911
4897
|
if (varRefRe.test(seg)) {
|
|
4912
4898
|
return {
|
|
4913
4899
|
allowed: false,
|
|
4914
|
-
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${
|
|
4900
|
+
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path7}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
|
|
4915
4901
|
riskLevel: "high",
|
|
4916
4902
|
riskType: "script_execution",
|
|
4917
4903
|
confidence: 90,
|
|
@@ -5715,15 +5701,15 @@ function parseShellString(s) {
|
|
|
5715
5701
|
let m;
|
|
5716
5702
|
while ((m = CHILD_CALL_RE.exec(s)) !== null) {
|
|
5717
5703
|
const interp = m[1];
|
|
5718
|
-
const
|
|
5704
|
+
const path7 = m[2].trim();
|
|
5719
5705
|
let rest = m[3].trim();
|
|
5720
|
-
if (
|
|
5706
|
+
if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
|
|
5721
5707
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5722
5708
|
const args = [];
|
|
5723
5709
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5724
5710
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5725
5711
|
}
|
|
5726
|
-
return { path:
|
|
5712
|
+
return { path: path7, args, interpreter: interp };
|
|
5727
5713
|
}
|
|
5728
5714
|
return null;
|
|
5729
5715
|
}
|
|
@@ -5769,9 +5755,9 @@ function extractCallsFromTree(tree, reachableLines) {
|
|
|
5769
5755
|
}
|
|
5770
5756
|
if (allStr && elts.length >= 2) {
|
|
5771
5757
|
const interp = elts[0];
|
|
5772
|
-
const
|
|
5773
|
-
if (!
|
|
5774
|
-
add({ path:
|
|
5758
|
+
const path7 = elts[1];
|
|
5759
|
+
if (!path7.startsWith("-") && !path7.startsWith("$") && !path7.includes("/dev/")) {
|
|
5760
|
+
add({ path: path7, args: elts.slice(2), interpreter: interp });
|
|
5775
5761
|
return true;
|
|
5776
5762
|
}
|
|
5777
5763
|
}
|
|
@@ -5811,15 +5797,15 @@ function extractCallsRegex(content) {
|
|
|
5811
5797
|
let m;
|
|
5812
5798
|
while ((m = CHILD_CALL_RE.exec(content)) !== null) {
|
|
5813
5799
|
const interp = m[1];
|
|
5814
|
-
const
|
|
5800
|
+
const path7 = m[2].trim();
|
|
5815
5801
|
let rest = m[3].trim();
|
|
5816
|
-
if (
|
|
5802
|
+
if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
|
|
5817
5803
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5818
5804
|
const args = [];
|
|
5819
5805
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5820
5806
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5821
5807
|
}
|
|
5822
|
-
calls.push({ path:
|
|
5808
|
+
calls.push({ path: path7, args, interpreter: interp });
|
|
5823
5809
|
}
|
|
5824
5810
|
return calls;
|
|
5825
5811
|
}
|
|
@@ -6602,15 +6588,15 @@ function extractCallsFromContent(content) {
|
|
|
6602
6588
|
CHILD_CALL_RE2.lastIndex = 0;
|
|
6603
6589
|
while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
|
|
6604
6590
|
const interp = m[1];
|
|
6605
|
-
const
|
|
6591
|
+
const path7 = m[2].trim();
|
|
6606
6592
|
let rest = m[3].trim();
|
|
6607
|
-
if (
|
|
6593
|
+
if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
|
|
6608
6594
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
6609
6595
|
const args = [];
|
|
6610
6596
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
6611
6597
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
6612
6598
|
}
|
|
6613
|
-
calls.push({ path:
|
|
6599
|
+
calls.push({ path: path7, args, interpreter: interp });
|
|
6614
6600
|
}
|
|
6615
6601
|
return calls;
|
|
6616
6602
|
}
|
|
@@ -7299,6 +7285,464 @@ var init_script_content_analyzer = __esm({
|
|
|
7299
7285
|
}
|
|
7300
7286
|
});
|
|
7301
7287
|
|
|
7288
|
+
// src/infra/trace-log.ts
|
|
7289
|
+
import fs4 from "fs";
|
|
7290
|
+
import path4 from "path";
|
|
7291
|
+
function traceLevel() {
|
|
7292
|
+
if (_levelCache !== null) return _levelCache;
|
|
7293
|
+
const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
|
|
7294
|
+
let level;
|
|
7295
|
+
if (raw in LEVEL_NAMES) {
|
|
7296
|
+
level = LEVEL_NAMES[raw];
|
|
7297
|
+
} else {
|
|
7298
|
+
level = LEVEL_SUMMARY;
|
|
7299
|
+
if (!_warnedInvalid) {
|
|
7300
|
+
_warnedInvalid = true;
|
|
7301
|
+
console.warn(
|
|
7302
|
+
`[AgentMoss] AGENT_MOSS_TRACE_LEVEL=${JSON.stringify(raw)} \u975E\u6CD5\uFF0C\u6309 summary \u5904\u7406\uFF08\u53EF\u9009 off/summary/full\uFF09`
|
|
7303
|
+
);
|
|
7304
|
+
}
|
|
7305
|
+
}
|
|
7306
|
+
_levelCache = level;
|
|
7307
|
+
_levelCacheRaw = raw;
|
|
7308
|
+
return level;
|
|
7309
|
+
}
|
|
7310
|
+
function nowIso() {
|
|
7311
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
7312
|
+
}
|
|
7313
|
+
function tracePath() {
|
|
7314
|
+
const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
|
|
7315
|
+
if (explicit) return explicit;
|
|
7316
|
+
try {
|
|
7317
|
+
return path4.join(getDataRoot(), "agent_moss_trace.log");
|
|
7318
|
+
} catch {
|
|
7319
|
+
return "agent_moss_trace.log";
|
|
7320
|
+
}
|
|
7321
|
+
}
|
|
7322
|
+
function sanitize(key, value) {
|
|
7323
|
+
if (SECRET_KEYS.has(key.toLowerCase())) return "***";
|
|
7324
|
+
if (typeof value === "string") {
|
|
7325
|
+
let v = value;
|
|
7326
|
+
if (v.length > MAX_FIELD_CHARS) {
|
|
7327
|
+
const original = v.length;
|
|
7328
|
+
v = `${v.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
|
|
7329
|
+
}
|
|
7330
|
+
return v;
|
|
7331
|
+
}
|
|
7332
|
+
if (value === null || ["number", "boolean"].includes(typeof value)) return value;
|
|
7333
|
+
let text;
|
|
7334
|
+
try {
|
|
7335
|
+
text = JSON.stringify(value);
|
|
7336
|
+
} catch {
|
|
7337
|
+
return String(value);
|
|
7338
|
+
}
|
|
7339
|
+
if (text.length > MAX_FIELD_CHARS) {
|
|
7340
|
+
const original = text.length;
|
|
7341
|
+
return `${text.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
|
|
7342
|
+
}
|
|
7343
|
+
return value;
|
|
7344
|
+
}
|
|
7345
|
+
function trace(event, level = LEVEL_SUMMARY, fields = {}) {
|
|
7346
|
+
if (traceLevel() < level) return;
|
|
7347
|
+
try {
|
|
7348
|
+
const record = { ts: nowIso(), event };
|
|
7349
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
7350
|
+
record[key] = sanitize(key, value);
|
|
7351
|
+
}
|
|
7352
|
+
const line = `${JSON.stringify(record)}
|
|
7353
|
+
`;
|
|
7354
|
+
const file = tracePath();
|
|
7355
|
+
try {
|
|
7356
|
+
const dir = path4.dirname(file);
|
|
7357
|
+
if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
|
|
7358
|
+
try {
|
|
7359
|
+
const st = fs4.statSync(file);
|
|
7360
|
+
if (st.size > MAX_FILE_BYTES) fs4.renameSync(file, `${file}.1`);
|
|
7361
|
+
} catch {
|
|
7362
|
+
}
|
|
7363
|
+
fs4.appendFileSync(file, line, { encoding: "utf-8", mode: 384 });
|
|
7364
|
+
} catch {
|
|
7365
|
+
}
|
|
7366
|
+
} catch {
|
|
7367
|
+
}
|
|
7368
|
+
}
|
|
7369
|
+
function traceSummary(event, fields = {}) {
|
|
7370
|
+
trace(event, LEVEL_SUMMARY, fields);
|
|
7371
|
+
}
|
|
7372
|
+
function traceFull(event, fields = {}) {
|
|
7373
|
+
trace(event, LEVEL_FULL, fields);
|
|
7374
|
+
}
|
|
7375
|
+
var LEVEL_OFF, LEVEL_SUMMARY, LEVEL_FULL, LEVEL_NAMES, MAX_FIELD_CHARS, SECRET_KEYS, MAX_FILE_BYTES, _levelCache, _levelCacheRaw, _warnedInvalid;
|
|
7376
|
+
var init_trace_log = __esm({
|
|
7377
|
+
"src/infra/trace-log.ts"() {
|
|
7378
|
+
"use strict";
|
|
7379
|
+
init_esm_shims();
|
|
7380
|
+
init_paths();
|
|
7381
|
+
LEVEL_OFF = 0;
|
|
7382
|
+
LEVEL_SUMMARY = 1;
|
|
7383
|
+
LEVEL_FULL = 2;
|
|
7384
|
+
LEVEL_NAMES = {
|
|
7385
|
+
off: LEVEL_OFF,
|
|
7386
|
+
summary: LEVEL_SUMMARY,
|
|
7387
|
+
full: LEVEL_FULL
|
|
7388
|
+
};
|
|
7389
|
+
MAX_FIELD_CHARS = 64 * 1024;
|
|
7390
|
+
SECRET_KEYS = /* @__PURE__ */ new Set([
|
|
7391
|
+
"api_key",
|
|
7392
|
+
"apikey",
|
|
7393
|
+
"authorization",
|
|
7394
|
+
"auth_token",
|
|
7395
|
+
"token",
|
|
7396
|
+
"password"
|
|
7397
|
+
]);
|
|
7398
|
+
MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
7399
|
+
_levelCache = null;
|
|
7400
|
+
_levelCacheRaw = null;
|
|
7401
|
+
_warnedInvalid = false;
|
|
7402
|
+
}
|
|
7403
|
+
});
|
|
7404
|
+
|
|
7405
|
+
// src/infra/circuit-breaker.ts
|
|
7406
|
+
function envInt2(name, fallback) {
|
|
7407
|
+
const raw = process.env[name];
|
|
7408
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
7409
|
+
const n = Number(raw);
|
|
7410
|
+
return Number.isFinite(n) ? n : fallback;
|
|
7411
|
+
}
|
|
7412
|
+
function getBreaker() {
|
|
7413
|
+
if (_breaker === null) {
|
|
7414
|
+
_breaker = new CircuitBreaker(
|
|
7415
|
+
envInt2("AGENT_MOSS_LLM_CIRCUIT_THRESHOLD", 5),
|
|
7416
|
+
envInt2("AGENT_MOSS_LLM_CIRCUIT_COOLDOWN", 30)
|
|
7417
|
+
);
|
|
7418
|
+
}
|
|
7419
|
+
return _breaker;
|
|
7420
|
+
}
|
|
7421
|
+
var CLOSED, OPEN, HALF_OPEN, CircuitBreaker, _breaker;
|
|
7422
|
+
var init_circuit_breaker = __esm({
|
|
7423
|
+
"src/infra/circuit-breaker.ts"() {
|
|
7424
|
+
"use strict";
|
|
7425
|
+
init_esm_shims();
|
|
7426
|
+
CLOSED = "closed";
|
|
7427
|
+
OPEN = "open";
|
|
7428
|
+
HALF_OPEN = "half_open";
|
|
7429
|
+
CircuitBreaker = class {
|
|
7430
|
+
constructor(threshold = 5, cooldown = 30) {
|
|
7431
|
+
this.threshold = threshold;
|
|
7432
|
+
this.cooldown = cooldown;
|
|
7433
|
+
}
|
|
7434
|
+
threshold;
|
|
7435
|
+
cooldown;
|
|
7436
|
+
state = CLOSED;
|
|
7437
|
+
failures = 0;
|
|
7438
|
+
openedAt = 0;
|
|
7439
|
+
openCount = 0;
|
|
7440
|
+
shortCircuitCount = 0;
|
|
7441
|
+
get currentState() {
|
|
7442
|
+
return this.state;
|
|
7443
|
+
}
|
|
7444
|
+
allow() {
|
|
7445
|
+
if (this.threshold <= 0) return true;
|
|
7446
|
+
if (this.state === CLOSED) return true;
|
|
7447
|
+
if (this.state === OPEN) {
|
|
7448
|
+
if ((performance.now() - this.openedAt) / 1e3 >= this.cooldown) {
|
|
7449
|
+
this.state = HALF_OPEN;
|
|
7450
|
+
return true;
|
|
7451
|
+
}
|
|
7452
|
+
this.shortCircuitCount += 1;
|
|
7453
|
+
return false;
|
|
7454
|
+
}
|
|
7455
|
+
return true;
|
|
7456
|
+
}
|
|
7457
|
+
recordSuccess() {
|
|
7458
|
+
if (this.threshold <= 0) return;
|
|
7459
|
+
this.state = CLOSED;
|
|
7460
|
+
this.failures = 0;
|
|
7461
|
+
}
|
|
7462
|
+
recordFailure() {
|
|
7463
|
+
if (this.threshold <= 0) return;
|
|
7464
|
+
if (this.state === HALF_OPEN) {
|
|
7465
|
+
this.state = OPEN;
|
|
7466
|
+
this.openedAt = performance.now();
|
|
7467
|
+
this.openCount += 1;
|
|
7468
|
+
return;
|
|
7469
|
+
}
|
|
7470
|
+
this.failures += 1;
|
|
7471
|
+
if (this.failures >= this.threshold) {
|
|
7472
|
+
this.state = OPEN;
|
|
7473
|
+
this.openedAt = performance.now();
|
|
7474
|
+
this.openCount += 1;
|
|
7475
|
+
}
|
|
7476
|
+
}
|
|
7477
|
+
snapshot() {
|
|
7478
|
+
return {
|
|
7479
|
+
state: this.state,
|
|
7480
|
+
failures: this.failures,
|
|
7481
|
+
threshold: this.threshold,
|
|
7482
|
+
cooldown_sec: this.cooldown,
|
|
7483
|
+
open_count: this.openCount,
|
|
7484
|
+
short_circuit_count: this.shortCircuitCount
|
|
7485
|
+
};
|
|
7486
|
+
}
|
|
7487
|
+
reset() {
|
|
7488
|
+
this.state = CLOSED;
|
|
7489
|
+
this.failures = 0;
|
|
7490
|
+
this.openedAt = 0;
|
|
7491
|
+
}
|
|
7492
|
+
};
|
|
7493
|
+
_breaker = null;
|
|
7494
|
+
}
|
|
7495
|
+
});
|
|
7496
|
+
|
|
7497
|
+
// src/infra/metrics.ts
|
|
7498
|
+
function escapeLabel(value) {
|
|
7499
|
+
return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
|
|
7500
|
+
}
|
|
7501
|
+
function formatLabels(labels) {
|
|
7502
|
+
if (!labels) return "";
|
|
7503
|
+
const keys = Object.keys(labels).sort();
|
|
7504
|
+
if (!keys.length) return "";
|
|
7505
|
+
return `{${keys.map((k) => `${k}="${escapeLabel(labels[k])}"`).join(",")}}`;
|
|
7506
|
+
}
|
|
7507
|
+
function keyOf(labelnames, labels) {
|
|
7508
|
+
return labelnames.map((k) => String(labels[k] ?? "")).join("");
|
|
7509
|
+
}
|
|
7510
|
+
function decodeKey(labelnames, key) {
|
|
7511
|
+
if (!labelnames.length) return void 0;
|
|
7512
|
+
const parts = key.split("");
|
|
7513
|
+
const out = {};
|
|
7514
|
+
labelnames.forEach((k, i) => {
|
|
7515
|
+
out[k] = parts[i] ?? "";
|
|
7516
|
+
});
|
|
7517
|
+
return out;
|
|
7518
|
+
}
|
|
7519
|
+
function renderPrometheus() {
|
|
7520
|
+
const lines = [];
|
|
7521
|
+
for (const m of [
|
|
7522
|
+
ANALYZE_TOTAL,
|
|
7523
|
+
ANALYZE_DURATION,
|
|
7524
|
+
LAYER_HIT_TOTAL,
|
|
7525
|
+
REJECTED_TOTAL,
|
|
7526
|
+
LLM_CALLS_TOTAL,
|
|
7527
|
+
LLM_DURATION,
|
|
7528
|
+
POOL_INFLIGHT,
|
|
7529
|
+
CHAIN_NODES,
|
|
7530
|
+
CHAIN_DB_BYTES,
|
|
7531
|
+
LOOP_LAG,
|
|
7532
|
+
LOOP_LAG_MAX,
|
|
7533
|
+
UPTIME,
|
|
7534
|
+
LLM_CIRCUIT_STATE,
|
|
7535
|
+
LLM_SHORT_CIRCUIT_TOTAL
|
|
7536
|
+
]) {
|
|
7537
|
+
lines.push(...m.render());
|
|
7538
|
+
}
|
|
7539
|
+
return `${lines.join("\n")}
|
|
7540
|
+
`;
|
|
7541
|
+
}
|
|
7542
|
+
function refreshRuntimeGauges(g) {
|
|
7543
|
+
UPTIME.set((Date.now() - STARTED_AT) / 1e3);
|
|
7544
|
+
try {
|
|
7545
|
+
const snap = getBreaker().snapshot();
|
|
7546
|
+
const stateMap = { closed: 0, open: 1, half_open: 2 };
|
|
7547
|
+
LLM_CIRCUIT_STATE.set(stateMap[String(snap.state)] ?? 0);
|
|
7548
|
+
} catch {
|
|
7549
|
+
}
|
|
7550
|
+
if (g.pools !== void 0) {
|
|
7551
|
+
POOL_INFLIGHT.clear();
|
|
7552
|
+
for (const [key, value] of Object.entries(g.pools)) {
|
|
7553
|
+
POOL_INFLIGHT.set(value, { pool: key });
|
|
7554
|
+
}
|
|
7555
|
+
}
|
|
7556
|
+
if (g.chainNodes !== void 0) {
|
|
7557
|
+
CHAIN_NODES.clear();
|
|
7558
|
+
CHAIN_NODES.set(g.chainNodes, { agent: "__total__" });
|
|
7559
|
+
}
|
|
7560
|
+
if (g.chainDbBytes !== void 0) CHAIN_DB_BYTES.set(g.chainDbBytes);
|
|
7561
|
+
if (g.loopLagMs !== void 0) LOOP_LAG.set(g.loopLagMs / 1e3);
|
|
7562
|
+
if (g.loopLagMaxMs !== void 0) LOOP_LAG_MAX.set(g.loopLagMaxMs / 1e3);
|
|
7563
|
+
}
|
|
7564
|
+
var DEFAULT_BUCKETS, STARTED_AT, Counter, Gauge, Histogram, ANALYZE_TOTAL, ANALYZE_DURATION, LAYER_HIT_TOTAL, REJECTED_TOTAL, LLM_CALLS_TOTAL, LLM_DURATION, POOL_INFLIGHT, CHAIN_NODES, CHAIN_DB_BYTES, LOOP_LAG, LOOP_LAG_MAX, UPTIME, LLM_CIRCUIT_STATE, LLM_SHORT_CIRCUIT_TOTAL;
|
|
7565
|
+
var init_metrics = __esm({
|
|
7566
|
+
"src/infra/metrics.ts"() {
|
|
7567
|
+
"use strict";
|
|
7568
|
+
init_esm_shims();
|
|
7569
|
+
init_circuit_breaker();
|
|
7570
|
+
DEFAULT_BUCKETS = [
|
|
7571
|
+
5e-3,
|
|
7572
|
+
0.01,
|
|
7573
|
+
0.025,
|
|
7574
|
+
0.05,
|
|
7575
|
+
0.1,
|
|
7576
|
+
0.25,
|
|
7577
|
+
0.5,
|
|
7578
|
+
1,
|
|
7579
|
+
2.5,
|
|
7580
|
+
5,
|
|
7581
|
+
10,
|
|
7582
|
+
30,
|
|
7583
|
+
60
|
|
7584
|
+
];
|
|
7585
|
+
STARTED_AT = Date.now();
|
|
7586
|
+
Counter = class {
|
|
7587
|
+
constructor(name, helpText, labelnames = []) {
|
|
7588
|
+
this.name = name;
|
|
7589
|
+
this.helpText = helpText;
|
|
7590
|
+
this.labelnames = labelnames;
|
|
7591
|
+
}
|
|
7592
|
+
name;
|
|
7593
|
+
helpText;
|
|
7594
|
+
labelnames;
|
|
7595
|
+
values = /* @__PURE__ */ new Map();
|
|
7596
|
+
inc(amount = 1, labels = {}) {
|
|
7597
|
+
const k = keyOf(this.labelnames, labels);
|
|
7598
|
+
this.values.set(k, (this.values.get(k) ?? 0) + amount);
|
|
7599
|
+
}
|
|
7600
|
+
render() {
|
|
7601
|
+
const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} counter`];
|
|
7602
|
+
if (!this.values.size) {
|
|
7603
|
+
const empty = this.labelnames.length ? Object.fromEntries(this.labelnames.map((k) => [k, ""])) : void 0;
|
|
7604
|
+
out.push(`${this.name}${formatLabels(empty)} 0`);
|
|
7605
|
+
return out;
|
|
7606
|
+
}
|
|
7607
|
+
for (const [k, v] of this.values) {
|
|
7608
|
+
out.push(`${this.name}${formatLabels(decodeKey(this.labelnames, k))} ${v}`);
|
|
7609
|
+
}
|
|
7610
|
+
return out;
|
|
7611
|
+
}
|
|
7612
|
+
};
|
|
7613
|
+
Gauge = class {
|
|
7614
|
+
constructor(name, helpText, labelnames = []) {
|
|
7615
|
+
this.name = name;
|
|
7616
|
+
this.helpText = helpText;
|
|
7617
|
+
this.labelnames = labelnames;
|
|
7618
|
+
}
|
|
7619
|
+
name;
|
|
7620
|
+
helpText;
|
|
7621
|
+
labelnames;
|
|
7622
|
+
values = /* @__PURE__ */ new Map();
|
|
7623
|
+
set(value, labels = {}) {
|
|
7624
|
+
this.values.set(keyOf(this.labelnames, labels), Number(value));
|
|
7625
|
+
}
|
|
7626
|
+
clear() {
|
|
7627
|
+
this.values.clear();
|
|
7628
|
+
}
|
|
7629
|
+
render() {
|
|
7630
|
+
const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} gauge`];
|
|
7631
|
+
for (const [k, v] of this.values) {
|
|
7632
|
+
const labels = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : void 0;
|
|
7633
|
+
out.push(`${this.name}${formatLabels(labels)} ${v}`);
|
|
7634
|
+
}
|
|
7635
|
+
return out;
|
|
7636
|
+
}
|
|
7637
|
+
};
|
|
7638
|
+
Histogram = class {
|
|
7639
|
+
constructor(name, helpText, buckets = DEFAULT_BUCKETS, labelnames = []) {
|
|
7640
|
+
this.name = name;
|
|
7641
|
+
this.helpText = helpText;
|
|
7642
|
+
this.buckets = buckets;
|
|
7643
|
+
this.labelnames = labelnames;
|
|
7644
|
+
}
|
|
7645
|
+
name;
|
|
7646
|
+
helpText;
|
|
7647
|
+
buckets;
|
|
7648
|
+
labelnames;
|
|
7649
|
+
values = /* @__PURE__ */ new Map();
|
|
7650
|
+
observe(value, labels = {}) {
|
|
7651
|
+
const k = keyOf(this.labelnames, labels);
|
|
7652
|
+
let slot = this.values.get(k);
|
|
7653
|
+
if (!slot) {
|
|
7654
|
+
slot = { buckets: this.buckets.map(() => 0), sum: 0, count: 0 };
|
|
7655
|
+
this.values.set(k, slot);
|
|
7656
|
+
}
|
|
7657
|
+
for (let i = 0; i < this.buckets.length; i++) {
|
|
7658
|
+
if (value <= this.buckets[i]) slot.buckets[i] += 1;
|
|
7659
|
+
}
|
|
7660
|
+
slot.sum += value;
|
|
7661
|
+
slot.count += 1;
|
|
7662
|
+
}
|
|
7663
|
+
render() {
|
|
7664
|
+
const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} histogram`];
|
|
7665
|
+
for (const [k, slot] of this.values) {
|
|
7666
|
+
const base = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : {};
|
|
7667
|
+
this.buckets.forEach((bound, i) => {
|
|
7668
|
+
out.push(`${this.name}_bucket${formatLabels({ ...base, le: String(bound) })} ${slot.buckets[i]}`);
|
|
7669
|
+
});
|
|
7670
|
+
out.push(`${this.name}_bucket${formatLabels({ ...base, le: "+Inf" })} ${slot.count}`);
|
|
7671
|
+
out.push(`${this.name}_sum${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.sum}`);
|
|
7672
|
+
out.push(`${this.name}_count${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.count}`);
|
|
7673
|
+
}
|
|
7674
|
+
return out;
|
|
7675
|
+
}
|
|
7676
|
+
};
|
|
7677
|
+
ANALYZE_TOTAL = new Counter(
|
|
7678
|
+
"agent_moss_analyze_total",
|
|
7679
|
+
"Total analyze requests handled, by decision and risk level.",
|
|
7680
|
+
["decision", "risk_level"]
|
|
7681
|
+
);
|
|
7682
|
+
ANALYZE_DURATION = new Histogram(
|
|
7683
|
+
"agent_moss_analyze_duration_seconds",
|
|
7684
|
+
"End-to-end analyze duration in seconds.",
|
|
7685
|
+
DEFAULT_BUCKETS,
|
|
7686
|
+
["decision"]
|
|
7687
|
+
);
|
|
7688
|
+
LAYER_HIT_TOTAL = new Counter(
|
|
7689
|
+
"agent_moss_layer_hit_total",
|
|
7690
|
+
"Number of requests where a given defense layer produced the final verdict.",
|
|
7691
|
+
["layer"]
|
|
7692
|
+
);
|
|
7693
|
+
REJECTED_TOTAL = new Counter(
|
|
7694
|
+
"agent_moss_rejected_total",
|
|
7695
|
+
"Requests rejected before analysis (concurrency / rate limit / auth).",
|
|
7696
|
+
["reason"]
|
|
7697
|
+
);
|
|
7698
|
+
LLM_CALLS_TOTAL = new Counter(
|
|
7699
|
+
"agent_moss_llm_calls_total",
|
|
7700
|
+
"LLM API calls, by outcome.",
|
|
7701
|
+
["result"]
|
|
7702
|
+
);
|
|
7703
|
+
LLM_DURATION = new Histogram(
|
|
7704
|
+
"agent_moss_llm_duration_seconds",
|
|
7705
|
+
"LLM API call duration in seconds.",
|
|
7706
|
+
DEFAULT_BUCKETS,
|
|
7707
|
+
["result"]
|
|
7708
|
+
);
|
|
7709
|
+
POOL_INFLIGHT = new Gauge(
|
|
7710
|
+
"agent_moss_pool_inflight",
|
|
7711
|
+
"Current in-flight requests per concurrency pool.",
|
|
7712
|
+
["pool"]
|
|
7713
|
+
);
|
|
7714
|
+
CHAIN_NODES = new Gauge(
|
|
7715
|
+
"agent_moss_chain_nodes",
|
|
7716
|
+
"Number of nodes in the stateful chain timeline.",
|
|
7717
|
+
["agent"]
|
|
7718
|
+
);
|
|
7719
|
+
CHAIN_DB_BYTES = new Gauge(
|
|
7720
|
+
"agent_moss_chain_db_bytes",
|
|
7721
|
+
"Size of the chain state database in bytes."
|
|
7722
|
+
);
|
|
7723
|
+
LOOP_LAG = new Gauge(
|
|
7724
|
+
"agent_moss_event_loop_lag_seconds",
|
|
7725
|
+
"Most recent event loop lag sample in seconds."
|
|
7726
|
+
);
|
|
7727
|
+
LOOP_LAG_MAX = new Gauge(
|
|
7728
|
+
"agent_moss_event_loop_lag_max_seconds",
|
|
7729
|
+
"Maximum event loop lag observed since process start, in seconds."
|
|
7730
|
+
);
|
|
7731
|
+
UPTIME = new Gauge(
|
|
7732
|
+
"agent_moss_uptime_seconds",
|
|
7733
|
+
"Seconds since process start."
|
|
7734
|
+
);
|
|
7735
|
+
LLM_CIRCUIT_STATE = new Gauge(
|
|
7736
|
+
"agent_moss_llm_circuit_state",
|
|
7737
|
+
"LLM circuit breaker state (0=closed, 1=open, 2=half_open)."
|
|
7738
|
+
);
|
|
7739
|
+
LLM_SHORT_CIRCUIT_TOTAL = new Counter(
|
|
7740
|
+
"agent_moss_llm_short_circuit_total",
|
|
7741
|
+
"LLM calls short-circuited by the breaker (no network request made)."
|
|
7742
|
+
);
|
|
7743
|
+
}
|
|
7744
|
+
});
|
|
7745
|
+
|
|
7302
7746
|
// src/engine/token-stats.ts
|
|
7303
7747
|
var token_stats_exports = {};
|
|
7304
7748
|
__export(token_stats_exports, {
|
|
@@ -7307,9 +7751,10 @@ __export(token_stats_exports, {
|
|
|
7307
7751
|
getTokenStats: () => getTokenStats,
|
|
7308
7752
|
getTokenTrend: () => getTokenTrend,
|
|
7309
7753
|
recordTokenUsage: () => recordTokenUsage,
|
|
7310
|
-
resetTokenStats: () => resetTokenStats
|
|
7754
|
+
resetTokenStats: () => resetTokenStats,
|
|
7755
|
+
resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
|
|
7311
7756
|
});
|
|
7312
|
-
import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2 } from "fs";
|
|
7757
|
+
import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync5 } from "fs";
|
|
7313
7758
|
function getStatsPath() {
|
|
7314
7759
|
const envPath = process.env[ENV_STATS_PATH];
|
|
7315
7760
|
if (envPath) return envPath;
|
|
@@ -7317,11 +7762,24 @@ function getStatsPath() {
|
|
|
7317
7762
|
}
|
|
7318
7763
|
function loadAllRecords(statsPath) {
|
|
7319
7764
|
if (!existsSync13(statsPath)) return [];
|
|
7765
|
+
let sig = "";
|
|
7320
7766
|
try {
|
|
7321
|
-
const
|
|
7322
|
-
|
|
7323
|
-
|
|
7767
|
+
const st = statSync5(statsPath);
|
|
7768
|
+
sig = `${st.mtimeMs}:${st.size}`;
|
|
7769
|
+
} catch {
|
|
7324
7770
|
return [];
|
|
7771
|
+
}
|
|
7772
|
+
if (_recordsCache && _recordsCache.path === statsPath && _recordsCache.sig === sig) {
|
|
7773
|
+
return _recordsCache.records.slice();
|
|
7774
|
+
}
|
|
7775
|
+
try {
|
|
7776
|
+
const data = JSON.parse(readFileSync13(statsPath, "utf-8"));
|
|
7777
|
+
let records;
|
|
7778
|
+
if (Array.isArray(data)) records = data;
|
|
7779
|
+
else if (data && Array.isArray(data.records)) records = data.records;
|
|
7780
|
+
else records = [];
|
|
7781
|
+
_recordsCache = { path: statsPath, sig, records };
|
|
7782
|
+
return records.slice();
|
|
7325
7783
|
} catch (e) {
|
|
7326
7784
|
return [];
|
|
7327
7785
|
}
|
|
@@ -7331,9 +7789,22 @@ function saveRecords(statsPath, records) {
|
|
|
7331
7789
|
const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
|
|
7332
7790
|
if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
|
|
7333
7791
|
writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
|
|
7792
|
+
try {
|
|
7793
|
+
const st = statSync5(statsPath);
|
|
7794
|
+
_recordsCache = {
|
|
7795
|
+
path: statsPath,
|
|
7796
|
+
sig: `${st.mtimeMs}:${st.size}`,
|
|
7797
|
+
records: records.slice()
|
|
7798
|
+
};
|
|
7799
|
+
} catch {
|
|
7800
|
+
_recordsCache = null;
|
|
7801
|
+
}
|
|
7334
7802
|
} catch (e) {
|
|
7335
7803
|
}
|
|
7336
7804
|
}
|
|
7805
|
+
function resetTokenStatsCacheForTests() {
|
|
7806
|
+
_recordsCache = null;
|
|
7807
|
+
}
|
|
7337
7808
|
function recordTokenUsage(record) {
|
|
7338
7809
|
const statsPath = getStatsPath();
|
|
7339
7810
|
const records = loadAllRecords(statsPath);
|
|
@@ -7462,8 +7933,9 @@ function resetTokenStats() {
|
|
|
7462
7933
|
} catch {
|
|
7463
7934
|
}
|
|
7464
7935
|
}
|
|
7936
|
+
_recordsCache = null;
|
|
7465
7937
|
}
|
|
7466
|
-
var ENV_STATS_PATH, MAX_RECORDS;
|
|
7938
|
+
var ENV_STATS_PATH, MAX_RECORDS, _recordsCache;
|
|
7467
7939
|
var init_token_stats = __esm({
|
|
7468
7940
|
"src/engine/token-stats.ts"() {
|
|
7469
7941
|
"use strict";
|
|
@@ -7471,6 +7943,7 @@ var init_token_stats = __esm({
|
|
|
7471
7943
|
init_paths();
|
|
7472
7944
|
ENV_STATS_PATH = "AGENT_MOSS_TOKEN_STATS_PATH";
|
|
7473
7945
|
MAX_RECORDS = 1e4;
|
|
7946
|
+
_recordsCache = null;
|
|
7474
7947
|
}
|
|
7475
7948
|
});
|
|
7476
7949
|
|
|
@@ -7478,6 +7951,22 @@ var init_token_stats = __esm({
|
|
|
7478
7951
|
import { createHash as createHash3 } from "crypto";
|
|
7479
7952
|
import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
|
|
7480
7953
|
import OpenAI from "openai";
|
|
7954
|
+
function responseFieldLengths(message) {
|
|
7955
|
+
if (!message || typeof message !== "object") return {};
|
|
7956
|
+
const out = {};
|
|
7957
|
+
for (const [key, value] of Object.entries(message)) {
|
|
7958
|
+
if (value === null || value === void 0 || value === "") continue;
|
|
7959
|
+
if (Array.isArray(value) && value.length === 0) continue;
|
|
7960
|
+
if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) continue;
|
|
7961
|
+
if (typeof value === "boolean") continue;
|
|
7962
|
+
try {
|
|
7963
|
+
out[key] = typeof value === "string" ? value.length : String(JSON.stringify(value)).length;
|
|
7964
|
+
} catch {
|
|
7965
|
+
out[key] = -1;
|
|
7966
|
+
}
|
|
7967
|
+
}
|
|
7968
|
+
return out;
|
|
7969
|
+
}
|
|
7481
7970
|
async function runLLMAnalysis(input, previous) {
|
|
7482
7971
|
if (!isLLMAvailable()) {
|
|
7483
7972
|
console.log("[AgentMoss] LLM not configured, skipping deep analysis");
|
|
@@ -7560,7 +8049,23 @@ async function runLLMAnalysis(input, previous) {
|
|
|
7560
8049
|
);
|
|
7561
8050
|
}
|
|
7562
8051
|
logPrompt(prompt, input.aNext, previous.llmLogPath);
|
|
8052
|
+
traceFull("l3.prompt", {
|
|
8053
|
+
phase: "security_judge",
|
|
8054
|
+
model: config.model,
|
|
8055
|
+
base_url: config.baseUrl,
|
|
8056
|
+
action_type: input.aNext.actionType,
|
|
8057
|
+
action_detail: input.aNext.actionDetail,
|
|
8058
|
+
prompt,
|
|
8059
|
+
prompt_chars: prompt.length
|
|
8060
|
+
});
|
|
7563
8061
|
const result = await analyzeWithLLM(prompt, config);
|
|
8062
|
+
traceSummary("l3.verdict", {
|
|
8063
|
+
allowed: result.allowed,
|
|
8064
|
+
risk_level: result.riskLevel,
|
|
8065
|
+
risk_type: result.riskType,
|
|
8066
|
+
reason: result.reason,
|
|
8067
|
+
confidence: result.confidence
|
|
8068
|
+
});
|
|
7564
8069
|
if (llmCache.size >= LLM_CACHE_MAX) {
|
|
7565
8070
|
const firstKey = llmCache.keys().next().value;
|
|
7566
8071
|
if (firstKey) llmCache.delete(firstKey);
|
|
@@ -7702,6 +8207,14 @@ function formatHints(previous) {
|
|
|
7702
8207
|
}
|
|
7703
8208
|
async function analyzeWithLLM(prompt, config) {
|
|
7704
8209
|
console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
|
|
8210
|
+
const _llmStart = performance.now();
|
|
8211
|
+
const _recordLlm = (result) => {
|
|
8212
|
+
try {
|
|
8213
|
+
LLM_CALLS_TOTAL.inc(1, { result });
|
|
8214
|
+
LLM_DURATION.observe(Math.max(0, (performance.now() - _llmStart) / 1e3), { result });
|
|
8215
|
+
} catch {
|
|
8216
|
+
}
|
|
8217
|
+
};
|
|
7705
8218
|
const provider = detectProvider(config.baseUrl, config.provider);
|
|
7706
8219
|
const extraHeaders = getProviderHeaders(provider);
|
|
7707
8220
|
if (Object.keys(extraHeaders).length > 0) {
|
|
@@ -7723,6 +8236,17 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7723
8236
|
console.error(`[AgentMoss] totalTimeout (${timeoutCfg.totalTimeout}s) exceeded, aborting all LLM calls`);
|
|
7724
8237
|
abortController.abort();
|
|
7725
8238
|
}, totalTimeoutMs);
|
|
8239
|
+
const breaker = getBreaker();
|
|
8240
|
+
if (!breaker.allow()) {
|
|
8241
|
+
try {
|
|
8242
|
+
LLM_SHORT_CIRCUIT_TOTAL.inc(1);
|
|
8243
|
+
} catch {
|
|
8244
|
+
}
|
|
8245
|
+
_recordLlm("error");
|
|
8246
|
+
throw new Error(
|
|
8247
|
+
"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"
|
|
8248
|
+
);
|
|
8249
|
+
}
|
|
7726
8250
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
7727
8251
|
if (abortController.signal.aborted) {
|
|
7728
8252
|
break;
|
|
@@ -7736,22 +8260,49 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7736
8260
|
{ 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" },
|
|
7737
8261
|
{ role: "user", content: prompt }
|
|
7738
8262
|
],
|
|
7739
|
-
signal: abortController.signal
|
|
8263
|
+
signal: abortController.signal,
|
|
8264
|
+
// 私有化网关的额外参数(关思考等)原样透传;空则不传。
|
|
8265
|
+
...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
|
|
7740
8266
|
});
|
|
7741
8267
|
const message = response.choices[0]?.message;
|
|
7742
8268
|
const content = message?.content ?? "";
|
|
7743
8269
|
const finishReason = response.choices[0]?.finish_reason;
|
|
7744
|
-
const
|
|
8270
|
+
const fieldLengths = responseFieldLengths(message);
|
|
7745
8271
|
const usage = response.usage;
|
|
7746
8272
|
if (!content) {
|
|
7747
|
-
const detail = `model=${response.model || config.model} finish_reason=${finishReason}
|
|
8273
|
+
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 ?? "?"}`;
|
|
8274
|
+
traceFull("l3.empty_response", {
|
|
8275
|
+
model: response.model || config.model,
|
|
8276
|
+
finish_reason: finishReason,
|
|
8277
|
+
message,
|
|
8278
|
+
prompt_tokens: usage?.prompt_tokens ?? 0,
|
|
8279
|
+
completion_tokens: usage?.completion_tokens ?? 0
|
|
8280
|
+
});
|
|
8281
|
+
let fullMessage = "<empty>";
|
|
8282
|
+
try {
|
|
8283
|
+
fullMessage = JSON.stringify(message ?? {});
|
|
8284
|
+
if (fullMessage.length > 8e3) {
|
|
8285
|
+
fullMessage = `${fullMessage.slice(0, 8e3)}...[truncated ${fullMessage.length} chars]`;
|
|
8286
|
+
}
|
|
8287
|
+
} catch {
|
|
8288
|
+
fullMessage = "<\u65E0\u6CD5\u5E8F\u5217\u5316>";
|
|
8289
|
+
}
|
|
7748
8290
|
if (finishReason === "length") {
|
|
7749
|
-
console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
|
|
8291
|
+
console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
|
|
7750
8292
|
throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
|
|
7751
8293
|
}
|
|
7752
|
-
console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
|
|
8294
|
+
console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
|
|
8295
|
+
_recordLlm("empty");
|
|
7753
8296
|
throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
|
|
7754
8297
|
}
|
|
8298
|
+
traceFull("l3.response", {
|
|
8299
|
+
phase: "security_judge",
|
|
8300
|
+
attempt: attempt + 1,
|
|
8301
|
+
model: response.model || config.model,
|
|
8302
|
+
content,
|
|
8303
|
+
prompt_tokens: usage?.prompt_tokens ?? 0,
|
|
8304
|
+
completion_tokens: usage?.completion_tokens ?? 0
|
|
8305
|
+
});
|
|
7755
8306
|
console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
|
|
7756
8307
|
let jsonStr = content.trim();
|
|
7757
8308
|
if (jsonStr.startsWith("```")) {
|
|
@@ -7782,6 +8333,8 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7782
8333
|
clearTimeout(totalTimeoutTimer);
|
|
7783
8334
|
const riskLevel = parsed.riskLevel ?? parsed.risk_level;
|
|
7784
8335
|
const riskType = parsed.riskType ?? parsed.risk_type;
|
|
8336
|
+
breaker.recordSuccess();
|
|
8337
|
+
_recordLlm("success");
|
|
7785
8338
|
return {
|
|
7786
8339
|
allowed: parsed.allowed !== false,
|
|
7787
8340
|
reason: parsed.reason || "LLM \u5206\u6790\u5B8C\u6210",
|
|
@@ -7792,6 +8345,7 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7792
8345
|
violatedLayers: ["L3.1"]
|
|
7793
8346
|
};
|
|
7794
8347
|
} catch (err) {
|
|
8348
|
+
breaker.recordFailure();
|
|
7795
8349
|
if (abortController.signal.aborted) {
|
|
7796
8350
|
console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
|
|
7797
8351
|
break;
|
|
@@ -7824,6 +8378,9 @@ var init_llm_analyzer = __esm({
|
|
|
7824
8378
|
init_template_loader();
|
|
7825
8379
|
init_script_analyzer();
|
|
7826
8380
|
init_script_content_analyzer();
|
|
8381
|
+
init_trace_log();
|
|
8382
|
+
init_metrics();
|
|
8383
|
+
init_circuit_breaker();
|
|
7827
8384
|
llmCache = /* @__PURE__ */ new Map();
|
|
7828
8385
|
LLM_CACHE_MAX = 200;
|
|
7829
8386
|
}
|
|
@@ -7862,8 +8419,8 @@ var init_rule_store = __esm({
|
|
|
7862
8419
|
BrainRuleStore = class {
|
|
7863
8420
|
path;
|
|
7864
8421
|
data;
|
|
7865
|
-
constructor(
|
|
7866
|
-
this.path =
|
|
8422
|
+
constructor(path7) {
|
|
8423
|
+
this.path = path7 || getRulesPath();
|
|
7867
8424
|
this.data = this.load();
|
|
7868
8425
|
}
|
|
7869
8426
|
load() {
|
|
@@ -8316,10 +8873,10 @@ ${reason.slice(0, 500)}
|
|
|
8316
8873
|
const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
|
|
8317
8874
|
let mm;
|
|
8318
8875
|
while ((mm = pathRe.exec(src)) !== null) {
|
|
8319
|
-
const
|
|
8320
|
-
if (
|
|
8321
|
-
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(
|
|
8322
|
-
const gen = this.generalizePath(
|
|
8876
|
+
const path7 = mm[1];
|
|
8877
|
+
if (path7.split("/").length < 3) continue;
|
|
8878
|
+
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path7)) continue;
|
|
8879
|
+
const gen = this.generalizePath(path7);
|
|
8323
8880
|
if (seen.has(gen)) continue;
|
|
8324
8881
|
seen.add(gen);
|
|
8325
8882
|
patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
|
|
@@ -8338,8 +8895,8 @@ ${reason.slice(0, 500)}
|
|
|
8338
8895
|
}
|
|
8339
8896
|
return false;
|
|
8340
8897
|
}
|
|
8341
|
-
generalizePath(
|
|
8342
|
-
const p =
|
|
8898
|
+
generalizePath(path7) {
|
|
8899
|
+
const p = path7.toLowerCase();
|
|
8343
8900
|
if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
|
|
8344
8901
|
return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
|
|
8345
8902
|
}
|
|
@@ -8930,38 +9487,38 @@ function labelEvent(actionDetail) {
|
|
|
8930
9487
|
}
|
|
8931
9488
|
return hits;
|
|
8932
9489
|
}
|
|
8933
|
-
function evaluateLTL(formula,
|
|
9490
|
+
function evaluateLTL(formula, trace2, pos) {
|
|
8934
9491
|
const op = formula[0];
|
|
8935
9492
|
switch (op) {
|
|
8936
9493
|
case "ap":
|
|
8937
|
-
return
|
|
9494
|
+
return trace2[pos].has(formula[1]);
|
|
8938
9495
|
case "!":
|
|
8939
|
-
return !evaluateLTL(formula[1],
|
|
9496
|
+
return !evaluateLTL(formula[1], trace2, pos);
|
|
8940
9497
|
case "&":
|
|
8941
|
-
return evaluateLTL(formula[1],
|
|
9498
|
+
return evaluateLTL(formula[1], trace2, pos) && evaluateLTL(formula[2], trace2, pos);
|
|
8942
9499
|
case "|":
|
|
8943
|
-
return evaluateLTL(formula[1],
|
|
9500
|
+
return evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
|
|
8944
9501
|
case "->":
|
|
8945
|
-
return !evaluateLTL(formula[1],
|
|
9502
|
+
return !evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
|
|
8946
9503
|
case "X":
|
|
8947
|
-
return pos + 1 <
|
|
9504
|
+
return pos + 1 < trace2.length && evaluateLTL(formula[1], trace2, pos + 1);
|
|
8948
9505
|
case "G": {
|
|
8949
|
-
for (let j = pos; j <
|
|
8950
|
-
if (!evaluateLTL(formula[1],
|
|
9506
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
9507
|
+
if (!evaluateLTL(formula[1], trace2, j)) return false;
|
|
8951
9508
|
}
|
|
8952
9509
|
return true;
|
|
8953
9510
|
}
|
|
8954
9511
|
case "F": {
|
|
8955
|
-
for (let j = pos; j <
|
|
8956
|
-
if (evaluateLTL(formula[1],
|
|
9512
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
9513
|
+
if (evaluateLTL(formula[1], trace2, j)) return true;
|
|
8957
9514
|
}
|
|
8958
9515
|
return false;
|
|
8959
9516
|
}
|
|
8960
9517
|
case "U": {
|
|
8961
|
-
for (let j = pos; j <
|
|
8962
|
-
if (evaluateLTL(formula[2],
|
|
9518
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
9519
|
+
if (evaluateLTL(formula[2], trace2, j)) {
|
|
8963
9520
|
for (let k = pos; k < j; k++) {
|
|
8964
|
-
if (!evaluateLTL(formula[1],
|
|
9521
|
+
if (!evaluateLTL(formula[1], trace2, k)) return false;
|
|
8965
9522
|
}
|
|
8966
9523
|
return true;
|
|
8967
9524
|
}
|
|
@@ -8990,11 +9547,11 @@ function checkMCRules(graph) {
|
|
|
8990
9547
|
const mc = loadMC();
|
|
8991
9548
|
const rules = mc.rules || [];
|
|
8992
9549
|
if (rules.length === 0) return violations;
|
|
8993
|
-
const
|
|
9550
|
+
const trace2 = nodes.map((n) => labelEvent(n.actionDetail));
|
|
8994
9551
|
const witnessMode = graph.witnessIdx !== void 0;
|
|
8995
9552
|
for (const rule of rules) {
|
|
8996
9553
|
if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
|
|
8997
|
-
if (ruleViolates(rule,
|
|
9554
|
+
if (ruleViolates(rule, trace2, witnessMode)) {
|
|
8998
9555
|
violations.push({
|
|
8999
9556
|
propertyId: String(rule.id || "mc-ltl"),
|
|
9000
9557
|
reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
|
|
@@ -9185,12 +9742,12 @@ var init_builder = __esm({
|
|
|
9185
9742
|
});
|
|
9186
9743
|
|
|
9187
9744
|
// src/engine/formal-engine/properties.ts
|
|
9188
|
-
function graphFromPath(nodes,
|
|
9745
|
+
function graphFromPath(nodes, path7, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
|
|
9189
9746
|
const byKey = /* @__PURE__ */ new Map();
|
|
9190
9747
|
for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
|
|
9191
9748
|
const gNodes = [];
|
|
9192
9749
|
const gEdges = [];
|
|
9193
|
-
for (const item of
|
|
9750
|
+
for (const item of path7) {
|
|
9194
9751
|
const n = byKey.get(`${item.sessionId}#${item.seq}`);
|
|
9195
9752
|
gNodes.push({
|
|
9196
9753
|
session_id: item.sessionId,
|
|
@@ -9256,22 +9813,22 @@ function checkCrossSessionChain(graph) {
|
|
|
9256
9813
|
if (witness !== void 0) {
|
|
9257
9814
|
if (nodes[witness].stage !== stages[stages.length - 1]) continue;
|
|
9258
9815
|
let matched = 0;
|
|
9259
|
-
const
|
|
9816
|
+
const path7 = [];
|
|
9260
9817
|
for (let k = 0; k < witness; k++) {
|
|
9261
9818
|
const n = nodes[k];
|
|
9262
9819
|
if (matched < stages.length - 1 && n.stage === stages[matched]) {
|
|
9263
9820
|
matched += 1;
|
|
9264
|
-
|
|
9821
|
+
path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9265
9822
|
}
|
|
9266
9823
|
}
|
|
9267
9824
|
if (matched < stages.length - 1) continue;
|
|
9268
|
-
|
|
9825
|
+
path7.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
|
|
9269
9826
|
violations.push({
|
|
9270
9827
|
propertyId: "cross-" + chain.id,
|
|
9271
9828
|
reason: chain.reason,
|
|
9272
9829
|
riskLevel: chain.riskLevel,
|
|
9273
|
-
path:
|
|
9274
|
-
graph: graphFromPath(nodes,
|
|
9830
|
+
path: path7,
|
|
9831
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9275
9832
|
property_id: "cross-" + chain.id,
|
|
9276
9833
|
property_short: "P1",
|
|
9277
9834
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -9281,11 +9838,11 @@ function checkCrossSessionChain(graph) {
|
|
|
9281
9838
|
} else {
|
|
9282
9839
|
let matched = 0;
|
|
9283
9840
|
let stageIdx = 0;
|
|
9284
|
-
const
|
|
9841
|
+
const path7 = [];
|
|
9285
9842
|
for (const n of nodes) {
|
|
9286
9843
|
if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
|
|
9287
9844
|
matched += 1;
|
|
9288
|
-
|
|
9845
|
+
path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9289
9846
|
stageIdx += 1;
|
|
9290
9847
|
if (matched >= stages.length) break;
|
|
9291
9848
|
}
|
|
@@ -9295,8 +9852,8 @@ function checkCrossSessionChain(graph) {
|
|
|
9295
9852
|
propertyId: "cross-" + chain.id,
|
|
9296
9853
|
reason: chain.reason,
|
|
9297
9854
|
riskLevel: chain.riskLevel,
|
|
9298
|
-
path:
|
|
9299
|
-
graph: graphFromPath(nodes,
|
|
9855
|
+
path: path7,
|
|
9856
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9300
9857
|
property_id: "cross-" + chain.id,
|
|
9301
9858
|
property_short: "P1",
|
|
9302
9859
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -9343,7 +9900,7 @@ function checkSensitiveDataFlow(graph) {
|
|
|
9343
9900
|
}
|
|
9344
9901
|
}
|
|
9345
9902
|
}
|
|
9346
|
-
const
|
|
9903
|
+
const tracePath2 = (idx) => {
|
|
9347
9904
|
const chain = [idx];
|
|
9348
9905
|
const seen = /* @__PURE__ */ new Set([idx]);
|
|
9349
9906
|
while (true) {
|
|
@@ -9402,7 +9959,7 @@ function checkSensitiveDataFlow(graph) {
|
|
|
9402
9959
|
for (const i of candidates) {
|
|
9403
9960
|
const n = nodes[i];
|
|
9404
9961
|
if (tainted.has(i) && EXFIL_RE.test(n.actionDetail)) {
|
|
9405
|
-
const chain =
|
|
9962
|
+
const chain = tracePath2(i);
|
|
9406
9963
|
violations.push({
|
|
9407
9964
|
propertyId: "sensitive-data-flow",
|
|
9408
9965
|
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`,
|
|
@@ -9517,7 +10074,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
9517
10074
|
if (candidates.length > 0) {
|
|
9518
10075
|
const pre = nodes[candidates[candidates.length - 1]];
|
|
9519
10076
|
const post = nodes[firstEv];
|
|
9520
|
-
const
|
|
10077
|
+
const path7 = [
|
|
9521
10078
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
9522
10079
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
9523
10080
|
];
|
|
@@ -9525,8 +10082,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
9525
10082
|
propertyId: "no-exfil-after-privesc",
|
|
9526
10083
|
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",
|
|
9527
10084
|
riskLevel: "critical",
|
|
9528
|
-
path:
|
|
9529
|
-
graph: graphFromPath(nodes,
|
|
10085
|
+
path: path7,
|
|
10086
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9530
10087
|
property_id: "no-exfil-after-privesc",
|
|
9531
10088
|
property_short: "P4",
|
|
9532
10089
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9543,7 +10100,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
9543
10100
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
9544
10101
|
if (!isExfilNode(nodes[j])) continue;
|
|
9545
10102
|
if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
|
|
9546
|
-
const
|
|
10103
|
+
const path7 = [
|
|
9547
10104
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
9548
10105
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
9549
10106
|
];
|
|
@@ -9551,8 +10108,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
9551
10108
|
propertyId: "no-exfil-after-privesc",
|
|
9552
10109
|
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",
|
|
9553
10110
|
riskLevel: "critical",
|
|
9554
|
-
path:
|
|
9555
|
-
graph: graphFromPath(nodes,
|
|
10111
|
+
path: path7,
|
|
10112
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9556
10113
|
property_id: "no-exfil-after-privesc",
|
|
9557
10114
|
property_short: "P4",
|
|
9558
10115
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9584,7 +10141,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9584
10141
|
}
|
|
9585
10142
|
if (pre) {
|
|
9586
10143
|
const post = nodes[firstEv];
|
|
9587
|
-
const
|
|
10144
|
+
const path7 = [
|
|
9588
10145
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
9589
10146
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
9590
10147
|
];
|
|
@@ -9592,8 +10149,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9592
10149
|
propertyId: "no-exfil-after-credential",
|
|
9593
10150
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
9594
10151
|
riskLevel: "critical",
|
|
9595
|
-
path:
|
|
9596
|
-
graph: graphFromPath(nodes,
|
|
10152
|
+
path: path7,
|
|
10153
|
+
graph: graphFromPath(nodes, path7, "data", {
|
|
9597
10154
|
property_id: "no-exfil-after-credential",
|
|
9598
10155
|
property_short: "P5",
|
|
9599
10156
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9609,7 +10166,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9609
10166
|
if (!isCredNode(nodes[i])) continue;
|
|
9610
10167
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
9611
10168
|
if (isExfilNode(nodes[j])) {
|
|
9612
|
-
const
|
|
10169
|
+
const path7 = [
|
|
9613
10170
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
9614
10171
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
9615
10172
|
];
|
|
@@ -9617,8 +10174,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9617
10174
|
propertyId: "no-exfil-after-credential",
|
|
9618
10175
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
9619
10176
|
riskLevel: "critical",
|
|
9620
|
-
path:
|
|
9621
|
-
graph: graphFromPath(nodes,
|
|
10177
|
+
path: path7,
|
|
10178
|
+
graph: graphFromPath(nodes, path7, "data", {
|
|
9622
10179
|
property_id: "no-exfil-after-credential",
|
|
9623
10180
|
property_short: "P5",
|
|
9624
10181
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9777,13 +10334,13 @@ function checkSensitiveDataAggregation(graph) {
|
|
|
9777
10334
|
if (!isExfilNode(n)) continue;
|
|
9778
10335
|
const srcs = sourcesFor(i);
|
|
9779
10336
|
if (srcs.size >= 2) {
|
|
9780
|
-
const
|
|
10337
|
+
const path7 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
9781
10338
|
violations.push({
|
|
9782
10339
|
propertyId: "sensitive-data-aggregation",
|
|
9783
10340
|
reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
|
|
9784
10341
|
riskLevel: "critical",
|
|
9785
|
-
path:
|
|
9786
|
-
graph: graphFromPath(nodes,
|
|
10342
|
+
path: path7,
|
|
10343
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9787
10344
|
property_id: "sensitive-data-aggregation",
|
|
9788
10345
|
property_short: "P8",
|
|
9789
10346
|
property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
|
|
@@ -10242,11 +10799,11 @@ var init_stateful = __esm({
|
|
|
10242
10799
|
}
|
|
10243
10800
|
}
|
|
10244
10801
|
chainPath(stages) {
|
|
10245
|
-
const
|
|
10802
|
+
const path7 = [];
|
|
10246
10803
|
let want = stages[0];
|
|
10247
10804
|
for (const n of this.nodes_) {
|
|
10248
10805
|
if (n.stage === want) {
|
|
10249
|
-
|
|
10806
|
+
path7.push({
|
|
10250
10807
|
sessionId: n.sessionId,
|
|
10251
10808
|
seq: n.seq,
|
|
10252
10809
|
stage: n.stage,
|
|
@@ -10262,12 +10819,12 @@ var init_stateful = __esm({
|
|
|
10262
10819
|
}
|
|
10263
10820
|
}
|
|
10264
10821
|
}
|
|
10265
|
-
return
|
|
10822
|
+
return path7;
|
|
10266
10823
|
}
|
|
10267
10824
|
/** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
|
|
10268
10825
|
buildChainGraph(stages, chainId) {
|
|
10269
|
-
const
|
|
10270
|
-
const gNodes =
|
|
10826
|
+
const path7 = this.chainPath(stages);
|
|
10827
|
+
const gNodes = path7.map((p, i) => {
|
|
10271
10828
|
const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
|
|
10272
10829
|
return {
|
|
10273
10830
|
session_id: p.sessionId,
|
|
@@ -10518,16 +11075,42 @@ var init_stateful = __esm({
|
|
|
10518
11075
|
});
|
|
10519
11076
|
|
|
10520
11077
|
// src/engine/formal-engine/chain_state.ts
|
|
10521
|
-
import * as
|
|
11078
|
+
import * as fs5 from "fs";
|
|
10522
11079
|
import * as os2 from "os";
|
|
10523
|
-
import * as
|
|
11080
|
+
import * as path5 from "path";
|
|
10524
11081
|
import { createHash as createHash4 } from "crypto";
|
|
10525
11082
|
function defaultStateDbPath() {
|
|
10526
|
-
const dir = process.env.AGENT_MOSS_STATE_DIR ||
|
|
11083
|
+
const dir = process.env.AGENT_MOSS_STATE_DIR || path5.join(os2.homedir(), ".agentmoss");
|
|
10527
11084
|
const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
|
|
10528
|
-
return
|
|
11085
|
+
return path5.join(dir, `stateful_chains_${tag}.json`);
|
|
10529
11086
|
}
|
|
10530
|
-
|
|
11087
|
+
function registerExitFlush(store) {
|
|
11088
|
+
if (_exitHookRegistered) return;
|
|
11089
|
+
_exitHookRegistered = true;
|
|
11090
|
+
const flush = () => {
|
|
11091
|
+
try {
|
|
11092
|
+
store.flush();
|
|
11093
|
+
} catch {
|
|
11094
|
+
}
|
|
11095
|
+
};
|
|
11096
|
+
process.once("exit", flush);
|
|
11097
|
+
process.once("SIGINT", () => {
|
|
11098
|
+
flush();
|
|
11099
|
+
process.exit(0);
|
|
11100
|
+
});
|
|
11101
|
+
process.once("SIGTERM", () => {
|
|
11102
|
+
flush();
|
|
11103
|
+
process.exit(0);
|
|
11104
|
+
});
|
|
11105
|
+
}
|
|
11106
|
+
function getChainStateStore(filePath = "") {
|
|
11107
|
+
if (_store === null || filePath && filePath !== _store["filePath"]) {
|
|
11108
|
+
_store = new ChainStateStore(filePath);
|
|
11109
|
+
registerExitFlush(_store);
|
|
11110
|
+
}
|
|
11111
|
+
return _store;
|
|
11112
|
+
}
|
|
11113
|
+
var ChainStateStore, _store, _exitHookRegistered;
|
|
10531
11114
|
var init_chain_state = __esm({
|
|
10532
11115
|
"src/engine/formal-engine/chain_state.ts"() {
|
|
10533
11116
|
"use strict";
|
|
@@ -10538,15 +11121,33 @@ var init_chain_state = __esm({
|
|
|
10538
11121
|
filePath;
|
|
10539
11122
|
data;
|
|
10540
11123
|
_timer = null;
|
|
10541
|
-
|
|
11124
|
+
/**
|
|
11125
|
+
* 落盘防抖间隔。**与 Python 端对齐为 1 秒**(2026-11 长稳实测)。
|
|
11126
|
+
*
|
|
11127
|
+
* 原来是 50ms:Node 是单线程,`_syncDirtyToData` 里的 `toSnapshot()` 是
|
|
11128
|
+
* O(节点数) 的全量构建(2 万节点约 40ms),50ms 触发一次等于 80% 的时间
|
|
11129
|
+
* 在序列化,请求全被卡住。1 秒一次把开销摊薄 20 倍;崩溃最坏丢 1 秒增量,
|
|
11130
|
+
* 与 Python 端同一量级。
|
|
11131
|
+
*/
|
|
11132
|
+
_flushDelayMs = 1e3;
|
|
11133
|
+
/**
|
|
11134
|
+
* 内存中的 tracker(唯一事实源)。2026-11 与 Python 端对齐:
|
|
11135
|
+
* 旧实现每次 applyAction 都 `restore(entry.state)` 重建所有节点 +
|
|
11136
|
+
* `toSnapshot()` 全量序列化,O(节点数);长时间运行后每次调用几十到几百毫秒,
|
|
11137
|
+
* 在 Node 单线程上等于把事件循环卡死。现在 apply 只改内存对象,序列化推迟到
|
|
11138
|
+
* 防抖落盘时批量做。
|
|
11139
|
+
*/
|
|
11140
|
+
_trackers = /* @__PURE__ */ new Map();
|
|
11141
|
+
/** 自上次落盘以来变过的 agentId */
|
|
11142
|
+
_dirty = /* @__PURE__ */ new Set();
|
|
10542
11143
|
constructor(filePath = "") {
|
|
10543
11144
|
this.filePath = filePath || defaultStateDbPath();
|
|
10544
11145
|
this.data = this._read();
|
|
10545
11146
|
}
|
|
10546
11147
|
_read() {
|
|
10547
11148
|
try {
|
|
10548
|
-
if (
|
|
10549
|
-
const raw =
|
|
11149
|
+
if (fs5.existsSync(this.filePath)) {
|
|
11150
|
+
const raw = fs5.readFileSync(this.filePath, "utf-8");
|
|
10550
11151
|
return JSON.parse(raw);
|
|
10551
11152
|
}
|
|
10552
11153
|
} catch {
|
|
@@ -10559,12 +11160,22 @@ var init_chain_state = __esm({
|
|
|
10559
11160
|
this._timer = setTimeout(() => {
|
|
10560
11161
|
this._timer = null;
|
|
10561
11162
|
try {
|
|
10562
|
-
|
|
11163
|
+
this._syncDirtyToData();
|
|
11164
|
+
ensurePrivateDir(path5.dirname(this.filePath));
|
|
10563
11165
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
10564
11166
|
} catch {
|
|
10565
11167
|
}
|
|
10566
11168
|
}, this._flushDelayMs);
|
|
10567
11169
|
}
|
|
11170
|
+
/** 把 dirty 的 tracker 序列化进 data(只在落盘时做,避免每次 apply 都 O(n))。 */
|
|
11171
|
+
_syncDirtyToData() {
|
|
11172
|
+
for (const agentId of this._dirty) {
|
|
11173
|
+
const t = this._trackers.get(agentId);
|
|
11174
|
+
if (!t) continue;
|
|
11175
|
+
this.data[agentId] = { state: t.toSnapshot(), updated_at: (/* @__PURE__ */ new Date()).toISOString() };
|
|
11176
|
+
}
|
|
11177
|
+
this._dirty.clear();
|
|
11178
|
+
}
|
|
10568
11179
|
/** 立即落盘(测试/关停前调用,保证状态不丢)。 */
|
|
10569
11180
|
flush() {
|
|
10570
11181
|
if (this._timer !== null) {
|
|
@@ -10572,29 +11183,39 @@ var init_chain_state = __esm({
|
|
|
10572
11183
|
this._timer = null;
|
|
10573
11184
|
}
|
|
10574
11185
|
try {
|
|
10575
|
-
|
|
11186
|
+
this._syncDirtyToData();
|
|
11187
|
+
ensurePrivateDir(path5.dirname(this.filePath));
|
|
10576
11188
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
10577
11189
|
} catch {
|
|
10578
11190
|
}
|
|
10579
11191
|
}
|
|
10580
11192
|
load(agentId) {
|
|
11193
|
+
const cached2 = this._trackers.get(agentId);
|
|
11194
|
+
if (cached2) return cached2;
|
|
10581
11195
|
const entry = this.data[agentId];
|
|
10582
11196
|
if (!entry) return null;
|
|
10583
11197
|
const t = new StatefulChainTracker(agentId);
|
|
10584
11198
|
t.restore(entry.state);
|
|
11199
|
+
this._trackers.set(agentId, t);
|
|
10585
11200
|
return t;
|
|
10586
11201
|
}
|
|
10587
11202
|
save(tracker) {
|
|
10588
|
-
this.
|
|
10589
|
-
|
|
10590
|
-
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
10591
|
-
};
|
|
11203
|
+
this._trackers.set(tracker.agentId, tracker);
|
|
11204
|
+
this._dirty.add(tracker.agentId);
|
|
10592
11205
|
this._scheduleWrite();
|
|
10593
11206
|
}
|
|
10594
11207
|
delete(agentId) {
|
|
11208
|
+
this._trackers.delete(agentId);
|
|
11209
|
+
this._dirty.delete(agentId);
|
|
10595
11210
|
delete this.data[agentId];
|
|
10596
11211
|
this._scheduleWrite();
|
|
10597
11212
|
}
|
|
11213
|
+
/** 当前内存中的 tracker 数 / 节点总数(健康检查用)。 */
|
|
11214
|
+
stats() {
|
|
11215
|
+
let nodes = 0;
|
|
11216
|
+
for (const t of this._trackers.values()) nodes += t.nodes.length;
|
|
11217
|
+
return { agents: this._trackers.size, nodes };
|
|
11218
|
+
}
|
|
10598
11219
|
applyAction(agentId, aNext, sessionId, isError = false, sourceAgent = "", instanceId = "") {
|
|
10599
11220
|
const t = this.load(agentId) || new StatefulChainTracker(agentId);
|
|
10600
11221
|
const r = t.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
|
|
@@ -10609,6 +11230,8 @@ var init_chain_state = __esm({
|
|
|
10609
11230
|
return r;
|
|
10610
11231
|
}
|
|
10611
11232
|
};
|
|
11233
|
+
_store = null;
|
|
11234
|
+
_exitHookRegistered = false;
|
|
10612
11235
|
}
|
|
10613
11236
|
});
|
|
10614
11237
|
|
|
@@ -10716,6 +11339,14 @@ function _resetBrainForTest() {
|
|
|
10716
11339
|
async function runAnalysis(input) {
|
|
10717
11340
|
const observedFormalLayers = [];
|
|
10718
11341
|
const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
|
|
11342
|
+
if (heuristicResult) {
|
|
11343
|
+
traceSummary("l1.result", {
|
|
11344
|
+
hit: !heuristicResult.allowed,
|
|
11345
|
+
risk_level: heuristicResult.riskLevel,
|
|
11346
|
+
risk_type: heuristicResult.riskType,
|
|
11347
|
+
reason: heuristicResult.reason
|
|
11348
|
+
});
|
|
11349
|
+
}
|
|
10719
11350
|
const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
|
|
10720
11351
|
const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
|
|
10721
11352
|
if (heuristicResult && !heuristicResult.allowed) {
|
|
@@ -10859,6 +11490,14 @@ async function runAnalysis(input) {
|
|
|
10859
11490
|
}
|
|
10860
11491
|
}
|
|
10861
11492
|
const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
|
|
11493
|
+
if (logicResult) {
|
|
11494
|
+
traceSummary("l2.result", {
|
|
11495
|
+
hit: !logicResult.allowed,
|
|
11496
|
+
risk_level: logicResult.riskLevel,
|
|
11497
|
+
risk_type: logicResult.riskType,
|
|
11498
|
+
reason: logicResult.reason
|
|
11499
|
+
});
|
|
11500
|
+
}
|
|
10862
11501
|
const l1FileAccessHit = !!(heuristicResult && !heuristicResult.allowed && heuristicResult.riskType === "file_access");
|
|
10863
11502
|
const effectiveResult = logicResult && !logicResult.allowed ? logicResult : l1FileAccessHit ? heuristicResult : null;
|
|
10864
11503
|
if (effectiveResult) {
|
|
@@ -11088,6 +11727,7 @@ var init_coordinator = __esm({
|
|
|
11088
11727
|
init_llm_analyzer();
|
|
11089
11728
|
init_script_content_analyzer();
|
|
11090
11729
|
init_config();
|
|
11730
|
+
init_trace_log();
|
|
11091
11731
|
init_runtime_config();
|
|
11092
11732
|
init_agents();
|
|
11093
11733
|
init_scenarios();
|
|
@@ -11324,6 +11964,8 @@ var AnalyzeResponseSchema = z.object({
|
|
|
11324
11964
|
analysis_duration_ms: z.number().default(0),
|
|
11325
11965
|
// 组合攻击链反例路径:每步 [session_id, seq, stage, timestamp],含真实发生时间
|
|
11326
11966
|
violation_chain: z.array(z.array(z.union([z.string(), z.number()]).nullable())).default([]),
|
|
11967
|
+
// 本次判定的能力降级说明(2026-11):正常为空;链状态触顶时说明 L2.2 未覆盖
|
|
11968
|
+
degraded: z.array(z.string()).default([]),
|
|
11327
11969
|
// 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
|
|
11328
11970
|
violation_graph: z.object({
|
|
11329
11971
|
// 性质元信息(前端展示"违反了哪条性质")
|
|
@@ -11363,12 +12005,18 @@ var AnalyzeResponseSchema = z.object({
|
|
|
11363
12005
|
}).nullable().default(null)
|
|
11364
12006
|
});
|
|
11365
12007
|
var HealthResponseSchema = z.object({
|
|
12008
|
+
// healthy | degraded(2026-11):degraded 表示服务可用但**某项安全能力已降级**
|
|
12009
|
+
// (链状态触顶、LLM 熔断)。任何探活/监控只看 status 就能发现异常。
|
|
11366
12010
|
status: z.string().default("healthy"),
|
|
12011
|
+
// 降级原因(status=degraded 时非空)
|
|
12012
|
+
degraded: z.array(z.string()).default([]),
|
|
11367
12013
|
version: z.string().default(version),
|
|
11368
12014
|
// 归属实例标识:值来自 env AGENT_MOSS_INSTANCE(spawn/systemd 注入),默认空串。
|
|
11369
12015
|
// 多个 agentmoss 同机并存时,调用方按 instance 过滤避免连到别人的进程。
|
|
11370
12016
|
// 空=未配置(独立部署或旧版),调用方可选择兼容或严格过滤。
|
|
11371
|
-
instance: z.string().default("")
|
|
12017
|
+
instance: z.string().default(""),
|
|
12018
|
+
// 运行态指标(2026-11 增强):事件循环延迟、并发池占用、链状态规模。
|
|
12019
|
+
metrics: z.record(z.unknown()).default({})
|
|
11372
12020
|
});
|
|
11373
12021
|
var ReviewRequestSchema = z.object({
|
|
11374
12022
|
agent_id: z.string().default("").describe("\u76EE\u6807 agent \u6807\u8BC6\uFF08\u51B3\u5B9A\u72B6\u6001\u5E93\u5206\u6876\uFF09"),
|
|
@@ -11849,7 +12497,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
11849
12497
|
|
|
11850
12498
|
// src/actrail.ts
|
|
11851
12499
|
init_esm_shims();
|
|
11852
|
-
import * as
|
|
12500
|
+
import * as fs6 from "fs";
|
|
11853
12501
|
|
|
11854
12502
|
// src/infra/esm-require.ts
|
|
11855
12503
|
init_esm_shims();
|
|
@@ -11880,7 +12528,7 @@ function getStoragePath() {
|
|
|
11880
12528
|
function reportEnforcementEvent(opts) {
|
|
11881
12529
|
if (!isEnabled()) return false;
|
|
11882
12530
|
const storagePath = getStoragePath();
|
|
11883
|
-
if (!
|
|
12531
|
+
if (!fs6.existsSync(storagePath)) return false;
|
|
11884
12532
|
try {
|
|
11885
12533
|
let Database;
|
|
11886
12534
|
try {
|
|
@@ -11960,6 +12608,7 @@ function reportEnforcementEvent(opts) {
|
|
|
11960
12608
|
|
|
11961
12609
|
// src/routes.ts
|
|
11962
12610
|
init_formal_engine();
|
|
12611
|
+
init_circuit_breaker();
|
|
11963
12612
|
|
|
11964
12613
|
// src/engine/formal-engine/pattern_miner.ts
|
|
11965
12614
|
init_esm_shims();
|
|
@@ -12042,10 +12691,10 @@ function mineDangerousPatterns(sessions, minSup = 2, maxLen = 4) {
|
|
|
12042
12691
|
|
|
12043
12692
|
// src/agent-gate-reader.ts
|
|
12044
12693
|
init_esm_shims();
|
|
12045
|
-
import * as
|
|
12694
|
+
import * as fs7 from "fs";
|
|
12046
12695
|
import * as os3 from "os";
|
|
12047
|
-
import * as
|
|
12048
|
-
var DEFAULT_AGENTGATE_SQLITE =
|
|
12696
|
+
import * as path6 from "path";
|
|
12697
|
+
var DEFAULT_AGENTGATE_SQLITE = path6.join(
|
|
12049
12698
|
os3.homedir(),
|
|
12050
12699
|
".local",
|
|
12051
12700
|
"share",
|
|
@@ -12061,10 +12710,10 @@ function normalizeAction(row) {
|
|
|
12061
12710
|
function readJsonDir(dirPath, limit = 1e5) {
|
|
12062
12711
|
const sessions = /* @__PURE__ */ new Map();
|
|
12063
12712
|
try {
|
|
12064
|
-
const files =
|
|
12713
|
+
const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
|
|
12065
12714
|
for (const f of files.slice(-200)) {
|
|
12066
12715
|
const sid = f.replace(/\.json$/, "");
|
|
12067
|
-
const raw =
|
|
12716
|
+
const raw = fs7.readFileSync(path6.join(dirPath, f), "utf-8");
|
|
12068
12717
|
const arr = JSON.parse(raw);
|
|
12069
12718
|
if (!Array.isArray(arr)) continue;
|
|
12070
12719
|
for (const item of arr) {
|
|
@@ -12121,7 +12770,7 @@ function readSqlite(dbPath, limit = 1e5) {
|
|
|
12121
12770
|
function loadAgentGateSessions(dbPath = "") {
|
|
12122
12771
|
if (dbPath) {
|
|
12123
12772
|
try {
|
|
12124
|
-
if (
|
|
12773
|
+
if (fs7.statSync(dbPath).isDirectory()) {
|
|
12125
12774
|
return readJsonDir(dbPath);
|
|
12126
12775
|
}
|
|
12127
12776
|
} catch {
|
|
@@ -12132,7 +12781,7 @@ function loadAgentGateSessions(dbPath = "") {
|
|
|
12132
12781
|
}
|
|
12133
12782
|
const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
|
|
12134
12783
|
if (sql.length > 0) return sql;
|
|
12135
|
-
const jsonDefault =
|
|
12784
|
+
const jsonDefault = path6.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
|
|
12136
12785
|
return readJsonDir(jsonDefault);
|
|
12137
12786
|
}
|
|
12138
12787
|
|
|
@@ -12207,16 +12856,105 @@ function normalizeObservablePayload(body) {
|
|
|
12207
12856
|
init_rule_store();
|
|
12208
12857
|
init_skill_manager();
|
|
12209
12858
|
init_asset_dir();
|
|
12859
|
+
init_trace_log();
|
|
12860
|
+
|
|
12861
|
+
// src/infra/loop-monitor.ts
|
|
12862
|
+
init_esm_shims();
|
|
12863
|
+
import { monitorEventLoopDelay } from "perf_hooks";
|
|
12864
|
+
var _histogram = null;
|
|
12865
|
+
var _timer = null;
|
|
12866
|
+
function startLoopMonitor() {
|
|
12867
|
+
if (_histogram !== null) return;
|
|
12868
|
+
_histogram = monitorEventLoopDelay({ resolution: 20 });
|
|
12869
|
+
_histogram.enable();
|
|
12870
|
+
_timer = setInterval(() => {
|
|
12871
|
+
try {
|
|
12872
|
+
_histogram?.reset();
|
|
12873
|
+
} catch {
|
|
12874
|
+
}
|
|
12875
|
+
}, 1e3);
|
|
12876
|
+
if (typeof _timer.unref === "function") _timer.unref();
|
|
12877
|
+
}
|
|
12878
|
+
function loopMonitorSnapshot() {
|
|
12879
|
+
if (_histogram === null) return {};
|
|
12880
|
+
try {
|
|
12881
|
+
const meanMs = _histogram.mean / 1e6;
|
|
12882
|
+
const maxMs = _histogram.max / 1e6;
|
|
12883
|
+
return {
|
|
12884
|
+
loop_lag_ms: Math.round(meanMs * 10) / 10,
|
|
12885
|
+
loop_lag_max_ms: Math.round(maxMs * 10) / 10
|
|
12886
|
+
};
|
|
12887
|
+
} catch {
|
|
12888
|
+
return {};
|
|
12889
|
+
}
|
|
12890
|
+
}
|
|
12891
|
+
|
|
12892
|
+
// src/infra/runtime-stats.ts
|
|
12893
|
+
init_esm_shims();
|
|
12894
|
+
var _pools = null;
|
|
12895
|
+
function registerPools(pools) {
|
|
12896
|
+
_pools = pools;
|
|
12897
|
+
}
|
|
12898
|
+
function poolsSnapshot() {
|
|
12899
|
+
try {
|
|
12900
|
+
return _pools ? _pools.snapshot() : {};
|
|
12901
|
+
} catch {
|
|
12902
|
+
return {};
|
|
12903
|
+
}
|
|
12904
|
+
}
|
|
12905
|
+
|
|
12906
|
+
// src/routes.ts
|
|
12907
|
+
init_metrics();
|
|
12210
12908
|
import { join as join18, dirname as dirname12 } from "path";
|
|
12211
12909
|
import { fileURLToPath as fileURLToPath10 } from "url";
|
|
12212
12910
|
var __dirname9 = dirname12(fileURLToPath10(import.meta.url));
|
|
12213
12911
|
async function healthRoute(c) {
|
|
12912
|
+
const metrics = {};
|
|
12913
|
+
try {
|
|
12914
|
+
Object.assign(metrics, loopMonitorSnapshot());
|
|
12915
|
+
} catch {
|
|
12916
|
+
}
|
|
12917
|
+
metrics.pools = poolsSnapshot();
|
|
12918
|
+
try {
|
|
12919
|
+
const chainStats = getChainStateStoreFor("").stats();
|
|
12920
|
+
metrics.chain_agents = chainStats.agents;
|
|
12921
|
+
metrics.chain_nodes = chainStats.nodes;
|
|
12922
|
+
metrics.chain_capacity = MAX_NODES;
|
|
12923
|
+
metrics.chain_usage_pct = Math.round(chainStats.nodes / MAX_NODES * 1e3) / 10;
|
|
12924
|
+
} catch {
|
|
12925
|
+
}
|
|
12926
|
+
const degraded = [];
|
|
12927
|
+
const pct = metrics.chain_usage_pct;
|
|
12928
|
+
if (typeof pct === "number") {
|
|
12929
|
+
if (pct >= 100) {
|
|
12930
|
+
degraded.push(
|
|
12931
|
+
`\u3010\u5DF2\u964D\u7EA7\u3011\u94FE\u72B6\u6001\u65F6\u95F4\u7EBF\u5DF2\u6EE1\uFF08${metrics.chain_nodes}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u65B0\u52A8\u4F5C\u4E0D\u518D\u5165\u94FE\uFF0C**L2.2 \u7EC4\u5408\u94FE\u68C0\u6D4B\u5DF2\u5931\u6548**\uFF08\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u653B\u51FB\u53EF\u80FD\u6F0F\u5224\uFF09\uFF0CL1/L2.1/L3 \u6B63\u5E38\u3002\u5904\u7406\uFF1Aagent-moss state backup <\u5907\u4EFD\u76EE\u5F55> \u2192 systemctl stop agent_moss \u2192 agent-moss state reset --yes \u2192 systemctl start agent_moss\uFF1B\u6216\u8C03\u5927 AGENT_MOSS_CHAIN_MAX_NODES \u540E\u91CD\u542F\u3002\u8BE6\u89C1 docs/UPGRADE_GUIDE.md`
|
|
12932
|
+
);
|
|
12933
|
+
} else if (pct >= 90) {
|
|
12934
|
+
degraded.push(
|
|
12935
|
+
`\u3010\u9884\u8B66\u3011\u94FE\u72B6\u6001\u65F6\u95F4\u7EBF\u5DF2\u7528 ${pct}%\uFF08${metrics.chain_nodes}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u5373\u5C06\u89E6\u9876\uFF0C\u89E6\u9876\u540E L2.2 \u7EC4\u5408\u94FE\u68C0\u6D4B\uFF08\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u653B\u51FB\uFF09\u5C06\u5931\u6548\uFF0CL1/L2.1/L3 \u4E0D\u53D7\u5F71\u54CD\u3002\u5904\u7406\uFF08\u4EFB\u9009\u5176\u4E00\uFF09\uFF1A\u2460 \u5907\u4EFD\u540E\u91CD\u7F6E\uFF1Aagent-moss state backup <\u5907\u4EFD\u76EE\u5F55> \u2192 \u505C\u670D \u2192 agent-moss state reset --yes \u2192 \u8D77\u670D\uFF1B\u2461 \u4E34\u65F6\u6269\u5BB9\uFF1A\u8C03\u5927 AGENT_MOSS_CHAIN_MAX_NODES \u540E\u91CD\u542F\u3002\u8BE6\u89C1 docs/PERFORMANCE_TUNING.md \u7B2C 5 \u8282`
|
|
12936
|
+
);
|
|
12937
|
+
}
|
|
12938
|
+
}
|
|
12939
|
+
try {
|
|
12940
|
+
const snap = getBreaker().snapshot();
|
|
12941
|
+
if (snap.state === "open") {
|
|
12942
|
+
degraded.push(
|
|
12943
|
+
`\u3010\u5DF2\u964D\u7EA7\u3011LLM \u7194\u65AD\u5668\u5DF2\u6253\u5F00\uFF08\u8FDE\u7EED\u5931\u8D25 ${snap.failures} \u6B21\uFF0C\u9608\u503C ${snap.threshold}\uFF09\uFF1A**L3 \u8BED\u4E49\u5206\u6790\u505C\u6B62\u5DE5\u4F5C**\uFF0C\u5F53\u524D\u6309 AGENT_MOSS_LLM_FAIL_MODE \u7684\u65E2\u5B9A\u7B56\u7565\u5904\u7406\uFF08fail_open \u653E\u884C / fail_closed \u62D2\u7EDD\uFF09\uFF0CL1/L2 \u6B63\u5E38\u3002\u5904\u7406\uFF1A\u68C0\u67E5\u6A21\u578B\u670D\u52A1\u662F\u5426\u5B58\u6D3B\u3001\u7F51\u7EDC\u662F\u5426\u901A\u3001api_key \u662F\u5426\u6709\u6548\uFF1B\u4FEE\u590D\u540E\u51B7\u5374 ${snap.cooldown_sec} \u79D2\u4F1A\u81EA\u52A8\u653E\u8BD5\u63A2\u8BF7\u6C42\u6062\u590D\uFF0C\u65E0\u9700\u91CD\u542F\u3002\u6392\u67E5\u6B65\u9AA4\u89C1 docs/LLM_TROUBLESHOOTING.md`
|
|
12944
|
+
);
|
|
12945
|
+
}
|
|
12946
|
+
} catch {
|
|
12947
|
+
}
|
|
12214
12948
|
return c.json(HealthResponseSchema.parse({
|
|
12215
|
-
|
|
12949
|
+
status: degraded.length ? "degraded" : "healthy",
|
|
12950
|
+
degraded,
|
|
12951
|
+
instance: process.env.AGENT_MOSS_INSTANCE || "",
|
|
12952
|
+
metrics
|
|
12216
12953
|
}));
|
|
12217
12954
|
}
|
|
12218
12955
|
async function analyzeRoute(c) {
|
|
12219
12956
|
const t0 = performance.now();
|
|
12957
|
+
const degradedNotes = [];
|
|
12220
12958
|
try {
|
|
12221
12959
|
const body = await c.req.json();
|
|
12222
12960
|
const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
|
|
@@ -12244,6 +12982,20 @@ async function analyzeRoute(c) {
|
|
|
12244
12982
|
const instanceId = String(
|
|
12245
12983
|
req.instance_id || req.metadata?.instance_id || ""
|
|
12246
12984
|
);
|
|
12985
|
+
traceFull("request", {
|
|
12986
|
+
session_id: req.session_id,
|
|
12987
|
+
agent_id: agentId,
|
|
12988
|
+
os_type: osType,
|
|
12989
|
+
cwd: req.cwd,
|
|
12990
|
+
action_type: req.a_next.action_type,
|
|
12991
|
+
action_detail: req.a_next.action_detail,
|
|
12992
|
+
reason: req.reason,
|
|
12993
|
+
prompt_session: req.prompt_session,
|
|
12994
|
+
action_history: req.action_history,
|
|
12995
|
+
prompt_history: req.prompt_history,
|
|
12996
|
+
session_history: req.session_history,
|
|
12997
|
+
metadata: req.metadata
|
|
12998
|
+
});
|
|
12247
12999
|
const result = await analyze({
|
|
12248
13000
|
sessionId: req.session_id,
|
|
12249
13001
|
promptSession: req.prompt_session,
|
|
@@ -12303,6 +13055,29 @@ async function analyzeRoute(c) {
|
|
|
12303
13055
|
llmLogPath: req.metadata?.llm_log_path
|
|
12304
13056
|
});
|
|
12305
13057
|
const durationMs = performance.now() - t0;
|
|
13058
|
+
const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
|
|
13059
|
+
if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
|
|
13060
|
+
console.warn(
|
|
13061
|
+
`[AgentMoss] \u6162\u8BF7\u6C42: ${Math.round(durationMs)}ms\uFF08\u9608\u503C ${slowMs}ms\uFF09 action_type=${req.a_next.action_type} agent=${agentId || "-"} decision=${result.decision}`
|
|
13062
|
+
);
|
|
13063
|
+
}
|
|
13064
|
+
try {
|
|
13065
|
+
ANALYZE_TOTAL.inc(1, { decision: result.decision, risk_level: result.risk_level });
|
|
13066
|
+
ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
|
|
13067
|
+
for (const layer of result.violated_layers || []) {
|
|
13068
|
+
LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
|
|
13069
|
+
}
|
|
13070
|
+
} catch {
|
|
13071
|
+
}
|
|
13072
|
+
traceSummary("result", {
|
|
13073
|
+
session_id: req.session_id,
|
|
13074
|
+
decision: result.decision,
|
|
13075
|
+
risk_level: result.risk_level,
|
|
13076
|
+
risk_type: result.risk_type,
|
|
13077
|
+
reason: result.reason,
|
|
13078
|
+
violated_layers: result.violated_layers,
|
|
13079
|
+
duration_ms: Math.round(durationMs * 10) / 10
|
|
13080
|
+
});
|
|
12306
13081
|
try {
|
|
12307
13082
|
reportEnforcementEvent({
|
|
12308
13083
|
traceId: req.session_id,
|
|
@@ -12334,6 +13109,20 @@ async function analyzeRoute(c) {
|
|
|
12334
13109
|
// 来源:真实 agent(桶 key 可能是 __system__)
|
|
12335
13110
|
instanceId
|
|
12336
13111
|
);
|
|
13112
|
+
try {
|
|
13113
|
+
const total = store.stats().nodes;
|
|
13114
|
+
const pct = Math.round(total / MAX_NODES * 1e3) / 10;
|
|
13115
|
+
if (total >= MAX_NODES) {
|
|
13116
|
+
degradedNotes.push(
|
|
13117
|
+
`\u3010\u5DF2\u964D\u7EA7\u3011\u94FE\u72B6\u6001\u65F6\u95F4\u7EBF\u5DF2\u6EE1\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A**\u672C\u6B21\u52A8\u4F5C\u672A\u53C2\u4E0E L2.2 \u7EC4\u5408\u94FE\u68C0\u6D4B**\uFF08L1/L2.1/L3 \u4E0D\u53D7\u5F71\u54CD\uFF0C\u4ECD\u5728\u6B63\u5E38\u5DE5\u4F5C\uFF09\u3002\u5F71\u54CD\uFF1A\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u653B\u51FB\uFF08\u5982\u5148\u4E0B\u8F7D\u540E\u6267\u884C\u3001\u5148\u8BFB\u51ED\u636E\u540E\u5916\u4F20\uFF09\u53EF\u80FD\u6F0F\u5224\u3002\u5904\u7406\uFF1Aagent-moss state backup <\u5907\u4EFD\u76EE\u5F55> \u2192 systemctl stop agent_moss \u2192 agent-moss state reset --yes \u2192 systemctl start agent_moss\uFF1B\u6216\u8C03\u5927 AGENT_MOSS_CHAIN_MAX_NODES \u5E76\u91CD\u542F\u3002\u8BE6\u89C1 docs/UPGRADE_GUIDE.md`
|
|
13118
|
+
);
|
|
13119
|
+
} else if (pct >= 90) {
|
|
13120
|
+
degradedNotes.push(
|
|
13121
|
+
`\u3010\u9884\u8B66\u3011\u94FE\u72B6\u6001\u65F6\u95F4\u7EBF\u5DF2\u7528 ${pct}%\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A**\u672C\u6B21\u5224\u5B9A\u5B8C\u6574**\uFF0C\u4F46\u5373\u5C06\u89E6\u9876\u3002\u89E6\u9876\u540E L2.2 \u7EC4\u5408\u94FE\u68C0\u6D4B\uFF08\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u653B\u51FB\uFF09\u5C06\u5931\u6548\uFF0CL1/L2.1/L3 \u4E0D\u53D7\u5F71\u54CD\u3002\u5904\u7406\uFF08\u4EFB\u9009\u5176\u4E00\uFF09\uFF1A\u2460 \u5907\u4EFD\u540E\u91CD\u7F6E\uFF1Aagent-moss state backup <\u5907\u4EFD\u76EE\u5F55> \u2192 \u505C\u670D \u2192 agent-moss state reset --yes \u2192 \u8D77\u670D\uFF1B\u2461 \u4E34\u65F6\u6269\u5BB9\uFF1A\u8C03\u5927 AGENT_MOSS_CHAIN_MAX_NODES \u540E\u91CD\u542F\u3002\u8BE6\u89C1 docs/PERFORMANCE_TUNING.md \u7B2C 5 \u8282`
|
|
13122
|
+
);
|
|
13123
|
+
}
|
|
13124
|
+
} catch {
|
|
13125
|
+
}
|
|
12337
13126
|
const judgment = incMatchedToDeny(inc);
|
|
12338
13127
|
if (judgment) {
|
|
12339
13128
|
const layers = [...result.violated_layers];
|
|
@@ -12376,7 +13165,9 @@ async function analyzeRoute(c) {
|
|
|
12376
13165
|
confidence: result.confidence,
|
|
12377
13166
|
analysis_duration_ms: Math.round(durationMs * 10) / 10,
|
|
12378
13167
|
violation_chain: result.violation_chain ?? [],
|
|
12379
|
-
violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id)
|
|
13168
|
+
violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
|
|
13169
|
+
// 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
|
|
13170
|
+
degraded: degradedNotes
|
|
12380
13171
|
})
|
|
12381
13172
|
);
|
|
12382
13173
|
} catch (err) {
|
|
@@ -12395,10 +13186,8 @@ async function analyzeRoute(c) {
|
|
|
12395
13186
|
return c.json({ detail: `Internal server error (ref: ${ref})`, error: "Internal error" }, 500);
|
|
12396
13187
|
}
|
|
12397
13188
|
}
|
|
12398
|
-
var reviewStore = null;
|
|
12399
13189
|
function getChainStateStoreFor(_agentId) {
|
|
12400
|
-
|
|
12401
|
-
return reviewStore;
|
|
13190
|
+
return getChainStateStore();
|
|
12402
13191
|
}
|
|
12403
13192
|
function incMatchedToDeny(inc) {
|
|
12404
13193
|
if (inc.matched) {
|
|
@@ -12997,6 +13786,8 @@ function createConsoleRouter() {
|
|
|
12997
13786
|
|
|
12998
13787
|
// src/server.ts
|
|
12999
13788
|
init_runtime_config();
|
|
13789
|
+
init_metrics();
|
|
13790
|
+
init_formal_engine();
|
|
13000
13791
|
init_rules_mode();
|
|
13001
13792
|
init_rules_loader();
|
|
13002
13793
|
function logDeploymentSelfCheck() {
|
|
@@ -13077,6 +13868,10 @@ var PooledLimiter = class {
|
|
|
13077
13868
|
if (cur <= 1) this.counts.delete(key);
|
|
13078
13869
|
else this.counts.set(key, cur - 1);
|
|
13079
13870
|
}
|
|
13871
|
+
/** 当前各池占用快照(健康检查用,对齐 Python `_PooledLimiter.snapshot`)。 */
|
|
13872
|
+
snapshot() {
|
|
13873
|
+
return Object.fromEntries(this.counts);
|
|
13874
|
+
}
|
|
13080
13875
|
};
|
|
13081
13876
|
var RateLimiter = class {
|
|
13082
13877
|
constructor(qps, burst) {
|
|
@@ -13120,9 +13915,11 @@ function createApp() {
|
|
|
13120
13915
|
)
|
|
13121
13916
|
);
|
|
13122
13917
|
const pools = new PooledLimiter();
|
|
13918
|
+
registerPools(pools);
|
|
13919
|
+
startLoopMonitor();
|
|
13123
13920
|
const limiter = new RateLimiter(rateLimitQps());
|
|
13124
13921
|
app.use("*", async (c, next) => {
|
|
13125
|
-
const
|
|
13922
|
+
const path7 = new URL(c.req.url).pathname;
|
|
13126
13923
|
const method = c.req.method.toUpperCase();
|
|
13127
13924
|
if (method === "OPTIONS") return next();
|
|
13128
13925
|
const maxBody = maxBodyBytes();
|
|
@@ -13136,16 +13933,16 @@ function createApp() {
|
|
|
13136
13933
|
if (originCheckEnabled()) {
|
|
13137
13934
|
const origin = c.req.header("origin") || "";
|
|
13138
13935
|
if (origin && !originAllowed(origin, c.req.header("host") || "")) {
|
|
13139
|
-
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${
|
|
13936
|
+
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path7}`);
|
|
13140
13937
|
return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
|
|
13141
13938
|
}
|
|
13142
13939
|
}
|
|
13143
|
-
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers,
|
|
13144
|
-
const isPublicPage = !
|
|
13940
|
+
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path7);
|
|
13941
|
+
const isPublicPage = !path7.startsWith("/console/api") && (path7 === "/console" || path7.startsWith("/console/"));
|
|
13145
13942
|
if (!okAuth && !isPublicPage) {
|
|
13146
13943
|
return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
|
|
13147
13944
|
}
|
|
13148
|
-
if (limiter.enabled &&
|
|
13945
|
+
if (limiter.enabled && path7.startsWith("/api/")) {
|
|
13149
13946
|
const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
|
|
13150
13947
|
if (!limiter.allow(key)) {
|
|
13151
13948
|
return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
|
|
@@ -13179,7 +13976,7 @@ function createApp() {
|
|
|
13179
13976
|
return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
|
|
13180
13977
|
}
|
|
13181
13978
|
}
|
|
13182
|
-
const pool = poolOf(
|
|
13979
|
+
const pool = poolOf(path7);
|
|
13183
13980
|
if (!take(`pool:${pool}`, poolLimit(pool))) {
|
|
13184
13981
|
const qkey = principal ? "p:" + principalHash(principal) : "c:local";
|
|
13185
13982
|
const [qn, abusive] = noteQueueReject(qkey);
|
|
@@ -13196,6 +13993,23 @@ function createApp() {
|
|
|
13196
13993
|
while (keys.length) pools.release(keys.pop());
|
|
13197
13994
|
}
|
|
13198
13995
|
});
|
|
13996
|
+
app.get("/metrics", (c) => {
|
|
13997
|
+
let chainNodes;
|
|
13998
|
+
try {
|
|
13999
|
+
chainNodes = getChainStateStore().stats().nodes;
|
|
14000
|
+
} catch {
|
|
14001
|
+
}
|
|
14002
|
+
const lag = loopMonitorSnapshot();
|
|
14003
|
+
refreshRuntimeGauges({
|
|
14004
|
+
pools: pools.snapshot(),
|
|
14005
|
+
chainNodes,
|
|
14006
|
+
loopLagMs: lag.loop_lag_ms,
|
|
14007
|
+
loopLagMaxMs: lag.loop_lag_max_ms
|
|
14008
|
+
});
|
|
14009
|
+
return c.text(renderPrometheus(), 200, {
|
|
14010
|
+
"Content-Type": "text/plain; version=0.0.4; charset=utf-8"
|
|
14011
|
+
});
|
|
14012
|
+
});
|
|
13199
14013
|
app.get("/api/v1/health", healthRoute);
|
|
13200
14014
|
app.post("/api/v1/analyze", analyzeRoute);
|
|
13201
14015
|
app.post("/api/v1/review", reviewRoute);
|