@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/server.js CHANGED
@@ -1,11 +1,5 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
- }) : x)(function(x) {
6
- if (typeof require !== "undefined") return require.apply(this, arguments);
7
- throw Error('Dynamic require of "' + x + '" is not supported');
8
- });
9
3
  var __esm = (fn, res) => function __init() {
10
4
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
5
  };
@@ -407,22 +401,22 @@ function loadToolRegistry() {
407
401
  data.tools = tools;
408
402
  return data;
409
403
  }
410
- function scanStructEntry(cat, value, path6) {
404
+ function scanStructEntry(cat, value, path7) {
411
405
  if (cat === "skills") {
412
406
  if (!value || typeof value !== "object" || Array.isArray(value)) {
413
- 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`);
407
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
414
408
  return null;
415
409
  }
416
410
  const out = {};
417
411
  for (const [skCat, skills] of Object.entries(value)) {
418
412
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
419
- 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`);
413
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
420
414
  continue;
421
415
  }
422
416
  const keep = {};
423
417
  for (const [name, kws] of Object.entries(skills)) {
424
418
  if (Array.isArray(kws)) keep[name] = kws;
425
- 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`);
419
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
426
420
  }
427
421
  if (Object.keys(keep).length > 0) out[skCat] = keep;
428
422
  }
@@ -430,37 +424,37 @@ function scanStructEntry(cat, value, path6) {
430
424
  }
431
425
  if (cat === "ltl_rules") {
432
426
  if (!Array.isArray(value)) {
433
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
427
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
434
428
  return null;
435
429
  }
436
430
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
437
431
  if (keep.length !== value.length) {
438
- 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`);
432
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
439
433
  }
440
434
  return keep.length > 0 ? keep : null;
441
435
  }
442
436
  if (cat === "tools") {
443
437
  if (!value || typeof value !== "object" || Array.isArray(value)) {
444
- 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`);
438
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
445
439
  return null;
446
440
  }
447
441
  const keep = {};
448
442
  for (const [k, v] of Object.entries(value)) {
449
443
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
450
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
444
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
451
445
  }
452
446
  return Object.keys(keep).length > 0 ? keep : null;
453
447
  }
454
448
  return null;
455
449
  }
456
- function scanRulesFile(path6, kind) {
450
+ function scanRulesFile(path7, kind) {
457
451
  const out = {};
458
452
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
459
453
  let parsed;
460
454
  try {
461
- parsed = JSON.parse(readFileSync2(path6, "utf-8"));
455
+ parsed = JSON.parse(readFileSync2(path7, "utf-8"));
462
456
  } catch (e) {
463
- 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}`);
457
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
464
458
  return out;
465
459
  }
