@kenhkl/agent-moss 0.17.41 → 0.17.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -918,6 +918,12 @@ function originAllowed(origin, hostHeader, extra) {
918
918
  return false;
919
919
  }
920
920
  }
921
+ function validGateCallId(value) {
922
+ return typeof value === "string" && /^[0-9a-f]{32}$/.test(value);
923
+ }
924
+ function validGateCallTime(value) {
925
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= Number.MAX_SAFE_INTEGER;
926
+ }
921
927
  function authMode() {
922
928
  return (env("AGENT_MOSS_AUTH_MODE", AUTH_MODE_AUTO) || AUTH_MODE_AUTO).toLowerCase();
923
929
  }
@@ -1012,13 +1018,17 @@ function parseAgentTokens(raw) {
1012
1018
  }
1013
1019
  function resolveAuth() {
1014
1020
  const rawAgents = env("AGENT_MOSS_AGENT_TOKENS");
1021
+ const gateToken = env("AGENT_MOSS_GATE_AUTH_TOKEN");
1022
+ const consoleToken = env("AGENT_MOSS_CONSOLE_TOKEN");
1015
1023
  const key = [
1016
1024
  authMode(),
1017
1025
  env("AGENT_MOSS_AUTH_TOKEN"),
1018
1026
  env("AGENT_MOSS_AUTH_TOKEN_FILE"),
1019
1027
  env("AGENT_MOSS_AUTH_TOKEN_FD"),
1020
1028
  rawAgents,
1021
- env("AGENT_MOSS_DATA_DIR")
1029
+ env("AGENT_MOSS_DATA_DIR"),
1030
+ gateToken,
1031
+ consoleToken
1022
1032
  ].join("\0");
1023
1033
  if (tokenCache && tokenCache.key === key) {
1024
1034
  return [tokenCache.token, tokenCache.agents, tokenCache.error];
@@ -1041,6 +1051,13 @@ function resolveAuth() {
1041
1051
  }
1042
1052
  }
1043
1053
  const agents = parseAgentTokens(rawAgents);
1054
+ if (!error && authMode() === AUTH_MODE_OFF && gateToken) {
1055
+ error = "AGENT_MOSS_GATE_AUTH_TOKEN \u4E0D\u80FD\u5728 AGENT_MOSS_AUTH_MODE=off \u65F6\u542F\u7528";
1056
+ } else if (!error && gateToken) {
1057
+ if (gateToken === token || gateToken === consoleToken || Object.values(agents).includes(gateToken)) {
1058
+ error = "AGENT_MOSS_GATE_AUTH_TOKEN \u5FC5\u987B\u4E0E\u5168\u5C40\u3001Agent \u548C Console \u51ED\u636E\u4E0D\u540C";
1059
+ }
1060
+ }
1044
1061
  tokenCache = { key, token, agents, error };
1045
1062
  return [token, agents, error];
1046
1063
  }
