@kenhkl/agent-moss 0.17.41 → 0.17.42

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/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 isHealth = HEALTH_PATHS.includes(path9.replace(/\/+$/, ""));
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 (path9.startsWith("/console/api")) {
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
- if (kws.some((kw) => t.includes(String(kw).toLowerCase()))) out.add(cat);
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;
@@ -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();
@@ -4992,6 +5149,21 @@ function detectLanguage(path9, content) {
4992
5149
  }
4993
5150
  return "other";
4994
5151
  }
5152
+ function isInstructionTarget(path9) {
5153
+ const p = (path9 || "").replace(/\\/g, "/").toLowerCase();
5154
+ if (!p) return false;
5155
+ const base = p.split("/").pop() || "";
5156
+ if (["agents.md", "claude.md", "system.md", "prompt.md", "instructions.md", ".cursorrules"].includes(base)) {
5157
+ return true;
5158
+ }
5159
+ if (/(?:^|[-_.])(?:prompt|instruction|system)(?:[-_.]|$)/.test(base)) return true;
5160
+ return INSTRUCTION_TARGET_RE.test(p);
5161
+ }
5162
+ function isDataDocument(actionType, actionDetailRaw) {
5163
+ const payload = extractWritePayload(actionType, actionDetailRaw);
5164
+ if (payload === null) return false;
5165
+ return detectLanguage(payload.path, payload.content) === "data" && !isInstructionTarget(payload.path);
5166
+ }
4995
5167
  function stripShellComments(text) {
4996
5168
  const out = [];
4997
5169
  let heredocEnd = null;
@@ -5154,7 +5326,7 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
5154
5326
  }
5155
5327
  return snippets;