466
460
  const classifyFlat = (r) => {
@@ -484,44 +478,44 @@ function scanRulesFile(path6, kind) {
484
478
  }
485
479
  if (flatBad > 0) {
486
480
  console.warn(
487
- `[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`
481
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
488
482
  );
489
483
  }
490
484
  } else {
491
- 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`);
485
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
492
486
  return out;
493
487
  }
494
488
  for (const [cat, rules] of pairs) {
495
489
  if (String(cat).startsWith("_")) continue;
496
490
  if (STRUCT_KEYS.includes(cat)) {
497
- const got = scanStructEntry(cat, rules, path6);
491
+ const got = scanStructEntry(cat, rules, path7);
498
492
  if (got !== null) out[cat] = got;
499
493
  continue;
500
494
  }
501
495
  const required = EXTRA_CATEGORIES[cat];
502
496
  if (!required) {
503
497
  console.warn(
504
- `[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`
498
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
505
499
  );
506
500
  continue;
507
501
  }
508
502
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
509
503
  console.error(
510
- `[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
504
+ `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path7} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
511
505
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
512
506
  \u4F60\u5199\u7684\u50CF\u662F runtime config \u7684\u683C\u5F0F\uFF08{"category_enabled": ..., "rules": [...]}\uFF09\u2014\u2014\u90A3\u662F ~/.config/agentmoss/agent_moss_runtime.json \u7684\u683C\u5F0F\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5F53\u89C4\u5219\u6587\u4EF6\u7528\u3002`
513
507
  );
514
508
  continue;
515
509
  }
516
510
  if (!Array.isArray(rules)) {
517
- 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`);
511
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
518
512
  continue;
519
513
  }
520
514
  const items = [];
521
515
  for (const r of rules) {
522
516
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
523
517
  console.warn(
524
- `[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`
518
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
525
519
  );
526
520
  continue;
527
521
  }
@@ -531,7 +525,7 @@ function scanRulesFile(path6, kind) {
531
525
  }
532
526
  if (Object.keys(out).length > 0) {
533
527
  console.info(
534
- `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path6}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
528
+ `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path7}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
535
529
  );
536
530
  }
537
531
  return out;
@@ -725,7 +719,7 @@ var init_rules_loader = __esm({
725
719
 
726
720
  // src/infra/security-policy.ts
727
721
  import { createHash as createHash2, randomBytes, timingSafeEqual } from "crypto";
728
- import { chmodSync, closeSync, existsSync as existsSync3, lstatSync, mkdirSync, openSync, readFileSync as readFileSync4, readSync, realpathSync, writeSync } from "fs";
722
+ import { chmodSync, closeSync, constants as fsConstants, existsSync as existsSync3, lstatSync, mkdirSync, openSync, readFileSync as readFileSync4, readSync, realpathSync, writeSync } from "fs";
729
723
  import { homedir as homedir2, tmpdir } from "os";
730
724
  import { basename, isAbsolute, join as join4, relative, resolve as resolve2, dirname as dirname2 } from "path";
731
725
  function env(name, dflt = "") {
@@ -801,10 +795,10 @@ function readExplicitToken() {
801
795
  if (tok) return tok;
802
796
  const fdTok = readFdToken();
803
797
  if (fdTok) return fdTok;
804
- const path6 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
805
- if (path6) {
798
+ const path7 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
799
+ if (path7) {
806
800
  try {
807
- return readFileSync4(path6, "utf-8").trim();
801
+ return readFileSync4(path7, "utf-8").trim();
808
802
  } catch {
809
803
  return "";
810
804
  }
@@ -812,23 +806,23 @@ function readExplicitToken() {
812
806
  return "";
813
807
  }
814
808
  function ensureAutoToken() {
815
- const path6 = autoTokenPath();
809
+ const path7 = autoTokenPath();
816
810
  try {
817
- if (existsSync3(path6) && !lstatSync(path6).isSymbolicLink()) {
818
- const tok2 = readFileSync4(path6, "utf-8").trim();
811
+ if (existsSync3(path7) && !lstatSync(path7).isSymbolicLink()) {
812
+ const tok2 = readFileSync4(path7, "utf-8").trim();
819
813
  if (tok2) {
820
814
  try {
821
- chmodSync(path6, 384);
815
+ chmodSync(path7, 384);
822
816
  } catch {
823
817
  }
824
818
  return tok2;
825
819
  }
826
820
  }
827
821
  const tok = randomBytes(32).toString("base64url");
828
- ensurePrivateDir(dirname2(path6));
829
- if (!writePrivateText(path6, tok + "\n")) return "";
822
+ ensurePrivateDir(dirname2(path7));
823
+ if (!writePrivateText(path7, tok + "\n")) return "";
830
824
  console.warn(
831
- `[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`
825
+ `[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${path7}\uFF080600\uFF09\u3002\u5BA2\u6237\u7AEF\u9700\u5E26 \`Authorization: Bearer <token>\`\uFF1B\u67E5\u770B\uFF1Acat ${path7}\uFF1B\u5982\u9700\u5173\u95ED\u9274\u6743\uFF1AAGENT_MOSS_AUTH_MODE=off`
832
826
  );
833
827
  return tok;
834
828
  } catch (e) {
@@ -901,16 +895,16 @@ function constEq(a, b) {
901
895
  if (ba.length !== bb.length) return false;
902
896
  return timingSafeEqual(ba, bb);
903
897
  }
904
- function checkRequestAuth(headers, path6) {
898
+ function checkRequestAuth(headers, path7) {
905
899
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
906
- const isHealth = HEALTH_PATHS.includes(path6.replace(/\/+$/, ""));
900
+ const isHealth = HEALTH_PATHS.includes(path7.replace(/\/+$/, ""));
907
901
  const [gt0, agents, err] = resolveAuth();
908
902
  if (err) return isHealth ? [true, ""] : [false, ""];
909
903
  if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
910
904
  if (isHealth) return [true, ""];
911
905
  const tok = bearer(headers);
912
906
  if (!tok) return [false, ""];
913
- if (path6.startsWith("/console/api")) {
907
+ if (path7.startsWith("/console/api")) {
914
908
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
915
909
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
916
910
  }
@@ -929,8 +923,8 @@ function bindAgent(principal, agentId) {
929
923
  if (!agentId) return [true, bound];
930
924
  return [bound === agentId, bound];
931
925
  }
932
- function principalOf(headers, path6 = "") {
933
- const [ok, principal] = checkRequestAuth(headers, path6);
926
+ function principalOf(headers, path7 = "") {
927
+ const [ok, principal] = checkRequestAuth(headers, path7);
934
928
  return ok ? principal : "";
935
929
  }
936
930
  function principalHash(principal) {
@@ -1009,9 +1003,8 @@ function ensurePrivateDir(dir) {
1009
1003
  }
1010
1004
  function writePrivateText(file, text) {
1011
1005
  try {
1012
- const flags = __require("fs").constants;
1013
- let openFlags = flags.O_WRONLY | flags.O_CREAT | flags.O_TRUNC;
1014
- if (flags.O_NOFOLLOW) openFlags |= flags.O_NOFOLLOW;
1006
+ let openFlags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC;
1007
+ if (fsConstants.O_NOFOLLOW) openFlags |= fsConstants.O_NOFOLLOW;
1015
1008
  const fd = openSync(file, openFlags, 384);
1016
1009
  try {
1017
1010
  writeSync(fd, text);
@@ -1188,11 +1181,11 @@ function errorDetailMode() {
1188
1181
  function maxBodyBytes() {
1189
1182
  return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
1190
1183
  }
1191
- function poolOf(path6) {
1192
- if (path6 === "/api/v1/analyze" || path6.startsWith("/api/v1/analyze/")) return "biz";
1193
- if (path6 === "/api/v1/review" || path6.startsWith("/api/v1/review/")) return "review";
1194
- if (path6 === "/console" || path6.startsWith("/console/") || path6.startsWith("/api/v1/brain")) return "ops";
1195
- if (path6 === "/api/v1/health") return "health";
1184
+ function poolOf(path7) {
1185
+ if (path7 === "/api/v1/analyze" || path7.startsWith("/api/v1/analyze/")) return "biz";
1186
+ if (path7 === "/api/v1/review" || path7.startsWith("/api/v1/review/")) return "review";
1187
+ if (path7 === "/console" || path7.startsWith("/console/") || path7.startsWith("/api/v1/brain")) return "ops";
1188
+ if (path7 === "/api/v1/health") return "health";
1196
1189
  return "other";
1197
1190
  }
1198
1191
  function poolLimit(name) {
@@ -1505,7 +1498,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
1505
1498
  os: String(sp.os || "linux").toLowerCase()
1506
1499
  }));
1507
1500
  }
1508
- function _scopeOf(os4, path6) {
1501
+ function _scopeOf(os4, path7) {
1509
1502
  if (!_scopeIndex) {
1510
1503
  _scopeIndex = /* @__PURE__ */ new Map();
1511
1504
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -1513,7 +1506,7 @@ function _scopeOf(os4, path6) {
1513
1506
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
1514
1507
  }
1515
1508
  }
1516
- return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path6}`) || "root";
1509
+ return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path7}`) || "root";
1517
1510
  }
1518
1511
  function getSensitivePathsForOs(osType) {
1519
1512
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -1864,17 +1857,17 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
1864
1857
  return null;
1865
1858
  }
1866
1859
  const unreadPaths = [];
1867
- for (const path6 of filteredPaths) {
1860
+ for (const path7 of filteredPaths) {
1868
1861
  const hasRead = [...historyReadPaths].some(
1869
- (rp) => path6 === rp || path6.startsWith(rp) || rp.startsWith(path6)
1862
+ (rp) => path7 === rp || path7.startsWith(rp) || rp.startsWith(path7)
1870
1863
  );
1871
1864
  if (!hasRead) {
1872
- let isCreate = !fs.existsSync(path6);
1865
+ let isCreate = !fs.existsSync(path7);
1873
1866
  if (!isCreate) {
1874
1867
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
1875
1868
  }
1876
1869
  if (!isCreate) {
1877
- unreadPaths.push(path6);
1870
+ unreadPaths.push(path7);
1878
1871
  }
1879
1872
  }
1880
1873
  }
@@ -2068,16 +2061,16 @@ var init_logic_rules = __esm({
2068
2061
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
2069
2062
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
2070
2063
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
2071
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2064
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2072
2065
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
2073
2066
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
2074
- CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2067
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2075
2068
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
2076
2069
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
2077
- CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2070
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2078
2071
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
2079
2072
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
2080
- CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
2073
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2081
2074
  _scopeIndex = null;
2082
2075
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
2083
2076
  "ask_user_question",
@@ -3846,7 +3839,9 @@ function loadLLMConfigFromFile(configPath) {
3846
3839
  model: llm.model || "",
3847
3840
  temperature: llm.temperature ?? 0.1,
3848
3841
  maxTokens: llm.max_tokens ?? 4096,
3849
- timeout: llm.timeout ?? 40
3842
+ timeout: llm.timeout ?? 40,
3843
+ // 部署级透传参数(关思考等)。非对象直接忽略:写错不能拖垮配置加载。
3844
+ ...llm.extra_body && typeof llm.extra_body === "object" && !Array.isArray(llm.extra_body) ? { extraBody: llm.extra_body } : {}
3850
3845
  };
3851
3846
  }
3852
3847
  function loadTimeoutRetryFromFile(configPath) {
@@ -4678,16 +4673,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4678
4673
  if (String(osType || "").toLowerCase() === "windows") {
4679
4674
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
4680
4675
  }
4681
- const pathMatches = (text, path6) => {
4682
- const parts = path6.split(/(\(\?!.*?\))/);
4676
+ const pathMatches = (text, path7) => {
4677
+ const parts = path7.split(/(\(\?!.*?\))/);
4683
4678
  const escaped = parts.map((part) => {
4684
4679
  if (part.startsWith("(?!")) return part;
4685
4680
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4686
4681
  }).join("");
4687
- const re = path6.startsWith(".") || path6.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4682
+ const re = path7.startsWith(".") || path7.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4688
4683
  return re.test(text);
4689
4684
  };
4690
- const pathMatchesAny = (path6) => pathScanTexts.some((t) => pathMatches(t, path6));
4685
+ const pathMatchesAny = (path7) => pathScanTexts.some((t) => pathMatches(t, path7));
4691
4686
  for (const sp of rootPaths) {
4692
4687
  if (pathMatchesAny(sp.path.toLowerCase())) {
4693
4688
  if (keygenGenerate) continue;
@@ -4830,8 +4825,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4830
4825
  }
4831
4826
  return null;
4832
4827
  }
4833
- function isHomeValue(path6) {
4834
- let p = path6.trim().toLowerCase();
4828
+ function isHomeValue(path7) {
4829
+ let p = path7.trim().toLowerCase();
4835
4830
  if (p.startsWith("$(") && p.endsWith(")")) {
4836
4831
  const inner = p.slice(2, -1).trim();
4837
4832
  return HOME_TARGET_RE.test(" " + inner);
@@ -4887,15 +4882,15 @@ function checkHomeDeletion(actionType, actionDetail) {
4887
4882
  }
4888
4883
  const assigned = {};
4889
4884
  for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
4890
- for (const [varName, path6] of Object.entries(assigned)) {
4891
- if (!isHomeValue(path6)) continue;
4885
+ for (const [varName, path7] of Object.entries(assigned)) {
4886
+ if (!isHomeValue(path7)) continue;
4892
4887
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
4893
4888
  for (const seg of segs) {
4894
4889
  if (!isDeleteCommand(seg)) continue;
4895
4890
  if (varRefRe.test(seg)) {
4896
4891
  return {
4897
4892
  allowed: false,
4898
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path6}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
4893
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path7}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
4899
4894
  riskLevel: "high",
4900
4895
  riskType: "script_execution",
4901
4896
  confidence: 90,
@@ -5699,15 +5694,15 @@ function parseShellString(s) {
5699
5694
  let m;
5700
5695
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
5701
5696
  const interp = m[1];
5702
- const path6 = m[2].trim();
5697
+ const path7 = m[2].trim();
5703
5698
  let rest = m[3].trim();
5704
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
5699
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
5705
5700
  rest = rest.split(/[;|&<>]/)[0].trim();
5706
5701
  const args = [];
5707
5702
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
5708
5703
  args.push(tm[1] ? tm[2] : tm[3]);
5709
5704
  }
5710
- return { path: path6, args, interpreter: interp };
5705
+ return { path: path7, args, interpreter: interp };
5711
5706
  }
5712
5707
  return null;
5713
5708
  }
@@ -5753,9 +5748,9 @@ function extractCallsFromTree(tree, reachableLines) {
5753
5748
  }
5754
5749
  if (allStr && elts.length >= 2) {
5755
5750
  const interp = elts[0];
5756
- const path6 = elts[1];
5757
- if (!path6.startsWith("-") && !path6.startsWith("$") && !path6.includes("/dev/")) {
5758
- add({ path: path6, args: elts.slice(2), interpreter: interp });
5751
+ const path7 = elts[1];
5752
+ if (!path7.startsWith("-") && !path7.startsWith("$") && !path7.includes("/dev/")) {
5753
+ add({ path: path7, args: elts.slice(2), interpreter: interp });
5759
5754
  return true;
5760
5755
  }
5761
5756
  }
@@ -5795,15 +5790,15 @@ function extractCallsRegex(content) {
5795
5790
  let m;
5796
5791
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
5797
5792
  const interp = m[1];
5798
- const path6 = m[2].trim();
5793
+ const path7 = m[2].trim();
5799
5794
  let rest = m[3].trim();
5800
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
5795
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
5801
5796
  rest = rest.split(/[;|&<>]/)[0].trim();
5802
5797
  const args = [];
5803
5798
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
5804
5799
  args.push(tm[1] ? tm[2] : tm[3]);
5805
5800
  }
5806
- calls.push({ path: path6, args, interpreter: interp });
5801
+ calls.push({ path: path7, args, interpreter: interp });
5807
5802
  }
5808
5803
  return calls;
5809
5804
  }
@@ -6586,15 +6581,15 @@ function extractCallsFromContent(content) {
6586
6581
  CHILD_CALL_RE2.lastIndex = 0;
6587
6582
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
6588
6583
  const interp = m[1];
6589
- const path6 = m[2].trim();
6584
+ const path7 = m[2].trim();
6590
6585
  let rest = m[3].trim();
6591
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
6586
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6592
6587
  rest = rest.split(/[;|&<>]/)[0].trim();
6593
6588
  const args = [];
6594
6589
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6595
6590
  args.push(tm[1] ? tm[2] : tm[3]);
6596
6591
  }
6597
- calls.push({ path: path6, args, interpreter: interp });
6592
+ calls.push({ path: path7, args, interpreter: interp });
6598
6593
  }
6599
6594
  return calls;
6600
6595
  }
@@ -7283,6 +7278,464 @@ var init_script_content_analyzer = __esm({
7283
7278
  }
7284
7279
  });
7285
7280
 
7281
+ // src/infra/trace-log.ts
7282
+ import fs4 from "fs";
7283
+ import path4 from "path";
7284
+ function traceLevel() {
7285
+ if (_levelCache !== null) return _levelCache;
7286
+ const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
7287
+ let level;
7288
+ if (raw in LEVEL_NAMES) {
7289
+ level = LEVEL_NAMES[raw];
7290
+ } else {
7291
+ level = LEVEL_SUMMARY;
7292
+ if (!_warnedInvalid) {
7293
+ _warnedInvalid = true;
7294
+ console.warn(
7295
+ `[AgentMoss] AGENT_MOSS_TRACE_LEVEL=${JSON.stringify(raw)} \u975E\u6CD5\uFF0C\u6309 summary \u5904\u7406\uFF08\u53EF\u9009 off/summary/full\uFF09`
7296
+ );
7297
+ }
7298
+ }
7299
+ _levelCache = level;
7300
+ _levelCacheRaw = raw;
7301
+ return level;
7302
+ }
7303
+ function nowIso() {
7304
+ return (/* @__PURE__ */ new Date()).toISOString();
7305
+ }
7306
+ function tracePath() {
7307
+ const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
7308
+ if (explicit) return explicit;
7309
+ try {
7310
+ return path4.join(getDataRoot(), "agent_moss_trace.log");
7311
+ } catch {
7312
+ return "agent_moss_trace.log";
7313
+ }
7314
+ }
7315
+ function sanitize(key, value) {
7316
+ if (SECRET_KEYS.has(key.toLowerCase())) return "***";
7317
+ if (typeof value === "string") {
7318
+ let v = value;
7319
+ if (v.length > MAX_FIELD_CHARS) {
7320
+ const original = v.length;
7321
+ v = `${v.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
7322
+ }
7323
+ return v;
7324
+ }
7325
+ if (value === null || ["number", "boolean"].includes(typeof value)) return value;
7326
+ let text;
7327
+ try {
7328
+ text = JSON.stringify(value);
7329
+ } catch {
7330
+ return String(value);
7331
+ }
7332
+ if (text.length > MAX_FIELD_CHARS) {
7333
+ const original = text.length;
7334
+ return `${text.slice(0, MAX_FIELD_CHARS)}...[truncated ${original} chars]`;
7335
+ }
7336
+ return value;
7337
+ }
7338
+ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
7339
+ if (traceLevel() < level) return;
7340
+ try {
7341
+ const record = { ts: nowIso(), event };
7342
+ for (const [key, value] of Object.entries(fields)) {
7343
+ record[key] = sanitize(key, value);
7344
+ }
7345
+ const line = `${JSON.stringify(record)}
7346
+ `;
7347
+ const file = tracePath();
7348
+ try {
7349
+ const dir = path4.dirname(file);
7350
+ if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
7351
+ try {
7352
+ const st = fs4.statSync(file);
7353
+ if (st.size > MAX_FILE_BYTES) fs4.renameSync(file, `${file}.1`);
7354
+ } catch {
7355
+ }
7356
+ fs4.appendFileSync(file, line, { encoding: "utf-8", mode: 384 });
7357
+ } catch {
7358
+ }
7359
+ } catch {
7360
+ }
7361
+ }
7362
+ function traceSummary(event, fields = {}) {
7363
+ trace(event, LEVEL_SUMMARY, fields);
7364
+ }
7365
+ function traceFull(event, fields = {}) {
7366
+ trace(event, LEVEL_FULL, fields);
7367
+ }
7368
+ var LEVEL_OFF, LEVEL_SUMMARY, LEVEL_FULL, LEVEL_NAMES, MAX_FIELD_CHARS, SECRET_KEYS, MAX_FILE_BYTES, _levelCache, _levelCacheRaw, _warnedInvalid;
7369
+ var init_trace_log = __esm({
7370
+ "src/infra/trace-log.ts"() {
7371
+ "use strict";
7372
+ init_esm_shims();
7373
+ init_paths();
7374
+ LEVEL_OFF = 0;
7375
+ LEVEL_SUMMARY = 1;
7376
+ LEVEL_FULL = 2;
7377
+ LEVEL_NAMES = {
7378
+ off: LEVEL_OFF,
7379
+ summary: LEVEL_SUMMARY,
7380
+ full: LEVEL_FULL
7381
+ };
7382
+ MAX_FIELD_CHARS = 64 * 1024;
7383
+ SECRET_KEYS = /* @__PURE__ */ new Set([
7384
+ "api_key",
7385
+ "apikey",
7386
+ "authorization",
7387
+ "auth_token",
7388
+ "token",
7389
+ "password"
7390
+ ]);
7391
+ MAX_FILE_BYTES = 20 * 1024 * 1024;
7392
+ _levelCache = null;
7393
+ _levelCacheRaw = null;
7394
+ _warnedInvalid = false;
7395
+ }
7396
+ });
7397
+
7398
+ // src/infra/circuit-breaker.ts
7399
+ function envInt2(name, fallback) {
7400
+ const raw = process.env[name];
7401
+ if (raw === void 0 || raw.trim() === "") return fallback;
7402
+ const n = Number(raw);
7403
+ return Number.isFinite(n) ? n : fallback;
7404
+ }
7405
+ function getBreaker() {
7406
+ if (_breaker === null) {
7407
+ _breaker = new CircuitBreaker(
7408
+ envInt2("AGENT_MOSS_LLM_CIRCUIT_THRESHOLD", 5),
7409
+ envInt2("AGENT_MOSS_LLM_CIRCUIT_COOLDOWN", 30)
7410
+ );
7411
+ }
7412
+ return _breaker;
7413
+ }
7414
+ var CLOSED, OPEN, HALF_OPEN, CircuitBreaker, _breaker;
7415
+ var init_circuit_breaker = __esm({
7416
+ "src/infra/circuit-breaker.ts"() {
7417
+ "use strict";
7418
+ init_esm_shims();
7419
+ CLOSED = "closed";
7420
+ OPEN = "open";
7421
+ HALF_OPEN = "half_open";
7422
+ CircuitBreaker = class {
7423
+ constructor(threshold = 5, cooldown = 30) {
7424
+ this.threshold = threshold;
7425
+ this.cooldown = cooldown;
7426
+ }
7427
+ threshold;
7428
+ cooldown;
7429
+ state = CLOSED;
7430
+ failures = 0;
7431
+ openedAt = 0;
7432
+ openCount = 0;
7433
+ shortCircuitCount = 0;
7434
+ get currentState() {
7435
+ return this.state;
7436
+ }
7437
+ allow() {
7438
+ if (this.threshold <= 0) return true;
7439
+ if (this.state === CLOSED) return true;
7440
+ if (this.state === OPEN) {
7441
+ if ((performance.now() - this.openedAt) / 1e3 >= this.cooldown) {
7442
+ this.state = HALF_OPEN;
7443
+ return true;
7444
+ }
7445
+ this.shortCircuitCount += 1;
7446
+ return false;
7447
+ }
7448
+ return true;
7449
+ }
7450
+ recordSuccess() {
7451
+ if (this.threshold <= 0) return;
7452
+ this.state = CLOSED;
7453
+ this.failures = 0;
7454
+ }
7455
+ recordFailure() {
7456
+ if (this.threshold <= 0) return;
7457
+ if (this.state === HALF_OPEN) {
7458
+ this.state = OPEN;
7459
+ this.openedAt = performance.now();
7460
+ this.openCount += 1;
7461
+ return;
7462
+ }
7463
+ this.failures += 1;
7464
+ if (this.failures >= this.threshold) {
7465
+ this.state = OPEN;
7466
+ this.openedAt = performance.now();
7467
+ this.openCount += 1;
7468
+ }
7469
+ }
7470
+ snapshot() {
7471
+ return {
7472
+ state: this.state,
7473
+ failures: this.failures,
7474
+ threshold: this.threshold,
7475
+ cooldown_sec: this.cooldown,
7476
+ open_count: this.openCount,
7477
+ short_circuit_count: this.shortCircuitCount
7478
+ };
7479
+ }
7480
+ reset() {
7481
+ this.state = CLOSED;
7482
+ this.failures = 0;
7483
+ this.openedAt = 0;
7484
+ }
7485
+ };
7486
+ _breaker = null;
7487
+ }
7488
+ });
7489
+
7490
+ // src/infra/metrics.ts
7491
+ function escapeLabel(value) {
7492
+ return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
7493
+ }
7494
+ function formatLabels(labels) {
7495
+ if (!labels) return "";
7496
+ const keys = Object.keys(labels).sort();
7497
+ if (!keys.length) return "";
7498
+ return `{${keys.map((k) => `${k}="${escapeLabel(labels[k])}"`).join(",")}}`;
7499
+ }
7500
+ function keyOf(labelnames, labels) {
7501
+ return labelnames.map((k) => String(labels[k] ?? "")).join("");
7502
+ }
7503
+ function decodeKey(labelnames, key) {
7504
+ if (!labelnames.length) return void 0;
7505
+ const parts = key.split("");
7506
+ const out = {};
7507
+ labelnames.forEach((k, i) => {
7508
+ out[k] = parts[i] ?? "";
7509
+ });
7510
+ return out;
7511
+ }
7512
+ function renderPrometheus() {
7513
+ const lines = [];
7514
+ for (const m of [
7515
+ ANALYZE_TOTAL,
7516
+ ANALYZE_DURATION,
7517
+ LAYER_HIT_TOTAL,
7518
+ REJECTED_TOTAL,
7519
+ LLM_CALLS_TOTAL,
7520
+ LLM_DURATION,
7521
+ POOL_INFLIGHT,
7522
+ CHAIN_NODES,
7523
+ CHAIN_DB_BYTES,
7524
+ LOOP_LAG,
7525
+ LOOP_LAG_MAX,
7526
+ UPTIME,
7527
+ LLM_CIRCUIT_STATE,
7528
+ LLM_SHORT_CIRCUIT_TOTAL
7529
+ ]) {
7530
+ lines.push(...m.render());
7531
+ }
7532
+ return `${lines.join("\n")}
7533
+ `;
7534
+ }
7535
+ function refreshRuntimeGauges(g) {
7536
+ UPTIME.set((Date.now() - STARTED_AT) / 1e3);
7537
+ try {
7538
+ const snap = getBreaker().snapshot();
7539
+ const stateMap = { closed: 0, open: 1, half_open: 2 };
7540
+ LLM_CIRCUIT_STATE.set(stateMap[String(snap.state)] ?? 0);
7541
+ } catch {
7542
+ }
7543
+ if (g.pools !== void 0) {
7544
+ POOL_INFLIGHT.clear();
7545
+ for (const [key, value] of Object.entries(g.pools)) {
7546
+ POOL_INFLIGHT.set(value, { pool: key });
7547
+ }
7548
+ }
7549
+ if (g.chainNodes !== void 0) {
7550
+ CHAIN_NODES.clear();
7551
+ CHAIN_NODES.set(g.chainNodes, { agent: "__total__" });
7552
+ }
7553
+ if (g.chainDbBytes !== void 0) CHAIN_DB_BYTES.set(g.chainDbBytes);
7554
+ if (g.loopLagMs !== void 0) LOOP_LAG.set(g.loopLagMs / 1e3);
7555
+ if (g.loopLagMaxMs !== void 0) LOOP_LAG_MAX.set(g.loopLagMaxMs / 1e3);
7556
+ }
7557
+ 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;
7558
+ var init_metrics = __esm({
7559
+ "src/infra/metrics.ts"() {
7560
+ "use strict";
7561
+ init_esm_shims();
7562
+ init_circuit_breaker();
7563
+ DEFAULT_BUCKETS = [
7564
+ 5e-3,
7565
+ 0.01,
7566
+ 0.025,
7567
+ 0.05,
7568
+ 0.1,
7569
+ 0.25,
7570
+ 0.5,
7571
+ 1,
7572
+ 2.5,
7573
+ 5,
7574
+ 10,
7575
+ 30,
7576
+ 60
7577
+ ];
7578
+ STARTED_AT = Date.now();
7579
+ Counter = class {
7580
+ constructor(name, helpText, labelnames = []) {
7581
+ this.name = name;
7582
+ this.helpText = helpText;
7583
+ this.labelnames = labelnames;
7584
+ }
7585
+ name;
7586
+ helpText;
7587
+ labelnames;
7588
+ values = /* @__PURE__ */ new Map();
7589
+ inc(amount = 1, labels = {}) {
7590
+ const k = keyOf(this.labelnames, labels);
7591
+ this.values.set(k, (this.values.get(k) ?? 0) + amount);
7592
+ }
7593
+ render() {
7594
+ const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} counter`];
7595
+ if (!this.values.size) {
7596
+ const empty = this.labelnames.length ? Object.fromEntries(this.labelnames.map((k) => [k, ""])) : void 0;
7597
+ out.push(`${this.name}${formatLabels(empty)} 0`);
7598
+ return out;
7599
+ }
7600
+ for (const [k, v] of this.values) {
7601
+ out.push(`${this.name}${formatLabels(decodeKey(this.labelnames, k))} ${v}`);
7602
+ }
7603
+ return out;
7604
+ }
7605
+ };
7606
+ Gauge = class {
7607
+ constructor(name, helpText, labelnames = []) {
7608
+ this.name = name;
7609
+ this.helpText = helpText;
7610
+ this.labelnames = labelnames;
7611
+ }
7612
+ name;
7613
+ helpText;
7614
+ labelnames;
7615
+ values = /* @__PURE__ */ new Map();
7616
+ set(value, labels = {}) {
7617
+ this.values.set(keyOf(this.labelnames, labels), Number(value));
7618
+ }
7619
+ clear() {
7620
+ this.values.clear();
7621
+ }
7622
+ render() {
7623
+ const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} gauge`];
7624
+ for (const [k, v] of this.values) {
7625
+ const labels = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : void 0;
7626
+ out.push(`${this.name}${formatLabels(labels)} ${v}`);
7627
+ }
7628
+ return out;
7629
+ }
7630
+ };
7631
+ Histogram = class {
7632
+ constructor(name, helpText, buckets = DEFAULT_BUCKETS, labelnames = []) {
7633
+ this.name = name;
7634
+ this.helpText = helpText;
7635
+ this.buckets = buckets;
7636
+ this.labelnames = labelnames;
7637
+ }
7638
+ name;
7639
+ helpText;
7640
+ buckets;
7641
+ labelnames;
7642
+ values = /* @__PURE__ */ new Map();
7643
+ observe(value, labels = {}) {
7644
+ const k = keyOf(this.labelnames, labels);
7645
+ let slot = this.values.get(k);
7646
+ if (!slot) {
7647
+ slot = { buckets: this.buckets.map(() => 0), sum: 0, count: 0 };
7648
+ this.values.set(k, slot);
7649
+ }
7650
+ for (let i = 0; i < this.buckets.length; i++) {
7651
+ if (value <= this.buckets[i]) slot.buckets[i] += 1;
7652
+ }
7653
+ slot.sum += value;
7654
+ slot.count += 1;
7655
+ }
7656
+ render() {
7657
+ const out = [`# HELP ${this.name} ${this.helpText}`, `# TYPE ${this.name} histogram`];
7658
+ for (const [k, slot] of this.values) {
7659
+ const base = this.labelnames.length ? Object.fromEntries(this.labelnames.map((n, i) => [n, k.split("")[i] ?? ""])) : {};
7660
+ this.buckets.forEach((bound, i) => {
7661
+ out.push(`${this.name}_bucket${formatLabels({ ...base, le: String(bound) })} ${slot.buckets[i]}`);
7662
+ });
7663
+ out.push(`${this.name}_bucket${formatLabels({ ...base, le: "+Inf" })} ${slot.count}`);
7664
+ out.push(`${this.name}_sum${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.sum}`);
7665
+ out.push(`${this.name}_count${formatLabels(Object.keys(base).length ? base : void 0)} ${slot.count}`);
7666
+ }
7667
+ return out;
7668
+ }
7669
+ };
7670
+ ANALYZE_TOTAL = new Counter(
7671
+ "agent_moss_analyze_total",
7672
+ "Total analyze requests handled, by decision and risk level.",
7673
+ ["decision", "risk_level"]
7674
+ );
7675
+ ANALYZE_DURATION = new Histogram(
7676
+ "agent_moss_analyze_duration_seconds",
7677
+ "End-to-end analyze duration in seconds.",
7678
+ DEFAULT_BUCKETS,
7679
+ ["decision"]
7680
+ );
7681
+ LAYER_HIT_TOTAL = new Counter(
7682
+ "agent_moss_layer_hit_total",
7683
+ "Number of requests where a given defense layer produced the final verdict.",
7684
+ ["layer"]
7685
+ );
7686
+ REJECTED_TOTAL = new Counter(
7687
+ "agent_moss_rejected_total",
7688
+ "Requests rejected before analysis (concurrency / rate limit / auth).",
7689
+ ["reason"]
7690
+ );
7691
+ LLM_CALLS_TOTAL = new Counter(
7692
+ "agent_moss_llm_calls_total",
7693
+ "LLM API calls, by outcome.",
7694
+ ["result"]
7695
+ );
7696
+ LLM_DURATION = new Histogram(
7697
+ "agent_moss_llm_duration_seconds",
7698
+ "LLM API call duration in seconds.",
7699
+ DEFAULT_BUCKETS,
7700
+ ["result"]
7701
+ );
7702
+ POOL_INFLIGHT = new Gauge(
7703
+ "agent_moss_pool_inflight",
7704
+ "Current in-flight requests per concurrency pool.",
7705
+ ["pool"]
7706
+ );
7707
+ CHAIN_NODES = new Gauge(
7708
+ "agent_moss_chain_nodes",
7709
+ "Number of nodes in the stateful chain timeline.",
7710
+ ["agent"]
7711
+ );
7712
+ CHAIN_DB_BYTES = new Gauge(
7713
+ "agent_moss_chain_db_bytes",
7714
+ "Size of the chain state database in bytes."
7715
+ );
7716
+ LOOP_LAG = new Gauge(
7717
+ "agent_moss_event_loop_lag_seconds",
7718
+ "Most recent event loop lag sample in seconds."
7719
+ );
7720
+ LOOP_LAG_MAX = new Gauge(
7721
+ "agent_moss_event_loop_lag_max_seconds",
7722
+ "Maximum event loop lag observed since process start, in seconds."
7723
+ );
7724
+ UPTIME = new Gauge(
7725
+ "agent_moss_uptime_seconds",
7726
+ "Seconds since process start."
7727
+ );
7728
+ LLM_CIRCUIT_STATE = new Gauge(
7729
+ "agent_moss_llm_circuit_state",
7730
+ "LLM circuit breaker state (0=closed, 1=open, 2=half_open)."
7731
+ );
7732
+ LLM_SHORT_CIRCUIT_TOTAL = new Counter(
7733
+ "agent_moss_llm_short_circuit_total",
7734
+ "LLM calls short-circuited by the breaker (no network request made)."
7735
+ );
7736
+ }
7737
+ });
7738
+
7286
7739
  // src/engine/token-stats.ts
7287
7740
  var token_stats_exports = {};
7288
7741
  __export(token_stats_exports, {
@@ -7291,9 +7744,10 @@ __export(token_stats_exports, {
7291
7744
  getTokenStats: () => getTokenStats,
7292
7745
  getTokenTrend: () => getTokenTrend,
7293
7746
  recordTokenUsage: () => recordTokenUsage,
7294
- resetTokenStats: () => resetTokenStats
7747
+ resetTokenStats: () => resetTokenStats,
7748
+ resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
7295
7749
  });
7296
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2 } from "fs";
7750
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync5 } from "fs";
7297
7751
  function getStatsPath() {
7298
7752
  const envPath = process.env[ENV_STATS_PATH];
7299
7753
  if (envPath) return envPath;
@@ -7301,11 +7755,24 @@ function getStatsPath() {
7301
7755
  }
7302
7756
  function loadAllRecords(statsPath) {
7303
7757
  if (!existsSync13(statsPath)) return [];
7758
+ let sig = "";
7304
7759
  try {
7305
- const data = JSON.parse(readFileSync13(statsPath, "utf-8"));
7306
- if (Array.isArray(data)) return data;
7307
- if (data && Array.isArray(data.records)) return data.records;
7760
+ const st = statSync5(statsPath);
7761
+ sig = `${st.mtimeMs}:${st.size}`;
7762
+ } catch {
7308
7763
  return [];
7764
+ }
7765
+ if (_recordsCache && _recordsCache.path === statsPath && _recordsCache.sig === sig) {
7766
+ return _recordsCache.records.slice();
7767
+ }
7768
+ try {
7769
+ const data = JSON.parse(readFileSync13(statsPath, "utf-8"));
7770
+ let records;
7771
+ if (Array.isArray(data)) records = data;
7772
+ else if (data && Array.isArray(data.records)) records = data.records;
7773
+ else records = [];
7774
+ _recordsCache = { path: statsPath, sig, records };
7775
+ return records.slice();
7309
7776
  } catch (e) {
7310
7777
  return [];
7311
7778
  }
@@ -7315,9 +7782,22 @@ function saveRecords(statsPath, records) {
7315
7782
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
7316
7783
  if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
7317
7784
  writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
7785
+ try {
7786
+ const st = statSync5(statsPath);
7787
+ _recordsCache = {
7788
+ path: statsPath,
7789
+ sig: `${st.mtimeMs}:${st.size}`,
7790
+ records: records.slice()
7791
+ };
7792
+ } catch {
7793
+ _recordsCache = null;
7794
+ }
7318
7795
  } catch (e) {
7319
7796
  }
7320
7797
  }
7798
+ function resetTokenStatsCacheForTests() {
7799
+ _recordsCache = null;
7800
+ }
7321
7801
  function recordTokenUsage(record) {
7322
7802
  const statsPath = getStatsPath();
7323
7803
  const records = loadAllRecords(statsPath);
@@ -7446,8 +7926,9 @@ function resetTokenStats() {
7446
7926
  } catch {
7447
7927
  }
7448
7928
  }
7929
+ _recordsCache = null;
7449
7930
  }
7450
- var ENV_STATS_PATH, MAX_RECORDS;
7931
+ var ENV_STATS_PATH, MAX_RECORDS, _recordsCache;
7451
7932
  var init_token_stats = __esm({
7452
7933
  "src/engine/token-stats.ts"() {
7453
7934
  "use strict";
@@ -7455,13 +7936,30 @@ var init_token_stats = __esm({
7455
7936
  init_paths();
7456
7937
  ENV_STATS_PATH = "AGENT_MOSS_TOKEN_STATS_PATH";
7457
7938
  MAX_RECORDS = 1e4;
7939
+ _recordsCache = null;
7458
7940
  }
7459
7941
  });
7460
7942
 
7461
7943
  // src/engine/llm-analyzer.ts
7462
7944
  import { createHash as createHash3 } from "crypto";
7463
- import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
7945
+ import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants2 } from "fs";
7464
7946
  import OpenAI from "openai";
7947
+ function responseFieldLengths(message) {
7948
+ if (!message || typeof message !== "object") return {};
7949
+ const out = {};
7950
+ for (const [key, value] of Object.entries(message)) {
7951
+ if (value === null || value === void 0 || value === "") continue;
7952
+ if (Array.isArray(value) && value.length === 0) continue;
7953
+ if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) continue;
7954
+ if (typeof value === "boolean") continue;
7955
+ try {
7956
+ out[key] = typeof value === "string" ? value.length : String(JSON.stringify(value)).length;
7957
+ } catch {
7958
+ out[key] = -1;
7959
+ }
7960
+ }
7961
+ return out;
7962
+ }
7465
7963
  async function runLLMAnalysis(input, previous) {
7466
7964
  if (!isLLMAvailable()) {
7467
7965
  console.log("[AgentMoss] LLM not configured, skipping deep analysis");
@@ -7544,7 +8042,23 @@ async function runLLMAnalysis(input, previous) {
7544
8042
  );
7545
8043
  }
7546
8044
  logPrompt(prompt, input.aNext, previous.llmLogPath);
8045
+ traceFull("l3.prompt", {
8046
+ phase: "security_judge",
8047
+ model: config.model,
8048
+ base_url: config.baseUrl,
8049
+ action_type: input.aNext.actionType,
8050
+ action_detail: input.aNext.actionDetail,
8051
+ prompt,
8052
+ prompt_chars: prompt.length
8053
+ });
7547
8054
  const result = await analyzeWithLLM(prompt, config);
8055
+ traceSummary("l3.verdict", {
8056
+ allowed: result.allowed,
8057
+ risk_level: result.riskLevel,
8058
+ risk_type: result.riskType,
8059
+ reason: result.reason,
8060
+ confidence: result.confidence
8061
+ });
7548
8062
  if (llmCache.size >= LLM_CACHE_MAX) {
7549
8063
  const firstKey = llmCache.keys().next().value;
7550
8064
  if (firstKey) llmCache.delete(firstKey);
@@ -7565,8 +8079,8 @@ function logPrompt(prompt, aNext, logPath) {
7565
8079
  ${prompt}
7566
8080
  --- END PROMPT ---
7567
8081
  `;
7568
- let flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND;
7569
- if (fsConstants.O_NOFOLLOW) flags |= fsConstants.O_NOFOLLOW;
8082
+ let flags = fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_APPEND;
8083
+ if (fsConstants2.O_NOFOLLOW) flags |= fsConstants2.O_NOFOLLOW;
7570
8084
  const fd = openSync2(logPath, flags, 384);
7571
8085
  try {
7572
8086
  writeSync2(fd, line);
@@ -7686,6 +8200,14 @@ function formatHints(previous) {
7686
8200
  }
7687
8201
  async function analyzeWithLLM(prompt, config) {
7688
8202
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
8203
+ const _llmStart = performance.now();
8204
+ const _recordLlm = (result) => {
8205
+ try {
8206
+ LLM_CALLS_TOTAL.inc(1, { result });
8207
+ LLM_DURATION.observe(Math.max(0, (performance.now() - _llmStart) / 1e3), { result });
8208
+ } catch {
8209
+ }
8210
+ };
7689
8211
  const provider = detectProvider(config.baseUrl, config.provider);
7690
8212
  const extraHeaders = getProviderHeaders(provider);
7691
8213
  if (Object.keys(extraHeaders).length > 0) {
@@ -7707,6 +8229,17 @@ async function analyzeWithLLM(prompt, config) {
7707
8229
  console.error(`[AgentMoss] totalTimeout (${timeoutCfg.totalTimeout}s) exceeded, aborting all LLM calls`);
7708
8230
  abortController.abort();
7709
8231
  }, totalTimeoutMs);
8232
+ const breaker = getBreaker();
8233
+ if (!breaker.allow()) {
8234
+ try {
8235
+ LLM_SHORT_CIRCUIT_TOTAL.inc(1);
8236
+ } catch {
8237
+ }
8238
+ _recordLlm("error");
8239
+ throw new Error(
8240
+ "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"
8241
+ );
8242
+ }
7710
8243
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
7711
8244
  if (abortController.signal.aborted) {
7712
8245
  break;
@@ -7720,22 +8253,49 @@ async function analyzeWithLLM(prompt, config) {
7720
8253
  { role: "system", content: "\u53EA\u8F93\u51FA\u7EAF JSON\uFF0C\u4E0D\u8981\u5305\u542B markdown \u6807\u8BB0\u3001\u4EE3\u7801\u5757\u6216\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002" },
7721
8254
  { role: "user", content: prompt }
7722
8255
  ],
7723
- signal: abortController.signal
8256
+ signal: abortController.signal,
8257
+ // 私有化网关的额外参数(关思考等)原样透传;空则不传。
8258
+ ...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
7724
8259
  });
7725
8260
  const message = response.choices[0]?.message;
7726
8261
  const content = message?.content ?? "";
7727
8262
  const finishReason = response.choices[0]?.finish_reason;
7728
- const reasoningLen = typeof message?.reasoning_content === "string" ? message.reasoning_content.length : 0;
8263
+ const fieldLengths = responseFieldLengths(message);
7729
8264
  const usage = response.usage;
7730
8265
  if (!content) {
7731
- 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 ?? "?"}`;
8266
+ 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 ?? "?"}`;
8267
+ traceFull("l3.empty_response", {
8268
+ model: response.model || config.model,
8269
+ finish_reason: finishReason,
8270
+ message,
8271
+ prompt_tokens: usage?.prompt_tokens ?? 0,
8272
+ completion_tokens: usage?.completion_tokens ?? 0
8273
+ });
8274
+ let fullMessage = "<empty>";
8275
+ try {
8276
+ fullMessage = JSON.stringify(message ?? {});
8277
+ if (fullMessage.length > 8e3) {
8278
+ fullMessage = `${fullMessage.slice(0, 8e3)}...[truncated ${fullMessage.length} chars]`;
8279
+ }
8280
+ } catch {
8281
+ fullMessage = "<\u65E0\u6CD5\u5E8F\u5217\u5316>";
8282
+ }
7732
8283
  if (finishReason === "length") {
7733
- console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
8284
+ console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
7734
8285
  throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
7735
8286
  }
7736
- console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
8287
+ console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail} | \u5B8C\u6574\u54CD\u5E94: ${fullMessage}`);
8288
+ _recordLlm("empty");
7737
8289
  throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
7738
8290
  }
8291
+ traceFull("l3.response", {
8292
+ phase: "security_judge",
8293
+ attempt: attempt + 1,
8294
+ model: response.model || config.model,
8295
+ content,
8296
+ prompt_tokens: usage?.prompt_tokens ?? 0,
8297
+ completion_tokens: usage?.completion_tokens ?? 0
8298
+ });
7739
8299
  console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
7740
8300
  let jsonStr = content.trim();
7741
8301
  if (jsonStr.startsWith("```")) {
@@ -7766,6 +8326,8 @@ async function analyzeWithLLM(prompt, config) {
7766
8326
  clearTimeout(totalTimeoutTimer);
7767
8327
  const riskLevel = parsed.riskLevel ?? parsed.risk_level;
7768
8328
  const riskType = parsed.riskType ?? parsed.risk_type;
8329
+ breaker.recordSuccess();
8330
+ _recordLlm("success");
7769
8331
  return {
7770
8332
  allowed: parsed.allowed !== false,
7771
8333
  reason: parsed.reason || "LLM \u5206\u6790\u5B8C\u6210",
@@ -7776,6 +8338,7 @@ async function analyzeWithLLM(prompt, config) {
7776
8338
  violatedLayers: ["L3.1"]
7777
8339
  };
7778
8340
  } catch (err) {
8341
+ breaker.recordFailure();
7779
8342
  if (abortController.signal.aborted) {
7780
8343
  console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
7781
8344
  break;
@@ -7808,6 +8371,9 @@ var init_llm_analyzer = __esm({
7808
8371
  init_template_loader();
7809
8372
  init_script_analyzer();
7810
8373
  init_script_content_analyzer();
8374
+ init_trace_log();
8375
+ init_metrics();
8376
+ init_circuit_breaker();
7811
8377
  llmCache = /* @__PURE__ */ new Map();
7812
8378
  LLM_CACHE_MAX = 200;
7813
8379
  }
@@ -7846,8 +8412,8 @@ var init_rule_store = __esm({
7846
8412
  BrainRuleStore = class {
7847
8413
  path;
7848
8414
  data;
7849
- constructor(path6) {
7850
- this.path = path6 || getRulesPath();
8415
+ constructor(path7) {
8416
+ this.path = path7 || getRulesPath();
7851
8417
  this.data = this.load();
7852
8418
  }
7853
8419
  load() {
@@ -8300,10 +8866,10 @@ ${reason.slice(0, 500)}
8300
8866
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
8301
8867
  let mm;
8302
8868
  while ((mm = pathRe.exec(src)) !== null) {
8303
- const path6 = mm[1];
8304
- if (path6.split("/").length < 3) continue;
8305
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path6)) continue;
8306
- const gen = this.generalizePath(path6);
8869
+ const path7 = mm[1];
8870
+ if (path7.split("/").length < 3) continue;
8871
+ if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path7)) continue;
8872
+ const gen = this.generalizePath(path7);
8307
8873
  if (seen.has(gen)) continue;
8308
8874
  seen.add(gen);
8309
8875
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -8322,8 +8888,8 @@ ${reason.slice(0, 500)}
8322
8888
  }
8323
8889
  return false;
8324
8890
  }
8325
- generalizePath(path6) {
8326
- const p = path6.toLowerCase();
8891
+ generalizePath(path7) {
8892
+ const p = path7.toLowerCase();
8327
8893
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
8328
8894
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
8329
8895
  }
@@ -8914,38 +9480,38 @@ function labelEvent(actionDetail) {
8914
9480
  }
8915
9481
  return hits;
8916
9482
  }
8917
- function evaluateLTL(formula, trace, pos) {
9483
+ function evaluateLTL(formula, trace2, pos) {
8918
9484
  const op = formula[0];
8919
9485
  switch (op) {
8920
9486
  case "ap":
8921
- return trace[pos].has(formula[1]);
9487
+ return trace2[pos].has(formula[1]);
8922
9488
  case "!":
8923
- return !evaluateLTL(formula[1], trace, pos);
9489
+ return !evaluateLTL(formula[1], trace2, pos);
8924
9490
  case "&":
8925
- return evaluateLTL(formula[1], trace, pos) && evaluateLTL(formula[2], trace, pos);
9491
+ return evaluateLTL(formula[1], trace2, pos) && evaluateLTL(formula[2], trace2, pos);
8926
9492
  case "|":
8927
- return evaluateLTL(formula[1], trace, pos) || evaluateLTL(formula[2], trace, pos);
9493
+ return evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
8928
9494
  case "->":
8929
- return !evaluateLTL(formula[1], trace, pos) || evaluateLTL(formula[2], trace, pos);
9495
+ return !evaluateLTL(formula[1], trace2, pos) || evaluateLTL(formula[2], trace2, pos);
8930
9496
  case "X":
8931
- return pos + 1 < trace.length && evaluateLTL(formula[1], trace, pos + 1);
9497
+ return pos + 1 < trace2.length && evaluateLTL(formula[1], trace2, pos + 1);
8932
9498
  case "G": {
8933
- for (let j = pos; j < trace.length; j++) {
8934
- if (!evaluateLTL(formula[1], trace, j)) return false;
9499
+ for (let j = pos; j < trace2.length; j++) {
9500
+ if (!evaluateLTL(formula[1], trace2, j)) return false;
8935
9501
  }
8936
9502
  return true;
8937
9503
  }
8938
9504
  case "F": {
8939
- for (let j = pos; j < trace.length; j++) {
8940
- if (evaluateLTL(formula[1], trace, j)) return true;
9505
+ for (let j = pos; j < trace2.length; j++) {
9506
+ if (evaluateLTL(formula[1], trace2, j)) return true;
8941
9507
  }
8942
9508
  return false;
8943
9509
  }
8944
9510
  case "U": {
8945
- for (let j = pos; j < trace.length; j++) {
8946
- if (evaluateLTL(formula[2], trace, j)) {
9511
+ for (let j = pos; j < trace2.length; j++) {
9512
+ if (evaluateLTL(formula[2], trace2, j)) {
8947
9513
  for (let k = pos; k < j; k++) {
8948
- if (!evaluateLTL(formula[1], trace, k)) return false;
9514
+ if (!evaluateLTL(formula[1], trace2, k)) return false;
8949
9515
  }
8950
9516
  return true;
8951
9517
  }
@@ -8974,11 +9540,11 @@ function checkMCRules(graph) {
8974
9540
  const mc = loadMC();
8975
9541
  const rules = mc.rules || [];
8976
9542
  if (rules.length === 0) return violations;
8977
- const trace = nodes.map((n) => labelEvent(n.actionDetail));
9543
+ const trace2 = nodes.map((n) => labelEvent(n.actionDetail));
8978
9544
  const witnessMode = graph.witnessIdx !== void 0;
8979
9545
  for (const rule of rules) {
8980
9546
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
8981
- if (ruleViolates(rule, trace, witnessMode)) {
9547
+ if (ruleViolates(rule, trace2, witnessMode)) {
8982
9548
  violations.push({
8983
9549
  propertyId: String(rule.id || "mc-ltl"),
8984
9550
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
@@ -9169,12 +9735,12 @@ var init_builder = __esm({
9169
9735
  });
9170
9736
 
9171
9737
  // src/engine/formal-engine/properties.ts
9172
- function graphFromPath(nodes, path6, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
9738
+ function graphFromPath(nodes, path7, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
9173
9739
  const byKey = /* @__PURE__ */ new Map();
9174
9740
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
9175
9741
  const gNodes = [];
9176
9742
  const gEdges = [];
9177
- for (const item of path6) {
9743
+ for (const item of path7) {
9178
9744
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
9179
9745
  gNodes.push({
9180
9746
  session_id: item.sessionId,
@@ -9240,22 +9806,22 @@ function checkCrossSessionChain(graph) {
9240
9806
  if (witness !== void 0) {
9241
9807
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
9242
9808
  let matched = 0;
9243
- const path6 = [];
9809
+ const path7 = [];
9244
9810
  for (let k = 0; k < witness; k++) {
9245
9811
  const n = nodes[k];
9246
9812
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
9247
9813
  matched += 1;
9248
- path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9814
+ path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9249
9815
  }
9250
9816
  }
9251
9817
  if (matched < stages.length - 1) continue;
9252
- path6.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
9818
+ path7.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
9253
9819
  violations.push({
9254
9820
  propertyId: "cross-" + chain.id,
9255
9821
  reason: chain.reason,
9256
9822
  riskLevel: chain.riskLevel,
9257
- path: path6,
9258
- graph: graphFromPath(nodes, path6, "next", {
9823
+ path: path7,
9824
+ graph: graphFromPath(nodes, path7, "next", {
9259
9825
  property_id: "cross-" + chain.id,
9260
9826
  property_short: "P1",
9261
9827
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -9265,11 +9831,11 @@ function checkCrossSessionChain(graph) {
9265
9831
  } else {
9266
9832
  let matched = 0;
9267
9833
  let stageIdx = 0;
9268
- const path6 = [];
9834
+ const path7 = [];
9269
9835
  for (const n of nodes) {
9270
9836
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
9271
9837
  matched += 1;
9272
- path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9838
+ path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9273
9839
  stageIdx += 1;
9274
9840
  if (matched >= stages.length) break;
9275
9841
  }
@@ -9279,8 +9845,8 @@ function checkCrossSessionChain(graph) {
9279
9845
  propertyId: "cross-" + chain.id,
9280
9846
  reason: chain.reason,
9281
9847
  riskLevel: chain.riskLevel,
9282
- path: path6,
9283
- graph: graphFromPath(nodes, path6, "next", {
9848
+ path: path7,
9849
+ graph: graphFromPath(nodes, path7, "next", {
9284
9850
  property_id: "cross-" + chain.id,
9285
9851
  property_short: "P1",
9286
9852
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -9327,7 +9893,7 @@ function checkSensitiveDataFlow(graph) {
9327
9893
  }
9328
9894
  }
9329
9895
  }
9330
- const tracePath = (idx) => {
9896
+ const tracePath2 = (idx) => {
9331
9897
  const chain = [idx];
9332
9898
  const seen = /* @__PURE__ */ new Set([idx]);
9333
9899
  while (true) {
@@ -9386,7 +9952,7 @@ function checkSensitiveDataFlow(graph) {
9386
9952
  for (const i of candidates) {
9387
9953
  const n = nodes[i];
9388
9954
  if (tainted.has(i) && EXFIL_RE.test(n.actionDetail)) {
9389
- const chain = tracePath(i);
9955
+ const chain = tracePath2(i);
9390
9956
  violations.push({
9391
9957
  propertyId: "sensitive-data-flow",
9392
9958
  reason: `\u654F\u611F\u6570\u636E\u4F20\u64AD\u5916\u4F20\uFF1A${tainted.get(i).source} \u2192 ${n.sessionId}#${n.seq} \u7ECF\u5171\u4EAB\u8F7D\u4F53\u5916\u53D1`,
@@ -9501,7 +10067,7 @@ function checkNeverExfilAfterPrivesc(graph) {
9501
10067
  if (candidates.length > 0) {
9502
10068
  const pre = nodes[candidates[candidates.length - 1]];
9503
10069
  const post = nodes[firstEv];
9504
- const path6 = [
10070
+ const path7 = [
9505
10071
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
9506
10072
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
9507
10073
  ];
@@ -9509,8 +10075,8 @@ function checkNeverExfilAfterPrivesc(graph) {
9509
10075
  propertyId: "no-exfil-after-privesc",
9510
10076
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
9511
10077
  riskLevel: "critical",
9512
- path: path6,
9513
- graph: graphFromPath(nodes, path6, "next", {
10078
+ path: path7,
10079
+ graph: graphFromPath(nodes, path7, "next", {
9514
10080
  property_id: "no-exfil-after-privesc",
9515
10081
  property_short: "P4",
9516
10082
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -9527,7 +10093,7 @@ function checkNeverExfilAfterPrivesc(graph) {
9527
10093
  for (let j = i + 1; j < nodes.length; j++) {
9528
10094
  if (!isExfilNode(nodes[j])) continue;
9529
10095
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
9530
- const path6 = [
10096
+ const path7 = [
9531
10097
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
9532
10098
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
9533
10099
  ];
@@ -9535,8 +10101,8 @@ function checkNeverExfilAfterPrivesc(graph) {
9535
10101
  propertyId: "no-exfil-after-privesc",
9536
10102
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
9537
10103
  riskLevel: "critical",
9538
- path: path6,
9539
- graph: graphFromPath(nodes, path6, "next", {
10104
+ path: path7,
10105
+ graph: graphFromPath(nodes, path7, "next", {
9540
10106
  property_id: "no-exfil-after-privesc",
9541
10107
  property_short: "P4",
9542
10108
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -9568,7 +10134,7 @@ function checkNeverExfilAfterCred(graph) {
9568
10134
  }
9569
10135
  if (pre) {
9570
10136
  const post = nodes[firstEv];
9571
- const path6 = [
10137
+ const path7 = [
9572
10138
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
9573
10139
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
9574
10140
  ];
@@ -9576,8 +10142,8 @@ function checkNeverExfilAfterCred(graph) {
9576
10142
  propertyId: "no-exfil-after-credential",
9577
10143
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
9578
10144
  riskLevel: "critical",
9579
- path: path6,
9580
- graph: graphFromPath(nodes, path6, "data", {
10145
+ path: path7,
10146
+ graph: graphFromPath(nodes, path7, "data", {
9581
10147
  property_id: "no-exfil-after-credential",
9582
10148
  property_short: "P5",
9583
10149
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -9593,7 +10159,7 @@ function checkNeverExfilAfterCred(graph) {
9593
10159
  if (!isCredNode(nodes[i])) continue;
9594
10160
  for (let j = i + 1; j < nodes.length; j++) {
9595
10161
  if (isExfilNode(nodes[j])) {
9596
- const path6 = [
10162
+ const path7 = [
9597
10163
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
9598
10164
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
9599
10165
  ];
@@ -9601,8 +10167,8 @@ function checkNeverExfilAfterCred(graph) {
9601
10167
  propertyId: "no-exfil-after-credential",
9602
10168
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
9603
10169
  riskLevel: "critical",
9604
- path: path6,
9605
- graph: graphFromPath(nodes, path6, "data", {
10170
+ path: path7,
10171
+ graph: graphFromPath(nodes, path7, "data", {
9606
10172
  property_id: "no-exfil-after-credential",
9607
10173
  property_short: "P5",
9608
10174
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -9761,13 +10327,13 @@ function checkSensitiveDataAggregation(graph) {
9761
10327
  if (!isExfilNode(n)) continue;
9762
10328
  const srcs = sourcesFor(i);
9763
10329
  if (srcs.size >= 2) {
9764
- const path6 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10330
+ const path7 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
9765
10331
  violations.push({
9766
10332
  propertyId: "sensitive-data-aggregation",
9767
10333
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
9768
10334
  riskLevel: "critical",
9769
- path: path6,
9770
- graph: graphFromPath(nodes, path6, "next", {
10335
+ path: path7,
10336
+ graph: graphFromPath(nodes, path7, "next", {
9771
10337
  property_id: "sensitive-data-aggregation",
9772
10338
  property_short: "P8",
9773
10339
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -10226,11 +10792,11 @@ var init_stateful = __esm({
10226
10792
  }
10227
10793
  }
10228
10794
  chainPath(stages) {
10229
- const path6 = [];
10795
+ const path7 = [];
10230
10796
  let want = stages[0];
10231
10797
  for (const n of this.nodes_) {
10232
10798
  if (n.stage === want) {
10233
- path6.push({
10799
+ path7.push({
10234
10800
  sessionId: n.sessionId,
10235
10801
  seq: n.seq,
10236
10802
  stage: n.stage,
@@ -10246,12 +10812,12 @@ var init_stateful = __esm({
10246
10812
  }
10247
10813
  }
10248
10814
  }
10249
- return path6;
10815
+ return path7;
10250
10816
  }
10251
10817
  /** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
10252
10818
  buildChainGraph(stages, chainId) {
10253
- const path6 = this.chainPath(stages);
10254
- const gNodes = path6.map((p, i) => {
10819
+ const path7 = this.chainPath(stages);
10820
+ const gNodes = path7.map((p, i) => {
10255
10821
  const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
10256
10822
  return {
10257
10823
  session_id: p.sessionId,
@@ -10502,16 +11068,42 @@ var init_stateful = __esm({
10502
11068
  });
10503
11069
 
10504
11070
  // src/engine/formal-engine/chain_state.ts
10505
- import * as fs4 from "fs";
11071
+ import * as fs5 from "fs";
10506
11072
  import * as os2 from "os";
10507
- import * as path4 from "path";
11073
+ import * as path5 from "path";
10508
11074
  import { createHash as createHash4 } from "crypto";
10509
11075
  function defaultStateDbPath() {
10510
- const dir = process.env.AGENT_MOSS_STATE_DIR || path4.join(os2.homedir(), ".agentmoss");
11076
+ const dir = process.env.AGENT_MOSS_STATE_DIR || path5.join(os2.homedir(), ".agentmoss");
10511
11077
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
10512
- return path4.join(dir, `stateful_chains_${tag}.json`);
11078
+ return path5.join(dir, `stateful_chains_${tag}.json`);
10513
11079
  }
10514
- var ChainStateStore;
11080
+ function registerExitFlush(store) {
11081
+ if (_exitHookRegistered) return;
11082
+ _exitHookRegistered = true;
11083
+ const flush = () => {
11084
+ try {
11085
+ store.flush();
11086
+ } catch {
11087
+ }
11088
+ };
11089
+ process.once("exit", flush);
11090
+ process.once("SIGINT", () => {
11091
+ flush();
11092
+ process.exit(0);
11093
+ });
11094
+ process.once("SIGTERM", () => {
11095
+ flush();
11096
+ process.exit(0);
11097
+ });
11098
+ }
11099
+ function getChainStateStore(filePath = "") {
11100
+ if (_store === null || filePath && filePath !== _store["filePath"]) {
11101
+ _store = new ChainStateStore(filePath);
11102
+ registerExitFlush(_store);
11103
+ }
11104
+ return _store;
11105
+ }
11106
+ var ChainStateStore, _store, _exitHookRegistered;
10515
11107
  var init_chain_state = __esm({
10516
11108
  "src/engine/formal-engine/chain_state.ts"() {
10517
11109
  "use strict";
@@ -10522,15 +11114,40 @@ var init_chain_state = __esm({
10522
11114
  filePath;
10523
11115
  data;
10524
11116
  _timer = null;
10525
- _flushDelayMs = 50;
11117
+ /**
11118
+ * 落盘防抖间隔。**与 Python 端对齐为 1 秒**(2026-11 长稳实测)。
11119
+ *
11120
+ * 原来是 50ms:Node 是单线程,`_syncDirtyToData` 里的 `toSnapshot()` 是
11121
+ * O(节点数) 的全量构建(2 万节点约 40ms),50ms 触发一次等于 80% 的时间
11122
+ * 在序列化,请求全被卡住。1 秒一次把开销摊薄 20 倍;崩溃最坏丢 1 秒增量,
11123
+ * 与 Python 端同一量级。
11124
+ */
11125
+ _flushDelayMs = 1e3;
11126
+ /**
11127
+ * 内存中的 tracker(唯一事实源)。2026-11 与 Python 端对齐:
11128
+ * 旧实现每次 applyAction 都 `restore(entry.state)` 重建所有节点 +
11129
+ * `toSnapshot()` 全量序列化,O(节点数);长时间运行后每次调用几十到几百毫秒,
11130
+ * 在 Node 单线程上等于把事件循环卡死。现在 apply 只改内存对象,序列化推迟到
11131
+ * 防抖落盘时批量做。
11132
+ */
11133
+ _trackers = /* @__PURE__ */ new Map();
11134
+ /** 自上次落盘以来变过的 agentId */
11135
+ _dirty = /* @__PURE__ */ new Set();
11136
+ /**
11137
+ * 多进程模式(2026-11,对齐 Python `enable_multi_process`):
11138
+ * AGENT_MOSS_MULTI_PROCESS=1 时启用。Node cluster / PM2 多进程部署下,
11139
+ * 各进程的 `data` 是独立快照,防抖写会互相覆盖(JSON 文件没有 SQLite 那样的锁)。
11140
+ * 启用后:每次 applyAction 用**文件锁**串行化,锁内重新读文件 → 判定 → 立即写。
11141
+ */
11142
+ _multiProcess = false;
10526
11143
  constructor(filePath = "") {
10527
11144
  this.filePath = filePath || defaultStateDbPath();
10528
11145
  this.data = this._read();
10529
11146
  }
10530
11147
  _read() {
10531
11148
  try {
10532
- if (fs4.existsSync(this.filePath)) {
10533
- const raw = fs4.readFileSync(this.filePath, "utf-8");
11149
+ if (fs5.existsSync(this.filePath)) {
11150
+ const raw = fs5.readFileSync(this.filePath, "utf-8");
10534
11151
  return JSON.parse(raw);
10535
11152
  }
10536
11153
  } catch {
@@ -10543,12 +11160,22 @@ var init_chain_state = __esm({
10543
11160
  this._timer = setTimeout(() => {
10544
11161
  this._timer = null;
10545
11162
  try {
10546
- ensurePrivateDir(path4.dirname(this.filePath));
11163
+ this._syncDirtyToData();
11164
+ ensurePrivateDir(path5.dirname(this.filePath));
10547
11165
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
10548
11166
  } catch {
10549
11167
  }
10550
11168
  }, this._flushDelayMs);
10551
11169
  }
11170
+ /** 把 dirty 的 tracker 序列化进 data(只在落盘时做,避免每次 apply 都 O(n))。 */
11171
+ _syncDirtyToData() {
11172
+ for (const agentId of this._dirty) {
11173
+ const t = this._trackers.get(agentId);
11174
+ if (!t) continue;
11175
+ this.data[agentId] = { state: t.toSnapshot(), updated_at: (/* @__PURE__ */ new Date()).toISOString() };
11176
+ }
11177
+ this._dirty.clear();
11178
+ }
10552
11179
  /** 立即落盘(测试/关停前调用,保证状态不丢)。 */
10553
11180
  flush() {
10554
11181
  if (this._timer !== null) {
@@ -10556,30 +11183,100 @@ var init_chain_state = __esm({
10556
11183
  this._timer = null;
10557
11184
  }
10558
11185
  try {
10559
- ensurePrivateDir(path4.dirname(this.filePath));
11186
+ this._syncDirtyToData();
11187
+ ensurePrivateDir(path5.dirname(this.filePath));
10560
11188
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
10561
11189
  } catch {
10562
11190
  }
10563
11191
  }
10564
11192
  load(agentId) {
11193
+ const cached2 = this._trackers.get(agentId);
11194
+ if (cached2) return cached2;
10565
11195
  const entry = this.data[agentId];
10566
11196
  if (!entry) return null;
10567
11197
  const t = new StatefulChainTracker(agentId);
10568
11198
  t.restore(entry.state);
11199
+ this._trackers.set(agentId, t);
10569
11200
  return t;
10570
11201
  }
10571
11202
  save(tracker) {
10572
- this.data[tracker.agentId] = {
10573
- state: tracker.toSnapshot(),
10574
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
10575
- };
11203
+ this._trackers.set(tracker.agentId, tracker);
11204
+ this._dirty.add(tracker.agentId);
10576
11205
  this._scheduleWrite();
10577
11206
  }
10578
11207
  delete(agentId) {
11208
+ this._trackers.delete(agentId);
11209
+ this._dirty.delete(agentId);
10579
11210
  delete this.data[agentId];
10580
11211
  this._scheduleWrite();
10581
11212
  }
11213
+ /** 启用多进程模式(对齐 Python)。 */
11214
+ enableMultiProcess() {
11215
+ this._multiProcess = true;
11216
+ }
11217
+ /**
11218
+ * 同步文件锁(原子创建 `<file>.lock`)。
11219
+ *
11220
+ * Node 是单线程,锁竞争时用 Atomics.wait 做**同步睡眠**而不是忙等 ——
11221
+ * 忙等会把事件循环完全占死,其它请求也没法推进。
11222
+ */
11223
+ _withFileLock(fn) {
11224
+ const lockPath = `${this.filePath}.lock`;
11225
+ const sleepBuf = new Int32Array(new SharedArrayBuffer(4));
11226
+ for (let attempt = 0; attempt < 100; attempt++) {
11227
+ try {
11228
+ const fd = fs5.openSync(lockPath, "wx");
11229
+ try {
11230
+ return fn();
11231
+ } finally {
11232
+ try {
11233
+ fs5.closeSync(fd);
11234
+ } catch {
11235
+ }
11236
+ try {
11237
+ fs5.unlinkSync(lockPath);
11238
+ } catch {
11239
+ }
11240
+ }
11241
+ } catch (e) {
11242
+ if (e?.code !== "EEXIST") throw e;
11243
+ try {
11244
+ Atomics.wait(sleepBuf, 0, 0, 20);
11245
+ } catch {
11246
+ }
11247
+ }
11248
+ }
11249
+ throw new Error(`chain state lock timeout: ${lockPath}`);
11250
+ }
11251
+ /** 立即把内存写进文件(多进程模式用,不走防抖)。 */
11252
+ _flushNow() {
11253
+ this._syncDirtyToData();
11254
+ try {
11255
+ const _dirOk = ensurePrivateDir(path5.dirname(this.filePath));
11256
+ const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11257
+ if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
11258
+ } catch (e) {
11259
+ console.error("[AgentMoss] chain state flush failed:", e?.message || e);
11260
+ }
11261
+ }
11262
+ /** 当前内存中的 tracker 数 / 节点总数(健康检查用)。 */
11263
+ stats() {
11264
+ let nodes = 0;
11265
+ for (const t of this._trackers.values()) nodes += t.nodes.length;
11266
+ return { agents: this._trackers.size, nodes };
11267
+ }
10582
11268
  applyAction(agentId, aNext, sessionId, isError = false, sourceAgent = "", instanceId = "") {
11269
+ if (this._multiProcess) {
11270
+ return this._withFileLock(() => {
11271
+ this.data = this._read();
11272
+ this._trackers.clear();
11273
+ const t2 = this.load(agentId) || new StatefulChainTracker(agentId);
11274
+ const r2 = t2.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
11275
+ this.save(t2);
11276
+ this._flushNow();
11277
+ return r2;
11278
+ });
11279
+ }
10583
11280
  const t = this.load(agentId) || new StatefulChainTracker(agentId);
10584
11281
  const r = t.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
10585
11282
  this.save(t);
@@ -10593,6 +11290,8 @@ var init_chain_state = __esm({
10593
11290
  return r;
10594
11291
  }
10595
11292
  };
11293
+ _store = null;
11294
+ _exitHookRegistered = false;
10596
11295
  }
10597
11296
  });
10598
11297
 
@@ -10700,6 +11399,14 @@ function _resetBrainForTest() {
10700
11399
  async function runAnalysis(input) {
10701
11400
  const observedFormalLayers = [];
10702
11401
  const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
11402
+ if (heuristicResult) {
11403
+ traceSummary("l1.result", {
11404
+ hit: !heuristicResult.allowed,
11405
+ risk_level: heuristicResult.riskLevel,
11406
+ risk_type: heuristicResult.riskType,
11407
+ reason: heuristicResult.reason
11408
+ });
11409
+ }
10703
11410
  const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
10704
11411
  const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
10705
11412
  if (heuristicResult && !heuristicResult.allowed) {
@@ -10843,6 +11550,14 @@ async function runAnalysis(input) {
10843
11550
  }
10844
11551
  }
10845
11552
  const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
11553
+ if (logicResult) {
11554
+ traceSummary("l2.result", {
11555
+ hit: !logicResult.allowed,
11556
+ risk_level: logicResult.riskLevel,
11557
+ risk_type: logicResult.riskType,
11558
+ reason: logicResult.reason
11559
+ });
11560
+ }
10846
11561
  const l1FileAccessHit = !!(heuristicResult && !heuristicResult.allowed && heuristicResult.riskType === "file_access");
10847
11562
  const effectiveResult = logicResult && !logicResult.allowed ? logicResult : l1FileAccessHit ? heuristicResult : null;
10848
11563
  if (effectiveResult) {
@@ -11072,6 +11787,7 @@ var init_coordinator = __esm({
11072
11787
  init_llm_analyzer();
11073
11788
  init_script_content_analyzer();
11074
11789
  init_config();
11790
+ init_trace_log();
11075
11791
  init_runtime_config();
11076
11792
  init_agents();
11077
11793
  init_scenarios();
@@ -11308,6 +12024,8 @@ var AnalyzeResponseSchema = z.object({
11308
12024
  analysis_duration_ms: z.number().default(0),
11309
12025
  // 组合攻击链反例路径:每步 [session_id, seq, stage, timestamp],含真实发生时间
11310
12026
  violation_chain: z.array(z.array(z.union([z.string(), z.number()]).nullable())).default([]),
12027
+ // 本次判定的能力降级说明(2026-11):正常为空;链状态触顶时说明 L2.2 未覆盖
12028
+ degraded: z.array(z.string()).default([]),
11311
12029
  // 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
11312
12030
  violation_graph: z.object({
11313
12031
  // 性质元信息(前端展示"违反了哪条性质")
@@ -11347,12 +12065,18 @@ var AnalyzeResponseSchema = z.object({
11347
12065
  }).nullable().default(null)
11348
12066
  });
11349
12067
  var HealthResponseSchema = z.object({
12068
+ // healthy | degraded(2026-11):degraded 表示服务可用但**某项安全能力已降级**
12069
+ // (链状态触顶、LLM 熔断)。任何探活/监控只看 status 就能发现异常。
11350
12070
  status: z.string().default("healthy"),
12071
+ // 降级原因(status=degraded 时非空)
12072
+ degraded: z.array(z.string()).default([]),
11351
12073
  version: z.string().default(version),
11352
12074
  // 归属实例标识:值来自 env AGENT_MOSS_INSTANCE(spawn/systemd 注入),默认空串。
11353
12075
  // 多个 agentmoss 同机并存时,调用方按 instance 过滤避免连到别人的进程。
11354
12076
  // 空=未配置(独立部署或旧版),调用方可选择兼容或严格过滤。
11355
- instance: z.string().default("")
12077
+ instance: z.string().default(""),
12078
+ // 运行态指标(2026-11 增强):事件循环延迟、并发池占用、链状态规模。
12079
+ metrics: z.record(z.unknown()).default({})
11356
12080
  });
11357
12081
  var ReviewRequestSchema = z.object({
11358
12082
  agent_id: z.string().default("").describe("\u76EE\u6807 agent \u6807\u8BC6\uFF08\u51B3\u5B9A\u72B6\u6001\u5E93\u5206\u6876\uFF09"),
@@ -11389,7 +12113,7 @@ init_security_policy();
11389
12113
  init_paths();
11390
12114
  init_config();
11391
12115
  import { createHash as createHash5 } from "crypto";
11392
- import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync3 } from "fs";
12116
+ import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
11393
12117
  import { tmpdir as tmpdir2 } from "os";
11394
12118
  import { join as join15 } from "path";
11395
12119
  var CACHE_DIR = join15(tmpdir2(), "agent_moss_policy_cache");
@@ -11471,7 +12195,7 @@ var PolicyCache = class {
11471
12195
  invalidate(sessionId, promptSession) {
11472
12196
  this.memory.delete(this.cacheKey(sessionId, promptSession));
11473
12197
  try {
11474
- unlinkSync3(this.cacheFilePath(sessionId, promptSession));
12198
+ unlinkSync4(this.cacheFilePath(sessionId, promptSession));
11475
12199
  } catch {
11476
12200
  }
11477
12201
  }
@@ -11485,7 +12209,7 @@ var PolicyCache = class {
11485
12209
  if (existsSync17(dir)) {
11486
12210
  for (const f of readdirSync5(dir)) {
11487
12211
  try {
11488
- unlinkSync3(join15(dir, f));
12212
+ unlinkSync4(join15(dir, f));
11489
12213
  } catch {
11490
12214
  }
11491
12215
  }
@@ -11501,7 +12225,7 @@ var PolicyCache = class {
11501
12225
  for (const sessionDir of readdirSync5(cacheDir())) {
11502
12226
  const dir = join15(cacheDir(), sessionDir);
11503
12227
  try {
11504
- for (const f of readdirSync5(dir)) unlinkSync3(join15(dir, f));
12228
+ for (const f of readdirSync5(dir)) unlinkSync4(join15(dir, f));
11505
12229
  rmdirSync(dir);
11506
12230
  } catch {
11507
12231
  }
@@ -11833,7 +12557,7 @@ async function analyzeInner(input, mossLog) {
11833
12557
 
11834
12558
  // src/actrail.ts
11835
12559
  init_esm_shims();
11836
- import * as fs5 from "fs";
12560
+ import * as fs6 from "fs";
11837
12561
 
11838
12562
  // src/infra/esm-require.ts
11839
12563
  init_esm_shims();
@@ -11864,7 +12588,7 @@ function getStoragePath() {
11864
12588
  function reportEnforcementEvent(opts) {
11865
12589
  if (!isEnabled()) return false;
11866
12590
  const storagePath = getStoragePath();
11867
- if (!fs5.existsSync(storagePath)) return false;
12591
+ if (!fs6.existsSync(storagePath)) return false;
11868
12592
  try {
11869
12593
  let Database;
11870
12594
  try {
@@ -11944,6 +12668,7 @@ function reportEnforcementEvent(opts) {
11944
12668
 
11945
12669
  // src/routes.ts
11946
12670
  init_formal_engine();
12671
+ init_circuit_breaker();
11947
12672
 
11948
12673
  // src/engine/formal-engine/pattern_miner.ts
11949
12674
  init_esm_shims();
@@ -12026,10 +12751,10 @@ function mineDangerousPatterns(sessions, minSup = 2, maxLen = 4) {
12026
12751
 
12027
12752
  // src/agent-gate-reader.ts
12028
12753
  init_esm_shims();
12029
- import * as fs6 from "fs";
12754
+ import * as fs7 from "fs";
12030
12755
  import * as os3 from "os";
12031
- import * as path5 from "path";
12032
- var DEFAULT_AGENTGATE_SQLITE = path5.join(
12756
+ import * as path6 from "path";
12757
+ var DEFAULT_AGENTGATE_SQLITE = path6.join(
12033
12758
  os3.homedir(),
12034
12759
  ".local",
12035
12760
  "share",
@@ -12045,10 +12770,10 @@ function normalizeAction(row) {
12045
12770
  function readJsonDir(dirPath, limit = 1e5) {
12046
12771
  const sessions = /* @__PURE__ */ new Map();
12047
12772
  try {
12048
- const files = fs6.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
12773
+ const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
12049
12774
  for (const f of files.slice(-200)) {
12050
12775
  const sid = f.replace(/\.json$/, "");
12051
- const raw = fs6.readFileSync(path5.join(dirPath, f), "utf-8");
12776
+ const raw = fs7.readFileSync(path6.join(dirPath, f), "utf-8");
12052
12777
  const arr = JSON.parse(raw);
12053
12778
  if (!Array.isArray(arr)) continue;
12054
12779
  for (const item of arr) {
@@ -12105,7 +12830,7 @@ function readSqlite(dbPath, limit = 1e5) {
12105
12830
  function loadAgentGateSessions(dbPath = "") {
12106
12831
  if (dbPath) {
12107
12832
  try {
12108
- if (fs6.statSync(dbPath).isDirectory()) {
12833
+ if (fs7.statSync(dbPath).isDirectory()) {
12109
12834
  return readJsonDir(dbPath);
12110
12835
  }
12111
12836
  } catch {
@@ -12116,7 +12841,7 @@ function loadAgentGateSessions(dbPath = "") {
12116
12841
  }
12117
12842
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
12118
12843
  if (sql.length > 0) return sql;
12119
- const jsonDefault = path5.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
12844
+ const jsonDefault = path6.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
12120
12845
  return readJsonDir(jsonDefault);
12121
12846
  }
12122
12847
 
@@ -12191,16 +12916,105 @@ function normalizeObservablePayload(body) {
12191
12916
  init_rule_store();
12192
12917
  init_skill_manager();
12193
12918
  init_asset_dir();
12919
+ init_trace_log();
12920
+
12921
+ // src/infra/loop-monitor.ts
12922
+ init_esm_shims();
12923
+ import { monitorEventLoopDelay } from "perf_hooks";
12924
+ var _histogram = null;
12925
+ var _timer = null;
12926
+ function startLoopMonitor() {
12927
+ if (_histogram !== null) return;
12928
+ _histogram = monitorEventLoopDelay({ resolution: 20 });
12929
+ _histogram.enable();
12930
+ _timer = setInterval(() => {
12931
+ try {
12932
+ _histogram?.reset();
12933
+ } catch {
12934
+ }
12935
+ }, 1e3);
12936
+ if (typeof _timer.unref === "function") _timer.unref();
12937
+ }
12938
+ function loopMonitorSnapshot() {
12939
+ if (_histogram === null) return {};
12940
+ try {
12941
+ const meanMs = _histogram.mean / 1e6;
12942
+ const maxMs = _histogram.max / 1e6;
12943
+ return {
12944
+ loop_lag_ms: Math.round(meanMs * 10) / 10,
12945
+ loop_lag_max_ms: Math.round(maxMs * 10) / 10
12946
+ };
12947
+ } catch {
12948
+ return {};
12949
+ }
12950
+ }
12951
+
12952
+ // src/infra/runtime-stats.ts
12953
+ init_esm_shims();
12954
+ var _pools = null;
12955
+ function registerPools(pools) {
12956
+ _pools = pools;
12957
+ }
12958
+ function poolsSnapshot() {
12959
+ try {
12960
+ return _pools ? _pools.snapshot() : {};
12961
+ } catch {
12962
+ return {};
12963
+ }
12964
+ }
12965
+
12966
+ // src/routes.ts
12967
+ init_metrics();
12194
12968
  import { join as join18, dirname as dirname12 } from "path";
12195
12969
  import { fileURLToPath as fileURLToPath10 } from "url";
12196
12970
  var __dirname9 = dirname12(fileURLToPath10(import.meta.url));
12197
12971
  async function healthRoute(c) {
12972
+ const metrics = {};
12973
+ try {
12974
+ Object.assign(metrics, loopMonitorSnapshot());
12975
+ } catch {
12976
+ }
12977
+ metrics.pools = poolsSnapshot();
12978
+ try {
12979
+ const chainStats = getChainStateStoreFor("").stats();
12980
+ metrics.chain_agents = chainStats.agents;
12981
+ metrics.chain_nodes = chainStats.nodes;
12982
+ metrics.chain_capacity = MAX_NODES;
12983
+ metrics.chain_usage_pct = Math.round(chainStats.nodes / MAX_NODES * 1e3) / 10;
12984
+ } catch {
12985
+ }
12986
+ const degraded = [];
12987
+ const pct = metrics.chain_usage_pct;
12988
+ if (typeof pct === "number") {
12989
+ if (pct >= 100) {
12990
+ degraded.push(
12991
+ `\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`
12992
+ );
12993
+ } else if (pct >= 90) {
12994
+ degraded.push(
12995
+ `\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`
12996
+ );
12997
+ }
12998
+ }
12999
+ try {
13000
+ const snap = getBreaker().snapshot();
13001
+ if (snap.state === "open") {
13002
+ degraded.push(
13003
+ `\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`
13004
+ );
13005
+ }
13006
+ } catch {
13007
+ }
12198
13008
  return c.json(HealthResponseSchema.parse({
12199
- instance: process.env.AGENT_MOSS_INSTANCE || ""
13009
+ status: degraded.length ? "degraded" : "healthy",
13010
+ degraded,
13011
+ instance: process.env.AGENT_MOSS_INSTANCE || "",
13012
+ metrics
12200
13013
  }));
12201
13014
  }
12202
13015
  async function analyzeRoute(c) {
12203
13016
  const t0 = performance.now();
13017
+ const degradedNotes = [];
12204
13018
  try {
12205
13019
  const body = await c.req.json();
12206
13020
  const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
@@ -12228,6 +13042,20 @@ async function analyzeRoute(c) {
12228
13042
  const instanceId = String(
12229
13043
  req.instance_id || req.metadata?.instance_id || ""
12230
13044
  );
13045
+ traceFull("request", {
13046
+ session_id: req.session_id,
13047
+ agent_id: agentId,
13048
+ os_type: osType,
13049
+ cwd: req.cwd,
13050
+ action_type: req.a_next.action_type,
13051
+ action_detail: req.a_next.action_detail,
13052
+ reason: req.reason,
13053
+ prompt_session: req.prompt_session,
13054
+ action_history: req.action_history,
13055
+ prompt_history: req.prompt_history,
13056
+ session_history: req.session_history,
13057
+ metadata: req.metadata
13058
+ });
12231
13059
  const result = await analyze({
12232
13060
  sessionId: req.session_id,
12233
13061
  promptSession: req.prompt_session,
@@ -12287,6 +13115,29 @@ async function analyzeRoute(c) {
12287
13115
  llmLogPath: req.metadata?.llm_log_path
12288
13116
  });
12289
13117
  const durationMs = performance.now() - t0;
13118
+ const slowMs = Number(process.env.AGENT_MOSS_SLOW_REQUEST_MS || "1000");
13119
+ if (Number.isFinite(slowMs) && slowMs > 0 && durationMs >= slowMs) {
13120
+ console.warn(
13121
+ `[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}`
13122
+ );
13123
+ }
13124
+ try {
13125
+ ANALYZE_TOTAL.inc(1, { decision: result.decision, risk_level: result.risk_level });
13126
+ ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
13127
+ for (const layer of result.violated_layers || []) {
13128
+ LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
13129
+ }
13130
+ } catch {
13131
+ }
13132
+ traceSummary("result", {
13133
+ session_id: req.session_id,
13134
+ decision: result.decision,
13135
+ risk_level: result.risk_level,
13136
+ risk_type: result.risk_type,
13137
+ reason: result.reason,
13138
+ violated_layers: result.violated_layers,
13139
+ duration_ms: Math.round(durationMs * 10) / 10
13140
+ });
12290
13141
  try {
12291
13142
  reportEnforcementEvent({
12292
13143
  traceId: req.session_id,
@@ -12318,6 +13169,20 @@ async function analyzeRoute(c) {
12318
13169
  // 来源:真实 agent(桶 key 可能是 __system__)
12319
13170
  instanceId
12320
13171
  );
13172
+ try {
13173
+ const total = store.stats().nodes;
13174
+ const pct = Math.round(total / MAX_NODES * 1e3) / 10;
13175
+ if (total >= MAX_NODES) {
13176
+ degradedNotes.push(
13177
+ `\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`
13178
+ );
13179
+ } else if (pct >= 90) {
13180
+ degradedNotes.push(
13181
+ `\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`
13182
+ );
13183
+ }
13184
+ } catch {
13185
+ }
12321
13186
  const judgment = incMatchedToDeny(inc);
12322
13187
  if (judgment) {
12323
13188
  const layers = [...result.violated_layers];
@@ -12360,7 +13225,9 @@ async function analyzeRoute(c) {
12360
13225
  confidence: result.confidence,
12361
13226
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
12362
13227
  violation_chain: result.violation_chain ?? [],
12363
- violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id)
13228
+ violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
13229
+ // 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
13230
+ degraded: degradedNotes
12364
13231
  })
12365
13232
  );
12366
13233
  } catch (err) {
@@ -12379,10 +13246,8 @@ async function analyzeRoute(c) {
12379
13246
  return c.json({ detail: `Internal server error (ref: ${ref})`, error: "Internal error" }, 500);
12380
13247
  }
12381
13248
  }
12382
- var reviewStore = null;
12383
13249
  function getChainStateStoreFor(_agentId) {
12384
- if (!reviewStore) reviewStore = new ChainStateStore();
12385
- return reviewStore;
13250
+ return getChainStateStore();
12386
13251
  }
12387
13252
  function incMatchedToDeny(inc) {
12388
13253
  if (inc.matched) {
@@ -12604,7 +13469,7 @@ init_asset_dir();
12604
13469
  init_rules_mode();
12605
13470
  import { Hono } from "hono";
12606
13471
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
12607
- import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync4 } from "fs";
13472
+ import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
12608
13473
  import { join as join19, dirname as dirname13 } from "path";
12609
13474
  import { fileURLToPath as fileURLToPath11 } from "url";
12610
13475
  var __dirname10 = dirname13(fileURLToPath11(import.meta.url));
@@ -12952,7 +13817,7 @@ function createConsoleRouter() {
12952
13817
  const defaults = generateSourceDefaults();
12953
13818
  try {
12954
13819
  const p = getRuntimeConfigPath();
12955
- if (existsSync20(p)) unlinkSync4(p);
13820
+ if (existsSync20(p)) unlinkSync5(p);
12956
13821
  } catch {
12957
13822
  }
12958
13823
  return c.json(withL22View(defaults));
@@ -12981,6 +13846,8 @@ function createConsoleRouter() {
12981
13846
 
12982
13847
  // src/server.ts
12983
13848
  init_runtime_config();
13849
+ init_metrics();
13850
+ init_formal_engine();
12984
13851
  init_rules_mode();
12985
13852
  init_rules_loader();
12986
13853
  function logDeploymentSelfCheck() {
@@ -13061,6 +13928,10 @@ var PooledLimiter = class {
13061
13928
  if (cur <= 1) this.counts.delete(key);
13062
13929
  else this.counts.set(key, cur - 1);
13063
13930
  }
13931
+ /** 当前各池占用快照(健康检查用,对齐 Python `_PooledLimiter.snapshot`)。 */
13932
+ snapshot() {
13933
+ return Object.fromEntries(this.counts);
13934
+ }
13064
13935
  };
13065
13936
  var RateLimiter = class {
13066
13937
  constructor(qps, burst) {
@@ -13089,6 +13960,13 @@ var RateLimiter = class {
13089
13960
  }
13090
13961
  };
13091
13962
  function createApp() {
13963
+ try {
13964
+ if (String(process.env.AGENT_MOSS_MULTI_PROCESS || "").toLowerCase() in { "1": 1, "true": 1, "yes": 1, "on": 1 }) {
13965
+ getChainStateStore().enableMultiProcess();
13966
+ console.log("[AgentMoss] \u94FE\u72B6\u6001\u591A\u8FDB\u7A0B\u6A21\u5F0F\uFF1A\u5DF2\u542F\u7528\uFF08\u6587\u4EF6\u9501 + \u7ACB\u5373\u843D\u76D8\uFF09");
13967
+ }
13968
+ } catch {
13969
+ }
13092
13970
  enforceRulesContract();
13093
13971
  hardenExistingPaths();
13094
13972
  const app = new Hono2();
@@ -13104,9 +13982,11 @@ function createApp() {
13104
13982
  )
13105
13983
  );
13106
13984
  const pools = new PooledLimiter();
13985
+ registerPools(pools);
13986
+ startLoopMonitor();
13107
13987
  const limiter = new RateLimiter(rateLimitQps());
13108
13988
  app.use("*", async (c, next) => {
13109
- const path6 = new URL(c.req.url).pathname;
13989
+ const path7 = new URL(c.req.url).pathname;
13110
13990
  const method = c.req.method.toUpperCase();
13111
13991
  if (method === "OPTIONS") return next();
13112
13992
  const maxBody = maxBodyBytes();
@@ -13120,16 +14000,16 @@ function createApp() {
13120
14000
  if (originCheckEnabled()) {
13121
14001
  const origin = c.req.header("origin") || "";
13122
14002
  if (origin && !originAllowed(origin, c.req.header("host") || "")) {
13123
- console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path6}`);
14003
+ console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path7}`);
13124
14004
  return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
13125
14005
  }
13126
14006
  }
13127
- const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path6);
13128
- const isPublicPage = !path6.startsWith("/console/api") && (path6 === "/console" || path6.startsWith("/console/"));
14007
+ const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path7);
14008
+ const isPublicPage = !path7.startsWith("/console/api") && (path7 === "/console" || path7.startsWith("/console/"));
13129
14009
  if (!okAuth && !isPublicPage) {
13130
14010
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
13131
14011
  }
13132
- if (limiter.enabled && path6.startsWith("/api/")) {
14012
+ if (limiter.enabled && path7.startsWith("/api/")) {
13133
14013
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
13134
14014
  if (!limiter.allow(key)) {
13135
14015
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
@@ -13163,7 +14043,7 @@ function createApp() {
13163
14043
  return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
13164
14044
  }
13165
14045
  }
13166
- const pool = poolOf(path6);
14046
+ const pool = poolOf(path7);
13167
14047
  if (!take(`pool:${pool}`, poolLimit(pool))) {
13168
14048
  const qkey = principal ? "p:" + principalHash(principal) : "c:local";
13169
14049
  const [qn, abusive] = noteQueueReject(qkey);
@@ -13180,6 +14060,23 @@ function createApp() {
13180
14060
  while (keys.length) pools.release(keys.pop());
13181
14061
  }
13182
14062
  });
14063
+ app.get("/metrics", (c) => {
14064
+ let chainNodes;
14065
+ try {
14066
+ chainNodes = getChainStateStore().stats().nodes;
14067
+ } catch {
14068
+ }
14069
+ const lag = loopMonitorSnapshot();
14070
+ refreshRuntimeGauges({
14071
+ pools: pools.snapshot(),
14072
+ chainNodes,
14073
+ loopLagMs: lag.loop_lag_ms,
14074
+ loopLagMaxMs: lag.loop_lag_max_ms
14075
+ });
14076
+ return c.text(renderPrometheus(), 200, {
14077
+ "Content-Type": "text/plain; version=0.0.4; charset=utf-8"
14078
+ });
14079
+ });
13183
14080
  app.get("/api/v1/health", healthRoute);
13184
14081
  app.post("/api/v1/analyze", analyzeRoute);
13185
14082
  app.post("/api/v1/review", reviewRoute);
@@ -13278,7 +14175,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
13278
14175
  },
13279
14176
  serve: async () => {
13280
14177
  failFastOnAuthError();
13281
- const { mkdirSync: mkdirSync8, existsSync: existsSync22, unlinkSync: unlinkSync5 } = await import("fs");
14178
+ const { mkdirSync: mkdirSync8, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
13282
14179
  const { dirname: dirname14 } = await import("path");
13283
14180
  const dir = dirname14(socketPath);
13284
14181
  if (dir) {
@@ -13305,7 +14202,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
13305
14202
  );
13306
14203
  } else {
13307
14204
  try {
13308
- unlinkSync5(socketPath);
14205
+ unlinkSync6(socketPath);
13309
14206
  console.log(`[AgentMoss] \u6E05\u7406\u6B8B\u7559 socket \u6587\u4EF6: ${socketPath}`);
13310
14207
  } catch {
13311
14208
  }