@kenhkl/agent-moss 0.17.24 → 0.17.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -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,7 +2262,8 @@ 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";
@@ -2102,7 +2304,11 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2102
2304
  const SOURCE_ARG_CMDS = new Set(_LOGIC.source_arg_commands ?? []);
2103
2305
  const REDIRECT_TARGET_RE = new RegExp(`>{1,2}\\s*(?!&)(?:'(/[^']+)'|"(/[^\\"]+)"|(/[^\\s;|&><'\\"]+))`);
2104
2306
  const targetPaths = [];
2105
- for (const seg of splitCommandSegments(actionDetail)) {
2307
+ const singleFileTool = singleFileTools.has(actionType);
2308
+ if (singleFileTool && MISSING_WRITE_PATH_RE.test(actionDetailRaw)) {
2309
+ return null;
2310
+ }
2311
+ for (const seg of singleFileTool ? [] : splitCommandSegments(actionDetailRaw)) {
2106
2312
  const trimmed = seg.trim();
2107
2313
  if (!trimmed) continue;
2108
2314
  const firstWord = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
@@ -2134,16 +2340,31 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2134
2340
  targetPaths.push(...segPathsFiltered);
2135
2341
  }
2136
2342
  }
2343
+ if (singleFileTool) {
2344
+ targetPaths.length = 0;
2345
+ targetPaths.push(...declaredWritePaths(actionDetailRaw, osType));
2346
+ }
2137
2347
  const uniqueTargetPaths = [...new Set(targetPaths)].filter((p) => !PSEUDO_FS_PREFIXES.some((pfx) => p.startsWith(pfx)));
2138
2348
  if (uniqueTargetPaths.length === 0) return null;
2139
- const historyReadPaths = /* @__PURE__ */ new Set();
2349
+ const historyFullReadPaths = /* @__PURE__ */ new Set();
2350
+ const historyPartialRead = /* @__PURE__ */ new Map();
2140
2351
  for (const action of actionHistory) {
2141
- const histDetail = action.actionDetail.toLowerCase();
2352
+ const histDetailRaw = action.actionDetail;
2142
2353
  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);
2354
+ const traits = getPlatformTraits(osType);
2355
+ const coverage = historyReadCoverage(
2356
+ histType,
2357
+ histDetailRaw,
2358
+ traits.readKeywords,
2359
+ traits.writeKeywords
2360
+ );
2361
+ for (const p of coverage.full) historyFullReadPaths.add(p);
2362
+ for (const [p, upto] of coverage.partial) {
2363
+ if (historyPartialRead.has(p)) {
2364
+ const old = historyPartialRead.get(p);
2365
+ historyPartialRead.set(p, old == null || upto == null ? null : Math.max(old, upto));
2366
+ } else {
2367
+ historyPartialRead.set(p, upto);
2147
2368
  }
2148
2369
  }
2149
2370
  }
@@ -2156,18 +2377,49 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
2156
2377
  if (filteredPaths.length === 0) {
2157
2378
  return null;
2158
2379
  }
2380
+ const normalizedTargets = filteredPaths.map((p) => normalizePathForCompare(p, cwd)).filter((p, i, arr) => p && arr.indexOf(p) === i);
2381
+ const normalizedFullReads = new Set(
2382
+ [...historyFullReadPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2383
+ );
2384
+ const normalizedPartialReads = /* @__PURE__ */ new Map();
2385
+ for (const [p, upto] of historyPartialRead) {
2386
+ const np = normalizePathForCompare(p, cwd);
2387
+ if (np) normalizedPartialReads.set(np, upto);
2388
+ }
2389
+ const appendTargets = appendOnlyTargets(actionDetailRaw, osType);
2390
+ if (APPEND_MODE_RE.test(actionDetailRaw)) {
2391
+ for (const p of filteredPaths) appendTargets.add(p);
2392
+ }
2393
+ let checkTargets = normalizedTargets;
2394
+ if (appendTargets.size > 0) {
2395
+ const appendNorm = new Set(
2396
+ [...appendTargets].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
2397
+ );
2398
+ checkTargets = normalizedTargets.filter((p) => !([...appendNorm].some((ap) => pathIsSameOrUnder(p, ap) || pathIsSameOrUnder(ap, p)) && !isProtectedWritePath(p)));
2399
+ if (checkTargets.length === 0) return null;
2400
+ }
2159
2401
  const unreadPaths = [];
2160
- for (const path7 of filteredPaths) {
2161
- const hasRead = [...historyReadPaths].some(
2162
- (rp) => path7 === rp || path7.startsWith(rp) || rp.startsWith(path7)
2402
+ for (const path8 of checkTargets) {
2403
+ const isFullRead = [...normalizedFullReads].some(
2404
+ (rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
2163
2405
  );
2164
- if (!hasRead) {
2165
- let isCreate = !fs.existsSync(path7);
2406
+ let isPartialCovered = false;
2407
+ if (!isFullRead) {
2408
+ for (const [pp, upto] of normalizedPartialReads) {
2409
+ if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
2410
+ if (upto != null && fileHasAtMostLines(path8, upto)) {
2411
+ isPartialCovered = true;
2412
+ break;
2413
+ }
2414
+ }
2415
+ }
2416
+ if (!isFullRead && !isPartialCovered) {
2417
+ let isCreate = !fs.existsSync(path8);
2166
2418
  if (!isCreate) {
2167
2419
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
2168
2420
  }
2169
2421
  if (!isCreate) {
2170
- unreadPaths.push(path7);
2422
+ unreadPaths.push(path8);
2171
2423
  }
2172
2424
  }
2173
2425
  }
@@ -2344,7 +2596,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2344
2596
  violatedLayers: ["L2.1"]
2345
2597
  };
2346
2598
  }
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;
2599
+ var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
2348
2600
  var init_logic_rules = __esm({
2349
2601
  "src/engine/logic-rules.ts"() {
2350
2602
  "use strict";
@@ -2361,16 +2613,16 @@ var init_logic_rules = __esm({
2361
2613
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
2362
2614
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
2363
2615
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
2364
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
2616
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2365
2617
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
2366
2618
  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 }));
2619
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2368
2620
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
2369
2621
  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 }));
2622
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2371
2623
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
2372
2624
  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 }));
2625
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2374
2626
  _scopeIndex = null;
2375
2627
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
2376
2628
  "ask_user_question",
@@ -2393,6 +2645,23 @@ var init_logic_rules = __esm({
2393
2645
  ]);
2394
2646
  NON_WRITE_TOOL_PREFIXES = _LOGIC.non_write_tool_prefixes ?? [];
2395
2647
  PSEUDO_FS_PREFIXES = ["/sys/", "/proc/", "/dev/", "/run/"];
2648
+ SINGLE_FILE_WRITE_TOOLS = new Set(
2649
+ _LOGIC.single_file_write_tools ?? []
2650
+ );
2651
+ WRITE_INTENT_KEYWORDS = _LOGIC.write_intent_keywords ?? [];
2652
+ MISSING_WRITE_PATH_RE = /(?:写入文件|编辑文件|写入|编辑)\s*[::]\s*\?/;
2653
+ DECLARED_WRITE_PATH_RE = /(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*([~./][^\s—|,;]+)/;
2654
+ DECLARED_WRITE_PATH_JSON_RE = /"(?:file_path|filePath|path)"\s*:\s*"([^"]+)"/;
2655
+ PROTECTED_WRITE_PREFIXES = _LOGIC.protected_write_prefixes ?? [];
2656
+ PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
2657
+ APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
2658
+ APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
2659
+ SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
2660
+ SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
2661
+ SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
2662
+ HEAD_TAIL_LIMIT_RE = /(?:-n\s*|-\s*)(\d+)/;
2663
+ SED_RANGE_RE = /-n\s+['"]?(\d+)\s*,\s*(\d+|\$)\s*p/;
2664
+ PARTIAL_COVER_CHECK_MAX_LINES = 1e5;
2396
2665
  WRITE_KEYWORDS = ["write", "\u5199\u5165", "save", "\u4FDD\u5B58", "modify", "\u4FEE\u6539", "update", "\u66F4\u65B0", "delete", "\u5220\u9664", "remove", "\u79FB\u9664", "create", "\u521B\u5EFA", "append", "\u8FFD\u52A0", "truncate", "\u622A\u65AD", "overwrite", "\u8986\u76D6", "replace", "\u66FF\u6362", "edit"];
2397
2666
  SED_INPLACE_RE = /\bsed\s+(?:-\S+\s+)*(?:-[a-zA-Z]*i[a-zA-Z]*|--in-place)\b/i;
2398
2667
  DEVNULL_REDIRECT_RE = /(?:2|&|1)?\s*>\s*\/dev\/null\b/g;
@@ -2411,7 +2680,8 @@ var init_logic_rules = __esm({
2411
2680
  intentKeywords: p.intent_keywords,
2412
2681
  dangerousActions: p.dangerous_actions,
2413
2682
  reason: p.reason,
2414
- os: String(p.os || "linux").toLowerCase()
2683
+ os: String(p.os || "linux").toLowerCase(),
2684
+ allowIfWriteIntent: p.allow_if_write_intent === true
2415
2685
  }));
2416
2686
  })();
