@kenhkl/agent-moss 0.17.24 → 0.17.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/opendesk/rules.json +5 -0
- package/dist/cli.js +550 -266
- package/dist/engine/coordinator.js +461 -177
- package/dist/rules/l2_rules.json +4 -2
- package/dist/rules/logic_rules.json +65 -1
- package/dist/server.js +516 -232
- 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,7 +1962,8 @@ 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";
|
|
@@ -1802,7 +2004,11 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1802
2004
|
const SOURCE_ARG_CMDS = new Set(_LOGIC.source_arg_commands ?? []);
|
|
1803
2005
|
const REDIRECT_TARGET_RE = new RegExp(`>{1,2}\\s*(?!&)(?:'(/[^']+)'|"(/[^\\"]+)"|(/[^\\s;|&><'\\"]+))`);
|
|
1804
2006
|
const targetPaths = [];
|
|
1805
|
-
|
|
2007
|
+
const singleFileTool = singleFileTools.has(actionType);
|
|
2008
|
+
if (singleFileTool && MISSING_WRITE_PATH_RE.test(actionDetailRaw)) {
|
|
2009
|
+
return null;
|
|
2010
|
+
}
|
|
2011
|
+
for (const seg of singleFileTool ? [] : splitCommandSegments(actionDetailRaw)) {
|
|
1806
2012
|
const trimmed = seg.trim();
|
|
1807
2013
|
if (!trimmed) continue;
|
|
1808
2014
|
const firstWord = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
|
|
@@ -1834,16 +2040,31 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1834
2040
|
targetPaths.push(...segPathsFiltered);
|
|
1835
2041
|
}
|
|
1836
2042
|
}
|
|
2043
|
+
if (singleFileTool) {
|
|
2044
|
+
targetPaths.length = 0;
|
|
2045
|
+
targetPaths.push(...declaredWritePaths(actionDetailRaw, osType));
|
|
2046
|
+
}
|
|
1837
2047
|
const uniqueTargetPaths = [...new Set(targetPaths)].filter((p) => !PSEUDO_FS_PREFIXES.some((pfx) => p.startsWith(pfx)));
|
|
1838
2048
|
if (uniqueTargetPaths.length === 0) return null;
|
|
1839
|
-
const
|
|
2049
|
+
const historyFullReadPaths = /* @__PURE__ */ new Set();
|
|
2050
|
+
const historyPartialRead = /* @__PURE__ */ new Map();
|
|
1840
2051
|
for (const action of actionHistory) {
|
|
1841
|
-
const
|
|
2052
|
+
const histDetailRaw = action.actionDetail;
|
|
1842
2053
|
const histType = action.actionType.toLowerCase();
|
|
1843
|
-
const
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
2054
|
+
const traits = getPlatformTraits(osType);
|
|
2055
|
+
const coverage = historyReadCoverage(
|
|
2056
|
+
histType,
|
|
2057
|
+
histDetailRaw,
|
|
2058
|
+
traits.readKeywords,
|
|
2059
|
+
traits.writeKeywords
|
|
2060
|
+
);
|
|
2061
|
+
for (const p of coverage.full) historyFullReadPaths.add(p);
|
|
2062
|
+
for (const [p, upto] of coverage.partial) {
|
|
2063
|
+
if (historyPartialRead.has(p)) {
|
|
2064
|
+
const old = historyPartialRead.get(p);
|
|
2065
|
+
historyPartialRead.set(p, old == null || upto == null ? null : Math.max(old, upto));
|
|
2066
|
+
} else {
|
|
2067
|
+
historyPartialRead.set(p, upto);
|
|
1847
2068
|
}
|
|
1848
2069
|
}
|
|
1849
2070
|
}
|
|
@@ -1856,18 +2077,49 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1856
2077
|
if (filteredPaths.length === 0) {
|
|
1857
2078
|
return null;
|
|
1858
2079
|
}
|
|
2080
|
+
const normalizedTargets = filteredPaths.map((p) => normalizePathForCompare(p, cwd)).filter((p, i, arr) => p && arr.indexOf(p) === i);
|
|
2081
|
+
const normalizedFullReads = new Set(
|
|
2082
|
+
[...historyFullReadPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
|
|
2083
|
+
);
|
|
2084
|
+
const normalizedPartialReads = /* @__PURE__ */ new Map();
|
|
2085
|
+
for (const [p, upto] of historyPartialRead) {
|
|
2086
|
+
const np = normalizePathForCompare(p, cwd);
|
|
2087
|
+
if (np) normalizedPartialReads.set(np, upto);
|
|
2088
|
+
}
|
|
2089
|
+
const appendTargets = appendOnlyTargets(actionDetailRaw, osType);
|
|
2090
|
+
if (APPEND_MODE_RE.test(actionDetailRaw)) {
|
|
2091
|
+
for (const p of filteredPaths) appendTargets.add(p);
|
|
2092
|
+
}
|
|
2093
|
+
let checkTargets = normalizedTargets;
|
|
2094
|
+
if (appendTargets.size > 0) {
|
|
2095
|
+
const appendNorm = new Set(
|
|
2096
|
+
[...appendTargets].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
|
|
2097
|
+
);
|
|
2098
|
+
checkTargets = normalizedTargets.filter((p) => !([...appendNorm].some((ap) => pathIsSameOrUnder(p, ap) || pathIsSameOrUnder(ap, p)) && !isProtectedWritePath(p)));
|
|
2099
|
+
if (checkTargets.length === 0) return null;
|
|
2100
|
+
}
|
|
1859
2101
|
const unreadPaths = [];
|
|
1860
|
-
for (const
|
|
1861
|
-
const
|
|
1862
|
-
(rp) =>
|
|
2102
|
+
for (const path8 of checkTargets) {
|
|
2103
|
+
const isFullRead = [...normalizedFullReads].some(
|
|
2104
|
+
(rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
|
|
1863
2105
|
);
|
|
1864
|
-
|
|
1865
|
-
|
|
2106
|
+
let isPartialCovered = false;
|
|
2107
|
+
if (!isFullRead) {
|
|
2108
|
+
for (const [pp, upto] of normalizedPartialReads) {
|
|
2109
|
+
if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
|
|
2110
|
+
if (upto != null && fileHasAtMostLines(path8, upto)) {
|
|
2111
|
+
isPartialCovered = true;
|
|
2112
|
+
break;
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
if (!isFullRead && !isPartialCovered) {
|
|
2117
|
+
let isCreate = !fs.existsSync(path8);
|
|
1866
2118
|
if (!isCreate) {
|
|
1867
2119
|
isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
|
|
1868
2120
|
}
|
|
1869
2121
|
if (!isCreate) {
|
|
1870
|
-
unreadPaths.push(
|
|
2122
|
+
unreadPaths.push(path8);
|
|
1871
2123
|
}
|
|
1872
2124
|
}
|
|
1873
2125
|
}
|
|
@@ -2044,7 +2296,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
|
|
|
2044
2296
|
violatedLayers: ["L2.1"]
|
|
2045
2297
|
};
|
|
2046
2298
|
}
|
|
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;
|
|
2299
|
+
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
2300
|
var init_logic_rules = __esm({
|
|
2049
2301
|
"src/engine/logic-rules.ts"() {
|
|
2050
2302
|
"use strict";
|
|
@@ -2061,16 +2313,16 @@ var init_logic_rules = __esm({
|
|
|
2061
2313
|
ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
|
|
2062
2314
|
ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
|
|
2063
2315
|
HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
|
|
2064
|
-
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path:
|
|
2316
|
+
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2065
2317
|
ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
|
|
2066
2318
|
HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
|
|
2067
|
-
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path:
|
|
2319
|
+
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2068
2320
|
ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
|
|
2069
2321
|
HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
|
|
2070
|
-
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path:
|
|
2322
|
+
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2071
2323
|
ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
|
|
2072
2324
|
HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
|
|
2073
|
-
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path:
|
|
2325
|
+
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2074
2326
|
_scopeIndex = null;
|
|
2075
2327
|
NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
|
|
2076
2328
|
"ask_user_question",
|
|
@@ -2093,6 +2345,23 @@ var init_logic_rules = __esm({
|
|
|
2093
2345
|
]);
|
|
2094
2346
|
NON_WRITE_TOOL_PREFIXES = _LOGIC.non_write_tool_prefixes ?? [];
|
|
2095
2347
|
PSEUDO_FS_PREFIXES = ["/sys/", "/proc/", "/dev/", "/run/"];
|
|
2348
|
+
SINGLE_FILE_WRITE_TOOLS = new Set(
|
|
2349
|
+
_LOGIC.single_file_write_tools ?? []
|
|
2350
|
+
);
|
|
2351
|
+
WRITE_INTENT_KEYWORDS = _LOGIC.write_intent_keywords ?? [];
|
|
2352
|
+
MISSING_WRITE_PATH_RE = /(?:写入文件|编辑文件|写入|编辑)\s*[::]\s*\?/;
|
|
2353
|
+
DECLARED_WRITE_PATH_RE = /(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*([~./][^\s—|,;]+)/;
|
|
2354
|
+
DECLARED_WRITE_PATH_JSON_RE = /"(?:file_path|filePath|path)"\s*:\s*"([^"]+)"/;
|
|
2355
|
+
PROTECTED_WRITE_PREFIXES = _LOGIC.protected_write_prefixes ?? [];
|
|
2356
|
+
PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
|
|
2357
|
+
APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
|
|
2358
|
+
APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
|
|
2359
|
+
SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
|
|
2360
|
+
SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
|
|
2361
|
+
SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
|
|
2362
|
+
HEAD_TAIL_LIMIT_RE = /(?:-n\s*|-\s*)(\d+)/;
|
|
2363
|
+
SED_RANGE_RE = /-n\s+['"]?(\d+)\s*,\s*(\d+|\$)\s*p/;
|
|
2364
|
+
PARTIAL_COVER_CHECK_MAX_LINES = 1e5;
|
|
2096
2365
|
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
2366
|
SED_INPLACE_RE = /\bsed\s+(?:-\S+\s+)*(?:-[a-zA-Z]*i[a-zA-Z]*|--in-place)\b/i;
|
|
2098
2367
|
DEVNULL_REDIRECT_RE = /(?:2|&|1)?\s*>\s*\/dev\/null\b/g;
|
|
@@ -2111,7 +2380,8 @@ var init_logic_rules = __esm({
|
|
|
2111
2380
|
intentKeywords: p.intent_keywords,
|
|
2112
2381
|
dangerousActions: p.dangerous_actions,
|
|
2113
2382
|
reason: p.reason,
|
|
2114
|
-
os: String(p.os || "linux").toLowerCase()
|
|
2383
|
+
os: String(p.os || "linux").toLowerCase(),
|
|
2384
|
+
allowIfWriteIntent: p.allow_if_write_intent === true
|
|
2115
2385
|
}));
|
|
2116
2386
|
})();
|
|
2117
2387
|
COMBO_STAGES = (() => {
|
|
@@ -2152,11 +2422,11 @@ var init_logic_rules = __esm({
|
|
|
2152
2422
|
|
|
2153
2423
|
// src/engine/asset-dir.ts
|
|
2154
2424
|
import { existsSync as existsSync5 } from "fs";
|
|
2155
|
-
import { join as
|
|
2425
|
+
import { join as join6, resolve as resolve3 } from "path";
|
|
2156
2426
|
function assetDirCandidates(moduleDir, name) {
|
|
2157
2427
|
const root = getRulesRoot();
|
|
2158
2428
|
if (root) {
|
|
2159
|
-
const p =
|
|
2429
|
+
const p = join6(root, name);
|
|
2160
2430
|
return [p, p];
|
|
2161
2431
|
}
|
|
2162
2432
|
return [
|
|
@@ -2375,7 +2645,7 @@ __export(runtime_config_exports, {
|
|
|
2375
2645
|
updateSkillEnabled: () => updateSkillEnabled
|
|
2376
2646
|
});
|
|
2377
2647
|
import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
|
|
2378
|
-
import { join as
|
|
2648
|
+
import { join as join7 } from "path";
|
|
2379
2649
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
2380
2650
|
import { dirname as dirname4 } from "path";
|
|
2381
2651
|
function runtimeDir() {
|
|
@@ -2511,8 +2781,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
|
|
|
2511
2781
|
function _filterRulesByOs(rules, osType) {
|
|
2512
2782
|
const accepted = acceptedOsValues(osType);
|
|
2513
2783
|
return rules.filter((r) => {
|
|
2514
|
-
const
|
|
2515
|
-
return
|
|
2784
|
+
const os5 = String(r.os || "linux").toLowerCase();
|
|
2785
|
+
return os5 === "all" || accepted.includes(os5);
|
|
2516
2786
|
});
|
|
2517
2787
|
}
|
|
2518
2788
|
function _userCustomRules(runtime, layers, requiredKey) {
|
|
@@ -2714,7 +2984,7 @@ function _l2SensitivePathsToRules() {
|
|
|
2714
2984
|
const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
|
|
2715
2985
|
const all = [...root, ...home, ...credential];
|
|
2716
2986
|
for (const sp of all) {
|
|
2717
|
-
const
|
|
2987
|
+
const os5 = String(sp.os || "linux").toLowerCase();
|
|
2718
2988
|
const denyMode = sp.denyMode || _deriveDenyMode({
|
|
2719
2989
|
deny_mode: sp.deny_mode,
|
|
2720
2990
|
credential: sp.credential,
|
|
@@ -2724,7 +2994,7 @@ function _l2SensitivePathsToRules() {
|
|
|
2724
2994
|
// id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
|
|
2725
2995
|
// hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
|
|
2726
2996
|
// Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
|
|
2727
|
-
id: `path_${
|
|
2997
|
+
id: `path_${os5}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
|
|
2728
2998
|
path: sp.path,
|
|
2729
2999
|
risk_level: sp.riskLevel,
|
|
2730
3000
|
desc: sp.desc,
|
|
@@ -2733,7 +3003,7 @@ function _l2SensitivePathsToRules() {
|
|
|
2733
3003
|
skip_l3_on_disabled: true,
|
|
2734
3004
|
enabled: true,
|
|
2735
3005
|
builtin: true,
|
|
2736
|
-
os:
|
|
3006
|
+
os: os5
|
|
2737
3007
|
};
|
|
2738
3008
|
_syncDenyModeFields(rule);
|
|
2739
3009
|
if (sp.dirDelOnly) rule.dir_del_only = true;
|
|
@@ -2751,6 +3021,9 @@ function _l2IntentPatternsToRules() {
|
|
|
2751
3021
|
intent_keywords: pat.intentKeywords,
|
|
2752
3022
|
dangerous_actions: pat.dangerousActions,
|
|
2753
3023
|
reason: pat.reason,
|
|
3024
|
+
// 旧 runtime 里没有这个字段:缺省 false,但 getIntentPatternsForOs 会按
|
|
3025
|
+
// reason 回填内置默认值,避免旧配置让新豁免失效。
|
|
3026
|
+
allow_if_write_intent: pat.allowIfWriteIntent,
|
|
2754
3027
|
skip_l3_on_disabled: true,
|
|
2755
3028
|
enabled: true,
|
|
2756
3029
|
builtin: true
|
|
@@ -2821,7 +3094,7 @@ function _l3SkillsToRules() {
|
|
|
2821
3094
|
function _scenarioRulesToDefaults() {
|
|
2822
3095
|
const out = {};
|
|
2823
3096
|
const _root = getRulesRoot();
|
|
2824
|
-
const scenDir = _root ?
|
|
3097
|
+
const scenDir = _root ? join7(_root, "scenarios") : existsSync7(_SCENARIOS_DIR_PROD) ? _SCENARIOS_DIR_PROD : existsSync7(_SCENARIOS_DIR_DEV) ? _SCENARIOS_DIR_DEV : _SCENARIOS_DIR_PROD;
|
|
2825
3098
|
if (!existsSync7(scenDir)) return out;
|
|
2826
3099
|
let entries;
|
|
2827
3100
|
try {
|
|
@@ -2830,7 +3103,7 @@ function _scenarioRulesToDefaults() {
|
|
|
2830
3103
|
return out;
|
|
2831
3104
|
}
|
|
2832
3105
|
for (const scenarioId of entries) {
|
|
2833
|
-
const rulesFile = resolveScenarioRulesFile(scenarioId) ??
|
|
3106
|
+
const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join7(scenDir, scenarioId, "rules.json");
|
|
2834
3107
|
if (!existsSync7(rulesFile)) continue;
|
|
2835
3108
|
let data;
|
|
2836
3109
|
try {
|
|
@@ -2871,7 +3144,7 @@ function _scenarioRulesToDefaults() {
|
|
|
2871
3144
|
function _agentRulesToDefaults() {
|
|
2872
3145
|
const out = {};
|
|
2873
3146
|
const _root = getRulesRoot();
|
|
2874
|
-
const agentsDir = _root ?
|
|
3147
|
+
const agentsDir = _root ? join7(_root, "agents") : existsSync7(_AGENTS_DIR_PROD) ? _AGENTS_DIR_PROD : existsSync7(_AGENTS_DIR_DEV) ? _AGENTS_DIR_DEV : _AGENTS_DIR_PROD;
|
|
2875
3148
|
if (!existsSync7(agentsDir)) return out;
|
|
2876
3149
|
let entries;
|
|
2877
3150
|
try {
|
|
@@ -2880,7 +3153,7 @@ function _agentRulesToDefaults() {
|
|
|
2880
3153
|
return out;
|
|
2881
3154
|
}
|
|
2882
3155
|
for (const agentId of entries) {
|
|
2883
|
-
const rulesFile =
|
|
3156
|
+
const rulesFile = join7(agentsDir, agentId, "rules.json");
|
|
2884
3157
|
if (!existsSync7(rulesFile)) continue;
|
|
2885
3158
|
let data;
|
|
2886
3159
|
try {
|
|
@@ -2913,6 +3186,11 @@ function _agentRulesToDefaults() {
|
|
|
2913
3186
|
category_enabled: true,
|
|
2914
3187
|
category_desc: "agent \u4E13\u5C5E\u654F\u611F\u8DEF\u5F84\uFF08L1 \u672B\u5C3E\u8FFD\u52A0\uFF09",
|
|
2915
3188
|
rules: (data.extra_sensitive_paths || []).map((sp) => ({ ...sp, enabled: true, builtin: true }))
|
|
3189
|
+
},
|
|
3190
|
+
extra_single_file_write_tools: {
|
|
3191
|
+
category_enabled: true,
|
|
3192
|
+
category_desc: "agent \u4E13\u5C5E\u5355\u6587\u4EF6\u5199\u5DE5\u5177\uFF08read_before_write \u53EA\u53D6\u58F0\u660E\u8DEF\u5F84\uFF09",
|
|
3193
|
+
rules: (data.extra_single_file_write_tools || []).map((v) => ({ value: v, enabled: true, builtin: true }))
|
|
2916
3194
|
}
|
|
2917
3195
|
};
|
|
2918
3196
|
}
|
|
@@ -3261,8 +3539,8 @@ function _filterDefaultsByOs(rules, osType) {
|
|
|
3261
3539
|
const accepted = acceptedOsValues(osType);
|
|
3262
3540
|
return rules.filter((r) => {
|
|
3263
3541
|
if (!r.os) return true;
|
|
3264
|
-
const
|
|
3265
|
-
return
|
|
3542
|
+
const os5 = String(r.os).toLowerCase();
|
|
3543
|
+
return os5 === "all" || accepted.includes(os5);
|
|
3266
3544
|
});
|
|
3267
3545
|
}
|
|
3268
3546
|
function _hasRulesForOs(rules, osType) {
|
|
@@ -3387,7 +3665,8 @@ function effectiveIntentPatterns(osType) {
|
|
|
3387
3665
|
intentKeywords: r.intent_keywords || [],
|
|
3388
3666
|
dangerousActions: r.dangerous_actions || [],
|
|
3389
3667
|
reason: String(r.reason || ""),
|
|
3390
|
-
os: String(r.os || "linux").toLowerCase()
|
|
3668
|
+
os: String(r.os || "linux").toLowerCase(),
|
|
3669
|
+
allowIfWriteIntent: r.allow_if_write_intent === true
|
|
3391
3670
|
}));
|
|
3392
3671
|
});
|
|
3393
3672
|
}
|
|
@@ -3492,12 +3771,12 @@ function addCustomSkill(skillId, category, keywords, content) {
|
|
|
3492
3771
|
);
|
|
3493
3772
|
}
|
|
3494
3773
|
const runtime = loadRuntimeConfig();
|
|
3495
|
-
const skillsDir =
|
|
3774
|
+
const skillsDir = join7(getRuntimeConfigDir(), "agent_moss_skills");
|
|
3496
3775
|
try {
|
|
3497
3776
|
mkdirSync2(skillsDir, { recursive: true });
|
|
3498
3777
|
} catch {
|
|
3499
3778
|
}
|
|
3500
|
-
writeFileSync(
|
|
3779
|
+
writeFileSync(join7(skillsDir, `${skillId}.md`), content, "utf-8");
|
|
3501
3780
|
const l3 = runtime.L3_skills || (runtime.L3_skills = {});
|
|
3502
3781
|
const cat = l3[category] || (l3[category] = { category_enabled: true, category_desc: "", skills: [] });
|
|
3503
3782
|
(cat.skills || (cat.skills = [])).push({ id: skillId, keywords, enabled: true, builtin: false });
|
|
@@ -3512,7 +3791,7 @@ function deleteCustomSkill(skillId, category) {
|
|
|
3512
3791
|
if (idx >= 0) {
|
|
3513
3792
|
if (skills[idx].builtin) return null;
|
|
3514
3793
|
skills.splice(idx, 1);
|
|
3515
|
-
const skillPath =
|
|
3794
|
+
const skillPath = join7(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
|
|
3516
3795
|
try {
|
|
3517
3796
|
if (existsSync7(skillPath)) unlinkSync(skillPath);
|
|
3518
3797
|
} catch {
|
|
@@ -3575,6 +3854,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
|
|
|
3575
3854
|
read_only: r.read_only,
|
|
3576
3855
|
deny_mode: r.deny_mode
|
|
3577
3856
|
}));
|
|
3857
|
+
const singleFileWriteTools = _agentCategoryEnabledRules(agentData.extra_single_file_write_tools).filter((r) => r.value).map((r) => String(r.value).toLowerCase());
|
|
3578
3858
|
return {
|
|
3579
3859
|
agent_id: agentId,
|
|
3580
3860
|
description: "",
|
|
@@ -3583,6 +3863,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
|
|
|
3583
3863
|
extra_sensitive_paths: sensitivePaths,
|
|
3584
3864
|
builtin_safe_skills: safeSkills.filter((r) => r.value).map((r) => r.value),
|
|
3585
3865
|
builtin_safe_action_types: safeAction.filter((r) => r.value).map((r) => r.value),
|
|
3866
|
+
extra_single_file_write_tools: singleFileWriteTools,
|
|
3586
3867
|
extra_skills: []
|
|
3587
3868
|
};
|
|
3588
3869
|
}
|
|
@@ -3661,6 +3942,7 @@ function getEnabledScenarioExtensions(runtime, scenarioId) {
|
|
|
3661
3942
|
extra_sensitive_paths: sensitivePaths,
|
|
3662
3943
|
builtin_safe_skills: [],
|
|
3663
3944
|
builtin_safe_action_types: [],
|
|
3945
|
+
extra_single_file_write_tools: [],
|
|
3664
3946
|
extra_skills: []
|
|
3665
3947
|
};
|
|
3666
3948
|
}
|
|
@@ -3721,7 +4003,7 @@ var init_runtime_config = __esm({
|
|
|
3721
4003
|
__dirname4 = dirname4(fileURLToPath4(import.meta.url));
|
|
3722
4004
|
ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
|
|
3723
4005
|
RUNTIME_CONFIG_DIR = runtimeDir();
|
|
3724
|
-
RUNTIME_CONFIG_PATH =
|
|
4006
|
+
RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
|
|
3725
4007
|
LAYER_DISABLE_ENV = {
|
|
3726
4008
|
L1_heuristic: "AGENT_MOSS_DISABLE_HEURISTIC",
|
|
3727
4009
|
L2_logic_rules: "AGENT_MOSS_DISABLE_LOGIC_RULES",
|
|
@@ -3749,10 +4031,10 @@ var init_runtime_config = __esm({
|
|
|
3749
4031
|
intent_consistency: ["intent_keywords", "reason"]
|
|
3750
4032
|
};
|
|
3751
4033
|
hasRuntimeConfigCache = /* @__PURE__ */ new Map();
|
|
3752
|
-
_AGENTS_DIR_PROD =
|
|
3753
|
-
_AGENTS_DIR_DEV =
|
|
3754
|
-
_SCENARIOS_DIR_PROD =
|
|
3755
|
-
_SCENARIOS_DIR_DEV =
|
|
4034
|
+
_AGENTS_DIR_PROD = join7(__dirname4, "agents");
|
|
4035
|
+
_AGENTS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "agents");
|
|
4036
|
+
_SCENARIOS_DIR_PROD = join7(__dirname4, "scenarios");
|
|
4037
|
+
_SCENARIOS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
|
|
3756
4038
|
_effectiveCache = /* @__PURE__ */ new WeakMap();
|
|
3757
4039
|
SKILL_ID_RE = /^[A-Za-z0-9_-]+$/;
|
|
3758
4040
|
registerRuntimeConfigBridge({
|
|
@@ -3795,7 +4077,7 @@ __export(config_exports, {
|
|
|
3795
4077
|
wildcardToRegExp: () => wildcardToRegExp
|
|
3796
4078
|
});
|
|
3797
4079
|
import fs2 from "fs";
|
|
3798
|
-
import
|
|
4080
|
+
import path3 from "path";
|
|
3799
4081
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
3800
4082
|
function loadConfigFile(filePath) {
|
|
3801
4083
|
try {
|
|
@@ -3808,17 +4090,17 @@ function loadConfigFile(filePath) {
|
|
|
3808
4090
|
function resolveConfigPath() {
|
|
3809
4091
|
const envPath = process.env.AGENT_MOSS_CONFIG_PATH;
|
|
3810
4092
|
if (envPath) return envPath;
|
|
3811
|
-
const userConfig =
|
|
4093
|
+
const userConfig = path3.join(getConfigDir(), "config.json");
|
|
3812
4094
|
if (fs2.existsSync(userConfig)) return userConfig;
|
|
3813
4095
|
const defaultCandidates = [
|
|
3814
|
-
|
|
3815
|
-
|
|
3816
|
-
|
|
3817
|
-
|
|
4096
|
+
path3.join(__configModuleDir, "config.json.example"),
|
|
4097
|
+
path3.join(__configModuleDir, "..", "config.json.example"),
|
|
4098
|
+
path3.join(__configModuleDir, "..", "..", "agent_moss", "infra", "config.json.example"),
|
|
4099
|
+
path3.join(__configModuleDir, "..", "..", "..", "agent_moss", "infra", "config.json.example")
|
|
3818
4100
|
];
|
|
3819
4101
|
const defaultConfig = defaultCandidates.find((p) => fs2.existsSync(p));
|
|
3820
4102
|
if (defaultConfig) {
|
|
3821
|
-
const configDir =
|
|
4103
|
+
const configDir = path3.dirname(userConfig);
|
|
3822
4104
|
fs2.mkdirSync(configDir, { recursive: true });
|
|
3823
4105
|
const pkgConfig = loadConfigFile(defaultConfig);
|
|
3824
4106
|
const safeConfig = pkgConfig ? { ...pkgConfig, llm: { ...pkgConfig.llm, api_key: "" } } : {};
|
|
@@ -4048,7 +4330,7 @@ var init_config = __esm({
|
|
|
4048
4330
|
init_rules_mode();
|
|
4049
4331
|
__configModuleDir = (() => {
|
|
4050
4332
|
try {
|
|
4051
|
-
return
|
|
4333
|
+
return path3.dirname(fileURLToPath5(import.meta.url));
|
|
4052
4334
|
} catch {
|
|
4053
4335
|
return typeof __dirname !== "undefined" ? __dirname : process.cwd();
|
|
4054
4336
|
}
|
|
@@ -4071,11 +4353,11 @@ var init_config = __esm({
|
|
|
4071
4353
|
};
|
|
4072
4354
|
})();
|
|
4073
4355
|
USER_RULES_PATHS = [
|
|
4074
|
-
|
|
4356
|
+
path3.join(__configModuleDir, "rules", "user_rules.json"),
|
|
4075
4357
|
// 源在 ts/src/rules(一般不存在)
|
|
4076
|
-
|
|
4358
|
+
path3.join(__configModuleDir, "..", "rules", "user_rules.json"),
|
|
4077
4359
|
// dist: dist/engine/../rules = dist/rules ✅
|
|
4078
|
-
|
|
4360
|
+
path3.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
|
|
4079
4361
|
// dev src: ts/src/../../agent_moss
|
|
4080
4362
|
];
|
|
4081
4363
|
customRules = loadCustomRules();
|
|
@@ -4093,11 +4375,11 @@ var init_config = __esm({
|
|
|
4093
4375
|
|
|
4094
4376
|
// src/agents/index.ts
|
|
4095
4377
|
import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
|
|
4096
|
-
import { resolve as resolve5, dirname as dirname5, join as
|
|
4378
|
+
import { resolve as resolve5, dirname as dirname5, join as join8 } from "path";
|
|
4097
4379
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
4098
4380
|
function resolveAgentsDir() {
|
|
4099
4381
|
const root = getRulesRoot();
|
|
4100
|
-
if (root) return
|
|
4382
|
+
if (root) return join8(root, "agents");
|
|
4101
4383
|
if (existsSync8(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
|
|
4102
4384
|
if (existsSync8(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
|
|
4103
4385
|
return AGENTS_DIR_PROD;
|
|
@@ -4158,6 +4440,7 @@ function mergeAgentExtensions(...exts) {
|
|
|
4158
4440
|
extra_sensitive_paths: nonNull.flatMap((e) => e.extra_sensitive_paths || []),
|
|
4159
4441
|
builtin_safe_skills: nonNull.flatMap((e) => e.builtin_safe_skills || []),
|
|
4160
4442
|
builtin_safe_action_types: nonNull.flatMap((e) => e.builtin_safe_action_types || []),
|
|
4443
|
+
extra_single_file_write_tools: nonNull.flatMap((e) => e.extra_single_file_write_tools || []),
|
|
4161
4444
|
extra_skills: nonNull.flatMap((e) => e.extra_skills || [])
|
|
4162
4445
|
};
|
|
4163
4446
|
}
|
|
@@ -4179,11 +4462,11 @@ var init_agents = __esm({
|
|
|
4179
4462
|
|
|
4180
4463
|
// src/scenarios/index.ts
|
|
4181
4464
|
import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
|
|
4182
|
-
import { resolve as resolve6, dirname as dirname6, join as
|
|
4465
|
+
import { resolve as resolve6, dirname as dirname6, join as join9 } from "path";
|
|
4183
4466
|
import { fileURLToPath as fileURLToPath7 } from "url";
|
|
4184
4467
|
function resolveScenariosDir() {
|
|
4185
4468
|
const root = getRulesRoot();
|
|
4186
|
-
if (root) return
|
|
4469
|
+
if (root) return join9(root, "scenarios");
|
|
4187
4470
|
if (existsSync9(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
|
|
4188
4471
|
if (existsSync9(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
|
|
4189
4472
|
return SCENARIOS_DIR_PROD;
|
|
@@ -4241,6 +4524,7 @@ function getScenarioExtensions(scenarioId) {
|
|
|
4241
4524
|
extra_sensitive_paths: data.extra_sensitive_paths || [],
|
|
4242
4525
|
builtin_safe_skills: data.builtin_safe_skills || [],
|
|
4243
4526
|
builtin_safe_action_types: data.builtin_safe_action_types || [],
|
|
4527
|
+
extra_single_file_write_tools: data.extra_single_file_write_tools || [],
|
|
4244
4528
|
extra_skills: data.extra_skills || []
|
|
4245
4529
|
};
|
|
4246
4530
|
} catch (e) {
|
|
@@ -4673,16 +4957,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4673
4957
|
if (String(osType || "").toLowerCase() === "windows") {
|
|
4674
4958
|
pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
|
|
4675
4959
|
}
|
|
4676
|
-
const pathMatches = (text,
|
|
4677
|
-
const parts =
|
|
4960
|
+
const pathMatches = (text, path8) => {
|
|
4961
|
+
const parts = path8.split(/(\(\?!.*?\))/);
|
|
4678
4962
|
const escaped = parts.map((part) => {
|
|
4679
4963
|
if (part.startsWith("(?!")) return part;
|
|
4680
4964
|
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4681
4965
|
}).join("");
|
|
4682
|
-
const re =
|
|
4966
|
+
const re = path8.startsWith(".") || path8.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
|
|
4683
4967
|
return re.test(text);
|
|
4684
4968
|
};
|
|
4685
|
-
const pathMatchesAny = (
|
|
4969
|
+
const pathMatchesAny = (path8) => pathScanTexts.some((t) => pathMatches(t, path8));
|
|
4686
4970
|
for (const sp of rootPaths) {
|
|
4687
4971
|
if (pathMatchesAny(sp.path.toLowerCase())) {
|
|
4688
4972
|
if (keygenGenerate) continue;
|
|
@@ -4825,8 +5109,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4825
5109
|
}
|
|
4826
5110
|
return null;
|
|
4827
5111
|
}
|
|
4828
|
-
function isHomeValue(
|
|
4829
|
-
let p =
|
|
5112
|
+
function isHomeValue(path8) {
|
|
5113
|
+
let p = path8.trim().toLowerCase();
|
|
4830
5114
|
if (p.startsWith("$(") && p.endsWith(")")) {
|
|
4831
5115
|
const inner = p.slice(2, -1).trim();
|
|
4832
5116
|
return HOME_TARGET_RE.test(" " + inner);
|
|
@@ -4882,15 +5166,15 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
4882
5166
|
}
|
|
4883
5167
|
const assigned = {};
|
|
4884
5168
|
for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
|
|
4885
|
-
for (const [varName,
|
|
4886
|
-
if (!isHomeValue(
|
|
5169
|
+
for (const [varName, path8] of Object.entries(assigned)) {
|
|
5170
|
+
if (!isHomeValue(path8)) continue;
|
|
4887
5171
|
const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
|
|
4888
5172
|
for (const seg of segs) {
|
|
4889
5173
|
if (!isDeleteCommand(seg)) continue;
|
|
4890
5174
|
if (varRefRe.test(seg)) {
|
|
4891
5175
|
return {
|
|
4892
5176
|
allowed: false,
|
|
4893
|
-
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${
|
|
5177
|
+
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path8}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
|
|
4894
5178
|
riskLevel: "high",
|
|
4895
5179
|
riskType: "script_execution",
|
|
4896
5180
|
confidence: 90,
|
|
@@ -5186,7 +5470,7 @@ var init_template_loader = __esm({
|
|
|
5186
5470
|
|
|
5187
5471
|
// src/engine/script-analyzer.ts
|
|
5188
5472
|
import { readFileSync as readFileSync10 } from "fs";
|
|
5189
|
-
import { resolve as resolve8, join as
|
|
5473
|
+
import { resolve as resolve8, join as join10 } from "path";
|
|
5190
5474
|
function emptyResult() {
|
|
5191
5475
|
return { scriptPath: "", scriptContent: "", matchedKeywords: [], lineCount: 0, isSuspicious: false, error: "", riskLevel: "", riskReason: "" };
|
|
5192
5476
|
}
|
|
@@ -5239,7 +5523,7 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
|
|
|
5239
5523
|
}
|
|
5240
5524
|
function readScriptContent(scriptPath, maxLines = 500) {
|
|
5241
5525
|
try {
|
|
5242
|
-
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ?
|
|
5526
|
+
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join10(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
|
|
5243
5527
|
const raw = readFileSync10(expandedPath, "utf-8");
|
|
5244
5528
|
const lines = raw.split("\n").slice(0, maxLines);
|
|
5245
5529
|
return { content: lines.join("\n"), lineCount: lines.length, error: "" };
|
|
@@ -5694,15 +5978,15 @@ function parseShellString(s) {
|
|
|
5694
5978
|
let m;
|
|
5695
5979
|
while ((m = CHILD_CALL_RE.exec(s)) !== null) {
|
|
5696
5980
|
const interp = m[1];
|
|
5697
|
-
const
|
|
5981
|
+
const path8 = m[2].trim();
|
|
5698
5982
|
let rest = m[3].trim();
|
|
5699
|
-
if (
|
|
5983
|
+
if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
|
|
5700
5984
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5701
5985
|
const args = [];
|
|
5702
5986
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5703
5987
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5704
5988
|
}
|
|
5705
|
-
return { path:
|
|
5989
|
+
return { path: path8, args, interpreter: interp };
|
|
5706
5990
|
}
|
|
5707
5991
|
return null;
|
|
5708
5992
|
}
|
|
@@ -5748,9 +6032,9 @@ function extractCallsFromTree(tree, reachableLines) {
|
|
|
5748
6032
|
}
|
|
5749
6033
|
if (allStr && elts.length >= 2) {
|
|
5750
6034
|
const interp = elts[0];
|
|
5751
|
-
const
|
|
5752
|
-
if (!
|
|
5753
|
-
add({ path:
|
|
6035
|
+
const path8 = elts[1];
|
|
6036
|
+
if (!path8.startsWith("-") && !path8.startsWith("$") && !path8.includes("/dev/")) {
|
|
6037
|
+
add({ path: path8, args: elts.slice(2), interpreter: interp });
|
|
5754
6038
|
return true;
|
|
5755
6039
|
}
|
|
5756
6040
|
}
|
|
@@ -5790,15 +6074,15 @@ function extractCallsRegex(content) {
|
|
|
5790
6074
|
let m;
|
|
5791
6075
|
while ((m = CHILD_CALL_RE.exec(content)) !== null) {
|
|
5792
6076
|
const interp = m[1];
|
|
5793
|
-
const
|
|
6077
|
+
const path8 = m[2].trim();
|
|
5794
6078
|
let rest = m[3].trim();
|
|
5795
|
-
if (
|
|
6079
|
+
if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
|
|
5796
6080
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5797
6081
|
const args = [];
|
|
5798
6082
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5799
6083
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5800
6084
|
}
|
|
5801
|
-
calls.push({ path:
|
|
6085
|
+
calls.push({ path: path8, args, interpreter: interp });
|
|
5802
6086
|
}
|
|
5803
6087
|
return calls;
|
|
5804
6088
|
}
|
|
@@ -6581,15 +6865,15 @@ function extractCallsFromContent(content) {
|
|
|
6581
6865
|
CHILD_CALL_RE2.lastIndex = 0;
|
|
6582
6866
|
while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
|
|
6583
6867
|
const interp = m[1];
|
|
6584
|
-
const
|
|
6868
|
+
const path8 = m[2].trim();
|
|
6585
6869
|
let rest = m[3].trim();
|
|
6586
|
-
if (
|
|
6870
|
+
if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
|
|
6587
6871
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
6588
6872
|
const args = [];
|
|
6589
6873
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
6590
6874
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
6591
6875
|
}
|
|
6592
|
-
calls.push({ path:
|
|
6876
|
+
calls.push({ path: path8, args, interpreter: interp });
|
|
6593
6877
|
}
|
|
6594
6878
|
return calls;
|
|
6595
6879
|
}
|
|
@@ -6658,8 +6942,8 @@ var init_backends = __esm({
|
|
|
6658
6942
|
|
|
6659
6943
|
// src/engine/script-engine/tracker.ts
|
|
6660
6944
|
import * as fs3 from "fs";
|
|
6661
|
-
import * as
|
|
6662
|
-
import * as
|
|
6945
|
+
import * as path4 from "path";
|
|
6946
|
+
import * as os2 from "os";
|
|
6663
6947
|
function maxFileSizeFromEnv() {
|
|
6664
6948
|
const raw = (process.env.AGENT_MOSS_SCRIPT_MAX_FILE_SIZE || "").trim();
|
|
6665
6949
|
if (raw) {
|
|
@@ -6678,11 +6962,11 @@ function pickBackend(pathStr) {
|
|
|
6678
6962
|
function resolvePath(p, baseDir) {
|
|
6679
6963
|
let expanded = p;
|
|
6680
6964
|
if (expanded.startsWith("~/") || expanded === "~") {
|
|
6681
|
-
expanded =
|
|
6682
|
-
} else if (!
|
|
6683
|
-
expanded =
|
|
6965
|
+
expanded = path4.join(os2.homedir(), expanded.slice(1));
|
|
6966
|
+
} else if (!path4.isAbsolute(expanded) && baseDir) {
|
|
6967
|
+
expanded = path4.join(baseDir, expanded);
|
|
6684
6968
|
}
|
|
6685
|
-
return
|
|
6969
|
+
return path4.resolve(expanded);
|
|
6686
6970
|
}
|
|
6687
6971
|
function readScript(pathStr, maxFileSize) {
|
|
6688
6972
|
try {
|
|
@@ -6776,7 +7060,7 @@ var init_tracker = __esm({
|
|
|
6776
7060
|
const baseDir = cwd || process.cwd();
|
|
6777
7061
|
const resolved = resolvePath(entryPath);
|
|
6778
7062
|
this.result.entryPath = resolved;
|
|
6779
|
-
this.visitScript(resolved, 0,
|
|
7063
|
+
this.visitScript(resolved, 0, path4.dirname(resolved), entryArgs);
|
|
6780
7064
|
const nodes = this.result.nodes;
|
|
6781
7065
|
this.result.hasCritical = nodes.some((n) => n.l1RiskLevel === "critical" || n.l2RiskLevel === "critical" || n.keywordRiskLevel === "critical") || this.result.hasCritical;
|
|
6782
7066
|
this.result.hasHigh = nodes.some((n) => ["high", "critical"].includes(n.l1RiskLevel) || ["high", "critical"].includes(n.l2RiskLevel) || ["high", "critical"].includes(n.keywordRiskLevel));
|
|
@@ -6838,12 +7122,12 @@ var init_tracker = __esm({
|
|
|
6838
7122
|
}
|
|
6839
7123
|
}
|
|
6840
7124
|
}
|
|
6841
|
-
const parentDir =
|
|
7125
|
+
const parentDir = path4.dirname(pathStr);
|
|
6842
7126
|
const childPaths = [];
|
|
6843
7127
|
for (const call of ir.calls) {
|
|
6844
7128
|
const child = resolvePath(call.path, parentDir);
|
|
6845
7129
|
childPaths.push(child);
|
|
6846
|
-
this.visitScript(child, depth + 1,
|
|
7130
|
+
this.visitScript(child, depth + 1, path4.dirname(child), call.args);
|
|
6847
7131
|
if (this.result.hasCritical) break;
|
|
6848
7132
|
}
|
|
6849
7133
|
node.childPaths = childPaths;
|
|
@@ -6855,8 +7139,8 @@ var init_tracker = __esm({
|
|
|
6855
7139
|
|
|
6856
7140
|
// src/engine/script-content-analyzer.ts
|
|
6857
7141
|
import { statSync as statSync4, existsSync as existsSync12 } from "fs";
|
|
6858
|
-
import { resolve as resolve10, join as
|
|
6859
|
-
import { homedir as
|
|
7142
|
+
import { resolve as resolve10, join as join12, isAbsolute as isAbsolute4 } from "path";
|
|
7143
|
+
import { homedir as homedir5 } from "os";
|
|
6860
7144
|
function emptyChain() {
|
|
6861
7145
|
return {
|
|
6862
7146
|
nodes: [],
|
|
@@ -7038,7 +7322,7 @@ function shlexSplit(s) {
|
|
|
7038
7322
|
function resolvePath2(p) {
|
|
7039
7323
|
let expanded = p;
|
|
7040
7324
|
if (expanded.startsWith("~/") || expanded === "~") {
|
|
7041
|
-
expanded =
|
|
7325
|
+
expanded = join12(homedir5(), expanded.slice(1));
|
|
7042
7326
|
}
|
|
7043
7327
|
return resolve10(expanded);
|
|
7044
7328
|
}
|
|
@@ -7161,8 +7445,8 @@ function analyzeScriptContent2(input, ext) {
|
|
|
7161
7445
|
resolvedPath = inline;
|
|
7162
7446
|
isInline = true;
|
|
7163
7447
|
}
|
|
7164
|
-
if (resolvedPath && !
|
|
7165
|
-
resolvedPath =
|
|
7448
|
+
if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
|
|
7449
|
+
resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
|
|
7166
7450
|
}
|
|
7167
7451
|
const l1Adapter = (content) => {
|
|
7168
7452
|
const j = scanDangerousCommandPatterns("bash", content, input.osType);
|
|
@@ -7280,7 +7564,7 @@ var init_script_content_analyzer = __esm({
|
|
|
7280
7564
|
|
|
7281
7565
|
// src/infra/trace-log.ts
|
|
7282
7566
|
import fs4 from "fs";
|
|
7283
|
-
import
|
|
7567
|
+
import path5 from "path";
|
|
7284
7568
|
function traceLevel() {
|
|
7285
7569
|
if (_levelCache !== null) return _levelCache;
|
|
7286
7570
|
const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
|
|
@@ -7307,7 +7591,7 @@ function tracePath() {
|
|
|
7307
7591
|
const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
|
|
7308
7592
|
if (explicit) return explicit;
|
|
7309
7593
|
try {
|
|
7310
|
-
return
|
|
7594
|
+
return path5.join(getDataRoot(), "agent_moss_trace.log");
|
|
7311
7595
|
} catch {
|
|
7312
7596
|
return "agent_moss_trace.log";
|
|
7313
7597
|
}
|
|
@@ -7346,7 +7630,7 @@ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
|
|
|
7346
7630
|
`;
|
|
7347
7631
|
const file = tracePath();
|
|
7348
7632
|
try {
|
|
7349
|
-
const dir =
|
|
7633
|
+
const dir = path5.dirname(file);
|
|
7350
7634
|
if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
|
|
7351
7635
|
try {
|
|
7352
7636
|
const st = fs4.statSync(file);
|
|
@@ -7942,7 +8226,7 @@ var init_token_stats = __esm({
|
|
|
7942
8226
|
|
|
7943
8227
|
// src/engine/llm-analyzer.ts
|
|
7944
8228
|
import { createHash as createHash3 } from "crypto";
|
|
7945
|
-
import { openSync as
|
|
8229
|
+
import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
|
|
7946
8230
|
import OpenAI from "openai";
|
|
7947
8231
|
function responseFieldLengths(message) {
|
|
7948
8232
|
if (!message || typeof message !== "object") return {};
|
|
@@ -8081,11 +8365,11 @@ ${prompt}
|
|
|
8081
8365
|
`;
|
|
8082
8366
|
let flags = fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_APPEND;
|
|
8083
8367
|
if (fsConstants2.O_NOFOLLOW) flags |= fsConstants2.O_NOFOLLOW;
|
|
8084
|
-
const fd =
|
|
8368
|
+
const fd = openSync3(logPath, flags, 384);
|
|
8085
8369
|
try {
|
|
8086
8370
|
writeSync2(fd, line);
|
|
8087
8371
|
} finally {
|
|
8088
|
-
|
|
8372
|
+
closeSync3(fd);
|
|
8089
8373
|
}
|
|
8090
8374
|
} catch (e) {
|
|
8091
8375
|
console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
|
|
@@ -8381,8 +8665,8 @@ var init_llm_analyzer = __esm({
|
|
|
8381
8665
|
|
|
8382
8666
|
// src/brain/rule-store.ts
|
|
8383
8667
|
import { existsSync as existsSync14, readFileSync as readFileSync14, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
|
|
8384
|
-
import { join as
|
|
8385
|
-
import { homedir as
|
|
8668
|
+
import { join as join13 } from "path";
|
|
8669
|
+
import { homedir as homedir6 } from "os";
|
|
8386
8670
|
function getRulesPath() {
|
|
8387
8671
|
const envPath = process.env[ENV_RULES_PATH];
|
|
8388
8672
|
if (envPath) return envPath;
|
|
@@ -8400,7 +8684,7 @@ var init_rule_store = __esm({
|
|
|
8400
8684
|
"src/brain/rule-store.ts"() {
|
|
8401
8685
|
"use strict";
|
|
8402
8686
|
init_esm_shims();
|
|
8403
|
-
DEFAULT_RULES_PATH =
|
|
8687
|
+
DEFAULT_RULES_PATH = join13(homedir6(), ".agentmoss", "brain", "rules.json");
|
|
8404
8688
|
ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
|
|
8405
8689
|
STATUS_DRAFT = "draft";
|
|
8406
8690
|
STATUS_APPROVED = "approved";
|
|
@@ -8412,8 +8696,8 @@ var init_rule_store = __esm({
|
|
|
8412
8696
|
BrainRuleStore = class {
|
|
8413
8697
|
path;
|
|
8414
8698
|
data;
|
|
8415
|
-
constructor(
|
|
8416
|
-
this.path =
|
|
8699
|
+
constructor(path8) {
|
|
8700
|
+
this.path = path8 || getRulesPath();
|
|
8417
8701
|
this.data = this.load();
|
|
8418
8702
|
}
|
|
8419
8703
|
load() {
|
|
@@ -8866,10 +9150,10 @@ ${reason.slice(0, 500)}
|
|
|
8866
9150
|
const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
|
|
8867
9151
|
let mm;
|
|
8868
9152
|
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(
|
|
9153
|
+
const path8 = mm[1];
|
|
9154
|
+
if (path8.split("/").length < 3) continue;
|
|
9155
|
+
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path8)) continue;
|
|
9156
|
+
const gen = this.generalizePath(path8);
|
|
8873
9157
|
if (seen.has(gen)) continue;
|
|
8874
9158
|
seen.add(gen);
|
|
8875
9159
|
patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
|
|
@@ -8888,8 +9172,8 @@ ${reason.slice(0, 500)}
|
|
|
8888
9172
|
}
|
|
8889
9173
|
return false;
|
|
8890
9174
|
}
|
|
8891
|
-
generalizePath(
|
|
8892
|
-
const p =
|
|
9175
|
+
generalizePath(path8) {
|
|
9176
|
+
const p = path8.toLowerCase();
|
|
8893
9177
|
if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
|
|
8894
9178
|
return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
|
|
8895
9179
|
}
|
|
@@ -9016,8 +9300,8 @@ var init_reviewer = __esm({
|
|
|
9016
9300
|
|
|
9017
9301
|
// src/brain/skill-manager.ts
|
|
9018
9302
|
import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync, writeFileSync as writeFileSync4 } from "fs";
|
|
9019
|
-
import { homedir as
|
|
9020
|
-
import { join as
|
|
9303
|
+
import { homedir as homedir7 } from "os";
|
|
9304
|
+
import { join as join14 } from "path";
|
|
9021
9305
|
import { randomUUID } from "crypto";
|
|
9022
9306
|
function getMetaPath(override) {
|
|
9023
9307
|
return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
|
|
@@ -9027,14 +9311,14 @@ var init_skill_manager = __esm({
|
|
|
9027
9311
|
"src/brain/skill-manager.ts"() {
|
|
9028
9312
|
"use strict";
|
|
9029
9313
|
init_esm_shims();
|
|
9030
|
-
DEFAULT_SKILL_META_PATH =
|
|
9314
|
+
DEFAULT_SKILL_META_PATH = join14(homedir7(), ".agentmoss", "brain", "skill_meta.json");
|
|
9031
9315
|
ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
|
|
9032
9316
|
BrainSkillManager = class {
|
|
9033
9317
|
constructor(skillsDir, metaPath) {
|
|
9034
9318
|
this.skillsDir = skillsDir;
|
|
9035
9319
|
this.metaPath = getMetaPath(metaPath);
|
|
9036
9320
|
try {
|
|
9037
|
-
mkdirSync5(
|
|
9321
|
+
mkdirSync5(join14(this.metaPath, ".."), { recursive: true });
|
|
9038
9322
|
} catch {
|
|
9039
9323
|
}
|
|
9040
9324
|
this.load();
|
|
@@ -9069,7 +9353,7 @@ var init_skill_manager = __esm({
|
|
|
9069
9353
|
let changed = false;
|
|
9070
9354
|
for (const sk of this.skills) {
|
|
9071
9355
|
if (sk.status !== "active") continue;
|
|
9072
|
-
if (!existsSync15(
|
|
9356
|
+
if (!existsSync15(join14(this.skillsDir, `${sk.name}.md`))) {
|
|
9073
9357
|
sk.status = "stale";
|
|
9074
9358
|
changed = true;
|
|
9075
9359
|
}
|
|
@@ -9081,7 +9365,7 @@ var init_skill_manager = __esm({
|
|
|
9081
9365
|
const id = skill.id || randomUUID();
|
|
9082
9366
|
const name = skill.name || `brain_${id.slice(0, 8)}`;
|
|
9083
9367
|
if (!existsSync15(this.skillsDir)) return "";
|
|
9084
|
-
const mdPath =
|
|
9368
|
+
const mdPath = join14(this.skillsDir, `${name}.md`);
|
|
9085
9369
|
if (existsSync15(mdPath)) return "";
|
|
9086
9370
|
try {
|
|
9087
9371
|
writeFileSync4(mdPath, skill.content, "utf-8");
|
|
@@ -9131,7 +9415,7 @@ var init_skill_manager = __esm({
|
|
|
9131
9415
|
const out = [];
|
|
9132
9416
|
for (const sk of this.skills) {
|
|
9133
9417
|
if (sk.origin_node !== "local" || sk.status !== "active") continue;
|
|
9134
|
-
const mdPath =
|
|
9418
|
+
const mdPath = join14(this.skillsDir, `${sk.name}.md`);
|
|
9135
9419
|
if (!existsSync15(mdPath)) continue;
|
|
9136
9420
|
out.push({
|
|
9137
9421
|
name: sk.name,
|
|
@@ -9735,12 +10019,12 @@ var init_builder = __esm({
|
|
|
9735
10019
|
});
|
|
9736
10020
|
|
|
9737
10021
|
// src/engine/formal-engine/properties.ts
|
|
9738
|
-
function graphFromPath(nodes,
|
|
10022
|
+
function graphFromPath(nodes, path8, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
|
|
9739
10023
|
const byKey = /* @__PURE__ */ new Map();
|
|
9740
10024
|
for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
|
|
9741
10025
|
const gNodes = [];
|
|
9742
10026
|
const gEdges = [];
|
|
9743
|
-
for (const item of
|
|
10027
|
+
for (const item of path8) {
|
|
9744
10028
|
const n = byKey.get(`${item.sessionId}#${item.seq}`);
|
|
9745
10029
|
gNodes.push({
|
|
9746
10030
|
session_id: item.sessionId,
|
|
@@ -9806,22 +10090,22 @@ function checkCrossSessionChain(graph) {
|
|
|
9806
10090
|
if (witness !== void 0) {
|
|
9807
10091
|
if (nodes[witness].stage !== stages[stages.length - 1]) continue;
|
|
9808
10092
|
let matched = 0;
|
|
9809
|
-
const
|
|
10093
|
+
const path8 = [];
|
|
9810
10094
|
for (let k = 0; k < witness; k++) {
|
|
9811
10095
|
const n = nodes[k];
|
|
9812
10096
|
if (matched < stages.length - 1 && n.stage === stages[matched]) {
|
|
9813
10097
|
matched += 1;
|
|
9814
|
-
|
|
10098
|
+
path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9815
10099
|
}
|
|
9816
10100
|
}
|
|
9817
10101
|
if (matched < stages.length - 1) continue;
|
|
9818
|
-
|
|
10102
|
+
path8.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
|
|
9819
10103
|
violations.push({
|
|
9820
10104
|
propertyId: "cross-" + chain.id,
|
|
9821
10105
|
reason: chain.reason,
|
|
9822
10106
|
riskLevel: chain.riskLevel,
|
|
9823
|
-
path:
|
|
9824
|
-
graph: graphFromPath(nodes,
|
|
10107
|
+
path: path8,
|
|
10108
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
9825
10109
|
property_id: "cross-" + chain.id,
|
|
9826
10110
|
property_short: "P1",
|
|
9827
10111
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -9831,11 +10115,11 @@ function checkCrossSessionChain(graph) {
|
|
|
9831
10115
|
} else {
|
|
9832
10116
|
let matched = 0;
|
|
9833
10117
|
let stageIdx = 0;
|
|
9834
|
-
const
|
|
10118
|
+
const path8 = [];
|
|
9835
10119
|
for (const n of nodes) {
|
|
9836
10120
|
if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
|
|
9837
10121
|
matched += 1;
|
|
9838
|
-
|
|
10122
|
+
path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9839
10123
|
stageIdx += 1;
|
|
9840
10124
|
if (matched >= stages.length) break;
|
|
9841
10125
|
}
|
|
@@ -9845,8 +10129,8 @@ function checkCrossSessionChain(graph) {
|
|
|
9845
10129
|
propertyId: "cross-" + chain.id,
|
|
9846
10130
|
reason: chain.reason,
|
|
9847
10131
|
riskLevel: chain.riskLevel,
|
|
9848
|
-
path:
|
|
9849
|
-
graph: graphFromPath(nodes,
|
|
10132
|
+
path: path8,
|
|
10133
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
9850
10134
|
property_id: "cross-" + chain.id,
|
|
9851
10135
|
property_short: "P1",
|
|
9852
10136
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -10067,7 +10351,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10067
10351
|
if (candidates.length > 0) {
|
|
10068
10352
|
const pre = nodes[candidates[candidates.length - 1]];
|
|
10069
10353
|
const post = nodes[firstEv];
|
|
10070
|
-
const
|
|
10354
|
+
const path8 = [
|
|
10071
10355
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
10072
10356
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
10073
10357
|
];
|
|
@@ -10075,8 +10359,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10075
10359
|
propertyId: "no-exfil-after-privesc",
|
|
10076
10360
|
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
10361
|
riskLevel: "critical",
|
|
10078
|
-
path:
|
|
10079
|
-
graph: graphFromPath(nodes,
|
|
10362
|
+
path: path8,
|
|
10363
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
10080
10364
|
property_id: "no-exfil-after-privesc",
|
|
10081
10365
|
property_short: "P4",
|
|
10082
10366
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10093,7 +10377,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10093
10377
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
10094
10378
|
if (!isExfilNode(nodes[j])) continue;
|
|
10095
10379
|
if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
|
|
10096
|
-
const
|
|
10380
|
+
const path8 = [
|
|
10097
10381
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
10098
10382
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
10099
10383
|
];
|
|
@@ -10101,8 +10385,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10101
10385
|
propertyId: "no-exfil-after-privesc",
|
|
10102
10386
|
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
10387
|
riskLevel: "critical",
|
|
10104
|
-
path:
|
|
10105
|
-
graph: graphFromPath(nodes,
|
|
10388
|
+
path: path8,
|
|
10389
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
10106
10390
|
property_id: "no-exfil-after-privesc",
|
|
10107
10391
|
property_short: "P4",
|
|
10108
10392
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10134,7 +10418,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10134
10418
|
}
|
|
10135
10419
|
if (pre) {
|
|
10136
10420
|
const post = nodes[firstEv];
|
|
10137
|
-
const
|
|
10421
|
+
const path8 = [
|
|
10138
10422
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
10139
10423
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
10140
10424
|
];
|
|
@@ -10142,8 +10426,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10142
10426
|
propertyId: "no-exfil-after-credential",
|
|
10143
10427
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
10144
10428
|
riskLevel: "critical",
|
|
10145
|
-
path:
|
|
10146
|
-
graph: graphFromPath(nodes,
|
|
10429
|
+
path: path8,
|
|
10430
|
+
graph: graphFromPath(nodes, path8, "data", {
|
|
10147
10431
|
property_id: "no-exfil-after-credential",
|
|
10148
10432
|
property_short: "P5",
|
|
10149
10433
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10159,7 +10443,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10159
10443
|
if (!isCredNode(nodes[i])) continue;
|
|
10160
10444
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
10161
10445
|
if (isExfilNode(nodes[j])) {
|
|
10162
|
-
const
|
|
10446
|
+
const path8 = [
|
|
10163
10447
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
10164
10448
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
10165
10449
|
];
|
|
@@ -10167,8 +10451,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10167
10451
|
propertyId: "no-exfil-after-credential",
|
|
10168
10452
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
10169
10453
|
riskLevel: "critical",
|
|
10170
|
-
path:
|
|
10171
|
-
graph: graphFromPath(nodes,
|
|
10454
|
+
path: path8,
|
|
10455
|
+
graph: graphFromPath(nodes, path8, "data", {
|
|
10172
10456
|
property_id: "no-exfil-after-credential",
|
|
10173
10457
|
property_short: "P5",
|
|
10174
10458
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10327,13 +10611,13 @@ function checkSensitiveDataAggregation(graph) {
|
|
|
10327
10611
|
if (!isExfilNode(n)) continue;
|
|
10328
10612
|
const srcs = sourcesFor(i);
|
|
10329
10613
|
if (srcs.size >= 2) {
|
|
10330
|
-
const
|
|
10614
|
+
const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
10331
10615
|
violations.push({
|
|
10332
10616
|
propertyId: "sensitive-data-aggregation",
|
|
10333
10617
|
reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
|
|
10334
10618
|
riskLevel: "critical",
|
|
10335
|
-
path:
|
|
10336
|
-
graph: graphFromPath(nodes,
|
|
10619
|
+
path: path8,
|
|
10620
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
10337
10621
|
property_id: "sensitive-data-aggregation",
|
|
10338
10622
|
property_short: "P8",
|
|
10339
10623
|
property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
|
|
@@ -10792,11 +11076,11 @@ var init_stateful = __esm({
|
|
|
10792
11076
|
}
|
|
10793
11077
|
}
|
|
10794
11078
|
chainPath(stages) {
|
|
10795
|
-
const
|
|
11079
|
+
const path8 = [];
|
|
10796
11080
|
let want = stages[0];
|
|
10797
11081
|
for (const n of this.nodes_) {
|
|
10798
11082
|
if (n.stage === want) {
|
|
10799
|
-
|
|
11083
|
+
path8.push({
|
|
10800
11084
|
sessionId: n.sessionId,
|
|
10801
11085
|
seq: n.seq,
|
|
10802
11086
|
stage: n.stage,
|
|
@@ -10812,12 +11096,12 @@ var init_stateful = __esm({
|
|
|
10812
11096
|
}
|
|
10813
11097
|
}
|
|
10814
11098
|
}
|
|
10815
|
-
return
|
|
11099
|
+
return path8;
|
|
10816
11100
|
}
|
|
10817
11101
|
/** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
|
|
10818
11102
|
buildChainGraph(stages, chainId) {
|
|
10819
|
-
const
|
|
10820
|
-
const gNodes =
|
|
11103
|
+
const path8 = this.chainPath(stages);
|
|
11104
|
+
const gNodes = path8.map((p, i) => {
|
|
10821
11105
|
const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
|
|
10822
11106
|
return {
|
|
10823
11107
|
session_id: p.sessionId,
|
|
@@ -11069,13 +11353,13 @@ var init_stateful = __esm({
|
|
|
11069
11353
|
|
|
11070
11354
|
// src/engine/formal-engine/chain_state.ts
|
|
11071
11355
|
import * as fs5 from "fs";
|
|
11072
|
-
import * as
|
|
11073
|
-
import * as
|
|
11356
|
+
import * as os3 from "os";
|
|
11357
|
+
import * as path6 from "path";
|
|
11074
11358
|
import { createHash as createHash4 } from "crypto";
|
|
11075
11359
|
function defaultStateDbPath() {
|
|
11076
|
-
const dir = process.env.AGENT_MOSS_STATE_DIR ||
|
|
11360
|
+
const dir = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
|
|
11077
11361
|
const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
|
|
11078
|
-
return
|
|
11362
|
+
return path6.join(dir, `stateful_chains_${tag}.json`);
|
|
11079
11363
|
}
|
|
11080
11364
|
function registerExitFlush(store) {
|
|
11081
11365
|
if (_exitHookRegistered) return;
|
|
@@ -11161,7 +11445,7 @@ var init_chain_state = __esm({
|
|
|
11161
11445
|
this._timer = null;
|
|
11162
11446
|
try {
|
|
11163
11447
|
this._syncDirtyToData();
|
|
11164
|
-
ensurePrivateDir(
|
|
11448
|
+
ensurePrivateDir(path6.dirname(this.filePath));
|
|
11165
11449
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
11166
11450
|
} catch {
|
|
11167
11451
|
}
|
|
@@ -11184,7 +11468,7 @@ var init_chain_state = __esm({
|
|
|
11184
11468
|
}
|
|
11185
11469
|
try {
|
|
11186
11470
|
this._syncDirtyToData();
|
|
11187
|
-
ensurePrivateDir(
|
|
11471
|
+
ensurePrivateDir(path6.dirname(this.filePath));
|
|
11188
11472
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
11189
11473
|
} catch {
|
|
11190
11474
|
}
|
|
@@ -11252,7 +11536,7 @@ var init_chain_state = __esm({
|
|
|
11252
11536
|
_flushNow() {
|
|
11253
11537
|
this._syncDirtyToData();
|
|
11254
11538
|
try {
|
|
11255
|
-
const _dirOk = ensurePrivateDir(
|
|
11539
|
+
const _dirOk = ensurePrivateDir(path6.dirname(this.filePath));
|
|
11256
11540
|
const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
11257
11541
|
if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
|
|
11258
11542
|
} catch (e) {
|
|
@@ -11549,7 +11833,7 @@ async function runAnalysis(input) {
|
|
|
11549
11833
|
skipLLM = true;
|
|
11550
11834
|
}
|
|
11551
11835
|
}
|
|
11552
|
-
const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
|
|
11836
|
+
const logicResult = isLogicRulesEnabled() ? runLogicCheck(input, { agentExt }) : null;
|
|
11553
11837
|
if (logicResult) {
|
|
11554
11838
|
traceSummary("l2.result", {
|
|
11555
11839
|
hit: !logicResult.allowed,
|
|
@@ -12105,7 +12389,7 @@ init_security_policy();
|
|
|
12105
12389
|
init_coordinator();
|
|
12106
12390
|
import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
|
|
12107
12391
|
import { tmpdir as tmpdir3 } from "os";
|
|
12108
|
-
import { join as
|
|
12392
|
+
import { join as join17, resolve as resolve11 } from "path";
|
|
12109
12393
|
|
|
12110
12394
|
// src/infra/policy-cache.ts
|
|
12111
12395
|
init_esm_shims();
|
|
@@ -12115,8 +12399,8 @@ init_config();
|
|
|
12115
12399
|
import { createHash as createHash5 } from "crypto";
|
|
12116
12400
|
import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
|
|
12117
12401
|
import { tmpdir as tmpdir2 } from "os";
|
|
12118
|
-
import { join as
|
|
12119
|
-
var CACHE_DIR =
|
|
12402
|
+
import { join as join16 } from "path";
|
|
12403
|
+
var CACHE_DIR = join16(tmpdir2(), "agent_moss_policy_cache");
|
|
12120
12404
|
var cacheDirOverride = null;
|
|
12121
12405
|
function cacheDir() {
|
|
12122
12406
|
return cacheDirOverride ?? CACHE_DIR;
|
|
@@ -12125,7 +12409,7 @@ function safeCacheDir() {
|
|
|
12125
12409
|
const dir = cacheDir();
|
|
12126
12410
|
if (ensurePrivateDir(dir)) return dir;
|
|
12127
12411
|
try {
|
|
12128
|
-
const fallback =
|
|
12412
|
+
const fallback = join16(getDataRoot(), "policy_cache");
|
|
12129
12413
|
if (ensurePrivateDir(fallback)) {
|
|
12130
12414
|
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
12415
|
return fallback;
|
|
@@ -12147,7 +12431,7 @@ var PolicyCache = class {
|
|
|
12147
12431
|
cacheFilePath(sessionId, promptSession) {
|
|
12148
12432
|
const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
|
|
12149
12433
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12150
|
-
return
|
|
12434
|
+
return join16(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
|
|
12151
12435
|
}
|
|
12152
12436
|
/** 取缓存:内存 → 文件;未命中返回 null。 */
|
|
12153
12437
|
get(sessionId, promptSession) {
|
|
@@ -12178,7 +12462,7 @@ var PolicyCache = class {
|
|
|
12178
12462
|
try {
|
|
12179
12463
|
const dir = safeCacheDir();
|
|
12180
12464
|
const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12181
|
-
if (!ensurePrivateDir(
|
|
12465
|
+
if (!ensurePrivateDir(join16(dir, sub))) return;
|
|
12182
12466
|
writePrivateText(file, policy);
|
|
12183
12467
|
} catch {
|
|
12184
12468
|
}
|
|
@@ -12204,12 +12488,12 @@ var PolicyCache = class {
|
|
|
12204
12488
|
if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
|
|
12205
12489
|
}
|
|
12206
12490
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12207
|
-
const dir =
|
|
12491
|
+
const dir = join16(cacheDir(), safeSessionId);
|
|
12208
12492
|
try {
|
|
12209
12493
|
if (existsSync17(dir)) {
|
|
12210
12494
|
for (const f of readdirSync5(dir)) {
|
|
12211
12495
|
try {
|
|
12212
|
-
unlinkSync4(
|
|
12496
|
+
unlinkSync4(join16(dir, f));
|
|
12213
12497
|
} catch {
|
|
12214
12498
|
}
|
|
12215
12499
|
}
|
|
@@ -12223,9 +12507,9 @@ var PolicyCache = class {
|
|
|
12223
12507
|
try {
|
|
12224
12508
|
if (existsSync17(cacheDir())) {
|
|
12225
12509
|
for (const sessionDir of readdirSync5(cacheDir())) {
|
|
12226
|
-
const dir =
|
|
12510
|
+
const dir = join16(cacheDir(), sessionDir);
|
|
12227
12511
|
try {
|
|
12228
|
-
for (const f of readdirSync5(dir)) unlinkSync4(
|
|
12512
|
+
for (const f of readdirSync5(dir)) unlinkSync4(join16(dir, f));
|
|
12229
12513
|
rmdirSync(dir);
|
|
12230
12514
|
} catch {
|
|
12231
12515
|
}
|
|
@@ -12312,7 +12596,7 @@ ${safe(policy, 2e3)}`);
|
|
|
12312
12596
|
|
|
12313
12597
|
// src/engine/analyzer.ts
|
|
12314
12598
|
import { parse as parseToml } from "smol-toml";
|
|
12315
|
-
var POLICY_OUTPUT_DIR =
|
|
12599
|
+
var POLICY_OUTPUT_DIR = join17(tmpdir3(), "agent_moss");
|
|
12316
12600
|
var policyOutputDirOverride = null;
|
|
12317
12601
|
function policyOutputDir() {
|
|
12318
12602
|
return policyOutputDirOverride ?? POLICY_OUTPUT_DIR;
|
|
@@ -12351,7 +12635,7 @@ function savePolicyToFile(sessionId, policyToml) {
|
|
|
12351
12635
|
return null;
|
|
12352
12636
|
}
|
|
12353
12637
|
const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12354
|
-
const filepath =
|
|
12638
|
+
const filepath = join17(outDir, `${safeName}.toml`);
|
|
12355
12639
|
writePrivateText(filepath, policyToml);
|
|
12356
12640
|
return filepath;
|
|
12357
12641
|
} catch (err) {
|
|
@@ -12752,10 +13036,10 @@ function mineDangerousPatterns(sessions, minSup = 2, maxLen = 4) {
|
|
|
12752
13036
|
// src/agent-gate-reader.ts
|
|
12753
13037
|
init_esm_shims();
|
|
12754
13038
|
import * as fs7 from "fs";
|
|
12755
|
-
import * as
|
|
12756
|
-
import * as
|
|
12757
|
-
var DEFAULT_AGENTGATE_SQLITE =
|
|
12758
|
-
|
|
13039
|
+
import * as os4 from "os";
|
|
13040
|
+
import * as path7 from "path";
|
|
13041
|
+
var DEFAULT_AGENTGATE_SQLITE = path7.join(
|
|
13042
|
+
os4.homedir(),
|
|
12759
13043
|
".local",
|
|
12760
13044
|
"share",
|
|
12761
13045
|
"agent_gate",
|
|
@@ -12773,7 +13057,7 @@ function readJsonDir(dirPath, limit = 1e5) {
|
|
|
12773
13057
|
const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
|
|
12774
13058
|
for (const f of files.slice(-200)) {
|
|
12775
13059
|
const sid = f.replace(/\.json$/, "");
|
|
12776
|
-
const raw = fs7.readFileSync(
|
|
13060
|
+
const raw = fs7.readFileSync(path7.join(dirPath, f), "utf-8");
|
|
12777
13061
|
const arr = JSON.parse(raw);
|
|
12778
13062
|
if (!Array.isArray(arr)) continue;
|
|
12779
13063
|
for (const item of arr) {
|
|
@@ -12841,7 +13125,7 @@ function loadAgentGateSessions(dbPath = "") {
|
|
|
12841
13125
|
}
|
|
12842
13126
|
const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
|
|
12843
13127
|
if (sql.length > 0) return sql;
|
|
12844
|
-
const jsonDefault =
|
|
13128
|
+
const jsonDefault = path7.join(os4.homedir(), ".local", "share", "agent_gate", "tool_calls");
|
|
12845
13129
|
return readJsonDir(jsonDefault);
|
|
12846
13130
|
}
|
|
12847
13131
|
|
|
@@ -12965,7 +13249,7 @@ function poolsSnapshot() {
|
|
|
12965
13249
|
|
|
12966
13250
|
// src/routes.ts
|
|
12967
13251
|
init_metrics();
|
|
12968
|
-
import { join as
|
|
13252
|
+
import { join as join19, dirname as dirname12 } from "path";
|
|
12969
13253
|
import { fileURLToPath as fileURLToPath10 } from "url";
|
|
12970
13254
|
var __dirname9 = dirname12(fileURLToPath10(import.meta.url));
|
|
12971
13255
|
async function healthRoute(c) {
|
|
@@ -13365,7 +13649,7 @@ function getBrainRuleStore() {
|
|
|
13365
13649
|
return new BrainRuleStore();
|
|
13366
13650
|
}
|
|
13367
13651
|
function getBrainSkillManager() {
|
|
13368
|
-
const dir = resolveAssetDir(__dirname9, "skills") ??
|
|
13652
|
+
const dir = resolveAssetDir(__dirname9, "skills") ?? join19(__dirname9, "..", "..", "agent_moss", "skills");
|
|
13369
13653
|
return new BrainSkillManager(dir);
|
|
13370
13654
|
}
|
|
13371
13655
|
async function brainRulesRoute(c) {
|
|
@@ -13470,10 +13754,10 @@ init_rules_mode();
|
|
|
13470
13754
|
import { Hono } from "hono";
|
|
13471
13755
|
import { timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
13472
13756
|
import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
|
|
13473
|
-
import { join as
|
|
13757
|
+
import { join as join20, dirname as dirname13 } from "path";
|
|
13474
13758
|
import { fileURLToPath as fileURLToPath11 } from "url";
|
|
13475
13759
|
var __dirname10 = dirname13(fileURLToPath11(import.meta.url));
|
|
13476
|
-
var STATIC_DIR =
|
|
13760
|
+
var STATIC_DIR = join20(__dirname10, "static");
|
|
13477
13761
|
var CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
|
|
13478
13762
|
function getConsoleToken() {
|
|
13479
13763
|
return process.env[CONSOLE_TOKEN_ENV] || "";
|
|
@@ -13515,7 +13799,7 @@ function createConsoleRouter() {
|
|
|
13515
13799
|
console2.use("/api/*", authMiddleware());
|
|
13516
13800
|
console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
|
|
13517
13801
|
const serveIndex = (c) => {
|
|
13518
|
-
const indexFile =
|
|
13802
|
+
const indexFile = join20(STATIC_DIR, "index.html");
|
|
13519
13803
|
if (existsSync20(indexFile)) {
|
|
13520
13804
|
return c.html(readFileSync20(indexFile, "utf-8"));
|
|
13521
13805
|
}
|
|
@@ -13712,11 +13996,11 @@ function createConsoleRouter() {
|
|
|
13712
13996
|
if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
|
|
13713
13997
|
return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
|
|
13714
13998
|
}
|
|
13715
|
-
const userPath =
|
|
13999
|
+
const userPath = join20(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
|
|
13716
14000
|
const builtinDir = resolveAssetDir(__dirname10, "skills");
|
|
13717
14001
|
const candidates = [
|
|
13718
14002
|
...isRuntimeConfigDisabled() ? [] : [userPath],
|
|
13719
|
-
builtinDir ?
|
|
14003
|
+
builtinDir ? join20(builtinDir, `${skillId}.md`) : ""
|
|
13720
14004
|
].filter(Boolean);
|
|
13721
14005
|
for (const p of candidates) {
|
|
13722
14006
|
if (existsSync20(p)) {
|
|
@@ -13986,7 +14270,7 @@ function createApp() {
|
|
|
13986
14270
|
startLoopMonitor();
|
|
13987
14271
|
const limiter = new RateLimiter(rateLimitQps());
|
|
13988
14272
|
app.use("*", async (c, next) => {
|
|
13989
|
-
const
|
|
14273
|
+
const path8 = new URL(c.req.url).pathname;
|
|
13990
14274
|
const method = c.req.method.toUpperCase();
|
|
13991
14275
|
if (method === "OPTIONS") return next();
|
|
13992
14276
|
const maxBody = maxBodyBytes();
|
|
@@ -14000,16 +14284,16 @@ function createApp() {
|
|
|
14000
14284
|
if (originCheckEnabled()) {
|
|
14001
14285
|
const origin = c.req.header("origin") || "";
|
|
14002
14286
|
if (origin && !originAllowed(origin, c.req.header("host") || "")) {
|
|
14003
|
-
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${
|
|
14287
|
+
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path8}`);
|
|
14004
14288
|
return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
|
|
14005
14289
|
}
|
|
14006
14290
|
}
|
|
14007
|
-
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers,
|
|
14008
|
-
const isPublicPage = !
|
|
14291
|
+
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path8);
|
|
14292
|
+
const isPublicPage = !path8.startsWith("/console/api") && (path8 === "/console" || path8.startsWith("/console/"));
|
|
14009
14293
|
if (!okAuth && !isPublicPage) {
|
|
14010
14294
|
return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
|
|
14011
14295
|
}
|
|
14012
|
-
if (limiter.enabled &&
|
|
14296
|
+
if (limiter.enabled && path8.startsWith("/api/")) {
|
|
14013
14297
|
const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
|
|
14014
14298
|
if (!limiter.allow(key)) {
|
|
14015
14299
|
return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
|
|
@@ -14043,7 +14327,7 @@ function createApp() {
|
|
|
14043
14327
|
return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
|
|
14044
14328
|
}
|
|
14045
14329
|
}
|
|
14046
|
-
const pool = poolOf(
|
|
14330
|
+
const pool = poolOf(path8);
|
|
14047
14331
|
if (!take(`pool:${pool}`, poolLimit(pool))) {
|
|
14048
14332
|
const qkey = principal ? "p:" + principalHash(principal) : "c:local";
|
|
14049
14333
|
const [qn, abusive] = noteQueueReject(qkey);
|