@kenhkl/agent-moss 0.17.33 → 0.17.35

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
@@ -96,6 +96,13 @@ function getTokenStatsPath() {
96
96
  }
97
97
  return join(getDataRoot(), "agent_moss_token_stats.json");
98
98
  }
99
+ function getInstanceDir() {
100
+ const instance = getInstance();
101
+ return instance ? join(getDataRoot(), instance) : getDataRoot();
102
+ }
103
+ function getPortFilePath() {
104
+ return join(getInstanceDir(), "agent_moss_server.port.json");
105
+ }
99
106
  var ENV_DATA_ROOT, ENV_INSTANCE, DEFAULT_DATA_ROOT, ENV_RULES_ROOT, ID_MAX_LEN, ID_PATTERN;
100
107
  var init_paths = __esm({
101
108
  "src/infra/paths.ts"() {
@@ -401,22 +408,22 @@ function loadToolRegistry() {
401
408
  data.tools = tools;
402
409
  return data;
403
410
  }
404
- function scanStructEntry(cat, value, path8) {
411
+ function scanStructEntry(cat, value, path9) {
405
412
  if (cat === "skills") {
406
413
  if (!value || typeof value !== "object" || Array.isArray(value)) {
407
- 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`);
408
415
  return null;
409
416
  }
410
417
  const out = {};
411
418
  for (const [skCat, skills] of Object.entries(value)) {
412
419
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
413
- 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`);
414
421
  continue;
415
422
  }
416
423
  const keep = {};
417
424
  for (const [name, kws] of Object.entries(skills)) {
418
425
  if (Array.isArray(kws)) keep[name] = kws;
419
- 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`);
420
427
  }
421
428
  if (Object.keys(keep).length > 0) out[skCat] = keep;
422
429
  }
@@ -424,37 +431,37 @@ function scanStructEntry(cat, value, path8) {
424
431
  }
425
432
  if (cat === "ltl_rules") {
426
433
  if (!Array.isArray(value)) {
427
- 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`);
428
435
  return null;
429
436
  }
430
437
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
431
438
  if (keep.length !== value.length) {
432
- 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`);
433
440
  }
434
441
  return keep.length > 0 ? keep : null;
435
442
  }
436
443
  if (cat === "tools") {
437
444
  if (!value || typeof value !== "object" || Array.isArray(value)) {
438
- 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`);
439
446
  return null;
440
447
  }
441
448
  const keep = {};
442
449
  for (const [k, v] of Object.entries(value)) {
443
450
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
444
- 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`);
445
452
  }
446
453
  return Object.keys(keep).length > 0 ? keep : null;
447
454
  }
448
455
  return null;
449
456
  }
450
- function scanRulesFile(path8, kind) {
457
+ function scanRulesFile(path9, kind) {
451
458
  const out = {};
452
459
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
453
460
  let parsed;
454
461
  try {
455
- parsed = JSON.parse(readFileSync2(path8, "utf-8"));
462
+ parsed = JSON.parse(readFileSync2(path9, "utf-8"));
456
463
  } catch (e) {
457
- 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}`);
458
465
  return out;
459
466
  }
460
467
  const classifyFlat = (r) => {
@@ -478,44 +485,44 @@ function scanRulesFile(path8, kind) {
478
485
  }
479
486
  if (flatBad > 0) {
480
487
  console.warn(
481
- `[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`
482
489
  );
483
490
  }
484
491
  } else {
485
- 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`);
486
493
  return out;
487
494
  }
488
495
  for (const [cat, rules] of pairs) {
489
496
  if (String(cat).startsWith("_")) continue;
490
497
  if (STRUCT_KEYS.includes(cat)) {
491
- const got = scanStructEntry(cat, rules, path8);
498
+ const got = scanStructEntry(cat, rules, path9);
492
499
  if (got !== null) out[cat] = got;
493
500
  continue;
494
501
  }
495
502
  const required = EXTRA_CATEGORIES[cat];
496
503
  if (!required) {
497
504
  console.warn(
498
- `[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`
499
506
  );
500
507
  continue;
501
508
  }
502
509
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
503
510
  console.error(
504
- `[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
505
512
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
506
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`
507
514
  );
508
515
  continue;
509
516
  }
510
517
  if (!Array.isArray(rules)) {
511
- 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`);
512
519
  continue;
513
520
  }
514
521
  const items = [];
515
522
  for (const r of rules) {
516
523
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
517
524
  console.warn(
518
- `[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`
519
526
  );
520
527
  continue;
521
528
  }
@@ -525,7 +532,7 @@ function scanRulesFile(path8, kind) {
525
532
  }
526
533
  if (Object.keys(out).length > 0) {
527
534
  console.info(
528
- `[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(", ")
529
536
  );
530
537
  }
531
538
  return out;
@@ -790,44 +797,51 @@ function readFdToken() {
790
797
  fdTokenCache.set(fd, tok);
791
798
  return tok;
792
799
  }
793
- function readExplicitToken() {
800
+ function readExplicitTokenResult() {
794
801
  const tok = env("AGENT_MOSS_AUTH_TOKEN");
795
- if (tok) return tok;
802
+ if (tok) return [tok, ""];
796
803
  const fdTok = readFdToken();
797
- if (fdTok) return fdTok;
798
- const path8 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
799
- if (path8) {
804
+ if (fdTok) return [fdTok, ""];
805
+ const path9 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
806
+ if (path9) {
800
807
  try {
801
- return readFileSync4(path8, "utf-8").trim();
802
- } catch {
803
- 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`];
804
815
  }
805
816
  }
806
- return "";
817
+ return ["", ""];
807
818
  }
808
819
  function ensureAutoToken() {
809
- const path8 = autoTokenPath();
820
+ const path9 = autoTokenPath();
810
821
  try {
811
- if (existsSync3(path8) && !lstatSync(path8).isSymbolicLink()) {
812
- const tok2 = readFileSync4(path8, "utf-8").trim();
822
+ if (existsSync3(path9) && !lstatSync(path9).isSymbolicLink()) {
823
+ const tok2 = readFileSync4(path9, "utf-8").trim();
813
824
  if (tok2) {
814
825
  try {
815
- chmodSync(path8, 384);
826
+ chmodSync(path9, 384);
816
827
  } catch {
817
828
  }
818
829
  return tok2;
819
830
  }
820
831
  }
821
832
  const tok = randomBytes(32).toString("base64url");
822
- ensurePrivateDir(dirname2(path8));
823
- 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
+ }
824
839
  console.warn(
825
- `[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`
826
841
  );
827
842
  return tok;
828
843
  } catch (e) {
829
- console.error("[AgentMoss] \u751F\u6210\u8BBF\u95EE token \u5931\u8D25\uFF08\u672C\u6B21\u8FD0\u884C\u5C06\u4E0D\u9274\u6743\uFF09:", e);
830
- return "";
844
+ throw new Error(`\u81EA\u52A8\u8BBF\u95EE token \u751F\u6210/\u8BFB\u53D6\u5931\u8D25\uFF08${path9}\uFF09\uFF1A${e?.message ?? e}`);
831
845
  }
832
846
  }
833
847
  function parseAgentTokens(raw) {
@@ -856,12 +870,22 @@ function resolveAuth() {
856
870
  return [tokenCache.token, tokenCache.agents, tokenCache.error];
857
871
  }
858
872
  let error = "";
859
- let token = readExplicitToken();
860
- 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) {
861
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";
862
879
  console.error(`[agent-moss] ${error}`);
863
880
  }
864
- 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
+ }
865
889
  const agents = parseAgentTokens(rawAgents);
