@kenhkl/agent-moss 0.17.17 → 0.17.19

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 CHANGED
@@ -7782,6 +7782,7 @@ var init_token_stats = __esm({
7782
7782
  });
7783
7783
 
7784
7784
  // src/engine/llm-analyzer.ts
7785
+ import { createHash as createHash3 } from "crypto";
7785
7786
  import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
7786
7787
  import OpenAI from "openai";
7787
7788
  async function runLLMAnalysis(input, previous) {
@@ -7808,7 +7809,7 @@ async function runLLMAnalysis(input, previous) {
7808
7809
  }
7809
7810
  const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
7810
7811
  const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
7811
- const cacheKey = `${input.aNext.actionType}:${rawDetail || input.aNext.actionDetail}`;
7812
+ const cacheKey = `${input.aNext.actionType}:${createHash3("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
7812
7813
  const cached2 = llmCache.get(cacheKey);
7813
7814
  if (cached2) {
7814
7815
  console.log("[AgentMoss] LLM cache hit");
@@ -7823,7 +7824,48 @@ async function runLLMAnalysis(input, previous) {
7823
7824
  } else {
7824
7825
  scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
7825
7826
  }
7826
- const prompt = buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis, previous.skipL3Hints ?? "", scriptChainText, previous.pathContext ?? "");
7827
+ const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
7828
+ let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
7829
+ let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
7830
+ let prompt = "";
7831
+ for (let attempt = 0; attempt < 4; attempt++) {
7832
+ prompt = buildPrompt(
7833
+ input,
7834
+ previous,
7835
+ matchedSkills,
7836
+ templates,
7837
+ scriptAnalysis,
7838
+ previous.skipL3Hints ?? "",
7839
+ scriptChainText,
7840
+ previous.pathContext ?? "",
7841
+ historyMaxItems,
7842
+ historyMaxChars
7843
+ );
7844
+ if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
7845
+ historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
7846
+ historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
7847
+ }
7848
+ if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
7849
+ const estimated = estimateTokens(prompt);
7850
+ const ratio = estimated / maxPromptTokens;
7851
+ const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
7852
+ const truncated = truncateDetail(input.aNext.actionDetail, allowed);
7853
+ prompt = buildPrompt(
7854
+ { ...input, aNext: { ...input.aNext, actionDetail: truncated } },
7855
+ previous,
7856
+ matchedSkills,
7857
+ templates,
7858
+ scriptAnalysis,
7859
+ previous.skipL3Hints ?? "",
7860
+ scriptChainText,
7861
+ previous.pathContext ?? "",
7862
+ historyMaxItems,
7863
+ historyMaxChars
7864
+ );
7865
+ console.warn(
7866
+ `[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`
7867
+ );
7868
+ }
7827
7869
  logPrompt(prompt, input.aNext, previous.llmLogPath);
7828
7870
  const result = await analyzeWithLLM(prompt, config);
7829
7871
  if (llmCache.size >= LLM_CACHE_MAX) {
@@ -7858,9 +7900,39 @@ ${prompt}
7858
7900
  console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
7859
7901
  }
7860
7902
  }
7861
- function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis, skipL3Hints = "", scriptChainText = "", pathContext = "") {
7903
+ function getNumSetting(key, def) {
7904
+ const v = parseInt(getAgentMossSetting(key, String(def)), 10);
7905
+ return Number.isFinite(v) ? v : def;
7906
+ }
7907
+ function truncateDetail(detail, maxChars) {
7908
+ if (maxChars <= 0 || detail.length <= maxChars) return detail;
7909
+ const head = Math.max(1, Math.floor(maxChars * 0.6));
7910
+ const tail = Math.max(0, maxChars - head);
7911
+ const omitted = detail.length - maxChars;
7912
+ return `${detail.slice(0, head)}...[\u7701\u7565 ${omitted} \u5B57\u7B26]...${tail ? detail.slice(-tail) : ""}`;
7913
+ }
7914
+ function estimateTokens(text) {
7915
+ return Math.floor(text.length / 2.5) + 1;
7916
+ }
7917
+ function formatActionHistory(history, maxItems, maxChars) {
7918
+ if (!history.length) return "(\u65E0\u5386\u53F2\u64CD\u4F5C)";
7919
+ let items = history;
7920
+ let omitted = 0;
7921
+ if (maxItems > 0 && history.length > maxItems) {
7922
+ omitted = history.length - maxItems;
7923
+ items = history.slice(-maxItems);
7924
+ }
7925
+ const lines = [];
7926
+ if (omitted) lines.push(`\uFF08\u66F4\u65E9\u7684 ${omitted} \u6761\u5386\u53F2\u52A8\u4F5C\u5DF2\u7701\u7565\uFF09`);
7927
+ items.forEach((h, i) => {
7928
+ const detail = truncateDetail(h.actionDetail || "", maxChars);
7929
+ lines.push(detail ? `${i + 1}. ${h.actionType}: ${detail}` : `${i + 1}. ${h.actionType}`);
7930
+ });
7931
+ return lines.join("\n");
7932
+ }
7933
+ 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
7934
  const skillsText = formatSkillsForPrompt(matchedSkills);
7863
- const historyStr = input.actionHistory.map((h, i) => `${i + 1}. ${h.actionType}: ${h.actionDetail}`).join("\n") || "(\u65E0\u5386\u53F2\u64CD\u4F5C)";
7935
+ const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
7864
7936
  const promptHistoryText = formatPromptHistory(input.promptHistory);
7865
7937
  const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
7866
7938
  const hintsText = formatHints(previous);
@@ -7973,23 +8045,44 @@ async function analyzeWithLLM(prompt, config) {
7973
8045
  ],
7974
8046
  signal: abortController.signal
7975
8047
  });
7976
- const content = response.choices[0]?.message?.content || "{}";
8048
+ const message = response.choices[0]?.message;
8049
+ const content = message?.content ?? "";
8050
+ const finishReason = response.choices[0]?.finish_reason;
8051
+ const reasoningLen = typeof message?.reasoning_content === "string" ? message.reasoning_content.length : 0;
8052
+ const usage = response.usage;
8053
+ if (!content) {
8054
+ 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 ?? "?"}`;
8055
+ if (finishReason === "length") {
8056
+ console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
8057
+ throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
8058
+ }
8059
+ console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
8060
+ throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
8061
+ }
7977
8062
  console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
7978
8063
  let jsonStr = content.trim();
7979
8064
  if (jsonStr.startsWith("```")) {
7980
8065
  jsonStr = jsonStr.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "");
7981
8066
  }
