@kenhkl/agent-moss 0.17.24 → 0.17.26

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
@@ -402,22 +402,22 @@ function loadToolRegistry() {
402
402
  data.tools = tools;
403
403
  return data;
404
404
  }
405
- function scanStructEntry(cat, value, path7) {
405
+ function scanStructEntry(cat, value, path8) {
406
406
  if (cat === "skills") {
407
407
  if (!value || typeof value !== "object" || Array.isArray(value)) {
408
- 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`);
409
409
  return null;
410
410
  }
411
411
  const out = {};
412
412
  for (const [skCat, skills] of Object.entries(value)) {
413
413
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
414
- 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`);
415
415
  continue;
416
416
  }
417
417
  const keep = {};
418
418
  for (const [name, kws] of Object.entries(skills)) {
419
419
  if (Array.isArray(kws)) keep[name] = kws;
420
- 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`);
421
421
  }
422
422
  if (Object.keys(keep).length > 0) out[skCat] = keep;
423
423
  }
@@ -425,37 +425,37 @@ function scanStructEntry(cat, value, path7) {
425
425
  }
426
426
  if (cat === "ltl_rules") {
427
427
  if (!Array.isArray(value)) {
428
- 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`);
429
429
  return null;
430
430
  }
431
431
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
432
432
  if (keep.length !== value.length) {
433
- 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`);
434
434
  }
435
435
  return keep.length > 0 ? keep : null;
436
436
  }
437
437
  if (cat === "tools") {
438
438
  if (!value || typeof value !== "object" || Array.isArray(value)) {
439
- 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`);
440
440
  return null;
441
441
  }
442
442
  const keep = {};
443
443
  for (const [k, v] of Object.entries(value)) {
444
444
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
445
- 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`);
446
446
  }
447
447
  return Object.keys(keep).length > 0 ? keep : null;
448
448
  }
449
449
  return null;
450
450
  }
451
- function scanRulesFile(path7, kind) {
451
+ function scanRulesFile(path8, kind) {
452
452
  const out = {};
453
453
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
454
454
  let parsed;
455
455
  try {
456
- parsed = JSON.parse(readFileSync2(path7, "utf-8"));
456
+ parsed = JSON.parse(readFileSync2(path8, "utf-8"));
457
457
  } catch (e) {
458
- 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}`);
459
459
  return out;
460
460
  }
461
461
  const classifyFlat = (r) => {
@@ -479,44 +479,44 @@ function scanRulesFile(path7, kind) {
479
479
  }
480
480
  if (flatBad > 0) {
481
481
  console.warn(
482
- `[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`
483
483
  );
484
484
  }
485
485
  } else {
486
- 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`);
487
487
  return out;
488
488
  }
489
489
  for (const [cat, rules] of pairs) {
490
490
  if (String(cat).startsWith("_")) continue;
491
491
  if (STRUCT_KEYS.includes(cat)) {
492
- const got = scanStructEntry(cat, rules, path7);
492
+ const got = scanStructEntry(cat, rules, path8);
493
493
  if (got !== null) out[cat] = got;
494
494
  continue;
495
495
  }
496
496
  const required = EXTRA_CATEGORIES[cat];
497
497
  if (!required) {
498
498
  console.warn(
499
- `[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`
500
500
  );
501
501
  continue;
502
502
  }
503
503
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
504
504
  console.error(
505
- `[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
506
506
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
507
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`
508
508
  );
509
509
  continue;
510
510
  }
511
511
  if (!Array.isArray(rules)) {
512
- 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`);
513
513
  continue;
514
514
  }
515
515
  const items = [];
516
516
  for (const r of rules) {
517
517
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
518
518
  console.warn(
519
- `[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`
520
520
  );
521
521
  continue;
522
522
  }
@@ -526,7 +526,7 @@ function scanRulesFile(path7, kind) {
526
526
  }
527
527
  if (Object.keys(out).length > 0) {
528
528
  console.info(
529
- `[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(", ")
530
530
  );
531
531
  }
532
532
  return out;
@@ -949,10 +949,10 @@ function readExplicitToken() {
949
949
  if (tok) return tok;
950
950
  const fdTok = readFdToken();
951
951
  if (fdTok) return fdTok;
952
- const path7 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
953
- if (path7) {
952
+ const path8 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
953
+ if (path8) {
954
954
  try {
955
- return readFileSync4(path7, "utf-8").trim();
955
+ return readFileSync4(path8, "utf-8").trim();
956
956
  } catch {
957
957
  return "";
958
958
  }
@@ -960,23 +960,23 @@ function readExplicitToken() {
960
960
  return "";
961
961
  }
962
962
  function ensureAutoToken() {
963
- const path7 = autoTokenPath();
963
+ const path8 = autoTokenPath();
964
964
  try {
965
- if (existsSync3(path7) && !lstatSync(path7).isSymbolicLink()) {
966
- const tok2 = readFileSync4(path7, "utf-8").trim();
965
+ if (existsSync3(path8) && !lstatSync(path8).isSymbolicLink()) {
966
+ const tok2 = readFileSync4(path8, "utf-8").trim();
967
967
  if (tok2) {
968
968
  try {
969
- chmodSync(path7, 384);
969
+ chmodSync(path8, 384);
970
970
  } catch {
971
971
  }
972
972
  return tok2;
973
973
  }
974
974
  }
975
975
  const tok = randomBytes(32).toString("base64url");
976
- ensurePrivateDir(dirname2(path7));
977
- if (!writePrivateText(path7, tok + "\n")) return "";
976
+ ensurePrivateDir(dirname2(path8));
977
+ if (!writePrivateText(path8, tok + "\n")) return "";
978
978
  console.warn(
979
- `[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`
980
980
  );
981
981
  return tok;
982
982
  } catch (e) {
@@ -1049,16 +1049,16 @@ function constEq(a, b) {
1049
1049
  if (ba.length !== bb.length) return false;
1050
1050
  return timingSafeEqual(ba, bb);
1051
1051
  }
1052
- function checkRequestAuth(headers, path7) {
1052
+ function checkRequestAuth(headers, path8) {
1053
1053
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
1054
- const isHealth = HEALTH_PATHS.includes(path7.replace(/\/+$/, ""));
1054
+ const isHealth = HEALTH_PATHS.includes(path8.replace(/\/+$/, ""));
1055
1055
  const [gt0, agents, err] = resolveAuth();
1056
1056
  if (err) return isHealth ? [true, ""] : [false, ""];
1057
1057
  if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
1058
1058
  if (isHealth) return [true, ""];
1059
1059
  const tok = bearer(headers);
1060
1060
  if (!tok) return [false, ""];
1061
- if (path7.startsWith("/console/api")) {
1061
+ if (path8.startsWith("/console/api")) {
1062
1062
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
1063
1063
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
1064
1064
  }
@@ -1077,8 +1077,8 @@ function bindAgent(principal, agentId) {
1077
1077
  if (!agentId) return [true, bound];
1078
1078
  return [bound === agentId, bound];
1079
1079
  }
1080
- function principalOf(headers, path7 = "") {
1081
- const [ok, principal] = checkRequestAuth(headers, path7);
1080
+ function principalOf(headers, path8 = "") {
1081
+ const [ok, principal] = checkRequestAuth(headers, path8);
1082
1082
  return ok ? principal : "";
1083
1083
  }
1084
1084
  function principalHash(principal) {
@@ -1335,11 +1335,11 @@ function errorDetailMode() {
1335
1335
  function maxBodyBytes() {
1336
1336
  return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
1337
1337
  }
1338
- function poolOf(path7) {
1339
- if (path7 === "/api/v1/analyze" || path7.startsWith("/api/v1/analyze/")) return "biz";
1340
- if (path7 === "/api/v1/review" || path7.startsWith("/api/v1/review/")) return "review";
1341
- if (path7 === "/console" || path7.startsWith("/console/") || path7.startsWith("/api/v1/brain")) return "ops";
1342
- 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";
1343
1343
  return "other";
1344
1344
  }
1345
1345
  function poolLimit(name) {
@@ -1772,6 +1772,8 @@ var init_platform_traits = __esm({
1772
1772
 
1773
1773
  // src/engine/logic-rules.ts
1774
1774
  import * as fs from "fs";
1775
+ import * as path2 from "path";
1776
+ import * as os from "os";
1775
1777
  function hasExecBypassChain(actionDetail) {
1776
1778
  const execAfter = "&&|\\|\\||;|\\n|\\|";
1777
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);
@@ -1798,7 +1800,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
1798
1800
  os: String(sp.os || "linux").toLowerCase()
1799
1801
  }));
1800
1802
  }
1801
- function _scopeOf(os4, path7) {
1803
+ function _scopeOf(os5, path8) {
1802
1804
  if (!_scopeIndex) {
1803
1805
  _scopeIndex = /* @__PURE__ */ new Map();
1804
1806
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -1806,7 +1808,7 @@ function _scopeOf(os4, path7) {
1806
1808
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
1807
1809
  }
1808
1810
  }
1809
- return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path7}`) || "root";
1811
+ return _scopeIndex.get(`${String(os5 || "linux").toLowerCase()}|${path8}`) || "root";
1810
1812
  }
1811
1813
  function getSensitivePathsForOs(osType) {
1812
1814
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -1848,6 +1850,188 @@ function getSensitivePathsForOsBuiltin(osType) {
1848
1850
  }
1849
1851
  return { root: ROOT_SENSITIVE_PATHS, home: HOME_SENSITIVE_PATHS, credential: CREDENTIAL_PATHS };
1850
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
+ }
1851
2035
  function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWORDS, osType) {
1852
2036
  if (writeKeywords.some((kw) => actionType.includes(kw) || actionDetail.includes(kw))) return true;
1853
2037
  const { writeCommandRes } = getPlatformTraits(osType);
@@ -1887,7 +2071,12 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
1887
2071
  }
1888
2072
  function getIntentPatternsForOs(osType) {
1889
2073
  const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
1890
- 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
+ }
1891
2080
  const accepted = acceptedOsValues(osType);
1892
2081
  return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
1893
2082
  }
@@ -1938,6 +2127,9 @@ function checkIntentConsistency(input) {
1938
2127
  );
1939
2128
  const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(actionDetail, kw));
1940
2129
  if (intentMatched && dangerousMatched) {
2130
+ if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
2131
+ continue;
2132
+ }
1941
2133
  return {
1942
2134
  allowed: false,
1943
2135
  reason: pattern.reason,
@@ -1958,7 +2150,16 @@ function runLogicCheck(input, opts) {
1958
2150
  const resolvedCwd = cwd || "/";
1959
2151
  const isExcludedType = EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p));
1960
2152
  if (!opts?.skipReadBeforeWrite) {
1961
- 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
+ );
1962
2163
  if (rbwResult) return rbwResult;
1963
2164
  }
1964
2165
  const intentResult = checkIntentConsistency(input);
@@ -2061,11 +2262,15 @@ function extractFilePaths(text, osType) {
2061
2262
  }
2062
2263
  return [...new Set(paths)];
2063
2264
  }
2064
- 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();
2065
2267
  if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
2066
2268
  if (NON_WRITE_TOOLS.has(actionType)) return null;
2067
2269
  const isBashLike = actionType === "bash" || actionType === "executebash" || actionType === "terminal-executebash";
2068
- const isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
2270
+ let isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
2271
+ if (!isWrite && /\btar\b/.test(actionDetail) && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(actionDetail)) {
2272
+ isWrite = true;
2273
+ }
2069
2274
  if (!isWrite) return null;
2070
2275
  const WRITE_CMDS = new Set(_LOGIC.write_commands ?? []);
2071
2276
  if (isBashLike) {
@@ -2087,6 +2292,10 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2087
2292
  hasWriteSeg = true;
2088
2293
  break;
2089
2294
  }