866
890
  tokenCache = { key, token, agents, error };
867
891
  return [token, agents, error];
@@ -881,8 +905,8 @@ function failFastOnAuthError() {
881
905
  }
882
906
  function authEnabled() {
883
907
  if (authMode() === AUTH_MODE_OFF) return false;
884
- const [tok, agents] = resolveAuth();
885
- 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;
886
910
  }
887
911
  function bearer(headers) {
888
912
  const get = (k) => headers instanceof Headers ? headers.get(k) ?? "" : headers[k] ?? "";
@@ -895,16 +919,16 @@ function constEq(a, b) {
895
919
  if (ba.length !== bb.length) return false;
896
920
  return timingSafeEqual(ba, bb);
897
921
  }
898
- function checkRequestAuth(headers, path8) {
922
+ function checkRequestAuth(headers, path9) {
899
923
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
900
- const isHealth = HEALTH_PATHS.includes(path8.replace(/\/+$/, ""));
924
+ const isHealth = HEALTH_PATHS.includes(path9.replace(/\/+$/, ""));
901
925
  const [gt0, agents, err] = resolveAuth();
902
926
  if (err) return isHealth ? [true, ""] : [false, ""];
903
927
  if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
904
928
  if (isHealth) return [true, ""];
905
929
  const tok = bearer(headers);
906
930
  if (!tok) return [false, ""];
907
- if (path8.startsWith("/console/api")) {
931
+ if (path9.startsWith("/console/api")) {
908
932
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
909
933
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
910
934
  }
@@ -923,8 +947,8 @@ function bindAgent(principal, agentId) {
923
947
  if (!agentId) return [true, bound];
924
948
  return [bound === agentId, bound];
925
949
  }
926
- function principalOf(headers, path8 = "") {
927
- const [ok, principal] = checkRequestAuth(headers, path8);
950
+ function principalOf(headers, path9 = "") {
951
+ const [ok, principal] = checkRequestAuth(headers, path9);
928
952
  return ok ? principal : "";
929
953
  }
930
954
  function principalHash(principal) {
@@ -1181,11 +1205,11 @@ function errorDetailMode() {
1181
1205
  function maxBodyBytes() {
1182
1206
  return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
1183
1207
  }
1184
- function poolOf(path8) {
1185
- if (path8 === "/api/v1/analyze" || path8.startsWith("/api/v1/analyze/")) return "biz";
1186
- if (path8 === "/api/v1/review" || path8.startsWith("/api/v1/review/")) return "review";
1187
- if (path8 === "/console" || path8.startsWith("/console/") || path8.startsWith("/api/v1/brain")) return "ops";
1188
- 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";
1189
1213
  return "other";
1190
1214
  }
1191
1215
  function poolLimit(name) {
@@ -1500,7 +1524,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
1500
1524
  os: String(sp.os || "linux").toLowerCase()
1501
1525
  }));
1502
1526
  }
1503
- function _scopeOf(os5, path8) {
1527
+ function _scopeOf(os6, path9) {
1504
1528
  if (!_scopeIndex) {
1505
1529
  _scopeIndex = /* @__PURE__ */ new Map();
1506
1530
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -1508,7 +1532,7 @@ function _scopeOf(os5, path8) {
1508
1532
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
1509
1533
  }
1510
1534
  }
1511
- return _scopeIndex.get(`${String(os5 || "linux").toLowerCase()}|${path8}`) || "root";
1535
+ return _scopeIndex.get(`${String(os6 || "linux").toLowerCase()}|${path9}`) || "root";
1512
1536
  }
1513
1537
  function getSensitivePathsForOs(osType) {
1514
1538
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -2227,36 +2251,36 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2227
2251
  }
2228
2252
  const preciseEdit = isPreciseEditTool(actionType);
2229
2253
  const unreadPaths = [];
2230
- for (const path8 of checkTargets) {
2231
- if (isDirectoryTarget(path8)) continue;
2254
+ for (const path9 of checkTargets) {
2255
+ if (isDirectoryTarget(path9)) continue;
2232
2256
  let isFullRead = [...normalizedFullReads].some(
2233
- (rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
2257
+ (rp) => pathIsSameOrUnder(path9, rp) || pathIsSameOrUnder(rp, path9)
2234
2258
  );
2235
2259
  if (!isFullRead && preciseEdit && [...normalizedWrittenPaths].some(
2236
- (wp) => pathIsSameOrUnder(path8, wp) || pathIsSameOrUnder(wp, path8)
2260
+ (wp) => pathIsSameOrUnder(path9, wp) || pathIsSameOrUnder(wp, path9)
2237
2261
  )) {
2238
2262
  isFullRead = true;
2239
2263
  }
2240
- if (!isFullRead && !isProtectedWritePath(path8) && isScriptGeneratedTarget(path8, historyWrittenScripts, shellRunActions)) {
2264
+ if (!isFullRead && !isProtectedWritePath(path9) && isScriptGeneratedTarget(path9, historyWrittenScripts, shellRunActions)) {
2241
2265
  isFullRead = true;
2242
2266
  }
2243
2267
  let isPartialCovered = false;
2244
2268
  if (!isFullRead) {
2245
2269
  for (const [pp, upto] of normalizedPartialReads) {
2246
- if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
2247
- if (preciseEdit || upto != null && fileHasAtMostLines(path8, upto)) {
2270
+ if (!(pathIsSameOrUnder(path9, pp) || pathIsSameOrUnder(pp, path9))) continue;
2271
+ if (preciseEdit || upto != null && fileHasAtMostLines(path9, upto)) {
2248
2272
  isPartialCovered = true;
2249
2273
  break;
2250
2274
  }
2251
2275
  }
2252
2276
  }
2253
2277
  if (!isFullRead && !isPartialCovered) {
2254
- let isCreate = !fs.existsSync(path8);
2278
+ let isCreate = !fs.existsSync(path9);
2255
2279
  if (!isCreate) {
2256
2280
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
2257
2281
  }
2258
2282
  if (!isCreate) {
2259
- unreadPaths.push(path8);
2283
+ unreadPaths.push(path9);
2260
2284
  }
2261
2285
  }
2262
2286
  }
@@ -2450,16 +2474,16 @@ var init_logic_rules = __esm({
2450
2474
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
2451
2475
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
2452
2476
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
2453
- 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 }));
2454
2478
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
2455
2479
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
2456
- 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 }));
2457
2481
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
2458
2482
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
2459
- 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 }));
2460
2484
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
2461
2485
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
2462
- 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 }));
2463
2487
  _scopeIndex = null;
2464
2488
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
2465
2489
  "ask_user_question",
@@ -2935,8 +2959,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
2935
2959
  function _filterRulesByOs(rules, osType) {
2936
2960
  const accepted = acceptedOsValues(osType);
2937
2961
  return rules.filter((r) => {
2938
- const os5 = String(r.os || "linux").toLowerCase();
2939
- return os5 === "all" || accepted.includes(os5);
2962
+ const os6 = String(r.os || "linux").toLowerCase();
2963
+ return os6 === "all" || accepted.includes(os6);
2940
2964
  });
2941
2965
  }
