@kenhkl/agent-moss 0.17.24 → 0.17.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/opendesk/rules.json +5 -0
- package/dist/cli.js +830 -273
- package/dist/engine/coordinator.js +741 -184
- package/dist/rules/heuristic_rules.json +44 -1
- package/dist/rules/l2_rules.json +4 -2
- package/dist/rules/logic_rules.json +65 -1
- package/dist/server.js +796 -239
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -401,22 +401,22 @@ function loadToolRegistry() {
|
|
|
401
401
|
data.tools = tools;
|
|
402
402
|
return data;
|
|
403
403
|
}
|
|
404
|
-
function scanStructEntry(cat, value,
|
|
404
|
+
function scanStructEntry(cat, value, path8) {
|
|
405
405
|
if (cat === "skills") {
|
|
406
406
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
407
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
407
|
+
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`);
|
|
408
408
|
return null;
|
|
409
409
|
}
|
|
410
410
|
const out = {};
|
|
411
411
|
for (const [skCat, skills] of Object.entries(value)) {
|
|
412
412
|
if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
|
|
413
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
413
|
+
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`);
|
|
414
414
|
continue;
|
|
415
415
|
}
|
|
416
416
|
const keep = {};
|
|
417
417
|
for (const [name, kws] of Object.entries(skills)) {
|
|
418
418
|
if (Array.isArray(kws)) keep[name] = kws;
|
|
419
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
419
|
+
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`);
|
|
420
420
|
}
|
|
421
421
|
if (Object.keys(keep).length > 0) out[skCat] = keep;
|
|
422
422
|
}
|
|
@@ -424,37 +424,37 @@ function scanStructEntry(cat, value, path7) {
|
|
|
424
424
|
}
|
|
425
425
|
if (cat === "ltl_rules") {
|
|
426
426
|
if (!Array.isArray(value)) {
|
|
427
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
427
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
428
428
|
return null;
|
|
429
429
|
}
|
|
430
430
|
const keep = value.filter((r) => r && typeof r === "object" && r.id);
|
|
431
431
|
if (keep.length !== value.length) {
|
|
432
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
432
|
+
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`);
|
|
433
433
|
}
|
|
434
434
|
return keep.length > 0 ? keep : null;
|
|
435
435
|
}
|
|
436
436
|
if (cat === "tools") {
|
|
437
437
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
438
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
438
|
+
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`);
|
|
439
439
|
return null;
|
|
440
440
|
}
|
|
441
441
|
const keep = {};
|
|
442
442
|
for (const [k, v] of Object.entries(value)) {
|
|
443
443
|
if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
|
|
444
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
444
|
+
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
445
445
|
}
|
|
446
446
|
return Object.keys(keep).length > 0 ? keep : null;
|
|
447
447
|
}
|
|
448
448
|
return null;
|
|
449
449
|
}
|
|
450
|
-
function scanRulesFile(
|
|
450
|
+
function scanRulesFile(path8, kind) {
|
|
451
451
|
const out = {};
|
|
452
452
|
const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
|
|
453
453
|
let parsed;
|
|
454
454
|
try {
|
|
455
|
-
parsed = JSON.parse(readFileSync2(
|
|
455
|
+
parsed = JSON.parse(readFileSync2(path8, "utf-8"));
|
|
456
456
|
} catch (e) {
|
|
457
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
457
|
+
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}`);
|
|
458
458
|
return out;
|
|
459
459
|
}
|
|
460
460
|
const classifyFlat = (r) => {
|
|
@@ -478,44 +478,44 @@ function scanRulesFile(path7, kind) {
|
|
|
478
478
|
}
|
|
479
479
|
if (flatBad > 0) {
|
|
480
480
|
console.warn(
|
|
481
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
481
|
+
`[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`
|
|
482
482
|
);
|
|
483
483
|
}
|
|
484
484
|
} else {
|
|
485
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
485
|
+
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`);
|
|
486
486
|
return out;
|
|
487
487
|
}
|
|
488
488
|
for (const [cat, rules] of pairs) {
|
|
489
489
|
if (String(cat).startsWith("_")) continue;
|
|
490
490
|
if (STRUCT_KEYS.includes(cat)) {
|
|
491
|
-
const got = scanStructEntry(cat, rules,
|
|
491
|
+
const got = scanStructEntry(cat, rules, path8);
|
|
492
492
|
if (got !== null) out[cat] = got;
|
|
493
493
|
continue;
|
|
494
494
|
}
|
|
495
495
|
const required = EXTRA_CATEGORIES[cat];
|
|
496
496
|
if (!required) {
|
|
497
497
|
console.warn(
|
|
498
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
498
|
+
`[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`
|
|
499
499
|
);
|
|
500
500
|
continue;
|
|
501
501
|
}
|
|
502
502
|
if (rules && typeof rules === "object" && !Array.isArray(rules)) {
|
|
503
503
|
console.error(
|
|
504
|
-
`[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${
|
|
504
|
+
`[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
|
|
505
505
|
\u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
|
|
506
506
|
\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`
|
|
507
507
|
);
|
|
508
508
|
continue;
|
|
509
509
|
}
|
|
510
510
|
if (!Array.isArray(rules)) {
|
|
511
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
511
|
+
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`);
|
|
512
512
|
continue;
|
|
513
513
|
}
|
|
514
514
|
const items = [];
|
|
515
515
|
for (const r of rules) {
|
|
516
516
|
if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
|
|
517
517
|
console.warn(
|
|
518
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
518
|
+
`[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`
|
|
519
519
|
);
|
|
520
520
|
continue;
|
|
521
521
|
}
|
|
@@ -525,7 +525,7 @@ function scanRulesFile(path7, kind) {
|
|
|
525
525
|
}
|
|
526
526
|
if (Object.keys(out).length > 0) {
|
|
527
527
|
console.info(
|
|
528
|
-
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${
|
|
528
|
+
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path8}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
|
|
529
529
|
);
|
|
530
530
|
}
|
|
531
531
|
return out;
|
|
@@ -795,10 +795,10 @@ function readExplicitToken() {
|
|
|
795
795
|
if (tok) return tok;
|
|
796
796
|
const fdTok = readFdToken();
|
|
797
797
|
if (fdTok) return fdTok;
|
|
798
|
-
const
|
|
799
|
-
if (
|
|
798
|
+
const path8 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
|
|
799
|
+
if (path8) {
|
|
800
800
|
try {
|
|
801
|
-
return readFileSync4(
|
|
801
|
+
return readFileSync4(path8, "utf-8").trim();
|
|
802
802
|
} catch {
|
|
803
803
|
return "";
|
|
804
804
|
}
|
|
@@ -806,23 +806,23 @@ function readExplicitToken() {
|
|
|
806
806
|
return "";
|
|
807
807
|
}
|
|
808
808
|
function ensureAutoToken() {
|
|
809
|
-
const
|
|
809
|
+
const path8 = autoTokenPath();
|
|
810
810
|
try {
|
|
811
|
-
if (existsSync3(
|
|
812
|
-
const tok2 = readFileSync4(
|
|
811
|
+
if (existsSync3(path8) && !lstatSync(path8).isSymbolicLink()) {
|
|
812
|
+
const tok2 = readFileSync4(path8, "utf-8").trim();
|
|
813
813
|
if (tok2) {
|
|
814
814
|
try {
|
|
815
|
-
chmodSync(
|
|
815
|
+
chmodSync(path8, 384);
|
|
816
816
|
} catch {
|
|
817
817
|
}
|
|
818
818
|
return tok2;
|
|
819
819
|
}
|
|
820
820
|
}
|
|
821
821
|
const tok = randomBytes(32).toString("base64url");
|
|
822
|
-
ensurePrivateDir(dirname2(
|
|
823
|
-
if (!writePrivateText(
|
|
822
|
+
ensurePrivateDir(dirname2(path8));
|
|
823
|
+
if (!writePrivateText(path8, tok + "\n")) return "";
|
|
824
824
|
console.warn(
|
|
825
|
-
`[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${
|
|
825
|
+
`[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`
|
|
826
826
|
);
|
|
827
827
|
return tok;
|
|
828
828
|
} catch (e) {
|
|
@@ -895,16 +895,16 @@ function constEq(a, b) {
|
|
|
895
895
|
if (ba.length !== bb.length) return false;
|
|
896
896
|
return timingSafeEqual(ba, bb);
|
|
897
897
|
}
|
|
898
|
-
function checkRequestAuth(headers,
|
|
898
|
+
function checkRequestAuth(headers, path8) {
|
|
899
899
|
if (authMode() === AUTH_MODE_OFF) return [true, ""];
|
|
900
|
-
const isHealth = HEALTH_PATHS.includes(
|
|
900
|
+
const isHealth = HEALTH_PATHS.includes(path8.replace(/\/+$/, ""));
|
|
901
901
|
const [gt0, agents, err] = resolveAuth();
|
|
902
902
|
if (err) return isHealth ? [true, ""] : [false, ""];
|
|
903
903
|
if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
|
|
904
904
|
if (isHealth) return [true, ""];
|
|
905
905
|
const tok = bearer(headers);
|
|
906
906
|
if (!tok) return [false, ""];
|
|
907
|
-
if (
|
|
907
|
+
if (path8.startsWith("/console/api")) {
|
|
908
908
|
const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
|
|
909
909
|
if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
|
|
910
910
|
}
|
|
@@ -923,8 +923,8 @@ function bindAgent(principal, agentId) {
|
|
|
923
923
|
if (!agentId) return [true, bound];
|
|
924
924
|
return [bound === agentId, bound];
|
|
925
925
|
}
|
|
926
|
-
function principalOf(headers,
|
|
927
|
-
const [ok, principal] = checkRequestAuth(headers,
|
|
926
|
+
function principalOf(headers, path8 = "") {
|
|
927
|
+
const [ok, principal] = checkRequestAuth(headers, path8);
|
|
928
928
|
return ok ? principal : "";
|
|
929
929
|
}
|
|
930
930
|
function principalHash(principal) {
|
|
@@ -1181,11 +1181,11 @@ function errorDetailMode() {
|
|
|
1181
1181
|
function maxBodyBytes() {
|
|
1182
1182
|
return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
|
|
1183
1183
|
}
|
|
1184
|
-
function poolOf(
|
|
1185
|
-
if (
|
|
1186
|
-
if (
|
|
1187
|
-
if (
|
|
1188
|
-
if (
|
|
1184
|
+
function poolOf(path8) {
|
|
1185
|
+
if (path8 === "/api/v1/analyze" || path8.startsWith("/api/v1/analyze/")) return "biz";
|
|
1186
|
+
if (path8 === "/api/v1/review" || path8.startsWith("/api/v1/review/")) return "review";
|
|
1187
|
+
if (path8 === "/console" || path8.startsWith("/console/") || path8.startsWith("/api/v1/brain")) return "ops";
|
|
1188
|
+
if (path8 === "/api/v1/health") return "health";
|
|
1189
1189
|
return "other";
|
|
1190
1190
|
}
|
|
1191
1191
|
function poolLimit(name) {
|
|
@@ -1472,6 +1472,8 @@ var init_platform_traits = __esm({
|
|
|
1472
1472
|
|
|
1473
1473
|
// src/engine/logic-rules.ts
|
|
1474
1474
|
import * as fs from "fs";
|
|
1475
|
+
import * as path2 from "path";
|
|
1476
|
+
import * as os from "os";
|
|
1475
1477
|
function hasExecBypassChain(actionDetail) {
|
|
1476
1478
|
const execAfter = "&&|\\|\\||;|\\n|\\|";
|
|
1477
1479
|
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);
|
|
@@ -1498,7 +1500,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
|
|
|
1498
1500
|
os: String(sp.os || "linux").toLowerCase()
|
|
1499
1501
|
}));
|
|
1500
1502
|
}
|
|
1501
|
-
function _scopeOf(
|
|
1503
|
+
function _scopeOf(os5, path8) {
|
|
1502
1504
|
if (!_scopeIndex) {
|
|
1503
1505
|
_scopeIndex = /* @__PURE__ */ new Map();
|
|
1504
1506
|
for (const sp of loadL1().sensitive_path_access || []) {
|
|
@@ -1506,7 +1508,7 @@ function _scopeOf(os4, path7) {
|
|
|
1506
1508
|
if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
|
|
1507
1509
|
}
|
|
1508
1510
|
}
|
|
1509
|
-
return _scopeIndex.get(`${String(
|
|
1511
|
+
return _scopeIndex.get(`${String(os5 || "linux").toLowerCase()}|${path8}`) || "root";
|
|
1510
1512
|
}
|
|
1511
1513
|
function getSensitivePathsForOs(osType) {
|
|
1512
1514
|
const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
|
|
@@ -1548,6 +1550,188 @@ function getSensitivePathsForOsBuiltin(osType) {
|
|
|
1548
1550
|
}
|
|
1549
1551
|
return { root: ROOT_SENSITIVE_PATHS, home: HOME_SENSITIVE_PATHS, credential: CREDENTIAL_PATHS };
|
|
1550
1552
|
}
|
|
1553
|
+
function declaredWritePaths(actionDetailRaw, osType) {
|
|
1554
|
+
const m = actionDetailRaw.match(DECLARED_WRITE_PATH_RE);
|
|
1555
|
+
if (m) return [m[1]];
|
|
1556
|
+
const j = actionDetailRaw.match(DECLARED_WRITE_PATH_JSON_RE);
|
|
1557
|
+
if (j) return [j[1]];
|
|
1558
|
+
return extractFilePaths(actionDetailRaw, osType).slice(0, 1);
|
|
1559
|
+
}
|
|
1560
|
+
function normalizePathForCompare(p, cwd) {
|
|
1561
|
+
if (!p) return p;
|
|
1562
|
+
let expanded = p;
|
|
1563
|
+
if (expanded === "~" || expanded.startsWith("~/") || expanded.startsWith("~\\")) {
|
|
1564
|
+
expanded = os.homedir() + expanded.slice(1);
|
|
1565
|
+
}
|
|
1566
|
+
if (!path2.isAbsolute(expanded) && cwd) expanded = path2.join(cwd, expanded);
|
|
1567
|
+
return path2.normalize(expanded);
|
|
1568
|
+
}
|
|
1569
|
+
function pathIsSameOrUnder(p, base) {
|
|
1570
|
+
if (!p || !base) return false;
|
|
1571
|
+
if (p === base) return true;
|
|
1572
|
+
return p.startsWith(base.replace(/[\\/]+$/, "") + path2.sep);
|
|
1573
|
+
}
|
|
1574
|
+
function isProtectedWritePath(p) {
|
|
1575
|
+
if (!p) return false;
|
|
1576
|
+
if (PROTECTED_WRITE_PREFIXES.some((prefix) => p.startsWith(prefix))) return true;
|
|
1577
|
+
const home = os.homedir();
|
|
1578
|
+
if (home && (p === home || p.startsWith(home + path2.sep))) {
|
|
1579
|
+
const rel = p.slice(home.length).replace(/^[\\/]+/, "");
|
|
1580
|
+
const first = rel.split(/[\\/]/)[0] || "";
|
|
1581
|
+
return PROTECTED_HOME_ENTRIES.has(first);
|
|
1582
|
+
}
|
|
1583
|
+
return false;
|
|
1584
|
+
}
|
|
1585
|
+
function historyCommandText(histDetailRaw) {
|
|
1586
|
+
const text = histDetailRaw.trim();
|
|
1587
|
+
if (text.startsWith("{")) {
|
|
1588
|
+
try {
|
|
1589
|
+
const obj = JSON.parse(text);
|
|
1590
|
+
if (obj && typeof obj === "object") {
|
|
1591
|
+
for (const key of ["command", "cmd"]) {
|
|
1592
|
+
if (typeof obj[key] === "string" && obj[key].trim()) return obj[key];
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
} catch {
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
return histDetailRaw;
|
|
1599
|
+
}
|
|
1600
|
+
function parseHeadTailLimit(seg) {
|
|
1601
|
+
const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
|
|
1602
|
+
if (firstWord !== "head" && firstWord !== "tail") return null;
|
|
1603
|
+
const m = seg.match(HEAD_TAIL_LIMIT_RE);
|
|
1604
|
+
return m ? Number(m[1]) : 10;
|
|
1605
|
+
}
|
|
1606
|
+
function parseHeadTailLimitForPipeline(segments) {
|
|
1607
|
+
for (const rawSeg of segments) {
|
|
1608
|
+
const seg = rawSeg.trim();
|
|
1609
|
+
if (!seg) continue;
|
|
1610
|
+
if (seg.startsWith("head") || seg.startsWith("tail")) return parseHeadTailLimit(seg);
|
|
1611
|
+
}
|
|
1612
|
+
return null;
|
|
1613
|
+
}
|
|
1614
|
+
function historyReadCoverage(histType, histDetailRaw, readKeywords, writeKeywords) {
|
|
1615
|
+
const full = /* @__PURE__ */ new Set();
|
|
1616
|
+
const partial = /* @__PURE__ */ new Map();
|
|
1617
|
+
const addPartial = (paths, upto) => {
|
|
1618
|
+
for (const p of paths) {
|
|
1619
|
+
if (partial.has(p)) {
|
|
1620
|
+
const old = partial.get(p);
|
|
1621
|
+
partial.set(p, old == null || upto == null ? null : Math.max(old, upto));
|
|
1622
|
+
} else {
|
|
1623
|
+
partial.set(p, upto);
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
if (writeKeywords.some((kw) => histType.includes(kw))) return { full, partial };
|
|
1628
|
+
if (histType === "bash" || histType === "executebash" || histType === "terminal-executebash") {
|
|
1629
|
+
const segments = splitCommandSegments(historyCommandText(histDetailRaw));
|
|
1630
|
+
const words = segments.map((s) => s.trim().split(/\s+/)[0]?.toLowerCase() || "").filter(Boolean);
|
|
1631
|
+
const hasTruncatingPipe = words.some((w) => SHELL_TRUNCATING_CMDS.has(w));
|
|
1632
|
+
for (const rawSeg of segments) {
|
|
1633
|
+
const seg = rawSeg.trim();
|
|
1634
|
+
if (!seg) continue;
|
|
1635
|
+
const firstWord = seg.split(/\s+/)[0]?.toLowerCase() || "";
|
|
1636
|
+
const paths = extractFilePaths(seg);
|
|
1637
|
+
if (paths.length === 0) continue;
|
|
1638
|
+
if (SHELL_FULL_READ_CMDS.includes(firstWord)) {
|
|
1639
|
+
if (hasTruncatingPipe) addPartial(paths, parseHeadTailLimitForPipeline(segments));
|
|
1640
|
+
else for (const p of paths) full.add(p);
|
|
1641
|
+
} else if (firstWord === "head" || firstWord === "tail") {
|
|
1642
|
+
addPartial(paths, parseHeadTailLimit(seg));
|
|
1643
|
+
} else if (SHELL_PARTIAL_READ_CMDS.includes(firstWord)) {
|
|
1644
|
+
addPartial(paths, null);
|
|
1645
|
+
} else if (firstWord === "sed") {
|
|
1646
|
+
if (SED_INPLACE_RE.test(seg)) continue;
|
|
1647
|
+
const m = seg.match(SED_RANGE_RE);
|
|
1648
|
+
if (m) {
|
|
1649
|
+
if (m[2] === "$" && m[1] === "1") for (const p of paths) full.add(p);
|
|
1650
|
+
else addPartial(paths, null);
|
|
1651
|
+
} else {
|
|
1652
|
+
for (const p of paths) full.add(p);
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
return { full, partial };
|
|
1657
|
+
}
|
|
1658
|
+
let offset;
|
|
1659
|
+
let limit;
|
|
1660
|
+
const detail = histDetailRaw.trim();
|
|
1661
|
+
if (detail.startsWith("{")) {
|
|
1662
|
+
try {
|
|
1663
|
+
const obj = JSON.parse(detail);
|
|
1664
|
+
if (obj && typeof obj === "object") {
|
|
1665
|
+
offset = obj.offset;
|
|
1666
|
+
limit = obj.limit;
|
|
1667
|
+
}
|
|
1668
|
+
} catch {
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
if (histType.includes("read")) {
|
|
1672
|
+
if (offset != null || limit != null) {
|
|
1673
|
+
const off = typeof offset === "number" ? offset : Number(offset) || 1;
|
|
1674
|
+
const lim = typeof limit === "number" ? limit : limit != null ? Number(limit) || null : null;
|
|
1675
|
+
const upto = off === 1 && lim != null ? off + lim - 1 : null;
|
|
1676
|
+
addPartial(extractFilePaths(detail), upto);
|
|
1677
|
+
} else {
|
|
1678
|
+
for (const p of extractFilePaths(detail)) full.add(p);
|
|
1679
|
+
}
|
|
1680
|
+
} else if (histType.includes("grep") || histType.includes("search")) {
|
|
1681
|
+
addPartial(extractFilePaths(detail), null);
|
|
1682
|
+
} else if (histType.includes("glob") || histType.includes("list")) {
|
|
1683
|
+
} else if (readKeywords.some((kw) => histType.includes(kw))) {
|
|
1684
|
+
addPartial(extractFilePaths(detail), null);
|
|
1685
|
+
}
|
|
1686
|
+
return { full, partial };
|
|
1687
|
+
}
|
|
1688
|
+
function fileHasAtMostLines(filePath, limit) {
|
|
1689
|
+
if (limit <= 0 || limit > PARTIAL_COVER_CHECK_MAX_LINES) return false;
|
|
1690
|
+
try {
|
|
1691
|
+
const fd = fs.openSync(filePath, "r");
|
|
1692
|
+
try {
|
|
1693
|
+
const buf = Buffer.alloc(64 * 1024);
|
|
1694
|
+
let lines = 0;
|
|
1695
|
+
for (; ; ) {
|
|
1696
|
+
const n = fs.readSync(fd, buf, 0, buf.length, null);
|
|
1697
|
+
if (n <= 0) break;
|
|
1698
|
+
for (let i = 0; i < n; i++) {
|
|
1699
|
+
if (buf[i] === 10) {
|
|
1700
|
+
lines++;
|
|
1701
|
+
if (lines > limit) return false;
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
return true;
|
|
1706
|
+
} finally {
|
|
1707
|
+
fs.closeSync(fd);
|
|
1708
|
+
}
|
|
1709
|
+
} catch {
|
|
1710
|
+
return false;
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
function appendOnlyTargets(actionDetailRaw, osType) {
|
|
1714
|
+
const out = /* @__PURE__ */ new Set();
|
|
1715
|
+
for (const rawSeg of splitCommandSegments(actionDetailRaw)) {
|
|
1716
|
+
const seg = rawSeg.trim();
|
|
1717
|
+
if (!seg) continue;
|
|
1718
|
+
const segNoAppend = seg.replace(new RegExp(APPEND_REDIRECT_SOURCE, "g"), " ");
|
|
1719
|
+
const segNoQuotes = segNoAppend.replace(/'[^']*'|"[^"]*"/g, "");
|
|
1720
|
+
const hasOverwrite = /(?<![/\-=>])>\s*(?!&)\S/.test(segNoQuotes);
|
|
1721
|
+
if (hasOverwrite) continue;
|
|
1722
|
+
const re = new RegExp(APPEND_REDIRECT_SOURCE, "g");
|
|
1723
|
+
let m;
|
|
1724
|
+
while ((m = re.exec(seg)) !== null) {
|
|
1725
|
+
const p = m[1] || m[2] || m[3];
|
|
1726
|
+
if (p) out.add(p);
|
|
1727
|
+
}
|
|
1728
|
+
const firstWord = seg.split(/\s+/)[0]?.toLowerCase() || "";
|
|
1729
|
+
if (firstWord === "tee" && /(?:^|\s)(?:-a|--append)(?:\s|$)/.test(seg)) {
|
|
1730
|
+
for (const p of extractFilePaths(seg, osType)) out.add(p);
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
return out;
|
|
1734
|
+
}
|
|
1551
1735
|
function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWORDS, osType) {
|
|
1552
1736
|
if (writeKeywords.some((kw) => actionType.includes(kw) || actionDetail.includes(kw))) return true;
|
|
1553
1737
|
const { writeCommandRes } = getPlatformTraits(osType);
|
|
@@ -1587,7 +1771,12 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
|
|
|
1587
1771
|
}
|
|
1588
1772
|
function getIntentPatternsForOs(osType) {
|
|
1589
1773
|
const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
|
|
1590
|
-
if (effective)
|
|
1774
|
+
if (effective) {
|
|
1775
|
+
return effective.map((p) => ({
|
|
1776
|
+
...p,
|
|
1777
|
+
allowIfWriteIntent: p.allowIfWriteIntent ?? INTENT_DEVIATION_PATTERNS.find((d) => d.reason === p.reason)?.allowIfWriteIntent ?? false
|
|
1778
|
+
}));
|
|
1779
|
+
}
|
|
1591
1780
|
const accepted = acceptedOsValues(osType);
|
|
1592
1781
|
return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
|
|
1593
1782
|
}
|
|
@@ -1638,6 +1827,9 @@ function checkIntentConsistency(input) {
|
|
|
1638
1827
|
);
|
|
1639
1828
|
const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(actionDetail, kw));
|
|
1640
1829
|
if (intentMatched && dangerousMatched) {
|
|
1830
|
+
if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
|
|
1831
|
+
continue;
|
|
1832
|
+
}
|
|
1641
1833
|
return {
|
|
1642
1834
|
allowed: false,
|
|
1643
1835
|
reason: pattern.reason,
|
|
@@ -1658,7 +1850,16 @@ function runLogicCheck(input, opts) {
|
|
|
1658
1850
|
const resolvedCwd = cwd || "/";
|
|
1659
1851
|
const isExcludedType = EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p));
|
|
1660
1852
|
if (!opts?.skipReadBeforeWrite) {
|
|
1661
|
-
const
|
|
1853
|
+
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;
|
|
1854
|
+
const rbwResult = checkReadBeforeWrite(
|
|
1855
|
+
actionType,
|
|
1856
|
+
aNext.actionDetail,
|
|
1857
|
+
actionHistory,
|
|
1858
|
+
input.reason,
|
|
1859
|
+
resolvedCwd,
|
|
1860
|
+
input.osType,
|
|
1861
|
+
singleFileTools
|
|
1862
|
+
);
|
|
1662
1863
|
if (rbwResult) return rbwResult;
|
|
1663
1864
|
}
|
|
1664
1865
|
const intentResult = checkIntentConsistency(input);
|
|
@@ -1761,11 +1962,15 @@ function extractFilePaths(text, osType) {
|
|
|
1761
1962
|
}
|
|
1762
1963
|
return [...new Set(paths)];
|
|
1763
1964
|
}
|
|
1764
|
-
function checkReadBeforeWrite(actionType,
|
|
1965
|
+
function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason, cwd, osType, singleFileTools = SINGLE_FILE_WRITE_TOOLS) {
|
|
1966
|
+
const actionDetail = actionDetailRaw.toLowerCase();
|
|
1765
1967
|
if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
|
|
1766
1968
|
if (NON_WRITE_TOOLS.has(actionType)) return null;
|
|
1767
1969
|
const isBashLike = actionType === "bash" || actionType === "executebash" || actionType === "terminal-executebash";
|
|
1768
|
-
|
|
1970
|
+
let isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
|
|
1971
|
+
if (!isWrite && /\btar\b/.test(actionDetail) && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(actionDetail)) {
|
|
1972
|
+
isWrite = true;
|
|
1973
|
+
}
|
|
1769
1974
|
if (!isWrite) return null;
|
|
1770
1975
|
const WRITE_CMDS = new Set(_LOGIC.write_commands ?? []);
|
|
1771
1976
|
if (isBashLike) {
|
|
@@ -1787,6 +1992,10 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1787
1992
|
hasWriteSeg = true;
|
|
1788
1993
|
break;
|
|
1789
1994
|
}
|
|
1995
|
+
if (fw === "tar" && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed) && /(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)\S+/.test(trimmed)) {
|
|
1996
|
+
hasWriteSeg = true;
|
|
1997
|
+
break;
|
|
1998
|
+
}
|
|
1790
1999
|
if ((fw === "wget" || fw === "curl") && (/\s(?:-O|--output-document|--output)(?:=|\s|$)/i.test(trimmed) || /\s-O\S/.test(trimmed))) {
|
|
1791
2000
|
hasWriteSeg = true;
|
|
1792
2001
|
break;
|
|
@@ -1802,7 +2011,11 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1802
2011
|
const SOURCE_ARG_CMDS = new Set(_LOGIC.source_arg_commands ?? []);
|
|
1803
2012
|
const REDIRECT_TARGET_RE = new RegExp(`>{1,2}\\s*(?!&)(?:'(/[^']+)'|"(/[^\\"]+)"|(/[^\\s;|&><'\\"]+))`);
|
|
1804
2013
|
const targetPaths = [];
|
|
1805
|
-
|
|
2014
|
+
const singleFileTool = singleFileTools.has(actionType);
|
|
2015
|
+
if (singleFileTool && MISSING_WRITE_PATH_RE.test(actionDetailRaw)) {
|
|
2016
|
+
return null;
|
|
2017
|
+
}
|
|
2018
|
+
for (const seg of singleFileTool ? [] : splitCommandSegments(actionDetailRaw)) {
|
|
1806
2019
|
const trimmed = seg.trim();
|
|
1807
2020
|
if (!trimmed) continue;
|
|
1808
2021
|
const firstWord = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
|
|
@@ -1822,6 +2035,11 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1822
2035
|
const segPathsFiltered = firstWord === "wget" || firstWord === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
|
|
1823
2036
|
if (SOURCE_ARG_CMDS.has(firstWord)) {
|
|
1824
2037
|
if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
|
|
2038
|
+
} else if (firstWord === "tar") {
|
|
2039
|
+
if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
|
|
2040
|
+
const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
|
|
2041
|
+
if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
|
|
2042
|
+
}
|
|
1825
2043
|
} else if (firstWord === "dd") {
|
|
1826
2044
|
const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
|
|
1827
2045
|
const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
|
|
@@ -1834,16 +2052,31 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1834
2052
|
targetPaths.push(...segPathsFiltered);
|
|
1835
2053
|
}
|
|
1836
2054
|
}
|
|
2055
|
+
if (singleFileTool) {
|
|
2056
|
+
targetPaths.length = 0;
|
|
2057
|
+
targetPaths.push(...declaredWritePaths(actionDetailRaw, osType));
|
|
2058
|
+
}
|
|
1837
2059
|
const uniqueTargetPaths = [...new Set(targetPaths)].filter((p) => !PSEUDO_FS_PREFIXES.some((pfx) => p.startsWith(pfx)));
|
|
1838
2060
|
if (uniqueTargetPaths.length === 0) return null;
|
|
1839
|
-
const
|
|
2061
|
+
const historyFullReadPaths = /* @__PURE__ */ new Set();
|
|
2062
|
+
const historyPartialRead = /* @__PURE__ */ new Map();
|
|
1840
2063
|
for (const action of actionHistory) {
|
|
1841
|
-
const
|
|
2064
|
+
const histDetailRaw = action.actionDetail;
|
|
1842
2065
|
const histType = action.actionType.toLowerCase();
|
|
1843
|
-
const
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
2066
|
+
const traits = getPlatformTraits(osType);
|
|
2067
|
+
const coverage = historyReadCoverage(
|
|
2068
|
+
histType,
|
|
2069
|
+
histDetailRaw,
|
|
2070
|
+
traits.readKeywords,
|
|
2071
|
+
traits.writeKeywords
|
|
2072
|
+
);
|
|
2073
|
+
for (const p of coverage.full) historyFullReadPaths.add(p);
|
|
2074
|
+
for (const [p, upto] of coverage.partial) {
|
|
2075
|
+
if (historyPartialRead.has(p)) {
|
|
2076
|
+
const old = historyPartialRead.get(p);
|
|
2077
|
+
historyPartialRead.set(p, old == null || upto == null ? null : Math.max(old, upto));
|
|
2078
|
+
} else {
|
|
2079
|
+
historyPartialRead.set(p, upto);
|
|
1847
2080
|
}
|
|
1848
2081
|
}
|
|
1849
2082
|
}
|
|
@@ -1856,18 +2089,49 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1856
2089
|
if (filteredPaths.length === 0) {
|
|
1857
2090
|
return null;
|
|
1858
2091
|
}
|
|
2092
|
+
const normalizedTargets = filteredPaths.map((p) => normalizePathForCompare(p, cwd)).filter((p, i, arr) => p && arr.indexOf(p) === i);
|
|
2093
|
+
const normalizedFullReads = new Set(
|
|
2094
|
+
[...historyFullReadPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
|
|
2095
|
+
);
|
|
2096
|
+
const normalizedPartialReads = /* @__PURE__ */ new Map();
|
|
2097
|
+
for (const [p, upto] of historyPartialRead) {
|
|
2098
|
+
const np = normalizePathForCompare(p, cwd);
|
|
2099
|
+
if (np) normalizedPartialReads.set(np, upto);
|
|
2100
|
+
}
|
|
2101
|
+
const appendTargets = appendOnlyTargets(actionDetailRaw, osType);
|
|
2102
|
+
if (APPEND_MODE_RE.test(actionDetailRaw)) {
|
|
2103
|
+
for (const p of filteredPaths) appendTargets.add(p);
|
|
2104
|
+
}
|
|
2105
|
+
let checkTargets = normalizedTargets;
|
|
2106
|
+
if (appendTargets.size > 0) {
|
|
2107
|
+
const appendNorm = new Set(
|
|
2108
|
+
[...appendTargets].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
|
|
2109
|
+
);
|
|
2110
|
+
checkTargets = normalizedTargets.filter((p) => !([...appendNorm].some((ap) => pathIsSameOrUnder(p, ap) || pathIsSameOrUnder(ap, p)) && !isProtectedWritePath(p)));
|
|
2111
|
+
if (checkTargets.length === 0) return null;
|
|
2112
|
+
}
|
|
1859
2113
|
const unreadPaths = [];
|
|
1860
|
-
for (const
|
|
1861
|
-
const
|
|
1862
|
-
(rp) =>
|
|
2114
|
+
for (const path8 of checkTargets) {
|
|
2115
|
+
const isFullRead = [...normalizedFullReads].some(
|
|
2116
|
+
(rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
|
|
1863
2117
|
);
|
|
1864
|
-
|
|
1865
|
-
|
|
2118
|
+
let isPartialCovered = false;
|
|
2119
|
+
if (!isFullRead) {
|
|
2120
|
+
for (const [pp, upto] of normalizedPartialReads) {
|
|
2121
|
+
if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
|
|
2122
|
+
if (upto != null && fileHasAtMostLines(path8, upto)) {
|
|
2123
|
+
isPartialCovered = true;
|
|
2124
|
+
break;
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
if (!isFullRead && !isPartialCovered) {
|
|
2129
|
+
let isCreate = !fs.existsSync(path8);
|
|
1866
2130
|
if (!isCreate) {
|
|
1867
2131
|
isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
|
|
1868
2132
|
}
|
|
1869
2133
|
if (!isCreate) {
|
|
1870
|
-
unreadPaths.push(
|
|
2134
|
+
unreadPaths.push(path8);
|
|
1871
2135
|
}
|
|
1872
2136
|
}
|
|
1873
2137
|
}
|
|
@@ -2044,7 +2308,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
|
|
|
2044
2308
|
violatedLayers: ["L2.1"]
|
|
2045
2309
|
};
|
|
2046
2310
|
}
|
|
2047
|
-
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;
|
|
2311
|
+
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;
|
|
2048
2312
|
var init_logic_rules = __esm({
|
|
2049
2313
|
"src/engine/logic-rules.ts"() {
|
|
2050
2314
|
"use strict";
|
|
@@ -2061,16 +2325,16 @@ var init_logic_rules = __esm({
|
|
|
2061
2325
|
ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
|
|
2062
2326
|
ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
|
|
2063
2327
|
HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
|
|
2064
|
-
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path:
|
|
2328
|
+
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2065
2329
|
ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
|
|
2066
2330
|
HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
|
|
2067
|
-
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path:
|
|
2331
|
+
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2068
2332
|
ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
|
|
2069
2333
|
HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
|
|
2070
|
-
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path:
|
|
2334
|
+
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2071
2335
|
ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
|
|
2072
2336
|
HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
|
|
2073
|
-
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path:
|
|
2337
|
+
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2074
2338
|
_scopeIndex = null;
|
|
2075
2339
|
NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
|
|
2076
2340
|
"ask_user_question",
|
|
@@ -2093,6 +2357,23 @@ var init_logic_rules = __esm({
|
|
|
2093
2357
|
]);
|
|
2094
2358
|
NON_WRITE_TOOL_PREFIXES = _LOGIC.non_write_tool_prefixes ?? [];
|
|
2095
2359
|
PSEUDO_FS_PREFIXES = ["/sys/", "/proc/", "/dev/", "/run/"];
|
|
2360
|
+
SINGLE_FILE_WRITE_TOOLS = new Set(
|
|
2361
|
+
_LOGIC.single_file_write_tools ?? []
|
|
2362
|
+
);
|
|
2363
|
+
WRITE_INTENT_KEYWORDS = _LOGIC.write_intent_keywords ?? [];
|
|
2364
|
+
MISSING_WRITE_PATH_RE = /(?:写入文件|编辑文件|写入|编辑)\s*[::]\s*\?/;
|
|
2365
|
+
DECLARED_WRITE_PATH_RE = /(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*([~./][^\s—|,;]+)/;
|
|
2366
|
+
DECLARED_WRITE_PATH_JSON_RE = /"(?:file_path|filePath|path)"\s*:\s*"([^"]+)"/;
|
|
2367
|
+
PROTECTED_WRITE_PREFIXES = _LOGIC.protected_write_prefixes ?? [];
|
|
2368
|
+
PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
|
|
2369
|
+
APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
|
|
2370
|
+
APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
|
|
2371
|
+
SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
|
|
2372
|
+
SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
|
|
2373
|
+
SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
|
|
2374
|
+
HEAD_TAIL_LIMIT_RE = /(?:-n\s*|-\s*)(\d+)/;
|
|
2375
|
+
SED_RANGE_RE = /-n\s+['"]?(\d+)\s*,\s*(\d+|\$)\s*p/;
|
|
2376
|
+
PARTIAL_COVER_CHECK_MAX_LINES = 1e5;
|
|
2096
2377
|
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"];
|
|
2097
2378
|
SED_INPLACE_RE = /\bsed\s+(?:-\S+\s+)*(?:-[a-zA-Z]*i[a-zA-Z]*|--in-place)\b/i;
|
|
2098
2379
|
DEVNULL_REDIRECT_RE = /(?:2|&|1)?\s*>\s*\/dev\/null\b/g;
|
|
@@ -2111,7 +2392,8 @@ var init_logic_rules = __esm({
|
|
|
2111
2392
|
intentKeywords: p.intent_keywords,
|
|
2112
2393
|
dangerousActions: p.dangerous_actions,
|
|
2113
2394
|
reason: p.reason,
|
|
2114
|
-
os: String(p.os || "linux").toLowerCase()
|
|
2395
|
+
os: String(p.os || "linux").toLowerCase(),
|
|
2396
|
+
allowIfWriteIntent: p.allow_if_write_intent === true
|
|
2115
2397
|
}));
|
|
2116
2398
|
})();
|
|
2117
2399
|
COMBO_STAGES = (() => {
|
|
@@ -2152,11 +2434,11 @@ var init_logic_rules = __esm({
|
|
|
2152
2434
|
|
|
2153
2435
|
// src/engine/asset-dir.ts
|
|
2154
2436
|
import { existsSync as existsSync5 } from "fs";
|
|
2155
|
-
import { join as
|
|
2437
|
+
import { join as join6, resolve as resolve3 } from "path";
|
|
2156
2438
|
function assetDirCandidates(moduleDir, name) {
|
|
2157
2439
|
const root = getRulesRoot();
|
|
2158
2440
|
if (root) {
|
|
2159
|
-
const p =
|
|
2441
|
+
const p = join6(root, name);
|
|
2160
2442
|
return [p, p];
|
|
2161
2443
|
}
|
|
2162
2444
|
return [
|
|
@@ -2375,7 +2657,7 @@ __export(runtime_config_exports, {
|
|
|
2375
2657
|
updateSkillEnabled: () => updateSkillEnabled
|
|
2376
2658
|
});
|
|
2377
2659
|
import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
|
|
2378
|
-
import { join as
|
|
2660
|
+
import { join as join7 } from "path";
|
|
2379
2661
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
2380
2662
|
import { dirname as dirname4 } from "path";
|
|
2381
2663
|
function runtimeDir() {
|
|
@@ -2511,8 +2793,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
|
|
|
2511
2793
|
function _filterRulesByOs(rules, osType) {
|
|
2512
2794
|
const accepted = acceptedOsValues(osType);
|
|
2513
2795
|
return rules.filter((r) => {
|
|
2514
|
-
const
|
|
2515
|
-
return
|
|
2796
|
+
const os5 = String(r.os || "linux").toLowerCase();
|
|
2797
|
+
return os5 === "all" || accepted.includes(os5);
|
|
2516
2798
|
});
|
|
2517
2799
|
}
|
|
2518
2800
|
function _userCustomRules(runtime, layers, requiredKey) {
|
|
@@ -2714,7 +2996,7 @@ function _l2SensitivePathsToRules() {
|
|
|
2714
2996
|
const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
|
|
2715
2997
|
const all = [...root, ...home, ...credential];
|
|
2716
2998
|
for (const sp of all) {
|
|
2717
|
-
const
|
|
2999
|
+
const os5 = String(sp.os || "linux").toLowerCase();
|
|
2718
3000
|
const denyMode = sp.denyMode || _deriveDenyMode({
|
|
2719
3001
|
deny_mode: sp.deny_mode,
|
|
2720
3002
|
credential: sp.credential,
|
|
@@ -2724,7 +3006,7 @@ function _l2SensitivePathsToRules() {
|
|
|
2724
3006
|
// id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
|
|
2725
3007
|
// hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
|
|
2726
3008
|
// Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
|
|
2727
|
-
id: `path_${
|
|
3009
|
+
id: `path_${os5}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
|
|
2728
3010
|
path: sp.path,
|
|
2729
3011
|
risk_level: sp.riskLevel,
|
|
2730
3012
|
desc: sp.desc,
|
|
@@ -2733,7 +3015,7 @@ function _l2SensitivePathsToRules() {
|
|
|
2733
3015
|
skip_l3_on_disabled: true,
|
|
2734
3016
|
enabled: true,
|
|
2735
3017
|
builtin: true,
|
|
2736
|
-
os:
|
|
3018
|
+
os: os5
|
|
2737
3019
|
};
|
|
2738
3020
|
_syncDenyModeFields(rule);
|
|
2739
3021
|
if (sp.dirDelOnly) rule.dir_del_only = true;
|
|
@@ -2751,6 +3033,9 @@ function _l2IntentPatternsToRules() {
|
|
|
2751
3033
|
intent_keywords: pat.intentKeywords,
|
|
2752
3034
|
dangerous_actions: pat.dangerousActions,
|
|
2753
3035
|
reason: pat.reason,
|
|
3036
|
+
// 旧 runtime 里没有这个字段:缺省 false,但 getIntentPatternsForOs 会按
|
|
3037
|
+
// reason 回填内置默认值,避免旧配置让新豁免失效。
|
|
3038
|
+
allow_if_write_intent: pat.allowIfWriteIntent,
|
|
2754
3039
|
skip_l3_on_disabled: true,
|
|
2755
3040
|
enabled: true,
|
|
2756
3041
|
builtin: true
|
|
@@ -2821,7 +3106,7 @@ function _l3SkillsToRules() {
|
|
|
2821
3106
|
function _scenarioRulesToDefaults() {
|
|
2822
3107
|
const out = {};
|
|
2823
3108
|
const _root = getRulesRoot();
|
|
2824
|
-
const scenDir = _root ?
|
|
3109
|
+
const scenDir = _root ? join7(_root, "scenarios") : existsSync7(_SCENARIOS_DIR_PROD) ? _SCENARIOS_DIR_PROD : existsSync7(_SCENARIOS_DIR_DEV) ? _SCENARIOS_DIR_DEV : _SCENARIOS_DIR_PROD;
|
|
2825
3110
|
if (!existsSync7(scenDir)) return out;
|
|
2826
3111
|
let entries;
|
|
2827
3112
|
try {
|
|
@@ -2830,7 +3115,7 @@ function _scenarioRulesToDefaults() {
|
|
|
2830
3115
|
return out;
|
|
2831
3116
|
}
|
|
2832
3117
|
for (const scenarioId of entries) {
|
|
2833
|
-
const rulesFile = resolveScenarioRulesFile(scenarioId) ??
|
|
3118
|
+
const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join7(scenDir, scenarioId, "rules.json");
|
|
2834
3119
|
if (!existsSync7(rulesFile)) continue;
|
|
2835
3120
|
let data;
|
|
2836
3121
|
try {
|
|
@@ -2871,7 +3156,7 @@ function _scenarioRulesToDefaults() {
|
|
|
2871
3156
|
function _agentRulesToDefaults() {
|
|
2872
3157
|
const out = {};
|
|
2873
3158
|
const _root = getRulesRoot();
|
|
2874
|
-
const agentsDir = _root ?
|
|
3159
|
+
const agentsDir = _root ? join7(_root, "agents") : existsSync7(_AGENTS_DIR_PROD) ? _AGENTS_DIR_PROD : existsSync7(_AGENTS_DIR_DEV) ? _AGENTS_DIR_DEV : _AGENTS_DIR_PROD;
|
|
2875
3160
|
if (!existsSync7(agentsDir)) return out;
|
|
2876
3161
|
let entries;
|
|
2877
3162
|
try {
|
|
@@ -2880,7 +3165,7 @@ function _agentRulesToDefaults() {
|
|
|
2880
3165
|
return out;
|
|
2881
3166
|
}
|
|
2882
3167
|
for (const agentId of entries) {
|
|
2883
|
-
const rulesFile =
|
|
3168
|
+
const rulesFile = join7(agentsDir, agentId, "rules.json");
|
|
2884
3169
|
if (!existsSync7(rulesFile)) continue;
|
|
2885
3170
|
let data;
|
|
2886
3171
|
try {
|
|
@@ -2913,6 +3198,11 @@ function _agentRulesToDefaults() {
|
|
|
2913
3198
|
category_enabled: true,
|
|
2914
3199
|
category_desc: "agent \u4E13\u5C5E\u654F\u611F\u8DEF\u5F84\uFF08L1 \u672B\u5C3E\u8FFD\u52A0\uFF09",
|
|
2915
3200
|
rules: (data.extra_sensitive_paths || []).map((sp) => ({ ...sp, enabled: true, builtin: true }))
|
|
3201
|
+
},
|
|
3202
|
+
extra_single_file_write_tools: {
|
|
3203
|
+
category_enabled: true,
|
|
3204
|
+
category_desc: "agent \u4E13\u5C5E\u5355\u6587\u4EF6\u5199\u5DE5\u5177\uFF08read_before_write \u53EA\u53D6\u58F0\u660E\u8DEF\u5F84\uFF09",
|
|
3205
|
+
rules: (data.extra_single_file_write_tools || []).map((v) => ({ value: v, enabled: true, builtin: true }))
|
|
2916
3206
|
}
|
|
2917
3207
|
};
|
|
2918
3208
|
}
|
|
@@ -3217,7 +3507,9 @@ function getEnabledL2IntentPatterns(runtime, osType) {
|
|
|
3217
3507
|
return rules.map((r) => ({
|
|
3218
3508
|
intent_keywords: r.intent_keywords || [],
|
|
3219
3509
|
dangerous_actions: r.dangerous_actions || [],
|
|
3220
|
-
reason: r.reason || ""
|
|
3510
|
+
reason: r.reason || "",
|
|
3511
|
+
allow_if_write_intent: r.allow_if_write_intent === true,
|
|
3512
|
+
os: r.os
|
|
3221
3513
|
}));
|
|
3222
3514
|
}
|
|
3223
3515
|
function getEnabledL2PasswordPatterns(runtime) {
|
|
@@ -3261,8 +3553,8 @@ function _filterDefaultsByOs(rules, osType) {
|
|
|
3261
3553
|
const accepted = acceptedOsValues(osType);
|
|
3262
3554
|
return rules.filter((r) => {
|
|
3263
3555
|
if (!r.os) return true;
|
|
3264
|
-
const
|
|
3265
|
-
return
|
|
3556
|
+
const os5 = String(r.os).toLowerCase();
|
|
3557
|
+
return os5 === "all" || accepted.includes(os5);
|
|
3266
3558
|
});
|
|
3267
3559
|
}
|
|
3268
3560
|
function _hasRulesForOs(rules, osType) {
|
|
@@ -3387,7 +3679,8 @@ function effectiveIntentPatterns(osType) {
|
|
|
3387
3679
|
intentKeywords: r.intent_keywords || [],
|
|
3388
3680
|
dangerousActions: r.dangerous_actions || [],
|
|
3389
3681
|
reason: String(r.reason || ""),
|
|
3390
|
-
os: String(r.os || "linux").toLowerCase()
|
|
3682
|
+
os: String(r.os || "linux").toLowerCase(),
|
|
3683
|
+
allowIfWriteIntent: r.allow_if_write_intent === true
|
|
3391
3684
|
}));
|
|
3392
3685
|
});
|
|
3393
3686
|
}
|
|
@@ -3492,12 +3785,12 @@ function addCustomSkill(skillId, category, keywords, content) {
|
|
|
3492
3785
|
);
|
|
3493
3786
|
}
|
|
3494
3787
|
const runtime = loadRuntimeConfig();
|
|
3495
|
-
const skillsDir =
|
|
3788
|
+
const skillsDir = join7(getRuntimeConfigDir(), "agent_moss_skills");
|
|
3496
3789
|
try {
|
|
3497
3790
|
mkdirSync2(skillsDir, { recursive: true });
|
|
3498
3791
|
} catch {
|
|
3499
3792
|
}
|
|
3500
|
-
writeFileSync(
|
|
3793
|
+
writeFileSync(join7(skillsDir, `${skillId}.md`), content, "utf-8");
|
|
3501
3794
|
const l3 = runtime.L3_skills || (runtime.L3_skills = {});
|
|
3502
3795
|
const cat = l3[category] || (l3[category] = { category_enabled: true, category_desc: "", skills: [] });
|
|
3503
3796
|
(cat.skills || (cat.skills = [])).push({ id: skillId, keywords, enabled: true, builtin: false });
|
|
@@ -3512,7 +3805,7 @@ function deleteCustomSkill(skillId, category) {
|
|
|
3512
3805
|
if (idx >= 0) {
|
|
3513
3806
|
if (skills[idx].builtin) return null;
|
|
3514
3807
|
skills.splice(idx, 1);
|
|
3515
|
-
const skillPath =
|
|
3808
|
+
const skillPath = join7(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
|
|
3516
3809
|
try {
|
|
3517
3810
|
if (existsSync7(skillPath)) unlinkSync(skillPath);
|
|
3518
3811
|
} catch {
|
|
@@ -3575,6 +3868,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
|
|
|
3575
3868
|
read_only: r.read_only,
|
|
3576
3869
|
deny_mode: r.deny_mode
|
|
3577
3870
|
}));
|
|
3871
|
+
const singleFileWriteTools = _agentCategoryEnabledRules(agentData.extra_single_file_write_tools).filter((r) => r.value).map((r) => String(r.value).toLowerCase());
|
|
3578
3872
|
return {
|
|
3579
3873
|
agent_id: agentId,
|
|
3580
3874
|
description: "",
|
|
@@ -3583,6 +3877,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
|
|
|
3583
3877
|
extra_sensitive_paths: sensitivePaths,
|
|
3584
3878
|
builtin_safe_skills: safeSkills.filter((r) => r.value).map((r) => r.value),
|
|
3585
3879
|
builtin_safe_action_types: safeAction.filter((r) => r.value).map((r) => r.value),
|
|
3880
|
+
extra_single_file_write_tools: singleFileWriteTools,
|
|
3586
3881
|
extra_skills: []
|
|
3587
3882
|
};
|
|
3588
3883
|
}
|
|
@@ -3661,6 +3956,7 @@ function getEnabledScenarioExtensions(runtime, scenarioId) {
|
|
|
3661
3956
|
extra_sensitive_paths: sensitivePaths,
|
|
3662
3957
|
builtin_safe_skills: [],
|
|
3663
3958
|
builtin_safe_action_types: [],
|
|
3959
|
+
extra_single_file_write_tools: [],
|
|
3664
3960
|
extra_skills: []
|
|
3665
3961
|
};
|
|
3666
3962
|
}
|
|
@@ -3721,7 +4017,7 @@ var init_runtime_config = __esm({
|
|
|
3721
4017
|
__dirname4 = dirname4(fileURLToPath4(import.meta.url));
|
|
3722
4018
|
ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
|
|
3723
4019
|
RUNTIME_CONFIG_DIR = runtimeDir();
|
|
3724
|
-
RUNTIME_CONFIG_PATH =
|
|
4020
|
+
RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
|
|
3725
4021
|
LAYER_DISABLE_ENV = {
|
|
3726
4022
|
L1_heuristic: "AGENT_MOSS_DISABLE_HEURISTIC",
|
|
3727
4023
|
L2_logic_rules: "AGENT_MOSS_DISABLE_LOGIC_RULES",
|
|
@@ -3749,10 +4045,10 @@ var init_runtime_config = __esm({
|
|
|
3749
4045
|
intent_consistency: ["intent_keywords", "reason"]
|
|
3750
4046
|
};
|
|
3751
4047
|
hasRuntimeConfigCache = /* @__PURE__ */ new Map();
|
|
3752
|
-
_AGENTS_DIR_PROD =
|
|
3753
|
-
_AGENTS_DIR_DEV =
|
|
3754
|
-
_SCENARIOS_DIR_PROD =
|
|
3755
|
-
_SCENARIOS_DIR_DEV =
|
|
4048
|
+
_AGENTS_DIR_PROD = join7(__dirname4, "agents");
|
|
4049
|
+
_AGENTS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "agents");
|
|
4050
|
+
_SCENARIOS_DIR_PROD = join7(__dirname4, "scenarios");
|
|
4051
|
+
_SCENARIOS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
|
|
3756
4052
|
_effectiveCache = /* @__PURE__ */ new WeakMap();
|
|
3757
4053
|
SKILL_ID_RE = /^[A-Za-z0-9_-]+$/;
|
|
3758
4054
|
registerRuntimeConfigBridge({
|
|
@@ -3795,7 +4091,7 @@ __export(config_exports, {
|
|
|
3795
4091
|
wildcardToRegExp: () => wildcardToRegExp
|
|
3796
4092
|
});
|
|
3797
4093
|
import fs2 from "fs";
|
|
3798
|
-
import
|
|
4094
|
+
import path3 from "path";
|
|
3799
4095
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
3800
4096
|
function loadConfigFile(filePath) {
|
|
3801
4097
|
try {
|
|
@@ -3808,17 +4104,17 @@ function loadConfigFile(filePath) {
|
|
|
3808
4104
|
function resolveConfigPath() {
|
|
3809
4105
|
const envPath = process.env.AGENT_MOSS_CONFIG_PATH;
|
|
3810
4106
|
if (envPath) return envPath;
|
|
3811
|
-
const userConfig =
|
|
4107
|
+
const userConfig = path3.join(getConfigDir(), "config.json");
|
|
3812
4108
|
if (fs2.existsSync(userConfig)) return userConfig;
|
|
3813
4109
|
const defaultCandidates = [
|
|
3814
|
-
|
|
3815
|
-
|
|
3816
|
-
|
|
3817
|
-
|
|
4110
|
+
path3.join(__configModuleDir, "config.json.example"),
|
|
4111
|
+
path3.join(__configModuleDir, "..", "config.json.example"),
|
|
4112
|
+
path3.join(__configModuleDir, "..", "..", "agent_moss", "infra", "config.json.example"),
|
|
4113
|
+
path3.join(__configModuleDir, "..", "..", "..", "agent_moss", "infra", "config.json.example")
|
|
3818
4114
|
];
|
|
3819
4115
|
const defaultConfig = defaultCandidates.find((p) => fs2.existsSync(p));
|
|
3820
4116
|
if (defaultConfig) {
|
|
3821
|
-
const configDir =
|
|
4117
|
+
const configDir = path3.dirname(userConfig);
|
|
3822
4118
|
fs2.mkdirSync(configDir, { recursive: true });
|
|
3823
4119
|
const pkgConfig = loadConfigFile(defaultConfig);
|
|
3824
4120
|
const safeConfig = pkgConfig ? { ...pkgConfig, llm: { ...pkgConfig.llm, api_key: "" } } : {};
|
|
@@ -4048,7 +4344,7 @@ var init_config = __esm({
|
|
|
4048
4344
|
init_rules_mode();
|
|
4049
4345
|
__configModuleDir = (() => {
|
|
4050
4346
|
try {
|
|
4051
|
-
return
|
|
4347
|
+
return path3.dirname(fileURLToPath5(import.meta.url));
|
|
4052
4348
|
} catch {
|
|
4053
4349
|
return typeof __dirname !== "undefined" ? __dirname : process.cwd();
|
|
4054
4350
|
}
|
|
@@ -4071,11 +4367,11 @@ var init_config = __esm({
|
|
|
4071
4367
|
};
|
|
4072
4368
|
})();
|
|
4073
4369
|
USER_RULES_PATHS = [
|
|
4074
|
-
|
|
4370
|
+
path3.join(__configModuleDir, "rules", "user_rules.json"),
|
|
4075
4371
|
// 源在 ts/src/rules(一般不存在)
|
|
4076
|
-
|
|
4372
|
+
path3.join(__configModuleDir, "..", "rules", "user_rules.json"),
|
|
4077
4373
|
// dist: dist/engine/../rules = dist/rules ✅
|
|
4078
|
-
|
|
4374
|
+
path3.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
|
|
4079
4375
|
// dev src: ts/src/../../agent_moss
|
|
4080
4376
|
];
|
|
4081
4377
|
customRules = loadCustomRules();
|
|
@@ -4093,11 +4389,11 @@ var init_config = __esm({
|
|
|
4093
4389
|
|
|
4094
4390
|
// src/agents/index.ts
|
|
4095
4391
|
import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
|
|
4096
|
-
import { resolve as resolve5, dirname as dirname5, join as
|
|
4392
|
+
import { resolve as resolve5, dirname as dirname5, join as join8 } from "path";
|
|
4097
4393
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
4098
4394
|
function resolveAgentsDir() {
|
|
4099
4395
|
const root = getRulesRoot();
|
|
4100
|
-
if (root) return
|
|
4396
|
+
if (root) return join8(root, "agents");
|
|
4101
4397
|
if (existsSync8(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
|
|
4102
4398
|
if (existsSync8(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
|
|
4103
4399
|
return AGENTS_DIR_PROD;
|
|
@@ -4158,6 +4454,7 @@ function mergeAgentExtensions(...exts) {
|
|
|
4158
4454
|
extra_sensitive_paths: nonNull.flatMap((e) => e.extra_sensitive_paths || []),
|
|
4159
4455
|
builtin_safe_skills: nonNull.flatMap((e) => e.builtin_safe_skills || []),
|
|
4160
4456
|
builtin_safe_action_types: nonNull.flatMap((e) => e.builtin_safe_action_types || []),
|
|
4457
|
+
extra_single_file_write_tools: nonNull.flatMap((e) => e.extra_single_file_write_tools || []),
|
|
4161
4458
|
extra_skills: nonNull.flatMap((e) => e.extra_skills || [])
|
|
4162
4459
|
};
|
|
4163
4460
|
}
|
|
@@ -4179,11 +4476,11 @@ var init_agents = __esm({
|
|
|
4179
4476
|
|
|
4180
4477
|
// src/scenarios/index.ts
|
|
4181
4478
|
import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
|
|
4182
|
-
import { resolve as resolve6, dirname as dirname6, join as
|
|
4479
|
+
import { resolve as resolve6, dirname as dirname6, join as join9 } from "path";
|
|
4183
4480
|
import { fileURLToPath as fileURLToPath7 } from "url";
|
|
4184
4481
|
function resolveScenariosDir() {
|
|
4185
4482
|
const root = getRulesRoot();
|
|
4186
|
-
if (root) return
|
|
4483
|
+
if (root) return join9(root, "scenarios");
|
|
4187
4484
|
if (existsSync9(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
|
|
4188
4485
|
if (existsSync9(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
|
|
4189
4486
|
return SCENARIOS_DIR_PROD;
|
|
@@ -4241,6 +4538,7 @@ function getScenarioExtensions(scenarioId) {
|
|
|
4241
4538
|
extra_sensitive_paths: data.extra_sensitive_paths || [],
|
|
4242
4539
|
builtin_safe_skills: data.builtin_safe_skills || [],
|
|
4243
4540
|
builtin_safe_action_types: data.builtin_safe_action_types || [],
|
|
4541
|
+
extra_single_file_write_tools: data.extra_single_file_write_tools || [],
|
|
4244
4542
|
extra_skills: data.extra_skills || []
|
|
4245
4543
|
};
|
|
4246
4544
|
} catch (e) {
|
|
@@ -4282,6 +4580,256 @@ var init_scenarios = __esm({
|
|
|
4282
4580
|
}
|
|
4283
4581
|
});
|
|
4284
4582
|
|
|
4583
|
+
// src/engine/written-content-analyzer.ts
|
|
4584
|
+
function isFileWriteAction(actionType) {
|
|
4585
|
+
const at = (actionType || "").toLowerCase();
|
|
4586
|
+
if (WRITE_TOOL_EXACT.has(at)) return true;
|
|
4587
|
+
if (WRITE_TOOL_SUFFIXES.some((s) => at.endsWith(s))) return true;
|
|
4588
|
+
return false;
|
|
4589
|
+
}
|
|
4590
|
+
function isApplyPatch(actionType) {
|
|
4591
|
+
const at = (actionType || "").toLowerCase();
|
|
4592
|
+
return APPLY_PATCH_SUFFIXES.some((s) => at.endsWith(s));
|
|
4593
|
+
}
|
|
4594
|
+
function extractWritePayload(actionType, actionDetailRaw) {
|
|
4595
|
+
if (isApplyPatch(actionType)) return null;
|
|
4596
|
+
const detail = actionDetailRaw || "";
|
|
4597
|
+
const m = detail.match(WRITE_PREFIX_RE);
|
|
4598
|
+
if (m) {
|
|
4599
|
+
const path8 = m[1];
|
|
4600
|
+
let content = m[2] || "";
|
|
4601
|
+
if (!path8 || path8 === "?" || path8 === "-" || !content.trim()) return null;
|
|
4602
|
+
if ((actionType || "").toLowerCase().includes("editfile")) {
|
|
4603
|
+
const nm = content.match(EDIT_NEW_RE);
|
|
4604
|
+
if (nm) content = nm[1];
|
|
4605
|
+
}
|
|
4606
|
+
return { path: path8, content };
|
|
4607
|
+
}
|
|
4608
|
+
const stripped = detail.trim();
|
|
4609
|
+
if (stripped.startsWith("{")) {
|
|
4610
|
+
try {
|
|
4611
|
+
const obj = JSON.parse(stripped);
|
|
4612
|
+
if (obj && typeof obj === "object") {
|
|
4613
|
+
const path8 = obj.path || obj.file_path || obj.filePath;
|
|
4614
|
+
const content = obj.content || obj.newString || obj.new_string;
|
|
4615
|
+
if (typeof path8 === "string" && path8 !== "" && path8 !== "?" && path8 !== "-" && typeof content === "string" && content.trim()) {
|
|
4616
|
+
return { path: path8, content };
|
|
4617
|
+
}
|
|
4618
|
+
}
|
|
4619
|
+
} catch {
|
|
4620
|
+
}
|
|
4621
|
+
}
|
|
4622
|
+
return null;
|
|
4623
|
+
}
|
|
4624
|
+
function handlesWrittenContent(actionType, actionDetailRaw) {
|
|
4625
|
+
if (!isFileWriteAction(actionType)) return false;
|
|
4626
|
+
if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
|
|
4627
|
+
return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
|
|
4628
|
+
}
|
|
4629
|
+
function detectLanguage(path8, content) {
|
|
4630
|
+
const ext = path8.slice(path8.lastIndexOf(".") >= 0 ? path8.lastIndexOf(".") : path8.length).toLowerCase();
|
|
4631
|
+
if (SHELL_EXTS.has(ext)) return "shell";
|
|
4632
|
+
if (PY_EXTS.has(ext)) return "python";
|
|
4633
|
+
if (DATA_EXTS.has(ext)) return "data";
|
|
4634
|
+
if (!ext) {
|
|
4635
|
+
const first = content.trim() ? content.trim().split(/\r?\n/)[0] : "";
|
|
4636
|
+
if (first.startsWith("#!")) {
|
|
4637
|
+
if (/\b(?:ba|z|k|da)?sh\b/.test(first)) return "shell";
|
|
4638
|
+
if (first.includes("python")) return "python";
|
|
4639
|
+
}
|
|
4640
|
+
return "data";
|
|
4641
|
+
}
|
|
4642
|
+
return "other";
|
|
4643
|
+
}
|
|
4644
|
+
function stripShellComments(text) {
|
|
4645
|
+
const out = [];
|
|
4646
|
+
for (const line of text.split(/\r?\n/)) {
|
|
4647
|
+
const res = [];
|
|
4648
|
+
let quote = null;
|
|
4649
|
+
for (let i = 0; i < line.length; i++) {
|
|
4650
|
+
const ch = line[i];
|
|
4651
|
+
if (quote) {
|
|
4652
|
+
res.push(ch);
|
|
4653
|
+
if (ch === quote) quote = null;
|
|
4654
|
+
continue;
|
|
4655
|
+
}
|
|
4656
|
+
if (ch === "'" || ch === '"') {
|
|
4657
|
+
quote = ch;
|
|
4658
|
+
res.push(ch);
|
|
4659
|
+
continue;
|
|
4660
|
+
}
|
|
4661
|
+
if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) break;
|
|
4662
|
+
res.push(ch);
|
|
4663
|
+
}
|
|
4664
|
+
out.push(res.join(""));
|
|
4665
|
+
}
|
|
4666
|
+
return out.join("\n");
|
|
4667
|
+
}
|
|
4668
|
+
function stripShellDocsOnly(content) {
|
|
4669
|
+
if (!content) return content;
|
|
4670
|
+
if (INTERP_HEREDOC_RE.test(content)) return content;
|
|
4671
|
+
const withoutHeredoc = content.replace(QUOTED_HEREDOC_RE, "<<quoted-heredoc>>\n");
|
|
4672
|
+
return stripShellComments(withoutHeredoc);
|
|
4673
|
+
}
|
|
4674
|
+
function lineSnippets(content, precheck) {
|
|
4675
|
+
const lines = content.split(/\r?\n/);
|
|
4676
|
+
const picked = /* @__PURE__ */ new Set();
|
|
4677
|
+
for (let i = 0; i < lines.length; i++) {
|
|
4678
|
+
precheck.lastIndex = 0;
|
|
4679
|
+
if (precheck.test(lines[i])) {
|
|
4680
|
+
picked.add(i - 1);
|
|
4681
|
+
picked.add(i);
|
|
4682
|
+
picked.add(i + 1);
|
|
4683
|
+
}
|
|
4684
|
+
}
|
|
4685
|
+
const snippets = [];
|
|
4686
|
+
let total = 0;
|
|
4687
|
+
for (const i of [...picked].sort((a, b) => a - b)) {
|
|
4688
|
+
if (i < 0 || i >= lines.length) continue;
|
|
4689
|
+
const s = lines[i];
|
|
4690
|
+
if (total + s.length > MAX_SCAN) break;
|
|
4691
|
+
snippets.push(s);
|
|
4692
|
+
total += s.length + 1;
|
|
4693
|
+
}
|
|
4694
|
+
return snippets;
|
|
4695
|
+
}
|
|
4696
|
+
function stripPythonLiterals(content) {
|
|
4697
|
+
const chars = content.split("");
|
|
4698
|
+
let i = 0;
|
|
4699
|
+
const n = chars.length;
|
|
4700
|
+
while (i < n) {
|
|
4701
|
+
const ch = chars[i];
|
|
4702
|
+
if (ch === "#") {
|
|
4703
|
+
while (i < n && chars[i] !== "\n") {
|
|
4704
|
+
chars[i] = " ";
|
|
4705
|
+
i++;
|
|
4706
|
+
}
|
|
4707
|
+
continue;
|
|
4708
|
+
}
|
|
4709
|
+
if (ch === "'" || ch === '"') {
|
|
4710
|
+
const triple = chars[i + 1] === ch && chars[i + 2] === ch;
|
|
4711
|
+
const quoteLen = triple ? 3 : 1;
|
|
4712
|
+
const q = ch;
|
|
4713
|
+
i += quoteLen;
|
|
4714
|
+
while (i < n) {
|
|
4715
|
+
if (chars[i] === "\\") {
|
|
4716
|
+
chars[i] = " ";
|
|
4717
|
+
if (i + 1 < n) chars[i + 1] = " ";
|
|
4718
|
+
i += 2;
|
|
4719
|
+
continue;
|
|
4720
|
+
}
|
|
4721
|
+
if (chars[i] === q && (!triple || chars[i + 1] === q && chars[i + 2] === q)) {
|
|
4722
|
+
for (let k = 0; k < quoteLen; k++) {
|
|
4723
|
+
chars[i + k] = " ";
|
|
4724
|
+
}
|
|
4725
|
+
i += quoteLen;
|
|
4726
|
+
break;
|
|
4727
|
+
}
|
|
4728
|
+
chars[i] = " ";
|
|
4729
|
+
i++;
|
|
4730
|
+
}
|
|
4731
|
+
continue;
|
|
4732
|
+
}
|
|
4733
|
+
i++;
|
|
4734
|
+
}
|
|
4735
|
+
return chars.join("");
|
|
4736
|
+
}
|
|
4737
|
+
function balancedArgs(original, openIndex) {
|
|
4738
|
+
let depth = 0;
|
|
4739
|
+
let quote = null;
|
|
4740
|
+
for (let i = openIndex; i < original.length && i < openIndex + 8e3; i++) {
|
|
4741
|
+
const ch = original[i];
|
|
4742
|
+
if (quote) {
|
|
4743
|
+
if (ch === "\\") {
|
|
4744
|
+
i++;
|
|
4745
|
+
continue;
|
|
4746
|
+
}
|
|
4747
|
+
if (ch === quote) quote = null;
|
|
4748
|
+
continue;
|
|
4749
|
+
}
|
|
4750
|
+
if (ch === "'" || ch === '"') {
|
|
4751
|
+
quote = ch;
|
|
4752
|
+
continue;
|
|
4753
|
+
}
|
|
4754
|
+
if (ch === "(") depth++;
|
|
4755
|
+
else if (ch === ")") {
|
|
4756
|
+
depth--;
|
|
4757
|
+
if (depth === 0) return original.slice(openIndex + 1, i);
|
|
4758
|
+
}
|
|
4759
|
+
}
|
|
4760
|
+
return original.slice(openIndex + 1, Math.min(original.length, openIndex + 2e3));
|
|
4761
|
+
}
|
|
4762
|
+
function pythonSnippets(content) {
|
|
4763
|
+
const stripped = stripPythonLiterals(content);
|
|
4764
|
+
const snippets = [];
|
|
4765
|
+
PY_DANGEROUS_CALL_RE.lastIndex = 0;
|
|
4766
|
+
let m;
|
|
4767
|
+
while ((m = PY_DANGEROUS_CALL_RE.exec(stripped)) !== null) {
|
|
4768
|
+
const callName = m[0].replace(/\s*\($/, "").trim();
|
|
4769
|
+
const openIndex = m.index + m[0].length - 1;
|
|
4770
|
+
const args = balancedArgs(content, openIndex);
|
|
4771
|
+
snippets.push(`${callName}(${args})`);
|
|
4772
|
+
if (snippets.length >= 200) break;
|
|
4773
|
+
}
|
|
4774
|
+
return snippets;
|
|
4775
|
+
}
|
|
4776
|
+
function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper) {
|
|
4777
|
+
if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
|
|
4778
|
+
const payload = extractWritePayload(actionType, actionDetailRaw);
|
|
4779
|
+
if (!payload) return [];
|
|
4780
|
+
const { path: path8, content: rawContent } = payload;
|
|
4781
|
+
const language = detectLanguage(path8, rawContent);
|
|
4782
|
+
if (language === "data") return [];
|
|
4783
|
+
let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
|
|
4784
|
+
const started = Date.now();
|
|
4785
|
+
if (language === "python") {
|
|
4786
|
+
if (!PY_PRECHECK.test(content)) return [];
|
|
4787
|
+
return pythonSnippets(content);
|
|
4788
|
+
}
|
|
4789
|
+
content = stripShellDocsOnly(content);
|
|
4790
|
+
if (literalStripper) content = literalStripper(content);
|
|
4791
|
+
if (!SHELL_PRECHECK.test(content)) return [];
|
|
4792
|
+
const snippets = lineSnippets(content, SHELL_PRECHECK);
|
|
4793
|
+
if (Date.now() - started > MAX_MS) {
|
|
4794
|
+
return snippets;
|
|
4795
|
+
}
|
|
4796
|
+
return snippets;
|
|
4797
|
+
}
|
|
4798
|
+
var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE;
|
|
4799
|
+
var init_written_content_analyzer = __esm({
|
|
4800
|
+
"src/engine/written-content-analyzer.ts"() {
|
|
4801
|
+
"use strict";
|
|
4802
|
+
init_esm_shims();
|
|
4803
|
+
init_rules_loader();
|
|
4804
|
+
CFG = loadHeuristicRules().write_content_analysis || {};
|
|
4805
|
+
DATA_EXTS = new Set((CFG.data_exts || []).map((e) => e.toLowerCase()));
|
|
4806
|
+
SHELL_EXTS = new Set((CFG.shell_exts || []).map((e) => e.toLowerCase()));
|
|
4807
|
+
PY_EXTS = new Set((CFG.python_exts || []).map((e) => e.toLowerCase()));
|
|
4808
|
+
SHELL_PRECHECK = new RegExp(CFG.shell_precheck || "$^");
|
|
4809
|
+
PY_PRECHECK = new RegExp(CFG.python_precheck || "$^");
|
|
4810
|
+
MAX_CONTENT = Number(CFG.max_content_bytes || 262144);
|
|
4811
|
+
MAX_SCAN = Number(CFG.max_scan_bytes || 65536);
|
|
4812
|
+
MAX_MS = Number(CFG.max_scan_ms || 100);
|
|
4813
|
+
WRITE_TOOL_EXACT = /* @__PURE__ */ new Set([
|
|
4814
|
+
"write",
|
|
4815
|
+
"file_write",
|
|
4816
|
+
"writefile",
|
|
4817
|
+
"edit",
|
|
4818
|
+
"file_edit",
|
|
4819
|
+
"editfile",
|
|
4820
|
+
"searchreplace",
|
|
4821
|
+
"search_replace"
|
|
4822
|
+
]);
|
|
4823
|
+
WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
|
|
4824
|
+
APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
|
|
4825
|
+
WRITE_PREFIX_RE = /^(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*(.+?)\s*(?:\(\s*追加\s*\))?\s*—\s*([\s\S]*)$/;
|
|
4826
|
+
EDIT_NEW_RE = /\|\s*new:\s*([\s\S]*)$/i;
|
|
4827
|
+
INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
|
|
4828
|
+
QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
|
|
4829
|
+
PY_DANGEROUS_CALL_RE = /(?:os\.(?:system|popen|remove|unlink|rmdir|chmod|chown|kill|spawn\w*)|subprocess\.\w+|pty\.\w+|ctypes\.\w+|eval|exec|compile|__import__|shutil\.(?:rmtree|move|copy\w*))\s*\(/g;
|
|
4830
|
+
}
|
|
4831
|
+
});
|
|
4832
|
+
|
|
4285
4833
|
// src/engine/heuristic.ts
|
|
4286
4834
|
function _effectiveDangerousPatterns(osType) {
|
|
4287
4835
|
return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
|
|
@@ -4389,8 +4937,16 @@ function runHeuristicCheck(input) {
|
|
|
4389
4937
|
} catch {
|
|
4390
4938
|
}
|
|
4391
4939
|
}
|
|
4392
|
-
const scanDetail = normalizePathSegments(
|
|
4393
|
-
|
|
4940
|
+
const scanDetail = normalizePathSegments(
|
|
4941
|
+
stripLiteralTextSegments(stripShellDocsOnly(input.aNext.actionDetail))
|
|
4942
|
+
);
|
|
4943
|
+
const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
|
|
4944
|
+
const writeSnippets = extractDangerousSnippets(
|
|
4945
|
+
input.aNext.actionType,
|
|
4946
|
+
input.aNext.actionDetail,
|
|
4947
|
+
stripLiteralTextSegments
|
|
4948
|
+
);
|
|
4949
|
+
const scanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => [`${input.aNext.actionType}: ${sn}`, sn]) : String(input.osType || "").toLowerCase() === "windows" ? [
|
|
4394
4950
|
`${input.aNext.actionType}: ${scanDetail}`,
|
|
4395
4951
|
scanDetail,
|
|
4396
4952
|
`${input.aNext.actionType}: ${scanDetail.replace(/\//g, "\\")}`,
|
|
@@ -4451,9 +5007,9 @@ function runHeuristicCheck(input) {
|
|
|
4451
5007
|
const actionTypeL = input.aNext.actionType.toLowerCase();
|
|
4452
5008
|
const detailL = input.aNext.actionDetail.toLowerCase();
|
|
4453
5009
|
const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
|
|
4454
|
-
const dangerousResult = checkDangerousPatterns(actionTypeL, detailL);
|
|
5010
|
+
const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
|
|
4455
5011
|
const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
|
|
4456
|
-
const homeResult = checkHomeDeletion(actionTypeL, detailL);
|
|
5012
|
+
const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
|
|
4457
5013
|
const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
|
|
4458
5014
|
if (mergeResults.length > 0) {
|
|
4459
5015
|
let best = mergeResults[0];
|
|
@@ -4673,16 +5229,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4673
5229
|
if (String(osType || "").toLowerCase() === "windows") {
|
|
4674
5230
|
pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
|
|
4675
5231
|
}
|
|
4676
|
-
const pathMatches = (text,
|
|
4677
|
-
const parts =
|
|
5232
|
+
const pathMatches = (text, path8) => {
|
|
5233
|
+
const parts = path8.split(/(\(\?!.*?\))/);
|
|
4678
5234
|
const escaped = parts.map((part) => {
|
|
4679
5235
|
if (part.startsWith("(?!")) return part;
|
|
4680
5236
|
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4681
5237
|
}).join("");
|
|
4682
|
-
const re =
|
|
5238
|
+
const re = path8.startsWith(".") || path8.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
|
|
4683
5239
|
return re.test(text);
|
|
4684
5240
|
};
|
|
4685
|
-
const pathMatchesAny = (
|
|
5241
|
+
const pathMatchesAny = (path8) => pathScanTexts.some((t) => pathMatches(t, path8));
|
|
4686
5242
|
for (const sp of rootPaths) {
|
|
4687
5243
|
if (pathMatchesAny(sp.path.toLowerCase())) {
|
|
4688
5244
|
if (keygenGenerate) continue;
|
|
@@ -4825,8 +5381,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4825
5381
|
}
|
|
4826
5382
|
return null;
|
|
4827
5383
|
}
|
|
4828
|
-
function isHomeValue(
|
|
4829
|
-
let p =
|
|
5384
|
+
function isHomeValue(path8) {
|
|
5385
|
+
let p = path8.trim().toLowerCase();
|
|
4830
5386
|
if (p.startsWith("$(") && p.endsWith(")")) {
|
|
4831
5387
|
const inner = p.slice(2, -1).trim();
|
|
4832
5388
|
return HOME_TARGET_RE.test(" " + inner);
|
|
@@ -4882,15 +5438,15 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
4882
5438
|
}
|
|
4883
5439
|
const assigned = {};
|
|
4884
5440
|
for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
|
|
4885
|
-
for (const [varName,
|
|
4886
|
-
if (!isHomeValue(
|
|
5441
|
+
for (const [varName, path8] of Object.entries(assigned)) {
|
|
5442
|
+
if (!isHomeValue(path8)) continue;
|
|
4887
5443
|
const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
|
|
4888
5444
|
for (const seg of segs) {
|
|
4889
5445
|
if (!isDeleteCommand(seg)) continue;
|
|
4890
5446
|
if (varRefRe.test(seg)) {
|
|
4891
5447
|
return {
|
|
4892
5448
|
allowed: false,
|
|
4893
|
-
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${
|
|
5449
|
+
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path8}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
|
|
4894
5450
|
riskLevel: "high",
|
|
4895
5451
|
riskType: "script_execution",
|
|
4896
5452
|
confidence: 90,
|
|
@@ -4951,7 +5507,7 @@ function isSshKeygenGenerate(command) {
|
|
|
4951
5507
|
}
|
|
4952
5508
|
function checkDangerousPatterns(actionType, actionDetail) {
|
|
4953
5509
|
if (actionType === "file_write" || actionType === "file_edit") return null;
|
|
4954
|
-
const scan = stripHeredocContent(actionDetail);
|
|
5510
|
+
const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
|
|
4955
5511
|
const isTempPath = TEMP_DIRS2.some(
|
|
4956
5512
|
(td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
|
|
4957
5513
|
) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
|
|
@@ -5109,6 +5665,7 @@ var init_heuristic = __esm({
|
|
|
5109
5665
|
init_runtime_config();
|
|
5110
5666
|
init_runtime_config_bridge();
|
|
5111
5667
|
init_rules_loader();
|
|
5668
|
+
init_written_content_analyzer();
|
|
5112
5669
|
init_logic_rules();
|
|
5113
5670
|
INJECTION_KEYWORDS = (() => {
|
|
5114
5671
|
const kws = loadL1().injection_detection || [];
|
|
@@ -5186,7 +5743,7 @@ var init_template_loader = __esm({
|
|
|
5186
5743
|
|
|
5187
5744
|
// src/engine/script-analyzer.ts
|
|
5188
5745
|
import { readFileSync as readFileSync10 } from "fs";
|
|
5189
|
-
import { resolve as resolve8, join as
|
|
5746
|
+
import { resolve as resolve8, join as join10 } from "path";
|
|
5190
5747
|
function emptyResult() {
|
|
5191
5748
|
return { scriptPath: "", scriptContent: "", matchedKeywords: [], lineCount: 0, isSuspicious: false, error: "", riskLevel: "", riskReason: "" };
|
|
5192
5749
|
}
|
|
@@ -5239,7 +5796,7 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
|
|
|
5239
5796
|
}
|
|
5240
5797
|
function readScriptContent(scriptPath, maxLines = 500) {
|
|
5241
5798
|
try {
|
|
5242
|
-
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ?
|
|
5799
|
+
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join10(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
|
|
5243
5800
|
const raw = readFileSync10(expandedPath, "utf-8");
|
|
5244
5801
|
const lines = raw.split("\n").slice(0, maxLines);
|
|
5245
5802
|
return { content: lines.join("\n"), lineCount: lines.length, error: "" };
|
|
@@ -5694,15 +6251,15 @@ function parseShellString(s) {
|
|
|
5694
6251
|
let m;
|
|
5695
6252
|
while ((m = CHILD_CALL_RE.exec(s)) !== null) {
|
|
5696
6253
|
const interp = m[1];
|
|
5697
|
-
const
|
|
6254
|
+
const path8 = m[2].trim();
|
|
5698
6255
|
let rest = m[3].trim();
|
|
5699
|
-
if (
|
|
6256
|
+
if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
|
|
5700
6257
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5701
6258
|
const args = [];
|
|
5702
6259
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5703
6260
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5704
6261
|
}
|
|
5705
|
-
return { path:
|
|
6262
|
+
return { path: path8, args, interpreter: interp };
|
|
5706
6263
|
}
|
|
5707
6264
|
return null;
|
|
5708
6265
|
}
|
|
@@ -5748,9 +6305,9 @@ function extractCallsFromTree(tree, reachableLines) {
|
|
|
5748
6305
|
}
|
|
5749
6306
|
if (allStr && elts.length >= 2) {
|
|
5750
6307
|
const interp = elts[0];
|
|
5751
|
-
const
|
|
5752
|
-
if (!
|
|
5753
|
-
add({ path:
|
|
6308
|
+
const path8 = elts[1];
|
|
6309
|
+
if (!path8.startsWith("-") && !path8.startsWith("$") && !path8.includes("/dev/")) {
|
|
6310
|
+
add({ path: path8, args: elts.slice(2), interpreter: interp });
|
|
5754
6311
|
return true;
|
|
5755
6312
|
}
|
|
5756
6313
|
}
|
|
@@ -5790,15 +6347,15 @@ function extractCallsRegex(content) {
|
|
|
5790
6347
|
let m;
|
|
5791
6348
|
while ((m = CHILD_CALL_RE.exec(content)) !== null) {
|
|
5792
6349
|
const interp = m[1];
|
|
5793
|
-
const
|
|
6350
|
+
const path8 = m[2].trim();
|
|
5794
6351
|
let rest = m[3].trim();
|
|
5795
|
-
if (
|
|
6352
|
+
if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
|
|
5796
6353
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5797
6354
|
const args = [];
|
|
5798
6355
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5799
6356
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5800
6357
|
}
|
|
5801
|
-
calls.push({ path:
|
|
6358
|
+
calls.push({ path: path8, args, interpreter: interp });
|
|
5802
6359
|
}
|
|
5803
6360
|
return calls;
|
|
5804
6361
|
}
|
|
@@ -6581,15 +7138,15 @@ function extractCallsFromContent(content) {
|
|
|
6581
7138
|
CHILD_CALL_RE2.lastIndex = 0;
|
|
6582
7139
|
while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
|
|
6583
7140
|
const interp = m[1];
|
|
6584
|
-
const
|
|
7141
|
+
const path8 = m[2].trim();
|
|
6585
7142
|
let rest = m[3].trim();
|
|
6586
|
-
if (
|
|
7143
|
+
if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
|
|
6587
7144
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
6588
7145
|
const args = [];
|
|
6589
7146
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
6590
7147
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
6591
7148
|
}
|
|
6592
|
-
calls.push({ path:
|
|
7149
|
+
calls.push({ path: path8, args, interpreter: interp });
|
|
6593
7150
|
}
|
|
6594
7151
|
return calls;
|
|
6595
7152
|
}
|
|
@@ -6658,8 +7215,8 @@ var init_backends = __esm({
|
|
|
6658
7215
|
|
|
6659
7216
|
// src/engine/script-engine/tracker.ts
|
|
6660
7217
|
import * as fs3 from "fs";
|
|
6661
|
-
import * as
|
|
6662
|
-
import * as
|
|
7218
|
+
import * as path4 from "path";
|
|
7219
|
+
import * as os2 from "os";
|
|
6663
7220
|
function maxFileSizeFromEnv() {
|
|
6664
7221
|
const raw = (process.env.AGENT_MOSS_SCRIPT_MAX_FILE_SIZE || "").trim();
|
|
6665
7222
|
if (raw) {
|
|
@@ -6678,11 +7235,11 @@ function pickBackend(pathStr) {
|
|
|
6678
7235
|
function resolvePath(p, baseDir) {
|
|
6679
7236
|
let expanded = p;
|
|
6680
7237
|
if (expanded.startsWith("~/") || expanded === "~") {
|
|
6681
|
-
expanded =
|
|
6682
|
-
} else if (!
|
|
6683
|
-
expanded =
|
|
7238
|
+
expanded = path4.join(os2.homedir(), expanded.slice(1));
|
|
7239
|
+
} else if (!path4.isAbsolute(expanded) && baseDir) {
|
|
7240
|
+
expanded = path4.join(baseDir, expanded);
|
|
6684
7241
|
}
|
|
6685
|
-
return
|
|
7242
|
+
return path4.resolve(expanded);
|
|
6686
7243
|
}
|
|
6687
7244
|
function readScript(pathStr, maxFileSize) {
|
|
6688
7245
|
try {
|
|
@@ -6776,7 +7333,7 @@ var init_tracker = __esm({
|
|
|
6776
7333
|
const baseDir = cwd || process.cwd();
|
|
6777
7334
|
const resolved = resolvePath(entryPath);
|
|
6778
7335
|
this.result.entryPath = resolved;
|
|
6779
|
-
this.visitScript(resolved, 0,
|
|
7336
|
+
this.visitScript(resolved, 0, path4.dirname(resolved), entryArgs);
|
|
6780
7337
|
const nodes = this.result.nodes;
|
|
6781
7338
|
this.result.hasCritical = nodes.some((n) => n.l1RiskLevel === "critical" || n.l2RiskLevel === "critical" || n.keywordRiskLevel === "critical") || this.result.hasCritical;
|
|
6782
7339
|
this.result.hasHigh = nodes.some((n) => ["high", "critical"].includes(n.l1RiskLevel) || ["high", "critical"].includes(n.l2RiskLevel) || ["high", "critical"].includes(n.keywordRiskLevel));
|
|
@@ -6838,12 +7395,12 @@ var init_tracker = __esm({
|
|
|
6838
7395
|
}
|
|
6839
7396
|
}
|
|
6840
7397
|
}
|
|
6841
|
-
const parentDir =
|
|
7398
|
+
const parentDir = path4.dirname(pathStr);
|
|
6842
7399
|
const childPaths = [];
|
|
6843
7400
|
for (const call of ir.calls) {
|
|
6844
7401
|
const child = resolvePath(call.path, parentDir);
|
|
6845
7402
|
childPaths.push(child);
|
|
6846
|
-
this.visitScript(child, depth + 1,
|
|
7403
|
+
this.visitScript(child, depth + 1, path4.dirname(child), call.args);
|
|
6847
7404
|
if (this.result.hasCritical) break;
|
|
6848
7405
|
}
|
|
6849
7406
|
node.childPaths = childPaths;
|
|
@@ -6855,8 +7412,8 @@ var init_tracker = __esm({
|
|
|
6855
7412
|
|
|
6856
7413
|
// src/engine/script-content-analyzer.ts
|
|
6857
7414
|
import { statSync as statSync4, existsSync as existsSync12 } from "fs";
|
|
6858
|
-
import { resolve as resolve10, join as
|
|
6859
|
-
import { homedir as
|
|
7415
|
+
import { resolve as resolve10, join as join12, isAbsolute as isAbsolute4 } from "path";
|
|
7416
|
+
import { homedir as homedir5 } from "os";
|
|
6860
7417
|
function emptyChain() {
|
|
6861
7418
|
return {
|
|
6862
7419
|
nodes: [],
|
|
@@ -7038,7 +7595,7 @@ function shlexSplit(s) {
|
|
|
7038
7595
|
function resolvePath2(p) {
|
|
7039
7596
|
let expanded = p;
|
|
7040
7597
|
if (expanded.startsWith("~/") || expanded === "~") {
|
|
7041
|
-
expanded =
|
|
7598
|
+
expanded = join12(homedir5(), expanded.slice(1));
|
|
7042
7599
|
}
|
|
7043
7600
|
return resolve10(expanded);
|
|
7044
7601
|
}
|
|
@@ -7161,8 +7718,8 @@ function analyzeScriptContent2(input, ext) {
|
|
|
7161
7718
|
resolvedPath = inline;
|
|
7162
7719
|
isInline = true;
|
|
7163
7720
|
}
|
|
7164
|
-
if (resolvedPath && !
|
|
7165
|
-
resolvedPath =
|
|
7721
|
+
if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
|
|
7722
|
+
resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
|
|
7166
7723
|
}
|
|
7167
7724
|
const l1Adapter = (content) => {
|
|
7168
7725
|
const j = scanDangerousCommandPatterns("bash", content, input.osType);
|
|
@@ -7280,7 +7837,7 @@ var init_script_content_analyzer = __esm({
|
|
|
7280
7837
|
|
|
7281
7838
|
// src/infra/trace-log.ts
|
|
7282
7839
|
import fs4 from "fs";
|
|
7283
|
-
import
|
|
7840
|
+
import path5 from "path";
|
|
7284
7841
|
function traceLevel() {
|
|
7285
7842
|
if (_levelCache !== null) return _levelCache;
|
|
7286
7843
|
const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
|
|
@@ -7307,7 +7864,7 @@ function tracePath() {
|
|
|
7307
7864
|
const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
|
|
7308
7865
|
if (explicit) return explicit;
|
|
7309
7866
|
try {
|
|
7310
|
-
return
|
|
7867
|
+
return path5.join(getDataRoot(), "agent_moss_trace.log");
|
|
7311
7868
|
} catch {
|
|
7312
7869
|
return "agent_moss_trace.log";
|
|
7313
7870
|
}
|
|
@@ -7346,7 +7903,7 @@ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
|
|
|
7346
7903
|
`;
|
|
7347
7904
|
const file = tracePath();
|
|
7348
7905
|
try {
|
|
7349
|
-
const dir =
|
|
7906
|
+
const dir = path5.dirname(file);
|
|
7350
7907
|
if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
|
|
7351
7908
|
try {
|
|
7352
7909
|
const st = fs4.statSync(file);
|
|
@@ -7942,7 +8499,7 @@ var init_token_stats = __esm({
|
|
|
7942
8499
|
|
|
7943
8500
|
// src/engine/llm-analyzer.ts
|
|
7944
8501
|
import { createHash as createHash3 } from "crypto";
|
|
7945
|
-
import { openSync as
|
|
8502
|
+
import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
|
|
7946
8503
|
import OpenAI from "openai";
|
|
7947
8504
|
function responseFieldLengths(message) {
|
|
7948
8505
|
if (!message || typeof message !== "object") return {};
|
|
@@ -8081,11 +8638,11 @@ ${prompt}
|
|
|
8081
8638
|
`;
|
|
8082
8639
|
let flags = fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_APPEND;
|
|
8083
8640
|
if (fsConstants2.O_NOFOLLOW) flags |= fsConstants2.O_NOFOLLOW;
|
|
8084
|
-
const fd =
|
|
8641
|
+
const fd = openSync3(logPath, flags, 384);
|
|
8085
8642
|
try {
|
|
8086
8643
|
writeSync2(fd, line);
|
|
8087
8644
|
} finally {
|
|
8088
|
-
|
|
8645
|
+
closeSync3(fd);
|
|
8089
8646
|
}
|
|
8090
8647
|
} catch (e) {
|
|
8091
8648
|
console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
|
|
@@ -8381,8 +8938,8 @@ var init_llm_analyzer = __esm({
|
|
|
8381
8938
|
|
|
8382
8939
|
// src/brain/rule-store.ts
|
|
8383
8940
|
import { existsSync as existsSync14, readFileSync as readFileSync14, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
|
|
8384
|
-
import { join as
|
|
8385
|
-
import { homedir as
|
|
8941
|
+
import { join as join13 } from "path";
|
|
8942
|
+
import { homedir as homedir6 } from "os";
|
|
8386
8943
|
function getRulesPath() {
|
|
8387
8944
|
const envPath = process.env[ENV_RULES_PATH];
|
|
8388
8945
|
if (envPath) return envPath;
|
|
@@ -8400,7 +8957,7 @@ var init_rule_store = __esm({
|
|
|
8400
8957
|
"src/brain/rule-store.ts"() {
|
|
8401
8958
|
"use strict";
|
|
8402
8959
|
init_esm_shims();
|
|
8403
|
-
DEFAULT_RULES_PATH =
|
|
8960
|
+
DEFAULT_RULES_PATH = join13(homedir6(), ".agentmoss", "brain", "rules.json");
|
|
8404
8961
|
ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
|
|
8405
8962
|
STATUS_DRAFT = "draft";
|
|
8406
8963
|
STATUS_APPROVED = "approved";
|
|
@@ -8412,8 +8969,8 @@ var init_rule_store = __esm({
|
|
|
8412
8969
|
BrainRuleStore = class {
|
|
8413
8970
|
path;
|
|
8414
8971
|
data;
|
|
8415
|
-
constructor(
|
|
8416
|
-
this.path =
|
|
8972
|
+
constructor(path8) {
|
|
8973
|
+
this.path = path8 || getRulesPath();
|
|
8417
8974
|
this.data = this.load();
|
|
8418
8975
|
}
|
|
8419
8976
|
load() {
|
|
@@ -8866,10 +9423,10 @@ ${reason.slice(0, 500)}
|
|
|
8866
9423
|
const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
|
|
8867
9424
|
let mm;
|
|
8868
9425
|
while ((mm = pathRe.exec(src)) !== null) {
|
|
8869
|
-
const
|
|
8870
|
-
if (
|
|
8871
|
-
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(
|
|
8872
|
-
const gen = this.generalizePath(
|
|
9426
|
+
const path8 = mm[1];
|
|
9427
|
+
if (path8.split("/").length < 3) continue;
|
|
9428
|
+
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path8)) continue;
|
|
9429
|
+
const gen = this.generalizePath(path8);
|
|
8873
9430
|
if (seen.has(gen)) continue;
|
|
8874
9431
|
seen.add(gen);
|
|
8875
9432
|
patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
|
|
@@ -8888,8 +9445,8 @@ ${reason.slice(0, 500)}
|
|
|
8888
9445
|
}
|
|
8889
9446
|
return false;
|
|
8890
9447
|
}
|
|
8891
|
-
generalizePath(
|
|
8892
|
-
const p =
|
|
9448
|
+
generalizePath(path8) {
|
|
9449
|
+
const p = path8.toLowerCase();
|
|
8893
9450
|
if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
|
|
8894
9451
|
return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
|
|
8895
9452
|
}
|
|
@@ -9016,8 +9573,8 @@ var init_reviewer = __esm({
|
|
|
9016
9573
|
|
|
9017
9574
|
// src/brain/skill-manager.ts
|
|
9018
9575
|
import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync, writeFileSync as writeFileSync4 } from "fs";
|
|
9019
|
-
import { homedir as
|
|
9020
|
-
import { join as
|
|
9576
|
+
import { homedir as homedir7 } from "os";
|
|
9577
|
+
import { join as join14 } from "path";
|
|
9021
9578
|
import { randomUUID } from "crypto";
|
|
9022
9579
|
function getMetaPath(override) {
|
|
9023
9580
|
return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
|
|
@@ -9027,14 +9584,14 @@ var init_skill_manager = __esm({
|
|
|
9027
9584
|
"src/brain/skill-manager.ts"() {
|
|
9028
9585
|
"use strict";
|
|
9029
9586
|
init_esm_shims();
|
|
9030
|
-
DEFAULT_SKILL_META_PATH =
|
|
9587
|
+
DEFAULT_SKILL_META_PATH = join14(homedir7(), ".agentmoss", "brain", "skill_meta.json");
|
|
9031
9588
|
ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
|
|
9032
9589
|
BrainSkillManager = class {
|
|
9033
9590
|
constructor(skillsDir, metaPath) {
|
|
9034
9591
|
this.skillsDir = skillsDir;
|
|
9035
9592
|
this.metaPath = getMetaPath(metaPath);
|
|
9036
9593
|
try {
|
|
9037
|
-
mkdirSync5(
|
|
9594
|
+
mkdirSync5(join14(this.metaPath, ".."), { recursive: true });
|
|
9038
9595
|
} catch {
|
|
9039
9596
|
}
|
|
9040
9597
|
this.load();
|
|
@@ -9069,7 +9626,7 @@ var init_skill_manager = __esm({
|
|
|
9069
9626
|
let changed = false;
|
|
9070
9627
|
for (const sk of this.skills) {
|
|
9071
9628
|
if (sk.status !== "active") continue;
|
|
9072
|
-
if (!existsSync15(
|
|
9629
|
+
if (!existsSync15(join14(this.skillsDir, `${sk.name}.md`))) {
|
|
9073
9630
|
sk.status = "stale";
|
|
9074
9631
|
changed = true;
|
|
9075
9632
|
}
|
|
@@ -9081,7 +9638,7 @@ var init_skill_manager = __esm({
|
|
|
9081
9638
|
const id = skill.id || randomUUID();
|
|
9082
9639
|
const name = skill.name || `brain_${id.slice(0, 8)}`;
|
|
9083
9640
|
if (!existsSync15(this.skillsDir)) return "";
|
|
9084
|
-
const mdPath =
|
|
9641
|
+
const mdPath = join14(this.skillsDir, `${name}.md`);
|
|
9085
9642
|
if (existsSync15(mdPath)) return "";
|
|
9086
9643
|
try {
|
|
9087
9644
|
writeFileSync4(mdPath, skill.content, "utf-8");
|
|
@@ -9131,7 +9688,7 @@ var init_skill_manager = __esm({
|
|
|
9131
9688
|
const out = [];
|
|
9132
9689
|
for (const sk of this.skills) {
|
|
9133
9690
|
if (sk.origin_node !== "local" || sk.status !== "active") continue;
|
|
9134
|
-
const mdPath =
|
|
9691
|
+
const mdPath = join14(this.skillsDir, `${sk.name}.md`);
|
|
9135
9692
|
if (!existsSync15(mdPath)) continue;
|
|
9136
9693
|
out.push({
|
|
9137
9694
|
name: sk.name,
|
|
@@ -9735,12 +10292,12 @@ var init_builder = __esm({
|
|
|
9735
10292
|
});
|
|
9736
10293
|
|
|
9737
10294
|
// src/engine/formal-engine/properties.ts
|
|
9738
|
-
function graphFromPath(nodes,
|
|
10295
|
+
function graphFromPath(nodes, path8, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
|
|
9739
10296
|
const byKey = /* @__PURE__ */ new Map();
|
|
9740
10297
|
for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
|
|
9741
10298
|
const gNodes = [];
|
|
9742
10299
|
const gEdges = [];
|
|
9743
|
-
for (const item of
|
|
10300
|
+
for (const item of path8) {
|
|
9744
10301
|
const n = byKey.get(`${item.sessionId}#${item.seq}`);
|
|
9745
10302
|
gNodes.push({
|
|
9746
10303
|
session_id: item.sessionId,
|
|
@@ -9806,22 +10363,22 @@ function checkCrossSessionChain(graph) {
|
|
|
9806
10363
|
if (witness !== void 0) {
|
|
9807
10364
|
if (nodes[witness].stage !== stages[stages.length - 1]) continue;
|
|
9808
10365
|
let matched = 0;
|
|
9809
|
-
const
|
|
10366
|
+
const path8 = [];
|
|
9810
10367
|
for (let k = 0; k < witness; k++) {
|
|
9811
10368
|
const n = nodes[k];
|
|
9812
10369
|
if (matched < stages.length - 1 && n.stage === stages[matched]) {
|
|
9813
10370
|
matched += 1;
|
|
9814
|
-
|
|
10371
|
+
path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9815
10372
|
}
|
|
9816
10373
|
}
|
|
9817
10374
|
if (matched < stages.length - 1) continue;
|
|
9818
|
-
|
|
10375
|
+
path8.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
|
|
9819
10376
|
violations.push({
|
|
9820
10377
|
propertyId: "cross-" + chain.id,
|
|
9821
10378
|
reason: chain.reason,
|
|
9822
10379
|
riskLevel: chain.riskLevel,
|
|
9823
|
-
path:
|
|
9824
|
-
graph: graphFromPath(nodes,
|
|
10380
|
+
path: path8,
|
|
10381
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
9825
10382
|
property_id: "cross-" + chain.id,
|
|
9826
10383
|
property_short: "P1",
|
|
9827
10384
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -9831,11 +10388,11 @@ function checkCrossSessionChain(graph) {
|
|
|
9831
10388
|
} else {
|
|
9832
10389
|
let matched = 0;
|
|
9833
10390
|
let stageIdx = 0;
|
|
9834
|
-
const
|
|
10391
|
+
const path8 = [];
|
|
9835
10392
|
for (const n of nodes) {
|
|
9836
10393
|
if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
|
|
9837
10394
|
matched += 1;
|
|
9838
|
-
|
|
10395
|
+
path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9839
10396
|
stageIdx += 1;
|
|
9840
10397
|
if (matched >= stages.length) break;
|
|
9841
10398
|
}
|
|
@@ -9845,8 +10402,8 @@ function checkCrossSessionChain(graph) {
|
|
|
9845
10402
|
propertyId: "cross-" + chain.id,
|
|
9846
10403
|
reason: chain.reason,
|
|
9847
10404
|
riskLevel: chain.riskLevel,
|
|
9848
|
-
path:
|
|
9849
|
-
graph: graphFromPath(nodes,
|
|
10405
|
+
path: path8,
|
|
10406
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
9850
10407
|
property_id: "cross-" + chain.id,
|
|
9851
10408
|
property_short: "P1",
|
|
9852
10409
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -10067,7 +10624,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10067
10624
|
if (candidates.length > 0) {
|
|
10068
10625
|
const pre = nodes[candidates[candidates.length - 1]];
|
|
10069
10626
|
const post = nodes[firstEv];
|
|
10070
|
-
const
|
|
10627
|
+
const path8 = [
|
|
10071
10628
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
10072
10629
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
10073
10630
|
];
|
|
@@ -10075,8 +10632,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10075
10632
|
propertyId: "no-exfil-after-privesc",
|
|
10076
10633
|
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",
|
|
10077
10634
|
riskLevel: "critical",
|
|
10078
|
-
path:
|
|
10079
|
-
graph: graphFromPath(nodes,
|
|
10635
|
+
path: path8,
|
|
10636
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
10080
10637
|
property_id: "no-exfil-after-privesc",
|
|
10081
10638
|
property_short: "P4",
|
|
10082
10639
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10093,7 +10650,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10093
10650
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
10094
10651
|
if (!isExfilNode(nodes[j])) continue;
|
|
10095
10652
|
if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
|
|
10096
|
-
const
|
|
10653
|
+
const path8 = [
|
|
10097
10654
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
10098
10655
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
10099
10656
|
];
|
|
@@ -10101,8 +10658,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10101
10658
|
propertyId: "no-exfil-after-privesc",
|
|
10102
10659
|
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",
|
|
10103
10660
|
riskLevel: "critical",
|
|
10104
|
-
path:
|
|
10105
|
-
graph: graphFromPath(nodes,
|
|
10661
|
+
path: path8,
|
|
10662
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
10106
10663
|
property_id: "no-exfil-after-privesc",
|
|
10107
10664
|
property_short: "P4",
|
|
10108
10665
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10134,7 +10691,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10134
10691
|
}
|
|
10135
10692
|
if (pre) {
|
|
10136
10693
|
const post = nodes[firstEv];
|
|
10137
|
-
const
|
|
10694
|
+
const path8 = [
|
|
10138
10695
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
10139
10696
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
10140
10697
|
];
|
|
@@ -10142,8 +10699,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10142
10699
|
propertyId: "no-exfil-after-credential",
|
|
10143
10700
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
10144
10701
|
riskLevel: "critical",
|
|
10145
|
-
path:
|
|
10146
|
-
graph: graphFromPath(nodes,
|
|
10702
|
+
path: path8,
|
|
10703
|
+
graph: graphFromPath(nodes, path8, "data", {
|
|
10147
10704
|
property_id: "no-exfil-after-credential",
|
|
10148
10705
|
property_short: "P5",
|
|
10149
10706
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10159,7 +10716,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10159
10716
|
if (!isCredNode(nodes[i])) continue;
|
|
10160
10717
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
10161
10718
|
if (isExfilNode(nodes[j])) {
|
|
10162
|
-
const
|
|
10719
|
+
const path8 = [
|
|
10163
10720
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
10164
10721
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
10165
10722
|
];
|
|
@@ -10167,8 +10724,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10167
10724
|
propertyId: "no-exfil-after-credential",
|
|
10168
10725
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
10169
10726
|
riskLevel: "critical",
|
|
10170
|
-
path:
|
|
10171
|
-
graph: graphFromPath(nodes,
|
|
10727
|
+
path: path8,
|
|
10728
|
+
graph: graphFromPath(nodes, path8, "data", {
|
|
10172
10729
|
property_id: "no-exfil-after-credential",
|
|
10173
10730
|
property_short: "P5",
|
|
10174
10731
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10327,13 +10884,13 @@ function checkSensitiveDataAggregation(graph) {
|
|
|
10327
10884
|
if (!isExfilNode(n)) continue;
|
|
10328
10885
|
const srcs = sourcesFor(i);
|
|
10329
10886
|
if (srcs.size >= 2) {
|
|
10330
|
-
const
|
|
10887
|
+
const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
10331
10888
|
violations.push({
|
|
10332
10889
|
propertyId: "sensitive-data-aggregation",
|
|
10333
10890
|
reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
|
|
10334
10891
|
riskLevel: "critical",
|
|
10335
|
-
path:
|
|
10336
|
-
graph: graphFromPath(nodes,
|
|
10892
|
+
path: path8,
|
|
10893
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
10337
10894
|
property_id: "sensitive-data-aggregation",
|
|
10338
10895
|
property_short: "P8",
|
|
10339
10896
|
property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
|
|
@@ -10792,11 +11349,11 @@ var init_stateful = __esm({
|
|
|
10792
11349
|
}
|
|
10793
11350
|
}
|
|
10794
11351
|
chainPath(stages) {
|
|
10795
|
-
const
|
|
11352
|
+
const path8 = [];
|
|
10796
11353
|
let want = stages[0];
|
|
10797
11354
|
for (const n of this.nodes_) {
|
|
10798
11355
|
if (n.stage === want) {
|
|
10799
|
-
|
|
11356
|
+
path8.push({
|
|
10800
11357
|
sessionId: n.sessionId,
|
|
10801
11358
|
seq: n.seq,
|
|
10802
11359
|
stage: n.stage,
|
|
@@ -10812,12 +11369,12 @@ var init_stateful = __esm({
|
|
|
10812
11369
|
}
|
|
10813
11370
|
}
|
|
10814
11371
|
}
|
|
10815
|
-
return
|
|
11372
|
+
return path8;
|
|
10816
11373
|
}
|
|
10817
11374
|
/** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
|
|
10818
11375
|
buildChainGraph(stages, chainId) {
|
|
10819
|
-
const
|
|
10820
|
-
const gNodes =
|
|
11376
|
+
const path8 = this.chainPath(stages);
|
|
11377
|
+
const gNodes = path8.map((p, i) => {
|
|
10821
11378
|
const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
|
|
10822
11379
|
return {
|
|
10823
11380
|
session_id: p.sessionId,
|
|
@@ -11069,13 +11626,13 @@ var init_stateful = __esm({
|
|
|
11069
11626
|
|
|
11070
11627
|
// src/engine/formal-engine/chain_state.ts
|
|
11071
11628
|
import * as fs5 from "fs";
|
|
11072
|
-
import * as
|
|
11073
|
-
import * as
|
|
11629
|
+
import * as os3 from "os";
|
|
11630
|
+
import * as path6 from "path";
|
|
11074
11631
|
import { createHash as createHash4 } from "crypto";
|
|
11075
11632
|
function defaultStateDbPath() {
|
|
11076
|
-
const dir = process.env.AGENT_MOSS_STATE_DIR ||
|
|
11633
|
+
const dir = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
|
|
11077
11634
|
const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
|
|
11078
|
-
return
|
|
11635
|
+
return path6.join(dir, `stateful_chains_${tag}.json`);
|
|
11079
11636
|
}
|
|
11080
11637
|
function registerExitFlush(store) {
|
|
11081
11638
|
if (_exitHookRegistered) return;
|
|
@@ -11161,7 +11718,7 @@ var init_chain_state = __esm({
|
|
|
11161
11718
|
this._timer = null;
|
|
11162
11719
|
try {
|
|
11163
11720
|
this._syncDirtyToData();
|
|
11164
|
-
ensurePrivateDir(
|
|
11721
|
+
ensurePrivateDir(path6.dirname(this.filePath));
|
|
11165
11722
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
11166
11723
|
} catch {
|
|
11167
11724
|
}
|
|
@@ -11184,7 +11741,7 @@ var init_chain_state = __esm({
|
|
|
11184
11741
|
}
|
|
11185
11742
|
try {
|
|
11186
11743
|
this._syncDirtyToData();
|
|
11187
|
-
ensurePrivateDir(
|
|
11744
|
+
ensurePrivateDir(path6.dirname(this.filePath));
|
|
11188
11745
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
11189
11746
|
} catch {
|
|
11190
11747
|
}
|
|
@@ -11252,7 +11809,7 @@ var init_chain_state = __esm({
|
|
|
11252
11809
|
_flushNow() {
|
|
11253
11810
|
this._syncDirtyToData();
|
|
11254
11811
|
try {
|
|
11255
|
-
const _dirOk = ensurePrivateDir(
|
|
11812
|
+
const _dirOk = ensurePrivateDir(path6.dirname(this.filePath));
|
|
11256
11813
|
const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
11257
11814
|
if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
|
|
11258
11815
|
} catch (e) {
|
|
@@ -11549,7 +12106,7 @@ async function runAnalysis(input) {
|
|
|
11549
12106
|
skipLLM = true;
|
|
11550
12107
|
}
|
|
11551
12108
|
}
|
|
11552
|
-
const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
|
|
12109
|
+
const logicResult = isLogicRulesEnabled() ? runLogicCheck(input, { agentExt }) : null;
|
|
11553
12110
|
if (logicResult) {
|
|
11554
12111
|
traceSummary("l2.result", {
|
|
11555
12112
|
hit: !logicResult.allowed,
|
|
@@ -12105,7 +12662,7 @@ init_security_policy();
|
|
|
12105
12662
|
init_coordinator();
|
|
12106
12663
|
import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
|
|
12107
12664
|
import { tmpdir as tmpdir3 } from "os";
|
|
12108
|
-
import { join as
|
|
12665
|
+
import { join as join17, resolve as resolve11 } from "path";
|
|
12109
12666
|
|
|
12110
12667
|
// src/infra/policy-cache.ts
|
|
12111
12668
|
init_esm_shims();
|
|
@@ -12115,8 +12672,8 @@ init_config();
|
|
|
12115
12672
|
import { createHash as createHash5 } from "crypto";
|
|
12116
12673
|
import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
|
|
12117
12674
|
import { tmpdir as tmpdir2 } from "os";
|
|
12118
|
-
import { join as
|
|
12119
|
-
var CACHE_DIR =
|
|
12675
|
+
import { join as join16 } from "path";
|
|
12676
|
+
var CACHE_DIR = join16(tmpdir2(), "agent_moss_policy_cache");
|
|
12120
12677
|
var cacheDirOverride = null;
|
|
12121
12678
|
function cacheDir() {
|
|
12122
12679
|
return cacheDirOverride ?? CACHE_DIR;
|
|
@@ -12125,7 +12682,7 @@ function safeCacheDir() {
|
|
|
12125
12682
|
const dir = cacheDir();
|
|
12126
12683
|
if (ensurePrivateDir(dir)) return dir;
|
|
12127
12684
|
try {
|
|
12128
|
-
const fallback =
|
|
12685
|
+
const fallback = join16(getDataRoot(), "policy_cache");
|
|
12129
12686
|
if (ensurePrivateDir(fallback)) {
|
|
12130
12687
|
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}`);
|
|
12131
12688
|
return fallback;
|
|
@@ -12147,7 +12704,7 @@ var PolicyCache = class {
|
|
|
12147
12704
|
cacheFilePath(sessionId, promptSession) {
|
|
12148
12705
|
const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
|
|
12149
12706
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12150
|
-
return
|
|
12707
|
+
return join16(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
|
|
12151
12708
|
}
|
|
12152
12709
|
/** 取缓存:内存 → 文件;未命中返回 null。 */
|
|
12153
12710
|
get(sessionId, promptSession) {
|
|
@@ -12178,7 +12735,7 @@ var PolicyCache = class {
|
|
|
12178
12735
|
try {
|
|
12179
12736
|
const dir = safeCacheDir();
|
|
12180
12737
|
const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12181
|
-
if (!ensurePrivateDir(
|
|
12738
|
+
if (!ensurePrivateDir(join16(dir, sub))) return;
|
|
12182
12739
|
writePrivateText(file, policy);
|
|
12183
12740
|
} catch {
|
|
12184
12741
|
}
|
|
@@ -12204,12 +12761,12 @@ var PolicyCache = class {
|
|
|
12204
12761
|
if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
|
|
12205
12762
|
}
|
|
12206
12763
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12207
|
-
const dir =
|
|
12764
|
+
const dir = join16(cacheDir(), safeSessionId);
|
|
12208
12765
|
try {
|
|
12209
12766
|
if (existsSync17(dir)) {
|
|
12210
12767
|
for (const f of readdirSync5(dir)) {
|
|
12211
12768
|
try {
|
|
12212
|
-
unlinkSync4(
|
|
12769
|
+
unlinkSync4(join16(dir, f));
|
|
12213
12770
|
} catch {
|
|
12214
12771
|
}
|
|
12215
12772
|
}
|
|
@@ -12223,9 +12780,9 @@ var PolicyCache = class {
|
|
|
12223
12780
|
try {
|
|
12224
12781
|
if (existsSync17(cacheDir())) {
|
|
12225
12782
|
for (const sessionDir of readdirSync5(cacheDir())) {
|
|
12226
|
-
const dir =
|
|
12783
|
+
const dir = join16(cacheDir(), sessionDir);
|
|
12227
12784
|
try {
|
|
12228
|
-
for (const f of readdirSync5(dir)) unlinkSync4(
|
|
12785
|
+
for (const f of readdirSync5(dir)) unlinkSync4(join16(dir, f));
|
|
12229
12786
|
rmdirSync(dir);
|
|
12230
12787
|
} catch {
|
|
12231
12788
|
}
|
|
@@ -12312,7 +12869,7 @@ ${safe(policy, 2e3)}`);
|
|
|
12312
12869
|
|
|
12313
12870
|
// src/engine/analyzer.ts
|
|
12314
12871
|
import { parse as parseToml } from "smol-toml";
|
|
12315
|
-
var POLICY_OUTPUT_DIR =
|
|
12872
|
+
var POLICY_OUTPUT_DIR = join17(tmpdir3(), "agent_moss");
|
|
12316
12873
|
var policyOutputDirOverride = null;
|
|
12317
12874
|
function policyOutputDir() {
|
|
12318
12875
|
return policyOutputDirOverride ?? POLICY_OUTPUT_DIR;
|
|
@@ -12351,7 +12908,7 @@ function savePolicyToFile(sessionId, policyToml) {
|
|
|
12351
12908
|
return null;
|
|
12352
12909
|
}
|
|
12353
12910
|
const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12354
|
-
const filepath =
|
|
12911
|
+
const filepath = join17(outDir, `${safeName}.toml`);
|
|
12355
12912
|
writePrivateText(filepath, policyToml);
|
|
12356
12913
|
return filepath;
|
|
12357
12914
|
} catch (err) {
|
|
@@ -12752,10 +13309,10 @@ function mineDangerousPatterns(sessions, minSup = 2, maxLen = 4) {
|
|
|
12752
13309
|
// src/agent-gate-reader.ts
|
|
12753
13310
|
init_esm_shims();
|
|
12754
13311
|
import * as fs7 from "fs";
|
|
12755
|
-
import * as
|
|
12756
|
-
import * as
|
|
12757
|
-
var DEFAULT_AGENTGATE_SQLITE =
|
|
12758
|
-
|
|
13312
|
+
import * as os4 from "os";
|
|
13313
|
+
import * as path7 from "path";
|
|
13314
|
+
var DEFAULT_AGENTGATE_SQLITE = path7.join(
|
|
13315
|
+
os4.homedir(),
|
|
12759
13316
|
".local",
|
|
12760
13317
|
"share",
|
|
12761
13318
|
"agent_gate",
|
|
@@ -12773,7 +13330,7 @@ function readJsonDir(dirPath, limit = 1e5) {
|
|
|
12773
13330
|
const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
|
|
12774
13331
|
for (const f of files.slice(-200)) {
|
|
12775
13332
|
const sid = f.replace(/\.json$/, "");
|
|
12776
|
-
const raw = fs7.readFileSync(
|
|
13333
|
+
const raw = fs7.readFileSync(path7.join(dirPath, f), "utf-8");
|
|
12777
13334
|
const arr = JSON.parse(raw);
|
|
12778
13335
|
if (!Array.isArray(arr)) continue;
|
|
12779
13336
|
for (const item of arr) {
|
|
@@ -12841,7 +13398,7 @@ function loadAgentGateSessions(dbPath = "") {
|
|
|
12841
13398
|
}
|
|
12842
13399
|
const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
|
|
12843
13400
|
if (sql.length > 0) return sql;
|
|
12844
|
-
const jsonDefault =
|
|
13401
|
+
const jsonDefault = path7.join(os4.homedir(), ".local", "share", "agent_gate", "tool_calls");
|
|
12845
13402
|
return readJsonDir(jsonDefault);
|
|
12846
13403
|
}
|
|
12847
13404
|
|
|
@@ -12965,7 +13522,7 @@ function poolsSnapshot() {
|
|
|
12965
13522
|
|
|
12966
13523
|
// src/routes.ts
|
|
12967
13524
|
init_metrics();
|
|
12968
|
-
import { join as
|
|
13525
|
+
import { join as join19, dirname as dirname12 } from "path";
|
|
12969
13526
|
import { fileURLToPath as fileURLToPath10 } from "url";
|
|
12970
13527
|
var __dirname9 = dirname12(fileURLToPath10(import.meta.url));
|
|
12971
13528
|
async function healthRoute(c) {
|
|
@@ -13365,7 +13922,7 @@ function getBrainRuleStore() {
|
|
|
13365
13922
|
return new BrainRuleStore();
|
|
13366
13923
|
}
|
|
13367
13924
|
function getBrainSkillManager() {
|
|
13368
|
-
const dir = resolveAssetDir(__dirname9, "skills") ??
|
|
13925
|
+
const dir = resolveAssetDir(__dirname9, "skills") ?? join19(__dirname9, "..", "..", "agent_moss", "skills");
|
|
13369
13926
|
return new BrainSkillManager(dir);
|
|
13370
13927
|
}
|
|
13371
13928
|
async function brainRulesRoute(c) {
|
|
@@ -13470,10 +14027,10 @@ init_rules_mode();
|
|
|
13470
14027
|
import { Hono } from "hono";
|
|
13471
14028
|
import { timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
13472
14029
|
import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
|
|
13473
|
-
import { join as
|
|
14030
|
+
import { join as join20, dirname as dirname13 } from "path";
|
|
13474
14031
|
import { fileURLToPath as fileURLToPath11 } from "url";
|
|
13475
14032
|
var __dirname10 = dirname13(fileURLToPath11(import.meta.url));
|
|
13476
|
-
var STATIC_DIR =
|
|
14033
|
+
var STATIC_DIR = join20(__dirname10, "static");
|
|
13477
14034
|
var CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
|
|
13478
14035
|
function getConsoleToken() {
|
|
13479
14036
|
return process.env[CONSOLE_TOKEN_ENV] || "";
|
|
@@ -13515,7 +14072,7 @@ function createConsoleRouter() {
|
|
|
13515
14072
|
console2.use("/api/*", authMiddleware());
|
|
13516
14073
|
console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
|
|
13517
14074
|
const serveIndex = (c) => {
|
|
13518
|
-
const indexFile =
|
|
14075
|
+
const indexFile = join20(STATIC_DIR, "index.html");
|
|
13519
14076
|
if (existsSync20(indexFile)) {
|
|
13520
14077
|
return c.html(readFileSync20(indexFile, "utf-8"));
|
|
13521
14078
|
}
|
|
@@ -13712,11 +14269,11 @@ function createConsoleRouter() {
|
|
|
13712
14269
|
if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
|
|
13713
14270
|
return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
|
|
13714
14271
|
}
|
|
13715
|
-
const userPath =
|
|
14272
|
+
const userPath = join20(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
|
|
13716
14273
|
const builtinDir = resolveAssetDir(__dirname10, "skills");
|
|
13717
14274
|
const candidates = [
|
|
13718
14275
|
...isRuntimeConfigDisabled() ? [] : [userPath],
|
|
13719
|
-
builtinDir ?
|
|
14276
|
+
builtinDir ? join20(builtinDir, `${skillId}.md`) : ""
|
|
13720
14277
|
].filter(Boolean);
|
|
13721
14278
|
for (const p of candidates) {
|
|
13722
14279
|
if (existsSync20(p)) {
|
|
@@ -13986,7 +14543,7 @@ function createApp() {
|
|
|
13986
14543
|
startLoopMonitor();
|
|
13987
14544
|
const limiter = new RateLimiter(rateLimitQps());
|
|
13988
14545
|
app.use("*", async (c, next) => {
|
|
13989
|
-
const
|
|
14546
|
+
const path8 = new URL(c.req.url).pathname;
|
|
13990
14547
|
const method = c.req.method.toUpperCase();
|
|
13991
14548
|
if (method === "OPTIONS") return next();
|
|
13992
14549
|
const maxBody = maxBodyBytes();
|
|
@@ -14000,16 +14557,16 @@ function createApp() {
|
|
|
14000
14557
|
if (originCheckEnabled()) {
|
|
14001
14558
|
const origin = c.req.header("origin") || "";
|
|
14002
14559
|
if (origin && !originAllowed(origin, c.req.header("host") || "")) {
|
|
14003
|
-
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${
|
|
14560
|
+
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path8}`);
|
|
14004
14561
|
return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
|
|
14005
14562
|
}
|
|
14006
14563
|
}
|
|
14007
|
-
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers,
|
|
14008
|
-
const isPublicPage = !
|
|
14564
|
+
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path8);
|
|
14565
|
+
const isPublicPage = !path8.startsWith("/console/api") && (path8 === "/console" || path8.startsWith("/console/"));
|
|
14009
14566
|
if (!okAuth && !isPublicPage) {
|
|
14010
14567
|
return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
|
|
14011
14568
|
}
|
|
14012
|
-
if (limiter.enabled &&
|
|
14569
|
+
if (limiter.enabled && path8.startsWith("/api/")) {
|
|
14013
14570
|
const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
|
|
14014
14571
|
if (!limiter.allow(key)) {
|
|
14015
14572
|
return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
|
|
@@ -14043,7 +14600,7 @@ function createApp() {
|
|
|
14043
14600
|
return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
|
|
14044
14601
|
}
|
|
14045
14602
|
}
|
|
14046
|
-
const pool = poolOf(
|
|
14603
|
+
const pool = poolOf(path8);
|
|
14047
14604
|
if (!take(`pool:${pool}`, poolLimit(pool))) {
|
|
14048
14605
|
const qkey = principal ? "p:" + principalHash(principal) : "c:local";
|
|
14049
14606
|
const [qn, abusive] = noteQueueReject(qkey);
|