@kenhkl/agent-moss 0.17.34 → 0.17.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -409,22 +409,22 @@ function loadToolRegistry() {
409
409
  data.tools = tools;
410
410
  return data;
411
411
  }
412
- function scanStructEntry(cat, value, path8) {
412
+ function scanStructEntry(cat, value, path9) {
413
413
  if (cat === "skills") {
414
414
  if (!value || typeof value !== "object" || Array.isArray(value)) {
415
- 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`);
416
416
  return null;
417
417
  }
418
418
  const out = {};
419
419
  for (const [skCat, skills] of Object.entries(value)) {
420
420
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
421
- 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`);
422
422
  continue;
423
423
  }
424
424
  const keep = {};
425
425
  for (const [name, kws] of Object.entries(skills)) {
426
426
  if (Array.isArray(kws)) keep[name] = kws;
427
- 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`);
428
428
  }
429
429
  if (Object.keys(keep).length > 0) out[skCat] = keep;
430
430
  }
@@ -432,37 +432,37 @@ function scanStructEntry(cat, value, path8) {
432
432
  }
433
433
  if (cat === "ltl_rules") {
434
434
  if (!Array.isArray(value)) {
435
- 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`);
436
436
  return null;
437
437
  }
438
438
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
439
439
  if (keep.length !== value.length) {
440
- 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`);
441
441
  }
442
442
  return keep.length > 0 ? keep : null;
443
443
  }
444
444
  if (cat === "tools") {
445
445
  if (!value || typeof value !== "object" || Array.isArray(value)) {
446
- 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`);
447
447
  return null;
448
448
  }
449
449
  const keep = {};
450
450
  for (const [k, v] of Object.entries(value)) {
451
451
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
452
- 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`);
453
453
  }
454
454
  return Object.keys(keep).length > 0 ? keep : null;
455
455
  }
456
456
  return null;
457
457
  }
458
- function scanRulesFile(path8, kind) {
458
+ function scanRulesFile(path9, kind) {
459
459
  const out = {};
460
460
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
461
461
  let parsed;
462
462
  try {
463
- parsed = JSON.parse(readFileSync2(path8, "utf-8"));
463
+ parsed = JSON.parse(readFileSync2(path9, "utf-8"));
464
464
  } catch (e) {
465
- 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}`);
466
466
  return out;
467
467
  }
468
468
  const classifyFlat = (r) => {
@@ -486,44 +486,44 @@ function scanRulesFile(path8, kind) {
486
486
  }
487
487
  if (flatBad > 0) {
488
488
  console.warn(
489
- `[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`
490
490
  );
491
491
  }
492
492
  } else {
493
- 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`);
494
494
  return out;
495
495
  }
496
496
  for (const [cat, rules] of pairs) {
497
497
  if (String(cat).startsWith("_")) continue;
498
498
  if (STRUCT_KEYS.includes(cat)) {
499
- const got = scanStructEntry(cat, rules, path8);
499
+ const got = scanStructEntry(cat, rules, path9);
500
500
  if (got !== null) out[cat] = got;
501
501
  continue;
502
502
  }
503
503
  const required = EXTRA_CATEGORIES[cat];
504
504
  if (!required) {
505
505
  console.warn(
506
- `[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`
507
507
  );
508
508
  continue;
509
509
  }
510
510
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
511
511
  console.error(
512
- `[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
513
513
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
514
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`
515
515
  );
516
516
  continue;
517
517
  }
518
518
  if (!Array.isArray(rules)) {
519
- 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`);
520
520
  continue;
521
521
  }
522
522
  const items = [];
523
523
  for (const r of rules) {
524
524
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
525
525
  console.warn(
526
- `[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`
527
527
  );
528
528
  continue;
529
529
  }
@@ -533,7 +533,7 @@ function scanRulesFile(path8, kind) {
533
533
  }
534
534
  if (Object.keys(out).length > 0) {
535
535
  console.info(
536
- `[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(", ")
537
537
  );
538
538
  }
539
539
  return out;
@@ -951,44 +951,51 @@ function readFdToken() {
951
951
  fdTokenCache.set(fd, tok);
952
952
  return tok;
953
953
  }
954
- function readExplicitToken() {
954
+ function readExplicitTokenResult() {
955
955
  const tok = env("AGENT_MOSS_AUTH_TOKEN");
956
- if (tok) return tok;
956
+ if (tok) return [tok, ""];
957
957
  const fdTok = readFdToken();
958
- if (fdTok) return fdTok;
959
- const path8 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
960
- if (path8) {
958
+ if (fdTok) return [fdTok, ""];
959
+ const path9 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
960
+ if (path9) {
961
961
  try {
962
- return readFileSync4(path8, "utf-8").trim();
963
- } catch {
964
- 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`];
965
969
  }
966
970
  }
967
- return "";
971
+ return ["", ""];
968
972
  }
969
973
  function ensureAutoToken() {
970
- const path8 = autoTokenPath();
974
+ const path9 = autoTokenPath();
971
975
  try {
972
- if (existsSync3(path8) && !lstatSync(path8).isSymbolicLink()) {
973
- const tok2 = readFileSync4(path8, "utf-8").trim();
976
+ if (existsSync3(path9) && !lstatSync(path9).isSymbolicLink()) {
977
+ const tok2 = readFileSync4(path9, "utf-8").trim();
974
978
  if (tok2) {
975
979
  try {
976
- chmodSync(path8, 384);
980
+ chmodSync(path9, 384);
977
981
  } catch {
978
982
  }
979
983
  return tok2;
980
984
  }
981
985
  }
982
986
  const tok = randomBytes(32).toString("base64url");
983
- ensurePrivateDir(dirname2(path8));
984
- 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
+ }
985
993
  console.warn(
986
- `[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`
987
995
  );
988
996
  return tok;
989
997
  } catch (e) {
990
- console.error("[AgentMoss] \u751F\u6210\u8BBF\u95EE token \u5931\u8D25\uFF08\u672C\u6B21\u8FD0\u884C\u5C06\u4E0D\u9274\u6743\uFF09:", e);
991
- return "";
998
+ throw new Error(`\u81EA\u52A8\u8BBF\u95EE token \u751F\u6210/\u8BFB\u53D6\u5931\u8D25\uFF08${path9}\uFF09\uFF1A${e?.message ?? e}`);
992
999
  }
993
1000
  }
994
1001
  function parseAgentTokens(raw) {
@@ -1017,12 +1024,22 @@ function resolveAuth() {
1017
1024
  return [tokenCache.token, tokenCache.agents, tokenCache.error];
1018
1025
  }
1019
1026
  let error = "";
1020
- let token = readExplicitToken();
1021
- 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) {
1022
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";
1023
1033
  console.error(`[agent-moss] ${error}`);
1024
1034
  }
1025
- 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
+ }
1026
1043
  const agents = parseAgentTokens(rawAgents);
1027
1044
  tokenCache = { key, token, agents, error };
1028
1045
  return [token, agents, error];
@@ -1042,8 +1059,8 @@ function failFastOnAuthError() {
1042
1059
  }
1043
1060
  function authEnabled() {
1044
1061
  if (authMode() === AUTH_MODE_OFF) return false;
1045
- const [tok, agents] = resolveAuth();
1046
- 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;
1047
1064
  }