7982
- const parsed = JSON.parse(jsonStr);
8067
+ let parsed;
7983
8068
  try {
7984
- const usage = response.usage;
8069
+ parsed = JSON.parse(jsonStr);
8070
+ } catch (parseErr) {
8071
+ console.error(
8072
+ `[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u89E3\u6790\u5931\u8D25: ${parseErr.message} | \u539F\u59CB\u524D 300 \u5B57\u7B26: ${content.substring(0, 300)}`
8073
+ );
8074
+ throw parseErr;
8075
+ }
8076
+ try {
8077
+ const usage2 = response.usage;
7985
8078
  const { recordTokenUsage: recordTokenUsage2 } = await Promise.resolve().then(() => (init_token_stats(), token_stats_exports));
7986
8079
  recordTokenUsage2({
7987
8080
  sessionId: "audit",
7988
8081
  step: "L3_security_judge",
7989
8082
  model: response.model || config.model,
7990
- promptTokens: usage?.prompt_tokens || 0,
7991
- completionTokens: usage?.completion_tokens || 0,
7992
- totalTokens: usage?.total_tokens || 0
8083
+ promptTokens: usage2?.prompt_tokens || 0,
8084
+ completionTokens: usage2?.completion_tokens || 0,
8085
+ totalTokens: usage2?.total_tokens || 0
7993
8086
  });
7994
8087
  } catch {
7995
8088
  }
