@kenhkl/agent-moss 0.17.39 → 0.17.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1110,38 +1110,68 @@ function hardenExistingPaths() {
1110
1110
  function chainDetailMode() {
1111
1111
  return (env("AGENT_MOSS_CHAIN_DETAIL", "redacted") || "redacted").toLowerCase();
1112
1112
  }
1113
- function redactChain(chain, currentInstanceId = "", currentSessionId = "") {
1113
+ function chainNodeVisible(instanceId, sessionId, currentInstanceId, currentSessionId, sessionAlias) {
1114
+ const inst = String(instanceId ?? "") || "";
1115
+ if (inst) {
1116
+ return !!(currentInstanceId && inst === String(currentInstanceId));
1117
+ }
1118
+ const sid = String(sessionId ?? "") || "";
1119
+ return !!sid && (sid === currentSessionId || sid === sessionAlias);
1120
+ }
1121
+ function redactChain(chain, currentInstanceId = "", currentSessionId = "", opts = {}) {
1114
1122
  if (!chain || chain.length === 0) return [];
1115
1123
  if (chainDetailMode() === "full") return [...chain];
1116
- return chain.map((step) => {
1124
+ const nodes = opts.graph?.nodes || [];
1125
+ return chain.map((step, index) => {
1117
1126
  if (Array.isArray(step) && step.length >= 3) {
1118
- const [sid, seq, , ts] = step;
1119
- const inst = step.length > 5 ? String(step[5] ?? "") : "";
1120
- const sameInstance = !!(inst && currentInstanceId && inst === String(currentInstanceId));
1121
- const sameSessionFallback = !inst && !!currentSessionId && String(sid) === String(currentSessionId);
1122
- if (sameInstance || sameSessionFallback) return [...step];
1123
- return ["<other-session>", seq, "<\u5DF2\u9690\u85CF>", ts ?? ""];
1127
+ const sid = step[0];
1128
+ const seq = step[1];
1129
+ const ts = step.length > 3 ? step[3] : "";
1130
+ let inst = step.length > 5 ? step[5] : "";
1131
+ if (!inst && index < nodes.length) {
1132
+ const node = nodes[index];
1133
+ const detail = String(node.action_detail ?? "");
1134
+ const stepDetail = String(step[2] ?? "");
1135
+ if (String(sid) !== String(node.session_id ?? "") || String(seq) !== String(node.seq ?? "") || stepDetail !== detail && stepDetail !== detail.slice(0, 60)) {
1136
+ return ["<other-session>", seq, "<\u5DF2\u9690\u85CF>", ts];
1137
+ }
1138
+ inst = node.instance_id;
1139
+ }
1140
+ if (chainNodeVisible(inst, sid, currentInstanceId, currentSessionId, opts.sessionAlias || "")) {
1141
+ return [...step];
1142
+ }
1143
+ return ["<other-session>", seq, "<\u5DF2\u9690\u85CF>", ts];
1124
1144
  }
1125
1145
  return step;
1126
1146
  });
1127
1147
  }
1128
- function redactGraph(graph, currentInstanceId = "", currentSessionId = "") {
1148
+ function redactGraph(graph, currentInstanceId = "", currentSessionId = "", opts = {}) {
1129
1149
  if (!graph) return null;
1130
1150
  if (chainDetailMode() === "full") return graph;
1131
- const nodes = (graph.nodes || []).map((n) => {
1151
+ const hidden = /* @__PURE__ */ new Set();
1152
+ const nodes = (graph.nodes || []).map((n, index) => {
1132
1153
  const m = { ...n };
1133
- const inst = String(m.instance_id ?? "") || "";
1134
- const sid = String(m.session_id ?? "") || "";
1135
- const sameInstance = !!(inst && currentInstanceId && inst === String(currentInstanceId));
1136
- const sameSessionFallback = !inst && !!currentSessionId && sid === String(currentSessionId);
1137
- if (!(sameInstance || sameSessionFallback)) {
1154
+ if (!chainNodeVisible(
1155
+ m.instance_id,
1156
+ m.session_id,
1157
+ currentInstanceId,
1158
+ currentSessionId,
1159
+ opts.sessionAlias || ""
1160
+ )) {
1161
+ hidden.add(index);
1138
1162
  m.session_id = "<other-session>";
1139
1163
  m.action_detail = "<\u5DF2\u9690\u85CF>";
1140
1164
  m.resources = [];
1141
1165
  }
1142
1166
  return m;
1143
1167
  });
1144
- const out = { nodes, edges: graph.edges || [] };
1168
+ const edges = (graph.edges || []).map((edge) => {
1169
+ if ("label" in edge && (hidden.has(Number(edge.from)) || hidden.has(Number(edge.to)))) {
1170
+ return { ...edge, label: "" };
1171
+ }
1172
+ return edge;
1173
+ });
1174
+ const out = { nodes, edges };
1145
1175
  for (const key of ["property_id", "property_short", "property_name", "property_expression"]) {
1146
1176
  if (graph[key] !== void 0) out[key] = graph[key];
1147
1177
  }
@@ -1371,6 +1401,157 @@ function hasInlineDangerEvidence(command) {
1371
1401
  for (const re of DANGER_EVIDENCE_RES) if (re.test(code)) return true;
1372
1402
  return false;
1373
1403
  }
1404
+ function literalShellWord(raw) {
1405
+ if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) {
1406
+ const inner = raw.slice(1, -1);
1407
+ return inner.includes("'") ? null : inner;
1408
+ }
1409
+ if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) {
1410
+ const inner = raw.slice(1, -1);
1411
+ return /["\\$`]/.test(inner) ? null : inner;
1412
+ }
1413
+ if (!raw || /\s/.test(raw) || !/^[A-Za-z0-9_@%+=:,./-]+$/.test(raw)) return null;
1414
+ return raw;
1415
+ }
1416
+ function pythonStringLiteral(raw) {
1417
+ const text = raw.trim();
1418
+ if (text.length < 2) return null;
1419
+ const quote = text[0];
1420
+ if (quote !== "'" && quote !== '"' || text[text.length - 1] !== quote) return null;
1421
+ const inner = text.slice(1, -1);
1422
+ if (inner.includes(quote) || inner.includes("\\") || inner.includes("\n")) return null;
1423
+ return inner;
1424
+ }
1425
+ function splitPythonArgs(raw) {
1426
+ const parts = [];
1427
+ let current = "";
1428
+ let depth = 0;
1429
+ let quote = null;
1430
+ for (const ch of raw) {
1431
+ if (quote) {
1432
+ current += ch;
1433
+ if (ch === quote) quote = null;
1434
+ continue;
1435
+ }
1436
+ if (ch === "'" || ch === '"') {
1437
+ quote = ch;
1438
+ current += ch;
1439
+ continue;
1440
+ }
1441
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
1442
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1443
+ if (ch === "," && depth === 0) {
1444
+ parts.push(current.trim());
1445
+ current = "";
1446
+ continue;
1447
+ }
1448
+ current += ch;
1449
+ }
1450
+ if (quote || depth !== 0) return null;
1451
+ parts.push(current.trim());
1452
+ return parts;
1453
+ }
1454
+ function hasTopLevelChar(raw, target) {
1455
+ let depth = 0;
1456
+ let quote = null;
1457
+ for (const ch of raw) {
1458
+ if (quote) {
1459
+ if (ch === quote) quote = null;
1460
+ continue;
1461
+ }
1462
+ if (ch === "'" || ch === '"') quote = ch;
1463
+ else if (ch === "(" || ch === "[" || ch === "{") depth++;
1464
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1465
+ else if (ch === target && depth === 0) return true;
1466
+ }
1467
+ return false;
1468
+ }
1469
+ function splitPythonStatements(code) {
1470
+ const parts = [];
1471
+ let current = "";
1472
+ let depth = 0;
1473
+ let quote = null;
1474
+ for (const ch of code) {
1475
+ if (quote) {
1476
+ current += ch;
1477
+ if (ch === quote) quote = null;
1478
+ continue;
1479
+ }
1480
+ if (ch === "'" || ch === '"') {
1481
+ quote = ch;
1482
+ current += ch;
1483
+ continue;
1484
+ }
1485
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
1486
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1487
+ if ((ch === ";" || ch === "\n") && depth === 0) {
1488
+ parts.push(current);
1489
+ current = "";
1490
+ continue;
1491
+ }
1492
+ current += ch;
1493
+ }
1494
+ if (quote || depth !== 0) return null;
1495
+ parts.push(current);
1496
+ return parts.map((s) => s.trim()).filter((s) => s.length > 0);
1497
+ }
1498
+ function isSimpleOpenCall(expr, path9, binding) {
1499
+ const m = expr.match(/^open\s*\(([\s\S]*)\)$/);
1500
+ if (!m || hasTopLevelChar(m[1], "=")) return false;
1501
+ const args = splitPythonArgs(m[1]);
1502
+ if (!args || args.length !== 1 && args.length !== 2) return false;
1503
+ if (args.length === 2 && !["r", "rt", "rb"].includes(pythonStringLiteral(args[1]) ?? "")) {
1504
+ return false;
1505
+ }
1506
+ const target = args[0].trim();
1507
+ const literal = pythonStringLiteral(target);
1508
+ if (literal !== null) return literal === path9;
1509
+ return !!binding && target === binding;
1510
+ }
1511
+ function confirmsInlineRead(command, path9) {
1512
+ if (command.length > 8192 || !path9 || path9.startsWith("~")) return false;
1513
+ if (path9.includes("/") && !path9.startsWith("/")) return false;
1514
+ const wrapper = command.trim().match(/^python3?[ \t]+-c[ \t]+([\s\S]+)$/);
1515
+ if (!wrapper) return false;
1516
+ const code = literalShellWord(wrapper[1]);
1517
+ if (code === null) return false;
1518
+ const statements = splitPythonStatements(code);
1519
+ if (!statements || statements.length !== 1 && statements.length !== 2) return false;
1520
+ let expr;
1521
+ let binding = null;
1522
+ if (statements.length === 2) {
1523
+ const first = statements[0];
1524
+ if (first === "import os") {
1525
+ const sys = statements[1].match(/^os\.system\s*\(([\s\S]*)\)$/);
1526
+ if (!sys || hasTopLevelChar(sys[1], "=")) return false;
1527
+ const args = splitPythonArgs(sys[1]);
1528
+ if (!args || args.length !== 1) return false;
1529
+ const child = pythonStringLiteral(args[0]);
1530
+ if (child === null) return false;
1531
+ const cat = child.trim().match(/^cat[ \t]+([\s\S]+)$/);
1532
+ return !!cat && !path9.startsWith("-") && literalShellWord(cat[1].trim()) === path9;
1533
+ }
1534
+ const assign = first.match(/^([A-Za-z_]\w*)\s*=\s*([\s\S]+)$/);
1535
+ if (!assign) return false;
1536
+ const name = assign[1];
1537
+ const value = pythonStringLiteral(assign[2]);
1538
+ if (value !== path9 || ["open", "print", "__debug__"].includes(name)) return false;
1539
+ binding = name;
1540
+ expr = statements[1];
1541
+ } else {
1542
+ expr = statements[0];
1543
+ }
1544
+ const printCall = expr.match(/^print\s*\(([\s\S]*)\)$/);
1545
+ if (printCall) {
1546
+ if (hasTopLevelChar(printCall[1], "=")) return false;
1547
+ const args = splitPythonArgs(printCall[1]);
1548
+ if (!args || args.length !== 1) return false;
1549
+ expr = args[0];
1550
+ }
1551
+ const readCall = expr.match(/^([\s\S]+)\.read\s*\(\s*\)$/);
1552
+ if (readCall) expr = readCall[1];
1553
+ return isSimpleOpenCall(expr, path9, binding);
1554
+ }
1374
1555
  function analyzeInlineScript(command) {
1375
1556
  const code = extractInlineCode(command);
1376
1557
  if (!code) {
@@ -5010,6 +5191,7 @@ var init_written_content_analyzer = __esm({
5010
5191
  });
5011
5192
 
5012
5193
  // src/engine/heuristic.ts
5194
+ import { posix } from "path";
5013
5195
  function _effectiveDangerousPatterns(osType) {
5014
5196
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
5015
5197
  }
@@ -5037,6 +5219,112 @@ function normalizeShellObfuscation(text) {
5037
5219
  t = t.replace(/\$\{IFS\}|\$IFS/gi, " ");
5038
5220
  return t;
5039
5221
  }
5222
+ function shlexSplitLite(s) {
5223
+ const out = [];
5224
+ let cur = "";
5225
+ let quote = null;
5226
+ let quoted = false;
5227
+ for (let i = 0; i < s.length; i++) {
5228
+ const ch = s[i];
5229
+ if (quote) {
5230
+ if (ch === quote) quote = null;
5231
+ else if (ch === "\\" && quote === '"' && i + 1 < s.length) cur += s[++i];
5232
+ else cur += ch;
5233
+ continue;
5234
+ }
5235
+ if (ch === "'" || ch === '"') {
5236
+ quote = ch;
5237
+ quoted = true;
5238
+ continue;
5239
+ }
5240
+ if (/\s/.test(ch)) {
5241
+ if (cur || quoted) {
5242
+ out.push(cur);
5243
+ cur = "";
5244
+ quoted = false;
5245
+ }
5246
+ continue;
5247
+ }
5248
+ if (ch === "\\" && i + 1 < s.length) {
5249
+ cur += s[++i];
5250
+ continue;
5251
+ }
5252
+ cur += ch;
5253
+ }
5254
+ if (cur || quoted) out.push(cur);
5255
+ return out;
5256
+ }
5257
+ function rmExpandVars(token, env2) {
5258
+ let current = token;
5259
+ for (let round = 0; round < 3; round++) {
5260
+ const next = current.replace(RM_VAR_RE, (whole, braced, bare) => {
5261
+ const name = String(braced || bare).toLowerCase();
5262
+ return env2.get(name) ?? whole;
5263
+ });
5264
+ if (next === current) break;
5265
+ current = next;
5266
+ }
5267
+ return current;
5268
+ }
5269
+ function rmResolvedDangerous(resolved) {
5270
+ if (resolved === "/" || resolved.startsWith("/.")) return true;
5271
+ const first = resolved.split("/")[1] || "";
5272
+ if (first === "home") {
5273
+ const parts = resolved.split("/").filter(Boolean);
5274
+ return parts.length <= 2;
5275
+ }
5276
+ if (RM_SENSITIVE_FIRST.has(first)) return true;
5277
+ if (first === "var" && !(resolved === "/var/tmp" || resolved.startsWith("/var/tmp/"))) {
5278
+ return true;
5279
+ }
5280
+ return false;
5281
+ }
5282
+ function checkRmResolvedTargets(text) {
5283
+ const env2 = /* @__PURE__ */ new Map();
5284
+ for (let segment of splitCommandSegments2(text)) {
5285
+ if (!segment) continue;
5286
+ while (true) {
5287
+ const m = segment.match(RM_ASSIGN_RE);
5288
+ if (!m) break;
5289
+ let value = m[2].trim();
5290
+ if (value.length >= 2 && value[0] === value[value.length - 1] && (value[0] === "'" || value[0] === '"')) {
5291
+ value = value.slice(1, -1);
5292
+ }
5293
+ env2.set(m[1].toLowerCase(), rmExpandVars(value, env2));
5294
+ segment = segment.slice(m[0].length);
5295
+ }
5296
+ const parts = shlexSplitLite(segment);
5297
+ if (parts.length === 0) continue;
5298
+ let idx = 0;
5299
+ while (idx < parts.length && RM_COMMAND_PREFIXES.has(parts[idx].toLowerCase())) idx++;
5300
+ if (idx >= parts.length) continue;
5301
+ const commandWord = parts[idx].split("/").pop().replace(/^\\/, "").toLowerCase();
5302
+ if (commandWord !== "rm") continue;
5303
+ let optionsDone = false;
5304
+ for (const token of parts.slice(idx + 1)) {
5305
+ if (token === "--") {
5306
+ optionsDone = true;
5307
+ continue;
5308
+ }
5309
+ if (!optionsDone && token.startsWith("-")) continue;
5310
+ const target = rmExpandVars(token, env2);
5311
+ if (!target.startsWith("/")) continue;
5312
+ const resolved = posix.normalize(target);
5313
+ if (rmResolvedDangerous(resolved)) {
5314
+ return {
5315
+ allowed: false,
5316
+ reason: `\u68C0\u6D4B\u5230\u5220\u9664\u6839\u76EE\u5F55/\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55\uFF08\u89E3\u6790\u540E\u76EE\u6807 ${resolved}\uFF09`,
5317
+ riskLevel: "critical",
5318
+ riskType: "script_execution",
5319
+ confidence: 95,
5320
+ source: "heuristic",
5321
+ violatedLayers: ["L1.1"]
5322
+ };
5323
+ }
5324
+ }
5325
+ }
5326
+ return null;
5327
+ }
5040
5328
  function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
5041
5329
  const scanDetail = normalizePathSegments(stripLiteralTextSegments(actionDetail));
5042
5330
  const scanCommands = String(osType || "").toLowerCase() === "windows" ? [
@@ -5055,16 +5343,19 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
5055
5343
  }
5056
5344
  }
5057
5345
  }
5058
- if (!top) return null;
5059
- return {
5346
+ const toJudgment = (hit) => ({
5060
5347
  allowed: false,
5061
- reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${top.desc}`,
5062
- riskLevel: top.sev,
5063
- riskType: top.type,
5348
+ reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${hit.desc}`,
5349
+ riskLevel: hit.sev,
5350
+ riskType: hit.type,
5064
5351
  confidence: 95,
5065
5352
  source: "heuristic",
5066
5353
  violatedLayers: ["L1.1"]
5067
- };
5354
+ });
5355
+ if (top && severityRank(top.sev) >= severityRank("high")) return toJudgment(top);
5356
+ const rmResolved = checkRmResolvedTargets(scanDetail);
5357
+ if (rmResolved) return rmResolved;
5358
+ return top ? toJudgment(top) : null;
5068
5359
  }
5069
5360
  function allUrlsLoopback(actionDetail) {
5070
5361
  const hosts = actionDetail.match(new RegExp(LOOPBACK_URL_RE.source, "gi"));
@@ -5199,6 +5490,10 @@ function runHeuristicCheck(input) {
5199
5490
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
5200
5491
  const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
5201
5492
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
5493
+ if (isBashLike && !handledWrite && severityRank(highestSeverity) < severityRank("high") && !mergeResults.some((r) => severityRank(r.riskLevel) >= severityRank("high"))) {
5494
+ const rmResolved = checkRmResolvedTargets(scanDetail);
5495
+ if (rmResolved) mergeResults.push(rmResolved);
5496
+ }
5202
5497
  if (mergeResults.length > 0) {
5203
5498
  let best = mergeResults[0];
5204
5499
  for (const r of mergeResults) {
@@ -5215,6 +5510,9 @@ function runHeuristicCheck(input) {
5215
5510
  violatedLayers: ["L1.1"]
5216
5511
  };
5217
5512
  }
5513
+ if (best !== pathResult && pathResult?.deniedReadPath && best.riskType === "file_access" && best.riskLevel === pathResult.riskLevel) {
5514
+ best = { ...best, deniedReadPath: pathResult.deniedReadPath };
5515
+ }
5218
5516
  return best;
5219
5517
  }
5220
5518
  if (matched.length > 0) {
@@ -5474,7 +5772,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5474
5772
  riskType: "file_access",
5475
5773
  confidence: 90,
5476
5774
  source: "heuristic",
5477
- violatedLayers: ["L1.1"]
5775
+ violatedLayers: ["L1.1"],
5776
+ deniedReadPath: sp.path
5478
5777
  };
5479
5778
  }
5480
5779
  const denyMode = sp.denyMode || (sp.credential ? "deny_both" : sp.readOnly ? "deny_read" : "deny_write");
@@ -5488,7 +5787,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5488
5787
  confidence: 90,
5489
5788
  source: "heuristic",
5490
5789
  violatedLayers: ["L1.1"],
5491
- isCredential: !!sp.credential
5790
+ isCredential: !!sp.credential,
5791
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5492
5792
  };
5493
5793
  }
5494
5794
  }
@@ -5545,7 +5845,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5545
5845
  confidence: 90,
5546
5846
  source: "heuristic",
5547
5847
  violatedLayers: ["L1.1"],
5548
- isCredential: !!sp.credential
5848
+ isCredential: !!sp.credential,
5849
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5549
5850
  };
5550
5851
  }
5551
5852
  }
@@ -5568,7 +5869,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5568
5869
  confidence: 90,
5569
5870
  source: "heuristic",
5570
5871
  violatedLayers: ["L1.1"],
5571
- isCredential: !!sp.credential
5872
+ isCredential: !!sp.credential,
5873
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5572
5874
  };
5573
5875
  }
