@kenhkl/agent-moss 0.17.41 → 0.17.43
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/clawpartner/rules.json +14 -0
- package/dist/cli.js +942 -267
- package/dist/engine/coordinator.d.ts +7 -0
- package/dist/engine/coordinator.js +543 -126
- package/dist/rules/l2_rules.json +57 -3
- package/dist/scenarios/cloud/rules.json +11 -0
- package/dist/scenarios/endpoint/rules.json +11 -0
- package/dist/server.js +877 -220
- package/dist/templates/security_judge_template.txt +1 -1
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -764,6 +764,12 @@ function originAllowed(origin, hostHeader, extra) {
|
|
|
764
764
|
return false;
|
|
765
765
|
}
|
|
766
766
|
}
|
|
767
|
+
function validGateCallId(value) {
|
|
768
|
+
return typeof value === "string" && /^[0-9a-f]{32}$/.test(value);
|
|
769
|
+
}
|
|
770
|
+
function validGateCallTime(value) {
|
|
771
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= Number.MAX_SAFE_INTEGER;
|
|
772
|
+
}
|
|
767
773
|
function authMode() {
|
|
768
774
|
return (env("AGENT_MOSS_AUTH_MODE", AUTH_MODE_AUTO) || AUTH_MODE_AUTO).toLowerCase();
|
|
769
775
|
}
|
|
@@ -858,13 +864,17 @@ function parseAgentTokens(raw) {
|
|
|
858
864
|
}
|
|
859
865
|
function resolveAuth() {
|
|
860
866
|
const rawAgents = env("AGENT_MOSS_AGENT_TOKENS");
|
|
867
|
+
const gateToken = env("AGENT_MOSS_GATE_AUTH_TOKEN");
|
|
868
|
+
const consoleToken = env("AGENT_MOSS_CONSOLE_TOKEN");
|
|
861
869
|
const key = [
|
|
862
870
|
authMode(),
|
|
863
871
|
env("AGENT_MOSS_AUTH_TOKEN"),
|
|
864
872
|
env("AGENT_MOSS_AUTH_TOKEN_FILE"),
|
|
865
873
|
env("AGENT_MOSS_AUTH_TOKEN_FD"),
|
|
866
874
|
rawAgents,
|
|
867
|
-
env("AGENT_MOSS_DATA_DIR")
|
|
875
|
+
env("AGENT_MOSS_DATA_DIR"),
|
|
876
|
+
gateToken,
|
|
877
|
+
consoleToken
|
|
868
878
|
].join("\0");
|
|
869
879
|
if (tokenCache && tokenCache.key === key) {
|
|
870
880
|
return [tokenCache.token, tokenCache.agents, tokenCache.error];
|
|
@@ -887,6 +897,13 @@ function resolveAuth() {
|
|
|
887
897
|
}
|
|
888
898
|
}
|
|
889
899
|
const agents = parseAgentTokens(rawAgents);
|
|
900
|
+
if (!error && authMode() === AUTH_MODE_OFF && gateToken) {
|
|
901
|
+
error = "AGENT_MOSS_GATE_AUTH_TOKEN \u4E0D\u80FD\u5728 AGENT_MOSS_AUTH_MODE=off \u65F6\u542F\u7528";
|
|
902
|
+
} else if (!error && gateToken) {
|
|
903
|
+
if (gateToken === token || gateToken === consoleToken || Object.values(agents).includes(gateToken)) {
|
|
904
|
+
error = "AGENT_MOSS_GATE_AUTH_TOKEN \u5FC5\u987B\u4E0E\u5168\u5C40\u3001Agent \u548C Console \u51ED\u636E\u4E0D\u540C";
|
|
905
|
+
}
|
|
906
|
+
}
|
|
890
907
|
tokenCache = { key, token, agents, error };
|
|
891
908
|
return [token, agents, error];
|
|
892
909
|
}
|
|
@@ -906,7 +923,7 @@ function failFastOnAuthError() {
|
|
|
906
923
|
function authEnabled() {
|
|
907
924
|
if (authMode() === AUTH_MODE_OFF) return false;
|
|
908
925
|
const [tok, agents, err] = resolveAuth();
|
|
909
|
-
return Boolean(err) || Boolean(tok) || Object.keys(agents).length > 0;
|
|
926
|
+
return Boolean(err) || Boolean(tok) || Object.keys(agents).length > 0 || Boolean(env("AGENT_MOSS_GATE_AUTH_TOKEN"));
|
|
910
927
|
}
|
|
911
928
|
function bearer(headers) {
|
|
912
929
|
const get = (k) => headers instanceof Headers ? headers.get(k) ?? "" : headers[k] ?? "";
|
|
@@ -921,14 +938,19 @@ function constEq(a, b) {
|
|
|
921
938
|
}
|
|
922
939
|
function checkRequestAuth(headers, path9) {
|
|
923
940
|
if (authMode() === AUTH_MODE_OFF) return [true, ""];
|
|
924
|
-
const
|
|
941
|
+
const normalizedPath = path9.replace(/\/+$/, "");
|
|
942
|
+
const isHealth = HEALTH_PATHS.includes(normalizedPath);
|
|
925
943
|
const [gt0, agents, err] = resolveAuth();
|
|
944
|
+
const gateToken = env("AGENT_MOSS_GATE_AUTH_TOKEN");
|
|
926
945
|
if (err) return isHealth ? [true, ""] : [false, ""];
|
|
927
|
-
if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
|
|
946
|
+
if (!gt0 && Object.keys(agents).length === 0 && !gateToken) return [true, ""];
|
|
928
947
|
if (isHealth) return [true, ""];
|
|
929
948
|
const tok = bearer(headers);
|
|
930
949
|
if (!tok) return [false, ""];
|
|
931
|
-
if (
|
|
950
|
+
if (gateToken && GATE_AUTH_PATHS.has(normalizedPath) && constEq(tok, gateToken)) {
|
|
951
|
+
return [true, GATE_PRINCIPAL];
|
|
952
|
+
}
|
|
953
|
+
if (normalizedPath.startsWith("/console/api")) {
|
|
932
954
|
const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
|
|
933
955
|
if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
|
|
934
956
|
}
|
|
@@ -1274,7 +1296,7 @@ function maxConnections() {
|
|
|
1274
1296
|
function keepAliveSec() {
|
|
1275
1297
|
return envInt("AGENT_MOSS_KEEP_ALIVE_SEC", 5);
|
|
1276
1298
|
}
|
|
1277
|
-
var TRUTHY2, HEALTH_PATHS, AUTH_MODE_AUTO, AUTH_MODE_OFF, tokenCache, fdTokenCache, BLOCKED_HOSTS, sessionWindow, queueRejects, POOL_DEFAULTS;
|
|
1299
|
+
var TRUTHY2, HEALTH_PATHS, AUTH_MODE_AUTO, AUTH_MODE_OFF, GATE_PRINCIPAL, GATE_IDENTITY_HEADER, GATE_CALL_ID_HEADER, GATE_RATE_LIMIT_HEADER, GATE_BUSY_HEADER, GATE_AUTH_PATHS, tokenCache, fdTokenCache, BLOCKED_HOSTS, sessionWindow, queueRejects, POOL_DEFAULTS;
|
|
1278
1300
|
var init_security_policy = __esm({
|
|
1279
1301
|
"src/infra/security-policy.ts"() {
|
|
1280
1302
|
"use strict";
|
|
@@ -1284,6 +1306,12 @@ var init_security_policy = __esm({
|
|
|
1284
1306
|
HEALTH_PATHS = ["/api/v1/health"];
|
|
1285
1307
|
AUTH_MODE_AUTO = "auto";
|
|
1286
1308
|
AUTH_MODE_OFF = "off";
|
|
1309
|
+
GATE_PRINCIPAL = "gate";
|
|
1310
|
+
GATE_IDENTITY_HEADER = "X-AgentGate-Require-Identity";
|
|
1311
|
+
GATE_CALL_ID_HEADER = "X-AgentGate-Call-Id";
|
|
1312
|
+
GATE_RATE_LIMIT_HEADER = "X-AgentGate-Rate-Limited-Call-Id";
|
|
1313
|
+
GATE_BUSY_HEADER = "X-AgentGate-Busy-Call-Id";
|
|
1314
|
+
GATE_AUTH_PATHS = /* @__PURE__ */ new Set(["/api/v1/analyze", "/api/v1/review"]);
|
|
1287
1315
|
tokenCache = null;
|
|
1288
1316
|
fdTokenCache = /* @__PURE__ */ new Map();
|
|
1289
1317
|
BLOCKED_HOSTS = ["169.254.169.254", "metadata.google.internal", "metadata.tencentyun.com"];
|
|
@@ -2015,11 +2043,64 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
|
|
|
2015
2043
|
}
|
|
2016
2044
|
return false;
|
|
2017
2045
|
}
|
|
2046
|
+
function intentKeywordNegated(text, index) {
|
|
2047
|
+
if (NEGATION_WORDS.length === 0 || index <= 0) return false;
|
|
2048
|
+
const prefix = text.slice(Math.max(0, index - NEGATION_WINDOW), index);
|
|
2049
|
+
return NEGATION_WORDS.some((neg) => prefix.includes(neg));
|
|
2050
|
+
}
|
|
2051
|
+
function isBuildArtifactCleanup(actionDetail) {
|
|
2052
|
+
const text = (actionDetail || "").trim();
|
|
2053
|
+
if (!text) return false;
|
|
2054
|
+
let foundRm = false;
|
|
2055
|
+
const targets = [];
|
|
2056
|
+
for (const raw of splitCommandSegments(text)) {
|
|
2057
|
+
const s = raw.trim();
|
|
2058
|
+
if (!s) continue;
|
|
2059
|
+
let parts = s.split(/\s+/);
|
|
2060
|
+
if (parts[0]?.toLowerCase() === "sudo" || parts[0]?.toLowerCase() === "command") {
|
|
2061
|
+
parts = parts.slice(1);
|
|
2062
|
+
}
|
|
2063
|
+
if (!parts.length || parts[0].toLowerCase() !== "rm") continue;
|
|
2064
|
+
foundRm = true;
|
|
2065
|
+
for (const rawTok of parts.slice(1)) {
|
|
2066
|
+
const tok = rawTok.replace(/^['"]+|['"]+$/g, "");
|
|
2067
|
+
if (!tok || tok.startsWith("-")) continue;
|
|
2068
|
+
targets.push(tok);
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
if (!foundRm || targets.length === 0) return false;
|
|
2072
|
+
for (const target of targets) {
|
|
2073
|
+
let t = target.replace(/\\/g, "/");
|
|
2074
|
+
if (t.startsWith("/") || t.split("/").includes("..")) return false;
|
|
2075
|
+
while (t.startsWith("./")) t = t.slice(2);
|
|
2076
|
+
if (!t || [".", "*", "?"].includes(t)) return false;
|
|
2077
|
+
if (t.includes("*") || t.includes("?")) {
|
|
2078
|
+
if (!BUILD_ARTIFACT_GLOB_RE.test(t)) return false;
|
|
2079
|
+
continue;
|
|
2080
|
+
}
|
|
2081
|
+
const first = t.split("/")[0].toLowerCase();
|
|
2082
|
+
if (!BUILD_ARTIFACT_NAMES.has(first)) return false;
|
|
2083
|
+
}
|
|
2084
|
+
return true;
|
|
2085
|
+
}
|
|
2018
2086
|
function intentCategories(text) {
|
|
2019
2087
|
const t = (text || "").toLowerCase();
|
|
2020
2088
|
const out = /* @__PURE__ */ new Set();
|
|
2021
2089
|
for (const [cat, kws] of Object.entries(INTENT_CATEGORIES)) {
|
|
2022
|
-
|
|
2090
|
+
for (const kw of kws) {
|
|
2091
|
+
const needle = String(kw).toLowerCase();
|
|
2092
|
+
let start = 0;
|
|
2093
|
+
while (true) {
|
|
2094
|
+
const idx = t.indexOf(needle, start);
|
|
2095
|
+
if (idx < 0) break;
|
|
2096
|
+
if (!intentKeywordNegated(t, idx)) {
|
|
2097
|
+
out.add(cat);
|
|
2098
|
+
break;
|
|
2099
|
+
}
|
|
2100
|
+
start = idx + needle.length;
|
|
2101
|
+
}
|
|
2102
|
+
if (out.has(cat)) break;
|
|
2103
|
+
}
|
|
2023
2104
|
}
|
|
2024
2105
|
return out;
|
|
2025
2106
|
}
|
|
@@ -2122,6 +2203,52 @@ function checkIntentConsistency(input, agentExt) {
|
|
|
2122
2203
|
}
|
|
2123
2204
|
const actionCat = actionCategory(actionType, aNext.actionDetail, input.osType, extraWriteTools);
|
|
2124
2205
|
const reasonKey = intentMatrixViolation(intents, actionCat);
|
|
2206
|
+
const isReferencePrompt = REFERENCE_PRIOR_RE.test((promptSession || "").trim().toLowerCase());
|
|
2207
|
+
if (reasonKey === "read->overwrite" && !EXPLICIT_READONLY_RE.test(intentText) && !isReferencePrompt) {
|
|
2208
|
+
console.debug(
|
|
2209
|
+
`[intent] \u8BFB\u610F\u56FE + \u8986\u76D6\u52A8\u4F5C\uFF0C\u7F3A\u5C11\u660E\u786E\u53EA\u8BFB\u7EA6\u675F\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
|
|
2210
|
+
);
|
|
2211
|
+
return {
|
|
2212
|
+
allowed: true,
|
|
2213
|
+
reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
|
|
2214
|
+
riskLevel: "low",
|
|
2215
|
+
riskType: "",
|
|
2216
|
+
confidence: 50,
|
|
2217
|
+
source: "logic_rule",
|
|
2218
|
+
violatedLayers: [],
|
|
2219
|
+
l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u51FA\u73B0\u8BFB\u610F\u56FE\u8BCD\uFF0C\u4F46\u5F53\u524D\u52A8\u4F5C\u662F\u8986\u76D6\u5199\uFF0Cprompt \u6CA1\u6709\u660E\u786E\u201C\u53EA\u8BFB/\u4E0D\u8981\u4FEE\u6539\u201D\u7EA6\u675F\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
|
|
2220
|
+
};
|
|
2221
|
+
}
|
|
2222
|
+
if ((reasonKey === "read->delete" || reasonKey === "write->delete") && UPDATE_INTENT_RE.test(intentText) && !EXPLICIT_NO_DELETE_RE.test(intentText)) {
|
|
2223
|
+
console.debug(
|
|
2224
|
+
`[intent] \u66F4\u65B0\u7C7B\u610F\u56FE + \u5220\u9664\u52A8\u4F5C\uFF0C\u53EF\u80FD\u5305\u542B\u66FF\u6362\u6D41\u7A0B\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
|
|
2225
|
+
);
|
|
2226
|
+
return {
|
|
2227
|
+
allowed: true,
|
|
2228
|
+
reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
|
|
2229
|
+
riskLevel: "low",
|
|
2230
|
+
riskType: "",
|
|
2231
|
+
confidence: 50,
|
|
2232
|
+
source: "logic_rule",
|
|
2233
|
+
violatedLayers: [],
|
|
2234
|
+
l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u51FA\u73B0\u66F4\u65B0/\u4FEE\u6539\u7C7B\u610F\u56FE\uFF0C\u4F46\u5F53\u524D\u52A8\u4F5C\u662F\u5220\u9664\uFF0C\u53EF\u80FD\u662F\u5148\u5220\u65E7\u518D\u5199\u65B0\u7684\u66FF\u6362\u6D41\u7A0B\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
|
|
2235
|
+
};
|
|
2236
|
+
}
|
|
2237
|
+
if ((reasonKey === "read->delete" || reasonKey === "write->delete") && !isReferencePrompt && INTENT_AMBIGUITY_RE.test(intentText)) {
|
|
2238
|
+
console.debug(
|
|
2239
|
+
`[intent] \u610F\u56FE\u8BCD\u5B58\u5728\u6B67\u4E49\u4E0A\u4E0B\u6587\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
|
|
2240
|
+
);
|
|
2241
|
+
return {
|
|
2242
|
+
allowed: true,
|
|
2243
|
+
reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
|
|
2244
|
+
riskLevel: "low",
|
|
2245
|
+
riskType: "",
|
|
2246
|
+
confidence: 50,
|
|
2247
|
+
source: "logic_rule",
|
|
2248
|
+
violatedLayers: [],
|
|
2249
|
+
l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u610F\u56FE\u8BCD\u51FA\u73B0\u5728\u53EF\u80FD\u6539\u53D8\u542B\u4E49\u7684\u4E0A\u4E0B\u6587\uFF08\u5904\u7406/\u6761\u4EF6/\u793A\u4F8B/\u6309\u94AE/\u6307\u4EE3\u7B49\uFF09\u4E2D\uFF0C\u4E0D\u80FD\u4EC5\u51ED\u5173\u952E\u8BCD\u5224\u504F\u79BB\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2125
2252
|
if (reasonKey !== null) {
|
|
2126
2253
|
return {
|
|
2127
2254
|
allowed: false,
|
|
@@ -2638,7 +2765,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
|
|
|
2638
2765
|
violatedLayers: ["L2.1"]
|
|
2639
2766
|
};
|
|
2640
2767
|
}
|
|
2641
|
-
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, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, 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, SCRIPT_FILE_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, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, 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;
|
|
2768
|
+
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, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, 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, SCRIPT_FILE_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, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, NEGATION_WORDS, NEGATION_WINDOW, EXPLICIT_READONLY_RE, UPDATE_INTENT_RE, EXPLICIT_NO_DELETE_RE, INTENT_AMBIGUITY_RE, BUILD_ARTIFACT_NAMES, BUILD_ARTIFACT_GLOB_RE, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, 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;
|
|
2642
2769
|
var init_logic_rules = __esm({
|
|
2643
2770
|
"src/engine/logic-rules.ts"() {
|
|
2644
2771
|
"use strict";
|
|
@@ -2740,6 +2867,31 @@ var init_logic_rules = __esm({
|
|
|
2740
2867
|
(INTENT_MATRIX.delete_action_words || []).map((w) => String(w).toLowerCase())
|
|
2741
2868
|
);
|
|
2742
2869
|
ALL_INTENT_KEYWORDS = Object.values(INTENT_CATEGORIES).flat();
|
|
2870
|
+
NEGATION_WORDS = (INTENT_MATRIX.negation_words || []).map((w) => String(w).toLowerCase());
|
|
2871
|
+
NEGATION_WINDOW = 8;
|
|
2872
|
+
EXPLICIT_READONLY_RE = /(?:只读|仅读|只看|仅看|只查看|仅查看|只分析|仅分析|只做分析|只查询|仅查询|不要(?:修改|写入|写|改动|动)|禁止(?:修改|写入|写|改动)|不得(?:修改|写入|写|改动)|别(?:修改|写入|写|动)|read[- ]only|do not (?:modify|write|change)|don't (?:modify|write|change))/i;
|
|
2873
|
+
UPDATE_INTENT_RE = /(?:更新|修改|编辑|替换|覆盖|改成|改到|rename|replace|update|modify|edit)/i;
|
|
2874
|
+
EXPLICIT_NO_DELETE_RE = /(?:不要|禁止|不得|别|切勿)\s*(?:删除|删掉|删|移除|remove|delete|rm)/i;
|
|
2875
|
+
INTENT_AMBIGUITY_RE = /(?:处理|整理|优化|调整|清掉|如果|假如|若|或者|还是|看情况|根据|按.{0,6}要求|继续|之前|上次|刚才|顺便|示例|例如|比如|按钮|接口|函数|字段|变量|代码里|可能|建议|评估|考虑)/i;
|
|
2876
|
+
BUILD_ARTIFACT_NAMES = /* @__PURE__ */ new Set([
|
|
2877
|
+
"build",
|
|
2878
|
+
"dist",
|
|
2879
|
+
"target",
|
|
2880
|
+
"out",
|
|
2881
|
+
"tmp",
|
|
2882
|
+
"temp",
|
|
2883
|
+
"cache",
|
|
2884
|
+
".cache",
|
|
2885
|
+
"__pycache__",
|
|
2886
|
+
".pytest_cache",
|
|
2887
|
+
".mypy_cache",
|
|
2888
|
+
".tox",
|
|
2889
|
+
"node_modules",
|
|
2890
|
+
"coverage",
|
|
2891
|
+
".coverage",
|
|
2892
|
+
"htmlcov"
|
|
2893
|
+
]);
|
|
2894
|
+
BUILD_ARTIFACT_GLOB_RE = /^\*\.(?:pyc|pyo|class|o|obj|d|egg-info)$/i;
|
|
2743
2895
|
REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
|
|
2744
2896
|
REFERENCE_LOOKBACK = 3;
|
|
2745
2897
|
EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
|
|
@@ -3077,8 +3229,8 @@ function loadRuntimeConfig() {
|
|
|
3077
3229
|
}
|
|
3078
3230
|
try {
|
|
3079
3231
|
const st = statSync3(p);
|
|
3080
|
-
const
|
|
3081
|
-
if (runtimeConfigCache && runtimeConfigCache.key ===
|
|
3232
|
+
const cacheKey2 = `${p}|${st.mtimeMs}|${st.size}`;
|
|
3233
|
+
if (runtimeConfigCache && runtimeConfigCache.key === cacheKey2) {
|
|
3082
3234
|
return runtimeConfigCache.value;
|
|
3083
3235
|
}
|
|
3084
3236
|
const data = JSON.parse(readFileSync6(p, "utf-8"));
|
|
@@ -3103,7 +3255,7 @@ function loadRuntimeConfig() {
|
|
|
3103
3255
|
agent_rules: merged.agent_rules || {},
|
|
3104
3256
|
scenario_rules: merged.scenario_rules || {}
|
|
3105
3257
|
};
|
|
3106
|
-
runtimeConfigCache = { key:
|
|
3258
|
+
runtimeConfigCache = { key: cacheKey2, value: result };
|
|
3107
3259
|
return result;
|
|
3108
3260
|
} catch {
|
|
3109
3261
|
return emptyRuntimeConfig();
|
|
@@ -4423,6 +4575,7 @@ __export(config_exports, {
|
|
|
4423
4575
|
getAgentMossSetting: () => getAgentMossSetting,
|
|
4424
4576
|
getCacheOptions: () => getCacheOptions,
|
|
4425
4577
|
getCustomRules: () => getCustomRules,
|
|
4578
|
+
getDeployRole: () => getDeployRole,
|
|
4426
4579
|
getLLMConfig: () => getLLMConfig,
|
|
4427
4580
|
getLLMFailMode: () => getLLMFailMode,
|
|
4428
4581
|
getProviderHeaders: () => getProviderHeaders,
|
|
@@ -4605,6 +4758,10 @@ function getLLMFailMode() {
|
|
|
4605
4758
|
const val = (process.env.AGENT_MOSS_LLM_FAIL_MODE || "fail_open").toLowerCase();
|
|
4606
4759
|
return val === "fail_closed" ? "fail_closed" : "fail_open";
|
|
4607
4760
|
}
|
|
4761
|
+
function getDeployRole() {
|
|
4762
|
+
const val = String(process.env.AGENT_MOSS_DEPLOY_ROLE || "standalone").trim().toLowerCase();
|
|
4763
|
+
return val === "host" || val === "sandbox" ? val : "standalone";
|
|
4764
|
+
}
|
|
4608
4765
|
function detectProvider(baseUrl, providerHint = "") {
|
|
4609
4766
|
if (providerHint) {
|
|
4610
4767
|
const hint = providerHint.toLowerCase();
|
|
@@ -4738,15 +4895,66 @@ var init_config = __esm({
|
|
|
4738
4895
|
}
|
|
4739
4896
|
});
|
|
4740
4897
|
|
|
4741
|
-
// src/
|
|
4742
|
-
import { readFileSync as readFileSync7,
|
|
4743
|
-
import {
|
|
4898
|
+
// src/infra/edition-scope.ts
|
|
4899
|
+
import { existsSync as existsSync8, readFileSync as readFileSync7, statSync as statSync4 } from "fs";
|
|
4900
|
+
import { dirname as dirname6, join as join8, resolve as resolve5 } from "path";
|
|
4744
4901
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
4902
|
+
function scopePath(moduleDir) {
|
|
4903
|
+
const root = getRulesRoot();
|
|
4904
|
+
if (root) return join8(root, "edition_scope.json");
|
|
4905
|
+
const prod = resolve5(moduleDir, "..", "edition_scope.json");
|
|
4906
|
+
if (existsSync8(prod)) return prod;
|
|
4907
|
+
const dev = resolve5(moduleDir, "../../..", "agent_moss", "edition_scope.json");
|
|
4908
|
+
if (existsSync8(dev)) return dev;
|
|
4909
|
+
return prod;
|
|
4910
|
+
}
|
|
4911
|
+
function loadScope(moduleDir) {
|
|
4912
|
+
const file = scopePath(moduleDir);
|
|
4913
|
+
try {
|
|
4914
|
+
const st = statSync4(file);
|
|
4915
|
+
const key = `${file}:${st.mtimeMs}:${st.size}`;
|
|
4916
|
+
if (key === cacheKey) return cacheData;
|
|
4917
|
+
const parsed = JSON.parse(readFileSync7(file, "utf-8"));
|
|
4918
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
4919
|
+
throw new Error("\u6839\u8282\u70B9\u4E0D\u662F\u5BF9\u8C61");
|
|
4920
|
+
}
|
|
4921
|
+
cacheKey = key;
|
|
4922
|
+
cacheData = parsed;
|
|
4923
|
+
return cacheData;
|
|
4924
|
+
} catch {
|
|
4925
|
+
cacheKey = "";
|
|
4926
|
+
cacheData = null;
|
|
4927
|
+
return null;
|
|
4928
|
+
}
|
|
4929
|
+
}
|
|
4930
|
+
function isAllowed(kind, id, moduleDir = MODULE_DIR) {
|
|
4931
|
+
const scope = loadScope(moduleDir);
|
|
4932
|
+
if (!scope) return true;
|
|
4933
|
+
const allowed = scope[kind];
|
|
4934
|
+
if (!Array.isArray(allowed)) return true;
|
|
4935
|
+
return allowed.includes(id);
|
|
4936
|
+
}
|
|
4937
|
+
var MODULE_DIR, cacheKey, cacheData;
|
|
4938
|
+
var init_edition_scope = __esm({
|
|
4939
|
+
"src/infra/edition-scope.ts"() {
|
|
4940
|
+
"use strict";
|
|
4941
|
+
init_esm_shims();
|
|
4942
|
+
init_paths();
|
|
4943
|
+
MODULE_DIR = dirname6(fileURLToPath6(import.meta.url));
|
|
4944
|
+
cacheKey = "";
|
|
4945
|
+
cacheData = null;
|
|
4946
|
+
}
|
|
4947
|
+
});
|
|
4948
|
+
|
|
4949
|
+
// src/agents/index.ts
|
|
4950
|
+
import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
|
|
4951
|
+
import { resolve as resolve6, dirname as dirname7, join as join9 } from "path";
|
|
4952
|
+
import { fileURLToPath as fileURLToPath7 } from "url";
|
|
4745
4953
|
function resolveAgentsDir() {
|
|
4746
4954
|
const root = getRulesRoot();
|
|
4747
|
-
if (root) return
|
|
4748
|
-
if (
|
|
4749
|
-
if (
|
|
4955
|
+
if (root) return join9(root, "agents");
|
|
4956
|
+
if (existsSync9(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
|
|
4957
|
+
if (existsSync9(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
|
|
4750
4958
|
return AGENTS_DIR_PROD;
|
|
4751
4959
|
}
|
|
4752
4960
|
function getAgentExtensions(agentId) {
|
|
@@ -4755,6 +4963,7 @@ function getAgentExtensions(agentId) {
|
|
|
4755
4963
|
console.warn(`[AgentMoss agents] \u975E\u6CD5 agent_id \u5DF2\u5FFD\u7565\uFF08\u542B\u8DEF\u5F84\u5B57\u7B26\u6216\u8D85\u957F\uFF09: ${agentId.slice(0, 120)}`);
|
|
4756
4964
|
return null;
|
|
4757
4965
|
}
|
|
4966
|
+
if (!isAllowed("agents", agentId)) return null;
|
|
4758
4967
|
if (cache.size >= CACHE_MAX) cache.clear();
|
|
4759
4968
|
const fp = getRuleSourceFingerprint();
|
|
4760
4969
|
const cached2 = cache.get(agentId);
|
|
@@ -4768,13 +4977,13 @@ function getAgentExtensions(agentId) {
|
|
|
4768
4977
|
}
|
|
4769
4978
|
if (ext === null) {
|
|
4770
4979
|
const agentsDir = resolveAgentsDir();
|
|
4771
|
-
const rulesFile =
|
|
4772
|
-
if (!
|
|
4980
|
+
const rulesFile = resolve6(agentsDir, agentId, "rules.json");
|
|
4981
|
+
if (!existsSync9(rulesFile)) {
|
|
4773
4982
|
cache.set(agentId, { fp, ext: null });
|
|
4774
4983
|
return null;
|
|
4775
4984
|
}
|
|
4776
4985
|
try {
|
|
4777
|
-
const raw =
|
|
4986
|
+
const raw = readFileSync8(rulesFile, "utf-8");
|
|
4778
4987
|
ext = JSON.parse(raw);
|
|
4779
4988
|
if (!ext.agent_id) {
|
|
4780
4989
|
console.warn(`[AgentMoss agents] rules.json \u7F3A\u5C11 agent_id \u5B57\u6BB5: ${rulesFile}`);
|
|
@@ -4815,25 +5024,26 @@ var init_agents = __esm({
|
|
|
4815
5024
|
"use strict";
|
|
4816
5025
|
init_esm_shims();
|
|
4817
5026
|
init_paths();
|
|
5027
|
+
init_edition_scope();
|
|
4818
5028
|
init_runtime_config();
|
|
4819
|
-
__filename4 =
|
|
4820
|
-
__dirname5 =
|
|
4821
|
-
AGENTS_DIR_PROD =
|
|
4822
|
-
AGENTS_DIR_DEV_FALLBACK =
|
|
5029
|
+
__filename4 = fileURLToPath7(import.meta.url);
|
|
5030
|
+
__dirname5 = dirname7(__filename4);
|
|
5031
|
+
AGENTS_DIR_PROD = resolve6(__dirname5, "agents");
|
|
5032
|
+
AGENTS_DIR_DEV_FALLBACK = resolve6(__dirname5, "../../../agent_moss/agents");
|
|
4823
5033
|
cache = /* @__PURE__ */ new Map();
|
|
4824
5034
|
CACHE_MAX = 512;
|
|
4825
5035
|
}
|
|
4826
5036
|
});
|
|
4827
5037
|
|
|
4828
5038
|
// src/scenarios/index.ts
|
|
4829
|
-
import { readFileSync as
|
|
4830
|
-
import { resolve as
|
|
4831
|
-
import { fileURLToPath as
|
|
5039
|
+
import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
|
|
5040
|
+
import { resolve as resolve7, dirname as dirname8, join as join10 } from "path";
|
|
5041
|
+
import { fileURLToPath as fileURLToPath8 } from "url";
|
|
4832
5042
|
function resolveScenariosDir() {
|
|
4833
5043
|
const root = getRulesRoot();
|
|
4834
|
-
if (root) return
|
|
4835
|
-
if (
|
|
4836
|
-
if (
|
|
5044
|
+
if (root) return join10(root, "scenarios");
|
|
5045
|
+
if (existsSync10(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
|
|
5046
|
+
if (existsSync10(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
|
|
4837
5047
|
return SCENARIOS_DIR_PROD;
|
|
4838
5048
|
}
|
|
4839
5049
|
function getScenarioExtensions(scenarioId) {
|
|
@@ -4842,6 +5052,7 @@ function getScenarioExtensions(scenarioId) {
|
|
|
4842
5052
|
console.warn(`[AgentMoss scenarios] \u975E\u6CD5 scenario_id \u5DF2\u5FFD\u7565\uFF08\u542B\u8DEF\u5F84\u5B57\u7B26\u6216\u8D85\u957F\uFF09: ${scenarioId.slice(0, 120)}`);
|
|
4843
5053
|
return null;
|
|
4844
5054
|
}
|
|
5055
|
+
if (!isAllowed("scenarios", scenarioId)) return null;
|
|
4845
5056
|
if (cache2.size >= CACHE_MAX2) cache2.clear();
|
|
4846
5057
|
const fp = getRuleSourceFingerprint();
|
|
4847
5058
|
const cached2 = cache2.get(scenarioId);
|
|
@@ -4861,19 +5072,19 @@ function getScenarioExtensions(scenarioId) {
|
|
|
4861
5072
|
}
|
|
4862
5073
|
}
|
|
4863
5074
|
if (ext === null) {
|
|
4864
|
-
const builtinFile =
|
|
5075
|
+
const builtinFile = resolve7(resolveScenariosDir(), scenarioId, "rules.json");
|
|
4865
5076
|
const rulesFile = overrideHit ?? builtinFile;
|
|
4866
5077
|
if (overrideHit) {
|
|
4867
5078
|
console.warn(
|
|
4868
5079
|
`[AgentMoss] \u26A0\uFE0F \u573A\u666F ${scenarioId} \u89C4\u5219\u88AB\u8986\u76D6\u76EE\u5F55\u8986\u76D6: ${overrideHit}\uFF08\u5185\u7F6E\u9ED8\u8BA4 ${builtinFile} \u88AB\u5FFD\u7565\uFF09\u3002\u8BE5\u6587\u4EF6\u7531\u90E8\u7F72\u4FA7\u81EA\u884C\u7EF4\u62A4\uFF0C\u5185\u7F6E\u573A\u666F\u89C4\u5219\u66F4\u65B0\u4E0D\u4F1A\u53CD\u6620\u5230\u5B83\u4E0A\u9762\u3002`
|
|
4869
5080
|
);
|
|
4870
5081
|
}
|
|
4871
|
-
if (!
|
|
5082
|
+
if (!existsSync10(rulesFile)) {
|
|
4872
5083
|
cache2.set(scenarioId, { fp, ext: null });
|
|
4873
5084
|
return null;
|
|
4874
5085
|
}
|
|
4875
5086
|
try {
|
|
4876
|
-
const raw =
|
|
5087
|
+
const raw = readFileSync9(rulesFile, "utf-8");
|
|
4877
5088
|
const data = JSON.parse(raw);
|
|
4878
5089
|
const id = data.scenario_id || data.agent_id || "";
|
|
4879
5090
|
if (!id) {
|
|
@@ -4919,13 +5130,14 @@ var init_scenarios = __esm({
|
|
|
4919
5130
|
"use strict";
|
|
4920
5131
|
init_esm_shims();
|
|
4921
5132
|
init_paths();
|
|
5133
|
+
init_edition_scope();
|
|
4922
5134
|
init_agents();
|
|
4923
5135
|
init_runtime_config();
|
|
4924
5136
|
init_rules_loader();
|
|
4925
|
-
__filename5 =
|
|
4926
|
-
__dirname6 =
|
|
4927
|
-
SCENARIOS_DIR_PROD =
|
|
4928
|
-
SCENARIOS_DIR_DEV_FALLBACK =
|
|
5137
|
+
__filename5 = fileURLToPath8(import.meta.url);
|
|
5138
|
+
__dirname6 = dirname8(__filename5);
|
|
5139
|
+
SCENARIOS_DIR_PROD = resolve7(__dirname6, "scenarios");
|
|
5140
|
+
SCENARIOS_DIR_DEV_FALLBACK = resolve7(__dirname6, "../../../agent_moss/scenarios");
|
|
4929
5141
|
cache2 = /* @__PURE__ */ new Map();
|
|
4930
5142
|
CACHE_MAX2 = 512;
|
|
4931
5143
|
}
|
|
@@ -4992,6 +5204,21 @@ function detectLanguage(path9, content) {
|
|
|
4992
5204
|
}
|
|
4993
5205
|
return "other";
|
|
4994
5206
|
}
|
|
5207
|
+
function isInstructionTarget(path9) {
|
|
5208
|
+
const p = (path9 || "").replace(/\\/g, "/").toLowerCase();
|
|
5209
|
+
if (!p) return false;
|
|
5210
|
+
const base = p.split("/").pop() || "";
|
|
5211
|
+
if (["agents.md", "claude.md", "system.md", "prompt.md", "instructions.md", ".cursorrules"].includes(base)) {
|
|
5212
|
+
return true;
|
|
5213
|
+
}
|
|
5214
|
+
if (/(?:^|[-_.])(?:prompt|instruction|system)(?:[-_.]|$)/.test(base)) return true;
|
|
5215
|
+
return INSTRUCTION_TARGET_RE.test(p);
|
|
5216
|
+
}
|
|
5217
|
+
function isDataDocument(actionType, actionDetailRaw) {
|
|
5218
|
+
const payload = extractWritePayload(actionType, actionDetailRaw);
|
|
5219
|
+
if (payload === null) return false;
|
|
5220
|
+
return detectLanguage(payload.path, payload.content) === "data" && !isInstructionTarget(payload.path);
|
|
5221
|
+
}
|
|
4995
5222
|
function stripShellComments(text) {
|
|
4996
5223
|
const out = [];
|
|
4997
5224
|
let heredocEnd = null;
|
|
@@ -5154,7 +5381,7 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
|
|
|
5154
5381
|
}
|
|
5155
5382
|
return snippets;
|
|
5156
5383
|
}
|
|
5157
|
-
var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE, HEREDOC_START_RE;
|
|
5384
|
+
var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE, INSTRUCTION_TARGET_RE, HEREDOC_START_RE;
|
|
5158
5385
|
var init_written_content_analyzer = __esm({
|
|
5159
5386
|
"src/engine/written-content-analyzer.ts"() {
|
|
5160
5387
|
"use strict";
|
|
@@ -5177,7 +5404,12 @@ var init_written_content_analyzer = __esm({
|
|
|
5177
5404
|
"file_edit",
|
|
5178
5405
|
"editfile",
|
|
5179
5406
|
"searchreplace",
|
|
5180
|
-
"search_replace"
|
|
5407
|
+
"search_replace",
|
|
5408
|
+
// 通用 workspace 工具名(ClawPartner/QwenPaw 等宿主常用)
|
|
5409
|
+
"workspace_write_file",
|
|
5410
|
+
"workspace_edit_file",
|
|
5411
|
+
"workspace_writefile",
|
|
5412
|
+
"workspace_editfile"
|
|
5181
5413
|
]);
|
|
5182
5414
|
WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
|
|
5183
5415
|
APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
|
|
@@ -5186,6 +5418,7 @@ var init_written_content_analyzer = __esm({
|
|
|
5186
5418
|
INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
|
|
5187
5419
|
QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
|
|
5188
5420
|
PY_DANGEROUS_CALL_RE = /(?:os\.(?:system|popen|remove|unlink|rmdir|chmod|chown|kill|spawn\w*)|subprocess\.\w+|pty\.\w+|ctypes\.\w+|eval|exec|compile|__import__|shutil\.(?:rmtree|move|copy\w*))\s*\(/g;
|
|
5421
|
+
INSTRUCTION_TARGET_RE = /(?:^|[/\\])(?:prompts?|instructions?|skills?|memories|memory|config|policies|policy|\.claude|\.cursor)(?:[/\\]|$)|(?:^|[/\\])(?:AGENTS?|CLAUDE|SYSTEM|PROMPT|INSTRUCTIONS?)(?:\.[^/\\]+)?$|(?:^|[/\\])\.cursorrules$/i;
|
|
5189
5422
|
HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
|
|
5190
5423
|
}
|
|
5191
5424
|
});
|
|
@@ -5429,6 +5662,23 @@ function runHeuristicCheck(input) {
|
|
|
5429
5662
|
deobfuscated
|
|
5430
5663
|
);
|
|
5431
5664
|
}
|
|
5665
|
+
const extraScanDetail = stripSearchPatternLiterals(scanDetail);
|
|
5666
|
+
const extraScanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => {
|
|
5667
|
+
const stripped = stripSearchPatternLiterals(sn);
|
|
5668
|
+
return [`${input.aNext.actionType}: ${stripped}`, stripped];
|
|
5669
|
+
}) : String(input.osType || "").toLowerCase() === "windows" ? [
|
|
5670
|
+
`${input.aNext.actionType}: ${extraScanDetail}`,
|
|
5671
|
+
extraScanDetail,
|
|
5672
|
+
`${input.aNext.actionType}: ${extraScanDetail.replace(/\//g, "\\")}`,
|
|
5673
|
+
extraScanDetail.replace(/\//g, "\\")
|
|
5674
|
+
] : [`${input.aNext.actionType}: ${extraScanDetail}`, extraScanDetail];
|
|
5675
|
+
const extraDeobfuscated = normalizeShellObfuscation(extraScanDetail);
|
|
5676
|
+
if (extraDeobfuscated !== extraScanDetail) {
|
|
5677
|
+
extraScanCommands.push(
|
|
5678
|
+
`${input.aNext.actionType}: ${extraDeobfuscated}`,
|
|
5679
|
+
extraDeobfuscated
|
|
5680
|
+
);
|
|
5681
|
+
}
|
|
5432
5682
|
let topRiskType = "";
|
|
5433
5683
|
const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
|
|
5434
5684
|
const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
|
|
@@ -5453,7 +5703,7 @@ function runHeuristicCheck(input) {
|
|
|
5453
5703
|
for (const rule of agentExt.extra_command_patterns) {
|
|
5454
5704
|
try {
|
|
5455
5705
|
const re = new RegExp(rule.pattern, "i");
|
|
5456
|
-
if (
|
|
5706
|
+
if (extraScanCommands.some((c) => re.test(c))) {
|
|
5457
5707
|
matched.push(`agent \u4E13\u5C5E\u89C4\u5219: ${rule.reason}`);
|
|
5458
5708
|
if (severityRank(rule.risk_level) > severityRank(highestSeverity)) {
|
|
5459
5709
|
highestSeverity = rule.risk_level;
|
|
@@ -5464,7 +5714,7 @@ function runHeuristicCheck(input) {
|
|
|
5464
5714
|
}
|
|
5465
5715
|
}
|
|
5466
5716
|
}
|
|
5467
|
-
const injectionText = isSearchActionType(input.aNext.actionType) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
|
|
5717
|
+
const injectionText = isSearchActionType(input.aNext.actionType) || handledWrite && isDataDocument(input.aNext.actionType, input.aNext.actionDetail) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
|
|
5468
5718
|
let pythonWalkOnerrorOnly = false;
|
|
5469
5719
|
if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
|
|
5470
5720
|
pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
|
|
@@ -5715,16 +5965,83 @@ function splitCommandSegments2(actionDetail) {
|
|
|
5715
5965
|
if (start < actionDetail.length) segments.push(actionDetail.slice(start));
|
|
5716
5966
|
return segments;
|
|
5717
5967
|
}
|
|
5968
|
+
function shellTokens(seg) {
|
|
5969
|
+
const tokens = [];
|
|
5970
|
+
let cur = "";
|
|
5971
|
+
let quote = "";
|
|
5972
|
+
for (let i = 0; i < seg.length; i++) {
|
|
5973
|
+
const ch = seg[i];
|
|
5974
|
+
if (quote) {
|
|
5975
|
+
if (ch === quote) quote = "";
|
|
5976
|
+
else cur += ch;
|
|
5977
|
+
continue;
|
|
5978
|
+
}
|
|
5979
|
+
if (ch === '"' || ch === "'") {
|
|
5980
|
+
quote = ch;
|
|
5981
|
+
continue;
|
|
5982
|
+
}
|
|
5983
|
+
if (/\s/.test(ch)) {
|
|
5984
|
+
if (cur) {
|
|
5985
|
+
tokens.push(cur);
|
|
5986
|
+
cur = "";
|
|
5987
|
+
}
|
|
5988
|
+
continue;
|
|
5989
|
+
}
|
|
5990
|
+
cur += ch;
|
|
5991
|
+
}
|
|
5992
|
+
if (quote) return null;
|
|
5993
|
+
if (cur) tokens.push(cur);
|
|
5994
|
+
return tokens;
|
|
5995
|
+
}
|
|
5996
|
+
function stripSearchPatternArgument(seg) {
|
|
5997
|
+
if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) return seg;
|
|
5998
|
+
const tokens = shellTokens(seg);
|
|
5999
|
+
if (!tokens || tokens.length === 0) return seg;
|
|
6000
|
+
let idx = 0;
|
|
6001
|
+
while (idx < tokens.length && COMMAND_PREFIX_WORDS.has(tokens[idx])) idx++;
|
|
6002
|
+
if (idx >= tokens.length || !TEXT_SEARCH_COMMANDS.has(tokens[idx])) return seg;
|
|
6003
|
+
let patternIdx = null;
|
|
6004
|
+
let i = idx + 1;
|
|
6005
|
+
while (i < tokens.length) {
|
|
6006
|
+
const token = tokens[i];
|
|
6007
|
+
if (token === "--") {
|
|
6008
|
+
patternIdx = i + 1 < tokens.length ? i + 1 : null;
|
|
6009
|
+
break;
|
|
6010
|
+
}
|
|
6011
|
+
if (token === "-e" || token === "--regexp") {
|
|
6012
|
+
patternIdx = i + 1 < tokens.length ? i + 1 : null;
|
|
6013
|
+
break;
|
|
6014
|
+
}
|
|
6015
|
+
if (token.startsWith("--regexp=")) {
|
|
6016
|
+
patternIdx = i;
|
|
6017
|
+
break;
|
|
6018
|
+
}
|
|
6019
|
+
if (token === "-f" || token === "--file" || token.startsWith("--file=")) break;
|
|
6020
|
+
if (token.startsWith("-") && token !== "-") {
|
|
6021
|
+
i += SEARCH_OPTION_WITH_ARG.has(token) ? 2 : 1;
|
|
6022
|
+
continue;
|
|
6023
|
+
}
|
|
6024
|
+
patternIdx = i;
|
|
6025
|
+
break;
|
|
6026
|
+
}
|
|
6027
|
+
if (patternIdx === null || patternIdx >= tokens.length) return seg;
|
|
6028
|
+
tokens.splice(patternIdx, 1);
|
|
6029
|
+
return tokens.map((t) => /\s/.test(t) ? `'${t.replaceAll("'", "'\\''")}'` : t).join(" ");
|
|
6030
|
+
}
|
|
5718
6031
|
function stripSearchPatternLiterals(actionDetail) {
|
|
5719
6032
|
const parts = [];
|
|
5720
6033
|
for (const seg of splitCommandSegments2(actionDetail)) {
|
|
6034
|
+
if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) {
|
|
6035
|
+
parts.push(seg);
|
|
6036
|
+
continue;
|
|
6037
|
+
}
|
|
5721
6038
|
const low = seg.trim().toLowerCase();
|
|
5722
6039
|
const words = low.length ? low.split(/\s+/) : [];
|
|
5723
6040
|
let idx = 0;
|
|
5724
6041
|
while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
|
|
5725
6042
|
const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
|
|
5726
6043
|
if (isSearch && !low.includes("--pre")) {
|
|
5727
|
-
parts.push(seg
|
|
6044
|
+
parts.push(stripSearchPatternArgument(seg));
|
|
5728
6045
|
} else {
|
|
5729
6046
|
parts.push(seg);
|
|
5730
6047
|
}
|
|
@@ -6049,7 +6366,7 @@ function checkDangerousPatterns(actionType, actionDetail) {
|
|
|
6049
6366
|
) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
|
|
6050
6367
|
const wildcardDeleteRe = /(?:\brm\b|\b(r?mdir|del|delete|remove|rmdir|unlink)\b|\b删除\b|\b移除\b)[\s\S]{0,40}?[*?]|[*?][\s\S]{0,40}?\b(?:rm|del|delete|remove|rmdir|unlink)\b|rm\s+-[a-zA-Z]*[rf][a-zA-Z]*\s+\S*[*?]/i;
|
|
6051
6368
|
const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
|
|
6052
|
-
if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
|
|
6369
|
+
if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
|
|
6053
6370
|
return {
|
|
6054
6371
|
allowed: false,
|
|
6055
6372
|
reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
|
|
@@ -6191,7 +6508,7 @@ function checkLateralMovement(actionDetail) {
|
|
|
6191
6508
|
}
|
|
6192
6509
|
return null;
|
|
6193
6510
|
}
|
|
6194
|
-
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
6511
|
+
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SEARCH_OPTION_WITH_ARG, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
6195
6512
|
var init_heuristic = __esm({
|
|
6196
6513
|
"src/engine/heuristic.ts"() {
|
|
6197
6514
|
"use strict";
|
|
@@ -6240,6 +6557,28 @@ var init_heuristic = __esm({
|
|
|
6240
6557
|
COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
|
|
6241
6558
|
TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
|
|
6242
6559
|
COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
|
|
6560
|
+
SEARCH_OPTION_WITH_ARG = /* @__PURE__ */ new Set([
|
|
6561
|
+
"-m",
|
|
6562
|
+
"--max-count",
|
|
6563
|
+
"-A",
|
|
6564
|
+
"--after-context",
|
|
6565
|
+
"-B",
|
|
6566
|
+
"--before-context",
|
|
6567
|
+
"-C",
|
|
6568
|
+
"--context",
|
|
6569
|
+
"-d",
|
|
6570
|
+
"--directories",
|
|
6571
|
+
"-D",
|
|
6572
|
+
"--devices",
|
|
6573
|
+
"--include",
|
|
6574
|
+
"--exclude",
|
|
6575
|
+
"--exclude-dir",
|
|
6576
|
+
"--glob",
|
|
6577
|
+
"--iglob",
|
|
6578
|
+
"--type",
|
|
6579
|
+
"--type-add",
|
|
6580
|
+
"--type-not"
|
|
6581
|
+
]);
|
|
6243
6582
|
SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
|
|
6244
6583
|
SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
|
|
6245
6584
|
SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
|
|
@@ -6249,9 +6588,9 @@ var init_heuristic = __esm({
|
|
|
6249
6588
|
});
|
|
6250
6589
|
|
|
6251
6590
|
// src/engine/template-loader.ts
|
|
6252
|
-
import { readFileSync as
|
|
6253
|
-
import { resolve as
|
|
6254
|
-
import { fileURLToPath as
|
|
6591
|
+
import { readFileSync as readFileSync10, existsSync as existsSync11 } from "fs";
|
|
6592
|
+
import { resolve as resolve8, dirname as dirname9 } from "path";
|
|
6593
|
+
import { fileURLToPath as fileURLToPath9 } from "url";
|
|
6255
6594
|
function loadTemplates() {
|
|
6256
6595
|
if (cachedTemplates) return cachedTemplates;
|
|
6257
6596
|
cachedTemplates = {};
|
|
@@ -6262,10 +6601,10 @@ function loadTemplates() {
|
|
|
6262
6601
|
return cachedTemplates;
|
|
6263
6602
|
}
|
|
6264
6603
|
for (const file of TEMPLATE_FILES) {
|
|
6265
|
-
const filePath =
|
|
6266
|
-
if (
|
|
6604
|
+
const filePath = resolve8(dir, file);
|
|
6605
|
+
if (existsSync11(filePath)) {
|
|
6267
6606
|
const key = file.replace(".txt", "").replace("_template", "");
|
|
6268
|
-
cachedTemplates[key] =
|
|
6607
|
+
cachedTemplates[key] = readFileSync10(filePath, "utf-8");
|
|
6269
6608
|
}
|
|
6270
6609
|
}
|
|
6271
6610
|
console.log(`[AgentMoss] Loaded ${Object.keys(cachedTemplates).length} templates from ${dir}`);
|
|
@@ -6277,16 +6616,16 @@ var init_template_loader = __esm({
|
|
|
6277
6616
|
"use strict";
|
|
6278
6617
|
init_esm_shims();
|
|
6279
6618
|
init_asset_dir();
|
|
6280
|
-
__filename6 =
|
|
6281
|
-
__dirname7 =
|
|
6619
|
+
__filename6 = fileURLToPath9(import.meta.url);
|
|
6620
|
+
__dirname7 = dirname9(__filename6);
|
|
6282
6621
|
TEMPLATE_FILES = ["prompt1_template.txt", "prompt2_template.txt", "security_judge_template.txt"];
|
|
6283
6622
|
cachedTemplates = null;
|
|
6284
6623
|
}
|
|
6285
6624
|
});
|
|
6286
6625
|
|
|
6287
6626
|
// src/engine/script-analyzer.ts
|
|
6288
|
-
import { readFileSync as
|
|
6289
|
-
import { resolve as
|
|
6627
|
+
import { readFileSync as readFileSync11 } from "fs";
|
|
6628
|
+
import { resolve as resolve9, join as join11 } from "path";
|
|
6290
6629
|
function emptyResult() {
|
|
6291
6630
|
return { scriptPath: "", scriptContent: "", matchedKeywords: [], lineCount: 0, isSuspicious: false, error: "", riskLevel: "", riskReason: "" };
|
|
6292
6631
|
}
|
|
@@ -6339,8 +6678,8 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
|
|
|
6339
6678
|
}
|
|
6340
6679
|
function readScriptContent(scriptPath, maxLines = 500) {
|
|
6341
6680
|
try {
|
|
6342
|
-
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ?
|
|
6343
|
-
const raw =
|
|
6681
|
+
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join11(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve9(scriptPath);
|
|
6682
|
+
const raw = readFileSync11(expandedPath, "utf-8");
|
|
6344
6683
|
const lines = raw.split("\n").slice(0, maxLines);
|
|
6345
6684
|
return { content: lines.join("\n"), lineCount: lines.length, error: "" };
|
|
6346
6685
|
} catch (e) {
|
|
@@ -7618,7 +7957,7 @@ function evalIfCondition(cond, args) {
|
|
|
7618
7957
|
const op = m[2];
|
|
7619
7958
|
let left = m[1].trim();
|
|
7620
7959
|
let right = m[3].trim();
|
|
7621
|
-
const
|
|
7960
|
+
const resolve13 = (tok) => {
|
|
7622
7961
|
const rm = tok.match(/^\$(\d+)$/);
|
|
7623
7962
|
if (rm) {
|
|
7624
7963
|
const idx = parseInt(rm[1], 10);
|
|
@@ -7626,8 +7965,8 @@ function evalIfCondition(cond, args) {
|
|
|
7626
7965
|
}
|
|
7627
7966
|
return tok.startsWith("$") ? null : tok;
|
|
7628
7967
|
};
|
|
7629
|
-
const lv =
|
|
7630
|
-
const rv =
|
|
7968
|
+
const lv = resolve13(left);
|
|
7969
|
+
const rv = resolve13(right);
|
|
7631
7970
|
if (lv === null || rv === null) return null;
|
|
7632
7971
|
if (op === "=~") {
|
|
7633
7972
|
let re = rv;
|
|
@@ -7969,8 +8308,8 @@ var init_tracker = __esm({
|
|
|
7969
8308
|
});
|
|
7970
8309
|
|
|
7971
8310
|
// src/engine/script-content-analyzer.ts
|
|
7972
|
-
import { statSync as
|
|
7973
|
-
import { resolve as
|
|
8311
|
+
import { statSync as statSync6, existsSync as existsSync13 } from "fs";
|
|
8312
|
+
import { resolve as resolve11, join as join13, isAbsolute as isAbsolute4 } from "path";
|
|
7974
8313
|
import { homedir as homedir5 } from "os";
|
|
7975
8314
|
function emptyChain() {
|
|
7976
8315
|
return {
|
|
@@ -8082,8 +8421,8 @@ function extractInlineScriptPath(actionDetail) {
|
|
|
8082
8421
|
if (looksLikeScriptPath(tok)) {
|
|
8083
8422
|
try {
|
|
8084
8423
|
const resolved = resolvePath2(tok.replace(/^['"]|['"]$/g, ""));
|
|
8085
|
-
if (
|
|
8086
|
-
const stat =
|
|
8424
|
+
if (existsSync13(resolved)) {
|
|
8425
|
+
const stat = statSync6(resolved);
|
|
8087
8426
|
if (stat.isFile()) return resolved;
|
|
8088
8427
|
}
|
|
8089
8428
|
} catch {
|
|
@@ -8096,8 +8435,8 @@ function extractInlineScriptPath(actionDetail) {
|
|
|
8096
8435
|
const p = m[1];
|
|
8097
8436
|
try {
|
|
8098
8437
|
const resolved = resolvePath2(p);
|
|
8099
|
-
if (
|
|
8100
|
-
const stat =
|
|
8438
|
+
if (existsSync13(resolved)) {
|
|
8439
|
+
const stat = statSync6(resolved);
|
|
8101
8440
|
if (stat.isFile()) return resolved;
|
|
8102
8441
|
}
|
|
8103
8442
|
} catch {
|
|
@@ -8112,8 +8451,8 @@ function extractInlineScriptPath(actionDetail) {
|
|
|
8112
8451
|
let resolved;
|
|
8113
8452
|
try {
|
|
8114
8453
|
resolved = resolvePath2(p);
|
|
8115
|
-
if (
|
|
8116
|
-
const stat =
|
|
8454
|
+
if (existsSync13(resolved)) {
|
|
8455
|
+
const stat = statSync6(resolved);
|
|
8117
8456
|
if (stat.isFile()) return resolved;
|
|
8118
8457
|
}
|
|
8119
8458
|
} catch {
|
|
@@ -8153,9 +8492,9 @@ function shlexSplit(s) {
|
|
|
8153
8492
|
function resolvePath2(p) {
|
|
8154
8493
|
let expanded = p;
|
|
8155
8494
|
if (expanded.startsWith("~/") || expanded === "~") {
|
|
8156
|
-
expanded =
|
|
8495
|
+
expanded = join13(homedir5(), expanded.slice(1));
|
|
8157
8496
|
}
|
|
8158
|
-
return
|
|
8497
|
+
return resolve11(expanded);
|
|
8159
8498
|
}
|
|
8160
8499
|
function scanExtensionPatterns(ext, content) {
|
|
8161
8500
|
const pats = ext?.extra_command_patterns;
|
|
@@ -8242,7 +8581,7 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
|
8242
8581
|
isInline = true;
|
|
8243
8582
|
}
|
|
8244
8583
|
if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
|
|
8245
|
-
resolvedPath =
|
|
8584
|
+
resolvedPath = join13(input.cwd || process.cwd(), resolvedPath);
|
|
8246
8585
|
}
|
|
8247
8586
|
const l1Adapter = (content) => {
|
|
8248
8587
|
const extHit = scanExtensionPatterns(ext, content);
|
|
@@ -8843,17 +9182,17 @@ __export(token_stats_exports, {
|
|
|
8843
9182
|
resetTokenStats: () => resetTokenStats,
|
|
8844
9183
|
resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
|
|
8845
9184
|
});
|
|
8846
|
-
import { readFileSync as
|
|
9185
|
+
import { readFileSync as readFileSync14, writeFileSync as writeFileSync2, existsSync as existsSync14, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync7 } from "fs";
|
|
8847
9186
|
function getStatsPath() {
|
|
8848
9187
|
const envPath = process.env[ENV_STATS_PATH];
|
|
8849
9188
|
if (envPath) return envPath;
|
|
8850
9189
|
return getTokenStatsPath();
|
|
8851
9190
|
}
|
|
8852
9191
|
function loadAllRecords(statsPath) {
|
|
8853
|
-
if (!
|
|
9192
|
+
if (!existsSync14(statsPath)) return [];
|
|
8854
9193
|
let sig = "";
|
|
8855
9194
|
try {
|
|
8856
|
-
const st =
|
|
9195
|
+
const st = statSync7(statsPath);
|
|
8857
9196
|
sig = `${st.mtimeMs}:${st.size}`;
|
|
8858
9197
|
} catch {
|
|
8859
9198
|
return [];
|
|
@@ -8862,7 +9201,7 @@ function loadAllRecords(statsPath) {
|
|
|
8862
9201
|
return _recordsCache.records.slice();
|
|
8863
9202
|
}
|
|
8864
9203
|
try {
|
|
8865
|
-
const data = JSON.parse(
|
|
9204
|
+
const data = JSON.parse(readFileSync14(statsPath, "utf-8"));
|
|
8866
9205
|
let records;
|
|
8867
9206
|
if (Array.isArray(data)) records = data;
|
|
8868
9207
|
else if (data && Array.isArray(data.records)) records = data.records;
|
|
@@ -8876,7 +9215,7 @@ function loadAllRecords(statsPath) {
|
|
|
8876
9215
|
function saveRecords(statsPath, records) {
|
|
8877
9216
|
try {
|
|
8878
9217
|
const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
|
|
8879
|
-
if (dir && !
|
|
9218
|
+
if (dir && !existsSync14(dir)) mkdirSync3(dir, { recursive: true });
|
|
8880
9219
|
const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
|
|
8881
9220
|
try {
|
|
8882
9221
|
writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
|
|
@@ -8888,7 +9227,7 @@ function saveRecords(statsPath, records) {
|
|
|
8888
9227
|
}
|
|
8889
9228
|
}
|
|
8890
9229
|
try {
|
|
8891
|
-
const st =
|
|
9230
|
+
const st = statSync7(statsPath);
|
|
8892
9231
|
_recordsCache = {
|
|
8893
9232
|
path: statsPath,
|
|
8894
9233
|
sig: `${st.mtimeMs}:${st.size}`,
|
|
@@ -9025,7 +9364,7 @@ function getTokenTrend(days = 0, startDate, endDate) {
|
|
|
9025
9364
|
}
|
|
9026
9365
|
function resetTokenStats() {
|
|
9027
9366
|
const statsPath = getStatsPath();
|
|
9028
|
-
if (
|
|
9367
|
+
if (existsSync14(statsPath)) {
|
|
9029
9368
|
try {
|
|
9030
9369
|
unlinkSync2(statsPath);
|
|
9031
9370
|
} catch {
|
|
@@ -9125,8 +9464,8 @@ async function runLLMAnalysis(input, previous) {
|
|
|
9125
9464
|
}
|
|
9126
9465
|
const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
|
|
9127
9466
|
const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
|
|
9128
|
-
const
|
|
9129
|
-
const cached2 = llmCache.get(
|
|
9467
|
+
const cacheKey2 = `${input.aNext.actionType}:${createHash3("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
|
|
9468
|
+
const cached2 = llmCache.get(cacheKey2);
|
|
9130
9469
|
if (cached2) {
|
|
9131
9470
|
console.log("[AgentMoss] LLM cache hit");
|
|
9132
9471
|
return cached2;
|
|
@@ -9141,6 +9480,9 @@ async function runLLMAnalysis(input, previous) {
|
|
|
9141
9480
|
scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
|
|
9142
9481
|
}
|
|
9143
9482
|
const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
|
|
9483
|
+
const budgetMode = getAgentMossSetting("AGENT_MOSS_LLM_BUDGET_MODE", "hard").trim().toLowerCase() === "soft" ? "soft" : "hard";
|
|
9484
|
+
const budgetActive = maxPromptTokens > 0;
|
|
9485
|
+
const tokenLimit = budgetActive && budgetMode === "hard" ? Math.floor(maxPromptTokens * 100 / 115) : maxPromptTokens;
|
|
9144
9486
|
let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
|
|
9145
9487
|
let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
|
|
9146
9488
|
let prompt = "";
|
|
@@ -9157,13 +9499,14 @@ async function runLLMAnalysis(input, previous) {
|
|
|
9157
9499
|
historyMaxItems,
|
|
9158
9500
|
historyMaxChars
|
|
9159
9501
|
);
|
|
9160
|
-
if (
|
|
9502
|
+
if (!budgetActive || estimateTokens(prompt) <= tokenLimit) break;
|
|
9161
9503
|
historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
|
|
9162
9504
|
historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
|
|
9163
9505
|
}
|
|
9164
|
-
|
|
9506
|
+
let budgetCode = "";
|
|
9507
|
+
if (budgetActive && estimateTokens(prompt) > tokenLimit) {
|
|
9165
9508
|
const estimated = estimateTokens(prompt);
|
|
9166
|
-
const ratio = estimated /
|
|
9509
|
+
const ratio = tokenLimit > 0 ? estimated / tokenLimit : Number.POSITIVE_INFINITY;
|
|
9167
9510
|
const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
|
|
9168
9511
|
const truncated = truncateDetail(input.aNext.actionDetail, allowed);
|
|
9169
9512
|
prompt = buildPrompt(
|
|
@@ -9179,8 +9522,14 @@ async function runLLMAnalysis(input, previous) {
|
|
|
9179
9522
|
historyMaxChars
|
|
9180
9523
|
);
|
|
9181
9524
|
console.warn(
|
|
9182
|
-
`[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${
|
|
9525
|
+
`[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${tokenLimit}\uFF09\uFF0C\u5F53\u524D\u52A8\u4F5C\u8BE6\u60C5\u622A\u65AD\u81F3 ${truncated.length} \u5B57\u7B26`
|
|
9183
9526
|
);
|
|
9527
|
+
if (estimateTokens(prompt) > tokenLimit) {
|
|
9528
|
+
if (budgetMode === "hard") {
|
|
9529
|
+
throw new LLMPromptBudgetExceeded("l3_budget_unreachable");
|
|
9530
|
+
}
|
|
9531
|
+
budgetCode = "l3_budget_unreachable";
|
|
9532
|
+
}
|
|
9184
9533
|
}
|
|
9185
9534
|
logPrompt(prompt, input.aNext, previous.llmLogPath);
|
|
9186
9535
|
traceFull("l3.prompt", {
|
|
@@ -9193,6 +9542,7 @@ async function runLLMAnalysis(input, previous) {
|
|
|
9193
9542
|
prompt_chars: prompt.length
|
|
9194
9543
|
});
|
|
9195
9544
|
const result = await analyzeWithLLM(prompt, config);
|
|
9545
|
+
if (budgetCode) result.degraded = [...result.degraded || [], budgetCode];
|
|
9196
9546
|
traceSummary("l3.verdict", {
|
|
9197
9547
|
allowed: result.allowed,
|
|
9198
9548
|
risk_level: result.riskLevel,
|
|
@@ -9204,7 +9554,7 @@ async function runLLMAnalysis(input, previous) {
|
|
|
9204
9554
|
const firstKey = llmCache.keys().next().value;
|
|
9205
9555
|
if (firstKey) llmCache.delete(firstKey);
|
|
9206
9556
|
}
|
|
9207
|
-
llmCache.set(
|
|
9557
|
+
llmCache.set(cacheKey2, result);
|
|
9208
9558
|
return result;
|
|
9209
9559
|
}
|
|
9210
9560
|
function logPrompt(prompt, aNext, logPath) {
|
|
@@ -9266,11 +9616,14 @@ function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis,
|
|
|
9266
9616
|
const skillsText = formatSkillsForPrompt(matchedSkills);
|
|
9267
9617
|
const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
|
|
9268
9618
|
const promptHistoryText = formatPromptHistory(input.promptHistory);
|
|
9619
|
+
const historyAuthorization = /(因历史窗口上限省略|本段因长度上限已截断)/.test(promptHistoryText) ? `
|
|
9620
|
+
|
|
9621
|
+
${HISTORY_AUTHORIZATION}` : "";
|
|
9269
9622
|
const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
|
|
9270
9623
|
const hintsText = formatHints(previous);
|
|
9271
9624
|
const securityJudgeTemplate = templates["security_judge"];
|
|
9272
9625
|
if (securityJudgeTemplate) {
|
|
9273
|
-
return securityJudgeTemplate.replaceAll("{prompt_session}", input.promptSession || "\uFF08\u672A\u63D0\u4F9B\uFF09").replaceAll("{prompt_history_text}", promptHistoryText).replaceAll("{action_history}", historyStr).replaceAll("{action_type}", input.aNext.actionType).replaceAll("{action_detail}", input.aNext.actionDetail).replaceAll("{reason}", input.reason || "\u672A\u8BF4\u660E").replaceAll("{skills_text}", skillsText).replaceAll("{hints_text}", hintsText).replaceAll("{script_analysis_text}", scriptAnalysisText).replaceAll("{skip_l3_hints}", skipL3Hints).replaceAll("{path_context}", pathContext || "\uFF08\u672C\u547D\u4EE4\u65E0\u4E3B\u76EE\u5F55\u76F8\u5173\u8DEF\u5F84\u6BB5\uFF0C\u4E0D\u9002\u7528\uFF09").replaceAll("{{", "{").replaceAll("}}", "}");
|
|
9626
|
+
return securityJudgeTemplate.replaceAll("{prompt_session}", input.promptSession || "\uFF08\u672A\u63D0\u4F9B\uFF09").replaceAll("{prompt_history_text}", promptHistoryText).replaceAll("{history_authorization}", historyAuthorization).replaceAll("{action_history}", historyStr).replaceAll("{action_type}", input.aNext.actionType).replaceAll("{action_detail}", input.aNext.actionDetail).replaceAll("{reason}", input.reason || "\u672A\u8BF4\u660E").replaceAll("{skills_text}", skillsText).replaceAll("{hints_text}", hintsText).replaceAll("{script_analysis_text}", scriptAnalysisText).replaceAll("{skip_l3_hints}", skipL3Hints).replaceAll("{path_context}", pathContext || "\uFF08\u672C\u547D\u4EE4\u65E0\u4E3B\u76EE\u5F55\u76F8\u5173\u8DEF\u5F84\u6BB5\uFF0C\u4E0D\u9002\u7528\uFF09").replaceAll("{{", "{").replaceAll("}}", "}");
|
|
9274
9627
|
}
|
|
9275
9628
|
console.warn("[AgentMoss] security_judge template missing, using sparse fallback prompt");
|
|
9276
9629
|
return `## \u5F53\u524D\u64CD\u4F5C\u4E0A\u4E0B\u6587
|
|
@@ -9306,21 +9659,28 @@ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNu
|
|
|
9306
9659
|
}
|
|
9307
9660
|
const limit = Math.max(0, Math.floor(maxTurns));
|
|
9308
9661
|
const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
|
|
9662
|
+
let omitted = 0;
|
|
9309
9663
|
const lines = [];
|
|
9310
|
-
for (let i =
|
|
9664
|
+
for (let i = 0; i < promptHistory.length; i++) {
|
|
9311
9665
|
const turn = promptHistory[i];
|
|
9312
9666
|
const text = (typeof turn === "string" ? turn : turn?.text || "").trim();
|
|
9313
|
-
if (!text) continue;
|
|
9314
|
-
let line = ` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${text.slice(0, maxTextChars)}`;
|
|
9315
9667
|
const actions = typeof turn === "string" ? void 0 : turn?.actions;
|
|
9316
|
-
|
|
9317
|
-
|
|
9318
|
-
|
|
9319
|
-
|
|
9320
|
-
|
|
9668
|
+
const types = (actions || []).map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
|
|
9669
|
+
if (!text && types.length === 0) continue;
|
|
9670
|
+
if (i < firstTurnIndex) {
|
|
9671
|
+
omitted += 1;
|
|
9672
|
+
continue;
|
|
9673
|
+
}
|
|
9674
|
+
if (!text) {
|
|
9675
|
+
lines.push(` \u7B2C${i + 1}\u8F6E\u52A8\u4F5C: ${types.join(", ")}`);
|
|
9676
|
+
continue;
|
|
9321
9677
|
}
|
|
9322
|
-
|
|
9678
|
+
let shown = text.slice(0, maxTextChars);
|
|
9679
|
+
if (shown.length < text.length) shown += "\uFF08\u672C\u6BB5\u56E0\u957F\u5EA6\u4E0A\u9650\u5DF2\u622A\u65AD\uFF09";
|
|
9680
|
+
const suffix = types.length > 0 ? ` \u2192 \u52A8\u4F5C: ${types.join(", ")}` : "";
|
|
9681
|
+
lines.push(` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${shown}${suffix}`);
|
|
9323
9682
|
}
|
|
9683
|
+
if (omitted) lines.unshift(`\uFF08\u56E0\u5386\u53F2\u7A97\u53E3\u4E0A\u9650\u7701\u7565 ${omitted} \u8F6E\u66F4\u65E9\u5386\u53F2\u610F\u56FE\uFF09`);
|
|
9324
9684
|
return lines.length > 0 ? lines.join("\n") : "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
|
|
9325
9685
|
}
|
|
9326
9686
|
function formatHints(previous) {
|
|
@@ -9333,11 +9693,15 @@ function formatHints(previous) {
|
|
|
9333
9693
|
);
|
|
9334
9694
|
}
|
|
9335
9695
|
if (previous.logic) {
|
|
9336
|
-
|
|
9337
|
-
`\
|
|
9696
|
+
if (previous.logic.l3Hint) {
|
|
9697
|
+
hints.push(`\u2139\uFE0F ${previous.logic.l3Hint}`);
|
|
9698
|
+
} else {
|
|
9699
|
+
hints.push(
|
|
9700
|
+
`\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
|
|
9338
9701
|
\u7C7B\u578B: ${previous.logic.riskType}
|
|
9339
9702
|
\u539F\u56E0: ${previous.logic.reason}`
|
|
9340
|
-
|
|
9703
|
+
);
|
|
9704
|
+
}
|
|
9341
9705
|
}
|
|
9342
9706
|
return hints.length > 0 ? hints.join("\n\n") : "\u7279\u5F81\u5339\u914D\u68C0\u6D4B\u548C\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u5747\u672A\u53D1\u73B0\u98CE\u9669\u3002";
|
|
9343
9707
|
}
|
|
@@ -9538,7 +9902,7 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
9538
9902
|
)}`;
|
|
9539
9903
|
if (attempt < maxRetries) {
|
|
9540
9904
|
console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
|
|
9541
|
-
await new Promise((
|
|
9905
|
+
await new Promise((resolve13) => setTimeout(resolve13, retryCfg.retryInterval * 1e3));
|
|
9542
9906
|
} else {
|
|
9543
9907
|
clearTimeout(totalTimeoutTimer);
|
|
9544
9908
|
console.error(`[AgentMoss] LLM call failed after all retries: ${detail}`);
|
|
@@ -9549,7 +9913,7 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
9549
9913
|
clearTimeout(totalTimeoutTimer);
|
|
9550
9914
|
throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
|
|
9551
9915
|
}
|
|
9552
|
-
var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
|
|
9916
|
+
var LLMPromptBudgetExceeded, HISTORY_AUTHORIZATION, LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
|
|
9553
9917
|
var init_llm_analyzer = __esm({
|
|
9554
9918
|
"src/engine/llm-analyzer.ts"() {
|
|
9555
9919
|
"use strict";
|
|
@@ -9563,6 +9927,15 @@ var init_llm_analyzer = __esm({
|
|
|
9563
9927
|
init_trace_log();
|
|
9564
9928
|
init_metrics();
|
|
9565
9929
|
init_circuit_breaker();
|
|
9930
|
+
LLMPromptBudgetExceeded = class extends Error {
|
|
9931
|
+
code;
|
|
9932
|
+
constructor(code) {
|
|
9933
|
+
super(code);
|
|
9934
|
+
this.name = "LLMPromptBudgetExceeded";
|
|
9935
|
+
this.code = code;
|
|
9936
|
+
}
|
|
9937
|
+
};
|
|
9938
|
+
HISTORY_AUTHORIZATION = "\u88AB\u7701\u7565\u6216\u88AB\u622A\u65AD\u7684\u5386\u53F2\u4E0D\u80FD\u4F5C\u4E3A\u6388\u6743\u4F9D\u636E\u3002\n\u201C\u7EE7\u7EED\u201D\u53EA\u6307\u4EE3\u53EF\u89C1\u7684\u524D\u6587\uFF1B\u5982\u679C\u53EF\u89C1\u524D\u6587\u4E0D\u8DB3\u4EE5\u786E\u8BA4\u6307\u4EE3\u76EE\u6807\u6216\u6388\u6743\u8303\u56F4\uFF0C\u5E94\u5728 reason \u4E2D\u8BF4\u660E\u4F9D\u636E\u4E0D\u8DB3\uFF0C\u5E76\u6309\u6700\u5C0F\u6743\u9650\u539F\u5219\u5224\u65AD\u9700\u8981\u8BE5\u6388\u6743\u7684\u52A8\u4F5C\u3002\n\u5F53\u524D\u7528\u6237\u8BF7\u6C42\u4E2D\u660E\u786E\u5199\u51FA\u7684\u6388\u6743\u4ECD\u7136\u6709\u6548\uFF0C\u6309\u5176\u53EF\u89C1\u7684\u76EE\u6807\u548C\u9650\u5236\u5224\u65AD\u3002";
|
|
9566
9939
|
LLMCircuitOpenError = class extends Error {
|
|
9567
9940
|
constructor(message) {
|
|
9568
9941
|
super(message);
|
|
@@ -9575,8 +9948,8 @@ var init_llm_analyzer = __esm({
|
|
|
9575
9948
|
});
|
|
9576
9949
|
|
|
9577
9950
|
// src/brain/rule-store.ts
|
|
9578
|
-
import { existsSync as
|
|
9579
|
-
import { join as
|
|
9951
|
+
import { existsSync as existsSync15, readFileSync as readFileSync15, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
|
|
9952
|
+
import { join as join14 } from "path";
|
|
9580
9953
|
import { homedir as homedir6 } from "os";
|
|
9581
9954
|
function getRulesPath() {
|
|
9582
9955
|
const envPath = process.env[ENV_RULES_PATH];
|
|
@@ -9595,7 +9968,7 @@ var init_rule_store = __esm({
|
|
|
9595
9968
|
"src/brain/rule-store.ts"() {
|
|
9596
9969
|
"use strict";
|
|
9597
9970
|
init_esm_shims();
|
|
9598
|
-
DEFAULT_RULES_PATH =
|
|
9971
|
+
DEFAULT_RULES_PATH = join14(homedir6(), ".agentmoss", "brain", "rules.json");
|
|
9599
9972
|
ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
|
|
9600
9973
|
STATUS_DRAFT = "draft";
|
|
9601
9974
|
STATUS_APPROVED = "approved";
|
|
@@ -9612,11 +9985,11 @@ var init_rule_store = __esm({
|
|
|
9612
9985
|
this.data = this.load();
|
|
9613
9986
|
}
|
|
9614
9987
|
load() {
|
|
9615
|
-
if (!
|
|
9988
|
+
if (!existsSync15(this.path)) {
|
|
9616
9989
|
return { version: 1, rules: [], pattern_candidates: [] };
|
|
9617
9990
|
}
|
|
9618
9991
|
try {
|
|
9619
|
-
const raw = JSON.parse(
|
|
9992
|
+
const raw = JSON.parse(readFileSync15(this.path, "utf-8"));
|
|
9620
9993
|
return {
|
|
9621
9994
|
version: raw.version || 1,
|
|
9622
9995
|
rules: raw.rules || [],
|
|
@@ -10210,9 +10583,9 @@ var init_reviewer = __esm({
|
|
|
10210
10583
|
});
|
|
10211
10584
|
|
|
10212
10585
|
// src/brain/skill-manager.ts
|
|
10213
|
-
import { existsSync as
|
|
10586
|
+
import { existsSync as existsSync16, mkdirSync as mkdirSync5, readFileSync as readFileSync16, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
10214
10587
|
import { homedir as homedir7 } from "os";
|
|
10215
|
-
import { join as
|
|
10588
|
+
import { join as join15 } from "path";
|
|
10216
10589
|
import { randomUUID } from "crypto";
|
|
10217
10590
|
function getMetaPath(override) {
|
|
10218
10591
|
return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
|
|
@@ -10222,14 +10595,14 @@ var init_skill_manager = __esm({
|
|
|
10222
10595
|
"src/brain/skill-manager.ts"() {
|
|
10223
10596
|
"use strict";
|
|
10224
10597
|
init_esm_shims();
|
|
10225
|
-
DEFAULT_SKILL_META_PATH =
|
|
10598
|
+
DEFAULT_SKILL_META_PATH = join15(homedir7(), ".agentmoss", "brain", "skill_meta.json");
|
|
10226
10599
|
ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
|
|
10227
10600
|
BrainSkillManager = class {
|
|
10228
10601
|
constructor(skillsDir, metaPath) {
|
|
10229
10602
|
this.skillsDir = skillsDir;
|
|
10230
10603
|
this.metaPath = getMetaPath(metaPath);
|
|
10231
10604
|
try {
|
|
10232
|
-
mkdirSync5(
|
|
10605
|
+
mkdirSync5(join15(this.metaPath, ".."), { recursive: true });
|
|
10233
10606
|
} catch {
|
|
10234
10607
|
}
|
|
10235
10608
|
this.load();
|
|
@@ -10239,9 +10612,9 @@ var init_skill_manager = __esm({
|
|
|
10239
10612
|
skills = [];
|
|
10240
10613
|
metaPath;
|
|
10241
10614
|
load() {
|
|
10242
|
-
if (!
|
|
10615
|
+
if (!existsSync16(this.metaPath)) return;
|
|
10243
10616
|
try {
|
|
10244
|
-
const data = JSON.parse(
|
|
10617
|
+
const data = JSON.parse(readFileSync16(this.metaPath, "utf-8"));
|
|
10245
10618
|
this.skills = data.skills || [];
|
|
10246
10619
|
} catch {
|
|
10247
10620
|
this.skills = [];
|
|
@@ -10264,7 +10637,7 @@ var init_skill_manager = __esm({
|
|
|
10264
10637
|
let changed = false;
|
|
10265
10638
|
for (const sk of this.skills) {
|
|
10266
10639
|
if (sk.status !== "active") continue;
|
|
10267
|
-
if (!
|
|
10640
|
+
if (!existsSync16(join15(this.skillsDir, `${sk.name}.md`))) {
|
|
10268
10641
|
sk.status = "stale";
|
|
10269
10642
|
changed = true;
|
|
10270
10643
|
}
|
|
@@ -10275,9 +10648,9 @@ var init_skill_manager = __esm({
|
|
|
10275
10648
|
addSkill(skill) {
|
|
10276
10649
|
const id = skill.id || randomUUID();
|
|
10277
10650
|
const name = skill.name || `brain_${id.slice(0, 8)}`;
|
|
10278
|
-
if (!
|
|
10279
|
-
const mdPath =
|
|
10280
|
-
if (
|
|
10651
|
+
if (!existsSync16(this.skillsDir)) return "";
|
|
10652
|
+
const mdPath = join15(this.skillsDir, `${name}.md`);
|
|
10653
|
+
if (existsSync16(mdPath)) return "";
|
|
10281
10654
|
try {
|
|
10282
10655
|
writeFileSync4(mdPath, skill.content, "utf-8");
|
|
10283
10656
|
} catch {
|
|
@@ -10326,12 +10699,12 @@ var init_skill_manager = __esm({
|
|
|
10326
10699
|
const out = [];
|
|
10327
10700
|
for (const sk of this.skills) {
|
|
10328
10701
|
if (sk.origin_node !== "local" || sk.status !== "active") continue;
|
|
10329
|
-
const mdPath =
|
|
10330
|
-
if (!
|
|
10702
|
+
const mdPath = join15(this.skillsDir, `${sk.name}.md`);
|
|
10703
|
+
if (!existsSync16(mdPath)) continue;
|
|
10331
10704
|
out.push({
|
|
10332
10705
|
name: sk.name,
|
|
10333
10706
|
category: sk.category || "",
|
|
10334
|
-
content:
|
|
10707
|
+
content: readFileSync16(mdPath, "utf-8"),
|
|
10335
10708
|
keywords: sk.keywords || []
|
|
10336
10709
|
});
|
|
10337
10710
|
}
|
|
@@ -10418,8 +10791,8 @@ var init_curator = __esm({
|
|
|
10418
10791
|
});
|
|
10419
10792
|
|
|
10420
10793
|
// src/brain/contributor.ts
|
|
10421
|
-
import { dirname as
|
|
10422
|
-
import { fileURLToPath as
|
|
10794
|
+
import { dirname as dirname12 } from "path";
|
|
10795
|
+
import { fileURLToPath as fileURLToPath10 } from "url";
|
|
10423
10796
|
var __dirname8;
|
|
10424
10797
|
var init_contributor = __esm({
|
|
10425
10798
|
"src/brain/contributor.ts"() {
|
|
@@ -10428,7 +10801,7 @@ var init_contributor = __esm({
|
|
|
10428
10801
|
init_rule_store();
|
|
10429
10802
|
init_skill_manager();
|
|
10430
10803
|
init_asset_dir();
|
|
10431
|
-
__dirname8 =
|
|
10804
|
+
__dirname8 = dirname12(fileURLToPath10(import.meta.url));
|
|
10432
10805
|
}
|
|
10433
10806
|
});
|
|
10434
10807
|
|
|
@@ -10740,11 +11113,35 @@ function checkMCRules(graph) {
|
|
|
10740
11113
|
for (const rule of rules) {
|
|
10741
11114
|
if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
|
|
10742
11115
|
if (ruleViolates(rule, trace2, witnessMode)) {
|
|
11116
|
+
const pathNodes = nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3);
|
|
11117
|
+
const path9 = pathNodes.map((n) => ({
|
|
11118
|
+
sessionId: n.sessionId,
|
|
11119
|
+
seq: n.seq,
|
|
11120
|
+
detail: n.actionDetail.slice(0, 60)
|
|
11121
|
+
}));
|
|
10743
11122
|
violations.push({
|
|
10744
11123
|
propertyId: String(rule.id || "mc-ltl"),
|
|
10745
11124
|
reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
|
|
10746
11125
|
riskLevel: String(rule.risk_level || "high"),
|
|
10747
|
-
path:
|
|
11126
|
+
path: path9,
|
|
11127
|
+
graph: {
|
|
11128
|
+
property_id: String(rule.id || "mc-ltl"),
|
|
11129
|
+
property_short: "P6",
|
|
11130
|
+
property_name: "LTL \u6A21\u578B\u68C0\u6D4B",
|
|
11131
|
+
nodes: pathNodes.map((n) => ({
|
|
11132
|
+
session_id: n.sessionId,
|
|
11133
|
+
seq: n.seq,
|
|
11134
|
+
stage: n.stage,
|
|
11135
|
+
action_detail: n.actionDetail,
|
|
11136
|
+
resources: [...n.resources].sort(),
|
|
11137
|
+
instance_id: n.instanceId || ""
|
|
11138
|
+
})),
|
|
11139
|
+
edges: pathNodes.slice(1).map((_, i) => ({
|
|
11140
|
+
from: i,
|
|
11141
|
+
to: i + 1,
|
|
11142
|
+
type: "next"
|
|
11143
|
+
}))
|
|
11144
|
+
}
|
|
10748
11145
|
});
|
|
10749
11146
|
if (witnessMode) return violations;
|
|
10750
11147
|
}
|
|
@@ -11444,11 +11841,17 @@ function checkLowIntegrityCommandExec(graph) {
|
|
|
11444
11841
|
for (const i of candidates) {
|
|
11445
11842
|
const n = nodes[i];
|
|
11446
11843
|
if (lowAt.has(i) && isComputeNode(n)) {
|
|
11844
|
+
const path9 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
11447
11845
|
violations.push({
|
|
11448
11846
|
propertyId: "low-integrity-command-exec",
|
|
11449
11847
|
reason: `\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u63A7\u5236\u547D\u4EE4\u6267\u884C\uFF1A${lowAt.get(i)} \u2192 ${n.sessionId}#${n.seq} \u6267\u884C\u4E0D\u53EF\u4FE1\u5185\u5BB9`,
|
|
11450
11848
|
riskLevel: "critical",
|
|
11451
|
-
path:
|
|
11849
|
+
path: path9,
|
|
11850
|
+
graph: graphFromPath(nodes, path9, "next", {
|
|
11851
|
+
property_id: "low-integrity-command-exec",
|
|
11852
|
+
property_short: "P7",
|
|
11853
|
+
property_name: "\u4F4E\u5B8C\u6574\u6027\u547D\u4EE4\u6267\u884C"
|
|
11854
|
+
}, ["sink"])
|
|
11452
11855
|
});
|
|
11453
11856
|
if (witness !== void 0) return violations;
|
|
11454
11857
|
}
|
|
@@ -11490,11 +11893,21 @@ function checkCrossSessionReachability(graph) {
|
|
|
11490
11893
|
if (reached.has(i)) {
|
|
11491
11894
|
const srcIdx = Math.min(...sources);
|
|
11492
11895
|
const srcDesc = nodes[srcIdx].actionDetail.slice(0, 40);
|
|
11896
|
+
const path9 = nodes.slice(-3).map((m) => ({
|
|
11897
|
+
sessionId: m.sessionId,
|
|
11898
|
+
seq: m.seq,
|
|
11899
|
+
detail: m.actionDetail.slice(0, 60)
|
|
11900
|
+
}));
|
|
11493
11901
|
violations.push({
|
|
11494
11902
|
propertyId: "low-integrity-reachability",
|
|
11495
11903
|
reason: `\u4F4E\u5B8C\u6574\u6027\u6E90\u7ECF\u8DE8 session \u6570\u636E\u94FE\u591A\u8DF3\u5230\u8FBE\u5F53\u524D\u6267\u884C\uFF08\u6E90: ${srcDesc} \u2192 ${n.sessionId}#${n.seq}\uFF09`,
|
|
11496
11904
|
riskLevel: "high",
|
|
11497
|
-
path:
|
|
11905
|
+
path: path9,
|
|
11906
|
+
graph: graphFromPath(nodes, path9, "data", {
|
|
11907
|
+
property_id: "low-integrity-reachability",
|
|
11908
|
+
property_short: "P3",
|
|
11909
|
+
property_name: "\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u6D41\u53EF\u8FBE"
|
|
11910
|
+
})
|
|
11498
11911
|
});
|
|
11499
11912
|
if (witness !== void 0) return violations;
|
|
11500
11913
|
}
|
|
@@ -11834,7 +12247,24 @@ function fingerprint(sessionId, actionType, actionDetail, calledAt) {
|
|
|
11834
12247
|
].join("\0");
|
|
11835
12248
|
return createHash4("blake2b512").update(raw).digest("hex").slice(0, 16);
|
|
11836
12249
|
}
|
|
11837
|
-
|
|
12250
|
+
function gateOrder(action) {
|
|
12251
|
+
const callId = String(action?.gateCallId ?? "");
|
|
12252
|
+
const callTimeUs = Number(action?.gateCallTimeUs ?? 0);
|
|
12253
|
+
return callId && Number.isFinite(callTimeUs) && callTimeUs > 0 ? { callId, callTimeUs } : null;
|
|
12254
|
+
}
|
|
12255
|
+
function gateFingerprint(action, isError, agentId, instanceId, order) {
|
|
12256
|
+
const values = [
|
|
12257
|
+
String(action?.actionType ?? ""),
|
|
12258
|
+
String(action?.actionDetail ?? ""),
|
|
12259
|
+
String(action?.calledAt ?? ""),
|
|
12260
|
+
String(action?.agentId ?? agentId ?? ""),
|
|
12261
|
+
String(action?.instanceId ?? instanceId ?? ""),
|
|
12262
|
+
Boolean(isError),
|
|
12263
|
+
order.callTimeUs
|
|
12264
|
+
];
|
|
12265
|
+
return createHash4("sha256").update(JSON.stringify(values)).digest("hex");
|
|
12266
|
+
}
|
|
12267
|
+
var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, StatefulAnalysisUnavailable, UnconfirmedGateRetry, GateCallConflict, STAGES_PATTERNS, CHAINS, COMMON_DIR_RESOURCES2, MAX_NODES, TRUNCATED_DETAIL_RE, SHELL_ACTION_ALIASES, StatefulChainTracker;
|
|
11838
12268
|
var init_stateful = __esm({
|
|
11839
12269
|
"src/engine/formal-engine/stateful.ts"() {
|
|
11840
12270
|
"use strict";
|
|
@@ -11850,6 +12280,12 @@ var init_stateful = __esm({
|
|
|
11850
12280
|
SOCK_RE = /([\w./-]*(?:\/tmp\/|\/var\/run\/|\.sock\b)[\w./-]*)/;
|
|
11851
12281
|
UNIT_RE = /systemctl\s+(?:start|enable|restart)\s+([\w.-]+)/i;
|
|
11852
12282
|
PORT_STAGE_RE = /LISTEN|PERSIST|SCAN/;
|
|
12283
|
+
StatefulAnalysisUnavailable = class extends Error {
|
|
12284
|
+
};
|
|
12285
|
+
UnconfirmedGateRetry = class extends StatefulAnalysisUnavailable {
|
|
12286
|
+
};
|
|
12287
|
+
GateCallConflict = class extends UnconfirmedGateRetry {
|
|
12288
|
+
};
|
|
11853
12289
|
STAGES_PATTERNS = null;
|
|
11854
12290
|
CHAINS = null;
|
|
11855
12291
|
COMMON_DIR_RESOURCES2 = /* @__PURE__ */ new Set([
|
|
@@ -11893,6 +12329,8 @@ var init_stateful = __esm({
|
|
|
11893
12329
|
aliveResources = {};
|
|
11894
12330
|
seqNext = 0;
|
|
11895
12331
|
seededKeys = /* @__PURE__ */ new Set();
|
|
12332
|
+
/** (sessionId, gateCallId) → 节点,用于 Gate 精确一次关联。 */
|
|
12333
|
+
gateNodes = /* @__PURE__ */ new Map();
|
|
11896
12334
|
constructor(agentId = "") {
|
|
11897
12335
|
this.agentId = agentId;
|
|
11898
12336
|
loadRules();
|
|
@@ -11951,28 +12389,73 @@ var init_stateful = __esm({
|
|
|
11951
12389
|
}
|
|
11952
12390
|
return added;
|
|
11953
12391
|
}
|
|
12392
|
+
resultOf(node, matched, exfil) {
|
|
12393
|
+
return {
|
|
12394
|
+
seq: this.seqNext,
|
|
12395
|
+
node,
|
|
12396
|
+
matched,
|
|
12397
|
+
pendingPrefixes: this.pendingPrefixes,
|
|
12398
|
+
exfil,
|
|
12399
|
+
get shouldBlock() {
|
|
12400
|
+
return this.matched !== null || this.exfil.length > 0;
|
|
12401
|
+
}
|
|
12402
|
+
};
|
|
12403
|
+
}
|
|
11954
12404
|
/** 增量推进:把当前动作追加到时间线 → 链指针推进 → 判定。 */
|
|
11955
12405
|
advance(args) {
|
|
11956
12406
|
const { aNext, sessionId = "current", isError = false, agentId = "", instanceId = "" } = args;
|
|
11957
|
-
const
|
|
12407
|
+
const order = gateOrder(aNext);
|
|
12408
|
+
const gateFingerprintValue = order ? gateFingerprint(aNext, isError, agentId, instanceId, order) : "";
|
|
12409
|
+
if (order) {
|
|
12410
|
+
const existing = this.gateNodes.get(this.gateKey(sessionId, order.callId));
|
|
12411
|
+
if (existing) {
|
|
12412
|
+
if (existing.confirmed) {
|
|
12413
|
+
if (existing.inputFingerprint === gateFingerprintValue && existing.gateCallTimeUs === order.callTimeUs) {
|
|
12414
|
+
return this.resultOf(existing, existing.confirmed.matched, existing.confirmed.exfil);
|
|
12415
|
+
}
|
|
12416
|
+
throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u5185\u5BB9\u6216\u65F6\u95F4\u4E0D\u4E00\u81F4");
|
|
12417
|
+
}
|
|
12418
|
+
if (aNext.gateDeliveryUncertain === true) {
|
|
12419
|
+
throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
|
|
12420
|
+
}
|
|
12421
|
+
if (existing.gateCallTimeUs !== order.callTimeUs) {
|
|
12422
|
+
throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u65F6\u95F4\u4E0D\u4E00\u81F4");
|
|
12423
|
+
}
|
|
12424
|
+
if (existing.inputFingerprint) {
|
|
12425
|
+
throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u91CD\u590D\u8C03\u7528\u7F3A\u5C11\u9001\u8FBE\u4E0D\u786E\u5B9A\u6807\u8BB0");
|
|
12426
|
+
}
|
|
12427
|
+
return this.resultOf(existing, null, []);
|
|
12428
|
+
}
|
|
12429
|
+
if (aNext.gateDeliveryUncertain === true) {
|
|
12430
|
+
throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
|
|
12431
|
+
}
|
|
12432
|
+
}
|
|
12433
|
+
const node = this.appendNode(
|
|
12434
|
+
order ? {
|
|
12435
|
+
...aNext,
|
|
12436
|
+
gateCallId: order.callId,
|
|
12437
|
+
gateCallTimeUs: order.callTimeUs,
|
|
12438
|
+
gateInputFingerprint: gateFingerprintValue
|
|
12439
|
+
} : aNext,
|
|
12440
|
+
sessionId,
|
|
12441
|
+
isError,
|
|
12442
|
+
agentId,
|
|
12443
|
+
instanceId
|
|
12444
|
+
);
|
|
11958
12445
|
if (!node) {
|
|
11959
|
-
return
|
|
12446
|
+
return this.resultOf(null, null, []);
|
|
11960
12447
|
}
|
|
11961
12448
|
const seq = this.seqNext;
|
|
11962
12449
|
this.recordLifecycle(node);
|
|
11963
12450
|
const matched = this.advanceChains(node);
|
|
11964
12451
|
this.advanceTaint(node);
|
|
11965
12452
|
const exfil = this.checkExfilAfterTaint(node);
|
|
11966
|
-
|
|
11967
|
-
|
|
11968
|
-
node
|
|
11969
|
-
|
|
11970
|
-
|
|
11971
|
-
|
|
11972
|
-
get shouldBlock() {
|
|
11973
|
-
return this.matched !== null || this.exfil.length > 0;
|
|
11974
|
-
}
|
|
11975
|
-
};
|
|
12453
|
+
if (order) {
|
|
12454
|
+
node.confirmed = { matched, exfil };
|
|
12455
|
+
this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
|
|
12456
|
+
}
|
|
12457
|
+
void seq;
|
|
12458
|
+
return this.resultOf(node, matched, exfil);
|
|
11976
12459
|
}
|
|
11977
12460
|
/**
|
|
11978
12461
|
* 自动轮转:归档旧节点,只保留最近 `retain` 条,并重建链指针/taint。
|
|
@@ -12009,6 +12492,7 @@ var init_stateful = __esm({
|
|
|
12009
12492
|
this.taintOrigin.clear();
|
|
12010
12493
|
this.aliveResources = {};
|
|
12011
12494
|
this.seqNext = 0;
|
|
12495
|
+
this.gateNodes.clear();
|
|
12012
12496
|
for (const n of kept) {
|
|
12013
12497
|
const node = this.appendNode(
|
|
12014
12498
|
{
|
|
@@ -12016,7 +12500,12 @@ var init_stateful = __esm({
|
|
|
12016
12500
|
actionDetail: n.actionDetail,
|
|
12017
12501
|
agentId: n.agentId,
|
|
12018
12502
|
instanceId: n.instanceId,
|
|
12019
|
-
...n.timestamp ? { calledAt: n.timestamp } : {}
|
|
12503
|
+
...n.timestamp ? { calledAt: n.timestamp } : {},
|
|
12504
|
+
...n.gateCallId ? {
|
|
12505
|
+
gateCallId: n.gateCallId,
|
|
12506
|
+
gateCallTimeUs: n.gateCallTimeUs,
|
|
12507
|
+
gateInputFingerprint: n.inputFingerprint
|
|
12508
|
+
} : {}
|
|
12020
12509
|
},
|
|
12021
12510
|
n.sessionId,
|
|
12022
12511
|
n.isError,
|
|
@@ -12024,6 +12513,7 @@ var init_stateful = __esm({
|
|
|
12024
12513
|
n.instanceId
|
|
12025
12514
|
);
|
|
12026
12515
|
if (node) {
|
|
12516
|
+
if (n.confirmed) node.confirmed = n.confirmed;
|
|
12027
12517
|
this.recordLifecycle(node);
|
|
12028
12518
|
this.advanceTaint(node);
|
|
12029
12519
|
this.advanceChains(node);
|
|
@@ -12031,6 +12521,9 @@ var init_stateful = __esm({
|
|
|
12031
12521
|
}
|
|
12032
12522
|
return { archived: old.length, file };
|
|
12033
12523
|
}
|
|
12524
|
+
gateKey(sessionId, callId) {
|
|
12525
|
+
return `${sessionId}\0${callId}`;
|
|
12526
|
+
}
|
|
12034
12527
|
appendNode(action, sessionId, isError = false, agentId = "", instanceId = "") {
|
|
12035
12528
|
const ad = String(action.actionDetail || "");
|
|
12036
12529
|
const at = String(action.actionType || "");
|
|
@@ -12062,6 +12555,13 @@ var init_stateful = __esm({
|
|
|
12062
12555
|
lifecycle: lifecycleFor(ad, stage, isError),
|
|
12063
12556
|
timestamp: suppliedCalledAt || _StatefulChainTracker.now()
|
|
12064
12557
|
};
|
|
12558
|
+
const order = gateOrder(action);
|
|
12559
|
+
if (order) {
|
|
12560
|
+
node.gateCallId = order.callId;
|
|
12561
|
+
node.gateCallTimeUs = order.callTimeUs;
|
|
12562
|
+
node.inputFingerprint = String(action.gateInputFingerprint || "");
|
|
12563
|
+
this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
|
|
12564
|
+
}
|
|
12065
12565
|
this.nodes_.push(node);
|
|
12066
12566
|
this.seqNext += 1;
|
|
12067
12567
|
if (dedupeKey) this.seededKeys.add(dedupeKey);
|
|
@@ -12413,11 +12913,19 @@ var init_stateful = __esm({
|
|
|
12413
12913
|
// 旧快照无此字段 → 空
|
|
12414
12914
|
isError: Boolean(raw.isError),
|
|
12415
12915
|
lifecycle: String(raw.lifecycle || ""),
|
|
12416
|
-
timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null
|
|
12916
|
+
timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null,
|
|
12417
12917
|
// 旧快照无此字段 → null
|
|
12918
|
+
...raw.gateCallId ? { gateCallId: String(raw.gateCallId) } : {},
|
|
12919
|
+
...raw.gateCallTimeUs ? { gateCallTimeUs: Number(raw.gateCallTimeUs) } : {},
|
|
12920
|
+
...raw.inputFingerprint ? { inputFingerprint: String(raw.inputFingerprint) } : {},
|
|
12921
|
+
...raw.confirmed ? { confirmed: raw.confirmed } : {}
|
|
12418
12922
|
});
|
|
12419
12923
|
}
|
|
12420
12924
|
this.seqNext = Number(snapshot.seq_next || this.nodes_.length);
|
|
12925
|
+
this.gateNodes = /* @__PURE__ */ new Map();
|
|
12926
|
+
for (const n of this.nodes_) {
|
|
12927
|
+
if (n.gateCallId) this.gateNodes.set(this.gateKey(n.sessionId, n.gateCallId), n);
|
|
12928
|
+
}
|
|
12421
12929
|
for (const n of this.nodes_) {
|
|
12422
12930
|
if (n.timestamp) {
|
|
12423
12931
|
this.seededKeys.add(fingerprint(n.sessionId, n.actionType, n.actionDetail, n.timestamp));
|
|
@@ -12878,9 +13386,19 @@ async function runAnalysis(input) {
|
|
|
12878
13386
|
isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
|
|
12879
13387
|
isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
|
|
12880
13388
|
);
|
|
13389
|
+
const degradedNotes = [];
|
|
12881
13390
|
let scriptChain = null;
|
|
12882
|
-
if (input.aNext.actionType.toLowerCase() === "bash") {
|
|
13391
|
+
if (input.aNext.actionType.toLowerCase() === "bash" && getDeployRole() === "host") {
|
|
13392
|
+
degradedNotes.push("script_content_deferred_to_sandbox: AGENT_MOSS_DEPLOY_ROLE=host");
|
|
13393
|
+
} else if (input.aNext.actionType.toLowerCase() === "bash") {
|
|
12883
13394
|
scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
|
|
13395
|
+
if (scriptChain.nodes.length > 0) {
|
|
13396
|
+
for (const node of scriptChain.nodes) {
|
|
13397
|
+
if (node.error && !node.unanalyzable) {
|
|
13398
|
+
degradedNotes.push(`script_content_unavailable: ${node.scriptPath} (${node.error})`);
|
|
13399
|
+
}
|
|
13400
|
+
}
|
|
13401
|
+
}
|
|
12884
13402
|
if (heuristicEnabled && scriptChain.nodes.length > 0) {
|
|
12885
13403
|
for (const node of scriptChain.nodes) {
|
|
12886
13404
|
if (node.unanalyzable) {
|
|
@@ -13151,7 +13669,8 @@ async function runAnalysis(input) {
|
|
|
13151
13669
|
riskType: "",
|
|
13152
13670
|
confidence: 85,
|
|
13153
13671
|
source: "heuristic_and_logic_only",
|
|
13154
|
-
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
|
|
13672
|
+
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
|
|
13673
|
+
degraded: degradedNotes
|
|
13155
13674
|
};
|
|
13156
13675
|
}
|
|
13157
13676
|
let skipL3Hints = "\u65E0\uFF08\u5F53\u524D\u65E0\u7981\u7528\u89C4\u5219\u547D\u4E2D\uFF09";
|
|
@@ -13188,8 +13707,22 @@ async function runAnalysis(input) {
|
|
|
13188
13707
|
pathContext
|
|
13189
13708
|
});
|
|
13190
13709
|
} catch (e) {
|
|
13191
|
-
const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
|
|
13192
13710
|
const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
|
|
13711
|
+
if (e instanceof LLMPromptBudgetExceeded) {
|
|
13712
|
+
const failMode = getLLMFailMode2();
|
|
13713
|
+
const allowed = failMode === "fail_open";
|
|
13714
|
+
return {
|
|
13715
|
+
allowed,
|
|
13716
|
+
reason: `L3 prompt \u8D85\u51FA\u786C\u9884\u7B97\uFF0C\u5DF2\u8DF3\u8FC7\u8BED\u4E49\u5206\u6790\uFF0C\u6309 ${failMode} ${allowed ? "\u653E\u884C" : "\u62D2\u7EDD"}`,
|
|
13717
|
+
riskLevel: allowed ? "low" : "medium",
|
|
13718
|
+
riskType: "",
|
|
13719
|
+
confidence: allowed ? 50 : 60,
|
|
13720
|
+
source: "llm_budget_skipped",
|
|
13721
|
+
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
|
|
13722
|
+
degraded: [...degradedNotes, e.code]
|
|
13723
|
+
};
|
|
13724
|
+
}
|
|
13725
|
+
const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
|
|
13193
13726
|
if (getLLMFailMode2() === "fail_open") {
|
|
13194
13727
|
console.warn(`[AgentMoss] LLM \u5206\u6790\u5931\u8D25\uFF0Cfail_open \u6A21\u5F0F\uFF1A\u5141\u8BB8\u6267\u884C\uFF08\u524D\u4E24\u5C42\u672A\u62E6\u622A\uFF09: ${e.message}`);
|
|
13195
13728
|
return {
|
|
@@ -13199,7 +13732,8 @@ async function runAnalysis(input) {
|
|
|
13199
13732
|
riskType: "",
|
|
13200
13733
|
confidence: 50,
|
|
13201
13734
|
source: failSource,
|
|
13202
|
-
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
|
|
13735
|
+
violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
|
|
13736
|
+
degraded: degradedNotes
|
|
13203
13737
|
};
|
|
13204
13738
|
}
|
|
13205
13739
|
return {
|
|
@@ -13209,7 +13743,10 @@ async function runAnalysis(input) {
|
|
|
13209
13743
|
riskType: "",
|
|
13210
13744
|
confidence: 60,
|
|
13211
13745
|
source: failSource,
|
|
13212
|
-
violatedLayers: ["L3.1"]
|
|
13746
|
+
violatedLayers: ["L3.1"],
|
|
13747
|
+
degraded: degradedNotes,
|
|
13748
|
+
ask_recommended: true,
|
|
13749
|
+
ask_reason: "L3 \u8BED\u4E49\u5206\u6790\u4E0D\u53EF\u7528\uFF0C\u6309 fail_closed \u62D2\u7EDD\uFF1B\u8FD9\u662F\u201C\u6CA1\u67E5\u5B8C\u201D\u800C\u975E\u201C\u786E\u8BA4\u6709\u98CE\u9669\u201D\uFF0C\u5EFA\u8BAE\u5411\u7528\u6237\u786E\u8BA4\u662F\u5426\u7EE7\u7EED\u3002"
|
|
13213
13750
|
};
|
|
13214
13751
|
}
|
|
13215
13752
|
if (!llmResult.allowed && llmResult.confidence && llmResult.confidence >= 90 && _brainExtractor) {
|
|
@@ -13229,6 +13766,9 @@ async function runAnalysis(input) {
|
|
|
13229
13766
|
if (observedFormalLayers.length > 0 && llmResult.allowed) {
|
|
13230
13767
|
llmResult.violatedLayers = Array.from(/* @__PURE__ */ new Set([...observedFormalLayers, ...llmResult.violatedLayers || []]));
|
|
13231
13768
|
}
|
|
13769
|
+
if (degradedNotes.length > 0) {
|
|
13770
|
+
llmResult.degraded = Array.from(/* @__PURE__ */ new Set([...llmResult.degraded || [], ...degradedNotes]));
|
|
13771
|
+
}
|
|
13232
13772
|
return llmResult;
|
|
13233
13773
|
}
|
|
13234
13774
|
var TRUSTED_SKILLS_BASE, _brainStore, _brainExtractor, _brainSkillManager, _brainCurator, _brainInitialized, _brainLastMaintenance, BRAIN_MAINT_INTERVAL_MS, formalEngine;
|
|
@@ -13415,8 +13955,8 @@ init_paths();
|
|
|
13415
13955
|
import { cors } from "hono/cors";
|
|
13416
13956
|
import { logger } from "hono/logger";
|
|
13417
13957
|
import net from "net";
|
|
13418
|
-
import { existsSync as
|
|
13419
|
-
import { dirname as
|
|
13958
|
+
import { existsSync as existsSync22, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync10 } from "fs";
|
|
13959
|
+
import { dirname as dirname16 } from "path";
|
|
13420
13960
|
|
|
13421
13961
|
// src/package-json.ts
|
|
13422
13962
|
init_esm_shims();
|
|
@@ -13475,7 +14015,11 @@ var AnalyzeRequestSchema = z.object({
|
|
|
13475
14015
|
cwd: z.string().default("").describe("Current working directory"),
|
|
13476
14016
|
agent_id: z.string().default("").describe("Caller agent identifier, e.g. 'xiaoo' / 'opencode' / 'opendesk'. Empty = generic mode (no agent-specific rules)."),
|
|
13477
14017
|
instance_id: z.string().default("").describe("Agent installation/instance identifier. Used only for display-layer redaction: nodes from the same instance are returned unredacted. Does not affect detection."),
|
|
13478
|
-
metadata: z.record(z.unknown()).optional().describe("Extended metadata")
|
|
14018
|
+
metadata: z.record(z.unknown()).optional().describe("Extended metadata"),
|
|
14019
|
+
// 仅在 AgentGate 专用身份通过后校验;直连调用方传这些字段会被忽略。
|
|
14020
|
+
gate_call_id: z.unknown().optional(),
|
|
14021
|
+
gate_call_time_us: z.unknown().optional(),
|
|
14022
|
+
gate_delivery_uncertain: z.unknown().optional()
|
|
13479
14023
|
});
|
|
13480
14024
|
var AnalyzeResponseSchema = z.object({
|
|
13481
14025
|
decision: z.enum(["Allow", "Deny"]).describe("Allow or Deny"),
|
|
@@ -13505,6 +14049,11 @@ var AnalyzeResponseSchema = z.object({
|
|
|
13505
14049
|
""
|
|
13506
14050
|
// 未算出(极端异常路径)
|
|
13507
14051
|
]).default(""),
|
|
14052
|
+
/** Deny 但建议向用户确认(旧 agent 忽略仍是 Deny) */
|
|
14053
|
+
ask_recommended: z.boolean().default(false),
|
|
14054
|
+
ask_reason: z.string().default(""),
|
|
14055
|
+
/** Gate 专用调用回显;直连调用为空。 */
|
|
14056
|
+
gate_call_id: z.string().optional(),
|
|
13508
14057
|
// 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
|
|
13509
14058
|
violation_graph: z.object({
|
|
13510
14059
|
// 性质元信息(前端展示"违反了哪条性质")
|
|
@@ -13584,9 +14133,9 @@ var ReviewResponseSchema = z.object({
|
|
|
13584
14133
|
init_esm_shims();
|
|
13585
14134
|
init_security_policy();
|
|
13586
14135
|
init_coordinator();
|
|
13587
|
-
import { existsSync as
|
|
14136
|
+
import { existsSync as existsSync19, readFileSync as readFileSync19 } from "fs";
|
|
13588
14137
|
import { tmpdir as tmpdir3 } from "os";
|
|
13589
|
-
import { join as
|
|
14138
|
+
import { join as join19, resolve as resolve12 } from "path";
|
|
13590
14139
|
|
|
13591
14140
|
// src/engine/types.ts
|
|
13592
14141
|
init_esm_shims();
|
|
@@ -13597,7 +14146,7 @@ function deriveL3Outcome(j) {
|
|
|
13597
14146
|
if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
|
|
13598
14147
|
if (src === "llm_circuit_open") return "circuit_open";
|
|
13599
14148
|
if (src === "llm_failure_with_violation") return "failed_but_blocked";
|
|
13600
|
-
if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
|
|
14149
|
+
if (src === "heuristic_and_logic_only" || src === "disabled" || src === "llm_budget_skipped") return "skipped";
|
|
13601
14150
|
return "not_reached";
|
|
13602
14151
|
}
|
|
13603
14152
|
|
|
@@ -13607,10 +14156,10 @@ init_security_policy();
|
|
|
13607
14156
|
init_paths();
|
|
13608
14157
|
init_config();
|
|
13609
14158
|
import { createHash as createHash6 } from "crypto";
|
|
13610
|
-
import { existsSync as
|
|
14159
|
+
import { existsSync as existsSync18, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync18, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
|
|
13611
14160
|
import { tmpdir as tmpdir2 } from "os";
|
|
13612
|
-
import { join as
|
|
13613
|
-
var CACHE_DIR =
|
|
14161
|
+
import { join as join18 } from "path";
|
|
14162
|
+
var CACHE_DIR = join18(tmpdir2(), "agent_moss_policy_cache");
|
|
13614
14163
|
var cacheDirOverride = null;
|
|
13615
14164
|
function cacheDir() {
|
|
13616
14165
|
return cacheDirOverride ?? CACHE_DIR;
|
|
@@ -13619,7 +14168,7 @@ function safeCacheDir() {
|
|
|
13619
14168
|
const dir = cacheDir();
|
|
13620
14169
|
if (ensurePrivateDir(dir)) return dir;
|
|
13621
14170
|
try {
|
|
13622
|
-
const fallback =
|
|
14171
|
+
const fallback = join18(getDataRoot(), "policy_cache");
|
|
13623
14172
|
if (ensurePrivateDir(fallback)) {
|
|
13624
14173
|
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}`);
|
|
13625
14174
|
return fallback;
|
|
@@ -13641,7 +14190,7 @@ var PolicyCache = class {
|
|
|
13641
14190
|
cacheFilePath(sessionId, promptSession) {
|
|
13642
14191
|
const promptHash = createHash6("md5").update(promptSession).digest("hex").slice(0, 12);
|
|
13643
14192
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
13644
|
-
return
|
|
14193
|
+
return join18(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
|
|
13645
14194
|
}
|
|
13646
14195
|
/** 取缓存:内存 → 文件;未命中返回 null。 */
|
|
13647
14196
|
get(sessionId, promptSession) {
|
|
@@ -13654,9 +14203,9 @@ var PolicyCache = class {
|
|
|
13654
14203
|
return hit;
|
|
13655
14204
|
}
|
|
13656
14205
|
const file = this.cacheFilePath(sessionId, promptSession);
|
|
13657
|
-
if (
|
|
14206
|
+
if (existsSync18(file) && !lstatSync2(file).isSymbolicLink()) {
|
|
13658
14207
|
try {
|
|
13659
|
-
const policy =
|
|
14208
|
+
const policy = readFileSync18(file, "utf-8");
|
|
13660
14209
|
this.remember(key, policy);
|
|
13661
14210
|
return policy;
|
|
13662
14211
|
} catch {
|
|
@@ -13672,7 +14221,7 @@ var PolicyCache = class {
|
|
|
13672
14221
|
try {
|
|
13673
14222
|
const dir = safeCacheDir();
|
|
13674
14223
|
const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
13675
|
-
if (!ensurePrivateDir(
|
|
14224
|
+
if (!ensurePrivateDir(join18(dir, sub))) return;
|
|
13676
14225
|
writePrivateText(file, policy);
|
|
13677
14226
|
} catch {
|
|
13678
14227
|
}
|
|
@@ -13698,12 +14247,12 @@ var PolicyCache = class {
|
|
|
13698
14247
|
if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
|
|
13699
14248
|
}
|
|
13700
14249
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
13701
|
-
const dir =
|
|
14250
|
+
const dir = join18(cacheDir(), safeSessionId);
|
|
13702
14251
|
try {
|
|
13703
|
-
if (
|
|
14252
|
+
if (existsSync18(dir)) {
|
|
13704
14253
|
for (const f of readdirSync6(dir)) {
|
|
13705
14254
|
try {
|
|
13706
|
-
unlinkSync5(
|
|
14255
|
+
unlinkSync5(join18(dir, f));
|
|
13707
14256
|
} catch {
|
|
13708
14257
|
}
|
|
13709
14258
|
}
|
|
@@ -13715,11 +14264,11 @@ var PolicyCache = class {
|
|
|
13715
14264
|
clear() {
|
|
13716
14265
|
this.memory.clear();
|
|
13717
14266
|
try {
|
|
13718
|
-
if (
|
|
14267
|
+
if (existsSync18(cacheDir())) {
|
|
13719
14268
|
for (const sessionDir of readdirSync6(cacheDir())) {
|
|
13720
|
-
const dir =
|
|
14269
|
+
const dir = join18(cacheDir(), sessionDir);
|
|
13721
14270
|
try {
|
|
13722
|
-
for (const f of readdirSync6(dir)) unlinkSync5(
|
|
14271
|
+
for (const f of readdirSync6(dir)) unlinkSync5(join18(dir, f));
|
|
13723
14272
|
rmdirSync(dir);
|
|
13724
14273
|
} catch {
|
|
13725
14274
|
}
|
|
@@ -13806,7 +14355,7 @@ ${safe(policy, 2e3)}`);
|
|
|
13806
14355
|
|
|
13807
14356
|
// src/engine/analyzer.ts
|
|
13808
14357
|
import { parse as parseToml } from "smol-toml";
|
|
13809
|
-
var POLICY_OUTPUT_DIR =
|
|
14358
|
+
var POLICY_OUTPUT_DIR = join19(tmpdir3(), "agent_moss");
|
|
13810
14359
|
var policyOutputDirOverride = null;
|
|
13811
14360
|
function policyOutputDir() {
|
|
13812
14361
|
return policyOutputDirOverride ?? POLICY_OUTPUT_DIR;
|
|
@@ -13845,7 +14394,7 @@ function savePolicyToFile(sessionId, policyToml) {
|
|
|
13845
14394
|
return null;
|
|
13846
14395
|
}
|
|
13847
14396
|
const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
13848
|
-
const filepath =
|
|
14397
|
+
const filepath = join19(outDir, `${safeName}.toml`);
|
|
13849
14398
|
writePrivateText(filepath, policyToml);
|
|
13850
14399
|
return filepath;
|
|
13851
14400
|
} catch (err) {
|
|
@@ -13883,12 +14432,12 @@ function validateToml(tomlStr) {
|
|
|
13883
14432
|
function loadPolicyMappingDoc() {
|
|
13884
14433
|
const dir = resolveAssetDir(__dirname, "templates");
|
|
13885
14434
|
if (dir) {
|
|
13886
|
-
const p =
|
|
13887
|
-
if (
|
|
14435
|
+
const p = resolve12(dir, "policy_mapping.md");
|
|
14436
|
+
if (existsSync19(p)) return readFileSync19(p, "utf-8");
|
|
13888
14437
|
}
|
|
13889
14438
|
for (const cand of assetDirCandidates(__dirname, "templates")) {
|
|
13890
|
-
const p =
|
|
13891
|
-
if (
|
|
14439
|
+
const p = resolve12(cand, "policy_mapping.md");
|
|
14440
|
+
if (existsSync19(p)) return readFileSync19(p, "utf-8");
|
|
13892
14441
|
}
|
|
13893
14442
|
return "";
|
|
13894
14443
|
}
|
|
@@ -14168,6 +14717,7 @@ function reportEnforcementEvent(opts) {
|
|
|
14168
14717
|
|
|
14169
14718
|
// src/routes.ts
|
|
14170
14719
|
init_formal_engine();
|
|
14720
|
+
init_stateful();
|
|
14171
14721
|
init_circuit_breaker();
|
|
14172
14722
|
|
|
14173
14723
|
// src/engine/formal-engine/pattern_miner.ts
|
|
@@ -14267,6 +14817,16 @@ function normalizeAction(row) {
|
|
|
14267
14817
|
actionDetail: String(row.action_detail || row.command || row.input || "")
|
|
14268
14818
|
};
|
|
14269
14819
|
if (row.called_at) act.calledAt = String(row.called_at);
|
|
14820
|
+
try {
|
|
14821
|
+
const audit = JSON.parse(String(row.moss_response || "{}"));
|
|
14822
|
+
if (audit && audit._gate_protocol_rejected === true) {
|
|
14823
|
+
act.gateProtocolRejected = true;
|
|
14824
|
+
} else if (audit && typeof audit._gate_call_id === "string" && /^[0-9a-f]{32}$/.test(audit._gate_call_id) && Number.isInteger(audit._gate_call_time_us) && audit._gate_call_time_us > 0) {
|
|
14825
|
+
act.gateCallId = audit._gate_call_id;
|
|
14826
|
+
act.gateCallTimeUs = audit._gate_call_time_us;
|
|
14827
|
+
}
|
|
14828
|
+
} catch {
|
|
14829
|
+
}
|
|
14270
14830
|
return act;
|
|
14271
14831
|
}
|
|
14272
14832
|
function readJsonDir(dirPath, limit = 1e5, strict = false) {
|
|
@@ -14307,10 +14867,18 @@ function readSqlite(dbPath, limit = 1e5, strict = false) {
|
|
|
14307
14867
|
let db;
|
|
14308
14868
|
try {
|
|
14309
14869
|
db = new Database(dbPath, { readonly: true });
|
|
14310
|
-
|
|
14311
|
-
|
|
14312
|
-
|
|
14313
|
-
|
|
14870
|
+
let rows;
|
|
14871
|
+
try {
|
|
14872
|
+
rows = db.prepare(
|
|
14873
|
+
`SELECT session_id, action_type, tool_name, action_detail, command, called_at, moss_response
|
|
14874
|
+
FROM tool_calls ORDER BY called_at, id LIMIT ?`
|
|
14875
|
+
).all(limit);
|
|
14876
|
+
} catch {
|
|
14877
|
+
rows = db.prepare(
|
|
14878
|
+
`SELECT session_id, action_type, tool_name, action_detail, command, called_at
|
|
14879
|
+
FROM tool_calls ORDER BY called_at, id LIMIT ?`
|
|
14880
|
+
).all(limit);
|
|
14881
|
+
}
|
|
14314
14882
|
const sessions = /* @__PURE__ */ new Map();
|
|
14315
14883
|
for (const r of rows) {
|
|
14316
14884
|
const sid = String(r.session_id || "");
|
|
@@ -14465,9 +15033,9 @@ function poolsSnapshot() {
|
|
|
14465
15033
|
|
|
14466
15034
|
// src/routes.ts
|
|
14467
15035
|
init_metrics();
|
|
14468
|
-
import { join as
|
|
14469
|
-
import { fileURLToPath as
|
|
14470
|
-
var __dirname9 =
|
|
15036
|
+
import { join as join21, dirname as dirname14 } from "path";
|
|
15037
|
+
import { fileURLToPath as fileURLToPath11 } from "url";
|
|
15038
|
+
var __dirname9 = dirname14(fileURLToPath11(import.meta.url));
|
|
14471
15039
|
async function healthRoute(c) {
|
|
14472
15040
|
const metrics = {};
|
|
14473
15041
|
try {
|
|
@@ -14520,6 +15088,10 @@ async function analyzeRoute(c) {
|
|
|
14520
15088
|
try {
|
|
14521
15089
|
const body = await c.req.json();
|
|
14522
15090
|
const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
|
|
15091
|
+
const gateCallId = String(c.get("gateCallId") || "");
|
|
15092
|
+
if (gateCallId && (req.gate_call_id !== gateCallId || !validGateCallTime(req.gate_call_time_us) || typeof req.gate_delivery_uncertain !== "boolean")) {
|
|
15093
|
+
return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5143\u6570\u636E\u65E0\u6548" }, 422);
|
|
15094
|
+
}
|
|
14523
15095
|
const unmappedTool = String(
|
|
14524
15096
|
req.metadata?.unmapped_tool || ""
|
|
14525
15097
|
);
|
|
@@ -14632,7 +15204,16 @@ async function analyzeRoute(c) {
|
|
|
14632
15204
|
const store = getChainStateStoreFor(agentId);
|
|
14633
15205
|
const inc = store.applyAction(
|
|
14634
15206
|
chainBucket(agentId),
|
|
14635
|
-
{
|
|
15207
|
+
{
|
|
15208
|
+
actionType: req.a_next.action_type,
|
|
15209
|
+
actionDetail: req.a_next.action_detail,
|
|
15210
|
+
...req.a_next.called_at ? { calledAt: req.a_next.called_at } : {},
|
|
15211
|
+
...gateCallId ? {
|
|
15212
|
+
gateCallId,
|
|
15213
|
+
gateCallTimeUs: req.gate_call_time_us,
|
|
15214
|
+
gateDeliveryUncertain: req.gate_delivery_uncertain === true
|
|
15215
|
+
} : {}
|
|
15216
|
+
},
|
|
14636
15217
|
req.session_id,
|
|
14637
15218
|
Boolean(meta.is_error),
|
|
14638
15219
|
agentId,
|
|
@@ -14655,7 +15236,31 @@ async function analyzeRoute(c) {
|
|
|
14655
15236
|
}
|
|
14656
15237
|
finding = incMatchedToDeny(inc);
|
|
14657
15238
|
} catch (err) {
|
|
14658
|
-
|
|
15239
|
+
if (err instanceof UnconfirmedGateRetry) {
|
|
15240
|
+
const reason = "AgentMoss \u65E0\u6CD5\u786E\u8BA4\u672C\u6B21 Gate \u8C03\u7528\u662F\u5426\u5DF2\u5165\u94FE";
|
|
15241
|
+
degradedNotes.push(`\u3010\u5DF2\u964D\u7EA7\u3011${reason}\uFF1B\u672C\u6B21\u6309\u62D2\u7EDD\u5904\u7406\uFF0C\u907F\u514D\u91CD\u590D\u5165\u94FE\u3002`);
|
|
15242
|
+
if (result.decision !== "Deny") {
|
|
15243
|
+
result = {
|
|
15244
|
+
...result,
|
|
15245
|
+
decision: "Deny",
|
|
15246
|
+
reason,
|
|
15247
|
+
risk_type: "service_unavailable",
|
|
15248
|
+
risk_level: "high",
|
|
15249
|
+
policy: "",
|
|
15250
|
+
ask_recommended: true,
|
|
15251
|
+
ask_reason: "\u65E0\u6CD5\u786E\u8BA4\u672C\u6B21 Gate \u8C03\u7528\u662F\u5426\u5DF2\u5165\u94FE\uFF1B\u8FD9\u662F\u201C\u6CA1\u67E5\u5B8C\u201D\u800C\u975E\u201C\u786E\u8BA4\u6709\u98CE\u9669\u201D\uFF0C\u5EFA\u8BAE\u5411\u7528\u6237\u786E\u8BA4\u662F\u5426\u7EE7\u7EED\u3002"
|
|
15252
|
+
};
|
|
15253
|
+
}
|
|
15254
|
+
} else if (err instanceof StatefulAnalysisUnavailable) {
|
|
15255
|
+
degradedNotes.push(
|
|
15256
|
+
"\u3010\u5DF2\u964D\u7EA7\u3011\u6709\u72B6\u6001\u5206\u6790\u4E0D\u53EF\u7528\uFF08\u94FE\u72B6\u6001\u5B58\u50A8\u4E0D\u53EF\u7528\u6216\u672C\u6B21\u52A8\u4F5C\u8D85\u51FA\u4FDD\u7559\u7A97\u53E3\uFF09\uFF1A\u672C\u6B21\u52A8\u4F5C\u672A\u53C2\u4E0E L2.2 \u7EC4\u5408\u94FE\u68C0\u6D4B\uFF1BL1/L2.1/L3 \u5224\u5B9A\u4E0D\u53D7\u5F71\u54CD\u3002"
|
|
15257
|
+
);
|
|
15258
|
+
} else {
|
|
15259
|
+
console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
|
|
15260
|
+
degradedNotes.push(
|
|
15261
|
+
"\u3010\u5DF2\u964D\u7EA7\u3011\u6709\u72B6\u6001\u5206\u6790\u4E0D\u53EF\u7528\uFF08\u5185\u90E8\u5F02\u5E38\uFF09\uFF1A\u672C\u6B21\u52A8\u4F5C\u672A\u53C2\u4E0E L2.2 \u7EC4\u5408\u94FE\u68C0\u6D4B\uFF1BL1/L2.1/L3 \u5224\u5B9A\u4E0D\u53D7\u5F71\u54CD\u3002"
|
|
15262
|
+
);
|
|
15263
|
+
}
|
|
14659
15264
|
}
|
|
14660
15265
|
}
|
|
14661
15266
|
result = publicFormalResult(
|
|
@@ -14666,6 +15271,11 @@ async function analyzeRoute(c) {
|
|
|
14666
15271
|
req.session_history || []
|
|
14667
15272
|
);
|
|
14668
15273
|
const durationMs = performance.now() - t0;
|
|
15274
|
+
if (Array.isArray(result.degraded)) {
|
|
15275
|
+
for (const note of result.degraded) {
|
|
15276
|
+
if (note && !degradedNotes.includes(note)) degradedNotes.push(note);
|
|
15277
|
+
}
|
|
15278
|
+
}
|
|
14669
15279
|
const _l3FailMsg = String(result.reason || "").slice(0, 160);
|
|
14670
15280
|
if (result.l3_outcome === "reasoning_fallback") {
|
|
14671
15281
|
degradedNotes.push(
|
|
@@ -14755,7 +15365,10 @@ async function analyzeRoute(c) {
|
|
|
14755
15365
|
degraded: degradedNotes,
|
|
14756
15366
|
// L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
|
|
14757
15367
|
// 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
|
|
14758
|
-
l3_outcome: result.l3_outcome || ""
|
|
15368
|
+
l3_outcome: result.l3_outcome || "",
|
|
15369
|
+
ask_recommended: result.ask_recommended === true,
|
|
15370
|
+
ask_reason: String(result.ask_reason || ""),
|
|
15371
|
+
...gateCallId ? { gate_call_id: gateCallId } : {}
|
|
14759
15372
|
})
|
|
14760
15373
|
);
|
|
14761
15374
|
} catch (err) {
|
|
@@ -14912,7 +15525,11 @@ async function reviewRoute(c) {
|
|
|
14912
15525
|
if (!tracker) {
|
|
14913
15526
|
tracker = new StatefulChainTracker(bucket);
|
|
14914
15527
|
}
|
|
14915
|
-
const
|
|
15528
|
+
const seedSessions = sessions.map((s) => ({
|
|
15529
|
+
...s,
|
|
15530
|
+
actionHistory: (s.actionHistory || []).filter((a) => !a.gateProtocolRejected)
|
|
15531
|
+
}));
|
|
15532
|
+
const added = seedSessions.length > 0 ? tracker.seed(seedSessions) : 0;
|
|
14916
15533
|
store.save(tracker);
|
|
14917
15534
|
let verified = true;
|
|
14918
15535
|
const violations = [];
|
|
@@ -14976,7 +15593,7 @@ function getBrainRuleStore() {
|
|
|
14976
15593
|
return new BrainRuleStore();
|
|
14977
15594
|
}
|
|
14978
15595
|
function getBrainSkillManager() {
|
|
14979
|
-
const dir = resolveAssetDir(__dirname9, "skills") ??
|
|
15596
|
+
const dir = resolveAssetDir(__dirname9, "skills") ?? join21(__dirname9, "..", "..", "agent_moss", "skills");
|
|
14980
15597
|
return new BrainSkillManager(dir);
|
|
14981
15598
|
}
|
|
14982
15599
|
async function brainRulesRoute(c) {
|
|
@@ -15078,13 +15695,14 @@ init_token_stats();
|
|
|
15078
15695
|
init_rules_loader();
|
|
15079
15696
|
init_asset_dir();
|
|
15080
15697
|
init_rules_mode();
|
|
15698
|
+
init_edition_scope();
|
|
15081
15699
|
import { Hono } from "hono";
|
|
15082
15700
|
import { timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
15083
|
-
import { readFileSync as
|
|
15084
|
-
import { join as
|
|
15085
|
-
import { fileURLToPath as
|
|
15086
|
-
var __dirname10 =
|
|
15087
|
-
var STATIC_DIR =
|
|
15701
|
+
import { readFileSync as readFileSync21, existsSync as existsSync21, unlinkSync as unlinkSync6 } from "fs";
|
|
15702
|
+
import { join as join22, dirname as dirname15 } from "path";
|
|
15703
|
+
import { fileURLToPath as fileURLToPath12 } from "url";
|
|
15704
|
+
var __dirname10 = dirname15(fileURLToPath12(import.meta.url));
|
|
15705
|
+
var STATIC_DIR = join22(__dirname10, "static");
|
|
15088
15706
|
var CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
|
|
15089
15707
|
function getConsoleToken() {
|
|
15090
15708
|
return process.env[CONSOLE_TOKEN_ENV] || "";
|
|
@@ -15111,6 +15729,16 @@ function authMiddleware() {
|
|
|
15111
15729
|
function displayRuntimeConfig() {
|
|
15112
15730
|
return isRuntimeConfigDisabled() ? generateSourceDefaults() : loadRuntimeConfig();
|
|
15113
15731
|
}
|
|
15732
|
+
function scopedAgentRules(rc) {
|
|
15733
|
+
return Object.fromEntries(
|
|
15734
|
+
Object.entries(getAgentRules(rc)).filter(([id]) => isAllowed("agents", id))
|
|
15735
|
+
);
|
|
15736
|
+
}
|
|
15737
|
+
function scopedScenarioRules(rc) {
|
|
15738
|
+
return Object.fromEntries(
|
|
15739
|
+
Object.entries(getScenarioRules(rc)).filter(([id]) => isAllowed("scenarios", id))
|
|
15740
|
+
);
|
|
15741
|
+
}
|
|
15114
15742
|
function builtinOnlyReadOnlyMiddleware() {
|
|
15115
15743
|
return async (c, next) => {
|
|
15116
15744
|
if (isRuntimeConfigDisabled() && !["GET", "HEAD", "OPTIONS"].includes(c.req.method)) {
|
|
@@ -15126,9 +15754,9 @@ function createConsoleRouter() {
|
|
|
15126
15754
|
console2.use("/api/*", authMiddleware());
|
|
15127
15755
|
console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
|
|
15128
15756
|
const serveIndex = (c) => {
|
|
15129
|
-
const indexFile =
|
|
15130
|
-
if (
|
|
15131
|
-
return c.html(
|
|
15757
|
+
const indexFile = join22(STATIC_DIR, "index.html");
|
|
15758
|
+
if (existsSync21(indexFile)) {
|
|
15759
|
+
return c.html(readFileSync21(indexFile, "utf-8"));
|
|
15132
15760
|
}
|
|
15133
15761
|
return c.html("<h1>AgentMoss Policy Console</h1><p>Frontend not built. Use /console/api/* endpoints.</p>");
|
|
15134
15762
|
};
|
|
@@ -15323,22 +15951,22 @@ function createConsoleRouter() {
|
|
|
15323
15951
|
if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
|
|
15324
15952
|
return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
|
|
15325
15953
|
}
|
|
15326
|
-
const userPath =
|
|
15954
|
+
const userPath = join22(dirname15(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
|
|
15327
15955
|
const builtinDir = resolveAssetDir(__dirname10, "skills");
|
|
15328
15956
|
const candidates = [
|
|
15329
15957
|
...isRuntimeConfigDisabled() ? [] : [userPath],
|
|
15330
|
-
builtinDir ?
|
|
15958
|
+
builtinDir ? join22(builtinDir, `${skillId}.md`) : ""
|
|
15331
15959
|
].filter(Boolean);
|
|
15332
15960
|
for (const p of candidates) {
|
|
15333
|
-
if (
|
|
15334
|
-
return c.json({ skill_id: skillId, path: p, content:
|
|
15961
|
+
if (existsSync21(p)) {
|
|
15962
|
+
return c.json({ skill_id: skillId, path: p, content: readFileSync21(p, "utf-8") });
|
|
15335
15963
|
}
|
|
15336
15964
|
}
|
|
15337
15965
|
return c.json({ detail: `skill ${skillId} \u4E0D\u5B58\u5728` }, 404);
|
|
15338
15966
|
});
|
|
15339
15967
|
console2.get("/api/agents", (c) => {
|
|
15340
15968
|
const rc = displayRuntimeConfig();
|
|
15341
|
-
return c.json({ agents:
|
|
15969
|
+
return c.json({ agents: scopedAgentRules(rc) });
|
|
15342
15970
|
});
|
|
15343
15971
|
console2.put("/api/agents/rules/enabled", async (c) => {
|
|
15344
15972
|
const b = await c.req.json();
|
|
@@ -15347,8 +15975,9 @@ function createConsoleRouter() {
|
|
|
15347
15975
|
if (b.pattern) fp.pattern = b.pattern;
|
|
15348
15976
|
if (b.keyword) fp.keyword = b.keyword;
|
|
15349
15977
|
if (b.path) fp.path = b.path;
|
|
15978
|
+
if (!isAllowed("agents", b.agent_id)) return c.json({ detail: `agent ${b.agent_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
|
|
15350
15979
|
const rc = updateAgentRuleEnabled(b.agent_id, b.category, fp, b.enabled);
|
|
15351
|
-
return c.json({ agents:
|
|
15980
|
+
return c.json({ agents: scopedAgentRules(rc) });
|
|
15352
15981
|
});
|
|
15353
15982
|
console2.post("/api/agents/rules", async (c) => {
|
|
15354
15983
|
const b = await c.req.json();
|
|
@@ -15356,8 +15985,9 @@ function createConsoleRouter() {
|
|
|
15356
15985
|
for (const [k, v] of Object.entries(b)) {
|
|
15357
15986
|
if (!["agent_id", "category"].includes(k) && v !== void 0 && v !== null) rule[k] = v;
|
|
15358
15987
|
}
|
|
15988
|
+
if (!isAllowed("agents", b.agent_id)) return c.json({ detail: `agent ${b.agent_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
|
|
15359
15989
|
const rc = addAgentRule(b.agent_id, b.category, rule);
|
|
15360
|
-
return c.json({ agents:
|
|
15990
|
+
return c.json({ agents: scopedAgentRules(rc) });
|
|
15361
15991
|
});
|
|
15362
15992
|
console2.delete("/api/agents/rules", async (c) => {
|
|
15363
15993
|
const b = await c.req.json();
|
|
@@ -15366,18 +15996,20 @@ function createConsoleRouter() {
|
|
|
15366
15996
|
if (b.pattern) fp.pattern = b.pattern;
|
|
15367
15997
|
if (b.keyword) fp.keyword = b.keyword;
|
|
15368
15998
|
if (b.path) fp.path = b.path;
|
|
15999
|
+
if (!isAllowed("agents", b.agent_id)) return c.json({ detail: `agent ${b.agent_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
|
|
15369
16000
|
const rc = deleteAgentRule(b.agent_id, b.category, fp);
|
|
15370
|
-
return c.json({ agents:
|
|
16001
|
+
return c.json({ agents: scopedAgentRules(rc) });
|
|
15371
16002
|
});
|
|
15372
16003
|
console2.put("/api/agents/categories/enabled", async (c) => {
|
|
15373
16004
|
const b = await c.req.json();
|
|
16005
|
+
if (!isAllowed("agents", b.agent_id)) return c.json({ detail: `agent ${b.agent_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
|
|
15374
16006
|
const rc = updateAgentCategoryEnabled(b.agent_id, b.category, b.enabled);
|
|
15375
|
-
return c.json({ agents:
|
|
16007
|
+
return c.json({ agents: scopedAgentRules(rc) });
|
|
15376
16008
|
});
|
|
15377
16009
|
const enabledScenarioIds = () => (process.env.AGENT_MOSS_SCENARIO || "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
15378
16010
|
console2.get("/api/scenarios", (c) => {
|
|
15379
|
-
const all =
|
|
15380
|
-
const enabled = enabledScenarioIds();
|
|
16011
|
+
const all = scopedScenarioRules(displayRuntimeConfig());
|
|
16012
|
+
const enabled = enabledScenarioIds().filter((sid) => isAllowed("scenarios", sid));
|
|
15381
16013
|
if (!enabled.length) return c.json({ scenarios: {}, enabled: [] });
|
|
15382
16014
|
const shown = {};
|
|
15383
16015
|
for (const sid of enabled) if (all[sid]) shown[sid] = all[sid];
|
|
@@ -15390,8 +16022,9 @@ function createConsoleRouter() {
|
|
|
15390
16022
|
if (b.pattern) fp.pattern = b.pattern;
|
|
15391
16023
|
if (b.keyword) fp.keyword = b.keyword;
|
|
15392
16024
|
if (b.path) fp.path = b.path;
|
|
16025
|
+
if (!isAllowed("scenarios", b.scenario_id)) return c.json({ detail: `scenario ${b.scenario_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
|
|
15393
16026
|
const rc = updateScenarioRuleEnabled(b.scenario_id, b.category, fp, b.enabled);
|
|
15394
|
-
return c.json({ scenarios:
|
|
16027
|
+
return c.json({ scenarios: scopedScenarioRules(rc), enabled: enabledScenarioIds().filter((sid) => isAllowed("scenarios", sid)) });
|
|
15395
16028
|
});
|
|
15396
16029
|
console2.post("/api/scenarios/rules", async (c) => {
|
|
15397
16030
|
const b = await c.req.json();
|
|
@@ -15399,8 +16032,9 @@ function createConsoleRouter() {
|
|
|
15399
16032
|
for (const [k, v] of Object.entries(b)) {
|
|
15400
16033
|
if (!["scenario_id", "category"].includes(k) && v !== void 0 && v !== null) rule[k] = v;
|
|
15401
16034
|
}
|
|
16035
|
+
if (!isAllowed("scenarios", b.scenario_id)) return c.json({ detail: `scenario ${b.scenario_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
|
|
15402
16036
|
const rc = addScenarioRule(b.scenario_id, b.category, rule);
|
|
15403
|
-
return c.json({ scenarios:
|
|
16037
|
+
return c.json({ scenarios: scopedScenarioRules(rc), enabled: enabledScenarioIds().filter((sid) => isAllowed("scenarios", sid)) });
|
|
15404
16038
|
});
|
|
15405
16039
|
console2.delete("/api/scenarios/rules", async (c) => {
|
|
15406
16040
|
const b = await c.req.json();
|
|
@@ -15409,13 +16043,15 @@ function createConsoleRouter() {
|
|
|
15409
16043
|
if (b.pattern) fp.pattern = b.pattern;
|
|
15410
16044
|
if (b.keyword) fp.keyword = b.keyword;
|
|
15411
16045
|
if (b.path) fp.path = b.path;
|
|
16046
|
+
if (!isAllowed("scenarios", b.scenario_id)) return c.json({ detail: `scenario ${b.scenario_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
|
|
15412
16047
|
const rc = deleteScenarioRule(b.scenario_id, b.category, fp);
|
|
15413
|
-
return c.json({ scenarios:
|
|
16048
|
+
return c.json({ scenarios: scopedScenarioRules(rc), enabled: enabledScenarioIds().filter((sid) => isAllowed("scenarios", sid)) });
|
|
15414
16049
|
});
|
|
15415
16050
|
console2.put("/api/scenarios/categories/enabled", async (c) => {
|
|
15416
16051
|
const b = await c.req.json();
|
|
16052
|
+
if (!isAllowed("scenarios", b.scenario_id)) return c.json({ detail: `scenario ${b.scenario_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
|
|
15417
16053
|
const rc = updateScenarioCategoryEnabled(b.scenario_id, b.category, b.enabled);
|
|
15418
|
-
return c.json({ scenarios:
|
|
16054
|
+
return c.json({ scenarios: scopedScenarioRules(rc), enabled: enabledScenarioIds().filter((sid) => isAllowed("scenarios", sid)) });
|
|
15419
16055
|
});
|
|
15420
16056
|
console2.get("/api/config", (c) => {
|
|
15421
16057
|
const rc = displayRuntimeConfig();
|
|
@@ -15428,7 +16064,7 @@ function createConsoleRouter() {
|
|
|
15428
16064
|
const defaults = generateSourceDefaults();
|
|
15429
16065
|
try {
|
|
15430
16066
|
const p = getRuntimeConfigPath();
|
|
15431
|
-
if (
|
|
16067
|
+
if (existsSync21(p)) unlinkSync6(p);
|
|
15432
16068
|
} catch {
|
|
15433
16069
|
}
|
|
15434
16070
|
return c.json(withL22View(defaults));
|
|
@@ -15487,7 +16123,7 @@ function logDeploymentSelfCheck() {
|
|
|
15487
16123
|
console.log("\u5C42\u7EA7\u5F00\u5173: " + layerKeys.map((k) => `${k}=${isLayerEnabled(k) ? "on" : "OFF"}`).join(" "));
|
|
15488
16124
|
if (!builtinOnly) {
|
|
15489
16125
|
try {
|
|
15490
|
-
const dirs = rulesDirs().filter((d) =>
|
|
16126
|
+
const dirs = rulesDirs().filter((d) => existsSync22(d));
|
|
15491
16127
|
if (dirs.length > 0) {
|
|
15492
16128
|
console.log(`\u89C4\u5219\u76EE\u5F55: ${dirs.join(", ")}\uFF08\u53EA\u8BFB\u5176\u4E2D ${OVERRIDE_FILENAME} / ${EXTRA_FILENAME}\uFF09`);
|
|
15493
16129
|
}
|
|
@@ -15624,9 +16260,29 @@ function createApp() {
|
|
|
15624
16260
|
if (!okAuth && !isPublicPage) {
|
|
15625
16261
|
return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
|
|
15626
16262
|
}
|
|
16263
|
+
let gateCallId = null;
|
|
16264
|
+
const gateRequired = c.req.header(GATE_IDENTITY_HEADER);
|
|
16265
|
+
const gatePath = path9.replace(/\/+$/, "");
|
|
16266
|
+
if (method === "POST" && gateRequired !== void 0 && (gatePath === "/api/v1/analyze" || gatePath === "/api/v1/review")) {
|
|
16267
|
+
if (principal !== GATE_PRINCIPAL) {
|
|
16268
|
+
return c.json({ detail: "AgentGate \u4E13\u7528\u8EAB\u4EFD\u6821\u9A8C\u5931\u8D25" }, 403);
|
|
16269
|
+
}
|
|
16270
|
+
if (gateRequired !== "1") {
|
|
16271
|
+
return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
|
|
16272
|
+
}
|
|
16273
|
+
}
|
|
16274
|
+
if (method === "POST" && gatePath === "/api/v1/analyze" && principal === GATE_PRINCIPAL) {
|
|
16275
|
+
const id = c.req.header(GATE_CALL_ID_HEADER) || "";
|
|
16276
|
+
if (gateRequired !== "1" || !validGateCallId(id)) {
|
|
16277
|
+
return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
|
|
16278
|
+
}
|
|
16279
|
+
gateCallId = id;
|
|
16280
|
+
c.set("gateCallId", id);
|
|
16281
|
+
}
|
|
15627
16282
|
if (limiter.enabled && path9.startsWith("/api/")) {
|
|
15628
16283
|
const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
|
|
15629
16284
|
if (!limiter.allow(key)) {
|
|
16285
|
+
if (gateCallId) c.header(GATE_RATE_LIMIT_HEADER, gateCallId);
|
|
15630
16286
|
return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
|
|
15631
16287
|
}
|
|
15632
16288
|
}
|
|
@@ -15642,6 +16298,7 @@ function createApp() {
|
|
|
15642
16298
|
const busy = (detail, status = 503) => {
|
|
15643
16299
|
c.header("Retry-After", "1");
|
|
15644
16300
|
c.header("Connection", "close");
|
|
16301
|
+
if (gateCallId) c.header(GATE_BUSY_HEADER, gateCallId);
|
|
15645
16302
|
return c.json({ detail }, status);
|
|
15646
16303
|
};
|
|
15647
16304
|
try {
|
|
@@ -15709,12 +16366,12 @@ function createApp() {
|
|
|
15709
16366
|
}
|
|
15710
16367
|
async function findFreePort(startPort, host = "127.0.0.1", scan = 100) {
|
|
15711
16368
|
for (let port = startPort; port < startPort + scan; port++) {
|
|
15712
|
-
const free = await new Promise((
|
|
16369
|
+
const free = await new Promise((resolve13) => {
|
|
15713
16370
|
const server = net.createServer();
|
|
15714
16371
|
server.listen(port, host, () => {
|
|
15715
|
-
server.close(() =>
|
|
16372
|
+
server.close(() => resolve13(true));
|
|
15716
16373
|
});
|
|
15717
|
-
server.on("error", () =>
|
|
16374
|
+
server.on("error", () => resolve13(false));
|
|
15718
16375
|
});
|
|
15719
16376
|
if (free) {
|
|
15720
16377
|
if (port !== startPort) {
|
|
@@ -15759,7 +16416,7 @@ async function warmUpEngine() {
|
|
|
15759
16416
|
function writePortFile(port) {
|
|
15760
16417
|
try {
|
|
15761
16418
|
const path9 = getPortFilePath();
|
|
15762
|
-
mkdirSync10(
|
|
16419
|
+
mkdirSync10(dirname16(path9), { recursive: true });
|
|
15763
16420
|
const payload = JSON.stringify({
|
|
15764
16421
|
port,
|
|
15765
16422
|
pid: process.pid,
|
|
@@ -15805,29 +16462,29 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
|
|
|
15805
16462
|
socketPath,
|
|
15806
16463
|
close: async () => {
|
|
15807
16464
|
if (!server) return;
|
|
15808
|
-
await new Promise((
|
|
15809
|
-
server.close(() =>
|
|
16465
|
+
await new Promise((resolve13) => {
|
|
16466
|
+
server.close(() => resolve13());
|
|
15810
16467
|
});
|
|
15811
16468
|
server = null;
|
|
15812
16469
|
},
|
|
15813
16470
|
serve: async () => {
|
|
15814
16471
|
failFastOnAuthError();
|
|
15815
|
-
const { mkdirSync: mkdirSync11, existsSync:
|
|
15816
|
-
const { dirname:
|
|
15817
|
-
const dir =
|
|
16472
|
+
const { mkdirSync: mkdirSync11, existsSync: existsSync23, unlinkSync: unlinkSync7 } = await import("fs");
|
|
16473
|
+
const { dirname: dirname17 } = await import("path");
|
|
16474
|
+
const dir = dirname17(socketPath);
|
|
15818
16475
|
if (dir) {
|
|
15819
16476
|
try {
|
|
15820
16477
|
mkdirSync11(dir, { recursive: true });
|
|
15821
16478
|
} catch {
|
|
15822
16479
|
}
|
|
15823
16480
|
}
|
|
15824
|
-
if (
|
|
16481
|
+
if (existsSync23(socketPath)) {
|
|
15825
16482
|
const { connect } = await import("net");
|
|
15826
|
-
const inUse = await new Promise((
|
|
16483
|
+
const inUse = await new Promise((resolve13) => {
|
|
15827
16484
|
const probe = connect(socketPath);
|
|
15828
16485
|
const done = (v) => {
|
|
15829
16486
|
probe.destroy();
|
|
15830
|
-
|
|
16487
|
+
resolve13(v);
|
|
15831
16488
|
};
|
|
15832
16489
|
probe.once("connect", () => done(true));
|
|
15833
16490
|
probe.once("error", () => done(false));
|
|
@@ -15855,9 +16512,9 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
|
|
|
15855
16512
|
server.keepAliveTimeout = keepAliveSec() * 1e3;
|
|
15856
16513
|
} catch {
|
|
15857
16514
|
}
|
|
15858
|
-
await new Promise((
|
|
16515
|
+
await new Promise((resolve13, reject) => {
|
|
15859
16516
|
server.once("error", reject);
|
|
15860
|
-
server.listen(socketPath, () =>
|
|
16517
|
+
server.listen(socketPath, () => resolve13());
|
|
15861
16518
|
});
|
|
15862
16519
|
try {
|
|
15863
16520
|
const { chmodSync: chmodSync2 } = await import("fs");
|