@@ -8010,12 +8103,16 @@ async function analyzeWithLLM(prompt, config) {
8010
8103
  console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
8011
8104
  break;
8012
8105
  }
8106
+ const errObj = err;
8107
+ const status = errObj?.status ?? errObj?.statusCode;
8108
+ const body = errObj?.error ?? errObj?.body;
8109
+ const detail = status !== void 0 || body !== void 0 ? `${err.message} status=${status} body=${String(JSON.stringify(body)).slice(0, 300)}` : err.message;
8013
8110
  if (attempt < maxRetries) {
8014
- console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s:`, err.message);
8111
+ console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
8015
8112
  await new Promise((resolve12) => setTimeout(resolve12, retryCfg.retryInterval * 1e3));
8016
8113
  } else {
8017
8114
  clearTimeout(totalTimeoutTimer);
8018
- console.error("[AgentMoss] LLM call failed after all retries:", err.message);
8115
+ console.error(`[AgentMoss] LLM call failed after all retries: ${detail}`);
8019
8116
  throw new Error(`LLM \u5206\u6790\u5931\u8D25 (${maxRetries + 1} \u6B21\u5C1D\u8BD5): ${err.message}`);
8020
8117
  }
8021
8118
  }
@@ -10996,10 +11093,10 @@ var init_stateful = __esm({
10996
11093
  import * as fs4 from "fs";
10997
11094
  import * as os2 from "os";
10998
11095
  import * as path4 from "path";
10999
- import { createHash as createHash3 } from "crypto";
11096
+ import { createHash as createHash4 } from "crypto";
11000
11097
  function defaultStateDbPath() {
11001
11098
  const dir = process.env.AGENT_MOSS_STATE_DIR || path4.join(os2.homedir(), ".agentmoss");
11002
- const tag = createHash3("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
11099
+ const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
11003
11100
  return path4.join(dir, `stateful_chains_${tag}.json`);
11004
11101
  }
11005
11102
  var ChainStateStore;
@@ -11586,7 +11683,7 @@ var init_coordinator = __esm({
11586
11683
  });
11587
11684
 
11588
11685
  // src/infra/policy-cache.ts
11589
- import { createHash as createHash4 } from "crypto";
11686
+ import { createHash as createHash5 } from "crypto";
11590
11687
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync3 } from "fs";
11591
11688
  import { tmpdir as tmpdir3 } from "os";
11592
11689
  import { join as join16 } from "path";
@@ -11631,7 +11728,7 @@ var init_policy_cache = __esm({
11631
11728
  return `${sessionId}::${promptSession}`;
11632
11729
  }
11633
11730
  cacheFilePath(sessionId, promptSession) {
11634
- const promptHash = createHash4("md5").update(promptSession).digest("hex").slice(0, 12);
11731
+ const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
11635
11732
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
11636
11733
  return join16(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
11637
11734
  }
@@ -4831,6 +4831,7 @@ init_inline_analyzer();
4831
4831
 
4832
4832
  // src/engine/llm-analyzer.ts
4833
4833
  init_esm_shims();
4834
+ import { createHash } from "crypto";
4834
4835
 
4835
4836
  // src/infra/security-policy.ts
4836
4837
  init_esm_shims();
@@ -7048,7 +7049,7 @@ async function runLLMAnalysis(input, previous) {
7048
7049
  }
7049
7050
  const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
7050
7051
  const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
7051
- const cacheKey = `${input.aNext.actionType}:${rawDetail || input.aNext.actionDetail}`;
7052
+ const cacheKey = `${input.aNext.actionType}:${createHash("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
7052
7053
  const cached2 = llmCache.get(cacheKey);
7053
7054
  if (cached2) {
7054
7055
  console.log("[AgentMoss] LLM cache hit");
@@ -7063,7 +7064,48 @@ async function runLLMAnalysis(input, previous) {
7063
7064
  } else {
7064
7065
  scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
7065
7066
  }
7066
- const prompt = buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis, previous.skipL3Hints ?? "", scriptChainText, previous.pathContext ?? "");
7067
+ const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
7068
+ let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
7069
+ let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
7070
+ let prompt = "";
7071
+ for (let attempt = 0; attempt < 4; attempt++) {
7072
+ prompt = buildPrompt(
7073
+ input,
7074
+ previous,
7075
+ matchedSkills,
7076
+ templates,
7077
+ scriptAnalysis,
7078
+ previous.skipL3Hints ?? "",
7079
+ scriptChainText,
7080
+ previous.pathContext ?? "",
7081
+ historyMaxItems,
7082
+ historyMaxChars
7083
+ );
7084
+ if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
7085
+ historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
7086
+ historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
7087
+ }
7088
+ if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
7089
+ const estimated = estimateTokens(prompt);
7090
+ const ratio = estimated / maxPromptTokens;
7091
+ const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
7092
+ const truncated = truncateDetail(input.aNext.actionDetail, allowed);
7093
+ prompt = buildPrompt(
7094
+ { ...input, aNext: { ...input.aNext, actionDetail: truncated } },
7095
+ previous,
7096
+ matchedSkills,
7097
+ templates,
7098
+ scriptAnalysis,
7099
+ previous.skipL3Hints ?? "",
7100
+ scriptChainText,
7101
+ previous.pathContext ?? "",
7102
+ historyMaxItems,
7103
+ historyMaxChars
7104
+ );
7105
+ console.warn(
7106
+ `[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`
7107
+ );
7108
+ }
7067
7109
  logPrompt(prompt, input.aNext, previous.llmLogPath);
7068
7110
  const result = await analyzeWithLLM(prompt, config);
7069
7111
  if (llmCache.size >= LLM_CACHE_MAX) {
@@ -7098,9 +7140,39 @@ ${prompt}
7098
7140
  console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
7099
7141
  }
7100
7142
  }
7101
- function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis, skipL3Hints = "", scriptChainText = "", pathContext = "") {
7143
+ function getNumSetting(key, def) {
7144
+ const v = parseInt(getAgentMossSetting(key, String(def)), 10);
7145
+ return Number.isFinite(v) ? v : def;
7146
+ }
7147
+ function truncateDetail(detail, maxChars) {
7148
+ if (maxChars <= 0 || detail.length <= maxChars) return detail;
7149
+ const head = Math.max(1, Math.floor(maxChars * 0.6));
7150
+ const tail = Math.max(0, maxChars - head);
7151
+ const omitted = detail.length - maxChars;
7152
+ return `${detail.slice(0, head)}...[\u7701\u7565 ${omitted} \u5B57\u7B26]...${tail ? detail.slice(-tail) : ""}`;
7153
+ }
7154
+ function estimateTokens(text) {
7155
+ return Math.floor(text.length / 2.5) + 1;
7156
+ }
7157
+ function formatActionHistory(history, maxItems, maxChars) {
7158
+ if (!history.length) return "(\u65E0\u5386\u53F2\u64CD\u4F5C)";
7159
+ let items = history;
7160
+ let omitted = 0;
7161
+ if (maxItems > 0 && history.length > maxItems) {
7162
+ omitted = history.length - maxItems;
7163
+ items = history.slice(-maxItems);
7164
+ }
7165
+ const lines = [];
7166
+ if (omitted) lines.push(`\uFF08\u66F4\u65E9\u7684 ${omitted} \u6761\u5386\u53F2\u52A8\u4F5C\u5DF2\u7701\u7565\uFF09`);
7167
+ items.forEach((h, i) => {
7168
+ const detail = truncateDetail(h.actionDetail || "", maxChars);
7169
+ lines.push(detail ? `${i + 1}. ${h.actionType}: ${detail}` : `${i + 1}. ${h.actionType}`);
7170
+ });
7171
+ return lines.join("\n");
7172
+ }
7173
+ 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
7174
  const skillsText = formatSkillsForPrompt(matchedSkills);
7103
- const historyStr = input.actionHistory.map((h, i) => `${i + 1}. ${h.actionType}: ${h.actionDetail}`).join("\n") || "(\u65E0\u5386\u53F2\u64CD\u4F5C)";
7175
+ const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
7104
7176
  const promptHistoryText = formatPromptHistory(input.promptHistory);
7105
7177
  const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
7106
7178
  const hintsText = formatHints(previous);
@@ -7213,23 +7285,44 @@ async function analyzeWithLLM(prompt, config) {
7213
7285
  ],
7214
7286
  signal: abortController.signal
7215
7287
  });
