@kenhkl/agent-moss 0.17.41 → 0.17.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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;
@@ -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();
@@ -5316,6 +5482,21 @@ function detectLanguage(path9, content) {
5316
5482
  }
5317
5483
  return "other";
5318
5484
  }
5485
+ function isInstructionTarget(path9) {
5486
+ const p = (path9 || "").replace(/\\/g, "/").toLowerCase();
5487
+ if (!p) return false;
5488
+ const base = p.split("/").pop() || "";
5489
+ if (["agents.md", "claude.md", "system.md", "prompt.md", "instructions.md", ".cursorrules"].includes(base)) {
5490
+ return true;
5491
+ }
5492
+ if (/(?:^|[-_.])(?:prompt|instruction|system)(?:[-_.]|$)/.test(base)) return true;
5493
+ return INSTRUCTION_TARGET_RE.test(p);
5494
+ }
5495
+ function isDataDocument(actionType, actionDetailRaw) {
5496
+ const payload = extractWritePayload(actionType, actionDetailRaw);
5497
+ if (payload === null) return false;
5498
+ return detectLanguage(payload.path, payload.content) === "data" && !isInstructionTarget(payload.path);
5499
+ }
5319
5500
  function stripShellComments(text) {
5320
5501
  const out = [];
5321
5502
  let heredocEnd = null;
@@ -5478,7 +5659,7 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
5478
5659
  }
5479
5660
  return snippets;
