@kenhkl/agent-moss 0.17.22 → 0.17.24

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
@@ -1,12 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  var __defProp = Object.defineProperty;
3
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
- }) : x)(function(x) {
7
- if (typeof require !== "undefined") return require.apply(this, arguments);
8
- throw Error('Dynamic require of "' + x + '" is not supported');
9
- });
10
4
  var __esm = (fn, res) => function __init() {
11
5
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
6
  };
@@ -408,22 +402,22 @@ function loadToolRegistry() {
408
402
  data.tools = tools;
409
403
  return data;
410
404
  }
411
- function scanStructEntry(cat, value, path6) {
405
+ function scanStructEntry(cat, value, path7) {
412
406
  if (cat === "skills") {
413
407
  if (!value || typeof value !== "object" || Array.isArray(value)) {
414
- 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`);
408
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
415
409
  return null;
416
410
  }
417
411
  const out = {};
418
412
  for (const [skCat, skills] of Object.entries(value)) {
419
413
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
420
- 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`);
414
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
421
415
  continue;
422
416
  }
423
417
  const keep = {};
424
418
  for (const [name, kws] of Object.entries(skills)) {
425
419
  if (Array.isArray(kws)) keep[name] = kws;
426
- 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`);
420
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
427
421
  }
428
422
  if (Object.keys(keep).length > 0) out[skCat] = keep;
429
423
  }
@@ -431,37 +425,37 @@ function scanStructEntry(cat, value, path6) {
431
425
  }
432
426
  if (cat === "ltl_rules") {
433
427
  if (!Array.isArray(value)) {
434
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
428
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
435
429
  return null;
436
430
  }
437
431
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
438
432
  if (keep.length !== value.length) {
439
- 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`);
433
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
440
434
  }
441
435
  return keep.length > 0 ? keep : null;
442
436
  }
443
437
  if (cat === "tools") {
444
438
  if (!value || typeof value !== "object" || Array.isArray(value)) {
445
- 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`);
439
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
446
440
  return null;
447
441
  }
448
442
  const keep = {};
449
443
  for (const [k, v] of Object.entries(value)) {
450
444
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
451
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
445
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
452
446
  }
453
447
  return Object.keys(keep).length > 0 ? keep : null;
454
448
  }
455
449
  return null;
456
450
  }
457
- function scanRulesFile(path6, kind) {
451
+ function scanRulesFile(path7, kind) {
458
452
  const out = {};
459
453
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
460
454
  let parsed;
461
455
  try {
462
- parsed = JSON.parse(readFileSync2(path6, "utf-8"));
456
+ parsed = JSON.parse(readFileSync2(path7, "utf-8"));
463
457
  } catch (e) {
464
- 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}`);
458
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
465
459
  return out;
466
460
  }