1048
1065
  function bearer(headers) {
1049
1066
  const get = (k) => headers instanceof Headers ? headers.get(k) ?? "" : headers[k] ?? "";
@@ -1056,16 +1073,16 @@ function constEq(a, b) {
1056
1073
  if (ba.length !== bb.length) return false;
1057
1074
  return timingSafeEqual(ba, bb);
1058
1075
  }
1059
- function checkRequestAuth(headers, path8) {
1076
+ function checkRequestAuth(headers, path9) {
1060
1077
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
1061
- const isHealth = HEALTH_PATHS.includes(path8.replace(/\/+$/, ""));
1078
+ const isHealth = HEALTH_PATHS.includes(path9.replace(/\/+$/, ""));
1062
1079
  const [gt0, agents, err] = resolveAuth();
1063
1080
  if (err) return isHealth ? [true, ""] : [false, ""];
1064
1081
  if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
1065
1082
  if (isHealth) return [true, ""];
1066
1083
  const tok = bearer(headers);
1067
1084
  if (!tok) return [false, ""];
1068
- if (path8.startsWith("/console/api")) {
1085
+ if (path9.startsWith("/console/api")) {
1069
1086
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
1070
1087
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
1071
1088
  }
@@ -1084,8 +1101,8 @@ function bindAgent(principal, agentId) {
1084
1101
  if (!agentId) return [true, bound];
1085
1102
  return [bound === agentId, bound];
1086
1103
  }
1087
- function principalOf(headers, path8 = "") {
1088
- const [ok, principal] = checkRequestAuth(headers, path8);
1104
+ function principalOf(headers, path9 = "") {
1105
+ const [ok, principal] = checkRequestAuth(headers, path9);
1089
1106
  return ok ? principal : "";
1090
1107
  }
1091
1108
  function principalHash(principal) {
@@ -1342,11 +1359,11 @@ function errorDetailMode() {
1342
1359
  function maxBodyBytes() {
1343
1360
  return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
1344
1361
  }
1345
- function poolOf(path8) {
1346
- if (path8 === "/api/v1/analyze" || path8.startsWith("/api/v1/analyze/")) return "biz";
1347
- if (path8 === "/api/v1/review" || path8.startsWith("/api/v1/review/")) return "review";
1348
- if (path8 === "/console" || path8.startsWith("/console/") || path8.startsWith("/api/v1/brain")) return "ops";
1349
- 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";
1350
1367
  return "other";
1351
1368
  }
1352
1369
  function poolLimit(name) {
@@ -1831,7 +1848,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
1831
1848
  os: String(sp.os || "linux").toLowerCase()
1832
1849
  }));
1833
1850
  }
1834
- function _scopeOf(os5, path8) {
1851
+ function _scopeOf(os6, path9) {
1835
1852
  if (!_scopeIndex) {
1836
1853
  _scopeIndex = /* @__PURE__ */ new Map();
1837
1854
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -1839,7 +1856,7 @@ function _scopeOf(os5, path8) {
1839
1856
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
1840
1857
  }
1841
1858
  }
1842
- return _scopeIndex.get(`${String(os5 || "linux").toLowerCase()}|${path8}`) || "root";
1859
+ return _scopeIndex.get(`${String(os6 || "linux").toLowerCase()}|${path9}`) || "root";
1843
1860
  }
1844
1861
  function getSensitivePathsForOs(osType) {
1845
1862
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -2558,36 +2575,36 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
2558
2575
  }
2559
2576
  const preciseEdit = isPreciseEditTool(actionType);
2560
2577
  const unreadPaths = [];
2561
- for (const path8 of checkTargets) {
2562
- if (isDirectoryTarget(path8)) continue;
2578
+ for (const path9 of checkTargets) {
2579
+ if (isDirectoryTarget(path9)) continue;
2563
2580
  let isFullRead = [...normalizedFullReads].some(
2564
- (rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
2581
+ (rp) => pathIsSameOrUnder(path9, rp) || pathIsSameOrUnder(rp, path9)
2565
2582
  );
2566
2583
  if (!isFullRead && preciseEdit && [...normalizedWrittenPaths].some(
2567
- (wp) => pathIsSameOrUnder(path8, wp) || pathIsSameOrUnder(wp, path8)
2584
+ (wp) => pathIsSameOrUnder(path9, wp) || pathIsSameOrUnder(wp, path9)
2568
2585
  )) {
2569
2586
  isFullRead = true;
2570
2587
  }
2571
- if (!isFullRead && !isProtectedWritePath(path8) && isScriptGeneratedTarget(path8, historyWrittenScripts, shellRunActions)) {
2588
+ if (!isFullRead && !isProtectedWritePath(path9) && isScriptGeneratedTarget(path9, historyWrittenScripts, shellRunActions)) {
2572
2589
  isFullRead = true;
2573
2590
  }
2574
2591
  let isPartialCovered = false;
2575
2592
  if (!isFullRead) {
2576
2593
  for (const [pp, upto] of normalizedPartialReads) {
2577
- if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
2578
- if (preciseEdit || upto != null && fileHasAtMostLines(path8, upto)) {
2594
+ if (!(pathIsSameOrUnder(path9, pp) || pathIsSameOrUnder(pp, path9))) continue;
2595
+ if (preciseEdit || upto != null && fileHasAtMostLines(path9, upto)) {
2579
2596
  isPartialCovered = true;
2580
2597
  break;
2581
2598
  }
2582
2599
  }
2583
2600
  }
2584
2601
  if (!isFullRead && !isPartialCovered) {
2585
- let isCreate = !fs.existsSync(path8);
2602
+ let isCreate = !fs.existsSync(path9);
2586
2603
  if (!isCreate) {
2587
2604
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
2588
2605
  }
2589
2606
  if (!isCreate) {
2590
- unreadPaths.push(path8);
2607
+ unreadPaths.push(path9);
2591
2608
  }
2592
2609
  }
2593
2610
  }
@@ -2781,16 +2798,16 @@ var init_logic_rules = __esm({
2781
2798
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
2782
2799
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
2783
2800
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
2784
- 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 }));
2785
2802
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
2786
2803
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
2787
- 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 }));
2788
2805
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
2789
2806
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
2790
- 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 }));
2791
2808
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
2792
2809
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
2793
- 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 }));
2794
2811
  _scopeIndex = null;
2795
2812
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
2796
2813
  "ask_user_question",
@@ -3266,8 +3283,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
3266
3283
  function _filterRulesByOs(rules, osType) {
3267
3284
  const accepted = acceptedOsValues(osType);
3268
3285
  return rules.filter((r) => {
3269
- const os5 = String(r.os || "linux").toLowerCase();
3270
- return os5 === "all" || accepted.includes(os5);
3286
+ const os6 = String(r.os || "linux").toLowerCase();
3287
+ return os6 === "all" || accepted.includes(os6);
3271
3288
  });
3272
3289
  }
