@kenhkl/agent-moss 0.17.23 → 0.17.25

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
@@ -1,12 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  var __defProp = Object.defineProperty;
3
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
- }) : x)(function(x) {
7
- if (typeof require !== "undefined") return require.apply(this, arguments);
8
- throw Error('Dynamic require of "' + x + '" is not supported');
9
- });
10
4
  var __esm = (fn, res) => function __init() {
11
5
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
6
  };
@@ -408,22 +402,22 @@ function loadToolRegistry() {
408
402
  data.tools = tools;
409
403
  return data;
410
404
  }
411
- function scanStructEntry(cat, value, path7) {
405
+ function scanStructEntry(cat, value, path8) {
412
406
  if (cat === "skills") {
413
407
  if (!value || typeof value !== "object" || Array.isArray(value)) {
414
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
408
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
415
409
  return null;
416
410
  }
417
411
  const out = {};
418
412
  for (const [skCat, skills] of Object.entries(value)) {
419
413
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
420
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
414
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
421
415
  continue;
422
416
  }
423
417
  const keep = {};
424
418
  for (const [name, kws] of Object.entries(skills)) {
425
419
  if (Array.isArray(kws)) keep[name] = kws;
426
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
420
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
427
421
  }
428
422
  if (Object.keys(keep).length > 0) out[skCat] = keep;
429
423
  }
@@ -431,37 +425,37 @@ function scanStructEntry(cat, value, path7) {
431
425
  }
432
426
  if (cat === "ltl_rules") {
433
427
  if (!Array.isArray(value)) {
434
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
428
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
435
429
  return null;
436
430
  }
437
431
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
438
432
  if (keep.length !== value.length) {
439
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
433
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
440
434
  }
441
435
  return keep.length > 0 ? keep : null;
442
436
  }
443
437
  if (cat === "tools") {
444
438
  if (!value || typeof value !== "object" || Array.isArray(value)) {
445
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
439
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
446
440
  return null;
447
441
  }
448
442
  const keep = {};
449
443
  for (const [k, v] of Object.entries(value)) {
450
444
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
451
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
445
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
452
446
  }
453
447
  return Object.keys(keep).length > 0 ? keep : null;
454
448
  }
455
449
  return null;
456
450
  }
457
- function scanRulesFile(path7, kind) {
451
+ function scanRulesFile(path8, kind) {
458
452
  const out = {};
459
453
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
460
454
  let parsed;
461
455
  try {
462
- parsed = JSON.parse(readFileSync2(path7, "utf-8"));
456
+ parsed = JSON.parse(readFileSync2(path8, "utf-8"));
463
457
  } catch (e) {
464
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
458
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
465
459
  return out;
466
460
  }
467
461
  const classifyFlat = (r) => {
@@ -485,44 +479,44 @@ function scanRulesFile(path7, kind) {
485
479
  }
486
480
  if (flatBad > 0) {
487
481
  console.warn(
488
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
482
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
489
483
  );
490
484
  }
491
485
  } else {
492
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
486
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
493
487
  return out;
494
488
  }
495
489
  for (const [cat, rules] of pairs) {
496
490
  if (String(cat).startsWith("_")) continue;
497
491
  if (STRUCT_KEYS.includes(cat)) {
498
- const got = scanStructEntry(cat, rules, path7);
492
+ const got = scanStructEntry(cat, rules, path8);
499
493
  if (got !== null) out[cat] = got;
500
494
  continue;
501
495
  }
502
496
  const required = EXTRA_CATEGORIES[cat];
503
497
  if (!required) {
504
498
  console.warn(
505
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
499
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
506
500
  );
507
501
  continue;
508
502
  }
509
503
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
510
504
  console.error(
511
- `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path7} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
505
+ `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path8} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
512
506
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
513
507
  \u4F60\u5199\u7684\u50CF\u662F runtime config \u7684\u683C\u5F0F\uFF08{"category_enabled": ..., "rules": [...]}\uFF09\u2014\u2014\u90A3\u662F ~/.config/agentmoss/agent_moss_runtime.json \u7684\u683C\u5F0F\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5F53\u89C4\u5219\u6587\u4EF6\u7528\u3002`
514
508
  );
515
509
  continue;
516
510
  }
517
511
  if (!Array.isArray(rules)) {
518
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
512
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
519
513
  continue;
520
514
  }
521
515
  const items = [];
522
516
  for (const r of rules) {
523
517
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
524
518
  console.warn(
525
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
519
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
526
520
  );
527
521
  continue;
528
522
  }
@@ -532,7 +526,7 @@ function scanRulesFile(path7, kind) {
532
526
  }
533
527
  if (Object.keys(out).length > 0) {
534
528
  console.info(
535
- `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path7}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
529
+ `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path8}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
536
530
  );
537
531
  }
538
532
  return out;
@@ -879,7 +873,7 @@ var init_rules_contract = __esm({
879
873
 
880
874
  // src/infra/security-policy.ts
881
875
  import { createHash as createHash2, randomBytes, timingSafeEqual } from "crypto";
882
- import { chmodSync, closeSync, existsSync as existsSync3, lstatSync, mkdirSync, openSync, readFileSync as readFileSync4, readSync, realpathSync, writeSync } from "fs";
876
+ import { chmodSync, closeSync, constants as fsConstants, existsSync as existsSync3, lstatSync, mkdirSync, openSync, readFileSync as readFileSync4, readSync, realpathSync, writeSync } from "fs";
883
877
  import { homedir as homedir2, tmpdir } from "os";
884
878
  import { basename, isAbsolute, join as join4, relative, resolve as resolve2, dirname as dirname2 } from "path";
885
879
  function env(name, dflt = "") {
@@ -955,10 +949,10 @@ function readExplicitToken() {
955
949
  if (tok) return tok;
956
950
  const fdTok = readFdToken();
957
951
  if (fdTok) return fdTok;
958
- const path7 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
959
- if (path7) {
952
+ const path8 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
953
+ if (path8) {
960
954
  try {
961
- return readFileSync4(path7, "utf-8").trim();
955
+ return readFileSync4(path8, "utf-8").trim();
962
956
  } catch {
963
957
  return "";
964
958
  }
@@ -966,23 +960,23 @@ function readExplicitToken() {
966
960
  return "";
967
961
  }
968
962
  function ensureAutoToken() {
969
- const path7 = autoTokenPath();
963
+ const path8 = autoTokenPath();
970
964
  try {
971
- if (existsSync3(path7) && !lstatSync(path7).isSymbolicLink()) {
972
- const tok2 = readFileSync4(path7, "utf-8").trim();
965
+ if (existsSync3(path8) && !lstatSync(path8).isSymbolicLink()) {
966
+ const tok2 = readFileSync4(path8, "utf-8").trim();
973
967
  if (tok2) {
974
968
  try {
975
- chmodSync(path7, 384);
969
+ chmodSync(path8, 384);
976
970
  } catch {
977
971
  }
978
972
  return tok2;
979
973
  }
980
974
  }
981
975
  const tok = randomBytes(32).toString("base64url");
982
- ensurePrivateDir(dirname2(path7));
983
- if (!writePrivateText(path7, tok + "\n")) return "";
976
+ ensurePrivateDir(dirname2(path8));
977
+ if (!writePrivateText(path8, tok + "\n")) return "";
984
978
  console.warn(
985
- `[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${path7}\uFF080600\uFF09\u3002\u5BA2\u6237\u7AEF\u9700\u5E26 \`Authorization: Bearer <token>\`\uFF1B\u67E5\u770B\uFF1Acat ${path7}\uFF1B\u5982\u9700\u5173\u95ED\u9274\u6743\uFF1AAGENT_MOSS_AUTH_MODE=off`
979
+ `[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${path8}\uFF080600\uFF09\u3002\u5BA2\u6237\u7AEF\u9700\u5E26 \`Authorization: Bearer <token>\`\uFF1B\u67E5\u770B\uFF1Acat ${path8}\uFF1B\u5982\u9700\u5173\u95ED\u9274\u6743\uFF1AAGENT_MOSS_AUTH_MODE=off`
986
980
  );
987
981
  return tok;
988
982
  } catch (e) {
@@ -1055,16 +1049,16 @@ function constEq(a, b) {
1055
1049
  if (ba.length !== bb.length) return false;
1056
1050
  return timingSafeEqual(ba, bb);
1057
1051
  }
1058
- function checkRequestAuth(headers, path7) {
1052
+ function checkRequestAuth(headers, path8) {
1059
1053
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
1060
- const isHealth = HEALTH_PATHS.includes(path7.replace(/\/+$/, ""));
1054
+ const isHealth = HEALTH_PATHS.includes(path8.replace(/\/+$/, ""));
1061
1055
  const [gt0, agents, err] = resolveAuth();
1062
1056
  if (err) return isHealth ? [true, ""] : [false, ""];
1063
1057
  if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
1064
1058
  if (isHealth) return [true, ""];
1065
1059
  const tok = bearer(headers);
1066
1060
  if (!tok) return [false, ""];
1067
- if (path7.startsWith("/console/api")) {
1061
+ if (path8.startsWith("/console/api")) {
1068
1062
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
1069
1063
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
1070
1064
  }
@@ -1083,8 +1077,8 @@ function bindAgent(principal, agentId) {
1083
1077
  if (!agentId) return [true, bound];
1084
1078
  return [bound === agentId, bound];
1085
1079
  }
1086
- function principalOf(headers, path7 = "") {
1087
- const [ok, principal] = checkRequestAuth(headers, path7);
1080
+ function principalOf(headers, path8 = "") {
1081
+ const [ok, principal] = checkRequestAuth(headers, path8);
1088
1082
  return ok ? principal : "";
1089
1083
  }
1090
1084
  function principalHash(principal) {
@@ -1163,9 +1157,8 @@ function ensurePrivateDir(dir) {
1163
1157
  }
1164
1158
  function writePrivateText(file, text) {
1165
1159
  try {
1166
- const flags = __require("fs").constants;
1167
- let openFlags = flags.O_WRONLY | flags.O_CREAT | flags.O_TRUNC;
1168
- if (flags.O_NOFOLLOW) openFlags |= flags.O_NOFOLLOW;
1160
+ let openFlags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC;
1161
+ if (fsConstants.O_NOFOLLOW) openFlags |= fsConstants.O_NOFOLLOW;
1169
1162
  const fd = openSync(file, openFlags, 384);
1170
1163
  try {
1171
1164
  writeSync(fd, text);
@@ -1342,11 +1335,11 @@ function errorDetailMode() {
1342
1335
  function maxBodyBytes() {
1343
1336
  return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
1344
1337
  }
1345
- function poolOf(path7) {
1346
- if (path7 === "/api/v1/analyze" || path7.startsWith("/api/v1/analyze/")) return "biz";
1347
- if (path7 === "/api/v1/review" || path7.startsWith("/api/v1/review/")) return "review";
1348
- if (path7 === "/console" || path7.startsWith("/console/") || path7.startsWith("/api/v1/brain")) return "ops";
1349
- if (path7 === "/api/v1/health") return "health";
1338
+ function poolOf(path8) {
1339
+ if (path8 === "/api/v1/analyze" || path8.startsWith("/api/v1/analyze/")) return "biz";
1340
+ if (path8 === "/api/v1/review" || path8.startsWith("/api/v1/review/")) return "review";
1341
+ if (path8 === "/console" || path8.startsWith("/console/") || path8.startsWith("/api/v1/brain")) return "ops";
1342
+ if (path8 === "/api/v1/health") return "health";
1350
1343
  return "other";
1351
1344
  }
1352
1345
  function poolLimit(name) {
@@ -1779,6 +1772,8 @@ var init_platform_traits = __esm({
1779
1772
 
1780
1773
  // src/engine/logic-rules.ts
1781
1774
  import * as fs from "fs";
1775
+ import * as path2 from "path";
1776
+ import * as os from "os";
1782
1777
  function hasExecBypassChain(actionDetail) {
1783
1778
  const execAfter = "&&|\\|\\||;|\\n|\\|";
1784
1779
  return />\s*[/~]\S*\.(sh|py|pl|rb)\b/.test(actionDetail) && new RegExp(`(?:${execAfter})\\s*(?:bash|sh|zsh|dash|python|perl|ruby|node)`).test(actionDetail) || /\|\s*(?:bash|sh|zsh|dash|python|perl|ruby|node|crontab|at)\b/.test(actionDetail);
@@ -1805,7 +1800,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
1805
1800
  os: String(sp.os || "linux").toLowerCase()
1806
1801
  }));
1807
1802
  }
1808
- function _scopeOf(os4, path7) {
1803
+ function _scopeOf(os5, path8) {
1809
1804
  if (!_scopeIndex) {
1810
1805
  _scopeIndex = /* @__PURE__ */ new Map();
1811
1806
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -1813,7 +1808,7 @@ function _scopeOf(os4, path7) {
1813
1808
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
1814
1809
  }
1815
1810
  }
1816
- return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path7}`) || "root";
1811
+ return _scopeIndex.get(`${String(os5 || "linux").toLowerCase()}|${path8}`) || "root";
1817
1812
  }
1818
1813
  function getSensitivePathsForOs(osType) {
1819
1814
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -1855,6 +1850,188 @@ function getSensitivePathsForOsBuiltin(osType) {
1855
1850
  }
1856
1851
  return { root: ROOT_SENSITIVE_PATHS, home: HOME_SENSITIVE_PATHS, credential: CREDENTIAL_PATHS };
1857
1852
  }
1853
+ function declaredWritePaths(actionDetailRaw, osType) {
1854
+ const m = actionDetailRaw.match(DECLARED_WRITE_PATH_RE);
1855
+ if (m) return [m[1]];
1856
+ const j = actionDetailRaw.match(DECLARED_WRITE_PATH_JSON_RE);
1857
+ if (j) return [j[1]];
1858
+ return extractFilePaths(actionDetailRaw, osType).slice(0, 1);
1859
+ }
1860
+ function normalizePathForCompare(p, cwd) {
1861
+ if (!p) return p;
1862
+ let expanded = p;
1863
+ if (expanded === "~" || expanded.startsWith("~/") || expanded.startsWith("~\\")) {
1864
+ expanded = os.homedir() + expanded.slice(1);
1865
+ }
1866
+ if (!path2.isAbsolute(expanded) && cwd) expanded = path2.join(cwd, expanded);
1867
+ return path2.normalize(expanded);
1868
+ }
1869
+ function pathIsSameOrUnder(p, base) {
1870
+ if (!p || !base) return false;
1871
+ if (p === base) return true;
1872
+ return p.startsWith(base.replace(/[\\/]+$/, "") + path2.sep);
1873
+ }
1874
+ function isProtectedWritePath(p) {
1875
+ if (!p) return false;
1876
+ if (PROTECTED_WRITE_PREFIXES.some((prefix) => p.startsWith(prefix))) return true;
1877
+ const home = os.homedir();
1878
+ if (home && (p === home || p.startsWith(home + path2.sep))) {
1879
+ const rel = p.slice(home.length).replace(/^[\\/]+/, "");
1880
+ const first = rel.split(/[\\/]/)[0] || "";
1881
+ return PROTECTED_HOME_ENTRIES.has(first);
1882
+ }
1883
+ return false;
1884
+ }
1885
+ function historyCommandText(histDetailRaw) {
1886
+ const text = histDetailRaw.trim();
1887
+ if (text.startsWith("{")) {
1888
+ try {
1889
+ const obj = JSON.parse(text);
1890
+ if (obj && typeof obj === "object") {
1891
+ for (const key of ["command", "cmd"]) {
1892
+ if (typeof obj[key] === "string" && obj[key].trim()) return obj[key];
1893
+ }
1894
+ }
1895
+ } catch {
1896
+ }
1897
+ }
1898
+ return histDetailRaw;
1899
+ }
1900
+ function parseHeadTailLimit(seg) {
1901
+ const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
1902
+ if (firstWord !== "head" && firstWord !== "tail") return null;
1903
+ const m = seg.match(HEAD_TAIL_LIMIT_RE);
1904
+ return m ? Number(m[1]) : 10;
1905
+ }
1906
+ function parseHeadTailLimitForPipeline(segments) {
1907
+ for (const rawSeg of segments) {
1908
+ const seg = rawSeg.trim();
1909
+ if (!seg) continue;
1910
+ if (seg.startsWith("head") || seg.startsWith("tail")) return parseHeadTailLimit(seg);
1911
+ }
1912
+ return null;
1913
+ }
1914
+ function historyReadCoverage(histType, histDetailRaw, readKeywords, writeKeywords) {
1915
+ const full = /* @__PURE__ */ new Set();
1916
+ const partial = /* @__PURE__ */ new Map();
1917
+ const addPartial = (paths, upto) => {
1918
+ for (const p of paths) {
1919
+ if (partial.has(p)) {
1920
+ const old = partial.get(p);
1921
+ partial.set(p, old == null || upto == null ? null : Math.max(old, upto));
1922
+ } else {
1923
+ partial.set(p, upto);
1924
+ }
1925
+ }
1926
+ };
1927
+ if (writeKeywords.some((kw) => histType.includes(kw))) return { full, partial };
1928
+ if (histType === "bash" || histType === "executebash" || histType === "terminal-executebash") {
1929
+ const segments = splitCommandSegments(historyCommandText(histDetailRaw));
1930
+ const words = segments.map((s) => s.trim().split(/\s+/)[0]?.toLowerCase() || "").filter(Boolean);
1931
+ const hasTruncatingPipe = words.some((w) => SHELL_TRUNCATING_CMDS.has(w));
1932
+ for (const rawSeg of segments) {
1933
+ const seg = rawSeg.trim();
1934
+ if (!seg) continue;
1935
+ const firstWord = seg.split(/\s+/)[0]?.toLowerCase() || "";
1936
+ const paths = extractFilePaths(seg);
1937
+ if (paths.length === 0) continue;
1938
+ if (SHELL_FULL_READ_CMDS.includes(firstWord)) {
1939
+ if (hasTruncatingPipe) addPartial(paths, parseHeadTailLimitForPipeline(segments));
1940
+ else for (const p of paths) full.add(p);
1941
+ } else if (firstWord === "head" || firstWord === "tail") {
1942
+ addPartial(paths, parseHeadTailLimit(seg));
1943
+ } else if (SHELL_PARTIAL_READ_CMDS.includes(firstWord)) {
1944
+ addPartial(paths, null);
1945
+ } else if (firstWord === "sed") {
1946
+ if (SED_INPLACE_RE.test(seg)) continue;
1947
+ const m = seg.match(SED_RANGE_RE);
1948
+ if (m) {
1949
+ if (m[2] === "$" && m[1] === "1") for (const p of paths) full.add(p);
1950
+ else addPartial(paths, null);
1951
+ } else {
1952
+ for (const p of paths) full.add(p);
1953
+ }
1954
+ }
1955
+ }
1956
+ return { full, partial };
1957
+ }
1958
+ let offset;
1959
+ let limit;
1960
+ const detail = histDetailRaw.trim();
1961
+ if (detail.startsWith("{")) {
1962
+ try {
1963
+ const obj = JSON.parse(detail);
1964
+ if (obj && typeof obj === "object") {
1965
+ offset = obj.offset;
1966
+ limit = obj.limit;
1967
+ }
1968
+ } catch {
1969
+ }
1970
+ }
1971
+ if (histType.includes("read")) {
1972
+ if (offset != null || limit != null) {
1973
+ const off = typeof offset === "number" ? offset : Number(offset) || 1;
1974
+ const lim = typeof limit === "number" ? limit : limit != null ? Number(limit) || null : null;
1975
+ const upto = off === 1 && lim != null ? off + lim - 1 : null;
1976
+ addPartial(extractFilePaths(detail), upto);
1977
+ } else {
1978
+ for (const p of extractFilePaths(detail)) full.add(p);
1979
+ }
1980
+ } else if (histType.includes("grep") || histType.includes("search")) {
1981
+ addPartial(extractFilePaths(detail), null);
1982
+ } else if (histType.includes("glob") || histType.includes("list")) {
1983
+ } else if (readKeywords.some((kw) => histType.includes(kw))) {
1984
+ addPartial(extractFilePaths(detail), null);
1985
+ }
1986
+ return { full, partial };
1987
+ }
1988
+ function fileHasAtMostLines(filePath, limit) {
1989
+ if (limit <= 0 || limit > PARTIAL_COVER_CHECK_MAX_LINES) return false;
1990
+ try {
1991
+ const fd = fs.openSync(filePath, "r");
1992
+ try {
1993
+ const buf = Buffer.alloc(64 * 1024);
1994
+ let lines = 0;
1995
+ for (; ; ) {
1996
+ const n = fs.readSync(fd, buf, 0, buf.length, null);
1997
+ if (n <= 0) break;
1998
+ for (let i = 0; i < n; i++) {
1999
+ if (buf[i] === 10) {
2000
+ lines++;
2001
+ if (lines > limit) return false;
2002
+ }
2003
+ }
2004
+ }
2005
+ return true;
2006
+ } finally {
2007
+ fs.closeSync(fd);
2008
+ }
2009
+ } catch {
2010
+ return false;
2011
+ }
2012
+ }
2013
+ function appendOnlyTargets(actionDetailRaw, osType) {
2014
+ const out = /* @__PURE__ */ new Set();
2015
+ for (const rawSeg of splitCommandSegments(actionDetailRaw)) {
2016
+ const seg = rawSeg.trim();
2017
+ if (!seg) continue;
2018
+ const segNoAppend = seg.replace(new RegExp(APPEND_REDIRECT_SOURCE, "g"), " ");
2019
+ const segNoQuotes = segNoAppend.replace(/'[^']*'|"[^"]*"/g, "");
2020
+ const hasOverwrite = /(?<![/\-=>])>\s*(?!&)\S/.test(segNoQuotes);
2021
+ if (hasOverwrite) continue;
2022
+ const re = new RegExp(APPEND_REDIRECT_SOURCE, "g");
2023
+ let m;
2024
+ while ((m = re.exec(seg)) !== null) {
2025
+ const p = m[1] || m[2] || m[3];
2026
+ if (p) out.add(p);
2027
+ }
2028
+ const firstWord = seg.split(/\s+/)[0]?.toLowerCase() || "";
2029
+ if (firstWord === "tee" && /(?:^|\s)(?:-a|--append)(?:\s|$)/.test(seg)) {
2030
+ for (const p of extractFilePaths(seg, osType)) out.add(p);
2031
+ }
2032
+ }
2033
+ return out;
2034
+ }
1858
2035
  function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWORDS, osType) {
1859
2036
  if (writeKeywords.some((kw) => actionType.includes(kw) || actionDetail.includes(kw))) return true;
1860
2037
  const { writeCommandRes } = getPlatformTraits(osType);
@@ -1894,7 +2071,12 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
1894
2071
  }
1895
2072
  function getIntentPatternsForOs(osType) {
1896
2073
  const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
1897
- if (effective) return effective;
2074
+ if (effective) {
2075
+ return effective.map((p) => ({
2076
+ ...p,
2077
+ allowIfWriteIntent: p.allowIfWriteIntent ?? INTENT_DEVIATION_PATTERNS.find((d) => d.reason === p.reason)?.allowIfWriteIntent ?? false
2078
+ }));
2079
+ }
1898
2080
  const accepted = acceptedOsValues(osType);
1899
2081
  return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
1900
2082
  }
@@ -1945,6 +2127,9 @@ function checkIntentConsistency(input) {
1945
2127
  );
1946
2128
  const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(actionDetail, kw));
1947
2129
  if (intentMatched && dangerousMatched) {
2130
+ if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
2131
+ continue;
2132
+ }
1948
2133
  return {
1949
2134
  allowed: false,
1950
2135
  reason: pattern.reason,
@@ -1965,7 +2150,16 @@ function runLogicCheck(input, opts) {
1965
2150
  const resolvedCwd = cwd || "/";
1966
2151
  const isExcludedType = EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p));
1967
2152
  if (!opts?.skipReadBeforeWrite) {
1968
- const rbwResult = checkReadBeforeWrite(actionType, actionDetail, actionHistory, input.reason, resolvedCwd, input.osType);
2153
+ const singleFileTools = opts?.agentExt?.extra_single_file_write_tools?.length ? /* @__PURE__ */ new Set([...SINGLE_FILE_WRITE_TOOLS, ...opts.agentExt.extra_single_file_write_tools]) : SINGLE_FILE_WRITE_TOOLS;
2154
+ const rbwResult = checkReadBeforeWrite(
2155
+ actionType,
2156
+ aNext.actionDetail,
2157
+ actionHistory,
2158
+ input.reason,
2159
+ resolvedCwd,
2160
+ input.osType,
2161
+ singleFileTools
2162
+ );
1969
2163
  if (rbwResult) return rbwResult;
1970
2164
  }
1971
2165
  const intentResult = checkIntentConsistency(input);
@@ -2068,7 +2262,8 @@ function extractFilePaths(text, osType) {
2068
2262
  }
2069
2263
  return [...new Set(paths)];
2070
2264
  }
2071
- function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, cwd, osType) {
2265
+ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason, cwd, osType, singleFileTools = SINGLE_FILE_WRITE_TOOLS) {
2266
+ const actionDetail = actionDetailRaw.toLowerCase();
2072
2267
  if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
2073
2268
  if (NON_WRITE_TOOLS.has(actionType)) return null;
2074
2269
  const isBashLike = actionType === "bash" || actionType === "executebash" || actionType === "terminal-executebash";
@@ -2109,7 +2304,11 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2109
2304
  const SOURCE_ARG_CMDS = new Set(_LOGIC.source_arg_commands ?? []);
2110
2305
  const REDIRECT_TARGET_RE = new RegExp(`>{1,2}\\s*(?!&)(?:'(/[^']+)'|"(/[^\\"]+)"|(/[^\\s;|&><'\\"]+))`);
2111
2306
  const targetPaths = [];
2112
- for (const seg of splitCommandSegments(actionDetail)) {
2307
+ const singleFileTool = singleFileTools.has(actionType);
2308
+ if (singleFileTool && MISSING_WRITE_PATH_RE.test(actionDetailRaw)) {
2309
+ return null;
2310
+ }
2311
+ for (const seg of singleFileTool ? [] : splitCommandSegments(actionDetailRaw)) {
2113
2312
  const trimmed = seg.trim();
2114
2313
  if (!trimmed) continue;
2115
2314
  const firstWord = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
@@ -2141,16 +2340,31 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2141
2340
  targetPaths.push(...segPathsFiltered);
2142
2341
  }
2143
2342
  }
2343
+ if (singleFileTool) {
2344
+ targetPaths.length = 0;
2345
+ targetPaths.push(...declaredWritePaths(actionDetailRaw, osType));
2346
+ }
2144
2347
  const uniqueTargetPaths = [...new Set(targetPaths)].filter((p) => !PSEUDO_FS_PREFIXES.some((pfx) => p.startsWith(pfx)));
2145
2348
  if (uniqueTargetPaths.length === 0) return null;
2146
- const historyReadPaths = /* @__PURE__ */ new Set();
2349
+ const historyFullReadPaths = /* @__PURE__ */ new Set();
2350
+ const historyPartialRead = /* @__PURE__ */ new Map();
2147
2351
  for (const action of actionHistory) {
2148
- const histDetail = action.actionDetail.toLowerCase();
2352
+ const histDetailRaw = action.actionDetail;
2149
2353
  const histType = action.actionType.toLowerCase();
2150
- const isRead = getPlatformTraits(osType).readKeywords.some((kw) => histType.includes(kw) || histDetail.includes(kw));
2151
- if (isRead) {
2152
- for (const p of extractFilePaths(histDetail, osType)) {
2153
- historyReadPaths.add(p);
2354
+ const traits = getPlatformTraits(osType);
2355
+ const coverage = historyReadCoverage(
2356
+ histType,
2357
+ histDetailRaw,
2358
+ traits.readKeywords,
2359
+ traits.writeKeywords
2360
+ );
2361
+ for (const p of coverage.full) historyFullReadPaths.add(p);
2362
+ for (const [p, upto] of coverage.partial) {
2363
+ if (historyPartialRead.has(p)) {
2364
+ const old = historyPartialRead.get(p);
2365
+ historyPartialRead.set(p, old == null || upto == null ? null : Math.max(old, upto));
2366
+ } else {
2367
+ historyPartialRead.set(p, upto);
2154
2368
  }
2155
2369
  }
2156
2370
  }
@@ -2163,18 +2377,49 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2163
2377
  if (filteredPaths.length === 0) {
2164
2378
  return null;
2165
2379
  }
2380
+ const normalizedTargets = filteredPaths.map((p) => normalizePathForCompare(p, cwd)).filter((p, i, arr) => p && arr.indexOf(p) === i);
2381
+ const normalizedFullReads = new Set(
2382
+ [...historyFullReadPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2383
+ );
2384
+ const normalizedPartialReads = /* @__PURE__ */ new Map();
2385
+ for (const [p, upto] of historyPartialRead) {
2386
+ const np = normalizePathForCompare(p, cwd);
2387
+ if (np) normalizedPartialReads.set(np, upto);
2388
+ }
2389
+ const appendTargets = appendOnlyTargets(actionDetailRaw, osType);
2390
+ if (APPEND_MODE_RE.test(actionDetailRaw)) {
2391
+ for (const p of filteredPaths) appendTargets.add(p);
2392
+ }
2393
+ let checkTargets = normalizedTargets;
2394
+ if (appendTargets.size > 0) {
2395
+ const appendNorm = new Set(
2396
+ [...appendTargets].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2397
+ );
2398
+ checkTargets = normalizedTargets.filter((p) => !([...appendNorm].some((ap) => pathIsSameOrUnder(p, ap) || pathIsSameOrUnder(ap, p)) && !isProtectedWritePath(p)));
2399
+ if (checkTargets.length === 0) return null;
2400
+ }
2166
2401
  const unreadPaths = [];
2167
- for (const path7 of filteredPaths) {
2168
- const hasRead = [...historyReadPaths].some(
2169
- (rp) => path7 === rp || path7.startsWith(rp) || rp.startsWith(path7)
2402
+ for (const path8 of checkTargets) {
2403
+ const isFullRead = [...normalizedFullReads].some(
2404
+ (rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
2170
2405
  );
2171
- if (!hasRead) {
2172
- let isCreate = !fs.existsSync(path7);
2406
+ let isPartialCovered = false;
2407
+ if (!isFullRead) {
2408
+ for (const [pp, upto] of normalizedPartialReads) {
2409
+ if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
2410
+ if (upto != null && fileHasAtMostLines(path8, upto)) {
2411
+ isPartialCovered = true;
2412
+ break;
2413
+ }
2414
+ }
2415
+ }
2416
+ if (!isFullRead && !isPartialCovered) {
2417
+ let isCreate = !fs.existsSync(path8);
2173
2418
  if (!isCreate) {
2174
2419
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
2175
2420
  }
2176
2421
  if (!isCreate) {
2177
- unreadPaths.push(path7);
2422
+ unreadPaths.push(path8);
2178
2423
  }
2179
2424
  }
2180
2425
  }
@@ -2351,7 +2596,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2351
2596
  violatedLayers: ["L2.1"]
2352
2597
  };
2353
2598
  }
2354
- var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
2599
+ var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
2355
2600
  var init_logic_rules = __esm({
2356
2601
  "src/engine/logic-rules.ts"() {
2357
2602
  "use strict";
@@ -2368,16 +2613,16 @@ var init_logic_rules = __esm({
2368
2613
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
2369
2614
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
2370
2615
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
2371
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2616
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2372
2617
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
2373
2618
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
2374
- CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2619
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2375
2620
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
2376
2621
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
2377
- CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2622
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2378
2623
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
2379
2624
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
2380
- CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2625
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2381
2626
  _scopeIndex = null;
2382
2627
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
2383
2628
  "ask_user_question",
@@ -2400,6 +2645,23 @@ var init_logic_rules = __esm({
2400
2645
  ]);
2401
2646
  NON_WRITE_TOOL_PREFIXES = _LOGIC.non_write_tool_prefixes ?? [];
2402
2647
  PSEUDO_FS_PREFIXES = ["/sys/", "/proc/", "/dev/", "/run/"];
2648
+ SINGLE_FILE_WRITE_TOOLS = new Set(
2649
+ _LOGIC.single_file_write_tools ?? []
2650
+ );
2651
+ WRITE_INTENT_KEYWORDS = _LOGIC.write_intent_keywords ?? [];
2652
+ MISSING_WRITE_PATH_RE = /(?:写入文件|编辑文件|写入|编辑)\s*[::]\s*\?/;
2653
+ DECLARED_WRITE_PATH_RE = /(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*([~./][^\s—|,;]+)/;
2654
+ DECLARED_WRITE_PATH_JSON_RE = /"(?:file_path|filePath|path)"\s*:\s*"([^"]+)"/;
2655
+ PROTECTED_WRITE_PREFIXES = _LOGIC.protected_write_prefixes ?? [];
2656
+ PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
2657
+ APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
2658
+ APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
2659
+ SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
2660
+ SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
2661
+ SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
2662
+ HEAD_TAIL_LIMIT_RE = /(?:-n\s*|-\s*)(\d+)/;
2663
+ SED_RANGE_RE = /-n\s+['"]?(\d+)\s*,\s*(\d+|\$)\s*p/;
2664
+ PARTIAL_COVER_CHECK_MAX_LINES = 1e5;
2403
2665
  WRITE_KEYWORDS = ["write", "\u5199\u5165", "save", "\u4FDD\u5B58", "modify", "\u4FEE\u6539", "update", "\u66F4\u65B0", "delete", "\u5220\u9664", "remove", "\u79FB\u9664", "create", "\u521B\u5EFA", "append", "\u8FFD\u52A0", "truncate", "\u622A\u65AD", "overwrite", "\u8986\u76D6", "replace", "\u66FF\u6362", "edit"];
2404
2666
  SED_INPLACE_RE = /\bsed\s+(?:-\S+\s+)*(?:-[a-zA-Z]*i[a-zA-Z]*|--in-place)\b/i;
2405
2667
  DEVNULL_REDIRECT_RE = /(?:2|&|1)?\s*>\s*\/dev\/null\b/g;
@@ -2418,7 +2680,8 @@ var init_logic_rules = __esm({
2418
2680
  intentKeywords: p.intent_keywords,
2419
2681
  dangerousActions: p.dangerous_actions,
2420
2682
  reason: p.reason,
2421
- os: String(p.os || "linux").toLowerCase()
2683
+ os: String(p.os || "linux").toLowerCase(),
2684
+ allowIfWriteIntent: p.allow_if_write_intent === true
2422
2685
  }));
2423
2686
  })();
2424
2687
  COMBO_STAGES = (() => {
@@ -2459,11 +2722,11 @@ var init_logic_rules = __esm({
2459
2722
 
2460
2723
  // src/engine/asset-dir.ts
2461
2724
  import { existsSync as existsSync5 } from "fs";
2462
- import { join as join5, resolve as resolve3 } from "path";
2725
+ import { join as join6, resolve as resolve3 } from "path";
2463
2726
  function assetDirCandidates(moduleDir, name) {
2464
2727
  const root = getRulesRoot();
2465
2728
  if (root) {
2466
- const p = join5(root, name);
2729
+ const p = join6(root, name);
2467
2730
  return [p, p];
2468
2731
  }
2469
2732
  return [
@@ -2682,7 +2945,7 @@ __export(runtime_config_exports, {
2682
2945
  updateSkillEnabled: () => updateSkillEnabled
2683
2946
  });
2684
2947
  import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
2685
- import { join as join6 } from "path";
2948
+ import { join as join7 } from "path";
2686
2949
  import { fileURLToPath as fileURLToPath4 } from "url";
2687
2950
  import { dirname as dirname4 } from "path";
2688
2951
  function runtimeDir() {
@@ -2818,8 +3081,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
2818
3081
  function _filterRulesByOs(rules, osType) {
2819
3082
  const accepted = acceptedOsValues(osType);
2820
3083
  return rules.filter((r) => {
2821
- const os4 = String(r.os || "linux").toLowerCase();
2822
- return os4 === "all" || accepted.includes(os4);
3084
+ const os5 = String(r.os || "linux").toLowerCase();
3085
+ return os5 === "all" || accepted.includes(os5);
2823
3086
  });
2824
3087
  }
2825
3088
  function _userCustomRules(runtime, layers, requiredKey) {
@@ -3021,7 +3284,7 @@ function _l2SensitivePathsToRules() {
3021
3284
  const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
3022
3285
  const all = [...root, ...home, ...credential];
3023
3286
  for (const sp of all) {
3024
- const os4 = String(sp.os || "linux").toLowerCase();
3287
+ const os5 = String(sp.os || "linux").toLowerCase();
3025
3288
  const denyMode = sp.denyMode || _deriveDenyMode({
3026
3289
  deny_mode: sp.deny_mode,
3027
3290
  credential: sp.credential,
@@ -3031,7 +3294,7 @@ function _l2SensitivePathsToRules() {
3031
3294
  // id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
3032
3295
  // hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
3033
3296
  // Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
3034
- id: `path_${os4}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3297
+ id: `path_${os5}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3035
3298
  path: sp.path,
3036
3299
  risk_level: sp.riskLevel,
3037
3300
  desc: sp.desc,
@@ -3040,7 +3303,7 @@ function _l2SensitivePathsToRules() {
3040
3303
  skip_l3_on_disabled: true,
3041
3304
  enabled: true,
3042
3305
  builtin: true,
3043
- os: os4
3306
+ os: os5
3044
3307
  };
3045
3308
  _syncDenyModeFields(rule);
3046
3309
  if (sp.dirDelOnly) rule.dir_del_only = true;
@@ -3058,6 +3321,9 @@ function _l2IntentPatternsToRules() {
3058
3321
  intent_keywords: pat.intentKeywords,
3059
3322
  dangerous_actions: pat.dangerousActions,
3060
3323
  reason: pat.reason,
3324
+ // 旧 runtime 里没有这个字段:缺省 false,但 getIntentPatternsForOs 会按
3325
+ // reason 回填内置默认值,避免旧配置让新豁免失效。
3326
+ allow_if_write_intent: pat.allowIfWriteIntent,
3061
3327
  skip_l3_on_disabled: true,
3062
3328
  enabled: true,
3063
3329
  builtin: true
@@ -3128,7 +3394,7 @@ function _l3SkillsToRules() {
3128
3394
  function _scenarioRulesToDefaults() {
3129
3395
  const out = {};
3130
3396
  const _root = getRulesRoot();
3131
- const scenDir = _root ? join6(_root, "scenarios") : existsSync7(_SCENARIOS_DIR_PROD) ? _SCENARIOS_DIR_PROD : existsSync7(_SCENARIOS_DIR_DEV) ? _SCENARIOS_DIR_DEV : _SCENARIOS_DIR_PROD;
3397
+ const scenDir = _root ? join7(_root, "scenarios") : existsSync7(_SCENARIOS_DIR_PROD) ? _SCENARIOS_DIR_PROD : existsSync7(_SCENARIOS_DIR_DEV) ? _SCENARIOS_DIR_DEV : _SCENARIOS_DIR_PROD;
3132
3398
  if (!existsSync7(scenDir)) return out;
3133
3399
  let entries;
3134
3400
  try {
@@ -3137,7 +3403,7 @@ function _scenarioRulesToDefaults() {
3137
3403
  return out;
3138
3404
  }
3139
3405
  for (const scenarioId of entries) {
3140
- const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join6(scenDir, scenarioId, "rules.json");
3406
+ const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join7(scenDir, scenarioId, "rules.json");
3141
3407
  if (!existsSync7(rulesFile)) continue;
3142
3408
  let data;
3143
3409
  try {
@@ -3178,7 +3444,7 @@ function _scenarioRulesToDefaults() {
3178
3444
  function _agentRulesToDefaults() {
3179
3445
  const out = {};
3180
3446
  const _root = getRulesRoot();
3181
- const agentsDir = _root ? join6(_root, "agents") : existsSync7(_AGENTS_DIR_PROD) ? _AGENTS_DIR_PROD : existsSync7(_AGENTS_DIR_DEV) ? _AGENTS_DIR_DEV : _AGENTS_DIR_PROD;
3447
+ const agentsDir = _root ? join7(_root, "agents") : existsSync7(_AGENTS_DIR_PROD) ? _AGENTS_DIR_PROD : existsSync7(_AGENTS_DIR_DEV) ? _AGENTS_DIR_DEV : _AGENTS_DIR_PROD;
3182
3448
  if (!existsSync7(agentsDir)) return out;
3183
3449
  let entries;
3184
3450
  try {
@@ -3187,7 +3453,7 @@ function _agentRulesToDefaults() {
3187
3453
  return out;
3188
3454
  }
3189
3455
  for (const agentId of entries) {
3190
- const rulesFile = join6(agentsDir, agentId, "rules.json");
3456
+ const rulesFile = join7(agentsDir, agentId, "rules.json");
3191
3457
  if (!existsSync7(rulesFile)) continue;
3192
3458
  let data;
3193
3459
  try {
@@ -3220,6 +3486,11 @@ function _agentRulesToDefaults() {
3220
3486
  category_enabled: true,
3221
3487
  category_desc: "agent \u4E13\u5C5E\u654F\u611F\u8DEF\u5F84\uFF08L1 \u672B\u5C3E\u8FFD\u52A0\uFF09",
3222
3488
  rules: (data.extra_sensitive_paths || []).map((sp) => ({ ...sp, enabled: true, builtin: true }))
3489
+ },
3490
+ extra_single_file_write_tools: {
3491
+ category_enabled: true,
3492
+ category_desc: "agent \u4E13\u5C5E\u5355\u6587\u4EF6\u5199\u5DE5\u5177\uFF08read_before_write \u53EA\u53D6\u58F0\u660E\u8DEF\u5F84\uFF09",
3493
+ rules: (data.extra_single_file_write_tools || []).map((v) => ({ value: v, enabled: true, builtin: true }))
3223
3494
  }
3224
3495
  };
3225
3496
  }
@@ -3568,8 +3839,8 @@ function _filterDefaultsByOs(rules, osType) {
3568
3839
  const accepted = acceptedOsValues(osType);
3569
3840
  return rules.filter((r) => {
3570
3841
  if (!r.os) return true;
3571
- const os4 = String(r.os).toLowerCase();
3572
- return os4 === "all" || accepted.includes(os4);
3842
+ const os5 = String(r.os).toLowerCase();
3843
+ return os5 === "all" || accepted.includes(os5);
3573
3844
  });
3574
3845
  }
3575
3846
  function _hasRulesForOs(rules, osType) {
@@ -3694,7 +3965,8 @@ function effectiveIntentPatterns(osType) {
3694
3965
  intentKeywords: r.intent_keywords || [],
3695
3966
  dangerousActions: r.dangerous_actions || [],
3696
3967
  reason: String(r.reason || ""),
3697
- os: String(r.os || "linux").toLowerCase()
3968
+ os: String(r.os || "linux").toLowerCase(),
3969
+ allowIfWriteIntent: r.allow_if_write_intent === true
3698
3970
  }));
3699
3971
  });
3700
3972
  }
@@ -3799,12 +4071,12 @@ function addCustomSkill(skillId, category, keywords, content) {
3799
4071
  );
3800
4072
  }
3801
4073
  const runtime = loadRuntimeConfig();
3802
- const skillsDir = join6(getRuntimeConfigDir(), "agent_moss_skills");
4074
+ const skillsDir = join7(getRuntimeConfigDir(), "agent_moss_skills");
3803
4075
  try {
3804
4076
  mkdirSync2(skillsDir, { recursive: true });
3805
4077
  } catch {
3806
4078
  }
3807
- writeFileSync(join6(skillsDir, `${skillId}.md`), content, "utf-8");
4079
+ writeFileSync(join7(skillsDir, `${skillId}.md`), content, "utf-8");
3808
4080
  const l3 = runtime.L3_skills || (runtime.L3_skills = {});
3809
4081
  const cat = l3[category] || (l3[category] = { category_enabled: true, category_desc: "", skills: [] });
3810
4082
  (cat.skills || (cat.skills = [])).push({ id: skillId, keywords, enabled: true, builtin: false });
@@ -3819,7 +4091,7 @@ function deleteCustomSkill(skillId, category) {
3819
4091
  if (idx >= 0) {
3820
4092
  if (skills[idx].builtin) return null;
3821
4093
  skills.splice(idx, 1);
3822
- const skillPath = join6(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
4094
+ const skillPath = join7(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
3823
4095
  try {
3824
4096
  if (existsSync7(skillPath)) unlinkSync(skillPath);
3825
4097
  } catch {
@@ -3882,6 +4154,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
3882
4154
  read_only: r.read_only,
3883
4155
  deny_mode: r.deny_mode
3884
4156
  }));
4157
+ const singleFileWriteTools = _agentCategoryEnabledRules(agentData.extra_single_file_write_tools).filter((r) => r.value).map((r) => String(r.value).toLowerCase());
3885
4158
  return {
3886
4159
  agent_id: agentId,
3887
4160
  description: "",
@@ -3890,6 +4163,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
3890
4163
  extra_sensitive_paths: sensitivePaths,
3891
4164
  builtin_safe_skills: safeSkills.filter((r) => r.value).map((r) => r.value),
3892
4165
  builtin_safe_action_types: safeAction.filter((r) => r.value).map((r) => r.value),
4166
+ extra_single_file_write_tools: singleFileWriteTools,
3893
4167
  extra_skills: []
3894
4168
  };
3895
4169
  }
@@ -3968,6 +4242,7 @@ function getEnabledScenarioExtensions(runtime, scenarioId) {
3968
4242
  extra_sensitive_paths: sensitivePaths,
3969
4243
  builtin_safe_skills: [],
3970
4244
  builtin_safe_action_types: [],
4245
+ extra_single_file_write_tools: [],
3971
4246
  extra_skills: []
3972
4247
  };
3973
4248
  }
@@ -4028,7 +4303,7 @@ var init_runtime_config = __esm({
4028
4303
  __dirname4 = dirname4(fileURLToPath4(import.meta.url));
4029
4304
  ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
4030
4305
  RUNTIME_CONFIG_DIR = runtimeDir();
4031
- RUNTIME_CONFIG_PATH = join6(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
4306
+ RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
4032
4307
  LAYER_DISABLE_ENV = {
4033
4308
  L1_heuristic: "AGENT_MOSS_DISABLE_HEURISTIC",
4034
4309
  L2_logic_rules: "AGENT_MOSS_DISABLE_LOGIC_RULES",
@@ -4056,10 +4331,10 @@ var init_runtime_config = __esm({
4056
4331
  intent_consistency: ["intent_keywords", "reason"]
4057
4332
  };
4058
4333
  hasRuntimeConfigCache = /* @__PURE__ */ new Map();
4059
- _AGENTS_DIR_PROD = join6(__dirname4, "agents");
4060
- _AGENTS_DIR_DEV = join6(__dirname4, "..", "..", "..", "agent_moss", "agents");
4061
- _SCENARIOS_DIR_PROD = join6(__dirname4, "scenarios");
4062
- _SCENARIOS_DIR_DEV = join6(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
4334
+ _AGENTS_DIR_PROD = join7(__dirname4, "agents");
4335
+ _AGENTS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "agents");
4336
+ _SCENARIOS_DIR_PROD = join7(__dirname4, "scenarios");
4337
+ _SCENARIOS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
4063
4338
  _effectiveCache = /* @__PURE__ */ new WeakMap();
4064
4339
  SKILL_ID_RE = /^[A-Za-z0-9_-]+$/;
4065
4340
  registerRuntimeConfigBridge({
@@ -4102,7 +4377,7 @@ __export(config_exports, {
4102
4377
  wildcardToRegExp: () => wildcardToRegExp
4103
4378
  });
4104
4379
  import fs2 from "fs";
4105
- import path2 from "path";
4380
+ import path3 from "path";
4106
4381
  import { fileURLToPath as fileURLToPath5 } from "url";
4107
4382
  function loadConfigFile(filePath) {
4108
4383
  try {
@@ -4115,17 +4390,17 @@ function loadConfigFile(filePath) {
4115
4390
  function resolveConfigPath() {
4116
4391
  const envPath = process.env.AGENT_MOSS_CONFIG_PATH;
4117
4392
  if (envPath) return envPath;
4118
- const userConfig = path2.join(getConfigDir(), "config.json");
4393
+ const userConfig = path3.join(getConfigDir(), "config.json");
4119
4394
  if (fs2.existsSync(userConfig)) return userConfig;
4120
4395
  const defaultCandidates = [
4121
- path2.join(__configModuleDir, "config.json.example"),
4122
- path2.join(__configModuleDir, "..", "config.json.example"),
4123
- path2.join(__configModuleDir, "..", "..", "agent_moss", "infra", "config.json.example"),
4124
- path2.join(__configModuleDir, "..", "..", "..", "agent_moss", "infra", "config.json.example")
4396
+ path3.join(__configModuleDir, "config.json.example"),
4397
+ path3.join(__configModuleDir, "..", "config.json.example"),
4398
+ path3.join(__configModuleDir, "..", "..", "agent_moss", "infra", "config.json.example"),
4399
+ path3.join(__configModuleDir, "..", "..", "..", "agent_moss", "infra", "config.json.example")
4125
4400
  ];
4126
4401
  const defaultConfig = defaultCandidates.find((p) => fs2.existsSync(p));
4127
4402
  if (defaultConfig) {
4128
- const configDir = path2.dirname(userConfig);
4403
+ const configDir = path3.dirname(userConfig);
4129
4404
  fs2.mkdirSync(configDir, { recursive: true });
4130
4405
  const pkgConfig = loadConfigFile(defaultConfig);
4131
4406
  const safeConfig = pkgConfig ? { ...pkgConfig, llm: { ...pkgConfig.llm, api_key: "" } } : {};
@@ -4355,7 +4630,7 @@ var init_config = __esm({
4355
4630
  init_rules_mode();
4356
4631
  __configModuleDir = (() => {
4357
4632
  try {
4358
- return path2.dirname(fileURLToPath5(import.meta.url));
4633
+ return path3.dirname(fileURLToPath5(import.meta.url));
4359
4634
  } catch {
4360
4635
  return typeof __dirname !== "undefined" ? __dirname : process.cwd();
4361
4636
  }
@@ -4378,11 +4653,11 @@ var init_config = __esm({
4378
4653
  };
4379
4654
  })();
4380
4655
  USER_RULES_PATHS = [
4381
- path2.join(__configModuleDir, "rules", "user_rules.json"),
4656
+ path3.join(__configModuleDir, "rules", "user_rules.json"),
4382
4657
  // 源在 ts/src/rules(一般不存在)
4383
- path2.join(__configModuleDir, "..", "rules", "user_rules.json"),
4658
+ path3.join(__configModuleDir, "..", "rules", "user_rules.json"),
4384
4659
  // dist: dist/engine/../rules = dist/rules ✅
4385
- path2.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
4660
+ path3.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
4386
4661
  // dev src: ts/src/../../agent_moss
4387
4662
  ];
4388
4663
  customRules = loadCustomRules();
@@ -4400,11 +4675,11 @@ var init_config = __esm({
4400
4675
 
4401
4676
  // src/agents/index.ts
4402
4677
  import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
4403
- import { resolve as resolve5, dirname as dirname5, join as join7 } from "path";
4678
+ import { resolve as resolve5, dirname as dirname5, join as join8 } from "path";
4404
4679
  import { fileURLToPath as fileURLToPath6 } from "url";
4405
4680
  function resolveAgentsDir() {
4406
4681
  const root = getRulesRoot();
4407
- if (root) return join7(root, "agents");
4682
+ if (root) return join8(root, "agents");
4408
4683
  if (existsSync8(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
4409
4684
  if (existsSync8(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
4410
4685
  return AGENTS_DIR_PROD;
@@ -4465,6 +4740,7 @@ function mergeAgentExtensions(...exts) {
4465
4740
  extra_sensitive_paths: nonNull.flatMap((e) => e.extra_sensitive_paths || []),
4466
4741
  builtin_safe_skills: nonNull.flatMap((e) => e.builtin_safe_skills || []),
4467
4742
  builtin_safe_action_types: nonNull.flatMap((e) => e.builtin_safe_action_types || []),
4743
+ extra_single_file_write_tools: nonNull.flatMap((e) => e.extra_single_file_write_tools || []),
4468
4744
  extra_skills: nonNull.flatMap((e) => e.extra_skills || [])
4469
4745
  };
4470
4746
  }
@@ -4486,11 +4762,11 @@ var init_agents = __esm({
4486
4762
 
4487
4763
  // src/scenarios/index.ts
4488
4764
  import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
4489
- import { resolve as resolve6, dirname as dirname6, join as join8 } from "path";
4765
+ import { resolve as resolve6, dirname as dirname6, join as join9 } from "path";
4490
4766
  import { fileURLToPath as fileURLToPath7 } from "url";
4491
4767
  function resolveScenariosDir() {
4492
4768
  const root = getRulesRoot();
4493
- if (root) return join8(root, "scenarios");
4769
+ if (root) return join9(root, "scenarios");
4494
4770
  if (existsSync9(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
4495
4771
  if (existsSync9(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
4496
4772
  return SCENARIOS_DIR_PROD;
@@ -4548,6 +4824,7 @@ function getScenarioExtensions(scenarioId) {
4548
4824
  extra_sensitive_paths: data.extra_sensitive_paths || [],
4549
4825
  builtin_safe_skills: data.builtin_safe_skills || [],
4550
4826
  builtin_safe_action_types: data.builtin_safe_action_types || [],
4827
+ extra_single_file_write_tools: data.extra_single_file_write_tools || [],
4551
4828
  extra_skills: data.extra_skills || []
4552
4829
  };
4553
4830
  } catch (e) {
@@ -4980,16 +5257,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4980
5257
  if (String(osType || "").toLowerCase() === "windows") {
4981
5258
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
4982
5259
  }
4983
- const pathMatches = (text, path7) => {
4984
- const parts = path7.split(/(\(\?!.*?\))/);
5260
+ const pathMatches = (text, path8) => {
5261
+ const parts = path8.split(/(\(\?!.*?\))/);
4985
5262
  const escaped = parts.map((part) => {
4986
5263
  if (part.startsWith("(?!")) return part;
4987
5264
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4988
5265
  }).join("");
4989
- const re = path7.startsWith(".") || path7.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
5266
+ const re = path8.startsWith(".") || path8.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4990
5267
  return re.test(text);
4991
5268
  };
4992
- const pathMatchesAny = (path7) => pathScanTexts.some((t) => pathMatches(t, path7));
5269
+ const pathMatchesAny = (path8) => pathScanTexts.some((t) => pathMatches(t, path8));
4993
5270
  for (const sp of rootPaths) {
4994
5271
  if (pathMatchesAny(sp.path.toLowerCase())) {
4995
5272
  if (keygenGenerate) continue;
@@ -5132,8 +5409,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5132
5409
  }
5133
5410
  return null;
5134
5411
  }
5135
- function isHomeValue(path7) {
5136
- let p = path7.trim().toLowerCase();
5412
+ function isHomeValue(path8) {
5413
+ let p = path8.trim().toLowerCase();
5137
5414
  if (p.startsWith("$(") && p.endsWith(")")) {
5138
5415
  const inner = p.slice(2, -1).trim();
5139
5416
  return HOME_TARGET_RE.test(" " + inner);
@@ -5189,15 +5466,15 @@ function checkHomeDeletion(actionType, actionDetail) {
5189
5466
  }
5190
5467
  const assigned = {};
5191
5468
  for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
5192
- for (const [varName, path7] of Object.entries(assigned)) {
5193
- if (!isHomeValue(path7)) continue;
5469
+ for (const [varName, path8] of Object.entries(assigned)) {
5470
+ if (!isHomeValue(path8)) continue;
5194
5471
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
5195
5472
  for (const seg of segs) {
5196
5473
  if (!isDeleteCommand(seg)) continue;
5197
5474
  if (varRefRe.test(seg)) {
5198
5475
  return {
5199
5476
  allowed: false,
5200
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path7}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5477
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path8}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5201
5478
  riskLevel: "high",
5202
5479
  riskType: "script_execution",
5203
5480
  confidence: 90,
@@ -5493,7 +5770,7 @@ var init_template_loader = __esm({
5493
5770
 
5494
5771
  // src/engine/script-analyzer.ts
5495
5772
  import { readFileSync as readFileSync10 } from "fs";
5496
- import { resolve as resolve8, join as join9 } from "path";
5773
+ import { resolve as resolve8, join as join10 } from "path";
5497
5774
  function emptyResult() {
5498
5775
  return { scriptPath: "", scriptContent: "", matchedKeywords: [], lineCount: 0, isSuspicious: false, error: "", riskLevel: "", riskReason: "" };
5499
5776
  }
@@ -5546,7 +5823,7 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
5546
5823
  }
5547
5824
  function readScriptContent(scriptPath, maxLines = 500) {
5548
5825
  try {
5549
- const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join9(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
5826
+ const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join10(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
5550
5827
  const raw = readFileSync10(expandedPath, "utf-8");
5551
5828
  const lines = raw.split("\n").slice(0, maxLines);
5552
5829
  return { content: lines.join("\n"), lineCount: lines.length, error: "" };
@@ -6001,15 +6278,15 @@ function parseShellString(s) {
6001
6278
  let m;
6002
6279
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
6003
6280
  const interp = m[1];
6004
- const path7 = m[2].trim();
6281
+ const path8 = m[2].trim();
6005
6282
  let rest = m[3].trim();
6006
- if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6283
+ if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6007
6284
  rest = rest.split(/[;|&<>]/)[0].trim();
6008
6285
  const args = [];
6009
6286
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6010
6287
  args.push(tm[1] ? tm[2] : tm[3]);
6011
6288
  }
6012
- return { path: path7, args, interpreter: interp };
6289
+ return { path: path8, args, interpreter: interp };
6013
6290
  }
6014
6291
  return null;
6015
6292
  }
@@ -6055,9 +6332,9 @@ function extractCallsFromTree(tree, reachableLines) {
6055
6332
  }
6056
6333
  if (allStr && elts.length >= 2) {
6057
6334
  const interp = elts[0];
6058
- const path7 = elts[1];
6059
- if (!path7.startsWith("-") && !path7.startsWith("$") && !path7.includes("/dev/")) {
6060
- add({ path: path7, args: elts.slice(2), interpreter: interp });
6335
+ const path8 = elts[1];
6336
+ if (!path8.startsWith("-") && !path8.startsWith("$") && !path8.includes("/dev/")) {
6337
+ add({ path: path8, args: elts.slice(2), interpreter: interp });
6061
6338
  return true;
6062
6339
  }
6063
6340
  }
@@ -6097,15 +6374,15 @@ function extractCallsRegex(content) {
6097
6374
  let m;
6098
6375
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
6099
6376
  const interp = m[1];
6100
- const path7 = m[2].trim();
6377
+ const path8 = m[2].trim();
6101
6378
  let rest = m[3].trim();
6102
- if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6379
+ if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6103
6380
  rest = rest.split(/[;|&<>]/)[0].trim();
6104
6381
  const args = [];
6105
6382
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6106
6383
  args.push(tm[1] ? tm[2] : tm[3]);
6107
6384
  }
6108
- calls.push({ path: path7, args, interpreter: interp });
6385
+ calls.push({ path: path8, args, interpreter: interp });
6109
6386
  }
6110
6387
  return calls;
6111
6388
  }
@@ -6888,15 +7165,15 @@ function extractCallsFromContent(content) {
6888
7165
  CHILD_CALL_RE2.lastIndex = 0;
6889
7166
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
6890
7167
  const interp = m[1];
6891
- const path7 = m[2].trim();
7168
+ const path8 = m[2].trim();
6892
7169
  let rest = m[3].trim();
6893
- if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
7170
+ if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6894
7171
  rest = rest.split(/[;|&<>]/)[0].trim();
6895
7172
  const args = [];
6896
7173
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6897
7174
  args.push(tm[1] ? tm[2] : tm[3]);
6898
7175
  }
6899
- calls.push({ path: path7, args, interpreter: interp });
7176
+ calls.push({ path: path8, args, interpreter: interp });
6900
7177
  }
6901
7178
  return calls;
6902
7179
  }
@@ -6965,8 +7242,8 @@ var init_backends = __esm({
6965
7242
 
6966
7243
  // src/engine/script-engine/tracker.ts
6967
7244
  import * as fs3 from "fs";
6968
- import * as path3 from "path";
6969
- import * as os from "os";
7245
+ import * as path4 from "path";
7246
+ import * as os2 from "os";
6970
7247
  function maxFileSizeFromEnv() {
6971
7248
  const raw = (process.env.AGENT_MOSS_SCRIPT_MAX_FILE_SIZE || "").trim();
6972
7249
  if (raw) {
@@ -6985,11 +7262,11 @@ function pickBackend(pathStr) {
6985
7262
  function resolvePath(p, baseDir) {
6986
7263
  let expanded = p;
6987
7264
  if (expanded.startsWith("~/") || expanded === "~") {
6988
- expanded = path3.join(os.homedir(), expanded.slice(1));
6989
- } else if (!path3.isAbsolute(expanded) && baseDir) {
6990
- expanded = path3.join(baseDir, expanded);
7265
+ expanded = path4.join(os2.homedir(), expanded.slice(1));
7266
+ } else if (!path4.isAbsolute(expanded) && baseDir) {
7267
+ expanded = path4.join(baseDir, expanded);
6991
7268
  }
6992
- return path3.resolve(expanded);
7269
+ return path4.resolve(expanded);
6993
7270
  }
6994
7271
  function readScript(pathStr, maxFileSize) {
6995
7272
  try {
@@ -7083,7 +7360,7 @@ var init_tracker = __esm({
7083
7360
  const baseDir = cwd || process.cwd();
7084
7361
  const resolved = resolvePath(entryPath);
7085
7362
  this.result.entryPath = resolved;
7086
- this.visitScript(resolved, 0, path3.dirname(resolved), entryArgs);
7363
+ this.visitScript(resolved, 0, path4.dirname(resolved), entryArgs);
7087
7364
  const nodes = this.result.nodes;
7088
7365
  this.result.hasCritical = nodes.some((n) => n.l1RiskLevel === "critical" || n.l2RiskLevel === "critical" || n.keywordRiskLevel === "critical") || this.result.hasCritical;
7089
7366
  this.result.hasHigh = nodes.some((n) => ["high", "critical"].includes(n.l1RiskLevel) || ["high", "critical"].includes(n.l2RiskLevel) || ["high", "critical"].includes(n.keywordRiskLevel));
@@ -7145,12 +7422,12 @@ var init_tracker = __esm({
7145
7422
  }
7146
7423
  }
7147
7424
  }
7148
- const parentDir = path3.dirname(pathStr);
7425
+ const parentDir = path4.dirname(pathStr);
7149
7426
  const childPaths = [];
7150
7427
  for (const call of ir.calls) {
7151
7428
  const child = resolvePath(call.path, parentDir);
7152
7429
  childPaths.push(child);
7153
- this.visitScript(child, depth + 1, path3.dirname(child), call.args);
7430
+ this.visitScript(child, depth + 1, path4.dirname(child), call.args);
7154
7431
  if (this.result.hasCritical) break;
7155
7432
  }
7156
7433
  node.childPaths = childPaths;
@@ -7162,8 +7439,8 @@ var init_tracker = __esm({
7162
7439
 
7163
7440
  // src/engine/script-content-analyzer.ts
7164
7441
  import { statSync as statSync4, existsSync as existsSync12 } from "fs";
7165
- import { resolve as resolve10, join as join11, isAbsolute as isAbsolute3 } from "path";
7166
- import { homedir as homedir4 } from "os";
7442
+ import { resolve as resolve10, join as join12, isAbsolute as isAbsolute4 } from "path";
7443
+ import { homedir as homedir5 } from "os";
7167
7444
  function emptyChain() {
7168
7445
  return {
7169
7446
  nodes: [],
@@ -7345,7 +7622,7 @@ function shlexSplit(s) {
7345
7622
  function resolvePath2(p) {
7346
7623
  let expanded = p;
7347
7624
  if (expanded.startsWith("~/") || expanded === "~") {
7348
- expanded = join11(homedir4(), expanded.slice(1));
7625
+ expanded = join12(homedir5(), expanded.slice(1));
7349
7626
  }
7350
7627
  return resolve10(expanded);
7351
7628
  }
@@ -7468,8 +7745,8 @@ function analyzeScriptContent2(input, ext) {
7468
7745
  resolvedPath = inline;
7469
7746
  isInline = true;
7470
7747
  }
7471
- if (resolvedPath && !isAbsolute3(resolvedPath) && !resolvedPath.startsWith("~/")) {
7472
- resolvedPath = join11(input.cwd || process.cwd(), resolvedPath);
7748
+ if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
7749
+ resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
7473
7750
  }
7474
7751
  const l1Adapter = (content) => {
7475
7752
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
@@ -7587,7 +7864,7 @@ var init_script_content_analyzer = __esm({
7587
7864
 
7588
7865
  // src/infra/trace-log.ts
7589
7866
  import fs4 from "fs";
7590
- import path4 from "path";
7867
+ import path5 from "path";
7591
7868
  function traceLevel() {
7592
7869
  if (_levelCache !== null) return _levelCache;
7593
7870
  const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
@@ -7614,7 +7891,7 @@ function tracePath() {
7614
7891
  const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
7615
7892
  if (explicit) return explicit;
7616
7893
  try {
7617
- return path4.join(getDataRoot(), "agent_moss_trace.log");
7894
+ return path5.join(getDataRoot(), "agent_moss_trace.log");
7618
7895
  } catch {
7619
7896
  return "agent_moss_trace.log";
7620
7897
  }
@@ -7653,7 +7930,7 @@ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
7653
7930
  `;
7654
7931
  const file = tracePath();
7655
7932
  try {
7656
- const dir = path4.dirname(file);
7933
+ const dir = path5.dirname(file);
7657
7934
  if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
7658
7935
  try {
7659
7936
  const st = fs4.statSync(file);
@@ -8249,7 +8526,7 @@ var init_token_stats = __esm({
8249
8526
 
8250
8527
  // src/engine/llm-analyzer.ts
8251
8528
  import { createHash as createHash3 } from "crypto";
8252
- import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
8529
+ import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
8253
8530
  import OpenAI from "openai";
8254
8531
  function responseFieldLengths(message) {
8255
8532
  if (!message || typeof message !== "object") return {};
@@ -8386,13 +8663,13 @@ function logPrompt(prompt, aNext, logPath) {
8386
8663
  ${prompt}
8387
8664
  --- END PROMPT ---
8388
8665
  `;
8389
- let flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND;
8390
- if (fsConstants.O_NOFOLLOW) flags |= fsConstants.O_NOFOLLOW;
8391
- const fd = openSync2(logPath, flags, 384);
8666
+ let flags = fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_APPEND;
8667
+ if (fsConstants2.O_NOFOLLOW) flags |= fsConstants2.O_NOFOLLOW;
8668
+ const fd = openSync3(logPath, flags, 384);
8392
8669
  try {
8393
8670
  writeSync2(fd, line);
8394
8671
  } finally {
8395
- closeSync2(fd);
8672
+ closeSync3(fd);
8396
8673
  }
8397
8674
  } catch (e) {
8398
8675
  console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
@@ -8688,8 +8965,8 @@ var init_llm_analyzer = __esm({
8688
8965
 
8689
8966
  // src/brain/rule-store.ts
8690
8967
  import { existsSync as existsSync14, readFileSync as readFileSync14, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
8691
- import { join as join12 } from "path";
8692
- import { homedir as homedir5 } from "os";
8968
+ import { join as join13 } from "path";
8969
+ import { homedir as homedir6 } from "os";
8693
8970
  function getRulesPath() {
8694
8971
  const envPath = process.env[ENV_RULES_PATH];
8695
8972
  if (envPath) return envPath;
@@ -8707,7 +8984,7 @@ var init_rule_store = __esm({
8707
8984
  "src/brain/rule-store.ts"() {
8708
8985
  "use strict";
8709
8986
  init_esm_shims();
8710
- DEFAULT_RULES_PATH = join12(homedir5(), ".agentmoss", "brain", "rules.json");
8987
+ DEFAULT_RULES_PATH = join13(homedir6(), ".agentmoss", "brain", "rules.json");
8711
8988
  ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
8712
8989
  STATUS_DRAFT = "draft";
8713
8990
  STATUS_APPROVED = "approved";
@@ -8719,8 +8996,8 @@ var init_rule_store = __esm({
8719
8996
  BrainRuleStore = class {
8720
8997
  path;
8721
8998
  data;
8722
- constructor(path7) {
8723
- this.path = path7 || getRulesPath();
8999
+ constructor(path8) {
9000
+ this.path = path8 || getRulesPath();
8724
9001
  this.data = this.load();
8725
9002
  }
8726
9003
  load() {
@@ -9173,10 +9450,10 @@ ${reason.slice(0, 500)}
9173
9450
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
9174
9451
  let mm;
9175
9452
  while ((mm = pathRe.exec(src)) !== null) {
9176
- const path7 = mm[1];
9177
- if (path7.split("/").length < 3) continue;
9178
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path7)) continue;
9179
- const gen = this.generalizePath(path7);
9453
+ const path8 = mm[1];
9454
+ if (path8.split("/").length < 3) continue;
9455
+ if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path8)) continue;
9456
+ const gen = this.generalizePath(path8);
9180
9457
  if (seen.has(gen)) continue;
9181
9458
  seen.add(gen);
9182
9459
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -9195,8 +9472,8 @@ ${reason.slice(0, 500)}
9195
9472
  }
9196
9473
  return false;
9197
9474
  }
9198
- generalizePath(path7) {
9199
- const p = path7.toLowerCase();
9475
+ generalizePath(path8) {
9476
+ const p = path8.toLowerCase();
9200
9477
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
9201
9478
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
9202
9479
  }
@@ -9323,8 +9600,8 @@ var init_reviewer = __esm({
9323
9600
 
9324
9601
  // src/brain/skill-manager.ts
9325
9602
  import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync, writeFileSync as writeFileSync4 } from "fs";
9326
- import { homedir as homedir6 } from "os";
9327
- import { join as join13 } from "path";
9603
+ import { homedir as homedir7 } from "os";
9604
+ import { join as join14 } from "path";
9328
9605
  import { randomUUID } from "crypto";
9329
9606
  function getMetaPath(override) {
9330
9607
  return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
@@ -9334,14 +9611,14 @@ var init_skill_manager = __esm({
9334
9611
  "src/brain/skill-manager.ts"() {
9335
9612
  "use strict";
9336
9613
  init_esm_shims();
9337
- DEFAULT_SKILL_META_PATH = join13(homedir6(), ".agentmoss", "brain", "skill_meta.json");
9614
+ DEFAULT_SKILL_META_PATH = join14(homedir7(), ".agentmoss", "brain", "skill_meta.json");
9338
9615
  ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
9339
9616
  BrainSkillManager = class {
9340
9617
  constructor(skillsDir, metaPath) {
9341
9618
  this.skillsDir = skillsDir;
9342
9619
  this.metaPath = getMetaPath(metaPath);
9343
9620
  try {
9344
- mkdirSync5(join13(this.metaPath, ".."), { recursive: true });
9621
+ mkdirSync5(join14(this.metaPath, ".."), { recursive: true });
9345
9622
  } catch {
9346
9623
  }
9347
9624
  this.load();
@@ -9376,7 +9653,7 @@ var init_skill_manager = __esm({
9376
9653
  let changed = false;
9377
9654
  for (const sk of this.skills) {
9378
9655
  if (sk.status !== "active") continue;
9379
- if (!existsSync15(join13(this.skillsDir, `${sk.name}.md`))) {
9656
+ if (!existsSync15(join14(this.skillsDir, `${sk.name}.md`))) {
9380
9657
  sk.status = "stale";
9381
9658
  changed = true;
9382
9659
  }
@@ -9388,7 +9665,7 @@ var init_skill_manager = __esm({
9388
9665
  const id = skill.id || randomUUID();
9389
9666
  const name = skill.name || `brain_${id.slice(0, 8)}`;
9390
9667
  if (!existsSync15(this.skillsDir)) return "";
9391
- const mdPath = join13(this.skillsDir, `${name}.md`);
9668
+ const mdPath = join14(this.skillsDir, `${name}.md`);
9392
9669
  if (existsSync15(mdPath)) return "";
9393
9670
  try {
9394
9671
  writeFileSync4(mdPath, skill.content, "utf-8");
@@ -9438,7 +9715,7 @@ var init_skill_manager = __esm({
9438
9715
  const out = [];
9439
9716
  for (const sk of this.skills) {
9440
9717
  if (sk.origin_node !== "local" || sk.status !== "active") continue;
9441
- const mdPath = join13(this.skillsDir, `${sk.name}.md`);
9718
+ const mdPath = join14(this.skillsDir, `${sk.name}.md`);
9442
9719
  if (!existsSync15(mdPath)) continue;
9443
9720
  out.push({
9444
9721
  name: sk.name,
@@ -9555,7 +9832,7 @@ __export(contributor_exports, {
9555
9832
  });
9556
9833
  import { mkdirSync as mkdirSync6, mkdtempSync, rmSync, writeFileSync as writeFileSync5 } from "fs";
9557
9834
  import { tmpdir as tmpdir2 } from "os";
9558
- import { join as join14 } from "path";
9835
+ import { join as join15 } from "path";
9559
9836
  import { spawnSync } from "child_process";
9560
9837
  import { dirname as dirname10 } from "path";
9561
9838
  import { fileURLToPath as fileURLToPath9 } from "url";
@@ -9576,7 +9853,7 @@ function collectSkills(skillMgr) {
9576
9853
  }
9577
9854
  function writeExportFiles(outDir, rules, skills) {
9578
9855
  const written = [];
9579
- const rulesDir2 = join14(outDir, "rules");
9856
+ const rulesDir2 = join15(outDir, "rules");
9580
9857
  mkdirSync6(rulesDir2, { recursive: true });
9581
9858
  const byLayer = /* @__PURE__ */ new Map();
9582
9859
  for (const r of rules) {
@@ -9584,26 +9861,26 @@ function writeExportFiles(outDir, rules, skills) {
9584
9861
  byLayer.get(r.layer).push(r);
9585
9862
  }
9586
9863
  for (const layer of [...byLayer.keys()].sort((a, b) => a - b)) {
9587
- const path7 = join14(rulesDir2, `l${layer}_brain_rules.json`);
9588
- writeFileSync5(path7, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
9589
- written.push(path7);
9864
+ const path8 = join15(rulesDir2, `l${layer}_brain_rules.json`);
9865
+ writeFileSync5(path8, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
9866
+ written.push(path8);
9590
9867
  }
9591
9868
  if (rules.length === 0) {
9592
- const path7 = join14(rulesDir2, "empty.txt");
9593
- writeFileSync5(path7, "(no brain rules to contribute)", "utf-8");
9594
- written.push(path7);
9869
+ const path8 = join15(rulesDir2, "empty.txt");
9870
+ writeFileSync5(path8, "(no brain rules to contribute)", "utf-8");
9871
+ written.push(path8);
9595
9872
  }
9596
- const skillsDir = join14(outDir, "skills");
9873
+ const skillsDir = join15(outDir, "skills");
9597
9874
  mkdirSync6(skillsDir, { recursive: true });
9598
9875
  for (const sk of skills) {
9599
- const path7 = join14(skillsDir, `${sk.name}.md`);
9600
- writeFileSync5(path7, sk.content || "", "utf-8");
9601
- written.push(path7);
9876
+ const path8 = join15(skillsDir, `${sk.name}.md`);
9877
+ writeFileSync5(path8, sk.content || "", "utf-8");
9878
+ written.push(path8);
9602
9879
  }
9603
9880
  if (skills.length === 0) {
9604
- const path7 = join14(skillsDir, "empty.txt");
9605
- writeFileSync5(path7, "(no brain skills to contribute)", "utf-8");
9606
- written.push(path7);
9881
+ const path8 = join15(skillsDir, "empty.txt");
9882
+ writeFileSync5(path8, "(no brain skills to contribute)", "utf-8");
9883
+ written.push(path8);
9607
9884
  }
9608
9885
  return written;
9609
9886
  }
@@ -9731,7 +10008,7 @@ async function contribute(opts = {}) {
9731
10008
  console.log(`[Brain] push \u76EE\u6807: ${pushTarget}`);
9732
10009
  console.log(`[Brain] MR \u6307\u5411: ${DEFAULT_TARGET_REPO}`);
9733
10010
  const store = new BrainRuleStore();
9734
- const skillsDir = resolveAssetDir(__dirname8, "skills") ?? join14(__dirname8, "..", "..", "agent_moss", "skills");
10011
+ const skillsDir = resolveAssetDir(__dirname8, "skills") ?? join15(__dirname8, "..", "..", "agent_moss", "skills");
9735
10012
  const skillMgr = new BrainSkillManager(skillsDir);
9736
10013
  let rules;
9737
10014
  let skills;
@@ -9746,9 +10023,9 @@ async function contribute(opts = {}) {
9746
10023
  return 0;
9747
10024
  }
9748
10025
  console.log(`[Brain] \u5BFC\u51FA: ${rules.length} \u6761\u89C4\u5219, ${skills.length} \u4E2A Skill`);
9749
- const workdir = mkdtempSync(join14(tmpdir2(), "agentmoss-contrib-"));
10026
+ const workdir = mkdtempSync(join15(tmpdir2(), "agentmoss-contrib-"));
9750
10027
  try {
9751
- writeExportFiles(join14(workdir, "agent_moss", "brain_contrib"), rules, skills);
10028
+ writeExportFiles(join15(workdir, "agent_moss", "brain_contrib"), rules, skills);
9752
10029
  console.log(`[Brain] \u63A2\u6D4B ${pushTarget} \u8BBF\u95EE\u6743\u9650 ...`);
9753
10030
  if (!probeAccess(pushTarget)) {
9754
10031
  const username = getCurrentUsername();
@@ -10307,12 +10584,12 @@ var init_builder = __esm({
10307
10584
  });
10308
10585
 
10309
10586
  // src/engine/formal-engine/properties.ts
10310
- function graphFromPath(nodes, path7, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10587
+ function graphFromPath(nodes, path8, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10311
10588
  const byKey = /* @__PURE__ */ new Map();
10312
10589
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
10313
10590
  const gNodes = [];
10314
10591
  const gEdges = [];
10315
- for (const item of path7) {
10592
+ for (const item of path8) {
10316
10593
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
10317
10594
  gNodes.push({
10318
10595
  session_id: item.sessionId,
@@ -10378,22 +10655,22 @@ function checkCrossSessionChain(graph) {
10378
10655
  if (witness !== void 0) {
10379
10656
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
10380
10657
  let matched = 0;
10381
- const path7 = [];
10658
+ const path8 = [];
10382
10659
  for (let k = 0; k < witness; k++) {
10383
10660
  const n = nodes[k];
10384
10661
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
10385
10662
  matched += 1;
10386
- path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10663
+ path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10387
10664
  }
10388
10665
  }
10389
10666
  if (matched < stages.length - 1) continue;
10390
- path7.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
10667
+ path8.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
10391
10668
  violations.push({
10392
10669
  propertyId: "cross-" + chain.id,
10393
10670
  reason: chain.reason,
10394
10671
  riskLevel: chain.riskLevel,
10395
- path: path7,
10396
- graph: graphFromPath(nodes, path7, "next", {
10672
+ path: path8,
10673
+ graph: graphFromPath(nodes, path8, "next", {
10397
10674
  property_id: "cross-" + chain.id,
10398
10675
  property_short: "P1",
10399
10676
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -10403,11 +10680,11 @@ function checkCrossSessionChain(graph) {
10403
10680
  } else {
10404
10681
  let matched = 0;
10405
10682
  let stageIdx = 0;
10406
- const path7 = [];
10683
+ const path8 = [];
10407
10684
  for (const n of nodes) {
10408
10685
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
10409
10686
  matched += 1;
10410
- path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10687
+ path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10411
10688
  stageIdx += 1;
10412
10689
  if (matched >= stages.length) break;
10413
10690
  }
@@ -10417,8 +10694,8 @@ function checkCrossSessionChain(graph) {
10417
10694
  propertyId: "cross-" + chain.id,
10418
10695
  reason: chain.reason,
10419
10696
  riskLevel: chain.riskLevel,
10420
- path: path7,
10421
- graph: graphFromPath(nodes, path7, "next", {
10697
+ path: path8,
10698
+ graph: graphFromPath(nodes, path8, "next", {
10422
10699
  property_id: "cross-" + chain.id,
10423
10700
  property_short: "P1",
10424
10701
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -10639,7 +10916,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10639
10916
  if (candidates.length > 0) {
10640
10917
  const pre = nodes[candidates[candidates.length - 1]];
10641
10918
  const post = nodes[firstEv];
10642
- const path7 = [
10919
+ const path8 = [
10643
10920
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10644
10921
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10645
10922
  ];
@@ -10647,8 +10924,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10647
10924
  propertyId: "no-exfil-after-privesc",
10648
10925
  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",
10649
10926
  riskLevel: "critical",
10650
- path: path7,
10651
- graph: graphFromPath(nodes, path7, "next", {
10927
+ path: path8,
10928
+ graph: graphFromPath(nodes, path8, "next", {
10652
10929
  property_id: "no-exfil-after-privesc",
10653
10930
  property_short: "P4",
10654
10931
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10665,7 +10942,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10665
10942
  for (let j = i + 1; j < nodes.length; j++) {
10666
10943
  if (!isExfilNode(nodes[j])) continue;
10667
10944
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
10668
- const path7 = [
10945
+ const path8 = [
10669
10946
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10670
10947
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10671
10948
  ];
@@ -10673,8 +10950,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10673
10950
  propertyId: "no-exfil-after-privesc",
10674
10951
  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",
10675
10952
  riskLevel: "critical",
10676
- path: path7,
10677
- graph: graphFromPath(nodes, path7, "next", {
10953
+ path: path8,
10954
+ graph: graphFromPath(nodes, path8, "next", {
10678
10955
  property_id: "no-exfil-after-privesc",
10679
10956
  property_short: "P4",
10680
10957
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10706,7 +10983,7 @@ function checkNeverExfilAfterCred(graph) {
10706
10983
  }
10707
10984
  if (pre) {
10708
10985
  const post = nodes[firstEv];
10709
- const path7 = [
10986
+ const path8 = [
10710
10987
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10711
10988
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10712
10989
  ];
@@ -10714,8 +10991,8 @@ function checkNeverExfilAfterCred(graph) {
10714
10991
  propertyId: "no-exfil-after-credential",
10715
10992
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10716
10993
  riskLevel: "critical",
10717
- path: path7,
10718
- graph: graphFromPath(nodes, path7, "data", {
10994
+ path: path8,
10995
+ graph: graphFromPath(nodes, path8, "data", {
10719
10996
  property_id: "no-exfil-after-credential",
10720
10997
  property_short: "P5",
10721
10998
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10731,7 +11008,7 @@ function checkNeverExfilAfterCred(graph) {
10731
11008
  if (!isCredNode(nodes[i])) continue;
10732
11009
  for (let j = i + 1; j < nodes.length; j++) {
10733
11010
  if (isExfilNode(nodes[j])) {
10734
- const path7 = [
11011
+ const path8 = [
10735
11012
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10736
11013
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10737
11014
  ];
@@ -10739,8 +11016,8 @@ function checkNeverExfilAfterCred(graph) {
10739
11016
  propertyId: "no-exfil-after-credential",
10740
11017
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10741
11018
  riskLevel: "critical",
10742
- path: path7,
10743
- graph: graphFromPath(nodes, path7, "data", {
11019
+ path: path8,
11020
+ graph: graphFromPath(nodes, path8, "data", {
10744
11021
  property_id: "no-exfil-after-credential",
10745
11022
  property_short: "P5",
10746
11023
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10899,13 +11176,13 @@ function checkSensitiveDataAggregation(graph) {
10899
11176
  if (!isExfilNode(n)) continue;
10900
11177
  const srcs = sourcesFor(i);
10901
11178
  if (srcs.size >= 2) {
10902
- const path7 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11179
+ const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10903
11180
  violations.push({
10904
11181
  propertyId: "sensitive-data-aggregation",
10905
11182
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
10906
11183
  riskLevel: "critical",
10907
- path: path7,
10908
- graph: graphFromPath(nodes, path7, "next", {
11184
+ path: path8,
11185
+ graph: graphFromPath(nodes, path8, "next", {
10909
11186
  property_id: "sensitive-data-aggregation",
10910
11187
  property_short: "P8",
10911
11188
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -11364,11 +11641,11 @@ var init_stateful = __esm({
11364
11641
  }
11365
11642
  }
11366
11643
  chainPath(stages) {
11367
- const path7 = [];
11644
+ const path8 = [];
11368
11645
  let want = stages[0];
11369
11646
  for (const n of this.nodes_) {
11370
11647
  if (n.stage === want) {
11371
- path7.push({
11648
+ path8.push({
11372
11649
  sessionId: n.sessionId,
11373
11650
  seq: n.seq,
11374
11651
  stage: n.stage,
@@ -11384,12 +11661,12 @@ var init_stateful = __esm({
11384
11661
  }
11385
11662
  }
11386
11663
  }
11387
- return path7;
11664
+ return path8;
11388
11665
  }
11389
11666
  /** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
11390
11667
  buildChainGraph(stages, chainId) {
11391
- const path7 = this.chainPath(stages);
11392
- const gNodes = path7.map((p, i) => {
11668
+ const path8 = this.chainPath(stages);
11669
+ const gNodes = path8.map((p, i) => {
11393
11670
  const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
11394
11671
  return {
11395
11672
  session_id: p.sessionId,
@@ -11641,13 +11918,13 @@ var init_stateful = __esm({
11641
11918
 
11642
11919
  // src/engine/formal-engine/chain_state.ts
11643
11920
  import * as fs5 from "fs";
11644
- import * as os2 from "os";
11645
- import * as path5 from "path";
11921
+ import * as os3 from "os";
11922
+ import * as path6 from "path";
11646
11923
  import { createHash as createHash4 } from "crypto";
11647
11924
  function defaultStateDbPath() {
11648
- const dir = process.env.AGENT_MOSS_STATE_DIR || path5.join(os2.homedir(), ".agentmoss");
11925
+ const dir = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
11649
11926
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
11650
- return path5.join(dir, `stateful_chains_${tag}.json`);
11927
+ return path6.join(dir, `stateful_chains_${tag}.json`);
11651
11928
  }
11652
11929
  function registerExitFlush(store) {
11653
11930
  if (_exitHookRegistered) return;
@@ -11705,6 +11982,13 @@ var init_chain_state = __esm({
11705
11982
  _trackers = /* @__PURE__ */ new Map();
11706
11983
  /** 自上次落盘以来变过的 agentId */
11707
11984
  _dirty = /* @__PURE__ */ new Set();
11985
+ /**
11986
+ * 多进程模式(2026-11,对齐 Python `enable_multi_process`):
11987
+ * AGENT_MOSS_MULTI_PROCESS=1 时启用。Node cluster / PM2 多进程部署下,
11988
+ * 各进程的 `data` 是独立快照,防抖写会互相覆盖(JSON 文件没有 SQLite 那样的锁)。
11989
+ * 启用后:每次 applyAction 用**文件锁**串行化,锁内重新读文件 → 判定 → 立即写。
11990
+ */
11991
+ _multiProcess = false;
11708
11992
  constructor(filePath = "") {
11709
11993
  this.filePath = filePath || defaultStateDbPath();
11710
11994
  this.data = this._read();
@@ -11726,7 +12010,7 @@ var init_chain_state = __esm({
11726
12010
  this._timer = null;
11727
12011
  try {
11728
12012
  this._syncDirtyToData();
11729
- ensurePrivateDir(path5.dirname(this.filePath));
12013
+ ensurePrivateDir(path6.dirname(this.filePath));
11730
12014
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11731
12015
  } catch {
11732
12016
  }
@@ -11749,7 +12033,7 @@ var init_chain_state = __esm({
11749
12033
  }
11750
12034
  try {
11751
12035
  this._syncDirtyToData();
11752
- ensurePrivateDir(path5.dirname(this.filePath));
12036
+ ensurePrivateDir(path6.dirname(this.filePath));
11753
12037
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11754
12038
  } catch {
11755
12039
  }
@@ -11775,6 +12059,55 @@ var init_chain_state = __esm({
11775
12059
  delete this.data[agentId];
11776
12060
  this._scheduleWrite();
11777
12061
  }
12062
+ /** 启用多进程模式(对齐 Python)。 */
12063
+ enableMultiProcess() {
12064
+ this._multiProcess = true;
12065
+ }
12066
+ /**
12067
+ * 同步文件锁(原子创建 `<file>.lock`)。
12068
+ *
12069
+ * Node 是单线程,锁竞争时用 Atomics.wait 做**同步睡眠**而不是忙等 ——
12070
+ * 忙等会把事件循环完全占死,其它请求也没法推进。
12071
+ */
12072
+ _withFileLock(fn) {
12073
+ const lockPath = `${this.filePath}.lock`;
12074
+ const sleepBuf = new Int32Array(new SharedArrayBuffer(4));
12075
+ for (let attempt = 0; attempt < 100; attempt++) {
12076
+ try {
12077
+ const fd = fs5.openSync(lockPath, "wx");
12078
+ try {
12079
+ return fn();
12080
+ } finally {
12081
+ try {
12082
+ fs5.closeSync(fd);
12083
+ } catch {
12084
+ }
12085
+ try {
12086
+ fs5.unlinkSync(lockPath);
12087
+ } catch {
12088
+ }
12089
+ }
12090
+ } catch (e) {
12091
+ if (e?.code !== "EEXIST") throw e;
12092
+ try {
12093
+ Atomics.wait(sleepBuf, 0, 0, 20);
12094
+ } catch {
12095
+ }
12096
+ }
12097
+ }
12098
+ throw new Error(`chain state lock timeout: ${lockPath}`);
12099
+ }
12100
+ /** 立即把内存写进文件(多进程模式用,不走防抖)。 */
12101
+ _flushNow() {
12102
+ this._syncDirtyToData();
12103
+ try {
12104
+ const _dirOk = ensurePrivateDir(path6.dirname(this.filePath));
12105
+ const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
12106
+ if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
12107
+ } catch (e) {
12108
+ console.error("[AgentMoss] chain state flush failed:", e?.message || e);
12109
+ }
12110
+ }
11778
12111
  /** 当前内存中的 tracker 数 / 节点总数(健康检查用)。 */
11779
12112
  stats() {
11780
12113
  let nodes = 0;
@@ -11782,6 +12115,17 @@ var init_chain_state = __esm({
11782
12115
  return { agents: this._trackers.size, nodes };
11783
12116
  }
11784
12117
  applyAction(agentId, aNext, sessionId, isError = false, sourceAgent = "", instanceId = "") {
12118
+ if (this._multiProcess) {
12119
+ return this._withFileLock(() => {
12120
+ this.data = this._read();
12121
+ this._trackers.clear();
12122
+ const t2 = this.load(agentId) || new StatefulChainTracker(agentId);
12123
+ const r2 = t2.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
12124
+ this.save(t2);
12125
+ this._flushNow();
12126
+ return r2;
12127
+ });
12128
+ }
11785
12129
  const t = this.load(agentId) || new StatefulChainTracker(agentId);
11786
12130
  const r = t.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
11787
12131
  this.save(t);
@@ -12054,7 +12398,7 @@ async function runAnalysis(input) {
12054
12398
  skipLLM = true;
12055
12399
  }
12056
12400
  }
12057
- const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
12401
+ const logicResult = isLogicRulesEnabled() ? runLogicCheck(input, { agentExt }) : null;
12058
12402
  if (logicResult) {
12059
12403
  traceSummary("l2.result", {
12060
12404
  hit: !logicResult.allowed,
@@ -12317,9 +12661,9 @@ var init_coordinator = __esm({
12317
12661
 
12318
12662
  // src/infra/policy-cache.ts
12319
12663
  import { createHash as createHash5 } from "crypto";
12320
- import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync3 } from "fs";
12664
+ import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
12321
12665
  import { tmpdir as tmpdir3 } from "os";
12322
- import { join as join16 } from "path";
12666
+ import { join as join17 } from "path";
12323
12667
  function cacheDir() {
12324
12668
  return cacheDirOverride ?? CACHE_DIR;
12325
12669
  }
@@ -12327,7 +12671,7 @@ function safeCacheDir() {
12327
12671
  const dir = cacheDir();
12328
12672
  if (ensurePrivateDir(dir)) return dir;
12329
12673
  try {
12330
- const fallback = join16(getDataRoot(), "policy_cache");
12674
+ const fallback = join17(getDataRoot(), "policy_cache");
12331
12675
  if (ensurePrivateDir(fallback)) {
12332
12676
  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}`);
12333
12677
  return fallback;
@@ -12348,7 +12692,7 @@ var init_policy_cache = __esm({
12348
12692
  init_security_policy();
12349
12693
  init_paths();
12350
12694
  init_config();
12351
- CACHE_DIR = join16(tmpdir3(), "agent_moss_policy_cache");
12695
+ CACHE_DIR = join17(tmpdir3(), "agent_moss_policy_cache");
12352
12696
  cacheDirOverride = null;
12353
12697
  PolicyCache = class {
12354
12698
  // Map 的插入序即 LRU 序(get 时重新 set 到末尾)
@@ -12363,7 +12707,7 @@ var init_policy_cache = __esm({
12363
12707
  cacheFilePath(sessionId, promptSession) {
12364
12708
  const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
12365
12709
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12366
- return join16(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
12710
+ return join17(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
12367
12711
  }
12368
12712
  /** 取缓存:内存 → 文件;未命中返回 null。 */
12369
12713
  get(sessionId, promptSession) {
@@ -12394,7 +12738,7 @@ var init_policy_cache = __esm({
12394
12738
  try {
12395
12739
  const dir = safeCacheDir();
12396
12740
  const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12397
- if (!ensurePrivateDir(join16(dir, sub))) return;
12741
+ if (!ensurePrivateDir(join17(dir, sub))) return;
12398
12742
  writePrivateText(file, policy);
12399
12743
  } catch {
12400
12744
  }
@@ -12411,7 +12755,7 @@ var init_policy_cache = __esm({
12411
12755
  invalidate(sessionId, promptSession) {
12412
12756
  this.memory.delete(this.cacheKey(sessionId, promptSession));
12413
12757
  try {
12414
- unlinkSync3(this.cacheFilePath(sessionId, promptSession));
12758
+ unlinkSync4(this.cacheFilePath(sessionId, promptSession));
12415
12759
  } catch {
12416
12760
  }
12417
12761
  }
@@ -12420,12 +12764,12 @@ var init_policy_cache = __esm({
12420
12764
  if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
12421
12765
  }
12422
12766
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12423
- const dir = join16(cacheDir(), safeSessionId);
12767
+ const dir = join17(cacheDir(), safeSessionId);
12424
12768
  try {
12425
12769
  if (existsSync17(dir)) {
12426
12770
  for (const f of readdirSync5(dir)) {
12427
12771
  try {
12428
- unlinkSync3(join16(dir, f));
12772
+ unlinkSync4(join17(dir, f));
12429
12773
  } catch {
12430
12774
  }
12431
12775
  }
@@ -12439,9 +12783,9 @@ var init_policy_cache = __esm({
12439
12783
  try {
12440
12784
  if (existsSync17(cacheDir())) {
12441
12785
  for (const sessionDir of readdirSync5(cacheDir())) {
12442
- const dir = join16(cacheDir(), sessionDir);
12786
+ const dir = join17(cacheDir(), sessionDir);
12443
12787
  try {
12444
- for (const f of readdirSync5(dir)) unlinkSync3(join16(dir, f));
12788
+ for (const f of readdirSync5(dir)) unlinkSync4(join17(dir, f));
12445
12789
  rmdirSync(dir);
12446
12790
  } catch {
12447
12791
  }
@@ -12539,7 +12883,7 @@ __export(analyzer_exports, {
12539
12883
  });
12540
12884
  import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
12541
12885
  import { tmpdir as tmpdir4 } from "os";
12542
- import { join as join17, resolve as resolve11 } from "path";
12886
+ import { join as join18, resolve as resolve11 } from "path";
12543
12887
  import { parse as parseToml } from "smol-toml";
12544
12888
  function _setPolicyOutputDirForTest(dir) {
12545
12889
  policyOutputDirOverride = dir;
@@ -12556,7 +12900,7 @@ function savePolicyToFile(sessionId, policyToml) {
12556
12900
  return null;
12557
12901
  }
12558
12902
  const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12559
- const filepath = join17(outDir, `${safeName}.toml`);
12903
+ const filepath = join18(outDir, `${safeName}.toml`);
12560
12904
  writePrivateText(filepath, policyToml);
12561
12905
  return filepath;
12562
12906
  } catch (err) {
@@ -12772,7 +13116,7 @@ var init_analyzer = __esm({
12772
13116
  init_asset_dir();
12773
13117
  init_token_stats();
12774
13118
  init_logging();
12775
- POLICY_OUTPUT_DIR = join17(tmpdir4(), "agent_moss");
13119
+ POLICY_OUTPUT_DIR = join18(tmpdir4(), "agent_moss");
12776
13120
  policyOutputDirOverride = null;
12777
13121
  DEFAULT_READONLY_POLICY = `landlock_optional = false
12778
13122
  mount_isolation_fallback = false
@@ -13010,8 +13354,8 @@ var init_pattern_miner = __esm({
13010
13354
 
13011
13355
  // src/agent-gate-reader.ts
13012
13356
  import * as fs7 from "fs";
13013
- import * as os3 from "os";
13014
- import * as path6 from "path";
13357
+ import * as os4 from "os";
13358
+ import * as path7 from "path";
13015
13359
  function normalizeAction(row) {
13016
13360
  return {
13017
13361
  actionType: String(row.action_type || row.tool_name || row.name || ""),
@@ -13024,7 +13368,7 @@ function readJsonDir(dirPath, limit = 1e5) {
13024
13368
  const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
13025
13369
  for (const f of files.slice(-200)) {
13026
13370
  const sid = f.replace(/\.json$/, "");
13027
- const raw = fs7.readFileSync(path6.join(dirPath, f), "utf-8");
13371
+ const raw = fs7.readFileSync(path7.join(dirPath, f), "utf-8");
13028
13372
  const arr = JSON.parse(raw);
13029
13373
  if (!Array.isArray(arr)) continue;
13030
13374
  for (const item of arr) {
@@ -13092,7 +13436,7 @@ function loadAgentGateSessions(dbPath = "") {
13092
13436
  }
13093
13437
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
13094
13438
  if (sql.length > 0) return sql;
13095
- const jsonDefault = path6.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
13439
+ const jsonDefault = path7.join(os4.homedir(), ".local", "share", "agent_gate", "tool_calls");
13096
13440
  return readJsonDir(jsonDefault);
13097
13441
  }
13098
13442
  var DEFAULT_AGENTGATE_SQLITE;
@@ -13101,8 +13445,8 @@ var init_agent_gate_reader = __esm({
13101
13445
  "use strict";
13102
13446
  init_esm_shims();
13103
13447
  init_esm_require();
13104
- DEFAULT_AGENTGATE_SQLITE = path6.join(
13105
- os3.homedir(),
13448
+ DEFAULT_AGENTGATE_SQLITE = path7.join(
13449
+ os4.homedir(),
13106
13450
  ".local",
13107
13451
  "share",
13108
13452
  "agent_gate",
@@ -13242,7 +13586,7 @@ var init_runtime_stats = __esm({
13242
13586
 
13243
13587
  // src/routes.ts
13244
13588
  import { randomBytes as randomBytes2 } from "crypto";
13245
- import { join as join19, dirname as dirname12 } from "path";
13589
+ import { join as join20, dirname as dirname12 } from "path";
13246
13590
  import { fileURLToPath as fileURLToPath10 } from "url";
13247
13591
  async function healthRoute(c) {
13248
13592
  const metrics = {};
@@ -13641,7 +13985,7 @@ function getBrainRuleStore() {
13641
13985
  return new BrainRuleStore();
13642
13986
  }
13643
13987
  function getBrainSkillManager() {
13644
- const dir = resolveAssetDir(__dirname9, "skills") ?? join19(__dirname9, "..", "..", "agent_moss", "skills");
13988
+ const dir = resolveAssetDir(__dirname9, "skills") ?? join20(__dirname9, "..", "..", "agent_moss", "skills");
13645
13989
  return new BrainSkillManager(dir);
13646
13990
  }
13647
13991
  async function brainRulesRoute(c) {
@@ -13760,8 +14104,8 @@ var init_routes = __esm({
13760
14104
  // src/console/router.ts
13761
14105
  import { Hono } from "hono";
13762
14106
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
13763
- import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync4 } from "fs";
13764
- import { join as join20, dirname as dirname13 } from "path";
14107
+ import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
14108
+ import { join as join21, dirname as dirname13 } from "path";
13765
14109
  import { fileURLToPath as fileURLToPath11 } from "url";
13766
14110
  function getConsoleToken() {
13767
14111
  return process.env[CONSOLE_TOKEN_ENV] || "";
@@ -13803,7 +14147,7 @@ function createConsoleRouter() {
13803
14147
  console2.use("/api/*", authMiddleware());
13804
14148
  console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
13805
14149
  const serveIndex = (c) => {
13806
- const indexFile = join20(STATIC_DIR, "index.html");
14150
+ const indexFile = join21(STATIC_DIR, "index.html");
13807
14151
  if (existsSync20(indexFile)) {
13808
14152
  return c.html(readFileSync20(indexFile, "utf-8"));
13809
14153
  }
@@ -14000,11 +14344,11 @@ function createConsoleRouter() {
14000
14344
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
14001
14345
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
14002
14346
  }
14003
- const userPath = join20(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14347
+ const userPath = join21(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14004
14348
  const builtinDir = resolveAssetDir(__dirname10, "skills");
14005
14349
  const candidates = [
14006
14350
  ...isRuntimeConfigDisabled() ? [] : [userPath],
14007
- builtinDir ? join20(builtinDir, `${skillId}.md`) : ""
14351
+ builtinDir ? join21(builtinDir, `${skillId}.md`) : ""
14008
14352
  ].filter(Boolean);
14009
14353
  for (const p of candidates) {
14010
14354
  if (existsSync20(p)) {
@@ -14105,7 +14449,7 @@ function createConsoleRouter() {
14105
14449
  const defaults = generateSourceDefaults();
14106
14450
  try {
14107
14451
  const p = getRuntimeConfigPath();
14108
- if (existsSync20(p)) unlinkSync4(p);
14452
+ if (existsSync20(p)) unlinkSync5(p);
14109
14453
  } catch {
14110
14454
  }
14111
14455
  return c.json(withL22View(defaults));
@@ -14142,7 +14486,7 @@ var init_router = __esm({
14142
14486
  init_asset_dir();
14143
14487
  init_rules_mode();
14144
14488
  __dirname10 = dirname13(fileURLToPath11(import.meta.url));
14145
- STATIC_DIR = join20(__dirname10, "static");
14489
+ STATIC_DIR = join21(__dirname10, "static");
14146
14490
  CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
14147
14491
  }
14148
14492
  });
@@ -14236,6 +14580,13 @@ function logDeploymentSelfCheck() {
14236
14580
  }
14237
14581
  }
14238
14582
  function createApp() {
14583
+ try {
14584
+ if (String(process.env.AGENT_MOSS_MULTI_PROCESS || "").toLowerCase() in { "1": 1, "true": 1, "yes": 1, "on": 1 }) {
14585
+ getChainStateStore().enableMultiProcess();
14586
+ console.log("[AgentMoss] \u94FE\u72B6\u6001\u591A\u8FDB\u7A0B\u6A21\u5F0F\uFF1A\u5DF2\u542F\u7528\uFF08\u6587\u4EF6\u9501 + \u7ACB\u5373\u843D\u76D8\uFF09");
14587
+ }
14588
+ } catch {
14589
+ }
14239
14590
  enforceRulesContract();
14240
14591
  hardenExistingPaths();
14241
14592
  const app = new Hono2();
@@ -14255,7 +14606,7 @@ function createApp() {
14255
14606
  startLoopMonitor();
14256
14607
  const limiter = new RateLimiter(rateLimitQps());
14257
14608
  app.use("*", async (c, next) => {
14258
- const path7 = new URL(c.req.url).pathname;
14609
+ const path8 = new URL(c.req.url).pathname;
14259
14610
  const method = c.req.method.toUpperCase();
14260
14611
  if (method === "OPTIONS") return next();
14261
14612
  const maxBody = maxBodyBytes();
@@ -14269,16 +14620,16 @@ function createApp() {
14269
14620
  if (originCheckEnabled()) {
14270
14621
  const origin = c.req.header("origin") || "";
14271
14622
  if (origin && !originAllowed(origin, c.req.header("host") || "")) {
14272
- console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path7}`);
14623
+ console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path8}`);
14273
14624
  return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
14274
14625
  }
14275
14626
  }
14276
- const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path7);
14277
- const isPublicPage = !path7.startsWith("/console/api") && (path7 === "/console" || path7.startsWith("/console/"));
14627
+ const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path8);
14628
+ const isPublicPage = !path8.startsWith("/console/api") && (path8 === "/console" || path8.startsWith("/console/"));
14278
14629
  if (!okAuth && !isPublicPage) {
14279
14630
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
14280
14631
  }
14281
- if (limiter.enabled && path7.startsWith("/api/")) {
14632
+ if (limiter.enabled && path8.startsWith("/api/")) {
14282
14633
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
14283
14634
  if (!limiter.allow(key)) {
14284
14635
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
@@ -14312,7 +14663,7 @@ function createApp() {
14312
14663
  return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
14313
14664
  }
14314
14665
  }
14315
- const pool = poolOf(path7);
14666
+ const pool = poolOf(path8);
14316
14667
  if (!take(`pool:${pool}`, poolLimit(pool))) {
14317
14668
  const qkey = principal ? "p:" + principalHash(principal) : "c:local";
14318
14669
  const [qn, abusive] = noteQueueReject(qkey);
@@ -14438,7 +14789,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
14438
14789
  },
14439
14790
  serve: async () => {
14440
14791
  failFastOnAuthError();
14441
- const { mkdirSync: mkdirSync10, existsSync: existsSync23, unlinkSync: unlinkSync5 } = await import("fs");
14792
+ const { mkdirSync: mkdirSync10, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
14442
14793
  const { dirname: dirname15 } = await import("path");
14443
14794
  const dir = dirname15(socketPath);
14444
14795
  if (dir) {
@@ -14465,7 +14816,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
14465
14816
  );
14466
14817
  } else {
14467
14818
  try {
14468
- unlinkSync5(socketPath);
14819
+ unlinkSync6(socketPath);
14469
14820
  console.log(`[AgentMoss] \u6E05\u7406\u6B8B\u7559 socket \u6587\u4EF6: ${socketPath}`);
14470
14821
  } catch {
14471
14822
  }
@@ -14576,17 +14927,17 @@ __export(rules_tools_exports, {
14576
14927
  templateSourceDir: () => templateSourceDir
14577
14928
  });
14578
14929
  import { existsSync as existsSync22, mkdirSync as mkdirSync9, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync7 } from "fs";
14579
- import { dirname as dirname14, join as join21 } from "path";
14930
+ import { dirname as dirname14, join as join22 } from "path";
14580
14931
  import { fileURLToPath as fileURLToPath12 } from "url";
14581
14932
  function initRulesDir(targetDir, opts = {}) {
14582
14933
  mkdirSync9(targetDir, { recursive: true });
14583
14934
  const written = [];
14584
- const extraPath = join21(targetDir, EXTRA_FILENAME);
14935
+ const extraPath = join22(targetDir, EXTRA_FILENAME);
14585
14936
  if (opts.force || !existsSync22(extraPath)) {
14586
14937
  writeFileSync7(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
14587
14938
  written.push(extraPath);
14588
14939
  }
14589
- const samplePath = join21(targetDir, OVERRIDE_FILENAME);
14940
+ const samplePath = join22(targetDir, OVERRIDE_FILENAME);
14590
14941
  if (opts.force || !existsSync22(samplePath)) {
14591
14942
  let payload = OVERRIDE_TEMPLATE;
14592
14943
  if (opts.withBuiltin) {
@@ -14605,8 +14956,8 @@ function initRulesDir(targetDir, opts = {}) {
14605
14956
  writeFileSync7(samplePath, JSON.stringify(payload, null, 2), "utf-8");
14606
14957
  written.push(samplePath);
14607
14958
  }
14608
- const readmeSrc = join21(templateSourceDir(), "README.md");
14609
- const readmeDst = join21(targetDir, "README.md");
14959
+ const readmeSrc = join22(templateSourceDir(), "README.md");
14960
+ const readmeDst = join22(targetDir, "README.md");
14610
14961
  if (existsSync22(readmeSrc) && (opts.force || !existsSync22(readmeDst))) {
14611
14962
  writeFileSync7(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
14612
14963
  written.push(readmeDst);
@@ -14614,7 +14965,7 @@ function initRulesDir(targetDir, opts = {}) {
14614
14965
  return written;
14615
14966
  }
14616
14967
  function templateSourceDir() {
14617
- const cands = [join21(__dirname11, "data", "rules_template"), join21(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
14968
+ const cands = [join22(__dirname11, "data", "rules_template"), join22(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
14618
14969
  for (const c of cands) if (existsSync22(c)) return c;
14619
14970
  return cands[0];
14620
14971
  }
@@ -14623,7 +14974,7 @@ function templateFiles(dirs) {
14623
14974
  for (const d of dirs) {
14624
14975
  try {
14625
14976
  for (const name of readdirSync7(d)) {
14626
- if (name.endsWith(".json.\u793A\u4F8B")) out.push(join21(d, name));
14977
+ if (name.endsWith(".json.\u793A\u4F8B")) out.push(join22(d, name));
14627
14978
  }
14628
14979
  } catch {
14629
14980
  }
@@ -14828,7 +15179,7 @@ async function main() {
14828
15179
  process.exit(1);
14829
15180
  }
14830
15181
  const fs8 = await import("fs");
14831
- const path7 = await import("path");
15182
+ const path8 = await import("path");
14832
15183
  const useJson = args.includes("--json");
14833
15184
  const osType = process.platform === "win32" ? "windows" : "linux";
14834
15185
  const isFile = fs8.existsSync(target) && fs8.statSync(target).isFile();
@@ -14847,7 +15198,7 @@ async function main() {
14847
15198
  }
14848
15199
  process.exit(await analyzeRawCommand(target, useJson));
14849
15200
  }
14850
- const filePath = path7.resolve(target);
15201
+ const filePath = path8.resolve(target);
14851
15202
  const data = JSON.parse(fs8.readFileSync(filePath, "utf-8"));
14852
15203
  const { analyze: analyze2 } = await Promise.resolve().then(() => (init_analyzer(), analyzer_exports));
14853
15204
  const sessionId = String(data.session_id || "unknown");
@@ -14859,11 +15210,11 @@ async function main() {
14859
15210
  fs8.mkdirSync(outDir, { recursive: true });
14860
15211
  const safeSession = sessionId.replace(/\//g, "_");
14861
15212
  if (result.decision === "Allow") {
14862
- const policyPath = path7.join(outDir, `${safeSession}_policy.toml`);
15213
+ const policyPath = path8.join(outDir, `${safeSession}_policy.toml`);
14863
15214
  fs8.writeFileSync(policyPath, result.policy || "", "utf-8");
14864
15215
  console.log(`Policy written to ${policyPath}`);
14865
15216
  } else {
14866
- const denyPath = path7.join(outDir, `${safeSession}_deny_reason.txt`);
15217
+ const denyPath = path8.join(outDir, `${safeSession}_deny_reason.txt`);
14867
15218
  fs8.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
14868
15219
  console.log(`Deny reason written to ${denyPath}`);
14869
15220
  }
@@ -14954,7 +15305,7 @@ async function main() {
14954
15305
  const enable = args.includes("--enable");
14955
15306
  const { execSync } = await import("child_process");
14956
15307
  const fs8 = await import("fs");
14957
- const path7 = await import("path");
15308
+ const path8 = await import("path");
14958
15309
  const { fileURLToPath: fileURLToPath14 } = await import("url");
14959
15310
  if (process.getuid?.() !== 0) {
14960
15311
  try {
@@ -14971,17 +15322,17 @@ async function main() {
14971
15322
  process.exit(0);
14972
15323
  }
14973
15324
  const __filename7 = fileURLToPath14(import.meta.url);
14974
- const __dirname12 = path7.dirname(__filename7);
14975
- let srcPath = path7.join(__dirname12, "data", "agent_moss.service");
15325
+ const __dirname12 = path8.dirname(__filename7);
15326
+ let srcPath = path8.join(__dirname12, "data", "agent_moss.service");
14976
15327
  if (!fs8.existsSync(srcPath)) {
14977
- srcPath = path7.join(__dirname12, "..", "src", "data", "agent_moss.service");
15328
+ srcPath = path8.join(__dirname12, "..", "src", "data", "agent_moss.service");
14978
15329
  }
14979
15330
  if (!fs8.existsSync(srcPath)) {
14980
15331
  console.error("\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230 agent_moss.service \u6A21\u677F\u6587\u4EF6");
14981
15332
  process.exit(1);
14982
15333
  }
14983
15334
  const which = execSync("which agent-moss 2>/dev/null || true", { encoding: "utf-8" }).trim();
14984
- const binPath = which || `${process.execPath} ${path7.join(__dirname12, "cli.js")}`;
15335
+ const binPath = which || `${process.execPath} ${path8.join(__dirname12, "cli.js")}`;
14985
15336
  let content = fs8.readFileSync(srcPath, "utf-8");
14986
15337
  content = content.replace("__AGENT_MOSS_BIN__", binPath);
14987
15338
  const dst = "/etc/systemd/system/agent-moss.service";