5480
5661
  }
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;
5662
+ 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
5663
  var init_written_content_analyzer = __esm({
5483
5664
  "src/engine/written-content-analyzer.ts"() {
5484
5665
  "use strict";
@@ -5501,7 +5682,12 @@ var init_written_content_analyzer = __esm({
5501
5682
  "file_edit",
5502
5683
  "editfile",
5503
5684
  "searchreplace",
5504
- "search_replace"
5685
+ "search_replace",
5686
+ // 通用 workspace 工具名(ClawPartner/QwenPaw 等宿主常用)
5687
+ "workspace_write_file",
5688
+ "workspace_edit_file",
5689
+ "workspace_writefile",
5690
+ "workspace_editfile"
5505
5691
  ]);
5506
5692
  WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
5507
5693
  APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
@@ -5510,6 +5696,7 @@ var init_written_content_analyzer = __esm({
5510
5696
  INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
5511
5697
  QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
5512
5698
  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;
5699
+ INSTRUCTION_TARGET_RE = /(?:^|[/\\])(?:prompts?|instructions?|skills?|memories|memory|config|policies|policy|\.claude|\.cursor)(?:[/\\]|$)|(?:^|[/\\])(?:AGENTS?|CLAUDE|SYSTEM|PROMPT|INSTRUCTIONS?)(?:\.[^/\\]+)?$|(?:^|[/\\])\.cursorrules$/i;
5513
5700
  HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
5514
5701
  }
5515
5702
  });
@@ -5753,6 +5940,23 @@ function runHeuristicCheck(input) {
5753
5940
  deobfuscated
5754
5941
  );
5755
5942
  }
5943
+ const extraScanDetail = stripSearchPatternLiterals(scanDetail);
5944
+ const extraScanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => {
5945
+ const stripped = stripSearchPatternLiterals(sn);
5946
+ return [`${input.aNext.actionType}: ${stripped}`, stripped];
5947
+ }) : String(input.osType || "").toLowerCase() === "windows" ? [
5948
+ `${input.aNext.actionType}: ${extraScanDetail}`,
5949
+ extraScanDetail,
5950
+ `${input.aNext.actionType}: ${extraScanDetail.replace(/\//g, "\\")}`,
5951
+ extraScanDetail.replace(/\//g, "\\")
5952
+ ] : [`${input.aNext.actionType}: ${extraScanDetail}`, extraScanDetail];
5953
+ const extraDeobfuscated = normalizeShellObfuscation(extraScanDetail);
5954
+ if (extraDeobfuscated !== extraScanDetail) {
5955
+ extraScanCommands.push(
5956
+ `${input.aNext.actionType}: ${extraDeobfuscated}`,
5957
+ extraDeobfuscated
5958
+ );
5959
+ }
5756
5960
  let topRiskType = "";
5757
5961
  const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
5758
5962
  const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
@@ -5777,7 +5981,7 @@ function runHeuristicCheck(input) {
5777
5981
  for (const rule of agentExt.extra_command_patterns) {
5778
5982
  try {
5779
5983
  const re = new RegExp(rule.pattern, "i");
5780
- if (scanCommands.some((c) => re.test(c))) {
5984
+ if (extraScanCommands.some((c) => re.test(c))) {
5781
5985
  matched.push(`agent \u4E13\u5C5E\u89C4\u5219: ${rule.reason}`);
5782
5986
  if (severityRank(rule.risk_level) > severityRank(highestSeverity)) {
5783
5987
  highestSeverity = rule.risk_level;
@@ -5788,7 +5992,7 @@ function runHeuristicCheck(input) {
5788
5992
  }
5789
5993
  }
5790
5994
  }
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();
5995
+ 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
5996
  let pythonWalkOnerrorOnly = false;
5793
5997
  if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
5794
5998
  pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
@@ -6039,16 +6243,83 @@ function splitCommandSegments2(actionDetail) {
6039
6243
  if (start < actionDetail.length) segments.push(actionDetail.slice(start));
6040
6244
  return segments;
6041
6245
  }
6246
+ function shellTokens(seg) {
6247
+ const tokens = [];
6248
+ let cur = "";
6249
+ let quote = "";
6250
+ for (let i = 0; i < seg.length; i++) {
6251
+ const ch = seg[i];
6252
+ if (quote) {
6253
+ if (ch === quote) quote = "";
6254
+ else cur += ch;
6255
+ continue;
6256
+ }
6257
+ if (ch === '"' || ch === "'") {
6258
+ quote = ch;
6259
+ continue;
6260
+ }
6261
+ if (/\s/.test(ch)) {
6262
+ if (cur) {
6263
+ tokens.push(cur);
6264
+ cur = "";
6265
+ }
6266
+ continue;
6267
+ }
6268
+ cur += ch;
6269
+ }
6270
+ if (quote) return null;
6271
+ if (cur) tokens.push(cur);
6272
+ return tokens;
6273
+ }
6274
+ function stripSearchPatternArgument(seg) {
6275
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) return seg;
6276
+ const tokens = shellTokens(seg);
6277
+ if (!tokens || tokens.length === 0) return seg;
6278
+ let idx = 0;
6279
+ while (idx < tokens.length && COMMAND_PREFIX_WORDS.has(tokens[idx])) idx++;
6280
+ if (idx >= tokens.length || !TEXT_SEARCH_COMMANDS.has(tokens[idx])) return seg;
6281
+ let patternIdx = null;
6282
+ let i = idx + 1;
6283
+ while (i < tokens.length) {
6284
+ const token = tokens[i];
6285
+ if (token === "--") {
6286
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
6287
+ break;
6288
+ }
6289
+ if (token === "-e" || token === "--regexp") {
6290
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
6291
+ break;
6292
+ }
6293
+ if (token.startsWith("--regexp=")) {
6294
+ patternIdx = i;
6295
+ break;
6296
+ }
6297
+ if (token === "-f" || token === "--file" || token.startsWith("--file=")) break;
6298
+ if (token.startsWith("-") && token !== "-") {
6299
+ i += SEARCH_OPTION_WITH_ARG.has(token) ? 2 : 1;
6300
+ continue;
6301
+ }
6302
+ patternIdx = i;
6303
+ break;
6304
+ }
6305
+ if (patternIdx === null || patternIdx >= tokens.length) return seg;
6306
+ tokens.splice(patternIdx, 1);
6307
+ return tokens.map((t) => /\s/.test(t) ? `'${t.replaceAll("'", "'\\''")}'` : t).join(" ");
6308
+ }
6042
6309
  function stripSearchPatternLiterals(actionDetail) {
6043
6310
  const parts = [];
6044
6311
  for (const seg of splitCommandSegments2(actionDetail)) {
6312
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) {
6313
+ parts.push(seg);
6314
+ continue;
6315
+ }
6045
6316
  const low = seg.trim().toLowerCase();
6046
6317
  const words = low.length ? low.split(/\s+/) : [];
6047
6318
  let idx = 0;
6048
6319
  while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
6049
6320
  const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
6050
6321
  if (isSearch && !low.includes("--pre")) {
6051
- parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
6322
+ parts.push(stripSearchPatternArgument(seg));
6052
6323
  } else {
6053
6324
  parts.push(seg);
6054
6325
  }
@@ -6373,7 +6644,7 @@ function checkDangerousPatterns(actionType, actionDetail) {
6373
6644
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
6374
6645
  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
6646
  const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
6376
- if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
6647
+ if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
6377
6648
  return {
6378
6649
  allowed: false,
6379
6650
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -6515,7 +6786,7 @@ function checkLateralMovement(actionDetail) {
6515
6786
  }
6516
6787
  return null;
6517
6788
  }
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;
6789
+ 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
6790
  var init_heuristic = __esm({
6520
6791
  "src/engine/heuristic.ts"() {
6521
6792
  "use strict";
@@ -6564,6 +6835,28 @@ var init_heuristic = __esm({
6564
6835
  COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
6565
6836
  TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
6566
6837
  COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
6838
+ SEARCH_OPTION_WITH_ARG = /* @__PURE__ */ new Set([
6839
+ "-m",
6840
+ "--max-count",
6841
+ "-A",
6842
+ "--after-context",
6843
+ "-B",
6844
+ "--before-context",
6845
+ "-C",
6846
+ "--context",
6847
+ "-d",
6848
+ "--directories",
6849
+ "-D",
6850
+ "--devices",
6851
+ "--include",
6852
+ "--exclude",
6853
+ "--exclude-dir",
6854
+ "--glob",
6855
+ "--iglob",
6856
+ "--type",
6857
+ "--type-add",
6858
+ "--type-not"
6859
+ ]);
6567
6860
  SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
6568
6861
  SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
6569
6862
  SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
@@ -9465,6 +9758,9 @@ async function runLLMAnalysis(input, previous) {
9465
9758
  scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
9466
9759
  }
9467
9760
  const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
9761
+ const budgetMode = getAgentMossSetting("AGENT_MOSS_LLM_BUDGET_MODE", "hard").trim().toLowerCase() === "soft" ? "soft" : "hard";
9762
+ const budgetActive = maxPromptTokens > 0;
9763
+ const tokenLimit = budgetActive && budgetMode === "hard" ? Math.floor(maxPromptTokens * 100 / 115) : maxPromptTokens;
9468
9764
  let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
9469
9765
  let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
9470
9766
  let prompt = "";
@@ -9481,13 +9777,14 @@ async function runLLMAnalysis(input, previous) {
9481
9777
  historyMaxItems,
9482
9778
  historyMaxChars
9483
9779
  );
9484
- if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
9780
+ if (!budgetActive || estimateTokens(prompt) <= tokenLimit) break;
9485
9781
  historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
9486
9782
  historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
9487
9783
  }
9488
- if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
9784
+ let budgetCode = "";
9785
+ if (budgetActive && estimateTokens(prompt) > tokenLimit) {
9489
9786
  const estimated = estimateTokens(prompt);
9490
- const ratio = estimated / maxPromptTokens;
9787
+ const ratio = tokenLimit > 0 ? estimated / tokenLimit : Number.POSITIVE_INFINITY;
9491
9788
  const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
9492
9789
  const truncated = truncateDetail(input.aNext.actionDetail, allowed);
9493
9790
  prompt = buildPrompt(
@@ -9503,8 +9800,14 @@ async function runLLMAnalysis(input, previous) {
9503
9800
  historyMaxChars
9504
9801
  );
9505
9802
  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`
9803
+ `[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
9804
  );
9805
+ if (estimateTokens(prompt) > tokenLimit) {
9806
+ if (budgetMode === "hard") {
9807
+ throw new LLMPromptBudgetExceeded("l3_budget_unreachable");
9808
+ }
9809
+ budgetCode = "l3_budget_unreachable";
9810
+ }
9508
9811
  }
9509
9812
  logPrompt(prompt, input.aNext, previous.llmLogPath);
9510
9813
  traceFull("l3.prompt", {
@@ -9517,6 +9820,7 @@ async function runLLMAnalysis(input, previous) {
9517
9820
  prompt_chars: prompt.length
9518
9821
  });
9519
9822
  const result = await analyzeWithLLM(prompt, config);
9823
+ if (budgetCode) result.degraded = [...result.degraded || [], budgetCode];
9520
9824
  traceSummary("l3.verdict", {
9521
9825
  allowed: result.allowed,
9522
9826
  risk_level: result.riskLevel,
@@ -9590,11 +9894,14 @@ function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis,
9590
9894
  const skillsText = formatSkillsForPrompt(matchedSkills);
9591
9895
  const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
9592
9896
  const promptHistoryText = formatPromptHistory(input.promptHistory);
9897
+ const historyAuthorization = /(因历史窗口上限省略|本段因长度上限已截断)/.test(promptHistoryText) ? `
9898
+
9899
+ ${HISTORY_AUTHORIZATION}` : "";
9593
9900
  const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
9594
9901
  const hintsText = formatHints(previous);
9595
9902
  const securityJudgeTemplate = templates["security_judge"];
9596
9903
  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("}}", "}");
9904
+ 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
9905
  }
9599
9906
  console.warn("[AgentMoss] security_judge template missing, using sparse fallback prompt");
9600
9907
  return `## \u5F53\u524D\u64CD\u4F5C\u4E0A\u4E0B\u6587
@@ -9630,21 +9937,28 @@ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNu
9630
9937
  }
9631
9938
  const limit = Math.max(0, Math.floor(maxTurns));
9632
9939
  const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
9940
+ let omitted = 0;
9633
9941
  const lines = [];
9634
- for (let i = firstTurnIndex; i < promptHistory.length; i++) {
9942
+ for (let i = 0; i < promptHistory.length; i++) {
9635
9943
  const turn = promptHistory[i];
9636
9944
  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
9945
  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
- }
9946
+ const types = (actions || []).map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
9947
+ if (!text && types.length === 0) continue;
9948
+ if (i < firstTurnIndex) {
9949
+ omitted += 1;
9950
+ continue;
9951
+ }
9952
+ if (!text) {
9953
+ lines.push(` \u7B2C${i + 1}\u8F6E\u52A8\u4F5C: ${types.join(", ")}`);
9954
+ continue;
9645
9955
  }
9646
- lines.push(line);
9956
+ let shown = text.slice(0, maxTextChars);
9957
+ if (shown.length < text.length) shown += "\uFF08\u672C\u6BB5\u56E0\u957F\u5EA6\u4E0A\u9650\u5DF2\u622A\u65AD\uFF09";
9958
+ const suffix = types.length > 0 ? ` \u2192 \u52A8\u4F5C: ${types.join(", ")}` : "";
9959
+ lines.push(` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${shown}${suffix}`);
9647
9960
  }
9961
+ if (omitted) lines.unshift(`\uFF08\u56E0\u5386\u53F2\u7A97\u53E3\u4E0A\u9650\u7701\u7565 ${omitted} \u8F6E\u66F4\u65E9\u5386\u53F2\u610F\u56FE\uFF09`);
9648
9962
  return lines.length > 0 ? lines.join("\n") : "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
9649
9963
  }
9650
9964
  function formatHints(previous) {
@@ -9657,11 +9971,15 @@ function formatHints(previous) {
9657
9971
  );
9658
9972
  }
9659
9973
  if (previous.logic) {
9660
- hints.push(
9661
- `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
9974
+ if (previous.logic.l3Hint) {
9975
+ hints.push(`\u2139\uFE0F ${previous.logic.l3Hint}`);
9976
+ } else {
9977
+ hints.push(
9978
+ `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
9662
9979
  \u7C7B\u578B: ${previous.logic.riskType}
9663
9980
  \u539F\u56E0: ${previous.logic.reason}`
9664
- );
9981
+ );
9982
+ }
9665
9983
  }
9666
9984
  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
9985
  }
@@ -9873,7 +10191,7 @@ async function analyzeWithLLM(prompt, config) {
9873
10191
  clearTimeout(totalTimeoutTimer);
9874
10192
  throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
9875
10193
  }
9876
- var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
10194
+ var LLMPromptBudgetExceeded, HISTORY_AUTHORIZATION, LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
9877
10195
  var init_llm_analyzer = __esm({
9878
10196
  "src/engine/llm-analyzer.ts"() {
9879
10197
  "use strict";
@@ -9887,6 +10205,15 @@ var init_llm_analyzer = __esm({
9887
10205
  init_trace_log();
9888
10206
  init_metrics();
9889
10207
  init_circuit_breaker();
10208
+ LLMPromptBudgetExceeded = class extends Error {
10209
+ code;
10210
+ constructor(code) {
10211
+ super(code);
10212
+ this.name = "LLMPromptBudgetExceeded";
10213
+ this.code = code;
10214
+ }
10215
+ };
10216
+ 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
10217
  LLMCircuitOpenError = class extends Error {
9891
10218
  constructor(message) {
9892
10219
  super(message);
@@ -11329,11 +11656,35 @@ function checkMCRules(graph) {
11329
11656
  for (const rule of rules) {
11330
11657
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
11331
11658
  if (ruleViolates(rule, trace2, witnessMode)) {
11659
+ const pathNodes = nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3);
11660
+ const path9 = pathNodes.map((n) => ({
11661
+ sessionId: n.sessionId,
11662
+ seq: n.seq,
11663
+ detail: n.actionDetail.slice(0, 60)
11664
+ }));
11332
11665
  violations.push({
11333
11666
  propertyId: String(rule.id || "mc-ltl"),
11334
11667
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
11335
11668
  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) }))
11669
+ path: path9,
11670
+ graph: {
11671
+ property_id: String(rule.id || "mc-ltl"),
11672
+ property_short: "P6",
11673
+ property_name: "LTL \u6A21\u578B\u68C0\u6D4B",
11674
+ nodes: pathNodes.map((n) => ({
11675
+ session_id: n.sessionId,
11676
+ seq: n.seq,
11677
+ stage: n.stage,
11678
+ action_detail: n.actionDetail,
11679
+ resources: [...n.resources].sort(),
11680
+ instance_id: n.instanceId || ""
11681
+ })),
11682
+ edges: pathNodes.slice(1).map((_, i) => ({
11683
+ from: i,
11684
+ to: i + 1,
11685
+ type: "next"
11686
+ }))
11687
+ }
11337
11688
  });
11338
11689
  if (witnessMode) return violations;
11339
11690
  }
@@ -12033,11 +12384,17 @@ function checkLowIntegrityCommandExec(graph) {
12033
12384
  for (const i of candidates) {
12034
12385
  const n = nodes[i];
12035
12386
  if (lowAt.has(i) && isComputeNode(n)) {
12387
+ const path9 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
12036
12388
  violations.push({
12037
12389
  propertyId: "low-integrity-command-exec",
12038
12390
  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
12391
  riskLevel: "critical",
12040
- path: [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }]
12392
+ path: path9,
12393
+ graph: graphFromPath(nodes, path9, "next", {
12394
+ property_id: "low-integrity-command-exec",
12395
+ property_short: "P7",
12396
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u547D\u4EE4\u6267\u884C"
12397
+ }, ["sink"])
12041
12398
  });
12042
12399
  if (witness !== void 0) return violations;
12043
12400
  }
@@ -12079,11 +12436,21 @@ function checkCrossSessionReachability(graph) {
12079
12436
  if (reached.has(i)) {
12080
12437
  const srcIdx = Math.min(...sources);
12081
12438
  const srcDesc = nodes[srcIdx].actionDetail.slice(0, 40);
12439
+ const path9 = nodes.slice(-3).map((m) => ({
12440
+ sessionId: m.sessionId,
12441
+ seq: m.seq,
12442
+ detail: m.actionDetail.slice(0, 60)
12443
+ }));
12082
12444
  violations.push({
12083
12445
  propertyId: "low-integrity-reachability",
12084
12446
  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
12447
  riskLevel: "high",
12086
- path: nodes.slice(-3).map((m) => ({ sessionId: m.sessionId, seq: m.seq, detail: m.actionDetail.slice(0, 60) }))
12448
+ path: path9,
12449
+ graph: graphFromPath(nodes, path9, "data", {
12450
+ property_id: "low-integrity-reachability",
12451
+ property_short: "P3",
12452
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u6D41\u53EF\u8FBE"
12453
+ })
12087
12454
  });
12088
12455
  if (witness !== void 0) return violations;
12089
12456
  }
@@ -12423,7 +12790,24 @@ function fingerprint(sessionId, actionType, actionDetail, calledAt) {
12423
12790
  ].join("\0");
12424
12791
  return createHash4("blake2b512").update(raw).digest("hex").slice(0, 16);
12425
12792
  }
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;
12793
+ function gateOrder(action) {
12794
+ const callId = String(action?.gateCallId ?? "");
12795
+ const callTimeUs = Number(action?.gateCallTimeUs ?? 0);
12796
+ return callId && Number.isFinite(callTimeUs) && callTimeUs > 0 ? { callId, callTimeUs } : null;
12797
+ }
12798
+ function gateFingerprint(action, isError, agentId, instanceId, order) {
12799
+ const values = [
12800
+ String(action?.actionType ?? ""),
12801
+ String(action?.actionDetail ?? ""),
12802
+ String(action?.calledAt ?? ""),
12803
+ String(action?.agentId ?? agentId ?? ""),
12804
+ String(action?.instanceId ?? instanceId ?? ""),
12805
+ Boolean(isError),
12806
+ order.callTimeUs
12807
+ ];
12808
+ return createHash4("sha256").update(JSON.stringify(values)).digest("hex");
12809
+ }
12810
+ 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
12811
  var init_stateful = __esm({
12428
12812
  "src/engine/formal-engine/stateful.ts"() {
12429
12813
  "use strict";
@@ -12439,6 +12823,12 @@ var init_stateful = __esm({
12439
12823
  SOCK_RE = /([\w./-]*(?:\/tmp\/|\/var\/run\/|\.sock\b)[\w./-]*)/;
12440
12824
  UNIT_RE = /systemctl\s+(?:start|enable|restart)\s+([\w.-]+)/i;
12441
12825
  PORT_STAGE_RE = /LISTEN|PERSIST|SCAN/;
12826
+ StatefulAnalysisUnavailable = class extends Error {
12827
+ };
12828
+ UnconfirmedGateRetry = class extends StatefulAnalysisUnavailable {
12829
+ };
12830
+ GateCallConflict = class extends UnconfirmedGateRetry {
12831
+ };
12442
12832
  STAGES_PATTERNS = null;
12443
12833
  CHAINS = null;
12444
12834
  COMMON_DIR_RESOURCES2 = /* @__PURE__ */ new Set([
@@ -12482,6 +12872,8 @@ var init_stateful = __esm({
12482
12872
  aliveResources = {};
12483
12873
  seqNext = 0;
12484
12874
  seededKeys = /* @__PURE__ */ new Set();
12875
+ /** (sessionId, gateCallId) → 节点,用于 Gate 精确一次关联。 */
12876
+ gateNodes = /* @__PURE__ */ new Map();
12485
12877
  constructor(agentId = "") {
12486
12878
  this.agentId = agentId;
12487
12879
  loadRules();
@@ -12540,28 +12932,73 @@ var init_stateful = __esm({
12540
12932
  }
12541
12933
  return added;
12542
12934
  }
12935
+ resultOf(node, matched, exfil) {
12936
+ return {
12937
+ seq: this.seqNext,
12938
+ node,
12939
+ matched,
12940
+ pendingPrefixes: this.pendingPrefixes,
12941
+ exfil,
12942
+ get shouldBlock() {
12943
+ return this.matched !== null || this.exfil.length > 0;
12944
+ }
12945
+ };
12946
+ }
12543
12947
  /** 增量推进:把当前动作追加到时间线 → 链指针推进 → 判定。 */
12544
12948
  advance(args) {
12545
12949
  const { aNext, sessionId = "current", isError = false, agentId = "", instanceId = "" } = args;
12546
- const node = this.appendNode(aNext, sessionId, isError, agentId, instanceId);
12950
+ const order = gateOrder(aNext);
12951
+ const gateFingerprintValue = order ? gateFingerprint(aNext, isError, agentId, instanceId, order) : "";
12952
+ if (order) {
12953
+ const existing = this.gateNodes.get(this.gateKey(sessionId, order.callId));
12954
+ if (existing) {
12955
+ if (existing.confirmed) {
12956
+ if (existing.inputFingerprint === gateFingerprintValue && existing.gateCallTimeUs === order.callTimeUs) {
12957
+ return this.resultOf(existing, existing.confirmed.matched, existing.confirmed.exfil);
12958
+ }
12959
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u5185\u5BB9\u6216\u65F6\u95F4\u4E0D\u4E00\u81F4");
12960
+ }
12961
+ if (aNext.gateDeliveryUncertain === true) {
12962
+ throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
12963
+ }
12964
+ if (existing.gateCallTimeUs !== order.callTimeUs) {
12965
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u65F6\u95F4\u4E0D\u4E00\u81F4");
12966
+ }
12967
+ if (existing.inputFingerprint) {
12968
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u91CD\u590D\u8C03\u7528\u7F3A\u5C11\u9001\u8FBE\u4E0D\u786E\u5B9A\u6807\u8BB0");
12969
+ }
12970
+ return this.resultOf(existing, null, []);
12971
+ }
12972
+ if (aNext.gateDeliveryUncertain === true) {
12973
+ throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
12974
+ }
12975
+ }
12976
+ const node = this.appendNode(
12977
+ order ? {
12978
+ ...aNext,
12979
+ gateCallId: order.callId,
12980
+ gateCallTimeUs: order.callTimeUs,
12981
+ gateInputFingerprint: gateFingerprintValue
12982
+ } : aNext,
12983
+ sessionId,
12984
+ isError,
12985
+ agentId,
12986
+ instanceId
12987
+ );
12547
12988
  if (!node) {
12548
- return { seq: this.seqNext, node: null, matched: null, pendingPrefixes: this.pendingPrefixes, exfil: [], shouldBlock: false };
12989
+ return this.resultOf(null, null, []);
12549
12990
  }
12550
12991
  const seq = this.seqNext;
12551
12992
  this.recordLifecycle(node);
12552
12993
  const matched = this.advanceChains(node);
12553
12994
  this.advanceTaint(node);
12554
12995
  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
- };
12996
+ if (order) {
12997
+ node.confirmed = { matched, exfil };
12998
+ this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
12999
+ }
13000
+ void seq;
13001
+ return this.resultOf(node, matched, exfil);
12565
13002
  }
12566
13003
  /**
12567
13004
  * 自动轮转:归档旧节点,只保留最近 `retain` 条,并重建链指针/taint。
@@ -12598,6 +13035,7 @@ var init_stateful = __esm({
12598
13035
  this.taintOrigin.clear();
12599
13036
  this.aliveResources = {};
12600
13037
  this.seqNext = 0;
13038
+ this.gateNodes.clear();
12601
13039
  for (const n of kept) {
12602
13040
  const node = this.appendNode(
12603
13041
  {
@@ -12605,7 +13043,12 @@ var init_stateful = __esm({
12605
13043
  actionDetail: n.actionDetail,
12606
13044
  agentId: n.agentId,
12607
13045
  instanceId: n.instanceId,
12608
- ...n.timestamp ? { calledAt: n.timestamp } : {}
13046
+ ...n.timestamp ? { calledAt: n.timestamp } : {},
13047
+ ...n.gateCallId ? {
13048
+ gateCallId: n.gateCallId,
13049
+ gateCallTimeUs: n.gateCallTimeUs,
13050
+ gateInputFingerprint: n.inputFingerprint
13051
+ } : {}
12609
13052
  },
12610
13053
  n.sessionId,
12611
13054
  n.isError,
@@ -12613,6 +13056,7 @@ var init_stateful = __esm({
12613
13056
  n.instanceId
12614
13057
  );
12615
13058
  if (node) {
13059
+ if (n.confirmed) node.confirmed = n.confirmed;
12616
13060
  this.recordLifecycle(node);
12617
13061
  this.advanceTaint(node);
12618
13062
  this.advanceChains(node);
@@ -12620,6 +13064,9 @@ var init_stateful = __esm({
12620
13064
  }
12621
13065
  return { archived: old.length, file };
12622
13066
  }
13067
+ gateKey(sessionId, callId) {
13068
+ return `${sessionId}\0${callId}`;
13069
+ }
12623
13070
  appendNode(action, sessionId, isError = false, agentId = "", instanceId = "") {
12624
13071
  const ad = String(action.actionDetail || "");
12625
13072
  const at = String(action.actionType || "");
@@ -12651,6 +13098,13 @@ var init_stateful = __esm({
12651
13098
  lifecycle: lifecycleFor(ad, stage, isError),
12652
13099
  timestamp: suppliedCalledAt || _StatefulChainTracker.now()
12653
13100
  };
13101
+ const order = gateOrder(action);
13102
+ if (order) {
13103
+ node.gateCallId = order.callId;
13104
+ node.gateCallTimeUs = order.callTimeUs;
13105
+ node.inputFingerprint = String(action.gateInputFingerprint || "");
13106
+ this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
13107
+ }
12654
13108
  this.nodes_.push(node);
12655
13109
  this.seqNext += 1;
12656
13110
  if (dedupeKey) this.seededKeys.add(dedupeKey);
@@ -13002,11 +13456,19 @@ var init_stateful = __esm({
13002
13456
  // 旧快照无此字段 → 空
13003
13457
  isError: Boolean(raw.isError),
13004
13458
  lifecycle: String(raw.lifecycle || ""),
13005
- timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null
13459
+ timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null,
13006
13460
  // 旧快照无此字段 → null
13461
+ ...raw.gateCallId ? { gateCallId: String(raw.gateCallId) } : {},
13462
+ ...raw.gateCallTimeUs ? { gateCallTimeUs: Number(raw.gateCallTimeUs) } : {},
13463
+ ...raw.inputFingerprint ? { inputFingerprint: String(raw.inputFingerprint) } : {},
13464
+ ...raw.confirmed ? { confirmed: raw.confirmed } : {}
13007
13465
  });
13008
13466
  }
13009
13467
  this.seqNext = Number(snapshot.seq_next || this.nodes_.length);
13468
+ this.gateNodes = /* @__PURE__ */ new Map();
13469
+ for (const n of this.nodes_) {
13470
+ if (n.gateCallId) this.gateNodes.set(this.gateKey(n.sessionId, n.gateCallId), n);
13471
+ }
13010
13472
  for (const n of this.nodes_) {
13011
13473
  if (n.timestamp) {
13012
13474
  this.seededKeys.add(fingerprint(n.sessionId, n.actionType, n.actionDetail, n.timestamp));
@@ -13467,9 +13929,19 @@ async function runAnalysis(input) {
13467
13929
  isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
13468
13930
  isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
13469
13931
  );
13932
+ const degradedNotes = [];
13470
13933
  let scriptChain = null;
13471
- if (input.aNext.actionType.toLowerCase() === "bash") {
13934
+ if (input.aNext.actionType.toLowerCase() === "bash" && getDeployRole() === "host") {
13935
+ degradedNotes.push("script_content_deferred_to_sandbox: AGENT_MOSS_DEPLOY_ROLE=host");
13936
+ } else if (input.aNext.actionType.toLowerCase() === "bash") {
13472
13937
  scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
13938
+ if (scriptChain.nodes.length > 0) {
13939
+ for (const node of scriptChain.nodes) {
13940
+ if (node.error && !node.unanalyzable) {
13941
+ degradedNotes.push(`script_content_unavailable: ${node.scriptPath} (${node.error})`);
13942
+ }
13943
+ }
13944
+ }
13473
13945
  if (heuristicEnabled && scriptChain.nodes.length > 0) {
13474
13946
  for (const node of scriptChain.nodes) {
13475
13947
  if (node.unanalyzable) {
@@ -13740,7 +14212,8 @@ async function runAnalysis(input) {
13740
14212
  riskType: "",
13741
14213
  confidence: 85,
13742
14214
  source: "heuristic_and_logic_only",
13743
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
14215
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
14216
+ degraded: degradedNotes
13744
14217
  };
13745
14218
  }
13746
14219
  let skipL3Hints = "\u65E0\uFF08\u5F53\u524D\u65E0\u7981\u7528\u89C4\u5219\u547D\u4E2D\uFF09";
@@ -13777,8 +14250,22 @@ async function runAnalysis(input) {
13777
14250
  pathContext
13778
14251
  });
13779
14252
  } catch (e) {
13780
- const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
13781
14253
  const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
14254
+ if (e instanceof LLMPromptBudgetExceeded) {
14255
+ const failMode = getLLMFailMode2();
14256
+ const allowed = failMode === "fail_open";
14257
+ return {
14258
+ allowed,
14259
+ reason: `L3 prompt \u8D85\u51FA\u786C\u9884\u7B97\uFF0C\u5DF2\u8DF3\u8FC7\u8BED\u4E49\u5206\u6790\uFF0C\u6309 ${failMode} ${allowed ? "\u653E\u884C" : "\u62D2\u7EDD"}`,
14260
+ riskLevel: allowed ? "low" : "medium",
14261
+ riskType: "",
14262
+ confidence: allowed ? 50 : 60,
14263
+ source: "llm_budget_skipped",
14264
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
14265
+ degraded: [...degradedNotes, e.code]
14266
+ };
14267
+ }
14268
+ const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
13782
14269
  if (getLLMFailMode2() === "fail_open") {
13783
14270
  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
14271
  return {
@@ -13788,7 +14275,8 @@ async function runAnalysis(input) {
13788
14275
  riskType: "",
13789
14276
  confidence: 50,
13790
14277
  source: failSource,
13791
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
14278
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
14279
+ degraded: degradedNotes
13792
14280
  };
13793
14281
  }
13794
14282
  return {
@@ -13798,7 +14286,10 @@ async function runAnalysis(input) {
13798
14286
  riskType: "",
13799
14287
  confidence: 60,
13800
14288
  source: failSource,
13801
- violatedLayers: ["L3.1"]
14289
+ violatedLayers: ["L3.1"],
14290
+ degraded: degradedNotes,
14291
+ ask_recommended: true,
14292
+ 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
14293
  };
13803
14294
  }
13804
14295
  if (!llmResult.allowed && llmResult.confidence && llmResult.confidence >= 90 && _brainExtractor) {
@@ -13818,6 +14309,9 @@ async function runAnalysis(input) {
13818
14309
  if (observedFormalLayers.length > 0 && llmResult.allowed) {
13819
14310
  llmResult.violatedLayers = Array.from(/* @__PURE__ */ new Set([...observedFormalLayers, ...llmResult.violatedLayers || []]));
13820
14311
  }
14312
+ if (degradedNotes.length > 0) {
14313
+ llmResult.degraded = Array.from(/* @__PURE__ */ new Set([...llmResult.degraded || [], ...degradedNotes]));
14314
+ }
13821
14315
  return llmResult;
13822
14316
  }
13823
14317
  var TRUSTED_SKILLS_BASE, _brainStore, _brainExtractor, _brainSkillManager, _brainCurator, _brainInitialized, _brainLastMaintenance, BRAIN_MAINT_INTERVAL_MS, formalEngine;
@@ -13864,7 +14358,7 @@ function deriveL3Outcome(j) {
13864
14358
  if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
13865
14359
  if (src === "llm_circuit_open") return "circuit_open";
13866
14360
  if (src === "llm_failure_with_violation") return "failed_but_blocked";
13867
- if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
14361
+ if (src === "heuristic_and_logic_only" || src === "disabled" || src === "llm_budget_skipped") return "skipped";
13868
14362
  return "not_reached";
13869
14363
  }
13870
14364
  var init_types = __esm({
@@ -14584,6 +15078,16 @@ function normalizeAction(row) {
14584
15078
  actionDetail: String(row.action_detail || row.command || row.input || "")
14585
15079
  };
14586
15080
  if (row.called_at) act.calledAt = String(row.called_at);
15081
+ try {
15082
+ const audit = JSON.parse(String(row.moss_response || "{}"));
15083
+ if (audit && audit._gate_protocol_rejected === true) {
15084
+ act.gateProtocolRejected = true;
15085
+ } 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) {
15086
+ act.gateCallId = audit._gate_call_id;
15087
+ act.gateCallTimeUs = audit._gate_call_time_us;
15088
+ }
15089
+ } catch {
15090
+ }
14587
15091
  return act;
14588
15092
  }
14589
15093
  function readJsonDir(dirPath, limit = 1e5, strict = false) {
@@ -14624,10 +15128,18 @@ function readSqlite(dbPath, limit = 1e5, strict = false) {
14624
15128
  let db;
14625
15129
  try {
14626
15130
  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);
15131
+ let rows;
15132
+ try {
15133
+ rows = db.prepare(
15134
+ `SELECT session_id, action_type, tool_name, action_detail, command, called_at, moss_response
15135
+ FROM tool_calls ORDER BY called_at, id LIMIT ?`
15136
+ ).all(limit);
15137
+ } catch {
15138
+ rows = db.prepare(
15139
+ `SELECT session_id, action_type, tool_name, action_detail, command, called_at
15140
+ FROM tool_calls ORDER BY called_at, id LIMIT ?`
15141
+ ).all(limit);
15142
+ }
14631
15143
  const sessions = /* @__PURE__ */ new Map();
14632
15144
  for (const r of rows) {
14633
15145
  const sid = String(r.session_id || "");
@@ -14862,6 +15374,10 @@ async function analyzeRoute(c) {
14862
15374
  try {
14863
15375
  const body = await c.req.json();
14864
15376
  const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
15377
+ const gateCallId = String(c.get("gateCallId") || "");
15378
+ if (gateCallId && (req.gate_call_id !== gateCallId || !validGateCallTime(req.gate_call_time_us) || typeof req.gate_delivery_uncertain !== "boolean")) {
15379
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5143\u6570\u636E\u65E0\u6548" }, 422);
15380
+ }
14865
15381
  const unmappedTool = String(
14866
15382
  req.metadata?.unmapped_tool || ""
14867
15383
  );
@@ -14974,7 +15490,16 @@ async function analyzeRoute(c) {
14974
15490
  const store = getChainStateStoreFor(agentId);
14975
15491
  const inc = store.applyAction(
14976
15492
  chainBucket(agentId),
14977
- { actionType: req.a_next.action_type, actionDetail: req.a_next.action_detail },
15493
+ {
15494
+ actionType: req.a_next.action_type,
15495
+ actionDetail: req.a_next.action_detail,
15496
+ ...req.a_next.called_at ? { calledAt: req.a_next.called_at } : {},
15497
+ ...gateCallId ? {
15498
+ gateCallId,
15499
+ gateCallTimeUs: req.gate_call_time_us,
15500
+ gateDeliveryUncertain: req.gate_delivery_uncertain === true
15501
+ } : {}
15502
+ },
14978
15503
  req.session_id,
14979
15504
  Boolean(meta.is_error),
14980
15505
  agentId,
@@ -14997,7 +15522,31 @@ async function analyzeRoute(c) {
14997
15522
  }
14998
15523
  finding = incMatchedToDeny(inc);
14999
15524
  } catch (err) {
15000
- console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
15525
+ if (err instanceof UnconfirmedGateRetry) {
15526
+ const reason = "AgentMoss \u65E0\u6CD5\u786E\u8BA4\u672C\u6B21 Gate \u8C03\u7528\u662F\u5426\u5DF2\u5165\u94FE";
15527
+ degradedNotes.push(`\u3010\u5DF2\u964D\u7EA7\u3011${reason}\uFF1B\u672C\u6B21\u6309\u62D2\u7EDD\u5904\u7406\uFF0C\u907F\u514D\u91CD\u590D\u5165\u94FE\u3002`);
15528
+ if (result.decision !== "Deny") {
15529
+ result = {
15530
+ ...result,
15531
+ decision: "Deny",
15532
+ reason,
15533
+ risk_type: "service_unavailable",
15534
+ risk_level: "high",
15535
+ policy: "",
15536
+ ask_recommended: true,
15537
+ 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"
15538
+ };
15539
+ }
15540
+ } else if (err instanceof StatefulAnalysisUnavailable) {
15541
+ degradedNotes.push(
15542
+ "\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"
15543
+ );
15544
+ } else {
15545
+ console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
15546
+ degradedNotes.push(
15547
+ "\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"
15548
+ );
15549
+ }
15001
15550
  }
15002
15551
  }
15003
15552
  result = publicFormalResult(
@@ -15008,6 +15557,11 @@ async function analyzeRoute(c) {
15008
15557
  req.session_history || []
15009
15558
  );
15010
15559
  const durationMs = performance.now() - t0;
15560
+ if (Array.isArray(result.degraded)) {
15561
+ for (const note of result.degraded) {
15562
+ if (note && !degradedNotes.includes(note)) degradedNotes.push(note);
15563
+ }
15564
+ }
15011
15565
  const _l3FailMsg = String(result.reason || "").slice(0, 160);
15012
15566
  if (result.l3_outcome === "reasoning_fallback") {
15013
15567
  degradedNotes.push(
@@ -15097,7 +15651,10 @@ async function analyzeRoute(c) {
15097
15651
  degraded: degradedNotes,
15098
15652
  // L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
15099
15653
  // 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
15100
- l3_outcome: result.l3_outcome || ""
15654
+ l3_outcome: result.l3_outcome || "",
15655
+ ask_recommended: result.ask_recommended === true,
15656
+ ask_reason: String(result.ask_reason || ""),
15657
+ ...gateCallId ? { gate_call_id: gateCallId } : {}
15101
15658
  })
15102
15659
  );
15103
15660
  } catch (err) {
@@ -15253,7 +15810,11 @@ async function reviewRoute(c) {
15253
15810
  if (!tracker) {
15254
15811
  tracker = new StatefulChainTracker(bucket);
15255
15812
  }
15256
- const added = sessions.length > 0 ? tracker.seed(sessions) : 0;
15813
+ const seedSessions = sessions.map((s) => ({
15814
+ ...s,
15815
+ actionHistory: (s.actionHistory || []).filter((a) => !a.gateProtocolRejected)
15816
+ }));
15817
+ const added = seedSessions.length > 0 ? tracker.seed(seedSessions) : 0;
15257
15818
  store.save(tracker);
15258
15819
  let verified = true;
15259
15820
  const violations = [];
@@ -15418,6 +15979,7 @@ var init_routes = __esm({
15418
15979
  init_analyzer();
15419
15980
  init_actrail();
15420
15981
  init_formal_engine();
15982
+ init_stateful();
15421
15983
  init_circuit_breaker();
15422
15984
  init_pattern_miner();
15423
15985
  init_agent_gate_reader();
@@ -15967,9 +16529,29 @@ function createApp() {
15967
16529
  if (!okAuth && !isPublicPage) {
15968
16530
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
15969
16531
  }
16532
+ let gateCallId = null;
16533
+ const gateRequired = c.req.header(GATE_IDENTITY_HEADER);
16534
+ const gatePath = path9.replace(/\/+$/, "");
16535
+ if (method === "POST" && gateRequired !== void 0 && (gatePath === "/api/v1/analyze" || gatePath === "/api/v1/review")) {
16536
+ if (principal !== GATE_PRINCIPAL) {
16537
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8EAB\u4EFD\u6821\u9A8C\u5931\u8D25" }, 403);
16538
+ }
16539
+ if (gateRequired !== "1") {
16540
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
16541
+ }
16542
+ }
16543
+ if (method === "POST" && gatePath === "/api/v1/analyze" && principal === GATE_PRINCIPAL) {
16544
+ const id = c.req.header(GATE_CALL_ID_HEADER) || "";
16545
+ if (gateRequired !== "1" || !validGateCallId(id)) {
16546
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
16547
+ }
16548
+ gateCallId = id;
16549
+ c.set("gateCallId", id);
16550
+ }
15970
16551
  if (limiter.enabled && path9.startsWith("/api/")) {
15971
16552
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
15972
16553
  if (!limiter.allow(key)) {
16554
+ if (gateCallId) c.header(GATE_RATE_LIMIT_HEADER, gateCallId);
15973
16555
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
15974
16556
  }
15975
16557
  }
@@ -15985,6 +16567,7 @@ function createApp() {
15985
16567
  const busy = (detail, status = 503) => {
15986
16568
  c.header("Retry-After", "1");
15987
16569
  c.header("Connection", "close");
16570
+ if (gateCallId) c.header(GATE_BUSY_HEADER, gateCallId);
15988
16571
  return c.json({ detail }, status);
15989
16572
  };
15990
16573
  try {
@@ -16737,7 +17320,7 @@ async function main() {
16737
17320
  const expectInstance = process.env.AGENT_MOSS_INSTANCE || "";
16738
17321
  let foundPort = 0;
16739
17322
  let version2 = "";
16740
- const otherInstances = [];
17323
+ const seen = [];
16741
17324
  for (let port = 9090; port <= 9095; port++) {
16742
17325
  try {
16743
17326
  const data = await new Promise((resolve12, reject) => {
@@ -16752,22 +17335,30 @@ async function main() {
16752
17335
  }
16753
17336
  });
16754
17337
  });
17338
+ req.on("timeout", () => req.destroy(new Error("probe timeout")));
16755
17339
  req.on("error", reject);
16756
17340
  });
16757
- if (data.status === "healthy") {
17341
+ if (data.status === "healthy" || data.status === "degraded") {
16758
17342
  const inst = data.instance || "";
16759
- if (inst === expectInstance) {
17343
+ const ver = data.version || "";
17344
+ seen.push({ port, instance: inst, version: ver });
17345
+ if (!foundPort && inst === expectInstance) {
16760
17346
  foundPort = port;
16761
- version2 = data.version || "";
16762
- break;
17347
+ version2 = ver;
16763
17348
  }
16764
- otherInstances.push({ port, instance: inst });
16765
17349
  }
16766
17350
  } catch {
16767
17351
  }
16768
17352
  }
17353
+ const otherInstances = seen.filter((s) => s.port !== foundPort);
16769
17354
  if (foundPort) {
16770
17355
  console.log(`\u2705 AgentMoss \u670D\u52A1\u8FD0\u884C\u4E2D`);
17356
+ console.log(` Instance: ${expectInstance || "(\u672A\u6307\u5B9A)"}`);
17357
+ if (!expectInstance && seen.length > 1) {
17358
+ console.log(
17359
+ " \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"
17360
+ );
17361
+ }
16771
17362
  console.log(` \u7248\u672C: ${version2 || "?"}`);
16772
17363
  console.log(` \u7AEF\u53E3: ${foundPort}`);
16773
17364
  console.log(` Console: http://127.0.0.1:${foundPort}/console`);
@@ -16790,6 +17381,7 @@ async function main() {
16790
17381
  }
16791
17382
  });
16792
17383
  });
17384
+ req.on("timeout", () => req.destroy(new Error("probe timeout")));
16793
17385
  req.on("error", reject);
16794
17386
  });
16795
17387
  const layers = data.layers || {};
@@ -16801,6 +17393,15 @@ async function main() {
16801
17393
  console.log(` L3 LLM \u5206\u6790: ${l3}`);
16802
17394
  } catch {
16803
17395
  }
17396
+ if (otherInstances.length > 0) {
17397
+ console.log();
17398
+ console.log(` \u26A0\uFE0F \u540C\u673A\u53E6\u6709 ${otherInstances.length} \u4E2A\u5B9E\u4F8B\uFF08\u672A\u8BA1\u5165\u4E0A\u9762\u7684\u72B6\u6001\uFF09\uFF1A`);
17399
+ for (const o of otherInstances) {
17400
+ 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" : "";
17401
+ console.log(` \u7AEF\u53E3 ${o.port} instance=${o.instance || "(\u7A7A)"} v${o.version || "?"}${tag}`);
17402
+ }
17403
+ console.log(" \u67E5\u770B\u6307\u5B9A\u5B9E\u4F8B\uFF1AAGENT_MOSS_INSTANCE=<\u540D\u5B57> agent-moss status");
17404
+ }
16804
17405
  console.log();
16805
17406
  console.log(" \u542F\u505C\u547D\u4EE4\uFF1A");
16806
17407
  console.log(" systemctl start agent-moss \u542F\u52A8");
@@ -16809,15 +17410,15 @@ async function main() {
16809
17410
  console.log(" systemctl status agent-moss \u72B6\u6001");
16810
17411
  console.log(" journalctl -u agent_moss -f \u65E5\u5FD7");
16811
17412
  } else if (otherInstances.length > 0) {
16812
- console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C\uFF08instance=${expectInstance || "(\u7A7A)"}\uFF09`);
17413
+ console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C\uFF08instance=${expectInstance || "(\u672A\u6307\u5B9A)"}\uFF09`);
16813
17414
  console.log(` Systemd: ${systemdInfo ? "active" : "inactive"}`);
16814
- const detail = otherInstances.map((o) => `\u7AEF\u53E3 ${o.port} (instance=${o.instance || "(\u7A7A)"})`).join("; ");
17415
+ const detail = otherInstances.map((o) => `\u7AEF\u53E3 ${o.port} (instance=${o.instance || "(\u7A7A)"}, v${o.version || "?"})`).join("; ");
16815
17416
  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`);
17417
+ 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
17418
  console.log(` \u542F\u52A8\u672C\u5B9E\u4F8B: AGENT_MOSS_INSTANCE=${expectInstance || "xiaoo"} agent-moss server`);
16818
17419
  process.exit(1);
16819
17420
  } else {
16820
- console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C`);
17421
+ console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C\uFF08instance=${expectInstance || "(\u672A\u6307\u5B9A)"}\uFF09`);
16821
17422
  if (systemdInfo) {
16822
17423
  console.log(` Systemd: active \u4F46\u7AEF\u53E3\u63A2\u6D4B\u4E0D\u5230`);
16823
17424
  console.log(` \u68C0\u67E5\u65E5\u5FD7\uFF1Ajournalctl -u agent_moss -n 20 --no-pager`);