2942
2966
  function _userCustomRules(runtime, layers, requiredKey) {
@@ -3138,7 +3162,7 @@ function _l2SensitivePathsToRules() {
3138
3162
  const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
3139
3163
  const all = [...root, ...home, ...credential];
3140
3164
  for (const sp of all) {
3141
- const os5 = String(sp.os || "linux").toLowerCase();
3165
+ const os6 = String(sp.os || "linux").toLowerCase();
3142
3166
  const denyMode = sp.denyMode || _deriveDenyMode({
3143
3167
  deny_mode: sp.deny_mode,
3144
3168
  credential: sp.credential,
@@ -3148,7 +3172,7 @@ function _l2SensitivePathsToRules() {
3148
3172
  // id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
3149
3173
  // hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
3150
3174
  // Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
3151
- id: `path_${os5}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3175
+ id: `path_${os6}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3152
3176
  path: sp.path,
3153
3177
  risk_level: sp.riskLevel,
3154
3178
  desc: sp.desc,
@@ -3157,7 +3181,7 @@ function _l2SensitivePathsToRules() {
3157
3181
  skip_l3_on_disabled: true,
3158
3182
  enabled: true,
3159
3183
  builtin: true,
3160
- os: os5
3184
+ os: os6
3161
3185
  };
3162
3186
  _syncDenyModeFields(rule);
3163
3187
  if (sp.dirDelOnly) rule.dir_del_only = true;
@@ -3695,8 +3719,8 @@ function _filterDefaultsByOs(rules, osType) {
3695
3719
  const accepted = acceptedOsValues(osType);
3696
3720
  return rules.filter((r) => {
3697
3721
  if (!r.os) return true;
3698
- const os5 = String(r.os).toLowerCase();
3699
- return os5 === "all" || accepted.includes(os5);
3722
+ const os6 = String(r.os).toLowerCase();
3723
+ return os6 === "all" || accepted.includes(os6);
3700
3724
  });
3701
3725
  }
3702
3726
  function _hasRulesForOs(rules, osType) {
@@ -4738,24 +4762,24 @@ function extractWritePayload(actionType, actionDetailRaw) {
4738
4762
  const detail = actionDetailRaw || "";
4739
4763
  const m = detail.match(WRITE_PREFIX_RE);
4740
4764
  if (m) {
4741
- const path8 = m[1];
4765
+ const path9 = m[1];
4742
4766
  let content = m[2] || "";
4743
- if (!path8 || path8 === "?" || path8 === "-" || !content.trim()) return null;
4767
+ if (!path9 || path9 === "?" || path9 === "-" || !content.trim()) return null;
4744
4768
  if ((actionType || "").toLowerCase().includes("editfile")) {
4745
4769
  const nm = content.match(EDIT_NEW_RE);
4746
4770
  if (nm) content = nm[1];
4747
4771
  }
4748
- return { path: path8, content };
4772
+ return { path: path9, content };
4749
4773
  }
4750
4774
  const stripped = detail.trim();
4751
4775
  if (stripped.startsWith("{")) {
4752
4776
  try {
4753
4777
  const obj = JSON.parse(stripped);
4754
4778
  if (obj && typeof obj === "object") {
4755
- const path8 = obj.path || obj.file_path || obj.filePath;
4779
+ const path9 = obj.path || obj.file_path || obj.filePath;
4756
4780
  const content = obj.content || obj.newString || obj.new_string;
4757
- if (typeof path8 === "string" && path8 !== "" && path8 !== "?" && path8 !== "-" && typeof content === "string" && content.trim()) {
4758
- return { path: path8, content };
4781
+ if (typeof path9 === "string" && path9 !== "" && path9 !== "?" && path9 !== "-" && typeof content === "string" && content.trim()) {
4782
+ return { path: path9, content };
4759
4783
  }
4760
4784
  }
4761
4785
  } catch {
@@ -4768,8 +4792,8 @@ function handlesWrittenContent(actionType, actionDetailRaw) {
4768
4792
  if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
4769
4793
  return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
4770
4794
  }
4771
- function detectLanguage(path8, content) {
4772
- 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();
4773
4797
  if (SHELL_EXTS.has(ext)) return "shell";
4774
4798
  if (PY_EXTS.has(ext)) return "python";
4775
4799
  if (DATA_EXTS.has(ext)) return "data";
@@ -4927,8 +4951,8 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
4927
4951
  if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
4928
4952
  const payload = extractWritePayload(actionType, actionDetailRaw);
4929
4953
  if (!payload) return [];
4930
- const { path: path8, content: rawContent } = payload;
4931
- const language = detectLanguage(path8, rawContent);
4954
+ const { path: path9, content: rawContent } = payload;
4955
+ const language = detectLanguage(path9, rawContent);
4932
4956
  if (language === "data") return [];
4933
4957
  let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
4934
4958
  const started = Date.now();
@@ -5422,16 +5446,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5422
5446
  if (String(osType || "").toLowerCase() === "windows") {
5423
5447
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
5424
5448
  }
5425
- const pathMatches = (text, path8) => {
5426
- const parts = path8.split(/(\(\?!.*?\))/);
5449
+ const pathMatches = (text, path9) => {
5450
+ const parts = path9.split(/(\(\?!.*?\))/);
5427
5451
  const escaped = parts.map((part) => {
5428
5452
  if (part.startsWith("(?!")) return part;
5429
5453
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5430
5454
  }).join("");
5431
- 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");
5432
5456
  return re.test(text);
5433
5457
  };
5434
- const pathMatchesAny = (path8) => pathScanTexts.some((t) => pathMatches(t, path8));
5458
+ const pathMatchesAny = (path9) => pathScanTexts.some((t) => pathMatches(t, path9));
5435
5459
  for (const sp of rootPaths) {
5436
5460
  if (pathMatchesAny(sp.path.toLowerCase())) {
5437
5461
  if (keygenGenerate) continue;
@@ -5574,8 +5598,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5574
5598
  }
5575
5599
  return null;
5576
5600
  }
5577
- function isHomeValue(path8) {
5578
- let p = path8.trim().toLowerCase();
5601
+ function isHomeValue(path9) {
5602
+ let p = path9.trim().toLowerCase();
5579
5603
  if (p.startsWith("$(") && p.endsWith(")")) {
5580
5604
  const inner = p.slice(2, -1).trim();
5581
5605
  return HOME_TARGET_RE.test(" " + inner);
@@ -5631,15 +5655,15 @@ function checkHomeDeletion(actionType, actionDetail) {
5631
5655
  }
5632
5656
  const assigned = {};
5633
5657
  for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
5634
- for (const [varName, path8] of Object.entries(assigned)) {
5635
- if (!isHomeValue(path8)) continue;
5658
+ for (const [varName, path9] of Object.entries(assigned)) {
5659
+ if (!isHomeValue(path9)) continue;
5636
5660
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
5637
5661
  for (const seg of segs) {
5638
5662
  if (!isDeleteCommand(seg)) continue;
5639
5663
  if (varRefRe.test(seg)) {
5640
5664
  return {
5641
5665
  allowed: false,
5642
- 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`,
5643
5667
  riskLevel: "high",
5644
5668
  riskType: "script_execution",
5645
5669
  confidence: 90,
@@ -6447,15 +6471,15 @@ function parseShellString(s) {
6447
6471
  let m;
6448
6472
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
6449
6473
  const interp = m[1];
6450
- const path8 = m[2].trim();
6474
+ const path9 = m[2].trim();
6451
6475
  let rest = m[3].trim();
6452
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6476
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
6453
6477
  rest = rest.split(/[;|&<>]/)[0].trim();
6454
6478
  const args = [];
6455
6479
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6456
6480
  args.push(tm[1] ? tm[2] : tm[3]);
6457
6481
  }
6458
- return { path: path8, args, interpreter: interp };
6482
+ return { path: path9, args, interpreter: interp };
6459
6483
  }
6460
6484
  return null;
6461
6485
  }
@@ -6501,9 +6525,9 @@ function extractCallsFromTree(tree, reachableLines) {
6501
6525
  }
6502
6526
  if (allStr && elts.length >= 2) {
6503
6527
  const interp = elts[0];
6504
- const path8 = elts[1];
6505
- if (!path8.startsWith("-") && !path8.startsWith("$") && !path8.includes("/dev/")) {
6506
- 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 });
6507
6531
  return true;
6508
6532
  }
6509
6533
  }
@@ -6543,15 +6567,15 @@ function extractCallsRegex(content) {
6543
6567
  let m;
6544
6568
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
6545
6569
  const interp = m[1];
6546
- const path8 = m[2].trim();
6570
+ const path9 = m[2].trim();
6547
6571
  let rest = m[3].trim();
6548
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6572
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
6549
6573
  rest = rest.split(/[;|&<>]/)[0].trim();
6550
6574
  const args = [];
6551
6575
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6552
6576
  args.push(tm[1] ? tm[2] : tm[3]);
6553
6577
  }
6554
- calls.push({ path: path8, args, interpreter: interp });
6578
+ calls.push({ path: path9, args, interpreter: interp });
6555
6579
  }
6556
6580
  return calls;
6557
6581
  }
@@ -7345,15 +7369,15 @@ function extractCallsFromContent(content) {
7345
7369
  CHILD_CALL_RE2.lastIndex = 0;
7346
7370
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
7347
7371
  const interp = m[1];
7348
- const path8 = m[2].trim();
7372
+ const path9 = m[2].trim();
7349
7373
  let rest = m[3].trim();
7350
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
7374
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
7351
7375
  rest = rest.split(/[;|&<>]/)[0].trim();
7352
7376
  const args = [];
7353
7377
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
7354
7378
  args.push(tm[1] ? tm[2] : tm[3]);
7355
7379
  }
7356
- calls.push({ path: path8, args, interpreter: interp });
7380
+ calls.push({ path: path9, args, interpreter: interp });
7357
7381
  }
7358
7382
  return calls;
7359
7383
  }
@@ -8992,6 +9016,28 @@ function formatHints(previous) {
8992
9016
  }
8993
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";
8994
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
+ }
8995
9041
  async function analyzeWithLLM(prompt, config) {
8996
9042
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
8997
9043
  const _llmStart = performance.now();
@@ -9039,6 +9085,7 @@ async function analyzeWithLLM(prompt, config) {
9039
9085
  if (abortController.signal.aborted) {
9040
9086
  break;
9041
9087
  }
9088
+ const attemptStart = performance.now();
9042
9089
  try {
9043
9090
  const response = await client.chat.completions.create({
9044
9091
  model: config.model,
@@ -9154,7 +9201,16 @@ async function analyzeWithLLM(prompt, config) {
9154
9201
  const errObj = err;
9155
9202
  const status = errObj?.status ?? errObj?.statusCode;
9156
9203
  const body = errObj?.error ?? errObj?.body;
9157
- 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
+ )}`;
9158
9214
  if (attempt < maxRetries) {
9159
9215
  console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
9160
9216
  await new Promise((resolve12) => setTimeout(resolve12, retryCfg.retryInterval * 1e3));
@@ -9226,8 +9282,8 @@ var init_rule_store = __esm({
9226
9282
  BrainRuleStore = class {
9227
9283
  path;
9228
9284
  data;
9229
- constructor(path8) {
9230
- this.path = path8 || getRulesPath();
9285
+ constructor(path9) {
9286
+ this.path = path9 || getRulesPath();
9231
9287
  this.data = this.load();
9232
9288
  }
9233
9289
  load() {
@@ -9680,10 +9736,10 @@ ${reason.slice(0, 500)}
9680
9736
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
9681
9737
  let mm;
9682
9738
  while ((mm = pathRe.exec(src)) !== null) {
9683
- const path8 = mm[1];
9684
- if (path8.split("/").length < 3) continue;
9685
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path8)) continue;
9686
- 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);
9687
9743
  if (seen.has(gen)) continue;
9688
9744
  seen.add(gen);
9689
9745
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -9702,8 +9758,8 @@ ${reason.slice(0, 500)}
9702
9758
  }
9703
9759
  return false;
9704
9760
  }
9705
- generalizePath(path8) {
9706
- const p = path8.toLowerCase();
9761
+ generalizePath(path9) {
9762
+ const p = path9.toLowerCase();
9707
9763
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
9708
9764
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
9709
9765
  }
@@ -10563,12 +10619,12 @@ var init_builder = __esm({
10563
10619
  });
10564
10620
 
10565
10621
  // src/engine/formal-engine/properties.ts
10566
- function graphFromPath(nodes, path8, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10622
+ function graphFromPath(nodes, path9, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10567
10623
  const byKey = /* @__PURE__ */ new Map();
10568
10624
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
10569
10625
  const gNodes = [];
10570
10626
  const gEdges = [];
10571
- for (const item of path8) {
10627
+ for (const item of path9) {
10572
10628
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
10573
10629
  gNodes.push({
10574
10630
  session_id: item.sessionId,
@@ -10634,22 +10690,22 @@ function checkCrossSessionChain(graph) {
10634
10690
  if (witness !== void 0) {
10635
10691
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
10636
10692
  let matched = 0;
10637
- const path8 = [];
10693
+ const path9 = [];
10638
10694
  for (let k = 0; k < witness; k++) {
10639
10695
  const n = nodes[k];
10640
10696
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
10641
10697
  matched += 1;
10642
- 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) });
10643
10699
  }
10644
10700
  }
10645
10701
  if (matched < stages.length - 1) continue;
10646
- 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) });
10647
10703
  violations.push({
10648
10704
  propertyId: "cross-" + chain.id,
10649
10705
  reason: chain.reason,
10650
10706
  riskLevel: chain.riskLevel,
10651
- path: path8,
10652
- graph: graphFromPath(nodes, path8, "next", {
10707
+ path: path9,
10708
+ graph: graphFromPath(nodes, path9, "next", {
10653
10709
  property_id: "cross-" + chain.id,
10654
10710
  property_short: "P1",
10655
10711
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -10659,11 +10715,11 @@ function checkCrossSessionChain(graph) {
10659
10715
  } else {
10660
10716
  let matched = 0;
10661
10717
  let stageIdx = 0;
10662
- const path8 = [];
10718
+ const path9 = [];
10663
10719
  for (const n of nodes) {
10664
10720
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
10665
10721
  matched += 1;
10666
- 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) });
10667
10723
  stageIdx += 1;
10668
10724
  if (matched >= stages.length) break;
10669
10725
  }
@@ -10673,8 +10729,8 @@ function checkCrossSessionChain(graph) {
10673
10729
  propertyId: "cross-" + chain.id,
10674
10730
  reason: chain.reason,
10675
10731
  riskLevel: chain.riskLevel,
10676
- path: path8,
10677
- graph: graphFromPath(nodes, path8, "next", {
10732
+ path: path9,
10733
+ graph: graphFromPath(nodes, path9, "next", {
10678
10734
  property_id: "cross-" + chain.id,
10679
10735
  property_short: "P1",
10680
10736
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -10895,7 +10951,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10895
10951
  if (candidates.length > 0) {
10896
10952
  const pre = nodes[candidates[candidates.length - 1]];
10897
10953
  const post = nodes[firstEv];
10898
- const path8 = [
10954
+ const path9 = [
10899
10955
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10900
10956
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10901
10957
  ];
@@ -10903,8 +10959,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10903
10959
  propertyId: "no-exfil-after-privesc",
10904
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",
10905
10961
  riskLevel: "critical",
10906
- path: path8,
10907
- graph: graphFromPath(nodes, path8, "next", {
10962
+ path: path9,
10963
+ graph: graphFromPath(nodes, path9, "next", {
10908
10964
  property_id: "no-exfil-after-privesc",
10909
10965
  property_short: "P4",
10910
10966
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10921,7 +10977,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10921
10977
  for (let j = i + 1; j < nodes.length; j++) {
10922
10978
  if (!isExfilNode(nodes[j])) continue;
10923
10979
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
10924
- const path8 = [
10980
+ const path9 = [
10925
10981
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10926
10982
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10927
10983
  ];
@@ -10929,8 +10985,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10929
10985
  propertyId: "no-exfil-after-privesc",
10930
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",
10931
10987
  riskLevel: "critical",
10932
- path: path8,
10933
- graph: graphFromPath(nodes, path8, "next", {
10988
+ path: path9,
10989
+ graph: graphFromPath(nodes, path9, "next", {
10934
10990
  property_id: "no-exfil-after-privesc",
10935
10991
  property_short: "P4",
10936
10992
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10962,7 +11018,7 @@ function checkNeverExfilAfterCred(graph) {
10962
11018
  }
10963
11019
  if (pre) {
10964
11020
  const post = nodes[firstEv];
10965
- const path8 = [
11021
+ const path9 = [
10966
11022
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10967
11023
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10968
11024
  ];
@@ -10970,8 +11026,8 @@ function checkNeverExfilAfterCred(graph) {
10970
11026
  propertyId: "no-exfil-after-credential",
10971
11027
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10972
11028
  riskLevel: "critical",
10973
- path: path8,
10974
- graph: graphFromPath(nodes, path8, "data", {
11029
+ path: path9,
11030
+ graph: graphFromPath(nodes, path9, "data", {
10975
11031
  property_id: "no-exfil-after-credential",
10976
11032
  property_short: "P5",
10977
11033
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10987,7 +11043,7 @@ function checkNeverExfilAfterCred(graph) {
10987
11043
  if (!isCredNode(nodes[i])) continue;
10988
11044
  for (let j = i + 1; j < nodes.length; j++) {
10989
11045
  if (isExfilNode(nodes[j])) {
10990
- const path8 = [
11046
+ const path9 = [
10991
11047
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10992
11048
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10993
11049
  ];
@@ -10995,8 +11051,8 @@ function checkNeverExfilAfterCred(graph) {
10995
11051
  propertyId: "no-exfil-after-credential",
10996
11052
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10997
11053
  riskLevel: "critical",
10998
- path: path8,
10999
- graph: graphFromPath(nodes, path8, "data", {
11054
+ path: path9,
11055
+ graph: graphFromPath(nodes, path9, "data", {
11000
11056
  property_id: "no-exfil-after-credential",
11001
11057
  property_short: "P5",
11002
11058
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -11155,13 +11211,13 @@ function checkSensitiveDataAggregation(graph) {
11155
11211
  if (!isExfilNode(n)) continue;
11156
11212
  const srcs = sourcesFor(i);
11157
11213
  if (srcs.size >= 2) {
11158
- 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) }];
11159
11215
  violations.push({
11160
11216
  propertyId: "sensitive-data-aggregation",
11161
11217
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
11162
11218
  riskLevel: "critical",
11163
- path: path8,
11164
- graph: graphFromPath(nodes, path8, "next", {
11219
+ path: path9,
11220
+ graph: graphFromPath(nodes, path9, "next", {
11165
11221
  property_id: "sensitive-data-aggregation",
11166
11222
  property_short: "P8",
11167
11223
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -11283,6 +11339,10 @@ var init_engine = __esm({
11283
11339
  });
11284
11340
 
11285
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";
11286
11346
  function extractInstances(actionDetail, stage) {
11287
11347
  const out = [];
11288
11348
  if (PORT_STAGE_RE.test(stage)) {
@@ -11481,12 +11541,65 @@ var init_stateful = __esm({
11481
11541
  }
11482
11542
  };
11483
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
+ }
11484
11591
  appendNode(action, sessionId, isError = false, agentId = "", instanceId = "") {
11485
11592
  const ad = String(action.actionDetail || "");
11486
11593
  const at = String(action.actionType || "");
11487
11594
  if (!ad) return null;
11488
11595
  if (this.nodes_.length >= MAX_NODES) {
11489
- 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
+ }
11490
11603
  }
11491
11604
  const stage = markStage2(ad);
11492
11605
  const node = {
@@ -11634,11 +11747,11 @@ var init_stateful = __esm({
11634
11747
  }
11635
11748
  }
11636
11749
  chainPath(stages) {
11637
- const path8 = [];
11750
+ const path9 = [];
11638
11751
  let want = stages[0];
11639
11752
  for (const n of this.nodes_) {
11640
11753
  if (n.stage === want) {
11641
- path8.push({
11754
+ path9.push({
11642
11755
  sessionId: n.sessionId,
11643
11756
  seq: n.seq,
11644
11757
  stage: n.stage,
@@ -11654,12 +11767,12 @@ var init_stateful = __esm({
11654
11767
  }
11655
11768
  }
11656
11769
  }
11657
- return path8;
11770
+ return path9;
11658
11771
  }
11659
11772
  /** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
11660
11773
  buildChainGraph(stages, chainId) {
11661
- const path8 = this.chainPath(stages);
11662
- const gNodes = path8.map((p, i) => {
11774
+ const path9 = this.chainPath(stages);
11775
+ const gNodes = path9.map((p, i) => {
11663
11776
  const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
11664
11777
  return {
11665
11778
  session_id: p.sessionId,
@@ -11910,14 +12023,29 @@ var init_stateful = __esm({
11910
12023
  });
11911
12024
 
11912
12025
  // src/engine/formal-engine/chain_state.ts
11913
- import * as fs5 from "fs";
11914
- import * as os3 from "os";
11915
- import * as path6 from "path";
12026
+ import * as fs6 from "fs";
12027
+ import * as os4 from "os";
12028
+ import * as path7 from "path";
11916
12029
  import { createHash as createHash4 } from "crypto";
11917
12030
  function defaultStateDbPath() {
11918
- const dir = 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");
12032
+ const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
12033
+ const dir = instance ? path7.join(base, instance) : base;
11919
12034
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
11920
- return path6.join(dir, `stateful_chains_${tag}.json`);
12035
+ const target = path7.join(dir, `stateful_chains_${tag}.json`);
12036
+ if (instance) {
12037
+ const legacy = path7.join(base, `stateful_chains_${tag}.json`);
12038
+ if (!fs6.existsSync(target) && fs6.existsSync(legacy)) {
12039
+ try {
12040
+ fs6.mkdirSync(dir, { recursive: true });
12041
+ fs6.copyFileSync(legacy, target);
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}`);
12043
+ } catch (err) {
12044
+ console.warn("[AgentMoss] \u8FC1\u79FB\u94FE\u72B6\u6001\u6587\u4EF6\u5931\u8D25\uFF08\u5C06\u4F7F\u7528\u65B0\u7A7A\u6587\u4EF6\uFF09:", err);
12045
+ }
12046
+ }
12047
+ }
12048
+ return target;
11921
12049
  }
11922
12050
  function registerExitFlush(store) {
11923
12051
  if (_exitHookRegistered) return;
@@ -11988,8 +12116,8 @@ var init_chain_state = __esm({
11988
12116
  }
11989
12117
  _read() {
11990
12118
  try {
11991
- if (fs5.existsSync(this.filePath)) {
11992
- const raw = fs5.readFileSync(this.filePath, "utf-8");
12119
+ if (fs6.existsSync(this.filePath)) {
12120
+ const raw = fs6.readFileSync(this.filePath, "utf-8");
11993
12121
  return JSON.parse(raw);
11994
12122
  }
11995
12123
  } catch {
@@ -12003,7 +12131,7 @@ var init_chain_state = __esm({
12003
12131
  this._timer = null;
12004
12132
  try {
12005
12133
  this._syncDirtyToData();
12006
- ensurePrivateDir(path6.dirname(this.filePath));
12134
+ ensurePrivateDir(path7.dirname(this.filePath));
12007
12135
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12008
12136
  } catch {
12009
12137
  }
@@ -12026,7 +12154,7 @@ var init_chain_state = __esm({
12026
12154
  }
12027
12155
  try {
12028
12156
  this._syncDirtyToData();
12029
- ensurePrivateDir(path6.dirname(this.filePath));
12157
+ ensurePrivateDir(path7.dirname(this.filePath));
12030
12158
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12031
12159
  } catch {
12032
12160
  }
@@ -12067,16 +12195,16 @@ var init_chain_state = __esm({
12067
12195
  const sleepBuf = new Int32Array(new SharedArrayBuffer(4));
12068
12196
  for (let attempt = 0; attempt < 100; attempt++) {
12069
12197
  try {
12070
- const fd = fs5.openSync(lockPath, "wx");
12198
+ const fd = fs6.openSync(lockPath, "wx");
12071
12199
  try {
12072
12200
  return fn();
12073
12201
  } finally {
12074
12202
  try {
12075
- fs5.closeSync(fd);
12203
+ fs6.closeSync(fd);
12076
12204
  } catch {
12077
12205
  }
12078
12206
  try {
12079
- fs5.unlinkSync(lockPath);
12207
+ fs6.unlinkSync(lockPath);
12080
12208
  } catch {
12081
12209
  }
12082
12210
  }
@@ -12094,7 +12222,7 @@ var init_chain_state = __esm({
12094
12222
  _flushNow() {
12095
12223
  this._syncDirtyToData();
12096
12224
  try {
12097
- const _dirOk = ensurePrivateDir(path6.dirname(this.filePath));
12225
+ const _dirOk = ensurePrivateDir(path7.dirname(this.filePath));
12098
12226
  const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12099
12227
  if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
12100
12228
  } catch (e) {
@@ -12802,17 +12930,8 @@ init_paths();
12802
12930
  import { cors } from "hono/cors";
12803
12931
  import { logger } from "hono/logger";
12804
12932
  import net from "net";
12805
- import { existsSync as existsSync21, writeFileSync as writeFileSync6, renameSync as renameSync3, mkdirSync as mkdirSync8 } from "fs";
12806
- import { dirname as dirname15, join as join21 } from "path";
12807
-
12808
- // src/routes.ts
12809
- init_esm_shims();
12810
- init_security_policy();
12811
- import { randomBytes as randomBytes2 } from "crypto";
12812
-
12813
- // src/models.ts
12814
- init_esm_shims();
12815
- import { z } from "zod";
12933
+ import { existsSync as existsSync21, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync10 } from "fs";
12934
+ import { dirname as dirname15 } from "path";
12816
12935
 
12817
12936
  // src/package-json.ts
12818
12937
  init_esm_shims();
@@ -12821,7 +12940,14 @@ var require2 = createRequire(import.meta.url);
12821
12940
  var pkg = require2("../package.json");
12822
12941
  var version = pkg.version;
12823
12942
 
12943
+ // src/routes.ts
12944
+ init_esm_shims();
12945
+ init_security_policy();
12946
+ import { randomBytes as randomBytes2 } from "crypto";
12947
+
12824
12948
  // src/models.ts
12949
+ init_esm_shims();
12950
+ import { z } from "zod";
12825
12951
  var isNonEmptyNoControl = (v) => v.trim().length > 0 && ![...v].some((c) => {
12826
12952
  const n = c.codePointAt(0) ?? 0;
12827
12953
  return n < 32 || n >= 127 && n <= 159;
@@ -12975,7 +13101,7 @@ init_security_policy();
12975
13101
  init_coordinator();
12976
13102
  import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
12977
13103
  import { tmpdir as tmpdir3 } from "os";
12978
- import { join as join17, resolve as resolve11 } from "path";
13104
+ import { join as join18, resolve as resolve11 } from "path";
12979
13105
 
12980
13106
  // src/engine/types.ts
12981
13107
  init_esm_shims();
@@ -12998,8 +13124,8 @@ init_config();
12998
13124
  import { createHash as createHash5 } from "crypto";
12999
13125
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
13000
13126
  import { tmpdir as tmpdir2 } from "os";
13001
- import { join as join16 } from "path";
13002
- 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");
13003
13129
  var cacheDirOverride = null;
13004
13130
  function cacheDir() {
13005
13131
  return cacheDirOverride ?? CACHE_DIR;
@@ -13008,7 +13134,7 @@ function safeCacheDir() {
13008
13134
  const dir = cacheDir();
13009
13135
  if (ensurePrivateDir(dir)) return dir;
13010
13136
  try {
13011
- const fallback = join16(getDataRoot(), "policy_cache");
13137
+ const fallback = join17(getDataRoot(), "policy_cache");
13012
13138
  if (ensurePrivateDir(fallback)) {
13013
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}`);
13014
13140
  return fallback;
@@ -13030,7 +13156,7 @@ var PolicyCache = class {
13030
13156
  cacheFilePath(sessionId, promptSession) {
13031
13157
  const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
13032
13158
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13033
- return join16(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13159
+ return join17(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13034
13160
  }
13035
13161
  /** 取缓存:内存 → 文件;未命中返回 null。 */
13036
13162
  get(sessionId, promptSession) {
@@ -13061,7 +13187,7 @@ var PolicyCache = class {
13061
13187
  try {
13062
13188
  const dir = safeCacheDir();
13063
13189
  const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13064
- if (!ensurePrivateDir(join16(dir, sub))) return;
13190
+ if (!ensurePrivateDir(join17(dir, sub))) return;
13065
13191
  writePrivateText(file, policy);
13066
13192
  } catch {
13067
13193
  }
@@ -13087,12 +13213,12 @@ var PolicyCache = class {
13087
13213
  if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
13088
13214
  }
13089
13215
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13090
- const dir = join16(cacheDir(), safeSessionId);
13216
+ const dir = join17(cacheDir(), safeSessionId);
13091
13217
  try {
13092
13218
  if (existsSync17(dir)) {
13093
13219
  for (const f of readdirSync5(dir)) {
13094
13220
  try {
13095
- unlinkSync4(join16(dir, f));
13221
+ unlinkSync4(join17(dir, f));
13096
13222
  } catch {
13097
13223
  }
13098
13224
  }
@@ -13106,9 +13232,9 @@ var PolicyCache = class {
13106
13232
  try {
13107
13233
  if (existsSync17(cacheDir())) {
13108
13234
  for (const sessionDir of readdirSync5(cacheDir())) {
13109
- const dir = join16(cacheDir(), sessionDir);
13235
+ const dir = join17(cacheDir(), sessionDir);
13110
13236
  try {
13111
- for (const f of readdirSync5(dir)) unlinkSync4(join16(dir, f));
13237
+ for (const f of readdirSync5(dir)) unlinkSync4(join17(dir, f));
13112
13238
  rmdirSync(dir);
13113
13239
  } catch {
13114
13240
  }
@@ -13195,7 +13321,7 @@ ${safe(policy, 2e3)}`);
13195
13321
 
13196
13322
  // src/engine/analyzer.ts
13197
13323
  import { parse as parseToml } from "smol-toml";
13198
- var POLICY_OUTPUT_DIR = join17(tmpdir3(), "agent_moss");
13324
+ var POLICY_OUTPUT_DIR = join18(tmpdir3(), "agent_moss");
13199
13325
  var policyOutputDirOverride = null;
13200
13326
  function policyOutputDir() {
13201
13327
  return policyOutputDirOverride ?? POLICY_OUTPUT_DIR;
@@ -13234,7 +13360,7 @@ function savePolicyToFile(sessionId, policyToml) {
13234
13360
  return null;
13235
13361
  }
13236
13362
  const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13237
- const filepath = join17(outDir, `${safeName}.toml`);
13363
+ const filepath = join18(outDir, `${safeName}.toml`);
13238
13364
  writePrivateText(filepath, policyToml);
13239
13365
  return filepath;
13240
13366
  } catch (err) {
@@ -13446,7 +13572,7 @@ async function analyzeInner(input, mossLog) {
13446
13572
 
13447
13573
  // src/actrail.ts
13448
13574
  init_esm_shims();
13449
- import * as fs6 from "fs";
13575
+ import * as fs7 from "fs";
13450
13576
 
13451
13577
  // src/infra/esm-require.ts
13452
13578
  init_esm_shims();
@@ -13477,7 +13603,7 @@ function getStoragePath() {
13477
13603
  function reportEnforcementEvent(opts) {
13478
13604
  if (!isEnabled()) return false;
13479
13605
  const storagePath = getStoragePath();
13480
- if (!fs6.existsSync(storagePath)) return false;
13606
+ if (!fs7.existsSync(storagePath)) return false;
13481
13607
  try {
13482
13608
  let Database;
13483
13609
  try {
@@ -13640,11 +13766,11 @@ function mineDangerousPatterns(sessions, minSup = 2, maxLen = 4) {
13640
13766
 
13641
13767
  // src/agent-gate-reader.ts
13642
13768
  init_esm_shims();
13643
- import * as fs7 from "fs";
13644
- import * as os4 from "os";
13645
- import * as path7 from "path";
13646
- var DEFAULT_AGENTGATE_SQLITE = path7.join(
13647
- 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(),
13648
13774
  ".local",
13649
13775
  "share",
13650
13776
  "agent_gate",
@@ -13659,10 +13785,10 @@ function normalizeAction(row) {
13659
13785
  function readJsonDir(dirPath, limit = 1e5) {
13660
13786
  const sessions = /* @__PURE__ */ new Map();
13661
13787
  try {
13662
- const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
13788
+ const files = fs8.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
13663
13789
  for (const f of files.slice(-200)) {
13664
13790
  const sid = f.replace(/\.json$/, "");
13665
- const raw = fs7.readFileSync(path7.join(dirPath, f), "utf-8");
13791
+ const raw = fs8.readFileSync(path8.join(dirPath, f), "utf-8");
13666
13792
  const arr = JSON.parse(raw);
13667
13793
  if (!Array.isArray(arr)) continue;
13668
13794
  for (const item of arr) {
@@ -13719,7 +13845,7 @@ function readSqlite(dbPath, limit = 1e5) {
13719
13845
  function loadAgentGateSessions(dbPath = "") {
13720
13846
  if (dbPath) {
13721
13847
  try {
13722
- if (fs7.statSync(dbPath).isDirectory()) {
13848
+ if (fs8.statSync(dbPath).isDirectory()) {
13723
13849
  return readJsonDir(dbPath);
13724
13850
  }
13725
13851
  } catch {
@@ -13730,7 +13856,7 @@ function loadAgentGateSessions(dbPath = "") {
13730
13856
  }
13731
13857
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
13732
13858
  if (sql.length > 0) return sql;
13733
- 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");
13734
13860
  return readJsonDir(jsonDefault);
13735
13861
  }
13736
13862
 
@@ -13854,7 +13980,7 @@ function poolsSnapshot() {
13854
13980
 
13855
13981
  // src/routes.ts
13856
13982
  init_metrics();
13857
- import { join as join19, dirname as dirname13 } from "path";
13983
+ import { join as join20, dirname as dirname13 } from "path";
13858
13984
  import { fileURLToPath as fileURLToPath10 } from "url";
13859
13985
  var __dirname9 = dirname13(fileURLToPath10(import.meta.url));
13860
13986
  async function healthRoute(c) {
@@ -13877,11 +14003,11 @@ async function healthRoute(c) {
13877
14003
  if (typeof pct === "number") {
13878
14004
  if (pct >= 100) {
13879
14005
  degraded.push(
13880
- `\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`
13881
14007
  );
13882
14008
  } else if (pct >= 90) {
13883
14009
  degraded.push(
13884
- `\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`
13885
14011
  );
13886
14012
  }
13887
14013
  }
@@ -13889,7 +14015,7 @@ async function healthRoute(c) {
13889
14015
  const snap = getBreaker().snapshot();
13890
14016
  if (snap.state === "open") {
13891
14017
  degraded.push(
13892
- `\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`
13893
14019
  );
13894
14020
  }
13895
14021
  } catch {
@@ -14089,11 +14215,11 @@ async function analyzeRoute(c) {
14089
14215
  const pct = Math.round(total / MAX_NODES * 1e3) / 10;
14090
14216
  if (total >= MAX_NODES) {
14091
14217
  degradedNotes.push(
14092
- `\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`
14218
+ `\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`
14093
14219
  );
14094
14220
  } else if (pct >= 90) {
14095
14221
  degradedNotes.push(
14096
- `\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`
14222
+ `\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`
14097
14223
  );
14098
14224
  }
14099
14225
  } catch {
@@ -14283,7 +14409,7 @@ function getBrainRuleStore() {
14283
14409
  return new BrainRuleStore();
14284
14410
  }
14285
14411
  function getBrainSkillManager() {
14286
- const dir = resolveAssetDir(__dirname9, "skills") ?? join19(__dirname9, "..", "..", "agent_moss", "skills");
14412
+ const dir = resolveAssetDir(__dirname9, "skills") ?? join20(__dirname9, "..", "..", "agent_moss", "skills");
14287
14413
  return new BrainSkillManager(dir);
14288
14414
  }
14289
14415
  async function brainRulesRoute(c) {
@@ -14388,10 +14514,10 @@ init_rules_mode();
14388
14514
  import { Hono } from "hono";
14389
14515
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
14390
14516
  import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
14391
- import { join as join20, dirname as dirname14 } from "path";
14517
+ import { join as join21, dirname as dirname14 } from "path";
14392
14518
  import { fileURLToPath as fileURLToPath11 } from "url";
14393
14519
  var __dirname10 = dirname14(fileURLToPath11(import.meta.url));
14394
- var STATIC_DIR = join20(__dirname10, "static");
14520
+ var STATIC_DIR = join21(__dirname10, "static");
14395
14521
  var CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
14396
14522
  function getConsoleToken() {
14397
14523
  return process.env[CONSOLE_TOKEN_ENV] || "";
@@ -14433,7 +14559,7 @@ function createConsoleRouter() {
14433
14559
  console2.use("/api/*", authMiddleware());
14434
14560
  console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
14435
14561
  const serveIndex = (c) => {
14436
- const indexFile = join20(STATIC_DIR, "index.html");
14562
+ const indexFile = join21(STATIC_DIR, "index.html");
14437
14563
  if (existsSync20(indexFile)) {
14438
14564
  return c.html(readFileSync20(indexFile, "utf-8"));
14439
14565
  }
@@ -14630,11 +14756,11 @@ function createConsoleRouter() {
14630
14756
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
14631
14757
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
14632
14758
  }
14633
- const userPath = join20(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14759
+ const userPath = join21(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14634
14760
  const builtinDir = resolveAssetDir(__dirname10, "skills");
14635
14761
  const candidates = [
14636
14762
  ...isRuntimeConfigDisabled() ? [] : [userPath],
14637
- builtinDir ? join20(builtinDir, `${skillId}.md`) : ""
14763
+ builtinDir ? join21(builtinDir, `${skillId}.md`) : ""
14638
14764
  ].filter(Boolean);
14639
14765
  for (const p of candidates) {
14640
14766
  if (existsSync20(p)) {
@@ -14904,7 +15030,7 @@ function createApp() {
14904
15030
  startLoopMonitor();
14905
15031
  const limiter = new RateLimiter(rateLimitQps());
14906
15032
  app.use("*", async (c, next) => {
14907
- const path8 = new URL(c.req.url).pathname;
15033
+ const path9 = new URL(c.req.url).pathname;
14908
15034
  const method = c.req.method.toUpperCase();
14909
15035
  if (method === "OPTIONS") return next();
14910
15036
  const maxBody = maxBodyBytes();
@@ -14918,16 +15044,16 @@ function createApp() {
14918
15044
  if (originCheckEnabled()) {
14919
15045
  const origin = c.req.header("origin") || "";
14920
15046
  if (origin && !originAllowed(origin, c.req.header("host") || "")) {
14921
- console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path8}`);
15047
+ console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path9}`);
14922
15048
  return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
14923
15049
  }
14924
15050
  }
14925
- const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path8);
14926
- const isPublicPage = !path8.startsWith("/console/api") && (path8 === "/console" || path8.startsWith("/console/"));
15051
+ const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path9);
15052
+ const isPublicPage = !path9.startsWith("/console/api") && (path9 === "/console" || path9.startsWith("/console/"));
14927
15053
  if (!okAuth && !isPublicPage) {
14928
15054
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
14929
15055
  }
14930
- if (limiter.enabled && path8.startsWith("/api/")) {
15056
+ if (limiter.enabled && path9.startsWith("/api/")) {
14931
15057
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
14932
15058
  if (!limiter.allow(key)) {
14933
15059
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
@@ -14961,7 +15087,7 @@ function createApp() {
14961
15087
  return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
14962
15088
  }
14963
15089
  }
14964
- const pool = poolOf(path8);
15090
+ const pool = poolOf(path9);
14965
15091
  if (!take(`pool:${pool}`, poolLimit(pool))) {
14966
15092
  const qkey = principal ? "p:" + principalHash(principal) : "c:local";
14967
15093
  const [qn, abusive] = noteQueueReject(qkey);
@@ -15061,17 +15187,20 @@ async function warmUpEngine() {
15061
15187
  }
15062
15188
  function writePortFile(port) {
15063
15189
  try {
15064
- const path8 = join21(getDataRoot(), "agent_moss_server.port.json");
15065
- mkdirSync8(dirname15(path8), { recursive: true });
15190
+ const path9 = getPortFilePath();
15191
+ mkdirSync10(dirname15(path9), { recursive: true });
15066
15192
  const payload = JSON.stringify({
15067
15193
  port,
15068
15194
  pid: process.pid,
15195
+ // instance/version 供调用方校验,避免同机多实例端口文件串台
15196
+ instance: getInstance(),
15197
+ version,
15069
15198
  started_at: (/* @__PURE__ */ new Date()).toISOString()
15070
15199
  });
15071
- const tmp = `${path8}.tmp`;
15072
- writeFileSync6(tmp, payload, "utf-8");
15073
- renameSync3(tmp, path8);
15074
- console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path8} (port=${port})`);
15200
+ const tmp = `${path9}.tmp`;
15201
+ writeFileSync7(tmp, payload, "utf-8");
15202
+ renameSync3(tmp, path9);
15203
+ console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path9} (port=${port})`);
15075
15204
  } catch (err) {
15076
15205
  console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
15077
15206
  }
@@ -15112,12 +15241,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15112
15241
  },
15113
15242
  serve: async () => {
15114
15243
  failFastOnAuthError();
15115
- const { mkdirSync: mkdirSync9, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
15244
+ const { mkdirSync: mkdirSync11, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
15116
15245
  const { dirname: dirname16 } = await import("path");
15117
15246
  const dir = dirname16(socketPath);
15118
15247
  if (dir) {
15119
15248
  try {
15120
- mkdirSync9(dir, { recursive: true });
15249
+ mkdirSync11(dir, { recursive: true });
15121
15250
  } catch {
15122
15251
  }
15123
15252
  }