@kenhkl/agent-moss 0.17.22 → 0.17.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1055 -211
- package/dist/engine/coordinator.js +642 -116
- package/dist/server.js +1004 -174
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -407,22 +407,22 @@ function loadToolRegistry() {
|
|
|
407
407
|
data.tools = tools;
|
|
408
408
|
return data;
|
|
409
409
|
}
|
|
410
|
-
function scanStructEntry(cat, value,
|
|
410
|
+
function scanStructEntry(cat, value, path7) {
|
|
411
411
|
if (cat === "skills") {
|
|
412
412
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
413
|
-
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`);
|
|
414
414
|
return null;
|
|
415
415
|
}
|
|
416
416
|
const out = {};
|
|
417
417
|
for (const [skCat, skills] of Object.entries(value)) {
|
|
418
418
|
if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
|
|
419
|
-
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`);
|
|
420
420
|
continue;
|
|
421
421
|
}
|
|
422
422
|
const keep = {};
|
|
423
423
|
for (const [name, kws] of Object.entries(skills)) {
|
|
424
424
|
if (Array.isArray(kws)) keep[name] = kws;
|
|
425
|
-
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`);
|
|
426
426
|
}
|
|
427
427
|
if (Object.keys(keep).length > 0) out[skCat] = keep;
|
|
428
428
|
}
|
|
@@ -430,37 +430,37 @@ function scanStructEntry(cat, value, path6) {
|
|
|
430
430
|
}
|
|
431
431
|
if (cat === "ltl_rules") {
|
|
432
432
|
if (!Array.isArray(value)) {
|
|
433
|
-
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`);
|
|
434
434
|
return null;
|
|
435
435
|
}
|
|
436
436
|
const keep = value.filter((r) => r && typeof r === "object" && r.id);
|
|
437
437
|
if (keep.length !== value.length) {
|
|
438
|
-
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`);
|
|
439
439
|
}
|
|
440
440
|
return keep.length > 0 ? keep : null;
|
|
441
441
|
}
|
|
442
442
|
if (cat === "tools") {
|
|
443
443
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
444
|
-
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`);
|
|
445
445
|
return null;
|
|
446
446
|
}
|
|
447
447
|
const keep = {};
|
|
448
448
|
for (const [k, v] of Object.entries(value)) {
|
|
449
449
|
if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
|
|
450
|
-
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`);
|
|
451
451
|
}
|
|
452
452
|
return Object.keys(keep).length > 0 ? keep : null;
|
|
453
453
|
}
|
|
454
454
|
return null;
|
|
455
455
|
}
|
|
456
|
-
function scanRulesFile(
|
|
456
|
+
function scanRulesFile(path7, kind) {
|
|
457
457
|
const out = {};
|
|
458
458
|
const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
|
|
459
459
|
let parsed;
|
|
460
460
|
try {
|
|
461
|
-
parsed = JSON.parse(readFileSync2(
|
|
461
|
+
parsed = JSON.parse(readFileSync2(path7, "utf-8"));
|
|
462
462
|
} catch (e) {
|
|
463
|
-
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}`);
|
|
464
464
|
return out;
|
|
465
465
|
}
|
|
466
466
|
const classifyFlat = (r) => {
|
|
@@ -484,44 +484,44 @@ function scanRulesFile(path6, kind) {
|
|
|
484
484
|
}
|
|
485
485
|
if (flatBad > 0) {
|
|
486
486
|
console.warn(
|
|
487
|
-
`[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`
|
|
488
488
|
);
|
|
489
489
|
}
|
|
490
490
|
} else {
|
|
491
|
-
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`);
|
|
492
492
|
return out;
|
|
493
493
|
}
|
|
494
494
|
for (const [cat, rules] of pairs) {
|
|
495
495
|
if (String(cat).startsWith("_")) continue;
|
|
496
496
|
if (STRUCT_KEYS.includes(cat)) {
|
|
497
|
-
const got = scanStructEntry(cat, rules,
|
|
497
|
+
const got = scanStructEntry(cat, rules, path7);
|
|
498
498
|
if (got !== null) out[cat] = got;
|
|
499
499
|
continue;
|
|
500
500
|
}
|
|
501
501
|
const required = EXTRA_CATEGORIES[cat];
|
|
502
502
|
if (!required) {
|
|
503
503
|
console.warn(
|
|
504
|
-
`[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`
|
|
505
505
|
);
|
|
506
506
|
continue;
|
|
507
507
|
}
|
|
508
508
|
if (rules && typeof rules === "object" && !Array.isArray(rules)) {
|
|
509
509
|
console.error(
|
|
510
|
-
`[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
|
|
511
511
|
\u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
|
|
512
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`
|
|
513
513
|
);
|
|
514
514
|
continue;
|
|
515
515
|
}
|
|
516
516
|
if (!Array.isArray(rules)) {
|
|
517
|
-
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`);
|
|
518
518
|
continue;
|
|
519
519
|
}
|
|
520
520
|
const items = [];
|
|
521
521
|
for (const r of rules) {
|
|
522
522
|
if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
|
|
523
523
|
console.warn(
|
|
524
|
-
`[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`
|
|
525
525
|
);
|
|
526
526
|
continue;
|
|
527
527
|
}
|
|
@@ -531,7 +531,7 @@ function scanRulesFile(path6, kind) {
|
|
|
531
531
|
}
|
|
532
532
|
if (Object.keys(out).length > 0) {
|
|
533
533
|
console.info(
|
|
534
|
-
`[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(", ")
|
|
535
535
|
);
|
|
536
536
|
}
|
|
537
537
|
return out;
|
|
@@ -801,10 +801,10 @@ function readExplicitToken() {
|
|
|
801
801
|
if (tok) return tok;
|
|
802
802
|
const fdTok = readFdToken();
|
|
803
803
|
if (fdTok) return fdTok;
|
|
804
|
-
const
|
|
805
|
-
if (
|
|
804
|
+
const path7 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
|
|
805
|
+
if (path7) {
|
|
806
806
|
try {
|
|
807
|
-
return readFileSync4(
|
|
807
|
+
return readFileSync4(path7, "utf-8").trim();
|
|
808
808
|
} catch {
|
|
809
809
|
return "";
|
|
810
810
|
}
|
|
@@ -812,23 +812,23 @@ function readExplicitToken() {
|
|
|
812
812
|
return "";
|
|
813
813
|
}
|
|
814
814
|
function ensureAutoToken() {
|
|
815
|
-
const
|
|
815
|
+
const path7 = autoTokenPath();
|
|
816
816
|
try {
|
|
817
|
-
if (existsSync3(
|
|
818
|
-
const tok2 = readFileSync4(
|
|
817
|
+
if (existsSync3(path7) && !lstatSync(path7).isSymbolicLink()) {
|
|
818
|
+
const tok2 = readFileSync4(path7, "utf-8").trim();
|
|
819
819
|
if (tok2) {
|
|
820
820
|
try {
|
|
821
|
-
chmodSync(
|
|
821
|
+
chmodSync(path7, 384);
|
|
822
822
|
} catch {
|
|
823
823
|
}
|
|
824
824
|
return tok2;
|
|
825
825
|
}
|
|
826
826
|
}
|
|
827
827
|
const tok = randomBytes(32).toString("base64url");
|
|
828
|
-
ensurePrivateDir(dirname2(
|
|
829
|
-
if (!writePrivateText(
|
|
828
|
+
ensurePrivateDir(dirname2(path7));
|
|
829
|
+
if (!writePrivateText(path7, tok + "\n")) return "";
|
|
830
830
|
console.warn(
|
|
831
|
-
`[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`
|
|
832
832
|
);
|
|
833
833
|
return tok;
|
|
834
834
|
} catch (e) {
|
|
@@ -901,16 +901,16 @@ function constEq(a, b) {
|
|
|
901
901
|
if (ba.length !== bb.length) return false;
|
|
902
902
|
return timingSafeEqual(ba, bb);
|
|
903
903
|
}
|
|
904
|
-
function checkRequestAuth(headers,
|
|
904
|
+
function checkRequestAuth(headers, path7) {
|
|
905
905
|
if (authMode() === AUTH_MODE_OFF) return [true, ""];
|
|
906
|
-
const isHealth = HEALTH_PATHS.includes(
|
|
906
|
+
const isHealth = HEALTH_PATHS.includes(path7.replace(/\/+$/, ""));
|
|
907
907
|
const [gt0, agents, err] = resolveAuth();
|
|
908
908
|
if (err) return isHealth ? [true, ""] : [false, ""];
|
|
909
909
|
if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
|
|
910
910
|
if (isHealth) return [true, ""];
|
|
911
911
|
const tok = bearer(headers);
|
|
912
912
|
if (!tok) return [false, ""];
|
|
913
|
-
if (
|
|
913
|
+
if (path7.startsWith("/console/api")) {
|
|
914
914
|
const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
|
|
915
915
|
if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
|
|
916
916
|
}
|
|
@@ -929,8 +929,8 @@ function bindAgent(principal, agentId) {
|
|
|
929
929
|
if (!agentId) return [true, bound];
|
|
930
930
|
return [bound === agentId, bound];
|
|
931
931
|
}
|
|
932
|
-
function principalOf(headers,
|
|
933
|
-
const [ok, principal] = checkRequestAuth(headers,
|
|
932
|
+
function principalOf(headers, path7 = "") {
|
|
933
|
+
const [ok, principal] = checkRequestAuth(headers, path7);
|
|
934
934
|
return ok ? principal : "";
|
|
935
935
|
}
|
|
936
936
|
function principalHash(principal) {
|
|
@@ -1188,11 +1188,11 @@ function errorDetailMode() {
|
|
|
1188
1188
|
function maxBodyBytes() {
|
|
1189
1189
|
return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
|
|
1190
1190
|
}
|
|
1191
|
-
function poolOf(
|
|
1192
|
-
if (
|
|
1193
|
-
if (
|
|
1194
|
-
if (
|
|
1195
|
-
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";
|
|
1196
1196
|
return "other";
|
|
1197
1197
|
}
|
|
1198
1198
|
function poolLimit(name) {
|
|
@@ -1505,7 +1505,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
|
|
|
1505
1505
|
os: String(sp.os || "linux").toLowerCase()
|
|
1506
1506
|
}));
|
|
1507
1507
|
}
|
|
1508
|
-
function _scopeOf(os4,
|
|
1508
|
+
function _scopeOf(os4, path7) {
|
|
1509
1509
|
if (!_scopeIndex) {
|
|
1510
1510
|
_scopeIndex = /* @__PURE__ */ new Map();
|
|
1511
1511
|
for (const sp of loadL1().sensitive_path_access || []) {
|
|
@@ -1513,7 +1513,7 @@ function _scopeOf(os4, path6) {
|
|
|
1513
1513
|
if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
|
|
1514
1514
|
}
|
|
1515
1515
|
}
|
|
1516
|
-
return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${
|
|
1516
|
+
return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path7}`) || "root";
|
|
1517
1517
|
}
|
|
1518
1518
|
function getSensitivePathsForOs(osType) {
|
|
1519
1519
|
const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
|
|
@@ -1864,17 +1864,17 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1864
1864
|
return null;
|
|
1865
1865
|
}
|
|
1866
1866
|
const unreadPaths = [];
|
|
1867
|
-
for (const
|
|
1867
|
+
for (const path7 of filteredPaths) {
|
|
1868
1868
|
const hasRead = [...historyReadPaths].some(
|
|
1869
|
-
(rp) =>
|
|
1869
|
+
(rp) => path7 === rp || path7.startsWith(rp) || rp.startsWith(path7)
|
|
1870
1870
|
);
|
|
1871
1871
|
if (!hasRead) {
|
|
1872
|
-
let isCreate = !fs.existsSync(
|
|
1872
|
+
let isCreate = !fs.existsSync(path7);
|
|
1873
1873
|
if (!isCreate) {
|
|
1874
1874
|
isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
|
|
1875
1875
|
}
|
|
1876
1876
|
if (!isCreate) {
|
|
1877
|
-
unreadPaths.push(
|
|
1877
|
+
unreadPaths.push(path7);
|
|
1878
1878
|
}
|
|
1879
1879
|
}
|
|
1880
1880
|
}
|
|
@@ -2068,16 +2068,16 @@ var init_logic_rules = __esm({
|
|
|
2068
2068
|
ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
|
|
2069
2069
|
ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
|
|
2070
2070
|
HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
|
|
2071
|
-
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path:
|
|
2071
|
+
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2072
2072
|
ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
|
|
2073
2073
|
HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
|
|
2074
|
-
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 }));
|
|
2075
2075
|
ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
|
|
2076
2076
|
HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
|
|
2077
|
-
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 }));
|
|
2078
2078
|
ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
|
|
2079
2079
|
HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
|
|
2080
|
-
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 }));
|
|
2081
2081
|
_scopeIndex = null;
|
|
2082
2082
|
NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
|
|
2083
2083
|
"ask_user_question",
|
|
@@ -3846,7 +3846,9 @@ function loadLLMConfigFromFile(configPath) {
|
|
|
3846
3846
|
model: llm.model || "",
|
|
3847
3847
|
temperature: llm.temperature ?? 0.1,
|
|
3848
3848
|
maxTokens: llm.max_tokens ?? 4096,
|
|
3849
|
-
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 } : {}
|
|
3850
3852
|
};
|
|
3851
3853
|
}
|
|
3852
3854
|
function loadTimeoutRetryFromFile(configPath) {
|
|
@@ -4678,16 +4680,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4678
4680
|
if (String(osType || "").toLowerCase() === "windows") {
|
|
4679
4681
|
pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
|
|
4680
4682
|
}
|
|
4681
|
-
const pathMatches = (text,
|
|
4682
|
-
const parts =
|
|
4683
|
+
const pathMatches = (text, path7) => {
|
|
4684
|
+
const parts = path7.split(/(\(\?!.*?\))/);
|
|
4683
4685
|
const escaped = parts.map((part) => {
|
|
4684
4686
|
if (part.startsWith("(?!")) return part;
|
|
4685
4687
|
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4686
4688
|
}).join("");
|
|
4687
|
-
const re =
|
|
4689
|
+
const re = path7.startsWith(".") || path7.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
|
|
4688
4690
|
return re.test(text);
|
|
4689
4691
|
};
|
|
4690
|
-
const pathMatchesAny = (
|
|
4692
|
+
const pathMatchesAny = (path7) => pathScanTexts.some((t) => pathMatches(t, path7));
|
|
4691
4693
|
for (const sp of rootPaths) {
|
|
4692
4694
|
if (pathMatchesAny(sp.path.toLowerCase())) {
|
|
4693
4695
|
if (keygenGenerate) continue;
|
|
@@ -4830,8 +4832,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4830
4832
|
}
|
|
4831
4833
|
return null;
|
|
4832
4834
|
}
|
|
4833
|
-
function isHomeValue(
|
|
4834
|
-
let p =
|
|
4835
|
+
function isHomeValue(path7) {
|
|
4836
|
+
let p = path7.trim().toLowerCase();
|
|
4835
4837
|
if (p.startsWith("$(") && p.endsWith(")")) {
|
|
4836
4838
|
const inner = p.slice(2, -1).trim();
|
|
4837
4839
|
return HOME_TARGET_RE.test(" " + inner);
|
|
@@ -4887,15 +4889,15 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
4887
4889
|
}
|
|
4888
4890
|
const assigned = {};
|
|
4889
4891
|
for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
|
|
4890
|
-
for (const [varName,
|
|
4891
|
-
if (!isHomeValue(
|
|
4892
|
+
for (const [varName, path7] of Object.entries(assigned)) {
|
|
4893
|
+
if (!isHomeValue(path7)) continue;
|
|
4892
4894
|
const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
|
|
4893
4895
|
for (const seg of segs) {
|
|
4894
4896
|
if (!isDeleteCommand(seg)) continue;
|
|
4895
4897
|
if (varRefRe.test(seg)) {
|
|
4896
4898
|
return {
|
|
4897
4899
|
allowed: false,
|
|
4898
|
-
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`,
|
|
4899
4901
|
riskLevel: "high",
|
|
4900
4902
|
riskType: "script_execution",
|
|
4901
4903
|
confidence: 90,
|
|
@@ -5699,15 +5701,15 @@ function parseShellString(s) {
|
|
|
5699
5701
|
let m;
|
|
5700
5702
|
while ((m = CHILD_CALL_RE.exec(s)) !== null) {
|
|
5701
5703
|
const interp = m[1];
|
|
5702
|
-
const
|
|
5704
|
+
const path7 = m[2].trim();
|
|
5703
5705
|
let rest = m[3].trim();
|
|
5704
|
-
if (
|
|
5706
|
+
if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
|
|
5705
5707
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5706
5708
|
const args = [];
|
|
5707
5709
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5708
5710
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5709
5711
|
}
|
|
5710
|
-
return { path:
|
|
5712
|
+
return { path: path7, args, interpreter: interp };
|
|
5711
5713
|
}
|
|
5712
5714
|
return null;
|
|
5713
5715
|
}
|
|
@@ -5753,9 +5755,9 @@ function extractCallsFromTree(tree, reachableLines) {
|
|
|
5753
5755
|
}
|
|
5754
5756
|
if (allStr && elts.length >= 2) {
|
|
5755
5757
|
const interp = elts[0];
|
|
5756
|
-
const
|
|
5757
|
-
if (!
|
|
5758
|
-
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 });
|
|
5759
5761
|
return true;
|
|
5760
5762
|
}
|
|
5761
5763
|
}
|
|
@@ -5795,15 +5797,15 @@ function extractCallsRegex(content) {
|
|
|
5795
5797
|
let m;
|
|
5796
5798
|
while ((m = CHILD_CALL_RE.exec(content)) !== null) {
|
|
5797
5799
|
const interp = m[1];
|
|
5798
|
-
const
|
|
5800
|
+
const path7 = m[2].trim();
|
|
5799
5801
|
let rest = m[3].trim();
|
|
5800
|
-
if (
|
|
5802
|
+
if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
|
|
5801
5803
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5802
5804
|
const args = [];
|
|
5803
5805
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5804
5806
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5805
5807
|
}
|
|
5806
|
-
calls.push({ path:
|
|
5808
|
+
calls.push({ path: path7, args, interpreter: interp });
|
|
5807
5809
|
}
|
|
5808
5810
|
return calls;
|
|
5809
5811
|
}
|
|
@@ -6586,15 +6588,15 @@ function extractCallsFromContent(content) {
|
|
|
6586
6588
|
CHILD_CALL_RE2.lastIndex = 0;
|
|
6587
6589
|
while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
|
|
6588
6590
|
const interp = m[1];
|
|
6589
|
-
const
|
|
6591
|
+
const path7 = m[2].trim();
|
|
6590
6592
|
let rest = m[3].trim();
|
|
6591
|
-
if (
|
|
6593
|
+
if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
|
|
6592
6594
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
6593
6595
|
const args = [];
|
|
6594
6596
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
6595
6597
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
6596
6598
|
}
|
|
6597
|
-
calls.push({ path:
|
|
6599
|
+
calls.push({ path: path7, args, interpreter: interp });
|
|
6598
6600
|
}
|
|
6599
6601
|
return calls;
|
|
6600
6602
|
}
|
|
@@ -7283,6 +7285,464 @@ var init_script_content_analyzer = __esm({
|
|
|
7283
7285
|
}
|
|
7284
7286
|
});
|
|
7285
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
|
+
|
|
7286
7746
|
// src/engine/token-stats.ts
|
|
7287
7747
|
var token_stats_exports = {};
|
|
7288
7748
|
__export(token_stats_exports, {
|
|
@@ -7291,9 +7751,10 @@ __export(token_stats_exports, {
|
|
|
7291
7751
|
getTokenStats: () => getTokenStats,
|
|
7292
7752
|
getTokenTrend: () => getTokenTrend,
|
|
7293
7753
|
recordTokenUsage: () => recordTokenUsage,
|
|
7294
|
-
resetTokenStats: () => resetTokenStats
|
|
7754
|
+
resetTokenStats: () => resetTokenStats,
|
|
7755
|
+
resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
|
|
7295
7756
|
});
|
|
7296
|
-
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";
|
|
7297
7758
|
function getStatsPath() {
|
|
7298
7759
|
const envPath = process.env[ENV_STATS_PATH];
|
|
7299
7760
|
if (envPath) return envPath;
|
|
@@ -7301,11 +7762,24 @@ function getStatsPath() {
|
|
|
7301
7762
|
}
|
|
7302
7763
|
function loadAllRecords(statsPath) {
|
|
7303
7764
|
if (!existsSync13(statsPath)) return [];
|
|
7765
|
+
let sig = "";
|
|
7304
7766
|
try {
|
|
7305
|
-
const
|
|
7306
|
-
|
|
7307
|
-
|
|
7767
|
+
const st = statSync5(statsPath);
|
|
7768
|
+
sig = `${st.mtimeMs}:${st.size}`;
|
|
7769
|
+
} catch {
|
|
7308
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();
|
|
7309
7783
|
} catch (e) {
|
|
7310
7784
|
return [];
|
|
7311
7785
|
}
|
|
@@ -7315,9 +7789,22 @@ function saveRecords(statsPath, records) {
|
|
|
7315
7789
|
const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
|
|
7316
7790
|
if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
|
|
7317
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
|
+
}
|
|
7318
7802
|
} catch (e) {
|
|
7319
7803
|
}
|
|
7320
7804
|
}
|
|
7805
|
+
function resetTokenStatsCacheForTests() {
|
|
7806
|
+
_recordsCache = null;
|
|
7807
|
+
}
|
|
7321
7808
|
function recordTokenUsage(record) {
|
|
7322
7809
|
const statsPath = getStatsPath();
|
|
7323
7810
|
const records = loadAllRecords(statsPath);
|
|
@@ -7446,8 +7933,9 @@ function resetTokenStats() {
|
|
|
7446
7933
|
} catch {
|
|
7447
7934
|
}
|
|
7448
7935
|
}
|
|
7936
|
+
_recordsCache = null;
|
|
7449
7937
|
}
|
|
7450
|
-
var ENV_STATS_PATH, MAX_RECORDS;
|
|
7938
|
+
var ENV_STATS_PATH, MAX_RECORDS, _recordsCache;
|
|
7451
7939
|
var init_token_stats = __esm({
|
|
7452
7940
|
"src/engine/token-stats.ts"() {
|
|
7453
7941
|
"use strict";
|
|
@@ -7455,6 +7943,7 @@ var init_token_stats = __esm({
|
|
|
7455
7943
|
init_paths();
|
|
7456
7944
|
ENV_STATS_PATH = "AGENT_MOSS_TOKEN_STATS_PATH";
|
|
7457
7945
|
MAX_RECORDS = 1e4;
|
|
7946
|
+
_recordsCache = null;
|
|
7458
7947
|
}
|
|
7459
7948
|
});
|
|
7460
7949
|
|
|
@@ -7462,6 +7951,22 @@ var init_token_stats = __esm({
|
|
|
7462
7951
|
import { createHash as createHash3 } from "crypto";
|
|
7463
7952
|
import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
|
|
7464
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
|
+
}
|
|
7465
7970
|
async function runLLMAnalysis(input, previous) {
|
|
7466
7971
|
if (!isLLMAvailable()) {
|
|
7467
7972
|
console.log("[AgentMoss] LLM not configured, skipping deep analysis");
|
|
@@ -7544,7 +8049,23 @@ async function runLLMAnalysis(input, previous) {
|
|
|
7544
8049
|
);
|
|
7545
8050
|
}
|
|
7546
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
|
+
});
|
|
7547
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
|
+
});
|
|
7548
8069
|
if (llmCache.size >= LLM_CACHE_MAX) {
|
|
7549
8070
|
const firstKey = llmCache.keys().next().value;
|
|
7550
8071
|
if (firstKey) llmCache.delete(firstKey);
|
|
@@ -7686,6 +8207,14 @@ function formatHints(previous) {
|
|
|
7686
8207
|
}
|
|
7687
8208
|
async function analyzeWithLLM(prompt, config) {
|
|
7688
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
|
+
};
|
|
7689
8218
|
const provider = detectProvider(config.baseUrl, config.provider);
|
|
7690
8219
|
const extraHeaders = getProviderHeaders(provider);
|
|
7691
8220
|
if (Object.keys(extraHeaders).length > 0) {
|
|
@@ -7707,6 +8236,17 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7707
8236
|
console.error(`[AgentMoss] totalTimeout (${timeoutCfg.totalTimeout}s) exceeded, aborting all LLM calls`);
|
|
7708
8237
|
abortController.abort();
|
|
7709
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
|
+
}
|
|
7710
8250
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
7711
8251
|
if (abortController.signal.aborted) {
|
|
7712
8252
|
break;
|
|
@@ -7720,22 +8260,49 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7720
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" },
|
|
7721
8261
|
{ role: "user", content: prompt }
|
|
7722
8262
|
],
|
|
7723
|
-
signal: abortController.signal
|
|
8263
|
+
signal: abortController.signal,
|
|
8264
|
+
// 私有化网关的额外参数(关思考等)原样透传;空则不传。
|
|
8265
|
+
...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
|
|
7724
8266
|
});
|
|
7725
8267
|
const message = response.choices[0]?.message;
|
|
7726
8268
|
const content = message?.content ?? "";
|
|
7727
8269
|
const finishReason = response.choices[0]?.finish_reason;
|
|
7728
|
-
const
|
|
8270
|
+
const fieldLengths = responseFieldLengths(message);
|
|
7729
8271
|
const usage = response.usage;
|
|
7730
8272
|
if (!content) {
|
|
7731
|
-
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
|
+
}
|
|
7732
8290
|
if (finishReason === "length") {
|
|
7733
|
-
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}`);
|
|
7734
8292
|
throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
|
|
7735
8293
|
}
|
|
7736
|
-
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");
|
|
7737
8296
|
throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
|
|
7738
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
|
+
});
|
|
7739
8306
|
console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
|
|
7740
8307
|
let jsonStr = content.trim();
|
|
7741
8308
|
if (jsonStr.startsWith("```")) {
|
|
@@ -7766,6 +8333,8 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7766
8333
|
clearTimeout(totalTimeoutTimer);
|
|
7767
8334
|
const riskLevel = parsed.riskLevel ?? parsed.risk_level;
|
|
7768
8335
|
const riskType = parsed.riskType ?? parsed.risk_type;
|
|
8336
|
+
breaker.recordSuccess();
|
|
8337
|
+
_recordLlm("success");
|
|
7769
8338
|
return {
|
|
7770
8339
|
allowed: parsed.allowed !== false,
|
|
7771
8340
|
reason: parsed.reason || "LLM \u5206\u6790\u5B8C\u6210",
|
|
@@ -7776,6 +8345,7 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7776
8345
|
violatedLayers: ["L3.1"]
|
|
7777
8346
|
};
|
|
7778
8347
|
} catch (err) {
|
|
8348
|
+
breaker.recordFailure();
|
|
7779
8349
|
if (abortController.signal.aborted) {
|
|
7780
8350
|
console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
|
|
7781
8351
|
break;
|
|
@@ -7808,6 +8378,9 @@ var init_llm_analyzer = __esm({
|
|
|
7808
8378
|
init_template_loader();
|
|
7809
8379
|
init_script_analyzer();
|
|
7810
8380
|
init_script_content_analyzer();
|
|
8381
|
+
init_trace_log();
|
|
8382
|
+
init_metrics();
|
|
8383
|
+
init_circuit_breaker();
|
|
7811
8384
|
llmCache = /* @__PURE__ */ new Map();
|
|
7812
8385
|
LLM_CACHE_MAX = 200;
|
|
7813
8386
|
}
|
|
@@ -7846,8 +8419,8 @@ var init_rule_store = __esm({
|
|
|
7846
8419
|
BrainRuleStore = class {
|
|
7847
8420
|
path;
|
|
7848
8421
|
data;
|
|
7849
|
-
constructor(
|
|
7850
|
-
this.path =
|
|
8422
|
+
constructor(path7) {
|
|
8423
|
+
this.path = path7 || getRulesPath();
|
|
7851
8424
|
this.data = this.load();
|
|
7852
8425
|
}
|
|
7853
8426
|
load() {
|
|
@@ -8300,10 +8873,10 @@ ${reason.slice(0, 500)}
|
|
|
8300
8873
|
const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
|
|
8301
8874
|
let mm;
|
|
8302
8875
|
while ((mm = pathRe.exec(src)) !== null) {
|
|
8303
|
-
const
|
|
8304
|
-
if (
|
|
8305
|
-
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(
|
|
8306
|
-
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);
|
|
8307
8880
|
if (seen.has(gen)) continue;
|
|
8308
8881
|
seen.add(gen);
|
|
8309
8882
|
patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
|
|
@@ -8322,8 +8895,8 @@ ${reason.slice(0, 500)}
|
|
|
8322
8895
|
}
|
|
8323
8896
|
return false;
|
|
8324
8897
|
}
|
|
8325
|
-
generalizePath(
|
|
8326
|
-
const p =
|
|
8898
|
+
generalizePath(path7) {
|
|
8899
|
+
const p = path7.toLowerCase();
|
|
8327
8900
|
if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
|
|
8328
8901
|
return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
|
|
8329
8902
|
}
|
|
@@ -8914,38 +9487,38 @@ function labelEvent(actionDetail) {
|
|
|
8914
9487
|
}
|
|
8915
9488
|
return hits;
|
|
8916
9489
|
}
|
|
8917
|
-
function evaluateLTL(formula,
|
|
9490
|
+
function evaluateLTL(formula, trace2, pos) {
|
|
8918
9491
|
const op = formula[0];
|
|
8919
9492
|
switch (op) {
|
|
8920
9493
|
case "ap":
|
|
8921
|
-
return
|
|
9494
|
+
return trace2[pos].has(formula[1]);
|
|
8922
9495
|
case "!":
|
|
8923
|
-
return !evaluateLTL(formula[1],
|
|
9496
|
+
return !evaluateLTL(formula[1], trace2, pos);
|
|
8924
9497
|
case "&":
|
|
8925
|
-
return evaluateLTL(formula[1],
|
|
9498
|
+
return evaluateLTL(formula[1], trace2, pos) && evaluateLTL(formula[2], trace2, pos);
|
|
8926
9499
|
case "|":
|
|
8927
|
-
return evaluateLTL(formula[1],
|
|
9500
|
+
return evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
|
|
8928
9501
|
case "->":
|
|
8929
|
-
return !evaluateLTL(formula[1],
|
|
9502
|
+
return !evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
|
|
8930
9503
|
case "X":
|
|
8931
|
-
return pos + 1 <
|
|
9504
|
+
return pos + 1 < trace2.length && evaluateLTL(formula[1], trace2, pos + 1);
|
|
8932
9505
|
case "G": {
|
|
8933
|
-
for (let j = pos; j <
|
|
8934
|
-
if (!evaluateLTL(formula[1],
|
|
9506
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
9507
|
+
if (!evaluateLTL(formula[1], trace2, j)) return false;
|
|
8935
9508
|
}
|
|
8936
9509
|
return true;
|
|
8937
9510
|
}
|
|
8938
9511
|
case "F": {
|
|
8939
|
-
for (let j = pos; j <
|
|
8940
|
-
if (evaluateLTL(formula[1],
|
|
9512
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
9513
|
+
if (evaluateLTL(formula[1], trace2, j)) return true;
|
|
8941
9514
|
}
|
|
8942
9515
|
return false;
|
|
8943
9516
|
}
|
|
8944
9517
|
case "U": {
|
|
8945
|
-
for (let j = pos; j <
|
|
8946
|
-
if (evaluateLTL(formula[2],
|
|
9518
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
9519
|
+
if (evaluateLTL(formula[2], trace2, j)) {
|
|
8947
9520
|
for (let k = pos; k < j; k++) {
|
|
8948
|
-
if (!evaluateLTL(formula[1],
|
|
9521
|
+
if (!evaluateLTL(formula[1], trace2, k)) return false;
|
|
8949
9522
|
}
|
|
8950
9523
|
return true;
|
|
8951
9524
|
}
|
|
@@ -8974,11 +9547,11 @@ function checkMCRules(graph) {
|
|
|
8974
9547
|
const mc = loadMC();
|
|
8975
9548
|
const rules = mc.rules || [];
|
|
8976
9549
|
if (rules.length === 0) return violations;
|
|
8977
|
-
const
|
|
9550
|
+
const trace2 = nodes.map((n) => labelEvent(n.actionDetail));
|
|
8978
9551
|
const witnessMode = graph.witnessIdx !== void 0;
|
|
8979
9552
|
for (const rule of rules) {
|
|
8980
9553
|
if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
|
|
8981
|
-
if (ruleViolates(rule,
|
|
9554
|
+
if (ruleViolates(rule, trace2, witnessMode)) {
|
|
8982
9555
|
violations.push({
|
|
8983
9556
|
propertyId: String(rule.id || "mc-ltl"),
|
|
8984
9557
|
reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
|
|
@@ -9169,12 +9742,12 @@ var init_builder = __esm({
|
|
|
9169
9742
|
});
|
|
9170
9743
|
|
|
9171
9744
|
// src/engine/formal-engine/properties.ts
|
|
9172
|
-
function graphFromPath(nodes,
|
|
9745
|
+
function graphFromPath(nodes, path7, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
|
|
9173
9746
|
const byKey = /* @__PURE__ */ new Map();
|
|
9174
9747
|
for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
|
|
9175
9748
|
const gNodes = [];
|
|
9176
9749
|
const gEdges = [];
|
|
9177
|
-
for (const item of
|
|
9750
|
+
for (const item of path7) {
|
|
9178
9751
|
const n = byKey.get(`${item.sessionId}#${item.seq}`);
|
|
9179
9752
|
gNodes.push({
|
|
9180
9753
|
session_id: item.sessionId,
|
|
@@ -9240,22 +9813,22 @@ function checkCrossSessionChain(graph) {
|
|
|
9240
9813
|
if (witness !== void 0) {
|
|
9241
9814
|
if (nodes[witness].stage !== stages[stages.length - 1]) continue;
|
|
9242
9815
|
let matched = 0;
|
|
9243
|
-
const
|
|
9816
|
+
const path7 = [];
|
|
9244
9817
|
for (let k = 0; k < witness; k++) {
|
|
9245
9818
|
const n = nodes[k];
|
|
9246
9819
|
if (matched < stages.length - 1 && n.stage === stages[matched]) {
|
|
9247
9820
|
matched += 1;
|
|
9248
|
-
|
|
9821
|
+
path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9249
9822
|
}
|
|
9250
9823
|
}
|
|
9251
9824
|
if (matched < stages.length - 1) continue;
|
|
9252
|
-
|
|
9825
|
+
path7.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
|
|
9253
9826
|
violations.push({
|
|
9254
9827
|
propertyId: "cross-" + chain.id,
|
|
9255
9828
|
reason: chain.reason,
|
|
9256
9829
|
riskLevel: chain.riskLevel,
|
|
9257
|
-
path:
|
|
9258
|
-
graph: graphFromPath(nodes,
|
|
9830
|
+
path: path7,
|
|
9831
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9259
9832
|
property_id: "cross-" + chain.id,
|
|
9260
9833
|
property_short: "P1",
|
|
9261
9834
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -9265,11 +9838,11 @@ function checkCrossSessionChain(graph) {
|
|
|
9265
9838
|
} else {
|
|
9266
9839
|
let matched = 0;
|
|
9267
9840
|
let stageIdx = 0;
|
|
9268
|
-
const
|
|
9841
|
+
const path7 = [];
|
|
9269
9842
|
for (const n of nodes) {
|
|
9270
9843
|
if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
|
|
9271
9844
|
matched += 1;
|
|
9272
|
-
|
|
9845
|
+
path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9273
9846
|
stageIdx += 1;
|
|
9274
9847
|
if (matched >= stages.length) break;
|
|
9275
9848
|
}
|
|
@@ -9279,8 +9852,8 @@ function checkCrossSessionChain(graph) {
|
|
|
9279
9852
|
propertyId: "cross-" + chain.id,
|
|
9280
9853
|
reason: chain.reason,
|
|
9281
9854
|
riskLevel: chain.riskLevel,
|
|
9282
|
-
path:
|
|
9283
|
-
graph: graphFromPath(nodes,
|
|
9855
|
+
path: path7,
|
|
9856
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9284
9857
|
property_id: "cross-" + chain.id,
|
|
9285
9858
|
property_short: "P1",
|
|
9286
9859
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -9327,7 +9900,7 @@ function checkSensitiveDataFlow(graph) {
|
|
|
9327
9900
|
}
|
|
9328
9901
|
}
|
|
9329
9902
|
}
|
|
9330
|
-
const
|
|
9903
|
+
const tracePath2 = (idx) => {
|
|
9331
9904
|
const chain = [idx];
|
|
9332
9905
|
const seen = /* @__PURE__ */ new Set([idx]);
|
|
9333
9906
|
while (true) {
|
|
@@ -9386,7 +9959,7 @@ function checkSensitiveDataFlow(graph) {
|
|
|
9386
9959
|
for (const i of candidates) {
|
|
9387
9960
|
const n = nodes[i];
|
|
9388
9961
|
if (tainted.has(i) && EXFIL_RE.test(n.actionDetail)) {
|
|
9389
|
-
const chain =
|
|
9962
|
+
const chain = tracePath2(i);
|
|
9390
9963
|
violations.push({
|
|
9391
9964
|
propertyId: "sensitive-data-flow",
|
|
9392
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`,
|
|
@@ -9501,7 +10074,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
9501
10074
|
if (candidates.length > 0) {
|
|
9502
10075
|
const pre = nodes[candidates[candidates.length - 1]];
|
|
9503
10076
|
const post = nodes[firstEv];
|
|
9504
|
-
const
|
|
10077
|
+
const path7 = [
|
|
9505
10078
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
9506
10079
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
9507
10080
|
];
|
|
@@ -9509,8 +10082,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
9509
10082
|
propertyId: "no-exfil-after-privesc",
|
|
9510
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",
|
|
9511
10084
|
riskLevel: "critical",
|
|
9512
|
-
path:
|
|
9513
|
-
graph: graphFromPath(nodes,
|
|
10085
|
+
path: path7,
|
|
10086
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9514
10087
|
property_id: "no-exfil-after-privesc",
|
|
9515
10088
|
property_short: "P4",
|
|
9516
10089
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9527,7 +10100,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
9527
10100
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
9528
10101
|
if (!isExfilNode(nodes[j])) continue;
|
|
9529
10102
|
if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
|
|
9530
|
-
const
|
|
10103
|
+
const path7 = [
|
|
9531
10104
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
9532
10105
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
9533
10106
|
];
|
|
@@ -9535,8 +10108,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
9535
10108
|
propertyId: "no-exfil-after-privesc",
|
|
9536
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",
|
|
9537
10110
|
riskLevel: "critical",
|
|
9538
|
-
path:
|
|
9539
|
-
graph: graphFromPath(nodes,
|
|
10111
|
+
path: path7,
|
|
10112
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9540
10113
|
property_id: "no-exfil-after-privesc",
|
|
9541
10114
|
property_short: "P4",
|
|
9542
10115
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9568,7 +10141,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9568
10141
|
}
|
|
9569
10142
|
if (pre) {
|
|
9570
10143
|
const post = nodes[firstEv];
|
|
9571
|
-
const
|
|
10144
|
+
const path7 = [
|
|
9572
10145
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
9573
10146
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
9574
10147
|
];
|
|
@@ -9576,8 +10149,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9576
10149
|
propertyId: "no-exfil-after-credential",
|
|
9577
10150
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
9578
10151
|
riskLevel: "critical",
|
|
9579
|
-
path:
|
|
9580
|
-
graph: graphFromPath(nodes,
|
|
10152
|
+
path: path7,
|
|
10153
|
+
graph: graphFromPath(nodes, path7, "data", {
|
|
9581
10154
|
property_id: "no-exfil-after-credential",
|
|
9582
10155
|
property_short: "P5",
|
|
9583
10156
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9593,7 +10166,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9593
10166
|
if (!isCredNode(nodes[i])) continue;
|
|
9594
10167
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
9595
10168
|
if (isExfilNode(nodes[j])) {
|
|
9596
|
-
const
|
|
10169
|
+
const path7 = [
|
|
9597
10170
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
9598
10171
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
9599
10172
|
];
|
|
@@ -9601,8 +10174,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
9601
10174
|
propertyId: "no-exfil-after-credential",
|
|
9602
10175
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
9603
10176
|
riskLevel: "critical",
|
|
9604
|
-
path:
|
|
9605
|
-
graph: graphFromPath(nodes,
|
|
10177
|
+
path: path7,
|
|
10178
|
+
graph: graphFromPath(nodes, path7, "data", {
|
|
9606
10179
|
property_id: "no-exfil-after-credential",
|
|
9607
10180
|
property_short: "P5",
|
|
9608
10181
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -9761,13 +10334,13 @@ function checkSensitiveDataAggregation(graph) {
|
|
|
9761
10334
|
if (!isExfilNode(n)) continue;
|
|
9762
10335
|
const srcs = sourcesFor(i);
|
|
9763
10336
|
if (srcs.size >= 2) {
|
|
9764
|
-
const
|
|
10337
|
+
const path7 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
9765
10338
|
violations.push({
|
|
9766
10339
|
propertyId: "sensitive-data-aggregation",
|
|
9767
10340
|
reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
|
|
9768
10341
|
riskLevel: "critical",
|
|
9769
|
-
path:
|
|
9770
|
-
graph: graphFromPath(nodes,
|
|
10342
|
+
path: path7,
|
|
10343
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9771
10344
|
property_id: "sensitive-data-aggregation",
|
|
9772
10345
|
property_short: "P8",
|
|
9773
10346
|
property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
|
|
@@ -10226,11 +10799,11 @@ var init_stateful = __esm({
|
|
|
10226
10799
|
}
|
|
10227
10800
|
}
|
|
10228
10801
|
chainPath(stages) {
|
|
10229
|
-
const
|
|
10802
|
+
const path7 = [];
|
|
10230
10803
|
let want = stages[0];
|
|
10231
10804
|
for (const n of this.nodes_) {
|
|
10232
10805
|
if (n.stage === want) {
|
|
10233
|
-
|
|
10806
|
+
path7.push({
|
|
10234
10807
|
sessionId: n.sessionId,
|
|
10235
10808
|
seq: n.seq,
|
|
10236
10809
|
stage: n.stage,
|
|
@@ -10246,12 +10819,12 @@ var init_stateful = __esm({
|
|
|
10246
10819
|
}
|
|
10247
10820
|
}
|
|
10248
10821
|
}
|
|
10249
|
-
return
|
|
10822
|
+
return path7;
|
|
10250
10823
|
}
|
|
10251
10824
|
/** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
|
|
10252
10825
|
buildChainGraph(stages, chainId) {
|
|
10253
|
-
const
|
|
10254
|
-
const gNodes =
|
|
10826
|
+
const path7 = this.chainPath(stages);
|
|
10827
|
+
const gNodes = path7.map((p, i) => {
|
|
10255
10828
|
const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
|
|
10256
10829
|
return {
|
|
10257
10830
|
session_id: p.sessionId,
|
|
@@ -10502,16 +11075,42 @@ var init_stateful = __esm({
|
|
|
10502
11075
|
});
|
|
10503
11076
|
|
|
10504
11077
|
// src/engine/formal-engine/chain_state.ts
|
|
10505
|
-
import * as
|
|
11078
|
+
import * as fs5 from "fs";
|
|
10506
11079
|
import * as os2 from "os";
|
|
10507
|
-
import * as
|
|
11080
|
+
import * as path5 from "path";
|
|
10508
11081
|
import { createHash as createHash4 } from "crypto";
|
|
10509
11082
|
function defaultStateDbPath() {
|
|
10510
|
-
const dir = process.env.AGENT_MOSS_STATE_DIR ||
|
|
11083
|
+
const dir = process.env.AGENT_MOSS_STATE_DIR || path5.join(os2.homedir(), ".agentmoss");
|
|
10511
11084
|
const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
|
|
10512
|
-
return
|
|
11085
|
+
return path5.join(dir, `stateful_chains_${tag}.json`);
|
|
10513
11086
|
}
|
|
10514
|
-
|
|
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;
|
|
10515
11114
|
var init_chain_state = __esm({
|
|
10516
11115
|
"src/engine/formal-engine/chain_state.ts"() {
|
|
10517
11116
|
"use strict";
|
|
@@ -10522,15 +11121,33 @@ var init_chain_state = __esm({
|
|
|
10522
11121
|
filePath;
|
|
10523
11122
|
data;
|
|
10524
11123
|
_timer = null;
|
|
10525
|
-
|
|
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();
|
|
10526
11143
|
constructor(filePath = "") {
|
|
10527
11144
|
this.filePath = filePath || defaultStateDbPath();
|
|
10528
11145
|
this.data = this._read();
|
|
10529
11146
|
}
|
|
10530
11147
|
_read() {
|
|
10531
11148
|
try {
|
|
10532
|
-
if (
|
|
10533
|
-
const raw =
|
|
11149
|
+
if (fs5.existsSync(this.filePath)) {
|
|
11150
|
+
const raw = fs5.readFileSync(this.filePath, "utf-8");
|
|
10534
11151
|
return JSON.parse(raw);
|
|
10535
11152
|
}
|
|
10536
11153
|
} catch {
|
|
@@ -10543,12 +11160,22 @@ var init_chain_state = __esm({
|
|
|
10543
11160
|
this._timer = setTimeout(() => {
|
|
10544
11161
|
this._timer = null;
|
|
10545
11162
|
try {
|
|
10546
|
-
|
|
11163
|
+
this._syncDirtyToData();
|
|
11164
|
+
ensurePrivateDir(path5.dirname(this.filePath));
|
|
10547
11165
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
10548
11166
|
} catch {
|
|
10549
11167
|
}
|
|
10550
11168
|
}, this._flushDelayMs);
|
|
10551
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
|
+
}
|
|
10552
11179
|
/** 立即落盘(测试/关停前调用,保证状态不丢)。 */
|
|
10553
11180
|
flush() {
|
|
10554
11181
|
if (this._timer !== null) {
|
|
@@ -10556,29 +11183,39 @@ var init_chain_state = __esm({
|
|
|
10556
11183
|
this._timer = null;
|
|
10557
11184
|
}
|
|
10558
11185
|
try {
|
|
10559
|
-
|
|
11186
|
+
this._syncDirtyToData();
|
|
11187
|
+
ensurePrivateDir(path5.dirname(this.filePath));
|
|
10560
11188
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
10561
11189
|
} catch {
|
|
10562
11190
|
}
|
|
10563
11191
|
}
|
|
10564
11192
|
load(agentId) {
|
|
11193
|
+
const cached2 = this._trackers.get(agentId);
|
|
11194
|
+
if (cached2) return cached2;
|
|
10565
11195
|
const entry = this.data[agentId];
|
|
10566
11196
|
if (!entry) return null;
|
|
10567
11197
|
const t = new StatefulChainTracker(agentId);
|
|
10568
11198
|
t.restore(entry.state);
|
|
11199
|
+
this._trackers.set(agentId, t);
|
|
10569
11200
|
return t;
|
|
10570
11201
|
}
|
|
10571
11202
|
save(tracker) {
|
|
10572
|
-
this.
|
|
10573
|
-
|
|
10574
|
-
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
10575
|
-
};
|
|
11203
|
+
this._trackers.set(tracker.agentId, tracker);
|
|
11204
|
+
this._dirty.add(tracker.agentId);
|
|
10576
11205
|
this._scheduleWrite();
|
|
10577
11206
|
}
|
|
10578
11207
|
delete(agentId) {
|
|
11208
|
+
this._trackers.delete(agentId);
|
|
11209
|
+
this._dirty.delete(agentId);
|
|
10579
11210
|
delete this.data[agentId];
|
|
10580
11211
|
this._scheduleWrite();
|
|
10581
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
|
+
}
|
|
10582
11219
|
applyAction(agentId, aNext, sessionId, isError = false, sourceAgent = "", instanceId = "") {
|
|
10583
11220
|
const t = this.load(agentId) || new StatefulChainTracker(agentId);
|
|
10584
11221
|
const r = t.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
|
|
@@ -10593,6 +11230,8 @@ var init_chain_state = __esm({
|
|
|
10593
11230
|
return r;
|
|
10594
11231
|
}
|
|
10595
11232
|
};
|
|
11233
|
+
_store = null;
|
|
11234
|
+
_exitHookRegistered = false;
|
|
10596
11235
|
}
|
|
10597
11236
|
});
|
|
10598
11237
|
|
|
@@ -10700,6 +11339,14 @@ function _resetBrainForTest() {
|
|
|
10700
11339
|
async function runAnalysis(input) {
|
|
10701
11340
|
const observedFormalLayers = [];
|
|
10702
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
|
+
}
|
|
10703
11350
|
const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
|
|
10704
11351
|
const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
|
|
10705
11352
|
if (heuristicResult && !heuristicResult.allowed) {
|
|
@@ -10843,6 +11490,14 @@ async function runAnalysis(input) {
|
|
|
10843
11490
|
}
|
|
10844
11491
|
}
|
|
10845
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
|
+
}
|
|
10846
11501
|
const l1FileAccessHit = !!(heuristicResult && !heuristicResult.allowed && heuristicResult.riskType === "file_access");
|
|
10847
11502
|
const effectiveResult = logicResult && !logicResult.allowed ? logicResult : l1FileAccessHit ? heuristicResult : null;
|
|
10848
11503
|
if (effectiveResult) {
|
|
@@ -11072,6 +11727,7 @@ var init_coordinator = __esm({
|
|
|
11072
11727
|
init_llm_analyzer();
|
|
11073
11728
|
init_script_content_analyzer();
|
|
11074
11729
|
init_config();
|
|
11730
|
+
init_trace_log();
|
|
11075
11731
|
init_runtime_config();
|
|
11076
11732
|
init_agents();
|
|
11077
11733
|
init_scenarios();
|
|
@@ -11308,6 +11964,8 @@ var AnalyzeResponseSchema = z.object({
|
|
|
11308
11964
|
analysis_duration_ms: z.number().default(0),
|
|
11309
11965
|
// 组合攻击链反例路径:每步 [session_id, seq, stage, timestamp],含真实发生时间
|
|
11310
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([]),
|
|
11311
11969
|
// 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
|
|
11312
11970
|
violation_graph: z.object({
|
|
11313
11971
|
// 性质元信息(前端展示"违反了哪条性质")
|
|
@@ -11347,12 +12005,18 @@ var AnalyzeResponseSchema = z.object({
|
|
|
11347
12005
|
}).nullable().default(null)
|
|
11348
12006
|
});
|
|
11349
12007
|
var HealthResponseSchema = z.object({
|
|
12008
|
+
// healthy | degraded(2026-11):degraded 表示服务可用但**某项安全能力已降级**
|
|
12009
|
+
// (链状态触顶、LLM 熔断)。任何探活/监控只看 status 就能发现异常。
|
|
11350
12010
|
status: z.string().default("healthy"),
|
|
12011
|
+
// 降级原因(status=degraded 时非空)
|
|
12012
|
+
degraded: z.array(z.string()).default([]),
|
|
11351
12013
|
version: z.string().default(version),
|
|
11352
12014
|
// 归属实例标识:值来自 env AGENT_MOSS_INSTANCE(spawn/systemd 注入),默认空串。
|
|
11353
12015
|
// 多个 agentmoss 同机并存时,调用方按 instance 过滤避免连到别人的进程。
|
|
11354
12016
|
// 空=未配置(独立部署或旧版),调用方可选择兼容或严格过滤。
|
|
11355
|
-
instance: z.string().default("")
|
|
12017
|
+
instance: z.string().default(""),
|
|
12018
|
+
// 运行态指标(2026-11 增强):事件循环延迟、并发池占用、链状态规模。
|
|
12019
|
+
metrics: z.record(z.unknown()).default({})
|
|
11356
12020
|
});
|
|
11357
12021
|
var ReviewRequestSchema = z.object({
|
|
11358
12022
|
agent_id: z.string().default("").describe("\u76EE\u6807 agent \u6807\u8BC6\uFF08\u51B3\u5B9A\u72B6\u6001\u5E93\u5206\u6876\uFF09"),
|
|
@@ -11833,7 +12497,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
11833
12497
|
|
|
11834
12498
|
// src/actrail.ts
|
|
11835
12499
|
init_esm_shims();
|
|
11836
|
-
import * as
|
|
12500
|
+
import * as fs6 from "fs";
|
|
11837
12501
|
|
|
11838
12502
|
// src/infra/esm-require.ts
|
|
11839
12503
|
init_esm_shims();
|
|
@@ -11864,7 +12528,7 @@ function getStoragePath() {
|
|
|
11864
12528
|
function reportEnforcementEvent(opts) {
|
|
11865
12529
|
if (!isEnabled()) return false;
|
|
11866
12530
|
const storagePath = getStoragePath();
|
|
11867
|
-
if (!
|
|
12531
|
+
if (!fs6.existsSync(storagePath)) return false;
|
|
11868
12532
|
try {
|
|
11869
12533
|
let Database;
|
|
11870
12534
|
try {
|
|
@@ -11944,6 +12608,7 @@ function reportEnforcementEvent(opts) {
|
|
|
11944
12608
|
|
|
11945
12609
|
// src/routes.ts
|
|
11946
12610
|
init_formal_engine();
|
|
12611
|
+
init_circuit_breaker();
|
|
11947
12612
|
|
|
11948
12613
|
// src/engine/formal-engine/pattern_miner.ts
|
|
11949
12614
|
init_esm_shims();
|
|
@@ -12026,10 +12691,10 @@ function mineDangerousPatterns(sessions, minSup = 2, maxLen = 4) {
|
|
|
12026
12691
|
|
|
12027
12692
|
// src/agent-gate-reader.ts
|
|
12028
12693
|
init_esm_shims();
|
|
12029
|
-
import * as
|
|
12694
|
+
import * as fs7 from "fs";
|
|
12030
12695
|
import * as os3 from "os";
|
|
12031
|
-
import * as
|
|
12032
|
-
var DEFAULT_AGENTGATE_SQLITE =
|
|
12696
|
+
import * as path6 from "path";
|
|
12697
|
+
var DEFAULT_AGENTGATE_SQLITE = path6.join(
|
|
12033
12698
|
os3.homedir(),
|
|
12034
12699
|
".local",
|
|
12035
12700
|
"share",
|
|
@@ -12045,10 +12710,10 @@ function normalizeAction(row) {
|
|
|
12045
12710
|
function readJsonDir(dirPath, limit = 1e5) {
|
|
12046
12711
|
const sessions = /* @__PURE__ */ new Map();
|
|
12047
12712
|
try {
|
|
12048
|
-
const files =
|
|
12713
|
+
const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
|
|
12049
12714
|
for (const f of files.slice(-200)) {
|
|
12050
12715
|
const sid = f.replace(/\.json$/, "");
|
|
12051
|
-
const raw =
|
|
12716
|
+
const raw = fs7.readFileSync(path6.join(dirPath, f), "utf-8");
|
|
12052
12717
|
const arr = JSON.parse(raw);
|
|
12053
12718
|
if (!Array.isArray(arr)) continue;
|
|
12054
12719
|
for (const item of arr) {
|
|
@@ -12105,7 +12770,7 @@ function readSqlite(dbPath, limit = 1e5) {
|
|
|
12105
12770
|
function loadAgentGateSessions(dbPath = "") {
|
|
12106
12771
|
if (dbPath) {
|
|
12107
12772
|
try {
|
|
12108
|
-
if (
|
|
12773
|
+
if (fs7.statSync(dbPath).isDirectory()) {
|
|
12109
12774
|
return readJsonDir(dbPath);
|
|
12110
12775
|
}
|
|
12111
12776
|
} catch {
|
|
@@ -12116,7 +12781,7 @@ function loadAgentGateSessions(dbPath = "") {
|
|
|
12116
12781
|
}
|
|
12117
12782
|
const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
|
|
12118
12783
|
if (sql.length > 0) return sql;
|
|
12119
|
-
const jsonDefault =
|
|
12784
|
+
const jsonDefault = path6.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
|
|
12120
12785
|
return readJsonDir(jsonDefault);
|
|
12121
12786
|
}
|
|
12122
12787
|
|
|
@@ -12191,16 +12856,105 @@ function normalizeObservablePayload(body) {
|
|
|
12191
12856
|
init_rule_store();
|
|
12192
12857
|
init_skill_manager();
|
|
12193
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();
|
|
12194
12908
|
import { join as join18, dirname as dirname12 } from "path";
|
|
12195
12909
|
import { fileURLToPath as fileURLToPath10 } from "url";
|
|
12196
12910
|
var __dirname9 = dirname12(fileURLToPath10(import.meta.url));
|
|
12197
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
|
+
}
|
|
12198
12948
|
return c.json(HealthResponseSchema.parse({
|
|
12199
|
-
|
|
12949
|
+
status: degraded.length ? "degraded" : "healthy",
|
|
12950
|
+
degraded,
|
|
12951
|
+
instance: process.env.AGENT_MOSS_INSTANCE || "",
|
|
12952
|
+
metrics
|
|
12200
12953
|
}));
|
|
12201
12954
|
}
|
|
12202
12955
|
async function analyzeRoute(c) {
|
|
12203
12956
|
const t0 = performance.now();
|
|
12957
|
+
const degradedNotes = [];
|
|
12204
12958
|
try {
|
|
12205
12959
|
const body = await c.req.json();
|
|
12206
12960
|
const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
|
|
@@ -12228,6 +12982,20 @@ async function analyzeRoute(c) {
|
|
|
12228
12982
|
const instanceId = String(
|
|
12229
12983
|
req.instance_id || req.metadata?.instance_id || ""
|
|
12230
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
|
+
});
|
|
12231
12999
|
const result = await analyze({
|
|
12232
13000
|
sessionId: req.session_id,
|
|
12233
13001
|
promptSession: req.prompt_session,
|
|
@@ -12287,6 +13055,29 @@ async function analyzeRoute(c) {
|
|
|
12287
13055
|
llmLogPath: req.metadata?.llm_log_path
|
|
12288
13056
|
});
|
|
12289
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
|
+
});
|
|
12290
13081
|
try {
|
|
12291
13082
|
reportEnforcementEvent({
|
|
12292
13083
|
traceId: req.session_id,
|
|
@@ -12318,6 +13109,20 @@ async function analyzeRoute(c) {
|
|
|
12318
13109
|
// 来源:真实 agent(桶 key 可能是 __system__)
|
|
12319
13110
|
instanceId
|
|
12320
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
|
+
}
|
|
12321
13126
|
const judgment = incMatchedToDeny(inc);
|
|
12322
13127
|
if (judgment) {
|
|
12323
13128
|
const layers = [...result.violated_layers];
|
|
@@ -12360,7 +13165,9 @@ async function analyzeRoute(c) {
|
|
|
12360
13165
|
confidence: result.confidence,
|
|
12361
13166
|
analysis_duration_ms: Math.round(durationMs * 10) / 10,
|
|
12362
13167
|
violation_chain: result.violation_chain ?? [],
|
|
12363
|
-
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
|
|
12364
13171
|
})
|
|
12365
13172
|
);
|
|
12366
13173
|
} catch (err) {
|
|
@@ -12379,10 +13186,8 @@ async function analyzeRoute(c) {
|
|
|
12379
13186
|
return c.json({ detail: `Internal server error (ref: ${ref})`, error: "Internal error" }, 500);
|
|
12380
13187
|
}
|
|
12381
13188
|
}
|
|
12382
|
-
var reviewStore = null;
|
|
12383
13189
|
function getChainStateStoreFor(_agentId) {
|
|
12384
|
-
|
|
12385
|
-
return reviewStore;
|
|
13190
|
+
return getChainStateStore();
|
|
12386
13191
|
}
|
|
12387
13192
|
function incMatchedToDeny(inc) {
|
|
12388
13193
|
if (inc.matched) {
|
|
@@ -12981,6 +13786,8 @@ function createConsoleRouter() {
|
|
|
12981
13786
|
|
|
12982
13787
|
// src/server.ts
|
|
12983
13788
|
init_runtime_config();
|
|
13789
|
+
init_metrics();
|
|
13790
|
+
init_formal_engine();
|
|
12984
13791
|
init_rules_mode();
|
|
12985
13792
|
init_rules_loader();
|
|
12986
13793
|
function logDeploymentSelfCheck() {
|
|
@@ -13061,6 +13868,10 @@ var PooledLimiter = class {
|
|
|
13061
13868
|
if (cur <= 1) this.counts.delete(key);
|
|
13062
13869
|
else this.counts.set(key, cur - 1);
|
|
13063
13870
|
}
|
|
13871
|
+
/** 当前各池占用快照(健康检查用,对齐 Python `_PooledLimiter.snapshot`)。 */
|
|
13872
|
+
snapshot() {
|
|
13873
|
+
return Object.fromEntries(this.counts);
|
|
13874
|
+
}
|
|
13064
13875
|
};
|
|
13065
13876
|
var RateLimiter = class {
|
|
13066
13877
|
constructor(qps, burst) {
|
|
@@ -13104,9 +13915,11 @@ function createApp() {
|
|
|
13104
13915
|
)
|
|
13105
13916
|
);
|
|
13106
13917
|
const pools = new PooledLimiter();
|
|
13918
|
+
registerPools(pools);
|
|
13919
|
+
startLoopMonitor();
|
|
13107
13920
|
const limiter = new RateLimiter(rateLimitQps());
|
|
13108
13921
|
app.use("*", async (c, next) => {
|
|
13109
|
-
const
|
|
13922
|
+
const path7 = new URL(c.req.url).pathname;
|
|
13110
13923
|
const method = c.req.method.toUpperCase();
|
|
13111
13924
|
if (method === "OPTIONS") return next();
|
|
13112
13925
|
const maxBody = maxBodyBytes();
|
|
@@ -13120,16 +13933,16 @@ function createApp() {
|
|
|
13120
13933
|
if (originCheckEnabled()) {
|
|
13121
13934
|
const origin = c.req.header("origin") || "";
|
|
13122
13935
|
if (origin && !originAllowed(origin, c.req.header("host") || "")) {
|
|
13123
|
-
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}`);
|
|
13124
13937
|
return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
|
|
13125
13938
|
}
|
|
13126
13939
|
}
|
|
13127
|
-
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers,
|
|
13128
|
-
const isPublicPage = !
|
|
13940
|
+
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path7);
|
|
13941
|
+
const isPublicPage = !path7.startsWith("/console/api") && (path7 === "/console" || path7.startsWith("/console/"));
|
|
13129
13942
|
if (!okAuth && !isPublicPage) {
|
|
13130
13943
|
return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
|
|
13131
13944
|
}
|
|
13132
|
-
if (limiter.enabled &&
|
|
13945
|
+
if (limiter.enabled && path7.startsWith("/api/")) {
|
|
13133
13946
|
const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
|
|
13134
13947
|
if (!limiter.allow(key)) {
|
|
13135
13948
|
return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
|
|
@@ -13163,7 +13976,7 @@ function createApp() {
|
|
|
13163
13976
|
return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
|
|
13164
13977
|
}
|
|
13165
13978
|
}
|
|
13166
|
-
const pool = poolOf(
|
|
13979
|
+
const pool = poolOf(path7);
|
|
13167
13980
|
if (!take(`pool:${pool}`, poolLimit(pool))) {
|
|
13168
13981
|
const qkey = principal ? "p:" + principalHash(principal) : "c:local";
|
|
13169
13982
|
const [qn, abusive] = noteQueueReject(qkey);
|
|
@@ -13180,6 +13993,23 @@ function createApp() {
|
|
|
13180
13993
|
while (keys.length) pools.release(keys.pop());
|
|
13181
13994
|
}
|
|
13182
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
|
+
});
|
|
13183
14013
|
app.get("/api/v1/health", healthRoute);
|
|
13184
14014
|
app.post("/api/v1/analyze", analyzeRoute);
|
|
13185
14015
|
app.post("/api/v1/review", reviewRoute);
|