7216
- const content = response.choices[0]?.message?.content || "{}";
7288
+ const message = response.choices[0]?.message;
7289
+ const content = message?.content ?? "";
7290
+ const finishReason = response.choices[0]?.finish_reason;
7291
+ const reasoningLen = typeof message?.reasoning_content === "string" ? message.reasoning_content.length : 0;
7292
+ const usage = response.usage;
7293
+ if (!content) {
7294
+ 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 ?? "?"}`;
7295
+ if (finishReason === "length") {
7296
+ console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
7297
+ throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
7298
+ }
7299
+ console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
7300
+ throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
7301
+ }
7217
7302
  console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
7218
7303
  let jsonStr = content.trim();
7219
7304
  if (jsonStr.startsWith("```")) {
7220
7305
  jsonStr = jsonStr.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "");
7221
7306
  }
7222
- const parsed = JSON.parse(jsonStr);
7307
+ let parsed;
7223
7308
  try {
7224
- const usage = response.usage;
7309
+ parsed = JSON.parse(jsonStr);
7310
+ } catch (parseErr) {
7311
+ console.error(
7312
+ `[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u89E3\u6790\u5931\u8D25: ${parseErr.message} | \u539F\u59CB\u524D 300 \u5B57\u7B26: ${content.substring(0, 300)}`
7313
+ );
7314
+ throw parseErr;
7315
+ }
7316
+ try {
7317
+ const usage2 = response.usage;
7225
7318
  const { recordTokenUsage: recordTokenUsage2 } = await Promise.resolve().then(() => (init_token_stats(), token_stats_exports));
7226
7319
  recordTokenUsage2({
7227
7320
  sessionId: "audit",
7228
7321
  step: "L3_security_judge",
7229
7322
  model: response.model || config.model,
7230
- promptTokens: usage?.prompt_tokens || 0,
7231
- completionTokens: usage?.completion_tokens || 0,
7232
- totalTokens: usage?.total_tokens || 0
7323
+ promptTokens: usage2?.prompt_tokens || 0,
7324
+ completionTokens: usage2?.completion_tokens || 0,
7325
+ totalTokens: usage2?.total_tokens || 0
7233
7326
  });
7234
7327
  } catch {
7235
7328
  }
