@kenhkl/agent-moss 0.17.20 → 0.17.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -40,10 +40,6 @@ function getRulesRoot() {
40
40
  const raw = (process.env[ENV_RULES_ROOT] ?? "").trim();
41
41
  return raw ? raw : null;
42
42
  }
43
- function isRoot() {
44
- const getuid = process.getuid;
45
- return typeof getuid === "function" && getuid() === 0;
46
- }
47
43
  function resolveExplicitOwnerHome() {
48
44
  for (const name of [process.env.SUDO_USER, process.env.LOGNAME, process.env.USER]) {
49
45
  if (name && name !== "root" && name !== "") {
@@ -71,12 +67,6 @@ function listOwnerHomes() {
71
67
  }
72
68
  return homes;
73
69
  }
74
- function resolveOwnerHome() {
75
- const explicit = resolveExplicitOwnerHome();
76
- if (explicit) return explicit;
77
- const owners = listOwnerHomes();
78
- return owners.length > 0 ? owners[0] : null;
79
- }
80
70
  function homeOf(name) {
81
71
  try {
82
72
  const passwd = readFileSync("/etc/passwd", "utf-8");
@@ -94,12 +84,6 @@ function homeOf(name) {
94
84
  function getDataRoot() {
95
85
  const envPath = process.env[ENV_DATA_ROOT];
96
86
  if (envPath) return envPath;
97
- if (isRoot()) {
98
- const ownerHome = resolveOwnerHome();
99
- if (ownerHome) {
100
- return join(ownerHome, ".config", "agentmoss");
101
- }
102
- }
103
87
  return DEFAULT_DATA_ROOT;
104
88
  }
105
89
  function getInstance() {
@@ -424,22 +408,22 @@ function loadToolRegistry() {
424
408
  data.tools = tools;
425
409
  return data;
426
410
  }
427
- function scanStructEntry(cat, value, path6) {
411
+ function scanStructEntry(cat, value, path7) {
428
412
  if (cat === "skills") {
429
413
  if (!value || typeof value !== "object" || Array.isArray(value)) {
430
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
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`);
431
415
  return null;
432
416
  }
433
417
  const out = {};
434
418
  for (const [skCat, skills] of Object.entries(value)) {
435
419
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
436
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
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`);
437
421
  continue;
438
422
  }
439
423
  const keep = {};
440
424
  for (const [name, kws] of Object.entries(skills)) {
441
425
  if (Array.isArray(kws)) keep[name] = kws;
442
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
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`);
443
427
  }
444
428
  if (Object.keys(keep).length > 0) out[skCat] = keep;
445
429
  }
@@ -447,37 +431,37 @@ function scanStructEntry(cat, value, path6) {
447
431
  }
448
432
  if (cat === "ltl_rules") {
449
433
  if (!Array.isArray(value)) {
450
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
434
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
451
435
  return null;
452
436
  }
453
437
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
454
438
  if (keep.length !== value.length) {
455
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
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`);
456
440
  }
457
441
  return keep.length > 0 ? keep : null;
458
442
  }
459
443
  if (cat === "tools") {
460
444
  if (!value || typeof value !== "object" || Array.isArray(value)) {
461
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
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`);
462
446
  return null;
463
447
  }
464
448
  const keep = {};
465
449
  for (const [k, v] of Object.entries(value)) {
466
450
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
467
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
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`);
468
452
  }
469
453
  return Object.keys(keep).length > 0 ? keep : null;
470
454
  }
471
455
  return null;
472
456
  }
473
- function scanRulesFile(path6, kind) {
457
+ function scanRulesFile(path7, kind) {
474
458
  const out = {};
475
459
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
476
460
  let parsed;
477
461
  try {
478
- parsed = JSON.parse(readFileSync2(path6, "utf-8"));
462
+ parsed = JSON.parse(readFileSync2(path7, "utf-8"));
479
463
  } catch (e) {
480
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
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}`);
481
465
  return out;
482
466
  }
483
467
  const classifyFlat = (r) => {
@@ -501,44 +485,44 @@ function scanRulesFile(path6, kind) {
501
485
  }
502
486
  if (flatBad > 0) {
503
487
  console.warn(
504
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
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`
505
489
  );
506
490
  }
507
491
  } else {
508
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
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`);
509
493
  return out;
510
494
  }
511
495
  for (const [cat, rules] of pairs) {
512
496
  if (String(cat).startsWith("_")) continue;
513
497
  if (STRUCT_KEYS.includes(cat)) {
514
- const got = scanStructEntry(cat, rules, path6);
498
+ const got = scanStructEntry(cat, rules, path7);
515
499
  if (got !== null) out[cat] = got;
516
500
  continue;
517
501
  }
518
502
  const required = EXTRA_CATEGORIES[cat];
519
503
  if (!required) {
520
504
  console.warn(
521
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
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`
522
506
  );
523
507
  continue;
524
508
  }
525
509
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
526
510
  console.error(
527
- `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path6} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
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
528
512
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
529
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`
530
514
  );
531
515
  continue;
532
516
  }
533
517
  if (!Array.isArray(rules)) {
534
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
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`);
535
519
  continue;
536
520
  }
537
521
  const items = [];
538
522
  for (const r of rules) {
539
523
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
540
524
  console.warn(
541
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
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`
542
526
  );
543
527
  continue;
544
528
  }
@@ -548,7 +532,7 @@ function scanRulesFile(path6, kind) {
548
532
  }
549
533
  if (Object.keys(out).length > 0) {
550
534
  console.info(
551
- `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path6}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
535
+ `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path7}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
552
536
  );
553
537
  }
554
538
  return out;