2295
+ if (fw === "tar" && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed) && /(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)\S+/.test(trimmed)) {
2296
+ hasWriteSeg = true;
2297
+ break;
2298
+ }
2090
2299
  if ((fw === "wget" || fw === "curl") && (/\s(?:-O|--output-document|--output)(?:=|\s|$)/i.test(trimmed) || /\s-O\S/.test(trimmed))) {
2091
2300
  hasWriteSeg = true;
2092
2301
  break;
@@ -2102,7 +2311,11 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2102
2311
  const SOURCE_ARG_CMDS = new Set(_LOGIC.source_arg_commands ?? []);
2103
2312
  const REDIRECT_TARGET_RE = new RegExp(`>{1,2}\\s*(?!&)(?:'(/[^']+)'|"(/[^\\"]+)"|(/[^\\s;|&><'\\"]+))`);
2104
2313
  const targetPaths = [];
2105
- for (const seg of splitCommandSegments(actionDetail)) {
2314
+ const singleFileTool = singleFileTools.has(actionType);
2315
+ if (singleFileTool && MISSING_WRITE_PATH_RE.test(actionDetailRaw)) {
2316
+ return null;
2317
+ }
2318
+ for (const seg of singleFileTool ? [] : splitCommandSegments(actionDetailRaw)) {
2106
2319
  const trimmed = seg.trim();
2107
2320
  if (!trimmed) continue;
2108
2321
  const firstWord = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
@@ -2122,6 +2335,11 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2122
2335
  const segPathsFiltered = firstWord === "wget" || firstWord === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
2123
2336
  if (SOURCE_ARG_CMDS.has(firstWord)) {
2124
2337
  if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
2338
+ } else if (firstWord === "tar") {
2339
+ if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
2340
+ const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
2341
+ if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
2342
+ }
2125
2343
  } else if (firstWord === "dd") {
2126
2344
  const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
2127
2345
  const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
@@ -2134,16 +2352,31 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2134
2352
  targetPaths.push(...segPathsFiltered);
2135
2353
  }
2136
2354
  }
2355
+ if (singleFileTool) {
2356
+ targetPaths.length = 0;
2357
+ targetPaths.push(...declaredWritePaths(actionDetailRaw, osType));
2358
+ }
2137
2359
  const uniqueTargetPaths = [...new Set(targetPaths)].filter((p) => !PSEUDO_FS_PREFIXES.some((pfx) => p.startsWith(pfx)));
2138
2360
  if (uniqueTargetPaths.length === 0) return null;
2139
- const historyReadPaths = /* @__PURE__ */ new Set();
2361
+ const historyFullReadPaths = /* @__PURE__ */ new Set();
2362
+ const historyPartialRead = /* @__PURE__ */ new Map();
2140
2363
  for (const action of actionHistory) {
2141
- const histDetail = action.actionDetail.toLowerCase();
2364
+ const histDetailRaw = action.actionDetail;
2142
2365
  const histType = action.actionType.toLowerCase();
2143
- const isRead = getPlatformTraits(osType).readKeywords.some((kw) => histType.includes(kw) || histDetail.includes(kw));
2144
- if (isRead) {
2145
- for (const p of extractFilePaths(histDetail, osType)) {
2146
- historyReadPaths.add(p);
2366
+ const traits = getPlatformTraits(osType);
2367
+ const coverage = historyReadCoverage(
2368
+ histType,
2369
+ histDetailRaw,
2370
+ traits.readKeywords,
2371
+ traits.writeKeywords
2372
+ );
2373
+ for (const p of coverage.full) historyFullReadPaths.add(p);
2374
+ for (const [p, upto] of coverage.partial) {
2375
+ if (historyPartialRead.has(p)) {
2376
+ const old = historyPartialRead.get(p);
2377
+ historyPartialRead.set(p, old == null || upto == null ? null : Math.max(old, upto));
2378
+ } else {
2379
+ historyPartialRead.set(p, upto);
2147
2380
  }
2148
2381
  }
2149
2382
  }
@@ -2156,18 +2389,49 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2156
2389
  if (filteredPaths.length === 0) {
2157
2390
  return null;
2158
2391
  }
2392
+ const normalizedTargets = filteredPaths.map((p) => normalizePathForCompare(p, cwd)).filter((p, i, arr) => p && arr.indexOf(p) === i);
2393
+ const normalizedFullReads = new Set(
2394
+ [...historyFullReadPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2395
+ );
2396
+ const normalizedPartialReads = /* @__PURE__ */ new Map();
2397
+ for (const [p, upto] of historyPartialRead) {
2398
+ const np = normalizePathForCompare(p, cwd);
2399
+ if (np) normalizedPartialReads.set(np, upto);
2400
+ }
2401
+ const appendTargets = appendOnlyTargets(actionDetailRaw, osType);
2402
+ if (APPEND_MODE_RE.test(actionDetailRaw)) {
2403
+ for (const p of filteredPaths) appendTargets.add(p);
2404
+ }
2405
+ let checkTargets = normalizedTargets;
2406
+ if (appendTargets.size > 0) {
2407
+ const appendNorm = new Set(
2408
+ [...appendTargets].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2409
+ );
2410
+ checkTargets = normalizedTargets.filter((p) => !([...appendNorm].some((ap) => pathIsSameOrUnder(p, ap) || pathIsSameOrUnder(ap, p)) && !isProtectedWritePath(p)));
2411
+ if (checkTargets.length === 0) return null;
2412
+ }
2159
2413
  const unreadPaths = [];
2160
- for (const path7 of filteredPaths) {
2161
- const hasRead = [...historyReadPaths].some(
2162
- (rp) => path7 === rp || path7.startsWith(rp) || rp.startsWith(path7)
2414
+ for (const path8 of checkTargets) {
2415
+ const isFullRead = [...normalizedFullReads].some(
2416
+ (rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
2163
2417
  );
2164
- if (!hasRead) {
2165
- let isCreate = !fs.existsSync(path7);
2418
+ let isPartialCovered = false;
2419
+ if (!isFullRead) {
2420
+ for (const [pp, upto] of normalizedPartialReads) {
2421
+ if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
2422
+ if (upto != null && fileHasAtMostLines(path8, upto)) {
2423
+ isPartialCovered = true;
2424
+ break;
2425
+ }
2426
+ }
2427
+ }
2428
+ if (!isFullRead && !isPartialCovered) {
2429
+ let isCreate = !fs.existsSync(path8);
2166
2430
  if (!isCreate) {
2167
2431
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
2168
2432
  }
2169
2433
  if (!isCreate) {
2170
- unreadPaths.push(path7);
2434
+ unreadPaths.push(path8);
2171
2435
  }
2172
2436
  }
2173
2437
  }
@@ -2344,7 +2608,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2344
2608
  violatedLayers: ["L2.1"]
2345
2609
  };
2346
2610
  }
2347
- 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;
2611
+ 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;
2348
2612
  var init_logic_rules = __esm({
2349
2613
  "src/engine/logic-rules.ts"() {
2350
2614
  "use strict";
@@ -2361,16 +2625,16 @@ var init_logic_rules = __esm({
2361
2625
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
2362
2626
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
2363
2627
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
2364
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2628
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2365
2629
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
2366
2630
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
2367
- CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2631
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2368
2632
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
2369
2633
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
2370
- CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2634
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2371
2635
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
2372
2636
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
2373
- CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2637
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2374
2638
  _scopeIndex = null;
2375
2639
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
2376
2640
  "ask_user_question",
@@ -2393,6 +2657,23 @@ var init_logic_rules = __esm({
2393
2657
  ]);
2394
2658
  NON_WRITE_TOOL_PREFIXES = _LOGIC.non_write_tool_prefixes ?? [];
2395
2659
  PSEUDO_FS_PREFIXES = ["/sys/", "/proc/", "/dev/", "/run/"];
2660
+ SINGLE_FILE_WRITE_TOOLS = new Set(
2661
+ _LOGIC.single_file_write_tools ?? []
2662
+ );
2663
+ WRITE_INTENT_KEYWORDS = _LOGIC.write_intent_keywords ?? [];
2664
+ MISSING_WRITE_PATH_RE = /(?:写入文件|编辑文件|写入|编辑)\s*[::]\s*\?/;
2665
+ DECLARED_WRITE_PATH_RE = /(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*([~./][^\s—|,;]+)/;
2666
+ DECLARED_WRITE_PATH_JSON_RE = /"(?:file_path|filePath|path)"\s*:\s*"([^"]+)"/;
2667
+ PROTECTED_WRITE_PREFIXES = _LOGIC.protected_write_prefixes ?? [];
2668
+ PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
2669
+ APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
2670
+ APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
2671
+ SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
2672
+ SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
2673
+ SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
2674
+ HEAD_TAIL_LIMIT_RE = /(?:-n\s*|-\s*)(\d+)/;
2675
+ SED_RANGE_RE = /-n\s+['"]?(\d+)\s*,\s*(\d+|\$)\s*p/;
2676
+ PARTIAL_COVER_CHECK_MAX_LINES = 1e5;
2396
2677
  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"];
2397
2678
  SED_INPLACE_RE = /\bsed\s+(?:-\S+\s+)*(?:-[a-zA-Z]*i[a-zA-Z]*|--in-place)\b/i;
2398
2679
  DEVNULL_REDIRECT_RE = /(?:2|&|1)?\s*>\s*\/dev\/null\b/g;
@@ -2411,7 +2692,8 @@ var init_logic_rules = __esm({
2411
2692
  intentKeywords: p.intent_keywords,
2412
2693
  dangerousActions: p.dangerous_actions,
2413
2694
  reason: p.reason,
2414
- os: String(p.os || "linux").toLowerCase()
2695
+ os: String(p.os || "linux").toLowerCase(),
2696
+ allowIfWriteIntent: p.allow_if_write_intent === true
2415
2697
  }));
2416
2698
  })();
2417
2699
  COMBO_STAGES = (() => {
@@ -2452,11 +2734,11 @@ var init_logic_rules = __esm({
2452
2734
 
2453
2735
  // src/engine/asset-dir.ts
2454
2736
  import { existsSync as existsSync5 } from "fs";
2455
- import { join as join5, resolve as resolve3 } from "path";
2737
+ import { join as join6, resolve as resolve3 } from "path";
2456
2738
  function assetDirCandidates(moduleDir, name) {
2457
2739
  const root = getRulesRoot();
2458
2740
  if (root) {
2459
- const p = join5(root, name);
2741
+ const p = join6(root, name);
2460
2742
  return [p, p];
2461
2743
  }
2462
2744
  return [
@@ -2675,7 +2957,7 @@ __export(runtime_config_exports, {
2675
2957
  updateSkillEnabled: () => updateSkillEnabled
2676
2958
  });
2677
2959
  import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
2678
- import { join as join6 } from "path";
2960
+ import { join as join7 } from "path";
2679
2961
  import { fileURLToPath as fileURLToPath4 } from "url";
2680
2962
  import { dirname as dirname4 } from "path";
2681
2963
  function runtimeDir() {
@@ -2811,8 +3093,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
2811
3093
  function _filterRulesByOs(rules, osType) {
2812
3094
  const accepted = acceptedOsValues(osType);
2813
3095
  return rules.filter((r) => {
2814
- const os4 = String(r.os || "linux").toLowerCase();
2815
- return os4 === "all" || accepted.includes(os4);
3096
+ const os5 = String(r.os || "linux").toLowerCase();
3097
+ return os5 === "all" || accepted.includes(os5);
2816
3098
  });
2817
3099
  }
2818
3100
  function _userCustomRules(runtime, layers, requiredKey) {
@@ -3014,7 +3296,7 @@ function _l2SensitivePathsToRules() {
3014
3296
  const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
3015
3297
  const all = [...root, ...home, ...credential];
3016
3298
  for (const sp of all) {
3017
- const os4 = String(sp.os || "linux").toLowerCase();
3299
+ const os5 = String(sp.os || "linux").toLowerCase();
3018
3300
  const denyMode = sp.denyMode || _deriveDenyMode({
3019
3301
  deny_mode: sp.deny_mode,
3020
3302
  credential: sp.credential,
@@ -3024,7 +3306,7 @@ function _l2SensitivePathsToRules() {
3024
3306
  // id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
3025
3307
  // hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
3026
3308
  // Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
3027
- id: `path_${os4}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3309
+ id: `path_${os5}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3028
3310
  path: sp.path,
3029
3311
  risk_level: sp.riskLevel,
3030
3312
  desc: sp.desc,
@@ -3033,7 +3315,7 @@ function _l2SensitivePathsToRules() {
3033
3315
  skip_l3_on_disabled: true,
3034
3316
  enabled: true,
3035
3317
  builtin: true,
3036
- os: os4
3318
+ os: os5
3037
3319
  };
3038
3320
  _syncDenyModeFields(rule);
3039
3321
  if (sp.dirDelOnly) rule.dir_del_only = true;
@@ -3051,6 +3333,9 @@ function _l2IntentPatternsToRules() {
3051
3333
  intent_keywords: pat.intentKeywords,
3052
3334
  dangerous_actions: pat.dangerousActions,
3053
3335
  reason: pat.reason,
3336
+ // 旧 runtime 里没有这个字段:缺省 false,但 getIntentPatternsForOs 会按
3337
+ // reason 回填内置默认值,避免旧配置让新豁免失效。
3338
+ allow_if_write_intent: pat.allowIfWriteIntent,
3054
3339
  skip_l3_on_disabled: true,
3055
3340
  enabled: true,
3056
3341
  builtin: true
@@ -3121,7 +3406,7 @@ function _l3SkillsToRules() {
3121
3406
  function _scenarioRulesToDefaults() {
3122
3407
  const out = {};
3123
3408
  const _root = getRulesRoot();
3124
- const scenDir = _root ? join6(_root, "scenarios") : existsSync7(_SCENARIOS_DIR_PROD) ? _SCENARIOS_DIR_PROD : existsSync7(_SCENARIOS_DIR_DEV) ? _SCENARIOS_DIR_DEV : _SCENARIOS_DIR_PROD;
3409
+ const scenDir = _root ? join7(_root, "scenarios") : existsSync7(_SCENARIOS_DIR_PROD) ? _SCENARIOS_DIR_PROD : existsSync7(_SCENARIOS_DIR_DEV) ? _SCENARIOS_DIR_DEV : _SCENARIOS_DIR_PROD;
3125
3410
  if (!existsSync7(scenDir)) return out;
3126
3411
  let entries;
3127
3412
  try {
@@ -3130,7 +3415,7 @@ function _scenarioRulesToDefaults() {
3130
3415
  return out;
3131
3416
  }
3132
3417
  for (const scenarioId of entries) {
3133
- const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join6(scenDir, scenarioId, "rules.json");
3418
+ const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join7(scenDir, scenarioId, "rules.json");
3134
3419
  if (!existsSync7(rulesFile)) continue;
3135
3420
  let data;
3136
3421
  try {
@@ -3171,7 +3456,7 @@ function _scenarioRulesToDefaults() {
3171
3456
  function _agentRulesToDefaults() {
3172
3457
  const out = {};
3173
3458
  const _root = getRulesRoot();
3174
- const agentsDir = _root ? join6(_root, "agents") : existsSync7(_AGENTS_DIR_PROD) ? _AGENTS_DIR_PROD : existsSync7(_AGENTS_DIR_DEV) ? _AGENTS_DIR_DEV : _AGENTS_DIR_PROD;
3459
+ const agentsDir = _root ? join7(_root, "agents") : existsSync7(_AGENTS_DIR_PROD) ? _AGENTS_DIR_PROD : existsSync7(_AGENTS_DIR_DEV) ? _AGENTS_DIR_DEV : _AGENTS_DIR_PROD;
3175
3460
  if (!existsSync7(agentsDir)) return out;
3176
3461
  let entries;
3177
3462
  try {
@@ -3180,7 +3465,7 @@ function _agentRulesToDefaults() {
3180
3465
  return out;
3181
3466
  }
3182
3467
  for (const agentId of entries) {
3183
- const rulesFile = join6(agentsDir, agentId, "rules.json");
3468
+ const rulesFile = join7(agentsDir, agentId, "rules.json");
3184
3469
  if (!existsSync7(rulesFile)) continue;
3185
3470
  let data;
3186
3471
  try {
@@ -3213,6 +3498,11 @@ function _agentRulesToDefaults() {
3213
3498
  category_enabled: true,
3214
3499
  category_desc: "agent \u4E13\u5C5E\u654F\u611F\u8DEF\u5F84\uFF08L1 \u672B\u5C3E\u8FFD\u52A0\uFF09",
3215
3500
  rules: (data.extra_sensitive_paths || []).map((sp) => ({ ...sp, enabled: true, builtin: true }))
3501
+ },
3502
+ extra_single_file_write_tools: {
3503
+ category_enabled: true,
3504
+ category_desc: "agent \u4E13\u5C5E\u5355\u6587\u4EF6\u5199\u5DE5\u5177\uFF08read_before_write \u53EA\u53D6\u58F0\u660E\u8DEF\u5F84\uFF09",
3505
+ rules: (data.extra_single_file_write_tools || []).map((v) => ({ value: v, enabled: true, builtin: true }))
3216
3506
  }
3217
3507
  };
3218
3508
  }
@@ -3517,7 +3807,9 @@ function getEnabledL2IntentPatterns(runtime, osType) {
3517
3807
  return rules.map((r) => ({
3518
3808
  intent_keywords: r.intent_keywords || [],
3519
3809
  dangerous_actions: r.dangerous_actions || [],
3520
- reason: r.reason || ""
3810
+ reason: r.reason || "",
3811
+ allow_if_write_intent: r.allow_if_write_intent === true,
3812
+ os: r.os
3521
3813
  }));
3522
3814
  }
3523
3815
  function getEnabledL2PasswordPatterns(runtime) {
@@ -3561,8 +3853,8 @@ function _filterDefaultsByOs(rules, osType) {
3561
3853
  const accepted = acceptedOsValues(osType);
3562
3854
  return rules.filter((r) => {
3563
3855
  if (!r.os) return true;
3564
- const os4 = String(r.os).toLowerCase();
3565
- return os4 === "all" || accepted.includes(os4);
3856
+ const os5 = String(r.os).toLowerCase();
3857
+ return os5 === "all" || accepted.includes(os5);
3566
3858
  });
3567
3859
  }
3568
3860
  function _hasRulesForOs(rules, osType) {
@@ -3687,7 +3979,8 @@ function effectiveIntentPatterns(osType) {
3687
3979
  intentKeywords: r.intent_keywords || [],
3688
3980
  dangerousActions: r.dangerous_actions || [],
3689
3981
  reason: String(r.reason || ""),
3690
- os: String(r.os || "linux").toLowerCase()
3982
+ os: String(r.os || "linux").toLowerCase(),
3983
+ allowIfWriteIntent: r.allow_if_write_intent === true
3691
3984
  }));
3692
3985
  });
3693
3986
  }
@@ -3792,12 +4085,12 @@ function addCustomSkill(skillId, category, keywords, content) {
3792
4085
  );
3793
4086
  }
3794
4087
  const runtime = loadRuntimeConfig();
3795
- const skillsDir = join6(getRuntimeConfigDir(), "agent_moss_skills");
4088
+ const skillsDir = join7(getRuntimeConfigDir(), "agent_moss_skills");
3796
4089
  try {
3797
4090
  mkdirSync2(skillsDir, { recursive: true });
3798
4091
  } catch {
3799
4092
  }
3800
- writeFileSync(join6(skillsDir, `${skillId}.md`), content, "utf-8");
4093
+ writeFileSync(join7(skillsDir, `${skillId}.md`), content, "utf-8");
3801
4094
  const l3 = runtime.L3_skills || (runtime.L3_skills = {});
3802
4095
  const cat = l3[category] || (l3[category] = { category_enabled: true, category_desc: "", skills: [] });
3803
4096
  (cat.skills || (cat.skills = [])).push({ id: skillId, keywords, enabled: true, builtin: false });
@@ -3812,7 +4105,7 @@ function deleteCustomSkill(skillId, category) {
3812
4105
  if (idx >= 0) {
3813
4106
  if (skills[idx].builtin) return null;
3814
4107
  skills.splice(idx, 1);
3815
- const skillPath = join6(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
4108
+ const skillPath = join7(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
3816
4109
  try {
3817
4110
  if (existsSync7(skillPath)) unlinkSync(skillPath);
3818
4111
  } catch {
@@ -3875,6 +4168,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
3875
4168
  read_only: r.read_only,
3876
4169
  deny_mode: r.deny_mode
3877
4170
  }));
4171
+ const singleFileWriteTools = _agentCategoryEnabledRules(agentData.extra_single_file_write_tools).filter((r) => r.value).map((r) => String(r.value).toLowerCase());
3878
4172
  return {
3879
4173
  agent_id: agentId,
3880
4174
  description: "",
@@ -3883,6 +4177,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
3883
4177
  extra_sensitive_paths: sensitivePaths,
3884
4178
  builtin_safe_skills: safeSkills.filter((r) => r.value).map((r) => r.value),
3885
4179
  builtin_safe_action_types: safeAction.filter((r) => r.value).map((r) => r.value),
4180
+ extra_single_file_write_tools: singleFileWriteTools,
3886
4181
  extra_skills: []
3887
4182
  };
3888
4183
  }
@@ -3961,6 +4256,7 @@ function getEnabledScenarioExtensions(runtime, scenarioId) {
3961
4256
  extra_sensitive_paths: sensitivePaths,
3962
4257
  builtin_safe_skills: [],
3963
4258
  builtin_safe_action_types: [],
4259
+ extra_single_file_write_tools: [],
3964
4260
  extra_skills: []
3965
4261
  };
3966
4262
  }
@@ -4021,7 +4317,7 @@ var init_runtime_config = __esm({
4021
4317
  __dirname4 = dirname4(fileURLToPath4(import.meta.url));
4022
4318
  ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
4023
4319
  RUNTIME_CONFIG_DIR = runtimeDir();
4024
- RUNTIME_CONFIG_PATH = join6(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
4320
+ RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
4025
4321
  LAYER_DISABLE_ENV = {
4026
4322
  L1_heuristic: "AGENT_MOSS_DISABLE_HEURISTIC",
4027
4323
  L2_logic_rules: "AGENT_MOSS_DISABLE_LOGIC_RULES",
@@ -4049,10 +4345,10 @@ var init_runtime_config = __esm({
4049
4345
  intent_consistency: ["intent_keywords", "reason"]
4050
4346
  };
4051
4347
  hasRuntimeConfigCache = /* @__PURE__ */ new Map();
4052
- _AGENTS_DIR_PROD = join6(__dirname4, "agents");
4053
- _AGENTS_DIR_DEV = join6(__dirname4, "..", "..", "..", "agent_moss", "agents");
4054
- _SCENARIOS_DIR_PROD = join6(__dirname4, "scenarios");
4055
- _SCENARIOS_DIR_DEV = join6(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
4348
+ _AGENTS_DIR_PROD = join7(__dirname4, "agents");
4349
+ _AGENTS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "agents");
4350
+ _SCENARIOS_DIR_PROD = join7(__dirname4, "scenarios");
4351
+ _SCENARIOS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
4056
4352
  _effectiveCache = /* @__PURE__ */ new WeakMap();
4057
4353
  SKILL_ID_RE = /^[A-Za-z0-9_-]+$/;
4058
4354
  registerRuntimeConfigBridge({
@@ -4095,7 +4391,7 @@ __export(config_exports, {
4095
4391
  wildcardToRegExp: () => wildcardToRegExp
4096
4392
  });
4097
4393
  import fs2 from "fs";
4098
- import path2 from "path";
4394
+ import path3 from "path";
4099
4395
  import { fileURLToPath as fileURLToPath5 } from "url";
4100
4396
  function loadConfigFile(filePath) {
4101
4397
  try {
@@ -4108,17 +4404,17 @@ function loadConfigFile(filePath) {
4108
4404
  function resolveConfigPath() {
4109
4405
  const envPath = process.env.AGENT_MOSS_CONFIG_PATH;
4110
4406
  if (envPath) return envPath;
4111
- const userConfig = path2.join(getConfigDir(), "config.json");
4407
+ const userConfig = path3.join(getConfigDir(), "config.json");
4112
4408
  if (fs2.existsSync(userConfig)) return userConfig;
4113
4409
  const defaultCandidates = [
4114
- path2.join(__configModuleDir, "config.json.example"),
4115
- path2.join(__configModuleDir, "..", "config.json.example"),
4116
- path2.join(__configModuleDir, "..", "..", "agent_moss", "infra", "config.json.example"),
4117
- path2.join(__configModuleDir, "..", "..", "..", "agent_moss", "infra", "config.json.example")
4410
+ path3.join(__configModuleDir, "config.json.example"),
4411
+ path3.join(__configModuleDir, "..", "config.json.example"),
4412
+ path3.join(__configModuleDir, "..", "..", "agent_moss", "infra", "config.json.example"),
4413
+ path3.join(__configModuleDir, "..", "..", "..", "agent_moss", "infra", "config.json.example")
4118
4414
  ];
4119
4415
  const defaultConfig = defaultCandidates.find((p) => fs2.existsSync(p));
4120
4416
  if (defaultConfig) {
4121
- const configDir = path2.dirname(userConfig);
4417
+ const configDir = path3.dirname(userConfig);
4122
4418
  fs2.mkdirSync(configDir, { recursive: true });
4123
4419
  const pkgConfig = loadConfigFile(defaultConfig);
4124
4420
  const safeConfig = pkgConfig ? { ...pkgConfig, llm: { ...pkgConfig.llm, api_key: "" } } : {};
@@ -4348,7 +4644,7 @@ var init_config = __esm({
4348
4644
  init_rules_mode();
4349
4645
  __configModuleDir = (() => {
4350
4646
  try {
4351
- return path2.dirname(fileURLToPath5(import.meta.url));
4647
+ return path3.dirname(fileURLToPath5(import.meta.url));
4352
4648
  } catch {
4353
4649
  return typeof __dirname !== "undefined" ? __dirname : process.cwd();
4354
4650
  }
@@ -4371,11 +4667,11 @@ var init_config = __esm({
4371
4667
  };
4372
4668
  })();
4373
4669
  USER_RULES_PATHS = [
4374
- path2.join(__configModuleDir, "rules", "user_rules.json"),
4670
+ path3.join(__configModuleDir, "rules", "user_rules.json"),
4375
4671
  // 源在 ts/src/rules(一般不存在)
4376
- path2.join(__configModuleDir, "..", "rules", "user_rules.json"),
4672
+ path3.join(__configModuleDir, "..", "rules", "user_rules.json"),
4377
4673
  // dist: dist/engine/../rules = dist/rules ✅
4378
- path2.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
4674
+ path3.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
4379
4675
  // dev src: ts/src/../../agent_moss
4380
4676
  ];
4381
4677
  customRules = loadCustomRules();
@@ -4393,11 +4689,11 @@ var init_config = __esm({
4393
4689
 
4394
4690
  // src/agents/index.ts
4395
4691
  import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
4396
- import { resolve as resolve5, dirname as dirname5, join as join7 } from "path";
4692
+ import { resolve as resolve5, dirname as dirname5, join as join8 } from "path";
4397
4693
  import { fileURLToPath as fileURLToPath6 } from "url";
4398
4694
  function resolveAgentsDir() {
4399
4695
  const root = getRulesRoot();
4400
- if (root) return join7(root, "agents");
4696
+ if (root) return join8(root, "agents");
4401
4697
  if (existsSync8(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
4402
4698
  if (existsSync8(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
4403
4699
  return AGENTS_DIR_PROD;
@@ -4458,6 +4754,7 @@ function mergeAgentExtensions(...exts) {
4458
4754
  extra_sensitive_paths: nonNull.flatMap((e) => e.extra_sensitive_paths || []),
4459
4755
  builtin_safe_skills: nonNull.flatMap((e) => e.builtin_safe_skills || []),
4460
4756
  builtin_safe_action_types: nonNull.flatMap((e) => e.builtin_safe_action_types || []),
4757
+ extra_single_file_write_tools: nonNull.flatMap((e) => e.extra_single_file_write_tools || []),
4461
4758
  extra_skills: nonNull.flatMap((e) => e.extra_skills || [])
4462
4759
  };
4463
4760
  }
@@ -4479,11 +4776,11 @@ var init_agents = __esm({
4479
4776
 
4480
4777
  // src/scenarios/index.ts
4481
4778
  import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
4482
- import { resolve as resolve6, dirname as dirname6, join as join8 } from "path";
4779
+ import { resolve as resolve6, dirname as dirname6, join as join9 } from "path";
4483
4780
  import { fileURLToPath as fileURLToPath7 } from "url";
4484
4781
  function resolveScenariosDir() {
4485
4782
  const root = getRulesRoot();
4486
- if (root) return join8(root, "scenarios");
4783
+ if (root) return join9(root, "scenarios");
4487
4784
  if (existsSync9(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
4488
4785
  if (existsSync9(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
4489
4786
  return SCENARIOS_DIR_PROD;
@@ -4541,6 +4838,7 @@ function getScenarioExtensions(scenarioId) {
4541
4838
  extra_sensitive_paths: data.extra_sensitive_paths || [],
4542
4839
  builtin_safe_skills: data.builtin_safe_skills || [],
4543
4840
  builtin_safe_action_types: data.builtin_safe_action_types || [],
4841
+ extra_single_file_write_tools: data.extra_single_file_write_tools || [],
4544
4842
  extra_skills: data.extra_skills || []
4545
4843
  };
4546
4844
  } catch (e) {
@@ -4582,6 +4880,256 @@ var init_scenarios = __esm({
4582
4880
  }
4583
4881
  });
4584
4882
 
4883
+ // src/engine/written-content-analyzer.ts
4884
+ function isFileWriteAction(actionType) {
4885
+ const at = (actionType || "").toLowerCase();
4886
+ if (WRITE_TOOL_EXACT.has(at)) return true;
4887
+ if (WRITE_TOOL_SUFFIXES.some((s) => at.endsWith(s))) return true;
4888
+ return false;
4889
+ }
4890
+ function isApplyPatch(actionType) {
4891
+ const at = (actionType || "").toLowerCase();
4892
+ return APPLY_PATCH_SUFFIXES.some((s) => at.endsWith(s));
4893
+ }
4894
+ function extractWritePayload(actionType, actionDetailRaw) {
4895
+ if (isApplyPatch(actionType)) return null;
4896
+ const detail = actionDetailRaw || "";
4897
+ const m = detail.match(WRITE_PREFIX_RE);
4898
+ if (m) {
4899
+ const path8 = m[1];
4900
+ let content = m[2] || "";
4901
+ if (!path8 || path8 === "?" || path8 === "-" || !content.trim()) return null;
4902
+ if ((actionType || "").toLowerCase().includes("editfile")) {
4903
+ const nm = content.match(EDIT_NEW_RE);
4904
+ if (nm) content = nm[1];
4905
+ }
4906
+ return { path: path8, content };
4907
+ }
4908
+ const stripped = detail.trim();
4909
+ if (stripped.startsWith("{")) {
4910
+ try {
4911
+ const obj = JSON.parse(stripped);
4912
+ if (obj && typeof obj === "object") {
4913
+ const path8 = obj.path || obj.file_path || obj.filePath;
4914
+ const content = obj.content || obj.newString || obj.new_string;
4915
+ if (typeof path8 === "string" && path8 !== "" && path8 !== "?" && path8 !== "-" && typeof content === "string" && content.trim()) {
4916
+ return { path: path8, content };
4917
+ }
4918
+ }
4919
+ } catch {
4920
+ }
4921
+ }
4922
+ return null;
4923
+ }
4924
+ function handlesWrittenContent(actionType, actionDetailRaw) {
4925
+ if (!isFileWriteAction(actionType)) return false;
4926
+ if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
4927
+ return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
4928
+ }
4929
+ function detectLanguage(path8, content) {
4930
+ const ext = path8.slice(path8.lastIndexOf(".") >= 0 ? path8.lastIndexOf(".") : path8.length).toLowerCase();
4931
+ if (SHELL_EXTS.has(ext)) return "shell";
4932
+ if (PY_EXTS.has(ext)) return "python";
4933
+ if (DATA_EXTS.has(ext)) return "data";
4934
+ if (!ext) {
4935
+ const first = content.trim() ? content.trim().split(/\r?\n/)[0] : "";
4936
+ if (first.startsWith("#!")) {
4937
+ if (/\b(?:ba|z|k|da)?sh\b/.test(first)) return "shell";
4938
+ if (first.includes("python")) return "python";
4939
+ }
4940
+ return "data";
4941
+ }
4942
+ return "other";
4943
+ }
4944
+ function stripShellComments(text) {
4945
+ const out = [];
4946
+ for (const line of text.split(/\r?\n/)) {
4947
+ const res = [];
4948
+ let quote = null;
4949
+ for (let i = 0; i < line.length; i++) {
4950
+ const ch = line[i];
4951
+ if (quote) {
4952
+ res.push(ch);
4953
+ if (ch === quote) quote = null;
4954
+ continue;
4955
+ }
4956
+ if (ch === "'" || ch === '"') {
4957
+ quote = ch;
4958
+ res.push(ch);
4959
+ continue;
4960
+ }
4961
+ if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) break;
4962
+ res.push(ch);
4963
+ }
4964
+ out.push(res.join(""));
4965
+ }
4966
+ return out.join("\n");
4967
+ }
4968
+ function stripShellDocsOnly(content) {
4969
+ if (!content) return content;
4970
+ if (INTERP_HEREDOC_RE.test(content)) return content;
4971
+ const withoutHeredoc = content.replace(QUOTED_HEREDOC_RE, "<<quoted-heredoc>>\n");
4972
+ return stripShellComments(withoutHeredoc);
4973
+ }
4974
+ function lineSnippets(content, precheck) {
4975
+ const lines = content.split(/\r?\n/);
4976
+ const picked = /* @__PURE__ */ new Set();
4977
+ for (let i = 0; i < lines.length; i++) {
4978
+ precheck.lastIndex = 0;
4979
+ if (precheck.test(lines[i])) {
4980
+ picked.add(i - 1);
4981
+ picked.add(i);
4982
+ picked.add(i + 1);
4983
+ }
4984
+ }
4985
+ const snippets = [];
4986
+ let total = 0;
4987
+ for (const i of [...picked].sort((a, b) => a - b)) {
4988
+ if (i < 0 || i >= lines.length) continue;
4989
+ const s = lines[i];
4990
+ if (total + s.length > MAX_SCAN) break;
4991
+ snippets.push(s);
4992
+ total += s.length + 1;
4993
+ }
4994
+ return snippets;
4995
+ }
4996
+ function stripPythonLiterals(content) {
4997
+ const chars = content.split("");
4998
+ let i = 0;
4999
+ const n = chars.length;
5000
+ while (i < n) {
5001
+ const ch = chars[i];
5002
+ if (ch === "#") {
5003
+ while (i < n && chars[i] !== "\n") {
5004
+ chars[i] = " ";
5005
+ i++;
5006
+ }
5007
+ continue;
5008
+ }
5009
+ if (ch === "'" || ch === '"') {
5010
+ const triple = chars[i + 1] === ch && chars[i + 2] === ch;
5011
+ const quoteLen = triple ? 3 : 1;
5012
+ const q = ch;
5013
+ i += quoteLen;
5014
+ while (i < n) {
5015
+ if (chars[i] === "\\") {
5016
+ chars[i] = " ";
5017
+ if (i + 1 < n) chars[i + 1] = " ";
5018
+ i += 2;
5019
+ continue;
5020
+ }
5021
+ if (chars[i] === q && (!triple || chars[i + 1] === q && chars[i + 2] === q)) {
5022
+ for (let k = 0; k < quoteLen; k++) {
5023
+ chars[i + k] = " ";
5024
+ }
5025
+ i += quoteLen;
5026
+ break;
5027
+ }
5028
+ chars[i] = " ";
5029
+ i++;
5030
+ }
5031
+ continue;
5032
+ }
5033
+ i++;
5034
+ }
5035
+ return chars.join("");
5036
+ }
5037
+ function balancedArgs(original, openIndex) {
5038
+ let depth = 0;
5039
+ let quote = null;
5040
+ for (let i = openIndex; i < original.length && i < openIndex + 8e3; i++) {
5041
+ const ch = original[i];
5042
+ if (quote) {
5043
+ if (ch === "\\") {
5044
+ i++;
5045
+ continue;
5046
+ }
5047
+ if (ch === quote) quote = null;
5048
+ continue;
5049
+ }
5050
+ if (ch === "'" || ch === '"') {
5051
+ quote = ch;
5052
+ continue;
5053
+ }
5054
+ if (ch === "(") depth++;
5055
+ else if (ch === ")") {
5056
+ depth--;
5057
+ if (depth === 0) return original.slice(openIndex + 1, i);
5058
+ }
5059
+ }
5060
+ return original.slice(openIndex + 1, Math.min(original.length, openIndex + 2e3));
5061
+ }
5062
+ function pythonSnippets(content) {
5063
+ const stripped = stripPythonLiterals(content);
5064
+ const snippets = [];
5065
+ PY_DANGEROUS_CALL_RE.lastIndex = 0;
5066
+ let m;
5067
+ while ((m = PY_DANGEROUS_CALL_RE.exec(stripped)) !== null) {
5068
+ const callName = m[0].replace(/\s*\($/, "").trim();
5069
+ const openIndex = m.index + m[0].length - 1;
5070
+ const args = balancedArgs(content, openIndex);
5071
+ snippets.push(`${callName}(${args})`);
5072
+ if (snippets.length >= 200) break;
5073
+ }
5074
+ return snippets;
5075
+ }
5076
+ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper) {
5077
+ if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
5078
+ const payload = extractWritePayload(actionType, actionDetailRaw);
5079
+ if (!payload) return [];
5080
+ const { path: path8, content: rawContent } = payload;
5081
+ const language = detectLanguage(path8, rawContent);
5082
+ if (language === "data") return [];
5083
+ let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
5084
+ const started = Date.now();
5085
+ if (language === "python") {
5086
+ if (!PY_PRECHECK.test(content)) return [];
5087
+ return pythonSnippets(content);
5088
+ }
5089
+ content = stripShellDocsOnly(content);
5090
+ if (literalStripper) content = literalStripper(content);
5091
+ if (!SHELL_PRECHECK.test(content)) return [];
5092
+ const snippets = lineSnippets(content, SHELL_PRECHECK);
5093
+ if (Date.now() - started > MAX_MS) {
5094
+ return snippets;
5095
+ }
5096
+ return snippets;
5097
+ }
5098
+ var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE;
5099
+ var init_written_content_analyzer = __esm({
5100
+ "src/engine/written-content-analyzer.ts"() {
5101
+ "use strict";
5102
+ init_esm_shims();
5103
+ init_rules_loader();
5104
+ CFG = loadHeuristicRules().write_content_analysis || {};
5105
+ DATA_EXTS = new Set((CFG.data_exts || []).map((e) => e.toLowerCase()));
5106
+ SHELL_EXTS = new Set((CFG.shell_exts || []).map((e) => e.toLowerCase()));
5107
+ PY_EXTS = new Set((CFG.python_exts || []).map((e) => e.toLowerCase()));
5108
+ SHELL_PRECHECK = new RegExp(CFG.shell_precheck || "$^");
5109
+ PY_PRECHECK = new RegExp(CFG.python_precheck || "$^");
5110
+ MAX_CONTENT = Number(CFG.max_content_bytes || 262144);
5111
+ MAX_SCAN = Number(CFG.max_scan_bytes || 65536);
5112
+ MAX_MS = Number(CFG.max_scan_ms || 100);
5113
+ WRITE_TOOL_EXACT = /* @__PURE__ */ new Set([
5114
+ "write",
5115
+ "file_write",
5116
+ "writefile",
5117
+ "edit",
5118
+ "file_edit",
5119
+ "editfile",
5120
+ "searchreplace",
5121
+ "search_replace"
5122
+ ]);
5123
+ WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
5124
+ APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
5125
+ WRITE_PREFIX_RE = /^(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*(.+?)\s*(?:\(\s*追加\s*\))?\s*—\s*([\s\S]*)$/;
5126
+ EDIT_NEW_RE = /\|\s*new:\s*([\s\S]*)$/i;
5127
+ INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
5128
+ QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
5129
+ PY_DANGEROUS_CALL_RE = /(?:os\.(?:system|popen|remove|unlink|rmdir|chmod|chown|kill|spawn\w*)|subprocess\.\w+|pty\.\w+|ctypes\.\w+|eval|exec|compile|__import__|shutil\.(?:rmtree|move|copy\w*))\s*\(/g;
5130
+ }
5131
+ });
5132
+
4585
5133
  // src/engine/heuristic.ts
4586
5134
  function _effectiveDangerousPatterns(osType) {
4587
5135
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
@@ -4689,8 +5237,16 @@ function runHeuristicCheck(input) {
4689
5237
  } catch {
4690
5238
  }
4691
5239
  }
4692
- const scanDetail = normalizePathSegments(stripLiteralTextSegments(input.aNext.actionDetail));
4693
- const scanCommands = String(input.osType || "").toLowerCase() === "windows" ? [
5240
+ const scanDetail = normalizePathSegments(
5241
+ stripLiteralTextSegments(stripShellDocsOnly(input.aNext.actionDetail))
5242
+ );
5243
+ const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
5244
+ const writeSnippets = extractDangerousSnippets(
5245
+ input.aNext.actionType,
5246
+ input.aNext.actionDetail,
5247
+ stripLiteralTextSegments
5248
+ );
5249
+ const scanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => [`${input.aNext.actionType}: ${sn}`, sn]) : String(input.osType || "").toLowerCase() === "windows" ? [
4694
5250
  `${input.aNext.actionType}: ${scanDetail}`,
4695
5251
  scanDetail,
4696
5252
  `${input.aNext.actionType}: ${scanDetail.replace(/\//g, "\\")}`,
@@ -4751,9 +5307,9 @@ function runHeuristicCheck(input) {
4751
5307
  const actionTypeL = input.aNext.actionType.toLowerCase();
4752
5308
  const detailL = input.aNext.actionDetail.toLowerCase();
4753
5309
  const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
4754
- const dangerousResult = checkDangerousPatterns(actionTypeL, detailL);
5310
+ const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
4755
5311
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
4756
- const homeResult = checkHomeDeletion(actionTypeL, detailL);
5312
+ const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
4757
5313
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
4758
5314
  if (mergeResults.length > 0) {
4759
5315
  let best = mergeResults[0];
@@ -4973,16 +5529,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4973
5529
  if (String(osType || "").toLowerCase() === "windows") {
4974
5530
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
4975
5531
  }
4976
- const pathMatches = (text, path7) => {
4977
- const parts = path7.split(/(\(\?!.*?\))/);
5532
+ const pathMatches = (text, path8) => {
5533
+ const parts = path8.split(/(\(\?!.*?\))/);
4978
5534
  const escaped = parts.map((part) => {
4979
5535
  if (part.startsWith("(?!")) return part;
4980
5536
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4981
5537
  }).join("");
4982
- const re = path7.startsWith(".") || path7.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
5538
+ const re = path8.startsWith(".") || path8.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4983
5539
  return re.test(text);
4984
5540
  };
4985
- const pathMatchesAny = (path7) => pathScanTexts.some((t) => pathMatches(t, path7));
5541
+ const pathMatchesAny = (path8) => pathScanTexts.some((t) => pathMatches(t, path8));
4986
5542
  for (const sp of rootPaths) {
4987
5543
  if (pathMatchesAny(sp.path.toLowerCase())) {
4988
5544
  if (keygenGenerate) continue;
@@ -5125,8 +5681,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5125
5681
  }
5126
5682
  return null;
5127
5683
  }
5128
- function isHomeValue(path7) {
5129
- let p = path7.trim().toLowerCase();
5684
+ function isHomeValue(path8) {
5685
+ let p = path8.trim().toLowerCase();
5130
5686
  if (p.startsWith("$(") && p.endsWith(")")) {
5131
5687
  const inner = p.slice(2, -1).trim();
5132
5688
  return HOME_TARGET_RE.test(" " + inner);
@@ -5182,15 +5738,15 @@ function checkHomeDeletion(actionType, actionDetail) {
5182
5738
  }
5183
5739
  const assigned = {};
5184
5740
  for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
5185
- for (const [varName, path7] of Object.entries(assigned)) {
5186
- if (!isHomeValue(path7)) continue;
5741
+ for (const [varName, path8] of Object.entries(assigned)) {
5742
+ if (!isHomeValue(path8)) continue;
5187
5743
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
5188
5744
  for (const seg of segs) {
5189
5745
  if (!isDeleteCommand(seg)) continue;
5190
5746
  if (varRefRe.test(seg)) {
5191
5747
  return {
5192
5748
  allowed: false,
5193
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path7}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5749
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path8}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5194
5750
  riskLevel: "high",
5195
5751
  riskType: "script_execution",
5196
5752
  confidence: 90,
@@ -5251,7 +5807,7 @@ function isSshKeygenGenerate(command) {
5251
5807
  }
5252
5808
  function checkDangerousPatterns(actionType, actionDetail) {
5253
5809
  if (actionType === "file_write" || actionType === "file_edit") return null;
5254
- const scan = stripHeredocContent(actionDetail);
5810
+ const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
5255
5811
  const isTempPath = TEMP_DIRS2.some(
5256
5812
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
5257
5813
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
@@ -5409,6 +5965,7 @@ var init_heuristic = __esm({
5409
5965
  init_runtime_config();
5410
5966
  init_runtime_config_bridge();
5411
5967
  init_rules_loader();
5968
+ init_written_content_analyzer();
5412
5969
  init_logic_rules();
5413
5970
  INJECTION_KEYWORDS = (() => {
5414
5971
  const kws = loadL1().injection_detection || [];
@@ -5486,7 +6043,7 @@ var init_template_loader = __esm({
5486
6043
 
5487
6044
  // src/engine/script-analyzer.ts
5488
6045
  import { readFileSync as readFileSync10 } from "fs";
5489
- import { resolve as resolve8, join as join9 } from "path";
6046
+ import { resolve as resolve8, join as join10 } from "path";
5490
6047
  function emptyResult() {
5491
6048
  return { scriptPath: "", scriptContent: "", matchedKeywords: [], lineCount: 0, isSuspicious: false, error: "", riskLevel: "", riskReason: "" };
5492
6049
  }
@@ -5539,7 +6096,7 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
5539
6096
  }
5540
6097
  function readScriptContent(scriptPath, maxLines = 500) {
5541
6098
  try {
5542
- const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join9(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
6099
+ const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join10(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
5543
6100
  const raw = readFileSync10(expandedPath, "utf-8");
5544
6101
  const lines = raw.split("\n").slice(0, maxLines);
5545
6102
  return { content: lines.join("\n"), lineCount: lines.length, error: "" };
@@ -5994,15 +6551,15 @@ function parseShellString(s) {
5994
6551
  let m;
5995
6552
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
5996
6553
  const interp = m[1];
5997
- const path7 = m[2].trim();
6554
+ const path8 = m[2].trim();
5998
6555
  let rest = m[3].trim();
5999
- if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6556
+ if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6000
6557
  rest = rest.split(/[;|&<>]/)[0].trim();
6001
6558
  const args = [];
6002
6559
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6003
6560
  args.push(tm[1] ? tm[2] : tm[3]);
6004
6561
  }
6005
- return { path: path7, args, interpreter: interp };
6562
+ return { path: path8, args, interpreter: interp };
6006
6563
  }
6007
6564
  return null;
6008
6565
  }
@@ -6048,9 +6605,9 @@ function extractCallsFromTree(tree, reachableLines) {
6048
6605
  }
6049
6606
  if (allStr && elts.length >= 2) {
6050
6607
  const interp = elts[0];
6051
- const path7 = elts[1];
6052
- if (!path7.startsWith("-") && !path7.startsWith("$") && !path7.includes("/dev/")) {
6053
- add({ path: path7, args: elts.slice(2), interpreter: interp });
6608
+ const path8 = elts[1];
6609
+ if (!path8.startsWith("-") && !path8.startsWith("$") && !path8.includes("/dev/")) {
6610
+ add({ path: path8, args: elts.slice(2), interpreter: interp });
6054
6611
  return true;
6055
6612
  }
6056
6613
  }
@@ -6090,15 +6647,15 @@ function extractCallsRegex(content) {
6090
6647
  let m;
6091
6648
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
6092
6649
  const interp = m[1];
6093
- const path7 = m[2].trim();
6650
+ const path8 = m[2].trim();
6094
6651
  let rest = m[3].trim();
6095
- if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6652
+ if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6096
6653
  rest = rest.split(/[;|&<>]/)[0].trim();
6097
6654
  const args = [];
6098
6655
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6099
6656
  args.push(tm[1] ? tm[2] : tm[3]);
6100
6657
  }
6101
- calls.push({ path: path7, args, interpreter: interp });
6658
+ calls.push({ path: path8, args, interpreter: interp });
6102
6659
  }
6103
6660
  return calls;
6104
6661
  }
@@ -6881,15 +7438,15 @@ function extractCallsFromContent(content) {
6881
7438
  CHILD_CALL_RE2.lastIndex = 0;
6882
7439
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
6883
7440
  const interp = m[1];
6884
- const path7 = m[2].trim();
7441
+ const path8 = m[2].trim();
6885
7442
  let rest = m[3].trim();
6886
- if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
7443
+ if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6887
7444
  rest = rest.split(/[;|&<>]/)[0].trim();
6888
7445
  const args = [];
6889
7446
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6890
7447
  args.push(tm[1] ? tm[2] : tm[3]);
6891
7448
  }
6892
- calls.push({ path: path7, args, interpreter: interp });
7449
+ calls.push({ path: path8, args, interpreter: interp });
6893
7450
  }
6894
7451
  return calls;
6895
7452
  }
@@ -6958,8 +7515,8 @@ var init_backends = __esm({
6958
7515
 
6959
7516
  // src/engine/script-engine/tracker.ts
6960
7517
  import * as fs3 from "fs";
6961
- import * as path3 from "path";
6962
- import * as os from "os";
7518
+ import * as path4 from "path";
7519
+ import * as os2 from "os";
6963
7520
  function maxFileSizeFromEnv() {
6964
7521
  const raw = (process.env.AGENT_MOSS_SCRIPT_MAX_FILE_SIZE || "").trim();
6965
7522
  if (raw) {
@@ -6978,11 +7535,11 @@ function pickBackend(pathStr) {
6978
7535
  function resolvePath(p, baseDir) {
6979
7536
  let expanded = p;
6980
7537
  if (expanded.startsWith("~/") || expanded === "~") {
6981
- expanded = path3.join(os.homedir(), expanded.slice(1));
6982
- } else if (!path3.isAbsolute(expanded) && baseDir) {
6983
- expanded = path3.join(baseDir, expanded);
7538
+ expanded = path4.join(os2.homedir(), expanded.slice(1));
7539
+ } else if (!path4.isAbsolute(expanded) && baseDir) {
7540
+ expanded = path4.join(baseDir, expanded);
6984
7541
  }
6985
- return path3.resolve(expanded);
7542
+ return path4.resolve(expanded);
6986
7543
  }
6987
7544
  function readScript(pathStr, maxFileSize) {
6988
7545
  try {
@@ -7076,7 +7633,7 @@ var init_tracker = __esm({
7076
7633
  const baseDir = cwd || process.cwd();
7077
7634
  const resolved = resolvePath(entryPath);
7078
7635
  this.result.entryPath = resolved;
7079
- this.visitScript(resolved, 0, path3.dirname(resolved), entryArgs);
7636
+ this.visitScript(resolved, 0, path4.dirname(resolved), entryArgs);
7080
7637
  const nodes = this.result.nodes;
7081
7638
  this.result.hasCritical = nodes.some((n) => n.l1RiskLevel === "critical" || n.l2RiskLevel === "critical" || n.keywordRiskLevel === "critical") || this.result.hasCritical;
7082
7639
  this.result.hasHigh = nodes.some((n) => ["high", "critical"].includes(n.l1RiskLevel) || ["high", "critical"].includes(n.l2RiskLevel) || ["high", "critical"].includes(n.keywordRiskLevel));
@@ -7138,12 +7695,12 @@ var init_tracker = __esm({
7138
7695
  }
7139
7696
  }
7140
7697
  }
7141
- const parentDir = path3.dirname(pathStr);
7698
+ const parentDir = path4.dirname(pathStr);
7142
7699
  const childPaths = [];
7143
7700
  for (const call of ir.calls) {
7144
7701
  const child = resolvePath(call.path, parentDir);
7145
7702
  childPaths.push(child);
7146
- this.visitScript(child, depth + 1, path3.dirname(child), call.args);
7703
+ this.visitScript(child, depth + 1, path4.dirname(child), call.args);
7147
7704
  if (this.result.hasCritical) break;
7148
7705
  }
7149
7706
  node.childPaths = childPaths;
@@ -7155,8 +7712,8 @@ var init_tracker = __esm({
7155
7712
 
7156
7713
  // src/engine/script-content-analyzer.ts
7157
7714
  import { statSync as statSync4, existsSync as existsSync12 } from "fs";
7158
- import { resolve as resolve10, join as join11, isAbsolute as isAbsolute3 } from "path";
7159
- import { homedir as homedir4 } from "os";
7715
+ import { resolve as resolve10, join as join12, isAbsolute as isAbsolute4 } from "path";
7716
+ import { homedir as homedir5 } from "os";
7160
7717
  function emptyChain() {
7161
7718
  return {
7162
7719
  nodes: [],
@@ -7338,7 +7895,7 @@ function shlexSplit(s) {
7338
7895
  function resolvePath2(p) {
7339
7896
  let expanded = p;
7340
7897
  if (expanded.startsWith("~/") || expanded === "~") {
7341
- expanded = join11(homedir4(), expanded.slice(1));
7898
+ expanded = join12(homedir5(), expanded.slice(1));
7342
7899
  }
7343
7900
  return resolve10(expanded);
7344
7901
  }
@@ -7461,8 +8018,8 @@ function analyzeScriptContent2(input, ext) {
7461
8018
  resolvedPath = inline;
7462
8019
  isInline = true;
7463
8020
  }
7464
- if (resolvedPath && !isAbsolute3(resolvedPath) && !resolvedPath.startsWith("~/")) {
7465
- resolvedPath = join11(input.cwd || process.cwd(), resolvedPath);
8021
+ if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
8022
+ resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
7466
8023
  }
7467
8024
  const l1Adapter = (content) => {
7468
8025
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
@@ -7580,7 +8137,7 @@ var init_script_content_analyzer = __esm({
7580
8137
 
7581
8138
  // src/infra/trace-log.ts
7582
8139
  import fs4 from "fs";
7583
- import path4 from "path";
8140
+ import path5 from "path";
7584
8141
  function traceLevel() {
7585
8142
  if (_levelCache !== null) return _levelCache;
7586
8143
  const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
@@ -7607,7 +8164,7 @@ function tracePath() {
7607
8164
  const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
7608
8165
  if (explicit) return explicit;
7609
8166
  try {
7610
- return path4.join(getDataRoot(), "agent_moss_trace.log");
8167
+ return path5.join(getDataRoot(), "agent_moss_trace.log");
7611
8168
  } catch {
7612
8169
  return "agent_moss_trace.log";
7613
8170
  }
@@ -7646,7 +8203,7 @@ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
7646
8203
  `;
7647
8204
  const file = tracePath();
7648
8205
  try {
7649
- const dir = path4.dirname(file);
8206
+ const dir = path5.dirname(file);
7650
8207
  if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
7651
8208
  try {
7652
8209
  const st = fs4.statSync(file);
@@ -8242,7 +8799,7 @@ var init_token_stats = __esm({
8242
8799
 
8243
8800
  // src/engine/llm-analyzer.ts
8244
8801
  import { createHash as createHash3 } from "crypto";
8245
- import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants2 } from "fs";
8802
+ import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
8246
8803
  import OpenAI from "openai";
8247
8804
  function responseFieldLengths(message) {
8248
8805
  if (!message || typeof message !== "object") return {};
@@ -8381,11 +8938,11 @@ ${prompt}
8381
8938
  `;
8382
8939
  let flags = fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_APPEND;
8383
8940
  if (fsConstants2.O_NOFOLLOW) flags |= fsConstants2.O_NOFOLLOW;
8384
- const fd = openSync2(logPath, flags, 384);
8941
+ const fd = openSync3(logPath, flags, 384);
8385
8942
  try {
8386
8943
  writeSync2(fd, line);
8387
8944
  } finally {
8388
- closeSync2(fd);
8945
+ closeSync3(fd);
8389
8946
  }
8390
8947
  } catch (e) {
8391
8948
  console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
@@ -8681,8 +9238,8 @@ var init_llm_analyzer = __esm({
8681
9238
 
8682
9239
  // src/brain/rule-store.ts
8683
9240
  import { existsSync as existsSync14, readFileSync as readFileSync14, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
8684
- import { join as join12 } from "path";
8685
- import { homedir as homedir5 } from "os";
9241
+ import { join as join13 } from "path";
9242
+ import { homedir as homedir6 } from "os";
8686
9243
  function getRulesPath() {
8687
9244
  const envPath = process.env[ENV_RULES_PATH];
8688
9245
  if (envPath) return envPath;
@@ -8700,7 +9257,7 @@ var init_rule_store = __esm({
8700
9257
  "src/brain/rule-store.ts"() {
8701
9258
  "use strict";
8702
9259
  init_esm_shims();
8703
- DEFAULT_RULES_PATH = join12(homedir5(), ".agentmoss", "brain", "rules.json");
9260
+ DEFAULT_RULES_PATH = join13(homedir6(), ".agentmoss", "brain", "rules.json");
8704
9261
  ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
8705
9262
  STATUS_DRAFT = "draft";
8706
9263
  STATUS_APPROVED = "approved";
@@ -8712,8 +9269,8 @@ var init_rule_store = __esm({
8712
9269
  BrainRuleStore = class {
8713
9270
  path;
8714
9271
  data;
8715
- constructor(path7) {
8716
- this.path = path7 || getRulesPath();
9272
+ constructor(path8) {
9273
+ this.path = path8 || getRulesPath();
8717
9274
  this.data = this.load();
8718
9275
  }
8719
9276
  load() {
@@ -9166,10 +9723,10 @@ ${reason.slice(0, 500)}
9166
9723
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
9167
9724
  let mm;
9168
9725
  while ((mm = pathRe.exec(src)) !== null) {
9169
- const path7 = mm[1];
9170
- if (path7.split("/").length < 3) continue;
9171
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path7)) continue;
9172
- const gen = this.generalizePath(path7);
9726
+ const path8 = mm[1];
9727
+ if (path8.split("/").length < 3) continue;
9728
+ if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path8)) continue;
9729
+ const gen = this.generalizePath(path8);
9173
9730
  if (seen.has(gen)) continue;
9174
9731
  seen.add(gen);
9175
9732
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -9188,8 +9745,8 @@ ${reason.slice(0, 500)}
9188
9745
  }
9189
9746
  return false;
9190
9747
  }
9191
- generalizePath(path7) {
9192
- const p = path7.toLowerCase();
9748
+ generalizePath(path8) {
9749
+ const p = path8.toLowerCase();
9193
9750
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
9194
9751
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
9195
9752
  }
@@ -9316,8 +9873,8 @@ var init_reviewer = __esm({
9316
9873
 
9317
9874
  // src/brain/skill-manager.ts
9318
9875
  import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync, writeFileSync as writeFileSync4 } from "fs";
9319
- import { homedir as homedir6 } from "os";
9320
- import { join as join13 } from "path";
9876
+ import { homedir as homedir7 } from "os";
9877
+ import { join as join14 } from "path";
9321
9878
  import { randomUUID } from "crypto";
9322
9879
  function getMetaPath(override) {
9323
9880
  return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
@@ -9327,14 +9884,14 @@ var init_skill_manager = __esm({
9327
9884
  "src/brain/skill-manager.ts"() {
9328
9885
  "use strict";
9329
9886
  init_esm_shims();
9330
- DEFAULT_SKILL_META_PATH = join13(homedir6(), ".agentmoss", "brain", "skill_meta.json");
9887
+ DEFAULT_SKILL_META_PATH = join14(homedir7(), ".agentmoss", "brain", "skill_meta.json");
9331
9888
  ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
9332
9889
  BrainSkillManager = class {
9333
9890
  constructor(skillsDir, metaPath) {
9334
9891
  this.skillsDir = skillsDir;
9335
9892
  this.metaPath = getMetaPath(metaPath);
9336
9893
  try {
9337
- mkdirSync5(join13(this.metaPath, ".."), { recursive: true });
9894
+ mkdirSync5(join14(this.metaPath, ".."), { recursive: true });
9338
9895
  } catch {
9339
9896
  }
9340
9897
  this.load();
@@ -9369,7 +9926,7 @@ var init_skill_manager = __esm({
9369
9926
  let changed = false;
9370
9927
  for (const sk of this.skills) {
9371
9928
  if (sk.status !== "active") continue;
9372
- if (!existsSync15(join13(this.skillsDir, `${sk.name}.md`))) {
9929
+ if (!existsSync15(join14(this.skillsDir, `${sk.name}.md`))) {
9373
9930
  sk.status = "stale";
9374
9931
  changed = true;
9375
9932
  }
@@ -9381,7 +9938,7 @@ var init_skill_manager = __esm({
9381
9938
  const id = skill.id || randomUUID();
9382
9939
  const name = skill.name || `brain_${id.slice(0, 8)}`;
9383
9940
  if (!existsSync15(this.skillsDir)) return "";
9384
- const mdPath = join13(this.skillsDir, `${name}.md`);
9941
+ const mdPath = join14(this.skillsDir, `${name}.md`);
9385
9942
  if (existsSync15(mdPath)) return "";
9386
9943
  try {
9387
9944
  writeFileSync4(mdPath, skill.content, "utf-8");
@@ -9431,7 +9988,7 @@ var init_skill_manager = __esm({
9431
9988
  const out = [];
9432
9989
  for (const sk of this.skills) {
9433
9990
  if (sk.origin_node !== "local" || sk.status !== "active") continue;
9434
- const mdPath = join13(this.skillsDir, `${sk.name}.md`);
9991
+ const mdPath = join14(this.skillsDir, `${sk.name}.md`);
9435
9992
  if (!existsSync15(mdPath)) continue;
9436
9993
  out.push({
9437
9994
  name: sk.name,
@@ -9548,7 +10105,7 @@ __export(contributor_exports, {
9548
10105
  });
9549
10106
  import { mkdirSync as mkdirSync6, mkdtempSync, rmSync, writeFileSync as writeFileSync5 } from "fs";
9550
10107
  import { tmpdir as tmpdir2 } from "os";
9551
- import { join as join14 } from "path";
10108
+ import { join as join15 } from "path";
9552
10109
  import { spawnSync } from "child_process";
9553
10110
  import { dirname as dirname10 } from "path";
9554
10111
  import { fileURLToPath as fileURLToPath9 } from "url";
@@ -9569,7 +10126,7 @@ function collectSkills(skillMgr) {
9569
10126
  }
9570
10127
  function writeExportFiles(outDir, rules, skills) {
9571
10128
  const written = [];
9572
- const rulesDir2 = join14(outDir, "rules");
10129
+ const rulesDir2 = join15(outDir, "rules");
9573
10130
  mkdirSync6(rulesDir2, { recursive: true });
9574
10131
  const byLayer = /* @__PURE__ */ new Map();
9575
10132
  for (const r of rules) {
@@ -9577,26 +10134,26 @@ function writeExportFiles(outDir, rules, skills) {
9577
10134
  byLayer.get(r.layer).push(r);
9578
10135
  }
9579
10136
  for (const layer of [...byLayer.keys()].sort((a, b) => a - b)) {
9580
- const path7 = join14(rulesDir2, `l${layer}_brain_rules.json`);
9581
- writeFileSync5(path7, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
9582
- written.push(path7);
10137
+ const path8 = join15(rulesDir2, `l${layer}_brain_rules.json`);
10138
+ writeFileSync5(path8, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
10139
+ written.push(path8);
9583
10140
  }
9584
10141
  if (rules.length === 0) {
9585
- const path7 = join14(rulesDir2, "empty.txt");
9586
- writeFileSync5(path7, "(no brain rules to contribute)", "utf-8");
9587
- written.push(path7);
10142
+ const path8 = join15(rulesDir2, "empty.txt");
10143
+ writeFileSync5(path8, "(no brain rules to contribute)", "utf-8");
10144
+ written.push(path8);
9588
10145
  }
9589
- const skillsDir = join14(outDir, "skills");
10146
+ const skillsDir = join15(outDir, "skills");
9590
10147
  mkdirSync6(skillsDir, { recursive: true });
9591
10148
  for (const sk of skills) {
9592
- const path7 = join14(skillsDir, `${sk.name}.md`);
9593
- writeFileSync5(path7, sk.content || "", "utf-8");
9594
- written.push(path7);
10149
+ const path8 = join15(skillsDir, `${sk.name}.md`);
10150
+ writeFileSync5(path8, sk.content || "", "utf-8");
10151
+ written.push(path8);
9595
10152
  }
9596
10153
  if (skills.length === 0) {
9597
- const path7 = join14(skillsDir, "empty.txt");
9598
- writeFileSync5(path7, "(no brain skills to contribute)", "utf-8");
9599
- written.push(path7);
10154
+ const path8 = join15(skillsDir, "empty.txt");
10155
+ writeFileSync5(path8, "(no brain skills to contribute)", "utf-8");
10156
+ written.push(path8);
9600
10157
  }
9601
10158
  return written;
9602
10159
  }
@@ -9724,7 +10281,7 @@ async function contribute(opts = {}) {
9724
10281
  console.log(`[Brain] push \u76EE\u6807: ${pushTarget}`);
9725
10282
  console.log(`[Brain] MR \u6307\u5411: ${DEFAULT_TARGET_REPO}`);
9726
10283
  const store = new BrainRuleStore();
9727
- const skillsDir = resolveAssetDir(__dirname8, "skills") ?? join14(__dirname8, "..", "..", "agent_moss", "skills");
10284
+ const skillsDir = resolveAssetDir(__dirname8, "skills") ?? join15(__dirname8, "..", "..", "agent_moss", "skills");
9728
10285
  const skillMgr = new BrainSkillManager(skillsDir);
9729
10286
  let rules;
9730
10287
  let skills;
@@ -9739,9 +10296,9 @@ async function contribute(opts = {}) {
9739
10296
  return 0;
9740
10297
  }
9741
10298
  console.log(`[Brain] \u5BFC\u51FA: ${rules.length} \u6761\u89C4\u5219, ${skills.length} \u4E2A Skill`);
9742
- const workdir = mkdtempSync(join14(tmpdir2(), "agentmoss-contrib-"));
10299
+ const workdir = mkdtempSync(join15(tmpdir2(), "agentmoss-contrib-"));
9743
10300
  try {
9744
- writeExportFiles(join14(workdir, "agent_moss", "brain_contrib"), rules, skills);
10301
+ writeExportFiles(join15(workdir, "agent_moss", "brain_contrib"), rules, skills);
9745
10302
  console.log(`[Brain] \u63A2\u6D4B ${pushTarget} \u8BBF\u95EE\u6743\u9650 ...`);
9746
10303
  if (!probeAccess(pushTarget)) {
9747
10304
  const username = getCurrentUsername();
@@ -10300,12 +10857,12 @@ var init_builder = __esm({
10300
10857
  });
10301
10858
 
10302
10859
  // src/engine/formal-engine/properties.ts
10303
- function graphFromPath(nodes, path7, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10860
+ function graphFromPath(nodes, path8, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10304
10861
  const byKey = /* @__PURE__ */ new Map();
10305
10862
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
10306
10863
  const gNodes = [];
10307
10864
  const gEdges = [];
10308
- for (const item of path7) {
10865
+ for (const item of path8) {
10309
10866
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
10310
10867
  gNodes.push({
10311
10868
  session_id: item.sessionId,
@@ -10371,22 +10928,22 @@ function checkCrossSessionChain(graph) {
10371
10928
  if (witness !== void 0) {
10372
10929
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
10373
10930
  let matched = 0;
10374
- const path7 = [];
10931
+ const path8 = [];
10375
10932
  for (let k = 0; k < witness; k++) {
10376
10933
  const n = nodes[k];
10377
10934
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
10378
10935
  matched += 1;
10379
- path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10936
+ path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10380
10937
  }
10381
10938
  }
10382
10939
  if (matched < stages.length - 1) continue;
10383
- path7.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
10940
+ path8.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
10384
10941
  violations.push({
10385
10942
  propertyId: "cross-" + chain.id,
10386
10943
  reason: chain.reason,
10387
10944
  riskLevel: chain.riskLevel,
10388
- path: path7,
10389
- graph: graphFromPath(nodes, path7, "next", {
10945
+ path: path8,
10946
+ graph: graphFromPath(nodes, path8, "next", {
10390
10947
  property_id: "cross-" + chain.id,
10391
10948
  property_short: "P1",
10392
10949
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -10396,11 +10953,11 @@ function checkCrossSessionChain(graph) {
10396
10953
  } else {
10397
10954
  let matched = 0;
10398
10955
  let stageIdx = 0;
10399
- const path7 = [];
10956
+ const path8 = [];
10400
10957
  for (const n of nodes) {
10401
10958
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
10402
10959
  matched += 1;
10403
- path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10960
+ path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10404
10961
  stageIdx += 1;
10405
10962
  if (matched >= stages.length) break;
10406
10963
  }
@@ -10410,8 +10967,8 @@ function checkCrossSessionChain(graph) {
10410
10967
  propertyId: "cross-" + chain.id,
10411
10968
  reason: chain.reason,
10412
10969
  riskLevel: chain.riskLevel,
10413
- path: path7,
10414
- graph: graphFromPath(nodes, path7, "next", {
10970
+ path: path8,
10971
+ graph: graphFromPath(nodes, path8, "next", {
10415
10972
  property_id: "cross-" + chain.id,
10416
10973
  property_short: "P1",
10417
10974
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -10632,7 +11189,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10632
11189
  if (candidates.length > 0) {
10633
11190
  const pre = nodes[candidates[candidates.length - 1]];
10634
11191
  const post = nodes[firstEv];
10635
- const path7 = [
11192
+ const path8 = [
10636
11193
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10637
11194
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10638
11195
  ];
@@ -10640,8 +11197,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10640
11197
  propertyId: "no-exfil-after-privesc",
10641
11198
  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",
10642
11199
  riskLevel: "critical",
10643
- path: path7,
10644
- graph: graphFromPath(nodes, path7, "next", {
11200
+ path: path8,
11201
+ graph: graphFromPath(nodes, path8, "next", {
10645
11202
  property_id: "no-exfil-after-privesc",
10646
11203
  property_short: "P4",
10647
11204
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10658,7 +11215,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10658
11215
  for (let j = i + 1; j < nodes.length; j++) {
10659
11216
  if (!isExfilNode(nodes[j])) continue;
10660
11217
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
10661
- const path7 = [
11218
+ const path8 = [
10662
11219
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10663
11220
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10664
11221
  ];
@@ -10666,8 +11223,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10666
11223
  propertyId: "no-exfil-after-privesc",
10667
11224
  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",
10668
11225
  riskLevel: "critical",
10669
- path: path7,
10670
- graph: graphFromPath(nodes, path7, "next", {
11226
+ path: path8,
11227
+ graph: graphFromPath(nodes, path8, "next", {
10671
11228
  property_id: "no-exfil-after-privesc",
10672
11229
  property_short: "P4",
10673
11230
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10699,7 +11256,7 @@ function checkNeverExfilAfterCred(graph) {
10699
11256
  }
10700
11257
  if (pre) {
10701
11258
  const post = nodes[firstEv];
10702
- const path7 = [
11259
+ const path8 = [
10703
11260
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10704
11261
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10705
11262
  ];
@@ -10707,8 +11264,8 @@ function checkNeverExfilAfterCred(graph) {
10707
11264
  propertyId: "no-exfil-after-credential",
10708
11265
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10709
11266
  riskLevel: "critical",
10710
- path: path7,
10711
- graph: graphFromPath(nodes, path7, "data", {
11267
+ path: path8,
11268
+ graph: graphFromPath(nodes, path8, "data", {
10712
11269
  property_id: "no-exfil-after-credential",
10713
11270
  property_short: "P5",
10714
11271
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10724,7 +11281,7 @@ function checkNeverExfilAfterCred(graph) {
10724
11281
  if (!isCredNode(nodes[i])) continue;
10725
11282
  for (let j = i + 1; j < nodes.length; j++) {
10726
11283
  if (isExfilNode(nodes[j])) {
10727
- const path7 = [
11284
+ const path8 = [
10728
11285
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10729
11286
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10730
11287
  ];
@@ -10732,8 +11289,8 @@ function checkNeverExfilAfterCred(graph) {
10732
11289
  propertyId: "no-exfil-after-credential",
10733
11290
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10734
11291
  riskLevel: "critical",
10735
- path: path7,
10736
- graph: graphFromPath(nodes, path7, "data", {
11292
+ path: path8,
11293
+ graph: graphFromPath(nodes, path8, "data", {
10737
11294
  property_id: "no-exfil-after-credential",
10738
11295
  property_short: "P5",
10739
11296
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10892,13 +11449,13 @@ function checkSensitiveDataAggregation(graph) {
10892
11449
  if (!isExfilNode(n)) continue;
10893
11450
  const srcs = sourcesFor(i);
10894
11451
  if (srcs.size >= 2) {
10895
- const path7 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11452
+ const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10896
11453
  violations.push({
10897
11454
  propertyId: "sensitive-data-aggregation",
10898
11455
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
10899
11456
  riskLevel: "critical",
10900
- path: path7,
10901
- graph: graphFromPath(nodes, path7, "next", {
11457
+ path: path8,
11458
+ graph: graphFromPath(nodes, path8, "next", {
10902
11459
  property_id: "sensitive-data-aggregation",
10903
11460
  property_short: "P8",
10904
11461
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -11357,11 +11914,11 @@ var init_stateful = __esm({
11357
11914
  }
11358
11915
  }
11359
11916
  chainPath(stages) {
11360
- const path7 = [];
11917
+ const path8 = [];
11361
11918
  let want = stages[0];
11362
11919
  for (const n of this.nodes_) {
11363
11920
  if (n.stage === want) {
11364
- path7.push({
11921
+ path8.push({
11365
11922
  sessionId: n.sessionId,
11366
11923
  seq: n.seq,
11367
11924
  stage: n.stage,
@@ -11377,12 +11934,12 @@ var init_stateful = __esm({
11377
11934
  }
11378
11935
  }
11379
11936
  }
11380
- return path7;
11937
+ return path8;
11381
11938
  }
11382
11939
  /** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
11383
11940
  buildChainGraph(stages, chainId) {
11384
- const path7 = this.chainPath(stages);
11385
- const gNodes = path7.map((p, i) => {
11941
+ const path8 = this.chainPath(stages);
11942
+ const gNodes = path8.map((p, i) => {
11386
11943
  const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
11387
11944
  return {
11388
11945
  session_id: p.sessionId,
@@ -11634,13 +12191,13 @@ var init_stateful = __esm({
11634
12191
 
11635
12192
  // src/engine/formal-engine/chain_state.ts
11636
12193
  import * as fs5 from "fs";
11637
- import * as os2 from "os";
11638
- import * as path5 from "path";
12194
+ import * as os3 from "os";
12195
+ import * as path6 from "path";
11639
12196
  import { createHash as createHash4 } from "crypto";
11640
12197
  function defaultStateDbPath() {
11641
- const dir = process.env.AGENT_MOSS_STATE_DIR || path5.join(os2.homedir(), ".agentmoss");
12198
+ const dir = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
11642
12199
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
11643
- return path5.join(dir, `stateful_chains_${tag}.json`);
12200
+ return path6.join(dir, `stateful_chains_${tag}.json`);
11644
12201
  }
11645
12202
  function registerExitFlush(store) {
11646
12203
  if (_exitHookRegistered) return;
@@ -11726,7 +12283,7 @@ var init_chain_state = __esm({
11726
12283
  this._timer = null;
11727
12284
  try {
11728
12285
  this._syncDirtyToData();
11729
- ensurePrivateDir(path5.dirname(this.filePath));
12286
+ ensurePrivateDir(path6.dirname(this.filePath));
11730
12287
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11731
12288
  } catch {
11732
12289
  }
@@ -11749,7 +12306,7 @@ var init_chain_state = __esm({
11749
12306
  }
11750
12307
  try {
11751
12308
  this._syncDirtyToData();
11752
- ensurePrivateDir(path5.dirname(this.filePath));
12309
+ ensurePrivateDir(path6.dirname(this.filePath));
11753
12310
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11754
12311
  } catch {
11755
12312
  }
@@ -11817,7 +12374,7 @@ var init_chain_state = __esm({
11817
12374
  _flushNow() {
11818
12375
  this._syncDirtyToData();
11819
12376
  try {
11820
- const _dirOk = ensurePrivateDir(path5.dirname(this.filePath));
12377
+ const _dirOk = ensurePrivateDir(path6.dirname(this.filePath));
11821
12378
  const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11822
12379
  if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
11823
12380
  } catch (e) {
@@ -12114,7 +12671,7 @@ async function runAnalysis(input) {
12114
12671
  skipLLM = true;
12115
12672
  }
12116
12673
  }
12117
- const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
12674
+ const logicResult = isLogicRulesEnabled() ? runLogicCheck(input, { agentExt }) : null;
12118
12675
  if (logicResult) {
12119
12676
  traceSummary("l2.result", {
12120
12677
  hit: !logicResult.allowed,
@@ -12379,7 +12936,7 @@ var init_coordinator = __esm({
12379
12936
  import { createHash as createHash5 } from "crypto";
12380
12937
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
12381
12938
  import { tmpdir as tmpdir3 } from "os";
12382
- import { join as join16 } from "path";
12939
+ import { join as join17 } from "path";
12383
12940
  function cacheDir() {
12384
12941
  return cacheDirOverride ?? CACHE_DIR;
12385
12942
  }
@@ -12387,7 +12944,7 @@ function safeCacheDir() {
12387
12944
  const dir = cacheDir();
12388
12945
  if (ensurePrivateDir(dir)) return dir;
12389
12946
  try {
12390
- const fallback = join16(getDataRoot(), "policy_cache");
12947
+ const fallback = join17(getDataRoot(), "policy_cache");
12391
12948
  if (ensurePrivateDir(fallback)) {
12392
12949
  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}`);
12393
12950
  return fallback;
@@ -12408,7 +12965,7 @@ var init_policy_cache = __esm({
12408
12965
  init_security_policy();
12409
12966
  init_paths();
12410
12967
  init_config();
12411
- CACHE_DIR = join16(tmpdir3(), "agent_moss_policy_cache");
12968
+ CACHE_DIR = join17(tmpdir3(), "agent_moss_policy_cache");
12412
12969
  cacheDirOverride = null;
12413
12970
  PolicyCache = class {
12414
12971
  // Map 的插入序即 LRU 序(get 时重新 set 到末尾)
@@ -12423,7 +12980,7 @@ var init_policy_cache = __esm({
12423
12980
  cacheFilePath(sessionId, promptSession) {
12424
12981
  const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
12425
12982
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12426
- return join16(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
12983
+ return join17(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
12427
12984
  }
12428
12985
  /** 取缓存:内存 → 文件;未命中返回 null。 */
12429
12986
  get(sessionId, promptSession) {
@@ -12454,7 +13011,7 @@ var init_policy_cache = __esm({
12454
13011
  try {
12455
13012
  const dir = safeCacheDir();
12456
13013
  const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12457
- if (!ensurePrivateDir(join16(dir, sub))) return;
13014
+ if (!ensurePrivateDir(join17(dir, sub))) return;
12458
13015
  writePrivateText(file, policy);
12459
13016
  } catch {
12460
13017
  }
@@ -12480,12 +13037,12 @@ var init_policy_cache = __esm({
12480
13037
  if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
12481
13038
  }
12482
13039
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12483
- const dir = join16(cacheDir(), safeSessionId);
13040
+ const dir = join17(cacheDir(), safeSessionId);
12484
13041
  try {
12485
13042
  if (existsSync17(dir)) {
12486
13043
  for (const f of readdirSync5(dir)) {
12487
13044
  try {
12488
- unlinkSync4(join16(dir, f));
13045
+ unlinkSync4(join17(dir, f));
12489
13046
  } catch {
12490
13047
  }
12491
13048
  }
@@ -12499,9 +13056,9 @@ var init_policy_cache = __esm({
12499
13056
  try {
12500
13057
  if (existsSync17(cacheDir())) {
12501
13058
  for (const sessionDir of readdirSync5(cacheDir())) {
12502
- const dir = join16(cacheDir(), sessionDir);
13059
+ const dir = join17(cacheDir(), sessionDir);
12503
13060
  try {
12504
- for (const f of readdirSync5(dir)) unlinkSync4(join16(dir, f));
13061
+ for (const f of readdirSync5(dir)) unlinkSync4(join17(dir, f));
12505
13062
  rmdirSync(dir);
12506
13063
  } catch {
12507
13064
  }
@@ -12599,7 +13156,7 @@ __export(analyzer_exports, {
12599
13156
  });
12600
13157
  import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
12601
13158
  import { tmpdir as tmpdir4 } from "os";
12602
- import { join as join17, resolve as resolve11 } from "path";
13159
+ import { join as join18, resolve as resolve11 } from "path";
12603
13160
  import { parse as parseToml } from "smol-toml";
12604
13161
  function _setPolicyOutputDirForTest(dir) {
12605
13162
  policyOutputDirOverride = dir;
@@ -12616,7 +13173,7 @@ function savePolicyToFile(sessionId, policyToml) {
12616
13173
  return null;
12617
13174
  }
12618
13175
  const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12619
- const filepath = join17(outDir, `${safeName}.toml`);
13176
+ const filepath = join18(outDir, `${safeName}.toml`);
12620
13177
  writePrivateText(filepath, policyToml);
12621
13178
  return filepath;
12622
13179
  } catch (err) {
@@ -12832,7 +13389,7 @@ var init_analyzer = __esm({
12832
13389
  init_asset_dir();
12833
13390
  init_token_stats();
12834
13391
  init_logging();
12835
- POLICY_OUTPUT_DIR = join17(tmpdir4(), "agent_moss");
13392
+ POLICY_OUTPUT_DIR = join18(tmpdir4(), "agent_moss");
12836
13393
  policyOutputDirOverride = null;
12837
13394
  DEFAULT_READONLY_POLICY = `landlock_optional = false
12838
13395
  mount_isolation_fallback = false
@@ -13070,8 +13627,8 @@ var init_pattern_miner = __esm({
13070
13627
 
13071
13628
  // src/agent-gate-reader.ts
13072
13629
  import * as fs7 from "fs";
13073
- import * as os3 from "os";
13074
- import * as path6 from "path";
13630
+ import * as os4 from "os";
13631
+ import * as path7 from "path";
13075
13632
  function normalizeAction(row) {
13076
13633
  return {
13077
13634
  actionType: String(row.action_type || row.tool_name || row.name || ""),
@@ -13084,7 +13641,7 @@ function readJsonDir(dirPath, limit = 1e5) {
13084
13641
  const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
13085
13642
  for (const f of files.slice(-200)) {
13086
13643
  const sid = f.replace(/\.json$/, "");
13087
- const raw = fs7.readFileSync(path6.join(dirPath, f), "utf-8");
13644
+ const raw = fs7.readFileSync(path7.join(dirPath, f), "utf-8");
13088
13645
  const arr = JSON.parse(raw);
13089
13646
  if (!Array.isArray(arr)) continue;
13090
13647
  for (const item of arr) {
@@ -13152,7 +13709,7 @@ function loadAgentGateSessions(dbPath = "") {
13152
13709
  }
13153
13710
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
13154
13711
  if (sql.length > 0) return sql;
13155
- const jsonDefault = path6.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
13712
+ const jsonDefault = path7.join(os4.homedir(), ".local", "share", "agent_gate", "tool_calls");
13156
13713
  return readJsonDir(jsonDefault);
13157
13714
  }
13158
13715
  var DEFAULT_AGENTGATE_SQLITE;
@@ -13161,8 +13718,8 @@ var init_agent_gate_reader = __esm({
13161
13718
  "use strict";
13162
13719
  init_esm_shims();
13163
13720
  init_esm_require();
13164
- DEFAULT_AGENTGATE_SQLITE = path6.join(
13165
- os3.homedir(),
13721
+ DEFAULT_AGENTGATE_SQLITE = path7.join(
13722
+ os4.homedir(),
13166
13723
  ".local",
13167
13724
  "share",
13168
13725
  "agent_gate",
@@ -13302,7 +13859,7 @@ var init_runtime_stats = __esm({
13302
13859
 
13303
13860
  // src/routes.ts
13304
13861
  import { randomBytes as randomBytes2 } from "crypto";
13305
- import { join as join19, dirname as dirname12 } from "path";
13862
+ import { join as join20, dirname as dirname12 } from "path";
13306
13863
  import { fileURLToPath as fileURLToPath10 } from "url";
13307
13864
  async function healthRoute(c) {
13308
13865
  const metrics = {};
@@ -13701,7 +14258,7 @@ function getBrainRuleStore() {
13701
14258
  return new BrainRuleStore();
13702
14259
  }
13703
14260
  function getBrainSkillManager() {
13704
- const dir = resolveAssetDir(__dirname9, "skills") ?? join19(__dirname9, "..", "..", "agent_moss", "skills");
14261
+ const dir = resolveAssetDir(__dirname9, "skills") ?? join20(__dirname9, "..", "..", "agent_moss", "skills");
13705
14262
  return new BrainSkillManager(dir);
13706
14263
  }
13707
14264
  async function brainRulesRoute(c) {
@@ -13821,7 +14378,7 @@ var init_routes = __esm({
13821
14378
  import { Hono } from "hono";
13822
14379
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
13823
14380
  import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
13824
- import { join as join20, dirname as dirname13 } from "path";
14381
+ import { join as join21, dirname as dirname13 } from "path";
13825
14382
  import { fileURLToPath as fileURLToPath11 } from "url";
13826
14383
  function getConsoleToken() {
13827
14384
  return process.env[CONSOLE_TOKEN_ENV] || "";
@@ -13863,7 +14420,7 @@ function createConsoleRouter() {
13863
14420
  console2.use("/api/*", authMiddleware());
13864
14421
  console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
13865
14422
  const serveIndex = (c) => {
13866
- const indexFile = join20(STATIC_DIR, "index.html");
14423
+ const indexFile = join21(STATIC_DIR, "index.html");
13867
14424
  if (existsSync20(indexFile)) {
13868
14425
  return c.html(readFileSync20(indexFile, "utf-8"));
13869
14426
  }
@@ -14060,11 +14617,11 @@ function createConsoleRouter() {
14060
14617
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
14061
14618
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
14062
14619
  }
14063
- const userPath = join20(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14620
+ const userPath = join21(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14064
14621
  const builtinDir = resolveAssetDir(__dirname10, "skills");
14065
14622
  const candidates = [
14066
14623
  ...isRuntimeConfigDisabled() ? [] : [userPath],
14067
- builtinDir ? join20(builtinDir, `${skillId}.md`) : ""
14624
+ builtinDir ? join21(builtinDir, `${skillId}.md`) : ""
14068
14625
  ].filter(Boolean);
14069
14626
  for (const p of candidates) {
14070
14627
  if (existsSync20(p)) {
@@ -14202,7 +14759,7 @@ var init_router = __esm({
14202
14759
  init_asset_dir();
14203
14760
  init_rules_mode();
14204
14761
  __dirname10 = dirname13(fileURLToPath11(import.meta.url));
14205
- STATIC_DIR = join20(__dirname10, "static");
14762
+ STATIC_DIR = join21(__dirname10, "static");
14206
14763
  CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
14207
14764
  }
14208
14765
  });
@@ -14322,7 +14879,7 @@ function createApp() {
14322
14879
  startLoopMonitor();
14323
14880
  const limiter = new RateLimiter(rateLimitQps());
14324
14881
  app.use("*", async (c, next) => {
14325
- const path7 = new URL(c.req.url).pathname;
14882
+ const path8 = new URL(c.req.url).pathname;
14326
14883
  const method = c.req.method.toUpperCase();
14327
14884
  if (method === "OPTIONS") return next();
14328
14885
  const maxBody = maxBodyBytes();
@@ -14336,16 +14893,16 @@ function createApp() {
14336
14893
  if (originCheckEnabled()) {
14337
14894
  const origin = c.req.header("origin") || "";
14338
14895
  if (origin && !originAllowed(origin, c.req.header("host") || "")) {
14339
- console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path7}`);
14896
+ console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path8}`);
14340
14897
  return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
14341
14898
  }
14342
14899
  }
14343
- const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path7);
14344
- const isPublicPage = !path7.startsWith("/console/api") && (path7 === "/console" || path7.startsWith("/console/"));
14900
+ const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path8);
14901
+ const isPublicPage = !path8.startsWith("/console/api") && (path8 === "/console" || path8.startsWith("/console/"));
14345
14902
  if (!okAuth && !isPublicPage) {
14346
14903
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
14347
14904
  }
14348
- if (limiter.enabled && path7.startsWith("/api/")) {
14905
+ if (limiter.enabled && path8.startsWith("/api/")) {
14349
14906
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
14350
14907
  if (!limiter.allow(key)) {
14351
14908
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
@@ -14379,7 +14936,7 @@ function createApp() {
14379
14936
  return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
14380
14937
  }
14381
14938
  }
14382
- const pool = poolOf(path7);
14939
+ const pool = poolOf(path8);
14383
14940
  if (!take(`pool:${pool}`, poolLimit(pool))) {
14384
14941
  const qkey = principal ? "p:" + principalHash(principal) : "c:local";
14385
14942
  const [qn, abusive] = noteQueueReject(qkey);
@@ -14643,17 +15200,17 @@ __export(rules_tools_exports, {
14643
15200
  templateSourceDir: () => templateSourceDir
14644
15201
  });
14645
15202
  import { existsSync as existsSync22, mkdirSync as mkdirSync9, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync7 } from "fs";
14646
- import { dirname as dirname14, join as join21 } from "path";
15203
+ import { dirname as dirname14, join as join22 } from "path";
14647
15204
  import { fileURLToPath as fileURLToPath12 } from "url";
14648
15205
  function initRulesDir(targetDir, opts = {}) {
14649
15206
  mkdirSync9(targetDir, { recursive: true });
14650
15207
  const written = [];
14651
- const extraPath = join21(targetDir, EXTRA_FILENAME);
15208
+ const extraPath = join22(targetDir, EXTRA_FILENAME);
14652
15209
  if (opts.force || !existsSync22(extraPath)) {
14653
15210
  writeFileSync7(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
14654
15211
  written.push(extraPath);
14655
15212
  }
14656
- const samplePath = join21(targetDir, OVERRIDE_FILENAME);
15213
+ const samplePath = join22(targetDir, OVERRIDE_FILENAME);
14657
15214
  if (opts.force || !existsSync22(samplePath)) {
14658
15215
  let payload = OVERRIDE_TEMPLATE;
14659
15216
  if (opts.withBuiltin) {
@@ -14672,8 +15229,8 @@ function initRulesDir(targetDir, opts = {}) {
14672
15229
  writeFileSync7(samplePath, JSON.stringify(payload, null, 2), "utf-8");
14673
15230
  written.push(samplePath);
14674
15231
  }
14675
- const readmeSrc = join21(templateSourceDir(), "README.md");
14676
- const readmeDst = join21(targetDir, "README.md");
15232
+ const readmeSrc = join22(templateSourceDir(), "README.md");
15233
+ const readmeDst = join22(targetDir, "README.md");
14677
15234
  if (existsSync22(readmeSrc) && (opts.force || !existsSync22(readmeDst))) {
14678
15235
  writeFileSync7(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
14679
15236
  written.push(readmeDst);
@@ -14681,7 +15238,7 @@ function initRulesDir(targetDir, opts = {}) {
14681
15238
  return written;
14682
15239
  }
14683
15240
  function templateSourceDir() {
14684
- const cands = [join21(__dirname11, "data", "rules_template"), join21(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
15241
+ const cands = [join22(__dirname11, "data", "rules_template"), join22(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
14685
15242
  for (const c of cands) if (existsSync22(c)) return c;
14686
15243
  return cands[0];
14687
15244
  }
@@ -14690,7 +15247,7 @@ function templateFiles(dirs) {
14690
15247
  for (const d of dirs) {
14691
15248
  try {
14692
15249
  for (const name of readdirSync7(d)) {
14693
- if (name.endsWith(".json.\u793A\u4F8B")) out.push(join21(d, name));
15250
+ if (name.endsWith(".json.\u793A\u4F8B")) out.push(join22(d, name));
14694
15251
  }
14695
15252
  } catch {
14696
15253
  }
@@ -14895,7 +15452,7 @@ async function main() {
14895
15452
  process.exit(1);
14896
15453
  }
14897
15454
  const fs8 = await import("fs");
14898
- const path7 = await import("path");
15455
+ const path8 = await import("path");
14899
15456
  const useJson = args.includes("--json");
14900
15457
  const osType = process.platform === "win32" ? "windows" : "linux";
14901
15458
  const isFile = fs8.existsSync(target) && fs8.statSync(target).isFile();
@@ -14914,7 +15471,7 @@ async function main() {
14914
15471
  }
14915
15472
  process.exit(await analyzeRawCommand(target, useJson));
14916
15473
  }
14917
- const filePath = path7.resolve(target);
15474
+ const filePath = path8.resolve(target);
14918
15475
  const data = JSON.parse(fs8.readFileSync(filePath, "utf-8"));
14919
15476
  const { analyze: analyze2 } = await Promise.resolve().then(() => (init_analyzer(), analyzer_exports));
14920
15477
  const sessionId = String(data.session_id || "unknown");
@@ -14926,11 +15483,11 @@ async function main() {
14926
15483
  fs8.mkdirSync(outDir, { recursive: true });
14927
15484
  const safeSession = sessionId.replace(/\//g, "_");
14928
15485
  if (result.decision === "Allow") {
14929
- const policyPath = path7.join(outDir, `${safeSession}_policy.toml`);
15486
+ const policyPath = path8.join(outDir, `${safeSession}_policy.toml`);
14930
15487
  fs8.writeFileSync(policyPath, result.policy || "", "utf-8");
14931
15488
  console.log(`Policy written to ${policyPath}`);
14932
15489
  } else {
14933
- const denyPath = path7.join(outDir, `${safeSession}_deny_reason.txt`);
15490
+ const denyPath = path8.join(outDir, `${safeSession}_deny_reason.txt`);
14934
15491
  fs8.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
14935
15492
  console.log(`Deny reason written to ${denyPath}`);
14936
15493
  }
@@ -15021,7 +15578,7 @@ async function main() {
15021
15578
  const enable = args.includes("--enable");
15022
15579
  const { execSync } = await import("child_process");
15023
15580
  const fs8 = await import("fs");
15024
- const path7 = await import("path");
15581
+ const path8 = await import("path");
15025
15582
  const { fileURLToPath: fileURLToPath14 } = await import("url");
15026
15583
  if (process.getuid?.() !== 0) {
15027
15584
  try {
@@ -15038,17 +15595,17 @@ async function main() {
15038
15595
  process.exit(0);
15039
15596
  }
15040
15597
  const __filename7 = fileURLToPath14(import.meta.url);
15041
- const __dirname12 = path7.dirname(__filename7);
15042
- let srcPath = path7.join(__dirname12, "data", "agent_moss.service");
15598
+ const __dirname12 = path8.dirname(__filename7);
15599
+ let srcPath = path8.join(__dirname12, "data", "agent_moss.service");
15043
15600
  if (!fs8.existsSync(srcPath)) {
15044
- srcPath = path7.join(__dirname12, "..", "src", "data", "agent_moss.service");
15601
+ srcPath = path8.join(__dirname12, "..", "src", "data", "agent_moss.service");
15045
15602
  }
15046
15603
  if (!fs8.existsSync(srcPath)) {
15047
15604
  console.error("\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230 agent_moss.service \u6A21\u677F\u6587\u4EF6");
15048
15605
  process.exit(1);
15049
15606
  }
15050
15607
  const which = execSync("which agent-moss 2>/dev/null || true", { encoding: "utf-8" }).trim();
15051
- const binPath = which || `${process.execPath} ${path7.join(__dirname12, "cli.js")}`;
15608
+ const binPath = which || `${process.execPath} ${path8.join(__dirname12, "cli.js")}`;
15052
15609
  let content = fs8.readFileSync(srcPath, "utf-8");
15053
15610
  content = content.replace("__AGENT_MOSS_BIN__", binPath);
15054
15611
  const dst = "/etc/systemd/system/agent-moss.service";