@kenhkl/agent-moss 0.17.18 → 0.17.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +133 -51
- package/dist/engine/coordinator.js +130 -48
- package/dist/server.js +133 -51
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -4916,6 +4916,9 @@ function stripHeredocContent(actionDetail) {
|
|
|
4916
4916
|
);
|
|
4917
4917
|
}
|
|
4918
4918
|
function normalizePathSegments(text, foldQuotes = false) {
|
|
4919
|
+
if (!text.includes("//") && !text.includes("/./") && !text.includes("Q") && !text.includes("PROT")) {
|
|
4920
|
+
return text;
|
|
4921
|
+
}
|
|
4919
4922
|
const protTokens = [];
|
|
4920
4923
|
let t = text.replace(/\b(https?|ftp|file):\/\//gi, (m) => {
|
|
4921
4924
|
const scheme = m.slice(0, m.indexOf(":"));
|
|
@@ -4946,43 +4949,24 @@ function pathScanVariants(actionDetailLower) {
|
|
|
4946
4949
|
}
|
|
4947
4950
|
function splitCommandSegments2(actionDetail) {
|
|
4948
4951
|
const segments = [];
|
|
4949
|
-
let
|
|
4950
|
-
let
|
|
4951
|
-
|
|
4952
|
-
|
|
4953
|
-
|
|
4954
|
-
|
|
4955
|
-
|
|
4956
|
-
|
|
4957
|
-
|
|
4958
|
-
|
|
4959
|
-
|
|
4960
|
-
cur += ch;
|
|
4961
|
-
continue;
|
|
4962
|
-
}
|
|
4963
|
-
if (ch === ";" || ch === "\n") {
|
|
4964
|
-
segments.push(cur);
|
|
4965
|
-
segments.push(ch);
|
|
4966
|
-
cur = "";
|
|
4967
|
-
continue;
|
|
4968
|
-
}
|
|
4969
|
-
if (ch === "&" && actionDetail[i + 1] === "&") {
|
|
4970
|
-
segments.push(cur);
|
|
4971
|
-
segments.push("&&");
|
|
4972
|
-
cur = "";
|
|
4973
|
-
i++;
|
|
4974
|
-
continue;
|
|
4975
|
-
}
|
|
4976
|
-
if (ch === "|" && actionDetail[i + 1] === "|") {
|
|
4977
|
-
segments.push(cur);
|
|
4978
|
-
segments.push("||");
|
|
4979
|
-
cur = "";
|
|
4980
|
-
i++;
|
|
4952
|
+
let start = 0;
|
|
4953
|
+
let cursor = 0;
|
|
4954
|
+
while (true) {
|
|
4955
|
+
COMMAND_SEGMENT_TOKEN_RE.lastIndex = cursor;
|
|
4956
|
+
const match = COMMAND_SEGMENT_TOKEN_RE.exec(actionDetail);
|
|
4957
|
+
if (!match) break;
|
|
4958
|
+
const token = match[0];
|
|
4959
|
+
if (token === "'" || token === '"') {
|
|
4960
|
+
const end = actionDetail.indexOf(token, match.index + 1);
|
|
4961
|
+
if (end < 0) break;
|
|
4962
|
+
cursor = end + 1;
|
|
4981
4963
|
continue;
|
|
4982
4964
|
}
|
|
4983
|
-
|
|
4965
|
+
segments.push(actionDetail.slice(start, match.index));
|
|
4966
|
+
segments.push(token);
|
|
4967
|
+
start = cursor = match.index + token.length;
|
|
4984
4968
|
}
|
|
4985
|
-
if (
|
|
4969
|
+
if (start < actionDetail.length) segments.push(actionDetail.slice(start));
|
|
4986
4970
|
return segments;
|
|
4987
4971
|
}
|
|
4988
4972
|
function severityRank(s) {
|
|
@@ -5427,7 +5411,7 @@ function checkLateralMovement(actionDetail) {
|
|
|
5427
5411
|
}
|
|
5428
5412
|
return null;
|
|
5429
5413
|
}
|
|
5430
|
-
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, 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, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
5414
|
+
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, 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, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
5431
5415
|
var init_heuristic = __esm({
|
|
5432
5416
|
"src/engine/heuristic.ts"() {
|
|
5433
5417
|
"use strict";
|
|
@@ -5468,6 +5452,7 @@ var init_heuristic = __esm({
|
|
|
5468
5452
|
"\\bpasswd\\s+--stdin\\b",
|
|
5469
5453
|
"\\bchpasswd\\b"
|
|
5470
5454
|
]);
|
|
5455
|
+
COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
|
|
5471
5456
|
SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
|
|
5472
5457
|
SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
|
|
5473
5458
|
SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
|
|
@@ -7782,6 +7767,7 @@ var init_token_stats = __esm({
|
|
|
7782
7767
|
});
|
|
7783
7768
|
|
|
7784
7769
|
// src/engine/llm-analyzer.ts
|
|
7770
|
+
import { createHash as createHash3 } from "crypto";
|
|
7785
7771
|
import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
|
|
7786
7772
|
import OpenAI from "openai";
|
|
7787
7773
|
async function runLLMAnalysis(input, previous) {
|
|
@@ -7808,7 +7794,7 @@ async function runLLMAnalysis(input, previous) {
|
|
|
7808
7794
|
}
|
|
7809
7795
|
const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
|
|
7810
7796
|
const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
|
|
7811
|
-
const cacheKey = `${input.aNext.actionType}:${rawDetail || input.aNext.actionDetail}`;
|
|
7797
|
+
const cacheKey = `${input.aNext.actionType}:${createHash3("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
|
|
7812
7798
|
const cached2 = llmCache.get(cacheKey);
|
|
7813
7799
|
if (cached2) {
|
|
7814
7800
|
console.log("[AgentMoss] LLM cache hit");
|
|
@@ -7823,7 +7809,48 @@ async function runLLMAnalysis(input, previous) {
|
|
|
7823
7809
|
} else {
|
|
7824
7810
|
scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
|
|
7825
7811
|
}
|
|
7826
|
-
const
|
|
7812
|
+
const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
|
|
7813
|
+
let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
|
|
7814
|
+
let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
|
|
7815
|
+
let prompt = "";
|
|
7816
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
7817
|
+
prompt = buildPrompt(
|
|
7818
|
+
input,
|
|
7819
|
+
previous,
|
|
7820
|
+
matchedSkills,
|
|
7821
|
+
templates,
|
|
7822
|
+
scriptAnalysis,
|
|
7823
|
+
previous.skipL3Hints ?? "",
|
|
7824
|
+
scriptChainText,
|
|
7825
|
+
previous.pathContext ?? "",
|
|
7826
|
+
historyMaxItems,
|
|
7827
|
+
historyMaxChars
|
|
7828
|
+
);
|
|
7829
|
+
if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
|
|
7830
|
+
historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
|
|
7831
|
+
historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
|
|
7832
|
+
}
|
|
7833
|
+
if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
|
|
7834
|
+
const estimated = estimateTokens(prompt);
|
|
7835
|
+
const ratio = estimated / maxPromptTokens;
|
|
7836
|
+
const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
|
|
7837
|
+
const truncated = truncateDetail(input.aNext.actionDetail, allowed);
|
|
7838
|
+
prompt = buildPrompt(
|
|
7839
|
+
{ ...input, aNext: { ...input.aNext, actionDetail: truncated } },
|
|
7840
|
+
previous,
|
|
7841
|
+
matchedSkills,
|
|
7842
|
+
templates,
|
|
7843
|
+
scriptAnalysis,
|
|
7844
|
+
previous.skipL3Hints ?? "",
|
|
7845
|
+
scriptChainText,
|
|
7846
|
+
previous.pathContext ?? "",
|
|
7847
|
+
historyMaxItems,
|
|
7848
|
+
historyMaxChars
|
|
7849
|
+
);
|
|
7850
|
+
console.warn(
|
|
7851
|
+
`[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${maxPromptTokens}\uFF09\uFF0C\u5F53\u524D\u52A8\u4F5C\u8BE6\u60C5\u622A\u65AD\u81F3 ${truncated.length} \u5B57\u7B26`
|
|
7852
|
+
);
|
|
7853
|
+
}
|
|
7827
7854
|
logPrompt(prompt, input.aNext, previous.llmLogPath);
|
|
7828
7855
|
const result = await analyzeWithLLM(prompt, config);
|
|
7829
7856
|
if (llmCache.size >= LLM_CACHE_MAX) {
|
|
@@ -7858,9 +7885,39 @@ ${prompt}
|
|
|
7858
7885
|
console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
|
|
7859
7886
|
}
|
|
7860
7887
|
}
|
|
7861
|
-
function
|
|
7888
|
+
function getNumSetting(key, def) {
|
|
7889
|
+
const v = parseInt(getAgentMossSetting(key, String(def)), 10);
|
|
7890
|
+
return Number.isFinite(v) ? v : def;
|
|
7891
|
+
}
|
|
7892
|
+
function truncateDetail(detail, maxChars) {
|
|
7893
|
+
if (maxChars <= 0 || detail.length <= maxChars) return detail;
|
|
7894
|
+
const head = Math.max(1, Math.floor(maxChars * 0.6));
|
|
7895
|
+
const tail = Math.max(0, maxChars - head);
|
|
7896
|
+
const omitted = detail.length - maxChars;
|
|
7897
|
+
return `${detail.slice(0, head)}...[\u7701\u7565 ${omitted} \u5B57\u7B26]...${tail ? detail.slice(-tail) : ""}`;
|
|
7898
|
+
}
|
|
7899
|
+
function estimateTokens(text) {
|
|
7900
|
+
return Math.floor(text.length / 2.5) + 1;
|
|
7901
|
+
}
|
|
7902
|
+
function formatActionHistory(history, maxItems, maxChars) {
|
|
7903
|
+
if (!history.length) return "(\u65E0\u5386\u53F2\u64CD\u4F5C)";
|
|
7904
|
+
let items = history;
|
|
7905
|
+
let omitted = 0;
|
|
7906
|
+
if (maxItems > 0 && history.length > maxItems) {
|
|
7907
|
+
omitted = history.length - maxItems;
|
|
7908
|
+
items = history.slice(-maxItems);
|
|
7909
|
+
}
|
|
7910
|
+
const lines = [];
|
|
7911
|
+
if (omitted) lines.push(`\uFF08\u66F4\u65E9\u7684 ${omitted} \u6761\u5386\u53F2\u52A8\u4F5C\u5DF2\u7701\u7565\uFF09`);
|
|
7912
|
+
items.forEach((h, i) => {
|
|
7913
|
+
const detail = truncateDetail(h.actionDetail || "", maxChars);
|
|
7914
|
+
lines.push(detail ? `${i + 1}. ${h.actionType}: ${detail}` : `${i + 1}. ${h.actionType}`);
|
|
7915
|
+
});
|
|
7916
|
+
return lines.join("\n");
|
|
7917
|
+
}
|
|
7918
|
+
function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis, skipL3Hints = "", scriptChainText = "", pathContext = "", historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20), historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500)) {
|
|
7862
7919
|
const skillsText = formatSkillsForPrompt(matchedSkills);
|
|
7863
|
-
const historyStr = input.actionHistory
|
|
7920
|
+
const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
|
|
7864
7921
|
const promptHistoryText = formatPromptHistory(input.promptHistory);
|
|
7865
7922
|
const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
|
|
7866
7923
|
const hintsText = formatHints(previous);
|
|
@@ -7973,23 +8030,44 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7973
8030
|
],
|
|
7974
8031
|
signal: abortController.signal
|
|
7975
8032
|
});
|
|
7976
|
-
const
|
|
8033
|
+
const message = response.choices[0]?.message;
|
|
8034
|
+
const content = message?.content ?? "";
|
|
8035
|
+
const finishReason = response.choices[0]?.finish_reason;
|
|
8036
|
+
const reasoningLen = typeof message?.reasoning_content === "string" ? message.reasoning_content.length : 0;
|
|
8037
|
+
const usage = response.usage;
|
|
8038
|
+
if (!content) {
|
|
8039
|
+
const detail = `model=${response.model || config.model} finish_reason=${finishReason} content_len=0 reasoning_len=${reasoningLen} message_keys=${message ? Object.keys(message).join(",") : "(none)"} tokens=${usage?.prompt_tokens ?? "?"}/${usage?.completion_tokens ?? "?"}`;
|
|
8040
|
+
if (finishReason === "length") {
|
|
8041
|
+
console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
|
|
8042
|
+
throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
|
|
8043
|
+
}
|
|
8044
|
+
console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
|
|
8045
|
+
throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
|
|
8046
|
+
}
|
|
7977
8047
|
console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
|
|
7978
8048
|
let jsonStr = content.trim();
|
|
7979
8049
|
if (jsonStr.startsWith("```")) {
|
|
7980
8050
|
jsonStr = jsonStr.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "");
|
|
7981
8051
|
}
|
|
7982
|
-
|
|
8052
|
+
let parsed;
|
|
8053
|
+
try {
|
|
8054
|
+
parsed = JSON.parse(jsonStr);
|
|
8055
|
+
} catch (parseErr) {
|
|
8056
|
+
console.error(
|
|
8057
|
+
`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u89E3\u6790\u5931\u8D25: ${parseErr.message} | \u539F\u59CB\u524D 300 \u5B57\u7B26: ${content.substring(0, 300)}`
|
|
8058
|
+
);
|
|
8059
|
+
throw parseErr;
|
|
8060
|
+
}
|
|
7983
8061
|
try {
|
|
7984
|
-
const
|
|
8062
|
+
const usage2 = response.usage;
|
|
7985
8063
|
const { recordTokenUsage: recordTokenUsage2 } = await Promise.resolve().then(() => (init_token_stats(), token_stats_exports));
|
|
7986
8064
|
recordTokenUsage2({
|
|
7987
8065
|
sessionId: "audit",
|
|
7988
8066
|
step: "L3_security_judge",
|
|
7989
8067
|
model: response.model || config.model,
|
|
7990
|
-
promptTokens:
|
|
7991
|
-
completionTokens:
|
|
7992
|
-
totalTokens:
|
|
8068
|
+
promptTokens: usage2?.prompt_tokens || 0,
|
|
8069
|
+
completionTokens: usage2?.completion_tokens || 0,
|
|
8070
|
+
totalTokens: usage2?.total_tokens || 0
|
|
7993
8071
|
});
|
|
7994
8072
|
} catch {
|
|
7995
8073
|
}
|
|
@@ -8010,12 +8088,16 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
8010
8088
|
console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
|
|
8011
8089
|
break;
|
|
8012
8090
|
}
|
|
8091
|
+
const errObj = err;
|
|
8092
|
+
const status = errObj?.status ?? errObj?.statusCode;
|
|
8093
|
+
const body = errObj?.error ?? errObj?.body;
|
|
8094
|
+
const detail = status !== void 0 || body !== void 0 ? `${err.message} status=${status} body=${String(JSON.stringify(body)).slice(0, 300)}` : err.message;
|
|
8013
8095
|
if (attempt < maxRetries) {
|
|
8014
|
-
console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s
|
|
8096
|
+
console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
|
|
8015
8097
|
await new Promise((resolve12) => setTimeout(resolve12, retryCfg.retryInterval * 1e3));
|
|
8016
8098
|
} else {
|
|
8017
8099
|
clearTimeout(totalTimeoutTimer);
|
|
8018
|
-
console.error(
|
|
8100
|
+
console.error(`[AgentMoss] LLM call failed after all retries: ${detail}`);
|
|
8019
8101
|
throw new Error(`LLM \u5206\u6790\u5931\u8D25 (${maxRetries + 1} \u6B21\u5C1D\u8BD5): ${err.message}`);
|
|
8020
8102
|
}
|
|
8021
8103
|
}
|
|
@@ -10996,10 +11078,10 @@ var init_stateful = __esm({
|
|
|
10996
11078
|
import * as fs4 from "fs";
|
|
10997
11079
|
import * as os2 from "os";
|
|
10998
11080
|
import * as path4 from "path";
|
|
10999
|
-
import { createHash as
|
|
11081
|
+
import { createHash as createHash4 } from "crypto";
|
|
11000
11082
|
function defaultStateDbPath() {
|
|
11001
11083
|
const dir = process.env.AGENT_MOSS_STATE_DIR || path4.join(os2.homedir(), ".agentmoss");
|
|
11002
|
-
const tag =
|
|
11084
|
+
const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
|
|
11003
11085
|
return path4.join(dir, `stateful_chains_${tag}.json`);
|
|
11004
11086
|
}
|
|
11005
11087
|
var ChainStateStore;
|
|
@@ -11586,7 +11668,7 @@ var init_coordinator = __esm({
|
|
|
11586
11668
|
});
|
|
11587
11669
|
|
|
11588
11670
|
// src/infra/policy-cache.ts
|
|
11589
|
-
import { createHash as
|
|
11671
|
+
import { createHash as createHash5 } from "crypto";
|
|
11590
11672
|
import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync3 } from "fs";
|
|
11591
11673
|
import { tmpdir as tmpdir3 } from "os";
|
|
11592
11674
|
import { join as join16 } from "path";
|
|
@@ -11631,7 +11713,7 @@ var init_policy_cache = __esm({
|
|
|
11631
11713
|
return `${sessionId}::${promptSession}`;
|
|
11632
11714
|
}
|
|
11633
11715
|
cacheFilePath(sessionId, promptSession) {
|
|
11634
|
-
const promptHash =
|
|
11716
|
+
const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
|
|
11635
11717
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
11636
11718
|
return join16(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
|
|
11637
11719
|
}
|
|
@@ -4086,6 +4086,9 @@ function stripHeredocContent(actionDetail) {
|
|
|
4086
4086
|
);
|
|
4087
4087
|
}
|
|
4088
4088
|
function normalizePathSegments(text, foldQuotes = false) {
|
|
4089
|
+
if (!text.includes("//") && !text.includes("/./") && !text.includes("Q") && !text.includes("PROT")) {
|
|
4090
|
+
return text;
|
|
4091
|
+
}
|
|
4089
4092
|
const protTokens = [];
|
|
4090
4093
|
let t = text.replace(/\b(https?|ftp|file):\/\//gi, (m) => {
|
|
4091
4094
|
const scheme = m.slice(0, m.indexOf(":"));
|
|
@@ -4116,43 +4119,24 @@ function pathScanVariants(actionDetailLower) {
|
|
|
4116
4119
|
}
|
|
4117
4120
|
function splitCommandSegments2(actionDetail) {
|
|
4118
4121
|
const segments = [];
|
|
4119
|
-
let
|
|
4120
|
-
let
|
|
4121
|
-
|
|
4122
|
-
|
|
4123
|
-
|
|
4124
|
-
|
|
4125
|
-
|
|
4126
|
-
|
|
4127
|
-
|
|
4128
|
-
|
|
4129
|
-
|
|
4130
|
-
cur += ch;
|
|
4131
|
-
continue;
|
|
4132
|
-
}
|
|
4133
|
-
if (ch === ";" || ch === "\n") {
|
|
4134
|
-
segments.push(cur);
|
|
4135
|
-
segments.push(ch);
|
|
4136
|
-
cur = "";
|
|
4137
|
-
continue;
|
|
4138
|
-
}
|
|
4139
|
-
if (ch === "&" && actionDetail[i + 1] === "&") {
|
|
4140
|
-
segments.push(cur);
|
|
4141
|
-
segments.push("&&");
|
|
4142
|
-
cur = "";
|
|
4143
|
-
i++;
|
|
4144
|
-
continue;
|
|
4145
|
-
}
|
|
4146
|
-
if (ch === "|" && actionDetail[i + 1] === "|") {
|
|
4147
|
-
segments.push(cur);
|
|
4148
|
-
segments.push("||");
|
|
4149
|
-
cur = "";
|
|
4150
|
-
i++;
|
|
4122
|
+
let start = 0;
|
|
4123
|
+
let cursor = 0;
|
|
4124
|
+
while (true) {
|
|
4125
|
+
COMMAND_SEGMENT_TOKEN_RE.lastIndex = cursor;
|
|
4126
|
+
const match = COMMAND_SEGMENT_TOKEN_RE.exec(actionDetail);
|
|
4127
|
+
if (!match) break;
|
|
4128
|
+
const token = match[0];
|
|
4129
|
+
if (token === "'" || token === '"') {
|
|
4130
|
+
const end = actionDetail.indexOf(token, match.index + 1);
|
|
4131
|
+
if (end < 0) break;
|
|
4132
|
+
cursor = end + 1;
|
|
4151
4133
|
continue;
|
|
4152
4134
|
}
|
|
4153
|
-
|
|
4135
|
+
segments.push(actionDetail.slice(start, match.index));
|
|
4136
|
+
segments.push(token);
|
|
4137
|
+
start = cursor = match.index + token.length;
|
|
4154
4138
|
}
|
|
4155
|
-
if (
|
|
4139
|
+
if (start < actionDetail.length) segments.push(actionDetail.slice(start));
|
|
4156
4140
|
return segments;
|
|
4157
4141
|
}
|
|
4158
4142
|
function severityRank(s) {
|
|
@@ -4597,7 +4581,7 @@ function checkLateralMovement(actionDetail) {
|
|
|
4597
4581
|
}
|
|
4598
4582
|
return null;
|
|
4599
4583
|
}
|
|
4600
|
-
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, 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, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
4584
|
+
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, 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, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
4601
4585
|
var init_heuristic = __esm({
|
|
4602
4586
|
"src/engine/heuristic.ts"() {
|
|
4603
4587
|
"use strict";
|
|
@@ -4638,6 +4622,7 @@ var init_heuristic = __esm({
|
|
|
4638
4622
|
"\\bpasswd\\s+--stdin\\b",
|
|
4639
4623
|
"\\bchpasswd\\b"
|
|
4640
4624
|
]);
|
|
4625
|
+
COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
|
|
4641
4626
|
SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
|
|
4642
4627
|
SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
|
|
4643
4628
|
SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
|
|
@@ -4831,6 +4816,7 @@ init_inline_analyzer();
|
|
|
4831
4816
|
|
|
4832
4817
|
// src/engine/llm-analyzer.ts
|
|
4833
4818
|
init_esm_shims();
|
|
4819
|
+
import { createHash } from "crypto";
|
|
4834
4820
|
|
|
4835
4821
|
// src/infra/security-policy.ts
|
|
4836
4822
|
init_esm_shims();
|
|
@@ -7048,7 +7034,7 @@ async function runLLMAnalysis(input, previous) {
|
|
|
7048
7034
|
}
|
|
7049
7035
|
const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
|
|
7050
7036
|
const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
|
|
7051
|
-
const cacheKey = `${input.aNext.actionType}:${rawDetail || input.aNext.actionDetail}`;
|
|
7037
|
+
const cacheKey = `${input.aNext.actionType}:${createHash("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
|
|
7052
7038
|
const cached2 = llmCache.get(cacheKey);
|
|
7053
7039
|
if (cached2) {
|
|
7054
7040
|
console.log("[AgentMoss] LLM cache hit");
|
|
@@ -7063,7 +7049,48 @@ async function runLLMAnalysis(input, previous) {
|
|
|
7063
7049
|
} else {
|
|
7064
7050
|
scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
|
|
7065
7051
|
}
|
|
7066
|
-
const
|
|
7052
|
+
const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
|
|
7053
|
+
let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
|
|
7054
|
+
let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
|
|
7055
|
+
let prompt = "";
|
|
7056
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
7057
|
+
prompt = buildPrompt(
|
|
7058
|
+
input,
|
|
7059
|
+
previous,
|
|
7060
|
+
matchedSkills,
|
|
7061
|
+
templates,
|
|
7062
|
+
scriptAnalysis,
|
|
7063
|
+
previous.skipL3Hints ?? "",
|
|
7064
|
+
scriptChainText,
|
|
7065
|
+
previous.pathContext ?? "",
|
|
7066
|
+
historyMaxItems,
|
|
7067
|
+
historyMaxChars
|
|
7068
|
+
);
|
|
7069
|
+
if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
|
|
7070
|
+
historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
|
|
7071
|
+
historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
|
|
7072
|
+
}
|
|
7073
|
+
if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
|
|
7074
|
+
const estimated = estimateTokens(prompt);
|
|
7075
|
+
const ratio = estimated / maxPromptTokens;
|
|
7076
|
+
const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
|
|
7077
|
+
const truncated = truncateDetail(input.aNext.actionDetail, allowed);
|
|
7078
|
+
prompt = buildPrompt(
|
|
7079
|
+
{ ...input, aNext: { ...input.aNext, actionDetail: truncated } },
|
|
7080
|
+
previous,
|
|
7081
|
+
matchedSkills,
|
|
7082
|
+
templates,
|
|
7083
|
+
scriptAnalysis,
|
|
7084
|
+
previous.skipL3Hints ?? "",
|
|
7085
|
+
scriptChainText,
|
|
7086
|
+
previous.pathContext ?? "",
|
|
7087
|
+
historyMaxItems,
|
|
7088
|
+
historyMaxChars
|
|
7089
|
+
);
|
|
7090
|
+
console.warn(
|
|
7091
|
+
`[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${maxPromptTokens}\uFF09\uFF0C\u5F53\u524D\u52A8\u4F5C\u8BE6\u60C5\u622A\u65AD\u81F3 ${truncated.length} \u5B57\u7B26`
|
|
7092
|
+
);
|
|
7093
|
+
}
|
|
7067
7094
|
logPrompt(prompt, input.aNext, previous.llmLogPath);
|
|
7068
7095
|
const result = await analyzeWithLLM(prompt, config);
|
|
7069
7096
|
if (llmCache.size >= LLM_CACHE_MAX) {
|
|
@@ -7098,9 +7125,39 @@ ${prompt}
|
|
|
7098
7125
|
console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
|
|
7099
7126
|
}
|
|
7100
7127
|
}
|
|
7101
|
-
function
|
|
7128
|
+
function getNumSetting(key, def) {
|
|
7129
|
+
const v = parseInt(getAgentMossSetting(key, String(def)), 10);
|
|
7130
|
+
return Number.isFinite(v) ? v : def;
|
|
7131
|
+
}
|
|
7132
|
+
function truncateDetail(detail, maxChars) {
|
|
7133
|
+
if (maxChars <= 0 || detail.length <= maxChars) return detail;
|
|
7134
|
+
const head = Math.max(1, Math.floor(maxChars * 0.6));
|
|
7135
|
+
const tail = Math.max(0, maxChars - head);
|
|
7136
|
+
const omitted = detail.length - maxChars;
|
|
7137
|
+
return `${detail.slice(0, head)}...[\u7701\u7565 ${omitted} \u5B57\u7B26]...${tail ? detail.slice(-tail) : ""}`;
|
|
7138
|
+
}
|
|
7139
|
+
function estimateTokens(text) {
|
|
7140
|
+
return Math.floor(text.length / 2.5) + 1;
|
|
7141
|
+
}
|
|
7142
|
+
function formatActionHistory(history, maxItems, maxChars) {
|
|
7143
|
+
if (!history.length) return "(\u65E0\u5386\u53F2\u64CD\u4F5C)";
|
|
7144
|
+
let items = history;
|
|
7145
|
+
let omitted = 0;
|
|
7146
|
+
if (maxItems > 0 && history.length > maxItems) {
|
|
7147
|
+
omitted = history.length - maxItems;
|
|
7148
|
+
items = history.slice(-maxItems);
|
|
7149
|
+
}
|
|
7150
|
+
const lines = [];
|
|
7151
|
+
if (omitted) lines.push(`\uFF08\u66F4\u65E9\u7684 ${omitted} \u6761\u5386\u53F2\u52A8\u4F5C\u5DF2\u7701\u7565\uFF09`);
|
|
7152
|
+
items.forEach((h, i) => {
|
|
7153
|
+
const detail = truncateDetail(h.actionDetail || "", maxChars);
|
|
7154
|
+
lines.push(detail ? `${i + 1}. ${h.actionType}: ${detail}` : `${i + 1}. ${h.actionType}`);
|
|
7155
|
+
});
|
|
7156
|
+
return lines.join("\n");
|
|
7157
|
+
}
|
|
7158
|
+
function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis, skipL3Hints = "", scriptChainText = "", pathContext = "", historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20), historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500)) {
|
|
7102
7159
|
const skillsText = formatSkillsForPrompt(matchedSkills);
|
|
7103
|
-
const historyStr = input.actionHistory
|
|
7160
|
+
const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
|
|
7104
7161
|
const promptHistoryText = formatPromptHistory(input.promptHistory);
|
|
7105
7162
|
const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
|
|
7106
7163
|
const hintsText = formatHints(previous);
|
|
@@ -7213,23 +7270,44 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7213
7270
|
],
|
|
7214
7271
|
signal: abortController.signal
|
|
7215
7272
|
});
|
|
7216
|
-
const
|
|
7273
|
+
const message = response.choices[0]?.message;
|
|
7274
|
+
const content = message?.content ?? "";
|
|
7275
|
+
const finishReason = response.choices[0]?.finish_reason;
|
|
7276
|
+
const reasoningLen = typeof message?.reasoning_content === "string" ? message.reasoning_content.length : 0;
|
|
7277
|
+
const usage = response.usage;
|
|
7278
|
+
if (!content) {
|
|
7279
|
+
const detail = `model=${response.model || config.model} finish_reason=${finishReason} content_len=0 reasoning_len=${reasoningLen} message_keys=${message ? Object.keys(message).join(",") : "(none)"} tokens=${usage?.prompt_tokens ?? "?"}/${usage?.completion_tokens ?? "?"}`;
|
|
7280
|
+
if (finishReason === "length") {
|
|
7281
|
+
console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
|
|
7282
|
+
throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
|
|
7283
|
+
}
|
|
7284
|
+
console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
|
|
7285
|
+
throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
|
|
7286
|
+
}
|
|
7217
7287
|
console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
|
|
7218
7288
|
let jsonStr = content.trim();
|
|
7219
7289
|
if (jsonStr.startsWith("```")) {
|
|
7220
7290
|
jsonStr = jsonStr.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "");
|
|
7221
7291
|
}
|
|
7222
|
-
|
|
7292
|
+
let parsed;
|
|
7223
7293
|
try {
|
|
7224
|
-
|
|
7294
|
+
parsed = JSON.parse(jsonStr);
|
|
7295
|
+
} catch (parseErr) {
|
|
7296
|
+
console.error(
|
|
7297
|
+
`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u89E3\u6790\u5931\u8D25: ${parseErr.message} | \u539F\u59CB\u524D 300 \u5B57\u7B26: ${content.substring(0, 300)}`
|
|
7298
|
+
);
|
|
7299
|
+
throw parseErr;
|
|
7300
|
+
}
|
|
7301
|
+
try {
|
|
7302
|
+
const usage2 = response.usage;
|
|
7225
7303
|
const { recordTokenUsage: recordTokenUsage2 } = await Promise.resolve().then(() => (init_token_stats(), token_stats_exports));
|
|
7226
7304
|
recordTokenUsage2({
|
|
7227
7305
|
sessionId: "audit",
|
|
7228
7306
|
step: "L3_security_judge",
|
|
7229
7307
|
model: response.model || config.model,
|
|
7230
|
-
promptTokens:
|
|
7231
|
-
completionTokens:
|
|
7232
|
-
totalTokens:
|
|
7308
|
+
promptTokens: usage2?.prompt_tokens || 0,
|
|
7309
|
+
completionTokens: usage2?.completion_tokens || 0,
|
|
7310
|
+
totalTokens: usage2?.total_tokens || 0
|
|
7233
7311
|
});
|
|
7234
7312
|
} catch {
|
|
7235
7313
|
}
|
|
@@ -7250,12 +7328,16 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7250
7328
|
console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
|
|
7251
7329
|
break;
|
|
7252
7330
|
}
|
|
7331
|
+
const errObj = err;
|
|
7332
|
+
const status = errObj?.status ?? errObj?.statusCode;
|
|
7333
|
+
const body = errObj?.error ?? errObj?.body;
|
|
7334
|
+
const detail = status !== void 0 || body !== void 0 ? `${err.message} status=${status} body=${String(JSON.stringify(body)).slice(0, 300)}` : err.message;
|
|
7253
7335
|
if (attempt < maxRetries) {
|
|
7254
|
-
console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s
|
|
7336
|
+
console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
|
|
7255
7337
|
await new Promise((resolve11) => setTimeout(resolve11, retryCfg.retryInterval * 1e3));
|
|
7256
7338
|
} else {
|
|
7257
7339
|
clearTimeout(totalTimeoutTimer);
|
|
7258
|
-
console.error(
|
|
7340
|
+
console.error(`[AgentMoss] LLM call failed after all retries: ${detail}`);
|
|
7259
7341
|
throw new Error(`LLM \u5206\u6790\u5931\u8D25 (${maxRetries + 1} \u6B21\u5C1D\u8BD5): ${err.message}`);
|
|
7260
7342
|
}
|
|
7261
7343
|
}
|
|
@@ -9274,7 +9356,7 @@ init_esm_shims();
|
|
|
9274
9356
|
import * as fs4 from "fs";
|
|
9275
9357
|
import * as os2 from "os";
|
|
9276
9358
|
import * as path4 from "path";
|
|
9277
|
-
import { createHash } from "crypto";
|
|
9359
|
+
import { createHash as createHash2 } from "crypto";
|
|
9278
9360
|
|
|
9279
9361
|
// src/engine/coordinator.ts
|
|
9280
9362
|
var TRUSTED_SKILLS_BASE = /* @__PURE__ */ new Set([]);
|
package/dist/server.js
CHANGED
|
@@ -4624,6 +4624,9 @@ function stripHeredocContent(actionDetail) {
|
|
|
4624
4624
|
);
|
|
4625
4625
|
}
|
|
4626
4626
|
function normalizePathSegments(text, foldQuotes = false) {
|
|
4627
|
+
if (!text.includes("//") && !text.includes("/./") && !text.includes("Q") && !text.includes("PROT")) {
|
|
4628
|
+
return text;
|
|
4629
|
+
}
|
|
4627
4630
|
const protTokens = [];
|
|
4628
4631
|
let t = text.replace(/\b(https?|ftp|file):\/\//gi, (m) => {
|
|
4629
4632
|
const scheme = m.slice(0, m.indexOf(":"));
|
|
@@ -4654,43 +4657,24 @@ function pathScanVariants(actionDetailLower) {
|
|
|
4654
4657
|
}
|
|
4655
4658
|
function splitCommandSegments2(actionDetail) {
|
|
4656
4659
|
const segments = [];
|
|
4657
|
-
let
|
|
4658
|
-
let
|
|
4659
|
-
|
|
4660
|
-
|
|
4661
|
-
|
|
4662
|
-
|
|
4663
|
-
|
|
4660
|
+
let start = 0;
|
|
4661
|
+
let cursor = 0;
|
|
4662
|
+
while (true) {
|
|
4663
|
+
COMMAND_SEGMENT_TOKEN_RE.lastIndex = cursor;
|
|
4664
|
+
const match = COMMAND_SEGMENT_TOKEN_RE.exec(actionDetail);
|
|
4665
|
+
if (!match) break;
|
|
4666
|
+
const token = match[0];
|
|
4667
|
+
if (token === "'" || token === '"') {
|
|
4668
|
+
const end = actionDetail.indexOf(token, match.index + 1);
|
|
4669
|
+
if (end < 0) break;
|
|
4670
|
+
cursor = end + 1;
|
|
4664
4671
|
continue;
|
|
4665
4672
|
}
|
|
4666
|
-
|
|
4667
|
-
|
|
4668
|
-
|
|
4669
|
-
continue;
|
|
4670
|
-
}
|
|
4671
|
-
if (ch === ";" || ch === "\n") {
|
|
4672
|
-
segments.push(cur);
|
|
4673
|
-
segments.push(ch);
|
|
4674
|
-
cur = "";
|
|
4675
|
-
continue;
|
|
4676
|
-
}
|
|
4677
|
-
if (ch === "&" && actionDetail[i + 1] === "&") {
|
|
4678
|
-
segments.push(cur);
|
|
4679
|
-
segments.push("&&");
|
|
4680
|
-
cur = "";
|
|
4681
|
-
i++;
|
|
4682
|
-
continue;
|
|
4683
|
-
}
|
|
4684
|
-
if (ch === "|" && actionDetail[i + 1] === "|") {
|
|
4685
|
-
segments.push(cur);
|
|
4686
|
-
segments.push("||");
|
|
4687
|
-
cur = "";
|
|
4688
|
-
i++;
|
|
4689
|
-
continue;
|
|
4690
|
-
}
|
|
4691
|
-
cur += ch;
|
|
4673
|
+
segments.push(actionDetail.slice(start, match.index));
|
|
4674
|
+
segments.push(token);
|
|
4675
|
+
start = cursor = match.index + token.length;
|
|
4692
4676
|
}
|
|
4693
|
-
if (
|
|
4677
|
+
if (start < actionDetail.length) segments.push(actionDetail.slice(start));
|
|
4694
4678
|
return segments;
|
|
4695
4679
|
}
|
|
4696
4680
|
function severityRank(s) {
|
|
@@ -5135,7 +5119,7 @@ function checkLateralMovement(actionDetail) {
|
|
|
5135
5119
|
}
|
|
5136
5120
|
return null;
|
|
5137
5121
|
}
|
|
5138
|
-
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, 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, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
5122
|
+
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, 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, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
5139
5123
|
var init_heuristic = __esm({
|
|
5140
5124
|
"src/engine/heuristic.ts"() {
|
|
5141
5125
|
"use strict";
|
|
@@ -5176,6 +5160,7 @@ var init_heuristic = __esm({
|
|
|
5176
5160
|
"\\bpasswd\\s+--stdin\\b",
|
|
5177
5161
|
"\\bchpasswd\\b"
|
|
5178
5162
|
]);
|
|
5163
|
+
COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
|
|
5179
5164
|
SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
|
|
5180
5165
|
SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
|
|
5181
5166
|
SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
|
|
@@ -7490,6 +7475,7 @@ var init_token_stats = __esm({
|
|
|
7490
7475
|
});
|
|
7491
7476
|
|
|
7492
7477
|
// src/engine/llm-analyzer.ts
|
|
7478
|
+
import { createHash as createHash3 } from "crypto";
|
|
7493
7479
|
import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
|
|
7494
7480
|
import OpenAI from "openai";
|
|
7495
7481
|
async function runLLMAnalysis(input, previous) {
|
|
@@ -7516,7 +7502,7 @@ async function runLLMAnalysis(input, previous) {
|
|
|
7516
7502
|
}
|
|
7517
7503
|
const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
|
|
7518
7504
|
const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
|
|
7519
|
-
const cacheKey = `${input.aNext.actionType}:${rawDetail || input.aNext.actionDetail}`;
|
|
7505
|
+
const cacheKey = `${input.aNext.actionType}:${createHash3("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
|
|
7520
7506
|
const cached2 = llmCache.get(cacheKey);
|
|
7521
7507
|
if (cached2) {
|
|
7522
7508
|
console.log("[AgentMoss] LLM cache hit");
|
|
@@ -7531,7 +7517,48 @@ async function runLLMAnalysis(input, previous) {
|
|
|
7531
7517
|
} else {
|
|
7532
7518
|
scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
|
|
7533
7519
|
}
|
|
7534
|
-
const
|
|
7520
|
+
const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
|
|
7521
|
+
let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
|
|
7522
|
+
let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
|
|
7523
|
+
let prompt = "";
|
|
7524
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
7525
|
+
prompt = buildPrompt(
|
|
7526
|
+
input,
|
|
7527
|
+
previous,
|
|
7528
|
+
matchedSkills,
|
|
7529
|
+
templates,
|
|
7530
|
+
scriptAnalysis,
|
|
7531
|
+
previous.skipL3Hints ?? "",
|
|
7532
|
+
scriptChainText,
|
|
7533
|
+
previous.pathContext ?? "",
|
|
7534
|
+
historyMaxItems,
|
|
7535
|
+
historyMaxChars
|
|
7536
|
+
);
|
|
7537
|
+
if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
|
|
7538
|
+
historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
|
|
7539
|
+
historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
|
|
7540
|
+
}
|
|
7541
|
+
if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
|
|
7542
|
+
const estimated = estimateTokens(prompt);
|
|
7543
|
+
const ratio = estimated / maxPromptTokens;
|
|
7544
|
+
const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
|
|
7545
|
+
const truncated = truncateDetail(input.aNext.actionDetail, allowed);
|
|
7546
|
+
prompt = buildPrompt(
|
|
7547
|
+
{ ...input, aNext: { ...input.aNext, actionDetail: truncated } },
|
|
7548
|
+
previous,
|
|
7549
|
+
matchedSkills,
|
|
7550
|
+
templates,
|
|
7551
|
+
scriptAnalysis,
|
|
7552
|
+
previous.skipL3Hints ?? "",
|
|
7553
|
+
scriptChainText,
|
|
7554
|
+
previous.pathContext ?? "",
|
|
7555
|
+
historyMaxItems,
|
|
7556
|
+
historyMaxChars
|
|
7557
|
+
);
|
|
7558
|
+
console.warn(
|
|
7559
|
+
`[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${maxPromptTokens}\uFF09\uFF0C\u5F53\u524D\u52A8\u4F5C\u8BE6\u60C5\u622A\u65AD\u81F3 ${truncated.length} \u5B57\u7B26`
|
|
7560
|
+
);
|
|
7561
|
+
}
|
|
7535
7562
|
logPrompt(prompt, input.aNext, previous.llmLogPath);
|
|
7536
7563
|
const result = await analyzeWithLLM(prompt, config);
|
|
7537
7564
|
if (llmCache.size >= LLM_CACHE_MAX) {
|
|
@@ -7566,9 +7593,39 @@ ${prompt}
|
|
|
7566
7593
|
console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
|
|
7567
7594
|
}
|
|
7568
7595
|
}
|
|
7569
|
-
function
|
|
7596
|
+
function getNumSetting(key, def) {
|
|
7597
|
+
const v = parseInt(getAgentMossSetting(key, String(def)), 10);
|
|
7598
|
+
return Number.isFinite(v) ? v : def;
|
|
7599
|
+
}
|
|
7600
|
+
function truncateDetail(detail, maxChars) {
|
|
7601
|
+
if (maxChars <= 0 || detail.length <= maxChars) return detail;
|
|
7602
|
+
const head = Math.max(1, Math.floor(maxChars * 0.6));
|
|
7603
|
+
const tail = Math.max(0, maxChars - head);
|
|
7604
|
+
const omitted = detail.length - maxChars;
|
|
7605
|
+
return `${detail.slice(0, head)}...[\u7701\u7565 ${omitted} \u5B57\u7B26]...${tail ? detail.slice(-tail) : ""}`;
|
|
7606
|
+
}
|
|
7607
|
+
function estimateTokens(text) {
|
|
7608
|
+
return Math.floor(text.length / 2.5) + 1;
|
|
7609
|
+
}
|
|
7610
|
+
function formatActionHistory(history, maxItems, maxChars) {
|
|
7611
|
+
if (!history.length) return "(\u65E0\u5386\u53F2\u64CD\u4F5C)";
|
|
7612
|
+
let items = history;
|
|
7613
|
+
let omitted = 0;
|
|
7614
|
+
if (maxItems > 0 && history.length > maxItems) {
|
|
7615
|
+
omitted = history.length - maxItems;
|
|
7616
|
+
items = history.slice(-maxItems);
|
|
7617
|
+
}
|
|
7618
|
+
const lines = [];
|
|
7619
|
+
if (omitted) lines.push(`\uFF08\u66F4\u65E9\u7684 ${omitted} \u6761\u5386\u53F2\u52A8\u4F5C\u5DF2\u7701\u7565\uFF09`);
|
|
7620
|
+
items.forEach((h, i) => {
|
|
7621
|
+
const detail = truncateDetail(h.actionDetail || "", maxChars);
|
|
7622
|
+
lines.push(detail ? `${i + 1}. ${h.actionType}: ${detail}` : `${i + 1}. ${h.actionType}`);
|
|
7623
|
+
});
|
|
7624
|
+
return lines.join("\n");
|
|
7625
|
+
}
|
|
7626
|
+
function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis, skipL3Hints = "", scriptChainText = "", pathContext = "", historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20), historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500)) {
|
|
7570
7627
|
const skillsText = formatSkillsForPrompt(matchedSkills);
|
|
7571
|
-
const historyStr = input.actionHistory
|
|
7628
|
+
const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
|
|
7572
7629
|
const promptHistoryText = formatPromptHistory(input.promptHistory);
|
|
7573
7630
|
const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
|
|
7574
7631
|
const hintsText = formatHints(previous);
|
|
@@ -7681,23 +7738,44 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7681
7738
|
],
|
|
7682
7739
|
signal: abortController.signal
|
|
7683
7740
|
});
|
|
7684
|
-
const
|
|
7741
|
+
const message = response.choices[0]?.message;
|
|
7742
|
+
const content = message?.content ?? "";
|
|
7743
|
+
const finishReason = response.choices[0]?.finish_reason;
|
|
7744
|
+
const reasoningLen = typeof message?.reasoning_content === "string" ? message.reasoning_content.length : 0;
|
|
7745
|
+
const usage = response.usage;
|
|
7746
|
+
if (!content) {
|
|
7747
|
+
const detail = `model=${response.model || config.model} finish_reason=${finishReason} content_len=0 reasoning_len=${reasoningLen} message_keys=${message ? Object.keys(message).join(",") : "(none)"} tokens=${usage?.prompt_tokens ?? "?"}/${usage?.completion_tokens ?? "?"}`;
|
|
7748
|
+
if (finishReason === "length") {
|
|
7749
|
+
console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
|
|
7750
|
+
throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
|
|
7751
|
+
}
|
|
7752
|
+
console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
|
|
7753
|
+
throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
|
|
7754
|
+
}
|
|
7685
7755
|
console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
|
|
7686
7756
|
let jsonStr = content.trim();
|
|
7687
7757
|
if (jsonStr.startsWith("```")) {
|
|
7688
7758
|
jsonStr = jsonStr.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "");
|
|
7689
7759
|
}
|
|
7690
|
-
|
|
7760
|
+
let parsed;
|
|
7761
|
+
try {
|
|
7762
|
+
parsed = JSON.parse(jsonStr);
|
|
7763
|
+
} catch (parseErr) {
|
|
7764
|
+
console.error(
|
|
7765
|
+
`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u89E3\u6790\u5931\u8D25: ${parseErr.message} | \u539F\u59CB\u524D 300 \u5B57\u7B26: ${content.substring(0, 300)}`
|
|
7766
|
+
);
|
|
7767
|
+
throw parseErr;
|
|
7768
|
+
}
|
|
7691
7769
|
try {
|
|
7692
|
-
const
|
|
7770
|
+
const usage2 = response.usage;
|
|
7693
7771
|
const { recordTokenUsage: recordTokenUsage2 } = await Promise.resolve().then(() => (init_token_stats(), token_stats_exports));
|
|
7694
7772
|
recordTokenUsage2({
|
|
7695
7773
|
sessionId: "audit",
|
|
7696
7774
|
step: "L3_security_judge",
|
|
7697
7775
|
model: response.model || config.model,
|
|
7698
|
-
promptTokens:
|
|
7699
|
-
completionTokens:
|
|
7700
|
-
totalTokens:
|
|
7776
|
+
promptTokens: usage2?.prompt_tokens || 0,
|
|
7777
|
+
completionTokens: usage2?.completion_tokens || 0,
|
|
7778
|
+
totalTokens: usage2?.total_tokens || 0
|
|
7701
7779
|
});
|
|
7702
7780
|
} catch {
|
|
7703
7781
|
}
|
|
@@ -7718,12 +7796,16 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
7718
7796
|
console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
|
|
7719
7797
|
break;
|
|
7720
7798
|
}
|
|
7799
|
+
const errObj = err;
|
|
7800
|
+
const status = errObj?.status ?? errObj?.statusCode;
|
|
7801
|
+
const body = errObj?.error ?? errObj?.body;
|
|
7802
|
+
const detail = status !== void 0 || body !== void 0 ? `${err.message} status=${status} body=${String(JSON.stringify(body)).slice(0, 300)}` : err.message;
|
|
7721
7803
|
if (attempt < maxRetries) {
|
|
7722
|
-
console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s
|
|
7804
|
+
console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
|
|
7723
7805
|
await new Promise((resolve12) => setTimeout(resolve12, retryCfg.retryInterval * 1e3));
|
|
7724
7806
|
} else {
|
|
7725
7807
|
clearTimeout(totalTimeoutTimer);
|
|
7726
|
-
console.error(
|
|
7808
|
+
console.error(`[AgentMoss] LLM call failed after all retries: ${detail}`);
|
|
7727
7809
|
throw new Error(`LLM \u5206\u6790\u5931\u8D25 (${maxRetries + 1} \u6B21\u5C1D\u8BD5): ${err.message}`);
|
|
7728
7810
|
}
|
|
7729
7811
|
}
|
|
@@ -10439,10 +10521,10 @@ var init_stateful = __esm({
|
|
|
10439
10521
|
import * as fs4 from "fs";
|
|
10440
10522
|
import * as os2 from "os";
|
|
10441
10523
|
import * as path4 from "path";
|
|
10442
|
-
import { createHash as
|
|
10524
|
+
import { createHash as createHash4 } from "crypto";
|
|
10443
10525
|
function defaultStateDbPath() {
|
|
10444
10526
|
const dir = process.env.AGENT_MOSS_STATE_DIR || path4.join(os2.homedir(), ".agentmoss");
|
|
10445
|
-
const tag =
|
|
10527
|
+
const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
|
|
10446
10528
|
return path4.join(dir, `stateful_chains_${tag}.json`);
|
|
10447
10529
|
}
|
|
10448
10530
|
var ChainStateStore;
|
|
@@ -11322,7 +11404,7 @@ init_esm_shims();
|
|
|
11322
11404
|
init_security_policy();
|
|
11323
11405
|
init_paths();
|
|
11324
11406
|
init_config();
|
|
11325
|
-
import { createHash as
|
|
11407
|
+
import { createHash as createHash5 } from "crypto";
|
|
11326
11408
|
import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync3 } from "fs";
|
|
11327
11409
|
import { tmpdir as tmpdir2 } from "os";
|
|
11328
11410
|
import { join as join15 } from "path";
|
|
@@ -11355,7 +11437,7 @@ var PolicyCache = class {
|
|
|
11355
11437
|
return `${sessionId}::${promptSession}`;
|
|
11356
11438
|
}
|
|
11357
11439
|
cacheFilePath(sessionId, promptSession) {
|
|
11358
|
-
const promptHash =
|
|
11440
|
+
const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
|
|
11359
11441
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
11360
11442
|
return join15(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
|
|
11361
11443
|
}
|