@@ -7250,12 +7343,16 @@ async function analyzeWithLLM(prompt, config) {
7250
7343
  console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
7251
7344
  break;
7252
7345
  }
7346
+ const errObj = err;
7347
+ const status = errObj?.status ?? errObj?.statusCode;
7348
+ const body = errObj?.error ?? errObj?.body;
7349
+ const detail = status !== void 0 || body !== void 0 ? `${err.message} status=${status} body=${String(JSON.stringify(body)).slice(0, 300)}` : err.message;
7253
7350
  if (attempt < maxRetries) {
7254
- console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s:`, err.message);
7351
+ console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
7255
7352
  await new Promise((resolve11) => setTimeout(resolve11, retryCfg.retryInterval * 1e3));
7256
7353
  } else {
7257
7354
  clearTimeout(totalTimeoutTimer);
7258
- console.error("[AgentMoss] LLM call failed after all retries:", err.message);
7355
+ console.error(`[AgentMoss] LLM call failed after all retries: ${detail}`);
7259
7356
  throw new Error(`LLM \u5206\u6790\u5931\u8D25 (${maxRetries + 1} \u6B21\u5C1D\u8BD5): ${err.message}`);
7260
7357
  }
7261
7358
  }
@@ -9274,7 +9371,7 @@ init_esm_shims();
9274
9371
  import * as fs4 from "fs";
9275
9372
  import * as os2 from "os";
9276
9373
  import * as path4 from "path";
9277
- import { createHash } from "crypto";
9374
+ import { createHash as createHash2 } from "crypto";
9278
9375
 
9279
9376
  // src/engine/coordinator.ts
9280
9377
  var TRUSTED_SKILLS_BASE = /* @__PURE__ */ new Set([]);
package/dist/server.js CHANGED
@@ -7490,6 +7490,7 @@ var init_token_stats = __esm({
7490
7490
  });
7491
7491
 
7492
7492
  // src/engine/llm-analyzer.ts
7493
+ import { createHash as createHash3 } from "crypto";
7493
7494
  import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
7494
7495
  import OpenAI from "openai";
7495
7496
  async function runLLMAnalysis(input, previous) {
@@ -7516,7 +7517,7 @@ async function runLLMAnalysis(input, previous) {
7516
7517
  }
7517
7518
  const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
7518
7519
  const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
7519
- const cacheKey = `${input.aNext.actionType}:${rawDetail || input.aNext.actionDetail}`;
7520
+ const cacheKey = `${input.aNext.actionType}:${createHash3("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
7520
7521
  const cached2 = llmCache.get(cacheKey);
7521
7522
  if (cached2) {
7522
7523
  console.log("[AgentMoss] LLM cache hit");
@@ -7531,7 +7532,48 @@ async function runLLMAnalysis(input, previous) {
7531
7532
  } else {
7532
7533
  scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
7533
7534
  }
7534
- const prompt = buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis, previous.skipL3Hints ?? "", scriptChainText, previous.pathContext ?? "");
7535
+ const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
7536
+ let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
7537
+ let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
7538
+ let prompt = "";
7539
+ for (let attempt = 0; attempt < 4; attempt++) {
7540
+ prompt = buildPrompt(
7541
+ input,
7542
+ previous,
7543
+ matchedSkills,
7544
+ templates,
7545
+ scriptAnalysis,
7546
+ previous.skipL3Hints ?? "",
7547
+ scriptChainText,
7548
+ previous.pathContext ?? "",
7549
+ historyMaxItems,
7550
+ historyMaxChars
7551
+ );
7552
+ if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
7553
+ historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
7554
+ historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
7555
+ }
7556
+ if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
7557
+ const estimated = estimateTokens(prompt);
7558
+ const ratio = estimated / maxPromptTokens;
7559
+ const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
7560
+ const truncated = truncateDetail(input.aNext.actionDetail, allowed);
7561
+ prompt = buildPrompt(
7562
+ { ...input, aNext: { ...input.aNext, actionDetail: truncated } },
7563
+ previous,
7564
+ matchedSkills,
7565
+ templates,
7566
+ scriptAnalysis,
7567
+ previous.skipL3Hints ?? "",
7568
+ scriptChainText,
7569
+ previous.pathContext ?? "",
7570
+ historyMaxItems,
7571
+ historyMaxChars
7572
+ );
7573
+ console.warn(
7574
+ `[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`
7575
+ );
7576
+ }
7535
7577
  logPrompt(prompt, input.aNext, previous.llmLogPath);
7536
7578
  const result = await analyzeWithLLM(prompt, config);
7537
7579
  if (llmCache.size >= LLM_CACHE_MAX) {
@@ -7566,9 +7608,39 @@ ${prompt}
7566
7608
  console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
7567
7609
  }
7568
7610
  }
7569
- function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis, skipL3Hints = "", scriptChainText = "", pathContext = "") {
7611
+ function getNumSetting(key, def) {
7612
+ const v = parseInt(getAgentMossSetting(key, String(def)), 10);
7613
+ return Number.isFinite(v) ? v : def;
7614
+ }
7615
+ function truncateDetail(detail, maxChars) {
7616
+ if (maxChars <= 0 || detail.length <= maxChars) return detail;
7617
+ const head = Math.max(1, Math.floor(maxChars * 0.6));
7618
+ const tail = Math.max(0, maxChars - head);
7619
+ const omitted = detail.length - maxChars;
7620
+ return `${detail.slice(0, head)}...[\u7701\u7565 ${omitted} \u5B57\u7B26]...${tail ? detail.slice(-tail) : ""}`;
7621
+ }
7622
+ function estimateTokens(text) {
7623
+ return Math.floor(text.length / 2.5) + 1;
7624
+ }
7625
+ function formatActionHistory(history, maxItems, maxChars) {
7626
+ if (!history.length) return "(\u65E0\u5386\u53F2\u64CD\u4F5C)";
7627
+ let items = history;
7628
+ let omitted = 0;
7629
+ if (maxItems > 0 && history.length > maxItems) {
7630
+ omitted = history.length - maxItems;
7631
+ items = history.slice(-maxItems);
7632
+ }
7633
+ const lines = [];
7634
+ if (omitted) lines.push(`\uFF08\u66F4\u65E9\u7684 ${omitted} \u6761\u5386\u53F2\u52A8\u4F5C\u5DF2\u7701\u7565\uFF09`);
7635
+ items.forEach((h, i) => {
7636
+ const detail = truncateDetail(h.actionDetail || "", maxChars);
7637
+ lines.push(detail ? `${i + 1}. ${h.actionType}: ${detail}` : `${i + 1}. ${h.actionType}`);
7638
+ });
7639
+ return lines.join("\n");
7640
+ }
7641
+ 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
7642
  const skillsText = formatSkillsForPrompt(matchedSkills);
7571
- const historyStr = input.actionHistory.map((h, i) => `${i + 1}. ${h.actionType}: ${h.actionDetail}`).join("\n") || "(\u65E0\u5386\u53F2\u64CD\u4F5C)";
7643
+ const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
7572
7644
  const promptHistoryText = formatPromptHistory(input.promptHistory);
7573
7645
  const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
7574
7646
  const hintsText = formatHints(previous);
@@ -7681,23 +7753,44 @@ async function analyzeWithLLM(prompt, config) {
7681
7753
  ],
7682
7754
  signal: abortController.signal
7683
7755
  });
