@kenhkl/agent-moss 0.17.34 → 0.17.36

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
@@ -408,22 +408,22 @@ function loadToolRegistry() {
408
408
  data.tools = tools;
409
409
  return data;
410
410
  }
411
- function scanStructEntry(cat, value, path8) {
411
+ function scanStructEntry(cat, value, path9) {
412
412
  if (cat === "skills") {
413
413
  if (!value || typeof value !== "object" || Array.isArray(value)) {
414
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
414
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
415
415
  return null;
416
416
  }
417
417
  const out = {};
418
418
  for (const [skCat, skills] of Object.entries(value)) {
419
419
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
420
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
420
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
421
421
  continue;
422
422
  }
423
423
  const keep = {};
424
424
  for (const [name, kws] of Object.entries(skills)) {
425
425
  if (Array.isArray(kws)) keep[name] = kws;
426
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
426
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
427
427
  }
428
428
  if (Object.keys(keep).length > 0) out[skCat] = keep;
429
429
  }
@@ -431,37 +431,37 @@ function scanStructEntry(cat, value, path8) {
431
431
  }
432
432
  if (cat === "ltl_rules") {
433
433
  if (!Array.isArray(value)) {
434
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
434
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
435
435
  return null;
436
436
  }
437
437
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
438
438
  if (keep.length !== value.length) {
439
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
439
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
440
440
  }
441
441
  return keep.length > 0 ? keep : null;
442
442
  }
443
443
  if (cat === "tools") {
444
444
  if (!value || typeof value !== "object" || Array.isArray(value)) {
445
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
445
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
446
446
  return null;
447
447
  }
448
448
  const keep = {};
449
449
  for (const [k, v] of Object.entries(value)) {
450
450
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
451
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
451
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
452
452
  }
453
453
  return Object.keys(keep).length > 0 ? keep : null;
454
454
  }
455
455
  return null;
456
456
  }
457
- function scanRulesFile(path8, kind) {
457
+ function scanRulesFile(path9, kind) {
458
458
  const out = {};
459
459
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
460
460
  let parsed;
461
461
  try {
462
- parsed = JSON.parse(readFileSync2(path8, "utf-8"));
462
+ parsed = JSON.parse(readFileSync2(path9, "utf-8"));
463
463
  } catch (e) {
464
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
464
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
465
465
  return out;
466
466
  }
467
467
  const classifyFlat = (r) => {
@@ -485,44 +485,44 @@ function scanRulesFile(path8, kind) {
485
485
  }
486
486
  if (flatBad > 0) {
487
487
  console.warn(
488
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
488
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
489
489
  );
490
490
  }
491
491
  } else {
492
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
492
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
493
493
  return out;
494
494
  }
495
495
  for (const [cat, rules] of pairs) {
496
496
  if (String(cat).startsWith("_")) continue;
497
497
  if (STRUCT_KEYS.includes(cat)) {
498
- const got = scanStructEntry(cat, rules, path8);
498
+ const got = scanStructEntry(cat, rules, path9);
499
499
  if (got !== null) out[cat] = got;
500
500
  continue;
501
501
  }
502
502
  const required = EXTRA_CATEGORIES[cat];
503
503
  if (!required) {
504
504
  console.warn(
505
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
505
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
506
506
  );
507
507
  continue;
508
508
  }
509
509
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
510
510
  console.error(
511
- `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path8} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
511
+ `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path9} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
512
512
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
513
513
  \u4F60\u5199\u7684\u50CF\u662F runtime config \u7684\u683C\u5F0F\uFF08{"category_enabled": ..., "rules": [...]}\uFF09\u2014\u2014\u90A3\u662F ~/.config/agentmoss/agent_moss_runtime.json \u7684\u683C\u5F0F\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5F53\u89C4\u5219\u6587\u4EF6\u7528\u3002`
514
514
  );
515
515
  continue;
516
516
  }
517
517
  if (!Array.isArray(rules)) {
518
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
518
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
519
519
  continue;
520
520
  }
521
521
  const items = [];
522
522
  for (const r of rules) {
523
523
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
524
524
  console.warn(
525
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
525
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
526
526
  );
527
527
  continue;
528
528
  }
@@ -532,7 +532,7 @@ function scanRulesFile(path8, kind) {
532
532
  }
533
533
  if (Object.keys(out).length > 0) {
534
534
  console.info(
535
- `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path8}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
535
+ `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path9}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
536
536
  );
537
537
  }
538
538
  return out;
@@ -797,44 +797,51 @@ function readFdToken() {
797
797
  fdTokenCache.set(fd, tok);
798
798
  return tok;
799
799
  }
800
- function readExplicitToken() {
800
+ function readExplicitTokenResult() {
801
801
  const tok = env("AGENT_MOSS_AUTH_TOKEN");
802
- if (tok) return tok;
802
+ if (tok) return [tok, ""];
803
803
  const fdTok = readFdToken();
804
- if (fdTok) return fdTok;
805
- const path8 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
806
- if (path8) {
804
+ if (fdTok) return [fdTok, ""];
805
+ const path9 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
806
+ if (path9) {
807
807
  try {
808
- return readFileSync4(path8, "utf-8").trim();
809
- } catch {
810
- return "";
808
+ const fileTok = readFileSync4(path9, "utf-8").trim();
809
+ if (!fileTok) {
810
+ return ["", `AGENT_MOSS_AUTH_TOKEN_FILE \u6307\u5411\u7684\u6587\u4EF6\u4E3A\u7A7A: ${path9}\u3002\u8BF7\u5199\u5165 token\uFF0C\u6216\u663E\u5F0F\u8BBE AGENT_MOSS_AUTH_MODE=off`];
811
+ }
812
+ return [fileTok, ""];
813
+ } catch (e) {
814
+ return ["", `AGENT_MOSS_AUTH_TOKEN_FILE \u5DF2\u8BBE\u7F6E\u4F46\u65E0\u6CD5\u8BFB\u53D6 ${path9}: ${e?.message ?? e}\u3002\u8BF7\u786E\u8BA4\u6587\u4EF6\u5B58\u5728\u3001\u8FD0\u884C\u7528\u6237\u53EF\u8BFB\uFF1B\u6216\u6539\u7528 AGENT_MOSS_AUTH_TOKEN / AGENT_MOSS_AUTH_TOKEN_FD\uFF1B\u4E0D\u9700\u8981\u9274\u6743\u5219\u663E\u5F0F\u8BBE AGENT_MOSS_AUTH_MODE=off`];
811
815
  }
812
816
  }
813
- return "";
817
+ return ["", ""];
814
818
  }
815
819
  function ensureAutoToken() {
816
- const path8 = autoTokenPath();
820
+ const path9 = autoTokenPath();
817
821
  try {
818
- if (existsSync3(path8) && !lstatSync(path8).isSymbolicLink()) {
819
- const tok2 = readFileSync4(path8, "utf-8").trim();
822
+ if (existsSync3(path9) && !lstatSync(path9).isSymbolicLink()) {
823
+ const tok2 = readFileSync4(path9, "utf-8").trim();
820
824
  if (tok2) {
821
825
  try {
822
- chmodSync(path8, 384);
826
+ chmodSync(path9, 384);
823
827
  } catch {
824
828
  }
825
829
  return tok2;
826
830
  }
827
831
  }
828
832
  const tok = randomBytes(32).toString("base64url");
829
- ensurePrivateDir(dirname2(path8));
830
- if (!writePrivateText(path8, tok + "\n")) return "";
833
+ if (!ensurePrivateDir(dirname2(path9))) {
834
+ throw new Error(`\u65E0\u6CD5\u521B\u5EFA/\u6536\u7D27 token \u76EE\u5F55\uFF08\u6743\u9650\u6216\u5C5E\u4E3B\u5F02\u5E38\uFF09: ${dirname2(path9)}`);
835
+ }
836
+ if (!writePrivateText(path9, tok + "\n")) {
837
+ throw new Error(`\u5199\u5165\u81EA\u52A8 token \u5931\u8D25: ${path9}`);
838
+ }
831
839
  console.warn(
832
- `[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${path8}\uFF080600\uFF09\u3002\u5BA2\u6237\u7AEF\u9700\u5E26 \`Authorization: Bearer <token>\`\uFF1B\u67E5\u770B\uFF1Acat ${path8}\uFF1B\u5982\u9700\u5173\u95ED\u9274\u6743\uFF1AAGENT_MOSS_AUTH_MODE=off`
840
+ `[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${path9}\uFF080600\uFF09\u3002\u5BA2\u6237\u7AEF\u9700\u5E26 \`Authorization: Bearer <token>\`\uFF1B\u67E5\u770B\uFF1Acat ${path9}\uFF1B\u5982\u9700\u5173\u95ED\u9274\u6743\uFF1AAGENT_MOSS_AUTH_MODE=off`
833
841
  );
834
842
  return tok;
835
843
  } catch (e) {
836
- console.error("[AgentMoss] \u751F\u6210\u8BBF\u95EE token \u5931\u8D25\uFF08\u672C\u6B21\u8FD0\u884C\u5C06\u4E0D\u9274\u6743\uFF09:", e);
837
- return "";
844
+ throw new Error(`\u81EA\u52A8\u8BBF\u95EE token \u751F\u6210/\u8BFB\u53D6\u5931\u8D25\uFF08${path9}\uFF09\uFF1A${e?.message ?? e}`);
838
845
  }
839
846
  }
840
847
  function parseAgentTokens(raw) {
@@ -863,12 +870,22 @@ function resolveAuth() {
863
870
  return [tokenCache.token, tokenCache.agents, tokenCache.error];
864
871
  }
865
872
  let error = "";
866
- let token = readExplicitToken();
867
- if (!token && env("AGENT_MOSS_AUTH_TOKEN_FD") && authMode() !== AUTH_MODE_OFF) {
873
+ let token = "";
874
+ if (authMode() !== AUTH_MODE_OFF) {
875
+ [token, error] = readExplicitTokenResult();
876
+ }
877
+ if (!token && !error && env("AGENT_MOSS_AUTH_TOKEN_FD") && authMode() !== AUTH_MODE_OFF) {
868
878
  error = "AGENT_MOSS_AUTH_TOKEN_FD \u5DF2\u8BBE\u7F6E\uFF0C\u4F46\u6CA1\u80FD\u4ECE\u8BE5\u6587\u4EF6\u63CF\u8FF0\u7B26\u8BFB\u5230 token\u3002\u62D2\u7EDD\u964D\u7EA7\u5230\u78C1\u76D8 token\uFF08\u90A3\u4F1A\u5728\u672C\u673A\u7559\u4E0B\u4E00\u4EFD\u540C\u7528\u6237\u53EF\u8BFB\u7684\u51ED\u8BC1\uFF09\u3002";
869
879
  console.error(`[agent-moss] ${error}`);
870
880
  }
871
- if (!token && !error && authMode() !== AUTH_MODE_OFF) token = ensureAutoToken();
881
+ if (!token && !error && authMode() !== AUTH_MODE_OFF) {
882
+ try {
883
+ token = ensureAutoToken();
884
+ } catch (e) {
885
+ error = `${e?.message ?? e}\u3002\u8BF7\u786E\u8BA4\u6570\u636E\u76EE\u5F55\u53EF\u5199\u3001\u6743\u9650\u6B63\u786E\u3001\u78C1\u76D8\u672A\u6EE1\uFF1B\u4E0D\u9700\u8981\u9274\u6743\u8BF7\u663E\u5F0F\u8BBE AGENT_MOSS_AUTH_MODE=off`;
886
+ console.error(`[agent-moss] \u9274\u6743\u914D\u7F6E\u9519\u8BEF\uFF0C\u62D2\u7EDD\u542F\u52A8: ${error}`);
887
+ }
888
+ }
872
889
  const agents = parseAgentTokens(rawAgents);
873
890
  tokenCache = { key, token, agents, error };
874
891
  return [token, agents, error];
@@ -888,8 +905,8 @@ function failFastOnAuthError() {
888
905
  }
889
906
  function authEnabled() {
890
907
  if (authMode() === AUTH_MODE_OFF) return false;
891
- const [tok, agents] = resolveAuth();
892
- return Boolean(tok) || Object.keys(agents).length > 0;
908
+ const [tok, agents, err] = resolveAuth();
909
+ return Boolean(err) || Boolean(tok) || Object.keys(agents).length > 0;
893
910
  }
894
911
  function bearer(headers) {
895
912
  const get = (k) => headers instanceof Headers ? headers.get(k) ?? "" : headers[k] ?? "";
@@ -902,16 +919,16 @@ function constEq(a, b) {
902
919
  if (ba.length !== bb.length) return false;
903
920
  return timingSafeEqual(ba, bb);
904
921
  }
905
- function checkRequestAuth(headers, path8) {
922
+ function checkRequestAuth(headers, path9) {
906
923
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
907
- const isHealth = HEALTH_PATHS.includes(path8.replace(/\/+$/, ""));
924
+ const isHealth = HEALTH_PATHS.includes(path9.replace(/\/+$/, ""));
908
925
  const [gt0, agents, err] = resolveAuth();
909
926
  if (err) return isHealth ? [true, ""] : [false, ""];
910
927
  if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
911
928
  if (isHealth) return [true, ""];
912
929
  const tok = bearer(headers);
913
930
  if (!tok) return [false, ""];
914
- if (path8.startsWith("/console/api")) {
931
+ if (path9.startsWith("/console/api")) {
915
932
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
916
933
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
917
934
  }
@@ -930,8 +947,8 @@ function bindAgent(principal, agentId) {
930
947
  if (!agentId) return [true, bound];
931
948
  return [bound === agentId, bound];
932
949
  }
933
- function principalOf(headers, path8 = "") {
934
- const [ok, principal] = checkRequestAuth(headers, path8);
950
+ function principalOf(headers, path9 = "") {
951
+ const [ok, principal] = checkRequestAuth(headers, path9);
935
952
  return ok ? principal : "";
936
953
  }
937
954
  function principalHash(principal) {
@@ -1188,11 +1205,11 @@ function errorDetailMode() {
1188
1205
  function maxBodyBytes() {
1189
1206
  return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
1190
1207
  }
1191
- function poolOf(path8) {
1192
- if (path8 === "/api/v1/analyze" || path8.startsWith("/api/v1/analyze/")) return "biz";
1193
- if (path8 === "/api/v1/review" || path8.startsWith("/api/v1/review/")) return "review";
1194
- if (path8 === "/console" || path8.startsWith("/console/") || path8.startsWith("/api/v1/brain")) return "ops";
1195
- if (path8 === "/api/v1/health") return "health";
1208
+ function poolOf(path9) {
1209
+ if (path9 === "/api/v1/analyze" || path9.startsWith("/api/v1/analyze/")) return "biz";
1210
+ if (path9 === "/api/v1/review" || path9.startsWith("/api/v1/review/")) return "review";
1211
+ if (path9 === "/console" || path9.startsWith("/console/") || path9.startsWith("/api/v1/brain")) return "ops";
1212
+ if (path9 === "/api/v1/health") return "health";
1196
1213
  return "other";
1197
1214
  }
1198
1215
  function poolLimit(name) {
@@ -1507,7 +1524,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
1507
1524
  os: String(sp.os || "linux").toLowerCase()
1508
1525
  }));
1509
1526
  }
1510
- function _scopeOf(os5, path8) {
1527
+ function _scopeOf(os6, path9) {
1511
1528
  if (!_scopeIndex) {
1512
1529
  _scopeIndex = /* @__PURE__ */ new Map();
1513
1530
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -1515,7 +1532,7 @@ function _scopeOf(os5, path8) {
1515
1532
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
1516
1533
  }
1517
1534
  }
1518
- return _scopeIndex.get(`${String(os5 || "linux").toLowerCase()}|${path8}`) || "root";
1535
+ return _scopeIndex.get(`${String(os6 || "linux").toLowerCase()}|${path9}`) || "root";
1519
1536
  }
1520
1537
  function getSensitivePathsForOs(osType) {
1521
1538
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -2234,36 +2251,36 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2234
2251
  }
2235
2252
  const preciseEdit = isPreciseEditTool(actionType);
2236
2253
  const unreadPaths = [];
2237
- for (const path8 of checkTargets) {
2238
- if (isDirectoryTarget(path8)) continue;
2254
+ for (const path9 of checkTargets) {
2255
+ if (isDirectoryTarget(path9)) continue;
2239
2256
  let isFullRead = [...normalizedFullReads].some(
2240
- (rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
2257
+ (rp) => pathIsSameOrUnder(path9, rp) || pathIsSameOrUnder(rp, path9)
2241
2258
  );
2242
2259
  if (!isFullRead && preciseEdit && [...normalizedWrittenPaths].some(
2243
- (wp) => pathIsSameOrUnder(path8, wp) || pathIsSameOrUnder(wp, path8)
2260
+ (wp) => pathIsSameOrUnder(path9, wp) || pathIsSameOrUnder(wp, path9)
2244
2261
  )) {
2245
2262
  isFullRead = true;
2246
2263
  }
2247
- if (!isFullRead && !isProtectedWritePath(path8) && isScriptGeneratedTarget(path8, historyWrittenScripts, shellRunActions)) {
2264
+ if (!isFullRead && !isProtectedWritePath(path9) && isScriptGeneratedTarget(path9, historyWrittenScripts, shellRunActions)) {
2248
2265
  isFullRead = true;
2249
2266
  }
2250
2267
  let isPartialCovered = false;
2251
2268
  if (!isFullRead) {
2252
2269
  for (const [pp, upto] of normalizedPartialReads) {
2253
- if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
2254
- if (preciseEdit || upto != null && fileHasAtMostLines(path8, upto)) {
2270
+ if (!(pathIsSameOrUnder(path9, pp) || pathIsSameOrUnder(pp, path9))) continue;
2271
+ if (preciseEdit || upto != null && fileHasAtMostLines(path9, upto)) {
2255
2272
  isPartialCovered = true;
2256
2273
  break;
2257
2274
  }
2258
2275
  }
2259
2276
  }
2260
2277
  if (!isFullRead && !isPartialCovered) {
2261
- let isCreate = !fs.existsSync(path8);
2278
+ let isCreate = !fs.existsSync(path9);
2262
2279
  if (!isCreate) {
2263
2280
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
2264
2281
  }
2265
2282
  if (!isCreate) {
2266
- unreadPaths.push(path8);
2283
+ unreadPaths.push(path9);
2267
2284
  }
2268
2285
  }
2269
2286
  }
@@ -2457,16 +2474,16 @@ var init_logic_rules = __esm({
2457
2474
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
2458
2475
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
2459
2476
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
2460
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2477
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2461
2478
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
2462
2479
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
2463
- CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2480
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2464
2481
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
2465
2482
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
2466
- CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2483
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2467
2484
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
2468
2485
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
2469
- CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2486
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2470
2487
  _scopeIndex = null;
2471
2488
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
2472
2489
  "ask_user_question",
@@ -2942,8 +2959,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
2942
2959
  function _filterRulesByOs(rules, osType) {
2943
2960
  const accepted = acceptedOsValues(osType);
2944
2961
  return rules.filter((r) => {
2945
- const os5 = String(r.os || "linux").toLowerCase();
2946
- return os5 === "all" || accepted.includes(os5);
2962
+ const os6 = String(r.os || "linux").toLowerCase();
2963
+ return os6 === "all" || accepted.includes(os6);
2947
2964
  });
2948
2965
  }
2949
2966
  function _userCustomRules(runtime, layers, requiredKey) {
@@ -3145,7 +3162,7 @@ function _l2SensitivePathsToRules() {
3145
3162
  const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
3146
3163
  const all = [...root, ...home, ...credential];
3147
3164
  for (const sp of all) {
3148
- const os5 = String(sp.os || "linux").toLowerCase();
3165
+ const os6 = String(sp.os || "linux").toLowerCase();
3149
3166
  const denyMode = sp.denyMode || _deriveDenyMode({
3150
3167
  deny_mode: sp.deny_mode,
3151
3168
  credential: sp.credential,
@@ -3155,7 +3172,7 @@ function _l2SensitivePathsToRules() {
3155
3172
  // id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
3156
3173
  // hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
3157
3174
  // Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
3158
- id: `path_${os5}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3175
+ id: `path_${os6}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3159
3176
  path: sp.path,
3160
3177
  risk_level: sp.riskLevel,
3161
3178
  desc: sp.desc,
@@ -3164,7 +3181,7 @@ function _l2SensitivePathsToRules() {
3164
3181
  skip_l3_on_disabled: true,
3165
3182
  enabled: true,
3166
3183
  builtin: true,
3167
- os: os5
3184
+ os: os6
3168
3185
  };
3169
3186
  _syncDenyModeFields(rule);
3170
3187
  if (sp.dirDelOnly) rule.dir_del_only = true;
@@ -3702,8 +3719,8 @@ function _filterDefaultsByOs(rules, osType) {
3702
3719
  const accepted = acceptedOsValues(osType);
3703
3720
  return rules.filter((r) => {
3704
3721
  if (!r.os) return true;
3705
- const os5 = String(r.os).toLowerCase();
3706
- return os5 === "all" || accepted.includes(os5);
3722
+ const os6 = String(r.os).toLowerCase();
3723
+ return os6 === "all" || accepted.includes(os6);
3707
3724
  });
3708
3725
  }
3709
3726
  function _hasRulesForOs(rules, osType) {
@@ -4745,24 +4762,24 @@ function extractWritePayload(actionType, actionDetailRaw) {
4745
4762
  const detail = actionDetailRaw || "";
4746
4763
  const m = detail.match(WRITE_PREFIX_RE);
4747
4764
  if (m) {
4748
- const path8 = m[1];
4765
+ const path9 = m[1];
4749
4766
  let content = m[2] || "";
4750
- if (!path8 || path8 === "?" || path8 === "-" || !content.trim()) return null;
4767
+ if (!path9 || path9 === "?" || path9 === "-" || !content.trim()) return null;
4751
4768
  if ((actionType || "").toLowerCase().includes("editfile")) {
4752
4769
  const nm = content.match(EDIT_NEW_RE);
4753
4770
  if (nm) content = nm[1];
4754
4771
  }
4755
- return { path: path8, content };
4772
+ return { path: path9, content };
4756
4773
  }
4757
4774
  const stripped = detail.trim();
4758
4775
  if (stripped.startsWith("{")) {
4759
4776
  try {
4760
4777
  const obj = JSON.parse(stripped);
4761
4778
  if (obj && typeof obj === "object") {
4762
- const path8 = obj.path || obj.file_path || obj.filePath;
4779
+ const path9 = obj.path || obj.file_path || obj.filePath;
4763
4780
  const content = obj.content || obj.newString || obj.new_string;
4764
- if (typeof path8 === "string" && path8 !== "" && path8 !== "?" && path8 !== "-" && typeof content === "string" && content.trim()) {
4765
- return { path: path8, content };
4781
+ if (typeof path9 === "string" && path9 !== "" && path9 !== "?" && path9 !== "-" && typeof content === "string" && content.trim()) {
4782
+ return { path: path9, content };
4766
4783
  }
4767
4784
  }
4768
4785
  } catch {
@@ -4775,8 +4792,8 @@ function handlesWrittenContent(actionType, actionDetailRaw) {
4775
4792
  if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
4776
4793
  return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
4777
4794
  }
4778
- function detectLanguage(path8, content) {
4779
- const ext = path8.slice(path8.lastIndexOf(".") >= 0 ? path8.lastIndexOf(".") : path8.length).toLowerCase();
4795
+ function detectLanguage(path9, content) {
4796
+ const ext = path9.slice(path9.lastIndexOf(".") >= 0 ? path9.lastIndexOf(".") : path9.length).toLowerCase();
4780
4797
  if (SHELL_EXTS.has(ext)) return "shell";
4781
4798
  if (PY_EXTS.has(ext)) return "python";
4782
4799
  if (DATA_EXTS.has(ext)) return "data";
@@ -4934,8 +4951,8 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
4934
4951
  if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
4935
4952
  const payload = extractWritePayload(actionType, actionDetailRaw);
4936
4953
  if (!payload) return [];
4937
- const { path: path8, content: rawContent } = payload;
4938
- const language = detectLanguage(path8, rawContent);
4954
+ const { path: path9, content: rawContent } = payload;
4955
+ const language = detectLanguage(path9, rawContent);
4939
4956
  if (language === "data") return [];
4940
4957
  let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
4941
4958
  const started = Date.now();
@@ -5429,16 +5446,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5429
5446
  if (String(osType || "").toLowerCase() === "windows") {
5430
5447
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
5431
5448
  }
5432
- const pathMatches = (text, path8) => {
5433
- const parts = path8.split(/(\(\?!.*?\))/);
5449
+ const pathMatches = (text, path9) => {
5450
+ const parts = path9.split(/(\(\?!.*?\))/);
5434
5451
  const escaped = parts.map((part) => {
5435
5452
  if (part.startsWith("(?!")) return part;
5436
5453
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5437
5454
  }).join("");
5438
- const re = path8.startsWith(".") || path8.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
5455
+ const re = path9.startsWith(".") || path9.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
5439
5456
  return re.test(text);
5440
5457
  };
5441
- const pathMatchesAny = (path8) => pathScanTexts.some((t) => pathMatches(t, path8));
5458
+ const pathMatchesAny = (path9) => pathScanTexts.some((t) => pathMatches(t, path9));
5442
5459
  for (const sp of rootPaths) {
5443
5460
  if (pathMatchesAny(sp.path.toLowerCase())) {
5444
5461
  if (keygenGenerate) continue;
@@ -5581,8 +5598,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5581
5598
  }
5582
5599
  return null;
5583
5600
  }
5584
- function isHomeValue(path8) {
5585
- let p = path8.trim().toLowerCase();
5601
+ function isHomeValue(path9) {
5602
+ let p = path9.trim().toLowerCase();
5586
5603
  if (p.startsWith("$(") && p.endsWith(")")) {
5587
5604
  const inner = p.slice(2, -1).trim();
5588
5605
  return HOME_TARGET_RE.test(" " + inner);
@@ -5638,15 +5655,15 @@ function checkHomeDeletion(actionType, actionDetail) {
5638
5655
  }
5639
5656
  const assigned = {};
5640
5657
  for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
5641
- for (const [varName, path8] of Object.entries(assigned)) {
5642
- if (!isHomeValue(path8)) continue;
5658
+ for (const [varName, path9] of Object.entries(assigned)) {
5659
+ if (!isHomeValue(path9)) continue;
5643
5660
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
5644
5661
  for (const seg of segs) {
5645
5662
  if (!isDeleteCommand(seg)) continue;
5646
5663
  if (varRefRe.test(seg)) {
5647
5664
  return {
5648
5665
  allowed: false,
5649
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path8}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5666
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path9}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5650
5667
  riskLevel: "high",
5651
5668
  riskType: "script_execution",
5652
5669
  confidence: 90,
@@ -6454,15 +6471,15 @@ function parseShellString(s) {
6454
6471
  let m;
6455
6472
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
6456
6473
  const interp = m[1];
6457
- const path8 = m[2].trim();
6474
+ const path9 = m[2].trim();
6458
6475
  let rest = m[3].trim();
6459
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6476
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
6460
6477
  rest = rest.split(/[;|&<>]/)[0].trim();
6461
6478
  const args = [];
6462
6479
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6463
6480
  args.push(tm[1] ? tm[2] : tm[3]);
6464
6481
  }
6465
- return { path: path8, args, interpreter: interp };
6482
+ return { path: path9, args, interpreter: interp };
6466
6483
  }
6467
6484
  return null;
6468
6485
  }
@@ -6508,9 +6525,9 @@ function extractCallsFromTree(tree, reachableLines) {
6508
6525
  }
6509
6526
  if (allStr && elts.length >= 2) {
6510
6527
  const interp = elts[0];
6511
- const path8 = elts[1];
6512
- if (!path8.startsWith("-") && !path8.startsWith("$") && !path8.includes("/dev/")) {
6513
- add({ path: path8, args: elts.slice(2), interpreter: interp });
6528
+ const path9 = elts[1];
6529
+ if (!path9.startsWith("-") && !path9.startsWith("$") && !path9.includes("/dev/")) {
6530
+ add({ path: path9, args: elts.slice(2), interpreter: interp });
6514
6531
  return true;
6515
6532
  }
6516
6533
  }
@@ -6550,15 +6567,15 @@ function extractCallsRegex(content) {
6550
6567
  let m;
6551
6568
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
6552
6569
  const interp = m[1];
6553
- const path8 = m[2].trim();
6570
+ const path9 = m[2].trim();
6554
6571
  let rest = m[3].trim();
6555
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6572
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
6556
6573
  rest = rest.split(/[;|&<>]/)[0].trim();
6557
6574
  const args = [];
6558
6575
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6559
6576
  args.push(tm[1] ? tm[2] : tm[3]);
6560
6577
  }
6561
- calls.push({ path: path8, args, interpreter: interp });
6578
+ calls.push({ path: path9, args, interpreter: interp });
6562
6579
  }
6563
6580
  return calls;
6564
6581
  }
@@ -7352,15 +7369,15 @@ function extractCallsFromContent(content) {
7352
7369
  CHILD_CALL_RE2.lastIndex = 0;
7353
7370
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
7354
7371
  const interp = m[1];
7355
- const path8 = m[2].trim();
7372
+ const path9 = m[2].trim();
7356
7373
  let rest = m[3].trim();
7357
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
7374
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
7358
7375
  rest = rest.split(/[;|&<>]/)[0].trim();
7359
7376
  const args = [];
7360
7377
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
7361
7378
  args.push(tm[1] ? tm[2] : tm[3]);
7362
7379
  }
7363
- calls.push({ path: path8, args, interpreter: interp });
7380
+ calls.push({ path: path9, args, interpreter: interp });
7364
7381
  }
7365
7382
  return calls;
7366
7383
  }
@@ -8999,6 +9016,28 @@ function formatHints(previous) {
8999
9016
  }
9000
9017
  return hints.length > 0 ? hints.join("\n\n") : "\u7279\u5F81\u5339\u914D\u68C0\u6D4B\u548C\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u5747\u672A\u53D1\u73B0\u98CE\u9669\u3002";
9001
9018
  }
9019
+ function maskedBaseUrl(raw) {
9020
+ try {
9021
+ const u = new URL(raw || "https://api.openai.com/v1");
9022
+ return `${u.protocol}//${u.hostname}${u.port ? ":" + u.port : ""}${u.pathname || ""}`;
9023
+ } catch {
9024
+ return "(unparseable)";
9025
+ }
9026
+ }
9027
+ function llmErrorDetail(err, config, attempt, maxRetries, elapsedMs, promptChars, timeoutMs) {
9028
+ const chain = [];
9029
+ let cur = err;
9030
+ const seen = /* @__PURE__ */ new Set();
9031
+ while (cur && !seen.has(cur) && chain.length < 4) {
9032
+ seen.add(cur);
9033
+ chain.push(`${cur?.constructor?.name || typeof cur}(${String(cur?.message ?? cur).replace(/\n/g, " ").slice(0, 300)})`);
9034
+ cur = cur?.cause ?? cur?.context;
9035
+ }
9036
+ const proxy = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"].filter((n) => process.env[n]).join(",") || "none";
9037
+ const cause = err?.cause ?? err?.context;
9038
+ const errno = cause?.errno ?? cause?.code ?? err?.errno ?? err?.code;
9039
+ return `attempt=${attempt}/${maxRetries + 1} elapsed=${(elapsedMs / 1e3).toFixed(1)}s timeout=${(timeoutMs / 1e3).toFixed(1)}s model=${config.model} provider=${config.provider || "auto"} base_url=${maskedBaseUrl(config.baseUrl)} proxy=${proxy} prompt_chars=${promptChars} errno=${errno ?? "-"} chain=${chain.join(" <- ")}`;
9040
+ }
9002
9041
  async function analyzeWithLLM(prompt, config) {
9003
9042
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
9004
9043
  const _llmStart = performance.now();
@@ -9046,6 +9085,7 @@ async function analyzeWithLLM(prompt, config) {
9046
9085
  if (abortController.signal.aborted) {
9047
9086
  break;
9048
9087
  }
9088
+ const attemptStart = performance.now();
9049
9089
  try {
9050
9090
  const response = await client.chat.completions.create({
9051
9091
  model: config.model,
@@ -9161,7 +9201,16 @@ async function analyzeWithLLM(prompt, config) {
9161
9201
  const errObj = err;
9162
9202
  const status = errObj?.status ?? errObj?.statusCode;
9163
9203
  const body = errObj?.error ?? errObj?.body;
9164
- const detail = status !== void 0 || body !== void 0 ? `${err.message} status=${status} body=${String(JSON.stringify(body)).slice(0, 300)}` : err.message;
9204
+ const baseDetail = status !== void 0 || body !== void 0 ? `${err.message} status=${status} body=${String(JSON.stringify(body)).slice(0, 300)}` : err.message;
9205
+ const detail = `${baseDetail} | ${llmErrorDetail(
9206
+ err,
9207
+ config,
9208
+ attempt + 1,
9209
+ maxRetries,
9210
+ performance.now() - attemptStart,
9211
+ prompt.length,
9212
+ (config.timeout || timeoutCfg.prompt1Timeout) * 1e3
9213
+ )}`;
9165
9214
  if (attempt < maxRetries) {
9166
9215
  console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
9167
9216
  await new Promise((resolve12) => setTimeout(resolve12, retryCfg.retryInterval * 1e3));
@@ -9233,8 +9282,8 @@ var init_rule_store = __esm({
9233
9282
  BrainRuleStore = class {
9234
9283
  path;
9235
9284
  data;
9236
- constructor(path8) {
9237
- this.path = path8 || getRulesPath();
9285
+ constructor(path9) {
9286
+ this.path = path9 || getRulesPath();
9238
9287
  this.data = this.load();
9239
9288
  }
9240
9289
  load() {
@@ -9687,10 +9736,10 @@ ${reason.slice(0, 500)}
9687
9736
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
9688
9737
  let mm;
9689
9738
  while ((mm = pathRe.exec(src)) !== null) {
9690
- const path8 = mm[1];
9691
- if (path8.split("/").length < 3) continue;
9692
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path8)) continue;
9693
- const gen = this.generalizePath(path8);
9739
+ const path9 = mm[1];
9740
+ if (path9.split("/").length < 3) continue;
9741
+ if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path9)) continue;
9742
+ const gen = this.generalizePath(path9);
9694
9743
  if (seen.has(gen)) continue;
9695
9744
  seen.add(gen);
9696
9745
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -9709,8 +9758,8 @@ ${reason.slice(0, 500)}
9709
9758
  }
9710
9759
  return false;
9711
9760
  }
9712
- generalizePath(path8) {
9713
- const p = path8.toLowerCase();
9761
+ generalizePath(path9) {
9762
+ const p = path9.toLowerCase();
9714
9763
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
9715
9764
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
9716
9765
  }
@@ -10570,12 +10619,12 @@ var init_builder = __esm({
10570
10619
  });
10571
10620
 
10572
10621
  // src/engine/formal-engine/properties.ts
10573
- function graphFromPath(nodes, path8, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10622
+ function graphFromPath(nodes, path9, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10574
10623
  const byKey = /* @__PURE__ */ new Map();
10575
10624
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
10576
10625
  const gNodes = [];
10577
10626
  const gEdges = [];
10578
- for (const item of path8) {
10627
+ for (const item of path9) {
10579
10628
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
10580
10629
  gNodes.push({
10581
10630
  session_id: item.sessionId,
@@ -10641,22 +10690,22 @@ function checkCrossSessionChain(graph) {
10641
10690
  if (witness !== void 0) {
10642
10691
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
10643
10692
  let matched = 0;
10644
- const path8 = [];
10693
+ const path9 = [];
10645
10694
  for (let k = 0; k < witness; k++) {
10646
10695
  const n = nodes[k];
10647
10696
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
10648
10697
  matched += 1;
10649
- path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10698
+ path9.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10650
10699
  }
10651
10700
  }
10652
10701
  if (matched < stages.length - 1) continue;
10653
- path8.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
10702
+ path9.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
10654
10703
  violations.push({
10655
10704
  propertyId: "cross-" + chain.id,
10656
10705
  reason: chain.reason,
10657
10706
  riskLevel: chain.riskLevel,
10658
- path: path8,
10659
- graph: graphFromPath(nodes, path8, "next", {
10707
+ path: path9,
10708
+ graph: graphFromPath(nodes, path9, "next", {
10660
10709
  property_id: "cross-" + chain.id,
10661
10710
  property_short: "P1",
10662
10711
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -10666,11 +10715,11 @@ function checkCrossSessionChain(graph) {
10666
10715
  } else {
10667
10716
  let matched = 0;
10668
10717
  let stageIdx = 0;
10669
- const path8 = [];
10718
+ const path9 = [];
10670
10719
  for (const n of nodes) {
10671
10720
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
10672
10721
  matched += 1;
10673
- path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10722
+ path9.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10674
10723
  stageIdx += 1;
10675
10724
  if (matched >= stages.length) break;
10676
10725
  }
@@ -10680,8 +10729,8 @@ function checkCrossSessionChain(graph) {
10680
10729
  propertyId: "cross-" + chain.id,
10681
10730
  reason: chain.reason,
10682
10731
  riskLevel: chain.riskLevel,
10683
- path: path8,
10684
- graph: graphFromPath(nodes, path8, "next", {
10732
+ path: path9,
10733
+ graph: graphFromPath(nodes, path9, "next", {
10685
10734
  property_id: "cross-" + chain.id,
10686
10735
  property_short: "P1",
10687
10736
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -10902,7 +10951,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10902
10951
  if (candidates.length > 0) {
10903
10952
  const pre = nodes[candidates[candidates.length - 1]];
10904
10953
  const post = nodes[firstEv];
10905
- const path8 = [
10954
+ const path9 = [
10906
10955
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10907
10956
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10908
10957
  ];
@@ -10910,8 +10959,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10910
10959
  propertyId: "no-exfil-after-privesc",
10911
10960
  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",
10912
10961
  riskLevel: "critical",
10913
- path: path8,
10914
- graph: graphFromPath(nodes, path8, "next", {
10962
+ path: path9,
10963
+ graph: graphFromPath(nodes, path9, "next", {
10915
10964
  property_id: "no-exfil-after-privesc",
10916
10965
  property_short: "P4",
10917
10966
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10928,7 +10977,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10928
10977
  for (let j = i + 1; j < nodes.length; j++) {
10929
10978
  if (!isExfilNode(nodes[j])) continue;
10930
10979
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
10931
- const path8 = [
10980
+ const path9 = [
10932
10981
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10933
10982
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10934
10983
  ];
@@ -10936,8 +10985,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10936
10985
  propertyId: "no-exfil-after-privesc",
10937
10986
  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",
10938
10987
  riskLevel: "critical",
10939
- path: path8,
10940
- graph: graphFromPath(nodes, path8, "next", {
10988
+ path: path9,
10989
+ graph: graphFromPath(nodes, path9, "next", {
10941
10990
  property_id: "no-exfil-after-privesc",
10942
10991
  property_short: "P4",
10943
10992
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10969,7 +11018,7 @@ function checkNeverExfilAfterCred(graph) {
10969
11018
  }
10970
11019
  if (pre) {
10971
11020
  const post = nodes[firstEv];
10972
- const path8 = [
11021
+ const path9 = [
10973
11022
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10974
11023
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10975
11024
  ];
@@ -10977,8 +11026,8 @@ function checkNeverExfilAfterCred(graph) {
10977
11026
  propertyId: "no-exfil-after-credential",
10978
11027
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10979
11028
  riskLevel: "critical",
10980
- path: path8,
10981
- graph: graphFromPath(nodes, path8, "data", {
11029
+ path: path9,
11030
+ graph: graphFromPath(nodes, path9, "data", {
10982
11031
  property_id: "no-exfil-after-credential",
10983
11032
  property_short: "P5",
10984
11033
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10994,7 +11043,7 @@ function checkNeverExfilAfterCred(graph) {
10994
11043
  if (!isCredNode(nodes[i])) continue;
10995
11044
  for (let j = i + 1; j < nodes.length; j++) {
10996
11045
  if (isExfilNode(nodes[j])) {
10997
- const path8 = [
11046
+ const path9 = [
10998
11047
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10999
11048
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
11000
11049
  ];
@@ -11002,8 +11051,8 @@ function checkNeverExfilAfterCred(graph) {
11002
11051
  propertyId: "no-exfil-after-credential",
11003
11052
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
11004
11053
  riskLevel: "critical",
11005
- path: path8,
11006
- graph: graphFromPath(nodes, path8, "data", {
11054
+ path: path9,
11055
+ graph: graphFromPath(nodes, path9, "data", {
11007
11056
  property_id: "no-exfil-after-credential",
11008
11057
  property_short: "P5",
11009
11058
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -11162,13 +11211,13 @@ function checkSensitiveDataAggregation(graph) {
11162
11211
  if (!isExfilNode(n)) continue;
11163
11212
  const srcs = sourcesFor(i);
11164
11213
  if (srcs.size >= 2) {
11165
- const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11214
+ const path9 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11166
11215
  violations.push({
11167
11216
  propertyId: "sensitive-data-aggregation",
11168
11217
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
11169
11218
  riskLevel: "critical",
11170
- path: path8,
11171
- graph: graphFromPath(nodes, path8, "next", {
11219
+ path: path9,
11220
+ graph: graphFromPath(nodes, path9, "next", {
11172
11221
  property_id: "sensitive-data-aggregation",
11173
11222
  property_short: "P8",
11174
11223
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -11290,6 +11339,10 @@ var init_engine = __esm({
11290
11339
  });
11291
11340
 
11292
11341
  // src/engine/formal-engine/stateful.ts
11342
+ import * as fs5 from "fs";
11343
+ import * as os3 from "os";
11344
+ import * as path6 from "path";
11345
+ import { gzipSync } from "zlib";
11293
11346
  function extractInstances(actionDetail, stage) {
11294
11347
  const out = [];
11295
11348
  if (PORT_STAGE_RE.test(stage)) {
@@ -11488,12 +11541,65 @@ var init_stateful = __esm({
11488
11541
  }
11489
11542
  };
11490
11543
  }
11544
+ /**
11545
+ * 自动轮转:归档旧节点,只保留最近 `retain` 条,并重建链指针/taint。
11546
+ *
11547
+ * 派生缓存不是原始历史存储;归档失败抛异常,调用方不得丢状态。
11548
+ */
11549
+ rotate(archiveDir, retain) {
11550
+ const keep = Math.max(1, Math.min(retain ?? Math.floor(MAX_NODES / 2), MAX_NODES - 1));
11551
+ if (this.nodes_.length <= keep) return { archived: 0, file: "" };
11552
+ const old = this.nodes_.slice(0, this.nodes_.length - keep);
11553
+ const kept = this.nodes_.slice(-keep);
11554
+ const dir = archiveDir || process.env.AGENT_MOSS_CHAIN_ARCHIVE_DIR || path6.join(process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss"), "chain-archive");
11555
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
11556
+ const safeAgent = (this.agentId || "default").replace(/[^A-Za-z0-9_.-]/g, "_");
11557
+ const file = path6.join(dir, `chain-nodes-${safeAgent}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.jsonl.gz`);
11558
+ const payload = old.map((n) => JSON.stringify(n)).join("\n") + "\n";
11559
+ fs5.writeFileSync(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
11560
+ this.nodes_ = [];
11561
+ this.ptr = {};
11562
+ this.tainted.clear();
11563
+ this.taintedResources.clear();
11564
+ this.taintParent.clear();
11565
+ this.taintEdgeLabel.clear();
11566
+ this.taintOrigin.clear();
11567
+ this.aliveResources = {};
11568
+ this.seqNext = 0;
11569
+ for (const n of kept) {
11570
+ const node = this.appendNode(
11571
+ {
11572
+ actionType: n.actionType,
11573
+ actionDetail: n.actionDetail,
11574
+ agentId: n.agentId,
11575
+ instanceId: n.instanceId,
11576
+ ...n.timestamp ? { calledAt: n.timestamp } : {}
11577
+ },
11578
+ n.sessionId,
11579
+ n.isError,
11580
+ n.agentId,
11581
+ n.instanceId
11582
+ );
11583
+ if (node) {
11584
+ this.recordLifecycle(node);
11585
+ this.advanceTaint(node);
11586
+ this.advanceChains(node);
11587
+ }
11588
+ }
11589
+ return { archived: old.length, file };
11590
+ }
11491
11591
  appendNode(action, sessionId, isError = false, agentId = "", instanceId = "") {
11492
11592
  const ad = String(action.actionDetail || "");
11493
11593
  const at = String(action.actionType || "");
11494
11594
  if (!ad) return null;
11495
11595
  if (this.nodes_.length >= MAX_NODES) {
11496
- return null;
11596
+ try {
11597
+ const r = this.rotate();
11598
+ if (r.archived <= 0) return null;
11599
+ } catch (e) {
11600
+ console.error(`[AgentMoss] chain state rotate failed (${this.agentId}): ${e?.message ?? e}`);
11601
+ return null;
11602
+ }
11497
11603
  }
11498
11604
  const stage = markStage2(ad);
11499
11605
  const node = {
@@ -11641,11 +11747,11 @@ var init_stateful = __esm({
11641
11747
  }
11642
11748
  }
11643
11749
  chainPath(stages) {
11644
- const path8 = [];
11750
+ const path9 = [];
11645
11751
  let want = stages[0];
11646
11752
  for (const n of this.nodes_) {
11647
11753
  if (n.stage === want) {
11648
- path8.push({
11754
+ path9.push({
11649
11755
  sessionId: n.sessionId,
11650
11756
  seq: n.seq,
11651
11757
  stage: n.stage,
@@ -11661,12 +11767,12 @@ var init_stateful = __esm({
11661
11767
  }
11662
11768
  }
11663
11769
  }
11664
- return path8;
11770
+ return path9;
11665
11771
  }
11666
11772
  /** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
11667
11773
  buildChainGraph(stages, chainId) {
11668
- const path8 = this.chainPath(stages);
11669
- const gNodes = path8.map((p, i) => {
11774
+ const path9 = this.chainPath(stages);
11775
+ const gNodes = path9.map((p, i) => {
11670
11776
  const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
11671
11777
  return {
11672
11778
  session_id: p.sessionId,
@@ -11917,22 +12023,22 @@ var init_stateful = __esm({
11917
12023
  });
11918
12024
 
11919
12025
  // src/engine/formal-engine/chain_state.ts
11920
- import * as fs5 from "fs";
11921
- import * as os3 from "os";
11922
- import * as path6 from "path";
12026
+ import * as fs6 from "fs";
12027
+ import * as os4 from "os";
12028
+ import * as path7 from "path";
11923
12029
  import { createHash as createHash4 } from "crypto";
11924
12030
  function defaultStateDbPath() {
11925
- const base = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
12031
+ const base = process.env.AGENT_MOSS_STATE_DIR || path7.join(os4.homedir(), ".agentmoss");
11926
12032
  const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
11927
- const dir = instance ? path6.join(base, instance) : base;
12033
+ const dir = instance ? path7.join(base, instance) : base;
11928
12034
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
11929
- const target = path6.join(dir, `stateful_chains_${tag}.json`);
12035
+ const target = path7.join(dir, `stateful_chains_${tag}.json`);
11930
12036
  if (instance) {
11931
- const legacy = path6.join(base, `stateful_chains_${tag}.json`);
11932
- if (!fs5.existsSync(target) && fs5.existsSync(legacy)) {
12037
+ const legacy = path7.join(base, `stateful_chains_${tag}.json`);
12038
+ if (!fs6.existsSync(target) && fs6.existsSync(legacy)) {
11933
12039
  try {
11934
- fs5.mkdirSync(dir, { recursive: true });
11935
- fs5.copyFileSync(legacy, target);
12040
+ fs6.mkdirSync(dir, { recursive: true });
12041
+ fs6.copyFileSync(legacy, target);
11936
12042
  console.warn(`[AgentMoss] \u94FE\u72B6\u6001\u6587\u4EF6\u6309 instance \u9694\u79BB\uFF1A\u5DF2\u4ECE\u65E7\u5171\u4EAB\u6587\u4EF6\u590D\u5236\u5230 ${target}`);
11937
12043
  } catch (err) {
11938
12044
  console.warn("[AgentMoss] \u8FC1\u79FB\u94FE\u72B6\u6001\u6587\u4EF6\u5931\u8D25\uFF08\u5C06\u4F7F\u7528\u65B0\u7A7A\u6587\u4EF6\uFF09:", err);
@@ -12010,8 +12116,8 @@ var init_chain_state = __esm({
12010
12116
  }
12011
12117
  _read() {
12012
12118
  try {
12013
- if (fs5.existsSync(this.filePath)) {
12014
- const raw = fs5.readFileSync(this.filePath, "utf-8");
12119
+ if (fs6.existsSync(this.filePath)) {
12120
+ const raw = fs6.readFileSync(this.filePath, "utf-8");
12015
12121
  return JSON.parse(raw);
12016
12122
  }
12017
12123
  } catch {
@@ -12025,7 +12131,7 @@ var init_chain_state = __esm({
12025
12131
  this._timer = null;
12026
12132
  try {
12027
12133
  this._syncDirtyToData();
12028
- ensurePrivateDir(path6.dirname(this.filePath));
12134
+ ensurePrivateDir(path7.dirname(this.filePath));
12029
12135
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12030
12136
  } catch {
12031
12137
  }
@@ -12048,7 +12154,7 @@ var init_chain_state = __esm({
12048
12154
  }
12049
12155
  try {
12050
12156
  this._syncDirtyToData();
12051
- ensurePrivateDir(path6.dirname(this.filePath));
12157
+ ensurePrivateDir(path7.dirname(this.filePath));
12052
12158
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12053
12159
  } catch {
12054
12160
  }
@@ -12089,16 +12195,16 @@ var init_chain_state = __esm({
12089
12195
  const sleepBuf = new Int32Array(new SharedArrayBuffer(4));
12090
12196
  for (let attempt = 0; attempt < 100; attempt++) {
12091
12197
  try {
12092
- const fd = fs5.openSync(lockPath, "wx");
12198
+ const fd = fs6.openSync(lockPath, "wx");
12093
12199
  try {
12094
12200
  return fn();
12095
12201
  } finally {
12096
12202
  try {
12097
- fs5.closeSync(fd);
12203
+ fs6.closeSync(fd);
12098
12204
  } catch {
12099
12205
  }
12100
12206
  try {
12101
- fs5.unlinkSync(lockPath);
12207
+ fs6.unlinkSync(lockPath);
12102
12208
  } catch {
12103
12209
  }
12104
12210
  }
@@ -12116,7 +12222,7 @@ var init_chain_state = __esm({
12116
12222
  _flushNow() {
12117
12223
  this._syncDirtyToData();
12118
12224
  try {
12119
- const _dirOk = ensurePrivateDir(path6.dirname(this.filePath));
12225
+ const _dirOk = ensurePrivateDir(path7.dirname(this.filePath));
12120
12226
  const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12121
12227
  if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
12122
12228
  } catch (e) {
@@ -12824,7 +12930,7 @@ init_paths();
12824
12930
  import { cors } from "hono/cors";
12825
12931
  import { logger } from "hono/logger";
12826
12932
  import net from "net";
12827
- import { existsSync as existsSync21, writeFileSync as writeFileSync6, renameSync as renameSync3, mkdirSync as mkdirSync9 } from "fs";
12933
+ import { existsSync as existsSync21, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync10 } from "fs";
12828
12934
  import { dirname as dirname15 } from "path";
12829
12935
 
12830
12936
  // src/package-json.ts
@@ -12995,7 +13101,7 @@ init_security_policy();
12995
13101
  init_coordinator();
12996
13102
  import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
12997
13103
  import { tmpdir as tmpdir3 } from "os";
12998
- import { join as join17, resolve as resolve11 } from "path";
13104
+ import { join as join18, resolve as resolve11 } from "path";
12999
13105
 
13000
13106
  // src/engine/types.ts
13001
13107
  init_esm_shims();
@@ -13018,8 +13124,8 @@ init_config();
13018
13124
  import { createHash as createHash5 } from "crypto";
13019
13125
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
13020
13126
  import { tmpdir as tmpdir2 } from "os";
13021
- import { join as join16 } from "path";
13022
- var CACHE_DIR = join16(tmpdir2(), "agent_moss_policy_cache");
13127
+ import { join as join17 } from "path";
13128
+ var CACHE_DIR = join17(tmpdir2(), "agent_moss_policy_cache");
13023
13129
  var cacheDirOverride = null;
13024
13130
  function cacheDir() {
13025
13131
  return cacheDirOverride ?? CACHE_DIR;
@@ -13028,7 +13134,7 @@ function safeCacheDir() {
13028
13134
  const dir = cacheDir();
13029
13135
  if (ensurePrivateDir(dir)) return dir;
13030
13136
  try {
13031
- const fallback = join16(getDataRoot(), "policy_cache");
13137
+ const fallback = join17(getDataRoot(), "policy_cache");
13032
13138
  if (ensurePrivateDir(fallback)) {
13033
13139
  console.warn(`[AgentMoss] \u7F13\u5B58\u76EE\u5F55 ${dir} \u4E0D\u5B89\u5168\uFF08\u88AB\u5176\u4ED6\u7528\u6237\u62E5\u6709\u6216\u4E3A\u7B26\u53F7\u94FE\u63A5\uFF09\uFF0C\u5DF2\u56DE\u9000\u5230 ${fallback}`);
13034
13140
  return fallback;
@@ -13050,7 +13156,7 @@ var PolicyCache = class {
13050
13156
  cacheFilePath(sessionId, promptSession) {
13051
13157
  const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
13052
13158
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13053
- return join16(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13159
+ return join17(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13054
13160
  }
13055
13161
  /** 取缓存:内存 → 文件;未命中返回 null。 */
13056
13162
  get(sessionId, promptSession) {
@@ -13081,7 +13187,7 @@ var PolicyCache = class {
13081
13187
  try {
13082
13188
  const dir = safeCacheDir();
13083
13189
  const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13084
- if (!ensurePrivateDir(join16(dir, sub))) return;
13190
+ if (!ensurePrivateDir(join17(dir, sub))) return;
13085
13191
  writePrivateText(file, policy);
13086
13192
  } catch {
13087
13193
  }
@@ -13107,12 +13213,12 @@ var PolicyCache = class {
13107
13213
  if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
13108
13214
  }
13109
13215
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13110
- const dir = join16(cacheDir(), safeSessionId);
13216
+ const dir = join17(cacheDir(), safeSessionId);
13111
13217
  try {
13112
13218
  if (existsSync17(dir)) {
13113
13219
  for (const f of readdirSync5(dir)) {
13114
13220
  try {
13115
- unlinkSync4(join16(dir, f));
13221
+ unlinkSync4(join17(dir, f));
13116
13222
  } catch {
13117
13223
  }
13118
13224
  }
@@ -13126,9 +13232,9 @@ var PolicyCache = class {
13126
13232
  try {
13127
13233
  if (existsSync17(cacheDir())) {
13128
13234
  for (const sessionDir of readdirSync5(cacheDir())) {
13129
- const dir = join16(cacheDir(), sessionDir);
13235
+ const dir = join17(cacheDir(), sessionDir);
13130
13236
  try {
13131
- for (const f of readdirSync5(dir)) unlinkSync4(join16(dir, f));
13237
+ for (const f of readdirSync5(dir)) unlinkSync4(join17(dir, f));
13132
13238
  rmdirSync(dir);
13133
13239
  } catch {
13134
13240
  }
@@ -13215,7 +13321,7 @@ ${safe(policy, 2e3)}`);
13215
13321
 
13216
13322
  // src/engine/analyzer.ts
13217
13323
  import { parse as parseToml } from "smol-toml";
13218
- var POLICY_OUTPUT_DIR = join17(tmpdir3(), "agent_moss");
13324
+ var POLICY_OUTPUT_DIR = join18(tmpdir3(), "agent_moss");
13219
13325
  var policyOutputDirOverride = null;
13220
13326
  function policyOutputDir() {
13221
13327
  return policyOutputDirOverride ?? POLICY_OUTPUT_DIR;
@@ -13254,7 +13360,7 @@ function savePolicyToFile(sessionId, policyToml) {
13254
13360
  return null;
13255
13361
  }
13256
13362
  const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13257
- const filepath = join17(outDir, `${safeName}.toml`);
13363
+ const filepath = join18(outDir, `${safeName}.toml`);
13258
13364
  writePrivateText(filepath, policyToml);
13259
13365
  return filepath;
13260
13366
  } catch (err) {
@@ -13466,7 +13572,7 @@ async function analyzeInner(input, mossLog) {
13466
13572
 
13467
13573
  // src/actrail.ts
13468
13574
  init_esm_shims();
13469
- import * as fs6 from "fs";
13575
+ import * as fs7 from "fs";
13470
13576
 
13471
13577
  // src/infra/esm-require.ts
13472
13578
  init_esm_shims();
@@ -13497,7 +13603,7 @@ function getStoragePath() {
13497
13603
  function reportEnforcementEvent(opts) {
13498
13604
  if (!isEnabled()) return false;
13499
13605
  const storagePath = getStoragePath();
13500
- if (!fs6.existsSync(storagePath)) return false;
13606
+ if (!fs7.existsSync(storagePath)) return false;
13501
13607
  try {
13502
13608
  let Database;
13503
13609
  try {
@@ -13660,11 +13766,11 @@ function mineDangerousPatterns(sessions, minSup = 2, maxLen = 4) {
13660
13766
 
13661
13767
  // src/agent-gate-reader.ts
13662
13768
  init_esm_shims();
13663
- import * as fs7 from "fs";
13664
- import * as os4 from "os";
13665
- import * as path7 from "path";
13666
- var DEFAULT_AGENTGATE_SQLITE = path7.join(
13667
- os4.homedir(),
13769
+ import * as fs8 from "fs";
13770
+ import * as os5 from "os";
13771
+ import * as path8 from "path";
13772
+ var DEFAULT_AGENTGATE_SQLITE = path8.join(
13773
+ os5.homedir(),
13668
13774
  ".local",
13669
13775
  "share",
13670
13776
  "agent_gate",
@@ -13679,10 +13785,10 @@ function normalizeAction(row) {
13679
13785
  function readJsonDir(dirPath, limit = 1e5) {
13680
13786
  const sessions = /* @__PURE__ */ new Map();
13681
13787
  try {
13682
- const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
13788
+ const files = fs8.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
13683
13789
  for (const f of files.slice(-200)) {
13684
13790
  const sid = f.replace(/\.json$/, "");
13685
- const raw = fs7.readFileSync(path7.join(dirPath, f), "utf-8");
13791
+ const raw = fs8.readFileSync(path8.join(dirPath, f), "utf-8");
13686
13792
  const arr = JSON.parse(raw);
13687
13793
  if (!Array.isArray(arr)) continue;
13688
13794
  for (const item of arr) {
@@ -13739,7 +13845,7 @@ function readSqlite(dbPath, limit = 1e5) {
13739
13845
  function loadAgentGateSessions(dbPath = "") {
13740
13846
  if (dbPath) {
13741
13847
  try {
13742
- if (fs7.statSync(dbPath).isDirectory()) {
13848
+ if (fs8.statSync(dbPath).isDirectory()) {
13743
13849
  return readJsonDir(dbPath);
13744
13850
  }
13745
13851
  } catch {
@@ -13750,7 +13856,7 @@ function loadAgentGateSessions(dbPath = "") {
13750
13856
  }
13751
13857
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
13752
13858
  if (sql.length > 0) return sql;
13753
- const jsonDefault = path7.join(os4.homedir(), ".local", "share", "agent_gate", "tool_calls");
13859
+ const jsonDefault = path8.join(os5.homedir(), ".local", "share", "agent_gate", "tool_calls");
13754
13860
  return readJsonDir(jsonDefault);
13755
13861
  }
13756
13862
 
@@ -13874,7 +13980,7 @@ function poolsSnapshot() {
13874
13980
 
13875
13981
  // src/routes.ts
13876
13982
  init_metrics();
13877
- import { join as join19, dirname as dirname13 } from "path";
13983
+ import { join as join20, dirname as dirname13 } from "path";
13878
13984
  import { fileURLToPath as fileURLToPath10 } from "url";
13879
13985
  var __dirname9 = dirname13(fileURLToPath10(import.meta.url));
13880
13986
  async function healthRoute(c) {
@@ -13897,11 +14003,11 @@ async function healthRoute(c) {
13897
14003
  if (typeof pct === "number") {
13898
14004
  if (pct >= 100) {
13899
14005
  degraded.push(
13900
- `\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`
14006
+ `\u3010\u5DF2\u964D\u7EA7\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u8FBE\u5230\u4E0A\u9650\uFF08${metrics.chain_nodes}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u7CFB\u7EDF\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u9700\u8981\u624B\u5DE5 state reset\uFF1B\u82E5\u6301\u7EED\u51FA\u73B0\uFF0C\u68C0\u67E5\u5F52\u6863\u76EE\u5F55\u6743\u9650/\u78C1\u76D8\u7A7A\u95F4\u3002L1/L2.1/L3 \u6B63\u5E38\u3002\u8BE6\u89C1 docs/deploy/UPGRADE_GUIDE.md`
13901
14007
  );
13902
14008
  } else if (pct >= 90) {
13903
14009
  degraded.push(
13904
- `\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`
14010
+ `\u3010\u9884\u8B66\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u5DF2\u7528 ${pct}%\uFF08${metrics.chain_nodes}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u8FBE\u5230\u4E0A\u9650\u540E\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u4F1A\u5BFC\u81F4\u7EC4\u5408\u94FE\u68C0\u6D4B\u5931\u6548\uFF1B\u65E0\u9700\u624B\u5DE5 state reset\u3002\u8BE6\u89C1 docs/deploy/PERFORMANCE_TUNING.md \u7B2C 5 \u8282`
13905
14011
  );
13906
14012
  }
13907
14013
  }
@@ -13909,7 +14015,7 @@ async function healthRoute(c) {
13909
14015
  const snap = getBreaker().snapshot();
13910
14016
  if (snap.state === "open") {
13911
14017
  degraded.push(
13912
- `\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`
14018
+ `\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/deploy/LLM_TROUBLESHOOTING.md`
13913
14019
  );
13914
14020
  }
13915
14021
  } catch {
@@ -13929,6 +14035,14 @@ async function analyzeRoute(c) {
13929
14035
  try {
13930
14036
  const body = await c.req.json();
13931
14037
  const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
14038
+ const unmappedTool = String(
14039
+ req.metadata?.unmapped_tool || ""
14040
+ );
14041
+ if (unmappedTool) {
14042
+ degradedNotes.push(
14043
+ `\u3010\u5DF2\u964D\u7EA7\u3011\u5DE5\u5177\u540D '${unmappedTool}' \u672A\u8BC6\u522B\u4E3A\u6807\u51C6\u52A8\u4F5C\u7C7B\u578B\uFF1A\u4F9D\u8D56\u52A8\u4F5C\u7C7B\u578B\u7684 L2 \u89C4\u5219\uFF08\u8BFB\u540E\u5199 / \u7EC4\u5408\u94FE / \u6388\u6743\uFF09\u53EF\u80FD\u672A\u751F\u6548\uFF1BL1\uFF08\u547D\u4EE4\u5185\u5BB9\uFF09\u4E0E L3 \u6B63\u5E38\u3002\u53EF\u5728 AgentGate \u914D\u7F6E AGENT_GATE_TOOL_NAME_MAP \u8865\u5145\u6620\u5C04\uFF08\u5982 {"${unmappedTool}": "read"}\uFF09\u3002`
14044
+ );
14045
+ }
13932
14046
  let osType = req.os_type;
13933
14047
  if (!osType) {
13934
14048
  osType = process.platform === "win32" ? "windows" : "linux";
@@ -14109,11 +14223,11 @@ async function analyzeRoute(c) {
14109
14223
  const pct = Math.round(total / MAX_NODES * 1e3) / 10;
14110
14224
  if (total >= MAX_NODES) {
14111
14225
  degradedNotes.push(
14112
- `\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`
14226
+ `\u3010\u5DF2\u964D\u7EA7\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u8FBE\u5230\u4E0A\u9650\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u7CFB\u7EDF\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u9700\u8981\u624B\u5DE5 state reset\uFF1B\u82E5\u6301\u7EED\u51FA\u73B0\uFF0C\u68C0\u67E5\u5F52\u6863\u76EE\u5F55\u6743\u9650/\u78C1\u76D8\u7A7A\u95F4\u3002L1/L2.1/L3 \u6B63\u5E38\u3002\u8BE6\u89C1 docs/deploy/UPGRADE_GUIDE.md`
14113
14227
  );
14114
14228
  } else if (pct >= 90) {
14115
14229
  degradedNotes.push(
14116
- `\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`
14230
+ `\u3010\u9884\u8B66\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u5DF2\u7528 ${pct}%\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u8FBE\u5230\u4E0A\u9650\u540E\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u4F1A\u5BFC\u81F4\u7EC4\u5408\u94FE\u68C0\u6D4B\u5931\u6548\uFF1B\u65E0\u9700\u624B\u5DE5 state reset\u3002\u8BE6\u89C1 docs/deploy/PERFORMANCE_TUNING.md \u7B2C 5 \u8282`
14117
14231
  );
14118
14232
  }
14119
14233
  } catch {
@@ -14303,7 +14417,7 @@ function getBrainRuleStore() {
14303
14417
  return new BrainRuleStore();
14304
14418
  }
14305
14419
  function getBrainSkillManager() {
14306
- const dir = resolveAssetDir(__dirname9, "skills") ?? join19(__dirname9, "..", "..", "agent_moss", "skills");
14420
+ const dir = resolveAssetDir(__dirname9, "skills") ?? join20(__dirname9, "..", "..", "agent_moss", "skills");
14307
14421
  return new BrainSkillManager(dir);
14308
14422
  }
14309
14423
  async function brainRulesRoute(c) {
@@ -14408,10 +14522,10 @@ init_rules_mode();
14408
14522
  import { Hono } from "hono";
14409
14523
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
14410
14524
  import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
14411
- import { join as join20, dirname as dirname14 } from "path";
14525
+ import { join as join21, dirname as dirname14 } from "path";
14412
14526
  import { fileURLToPath as fileURLToPath11 } from "url";
14413
14527
  var __dirname10 = dirname14(fileURLToPath11(import.meta.url));
14414
- var STATIC_DIR = join20(__dirname10, "static");
14528
+ var STATIC_DIR = join21(__dirname10, "static");
14415
14529
  var CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
14416
14530
  function getConsoleToken() {
14417
14531
  return process.env[CONSOLE_TOKEN_ENV] || "";
@@ -14453,7 +14567,7 @@ function createConsoleRouter() {
14453
14567
  console2.use("/api/*", authMiddleware());
14454
14568
  console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
14455
14569
  const serveIndex = (c) => {
14456
- const indexFile = join20(STATIC_DIR, "index.html");
14570
+ const indexFile = join21(STATIC_DIR, "index.html");
14457
14571
  if (existsSync20(indexFile)) {
14458
14572
  return c.html(readFileSync20(indexFile, "utf-8"));
14459
14573
  }
@@ -14650,11 +14764,11 @@ function createConsoleRouter() {
14650
14764
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
14651
14765
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
14652
14766
  }
14653
- const userPath = join20(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14767
+ const userPath = join21(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14654
14768
  const builtinDir = resolveAssetDir(__dirname10, "skills");
14655
14769
  const candidates = [
14656
14770
  ...isRuntimeConfigDisabled() ? [] : [userPath],
14657
- builtinDir ? join20(builtinDir, `${skillId}.md`) : ""
14771
+ builtinDir ? join21(builtinDir, `${skillId}.md`) : ""
14658
14772
  ].filter(Boolean);
14659
14773
  for (const p of candidates) {
14660
14774
  if (existsSync20(p)) {
@@ -14924,7 +15038,7 @@ function createApp() {
14924
15038
  startLoopMonitor();
14925
15039
  const limiter = new RateLimiter(rateLimitQps());
14926
15040
  app.use("*", async (c, next) => {
14927
- const path8 = new URL(c.req.url).pathname;
15041
+ const path9 = new URL(c.req.url).pathname;
14928
15042
  const method = c.req.method.toUpperCase();
14929
15043
  if (method === "OPTIONS") return next();
14930
15044
  const maxBody = maxBodyBytes();
@@ -14938,16 +15052,16 @@ function createApp() {
14938
15052
  if (originCheckEnabled()) {
14939
15053
  const origin = c.req.header("origin") || "";
14940
15054
  if (origin && !originAllowed(origin, c.req.header("host") || "")) {
14941
- console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path8}`);
15055
+ console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path9}`);
14942
15056
  return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
14943
15057
  }
14944
15058
  }
14945
- const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path8);
14946
- const isPublicPage = !path8.startsWith("/console/api") && (path8 === "/console" || path8.startsWith("/console/"));
15059
+ const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path9);
15060
+ const isPublicPage = !path9.startsWith("/console/api") && (path9 === "/console" || path9.startsWith("/console/"));
14947
15061
  if (!okAuth && !isPublicPage) {
14948
15062
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
14949
15063
  }
14950
- if (limiter.enabled && path8.startsWith("/api/")) {
15064
+ if (limiter.enabled && path9.startsWith("/api/")) {
14951
15065
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
14952
15066
  if (!limiter.allow(key)) {
14953
15067
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
@@ -14981,7 +15095,7 @@ function createApp() {
14981
15095
  return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
14982
15096
  }
14983
15097
  }
14984
- const pool = poolOf(path8);
15098
+ const pool = poolOf(path9);
14985
15099
  if (!take(`pool:${pool}`, poolLimit(pool))) {
14986
15100
  const qkey = principal ? "p:" + principalHash(principal) : "c:local";
14987
15101
  const [qn, abusive] = noteQueueReject(qkey);
@@ -15081,8 +15195,8 @@ async function warmUpEngine() {
15081
15195
  }
15082
15196
  function writePortFile(port) {
15083
15197
  try {
15084
- const path8 = getPortFilePath();
15085
- mkdirSync9(dirname15(path8), { recursive: true });
15198
+ const path9 = getPortFilePath();
15199
+ mkdirSync10(dirname15(path9), { recursive: true });
15086
15200
  const payload = JSON.stringify({
15087
15201
  port,
15088
15202
  pid: process.pid,
@@ -15091,10 +15205,10 @@ function writePortFile(port) {
15091
15205
  version,
15092
15206
  started_at: (/* @__PURE__ */ new Date()).toISOString()
15093
15207
  });
15094
- const tmp = `${path8}.tmp`;
15095
- writeFileSync6(tmp, payload, "utf-8");
15096
- renameSync3(tmp, path8);
15097
- console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path8} (port=${port})`);
15208
+ const tmp = `${path9}.tmp`;
15209
+ writeFileSync7(tmp, payload, "utf-8");
15210
+ renameSync3(tmp, path9);
15211
+ console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path9} (port=${port})`);
15098
15212
  } catch (err) {
15099
15213
  console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
15100
15214
  }
@@ -15135,12 +15249,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15135
15249
  },
15136
15250
  serve: async () => {
15137
15251
  failFastOnAuthError();
15138
- const { mkdirSync: mkdirSync10, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
15252
+ const { mkdirSync: mkdirSync11, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
15139
15253
  const { dirname: dirname16 } = await import("path");
15140
15254
  const dir = dirname16(socketPath);
15141
15255
  if (dir) {
15142
15256
  try {
15143
- mkdirSync10(dir, { recursive: true });
15257
+ mkdirSync11(dir, { recursive: true });
15144
15258
  } catch {
15145
15259
  }
15146
15260
  }