@kenhkl/agent-moss 0.17.40 → 0.17.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -764,6 +764,12 @@ function originAllowed(origin, hostHeader, extra) {
764
764
  return false;
765
765
  }
766
766
  }
767
+ function validGateCallId(value) {
768
+ return typeof value === "string" && /^[0-9a-f]{32}$/.test(value);
769
+ }
770
+ function validGateCallTime(value) {
771
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= Number.MAX_SAFE_INTEGER;
772
+ }
767
773
  function authMode() {
768
774
  return (env("AGENT_MOSS_AUTH_MODE", AUTH_MODE_AUTO) || AUTH_MODE_AUTO).toLowerCase();
769
775
  }
@@ -858,13 +864,17 @@ function parseAgentTokens(raw) {
858
864
  }
859
865
  function resolveAuth() {
860
866
  const rawAgents = env("AGENT_MOSS_AGENT_TOKENS");
867
+ const gateToken = env("AGENT_MOSS_GATE_AUTH_TOKEN");
868
+ const consoleToken = env("AGENT_MOSS_CONSOLE_TOKEN");
861
869
  const key = [
862
870
  authMode(),
863
871
  env("AGENT_MOSS_AUTH_TOKEN"),
864
872
  env("AGENT_MOSS_AUTH_TOKEN_FILE"),
865
873
  env("AGENT_MOSS_AUTH_TOKEN_FD"),
866
874
  rawAgents,
867
- env("AGENT_MOSS_DATA_DIR")
875
+ env("AGENT_MOSS_DATA_DIR"),
876
+ gateToken,
877
+ consoleToken
868
878
  ].join("\0");
869
879
  if (tokenCache && tokenCache.key === key) {
870
880
  return [tokenCache.token, tokenCache.agents, tokenCache.error];
@@ -887,6 +897,13 @@ function resolveAuth() {
887
897
  }
888
898
  }
889
899
  const agents = parseAgentTokens(rawAgents);
900
+ if (!error && authMode() === AUTH_MODE_OFF && gateToken) {
901
+ error = "AGENT_MOSS_GATE_AUTH_TOKEN \u4E0D\u80FD\u5728 AGENT_MOSS_AUTH_MODE=off \u65F6\u542F\u7528";
902
+ } else if (!error && gateToken) {
903
+ if (gateToken === token || gateToken === consoleToken || Object.values(agents).includes(gateToken)) {
904
+ error = "AGENT_MOSS_GATE_AUTH_TOKEN \u5FC5\u987B\u4E0E\u5168\u5C40\u3001Agent \u548C Console \u51ED\u636E\u4E0D\u540C";
905
+ }
906
+ }
890
907
  tokenCache = { key, token, agents, error };
891
908
  return [token, agents, error];
892
909
  }