7684
- const content = response.choices[0]?.message?.content || "{}";
7756
+ const message = response.choices[0]?.message;
7757
+ const content = message?.content ?? "";
7758
+ const finishReason = response.choices[0]?.finish_reason;
7759
+ const reasoningLen = typeof message?.reasoning_content === "string" ? message.reasoning_content.length : 0;
7760
+ const usage = response.usage;
7761
+ if (!content) {
7762
+ 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 ?? "?"}`;
7763
+ if (finishReason === "length") {
7764
+ console.error(`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09: ${detail}`);
7765
+ throw new Error("LLM \u63A8\u7406\u8017\u5C3D token\uFF08finish_reason=length\uFF09\uFF0C\u65E0\u5B9E\u9645\u8F93\u51FA");
7766
+ }
7767
+ console.error(`[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A: ${detail}`);
7768
+ throw new Error("LLM \u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
7769
+ }
7685
7770
  console.log(`[AgentMoss] LLM raw response (attempt ${attempt + 1}/${maxRetries + 1}): ${content.substring(0, 300)}`);
7686
7771
  let jsonStr = content.trim();
7687
7772
  if (jsonStr.startsWith("```")) {
7688
7773
  jsonStr = jsonStr.replace(/^```[\w]*\n?/, "").replace(/\n?```$/, "");
7689
7774
  }