@@ -971,10 +955,10 @@ function readExplicitToken() {
971
955
  if (tok) return tok;
972
956
  const fdTok = readFdToken();
973
957
  if (fdTok) return fdTok;
974
- const path6 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
975
- if (path6) {
958
+ const path7 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
959
+ if (path7) {
976
960
  try {
977
- return readFileSync4(path6, "utf-8").trim();
961
+ return readFileSync4(path7, "utf-8").trim();
978
962
  } catch {
979
963
  return "";
980
964
  }
@@ -982,23 +966,23 @@ function readExplicitToken() {
982
966
  return "";
983
967
  }
984
968
  function ensureAutoToken() {
985
- const path6 = autoTokenPath();
969
+ const path7 = autoTokenPath();
986
970
  try {
987
- if (existsSync3(path6) && !lstatSync(path6).isSymbolicLink()) {
988
- const tok2 = readFileSync4(path6, "utf-8").trim();
971
+ if (existsSync3(path7) && !lstatSync(path7).isSymbolicLink()) {
972
+ const tok2 = readFileSync4(path7, "utf-8").trim();
989
973
  if (tok2) {
990
974
  try {
991
- chmodSync(path6, 384);
975
+ chmodSync(path7, 384);
992
976
  } catch {
993
977
  }
994
978
  return tok2;
995
979
  }
996
980
  }
997
981
  const tok = randomBytes(32).toString("base64url");
998
- ensurePrivateDir(dirname2(path6));
999
- if (!writePrivateText(path6, tok + "\n")) return "";
982
+ ensurePrivateDir(dirname2(path7));
983
+ if (!writePrivateText(path7, tok + "\n")) return "";
1000
984
  console.warn(
1001
- `[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${path6}\uFF080600\uFF09\u3002\u5BA2\u6237\u7AEF\u9700\u5E26 \`Authorization: Bearer <token>\`\uFF1B\u67E5\u770B\uFF1Acat ${path6}\uFF1B\u5982\u9700\u5173\u95ED\u9274\u6743\uFF1AAGENT_MOSS_AUTH_MODE=off`
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`
1002
986
  );
1003
987
  return tok;
1004
988
  } catch (e) {
@@ -1071,16 +1055,16 @@ function constEq(a, b) {
1071
1055
  if (ba.length !== bb.length) return false;
1072
1056
  return timingSafeEqual(ba, bb);
1073
1057
  }
1074
- function checkRequestAuth(headers, path6) {
1058
+ function checkRequestAuth(headers, path7) {
1075
1059
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
1076
- const isHealth = HEALTH_PATHS.includes(path6.replace(/\/+$/, ""));
1060
+ const isHealth = HEALTH_PATHS.includes(path7.replace(/\/+$/, ""));
1077
1061
  const [gt0, agents, err] = resolveAuth();
1078
1062
  if (err) return isHealth ? [true, ""] : [false, ""];
1079
1063
  if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
1080
1064
  if (isHealth) return [true, ""];
1081
1065
  const tok = bearer(headers);
1082
1066
  if (!tok) return [false, ""];
1083
- if (path6.startsWith("/console/api")) {
1067
+ if (path7.startsWith("/console/api")) {
1084
1068
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
1085
1069
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
1086
1070
  }
@@ -1099,8 +1083,8 @@ function bindAgent(principal, agentId) {
1099
1083
  if (!agentId) return [true, bound];
1100
1084
  return [bound === agentId, bound];
1101
1085
  }
1102
- function principalOf(headers, path6 = "") {
1103
- const [ok, principal] = checkRequestAuth(headers, path6);
1086
+ function principalOf(headers, path7 = "") {
1087
+ const [ok, principal] = checkRequestAuth(headers, path7);
1104
1088
  return ok ? principal : "";
1105
1089
  }
1106
1090
  function principalHash(principal) {
@@ -1358,11 +1342,11 @@ function errorDetailMode() {
1358
1342
  function maxBodyBytes() {
1359
1343
  return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
1360
1344
  }
1361
- function poolOf(path6) {
1362
- if (path6 === "/api/v1/analyze" || path6.startsWith("/api/v1/analyze/")) return "biz";
1363
- if (path6 === "/api/v1/review" || path6.startsWith("/api/v1/review/")) return "review";
1364
- if (path6 === "/console" || path6.startsWith("/console/") || path6.startsWith("/api/v1/brain")) return "ops";
1365
- if (path6 === "/api/v1/health") return "health";
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";
1366
1350
  return "other";
1367
1351
  }
1368
1352
  function poolLimit(name) {
@@ -1485,6 +1469,8 @@ var init_models = __esm({
1485
1469
  analysis_duration_ms: z.number().default(0),
1486
1470
  // 组合攻击链反例路径:每步 [session_id, seq, stage, timestamp],含真实发生时间
1487
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([]),
1488
1474
  // 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
1489
1475
  violation_graph: z.object({
1490
1476
  // 性质元信息(前端展示"违反了哪条性质")
@@ -1524,12 +1510,18 @@ var init_models = __esm({
1524
1510
  }).nullable().default(null)
1525
1511
  });
1526
1512
  HealthResponseSchema = z.object({
1513
+ // healthy | degraded(2026-11):degraded 表示服务可用但**某项安全能力已降级**
1514
+ // (链状态触顶、LLM 熔断)。任何探活/监控只看 status 就能发现异常。
1527
1515
  status: z.string().default("healthy"),
1516
+ // 降级原因(status=degraded 时非空)
1517
+ degraded: z.array(z.string()).default([]),
1528
1518
  version: z.string().default(version),
1529
1519
  // 归属实例标识:值来自 env AGENT_MOSS_INSTANCE(spawn/systemd 注入),默认空串。
1530
1520
  // 多个 agentmoss 同机并存时,调用方按 instance 过滤避免连到别人的进程。
1531
1521
  // 空=未配置(独立部署或旧版),调用方可选择兼容或严格过滤。
1532
- instance: z.string().default("")
1522
+ instance: z.string().default(""),
1523
+ // 运行态指标(2026-11 增强):事件循环延迟、并发池占用、链状态规模。
1524
+ metrics: z.record(z.unknown()).default({})
1533
1525
  });
1534
1526
  ReviewRequestSchema = z.object({
1535
1527
  agent_id: z.string().default("").describe("\u76EE\u6807 agent \u6807\u8BC6\uFF08\u51B3\u5B9A\u72B6\u6001\u5E93\u5206\u6876\uFF09"),
@@ -1813,7 +1805,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
1813
1805
  os: String(sp.os || "linux").toLowerCase()
1814
1806
  }));
1815
1807
  }
1816
- function _scopeOf(os4, path6) {
1808
+ function _scopeOf(os4, path7) {
1817
1809
  if (!_scopeIndex) {
1818
1810
  _scopeIndex = /* @__PURE__ */ new Map();
1819
1811
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -1821,7 +1813,7 @@ function _scopeOf(os4, path6) {
1821
1813
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
1822
1814
  }
1823
1815
  }
1824
- return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path6}`) || "root";
1816
+ return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path7}`) || "root";
1825
1817
  }
1826
1818
  function getSensitivePathsForOs(osType) {
1827
1819
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -2172,17 +2164,17 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2172
2164
  return null;
2173
2165
  }
2174
2166
  const unreadPaths = [];
2175
- for (const path6 of filteredPaths) {
2167
+ for (const path7 of filteredPaths) {
2176
2168
  const hasRead = [...historyReadPaths].some(
2177
- (rp) => path6 === rp || path6.startsWith(rp) || rp.startsWith(path6)
2169
+ (rp) => path7 === rp || path7.startsWith(rp) || rp.startsWith(path7)
2178
2170
  );
2179
2171
  if (!hasRead) {
2180
- let isCreate = !fs.existsSync(path6);
2172
+ let isCreate = !fs.existsSync(path7);
2181
2173
  if (!isCreate) {
2182
2174
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
2183
2175
  }
2184
2176
  if (!isCreate) {
2185
- unreadPaths.push(path6);
2177
+ unreadPaths.push(path7);
2186
2178
  }
2187
2179
  }
2188
2180
  }
@@ -2376,16 +2368,16 @@ var init_logic_rules = __esm({
2376
2368
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
2377
2369
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
2378
2370
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
2379
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2371
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2380
2372
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
2381
2373
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
2382
- CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2374
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2383
2375
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
2384
2376
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
2385
- CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2377
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2386
2378
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
2387
2379
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
2388
- CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2380
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2389
2381
  _scopeIndex = null;
2390
2382
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
2391
2383
  "ask_user_question",
@@ -4154,7 +4146,9 @@ function loadLLMConfigFromFile(configPath) {
4154
4146
  model: llm.model || "",
4155
4147
  temperature: llm.temperature ?? 0.1,
4156
4148
  maxTokens: llm.max_tokens ?? 4096,
4157
- 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 } : {}
4158
4152
  };
4159
4153
  }
4160
4154
  function loadTimeoutRetryFromFile(configPath) {
@@ -4986,16 +4980,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4986
4980
  if (String(osType || "").toLowerCase() === "windows") {
4987
4981
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
4988
4982
  }
4989
- const pathMatches = (text, path6) => {
4990
- const parts = path6.split(/(\(\?!.*?\))/);
4983
+ const pathMatches = (text, path7) => {
4984
+ const parts = path7.split(/(\(\?!.*?\))/);
4991
4985
  const escaped = parts.map((part) => {
4992
4986
  if (part.startsWith("(?!")) return part;
4993
4987
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4994
4988
  }).join("");
4995
- const re = path6.startsWith(".") || path6.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4989
+ const re = path7.startsWith(".") || path7.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4996
4990
  return re.test(text);
4997
4991
  };
4998
- const pathMatchesAny = (path6) => pathScanTexts.some((t) => pathMatches(t, path6));
4992
+ const pathMatchesAny = (path7) => pathScanTexts.some((t) => pathMatches(t, path7));
4999
4993
  for (const sp of rootPaths) {
5000
4994
  if (pathMatchesAny(sp.path.toLowerCase())) {
5001
4995
  if (keygenGenerate) continue;
@@ -5138,8 +5132,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5138
5132
  }
5139
5133
  return null;
5140
5134
  }
5141
- function isHomeValue(path6) {
5142
- let p = path6.trim().toLowerCase();
5135
+ function isHomeValue(path7) {
5136
+ let p = path7.trim().toLowerCase();
5143
5137
  if (p.startsWith("$(") && p.endsWith(")")) {
5144
5138
  const inner = p.slice(2, -1).trim();
5145
5139
  return HOME_TARGET_RE.test(" " + inner);
@@ -5195,15 +5189,15 @@ function checkHomeDeletion(actionType, actionDetail) {
5195
5189
  }
5196
5190
  const assigned = {};
5197
5191
  for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
5198
- for (const [varName, path6] of Object.entries(assigned)) {
5199
- if (!isHomeValue(path6)) continue;
5192
+ for (const [varName, path7] of Object.entries(assigned)) {
5193
+ if (!isHomeValue(path7)) continue;
5200
5194
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
5201
5195
  for (const seg of segs) {
5202
5196
  if (!isDeleteCommand(seg)) continue;
5203
5197
  if (varRefRe.test(seg)) {
5204
5198
  return {
5205
5199
  allowed: false,
5206
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path6}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5200
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path7}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5207
5201
  riskLevel: "high",
5208
5202
  riskType: "script_execution",
5209
5203
  confidence: 90,
@@ -6007,15 +6001,15 @@ function parseShellString(s) {
6007
6001
  let m;
6008
6002
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
6009
6003
  const interp = m[1];
6010
- const path6 = m[2].trim();
6004
+ const path7 = m[2].trim();
6011
6005
  let rest = m[3].trim();
6012
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
6006
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6013
6007
  rest = rest.split(/[;|&<>]/)[0].trim();
6014
6008
  const args = [];
6015
6009
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6016
6010
  args.push(tm[1] ? tm[2] : tm[3]);
6017
6011
  }
6018
- return { path: path6, args, interpreter: interp };
6012
+ return { path: path7, args, interpreter: interp };
6019
6013
  }
6020
6014
  return null;
6021
6015
  }
@@ -6061,9 +6055,9 @@ function extractCallsFromTree(tree, reachableLines) {
6061
6055
  }
6062
6056
  if (allStr && elts.length >= 2) {
6063
6057
  const interp = elts[0];
6064
- const path6 = elts[1];
6065
- if (!path6.startsWith("-") && !path6.startsWith("$") && !path6.includes("/dev/")) {
6066
- add({ path: path6, args: elts.slice(2), interpreter: interp });
6058
+ const path7 = elts[1];
6059
+ if (!path7.startsWith("-") && !path7.startsWith("$") && !path7.includes("/dev/")) {
6060
+ add({ path: path7, args: elts.slice(2), interpreter: interp });
6067
6061
  return true;
6068
6062
  }
6069
6063
  }
@@ -6103,15 +6097,15 @@ function extractCallsRegex(content) {
6103
6097
  let m;
6104
6098
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
6105
6099
  const interp = m[1];
6106
- const path6 = m[2].trim();
6100
+ const path7 = m[2].trim();
6107
6101
  let rest = m[3].trim();
6108
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
6102
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6109
6103
  rest = rest.split(/[;|&<>]/)[0].trim();
6110
6104
  const args = [];
6111
6105
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6112
6106
  args.push(tm[1] ? tm[2] : tm[3]);
6113
6107
  }
6114
- calls.push({ path: path6, args, interpreter: interp });
6108
+ calls.push({ path: path7, args, interpreter: interp });
6115
6109
  }
6116
6110
  return calls;
6117
6111
  }
@@ -6894,15 +6888,15 @@ function extractCallsFromContent(content) {
6894
6888
  CHILD_CALL_RE2.lastIndex = 0;
6895
6889
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
6896
6890
  const interp = m[1];
6897
- const path6 = m[2].trim();
6891
+ const path7 = m[2].trim();
6898
6892
  let rest = m[3].trim();
6899
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
6893
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6900
6894
  rest = rest.split(/[;|&<>]/)[0].trim();
6901
6895
  const args = [];
6902
6896
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6903
6897
  args.push(tm[1] ? tm[2] : tm[3]);
6904
6898
  }
6905
- calls.push({ path: path6, args, interpreter: interp });
6899
+ calls.push({ path: path7, args, interpreter: interp });
6906
6900
  }
6907
6901
  return calls;
6908
6902
  }
@@ -7591,6 +7585,464 @@ var init_script_content_analyzer = __esm({
7591
7585
  }
7592
7586
  });
7593
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
+
7594
8046
  // src/engine/token-stats.ts
7595
8047
  var token_stats_exports = {};
7596
8048
  __export(token_stats_exports, {
@@ -7599,9 +8051,10 @@ __export(token_stats_exports, {
7599
8051
  getTokenStats: () => getTokenStats,
7600
8052
  getTokenTrend: () => getTokenTrend,
7601
8053
  recordTokenUsage: () => recordTokenUsage,
7602
- resetTokenStats: () => resetTokenStats
8054
+ resetTokenStats: () => resetTokenStats,
8055
+ resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
7603
8056
  });
7604
- 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";
7605
8058
  function getStatsPath() {
7606
8059
  const envPath = process.env[ENV_STATS_PATH];
7607
8060
  if (envPath) return envPath;
@@ -7609,11 +8062,24 @@ function getStatsPath() {
7609
8062
  }
7610
8063
  function loadAllRecords(statsPath) {
7611
8064
  if (!existsSync13(statsPath)) return [];
8065
+ let sig = "";
7612
8066
  try {
7613
- const data = JSON.parse(readFileSync13(statsPath, "utf-8"));
7614
- if (Array.isArray(data)) return data;
7615
- if (data && Array.isArray(data.records)) return data.records;
8067
+ const st = statSync5(statsPath);
8068
+ sig = `${st.mtimeMs}:${st.size}`;
8069
+ } catch {
7616
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();
7617
8083
  } catch (e) {
7618
8084
  return [];
7619
8085
  }
@@ -7623,9 +8089,22 @@ function saveRecords(statsPath, records) {
7623
8089
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
7624
8090
  if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
7625
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
+ }
7626
8102
  } catch (e) {
7627
8103
  }
7628
8104
  }
8105
+ function resetTokenStatsCacheForTests() {
8106
+ _recordsCache = null;
8107
+ }
7629
8108
  function recordTokenUsage(record) {
7630
8109
  const statsPath = getStatsPath();
7631
8110
  const records = loadAllRecords(statsPath);
@@ -7754,8 +8233,9 @@ function resetTokenStats() {
7754
8233
  } catch {
7755
8234
  }
7756
8235
  }
8236
+ _recordsCache = null;
7757
8237
  }
7758
- var ENV_STATS_PATH, MAX_RECORDS;
8238
+ var ENV_STATS_PATH, MAX_RECORDS, _recordsCache;
7759
8239
  var init_token_stats = __esm({
7760
8240
  "src/engine/token-stats.ts"() {
7761
8241
  "use strict";
@@ -7763,6 +8243,7 @@ var init_token_stats = __esm({
7763
8243
  init_paths();
7764
8244
  ENV_STATS_PATH = "AGENT_MOSS_TOKEN_STATS_PATH";
7765
8245
  MAX_RECORDS = 1e4;
8246
+ _recordsCache = null;
7766
8247
  }
7767
8248
  });
7768
8249
 
@@ -7770,6 +8251,22 @@ var init_token_stats = __esm({
7770
8251
  import { createHash as createHash3 } from "crypto";
7771
8252
  import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
7772
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
+ }
7773
8270
  async function runLLMAnalysis(input, previous) {
7774
8271
  if (!isLLMAvailable()) {
7775
8272
  console.log("[AgentMoss] LLM not configured, skipping deep analysis");
@@ -7852,7 +8349,23 @@ async function runLLMAnalysis(input, previous) {
7852
8349
  );
7853
8350
  }
7854
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
+ });
7855
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
+ });
7856
8369
  if (llmCache.size >= LLM_CACHE_MAX) {
7857
8370
  const firstKey = llmCache.keys().next().value;
7858
8371
  if (firstKey) llmCache.delete(firstKey);
@@ -7994,6 +8507,14 @@ function formatHints(previous) {
7994
8507
  }
7995
8508
  async function analyzeWithLLM(prompt, config) {
7996
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
+ };
7997
8518
  const provider = detectProvider(config.baseUrl, config.provider);
7998
8519
  const extraHeaders = getProviderHeaders(provider);
7999
8520
  if (Object.keys(extraHeaders).length > 0) {
@@ -8015,6 +8536,17 @@ async function analyzeWithLLM(prompt, config) {
8015
8536
  console.error(`[AgentMoss] totalTimeout (${timeoutCfg.totalTimeout}s) exceeded, aborting all LLM calls`);
8016
8537
  abortController.abort();
8017
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
+ }
8018
8550
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
8019
8551
  if (abortController.signal.aborted) {
8020
8552
  break;
@@ -8028,22 +8560,49 @@ async function analyzeWithLLM(prompt, config) {
8028
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" },
8029
8561
  { role: "user", content: prompt }
8030
8562
  ],
8031
- signal: abortController.signal
8563
+ signal: abortController.signal,
8564
+ // 私有化网关的额外参数(关思考等)原样透传;空则不传。
8565
+ ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
8032
8566
  });
8033
8567
  const message = response.choices[0]?.message;
8034
8568
  const content = message?.content ?? "";
8035
8569
  const finishReason = response.choices[0]?.finish_reason;
8036
- const reasoningLen = typeof message?.reasoning_content === "string" ? message.reasoning_content.length : 0;
8570
+ const fieldLengths = responseFieldLengths(message);
8037
8571
  const usage = response.usage;
8038
8572
  if (!content) {
8039
- const detail = `model=${response.model || config.model} finish_reason=${finishReason} content_len=0 reasoning_len=${reasoningLen} message_keys=${message ? Object.keys(message).join(",") : "(none)"} tokens=${usage?.prompt_tokens ?? "?"}/${usage?.completion_tokens ?? "?"}`;
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
+ }
8040
8590
  if (finishReason === "length") {
8041
- 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}`);
8042
8592
  throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
8043
8593
  }
8044
- 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");
8045
8596
  throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
8046
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
+ });
8047
8606
  console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
8048
8607
  let jsonStr = content.trim();
8049
8608
  if (jsonStr.startsWith("```")) {
@@ -8074,6 +8633,8 @@ async function analyzeWithLLM(prompt, config) {
8074
8633
  clearTimeout(totalTimeoutTimer);
8075
8634
  const riskLevel = parsed.riskLevel ?? parsed.risk_level;
8076
8635
  const riskType = parsed.riskType ?? parsed.risk_type;
8636
+ breaker.recordSuccess();
8637
+ _recordLlm("success");
8077
8638
  return {
8078
8639
  allowed: parsed.allowed !== false,
8079
8640
  reason: parsed.reason || "LLM \u5206\u6790\u5B8C\u6210",
@@ -8084,6 +8645,7 @@ async function analyzeWithLLM(prompt, config) {
8084
8645
  violatedLayers: ["L3.1"]
8085
8646
  };
8086
8647
  } catch (err) {
8648
+ breaker.recordFailure();
8087
8649
  if (abortController.signal.aborted) {
8088
8650
  console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
8089
8651
  break;
@@ -8116,6 +8678,9 @@ var init_llm_analyzer = __esm({
8116
8678
  init_template_loader();
8117
8679
  init_script_analyzer();
8118
8680
  init_script_content_analyzer();
8681
+ init_trace_log();
8682
+ init_metrics();
8683
+ init_circuit_breaker();
8119
8684
  llmCache = /* @__PURE__ */ new Map();
8120
8685
  LLM_CACHE_MAX = 200;
8121
8686
  }
@@ -8154,8 +8719,8 @@ var init_rule_store = __esm({
8154
8719
  BrainRuleStore = class {
8155
8720
  path;
8156
8721
  data;
8157
- constructor(path6) {
8158
- this.path = path6 || getRulesPath();
8722
+ constructor(path7) {
8723
+ this.path = path7 || getRulesPath();
8159
8724
  this.data = this.load();
8160
8725
  }
8161
8726
  load() {
@@ -8608,10 +9173,10 @@ ${reason.slice(0, 500)}
8608
9173
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
8609
9174
  let mm;
8610
9175
  while ((mm = pathRe.exec(src)) !== null) {
8611
- const path6 = mm[1];
8612
- if (path6.split("/").length < 3) continue;
8613
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path6)) continue;
8614
- const gen = this.generalizePath(path6);
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);
8615
9180
  if (seen.has(gen)) continue;
8616
9181
  seen.add(gen);
8617
9182
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -8630,8 +9195,8 @@ ${reason.slice(0, 500)}
8630
9195
  }
8631
9196
  return false;
8632
9197
  }
8633
- generalizePath(path6) {
8634
- const p = path6.toLowerCase();
9198
+ generalizePath(path7) {
9199
+ const p = path7.toLowerCase();
8635
9200
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
8636
9201
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
8637
9202
  }
@@ -9019,26 +9584,26 @@ function writeExportFiles(outDir, rules, skills) {
9019
9584
  byLayer.get(r.layer).push(r);
9020
9585
  }
9021
9586
  for (const layer of [...byLayer.keys()].sort((a, b) => a - b)) {
9022
- const path6 = join14(rulesDir2, `l${layer}_brain_rules.json`);
9023
- writeFileSync5(path6, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
9024
- written.push(path6);
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);
9025
9590
  }
9026
9591
  if (rules.length === 0) {
9027
- const path6 = join14(rulesDir2, "empty.txt");
9028
- writeFileSync5(path6, "(no brain rules to contribute)", "utf-8");
9029
- written.push(path6);
9592
+ const path7 = join14(rulesDir2, "empty.txt");
9593
+ writeFileSync5(path7, "(no brain rules to contribute)", "utf-8");
9594
+ written.push(path7);
9030
9595
  }
9031
9596
  const skillsDir = join14(outDir, "skills");
9032
9597
  mkdirSync6(skillsDir, { recursive: true });
9033
9598
  for (const sk of skills) {
9034
- const path6 = join14(skillsDir, `${sk.name}.md`);
9035
- writeFileSync5(path6, sk.content || "", "utf-8");
9036
- written.push(path6);
9599
+ const path7 = join14(skillsDir, `${sk.name}.md`);
9600
+ writeFileSync5(path7, sk.content || "", "utf-8");
9601
+ written.push(path7);
9037
9602
  }
9038
9603
  if (skills.length === 0) {
9039
- const path6 = join14(skillsDir, "empty.txt");
9040
- writeFileSync5(path6, "(no brain skills to contribute)", "utf-8");
9041
- written.push(path6);
9604
+ const path7 = join14(skillsDir, "empty.txt");
9605
+ writeFileSync5(path7, "(no brain skills to contribute)", "utf-8");
9606
+ written.push(path7);
9042
9607
  }
9043
9608
  return written;
9044
9609
  }
@@ -9487,38 +10052,38 @@ function labelEvent(actionDetail) {
9487
10052
  }
9488
10053
  return hits;
9489
10054
  }
9490
- function evaluateLTL(formula, trace, pos) {
10055
+ function evaluateLTL(formula, trace2, pos) {
9491
10056
  const op = formula[0];
9492
10057
  switch (op) {
9493
10058
  case "ap":
9494
- return trace[pos].has(formula[1]);
10059
+ return trace2[pos].has(formula[1]);
9495
10060
  case "!":
9496
- return !evaluateLTL(formula[1], trace, pos);
10061
+ return !evaluateLTL(formula[1], trace2, pos);
9497
10062
  case "&":
9498
- return evaluateLTL(formula[1], trace, pos) && evaluateLTL(formula[2], trace, pos);
10063
+ return evaluateLTL(formula[1], trace2, pos) && evaluateLTL(formula[2], trace2, pos);
9499
10064
  case "|":
9500
- return evaluateLTL(formula[1], trace, pos) || evaluateLTL(formula[2], trace, pos);
10065
+ return evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
9501
10066
  case "->":
9502
- return !evaluateLTL(formula[1], trace, pos) || evaluateLTL(formula[2], trace, pos);
10067
+ return !evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
9503
10068
  case "X":
9504
- return pos + 1 < trace.length && evaluateLTL(formula[1], trace, pos + 1);
10069
+ return pos + 1 < trace2.length && evaluateLTL(formula[1], trace2, pos + 1);
9505
10070
  case "G": {
9506
- for (let j = pos; j < trace.length; j++) {
9507
- if (!evaluateLTL(formula[1], trace, j)) return false;
10071
+ for (let j = pos; j < trace2.length; j++) {
10072
+ if (!evaluateLTL(formula[1], trace2, j)) return false;
9508
10073
  }
9509
10074
  return true;
9510
10075
  }
9511
10076
  case "F": {
9512
- for (let j = pos; j < trace.length; j++) {
9513
- if (evaluateLTL(formula[1], trace, j)) return true;
10077
+ for (let j = pos; j < trace2.length; j++) {
10078
+ if (evaluateLTL(formula[1], trace2, j)) return true;
9514
10079
  }
9515
10080
  return false;
9516
10081
  }
9517
10082
  case "U": {
9518
- for (let j = pos; j < trace.length; j++) {
9519
- if (evaluateLTL(formula[2], trace, j)) {
10083
+ for (let j = pos; j < trace2.length; j++) {
10084
+ if (evaluateLTL(formula[2], trace2, j)) {
9520
10085
  for (let k = pos; k < j; k++) {
9521
- if (!evaluateLTL(formula[1], trace, k)) return false;
10086
+ if (!evaluateLTL(formula[1], trace2, k)) return false;
9522
10087
  }
9523
10088
  return true;
9524
10089
  }
@@ -9547,11 +10112,11 @@ function checkMCRules(graph) {
9547
10112
  const mc = loadMC();
9548
10113
  const rules = mc.rules || [];
9549
10114
  if (rules.length === 0) return violations;
9550
- const trace = nodes.map((n) => labelEvent(n.actionDetail));
10115
+ const trace2 = nodes.map((n) => labelEvent(n.actionDetail));
9551
10116
  const witnessMode = graph.witnessIdx !== void 0;
9552
10117
  for (const rule of rules) {
9553
10118
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
9554
- if (ruleViolates(rule, trace, witnessMode)) {
10119
+ if (ruleViolates(rule, trace2, witnessMode)) {
9555
10120
  violations.push({
9556
10121
  propertyId: String(rule.id || "mc-ltl"),
9557
10122
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
@@ -9742,12 +10307,12 @@ var init_builder = __esm({
9742
10307
  });
9743
10308
 
9744
10309
  // src/engine/formal-engine/properties.ts
9745
- function graphFromPath(nodes, path6, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10310
+ function graphFromPath(nodes, path7, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
9746
10311
  const byKey = /* @__PURE__ */ new Map();
9747
10312
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
9748
10313
  const gNodes = [];
9749
10314
  const gEdges = [];
9750
- for (const item of path6) {
10315
+ for (const item of path7) {
9751
10316
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
9752
10317
  gNodes.push({
9753
10318
  session_id: item.sessionId,
@@ -9813,22 +10378,22 @@ function checkCrossSessionChain(graph) {
9813
10378
  if (witness !== void 0) {
9814
10379
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
9815
10380
  let matched = 0;
9816
- const path6 = [];
10381
+ const path7 = [];
9817
10382
  for (let k = 0; k < witness; k++) {
9818
10383
  const n = nodes[k];
9819
10384
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
9820
10385
  matched += 1;
9821
- path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10386
+ path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9822
10387
  }
9823
10388
  }
9824
10389
  if (matched < stages.length - 1) continue;
9825
- path6.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
10390
+ path7.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
9826
10391
  violations.push({
9827
10392
  propertyId: "cross-" + chain.id,
9828
10393
  reason: chain.reason,
9829
10394
  riskLevel: chain.riskLevel,
9830
- path: path6,
9831
- graph: graphFromPath(nodes, path6, "next", {
10395
+ path: path7,
10396
+ graph: graphFromPath(nodes, path7, "next", {
9832
10397
  property_id: "cross-" + chain.id,
9833
10398
  property_short: "P1",
9834
10399
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -9838,11 +10403,11 @@ function checkCrossSessionChain(graph) {
9838
10403
  } else {
9839
10404
  let matched = 0;
9840
10405
  let stageIdx = 0;
9841
- const path6 = [];
10406
+ const path7 = [];
9842
10407
  for (const n of nodes) {
9843
10408
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
9844
10409
  matched += 1;
9845
- path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10410
+ path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9846
10411
  stageIdx += 1;
9847
10412
  if (matched >= stages.length) break;
9848
10413
  }
@@ -9852,8 +10417,8 @@ function checkCrossSessionChain(graph) {
9852
10417
  propertyId: "cross-" + chain.id,
9853
10418
  reason: chain.reason,
9854
10419
  riskLevel: chain.riskLevel,
9855
- path: path6,
9856
- graph: graphFromPath(nodes, path6, "next", {
10420
+ path: path7,
10421
+ graph: graphFromPath(nodes, path7, "next", {
9857
10422
  property_id: "cross-" + chain.id,
9858
10423
  property_short: "P1",
9859
10424
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -9900,7 +10465,7 @@ function checkSensitiveDataFlow(graph) {
9900
10465
  }
9901
10466
  }
9902
10467
  }
9903
- const tracePath = (idx) => {
10468
+ const tracePath2 = (idx) => {
9904
10469
  const chain = [idx];
9905
10470
  const seen = /* @__PURE__ */ new Set([idx]);
9906
10471
  while (true) {
@@ -9959,7 +10524,7 @@ function checkSensitiveDataFlow(graph) {
9959
10524
  for (const i of candidates) {
9960
10525
  const n = nodes[i];
9961
10526
  if (tainted.has(i) && EXFIL_RE.test(n.actionDetail)) {
9962
- const chain = tracePath(i);
10527
+ const chain = tracePath2(i);
9963
10528
  violations.push({
9964
10529
  propertyId: "sensitive-data-flow",
9965
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`,
@@ -10074,7 +10639,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10074
10639
  if (candidates.length > 0) {
10075
10640
  const pre = nodes[candidates[candidates.length - 1]];
10076
10641
  const post = nodes[firstEv];
10077
- const path6 = [
10642
+ const path7 = [
10078
10643
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10079
10644
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10080
10645
  ];
@@ -10082,8 +10647,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10082
10647
  propertyId: "no-exfil-after-privesc",
10083
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",
10084
10649
  riskLevel: "critical",
10085
- path: path6,
10086
- graph: graphFromPath(nodes, path6, "next", {
10650
+ path: path7,
10651
+ graph: graphFromPath(nodes, path7, "next", {
10087
10652
  property_id: "no-exfil-after-privesc",
10088
10653
  property_short: "P4",
10089
10654
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10100,7 +10665,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10100
10665
  for (let j = i + 1; j < nodes.length; j++) {
10101
10666
  if (!isExfilNode(nodes[j])) continue;
10102
10667
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
10103
- const path6 = [
10668
+ const path7 = [
10104
10669
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10105
10670
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10106
10671
  ];
@@ -10108,8 +10673,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10108
10673
  propertyId: "no-exfil-after-privesc",
10109
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",
10110
10675
  riskLevel: "critical",
10111
- path: path6,
10112
- graph: graphFromPath(nodes, path6, "next", {
10676
+ path: path7,
10677
+ graph: graphFromPath(nodes, path7, "next", {
10113
10678
  property_id: "no-exfil-after-privesc",
10114
10679
  property_short: "P4",
10115
10680
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10141,7 +10706,7 @@ function checkNeverExfilAfterCred(graph) {
10141
10706
  }
10142
10707
  if (pre) {
10143
10708
  const post = nodes[firstEv];
10144
- const path6 = [
10709
+ const path7 = [
10145
10710
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10146
10711
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10147
10712
  ];
@@ -10149,8 +10714,8 @@ function checkNeverExfilAfterCred(graph) {
10149
10714
  propertyId: "no-exfil-after-credential",
10150
10715
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10151
10716
  riskLevel: "critical",
10152
- path: path6,
10153
- graph: graphFromPath(nodes, path6, "data", {
10717
+ path: path7,
10718
+ graph: graphFromPath(nodes, path7, "data", {
10154
10719
  property_id: "no-exfil-after-credential",
10155
10720
  property_short: "P5",
10156
10721
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10166,7 +10731,7 @@ function checkNeverExfilAfterCred(graph) {
10166
10731
  if (!isCredNode(nodes[i])) continue;
10167
10732
  for (let j = i + 1; j < nodes.length; j++) {
10168
10733
  if (isExfilNode(nodes[j])) {
10169
- const path6 = [
10734
+ const path7 = [
10170
10735
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10171
10736
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10172
10737
  ];
@@ -10174,8 +10739,8 @@ function checkNeverExfilAfterCred(graph) {
10174
10739
  propertyId: "no-exfil-after-credential",
10175
10740
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10176
10741
  riskLevel: "critical",
10177
- path: path6,
10178
- graph: graphFromPath(nodes, path6, "data", {
10742
+ path: path7,
10743
+ graph: graphFromPath(nodes, path7, "data", {
10179
10744
  property_id: "no-exfil-after-credential",
10180
10745
  property_short: "P5",
10181
10746
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10334,13 +10899,13 @@ function checkSensitiveDataAggregation(graph) {
10334
10899
  if (!isExfilNode(n)) continue;
10335
10900
  const srcs = sourcesFor(i);
10336
10901
  if (srcs.size >= 2) {
10337
- const path6 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10902
+ const path7 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10338
10903
  violations.push({
10339
10904
  propertyId: "sensitive-data-aggregation",
10340
10905
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
10341
10906
  riskLevel: "critical",
10342
- path: path6,
10343
- graph: graphFromPath(nodes, path6, "next", {
10907
+ path: path7,
10908
+ graph: graphFromPath(nodes, path7, "next", {
10344
10909
  property_id: "sensitive-data-aggregation",
10345
10910
  property_short: "P8",
10346
10911
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -10799,11 +11364,11 @@ var init_stateful = __esm({
10799
11364
  }
10800
11365
  }
10801
11366
  chainPath(stages) {
10802
- const path6 = [];
11367
+ const path7 = [];
10803
11368
  let want = stages[0];
10804
11369
  for (const n of this.nodes_) {
10805
11370
  if (n.stage === want) {
10806
- path6.push({
11371
+ path7.push({
10807
11372
  sessionId: n.sessionId,
10808
11373
  seq: n.seq,
10809
11374
  stage: n.stage,
@@ -10819,12 +11384,12 @@ var init_stateful = __esm({
10819
11384
  }
10820
11385
  }
10821
11386
  }
10822
- return path6;
11387
+ return path7;
10823
11388
  }
10824
11389
  /** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
10825
11390
  buildChainGraph(stages, chainId) {
10826
- const path6 = this.chainPath(stages);
10827
- const gNodes = path6.map((p, i) => {
11391
+ const path7 = this.chainPath(stages);
11392
+ const gNodes = path7.map((p, i) => {
10828
11393
  const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
10829
11394
  return {
10830
11395
  session_id: p.sessionId,
@@ -11075,16 +11640,42 @@ var init_stateful = __esm({
11075
11640
  });
11076
11641
 
11077
11642
  // src/engine/formal-engine/chain_state.ts
11078
- import * as fs4 from "fs";
11643
+ import * as fs5 from "fs";
11079
11644
  import * as os2 from "os";
11080
- import * as path4 from "path";
11645
+ import * as path5 from "path";
11081
11646
  import { createHash as createHash4 } from "crypto";
11082
11647
  function defaultStateDbPath() {
11083
- const dir = process.env.AGENT_MOSS_STATE_DIR || path4.join(os2.homedir(), ".agentmoss");
11648
+ const dir = process.env.AGENT_MOSS_STATE_DIR || path5.join(os2.homedir(), ".agentmoss");
11084
11649
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
11085
- return path4.join(dir, `stateful_chains_${tag}.json`);
11650
+ return path5.join(dir, `stateful_chains_${tag}.json`);
11086
11651
  }
11087
- var ChainStateStore;
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
+ });
11670
+ }
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;
11088
11679
  var init_chain_state = __esm({
11089
11680
  "src/engine/formal-engine/chain_state.ts"() {
11090
11681
  "use strict";
@@ -11095,15 +11686,33 @@ var init_chain_state = __esm({
11095
11686
  filePath;
11096
11687
  data;
11097
11688
  _timer = null;
11098
- _flushDelayMs = 50;
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();
11099
11708
  constructor(filePath = "") {
11100
11709
  this.filePath = filePath || defaultStateDbPath();
11101
11710
  this.data = this._read();
11102
11711
  }
11103
11712
  _read() {
11104
11713
  try {
11105
- if (fs4.existsSync(this.filePath)) {
11106
- const raw = fs4.readFileSync(this.filePath, "utf-8");
11714
+ if (fs5.existsSync(this.filePath)) {
11715
+ const raw = fs5.readFileSync(this.filePath, "utf-8");
11107
11716
  return JSON.parse(raw);
11108
11717
  }
11109
11718
  } catch {
@@ -11116,12 +11725,22 @@ var init_chain_state = __esm({
11116
11725
  this._timer = setTimeout(() => {
11117
11726
  this._timer = null;
11118
11727
  try {
11119
- ensurePrivateDir(path4.dirname(this.filePath));
11728
+ this._syncDirtyToData();
11729
+ ensurePrivateDir(path5.dirname(this.filePath));
11120
11730
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11121
11731
  } catch {
11122
11732
  }
11123
11733
  }, this._flushDelayMs);
11124
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
+ }
11125
11744
  /** 立即落盘(测试/关停前调用,保证状态不丢)。 */
11126
11745
  flush() {
11127
11746
  if (this._timer !== null) {
@@ -11129,29 +11748,39 @@ var init_chain_state = __esm({
11129
11748
  this._timer = null;
11130
11749
  }
11131
11750
  try {
11132
- ensurePrivateDir(path4.dirname(this.filePath));
11751
+ this._syncDirtyToData();
11752
+ ensurePrivateDir(path5.dirname(this.filePath));
11133
11753
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11134
11754
  } catch {
11135
11755
  }
11136
11756
  }
11137
11757
  load(agentId) {
11758
+ const cached2 = this._trackers.get(agentId);
11759
+ if (cached2) return cached2;
11138
11760
  const entry = this.data[agentId];
11139
11761
  if (!entry) return null;
11140
11762
  const t = new StatefulChainTracker(agentId);
11141
11763
  t.restore(entry.state);
11764
+ this._trackers.set(agentId, t);
11142
11765
  return t;
11143
11766
  }
11144
11767
  save(tracker) {
11145
- this.data[tracker.agentId] = {
11146
- state: tracker.toSnapshot(),
11147
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
11148
- };
11768
+ this._trackers.set(tracker.agentId, tracker);
11769
+ this._dirty.add(tracker.agentId);
11149
11770
  this._scheduleWrite();
11150
11771
  }
11151
11772
  delete(agentId) {
11773
+ this._trackers.delete(agentId);
11774
+ this._dirty.delete(agentId);
11152
11775
  delete this.data[agentId];
11153
11776
  this._scheduleWrite();
11154
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
+ }
11155
11784
  applyAction(agentId, aNext, sessionId, isError = false, sourceAgent = "", instanceId = "") {
11156
11785
  const t = this.load(agentId) || new StatefulChainTracker(agentId);
11157
11786
  const r = t.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
@@ -11166,6 +11795,8 @@ var init_chain_state = __esm({
11166
11795
  return r;
11167
11796
  }
11168
11797
  };
11798
+ _store = null;
11799
+ _exitHookRegistered = false;
11169
11800
  }
11170
11801
  });
11171
11802
 
@@ -11273,6 +11904,14 @@ function _resetBrainForTest() {
11273
11904
  async function runAnalysis(input) {
11274
11905
  const observedFormalLayers = [];
11275
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
+ }
11276
11915
  const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
11277
11916
  const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
11278
11917
  if (heuristicResult && !heuristicResult.allowed) {
@@ -11416,6 +12055,14 @@ async function runAnalysis(input) {
11416
12055
  }
11417
12056
  }
11418
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
+ }
11419
12066
  const l1FileAccessHit = !!(heuristicResult && !heuristicResult.allowed && heuristicResult.riskType === "file_access");
11420
12067
  const effectiveResult = logicResult && !logicResult.allowed ? logicResult : l1FileAccessHit ? heuristicResult : null;
11421
12068
  if (effectiveResult) {
@@ -11645,6 +12292,7 @@ var init_coordinator = __esm({
11645
12292
  init_llm_analyzer();
11646
12293
  init_script_content_analyzer();
11647
12294
  init_config();
12295
+ init_trace_log();
11648
12296
  init_runtime_config();
11649
12297
  init_agents();
11650
12298
  init_scenarios();
@@ -12169,7 +12817,7 @@ var init_esm_require = __esm({
12169
12817
  });
12170
12818
 
12171
12819
  // src/actrail.ts
12172
- import * as fs5 from "fs";
12820
+ import * as fs6 from "fs";
12173
12821
  function escape(value) {
12174
12822
  return value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/=/g, "\\e");
12175
12823
  }
@@ -12190,7 +12838,7 @@ function getStoragePath() {
12190
12838
  function reportEnforcementEvent(opts) {
12191
12839
  if (!isEnabled()) return false;
12192
12840
  const storagePath = getStoragePath();
12193
- if (!fs5.existsSync(storagePath)) return false;
12841
+ if (!fs6.existsSync(storagePath)) return false;
12194
12842
  try {
12195
12843
  let Database;
12196
12844
  try {
@@ -12361,9 +13009,9 @@ var init_pattern_miner = __esm({
12361
13009
  });
12362
13010
 
12363
13011
  // src/agent-gate-reader.ts
12364
- import * as fs6 from "fs";
13012
+ import * as fs7 from "fs";
12365
13013
  import * as os3 from "os";
12366
- import * as path5 from "path";
13014
+ import * as path6 from "path";
12367
13015
  function normalizeAction(row) {
12368
13016
  return {
12369
13017
  actionType: String(row.action_type || row.tool_name || row.name || ""),
@@ -12373,10 +13021,10 @@ function normalizeAction(row) {
12373
13021
  function readJsonDir(dirPath, limit = 1e5) {
12374
13022
  const sessions = /* @__PURE__ */ new Map();
12375
13023
  try {
12376
- const files = fs6.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
13024
+ const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
12377
13025
  for (const f of files.slice(-200)) {
12378
13026
  const sid = f.replace(/\.json$/, "");
12379
- const raw = fs6.readFileSync(path5.join(dirPath, f), "utf-8");
13027
+ const raw = fs7.readFileSync(path6.join(dirPath, f), "utf-8");
12380
13028
  const arr = JSON.parse(raw);
12381
13029
  if (!Array.isArray(arr)) continue;
12382
13030
  for (const item of arr) {
@@ -12433,7 +13081,7 @@ function readSqlite(dbPath, limit = 1e5) {
12433
13081
  function loadAgentGateSessions(dbPath = "") {
12434
13082
  if (dbPath) {
12435
13083
  try {
12436
- if (fs6.statSync(dbPath).isDirectory()) {
13084
+ if (fs7.statSync(dbPath).isDirectory()) {
12437
13085
  return readJsonDir(dbPath);
12438
13086
  }
12439
13087
  } catch {
@@ -12444,7 +13092,7 @@ function loadAgentGateSessions(dbPath = "") {
12444
13092
  }
12445
13093
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
12446
13094
  if (sql.length > 0) return sql;
12447
- const jsonDefault = path5.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
13095
+ const jsonDefault = path6.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
12448
13096
  return readJsonDir(jsonDefault);
12449
13097
  }
12450
13098
  var DEFAULT_AGENTGATE_SQLITE;
@@ -12453,7 +13101,7 @@ var init_agent_gate_reader = __esm({
12453
13101
  "use strict";
12454
13102
  init_esm_shims();
12455
13103
  init_esm_require();
12456
- DEFAULT_AGENTGATE_SQLITE = path5.join(
13104
+ DEFAULT_AGENTGATE_SQLITE = path6.join(
12457
13105
  os3.homedir(),
12458
13106
  ".local",
12459
13107
  "share",
@@ -12535,17 +13183,114 @@ var init_observable = __esm({
12535
13183
  }
12536
13184
  });
12537
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
+
12538
13243
  // src/routes.ts
12539
13244
  import { randomBytes as randomBytes2 } from "crypto";
12540
13245
  import { join as join19, dirname as dirname12 } from "path";
12541
13246
  import { fileURLToPath as fileURLToPath10 } from "url";
12542
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
+ }
12543
13284
  return c.json(HealthResponseSchema.parse({
12544
- instance: process.env.AGENT_MOSS_INSTANCE || ""
13285
+ status: degraded.length ? "degraded" : "healthy",
13286
+ degraded,
13287
+ instance: process.env.AGENT_MOSS_INSTANCE || "",
13288
+ metrics
12545
13289
  }));
12546
13290
  }
12547
13291
  async function analyzeRoute(c) {
12548
13292
  const t0 = performance.now();
13293
+ const degradedNotes = [];
12549
13294
  try {
12550
13295
  const body = await c.req.json();
12551
13296
  const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
@@ -12573,6 +13318,20 @@ async function analyzeRoute(c) {
12573
13318
  const instanceId = String(
12574
13319
  req.instance_id || req.metadata?.instance_id || ""
12575
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
+ });
12576
13335
  const result = await analyze({
12577
13336
  sessionId: req.session_id,
12578
13337
  promptSession: req.prompt_session,
@@ -12632,6 +13391,29 @@ async function analyzeRoute(c) {
12632
13391
  llmLogPath: req.metadata?.llm_log_path
12633
13392
  });
12634
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
+ });
12635
13417
  try {
12636
13418
  reportEnforcementEvent({
12637
13419
  traceId: req.session_id,
@@ -12663,6 +13445,20 @@ async function analyzeRoute(c) {
12663
13445
  // 来源:真实 agent(桶 key 可能是 __system__)
12664
13446
  instanceId
12665
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
+ }
12666
13462
  const judgment = incMatchedToDeny(inc);
12667
13463
  if (judgment) {
12668
13464
  const layers = [...result.violated_layers];
@@ -12705,7 +13501,9 @@ async function analyzeRoute(c) {
12705
13501
  confidence: result.confidence,
12706
13502
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
12707
13503
  violation_chain: result.violation_chain ?? [],
12708
- 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
12709
13507
  })
12710
13508
  );
12711
13509
  } catch (err) {
@@ -12725,8 +13523,7 @@ async function analyzeRoute(c) {
12725
13523
  }
12726
13524
  }
12727
13525
  function getChainStateStoreFor(_agentId) {
12728
- if (!reviewStore) reviewStore = new ChainStateStore();
12729
- return reviewStore;
13526
+ return getChainStateStore();
12730
13527
  }
12731
13528
  function incMatchedToDeny(inc) {
12732
13529
  if (inc.matched) {
@@ -12935,7 +13732,7 @@ async function brainImportRoute(c) {
12935
13732
  })));
12936
13733
  return c.json({ imported: rules.length });
12937
13734
  }
12938
- var __dirname9, reviewStore;
13735
+ var __dirname9;
12939
13736
  var init_routes = __esm({
12940
13737
  "src/routes.ts"() {
12941
13738
  "use strict";
@@ -12945,14 +13742,18 @@ var init_routes = __esm({
12945
13742
  init_analyzer();
12946
13743
  init_actrail();
12947
13744
  init_formal_engine();
13745
+ init_circuit_breaker();
12948
13746
  init_pattern_miner();
12949
13747
  init_agent_gate_reader();
12950
13748
  init_observable();
12951
13749
  init_rule_store();
12952
13750
  init_skill_manager();
12953
13751
  init_asset_dir();
13752
+ init_trace_log();
13753
+ init_loop_monitor();
13754
+ init_runtime_stats();
13755
+ init_metrics();
12954
13756
  __dirname9 = dirname12(fileURLToPath10(import.meta.url));
12955
- reviewStore = null;
12956
13757
  }
12957
13758
  });
12958
13759
 
@@ -13450,9 +14251,11 @@ function createApp() {
13450
14251
  )
13451
14252
  );
13452
14253
  const pools = new PooledLimiter();
14254
+ registerPools(pools);
14255
+ startLoopMonitor();
13453
14256
  const limiter = new RateLimiter(rateLimitQps());
13454
14257
  app.use("*", async (c, next) => {
13455
- const path6 = new URL(c.req.url).pathname;
14258
+ const path7 = new URL(c.req.url).pathname;
13456
14259
  const method = c.req.method.toUpperCase();
13457
14260
  if (method === "OPTIONS") return next();
13458
14261
  const maxBody = maxBodyBytes();
@@ -13466,16 +14269,16 @@ function createApp() {
13466
14269
  if (originCheckEnabled()) {
13467
14270
  const origin = c.req.header("origin") || "";
13468
14271
  if (origin && !originAllowed(origin, c.req.header("host") || "")) {
13469
- console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path6}`);
14272
+ console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path7}`);
13470
14273
  return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
13471
14274
  }
13472
14275
  }
13473
- const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path6);
13474
- const isPublicPage = !path6.startsWith("/console/api") && (path6 === "/console" || path6.startsWith("/console/"));
14276
+ const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path7);
14277
+ const isPublicPage = !path7.startsWith("/console/api") && (path7 === "/console" || path7.startsWith("/console/"));
13475
14278
  if (!okAuth && !isPublicPage) {
13476
14279
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
13477
14280
  }
13478
- if (limiter.enabled && path6.startsWith("/api/")) {
14281
+ if (limiter.enabled && path7.startsWith("/api/")) {
13479
14282
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
13480
14283
  if (!limiter.allow(key)) {
13481
14284
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
@@ -13509,7 +14312,7 @@ function createApp() {
13509
14312
  return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
13510
14313
  }
13511
14314
  }
13512
- const pool = poolOf(path6);
14315
+ const pool = poolOf(path7);
13513
14316
  if (!take(`pool:${pool}`, poolLimit(pool))) {
13514
14317
  const qkey = principal ? "p:" + principalHash(principal) : "c:local";
13515
14318
  const [qn, abusive] = noteQueueReject(qkey);
@@ -13526,6 +14329,23 @@ function createApp() {
13526
14329
  while (keys.length) pools.release(keys.pop());
13527
14330
  }
13528
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
+ });
13529
14349
  app.get("/api/v1/health", healthRoute);
13530
14350
  app.post("/api/v1/analyze", analyzeRoute);
13531
14351
  app.post("/api/v1/review", reviewRoute);
@@ -13686,6 +14506,10 @@ var init_server = __esm({
13686
14506
  init_routes();
13687
14507
  init_console();
13688
14508
  init_runtime_config();
14509
+ init_runtime_stats();
14510
+ init_loop_monitor();
14511
+ init_metrics();
14512
+ init_formal_engine();
13689
14513
  init_rules_mode();
13690
14514
  init_rules_loader();
13691
14515
  PooledLimiter = class {
@@ -13702,6 +14526,10 @@ var init_server = __esm({
13702
14526
  if (cur <= 1) this.counts.delete(key);
13703
14527
  else this.counts.set(key, cur - 1);
13704
14528
  }
14529
+ /** 当前各池占用快照(健康检查用,对齐 Python `_PooledLimiter.snapshot`)。 */
14530
+ snapshot() {
14531
+ return Object.fromEntries(this.counts);
14532
+ }
13705
14533
  };
13706
14534
  RateLimiter = class {
13707
14535
  constructor(qps, burst) {
@@ -13979,7 +14807,7 @@ async function main() {
13979
14807
  case "init": {
13980
14808
  const flagIdx = args.findIndex((a) => a === "--output" || a === "-o");
13981
14809
  const output = (flagIdx >= 0 ? args[flagIdx + 1] : void 0) || args.slice(1).find((a) => !a.startsWith("-")) || "input.json";
13982
- const fs7 = await import("fs");
14810
+ const fs8 = await import("fs");
13983
14811
  const template = {
13984
14812
  session_id: "my-session-001",
13985
14813
  prompt_session: "Read /var/log/app.log and analyze errors",
@@ -13989,7 +14817,7 @@ async function main() {
13989
14817
  os_type: "",
13990
14818
  cwd: "/home/user/project"
13991
14819
  };
13992
- fs7.writeFileSync(output, JSON.stringify(template, null, 2), "utf-8");
14820
+ fs8.writeFileSync(output, JSON.stringify(template, null, 2), "utf-8");
13993
14821
  console.log(`Template written to ${output}`);
13994
14822
  break;
13995
14823
  }
@@ -13999,13 +14827,13 @@ async function main() {
13999
14827
  console.error('Usage: agent-moss analyze <input.json | "shell command">');
14000
14828
  process.exit(1);
14001
14829
  }
14002
- const fs7 = await import("fs");
14003
- const path6 = await import("path");
14830
+ const fs8 = await import("fs");
14831
+ const path7 = await import("path");
14004
14832
  const useJson = args.includes("--json");
14005
14833
  const osType = process.platform === "win32" ? "windows" : "linux";
14006
- const isFile = fs7.existsSync(target) && fs7.statSync(target).isFile();
14834
+ const isFile = fs8.existsSync(target) && fs8.statSync(target).isFile();
14007
14835
  if (!isFile) {
14008
- if (fs7.existsSync(target)) {
14836
+ if (fs8.existsSync(target)) {
14009
14837
  console.error(`\u9519\u8BEF: \u4E0D\u662F\u6587\u4EF6: ${target}`);
14010
14838
  process.exit(2);
14011
14839
  }
@@ -14019,8 +14847,8 @@ async function main() {
14019
14847
  }
14020
14848
  process.exit(await analyzeRawCommand(target, useJson));
14021
14849
  }
14022
- const filePath = path6.resolve(target);
14023
- const data = JSON.parse(fs7.readFileSync(filePath, "utf-8"));
14850
+ const filePath = path7.resolve(target);
14851
+ const data = JSON.parse(fs8.readFileSync(filePath, "utf-8"));
14024
14852
  const { analyze: analyze2 } = await Promise.resolve().then(() => (init_analyzer(), analyzer_exports));
14025
14853
  const sessionId = String(data.session_id || "unknown");
14026
14854
  const result = await analyze2(buildAnalysisInputFromFile(data));
@@ -14028,15 +14856,15 @@ async function main() {
14028
14856
  if (!args.includes("--no-file")) {
14029
14857
  const outDirIdx = args.findIndex((a) => a === "--output-dir" || a === "-o");
14030
14858
  const outDir = outDirIdx >= 0 && args[outDirIdx + 1] ? args[outDirIdx + 1] : process.cwd();
14031
- fs7.mkdirSync(outDir, { recursive: true });
14859
+ fs8.mkdirSync(outDir, { recursive: true });
14032
14860
  const safeSession = sessionId.replace(/\//g, "_");
14033
14861
  if (result.decision === "Allow") {
14034
- const policyPath = path6.join(outDir, `${safeSession}_policy.toml`);
14035
- fs7.writeFileSync(policyPath, result.policy || "", "utf-8");
14862
+ const policyPath = path7.join(outDir, `${safeSession}_policy.toml`);
14863
+ fs8.writeFileSync(policyPath, result.policy || "", "utf-8");
14036
14864
  console.log(`Policy written to ${policyPath}`);
14037
14865
  } else {
14038
- const denyPath = path6.join(outDir, `${safeSession}_deny_reason.txt`);
14039
- fs7.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
14866
+ const denyPath = path7.join(outDir, `${safeSession}_deny_reason.txt`);
14867
+ fs8.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
14040
14868
  console.log(`Deny reason written to ${denyPath}`);
14041
14869
  }
14042
14870
  }
@@ -14125,8 +14953,8 @@ async function main() {
14125
14953
  case "install": {
14126
14954
  const enable = args.includes("--enable");
14127
14955
  const { execSync } = await import("child_process");
14128
- const fs7 = await import("fs");
14129
- const path6 = await import("path");
14956
+ const fs8 = await import("fs");
14957
+ const path7 = await import("path");
14130
14958
  const { fileURLToPath: fileURLToPath14 } = await import("url");
14131
14959
  if (process.getuid?.() !== 0) {
14132
14960
  try {
@@ -14143,22 +14971,22 @@ async function main() {
14143
14971
  process.exit(0);
14144
14972
  }
14145
14973
  const __filename7 = fileURLToPath14(import.meta.url);
14146
- const __dirname12 = path6.dirname(__filename7);
14147
- let srcPath = path6.join(__dirname12, "data", "agent_moss.service");
14148
- if (!fs7.existsSync(srcPath)) {
14149
- srcPath = path6.join(__dirname12, "..", "src", "data", "agent_moss.service");
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");
14150
14978
  }
14151
- if (!fs7.existsSync(srcPath)) {
14979
+ if (!fs8.existsSync(srcPath)) {
14152
14980
  console.error("\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230 agent_moss.service \u6A21\u677F\u6587\u4EF6");
14153
14981
  process.exit(1);
14154
14982
  }
14155
14983
  const which = execSync("which agent-moss 2>/dev/null || true", { encoding: "utf-8" }).trim();
14156
- const binPath = which || `${process.execPath} ${path6.join(__dirname12, "cli.js")}`;
14157
- let content = fs7.readFileSync(srcPath, "utf-8");
14984
+ const binPath = which || `${process.execPath} ${path7.join(__dirname12, "cli.js")}`;
14985
+ let content = fs8.readFileSync(srcPath, "utf-8");
14158
14986
  content = content.replace("__AGENT_MOSS_BIN__", binPath);
14159
14987
  const dst = "/etc/systemd/system/agent-moss.service";
14160
- fs7.writeFileSync(dst, content, "utf-8");
14161
- fs7.chmodSync(dst, 420);
14988
+ fs8.writeFileSync(dst, content, "utf-8");
14989
+ fs8.chmodSync(dst, 420);
14162
14990
  console.log(`\u2705 \u5DF2\u5B89\u88C5 systemd service: ${dst}`);
14163
14991
  execSync("systemctl daemon-reload", { stdio: "inherit" });
14164
14992
  console.log("\u2705 systemctl daemon-reload \u5B8C\u6210");