@@ -906,7 +923,7 @@ function failFastOnAuthError() {
906
923
  function authEnabled() {
907
924
  if (authMode() === AUTH_MODE_OFF) return false;
908
925
  const [tok, agents, err] = resolveAuth();
909
- return Boolean(err) || Boolean(tok) || Object.keys(agents).length > 0;
926
+ return Boolean(err) || Boolean(tok) || Object.keys(agents).length > 0 || Boolean(env("AGENT_MOSS_GATE_AUTH_TOKEN"));
910
927
  }
911
928
  function bearer(headers) {
912
929
  const get = (k) => headers instanceof Headers ? headers.get(k) ?? "" : headers[k] ?? "";
@@ -921,14 +938,19 @@ function constEq(a, b) {
921
938
  }
922
939
  function checkRequestAuth(headers, path9) {
923
940
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
924
- const isHealth = HEALTH_PATHS.includes(path9.replace(/\/+$/, ""));
941
+ const normalizedPath = path9.replace(/\/+$/, "");
942
+ const isHealth = HEALTH_PATHS.includes(normalizedPath);
925
943
  const [gt0, agents, err] = resolveAuth();
944
+ const gateToken = env("AGENT_MOSS_GATE_AUTH_TOKEN");
926
945
  if (err) return isHealth ? [true, ""] : [false, ""];
927
- if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
946
+ if (!gt0 && Object.keys(agents).length === 0 && !gateToken) return [true, ""];
928
947
  if (isHealth) return [true, ""];
929
948
  const tok = bearer(headers);
930
949
  if (!tok) return [false, ""];
931
- if (path9.startsWith("/console/api")) {
950
+ if (gateToken && GATE_AUTH_PATHS.has(normalizedPath) && constEq(tok, gateToken)) {
951
+ return [true, GATE_PRINCIPAL];
952
+ }
953
+ if (normalizedPath.startsWith("/console/api")) {
932
954
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
933
955
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
934
956
  }
@@ -1110,38 +1132,68 @@ function hardenExistingPaths() {
1110
1132
  function chainDetailMode() {
1111
1133
  return (env("AGENT_MOSS_CHAIN_DETAIL", "redacted") || "redacted").toLowerCase();
1112
1134
  }
1113
- function redactChain(chain, currentInstanceId = "", currentSessionId = "") {
1135
+ function chainNodeVisible(instanceId, sessionId, currentInstanceId, currentSessionId, sessionAlias) {
1136
+ const inst = String(instanceId ?? "") || "";
1137
+ if (inst) {
1138
+ return !!(currentInstanceId && inst === String(currentInstanceId));
1139
+ }
1140
+ const sid = String(sessionId ?? "") || "";
1141
+ return !!sid && (sid === currentSessionId || sid === sessionAlias);
1142
+ }
1143
+ function redactChain(chain, currentInstanceId = "", currentSessionId = "", opts = {}) {
1114
1144
  if (!chain || chain.length === 0) return [];
1115
1145
  if (chainDetailMode() === "full") return [...chain];
1116
- return chain.map((step) => {
1146
+ const nodes = opts.graph?.nodes || [];
1147
+ return chain.map((step, index) => {
1117
1148
  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 ?? ""];
1149
+ const sid = step[0];
1150
+ const seq = step[1];
1151
+ const ts = step.length > 3 ? step[3] : "";
1152
+ let inst = step.length > 5 ? step[5] : "";
1153
+ if (!inst && index < nodes.length) {
1154
+ const node = nodes[index];
1155
+ const detail = String(node.action_detail ?? "");
1156
+ const stepDetail = String(step[2] ?? "");
1157
+ if (String(sid) !== String(node.session_id ?? "") || String(seq) !== String(node.seq ?? "") || stepDetail !== detail && stepDetail !== detail.slice(0, 60)) {
1158
+ return ["<other-session>", seq, "<\u5DF2\u9690\u85CF>", ts];
1159
+ }
1160
+ inst = node.instance_id;
1161
+ }
1162
+ if (chainNodeVisible(inst, sid, currentInstanceId, currentSessionId, opts.sessionAlias || "")) {
1163
+ return [...step];
1164
+ }
1165
+ return ["<other-session>", seq, "<\u5DF2\u9690\u85CF>", ts];
1124
1166
  }
1125
1167
  return step;
1126
1168
  });
1127
1169
  }
1128
- function redactGraph(graph, currentInstanceId = "", currentSessionId = "") {
1170
+ function redactGraph(graph, currentInstanceId = "", currentSessionId = "", opts = {}) {
1129
1171
  if (!graph) return null;
1130
1172
  if (chainDetailMode() === "full") return graph;
1131
- const nodes = (graph.nodes || []).map((n) => {
1173
+ const hidden = /* @__PURE__ */ new Set();
1174
+ const nodes = (graph.nodes || []).map((n, index) => {
1132
1175
  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)) {
1176
+ if (!chainNodeVisible(
1177
+ m.instance_id,
1178
+ m.session_id,
1179
+ currentInstanceId,
1180
+ currentSessionId,
1181
+ opts.sessionAlias || ""
1182
+ )) {
1183
+ hidden.add(index);
1138
1184
  m.session_id = "<other-session>";
1139
1185
  m.action_detail = "<\u5DF2\u9690\u85CF>";
1140
1186
  m.resources = [];
1141
1187
  }
1142
1188
  return m;
1143
1189
  });
1144
- const out = { nodes, edges: graph.edges || [] };
1190
+ const edges = (graph.edges || []).map((edge) => {
1191
+ if ("label" in edge && (hidden.has(Number(edge.from)) || hidden.has(Number(edge.to)))) {
1192
+ return { ...edge, label: "" };
1193
+ }
1194
+ return edge;
1195
+ });
1196
+ const out = { nodes, edges };
1145
1197
  for (const key of ["property_id", "property_short", "property_name", "property_expression"]) {
1146
1198
  if (graph[key] !== void 0) out[key] = graph[key];
1147
1199
  }
@@ -1244,7 +1296,7 @@ function maxConnections() {
1244
1296
  function keepAliveSec() {
1245
1297
  return envInt("AGENT_MOSS_KEEP_ALIVE_SEC", 5);
1246
1298
  }
1247
- var TRUTHY2, HEALTH_PATHS, AUTH_MODE_AUTO, AUTH_MODE_OFF, tokenCache, fdTokenCache, BLOCKED_HOSTS, sessionWindow, queueRejects, POOL_DEFAULTS;
1299
+ var TRUTHY2, HEALTH_PATHS, AUTH_MODE_AUTO, AUTH_MODE_OFF, GATE_PRINCIPAL, GATE_IDENTITY_HEADER, GATE_CALL_ID_HEADER, GATE_RATE_LIMIT_HEADER, GATE_BUSY_HEADER, GATE_AUTH_PATHS, tokenCache, fdTokenCache, BLOCKED_HOSTS, sessionWindow, queueRejects, POOL_DEFAULTS;
1248
1300
  var init_security_policy = __esm({
1249
1301
  "src/infra/security-policy.ts"() {
1250
1302
  "use strict";
@@ -1254,6 +1306,12 @@ var init_security_policy = __esm({
1254
1306
  HEALTH_PATHS = ["/api/v1/health"];
1255
1307
  AUTH_MODE_AUTO = "auto";
1256
1308
  AUTH_MODE_OFF = "off";
1309
+ GATE_PRINCIPAL = "gate";
1310
+ GATE_IDENTITY_HEADER = "X-AgentGate-Require-Identity";
1311
+ GATE_CALL_ID_HEADER = "X-AgentGate-Call-Id";
1312
+ GATE_RATE_LIMIT_HEADER = "X-AgentGate-Rate-Limited-Call-Id";
1313
+ GATE_BUSY_HEADER = "X-AgentGate-Busy-Call-Id";
1314
+ GATE_AUTH_PATHS = /* @__PURE__ */ new Set(["/api/v1/analyze", "/api/v1/review"]);
1257
1315
  tokenCache = null;
1258
1316
  fdTokenCache = /* @__PURE__ */ new Map();
1259
1317
  BLOCKED_HOSTS = ["169.254.169.254", "metadata.google.internal", "metadata.tencentyun.com"];
@@ -1371,6 +1429,157 @@ function hasInlineDangerEvidence(command) {
1371
1429
  for (const re of DANGER_EVIDENCE_RES) if (re.test(code)) return true;
1372
1430
  return false;
1373
1431
  }
1432
+ function literalShellWord(raw) {
1433
+ if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) {
1434
+ const inner = raw.slice(1, -1);
1435
+ return inner.includes("'") ? null : inner;
1436
+ }
1437
+ if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) {
1438
+ const inner = raw.slice(1, -1);
1439
+ return /["\\$`]/.test(inner) ? null : inner;
1440
+ }
1441
+ if (!raw || /\s/.test(raw) || !/^[A-Za-z0-9_@%+=:,./-]+$/.test(raw)) return null;
1442
+ return raw;
1443
+ }
1444
+ function pythonStringLiteral(raw) {
1445
+ const text = raw.trim();
1446
+ if (text.length < 2) return null;
1447
+ const quote = text[0];
1448
+ if (quote !== "'" && quote !== '"' || text[text.length - 1] !== quote) return null;
1449
+ const inner = text.slice(1, -1);
1450
+ if (inner.includes(quote) || inner.includes("\\") || inner.includes("\n")) return null;
1451
+ return inner;
1452
+ }
1453
+ function splitPythonArgs(raw) {
1454
+ const parts = [];
1455
+ let current = "";
1456
+ let depth = 0;
1457
+ let quote = null;
1458
+ for (const ch of raw) {
1459
+ if (quote) {
1460
+ current += ch;
1461
+ if (ch === quote) quote = null;
1462
+ continue;
1463
+ }
1464
+ if (ch === "'" || ch === '"') {
1465
+ quote = ch;
1466
+ current += ch;
1467
+ continue;
1468
+ }
1469
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
1470
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1471
+ if (ch === "," && depth === 0) {
1472
+ parts.push(current.trim());
1473
+ current = "";
1474
+ continue;
1475
+ }
1476
+ current += ch;
1477
+ }
1478
+ if (quote || depth !== 0) return null;
1479
+ parts.push(current.trim());
1480
+ return parts;
1481
+ }
1482
+ function hasTopLevelChar(raw, target) {
1483
+ let depth = 0;
1484
+ let quote = null;
1485
+ for (const ch of raw) {
1486
+ if (quote) {
1487
+ if (ch === quote) quote = null;
1488
+ continue;
1489
+ }
1490
+ if (ch === "'" || ch === '"') quote = ch;
1491
+ else if (ch === "(" || ch === "[" || ch === "{") depth++;
1492
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1493
+ else if (ch === target && depth === 0) return true;
1494
+ }
1495
+ return false;
1496
+ }
1497
+ function splitPythonStatements(code) {
1498
+ const parts = [];
1499
+ let current = "";
1500
+ let depth = 0;
1501
+ let quote = null;
1502
+ for (const ch of code) {
1503
+ if (quote) {
1504
+ current += ch;
1505
+ if (ch === quote) quote = null;
1506
+ continue;
1507
+ }
1508
+ if (ch === "'" || ch === '"') {
1509
+ quote = ch;
1510
+ current += ch;
1511
+ continue;
1512
+ }
1513
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
1514
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1515
+ if ((ch === ";" || ch === "\n") && depth === 0) {
1516
+ parts.push(current);
1517
+ current = "";
1518
+ continue;
1519
+ }
1520
+ current += ch;
1521
+ }
1522
+ if (quote || depth !== 0) return null;
1523
+ parts.push(current);
1524
+ return parts.map((s) => s.trim()).filter((s) => s.length > 0);
1525
+ }
1526
+ function isSimpleOpenCall(expr, path9, binding) {
1527
+ const m = expr.match(/^open\s*\(([\s\S]*)\)$/);
1528
+ if (!m || hasTopLevelChar(m[1], "=")) return false;
1529
+ const args = splitPythonArgs(m[1]);
1530
+ if (!args || args.length !== 1 && args.length !== 2) return false;
1531
+ if (args.length === 2 && !["r", "rt", "rb"].includes(pythonStringLiteral(args[1]) ?? "")) {
1532
+ return false;
1533
+ }
1534
+ const target = args[0].trim();
1535
+ const literal = pythonStringLiteral(target);
1536
+ if (literal !== null) return literal === path9;
1537
+ return !!binding && target === binding;
1538
+ }
1539
+ function confirmsInlineRead(command, path9) {
1540
+ if (command.length > 8192 || !path9 || path9.startsWith("~")) return false;
1541
+ if (path9.includes("/") && !path9.startsWith("/")) return false;
1542
+ const wrapper = command.trim().match(/^python3?[ \t]+-c[ \t]+([\s\S]+)$/);
1543
+ if (!wrapper) return false;
1544
+ const code = literalShellWord(wrapper[1]);
1545
+ if (code === null) return false;
1546
+ const statements = splitPythonStatements(code);
1547
+ if (!statements || statements.length !== 1 && statements.length !== 2) return false;
1548
+ let expr;
1549
+ let binding = null;
1550
+ if (statements.length === 2) {
1551
+ const first = statements[0];
1552
+ if (first === "import os") {
1553
+ const sys = statements[1].match(/^os\.system\s*\(([\s\S]*)\)$/);
1554
+ if (!sys || hasTopLevelChar(sys[1], "=")) return false;
1555
+ const args = splitPythonArgs(sys[1]);
1556
+ if (!args || args.length !== 1) return false;
1557
+ const child = pythonStringLiteral(args[0]);
1558
+ if (child === null) return false;
1559
+ const cat = child.trim().match(/^cat[ \t]+([\s\S]+)$/);
1560
+ return !!cat && !path9.startsWith("-") && literalShellWord(cat[1].trim()) === path9;
1561
+ }
1562
+ const assign = first.match(/^([A-Za-z_]\w*)\s*=\s*([\s\S]+)$/);
1563
+ if (!assign) return false;
1564
+ const name = assign[1];
1565
+ const value = pythonStringLiteral(assign[2]);
1566
+ if (value !== path9 || ["open", "print", "__debug__"].includes(name)) return false;
1567
+ binding = name;
1568
+ expr = statements[1];
1569
+ } else {
1570
+ expr = statements[0];
1571
+ }
1572
+ const printCall = expr.match(/^print\s*\(([\s\S]*)\)$/);
1573
+ if (printCall) {
1574
+ if (hasTopLevelChar(printCall[1], "=")) return false;
1575
+ const args = splitPythonArgs(printCall[1]);
1576
+ if (!args || args.length !== 1) return false;
1577
+ expr = args[0];
1578
+ }
1579
+ const readCall = expr.match(/^([\s\S]+)\.read\s*\(\s*\)$/);
1580
+ if (readCall) expr = readCall[1];
1581
+ return isSimpleOpenCall(expr, path9, binding);
1582
+ }
1374
1583
  function analyzeInlineScript(command) {
1375
1584
  const code = extractInlineCode(command);
1376
1585
  if (!code) {
@@ -1834,11 +2043,64 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
1834
2043
  }
1835
2044
  return false;
1836
2045
  }
2046
+ function intentKeywordNegated(text, index) {
2047
+ if (NEGATION_WORDS.length === 0 || index <= 0) return false;
2048
+ const prefix = text.slice(Math.max(0, index - NEGATION_WINDOW), index);
2049
+ return NEGATION_WORDS.some((neg) => prefix.includes(neg));
2050
+ }
2051
+ function isBuildArtifactCleanup(actionDetail) {
2052
+ const text = (actionDetail || "").trim();
2053
+ if (!text) return false;
2054
+ let foundRm = false;
2055
+ const targets = [];
2056
+ for (const raw of splitCommandSegments(text)) {
2057
+ const s = raw.trim();
2058
+ if (!s) continue;
2059
+ let parts = s.split(/\s+/);
2060
+ if (parts[0]?.toLowerCase() === "sudo" || parts[0]?.toLowerCase() === "command") {
2061
+ parts = parts.slice(1);
2062
+ }
2063
+ if (!parts.length || parts[0].toLowerCase() !== "rm") continue;
2064
+ foundRm = true;
2065
+ for (const rawTok of parts.slice(1)) {
2066
+ const tok = rawTok.replace(/^['"]+|['"]+$/g, "");
2067
+ if (!tok || tok.startsWith("-")) continue;
2068
+ targets.push(tok);
2069
+ }
2070
+ }
2071
+ if (!foundRm || targets.length === 0) return false;
2072
+ for (const target of targets) {
2073
+ let t = target.replace(/\\/g, "/");
2074
+ if (t.startsWith("/") || t.split("/").includes("..")) return false;
2075
+ while (t.startsWith("./")) t = t.slice(2);
2076
+ if (!t || [".", "*", "?"].includes(t)) return false;
2077
+ if (t.includes("*") || t.includes("?")) {
2078
+ if (!BUILD_ARTIFACT_GLOB_RE.test(t)) return false;
2079
+ continue;
2080
+ }
2081
+ const first = t.split("/")[0].toLowerCase();
2082
+ if (!BUILD_ARTIFACT_NAMES.has(first)) return false;
2083
+ }
2084
+ return true;
2085
+ }
1837
2086
  function intentCategories(text) {
1838
2087
  const t = (text || "").toLowerCase();
1839
2088
  const out = /* @__PURE__ */ new Set();
1840
2089
  for (const [cat, kws] of Object.entries(INTENT_CATEGORIES)) {
1841
- if (kws.some((kw) => t.includes(String(kw).toLowerCase()))) out.add(cat);
2090
+ for (const kw of kws) {
2091
+ const needle = String(kw).toLowerCase();
2092
+ let start = 0;
2093
+ while (true) {
2094
+ const idx = t.indexOf(needle, start);
2095
+ if (idx < 0) break;
2096
+ if (!intentKeywordNegated(t, idx)) {
2097
+ out.add(cat);
2098
+ break;
2099
+ }
2100
+ start = idx + needle.length;
2101
+ }
2102
+ if (out.has(cat)) break;
2103
+ }
1842
2104
  }
1843
2105
  return out;
1844
2106
  }
@@ -1941,6 +2203,52 @@ function checkIntentConsistency(input, agentExt) {
1941
2203
  }
1942
2204
  const actionCat = actionCategory(actionType, aNext.actionDetail, input.osType, extraWriteTools);
1943
2205
  const reasonKey = intentMatrixViolation(intents, actionCat);
2206
+ const isReferencePrompt = REFERENCE_PRIOR_RE.test((promptSession || "").trim().toLowerCase());
2207
+ if (reasonKey === "read->overwrite" && !EXPLICIT_READONLY_RE.test(intentText) && !isReferencePrompt) {
2208
+ console.debug(
2209
+ `[intent] \u8BFB\u610F\u56FE + \u8986\u76D6\u52A8\u4F5C\uFF0C\u7F3A\u5C11\u660E\u786E\u53EA\u8BFB\u7EA6\u675F\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
2210
+ );
2211
+ return {
2212
+ allowed: true,
2213
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
2214
+ riskLevel: "low",
2215
+ riskType: "",
2216
+ confidence: 50,
2217
+ source: "logic_rule",
2218
+ violatedLayers: [],
2219
+ l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u51FA\u73B0\u8BFB\u610F\u56FE\u8BCD\uFF0C\u4F46\u5F53\u524D\u52A8\u4F5C\u662F\u8986\u76D6\u5199\uFF0Cprompt \u6CA1\u6709\u660E\u786E\u201C\u53EA\u8BFB/\u4E0D\u8981\u4FEE\u6539\u201D\u7EA6\u675F\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
2220
+ };
2221
+ }
2222
+ if ((reasonKey === "read->delete" || reasonKey === "write->delete") && UPDATE_INTENT_RE.test(intentText) && !EXPLICIT_NO_DELETE_RE.test(intentText)) {
2223
+ console.debug(
2224
+ `[intent] \u66F4\u65B0\u7C7B\u610F\u56FE + \u5220\u9664\u52A8\u4F5C\uFF0C\u53EF\u80FD\u5305\u542B\u66FF\u6362\u6D41\u7A0B\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
2225
+ );
2226
+ return {
2227
+ allowed: true,
2228
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
2229
+ riskLevel: "low",
2230
+ riskType: "",
2231
+ confidence: 50,
2232
+ source: "logic_rule",
2233
+ violatedLayers: [],
2234
+ l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u51FA\u73B0\u66F4\u65B0/\u4FEE\u6539\u7C7B\u610F\u56FE\uFF0C\u4F46\u5F53\u524D\u52A8\u4F5C\u662F\u5220\u9664\uFF0C\u53EF\u80FD\u662F\u5148\u5220\u65E7\u518D\u5199\u65B0\u7684\u66FF\u6362\u6D41\u7A0B\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
2235
+ };
2236
+ }
2237
+ if ((reasonKey === "read->delete" || reasonKey === "write->delete") && !isReferencePrompt && INTENT_AMBIGUITY_RE.test(intentText)) {
2238
+ console.debug(
2239
+ `[intent] \u610F\u56FE\u8BCD\u5B58\u5728\u6B67\u4E49\u4E0A\u4E0B\u6587\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
2240
+ );
2241
+ return {
2242
+ allowed: true,
2243
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
2244
+ riskLevel: "low",
2245
+ riskType: "",
2246
+ confidence: 50,
2247
+ source: "logic_rule",
2248
+ violatedLayers: [],
2249
+ l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u610F\u56FE\u8BCD\u51FA\u73B0\u5728\u53EF\u80FD\u6539\u53D8\u542B\u4E49\u7684\u4E0A\u4E0B\u6587\uFF08\u5904\u7406/\u6761\u4EF6/\u793A\u4F8B/\u6309\u94AE/\u6307\u4EE3\u7B49\uFF09\u4E2D\uFF0C\u4E0D\u80FD\u4EC5\u51ED\u5173\u952E\u8BCD\u5224\u504F\u79BB\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
2250
+ };
2251
+ }
1944
2252
  if (reasonKey !== null) {
1945
2253
  return {
1946
2254
  allowed: false,
@@ -2457,7 +2765,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2457
2765
  violatedLayers: ["L2.1"]
2458
2766
  };
2459
2767
  }
2460
- var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SCRIPT_FILE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
2768
+ var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SCRIPT_FILE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, NEGATION_WORDS, NEGATION_WINDOW, EXPLICIT_READONLY_RE, UPDATE_INTENT_RE, EXPLICIT_NO_DELETE_RE, INTENT_AMBIGUITY_RE, BUILD_ARTIFACT_NAMES, BUILD_ARTIFACT_GLOB_RE, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
2461
2769
  var init_logic_rules = __esm({
2462
2770
  "src/engine/logic-rules.ts"() {
2463
2771
  "use strict";
@@ -2559,6 +2867,31 @@ var init_logic_rules = __esm({
2559
2867
  (INTENT_MATRIX.delete_action_words || []).map((w) => String(w).toLowerCase())
2560
2868
  );
2561
2869
  ALL_INTENT_KEYWORDS = Object.values(INTENT_CATEGORIES).flat();
2870
+ NEGATION_WORDS = (INTENT_MATRIX.negation_words || []).map((w) => String(w).toLowerCase());
2871
+ NEGATION_WINDOW = 8;
2872
+ EXPLICIT_READONLY_RE = /(?:只读|仅读|只看|仅看|只查看|仅查看|只分析|仅分析|只做分析|只查询|仅查询|不要(?:修改|写入|写|改动|动)|禁止(?:修改|写入|写|改动)|不得(?:修改|写入|写|改动)|别(?:修改|写入|写|动)|read[- ]only|do not (?:modify|write|change)|don't (?:modify|write|change))/i;
2873
+ UPDATE_INTENT_RE = /(?:更新|修改|编辑|替换|覆盖|改成|改到|rename|replace|update|modify|edit)/i;
2874
+ EXPLICIT_NO_DELETE_RE = /(?:不要|禁止|不得|别|切勿)\s*(?:删除|删掉|删|移除|remove|delete|rm)/i;
2875
+ INTENT_AMBIGUITY_RE = /(?:处理|整理|优化|调整|清掉|如果|假如|若|或者|还是|看情况|根据|按.{0,6}要求|继续|之前|上次|刚才|顺便|示例|例如|比如|按钮|接口|函数|字段|变量|代码里|可能|建议|评估|考虑)/i;
2876
+ BUILD_ARTIFACT_NAMES = /* @__PURE__ */ new Set([
2877
+ "build",
2878
+ "dist",
2879
+ "target",
2880
+ "out",
2881
+ "tmp",
2882
+ "temp",
2883
+ "cache",
2884
+ ".cache",
2885
+ "__pycache__",
2886
+ ".pytest_cache",
2887
+ ".mypy_cache",
2888
+ ".tox",
2889
+ "node_modules",
2890
+ "coverage",
2891
+ ".coverage",
2892
+ "htmlcov"
2893
+ ]);
2894
+ BUILD_ARTIFACT_GLOB_RE = /^\*\.(?:pyc|pyo|class|o|obj|d|egg-info)$/i;
2562
2895
  REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
2563
2896
  REFERENCE_LOOKBACK = 3;
2564
2897
  EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
@@ -4242,6 +4575,7 @@ __export(config_exports, {
4242
4575
  getAgentMossSetting: () => getAgentMossSetting,
4243
4576
  getCacheOptions: () => getCacheOptions,
4244
4577
  getCustomRules: () => getCustomRules,
4578
+ getDeployRole: () => getDeployRole,
4245
4579
  getLLMConfig: () => getLLMConfig,
4246
4580
  getLLMFailMode: () => getLLMFailMode,
4247
4581
  getProviderHeaders: () => getProviderHeaders,
@@ -4424,6 +4758,10 @@ function getLLMFailMode() {
4424
4758
  const val = (process.env.AGENT_MOSS_LLM_FAIL_MODE || "fail_open").toLowerCase();
4425
4759
  return val === "fail_closed" ? "fail_closed" : "fail_open";
4426
4760
  }
4761
+ function getDeployRole() {
4762
+ const val = String(process.env.AGENT_MOSS_DEPLOY_ROLE || "standalone").trim().toLowerCase();
4763
+ return val === "host" || val === "sandbox" ? val : "standalone";
4764
+ }
4427
4765
  function detectProvider(baseUrl, providerHint = "") {
4428
4766
  if (providerHint) {
4429
4767
  const hint = providerHint.toLowerCase();
@@ -4811,6 +5149,21 @@ function detectLanguage(path9, content) {
4811
5149
  }
4812
5150
  return "other";
4813
5151
  }
5152
+ function isInstructionTarget(path9) {
5153
+ const p = (path9 || "").replace(/\\/g, "/").toLowerCase();
5154
+ if (!p) return false;
5155
+ const base = p.split("/").pop() || "";
5156
+ if (["agents.md", "claude.md", "system.md", "prompt.md", "instructions.md", ".cursorrules"].includes(base)) {
5157
+ return true;
5158
+ }
5159
+ if (/(?:^|[-_.])(?:prompt|instruction|system)(?:[-_.]|$)/.test(base)) return true;
5160
+ return INSTRUCTION_TARGET_RE.test(p);
5161
+ }
5162
+ function isDataDocument(actionType, actionDetailRaw) {
5163
+ const payload = extractWritePayload(actionType, actionDetailRaw);
5164
+ if (payload === null) return false;
5165
+ return detectLanguage(payload.path, payload.content) === "data" && !isInstructionTarget(payload.path);
5166
+ }
4814
5167
  function stripShellComments(text) {
4815
5168
  const out = [];
4816
5169
  let heredocEnd = null;
@@ -4973,7 +5326,7 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
4973
5326
  }
4974
5327
  return snippets;
4975
5328
  }
4976
- var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE, HEREDOC_START_RE;
5329
+ var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE, INSTRUCTION_TARGET_RE, HEREDOC_START_RE;
4977
5330
  var init_written_content_analyzer = __esm({
4978
5331
  "src/engine/written-content-analyzer.ts"() {
4979
5332
  "use strict";
@@ -4996,7 +5349,12 @@ var init_written_content_analyzer = __esm({
4996
5349
  "file_edit",
4997
5350
  "editfile",
4998
5351
  "searchreplace",
4999
- "search_replace"
5352
+ "search_replace",
5353
+ // 通用 workspace 工具名(ClawPartner/QwenPaw 等宿主常用)
5354
+ "workspace_write_file",
5355
+ "workspace_edit_file",
5356
+ "workspace_writefile",
5357
+ "workspace_editfile"
5000
5358
  ]);
5001
5359
  WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
5002
5360
  APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
@@ -5005,11 +5363,13 @@ var init_written_content_analyzer = __esm({
5005
5363
  INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
5006
5364
  QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
5007
5365
  PY_DANGEROUS_CALL_RE = /(?:os\.(?:system|popen|remove|unlink|rmdir|chmod|chown|kill|spawn\w*)|subprocess\.\w+|pty\.\w+|ctypes\.\w+|eval|exec|compile|__import__|shutil\.(?:rmtree|move|copy\w*))\s*\(/g;
5366
+ INSTRUCTION_TARGET_RE = /(?:^|[/\\])(?:prompts?|instructions?|skills?|memories|memory|config|policies|policy|\.claude|\.cursor)(?:[/\\]|$)|(?:^|[/\\])(?:AGENTS?|CLAUDE|SYSTEM|PROMPT|INSTRUCTIONS?)(?:\.[^/\\]+)?$|(?:^|[/\\])\.cursorrules$/i;
5008
5367
  HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
5009
5368
  }
5010
5369
  });
5011
5370
 
5012
5371
  // src/engine/heuristic.ts
5372
+ import { posix } from "path";
5013
5373
  function _effectiveDangerousPatterns(osType) {
5014
5374
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
5015
5375
  }
@@ -5037,6 +5397,112 @@ function normalizeShellObfuscation(text) {
5037
5397
  t = t.replace(/\$\{IFS\}|\$IFS/gi, " ");
5038
5398
  return t;
5039
5399
  }
5400
+ function shlexSplitLite(s) {
5401
+ const out = [];
5402
+ let cur = "";
5403
+ let quote = null;
5404
+ let quoted = false;
5405
+ for (let i = 0; i < s.length; i++) {
5406
+ const ch = s[i];
5407
+ if (quote) {
5408
+ if (ch === quote) quote = null;
5409
+ else if (ch === "\\" && quote === '"' && i + 1 < s.length) cur += s[++i];
5410
+ else cur += ch;
5411
+ continue;
5412
+ }
5413
+ if (ch === "'" || ch === '"') {
5414
+ quote = ch;
5415
+ quoted = true;
5416
+ continue;
5417
+ }
5418
+ if (/\s/.test(ch)) {
5419
+ if (cur || quoted) {
5420
+ out.push(cur);
5421
+ cur = "";
5422
+ quoted = false;
5423
+ }
5424
+ continue;
5425
+ }
5426
+ if (ch === "\\" && i + 1 < s.length) {
5427
+ cur += s[++i];
5428
+ continue;
5429
+ }
5430
+ cur += ch;
5431
+ }
5432
+ if (cur || quoted) out.push(cur);
5433
+ return out;
5434
+ }
5435
+ function rmExpandVars(token, env2) {
5436
+ let current = token;
5437
+ for (let round = 0; round < 3; round++) {
5438
+ const next = current.replace(RM_VAR_RE, (whole, braced, bare) => {
5439
+ const name = String(braced || bare).toLowerCase();
5440
+ return env2.get(name) ?? whole;
5441
+ });
5442
+ if (next === current) break;
5443
+ current = next;
5444
+ }
5445
+ return current;
5446
+ }
5447
+ function rmResolvedDangerous(resolved) {
5448
+ if (resolved === "/" || resolved.startsWith("/.")) return true;
5449
+ const first = resolved.split("/")[1] || "";
5450
+ if (first === "home") {
5451
+ const parts = resolved.split("/").filter(Boolean);
5452
+ return parts.length <= 2;
5453
+ }
5454
+ if (RM_SENSITIVE_FIRST.has(first)) return true;
5455
+ if (first === "var" && !(resolved === "/var/tmp" || resolved.startsWith("/var/tmp/"))) {
5456
+ return true;
5457
+ }
5458
+ return false;
5459
+ }
5460
+ function checkRmResolvedTargets(text) {
5461
+ const env2 = /* @__PURE__ */ new Map();
5462
+ for (let segment of splitCommandSegments2(text)) {
5463
+ if (!segment) continue;
5464
+ while (true) {
5465
+ const m = segment.match(RM_ASSIGN_RE);
5466
+ if (!m) break;
5467
+ let value = m[2].trim();
5468
+ if (value.length >= 2 && value[0] === value[value.length - 1] && (value[0] === "'" || value[0] === '"')) {
5469
+ value = value.slice(1, -1);
5470
+ }
5471
+ env2.set(m[1].toLowerCase(), rmExpandVars(value, env2));
5472
+ segment = segment.slice(m[0].length);
5473
+ }
5474
+ const parts = shlexSplitLite(segment);
5475
+ if (parts.length === 0) continue;
5476
+ let idx = 0;
5477
+ while (idx < parts.length && RM_COMMAND_PREFIXES.has(parts[idx].toLowerCase())) idx++;
5478
+ if (idx >= parts.length) continue;
5479
+ const commandWord = parts[idx].split("/").pop().replace(/^\\/, "").toLowerCase();
5480
+ if (commandWord !== "rm") continue;
5481
+ let optionsDone = false;
5482
+ for (const token of parts.slice(idx + 1)) {
5483
+ if (token === "--") {
5484
+ optionsDone = true;
5485
+ continue;
5486
+ }
5487
+ if (!optionsDone && token.startsWith("-")) continue;
5488
+ const target = rmExpandVars(token, env2);
5489
+ if (!target.startsWith("/")) continue;
5490
+ const resolved = posix.normalize(target);
5491
+ if (rmResolvedDangerous(resolved)) {
5492
+ return {
5493
+ allowed: false,
5494
+ reason: `\u68C0\u6D4B\u5230\u5220\u9664\u6839\u76EE\u5F55/\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55\uFF08\u89E3\u6790\u540E\u76EE\u6807 ${resolved}\uFF09`,
5495
+ riskLevel: "critical",
5496
+ riskType: "script_execution",
5497
+ confidence: 95,
5498
+ source: "heuristic",
5499
+ violatedLayers: ["L1.1"]
5500
+ };
5501
+ }
5502
+ }
5503
+ }
5504
+ return null;
5505
+ }
5040
5506
  function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
5041
5507
  const scanDetail = normalizePathSegments(stripLiteralTextSegments(actionDetail));
5042
5508
  const scanCommands = String(osType || "").toLowerCase() === "windows" ? [
@@ -5055,16 +5521,19 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
5055
5521
  }
5056
5522
  }
5057
5523
  }
5058
- if (!top) return null;
5059
- return {
5524
+ const toJudgment = (hit) => ({
5060
5525
  allowed: false,
5061
- reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${top.desc}`,
5062
- riskLevel: top.sev,
5063
- riskType: top.type,
5526
+ reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${hit.desc}`,
5527
+ riskLevel: hit.sev,
5528
+ riskType: hit.type,
5064
5529
  confidence: 95,
5065
5530
  source: "heuristic",
5066
5531
  violatedLayers: ["L1.1"]
5067
- };
5532
+ });
5533
+ if (top && severityRank(top.sev) >= severityRank("high")) return toJudgment(top);
5534
+ const rmResolved = checkRmResolvedTargets(scanDetail);
5535
+ if (rmResolved) return rmResolved;
5536
+ return top ? toJudgment(top) : null;
5068
5537
  }
5069
5538
  function allUrlsLoopback(actionDetail) {
5070
5539
  const hosts = actionDetail.match(new RegExp(LOOPBACK_URL_RE.source, "gi"));
@@ -5138,6 +5607,23 @@ function runHeuristicCheck(input) {
5138
5607
  deobfuscated
5139
5608
  );
5140
5609
  }
5610
+ const extraScanDetail = stripSearchPatternLiterals(scanDetail);
5611
+ const extraScanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => {
5612
+ const stripped = stripSearchPatternLiterals(sn);
5613
+ return [`${input.aNext.actionType}: ${stripped}`, stripped];
5614
+ }) : String(input.osType || "").toLowerCase() === "windows" ? [
5615
+ `${input.aNext.actionType}: ${extraScanDetail}`,
5616
+ extraScanDetail,
5617
+ `${input.aNext.actionType}: ${extraScanDetail.replace(/\//g, "\\")}`,
5618
+ extraScanDetail.replace(/\//g, "\\")
5619
+ ] : [`${input.aNext.actionType}: ${extraScanDetail}`, extraScanDetail];
5620
+ const extraDeobfuscated = normalizeShellObfuscation(extraScanDetail);
5621
+ if (extraDeobfuscated !== extraScanDetail) {
5622
+ extraScanCommands.push(
5623
+ `${input.aNext.actionType}: ${extraDeobfuscated}`,
5624
+ extraDeobfuscated
5625
+ );
5626
+ }
5141
5627
  let topRiskType = "";
5142
5628
  const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
5143
5629
  const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
@@ -5162,7 +5648,7 @@ function runHeuristicCheck(input) {
5162
5648
  for (const rule of agentExt.extra_command_patterns) {
5163
5649
  try {
5164
5650
  const re = new RegExp(rule.pattern, "i");
5165
- if (scanCommands.some((c) => re.test(c))) {
5651
+ if (extraScanCommands.some((c) => re.test(c))) {
5166
5652
  matched.push(`agent \u4E13\u5C5E\u89C4\u5219: ${rule.reason}`);
5167
5653
  if (severityRank(rule.risk_level) > severityRank(highestSeverity)) {
5168
5654
  highestSeverity = rule.risk_level;
@@ -5173,7 +5659,7 @@ function runHeuristicCheck(input) {
5173
5659
  }
5174
5660
  }
5175
5661
  }
5176
- const injectionText = isSearchActionType(input.aNext.actionType) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
5662
+ const injectionText = isSearchActionType(input.aNext.actionType) || handledWrite && isDataDocument(input.aNext.actionType, input.aNext.actionDetail) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
5177
5663
  let pythonWalkOnerrorOnly = false;
5178
5664
  if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
5179
5665
  pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
@@ -5199,6 +5685,10 @@ function runHeuristicCheck(input) {
5199
5685
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
5200
5686
  const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
5201
5687
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
5688
+ if (isBashLike && !handledWrite && severityRank(highestSeverity) < severityRank("high") && !mergeResults.some((r) => severityRank(r.riskLevel) >= severityRank("high"))) {
5689
+ const rmResolved = checkRmResolvedTargets(scanDetail);
5690
+ if (rmResolved) mergeResults.push(rmResolved);
5691
+ }
5202
5692
  if (mergeResults.length > 0) {
5203
5693
  let best = mergeResults[0];
5204
5694
  for (const r of mergeResults) {
@@ -5215,6 +5705,9 @@ function runHeuristicCheck(input) {
5215
5705
  violatedLayers: ["L1.1"]
5216
5706
  };
5217
5707
  }
5708
+ if (best !== pathResult && pathResult?.deniedReadPath && best.riskType === "file_access" && best.riskLevel === pathResult.riskLevel) {
5709
+ best = { ...best, deniedReadPath: pathResult.deniedReadPath };
5710
+ }
5218
5711
  return best;
5219
5712
  }
5220
5713
  if (matched.length > 0) {
@@ -5417,16 +5910,83 @@ function splitCommandSegments2(actionDetail) {
5417
5910
  if (start < actionDetail.length) segments.push(actionDetail.slice(start));
5418
5911
  return segments;
5419
5912
  }
5913
+ function shellTokens(seg) {
5914
+ const tokens = [];
5915
+ let cur = "";
5916
+ let quote = "";
5917
+ for (let i = 0; i < seg.length; i++) {
5918
+ const ch = seg[i];
5919
+ if (quote) {
5920
+ if (ch === quote) quote = "";
5921
+ else cur += ch;
5922
+ continue;
5923
+ }
5924
+ if (ch === '"' || ch === "'") {
5925
+ quote = ch;
5926
+ continue;
5927
+ }
5928
+ if (/\s/.test(ch)) {
5929
+ if (cur) {
5930
+ tokens.push(cur);
5931
+ cur = "";
5932
+ }
5933
+ continue;
5934
+ }
5935
+ cur += ch;
5936
+ }
5937
+ if (quote) return null;
5938
+ if (cur) tokens.push(cur);
5939
+ return tokens;
5940
+ }
5941
+ function stripSearchPatternArgument(seg) {
5942
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) return seg;
5943
+ const tokens = shellTokens(seg);
5944
+ if (!tokens || tokens.length === 0) return seg;
5945
+ let idx = 0;
5946
+ while (idx < tokens.length && COMMAND_PREFIX_WORDS.has(tokens[idx])) idx++;
5947
+ if (idx >= tokens.length || !TEXT_SEARCH_COMMANDS.has(tokens[idx])) return seg;
5948
+ let patternIdx = null;
5949
+ let i = idx + 1;
5950
+ while (i < tokens.length) {
5951
+ const token = tokens[i];
5952
+ if (token === "--") {
5953
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
5954
+ break;
5955
+ }
5956
+ if (token === "-e" || token === "--regexp") {
5957
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
5958
+ break;
5959
+ }
5960
+ if (token.startsWith("--regexp=")) {
5961
+ patternIdx = i;
5962
+ break;
5963
+ }
5964
+ if (token === "-f" || token === "--file" || token.startsWith("--file=")) break;
5965
+ if (token.startsWith("-") && token !== "-") {
5966
+ i += SEARCH_OPTION_WITH_ARG.has(token) ? 2 : 1;
5967
+ continue;
5968
+ }
5969
+ patternIdx = i;
5970
+ break;
5971
+ }
5972
+ if (patternIdx === null || patternIdx >= tokens.length) return seg;
5973
+ tokens.splice(patternIdx, 1);
5974
+ return tokens.map((t) => /\s/.test(t) ? `'${t.replaceAll("'", "'\\''")}'` : t).join(" ");
5975
+ }
5420
5976
  function stripSearchPatternLiterals(actionDetail) {
5421
5977
  const parts = [];
5422
5978
  for (const seg of splitCommandSegments2(actionDetail)) {
5979
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) {
5980
+ parts.push(seg);
5981
+ continue;
5982
+ }
5423
5983
  const low = seg.trim().toLowerCase();
5424
5984
  const words = low.length ? low.split(/\s+/) : [];
5425
5985
  let idx = 0;
5426
5986
  while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
5427
5987
  const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
5428
5988
  if (isSearch && !low.includes("--pre")) {
5429
- parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
5989
+ parts.push(stripSearchPatternArgument(seg));
5430
5990
  } else {
5431
5991
  parts.push(seg);
5432
5992
  }
@@ -5474,7 +6034,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5474
6034
  riskType: "file_access",
5475
6035
  confidence: 90,
5476
6036
  source: "heuristic",
5477
- violatedLayers: ["L1.1"]
6037
+ violatedLayers: ["L1.1"],
6038
+ deniedReadPath: sp.path
5478
6039
  };
5479
6040
  }
5480
6041
  const denyMode = sp.denyMode || (sp.credential ? "deny_both" : sp.readOnly ? "deny_read" : "deny_write");
@@ -5488,7 +6049,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5488
6049
  confidence: 90,
5489
6050
  source: "heuristic",
5490
6051
  violatedLayers: ["L1.1"],
5491
- isCredential: !!sp.credential
6052
+ isCredential: !!sp.credential,
6053
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5492
6054
  };
5493
6055
  }
5494
6056
  }
@@ -5545,7 +6107,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5545
6107
  confidence: 90,
5546
6108
  source: "heuristic",
5547
6109
  violatedLayers: ["L1.1"],
5548
- isCredential: !!sp.credential
6110
+ isCredential: !!sp.credential,
6111
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5549
6112
  };
5550
6113
  }
5551
6114
  }
@@ -5568,7 +6131,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5568
6131
  confidence: 90,
5569
6132
  source: "heuristic",
5570
6133
  violatedLayers: ["L1.1"],
5571
- isCredential: !!sp.credential
6134
+ isCredential: !!sp.credential,
6135
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5572
6136
  };
5573
6137
  }
5574
6138
  }
@@ -5585,7 +6149,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5585
6149
  confidence: 90,
5586
6150
  source: "heuristic",
5587
6151
  violatedLayers: ["L1.1"],
5588
- isCredential: true
6152
+ isCredential: true,
6153
+ deniedReadPath: cp.path
5589
6154
  };
5590
6155
  }
5591
6156
  }
@@ -5746,7 +6311,7 @@ function checkDangerousPatterns(actionType, actionDetail) {
5746
6311
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
5747
6312
  const wildcardDeleteRe = /(?:\brm\b|\b(r?mdir|del|delete|remove|rmdir|unlink)\b|\b删除\b|\b移除\b)[\s\S]{0,40}?[*?]|[*?][\s\S]{0,40}?\b(?:rm|del|delete|remove|rmdir|unlink)\b|rm\s+-[a-zA-Z]*[rf][a-zA-Z]*\s+\S*[*?]/i;
5748
6313
  const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
5749
- if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
6314
+ if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
5750
6315
  return {
5751
6316
  allowed: false,
5752
6317
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -5888,7 +6453,7 @@ function checkLateralMovement(actionDetail) {
5888
6453
  }
5889
6454
  return null;
5890
6455
  }
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;
6456
+ var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SEARCH_OPTION_WITH_ARG, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
5892
6457
  var init_heuristic = __esm({
5893
6458
  "src/engine/heuristic.ts"() {
5894
6459
  "use strict";
@@ -5914,6 +6479,10 @@ var init_heuristic = __esm({
5914
6479
  DANGEROUS_PATTERNS_WINDOWS = _loadDangerousPatterns("windows");
5915
6480
  DANGEROUS_PATTERNS_MACOS = _loadDangerousPatterns("macos");
5916
6481
  DANGEROUS_PATTERNS_HARMONY = _loadDangerousPatterns("harmony");
6482
+ RM_ASSIGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|]+)\s*/;
6483
+ RM_VAR_RE = /\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;
6484
+ RM_COMMAND_PREFIXES = /* @__PURE__ */ new Set(["sudo", "env", "command", "builtin", "exec", "nohup", "time"]);
6485
+ RM_SENSITIVE_FIRST = /* @__PURE__ */ new Set(["etc", "usr", "boot", "root", "opt", "srv", "sys", "proc", "home"]);
5917
6486
  LOOPBACK_URL_RE = /https?:\/\/([^\/\s;'"|&)]+)/i;
5918
6487
  HEURISTIC_RULES = loadHeuristicRules();
5919
6488
  LOOPBACK_HOSTS = new Set(HEURISTIC_RULES.loopback_hosts ?? []);
@@ -5933,6 +6502,28 @@ var init_heuristic = __esm({
5933
6502
  COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
5934
6503
  TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
5935
6504
  COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
6505
+ SEARCH_OPTION_WITH_ARG = /* @__PURE__ */ new Set([
6506
+ "-m",
6507
+ "--max-count",
6508
+ "-A",
6509
+ "--after-context",
6510
+ "-B",
6511
+ "--before-context",
6512
+ "-C",
6513
+ "--context",
6514
+ "-d",
6515
+ "--directories",
6516
+ "-D",
6517
+ "--devices",
6518
+ "--include",
6519
+ "--exclude",
6520
+ "--exclude-dir",
6521
+ "--glob",
6522
+ "--iglob",
6523
+ "--type",
6524
+ "--type-add",
6525
+ "--type-not"
6526
+ ]);
5936
6527
  SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
5937
6528
  SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
5938
6529
  SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
@@ -8834,6 +9425,9 @@ async function runLLMAnalysis(input, previous) {
8834
9425
  scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
8835
9426
  }
8836
9427
  const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
9428
+ const budgetMode = getAgentMossSetting("AGENT_MOSS_LLM_BUDGET_MODE", "hard").trim().toLowerCase() === "soft" ? "soft" : "hard";
9429
+ const budgetActive = maxPromptTokens > 0;
9430
+ const tokenLimit = budgetActive && budgetMode === "hard" ? Math.floor(maxPromptTokens * 100 / 115) : maxPromptTokens;
8837
9431
  let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
8838
9432
  let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
8839
9433
  let prompt = "";
@@ -8850,13 +9444,14 @@ async function runLLMAnalysis(input, previous) {
8850
9444
  historyMaxItems,
8851
9445
  historyMaxChars
8852
9446
  );
8853
- if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
9447
+ if (!budgetActive || estimateTokens(prompt) <= tokenLimit) break;
8854
9448
  historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
8855
9449
  historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
8856
9450
  }
8857
- if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
9451
+ let budgetCode = "";
9452
+ if (budgetActive && estimateTokens(prompt) > tokenLimit) {
8858
9453
  const estimated = estimateTokens(prompt);
8859
- const ratio = estimated / maxPromptTokens;
9454
+ const ratio = tokenLimit > 0 ? estimated / tokenLimit : Number.POSITIVE_INFINITY;
8860
9455
  const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
8861
9456
  const truncated = truncateDetail(input.aNext.actionDetail, allowed);
8862
9457
  prompt = buildPrompt(
@@ -8872,8 +9467,14 @@ async function runLLMAnalysis(input, previous) {
8872
9467
  historyMaxChars
8873
9468
  );
8874
9469
  console.warn(
8875
- `[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${maxPromptTokens}\uFF09\uFF0C\u5F53\u524D\u52A8\u4F5C\u8BE6\u60C5\u622A\u65AD\u81F3 ${truncated.length} \u5B57\u7B26`
9470
+ `[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${tokenLimit}\uFF09\uFF0C\u5F53\u524D\u52A8\u4F5C\u8BE6\u60C5\u622A\u65AD\u81F3 ${truncated.length} \u5B57\u7B26`
8876
9471
  );
9472
+ if (estimateTokens(prompt) > tokenLimit) {
9473
+ if (budgetMode === "hard") {
9474
+ throw new LLMPromptBudgetExceeded("l3_budget_unreachable");
9475
+ }
9476
+ budgetCode = "l3_budget_unreachable";
9477
+ }
8877
9478
  }
8878
9479
  logPrompt(prompt, input.aNext, previous.llmLogPath);
8879
9480
  traceFull("l3.prompt", {
@@ -8886,6 +9487,7 @@ async function runLLMAnalysis(input, previous) {
8886
9487
  prompt_chars: prompt.length
8887
9488
  });
8888
9489
  const result = await analyzeWithLLM(prompt, config);
9490
+ if (budgetCode) result.degraded = [...result.degraded || [], budgetCode];
8889
9491
  traceSummary("l3.verdict", {
8890
9492
  allowed: result.allowed,
8891
9493
  risk_level: result.riskLevel,
@@ -8959,11 +9561,14 @@ function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis,
8959
9561
  const skillsText = formatSkillsForPrompt(matchedSkills);
8960
9562
  const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
8961
9563
  const promptHistoryText = formatPromptHistory(input.promptHistory);
9564
+ const historyAuthorization = /(因历史窗口上限省略|本段因长度上限已截断)/.test(promptHistoryText) ? `
9565
+
9566
+ ${HISTORY_AUTHORIZATION}` : "";
8962
9567
  const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
8963
9568
  const hintsText = formatHints(previous);
8964
9569
  const securityJudgeTemplate = templates["security_judge"];
8965
9570
  if (securityJudgeTemplate) {
8966
- return securityJudgeTemplate.replaceAll("{prompt_session}", input.promptSession || "\uFF08\u672A\u63D0\u4F9B\uFF09").replaceAll("{prompt_history_text}", promptHistoryText).replaceAll("{action_history}", historyStr).replaceAll("{action_type}", input.aNext.actionType).replaceAll("{action_detail}", input.aNext.actionDetail).replaceAll("{reason}", input.reason || "\u672A\u8BF4\u660E").replaceAll("{skills_text}", skillsText).replaceAll("{hints_text}", hintsText).replaceAll("{script_analysis_text}", scriptAnalysisText).replaceAll("{skip_l3_hints}", skipL3Hints).replaceAll("{path_context}", pathContext || "\uFF08\u672C\u547D\u4EE4\u65E0\u4E3B\u76EE\u5F55\u76F8\u5173\u8DEF\u5F84\u6BB5\uFF0C\u4E0D\u9002\u7528\uFF09").replaceAll("{{", "{").replaceAll("}}", "}");
9571
+ return securityJudgeTemplate.replaceAll("{prompt_session}", input.promptSession || "\uFF08\u672A\u63D0\u4F9B\uFF09").replaceAll("{prompt_history_text}", promptHistoryText).replaceAll("{history_authorization}", historyAuthorization).replaceAll("{action_history}", historyStr).replaceAll("{action_type}", input.aNext.actionType).replaceAll("{action_detail}", input.aNext.actionDetail).replaceAll("{reason}", input.reason || "\u672A\u8BF4\u660E").replaceAll("{skills_text}", skillsText).replaceAll("{hints_text}", hintsText).replaceAll("{script_analysis_text}", scriptAnalysisText).replaceAll("{skip_l3_hints}", skipL3Hints).replaceAll("{path_context}", pathContext || "\uFF08\u672C\u547D\u4EE4\u65E0\u4E3B\u76EE\u5F55\u76F8\u5173\u8DEF\u5F84\u6BB5\uFF0C\u4E0D\u9002\u7528\uFF09").replaceAll("{{", "{").replaceAll("}}", "}");
8967
9572
  }
8968
9573
  console.warn("[AgentMoss] security_judge template missing, using sparse fallback prompt");
8969
9574
  return `## \u5F53\u524D\u64CD\u4F5C\u4E0A\u4E0B\u6587
@@ -8993,25 +9598,34 @@ ${scriptAnalysisText}` : ""}
8993
9598
  \u8F93\u51FA\u683C\u5F0F:
8994
9599
  {"allowed": true/false, "reason": "\u5224\u65AD\u7406\u7531", "riskLevel": "low|medium|high|critical", "riskType": "\u98CE\u9669\u7C7B\u578B", "confidence": 0-100}`;
8995
9600
  }
8996
- function formatPromptHistory(promptHistory, maxTextChars = 500) {
9601
+ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNumSetting("AGENT_MOSS_LLM_PROMPT_HISTORY_MAX_TURNS", 20)) {
8997
9602
  if (!promptHistory || promptHistory.length === 0) {
8998
9603
  return "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
8999
9604
  }
9605
+ const limit = Math.max(0, Math.floor(maxTurns));
9606
+ const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
9607
+ let omitted = 0;
9000
9608
  const lines = [];
9001
9609
  for (let i = 0; i < promptHistory.length; i++) {
9002
9610
  const turn = promptHistory[i];
9003
9611
  const text = (typeof turn === "string" ? turn : turn?.text || "").trim();
9004
- if (!text) continue;
9005
- let line = ` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${text.slice(0, maxTextChars)}`;
9006
9612
  const actions = typeof turn === "string" ? void 0 : turn?.actions;
9007
- if (actions && actions.length > 0) {
9008
- const types = actions.map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
9009
- if (types.length > 0) {
9010
- line += ` \u2192 \u52A8\u4F5C: ${types.join(", ")}`;
9011
- }
9613
+ const types = (actions || []).map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
9614
+ if (!text && types.length === 0) continue;
9615
+ if (i < firstTurnIndex) {
9616
+ omitted += 1;
9617
+ continue;
9618
+ }
9619
+ if (!text) {
9620
+ lines.push(` \u7B2C${i + 1}\u8F6E\u52A8\u4F5C: ${types.join(", ")}`);
9621
+ continue;
9012
9622
  }
9013
- lines.push(line);
9623
+ let shown = text.slice(0, maxTextChars);
9624
+ if (shown.length < text.length) shown += "\uFF08\u672C\u6BB5\u56E0\u957F\u5EA6\u4E0A\u9650\u5DF2\u622A\u65AD\uFF09";
9625
+ const suffix = types.length > 0 ? ` \u2192 \u52A8\u4F5C: ${types.join(", ")}` : "";
9626
+ lines.push(` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${shown}${suffix}`);
9014
9627
  }
9628
+ if (omitted) lines.unshift(`\uFF08\u56E0\u5386\u53F2\u7A97\u53E3\u4E0A\u9650\u7701\u7565 ${omitted} \u8F6E\u66F4\u65E9\u5386\u53F2\u610F\u56FE\uFF09`);
9015
9629
  return lines.length > 0 ? lines.join("\n") : "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
9016
9630
  }
9017
9631
  function formatHints(previous) {
@@ -9024,11 +9638,15 @@ function formatHints(previous) {
9024
9638
  );
9025
9639
  }
9026
9640
  if (previous.logic) {
9027
- hints.push(
9028
- `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
9641
+ if (previous.logic.l3Hint) {
9642
+ hints.push(`\u2139\uFE0F ${previous.logic.l3Hint}`);
9643
+ } else {
9644
+ hints.push(
9645
+ `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
9029
9646
  \u7C7B\u578B: ${previous.logic.riskType}
9030
9647
  \u539F\u56E0: ${previous.logic.reason}`
9031
- );
9648
+ );
9649
+ }
9032
9650
  }
9033
9651
  return hints.length > 0 ? hints.join("\n\n") : "\u7279\u5F81\u5339\u914D\u68C0\u6D4B\u548C\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u5747\u672A\u53D1\u73B0\u98CE\u9669\u3002";
9034
9652
  }
@@ -9240,7 +9858,7 @@ async function analyzeWithLLM(prompt, config) {
9240
9858
  clearTimeout(totalTimeoutTimer);
9241
9859
  throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
9242
9860
  }
9243
- var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
9861
+ var LLMPromptBudgetExceeded, HISTORY_AUTHORIZATION, LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
9244
9862
  var init_llm_analyzer = __esm({
9245
9863
  "src/engine/llm-analyzer.ts"() {
9246
9864
  "use strict";
@@ -9254,6 +9872,15 @@ var init_llm_analyzer = __esm({
9254
9872
  init_trace_log();
9255
9873
  init_metrics();
9256
9874
  init_circuit_breaker();
9875
+ LLMPromptBudgetExceeded = class extends Error {
9876
+ code;
9877
+ constructor(code) {
9878
+ super(code);
9879
+ this.name = "LLMPromptBudgetExceeded";
9880
+ this.code = code;
9881
+ }
9882
+ };
9883
+ HISTORY_AUTHORIZATION = "\u88AB\u7701\u7565\u6216\u88AB\u622A\u65AD\u7684\u5386\u53F2\u4E0D\u80FD\u4F5C\u4E3A\u6388\u6743\u4F9D\u636E\u3002\n\u201C\u7EE7\u7EED\u201D\u53EA\u6307\u4EE3\u53EF\u89C1\u7684\u524D\u6587\uFF1B\u5982\u679C\u53EF\u89C1\u524D\u6587\u4E0D\u8DB3\u4EE5\u786E\u8BA4\u6307\u4EE3\u76EE\u6807\u6216\u6388\u6743\u8303\u56F4\uFF0C\u5E94\u5728 reason \u4E2D\u8BF4\u660E\u4F9D\u636E\u4E0D\u8DB3\uFF0C\u5E76\u6309\u6700\u5C0F\u6743\u9650\u539F\u5219\u5224\u65AD\u9700\u8981\u8BE5\u6388\u6743\u7684\u52A8\u4F5C\u3002\n\u5F53\u524D\u7528\u6237\u8BF7\u6C42\u4E2D\u660E\u786E\u5199\u51FA\u7684\u6388\u6743\u4ECD\u7136\u6709\u6548\uFF0C\u6309\u5176\u53EF\u89C1\u7684\u76EE\u6807\u548C\u9650\u5236\u5224\u65AD\u3002";
9257
9884
  LLMCircuitOpenError = class extends Error {
9258
9885
  constructor(message) {
9259
9886
  super(message);
@@ -10431,11 +11058,35 @@ function checkMCRules(graph) {
10431
11058
  for (const rule of rules) {
10432
11059
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
10433
11060
  if (ruleViolates(rule, trace2, witnessMode)) {
11061
+ const pathNodes = nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3);
11062
+ const path9 = pathNodes.map((n) => ({
11063
+ sessionId: n.sessionId,
11064
+ seq: n.seq,
11065
+ detail: n.actionDetail.slice(0, 60)
11066
+ }));
10434
11067
  violations.push({
10435
11068
  propertyId: String(rule.id || "mc-ltl"),
10436
11069
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
10437
11070
  riskLevel: String(rule.risk_level || "high"),
10438
- path: nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3).map((n) => ({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }))
11071
+ path: path9,
11072
+ graph: {
11073
+ property_id: String(rule.id || "mc-ltl"),
11074
+ property_short: "P6",
11075
+ property_name: "LTL \u6A21\u578B\u68C0\u6D4B",
11076
+ nodes: pathNodes.map((n) => ({
11077
+ session_id: n.sessionId,
11078
+ seq: n.seq,
11079
+ stage: n.stage,
11080
+ action_detail: n.actionDetail,
11081
+ resources: [...n.resources].sort(),
11082
+ instance_id: n.instanceId || ""
11083
+ })),
11084
+ edges: pathNodes.slice(1).map((_, i) => ({
11085
+ from: i,
11086
+ to: i + 1,
11087
+ type: "next"
11088
+ }))
11089
+ }
10439
11090
  });
10440
11091
  if (witnessMode) return violations;
10441
11092
  }
@@ -11135,11 +11786,17 @@ function checkLowIntegrityCommandExec(graph) {
11135
11786
  for (const i of candidates) {
11136
11787
  const n = nodes[i];
11137
11788
  if (lowAt.has(i) && isComputeNode(n)) {
11789
+ const path9 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11138
11790
  violations.push({
11139
11791
  propertyId: "low-integrity-command-exec",
11140
11792
  reason: `\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u63A7\u5236\u547D\u4EE4\u6267\u884C\uFF1A${lowAt.get(i)} \u2192 ${n.sessionId}#${n.seq} \u6267\u884C\u4E0D\u53EF\u4FE1\u5185\u5BB9`,
11141
11793
  riskLevel: "critical",
11142
- path: [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }]
11794
+ path: path9,
11795
+ graph: graphFromPath(nodes, path9, "next", {
11796
+ property_id: "low-integrity-command-exec",
11797
+ property_short: "P7",
11798
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u547D\u4EE4\u6267\u884C"
11799
+ }, ["sink"])
11143
11800
  });
11144
11801
  if (witness !== void 0) return violations;
11145
11802
  }
@@ -11181,11 +11838,21 @@ function checkCrossSessionReachability(graph) {
11181
11838
  if (reached.has(i)) {
11182
11839
  const srcIdx = Math.min(...sources);
11183
11840
  const srcDesc = nodes[srcIdx].actionDetail.slice(0, 40);
11841
+ const path9 = nodes.slice(-3).map((m) => ({
11842
+ sessionId: m.sessionId,
11843
+ seq: m.seq,
11844
+ detail: m.actionDetail.slice(0, 60)
11845
+ }));
11184
11846
  violations.push({
11185
11847
  propertyId: "low-integrity-reachability",
11186
11848
  reason: `\u4F4E\u5B8C\u6574\u6027\u6E90\u7ECF\u8DE8 session \u6570\u636E\u94FE\u591A\u8DF3\u5230\u8FBE\u5F53\u524D\u6267\u884C\uFF08\u6E90: ${srcDesc} \u2192 ${n.sessionId}#${n.seq}\uFF09`,
11187
11849
  riskLevel: "high",
11188
- path: nodes.slice(-3).map((m) => ({ sessionId: m.sessionId, seq: m.seq, detail: m.actionDetail.slice(0, 60) }))
11850
+ path: path9,
11851
+ graph: graphFromPath(nodes, path9, "data", {
11852
+ property_id: "low-integrity-reachability",
11853
+ property_short: "P3",
11854
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u6D41\u53EF\u8FBE"
11855
+ })
11189
11856
  });
11190
11857
  if (witness !== void 0) return violations;
11191
11858
  }
@@ -11355,6 +12022,7 @@ var init_engine = __esm({
11355
12022
  });
11356
12023
 
11357
12024
  // src/engine/formal-engine/stateful.ts
12025
+ import { createHash as createHash4 } from "crypto";
11358
12026
  import * as fs5 from "fs";
11359
12027
  import * as os3 from "os";
11360
12028
  import * as path6 from "path";
@@ -11495,7 +12163,53 @@ function cleanupChainArchives(dir, maxBytes = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_
11495
12163
  }
11496
12164
  return { deleted: removed, files: remainFiles, bytes: remainBytes };
11497
12165
  }
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;
12166
+ function canonicalActionType(actionType) {
12167
+ const low = String(actionType || "").trim().toLowerCase();
12168
+ return SHELL_ACTION_ALIASES[low] || low;
12169
+ }
12170
+ function canonicalDetail(actionDetail) {
12171
+ const detail = String(actionDetail || "");
12172
+ const m = TRUNCATED_DETAIL_RE.exec(detail);
12173
+ const digest = m ? m[1] : createHash4("sha256").update(detail).digest("hex").slice(0, 16);
12174
+ return `sha256:${digest}`;
12175
+ }
12176
+ function canonicalCalledAt(calledAt) {
12177
+ const value = String(calledAt || "").trim();
12178
+ if (!value) return "";
12179
+ let normalized = value;
12180
+ if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?$/.test(normalized)) {
12181
+ normalized = normalized.replace(" ", "T") + "Z";
12182
+ }
12183
+ const ms = Date.parse(normalized);
12184
+ return Number.isFinite(ms) ? String(Math.floor(ms / 1e3)) : value;
12185
+ }
12186
+ function fingerprint(sessionId, actionType, actionDetail, calledAt) {
12187
+ const raw = [
12188
+ String(sessionId),
12189
+ canonicalActionType(actionType),
12190
+ canonicalDetail(actionDetail),
12191
+ canonicalCalledAt(calledAt)
12192
+ ].join("\0");
12193
+ return createHash4("blake2b512").update(raw).digest("hex").slice(0, 16);
12194
+ }
12195
+ function gateOrder(action) {
12196
+ const callId = String(action?.gateCallId ?? "");
12197
+ const callTimeUs = Number(action?.gateCallTimeUs ?? 0);
12198
+ return callId && Number.isFinite(callTimeUs) && callTimeUs > 0 ? { callId, callTimeUs } : null;
12199
+ }
12200
+ function gateFingerprint(action, isError, agentId, instanceId, order) {
12201
+ const values = [
12202
+ String(action?.actionType ?? ""),
12203
+ String(action?.actionDetail ?? ""),
12204
+ String(action?.calledAt ?? ""),
12205
+ String(action?.agentId ?? agentId ?? ""),
12206
+ String(action?.instanceId ?? instanceId ?? ""),
12207
+ Boolean(isError),
12208
+ order.callTimeUs
12209
+ ];
12210
+ return createHash4("sha256").update(JSON.stringify(values)).digest("hex");
12211
+ }
12212
+ var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, StatefulAnalysisUnavailable, UnconfirmedGateRetry, GateCallConflict, STAGES_PATTERNS, CHAINS, COMMON_DIR_RESOURCES2, MAX_NODES, TRUNCATED_DETAIL_RE, SHELL_ACTION_ALIASES, StatefulChainTracker;
11499
12213
  var init_stateful = __esm({
11500
12214
  "src/engine/formal-engine/stateful.ts"() {
11501
12215
  "use strict";
@@ -11511,6 +12225,12 @@ var init_stateful = __esm({
11511
12225
  SOCK_RE = /([\w./-]*(?:\/tmp\/|\/var\/run\/|\.sock\b)[\w./-]*)/;
11512
12226
  UNIT_RE = /systemctl\s+(?:start|enable|restart)\s+([\w.-]+)/i;
11513
12227
  PORT_STAGE_RE = /LISTEN|PERSIST|SCAN/;
12228
+ StatefulAnalysisUnavailable = class extends Error {
12229
+ };
12230
+ UnconfirmedGateRetry = class extends StatefulAnalysisUnavailable {
12231
+ };
12232
+ GateCallConflict = class extends UnconfirmedGateRetry {
12233
+ };
11514
12234
  STAGES_PATTERNS = null;
11515
12235
  CHAINS = null;
11516
12236
  COMMON_DIR_RESOURCES2 = /* @__PURE__ */ new Set([
@@ -11527,6 +12247,13 @@ var init_stateful = __esm({
11527
12247
  "/storage"
11528
12248
  ]);
11529
12249
  MAX_NODES = resolveMaxNodes();
12250
+ TRUNCATED_DETAIL_RE = /…\[truncated \d+B sha256:([0-9a-f]{16})\]$/;
12251
+ SHELL_ACTION_ALIASES = {
12252
+ executebash: "bash",
12253
+ "terminal-executebash": "bash",
12254
+ execute_bash: "bash",
12255
+ terminal_execute_bash: "bash"
12256
+ };
11530
12257
  StatefulChainTracker = class _StatefulChainTracker {
11531
12258
  /** 本地接收时刻(实时路径无 called_at 时的兜底时间戳,ISO)。 */
11532
12259
  static now() {
@@ -11546,6 +12273,9 @@ var init_stateful = __esm({
11546
12273
  taintedResources = /* @__PURE__ */ new Set();
11547
12274
  aliveResources = {};
11548
12275
  seqNext = 0;
12276
+ seededKeys = /* @__PURE__ */ new Set();
12277
+ /** (sessionId, gateCallId) → 节点,用于 Gate 精确一次关联。 */
12278
+ gateNodes = /* @__PURE__ */ new Map();
11549
12279
  constructor(agentId = "") {
11550
12280
  this.agentId = agentId;
11551
12281
  loadRules();
@@ -11604,28 +12334,73 @@ var init_stateful = __esm({
11604
12334
  }
11605
12335
  return added;
11606
12336
  }
12337
+ resultOf(node, matched, exfil) {
12338
+ return {
12339
+ seq: this.seqNext,
12340
+ node,
12341
+ matched,
12342
+ pendingPrefixes: this.pendingPrefixes,
12343
+ exfil,
12344
+ get shouldBlock() {
12345
+ return this.matched !== null || this.exfil.length > 0;
12346
+ }
12347
+ };
12348
+ }
11607
12349
  /** 增量推进:把当前动作追加到时间线 → 链指针推进 → 判定。 */
11608
12350
  advance(args) {
11609
12351
  const { aNext, sessionId = "current", isError = false, agentId = "", instanceId = "" } = args;
11610
- const node = this.appendNode(aNext, sessionId, isError, agentId, instanceId);
12352
+ const order = gateOrder(aNext);
12353
+ const gateFingerprintValue = order ? gateFingerprint(aNext, isError, agentId, instanceId, order) : "";
12354
+ if (order) {
12355
+ const existing = this.gateNodes.get(this.gateKey(sessionId, order.callId));
12356
+ if (existing) {
12357
+ if (existing.confirmed) {
12358
+ if (existing.inputFingerprint === gateFingerprintValue && existing.gateCallTimeUs === order.callTimeUs) {
12359
+ return this.resultOf(existing, existing.confirmed.matched, existing.confirmed.exfil);
12360
+ }
12361
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u5185\u5BB9\u6216\u65F6\u95F4\u4E0D\u4E00\u81F4");
12362
+ }
12363
+ if (aNext.gateDeliveryUncertain === true) {
12364
+ throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
12365
+ }
12366
+ if (existing.gateCallTimeUs !== order.callTimeUs) {
12367
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u65F6\u95F4\u4E0D\u4E00\u81F4");
12368
+ }
12369
+ if (existing.inputFingerprint) {
12370
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u91CD\u590D\u8C03\u7528\u7F3A\u5C11\u9001\u8FBE\u4E0D\u786E\u5B9A\u6807\u8BB0");
12371
+ }
12372
+ return this.resultOf(existing, null, []);
12373
+ }
12374
+ if (aNext.gateDeliveryUncertain === true) {
12375
+ throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
12376
+ }
12377
+ }
12378
+ const node = this.appendNode(
12379
+ order ? {
12380
+ ...aNext,
12381
+ gateCallId: order.callId,
12382
+ gateCallTimeUs: order.callTimeUs,
12383
+ gateInputFingerprint: gateFingerprintValue
12384
+ } : aNext,
12385
+ sessionId,
12386
+ isError,
12387
+ agentId,
12388
+ instanceId
12389
+ );
11611
12390
  if (!node) {
11612
- return { seq: this.seqNext, node: null, matched: null, pendingPrefixes: this.pendingPrefixes, exfil: [], shouldBlock: false };
12391
+ return this.resultOf(null, null, []);
11613
12392
  }
11614
12393
  const seq = this.seqNext;
11615
12394
  this.recordLifecycle(node);
11616
12395
  const matched = this.advanceChains(node);
11617
12396
  this.advanceTaint(node);
11618
12397
  const exfil = this.checkExfilAfterTaint(node);
11619
- return {
11620
- seq,
11621
- node,
11622
- matched,
11623
- pendingPrefixes: this.pendingPrefixes,
11624
- exfil,
11625
- get shouldBlock() {
11626
- return this.matched !== null || this.exfil.length > 0;
11627
- }
11628
- };
12398
+ if (order) {
12399
+ node.confirmed = { matched, exfil };
12400
+ this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
12401
+ }
12402
+ void seq;
12403
+ return this.resultOf(node, matched, exfil);
11629
12404
  }
11630
12405
  /**
11631
12406
  * 自动轮转:归档旧节点,只保留最近 `retain` 条,并重建链指针/taint。
@@ -11662,6 +12437,7 @@ var init_stateful = __esm({
11662
12437
  this.taintOrigin.clear();
11663
12438
  this.aliveResources = {};
11664
12439
  this.seqNext = 0;
12440
+ this.gateNodes.clear();
11665
12441
  for (const n of kept) {
11666
12442
  const node = this.appendNode(
11667
12443
  {
@@ -11669,7 +12445,12 @@ var init_stateful = __esm({
11669
12445
  actionDetail: n.actionDetail,
11670
12446
  agentId: n.agentId,
11671
12447
  instanceId: n.instanceId,
11672
- ...n.timestamp ? { calledAt: n.timestamp } : {}
12448
+ ...n.timestamp ? { calledAt: n.timestamp } : {},
12449
+ ...n.gateCallId ? {
12450
+ gateCallId: n.gateCallId,
12451
+ gateCallTimeUs: n.gateCallTimeUs,
12452
+ gateInputFingerprint: n.inputFingerprint
12453
+ } : {}
11673
12454
  },
11674
12455
  n.sessionId,
11675
12456
  n.isError,
@@ -11677,6 +12458,7 @@ var init_stateful = __esm({
11677
12458
  n.instanceId
11678
12459
  );
11679
12460
  if (node) {
12461
+ if (n.confirmed) node.confirmed = n.confirmed;
11680
12462
  this.recordLifecycle(node);
11681
12463
  this.advanceTaint(node);
11682
12464
  this.advanceChains(node);
@@ -11684,10 +12466,16 @@ var init_stateful = __esm({
11684
12466
  }
11685
12467
  return { archived: old.length, file };
11686
12468
  }
12469
+ gateKey(sessionId, callId) {
12470
+ return `${sessionId}\0${callId}`;
12471
+ }
11687
12472
  appendNode(action, sessionId, isError = false, agentId = "", instanceId = "") {
11688
12473
  const ad = String(action.actionDetail || "");
11689
12474
  const at = String(action.actionType || "");
11690
12475
  if (!ad) return null;
12476
+ const suppliedCalledAt = typeof action.calledAt === "string" ? action.calledAt : "";
12477
+ const dedupeKey = suppliedCalledAt ? fingerprint(sessionId, at, ad, suppliedCalledAt) : "";
12478
+ if (dedupeKey && this.seededKeys.has(dedupeKey)) return null;
11691
12479
  if (this.nodes_.length >= MAX_NODES) {
11692
12480
  try {
11693
12481
  const r = this.rotate();
@@ -11710,10 +12498,18 @@ var init_stateful = __esm({
11710
12498
  agentId: String(action.agentId || agentId || ""),
11711
12499
  instanceId: String(action.instanceId || instanceId || ""),
11712
12500
  lifecycle: lifecycleFor(ad, stage, isError),
11713
- timestamp: typeof action.calledAt === "string" ? action.calledAt : _StatefulChainTracker.now()
12501
+ timestamp: suppliedCalledAt || _StatefulChainTracker.now()
11714
12502
  };
12503
+ const order = gateOrder(action);
12504
+ if (order) {
12505
+ node.gateCallId = order.callId;
12506
+ node.gateCallTimeUs = order.callTimeUs;
12507
+ node.inputFingerprint = String(action.gateInputFingerprint || "");
12508
+ this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
12509
+ }
11715
12510
  this.nodes_.push(node);
11716
12511
  this.seqNext += 1;
12512
+ if (dedupeKey) this.seededKeys.add(dedupeKey);
11717
12513
  return node;
11718
12514
  }
11719
12515
  recordLifecycle(node) {
@@ -12039,12 +12835,14 @@ var init_stateful = __esm({
12039
12835
  taint_parent: Object.fromEntries([...this.taintParent.entries()].map(([k, v]) => [String(k), v])),
12040
12836
  taint_origin: Object.fromEntries([...this.taintOrigin.entries()]),
12041
12837
  alive: { ...this.aliveResources },
12042
- seq_next: this.seqNext
12838
+ seq_next: this.seqNext,
12839
+ seeded_keys: [...this.seededKeys].sort()
12043
12840
  };
12044
12841
  }
12045
12842
  restore(snapshot) {
12046
12843
  if (!snapshot) return;
12047
12844
  this.agentId = String(snapshot.agent_id || this.agentId);
12845
+ this.seededKeys = new Set((snapshot.seeded_keys || []).map(String));
12048
12846
  for (const raw of snapshot.nodes || []) {
12049
12847
  this.nodes_.push({
12050
12848
  seq: Number(raw.seq || 0),
@@ -12060,11 +12858,24 @@ var init_stateful = __esm({
12060
12858
  // 旧快照无此字段 → 空
12061
12859
  isError: Boolean(raw.isError),
12062
12860
  lifecycle: String(raw.lifecycle || ""),
12063
- timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null
12861
+ timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null,
12064
12862
  // 旧快照无此字段 → null
12863
+ ...raw.gateCallId ? { gateCallId: String(raw.gateCallId) } : {},
12864
+ ...raw.gateCallTimeUs ? { gateCallTimeUs: Number(raw.gateCallTimeUs) } : {},
12865
+ ...raw.inputFingerprint ? { inputFingerprint: String(raw.inputFingerprint) } : {},
12866
+ ...raw.confirmed ? { confirmed: raw.confirmed } : {}
12065
12867
  });
12066
12868
  }
12067
12869
  this.seqNext = Number(snapshot.seq_next || this.nodes_.length);
12870
+ this.gateNodes = /* @__PURE__ */ new Map();
12871
+ for (const n of this.nodes_) {
12872
+ if (n.gateCallId) this.gateNodes.set(this.gateKey(n.sessionId, n.gateCallId), n);
12873
+ }
12874
+ for (const n of this.nodes_) {
12875
+ if (n.timestamp) {
12876
+ this.seededKeys.add(fingerprint(n.sessionId, n.actionType, n.actionDetail, n.timestamp));
12877
+ }
12878
+ }
12068
12879
  this.ptr = Object.fromEntries(Object.entries(snapshot.ptrs || {}).map(([k, v]) => [k, Number(v)]));
12069
12880
  this.tainted = new Set((snapshot.tainted || []).map(Number));
12070
12881
  this.taintParent = new Map(
@@ -12122,12 +12933,12 @@ var init_stateful = __esm({
12122
12933
  import * as fs6 from "fs";
12123
12934
  import * as os4 from "os";
12124
12935
  import * as path7 from "path";
12125
- import { createHash as createHash4 } from "crypto";
12936
+ import { createHash as createHash5 } from "crypto";
12126
12937
  function defaultStateDbPath() {
12127
12938
  const base = process.env.AGENT_MOSS_STATE_DIR || path7.join(os4.homedir(), ".agentmoss");
12128
12939
  const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
12129
12940
  const dir = instance ? path7.join(base, instance) : base;
12130
- const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
12941
+ const tag = createHash5("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
12131
12942
  const target = path7.join(dir, `stateful_chains_${tag}.json`);
12132
12943
  if (instance) {
12133
12944
  const legacy = path7.join(base, `stateful_chains_${tag}.json`);
@@ -12381,6 +13192,7 @@ __export(coordinator_exports, {
12381
13192
  TRUSTED_SKILLS_BASE: () => TRUSTED_SKILLS_BASE,
12382
13193
  _resetBrainForTest: () => _resetBrainForTest,
12383
13194
  extractFirstCommand: () => extractFirstCommand,
13195
+ independentFileCommand: () => independentFileCommand,
12384
13196
  matchesAny: () => matchesAny,
12385
13197
  runAnalysis: () => runAnalysis,
12386
13198
  splitCommandSegments: () => splitCommandSegments,
@@ -12400,6 +13212,25 @@ function extractRawCommand(detail) {
12400
13212
  const m = detail.match(/command=([^,]+)/);
12401
13213
  return m ? m[1].trim() : detail;
12402
13214
  }
13215
+ function independentFileCommand(command, osType) {
13216
+ if (String(osType).toLowerCase() === "windows") return "";
13217
+ if (["\\", "#", "<<", "<(", ">(", "`", "$"].some((mark) => command.includes(mark))) return "";
13218
+ const parts = splitCommandSegments(command);
13219
+ if (parts.length !== 2) return "";
13220
+ const ordinary = parts.filter((part2) => !isInlineScriptCommand(part2.toLowerCase()));
13221
+ if (ordinary.length !== 1) return "";
13222
+ const part = ordinary[0];
13223
+ const name = part.trim().split(/\s+/)[0] || "";
13224
+ const { writeCommandRes } = getPlatformTraits(osType);
13225
+ const isWriteCommandName = writeCommandRes.some((rx) => {
13226
+ const flags = rx.flags.replace("g", "");
13227
+ return new RegExp(`^(?:${rx.source})$`, flags).test(name);
13228
+ });
13229
+ if (SHELL_FULL_READ_CMDS.includes(name) || isWriteCommandName) {
13230
+ return part;
13231
+ }
13232
+ return "";
13233
+ }
12403
13234
  function matchesAny(cmd, patterns) {
12404
13235
  return patterns.some((p) => p.test(cmd));
12405
13236
  }
@@ -12477,21 +13308,42 @@ async function runAnalysis(input) {
12477
13308
  const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
12478
13309
  const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
12479
13310
  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;
13311
+ let skipInlineFileAccess = (isInlineScriptCmd || isLiteralTextCmd) && heuristicResult.riskType === "file_access";
13312
+ const shouldDenyL1 = heuristicResult.riskLevel === "high" || heuristicResult.riskLevel === "critical" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "file_access" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "resource_exhaustion";
13313
+ const bashLike = ["bash", "executebash", "terminal-executebash"].includes(input.aNext.actionType.toLowerCase());
13314
+ if (skipInlineFileAccess && shouldDenyL1 && isInlineScriptCmd && bashLike) {
13315
+ const detail = input.aNext.actionDetail;
13316
+ const command = independentFileCommand(detail, input.osType);
13317
+ if (command) {
13318
+ const hit = runHeuristicCheck({ ...input, aNext: { ...input.aNext, actionDetail: command } });
13319
+ if (hit && !hit.allowed && hit.riskType === "file_access" && ["medium", "high", "critical"].includes(hit.riskLevel)) {
13320
+ return hit;
13321
+ }
13322
+ } else if (String(input.osType || "").toLowerCase() !== "windows" && heuristicResult.deniedReadPath) {
13323
+ skipInlineFileAccess = !confirmsInlineRead(detail, heuristicResult.deniedReadPath);
12485
13324
  }
12486
13325
  }
13326
+ if (!skipInlineFileAccess && shouldDenyL1) {
13327
+ return heuristicResult;
13328
+ }
12487
13329
  }
12488
13330
  const agentExt = mergeAgentExtensions(
12489
13331
  isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
12490
13332
  isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
12491
13333
  );
13334
+ const degradedNotes = [];
12492
13335
  let scriptChain = null;
12493
- if (input.aNext.actionType.toLowerCase() === "bash") {
13336
+ if (input.aNext.actionType.toLowerCase() === "bash" && getDeployRole() === "host") {
13337
+ degradedNotes.push("script_content_deferred_to_sandbox: AGENT_MOSS_DEPLOY_ROLE=host");
13338
+ } else if (input.aNext.actionType.toLowerCase() === "bash") {
12494
13339
  scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
13340
+ if (scriptChain.nodes.length > 0) {
13341
+ for (const node of scriptChain.nodes) {
13342
+ if (node.error && !node.unanalyzable) {
13343
+ degradedNotes.push(`script_content_unavailable: ${node.scriptPath} (${node.error})`);
13344
+ }
13345
+ }
13346
+ }
12495
13347
  if (heuristicEnabled && scriptChain.nodes.length > 0) {
12496
13348
  for (const node of scriptChain.nodes) {
12497
13349
  if (node.unanalyzable) {
@@ -12762,7 +13614,8 @@ async function runAnalysis(input) {
12762
13614
  riskType: "",
12763
13615
  confidence: 85,
12764
13616
  source: "heuristic_and_logic_only",
12765
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
13617
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
13618
+ degraded: degradedNotes
12766
13619
  };
12767
13620
  }
12768
13621
  let skipL3Hints = "\u65E0\uFF08\u5F53\u524D\u65E0\u7981\u7528\u89C4\u5219\u547D\u4E2D\uFF09";
@@ -12799,8 +13652,22 @@ async function runAnalysis(input) {
12799
13652
  pathContext
12800
13653
  });
12801
13654
  } catch (e) {
12802
- const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
12803
13655
  const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
13656
+ if (e instanceof LLMPromptBudgetExceeded) {
13657
+ const failMode = getLLMFailMode2();
13658
+ const allowed = failMode === "fail_open";
13659
+ return {
13660
+ allowed,
13661
+ reason: `L3 prompt \u8D85\u51FA\u786C\u9884\u7B97\uFF0C\u5DF2\u8DF3\u8FC7\u8BED\u4E49\u5206\u6790\uFF0C\u6309 ${failMode} ${allowed ? "\u653E\u884C" : "\u62D2\u7EDD"}`,
13662
+ riskLevel: allowed ? "low" : "medium",
13663
+ riskType: "",
13664
+ confidence: allowed ? 50 : 60,
13665
+ source: "llm_budget_skipped",
13666
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
13667
+ degraded: [...degradedNotes, e.code]
13668
+ };
13669
+ }
13670
+ const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
12804
13671
  if (getLLMFailMode2() === "fail_open") {
12805
13672
  console.warn(`[AgentMoss] LLM \u5206\u6790\u5931\u8D25\uFF0Cfail_open \u6A21\u5F0F\uFF1A\u5141\u8BB8\u6267\u884C\uFF08\u524D\u4E24\u5C42\u672A\u62E6\u622A\uFF09: ${e.message}`);
12806
13673
  return {
@@ -12810,7 +13677,8 @@ async function runAnalysis(input) {
12810
13677
  riskType: "",
12811
13678
  confidence: 50,
12812
13679
  source: failSource,
12813
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
13680
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
13681
+ degraded: degradedNotes
12814
13682
  };
12815
13683
  }
12816
13684
  return {
@@ -12820,7 +13688,10 @@ async function runAnalysis(input) {
12820
13688
  riskType: "",
12821
13689
  confidence: 60,
12822
13690
  source: failSource,
12823
- violatedLayers: ["L3.1"]
13691
+ violatedLayers: ["L3.1"],
13692
+ degraded: degradedNotes,
13693
+ ask_recommended: true,
13694
+ ask_reason: "L3 \u8BED\u4E49\u5206\u6790\u4E0D\u53EF\u7528\uFF0C\u6309 fail_closed \u62D2\u7EDD\uFF1B\u8FD9\u662F\u201C\u6CA1\u67E5\u5B8C\u201D\u800C\u975E\u201C\u786E\u8BA4\u6709\u98CE\u9669\u201D\uFF0C\u5EFA\u8BAE\u5411\u7528\u6237\u786E\u8BA4\u662F\u5426\u7EE7\u7EED\u3002"
12824
13695
  };
12825
13696
  }
12826
13697
  if (!llmResult.allowed && llmResult.confidence && llmResult.confidence >= 90 && _brainExtractor) {
@@ -12840,6 +13711,9 @@ async function runAnalysis(input) {
12840
13711
  if (observedFormalLayers.length > 0 && llmResult.allowed) {
12841
13712
  llmResult.violatedLayers = Array.from(/* @__PURE__ */ new Set([...observedFormalLayers, ...llmResult.violatedLayers || []]));
12842
13713
  }
13714
+ if (degradedNotes.length > 0) {
13715
+ llmResult.degraded = Array.from(/* @__PURE__ */ new Set([...llmResult.degraded || [], ...degradedNotes]));
13716
+ }
12843
13717
  return llmResult;
12844
13718
  }
12845
13719
  var TRUSTED_SKILLS_BASE, _brainStore, _brainExtractor, _brainSkillManager, _brainCurator, _brainInitialized, _brainLastMaintenance, BRAIN_MAINT_INTERVAL_MS, formalEngine;
@@ -13086,7 +13960,11 @@ var AnalyzeRequestSchema = z.object({
13086
13960
  cwd: z.string().default("").describe("Current working directory"),
13087
13961
  agent_id: z.string().default("").describe("Caller agent identifier, e.g. 'xiaoo' / 'opencode' / 'opendesk'. Empty = generic mode (no agent-specific rules)."),
13088
13962
  instance_id: z.string().default("").describe("Agent installation/instance identifier. Used only for display-layer redaction: nodes from the same instance are returned unredacted. Does not affect detection."),
13089
- metadata: z.record(z.unknown()).optional().describe("Extended metadata")
13963
+ metadata: z.record(z.unknown()).optional().describe("Extended metadata"),
13964
+ // 仅在 AgentGate 专用身份通过后校验;直连调用方传这些字段会被忽略。
13965
+ gate_call_id: z.unknown().optional(),
13966
+ gate_call_time_us: z.unknown().optional(),
13967
+ gate_delivery_uncertain: z.unknown().optional()
13090
13968
  });
13091
13969
  var AnalyzeResponseSchema = z.object({
13092
13970
  decision: z.enum(["Allow", "Deny"]).describe("Allow or Deny"),
@@ -13116,6 +13994,11 @@ var AnalyzeResponseSchema = z.object({
13116
13994
  ""
13117
13995
  // 未算出(极端异常路径)
13118
13996
  ]).default(""),
13997
+ /** Deny 但建议向用户确认(旧 agent 忽略仍是 Deny) */
13998
+ ask_recommended: z.boolean().default(false),
13999
+ ask_reason: z.string().default(""),
14000
+ /** Gate 专用调用回显;直连调用为空。 */
14001
+ gate_call_id: z.string().optional(),
13119
14002
  // 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
13120
14003
  violation_graph: z.object({
13121
14004
  // 性质元信息(前端展示"违反了哪条性质")
@@ -13208,7 +14091,7 @@ function deriveL3Outcome(j) {
13208
14091
  if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
13209
14092
  if (src === "llm_circuit_open") return "circuit_open";
13210
14093
  if (src === "llm_failure_with_violation") return "failed_but_blocked";
13211
- if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
14094
+ if (src === "heuristic_and_logic_only" || src === "disabled" || src === "llm_budget_skipped") return "skipped";
13212
14095
  return "not_reached";
13213
14096
  }
13214
14097
 
@@ -13217,7 +14100,7 @@ init_esm_shims();
13217
14100
  init_security_policy();
13218
14101
  init_paths();
13219
14102
  init_config();
13220
- import { createHash as createHash5 } from "crypto";
14103
+ import { createHash as createHash6 } from "crypto";
13221
14104
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
13222
14105
  import { tmpdir as tmpdir2 } from "os";
13223
14106
  import { join as join17 } from "path";
@@ -13250,7 +14133,7 @@ var PolicyCache = class {
13250
14133
  return `${sessionId}::${promptSession}`;
13251
14134
  }
13252
14135
  cacheFilePath(sessionId, promptSession) {
13253
- const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
14136
+ const promptHash = createHash6("md5").update(promptSession).digest("hex").slice(0, 12);
13254
14137
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13255
14138
  return join17(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13256
14139
  }
@@ -13779,6 +14662,7 @@ function reportEnforcementEvent(opts) {
13779
14662
 
13780
14663
  // src/routes.ts
13781
14664
  init_formal_engine();
14665
+ init_stateful();
13782
14666
  init_circuit_breaker();
13783
14667
 
13784
14668
  // src/engine/formal-engine/pattern_miner.ts
@@ -13873,12 +14757,24 @@ var DEFAULT_AGENTGATE_SQLITE = path8.join(
13873
14757
  "agent_gate_ts.db"
13874
14758
  );
13875
14759
  function normalizeAction(row) {
13876
- return {
14760
+ const act = {
13877
14761
  actionType: String(row.action_type || row.tool_name || row.name || ""),
13878
14762
  actionDetail: String(row.action_detail || row.command || row.input || "")
13879
14763
  };
14764
+ if (row.called_at) act.calledAt = String(row.called_at);
14765
+ try {
14766
+ const audit = JSON.parse(String(row.moss_response || "{}"));
14767
+ if (audit && audit._gate_protocol_rejected === true) {
14768
+ act.gateProtocolRejected = true;
14769
+ } else if (audit && typeof audit._gate_call_id === "string" && /^[0-9a-f]{32}$/.test(audit._gate_call_id) && Number.isInteger(audit._gate_call_time_us) && audit._gate_call_time_us > 0) {
14770
+ act.gateCallId = audit._gate_call_id;
14771
+ act.gateCallTimeUs = audit._gate_call_time_us;
14772
+ }
14773
+ } catch {
14774
+ }
14775
+ return act;
13880
14776
  }
13881
- function readJsonDir(dirPath, limit = 1e5) {
14777
+ function readJsonDir(dirPath, limit = 1e5, strict = false) {
13882
14778
  const sessions = /* @__PURE__ */ new Map();
13883
14779
  try {
13884
14780
  const files = fs8.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
@@ -13900,24 +14796,34 @@ function readJsonDir(dirPath, limit = 1e5) {
13900
14796
  for (const v of sessions.values()) total += v.length;
13901
14797
  if (total > limit) break;
13902
14798
  }
13903
- } catch {
14799
+ } catch (err) {
14800
+ if (strict) throw err;
13904
14801
  }
13905
14802
  return [...sessions.entries()].map(([sessionId, actionHistory]) => ({ sessionId, actionHistory }));
13906
14803
  }
13907
- function readSqlite(dbPath, limit = 1e5) {
14804
+ function readSqlite(dbPath, limit = 1e5, strict = false) {
13908
14805
  let Database;
13909
14806
  try {
13910
14807
  Database = esmRequire("better-sqlite3");
13911
- } catch {
14808
+ } catch (err) {
14809
+ if (strict) throw err;
13912
14810
  return [];
13913
14811
  }
13914
14812
  let db;
13915
14813
  try {
13916
14814
  db = new Database(dbPath, { readonly: true });
13917
- const rows = db.prepare(
13918
- `SELECT session_id, action_type, tool_name, action_detail, command, called_at
13919
- FROM tool_calls ORDER BY called_at, id LIMIT ?`
13920
- ).all(limit);
14815
+ let rows;
14816
+ try {
14817
+ rows = db.prepare(
14818
+ `SELECT session_id, action_type, tool_name, action_detail, command, called_at, moss_response
14819
+ FROM tool_calls ORDER BY called_at, id LIMIT ?`
14820
+ ).all(limit);
14821
+ } catch {
14822
+ rows = db.prepare(
14823
+ `SELECT session_id, action_type, tool_name, action_detail, command, called_at
14824
+ FROM tool_calls ORDER BY called_at, id LIMIT ?`
14825
+ ).all(limit);
14826
+ }
13921
14827
  const sessions = /* @__PURE__ */ new Map();
13922
14828
  for (const r of rows) {
13923
14829
  const sid = String(r.session_id || "");
@@ -13929,7 +14835,8 @@ function readSqlite(dbPath, limit = 1e5) {
13929
14835
  sessions.set(sid, list);
13930
14836
  }
13931
14837
  return [...sessions.entries()].map(([sessionId, actionHistory]) => ({ sessionId, actionHistory }));
13932
- } catch {
14838
+ } catch (err) {
14839
+ if (strict) throw err;
13933
14840
  return [];
13934
14841
  } finally {
13935
14842
  try {
@@ -13940,15 +14847,10 @@ function readSqlite(dbPath, limit = 1e5) {
13940
14847
  }
13941
14848
  function loadAgentGateSessions(dbPath = "") {
13942
14849
  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);
14850
+ const target = dbPath.replace(/^~(?=$|\/)/, os5.homedir());
14851
+ const stat = fs8.statSync(target);
14852
+ if (stat.isDirectory()) return readJsonDir(target, 1e5, true);
14853
+ return readSqlite(target, 1e5, true);
13952
14854
  }
13953
14855
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
13954
14856
  if (sql.length > 0) return sql;
@@ -14131,6 +15033,10 @@ async function analyzeRoute(c) {
14131
15033
  try {
14132
15034
  const body = await c.req.json();
14133
15035
  const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
15036
+ const gateCallId = String(c.get("gateCallId") || "");
15037
+ if (gateCallId && (req.gate_call_id !== gateCallId || !validGateCallTime(req.gate_call_time_us) || typeof req.gate_delivery_uncertain !== "boolean")) {
15038
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5143\u6570\u636E\u65E0\u6548" }, 422);
15039
+ }
14134
15040
  const unmappedTool = String(
14135
15041
  req.metadata?.unmapped_tool || ""
14136
15042
  );
@@ -14177,7 +15083,7 @@ async function analyzeRoute(c) {
14177
15083
  session_history: req.session_history,
14178
15084
  metadata: req.metadata
14179
15085
  });
14180
- const result = await analyze({
15086
+ let result = await analyze({
14181
15087
  sessionId: req.session_id,
14182
15088
  promptSession: req.prompt_session,
14183
15089
  // output 必须透传:L2 的「授权(consent)」判定看的是**用户对提问的回答**,
@@ -14235,7 +15141,86 @@ async function analyzeRoute(c) {
14235
15141
  llmConfig: perRequestLlmEnabled() ? req.metadata?.llm_config : void 0,
14236
15142
  llmLogPath: req.metadata?.llm_log_path
14237
15143
  });
15144
+ const meta = req.metadata || {};
15145
+ const incEnabled = String(meta.stateful_incremental || "").toLowerCase();
15146
+ let finding = null;
15147
+ if (incEnabled === "1" || incEnabled === "true" || incEnabled === "yes" || incEnabled === "on") {
15148
+ try {
15149
+ const store = getChainStateStoreFor(agentId);
15150
+ const inc = store.applyAction(
15151
+ chainBucket(agentId),
15152
+ {
15153
+ actionType: req.a_next.action_type,
15154
+ actionDetail: req.a_next.action_detail,
15155
+ ...req.a_next.called_at ? { calledAt: req.a_next.called_at } : {},
15156
+ ...gateCallId ? {
15157
+ gateCallId,
15158
+ gateCallTimeUs: req.gate_call_time_us,
15159
+ gateDeliveryUncertain: req.gate_delivery_uncertain === true
15160
+ } : {}
15161
+ },
15162
+ req.session_id,
15163
+ Boolean(meta.is_error),
15164
+ agentId,
15165
+ // 来源:真实 agent(桶 key 可能是 __system__)
15166
+ instanceId
15167
+ );
15168
+ try {
15169
+ const total = store.stats().nodes;
15170
+ const pct = Math.round(total / MAX_NODES * 1e3) / 10;
15171
+ if (total >= MAX_NODES) {
15172
+ degradedNotes.push(
15173
+ `\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`
15174
+ );
15175
+ } else if (pct >= 90) {
15176
+ degradedNotes.push(
15177
+ `\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`
15178
+ );
15179
+ }
15180
+ } catch {
15181
+ }
15182
+ finding = incMatchedToDeny(inc);
15183
+ } catch (err) {
15184
+ if (err instanceof UnconfirmedGateRetry) {
15185
+ const reason = "AgentMoss \u65E0\u6CD5\u786E\u8BA4\u672C\u6B21 Gate \u8C03\u7528\u662F\u5426\u5DF2\u5165\u94FE";
15186
+ degradedNotes.push(`\u3010\u5DF2\u964D\u7EA7\u3011${reason}\uFF1B\u672C\u6B21\u6309\u62D2\u7EDD\u5904\u7406\uFF0C\u907F\u514D\u91CD\u590D\u5165\u94FE\u3002`);
15187
+ if (result.decision !== "Deny") {
15188
+ result = {
15189
+ ...result,
15190
+ decision: "Deny",
15191
+ reason,
15192
+ risk_type: "service_unavailable",
15193
+ risk_level: "high",
15194
+ policy: "",
15195
+ ask_recommended: true,
15196
+ ask_reason: "\u65E0\u6CD5\u786E\u8BA4\u672C\u6B21 Gate \u8C03\u7528\u662F\u5426\u5DF2\u5165\u94FE\uFF1B\u8FD9\u662F\u201C\u6CA1\u67E5\u5B8C\u201D\u800C\u975E\u201C\u786E\u8BA4\u6709\u98CE\u9669\u201D\uFF0C\u5EFA\u8BAE\u5411\u7528\u6237\u786E\u8BA4\u662F\u5426\u7EE7\u7EED\u3002"
15197
+ };
15198
+ }
15199
+ } else if (err instanceof StatefulAnalysisUnavailable) {
15200
+ degradedNotes.push(
15201
+ "\u3010\u5DF2\u964D\u7EA7\u3011\u6709\u72B6\u6001\u5206\u6790\u4E0D\u53EF\u7528\uFF08\u94FE\u72B6\u6001\u5B58\u50A8\u4E0D\u53EF\u7528\u6216\u672C\u6B21\u52A8\u4F5C\u8D85\u51FA\u4FDD\u7559\u7A97\u53E3\uFF09\uFF1A\u672C\u6B21\u52A8\u4F5C\u672A\u53C2\u4E0E L2.2 \u7EC4\u5408\u94FE\u68C0\u6D4B\uFF1BL1/L2.1/L3 \u5224\u5B9A\u4E0D\u53D7\u5F71\u54CD\u3002"
15202
+ );
15203
+ } else {
15204
+ console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
15205
+ degradedNotes.push(
15206
+ "\u3010\u5DF2\u964D\u7EA7\u3011\u6709\u72B6\u6001\u5206\u6790\u4E0D\u53EF\u7528\uFF08\u5185\u90E8\u5F02\u5E38\uFF09\uFF1A\u672C\u6B21\u52A8\u4F5C\u672A\u53C2\u4E0E L2.2 \u7EC4\u5408\u94FE\u68C0\u6D4B\uFF1BL1/L2.1/L3 \u5224\u5B9A\u4E0D\u53D7\u5F71\u54CD\u3002"
15207
+ );
15208
+ }
15209
+ }
15210
+ }
15211
+ result = publicFormalResult(
15212
+ result,
15213
+ finding,
15214
+ instanceId,
15215
+ req.session_id,
15216
+ req.session_history || []
15217
+ );
14238
15218
  const durationMs = performance.now() - t0;
15219
+ if (Array.isArray(result.degraded)) {
15220
+ for (const note of result.degraded) {
15221
+ if (note && !degradedNotes.includes(note)) degradedNotes.push(note);
15222
+ }
15223
+ }
14239
15224
  const _l3FailMsg = String(result.reason || "").slice(0, 160);
14240
15225
  if (result.l3_outcome === "reasoning_fallback") {
14241
15226
  degradedNotes.push(
@@ -14269,8 +15254,10 @@ async function analyzeRoute(c) {
14269
15254
  l3_outcome: result.l3_outcome || ""
14270
15255
  });
14271
15256
  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] });
15257
+ for (const layer of new Set(
15258
+ (result.violated_layers || []).map((layer2) => String(layer2).split("-")[0])
15259
+ )) {
15260
+ LAYER_HIT_TOTAL.inc(1, { layer });
14274
15261
  }
14275
15262
  } catch {
14276
15263
  }
@@ -14302,62 +15289,6 @@ async function analyzeRoute(c) {
14302
15289
  });
14303
15290
  } catch {
14304
15291
  }
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
15292
  return c.json(
14362
15293
  AnalyzeResponseSchema.parse({
14363
15294
  decision: result.decision,
@@ -14371,13 +15302,18 @@ async function analyzeRoute(c) {
14371
15302
  violated_policy: result.violated_policy,
14372
15303
  confidence: result.confidence,
14373
15304
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
15305
+ // 已在 publicFormalResult 中按静态/增量来源选定并脱敏;这里不能再按
15306
+ // 真实 session 二次脱敏,否则会把静态引擎的 `current` 别名节点误隐藏。
14374
15307
  violation_chain: result.violation_chain ?? [],
14375
- violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
15308
+ violation_graph: result.violation_graph ?? null,
14376
15309
  // 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
14377
15310
  degraded: degradedNotes,
14378
15311
  // L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
14379
15312
  // 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
14380
- l3_outcome: result.l3_outcome || ""
15313
+ l3_outcome: result.l3_outcome || "",
15314
+ ask_recommended: result.ask_recommended === true,
15315
+ ask_reason: String(result.ask_reason || ""),
15316
+ ...gateCallId ? { gate_call_id: gateCallId } : {}
14381
15317
  })
14382
15318
  );
14383
15319
  } catch (err) {
@@ -14399,6 +15335,84 @@ async function analyzeRoute(c) {
14399
15335
  function getChainStateStoreFor(_agentId) {
14400
15336
  return getChainStateStore();
14401
15337
  }
15338
+ var RISK_PRIORITY = { low: 0, medium: 1, high: 2, critical: 3 };
15339
+ function mergeStatefulDenial(result, finding) {
15340
+ const level = String(finding.risk_level || "high");
15341
+ const outcome = result.l3_outcome;
15342
+ 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);
15343
+ const merged = { ...result };
15344
+ if (statefulWins) {
15345
+ const reason = finding.reason || "\u6709\u72B6\u6001\u589E\u91CF\u94FE\u5224\u5B9A\uFF1A\u7EC4\u5408\u653B\u51FB\u94FE\u547D\u4E2D";
15346
+ Object.assign(merged, {
15347
+ decision: "Deny",
15348
+ reason,
15349
+ risk_level: level,
15350
+ risk_type: "formal_verification",
15351
+ source: "formal_engine",
15352
+ confidence: 90,
15353
+ policy: "",
15354
+ violated_policy: `[formal_verification] ${reason}`
15355
+ });
15356
+ }
15357
+ const layers = Array.isArray(result.violated_layers) ? result.violated_layers : [];
15358
+ merged.violated_layers = [.../* @__PURE__ */ new Set([...layers, "L2.2-stateful"])];
15359
+ if (outcome === "fail_open" || outcome === "fail_closed") {
15360
+ merged.l3_outcome = "failed_but_blocked";
15361
+ }
15362
+ console.error(
15363
+ `[AgentMoss] stateful \u589E\u91CF\u62E6\u622A: property=${finding.property_id || "?"} risk=${level} final_risk=${merged.risk_level}`
15364
+ );
15365
+ return { result: merged, wins: statefulWins };
15366
+ }
15367
+ function publicFormalResult(result, finding, instanceId, sessionId, sessionHistory) {
15368
+ let graph = result.violation_graph;
15369
+ let chain = result.violation_chain;
15370
+ let propertyId = graph?.property_id;
15371
+ let staticEvidence = Boolean(chain && chain.length || graph);
15372
+ if (!finding && !staticEvidence) return result;
15373
+ if (finding) {
15374
+ const merged = mergeStatefulDenial(result, finding);
15375
+ result = merged.result;
15376
+ if (merged.wins) propertyId = finding.property_id;
15377
+ const incrementalGraph = finding.violation_graph || {};
15378
+ const fillsMissingGraph = !graph && (finding.risk_level || "high") === result.risk_level && finding.violation_chain && incrementalGraph.nodes;
15379
+ if (merged.wins || !staticEvidence || fillsMissingGraph) {
15380
+ chain = finding.violation_chain;
15381
+ graph = incrementalGraph;
15382
+ staticEvidence = false;
15383
+ }
15384
+ }
15385
+ let publicSessionId = sessionId;
15386
+ let alias = "";
15387
+ if (staticEvidence) {
15388
+ if (!sessionHistory.some((s) => s.session_id === "current")) {
15389
+ alias = "current";
15390
+ } else if (publicSessionId === "current") {
15391
+ publicSessionId = "";
15392
+ }
15393
+ }
15394
+ const publicGraph = redactGraph(graph, instanceId, publicSessionId, { sessionAlias: alias });
15395
+ const out = {
15396
+ ...result,
15397
+ violation_chain: redactChain(chain || [], instanceId, publicSessionId, {
15398
+ graph,
15399
+ sessionAlias: alias
15400
+ }),
15401
+ violation_graph: publicGraph
15402
+ };
15403
+ if (propertyId === "sensitive-data-flow" && chainDetailMode() !== "full") {
15404
+ const nodes = publicGraph?.nodes || [];
15405
+ let reason = "\u654F\u611F\u6570\u636E\u4F20\u64AD\u5916\u4F20\uFF1A\u68C0\u6D4B\u5230\u7ECF\u5171\u4EAB\u8F7D\u4F53\u5916\u53D1";
15406
+ if (nodes.length >= 2) {
15407
+ const src = nodes[0];
15408
+ const dst = nodes[nodes.length - 1];
15409
+ 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`;
15410
+ }
15411
+ out.reason = reason;
15412
+ out.violated_policy = `[formal_verification] ${reason}`;
15413
+ }
15414
+ return out;
15415
+ }
14402
15416
  function incMatchedToDeny(inc) {
14403
15417
  if (inc.matched) {
14404
15418
  const chain = (inc.matched.path || []).map((p) => [p.sessionId, p.seq, p.stage, p.timestamp, p.agentId ?? null]);
@@ -14428,12 +15442,6 @@ async function reviewRoute(c) {
14428
15442
  const body = await c.req.json();
14429
15443
  const req = ReviewRequestSchema.parse(body);
14430
15444
  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
15445
  if (req.db_path && !pathWithin(req.db_path, reviewRoots())) {
14438
15446
  return c.json({
14439
15447
  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 +15449,39 @@ async function reviewRoute(c) {
14441
15449
  }
14442
15450
  let sessions = [];
14443
15451
  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
- }));
15452
+ try {
15453
+ sessions = loadAgentGateSessions(req.db_path);
15454
+ } catch (err) {
15455
+ if (err?.code === "ENOENT") {
15456
+ return c.json({ detail: "\u6307\u5B9A\u7684\u56DE\u987E\u8DEF\u5F84\u4E0D\u5B58\u5728" }, 404);
15457
+ }
15458
+ throw err;
15459
+ }
14449
15460
  } else {
14450
15461
  sessions = (req.sessions || []).map((s) => ({
14451
15462
  sessionId: s.session_id,
14452
- actionHistory: s.action_history.map((a) => ({ actionType: a.action_type, actionDetail: a.action_detail }))
15463
+ actionHistory: s.action_history.map((a) => ({ actionType: a.action_type, actionDetail: a.action_detail, calledAt: a.called_at }))
14453
15464
  }));
14454
15465
  }
14455
- const added = sessions.length > 0 ? tracker.seed(sessions) : 0;
15466
+ const explicitEmpty = !!req.db_path && sessions.length === 0;
15467
+ const store = getChainStateStoreFor(agentId);
15468
+ const bucket = chainBucket(agentId);
15469
+ let tracker = store.load(bucket);
15470
+ if (!tracker) {
15471
+ tracker = new StatefulChainTracker(bucket);
15472
+ }
15473
+ const seedSessions = sessions.map((s) => ({
15474
+ ...s,
15475
+ actionHistory: (s.actionHistory || []).filter((a) => !a.gateProtocolRejected)
15476
+ }));
15477
+ const added = seedSessions.length > 0 ? tracker.seed(seedSessions) : 0;
14456
15478
  store.save(tracker);
14457
15479
  let verified = true;
14458
15480
  const violations = [];
14459
- if (sessions.length > 0 || tracker.nodes.length > 0) {
15481
+ const shouldVerify = explicitEmpty ? Boolean(req.a_next) : sessions.length > 0 || tracker.nodes.length > 0;
15482
+ if (shouldVerify) {
14460
15483
  const eng = new FormalEngine();
14461
- const verifySessions = sessions.length > 0 ? sessions.map((s) => ({ sessionId: s.sessionId, actionHistory: s.actionHistory })) : tracker.nodes.length > 0 ? [{
15484
+ const verifySessions = explicitEmpty ? [] : sessions.length > 0 ? sessions.map((s) => ({ sessionId: s.sessionId, actionHistory: s.actionHistory })) : tracker.nodes.length > 0 ? [{
14462
15485
  sessionId: tracker.agentId,
14463
15486
  actionHistory: tracker.nodes.map((n) => ({
14464
15487
  actionType: n.actionType,
@@ -15163,9 +16186,29 @@ function createApp() {
15163
16186
  if (!okAuth && !isPublicPage) {
15164
16187
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
15165
16188
  }
16189
+ let gateCallId = null;
16190
+ const gateRequired = c.req.header(GATE_IDENTITY_HEADER);
16191
+ const gatePath = path9.replace(/\/+$/, "");
16192
+ if (method === "POST" && gateRequired !== void 0 && (gatePath === "/api/v1/analyze" || gatePath === "/api/v1/review")) {
16193
+ if (principal !== GATE_PRINCIPAL) {
16194
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8EAB\u4EFD\u6821\u9A8C\u5931\u8D25" }, 403);
16195
+ }
16196
+ if (gateRequired !== "1") {
16197
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
16198
+ }
16199
+ }
16200
+ if (method === "POST" && gatePath === "/api/v1/analyze" && principal === GATE_PRINCIPAL) {
16201
+ const id = c.req.header(GATE_CALL_ID_HEADER) || "";
16202
+ if (gateRequired !== "1" || !validGateCallId(id)) {
16203
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
16204
+ }
16205
+ gateCallId = id;
16206
+ c.set("gateCallId", id);
16207
+ }
15166
16208
  if (limiter.enabled && path9.startsWith("/api/")) {
15167
16209
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
15168
16210
  if (!limiter.allow(key)) {
16211
+ if (gateCallId) c.header(GATE_RATE_LIMIT_HEADER, gateCallId);
15169
16212
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
15170
16213
  }
15171
16214
  }
@@ -15181,6 +16224,7 @@ function createApp() {
15181
16224
  const busy = (detail, status = 503) => {
15182
16225
  c.header("Retry-After", "1");
15183
16226
  c.header("Connection", "close");
16227
+ if (gateCallId) c.header(GATE_BUSY_HEADER, gateCallId);
15184
16228
  return c.json({ detail }, status);
15185
16229
  };
15186
16230
  try {