@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/cli.js CHANGED
@@ -97,6 +97,13 @@ function getTokenStatsPath() {
97
97
  }
98
98
  return join(getDataRoot(), "agent_moss_token_stats.json");
99
99
  }
100
+ function getInstanceDir() {
101
+ const instance = getInstance();
102
+ return instance ? join(getDataRoot(), instance) : getDataRoot();
103
+ }
104
+ function getPortFilePath() {
105
+ return join(getInstanceDir(), "agent_moss_server.port.json");
106
+ }
100
107
  var ENV_DATA_ROOT, ENV_INSTANCE, DEFAULT_DATA_ROOT, ENV_RULES_ROOT, ID_MAX_LEN, ID_PATTERN;
101
108
  var init_paths = __esm({
102
109
  "src/infra/paths.ts"() {
@@ -402,22 +409,22 @@ function loadToolRegistry() {
402
409
  data.tools = tools;
403
410
  return data;
404
411
  }
405
- function scanStructEntry(cat, value, path8) {
412
+ function scanStructEntry(cat, value, path9) {
406
413
  if (cat === "skills") {
407
414
  if (!value || typeof value !== "object" || Array.isArray(value)) {
408
- 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`);
415
+ 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`);
409
416
  return null;
410
417
  }
411
418
  const out = {};
412
419
  for (const [skCat, skills] of Object.entries(value)) {
413
420
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
414
- 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`);
421
+ 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`);
415
422
  continue;
416
423
  }
417
424
  const keep = {};
418
425
  for (const [name, kws] of Object.entries(skills)) {
419
426
  if (Array.isArray(kws)) keep[name] = kws;
420
- 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`);
427
+ 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`);
421
428
  }
422
429
  if (Object.keys(keep).length > 0) out[skCat] = keep;
423
430
  }
@@ -425,37 +432,37 @@ function scanStructEntry(cat, value, path8) {
425
432
  }
426
433
  if (cat === "ltl_rules") {
427
434
  if (!Array.isArray(value)) {
428
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
435
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
429
436
  return null;
430
437
  }
431
438
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
432
439
  if (keep.length !== value.length) {
433
- 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`);
440
+ 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`);
434
441
  }
435
442
  return keep.length > 0 ? keep : null;
436
443
  }
437
444
  if (cat === "tools") {
438
445
  if (!value || typeof value !== "object" || Array.isArray(value)) {
439
- 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`);
446
+ 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`);
440
447
  return null;
441
448
  }
442
449
  const keep = {};
443
450
  for (const [k, v] of Object.entries(value)) {
444
451
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
445
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
452
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
446
453
  }
447
454
  return Object.keys(keep).length > 0 ? keep : null;
448
455
  }
449
456
  return null;
450
457
  }
451
- function scanRulesFile(path8, kind) {
458
+ function scanRulesFile(path9, kind) {
452
459
  const out = {};
453
460
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
454
461
  let parsed;
455
462
  try {
456
- parsed = JSON.parse(readFileSync2(path8, "utf-8"));
463
+ parsed = JSON.parse(readFileSync2(path9, "utf-8"));
457
464
  } catch (e) {
458
- 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}`);
465
+ 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}`);
459
466
  return out;
460
467
  }
461
468
  const classifyFlat = (r) => {
@@ -479,44 +486,44 @@ function scanRulesFile(path8, kind) {
479
486
  }
480
487
  if (flatBad > 0) {
481
488
  console.warn(
482
- `[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`
489
+ `[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`
483
490
  );
484
491
  }
485
492
  } else {
486
- 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`);
493
+ 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`);
487
494
  return out;
488
495
  }