5156
5328
  }
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;
5329
+ 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
5330
  var init_written_content_analyzer = __esm({
5159
5331
  "src/engine/written-content-analyzer.ts"() {
5160
5332
  "use strict";
@@ -5177,7 +5349,12 @@ var init_written_content_analyzer = __esm({
5177
5349
  "file_edit",
5178
5350
  "editfile",
5179
5351
  "searchreplace",
5180
- "search_replace"
5352
+ "search_replace",
5353
+ // 通用 workspace 工具名(ClawPartner/QwenPaw 等宿主常用)
5354
+ "workspace_write_file",
5355
+ "workspace_edit_file",
5356
+ "workspace_writefile",
5357
+ "workspace_editfile"
5181
5358
  ]);
5182
5359
  WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
5183
5360
  APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
@@ -5186,6 +5363,7 @@ var init_written_content_analyzer = __esm({
5186
5363
  INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
5187
5364
  QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
5188
5365
  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;
5366
+ INSTRUCTION_TARGET_RE = /(?:^|[/\\])(?:prompts?|instructions?|skills?|memories|memory|config|policies|policy|\.claude|\.cursor)(?:[/\\]|$)|(?:^|[/\\])(?:AGENTS?|CLAUDE|SYSTEM|PROMPT|INSTRUCTIONS?)(?:\.[^/\\]+)?$|(?:^|[/\\])\.cursorrules$/i;
5189
5367
  HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
5190
5368
  }
5191
5369
  });
@@ -5429,6 +5607,23 @@ function runHeuristicCheck(input) {
5429
5607
  deobfuscated
5430
5608
  );
5431
5609
  }
5610
+ const extraScanDetail = stripSearchPatternLiterals(scanDetail);
5611
+ const extraScanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => {
5612
+ const stripped = stripSearchPatternLiterals(sn);
5613
+ return [`${input.aNext.actionType}: ${stripped}`, stripped];
5614
+ }) : String(input.osType || "").toLowerCase() === "windows" ? [
5615
+ `${input.aNext.actionType}: ${extraScanDetail}`,
5616
+ extraScanDetail,
5617
+ `${input.aNext.actionType}: ${extraScanDetail.replace(/\//g, "\\")}`,
5618
+ extraScanDetail.replace(/\//g, "\\")
5619
+ ] : [`${input.aNext.actionType}: ${extraScanDetail}`, extraScanDetail];
5620
+ const extraDeobfuscated = normalizeShellObfuscation(extraScanDetail);
5621
+ if (extraDeobfuscated !== extraScanDetail) {
5622
+ extraScanCommands.push(
5623
+ `${input.aNext.actionType}: ${extraDeobfuscated}`,
5624
+ extraDeobfuscated
5625
+ );
5626
+ }
5432
5627
  let topRiskType = "";
5433
5628
  const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
5434
5629
  const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
@@ -5453,7 +5648,7 @@ function runHeuristicCheck(input) {
5453
5648
  for (const rule of agentExt.extra_command_patterns) {
5454
5649
  try {
5455
5650
  const re = new RegExp(rule.pattern, "i");
5456
- if (scanCommands.some((c) => re.test(c))) {
5651
+ if (extraScanCommands.some((c) => re.test(c))) {
5457
5652
  matched.push(`agent \u4E13\u5C5E\u89C4\u5219: ${rule.reason}`);
5458
5653
  if (severityRank(rule.risk_level) > severityRank(highestSeverity)) {
5459
5654
  highestSeverity = rule.risk_level;
@@ -5464,7 +5659,7 @@ function runHeuristicCheck(input) {
5464
5659
  }
5465
5660
  }
5466
5661
  }
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();
5662
+ 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
5663
  let pythonWalkOnerrorOnly = false;
5469
5664
  if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
5470
5665
  pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
@@ -5715,16 +5910,83 @@ function splitCommandSegments2(actionDetail) {
5715
5910
  if (start < actionDetail.length) segments.push(actionDetail.slice(start));
5716
5911
  return segments;
5717
5912
  }
5913
+ function shellTokens(seg) {
5914
+ const tokens = [];
5915
+ let cur = "";
5916
+ let quote = "";
5917
+ for (let i = 0; i < seg.length; i++) {
5918
+ const ch = seg[i];
5919
+ if (quote) {
5920
+ if (ch === quote) quote = "";
5921
+ else cur += ch;
5922
+ continue;
5923
+ }
5924
+ if (ch === '"' || ch === "'") {
5925
+ quote = ch;
5926
+ continue;
5927
+ }
5928
+ if (/\s/.test(ch)) {
5929
+ if (cur) {
5930
+ tokens.push(cur);
5931
+ cur = "";
5932
+ }
5933
+ continue;
5934
+ }
5935
+ cur += ch;
5936
+ }
5937
+ if (quote) return null;
5938
+ if (cur) tokens.push(cur);
5939
+ return tokens;
5940
+ }
5941
+ function stripSearchPatternArgument(seg) {
5942
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) return seg;
5943
+ const tokens = shellTokens(seg);
5944
+ if (!tokens || tokens.length === 0) return seg;
5945
+ let idx = 0;
5946
+ while (idx < tokens.length && COMMAND_PREFIX_WORDS.has(tokens[idx])) idx++;
5947
+ if (idx >= tokens.length || !TEXT_SEARCH_COMMANDS.has(tokens[idx])) return seg;
5948
+ let patternIdx = null;
5949
+ let i = idx + 1;
5950
+ while (i < tokens.length) {
5951
+ const token = tokens[i];
5952
+ if (token === "--") {
5953
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
5954
+ break;
5955
+ }
5956
+ if (token === "-e" || token === "--regexp") {
5957
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
5958
+ break;
5959
+ }
5960
+ if (token.startsWith("--regexp=")) {
5961
+ patternIdx = i;
5962
+ break;
5963
+ }
5964
+ if (token === "-f" || token === "--file" || token.startsWith("--file=")) break;
5965
+ if (token.startsWith("-") && token !== "-") {
5966
+ i += SEARCH_OPTION_WITH_ARG.has(token) ? 2 : 1;
5967
+ continue;
5968
+ }
5969
+ patternIdx = i;
5970
+ break;
5971
+ }
5972
+ if (patternIdx === null || patternIdx >= tokens.length) return seg;
5973
+ tokens.splice(patternIdx, 1);
5974
+ return tokens.map((t) => /\s/.test(t) ? `'${t.replaceAll("'", "'\\''")}'` : t).join(" ");
5975
+ }
5718
5976
  function stripSearchPatternLiterals(actionDetail) {
5719
5977
  const parts = [];
5720
5978
  for (const seg of splitCommandSegments2(actionDetail)) {
5979
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) {
5980
+ parts.push(seg);
5981
+ continue;
5982
+ }
5721
5983
  const low = seg.trim().toLowerCase();
5722
5984
  const words = low.length ? low.split(/\s+/) : [];
5723
5985
  let idx = 0;
5724
5986
  while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
5725
5987
  const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
5726
5988
  if (isSearch && !low.includes("--pre")) {
5727
- parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
5989
+ parts.push(stripSearchPatternArgument(seg));
5728
5990
  } else {
5729
5991
  parts.push(seg);
5730
5992
  }
@@ -6049,7 +6311,7 @@ function checkDangerousPatterns(actionType, actionDetail) {
6049
6311
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
6050
6312
  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
6313
  const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
6052
- if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
6314
+ if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
6053
6315
  return {
6054
6316
  allowed: false,
6055
6317
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -6191,7 +6453,7 @@ function checkLateralMovement(actionDetail) {
6191
6453
  }
6192
6454
  return null;
6193
6455
  }
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;
6456
+ 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
6457
  var init_heuristic = __esm({
6196
6458
  "src/engine/heuristic.ts"() {
6197
6459
  "use strict";
@@ -6240,6 +6502,28 @@ var init_heuristic = __esm({
6240
6502
  COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
6241
6503
  TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
6242
6504
  COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
6505
+ SEARCH_OPTION_WITH_ARG = /* @__PURE__ */ new Set([
6506
+ "-m",
6507
+ "--max-count",
6508
+ "-A",
6509
+ "--after-context",
6510
+ "-B",
6511
+ "--before-context",
6512
+ "-C",
6513
+ "--context",
6514
+ "-d",
6515
+ "--directories",
6516
+ "-D",
6517
+ "--devices",
6518
+ "--include",
6519
+ "--exclude",
6520
+ "--exclude-dir",
6521
+ "--glob",
6522
+ "--iglob",
6523
+ "--type",
6524
+ "--type-add",
6525
+ "--type-not"
6526
+ ]);
6243
6527
  SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
6244
6528
  SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
6245
6529
  SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
@@ -9141,6 +9425,9 @@ async function runLLMAnalysis(input, previous) {
9141
9425
  scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
9142
9426
  }
9143
9427
  const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
9428
+ const budgetMode = getAgentMossSetting("AGENT_MOSS_LLM_BUDGET_MODE", "hard").trim().toLowerCase() === "soft" ? "soft" : "hard";
9429
+ const budgetActive = maxPromptTokens > 0;
9430
+ const tokenLimit = budgetActive && budgetMode === "hard" ? Math.floor(maxPromptTokens * 100 / 115) : maxPromptTokens;
9144
9431
  let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
9145
9432
  let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
9146
9433
  let prompt = "";
@@ -9157,13 +9444,14 @@ async function runLLMAnalysis(input, previous) {
9157
9444
  historyMaxItems,
9158
9445
  historyMaxChars
9159
9446
  );
9160
- if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
9447
+ if (!budgetActive || estimateTokens(prompt) <= tokenLimit) break;
9161
9448
  historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
9162
9449
  historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
9163
9450
  }
9164
- if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
9451
+ let budgetCode = "";
9452
+ if (budgetActive && estimateTokens(prompt) > tokenLimit) {
9165
9453
  const estimated = estimateTokens(prompt);
9166
- const ratio = estimated / maxPromptTokens;
9454
+ const ratio = tokenLimit > 0 ? estimated / tokenLimit : Number.POSITIVE_INFINITY;
9167
9455
  const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
9168
9456
  const truncated = truncateDetail(input.aNext.actionDetail, allowed);
9169
9457
  prompt = buildPrompt(
@@ -9179,8 +9467,14 @@ async function runLLMAnalysis(input, previous) {
9179
9467
  historyMaxChars
9180
9468
  );
9181
9469
  console.warn(
9182
- `[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`
9470
+ `[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
9471
  );
9472
+ if (estimateTokens(prompt) > tokenLimit) {
9473
+ if (budgetMode === "hard") {
9474
+ throw new LLMPromptBudgetExceeded("l3_budget_unreachable");
9475
+ }
9476
+ budgetCode = "l3_budget_unreachable";
9477
+ }
9184
9478
  }
9185
9479
  logPrompt(prompt, input.aNext, previous.llmLogPath);
9186
9480
  traceFull("l3.prompt", {
@@ -9193,6 +9487,7 @@ async function runLLMAnalysis(input, previous) {
9193
9487
  prompt_chars: prompt.length
9194
9488
  });
9195
9489
  const result = await analyzeWithLLM(prompt, config);
9490
+ if (budgetCode) result.degraded = [...result.degraded || [], budgetCode];
9196
9491
  traceSummary("l3.verdict", {
9197
9492
  allowed: result.allowed,
9198
9493
  risk_level: result.riskLevel,
@@ -9266,11 +9561,14 @@ function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis,
9266
9561
  const skillsText = formatSkillsForPrompt(matchedSkills);
9267
9562
  const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
9268
9563
  const promptHistoryText = formatPromptHistory(input.promptHistory);
9564
+ const historyAuthorization = /(因历史窗口上限省略|本段因长度上限已截断)/.test(promptHistoryText) ? `
9565
+
9566
+ ${HISTORY_AUTHORIZATION}` : "";
9269
9567
  const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
9270
9568
  const hintsText = formatHints(previous);
9271
9569
  const securityJudgeTemplate = templates["security_judge"];
9272
9570
  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("}}", "}");
9571
+ 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
9572
  }
9275
9573
  console.warn("[AgentMoss] security_judge template missing, using sparse fallback prompt");
9276
9574
  return `## \u5F53\u524D\u64CD\u4F5C\u4E0A\u4E0B\u6587
@@ -9306,21 +9604,28 @@ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNu
9306
9604
  }
9307
9605
  const limit = Math.max(0, Math.floor(maxTurns));
9308
9606
  const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
9607
+ let omitted = 0;
9309
9608
  const lines = [];
9310
- for (let i = firstTurnIndex; i < promptHistory.length; i++) {
9609
+ for (let i = 0; i < promptHistory.length; i++) {
9311
9610
  const turn = promptHistory[i];
9312
9611
  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
9612
  const actions = typeof turn === "string" ? void 0 : turn?.actions;
9316
- if (actions && actions.length > 0) {
9317
- const types = actions.map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
9318
- if (types.length > 0) {
9319
- line += ` \u2192 \u52A8\u4F5C: ${types.join(", ")}`;
9320
- }
9613
+ const types = (actions || []).map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
9614
+ if (!text && types.length === 0) continue;
9615
+ if (i < firstTurnIndex) {
9616
+ omitted += 1;
9617
+ continue;
9618
+ }
9619
+ if (!text) {
9620
+ lines.push(` \u7B2C${i + 1}\u8F6E\u52A8\u4F5C: ${types.join(", ")}`);
9621
+ continue;
9321
9622
  }
9322
- lines.push(line);
9623
+ let shown = text.slice(0, maxTextChars);
9624
+ if (shown.length < text.length) shown += "\uFF08\u672C\u6BB5\u56E0\u957F\u5EA6\u4E0A\u9650\u5DF2\u622A\u65AD\uFF09";
9625
+ const suffix = types.length > 0 ? ` \u2192 \u52A8\u4F5C: ${types.join(", ")}` : "";
9626
+ lines.push(` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${shown}${suffix}`);
9323
9627
  }
9628
+ if (omitted) lines.unshift(`\uFF08\u56E0\u5386\u53F2\u7A97\u53E3\u4E0A\u9650\u7701\u7565 ${omitted} \u8F6E\u66F4\u65E9\u5386\u53F2\u610F\u56FE\uFF09`);
9324
9629
  return lines.length > 0 ? lines.join("\n") : "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
9325
9630
  }
9326
9631
  function formatHints(previous) {
@@ -9333,11 +9638,15 @@ function formatHints(previous) {
9333
9638
  );
9334
9639
  }
9335
9640
  if (previous.logic) {
9336
- hints.push(
9337
- `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
9641
+ if (previous.logic.l3Hint) {
9642
+ hints.push(`\u2139\uFE0F ${previous.logic.l3Hint}`);
9643
+ } else {
9644
+ hints.push(
9645
+ `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
9338
9646
  \u7C7B\u578B: ${previous.logic.riskType}
9339
9647
  \u539F\u56E0: ${previous.logic.reason}`
9340
- );
9648
+ );
9649
+ }
9341
9650
  }
9342
9651
  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
9652
  }
@@ -9549,7 +9858,7 @@ async function analyzeWithLLM(prompt, config) {
9549
9858
  clearTimeout(totalTimeoutTimer);
9550
9859
  throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
9551
9860
  }
9552
- var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
9861
+ var LLMPromptBudgetExceeded, HISTORY_AUTHORIZATION, LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
9553
9862
  var init_llm_analyzer = __esm({
9554
9863
  "src/engine/llm-analyzer.ts"() {
9555
9864
  "use strict";
@@ -9563,6 +9872,15 @@ var init_llm_analyzer = __esm({
9563
9872
  init_trace_log();
9564
9873
  init_metrics();
9565
9874
  init_circuit_breaker();
9875
+ LLMPromptBudgetExceeded = class extends Error {
9876
+ code;
9877
+ constructor(code) {
9878
+ super(code);
9879
+ this.name = "LLMPromptBudgetExceeded";
9880
+ this.code = code;
9881
+ }
9882
+ };
9883
+ 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
9884
  LLMCircuitOpenError = class extends Error {
9567
9885
  constructor(message) {
9568
9886
  super(message);
@@ -10740,11 +11058,35 @@ function checkMCRules(graph) {
10740
11058
  for (const rule of rules) {
10741
11059
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
10742
11060
  if (ruleViolates(rule, trace2, witnessMode)) {
11061
+ const pathNodes = nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3);
11062
+ const path9 = pathNodes.map((n) => ({
11063
+ sessionId: n.sessionId,
11064
+ seq: n.seq,
11065
+ detail: n.actionDetail.slice(0, 60)
11066
+ }));
10743
11067
  violations.push({
10744
11068
  propertyId: String(rule.id || "mc-ltl"),
10745
11069
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
10746
11070
  riskLevel: String(rule.risk_level || "high"),
10747
- path: nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3).map((n) => ({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }))
11071
+ path: path9,
11072
+ graph: {
11073
+ property_id: String(rule.id || "mc-ltl"),
11074
+ property_short: "P6",
11075
+ property_name: "LTL \u6A21\u578B\u68C0\u6D4B",
11076
+ nodes: pathNodes.map((n) => ({
11077
+ session_id: n.sessionId,
11078
+ seq: n.seq,
11079
+ stage: n.stage,
11080
+ action_detail: n.actionDetail,
11081
+ resources: [...n.resources].sort(),
11082
+ instance_id: n.instanceId || ""
11083
+ })),
11084
+ edges: pathNodes.slice(1).map((_, i) => ({
11085
+ from: i,
11086
+ to: i + 1,
11087
+ type: "next"
11088
+ }))
11089
+ }
10748
11090
  });
10749
11091
  if (witnessMode) return violations;
10750
11092
  }
@@ -11444,11 +11786,17 @@ function checkLowIntegrityCommandExec(graph) {
11444
11786
  for (const i of candidates) {
11445
11787
  const n = nodes[i];
11446
11788
  if (lowAt.has(i) && isComputeNode(n)) {
11789
+ const path9 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11447
11790
  violations.push({
11448
11791
  propertyId: "low-integrity-command-exec",
11449
11792
  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
11793
  riskLevel: "critical",
11451
- path: [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }]
11794
+ path: path9,
11795
+ graph: graphFromPath(nodes, path9, "next", {
11796
+ property_id: "low-integrity-command-exec",
11797
+ property_short: "P7",
11798
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u547D\u4EE4\u6267\u884C"
11799
+ }, ["sink"])
11452
11800
  });
11453
11801
  if (witness !== void 0) return violations;
11454
11802
  }
@@ -11490,11 +11838,21 @@ function checkCrossSessionReachability(graph) {
11490
11838
  if (reached.has(i)) {
11491
11839
  const srcIdx = Math.min(...sources);
11492
11840
  const srcDesc = nodes[srcIdx].actionDetail.slice(0, 40);
11841
+ const path9 = nodes.slice(-3).map((m) => ({
11842
+ sessionId: m.sessionId,
11843
+ seq: m.seq,
11844
+ detail: m.actionDetail.slice(0, 60)
11845
+ }));
11493
11846
  violations.push({
11494
11847
  propertyId: "low-integrity-reachability",
11495
11848
  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
11849
  riskLevel: "high",
11497
- path: nodes.slice(-3).map((m) => ({ sessionId: m.sessionId, seq: m.seq, detail: m.actionDetail.slice(0, 60) }))
11850
+ path: path9,
11851
+ graph: graphFromPath(nodes, path9, "data", {
11852
+ property_id: "low-integrity-reachability",
11853
+ property_short: "P3",
11854
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u6D41\u53EF\u8FBE"
11855
+ })
11498
11856
  });
11499
11857
  if (witness !== void 0) return violations;
11500
11858
  }
@@ -11834,7 +12192,24 @@ function fingerprint(sessionId, actionType, actionDetail, calledAt) {
11834
12192
  ].join("\0");
11835
12193
  return createHash4("blake2b512").update(raw).digest("hex").slice(0, 16);
11836
12194
  }
11837
- var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, STAGES_PATTERNS, CHAINS, COMMON_DIR_RESOURCES2, MAX_NODES, TRUNCATED_DETAIL_RE, SHELL_ACTION_ALIASES, StatefulChainTracker;
12195
+ function gateOrder(action) {
12196
+ const callId = String(action?.gateCallId ?? "");
12197
+ const callTimeUs = Number(action?.gateCallTimeUs ?? 0);
12198
+ return callId && Number.isFinite(callTimeUs) && callTimeUs > 0 ? { callId, callTimeUs } : null;
12199
+ }
12200
+ function gateFingerprint(action, isError, agentId, instanceId, order) {
12201
+ const values = [
12202
+ String(action?.actionType ?? ""),
12203
+ String(action?.actionDetail ?? ""),
12204
+ String(action?.calledAt ?? ""),
12205
+ String(action?.agentId ?? agentId ?? ""),
12206
+ String(action?.instanceId ?? instanceId ?? ""),
12207
+ Boolean(isError),
12208
+ order.callTimeUs
12209
+ ];
12210
+ return createHash4("sha256").update(JSON.stringify(values)).digest("hex");
12211
+ }
12212
+ 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
12213
  var init_stateful = __esm({
11839
12214
  "src/engine/formal-engine/stateful.ts"() {
11840
12215
  "use strict";
@@ -11850,6 +12225,12 @@ var init_stateful = __esm({
11850
12225
  SOCK_RE = /([\w./-]*(?:\/tmp\/|\/var\/run\/|\.sock\b)[\w./-]*)/;
11851
12226
  UNIT_RE = /systemctl\s+(?:start|enable|restart)\s+([\w.-]+)/i;
11852
12227
  PORT_STAGE_RE = /LISTEN|PERSIST|SCAN/;
12228
+ StatefulAnalysisUnavailable = class extends Error {
12229
+ };
12230
+ UnconfirmedGateRetry = class extends StatefulAnalysisUnavailable {
12231
+ };
12232
+ GateCallConflict = class extends UnconfirmedGateRetry {
12233
+ };
11853
12234
  STAGES_PATTERNS = null;
11854
12235
  CHAINS = null;
11855
12236
  COMMON_DIR_RESOURCES2 = /* @__PURE__ */ new Set([
@@ -11893,6 +12274,8 @@ var init_stateful = __esm({
11893
12274
  aliveResources = {};
11894
12275
  seqNext = 0;
11895
12276
  seededKeys = /* @__PURE__ */ new Set();
12277
+ /** (sessionId, gateCallId) → 节点,用于 Gate 精确一次关联。 */
12278
+ gateNodes = /* @__PURE__ */ new Map();
11896
12279
  constructor(agentId = "") {
11897
12280
  this.agentId = agentId;
11898
12281
  loadRules();
@@ -11951,28 +12334,73 @@ var init_stateful = __esm({
11951
12334
  }
11952
12335
  return added;
11953
12336
  }
12337
+ resultOf(node, matched, exfil) {
12338
+ return {
12339
+ seq: this.seqNext,
12340
+ node,
12341
+ matched,
12342
+ pendingPrefixes: this.pendingPrefixes,
12343
+ exfil,
12344
+ get shouldBlock() {
12345
+ return this.matched !== null || this.exfil.length > 0;
12346
+ }
12347
+ };
12348
+ }
11954
12349
  /** 增量推进:把当前动作追加到时间线 → 链指针推进 → 判定。 */
11955
12350
  advance(args) {
11956
12351
  const { aNext, sessionId = "current", isError = false, agentId = "", instanceId = "" } = args;
11957
- const node = this.appendNode(aNext, sessionId, isError, agentId, instanceId);
12352
+ const order = gateOrder(aNext);
12353
+ const gateFingerprintValue = order ? gateFingerprint(aNext, isError, agentId, instanceId, order) : "";
12354
+ if (order) {
12355
+ const existing = this.gateNodes.get(this.gateKey(sessionId, order.callId));
12356
+ if (existing) {
12357
+ if (existing.confirmed) {
12358
+ if (existing.inputFingerprint === gateFingerprintValue && existing.gateCallTimeUs === order.callTimeUs) {
12359
+ return this.resultOf(existing, existing.confirmed.matched, existing.confirmed.exfil);
12360
+ }
12361
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u5185\u5BB9\u6216\u65F6\u95F4\u4E0D\u4E00\u81F4");
12362
+ }
12363
+ if (aNext.gateDeliveryUncertain === true) {
12364
+ throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
12365
+ }
12366
+ if (existing.gateCallTimeUs !== order.callTimeUs) {
12367
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u65F6\u95F4\u4E0D\u4E00\u81F4");
12368
+ }
12369
+ if (existing.inputFingerprint) {
12370
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u91CD\u590D\u8C03\u7528\u7F3A\u5C11\u9001\u8FBE\u4E0D\u786E\u5B9A\u6807\u8BB0");
12371
+ }
12372
+ return this.resultOf(existing, null, []);
12373
+ }
12374
+ if (aNext.gateDeliveryUncertain === true) {
12375
+ throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
12376
+ }
12377
+ }
12378
+ const node = this.appendNode(
12379
+ order ? {
12380
+ ...aNext,
12381
+ gateCallId: order.callId,
12382
+ gateCallTimeUs: order.callTimeUs,
12383
+ gateInputFingerprint: gateFingerprintValue
12384
+ } : aNext,
12385
+ sessionId,
12386
+ isError,
12387
+ agentId,
12388
+ instanceId
12389
+ );
11958
12390
  if (!node) {
11959
- return { seq: this.seqNext, node: null, matched: null, pendingPrefixes: this.pendingPrefixes, exfil: [], shouldBlock: false };
12391
+ return this.resultOf(null, null, []);
11960
12392
  }
11961
12393
  const seq = this.seqNext;
11962
12394
  this.recordLifecycle(node);
11963
12395
  const matched = this.advanceChains(node);
11964
12396
  this.advanceTaint(node);
11965
12397
  const exfil = this.checkExfilAfterTaint(node);
11966
- return {
11967
- seq,
11968
- node,
11969
- matched,
11970
- pendingPrefixes: this.pendingPrefixes,
11971
- exfil,
11972
- get shouldBlock() {
11973
- return this.matched !== null || this.exfil.length > 0;
11974
- }
11975
- };
12398
+ if (order) {
12399
+ node.confirmed = { matched, exfil };
12400
+ this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
12401
+ }
12402
+ void seq;
12403
+ return this.resultOf(node, matched, exfil);
11976
12404
  }
11977
12405
  /**
11978
12406
  * 自动轮转:归档旧节点,只保留最近 `retain` 条,并重建链指针/taint。
@@ -12009,6 +12437,7 @@ var init_stateful = __esm({
12009
12437
  this.taintOrigin.clear();
12010
12438
  this.aliveResources = {};
12011
12439
  this.seqNext = 0;
12440
+ this.gateNodes.clear();
12012
12441
  for (const n of kept) {
12013
12442
  const node = this.appendNode(
12014
12443
  {
@@ -12016,7 +12445,12 @@ var init_stateful = __esm({
12016
12445
  actionDetail: n.actionDetail,
12017
12446
  agentId: n.agentId,
12018
12447
  instanceId: n.instanceId,
12019
- ...n.timestamp ? { calledAt: n.timestamp } : {}
12448
+ ...n.timestamp ? { calledAt: n.timestamp } : {},
12449
+ ...n.gateCallId ? {
12450
+ gateCallId: n.gateCallId,
12451
+ gateCallTimeUs: n.gateCallTimeUs,
12452
+ gateInputFingerprint: n.inputFingerprint
12453
+ } : {}
12020
12454
  },
12021
12455
  n.sessionId,
12022
12456
  n.isError,
@@ -12024,6 +12458,7 @@ var init_stateful = __esm({
12024
12458
  n.instanceId
12025
12459
  );
12026
12460
  if (node) {
12461
+ if (n.confirmed) node.confirmed = n.confirmed;
12027
12462
  this.recordLifecycle(node);
12028
12463
  this.advanceTaint(node);
12029
12464
  this.advanceChains(node);
@@ -12031,6 +12466,9 @@ var init_stateful = __esm({
12031
12466
  }
12032
12467
  return { archived: old.length, file };
12033
12468
  }
12469
+ gateKey(sessionId, callId) {
12470
+ return `${sessionId}\0${callId}`;
12471
+ }
12034
12472
  appendNode(action, sessionId, isError = false, agentId = "", instanceId = "") {
12035
12473
  const ad = String(action.actionDetail || "");
12036
12474
  const at = String(action.actionType || "");
@@ -12062,6 +12500,13 @@ var init_stateful = __esm({
12062
12500
  lifecycle: lifecycleFor(ad, stage, isError),
12063
12501
  timestamp: suppliedCalledAt || _StatefulChainTracker.now()
12064
12502
  };
12503
+ const order = gateOrder(action);
12504
+ if (order) {
12505
+ node.gateCallId = order.callId;
12506
+ node.gateCallTimeUs = order.callTimeUs;
12507
+ node.inputFingerprint = String(action.gateInputFingerprint || "");
12508
+ this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
12509
+ }
12065
12510
  this.nodes_.push(node);
12066
12511
  this.seqNext += 1;
12067
12512
  if (dedupeKey) this.seededKeys.add(dedupeKey);
@@ -12413,11 +12858,19 @@ var init_stateful = __esm({
12413
12858
  // 旧快照无此字段 → 空
12414
12859
  isError: Boolean(raw.isError),
12415
12860
  lifecycle: String(raw.lifecycle || ""),
12416
- timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null
12861
+ timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null,
12417
12862
  // 旧快照无此字段 → null
12863
+ ...raw.gateCallId ? { gateCallId: String(raw.gateCallId) } : {},
12864
+ ...raw.gateCallTimeUs ? { gateCallTimeUs: Number(raw.gateCallTimeUs) } : {},
12865
+ ...raw.inputFingerprint ? { inputFingerprint: String(raw.inputFingerprint) } : {},
12866
+ ...raw.confirmed ? { confirmed: raw.confirmed } : {}
12418
12867
  });
12419
12868
  }
12420
12869
  this.seqNext = Number(snapshot.seq_next || this.nodes_.length);
12870
+ this.gateNodes = /* @__PURE__ */ new Map();
12871
+ for (const n of this.nodes_) {
12872
+ if (n.gateCallId) this.gateNodes.set(this.gateKey(n.sessionId, n.gateCallId), n);
12873
+ }
12421
12874
  for (const n of this.nodes_) {
12422
12875
  if (n.timestamp) {
12423
12876
  this.seededKeys.add(fingerprint(n.sessionId, n.actionType, n.actionDetail, n.timestamp));
@@ -12878,9 +13331,19 @@ async function runAnalysis(input) {
12878
13331
  isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
12879
13332
  isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
12880
13333
  );
13334
+ const degradedNotes = [];
12881
13335
  let scriptChain = null;
12882
- if (input.aNext.actionType.toLowerCase() === "bash") {
13336
+ if (input.aNext.actionType.toLowerCase() === "bash" && getDeployRole() === "host") {
13337
+ degradedNotes.push("script_content_deferred_to_sandbox: AGENT_MOSS_DEPLOY_ROLE=host");
13338
+ } else if (input.aNext.actionType.toLowerCase() === "bash") {
12883
13339
  scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
13340
+ if (scriptChain.nodes.length > 0) {
13341
+ for (const node of scriptChain.nodes) {
13342
+ if (node.error && !node.unanalyzable) {
13343
+ degradedNotes.push(`script_content_unavailable: ${node.scriptPath} (${node.error})`);
13344
+ }
13345
+ }
13346
+ }
12884
13347
  if (heuristicEnabled && scriptChain.nodes.length > 0) {
12885
13348
  for (const node of scriptChain.nodes) {
12886
13349
  if (node.unanalyzable) {
@@ -13151,7 +13614,8 @@ async function runAnalysis(input) {
13151
13614
  riskType: "",
13152
13615
  confidence: 85,
13153
13616
  source: "heuristic_and_logic_only",
13154
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
13617
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
13618
+ degraded: degradedNotes
13155
13619
  };
13156
13620
  }
13157
13621
  let skipL3Hints = "\u65E0\uFF08\u5F53\u524D\u65E0\u7981\u7528\u89C4\u5219\u547D\u4E2D\uFF09";
@@ -13188,8 +13652,22 @@ async function runAnalysis(input) {
13188
13652
  pathContext
13189
13653
  });
13190
13654
  } catch (e) {
13191
- const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
13192
13655
  const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
13656
+ if (e instanceof LLMPromptBudgetExceeded) {
13657
+ const failMode = getLLMFailMode2();
13658
+ const allowed = failMode === "fail_open";
13659
+ return {
13660
+ allowed,
13661
+ reason: `L3 prompt \u8D85\u51FA\u786C\u9884\u7B97\uFF0C\u5DF2\u8DF3\u8FC7\u8BED\u4E49\u5206\u6790\uFF0C\u6309 ${failMode} ${allowed ? "\u653E\u884C" : "\u62D2\u7EDD"}`,
13662
+ riskLevel: allowed ? "low" : "medium",
13663
+ riskType: "",
13664
+ confidence: allowed ? 50 : 60,
13665
+ source: "llm_budget_skipped",
13666
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
13667
+ degraded: [...degradedNotes, e.code]
13668
+ };
13669
+ }
13670
+ const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
13193
13671
  if (getLLMFailMode2() === "fail_open") {
13194
13672
  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
13673
  return {
@@ -13199,7 +13677,8 @@ async function runAnalysis(input) {
13199
13677
  riskType: "",
13200
13678
  confidence: 50,
13201
13679
  source: failSource,
13202
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
13680
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
13681
+ degraded: degradedNotes
13203
13682
  };
13204
13683
  }
13205
13684
  return {
@@ -13209,7 +13688,10 @@ async function runAnalysis(input) {
13209
13688
  riskType: "",
13210
13689
  confidence: 60,
13211
13690
  source: failSource,
13212
- violatedLayers: ["L3.1"]
13691
+ violatedLayers: ["L3.1"],
13692
+ degraded: degradedNotes,
13693
+ ask_recommended: true,
13694
+ 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
13695
  };
13214
13696
  }
13215
13697
  if (!llmResult.allowed && llmResult.confidence && llmResult.confidence >= 90 && _brainExtractor) {
@@ -13229,6 +13711,9 @@ async function runAnalysis(input) {
13229
13711
  if (observedFormalLayers.length > 0 && llmResult.allowed) {
13230
13712
  llmResult.violatedLayers = Array.from(/* @__PURE__ */ new Set([...observedFormalLayers, ...llmResult.violatedLayers || []]));
13231
13713
  }
13714
+ if (degradedNotes.length > 0) {
13715
+ llmResult.degraded = Array.from(/* @__PURE__ */ new Set([...llmResult.degraded || [], ...degradedNotes]));
13716
+ }
13232
13717
  return llmResult;
13233
13718
  }
13234
13719
  var TRUSTED_SKILLS_BASE, _brainStore, _brainExtractor, _brainSkillManager, _brainCurator, _brainInitialized, _brainLastMaintenance, BRAIN_MAINT_INTERVAL_MS, formalEngine;
@@ -13475,7 +13960,11 @@ var AnalyzeRequestSchema = z.object({
13475
13960
  cwd: z.string().default("").describe("Current working directory"),
13476
13961
  agent_id: z.string().default("").describe("Caller agent identifier, e.g. 'xiaoo' / 'opencode' / 'opendesk'. Empty = generic mode (no agent-specific rules)."),
13477
13962
  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")
13963
+ metadata: z.record(z.unknown()).optional().describe("Extended metadata"),
13964
+ // 仅在 AgentGate 专用身份通过后校验;直连调用方传这些字段会被忽略。
13965
+ gate_call_id: z.unknown().optional(),
13966
+ gate_call_time_us: z.unknown().optional(),
13967
+ gate_delivery_uncertain: z.unknown().optional()
13479
13968
  });
13480
13969
  var AnalyzeResponseSchema = z.object({
13481
13970
  decision: z.enum(["Allow", "Deny"]).describe("Allow or Deny"),
@@ -13505,6 +13994,11 @@ var AnalyzeResponseSchema = z.object({
13505
13994
  ""
13506
13995
  // 未算出(极端异常路径)
13507
13996
  ]).default(""),
13997
+ /** Deny 但建议向用户确认(旧 agent 忽略仍是 Deny) */
13998
+ ask_recommended: z.boolean().default(false),
13999
+ ask_reason: z.string().default(""),
14000
+ /** Gate 专用调用回显;直连调用为空。 */
14001
+ gate_call_id: z.string().optional(),
13508
14002
  // 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
13509
14003
  violation_graph: z.object({
13510
14004
  // 性质元信息(前端展示"违反了哪条性质")
@@ -13597,7 +14091,7 @@ function deriveL3Outcome(j) {
13597
14091
  if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
13598
14092
  if (src === "llm_circuit_open") return "circuit_open";
13599
14093
  if (src === "llm_failure_with_violation") return "failed_but_blocked";
13600
- if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
14094
+ if (src === "heuristic_and_logic_only" || src === "disabled" || src === "llm_budget_skipped") return "skipped";
13601
14095
  return "not_reached";
13602
14096
  }
13603
14097
 
@@ -14168,6 +14662,7 @@ function reportEnforcementEvent(opts) {
14168
14662
 
14169
14663
  // src/routes.ts
14170
14664
  init_formal_engine();
14665
+ init_stateful();
14171
14666
  init_circuit_breaker();
14172
14667
 
14173
14668
  // src/engine/formal-engine/pattern_miner.ts
@@ -14267,6 +14762,16 @@ function normalizeAction(row) {
14267
14762
  actionDetail: String(row.action_detail || row.command || row.input || "")
14268
14763
  };
14269
14764
  if (row.called_at) act.calledAt = String(row.called_at);
14765
+ try {
14766
+ const audit = JSON.parse(String(row.moss_response || "{}"));
14767
+ if (audit && audit._gate_protocol_rejected === true) {
14768
+ act.gateProtocolRejected = true;
14769
+ } 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) {
14770
+ act.gateCallId = audit._gate_call_id;
14771
+ act.gateCallTimeUs = audit._gate_call_time_us;
14772
+ }
14773
+ } catch {
14774
+ }
14270
14775
  return act;
14271
14776
  }
14272
14777
  function readJsonDir(dirPath, limit = 1e5, strict = false) {
@@ -14307,10 +14812,18 @@ function readSqlite(dbPath, limit = 1e5, strict = false) {
14307
14812
  let db;
14308
14813
  try {
14309
14814
  db = new Database(dbPath, { readonly: true });
14310
- const rows = db.prepare(
14311
- `SELECT session_id, action_type, tool_name, action_detail, command, called_at
14312
- FROM tool_calls ORDER BY called_at, id LIMIT ?`
14313
- ).all(limit);
14815
+ let rows;
14816
+ try {
14817
+ rows = db.prepare(
14818
+ `SELECT session_id, action_type, tool_name, action_detail, command, called_at, moss_response
14819
+ FROM tool_calls ORDER BY called_at, id LIMIT ?`
14820
+ ).all(limit);
14821
+ } catch {
14822
+ rows = db.prepare(
14823
+ `SELECT session_id, action_type, tool_name, action_detail, command, called_at
14824
+ FROM tool_calls ORDER BY called_at, id LIMIT ?`
14825
+ ).all(limit);
14826
+ }
14314
14827
  const sessions = /* @__PURE__ */ new Map();
14315
14828
  for (const r of rows) {
14316
14829
  const sid = String(r.session_id || "");
@@ -14520,6 +15033,10 @@ async function analyzeRoute(c) {
14520
15033
  try {
14521
15034
  const body = await c.req.json();
14522
15035
  const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
15036
+ const gateCallId = String(c.get("gateCallId") || "");
15037
+ if (gateCallId && (req.gate_call_id !== gateCallId || !validGateCallTime(req.gate_call_time_us) || typeof req.gate_delivery_uncertain !== "boolean")) {
15038
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5143\u6570\u636E\u65E0\u6548" }, 422);
15039
+ }
14523
15040
  const unmappedTool = String(
14524
15041
  req.metadata?.unmapped_tool || ""
14525
15042
  );
@@ -14632,7 +15149,16 @@ async function analyzeRoute(c) {
14632
15149
  const store = getChainStateStoreFor(agentId);
14633
15150
  const inc = store.applyAction(
14634
15151
  chainBucket(agentId),
14635
- { actionType: req.a_next.action_type, actionDetail: req.a_next.action_detail },
15152
+ {
15153
+ actionType: req.a_next.action_type,
15154
+ actionDetail: req.a_next.action_detail,
15155
+ ...req.a_next.called_at ? { calledAt: req.a_next.called_at } : {},
15156
+ ...gateCallId ? {
15157
+ gateCallId,
15158
+ gateCallTimeUs: req.gate_call_time_us,
15159
+ gateDeliveryUncertain: req.gate_delivery_uncertain === true
15160
+ } : {}
15161
+ },
14636
15162
  req.session_id,
14637
15163
  Boolean(meta.is_error),
14638
15164
  agentId,
@@ -14655,7 +15181,31 @@ async function analyzeRoute(c) {
14655
15181
  }
14656
15182
  finding = incMatchedToDeny(inc);
14657
15183
  } catch (err) {
14658
- console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
15184
+ if (err instanceof UnconfirmedGateRetry) {
15185
+ const reason = "AgentMoss \u65E0\u6CD5\u786E\u8BA4\u672C\u6B21 Gate \u8C03\u7528\u662F\u5426\u5DF2\u5165\u94FE";
15186
+ degradedNotes.push(`\u3010\u5DF2\u964D\u7EA7\u3011${reason}\uFF1B\u672C\u6B21\u6309\u62D2\u7EDD\u5904\u7406\uFF0C\u907F\u514D\u91CD\u590D\u5165\u94FE\u3002`);
15187
+ if (result.decision !== "Deny") {
15188
+ result = {
15189
+ ...result,
15190
+ decision: "Deny",
15191
+ reason,
15192
+ risk_type: "service_unavailable",
15193
+ risk_level: "high",
15194
+ policy: "",
15195
+ ask_recommended: true,
15196
+ 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"
15197
+ };
15198
+ }
15199
+ } else if (err instanceof StatefulAnalysisUnavailable) {
15200
+ degradedNotes.push(
15201
+ "\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"
15202
+ );
15203
+ } else {
15204
+ console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
15205
+ degradedNotes.push(
15206
+ "\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"
15207
+ );
15208
+ }
14659
15209
  }
14660
15210
  }
14661
15211
  result = publicFormalResult(
@@ -14666,6 +15216,11 @@ async function analyzeRoute(c) {
14666
15216
  req.session_history || []
14667
15217
  );
14668
15218
  const durationMs = performance.now() - t0;
15219
+ if (Array.isArray(result.degraded)) {
15220
+ for (const note of result.degraded) {
15221
+ if (note && !degradedNotes.includes(note)) degradedNotes.push(note);
15222
+ }
15223
+ }
14669
15224
  const _l3FailMsg = String(result.reason || "").slice(0, 160);
14670
15225
  if (result.l3_outcome === "reasoning_fallback") {
14671
15226
  degradedNotes.push(
@@ -14755,7 +15310,10 @@ async function analyzeRoute(c) {
14755
15310
  degraded: degradedNotes,
14756
15311
  // L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
14757
15312
  // 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
14758
- l3_outcome: result.l3_outcome || ""
15313
+ l3_outcome: result.l3_outcome || "",
15314
+ ask_recommended: result.ask_recommended === true,
15315
+ ask_reason: String(result.ask_reason || ""),
15316
+ ...gateCallId ? { gate_call_id: gateCallId } : {}
14759
15317
  })
14760
15318
  );
14761
15319
  } catch (err) {
@@ -14912,7 +15470,11 @@ async function reviewRoute(c) {
14912
15470
  if (!tracker) {
14913
15471
  tracker = new StatefulChainTracker(bucket);
14914
15472
  }
14915
- const added = sessions.length > 0 ? tracker.seed(sessions) : 0;
15473
+ const seedSessions = sessions.map((s) => ({
15474
+ ...s,
15475
+ actionHistory: (s.actionHistory || []).filter((a) => !a.gateProtocolRejected)
15476
+ }));
15477
+ const added = seedSessions.length > 0 ? tracker.seed(seedSessions) : 0;
14916
15478
  store.save(tracker);
14917
15479
  let verified = true;
14918
15480
  const violations = [];
@@ -15624,9 +16186,29 @@ function createApp() {
15624
16186
  if (!okAuth && !isPublicPage) {
15625
16187
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
15626
16188
  }
16189
+ let gateCallId = null;
16190
+ const gateRequired = c.req.header(GATE_IDENTITY_HEADER);
16191
+ const gatePath = path9.replace(/\/+$/, "");
16192
+ if (method === "POST" && gateRequired !== void 0 && (gatePath === "/api/v1/analyze" || gatePath === "/api/v1/review")) {
16193
+ if (principal !== GATE_PRINCIPAL) {
16194
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8EAB\u4EFD\u6821\u9A8C\u5931\u8D25" }, 403);
16195
+ }
16196
+ if (gateRequired !== "1") {
16197
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
16198
+ }
16199
+ }
16200
+ if (method === "POST" && gatePath === "/api/v1/analyze" && principal === GATE_PRINCIPAL) {
16201
+ const id = c.req.header(GATE_CALL_ID_HEADER) || "";
16202
+ if (gateRequired !== "1" || !validGateCallId(id)) {
16203
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
16204
+ }
16205
+ gateCallId = id;
16206
+ c.set("gateCallId", id);
16207
+ }
15627
16208
  if (limiter.enabled && path9.startsWith("/api/")) {
15628
16209
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
15629
16210
  if (!limiter.allow(key)) {
16211
+ if (gateCallId) c.header(GATE_RATE_LIMIT_HEADER, gateCallId);
15630
16212
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
15631
16213
  }
15632
16214
  }
@@ -15642,6 +16224,7 @@ function createApp() {
15642
16224
  const busy = (detail, status = 503) => {
15643
16225
  c.header("Retry-After", "1");
15644
16226
  c.header("Connection", "close");
16227
+ if (gateCallId) c.header(GATE_BUSY_HEADER, gateCallId);
15645
16228
  return c.json({ detail }, status);
15646
16229
  };
15647
16230
  try {