5574
5876
  }
@@ -5585,7 +5887,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5585
5887
  confidence: 90,
5586
5888
  source: "heuristic",
5587
5889
  violatedLayers: ["L1.1"],
5588
- isCredential: true
5890
+ isCredential: true,
5891
+ deniedReadPath: cp.path
5589
5892
  };
5590
5893
  }
5591
5894
  }
@@ -5888,7 +6191,7 @@ function checkLateralMovement(actionDetail) {
5888
6191
  }
5889
6192
  return null;
5890
6193
  }
5891
- var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
6194
+ var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
5892
6195
  var init_heuristic = __esm({
5893
6196
  "src/engine/heuristic.ts"() {
5894
6197
  "use strict";
@@ -5914,6 +6217,10 @@ var init_heuristic = __esm({
5914
6217
  DANGEROUS_PATTERNS_WINDOWS = _loadDangerousPatterns("windows");
5915
6218
  DANGEROUS_PATTERNS_MACOS = _loadDangerousPatterns("macos");
5916
6219
  DANGEROUS_PATTERNS_HARMONY = _loadDangerousPatterns("harmony");
6220
+ RM_ASSIGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|]+)\s*/;
6221
+ RM_VAR_RE = /\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;
6222
+ RM_COMMAND_PREFIXES = /* @__PURE__ */ new Set(["sudo", "env", "command", "builtin", "exec", "nohup", "time"]);
6223
+ RM_SENSITIVE_FIRST = /* @__PURE__ */ new Set(["etc", "usr", "boot", "root", "opt", "srv", "sys", "proc", "home"]);
5917
6224
  LOOPBACK_URL_RE = /https?:\/\/([^\/\s;'"|&)]+)/i;
5918
6225
  HEURISTIC_RULES = loadHeuristicRules();
5919
6226
  LOOPBACK_HOSTS = new Set(HEURISTIC_RULES.loopback_hosts ?? []);
@@ -8993,12 +9300,14 @@ ${scriptAnalysisText}` : ""}
8993
9300
  \u8F93\u51FA\u683C\u5F0F:
8994
9301
  {"allowed": true/false, "reason": "\u5224\u65AD\u7406\u7531", "riskLevel": "low|medium|high|critical", "riskType": "\u98CE\u9669\u7C7B\u578B", "confidence": 0-100}`;
8995
9302
  }
8996
- function formatPromptHistory(promptHistory, maxTextChars = 500) {
9303
+ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNumSetting("AGENT_MOSS_LLM_PROMPT_HISTORY_MAX_TURNS", 20)) {
8997
9304
  if (!promptHistory || promptHistory.length === 0) {
8998
9305
  return "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
8999
9306
  }
9307
+ const limit = Math.max(0, Math.floor(maxTurns));
9308
+ const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
9000
9309
  const lines = [];
9001
- for (let i = 0; i < promptHistory.length; i++) {
9310
+ for (let i = firstTurnIndex; i < promptHistory.length; i++) {
9002
9311
  const turn = promptHistory[i];
9003
9312
  const text = (typeof turn === "string" ? turn : turn?.text || "").trim();
9004
9313
  if (!text) continue;
@@ -11355,6 +11664,7 @@ var init_engine = __esm({
11355
11664
  });
11356
11665
 
11357
11666
  // src/engine/formal-engine/stateful.ts
11667
+ import { createHash as createHash4 } from "crypto";
11358
11668
  import * as fs5 from "fs";
11359
11669
  import * as os3 from "os";
11360
11670
  import * as path6 from "path";
@@ -11495,7 +11805,36 @@ function cleanupChainArchives(dir, maxBytes = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_
11495
11805
  }
11496
11806
  return { deleted: removed, files: remainFiles, bytes: remainBytes };
11497
11807
  }
11498
- 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, StatefulChainTracker;
11808
+ function canonicalActionType(actionType) {
11809
+ const low = String(actionType || "").trim().toLowerCase();
11810
+ return SHELL_ACTION_ALIASES[low] || low;
11811
+ }
11812
+ function canonicalDetail(actionDetail) {
11813
+ const detail = String(actionDetail || "");
11814
+ const m = TRUNCATED_DETAIL_RE.exec(detail);
11815
+ const digest = m ? m[1] : createHash4("sha256").update(detail).digest("hex").slice(0, 16);
11816
+ return `sha256:${digest}`;
11817
+ }
11818
+ function canonicalCalledAt(calledAt) {
11819
+ const value = String(calledAt || "").trim();
11820
+ if (!value) return "";
11821
+ let normalized = value;
11822
+ if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?$/.test(normalized)) {
11823
+ normalized = normalized.replace(" ", "T") + "Z";
11824
+ }
11825
+ const ms = Date.parse(normalized);
11826
+ return Number.isFinite(ms) ? String(Math.floor(ms / 1e3)) : value;
11827
+ }
11828
+ function fingerprint(sessionId, actionType, actionDetail, calledAt) {
11829
+ const raw = [
11830
+ String(sessionId),
11831
+ canonicalActionType(actionType),
11832
+ canonicalDetail(actionDetail),
11833
+ canonicalCalledAt(calledAt)
11834
+ ].join("\0");
11835
+ return createHash4("blake2b512").update(raw).digest("hex").slice(0, 16);
11836
+ }
11837
+ var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, STAGES_PATTERNS, CHAINS, COMMON_DIR_RESOURCES2, MAX_NODES, TRUNCATED_DETAIL_RE, SHELL_ACTION_ALIASES, StatefulChainTracker;
11499
11838
  var init_stateful = __esm({
11500
11839
  "src/engine/formal-engine/stateful.ts"() {
11501
11840
  "use strict";
@@ -11527,6 +11866,13 @@ var init_stateful = __esm({
11527
11866
  "/storage"
11528
11867
  ]);
11529
11868
  MAX_NODES = resolveMaxNodes();
11869
+ TRUNCATED_DETAIL_RE = /…\[truncated \d+B sha256:([0-9a-f]{16})\]$/;
11870
+ SHELL_ACTION_ALIASES = {
11871
+ executebash: "bash",
11872
+ "terminal-executebash": "bash",
11873
+ execute_bash: "bash",
11874
+ terminal_execute_bash: "bash"
11875
+ };
11530
11876
  StatefulChainTracker = class _StatefulChainTracker {
11531
11877
  /** 本地接收时刻(实时路径无 called_at 时的兜底时间戳,ISO)。 */
11532
11878
  static now() {
@@ -11546,6 +11892,7 @@ var init_stateful = __esm({
11546
11892
  taintedResources = /* @__PURE__ */ new Set();
11547
11893
  aliveResources = {};
11548
11894
  seqNext = 0;
11895
+ seededKeys = /* @__PURE__ */ new Set();
11549
11896
  constructor(agentId = "") {
11550
11897
  this.agentId = agentId;
11551
11898
  loadRules();
@@ -11688,6 +12035,9 @@ var init_stateful = __esm({
11688
12035
  const ad = String(action.actionDetail || "");
11689
12036
  const at = String(action.actionType || "");
11690
12037
  if (!ad) return null;
12038
+ const suppliedCalledAt = typeof action.calledAt === "string" ? action.calledAt : "";
12039
+ const dedupeKey = suppliedCalledAt ? fingerprint(sessionId, at, ad, suppliedCalledAt) : "";
12040
+ if (dedupeKey && this.seededKeys.has(dedupeKey)) return null;
11691
12041
  if (this.nodes_.length >= MAX_NODES) {
11692
12042
  try {
11693
12043
  const r = this.rotate();
@@ -11710,10 +12060,11 @@ var init_stateful = __esm({
11710
12060
  agentId: String(action.agentId || agentId || ""),
11711
12061
  instanceId: String(action.instanceId || instanceId || ""),
11712
12062
  lifecycle: lifecycleFor(ad, stage, isError),
11713
- timestamp: typeof action.calledAt === "string" ? action.calledAt : _StatefulChainTracker.now()
12063
+ timestamp: suppliedCalledAt || _StatefulChainTracker.now()
11714
12064
  };
11715
12065
  this.nodes_.push(node);
11716
12066
  this.seqNext += 1;
12067
+ if (dedupeKey) this.seededKeys.add(dedupeKey);
11717
12068
  return node;
11718
12069
  }
11719
12070
  recordLifecycle(node) {
@@ -12039,12 +12390,14 @@ var init_stateful = __esm({
12039
12390
  taint_parent: Object.fromEntries([...this.taintParent.entries()].map(([k, v]) => [String(k), v])),
12040
12391
  taint_origin: Object.fromEntries([...this.taintOrigin.entries()]),
12041
12392
  alive: { ...this.aliveResources },
12042
- seq_next: this.seqNext
12393
+ seq_next: this.seqNext,
12394
+ seeded_keys: [...this.seededKeys].sort()
12043
12395
  };
12044
12396
  }
12045
12397
  restore(snapshot) {
12046
12398
  if (!snapshot) return;
12047
12399
  this.agentId = String(snapshot.agent_id || this.agentId);
12400
+ this.seededKeys = new Set((snapshot.seeded_keys || []).map(String));
12048
12401
  for (const raw of snapshot.nodes || []) {
12049
12402
  this.nodes_.push({
12050
12403
  seq: Number(raw.seq || 0),
@@ -12065,6 +12418,11 @@ var init_stateful = __esm({
12065
12418
  });
12066
12419
  }
12067
12420
  this.seqNext = Number(snapshot.seq_next || this.nodes_.length);
12421
+ for (const n of this.nodes_) {
12422
+ if (n.timestamp) {
12423
+ this.seededKeys.add(fingerprint(n.sessionId, n.actionType, n.actionDetail, n.timestamp));
12424
+ }
12425
+ }
12068
12426
  this.ptr = Object.fromEntries(Object.entries(snapshot.ptrs || {}).map(([k, v]) => [k, Number(v)]));
12069
12427
  this.tainted = new Set((snapshot.tainted || []).map(Number));
12070
12428
  this.taintParent = new Map(
@@ -12122,12 +12480,12 @@ var init_stateful = __esm({
12122
12480
  import * as fs6 from "fs";
12123
12481
  import * as os4 from "os";
12124
12482
  import * as path7 from "path";
12125
- import { createHash as createHash4 } from "crypto";
12483
+ import { createHash as createHash5 } from "crypto";
12126
12484
  function defaultStateDbPath() {
12127
12485
  const base = process.env.AGENT_MOSS_STATE_DIR || path7.join(os4.homedir(), ".agentmoss");
12128
12486
  const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
12129
12487
  const dir = instance ? path7.join(base, instance) : base;
12130
- const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
12488
+ const tag = createHash5("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
12131
12489
  const target = path7.join(dir, `stateful_chains_${tag}.json`);
12132
12490
  if (instance) {
12133
12491
  const legacy = path7.join(base, `stateful_chains_${tag}.json`);
@@ -12381,6 +12739,7 @@ __export(coordinator_exports, {
12381
12739
  TRUSTED_SKILLS_BASE: () => TRUSTED_SKILLS_BASE,
12382
12740
  _resetBrainForTest: () => _resetBrainForTest,
12383
12741
  extractFirstCommand: () => extractFirstCommand,
12742
+ independentFileCommand: () => independentFileCommand,
12384
12743
  matchesAny: () => matchesAny,
12385
12744
  runAnalysis: () => runAnalysis,
12386
12745
  splitCommandSegments: () => splitCommandSegments,
@@ -12400,6 +12759,25 @@ function extractRawCommand(detail) {
12400
12759
  const m = detail.match(/command=([^,]+)/);
12401
12760
  return m ? m[1].trim() : detail;
12402
12761
  }
12762
+ function independentFileCommand(command, osType) {
12763
+ if (String(osType).toLowerCase() === "windows") return "";
12764
+ if (["\\", "#", "<<", "<(", ">(", "`", "$"].some((mark) => command.includes(mark))) return "";
12765
+ const parts = splitCommandSegments(command);
12766
+ if (parts.length !== 2) return "";
12767
+ const ordinary = parts.filter((part2) => !isInlineScriptCommand(part2.toLowerCase()));
12768
+ if (ordinary.length !== 1) return "";
12769
+ const part = ordinary[0];
12770
+ const name = part.trim().split(/\s+/)[0] || "";
12771
+ const { writeCommandRes } = getPlatformTraits(osType);
12772
+ const isWriteCommandName = writeCommandRes.some((rx) => {
12773
+ const flags = rx.flags.replace("g", "");
12774
+ return new RegExp(`^(?:${rx.source})$`, flags).test(name);
12775
+ });
12776
+ if (SHELL_FULL_READ_CMDS.includes(name) || isWriteCommandName) {
12777
+ return part;
12778
+ }
12779
+ return "";
12780
+ }
12403
12781
  function matchesAny(cmd, patterns) {
12404
12782
  return patterns.some((p) => p.test(cmd));
12405
12783
  }
@@ -12477,13 +12855,24 @@ async function runAnalysis(input) {
12477
12855
  const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
12478
12856
  const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
12479
12857
  if (heuristicResult && !heuristicResult.allowed) {
12480
- const skipInlineFileAccess = (isInlineScriptCmd || isLiteralTextCmd) && heuristicResult.riskType === "file_access";
12481
- if (!skipInlineFileAccess) {
12482
- const shouldDenyL1 = heuristicResult.riskLevel === "high" || heuristicResult.riskLevel === "critical" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "file_access" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "resource_exhaustion";
12483
- if (shouldDenyL1) {
12484
- return heuristicResult;
12858
+ let skipInlineFileAccess = (isInlineScriptCmd || isLiteralTextCmd) && heuristicResult.riskType === "file_access";
12859
+ const shouldDenyL1 = heuristicResult.riskLevel === "high" || heuristicResult.riskLevel === "critical" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "file_access" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "resource_exhaustion";
12860
+ const bashLike = ["bash", "executebash", "terminal-executebash"].includes(input.aNext.actionType.toLowerCase());
12861
+ if (skipInlineFileAccess && shouldDenyL1 && isInlineScriptCmd && bashLike) {
12862
+ const detail = input.aNext.actionDetail;
12863
+ const command = independentFileCommand(detail, input.osType);
12864
+ if (command) {
12865
+ const hit = runHeuristicCheck({ ...input, aNext: { ...input.aNext, actionDetail: command } });
12866
+ if (hit && !hit.allowed && hit.riskType === "file_access" && ["medium", "high", "critical"].includes(hit.riskLevel)) {
12867
+ return hit;
12868
+ }
12869
+ } else if (String(input.osType || "").toLowerCase() !== "windows" && heuristicResult.deniedReadPath) {
12870
+ skipInlineFileAccess = !confirmsInlineRead(detail, heuristicResult.deniedReadPath);
12485
12871
  }
12486
12872
  }
12873
+ if (!skipInlineFileAccess && shouldDenyL1) {
12874
+ return heuristicResult;
12875
+ }
12487
12876
  }
12488
12877
  const agentExt = mergeAgentExtensions(
12489
12878
  isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
@@ -13217,7 +13606,7 @@ init_esm_shims();
13217
13606
  init_security_policy();
13218
13607
  init_paths();
13219
13608
  init_config();
13220
- import { createHash as createHash5 } from "crypto";
13609
+ import { createHash as createHash6 } from "crypto";
13221
13610
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
13222
13611
  import { tmpdir as tmpdir2 } from "os";
13223
13612
  import { join as join17 } from "path";
@@ -13250,7 +13639,7 @@ var PolicyCache = class {
13250
13639
  return `${sessionId}::${promptSession}`;
13251
13640
  }
13252
13641
  cacheFilePath(sessionId, promptSession) {
13253
- const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
13642
+ const promptHash = createHash6("md5").update(promptSession).digest("hex").slice(0, 12);
13254
13643
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13255
13644
  return join17(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13256
13645
  }
@@ -13873,12 +14262,14 @@ var DEFAULT_AGENTGATE_SQLITE = path8.join(
13873
14262
  "agent_gate_ts.db"
13874
14263
  );
13875
14264
  function normalizeAction(row) {
13876
- return {
14265
+ const act = {
13877
14266
  actionType: String(row.action_type || row.tool_name || row.name || ""),
13878
14267
  actionDetail: String(row.action_detail || row.command || row.input || "")
13879
14268
  };
14269
+ if (row.called_at) act.calledAt = String(row.called_at);
14270
+ return act;
13880
14271
  }
13881
- function readJsonDir(dirPath, limit = 1e5) {
14272
+ function readJsonDir(dirPath, limit = 1e5, strict = false) {
13882
14273
  const sessions = /* @__PURE__ */ new Map();
13883
14274
  try {
13884
14275
  const files = fs8.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
@@ -13900,15 +14291,17 @@ function readJsonDir(dirPath, limit = 1e5) {
13900
14291
  for (const v of sessions.values()) total += v.length;
13901
14292
  if (total > limit) break;
13902
14293
  }
13903
- } catch {
14294
+ } catch (err) {
14295
+ if (strict) throw err;
13904
14296
  }
13905
14297
  return [...sessions.entries()].map(([sessionId, actionHistory]) => ({ sessionId, actionHistory }));
13906
14298
  }
13907
- function readSqlite(dbPath, limit = 1e5) {
14299
+ function readSqlite(dbPath, limit = 1e5, strict = false) {
13908
14300
  let Database;
13909
14301
  try {
13910
14302
  Database = esmRequire("better-sqlite3");
13911
- } catch {
14303
+ } catch (err) {
14304
+ if (strict) throw err;
13912
14305
  return [];
13913
14306
  }
13914
14307
  let db;
@@ -13929,7 +14322,8 @@ function readSqlite(dbPath, limit = 1e5) {
13929
14322
  sessions.set(sid, list);
13930
14323
  }
13931
14324
  return [...sessions.entries()].map(([sessionId, actionHistory]) => ({ sessionId, actionHistory }));
13932
- } catch {
14325
+ } catch (err) {
14326
+ if (strict) throw err;
13933
14327
  return [];
13934
14328
  } finally {
13935
14329
  try {
@@ -13940,15 +14334,10 @@ function readSqlite(dbPath, limit = 1e5) {
13940
14334
  }
13941
14335
  function loadAgentGateSessions(dbPath = "") {
13942
14336
  if (dbPath) {
13943
- try {
13944
- if (fs8.statSync(dbPath).isDirectory()) {
13945
- return readJsonDir(dbPath);
13946
- }
13947
- } catch {
13948
- }
13949
- const sql2 = readSqlite(dbPath);
13950
- if (sql2.length > 0) return sql2;
13951
- return readJsonDir(dbPath);
14337
+ const target = dbPath.replace(/^~(?=$|\/)/, os5.homedir());
14338
+ const stat = fs8.statSync(target);
14339
+ if (stat.isDirectory()) return readJsonDir(target, 1e5, true);
14340
+ return readSqlite(target, 1e5, true);
13952
14341
  }
13953
14342
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
13954
14343
  if (sql.length > 0) return sql;
@@ -14177,7 +14566,7 @@ async function analyzeRoute(c) {
14177
14566
  session_history: req.session_history,
14178
14567
  metadata: req.metadata
14179
14568
  });
14180
- const result = await analyze({
14569
+ let result = await analyze({
14181
14570
  sessionId: req.session_id,
14182
14571
  promptSession: req.prompt_session,
14183
14572
  // output 必须透传:L2 的「授权(consent)」判定看的是**用户对提问的回答**,
@@ -14235,6 +14624,47 @@ async function analyzeRoute(c) {
14235
14624
  llmConfig: perRequestLlmEnabled() ? req.metadata?.llm_config : void 0,
14236
14625
  llmLogPath: req.metadata?.llm_log_path
14237
14626
  });
14627
+ const meta = req.metadata || {};
14628
+ const incEnabled = String(meta.stateful_incremental || "").toLowerCase();
14629
+ let finding = null;
14630
+ if (incEnabled === "1" || incEnabled === "true" || incEnabled === "yes" || incEnabled === "on") {
14631
+ try {
14632
+ const store = getChainStateStoreFor(agentId);
14633
+ const inc = store.applyAction(
14634
+ chainBucket(agentId),
14635
+ { actionType: req.a_next.action_type, actionDetail: req.a_next.action_detail },
14636
+ req.session_id,
14637
+ Boolean(meta.is_error),
14638
+ agentId,
14639
+ // 来源:真实 agent(桶 key 可能是 __system__)
14640
+ instanceId
14641
+ );
14642
+ try {
14643
+ const total = store.stats().nodes;
14644
+ const pct = Math.round(total / MAX_NODES * 1e3) / 10;
14645
+ if (total >= MAX_NODES) {
14646
+ degradedNotes.push(
14647
+ `\u3010\u5DF2\u964D\u7EA7\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u8FBE\u5230\u4E0A\u9650\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u7CFB\u7EDF\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u9700\u8981\u624B\u5DE5 state reset\uFF1B\u82E5\u6301\u7EED\u51FA\u73B0\uFF0C\u68C0\u67E5\u5F52\u6863\u76EE\u5F55\u6743\u9650/\u78C1\u76D8\u7A7A\u95F4\u3002L1/L2.1/L3 \u6B63\u5E38\u3002\u8BE6\u89C1 docs/deploy/UPGRADE_GUIDE.md`
14648
+ );
14649
+ } else if (pct >= 90) {
14650
+ degradedNotes.push(
14651
+ `\u3010\u9884\u8B66\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u5DF2\u7528 ${pct}%\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u8FBE\u5230\u4E0A\u9650\u540E\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u4F1A\u5BFC\u81F4\u7EC4\u5408\u94FE\u68C0\u6D4B\u5931\u6548\uFF1B\u65E0\u9700\u624B\u5DE5 state reset\u3002\u8BE6\u89C1 docs/deploy/PERFORMANCE_TUNING.md \u7B2C 5 \u8282`
14652
+ );
14653
+ }
14654
+ } catch {
14655
+ }
14656
+ finding = incMatchedToDeny(inc);
14657
+ } catch (err) {
14658
+ console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
14659
+ }
14660
+ }
14661
+ result = publicFormalResult(
14662
+ result,
14663
+ finding,
14664
+ instanceId,
14665
+ req.session_id,
14666
+ req.session_history || []
14667
+ );
14238
14668
  const durationMs = performance.now() - t0;
14239
14669
  const _l3FailMsg = String(result.reason || "").slice(0, 160);
14240
14670
  if (result.l3_outcome === "reasoning_fallback") {
@@ -14269,8 +14699,10 @@ async function analyzeRoute(c) {
14269
14699
  l3_outcome: result.l3_outcome || ""
14270
14700
  });
14271
14701
  ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
14272
- for (const layer of result.violated_layers || []) {
14273
- LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
14702
+ for (const layer of new Set(
14703
+ (result.violated_layers || []).map((layer2) => String(layer2).split("-")[0])
14704
+ )) {
14705
+ LAYER_HIT_TOTAL.inc(1, { layer });
14274
14706
  }
14275
14707
  } catch {
14276
14708
  }
@@ -14302,62 +14734,6 @@ async function analyzeRoute(c) {
14302
14734
  });
14303
14735
  } catch {
14304
14736
  }
14305
- const meta = req.metadata || {};
14306
- const incEnabled = String(meta.stateful_incremental || "").toLowerCase();
14307
- if (incEnabled === "1" || incEnabled === "true" || incEnabled === "yes" || incEnabled === "on") {
14308
- try {
14309
- const store = getChainStateStoreFor(agentId);
14310
- const inc = store.applyAction(
14311
- chainBucket(agentId),
14312
- { actionType: req.a_next.action_type, actionDetail: req.a_next.action_detail },
14313
- req.session_id,
14314
- Boolean(meta.is_error),
14315
- agentId,
14316
- // 来源:真实 agent(桶 key 可能是 __system__)
14317
- instanceId
14318
- );
14319
- try {
14320
- const total = store.stats().nodes;
14321
- const pct = Math.round(total / MAX_NODES * 1e3) / 10;
14322
- if (total >= MAX_NODES) {
14323
- degradedNotes.push(
14324
- `\u3010\u5DF2\u964D\u7EA7\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u8FBE\u5230\u4E0A\u9650\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u7CFB\u7EDF\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u9700\u8981\u624B\u5DE5 state reset\uFF1B\u82E5\u6301\u7EED\u51FA\u73B0\uFF0C\u68C0\u67E5\u5F52\u6863\u76EE\u5F55\u6743\u9650/\u78C1\u76D8\u7A7A\u95F4\u3002L1/L2.1/L3 \u6B63\u5E38\u3002\u8BE6\u89C1 docs/deploy/UPGRADE_GUIDE.md`
14325
- );
14326
- } else if (pct >= 90) {
14327
- degradedNotes.push(
14328
- `\u3010\u9884\u8B66\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u5DF2\u7528 ${pct}%\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u8FBE\u5230\u4E0A\u9650\u540E\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u4F1A\u5BFC\u81F4\u7EC4\u5408\u94FE\u68C0\u6D4B\u5931\u6548\uFF1B\u65E0\u9700\u624B\u5DE5 state reset\u3002\u8BE6\u89C1 docs/deploy/PERFORMANCE_TUNING.md \u7B2C 5 \u8282`
14329
- );
14330
- }
14331
- } catch {
14332
- }
14333
- const judgment = incMatchedToDeny(inc);
14334
- if (judgment) {
14335
- const layers = [...result.violated_layers];
14336
- if (!layers.includes("L2.2-stateful")) layers.push("L2.2-stateful");
14337
- console.error(
14338
- `[AgentMoss] stateful \u589E\u91CF\u62E6\u622A: agent=${agentId || "-"} property=${judgment.property_id} risk=${judgment.risk_level}`
14339
- );
14340
- return c.json(
14341
- AnalyzeResponseSchema.parse({
14342
- decision: "Deny",
14343
- reason: judgment.reason,
14344
- risk_level: judgment.risk_level,
14345
- risk_type: "formal_verification",
14346
- violated_layers: layers,
14347
- policy: "",
14348
- violated_policy: "",
14349
- confidence: 90,
14350
- analysis_duration_ms: Math.round((performance.now() - t0) * 10) / 10,
14351
- // 跨会话节点脱敏(时间线按 agent_id 共享,原样返回等于泄露别人的命令原文)
14352
- violation_chain: redactChain(judgment.violation_chain, instanceId, req.session_id),
14353
- violation_graph: redactGraph(judgment.violation_graph, instanceId, req.session_id)
14354
- })
14355
- );
14356
- }
14357
- } catch (err) {
14358
- console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
14359
- }
14360
- }
14361
14737
  return c.json(
14362
14738
  AnalyzeResponseSchema.parse({
14363
14739
  decision: result.decision,
@@ -14371,8 +14747,10 @@ async function analyzeRoute(c) {
14371
14747
  violated_policy: result.violated_policy,
14372
14748
  confidence: result.confidence,
14373
14749
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
14750
+ // 已在 publicFormalResult 中按静态/增量来源选定并脱敏;这里不能再按
14751
+ // 真实 session 二次脱敏,否则会把静态引擎的 `current` 别名节点误隐藏。
14374
14752
  violation_chain: result.violation_chain ?? [],
14375
- violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
14753
+ violation_graph: result.violation_graph ?? null,
14376
14754
  // 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
14377
14755
  degraded: degradedNotes,
14378
14756
  // L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
@@ -14399,6 +14777,84 @@ async function analyzeRoute(c) {
14399
14777
  function getChainStateStoreFor(_agentId) {
14400
14778
  return getChainStateStore();
14401
14779
  }
14780
+ var RISK_PRIORITY = { low: 0, medium: 1, high: 2, critical: 3 };
14781
+ function mergeStatefulDenial(result, finding) {
14782
+ const level = String(finding.risk_level || "high");
14783
+ const outcome = result.l3_outcome;
14784
+ const statefulWins = result.decision !== "Deny" || ["llm_failure_fallback", "llm_circuit_open", "llm_failure_with_violation"].includes(result.source) || (RISK_PRIORITY[level] ?? 0) > (RISK_PRIORITY[result.risk_level] ?? -1);
14785
+ const merged = { ...result };
14786
+ if (statefulWins) {
14787
+ const reason = finding.reason || "\u6709\u72B6\u6001\u589E\u91CF\u94FE\u5224\u5B9A\uFF1A\u7EC4\u5408\u653B\u51FB\u94FE\u547D\u4E2D";
14788
+ Object.assign(merged, {
14789
+ decision: "Deny",
14790
+ reason,
14791
+ risk_level: level,
14792
+ risk_type: "formal_verification",
14793
+ source: "formal_engine",
14794
+ confidence: 90,
14795
+ policy: "",
14796
+ violated_policy: `[formal_verification] ${reason}`
14797
+ });
14798
+ }
14799
+ const layers = Array.isArray(result.violated_layers) ? result.violated_layers : [];
14800
+ merged.violated_layers = [.../* @__PURE__ */ new Set([...layers, "L2.2-stateful"])];
14801
+ if (outcome === "fail_open" || outcome === "fail_closed") {
14802
+ merged.l3_outcome = "failed_but_blocked";
14803
+ }
14804
+ console.error(
14805
+ `[AgentMoss] stateful \u589E\u91CF\u62E6\u622A: property=${finding.property_id || "?"} risk=${level} final_risk=${merged.risk_level}`
14806
+ );
14807
+ return { result: merged, wins: statefulWins };
14808
+ }
14809
+ function publicFormalResult(result, finding, instanceId, sessionId, sessionHistory) {
14810
+ let graph = result.violation_graph;
14811
+ let chain = result.violation_chain;
14812
+ let propertyId = graph?.property_id;
14813
+ let staticEvidence = Boolean(chain && chain.length || graph);
14814
+ if (!finding && !staticEvidence) return result;
14815
+ if (finding) {
14816
+ const merged = mergeStatefulDenial(result, finding);
14817
+ result = merged.result;
14818
+ if (merged.wins) propertyId = finding.property_id;
14819
+ const incrementalGraph = finding.violation_graph || {};
14820
+ const fillsMissingGraph = !graph && (finding.risk_level || "high") === result.risk_level && finding.violation_chain && incrementalGraph.nodes;
14821
+ if (merged.wins || !staticEvidence || fillsMissingGraph) {
14822
+ chain = finding.violation_chain;
14823
+ graph = incrementalGraph;
14824
+ staticEvidence = false;
14825
+ }
14826
+ }
14827
+ let publicSessionId = sessionId;
14828
+ let alias = "";
14829
+ if (staticEvidence) {
14830
+ if (!sessionHistory.some((s) => s.session_id === "current")) {
14831
+ alias = "current";
14832
+ } else if (publicSessionId === "current") {
14833
+ publicSessionId = "";
14834
+ }
14835
+ }
14836
+ const publicGraph = redactGraph(graph, instanceId, publicSessionId, { sessionAlias: alias });
14837
+ const out = {
14838
+ ...result,
14839
+ violation_chain: redactChain(chain || [], instanceId, publicSessionId, {
14840
+ graph,
14841
+ sessionAlias: alias
14842
+ }),
14843
+ violation_graph: publicGraph
14844
+ };
14845
+ if (propertyId === "sensitive-data-flow" && chainDetailMode() !== "full") {
14846
+ const nodes = publicGraph?.nodes || [];
14847
+ let reason = "\u654F\u611F\u6570\u636E\u4F20\u64AD\u5916\u4F20\uFF1A\u68C0\u6D4B\u5230\u7ECF\u5171\u4EAB\u8F7D\u4F53\u5916\u53D1";
14848
+ if (nodes.length >= 2) {
14849
+ const src = nodes[0];
14850
+ const dst = nodes[nodes.length - 1];
14851
+ reason = `\u654F\u611F\u6570\u636E\u4F20\u64AD\u5916\u4F20\uFF1A${src.session_id}#${src.seq} \u2192 ${dst.session_id}#${dst.seq} \u7ECF\u5171\u4EAB\u8F7D\u4F53\u5916\u53D1`;
14852
+ }
14853
+ out.reason = reason;
14854
+ out.violated_policy = `[formal_verification] ${reason}`;
14855
+ }
14856
+ return out;
14857
+ }
14402
14858
  function incMatchedToDeny(inc) {
14403
14859
  if (inc.matched) {
14404
14860
  const chain = (inc.matched.path || []).map((p) => [p.sessionId, p.seq, p.stage, p.timestamp, p.agentId ?? null]);
@@ -14428,12 +14884,6 @@ async function reviewRoute(c) {
14428
14884
  const body = await c.req.json();
14429
14885
  const req = ReviewRequestSchema.parse(body);
14430
14886
  const agentId = req.agent_id || "default";
14431
- const store = getChainStateStoreFor(agentId);
14432
- const bucket = chainBucket(agentId);
14433
- let tracker = store.load(bucket);
14434
- if (!tracker) {
14435
- tracker = new StatefulChainTracker(bucket);
14436
- }
14437
14887
  if (req.db_path && !pathWithin(req.db_path, reviewRoots())) {
14438
14888
  return c.json({
14439
14889
  detail: "db_path \u4E0D\u5728\u5141\u8BB8\u8BFB\u53D6\u7684\u76EE\u5F55\u5185\uFF1B\u6807\u51C6 AgentGate \u90E8\u7F72\u65E0\u9700\u914D\u7F6E\uFF0C\u81EA\u5B9A\u4E49\u8DEF\u5F84\u8BF7\u52A0\u5165 AGENT_MOSS_REVIEW_PATHS"
@@ -14441,24 +14891,35 @@ async function reviewRoute(c) {
14441
14891
  }
14442
14892
  let sessions = [];
14443
14893
  if (req.db_path) {
14444
- sessions = loadAgentGateSessions(req.db_path);
14445
- if (sessions.length === 0) sessions = (req.sessions || []).map((s) => ({
14446
- sessionId: s.session_id,
14447
- actionHistory: s.action_history.map((a) => ({ actionType: a.action_type, actionDetail: a.action_detail }))
14448
- }));
14894
+ try {
14895
+ sessions = loadAgentGateSessions(req.db_path);
14896
+ } catch (err) {
14897
+ if (err?.code === "ENOENT") {
14898
+ return c.json({ detail: "\u6307\u5B9A\u7684\u56DE\u987E\u8DEF\u5F84\u4E0D\u5B58\u5728" }, 404);
14899
+ }
14900
+ throw err;
14901
+ }
14449
14902
  } else {
14450
14903
  sessions = (req.sessions || []).map((s) => ({
14451
14904
  sessionId: s.session_id,
14452
- actionHistory: s.action_history.map((a) => ({ actionType: a.action_type, actionDetail: a.action_detail }))
14905
+ actionHistory: s.action_history.map((a) => ({ actionType: a.action_type, actionDetail: a.action_detail, calledAt: a.called_at }))
14453
14906
  }));
14454
14907
  }
14908
+ const explicitEmpty = !!req.db_path && sessions.length === 0;
14909
+ const store = getChainStateStoreFor(agentId);
14910
+ const bucket = chainBucket(agentId);
14911
+ let tracker = store.load(bucket);
14912
+ if (!tracker) {
14913
+ tracker = new StatefulChainTracker(bucket);
14914
+ }
14455
14915
  const added = sessions.length > 0 ? tracker.seed(sessions) : 0;
14456
14916
  store.save(tracker);
14457
14917
  let verified = true;
14458
14918
  const violations = [];
14459
- if (sessions.length > 0 || tracker.nodes.length > 0) {
14919
+ const shouldVerify = explicitEmpty ? Boolean(req.a_next) : sessions.length > 0 || tracker.nodes.length > 0;
14920
+ if (shouldVerify) {
14460
14921
  const eng = new FormalEngine();
14461
- const verifySessions = sessions.length > 0 ? sessions.map((s) => ({ sessionId: s.sessionId, actionHistory: s.actionHistory })) : tracker.nodes.length > 0 ? [{
14922
+ const verifySessions = explicitEmpty ? [] : sessions.length > 0 ? sessions.map((s) => ({ sessionId: s.sessionId, actionHistory: s.actionHistory })) : tracker.nodes.length > 0 ? [{
14462
14923
  sessionId: tracker.agentId,
14463
14924
  actionHistory: tracker.nodes.map((n) => ({
14464
14925
  actionType: n.actionType,