489
496
  for (const [cat, rules] of pairs) {
490
497
  if (String(cat).startsWith("_")) continue;
491
498
  if (STRUCT_KEYS.includes(cat)) {
492
- const got = scanStructEntry(cat, rules, path8);
499
+ const got = scanStructEntry(cat, rules, path9);
493
500
  if (got !== null) out[cat] = got;
494
501
  continue;
495
502
  }
496
503
  const required = EXTRA_CATEGORIES[cat];
497
504
  if (!required) {
498
505
  console.warn(
499
- `[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`
506
+ `[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`
500
507
  );
501
508
  continue;
502
509
  }
503
510
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
504
511
  console.error(
505
- `[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
512
+ `[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
506
513
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
507
514
  \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`
508
515
  );
509
516
  continue;
510
517
  }
511
518
  if (!Array.isArray(rules)) {
512
- 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`);
519
+ 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`);
513
520
  continue;
514
521
  }
515
522
  const items = [];
516
523
  for (const r of rules) {
517
524
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
518
525
  console.warn(
519
- `[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`
526
+ `[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`
520
527
  );
521
528
  continue;
522
529
  }
@@ -526,7 +533,7 @@ function scanRulesFile(path8, kind) {
526
533
  }
527
534
  if (Object.keys(out).length > 0) {
528
535
  console.info(
529
- `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path8}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
536
+ `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path9}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
530
537
  );
531
538
  }
532
539
  return out;
@@ -944,44 +951,51 @@ function readFdToken() {
944
951
  fdTokenCache.set(fd, tok);
945
952
  return tok;
946
953
  }
947
- function readExplicitToken() {
954
+ function readExplicitTokenResult() {
948
955
  const tok = env("AGENT_MOSS_AUTH_TOKEN");
949
- if (tok) return tok;
956
+ if (tok) return [tok, ""];
950
957
  const fdTok = readFdToken();
951
- if (fdTok) return fdTok;
952
- const path8 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
953
- if (path8) {
958
+ if (fdTok) return [fdTok, ""];
959
+ const path9 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
960
+ if (path9) {
954
961
  try {
955
- return readFileSync4(path8, "utf-8").trim();
956
- } catch {
957
- return "";
962
+ const fileTok = readFileSync4(path9, "utf-8").trim();
963
+ if (!fileTok) {
964
+ 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`];
965
+ }
966
+ return [fileTok, ""];
967
+ } catch (e) {
968
+ 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`];
958
969
  }
959
970
  }
960
- return "";
971
+ return ["", ""];
961
972
  }
962
973
  function ensureAutoToken() {
963
- const path8 = autoTokenPath();
974
+ const path9 = autoTokenPath();
964
975
  try {
965
- if (existsSync3(path8) && !lstatSync(path8).isSymbolicLink()) {
966
- const tok2 = readFileSync4(path8, "utf-8").trim();
976
+ if (existsSync3(path9) && !lstatSync(path9).isSymbolicLink()) {
977
+ const tok2 = readFileSync4(path9, "utf-8").trim();
967
978
  if (tok2) {
968
979
  try {
969
- chmodSync(path8, 384);
980
+ chmodSync(path9, 384);
970
981
  } catch {
971
982
  }
972
983
  return tok2;
973
984
  }
974
985
  }
975
986
  const tok = randomBytes(32).toString("base64url");
976
- ensurePrivateDir(dirname2(path8));
977
- if (!writePrivateText(path8, tok + "\n")) return "";
987
+ if (!ensurePrivateDir(dirname2(path9))) {
988
+ throw new Error(`\u65E0\u6CD5\u521B\u5EFA/\u6536\u7D27 token \u76EE\u5F55\uFF08\u6743\u9650\u6216\u5C5E\u4E3B\u5F02\u5E38\uFF09: ${dirname2(path9)}`);
989
+ }
990
+ if (!writePrivateText(path9, tok + "\n")) {
991
+ throw new Error(`\u5199\u5165\u81EA\u52A8 token \u5931\u8D25: ${path9}`);
992
+ }
978
993
  console.warn(
979
- `[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`
994
+ `[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`
980
995
  );
981
996
  return tok;
982
997
  } catch (e) {
983
- console.error("[AgentMoss] \u751F\u6210\u8BBF\u95EE token \u5931\u8D25\uFF08\u672C\u6B21\u8FD0\u884C\u5C06\u4E0D\u9274\u6743\uFF09:", e);
984
- return "";
998
+ throw new Error(`\u81EA\u52A8\u8BBF\u95EE token \u751F\u6210/\u8BFB\u53D6\u5931\u8D25\uFF08${path9}\uFF09\uFF1A${e?.message ?? e}`);
985
999
  }
986
1000
  }
987
1001
  function parseAgentTokens(raw) {
@@ -1010,12 +1024,22 @@ function resolveAuth() {
1010
1024
  return [tokenCache.token, tokenCache.agents, tokenCache.error];
1011
1025
  }
1012
1026
  let error = "";
1013
- let token = readExplicitToken();
1014
- if (!token && env("AGENT_MOSS_AUTH_TOKEN_FD") && authMode() !== AUTH_MODE_OFF) {
1027
+ let token = "";
1028
+ if (authMode() !== AUTH_MODE_OFF) {
1029
+ [token, error] = readExplicitTokenResult();
1030
+ }
1031
+ if (!token && !error && env("AGENT_MOSS_AUTH_TOKEN_FD") && authMode() !== AUTH_MODE_OFF) {
1015
1032
  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";
1016
1033
  console.error(`[agent-moss] ${error}`);
1017
1034
  }
1018
- if (!token && !error && authMode() !== AUTH_MODE_OFF) token = ensureAutoToken();
1035
+ if (!token && !error && authMode() !== AUTH_MODE_OFF) {
1036
+ try {
1037
+ token = ensureAutoToken();
1038
+ } catch (e) {
1039
+ 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`;
1040
+ console.error(`[agent-moss] \u9274\u6743\u914D\u7F6E\u9519\u8BEF\uFF0C\u62D2\u7EDD\u542F\u52A8: ${error}`);
1041
+ }
1042
+ }
1019
1043
  const agents = parseAgentTokens(rawAgents);
1020
1044
  tokenCache = { key, token, agents, error };
1021
1045
  return [token, agents, error];
@@ -1035,8 +1059,8 @@ function failFastOnAuthError() {
1035
1059
  }
1036
1060
  function authEnabled() {
1037
1061
  if (authMode() === AUTH_MODE_OFF) return false;
1038
- const [tok, agents] = resolveAuth();
1039
- return Boolean(tok) || Object.keys(agents).length > 0;
1062
+ const [tok, agents, err] = resolveAuth();
1063
+ return Boolean(err) || Boolean(tok) || Object.keys(agents).length > 0;
1040
1064
  }
1041
1065
  function bearer(headers) {
1042
1066
  const get = (k) => headers instanceof Headers ? headers.get(k) ?? "" : headers[k] ?? "";
@@ -1049,16 +1073,16 @@ function constEq(a, b) {
1049
1073
  if (ba.length !== bb.length) return false;
1050
1074
  return timingSafeEqual(ba, bb);
1051
1075
  }
1052
- function checkRequestAuth(headers, path8) {
1076
+ function checkRequestAuth(headers, path9) {
1053
1077
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
1054
- const isHealth = HEALTH_PATHS.includes(path8.replace(/\/+$/, ""));
1078
+ const isHealth = HEALTH_PATHS.includes(path9.replace(/\/+$/, ""));
1055
1079
  const [gt0, agents, err] = resolveAuth();
1056
1080
  if (err) return isHealth ? [true, ""] : [false, ""];
1057
1081
  if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
1058
1082
  if (isHealth) return [true, ""];
1059
1083
  const tok = bearer(headers);
1060
1084
  if (!tok) return [false, ""];
1061
- if (path8.startsWith("/console/api")) {
1085
+ if (path9.startsWith("/console/api")) {
1062
1086
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
1063
1087
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
1064
1088
  }
@@ -1077,8 +1101,8 @@ function bindAgent(principal, agentId) {
1077
1101
  if (!agentId) return [true, bound];
1078
1102
  return [bound === agentId, bound];
1079
1103
  }
1080
- function principalOf(headers, path8 = "") {
1081
- const [ok, principal] = checkRequestAuth(headers, path8);
1104
+ function principalOf(headers, path9 = "") {
1105
+ const [ok, principal] = checkRequestAuth(headers, path9);
1082
1106
  return ok ? principal : "";
1083
1107
  }
1084
1108
  function principalHash(principal) {
@@ -1335,11 +1359,11 @@ function errorDetailMode() {
1335
1359
  function maxBodyBytes() {
1336
1360
  return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
1337
1361
  }
1338
- function poolOf(path8) {
1339
- if (path8 === "/api/v1/analyze" || path8.startsWith("/api/v1/analyze/")) return "biz";
1340
- if (path8 === "/api/v1/review" || path8.startsWith("/api/v1/review/")) return "review";
1341
- if (path8 === "/console" || path8.startsWith("/console/") || path8.startsWith("/api/v1/brain")) return "ops";
1342
- if (path8 === "/api/v1/health") return "health";
1362
+ function poolOf(path9) {
1363
+ if (path9 === "/api/v1/analyze" || path9.startsWith("/api/v1/analyze/")) return "biz";
1364
+ if (path9 === "/api/v1/review" || path9.startsWith("/api/v1/review/")) return "review";
1365
+ if (path9 === "/console" || path9.startsWith("/console/") || path9.startsWith("/api/v1/brain")) return "ops";
1366
+ if (path9 === "/api/v1/health") return "health";
1343
1367
  return "other";
1344
1368
  }
1345
1369
  function poolLimit(name) {
@@ -1824,7 +1848,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
1824
1848
  os: String(sp.os || "linux").toLowerCase()
1825
1849
  }));
1826
1850
  }
1827
- function _scopeOf(os5, path8) {
1851
+ function _scopeOf(os6, path9) {
1828
1852
  if (!_scopeIndex) {
1829
1853
  _scopeIndex = /* @__PURE__ */ new Map();
1830
1854
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -1832,7 +1856,7 @@ function _scopeOf(os5, path8) {
1832
1856
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
1833
1857
  }
1834
1858
  }
1835
- return _scopeIndex.get(`${String(os5 || "linux").toLowerCase()}|${path8}`) || "root";
1859
+ return _scopeIndex.get(`${String(os6 || "linux").toLowerCase()}|${path9}`) || "root";
1836
1860
  }
1837
1861
  function getSensitivePathsForOs(osType) {
1838
1862
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -2551,36 +2575,36 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2551
2575
  }
2552
2576
  const preciseEdit = isPreciseEditTool(actionType);
2553
2577
  const unreadPaths = [];
2554
- for (const path8 of checkTargets) {
2555
- if (isDirectoryTarget(path8)) continue;
2578
+ for (const path9 of checkTargets) {
2579
+ if (isDirectoryTarget(path9)) continue;
2556
2580
  let isFullRead = [...normalizedFullReads].some(
2557
- (rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
2581
+ (rp) => pathIsSameOrUnder(path9, rp) || pathIsSameOrUnder(rp, path9)
2558
2582
  );
2559
2583
  if (!isFullRead && preciseEdit && [...normalizedWrittenPaths].some(
2560
- (wp) => pathIsSameOrUnder(path8, wp) || pathIsSameOrUnder(wp, path8)
2584
+ (wp) => pathIsSameOrUnder(path9, wp) || pathIsSameOrUnder(wp, path9)
2561
2585
  )) {
2562
2586
  isFullRead = true;
2563
2587
  }
2564
- if (!isFullRead && !isProtectedWritePath(path8) && isScriptGeneratedTarget(path8, historyWrittenScripts, shellRunActions)) {
2588
+ if (!isFullRead && !isProtectedWritePath(path9) && isScriptGeneratedTarget(path9, historyWrittenScripts, shellRunActions)) {
2565
2589
  isFullRead = true;
2566
2590
  }
2567
2591
  let isPartialCovered = false;
2568
2592
  if (!isFullRead) {
2569
2593
  for (const [pp, upto] of normalizedPartialReads) {
2570
- if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
2571
- if (preciseEdit || upto != null && fileHasAtMostLines(path8, upto)) {
2594
+ if (!(pathIsSameOrUnder(path9, pp) || pathIsSameOrUnder(pp, path9))) continue;
2595
+ if (preciseEdit || upto != null && fileHasAtMostLines(path9, upto)) {
2572
2596
  isPartialCovered = true;
2573
2597
  break;
2574
2598
  }
2575
2599
  }
2576
2600
  }
2577
2601
  if (!isFullRead && !isPartialCovered) {
2578
- let isCreate = !fs.existsSync(path8);
2602
+ let isCreate = !fs.existsSync(path9);
2579
2603
  if (!isCreate) {
2580
2604
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
2581
2605
  }
2582
2606
  if (!isCreate) {
2583
- unreadPaths.push(path8);
2607
+ unreadPaths.push(path9);
2584
2608
  }
2585
2609
  }
2586
2610
  }
@@ -2774,16 +2798,16 @@ var init_logic_rules = __esm({
2774
2798
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
2775
2799
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
2776
2800
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
2777
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2801
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2778
2802
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
2779
2803
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
2780
- CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2804
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2781
2805
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
2782
2806
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
2783
- CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2807
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2784
2808
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
2785
2809
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
2786
- CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2810
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2787
2811
  _scopeIndex = null;
2788
2812
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
2789
2813
  "ask_user_question",
@@ -3259,8 +3283,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
3259
3283
  function _filterRulesByOs(rules, osType) {
3260
3284
  const accepted = acceptedOsValues(osType);
3261
3285
  return rules.filter((r) => {
3262
- const os5 = String(r.os || "linux").toLowerCase();
3263
- return os5 === "all" || accepted.includes(os5);
3286
+ const os6 = String(r.os || "linux").toLowerCase();
3287
+ return os6 === "all" || accepted.includes(os6);
3264
3288
  });
3265
3289
  }
3266
3290
  function _userCustomRules(runtime, layers, requiredKey) {
@@ -3462,7 +3486,7 @@ function _l2SensitivePathsToRules() {
3462
3486
  const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
3463
3487
  const all = [...root, ...home, ...credential];
3464
3488
  for (const sp of all) {
3465
- const os5 = String(sp.os || "linux").toLowerCase();
3489
+ const os6 = String(sp.os || "linux").toLowerCase();
3466
3490
  const denyMode = sp.denyMode || _deriveDenyMode({
3467
3491
  deny_mode: sp.deny_mode,
3468
3492
  credential: sp.credential,
@@ -3472,7 +3496,7 @@ function _l2SensitivePathsToRules() {
3472
3496
  // id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
3473
3497
  // hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
3474
3498
  // Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
3475
- id: `path_${os5}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3499
+ id: `path_${os6}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3476
3500
  path: sp.path,
3477
3501
  risk_level: sp.riskLevel,
3478
3502
  desc: sp.desc,
@@ -3481,7 +3505,7 @@ function _l2SensitivePathsToRules() {
3481
3505
  skip_l3_on_disabled: true,
3482
3506
  enabled: true,
3483
3507
  builtin: true,
3484
- os: os5
3508
+ os: os6
3485
3509
  };
3486
3510
  _syncDenyModeFields(rule);
3487
3511
  if (sp.dirDelOnly) rule.dir_del_only = true;
@@ -4019,8 +4043,8 @@ function _filterDefaultsByOs(rules, osType) {
4019
4043
  const accepted = acceptedOsValues(osType);
4020
4044
  return rules.filter((r) => {
4021
4045
  if (!r.os) return true;
4022
- const os5 = String(r.os).toLowerCase();
4023
- return os5 === "all" || accepted.includes(os5);
4046
+ const os6 = String(r.os).toLowerCase();
4047
+ return os6 === "all" || accepted.includes(os6);
4024
4048
  });
4025
4049
  }
4026
4050
  function _hasRulesForOs(rules, osType) {
@@ -5062,24 +5086,24 @@ function extractWritePayload(actionType, actionDetailRaw) {
5062
5086
  const detail = actionDetailRaw || "";
5063
5087
  const m = detail.match(WRITE_PREFIX_RE);
5064
5088
  if (m) {
5065
- const path8 = m[1];
5089
+ const path9 = m[1];
5066
5090
  let content = m[2] || "";
5067
- if (!path8 || path8 === "?" || path8 === "-" || !content.trim()) return null;
5091
+ if (!path9 || path9 === "?" || path9 === "-" || !content.trim()) return null;
5068
5092
  if ((actionType || "").toLowerCase().includes("editfile")) {
5069
5093
  const nm = content.match(EDIT_NEW_RE);
5070
5094
  if (nm) content = nm[1];
5071
5095
  }
5072
- return { path: path8, content };
5096
+ return { path: path9, content };
5073
5097
  }
5074
5098
  const stripped = detail.trim();
5075
5099
  if (stripped.startsWith("{")) {
5076
5100
  try {
5077
5101
  const obj = JSON.parse(stripped);
5078
5102
  if (obj && typeof obj === "object") {
5079
- const path8 = obj.path || obj.file_path || obj.filePath;
5103
+ const path9 = obj.path || obj.file_path || obj.filePath;
5080
5104
  const content = obj.content || obj.newString || obj.new_string;
5081
- if (typeof path8 === "string" && path8 !== "" && path8 !== "?" && path8 !== "-" && typeof content === "string" && content.trim()) {
5082
- return { path: path8, content };
5105
+ if (typeof path9 === "string" && path9 !== "" && path9 !== "?" && path9 !== "-" && typeof content === "string" && content.trim()) {
5106
+ return { path: path9, content };
5083
5107
  }
5084
5108
  }
5085
5109
  } catch {
@@ -5092,8 +5116,8 @@ function handlesWrittenContent(actionType, actionDetailRaw) {
5092
5116
  if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
5093
5117
  return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
5094
5118
  }
5095
- function detectLanguage(path8, content) {
5096
- const ext = path8.slice(path8.lastIndexOf(".") >= 0 ? path8.lastIndexOf(".") : path8.length).toLowerCase();
5119
+ function detectLanguage(path9, content) {
5120
+ const ext = path9.slice(path9.lastIndexOf(".") >= 0 ? path9.lastIndexOf(".") : path9.length).toLowerCase();
5097
5121
  if (SHELL_EXTS.has(ext)) return "shell";
5098
5122
  if (PY_EXTS.has(ext)) return "python";
5099
5123
  if (DATA_EXTS.has(ext)) return "data";
@@ -5251,8 +5275,8 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
5251
5275
  if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
5252
5276
  const payload = extractWritePayload(actionType, actionDetailRaw);
5253
5277
  if (!payload) return [];
5254
- const { path: path8, content: rawContent } = payload;
5255
- const language = detectLanguage(path8, rawContent);
5278
+ const { path: path9, content: rawContent } = payload;
5279
+ const language = detectLanguage(path9, rawContent);
5256
5280
  if (language === "data") return [];
5257
5281
  let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
5258
5282
  const started = Date.now();
@@ -5746,16 +5770,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5746
5770
  if (String(osType || "").toLowerCase() === "windows") {
5747
5771
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
5748
5772
  }
5749
- const pathMatches = (text, path8) => {
5750
- const parts = path8.split(/(\(\?!.*?\))/);
5773
+ const pathMatches = (text, path9) => {
5774
+ const parts = path9.split(/(\(\?!.*?\))/);
5751
5775
  const escaped = parts.map((part) => {
5752
5776
  if (part.startsWith("(?!")) return part;
5753
5777
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5754
5778
  }).join("");
5755
- const re = path8.startsWith(".") || path8.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
5779
+ const re = path9.startsWith(".") || path9.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
5756
5780
  return re.test(text);
5757
5781
  };
5758
- const pathMatchesAny = (path8) => pathScanTexts.some((t) => pathMatches(t, path8));
5782
+ const pathMatchesAny = (path9) => pathScanTexts.some((t) => pathMatches(t, path9));
5759
5783
  for (const sp of rootPaths) {
5760
5784
  if (pathMatchesAny(sp.path.toLowerCase())) {
5761
5785
  if (keygenGenerate) continue;
@@ -5898,8 +5922,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5898
5922
  }
5899
5923
  return null;
5900
5924
  }
5901
- function isHomeValue(path8) {
5902
- let p = path8.trim().toLowerCase();
5925
+ function isHomeValue(path9) {
5926
+ let p = path9.trim().toLowerCase();
5903
5927
  if (p.startsWith("$(") && p.endsWith(")")) {
5904
5928
  const inner = p.slice(2, -1).trim();
5905
5929
  return HOME_TARGET_RE.test(" " + inner);
@@ -5955,15 +5979,15 @@ function checkHomeDeletion(actionType, actionDetail) {
5955
5979
  }
5956
5980
  const assigned = {};
5957
5981
  for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
5958
- for (const [varName, path8] of Object.entries(assigned)) {
5959
- if (!isHomeValue(path8)) continue;
5982
+ for (const [varName, path9] of Object.entries(assigned)) {
5983
+ if (!isHomeValue(path9)) continue;
5960
5984
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
5961
5985
  for (const seg of segs) {
5962
5986
  if (!isDeleteCommand(seg)) continue;
5963
5987
  if (varRefRe.test(seg)) {
5964
5988
  return {
5965
5989
  allowed: false,
5966
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path8}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5990
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path9}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5967
5991
  riskLevel: "high",
5968
5992
  riskType: "script_execution",
5969
5993
  confidence: 90,
@@ -6771,15 +6795,15 @@ function parseShellString(s) {
6771
6795
  let m;
6772
6796
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
6773
6797
  const interp = m[1];
6774
- const path8 = m[2].trim();
6798
+ const path9 = m[2].trim();
6775
6799
  let rest = m[3].trim();
6776
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6800
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
6777
6801
  rest = rest.split(/[;|&<>]/)[0].trim();
6778
6802
  const args = [];
6779
6803
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6780
6804
  args.push(tm[1] ? tm[2] : tm[3]);
6781
6805
  }
6782
- return { path: path8, args, interpreter: interp };
6806
+ return { path: path9, args, interpreter: interp };
6783
6807
  }
6784
6808
  return null;
6785
6809
  }
@@ -6825,9 +6849,9 @@ function extractCallsFromTree(tree, reachableLines) {
6825
6849
  }
6826
6850
  if (allStr && elts.length >= 2) {
6827
6851
  const interp = elts[0];
6828
- const path8 = elts[1];
6829
- if (!path8.startsWith("-") && !path8.startsWith("$") && !path8.includes("/dev/")) {
6830
- add({ path: path8, args: elts.slice(2), interpreter: interp });
6852
+ const path9 = elts[1];
6853
+ if (!path9.startsWith("-") && !path9.startsWith("$") && !path9.includes("/dev/")) {
6854
+ add({ path: path9, args: elts.slice(2), interpreter: interp });
6831
6855
  return true;
6832
6856
  }
6833
6857
  }
@@ -6867,15 +6891,15 @@ function extractCallsRegex(content) {
6867
6891
  let m;
6868
6892
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
6869
6893
  const interp = m[1];
6870
- const path8 = m[2].trim();
6894
+ const path9 = m[2].trim();
6871
6895
  let rest = m[3].trim();
6872
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6896
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
6873
6897
  rest = rest.split(/[;|&<>]/)[0].trim();
6874
6898
  const args = [];
6875
6899
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6876
6900
  args.push(tm[1] ? tm[2] : tm[3]);
6877
6901
  }
6878
- calls.push({ path: path8, args, interpreter: interp });
6902
+ calls.push({ path: path9, args, interpreter: interp });
6879
6903
  }
6880
6904
  return calls;
6881
6905
  }
@@ -7669,15 +7693,15 @@ function extractCallsFromContent(content) {
7669
7693
  CHILD_CALL_RE2.lastIndex = 0;
7670
7694
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
7671
7695
  const interp = m[1];
7672
- const path8 = m[2].trim();
7696
+ const path9 = m[2].trim();
7673
7697
  let rest = m[3].trim();
7674
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
7698
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
7675
7699
  rest = rest.split(/[;|&<>]/)[0].trim();
7676
7700
  const args = [];
7677
7701
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
7678
7702
  args.push(tm[1] ? tm[2] : tm[3]);
7679
7703
  }
7680
- calls.push({ path: path8, args, interpreter: interp });
7704
+ calls.push({ path: path9, args, interpreter: interp });
7681
7705
  }
7682
7706
  return calls;
7683
7707
  }
@@ -9316,6 +9340,28 @@ function formatHints(previous) {
9316
9340
  }
9317
9341
  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";
9318
9342
  }
9343
+ function maskedBaseUrl(raw) {
9344
+ try {
9345
+ const u = new URL(raw || "https://api.openai.com/v1");
9346
+ return `${u.protocol}//${u.hostname}${u.port ? ":" + u.port : ""}${u.pathname || ""}`;
9347
+ } catch {
9348
+ return "(unparseable)";
9349
+ }
9350
+ }
9351
+ function llmErrorDetail(err, config, attempt, maxRetries, elapsedMs, promptChars, timeoutMs) {
9352
+ const chain = [];
9353
+ let cur = err;
9354
+ const seen = /* @__PURE__ */ new Set();
9355
+ while (cur && !seen.has(cur) && chain.length < 4) {
9356
+ seen.add(cur);
9357
+ chain.push(`${cur?.constructor?.name || typeof cur}(${String(cur?.message ?? cur).replace(/\n/g, " ").slice(0, 300)})`);
9358
+ cur = cur?.cause ?? cur?.context;
9359
+ }
9360
+ const proxy = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"].filter((n) => process.env[n]).join(",") || "none";
9361
+ const cause = err?.cause ?? err?.context;
9362
+ const errno = cause?.errno ?? cause?.code ?? err?.errno ?? err?.code;
9363
+ 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(" <- ")}`;
9364
+ }
9319
9365
  async function analyzeWithLLM(prompt, config) {
9320
9366
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
9321
9367
  const _llmStart = performance.now();
@@ -9363,6 +9409,7 @@ async function analyzeWithLLM(prompt, config) {
9363
9409
  if (abortController.signal.aborted) {
9364
9410
  break;
9365
9411
  }
9412
+ const attemptStart = performance.now();
9366
9413
  try {
9367
9414
  const response = await client.chat.completions.create({
9368
9415
  model: config.model,
@@ -9478,7 +9525,16 @@ async function analyzeWithLLM(prompt, config) {
9478
9525
  const errObj = err;
9479
9526
  const status = errObj?.status ?? errObj?.statusCode;
9480
9527
  const body = errObj?.error ?? errObj?.body;
9481
- const detail = status !== void 0 || body !== void 0 ? `${err.message} status=${status} body=${String(JSON.stringify(body)).slice(0, 300)}` : err.message;
9528
+ const baseDetail = status !== void 0 || body !== void 0 ? `${err.message} status=${status} body=${String(JSON.stringify(body)).slice(0, 300)}` : err.message;
9529
+ const detail = `${baseDetail} | ${llmErrorDetail(
9530
+ err,
9531
+ config,
9532
+ attempt + 1,
9533
+ maxRetries,
9534
+ performance.now() - attemptStart,
9535
+ prompt.length,
9536
+ (config.timeout || timeoutCfg.prompt1Timeout) * 1e3
9537
+ )}`;
9482
9538
  if (attempt < maxRetries) {
9483
9539
  console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
9484
9540
  await new Promise((resolve12) => setTimeout(resolve12, retryCfg.retryInterval * 1e3));
@@ -9550,8 +9606,8 @@ var init_rule_store = __esm({
9550
9606
  BrainRuleStore = class {
9551
9607
  path;
9552
9608
  data;
9553
- constructor(path8) {
9554
- this.path = path8 || getRulesPath();
9609
+ constructor(path9) {
9610
+ this.path = path9 || getRulesPath();
9555
9611
  this.data = this.load();
9556
9612
  }
9557
9613
  load() {
@@ -10004,10 +10060,10 @@ ${reason.slice(0, 500)}
10004
10060
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
10005
10061
  let mm;
10006
10062
  while ((mm = pathRe.exec(src)) !== null) {
10007
- const path8 = mm[1];
10008
- if (path8.split("/").length < 3) continue;
10009
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path8)) continue;
10010
- const gen = this.generalizePath(path8);
10063
+ const path9 = mm[1];
10064
+ if (path9.split("/").length < 3) continue;
10065
+ if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path9)) continue;
10066
+ const gen = this.generalizePath(path9);
10011
10067
  if (seen.has(gen)) continue;
10012
10068
  seen.add(gen);
10013
10069
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -10026,8 +10082,8 @@ ${reason.slice(0, 500)}
10026
10082
  }
10027
10083
  return false;
10028
10084
  }
10029
- generalizePath(path8) {
10030
- const p = path8.toLowerCase();
10085
+ generalizePath(path9) {
10086
+ const p = path9.toLowerCase();
10031
10087
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
10032
10088
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
10033
10089
  }
@@ -10415,26 +10471,26 @@ function writeExportFiles(outDir, rules, skills) {
10415
10471
  byLayer.get(r.layer).push(r);
10416
10472
  }
10417
10473
  for (const layer of [...byLayer.keys()].sort((a, b) => a - b)) {
10418
- const path8 = join15(rulesDir2, `l${layer}_brain_rules.json`);
10419
- writeFileSync5(path8, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
10420
- written.push(path8);
10474
+ const path9 = join15(rulesDir2, `l${layer}_brain_rules.json`);
10475
+ writeFileSync5(path9, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
10476
+ written.push(path9);
10421
10477
  }
10422
10478
  if (rules.length === 0) {
10423
- const path8 = join15(rulesDir2, "empty.txt");
10424
- writeFileSync5(path8, "(no brain rules to contribute)", "utf-8");
10425
- written.push(path8);
10479
+ const path9 = join15(rulesDir2, "empty.txt");
10480
+ writeFileSync5(path9, "(no brain rules to contribute)", "utf-8");
10481
+ written.push(path9);
10426
10482
  }
10427
10483
  const skillsDir = join15(outDir, "skills");
10428
10484
  mkdirSync6(skillsDir, { recursive: true });
10429
10485
  for (const sk of skills) {
10430
- const path8 = join15(skillsDir, `${sk.name}.md`);
10431
- writeFileSync5(path8, sk.content || "", "utf-8");
10432
- written.push(path8);
10486
+ const path9 = join15(skillsDir, `${sk.name}.md`);
10487
+ writeFileSync5(path9, sk.content || "", "utf-8");
10488
+ written.push(path9);
10433
10489
  }
10434
10490
  if (skills.length === 0) {
10435
- const path8 = join15(skillsDir, "empty.txt");
10436
- writeFileSync5(path8, "(no brain skills to contribute)", "utf-8");
10437
- written.push(path8);
10491
+ const path9 = join15(skillsDir, "empty.txt");
10492
+ writeFileSync5(path9, "(no brain skills to contribute)", "utf-8");
10493
+ written.push(path9);
10438
10494
  }
10439
10495
  return written;
10440
10496
  }
@@ -11152,12 +11208,12 @@ var init_builder = __esm({
11152
11208
  });
11153
11209
 
11154
11210
  // src/engine/formal-engine/properties.ts
11155
- function graphFromPath(nodes, path8, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
11211
+ function graphFromPath(nodes, path9, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
11156
11212
  const byKey = /* @__PURE__ */ new Map();
11157
11213
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
11158
11214
  const gNodes = [];
11159
11215
  const gEdges = [];
11160
- for (const item of path8) {
11216
+ for (const item of path9) {
11161
11217
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
11162
11218
  gNodes.push({
11163
11219
  session_id: item.sessionId,
@@ -11223,22 +11279,22 @@ function checkCrossSessionChain(graph) {
11223
11279
  if (witness !== void 0) {
11224
11280
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
11225
11281
  let matched = 0;
11226
- const path8 = [];
11282
+ const path9 = [];
11227
11283
  for (let k = 0; k < witness; k++) {
11228
11284
  const n = nodes[k];
11229
11285
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
11230
11286
  matched += 1;
11231
- path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
11287
+ path9.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
11232
11288
  }
11233
11289
  }
11234
11290
  if (matched < stages.length - 1) continue;
11235
- path8.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
11291
+ path9.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
11236
11292
  violations.push({
11237
11293
  propertyId: "cross-" + chain.id,
11238
11294
  reason: chain.reason,
11239
11295
  riskLevel: chain.riskLevel,
11240
- path: path8,
11241
- graph: graphFromPath(nodes, path8, "next", {
11296
+ path: path9,
11297
+ graph: graphFromPath(nodes, path9, "next", {
11242
11298
  property_id: "cross-" + chain.id,
11243
11299
  property_short: "P1",
11244
11300
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -11248,11 +11304,11 @@ function checkCrossSessionChain(graph) {
11248
11304
  } else {
11249
11305
  let matched = 0;
11250
11306
  let stageIdx = 0;
11251
- const path8 = [];
11307
+ const path9 = [];
11252
11308
  for (const n of nodes) {
11253
11309
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
11254
11310
  matched += 1;
11255
- path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
11311
+ path9.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
11256
11312
  stageIdx += 1;
11257
11313
  if (matched >= stages.length) break;
11258
11314
  }
@@ -11262,8 +11318,8 @@ function checkCrossSessionChain(graph) {
11262
11318
  propertyId: "cross-" + chain.id,
11263
11319
  reason: chain.reason,
11264
11320
  riskLevel: chain.riskLevel,
11265
- path: path8,
11266
- graph: graphFromPath(nodes, path8, "next", {
11321
+ path: path9,
11322
+ graph: graphFromPath(nodes, path9, "next", {
11267
11323
  property_id: "cross-" + chain.id,
11268
11324
  property_short: "P1",
11269
11325
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -11484,7 +11540,7 @@ function checkNeverExfilAfterPrivesc(graph) {
11484
11540
  if (candidates.length > 0) {
11485
11541
  const pre = nodes[candidates[candidates.length - 1]];
11486
11542
  const post = nodes[firstEv];
11487
- const path8 = [
11543
+ const path9 = [
11488
11544
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
11489
11545
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
11490
11546
  ];
@@ -11492,8 +11548,8 @@ function checkNeverExfilAfterPrivesc(graph) {
11492
11548
  propertyId: "no-exfil-after-privesc",
11493
11549
  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",
11494
11550
  riskLevel: "critical",
11495
- path: path8,
11496
- graph: graphFromPath(nodes, path8, "next", {
11551
+ path: path9,
11552
+ graph: graphFromPath(nodes, path9, "next", {
11497
11553
  property_id: "no-exfil-after-privesc",
11498
11554
  property_short: "P4",
11499
11555
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -11510,7 +11566,7 @@ function checkNeverExfilAfterPrivesc(graph) {
11510
11566
  for (let j = i + 1; j < nodes.length; j++) {
11511
11567
  if (!isExfilNode(nodes[j])) continue;
11512
11568
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
11513
- const path8 = [
11569
+ const path9 = [
11514
11570
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
11515
11571
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
11516
11572
  ];
@@ -11518,8 +11574,8 @@ function checkNeverExfilAfterPrivesc(graph) {
11518
11574
  propertyId: "no-exfil-after-privesc",
11519
11575
  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",
11520
11576
  riskLevel: "critical",
11521
- path: path8,
11522
- graph: graphFromPath(nodes, path8, "next", {
11577
+ path: path9,
11578
+ graph: graphFromPath(nodes, path9, "next", {
11523
11579
  property_id: "no-exfil-after-privesc",
11524
11580
  property_short: "P4",
11525
11581
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -11551,7 +11607,7 @@ function checkNeverExfilAfterCred(graph) {
11551
11607
  }
11552
11608
  if (pre) {
11553
11609
  const post = nodes[firstEv];
11554
- const path8 = [
11610
+ const path9 = [
11555
11611
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
11556
11612
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
11557
11613
  ];
@@ -11559,8 +11615,8 @@ function checkNeverExfilAfterCred(graph) {
11559
11615
  propertyId: "no-exfil-after-credential",
11560
11616
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
11561
11617
  riskLevel: "critical",
11562
- path: path8,
11563
- graph: graphFromPath(nodes, path8, "data", {
11618
+ path: path9,
11619
+ graph: graphFromPath(nodes, path9, "data", {
11564
11620
  property_id: "no-exfil-after-credential",
11565
11621
  property_short: "P5",
11566
11622
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -11576,7 +11632,7 @@ function checkNeverExfilAfterCred(graph) {
11576
11632
  if (!isCredNode(nodes[i])) continue;
11577
11633
  for (let j = i + 1; j < nodes.length; j++) {
11578
11634
  if (isExfilNode(nodes[j])) {
11579
- const path8 = [
11635
+ const path9 = [
11580
11636
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
11581
11637
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
11582
11638
  ];
@@ -11584,8 +11640,8 @@ function checkNeverExfilAfterCred(graph) {
11584
11640
  propertyId: "no-exfil-after-credential",
11585
11641
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
11586
11642
  riskLevel: "critical",
11587
- path: path8,
11588
- graph: graphFromPath(nodes, path8, "data", {
11643
+ path: path9,
11644
+ graph: graphFromPath(nodes, path9, "data", {
11589
11645
  property_id: "no-exfil-after-credential",
11590
11646
  property_short: "P5",
11591
11647
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -11744,13 +11800,13 @@ function checkSensitiveDataAggregation(graph) {
11744
11800
  if (!isExfilNode(n)) continue;
11745
11801
  const srcs = sourcesFor(i);
11746
11802
  if (srcs.size >= 2) {
11747
- const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11803
+ const path9 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11748
11804
  violations.push({
11749
11805
  propertyId: "sensitive-data-aggregation",
11750
11806
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
11751
11807
  riskLevel: "critical",
11752
- path: path8,
11753
- graph: graphFromPath(nodes, path8, "next", {
11808
+ path: path9,
11809
+ graph: graphFromPath(nodes, path9, "next", {
11754
11810
  property_id: "sensitive-data-aggregation",
11755
11811
  property_short: "P8",
11756
11812
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -11872,6 +11928,10 @@ var init_engine = __esm({
11872
11928
  });
11873
11929
 
11874
11930
  // src/engine/formal-engine/stateful.ts
11931
+ import * as fs5 from "fs";
11932
+ import * as os3 from "os";
11933
+ import * as path6 from "path";
11934
+ import { gzipSync } from "zlib";
11875
11935
  function extractInstances(actionDetail, stage) {
11876
11936
  const out = [];
11877
11937
  if (PORT_STAGE_RE.test(stage)) {
@@ -12070,12 +12130,65 @@ var init_stateful = __esm({
12070
12130
  }
12071
12131
  };
12072
12132
  }
12133
+ /**
12134
+ * 自动轮转:归档旧节点,只保留最近 `retain` 条,并重建链指针/taint。
12135
+ *
12136
+ * 派生缓存不是原始历史存储;归档失败抛异常,调用方不得丢状态。
12137
+ */
12138
+ rotate(archiveDir, retain) {
12139
+ const keep = Math.max(1, Math.min(retain ?? Math.floor(MAX_NODES / 2), MAX_NODES - 1));
12140
+ if (this.nodes_.length <= keep) return { archived: 0, file: "" };
12141
+ const old = this.nodes_.slice(0, this.nodes_.length - keep);
12142
+ const kept = this.nodes_.slice(-keep);
12143
+ 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");
12144
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
12145
+ const safeAgent = (this.agentId || "default").replace(/[^A-Za-z0-9_.-]/g, "_");
12146
+ const file = path6.join(dir, `chain-nodes-${safeAgent}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.jsonl.gz`);
12147
+ const payload = old.map((n) => JSON.stringify(n)).join("\n") + "\n";
12148
+ fs5.writeFileSync(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
12149
+ this.nodes_ = [];
12150
+ this.ptr = {};
12151
+ this.tainted.clear();
12152
+ this.taintedResources.clear();
12153
+ this.taintParent.clear();
12154
+ this.taintEdgeLabel.clear();
12155
+ this.taintOrigin.clear();
12156
+ this.aliveResources = {};
12157
+ this.seqNext = 0;
12158
+ for (const n of kept) {
12159
+ const node = this.appendNode(
12160
+ {
12161
+ actionType: n.actionType,
12162
+ actionDetail: n.actionDetail,
12163
+ agentId: n.agentId,
12164
+ instanceId: n.instanceId,
12165
+ ...n.timestamp ? { calledAt: n.timestamp } : {}
12166
+ },
12167
+ n.sessionId,
12168
+ n.isError,
12169
+ n.agentId,
12170
+ n.instanceId
12171
+ );
12172
+ if (node) {
12173
+ this.recordLifecycle(node);
12174
+ this.advanceTaint(node);
12175
+ this.advanceChains(node);
12176
+ }
12177
+ }
12178
+ return { archived: old.length, file };
12179
+ }
12073
12180
  appendNode(action, sessionId, isError = false, agentId = "", instanceId = "") {
12074
12181
  const ad = String(action.actionDetail || "");
12075
12182
  const at = String(action.actionType || "");
12076
12183
  if (!ad) return null;
12077
12184
  if (this.nodes_.length >= MAX_NODES) {
12078
- return null;
12185
+ try {
12186
+ const r = this.rotate();
12187
+ if (r.archived <= 0) return null;
12188
+ } catch (e) {
12189
+ console.error(`[AgentMoss] chain state rotate failed (${this.agentId}): ${e?.message ?? e}`);
12190
+ return null;
12191
+ }
12079
12192
  }
12080
12193
  const stage = markStage2(ad);
12081
12194
  const node = {
@@ -12223,11 +12336,11 @@ var init_stateful = __esm({
12223
12336
  }
12224
12337
  }
12225
12338
  chainPath(stages) {
12226
- const path8 = [];
12339
+ const path9 = [];
12227
12340
  let want = stages[0];
12228
12341
  for (const n of this.nodes_) {
12229
12342
  if (n.stage === want) {
12230
- path8.push({
12343
+ path9.push({
12231
12344
  sessionId: n.sessionId,
12232
12345
  seq: n.seq,
12233
12346
  stage: n.stage,
@@ -12243,12 +12356,12 @@ var init_stateful = __esm({
12243
12356
  }
12244
12357
  }
12245
12358
  }
12246
- return path8;
12359
+ return path9;
12247
12360
  }
12248
12361
  /** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
12249
12362
  buildChainGraph(stages, chainId) {
12250
- const path8 = this.chainPath(stages);
12251
- const gNodes = path8.map((p, i) => {
12363
+ const path9 = this.chainPath(stages);
12364
+ const gNodes = path9.map((p, i) => {
12252
12365
  const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
12253
12366
  return {
12254
12367
  session_id: p.sessionId,
@@ -12499,14 +12612,29 @@ var init_stateful = __esm({
12499
12612
  });
12500
12613
 
12501
12614
  // src/engine/formal-engine/chain_state.ts
12502
- import * as fs5 from "fs";
12503
- import * as os3 from "os";
12504
- import * as path6 from "path";
12615
+ import * as fs6 from "fs";
12616
+ import * as os4 from "os";
12617
+ import * as path7 from "path";
12505
12618
  import { createHash as createHash4 } from "crypto";
12506
12619
  function defaultStateDbPath() {
12507
- const dir = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
12620
+ const base = process.env.AGENT_MOSS_STATE_DIR || path7.join(os4.homedir(), ".agentmoss");
12621
+ const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
12622
+ const dir = instance ? path7.join(base, instance) : base;
12508
12623
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
12509
- return path6.join(dir, `stateful_chains_${tag}.json`);
12624
+ const target = path7.join(dir, `stateful_chains_${tag}.json`);
12625
+ if (instance) {
12626
+ const legacy = path7.join(base, `stateful_chains_${tag}.json`);
12627
+ if (!fs6.existsSync(target) && fs6.existsSync(legacy)) {
12628
+ try {
12629
+ fs6.mkdirSync(dir, { recursive: true });
12630
+ fs6.copyFileSync(legacy, target);
12631
+ console.warn(`[AgentMoss] \u94FE\u72B6\u6001\u6587\u4EF6\u6309 instance \u9694\u79BB\uFF1A\u5DF2\u4ECE\u65E7\u5171\u4EAB\u6587\u4EF6\u590D\u5236\u5230 ${target}`);
12632
+ } catch (err) {
12633
+ console.warn("[AgentMoss] \u8FC1\u79FB\u94FE\u72B6\u6001\u6587\u4EF6\u5931\u8D25\uFF08\u5C06\u4F7F\u7528\u65B0\u7A7A\u6587\u4EF6\uFF09:", err);
12634
+ }
12635
+ }
12636
+ }
12637
+ return target;
12510
12638
  }
12511
12639
  function registerExitFlush(store) {
12512
12640
  if (_exitHookRegistered) return;
@@ -12577,8 +12705,8 @@ var init_chain_state = __esm({
12577
12705
  }
12578
12706
  _read() {
12579
12707
  try {
12580
- if (fs5.existsSync(this.filePath)) {
12581
- const raw = fs5.readFileSync(this.filePath, "utf-8");
12708
+ if (fs6.existsSync(this.filePath)) {
12709
+ const raw = fs6.readFileSync(this.filePath, "utf-8");
12582
12710
  return JSON.parse(raw);
12583
12711
  }
12584
12712
  } catch {
@@ -12592,7 +12720,7 @@ var init_chain_state = __esm({
12592
12720
  this._timer = null;
12593
12721
  try {
12594
12722
  this._syncDirtyToData();
12595
- ensurePrivateDir(path6.dirname(this.filePath));
12723
+ ensurePrivateDir(path7.dirname(this.filePath));
12596
12724
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12597
12725
  } catch {
12598
12726
  }
@@ -12615,7 +12743,7 @@ var init_chain_state = __esm({
12615
12743
  }
12616
12744
  try {
12617
12745
  this._syncDirtyToData();
12618
- ensurePrivateDir(path6.dirname(this.filePath));
12746
+ ensurePrivateDir(path7.dirname(this.filePath));
12619
12747
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12620
12748
  } catch {
12621
12749
  }
@@ -12656,16 +12784,16 @@ var init_chain_state = __esm({
12656
12784
  const sleepBuf = new Int32Array(new SharedArrayBuffer(4));
12657
12785
  for (let attempt = 0; attempt < 100; attempt++) {
12658
12786
  try {
12659
- const fd = fs5.openSync(lockPath, "wx");
12787
+ const fd = fs6.openSync(lockPath, "wx");
12660
12788
  try {
12661
12789
  return fn();
12662
12790
  } finally {
12663
12791
  try {
12664
- fs5.closeSync(fd);
12792
+ fs6.closeSync(fd);
12665
12793
  } catch {
12666
12794
  }
12667
12795
  try {
12668
- fs5.unlinkSync(lockPath);
12796
+ fs6.unlinkSync(lockPath);
12669
12797
  } catch {
12670
12798
  }
12671
12799
  }
@@ -12683,7 +12811,7 @@ var init_chain_state = __esm({
12683
12811
  _flushNow() {
12684
12812
  this._syncDirtyToData();
12685
12813
  try {
12686
- const _dirOk = ensurePrivateDir(path6.dirname(this.filePath));
12814
+ const _dirOk = ensurePrivateDir(path7.dirname(this.filePath));
12687
12815
  const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12688
12816
  if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
12689
12817
  } catch (e) {
@@ -13265,7 +13393,7 @@ var init_types = __esm({
13265
13393
  import { createHash as createHash5 } from "crypto";
13266
13394
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
13267
13395
  import { tmpdir as tmpdir3 } from "os";
13268
- import { join as join17 } from "path";
13396
+ import { join as join18 } from "path";
13269
13397
  function cacheDir() {
13270
13398
  return cacheDirOverride ?? CACHE_DIR;
13271
13399
  }
@@ -13273,7 +13401,7 @@ function safeCacheDir() {
13273
13401
  const dir = cacheDir();
13274
13402
  if (ensurePrivateDir(dir)) return dir;
13275
13403
  try {
13276
- const fallback = join17(getDataRoot(), "policy_cache");
13404
+ const fallback = join18(getDataRoot(), "policy_cache");
13277
13405
  if (ensurePrivateDir(fallback)) {
13278
13406
  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}`);
13279
13407
  return fallback;
@@ -13294,7 +13422,7 @@ var init_policy_cache = __esm({
13294
13422
  init_security_policy();
13295
13423
  init_paths();
13296
13424
  init_config();
13297
- CACHE_DIR = join17(tmpdir3(), "agent_moss_policy_cache");
13425
+ CACHE_DIR = join18(tmpdir3(), "agent_moss_policy_cache");
13298
13426
  cacheDirOverride = null;
13299
13427
  PolicyCache = class {
13300
13428
  // Map 的插入序即 LRU 序(get 时重新 set 到末尾)
@@ -13309,7 +13437,7 @@ var init_policy_cache = __esm({
13309
13437
  cacheFilePath(sessionId, promptSession) {
13310
13438
  const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
13311
13439
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13312
- return join17(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13440
+ return join18(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13313
13441
  }
13314
13442
  /** 取缓存:内存 → 文件;未命中返回 null。 */
13315
13443
  get(sessionId, promptSession) {
@@ -13340,7 +13468,7 @@ var init_policy_cache = __esm({
13340
13468
  try {
13341
13469
  const dir = safeCacheDir();
13342
13470
  const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13343
- if (!ensurePrivateDir(join17(dir, sub))) return;
13471
+ if (!ensurePrivateDir(join18(dir, sub))) return;
13344
13472
  writePrivateText(file, policy);
13345
13473
  } catch {
13346
13474
  }
@@ -13366,12 +13494,12 @@ var init_policy_cache = __esm({
13366
13494
  if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
13367
13495
  }
13368
13496
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13369
- const dir = join17(cacheDir(), safeSessionId);
13497
+ const dir = join18(cacheDir(), safeSessionId);
13370
13498
  try {
13371
13499
  if (existsSync17(dir)) {
13372
13500
  for (const f of readdirSync5(dir)) {
13373
13501
  try {
13374
- unlinkSync4(join17(dir, f));
13502
+ unlinkSync4(join18(dir, f));
13375
13503
  } catch {
13376
13504
  }
13377
13505
  }
@@ -13385,9 +13513,9 @@ var init_policy_cache = __esm({
13385
13513
  try {
13386
13514
  if (existsSync17(cacheDir())) {
13387
13515
  for (const sessionDir of readdirSync5(cacheDir())) {
13388
- const dir = join17(cacheDir(), sessionDir);
13516
+ const dir = join18(cacheDir(), sessionDir);
13389
13517
  try {
13390
- for (const f of readdirSync5(dir)) unlinkSync4(join17(dir, f));
13518
+ for (const f of readdirSync5(dir)) unlinkSync4(join18(dir, f));
13391
13519
  rmdirSync(dir);
13392
13520
  } catch {
13393
13521
  }
@@ -13485,7 +13613,7 @@ __export(analyzer_exports, {
13485
13613
  });
13486
13614
  import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
13487
13615
  import { tmpdir as tmpdir4 } from "os";
13488
- import { join as join18, resolve as resolve11 } from "path";
13616
+ import { join as join19, resolve as resolve11 } from "path";
13489
13617
  import { parse as parseToml } from "smol-toml";
13490
13618
  function _setPolicyOutputDirForTest(dir) {
13491
13619
  policyOutputDirOverride = dir;
@@ -13502,7 +13630,7 @@ function savePolicyToFile(sessionId, policyToml) {
13502
13630
  return null;
13503
13631
  }
13504
13632
  const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13505
- const filepath = join18(outDir, `${safeName}.toml`);
13633
+ const filepath = join19(outDir, `${safeName}.toml`);
13506
13634
  writePrivateText(filepath, policyToml);
13507
13635
  return filepath;
13508
13636
  } catch (err) {
@@ -13725,7 +13853,7 @@ var init_analyzer = __esm({
13725
13853
  init_asset_dir();
13726
13854
  init_token_stats();
13727
13855
  init_logging();
13728
- POLICY_OUTPUT_DIR = join18(tmpdir4(), "agent_moss");
13856
+ POLICY_OUTPUT_DIR = join19(tmpdir4(), "agent_moss");
13729
13857
  policyOutputDirOverride = null;
13730
13858
  DEFAULT_READONLY_POLICY = `landlock_optional = false
13731
13859
  mount_isolation_fallback = false
@@ -13770,7 +13898,7 @@ var init_esm_require = __esm({
13770
13898
  });
13771
13899
 
13772
13900
  // src/actrail.ts
13773
- import * as fs6 from "fs";
13901
+ import * as fs7 from "fs";
13774
13902
  function escape(value) {
13775
13903
  return value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/=/g, "\\e");
13776
13904
  }
@@ -13791,7 +13919,7 @@ function getStoragePath() {
13791
13919
  function reportEnforcementEvent(opts) {
13792
13920
  if (!isEnabled()) return false;
13793
13921
  const storagePath = getStoragePath();
13794
- if (!fs6.existsSync(storagePath)) return false;
13922
+ if (!fs7.existsSync(storagePath)) return false;
13795
13923
  try {
13796
13924
  let Database;
13797
13925
  try {
@@ -13962,9 +14090,9 @@ var init_pattern_miner = __esm({
13962
14090
  });
13963
14091
 
13964
14092
  // src/agent-gate-reader.ts
13965
- import * as fs7 from "fs";
13966
- import * as os4 from "os";
13967
- import * as path7 from "path";
14093
+ import * as fs8 from "fs";
14094
+ import * as os5 from "os";
14095
+ import * as path8 from "path";
13968
14096
  function normalizeAction(row) {
13969
14097
  return {
13970
14098
  actionType: String(row.action_type || row.tool_name || row.name || ""),
@@ -13974,10 +14102,10 @@ function normalizeAction(row) {
13974
14102
  function readJsonDir(dirPath, limit = 1e5) {
13975
14103
  const sessions = /* @__PURE__ */ new Map();
13976
14104
  try {
13977
- const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
14105
+ const files = fs8.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
13978
14106
  for (const f of files.slice(-200)) {
13979
14107
  const sid = f.replace(/\.json$/, "");
13980
- const raw = fs7.readFileSync(path7.join(dirPath, f), "utf-8");
14108
+ const raw = fs8.readFileSync(path8.join(dirPath, f), "utf-8");
13981
14109
  const arr = JSON.parse(raw);
13982
14110
  if (!Array.isArray(arr)) continue;
13983
14111
  for (const item of arr) {
@@ -14034,7 +14162,7 @@ function readSqlite(dbPath, limit = 1e5) {
14034
14162
  function loadAgentGateSessions(dbPath = "") {
14035
14163
  if (dbPath) {
14036
14164
  try {
14037
- if (fs7.statSync(dbPath).isDirectory()) {
14165
+ if (fs8.statSync(dbPath).isDirectory()) {
14038
14166
  return readJsonDir(dbPath);
14039
14167
  }
14040
14168
  } catch {
@@ -14045,7 +14173,7 @@ function loadAgentGateSessions(dbPath = "") {
14045
14173
  }
14046
14174
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
14047
14175
  if (sql.length > 0) return sql;
14048
- const jsonDefault = path7.join(os4.homedir(), ".local", "share", "agent_gate", "tool_calls");
14176
+ const jsonDefault = path8.join(os5.homedir(), ".local", "share", "agent_gate", "tool_calls");
14049
14177
  return readJsonDir(jsonDefault);
14050
14178
  }
14051
14179
  var DEFAULT_AGENTGATE_SQLITE;
@@ -14054,8 +14182,8 @@ var init_agent_gate_reader = __esm({
14054
14182
  "use strict";
14055
14183
  init_esm_shims();
14056
14184
  init_esm_require();
14057
- DEFAULT_AGENTGATE_SQLITE = path7.join(
14058
- os4.homedir(),
14185
+ DEFAULT_AGENTGATE_SQLITE = path8.join(
14186
+ os5.homedir(),
14059
14187
  ".local",
14060
14188
  "share",
14061
14189
  "agent_gate",
@@ -14195,7 +14323,7 @@ var init_runtime_stats = __esm({
14195
14323
 
14196
14324
  // src/routes.ts
14197
14325
  import { randomBytes as randomBytes2 } from "crypto";
14198
- import { join as join20, dirname as dirname13 } from "path";
14326
+ import { join as join21, dirname as dirname13 } from "path";
14199
14327
  import { fileURLToPath as fileURLToPath10 } from "url";
14200
14328
  async function healthRoute(c) {
14201
14329
  const metrics = {};
@@ -14217,11 +14345,11 @@ async function healthRoute(c) {
14217
14345
  if (typeof pct === "number") {
14218
14346
  if (pct >= 100) {
14219
14347
  degraded.push(
14220
- `\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`
14348
+ `\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`
14221
14349
  );
14222
14350
  } else if (pct >= 90) {
14223
14351
  degraded.push(
14224
- `\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`
14352
+ `\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`
14225
14353
  );
14226
14354
  }
14227
14355
  }
@@ -14229,7 +14357,7 @@ async function healthRoute(c) {
14229
14357
  const snap = getBreaker().snapshot();
14230
14358
  if (snap.state === "open") {
14231
14359
  degraded.push(
14232
- `\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`
14360
+ `\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`
14233
14361
  );
14234
14362
  }
14235
14363
  } catch {
@@ -14429,11 +14557,11 @@ async function analyzeRoute(c) {
14429
14557
  const pct = Math.round(total / MAX_NODES * 1e3) / 10;
14430
14558
  if (total >= MAX_NODES) {
14431
14559
  degradedNotes.push(
14432
- `\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`
14560
+ `\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`
14433
14561
  );
14434
14562
  } else if (pct >= 90) {
14435
14563
  degradedNotes.push(
14436
- `\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`
14564
+ `\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`
14437
14565
  );
14438
14566
  }
14439
14567
  } catch {
@@ -14623,7 +14751,7 @@ function getBrainRuleStore() {
14623
14751
  return new BrainRuleStore();
14624
14752
  }
14625
14753
  function getBrainSkillManager() {
14626
- const dir = resolveAssetDir(__dirname9, "skills") ?? join20(__dirname9, "..", "..", "agent_moss", "skills");
14754
+ const dir = resolveAssetDir(__dirname9, "skills") ?? join21(__dirname9, "..", "..", "agent_moss", "skills");
14627
14755
  return new BrainSkillManager(dir);
14628
14756
  }
14629
14757
  async function brainRulesRoute(c) {
@@ -14743,7 +14871,7 @@ var init_routes = __esm({
14743
14871
  import { Hono } from "hono";
14744
14872
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
14745
14873
  import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
14746
- import { join as join21, dirname as dirname14 } from "path";
14874
+ import { join as join22, dirname as dirname14 } from "path";
14747
14875
  import { fileURLToPath as fileURLToPath11 } from "url";
14748
14876
  function getConsoleToken() {
14749
14877
  return process.env[CONSOLE_TOKEN_ENV] || "";
@@ -14785,7 +14913,7 @@ function createConsoleRouter() {
14785
14913
  console2.use("/api/*", authMiddleware());
14786
14914
  console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
14787
14915
  const serveIndex = (c) => {
14788
- const indexFile = join21(STATIC_DIR, "index.html");
14916
+ const indexFile = join22(STATIC_DIR, "index.html");
14789
14917
  if (existsSync20(indexFile)) {
14790
14918
  return c.html(readFileSync20(indexFile, "utf-8"));
14791
14919
  }
@@ -14982,11 +15110,11 @@ function createConsoleRouter() {
14982
15110
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
14983
15111
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
14984
15112
  }
14985
- const userPath = join21(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
15113
+ const userPath = join22(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14986
15114
  const builtinDir = resolveAssetDir(__dirname10, "skills");
14987
15115
  const candidates = [
14988
15116
  ...isRuntimeConfigDisabled() ? [] : [userPath],
14989
- builtinDir ? join21(builtinDir, `${skillId}.md`) : ""
15117
+ builtinDir ? join22(builtinDir, `${skillId}.md`) : ""
14990
15118
  ].filter(Boolean);
14991
15119
  for (const p of candidates) {
14992
15120
  if (existsSync20(p)) {
@@ -15124,7 +15252,7 @@ var init_router = __esm({
15124
15252
  init_asset_dir();
15125
15253
  init_rules_mode();
15126
15254
  __dirname10 = dirname14(fileURLToPath11(import.meta.url));
15127
- STATIC_DIR = join21(__dirname10, "static");
15255
+ STATIC_DIR = join22(__dirname10, "static");
15128
15256
  CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
15129
15257
  }
15130
15258
  });
@@ -15152,8 +15280,8 @@ import { Hono as Hono2 } from "hono";
15152
15280
  import { cors } from "hono/cors";
15153
15281
  import { logger } from "hono/logger";
15154
15282
  import net from "net";
15155
- import { existsSync as existsSync21, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync9 } from "fs";
15156
- import { dirname as dirname15, join as join22 } from "path";
15283
+ import { existsSync as existsSync21, writeFileSync as writeFileSync8, renameSync as renameSync3, mkdirSync as mkdirSync11 } from "fs";
15284
+ import { dirname as dirname15 } from "path";
15157
15285
  function logDeploymentSelfCheck() {
15158
15286
  try {
15159
15287
  const mode = getRulesMode();
@@ -15245,7 +15373,7 @@ function createApp() {
15245
15373
  startLoopMonitor();
15246
15374
  const limiter = new RateLimiter(rateLimitQps());
15247
15375
  app.use("*", async (c, next) => {
15248
- const path8 = new URL(c.req.url).pathname;
15376
+ const path9 = new URL(c.req.url).pathname;
15249
15377
  const method = c.req.method.toUpperCase();
15250
15378
  if (method === "OPTIONS") return next();
15251
15379
  const maxBody = maxBodyBytes();
@@ -15259,16 +15387,16 @@ function createApp() {
15259
15387
  if (originCheckEnabled()) {
15260
15388
  const origin = c.req.header("origin") || "";
15261
15389
  if (origin && !originAllowed(origin, c.req.header("host") || "")) {
15262
- console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path8}`);
15390
+ console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path9}`);
15263
15391
  return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
15264
15392
  }
15265
15393
  }
15266
- const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path8);
15267
- const isPublicPage = !path8.startsWith("/console/api") && (path8 === "/console" || path8.startsWith("/console/"));
15394
+ const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path9);
15395
+ const isPublicPage = !path9.startsWith("/console/api") && (path9 === "/console" || path9.startsWith("/console/"));
15268
15396
  if (!okAuth && !isPublicPage) {
15269
15397
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
15270
15398
  }
15271
- if (limiter.enabled && path8.startsWith("/api/")) {
15399
+ if (limiter.enabled && path9.startsWith("/api/")) {
15272
15400
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
15273
15401
  if (!limiter.allow(key)) {
15274
15402
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
@@ -15302,7 +15430,7 @@ function createApp() {
15302
15430
  return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
15303
15431
  }
15304
15432
  }
15305
- const pool = poolOf(path8);
15433
+ const pool = poolOf(path9);
15306
15434
  if (!take(`pool:${pool}`, poolLimit(pool))) {
15307
15435
  const qkey = principal ? "p:" + principalHash(principal) : "c:local";
15308
15436
  const [qn, abusive] = noteQueueReject(qkey);
@@ -15396,17 +15524,20 @@ async function warmUpEngine() {
15396
15524
  }
15397
15525
  function writePortFile(port) {
15398
15526
  try {
15399
- const path8 = join22(getDataRoot(), "agent_moss_server.port.json");
15400
- mkdirSync9(dirname15(path8), { recursive: true });
15527
+ const path9 = getPortFilePath();
15528
+ mkdirSync11(dirname15(path9), { recursive: true });
15401
15529
  const payload = JSON.stringify({
15402
15530
  port,
15403
15531
  pid: process.pid,
15532
+ // instance/version 供调用方校验,避免同机多实例端口文件串台
15533
+ instance: getInstance(),
15534
+ version,
15404
15535
  started_at: (/* @__PURE__ */ new Date()).toISOString()
15405
15536
  });
15406
- const tmp = `${path8}.tmp`;
15407
- writeFileSync7(tmp, payload, "utf-8");
15408
- renameSync3(tmp, path8);
15409
- console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path8} (port=${port})`);
15537
+ const tmp = `${path9}.tmp`;
15538
+ writeFileSync8(tmp, payload, "utf-8");
15539
+ renameSync3(tmp, path9);
15540
+ console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path9} (port=${port})`);
15410
15541
  } catch (err) {
15411
15542
  console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
15412
15543
  }
@@ -15447,12 +15578,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15447
15578
  },
15448
15579
  serve: async () => {
15449
15580
  failFastOnAuthError();
15450
- const { mkdirSync: mkdirSync11, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15581
+ const { mkdirSync: mkdirSync13, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15451
15582
  const { dirname: dirname17 } = await import("path");
15452
15583
  const dir = dirname17(socketPath);
15453
15584
  if (dir) {
15454
15585
  try {
15455
- mkdirSync11(dir, { recursive: true });
15586
+ mkdirSync13(dir, { recursive: true });
15456
15587
  } catch {
15457
15588
  }
15458
15589
  }
@@ -15513,6 +15644,7 @@ var init_server = __esm({
15513
15644
  init_rules_contract();
15514
15645
  init_security_policy();
15515
15646
  init_paths();
15647
+ init_package_json();
15516
15648
  init_routes();
15517
15649
  init_console();
15518
15650
  init_runtime_config();
@@ -15585,18 +15717,18 @@ __export(rules_tools_exports, {
15585
15717
  rulesStatusText: () => rulesStatusText,
15586
15718
  templateSourceDir: () => templateSourceDir
15587
15719
  });
15588
- import { existsSync as existsSync22, mkdirSync as mkdirSync10, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync8 } from "fs";
15589
- import { dirname as dirname16, join as join23 } from "path";
15720
+ import { existsSync as existsSync22, mkdirSync as mkdirSync12, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync9 } from "fs";
15721
+ import { dirname as dirname16, join as join24 } from "path";
15590
15722
  import { fileURLToPath as fileURLToPath12 } from "url";
15591
15723
  function initRulesDir(targetDir, opts = {}) {
15592
- mkdirSync10(targetDir, { recursive: true });
15724
+ mkdirSync12(targetDir, { recursive: true });
15593
15725
  const written = [];
15594
- const extraPath = join23(targetDir, EXTRA_FILENAME);
15726
+ const extraPath = join24(targetDir, EXTRA_FILENAME);
15595
15727
  if (opts.force || !existsSync22(extraPath)) {
15596
- writeFileSync8(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
15728
+ writeFileSync9(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
15597
15729
  written.push(extraPath);
15598
15730
  }
15599
- const samplePath = join23(targetDir, OVERRIDE_FILENAME);
15731
+ const samplePath = join24(targetDir, OVERRIDE_FILENAME);
15600
15732
  if (opts.force || !existsSync22(samplePath)) {
15601
15733
  let payload = OVERRIDE_TEMPLATE;
15602
15734
  if (opts.withBuiltin) {
@@ -15612,19 +15744,19 @@ function initRulesDir(targetDir, opts = {}) {
15612
15744
  payload = { _\u8BF4\u660E: OVERRIDE_BUILTIN_NOTE };
15613
15745
  for (const k of L1_KEYS) payload[k] = data[k] || [];
15614
15746
  }
15615
- writeFileSync8(samplePath, JSON.stringify(payload, null, 2), "utf-8");
15747
+ writeFileSync9(samplePath, JSON.stringify(payload, null, 2), "utf-8");
15616
15748
  written.push(samplePath);
15617
15749
  }
15618
- const readmeSrc = join23(templateSourceDir(), "README.md");
15619
- const readmeDst = join23(targetDir, "README.md");
15750
+ const readmeSrc = join24(templateSourceDir(), "README.md");
15751
+ const readmeDst = join24(targetDir, "README.md");
15620
15752
  if (existsSync22(readmeSrc) && (opts.force || !existsSync22(readmeDst))) {
15621
- writeFileSync8(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
15753
+ writeFileSync9(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
15622
15754
  written.push(readmeDst);
15623
15755
  }
15624
15756
  return written;
15625
15757
  }
15626
15758
  function templateSourceDir() {
15627
- const cands = [join23(__dirname11, "data", "rules_template"), join23(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
15759
+ const cands = [join24(__dirname11, "data", "rules_template"), join24(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
15628
15760
  for (const c of cands) if (existsSync22(c)) return c;
15629
15761
  return cands[0];
15630
15762
  }
@@ -15633,7 +15765,7 @@ function templateFiles(dirs) {
15633
15765
  for (const d of dirs) {
15634
15766
  try {
15635
15767
  for (const name of readdirSync7(d)) {
15636
- if (name.endsWith(".json.\u793A\u4F8B")) out.push(join23(d, name));
15768
+ if (name.endsWith(".json.\u793A\u4F8B")) out.push(join24(d, name));
15637
15769
  }
15638
15770
  } catch {
15639
15771
  }
@@ -15817,7 +15949,7 @@ async function main() {
15817
15949
  case "init": {
15818
15950
  const flagIdx = args.findIndex((a) => a === "--output" || a === "-o");
15819
15951
  const output = (flagIdx >= 0 ? args[flagIdx + 1] : void 0) || args.slice(1).find((a) => !a.startsWith("-")) || "input.json";
15820
- const fs8 = await import("fs");
15952
+ const fs9 = await import("fs");
15821
15953
  const template = {
15822
15954
  session_id: "my-session-001",
15823
15955
  prompt_session: "Read /var/log/app.log and analyze errors",
@@ -15827,7 +15959,7 @@ async function main() {
15827
15959
  os_type: "",
15828
15960
  cwd: "/home/user/project"
15829
15961
  };
15830
- fs8.writeFileSync(output, JSON.stringify(template, null, 2), "utf-8");
15962
+ fs9.writeFileSync(output, JSON.stringify(template, null, 2), "utf-8");
15831
15963
  console.log(`Template written to ${output}`);
15832
15964
  break;
15833
15965
  }
@@ -15837,13 +15969,13 @@ async function main() {
15837
15969
  console.error('Usage: agent-moss analyze <input.json | "shell command">');
15838
15970
  process.exit(1);
15839
15971
  }
15840
- const fs8 = await import("fs");
15841
- const path8 = await import("path");
15972
+ const fs9 = await import("fs");
15973
+ const path9 = await import("path");
15842
15974
  const useJson = args.includes("--json");
15843
15975
  const osType = process.platform === "win32" ? "windows" : "linux";
15844
- const isFile = fs8.existsSync(target) && fs8.statSync(target).isFile();
15976
+ const isFile = fs9.existsSync(target) && fs9.statSync(target).isFile();
15845
15977
  if (!isFile) {
15846
- if (fs8.existsSync(target)) {
15978
+ if (fs9.existsSync(target)) {
15847
15979
  console.error(`\u9519\u8BEF: \u4E0D\u662F\u6587\u4EF6: ${target}`);
15848
15980
  process.exit(2);
15849
15981
  }
@@ -15857,8 +15989,8 @@ async function main() {
15857
15989
  }
15858
15990
  process.exit(await analyzeRawCommand(target, useJson));
15859
15991
  }
15860
- const filePath = path8.resolve(target);
15861
- const data = JSON.parse(fs8.readFileSync(filePath, "utf-8"));
15992
+ const filePath = path9.resolve(target);
15993
+ const data = JSON.parse(fs9.readFileSync(filePath, "utf-8"));
15862
15994
  const { analyze: analyze2 } = await Promise.resolve().then(() => (init_analyzer(), analyzer_exports));
15863
15995
  const sessionId = String(data.session_id || "unknown");
15864
15996
  const result = await analyze2(buildAnalysisInputFromFile(data));
@@ -15866,15 +15998,15 @@ async function main() {
15866
15998
  if (!args.includes("--no-file")) {
15867
15999
  const outDirIdx = args.findIndex((a) => a === "--output-dir" || a === "-o");
15868
16000
  const outDir = outDirIdx >= 0 && args[outDirIdx + 1] ? args[outDirIdx + 1] : process.cwd();
15869
- fs8.mkdirSync(outDir, { recursive: true });
16001
+ fs9.mkdirSync(outDir, { recursive: true });
15870
16002
  const safeSession = sessionId.replace(/\//g, "_");
15871
16003
  if (result.decision === "Allow") {
15872
- const policyPath = path8.join(outDir, `${safeSession}_policy.toml`);
15873
- fs8.writeFileSync(policyPath, result.policy || "", "utf-8");
16004
+ const policyPath = path9.join(outDir, `${safeSession}_policy.toml`);
16005
+ fs9.writeFileSync(policyPath, result.policy || "", "utf-8");
15874
16006
  console.log(`Policy written to ${policyPath}`);
15875
16007
  } else {
15876
- const denyPath = path8.join(outDir, `${safeSession}_deny_reason.txt`);
15877
- fs8.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
16008
+ const denyPath = path9.join(outDir, `${safeSession}_deny_reason.txt`);
16009
+ fs9.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
15878
16010
  console.log(`Deny reason written to ${denyPath}`);
15879
16011
  }
15880
16012
  }
@@ -15963,8 +16095,8 @@ async function main() {
15963
16095
  case "install": {
15964
16096
  const enable = args.includes("--enable");
15965
16097
  const { execSync } = await import("child_process");
15966
- const fs8 = await import("fs");
15967
- const path8 = await import("path");
16098
+ const fs9 = await import("fs");
16099
+ const path9 = await import("path");
15968
16100
  const { fileURLToPath: fileURLToPath14 } = await import("url");
15969
16101
  if (process.getuid?.() !== 0) {
15970
16102
  try {
@@ -15981,22 +16113,22 @@ async function main() {
15981
16113
  process.exit(0);
15982
16114
  }
15983
16115
  const __filename7 = fileURLToPath14(import.meta.url);
15984
- const __dirname12 = path8.dirname(__filename7);
15985
- let srcPath = path8.join(__dirname12, "data", "agent_moss.service");
15986
- if (!fs8.existsSync(srcPath)) {
15987
- srcPath = path8.join(__dirname12, "..", "src", "data", "agent_moss.service");
16116
+ const __dirname12 = path9.dirname(__filename7);
16117
+ let srcPath = path9.join(__dirname12, "data", "agent_moss.service");
16118
+ if (!fs9.existsSync(srcPath)) {
16119
+ srcPath = path9.join(__dirname12, "..", "src", "data", "agent_moss.service");
15988
16120
  }
15989
- if (!fs8.existsSync(srcPath)) {
16121
+ if (!fs9.existsSync(srcPath)) {
15990
16122
  console.error("\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230 agent_moss.service \u6A21\u677F\u6587\u4EF6");
15991
16123
  process.exit(1);
15992
16124
  }
15993
16125
  const which = execSync("which agent-moss 2>/dev/null || true", { encoding: "utf-8" }).trim();
15994
- const binPath = which || `${process.execPath} ${path8.join(__dirname12, "cli.js")}`;
15995
- let content = fs8.readFileSync(srcPath, "utf-8");
16126
+ const binPath = which || `${process.execPath} ${path9.join(__dirname12, "cli.js")}`;
16127
+ let content = fs9.readFileSync(srcPath, "utf-8");
15996
16128
  content = content.replace("__AGENT_MOSS_BIN__", binPath);
15997
16129
  const dst = "/etc/systemd/system/agent-moss.service";
15998
- fs8.writeFileSync(dst, content, "utf-8");
15999
- fs8.chmodSync(dst, 420);
16130
+ fs9.writeFileSync(dst, content, "utf-8");
16131
+ fs9.chmodSync(dst, 420);
16000
16132
  console.log(`\u2705 \u5DF2\u5B89\u88C5 systemd service: ${dst}`);
16001
16133
  execSync("systemctl daemon-reload", { stdio: "inherit" });
16002
16134
  console.log("\u2705 systemctl daemon-reload \u5B8C\u6210");