2417
2687
  COMBO_STAGES = (() => {
@@ -2452,11 +2722,11 @@ var init_logic_rules = __esm({
2452
2722
 
2453
2723
  // src/engine/asset-dir.ts
2454
2724
  import { existsSync as existsSync5 } from "fs";
2455
- import { join as join5, resolve as resolve3 } from "path";
2725
+ import { join as join6, resolve as resolve3 } from "path";
2456
2726
  function assetDirCandidates(moduleDir, name) {
2457
2727
  const root = getRulesRoot();
2458
2728
  if (root) {
2459
- const p = join5(root, name);
2729
+ const p = join6(root, name);
2460
2730
  return [p, p];
2461
2731
  }
2462
2732
  return [
@@ -2675,7 +2945,7 @@ __export(runtime_config_exports, {
2675
2945
  updateSkillEnabled: () => updateSkillEnabled
2676
2946
  });
2677
2947
  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";
2948
+ import { join as join7 } from "path";
2679
2949
  import { fileURLToPath as fileURLToPath4 } from "url";
2680
2950
  import { dirname as dirname4 } from "path";
2681
2951
  function runtimeDir() {
@@ -2811,8 +3081,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
2811
3081
  function _filterRulesByOs(rules, osType) {
2812
3082
  const accepted = acceptedOsValues(osType);
2813
3083
  return rules.filter((r) => {
2814
- const os4 = String(r.os || "linux").toLowerCase();
2815
- return os4 === "all" || accepted.includes(os4);
3084
+ const os5 = String(r.os || "linux").toLowerCase();
3085
+ return os5 === "all" || accepted.includes(os5);
2816
3086
  });
2817
3087
  }
2818
3088
  function _userCustomRules(runtime, layers, requiredKey) {
@@ -3014,7 +3284,7 @@ function _l2SensitivePathsToRules() {
3014
3284
  const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
3015
3285
  const all = [...root, ...home, ...credential];
3016
3286
  for (const sp of all) {
3017
- const os4 = String(sp.os || "linux").toLowerCase();
3287
+ const os5 = String(sp.os || "linux").toLowerCase();
3018
3288
  const denyMode = sp.denyMode || _deriveDenyMode({
3019
3289
  deny_mode: sp.deny_mode,
3020
3290
  credential: sp.credential,
@@ -3024,7 +3294,7 @@ function _l2SensitivePathsToRules() {
3024
3294
  // id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
3025
3295
  // hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
3026
3296
  // Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
3027
- id: `path_${os4}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3297
+ id: `path_${os5}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
3028
3298
  path: sp.path,
3029
3299
  risk_level: sp.riskLevel,
3030
3300
  desc: sp.desc,
@@ -3033,7 +3303,7 @@ function _l2SensitivePathsToRules() {
3033
3303
  skip_l3_on_disabled: true,
3034
3304
  enabled: true,
3035
3305
  builtin: true,
3036
- os: os4
3306
+ os: os5
3037
3307
  };
3038
3308
  _syncDenyModeFields(rule);
3039
3309
  if (sp.dirDelOnly) rule.dir_del_only = true;
@@ -3051,6 +3321,9 @@ function _l2IntentPatternsToRules() {
3051
3321
  intent_keywords: pat.intentKeywords,
3052
3322
  dangerous_actions: pat.dangerousActions,
3053
3323
  reason: pat.reason,
3324
+ // 旧 runtime 里没有这个字段:缺省 false,但 getIntentPatternsForOs 会按
3325
+ // reason 回填内置默认值,避免旧配置让新豁免失效。
3326
+ allow_if_write_intent: pat.allowIfWriteIntent,
3054
3327
  skip_l3_on_disabled: true,
3055
3328
  enabled: true,
3056
3329
  builtin: true
@@ -3121,7 +3394,7 @@ function _l3SkillsToRules() {
3121
3394
  function _scenarioRulesToDefaults() {
3122
3395
  const out = {};
3123
3396
  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;
3397
+ const scenDir = _root ? join7(_root, "scenarios") : existsSync7(_SCENARIOS_DIR_PROD) ? _SCENARIOS_DIR_PROD : existsSync7(_SCENARIOS_DIR_DEV) ? _SCENARIOS_DIR_DEV : _SCENARIOS_DIR_PROD;
3125
3398
  if (!existsSync7(scenDir)) return out;
3126
3399
  let entries;
3127
3400
  try {
@@ -3130,7 +3403,7 @@ function _scenarioRulesToDefaults() {
3130
3403
  return out;
3131
3404
  }
3132
3405
  for (const scenarioId of entries) {
3133
- const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join6(scenDir, scenarioId, "rules.json");
3406
+ const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join7(scenDir, scenarioId, "rules.json");
3134
3407
  if (!existsSync7(rulesFile)) continue;
3135
3408
  let data;
3136
3409
  try {
@@ -3171,7 +3444,7 @@ function _scenarioRulesToDefaults() {
3171
3444
  function _agentRulesToDefaults() {
3172
3445
  const out = {};
3173
3446
  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;
3447
+ const agentsDir = _root ? join7(_root, "agents") : existsSync7(_AGENTS_DIR_PROD) ? _AGENTS_DIR_PROD : existsSync7(_AGENTS_DIR_DEV) ? _AGENTS_DIR_DEV : _AGENTS_DIR_PROD;
3175
3448
  if (!existsSync7(agentsDir)) return out;
3176
3449
  let entries;
3177
3450
  try {
@@ -3180,7 +3453,7 @@ function _agentRulesToDefaults() {
3180
3453
  return out;
3181
3454
  }
3182
3455
  for (const agentId of entries) {
3183
- const rulesFile = join6(agentsDir, agentId, "rules.json");
3456
+ const rulesFile = join7(agentsDir, agentId, "rules.json");
3184
3457
  if (!existsSync7(rulesFile)) continue;
3185
3458
  let data;
3186
3459
  try {
@@ -3213,6 +3486,11 @@ function _agentRulesToDefaults() {
3213
3486
  category_enabled: true,
3214
3487
  category_desc: "agent \u4E13\u5C5E\u654F\u611F\u8DEF\u5F84\uFF08L1 \u672B\u5C3E\u8FFD\u52A0\uFF09",
3215
3488
  rules: (data.extra_sensitive_paths || []).map((sp) => ({ ...sp, enabled: true, builtin: true }))
3489
+ },
3490
+ extra_single_file_write_tools: {
3491
+ category_enabled: true,
3492
+ category_desc: "agent \u4E13\u5C5E\u5355\u6587\u4EF6\u5199\u5DE5\u5177\uFF08read_before_write \u53EA\u53D6\u58F0\u660E\u8DEF\u5F84\uFF09",
3493
+ rules: (data.extra_single_file_write_tools || []).map((v) => ({ value: v, enabled: true, builtin: true }))
3216
3494
  }
3217
3495
  };
3218
3496
  }
@@ -3561,8 +3839,8 @@ function _filterDefaultsByOs(rules, osType) {
3561
3839
  const accepted = acceptedOsValues(osType);
3562
3840
  return rules.filter((r) => {
3563
3841
  if (!r.os) return true;
3564
- const os4 = String(r.os).toLowerCase();
3565
- return os4 === "all" || accepted.includes(os4);
3842
+ const os5 = String(r.os).toLowerCase();
3843
+ return os5 === "all" || accepted.includes(os5);
3566
3844
  });
3567
3845
  }
3568
3846
  function _hasRulesForOs(rules, osType) {
@@ -3687,7 +3965,8 @@ function effectiveIntentPatterns(osType) {
3687
3965
  intentKeywords: r.intent_keywords || [],
3688
3966
  dangerousActions: r.dangerous_actions || [],
3689
3967
  reason: String(r.reason || ""),
3690
- os: String(r.os || "linux").toLowerCase()
3968
+ os: String(r.os || "linux").toLowerCase(),
3969
+ allowIfWriteIntent: r.allow_if_write_intent === true
3691
3970
  }));
3692
3971
  });
3693
3972
  }
@@ -3792,12 +4071,12 @@ function addCustomSkill(skillId, category, keywords, content) {
3792
4071
  );
3793
4072
  }
3794
4073
  const runtime = loadRuntimeConfig();
3795
- const skillsDir = join6(getRuntimeConfigDir(), "agent_moss_skills");
4074
+ const skillsDir = join7(getRuntimeConfigDir(), "agent_moss_skills");
3796
4075
  try {
3797
4076
  mkdirSync2(skillsDir, { recursive: true });
3798
4077
  } catch {
3799
4078
  }
3800
- writeFileSync(join6(skillsDir, `${skillId}.md`), content, "utf-8");
4079
+ writeFileSync(join7(skillsDir, `${skillId}.md`), content, "utf-8");
3801
4080
  const l3 = runtime.L3_skills || (runtime.L3_skills = {});
3802
4081
  const cat = l3[category] || (l3[category] = { category_enabled: true, category_desc: "", skills: [] });
3803
4082
  (cat.skills || (cat.skills = [])).push({ id: skillId, keywords, enabled: true, builtin: false });
@@ -3812,7 +4091,7 @@ function deleteCustomSkill(skillId, category) {
3812
4091
  if (idx >= 0) {
3813
4092
  if (skills[idx].builtin) return null;
3814
4093
  skills.splice(idx, 1);
3815
- const skillPath = join6(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
4094
+ const skillPath = join7(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
3816
4095
  try {
3817
4096
  if (existsSync7(skillPath)) unlinkSync(skillPath);
3818
4097
  } catch {
@@ -3875,6 +4154,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
3875
4154
  read_only: r.read_only,
3876
4155
  deny_mode: r.deny_mode
3877
4156
  }));
4157
+ const singleFileWriteTools = _agentCategoryEnabledRules(agentData.extra_single_file_write_tools).filter((r) => r.value).map((r) => String(r.value).toLowerCase());
3878
4158
  return {
3879
4159
  agent_id: agentId,
3880
4160
  description: "",
@@ -3883,6 +4163,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
3883
4163
  extra_sensitive_paths: sensitivePaths,
3884
4164
  builtin_safe_skills: safeSkills.filter((r) => r.value).map((r) => r.value),
3885
4165
  builtin_safe_action_types: safeAction.filter((r) => r.value).map((r) => r.value),
4166
+ extra_single_file_write_tools: singleFileWriteTools,
3886
4167
  extra_skills: []
3887
4168
  };
3888
4169
  }
@@ -3961,6 +4242,7 @@ function getEnabledScenarioExtensions(runtime, scenarioId) {
3961
4242
  extra_sensitive_paths: sensitivePaths,
3962
4243
  builtin_safe_skills: [],
3963
4244
  builtin_safe_action_types: [],
4245
+ extra_single_file_write_tools: [],
3964
4246
  extra_skills: []
3965
4247
  };
3966
4248
  }
@@ -4021,7 +4303,7 @@ var init_runtime_config = __esm({
4021
4303
  __dirname4 = dirname4(fileURLToPath4(import.meta.url));
4022
4304
  ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
4023
4305
  RUNTIME_CONFIG_DIR = runtimeDir();
4024
- RUNTIME_CONFIG_PATH = join6(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
4306
+ RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
4025
4307
  LAYER_DISABLE_ENV = {
4026
4308
  L1_heuristic: "AGENT_MOSS_DISABLE_HEURISTIC",
4027
4309
  L2_logic_rules: "AGENT_MOSS_DISABLE_LOGIC_RULES",
@@ -4049,10 +4331,10 @@ var init_runtime_config = __esm({
4049
4331
  intent_consistency: ["intent_keywords", "reason"]
4050
4332
  };
4051
4333
  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");
4334
+ _AGENTS_DIR_PROD = join7(__dirname4, "agents");
4335
+ _AGENTS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "agents");
4336
+ _SCENARIOS_DIR_PROD = join7(__dirname4, "scenarios");
4337
+ _SCENARIOS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
4056
4338
  _effectiveCache = /* @__PURE__ */ new WeakMap();
4057
4339
  SKILL_ID_RE = /^[A-Za-z0-9_-]+$/;
4058
4340
  registerRuntimeConfigBridge({
@@ -4095,7 +4377,7 @@ __export(config_exports, {
4095
4377
  wildcardToRegExp: () => wildcardToRegExp
4096
4378
  });
4097
4379
  import fs2 from "fs";
4098
- import path2 from "path";
4380
+ import path3 from "path";
4099
4381
  import { fileURLToPath as fileURLToPath5 } from "url";
4100
4382
  function loadConfigFile(filePath) {
4101
4383
  try {
@@ -4108,17 +4390,17 @@ function loadConfigFile(filePath) {
4108
4390
  function resolveConfigPath() {
4109
4391
  const envPath = process.env.AGENT_MOSS_CONFIG_PATH;
4110
4392
  if (envPath) return envPath;
4111
- const userConfig = path2.join(getConfigDir(), "config.json");
4393
+ const userConfig = path3.join(getConfigDir(), "config.json");
4112
4394
  if (fs2.existsSync(userConfig)) return userConfig;
4113
4395
  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")
4396
+ path3.join(__configModuleDir, "config.json.example"),
4397
+ path3.join(__configModuleDir, "..", "config.json.example"),
4398
+ path3.join(__configModuleDir, "..", "..", "agent_moss", "infra", "config.json.example"),
4399
+ path3.join(__configModuleDir, "..", "..", "..", "agent_moss", "infra", "config.json.example")
4118
4400
  ];
4119
4401
  const defaultConfig = defaultCandidates.find((p) => fs2.existsSync(p));
4120
4402
  if (defaultConfig) {
4121
- const configDir = path2.dirname(userConfig);
4403
+ const configDir = path3.dirname(userConfig);
4122
4404
  fs2.mkdirSync(configDir, { recursive: true });
4123
4405
  const pkgConfig = loadConfigFile(defaultConfig);
4124
4406
  const safeConfig = pkgConfig ? { ...pkgConfig, llm: { ...pkgConfig.llm, api_key: "" } } : {};
@@ -4348,7 +4630,7 @@ var init_config = __esm({
4348
4630
  init_rules_mode();
4349
4631
  __configModuleDir = (() => {
4350
4632
  try {
4351
- return path2.dirname(fileURLToPath5(import.meta.url));
4633
+ return path3.dirname(fileURLToPath5(import.meta.url));
4352
4634
  } catch {
4353
4635
  return typeof __dirname !== "undefined" ? __dirname : process.cwd();
4354
4636
  }
@@ -4371,11 +4653,11 @@ var init_config = __esm({
4371
4653
  };
4372
4654
  })();
4373
4655
  USER_RULES_PATHS = [
4374
- path2.join(__configModuleDir, "rules", "user_rules.json"),
4656
+ path3.join(__configModuleDir, "rules", "user_rules.json"),
4375
4657
  // 源在 ts/src/rules(一般不存在)
4376
- path2.join(__configModuleDir, "..", "rules", "user_rules.json"),
4658
+ path3.join(__configModuleDir, "..", "rules", "user_rules.json"),
4377
4659
  // dist: dist/engine/../rules = dist/rules ✅
4378
- path2.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
4660
+ path3.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
4379
4661
  // dev src: ts/src/../../agent_moss
4380
4662
  ];
4381
4663
  customRules = loadCustomRules();
@@ -4393,11 +4675,11 @@ var init_config = __esm({
4393
4675
 
4394
4676
  // src/agents/index.ts
4395
4677
  import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
4396
- import { resolve as resolve5, dirname as dirname5, join as join7 } from "path";
4678
+ import { resolve as resolve5, dirname as dirname5, join as join8 } from "path";
4397
4679
  import { fileURLToPath as fileURLToPath6 } from "url";
4398
4680
  function resolveAgentsDir() {
4399
4681
  const root = getRulesRoot();
4400
- if (root) return join7(root, "agents");
4682
+ if (root) return join8(root, "agents");
4401
4683
  if (existsSync8(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
4402
4684
  if (existsSync8(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
4403
4685
  return AGENTS_DIR_PROD;
@@ -4458,6 +4740,7 @@ function mergeAgentExtensions(...exts) {
4458
4740
  extra_sensitive_paths: nonNull.flatMap((e) => e.extra_sensitive_paths || []),
4459
4741
  builtin_safe_skills: nonNull.flatMap((e) => e.builtin_safe_skills || []),
4460
4742
  builtin_safe_action_types: nonNull.flatMap((e) => e.builtin_safe_action_types || []),
4743
+ extra_single_file_write_tools: nonNull.flatMap((e) => e.extra_single_file_write_tools || []),
4461
4744
  extra_skills: nonNull.flatMap((e) => e.extra_skills || [])
4462
4745
  };
4463
4746
  }
@@ -4479,11 +4762,11 @@ var init_agents = __esm({
4479
4762
 
4480
4763
  // src/scenarios/index.ts
4481
4764
  import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
4482
- import { resolve as resolve6, dirname as dirname6, join as join8 } from "path";
4765
+ import { resolve as resolve6, dirname as dirname6, join as join9 } from "path";
4483
4766
  import { fileURLToPath as fileURLToPath7 } from "url";
4484
4767
  function resolveScenariosDir() {
4485
4768
  const root = getRulesRoot();
4486
- if (root) return join8(root, "scenarios");
4769
+ if (root) return join9(root, "scenarios");
4487
4770
  if (existsSync9(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
4488
4771
  if (existsSync9(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
4489
4772
  return SCENARIOS_DIR_PROD;
@@ -4541,6 +4824,7 @@ function getScenarioExtensions(scenarioId) {
4541
4824
  extra_sensitive_paths: data.extra_sensitive_paths || [],
4542
4825
  builtin_safe_skills: data.builtin_safe_skills || [],
4543
4826
  builtin_safe_action_types: data.builtin_safe_action_types || [],
4827
+ extra_single_file_write_tools: data.extra_single_file_write_tools || [],
4544
4828
  extra_skills: data.extra_skills || []
4545
4829
  };
4546
4830
  } catch (e) {
@@ -4973,16 +5257,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4973
5257
  if (String(osType || "").toLowerCase() === "windows") {
4974
5258
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
4975
5259
  }
4976
- const pathMatches = (text, path7) => {
4977
- const parts = path7.split(/(\(\?!.*?\))/);
5260
+ const pathMatches = (text, path8) => {
5261
+ const parts = path8.split(/(\(\?!.*?\))/);
4978
5262
  const escaped = parts.map((part) => {
4979
5263
  if (part.startsWith("(?!")) return part;
4980
5264
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4981
5265
  }).join("");
4982
- const re = path7.startsWith(".") || path7.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
5266
+ const re = path8.startsWith(".") || path8.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4983
5267
  return re.test(text);
4984
5268
  };
4985
- const pathMatchesAny = (path7) => pathScanTexts.some((t) => pathMatches(t, path7));
5269
+ const pathMatchesAny = (path8) => pathScanTexts.some((t) => pathMatches(t, path8));
4986
5270
  for (const sp of rootPaths) {
4987
5271
  if (pathMatchesAny(sp.path.toLowerCase())) {
4988
5272
  if (keygenGenerate) continue;
@@ -5125,8 +5409,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5125
5409
  }
5126
5410
  return null;
5127
5411
  }
5128
- function isHomeValue(path7) {
5129
- let p = path7.trim().toLowerCase();
5412
+ function isHomeValue(path8) {
5413
+ let p = path8.trim().toLowerCase();
5130
5414
  if (p.startsWith("$(") && p.endsWith(")")) {
5131
5415
  const inner = p.slice(2, -1).trim();
5132
5416
  return HOME_TARGET_RE.test(" " + inner);
@@ -5182,15 +5466,15 @@ function checkHomeDeletion(actionType, actionDetail) {
5182
5466
  }
5183
5467
  const assigned = {};
5184
5468
  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;
5469
+ for (const [varName, path8] of Object.entries(assigned)) {
5470
+ if (!isHomeValue(path8)) continue;
5187
5471
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
5188
5472
  for (const seg of segs) {
5189
5473
  if (!isDeleteCommand(seg)) continue;
5190
5474
  if (varRefRe.test(seg)) {
5191
5475
  return {
5192
5476
  allowed: false,
5193
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path7}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5477
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path8}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5194
5478
  riskLevel: "high",
5195
5479
  riskType: "script_execution",
5196
5480
  confidence: 90,
@@ -5486,7 +5770,7 @@ var init_template_loader = __esm({
5486
5770
 
5487
5771
  // src/engine/script-analyzer.ts
5488
5772
  import { readFileSync as readFileSync10 } from "fs";
5489
- import { resolve as resolve8, join as join9 } from "path";
5773
+ import { resolve as resolve8, join as join10 } from "path";
5490
5774
  function emptyResult() {
5491
5775
  return { scriptPath: "", scriptContent: "", matchedKeywords: [], lineCount: 0, isSuspicious: false, error: "", riskLevel: "", riskReason: "" };
5492
5776
  }
@@ -5539,7 +5823,7 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
5539
5823
  }
5540
5824
  function readScriptContent(scriptPath, maxLines = 500) {
5541
5825
  try {
5542
- const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join9(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
5826
+ const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join10(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
5543
5827
  const raw = readFileSync10(expandedPath, "utf-8");
5544
5828
  const lines = raw.split("\n").slice(0, maxLines);
5545
5829
  return { content: lines.join("\n"), lineCount: lines.length, error: "" };
@@ -5994,15 +6278,15 @@ function parseShellString(s) {
5994
6278
  let m;
5995
6279
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
5996
6280
  const interp = m[1];
5997
- const path7 = m[2].trim();
6281
+ const path8 = m[2].trim();
5998
6282
  let rest = m[3].trim();
5999
- if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6283
+ if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6000
6284
  rest = rest.split(/[;|&<>]/)[0].trim();
6001
6285
  const args = [];
6002
6286
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6003
6287
  args.push(tm[1] ? tm[2] : tm[3]);
6004
6288
  }
6005
- return { path: path7, args, interpreter: interp };
6289
+ return { path: path8, args, interpreter: interp };
6006
6290
  }
6007
6291
  return null;
6008
6292
  }
@@ -6048,9 +6332,9 @@ function extractCallsFromTree(tree, reachableLines) {
6048
6332
  }
6049
6333
  if (allStr && elts.length >= 2) {
6050
6334
  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 });
6335
+ const path8 = elts[1];
6336
+ if (!path8.startsWith("-") && !path8.startsWith("$") && !path8.includes("/dev/")) {
6337
+ add({ path: path8, args: elts.slice(2), interpreter: interp });
6054
6338
  return true;
6055
6339
  }
6056
6340
  }
@@ -6090,15 +6374,15 @@ function extractCallsRegex(content) {
6090
6374
  let m;
6091
6375
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
6092
6376
  const interp = m[1];
6093
- const path7 = m[2].trim();
6377
+ const path8 = m[2].trim();
6094
6378
  let rest = m[3].trim();
6095
- if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6379
+ if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6096
6380
  rest = rest.split(/[;|&<>]/)[0].trim();
6097
6381
  const args = [];
6098
6382
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6099
6383
  args.push(tm[1] ? tm[2] : tm[3]);
6100
6384
  }
6101
- calls.push({ path: path7, args, interpreter: interp });
6385
+ calls.push({ path: path8, args, interpreter: interp });
6102
6386
  }
6103
6387
  return calls;
6104
6388
  }
@@ -6881,15 +7165,15 @@ function extractCallsFromContent(content) {
6881
7165
  CHILD_CALL_RE2.lastIndex = 0;
6882
7166
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
6883
7167
  const interp = m[1];
6884
- const path7 = m[2].trim();
7168
+ const path8 = m[2].trim();
6885
7169
  let rest = m[3].trim();
6886
- if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
7170
+ if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6887
7171
  rest = rest.split(/[;|&<>]/)[0].trim();
6888
7172
  const args = [];
6889
7173
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6890
7174
  args.push(tm[1] ? tm[2] : tm[3]);
6891
7175
  }
6892
- calls.push({ path: path7, args, interpreter: interp });
7176
+ calls.push({ path: path8, args, interpreter: interp });
6893
7177
  }
6894
7178
  return calls;
6895
7179
  }
@@ -6958,8 +7242,8 @@ var init_backends = __esm({
6958
7242
 
6959
7243
  // src/engine/script-engine/tracker.ts
6960
7244
  import * as fs3 from "fs";
6961
- import * as path3 from "path";
6962
- import * as os from "os";
7245
+ import * as path4 from "path";
7246
+ import * as os2 from "os";
6963
7247
  function maxFileSizeFromEnv() {
6964
7248
  const raw = (process.env.AGENT_MOSS_SCRIPT_MAX_FILE_SIZE || "").trim();
6965
7249
  if (raw) {
@@ -6978,11 +7262,11 @@ function pickBackend(pathStr) {
6978
7262
  function resolvePath(p, baseDir) {
6979
7263
  let expanded = p;
6980
7264
  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);
7265
+ expanded = path4.join(os2.homedir(), expanded.slice(1));
7266
+ } else if (!path4.isAbsolute(expanded) && baseDir) {
7267
+ expanded = path4.join(baseDir, expanded);
6984
7268
  }
6985
- return path3.resolve(expanded);
7269
+ return path4.resolve(expanded);
6986
7270
  }
6987
7271
  function readScript(pathStr, maxFileSize) {
6988
7272
  try {
@@ -7076,7 +7360,7 @@ var init_tracker = __esm({
7076
7360
  const baseDir = cwd || process.cwd();
7077
7361
  const resolved = resolvePath(entryPath);
7078
7362
  this.result.entryPath = resolved;
7079
- this.visitScript(resolved, 0, path3.dirname(resolved), entryArgs);
7363
+ this.visitScript(resolved, 0, path4.dirname(resolved), entryArgs);
7080
7364
  const nodes = this.result.nodes;
7081
7365
  this.result.hasCritical = nodes.some((n) => n.l1RiskLevel === "critical" || n.l2RiskLevel === "critical" || n.keywordRiskLevel === "critical") || this.result.hasCritical;
7082
7366
  this.result.hasHigh = nodes.some((n) => ["high", "critical"].includes(n.l1RiskLevel) || ["high", "critical"].includes(n.l2RiskLevel) || ["high", "critical"].includes(n.keywordRiskLevel));
@@ -7138,12 +7422,12 @@ var init_tracker = __esm({
7138
7422
  }
7139
7423
  }
7140
7424
  }
7141
- const parentDir = path3.dirname(pathStr);
7425
+ const parentDir = path4.dirname(pathStr);
7142
7426
  const childPaths = [];
7143
7427
  for (const call of ir.calls) {
7144
7428
  const child = resolvePath(call.path, parentDir);
7145
7429
  childPaths.push(child);
7146
- this.visitScript(child, depth + 1, path3.dirname(child), call.args);
7430
+ this.visitScript(child, depth + 1, path4.dirname(child), call.args);
7147
7431
  if (this.result.hasCritical) break;
7148
7432
  }
7149
7433
  node.childPaths = childPaths;
@@ -7155,8 +7439,8 @@ var init_tracker = __esm({
7155
7439
 
7156
7440
  // src/engine/script-content-analyzer.ts
7157
7441
  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";
7442
+ import { resolve as resolve10, join as join12, isAbsolute as isAbsolute4 } from "path";
7443
+ import { homedir as homedir5 } from "os";
7160
7444
  function emptyChain() {
7161
7445
  return {
7162
7446
  nodes: [],
@@ -7338,7 +7622,7 @@ function shlexSplit(s) {
7338
7622
  function resolvePath2(p) {
7339
7623
  let expanded = p;
7340
7624
  if (expanded.startsWith("~/") || expanded === "~") {
7341
- expanded = join11(homedir4(), expanded.slice(1));
7625
+ expanded = join12(homedir5(), expanded.slice(1));
7342
7626
  }
7343
7627
  return resolve10(expanded);
7344
7628
  }
@@ -7461,8 +7745,8 @@ function analyzeScriptContent2(input, ext) {
7461
7745
  resolvedPath = inline;
7462
7746
  isInline = true;
7463
7747
  }
7464
- if (resolvedPath && !isAbsolute3(resolvedPath) && !resolvedPath.startsWith("~/")) {
7465
- resolvedPath = join11(input.cwd || process.cwd(), resolvedPath);
7748
+ if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
7749
+ resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
7466
7750
  }
7467
7751
  const l1Adapter = (content) => {
7468
7752
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
@@ -7580,7 +7864,7 @@ var init_script_content_analyzer = __esm({
7580
7864
 
7581
7865
  // src/infra/trace-log.ts
7582
7866
  import fs4 from "fs";
7583
- import path4 from "path";
7867
+ import path5 from "path";
7584
7868
  function traceLevel() {
7585
7869
  if (_levelCache !== null) return _levelCache;
7586
7870
  const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
@@ -7607,7 +7891,7 @@ function tracePath() {
7607
7891
  const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
7608
7892
  if (explicit) return explicit;
7609
7893
  try {
7610
- return path4.join(getDataRoot(), "agent_moss_trace.log");
7894
+ return path5.join(getDataRoot(), "agent_moss_trace.log");
7611
7895
  } catch {
7612
7896
  return "agent_moss_trace.log";
7613
7897
  }
@@ -7646,7 +7930,7 @@ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
7646
7930
  `;
7647
7931
  const file = tracePath();
7648
7932
  try {
7649
- const dir = path4.dirname(file);
7933
+ const dir = path5.dirname(file);
7650
7934
  if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
7651
7935
  try {
7652
7936
  const st = fs4.statSync(file);
@@ -8242,7 +8526,7 @@ var init_token_stats = __esm({
8242
8526
 
8243
8527
  // src/engine/llm-analyzer.ts
8244
8528
  import { createHash as createHash3 } from "crypto";
8245
- import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants2 } from "fs";
8529
+ import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
8246
8530
  import OpenAI from "openai";
8247
8531
  function responseFieldLengths(message) {
8248
8532
  if (!message || typeof message !== "object") return {};
@@ -8381,11 +8665,11 @@ ${prompt}
8381
8665
  `;
8382
8666
  let flags = fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_APPEND;
8383
8667
  if (fsConstants2.O_NOFOLLOW) flags |= fsConstants2.O_NOFOLLOW;
8384
- const fd = openSync2(logPath, flags, 384);
8668
+ const fd = openSync3(logPath, flags, 384);
8385
8669
  try {
8386
8670
  writeSync2(fd, line);
8387
8671
  } finally {
8388
- closeSync2(fd);
8672
+ closeSync3(fd);
8389
8673
  }
8390
8674
  } catch (e) {
8391
8675
  console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
@@ -8681,8 +8965,8 @@ var init_llm_analyzer = __esm({
8681
8965
 
8682
8966
  // src/brain/rule-store.ts
8683
8967
  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";
8968
+ import { join as join13 } from "path";
8969
+ import { homedir as homedir6 } from "os";
8686
8970
  function getRulesPath() {
8687
8971
  const envPath = process.env[ENV_RULES_PATH];
8688
8972
  if (envPath) return envPath;
@@ -8700,7 +8984,7 @@ var init_rule_store = __esm({
8700
8984
  "src/brain/rule-store.ts"() {
8701
8985
  "use strict";
8702
8986
  init_esm_shims();
8703
- DEFAULT_RULES_PATH = join12(homedir5(), ".agentmoss", "brain", "rules.json");
8987
+ DEFAULT_RULES_PATH = join13(homedir6(), ".agentmoss", "brain", "rules.json");
8704
8988
  ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
8705
8989
  STATUS_DRAFT = "draft";
8706
8990
  STATUS_APPROVED = "approved";
@@ -8712,8 +8996,8 @@ var init_rule_store = __esm({
8712
8996
  BrainRuleStore = class {
8713
8997
  path;
8714
8998
  data;
8715
- constructor(path7) {
8716
- this.path = path7 || getRulesPath();
8999
+ constructor(path8) {
9000
+ this.path = path8 || getRulesPath();
8717
9001
  this.data = this.load();
8718
9002
  }
8719
9003
  load() {
@@ -9166,10 +9450,10 @@ ${reason.slice(0, 500)}
9166
9450
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
9167
9451
  let mm;
9168
9452
  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);
9453
+ const path8 = mm[1];
9454
+ if (path8.split("/").length < 3) continue;
9455
+ if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path8)) continue;
9456
+ const gen = this.generalizePath(path8);
9173
9457
  if (seen.has(gen)) continue;
9174
9458
  seen.add(gen);
9175
9459
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -9188,8 +9472,8 @@ ${reason.slice(0, 500)}
9188
9472
  }
9189
9473
  return false;
9190
9474
  }
9191
- generalizePath(path7) {
9192
- const p = path7.toLowerCase();
9475
+ generalizePath(path8) {
9476
+ const p = path8.toLowerCase();
9193
9477
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
9194
9478
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
9195
9479
  }
@@ -9316,8 +9600,8 @@ var init_reviewer = __esm({
9316
9600
 
9317
9601
  // src/brain/skill-manager.ts
9318
9602
  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";
9603
+ import { homedir as homedir7 } from "os";
9604
+ import { join as join14 } from "path";
9321
9605
  import { randomUUID } from "crypto";
9322
9606
  function getMetaPath(override) {
9323
9607
  return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
@@ -9327,14 +9611,14 @@ var init_skill_manager = __esm({
9327
9611
  "src/brain/skill-manager.ts"() {
9328
9612
  "use strict";
9329
9613
  init_esm_shims();
9330
- DEFAULT_SKILL_META_PATH = join13(homedir6(), ".agentmoss", "brain", "skill_meta.json");
9614
+ DEFAULT_SKILL_META_PATH = join14(homedir7(), ".agentmoss", "brain", "skill_meta.json");
9331
9615
  ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
9332
9616
  BrainSkillManager = class {
9333
9617
  constructor(skillsDir, metaPath) {
9334
9618
  this.skillsDir = skillsDir;
9335
9619
  this.metaPath = getMetaPath(metaPath);
9336
9620
  try {
9337
- mkdirSync5(join13(this.metaPath, ".."), { recursive: true });
9621
+ mkdirSync5(join14(this.metaPath, ".."), { recursive: true });
9338
9622
  } catch {
9339
9623
  }
9340
9624
  this.load();
@@ -9369,7 +9653,7 @@ var init_skill_manager = __esm({
9369
9653
  let changed = false;
9370
9654
  for (const sk of this.skills) {
9371
9655
  if (sk.status !== "active") continue;
9372
- if (!existsSync15(join13(this.skillsDir, `${sk.name}.md`))) {
9656
+ if (!existsSync15(join14(this.skillsDir, `${sk.name}.md`))) {
9373
9657
  sk.status = "stale";
9374
9658
  changed = true;
9375
9659
  }
@@ -9381,7 +9665,7 @@ var init_skill_manager = __esm({
9381
9665
  const id = skill.id || randomUUID();
9382
9666
  const name = skill.name || `brain_${id.slice(0, 8)}`;
9383
9667
  if (!existsSync15(this.skillsDir)) return "";
9384
- const mdPath = join13(this.skillsDir, `${name}.md`);
9668
+ const mdPath = join14(this.skillsDir, `${name}.md`);
9385
9669
  if (existsSync15(mdPath)) return "";
9386
9670
  try {
9387
9671
  writeFileSync4(mdPath, skill.content, "utf-8");
@@ -9431,7 +9715,7 @@ var init_skill_manager = __esm({
9431
9715
  const out = [];
9432
9716
  for (const sk of this.skills) {
9433
9717
  if (sk.origin_node !== "local" || sk.status !== "active") continue;
9434
- const mdPath = join13(this.skillsDir, `${sk.name}.md`);
9718
+ const mdPath = join14(this.skillsDir, `${sk.name}.md`);
9435
9719
  if (!existsSync15(mdPath)) continue;
9436
9720
  out.push({
9437
9721
  name: sk.name,
@@ -9548,7 +9832,7 @@ __export(contributor_exports, {
9548
9832
  });
9549
9833
  import { mkdirSync as mkdirSync6, mkdtempSync, rmSync, writeFileSync as writeFileSync5 } from "fs";
9550
9834
  import { tmpdir as tmpdir2 } from "os";
9551
- import { join as join14 } from "path";
9835
+ import { join as join15 } from "path";
9552
9836
  import { spawnSync } from "child_process";
9553
9837
  import { dirname as dirname10 } from "path";
9554
9838
  import { fileURLToPath as fileURLToPath9 } from "url";
@@ -9569,7 +9853,7 @@ function collectSkills(skillMgr) {
9569
9853
  }
9570
9854
  function writeExportFiles(outDir, rules, skills) {
9571
9855
  const written = [];
9572
- const rulesDir2 = join14(outDir, "rules");
9856
+ const rulesDir2 = join15(outDir, "rules");
9573
9857
  mkdirSync6(rulesDir2, { recursive: true });
9574
9858
  const byLayer = /* @__PURE__ */ new Map();
9575
9859
  for (const r of rules) {
@@ -9577,26 +9861,26 @@ function writeExportFiles(outDir, rules, skills) {
9577
9861
  byLayer.get(r.layer).push(r);
9578
9862
  }
9579
9863
  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);
9864
+ const path8 = join15(rulesDir2, `l${layer}_brain_rules.json`);
9865
+ writeFileSync5(path8, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
9866
+ written.push(path8);
9583
9867
  }
9584
9868
  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);
9869
+ const path8 = join15(rulesDir2, "empty.txt");
9870
+ writeFileSync5(path8, "(no brain rules to contribute)", "utf-8");
9871
+ written.push(path8);
9588
9872
  }
9589
- const skillsDir = join14(outDir, "skills");
9873
+ const skillsDir = join15(outDir, "skills");
9590
9874
  mkdirSync6(skillsDir, { recursive: true });
9591
9875
  for (const sk of skills) {
9592
- const path7 = join14(skillsDir, `${sk.name}.md`);
9593
- writeFileSync5(path7, sk.content || "", "utf-8");
9594
- written.push(path7);
9876
+ const path8 = join15(skillsDir, `${sk.name}.md`);
9877
+ writeFileSync5(path8, sk.content || "", "utf-8");
9878
+ written.push(path8);
9595
9879
  }
9596
9880
  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);
9881
+ const path8 = join15(skillsDir, "empty.txt");
9882
+ writeFileSync5(path8, "(no brain skills to contribute)", "utf-8");
9883
+ written.push(path8);
9600
9884
  }
9601
9885
  return written;
9602
9886
  }
@@ -9724,7 +10008,7 @@ async function contribute(opts = {}) {
9724
10008
  console.log(`[Brain] push \u76EE\u6807: ${pushTarget}`);
9725
10009
  console.log(`[Brain] MR \u6307\u5411: ${DEFAULT_TARGET_REPO}`);
9726
10010
  const store = new BrainRuleStore();
9727
- const skillsDir = resolveAssetDir(__dirname8, "skills") ?? join14(__dirname8, "..", "..", "agent_moss", "skills");
10011
+ const skillsDir = resolveAssetDir(__dirname8, "skills") ?? join15(__dirname8, "..", "..", "agent_moss", "skills");
9728
10012
  const skillMgr = new BrainSkillManager(skillsDir);
9729
10013
  let rules;
9730
10014
  let skills;
@@ -9739,9 +10023,9 @@ async function contribute(opts = {}) {
9739
10023
  return 0;
9740
10024
  }
9741
10025
  console.log(`[Brain] \u5BFC\u51FA: ${rules.length} \u6761\u89C4\u5219, ${skills.length} \u4E2A Skill`);
9742
- const workdir = mkdtempSync(join14(tmpdir2(), "agentmoss-contrib-"));
10026
+ const workdir = mkdtempSync(join15(tmpdir2(), "agentmoss-contrib-"));
9743
10027
  try {
9744
- writeExportFiles(join14(workdir, "agent_moss", "brain_contrib"), rules, skills);
10028
+ writeExportFiles(join15(workdir, "agent_moss", "brain_contrib"), rules, skills);
9745
10029
  console.log(`[Brain] \u63A2\u6D4B ${pushTarget} \u8BBF\u95EE\u6743\u9650 ...`);
9746
10030
  if (!probeAccess(pushTarget)) {
9747
10031
  const username = getCurrentUsername();
@@ -10300,12 +10584,12 @@ var init_builder = __esm({
10300
10584
  });
10301
10585
 
10302
10586
  // src/engine/formal-engine/properties.ts
10303
- function graphFromPath(nodes, path7, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10587
+ function graphFromPath(nodes, path8, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10304
10588
  const byKey = /* @__PURE__ */ new Map();
10305
10589
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
10306
10590
  const gNodes = [];
10307
10591
  const gEdges = [];
10308
- for (const item of path7) {
10592
+ for (const item of path8) {
10309
10593
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
10310
10594
  gNodes.push({
10311
10595
  session_id: item.sessionId,
@@ -10371,22 +10655,22 @@ function checkCrossSessionChain(graph) {
10371
10655
  if (witness !== void 0) {
10372
10656
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
10373
10657
  let matched = 0;
10374
- const path7 = [];
10658
+ const path8 = [];
10375
10659
  for (let k = 0; k < witness; k++) {
10376
10660
  const n = nodes[k];
10377
10661
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
10378
10662
  matched += 1;
10379
- path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10663
+ path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10380
10664
  }
10381
10665
  }
10382
10666
  if (matched < stages.length - 1) continue;
10383
- path7.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
10667
+ path8.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
10384
10668
  violations.push({
10385
10669
  propertyId: "cross-" + chain.id,
10386
10670
  reason: chain.reason,
10387
10671
  riskLevel: chain.riskLevel,
10388
- path: path7,
10389
- graph: graphFromPath(nodes, path7, "next", {
10672
+ path: path8,
10673
+ graph: graphFromPath(nodes, path8, "next", {
10390
10674
  property_id: "cross-" + chain.id,
10391
10675
  property_short: "P1",
10392
10676
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -10396,11 +10680,11 @@ function checkCrossSessionChain(graph) {
10396
10680
  } else {
10397
10681
  let matched = 0;
10398
10682
  let stageIdx = 0;
10399
- const path7 = [];
10683
+ const path8 = [];
10400
10684
  for (const n of nodes) {
10401
10685
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
10402
10686
  matched += 1;
10403
- path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10687
+ path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10404
10688
  stageIdx += 1;
10405
10689
  if (matched >= stages.length) break;
10406
10690
  }
@@ -10410,8 +10694,8 @@ function checkCrossSessionChain(graph) {
10410
10694
  propertyId: "cross-" + chain.id,
10411
10695
  reason: chain.reason,
10412
10696
  riskLevel: chain.riskLevel,
10413
- path: path7,
10414
- graph: graphFromPath(nodes, path7, "next", {
10697
+ path: path8,
10698
+ graph: graphFromPath(nodes, path8, "next", {
10415
10699
  property_id: "cross-" + chain.id,
10416
10700
  property_short: "P1",
10417
10701
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -10632,7 +10916,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10632
10916
  if (candidates.length > 0) {
10633
10917
  const pre = nodes[candidates[candidates.length - 1]];
10634
10918
  const post = nodes[firstEv];
10635
- const path7 = [
10919
+ const path8 = [
10636
10920
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10637
10921
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10638
10922
  ];
@@ -10640,8 +10924,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10640
10924
  propertyId: "no-exfil-after-privesc",
10641
10925
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
10642
10926
  riskLevel: "critical",
10643
- path: path7,
10644
- graph: graphFromPath(nodes, path7, "next", {
10927
+ path: path8,
10928
+ graph: graphFromPath(nodes, path8, "next", {
10645
10929
  property_id: "no-exfil-after-privesc",
10646
10930
  property_short: "P4",
10647
10931
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10658,7 +10942,7 @@ function checkNeverExfilAfterPrivesc(graph) {
10658
10942
  for (let j = i + 1; j < nodes.length; j++) {
10659
10943
  if (!isExfilNode(nodes[j])) continue;
10660
10944
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
10661
- const path7 = [
10945
+ const path8 = [
10662
10946
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10663
10947
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10664
10948
  ];
@@ -10666,8 +10950,8 @@ function checkNeverExfilAfterPrivesc(graph) {
10666
10950
  propertyId: "no-exfil-after-privesc",
10667
10951
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
10668
10952
  riskLevel: "critical",
10669
- path: path7,
10670
- graph: graphFromPath(nodes, path7, "next", {
10953
+ path: path8,
10954
+ graph: graphFromPath(nodes, path8, "next", {
10671
10955
  property_id: "no-exfil-after-privesc",
10672
10956
  property_short: "P4",
10673
10957
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -10699,7 +10983,7 @@ function checkNeverExfilAfterCred(graph) {
10699
10983
  }
10700
10984
  if (pre) {
10701
10985
  const post = nodes[firstEv];
10702
- const path7 = [
10986
+ const path8 = [
10703
10987
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
10704
10988
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
10705
10989
  ];
@@ -10707,8 +10991,8 @@ function checkNeverExfilAfterCred(graph) {
10707
10991
  propertyId: "no-exfil-after-credential",
10708
10992
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10709
10993
  riskLevel: "critical",
10710
- path: path7,
10711
- graph: graphFromPath(nodes, path7, "data", {
10994
+ path: path8,
10995
+ graph: graphFromPath(nodes, path8, "data", {
10712
10996
  property_id: "no-exfil-after-credential",
10713
10997
  property_short: "P5",
10714
10998
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10724,7 +11008,7 @@ function checkNeverExfilAfterCred(graph) {
10724
11008
  if (!isCredNode(nodes[i])) continue;
10725
11009
  for (let j = i + 1; j < nodes.length; j++) {
10726
11010
  if (isExfilNode(nodes[j])) {
10727
- const path7 = [
11011
+ const path8 = [
10728
11012
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
10729
11013
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
10730
11014
  ];
@@ -10732,8 +11016,8 @@ function checkNeverExfilAfterCred(graph) {
10732
11016
  propertyId: "no-exfil-after-credential",
10733
11017
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
10734
11018
  riskLevel: "critical",
10735
- path: path7,
10736
- graph: graphFromPath(nodes, path7, "data", {
11019
+ path: path8,
11020
+ graph: graphFromPath(nodes, path8, "data", {
10737
11021
  property_id: "no-exfil-after-credential",
10738
11022
  property_short: "P5",
10739
11023
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -10892,13 +11176,13 @@ function checkSensitiveDataAggregation(graph) {
10892
11176
  if (!isExfilNode(n)) continue;
10893
11177
  const srcs = sourcesFor(i);
10894
11178
  if (srcs.size >= 2) {
10895
- const path7 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11179
+ const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10896
11180
  violations.push({
10897
11181
  propertyId: "sensitive-data-aggregation",
10898
11182
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
10899
11183
  riskLevel: "critical",
10900
- path: path7,
10901
- graph: graphFromPath(nodes, path7, "next", {
11184
+ path: path8,
11185
+ graph: graphFromPath(nodes, path8, "next", {
10902
11186
  property_id: "sensitive-data-aggregation",
10903
11187
  property_short: "P8",
10904
11188
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -11357,11 +11641,11 @@ var init_stateful = __esm({
11357
11641
  }
11358
11642
  }
11359
11643
  chainPath(stages) {
11360
- const path7 = [];
11644
+ const path8 = [];
11361
11645
  let want = stages[0];
11362
11646
  for (const n of this.nodes_) {
11363
11647
  if (n.stage === want) {
11364
- path7.push({
11648
+ path8.push({
11365
11649
  sessionId: n.sessionId,
11366
11650
  seq: n.seq,
11367
11651
  stage: n.stage,
@@ -11377,12 +11661,12 @@ var init_stateful = __esm({
11377
11661
  }
11378
11662
  }
11379
11663
  }
11380
- return path7;
11664
+ return path8;
11381
11665
  }
11382
11666
  /** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
11383
11667
  buildChainGraph(stages, chainId) {
11384
- const path7 = this.chainPath(stages);
11385
- const gNodes = path7.map((p, i) => {
11668
+ const path8 = this.chainPath(stages);
11669
+ const gNodes = path8.map((p, i) => {
11386
11670
  const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
11387
11671
  return {
11388
11672
  session_id: p.sessionId,
@@ -11634,13 +11918,13 @@ var init_stateful = __esm({
11634
11918
 
11635
11919
  // src/engine/formal-engine/chain_state.ts
11636
11920
  import * as fs5 from "fs";
11637
- import * as os2 from "os";
11638
- import * as path5 from "path";
11921
+ import * as os3 from "os";
11922
+ import * as path6 from "path";
11639
11923
  import { createHash as createHash4 } from "crypto";
11640
11924
  function defaultStateDbPath() {
11641
- const dir = process.env.AGENT_MOSS_STATE_DIR || path5.join(os2.homedir(), ".agentmoss");
11925
+ const dir = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
11642
11926
  const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
11643
- return path5.join(dir, `stateful_chains_${tag}.json`);
11927
+ return path6.join(dir, `stateful_chains_${tag}.json`);
11644
11928
  }
11645
11929
  function registerExitFlush(store) {
11646
11930
  if (_exitHookRegistered) return;
@@ -11726,7 +12010,7 @@ var init_chain_state = __esm({
11726
12010
  this._timer = null;
11727
12011
  try {
11728
12012
  this._syncDirtyToData();
11729
- ensurePrivateDir(path5.dirname(this.filePath));
12013
+ ensurePrivateDir(path6.dirname(this.filePath));
11730
12014
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11731
12015
  } catch {
11732
12016
  }
@@ -11749,7 +12033,7 @@ var init_chain_state = __esm({
11749
12033
  }
11750
12034
  try {
11751
12035
  this._syncDirtyToData();
11752
- ensurePrivateDir(path5.dirname(this.filePath));
12036
+ ensurePrivateDir(path6.dirname(this.filePath));
11753
12037
  writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11754
12038
  } catch {
11755
12039
  }
@@ -11817,7 +12101,7 @@ var init_chain_state = __esm({
11817
12101
  _flushNow() {
11818
12102
  this._syncDirtyToData();
11819
12103
  try {
11820
- const _dirOk = ensurePrivateDir(path5.dirname(this.filePath));
12104
+ const _dirOk = ensurePrivateDir(path6.dirname(this.filePath));
11821
12105
  const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
11822
12106
  if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
11823
12107
  } catch (e) {
@@ -12114,7 +12398,7 @@ async function runAnalysis(input) {
12114
12398
  skipLLM = true;
12115
12399
  }
12116
12400
  }
12117
- const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
12401
+ const logicResult = isLogicRulesEnabled() ? runLogicCheck(input, { agentExt }) : null;
12118
12402
  if (logicResult) {
12119
12403
  traceSummary("l2.result", {
12120
12404
  hit: !logicResult.allowed,
@@ -12379,7 +12663,7 @@ var init_coordinator = __esm({
12379
12663
  import { createHash as createHash5 } from "crypto";
12380
12664
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
12381
12665
  import { tmpdir as tmpdir3 } from "os";
12382
- import { join as join16 } from "path";
12666
+ import { join as join17 } from "path";
12383
12667
  function cacheDir() {
12384
12668
  return cacheDirOverride ?? CACHE_DIR;
12385
12669
  }
@@ -12387,7 +12671,7 @@ function safeCacheDir() {
12387
12671
  const dir = cacheDir();
12388
12672
  if (ensurePrivateDir(dir)) return dir;
12389
12673
  try {
12390
- const fallback = join16(getDataRoot(), "policy_cache");
12674
+ const fallback = join17(getDataRoot(), "policy_cache");
12391
12675
  if (ensurePrivateDir(fallback)) {
12392
12676
  console.warn(`[AgentMoss] \u7F13\u5B58\u76EE\u5F55 ${dir} \u4E0D\u5B89\u5168\uFF08\u88AB\u5176\u4ED6\u7528\u6237\u62E5\u6709\u6216\u4E3A\u7B26\u53F7\u94FE\u63A5\uFF09\uFF0C\u5DF2\u56DE\u9000\u5230 ${fallback}`);
12393
12677
  return fallback;
@@ -12408,7 +12692,7 @@ var init_policy_cache = __esm({
12408
12692
  init_security_policy();
12409
12693
  init_paths();
12410
12694
  init_config();
12411
- CACHE_DIR = join16(tmpdir3(), "agent_moss_policy_cache");
12695
+ CACHE_DIR = join17(tmpdir3(), "agent_moss_policy_cache");
12412
12696
  cacheDirOverride = null;
12413
12697
  PolicyCache = class {
12414
12698
  // Map 的插入序即 LRU 序(get 时重新 set 到末尾)
@@ -12423,7 +12707,7 @@ var init_policy_cache = __esm({
12423
12707
  cacheFilePath(sessionId, promptSession) {
12424
12708
  const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
12425
12709
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12426
- return join16(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
12710
+ return join17(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
12427
12711
  }
12428
12712
  /** 取缓存:内存 → 文件;未命中返回 null。 */
12429
12713
  get(sessionId, promptSession) {
@@ -12454,7 +12738,7 @@ var init_policy_cache = __esm({
12454
12738
  try {
12455
12739
  const dir = safeCacheDir();
12456
12740
  const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12457
- if (!ensurePrivateDir(join16(dir, sub))) return;
12741
+ if (!ensurePrivateDir(join17(dir, sub))) return;
12458
12742
  writePrivateText(file, policy);
12459
12743
  } catch {
12460
12744
  }
@@ -12480,12 +12764,12 @@ var init_policy_cache = __esm({
12480
12764
  if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
12481
12765
  }
12482
12766
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12483
- const dir = join16(cacheDir(), safeSessionId);
12767
+ const dir = join17(cacheDir(), safeSessionId);
12484
12768
  try {
12485
12769
  if (existsSync17(dir)) {
12486
12770
  for (const f of readdirSync5(dir)) {
12487
12771
  try {
12488
- unlinkSync4(join16(dir, f));
12772
+ unlinkSync4(join17(dir, f));
12489
12773
  } catch {
12490
12774
  }
12491
12775
  }
@@ -12499,9 +12783,9 @@ var init_policy_cache = __esm({
12499
12783
  try {
12500
12784
  if (existsSync17(cacheDir())) {
12501
12785
  for (const sessionDir of readdirSync5(cacheDir())) {
12502
- const dir = join16(cacheDir(), sessionDir);
12786
+ const dir = join17(cacheDir(), sessionDir);
12503
12787
  try {
12504
- for (const f of readdirSync5(dir)) unlinkSync4(join16(dir, f));
12788
+ for (const f of readdirSync5(dir)) unlinkSync4(join17(dir, f));
12505
12789
  rmdirSync(dir);
12506
12790
  } catch {
12507
12791
  }
@@ -12599,7 +12883,7 @@ __export(analyzer_exports, {
12599
12883
  });
12600
12884
  import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
12601
12885
  import { tmpdir as tmpdir4 } from "os";
12602
- import { join as join17, resolve as resolve11 } from "path";
12886
+ import { join as join18, resolve as resolve11 } from "path";
12603
12887
  import { parse as parseToml } from "smol-toml";
12604
12888
  function _setPolicyOutputDirForTest(dir) {
12605
12889
  policyOutputDirOverride = dir;
@@ -12616,7 +12900,7 @@ function savePolicyToFile(sessionId, policyToml) {
12616
12900
  return null;
12617
12901
  }
12618
12902
  const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
12619
- const filepath = join17(outDir, `${safeName}.toml`);
12903
+ const filepath = join18(outDir, `${safeName}.toml`);
12620
12904
  writePrivateText(filepath, policyToml);
12621
12905
  return filepath;
12622
12906
  } catch (err) {
@@ -12832,7 +13116,7 @@ var init_analyzer = __esm({
12832
13116
  init_asset_dir();
12833
13117
  init_token_stats();
12834
13118
  init_logging();
12835
- POLICY_OUTPUT_DIR = join17(tmpdir4(), "agent_moss");
13119
+ POLICY_OUTPUT_DIR = join18(tmpdir4(), "agent_moss");
12836
13120
  policyOutputDirOverride = null;
12837
13121
  DEFAULT_READONLY_POLICY = `landlock_optional = false
12838
13122
  mount_isolation_fallback = false
@@ -13070,8 +13354,8 @@ var init_pattern_miner = __esm({
13070
13354
 
13071
13355
  // src/agent-gate-reader.ts
13072
13356
  import * as fs7 from "fs";
13073
- import * as os3 from "os";
13074
- import * as path6 from "path";
13357
+ import * as os4 from "os";
13358
+ import * as path7 from "path";
13075
13359
  function normalizeAction(row) {
13076
13360
  return {
13077
13361
  actionType: String(row.action_type || row.tool_name || row.name || ""),
@@ -13084,7 +13368,7 @@ function readJsonDir(dirPath, limit = 1e5) {
13084
13368
  const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
13085
13369
  for (const f of files.slice(-200)) {
13086
13370
  const sid = f.replace(/\.json$/, "");
13087
- const raw = fs7.readFileSync(path6.join(dirPath, f), "utf-8");
13371
+ const raw = fs7.readFileSync(path7.join(dirPath, f), "utf-8");
13088
13372
  const arr = JSON.parse(raw);
13089
13373
  if (!Array.isArray(arr)) continue;
13090
13374
  for (const item of arr) {
@@ -13152,7 +13436,7 @@ function loadAgentGateSessions(dbPath = "") {
13152
13436
  }
13153
13437
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
13154
13438
  if (sql.length > 0) return sql;
13155
- const jsonDefault = path6.join(os3.homedir(), ".local", "share", "agent_gate", "tool_calls");
13439
+ const jsonDefault = path7.join(os4.homedir(), ".local", "share", "agent_gate", "tool_calls");
13156
13440
  return readJsonDir(jsonDefault);
13157
13441
  }
13158
13442
  var DEFAULT_AGENTGATE_SQLITE;
@@ -13161,8 +13445,8 @@ var init_agent_gate_reader = __esm({
13161
13445
  "use strict";
13162
13446
  init_esm_shims();
13163
13447
  init_esm_require();
13164
- DEFAULT_AGENTGATE_SQLITE = path6.join(
13165
- os3.homedir(),
13448
+ DEFAULT_AGENTGATE_SQLITE = path7.join(
13449
+ os4.homedir(),
13166
13450
  ".local",
13167
13451
  "share",
13168
13452
  "agent_gate",
@@ -13302,7 +13586,7 @@ var init_runtime_stats = __esm({
13302
13586
 
13303
13587
  // src/routes.ts
13304
13588
  import { randomBytes as randomBytes2 } from "crypto";
13305
- import { join as join19, dirname as dirname12 } from "path";
13589
+ import { join as join20, dirname as dirname12 } from "path";
13306
13590
  import { fileURLToPath as fileURLToPath10 } from "url";
13307
13591
  async function healthRoute(c) {
13308
13592
  const metrics = {};
@@ -13701,7 +13985,7 @@ function getBrainRuleStore() {
13701
13985
  return new BrainRuleStore();
13702
13986
  }
13703
13987
  function getBrainSkillManager() {
13704
- const dir = resolveAssetDir(__dirname9, "skills") ?? join19(__dirname9, "..", "..", "agent_moss", "skills");
13988
+ const dir = resolveAssetDir(__dirname9, "skills") ?? join20(__dirname9, "..", "..", "agent_moss", "skills");
13705
13989
  return new BrainSkillManager(dir);
13706
13990
  }
13707
13991
  async function brainRulesRoute(c) {
@@ -13821,7 +14105,7 @@ var init_routes = __esm({
13821
14105
  import { Hono } from "hono";
13822
14106
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
13823
14107
  import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
13824
- import { join as join20, dirname as dirname13 } from "path";
14108
+ import { join as join21, dirname as dirname13 } from "path";
13825
14109
  import { fileURLToPath as fileURLToPath11 } from "url";
13826
14110
  function getConsoleToken() {
13827
14111
  return process.env[CONSOLE_TOKEN_ENV] || "";
@@ -13863,7 +14147,7 @@ function createConsoleRouter() {
13863
14147
  console2.use("/api/*", authMiddleware());
13864
14148
  console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
13865
14149
  const serveIndex = (c) => {
13866
- const indexFile = join20(STATIC_DIR, "index.html");
14150
+ const indexFile = join21(STATIC_DIR, "index.html");
13867
14151
  if (existsSync20(indexFile)) {
13868
14152
  return c.html(readFileSync20(indexFile, "utf-8"));
13869
14153
  }
@@ -14060,11 +14344,11 @@ function createConsoleRouter() {
14060
14344
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
14061
14345
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
14062
14346
  }
14063
- const userPath = join20(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14347
+ const userPath = join21(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
14064
14348
  const builtinDir = resolveAssetDir(__dirname10, "skills");
14065
14349
  const candidates = [
14066
14350
  ...isRuntimeConfigDisabled() ? [] : [userPath],
14067
- builtinDir ? join20(builtinDir, `${skillId}.md`) : ""
14351
+ builtinDir ? join21(builtinDir, `${skillId}.md`) : ""
14068
14352
  ].filter(Boolean);
14069
14353
  for (const p of candidates) {
14070
14354
  if (existsSync20(p)) {
@@ -14202,7 +14486,7 @@ var init_router = __esm({
14202
14486
  init_asset_dir();
14203
14487
  init_rules_mode();
14204
14488
  __dirname10 = dirname13(fileURLToPath11(import.meta.url));
14205
- STATIC_DIR = join20(__dirname10, "static");
14489
+ STATIC_DIR = join21(__dirname10, "static");
14206
14490
  CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
14207
14491
  }
14208
14492
  });
@@ -14322,7 +14606,7 @@ function createApp() {
14322
14606
  startLoopMonitor();
14323
14607
  const limiter = new RateLimiter(rateLimitQps());
14324
14608
  app.use("*", async (c, next) => {
14325
- const path7 = new URL(c.req.url).pathname;
14609
+ const path8 = new URL(c.req.url).pathname;
14326
14610
  const method = c.req.method.toUpperCase();
14327
14611
  if (method === "OPTIONS") return next();
14328
14612
  const maxBody = maxBodyBytes();
@@ -14336,16 +14620,16 @@ function createApp() {
14336
14620
  if (originCheckEnabled()) {
14337
14621
  const origin = c.req.header("origin") || "";
14338
14622
  if (origin && !originAllowed(origin, c.req.header("host") || "")) {
14339
- console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path7}`);
14623
+ console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path8}`);
14340
14624
  return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
14341
14625
  }
14342
14626
  }
14343
- const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path7);
14344
- const isPublicPage = !path7.startsWith("/console/api") && (path7 === "/console" || path7.startsWith("/console/"));
14627
+ const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path8);
14628
+ const isPublicPage = !path8.startsWith("/console/api") && (path8 === "/console" || path8.startsWith("/console/"));
14345
14629
  if (!okAuth && !isPublicPage) {
14346
14630
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
14347
14631
  }
14348
- if (limiter.enabled && path7.startsWith("/api/")) {
14632
+ if (limiter.enabled && path8.startsWith("/api/")) {
14349
14633
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
14350
14634
  if (!limiter.allow(key)) {
14351
14635
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
@@ -14379,7 +14663,7 @@ function createApp() {
14379
14663
  return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
14380
14664
  }
14381
14665
  }
14382
- const pool = poolOf(path7);
14666
+ const pool = poolOf(path8);
14383
14667
  if (!take(`pool:${pool}`, poolLimit(pool))) {
14384
14668
  const qkey = principal ? "p:" + principalHash(principal) : "c:local";
14385
14669
  const [qn, abusive] = noteQueueReject(qkey);
@@ -14643,17 +14927,17 @@ __export(rules_tools_exports, {
14643
14927
  templateSourceDir: () => templateSourceDir
14644
14928
  });
14645
14929
  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";
14930
+ import { dirname as dirname14, join as join22 } from "path";
14647
14931
  import { fileURLToPath as fileURLToPath12 } from "url";
14648
14932
  function initRulesDir(targetDir, opts = {}) {
14649
14933
  mkdirSync9(targetDir, { recursive: true });
14650
14934
  const written = [];
14651
- const extraPath = join21(targetDir, EXTRA_FILENAME);
14935
+ const extraPath = join22(targetDir, EXTRA_FILENAME);
14652
14936
  if (opts.force || !existsSync22(extraPath)) {
14653
14937
  writeFileSync7(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
14654
14938
  written.push(extraPath);
14655
14939
  }
14656
- const samplePath = join21(targetDir, OVERRIDE_FILENAME);
14940
+ const samplePath = join22(targetDir, OVERRIDE_FILENAME);
14657
14941
  if (opts.force || !existsSync22(samplePath)) {
14658
14942
  let payload = OVERRIDE_TEMPLATE;
14659
14943
  if (opts.withBuiltin) {
@@ -14672,8 +14956,8 @@ function initRulesDir(targetDir, opts = {}) {
14672
14956
  writeFileSync7(samplePath, JSON.stringify(payload, null, 2), "utf-8");
14673
14957
  written.push(samplePath);
14674
14958
  }
14675
- const readmeSrc = join21(templateSourceDir(), "README.md");
14676
- const readmeDst = join21(targetDir, "README.md");
14959
+ const readmeSrc = join22(templateSourceDir(), "README.md");
14960
+ const readmeDst = join22(targetDir, "README.md");
14677
14961
  if (existsSync22(readmeSrc) && (opts.force || !existsSync22(readmeDst))) {
14678
14962
  writeFileSync7(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
14679
14963
  written.push(readmeDst);
@@ -14681,7 +14965,7 @@ function initRulesDir(targetDir, opts = {}) {
14681
14965
  return written;
14682
14966
  }
14683
14967
  function templateSourceDir() {
14684
- const cands = [join21(__dirname11, "data", "rules_template"), join21(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
14968
+ const cands = [join22(__dirname11, "data", "rules_template"), join22(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
14685
14969
  for (const c of cands) if (existsSync22(c)) return c;
14686
14970
  return cands[0];
14687
14971
  }
@@ -14690,7 +14974,7 @@ function templateFiles(dirs) {
14690
14974
  for (const d of dirs) {
14691
14975
  try {
14692
14976
  for (const name of readdirSync7(d)) {
14693
- if (name.endsWith(".json.\u793A\u4F8B")) out.push(join21(d, name));
14977
+ if (name.endsWith(".json.\u793A\u4F8B")) out.push(join22(d, name));
14694
14978
  }
14695
14979
  } catch {
14696
14980
  }
@@ -14895,7 +15179,7 @@ async function main() {
14895
15179
  process.exit(1);
14896
15180
  }
14897
15181
  const fs8 = await import("fs");
14898
- const path7 = await import("path");
15182
+ const path8 = await import("path");
14899
15183
  const useJson = args.includes("--json");
14900
15184
  const osType = process.platform === "win32" ? "windows" : "linux";
14901
15185
  const isFile = fs8.existsSync(target) && fs8.statSync(target).isFile();
@@ -14914,7 +15198,7 @@ async function main() {
14914
15198
  }
14915
15199
  process.exit(await analyzeRawCommand(target, useJson));
14916
15200
  }
14917
- const filePath = path7.resolve(target);
15201
+ const filePath = path8.resolve(target);
14918
15202
  const data = JSON.parse(fs8.readFileSync(filePath, "utf-8"));
14919
15203
  const { analyze: analyze2 } = await Promise.resolve().then(() => (init_analyzer(), analyzer_exports));
14920
15204
  const sessionId = String(data.session_id || "unknown");
@@ -14926,11 +15210,11 @@ async function main() {
14926
15210
  fs8.mkdirSync(outDir, { recursive: true });
14927
15211
  const safeSession = sessionId.replace(/\//g, "_");
14928
15212
  if (result.decision === "Allow") {
14929
- const policyPath = path7.join(outDir, `${safeSession}_policy.toml`);
15213
+ const policyPath = path8.join(outDir, `${safeSession}_policy.toml`);
14930
15214
  fs8.writeFileSync(policyPath, result.policy || "", "utf-8");
14931
15215
  console.log(`Policy written to ${policyPath}`);
14932
15216
  } else {
14933
- const denyPath = path7.join(outDir, `${safeSession}_deny_reason.txt`);
15217
+ const denyPath = path8.join(outDir, `${safeSession}_deny_reason.txt`);
14934
15218
  fs8.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
14935
15219
  console.log(`Deny reason written to ${denyPath}`);
14936
15220
  }
@@ -15021,7 +15305,7 @@ async function main() {
15021
15305
  const enable = args.includes("--enable");
15022
15306
  const { execSync } = await import("child_process");
15023
15307
  const fs8 = await import("fs");
15024
- const path7 = await import("path");
15308
+ const path8 = await import("path");
15025
15309
  const { fileURLToPath: fileURLToPath14 } = await import("url");
15026
15310
  if (process.getuid?.() !== 0) {
15027
15311
  try {
@@ -15038,17 +15322,17 @@ async function main() {
15038
15322
  process.exit(0);
15039
15323
  }
15040
15324
  const __filename7 = fileURLToPath14(import.meta.url);
15041
- const __dirname12 = path7.dirname(__filename7);
15042
- let srcPath = path7.join(__dirname12, "data", "agent_moss.service");
15325
+ const __dirname12 = path8.dirname(__filename7);
15326
+ let srcPath = path8.join(__dirname12, "data", "agent_moss.service");
15043
15327
  if (!fs8.existsSync(srcPath)) {
15044
- srcPath = path7.join(__dirname12, "..", "src", "data", "agent_moss.service");
15328
+ srcPath = path8.join(__dirname12, "..", "src", "data", "agent_moss.service");
15045
15329
  }
15046
15330
  if (!fs8.existsSync(srcPath)) {
15047
15331
  console.error("\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230 agent_moss.service \u6A21\u677F\u6587\u4EF6");
15048
15332
  process.exit(1);
15049
15333
  }
15050
15334
  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")}`;
15335
+ const binPath = which || `${process.execPath} ${path8.join(__dirname12, "cli.js")}`;
15052
15336
  let content = fs8.readFileSync(srcPath, "utf-8");
15053
15337
  content = content.replace("__AGENT_MOSS_BIN__", binPath);
15054
15338
  const dst = "/etc/systemd/system/agent-moss.service";