@@ -1060,7 +1077,7 @@ function failFastOnAuthError() {
1060
1077
  function authEnabled() {
1061
1078
  if (authMode() === AUTH_MODE_OFF) return false;
1062
1079
  const [tok, agents, err] = resolveAuth();
1063
- return Boolean(err) || Boolean(tok) || Object.keys(agents).length > 0;
1080
+ return Boolean(err) || Boolean(tok) || Object.keys(agents).length > 0 || Boolean(env("AGENT_MOSS_GATE_AUTH_TOKEN"));
1064
1081
  }
1065
1082
  function bearer(headers) {
1066
1083
  const get = (k) => headers instanceof Headers ? headers.get(k) ?? "" : headers[k] ?? "";
@@ -1075,14 +1092,19 @@ function constEq(a, b) {
1075
1092
  }
1076
1093
  function checkRequestAuth(headers, path9) {
1077
1094
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
1078
- const isHealth = HEALTH_PATHS.includes(path9.replace(/\/+$/, ""));
1095
+ const normalizedPath = path9.replace(/\/+$/, "");
1096
+ const isHealth = HEALTH_PATHS.includes(normalizedPath);
1079
1097
  const [gt0, agents, err] = resolveAuth();
1098
+ const gateToken = env("AGENT_MOSS_GATE_AUTH_TOKEN");
1080
1099
  if (err) return isHealth ? [true, ""] : [false, ""];
1081
- if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
1100
+ if (!gt0 && Object.keys(agents).length === 0 && !gateToken) return [true, ""];
1082
1101
  if (isHealth) return [true, ""];
1083
1102
  const tok = bearer(headers);
1084
1103
  if (!tok) return [false, ""];
1085
- if (path9.startsWith("/console/api")) {
1104
+ if (gateToken && GATE_AUTH_PATHS.has(normalizedPath) && constEq(tok, gateToken)) {
1105
+ return [true, GATE_PRINCIPAL];
1106
+ }
1107
+ if (normalizedPath.startsWith("/console/api")) {
1086
1108
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
1087
1109
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
1088
1110
  }
@@ -1428,7 +1450,7 @@ function maxConnections() {
1428
1450
  function keepAliveSec() {
1429
1451
  return envInt("AGENT_MOSS_KEEP_ALIVE_SEC", 5);
1430
1452
  }
1431
- var TRUTHY2, HEALTH_PATHS, AUTH_MODE_AUTO, AUTH_MODE_OFF, tokenCache, fdTokenCache, BLOCKED_HOSTS, sessionWindow, queueRejects, POOL_DEFAULTS;
1453
+ 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;
1432
1454
  var init_security_policy = __esm({
1433
1455
  "src/infra/security-policy.ts"() {
1434
1456
  "use strict";
@@ -1438,6 +1460,12 @@ var init_security_policy = __esm({
1438
1460
  HEALTH_PATHS = ["/api/v1/health"];
1439
1461
  AUTH_MODE_AUTO = "auto";
1440
1462
  AUTH_MODE_OFF = "off";
1463
+ GATE_PRINCIPAL = "gate";
1464
+ GATE_IDENTITY_HEADER = "X-AgentGate-Require-Identity";
1465
+ GATE_CALL_ID_HEADER = "X-AgentGate-Call-Id";
1466
+ GATE_RATE_LIMIT_HEADER = "X-AgentGate-Rate-Limited-Call-Id";
1467
+ GATE_BUSY_HEADER = "X-AgentGate-Busy-Call-Id";
1468
+ GATE_AUTH_PATHS = /* @__PURE__ */ new Set(["/api/v1/analyze", "/api/v1/review"]);
1441
1469
  tokenCache = null;
1442
1470
  fdTokenCache = /* @__PURE__ */ new Map();
1443
1471
  BLOCKED_HOSTS = ["169.254.169.254", "metadata.google.internal", "metadata.tencentyun.com"];
@@ -1510,7 +1538,11 @@ var init_models = __esm({
1510
1538
  cwd: z.string().default("").describe("Current working directory"),
1511
1539
  agent_id: z.string().default("").describe("Caller agent identifier, e.g. 'xiaoo' / 'opencode' / 'opendesk'. Empty = generic mode (no agent-specific rules)."),
1512
1540
  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."),
1513
- metadata: z.record(z.unknown()).optional().describe("Extended metadata")
1541
+ metadata: z.record(z.unknown()).optional().describe("Extended metadata"),
1542
+ // 仅在 AgentGate 专用身份通过后校验;直连调用方传这些字段会被忽略。
1543
+ gate_call_id: z.unknown().optional(),
1544
+ gate_call_time_us: z.unknown().optional(),
1545
+ gate_delivery_uncertain: z.unknown().optional()
1514
1546
  });
1515
1547
  AnalyzeResponseSchema = z.object({
1516
1548
  decision: z.enum(["Allow", "Deny"]).describe("Allow or Deny"),
@@ -1540,6 +1572,11 @@ var init_models = __esm({
1540
1572
  ""
1541
1573
  // 未算出(极端异常路径)
1542
1574
  ]).default(""),
1575
+ /** Deny 但建议向用户确认(旧 agent 忽略仍是 Deny) */
1576
+ ask_recommended: z.boolean().default(false),
1577
+ ask_reason: z.string().default(""),
1578
+ /** Gate 专用调用回显;直连调用为空。 */
1579
+ gate_call_id: z.string().optional(),
1543
1580
  // 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
1544
1581
  violation_graph: z.object({
1545
1582
  // 性质元信息(前端展示"违反了哪条性质")
@@ -2339,11 +2376,64 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
2339
2376
  }
2340
2377
  return false;
2341
2378
  }
2379
+ function intentKeywordNegated(text, index) {
2380
+ if (NEGATION_WORDS.length === 0 || index <= 0) return false;
2381
+ const prefix = text.slice(Math.max(0, index - NEGATION_WINDOW), index);
2382
+ return NEGATION_WORDS.some((neg) => prefix.includes(neg));
2383
+ }
2384
+ function isBuildArtifactCleanup(actionDetail) {
2385
+ const text = (actionDetail || "").trim();
2386
+ if (!text) return false;
2387
+ let foundRm = false;
2388
+ const targets = [];
2389
+ for (const raw of splitCommandSegments(text)) {
2390
+ const s = raw.trim();
2391
+ if (!s) continue;
2392
+ let parts = s.split(/\s+/);
2393
+ if (parts[0]?.toLowerCase() === "sudo" || parts[0]?.toLowerCase() === "command") {
2394
+ parts = parts.slice(1);
2395
+ }
2396
+ if (!parts.length || parts[0].toLowerCase() !== "rm") continue;
2397
+ foundRm = true;
2398
+ for (const rawTok of parts.slice(1)) {
2399
+ const tok = rawTok.replace(/^['"]+|['"]+$/g, "");
2400
+ if (!tok || tok.startsWith("-")) continue;
2401
+ targets.push(tok);
2402
+ }
2403
+ }
2404
+ if (!foundRm || targets.length === 0) return false;
2405
+ for (const target of targets) {
2406
+ let t = target.replace(/\\/g, "/");
2407
+ if (t.startsWith("/") || t.split("/").includes("..")) return false;
2408
+ while (t.startsWith("./")) t = t.slice(2);
2409
+ if (!t || [".", "*", "?"].includes(t)) return false;
2410
+ if (t.includes("*") || t.includes("?")) {
2411
+ if (!BUILD_ARTIFACT_GLOB_RE.test(t)) return false;
2412
+ continue;
2413
+ }
2414
+ const first = t.split("/")[0].toLowerCase();
2415
+ if (!BUILD_ARTIFACT_NAMES.has(first)) return false;
2416
+ }
2417
+ return true;
2418
+ }
2342
2419
  function intentCategories(text) {
2343
2420
  const t = (text || "").toLowerCase();
2344
2421
  const out = /* @__PURE__ */ new Set();
2345
2422
  for (const [cat, kws] of Object.entries(INTENT_CATEGORIES)) {
2346
- if (kws.some((kw) => t.includes(String(kw).toLowerCase()))) out.add(cat);
2423
+ for (const kw of kws) {
2424
+ const needle = String(kw).toLowerCase();
2425
+ let start = 0;
2426
+ while (true) {
2427
+ const idx = t.indexOf(needle, start);
2428
+ if (idx < 0) break;
2429
+ if (!intentKeywordNegated(t, idx)) {
2430
+ out.add(cat);
2431
+ break;
2432
+ }
2433
+ start = idx + needle.length;
2434
+ }
2435
+ if (out.has(cat)) break;
2436
+ }
2347
2437
  }
2348
2438
  return out;
2349
2439
  }
@@ -2446,6 +2536,52 @@ function checkIntentConsistency(input, agentExt) {
2446
2536
  }
2447
2537
  const actionCat = actionCategory(actionType, aNext.actionDetail, input.osType, extraWriteTools);
2448
2538
  const reasonKey = intentMatrixViolation(intents, actionCat);
2539
+ const isReferencePrompt = REFERENCE_PRIOR_RE.test((promptSession || "").trim().toLowerCase());
2540
+ if (reasonKey === "read->overwrite" && !EXPLICIT_READONLY_RE.test(intentText) && !isReferencePrompt) {
2541
+ console.debug(
2542
+ `[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)}`
2543
+ );
2544
+ return {
2545
+ allowed: true,
2546
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
2547
+ riskLevel: "low",
2548
+ riskType: "",
2549
+ confidence: 50,
2550
+ source: "logic_rule",
2551
+ violatedLayers: [],
2552
+ 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)}`
2553
+ };
2554
+ }
2555
+ if ((reasonKey === "read->delete" || reasonKey === "write->delete") && UPDATE_INTENT_RE.test(intentText) && !EXPLICIT_NO_DELETE_RE.test(intentText)) {
2556
+ console.debug(
2557
+ `[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)}`
2558
+ );
2559
+ return {
2560
+ allowed: true,
2561
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
2562
+ riskLevel: "low",
2563
+ riskType: "",
2564
+ confidence: 50,
2565
+ source: "logic_rule",
2566
+ violatedLayers: [],
2567
+ 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)}`
2568
+ };
2569
+ }
2570
+ if ((reasonKey === "read->delete" || reasonKey === "write->delete") && !isReferencePrompt && INTENT_AMBIGUITY_RE.test(intentText)) {
2571
+ console.debug(
2572
+ `[intent] \u610F\u56FE\u8BCD\u5B58\u5728\u6B67\u4E49\u4E0A\u4E0B\u6587\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
2573
+ );
2574
+ return {
2575
+ allowed: true,
2576
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
2577
+ riskLevel: "low",
2578
+ riskType: "",
2579
+ confidence: 50,
2580
+ source: "logic_rule",
2581
+ violatedLayers: [],
2582
+ 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)}`
2583
+ };
2584
+ }
2449
2585
  if (reasonKey !== null) {
2450
2586
  return {
2451
2587
  allowed: false,
@@ -2962,7 +3098,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2962
3098
  violatedLayers: ["L2.1"]
2963
3099
  };
2964
3100
  }
2965
- 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;
3101
+ 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;
2966
3102
  var init_logic_rules = __esm({
2967
3103
  "src/engine/logic-rules.ts"() {
2968
3104
  "use strict";
@@ -3064,6 +3200,31 @@ var init_logic_rules = __esm({
3064
3200
  (INTENT_MATRIX.delete_action_words || []).map((w) => String(w).toLowerCase())
3065
3201
  );
3066
3202
  ALL_INTENT_KEYWORDS = Object.values(INTENT_CATEGORIES).flat();
3203
+ NEGATION_WORDS = (INTENT_MATRIX.negation_words || []).map((w) => String(w).toLowerCase());
3204
+ NEGATION_WINDOW = 8;
3205
+ EXPLICIT_READONLY_RE = /(?:只读|仅读|只看|仅看|只查看|仅查看|只分析|仅分析|只做分析|只查询|仅查询|不要(?:修改|写入|写|改动|动)|禁止(?:修改|写入|写|改动)|不得(?:修改|写入|写|改动)|别(?:修改|写入|写|动)|read[- ]only|do not (?:modify|write|change)|don't (?:modify|write|change))/i;
3206
+ UPDATE_INTENT_RE = /(?:更新|修改|编辑|替换|覆盖|改成|改到|rename|replace|update|modify|edit)/i;
3207
+ EXPLICIT_NO_DELETE_RE = /(?:不要|禁止|不得|别|切勿)\s*(?:删除|删掉|删|移除|remove|delete|rm)/i;
3208
+ INTENT_AMBIGUITY_RE = /(?:处理|整理|优化|调整|清掉|如果|假如|若|或者|还是|看情况|根据|按.{0,6}要求|继续|之前|上次|刚才|顺便|示例|例如|比如|按钮|接口|函数|字段|变量|代码里|可能|建议|评估|考虑)/i;
3209
+ BUILD_ARTIFACT_NAMES = /* @__PURE__ */ new Set([
3210
+ "build",
3211
+ "dist",
3212
+ "target",
3213
+ "out",
3214
+ "tmp",
3215
+ "temp",
3216
+ "cache",
3217
+ ".cache",
3218
+ "__pycache__",
3219
+ ".pytest_cache",
3220
+ ".mypy_cache",
3221
+ ".tox",
3222
+ "node_modules",
3223
+ "coverage",
3224
+ ".coverage",
3225
+ "htmlcov"
3226
+ ]);
3227
+ BUILD_ARTIFACT_GLOB_RE = /^\*\.(?:pyc|pyo|class|o|obj|d|egg-info)$/i;
3067
3228
  REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
3068
3229
  REFERENCE_LOOKBACK = 3;
3069
3230
  EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
@@ -3401,8 +3562,8 @@ function loadRuntimeConfig() {
3401
3562
  }
3402
3563
  try {
3403
3564
  const st = statSync3(p);
3404
- const cacheKey = `${p}|${st.mtimeMs}|${st.size}`;
3405
- if (runtimeConfigCache && runtimeConfigCache.key === cacheKey) {
3565
+ const cacheKey2 = `${p}|${st.mtimeMs}|${st.size}`;
3566
+ if (runtimeConfigCache && runtimeConfigCache.key === cacheKey2) {
3406
3567
  return runtimeConfigCache.value;
3407
3568
  }
3408
3569
  const data = JSON.parse(readFileSync6(p, "utf-8"));
@@ -3427,7 +3588,7 @@ function loadRuntimeConfig() {
3427
3588
  agent_rules: merged.agent_rules || {},
3428
3589
  scenario_rules: merged.scenario_rules || {}
3429
3590
  };
3430
- runtimeConfigCache = { key: cacheKey, value: result };
3591
+ runtimeConfigCache = { key: cacheKey2, value: result };
3431
3592
  return result;
3432
3593
  } catch {
3433
3594
  return emptyRuntimeConfig();
@@ -4747,6 +4908,7 @@ __export(config_exports, {
4747
4908
  getAgentMossSetting: () => getAgentMossSetting,
4748
4909
  getCacheOptions: () => getCacheOptions,
4749
4910
  getCustomRules: () => getCustomRules,
4911
+ getDeployRole: () => getDeployRole,
4750
4912
  getLLMConfig: () => getLLMConfig,
4751
4913
  getLLMFailMode: () => getLLMFailMode,
4752
4914
  getProviderHeaders: () => getProviderHeaders,
@@ -4929,6 +5091,10 @@ function getLLMFailMode() {
4929
5091
  const val = (process.env.AGENT_MOSS_LLM_FAIL_MODE || "fail_open").toLowerCase();
4930
5092
  return val === "fail_closed" ? "fail_closed" : "fail_open";
4931
5093
  }
5094
+ function getDeployRole() {
5095
+ const val = String(process.env.AGENT_MOSS_DEPLOY_ROLE || "standalone").trim().toLowerCase();
5096
+ return val === "host" || val === "sandbox" ? val : "standalone";
5097
+ }
4932
5098
  function detectProvider(baseUrl, providerHint = "") {
4933
5099
  if (providerHint) {
4934
5100
  const hint = providerHint.toLowerCase();
@@ -5062,15 +5228,66 @@ var init_config = __esm({
5062
5228
  }
5063
5229
  });
5064
5230
 
5065
- // src/agents/index.ts
5066
- import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
5067
- import { resolve as resolve5, dirname as dirname6, join as join8 } from "path";
5231
+ // src/infra/edition-scope.ts
5232
+ import { existsSync as existsSync8, readFileSync as readFileSync7, statSync as statSync4 } from "fs";
5233
+ import { dirname as dirname6, join as join8, resolve as resolve5 } from "path";
5068
5234
  import { fileURLToPath as fileURLToPath6 } from "url";
5235
+ function scopePath(moduleDir) {
5236
+ const root = getRulesRoot();
5237
+ if (root) return join8(root, "edition_scope.json");
5238
+ const prod = resolve5(moduleDir, "..", "edition_scope.json");
5239
+ if (existsSync8(prod)) return prod;
5240
+ const dev = resolve5(moduleDir, "../../..", "agent_moss", "edition_scope.json");
5241
+ if (existsSync8(dev)) return dev;
5242
+ return prod;
5243
+ }
5244
+ function loadScope(moduleDir) {
5245
+ const file = scopePath(moduleDir);
5246
+ try {
5247
+ const st = statSync4(file);
5248
+ const key = `${file}:${st.mtimeMs}:${st.size}`;
5249
+ if (key === cacheKey) return cacheData;
5250
+ const parsed = JSON.parse(readFileSync7(file, "utf-8"));
5251
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
5252
+ throw new Error("\u6839\u8282\u70B9\u4E0D\u662F\u5BF9\u8C61");
5253
+ }
5254
+ cacheKey = key;
5255
+ cacheData = parsed;
5256
+ return cacheData;
5257
+ } catch {
5258
+ cacheKey = "";
5259
+ cacheData = null;
5260
+ return null;
5261
+ }
5262
+ }
5263
+ function isAllowed(kind, id, moduleDir = MODULE_DIR) {
5264
+ const scope = loadScope(moduleDir);
5265
+ if (!scope) return true;
5266
+ const allowed = scope[kind];
5267
+ if (!Array.isArray(allowed)) return true;
5268
+ return allowed.includes(id);
5269
+ }
5270
+ var MODULE_DIR, cacheKey, cacheData;
5271
+ var init_edition_scope = __esm({
5272
+ "src/infra/edition-scope.ts"() {
5273
+ "use strict";
5274
+ init_esm_shims();
5275
+ init_paths();
5276
+ MODULE_DIR = dirname6(fileURLToPath6(import.meta.url));
5277
+ cacheKey = "";
5278
+ cacheData = null;
5279
+ }
5280
+ });
5281
+
5282
+ // src/agents/index.ts
5283
+ import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
5284
+ import { resolve as resolve6, dirname as dirname7, join as join9 } from "path";
5285
+ import { fileURLToPath as fileURLToPath7 } from "url";
5069
5286
  function resolveAgentsDir() {
5070
5287
  const root = getRulesRoot();
5071
- if (root) return join8(root, "agents");
5072
- if (existsSync8(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
5073
- if (existsSync8(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
5288
+ if (root) return join9(root, "agents");
5289
+ if (existsSync9(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
5290
+ if (existsSync9(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
5074
5291
  return AGENTS_DIR_PROD;
5075
5292
  }
5076
5293
  function getAgentExtensions(agentId) {
@@ -5079,6 +5296,7 @@ function getAgentExtensions(agentId) {
5079
5296
  console.warn(`[AgentMoss agents] \u975E\u6CD5 agent_id \u5DF2\u5FFD\u7565\uFF08\u542B\u8DEF\u5F84\u5B57\u7B26\u6216\u8D85\u957F\uFF09: ${agentId.slice(0, 120)}`);
5080
5297
  return null;
5081
5298
  }
5299
+ if (!isAllowed("agents", agentId)) return null;
5082
5300
  if (cache.size >= CACHE_MAX) cache.clear();
5083
5301
  const fp = getRuleSourceFingerprint();
5084
5302
  const cached2 = cache.get(agentId);
@@ -5092,13 +5310,13 @@ function getAgentExtensions(agentId) {
5092
5310
  }
5093
5311
  if (ext === null) {
5094
5312
  const agentsDir = resolveAgentsDir();
5095
- const rulesFile = resolve5(agentsDir, agentId, "rules.json");
5096
- if (!existsSync8(rulesFile)) {
5313
+ const rulesFile = resolve6(agentsDir, agentId, "rules.json");
5314
+ if (!existsSync9(rulesFile)) {
5097
5315
  cache.set(agentId, { fp, ext: null });
5098
5316
  return null;
5099
5317
  }
5100
5318
  try {
5101
- const raw = readFileSync7(rulesFile, "utf-8");
5319
+ const raw = readFileSync8(rulesFile, "utf-8");
5102
5320
  ext = JSON.parse(raw);
5103
5321
  if (!ext.agent_id) {
5104
5322
  console.warn(`[AgentMoss agents] rules.json \u7F3A\u5C11 agent_id \u5B57\u6BB5: ${rulesFile}`);
@@ -5139,25 +5357,26 @@ var init_agents = __esm({
5139
5357
  "use strict";
5140
5358
  init_esm_shims();
5141
5359
  init_paths();
5360
+ init_edition_scope();
5142
5361
  init_runtime_config();
5143
- __filename4 = fileURLToPath6(import.meta.url);
5144
- __dirname5 = dirname6(__filename4);
5145
- AGENTS_DIR_PROD = resolve5(__dirname5, "agents");
5146
- AGENTS_DIR_DEV_FALLBACK = resolve5(__dirname5, "../../../agent_moss/agents");
5362
+ __filename4 = fileURLToPath7(import.meta.url);
5363
+ __dirname5 = dirname7(__filename4);
5364
+ AGENTS_DIR_PROD = resolve6(__dirname5, "agents");
5365
+ AGENTS_DIR_DEV_FALLBACK = resolve6(__dirname5, "../../../agent_moss/agents");
5147
5366
  cache = /* @__PURE__ */ new Map();
5148
5367
  CACHE_MAX = 512;
5149
5368
  }
5150
5369
  });
5151
5370
 
5152
5371
  // src/scenarios/index.ts
5153
- import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
5154
- import { resolve as resolve6, dirname as dirname7, join as join9 } from "path";
5155
- import { fileURLToPath as fileURLToPath7 } from "url";
5372
+ import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
5373
+ import { resolve as resolve7, dirname as dirname8, join as join10 } from "path";
5374
+ import { fileURLToPath as fileURLToPath8 } from "url";
5156
5375
  function resolveScenariosDir() {
5157
5376
  const root = getRulesRoot();
5158
- if (root) return join9(root, "scenarios");
5159
- if (existsSync9(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
5160
- if (existsSync9(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
5377
+ if (root) return join10(root, "scenarios");
5378
+ if (existsSync10(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
5379
+ if (existsSync10(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
5161
5380
  return SCENARIOS_DIR_PROD;
5162
5381
  }
5163
5382
  function getScenarioExtensions(scenarioId) {
@@ -5166,6 +5385,7 @@ function getScenarioExtensions(scenarioId) {
5166
5385
  console.warn(`[AgentMoss scenarios] \u975E\u6CD5 scenario_id \u5DF2\u5FFD\u7565\uFF08\u542B\u8DEF\u5F84\u5B57\u7B26\u6216\u8D85\u957F\uFF09: ${scenarioId.slice(0, 120)}`);
5167
5386
  return null;
5168
5387
  }
5388
+ if (!isAllowed("scenarios", scenarioId)) return null;
5169
5389
  if (cache2.size >= CACHE_MAX2) cache2.clear();
5170
5390
  const fp = getRuleSourceFingerprint();
5171
5391
  const cached2 = cache2.get(scenarioId);
@@ -5185,19 +5405,19 @@ function getScenarioExtensions(scenarioId) {
5185
5405
  }
5186
5406
  }
5187
5407
  if (ext === null) {
5188
- const builtinFile = resolve6(resolveScenariosDir(), scenarioId, "rules.json");
5408
+ const builtinFile = resolve7(resolveScenariosDir(), scenarioId, "rules.json");
5189
5409
  const rulesFile = overrideHit ?? builtinFile;
5190
5410
  if (overrideHit) {
5191
5411
  console.warn(
5192
5412
  `[AgentMoss] \u26A0\uFE0F \u573A\u666F ${scenarioId} \u89C4\u5219\u88AB\u8986\u76D6\u76EE\u5F55\u8986\u76D6: ${overrideHit}\uFF08\u5185\u7F6E\u9ED8\u8BA4 ${builtinFile} \u88AB\u5FFD\u7565\uFF09\u3002\u8BE5\u6587\u4EF6\u7531\u90E8\u7F72\u4FA7\u81EA\u884C\u7EF4\u62A4\uFF0C\u5185\u7F6E\u573A\u666F\u89C4\u5219\u66F4\u65B0\u4E0D\u4F1A\u53CD\u6620\u5230\u5B83\u4E0A\u9762\u3002`
5193
5413
  );
5194
5414
  }
5195
- if (!existsSync9(rulesFile)) {
5415
+ if (!existsSync10(rulesFile)) {
5196
5416
  cache2.set(scenarioId, { fp, ext: null });
5197
5417
  return null;
5198
5418
  }
5199
5419
  try {
5200
- const raw = readFileSync8(rulesFile, "utf-8");
5420
+ const raw = readFileSync9(rulesFile, "utf-8");
5201
5421
  const data = JSON.parse(raw);
5202
5422
  const id = data.scenario_id || data.agent_id || "";
5203
5423
  if (!id) {
@@ -5243,13 +5463,14 @@ var init_scenarios = __esm({
5243
5463
  "use strict";
5244
5464
  init_esm_shims();
5245
5465
  init_paths();
5466
+ init_edition_scope();
5246
5467
  init_agents();
5247
5468
  init_runtime_config();
5248
5469
  init_rules_loader();
5249
- __filename5 = fileURLToPath7(import.meta.url);
5250
- __dirname6 = dirname7(__filename5);
5251
- SCENARIOS_DIR_PROD = resolve6(__dirname6, "scenarios");
5252
- SCENARIOS_DIR_DEV_FALLBACK = resolve6(__dirname6, "../../../agent_moss/scenarios");
5470
+ __filename5 = fileURLToPath8(import.meta.url);
5471
+ __dirname6 = dirname8(__filename5);
5472
+ SCENARIOS_DIR_PROD = resolve7(__dirname6, "scenarios");
5473
+ SCENARIOS_DIR_DEV_FALLBACK = resolve7(__dirname6, "../../../agent_moss/scenarios");
5253
5474
  cache2 = /* @__PURE__ */ new Map();
5254
5475
  CACHE_MAX2 = 512;
5255
5476
  }
@@ -5316,6 +5537,21 @@ function detectLanguage(path9, content) {
5316
5537
  }
5317
5538
  return "other";
5318
5539
  }
5540
+ function isInstructionTarget(path9) {
5541
+ const p = (path9 || "").replace(/\\/g, "/").toLowerCase();
5542
+ if (!p) return false;
5543
+ const base = p.split("/").pop() || "";
5544
+ if (["agents.md", "claude.md", "system.md", "prompt.md", "instructions.md", ".cursorrules"].includes(base)) {
5545
+ return true;
5546
+ }
5547
+ if (/(?:^|[-_.])(?:prompt|instruction|system)(?:[-_.]|$)/.test(base)) return true;
5548
+ return INSTRUCTION_TARGET_RE.test(p);
5549
+ }
5550
+ function isDataDocument(actionType, actionDetailRaw) {
5551
+ const payload = extractWritePayload(actionType, actionDetailRaw);
5552
+ if (payload === null) return false;
5553
+ return detectLanguage(payload.path, payload.content) === "data" && !isInstructionTarget(payload.path);
5554
+ }
5319
5555
  function stripShellComments(text) {
5320
5556
  const out = [];
5321
5557
  let heredocEnd = null;
@@ -5478,7 +5714,7 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
5478
5714
  }
5479
5715
  return snippets;
5480
5716
  }
5481
- 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;
5717
+ 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;
5482
5718
  var init_written_content_analyzer = __esm({
5483
5719
  "src/engine/written-content-analyzer.ts"() {
5484
5720
  "use strict";
@@ -5501,7 +5737,12 @@ var init_written_content_analyzer = __esm({
5501
5737
  "file_edit",
5502
5738
  "editfile",
5503
5739
  "searchreplace",
5504
- "search_replace"
5740
+ "search_replace",
5741
+ // 通用 workspace 工具名(ClawPartner/QwenPaw 等宿主常用)
5742
+ "workspace_write_file",
5743
+ "workspace_edit_file",
5744
+ "workspace_writefile",
5745
+ "workspace_editfile"
5505
5746
  ]);
5506
5747
  WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
5507
5748
  APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
@@ -5510,6 +5751,7 @@ var init_written_content_analyzer = __esm({
5510
5751
  INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
5511
5752
  QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
5512
5753
  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;
5754
+ INSTRUCTION_TARGET_RE = /(?:^|[/\\])(?:prompts?|instructions?|skills?|memories|memory|config|policies|policy|\.claude|\.cursor)(?:[/\\]|$)|(?:^|[/\\])(?:AGENTS?|CLAUDE|SYSTEM|PROMPT|INSTRUCTIONS?)(?:\.[^/\\]+)?$|(?:^|[/\\])\.cursorrules$/i;
5513
5755
  HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
5514
5756
  }
5515
5757
  });
@@ -5753,6 +5995,23 @@ function runHeuristicCheck(input) {
5753
5995
  deobfuscated
5754
5996
  );
5755
5997
  }
5998
+ const extraScanDetail = stripSearchPatternLiterals(scanDetail);
5999
+ const extraScanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => {
6000
+ const stripped = stripSearchPatternLiterals(sn);
6001
+ return [`${input.aNext.actionType}: ${stripped}`, stripped];
6002
+ }) : String(input.osType || "").toLowerCase() === "windows" ? [
6003
+ `${input.aNext.actionType}: ${extraScanDetail}`,
6004
+ extraScanDetail,
6005
+ `${input.aNext.actionType}: ${extraScanDetail.replace(/\//g, "\\")}`,
6006
+ extraScanDetail.replace(/\//g, "\\")
6007
+ ] : [`${input.aNext.actionType}: ${extraScanDetail}`, extraScanDetail];
6008
+ const extraDeobfuscated = normalizeShellObfuscation(extraScanDetail);
6009
+ if (extraDeobfuscated !== extraScanDetail) {
6010
+ extraScanCommands.push(
6011
+ `${input.aNext.actionType}: ${extraDeobfuscated}`,
6012
+ extraDeobfuscated
6013
+ );
6014
+ }
5756
6015
  let topRiskType = "";
5757
6016
  const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
5758
6017
  const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
@@ -5777,7 +6036,7 @@ function runHeuristicCheck(input) {
5777
6036
  for (const rule of agentExt.extra_command_patterns) {
5778
6037
  try {
5779
6038
  const re = new RegExp(rule.pattern, "i");
5780
- if (scanCommands.some((c) => re.test(c))) {
6039
+ if (extraScanCommands.some((c) => re.test(c))) {
5781
6040
  matched.push(`agent \u4E13\u5C5E\u89C4\u5219: ${rule.reason}`);
5782
6041
  if (severityRank(rule.risk_level) > severityRank(highestSeverity)) {
5783
6042
  highestSeverity = rule.risk_level;
@@ -5788,7 +6047,7 @@ function runHeuristicCheck(input) {
5788
6047
  }
5789
6048
  }
5790
6049
  }
5791
- 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();
6050
+ 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();
5792
6051
  let pythonWalkOnerrorOnly = false;
5793
6052
  if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
5794
6053
  pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
@@ -6039,16 +6298,83 @@ function splitCommandSegments2(actionDetail) {
6039
6298
  if (start < actionDetail.length) segments.push(actionDetail.slice(start));
6040
6299
  return segments;
6041
6300
  }
6301
+ function shellTokens(seg) {
6302
+ const tokens = [];
6303
+ let cur = "";
6304
+ let quote = "";
6305
+ for (let i = 0; i < seg.length; i++) {
6306
+ const ch = seg[i];
6307
+ if (quote) {
6308
+ if (ch === quote) quote = "";
6309
+ else cur += ch;
6310
+ continue;
6311
+ }
6312
+ if (ch === '"' || ch === "'") {
6313
+ quote = ch;
6314
+ continue;
6315
+ }
6316
+ if (/\s/.test(ch)) {
6317
+ if (cur) {
6318
+ tokens.push(cur);
6319
+ cur = "";
6320
+ }
6321
+ continue;
6322
+ }
6323
+ cur += ch;
6324
+ }
6325
+ if (quote) return null;
6326
+ if (cur) tokens.push(cur);
6327
+ return tokens;
6328
+ }
6329
+ function stripSearchPatternArgument(seg) {
6330
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) return seg;
6331
+ const tokens = shellTokens(seg);
6332
+ if (!tokens || tokens.length === 0) return seg;
6333
+ let idx = 0;
6334
+ while (idx < tokens.length && COMMAND_PREFIX_WORDS.has(tokens[idx])) idx++;
6335
+ if (idx >= tokens.length || !TEXT_SEARCH_COMMANDS.has(tokens[idx])) return seg;
6336
+ let patternIdx = null;
6337
+ let i = idx + 1;
6338
+ while (i < tokens.length) {
6339
+ const token = tokens[i];
6340
+ if (token === "--") {
6341
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
6342
+ break;
6343
+ }
6344
+ if (token === "-e" || token === "--regexp") {
6345
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
6346
+ break;
6347
+ }
6348
+ if (token.startsWith("--regexp=")) {
6349
+ patternIdx = i;
6350
+ break;
6351
+ }
6352
+ if (token === "-f" || token === "--file" || token.startsWith("--file=")) break;
6353
+ if (token.startsWith("-") && token !== "-") {
6354
+ i += SEARCH_OPTION_WITH_ARG.has(token) ? 2 : 1;
6355
+ continue;
6356
+ }
6357
+ patternIdx = i;
6358
+ break;
6359
+ }
6360
+ if (patternIdx === null || patternIdx >= tokens.length) return seg;
6361
+ tokens.splice(patternIdx, 1);
6362
+ return tokens.map((t) => /\s/.test(t) ? `'${t.replaceAll("'", "'\\''")}'` : t).join(" ");
6363
+ }
6042
6364
  function stripSearchPatternLiterals(actionDetail) {
6043
6365
  const parts = [];
6044
6366
  for (const seg of splitCommandSegments2(actionDetail)) {
6367
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) {
6368
+ parts.push(seg);
6369
+ continue;
6370
+ }
6045
6371
  const low = seg.trim().toLowerCase();
6046
6372
  const words = low.length ? low.split(/\s+/) : [];
6047
6373
  let idx = 0;
6048
6374
  while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
6049
6375
  const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
6050
6376
  if (isSearch && !low.includes("--pre")) {
6051
- parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
6377
+ parts.push(stripSearchPatternArgument(seg));
6052
6378
  } else {
6053
6379
  parts.push(seg);
6054
6380
  }
@@ -6373,7 +6699,7 @@ function checkDangerousPatterns(actionType, actionDetail) {
6373
6699
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
6374
6700
  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;
6375
6701
  const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
6376
- if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
6702
+ if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
6377
6703
  return {
6378
6704
  allowed: false,
6379
6705
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -6515,7 +6841,7 @@ function checkLateralMovement(actionDetail) {
6515
6841
  }
6516
6842
  return null;
6517
6843
  }
6518
- 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;
6844
+ 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;
6519
6845
  var init_heuristic = __esm({
6520
6846
  "src/engine/heuristic.ts"() {
6521
6847
  "use strict";
@@ -6564,6 +6890,28 @@ var init_heuristic = __esm({
6564
6890
  COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
6565
6891
  TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
6566
6892
  COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
6893
+ SEARCH_OPTION_WITH_ARG = /* @__PURE__ */ new Set([
6894
+ "-m",
6895
+ "--max-count",
6896
+ "-A",
6897
+ "--after-context",
6898
+ "-B",
6899
+ "--before-context",
6900
+ "-C",
6901
+ "--context",
6902
+ "-d",
6903
+ "--directories",
6904
+ "-D",
6905
+ "--devices",
6906
+ "--include",
6907
+ "--exclude",
6908
+ "--exclude-dir",
6909
+ "--glob",
6910
+ "--iglob",
6911
+ "--type",
6912
+ "--type-add",
6913
+ "--type-not"
6914
+ ]);
6567
6915
  SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
6568
6916
  SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
6569
6917
  SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
@@ -6573,9 +6921,9 @@ var init_heuristic = __esm({
6573
6921
  });
6574
6922
 
6575
6923
  // src/engine/template-loader.ts
6576
- import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
6577
- import { resolve as resolve7, dirname as dirname8 } from "path";
6578
- import { fileURLToPath as fileURLToPath8 } from "url";
6924
+ import { readFileSync as readFileSync10, existsSync as existsSync11 } from "fs";
6925
+ import { resolve as resolve8, dirname as dirname9 } from "path";
6926
+ import { fileURLToPath as fileURLToPath9 } from "url";
6579
6927
  function loadTemplates() {
6580
6928
  if (cachedTemplates) return cachedTemplates;
6581
6929
  cachedTemplates = {};
@@ -6586,10 +6934,10 @@ function loadTemplates() {
6586
6934
  return cachedTemplates;
6587
6935
  }
6588
6936
  for (const file of TEMPLATE_FILES) {
6589
- const filePath = resolve7(dir, file);
6590
- if (existsSync10(filePath)) {
6937
+ const filePath = resolve8(dir, file);
6938
+ if (existsSync11(filePath)) {
6591
6939
  const key = file.replace(".txt", "").replace("_template", "");
6592
- cachedTemplates[key] = readFileSync9(filePath, "utf-8");
6940
+ cachedTemplates[key] = readFileSync10(filePath, "utf-8");
6593
6941
  }
6594
6942
  }
6595
6943
  console.log(`[AgentMoss] Loaded ${Object.keys(cachedTemplates).length} templates from ${dir}`);
@@ -6601,16 +6949,16 @@ var init_template_loader = __esm({
6601
6949
  "use strict";
6602
6950
  init_esm_shims();
6603
6951
  init_asset_dir();
6604
- __filename6 = fileURLToPath8(import.meta.url);
6605
- __dirname7 = dirname8(__filename6);
6952
+ __filename6 = fileURLToPath9(import.meta.url);
6953
+ __dirname7 = dirname9(__filename6);
6606
6954
  TEMPLATE_FILES = ["prompt1_template.txt", "prompt2_template.txt", "security_judge_template.txt"];
6607
6955
  cachedTemplates = null;
6608
6956
  }
6609
6957
  });
6610
6958
 
6611
6959
  // src/engine/script-analyzer.ts
6612
- import { readFileSync as readFileSync10 } from "fs";
6613
- import { resolve as resolve8, join as join10 } from "path";
6960
+ import { readFileSync as readFileSync11 } from "fs";
6961
+ import { resolve as resolve9, join as join11 } from "path";
6614
6962
  function emptyResult() {
6615
6963
  return { scriptPath: "", scriptContent: "", matchedKeywords: [], lineCount: 0, isSuspicious: false, error: "", riskLevel: "", riskReason: "" };
6616
6964
  }
@@ -6663,8 +7011,8 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
6663
7011
  }
6664
7012
  function readScriptContent(scriptPath, maxLines = 500) {
6665
7013
  try {
6666
- const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join10(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
6667
- const raw = readFileSync10(expandedPath, "utf-8");
7014
+ const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join11(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve9(scriptPath);
7015
+ const raw = readFileSync11(expandedPath, "utf-8");
6668
7016
  const lines = raw.split("\n").slice(0, maxLines);
6669
7017
  return { content: lines.join("\n"), lineCount: lines.length, error: "" };
6670
7018
  } catch (e) {
@@ -7942,7 +8290,7 @@ function evalIfCondition(cond, args) {
7942
8290
  const op = m[2];
7943
8291
  let left = m[1].trim();
7944
8292
  let right = m[3].trim();
7945
- const resolve12 = (tok) => {
8293
+ const resolve13 = (tok) => {
7946
8294
  const rm = tok.match(/^\$(\d+)$/);
7947
8295
  if (rm) {
7948
8296
  const idx = parseInt(rm[1], 10);
@@ -7950,8 +8298,8 @@ function evalIfCondition(cond, args) {
7950
8298
  }
7951
8299
  return tok.startsWith("$") ? null : tok;
7952
8300
  };
7953
- const lv = resolve12(left);
7954
- const rv = resolve12(right);
8301
+ const lv = resolve13(left);
8302
+ const rv = resolve13(right);
7955
8303
  if (lv === null || rv === null) return null;
7956
8304
  if (op === "=~") {
7957
8305
  let re = rv;
@@ -8293,8 +8641,8 @@ var init_tracker = __esm({
8293
8641
  });
8294
8642
 
8295
8643
  // src/engine/script-content-analyzer.ts
8296
- import { statSync as statSync5, existsSync as existsSync12 } from "fs";
8297
- import { resolve as resolve10, join as join12, isAbsolute as isAbsolute4 } from "path";
8644
+ import { statSync as statSync6, existsSync as existsSync13 } from "fs";
8645
+ import { resolve as resolve11, join as join13, isAbsolute as isAbsolute4 } from "path";
8298
8646
  import { homedir as homedir5 } from "os";
8299
8647
  function emptyChain() {
8300
8648
  return {
@@ -8406,8 +8754,8 @@ function extractInlineScriptPath(actionDetail) {
8406
8754
  if (looksLikeScriptPath(tok)) {
8407
8755
  try {
8408
8756
  const resolved = resolvePath2(tok.replace(/^['"]|['"]$/g, ""));
8409
- if (existsSync12(resolved)) {
8410
- const stat = statSync5(resolved);
8757
+ if (existsSync13(resolved)) {
8758
+ const stat = statSync6(resolved);
8411
8759
  if (stat.isFile()) return resolved;
8412
8760
  }
8413
8761
  } catch {
@@ -8420,8 +8768,8 @@ function extractInlineScriptPath(actionDetail) {
8420
8768
  const p = m[1];
8421
8769
  try {
8422
8770
  const resolved = resolvePath2(p);
8423
- if (existsSync12(resolved)) {
8424
- const stat = statSync5(resolved);
8771
+ if (existsSync13(resolved)) {
8772
+ const stat = statSync6(resolved);
8425
8773
  if (stat.isFile()) return resolved;
8426
8774
  }
8427
8775
  } catch {
@@ -8436,8 +8784,8 @@ function extractInlineScriptPath(actionDetail) {
8436
8784
  let resolved;
8437
8785
  try {
8438
8786
  resolved = resolvePath2(p);
8439
- if (existsSync12(resolved)) {
8440
- const stat = statSync5(resolved);
8787
+ if (existsSync13(resolved)) {
8788
+ const stat = statSync6(resolved);
8441
8789
  if (stat.isFile()) return resolved;
8442
8790
  }
8443
8791
  } catch {
@@ -8477,9 +8825,9 @@ function shlexSplit(s) {
8477
8825
  function resolvePath2(p) {
8478
8826
  let expanded = p;
8479
8827
  if (expanded.startsWith("~/") || expanded === "~") {
8480
- expanded = join12(homedir5(), expanded.slice(1));
8828
+ expanded = join13(homedir5(), expanded.slice(1));
8481
8829
  }
8482
- return resolve10(expanded);
8830
+ return resolve11(expanded);
8483
8831
  }
8484
8832
  function scanExtensionPatterns(ext, content) {
8485
8833
  const pats = ext?.extra_command_patterns;
@@ -8566,7 +8914,7 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
8566
8914
  isInline = true;
8567
8915
  }
8568
8916
  if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
8569
- resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
8917
+ resolvedPath = join13(input.cwd || process.cwd(), resolvedPath);
8570
8918
  }
8571
8919
  const l1Adapter = (content) => {
8572
8920
  const extHit = scanExtensionPatterns(ext, content);
@@ -9167,17 +9515,17 @@ __export(token_stats_exports, {
9167
9515
  resetTokenStats: () => resetTokenStats,
9168
9516
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
9169
9517
  });
9170
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
9518
+ import { readFileSync as readFileSync14, writeFileSync as writeFileSync2, existsSync as existsSync14, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync7 } from "fs";
9171
9519
  function getStatsPath() {
9172
9520
  const envPath = process.env[ENV_STATS_PATH];
9173
9521
  if (envPath) return envPath;
9174
9522
  return getTokenStatsPath();
9175
9523
  }
9176
9524
  function loadAllRecords(statsPath) {
9177
- if (!existsSync13(statsPath)) return [];
9525
+ if (!existsSync14(statsPath)) return [];
9178
9526
  let sig = "";
9179
9527
  try {
9180
- const st = statSync6(statsPath);
9528
+ const st = statSync7(statsPath);
9181
9529
  sig = `${st.mtimeMs}:${st.size}`;
9182
9530
  } catch {
9183
9531
  return [];
@@ -9186,7 +9534,7 @@ function loadAllRecords(statsPath) {
9186
9534
  return _recordsCache.records.slice();
9187
9535
  }
9188
9536
  try {
9189
- const data = JSON.parse(readFileSync13(statsPath, "utf-8"));
9537
+ const data = JSON.parse(readFileSync14(statsPath, "utf-8"));
9190
9538
  let records;
9191
9539
  if (Array.isArray(data)) records = data;
9192
9540
  else if (data && Array.isArray(data.records)) records = data.records;
@@ -9200,7 +9548,7 @@ function loadAllRecords(statsPath) {
9200
9548
  function saveRecords(statsPath, records) {
9201
9549
  try {
9202
9550
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
9203
- if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
9551
+ if (dir && !existsSync14(dir)) mkdirSync3(dir, { recursive: true });
9204
9552
  const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
9205
9553
  try {
9206
9554
  writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
@@ -9212,7 +9560,7 @@ function saveRecords(statsPath, records) {
9212
9560
  }
9213
9561
  }
9214
9562
  try {
9215
- const st = statSync6(statsPath);
9563
+ const st = statSync7(statsPath);
9216
9564
  _recordsCache = {
9217
9565
  path: statsPath,
9218
9566
  sig: `${st.mtimeMs}:${st.size}`,
@@ -9349,7 +9697,7 @@ function getTokenTrend(days = 0, startDate, endDate) {
9349
9697
  }
9350
9698
  function resetTokenStats() {
9351
9699
  const statsPath = getStatsPath();
9352
- if (existsSync13(statsPath)) {
9700
+ if (existsSync14(statsPath)) {
9353
9701
  try {
9354
9702
  unlinkSync2(statsPath);
9355
9703
  } catch {
@@ -9449,8 +9797,8 @@ async function runLLMAnalysis(input, previous) {
9449
9797
  }
9450
9798
  const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
9451
9799
  const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
9452
- const cacheKey = `${input.aNext.actionType}:${createHash3("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
9453
- const cached2 = llmCache.get(cacheKey);
9800
+ const cacheKey2 = `${input.aNext.actionType}:${createHash3("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
9801
+ const cached2 = llmCache.get(cacheKey2);
9454
9802
  if (cached2) {
9455
9803
  console.log("[AgentMoss] LLM cache hit");
9456
9804
  return cached2;
@@ -9465,6 +9813,9 @@ async function runLLMAnalysis(input, previous) {
9465
9813
  scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
9466
9814
  }
9467
9815
  const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
9816
+ const budgetMode = getAgentMossSetting("AGENT_MOSS_LLM_BUDGET_MODE", "hard").trim().toLowerCase() === "soft" ? "soft" : "hard";
9817
+ const budgetActive = maxPromptTokens > 0;
9818
+ const tokenLimit = budgetActive && budgetMode === "hard" ? Math.floor(maxPromptTokens * 100 / 115) : maxPromptTokens;
9468
9819
  let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
9469
9820
  let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
9470
9821
  let prompt = "";
@@ -9481,13 +9832,14 @@ async function runLLMAnalysis(input, previous) {
9481
9832
  historyMaxItems,
9482
9833
  historyMaxChars
9483
9834
  );
9484
- if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
9835
+ if (!budgetActive || estimateTokens(prompt) <= tokenLimit) break;
9485
9836
  historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
9486
9837
  historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
9487
9838
  }
9488
- if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
9839
+ let budgetCode = "";
9840
+ if (budgetActive && estimateTokens(prompt) > tokenLimit) {
9489
9841
  const estimated = estimateTokens(prompt);
9490
- const ratio = estimated / maxPromptTokens;
9842
+ const ratio = tokenLimit > 0 ? estimated / tokenLimit : Number.POSITIVE_INFINITY;
9491
9843
  const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
9492
9844
  const truncated = truncateDetail(input.aNext.actionDetail, allowed);
9493
9845
  prompt = buildPrompt(
@@ -9503,8 +9855,14 @@ async function runLLMAnalysis(input, previous) {
9503
9855
  historyMaxChars
9504
9856
  );
9505
9857
  console.warn(
9506
- `[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`
9858
+ `[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`
9507
9859
  );
9860
+ if (estimateTokens(prompt) > tokenLimit) {
9861
+ if (budgetMode === "hard") {
9862
+ throw new LLMPromptBudgetExceeded("l3_budget_unreachable");
9863
+ }
9864
+ budgetCode = "l3_budget_unreachable";
9865
+ }
9508
9866
  }
9509
9867
  logPrompt(prompt, input.aNext, previous.llmLogPath);
9510
9868
  traceFull("l3.prompt", {
@@ -9517,6 +9875,7 @@ async function runLLMAnalysis(input, previous) {
9517
9875
  prompt_chars: prompt.length
9518
9876
  });
9519
9877
  const result = await analyzeWithLLM(prompt, config);
9878
+ if (budgetCode) result.degraded = [...result.degraded || [], budgetCode];
9520
9879
  traceSummary("l3.verdict", {
9521
9880
  allowed: result.allowed,
9522
9881
  risk_level: result.riskLevel,
@@ -9528,7 +9887,7 @@ async function runLLMAnalysis(input, previous) {
9528
9887
  const firstKey = llmCache.keys().next().value;
9529
9888
  if (firstKey) llmCache.delete(firstKey);
9530
9889
  }
9531
- llmCache.set(cacheKey, result);
9890
+ llmCache.set(cacheKey2, result);
9532
9891
  return result;
9533
9892
  }
9534
9893
  function logPrompt(prompt, aNext, logPath) {
@@ -9590,11 +9949,14 @@ function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis,
9590
9949
  const skillsText = formatSkillsForPrompt(matchedSkills);
9591
9950
  const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
9592
9951
  const promptHistoryText = formatPromptHistory(input.promptHistory);
9952
+ const historyAuthorization = /(因历史窗口上限省略|本段因长度上限已截断)/.test(promptHistoryText) ? `
9953
+
9954
+ ${HISTORY_AUTHORIZATION}` : "";
9593
9955
  const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
9594
9956
  const hintsText = formatHints(previous);
9595
9957
  const securityJudgeTemplate = templates["security_judge"];
9596
9958
  if (securityJudgeTemplate) {
9597
- 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("}}", "}");
9959
+ 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("}}", "}");
9598
9960
  }
9599
9961
  console.warn("[AgentMoss] security_judge template missing, using sparse fallback prompt");
9600
9962
  return `## \u5F53\u524D\u64CD\u4F5C\u4E0A\u4E0B\u6587
@@ -9630,21 +9992,28 @@ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNu
9630
9992
  }
9631
9993
  const limit = Math.max(0, Math.floor(maxTurns));
9632
9994
  const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
9995
+ let omitted = 0;
9633
9996
  const lines = [];
9634
- for (let i = firstTurnIndex; i < promptHistory.length; i++) {
9997
+ for (let i = 0; i < promptHistory.length; i++) {
9635
9998
  const turn = promptHistory[i];
9636
9999
  const text = (typeof turn === "string" ? turn : turn?.text || "").trim();
9637
- if (!text) continue;
9638
- let line = ` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${text.slice(0, maxTextChars)}`;
9639
10000
  const actions = typeof turn === "string" ? void 0 : turn?.actions;
9640
- if (actions && actions.length > 0) {
9641
- const types = actions.map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
9642
- if (types.length > 0) {
9643
- line += ` \u2192 \u52A8\u4F5C: ${types.join(", ")}`;
9644
- }
10001
+ const types = (actions || []).map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
10002
+ if (!text && types.length === 0) continue;
10003
+ if (i < firstTurnIndex) {
10004
+ omitted += 1;
10005
+ continue;
9645
10006
  }
9646
- lines.push(line);
10007
+ if (!text) {
10008
+ lines.push(` \u7B2C${i + 1}\u8F6E\u52A8\u4F5C: ${types.join(", ")}`);
10009
+ continue;
10010
+ }
10011
+ let shown = text.slice(0, maxTextChars);
10012
+ if (shown.length < text.length) shown += "\uFF08\u672C\u6BB5\u56E0\u957F\u5EA6\u4E0A\u9650\u5DF2\u622A\u65AD\uFF09";
10013
+ const suffix = types.length > 0 ? ` \u2192 \u52A8\u4F5C: ${types.join(", ")}` : "";
10014
+ lines.push(` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${shown}${suffix}`);
9647
10015
  }
10016
+ if (omitted) lines.unshift(`\uFF08\u56E0\u5386\u53F2\u7A97\u53E3\u4E0A\u9650\u7701\u7565 ${omitted} \u8F6E\u66F4\u65E9\u5386\u53F2\u610F\u56FE\uFF09`);
9648
10017
  return lines.length > 0 ? lines.join("\n") : "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
9649
10018
  }
9650
10019
  function formatHints(previous) {
@@ -9657,11 +10026,15 @@ function formatHints(previous) {
9657
10026
  );
9658
10027
  }
9659
10028
  if (previous.logic) {
9660
- hints.push(
9661
- `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
10029
+ if (previous.logic.l3Hint) {
10030
+ hints.push(`\u2139\uFE0F ${previous.logic.l3Hint}`);
10031
+ } else {
10032
+ hints.push(
10033
+ `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
9662
10034
  \u7C7B\u578B: ${previous.logic.riskType}
9663
10035
  \u539F\u56E0: ${previous.logic.reason}`
9664
- );
10036
+ );
10037
+ }
9665
10038
  }
9666
10039
  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";
9667
10040
  }
@@ -9862,7 +10235,7 @@ async function analyzeWithLLM(prompt, config) {
9862
10235
  )}`;
9863
10236
  if (attempt < maxRetries) {
9864
10237
  console.error(`[AgentMoss] LLM call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${retryCfg.retryInterval}s: ${detail}`);
9865
- await new Promise((resolve12) => setTimeout(resolve12, retryCfg.retryInterval * 1e3));
10238
+ await new Promise((resolve13) => setTimeout(resolve13, retryCfg.retryInterval * 1e3));
9866
10239
  } else {
9867
10240
  clearTimeout(totalTimeoutTimer);
9868
10241
  console.error(`[AgentMoss] LLM call failed after all retries: ${detail}`);
@@ -9873,7 +10246,7 @@ async function analyzeWithLLM(prompt, config) {
9873
10246
  clearTimeout(totalTimeoutTimer);
9874
10247
  throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
9875
10248
  }
9876
- var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
10249
+ var LLMPromptBudgetExceeded, HISTORY_AUTHORIZATION, LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
9877
10250
  var init_llm_analyzer = __esm({
9878
10251
  "src/engine/llm-analyzer.ts"() {
9879
10252
  "use strict";
@@ -9887,6 +10260,15 @@ var init_llm_analyzer = __esm({
9887
10260
  init_trace_log();
9888
10261
  init_metrics();
9889
10262
  init_circuit_breaker();
10263
+ LLMPromptBudgetExceeded = class extends Error {
10264
+ code;
10265
+ constructor(code) {
10266
+ super(code);
10267
+ this.name = "LLMPromptBudgetExceeded";
10268
+ this.code = code;
10269
+ }
10270
+ };
10271
+ 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";
9890
10272
  LLMCircuitOpenError = class extends Error {
9891
10273
  constructor(message) {
9892
10274
  super(message);
@@ -9899,8 +10281,8 @@ var init_llm_analyzer = __esm({
9899
10281
  });
9900
10282
 
9901
10283
  // src/brain/rule-store.ts
9902
- import { existsSync as existsSync14, readFileSync as readFileSync14, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
9903
- import { join as join13 } from "path";
10284
+ import { existsSync as existsSync15, readFileSync as readFileSync15, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
10285
+ import { join as join14 } from "path";
9904
10286
  import { homedir as homedir6 } from "os";
9905
10287
  function getRulesPath() {
9906
10288
  const envPath = process.env[ENV_RULES_PATH];
@@ -9919,7 +10301,7 @@ var init_rule_store = __esm({
9919
10301
  "src/brain/rule-store.ts"() {
9920
10302
  "use strict";
9921
10303
  init_esm_shims();
9922
- DEFAULT_RULES_PATH = join13(homedir6(), ".agentmoss", "brain", "rules.json");
10304
+ DEFAULT_RULES_PATH = join14(homedir6(), ".agentmoss", "brain", "rules.json");
9923
10305
  ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
9924
10306
  STATUS_DRAFT = "draft";
9925
10307
  STATUS_APPROVED = "approved";
@@ -9936,11 +10318,11 @@ var init_rule_store = __esm({
9936
10318
  this.data = this.load();
9937
10319
  }
9938
10320
  load() {
9939
- if (!existsSync14(this.path)) {
10321
+ if (!existsSync15(this.path)) {
9940
10322
  return { version: 1, rules: [], pattern_candidates: [] };
9941
10323
  }
9942
10324
  try {
9943
- const raw = JSON.parse(readFileSync14(this.path, "utf-8"));
10325
+ const raw = JSON.parse(readFileSync15(this.path, "utf-8"));
9944
10326
  return {
9945
10327
  version: raw.version || 1,
9946
10328
  rules: raw.rules || [],
@@ -10534,9 +10916,9 @@ var init_reviewer = __esm({
10534
10916
  });
10535
10917
 
10536
10918
  // src/brain/skill-manager.ts
10537
- import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
10919
+ import { existsSync as existsSync16, mkdirSync as mkdirSync5, readFileSync as readFileSync16, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
10538
10920
  import { homedir as homedir7 } from "os";
10539
- import { join as join14 } from "path";
10921
+ import { join as join15 } from "path";
10540
10922
  import { randomUUID } from "crypto";
10541
10923
  function getMetaPath(override) {
10542
10924
  return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
@@ -10546,14 +10928,14 @@ var init_skill_manager = __esm({
10546
10928
  "src/brain/skill-manager.ts"() {
10547
10929
  "use strict";
10548
10930
  init_esm_shims();
10549
- DEFAULT_SKILL_META_PATH = join14(homedir7(), ".agentmoss", "brain", "skill_meta.json");
10931
+ DEFAULT_SKILL_META_PATH = join15(homedir7(), ".agentmoss", "brain", "skill_meta.json");
10550
10932
  ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
10551
10933
  BrainSkillManager = class {
10552
10934
  constructor(skillsDir, metaPath) {
10553
10935
  this.skillsDir = skillsDir;
10554
10936
  this.metaPath = getMetaPath(metaPath);
10555
10937
  try {
10556
- mkdirSync5(join14(this.metaPath, ".."), { recursive: true });
10938
+ mkdirSync5(join15(this.metaPath, ".."), { recursive: true });
10557
10939
  } catch {
10558
10940
  }
10559
10941
  this.load();
@@ -10563,9 +10945,9 @@ var init_skill_manager = __esm({
10563
10945
  skills = [];
10564
10946
  metaPath;
10565
10947
  load() {
10566
- if (!existsSync15(this.metaPath)) return;
10948
+ if (!existsSync16(this.metaPath)) return;
10567
10949
  try {
10568
- const data = JSON.parse(readFileSync15(this.metaPath, "utf-8"));
10950
+ const data = JSON.parse(readFileSync16(this.metaPath, "utf-8"));
10569
10951
  this.skills = data.skills || [];
10570
10952
  } catch {
10571
10953
  this.skills = [];
@@ -10588,7 +10970,7 @@ var init_skill_manager = __esm({
10588
10970
  let changed = false;
10589
10971
  for (const sk of this.skills) {
10590
10972
  if (sk.status !== "active") continue;
10591
- if (!existsSync15(join14(this.skillsDir, `${sk.name}.md`))) {
10973
+ if (!existsSync16(join15(this.skillsDir, `${sk.name}.md`))) {
10592
10974
  sk.status = "stale";
10593
10975
  changed = true;
10594
10976
  }
@@ -10599,9 +10981,9 @@ var init_skill_manager = __esm({
10599
10981
  addSkill(skill) {
10600
10982
  const id = skill.id || randomUUID();
10601
10983
  const name = skill.name || `brain_${id.slice(0, 8)}`;
10602
- if (!existsSync15(this.skillsDir)) return "";
10603
- const mdPath = join14(this.skillsDir, `${name}.md`);
10604
- if (existsSync15(mdPath)) return "";
10984
+ if (!existsSync16(this.skillsDir)) return "";
10985
+ const mdPath = join15(this.skillsDir, `${name}.md`);
10986
+ if (existsSync16(mdPath)) return "";
10605
10987
  try {
10606
10988
  writeFileSync4(mdPath, skill.content, "utf-8");
10607
10989
  } catch {
@@ -10650,12 +11032,12 @@ var init_skill_manager = __esm({
10650
11032
  const out = [];
10651
11033
  for (const sk of this.skills) {
10652
11034
  if (sk.origin_node !== "local" || sk.status !== "active") continue;
10653
- const mdPath = join14(this.skillsDir, `${sk.name}.md`);
10654
- if (!existsSync15(mdPath)) continue;
11035
+ const mdPath = join15(this.skillsDir, `${sk.name}.md`);
11036
+ if (!existsSync16(mdPath)) continue;
10655
11037
  out.push({
10656
11038
  name: sk.name,
10657
11039
  category: sk.category || "",
10658
- content: readFileSync15(mdPath, "utf-8"),
11040
+ content: readFileSync16(mdPath, "utf-8"),
10659
11041
  keywords: sk.keywords || []
10660
11042
  });
10661
11043
  }
@@ -10767,10 +11149,10 @@ __export(contributor_exports, {
10767
11149
  });
10768
11150
  import { mkdirSync as mkdirSync6, mkdtempSync, rmSync, writeFileSync as writeFileSync5 } from "fs";
10769
11151
  import { tmpdir as tmpdir2 } from "os";
10770
- import { join as join15 } from "path";
11152
+ import { join as join16 } from "path";
10771
11153
  import { spawnSync } from "child_process";
10772
- import { dirname as dirname11 } from "path";
10773
- import { fileURLToPath as fileURLToPath9 } from "url";
11154
+ import { dirname as dirname12 } from "path";
11155
+ import { fileURLToPath as fileURLToPath10 } from "url";
10774
11156
  function collectRules(store) {
10775
11157
  return store.getActiveRules().filter((r) => EXPORT_RULE_SOURCES.includes(r.source)).map((r) => ({
10776
11158
  layer: r.layer,
@@ -10788,7 +11170,7 @@ function collectSkills(skillMgr) {
10788
11170
  }
10789
11171
  function writeExportFiles(outDir, rules, skills) {
10790
11172
  const written = [];
10791
- const rulesDir2 = join15(outDir, "rules");
11173
+ const rulesDir2 = join16(outDir, "rules");
10792
11174
  mkdirSync6(rulesDir2, { recursive: true });
10793
11175
  const byLayer = /* @__PURE__ */ new Map();
10794
11176
  for (const r of rules) {
@@ -10796,24 +11178,24 @@ function writeExportFiles(outDir, rules, skills) {
10796
11178
  byLayer.get(r.layer).push(r);
10797
11179
  }
10798
11180
  for (const layer of [...byLayer.keys()].sort((a, b) => a - b)) {
10799
- const path9 = join15(rulesDir2, `l${layer}_brain_rules.json`);
11181
+ const path9 = join16(rulesDir2, `l${layer}_brain_rules.json`);
10800
11182
  writeFileSync5(path9, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
10801
11183
  written.push(path9);
10802
11184
  }
10803
11185
  if (rules.length === 0) {
10804
- const path9 = join15(rulesDir2, "empty.txt");
11186
+ const path9 = join16(rulesDir2, "empty.txt");
10805
11187
  writeFileSync5(path9, "(no brain rules to contribute)", "utf-8");
10806
11188
  written.push(path9);
10807
11189
  }
10808
- const skillsDir = join15(outDir, "skills");
11190
+ const skillsDir = join16(outDir, "skills");
10809
11191
  mkdirSync6(skillsDir, { recursive: true });
10810
11192
  for (const sk of skills) {
10811
- const path9 = join15(skillsDir, `${sk.name}.md`);
11193
+ const path9 = join16(skillsDir, `${sk.name}.md`);
10812
11194
  writeFileSync5(path9, sk.content || "", "utf-8");
10813
11195
  written.push(path9);
10814
11196
  }
10815
11197
  if (skills.length === 0) {
10816
- const path9 = join15(skillsDir, "empty.txt");
11198
+ const path9 = join16(skillsDir, "empty.txt");
10817
11199
  writeFileSync5(path9, "(no brain skills to contribute)", "utf-8");
10818
11200
  written.push(path9);
10819
11201
  }
@@ -10943,7 +11325,7 @@ async function contribute(opts = {}) {
10943
11325
  console.log(`[Brain] push \u76EE\u6807: ${pushTarget}`);
10944
11326
  console.log(`[Brain] MR \u6307\u5411: ${DEFAULT_TARGET_REPO}`);
10945
11327
  const store = new BrainRuleStore();
10946
- const skillsDir = resolveAssetDir(__dirname8, "skills") ?? join15(__dirname8, "..", "..", "agent_moss", "skills");
11328
+ const skillsDir = resolveAssetDir(__dirname8, "skills") ?? join16(__dirname8, "..", "..", "agent_moss", "skills");
10947
11329
  const skillMgr = new BrainSkillManager(skillsDir);
10948
11330
  let rules;
10949
11331
  let skills;
@@ -10958,9 +11340,9 @@ async function contribute(opts = {}) {
10958
11340
  return 0;
10959
11341
  }
10960
11342
  console.log(`[Brain] \u5BFC\u51FA: ${rules.length} \u6761\u89C4\u5219, ${skills.length} \u4E2A Skill`);
10961
- const workdir = mkdtempSync(join15(tmpdir2(), "agentmoss-contrib-"));
11343
+ const workdir = mkdtempSync(join16(tmpdir2(), "agentmoss-contrib-"));
10962
11344
  try {
10963
- writeExportFiles(join15(workdir, "agent_moss", "brain_contrib"), rules, skills);
11345
+ writeExportFiles(join16(workdir, "agent_moss", "brain_contrib"), rules, skills);
10964
11346
  console.log(`[Brain] \u63A2\u6D4B ${pushTarget} \u8BBF\u95EE\u6743\u9650 ...`);
10965
11347
  if (!probeAccess(pushTarget)) {
10966
11348
  const username = getCurrentUsername();
@@ -11010,7 +11392,7 @@ var init_contributor = __esm({
11010
11392
  init_rule_store();
11011
11393
  init_skill_manager();
11012
11394
  init_asset_dir();
11013
- __dirname8 = dirname11(fileURLToPath9(import.meta.url));
11395
+ __dirname8 = dirname12(fileURLToPath10(import.meta.url));
11014
11396
  DEFAULT_TARGET_REPO = "ssh://git@atomgit.com/kenhkl/AgentMoss.git";
11015
11397
  CONTACT_EMAIL = "kenhkl11@hotmail.com";
11016
11398
  TOKEN_ENV = "AGENT_MOSS_CONTRIBUTE_TOKEN";
@@ -11329,11 +11711,35 @@ function checkMCRules(graph) {
11329
11711
  for (const rule of rules) {
11330
11712
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
11331
11713
  if (ruleViolates(rule, trace2, witnessMode)) {
11714
+ const pathNodes = nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3);
11715
+ const path9 = pathNodes.map((n) => ({
11716
+ sessionId: n.sessionId,
11717
+ seq: n.seq,
11718
+ detail: n.actionDetail.slice(0, 60)
11719
+ }));
11332
11720
  violations.push({
11333
11721
  propertyId: String(rule.id || "mc-ltl"),
11334
11722
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
11335
11723
  riskLevel: String(rule.risk_level || "high"),
11336
- 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) }))
11724
+ path: path9,
11725
+ graph: {
11726
+ property_id: String(rule.id || "mc-ltl"),
11727
+ property_short: "P6",
11728
+ property_name: "LTL \u6A21\u578B\u68C0\u6D4B",
11729
+ nodes: pathNodes.map((n) => ({
11730
+ session_id: n.sessionId,
11731
+ seq: n.seq,
11732
+ stage: n.stage,
11733
+ action_detail: n.actionDetail,
11734
+ resources: [...n.resources].sort(),
11735
+ instance_id: n.instanceId || ""
11736
+ })),
11737
+ edges: pathNodes.slice(1).map((_, i) => ({
11738
+ from: i,
11739
+ to: i + 1,
11740
+ type: "next"
11741
+ }))
11742
+ }
11337
11743
  });
11338
11744
  if (witnessMode) return violations;
11339
11745
  }
@@ -12033,11 +12439,17 @@ function checkLowIntegrityCommandExec(graph) {
12033
12439
  for (const i of candidates) {
12034
12440
  const n = nodes[i];
12035
12441
  if (lowAt.has(i) && isComputeNode(n)) {
12442
+ const path9 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
12036
12443
  violations.push({
12037
12444
  propertyId: "low-integrity-command-exec",
12038
12445
  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`,
12039
12446
  riskLevel: "critical",
12040
- path: [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }]
12447
+ path: path9,
12448
+ graph: graphFromPath(nodes, path9, "next", {
12449
+ property_id: "low-integrity-command-exec",
12450
+ property_short: "P7",
12451
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u547D\u4EE4\u6267\u884C"
12452
+ }, ["sink"])
12041
12453
  });
12042
12454
  if (witness !== void 0) return violations;
12043
12455
  }
@@ -12079,11 +12491,21 @@ function checkCrossSessionReachability(graph) {
12079
12491
  if (reached.has(i)) {
12080
12492
  const srcIdx = Math.min(...sources);
12081
12493
  const srcDesc = nodes[srcIdx].actionDetail.slice(0, 40);
12494
+ const path9 = nodes.slice(-3).map((m) => ({
12495
+ sessionId: m.sessionId,
12496
+ seq: m.seq,
12497
+ detail: m.actionDetail.slice(0, 60)
12498
+ }));
12082
12499
  violations.push({
12083
12500
  propertyId: "low-integrity-reachability",
12084
12501
  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`,
12085
12502
  riskLevel: "high",
12086
- path: nodes.slice(-3).map((m) => ({ sessionId: m.sessionId, seq: m.seq, detail: m.actionDetail.slice(0, 60) }))
12503
+ path: path9,
12504
+ graph: graphFromPath(nodes, path9, "data", {
12505
+ property_id: "low-integrity-reachability",
12506
+ property_short: "P3",
12507
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u6D41\u53EF\u8FBE"
12508
+ })
12087
12509
  });
12088
12510
  if (witness !== void 0) return violations;
12089
12511
  }
@@ -12423,7 +12845,24 @@ function fingerprint(sessionId, actionType, actionDetail, calledAt) {
12423
12845
  ].join("\0");
12424
12846
  return createHash4("blake2b512").update(raw).digest("hex").slice(0, 16);
12425
12847
  }
12426
- 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;
12848
+ function gateOrder(action) {
12849
+ const callId = String(action?.gateCallId ?? "");
12850
+ const callTimeUs = Number(action?.gateCallTimeUs ?? 0);
12851
+ return callId && Number.isFinite(callTimeUs) && callTimeUs > 0 ? { callId, callTimeUs } : null;
12852
+ }
12853
+ function gateFingerprint(action, isError, agentId, instanceId, order) {
12854
+ const values = [
12855
+ String(action?.actionType ?? ""),
12856
+ String(action?.actionDetail ?? ""),
12857
+ String(action?.calledAt ?? ""),
12858
+ String(action?.agentId ?? agentId ?? ""),
12859
+ String(action?.instanceId ?? instanceId ?? ""),
12860
+ Boolean(isError),
12861
+ order.callTimeUs
12862
+ ];
12863
+ return createHash4("sha256").update(JSON.stringify(values)).digest("hex");
12864
+ }
12865
+ 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;
12427
12866
  var init_stateful = __esm({
12428
12867
  "src/engine/formal-engine/stateful.ts"() {
12429
12868
  "use strict";
@@ -12439,6 +12878,12 @@ var init_stateful = __esm({
12439
12878
  SOCK_RE = /([\w./-]*(?:\/tmp\/|\/var\/run\/|\.sock\b)[\w./-]*)/;
12440
12879
  UNIT_RE = /systemctl\s+(?:start|enable|restart)\s+([\w.-]+)/i;
12441
12880
  PORT_STAGE_RE = /LISTEN|PERSIST|SCAN/;
12881
+ StatefulAnalysisUnavailable = class extends Error {
12882
+ };
12883
+ UnconfirmedGateRetry = class extends StatefulAnalysisUnavailable {
12884
+ };
12885
+ GateCallConflict = class extends UnconfirmedGateRetry {
12886
+ };
12442
12887
  STAGES_PATTERNS = null;
12443
12888
  CHAINS = null;
12444
12889
  COMMON_DIR_RESOURCES2 = /* @__PURE__ */ new Set([
@@ -12482,6 +12927,8 @@ var init_stateful = __esm({
12482
12927
  aliveResources = {};
12483
12928
  seqNext = 0;
12484
12929
  seededKeys = /* @__PURE__ */ new Set();
12930
+ /** (sessionId, gateCallId) → 节点,用于 Gate 精确一次关联。 */
12931
+ gateNodes = /* @__PURE__ */ new Map();
12485
12932
  constructor(agentId = "") {
12486
12933
  this.agentId = agentId;
12487
12934
  loadRules();
@@ -12540,28 +12987,73 @@ var init_stateful = __esm({
12540
12987
  }
12541
12988
  return added;
12542
12989
  }
12990
+ resultOf(node, matched, exfil) {
12991
+ return {
12992
+ seq: this.seqNext,
12993
+ node,
12994
+ matched,
12995
+ pendingPrefixes: this.pendingPrefixes,
12996
+ exfil,
12997
+ get shouldBlock() {
12998
+ return this.matched !== null || this.exfil.length > 0;
12999
+ }
13000
+ };
13001
+ }
12543
13002
  /** 增量推进:把当前动作追加到时间线 → 链指针推进 → 判定。 */
12544
13003
  advance(args) {
12545
13004
  const { aNext, sessionId = "current", isError = false, agentId = "", instanceId = "" } = args;
12546
- const node = this.appendNode(aNext, sessionId, isError, agentId, instanceId);
13005
+ const order = gateOrder(aNext);
13006
+ const gateFingerprintValue = order ? gateFingerprint(aNext, isError, agentId, instanceId, order) : "";
13007
+ if (order) {
13008
+ const existing = this.gateNodes.get(this.gateKey(sessionId, order.callId));
13009
+ if (existing) {
13010
+ if (existing.confirmed) {
13011
+ if (existing.inputFingerprint === gateFingerprintValue && existing.gateCallTimeUs === order.callTimeUs) {
13012
+ return this.resultOf(existing, existing.confirmed.matched, existing.confirmed.exfil);
13013
+ }
13014
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u5185\u5BB9\u6216\u65F6\u95F4\u4E0D\u4E00\u81F4");
13015
+ }
13016
+ if (aNext.gateDeliveryUncertain === true) {
13017
+ throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
13018
+ }
13019
+ if (existing.gateCallTimeUs !== order.callTimeUs) {
13020
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u65F6\u95F4\u4E0D\u4E00\u81F4");
13021
+ }
13022
+ if (existing.inputFingerprint) {
13023
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u91CD\u590D\u8C03\u7528\u7F3A\u5C11\u9001\u8FBE\u4E0D\u786E\u5B9A\u6807\u8BB0");
13024
+ }
13025
+ return this.resultOf(existing, null, []);
13026
+ }
13027
+ if (aNext.gateDeliveryUncertain === true) {
13028
+ throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
13029
+ }
13030
+ }
13031
+ const node = this.appendNode(
13032
+ order ? {
13033
+ ...aNext,
13034
+ gateCallId: order.callId,
13035
+ gateCallTimeUs: order.callTimeUs,
13036
+ gateInputFingerprint: gateFingerprintValue
13037
+ } : aNext,
13038
+ sessionId,
13039
+ isError,
13040
+ agentId,
13041
+ instanceId
13042
+ );
12547
13043
  if (!node) {
12548
- return { seq: this.seqNext, node: null, matched: null, pendingPrefixes: this.pendingPrefixes, exfil: [], shouldBlock: false };
13044
+ return this.resultOf(null, null, []);
12549
13045
  }
12550
13046
  const seq = this.seqNext;
12551
13047
  this.recordLifecycle(node);
12552
13048
  const matched = this.advanceChains(node);
12553
13049
  this.advanceTaint(node);
12554
13050
  const exfil = this.checkExfilAfterTaint(node);
12555
- return {
12556
- seq,
12557
- node,
12558
- matched,
12559
- pendingPrefixes: this.pendingPrefixes,
12560
- exfil,
12561
- get shouldBlock() {
12562
- return this.matched !== null || this.exfil.length > 0;
12563
- }
12564
- };
13051
+ if (order) {
13052
+ node.confirmed = { matched, exfil };
13053
+ this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
13054
+ }
13055
+ void seq;
13056
+ return this.resultOf(node, matched, exfil);
12565
13057
  }
12566
13058
  /**
12567
13059
  * 自动轮转:归档旧节点,只保留最近 `retain` 条,并重建链指针/taint。
@@ -12598,6 +13090,7 @@ var init_stateful = __esm({
12598
13090
  this.taintOrigin.clear();
12599
13091
  this.aliveResources = {};
12600
13092
  this.seqNext = 0;
13093
+ this.gateNodes.clear();
12601
13094
  for (const n of kept) {
12602
13095
  const node = this.appendNode(
12603
13096
  {
@@ -12605,7 +13098,12 @@ var init_stateful = __esm({
12605
13098
  actionDetail: n.actionDetail,
12606
13099
  agentId: n.agentId,
12607
13100
  instanceId: n.instanceId,
12608
- ...n.timestamp ? { calledAt: n.timestamp } : {}
13101
+ ...n.timestamp ? { calledAt: n.timestamp } : {},
13102
+ ...n.gateCallId ? {
13103
+ gateCallId: n.gateCallId,
13104
+ gateCallTimeUs: n.gateCallTimeUs,
13105
+ gateInputFingerprint: n.inputFingerprint
13106
+ } : {}
12609
13107
  },
12610
13108
  n.sessionId,
12611
13109
  n.isError,
@@ -12613,6 +13111,7 @@ var init_stateful = __esm({
12613
13111
  n.instanceId
12614
13112
  );
12615
13113
  if (node) {
13114
+ if (n.confirmed) node.confirmed = n.confirmed;
12616
13115
  this.recordLifecycle(node);
12617
13116
  this.advanceTaint(node);
12618
13117
  this.advanceChains(node);
@@ -12620,6 +13119,9 @@ var init_stateful = __esm({
12620
13119
  }
12621
13120
  return { archived: old.length, file };
12622
13121
  }
13122
+ gateKey(sessionId, callId) {
13123
+ return `${sessionId}\0${callId}`;
13124
+ }
12623
13125
  appendNode(action, sessionId, isError = false, agentId = "", instanceId = "") {
12624
13126
  const ad = String(action.actionDetail || "");
12625
13127
  const at = String(action.actionType || "");
@@ -12651,6 +13153,13 @@ var init_stateful = __esm({
12651
13153
  lifecycle: lifecycleFor(ad, stage, isError),
12652
13154
  timestamp: suppliedCalledAt || _StatefulChainTracker.now()
12653
13155
  };
13156
+ const order = gateOrder(action);
13157
+ if (order) {
13158
+ node.gateCallId = order.callId;
13159
+ node.gateCallTimeUs = order.callTimeUs;
13160
+ node.inputFingerprint = String(action.gateInputFingerprint || "");
13161
+ this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
13162
+ }
12654
13163
  this.nodes_.push(node);
12655
13164
  this.seqNext += 1;
12656
13165
  if (dedupeKey) this.seededKeys.add(dedupeKey);
@@ -13002,11 +13511,19 @@ var init_stateful = __esm({
13002
13511
  // 旧快照无此字段 → 空
13003
13512
  isError: Boolean(raw.isError),
13004
13513
  lifecycle: String(raw.lifecycle || ""),
13005
- timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null
13514
+ timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null,
13006
13515
  // 旧快照无此字段 → null
13516
+ ...raw.gateCallId ? { gateCallId: String(raw.gateCallId) } : {},
13517
+ ...raw.gateCallTimeUs ? { gateCallTimeUs: Number(raw.gateCallTimeUs) } : {},
13518
+ ...raw.inputFingerprint ? { inputFingerprint: String(raw.inputFingerprint) } : {},
13519
+ ...raw.confirmed ? { confirmed: raw.confirmed } : {}
13007
13520
  });
13008
13521
  }
13009
13522
  this.seqNext = Number(snapshot.seq_next || this.nodes_.length);
13523
+ this.gateNodes = /* @__PURE__ */ new Map();
13524
+ for (const n of this.nodes_) {
13525
+ if (n.gateCallId) this.gateNodes.set(this.gateKey(n.sessionId, n.gateCallId), n);
13526
+ }
13010
13527
  for (const n of this.nodes_) {
13011
13528
  if (n.timestamp) {
13012
13529
  this.seededKeys.add(fingerprint(n.sessionId, n.actionType, n.actionDetail, n.timestamp));
@@ -13467,9 +13984,19 @@ async function runAnalysis(input) {
13467
13984
  isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
13468
13985
  isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
13469
13986
  );
13987
+ const degradedNotes = [];
13470
13988
  let scriptChain = null;
13471
- if (input.aNext.actionType.toLowerCase() === "bash") {
13989
+ if (input.aNext.actionType.toLowerCase() === "bash" && getDeployRole() === "host") {
13990
+ degradedNotes.push("script_content_deferred_to_sandbox: AGENT_MOSS_DEPLOY_ROLE=host");
13991
+ } else if (input.aNext.actionType.toLowerCase() === "bash") {
13472
13992
  scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
13993
+ if (scriptChain.nodes.length > 0) {
13994
+ for (const node of scriptChain.nodes) {
13995
+ if (node.error && !node.unanalyzable) {
13996
+ degradedNotes.push(`script_content_unavailable: ${node.scriptPath} (${node.error})`);
13997
+ }
13998
+ }
13999
+ }
13473
14000
  if (heuristicEnabled && scriptChain.nodes.length > 0) {
13474
14001
  for (const node of scriptChain.nodes) {
13475
14002
  if (node.unanalyzable) {
@@ -13740,7 +14267,8 @@ async function runAnalysis(input) {
13740
14267
  riskType: "",
13741
14268
  confidence: 85,
13742
14269
  source: "heuristic_and_logic_only",
13743
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
14270
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
14271
+ degraded: degradedNotes
13744
14272
  };
13745
14273
  }
13746
14274
  let skipL3Hints = "\u65E0\uFF08\u5F53\u524D\u65E0\u7981\u7528\u89C4\u5219\u547D\u4E2D\uFF09";
@@ -13777,8 +14305,22 @@ async function runAnalysis(input) {
13777
14305
  pathContext
13778
14306
  });
13779
14307
  } catch (e) {
13780
- const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
13781
14308
  const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
14309
+ if (e instanceof LLMPromptBudgetExceeded) {
14310
+ const failMode = getLLMFailMode2();
14311
+ const allowed = failMode === "fail_open";
14312
+ return {
14313
+ allowed,
14314
+ reason: `L3 prompt \u8D85\u51FA\u786C\u9884\u7B97\uFF0C\u5DF2\u8DF3\u8FC7\u8BED\u4E49\u5206\u6790\uFF0C\u6309 ${failMode} ${allowed ? "\u653E\u884C" : "\u62D2\u7EDD"}`,
14315
+ riskLevel: allowed ? "low" : "medium",
14316
+ riskType: "",
14317
+ confidence: allowed ? 50 : 60,
14318
+ source: "llm_budget_skipped",
14319
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
14320
+ degraded: [...degradedNotes, e.code]
14321
+ };
14322
+ }
14323
+ const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
13782
14324
  if (getLLMFailMode2() === "fail_open") {
13783
14325
  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}`);
13784
14326
  return {
@@ -13788,7 +14330,8 @@ async function runAnalysis(input) {
13788
14330
  riskType: "",
13789
14331
  confidence: 50,
13790
14332
  source: failSource,
13791
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
14333
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
14334
+ degraded: degradedNotes
13792
14335
  };
13793
14336
  }
13794
14337
  return {
@@ -13798,7 +14341,10 @@ async function runAnalysis(input) {
13798
14341
  riskType: "",
13799
14342
  confidence: 60,
13800
14343
  source: failSource,
13801
- violatedLayers: ["L3.1"]
14344
+ violatedLayers: ["L3.1"],
14345
+ degraded: degradedNotes,
14346
+ ask_recommended: true,
14347
+ 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"
13802
14348
  };
13803
14349
  }
13804
14350
  if (!llmResult.allowed && llmResult.confidence && llmResult.confidence >= 90 && _brainExtractor) {
@@ -13818,6 +14364,9 @@ async function runAnalysis(input) {
13818
14364
  if (observedFormalLayers.length > 0 && llmResult.allowed) {
13819
14365
  llmResult.violatedLayers = Array.from(/* @__PURE__ */ new Set([...observedFormalLayers, ...llmResult.violatedLayers || []]));
13820
14366
  }
14367
+ if (degradedNotes.length > 0) {
14368
+ llmResult.degraded = Array.from(/* @__PURE__ */ new Set([...llmResult.degraded || [], ...degradedNotes]));
14369
+ }
13821
14370
  return llmResult;
13822
14371
  }
13823
14372
  var TRUSTED_SKILLS_BASE, _brainStore, _brainExtractor, _brainSkillManager, _brainCurator, _brainInitialized, _brainLastMaintenance, BRAIN_MAINT_INTERVAL_MS, formalEngine;
@@ -13864,7 +14413,7 @@ function deriveL3Outcome(j) {
13864
14413
  if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
13865
14414
  if (src === "llm_circuit_open") return "circuit_open";
13866
14415
  if (src === "llm_failure_with_violation") return "failed_but_blocked";
13867
- if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
14416
+ if (src === "heuristic_and_logic_only" || src === "disabled" || src === "llm_budget_skipped") return "skipped";
13868
14417
  return "not_reached";
13869
14418
  }
13870
14419
  var init_types = __esm({
@@ -13876,9 +14425,9 @@ var init_types = __esm({
13876
14425
 
13877
14426
  // src/infra/policy-cache.ts
13878
14427
  import { createHash as createHash6 } from "crypto";
13879
- import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
14428
+ import { existsSync as existsSync18, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync18, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
13880
14429
  import { tmpdir as tmpdir3 } from "os";
13881
- import { join as join18 } from "path";
14430
+ import { join as join19 } from "path";
13882
14431
  function cacheDir() {
13883
14432
  return cacheDirOverride ?? CACHE_DIR;
13884
14433
  }
@@ -13886,7 +14435,7 @@ function safeCacheDir() {
13886
14435
  const dir = cacheDir();
13887
14436
  if (ensurePrivateDir(dir)) return dir;
13888
14437
  try {
13889
- const fallback = join18(getDataRoot(), "policy_cache");
14438
+ const fallback = join19(getDataRoot(), "policy_cache");
13890
14439
  if (ensurePrivateDir(fallback)) {
13891
14440
  console.warn(`[AgentMoss] \u7F13\u5B58\u76EE\u5F55 ${dir} \u4E0D\u5B89\u5168\uFF08\u88AB\u5176\u4ED6\u7528\u6237\u62E5\u6709\u6216\u4E3A\u7B26\u53F7\u94FE\u63A5\uFF09\uFF0C\u5DF2\u56DE\u9000\u5230 ${fallback}`);
13892
14441
  return fallback;
@@ -13907,7 +14456,7 @@ var init_policy_cache = __esm({
13907
14456
  init_security_policy();
13908
14457
  init_paths();
13909
14458
  init_config();
13910
- CACHE_DIR = join18(tmpdir3(), "agent_moss_policy_cache");
14459
+ CACHE_DIR = join19(tmpdir3(), "agent_moss_policy_cache");
13911
14460
  cacheDirOverride = null;
13912
14461
  PolicyCache = class {
13913
14462
  // Map 的插入序即 LRU 序(get 时重新 set 到末尾)
@@ -13922,7 +14471,7 @@ var init_policy_cache = __esm({
13922
14471
  cacheFilePath(sessionId, promptSession) {
13923
14472
  const promptHash = createHash6("md5").update(promptSession).digest("hex").slice(0, 12);
13924
14473
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13925
- return join18(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
14474
+ return join19(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13926
14475
  }
13927
14476
  /** 取缓存:内存 → 文件;未命中返回 null。 */
13928
14477
  get(sessionId, promptSession) {
@@ -13935,9 +14484,9 @@ var init_policy_cache = __esm({
13935
14484
  return hit;
13936
14485
  }
13937
14486
  const file = this.cacheFilePath(sessionId, promptSession);
13938
- if (existsSync17(file) && !lstatSync2(file).isSymbolicLink()) {
14487
+ if (existsSync18(file) && !lstatSync2(file).isSymbolicLink()) {
13939
14488
  try {
13940
- const policy = readFileSync17(file, "utf-8");
14489
+ const policy = readFileSync18(file, "utf-8");
13941
14490
  this.remember(key, policy);
13942
14491
  return policy;
13943
14492
  } catch {
@@ -13953,7 +14502,7 @@ var init_policy_cache = __esm({
13953
14502
  try {
13954
14503
  const dir = safeCacheDir();
13955
14504
  const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13956
- if (!ensurePrivateDir(join18(dir, sub))) return;
14505
+ if (!ensurePrivateDir(join19(dir, sub))) return;
13957
14506
  writePrivateText(file, policy);
13958
14507
  } catch {
13959
14508
  }
@@ -13979,12 +14528,12 @@ var init_policy_cache = __esm({
13979
14528
  if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
13980
14529
  }
13981
14530
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13982
- const dir = join18(cacheDir(), safeSessionId);
14531
+ const dir = join19(cacheDir(), safeSessionId);
13983
14532
  try {
13984
- if (existsSync17(dir)) {
14533
+ if (existsSync18(dir)) {
13985
14534
  for (const f of readdirSync6(dir)) {
13986
14535
  try {
13987
- unlinkSync5(join18(dir, f));
14536
+ unlinkSync5(join19(dir, f));
13988
14537
  } catch {
13989
14538
  }
13990
14539
  }
@@ -13996,11 +14545,11 @@ var init_policy_cache = __esm({
13996
14545
  clear() {
13997
14546
  this.memory.clear();
13998
14547
  try {
13999
- if (existsSync17(cacheDir())) {
14548
+ if (existsSync18(cacheDir())) {
14000
14549
  for (const sessionDir of readdirSync6(cacheDir())) {
14001
- const dir = join18(cacheDir(), sessionDir);
14550
+ const dir = join19(cacheDir(), sessionDir);
14002
14551
  try {
14003
- for (const f of readdirSync6(dir)) unlinkSync5(join18(dir, f));
14552
+ for (const f of readdirSync6(dir)) unlinkSync5(join19(dir, f));
14004
14553
  rmdirSync(dir);
14005
14554
  } catch {
14006
14555
  }
@@ -14096,9 +14645,9 @@ __export(analyzer_exports, {
14096
14645
  savePolicyToFile: () => savePolicyToFile,
14097
14646
  validateToml: () => validateToml
14098
14647
  });
14099
- import { existsSync as existsSync18, readFileSync as readFileSync18 } from "fs";
14648
+ import { existsSync as existsSync19, readFileSync as readFileSync19 } from "fs";
14100
14649
  import { tmpdir as tmpdir4 } from "os";
14101
- import { join as join19, resolve as resolve11 } from "path";
14650
+ import { join as join20, resolve as resolve12 } from "path";
14102
14651
  import { parse as parseToml } from "smol-toml";
14103
14652
  function _setPolicyOutputDirForTest(dir) {
14104
14653
  policyOutputDirOverride = dir;
@@ -14115,7 +14664,7 @@ function savePolicyToFile(sessionId, policyToml) {
14115
14664
  return null;
14116
14665
  }
14117
14666
  const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
14118
- const filepath = join19(outDir, `${safeName}.toml`);
14667
+ const filepath = join20(outDir, `${safeName}.toml`);
14119
14668
  writePrivateText(filepath, policyToml);
14120
14669
  return filepath;
14121
14670
  } catch (err) {
@@ -14153,12 +14702,12 @@ function validateToml(tomlStr) {
14153
14702
  function loadPolicyMappingDoc() {
14154
14703
  const dir = resolveAssetDir(__dirname, "templates");
14155
14704
  if (dir) {
14156
- const p = resolve11(dir, "policy_mapping.md");
14157
- if (existsSync18(p)) return readFileSync18(p, "utf-8");
14705
+ const p = resolve12(dir, "policy_mapping.md");
14706
+ if (existsSync19(p)) return readFileSync19(p, "utf-8");
14158
14707
  }
14159
14708
  for (const cand of assetDirCandidates(__dirname, "templates")) {
14160
- const p = resolve11(cand, "policy_mapping.md");
14161
- if (existsSync18(p)) return readFileSync18(p, "utf-8");
14709
+ const p = resolve12(cand, "policy_mapping.md");
14710
+ if (existsSync19(p)) return readFileSync19(p, "utf-8");
14162
14711
  }
14163
14712
  return "";
14164
14713
  }
@@ -14338,7 +14887,7 @@ var init_analyzer = __esm({
14338
14887
  init_asset_dir();
14339
14888
  init_token_stats();
14340
14889
  init_logging();
14341
- POLICY_OUTPUT_DIR = join19(tmpdir4(), "agent_moss");
14890
+ POLICY_OUTPUT_DIR = join20(tmpdir4(), "agent_moss");
14342
14891
  policyOutputDirOverride = null;
14343
14892
  DEFAULT_READONLY_POLICY = `landlock_optional = false
14344
14893
  mount_isolation_fallback = false
@@ -14584,6 +15133,16 @@ function normalizeAction(row) {
14584
15133
  actionDetail: String(row.action_detail || row.command || row.input || "")
14585
15134
  };
14586
15135
  if (row.called_at) act.calledAt = String(row.called_at);
15136
+ try {
15137
+ const audit = JSON.parse(String(row.moss_response || "{}"));
15138
+ if (audit && audit._gate_protocol_rejected === true) {
15139
+ act.gateProtocolRejected = true;
15140
+ } 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) {
15141
+ act.gateCallId = audit._gate_call_id;
15142
+ act.gateCallTimeUs = audit._gate_call_time_us;
15143
+ }
15144
+ } catch {
15145
+ }
14587
15146
  return act;
14588
15147
  }
14589
15148
  function readJsonDir(dirPath, limit = 1e5, strict = false) {
@@ -14624,10 +15183,18 @@ function readSqlite(dbPath, limit = 1e5, strict = false) {
14624
15183
  let db;
14625
15184
  try {
14626
15185
  db = new Database(dbPath, { readonly: true });
14627
- const rows = db.prepare(
14628
- `SELECT session_id, action_type, tool_name, action_detail, command, called_at
14629
- FROM tool_calls ORDER BY called_at, id LIMIT ?`
14630
- ).all(limit);
15186
+ let rows;
15187
+ try {
15188
+ rows = db.prepare(
15189
+ `SELECT session_id, action_type, tool_name, action_detail, command, called_at, moss_response
15190
+ FROM tool_calls ORDER BY called_at, id LIMIT ?`
15191
+ ).all(limit);
15192
+ } catch {
15193
+ rows = db.prepare(
15194
+ `SELECT session_id, action_type, tool_name, action_detail, command, called_at
15195
+ FROM tool_calls ORDER BY called_at, id LIMIT ?`
15196
+ ).all(limit);
15197
+ }
14631
15198
  const sessions = /* @__PURE__ */ new Map();
14632
15199
  for (const r of rows) {
14633
15200
  const sid = String(r.session_id || "");
@@ -14808,8 +15375,8 @@ var init_runtime_stats = __esm({
14808
15375
 
14809
15376
  // src/routes.ts
14810
15377
  import { randomBytes as randomBytes2 } from "crypto";
14811
- import { join as join21, dirname as dirname13 } from "path";
14812
- import { fileURLToPath as fileURLToPath10 } from "url";
15378
+ import { join as join22, dirname as dirname14 } from "path";
15379
+ import { fileURLToPath as fileURLToPath11 } from "url";
14813
15380
  async function healthRoute(c) {
14814
15381
  const metrics = {};
14815
15382
  try {
@@ -14862,6 +15429,10 @@ async function analyzeRoute(c) {
14862
15429
  try {
14863
15430
  const body = await c.req.json();
14864
15431
  const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
15432
+ const gateCallId = String(c.get("gateCallId") || "");
15433
+ if (gateCallId && (req.gate_call_id !== gateCallId || !validGateCallTime(req.gate_call_time_us) || typeof req.gate_delivery_uncertain !== "boolean")) {
15434
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5143\u6570\u636E\u65E0\u6548" }, 422);
15435
+ }
14865
15436
  const unmappedTool = String(
14866
15437
  req.metadata?.unmapped_tool || ""
14867
15438
  );
@@ -14974,7 +15545,16 @@ async function analyzeRoute(c) {
14974
15545
  const store = getChainStateStoreFor(agentId);
14975
15546
  const inc = store.applyAction(
14976
15547
  chainBucket(agentId),
14977
- { actionType: req.a_next.action_type, actionDetail: req.a_next.action_detail },
15548
+ {
15549
+ actionType: req.a_next.action_type,
15550
+ actionDetail: req.a_next.action_detail,
15551
+ ...req.a_next.called_at ? { calledAt: req.a_next.called_at } : {},
15552
+ ...gateCallId ? {
15553
+ gateCallId,
15554
+ gateCallTimeUs: req.gate_call_time_us,
15555
+ gateDeliveryUncertain: req.gate_delivery_uncertain === true
15556
+ } : {}
15557
+ },
14978
15558
  req.session_id,
14979
15559
  Boolean(meta.is_error),
14980
15560
  agentId,
@@ -14997,7 +15577,31 @@ async function analyzeRoute(c) {
14997
15577
  }
14998
15578
  finding = incMatchedToDeny(inc);
14999
15579
  } catch (err) {
15000
- console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
15580
+ if (err instanceof UnconfirmedGateRetry) {
15581
+ const reason = "AgentMoss \u65E0\u6CD5\u786E\u8BA4\u672C\u6B21 Gate \u8C03\u7528\u662F\u5426\u5DF2\u5165\u94FE";
15582
+ degradedNotes.push(`\u3010\u5DF2\u964D\u7EA7\u3011${reason}\uFF1B\u672C\u6B21\u6309\u62D2\u7EDD\u5904\u7406\uFF0C\u907F\u514D\u91CD\u590D\u5165\u94FE\u3002`);
15583
+ if (result.decision !== "Deny") {
15584
+ result = {
15585
+ ...result,
15586
+ decision: "Deny",
15587
+ reason,
15588
+ risk_type: "service_unavailable",
15589
+ risk_level: "high",
15590
+ policy: "",
15591
+ ask_recommended: true,
15592
+ 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"
15593
+ };
15594
+ }
15595
+ } else if (err instanceof StatefulAnalysisUnavailable) {
15596
+ degradedNotes.push(
15597
+ "\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"
15598
+ );
15599
+ } else {
15600
+ console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
15601
+ degradedNotes.push(
15602
+ "\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"
15603
+ );
15604
+ }
15001
15605
  }
15002
15606
  }
15003
15607
  result = publicFormalResult(
@@ -15008,6 +15612,11 @@ async function analyzeRoute(c) {
15008
15612
  req.session_history || []
15009
15613
  );
15010
15614
  const durationMs = performance.now() - t0;
15615
+ if (Array.isArray(result.degraded)) {
15616
+ for (const note of result.degraded) {
15617
+ if (note && !degradedNotes.includes(note)) degradedNotes.push(note);
15618
+ }
15619
+ }
15011
15620
  const _l3FailMsg = String(result.reason || "").slice(0, 160);
15012
15621
  if (result.l3_outcome === "reasoning_fallback") {
15013
15622
  degradedNotes.push(
@@ -15097,7 +15706,10 @@ async function analyzeRoute(c) {
15097
15706
  degraded: degradedNotes,
15098
15707
  // L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
15099
15708
  // 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
15100
- l3_outcome: result.l3_outcome || ""
15709
+ l3_outcome: result.l3_outcome || "",
15710
+ ask_recommended: result.ask_recommended === true,
15711
+ ask_reason: String(result.ask_reason || ""),
15712
+ ...gateCallId ? { gate_call_id: gateCallId } : {}
15101
15713
  })
15102
15714
  );
15103
15715
  } catch (err) {
@@ -15253,7 +15865,11 @@ async function reviewRoute(c) {
15253
15865
  if (!tracker) {
15254
15866
  tracker = new StatefulChainTracker(bucket);
15255
15867
  }
15256
- const added = sessions.length > 0 ? tracker.seed(sessions) : 0;
15868
+ const seedSessions = sessions.map((s) => ({
15869
+ ...s,
15870
+ actionHistory: (s.actionHistory || []).filter((a) => !a.gateProtocolRejected)
15871
+ }));
15872
+ const added = seedSessions.length > 0 ? tracker.seed(seedSessions) : 0;
15257
15873
  store.save(tracker);
15258
15874
  let verified = true;
15259
15875
  const violations = [];
@@ -15317,7 +15933,7 @@ function getBrainRuleStore() {
15317
15933
  return new BrainRuleStore();
15318
15934
  }
15319
15935
  function getBrainSkillManager() {
15320
- const dir = resolveAssetDir(__dirname9, "skills") ?? join21(__dirname9, "..", "..", "agent_moss", "skills");
15936
+ const dir = resolveAssetDir(__dirname9, "skills") ?? join22(__dirname9, "..", "..", "agent_moss", "skills");
15321
15937
  return new BrainSkillManager(dir);
15322
15938
  }
15323
15939
  async function brainRulesRoute(c) {
@@ -15418,6 +16034,7 @@ var init_routes = __esm({
15418
16034
  init_analyzer();
15419
16035
  init_actrail();
15420
16036
  init_formal_engine();
16037
+ init_stateful();
15421
16038
  init_circuit_breaker();
15422
16039
  init_pattern_miner();
15423
16040
  init_agent_gate_reader();
@@ -15429,7 +16046,7 @@ var init_routes = __esm({
15429
16046
  init_loop_monitor();
15430
16047
  init_runtime_stats();
15431
16048
  init_metrics();
15432
- __dirname9 = dirname13(fileURLToPath10(import.meta.url));
16049
+ __dirname9 = dirname14(fileURLToPath11(import.meta.url));
15433
16050
  RISK_PRIORITY = { low: 0, medium: 1, high: 2, critical: 3 };
15434
16051
  }
15435
16052
  });
@@ -15437,9 +16054,9 @@ var init_routes = __esm({
15437
16054
  // src/console/router.ts
15438
16055
  import { Hono } from "hono";
15439
16056
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
15440
- import { readFileSync as readFileSync20, existsSync as existsSync20, unlinkSync as unlinkSync6 } from "fs";
15441
- import { join as join22, dirname as dirname14 } from "path";
15442
- import { fileURLToPath as fileURLToPath11 } from "url";
16057
+ import { readFileSync as readFileSync21, existsSync as existsSync21, unlinkSync as unlinkSync6 } from "fs";
16058
+ import { join as join23, dirname as dirname15 } from "path";
16059
+ import { fileURLToPath as fileURLToPath12 } from "url";
15443
16060
  function getConsoleToken() {
15444
16061
  return process.env[CONSOLE_TOKEN_ENV] || "";
15445
16062
  }
@@ -15465,6 +16082,16 @@ function authMiddleware() {
15465
16082
  function displayRuntimeConfig() {
15466
16083
  return isRuntimeConfigDisabled() ? generateSourceDefaults() : loadRuntimeConfig();
15467
16084
  }
16085
+ function scopedAgentRules(rc) {
16086
+ return Object.fromEntries(
16087
+ Object.entries(getAgentRules(rc)).filter(([id]) => isAllowed("agents", id))
16088
+ );
16089
+ }
16090
+ function scopedScenarioRules(rc) {
16091
+ return Object.fromEntries(
16092
+ Object.entries(getScenarioRules(rc)).filter(([id]) => isAllowed("scenarios", id))
16093
+ );
16094
+ }
15468
16095
  function builtinOnlyReadOnlyMiddleware() {
15469
16096
  return async (c, next) => {
15470
16097
  if (isRuntimeConfigDisabled() && !["GET", "HEAD", "OPTIONS"].includes(c.req.method)) {
@@ -15480,9 +16107,9 @@ function createConsoleRouter() {
15480
16107
  console2.use("/api/*", authMiddleware());
15481
16108
  console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
15482
16109
  const serveIndex = (c) => {
15483
- const indexFile = join22(STATIC_DIR, "index.html");
15484
- if (existsSync20(indexFile)) {
15485
- return c.html(readFileSync20(indexFile, "utf-8"));
16110
+ const indexFile = join23(STATIC_DIR, "index.html");
16111
+ if (existsSync21(indexFile)) {
16112
+ return c.html(readFileSync21(indexFile, "utf-8"));
15486
16113
  }
15487
16114
  return c.html("<h1>AgentMoss Policy Console</h1><p>Frontend not built. Use /console/api/* endpoints.</p>");
15488
16115
  };
@@ -15677,22 +16304,22 @@ function createConsoleRouter() {
15677
16304
  if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
15678
16305
  return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
15679
16306
  }
15680
- const userPath = join22(dirname14(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
16307
+ const userPath = join23(dirname15(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
15681
16308
  const builtinDir = resolveAssetDir(__dirname10, "skills");
15682
16309
  const candidates = [
15683
16310
  ...isRuntimeConfigDisabled() ? [] : [userPath],
15684
- builtinDir ? join22(builtinDir, `${skillId}.md`) : ""
16311
+ builtinDir ? join23(builtinDir, `${skillId}.md`) : ""
15685
16312
  ].filter(Boolean);
15686
16313
  for (const p of candidates) {
15687
- if (existsSync20(p)) {
15688
- return c.json({ skill_id: skillId, path: p, content: readFileSync20(p, "utf-8") });
16314
+ if (existsSync21(p)) {
16315
+ return c.json({ skill_id: skillId, path: p, content: readFileSync21(p, "utf-8") });
15689
16316
  }
15690
16317
  }
15691
16318
  return c.json({ detail: `skill ${skillId} \u4E0D\u5B58\u5728` }, 404);
15692
16319
  });
15693
16320
  console2.get("/api/agents", (c) => {
15694
16321
  const rc = displayRuntimeConfig();
15695
- return c.json({ agents: getAgentRules(rc) });
16322
+ return c.json({ agents: scopedAgentRules(rc) });
15696
16323
  });
15697
16324
  console2.put("/api/agents/rules/enabled", async (c) => {
15698
16325
  const b = await c.req.json();
@@ -15701,8 +16328,9 @@ function createConsoleRouter() {
15701
16328
  if (b.pattern) fp.pattern = b.pattern;
15702
16329
  if (b.keyword) fp.keyword = b.keyword;
15703
16330
  if (b.path) fp.path = b.path;
16331
+ if (!isAllowed("agents", b.agent_id)) return c.json({ detail: `agent ${b.agent_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
15704
16332
  const rc = updateAgentRuleEnabled(b.agent_id, b.category, fp, b.enabled);
15705
- return c.json({ agents: getAgentRules(rc) });
16333
+ return c.json({ agents: scopedAgentRules(rc) });
15706
16334
  });
15707
16335
  console2.post("/api/agents/rules", async (c) => {
15708
16336
  const b = await c.req.json();
@@ -15710,8 +16338,9 @@ function createConsoleRouter() {
15710
16338
  for (const [k, v] of Object.entries(b)) {
15711
16339
  if (!["agent_id", "category"].includes(k) && v !== void 0 && v !== null) rule[k] = v;
15712
16340
  }
16341
+ if (!isAllowed("agents", b.agent_id)) return c.json({ detail: `agent ${b.agent_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
15713
16342
  const rc = addAgentRule(b.agent_id, b.category, rule);
15714
- return c.json({ agents: getAgentRules(rc) });
16343
+ return c.json({ agents: scopedAgentRules(rc) });
15715
16344
  });
15716
16345
  console2.delete("/api/agents/rules", async (c) => {
15717
16346
  const b = await c.req.json();
@@ -15720,18 +16349,20 @@ function createConsoleRouter() {
15720
16349
  if (b.pattern) fp.pattern = b.pattern;
15721
16350
  if (b.keyword) fp.keyword = b.keyword;
15722
16351
  if (b.path) fp.path = b.path;
16352
+ if (!isAllowed("agents", b.agent_id)) return c.json({ detail: `agent ${b.agent_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
15723
16353
  const rc = deleteAgentRule(b.agent_id, b.category, fp);
15724
- return c.json({ agents: getAgentRules(rc) });
16354
+ return c.json({ agents: scopedAgentRules(rc) });
15725
16355
  });
15726
16356
  console2.put("/api/agents/categories/enabled", async (c) => {
15727
16357
  const b = await c.req.json();
16358
+ if (!isAllowed("agents", b.agent_id)) return c.json({ detail: `agent ${b.agent_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
15728
16359
  const rc = updateAgentCategoryEnabled(b.agent_id, b.category, b.enabled);
15729
- return c.json({ agents: getAgentRules(rc) });
16360
+ return c.json({ agents: scopedAgentRules(rc) });
15730
16361
  });
15731
16362
  const enabledScenarioIds = () => (process.env.AGENT_MOSS_SCENARIO || "").split(",").map((s) => s.trim()).filter(Boolean);
15732
16363
  console2.get("/api/scenarios", (c) => {
15733
- const all = getScenarioRules(displayRuntimeConfig());
15734
- const enabled = enabledScenarioIds();
16364
+ const all = scopedScenarioRules(displayRuntimeConfig());
16365
+ const enabled = enabledScenarioIds().filter((sid) => isAllowed("scenarios", sid));
15735
16366
  if (!enabled.length) return c.json({ scenarios: {}, enabled: [] });
15736
16367
  const shown = {};
15737
16368
  for (const sid of enabled) if (all[sid]) shown[sid] = all[sid];
@@ -15744,8 +16375,9 @@ function createConsoleRouter() {
15744
16375
  if (b.pattern) fp.pattern = b.pattern;
15745
16376
  if (b.keyword) fp.keyword = b.keyword;
15746
16377
  if (b.path) fp.path = b.path;
16378
+ if (!isAllowed("scenarios", b.scenario_id)) return c.json({ detail: `scenario ${b.scenario_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
15747
16379
  const rc = updateScenarioRuleEnabled(b.scenario_id, b.category, fp, b.enabled);
15748
- return c.json({ scenarios: getScenarioRules(rc), enabled: enabledScenarioIds() });
16380
+ return c.json({ scenarios: scopedScenarioRules(rc), enabled: enabledScenarioIds().filter((sid) => isAllowed("scenarios", sid)) });
15749
16381
  });
15750
16382
  console2.post("/api/scenarios/rules", async (c) => {
15751
16383
  const b = await c.req.json();
@@ -15753,8 +16385,9 @@ function createConsoleRouter() {
15753
16385
  for (const [k, v] of Object.entries(b)) {
15754
16386
  if (!["scenario_id", "category"].includes(k) && v !== void 0 && v !== null) rule[k] = v;
15755
16387
  }
16388
+ if (!isAllowed("scenarios", b.scenario_id)) return c.json({ detail: `scenario ${b.scenario_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
15756
16389
  const rc = addScenarioRule(b.scenario_id, b.category, rule);
15757
- return c.json({ scenarios: getScenarioRules(rc), enabled: enabledScenarioIds() });
16390
+ return c.json({ scenarios: scopedScenarioRules(rc), enabled: enabledScenarioIds().filter((sid) => isAllowed("scenarios", sid)) });
15758
16391
  });
15759
16392
  console2.delete("/api/scenarios/rules", async (c) => {
15760
16393
  const b = await c.req.json();
@@ -15763,13 +16396,15 @@ function createConsoleRouter() {
15763
16396
  if (b.pattern) fp.pattern = b.pattern;
15764
16397
  if (b.keyword) fp.keyword = b.keyword;
15765
16398
  if (b.path) fp.path = b.path;
16399
+ if (!isAllowed("scenarios", b.scenario_id)) return c.json({ detail: `scenario ${b.scenario_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
15766
16400
  const rc = deleteScenarioRule(b.scenario_id, b.category, fp);
15767
- return c.json({ scenarios: getScenarioRules(rc), enabled: enabledScenarioIds() });
16401
+ return c.json({ scenarios: scopedScenarioRules(rc), enabled: enabledScenarioIds().filter((sid) => isAllowed("scenarios", sid)) });
15768
16402
  });
15769
16403
  console2.put("/api/scenarios/categories/enabled", async (c) => {
15770
16404
  const b = await c.req.json();
16405
+ if (!isAllowed("scenarios", b.scenario_id)) return c.json({ detail: `scenario ${b.scenario_id} \u4E0D\u5728\u672C\u4EA4\u4ED8\u8303\u56F4\u5185` }, 404);
15771
16406
  const rc = updateScenarioCategoryEnabled(b.scenario_id, b.category, b.enabled);
15772
- return c.json({ scenarios: getScenarioRules(rc), enabled: enabledScenarioIds() });
16407
+ return c.json({ scenarios: scopedScenarioRules(rc), enabled: enabledScenarioIds().filter((sid) => isAllowed("scenarios", sid)) });
15773
16408
  });
15774
16409
  console2.get("/api/config", (c) => {
15775
16410
  const rc = displayRuntimeConfig();
@@ -15782,7 +16417,7 @@ function createConsoleRouter() {
15782
16417
  const defaults = generateSourceDefaults();
15783
16418
  try {
15784
16419
  const p = getRuntimeConfigPath();
15785
- if (existsSync20(p)) unlinkSync6(p);
16420
+ if (existsSync21(p)) unlinkSync6(p);
15786
16421
  } catch {
15787
16422
  }
15788
16423
  return c.json(withL22View(defaults));
@@ -15818,8 +16453,9 @@ var init_router = __esm({
15818
16453
  init_rules_loader();
15819
16454
  init_asset_dir();
15820
16455
  init_rules_mode();
15821
- __dirname10 = dirname14(fileURLToPath11(import.meta.url));
15822
- STATIC_DIR = join22(__dirname10, "static");
16456
+ init_edition_scope();
16457
+ __dirname10 = dirname15(fileURLToPath12(import.meta.url));
16458
+ STATIC_DIR = join23(__dirname10, "static");
15823
16459
  CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
15824
16460
  }
15825
16461
  });
@@ -15847,8 +16483,8 @@ import { Hono as Hono2 } from "hono";
15847
16483
  import { cors } from "hono/cors";
15848
16484
  import { logger } from "hono/logger";
15849
16485
  import net from "net";
15850
- import { existsSync as existsSync21, writeFileSync as writeFileSync8, renameSync as renameSync3, mkdirSync as mkdirSync11 } from "fs";
15851
- import { dirname as dirname15 } from "path";
16486
+ import { existsSync as existsSync22, writeFileSync as writeFileSync8, renameSync as renameSync3, mkdirSync as mkdirSync11 } from "fs";
16487
+ import { dirname as dirname16 } from "path";
15852
16488
  function logDeploymentSelfCheck() {
15853
16489
  try {
15854
16490
  const mode = getRulesMode();
@@ -15875,7 +16511,7 @@ function logDeploymentSelfCheck() {
15875
16511
  console.log("\u5C42\u7EA7\u5F00\u5173: " + layerKeys.map((k) => `${k}=${isLayerEnabled(k) ? "on" : "OFF"}`).join(" "));
15876
16512
  if (!builtinOnly) {
15877
16513
  try {
15878
- const dirs = rulesDirs().filter((d) => existsSync21(d));
16514
+ const dirs = rulesDirs().filter((d) => existsSync22(d));
15879
16515
  if (dirs.length > 0) {
15880
16516
  console.log(`\u89C4\u5219\u76EE\u5F55: ${dirs.join(", ")}\uFF08\u53EA\u8BFB\u5176\u4E2D ${OVERRIDE_FILENAME} / ${EXTRA_FILENAME}\uFF09`);
15881
16517
  }
@@ -15967,9 +16603,29 @@ function createApp() {
15967
16603
  if (!okAuth && !isPublicPage) {
15968
16604
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
15969
16605
  }
16606
+ let gateCallId = null;
16607
+ const gateRequired = c.req.header(GATE_IDENTITY_HEADER);
16608
+ const gatePath = path9.replace(/\/+$/, "");
16609
+ if (method === "POST" && gateRequired !== void 0 && (gatePath === "/api/v1/analyze" || gatePath === "/api/v1/review")) {
16610
+ if (principal !== GATE_PRINCIPAL) {
16611
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8EAB\u4EFD\u6821\u9A8C\u5931\u8D25" }, 403);
16612
+ }
16613
+ if (gateRequired !== "1") {
16614
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
16615
+ }
16616
+ }
16617
+ if (method === "POST" && gatePath === "/api/v1/analyze" && principal === GATE_PRINCIPAL) {
16618
+ const id = c.req.header(GATE_CALL_ID_HEADER) || "";
16619
+ if (gateRequired !== "1" || !validGateCallId(id)) {
16620
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
16621
+ }
16622
+ gateCallId = id;
16623
+ c.set("gateCallId", id);
16624
+ }
15970
16625
  if (limiter.enabled && path9.startsWith("/api/")) {
15971
16626
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
15972
16627
  if (!limiter.allow(key)) {
16628
+ if (gateCallId) c.header(GATE_RATE_LIMIT_HEADER, gateCallId);
15973
16629
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
15974
16630
  }
15975
16631
  }
@@ -15985,6 +16641,7 @@ function createApp() {
15985
16641
  const busy = (detail, status = 503) => {
15986
16642
  c.header("Retry-After", "1");
15987
16643
  c.header("Connection", "close");
16644
+ if (gateCallId) c.header(GATE_BUSY_HEADER, gateCallId);
15988
16645
  return c.json({ detail }, status);
15989
16646
  };
15990
16647
  try {
@@ -16052,12 +16709,12 @@ function createApp() {
16052
16709
  }
16053
16710
  async function findFreePort(startPort, host = "127.0.0.1", scan = 100) {
16054
16711
  for (let port = startPort; port < startPort + scan; port++) {
16055
- const free = await new Promise((resolve12) => {
16712
+ const free = await new Promise((resolve13) => {
16056
16713
  const server = net.createServer();
16057
16714
  server.listen(port, host, () => {
16058
- server.close(() => resolve12(true));
16715
+ server.close(() => resolve13(true));
16059
16716
  });
16060
- server.on("error", () => resolve12(false));
16717
+ server.on("error", () => resolve13(false));
16061
16718
  });
16062
16719
  if (free) {
16063
16720
  if (port !== startPort) {
@@ -16096,7 +16753,7 @@ async function warmUpEngine() {
16096
16753
  function writePortFile(port) {
16097
16754
  try {
16098
16755
  const path9 = getPortFilePath();
16099
- mkdirSync11(dirname15(path9), { recursive: true });
16756
+ mkdirSync11(dirname16(path9), { recursive: true });
16100
16757
  const payload = JSON.stringify({
16101
16758
  port,
16102
16759
  pid: process.pid,
@@ -16142,29 +16799,29 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
16142
16799
  socketPath,
16143
16800
  close: async () => {
16144
16801
  if (!server) return;
16145
- await new Promise((resolve12) => {
16146
- server.close(() => resolve12());
16802
+ await new Promise((resolve13) => {
16803
+ server.close(() => resolve13());
16147
16804
  });
16148
16805
  server = null;
16149
16806
  },
16150
16807
  serve: async () => {
16151
16808
  failFastOnAuthError();
16152
- const { mkdirSync: mkdirSync13, existsSync: existsSync23, unlinkSync: unlinkSync7 } = await import("fs");
16153
- const { dirname: dirname17 } = await import("path");
16154
- const dir = dirname17(socketPath);
16809
+ const { mkdirSync: mkdirSync13, existsSync: existsSync24, unlinkSync: unlinkSync7 } = await import("fs");
16810
+ const { dirname: dirname18 } = await import("path");
16811
+ const dir = dirname18(socketPath);
16155
16812
  if (dir) {
16156
16813
  try {
16157
16814
  mkdirSync13(dir, { recursive: true });
16158
16815
  } catch {
16159
16816
  }
16160
16817
  }
16161
- if (existsSync23(socketPath)) {
16818
+ if (existsSync24(socketPath)) {
16162
16819
  const { connect } = await import("net");
16163
- const inUse = await new Promise((resolve12) => {
16820
+ const inUse = await new Promise((resolve13) => {
16164
16821
  const probe = connect(socketPath);
16165
16822
  const done = (v) => {
16166
16823
  probe.destroy();
16167
- resolve12(v);
16824
+ resolve13(v);
16168
16825
  };
16169
16826
  probe.once("connect", () => done(true));
16170
16827
  probe.once("error", () => done(false));
@@ -16192,9 +16849,9 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
16192
16849
  server.keepAliveTimeout = keepAliveSec() * 1e3;
16193
16850
  } catch {
16194
16851
  }
16195
- await new Promise((resolve12, reject) => {
16852
+ await new Promise((resolve13, reject) => {
16196
16853
  server.once("error", reject);
16197
- server.listen(socketPath, () => resolve12());
16854
+ server.listen(socketPath, () => resolve13());
16198
16855
  });
16199
16856
  try {
16200
16857
  const { chmodSync: chmodSync2 } = await import("fs");
@@ -16288,26 +16945,26 @@ __export(rules_tools_exports, {
16288
16945
  rulesStatusText: () => rulesStatusText,
16289
16946
  templateSourceDir: () => templateSourceDir
16290
16947
  });
16291
- import { existsSync as existsSync22, mkdirSync as mkdirSync12, readdirSync as readdirSync8, readFileSync as readFileSync21, writeFileSync as writeFileSync9 } from "fs";
16292
- import { dirname as dirname16, join as join24 } from "path";
16293
- import { fileURLToPath as fileURLToPath12 } from "url";
16948
+ import { existsSync as existsSync23, mkdirSync as mkdirSync12, readdirSync as readdirSync8, readFileSync as readFileSync22, writeFileSync as writeFileSync9 } from "fs";
16949
+ import { dirname as dirname17, join as join25 } from "path";
16950
+ import { fileURLToPath as fileURLToPath13 } from "url";
16294
16951
  function initRulesDir(targetDir, opts = {}) {
16295
16952
  mkdirSync12(targetDir, { recursive: true });
16296
16953
  const written = [];
16297
- const extraPath = join24(targetDir, EXTRA_FILENAME);
16298
- if (opts.force || !existsSync22(extraPath)) {
16954
+ const extraPath = join25(targetDir, EXTRA_FILENAME);
16955
+ if (opts.force || !existsSync23(extraPath)) {
16299
16956
  writeFileSync9(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
16300
16957
  written.push(extraPath);
16301
16958
  }
16302
- const samplePath = join24(targetDir, OVERRIDE_FILENAME);
16303
- if (opts.force || !existsSync22(samplePath)) {
16959
+ const samplePath = join25(targetDir, OVERRIDE_FILENAME);
16960
+ if (opts.force || !existsSync23(samplePath)) {
16304
16961
  let payload = OVERRIDE_TEMPLATE;
16305
16962
  if (opts.withBuiltin) {
16306
16963
  let data = {};
16307
16964
  const builtin = resolveRulesFile("l1_rules.json");
16308
- if (builtin && existsSync22(builtin)) {
16965
+ if (builtin && existsSync23(builtin)) {
16309
16966
  try {
16310
- data = JSON.parse(readFileSync21(builtin, "utf-8")) || {};
16967
+ data = JSON.parse(readFileSync22(builtin, "utf-8")) || {};
16311
16968
  } catch {
16312
16969
  data = {};
16313
16970
  }
@@ -16318,17 +16975,17 @@ function initRulesDir(targetDir, opts = {}) {
16318
16975
  writeFileSync9(samplePath, JSON.stringify(payload, null, 2), "utf-8");
16319
16976
  written.push(samplePath);
16320
16977
  }
16321
- const readmeSrc = join24(templateSourceDir(), "README.md");
16322
- const readmeDst = join24(targetDir, "README.md");
16323
- if (existsSync22(readmeSrc) && (opts.force || !existsSync22(readmeDst))) {
16324
- writeFileSync9(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
16978
+ const readmeSrc = join25(templateSourceDir(), "README.md");
16979
+ const readmeDst = join25(targetDir, "README.md");
16980
+ if (existsSync23(readmeSrc) && (opts.force || !existsSync23(readmeDst))) {
16981
+ writeFileSync9(readmeDst, readFileSync22(readmeSrc, "utf-8"), "utf-8");
16325
16982
  written.push(readmeDst);
16326
16983
  }
16327
16984
  return written;
16328
16985
  }
16329
16986
  function templateSourceDir() {
16330
- const cands = [join24(__dirname11, "data", "rules_template"), join24(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
16331
- for (const c of cands) if (existsSync22(c)) return c;
16987
+ const cands = [join25(__dirname11, "data", "rules_template"), join25(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
16988
+ for (const c of cands) if (existsSync23(c)) return c;
16332
16989
  return cands[0];
16333
16990
  }
16334
16991
  function templateFiles(dirs) {
@@ -16336,7 +16993,7 @@ function templateFiles(dirs) {
16336
16993
  for (const d of dirs) {
16337
16994
  try {
16338
16995
  for (const name of readdirSync8(d)) {
16339
- if (name.endsWith(".json.\u793A\u4F8B")) out.push(join24(d, name));
16996
+ if (name.endsWith(".json.\u793A\u4F8B")) out.push(join25(d, name));
16340
16997
  }
16341
16998
  } catch {
16342
16999
  }
@@ -16345,7 +17002,7 @@ function templateFiles(dirs) {
16345
17002
  }
16346
17003
  function rulesStatusText() {
16347
17004
  const lines = [];
16348
- const existing = rulesDirs().filter((d) => existsSync22(d));
17005
+ const existing = rulesDirs().filter((d) => existsSync23(d));
16349
17006
  lines.push("\u89C4\u5219\u76EE\u5F55: " + (existing.length > 0 ? existing.join(", ") : "\uFF08\u672A\u8BBE\u7F6E / \u4E0D\u5B58\u5728\uFF09"));
16350
17007
  if (existing.length > 0) {
16351
17008
  lines.push(` \uFF08\u53EA\u8BFB\u5176\u4E2D\u7684 ${OVERRIDE_FILENAME} \u4E0E ${EXTRA_FILENAME}\uFF1B\u5176\u4ED6\u6587\u4EF6\u540D\u4E00\u5F8B\u4E0D\u8BFB\uFF09`);
@@ -16392,7 +17049,7 @@ var init_rules_tools = __esm({
16392
17049
  "use strict";
16393
17050
  init_esm_shims();
16394
17051
  init_rules_loader();
16395
- __dirname11 = dirname16(fileURLToPath12(import.meta.url));
17052
+ __dirname11 = dirname17(fileURLToPath13(import.meta.url));
16396
17053
  EXTRA_TEMPLATE = {
16397
17054
  _\u8BF4\u660E: [
16398
17055
  "\u8FFD\u52A0\u89C4\u5219\uFF1A\u5185\u7F6E\u89C4\u5219\u5168\u90E8\u4FDD\u7559\uFF0C\u4F60\u5199\u5728\u8FD9\u91CC\u7684\u89C4\u5219\u52A0\u5728\u5185\u7F6E\u4E4B\u540E\u4E00\u8D77\u5224\u5B9A\u3002",
@@ -16435,7 +17092,7 @@ var init_rules_tools = __esm({
16435
17092
  init_esm_shims();
16436
17093
  init_server();
16437
17094
  init_package_json();
16438
- import { fileURLToPath as fileURLToPath13 } from "url";
17095
+ import { fileURLToPath as fileURLToPath14 } from "url";
16439
17096
  import { realpathSync as realpathSync2 } from "fs";
16440
17097
  function printHelp() {
16441
17098
  console.log(`AgentMoss security analysis engine (TypeScript v${version})
@@ -16668,7 +17325,7 @@ async function main() {
16668
17325
  const { execSync } = await import("child_process");
16669
17326
  const fs9 = await import("fs");
16670
17327
  const path9 = await import("path");
16671
- const { fileURLToPath: fileURLToPath14 } = await import("url");
17328
+ const { fileURLToPath: fileURLToPath15 } = await import("url");
16672
17329
  if (process.getuid?.() !== 0) {
16673
17330
  try {
16674
17331
  execSync("sudo -n true", { stdio: "ignore", timeout: 5e3 });
@@ -16683,7 +17340,7 @@ async function main() {
16683
17340
  execSync(sudoArgs.join(" "), { stdio: "inherit" });
16684
17341
  process.exit(0);
16685
17342
  }
16686
- const __filename7 = fileURLToPath14(import.meta.url);
17343
+ const __filename7 = fileURLToPath15(import.meta.url);
16687
17344
  const __dirname12 = path9.dirname(__filename7);
16688
17345
  let srcPath = path9.join(__dirname12, "data", "agent_moss.service");
16689
17346
  if (!fs9.existsSync(srcPath)) {
@@ -16737,37 +17394,45 @@ async function main() {
16737
17394
  const expectInstance = process.env.AGENT_MOSS_INSTANCE || "";
16738
17395
  let foundPort = 0;
16739
17396
  let version2 = "";
16740
- const otherInstances = [];
17397
+ const seen = [];
16741
17398
  for (let port = 9090; port <= 9095; port++) {
16742
17399
  try {
16743
- const data = await new Promise((resolve12, reject) => {
17400
+ const data = await new Promise((resolve13, reject) => {
16744
17401
  const req = http.get(`http://127.0.0.1:${port}/api/v1/health`, { timeout: 2e3 }, (res) => {
16745
17402
  let body = "";
16746
17403
  res.on("data", (chunk) => body += chunk);
16747
17404
  res.on("end", () => {
16748
17405
  try {
16749
- resolve12(JSON.parse(body));
17406
+ resolve13(JSON.parse(body));
16750
17407
  } catch {
16751
17408
  reject();
16752
17409
  }
16753
17410
  });
16754
17411
  });
17412
+ req.on("timeout", () => req.destroy(new Error("probe timeout")));
16755
17413
  req.on("error", reject);
16756
17414
  });
16757
- if (data.status === "healthy") {
17415
+ if (data.status === "healthy" || data.status === "degraded") {
16758
17416
  const inst = data.instance || "";
16759
- if (inst === expectInstance) {
17417
+ const ver = data.version || "";
17418
+ seen.push({ port, instance: inst, version: ver });
17419
+ if (!foundPort && inst === expectInstance) {
16760
17420
  foundPort = port;
16761
- version2 = data.version || "";
16762
- break;
17421
+ version2 = ver;
16763
17422
  }
16764
- otherInstances.push({ port, instance: inst });
16765
17423
  }
16766
17424
  } catch {
16767
17425
  }
16768
17426
  }
17427
+ const otherInstances = seen.filter((s) => s.port !== foundPort);
16769
17428
  if (foundPort) {
16770
17429
  console.log(`\u2705 AgentMoss \u670D\u52A1\u8FD0\u884C\u4E2D`);
17430
+ console.log(` Instance: ${expectInstance || "(\u672A\u6307\u5B9A)"}`);
17431
+ if (!expectInstance && seen.length > 1) {
17432
+ console.log(
17433
+ " \u26A0\uFE0F \u672A\u8BBE\u7F6E AGENT_MOSS_INSTANCE\uFF0C\u4E0A\u9762\u663E\u793A\u7684\u662F\u7B2C\u4E00\u4E2A instance \u4E3A\u7A7A\u7684\u5B9E\u4F8B\uFF1B\u540C\u673A\u7684\u5176\u5B83\u5B9E\u4F8B\u89C1\u4E0B\u65B9\u6E05\u5355"
17434
+ );
17435
+ }
16771
17436
  console.log(` \u7248\u672C: ${version2 || "?"}`);
16772
17437
  console.log(` \u7AEF\u53E3: ${foundPort}`);
16773
17438
  console.log(` Console: http://127.0.0.1:${foundPort}/console`);
@@ -16778,18 +17443,19 @@ async function main() {
16778
17443
  console.log(` Systemd: \u672A\u6CE8\u518C\uFF08\u8FD0\u884C agent-moss install --enable \u5B89\u88C5\uFF09`);
16779
17444
  }
16780
17445
  try {
16781
- const data = await new Promise((resolve12, reject) => {
17446
+ const data = await new Promise((resolve13, reject) => {
16782
17447
  const req = http.get(`http://127.0.0.1:${foundPort}/console/api/config`, { timeout: 3e3 }, (res) => {
16783
17448
  let body = "";
16784
17449
  res.on("data", (chunk) => body += chunk);
16785
17450
  res.on("end", () => {
16786
17451
  try {
16787
- resolve12(JSON.parse(body));
17452
+ resolve13(JSON.parse(body));
16788
17453
  } catch {
16789
17454
  reject();
16790
17455
  }
16791
17456
  });
16792
17457
  });
17458
+ req.on("timeout", () => req.destroy(new Error("probe timeout")));
16793
17459
  req.on("error", reject);
16794
17460
  });
16795
17461
  const layers = data.layers || {};
@@ -16801,6 +17467,15 @@ async function main() {
16801
17467
  console.log(` L3 LLM \u5206\u6790: ${l3}`);
16802
17468
  } catch {
16803
17469
  }
17470
+ if (otherInstances.length > 0) {
17471
+ console.log();
17472
+ console.log(` \u26A0\uFE0F \u540C\u673A\u53E6\u6709 ${otherInstances.length} \u4E2A\u5B9E\u4F8B\uFF08\u672A\u8BA1\u5165\u4E0A\u9762\u7684\u72B6\u6001\uFF09\uFF1A`);
17473
+ for (const o of otherInstances) {
17474
+ const tag = o.instance === expectInstance ? " \u2190 \u4E0E\u672C\u5B9E\u4F8B\u540C\u540D\uFF08\u53EF\u80FD\u662F\u5347\u7EA7\u540E\u672A\u9000\u51FA\u7684\u65E7/\u65B0\u8FDB\u7A0B\uFF09" : "";
17475
+ console.log(` \u7AEF\u53E3 ${o.port} instance=${o.instance || "(\u7A7A)"} v${o.version || "?"}${tag}`);
17476
+ }
17477
+ console.log(" \u67E5\u770B\u6307\u5B9A\u5B9E\u4F8B\uFF1AAGENT_MOSS_INSTANCE=<\u540D\u5B57> agent-moss status");
17478
+ }
16804
17479
  console.log();
16805
17480
  console.log(" \u542F\u505C\u547D\u4EE4\uFF1A");
16806
17481
  console.log(" systemctl start agent-moss \u542F\u52A8");
@@ -16809,15 +17484,15 @@ async function main() {
16809
17484
  console.log(" systemctl status agent-moss \u72B6\u6001");
16810
17485
  console.log(" journalctl -u agent_moss -f \u65E5\u5FD7");
16811
17486
  } else if (otherInstances.length > 0) {
16812
- console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C\uFF08instance=${expectInstance || "(\u7A7A)"}\uFF09`);
17487
+ console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C\uFF08instance=${expectInstance || "(\u672A\u6307\u5B9A)"}\uFF09`);
16813
17488
  console.log(` Systemd: ${systemdInfo ? "active" : "inactive"}`);
16814
- const detail = otherInstances.map((o) => `\u7AEF\u53E3 ${o.port} (instance=${o.instance || "(\u7A7A)"})`).join("; ");
17489
+ const detail = otherInstances.map((o) => `\u7AEF\u53E3 ${o.port} (instance=${o.instance || "(\u7A7A)"}, v${o.version || "?"})`).join("; ");
16815
17490
  console.log(` \u26A0\uFE0F \u68C0\u6D4B\u5230\u5176\u4ED6 agent \u7684 agentmoss \u5B9E\u4F8B: ${detail}`);
16816
- console.log(` \u8FD9\u4E9B\u4E0D\u5C5E\u4E8E\u672C\u5B9E\u4F8B\uFF08instance=${expectInstance || "(\u7A7A)"}\uFF09\uFF0C\u672A\u8BA1\u5165\u8FD0\u884C\u72B6\u6001\u3002`);
17491
+ console.log(` \u8FD9\u4E9B\u4E0D\u5C5E\u4E8E\u672C\u5B9E\u4F8B\uFF08instance=${expectInstance || "(\u672A\u6307\u5B9A)"}\uFF09\uFF0C\u672A\u8BA1\u5165\u8FD0\u884C\u72B6\u6001\u3002`);
16817
17492
  console.log(` \u542F\u52A8\u672C\u5B9E\u4F8B: AGENT_MOSS_INSTANCE=${expectInstance || "xiaoo"} agent-moss server`);
16818
17493
  process.exit(1);
16819
17494
  } else {
16820
- console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C`);
17495
+ console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C\uFF08instance=${expectInstance || "(\u672A\u6307\u5B9A)"}\uFF09`);
16821
17496
  if (systemdInfo) {
16822
17497
  console.log(` Systemd: active \u4F46\u7AEF\u53E3\u63A2\u6D4B\u4E0D\u5230`);
16823
17498
  console.log(` \u68C0\u67E5\u65E5\u5FD7\uFF1Ajournalctl -u agent_moss -n 20 --no-pager`);
@@ -16839,9 +17514,9 @@ async function main() {
16839
17514
  var isMain = (() => {
16840
17515
  try {
16841
17516
  if (!process.argv[1]) return false;
16842
- const thisFile = realpathSync2(fileURLToPath13(import.meta.url));
17517
+ const thisFile = realpathSync2(fileURLToPath14(import.meta.url));
16843
17518
  const argv1 = realpathSync2(
16844
- process.argv[1].startsWith("file://") ? fileURLToPath13(process.argv[1]) : process.argv[1]
17519
+ process.argv[1].startsWith("file://") ? fileURLToPath14(process.argv[1]) : process.argv[1]
16845
17520
  );
16846
17521
  return thisFile === argv1;
16847
17522
  } catch {