@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/cli.js
CHANGED
|
@@ -408,22 +408,22 @@ function loadToolRegistry() {
|
|
|
408
408
|
data.tools = tools;
|
|
409
409
|
return data;
|
|
410
410
|
}
|
|
411
|
-
function scanStructEntry(cat, value,
|
|
411
|
+
function scanStructEntry(cat, value, path7) {
|
|
412
412
|
if (cat === "skills") {
|
|
413
413
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
414
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
414
|
+
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`);
|
|
415
415
|
return null;
|
|
416
416
|
}
|
|
417
417
|
const out = {};
|
|
418
418
|
for (const [skCat, skills] of Object.entries(value)) {
|
|
419
419
|
if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
|
|
420
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
420
|
+
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`);
|
|
421
421
|
continue;
|
|
422
422
|
}
|
|
423
423
|
const keep = {};
|
|
424
424
|
for (const [name, kws] of Object.entries(skills)) {
|
|
425
425
|
if (Array.isArray(kws)) keep[name] = kws;
|
|
426
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
426
|
+
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`);
|
|
427
427
|
}
|
|
428
428
|
if (Object.keys(keep).length > 0) out[skCat] = keep;
|
|
429
429
|
}
|
|
@@ -431,37 +431,37 @@ function scanStructEntry(cat, value, path6) {
|
|
|
431
431
|
}
|
|
432
432
|
if (cat === "ltl_rules") {
|
|
433
433
|
if (!Array.isArray(value)) {
|
|
434
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
434
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
435
435
|
return null;
|
|
436
436
|
}
|
|
437
437
|
const keep = value.filter((r) => r && typeof r === "object" && r.id);
|
|
438
438
|
if (keep.length !== value.length) {
|
|
439
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
439
|
+
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`);
|
|
440
440
|
}
|
|
441
441
|
return keep.length > 0 ? keep : null;
|
|
442
442
|
}
|
|
443
443
|
if (cat === "tools") {
|
|
444
444
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
445
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
445
|
+
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`);
|
|
446
446
|
return null;
|
|
447
447
|
}
|
|
448
448
|
const keep = {};
|
|
449
449
|
for (const [k, v] of Object.entries(value)) {
|
|
450
450
|
if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
|
|
451
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
451
|
+
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
452
452
|
}
|
|
453
453
|
return Object.keys(keep).length > 0 ? keep : null;
|
|
454
454
|
}
|
|
455
455
|
return null;
|
|
456
456
|
}
|
|
457
|
-
function scanRulesFile(
|
|
457
|
+
function scanRulesFile(path7, kind) {
|
|
458
458
|
const out = {};
|
|
459
459
|
const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
|
|
460
460
|
let parsed;
|
|
461
461
|
try {
|
|
462
|
-
parsed = JSON.parse(readFileSync2(
|
|
462
|
+
parsed = JSON.parse(readFileSync2(path7, "utf-8"));
|
|
463
463
|
} catch (e) {
|
|
464
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
464
|
+
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}`);
|
|
465
465
|
return out;
|
|
466
466
|
}
|
|
467
467
|
const classifyFlat = (r) => {
|
|
@@ -485,44 +485,44 @@ function scanRulesFile(path6, kind) {
|
|
|
485
485
|
}
|
|
486
486
|
if (flatBad > 0) {
|
|
487
487
|
console.warn(
|
|
488
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
488
|
+
`[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`
|
|
489
489
|
);
|
|
490
490
|
}
|
|
491
491
|
} else {
|
|
492
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
492
|
+
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`);
|
|
493
493
|
return out;
|
|
494
494
|
}
|
|
495
495
|
for (const [cat, rules] of pairs) {
|
|
496
496
|
if (String(cat).startsWith("_")) continue;
|
|
497
497
|
if (STRUCT_KEYS.includes(cat)) {
|
|
498
|
-
const got = scanStructEntry(cat, rules,
|
|
498
|
+
const got = scanStructEntry(cat, rules, path7);
|
|
499
499
|
if (got !== null) out[cat] = got;
|
|
500
500
|
continue;
|
|
501
501
|
}
|
|
502
502
|
const required = EXTRA_CATEGORIES[cat];
|
|
503
503
|
if (!required) {
|
|
504
504
|
console.warn(
|
|
505
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
505
|
+
`[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`
|
|
506
506
|
);
|
|
507
507
|
continue;
|
|
508
508
|
}
|
|
509
509
|
if (rules && typeof rules === "object" && !Array.isArray(rules)) {
|
|
510
510
|
console.error(
|
|
511
|
-
`[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${
|
|
511
|
+
`[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
|
|
512
512
|
\u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
|
|
513
513
|
\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`
|
|
514
514
|
);
|
|
515
515
|
continue;
|
|
516
516
|
}
|
|
517
517
|
if (!Array.isArray(rules)) {
|
|
518
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
518
|
+
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`);
|
|
519
519
|
continue;
|
|
520
520
|
}
|
|
521
521
|
const items = [];
|
|
522
522
|
for (const r of rules) {
|
|
523
523
|
if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
|
|
524
524
|
console.warn(
|
|
525
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
525
|
+
`[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`
|
|
526
526
|
);
|
|
527
527
|
continue;
|
|
528
528
|
}
|
|
@@ -532,7 +532,7 @@ function scanRulesFile(path6, kind) {
|
|
|
532
532
|
}
|
|
533
533
|
if (Object.keys(out).length > 0) {
|
|
534
534
|
console.info(
|
|
535
|
-
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${
|
|
535
|
+
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path7}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
|
|
536
536
|
);
|
|
537
537
|
}
|
|
538
538
|
return out;
|
|
@@ -955,10 +955,10 @@ function readExplicitToken() {
|
|
|
955
955
|
if (tok) return tok;
|
|
956
956
|
const fdTok = readFdToken();
|
|
957
957
|
if (fdTok) return fdTok;
|
|
958
|
-
const
|
|
959
|
-
if (
|
|
958
|
+
const path7 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
|
|
959
|
+
if (path7) {
|
|
960
960
|
try {
|
|
961
|
-
return readFileSync4(
|
|
961
|
+
return readFileSync4(path7, "utf-8").trim();
|
|
962
962
|
} catch {
|
|
963
963
|
return "";
|
|
964
964
|
}
|
|
@@ -966,23 +966,23 @@ function readExplicitToken() {
|
|
|
966
966
|
return "";
|
|
967
967
|
}
|
|
968
968
|
function ensureAutoToken() {
|
|
969
|
-
const
|
|
969
|
+
const path7 = autoTokenPath();
|
|
970
970
|
try {
|
|
971
|
-
if (existsSync3(
|
|
972
|
-
const tok2 = readFileSync4(
|
|
971
|
+
if (existsSync3(path7) && !lstatSync(path7).isSymbolicLink()) {
|
|
972
|
+
const tok2 = readFileSync4(path7, "utf-8").trim();
|
|
973
973
|
if (tok2) {
|
|
974
974
|
try {
|
|
975
|
-
chmodSync(
|
|
975
|
+
chmodSync(path7, 384);
|
|
976
976
|
} catch {
|
|
977
977
|
}
|
|
978
978
|
return tok2;
|
|
979
979
|
}
|
|
980
980
|
}
|
|
981
981
|
const tok = randomBytes(32).toString("base64url");
|
|
982
|
-
ensurePrivateDir(dirname2(
|
|
983
|
-
if (!writePrivateText(
|
|
982
|
+
ensurePrivateDir(dirname2(path7));
|
|
983
|
+
if (!writePrivateText(path7, tok + "\n")) return "";
|
|
984
984
|
console.warn(
|
|
985
|
-
`[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${
|
|
985
|
+
`[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`
|
|
986
986
|
);
|
|
987
987
|
return tok;
|
|
988
988
|
} catch (e) {
|
|
@@ -1055,16 +1055,16 @@ function constEq(a, b) {
|
|
|
1055
1055
|
if (ba.length !== bb.length) return false;
|
|
1056
1056
|
return timingSafeEqual(ba, bb);
|
|
1057
1057
|
}
|
|
1058
|
-
function checkRequestAuth(headers,
|
|
1058
|
+
function checkRequestAuth(headers, path7) {
|
|
1059
1059
|
if (authMode() === AUTH_MODE_OFF) return [true, ""];
|
|
1060
|
-
const isHealth = HEALTH_PATHS.includes(
|
|
1060
|
+
const isHealth = HEALTH_PATHS.includes(path7.replace(/\/+$/, ""));
|
|
1061
1061
|
const [gt0, agents, err] = resolveAuth();
|
|
1062
1062
|
if (err) return isHealth ? [true, ""] : [false, ""];
|
|
1063
1063
|
if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
|
|
1064
1064
|
if (isHealth) return [true, ""];
|
|
1065
1065
|
const tok = bearer(headers);
|
|
1066
1066
|
if (!tok) return [false, ""];
|
|
1067
|
-
if (
|
|
1067
|
+
if (path7.startsWith("/console/api")) {
|
|
1068
1068
|
const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
|
|
1069
1069
|
if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
|
|
1070
1070
|
}
|
|
@@ -1083,8 +1083,8 @@ function bindAgent(principal, agentId) {
|
|
|
1083
1083
|
if (!agentId) return [true, bound];
|
|
1084
1084
|
return [bound === agentId, bound];
|
|
1085
1085
|
}
|
|
1086
|
-
function principalOf(headers,
|
|
1087
|
-
const [ok, principal] = checkRequestAuth(headers,
|
|
1086
|
+
function principalOf(headers, path7 = "") {
|
|
1087
|
+
const [ok, principal] = checkRequestAuth(headers, path7);
|
|
1088
1088
|
return ok ? principal : "";
|
|
1089
1089
|
}
|
|
1090
1090
|
function principalHash(principal) {
|
|
@@ -1342,11 +1342,11 @@ function errorDetailMode() {
|
|
|
1342
1342
|
function maxBodyBytes() {
|
|
1343
1343
|
return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
|
|
1344
1344
|
}
|
|
1345
|
-
function poolOf(
|
|
1346
|
-
if (
|
|
1347
|
-
if (
|
|
1348
|
-
if (
|
|
1349
|
-
if (
|
|
1345
|
+
function poolOf(path7) {
|
|
1346
|
+
if (path7 === "/api/v1/analyze" || path7.startsWith("/api/v1/analyze/")) return "biz";
|
|
1347
|
+
if (path7 === "/api/v1/review" || path7.startsWith("/api/v1/review/")) return "review";
|
|
1348
|
+
if (path7 === "/console" || path7.startsWith("/console/") || path7.startsWith("/api/v1/brain")) return "ops";
|
|
1349
|
+
if (path7 === "/api/v1/health") return "health";
|
|
1350
1350
|
return "other";
|
|
1351
1351
|
}
|
|
1352
1352
|
function poolLimit(name) {
|
|
@@ -1469,6 +1469,8 @@ var init_models = __esm({
|
|
|
1469
1469
|
analysis_duration_ms: z.number().default(0),
|
|
1470
1470
|
// 组合攻击链反例路径:每步 [session_id, seq, stage, timestamp],含真实发生时间
|
|
1471
1471
|
violation_chain: z.array(z.array(z.union([z.string(), z.number()]).nullable())).default([]),
|
|
1472
|
+
// 本次判定的能力降级说明(2026-11):正常为空;链状态触顶时说明 L2.2 未覆盖
|
|
1473
|
+
degraded: z.array(z.string()).default([]),
|
|
1472
1474
|
// 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
|
|
1473
1475
|
violation_graph: z.object({
|
|
1474
1476
|
// 性质元信息(前端展示"违反了哪条性质")
|
|
@@ -1508,12 +1510,18 @@ var init_models = __esm({
|
|
|
1508
1510
|
}).nullable().default(null)
|
|
1509
1511
|
});
|
|
1510
1512
|
HealthResponseSchema = z.object({
|
|
1513
|
+
// healthy | degraded(2026-11):degraded 表示服务可用但**某项安全能力已降级**
|
|
1514
|
+
// (链状态触顶、LLM 熔断)。任何探活/监控只看 status 就能发现异常。
|
|
1511
1515
|
status: z.string().default("healthy"),
|
|
1516
|
+
// 降级原因(status=degraded 时非空)
|
|
1517
|
+
degraded: z.array(z.string()).default([]),
|
|
1512
1518
|
version: z.string().default(version),
|
|
1513
1519
|
// 归属实例标识:值来自 env AGENT_MOSS_INSTANCE(spawn/systemd 注入),默认空串。
|
|
1514
1520
|
// 多个 agentmoss 同机并存时,调用方按 instance 过滤避免连到别人的进程。
|
|
1515
1521
|
// 空=未配置(独立部署或旧版),调用方可选择兼容或严格过滤。
|
|
1516
|
-
instance: z.string().default("")
|
|
1522
|
+
instance: z.string().default(""),
|
|
1523
|
+
// 运行态指标(2026-11 增强):事件循环延迟、并发池占用、链状态规模。
|
|
1524
|
+
metrics: z.record(z.unknown()).default({})
|
|
1517
1525
|
});
|
|
1518
1526
|
ReviewRequestSchema = z.object({
|
|
1519
1527
|
agent_id: z.string().default("").describe("\u76EE\u6807 agent \u6807\u8BC6\uFF08\u51B3\u5B9A\u72B6\u6001\u5E93\u5206\u6876\uFF09"),
|
|
@@ -1797,7 +1805,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
|
|
|
1797
1805
|
os: String(sp.os || "linux").toLowerCase()
|
|
1798
1806
|
}));
|
|
1799
1807
|
}
|
|
1800
|
-
function _scopeOf(os4,
|
|
1808
|
+
function _scopeOf(os4, path7) {
|
|
1801
1809
|
if (!_scopeIndex) {
|
|
1802
1810
|
_scopeIndex = /* @__PURE__ */ new Map();
|
|
1803
1811
|
for (const sp of loadL1().sensitive_path_access || []) {
|
|
@@ -1805,7 +1813,7 @@ function _scopeOf(os4, path6) {
|
|
|
1805
1813
|
if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
|
|
1806
1814
|
}
|
|
1807
1815
|
}
|
|
1808
|
-
return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${
|
|
1816
|
+
return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path7}`) || "root";
|
|
1809
1817
|
}
|
|
1810
1818
|
function getSensitivePathsForOs(osType) {
|
|
1811
1819
|
const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
|
|
@@ -2156,17 +2164,17 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
2156
2164
|
return null;
|
|
2157
2165
|
}
|
|
2158
2166
|
const unreadPaths = [];
|
|
2159
|
-
for (const
|
|
2167
|
+
for (const path7 of filteredPaths) {
|
|
2160
2168
|
const hasRead = [...historyReadPaths].some(
|
|
2161
|
-
(rp) =>
|
|
2169
|
+
(rp) => path7 === rp || path7.startsWith(rp) || rp.startsWith(path7)
|
|
2162
2170
|
);
|
|
2163
2171
|
if (!hasRead) {
|
|
2164
|
-
let isCreate = !fs.existsSync(
|
|
2172
|
+
let isCreate = !fs.existsSync(path7);
|
|
2165
2173
|
if (!isCreate) {
|
|
2166
2174
|
isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
|
|
2167
2175
|
}
|
|
2168
2176
|
if (!isCreate) {
|
|
2169
|
-
unreadPaths.push(
|
|
2177
|
+
unreadPaths.push(path7);
|
|
2170
2178
|
}
|
|
2171
2179
|
}
|
|
2172
2180
|
}
|
|
@@ -2360,16 +2368,16 @@ var init_logic_rules = __esm({
|
|
|
2360
2368
|
ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
|
|
2361
2369
|
ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
|
|
2362
2370
|
HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
|
|
2363
|
-
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path:
|
|
2371
|
+
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2364
2372
|
ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
|
|
2365
2373
|
HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
|
|
2366
|
-
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path:
|
|
2374
|
+
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2367
2375
|
ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
|
|
2368
2376
|
HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
|
|
2369
|
-
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path:
|
|
2377
|
+
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2370
2378
|
ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
|
|
2371
2379
|
HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
|
|
2372
|
-
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path:
|
|
2380
|
+
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2373
2381
|
_scopeIndex = null;
|
|
2374
2382
|
NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
|
|
2375
2383
|
"ask_user_question",
|
|
@@ -4138,7 +4146,9 @@ function loadLLMConfigFromFile(configPath) {
|
|
|
4138
4146
|
model: llm.model || "",
|
|
4139
4147
|
temperature: llm.temperature ?? 0.1,
|
|
4140
4148
|
maxTokens: llm.max_tokens ?? 4096,
|
|
4141
|
-
timeout: llm.timeout ?? 40
|
|
4149
|
+
timeout: llm.timeout ?? 40,
|
|
4150
|
+
// 部署级透传参数(关思考等)。非对象直接忽略:写错不能拖垮配置加载。
|
|
4151
|
+
...llm.extra_body && typeof llm.extra_body === "object" && !Array.isArray(llm.extra_body) ? { extraBody: llm.extra_body } : {}
|
|
4142
4152
|
};
|
|
4143
4153
|
}
|
|
4144
4154
|
function loadTimeoutRetryFromFile(configPath) {
|
|
@@ -4970,16 +4980,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4970
4980
|
if (String(osType || "").toLowerCase() === "windows") {
|
|
4971
4981
|
pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
|
|
4972
4982
|
}
|
|
4973
|
-
const pathMatches = (text,
|
|
4974
|
-
const parts =
|
|
4983
|
+
const pathMatches = (text, path7) => {
|
|
4984
|
+
const parts = path7.split(/(\(\?!.*?\))/);
|
|
4975
4985
|
const escaped = parts.map((part) => {
|
|
4976
4986
|
if (part.startsWith("(?!")) return part;
|
|
4977
4987
|
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4978
4988
|
}).join("");
|
|
4979
|
-
const re =
|
|
4989
|
+
const re = path7.startsWith(".") || path7.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
|
|
4980
4990
|
return re.test(text);
|
|
4981
4991
|
};
|
|
4982
|
-
const pathMatchesAny = (
|
|
4992
|
+
const pathMatchesAny = (path7) => pathScanTexts.some((t) => pathMatches(t, path7));
|
|
4983
4993
|
for (const sp of rootPaths) {
|
|
4984
4994
|
if (pathMatchesAny(sp.path.toLowerCase())) {
|
|
4985
4995
|
if (keygenGenerate) continue;
|
|
@@ -5122,8 +5132,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
5122
5132
|
}
|
|
5123
5133
|
return null;
|
|
5124
5134
|
}
|
|
5125
|
-
function isHomeValue(
|
|
5126
|
-
let p =
|
|
5135
|
+
function isHomeValue(path7) {
|
|
5136
|
+
let p = path7.trim().toLowerCase();
|
|
5127
5137
|
if (p.startsWith("$(") && p.endsWith(")")) {
|
|
5128
5138
|
const inner = p.slice(2, -1).trim();
|
|
5129
5139
|
return HOME_TARGET_RE.test(" " + inner);
|
|
@@ -5179,15 +5189,15 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
5179
5189
|
}
|
|
5180
5190
|
const assigned = {};
|
|
5181
5191
|
for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
|
|
5182
|
-
for (const [varName,
|
|
5183
|
-
if (!isHomeValue(
|
|
5192
|
+
for (const [varName, path7] of Object.entries(assigned)) {
|
|
5193
|
+
if (!isHomeValue(path7)) continue;
|
|
5184
5194
|
const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
|
|
5185
5195
|
for (const seg of segs) {
|
|
5186
5196
|
if (!isDeleteCommand(seg)) continue;
|
|
5187
5197
|
if (varRefRe.test(seg)) {
|
|
5188
5198
|
return {
|
|
5189
5199
|
allowed: false,
|
|
5190
|
-
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${
|
|
5200
|
+
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path7}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
|
|
5191
5201
|
riskLevel: "high",
|
|
5192
5202
|
riskType: "script_execution",
|
|
5193
5203
|
confidence: 90,
|
|
@@ -5991,15 +6001,15 @@ function parseShellString(s) {
|
|
|
5991
6001
|
let m;
|
|
5992
6002
|
while ((m = CHILD_CALL_RE.exec(s)) !== null) {
|
|
5993
6003
|
const interp = m[1];
|
|
5994
|
-
const
|
|
6004
|
+
const path7 = m[2].trim();
|
|
5995
6005
|
let rest = m[3].trim();
|
|
5996
|
-
if (
|
|
6006
|
+
if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
|
|
5997
6007
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5998
6008
|
const args = [];
|
|
5999
6009
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
6000
6010
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
6001
6011
|
}
|
|
6002
|
-
return { path:
|
|
6012
|
+
return { path: path7, args, interpreter: interp };
|
|
6003
6013
|
}
|
|
6004
6014
|
return null;
|
|
6005
6015
|
}
|
|
@@ -6045,9 +6055,9 @@ function extractCallsFromTree(tree, reachableLines) {
|
|
|
6045
6055
|
}
|
|
6046
6056
|
if (allStr && elts.length >= 2) {
|
|
6047
6057
|
const interp = elts[0];
|
|
6048
|
-
const
|
|
6049
|
-
if (!
|
|
6050
|
-
add({ path:
|
|
6058
|
+
const path7 = elts[1];
|
|
6059
|
+
if (!path7.startsWith("-") && !path7.startsWith("$") && !path7.includes("/dev/")) {
|
|
6060
|
+
add({ path: path7, args: elts.slice(2), interpreter: interp });
|
|
6051
6061
|
return true;
|
|
6052
6062
|
}
|
|
6053
6063
|
}
|
|
@@ -6087,15 +6097,15 @@ function extractCallsRegex(content) {
|
|
|
6087
6097
|
let m;
|
|
6088
6098
|
while ((m = CHILD_CALL_RE.exec(content)) !== null) {
|
|
6089
6099
|
const interp = m[1];
|
|
6090
|
-
const
|
|
6100
|
+
const path7 = m[2].trim();
|
|
6091
6101
|
let rest = m[3].trim();
|
|
6092
|
-
if (
|
|
6102
|
+
if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
|
|
6093
6103
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
6094
6104
|
const args = [];
|
|
6095
6105
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
6096
6106
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
6097
6107
|
}
|
|
6098
|
-
calls.push({ path:
|
|
6108
|
+
calls.push({ path: path7, args, interpreter: interp });
|
|
6099
6109
|
}
|
|
6100
6110
|
return calls;
|
|
6101
6111
|
}
|
|
@@ -6878,15 +6888,15 @@ function extractCallsFromContent(content) {
|
|
|
6878
6888
|
CHILD_CALL_RE2.lastIndex = 0;
|
|
6879
6889
|
while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
|
|
6880
6890
|
const interp = m[1];
|
|
6881
|
-
const
|
|
6891
|
+
const path7 = m[2].trim();
|
|
6882
6892
|
let rest = m[3].trim();
|
|
6883
|
-
if (
|
|
6893
|
+
if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
|
|
6884
6894
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
6885
6895
|
const args = [];
|
|
6886
6896
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
6887
6897
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
6888
6898
|
}
|
|
6889
|
-
calls.push({ path:
|
|
6899
|
+
calls.push({ path: path7, args, interpreter: interp });
|
|
6890
6900
|
}
|
|
6891
6901
|
return calls;
|
|
6892
6902
|
}
|
|
@@ -7575,6 +7585,464 @@ var init_script_content_analyzer = __esm({
|
|
|
7575
7585
|
}
|
|
7576
7586
|
});
|
|
7577
7587
|
|
|
7588
|
+
// src/infra/trace-log.ts
|
|
7589
|
+
import fs4 from "fs";
|
|
7590
|
+
import path4 from "path";
|
|
7591
|
+
function traceLevel() {
|
|
7592
|
+
if (_levelCache !== null) return _levelCache;
|
|
7593
|
+
const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
|
|
7594
|
+
let level;
|
|
7595
|
+
if (raw in LEVEL_NAMES) {
|
|
7596
|
+
level = LEVEL_NAMES[raw];
|
|
7597
|
+
} else {
|
|
7598
|
+
level = LEVEL_SUMMARY;
|
|
7599
|
+
if (!_warnedInvalid) {
|
|
7600
|
+
_warnedInvalid = true;
|
|
7601
|
+
console.warn(
|
|
7602
|
+
`[AgentMoss] AGENT_MOSS_TRACE_LEVEL=${JSON.stringify(raw)} \u975E\u6CD5\uFF0C\u6309 summary \u5904\u7406\uFF08\u53EF\u9009 off/summary/full\uFF09`
|
|
7603
|
+
);
|
|
7604
|
+
}
|
|
7605
|
+
}
|
|
7606
|
+
_levelCache = level;
|
|
7607
|
+
_levelCacheRaw = raw;
|
|
7608
|
+
return level;
|
|
7609
|
+
}
|
|
7610
|
+
function nowIso() {
|
|
7611
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
7612
|
+
}
|
|
7613
|
+
function tracePath() {
|
|
7614
|
+
const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
|
|
7615
|
+
if (explicit) return explicit;
|
|
7616
|
+
try {
|
|
7617
|
+
return path4.join(getDataRoot(), "agent_moss_trace.log");
|
|
7618
|
+
} catch {
|
|
7619
|
+
return "agent_moss_trace.log";
|
|
7620
|
+
}
|
|
7621
|
+
}
|
|
7622
|
+
function sanitize(key, value) {
|
|
7623
|
+
if (SECRET_KEYS.has(key.toLowerCase())) return "***";
|
|
7624
|
+
if (typeof value === "string") {
|
|
7625
|
+
let v = value;
|
|
7626
|
+
if (v.length > MAX_FIELD_CHARS) {
|
|
7627
|
+
const original = v.length;
|
|
7628
|
+
v = `${v.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
|
|
7629
|
+
}
|
|
7630
|
+
return v;
|
|
7631
|
+
}
|
|
7632
|
+
if (value === null || ["number", "boolean"].includes(typeof value)) return value;
|
|
7633
|
+
let text;
|
|
7634
|
+
try {
|
|
7635
|
+
text = JSON.stringify(value);
|
|
7636
|
+
} catch {
|
|
7637
|
+
return String(value);
|
|
7638
|
+
}
|
|
7639
|
+
if (text.length > MAX_FIELD_CHARS) {
|
|
7640
|
+
const original = text.length;
|
|
7641
|
+
return `${text.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
|
|
7642
|
+
}
|
|
7643
|
+
return value;
|
|
7644
|
+
}
|
|
7645
|
+
function trace(event, level = LEVEL_SUMMARY, fields = {}) {
|
|
7646
|
+
if (traceLevel() < level) return;
|
|
7647
|
+
try {
|
|
7648
|
+
const record = { ts: nowIso(), event };
|
|
7649
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
7650
|
+
record[key] = sanitize(key, value);
|
|
7651
|
+
}
|
|
7652
|
+
const line = `${JSON.stringify(record)}
|
|
7653
|
+
`;
|
|
7654
|
+
const file = tracePath();
|
|
7655
|
+
try {
|
|
7656
|
+
const dir = path4.dirname(file);
|
|
7657
|
+
if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
|
|
7658
|
+
try {
|
|
7659
|
+
const st = fs4.statSync(file);
|
|
7660
|
+
if (st.size > MAX_FILE_BYTES) fs4.renameSync(file, `${file}.1`);
|
|
7661
|
+
} catch {
|
|
7662
|
+
}
|
|
7663
|
+
fs4.appendFileSync(file, line, { encoding: "utf-8", mode: 384 });
|
|
7664
|
+
} catch {
|
|
7665
|
+
}
|
|
7666
|
+
} catch {
|
|
7667
|
+
}
|
|
7668
|
+
}
|
|
7669
|
+
function traceSummary(event, fields = {}) {
|
|
7670
|
+
trace(event, LEVEL_SUMMARY, fields);
|
|
7671
|
+
}
|
|
7672
|
+
function traceFull(event, fields = {}) {
|
|
7673
|
+
trace(event, LEVEL_FULL, fields);
|
|
7674
|
+
}
|
|
7675
|
+
var LEVEL_OFF, LEVEL_SUMMARY, LEVEL_FULL, LEVEL_NAMES, MAX_FIELD_CHARS, SECRET_KEYS, MAX_FILE_BYTES, _levelCache, _levelCacheRaw, _warnedInvalid;
|
|
7676
|
+
var init_trace_log = __esm({
|
|
7677
|
+
"src/infra/trace-log.ts"() {
|
|
7678
|
+
"use strict";
|
|
7679
|
+
init_esm_shims();
|
|
7680
|
+
init_paths();
|
|
7681
|
+
LEVEL_OFF = 0;
|
|
7682
|
+
LEVEL_SUMMARY = 1;
|
|
7683
|
+
LEVEL_FULL = 2;
|
|
7684
|
+
LEVEL_NAMES = {
|
|
7685
|
+
off: LEVEL_OFF,
|
|
7686
|
+
summary: LEVEL_SUMMARY,
|
|
7687
|
+
full: LEVEL_FULL
|
|
7688
|
+
};
|
|
7689
|
+
MAX_FIELD_CHARS = 64 * 1024;
|
|
7690
|
+
SECRET_KEYS = /* @__PURE__ */ new Set([
|
|
7691
|
+
"api_key",
|
|
7692
|
+
"apikey",
|
|
7693
|
+
"authorization",
|
|
7694
|
+
"auth_token",
|
|
7695
|
+
"token",
|
|
7696
|
+
"password"
|
|
7697
|
+
]);
|
|
7698
|
+
MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
7699
|
+
_levelCache = null;
|
|
7700
|
+
_levelCacheRaw = null;
|
|
7701
|
+
_warnedInvalid = false;
|
|
7702
|
+
}
|
|
7703
|
+
});
|
|
7704
|
+
|
|
7705
|
+
// src/infra/circuit-breaker.ts
|
|
7706
|
+
function envInt2(name, fallback) {
|
|
7707
|
+
const raw = process.env[name];
|
|
7708
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
7709
|
+
const n = Number(raw);
|
|
7710
|
+
return Number.isFinite(n) ? n : fallback;
|
|
7711
|
+
}
|
|
7712
|
+
function getBreaker() {
|
|
7713
|
+
if (_breaker === null) {
|
|
7714
|
+
_breaker = new CircuitBreaker(
|
|
7715
|
+
envInt2("AGENT_MOSS_LLM_CIRCUIT_THRESHOLD", 5),
|
|
7716
|
+
envInt2("AGENT_MOSS_LLM_CIRCUIT_COOLDOWN", 30)
|
|
7717
|
+
);
|
|
7718
|
+
}
|
|
7719
|
+
return _breaker;
|
|
7720
|
+
}
|
|
7721
|
+
var CLOSED, OPEN, HALF_OPEN, CircuitBreaker, _breaker;
|
|
7722
|
+
var init_circuit_breaker = __esm({
|
|
7723
|
+
"src/infra/circuit-breaker.ts"() {
|
|
7724
|
+
"use strict";
|
|
7725
|
+
init_esm_shims();
|
|
7726
|
+
CLOSED = "closed";
|
|
7727
|
+
OPEN = "open";
|
|
7728
|
+
HALF_OPEN = "half_open";
|
|
7729
|
+
CircuitBreaker = class {
|
|
7730
|
+
constructor(threshold = 5, cooldown = 30) {
|
|
7731
|
+
this.threshold = threshold;
|
|
7732
|
+
this.cooldown = cooldown;
|
|
7733
|
+
}
|
|
7734
|
+
threshold;
|
|
7735
|
+
cooldown;
|
|
7736
|
+
state = CLOSED;
|
|
7737
|
+
failures = 0;
|
|
7738
|
+
openedAt = 0;
|
|
7739
|
+
openCount = 0;
|
|
7740
|
+
shortCircuitCount = 0;
|
|
7741
|
+
get currentState() {
|
|
7742
|
+
return this.state;
|
|
7743
|
+
}
|
|
7744
|
+
allow() {
|
|
7745
|
+
if (this.threshold <= 0) return true;
|
|
7746
|
+
if (this.state === CLOSED) return true;
|
|
7747
|
+
if (this.state === OPEN) {
|
|
7748
|
+
if ((performance.now() - this.openedAt) / 1e3 >= this.cooldown) {
|
|
7749
|
+
this.state = HALF_OPEN;
|
|
7750
|
+
return true;
|
|
7751
|
+
}
|
|
7752
|
+
this.shortCircuitCount += 1;
|
|
7753
|
+
return false;
|
|
7754
|
+
}
|
|
7755
|
+
return true;
|
|
7756
|
+
}
|
|
7757
|
+
recordSuccess() {
|
|
7758
|
+
if (this.threshold <= 0) return;
|
|
7759
|
+
this.state = CLOSED;
|
|
7760
|
+
this.failures = 0;
|
|
7761
|
+
}
|
|
7762
|
+
recordFailure() {
|
|
7763
|
+
if (this.threshold <= 0) return;
|
|
7764
|
+
if (this.state === HALF_OPEN) {
|
|
7765
|
+
this.state = OPEN;
|
|
7766
|
+
this.openedAt = performance.now();
|
|
7767
|
+
this.openCount += 1;
|
|
7768
|
+
return;
|
|
7769
|
+
}
|
|
7770
|
+
this.failures += 1;
|
|
7771
|
+
if (this.failures >= this.threshold) {
|
|
7772
|
+
this.state = OPEN;
|
|
7773
|
+
this.openedAt = performance.now();
|
|
7774
|
+
this.openCount += 1;
|
|
7775
|
+
}
|
|
7776
|
+
}
|
|
7777
|
+
snapshot() {
|
|
7778
|
+
return {
|
|
7779
|
+
state: this.state,
|
|
7780
|
+
failures: this.failures,
|
|
7781
|
+
threshold: this.threshold,
|
|
7782
|
+
cooldown_sec: this.cooldown,
|
|
7783
|
+
open_count: this.openCount,
|
|
7784
|
+
short_circuit_count: this.shortCircuitCount
|
|
7785
|
+
};
|
|
7786
|
+
}
|
|
7787
|
+
reset() {
|
|
7788
|
+
this.state = CLOSED;
|
|
7789
|
+
this.failures = 0;
|
|
7790
|
+
this.openedAt = 0;
|
|
7791
|
+
}
|
|
7792
|
+
};
|
|
7793
|
+
_breaker = null;
|
|
7794
|
+
}
|
|
7795
|
+
});
|
|
7796
|
+
|
|
7797
|
+
// src/infra/metrics.ts
|
|
7798
|
+
function escapeLabel(value) {
|
|
7799
|
+
return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
|
|
7800
|
+
}
|
|
7801
|
+
function formatLabels(labels) {
|
|
7802
|
+
if (!labels) return "";
|
|
7803
|
+
const keys = Object.keys(labels).sort();
|
|
7804
|
+
if (!keys.length) return "";
|
|
7805
|
+
return `{${keys.map((k) => `${k}="${escapeLabel(labels[k])}"`).join(",")}}`;
|
|
7806
|
+
}
|
|
7807
|
+
function keyOf(labelnames, labels) {
|
|
7808
|
+
return labelnames.map((k) => String(labels[k] ?? "")).join("");
|
|
7809
|
+
}
|
|
7810
|
+
function decodeKey(labelnames, key) {
|
|
7811
|
+
if (!labelnames.length) return void 0;
|
|
7812
|
+
const parts = key.split("");
|
|
7813
|
+
const out = {};
|
|
7814
|
+
labelnames.forEach((k, i) => {
|
|
7815
|
+
out[k] = parts[i] ?? "";
|
|
7816
|
+
});
|
|
7817
|
+
return out;
|
|
7818
|
+
}
|
|
7819
|
+
function renderPrometheus() {
|
|
7820
|
+
const lines = [];
|
|
7821
|
+
for (const m of [
|
|
7822
|
+
ANALYZE_TOTAL,
|
|
7823
|
+
ANALYZE_DURATION,
|
|
7824
|
+
LAYER_HIT_TOTAL,
|
|
7825
|
+
REJECTED_TOTAL,
|
|
7826
|
+
LLM_CALLS_TOTAL,
|
|
7827
|
+
LLM_DURATION,
|
|
7828
|
+
POOL_INFLIGHT,
|
|
7829
|
+
CHAIN_NODES,
|
|
7830
|
+
CHAIN_DB_BYTES,
|
|
7831
|
+
LOOP_LAG,
|
|
7832
|
+
LOOP_LAG_MAX,
|
|
7833
|
+
UPTIME,
|
|
7834
|
+
LLM_CIRCUIT_STATE,
|
|
7835
|
+
LLM_SHORT_CIRCUIT_TOTAL
|
|
7836
|
+
]) {
|
|
7837
|
+
lines.push(...m.render());
|
|
7838
|
+
}
|
|
7839
|
+
return `${lines.join("\n")}
|
|
7840
|
+
`;
|
|
7841
|
+
}
|
|
7842
|
+
function refreshRuntimeGauges(g) {
|
|
7843
|
+
UPTIME.set((Date.now() - STARTED_AT) / 1e3);
|
|
7844
|
+
try {
|
|
7845
|
+
const snap = getBreaker().snapshot();
|
|
7846
|
+
const stateMap = { closed: 0, open: 1, half_open: 2 };
|
|
7847
|
+
LLM_CIRCUIT_STATE.set(stateMap[String(snap.state)] ?? 0);
|
|
7848
|
+
} catch {
|
|
7849
|
+
}
|
|
7850
|
+
if (g.pools !== void 0) {
|
|
7851
|
+
POOL_INFLIGHT.clear();
|
|
7852
|
+
for (const [key, value] of Object.entries(g.pools)) {
|
|
7853
|
+
POOL_INFLIGHT.set(value, { pool: key });
|
|
7854
|
+
}
|
|
7855
|
+
}
|
|
7856
|
+
if (g.chainNodes !== void 0) {
|
|
7857
|
+
CHAIN_NODES.clear();
|
|
7858
|
+
CHAIN_NODES.set(g.chainNodes, { agent: "__total__" });
|
|
7859
|
+
}
|
|
7860
|
+
if (g.chainDbBytes !== void 0) CHAIN_DB_BYTES.set(g.chainDbBytes);
|
|
7861
|
+
if (g.loopLagMs !== void 0) LOOP_LAG.set(g.loopLagMs / 1e3);
|
|
7862
|
+
if (g.loopLagMaxMs !== void 0) LOOP_LAG_MAX.set(g.loopLagMaxMs / 1e3);
|
|
7863
|
+
}
|
|
7864
|
+
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;
|
|
7865
|
+
var init_metrics = __esm({
|
|
7866
|
+
"src/infra/metrics.ts"() {
|
|
7867
|
+
"use strict";
|
|
7868
|
+
init_esm_shims();
|
|
7869
|
+
init_circuit_breaker();
|
|
7870
|
+
DEFAULT_BUCKETS = [
|
|
7871
|
+
5e-3,
|
|
7872
|
+
0.01,
|
|
7873
|
+
0.025,
|
|
7874
|
+
0.05,
|
|
7875
|
+
0.1,
|
|
7876
|
+
0.25,
|
|
7877
|
+
0.5,
|
|
7878
|
+
1,
|
|
7879
|
+
2.5,
|
|
7880
|
+
5,
|
|
7881
|
+
10,
|
|
7882
|
+
30,
|
|
7883
|
+
60
|
|
7884
|
+
];
|
|
7885
|
+
STARTED_AT = Date.now();
|
|
7886
|
+
Counter = class {
|
|
7887
|
+
constructor(name, helpText, labelnames = []) {
|
|
7888
|
+
this.name = name;
|
|
7889
|
+
this.helpText = helpText;
|
|
7890
|
+
this.labelnames = labelnames;
|
|
7891
|
+
}
|
|
7892
|
+
name;
|
|
7893
|
+
helpText;
|
|
7894
|
+
labelnames;
|
|
7895
|
+
values = /* @__PURE__ */ new Map();
|
|
7896
|
+
inc(amount = 1, labels = {}) {
|
|
7897
|
+
const k = keyOf(this.labelnames, labels);
|
|
7898
|
+
this.values.set(k, (this.values.get(k) ?? 0) + amount);
|
|
7899
|
+
}
|
|
7900
|
+
render() {
|
|
7901
|
+
const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} counter`];
|
|
7902
|
+
if (!this.values.size) {
|
|
7903
|
+
const empty = this.labelnames.length ? Object.fromEntries(this.labelnames.map((k) => [k, ""])) : void 0;
|
|
7904
|
+
out.push(`${this.name}${formatLabels(empty)} 0`);
|
|
7905
|
+
return out;
|
|
7906
|
+
}
|
|
7907
|
+
for (const [k, v] of this.values) {
|
|
7908
|
+
out.push(`${this.name}${formatLabels(decodeKey(this.labelnames, k))} ${v}`);
|
|
7909
|
+
}
|
|
7910
|
+
return out;
|
|
7911
|
+
}
|
|
7912
|
+
};
|
|
7913
|
+
Gauge = class {
|
|
7914
|
+
constructor(name, helpText, labelnames = []) {
|
|
7915
|
+
this.name = name;
|
|
7916
|
+
this.helpText = helpText;
|
|
7917
|
+
this.labelnames = labelnames;
|
|
7918
|
+
}
|
|
7919
|
+
name;
|
|
7920
|
+
helpText;
|
|
7921
|
+
labelnames;
|
|
7922
|
+
values = /* @__PURE__ */ new Map();
|
|
7923
|
+
set(value, labels = {}) {
|
|
7924
|
+
this.values.set(keyOf(this.labelnames, labels), Number(value));
|
|
7925
|
+
}
|
|
7926
|
+
clear() {
|
|
7927
|
+
this.values.clear();
|
|
7928
|
+
}
|
|
7929
|
+
render() {
|
|
7930
|
+
const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} gauge`];
|
|
7931
|
+
for (const [k, v] of this.values) {
|
|
7932
|
+
const labels = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : void 0;
|
|
7933
|
+
out.push(`${this.name}${formatLabels(labels)} ${v}`);
|
|
7934
|
+
}
|
|
7935
|
+
return out;
|
|
7936
|
+
}
|
|
7937
|
+
};
|
|
7938
|
+
Histogram = class {
|
|
7939
|
+
constructor(name, helpText, buckets = DEFAULT_BUCKETS, labelnames = []) {
|
|
7940
|
+
this.name = name;
|
|
7941
|
+
this.helpText = helpText;
|
|
7942
|
+
this.buckets = buckets;
|
|
7943
|
+
this.labelnames = labelnames;
|
|
7944
|
+
}
|
|
7945
|
+
name;
|
|
7946
|
+
helpText;
|
|
7947
|
+
buckets;
|
|
7948
|
+
labelnames;
|
|
7949
|
+
values = /* @__PURE__ */ new Map();
|
|
7950
|
+
observe(value, labels = {}) {
|
|
7951
|
+
const k = keyOf(this.labelnames, labels);
|
|
7952
|
+
let slot = this.values.get(k);
|
|
7953
|
+
if (!slot) {
|
|
7954
|
+
slot = { buckets: this.buckets.map(() => 0), sum: 0, count: 0 };
|
|
7955
|
+
this.values.set(k, slot);
|
|
7956
|
+
}
|
|
7957
|
+
for (let i = 0; i < this.buckets.length; i++) {
|
|
7958
|
+
if (value <= this.buckets[i]) slot.buckets[i] += 1;
|
|
7959
|
+
}
|
|
7960
|
+
slot.sum += value;
|
|
7961
|
+
slot.count += 1;
|
|
7962
|
+
}
|
|
7963
|
+
render() {
|
|
7964
|
+
const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} histogram`];
|
|
7965
|
+
for (const [k, slot] of this.values) {
|
|
7966
|
+
const base = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : {};
|
|
7967
|
+
this.buckets.forEach((bound, i) => {
|
|
7968
|
+
out.push(`${this.name}_bucket${formatLabels({ ...base, le: String(bound) })} ${slot.buckets[i]}`);
|
|
7969
|
+
});
|
|
7970
|
+
out.push(`${this.name}_bucket${formatLabels({ ...base, le: "+Inf" })} ${slot.count}`);
|
|
7971
|
+
out.push(`${this.name}_sum${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.sum}`);
|
|
7972
|
+
out.push(`${this.name}_count${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.count}`);
|
|
7973
|
+
}
|
|
7974
|
+
return out;
|
|
7975
|
+
}
|
|
7976
|
+
};
|
|
7977
|
+
ANALYZE_TOTAL = new Counter(
|
|
7978
|
+
"agent_moss_analyze_total",
|
|
7979
|
+
"Total analyze requests handled, by decision and risk level.",
|
|
7980
|
+
["decision", "risk_level"]
|
|
7981
|
+
);
|
|
7982
|
+
ANALYZE_DURATION = new Histogram(
|
|
7983
|
+
"agent_moss_analyze_duration_seconds",
|
|
7984
|
+
"End-to-end analyze duration in seconds.",
|
|
7985
|
+
DEFAULT_BUCKETS,
|
|
7986
|
+
["decision"]
|
|
7987
|
+
);
|
|
7988
|
+
LAYER_HIT_TOTAL = new Counter(
|
|
7989
|
+
"agent_moss_layer_hit_total",
|
|
7990
|
+
"Number of requests where a given defense layer produced the final verdict.",
|
|
7991
|
+
["layer"]
|
|
7992
|
+
);
|
|
7993
|
+
REJECTED_TOTAL = new Counter(
|
|
7994
|
+
"agent_moss_rejected_total",
|
|
7995
|
+
"Requests rejected before analysis (concurrency / rate limit / auth).",
|
|
7996
|
+
["reason"]
|
|
7997
|
+
);
|
|
7998
|
+
LLM_CALLS_TOTAL = new Counter(
|
|
7999
|
+
"agent_moss_llm_calls_total",
|
|
8000
|
+
"LLM API calls, by outcome.",
|
|
8001
|
+
["result"]
|
|
8002
|
+
);
|
|
8003
|
+
LLM_DURATION = new Histogram(
|
|
8004
|
+
"agent_moss_llm_duration_seconds",
|
|
8005
|
+
"LLM API call duration in seconds.",
|
|
8006
|
+
DEFAULT_BUCKETS,
|
|
8007
|
+
["result"]
|
|
8008
|
+
);
|
|
8009
|
+
POOL_INFLIGHT = new Gauge(
|
|
8010
|
+
"agent_moss_pool_inflight",
|
|
8011
|
+
"Current in-flight requests per concurrency pool.",
|
|
8012
|
+
["pool"]
|
|
8013
|
+
);
|
|
8014
|
+
CHAIN_NODES = new Gauge(
|
|
8015
|
+
"agent_moss_chain_nodes",
|
|
8016
|
+
"Number of nodes in the stateful chain timeline.",
|
|
8017
|
+
["agent"]
|
|
8018
|
+
);
|
|
8019
|
+
CHAIN_DB_BYTES = new Gauge(
|
|
8020
|
+
"agent_moss_chain_db_bytes",
|
|
8021
|
+
"Size of the chain state database in bytes."
|
|
8022
|
+
);
|
|
8023
|
+
LOOP_LAG = new Gauge(
|
|
8024
|
+
"agent_moss_event_loop_lag_seconds",
|
|
8025
|
+
"Most recent event loop lag sample in seconds."
|
|
8026
|
+
);
|
|
8027
|
+
LOOP_LAG_MAX = new Gauge(
|
|
8028
|
+
"agent_moss_event_loop_lag_max_seconds",
|
|
8029
|
+
"Maximum event loop lag observed since process start, in seconds."
|
|
8030
|
+
);
|
|
8031
|
+
UPTIME = new Gauge(
|
|
8032
|
+
"agent_moss_uptime_seconds",
|
|
8033
|
+
"Seconds since process start."
|
|
8034
|
+
);
|
|
8035
|
+
LLM_CIRCUIT_STATE = new Gauge(
|
|
8036
|
+
"agent_moss_llm_circuit_state",
|
|
8037
|
+
"LLM circuit breaker state (0=closed, 1=open, 2=half_open)."
|
|
8038
|
+
);
|
|
8039
|
+
LLM_SHORT_CIRCUIT_TOTAL = new Counter(
|
|
8040
|
+
"agent_moss_llm_short_circuit_total",
|
|
8041
|
+
"LLM calls short-circuited by the breaker (no network request made)."
|
|
8042
|
+
);
|
|
8043
|
+
}
|
|
8044
|
+
});
|
|
8045
|
+
|
|
7578
8046
|
// src/engine/token-stats.ts
|
|
7579
8047
|
var token_stats_exports = {};
|
|
7580
8048
|
__export(token_stats_exports, {
|
|
@@ -7583,9 +8051,10 @@ __export(token_stats_exports, {
|
|
|
7583
8051
|
getTokenStats: () => getTokenStats,
|
|
7584
8052
|
getTokenTrend: () => getTokenTrend,
|
|
7585
8053
|
recordTokenUsage: () => recordTokenUsage,
|
|
7586
|
-
resetTokenStats: () => resetTokenStats
|
|
8054
|
+
resetTokenStats: () => resetTokenStats,
|
|
8055
|
+
resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
|
|
7587
8056
|
});
|
|
7588
|
-
import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2 } from "fs";
|
|
8057
|
+
import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync5 } from "fs";
|
|
7589
8058
|
function getStatsPath() {
|
|
7590
8059
|
const envPath = process.env[ENV_STATS_PATH];
|
|
7591
8060
|
if (envPath) return envPath;
|
|
@@ -7593,11 +8062,24 @@ function getStatsPath() {
|
|
|
7593
8062
|
}
|
|
7594
8063
|
function loadAllRecords(statsPath) {
|
|
7595
8064
|
if (!existsSync13(statsPath)) return [];
|
|
8065
|
+
let sig = "";
|
|
7596
8066
|
try {
|
|
7597
|
-
const
|
|
7598
|
-
|
|
7599
|
-
|
|
8067
|
+
const st = statSync5(statsPath);
|
|
8068
|
+
sig = `${st.mtimeMs}:${st.size}`;
|
|
8069
|
+
} catch {
|
|
7600
8070
|
return [];
|
|
8071
|
+
}
|
|
8072
|
+
if (_recordsCache && _recordsCache.path === statsPath && _recordsCache.sig === sig) {
|
|
8073
|
+
return _recordsCache.records.slice();
|
|
8074
|
+
}
|
|
8075
|
+
try {
|
|
8076
|
+
const data = JSON.parse(readFileSync13(statsPath, "utf-8"));
|
|
8077
|
+
let records;
|
|
8078
|
+
if (Array.isArray(data)) records = data;
|
|
8079
|
+
else if (data && Array.isArray(data.records)) records = data.records;
|
|
8080
|
+
else records = [];
|
|
8081
|
+
_recordsCache = { path: statsPath, sig, records };
|
|
8082
|
+
return records.slice();
|
|
7601
8083
|
} catch (e) {
|
|
7602
8084
|
return [];
|
|
7603
8085
|
}
|
|
@@ -7607,9 +8089,22 @@ function saveRecords(statsPath, records) {
|
|
|
7607
8089
|
const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
|
|
7608
8090
|
if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
|
|
7609
8091
|
writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
|
|
8092
|
+
try {
|
|
8093
|
+
const st = statSync5(statsPath);
|
|
8094
|
+
_recordsCache = {
|
|
8095
|
+
path: statsPath,
|
|
8096
|
+
sig: `${st.mtimeMs}:${st.size}`,
|
|
8097
|
+
records: records.slice()
|
|
8098
|
+
};
|
|
8099
|
+
} catch {
|
|
8100
|
+
_recordsCache = null;
|
|
8101
|
+
}
|
|
7610
8102
|
} catch (e) {
|
|
7611
8103
|
}
|
|
7612
8104
|
}
|
|
8105
|
+
function resetTokenStatsCacheForTests() {
|
|
8106
|
+
_recordsCache = null;
|
|
8107
|
+
}
|
|
7613
8108
|
function recordTokenUsage(record) {
|
|
7614
8109
|
const statsPath = getStatsPath();
|
|
7615
8110
|
const records = loadAllRecords(statsPath);
|
|
@@ -7738,8 +8233,9 @@ function resetTokenStats() {
|
|
|
7738
8233
|
} catch {
|
|
7739
8234
|
}
|
|
7740
8235
|
}
|
|
8236
|
+
_recordsCache = null;
|
|
7741
8237
|
}
|
|
7742
|
-
var ENV_STATS_PATH, MAX_RECORDS;
|
|
8238
|
+
var ENV_STATS_PATH, MAX_RECORDS, _recordsCache;
|
|
7743
8239
|
var init_token_stats = __esm({
|
|
7744
8240
|
"src/engine/token-stats.ts"() {
|
|
7745
8241
|
"use strict";
|
|
@@ -7747,6 +8243,7 @@ var init_token_stats = __esm({
|
|
|
7747
8243
|
init_paths();
|
|
7748
8244
|
ENV_STATS_PATH = "AGENT_MOSS_TOKEN_STATS_PATH";
|
|
7749
8245
|
MAX_RECORDS = 1e4;
|
|
8246
|
+
_recordsCache = null;
|
|
7750
8247
|
}
|
|
7751
8248
|
});
|
|
7752
8249
|
|
|
@@ -7754,6 +8251,22 @@ var init_token_stats = __esm({
|
|
|
7754
8251
|
import { createHash as createHash3 } from "crypto";
|
|
7755
8252
|
import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
|
|
7756
8253
|
import OpenAI from "openai";
|
|
8254
|
+
function responseFieldLengths(message) {
|
|
8255
|
+
if (!message || typeof message !== "object") return {};
|
|
8256
|
+
const out = {};
|
|
8257
|
+
for (const [key, value] of Object.entries(message)) {
|
|
8258
|
+
if (value === null || value === void 0 || value === "") continue;
|
|
8259
|
+
if (Array.isArray(value) && value.length === 0) continue;
|
|
8260
|
+
if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) continue;
|
|
8261
|
+
if (typeof value === "boolean") continue;
|
|
8262
|
+
try {
|
|
8263
|
+
out[key] = typeof value === "string" ? value.length : String(JSON.stringify(value)).length;
|
|
8264
|
+
} catch {
|
|
8265
|
+
out[key] = -1;
|
|
8266
|
+
}
|
|
8267
|
+
}
|
|
8268
|
+
return out;
|
|
8269
|
+
}
|
|
7757
8270
|
async function runLLMAnalysis(input, previous) {
|
|
7758
8271
|
if (!isLLMAvailable()) {
|
|
7759
8272
|
console.log("[AgentMoss] LLM not configured, skipping deep analysis");
|
|
@@ -7836,7 +8349,23 @@ async function runLLMAnalysis(input, previous) {
|
|
|
7836
8349
|
);
|
|
7837
8350
|
}
|
|
7838
8351
|
logPrompt(prompt, input.aNext, previous.llmLogPath);
|
|
8352
|
+
traceFull("l3.prompt", {
|
|
8353
|
+
phase: "security_judge",
|
|
8354
|
+
model: config.model,
|
|
8355
|
+
base_url: config.baseUrl,
|
|
8356
|
+
action_type: input.aNext.actionType,
|
|
8357
|
+
action_detail: input.aNext.actionDetail,
|
|
8358
|
+
prompt,
|
|
8359
|
+
prompt_chars: prompt.length
|
|
8360
|
+
});
|
|
7839
8361
|
const result = await analyzeWithLLM(prompt, config);
|
|
8362
|
+
traceSummary("l3.verdict", {
|
|
8363
|
+
allowed: result.allowed,
|
|
8364
|
+
risk_level: result.riskLevel,
|
|
8365
|
+
risk_type: result.riskType,
|
|
8366
|
+
reason: result.reason,
|
|
8367
|
+
confidence: result.confidence
|
|
8368
|
+
});
|
|
7840
8369
|
if (llmCache.size >= LLM_CACHE_MAX) {
|
|
7841
8370
|
const firstKey = llmCache.keys().next().value;
|
|
7842
8371
|
if (firstKey) llmCache.delete(firstKey);
|
|
@@ -7978,6 +8507,14 @@ function formatHints(previous) {
|
|
|
7978
8507
|
}
|
|
7979
8508
|
async function analyzeWithLLM(prompt, config) {
|
|
7980
8509
|
console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
|
|
8510
|
+
const _llmStart = performance.now();
|
|
8511
|
+
const _recordLlm = (result) => {
|
|
8512
|
+
try {
|
|
8513
|
+
LLM_CALLS_TOTAL.inc(1, { result });
|
|
8514
|
+
LLM_DURATION.observe(Math.max(0, (performance.now() - _llmStart) / 1e3), { result });
|
|
8515
|
+
} catch {
|
|
8516
|
+
}
|
|
8517
|
+
};
|
|
7981
8518
|
const provider = detectProvider(config.baseUrl, config.provider);
|
|
7982
8519
|
const extraHeaders = getProviderHeaders(provider);
|
|
7983
8520
|
if (Object.keys(extraHeaders).length > 0) {
|
|
@@ -7999,6 +8536,17 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7999
8536
|
console.error(`[AgentMoss] totalTimeout (${timeoutCfg.totalTimeout}s) exceeded, aborting all LLM calls`);
|
|
8000
8537
|
abortController.abort();
|
|
8001
8538
|
}, totalTimeoutMs);
|
|
8539
|
+
const breaker = getBreaker();
|
|
8540
|
+
if (!breaker.allow()) {
|
|
8541
|
+
try {
|
|
8542
|
+
LLM_SHORT_CIRCUIT_TOTAL.inc(1);
|
|
8543
|
+
} catch {
|
|
8544
|
+
}
|
|
8545
|
+
_recordLlm("error");
|
|
8546
|
+
throw new Error(
|
|
8547
|
+
"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"
|
|
8548
|
+
);
|
|
8549
|
+
}
|
|
8002
8550
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
8003
8551
|
if (abortController.signal.aborted) {
|
|
8004
8552
|
break;
|
|
@@ -8012,22 +8560,49 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
8012
8560
|
{ 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" },
|
|
8013
8561
|
{ role: "user", content: prompt }
|
|
8014
8562
|
],
|
|
8015
|
-
signal: abortController.signal
|
|
8563
|
+
signal: abortController.signal,
|
|
8564
|
+
// 私有化网关的额外参数(关思考等)原样透传;空则不传。
|
|
8565
|
+
...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
|
|
8016
8566
|
});
|
|
8017
8567
|
const message = response.choices[0]?.message;
|
|
8018
8568
|
const content = message?.content ?? "";
|
|
8019
8569
|
const finishReason = response.choices[0]?.finish_reason;
|
|
8020
|
-
const
|
|
8570
|
+
const fieldLengths = responseFieldLengths(message);
|
|
8021
8571
|
const usage = response.usage;
|
|
8022
8572
|
if (!content) {
|
|
8023
|
-
const detail = `model=${response.model || config.model} finish_reason=${finishReason}
|
|
8573
|
+
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 ?? "?"}`;
|
|
8574
|
+
traceFull("l3.empty_response", {
|
|
8575
|
+
model: response.model || config.model,
|
|
8576
|
+
finish_reason: finishReason,
|
|
8577
|
+
message,
|
|
8578
|
+
prompt_tokens: usage?.prompt_tokens ?? 0,
|
|
8579
|
+
completion_tokens: usage?.completion_tokens ?? 0
|
|
8580
|
+
});
|
|
8581
|
+
let fullMessage = "<empty>";
|
|
8582
|
+
try {
|
|
8583
|
+
fullMessage = JSON.stringify(message ?? {});
|
|
8584
|
+
if (fullMessage.length > 8e3) {
|
|
8585
|
+
fullMessage = `${fullMessage.slice(0, 8e3)}...[truncated ${fullMessage.length} chars]`;
|
|
8586
|
+
}
|
|
8587
|
+
} catch {
|
|
8588
|
+
fullMessage = "<\u65E0\u6CD5\u5E8F\u5217\u5316>";
|
|
8589
|
+
}
|
|
8024
8590
|
if (finishReason === "length") {
|
|
8025
|
-
console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
|
|
8591
|
+
console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
|
|
8026
8592
|
throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
|
|
8027
8593
|
}
|
|
8028
|
-
console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
|
|
8594
|
+
console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
|
|
8595
|
+
_recordLlm("empty");
|
|
8029
8596
|
throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
|
|
8030
8597
|
}
|
|
8598
|
+
traceFull("l3.response", {
|
|
8599
|
+
phase: "security_judge",
|
|
8600
|
+
attempt: attempt + 1,
|
|
8601
|
+
model: response.model || config.model,
|
|
8602
|
+
content,
|
|
8603
|
+
prompt_tokens: usage?.prompt_tokens ?? 0,
|
|
8604
|
+
completion_tokens: usage?.completion_tokens ?? 0
|
|
8605
|
+
});
|
|
8031
8606
|
console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
|
|
8032
8607
|
let jsonStr = content.trim();
|
|
8033
8608
|
if (jsonStr.startsWith("```")) {
|
|
@@ -8058,6 +8633,8 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
8058
8633
|
clearTimeout(totalTimeoutTimer);
|
|
8059
8634
|
const riskLevel = parsed.riskLevel ?? parsed.risk_level;
|
|
8060
8635
|
const riskType = parsed.riskType ?? parsed.risk_type;
|
|
8636
|
+
breaker.recordSuccess();
|
|
8637
|
+
_recordLlm("success");
|
|
8061
8638
|
return {
|
|
8062
8639
|
allowed: parsed.allowed !== false,
|
|
8063
8640
|
reason: parsed.reason || "LLM \u5206\u6790\u5B8C\u6210",
|
|
@@ -8068,6 +8645,7 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
8068
8645
|
violatedLayers: ["L3.1"]
|
|
8069
8646
|
};
|
|
8070
8647
|
} catch (err) {
|
|
8648
|
+
breaker.recordFailure();
|
|
8071
8649
|
if (abortController.signal.aborted) {
|
|
8072
8650
|
console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
|
|
8073
8651
|
break;
|
|
@@ -8100,6 +8678,9 @@ var init_llm_analyzer = __esm({
|
|
|
8100
8678
|
init_template_loader();
|
|
8101
8679
|
init_script_analyzer();
|
|
8102
8680
|
init_script_content_analyzer();
|
|
8681
|
+
init_trace_log();
|
|
8682
|
+
init_metrics();
|
|
8683
|
+
init_circuit_breaker();
|
|
8103
8684
|
llmCache = /* @__PURE__ */ new Map();
|
|
8104
8685
|
LLM_CACHE_MAX = 200;
|
|
8105
8686
|
}
|
|
@@ -8138,8 +8719,8 @@ var init_rule_store = __esm({
|
|
|
8138
8719
|
BrainRuleStore = class {
|
|
8139
8720
|
path;
|
|
8140
8721
|
data;
|
|
8141
|
-
constructor(
|
|
8142
|
-
this.path =
|
|
8722
|
+
constructor(path7) {
|
|
8723
|
+
this.path = path7 || getRulesPath();
|
|
8143
8724
|
this.data = this.load();
|
|
8144
8725
|
}
|
|
8145
8726
|
load() {
|
|
@@ -8592,10 +9173,10 @@ ${reason.slice(0, 500)}
|
|
|
8592
9173
|
const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
|
|
8593
9174
|
let mm;
|
|
8594
9175
|
while ((mm = pathRe.exec(src)) !== null) {
|
|
8595
|
-
const
|
|
8596
|
-
if (
|
|
8597
|
-
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(
|
|
8598
|
-
const gen = this.generalizePath(
|
|
9176
|
+
const path7 = mm[1];
|
|
9177
|
+
if (path7.split("/").length < 3) continue;
|
|
9178
|
+
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path7)) continue;
|
|
9179
|
+
const gen = this.generalizePath(path7);
|
|
8599
9180
|
if (seen.has(gen)) continue;
|
|
8600
9181
|
seen.add(gen);
|
|
8601
9182
|
patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
|
|
@@ -8614,8 +9195,8 @@ ${reason.slice(0, 500)}
|
|
|
8614
9195
|
}
|
|
8615
9196
|
return false;
|
|
8616
9197
|
}
|
|
8617
|
-
generalizePath(
|
|
8618
|
-
const p =
|
|
9198
|
+
generalizePath(path7) {
|
|
9199
|
+
const p = path7.toLowerCase();
|
|
8619
9200
|
if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
|
|
8620
9201
|
return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
|
|
8621
9202
|
}
|
|
@@ -9003,26 +9584,26 @@ function writeExportFiles(outDir, rules, skills) {
|
|
|
9003
9584
|
byLayer.get(r.layer).push(r);
|
|
9004
9585
|
}
|
|
9005
9586
|
for (const layer of [...byLayer.keys()].sort((a, b) => a - b)) {
|
|
9006
|
-
const
|
|
9007
|
-
writeFileSync5(
|
|
9008
|
-
written.push(
|
|
9587
|
+
const path7 = join14(rulesDir2, `l${layer}_brain_rules.json`);
|
|
9588
|
+
writeFileSync5(path7, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
|
|
9589
|
+
written.push(path7);
|
|
9009
9590
|
}
|
|
9010
9591
|
if (rules.length === 0) {
|
|
9011
|
-
const
|
|
9012
|
-
writeFileSync5(
|
|
9013
|
-
written.push(
|
|
9592
|
+
const path7 = join14(rulesDir2, "empty.txt");
|
|
9593
|
+
writeFileSync5(path7, "(no brain rules to contribute)", "utf-8");
|
|
9594
|
+
written.push(path7);
|
|
9014
9595
|
}
|
|
9015
9596
|
const skillsDir = join14(outDir, "skills");
|
|
9016
9597
|
mkdirSync6(skillsDir, { recursive: true });
|
|
9017
9598
|
for (const sk of skills) {
|
|
9018
|
-
const
|
|
9019
|
-
writeFileSync5(
|
|
9020
|
-
written.push(
|
|
9599
|
+
const path7 = join14(skillsDir, `${sk.name}.md`);
|
|
9600
|
+
writeFileSync5(path7, sk.content || "", "utf-8");
|
|
9601
|
+
written.push(path7);
|
|
9021
9602
|
}
|
|
9022
9603
|
if (skills.length === 0) {
|
|
9023
|
-
const
|
|
9024
|
-
writeFileSync5(
|
|
9025
|
-
written.push(
|
|
9604
|
+
const path7 = join14(skillsDir, "empty.txt");
|
|
9605
|
+
writeFileSync5(path7, "(no brain skills to contribute)", "utf-8");
|
|
9606
|
+
written.push(path7);
|
|
9026
9607
|
}
|
|
9027
9608
|
return written;
|
|
9028
9609
|
}
|
|
@@ -9471,38 +10052,38 @@ function labelEvent(actionDetail) {
|
|
|
9471
10052
|
}
|
|
9472
10053
|
return hits;
|
|
9473
10054
|
}
|
|
9474
|
-
function evaluateLTL(formula,
|
|
10055
|
+
function evaluateLTL(formula, trace2, pos) {
|
|
9475
10056
|
const op = formula[0];
|
|
9476
10057
|
switch (op) {
|
|
9477
10058
|
case "ap":
|
|
9478
|
-
return
|
|
10059
|
+
return trace2[pos].has(formula[1]);
|
|
9479
10060
|
case "!":
|
|
9480
|
-
return !evaluateLTL(formula[1],
|
|
10061
|
+
return !evaluateLTL(formula[1], trace2, pos);
|
|
9481
10062
|
case "&":
|
|
9482
|
-
return evaluateLTL(formula[1],
|
|
10063
|
+
return evaluateLTL(formula[1], trace2, pos) && evaluateLTL(formula[2], trace2, pos);
|
|
9483
10064
|
case "|":
|
|
9484
|
-
return evaluateLTL(formula[1],
|
|
10065
|
+
return evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
|
|
9485
10066
|
case "->":
|
|
9486
|
-
return !evaluateLTL(formula[1],
|
|
10067
|
+
return !evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
|
|
9487
10068
|
case "X":
|
|
9488
|
-
return pos + 1 <
|
|
10069
|
+
return pos + 1 < trace2.length && evaluateLTL(formula[1], trace2, pos + 1);
|
|
9489
10070
|
case "G": {
|
|
9490
|
-
for (let j = pos; j <
|
|
9491
|
-
if (!evaluateLTL(formula[1],
|
|
10071
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
10072
|
+
if (!evaluateLTL(formula[1], trace2, j)) return false;
|
|
9492
10073
|
}
|
|
9493
10074
|
return true;
|
|
9494
10075
|
}
|
|
9495
10076
|
case "F": {
|
|
9496
|
-
for (let j = pos; j <
|
|
9497
|
-
if (evaluateLTL(formula[1],
|
|
10077
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
10078
|
+
if (evaluateLTL(formula[1], trace2, j)) return true;
|
|
9498
10079
|
}
|
|
9499
10080
|
return false;
|
|
9500
10081
|
}
|
|
9501
10082
|
case "U": {
|
|
9502
|
-
for (let j = pos; j <
|
|
9503
|
-
if (evaluateLTL(formula[2],
|
|
10083
|
+
for (let j = pos; j < trace2.length; j++) {
|
|
10084
|
+
if (evaluateLTL(formula[2], trace2, j)) {
|
|
9504
10085
|
for (let k = pos; k < j; k++) {
|
|
9505
|
-
if (!evaluateLTL(formula[1],
|
|
10086
|
+
if (!evaluateLTL(formula[1], trace2, k)) return false;
|
|
9506
10087
|
}
|
|
9507
10088
|
return true;
|
|
9508
10089
|
}
|
|
@@ -9531,11 +10112,11 @@ function checkMCRules(graph) {
|
|
|
9531
10112
|
const mc = loadMC();
|
|
9532
10113
|
const rules = mc.rules || [];
|
|
9533
10114
|
if (rules.length === 0) return violations;
|
|
9534
|
-
const
|
|
10115
|
+
const trace2 = nodes.map((n) => labelEvent(n.actionDetail));
|
|
9535
10116
|
const witnessMode = graph.witnessIdx !== void 0;
|
|
9536
10117
|
for (const rule of rules) {
|
|
9537
10118
|
if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
|
|
9538
|
-
if (ruleViolates(rule,
|
|
10119
|
+
if (ruleViolates(rule, trace2, witnessMode)) {
|
|
9539
10120
|
violations.push({
|
|
9540
10121
|
propertyId: String(rule.id || "mc-ltl"),
|
|
9541
10122
|
reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
|
|
@@ -9726,12 +10307,12 @@ var init_builder = __esm({
|
|
|
9726
10307
|
});
|
|
9727
10308
|
|
|
9728
10309
|
// src/engine/formal-engine/properties.ts
|
|
9729
|
-
function graphFromPath(nodes,
|
|
10310
|
+
function graphFromPath(nodes, path7, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
|
|
9730
10311
|
const byKey = /* @__PURE__ */ new Map();
|
|
9731
10312
|
for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
|
|
9732
10313
|
const gNodes = [];
|
|
9733
10314
|
const gEdges = [];
|
|
9734
|
-
for (const item of
|
|
10315
|
+
for (const item of path7) {
|
|
9735
10316
|
const n = byKey.get(`${item.sessionId}#${item.seq}`);
|
|
9736
10317
|
gNodes.push({
|
|
9737
10318
|
session_id: item.sessionId,
|
|
@@ -9797,22 +10378,22 @@ function checkCrossSessionChain(graph) {
|
|
|
9797
10378
|
if (witness !== void 0) {
|
|
9798
10379
|
if (nodes[witness].stage !== stages[stages.length - 1]) continue;
|
|
9799
10380
|
let matched = 0;
|
|
9800
|
-
const
|
|
10381
|
+
const path7 = [];
|
|
9801
10382
|
for (let k = 0; k < witness; k++) {
|
|
9802
10383
|
const n = nodes[k];
|
|
9803
10384
|
if (matched < stages.length - 1 && n.stage === stages[matched]) {
|
|
9804
10385
|
matched += 1;
|
|
9805
|
-
|
|
10386
|
+
path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9806
10387
|
}
|
|
9807
10388
|
}
|
|
9808
10389
|
if (matched < stages.length - 1) continue;
|
|
9809
|
-
|
|
10390
|
+
path7.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
|
|
9810
10391
|
violations.push({
|
|
9811
10392
|
propertyId: "cross-" + chain.id,
|
|
9812
10393
|
reason: chain.reason,
|
|
9813
10394
|
riskLevel: chain.riskLevel,
|
|
9814
|
-
path:
|
|
9815
|
-
graph: graphFromPath(nodes,
|
|
10395
|
+
path: path7,
|
|
10396
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9816
10397
|
property_id: "cross-" + chain.id,
|
|
9817
10398
|
property_short: "P1",
|
|
9818
10399
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -9822,11 +10403,11 @@ function checkCrossSessionChain(graph) {
|
|
|
9822
10403
|
} else {
|
|
9823
10404
|
let matched = 0;
|
|
9824
10405
|
let stageIdx = 0;
|
|
9825
|
-
const
|
|
10406
|
+
const path7 = [];
|
|
9826
10407
|
for (const n of nodes) {
|
|
9827
10408
|
if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
|
|
9828
10409
|
matched += 1;
|
|
9829
|
-
|
|
10410
|
+
path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9830
10411
|
stageIdx += 1;
|
|
9831
10412
|
if (matched >= stages.length) break;
|
|
9832
10413
|
}
|
|
@@ -9836,8 +10417,8 @@ function checkCrossSessionChain(graph) {
|
|
|
9836
10417
|
propertyId: "cross-" + chain.id,
|
|
9837
10418
|
reason: chain.reason,
|
|
9838
10419
|
riskLevel: chain.riskLevel,
|
|
9839
|
-
path:
|
|
9840
|
-
graph: graphFromPath(nodes,
|
|
10420
|
+
path: path7,
|
|
10421
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
9841
10422
|
property_id: "cross-" + chain.id,
|
|
9842
10423
|
property_short: "P1",
|
|
9843
10424
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -9884,7 +10465,7 @@ function checkSensitiveDataFlow(graph) {
|
|
|
9884
10465
|
}
|
|
9885
10466
|
}
|
|
9886
10467
|
}
|
|
9887
|
-
const
|
|
10468
|
+
const tracePath2 = (idx) => {
|
|
9888
10469
|
const chain = [idx];
|
|
9889
10470
|
const seen = /* @__PURE__ */ new Set([idx]);
|
|
9890
10471
|
while (true) {
|
|
@@ -9943,7 +10524,7 @@ function checkSensitiveDataFlow(graph) {
|
|
|
9943
10524
|
for (const i of candidates) {
|
|
9944
10525
|
const n = nodes[i];
|
|
9945
10526
|
if (tainted.has(i) && EXFIL_RE.test(n.actionDetail)) {
|
|
9946
|
-
const chain =
|
|
10527
|
+
const chain = tracePath2(i);
|
|
9947
10528
|
violations.push({
|
|
9948
10529
|
propertyId: "sensitive-data-flow",
|
|
9949
10530
|
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`,
|
|
@@ -10058,7 +10639,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10058
10639
|
if (candidates.length > 0) {
|
|
10059
10640
|
const pre = nodes[candidates[candidates.length - 1]];
|
|
10060
10641
|
const post = nodes[firstEv];
|
|
10061
|
-
const
|
|
10642
|
+
const path7 = [
|
|
10062
10643
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
10063
10644
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
10064
10645
|
];
|
|
@@ -10066,8 +10647,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10066
10647
|
propertyId: "no-exfil-after-privesc",
|
|
10067
10648
|
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",
|
|
10068
10649
|
riskLevel: "critical",
|
|
10069
|
-
path:
|
|
10070
|
-
graph: graphFromPath(nodes,
|
|
10650
|
+
path: path7,
|
|
10651
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
10071
10652
|
property_id: "no-exfil-after-privesc",
|
|
10072
10653
|
property_short: "P4",
|
|
10073
10654
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10084,7 +10665,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10084
10665
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
10085
10666
|
if (!isExfilNode(nodes[j])) continue;
|
|
10086
10667
|
if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
|
|
10087
|
-
const
|
|
10668
|
+
const path7 = [
|
|
10088
10669
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
10089
10670
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
10090
10671
|
];
|
|
@@ -10092,8 +10673,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10092
10673
|
propertyId: "no-exfil-after-privesc",
|
|
10093
10674
|
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",
|
|
10094
10675
|
riskLevel: "critical",
|
|
10095
|
-
path:
|
|
10096
|
-
graph: graphFromPath(nodes,
|
|
10676
|
+
path: path7,
|
|
10677
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
10097
10678
|
property_id: "no-exfil-after-privesc",
|
|
10098
10679
|
property_short: "P4",
|
|
10099
10680
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10125,7 +10706,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10125
10706
|
}
|
|
10126
10707
|
if (pre) {
|
|
10127
10708
|
const post = nodes[firstEv];
|
|
10128
|
-
const
|
|
10709
|
+
const path7 = [
|
|
10129
10710
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
10130
10711
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
10131
10712
|
];
|
|
@@ -10133,8 +10714,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10133
10714
|
propertyId: "no-exfil-after-credential",
|
|
10134
10715
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
10135
10716
|
riskLevel: "critical",
|
|
10136
|
-
path:
|
|
10137
|
-
graph: graphFromPath(nodes,
|
|
10717
|
+
path: path7,
|
|
10718
|
+
graph: graphFromPath(nodes, path7, "data", {
|
|
10138
10719
|
property_id: "no-exfil-after-credential",
|
|
10139
10720
|
property_short: "P5",
|
|
10140
10721
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10150,7 +10731,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10150
10731
|
if (!isCredNode(nodes[i])) continue;
|
|
10151
10732
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
10152
10733
|
if (isExfilNode(nodes[j])) {
|
|
10153
|
-
const
|
|
10734
|
+
const path7 = [
|
|
10154
10735
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
10155
10736
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
10156
10737
|
];
|
|
@@ -10158,8 +10739,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10158
10739
|
propertyId: "no-exfil-after-credential",
|
|
10159
10740
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
10160
10741
|
riskLevel: "critical",
|
|
10161
|
-
path:
|
|
10162
|
-
graph: graphFromPath(nodes,
|
|
10742
|
+
path: path7,
|
|
10743
|
+
graph: graphFromPath(nodes, path7, "data", {
|
|
10163
10744
|
property_id: "no-exfil-after-credential",
|
|
10164
10745
|
property_short: "P5",
|
|
10165
10746
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10318,13 +10899,13 @@ function checkSensitiveDataAggregation(graph) {
|
|
|
10318
10899
|
if (!isExfilNode(n)) continue;
|
|
10319
10900
|
const srcs = sourcesFor(i);
|
|
10320
10901
|
if (srcs.size >= 2) {
|
|
10321
|
-
const
|
|
10902
|
+
const path7 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
10322
10903
|
violations.push({
|
|
10323
10904
|
propertyId: "sensitive-data-aggregation",
|
|
10324
10905
|
reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
|
|
10325
10906
|
riskLevel: "critical",
|
|
10326
|
-
path:
|
|
10327
|
-
graph: graphFromPath(nodes,
|
|
10907
|
+
path: path7,
|
|
10908
|
+
graph: graphFromPath(nodes, path7, "next", {
|
|
10328
10909
|
property_id: "sensitive-data-aggregation",
|
|
10329
10910
|
property_short: "P8",
|
|
10330
10911
|
property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
|
|
@@ -10783,11 +11364,11 @@ var init_stateful = __esm({
|
|
|
10783
11364
|
}
|
|
10784
11365
|
}
|
|
10785
11366
|
chainPath(stages) {
|
|
10786
|
-
const
|
|
11367
|
+
const path7 = [];
|
|
10787
11368
|
let want = stages[0];
|
|
10788
11369
|
for (const n of this.nodes_) {
|
|
10789
11370
|
if (n.stage === want) {
|
|
10790
|
-
|
|
11371
|
+
path7.push({
|
|
10791
11372
|
sessionId: n.sessionId,
|
|
10792
11373
|
seq: n.seq,
|
|
10793
11374
|
stage: n.stage,
|
|
@@ -10803,12 +11384,12 @@ var init_stateful = __esm({
|
|
|
10803
11384
|
}
|
|
10804
11385
|
}
|
|
10805
11386
|
}
|
|
10806
|
-
return
|
|
11387
|
+
return path7;
|
|
10807
11388
|
}
|
|
10808
11389
|
/** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
|
|
10809
11390
|
buildChainGraph(stages, chainId) {
|
|
10810
|
-
const
|
|
10811
|
-
const gNodes =
|
|
11391
|
+
const path7 = this.chainPath(stages);
|
|
11392
|
+
const gNodes = path7.map((p, i) => {
|
|
10812
11393
|
const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
|
|
10813
11394
|
return {
|
|
10814
11395
|
session_id: p.sessionId,
|
|
@@ -11059,16 +11640,42 @@ var init_stateful = __esm({
|
|
|
11059
11640
|
});
|
|
11060
11641
|
|
|
11061
11642
|
// src/engine/formal-engine/chain_state.ts
|
|
11062
|
-
import * as
|
|
11643
|
+
import * as fs5 from "fs";
|
|
11063
11644
|
import * as os2 from "os";
|
|
11064
|
-
import * as
|
|
11645
|
+
import * as path5 from "path";
|
|
11065
11646
|
import { createHash as createHash4 } from "crypto";
|
|
11066
11647
|
function defaultStateDbPath() {
|
|
11067
|
-
const dir = process.env.AGENT_MOSS_STATE_DIR ||
|
|
11648
|
+
const dir = process.env.AGENT_MOSS_STATE_DIR || path5.join(os2.homedir(), ".agentmoss");
|
|
11068
11649
|
const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
|
|
11069
|
-
return
|
|
11650
|
+
return path5.join(dir, `stateful_chains_${tag}.json`);
|
|
11651
|
+
}
|
|
11652
|
+
function registerExitFlush(store) {
|
|
11653
|
+
if (_exitHookRegistered) return;
|
|
11654
|
+
_exitHookRegistered = true;
|
|
11655
|
+
const flush = () => {
|
|
11656
|
+
try {
|
|
11657
|
+
store.flush();
|
|
11658
|
+
} catch {
|
|
11659
|
+
}
|
|
11660
|
+
};
|
|
11661
|
+
process.once("exit", flush);
|
|
11662
|
+
process.once("SIGINT", () => {
|
|
11663
|
+
flush();
|
|
11664
|
+
process.exit(0);
|
|
11665
|
+
});
|
|
11666
|
+
process.once("SIGTERM", () => {
|
|
11667
|
+
flush();
|
|
11668
|
+
process.exit(0);
|
|
11669
|
+
});
|
|
11070
11670
|
}
|
|
11071
|
-
|
|
11671
|
+
function getChainStateStore(filePath = "") {
|
|
11672
|
+
if (_store === null || filePath && filePath !== _store["filePath"]) {
|
|
11673
|
+
_store = new ChainStateStore(filePath);
|
|
11674
|
+
registerExitFlush(_store);
|
|
11675
|
+
}
|
|
11676
|
+
return _store;
|
|
11677
|
+
}
|
|
11678
|
+
var ChainStateStore, _store, _exitHookRegistered;
|
|
11072
11679
|
var init_chain_state = __esm({
|
|
11073
11680
|
"src/engine/formal-engine/chain_state.ts"() {
|
|
11074
11681
|
"use strict";
|
|
@@ -11079,15 +11686,33 @@ var init_chain_state = __esm({
|
|
|
11079
11686
|
filePath;
|
|
11080
11687
|
data;
|
|
11081
11688
|
_timer = null;
|
|
11082
|
-
|
|
11689
|
+
/**
|
|
11690
|
+
* 落盘防抖间隔。**与 Python 端对齐为 1 秒**(2026-11 长稳实测)。
|
|
11691
|
+
*
|
|
11692
|
+
* 原来是 50ms:Node 是单线程,`_syncDirtyToData` 里的 `toSnapshot()` 是
|
|
11693
|
+
* O(节点数) 的全量构建(2 万节点约 40ms),50ms 触发一次等于 80% 的时间
|
|
11694
|
+
* 在序列化,请求全被卡住。1 秒一次把开销摊薄 20 倍;崩溃最坏丢 1 秒增量,
|
|
11695
|
+
* 与 Python 端同一量级。
|
|
11696
|
+
*/
|
|
11697
|
+
_flushDelayMs = 1e3;
|
|
11698
|
+
/**
|
|
11699
|
+
* 内存中的 tracker(唯一事实源)。2026-11 与 Python 端对齐:
|
|
11700
|
+
* 旧实现每次 applyAction 都 `restore(entry.state)` 重建所有节点 +
|
|
11701
|
+
* `toSnapshot()` 全量序列化,O(节点数);长时间运行后每次调用几十到几百毫秒,
|
|
11702
|
+
* 在 Node 单线程上等于把事件循环卡死。现在 apply 只改内存对象,序列化推迟到
|
|
11703
|
+
* 防抖落盘时批量做。
|
|
11704
|
+
*/
|
|
11705
|
+
_trackers = /* @__PURE__ */ new Map();
|
|
11706
|
+
/** 自上次落盘以来变过的 agentId */
|
|
11707
|
+
_dirty = /* @__PURE__ */ new Set();
|
|
11083
11708
|
constructor(filePath = "") {
|
|
11084
11709
|
this.filePath = filePath || defaultStateDbPath();
|
|
11085
11710
|
this.data = this._read();
|
|
11086
11711
|
}
|
|
11087
11712
|
_read() {
|
|
11088
11713
|
try {
|
|
11089
|
-
if (
|
|
11090
|
-
const raw =
|
|
11714
|
+
if (fs5.existsSync(this.filePath)) {
|
|
11715
|
+
const raw = fs5.readFileSync(this.filePath, "utf-8");
|
|
11091
11716
|
return JSON.parse(raw);
|
|
11092
11717
|
}
|
|
11093
11718
|
} catch {
|
|
@@ -11100,12 +11725,22 @@ var init_chain_state = __esm({
|
|
|
11100
11725
|
this._timer = setTimeout(() => {
|
|
11101
11726
|
this._timer = null;
|
|
11102
11727
|
try {
|
|
11103
|
-
|
|
11728
|
+
this._syncDirtyToData();
|
|
11729
|
+
ensurePrivateDir(path5.dirname(this.filePath));
|
|
11104
11730
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
11105
11731
|
} catch {
|
|
11106
11732
|
}
|
|
11107
11733
|
}, this._flushDelayMs);
|
|
11108
11734
|
}
|
|
11735
|
+
/** 把 dirty 的 tracker 序列化进 data(只在落盘时做,避免每次 apply 都 O(n))。 */
|
|
11736
|
+
_syncDirtyToData() {
|
|
11737
|
+
for (const agentId of this._dirty) {
|
|
11738
|
+
const t = this._trackers.get(agentId);
|
|
11739
|
+
if (!t) continue;
|
|
11740
|
+
this.data[agentId] = { state: t.toSnapshot(), updated_at: (/* @__PURE__ */ new Date()).toISOString() };
|
|
11741
|
+
}
|
|
11742
|
+
this._dirty.clear();
|
|
11743
|
+
}
|
|
11109
11744
|
/** 立即落盘(测试/关停前调用,保证状态不丢)。 */
|
|
11110
11745
|
flush() {
|
|
11111
11746
|
if (this._timer !== null) {
|
|
@@ -11113,29 +11748,39 @@ var init_chain_state = __esm({
|
|
|
11113
11748
|
this._timer = null;
|
|
11114
11749
|
}
|
|
11115
11750
|
try {
|
|
11116
|
-
|
|
11751
|
+
this._syncDirtyToData();
|
|
11752
|
+
ensurePrivateDir(path5.dirname(this.filePath));
|
|
11117
11753
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
11118
11754
|
} catch {
|
|
11119
11755
|
}
|
|
11120
11756
|
}
|
|
11121
11757
|
load(agentId) {
|
|
11758
|
+
const cached2 = this._trackers.get(agentId);
|
|
11759
|
+
if (cached2) return cached2;
|
|
11122
11760
|
const entry = this.data[agentId];
|
|
11123
11761
|
if (!entry) return null;
|
|
11124
11762
|
const t = new StatefulChainTracker(agentId);
|
|
11125
11763
|
t.restore(entry.state);
|
|
11764
|
+
this._trackers.set(agentId, t);
|
|
11126
11765
|
return t;
|
|
11127
11766
|
}
|
|
11128
11767
|
save(tracker) {
|
|
11129
|
-
this.
|
|
11130
|
-
|
|
11131
|
-
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
11132
|
-
};
|
|
11768
|
+
this._trackers.set(tracker.agentId, tracker);
|
|
11769
|
+
this._dirty.add(tracker.agentId);
|
|
11133
11770
|
this._scheduleWrite();
|
|
11134
11771
|
}
|
|
11135
11772
|
delete(agentId) {
|
|
11773
|
+
this._trackers.delete(agentId);
|
|
11774
|
+
this._dirty.delete(agentId);
|
|
11136
11775
|
delete this.data[agentId];
|
|
11137
11776
|
this._scheduleWrite();
|
|
11138
11777
|
}
|
|
11778
|
+
/** 当前内存中的 tracker 数 / 节点总数(健康检查用)。 */
|
|
11779
|
+
stats() {
|
|
11780
|
+
let nodes = 0;
|
|
11781
|
+
for (const t of this._trackers.values()) nodes += t.nodes.length;
|
|
11782
|
+
return { agents: this._trackers.size, nodes };
|
|
11783
|
+
}
|
|
11139
11784
|
applyAction(agentId, aNext, sessionId, isError = false, sourceAgent = "", instanceId = "") {
|
|
11140
11785
|
const t = this.load(agentId) || new StatefulChainTracker(agentId);
|
|
11141
11786
|
const r = t.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
|
|
@@ -11150,6 +11795,8 @@ var init_chain_state = __esm({
|
|
|
11150
11795
|
return r;
|
|
11151
11796
|
}
|
|
11152
11797
|
};
|
|
11798
|
+
_store = null;
|
|
11799
|
+
_exitHookRegistered = false;
|
|
11153
11800
|
}
|
|
11154
11801
|
});
|
|
11155
11802
|
|
|
@@ -11257,6 +11904,14 @@ function _resetBrainForTest() {
|
|
|
11257
11904
|
async function runAnalysis(input) {
|
|
11258
11905
|
const observedFormalLayers = [];
|
|
11259
11906
|
const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
|
|
11907
|
+
if (heuristicResult) {
|
|
11908
|
+
traceSummary("l1.result", {
|
|
11909
|
+
hit: !heuristicResult.allowed,
|
|
11910
|
+
risk_level: heuristicResult.riskLevel,
|
|
11911
|
+
risk_type: heuristicResult.riskType,
|
|
11912
|
+
reason: heuristicResult.reason
|
|
11913
|
+
});
|
|
11914
|
+
}
|
|
11260
11915
|
const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
|
|
11261
11916
|
const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
|
|
11262
11917
|
if (heuristicResult && !heuristicResult.allowed) {
|
|
@@ -11400,6 +12055,14 @@ async function runAnalysis(input) {
|
|
|
11400
12055
|
}
|
|
11401
12056
|
}
|
|
11402
12057
|
const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
|
|
12058
|
+
if (logicResult) {
|
|
12059
|
+
traceSummary("l2.result", {
|
|
12060
|
+
hit: !logicResult.allowed,
|
|
12061
|
+
risk_level: logicResult.riskLevel,
|
|
12062
|
+
risk_type: logicResult.riskType,
|
|
12063
|
+
reason: logicResult.reason
|
|
12064
|
+
});
|
|
12065
|
+
}
|
|
11403
12066
|
const l1FileAccessHit = !!(heuristicResult && !heuristicResult.allowed && heuristicResult.riskType === "file_access");
|
|
11404
12067
|
const effectiveResult = logicResult && !logicResult.allowed ? logicResult : l1FileAccessHit ? heuristicResult : null;
|
|
11405
12068
|
if (effectiveResult) {
|
|
@@ -11629,6 +12292,7 @@ var init_coordinator = __esm({
|
|
|
11629
12292
|
init_llm_analyzer();
|
|
11630
12293
|
init_script_content_analyzer();
|
|
11631
12294
|
init_config();
|
|
12295
|
+
init_trace_log();
|
|
11632
12296
|
init_runtime_config();
|
|
11633
12297
|
init_agents();
|
|
11634
12298
|
init_scenarios();
|
|
@@ -12153,7 +12817,7 @@ var init_esm_require = __esm({
|
|
|
12153
12817
|
});
|
|
12154
12818
|
|
|
12155
12819
|
// src/actrail.ts
|
|
12156
|
-
import * as
|
|
12820
|
+
import * as fs6 from "fs";
|
|
12157
12821
|
function escape(value) {
|
|
12158
12822
|
return value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/=/g, "\\e");
|
|
12159
12823
|
}
|
|
@@ -12174,7 +12838,7 @@ function getStoragePath() {
|
|
|
12174
12838
|
function reportEnforcementEvent(opts) {
|
|
12175
12839
|
if (!isEnabled()) return false;
|
|
12176
12840
|
const storagePath = getStoragePath();
|
|
12177
|
-
if (!
|
|
12841
|
+
if (!fs6.existsSync(storagePath)) return false;
|
|
12178
12842
|
try {
|
|
12179
12843
|
let Database;
|
|
12180
12844
|
try {
|
|
@@ -12345,9 +13009,9 @@ var init_pattern_miner = __esm({
|
|
|
12345
13009
|
});
|
|
12346
13010
|
|
|
12347
13011
|
// src/agent-gate-reader.ts
|
|
12348
|
-
import * as
|
|
13012
|
+
import * as fs7 from "fs";
|
|
12349
13013
|
import * as os3 from "os";
|
|
12350
|
-
import * as
|
|
13014
|
+
import * as path6 from "path";
|
|
12351
13015
|
function normalizeAction(row) {
|
|
12352
13016
|
return {
|
|
12353
13017
|
actionType: String(row.action_type || row.tool_name || row.name || ""),
|
|
@@ -12357,10 +13021,10 @@ function normalizeAction(row) {
|
|
|
12357
13021
|
function readJsonDir(dirPath, limit = 1e5) {
|
|
12358
13022
|
const sessions = /* @__PURE__ */ new Map();
|
|
12359
13023
|
try {
|
|
12360
|
-
const files =
|
|
13024
|
+
const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
|
|
12361
13025
|
for (const f of files.slice(-200)) {
|
|
12362
13026
|
const sid = f.replace(/\.json$/, "");
|
|
12363
|
-
const raw =
|
|
13027
|
+
const raw = fs7.readFileSync(path6.join(dirPath, f), "utf-8");
|
|
12364
13028
|
const arr = JSON.parse(raw);
|
|
12365
13029
|
if (!Array.isArray(arr)) continue;
|
|
12366
13030
|
for (const item of arr) {
|
|
@@ -12417,7 +13081,7 @@ function readSqlite(dbPath, limit = 1e5) {
|
|
|
12417
13081
|
function loadAgentGateSessions(dbPath = "") {
|
|
12418
13082
|
if (dbPath) {
|
|
12419
13083
|
try {
|
|
12420
|
-
if (
|
|
13084
|
+
if (fs7.statSync(dbPath).isDirectory()) {
|
|
12421
13085
|
return readJsonDir(dbPath);
|
|
12422
13086
|
}
|
|
12423
13087
|
} catch {
|
|
@@ -12428,7 +13092,7 @@ function loadAgentGateSessions(dbPath = "") {
|
|
|
12428
13092
|
}
|
|
12429
13093
|
const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
|
|
12430
13094
|
if (sql.length > 0) return sql;
|
|
12431
|
-
const jsonDefault =
|
|
13095
|
+
const jsonDefault = path6.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
|
|
12432
13096
|
return readJsonDir(jsonDefault);
|
|
12433
13097
|
}
|
|
12434
13098
|
var DEFAULT_AGENTGATE_SQLITE;
|
|
@@ -12437,7 +13101,7 @@ var init_agent_gate_reader = __esm({
|
|
|
12437
13101
|
"use strict";
|
|
12438
13102
|
init_esm_shims();
|
|
12439
13103
|
init_esm_require();
|
|
12440
|
-
DEFAULT_AGENTGATE_SQLITE =
|
|
13104
|
+
DEFAULT_AGENTGATE_SQLITE = path6.join(
|
|
12441
13105
|
os3.homedir(),
|
|
12442
13106
|
".local",
|
|
12443
13107
|
"share",
|
|
@@ -12519,17 +13183,114 @@ var init_observable = __esm({
|
|
|
12519
13183
|
}
|
|
12520
13184
|
});
|
|
12521
13185
|
|
|
13186
|
+
// src/infra/loop-monitor.ts
|
|
13187
|
+
import { monitorEventLoopDelay } from "perf_hooks";
|
|
13188
|
+
function startLoopMonitor() {
|
|
13189
|
+
if (_histogram !== null) return;
|
|
13190
|
+
_histogram = monitorEventLoopDelay({ resolution: 20 });
|
|
13191
|
+
_histogram.enable();
|
|
13192
|
+
_timer = setInterval(() => {
|
|
13193
|
+
try {
|
|
13194
|
+
_histogram?.reset();
|
|
13195
|
+
} catch {
|
|
13196
|
+
}
|
|
13197
|
+
}, 1e3);
|
|
13198
|
+
if (typeof _timer.unref === "function") _timer.unref();
|
|
13199
|
+
}
|
|
13200
|
+
function loopMonitorSnapshot() {
|
|
13201
|
+
if (_histogram === null) return {};
|
|
13202
|
+
try {
|
|
13203
|
+
const meanMs = _histogram.mean / 1e6;
|
|
13204
|
+
const maxMs = _histogram.max / 1e6;
|
|
13205
|
+
return {
|
|
13206
|
+
loop_lag_ms: Math.round(meanMs * 10) / 10,
|
|
13207
|
+
loop_lag_max_ms: Math.round(maxMs * 10) / 10
|
|
13208
|
+
};
|
|
13209
|
+
} catch {
|
|
13210
|
+
return {};
|
|
13211
|
+
}
|
|
13212
|
+
}
|
|
13213
|
+
var _histogram, _timer;
|
|
13214
|
+
var init_loop_monitor = __esm({
|
|
13215
|
+
"src/infra/loop-monitor.ts"() {
|
|
13216
|
+
"use strict";
|
|
13217
|
+
init_esm_shims();
|
|
13218
|
+
_histogram = null;
|
|
13219
|
+
_timer = null;
|
|
13220
|
+
}
|
|
13221
|
+
});
|
|
13222
|
+
|
|
13223
|
+
// src/infra/runtime-stats.ts
|
|
13224
|
+
function registerPools(pools) {
|
|
13225
|
+
_pools = pools;
|
|
13226
|
+
}
|
|
13227
|
+
function poolsSnapshot() {
|
|
13228
|
+
try {
|
|
13229
|
+
return _pools ? _pools.snapshot() : {};
|
|
13230
|
+
} catch {
|
|
13231
|
+
return {};
|
|
13232
|
+
}
|
|
13233
|
+
}
|
|
13234
|
+
var _pools;
|
|
13235
|
+
var init_runtime_stats = __esm({
|
|
13236
|
+
"src/infra/runtime-stats.ts"() {
|
|
13237
|
+
"use strict";
|
|
13238
|
+
init_esm_shims();
|
|
13239
|
+
_pools = null;
|
|
13240
|
+
}
|
|
13241
|
+
});
|
|
13242
|
+
|
|
12522
13243
|
// src/routes.ts
|
|
12523
13244
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
12524
13245
|
import { join as join19, dirname as dirname12 } from "path";
|
|
12525
13246
|
import { fileURLToPath as fileURLToPath10 } from "url";
|
|
12526
13247
|
async function healthRoute(c) {
|
|
13248
|
+
const metrics = {};
|
|
13249
|
+
try {
|
|
13250
|
+
Object.assign(metrics, loopMonitorSnapshot());
|
|
13251
|
+
} catch {
|
|
13252
|
+
}
|
|
13253
|
+
metrics.pools = poolsSnapshot();
|
|
13254
|
+
try {
|
|
13255
|
+
const chainStats = getChainStateStoreFor("").stats();
|
|
13256
|
+
metrics.chain_agents = chainStats.agents;
|
|
13257
|
+
metrics.chain_nodes = chainStats.nodes;
|
|
13258
|
+
metrics.chain_capacity = MAX_NODES;
|
|
13259
|
+
metrics.chain_usage_pct = Math.round(chainStats.nodes / MAX_NODES * 1e3) / 10;
|
|
13260
|
+
} catch {
|
|
13261
|
+
}
|
|
13262
|
+
const degraded = [];
|
|
13263
|
+
const pct = metrics.chain_usage_pct;
|
|
13264
|
+
if (typeof pct === "number") {
|
|
13265
|
+
if (pct >= 100) {
|
|
13266
|
+
degraded.push(
|
|
13267
|
+
`\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`
|
|
13268
|
+
);
|
|
13269
|
+
} else if (pct >= 90) {
|
|
13270
|
+
degraded.push(
|
|
13271
|
+
`\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`
|
|
13272
|
+
);
|
|
13273
|
+
}
|
|
13274
|
+
}
|
|
13275
|
+
try {
|
|
13276
|
+
const snap = getBreaker().snapshot();
|
|
13277
|
+
if (snap.state === "open") {
|
|
13278
|
+
degraded.push(
|
|
13279
|
+
`\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`
|
|
13280
|
+
);
|
|
13281
|
+
}
|
|
13282
|
+
} catch {
|
|
13283
|
+
}
|
|
12527
13284
|
return c.json(HealthResponseSchema.parse({
|
|
12528
|
-
|
|
13285
|
+
status: degraded.length ? "degraded" : "healthy",
|
|
13286
|
+
degraded,
|
|
13287
|
+
instance: process.env.AGENT_MOSS_INSTANCE || "",
|
|
13288
|
+
metrics
|
|
12529
13289
|
}));
|
|
12530
13290
|
}
|
|
12531
13291
|
async function analyzeRoute(c) {
|
|
12532
13292
|
const t0 = performance.now();
|
|
13293
|
+
const degradedNotes = [];
|
|
12533
13294
|
try {
|
|
12534
13295
|
const body = await c.req.json();
|
|
12535
13296
|
const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
|
|
@@ -12557,6 +13318,20 @@ async function analyzeRoute(c) {
|
|
|
12557
13318
|
const instanceId = String(
|
|
12558
13319
|
req.instance_id || req.metadata?.instance_id || ""
|
|
12559
13320
|
);
|
|
13321
|
+
traceFull("request", {
|
|
13322
|
+
session_id: req.session_id,
|
|
13323
|
+
agent_id: agentId,
|
|
13324
|
+
os_type: osType,
|
|
13325
|
+
cwd: req.cwd,
|
|
13326
|
+
action_type: req.a_next.action_type,
|
|
13327
|
+
action_detail: req.a_next.action_detail,
|
|
13328
|
+
reason: req.reason,
|
|
13329
|
+
prompt_session: req.prompt_session,
|
|
13330
|
+
action_history: req.action_history,
|
|
13331
|
+
prompt_history: req.prompt_history,
|
|
13332
|
+
session_history: req.session_history,
|
|
13333
|
+
metadata: req.metadata
|
|
13334
|
+
});
|
|
12560
13335
|
const result = await analyze({
|
|
12561
13336
|
sessionId: req.session_id,
|
|
12562
13337
|
promptSession: req.prompt_session,
|
|
@@ -12616,6 +13391,29 @@ async function analyzeRoute(c) {
|
|
|
12616
13391
|
llmLogPath: req.metadata?.llm_log_path
|
|
12617
13392
|
});
|
|
12618
13393
|
const durationMs = performance.now() - t0;
|
|
13394
|
+
const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
|
|
13395
|
+
if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
|
|
13396
|
+
console.warn(
|
|
13397
|
+
`[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}`
|
|
13398
|
+
);
|
|
13399
|
+
}
|
|
13400
|
+
try {
|
|
13401
|
+
ANALYZE_TOTAL.inc(1, { decision: result.decision, risk_level: result.risk_level });
|
|
13402
|
+
ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
|
|
13403
|
+
for (const layer of result.violated_layers || []) {
|
|
13404
|
+
LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
|
|
13405
|
+
}
|
|
13406
|
+
} catch {
|
|
13407
|
+
}
|
|
13408
|
+
traceSummary("result", {
|
|
13409
|
+
session_id: req.session_id,
|
|
13410
|
+
decision: result.decision,
|
|
13411
|
+
risk_level: result.risk_level,
|
|
13412
|
+
risk_type: result.risk_type,
|
|
13413
|
+
reason: result.reason,
|
|
13414
|
+
violated_layers: result.violated_layers,
|
|
13415
|
+
duration_ms: Math.round(durationMs * 10) / 10
|
|
13416
|
+
});
|
|
12619
13417
|
try {
|
|
12620
13418
|
reportEnforcementEvent({
|
|
12621
13419
|
traceId: req.session_id,
|
|
@@ -12647,6 +13445,20 @@ async function analyzeRoute(c) {
|
|
|
12647
13445
|
// 来源:真实 agent(桶 key 可能是 __system__)
|
|
12648
13446
|
instanceId
|
|
12649
13447
|
);
|
|
13448
|
+
try {
|
|
13449
|
+
const total = store.stats().nodes;
|
|
13450
|
+
const pct = Math.round(total / MAX_NODES * 1e3) / 10;
|
|
13451
|
+
if (total >= MAX_NODES) {
|
|
13452
|
+
degradedNotes.push(
|
|
13453
|
+
`\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`
|
|
13454
|
+
);
|
|
13455
|
+
} else if (pct >= 90) {
|
|
13456
|
+
degradedNotes.push(
|
|
13457
|
+
`\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`
|
|
13458
|
+
);
|
|
13459
|
+
}
|
|
13460
|
+
} catch {
|
|
13461
|
+
}
|
|
12650
13462
|
const judgment = incMatchedToDeny(inc);
|
|
12651
13463
|
if (judgment) {
|
|
12652
13464
|
const layers = [...result.violated_layers];
|
|
@@ -12689,7 +13501,9 @@ async function analyzeRoute(c) {
|
|
|
12689
13501
|
confidence: result.confidence,
|
|
12690
13502
|
analysis_duration_ms: Math.round(durationMs * 10) / 10,
|
|
12691
13503
|
violation_chain: result.violation_chain ?? [],
|
|
12692
|
-
violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id)
|
|
13504
|
+
violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
|
|
13505
|
+
// 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
|
|
13506
|
+
degraded: degradedNotes
|
|
12693
13507
|
})
|
|
12694
13508
|
);
|
|
12695
13509
|
} catch (err) {
|
|
@@ -12709,8 +13523,7 @@ async function analyzeRoute(c) {
|
|
|
12709
13523
|
}
|
|
12710
13524
|
}
|
|
12711
13525
|
function getChainStateStoreFor(_agentId) {
|
|
12712
|
-
|
|
12713
|
-
return reviewStore;
|
|
13526
|
+
return getChainStateStore();
|
|
12714
13527
|
}
|
|
12715
13528
|
function incMatchedToDeny(inc) {
|
|
12716
13529
|
if (inc.matched) {
|
|
@@ -12919,7 +13732,7 @@ async function brainImportRoute(c) {
|
|
|
12919
13732
|
})));
|
|
12920
13733
|
return c.json({ imported: rules.length });
|
|
12921
13734
|
}
|
|
12922
|
-
var __dirname9
|
|
13735
|
+
var __dirname9;
|
|
12923
13736
|
var init_routes = __esm({
|
|
12924
13737
|
"src/routes.ts"() {
|
|
12925
13738
|
"use strict";
|
|
@@ -12929,14 +13742,18 @@ var init_routes = __esm({
|
|
|
12929
13742
|
init_analyzer();
|
|
12930
13743
|
init_actrail();
|
|
12931
13744
|
init_formal_engine();
|
|
13745
|
+
init_circuit_breaker();
|
|
12932
13746
|
init_pattern_miner();
|
|
12933
13747
|
init_agent_gate_reader();
|
|
12934
13748
|
init_observable();
|
|
12935
13749
|
init_rule_store();
|
|
12936
13750
|
init_skill_manager();
|
|
12937
13751
|
init_asset_dir();
|
|
13752
|
+
init_trace_log();
|
|
13753
|
+
init_loop_monitor();
|
|
13754
|
+
init_runtime_stats();
|
|
13755
|
+
init_metrics();
|
|
12938
13756
|
__dirname9 = dirname12(fileURLToPath10(import.meta.url));
|
|
12939
|
-
reviewStore = null;
|
|
12940
13757
|
}
|
|
12941
13758
|
});
|
|
12942
13759
|
|
|
@@ -13434,9 +14251,11 @@ function createApp() {
|
|
|
13434
14251
|
)
|
|
13435
14252
|
);
|
|
13436
14253
|
const pools = new PooledLimiter();
|
|
14254
|
+
registerPools(pools);
|
|
14255
|
+
startLoopMonitor();
|
|
13437
14256
|
const limiter = new RateLimiter(rateLimitQps());
|
|
13438
14257
|
app.use("*", async (c, next) => {
|
|
13439
|
-
const
|
|
14258
|
+
const path7 = new URL(c.req.url).pathname;
|
|
13440
14259
|
const method = c.req.method.toUpperCase();
|
|
13441
14260
|
if (method === "OPTIONS") return next();
|
|
13442
14261
|
const maxBody = maxBodyBytes();
|
|
@@ -13450,16 +14269,16 @@ function createApp() {
|
|
|
13450
14269
|
if (originCheckEnabled()) {
|
|
13451
14270
|
const origin = c.req.header("origin") || "";
|
|
13452
14271
|
if (origin && !originAllowed(origin, c.req.header("host") || "")) {
|
|
13453
|
-
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${
|
|
14272
|
+
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path7}`);
|
|
13454
14273
|
return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
|
|
13455
14274
|
}
|
|
13456
14275
|
}
|
|
13457
|
-
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers,
|
|
13458
|
-
const isPublicPage = !
|
|
14276
|
+
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path7);
|
|
14277
|
+
const isPublicPage = !path7.startsWith("/console/api") && (path7 === "/console" || path7.startsWith("/console/"));
|
|
13459
14278
|
if (!okAuth && !isPublicPage) {
|
|
13460
14279
|
return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
|
|
13461
14280
|
}
|
|
13462
|
-
if (limiter.enabled &&
|
|
14281
|
+
if (limiter.enabled && path7.startsWith("/api/")) {
|
|
13463
14282
|
const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
|
|
13464
14283
|
if (!limiter.allow(key)) {
|
|
13465
14284
|
return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
|
|
@@ -13493,7 +14312,7 @@ function createApp() {
|
|
|
13493
14312
|
return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
|
|
13494
14313
|
}
|
|
13495
14314
|
}
|
|
13496
|
-
const pool = poolOf(
|
|
14315
|
+
const pool = poolOf(path7);
|
|
13497
14316
|
if (!take(`pool:${pool}`, poolLimit(pool))) {
|
|
13498
14317
|
const qkey = principal ? "p:" + principalHash(principal) : "c:local";
|
|
13499
14318
|
const [qn, abusive] = noteQueueReject(qkey);
|
|
@@ -13510,6 +14329,23 @@ function createApp() {
|
|
|
13510
14329
|
while (keys.length) pools.release(keys.pop());
|
|
13511
14330
|
}
|
|
13512
14331
|
});
|
|
14332
|
+
app.get("/metrics", (c) => {
|
|
14333
|
+
let chainNodes;
|
|
14334
|
+
try {
|
|
14335
|
+
chainNodes = getChainStateStore().stats().nodes;
|
|
14336
|
+
} catch {
|
|
14337
|
+
}
|
|
14338
|
+
const lag = loopMonitorSnapshot();
|
|
14339
|
+
refreshRuntimeGauges({
|
|
14340
|
+
pools: pools.snapshot(),
|
|
14341
|
+
chainNodes,
|
|
14342
|
+
loopLagMs: lag.loop_lag_ms,
|
|
14343
|
+
loopLagMaxMs: lag.loop_lag_max_ms
|
|
14344
|
+
});
|
|
14345
|
+
return c.text(renderPrometheus(), 200, {
|
|
14346
|
+
"Content-Type": "text/plain; version=0.0.4; charset=utf-8"
|
|
14347
|
+
});
|
|
14348
|
+
});
|
|
13513
14349
|
app.get("/api/v1/health", healthRoute);
|
|
13514
14350
|
app.post("/api/v1/analyze", analyzeRoute);
|
|
13515
14351
|
app.post("/api/v1/review", reviewRoute);
|
|
@@ -13670,6 +14506,10 @@ var init_server = __esm({
|
|
|
13670
14506
|
init_routes();
|
|
13671
14507
|
init_console();
|
|
13672
14508
|
init_runtime_config();
|
|
14509
|
+
init_runtime_stats();
|
|
14510
|
+
init_loop_monitor();
|
|
14511
|
+
init_metrics();
|
|
14512
|
+
init_formal_engine();
|
|
13673
14513
|
init_rules_mode();
|
|
13674
14514
|
init_rules_loader();
|
|
13675
14515
|
PooledLimiter = class {
|
|
@@ -13686,6 +14526,10 @@ var init_server = __esm({
|
|
|
13686
14526
|
if (cur <= 1) this.counts.delete(key);
|
|
13687
14527
|
else this.counts.set(key, cur - 1);
|
|
13688
14528
|
}
|
|
14529
|
+
/** 当前各池占用快照(健康检查用,对齐 Python `_PooledLimiter.snapshot`)。 */
|
|
14530
|
+
snapshot() {
|
|
14531
|
+
return Object.fromEntries(this.counts);
|
|
14532
|
+
}
|
|
13689
14533
|
};
|
|
13690
14534
|
RateLimiter = class {
|
|
13691
14535
|
constructor(qps, burst) {
|
|
@@ -13963,7 +14807,7 @@ async function main() {
|
|
|
13963
14807
|
case "init": {
|
|
13964
14808
|
const flagIdx = args.findIndex((a) => a === "--output" || a === "-o");
|
|
13965
14809
|
const output = (flagIdx >= 0 ? args[flagIdx + 1] : void 0) || args.slice(1).find((a) => !a.startsWith("-")) || "input.json";
|
|
13966
|
-
const
|
|
14810
|
+
const fs8 = await import("fs");
|
|
13967
14811
|
const template = {
|
|
13968
14812
|
session_id: "my-session-001",
|
|
13969
14813
|
prompt_session: "Read /var/log/app.log and analyze errors",
|
|
@@ -13973,7 +14817,7 @@ async function main() {
|
|
|
13973
14817
|
os_type: "",
|
|
13974
14818
|
cwd: "/home/user/project"
|
|
13975
14819
|
};
|
|
13976
|
-
|
|
14820
|
+
fs8.writeFileSync(output, JSON.stringify(template, null, 2), "utf-8");
|
|
13977
14821
|
console.log(`Template written to ${output}`);
|
|
13978
14822
|
break;
|
|
13979
14823
|
}
|
|
@@ -13983,13 +14827,13 @@ async function main() {
|
|
|
13983
14827
|
console.error('Usage: agent-moss analyze <input.json | "shell command">');
|
|
13984
14828
|
process.exit(1);
|
|
13985
14829
|
}
|
|
13986
|
-
const
|
|
13987
|
-
const
|
|
14830
|
+
const fs8 = await import("fs");
|
|
14831
|
+
const path7 = await import("path");
|
|
13988
14832
|
const useJson = args.includes("--json");
|
|
13989
14833
|
const osType = process.platform === "win32" ? "windows" : "linux";
|
|
13990
|
-
const isFile =
|
|
14834
|
+
const isFile = fs8.existsSync(target) && fs8.statSync(target).isFile();
|
|
13991
14835
|
if (!isFile) {
|
|
13992
|
-
if (
|
|
14836
|
+
if (fs8.existsSync(target)) {
|
|
13993
14837
|
console.error(`\u9519\u8BEF: \u4E0D\u662F\u6587\u4EF6: ${target}`);
|
|
13994
14838
|
process.exit(2);
|
|
13995
14839
|
}
|
|
@@ -14003,8 +14847,8 @@ async function main() {
|
|
|
14003
14847
|
}
|
|
14004
14848
|
process.exit(await analyzeRawCommand(target, useJson));
|
|
14005
14849
|
}
|
|
14006
|
-
const filePath =
|
|
14007
|
-
const data = JSON.parse(
|
|
14850
|
+
const filePath = path7.resolve(target);
|
|
14851
|
+
const data = JSON.parse(fs8.readFileSync(filePath, "utf-8"));
|
|
14008
14852
|
const { analyze: analyze2 } = await Promise.resolve().then(() => (init_analyzer(), analyzer_exports));
|
|
14009
14853
|
const sessionId = String(data.session_id || "unknown");
|
|
14010
14854
|
const result = await analyze2(buildAnalysisInputFromFile(data));
|
|
@@ -14012,15 +14856,15 @@ async function main() {
|
|
|
14012
14856
|
if (!args.includes("--no-file")) {
|
|
14013
14857
|
const outDirIdx = args.findIndex((a) => a === "--output-dir" || a === "-o");
|
|
14014
14858
|
const outDir = outDirIdx >= 0 && args[outDirIdx + 1] ? args[outDirIdx + 1] : process.cwd();
|
|
14015
|
-
|
|
14859
|
+
fs8.mkdirSync(outDir, { recursive: true });
|
|
14016
14860
|
const safeSession = sessionId.replace(/\//g, "_");
|
|
14017
14861
|
if (result.decision === "Allow") {
|
|
14018
|
-
const policyPath =
|
|
14019
|
-
|
|
14862
|
+
const policyPath = path7.join(outDir, `${safeSession}_policy.toml`);
|
|
14863
|
+
fs8.writeFileSync(policyPath, result.policy || "", "utf-8");
|
|
14020
14864
|
console.log(`Policy written to ${policyPath}`);
|
|
14021
14865
|
} else {
|
|
14022
|
-
const denyPath =
|
|
14023
|
-
|
|
14866
|
+
const denyPath = path7.join(outDir, `${safeSession}_deny_reason.txt`);
|
|
14867
|
+
fs8.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
|
|
14024
14868
|
console.log(`Deny reason written to ${denyPath}`);
|
|
14025
14869
|
}
|
|
14026
14870
|
}
|
|
@@ -14109,8 +14953,8 @@ async function main() {
|
|
|
14109
14953
|
case "install": {
|
|
14110
14954
|
const enable = args.includes("--enable");
|
|
14111
14955
|
const { execSync } = await import("child_process");
|
|
14112
|
-
const
|
|
14113
|
-
const
|
|
14956
|
+
const fs8 = await import("fs");
|
|
14957
|
+
const path7 = await import("path");
|
|
14114
14958
|
const { fileURLToPath: fileURLToPath14 } = await import("url");
|
|
14115
14959
|
if (process.getuid?.() !== 0) {
|
|
14116
14960
|
try {
|
|
@@ -14127,22 +14971,22 @@ async function main() {
|
|
|
14127
14971
|
process.exit(0);
|
|
14128
14972
|
}
|
|
14129
14973
|
const __filename7 = fileURLToPath14(import.meta.url);
|
|
14130
|
-
const __dirname12 =
|
|
14131
|
-
let srcPath =
|
|
14132
|
-
if (!
|
|
14133
|
-
srcPath =
|
|
14974
|
+
const __dirname12 = path7.dirname(__filename7);
|
|
14975
|
+
let srcPath = path7.join(__dirname12, "data", "agent_moss.service");
|
|
14976
|
+
if (!fs8.existsSync(srcPath)) {
|
|
14977
|
+
srcPath = path7.join(__dirname12, "..", "src", "data", "agent_moss.service");
|
|
14134
14978
|
}
|
|
14135
|
-
if (!
|
|
14979
|
+
if (!fs8.existsSync(srcPath)) {
|
|
14136
14980
|
console.error("\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230 agent_moss.service \u6A21\u677F\u6587\u4EF6");
|
|
14137
14981
|
process.exit(1);
|
|
14138
14982
|
}
|
|
14139
14983
|
const which = execSync("which agent-moss 2>/dev/null || true", { encoding: "utf-8" }).trim();
|
|
14140
|
-
const binPath = which || `${process.execPath} ${
|
|
14141
|
-
let content =
|
|
14984
|
+
const binPath = which || `${process.execPath} ${path7.join(__dirname12, "cli.js")}`;
|
|
14985
|
+
let content = fs8.readFileSync(srcPath, "utf-8");
|
|
14142
14986
|
content = content.replace("__AGENT_MOSS_BIN__", binPath);
|
|
14143
14987
|
const dst = "/etc/systemd/system/agent-moss.service";
|
|
14144
|
-
|
|
14145
|
-
|
|
14988
|
+
fs8.writeFileSync(dst, content, "utf-8");
|
|
14989
|
+
fs8.chmodSync(dst, 420);
|
|
14146
14990
|
console.log(`\u2705 \u5DF2\u5B89\u88C5 systemd service: ${dst}`);
|
|
14147
14991
|
execSync("systemctl daemon-reload", { stdio: "inherit" });
|
|
14148
14992
|
console.log("\u2705 systemctl daemon-reload \u5B8C\u6210");
|