467
461
  const classifyFlat = (r) => {
@@ -485,44 +479,44 @@ function scanRulesFile(path6, kind) {
485
479
  }
486
480
  if (flatBad > 0) {
487
481
  console.warn(
488
- `[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`
482
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
489
483
  );
490
484
  }
491
485
  } else {
492
- 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`);
486
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
493
487
  return out;
494
488
  }
495
489
  for (const [cat, rules] of pairs) {
496
490
  if (String(cat).startsWith("_")) continue;
497
491
  if (STRUCT_KEYS.includes(cat)) {
498
- const got = scanStructEntry(cat, rules, path6);
492
+ const got = scanStructEntry(cat, rules, path7);
499
493
  if (got !== null) out[cat] = got;
500
494
  continue;
501
495
  }
502
496
  const required = EXTRA_CATEGORIES[cat];
503
497
  if (!required) {
504
498
  console.warn(
505
- `[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`
499
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
506
500
  );
507
501
  continue;
508
502
  }
509
503
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
510
504
  console.error(
511
- `[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
505
+ `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path7} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
512
506
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
513
507
  \u4F60\u5199\u7684\u50CF\u662F runtime config \u7684\u683C\u5F0F\uFF08{"category_enabled": ..., "rules": [...]}\uFF09\u2014\u2014\u90A3\u662F ~/.config/agentmoss/agent_moss_runtime.json \u7684\u683C\u5F0F\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5F53\u89C4\u5219\u6587\u4EF6\u7528\u3002`
514
508
  );
515
509
  continue;
516
510
  }
517
511
  if (!Array.isArray(rules)) {
518
- 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`);
512
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
519
513
  continue;
520
514
  }
521
515
  const items = [];
522
516
  for (const r of rules) {
523
517
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
524
518
  console.warn(
525
- `[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`
519
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
526
520
  );
527
521
  continue;
528
522
  }
@@ -532,7 +526,7 @@ function scanRulesFile(path6, kind) {
532
526
  }
533
527
  if (Object.keys(out).length > 0) {
534
528
  console.info(
535
- `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path6}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
529
+ `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path7}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
536
530
  );
537
531
  }
538
532
  return out;
@@ -879,7 +873,7 @@ var init_rules_contract = __esm({
879
873
 
880
874
  // src/infra/security-policy.ts
881
875
  import { createHash as createHash2, randomBytes, timingSafeEqual } from "crypto";
882
- import { chmodSync, closeSync, existsSync as existsSync3, lstatSync, mkdirSync, openSync, readFileSync as readFileSync4, readSync, realpathSync, writeSync } from "fs";
876
+ import { chmodSync, closeSync, constants as fsConstants, existsSync as existsSync3, lstatSync, mkdirSync, openSync, readFileSync as readFileSync4, readSync, realpathSync, writeSync } from "fs";
883
877
  import { homedir as homedir2, tmpdir } from "os";
884
878
  import { basename, isAbsolute, join as join4, relative, resolve as resolve2, dirname as dirname2 } from "path";
885
879
  function env(name, dflt = "") {
@@ -955,10 +949,10 @@ function readExplicitToken() {
955
949
  if (tok) return tok;
956
950
  const fdTok = readFdToken();
957
951
  if (fdTok) return fdTok;
958
- const path6 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
959
- if (path6) {
952
+ const path7 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
953
+ if (path7) {
960
954
  try {
961
- return readFileSync4(path6, "utf-8").trim();
955
+ return readFileSync4(path7, "utf-8").trim();
962
956
  } catch {
963
957
  return "";
964
958
  }
@@ -966,23 +960,23 @@ function readExplicitToken() {
966
960
  return "";
967
961
  }
968
962
  function ensureAutoToken() {
969
- const path6 = autoTokenPath();
963
+ const path7 = autoTokenPath();
970
964
  try {
971
- if (existsSync3(path6) && !lstatSync(path6).isSymbolicLink()) {
972
- const tok2 = readFileSync4(path6, "utf-8").trim();
965
+ if (existsSync3(path7) && !lstatSync(path7).isSymbolicLink()) {
966
+ const tok2 = readFileSync4(path7, "utf-8").trim();
973
967
  if (tok2) {
974
968
  try {
975
- chmodSync(path6, 384);
969
+ chmodSync(path7, 384);
976
970
  } catch {
977
971
  }
978
972
  return tok2;
979
973
  }
980
974
  }
981
975
  const tok = randomBytes(32).toString("base64url");
982
- ensurePrivateDir(dirname2(path6));
983
- if (!writePrivateText(path6, tok + "\n")) return "";
976
+ ensurePrivateDir(dirname2(path7));
977
+ if (!writePrivateText(path7, tok + "\n")) return "";
984
978
  console.warn(
985
- `[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`
979
+ `[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${path7}\uFF080600\uFF09\u3002\u5BA2\u6237\u7AEF\u9700\u5E26 \`Authorization: Bearer <token>\`\uFF1B\u67E5\u770B\uFF1Acat ${path7}\uFF1B\u5982\u9700\u5173\u95ED\u9274\u6743\uFF1AAGENT_MOSS_AUTH_MODE=off`
986
980
  );
987
981
  return tok;
988
982
  } catch (e) {
@@ -1055,16 +1049,16 @@ function constEq(a, b) {
1055
1049
  if (ba.length !== bb.length) return false;
1056
1050
  return timingSafeEqual(ba, bb);
1057
1051
  }
1058
- function checkRequestAuth(headers, path6) {
1052
+ function checkRequestAuth(headers, path7) {
1059
1053
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
1060
- const isHealth = HEALTH_PATHS.includes(path6.replace(/\/+$/, ""));
1054
+ const isHealth = HEALTH_PATHS.includes(path7.replace(/\/+$/, ""));
1061
1055
  const [gt0, agents, err] = resolveAuth();
1062
1056
  if (err) return isHealth ? [true, ""] : [false, ""];
1063
1057
  if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
1064
1058
  if (isHealth) return [true, ""];
1065
1059
  const tok = bearer(headers);
1066
1060
  if (!tok) return [false, ""];
1067
- if (path6.startsWith("/console/api")) {
1061
+ if (path7.startsWith("/console/api")) {
1068
1062
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
1069
1063
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
1070
1064
  }
@@ -1083,8 +1077,8 @@ function bindAgent(principal, agentId) {
1083
1077
  if (!agentId) return [true, bound];
1084
1078
  return [bound === agentId, bound];
1085
1079
  }
1086
- function principalOf(headers, path6 = "") {
1087
- const [ok, principal] = checkRequestAuth(headers, path6);
1080
+ function principalOf(headers, path7 = "") {
1081
+ const [ok, principal] = checkRequestAuth(headers, path7);
1088
1082
  return ok ? principal : "";
1089
1083
  }
1090
1084
  function principalHash(principal) {
@@ -1163,9 +1157,8 @@ function ensurePrivateDir(dir) {
1163
1157
  }
1164
1158
  function writePrivateText(file, text) {
1165
1159
  try {
1166
- const flags = __require("fs").constants;
1167
- let openFlags = flags.O_WRONLY | flags.O_CREAT | flags.O_TRUNC;
1168
- if (flags.O_NOFOLLOW) openFlags |= flags.O_NOFOLLOW;
1160
+ let openFlags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC;
1161
+ if (fsConstants.O_NOFOLLOW) openFlags |= fsConstants.O_NOFOLLOW;
1169
1162
  const fd = openSync(file, openFlags, 384);
1170
1163
  try {
1171
1164
  writeSync(fd, text);
@@ -1342,11 +1335,11 @@ function errorDetailMode() {
1342
1335
  function maxBodyBytes() {
1343
1336
  return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
1344
1337
  }
1345
- function poolOf(path6) {
1346
- if (path6 === "/api/v1/analyze" || path6.startsWith("/api/v1/analyze/")) return "biz";
1347
- if (path6 === "/api/v1/review" || path6.startsWith("/api/v1/review/")) return "review";
1348
- if (path6 === "/console" || path6.startsWith("/console/") || path6.startsWith("/api/v1/brain")) return "ops";
1349
- if (path6 === "/api/v1/health") return "health";
1338
+ function poolOf(path7) {
1339
+ if (path7 === "/api/v1/analyze" || path7.startsWith("/api/v1/analyze/")) return "biz";
1340
+ if (path7 === "/api/v1/review" || path7.startsWith("/api/v1/review/")) return "review";
1341
+ if (path7 === "/console" || path7.startsWith("/console/") || path7.startsWith("/api/v1/brain")) return "ops";
1342
+ if (path7 === "/api/v1/health") return "health";
1350
1343
  return "other";
1351
1344
  }
1352
1345
  function poolLimit(name) {
@@ -1469,6 +1462,8 @@ var init_models = __esm({
1469
1462
  analysis_duration_ms: z.number().default(0),
1470
1463
  // 组合攻击链反例路径:每步 [session_id, seq, stage, timestamp],含真实发生时间
1471
1464
  violation_chain: z.array(z.array(z.union([z.string(), z.number()]).nullable())).default([]),
1465
+ // 本次判定的能力降级说明(2026-11):正常为空;链状态触顶时说明 L2.2 未覆盖
1466
+ degraded: z.array(z.string()).default([]),
1472
1467
  // 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
1473
1468
  violation_graph: z.object({
1474
1469
  // 性质元信息(前端展示"违反了哪条性质")
@@ -1508,12 +1503,18 @@ var init_models = __esm({
1508
1503
  }).nullable().default(null)
1509
1504
  });
1510
1505
  HealthResponseSchema = z.object({
1506
+ // healthy | degraded(2026-11):degraded 表示服务可用但**某项安全能力已降级**
1507
+ // (链状态触顶、LLM 熔断)。任何探活/监控只看 status 就能发现异常。
1511
1508
  status: z.string().default("healthy"),
1509
+ // 降级原因(status=degraded 时非空)
1510
+ degraded: z.array(z.string()).default([]),
1512
1511
  version: z.string().default(version),
1513
1512
  // 归属实例标识:值来自 env AGENT_MOSS_INSTANCE(spawn/systemd 注入),默认空串。
1514
1513
  // 多个 agentmoss 同机并存时,调用方按 instance 过滤避免连到别人的进程。
1515
1514
  // 空=未配置(独立部署或旧版),调用方可选择兼容或严格过滤。
1516
- instance: z.string().default("")
1515
+ instance: z.string().default(""),
1516
+ // 运行态指标(2026-11 增强):事件循环延迟、并发池占用、链状态规模。
1517
+ metrics: z.record(z.unknown()).default({})
1517
1518
  });
1518
1519
  ReviewRequestSchema = z.object({
1519
1520
  agent_id: z.string().default("").describe("\u76EE\u6807 agent \u6807\u8BC6\uFF08\u51B3\u5B9A\u72B6\u6001\u5E93\u5206\u6876\uFF09"),
@@ -1797,7 +1798,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
1797
1798
  os: String(sp.os || "linux").toLowerCase()
1798
1799
  }));
1799
1800
  }
1800
- function _scopeOf(os4, path6) {
1801
+ function _scopeOf(os4, path7) {
1801
1802
  if (!_scopeIndex) {
1802
1803
  _scopeIndex = /* @__PURE__ */ new Map();
1803
1804
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -1805,7 +1806,7 @@ function _scopeOf(os4, path6) {
1805
1806
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
1806
1807
  }
1807
1808
  }
1808
- return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path6}`) || "root";
1809
+ return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path7}`) || "root";
1809
1810
  }
1810
1811
  function getSensitivePathsForOs(osType) {
1811
1812
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -2156,17 +2157,17 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2156
2157
  return null;
2157
2158
  }
2158
2159
  const unreadPaths = [];
2159
- for (const path6 of filteredPaths) {
2160
+ for (const path7 of filteredPaths) {
2160
2161
  const hasRead = [...historyReadPaths].some(
2161
- (rp) => path6 === rp || path6.startsWith(rp) || rp.startsWith(path6)
2162
+ (rp) => path7 === rp || path7.startsWith(rp) || rp.startsWith(path7)
2162
2163
  );
2163
2164
  if (!hasRead) {
2164
- let isCreate = !fs.existsSync(path6);
2165
+ let isCreate = !fs.existsSync(path7);
2165
2166
  if (!isCreate) {
2166
2167
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
2167
2168
  }
2168
2169
  if (!isCreate) {
2169
- unreadPaths.push(path6);
2170
+ unreadPaths.push(path7);
2170
2171
  }
2171
2172
  }
2172
2173
  }
@@ -2360,16 +2361,16 @@ var init_logic_rules = __esm({
2360
2361
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
2361
2362
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
2362
2363
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
2363
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2364
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2364
2365
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
2365
2366
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
2366
- CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2367
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2367
2368
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
2368
2369
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
2369
- CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2370
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2370
2371
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
2371
2372
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
2372
- CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2373
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2373
2374
  _scopeIndex = null;
2374
2375
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
2375
2376
  "ask_user_question",
@@ -4138,7 +4139,9 @@ function loadLLMConfigFromFile(configPath) {
4138
4139
  model: llm.model || "",
4139
4140
  temperature: llm.temperature ?? 0.1,
4140
4141
  maxTokens: llm.max_tokens ?? 4096,
4141
- timeout: llm.timeout ?? 40
4142
+ timeout: llm.timeout ?? 40,
4143
+ // 部署级透传参数(关思考等)。非对象直接忽略:写错不能拖垮配置加载。
4144
+ ...llm.extra_body && typeof llm.extra_body === "object" && !Array.isArray(llm.extra_body) ? { extraBody: llm.extra_body } : {}
4142
4145
  };
4143
4146
  }
4144
4147
  function loadTimeoutRetryFromFile(configPath) {
@@ -4970,16 +4973,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4970
4973
  if (String(osType || "").toLowerCase() === "windows") {
4971
4974
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
4972
4975
  }
4973
- const pathMatches = (text, path6) => {
4974
- const parts = path6.split(/(\(\?!.*?\))/);
4976
+ const pathMatches = (text, path7) => {
4977
+ const parts = path7.split(/(\(\?!.*?\))/);
4975
4978
  const escaped = parts.map((part) => {
4976
4979
  if (part.startsWith("(?!")) return part;
4977
4980
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4978
4981
  }).join("");
4979
- const re = path6.startsWith(".") || path6.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4982
+ const re = path7.startsWith(".") || path7.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4980
4983
  return re.test(text);
4981
4984
  };
4982
- const pathMatchesAny = (path6) => pathScanTexts.some((t) => pathMatches(t, path6));
4985
+ const pathMatchesAny = (path7) => pathScanTexts.some((t) => pathMatches(t, path7));
4983
4986
  for (const sp of rootPaths) {
4984
4987
  if (pathMatchesAny(sp.path.toLowerCase())) {
4985
4988
  if (keygenGenerate) continue;
@@ -5122,8 +5125,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5122
5125
  }
5123
5126
  return null;
5124
5127
  }
5125
- function isHomeValue(path6) {
5126
- let p = path6.trim().toLowerCase();
5128
+ function isHomeValue(path7) {
5129
+ let p = path7.trim().toLowerCase();
5127
5130
  if (p.startsWith("$(") && p.endsWith(")")) {
5128
5131
  const inner = p.slice(2, -1).trim();
5129
5132
  return HOME_TARGET_RE.test(" " + inner);
@@ -5179,15 +5182,15 @@ function checkHomeDeletion(actionType, actionDetail) {
5179
5182
  }
5180
5183
  const assigned = {};
5181
5184
  for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
5182
- for (const [varName, path6] of Object.entries(assigned)) {
5183
- if (!isHomeValue(path6)) continue;
5185
+ for (const [varName, path7] of Object.entries(assigned)) {
5186
+ if (!isHomeValue(path7)) continue;
5184
5187
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
5185
5188
  for (const seg of segs) {
5186
5189
  if (!isDeleteCommand(seg)) continue;
5187
5190
  if (varRefRe.test(seg)) {
5188
5191
  return {
5189
5192
  allowed: false,
5190
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path6}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5193
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path7}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5191
5194
  riskLevel: "high",
5192
5195
  riskType: "script_execution",
5193
5196
  confidence: 90,
@@ -5991,15 +5994,15 @@ function parseShellString(s) {
5991
5994
  let m;
5992
5995
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
5993
5996
  const interp = m[1];
5994
- const path6 = m[2].trim();
5997
+ const path7 = m[2].trim();
5995
5998
  let rest = m[3].trim();
5996
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
5999
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
5997
6000
  rest = rest.split(/[;|&<>]/)[0].trim();
5998
6001
  const args = [];
5999
6002
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6000
6003
  args.push(tm[1] ? tm[2] : tm[3]);
6001
6004
  }
6002
- return { path: path6, args, interpreter: interp };
6005
+ return { path: path7, args, interpreter: interp };
6003
6006
  }
6004
6007
  return null;
6005
6008
  }
@@ -6045,9 +6048,9 @@ function extractCallsFromTree(tree, reachableLines) {
6045
6048
  }
6046
6049
  if (allStr && elts.length >= 2) {
6047
6050
  const interp = elts[0];
6048
- const path6 = elts[1];
6049
- if (!path6.startsWith("-") && !path6.startsWith("$") && !path6.includes("/dev/")) {
6050
- add({ path: path6, args: elts.slice(2), interpreter: interp });
6051
+ const path7 = elts[1];
6052
+ if (!path7.startsWith("-") && !path7.startsWith("$") && !path7.includes("/dev/")) {
6053
+ add({ path: path7, args: elts.slice(2), interpreter: interp });
6051
6054
  return true;
6052
6055
  }
6053
6056
  }
@@ -6087,15 +6090,15 @@ function extractCallsRegex(content) {
6087
6090
  let m;
6088
6091
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
6089
6092
  const interp = m[1];
6090
- const path6 = m[2].trim();
6093
+ const path7 = m[2].trim();
6091
6094
  let rest = m[3].trim();
6092
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
6095
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6093
6096
  rest = rest.split(/[;|&<>]/)[0].trim();
6094
6097
  const args = [];
6095
6098
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6096
6099
  args.push(tm[1] ? tm[2] : tm[3]);
6097
6100
  }
6098
- calls.push({ path: path6, args, interpreter: interp });
6101
+ calls.push({ path: path7, args, interpreter: interp });
6099
6102
  }
6100
6103
  return calls;
6101
6104
  }
@@ -6878,15 +6881,15 @@ function extractCallsFromContent(content) {
6878
6881
  CHILD_CALL_RE2.lastIndex = 0;
6879
6882
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
6880
6883
  const interp = m[1];
6881
- const path6 = m[2].trim();
6884
+ const path7 = m[2].trim();
6882
6885
  let rest = m[3].trim();
6883
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
6886
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6884
6887
  rest = rest.split(/[;|&<>]/)[0].trim();
6885
6888
  const args = [];
6886
6889
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6887
6890
  args.push(tm[1] ? tm[2] : tm[3]);
6888
6891
  }
6889
- calls.push({ path: path6, args, interpreter: interp });
6892
+ calls.push({ path: path7, args, interpreter: interp });
6890
6893
  }
6891
6894
  return calls;
6892
6895
  }
@@ -7575,6 +7578,464 @@ var init_script_content_analyzer = __esm({
7575
7578
  }
7576
7579
  });
7577
7580
 
7581
+ // src/infra/trace-log.ts
7582
+ import fs4 from "fs";
7583
+ import path4 from "path";
7584
+ function traceLevel() {
7585
+ if (_levelCache !== null) return _levelCache;
7586
+ const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
7587
+ let level;
7588
+ if (raw in LEVEL_NAMES) {
7589
+ level = LEVEL_NAMES[raw];
7590
+ } else {
7591
+ level = LEVEL_SUMMARY;
7592
+ if (!_warnedInvalid) {
7593
+ _warnedInvalid = true;
7594
+ console.warn(
7595
+ `[AgentMoss] AGENT_MOSS_TRACE_LEVEL=${JSON.stringify(raw)} \u975E\u6CD5\uFF0C\u6309 summary \u5904\u7406\uFF08\u53EF\u9009 off/summary/full\uFF09`
7596
+ );
7597
+ }
7598
+ }
7599
+ _levelCache = level;
7600
+ _levelCacheRaw = raw;
7601
+ return level;
7602
+ }
7603
+ function nowIso() {
7604
+ return (/* @__PURE__ */ new Date()).toISOString();
7605
+ }
7606
+ function tracePath() {
7607
+ const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
7608
+ if (explicit) return explicit;
7609
+ try {
7610
+ return path4.join(getDataRoot(), "agent_moss_trace.log");
7611
+ } catch {
7612
+ return "agent_moss_trace.log";
7613
+ }
7614
+ }
7615
+ function sanitize(key, value) {
7616
+ if (SECRET_KEYS.has(key.toLowerCase())) return "***";
7617
+ if (typeof value === "string") {
7618
+ let v = value;
7619
+ if (v.length > MAX_FIELD_CHARS) {
7620
+ const original = v.length;
7621
+ v = `${v.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
7622
+ }
7623
+ return v;
7624
+ }
7625
+ if (value === null || ["number", "boolean"].includes(typeof value)) return value;
7626
+ let text;
7627
+ try {
7628
+ text = JSON.stringify(value);
7629
+ } catch {
7630
+ return String(value);
7631
+ }
7632
+ if (text.length > MAX_FIELD_CHARS) {
7633
+ const original = text.length;
7634
+ return `${text.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
7635
+ }
7636
+ return value;
7637
+ }
7638
+ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
7639
+ if (traceLevel() < level) return;
7640
+ try {
7641
+ const record = { ts: nowIso(), event };
7642
+ for (const [key, value] of Object.entries(fields)) {
7643
+ record[key] = sanitize(key, value);
7644
+ }
7645
+ const line = `${JSON.stringify(record)}
7646
+ `;
7647
+ const file = tracePath();
7648
+ try {
7649
+ const dir = path4.dirname(file);
7650
+ if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
7651
+ try {
7652
+ const st = fs4.statSync(file);
7653
+ if (st.size > MAX_FILE_BYTES) fs4.renameSync(file, `${file}.1`);
7654
+ } catch {
7655
+ }
7656
+ fs4.appendFileSync(file, line, { encoding: "utf-8", mode: 384 });
7657
+ } catch {
7658
+ }
7659
+ } catch {
7660
+ }
7661
+ }
7662
+ function traceSummary(event, fields = {}) {
7663
+ trace(event, LEVEL_SUMMARY, fields);
7664
+ }
7665
+ function traceFull(event, fields = {}) {
7666
+ trace(event, LEVEL_FULL, fields);
7667
+ }
7668
+ var LEVEL_OFF, LEVEL_SUMMARY, LEVEL_FULL, LEVEL_NAMES, MAX_FIELD_CHARS, SECRET_KEYS, MAX_FILE_BYTES, _levelCache, _levelCacheRaw, _warnedInvalid;
7669
+ var init_trace_log = __esm({
7670
+ "src/infra/trace-log.ts"() {
7671
+ "use strict";
7672
+ init_esm_shims();
7673
+ init_paths();
7674
+ LEVEL_OFF = 0;
7675
+ LEVEL_SUMMARY = 1;
7676
+ LEVEL_FULL = 2;
7677
+ LEVEL_NAMES = {
7678
+ off: LEVEL_OFF,
7679
+ summary: LEVEL_SUMMARY,
7680
+ full: LEVEL_FULL
7681
+ };
7682
+ MAX_FIELD_CHARS = 64 * 1024;
7683
+ SECRET_KEYS = /* @__PURE__ */ new Set([
7684
+ "api_key",
7685
+ "apikey",
7686
+ "authorization",
7687
+ "auth_token",
7688
+ "token",
7689
+ "password"
7690
+ ]);
7691
+ MAX_FILE_BYTES = 20 * 1024 * 1024;
7692
+ _levelCache = null;
7693
+ _levelCacheRaw = null;
7694
+ _warnedInvalid = false;
7695
+ }
7696
+ });
7697
+
7698
+ // src/infra/circuit-breaker.ts
7699
+ function envInt2(name, fallback) {
7700
+ const raw = process.env[name];
7701
+ if (raw === void 0 || raw.trim() === "") return fallback;
7702
+ const n = Number(raw);
7703
+ return Number.isFinite(n) ? n : fallback;
7704
+ }
7705
+ function getBreaker() {
7706
+ if (_breaker === null) {
7707
+ _breaker = new CircuitBreaker(
7708
+ envInt2("AGENT_MOSS_LLM_CIRCUIT_THRESHOLD", 5),
7709
+ envInt2("AGENT_MOSS_LLM_CIRCUIT_COOLDOWN", 30)
7710
+ );
7711
+ }
7712
+ return _breaker;
7713
+ }
7714
+ var CLOSED, OPEN, HALF_OPEN, CircuitBreaker, _breaker;
7715
+ var init_circuit_breaker = __esm({
7716
+ "src/infra/circuit-breaker.ts"() {
7717
+ "use strict";
7718
+ init_esm_shims();
7719
+ CLOSED = "closed";
7720
+ OPEN = "open";
7721
+ HALF_OPEN = "half_open";
7722
+ CircuitBreaker = class {
7723
+ constructor(threshold = 5, cooldown = 30) {
7724
+ this.threshold = threshold;
7725
+ this.cooldown = cooldown;
7726
+ }
7727
+ threshold;
7728
+ cooldown;
7729
+ state = CLOSED;
7730
+ failures = 0;
7731
+ openedAt = 0;
7732
+ openCount = 0;
7733
+ shortCircuitCount = 0;
7734
+ get currentState() {
7735
+ return this.state;
7736
+ }
7737
+ allow() {
7738
+ if (this.threshold <= 0) return true;
7739
+ if (this.state === CLOSED) return true;
7740
+ if (this.state === OPEN) {
7741
+ if ((performance.now() - this.openedAt) / 1e3 >= this.cooldown) {
7742
+ this.state = HALF_OPEN;
7743
+ return true;
7744
+ }
7745
+ this.shortCircuitCount += 1;
7746
+ return false;
7747
+ }
7748
+ return true;
7749
+ }
7750
+ recordSuccess() {
7751
+ if (this.threshold <= 0) return;
7752
+ this.state = CLOSED;
7753
+ this.failures = 0;
7754
+ }
7755
+ recordFailure() {
7756
+ if (this.threshold <= 0) return;
7757
+ if (this.state === HALF_OPEN) {
7758
+ this.state = OPEN;
7759
+ this.openedAt = performance.now();
7760
+ this.openCount += 1;
7761
+ return;
7762
+ }
7763
+ this.failures += 1;
7764
+ if (this.failures >= this.threshold) {
7765
+ this.state = OPEN;
7766
+ this.openedAt = performance.now();
7767
+ this.openCount += 1;
7768
+ }
7769
+ }
7770
+ snapshot() {
7771
+ return {
7772
+ state: this.state,
7773
+ failures: this.failures,
7774
+ threshold: this.threshold,
7775
+ cooldown_sec: this.cooldown,
7776
+ open_count: this.openCount,
7777
+ short_circuit_count: this.shortCircuitCount
7778
+ };
7779
+ }
7780
+ reset() {
7781
+ this.state = CLOSED;
7782
+ this.failures = 0;
7783
+ this.openedAt = 0;
7784
+ }
7785
+ };
7786
+ _breaker = null;
7787
+ }
7788
+ });
7789
+
7790
+ // src/infra/metrics.ts
7791
+ function escapeLabel(value) {
7792
+ return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
7793
+ }
7794
+ function formatLabels(labels) {
7795
+ if (!labels) return "";
7796
+ const keys = Object.keys(labels).sort();
7797
+ if (!keys.length) return "";
7798
+ return `{${keys.map((k) => `${k}="${escapeLabel(labels[k])}"`).join(",")}}`;
7799
+ }
7800
+ function keyOf(labelnames, labels) {
7801
+ return labelnames.map((k) => String(labels[k] ?? "")).join("");
7802
+ }
7803
+ function decodeKey(labelnames, key) {
7804
+ if (!labelnames.length) return void 0;
7805
+ const parts = key.split("");
7806
+ const out = {};
7807
+ labelnames.forEach((k, i) => {
7808
+ out[k] = parts[i] ?? "";
7809
+ });
7810
+ return out;
7811
+ }
7812
+ function renderPrometheus() {
7813
+ const lines = [];
7814
+ for (const m of [
7815
+ ANALYZE_TOTAL,
7816
+ ANALYZE_DURATION,
7817
+ LAYER_HIT_TOTAL,
7818
+ REJECTED_TOTAL,
7819
+ LLM_CALLS_TOTAL,
7820
+ LLM_DURATION,
7821
+ POOL_INFLIGHT,
7822
+ CHAIN_NODES,
7823
+ CHAIN_DB_BYTES,
7824
+ LOOP_LAG,
7825
+ LOOP_LAG_MAX,
7826
+ UPTIME,
7827
+ LLM_CIRCUIT_STATE,
7828
+ LLM_SHORT_CIRCUIT_TOTAL
7829
+ ]) {
7830
+ lines.push(...m.render());
7831
+ }
7832
+ return `${lines.join("\n")}
7833
+ `;
7834
+ }
7835
+ function refreshRuntimeGauges(g) {
7836
+ UPTIME.set((Date.now() - STARTED_AT) / 1e3);
7837
+ try {
7838
+ const snap = getBreaker().snapshot();
7839
+ const stateMap = { closed: 0, open: 1, half_open: 2 };
7840
+ LLM_CIRCUIT_STATE.set(stateMap[String(snap.state)] ?? 0);
7841
+ } catch {
7842
+ }
7843
+ if (g.pools !== void 0) {
7844
+ POOL_INFLIGHT.clear();
7845
+ for (const [key, value] of Object.entries(g.pools)) {
7846
+ POOL_INFLIGHT.set(value, { pool: key });
7847
+ }
7848
+ }
7849
+ if (g.chainNodes !== void 0) {
7850
+ CHAIN_NODES.clear();
7851
+ CHAIN_NODES.set(g.chainNodes, { agent: "__total__" });
7852
+ }
7853
+ if (g.chainDbBytes !== void 0) CHAIN_DB_BYTES.set(g.chainDbBytes);
7854
+ if (g.loopLagMs !== void 0) LOOP_LAG.set(g.loopLagMs / 1e3);
7855
+ if (g.loopLagMaxMs !== void 0) LOOP_LAG_MAX.set(g.loopLagMaxMs / 1e3);
7856
+ }
7857
+ 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;
7858
+ var init_metrics = __esm({
7859
+ "src/infra/metrics.ts"() {
7860
+ "use strict";
7861
+ init_esm_shims();
7862
+ init_circuit_breaker();
7863
+ DEFAULT_BUCKETS = [
7864
+ 5e-3,
7865
+ 0.01,
7866
+ 0.025,
7867
+ 0.05,
7868
+ 0.1,
7869
+ 0.25,
7870
+ 0.5,
7871
+ 1,
7872
+ 2.5,
7873
+ 5,
7874
+ 10,
7875
+ 30,
7876
+ 60
7877
+ ];
7878
+ STARTED_AT = Date.now();
7879
+ Counter = class {
7880
+ constructor(name, helpText, labelnames = []) {
7881
+ this.name = name;
7882
+ this.helpText = helpText;
7883
+ this.labelnames = labelnames;
7884
+ }
7885
+ name;
7886
+ helpText;
7887
+ labelnames;
7888
+ values = /* @__PURE__ */ new Map();
7889
+ inc(amount = 1, labels = {}) {
7890
+ const k = keyOf(this.labelnames, labels);
7891
+ this.values.set(k, (this.values.get(k) ?? 0) + amount);
7892
+ }
7893
+ render() {
7894
+ const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} counter`];
7895
+ if (!this.values.size) {
7896
+ const empty = this.labelnames.length ? Object.fromEntries(this.labelnames.map((k) => [k, ""])) : void 0;
7897
+ out.push(`${this.name}${formatLabels(empty)} 0`);
7898
+ return out;
7899
+ }
7900
+ for (const [k, v] of this.values) {
7901
+ out.push(`${this.name}${formatLabels(decodeKey(this.labelnames, k))} ${v}`);
7902
+ }
7903
+ return out;
7904
+ }
7905
+ };
7906
+ Gauge = class {
7907
+ constructor(name, helpText, labelnames = []) {
7908
+ this.name = name;
7909
+ this.helpText = helpText;
7910
+ this.labelnames = labelnames;
7911
+ }
7912
+ name;
7913
+ helpText;
7914
+ labelnames;
7915
+ values = /* @__PURE__ */ new Map();
7916
+ set(value, labels = {}) {
7917
+ this.values.set(keyOf(this.labelnames, labels), Number(value));
7918
+ }
7919
+ clear() {
7920
+ this.values.clear();
7921
+ }
7922
+ render() {
7923
+ const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} gauge`];
7924
+ for (const [k, v] of this.values) {
7925
+ const labels = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : void 0;
7926
+ out.push(`${this.name}${formatLabels(labels)} ${v}`);
7927
+ }
7928
+ return out;
7929
+ }
7930
+ };
7931
+ Histogram = class {
7932
+ constructor(name, helpText, buckets = DEFAULT_BUCKETS, labelnames = []) {
7933
+ this.name = name;
7934
+ this.helpText = helpText;
7935
+ this.buckets = buckets;
7936
+ this.labelnames = labelnames;
7937
+ }
7938
+ name;
7939
+ helpText;
7940
+ buckets;
7941
+ labelnames;
7942
+ values = /* @__PURE__ */ new Map();
7943
+ observe(value, labels = {}) {
7944
+ const k = keyOf(this.labelnames, labels);
7945
+ let slot = this.values.get(k);
7946
+ if (!slot) {
7947
+ slot = { buckets: this.buckets.map(() => 0), sum: 0, count: 0 };
7948
+ this.values.set(k, slot);
7949
+ }
7950
+ for (let i = 0; i < this.buckets.length; i++) {
7951
+ if (value <= this.buckets[i]) slot.buckets[i] += 1;
7952
+ }
7953
+ slot.sum += value;
7954
+ slot.count += 1;
7955
+ }
7956
+ render() {
7957
+ const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} histogram`];
7958
+ for (const [k, slot] of this.values) {
7959
+ const base = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : {};
7960
+ this.buckets.forEach((bound, i) => {
7961
+ out.push(`${this.name}_bucket${formatLabels({ ...base, le: String(bound) })} ${slot.buckets[i]}`);
7962
+ });
7963
+ out.push(`${this.name}_bucket${formatLabels({ ...base, le: "+Inf" })} ${slot.count}`);
7964
+ out.push(`${this.name}_sum${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.sum}`);
7965
+ out.push(`${this.name}_count${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.count}`);
7966
+ }
7967
+ return out;
7968
+ }
7969
+ };
7970
+ ANALYZE_TOTAL = new Counter(
7971
+ "agent_moss_analyze_total",
7972
+ "Total analyze requests handled, by decision and risk level.",
7973
+ ["decision", "risk_level"]
7974
+ );
7975
+ ANALYZE_DURATION = new Histogram(
7976
+ "agent_moss_analyze_duration_seconds",
7977
+ "End-to-end analyze duration in seconds.",
7978
+ DEFAULT_BUCKETS,
7979
+ ["decision"]
7980
+ );
7981
+ LAYER_HIT_TOTAL = new Counter(
7982
+ "agent_moss_layer_hit_total",
7983
+ "Number of requests where a given defense layer produced the final verdict.",
7984
+ ["layer"]
7985
+ );
7986
+ REJECTED_TOTAL = new Counter(
7987
+ "agent_moss_rejected_total",
7988
+ "Requests rejected before analysis (concurrency / rate limit / auth).",
7989
+ ["reason"]
7990
+ );
7991
+ LLM_CALLS_TOTAL = new Counter(
7992
+ "agent_moss_llm_calls_total",
7993
+ "LLM API calls, by outcome.",
7994
+ ["result"]
7995
+ );
7996
+ LLM_DURATION = new Histogram(
7997
+ "agent_moss_llm_duration_seconds",
7998
+ "LLM API call duration in seconds.",
7999
+ DEFAULT_BUCKETS,
8000
+ ["result"]
8001
+ );
8002
+ POOL_INFLIGHT = new Gauge(
8003
+ "agent_moss_pool_inflight",
8004
+ "Current in-flight requests per concurrency pool.",
8005
+ ["pool"]
8006
+ );
8007
+ CHAIN_NODES = new Gauge(
8008
+ "agent_moss_chain_nodes",
8009
+ "Number of nodes in the stateful chain timeline.",
8010
+ ["agent"]
8011
+ );
8012
+ CHAIN_DB_BYTES = new Gauge(
8013
+ "agent_moss_chain_db_bytes",
8014
+ "Size of the chain state database in bytes."
8015
+ );
8016
+ LOOP_LAG = new Gauge(
8017
+ "agent_moss_event_loop_lag_seconds",
8018
+ "Most recent event loop lag sample in seconds."
8019
+ );
8020
+ LOOP_LAG_MAX = new Gauge(
8021
+ "agent_moss_event_loop_lag_max_seconds",
8022
+ "Maximum event loop lag observed since process start, in seconds."
8023
+ );
8024
+ UPTIME = new Gauge(
8025
+ "agent_moss_uptime_seconds",
8026
+ "Seconds since process start."
8027
+ );
8028
+ LLM_CIRCUIT_STATE = new Gauge(
8029
+ "agent_moss_llm_circuit_state",
8030
+ "LLM circuit breaker state (0=closed, 1=open, 2=half_open)."
8031
+ );
8032
+ LLM_SHORT_CIRCUIT_TOTAL = new Counter(
8033
+ "agent_moss_llm_short_circuit_total",
8034
+ "LLM calls short-circuited by the breaker (no network request made)."
8035
+ );
8036
+ }
8037
+ });
8038
+
7578
8039
  // src/engine/token-stats.ts
7579
8040
  var token_stats_exports = {};
7580
8041
  __export(token_stats_exports, {
@@ -7583,9 +8044,10 @@ __export(token_stats_exports, {
7583
8044
  getTokenStats: () => getTokenStats,
7584
8045
  getTokenTrend: () => getTokenTrend,
7585
8046
  recordTokenUsage: () => recordTokenUsage,
7586
- resetTokenStats: () => resetTokenStats
8047
+ resetTokenStats: () => resetTokenStats,
8048
+ resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
7587
8049
  });
7588
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2 } from "fs";
8050
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync5 } from "fs";
7589
8051
  function getStatsPath() {
7590
8052
  const envPath = process.env[ENV_STATS_PATH];
7591
8053
  if (envPath) return envPath;
@@ -7593,11 +8055,24 @@ function getStatsPath() {
7593
8055
  }
7594
8056
  function loadAllRecords(statsPath) {
7595
8057
  if (!existsSync13(statsPath)) return [];
8058
+ let sig = "";
7596
8059
  try {
7597
- const data = JSON.parse(readFileSync13(statsPath, "utf-8"));
7598
- if (Array.isArray(data)) return data;
7599
- if (data && Array.isArray(data.records)) return data.records;
8060
+ const st = statSync5(statsPath);
8061
+ sig = `${st.mtimeMs}:${st.size}`;
8062
+ } catch {
7600
8063
  return [];
8064
+ }
8065
+ if (_recordsCache && _recordsCache.path === statsPath && _recordsCache.sig === sig) {
8066
+ return _recordsCache.records.slice();
8067
+ }
8068
+ try {
8069
+ const data = JSON.parse(readFileSync13(statsPath, "utf-8"));
8070
+ let records;
8071
+ if (Array.isArray(data)) records = data;
8072
+ else if (data && Array.isArray(data.records)) records = data.records;
8073
+ else records = [];
8074
+ _recordsCache = { path: statsPath, sig, records };
8075
+ return records.slice();
7601
8076
  } catch (e) {
7602
8077
  return [];
7603
8078
  }
@@ -7607,9 +8082,22 @@ function saveRecords(statsPath, records) {
7607
8082
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
7608
8083
  if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
7609
8084
  writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
8085
+ try {
8086
+ const st = statSync5(statsPath);
8087
+ _recordsCache = {
8088
+ path: statsPath,
8089
+ sig: `${st.mtimeMs}:${st.size}`,
8090
+ records: records.slice()
8091
+ };
8092
+ } catch {
8093
+ _recordsCache = null;
8094
+ }
7610
8095
  } catch (e) {
7611
8096
  }
7612
8097
  }
8098
+ function resetTokenStatsCacheForTests() {
8099
+ _recordsCache = null;
8100
+ }
7613
8101
  function recordTokenUsage(record) {
7614
8102
  const statsPath = getStatsPath();
7615
8103
  const records = loadAllRecords(statsPath);
@@ -7738,8 +8226,9 @@ function resetTokenStats() {
7738
8226
  } catch {
7739
8227
  }
7740
8228
  }
8229
+ _recordsCache = null;
7741
8230
  }
7742
- var ENV_STATS_PATH, MAX_RECORDS;
8231
+ var ENV_STATS_PATH, MAX_RECORDS, _recordsCache;
7743
8232
  var init_token_stats = __esm({
7744
8233
  "src/engine/token-stats.ts"() {
7745
8234
  "use strict";
@@ -7747,13 +8236,30 @@ var init_token_stats = __esm({
7747
8236
  init_paths();
7748
8237
  ENV_STATS_PATH = "AGENT_MOSS_TOKEN_STATS_PATH";
7749
8238
  MAX_RECORDS = 1e4;
8239
+ _recordsCache = null;
7750
8240
  }
7751
8241
  });
7752
8242
 
7753
8243
  // src/engine/llm-analyzer.ts
7754
8244
  import { createHash as createHash3 } from "crypto";
7755
- import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
8245
+ import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants2 } from "fs";
7756
8246
  import OpenAI from "openai";
8247
+ function responseFieldLengths(message) {
8248
+ if (!message || typeof message !== "object") return {};
8249
+ const out = {};
8250
+ for (const [key, value] of Object.entries(message)) {
8251
+ if (value === null || value === void 0 || value === "") continue;
8252
+ if (Array.isArray(value) && value.length === 0) continue;
8253
+ if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) continue;
8254
+ if (typeof value === "boolean") continue;
8255
+ try {
8256
+ out[key] = typeof value === "string" ? value.length : String(JSON.stringify(value)).length;
8257
+ } catch {
8258
+ out[key] = -1;
8259
+ }
8260
+ }
8261
+ return out;
8262
+ }
7757
8263
  async function runLLMAnalysis(input, previous) {
7758
8264
  if (!isLLMAvailable()) {
7759
8265
  console.log("[AgentMoss] LLM not configured, skipping deep analysis");
@@ -7836,7 +8342,23 @@ async function runLLMAnalysis(input, previous) {
7836
8342
  );
7837
8343
  }
7838
8344
  logPrompt(prompt, input.aNext, previous.llmLogPath);
8345
+ traceFull("l3.prompt", {
8346
+ phase: "security_judge",
8347
+ model: config.model,
8348
+ base_url: config.baseUrl,
8349
+ action_type: input.aNext.actionType,
8350
+ action_detail: input.aNext.actionDetail,
8351
+ prompt,
8352
+ prompt_chars: prompt.length
8353
+ });
7839
8354
  const result = await analyzeWithLLM(prompt, config);
8355
+ traceSummary("l3.verdict", {
8356
+ allowed: result.allowed,
8357
+ risk_level: result.riskLevel,
8358
+ risk_type: result.riskType,
8359
+ reason: result.reason,
8360
+ confidence: result.confidence
8361
+ });
7840
8362
  if (llmCache.size >= LLM_CACHE_MAX) {
7841
8363
  const firstKey = llmCache.keys().next().value;
7842
8364
  if (firstKey) llmCache.delete(firstKey);
@@ -7857,8 +8379,8 @@ function logPrompt(prompt, aNext, logPath) {
7857
8379
  ${prompt}
7858
8380
  --- END PROMPT ---
7859
8381
  `;
7860
- let flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND;
7861
- if (fsConstants.O_NOFOLLOW) flags |= fsConstants.O_NOFOLLOW;
8382
+ let flags = fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_APPEND;
8383
+ if (fsConstants2.O_NOFOLLOW) flags |= fsConstants2.O_NOFOLLOW;
7862
8384
  const fd = openSync2(logPath, flags, 384);
7863
8385
  try {
7864
8386
  writeSync2(fd, line);
@@ -7978,6 +8500,14 @@ function formatHints(previous) {
7978
8500
  }
7979
8501
  async function analyzeWithLLM(prompt, config) {
7980
8502
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
8503
+ const _llmStart = performance.now();
8504
+ const _recordLlm = (result) => {
8505
+ try {
8506
+ LLM_CALLS_TOTAL.inc(1, { result });
8507
+ LLM_DURATION.observe(Math.max(0, (performance.now() - _llmStart) / 1e3), { result });
8508
+ } catch {
8509
+ }
8510
+ };
7981
8511
  const provider = detectProvider(config.baseUrl, config.provider);
7982
8512
  const extraHeaders = getProviderHeaders(provider);
7983
8513
  if (Object.keys(extraHeaders).length > 0) {
@@ -7999,6 +8529,17 @@ async function analyzeWithLLM(prompt, config) {
7999
8529
  console.error(`[AgentMoss] totalTimeout (${timeoutCfg.totalTimeout}s) exceeded, aborting all LLM calls`);
8000
8530
  abortController.abort();
8001
8531
  }, totalTimeoutMs);
8532
+ const breaker = getBreaker();
8533
+ if (!breaker.allow()) {
8534
+ try {
8535
+ LLM_SHORT_CIRCUIT_TOTAL.inc(1);
8536
+ } catch {
8537
+ }
8538
+ _recordLlm("error");
8539
+ throw new Error(
8540
+ "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"
8541
+ );
8542
+ }
8002
8543
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
8003
8544
  if (abortController.signal.aborted) {
8004
8545
  break;
@@ -8012,22 +8553,49 @@ async function analyzeWithLLM(prompt, config) {
8012
8553
  { role: "system", content: "\u53EA\u8F93\u51FA\u7EAF JSON\uFF0C\u4E0D\u8981\u5305\u542B markdown \u6807\u8BB0\u3001\u4EE3\u7801\u5757\u6216\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002" },
8013
8554
  { role: "user", content: prompt }
8014
8555
  ],
8015
- signal: abortController.signal
8556
+ signal: abortController.signal,
8557
+ // 私有化网关的额外参数(关思考等)原样透传;空则不传。
8558
+ ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
8016
8559
  });
8017
8560
  const message = response.choices[0]?.message;
8018
8561
  const content = message?.content ?? "";
8019
8562
  const finishReason = response.choices[0]?.finish_reason;
8020
- const reasoningLen = typeof message?.reasoning_content === "string" ? message.reasoning_content.length : 0;
8563
+ const fieldLengths = responseFieldLengths(message);
8021
8564
  const usage = response.usage;
8022
8565
  if (!content) {
8023
- 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 ?? "?"}`;
8566
+ 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 ?? "?"}`;
8567
+ traceFull("l3.empty_response", {
8568
+ model: response.model || config.model,
8569
+ finish_reason: finishReason,
8570
+ message,
8571
+ prompt_tokens: usage?.prompt_tokens ?? 0,
8572
+ completion_tokens: usage?.completion_tokens ?? 0
8573
+ });
8574
+ let fullMessage = "<empty>";
8575
+ try {
8576
+ fullMessage = JSON.stringify(message ?? {});
8577
+ if (fullMessage.length > 8e3) {
8578
+ fullMessage = `${fullMessage.slice(0, 8e3)}...[truncated ${fullMessage.length} chars]`;
8579
+ }
8580
+ } catch {
8581
+ fullMessage = "<\u65E0\u6CD5\u5E8F\u5217\u5316>";
8582
+ }
8024
8583
  if (finishReason === "length") {
8025
- console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
8584
+ console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
8026
8585
  throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
8027
8586
  }
8028
- console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
8587
+ console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
8588
+ _recordLlm("empty");
8029
8589
  throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
8030
8590
  }
8591
+ traceFull("l3.response", {
8592
+ phase: "security_judge",
8593
+ attempt: attempt + 1,
8594
+ model: response.model || config.model,
8595
+ content,
8596
+ prompt_tokens: usage?.prompt_tokens ?? 0,
8597
+ completion_tokens: usage?.completion_tokens ?? 0
8598
+ });
8031
8599
  console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
8032
8600
  let jsonStr = content.trim();
8033
8601
  if (jsonStr.startsWith("```")) {
@@ -8058,6 +8626,8 @@ async function analyzeWithLLM(prompt, config) {
8058
8626
  clearTimeout(totalTimeoutTimer);
8059
8627
  const riskLevel = parsed.riskLevel ?? parsed.risk_level;
8060
8628
  const riskType = parsed.riskType ?? parsed.risk_type;
8629
+ breaker.recordSuccess();
8630
+ _recordLlm("success");
8061
8631
  return {
8062
8632
  allowed: parsed.allowed !== false,
8063
8633
  reason: parsed.reason || "LLM \u5206\u6790\u5B8C\u6210",
@@ -8068,6 +8638,7 @@ async function analyzeWithLLM(prompt, config) {
8068
8638
  violatedLayers: ["L3.1"]
8069
8639
  };
8070
8640
  } catch (err) {
8641
+ breaker.recordFailure();
8071
8642
  if (abortController.signal.aborted) {
8072
8643
  console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
8073
8644
  break;
@@ -8100,6 +8671,9 @@ var init_llm_analyzer = __esm({
8100
8671
  init_template_loader();
8101
8672
  init_script_analyzer();
8102
8673
  init_script_content_analyzer();
8674
+ init_trace_log();
8675
+ init_metrics();
8676
+ init_circuit_breaker();
8103
8677
  llmCache = /* @__PURE__ */ new Map();
8104
8678
  LLM_CACHE_MAX = 200;
8105
8679
  }
@@ -8138,8 +8712,8 @@ var init_rule_store = __esm({
8138
8712
  BrainRuleStore = class {
8139
8713
  path;
8140
8714
  data;
8141
- constructor(path6) {
8142
- this.path = path6 || getRulesPath();
8715
+ constructor(path7) {
8716
+ this.path = path7 || getRulesPath();
8143
8717
  this.data = this.load();
8144
8718
  }
8145
8719
  load() {
@@ -8592,10 +9166,10 @@ ${reason.slice(0, 500)}
8592
9166
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
8593
9167
  let mm;
8594
9168
  while ((mm = pathRe.exec(src)) !== null) {
8595
- const path6 = mm[1];
8596
- if (path6.split("/").length < 3) continue;
8597
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path6)) continue;
8598
- const gen = this.generalizePath(path6);
9169
+ const path7 = mm[1];
9170
+ if (path7.split("/").length < 3) continue;
9171
+ if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path7)) continue;
9172
+ const gen = this.generalizePath(path7);
8599
9173
  if (seen.has(gen)) continue;
8600
9174
  seen.add(gen);
8601
9175
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -8614,8 +9188,8 @@ ${reason.slice(0, 500)}
8614
9188
  }
8615
9189
  return false;
8616
9190
  }
8617
- generalizePath(path6) {
8618
- const p = path6.toLowerCase();
9191
+ generalizePath(path7) {
9192
+ const p = path7.toLowerCase();
8619
9193
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
8620
9194
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
8621
9195
  }
@@ -9003,26 +9577,26 @@ function writeExportFiles(outDir, rules, skills) {
9003
9577
  byLayer.get(r.layer).push(r);
9004
9578
  }
9005
9579
  for (const layer of [...byLayer.keys()].sort((a, b) => a - b)) {
9006
- const path6 = join14(rulesDir2, `l${layer}_brain_rules.json`);
9007
- writeFileSync5(path6, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
9008
- written.push(path6);
9580
+ const path7 = join14(rulesDir2, `l${layer}_brain_rules.json`);
9581
+ writeFileSync5(path7, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
9582
+ written.push(path7);
9009
9583
  }
9010
9584
  if (rules.length === 0) {
9011
- const path6 = join14(rulesDir2, "empty.txt");
9012
- writeFileSync5(path6, "(no brain rules to contribute)", "utf-8");
9013
- written.push(path6);
9585
+ const path7 = join14(rulesDir2, "empty.txt");
9586
+ writeFileSync5(path7, "(no brain rules to contribute)", "utf-8");
9587
+ written.push(path7);
9014
9588
  }
9015
9589
  const skillsDir = join14(outDir, "skills");
9016
9590
  mkdirSync6(skillsDir, { recursive: true });
9017
9591
  for (const sk of skills) {
9018
- const path6 = join14(skillsDir, `${sk.name}.md`);
9019
- writeFileSync5(path6, sk.content || "", "utf-8");
9020
- written.push(path6);
9592
+ const path7 = join14(skillsDir, `${sk.name}.md`);
9593
+ writeFileSync5(path7, sk.content || "", "utf-8");
9594
+ written.push(path7);
9021
9595
  }
9022
9596
  if (skills.length === 0) {
9023
- const path6 = join14(skillsDir, "empty.txt");
9024
- writeFileSync5(path6, "(no brain skills to contribute)", "utf-8");
9025
- written.push(path6);
9597
+ const path7 = join14(skillsDir, "empty.txt");
9598
+ writeFileSync5(path7, "(no brain skills to contribute)", "utf-8");
9599
+ written.push(path7);
9026
9600
  }
9027
9601
  return written;
9028
9602
  }
@@ -9471,38 +10045,38 @@ function labelEvent(actionDetail) {
9471
10045
  }
9472
10046
  return hits;
9473
10047
  }
9474
- function evaluateLTL(formula, trace, pos) {
10048
+ function evaluateLTL(formula, trace2, pos) {
9475
10049
  const op = formula[0];
9476
10050
  switch (op) {
9477
10051
  case "ap":
9478
- return trace[pos].has(formula[1]);
10052
+ return trace2[pos].has(formula[1]);
9479
10053
  case "!":
9480
- return !evaluateLTL(formula[1], trace, pos);
10054
+ return !evaluateLTL(formula[1], trace2, pos);
9481
10055
  case "&":
9482
- return evaluateLTL(formula[1], trace, pos) && evaluateLTL(formula[2], trace, pos);
10056
+ return evaluateLTL(formula[1], trace2, pos) && evaluateLTL(formula[2], trace2, pos);
9483
10057
  case "|":
9484
- return evaluateLTL(formula[1], trace, pos) || evaluateLTL(formula[2], trace, pos);
10058
+ return evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
9485
10059
  case "->":
9486
- return !evaluateLTL(formula[1], trace, pos) || evaluateLTL(formula[2], trace, pos);
10060
+ return !evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
9487
10061
  case "X":
9488
- return pos + 1 < trace.length && evaluateLTL(formula[1], trace, pos + 1);
10062
+ return pos + 1 < trace2.length && evaluateLTL(formula[1], trace2, pos + 1);
9489
10063
  case "G": {
9490
- for (let j = pos; j < trace.length; j++) {
9491
- if (!evaluateLTL(formula[1], trace, j)) return false;
10064
+ for (let j = pos; j < trace2.length; j++) {
10065
+ if (!evaluateLTL(formula[1], trace2, j)) return false;
9492
10066
  }
9493
10067
  return true;
9494
10068
  }
9495
10069
  case "F": {
9496
- for (let j = pos; j < trace.length; j++) {
9497
- if (evaluateLTL(formula[1], trace, j)) return true;
10070
+ for (let j = pos; j < trace2.length; j++) {
10071
+ if (evaluateLTL(formula[1], trace2, j)) return true;
9498
10072
  }
9499
10073
  return false;
9500
10074
  }
9501
10075
  case "U": {
9502
- for (let j = pos; j < trace.length; j++) {
9503
- if (evaluateLTL(formula[2], trace, j)) {
10076
+ for (let j = pos; j < trace2.length; j++) {
10077
+ if (evaluateLTL(formula[2], trace2, j)) {
9504
10078
  for (let k = pos; k < j; k++) {
9505
- if (!evaluateLTL(formula[1], trace, k)) return false;
10079
+ if (!evaluateLTL(formula[1], trace2, k)) return false;
9506
10080
  }
9507
10081
  return true;
9508
10082
  }
@@ -9531,11 +10105,11 @@ function checkMCRules(graph) {
9531
10105
  const mc = loadMC();
9532
10106
  const rules = mc.rules || [];
9533
10107
  if (rules.length === 0) return violations;
9534
- const trace = nodes.map((n) => labelEvent(n.actionDetail));
10108
+ const trace2 = nodes.map((n) => labelEvent(n.actionDetail));
9535
10109
  const witnessMode = graph.witnessIdx !== void 0;
9536
10110
  for (const rule of rules) {
9537
10111
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
9538
- if (ruleViolates(rule, trace, witnessMode)) {
10112
+ if (ruleViolates(rule, trace2, witnessMode)) {
9539
10113
  violations.push({
9540
10114
  propertyId: String(rule.id || "mc-ltl"),
9541
10115
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
@@ -9726,12 +10300,12 @@ var init_builder = __esm({
9726
10300
  });
9727
10301
 
9728
10302
  // src/engine/formal-engine/properties.ts
9729
- function graphFromPath(nodes, path6, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10303
+ function graphFromPath(nodes, path7, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
9730
10304
  const byKey = /* @__PURE__ */ new Map();
9731
10305
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
9732
10306
  const gNodes = [];
9733
10307
  const gEdges = [];
9734
- for (const item of path6) {
10308
+ for (const item of path7) {
9735
10309
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
9736
10310
  gNodes.push({
9737
10311
  session_id: item.sessionId,
@@ -9797,22 +10371,22 @@ function checkCrossSessionChain(graph) {
9797
10371
  if (witness !== void 0) {
9798
10372
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
9799
10373
  let matched = 0;
9800
- const path6 = [];
10374
+ const path7 = [];
9801
10375
  for (let k = 0; k < witness; k++) {
9802
10376
  const n = nodes[k];
9803
10377
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
9804
10378
  matched += 1;
9805
- path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10379
+ path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9806
10380
  }
9807
10381
  }
9808
10382
  if (matched < stages.length - 1) continue;
9809
- path6.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
10383
+ path7.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
9810
10384
  violations.push({
9811
10385
  propertyId: "cross-" + chain.id,
9812
10386
  reason: chain.reason,
9813
10387
  riskLevel: chain.riskLevel,
9814
- path: path6,
9815
- graph: graphFromPath(nodes, path6, "next", {
10388
+ path: path7,
10389
+ graph: graphFromPath(nodes, path7, "next", {
9816
10390
  property_id: "cross-" + chain.id,
9817
10391
  property_short: "P1",
9818
10392
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -9822,11 +10396,11 @@ function checkCrossSessionChain(graph) {
9822
10396
  } else {
9823
10397
  let matched = 0;
9824
10398
  let stageIdx = 0;
9825
- const path6 = [];
10399
+ const path7 = [];
9826
10400
  for (const n of nodes) {
9827
10401
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
9828
10402
  matched += 1;
9829
- path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10403
+ path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9830
10404
  stageIdx += 1;
9831
10405
  if (matched >= stages.length) break;
9832
10406
  }
@@ -9836,8 +10410,8 @@ function checkCrossSessionChain(graph) {
9836
10410
  propertyId: "cross-" + chain.id,
9837
10411
  reason: chain.reason,
9838
10412
  riskLevel: chain.riskLevel,
9839
- path: path6,
9840
- graph: graphFromPath(nodes, path6, "next", {
10413
+ path: path7,
10414
+ graph: graphFromPath(nodes, path7, "next", {
9841
10415
  property_id: "cross-" + chain.id,
9842
10416
  property_short: "P1",
9843
10417
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -9884,7 +10458,7 @@ function checkSensitiveDataFlow(graph) {
9884
10458
  }
9885
10459
  }
9886
10460
  }
9887
- const tracePath = (idx) => {
10461
+ const tracePath2 = (idx) => {
9888
10462
  const chain = [idx];
9889
10463
  const seen = /* @__PURE__ */ new Set([idx]);
9890
10464
  while (true) {
@@ -9943,7 +10517,7 @@ function checkSensitiveDataFlow(graph) {
9943
10517
  for (const i of candidates) {
9944
10518
  const n = nodes[i];
9945
10519
  if (tainted.has(i) && EXFIL_RE.test(n.actionDetail)) {
9946
- const chain = tracePath(i);
10520
+ const chain = tracePath2(i);
9947
10521
  violations.push({
9948
10522
  propertyId: "sensitive-data-flow",
9949
10523
  reason: `\u654F\u611F\u6570\u636E\u4F20\u64AD\u5916\u4F20\uFF1A${tainted.get(i).source} \u2192 ${n.sessionId}#${n.seq} \u7ECF\u5171\u4EAB\u8F7D\u4F53\u5916\u53D1`,
@@ -10058,7 +10632,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10058
10632
  if (candidates.length > 0) {
10059
10633
  const pre = nodes[candidates[candidates.length - 1]];
10060
10634
  const post = nodes[firstEv];
10061
- const path6 = [
10635
+ const path7 = [
10062
10636
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10063
10637
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10064
10638
  ];
@@ -10066,8 +10640,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10066
10640
  propertyId: "no-exfil-after-privesc",
10067
10641
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
10068
10642
  riskLevel: "critical",
10069
- path: path6,
10070
- graph: graphFromPath(nodes, path6, "next", {
10643
+ path: path7,
10644
+ graph: graphFromPath(nodes, path7, "next", {
10071
10645
  property_id: "no-exfil-after-privesc",
10072
10646
  property_short: "P4",
10073
10647
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10084,7 +10658,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10084
10658
  for (let j = i + 1; j < nodes.length; j++) {
10085
10659
  if (!isExfilNode(nodes[j])) continue;
10086
10660
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
10087
- const path6 = [
10661
+ const path7 = [
10088
10662
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10089
10663
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10090
10664
  ];
@@ -10092,8 +10666,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10092
10666
  propertyId: "no-exfil-after-privesc",
10093
10667
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
10094
10668
  riskLevel: "critical",
10095
- path: path6,
10096
- graph: graphFromPath(nodes, path6, "next", {
10669
+ path: path7,
10670
+ graph: graphFromPath(nodes, path7, "next", {
10097
10671
  property_id: "no-exfil-after-privesc",
10098
10672
  property_short: "P4",
10099
10673
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10125,7 +10699,7 @@ function checkNeverExfilAfterCred(graph) {
10125
10699
  }
10126
10700
  if (pre) {
10127
10701
  const post = nodes[firstEv];
10128
- const path6 = [
10702
+ const path7 = [
10129
10703
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10130
10704
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10131
10705
  ];
@@ -10133,8 +10707,8 @@ function checkNeverExfilAfterCred(graph) {
10133
10707
  propertyId: "no-exfil-after-credential",
10134
10708
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10135
10709
  riskLevel: "critical",
10136
- path: path6,
10137
- graph: graphFromPath(nodes, path6, "data", {
10710
+ path: path7,
10711
+ graph: graphFromPath(nodes, path7, "data", {
10138
10712
  property_id: "no-exfil-after-credential",
10139
10713
  property_short: "P5",
10140
10714
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10150,7 +10724,7 @@ function checkNeverExfilAfterCred(graph) {
10150
10724
  if (!isCredNode(nodes[i])) continue;
10151
10725
  for (let j = i + 1; j < nodes.length; j++) {
10152
10726
  if (isExfilNode(nodes[j])) {
10153
- const path6 = [
10727
+ const path7 = [
10154
10728
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10155
10729
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10156
10730
  ];
@@ -10158,8 +10732,8 @@ function checkNeverExfilAfterCred(graph) {
10158
10732
  propertyId: "no-exfil-after-credential",
10159
10733
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10160
10734
  riskLevel: "critical",
10161
- path: path6,
10162
- graph: graphFromPath(nodes, path6, "data", {
10735
+ path: path7,
10736
+ graph: graphFromPath(nodes, path7, "data", {
10163
10737
  property_id: "no-exfil-after-credential",
10164
10738
  property_short: "P5",
10165
10739
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10318,13 +10892,13 @@ function checkSensitiveDataAggregation(graph) {
10318
10892
  if (!isExfilNode(n)) continue;
10319
10893
  const srcs = sourcesFor(i);
10320
10894
  if (srcs.size >= 2) {
10321
- const path6 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10895
+ const path7 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10322
10896
  violations.push({
10323
10897
  propertyId: "sensitive-data-aggregation",
10324
10898
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
10325
10899
  riskLevel: "critical",
10326
- path: path6,
10327
- graph: graphFromPath(nodes, path6, "next", {
10900
+ path: path7,
10901
+ graph: graphFromPath(nodes, path7, "next", {
10328
10902
  property_id: "sensitive-data-aggregation",
10329
10903
  property_short: "P8",
10330
10904
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -10783,11 +11357,11 @@ var init_stateful = __esm({
10783
11357
  }
10784
11358
  }
10785
11359
  chainPath(stages) {
10786
- const path6 = [];
11360
+ const path7 = [];
10787
11361
  let want = stages[0];
10788
11362
  for (const n of this.nodes_) {
10789
11363
  if (n.stage === want) {
10790
- path6.push({
11364
+ path7.push({
10791
11365
  sessionId: n.sessionId,
10792
11366
  seq: n.seq,
10793
11367
  stage: n.stage,
@@ -10803,12 +11377,12 @@ var init_stateful = __esm({
10803
11377
  }
10804
11378
  }
10805
11379
  }
10806
- return path6;
11380
+ return path7;
10807
11381
  }
10808
11382
  /** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
10809
11383
  buildChainGraph(stages, chainId) {
10810
- const path6 = this.chainPath(stages);
10811
- const gNodes = path6.map((p, i) => {
11384
+ const path7 = this.chainPath(stages);
11385
+ const gNodes = path7.map((p, i) => {
10812
11386
  const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
10813
11387
  return {
10814
11388
  session_id: p.sessionId,
@@ -11059,16 +11633,42 @@ var init_stateful = __esm({
11059
11633
  });
11060
11634
 
11061
11635
  // src/engine/formal-engine/chain_state.ts
11062
- import * as fs4 from "fs";
11636
+ import * as fs5 from "fs";
11063
11637
  import * as os2 from "os";
11064
- import * as path4 from "path";
11638
+ import * as path5 from "path";
11065
11639
  import { createHash as createHash4 } from "crypto";
11066
11640
  function defaultStateDbPath() {
11067
- const dir = process.env.AGENT_MOSS_STATE_DIR || path4.join(os2.homedir(), ".agentmoss");
11641
+ const dir = process.env.AGENT_MOSS_STATE_DIR || path5.join(os2.homedir(), ".agentmoss");
11068
11642
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
11069
- return path4.join(dir, `stateful_chains_${tag}.json`);
11643
+ return path5.join(dir, `stateful_chains_${tag}.json`);
11070
11644
  }
11071
- var ChainStateStore;
11645
+ function registerExitFlush(store) {
11646
+ if (_exitHookRegistered) return;
11647
+ _exitHookRegistered = true;
11648
+ const flush = () => {
11649
+ try {
11650
+ store.flush();
11651
+ } catch {
11652
+ }
11653
+ };
11654
+ process.once("exit", flush);
11655
+ process.once("SIGINT", () => {
11656
+ flush();
11657
+ process.exit(0);
11658
+ });
11659
+ process.once("SIGTERM", () => {
11660
+ flush();
11661
+ process.exit(0);
11662
+ });
11663
+ }
11664
+ function getChainStateStore(filePath = "") {
11665
+ if (_store === null || filePath && filePath !== _store["filePath"]) {
11666
+ _store = new ChainStateStore(filePath);
11667
+ registerExitFlush(_store);
11668
+ }
11669
+ return _store;
11670
+ }
11671
+ var ChainStateStore, _store, _exitHookRegistered;
11072
11672
  var init_chain_state = __esm({
11073
11673
  "src/engine/formal-engine/chain_state.ts"() {
11074
11674
  "use strict";
@@ -11079,15 +11679,40 @@ var init_chain_state = __esm({
11079
11679
  filePath;
11080
11680
  data;
11081
11681
  _timer = null;
11082
- _flushDelayMs = 50;
11682
+ /**
11683
+ * 落盘防抖间隔。**与 Python 端对齐为 1 秒**(2026-11 长稳实测)。
11684
+ *
11685
+ * 原来是 50ms:Node 是单线程,`_syncDirtyToData` 里的 `toSnapshot()` 是
11686
+ * O(节点数) 的全量构建(2 万节点约 40ms),50ms 触发一次等于 80% 的时间
11687
+ * 在序列化,请求全被卡住。1 秒一次把开销摊薄 20 倍;崩溃最坏丢 1 秒增量,
11688
+ * 与 Python 端同一量级。
11689
+ */
11690
+ _flushDelayMs = 1e3;
11691
+ /**
11692
+ * 内存中的 tracker(唯一事实源)。2026-11 与 Python 端对齐:
11693
+ * 旧实现每次 applyAction 都 `restore(entry.state)` 重建所有节点 +
11694
+ * `toSnapshot()` 全量序列化,O(节点数);长时间运行后每次调用几十到几百毫秒,
11695
+ * 在 Node 单线程上等于把事件循环卡死。现在 apply 只改内存对象,序列化推迟到
11696
+ * 防抖落盘时批量做。
11697
+ */
11698
+ _trackers = /* @__PURE__ */ new Map();
11699
+ /** 自上次落盘以来变过的 agentId */
11700
+ _dirty = /* @__PURE__ */ new Set();
11701
+ /**
11702
+ * 多进程模式(2026-11,对齐 Python `enable_multi_process`):
11703
+ * AGENT_MOSS_MULTI_PROCESS=1 时启用。Node cluster / PM2 多进程部署下,
11704
+ * 各进程的 `data` 是独立快照,防抖写会互相覆盖(JSON 文件没有 SQLite 那样的锁)。
11705
+ * 启用后:每次 applyAction 用**文件锁**串行化,锁内重新读文件 → 判定 → 立即写。
11706
+ */
11707
+ _multiProcess = false;
11083
11708
  constructor(filePath = "") {
11084
11709
  this.filePath = filePath || defaultStateDbPath();
11085
11710
  this.data = this._read();
11086
11711
  }
11087
11712
  _read() {
11088
11713
  try {
11089
- if (fs4.existsSync(this.filePath)) {
11090
- const raw = fs4.readFileSync(this.filePath, "utf-8");
11714
+ if (fs5.existsSync(this.filePath)) {
11715
+ const raw = fs5.readFileSync(this.filePath, "utf-8");
11091
11716
  return JSON.parse(raw);
11092
11717
  }
11093
11718
  } catch {
@@ -11100,12 +11725,22 @@ var init_chain_state = __esm({
11100
11725
  this._timer = setTimeout(() => {
11101
11726
  this._timer = null;
11102
11727
  try {
11103
- ensurePrivateDir(path4.dirname(this.filePath));
11728
+ this._syncDirtyToData();
11729
+ ensurePrivateDir(path5.dirname(this.filePath));
11104
11730
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11105
11731
  } catch {
11106
11732
  }
11107
11733
  }, this._flushDelayMs);
11108
11734
  }
11735
+ /** 把 dirty 的 tracker 序列化进 data(只在落盘时做,避免每次 apply 都 O(n))。 */
11736
+ _syncDirtyToData() {
11737
+ for (const agentId of this._dirty) {
11738
+ const t = this._trackers.get(agentId);
11739
+ if (!t) continue;
11740
+ this.data[agentId] = { state: t.toSnapshot(), updated_at: (/* @__PURE__ */ new Date()).toISOString() };
11741
+ }
11742
+ this._dirty.clear();
11743
+ }
11109
11744
  /** 立即落盘(测试/关停前调用,保证状态不丢)。 */
11110
11745
  flush() {
11111
11746
  if (this._timer !== null) {
@@ -11113,30 +11748,100 @@ var init_chain_state = __esm({
11113
11748
  this._timer = null;
11114
11749
  }
11115
11750
  try {
11116
- ensurePrivateDir(path4.dirname(this.filePath));
11751
+ this._syncDirtyToData();
11752
+ ensurePrivateDir(path5.dirname(this.filePath));
11117
11753
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11118
11754
  } catch {
11119
11755
  }
11120
11756
  }
11121
11757
  load(agentId) {
11758
+ const cached2 = this._trackers.get(agentId);
11759
+ if (cached2) return cached2;
11122
11760
  const entry = this.data[agentId];
11123
11761
  if (!entry) return null;
11124
11762
  const t = new StatefulChainTracker(agentId);
11125
11763
  t.restore(entry.state);
11764
+ this._trackers.set(agentId, t);
11126
11765
  return t;
11127
11766
  }
11128
11767
  save(tracker) {
11129
- this.data[tracker.agentId] = {
11130
- state: tracker.toSnapshot(),
11131
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
11132
- };
11768
+ this._trackers.set(tracker.agentId, tracker);
11769
+ this._dirty.add(tracker.agentId);
11133
11770
  this._scheduleWrite();
11134
11771
  }
11135
11772
  delete(agentId) {
11773
+ this._trackers.delete(agentId);
11774
+ this._dirty.delete(agentId);
11136
11775
  delete this.data[agentId];
11137
11776
  this._scheduleWrite();
11138
11777
  }
11778
+ /** 启用多进程模式(对齐 Python)。 */
11779
+ enableMultiProcess() {
11780
+ this._multiProcess = true;
11781
+ }
11782
+ /**
11783
+ * 同步文件锁(原子创建 `<file>.lock`)。
11784
+ *
11785
+ * Node 是单线程,锁竞争时用 Atomics.wait 做**同步睡眠**而不是忙等 ——
11786
+ * 忙等会把事件循环完全占死,其它请求也没法推进。
11787
+ */
11788
+ _withFileLock(fn) {
11789
+ const lockPath = `${this.filePath}.lock`;
11790
+ const sleepBuf = new Int32Array(new SharedArrayBuffer(4));
11791
+ for (let attempt = 0; attempt < 100; attempt++) {
11792
+ try {
11793
+ const fd = fs5.openSync(lockPath, "wx");
11794
+ try {
11795
+ return fn();
11796
+ } finally {
11797
+ try {
11798
+ fs5.closeSync(fd);
11799
+ } catch {
11800
+ }
11801
+ try {
11802
+ fs5.unlinkSync(lockPath);
11803
+ } catch {
11804
+ }
11805
+ }
11806
+ } catch (e) {
11807
+ if (e?.code !== "EEXIST") throw e;
11808
+ try {
11809
+ Atomics.wait(sleepBuf, 0, 0, 20);
11810
+ } catch {
11811
+ }
11812
+ }
11813
+ }
11814
+ throw new Error(`chain state lock timeout: ${lockPath}`);
11815
+ }
11816
+ /** 立即把内存写进文件(多进程模式用,不走防抖)。 */
11817
+ _flushNow() {
11818
+ this._syncDirtyToData();
11819
+ try {
11820
+ const _dirOk = ensurePrivateDir(path5.dirname(this.filePath));
11821
+ const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11822
+ if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
11823
+ } catch (e) {
11824
+ console.error("[AgentMoss] chain state flush failed:", e?.message || e);
11825
+ }
11826
+ }
11827
+ /** 当前内存中的 tracker 数 / 节点总数(健康检查用)。 */
11828
+ stats() {
11829
+ let nodes = 0;
11830
+ for (const t of this._trackers.values()) nodes += t.nodes.length;
11831
+ return { agents: this._trackers.size, nodes };
11832
+ }
11139
11833
  applyAction(agentId, aNext, sessionId, isError = false, sourceAgent = "", instanceId = "") {
11834
+ if (this._multiProcess) {
11835
+ return this._withFileLock(() => {
11836
+ this.data = this._read();
11837
+ this._trackers.clear();
11838
+ const t2 = this.load(agentId) || new StatefulChainTracker(agentId);
11839
+ const r2 = t2.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
11840
+ this.save(t2);
11841
+ this._flushNow();
11842
+ return r2;
11843
+ });
11844
+ }
11140
11845
  const t = this.load(agentId) || new StatefulChainTracker(agentId);
11141
11846
  const r = t.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
11142
11847
  this.save(t);
@@ -11150,6 +11855,8 @@ var init_chain_state = __esm({
11150
11855
  return r;
11151
11856
  }
11152
11857
  };
11858
+ _store = null;
11859
+ _exitHookRegistered = false;
11153
11860
  }
11154
11861
  });
11155
11862
 
@@ -11257,6 +11964,14 @@ function _resetBrainForTest() {
11257
11964
  async function runAnalysis(input) {
11258
11965
  const observedFormalLayers = [];
11259
11966
  const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
11967
+ if (heuristicResult) {
11968
+ traceSummary("l1.result", {
11969
+ hit: !heuristicResult.allowed,
11970
+ risk_level: heuristicResult.riskLevel,
11971
+ risk_type: heuristicResult.riskType,
11972
+ reason: heuristicResult.reason
11973
+ });
11974
+ }
11260
11975
  const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
11261
11976
  const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
11262
11977
  if (heuristicResult && !heuristicResult.allowed) {
@@ -11400,6 +12115,14 @@ async function runAnalysis(input) {
11400
12115
  }
11401
12116
  }
11402
12117
  const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
12118
+ if (logicResult) {
12119
+ traceSummary("l2.result", {
12120
+ hit: !logicResult.allowed,
12121
+ risk_level: logicResult.riskLevel,
12122
+ risk_type: logicResult.riskType,
12123
+ reason: logicResult.reason
12124
+ });
12125
+ }
11403
12126
  const l1FileAccessHit = !!(heuristicResult && !heuristicResult.allowed && heuristicResult.riskType === "file_access");
11404
12127
  const effectiveResult = logicResult && !logicResult.allowed ? logicResult : l1FileAccessHit ? heuristicResult : null;
11405
12128
  if (effectiveResult) {
@@ -11629,6 +12352,7 @@ var init_coordinator = __esm({
11629
12352
  init_llm_analyzer();
11630
12353
  init_script_content_analyzer();
11631
12354
  init_config();
12355
+ init_trace_log();
11632
12356
  init_runtime_config();
11633
12357
  init_agents();
11634
12358
  init_scenarios();
@@ -11653,7 +12377,7 @@ var init_coordinator = __esm({
11653
12377
 
11654
12378
  // src/infra/policy-cache.ts
11655
12379
  import { createHash as createHash5 } from "crypto";
11656
- import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync3 } from "fs";
12380
+ import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
11657
12381
  import { tmpdir as tmpdir3 } from "os";
11658
12382
  import { join as join16 } from "path";
11659
12383
  function cacheDir() {
@@ -11747,7 +12471,7 @@ var init_policy_cache = __esm({
11747
12471
  invalidate(sessionId, promptSession) {
11748
12472
  this.memory.delete(this.cacheKey(sessionId, promptSession));
11749
12473
  try {
11750
- unlinkSync3(this.cacheFilePath(sessionId, promptSession));
12474
+ unlinkSync4(this.cacheFilePath(sessionId, promptSession));
11751
12475
  } catch {
11752
12476
  }
11753
12477
  }
@@ -11761,7 +12485,7 @@ var init_policy_cache = __esm({
11761
12485
  if (existsSync17(dir)) {
11762
12486
  for (const f of readdirSync5(dir)) {
11763
12487
  try {
11764
- unlinkSync3(join16(dir, f));
12488
+ unlinkSync4(join16(dir, f));
11765
12489
  } catch {
11766
12490
  }
11767
12491
  }
@@ -11777,7 +12501,7 @@ var init_policy_cache = __esm({
11777
12501
  for (const sessionDir of readdirSync5(cacheDir())) {
11778
12502
  const dir = join16(cacheDir(), sessionDir);
11779
12503
  try {
11780
- for (const f of readdirSync5(dir)) unlinkSync3(join16(dir, f));
12504
+ for (const f of readdirSync5(dir)) unlinkSync4(join16(dir, f));
11781
12505
  rmdirSync(dir);
11782
12506
  } catch {
11783
12507
  }
@@ -12153,7 +12877,7 @@ var init_esm_require = __esm({
12153
12877
  });
12154
12878
 
12155
12879
  // src/actrail.ts
12156
- import * as fs5 from "fs";
12880
+ import * as fs6 from "fs";
12157
12881
  function escape(value) {
12158
12882
  return value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/=/g, "\\e");
12159
12883
  }
@@ -12174,7 +12898,7 @@ function getStoragePath() {
12174
12898
  function reportEnforcementEvent(opts) {
12175
12899
  if (!isEnabled()) return false;
12176
12900
  const storagePath = getStoragePath();
12177
- if (!fs5.existsSync(storagePath)) return false;
12901
+ if (!fs6.existsSync(storagePath)) return false;
12178
12902
  try {
12179
12903
  let Database;
12180
12904
  try {
@@ -12345,9 +13069,9 @@ var init_pattern_miner = __esm({
12345
13069
  });
12346
13070
 
12347
13071
  // src/agent-gate-reader.ts
12348
- import * as fs6 from "fs";
13072
+ import * as fs7 from "fs";
12349
13073
  import * as os3 from "os";
12350
- import * as path5 from "path";
13074
+ import * as path6 from "path";
12351
13075
  function normalizeAction(row) {
12352
13076
  return {
12353
13077
  actionType: String(row.action_type || row.tool_name || row.name || ""),
@@ -12357,10 +13081,10 @@ function normalizeAction(row) {
12357
13081
  function readJsonDir(dirPath, limit = 1e5) {
12358
13082
  const sessions = /* @__PURE__ */ new Map();
12359
13083
  try {
12360
- const files = fs6.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
13084
+ const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
12361
13085
  for (const f of files.slice(-200)) {
12362
13086
  const sid = f.replace(/\.json$/, "");
12363
- const raw = fs6.readFileSync(path5.join(dirPath, f), "utf-8");
13087
+ const raw = fs7.readFileSync(path6.join(dirPath, f), "utf-8");
12364
13088
  const arr = JSON.parse(raw);
12365
13089
  if (!Array.isArray(arr)) continue;
12366
13090
  for (const item of arr) {
@@ -12417,7 +13141,7 @@ function readSqlite(dbPath, limit = 1e5) {
12417
13141
  function loadAgentGateSessions(dbPath = "") {
12418
13142
  if (dbPath) {
12419
13143
  try {
12420
- if (fs6.statSync(dbPath).isDirectory()) {
13144
+ if (fs7.statSync(dbPath).isDirectory()) {
12421
13145
  return readJsonDir(dbPath);
12422
13146
  }
12423
13147
  } catch {
@@ -12428,7 +13152,7 @@ function loadAgentGateSessions(dbPath = "") {
12428
13152
  }
12429
13153
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
12430
13154
  if (sql.length > 0) return sql;
12431
- const jsonDefault = path5.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
13155
+ const jsonDefault = path6.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
12432
13156
  return readJsonDir(jsonDefault);
12433
13157
  }
12434
13158
  var DEFAULT_AGENTGATE_SQLITE;
@@ -12437,7 +13161,7 @@ var init_agent_gate_reader = __esm({
12437
13161
  "use strict";
12438
13162
  init_esm_shims();
12439
13163
  init_esm_require();
12440
- DEFAULT_AGENTGATE_SQLITE = path5.join(
13164
+ DEFAULT_AGENTGATE_SQLITE = path6.join(
12441
13165
  os3.homedir(),
12442
13166
  ".local",
12443
13167
  "share",
@@ -12519,17 +13243,114 @@ var init_observable = __esm({
12519
13243
  }
12520
13244
  });
12521
13245
 
13246
+ // src/infra/loop-monitor.ts
13247
+ import { monitorEventLoopDelay } from "perf_hooks";
13248
+ function startLoopMonitor() {
13249
+ if (_histogram !== null) return;
13250
+ _histogram = monitorEventLoopDelay({ resolution: 20 });
13251
+ _histogram.enable();
13252
+ _timer = setInterval(() => {
13253
+ try {
13254
+ _histogram?.reset();
13255
+ } catch {
13256
+ }
13257
+ }, 1e3);
13258
+ if (typeof _timer.unref === "function") _timer.unref();
13259
+ }
13260
+ function loopMonitorSnapshot() {
13261
+ if (_histogram === null) return {};
13262
+ try {
13263
+ const meanMs = _histogram.mean / 1e6;
13264
+ const maxMs = _histogram.max / 1e6;
13265
+ return {
13266
+ loop_lag_ms: Math.round(meanMs * 10) / 10,
13267
+ loop_lag_max_ms: Math.round(maxMs * 10) / 10
13268
+ };
13269
+ } catch {
13270
+ return {};
13271
+ }
13272
+ }
13273
+ var _histogram, _timer;
13274
+ var init_loop_monitor = __esm({
13275
+ "src/infra/loop-monitor.ts"() {
13276
+ "use strict";
13277
+ init_esm_shims();
13278
+ _histogram = null;
13279
+ _timer = null;
13280
+ }
13281
+ });
13282
+
13283
+ // src/infra/runtime-stats.ts
13284
+ function registerPools(pools) {
13285
+ _pools = pools;
13286
+ }
13287
+ function poolsSnapshot() {
13288
+ try {
13289
+ return _pools ? _pools.snapshot() : {};
13290
+ } catch {
13291
+ return {};
13292
+ }
13293
+ }
13294
+ var _pools;
13295
+ var init_runtime_stats = __esm({
13296
+ "src/infra/runtime-stats.ts"() {
13297
+ "use strict";
13298
+ init_esm_shims();
13299
+ _pools = null;
13300
+ }
13301
+ });
13302
+
12522
13303
  // src/routes.ts
12523
13304
  import { randomBytes as randomBytes2 } from "crypto";
12524
13305
  import { join as join19, dirname as dirname12 } from "path";
12525
13306
  import { fileURLToPath as fileURLToPath10 } from "url";
12526
13307
  async function healthRoute(c) {
13308
+ const metrics = {};
13309
+ try {
13310
+ Object.assign(metrics, loopMonitorSnapshot());
13311
+ } catch {
13312
+ }
13313
+ metrics.pools = poolsSnapshot();
13314
+ try {
13315
+ const chainStats = getChainStateStoreFor("").stats();
13316
+ metrics.chain_agents = chainStats.agents;
13317
+ metrics.chain_nodes = chainStats.nodes;
13318
+ metrics.chain_capacity = MAX_NODES;
13319
+ metrics.chain_usage_pct = Math.round(chainStats.nodes / MAX_NODES * 1e3) / 10;
13320
+ } catch {
13321
+ }
13322
+ const degraded = [];
13323
+ const pct = metrics.chain_usage_pct;
13324
+ if (typeof pct === "number") {
13325
+ if (pct >= 100) {
13326
+ degraded.push(
13327
+ `\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`
13328
+ );
13329
+ } else if (pct >= 90) {
13330
+ degraded.push(
13331
+ `\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`
13332
+ );
13333
+ }
13334
+ }
13335
+ try {
13336
+ const snap = getBreaker().snapshot();
13337
+ if (snap.state === "open") {
13338
+ degraded.push(
13339
+ `\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`
13340
+ );
13341
+ }
13342
+ } catch {
13343
+ }
12527
13344
  return c.json(HealthResponseSchema.parse({
12528
- instance: process.env.AGENT_MOSS_INSTANCE || ""
13345
+ status: degraded.length ? "degraded" : "healthy",
13346
+ degraded,
13347
+ instance: process.env.AGENT_MOSS_INSTANCE || "",
13348
+ metrics
12529
13349
  }));
12530
13350
  }
12531
13351
  async function analyzeRoute(c) {
12532
13352
  const t0 = performance.now();
13353
+ const degradedNotes = [];
12533
13354
  try {
12534
13355
  const body = await c.req.json();
12535
13356
  const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
@@ -12557,6 +13378,20 @@ async function analyzeRoute(c) {
12557
13378
  const instanceId = String(
12558
13379
  req.instance_id || req.metadata?.instance_id || ""
12559
13380
  );
13381
+ traceFull("request", {
13382
+ session_id: req.session_id,
13383
+ agent_id: agentId,
13384
+ os_type: osType,
13385
+ cwd: req.cwd,
13386
+ action_type: req.a_next.action_type,
13387
+ action_detail: req.a_next.action_detail,
13388
+ reason: req.reason,
13389
+ prompt_session: req.prompt_session,
13390
+ action_history: req.action_history,
13391
+ prompt_history: req.prompt_history,
13392
+ session_history: req.session_history,
13393
+ metadata: req.metadata
13394
+ });
12560
13395
  const result = await analyze({
12561
13396
  sessionId: req.session_id,
12562
13397
  promptSession: req.prompt_session,
@@ -12616,6 +13451,29 @@ async function analyzeRoute(c) {
12616
13451
  llmLogPath: req.metadata?.llm_log_path
12617
13452
  });
12618
13453
  const durationMs = performance.now() - t0;
13454
+ const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
13455
+ if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
13456
+ console.warn(
13457
+ `[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}`
13458
+ );
13459
+ }
13460
+ try {
13461
+ ANALYZE_TOTAL.inc(1, { decision: result.decision, risk_level: result.risk_level });
13462
+ ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
13463
+ for (const layer of result.violated_layers || []) {
13464
+ LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
13465
+ }
13466
+ } catch {
13467
+ }
13468
+ traceSummary("result", {
13469
+ session_id: req.session_id,
13470
+ decision: result.decision,
13471
+ risk_level: result.risk_level,
13472
+ risk_type: result.risk_type,
13473
+ reason: result.reason,
13474
+ violated_layers: result.violated_layers,
13475
+ duration_ms: Math.round(durationMs * 10) / 10
13476
+ });
12619
13477
  try {
12620
13478
  reportEnforcementEvent({
12621
13479
  traceId: req.session_id,
@@ -12647,6 +13505,20 @@ async function analyzeRoute(c) {
12647
13505
  // 来源:真实 agent(桶 key 可能是 __system__)
12648
13506
  instanceId
12649
13507
  );
13508
+ try {
13509
+ const total = store.stats().nodes;
13510
+ const pct = Math.round(total / MAX_NODES * 1e3) / 10;
13511
+ if (total >= MAX_NODES) {
13512
+ degradedNotes.push(
13513
+ `\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`
13514
+ );
13515
+ } else if (pct >= 90) {
13516
+ degradedNotes.push(
13517
+ `\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`
13518
+ );
13519
+ }
13520
+ } catch {
13521
+ }
12650
13522
  const judgment = incMatchedToDeny(inc);
12651
13523
  if (judgment) {
12652
13524
  const layers = [...result.violated_layers];
@@ -12689,7 +13561,9 @@ async function analyzeRoute(c) {
12689
13561
  confidence: result.confidence,
12690
13562
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
12691
13563
  violation_chain: result.violation_chain ?? [],
12692
- violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id)
13564
+ violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
13565
+ // 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
13566
+ degraded: degradedNotes
12693
13567
  })
12694
13568
  );
12695
13569
  } catch (err) {
@@ -12709,8 +13583,7 @@ async function analyzeRoute(c) {
12709
13583
  }
12710
13584
  }
12711
13585
  function getChainStateStoreFor(_agentId) {
12712
- if (!reviewStore) reviewStore = new ChainStateStore();
12713
- return reviewStore;
13586
+ return getChainStateStore();
12714
13587
  }
12715
13588
  function incMatchedToDeny(inc) {
12716
13589
  if (inc.matched) {
@@ -12919,7 +13792,7 @@ async function brainImportRoute(c) {
12919
13792
  })));
12920
13793
  return c.json({ imported: rules.length });
12921
13794
  }
12922
- var __dirname9, reviewStore;
13795
+ var __dirname9;
12923
13796
  var init_routes = __esm({
12924
13797
  "src/routes.ts"() {
12925
13798
  "use strict";
@@ -12929,21 +13802,25 @@ var init_routes = __esm({
12929
13802
  init_analyzer();
12930
13803
  init_actrail();
12931
13804
  init_formal_engine();
13805
+ init_circuit_breaker();
12932
13806
  init_pattern_miner();
12933
13807
  init_agent_gate_reader();
12934
13808
  init_observable();
12935
13809
  init_rule_store();
12936
13810
  init_skill_manager();
12937
13811
  init_asset_dir();
13812
+ init_trace_log();
13813
+ init_loop_monitor();
13814
+ init_runtime_stats();
13815
+ init_metrics();
12938
13816
  __dirname9 = dirname12(fileURLToPath10(import.meta.url));
12939
- reviewStore = null;
12940
13817
  }
12941
13818
  });
12942
13819
 
12943
13820
  // src/console/router.ts
12944
13821
  import { Hono } from "hono";
12945
13822
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
12946
- import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync4 } from "fs";
13823
+ import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
12947
13824
  import { join as join20, dirname as dirname13 } from "path";
12948
13825
  import { fileURLToPath as fileURLToPath11 } from "url";
12949
13826
  function getConsoleToken() {
@@ -13288,7 +14165,7 @@ function createConsoleRouter() {
13288
14165
  const defaults = generateSourceDefaults();
13289
14166
  try {
13290
14167
  const p = getRuntimeConfigPath();
13291
- if (existsSync20(p)) unlinkSync4(p);
14168
+ if (existsSync20(p)) unlinkSync5(p);
13292
14169
  } catch {
13293
14170
  }
13294
14171
  return c.json(withL22View(defaults));
@@ -13419,6 +14296,13 @@ function logDeploymentSelfCheck() {
13419
14296
  }
13420
14297
  }
13421
14298
  function createApp() {
14299
+ try {
14300
+ if (String(process.env.AGENT_MOSS_MULTI_PROCESS || "").toLowerCase() in { "1": 1, "true": 1, "yes": 1, "on": 1 }) {
14301
+ getChainStateStore().enableMultiProcess();
14302
+ console.log("[AgentMoss] \u94FE\u72B6\u6001\u591A\u8FDB\u7A0B\u6A21\u5F0F\uFF1A\u5DF2\u542F\u7528\uFF08\u6587\u4EF6\u9501 + \u7ACB\u5373\u843D\u76D8\uFF09");
14303
+ }
14304
+ } catch {
14305
+ }
13422
14306
  enforceRulesContract();
13423
14307
  hardenExistingPaths();
13424
14308
  const app = new Hono2();
@@ -13434,9 +14318,11 @@ function createApp() {
13434
14318
  )
13435
14319
  );
13436
14320
  const pools = new PooledLimiter();
14321
+ registerPools(pools);
14322
+ startLoopMonitor();
13437
14323
  const limiter = new RateLimiter(rateLimitQps());
13438
14324
  app.use("*", async (c, next) => {
13439
- const path6 = new URL(c.req.url).pathname;
14325
+ const path7 = new URL(c.req.url).pathname;
13440
14326
  const method = c.req.method.toUpperCase();
13441
14327
  if (method === "OPTIONS") return next();
13442
14328
  const maxBody = maxBodyBytes();
@@ -13450,16 +14336,16 @@ function createApp() {
13450
14336
  if (originCheckEnabled()) {
13451
14337
  const origin = c.req.header("origin") || "";
13452
14338
  if (origin && !originAllowed(origin, c.req.header("host") || "")) {
13453
- console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path6}`);
14339
+ console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path7}`);
13454
14340
  return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
13455
14341
  }
13456
14342
  }
13457
- const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path6);
13458
- const isPublicPage = !path6.startsWith("/console/api") && (path6 === "/console" || path6.startsWith("/console/"));
14343
+ const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path7);
14344
+ const isPublicPage = !path7.startsWith("/console/api") && (path7 === "/console" || path7.startsWith("/console/"));
13459
14345
  if (!okAuth && !isPublicPage) {
13460
14346
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
13461
14347
  }
13462
- if (limiter.enabled && path6.startsWith("/api/")) {
14348
+ if (limiter.enabled && path7.startsWith("/api/")) {
13463
14349
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
13464
14350
  if (!limiter.allow(key)) {
13465
14351
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
@@ -13493,7 +14379,7 @@ function createApp() {
13493
14379
  return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
13494
14380
  }
13495
14381
  }
13496
- const pool = poolOf(path6);
14382
+ const pool = poolOf(path7);
13497
14383
  if (!take(`pool:${pool}`, poolLimit(pool))) {
13498
14384
  const qkey = principal ? "p:" + principalHash(principal) : "c:local";
13499
14385
  const [qn, abusive] = noteQueueReject(qkey);
@@ -13510,6 +14396,23 @@ function createApp() {
13510
14396
  while (keys.length) pools.release(keys.pop());
13511
14397
  }
13512
14398
  });
14399
+ app.get("/metrics", (c) => {
14400
+ let chainNodes;
14401
+ try {
14402
+ chainNodes = getChainStateStore().stats().nodes;
14403
+ } catch {
14404
+ }
14405
+ const lag = loopMonitorSnapshot();
14406
+ refreshRuntimeGauges({
14407
+ pools: pools.snapshot(),
14408
+ chainNodes,
14409
+ loopLagMs: lag.loop_lag_ms,
14410
+ loopLagMaxMs: lag.loop_lag_max_ms
14411
+ });
14412
+ return c.text(renderPrometheus(), 200, {
14413
+ "Content-Type": "text/plain; version=0.0.4; charset=utf-8"
14414
+ });
14415
+ });
13513
14416
  app.get("/api/v1/health", healthRoute);
13514
14417
  app.post("/api/v1/analyze", analyzeRoute);
13515
14418
  app.post("/api/v1/review", reviewRoute);
@@ -13602,7 +14505,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
13602
14505
  },
13603
14506
  serve: async () => {
13604
14507
  failFastOnAuthError();
13605
- const { mkdirSync: mkdirSync10, existsSync: existsSync23, unlinkSync: unlinkSync5 } = await import("fs");
14508
+ const { mkdirSync: mkdirSync10, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
13606
14509
  const { dirname: dirname15 } = await import("path");
13607
14510
  const dir = dirname15(socketPath);
13608
14511
  if (dir) {
@@ -13629,7 +14532,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
13629
14532
  );
13630
14533
  } else {
13631
14534
  try {
13632
- unlinkSync5(socketPath);
14535
+ unlinkSync6(socketPath);
13633
14536
  console.log(`[AgentMoss] \u6E05\u7406\u6B8B\u7559 socket \u6587\u4EF6: ${socketPath}`);
13634
14537
  } catch {
13635
14538
  }
@@ -13670,6 +14573,10 @@ var init_server = __esm({
13670
14573
  init_routes();
13671
14574
  init_console();
13672
14575
  init_runtime_config();
14576
+ init_runtime_stats();
14577
+ init_loop_monitor();
14578
+ init_metrics();
14579
+ init_formal_engine();
13673
14580
  init_rules_mode();
13674
14581
  init_rules_loader();
13675
14582
  PooledLimiter = class {
@@ -13686,6 +14593,10 @@ var init_server = __esm({
13686
14593
  if (cur <= 1) this.counts.delete(key);
13687
14594
  else this.counts.set(key, cur - 1);
13688
14595
  }
14596
+ /** 当前各池占用快照(健康检查用,对齐 Python `_PooledLimiter.snapshot`)。 */
14597
+ snapshot() {
14598
+ return Object.fromEntries(this.counts);
14599
+ }
13689
14600
  };
13690
14601
  RateLimiter = class {
13691
14602
  constructor(qps, burst) {
@@ -13963,7 +14874,7 @@ async function main() {
13963
14874
  case "init": {
13964
14875
  const flagIdx = args.findIndex((a) => a === "--output" || a === "-o");
13965
14876
  const output = (flagIdx >= 0 ? args[flagIdx + 1] : void 0) || args.slice(1).find((a) => !a.startsWith("-")) || "input.json";
13966
- const fs7 = await import("fs");
14877
+ const fs8 = await import("fs");
13967
14878
  const template = {
13968
14879
  session_id: "my-session-001",
13969
14880
  prompt_session: "Read /var/log/app.log and analyze errors",
@@ -13973,7 +14884,7 @@ async function main() {
13973
14884
  os_type: "",
13974
14885
  cwd: "/home/user/project"
13975
14886
  };
13976
- fs7.writeFileSync(output, JSON.stringify(template, null, 2), "utf-8");
14887
+ fs8.writeFileSync(output, JSON.stringify(template, null, 2), "utf-8");
13977
14888
  console.log(`Template written to ${output}`);
13978
14889
  break;
13979
14890
  }
@@ -13983,13 +14894,13 @@ async function main() {
13983
14894
  console.error('Usage: agent-moss analyze <input.json | "shell command">');
13984
14895
  process.exit(1);
13985
14896
  }
13986
- const fs7 = await import("fs");
13987
- const path6 = await import("path");
14897
+ const fs8 = await import("fs");
14898
+ const path7 = await import("path");
13988
14899
  const useJson = args.includes("--json");
13989
14900
  const osType = process.platform === "win32" ? "windows" : "linux";
13990
- const isFile = fs7.existsSync(target) && fs7.statSync(target).isFile();
14901
+ const isFile = fs8.existsSync(target) && fs8.statSync(target).isFile();
13991
14902
  if (!isFile) {
13992
- if (fs7.existsSync(target)) {
14903
+ if (fs8.existsSync(target)) {
13993
14904
  console.error(`\u9519\u8BEF: \u4E0D\u662F\u6587\u4EF6: ${target}`);
13994
14905
  process.exit(2);
13995
14906
  }
@@ -14003,8 +14914,8 @@ async function main() {
14003
14914
  }
14004
14915
  process.exit(await analyzeRawCommand(target, useJson));
14005
14916
  }
14006
- const filePath = path6.resolve(target);
14007
- const data = JSON.parse(fs7.readFileSync(filePath, "utf-8"));
14917
+ const filePath = path7.resolve(target);
14918
+ const data = JSON.parse(fs8.readFileSync(filePath, "utf-8"));
14008
14919
  const { analyze: analyze2 } = await Promise.resolve().then(() => (init_analyzer(), analyzer_exports));
14009
14920
  const sessionId = String(data.session_id || "unknown");
14010
14921
  const result = await analyze2(buildAnalysisInputFromFile(data));
@@ -14012,15 +14923,15 @@ async function main() {
14012
14923
  if (!args.includes("--no-file")) {
14013
14924
  const outDirIdx = args.findIndex((a) => a === "--output-dir" || a === "-o");
14014
14925
  const outDir = outDirIdx >= 0 && args[outDirIdx + 1] ? args[outDirIdx + 1] : process.cwd();
14015
- fs7.mkdirSync(outDir, { recursive: true });
14926
+ fs8.mkdirSync(outDir, { recursive: true });
14016
14927
  const safeSession = sessionId.replace(/\//g, "_");
14017
14928
  if (result.decision === "Allow") {
14018
- const policyPath = path6.join(outDir, `${safeSession}_policy.toml`);
14019
- fs7.writeFileSync(policyPath, result.policy || "", "utf-8");
14929
+ const policyPath = path7.join(outDir, `${safeSession}_policy.toml`);
14930
+ fs8.writeFileSync(policyPath, result.policy || "", "utf-8");
14020
14931
  console.log(`Policy written to ${policyPath}`);
14021
14932
  } else {
14022
- const denyPath = path6.join(outDir, `${safeSession}_deny_reason.txt`);
14023
- fs7.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
14933
+ const denyPath = path7.join(outDir, `${safeSession}_deny_reason.txt`);
14934
+ fs8.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
14024
14935
  console.log(`Deny reason written to ${denyPath}`);
14025
14936
  }
14026
14937
  }
@@ -14109,8 +15020,8 @@ async function main() {
14109
15020
  case "install": {
14110
15021
  const enable = args.includes("--enable");
14111
15022
  const { execSync } = await import("child_process");
14112
- const fs7 = await import("fs");
14113
- const path6 = await import("path");
15023
+ const fs8 = await import("fs");
15024
+ const path7 = await import("path");
14114
15025
  const { fileURLToPath: fileURLToPath14 } = await import("url");
14115
15026
  if (process.getuid?.() !== 0) {
14116
15027
  try {
@@ -14127,22 +15038,22 @@ async function main() {
14127
15038
  process.exit(0);
14128
15039
  }
14129
15040
  const __filename7 = fileURLToPath14(import.meta.url);
14130
- const __dirname12 = path6.dirname(__filename7);
14131
- let srcPath = path6.join(__dirname12, "data", "agent_moss.service");
14132
- if (!fs7.existsSync(srcPath)) {
14133
- srcPath = path6.join(__dirname12, "..", "src", "data", "agent_moss.service");
15041
+ const __dirname12 = path7.dirname(__filename7);
15042
+ let srcPath = path7.join(__dirname12, "data", "agent_moss.service");
15043
+ if (!fs8.existsSync(srcPath)) {
15044
+ srcPath = path7.join(__dirname12, "..", "src", "data", "agent_moss.service");
14134
15045
  }
14135
- if (!fs7.existsSync(srcPath)) {
15046
+ if (!fs8.existsSync(srcPath)) {
14136
15047
  console.error("\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230 agent_moss.service \u6A21\u677F\u6587\u4EF6");
14137
15048
  process.exit(1);
14138
15049
  }
14139
15050
  const which = execSync("which agent-moss 2>/dev/null || true", { encoding: "utf-8" }).trim();
14140
- const binPath = which || `${process.execPath} ${path6.join(__dirname12, "cli.js")}`;
14141
- let content = fs7.readFileSync(srcPath, "utf-8");
15051
+ const binPath = which || `${process.execPath} ${path7.join(__dirname12, "cli.js")}`;
15052
+ let content = fs8.readFileSync(srcPath, "utf-8");
14142
15053
  content = content.replace("__AGENT_MOSS_BIN__", binPath);
14143
15054
  const dst = "/etc/systemd/system/agent-moss.service";
14144
- fs7.writeFileSync(dst, content, "utf-8");
14145
- fs7.chmodSync(dst, 420);
15055
+ fs8.writeFileSync(dst, content, "utf-8");
15056
+ fs8.chmodSync(dst, 420);
14146
15057
  console.log(`\u2705 \u5DF2\u5B89\u88C5 systemd service: ${dst}`);
14147
15058
  execSync("systemctl daemon-reload", { stdio: "inherit" });
14148
15059
  console.log("\u2705 systemctl daemon-reload \u5B8C\u6210");