7690
- const parsed = JSON.parse(jsonStr);
7775
+ let parsed;
7776
+ try {
7777
+ parsed = JSON.parse(jsonStr);
7778
+ } catch (parseErr) {
7779
+ console.error(
7780
+ `[AgentMoss] LLM \u8FD4\u56DE\u5185\u5BB9\u89E3\u6790\u5931\u8D25: ${parseErr.message} | \u539F\u59CB\u524D 300 \u5B57\u7B26: ${content.substring(0, 300)}`
7781
+ );
7782
+ throw parseErr;
7783
+ }
7691
7784
  try {
7692
- const usage = response.usage;
7785
+ const usage2 = response.usage;
7693
7786
  const { recordTokenUsage: recordTokenUsage2 } = await Promise.resolve().then(() => (init_token_stats(), token_stats_exports));
7694
7787
  recordTokenUsage2({
7695
7788
  sessionId: "audit",
7696
7789
  step: "L3_security_judge",
7697
7790
  model: response.model || config.model,
7698
- promptTokens: usage?.prompt_tokens || 0,
7699
- completionTokens: usage?.completion_tokens || 0,
7700
- totalTokens: usage?.total_tokens || 0
7791
+ promptTokens: usage2?.prompt_tokens || 0,
7792
+ completionTokens: usage2?.completion_tokens || 0,
7793
+ totalTokens: usage2?.total_tokens || 0
7701
7794
  });
7702
7795
  } catch {
7703
7796
  }
