@kenhkl/agent-moss 0.17.23 → 0.17.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/opendesk/rules.json +5 -0
- package/dist/cli.js +634 -283
- package/dist/engine/coordinator.js +463 -179
- package/dist/rules/l2_rules.json +4 -2
- package/dist/rules/logic_rules.json +65 -1
- package/dist/server.js +600 -249
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -1,11 +1,5 @@
|
|
|
1
1
|
var __defProp = Object.defineProperty;
|
|
2
2
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
4
|
-
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
5
|
-
}) : x)(function(x) {
|
|
6
|
-
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
7
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
8
|
-
});
|
|
9
3
|
var __esm = (fn, res) => function __init() {
|
|
10
4
|
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
11
5
|
};
|
|
@@ -407,22 +401,22 @@ function loadToolRegistry() {
|
|
|
407
401
|
data.tools = tools;
|
|
408
402
|
return data;
|
|
409
403
|
}
|
|
410
|
-
function scanStructEntry(cat, value,
|
|
404
|
+
function scanStructEntry(cat, value, path8) {
|
|
411
405
|
if (cat === "skills") {
|
|
412
406
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
413
|
-
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`);
|
|
414
408
|
return null;
|
|
415
409
|
}
|
|
416
410
|
const out = {};
|
|
417
411
|
for (const [skCat, skills] of Object.entries(value)) {
|
|
418
412
|
if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
|
|
419
|
-
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`);
|
|
420
414
|
continue;
|
|
421
415
|
}
|
|
422
416
|
const keep = {};
|
|
423
417
|
for (const [name, kws] of Object.entries(skills)) {
|
|
424
418
|
if (Array.isArray(kws)) keep[name] = kws;
|
|
425
|
-
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`);
|
|
426
420
|
}
|
|
427
421
|
if (Object.keys(keep).length > 0) out[skCat] = keep;
|
|
428
422
|
}
|
|
@@ -430,37 +424,37 @@ function scanStructEntry(cat, value, path7) {
|
|
|
430
424
|
}
|
|
431
425
|
if (cat === "ltl_rules") {
|
|
432
426
|
if (!Array.isArray(value)) {
|
|
433
|
-
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`);
|
|
434
428
|
return null;
|
|
435
429
|
}
|
|
436
430
|
const keep = value.filter((r) => r && typeof r === "object" && r.id);
|
|
437
431
|
if (keep.length !== value.length) {
|
|
438
|
-
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`);
|
|
439
433
|
}
|
|
440
434
|
return keep.length > 0 ? keep : null;
|
|
441
435
|
}
|
|
442
436
|
if (cat === "tools") {
|
|
443
437
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
444
|
-
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`);
|
|
445
439
|
return null;
|
|
446
440
|
}
|
|
447
441
|
const keep = {};
|
|
448
442
|
for (const [k, v] of Object.entries(value)) {
|
|
449
443
|
if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
|
|
450
|
-
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`);
|
|
451
445
|
}
|
|
452
446
|
return Object.keys(keep).length > 0 ? keep : null;
|
|
453
447
|
}
|
|
454
448
|
return null;
|
|
455
449
|
}
|
|
456
|
-
function scanRulesFile(
|
|
450
|
+
function scanRulesFile(path8, kind) {
|
|
457
451
|
const out = {};
|
|
458
452
|
const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
|
|
459
453
|
let parsed;
|
|
460
454
|
try {
|
|
461
|
-
parsed = JSON.parse(readFileSync2(
|
|
455
|
+
parsed = JSON.parse(readFileSync2(path8, "utf-8"));
|
|
462
456
|
} catch (e) {
|
|
463
|
-
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}`);
|
|
464
458
|
return out;
|
|
465
459
|
}
|
|
466
460
|
const classifyFlat = (r) => {
|
|
@@ -484,44 +478,44 @@ function scanRulesFile(path7, kind) {
|
|
|
484
478
|
}
|
|
485
479
|
if (flatBad > 0) {
|
|
486
480
|
console.warn(
|
|
487
|
-
`[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`
|
|
488
482
|
);
|
|
489
483
|
}
|
|
490
484
|
} else {
|
|
491
|
-
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`);
|
|
492
486
|
return out;
|
|
493
487
|
}
|
|
494
488
|
for (const [cat, rules] of pairs) {
|
|
495
489
|
if (String(cat).startsWith("_")) continue;
|
|
496
490
|
if (STRUCT_KEYS.includes(cat)) {
|
|
497
|
-
const got = scanStructEntry(cat, rules,
|
|
491
|
+
const got = scanStructEntry(cat, rules, path8);
|
|
498
492
|
if (got !== null) out[cat] = got;
|
|
499
493
|
continue;
|
|
500
494
|
}
|
|
501
495
|
const required = EXTRA_CATEGORIES[cat];
|
|
502
496
|
if (!required) {
|
|
503
497
|
console.warn(
|
|
504
|
-
`[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`
|
|
505
499
|
);
|
|
506
500
|
continue;
|
|
507
501
|
}
|
|
508
502
|
if (rules && typeof rules === "object" && !Array.isArray(rules)) {
|
|
509
503
|
console.error(
|
|
510
|
-
`[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
|
|
511
505
|
\u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
|
|
512
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`
|
|
513
507
|
);
|
|
514
508
|
continue;
|
|
515
509
|
}
|
|
516
510
|
if (!Array.isArray(rules)) {
|
|
517
|
-
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`);
|
|
518
512
|
continue;
|
|
519
513
|
}
|
|
520
514
|
const items = [];
|
|
521
515
|
for (const r of rules) {
|
|
522
516
|
if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
|
|
523
517
|
console.warn(
|
|
524
|
-
`[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`
|
|
525
519
|
);
|
|
526
520
|
continue;
|
|
527
521
|
}
|
|
@@ -531,7 +525,7 @@ function scanRulesFile(path7, kind) {
|
|
|
531
525
|
}
|
|
532
526
|
if (Object.keys(out).length > 0) {
|
|
533
527
|
console.info(
|
|
534
|
-
`[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(", ")
|
|
535
529
|
);
|
|
536
530
|
}
|
|
537
531
|
return out;
|
|
@@ -725,7 +719,7 @@ var init_rules_loader = __esm({
|
|
|
725
719
|
|
|
726
720
|
// src/infra/security-policy.ts
|
|
727
721
|
import { createHash as createHash2, randomBytes, timingSafeEqual } from "crypto";
|
|
728
|
-
import { chmodSync, closeSync, existsSync as existsSync3, lstatSync, mkdirSync, openSync, readFileSync as readFileSync4, readSync, realpathSync, writeSync } from "fs";
|
|
722
|
+
import { chmodSync, closeSync, constants as fsConstants, existsSync as existsSync3, lstatSync, mkdirSync, openSync, readFileSync as readFileSync4, readSync, realpathSync, writeSync } from "fs";
|
|
729
723
|
import { homedir as homedir2, tmpdir } from "os";
|
|
730
724
|
import { basename, isAbsolute, join as join4, relative, resolve as resolve2, dirname as dirname2 } from "path";
|
|
731
725
|
function env(name, dflt = "") {
|
|
@@ -801,10 +795,10 @@ function readExplicitToken() {
|
|
|
801
795
|
if (tok) return tok;
|
|
802
796
|
const fdTok = readFdToken();
|
|
803
797
|
if (fdTok) return fdTok;
|
|
804
|
-
const
|
|
805
|
-
if (
|
|
798
|
+
const path8 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
|
|
799
|
+
if (path8) {
|
|
806
800
|
try {
|
|
807
|
-
return readFileSync4(
|
|
801
|
+
return readFileSync4(path8, "utf-8").trim();
|
|
808
802
|
} catch {
|
|
809
803
|
return "";
|
|
810
804
|
}
|
|
@@ -812,23 +806,23 @@ function readExplicitToken() {
|
|
|
812
806
|
return "";
|
|
813
807
|
}
|
|
814
808
|
function ensureAutoToken() {
|
|
815
|
-
const
|
|
809
|
+
const path8 = autoTokenPath();
|
|
816
810
|
try {
|
|
817
|
-
if (existsSync3(
|
|
818
|
-
const tok2 = readFileSync4(
|
|
811
|
+
if (existsSync3(path8) && !lstatSync(path8).isSymbolicLink()) {
|
|
812
|
+
const tok2 = readFileSync4(path8, "utf-8").trim();
|
|
819
813
|
if (tok2) {
|
|
820
814
|
try {
|
|
821
|
-
chmodSync(
|
|
815
|
+
chmodSync(path8, 384);
|
|
822
816
|
} catch {
|
|
823
817
|
}
|
|
824
818
|
return tok2;
|
|
825
819
|
}
|
|
826
820
|
}
|
|
827
821
|
const tok = randomBytes(32).toString("base64url");
|
|
828
|
-
ensurePrivateDir(dirname2(
|
|
829
|
-
if (!writePrivateText(
|
|
822
|
+
ensurePrivateDir(dirname2(path8));
|
|
823
|
+
if (!writePrivateText(path8, tok + "\n")) return "";
|
|
830
824
|
console.warn(
|
|
831
|
-
`[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`
|
|
832
826
|
);
|
|
833
827
|
return tok;
|
|
834
828
|
} catch (e) {
|
|
@@ -901,16 +895,16 @@ function constEq(a, b) {
|
|
|
901
895
|
if (ba.length !== bb.length) return false;
|
|
902
896
|
return timingSafeEqual(ba, bb);
|
|
903
897
|
}
|
|
904
|
-
function checkRequestAuth(headers,
|
|
898
|
+
function checkRequestAuth(headers, path8) {
|
|
905
899
|
if (authMode() === AUTH_MODE_OFF) return [true, ""];
|
|
906
|
-
const isHealth = HEALTH_PATHS.includes(
|
|
900
|
+
const isHealth = HEALTH_PATHS.includes(path8.replace(/\/+$/, ""));
|
|
907
901
|
const [gt0, agents, err] = resolveAuth();
|
|
908
902
|
if (err) return isHealth ? [true, ""] : [false, ""];
|
|
909
903
|
if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
|
|
910
904
|
if (isHealth) return [true, ""];
|
|
911
905
|
const tok = bearer(headers);
|
|
912
906
|
if (!tok) return [false, ""];
|
|
913
|
-
if (
|
|
907
|
+
if (path8.startsWith("/console/api")) {
|
|
914
908
|
const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
|
|
915
909
|
if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
|
|
916
910
|
}
|
|
@@ -929,8 +923,8 @@ function bindAgent(principal, agentId) {
|
|
|
929
923
|
if (!agentId) return [true, bound];
|
|
930
924
|
return [bound === agentId, bound];
|
|
931
925
|
}
|
|
932
|
-
function principalOf(headers,
|
|
933
|
-
const [ok, principal] = checkRequestAuth(headers,
|
|
926
|
+
function principalOf(headers, path8 = "") {
|
|
927
|
+
const [ok, principal] = checkRequestAuth(headers, path8);
|
|
934
928
|
return ok ? principal : "";
|
|
935
929
|
}
|
|
936
930
|
function principalHash(principal) {
|
|
@@ -1009,9 +1003,8 @@ function ensurePrivateDir(dir) {
|
|
|
1009
1003
|
}
|
|
1010
1004
|
function writePrivateText(file, text) {
|
|
1011
1005
|
try {
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
if (flags.O_NOFOLLOW) openFlags |= flags.O_NOFOLLOW;
|
|
1006
|
+
let openFlags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC;
|
|
1007
|
+
if (fsConstants.O_NOFOLLOW) openFlags |= fsConstants.O_NOFOLLOW;
|
|
1015
1008
|
const fd = openSync(file, openFlags, 384);
|
|
1016
1009
|
try {
|
|
1017
1010
|
writeSync(fd, text);
|
|
@@ -1188,11 +1181,11 @@ function errorDetailMode() {
|
|
|
1188
1181
|
function maxBodyBytes() {
|
|
1189
1182
|
return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
|
|
1190
1183
|
}
|
|
1191
|
-
function poolOf(
|
|
1192
|
-
if (
|
|
1193
|
-
if (
|
|
1194
|
-
if (
|
|
1195
|
-
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";
|
|
1196
1189
|
return "other";
|
|
1197
1190
|
}
|
|
1198
1191
|
function poolLimit(name) {
|
|
@@ -1479,6 +1472,8 @@ var init_platform_traits = __esm({
|
|
|
1479
1472
|
|
|
1480
1473
|
// src/engine/logic-rules.ts
|
|
1481
1474
|
import * as fs from "fs";
|
|
1475
|
+
import * as path2 from "path";
|
|
1476
|
+
import * as os from "os";
|
|
1482
1477
|
function hasExecBypassChain(actionDetail) {
|
|
1483
1478
|
const execAfter = "&&|\\|\\||;|\\n|\\|";
|
|
1484
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);
|
|
@@ -1505,7 +1500,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
|
|
|
1505
1500
|
os: String(sp.os || "linux").toLowerCase()
|
|
1506
1501
|
}));
|
|
1507
1502
|
}
|
|
1508
|
-
function _scopeOf(
|
|
1503
|
+
function _scopeOf(os5, path8) {
|
|
1509
1504
|
if (!_scopeIndex) {
|
|
1510
1505
|
_scopeIndex = /* @__PURE__ */ new Map();
|
|
1511
1506
|
for (const sp of loadL1().sensitive_path_access || []) {
|
|
@@ -1513,7 +1508,7 @@ function _scopeOf(os4, path7) {
|
|
|
1513
1508
|
if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
|
|
1514
1509
|
}
|
|
1515
1510
|
}
|
|
1516
|
-
return _scopeIndex.get(`${String(
|
|
1511
|
+
return _scopeIndex.get(`${String(os5 || "linux").toLowerCase()}|${path8}`) || "root";
|
|
1517
1512
|
}
|
|
1518
1513
|
function getSensitivePathsForOs(osType) {
|
|
1519
1514
|
const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
|
|
@@ -1555,6 +1550,188 @@ function getSensitivePathsForOsBuiltin(osType) {
|
|
|
1555
1550
|
}
|
|
1556
1551
|
return { root: ROOT_SENSITIVE_PATHS, home: HOME_SENSITIVE_PATHS, credential: CREDENTIAL_PATHS };
|
|
1557
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
|
+
}
|
|
1558
1735
|
function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWORDS, osType) {
|
|
1559
1736
|
if (writeKeywords.some((kw) => actionType.includes(kw) || actionDetail.includes(kw))) return true;
|
|
1560
1737
|
const { writeCommandRes } = getPlatformTraits(osType);
|
|
@@ -1594,7 +1771,12 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
|
|
|
1594
1771
|
}
|
|
1595
1772
|
function getIntentPatternsForOs(osType) {
|
|
1596
1773
|
const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
|
|
1597
|
-
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
|
+
}
|
|
1598
1780
|
const accepted = acceptedOsValues(osType);
|
|
1599
1781
|
return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
|
|
1600
1782
|
}
|
|
@@ -1645,6 +1827,9 @@ function checkIntentConsistency(input) {
|
|
|
1645
1827
|
);
|
|
1646
1828
|
const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(actionDetail, kw));
|
|
1647
1829
|
if (intentMatched && dangerousMatched) {
|
|
1830
|
+
if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
|
|
1831
|
+
continue;
|
|
1832
|
+
}
|
|
1648
1833
|
return {
|
|
1649
1834
|
allowed: false,
|
|
1650
1835
|
reason: pattern.reason,
|
|
@@ -1665,7 +1850,16 @@ function runLogicCheck(input, opts) {
|
|
|
1665
1850
|
const resolvedCwd = cwd || "/";
|
|
1666
1851
|
const isExcludedType = EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p));
|
|
1667
1852
|
if (!opts?.skipReadBeforeWrite) {
|
|
1668
|
-
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
|
+
);
|
|
1669
1863
|
if (rbwResult) return rbwResult;
|
|
1670
1864
|
}
|
|
1671
1865
|
const intentResult = checkIntentConsistency(input);
|
|
@@ -1768,7 +1962,8 @@ function extractFilePaths(text, osType) {
|
|
|
1768
1962
|
}
|
|
1769
1963
|
return [...new Set(paths)];
|
|
1770
1964
|
}
|
|
1771
|
-
function checkReadBeforeWrite(actionType,
|
|
1965
|
+
function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason, cwd, osType, singleFileTools = SINGLE_FILE_WRITE_TOOLS) {
|
|
1966
|
+
const actionDetail = actionDetailRaw.toLowerCase();
|
|
1772
1967
|
if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
|
|
1773
1968
|
if (NON_WRITE_TOOLS.has(actionType)) return null;
|
|
1774
1969
|
const isBashLike = actionType === "bash" || actionType === "executebash" || actionType === "terminal-executebash";
|
|
@@ -1809,7 +2004,11 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1809
2004
|
const SOURCE_ARG_CMDS = new Set(_LOGIC.source_arg_commands ?? []);
|
|
1810
2005
|
const REDIRECT_TARGET_RE = new RegExp(`>{1,2}\\s*(?!&)(?:'(/[^']+)'|"(/[^\\"]+)"|(/[^\\s;|&><'\\"]+))`);
|
|
1811
2006
|
const targetPaths = [];
|
|
1812
|
-
|
|
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)) {
|
|
1813
2012
|
const trimmed = seg.trim();
|
|
1814
2013
|
if (!trimmed) continue;
|
|
1815
2014
|
const firstWord = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
|
|
@@ -1841,16 +2040,31 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1841
2040
|
targetPaths.push(...segPathsFiltered);
|
|
1842
2041
|
}
|
|
1843
2042
|
}
|
|
2043
|
+
if (singleFileTool) {
|
|
2044
|
+
targetPaths.length = 0;
|
|
2045
|
+
targetPaths.push(...declaredWritePaths(actionDetailRaw, osType));
|
|
2046
|
+
}
|
|
1844
2047
|
const uniqueTargetPaths = [...new Set(targetPaths)].filter((p) => !PSEUDO_FS_PREFIXES.some((pfx) => p.startsWith(pfx)));
|
|
1845
2048
|
if (uniqueTargetPaths.length === 0) return null;
|
|
1846
|
-
const
|
|
2049
|
+
const historyFullReadPaths = /* @__PURE__ */ new Set();
|
|
2050
|
+
const historyPartialRead = /* @__PURE__ */ new Map();
|
|
1847
2051
|
for (const action of actionHistory) {
|
|
1848
|
-
const
|
|
2052
|
+
const histDetailRaw = action.actionDetail;
|
|
1849
2053
|
const histType = action.actionType.toLowerCase();
|
|
1850
|
-
const
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
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);
|
|
1854
2068
|
}
|
|
1855
2069
|
}
|
|
1856
2070
|
}
|
|
@@ -1863,18 +2077,49 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
|
|
|
1863
2077
|
if (filteredPaths.length === 0) {
|
|
1864
2078
|
return null;
|
|
1865
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
|
+
}
|
|
1866
2101
|
const unreadPaths = [];
|
|
1867
|
-
for (const
|
|
1868
|
-
const
|
|
1869
|
-
(rp) =>
|
|
2102
|
+
for (const path8 of checkTargets) {
|
|
2103
|
+
const isFullRead = [...normalizedFullReads].some(
|
|
2104
|
+
(rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
|
|
1870
2105
|
);
|
|
1871
|
-
|
|
1872
|
-
|
|
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);
|
|
1873
2118
|
if (!isCreate) {
|
|
1874
2119
|
isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
|
|
1875
2120
|
}
|
|
1876
2121
|
if (!isCreate) {
|
|
1877
|
-
unreadPaths.push(
|
|
2122
|
+
unreadPaths.push(path8);
|
|
1878
2123
|
}
|
|
1879
2124
|
}
|
|
1880
2125
|
}
|
|
@@ -2051,7 +2296,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
|
|
|
2051
2296
|
violatedLayers: ["L2.1"]
|
|
2052
2297
|
};
|
|
2053
2298
|
}
|
|
2054
|
-
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;
|
|
2055
2300
|
var init_logic_rules = __esm({
|
|
2056
2301
|
"src/engine/logic-rules.ts"() {
|
|
2057
2302
|
"use strict";
|
|
@@ -2068,16 +2313,16 @@ var init_logic_rules = __esm({
|
|
|
2068
2313
|
ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
|
|
2069
2314
|
ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
|
|
2070
2315
|
HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
|
|
2071
|
-
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path:
|
|
2316
|
+
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2072
2317
|
ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
|
|
2073
2318
|
HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
|
|
2074
|
-
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 }));
|
|
2075
2320
|
ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
|
|
2076
2321
|
HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
|
|
2077
|
-
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 }));
|
|
2078
2323
|
ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
|
|
2079
2324
|
HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
|
|
2080
|
-
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 }));
|
|
2081
2326
|
_scopeIndex = null;
|
|
2082
2327
|
NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
|
|
2083
2328
|
"ask_user_question",
|
|
@@ -2100,6 +2345,23 @@ var init_logic_rules = __esm({
|
|
|
2100
2345
|
]);
|
|
2101
2346
|
NON_WRITE_TOOL_PREFIXES = _LOGIC.non_write_tool_prefixes ?? [];
|
|
2102
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;
|
|
2103
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"];
|
|
2104
2366
|
SED_INPLACE_RE = /\bsed\s+(?:-\S+\s+)*(?:-[a-zA-Z]*i[a-zA-Z]*|--in-place)\b/i;
|
|
2105
2367
|
DEVNULL_REDIRECT_RE = /(?:2|&|1)?\s*>\s*\/dev\/null\b/g;
|
|
@@ -2118,7 +2380,8 @@ var init_logic_rules = __esm({
|
|
|
2118
2380
|
intentKeywords: p.intent_keywords,
|
|
2119
2381
|
dangerousActions: p.dangerous_actions,
|
|
2120
2382
|
reason: p.reason,
|
|
2121
|
-
os: String(p.os || "linux").toLowerCase()
|
|
2383
|
+
os: String(p.os || "linux").toLowerCase(),
|
|
2384
|
+
allowIfWriteIntent: p.allow_if_write_intent === true
|
|
2122
2385
|
}));
|
|
2123
2386
|
})();
|
|
2124
2387
|
COMBO_STAGES = (() => {
|
|
@@ -2159,11 +2422,11 @@ var init_logic_rules = __esm({
|
|
|
2159
2422
|
|
|
2160
2423
|
// src/engine/asset-dir.ts
|
|
2161
2424
|
import { existsSync as existsSync5 } from "fs";
|
|
2162
|
-
import { join as
|
|
2425
|
+
import { join as join6, resolve as resolve3 } from "path";
|
|
2163
2426
|
function assetDirCandidates(moduleDir, name) {
|
|
2164
2427
|
const root = getRulesRoot();
|
|
2165
2428
|
if (root) {
|
|
2166
|
-
const p =
|
|
2429
|
+
const p = join6(root, name);
|
|
2167
2430
|
return [p, p];
|
|
2168
2431
|
}
|
|
2169
2432
|
return [
|
|
@@ -2382,7 +2645,7 @@ __export(runtime_config_exports, {
|
|
|
2382
2645
|
updateSkillEnabled: () => updateSkillEnabled
|
|
2383
2646
|
});
|
|
2384
2647
|
import { readFileSync as readFileSync6, writeFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, unlinkSync, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
|
|
2385
|
-
import { join as
|
|
2648
|
+
import { join as join7 } from "path";
|
|
2386
2649
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
2387
2650
|
import { dirname as dirname4 } from "path";
|
|
2388
2651
|
function runtimeDir() {
|
|
@@ -2518,8 +2781,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
|
|
|
2518
2781
|
function _filterRulesByOs(rules, osType) {
|
|
2519
2782
|
const accepted = acceptedOsValues(osType);
|
|
2520
2783
|
return rules.filter((r) => {
|
|
2521
|
-
const
|
|
2522
|
-
return
|
|
2784
|
+
const os5 = String(r.os || "linux").toLowerCase();
|
|
2785
|
+
return os5 === "all" || accepted.includes(os5);
|
|
2523
2786
|
});
|
|
2524
2787
|
}
|
|
2525
2788
|
function _userCustomRules(runtime, layers, requiredKey) {
|
|
@@ -2721,7 +2984,7 @@ function _l2SensitivePathsToRules() {
|
|
|
2721
2984
|
const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
|
|
2722
2985
|
const all = [...root, ...home, ...credential];
|
|
2723
2986
|
for (const sp of all) {
|
|
2724
|
-
const
|
|
2987
|
+
const os5 = String(sp.os || "linux").toLowerCase();
|
|
2725
2988
|
const denyMode = sp.denyMode || _deriveDenyMode({
|
|
2726
2989
|
deny_mode: sp.deny_mode,
|
|
2727
2990
|
credential: sp.credential,
|
|
@@ -2731,7 +2994,7 @@ function _l2SensitivePathsToRules() {
|
|
|
2731
2994
|
// id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
|
|
2732
2995
|
// hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
|
|
2733
2996
|
// Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
|
|
2734
|
-
id: `path_${
|
|
2997
|
+
id: `path_${os5}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
|
|
2735
2998
|
path: sp.path,
|
|
2736
2999
|
risk_level: sp.riskLevel,
|
|
2737
3000
|
desc: sp.desc,
|
|
@@ -2740,7 +3003,7 @@ function _l2SensitivePathsToRules() {
|
|
|
2740
3003
|
skip_l3_on_disabled: true,
|
|
2741
3004
|
enabled: true,
|
|
2742
3005
|
builtin: true,
|
|
2743
|
-
os:
|
|
3006
|
+
os: os5
|
|
2744
3007
|
};
|
|
2745
3008
|
_syncDenyModeFields(rule);
|
|
2746
3009
|
if (sp.dirDelOnly) rule.dir_del_only = true;
|
|
@@ -2758,6 +3021,9 @@ function _l2IntentPatternsToRules() {
|
|
|
2758
3021
|
intent_keywords: pat.intentKeywords,
|
|
2759
3022
|
dangerous_actions: pat.dangerousActions,
|
|
2760
3023
|
reason: pat.reason,
|
|
3024
|
+
// 旧 runtime 里没有这个字段:缺省 false,但 getIntentPatternsForOs 会按
|
|
3025
|
+
// reason 回填内置默认值,避免旧配置让新豁免失效。
|
|
3026
|
+
allow_if_write_intent: pat.allowIfWriteIntent,
|
|
2761
3027
|
skip_l3_on_disabled: true,
|
|
2762
3028
|
enabled: true,
|
|
2763
3029
|
builtin: true
|
|
@@ -2828,7 +3094,7 @@ function _l3SkillsToRules() {
|
|
|
2828
3094
|
function _scenarioRulesToDefaults() {
|
|
2829
3095
|
const out = {};
|
|
2830
3096
|
const _root = getRulesRoot();
|
|
2831
|
-
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;
|
|
2832
3098
|
if (!existsSync7(scenDir)) return out;
|
|
2833
3099
|
let entries;
|
|
2834
3100
|
try {
|
|
@@ -2837,7 +3103,7 @@ function _scenarioRulesToDefaults() {
|
|
|
2837
3103
|
return out;
|
|
2838
3104
|
}
|
|
2839
3105
|
for (const scenarioId of entries) {
|
|
2840
|
-
const rulesFile = resolveScenarioRulesFile(scenarioId) ??
|
|
3106
|
+
const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join7(scenDir, scenarioId, "rules.json");
|
|
2841
3107
|
if (!existsSync7(rulesFile)) continue;
|
|
2842
3108
|
let data;
|
|
2843
3109
|
try {
|
|
@@ -2878,7 +3144,7 @@ function _scenarioRulesToDefaults() {
|
|
|
2878
3144
|
function _agentRulesToDefaults() {
|
|
2879
3145
|
const out = {};
|
|
2880
3146
|
const _root = getRulesRoot();
|
|
2881
|
-
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;
|
|
2882
3148
|
if (!existsSync7(agentsDir)) return out;
|
|
2883
3149
|
let entries;
|
|
2884
3150
|
try {
|
|
@@ -2887,7 +3153,7 @@ function _agentRulesToDefaults() {
|
|
|
2887
3153
|
return out;
|
|
2888
3154
|
}
|
|
2889
3155
|
for (const agentId of entries) {
|
|
2890
|
-
const rulesFile =
|
|
3156
|
+
const rulesFile = join7(agentsDir, agentId, "rules.json");
|
|
2891
3157
|
if (!existsSync7(rulesFile)) continue;
|
|
2892
3158
|
let data;
|
|
2893
3159
|
try {
|
|
@@ -2920,6 +3186,11 @@ function _agentRulesToDefaults() {
|
|
|
2920
3186
|
category_enabled: true,
|
|
2921
3187
|
category_desc: "agent \u4E13\u5C5E\u654F\u611F\u8DEF\u5F84\uFF08L1 \u672B\u5C3E\u8FFD\u52A0\uFF09",
|
|
2922
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 }))
|
|
2923
3194
|
}
|
|
2924
3195
|
};
|
|
2925
3196
|
}
|
|
@@ -3268,8 +3539,8 @@ function _filterDefaultsByOs(rules, osType) {
|
|
|
3268
3539
|
const accepted = acceptedOsValues(osType);
|
|
3269
3540
|
return rules.filter((r) => {
|
|
3270
3541
|
if (!r.os) return true;
|
|
3271
|
-
const
|
|
3272
|
-
return
|
|
3542
|
+
const os5 = String(r.os).toLowerCase();
|
|
3543
|
+
return os5 === "all" || accepted.includes(os5);
|
|
3273
3544
|
});
|
|
3274
3545
|
}
|
|
3275
3546
|
function _hasRulesForOs(rules, osType) {
|
|
@@ -3394,7 +3665,8 @@ function effectiveIntentPatterns(osType) {
|
|
|
3394
3665
|
intentKeywords: r.intent_keywords || [],
|
|
3395
3666
|
dangerousActions: r.dangerous_actions || [],
|
|
3396
3667
|
reason: String(r.reason || ""),
|
|
3397
|
-
os: String(r.os || "linux").toLowerCase()
|
|
3668
|
+
os: String(r.os || "linux").toLowerCase(),
|
|
3669
|
+
allowIfWriteIntent: r.allow_if_write_intent === true
|
|
3398
3670
|
}));
|
|
3399
3671
|
});
|
|
3400
3672
|
}
|
|
@@ -3499,12 +3771,12 @@ function addCustomSkill(skillId, category, keywords, content) {
|
|
|
3499
3771
|
);
|
|
3500
3772
|
}
|
|
3501
3773
|
const runtime = loadRuntimeConfig();
|
|
3502
|
-
const skillsDir =
|
|
3774
|
+
const skillsDir = join7(getRuntimeConfigDir(), "agent_moss_skills");
|
|
3503
3775
|
try {
|
|
3504
3776
|
mkdirSync2(skillsDir, { recursive: true });
|
|
3505
3777
|
} catch {
|
|
3506
3778
|
}
|
|
3507
|
-
writeFileSync(
|
|
3779
|
+
writeFileSync(join7(skillsDir, `${skillId}.md`), content, "utf-8");
|
|
3508
3780
|
const l3 = runtime.L3_skills || (runtime.L3_skills = {});
|
|
3509
3781
|
const cat = l3[category] || (l3[category] = { category_enabled: true, category_desc: "", skills: [] });
|
|
3510
3782
|
(cat.skills || (cat.skills = [])).push({ id: skillId, keywords, enabled: true, builtin: false });
|
|
@@ -3519,7 +3791,7 @@ function deleteCustomSkill(skillId, category) {
|
|
|
3519
3791
|
if (idx >= 0) {
|
|
3520
3792
|
if (skills[idx].builtin) return null;
|
|
3521
3793
|
skills.splice(idx, 1);
|
|
3522
|
-
const skillPath =
|
|
3794
|
+
const skillPath = join7(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
|
|
3523
3795
|
try {
|
|
3524
3796
|
if (existsSync7(skillPath)) unlinkSync(skillPath);
|
|
3525
3797
|
} catch {
|
|
@@ -3582,6 +3854,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
|
|
|
3582
3854
|
read_only: r.read_only,
|
|
3583
3855
|
deny_mode: r.deny_mode
|
|
3584
3856
|
}));
|
|
3857
|
+
const singleFileWriteTools = _agentCategoryEnabledRules(agentData.extra_single_file_write_tools).filter((r) => r.value).map((r) => String(r.value).toLowerCase());
|
|
3585
3858
|
return {
|
|
3586
3859
|
agent_id: agentId,
|
|
3587
3860
|
description: "",
|
|
@@ -3590,6 +3863,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
|
|
|
3590
3863
|
extra_sensitive_paths: sensitivePaths,
|
|
3591
3864
|
builtin_safe_skills: safeSkills.filter((r) => r.value).map((r) => r.value),
|
|
3592
3865
|
builtin_safe_action_types: safeAction.filter((r) => r.value).map((r) => r.value),
|
|
3866
|
+
extra_single_file_write_tools: singleFileWriteTools,
|
|
3593
3867
|
extra_skills: []
|
|
3594
3868
|
};
|
|
3595
3869
|
}
|
|
@@ -3668,6 +3942,7 @@ function getEnabledScenarioExtensions(runtime, scenarioId) {
|
|
|
3668
3942
|
extra_sensitive_paths: sensitivePaths,
|
|
3669
3943
|
builtin_safe_skills: [],
|
|
3670
3944
|
builtin_safe_action_types: [],
|
|
3945
|
+
extra_single_file_write_tools: [],
|
|
3671
3946
|
extra_skills: []
|
|
3672
3947
|
};
|
|
3673
3948
|
}
|
|
@@ -3728,7 +4003,7 @@ var init_runtime_config = __esm({
|
|
|
3728
4003
|
__dirname4 = dirname4(fileURLToPath4(import.meta.url));
|
|
3729
4004
|
ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
|
|
3730
4005
|
RUNTIME_CONFIG_DIR = runtimeDir();
|
|
3731
|
-
RUNTIME_CONFIG_PATH =
|
|
4006
|
+
RUNTIME_CONFIG_PATH = join7(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
|
|
3732
4007
|
LAYER_DISABLE_ENV = {
|
|
3733
4008
|
L1_heuristic: "AGENT_MOSS_DISABLE_HEURISTIC",
|
|
3734
4009
|
L2_logic_rules: "AGENT_MOSS_DISABLE_LOGIC_RULES",
|
|
@@ -3756,10 +4031,10 @@ var init_runtime_config = __esm({
|
|
|
3756
4031
|
intent_consistency: ["intent_keywords", "reason"]
|
|
3757
4032
|
};
|
|
3758
4033
|
hasRuntimeConfigCache = /* @__PURE__ */ new Map();
|
|
3759
|
-
_AGENTS_DIR_PROD =
|
|
3760
|
-
_AGENTS_DIR_DEV =
|
|
3761
|
-
_SCENARIOS_DIR_PROD =
|
|
3762
|
-
_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");
|
|
3763
4038
|
_effectiveCache = /* @__PURE__ */ new WeakMap();
|
|
3764
4039
|
SKILL_ID_RE = /^[A-Za-z0-9_-]+$/;
|
|
3765
4040
|
registerRuntimeConfigBridge({
|
|
@@ -3802,7 +4077,7 @@ __export(config_exports, {
|
|
|
3802
4077
|
wildcardToRegExp: () => wildcardToRegExp
|
|
3803
4078
|
});
|
|
3804
4079
|
import fs2 from "fs";
|
|
3805
|
-
import
|
|
4080
|
+
import path3 from "path";
|
|
3806
4081
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
3807
4082
|
function loadConfigFile(filePath) {
|
|
3808
4083
|
try {
|
|
@@ -3815,17 +4090,17 @@ function loadConfigFile(filePath) {
|
|
|
3815
4090
|
function resolveConfigPath() {
|
|
3816
4091
|
const envPath = process.env.AGENT_MOSS_CONFIG_PATH;
|
|
3817
4092
|
if (envPath) return envPath;
|
|
3818
|
-
const userConfig =
|
|
4093
|
+
const userConfig = path3.join(getConfigDir(), "config.json");
|
|
3819
4094
|
if (fs2.existsSync(userConfig)) return userConfig;
|
|
3820
4095
|
const defaultCandidates = [
|
|
3821
|
-
|
|
3822
|
-
|
|
3823
|
-
|
|
3824
|
-
|
|
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")
|
|
3825
4100
|
];
|
|
3826
4101
|
const defaultConfig = defaultCandidates.find((p) => fs2.existsSync(p));
|
|
3827
4102
|
if (defaultConfig) {
|
|
3828
|
-
const configDir =
|
|
4103
|
+
const configDir = path3.dirname(userConfig);
|
|
3829
4104
|
fs2.mkdirSync(configDir, { recursive: true });
|
|
3830
4105
|
const pkgConfig = loadConfigFile(defaultConfig);
|
|
3831
4106
|
const safeConfig = pkgConfig ? { ...pkgConfig, llm: { ...pkgConfig.llm, api_key: "" } } : {};
|
|
@@ -4055,7 +4330,7 @@ var init_config = __esm({
|
|
|
4055
4330
|
init_rules_mode();
|
|
4056
4331
|
__configModuleDir = (() => {
|
|
4057
4332
|
try {
|
|
4058
|
-
return
|
|
4333
|
+
return path3.dirname(fileURLToPath5(import.meta.url));
|
|
4059
4334
|
} catch {
|
|
4060
4335
|
return typeof __dirname !== "undefined" ? __dirname : process.cwd();
|
|
4061
4336
|
}
|
|
@@ -4078,11 +4353,11 @@ var init_config = __esm({
|
|
|
4078
4353
|
};
|
|
4079
4354
|
})();
|
|
4080
4355
|
USER_RULES_PATHS = [
|
|
4081
|
-
|
|
4356
|
+
path3.join(__configModuleDir, "rules", "user_rules.json"),
|
|
4082
4357
|
// 源在 ts/src/rules(一般不存在)
|
|
4083
|
-
|
|
4358
|
+
path3.join(__configModuleDir, "..", "rules", "user_rules.json"),
|
|
4084
4359
|
// dist: dist/engine/../rules = dist/rules ✅
|
|
4085
|
-
|
|
4360
|
+
path3.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
|
|
4086
4361
|
// dev src: ts/src/../../agent_moss
|
|
4087
4362
|
];
|
|
4088
4363
|
customRules = loadCustomRules();
|
|
@@ -4100,11 +4375,11 @@ var init_config = __esm({
|
|
|
4100
4375
|
|
|
4101
4376
|
// src/agents/index.ts
|
|
4102
4377
|
import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
|
|
4103
|
-
import { resolve as resolve5, dirname as dirname5, join as
|
|
4378
|
+
import { resolve as resolve5, dirname as dirname5, join as join8 } from "path";
|
|
4104
4379
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
4105
4380
|
function resolveAgentsDir() {
|
|
4106
4381
|
const root = getRulesRoot();
|
|
4107
|
-
if (root) return
|
|
4382
|
+
if (root) return join8(root, "agents");
|
|
4108
4383
|
if (existsSync8(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
|
|
4109
4384
|
if (existsSync8(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
|
|
4110
4385
|
return AGENTS_DIR_PROD;
|
|
@@ -4165,6 +4440,7 @@ function mergeAgentExtensions(...exts) {
|
|
|
4165
4440
|
extra_sensitive_paths: nonNull.flatMap((e) => e.extra_sensitive_paths || []),
|
|
4166
4441
|
builtin_safe_skills: nonNull.flatMap((e) => e.builtin_safe_skills || []),
|
|
4167
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 || []),
|
|
4168
4444
|
extra_skills: nonNull.flatMap((e) => e.extra_skills || [])
|
|
4169
4445
|
};
|
|
4170
4446
|
}
|
|
@@ -4186,11 +4462,11 @@ var init_agents = __esm({
|
|
|
4186
4462
|
|
|
4187
4463
|
// src/scenarios/index.ts
|
|
4188
4464
|
import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
|
|
4189
|
-
import { resolve as resolve6, dirname as dirname6, join as
|
|
4465
|
+
import { resolve as resolve6, dirname as dirname6, join as join9 } from "path";
|
|
4190
4466
|
import { fileURLToPath as fileURLToPath7 } from "url";
|
|
4191
4467
|
function resolveScenariosDir() {
|
|
4192
4468
|
const root = getRulesRoot();
|
|
4193
|
-
if (root) return
|
|
4469
|
+
if (root) return join9(root, "scenarios");
|
|
4194
4470
|
if (existsSync9(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
|
|
4195
4471
|
if (existsSync9(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
|
|
4196
4472
|
return SCENARIOS_DIR_PROD;
|
|
@@ -4248,6 +4524,7 @@ function getScenarioExtensions(scenarioId) {
|
|
|
4248
4524
|
extra_sensitive_paths: data.extra_sensitive_paths || [],
|
|
4249
4525
|
builtin_safe_skills: data.builtin_safe_skills || [],
|
|
4250
4526
|
builtin_safe_action_types: data.builtin_safe_action_types || [],
|
|
4527
|
+
extra_single_file_write_tools: data.extra_single_file_write_tools || [],
|
|
4251
4528
|
extra_skills: data.extra_skills || []
|
|
4252
4529
|
};
|
|
4253
4530
|
} catch (e) {
|
|
@@ -4680,16 +4957,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4680
4957
|
if (String(osType || "").toLowerCase() === "windows") {
|
|
4681
4958
|
pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
|
|
4682
4959
|
}
|
|
4683
|
-
const pathMatches = (text,
|
|
4684
|
-
const parts =
|
|
4960
|
+
const pathMatches = (text, path8) => {
|
|
4961
|
+
const parts = path8.split(/(\(\?!.*?\))/);
|
|
4685
4962
|
const escaped = parts.map((part) => {
|
|
4686
4963
|
if (part.startsWith("(?!")) return part;
|
|
4687
4964
|
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4688
4965
|
}).join("");
|
|
4689
|
-
const re =
|
|
4966
|
+
const re = path8.startsWith(".") || path8.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
|
|
4690
4967
|
return re.test(text);
|
|
4691
4968
|
};
|
|
4692
|
-
const pathMatchesAny = (
|
|
4969
|
+
const pathMatchesAny = (path8) => pathScanTexts.some((t) => pathMatches(t, path8));
|
|
4693
4970
|
for (const sp of rootPaths) {
|
|
4694
4971
|
if (pathMatchesAny(sp.path.toLowerCase())) {
|
|
4695
4972
|
if (keygenGenerate) continue;
|
|
@@ -4832,8 +5109,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
4832
5109
|
}
|
|
4833
5110
|
return null;
|
|
4834
5111
|
}
|
|
4835
|
-
function isHomeValue(
|
|
4836
|
-
let p =
|
|
5112
|
+
function isHomeValue(path8) {
|
|
5113
|
+
let p = path8.trim().toLowerCase();
|
|
4837
5114
|
if (p.startsWith("$(") && p.endsWith(")")) {
|
|
4838
5115
|
const inner = p.slice(2, -1).trim();
|
|
4839
5116
|
return HOME_TARGET_RE.test(" " + inner);
|
|
@@ -4889,15 +5166,15 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
4889
5166
|
}
|
|
4890
5167
|
const assigned = {};
|
|
4891
5168
|
for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
|
|
4892
|
-
for (const [varName,
|
|
4893
|
-
if (!isHomeValue(
|
|
5169
|
+
for (const [varName, path8] of Object.entries(assigned)) {
|
|
5170
|
+
if (!isHomeValue(path8)) continue;
|
|
4894
5171
|
const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
|
|
4895
5172
|
for (const seg of segs) {
|
|
4896
5173
|
if (!isDeleteCommand(seg)) continue;
|
|
4897
5174
|
if (varRefRe.test(seg)) {
|
|
4898
5175
|
return {
|
|
4899
5176
|
allowed: false,
|
|
4900
|
-
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`,
|
|
4901
5178
|
riskLevel: "high",
|
|
4902
5179
|
riskType: "script_execution",
|
|
4903
5180
|
confidence: 90,
|
|
@@ -5193,7 +5470,7 @@ var init_template_loader = __esm({
|
|
|
5193
5470
|
|
|
5194
5471
|
// src/engine/script-analyzer.ts
|
|
5195
5472
|
import { readFileSync as readFileSync10 } from "fs";
|
|
5196
|
-
import { resolve as resolve8, join as
|
|
5473
|
+
import { resolve as resolve8, join as join10 } from "path";
|
|
5197
5474
|
function emptyResult() {
|
|
5198
5475
|
return { scriptPath: "", scriptContent: "", matchedKeywords: [], lineCount: 0, isSuspicious: false, error: "", riskLevel: "", riskReason: "" };
|
|
5199
5476
|
}
|
|
@@ -5246,7 +5523,7 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
|
|
|
5246
5523
|
}
|
|
5247
5524
|
function readScriptContent(scriptPath, maxLines = 500) {
|
|
5248
5525
|
try {
|
|
5249
|
-
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ?
|
|
5526
|
+
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join10(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
|
|
5250
5527
|
const raw = readFileSync10(expandedPath, "utf-8");
|
|
5251
5528
|
const lines = raw.split("\n").slice(0, maxLines);
|
|
5252
5529
|
return { content: lines.join("\n"), lineCount: lines.length, error: "" };
|
|
@@ -5701,15 +5978,15 @@ function parseShellString(s) {
|
|
|
5701
5978
|
let m;
|
|
5702
5979
|
while ((m = CHILD_CALL_RE.exec(s)) !== null) {
|
|
5703
5980
|
const interp = m[1];
|
|
5704
|
-
const
|
|
5981
|
+
const path8 = m[2].trim();
|
|
5705
5982
|
let rest = m[3].trim();
|
|
5706
|
-
if (
|
|
5983
|
+
if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
|
|
5707
5984
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5708
5985
|
const args = [];
|
|
5709
5986
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5710
5987
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5711
5988
|
}
|
|
5712
|
-
return { path:
|
|
5989
|
+
return { path: path8, args, interpreter: interp };
|
|
5713
5990
|
}
|
|
5714
5991
|
return null;
|
|
5715
5992
|
}
|
|
@@ -5755,9 +6032,9 @@ function extractCallsFromTree(tree, reachableLines) {
|
|
|
5755
6032
|
}
|
|
5756
6033
|
if (allStr && elts.length >= 2) {
|
|
5757
6034
|
const interp = elts[0];
|
|
5758
|
-
const
|
|
5759
|
-
if (!
|
|
5760
|
-
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 });
|
|
5761
6038
|
return true;
|
|
5762
6039
|
}
|
|
5763
6040
|
}
|
|
@@ -5797,15 +6074,15 @@ function extractCallsRegex(content) {
|
|
|
5797
6074
|
let m;
|
|
5798
6075
|
while ((m = CHILD_CALL_RE.exec(content)) !== null) {
|
|
5799
6076
|
const interp = m[1];
|
|
5800
|
-
const
|
|
6077
|
+
const path8 = m[2].trim();
|
|
5801
6078
|
let rest = m[3].trim();
|
|
5802
|
-
if (
|
|
6079
|
+
if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
|
|
5803
6080
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
5804
6081
|
const args = [];
|
|
5805
6082
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
5806
6083
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
5807
6084
|
}
|
|
5808
|
-
calls.push({ path:
|
|
6085
|
+
calls.push({ path: path8, args, interpreter: interp });
|
|
5809
6086
|
}
|
|
5810
6087
|
return calls;
|
|
5811
6088
|
}
|
|
@@ -6588,15 +6865,15 @@ function extractCallsFromContent(content) {
|
|
|
6588
6865
|
CHILD_CALL_RE2.lastIndex = 0;
|
|
6589
6866
|
while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
|
|
6590
6867
|
const interp = m[1];
|
|
6591
|
-
const
|
|
6868
|
+
const path8 = m[2].trim();
|
|
6592
6869
|
let rest = m[3].trim();
|
|
6593
|
-
if (
|
|
6870
|
+
if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
|
|
6594
6871
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
6595
6872
|
const args = [];
|
|
6596
6873
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
6597
6874
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
6598
6875
|
}
|
|
6599
|
-
calls.push({ path:
|
|
6876
|
+
calls.push({ path: path8, args, interpreter: interp });
|
|
6600
6877
|
}
|
|
6601
6878
|
return calls;
|
|
6602
6879
|
}
|
|
@@ -6665,8 +6942,8 @@ var init_backends = __esm({
|
|
|
6665
6942
|
|
|
6666
6943
|
// src/engine/script-engine/tracker.ts
|
|
6667
6944
|
import * as fs3 from "fs";
|
|
6668
|
-
import * as
|
|
6669
|
-
import * as
|
|
6945
|
+
import * as path4 from "path";
|
|
6946
|
+
import * as os2 from "os";
|
|
6670
6947
|
function maxFileSizeFromEnv() {
|
|
6671
6948
|
const raw = (process.env.AGENT_MOSS_SCRIPT_MAX_FILE_SIZE || "").trim();
|
|
6672
6949
|
if (raw) {
|
|
@@ -6685,11 +6962,11 @@ function pickBackend(pathStr) {
|
|
|
6685
6962
|
function resolvePath(p, baseDir) {
|
|
6686
6963
|
let expanded = p;
|
|
6687
6964
|
if (expanded.startsWith("~/") || expanded === "~") {
|
|
6688
|
-
expanded =
|
|
6689
|
-
} else if (!
|
|
6690
|
-
expanded =
|
|
6965
|
+
expanded = path4.join(os2.homedir(), expanded.slice(1));
|
|
6966
|
+
} else if (!path4.isAbsolute(expanded) && baseDir) {
|
|
6967
|
+
expanded = path4.join(baseDir, expanded);
|
|
6691
6968
|
}
|
|
6692
|
-
return
|
|
6969
|
+
return path4.resolve(expanded);
|
|
6693
6970
|
}
|
|
6694
6971
|
function readScript(pathStr, maxFileSize) {
|
|
6695
6972
|
try {
|
|
@@ -6783,7 +7060,7 @@ var init_tracker = __esm({
|
|
|
6783
7060
|
const baseDir = cwd || process.cwd();
|
|
6784
7061
|
const resolved = resolvePath(entryPath);
|
|
6785
7062
|
this.result.entryPath = resolved;
|
|
6786
|
-
this.visitScript(resolved, 0,
|
|
7063
|
+
this.visitScript(resolved, 0, path4.dirname(resolved), entryArgs);
|
|
6787
7064
|
const nodes = this.result.nodes;
|
|
6788
7065
|
this.result.hasCritical = nodes.some((n) => n.l1RiskLevel === "critical" || n.l2RiskLevel === "critical" || n.keywordRiskLevel === "critical") || this.result.hasCritical;
|
|
6789
7066
|
this.result.hasHigh = nodes.some((n) => ["high", "critical"].includes(n.l1RiskLevel) || ["high", "critical"].includes(n.l2RiskLevel) || ["high", "critical"].includes(n.keywordRiskLevel));
|
|
@@ -6845,12 +7122,12 @@ var init_tracker = __esm({
|
|
|
6845
7122
|
}
|
|
6846
7123
|
}
|
|
6847
7124
|
}
|
|
6848
|
-
const parentDir =
|
|
7125
|
+
const parentDir = path4.dirname(pathStr);
|
|
6849
7126
|
const childPaths = [];
|
|
6850
7127
|
for (const call of ir.calls) {
|
|
6851
7128
|
const child = resolvePath(call.path, parentDir);
|
|
6852
7129
|
childPaths.push(child);
|
|
6853
|
-
this.visitScript(child, depth + 1,
|
|
7130
|
+
this.visitScript(child, depth + 1, path4.dirname(child), call.args);
|
|
6854
7131
|
if (this.result.hasCritical) break;
|
|
6855
7132
|
}
|
|
6856
7133
|
node.childPaths = childPaths;
|
|
@@ -6862,8 +7139,8 @@ var init_tracker = __esm({
|
|
|
6862
7139
|
|
|
6863
7140
|
// src/engine/script-content-analyzer.ts
|
|
6864
7141
|
import { statSync as statSync4, existsSync as existsSync12 } from "fs";
|
|
6865
|
-
import { resolve as resolve10, join as
|
|
6866
|
-
import { homedir as
|
|
7142
|
+
import { resolve as resolve10, join as join12, isAbsolute as isAbsolute4 } from "path";
|
|
7143
|
+
import { homedir as homedir5 } from "os";
|
|
6867
7144
|
function emptyChain() {
|
|
6868
7145
|
return {
|
|
6869
7146
|
nodes: [],
|
|
@@ -7045,7 +7322,7 @@ function shlexSplit(s) {
|
|
|
7045
7322
|
function resolvePath2(p) {
|
|
7046
7323
|
let expanded = p;
|
|
7047
7324
|
if (expanded.startsWith("~/") || expanded === "~") {
|
|
7048
|
-
expanded =
|
|
7325
|
+
expanded = join12(homedir5(), expanded.slice(1));
|
|
7049
7326
|
}
|
|
7050
7327
|
return resolve10(expanded);
|
|
7051
7328
|
}
|
|
@@ -7168,8 +7445,8 @@ function analyzeScriptContent2(input, ext) {
|
|
|
7168
7445
|
resolvedPath = inline;
|
|
7169
7446
|
isInline = true;
|
|
7170
7447
|
}
|
|
7171
|
-
if (resolvedPath && !
|
|
7172
|
-
resolvedPath =
|
|
7448
|
+
if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
|
|
7449
|
+
resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
|
|
7173
7450
|
}
|
|
7174
7451
|
const l1Adapter = (content) => {
|
|
7175
7452
|
const j = scanDangerousCommandPatterns("bash", content, input.osType);
|
|
@@ -7287,7 +7564,7 @@ var init_script_content_analyzer = __esm({
|
|
|
7287
7564
|
|
|
7288
7565
|
// src/infra/trace-log.ts
|
|
7289
7566
|
import fs4 from "fs";
|
|
7290
|
-
import
|
|
7567
|
+
import path5 from "path";
|
|
7291
7568
|
function traceLevel() {
|
|
7292
7569
|
if (_levelCache !== null) return _levelCache;
|
|
7293
7570
|
const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
|
|
@@ -7314,7 +7591,7 @@ function tracePath() {
|
|
|
7314
7591
|
const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
|
|
7315
7592
|
if (explicit) return explicit;
|
|
7316
7593
|
try {
|
|
7317
|
-
return
|
|
7594
|
+
return path5.join(getDataRoot(), "agent_moss_trace.log");
|
|
7318
7595
|
} catch {
|
|
7319
7596
|
return "agent_moss_trace.log";
|
|
7320
7597
|
}
|
|
@@ -7353,7 +7630,7 @@ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
|
|
|
7353
7630
|
`;
|
|
7354
7631
|
const file = tracePath();
|
|
7355
7632
|
try {
|
|
7356
|
-
const dir =
|
|
7633
|
+
const dir = path5.dirname(file);
|
|
7357
7634
|
if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
|
|
7358
7635
|
try {
|
|
7359
7636
|
const st = fs4.statSync(file);
|
|
@@ -7949,7 +8226,7 @@ var init_token_stats = __esm({
|
|
|
7949
8226
|
|
|
7950
8227
|
// src/engine/llm-analyzer.ts
|
|
7951
8228
|
import { createHash as createHash3 } from "crypto";
|
|
7952
|
-
import { openSync as
|
|
8229
|
+
import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
|
|
7953
8230
|
import OpenAI from "openai";
|
|
7954
8231
|
function responseFieldLengths(message) {
|
|
7955
8232
|
if (!message || typeof message !== "object") return {};
|
|
@@ -8086,13 +8363,13 @@ function logPrompt(prompt, aNext, logPath) {
|
|
|
8086
8363
|
${prompt}
|
|
8087
8364
|
--- END PROMPT ---
|
|
8088
8365
|
`;
|
|
8089
|
-
let flags =
|
|
8090
|
-
if (
|
|
8091
|
-
const fd =
|
|
8366
|
+
let flags = fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_APPEND;
|
|
8367
|
+
if (fsConstants2.O_NOFOLLOW) flags |= fsConstants2.O_NOFOLLOW;
|
|
8368
|
+
const fd = openSync3(logPath, flags, 384);
|
|
8092
8369
|
try {
|
|
8093
8370
|
writeSync2(fd, line);
|
|
8094
8371
|
} finally {
|
|
8095
|
-
|
|
8372
|
+
closeSync3(fd);
|
|
8096
8373
|
}
|
|
8097
8374
|
} catch (e) {
|
|
8098
8375
|
console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
|
|
@@ -8388,8 +8665,8 @@ var init_llm_analyzer = __esm({
|
|
|
8388
8665
|
|
|
8389
8666
|
// src/brain/rule-store.ts
|
|
8390
8667
|
import { existsSync as existsSync14, readFileSync as readFileSync14, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
|
|
8391
|
-
import { join as
|
|
8392
|
-
import { homedir as
|
|
8668
|
+
import { join as join13 } from "path";
|
|
8669
|
+
import { homedir as homedir6 } from "os";
|
|
8393
8670
|
function getRulesPath() {
|
|
8394
8671
|
const envPath = process.env[ENV_RULES_PATH];
|
|
8395
8672
|
if (envPath) return envPath;
|
|
@@ -8407,7 +8684,7 @@ var init_rule_store = __esm({
|
|
|
8407
8684
|
"src/brain/rule-store.ts"() {
|
|
8408
8685
|
"use strict";
|
|
8409
8686
|
init_esm_shims();
|
|
8410
|
-
DEFAULT_RULES_PATH =
|
|
8687
|
+
DEFAULT_RULES_PATH = join13(homedir6(), ".agentmoss", "brain", "rules.json");
|
|
8411
8688
|
ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
|
|
8412
8689
|
STATUS_DRAFT = "draft";
|
|
8413
8690
|
STATUS_APPROVED = "approved";
|
|
@@ -8419,8 +8696,8 @@ var init_rule_store = __esm({
|
|
|
8419
8696
|
BrainRuleStore = class {
|
|
8420
8697
|
path;
|
|
8421
8698
|
data;
|
|
8422
|
-
constructor(
|
|
8423
|
-
this.path =
|
|
8699
|
+
constructor(path8) {
|
|
8700
|
+
this.path = path8 || getRulesPath();
|
|
8424
8701
|
this.data = this.load();
|
|
8425
8702
|
}
|
|
8426
8703
|
load() {
|
|
@@ -8873,10 +9150,10 @@ ${reason.slice(0, 500)}
|
|
|
8873
9150
|
const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
|
|
8874
9151
|
let mm;
|
|
8875
9152
|
while ((mm = pathRe.exec(src)) !== null) {
|
|
8876
|
-
const
|
|
8877
|
-
if (
|
|
8878
|
-
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(
|
|
8879
|
-
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);
|
|
8880
9157
|
if (seen.has(gen)) continue;
|
|
8881
9158
|
seen.add(gen);
|
|
8882
9159
|
patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
|
|
@@ -8895,8 +9172,8 @@ ${reason.slice(0, 500)}
|
|
|
8895
9172
|
}
|
|
8896
9173
|
return false;
|
|
8897
9174
|
}
|
|
8898
|
-
generalizePath(
|
|
8899
|
-
const p =
|
|
9175
|
+
generalizePath(path8) {
|
|
9176
|
+
const p = path8.toLowerCase();
|
|
8900
9177
|
if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
|
|
8901
9178
|
return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
|
|
8902
9179
|
}
|
|
@@ -9023,8 +9300,8 @@ var init_reviewer = __esm({
|
|
|
9023
9300
|
|
|
9024
9301
|
// src/brain/skill-manager.ts
|
|
9025
9302
|
import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync, writeFileSync as writeFileSync4 } from "fs";
|
|
9026
|
-
import { homedir as
|
|
9027
|
-
import { join as
|
|
9303
|
+
import { homedir as homedir7 } from "os";
|
|
9304
|
+
import { join as join14 } from "path";
|
|
9028
9305
|
import { randomUUID } from "crypto";
|
|
9029
9306
|
function getMetaPath(override) {
|
|
9030
9307
|
return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
|
|
@@ -9034,14 +9311,14 @@ var init_skill_manager = __esm({
|
|
|
9034
9311
|
"src/brain/skill-manager.ts"() {
|
|
9035
9312
|
"use strict";
|
|
9036
9313
|
init_esm_shims();
|
|
9037
|
-
DEFAULT_SKILL_META_PATH =
|
|
9314
|
+
DEFAULT_SKILL_META_PATH = join14(homedir7(), ".agentmoss", "brain", "skill_meta.json");
|
|
9038
9315
|
ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
|
|
9039
9316
|
BrainSkillManager = class {
|
|
9040
9317
|
constructor(skillsDir, metaPath) {
|
|
9041
9318
|
this.skillsDir = skillsDir;
|
|
9042
9319
|
this.metaPath = getMetaPath(metaPath);
|
|
9043
9320
|
try {
|
|
9044
|
-
mkdirSync5(
|
|
9321
|
+
mkdirSync5(join14(this.metaPath, ".."), { recursive: true });
|
|
9045
9322
|
} catch {
|
|
9046
9323
|
}
|
|
9047
9324
|
this.load();
|
|
@@ -9076,7 +9353,7 @@ var init_skill_manager = __esm({
|
|
|
9076
9353
|
let changed = false;
|
|
9077
9354
|
for (const sk of this.skills) {
|
|
9078
9355
|
if (sk.status !== "active") continue;
|
|
9079
|
-
if (!existsSync15(
|
|
9356
|
+
if (!existsSync15(join14(this.skillsDir, `${sk.name}.md`))) {
|
|
9080
9357
|
sk.status = "stale";
|
|
9081
9358
|
changed = true;
|
|
9082
9359
|
}
|
|
@@ -9088,7 +9365,7 @@ var init_skill_manager = __esm({
|
|
|
9088
9365
|
const id = skill.id || randomUUID();
|
|
9089
9366
|
const name = skill.name || `brain_${id.slice(0, 8)}`;
|
|
9090
9367
|
if (!existsSync15(this.skillsDir)) return "";
|
|
9091
|
-
const mdPath =
|
|
9368
|
+
const mdPath = join14(this.skillsDir, `${name}.md`);
|
|
9092
9369
|
if (existsSync15(mdPath)) return "";
|
|
9093
9370
|
try {
|
|
9094
9371
|
writeFileSync4(mdPath, skill.content, "utf-8");
|
|
@@ -9138,7 +9415,7 @@ var init_skill_manager = __esm({
|
|
|
9138
9415
|
const out = [];
|
|
9139
9416
|
for (const sk of this.skills) {
|
|
9140
9417
|
if (sk.origin_node !== "local" || sk.status !== "active") continue;
|
|
9141
|
-
const mdPath =
|
|
9418
|
+
const mdPath = join14(this.skillsDir, `${sk.name}.md`);
|
|
9142
9419
|
if (!existsSync15(mdPath)) continue;
|
|
9143
9420
|
out.push({
|
|
9144
9421
|
name: sk.name,
|
|
@@ -9742,12 +10019,12 @@ var init_builder = __esm({
|
|
|
9742
10019
|
});
|
|
9743
10020
|
|
|
9744
10021
|
// src/engine/formal-engine/properties.ts
|
|
9745
|
-
function graphFromPath(nodes,
|
|
10022
|
+
function graphFromPath(nodes, path8, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
|
|
9746
10023
|
const byKey = /* @__PURE__ */ new Map();
|
|
9747
10024
|
for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
|
|
9748
10025
|
const gNodes = [];
|
|
9749
10026
|
const gEdges = [];
|
|
9750
|
-
for (const item of
|
|
10027
|
+
for (const item of path8) {
|
|
9751
10028
|
const n = byKey.get(`${item.sessionId}#${item.seq}`);
|
|
9752
10029
|
gNodes.push({
|
|
9753
10030
|
session_id: item.sessionId,
|
|
@@ -9813,22 +10090,22 @@ function checkCrossSessionChain(graph) {
|
|
|
9813
10090
|
if (witness !== void 0) {
|
|
9814
10091
|
if (nodes[witness].stage !== stages[stages.length - 1]) continue;
|
|
9815
10092
|
let matched = 0;
|
|
9816
|
-
const
|
|
10093
|
+
const path8 = [];
|
|
9817
10094
|
for (let k = 0; k < witness; k++) {
|
|
9818
10095
|
const n = nodes[k];
|
|
9819
10096
|
if (matched < stages.length - 1 && n.stage === stages[matched]) {
|
|
9820
10097
|
matched += 1;
|
|
9821
|
-
|
|
10098
|
+
path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9822
10099
|
}
|
|
9823
10100
|
}
|
|
9824
10101
|
if (matched < stages.length - 1) continue;
|
|
9825
|
-
|
|
10102
|
+
path8.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
|
|
9826
10103
|
violations.push({
|
|
9827
10104
|
propertyId: "cross-" + chain.id,
|
|
9828
10105
|
reason: chain.reason,
|
|
9829
10106
|
riskLevel: chain.riskLevel,
|
|
9830
|
-
path:
|
|
9831
|
-
graph: graphFromPath(nodes,
|
|
10107
|
+
path: path8,
|
|
10108
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
9832
10109
|
property_id: "cross-" + chain.id,
|
|
9833
10110
|
property_short: "P1",
|
|
9834
10111
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -9838,11 +10115,11 @@ function checkCrossSessionChain(graph) {
|
|
|
9838
10115
|
} else {
|
|
9839
10116
|
let matched = 0;
|
|
9840
10117
|
let stageIdx = 0;
|
|
9841
|
-
const
|
|
10118
|
+
const path8 = [];
|
|
9842
10119
|
for (const n of nodes) {
|
|
9843
10120
|
if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
|
|
9844
10121
|
matched += 1;
|
|
9845
|
-
|
|
10122
|
+
path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
9846
10123
|
stageIdx += 1;
|
|
9847
10124
|
if (matched >= stages.length) break;
|
|
9848
10125
|
}
|
|
@@ -9852,8 +10129,8 @@ function checkCrossSessionChain(graph) {
|
|
|
9852
10129
|
propertyId: "cross-" + chain.id,
|
|
9853
10130
|
reason: chain.reason,
|
|
9854
10131
|
riskLevel: chain.riskLevel,
|
|
9855
|
-
path:
|
|
9856
|
-
graph: graphFromPath(nodes,
|
|
10132
|
+
path: path8,
|
|
10133
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
9857
10134
|
property_id: "cross-" + chain.id,
|
|
9858
10135
|
property_short: "P1",
|
|
9859
10136
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -10074,7 +10351,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10074
10351
|
if (candidates.length > 0) {
|
|
10075
10352
|
const pre = nodes[candidates[candidates.length - 1]];
|
|
10076
10353
|
const post = nodes[firstEv];
|
|
10077
|
-
const
|
|
10354
|
+
const path8 = [
|
|
10078
10355
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
10079
10356
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
10080
10357
|
];
|
|
@@ -10082,8 +10359,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10082
10359
|
propertyId: "no-exfil-after-privesc",
|
|
10083
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",
|
|
10084
10361
|
riskLevel: "critical",
|
|
10085
|
-
path:
|
|
10086
|
-
graph: graphFromPath(nodes,
|
|
10362
|
+
path: path8,
|
|
10363
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
10087
10364
|
property_id: "no-exfil-after-privesc",
|
|
10088
10365
|
property_short: "P4",
|
|
10089
10366
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10100,7 +10377,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10100
10377
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
10101
10378
|
if (!isExfilNode(nodes[j])) continue;
|
|
10102
10379
|
if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
|
|
10103
|
-
const
|
|
10380
|
+
const path8 = [
|
|
10104
10381
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
10105
10382
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
10106
10383
|
];
|
|
@@ -10108,8 +10385,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
10108
10385
|
propertyId: "no-exfil-after-privesc",
|
|
10109
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",
|
|
10110
10387
|
riskLevel: "critical",
|
|
10111
|
-
path:
|
|
10112
|
-
graph: graphFromPath(nodes,
|
|
10388
|
+
path: path8,
|
|
10389
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
10113
10390
|
property_id: "no-exfil-after-privesc",
|
|
10114
10391
|
property_short: "P4",
|
|
10115
10392
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10141,7 +10418,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10141
10418
|
}
|
|
10142
10419
|
if (pre) {
|
|
10143
10420
|
const post = nodes[firstEv];
|
|
10144
|
-
const
|
|
10421
|
+
const path8 = [
|
|
10145
10422
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
10146
10423
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
10147
10424
|
];
|
|
@@ -10149,8 +10426,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10149
10426
|
propertyId: "no-exfil-after-credential",
|
|
10150
10427
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
10151
10428
|
riskLevel: "critical",
|
|
10152
|
-
path:
|
|
10153
|
-
graph: graphFromPath(nodes,
|
|
10429
|
+
path: path8,
|
|
10430
|
+
graph: graphFromPath(nodes, path8, "data", {
|
|
10154
10431
|
property_id: "no-exfil-after-credential",
|
|
10155
10432
|
property_short: "P5",
|
|
10156
10433
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10166,7 +10443,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10166
10443
|
if (!isCredNode(nodes[i])) continue;
|
|
10167
10444
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
10168
10445
|
if (isExfilNode(nodes[j])) {
|
|
10169
|
-
const
|
|
10446
|
+
const path8 = [
|
|
10170
10447
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
10171
10448
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
10172
10449
|
];
|
|
@@ -10174,8 +10451,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
10174
10451
|
propertyId: "no-exfil-after-credential",
|
|
10175
10452
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
10176
10453
|
riskLevel: "critical",
|
|
10177
|
-
path:
|
|
10178
|
-
graph: graphFromPath(nodes,
|
|
10454
|
+
path: path8,
|
|
10455
|
+
graph: graphFromPath(nodes, path8, "data", {
|
|
10179
10456
|
property_id: "no-exfil-after-credential",
|
|
10180
10457
|
property_short: "P5",
|
|
10181
10458
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -10334,13 +10611,13 @@ function checkSensitiveDataAggregation(graph) {
|
|
|
10334
10611
|
if (!isExfilNode(n)) continue;
|
|
10335
10612
|
const srcs = sourcesFor(i);
|
|
10336
10613
|
if (srcs.size >= 2) {
|
|
10337
|
-
const
|
|
10614
|
+
const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
10338
10615
|
violations.push({
|
|
10339
10616
|
propertyId: "sensitive-data-aggregation",
|
|
10340
10617
|
reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
|
|
10341
10618
|
riskLevel: "critical",
|
|
10342
|
-
path:
|
|
10343
|
-
graph: graphFromPath(nodes,
|
|
10619
|
+
path: path8,
|
|
10620
|
+
graph: graphFromPath(nodes, path8, "next", {
|
|
10344
10621
|
property_id: "sensitive-data-aggregation",
|
|
10345
10622
|
property_short: "P8",
|
|
10346
10623
|
property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
|
|
@@ -10799,11 +11076,11 @@ var init_stateful = __esm({
|
|
|
10799
11076
|
}
|
|
10800
11077
|
}
|
|
10801
11078
|
chainPath(stages) {
|
|
10802
|
-
const
|
|
11079
|
+
const path8 = [];
|
|
10803
11080
|
let want = stages[0];
|
|
10804
11081
|
for (const n of this.nodes_) {
|
|
10805
11082
|
if (n.stage === want) {
|
|
10806
|
-
|
|
11083
|
+
path8.push({
|
|
10807
11084
|
sessionId: n.sessionId,
|
|
10808
11085
|
seq: n.seq,
|
|
10809
11086
|
stage: n.stage,
|
|
@@ -10819,12 +11096,12 @@ var init_stateful = __esm({
|
|
|
10819
11096
|
}
|
|
10820
11097
|
}
|
|
10821
11098
|
}
|
|
10822
|
-
return
|
|
11099
|
+
return path8;
|
|
10823
11100
|
}
|
|
10824
11101
|
/** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
|
|
10825
11102
|
buildChainGraph(stages, chainId) {
|
|
10826
|
-
const
|
|
10827
|
-
const gNodes =
|
|
11103
|
+
const path8 = this.chainPath(stages);
|
|
11104
|
+
const gNodes = path8.map((p, i) => {
|
|
10828
11105
|
const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
|
|
10829
11106
|
return {
|
|
10830
11107
|
session_id: p.sessionId,
|
|
@@ -11076,13 +11353,13 @@ var init_stateful = __esm({
|
|
|
11076
11353
|
|
|
11077
11354
|
// src/engine/formal-engine/chain_state.ts
|
|
11078
11355
|
import * as fs5 from "fs";
|
|
11079
|
-
import * as
|
|
11080
|
-
import * as
|
|
11356
|
+
import * as os3 from "os";
|
|
11357
|
+
import * as path6 from "path";
|
|
11081
11358
|
import { createHash as createHash4 } from "crypto";
|
|
11082
11359
|
function defaultStateDbPath() {
|
|
11083
|
-
const dir = process.env.AGENT_MOSS_STATE_DIR ||
|
|
11360
|
+
const dir = process.env.AGENT_MOSS_STATE_DIR || path6.join(os3.homedir(), ".agentmoss");
|
|
11084
11361
|
const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
|
|
11085
|
-
return
|
|
11362
|
+
return path6.join(dir, `stateful_chains_${tag}.json`);
|
|
11086
11363
|
}
|
|
11087
11364
|
function registerExitFlush(store) {
|
|
11088
11365
|
if (_exitHookRegistered) return;
|
|
@@ -11140,6 +11417,13 @@ var init_chain_state = __esm({
|
|
|
11140
11417
|
_trackers = /* @__PURE__ */ new Map();
|
|
11141
11418
|
/** 自上次落盘以来变过的 agentId */
|
|
11142
11419
|
_dirty = /* @__PURE__ */ new Set();
|
|
11420
|
+
/**
|
|
11421
|
+
* 多进程模式(2026-11,对齐 Python `enable_multi_process`):
|
|
11422
|
+
* AGENT_MOSS_MULTI_PROCESS=1 时启用。Node cluster / PM2 多进程部署下,
|
|
11423
|
+
* 各进程的 `data` 是独立快照,防抖写会互相覆盖(JSON 文件没有 SQLite 那样的锁)。
|
|
11424
|
+
* 启用后:每次 applyAction 用**文件锁**串行化,锁内重新读文件 → 判定 → 立即写。
|
|
11425
|
+
*/
|
|
11426
|
+
_multiProcess = false;
|
|
11143
11427
|
constructor(filePath = "") {
|
|
11144
11428
|
this.filePath = filePath || defaultStateDbPath();
|
|
11145
11429
|
this.data = this._read();
|
|
@@ -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
|
}
|
|
@@ -11210,6 +11494,55 @@ var init_chain_state = __esm({
|
|
|
11210
11494
|
delete this.data[agentId];
|
|
11211
11495
|
this._scheduleWrite();
|
|
11212
11496
|
}
|
|
11497
|
+
/** 启用多进程模式(对齐 Python)。 */
|
|
11498
|
+
enableMultiProcess() {
|
|
11499
|
+
this._multiProcess = true;
|
|
11500
|
+
}
|
|
11501
|
+
/**
|
|
11502
|
+
* 同步文件锁(原子创建 `<file>.lock`)。
|
|
11503
|
+
*
|
|
11504
|
+
* Node 是单线程,锁竞争时用 Atomics.wait 做**同步睡眠**而不是忙等 ——
|
|
11505
|
+
* 忙等会把事件循环完全占死,其它请求也没法推进。
|
|
11506
|
+
*/
|
|
11507
|
+
_withFileLock(fn) {
|
|
11508
|
+
const lockPath = `${this.filePath}.lock`;
|
|
11509
|
+
const sleepBuf = new Int32Array(new SharedArrayBuffer(4));
|
|
11510
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
11511
|
+
try {
|
|
11512
|
+
const fd = fs5.openSync(lockPath, "wx");
|
|
11513
|
+
try {
|
|
11514
|
+
return fn();
|
|
11515
|
+
} finally {
|
|
11516
|
+
try {
|
|
11517
|
+
fs5.closeSync(fd);
|
|
11518
|
+
} catch {
|
|
11519
|
+
}
|
|
11520
|
+
try {
|
|
11521
|
+
fs5.unlinkSync(lockPath);
|
|
11522
|
+
} catch {
|
|
11523
|
+
}
|
|
11524
|
+
}
|
|
11525
|
+
} catch (e) {
|
|
11526
|
+
if (e?.code !== "EEXIST") throw e;
|
|
11527
|
+
try {
|
|
11528
|
+
Atomics.wait(sleepBuf, 0, 0, 20);
|
|
11529
|
+
} catch {
|
|
11530
|
+
}
|
|
11531
|
+
}
|
|
11532
|
+
}
|
|
11533
|
+
throw new Error(`chain state lock timeout: ${lockPath}`);
|
|
11534
|
+
}
|
|
11535
|
+
/** 立即把内存写进文件(多进程模式用,不走防抖)。 */
|
|
11536
|
+
_flushNow() {
|
|
11537
|
+
this._syncDirtyToData();
|
|
11538
|
+
try {
|
|
11539
|
+
const _dirOk = ensurePrivateDir(path6.dirname(this.filePath));
|
|
11540
|
+
const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
11541
|
+
if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
|
|
11542
|
+
} catch (e) {
|
|
11543
|
+
console.error("[AgentMoss] chain state flush failed:", e?.message || e);
|
|
11544
|
+
}
|
|
11545
|
+
}
|
|
11213
11546
|
/** 当前内存中的 tracker 数 / 节点总数(健康检查用)。 */
|
|
11214
11547
|
stats() {
|
|
11215
11548
|
let nodes = 0;
|
|
@@ -11217,6 +11550,17 @@ var init_chain_state = __esm({
|
|
|
11217
11550
|
return { agents: this._trackers.size, nodes };
|
|
11218
11551
|
}
|
|
11219
11552
|
applyAction(agentId, aNext, sessionId, isError = false, sourceAgent = "", instanceId = "") {
|
|
11553
|
+
if (this._multiProcess) {
|
|
11554
|
+
return this._withFileLock(() => {
|
|
11555
|
+
this.data = this._read();
|
|
11556
|
+
this._trackers.clear();
|
|
11557
|
+
const t2 = this.load(agentId) || new StatefulChainTracker(agentId);
|
|
11558
|
+
const r2 = t2.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
|
|
11559
|
+
this.save(t2);
|
|
11560
|
+
this._flushNow();
|
|
11561
|
+
return r2;
|
|
11562
|
+
});
|
|
11563
|
+
}
|
|
11220
11564
|
const t = this.load(agentId) || new StatefulChainTracker(agentId);
|
|
11221
11565
|
const r = t.advance({ aNext, sessionId, isError, agentId: sourceAgent, instanceId });
|
|
11222
11566
|
this.save(t);
|
|
@@ -11489,7 +11833,7 @@ async function runAnalysis(input) {
|
|
|
11489
11833
|
skipLLM = true;
|
|
11490
11834
|
}
|
|
11491
11835
|
}
|
|
11492
|
-
const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
|
|
11836
|
+
const logicResult = isLogicRulesEnabled() ? runLogicCheck(input, { agentExt }) : null;
|
|
11493
11837
|
if (logicResult) {
|
|
11494
11838
|
traceSummary("l2.result", {
|
|
11495
11839
|
hit: !logicResult.allowed,
|
|
@@ -12045,7 +12389,7 @@ init_security_policy();
|
|
|
12045
12389
|
init_coordinator();
|
|
12046
12390
|
import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
|
|
12047
12391
|
import { tmpdir as tmpdir3 } from "os";
|
|
12048
|
-
import { join as
|
|
12392
|
+
import { join as join17, resolve as resolve11 } from "path";
|
|
12049
12393
|
|
|
12050
12394
|
// src/infra/policy-cache.ts
|
|
12051
12395
|
init_esm_shims();
|
|
@@ -12053,10 +12397,10 @@ init_security_policy();
|
|
|
12053
12397
|
init_paths();
|
|
12054
12398
|
init_config();
|
|
12055
12399
|
import { createHash as createHash5 } from "crypto";
|
|
12056
|
-
import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as
|
|
12400
|
+
import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
|
|
12057
12401
|
import { tmpdir as tmpdir2 } from "os";
|
|
12058
|
-
import { join as
|
|
12059
|
-
var CACHE_DIR =
|
|
12402
|
+
import { join as join16 } from "path";
|
|
12403
|
+
var CACHE_DIR = join16(tmpdir2(), "agent_moss_policy_cache");
|
|
12060
12404
|
var cacheDirOverride = null;
|
|
12061
12405
|
function cacheDir() {
|
|
12062
12406
|
return cacheDirOverride ?? CACHE_DIR;
|
|
@@ -12065,7 +12409,7 @@ function safeCacheDir() {
|
|
|
12065
12409
|
const dir = cacheDir();
|
|
12066
12410
|
if (ensurePrivateDir(dir)) return dir;
|
|
12067
12411
|
try {
|
|
12068
|
-
const fallback =
|
|
12412
|
+
const fallback = join16(getDataRoot(), "policy_cache");
|
|
12069
12413
|
if (ensurePrivateDir(fallback)) {
|
|
12070
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}`);
|
|
12071
12415
|
return fallback;
|
|
@@ -12087,7 +12431,7 @@ var PolicyCache = class {
|
|
|
12087
12431
|
cacheFilePath(sessionId, promptSession) {
|
|
12088
12432
|
const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
|
|
12089
12433
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12090
|
-
return
|
|
12434
|
+
return join16(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
|
|
12091
12435
|
}
|
|
12092
12436
|
/** 取缓存:内存 → 文件;未命中返回 null。 */
|
|
12093
12437
|
get(sessionId, promptSession) {
|
|
@@ -12118,7 +12462,7 @@ var PolicyCache = class {
|
|
|
12118
12462
|
try {
|
|
12119
12463
|
const dir = safeCacheDir();
|
|
12120
12464
|
const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12121
|
-
if (!ensurePrivateDir(
|
|
12465
|
+
if (!ensurePrivateDir(join16(dir, sub))) return;
|
|
12122
12466
|
writePrivateText(file, policy);
|
|
12123
12467
|
} catch {
|
|
12124
12468
|
}
|
|
@@ -12135,7 +12479,7 @@ var PolicyCache = class {
|
|
|
12135
12479
|
invalidate(sessionId, promptSession) {
|
|
12136
12480
|
this.memory.delete(this.cacheKey(sessionId, promptSession));
|
|
12137
12481
|
try {
|
|
12138
|
-
|
|
12482
|
+
unlinkSync4(this.cacheFilePath(sessionId, promptSession));
|
|
12139
12483
|
} catch {
|
|
12140
12484
|
}
|
|
12141
12485
|
}
|
|
@@ -12144,12 +12488,12 @@ var PolicyCache = class {
|
|
|
12144
12488
|
if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
|
|
12145
12489
|
}
|
|
12146
12490
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12147
|
-
const dir =
|
|
12491
|
+
const dir = join16(cacheDir(), safeSessionId);
|
|
12148
12492
|
try {
|
|
12149
12493
|
if (existsSync17(dir)) {
|
|
12150
12494
|
for (const f of readdirSync5(dir)) {
|
|
12151
12495
|
try {
|
|
12152
|
-
|
|
12496
|
+
unlinkSync4(join16(dir, f));
|
|
12153
12497
|
} catch {
|
|
12154
12498
|
}
|
|
12155
12499
|
}
|
|
@@ -12163,9 +12507,9 @@ var PolicyCache = class {
|
|
|
12163
12507
|
try {
|
|
12164
12508
|
if (existsSync17(cacheDir())) {
|
|
12165
12509
|
for (const sessionDir of readdirSync5(cacheDir())) {
|
|
12166
|
-
const dir =
|
|
12510
|
+
const dir = join16(cacheDir(), sessionDir);
|
|
12167
12511
|
try {
|
|
12168
|
-
for (const f of readdirSync5(dir))
|
|
12512
|
+
for (const f of readdirSync5(dir)) unlinkSync4(join16(dir, f));
|
|
12169
12513
|
rmdirSync(dir);
|
|
12170
12514
|
} catch {
|
|
12171
12515
|
}
|
|
@@ -12252,7 +12596,7 @@ ${safe(policy, 2e3)}`);
|
|
|
12252
12596
|
|
|
12253
12597
|
// src/engine/analyzer.ts
|
|
12254
12598
|
import { parse as parseToml } from "smol-toml";
|
|
12255
|
-
var POLICY_OUTPUT_DIR =
|
|
12599
|
+
var POLICY_OUTPUT_DIR = join17(tmpdir3(), "agent_moss");
|
|
12256
12600
|
var policyOutputDirOverride = null;
|
|
12257
12601
|
function policyOutputDir() {
|
|
12258
12602
|
return policyOutputDirOverride ?? POLICY_OUTPUT_DIR;
|
|
@@ -12291,7 +12635,7 @@ function savePolicyToFile(sessionId, policyToml) {
|
|
|
12291
12635
|
return null;
|
|
12292
12636
|
}
|
|
12293
12637
|
const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
12294
|
-
const filepath =
|
|
12638
|
+
const filepath = join17(outDir, `${safeName}.toml`);
|
|
12295
12639
|
writePrivateText(filepath, policyToml);
|
|
12296
12640
|
return filepath;
|
|
12297
12641
|
} catch (err) {
|
|
@@ -12692,10 +13036,10 @@ function mineDangerousPatterns(sessions, minSup = 2, maxLen = 4) {
|
|
|
12692
13036
|
// src/agent-gate-reader.ts
|
|
12693
13037
|
init_esm_shims();
|
|
12694
13038
|
import * as fs7 from "fs";
|
|
12695
|
-
import * as
|
|
12696
|
-
import * as
|
|
12697
|
-
var DEFAULT_AGENTGATE_SQLITE =
|
|
12698
|
-
|
|
13039
|
+
import * as os4 from "os";
|
|
13040
|
+
import * as path7 from "path";
|
|
13041
|
+
var DEFAULT_AGENTGATE_SQLITE = path7.join(
|
|
13042
|
+
os4.homedir(),
|
|
12699
13043
|
".local",
|
|
12700
13044
|
"share",
|
|
12701
13045
|
"agent_gate",
|
|
@@ -12713,7 +13057,7 @@ function readJsonDir(dirPath, limit = 1e5) {
|
|
|
12713
13057
|
const files = fs7.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
|
|
12714
13058
|
for (const f of files.slice(-200)) {
|
|
12715
13059
|
const sid = f.replace(/\.json$/, "");
|
|
12716
|
-
const raw = fs7.readFileSync(
|
|
13060
|
+
const raw = fs7.readFileSync(path7.join(dirPath, f), "utf-8");
|
|
12717
13061
|
const arr = JSON.parse(raw);
|
|
12718
13062
|
if (!Array.isArray(arr)) continue;
|
|
12719
13063
|
for (const item of arr) {
|
|
@@ -12781,7 +13125,7 @@ function loadAgentGateSessions(dbPath = "") {
|
|
|
12781
13125
|
}
|
|
12782
13126
|
const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
|
|
12783
13127
|
if (sql.length > 0) return sql;
|
|
12784
|
-
const jsonDefault =
|
|
13128
|
+
const jsonDefault = path7.join(os4.homedir(), ".local", "share", "agent_gate", "tool_calls");
|
|
12785
13129
|
return readJsonDir(jsonDefault);
|
|
12786
13130
|
}
|
|
12787
13131
|
|
|
@@ -12905,7 +13249,7 @@ function poolsSnapshot() {
|
|
|
12905
13249
|
|
|
12906
13250
|
// src/routes.ts
|
|
12907
13251
|
init_metrics();
|
|
12908
|
-
import { join as
|
|
13252
|
+
import { join as join19, dirname as dirname12 } from "path";
|
|
12909
13253
|
import { fileURLToPath as fileURLToPath10 } from "url";
|
|
12910
13254
|
var __dirname9 = dirname12(fileURLToPath10(import.meta.url));
|
|
12911
13255
|
async function healthRoute(c) {
|
|
@@ -13305,7 +13649,7 @@ function getBrainRuleStore() {
|
|
|
13305
13649
|
return new BrainRuleStore();
|
|
13306
13650
|
}
|
|
13307
13651
|
function getBrainSkillManager() {
|
|
13308
|
-
const dir = resolveAssetDir(__dirname9, "skills") ??
|
|
13652
|
+
const dir = resolveAssetDir(__dirname9, "skills") ?? join19(__dirname9, "..", "..", "agent_moss", "skills");
|
|
13309
13653
|
return new BrainSkillManager(dir);
|
|
13310
13654
|
}
|
|
13311
13655
|
async function brainRulesRoute(c) {
|
|
@@ -13409,11 +13753,11 @@ init_asset_dir();
|
|
|
13409
13753
|
init_rules_mode();
|
|
13410
13754
|
import { Hono } from "hono";
|
|
13411
13755
|
import { timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
13412
|
-
import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as
|
|
13413
|
-
import { join as
|
|
13756
|
+
import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync5 } from "fs";
|
|
13757
|
+
import { join as join20, dirname as dirname13 } from "path";
|
|
13414
13758
|
import { fileURLToPath as fileURLToPath11 } from "url";
|
|
13415
13759
|
var __dirname10 = dirname13(fileURLToPath11(import.meta.url));
|
|
13416
|
-
var STATIC_DIR =
|
|
13760
|
+
var STATIC_DIR = join20(__dirname10, "static");
|
|
13417
13761
|
var CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
|
|
13418
13762
|
function getConsoleToken() {
|
|
13419
13763
|
return process.env[CONSOLE_TOKEN_ENV] || "";
|
|
@@ -13455,7 +13799,7 @@ function createConsoleRouter() {
|
|
|
13455
13799
|
console2.use("/api/*", authMiddleware());
|
|
13456
13800
|
console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
|
|
13457
13801
|
const serveIndex = (c) => {
|
|
13458
|
-
const indexFile =
|
|
13802
|
+
const indexFile = join20(STATIC_DIR, "index.html");
|
|
13459
13803
|
if (existsSync20(indexFile)) {
|
|
13460
13804
|
return c.html(readFileSync20(indexFile, "utf-8"));
|
|
13461
13805
|
}
|
|
@@ -13652,11 +13996,11 @@ function createConsoleRouter() {
|
|
|
13652
13996
|
if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
|
|
13653
13997
|
return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
|
|
13654
13998
|
}
|
|
13655
|
-
const userPath =
|
|
13999
|
+
const userPath = join20(dirname13(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
|
|
13656
14000
|
const builtinDir = resolveAssetDir(__dirname10, "skills");
|
|
13657
14001
|
const candidates = [
|
|
13658
14002
|
...isRuntimeConfigDisabled() ? [] : [userPath],
|
|
13659
|
-
builtinDir ?
|
|
14003
|
+
builtinDir ? join20(builtinDir, `${skillId}.md`) : ""
|
|
13660
14004
|
].filter(Boolean);
|
|
13661
14005
|
for (const p of candidates) {
|
|
13662
14006
|
if (existsSync20(p)) {
|
|
@@ -13757,7 +14101,7 @@ function createConsoleRouter() {
|
|
|
13757
14101
|
const defaults = generateSourceDefaults();
|
|
13758
14102
|
try {
|
|
13759
14103
|
const p = getRuntimeConfigPath();
|
|
13760
|
-
if (existsSync20(p))
|
|
14104
|
+
if (existsSync20(p)) unlinkSync5(p);
|
|
13761
14105
|
} catch {
|
|
13762
14106
|
}
|
|
13763
14107
|
return c.json(withL22View(defaults));
|
|
@@ -13900,6 +14244,13 @@ var RateLimiter = class {
|
|
|
13900
14244
|
}
|
|
13901
14245
|
};
|
|
13902
14246
|
function createApp() {
|
|
14247
|
+
try {
|
|
14248
|
+
if (String(process.env.AGENT_MOSS_MULTI_PROCESS || "").toLowerCase() in { "1": 1, "true": 1, "yes": 1, "on": 1 }) {
|
|
14249
|
+
getChainStateStore().enableMultiProcess();
|
|
14250
|
+
console.log("[AgentMoss] \u94FE\u72B6\u6001\u591A\u8FDB\u7A0B\u6A21\u5F0F\uFF1A\u5DF2\u542F\u7528\uFF08\u6587\u4EF6\u9501 + \u7ACB\u5373\u843D\u76D8\uFF09");
|
|
14251
|
+
}
|
|
14252
|
+
} catch {
|
|
14253
|
+
}
|
|
13903
14254
|
enforceRulesContract();
|
|
13904
14255
|
hardenExistingPaths();
|
|
13905
14256
|
const app = new Hono2();
|
|
@@ -13919,7 +14270,7 @@ function createApp() {
|
|
|
13919
14270
|
startLoopMonitor();
|
|
13920
14271
|
const limiter = new RateLimiter(rateLimitQps());
|
|
13921
14272
|
app.use("*", async (c, next) => {
|
|
13922
|
-
const
|
|
14273
|
+
const path8 = new URL(c.req.url).pathname;
|
|
13923
14274
|
const method = c.req.method.toUpperCase();
|
|
13924
14275
|
if (method === "OPTIONS") return next();
|
|
13925
14276
|
const maxBody = maxBodyBytes();
|
|
@@ -13933,16 +14284,16 @@ function createApp() {
|
|
|
13933
14284
|
if (originCheckEnabled()) {
|
|
13934
14285
|
const origin = c.req.header("origin") || "";
|
|
13935
14286
|
if (origin && !originAllowed(origin, c.req.header("host") || "")) {
|
|
13936
|
-
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}`);
|
|
13937
14288
|
return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
|
|
13938
14289
|
}
|
|
13939
14290
|
}
|
|
13940
|
-
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers,
|
|
13941
|
-
const isPublicPage = !
|
|
14291
|
+
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path8);
|
|
14292
|
+
const isPublicPage = !path8.startsWith("/console/api") && (path8 === "/console" || path8.startsWith("/console/"));
|
|
13942
14293
|
if (!okAuth && !isPublicPage) {
|
|
13943
14294
|
return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
|
|
13944
14295
|
}
|
|
13945
|
-
if (limiter.enabled &&
|
|
14296
|
+
if (limiter.enabled && path8.startsWith("/api/")) {
|
|
13946
14297
|
const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
|
|
13947
14298
|
if (!limiter.allow(key)) {
|
|
13948
14299
|
return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
|
|
@@ -13976,7 +14327,7 @@ function createApp() {
|
|
|
13976
14327
|
return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
|
|
13977
14328
|
}
|
|
13978
14329
|
}
|
|
13979
|
-
const pool = poolOf(
|
|
14330
|
+
const pool = poolOf(path8);
|
|
13980
14331
|
if (!take(`pool:${pool}`, poolLimit(pool))) {
|
|
13981
14332
|
const qkey = principal ? "p:" + principalHash(principal) : "c:local";
|
|
13982
14333
|
const [qn, abusive] = noteQueueReject(qkey);
|
|
@@ -14108,7 +14459,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
|
|
|
14108
14459
|
},
|
|
14109
14460
|
serve: async () => {
|
|
14110
14461
|
failFastOnAuthError();
|
|
14111
|
-
const { mkdirSync: mkdirSync8, existsSync: existsSync22, unlinkSync:
|
|
14462
|
+
const { mkdirSync: mkdirSync8, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
|
|
14112
14463
|
const { dirname: dirname14 } = await import("path");
|
|
14113
14464
|
const dir = dirname14(socketPath);
|
|
14114
14465
|
if (dir) {
|
|
@@ -14135,7 +14486,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
|
|
|
14135
14486
|
);
|
|
14136
14487
|
} else {
|
|
14137
14488
|
try {
|
|
14138
|
-
|
|
14489
|
+
unlinkSync6(socketPath);
|
|
14139
14490
|
console.log(`[AgentMoss] \u6E05\u7406\u6B8B\u7559 socket \u6587\u4EF6: ${socketPath}`);
|
|
14140
14491
|
} catch {
|
|
14141
14492
|
}
|