3273
3290
  function _userCustomRules(runtime, layers, requiredKey) {
@@ -3469,7 +3486,7 @@ function _l2SensitivePathsToRules() {
3469
3486
  const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
3470
3487
  const all = [...root, ...home, ...credential];
3471
3488
  for (const sp of all) {
3472
- const os5 = String(sp.os || "linux").toLowerCase();
3489
+ const os6 = String(sp.os || "linux").toLowerCase();
3473
3490
  const denyMode = sp.denyMode || _deriveDenyMode({
3474
3491
  deny_mode: sp.deny_mode,
3475
3492
  credential: sp.credential,
@@ -3479,7 +3496,7 @@ function _l2SensitivePathsToRules() {
3479
3496
  // id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
3480
3497
  // hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
3481
3498
  // Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
3482
- id: `path_${os5}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3499
+ id: `path_${os6}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3483
3500
  path: sp.path,
3484
3501
  risk_level: sp.riskLevel,
3485
3502
  desc: sp.desc,
@@ -3488,7 +3505,7 @@ function _l2SensitivePathsToRules() {
3488
3505
  skip_l3_on_disabled: true,
3489
3506
  enabled: true,
3490
3507
  builtin: true,
3491
- os: os5
3508
+ os: os6
3492
3509
  };
3493
3510
  _syncDenyModeFields(rule);
3494
3511
  if (sp.dirDelOnly) rule.dir_del_only = true;
@@ -4026,8 +4043,8 @@ function _filterDefaultsByOs(rules, osType) {
4026
4043
  const accepted = acceptedOsValues(osType);
4027
4044
  return rules.filter((r) => {
4028
4045
  if (!r.os) return true;
4029
- const os5 = String(r.os).toLowerCase();
4030
- return os5 === "all" || accepted.includes(os5);
4046
+ const os6 = String(r.os).toLowerCase();
4047
+ return os6 === "all" || accepted.includes(os6);
4031
4048
  });
4032
4049
  }
4033
4050
  function _hasRulesForOs(rules, osType) {
@@ -5069,24 +5086,24 @@ function extractWritePayload(actionType, actionDetailRaw) {
5069
5086
  const detail = actionDetailRaw || "";
5070
5087
  const m = detail.match(WRITE_PREFIX_RE);
5071
5088
  if (m) {
5072
- const path8 = m[1];
5089
+ const path9 = m[1];
5073
5090
  let content = m[2] || "";
5074
- if (!path8 || path8 === "?" || path8 === "-" || !content.trim()) return null;
5091
+ if (!path9 || path9 === "?" || path9 === "-" || !content.trim()) return null;
5075
5092
  if ((actionType || "").toLowerCase().includes("editfile")) {
5076
5093
  const nm = content.match(EDIT_NEW_RE);
5077
5094
  if (nm) content = nm[1];
5078
5095
  }
5079
- return { path: path8, content };
5096
+ return { path: path9, content };
5080
5097
  }
5081
5098
  const stripped = detail.trim();
5082
5099
  if (stripped.startsWith("{")) {
5083
5100
  try {
5084
5101
  const obj = JSON.parse(stripped);
5085
5102
  if (obj && typeof obj === "object") {
5086
- const path8 = obj.path || obj.file_path || obj.filePath;
5103
+ const path9 = obj.path || obj.file_path || obj.filePath;
5087
5104
  const content = obj.content || obj.newString || obj.new_string;
5088
- if (typeof path8 === "string" && path8 !== "" && path8 !== "?" && path8 !== "-" && typeof content === "string" && content.trim()) {
5089
- return { path: path8, content };
5105
+ if (typeof path9 === "string" && path9 !== "" && path9 !== "?" && path9 !== "-" && typeof content === "string" && content.trim()) {
5106
+ return { path: path9, content };
5090
5107
  }
5091
5108
  }
5092
5109
  } catch {
@@ -5099,8 +5116,8 @@ function handlesWrittenContent(actionType, actionDetailRaw) {
5099
5116
  if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
5100
5117
  return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
5101
5118
  }
5102
- function detectLanguage(path8, content) {
5103
- 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();
5104
5121
  if (SHELL_EXTS.has(ext)) return "shell";
5105
5122
  if (PY_EXTS.has(ext)) return "python";
5106
5123
  if (DATA_EXTS.has(ext)) return "data";
@@ -5258,8 +5275,8 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
5258
5275
  if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
5259
5276
  const payload = extractWritePayload(actionType, actionDetailRaw);
5260
5277
  if (!payload) return [];
5261
- const { path: path8, content: rawContent } = payload;
5262
- const language = detectLanguage(path8, rawContent);
5278
+ const { path: path9, content: rawContent } = payload;
5279
+ const language = detectLanguage(path9, rawContent);
5263
5280
  if (language === "data") return [];
5264
5281
  let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
5265
5282
  const started = Date.now();
@@ -5753,16 +5770,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5753
5770
  if (String(osType || "").toLowerCase() === "windows") {
5754
5771
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
5755
5772
  }
5756
- const pathMatches = (text, path8) => {
5757
- const parts = path8.split(/(\(\?!.*?\))/);
5773
+ const pathMatches = (text, path9) => {
5774
+ const parts = path9.split(/(\(\?!.*?\))/);
5758
5775
  const escaped = parts.map((part) => {
5759
5776
  if (part.startsWith("(?!")) return part;
5760
5777
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5761
5778
  }).join("");
5762
- 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");
5763
5780
  return re.test(text);
5764
5781
  };
5765
- const pathMatchesAny = (path8) => pathScanTexts.some((t) => pathMatches(t, path8));
5782
+ const pathMatchesAny = (path9) => pathScanTexts.some((t) => pathMatches(t, path9));
5766
5783
  for (const sp of rootPaths) {
5767
5784
  if (pathMatchesAny(sp.path.toLowerCase())) {
5768
5785
  if (keygenGenerate) continue;
@@ -5905,8 +5922,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5905
5922
  }
5906
5923
  return null;
5907
5924
  }
5908
- function isHomeValue(path8) {
5909
- let p = path8.trim().toLowerCase();
5925
+ function isHomeValue(path9) {
5926
+ let p = path9.trim().toLowerCase();
5910
5927
  if (p.startsWith("$(") && p.endsWith(")")) {
5911
5928
  const inner = p.slice(2, -1).trim();
5912
5929
  return HOME_TARGET_RE.test(" " + inner);
@@ -5962,15 +5979,15 @@ function checkHomeDeletion(actionType, actionDetail) {
5962
5979
  }
5963
5980
  const assigned = {};
5964
5981
  for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
5965
- for (const [varName, path8] of Object.entries(assigned)) {
5966
- if (!isHomeValue(path8)) continue;
5982
+ for (const [varName, path9] of Object.entries(assigned)) {
5983
+ if (!isHomeValue(path9)) continue;
5967
5984
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
5968
5985
  for (const seg of segs) {
5969
5986
  if (!isDeleteCommand(seg)) continue;
5970
5987
  if (varRefRe.test(seg)) {
5971
5988
  return {
5972
5989
  allowed: false,
5973
- 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`,
5974
5991
  riskLevel: "high",
5975
5992
  riskType: "script_execution",
5976
5993
  confidence: 90,
@@ -6778,15 +6795,15 @@ function parseShellString(s) {
6778
6795
  let m;
6779
6796
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
6780
6797
  const interp = m[1];
6781
- const path8 = m[2].trim();
6798
+ const path9 = m[2].trim();
6782
6799
  let rest = m[3].trim();
6783
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6800
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
6784
6801
  rest = rest.split(/[;|&<>]/)[0].trim();
6785
6802
  const args = [];
6786
6803
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6787
6804
  args.push(tm[1] ? tm[2] : tm[3]);
6788
6805
  }
6789
- return { path: path8, args, interpreter: interp };
6806
+ return { path: path9, args, interpreter: interp };
6790
6807
  }
6791
6808
  return null;
6792
6809
  }
@@ -6832,9 +6849,9 @@ function extractCallsFromTree(tree, reachableLines) {
6832
6849
  }
6833
6850
  if (allStr && elts.length >= 2) {
6834
6851
  const interp = elts[0];
6835
- const path8 = elts[1];
6836
- if (!path8.startsWith("-") && !path8.startsWith("$") && !path8.includes("/dev/")) {
6837
- 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 });
6838
6855
  return true;
6839
6856
  }
6840
6857
  }
@@ -6874,15 +6891,15 @@ function extractCallsRegex(content) {
6874
6891
  let m;
6875
6892
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
6876
6893
  const interp = m[1];
6877
- const path8 = m[2].trim();
6894
+ const path9 = m[2].trim();
6878
6895
  let rest = m[3].trim();
6879
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6896
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
6880
6897
  rest = rest.split(/[;|&<>]/)[0].trim();
6881
6898
  const args = [];
6882
6899
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6883
6900
  args.push(tm[1] ? tm[2] : tm[3]);
6884
6901
  }
6885
- calls.push({ path: path8, args, interpreter: interp });
6902
+ calls.push({ path: path9, args, interpreter: interp });
6886
6903
  }
6887
6904
  return calls;
6888
6905
  }
@@ -7676,15 +7693,15 @@ function extractCallsFromContent(content) {
7676
7693
  CHILD_CALL_RE2.lastIndex = 0;
7677
7694
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
7678
7695
  const interp = m[1];
7679
- const path8 = m[2].trim();
7696
+ const path9 = m[2].trim();
7680
7697
  let rest = m[3].trim();
7681
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
7698
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
7682
7699
  rest = rest.split(/[;|&<>]/)[0].trim();
7683
7700
  const args = [];
7684
7701
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
7685
7702
  args.push(tm[1] ? tm[2] : tm[3]);
7686
7703
  }
7687
- calls.push({ path: path8, args, interpreter: interp });
7704
+ calls.push({ path: path9, args, interpreter: interp });
7688
7705
  }
7689
7706
  return calls;
7690
7707
  }
@@ -9323,6 +9340,28 @@ function formatHints(previous) {
9323
9340
  }
9324
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";
9325
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
+ }
9326
9365
  async function analyzeWithLLM(prompt, config) {
9327
9366
  console.log(`[AgentMoss] LLM analyzing with model: ${config.model}, url: ${config.baseUrl}`);
9328
9367
  const _llmStart = performance.now();
@@ -9370,6 +9409,7 @@ async function analyzeWithLLM(prompt, config) {
9370
9409
  if (abortController.signal.aborted) {
9371
9410
  break;
9372
9411
  }
9412
+ const attemptStart = performance.now();
9373
9413
  try {
9374
9414
  const response = await client.chat.completions.create({
9375
9415
  model: config.model,
@@ -9485,7 +9525,16 @@ async function analyzeWithLLM(prompt, config) {
9485
9525
  const errObj = err;
9486
9526
  const status = errObj?.status ?? errObj?.statusCode;
9487
9527
  const body = errObj?.error ?? errObj?.body;
9488
- 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
+ )}`;
9489
9538
  if (attempt < maxRetries) {
9490
9539
  console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
9491
9540
  await new Promise((resolve12) => setTimeout(resolve12, retryCfg.retryInterval * 1e3));
@@ -9557,8 +9606,8 @@ var init_rule_store = __esm({
9557
9606
  BrainRuleStore = class {
9558
9607
  path;
9559
9608
  data;
9560
- constructor(path8) {
9561
- this.path = path8 || getRulesPath();
9609
+ constructor(path9) {
9610
+ this.path = path9 || getRulesPath();
9562
9611
  this.data = this.load();
9563
9612
  }
9564
9613
  load() {
@@ -10011,10 +10060,10 @@ ${reason.slice(0, 500)}
10011
10060
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
10012
10061
  let mm;
10013
10062
  while ((mm = pathRe.exec(src)) !== null) {
10014
- const path8 = mm[1];
10015
- if (path8.split("/").length < 3) continue;
10016
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path8)) continue;
10017
- 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);
10018
10067
  if (seen.has(gen)) continue;
10019
10068
  seen.add(gen);
10020
10069
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -10033,8 +10082,8 @@ ${reason.slice(0, 500)}
10033
10082
  }
10034
10083
  return false;
10035
10084
  }
10036
- generalizePath(path8) {
10037
- const p = path8.toLowerCase();
10085
+ generalizePath(path9) {
10086
+ const p = path9.toLowerCase();
10038
10087
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
10039
10088
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
10040
10089
  }
@@ -10422,26 +10471,26 @@ function writeExportFiles(outDir, rules, skills) {
10422
10471
  byLayer.get(r.layer).push(r);
10423
10472
  }
10424
10473
  for (const layer of [...byLayer.keys()].sort((a, b) => a - b)) {
10425
- const path8 = join15(rulesDir2, `l${layer}_brain_rules.json`);
10426
- writeFileSync5(path8, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
10427
- 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);
10428
10477
  }
10429
10478
  if (rules.length === 0) {
10430
- const path8 = join15(rulesDir2, "empty.txt");
10431
- writeFileSync5(path8, "(no brain rules to contribute)", "utf-8");
10432
- written.push(path8);
10479
+ const path9 = join15(rulesDir2, "empty.txt");
10480
+ writeFileSync5(path9, "(no brain rules to contribute)", "utf-8");
10481
+ written.push(path9);
10433
10482
  }
10434
10483
  const skillsDir = join15(outDir, "skills");
10435
10484
  mkdirSync6(skillsDir, { recursive: true });
10436
10485
  for (const sk of skills) {
10437
- const path8 = join15(skillsDir, `${sk.name}.md`);
10438
- writeFileSync5(path8, sk.content || "", "utf-8");
10439
- written.push(path8);
10486
+ const path9 = join15(skillsDir, `${sk.name}.md`);
10487
+ writeFileSync5(path9, sk.content || "", "utf-8");
10488
+ written.push(path9);
10440
10489
  }
10441
10490
  if (skills.length === 0) {
10442
- const path8 = join15(skillsDir, "empty.txt");
10443
- writeFileSync5(path8, "(no brain skills to contribute)", "utf-8");
10444
- written.push(path8);
10491
+ const path9 = join15(skillsDir, "empty.txt");
10492
+ writeFileSync5(path9, "(no brain skills to contribute)", "utf-8");
10493
+ written.push(path9);
10445
10494
  }
10446
10495
  return written;
10447
10496
  }
@@ -11159,12 +11208,12 @@ var init_builder = __esm({
11159
11208
  });
11160
11209
 
11161
11210
  // src/engine/formal-engine/properties.ts
11162
- function graphFromPath(nodes, path8, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
11211
+ function graphFromPath(nodes, path9, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
11163
11212
  const byKey = /* @__PURE__ */ new Map();
11164
11213
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
11165
11214
  const gNodes = [];
11166
11215
  const gEdges = [];
11167
- for (const item of path8) {
11216
+ for (const item of path9) {
11168
11217
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
11169
11218
  gNodes.push({
11170
11219
  session_id: item.sessionId,
@@ -11230,22 +11279,22 @@ function checkCrossSessionChain(graph) {
11230
11279
  if (witness !== void 0) {
11231
11280
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
11232
11281
  let matched = 0;
11233
- const path8 = [];
11282
+ const path9 = [];
11234
11283
  for (let k = 0; k < witness; k++) {
11235
11284
  const n = nodes[k];
11236
11285
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
11237
11286
  matched += 1;
11238
- 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) });
11239
11288
  }
11240
11289
  }
11241
11290
  if (matched < stages.length - 1) continue;
11242
- 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) });
11243
11292
  violations.push({
11244
11293
  propertyId: "cross-" + chain.id,
11245
11294
  reason: chain.reason,
11246
11295
  riskLevel: chain.riskLevel,
11247
- path: path8,
11248
- graph: graphFromPath(nodes, path8, "next", {
11296
+ path: path9,
11297
+ graph: graphFromPath(nodes, path9, "next", {
11249
11298
  property_id: "cross-" + chain.id,
11250
11299
  property_short: "P1",
11251
11300
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -11255,11 +11304,11 @@ function checkCrossSessionChain(graph) {
11255
11304
  } else {
11256
11305
  let matched = 0;
11257
11306
  let stageIdx = 0;
11258
- const path8 = [];
11307
+ const path9 = [];
11259
11308
  for (const n of nodes) {
11260
11309
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
11261
11310
  matched += 1;
11262
- 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) });
11263
11312
  stageIdx += 1;
11264
11313
  if (matched >= stages.length) break;
11265
11314
  }
@@ -11269,8 +11318,8 @@ function checkCrossSessionChain(graph) {
11269
11318
  propertyId: "cross-" + chain.id,
11270
11319
  reason: chain.reason,
11271
11320
  riskLevel: chain.riskLevel,
11272
- path: path8,
11273
- graph: graphFromPath(nodes, path8, "next", {
11321
+ path: path9,
11322
+ graph: graphFromPath(nodes, path9, "next", {
11274
11323
  property_id: "cross-" + chain.id,
11275
11324
  property_short: "P1",
11276
11325
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -11491,7 +11540,7 @@ function checkNeverExfilAfterPrivesc(graph) {
11491
11540
  if (candidates.length > 0) {
11492
11541
  const pre = nodes[candidates[candidates.length - 1]];
11493
11542
  const post = nodes[firstEv];
11494
- const path8 = [
11543
+ const path9 = [
11495
11544
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
11496
11545
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
11497
11546
  ];
@@ -11499,8 +11548,8 @@ function checkNeverExfilAfterPrivesc(graph) {
11499
11548
  propertyId: "no-exfil-after-privesc",
11500
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",
11501
11550
  riskLevel: "critical",
11502
- path: path8,
11503
- graph: graphFromPath(nodes, path8, "next", {
11551
+ path: path9,
11552
+ graph: graphFromPath(nodes, path9, "next", {
11504
11553
  property_id: "no-exfil-after-privesc",
11505
11554
  property_short: "P4",
11506
11555
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -11517,7 +11566,7 @@ function checkNeverExfilAfterPrivesc(graph) {
11517
11566
  for (let j = i + 1; j < nodes.length; j++) {
11518
11567
  if (!isExfilNode(nodes[j])) continue;
11519
11568
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
11520
- const path8 = [
11569
+ const path9 = [
11521
11570
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
11522
11571
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
11523
11572
  ];
@@ -11525,8 +11574,8 @@ function checkNeverExfilAfterPrivesc(graph) {
11525
11574
  propertyId: "no-exfil-after-privesc",
11526
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",
11527
11576
  riskLevel: "critical",
11528
- path: path8,
11529
- graph: graphFromPath(nodes, path8, "next", {
11577
+ path: path9,
11578
+ graph: graphFromPath(nodes, path9, "next", {
11530
11579
  property_id: "no-exfil-after-privesc",
11531
11580
  property_short: "P4",
11532
11581
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -11558,7 +11607,7 @@ function checkNeverExfilAfterCred(graph) {
11558
11607
  }
11559
11608
  if (pre) {
11560
11609
  const post = nodes[firstEv];
11561
- const path8 = [
11610
+ const path9 = [
11562
11611
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
11563
11612
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
11564
11613
  ];
@@ -11566,8 +11615,8 @@ function checkNeverExfilAfterCred(graph) {
11566
11615
  propertyId: "no-exfil-after-credential",
11567
11616
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
11568
11617
  riskLevel: "critical",
11569
- path: path8,
11570
- graph: graphFromPath(nodes, path8, "data", {
11618
+ path: path9,
11619
+ graph: graphFromPath(nodes, path9, "data", {
11571
11620
  property_id: "no-exfil-after-credential",
11572
11621
  property_short: "P5",
11573
11622
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -11583,7 +11632,7 @@ function checkNeverExfilAfterCred(graph) {
11583
11632
  if (!isCredNode(nodes[i])) continue;
11584
11633
  for (let j = i + 1; j < nodes.length; j++) {
11585
11634
  if (isExfilNode(nodes[j])) {
11586
- const path8 = [
11635
+ const path9 = [
11587
11636
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
11588
11637
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
11589
11638
  ];
@@ -11591,8 +11640,8 @@ function checkNeverExfilAfterCred(graph) {
11591
11640
  propertyId: "no-exfil-after-credential",
11592
11641
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
11593
11642
  riskLevel: "critical",
11594
- path: path8,
11595
- graph: graphFromPath(nodes, path8, "data", {
11643
+ path: path9,
11644
+ graph: graphFromPath(nodes, path9, "data", {
11596
11645
  property_id: "no-exfil-after-credential",
11597
11646
  property_short: "P5",
11598
11647
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -11751,13 +11800,13 @@ function checkSensitiveDataAggregation(graph) {
11751
11800
  if (!isExfilNode(n)) continue;
11752
11801
  const srcs = sourcesFor(i);
11753
11802
  if (srcs.size >= 2) {
11754
- 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) }];
11755
11804
  violations.push({
11756
11805
  propertyId: "sensitive-data-aggregation",
11757
11806
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
11758
11807
  riskLevel: "critical",
11759
- path: path8,
11760
- graph: graphFromPath(nodes, path8, "next", {
11808
+ path: path9,
11809
+ graph: graphFromPath(nodes, path9, "next", {
11761
11810
  property_id: "sensitive-data-aggregation",
11762
11811
  property_short: "P8",
11763
11812
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -11879,6 +11928,10 @@ var init_engine = __esm({
11879
11928
  });
11880
11929
 
11881
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";
11882
11935
  function extractInstances(actionDetail, stage) {
11883
11936
  const out = [];
11884
11937
  if (PORT_STAGE_RE.test(stage)) {
@@ -12077,12 +12130,65 @@ var init_stateful = __esm({
12077
12130
  }
12078
12131
  };
12079
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
+ }
12080
12180
  appendNode(action, sessionId, isError = false, agentId = "", instanceId = "") {
12081
12181
  const ad = String(action.actionDetail || "");
12082
12182
  const at = String(action.actionType || "");
12083
12183
  if (!ad) return null;
12084
12184
  if (this.nodes_.length >= MAX_NODES) {
12085
- 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
+ }
12086
12192
  }
12087
12193
  const stage = markStage2(ad);
12088
12194
  const node = {
@@ -12230,11 +12336,11 @@ var init_stateful = __esm({
12230
12336
  }
12231
12337
  }
12232
12338
  chainPath(stages) {
12233
- const path8 = [];
12339
+ const path9 = [];
12234
12340
  let want = stages[0];
12235
12341
  for (const n of this.nodes_) {
12236
12342
  if (n.stage === want) {
12237
- path8.push({
12343
+ path9.push({
12238
12344
  sessionId: n.sessionId,
12239
12345
  seq: n.seq,
12240
12346
  stage: n.stage,
@@ -12250,12 +12356,12 @@ var init_stateful = __esm({
12250
12356
  }
12251
12357
  }
12252
12358
  }
12253
- return path8;
12359
+ return path9;
12254
12360
  }
12255
12361
  /** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
12256
12362
  buildChainGraph(stages, chainId) {
12257
- const path8 = this.chainPath(stages);
12258
- const gNodes = path8.map((p, i) => {
12363
+ const path9 = this.chainPath(stages);
12364
+ const gNodes = path9.map((p, i) => {
12259
12365
  const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
12260
12366
  return {
12261
12367
  session_id: p.sessionId,
@@ -12506,22 +12612,22 @@ var init_stateful = __esm({
12506
12612
  });
12507
12613
 
12508
12614
  // src/engine/formal-engine/chain_state.ts
12509
- import * as fs5 from "fs";
12510
- import * as os3 from "os";
12511
- import * as path6 from "path";
12615
+ import * as fs6 from "fs";
12616
+ import * as os4 from "os";
12617
+ import * as path7 from "path";
12512
12618
  import { createHash as createHash4 } from "crypto";
12513
12619
  function defaultStateDbPath() {
12514
- const base = 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");
12515
12621
  const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
12516
- const dir = instance ? path6.join(base, instance) : base;
12622
+ const dir = instance ? path7.join(base, instance) : base;
12517
12623
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
12518
- const target = path6.join(dir, `stateful_chains_${tag}.json`);
12624
+ const target = path7.join(dir, `stateful_chains_${tag}.json`);
12519
12625
  if (instance) {
12520
- const legacy = path6.join(base, `stateful_chains_${tag}.json`);
12521
- if (!fs5.existsSync(target) && fs5.existsSync(legacy)) {
12626
+ const legacy = path7.join(base, `stateful_chains_${tag}.json`);
12627
+ if (!fs6.existsSync(target) && fs6.existsSync(legacy)) {
12522
12628
  try {
12523
- fs5.mkdirSync(dir, { recursive: true });
12524
- fs5.copyFileSync(legacy, target);
12629
+ fs6.mkdirSync(dir, { recursive: true });
12630
+ fs6.copyFileSync(legacy, target);
12525
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}`);
12526
12632
  } catch (err) {
12527
12633
  console.warn("[AgentMoss] \u8FC1\u79FB\u94FE\u72B6\u6001\u6587\u4EF6\u5931\u8D25\uFF08\u5C06\u4F7F\u7528\u65B0\u7A7A\u6587\u4EF6\uFF09:", err);
@@ -12599,8 +12705,8 @@ var init_chain_state = __esm({
12599
12705
  }
12600
12706
  _read() {
12601
12707
  try {
12602
- if (fs5.existsSync(this.filePath)) {
12603
- const raw = fs5.readFileSync(this.filePath, "utf-8");
12708
+ if (fs6.existsSync(this.filePath)) {
12709
+ const raw = fs6.readFileSync(this.filePath, "utf-8");
12604
12710
  return JSON.parse(raw);
12605
12711
  }
12606
12712
  } catch {
@@ -12614,7 +12720,7 @@ var init_chain_state = __esm({
12614
12720
  this._timer = null;
12615
12721
  try {
12616
12722
  this._syncDirtyToData();
12617
- ensurePrivateDir(path6.dirname(this.filePath));
12723
+ ensurePrivateDir(path7.dirname(this.filePath));
12618
12724
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12619
12725
  } catch {
12620
12726
  }
@@ -12637,7 +12743,7 @@ var init_chain_state = __esm({
12637
12743
  }
12638
12744
  try {
12639
12745
  this._syncDirtyToData();
12640
- ensurePrivateDir(path6.dirname(this.filePath));
12746
+ ensurePrivateDir(path7.dirname(this.filePath));
12641
12747
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12642
12748
  } catch {
12643
12749
  }
@@ -12678,16 +12784,16 @@ var init_chain_state = __esm({
12678
12784
  const sleepBuf = new Int32Array(new SharedArrayBuffer(4));
12679
12785
  for (let attempt = 0; attempt < 100; attempt++) {
12680
12786
  try {
12681
- const fd = fs5.openSync(lockPath, "wx");
12787
+ const fd = fs6.openSync(lockPath, "wx");
12682
12788
  try {
12683
12789
  return fn();
12684
12790
  } finally {
12685
12791
  try {
12686
- fs5.closeSync(fd);
12792
+ fs6.closeSync(fd);
12687
12793
  } catch {
12688
12794
  }
12689
12795
  try {
12690
- fs5.unlinkSync(lockPath);
12796
+ fs6.unlinkSync(lockPath);
12691
12797
  } catch {
12692
12798
  }
12693
12799
  }
@@ -12705,7 +12811,7 @@ var init_chain_state = __esm({
12705
12811
  _flushNow() {
12706
12812
  this._syncDirtyToData();
12707
12813
  try {
12708
- const _dirOk = ensurePrivateDir(path6.dirname(this.filePath));
12814
+ const _dirOk = ensurePrivateDir(path7.dirname(this.filePath));
12709
12815
  const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12710
12816
  if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
12711
12817
  } catch (e) {
@@ -13287,7 +13393,7 @@ var init_types = __esm({
13287
13393
  import { createHash as createHash5 } from "crypto";
13288
13394
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
13289
13395
  import { tmpdir as tmpdir3 } from "os";
13290
- import { join as join17 } from "path";
13396
+ import { join as join18 } from "path";
13291
13397
  function cacheDir() {
13292
13398
  return cacheDirOverride ?? CACHE_DIR;
13293
13399
  }
@@ -13295,7 +13401,7 @@ function safeCacheDir() {
13295
13401
  const dir = cacheDir();
13296
13402
  if (ensurePrivateDir(dir)) return dir;
13297
13403
  try {
13298
- const fallback = join17(getDataRoot(), "policy_cache");
13404
+ const fallback = join18(getDataRoot(), "policy_cache");
13299
13405
  if (ensurePrivateDir(fallback)) {
13300
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}`);
13301
13407
  return fallback;
@@ -13316,7 +13422,7 @@ var init_policy_cache = __esm({
13316
13422
  init_security_policy();
13317
13423
  init_paths();
13318
13424
  init_config();
13319
- CACHE_DIR = join17(tmpdir3(), "agent_moss_policy_cache");
13425
+ CACHE_DIR = join18(tmpdir3(), "agent_moss_policy_cache");
13320
13426
  cacheDirOverride = null;
13321
13427
  PolicyCache = class {
13322
13428
  // Map 的插入序即 LRU 序(get 时重新 set 到末尾)
@@ -13331,7 +13437,7 @@ var init_policy_cache = __esm({
13331
13437
  cacheFilePath(sessionId, promptSession) {
13332
13438
  const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
13333
13439
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13334
- return join17(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13440
+ return join18(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13335
13441
  }
13336
13442
  /** 取缓存:内存 → 文件;未命中返回 null。 */
13337
13443
  get(sessionId, promptSession) {
@@ -13362,7 +13468,7 @@ var init_policy_cache = __esm({
13362
13468
  try {
13363
13469
  const dir = safeCacheDir();
13364
13470
  const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13365
- if (!ensurePrivateDir(join17(dir, sub))) return;
13471
+ if (!ensurePrivateDir(join18(dir, sub))) return;
13366
13472
  writePrivateText(file, policy);
13367
13473
  } catch {
13368
13474
  }
@@ -13388,12 +13494,12 @@ var init_policy_cache = __esm({
13388
13494
  if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
13389
13495
  }
13390
13496
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13391
- const dir = join17(cacheDir(), safeSessionId);
13497
+ const dir = join18(cacheDir(), safeSessionId);
13392
13498
  try {
13393
13499
  if (existsSync17(dir)) {
13394
13500
  for (const f of readdirSync5(dir)) {
13395
13501
  try {
13396
- unlinkSync4(join17(dir, f));
13502
+ unlinkSync4(join18(dir, f));
13397
13503
  } catch {
13398
13504
  }
13399
13505
  }
@@ -13407,9 +13513,9 @@ var init_policy_cache = __esm({
13407
13513
  try {
13408
13514
  if (existsSync17(cacheDir())) {
13409
13515
  for (const sessionDir of readdirSync5(cacheDir())) {
13410
- const dir = join17(cacheDir(), sessionDir);
13516
+ const dir = join18(cacheDir(), sessionDir);
13411
13517
  try {
13412
- for (const f of readdirSync5(dir)) unlinkSync4(join17(dir, f));
13518
+ for (const f of readdirSync5(dir)) unlinkSync4(join18(dir, f));
13413
13519
  rmdirSync(dir);
13414
13520
  } catch {
13415
13521
  }
@@ -13507,7 +13613,7 @@ __export(analyzer_exports, {
13507
13613
  });
13508
13614
  import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
13509
13615
  import { tmpdir as tmpdir4 } from "os";
13510
- import { join as join18, resolve as resolve11 } from "path";
13616
+ import { join as join19, resolve as resolve11 } from "path";
13511
13617
  import { parse as parseToml } from "smol-toml";
13512
13618
  function _setPolicyOutputDirForTest(dir) {
13513
13619
  policyOutputDirOverride = dir;
@@ -13524,7 +13630,7 @@ function savePolicyToFile(sessionId, policyToml) {
13524
13630
  return null;
13525
13631
  }
13526
13632
  const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13527
- const filepath = join18(outDir, `${safeName}.toml`);
13633
+ const filepath = join19(outDir, `${safeName}.toml`);
13528
13634
  writePrivateText(filepath, policyToml);
13529
13635
  return filepath;
13530
13636
  } catch (err) {
@@ -13747,7 +13853,7 @@ var init_analyzer = __esm({
13747
13853
  init_asset_dir();
13748
13854
  init_token_stats();
13749
13855
  init_logging();
13750
- POLICY_OUTPUT_DIR = join18(tmpdir4(), "agent_moss");
13856
+ POLICY_OUTPUT_DIR = join19(tmpdir4(), "agent_moss");
13751
13857
  policyOutputDirOverride = null;
13752
13858
  DEFAULT_READONLY_POLICY = `landlock_optional = false
13753
13859
  mount_isolation_fallback = false
@@ -13792,7 +13898,7 @@ var init_esm_require = __esm({
13792
13898
  });
13793
13899
 
13794
13900
  // src/actrail.ts
13795
- import * as fs6 from "fs";
13901
+ import * as fs7 from "fs";
13796
13902
  function escape(value) {
13797
13903
  return value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/=/g, "\\e");
13798
13904
  }
@@ -13813,7 +13919,7 @@ function getStoragePath() {
13813
13919
  function reportEnforcementEvent(opts) {
13814
13920
  if (!isEnabled()) return false;
13815
13921
  const storagePath = getStoragePath();
13816
- if (!fs6.existsSync(storagePath)) return false;
13922
+ if (!fs7.existsSync(storagePath)) return false;
13817
13923
  try {
13818
13924
  let Database;
13819
13925
  try {
@@ -13984,9 +14090,9 @@ var init_pattern_miner = __esm({
13984
14090
  });
13985
14091
 
13986
14092
  // src/agent-gate-reader.ts
13987
- import * as fs7 from "fs";
13988
- import * as os4 from "os";
13989
- import * as path7 from "path";
14093
+ import * as fs8 from "fs";
14094
+ import * as os5 from "os";
14095
+ import * as path8 from "path";
13990
14096
  function normalizeAction(row) {
13991
14097
  return {
13992
14098
  actionType: String(row.action_type || row.tool_name || row.name || ""),
@@ -13996,10 +14102,10 @@ function normalizeAction(row) {
13996
14102
  function readJsonDir(dirPath, limit = 1e5) {
13997
14103
  const sessions = /* @__PURE__ */ new Map();
13998
14104
  try {
13999
- const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
14105
+ const files = fs8.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
14000
14106
  for (const f of files.slice(-200)) {
14001
14107
  const sid = f.replace(/\.json$/, "");
14002
- const raw = fs7.readFileSync(path7.join(dirPath, f), "utf-8");
14108
+ const raw = fs8.readFileSync(path8.join(dirPath, f), "utf-8");
14003
14109
  const arr = JSON.parse(raw);
14004
14110
  if (!Array.isArray(arr)) continue;
14005
14111
  for (const item of arr) {
@@ -14056,7 +14162,7 @@ function readSqlite(dbPath, limit = 1e5) {
14056
14162
  function loadAgentGateSessions(dbPath = "") {
14057
14163
  if (dbPath) {
14058
14164
  try {
14059
- if (fs7.statSync(dbPath).isDirectory()) {
14165
+ if (fs8.statSync(dbPath).isDirectory()) {
14060
14166
  return readJsonDir(dbPath);
14061
14167
  }
14062
14168
  } catch {
@@ -14067,7 +14173,7 @@ function loadAgentGateSessions(dbPath = "") {
14067
14173
  }
14068
14174
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
14069
14175
  if (sql.length > 0) return sql;
14070
- 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");
14071
14177
  return readJsonDir(jsonDefault);
14072
14178
  }
14073
14179
  var DEFAULT_AGENTGATE_SQLITE;
@@ -14076,8 +14182,8 @@ var init_agent_gate_reader = __esm({
14076
14182
  "use strict";
14077
14183
  init_esm_shims();
14078
14184
  init_esm_require();
14079
- DEFAULT_AGENTGATE_SQLITE = path7.join(
14080
- os4.homedir(),
14185
+ DEFAULT_AGENTGATE_SQLITE = path8.join(
14186
+ os5.homedir(),
14081
14187
  ".local",
14082
14188
  "share",
14083
14189
  "agent_gate",
@@ -14217,7 +14323,7 @@ var init_runtime_stats = __esm({
14217
14323
 
14218
14324
  // src/routes.ts
14219
14325
  import { randomBytes as randomBytes2 } from "crypto";
14220
- import { join as join20, dirname as dirname13 } from "path";
14326
+ import { join as join21, dirname as dirname13 } from "path";
14221
14327
  import { fileURLToPath as fileURLToPath10 } from "url";
14222
14328
  async function healthRoute(c) {
14223
14329
  const metrics = {};
@@ -14239,11 +14345,11 @@ async function healthRoute(c) {
14239
14345
  if (typeof pct === "number") {
14240
14346
  if (pct >= 100) {
14241
14347
  degraded.push(
14242
- `\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`
14243
14349
  );
14244
14350
  } else if (pct >= 90) {
14245
14351
  degraded.push(
14246
- `\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`
14247
14353
  );
14248
14354
  }
14249
14355
  }
@@ -14251,7 +14357,7 @@ async function healthRoute(c) {
14251
14357
  const snap = getBreaker().snapshot();
14252
14358
  if (snap.state === "open") {
14253
14359
  degraded.push(
14254
- `\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`
14255
14361
  );
14256
14362
  }
14257
14363
  } catch {
@@ -14271,6 +14377,14 @@ async function analyzeRoute(c) {
14271
14377
  try {
14272
14378
  const body = await c.req.json();
14273
14379
  const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
14380
+ const unmappedTool = String(
14381
+ req.metadata?.unmapped_tool || ""
14382
+ );
14383
+ if (unmappedTool) {
14384
+ degradedNotes.push(
14385
+ `\u3010\u5DF2\u964D\u7EA7\u3011\u5DE5\u5177\u540D '${unmappedTool}' \u672A\u8BC6\u522B\u4E3A\u6807\u51C6\u52A8\u4F5C\u7C7B\u578B\uFF1A\u4F9D\u8D56\u52A8\u4F5C\u7C7B\u578B\u7684 L2 \u89C4\u5219\uFF08\u8BFB\u540E\u5199 / \u7EC4\u5408\u94FE / \u6388\u6743\uFF09\u53EF\u80FD\u672A\u751F\u6548\uFF1BL1\uFF08\u547D\u4EE4\u5185\u5BB9\uFF09\u4E0E L3 \u6B63\u5E38\u3002\u53EF\u5728 AgentGate \u914D\u7F6E AGENT_GATE_TOOL_NAME_MAP \u8865\u5145\u6620\u5C04\uFF08\u5982 {"${unmappedTool}": "read"}\uFF09\u3002`
14386
+ );
14387
+ }
14274
14388
  let osType = req.os_type;
14275
14389
  if (!osType) {
14276
14390
  osType = process.platform === "win32" ? "windows" : "linux";
@@ -14451,11 +14565,11 @@ async function analyzeRoute(c) {
14451
14565
  const pct = Math.round(total / MAX_NODES * 1e3) / 10;
14452
14566
  if (total >= MAX_NODES) {
14453
14567
  degradedNotes.push(
14454
- `\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`
14568
+ `\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`
14455
14569
  );
14456
14570
  } else if (pct >= 90) {
14457
14571
  degradedNotes.push(
14458
- `\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`
14572
+ `\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`
14459
14573
  );
14460
14574
  }
14461
14575
  } catch {
@@ -14645,7 +14759,7 @@ function getBrainRuleStore() {
14645
14759
  return new BrainRuleStore();
14646
14760
  }
14647
14761
  function getBrainSkillManager() {
14648
- const dir = resolveAssetDir(__dirname9, "skills") ?? join20(__dirname9, "..", "..", "agent_moss", "skills");
14762
+ const dir = resolveAssetDir(__dirname9, "skills") ?? join21(__dirname9, "..", "..", "agent_moss", "skills");
14649
14763
  return new BrainSkillManager(dir);
14650
14764
  }
14651
14765
  async function brainRulesRoute(c) {
@@ -14765,7 +14879,7 @@ var init_routes = __esm({
14765
14879
  import { Hono } from "hono";
14766
14880
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
14767
14881
  import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
14768
- import { join as join21, dirname as dirname14 } from "path";
14882
+ import { join as join22, dirname as dirname14 } from "path";
14769
14883
  import { fileURLToPath as fileURLToPath11 } from "url";
14770
14884
  function getConsoleToken() {
14771
14885
  return process.env[CONSOLE_TOKEN_ENV] || "";
@@ -14807,7 +14921,7 @@ function createConsoleRouter() {
14807
14921
  console2.use("/api/*", authMiddleware());
14808
14922
  console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
14809
14923
  const serveIndex = (c) => {
14810
- const indexFile = join21(STATIC_DIR, "index.html");
14924
+ const indexFile = join22(STATIC_DIR, "index.html");
14811
14925
  if (existsSync20(indexFile)) {
14812
14926
  return c.html(readFileSync20(indexFile, "utf-8"));
14813
14927
  }
@@ -15004,11 +15118,11 @@ function createConsoleRouter() {
15004
15118
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
15005
15119
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
15006
15120
  }
15007
- const userPath = join21(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
15121
+ const userPath = join22(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
15008
15122
  const builtinDir = resolveAssetDir(__dirname10, "skills");
15009
15123
  const candidates = [
15010
15124
  ...isRuntimeConfigDisabled() ? [] : [userPath],
15011
- builtinDir ? join21(builtinDir, `${skillId}.md`) : ""
15125
+ builtinDir ? join22(builtinDir, `${skillId}.md`) : ""
15012
15126
  ].filter(Boolean);
15013
15127
  for (const p of candidates) {
15014
15128
  if (existsSync20(p)) {
@@ -15146,7 +15260,7 @@ var init_router = __esm({
15146
15260
  init_asset_dir();
15147
15261
  init_rules_mode();
15148
15262
  __dirname10 = dirname14(fileURLToPath11(import.meta.url));
15149
- STATIC_DIR = join21(__dirname10, "static");
15263
+ STATIC_DIR = join22(__dirname10, "static");
15150
15264
  CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
15151
15265
  }
15152
15266
  });
@@ -15174,7 +15288,7 @@ import { Hono as Hono2 } from "hono";
15174
15288
  import { cors } from "hono/cors";
15175
15289
  import { logger } from "hono/logger";
15176
15290
  import net from "net";
15177
- import { existsSync as existsSync21, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync10 } from "fs";
15291
+ import { existsSync as existsSync21, writeFileSync as writeFileSync8, renameSync as renameSync3, mkdirSync as mkdirSync11 } from "fs";
15178
15292
  import { dirname as dirname15 } from "path";
15179
15293
  function logDeploymentSelfCheck() {
15180
15294
  try {
@@ -15267,7 +15381,7 @@ function createApp() {
15267
15381
  startLoopMonitor();
15268
15382
  const limiter = new RateLimiter(rateLimitQps());
15269
15383
  app.use("*", async (c, next) => {
15270
- const path8 = new URL(c.req.url).pathname;
15384
+ const path9 = new URL(c.req.url).pathname;
15271
15385
  const method = c.req.method.toUpperCase();
15272
15386
  if (method === "OPTIONS") return next();
15273
15387
  const maxBody = maxBodyBytes();
@@ -15281,16 +15395,16 @@ function createApp() {
15281
15395
  if (originCheckEnabled()) {
15282
15396
  const origin = c.req.header("origin") || "";
15283
15397
  if (origin && !originAllowed(origin, c.req.header("host") || "")) {
15284
- console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path8}`);
15398
+ console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path9}`);
15285
15399
  return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
15286
15400
  }
15287
15401
  }
15288
- const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path8);
15289
- const isPublicPage = !path8.startsWith("/console/api") && (path8 === "/console" || path8.startsWith("/console/"));
15402
+ const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path9);
15403
+ const isPublicPage = !path9.startsWith("/console/api") && (path9 === "/console" || path9.startsWith("/console/"));
15290
15404
  if (!okAuth && !isPublicPage) {
15291
15405
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
15292
15406
  }
15293
- if (limiter.enabled && path8.startsWith("/api/")) {
15407
+ if (limiter.enabled && path9.startsWith("/api/")) {
15294
15408
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
15295
15409
  if (!limiter.allow(key)) {
15296
15410
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
@@ -15324,7 +15438,7 @@ function createApp() {
15324
15438
  return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
15325
15439
  }
15326
15440
  }
15327
- const pool = poolOf(path8);
15441
+ const pool = poolOf(path9);
15328
15442
  if (!take(`pool:${pool}`, poolLimit(pool))) {
15329
15443
  const qkey = principal ? "p:" + principalHash(principal) : "c:local";
15330
15444
  const [qn, abusive] = noteQueueReject(qkey);
@@ -15418,8 +15532,8 @@ async function warmUpEngine() {
15418
15532
  }
15419
15533
  function writePortFile(port) {
15420
15534
  try {
15421
- const path8 = getPortFilePath();
15422
- mkdirSync10(dirname15(path8), { recursive: true });
15535
+ const path9 = getPortFilePath();
15536
+ mkdirSync11(dirname15(path9), { recursive: true });
15423
15537
  const payload = JSON.stringify({
15424
15538
  port,
15425
15539
  pid: process.pid,
@@ -15428,10 +15542,10 @@ function writePortFile(port) {
15428
15542
  version,
15429
15543
  started_at: (/* @__PURE__ */ new Date()).toISOString()
15430
15544
  });
15431
- const tmp = `${path8}.tmp`;
15432
- writeFileSync7(tmp, payload, "utf-8");
15433
- renameSync3(tmp, path8);
15434
- console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path8} (port=${port})`);
15545
+ const tmp = `${path9}.tmp`;
15546
+ writeFileSync8(tmp, payload, "utf-8");
15547
+ renameSync3(tmp, path9);
15548
+ console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path9} (port=${port})`);
15435
15549
  } catch (err) {
15436
15550
  console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
15437
15551
  }
@@ -15472,12 +15586,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15472
15586
  },
15473
15587
  serve: async () => {
15474
15588
  failFastOnAuthError();
15475
- const { mkdirSync: mkdirSync12, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15589
+ const { mkdirSync: mkdirSync13, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15476
15590
  const { dirname: dirname17 } = await import("path");
15477
15591
  const dir = dirname17(socketPath);
15478
15592
  if (dir) {
15479
15593
  try {
15480
- mkdirSync12(dir, { recursive: true });
15594
+ mkdirSync13(dir, { recursive: true });
15481
15595
  } catch {
15482
15596
  }
15483
15597
  }
@@ -15611,18 +15725,18 @@ __export(rules_tools_exports, {
15611
15725
  rulesStatusText: () => rulesStatusText,
15612
15726
  templateSourceDir: () => templateSourceDir
15613
15727
  });
15614
- import { existsSync as existsSync22, mkdirSync as mkdirSync11, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync8 } from "fs";
15615
- import { dirname as dirname16, join as join23 } from "path";
15728
+ import { existsSync as existsSync22, mkdirSync as mkdirSync12, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync9 } from "fs";
15729
+ import { dirname as dirname16, join as join24 } from "path";
15616
15730
  import { fileURLToPath as fileURLToPath12 } from "url";
15617
15731
  function initRulesDir(targetDir, opts = {}) {
15618
- mkdirSync11(targetDir, { recursive: true });
15732
+ mkdirSync12(targetDir, { recursive: true });
15619
15733
  const written = [];
15620
- const extraPath = join23(targetDir, EXTRA_FILENAME);
15734
+ const extraPath = join24(targetDir, EXTRA_FILENAME);
15621
15735
  if (opts.force || !existsSync22(extraPath)) {
15622
- writeFileSync8(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
15736
+ writeFileSync9(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
15623
15737
  written.push(extraPath);
15624
15738
  }
15625
- const samplePath = join23(targetDir, OVERRIDE_FILENAME);
15739
+ const samplePath = join24(targetDir, OVERRIDE_FILENAME);
15626
15740
  if (opts.force || !existsSync22(samplePath)) {
15627
15741
  let payload = OVERRIDE_TEMPLATE;
15628
15742
  if (opts.withBuiltin) {
@@ -15638,19 +15752,19 @@ function initRulesDir(targetDir, opts = {}) {
15638
15752
  payload = { _\u8BF4\u660E: OVERRIDE_BUILTIN_NOTE };
15639
15753
  for (const k of L1_KEYS) payload[k] = data[k] || [];
15640
15754
  }
15641
- writeFileSync8(samplePath, JSON.stringify(payload, null, 2), "utf-8");
15755
+ writeFileSync9(samplePath, JSON.stringify(payload, null, 2), "utf-8");
15642
15756
  written.push(samplePath);
15643
15757
  }
15644
- const readmeSrc = join23(templateSourceDir(), "README.md");
15645
- const readmeDst = join23(targetDir, "README.md");
15758
+ const readmeSrc = join24(templateSourceDir(), "README.md");
15759
+ const readmeDst = join24(targetDir, "README.md");
15646
15760
  if (existsSync22(readmeSrc) && (opts.force || !existsSync22(readmeDst))) {
15647
- writeFileSync8(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
15761
+ writeFileSync9(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
15648
15762
  written.push(readmeDst);
15649
15763
  }
15650
15764
  return written;
15651
15765
  }
15652
15766
  function templateSourceDir() {
15653
- const cands = [join23(__dirname11, "data", "rules_template"), join23(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
15767
+ const cands = [join24(__dirname11, "data", "rules_template"), join24(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
15654
15768
  for (const c of cands) if (existsSync22(c)) return c;
15655
15769
  return cands[0];
15656
15770
  }
@@ -15659,7 +15773,7 @@ function templateFiles(dirs) {
15659
15773
  for (const d of dirs) {
15660
15774
  try {
15661
15775
  for (const name of readdirSync7(d)) {
15662
- if (name.endsWith(".json.\u793A\u4F8B")) out.push(join23(d, name));
15776
+ if (name.endsWith(".json.\u793A\u4F8B")) out.push(join24(d, name));
15663
15777
  }
15664
15778
  } catch {
15665
15779
  }
@@ -15843,7 +15957,7 @@ async function main() {
15843
15957
  case "init": {
15844
15958
  const flagIdx = args.findIndex((a) => a === "--output" || a === "-o");
15845
15959
  const output = (flagIdx >= 0 ? args[flagIdx + 1] : void 0) || args.slice(1).find((a) => !a.startsWith("-")) || "input.json";
15846
- const fs8 = await import("fs");
15960
+ const fs9 = await import("fs");
15847
15961
  const template = {
15848
15962
  session_id: "my-session-001",
15849
15963
  prompt_session: "Read /var/log/app.log and analyze errors",
@@ -15853,7 +15967,7 @@ async function main() {
15853
15967
  os_type: "",
15854
15968
  cwd: "/home/user/project"
15855
15969
  };
15856
- fs8.writeFileSync(output, JSON.stringify(template, null, 2), "utf-8");
15970
+ fs9.writeFileSync(output, JSON.stringify(template, null, 2), "utf-8");
15857
15971
  console.log(`Template written to ${output}`);
15858
15972
  break;
15859
15973
  }
@@ -15863,13 +15977,13 @@ async function main() {
15863
15977
  console.error('Usage: agent-moss analyze <input.json | "shell command">');
15864
15978
  process.exit(1);
15865
15979
  }
15866
- const fs8 = await import("fs");
15867
- const path8 = await import("path");
15980
+ const fs9 = await import("fs");
15981
+ const path9 = await import("path");
15868
15982
  const useJson = args.includes("--json");
15869
15983
  const osType = process.platform === "win32" ? "windows" : "linux";
15870
- const isFile = fs8.existsSync(target) && fs8.statSync(target).isFile();
15984
+ const isFile = fs9.existsSync(target) && fs9.statSync(target).isFile();
15871
15985
  if (!isFile) {
15872
- if (fs8.existsSync(target)) {
15986
+ if (fs9.existsSync(target)) {
15873
15987
  console.error(`\u9519\u8BEF: \u4E0D\u662F\u6587\u4EF6: ${target}`);
15874
15988
  process.exit(2);
15875
15989
  }
@@ -15883,8 +15997,8 @@ async function main() {
15883
15997
  }
15884
15998
  process.exit(await analyzeRawCommand(target, useJson));
15885
15999
  }
15886
- const filePath = path8.resolve(target);
15887
- const data = JSON.parse(fs8.readFileSync(filePath, "utf-8"));
16000
+ const filePath = path9.resolve(target);
16001
+ const data = JSON.parse(fs9.readFileSync(filePath, "utf-8"));
15888
16002
  const { analyze: analyze2 } = await Promise.resolve().then(() => (init_analyzer(), analyzer_exports));
15889
16003
  const sessionId = String(data.session_id || "unknown");
15890
16004
  const result = await analyze2(buildAnalysisInputFromFile(data));
@@ -15892,15 +16006,15 @@ async function main() {
15892
16006
  if (!args.includes("--no-file")) {
15893
16007
  const outDirIdx = args.findIndex((a) => a === "--output-dir" || a === "-o");
15894
16008
  const outDir = outDirIdx >= 0 && args[outDirIdx + 1] ? args[outDirIdx + 1] : process.cwd();
15895
- fs8.mkdirSync(outDir, { recursive: true });
16009
+ fs9.mkdirSync(outDir, { recursive: true });
15896
16010
  const safeSession = sessionId.replace(/\//g, "_");
15897
16011
  if (result.decision === "Allow") {
15898
- const policyPath = path8.join(outDir, `${safeSession}_policy.toml`);
15899
- fs8.writeFileSync(policyPath, result.policy || "", "utf-8");
16012
+ const policyPath = path9.join(outDir, `${safeSession}_policy.toml`);
16013
+ fs9.writeFileSync(policyPath, result.policy || "", "utf-8");
15900
16014
  console.log(`Policy written to ${policyPath}`);
15901
16015
  } else {
15902
- const denyPath = path8.join(outDir, `${safeSession}_deny_reason.txt`);
15903
- fs8.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
16016
+ const denyPath = path9.join(outDir, `${safeSession}_deny_reason.txt`);
16017
+ fs9.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
15904
16018
  console.log(`Deny reason written to ${denyPath}`);
15905
16019
  }
15906
16020
  }
@@ -15989,8 +16103,8 @@ async function main() {
15989
16103
  case "install": {
15990
16104
  const enable = args.includes("--enable");
15991
16105
  const { execSync } = await import("child_process");
15992
- const fs8 = await import("fs");
15993
- const path8 = await import("path");
16106
+ const fs9 = await import("fs");
16107
+ const path9 = await import("path");
15994
16108
  const { fileURLToPath: fileURLToPath14 } = await import("url");
15995
16109
  if (process.getuid?.() !== 0) {
15996
16110
  try {
@@ -16007,22 +16121,22 @@ async function main() {
16007
16121
  process.exit(0);
16008
16122
  }
16009
16123
  const __filename7 = fileURLToPath14(import.meta.url);
16010
- const __dirname12 = path8.dirname(__filename7);
16011
- let srcPath = path8.join(__dirname12, "data", "agent_moss.service");
16012
- if (!fs8.existsSync(srcPath)) {
16013
- srcPath = path8.join(__dirname12, "..", "src", "data", "agent_moss.service");
16124
+ const __dirname12 = path9.dirname(__filename7);
16125
+ let srcPath = path9.join(__dirname12, "data", "agent_moss.service");
16126
+ if (!fs9.existsSync(srcPath)) {
16127
+ srcPath = path9.join(__dirname12, "..", "src", "data", "agent_moss.service");
16014
16128
  }
16015
- if (!fs8.existsSync(srcPath)) {
16129
+ if (!fs9.existsSync(srcPath)) {
16016
16130
  console.error("\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230 agent_moss.service \u6A21\u677F\u6587\u4EF6");
16017
16131
  process.exit(1);
16018
16132
  }
16019
16133
  const which = execSync("which agent-moss 2>/dev/null || true", { encoding: "utf-8" }).trim();
16020
- const binPath = which || `${process.execPath} ${path8.join(__dirname12, "cli.js")}`;
16021
- let content = fs8.readFileSync(srcPath, "utf-8");
16134
+ const binPath = which || `${process.execPath} ${path9.join(__dirname12, "cli.js")}`;
16135
+ let content = fs9.readFileSync(srcPath, "utf-8");
16022
16136
  content = content.replace("__AGENT_MOSS_BIN__", binPath);
16023
16137
  const dst = "/etc/systemd/system/agent-moss.service";
16024
- fs8.writeFileSync(dst, content, "utf-8");
16025
- fs8.chmodSync(dst, 420);
16138
+ fs9.writeFileSync(dst, content, "utf-8");
16139
+ fs9.chmodSync(dst, 420);
16026
16140
  console.log(`\u2705 \u5DF2\u5B89\u88C5 systemd service: ${dst}`);
16027
16141
  execSync("systemctl daemon-reload", { stdio: "inherit" });
16028
16142
  console.log("\u2705 systemctl daemon-reload \u5B8C\u6210");