@@ -7718,12 +7811,16 @@ async function analyzeWithLLM(prompt, config) {
7718
7811
  console.error(`[AgentMoss] LLM analysis aborted by totalTimeout (${timeoutCfg.totalTimeout}s)`);
7719
7812
  break;
7720
7813
  }
7814
+ const errObj = err;
7815
+ const status = errObj?.status ?? errObj?.statusCode;
7816
+ const body = errObj?.error ?? errObj?.body;
7817
+ const detail = status !== void 0 || body !== void 0 ? `${err.message} status=${status} body=${String(JSON.stringify(body)).slice(0, 300)}` : err.message;
7721
7818
  if (attempt < maxRetries) {
7722
- console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s:`, err.message);
7819
+ console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
7723
7820
  await new Promise((resolve12) => setTimeout(resolve12, retryCfg.retryInterval * 1e3));
7724
7821
  } else {
7725
7822
  clearTimeout(totalTimeoutTimer);
7726
- console.error("[AgentMoss] LLM call failed after all retries:", err.message);
7823
+ console.error(`[AgentMoss] LLM call failed after all retries: ${detail}`);
7727
7824
  throw new Error(`LLM \u5206\u6790\u5931\u8D25 (${maxRetries + 1} \u6B21\u5C1D\u8BD5): ${err.message}`);
7728
7825
  }
7729
7826
  }
@@ -10439,10 +10536,10 @@ var init_stateful = __esm({
10439
10536
  import * as fs4 from "fs";
10440
10537
  import * as os2 from "os";
10441
10538
  import * as path4 from "path";
10442
- import { createHash as createHash3 } from "crypto";
10539
+ import { createHash as createHash4 } from "crypto";
10443
10540
  function defaultStateDbPath() {
10444
10541
  const dir = process.env.AGENT_MOSS_STATE_DIR || path4.join(os2.homedir(), ".agentmoss");
10445
- const tag = createHash3("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
10542
+ const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
10446
10543
  return path4.join(dir, `stateful_chains_${tag}.json`);
10447
10544
  }
10448
10545
  var ChainStateStore;
@@ -11322,7 +11419,7 @@ init_esm_shims();
11322
11419
  init_security_policy();
11323
11420
  init_paths();
11324
11421
  init_config();
11325
- import { createHash as createHash4 } from "crypto";
11422
+ import { createHash as createHash5 } from "crypto";
11326
11423
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync5, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync3 } from "fs";
11327
11424
  import { tmpdir as tmpdir2 } from "os";
11328
11425
  import { join as join15 } from "path";
@@ -11355,7 +11452,7 @@ var PolicyCache = class {
11355
11452
  return `${sessionId}::${promptSession}`;
11356
11453
  }
11357
11454
  cacheFilePath(sessionId, promptSession) {
11358
- const promptHash = createHash4("md5").update(promptSession).digest("hex").slice(0, 12);
11455
+ const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
11359
11456
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
11360
11457
  return join15(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
11361
11458
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kenhkl/agent-moss",
3
- "version": "0.17.17",
3
+ "version": "0.17.19",
4
4
  "description": "Multi-layer security analysis engine for AI agents (TypeScript)",
5
5
  "type": "module",
6
6
  "main": "dist/server.js",