@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/cli.js CHANGED
@@ -918,6 +918,12 @@ function originAllowed(origin, hostHeader, extra) {
918
918
  return false;
919
919
  }
920
920
  }
921
+ function validGateCallId(value) {
922
+ return typeof value === "string" && /^[0-9a-f]{32}$/.test(value);
923
+ }
924
+ function validGateCallTime(value) {
925
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= Number.MAX_SAFE_INTEGER;
926
+ }
921
927
  function authMode() {
922
928
  return (env("AGENT_MOSS_AUTH_MODE", AUTH_MODE_AUTO) || AUTH_MODE_AUTO).toLowerCase();
923
929
  }
@@ -1012,13 +1018,17 @@ function parseAgentTokens(raw) {
1012
1018
  }
1013
1019
  function resolveAuth() {
1014
1020
  const rawAgents = env("AGENT_MOSS_AGENT_TOKENS");
1021
+ const gateToken = env("AGENT_MOSS_GATE_AUTH_TOKEN");
1022
+ const consoleToken = env("AGENT_MOSS_CONSOLE_TOKEN");
1015
1023
  const key = [
1016
1024
  authMode(),
1017
1025
  env("AGENT_MOSS_AUTH_TOKEN"),
1018
1026
  env("AGENT_MOSS_AUTH_TOKEN_FILE"),
1019
1027
  env("AGENT_MOSS_AUTH_TOKEN_FD"),
1020
1028
  rawAgents,
1021
- env("AGENT_MOSS_DATA_DIR")
1029
+ env("AGENT_MOSS_DATA_DIR"),
1030
+ gateToken,
1031
+ consoleToken
1022
1032
  ].join("\0");
1023
1033
  if (tokenCache && tokenCache.key === key) {
1024
1034
  return [tokenCache.token, tokenCache.agents, tokenCache.error];
@@ -1041,6 +1051,13 @@ function resolveAuth() {
1041
1051
  }
1042
1052
  }
1043
1053
  const agents = parseAgentTokens(rawAgents);
1054
+ if (!error && authMode() === AUTH_MODE_OFF && gateToken) {
1055
+ error = "AGENT_MOSS_GATE_AUTH_TOKEN \u4E0D\u80FD\u5728 AGENT_MOSS_AUTH_MODE=off \u65F6\u542F\u7528";
1056
+ } else if (!error && gateToken) {
1057
+ if (gateToken === token || gateToken === consoleToken || Object.values(agents).includes(gateToken)) {
1058
+ error = "AGENT_MOSS_GATE_AUTH_TOKEN \u5FC5\u987B\u4E0E\u5168\u5C40\u3001Agent \u548C Console \u51ED\u636E\u4E0D\u540C";
1059
+ }
1060
+ }
1044
1061
  tokenCache = { key, token, agents, error };
1045
1062
  return [token, agents, error];
1046
1063
  }
@@ -1060,7 +1077,7 @@ function failFastOnAuthError() {
1060
1077
  function authEnabled() {
1061
1078
  if (authMode() === AUTH_MODE_OFF) return false;
1062
1079
  const [tok, agents, err] = resolveAuth();
1063
- return Boolean(err) || Boolean(tok) || Object.keys(agents).length > 0;
1080
+ return Boolean(err) || Boolean(tok) || Object.keys(agents).length > 0 || Boolean(env("AGENT_MOSS_GATE_AUTH_TOKEN"));
1064
1081
  }
1065
1082
  function bearer(headers) {
1066
1083
  const get = (k) => headers instanceof Headers ? headers.get(k) ?? "" : headers[k] ?? "";
@@ -1075,14 +1092,19 @@ function constEq(a, b) {
1075
1092
  }
1076
1093
  function checkRequestAuth(headers, path9) {
1077
1094
  if (authMode() === AUTH_MODE_OFF) return [true, ""];
1078
- const isHealth = HEALTH_PATHS.includes(path9.replace(/\/+$/, ""));
1095
+ const normalizedPath = path9.replace(/\/+$/, "");
1096
+ const isHealth = HEALTH_PATHS.includes(normalizedPath);
1079
1097
  const [gt0, agents, err] = resolveAuth();
1098
+ const gateToken = env("AGENT_MOSS_GATE_AUTH_TOKEN");
1080
1099
  if (err) return isHealth ? [true, ""] : [false, ""];
1081
- if (!gt0 && Object.keys(agents).length === 0) return [true, ""];
1100
+ if (!gt0 && Object.keys(agents).length === 0 && !gateToken) return [true, ""];
1082
1101
  if (isHealth) return [true, ""];
1083
1102
  const tok = bearer(headers);
1084
1103
  if (!tok) return [false, ""];
1085
- if (path9.startsWith("/console/api")) {
1104
+ if (gateToken && GATE_AUTH_PATHS.has(normalizedPath) && constEq(tok, gateToken)) {
1105
+ return [true, GATE_PRINCIPAL];
1106
+ }
1107
+ if (normalizedPath.startsWith("/console/api")) {
1086
1108
  const consoleTok = env("AGENT_MOSS_CONSOLE_TOKEN");
1087
1109
  if (consoleTok && constEq(tok, consoleTok)) return [true, "console"];
1088
1110
  }
@@ -1264,38 +1286,68 @@ function hardenExistingPaths() {
1264
1286
  function chainDetailMode() {
1265
1287
  return (env("AGENT_MOSS_CHAIN_DETAIL", "redacted") || "redacted").toLowerCase();
1266
1288
  }
1267
- function redactChain(chain, currentInstanceId = "", currentSessionId = "") {
1289
+ function chainNodeVisible(instanceId, sessionId, currentInstanceId, currentSessionId, sessionAlias) {
1290
+ const inst = String(instanceId ?? "") || "";
1291
+ if (inst) {
1292
+ return !!(currentInstanceId && inst === String(currentInstanceId));
1293
+ }
1294
+ const sid = String(sessionId ?? "") || "";
1295
+ return !!sid && (sid === currentSessionId || sid === sessionAlias);
1296
+ }
1297
+ function redactChain(chain, currentInstanceId = "", currentSessionId = "", opts = {}) {
1268
1298
  if (!chain || chain.length === 0) return [];
1269
1299
  if (chainDetailMode() === "full") return [...chain];
1270
- return chain.map((step) => {
1300
+ const nodes = opts.graph?.nodes || [];
1301
+ return chain.map((step, index) => {
1271
1302
  if (Array.isArray(step) && step.length >= 3) {
1272
- const [sid, seq, , ts] = step;
1273
- const inst = step.length > 5 ? String(step[5] ?? "") : "";
1274
- const sameInstance = !!(inst && currentInstanceId && inst === String(currentInstanceId));
1275
- const sameSessionFallback = !inst && !!currentSessionId && String(sid) === String(currentSessionId);
1276
- if (sameInstance || sameSessionFallback) return [...step];
1277
- return ["<other-session>", seq, "<\u5DF2\u9690\u85CF>", ts ?? ""];
1303
+ const sid = step[0];
1304
+ const seq = step[1];
1305
+ const ts = step.length > 3 ? step[3] : "";
1306
+ let inst = step.length > 5 ? step[5] : "";
1307
+ if (!inst && index < nodes.length) {
1308
+ const node = nodes[index];
1309
+ const detail = String(node.action_detail ?? "");
1310
+ const stepDetail = String(step[2] ?? "");
1311
+ if (String(sid) !== String(node.session_id ?? "") || String(seq) !== String(node.seq ?? "") || stepDetail !== detail && stepDetail !== detail.slice(0, 60)) {
1312
+ return ["<other-session>", seq, "<\u5DF2\u9690\u85CF>", ts];
1313
+ }
1314
+ inst = node.instance_id;
1315
+ }
1316
+ if (chainNodeVisible(inst, sid, currentInstanceId, currentSessionId, opts.sessionAlias || "")) {
1317
+ return [...step];
1318
+ }
1319
+ return ["<other-session>", seq, "<\u5DF2\u9690\u85CF>", ts];
1278
1320
  }
1279
1321
  return step;
1280
1322
  });
1281
1323
  }
1282
- function redactGraph(graph, currentInstanceId = "", currentSessionId = "") {
1324
+ function redactGraph(graph, currentInstanceId = "", currentSessionId = "", opts = {}) {
1283
1325
  if (!graph) return null;
1284
1326
  if (chainDetailMode() === "full") return graph;
1285
- const nodes = (graph.nodes || []).map((n) => {
1327
+ const hidden = /* @__PURE__ */ new Set();
1328
+ const nodes = (graph.nodes || []).map((n, index) => {
1286
1329
  const m = { ...n };
1287
- const inst = String(m.instance_id ?? "") || "";
1288
- const sid = String(m.session_id ?? "") || "";
1289
- const sameInstance = !!(inst && currentInstanceId && inst === String(currentInstanceId));
1290
- const sameSessionFallback = !inst && !!currentSessionId && sid === String(currentSessionId);
1291
- if (!(sameInstance || sameSessionFallback)) {
1330
+ if (!chainNodeVisible(
1331
+ m.instance_id,
1332
+ m.session_id,
1333
+ currentInstanceId,
1334
+ currentSessionId,
1335
+ opts.sessionAlias || ""
1336
+ )) {
1337
+ hidden.add(index);
1292
1338
  m.session_id = "<other-session>";
1293
1339
  m.action_detail = "<\u5DF2\u9690\u85CF>";
1294
1340
  m.resources = [];
1295
1341
  }
1296
1342
  return m;
1297
1343
  });
1298
- const out = { nodes, edges: graph.edges || [] };
1344
+ const edges = (graph.edges || []).map((edge) => {
1345
+ if ("label" in edge && (hidden.has(Number(edge.from)) || hidden.has(Number(edge.to)))) {
1346
+ return { ...edge, label: "" };
1347
+ }
1348
+ return edge;
1349
+ });
1350
+ const out = { nodes, edges };
1299
1351
  for (const key of ["property_id", "property_short", "property_name", "property_expression"]) {
1300
1352
  if (graph[key] !== void 0) out[key] = graph[key];
1301
1353
  }
@@ -1398,7 +1450,7 @@ function maxConnections() {
1398
1450
  function keepAliveSec() {
1399
1451
  return envInt("AGENT_MOSS_KEEP_ALIVE_SEC", 5);
1400
1452
  }
1401
- var TRUTHY2, HEALTH_PATHS, AUTH_MODE_AUTO, AUTH_MODE_OFF, tokenCache, fdTokenCache, BLOCKED_HOSTS, sessionWindow, queueRejects, POOL_DEFAULTS;
1453
+ var TRUTHY2, HEALTH_PATHS, AUTH_MODE_AUTO, AUTH_MODE_OFF, GATE_PRINCIPAL, GATE_IDENTITY_HEADER, GATE_CALL_ID_HEADER, GATE_RATE_LIMIT_HEADER, GATE_BUSY_HEADER, GATE_AUTH_PATHS, tokenCache, fdTokenCache, BLOCKED_HOSTS, sessionWindow, queueRejects, POOL_DEFAULTS;
1402
1454
  var init_security_policy = __esm({
1403
1455
  "src/infra/security-policy.ts"() {
1404
1456
  "use strict";
@@ -1408,6 +1460,12 @@ var init_security_policy = __esm({
1408
1460
  HEALTH_PATHS = ["/api/v1/health"];
1409
1461
  AUTH_MODE_AUTO = "auto";
1410
1462
  AUTH_MODE_OFF = "off";
1463
+ GATE_PRINCIPAL = "gate";
1464
+ GATE_IDENTITY_HEADER = "X-AgentGate-Require-Identity";
1465
+ GATE_CALL_ID_HEADER = "X-AgentGate-Call-Id";
1466
+ GATE_RATE_LIMIT_HEADER = "X-AgentGate-Rate-Limited-Call-Id";
1467
+ GATE_BUSY_HEADER = "X-AgentGate-Busy-Call-Id";
1468
+ GATE_AUTH_PATHS = /* @__PURE__ */ new Set(["/api/v1/analyze", "/api/v1/review"]);
1411
1469
  tokenCache = null;
1412
1470
  fdTokenCache = /* @__PURE__ */ new Map();
1413
1471
  BLOCKED_HOSTS = ["169.254.169.254", "metadata.google.internal", "metadata.tencentyun.com"];
@@ -1480,7 +1538,11 @@ var init_models = __esm({
1480
1538
  cwd: z.string().default("").describe("Current working directory"),
1481
1539
  agent_id: z.string().default("").describe("Caller agent identifier, e.g. 'xiaoo' / 'opencode' / 'opendesk'. Empty = generic mode (no agent-specific rules)."),
1482
1540
  instance_id: z.string().default("").describe("Agent installation/instance identifier. Used only for display-layer redaction: nodes from the same instance are returned unredacted. Does not affect detection."),
1483
- metadata: z.record(z.unknown()).optional().describe("Extended metadata")
1541
+ metadata: z.record(z.unknown()).optional().describe("Extended metadata"),
1542
+ // 仅在 AgentGate 专用身份通过后校验;直连调用方传这些字段会被忽略。
1543
+ gate_call_id: z.unknown().optional(),
1544
+ gate_call_time_us: z.unknown().optional(),
1545
+ gate_delivery_uncertain: z.unknown().optional()
1484
1546
  });
1485
1547
  AnalyzeResponseSchema = z.object({
1486
1548
  decision: z.enum(["Allow", "Deny"]).describe("Allow or Deny"),
@@ -1510,6 +1572,11 @@ var init_models = __esm({
1510
1572
  ""
1511
1573
  // 未算出(极端异常路径)
1512
1574
  ]).default(""),
1575
+ /** Deny 但建议向用户确认(旧 agent 忽略仍是 Deny) */
1576
+ ask_recommended: z.boolean().default(false),
1577
+ ask_reason: z.string().default(""),
1578
+ /** Gate 专用调用回显;直连调用为空。 */
1579
+ gate_call_id: z.string().optional(),
1513
1580
  // 结构化攻击链图(前端可视化):节点 + 边(next 时序 / data 数据流)
1514
1581
  violation_graph: z.object({
1515
1582
  // 性质元信息(前端展示"违反了哪条性质")
@@ -1695,6 +1762,157 @@ function hasInlineDangerEvidence(command) {
1695
1762
  for (const re of DANGER_EVIDENCE_RES) if (re.test(code)) return true;
1696
1763
  return false;
1697
1764
  }
1765
+ function literalShellWord(raw) {
1766
+ if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) {
1767
+ const inner = raw.slice(1, -1);
1768
+ return inner.includes("'") ? null : inner;
1769
+ }
1770
+ if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) {
1771
+ const inner = raw.slice(1, -1);
1772
+ return /["\\$`]/.test(inner) ? null : inner;
1773
+ }
1774
+ if (!raw || /\s/.test(raw) || !/^[A-Za-z0-9_@%+=:,./-]+$/.test(raw)) return null;
1775
+ return raw;
1776
+ }
1777
+ function pythonStringLiteral(raw) {
1778
+ const text = raw.trim();
1779
+ if (text.length < 2) return null;
1780
+ const quote = text[0];
1781
+ if (quote !== "'" && quote !== '"' || text[text.length - 1] !== quote) return null;
1782
+ const inner = text.slice(1, -1);
1783
+ if (inner.includes(quote) || inner.includes("\\") || inner.includes("\n")) return null;
1784
+ return inner;
1785
+ }
1786
+ function splitPythonArgs(raw) {
1787
+ const parts = [];
1788
+ let current = "";
1789
+ let depth = 0;
1790
+ let quote = null;
1791
+ for (const ch of raw) {
1792
+ if (quote) {
1793
+ current += ch;
1794
+ if (ch === quote) quote = null;
1795
+ continue;
1796
+ }
1797
+ if (ch === "'" || ch === '"') {
1798
+ quote = ch;
1799
+ current += ch;
1800
+ continue;
1801
+ }
1802
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
1803
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1804
+ if (ch === "," && depth === 0) {
1805
+ parts.push(current.trim());
1806
+ current = "";
1807
+ continue;
1808
+ }
1809
+ current += ch;
1810
+ }
1811
+ if (quote || depth !== 0) return null;
1812
+ parts.push(current.trim());
1813
+ return parts;
1814
+ }
1815
+ function hasTopLevelChar(raw, target) {
1816
+ let depth = 0;
1817
+ let quote = null;
1818
+ for (const ch of raw) {
1819
+ if (quote) {
1820
+ if (ch === quote) quote = null;
1821
+ continue;
1822
+ }
1823
+ if (ch === "'" || ch === '"') quote = ch;
1824
+ else if (ch === "(" || ch === "[" || ch === "{") depth++;
1825
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1826
+ else if (ch === target && depth === 0) return true;
1827
+ }
1828
+ return false;
1829
+ }
1830
+ function splitPythonStatements(code) {
1831
+ const parts = [];
1832
+ let current = "";
1833
+ let depth = 0;
1834
+ let quote = null;
1835
+ for (const ch of code) {
1836
+ if (quote) {
1837
+ current += ch;
1838
+ if (ch === quote) quote = null;
1839
+ continue;
1840
+ }
1841
+ if (ch === "'" || ch === '"') {
1842
+ quote = ch;
1843
+ current += ch;
1844
+ continue;
1845
+ }
1846
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
1847
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1848
+ if ((ch === ";" || ch === "\n") && depth === 0) {
1849
+ parts.push(current);
1850
+ current = "";
1851
+ continue;
1852
+ }
1853
+ current += ch;
1854
+ }
1855
+ if (quote || depth !== 0) return null;
1856
+ parts.push(current);
1857
+ return parts.map((s) => s.trim()).filter((s) => s.length > 0);
1858
+ }
1859
+ function isSimpleOpenCall(expr, path9, binding) {
1860
+ const m = expr.match(/^open\s*\(([\s\S]*)\)$/);
1861
+ if (!m || hasTopLevelChar(m[1], "=")) return false;
1862
+ const args = splitPythonArgs(m[1]);
1863
+ if (!args || args.length !== 1 && args.length !== 2) return false;
1864
+ if (args.length === 2 && !["r", "rt", "rb"].includes(pythonStringLiteral(args[1]) ?? "")) {
1865
+ return false;
1866
+ }
1867
+ const target = args[0].trim();
1868
+ const literal = pythonStringLiteral(target);
1869
+ if (literal !== null) return literal === path9;
1870
+ return !!binding && target === binding;
1871
+ }
1872
+ function confirmsInlineRead(command, path9) {
1873
+ if (command.length > 8192 || !path9 || path9.startsWith("~")) return false;
1874
+ if (path9.includes("/") && !path9.startsWith("/")) return false;
1875
+ const wrapper = command.trim().match(/^python3?[ \t]+-c[ \t]+([\s\S]+)$/);
1876
+ if (!wrapper) return false;
1877
+ const code = literalShellWord(wrapper[1]);
1878
+ if (code === null) return false;
1879
+ const statements = splitPythonStatements(code);
1880
+ if (!statements || statements.length !== 1 && statements.length !== 2) return false;
1881
+ let expr;
1882
+ let binding = null;
1883
+ if (statements.length === 2) {
1884
+ const first = statements[0];
1885
+ if (first === "import os") {
1886
+ const sys = statements[1].match(/^os\.system\s*\(([\s\S]*)\)$/);
1887
+ if (!sys || hasTopLevelChar(sys[1], "=")) return false;
1888
+ const args = splitPythonArgs(sys[1]);
1889
+ if (!args || args.length !== 1) return false;
1890
+ const child = pythonStringLiteral(args[0]);
1891
+ if (child === null) return false;
1892
+ const cat = child.trim().match(/^cat[ \t]+([\s\S]+)$/);
1893
+ return !!cat && !path9.startsWith("-") && literalShellWord(cat[1].trim()) === path9;
1894
+ }
1895
+ const assign = first.match(/^([A-Za-z_]\w*)\s*=\s*([\s\S]+)$/);
1896
+ if (!assign) return false;
1897
+ const name = assign[1];
1898
+ const value = pythonStringLiteral(assign[2]);
1899
+ if (value !== path9 || ["open", "print", "__debug__"].includes(name)) return false;
1900
+ binding = name;
1901
+ expr = statements[1];
1902
+ } else {
1903
+ expr = statements[0];
1904
+ }
1905
+ const printCall = expr.match(/^print\s*\(([\s\S]*)\)$/);
1906
+ if (printCall) {
1907
+ if (hasTopLevelChar(printCall[1], "=")) return false;
1908
+ const args = splitPythonArgs(printCall[1]);
1909
+ if (!args || args.length !== 1) return false;
1910
+ expr = args[0];
1911
+ }
1912
+ const readCall = expr.match(/^([\s\S]+)\.read\s*\(\s*\)$/);
1913
+ if (readCall) expr = readCall[1];
1914
+ return isSimpleOpenCall(expr, path9, binding);
1915
+ }
1698
1916
  function analyzeInlineScript(command) {
1699
1917
  const code = extractInlineCode(command);
1700
1918
  if (!code) {
@@ -2158,11 +2376,64 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
2158
2376
  }
2159
2377
  return false;
2160
2378
  }
2379
+ function intentKeywordNegated(text, index) {
2380
+ if (NEGATION_WORDS.length === 0 || index <= 0) return false;
2381
+ const prefix = text.slice(Math.max(0, index - NEGATION_WINDOW), index);
2382
+ return NEGATION_WORDS.some((neg) => prefix.includes(neg));
2383
+ }
2384
+ function isBuildArtifactCleanup(actionDetail) {
2385
+ const text = (actionDetail || "").trim();
2386
+ if (!text) return false;
2387
+ let foundRm = false;
2388
+ const targets = [];
2389
+ for (const raw of splitCommandSegments(text)) {
2390
+ const s = raw.trim();
2391
+ if (!s) continue;
2392
+ let parts = s.split(/\s+/);
2393
+ if (parts[0]?.toLowerCase() === "sudo" || parts[0]?.toLowerCase() === "command") {
2394
+ parts = parts.slice(1);
2395
+ }
2396
+ if (!parts.length || parts[0].toLowerCase() !== "rm") continue;
2397
+ foundRm = true;
2398
+ for (const rawTok of parts.slice(1)) {
2399
+ const tok = rawTok.replace(/^['"]+|['"]+$/g, "");
2400
+ if (!tok || tok.startsWith("-")) continue;
2401
+ targets.push(tok);
2402
+ }
2403
+ }
2404
+ if (!foundRm || targets.length === 0) return false;
2405
+ for (const target of targets) {
2406
+ let t = target.replace(/\\/g, "/");
2407
+ if (t.startsWith("/") || t.split("/").includes("..")) return false;
2408
+ while (t.startsWith("./")) t = t.slice(2);
2409
+ if (!t || [".", "*", "?"].includes(t)) return false;
2410
+ if (t.includes("*") || t.includes("?")) {
2411
+ if (!BUILD_ARTIFACT_GLOB_RE.test(t)) return false;
2412
+ continue;
2413
+ }
2414
+ const first = t.split("/")[0].toLowerCase();
2415
+ if (!BUILD_ARTIFACT_NAMES.has(first)) return false;
2416
+ }
2417
+ return true;
2418
+ }
2161
2419
  function intentCategories(text) {
2162
2420
  const t = (text || "").toLowerCase();
2163
2421
  const out = /* @__PURE__ */ new Set();
2164
2422
  for (const [cat, kws] of Object.entries(INTENT_CATEGORIES)) {
2165
- if (kws.some((kw) => t.includes(String(kw).toLowerCase()))) out.add(cat);
2423
+ for (const kw of kws) {
2424
+ const needle = String(kw).toLowerCase();
2425
+ let start = 0;
2426
+ while (true) {
2427
+ const idx = t.indexOf(needle, start);
2428
+ if (idx < 0) break;
2429
+ if (!intentKeywordNegated(t, idx)) {
2430
+ out.add(cat);
2431
+ break;
2432
+ }
2433
+ start = idx + needle.length;
2434
+ }
2435
+ if (out.has(cat)) break;
2436
+ }
2166
2437
  }
2167
2438
  return out;
2168
2439
  }
@@ -2265,6 +2536,52 @@ function checkIntentConsistency(input, agentExt) {
2265
2536
  }
2266
2537
  const actionCat = actionCategory(actionType, aNext.actionDetail, input.osType, extraWriteTools);
2267
2538
  const reasonKey = intentMatrixViolation(intents, actionCat);
2539
+ const isReferencePrompt = REFERENCE_PRIOR_RE.test((promptSession || "").trim().toLowerCase());
2540
+ if (reasonKey === "read->overwrite" && !EXPLICIT_READONLY_RE.test(intentText) && !isReferencePrompt) {
2541
+ console.debug(
2542
+ `[intent] \u8BFB\u610F\u56FE + \u8986\u76D6\u52A8\u4F5C\uFF0C\u7F3A\u5C11\u660E\u786E\u53EA\u8BFB\u7EA6\u675F\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
2543
+ );
2544
+ return {
2545
+ allowed: true,
2546
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
2547
+ riskLevel: "low",
2548
+ riskType: "",
2549
+ confidence: 50,
2550
+ source: "logic_rule",
2551
+ violatedLayers: [],
2552
+ l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u51FA\u73B0\u8BFB\u610F\u56FE\u8BCD\uFF0C\u4F46\u5F53\u524D\u52A8\u4F5C\u662F\u8986\u76D6\u5199\uFF0Cprompt \u6CA1\u6709\u660E\u786E\u201C\u53EA\u8BFB/\u4E0D\u8981\u4FEE\u6539\u201D\u7EA6\u675F\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
2553
+ };
2554
+ }
2555
+ if ((reasonKey === "read->delete" || reasonKey === "write->delete") && UPDATE_INTENT_RE.test(intentText) && !EXPLICIT_NO_DELETE_RE.test(intentText)) {
2556
+ console.debug(
2557
+ `[intent] \u66F4\u65B0\u7C7B\u610F\u56FE + \u5220\u9664\u52A8\u4F5C\uFF0C\u53EF\u80FD\u5305\u542B\u66FF\u6362\u6D41\u7A0B\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
2558
+ );
2559
+ return {
2560
+ allowed: true,
2561
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
2562
+ riskLevel: "low",
2563
+ riskType: "",
2564
+ confidence: 50,
2565
+ source: "logic_rule",
2566
+ violatedLayers: [],
2567
+ l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u51FA\u73B0\u66F4\u65B0/\u4FEE\u6539\u7C7B\u610F\u56FE\uFF0C\u4F46\u5F53\u524D\u52A8\u4F5C\u662F\u5220\u9664\uFF0C\u53EF\u80FD\u662F\u5148\u5220\u65E7\u518D\u5199\u65B0\u7684\u66FF\u6362\u6D41\u7A0B\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
2568
+ };
2569
+ }
2570
+ if ((reasonKey === "read->delete" || reasonKey === "write->delete") && !isReferencePrompt && INTENT_AMBIGUITY_RE.test(intentText)) {
2571
+ console.debug(
2572
+ `[intent] \u610F\u56FE\u8BCD\u5B58\u5728\u6B67\u4E49\u4E0A\u4E0B\u6587\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
2573
+ );
2574
+ return {
2575
+ allowed: true,
2576
+ reason: "L2 \u610F\u56FE\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3",
2577
+ riskLevel: "low",
2578
+ riskType: "",
2579
+ confidence: 50,
2580
+ source: "logic_rule",
2581
+ violatedLayers: [],
2582
+ l3Hint: `L2 \u610F\u56FE\u89C2\u5BDF\uFF08\u4E0D\u786E\u5B9A\uFF0C\u4EA4 L3\uFF09\uFF1A\u610F\u56FE\u8BCD\u51FA\u73B0\u5728\u53EF\u80FD\u6539\u53D8\u542B\u4E49\u7684\u4E0A\u4E0B\u6587\uFF08\u5904\u7406/\u6761\u4EF6/\u793A\u4F8B/\u6309\u94AE/\u6307\u4EE3\u7B49\uFF09\u4E2D\uFF0C\u4E0D\u80FD\u4EC5\u51ED\u5173\u952E\u8BCD\u5224\u504F\u79BB\u3002prompt=${(promptSession || "").slice(0, 160)}\uFF0C\u52A8\u4F5C=${actionCat}\uFF0C\u76EE\u6807=${aNext.actionDetail.slice(0, 160)}`
2583
+ };
2584
+ }
2268
2585
  if (reasonKey !== null) {
2269
2586
  return {
2270
2587
  allowed: false,
@@ -2781,7 +3098,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
2781
3098
  violatedLayers: ["L2.1"]
2782
3099
  };
2783
3100
  }
2784
- var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SCRIPT_FILE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
3101
+ var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SCRIPT_FILE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, NEGATION_WORDS, NEGATION_WINDOW, EXPLICIT_READONLY_RE, UPDATE_INTENT_RE, EXPLICIT_NO_DELETE_RE, INTENT_AMBIGUITY_RE, BUILD_ARTIFACT_NAMES, BUILD_ARTIFACT_GLOB_RE, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
2785
3102
  var init_logic_rules = __esm({
2786
3103
  "src/engine/logic-rules.ts"() {
2787
3104
  "use strict";
@@ -2883,6 +3200,31 @@ var init_logic_rules = __esm({
2883
3200
  (INTENT_MATRIX.delete_action_words || []).map((w) => String(w).toLowerCase())
2884
3201
  );
2885
3202
  ALL_INTENT_KEYWORDS = Object.values(INTENT_CATEGORIES).flat();
3203
+ NEGATION_WORDS = (INTENT_MATRIX.negation_words || []).map((w) => String(w).toLowerCase());
3204
+ NEGATION_WINDOW = 8;
3205
+ EXPLICIT_READONLY_RE = /(?:只读|仅读|只看|仅看|只查看|仅查看|只分析|仅分析|只做分析|只查询|仅查询|不要(?:修改|写入|写|改动|动)|禁止(?:修改|写入|写|改动)|不得(?:修改|写入|写|改动)|别(?:修改|写入|写|动)|read[- ]only|do not (?:modify|write|change)|don't (?:modify|write|change))/i;
3206
+ UPDATE_INTENT_RE = /(?:更新|修改|编辑|替换|覆盖|改成|改到|rename|replace|update|modify|edit)/i;
3207
+ EXPLICIT_NO_DELETE_RE = /(?:不要|禁止|不得|别|切勿)\s*(?:删除|删掉|删|移除|remove|delete|rm)/i;
3208
+ INTENT_AMBIGUITY_RE = /(?:处理|整理|优化|调整|清掉|如果|假如|若|或者|还是|看情况|根据|按.{0,6}要求|继续|之前|上次|刚才|顺便|示例|例如|比如|按钮|接口|函数|字段|变量|代码里|可能|建议|评估|考虑)/i;
3209
+ BUILD_ARTIFACT_NAMES = /* @__PURE__ */ new Set([
3210
+ "build",
3211
+ "dist",
3212
+ "target",
3213
+ "out",
3214
+ "tmp",
3215
+ "temp",
3216
+ "cache",
3217
+ ".cache",
3218
+ "__pycache__",
3219
+ ".pytest_cache",
3220
+ ".mypy_cache",
3221
+ ".tox",
3222
+ "node_modules",
3223
+ "coverage",
3224
+ ".coverage",
3225
+ "htmlcov"
3226
+ ]);
3227
+ BUILD_ARTIFACT_GLOB_RE = /^\*\.(?:pyc|pyo|class|o|obj|d|egg-info)$/i;
2886
3228
  REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
2887
3229
  REFERENCE_LOOKBACK = 3;
2888
3230
  EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
@@ -4566,6 +4908,7 @@ __export(config_exports, {
4566
4908
  getAgentMossSetting: () => getAgentMossSetting,
4567
4909
  getCacheOptions: () => getCacheOptions,
4568
4910
  getCustomRules: () => getCustomRules,
4911
+ getDeployRole: () => getDeployRole,
4569
4912
  getLLMConfig: () => getLLMConfig,
4570
4913
  getLLMFailMode: () => getLLMFailMode,
4571
4914
  getProviderHeaders: () => getProviderHeaders,
@@ -4748,6 +5091,10 @@ function getLLMFailMode() {
4748
5091
  const val = (process.env.AGENT_MOSS_LLM_FAIL_MODE || "fail_open").toLowerCase();
4749
5092
  return val === "fail_closed" ? "fail_closed" : "fail_open";
4750
5093
  }
5094
+ function getDeployRole() {
5095
+ const val = String(process.env.AGENT_MOSS_DEPLOY_ROLE || "standalone").trim().toLowerCase();
5096
+ return val === "host" || val === "sandbox" ? val : "standalone";
5097
+ }
4751
5098
  function detectProvider(baseUrl, providerHint = "") {
4752
5099
  if (providerHint) {
4753
5100
  const hint = providerHint.toLowerCase();
@@ -5135,6 +5482,21 @@ function detectLanguage(path9, content) {
5135
5482
  }
5136
5483
  return "other";
5137
5484
  }
5485
+ function isInstructionTarget(path9) {
5486
+ const p = (path9 || "").replace(/\\/g, "/").toLowerCase();
5487
+ if (!p) return false;
5488
+ const base = p.split("/").pop() || "";
5489
+ if (["agents.md", "claude.md", "system.md", "prompt.md", "instructions.md", ".cursorrules"].includes(base)) {
5490
+ return true;
5491
+ }
5492
+ if (/(?:^|[-_.])(?:prompt|instruction|system)(?:[-_.]|$)/.test(base)) return true;
5493
+ return INSTRUCTION_TARGET_RE.test(p);
5494
+ }
5495
+ function isDataDocument(actionType, actionDetailRaw) {
5496
+ const payload = extractWritePayload(actionType, actionDetailRaw);
5497
+ if (payload === null) return false;
5498
+ return detectLanguage(payload.path, payload.content) === "data" && !isInstructionTarget(payload.path);
5499
+ }
5138
5500
  function stripShellComments(text) {
5139
5501
  const out = [];
5140
5502
  let heredocEnd = null;
@@ -5297,7 +5659,7 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
5297
5659
  }
5298
5660
  return snippets;
5299
5661
  }
5300
- var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE, HEREDOC_START_RE;
5662
+ var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE, INSTRUCTION_TARGET_RE, HEREDOC_START_RE;
5301
5663
  var init_written_content_analyzer = __esm({
5302
5664
  "src/engine/written-content-analyzer.ts"() {
5303
5665
  "use strict";
@@ -5320,7 +5682,12 @@ var init_written_content_analyzer = __esm({
5320
5682
  "file_edit",
5321
5683
  "editfile",
5322
5684
  "searchreplace",
5323
- "search_replace"
5685
+ "search_replace",
5686
+ // 通用 workspace 工具名(ClawPartner/QwenPaw 等宿主常用)
5687
+ "workspace_write_file",
5688
+ "workspace_edit_file",
5689
+ "workspace_writefile",
5690
+ "workspace_editfile"
5324
5691
  ]);
5325
5692
  WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
5326
5693
  APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
@@ -5329,11 +5696,13 @@ var init_written_content_analyzer = __esm({
5329
5696
  INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
5330
5697
  QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
5331
5698
  PY_DANGEROUS_CALL_RE = /(?:os\.(?:system|popen|remove|unlink|rmdir|chmod|chown|kill|spawn\w*)|subprocess\.\w+|pty\.\w+|ctypes\.\w+|eval|exec|compile|__import__|shutil\.(?:rmtree|move|copy\w*))\s*\(/g;
5699
+ INSTRUCTION_TARGET_RE = /(?:^|[/\\])(?:prompts?|instructions?|skills?|memories|memory|config|policies|policy|\.claude|\.cursor)(?:[/\\]|$)|(?:^|[/\\])(?:AGENTS?|CLAUDE|SYSTEM|PROMPT|INSTRUCTIONS?)(?:\.[^/\\]+)?$|(?:^|[/\\])\.cursorrules$/i;
5332
5700
  HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
5333
5701
  }
5334
5702
  });
5335
5703
 
5336
5704
  // src/engine/heuristic.ts
5705
+ import { posix } from "path";
5337
5706
  function _effectiveDangerousPatterns(osType) {
5338
5707
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
5339
5708
  }
@@ -5361,6 +5730,112 @@ function normalizeShellObfuscation(text) {
5361
5730
  t = t.replace(/\$\{IFS\}|\$IFS/gi, " ");
5362
5731
  return t;
5363
5732
  }
5733
+ function shlexSplitLite(s) {
5734
+ const out = [];
5735
+ let cur = "";
5736
+ let quote = null;
5737
+ let quoted = false;
5738
+ for (let i = 0; i < s.length; i++) {
5739
+ const ch = s[i];
5740
+ if (quote) {
5741
+ if (ch === quote) quote = null;
5742
+ else if (ch === "\\" && quote === '"' && i + 1 < s.length) cur += s[++i];
5743
+ else cur += ch;
5744
+ continue;
5745
+ }
5746
+ if (ch === "'" || ch === '"') {
5747
+ quote = ch;
5748
+ quoted = true;
5749
+ continue;
5750
+ }
5751
+ if (/\s/.test(ch)) {
5752
+ if (cur || quoted) {
5753
+ out.push(cur);
5754
+ cur = "";
5755
+ quoted = false;
5756
+ }
5757
+ continue;
5758
+ }
5759
+ if (ch === "\\" && i + 1 < s.length) {
5760
+ cur += s[++i];
5761
+ continue;
5762
+ }
5763
+ cur += ch;
5764
+ }
5765
+ if (cur || quoted) out.push(cur);
5766
+ return out;
5767
+ }
5768
+ function rmExpandVars(token, env2) {
5769
+ let current = token;
5770
+ for (let round = 0; round < 3; round++) {
5771
+ const next = current.replace(RM_VAR_RE, (whole, braced, bare) => {
5772
+ const name = String(braced || bare).toLowerCase();
5773
+ return env2.get(name) ?? whole;
5774
+ });
5775
+ if (next === current) break;
5776
+ current = next;
5777
+ }
5778
+ return current;
5779
+ }
5780
+ function rmResolvedDangerous(resolved) {
5781
+ if (resolved === "/" || resolved.startsWith("/.")) return true;
5782
+ const first = resolved.split("/")[1] || "";
5783
+ if (first === "home") {
5784
+ const parts = resolved.split("/").filter(Boolean);
5785
+ return parts.length <= 2;
5786
+ }
5787
+ if (RM_SENSITIVE_FIRST.has(first)) return true;
5788
+ if (first === "var" && !(resolved === "/var/tmp" || resolved.startsWith("/var/tmp/"))) {
5789
+ return true;
5790
+ }
5791
+ return false;
5792
+ }
5793
+ function checkRmResolvedTargets(text) {
5794
+ const env2 = /* @__PURE__ */ new Map();
5795
+ for (let segment of splitCommandSegments2(text)) {
5796
+ if (!segment) continue;
5797
+ while (true) {
5798
+ const m = segment.match(RM_ASSIGN_RE);
5799
+ if (!m) break;
5800
+ let value = m[2].trim();
5801
+ if (value.length >= 2 && value[0] === value[value.length - 1] && (value[0] === "'" || value[0] === '"')) {
5802
+ value = value.slice(1, -1);
5803
+ }
5804
+ env2.set(m[1].toLowerCase(), rmExpandVars(value, env2));
5805
+ segment = segment.slice(m[0].length);
5806
+ }
5807
+ const parts = shlexSplitLite(segment);
5808
+ if (parts.length === 0) continue;
5809
+ let idx = 0;
5810
+ while (idx < parts.length && RM_COMMAND_PREFIXES.has(parts[idx].toLowerCase())) idx++;
5811
+ if (idx >= parts.length) continue;
5812
+ const commandWord = parts[idx].split("/").pop().replace(/^\\/, "").toLowerCase();
5813
+ if (commandWord !== "rm") continue;
5814
+ let optionsDone = false;
5815
+ for (const token of parts.slice(idx + 1)) {
5816
+ if (token === "--") {
5817
+ optionsDone = true;
5818
+ continue;
5819
+ }
5820
+ if (!optionsDone && token.startsWith("-")) continue;
5821
+ const target = rmExpandVars(token, env2);
5822
+ if (!target.startsWith("/")) continue;
5823
+ const resolved = posix.normalize(target);
5824
+ if (rmResolvedDangerous(resolved)) {
5825
+ return {
5826
+ allowed: false,
5827
+ reason: `\u68C0\u6D4B\u5230\u5220\u9664\u6839\u76EE\u5F55/\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55\uFF08\u89E3\u6790\u540E\u76EE\u6807 ${resolved}\uFF09`,
5828
+ riskLevel: "critical",
5829
+ riskType: "script_execution",
5830
+ confidence: 95,
5831
+ source: "heuristic",
5832
+ violatedLayers: ["L1.1"]
5833
+ };
5834
+ }
5835
+ }
5836
+ }
5837
+ return null;
5838
+ }
5364
5839
  function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
5365
5840
  const scanDetail = normalizePathSegments(stripLiteralTextSegments(actionDetail));
5366
5841
  const scanCommands = String(osType || "").toLowerCase() === "windows" ? [
@@ -5379,16 +5854,19 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
5379
5854
  }
5380
5855
  }
5381
5856
  }
5382
- if (!top) return null;
5383
- return {
5857
+ const toJudgment = (hit) => ({
5384
5858
  allowed: false,
5385
- reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${top.desc}`,
5386
- riskLevel: top.sev,
5387
- riskType: top.type,
5859
+ reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${hit.desc}`,
5860
+ riskLevel: hit.sev,
5861
+ riskType: hit.type,
5388
5862
  confidence: 95,
5389
5863
  source: "heuristic",
5390
5864
  violatedLayers: ["L1.1"]
5391
- };
5865
+ });
5866
+ if (top && severityRank(top.sev) >= severityRank("high")) return toJudgment(top);
5867
+ const rmResolved = checkRmResolvedTargets(scanDetail);
5868
+ if (rmResolved) return rmResolved;
5869
+ return top ? toJudgment(top) : null;
5392
5870
  }
5393
5871
  function allUrlsLoopback(actionDetail) {
5394
5872
  const hosts = actionDetail.match(new RegExp(LOOPBACK_URL_RE.source, "gi"));
@@ -5462,6 +5940,23 @@ function runHeuristicCheck(input) {
5462
5940
  deobfuscated
5463
5941
  );
5464
5942
  }
5943
+ const extraScanDetail = stripSearchPatternLiterals(scanDetail);
5944
+ const extraScanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => {
5945
+ const stripped = stripSearchPatternLiterals(sn);
5946
+ return [`${input.aNext.actionType}: ${stripped}`, stripped];
5947
+ }) : String(input.osType || "").toLowerCase() === "windows" ? [
5948
+ `${input.aNext.actionType}: ${extraScanDetail}`,
5949
+ extraScanDetail,
5950
+ `${input.aNext.actionType}: ${extraScanDetail.replace(/\//g, "\\")}`,
5951
+ extraScanDetail.replace(/\//g, "\\")
5952
+ ] : [`${input.aNext.actionType}: ${extraScanDetail}`, extraScanDetail];
5953
+ const extraDeobfuscated = normalizeShellObfuscation(extraScanDetail);
5954
+ if (extraDeobfuscated !== extraScanDetail) {
5955
+ extraScanCommands.push(
5956
+ `${input.aNext.actionType}: ${extraDeobfuscated}`,
5957
+ extraDeobfuscated
5958
+ );
5959
+ }
5465
5960
  let topRiskType = "";
5466
5961
  const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
5467
5962
  const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
@@ -5486,7 +5981,7 @@ function runHeuristicCheck(input) {
5486
5981
  for (const rule of agentExt.extra_command_patterns) {
5487
5982
  try {
5488
5983
  const re = new RegExp(rule.pattern, "i");
5489
- if (scanCommands.some((c) => re.test(c))) {
5984
+ if (extraScanCommands.some((c) => re.test(c))) {
5490
5985
  matched.push(`agent \u4E13\u5C5E\u89C4\u5219: ${rule.reason}`);
5491
5986
  if (severityRank(rule.risk_level) > severityRank(highestSeverity)) {
5492
5987
  highestSeverity = rule.risk_level;
@@ -5497,7 +5992,7 @@ function runHeuristicCheck(input) {
5497
5992
  }
5498
5993
  }
5499
5994
  }
5500
- const injectionText = isSearchActionType(input.aNext.actionType) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
5995
+ const injectionText = isSearchActionType(input.aNext.actionType) || handledWrite && isDataDocument(input.aNext.actionType, input.aNext.actionDetail) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
5501
5996
  let pythonWalkOnerrorOnly = false;
5502
5997
  if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
5503
5998
  pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
@@ -5523,6 +6018,10 @@ function runHeuristicCheck(input) {
5523
6018
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
5524
6019
  const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
5525
6020
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
6021
+ if (isBashLike && !handledWrite && severityRank(highestSeverity) < severityRank("high") && !mergeResults.some((r) => severityRank(r.riskLevel) >= severityRank("high"))) {
6022
+ const rmResolved = checkRmResolvedTargets(scanDetail);
6023
+ if (rmResolved) mergeResults.push(rmResolved);
6024
+ }
5526
6025
  if (mergeResults.length > 0) {
5527
6026
  let best = mergeResults[0];
5528
6027
  for (const r of mergeResults) {
@@ -5539,6 +6038,9 @@ function runHeuristicCheck(input) {
5539
6038
  violatedLayers: ["L1.1"]
5540
6039
  };
5541
6040
  }
6041
+ if (best !== pathResult && pathResult?.deniedReadPath && best.riskType === "file_access" && best.riskLevel === pathResult.riskLevel) {
6042
+ best = { ...best, deniedReadPath: pathResult.deniedReadPath };
6043
+ }
5542
6044
  return best;
5543
6045
  }
5544
6046
  if (matched.length > 0) {
@@ -5741,16 +6243,83 @@ function splitCommandSegments2(actionDetail) {
5741
6243
  if (start < actionDetail.length) segments.push(actionDetail.slice(start));
5742
6244
  return segments;
5743
6245
  }
6246
+ function shellTokens(seg) {
6247
+ const tokens = [];
6248
+ let cur = "";
6249
+ let quote = "";
6250
+ for (let i = 0; i < seg.length; i++) {
6251
+ const ch = seg[i];
6252
+ if (quote) {
6253
+ if (ch === quote) quote = "";
6254
+ else cur += ch;
6255
+ continue;
6256
+ }
6257
+ if (ch === '"' || ch === "'") {
6258
+ quote = ch;
6259
+ continue;
6260
+ }
6261
+ if (/\s/.test(ch)) {
6262
+ if (cur) {
6263
+ tokens.push(cur);
6264
+ cur = "";
6265
+ }
6266
+ continue;
6267
+ }
6268
+ cur += ch;
6269
+ }
6270
+ if (quote) return null;
6271
+ if (cur) tokens.push(cur);
6272
+ return tokens;
6273
+ }
6274
+ function stripSearchPatternArgument(seg) {
6275
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) return seg;
6276
+ const tokens = shellTokens(seg);
6277
+ if (!tokens || tokens.length === 0) return seg;
6278
+ let idx = 0;
6279
+ while (idx < tokens.length && COMMAND_PREFIX_WORDS.has(tokens[idx])) idx++;
6280
+ if (idx >= tokens.length || !TEXT_SEARCH_COMMANDS.has(tokens[idx])) return seg;
6281
+ let patternIdx = null;
6282
+ let i = idx + 1;
6283
+ while (i < tokens.length) {
6284
+ const token = tokens[i];
6285
+ if (token === "--") {
6286
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
6287
+ break;
6288
+ }
6289
+ if (token === "-e" || token === "--regexp") {
6290
+ patternIdx = i + 1 < tokens.length ? i + 1 : null;
6291
+ break;
6292
+ }
6293
+ if (token.startsWith("--regexp=")) {
6294
+ patternIdx = i;
6295
+ break;
6296
+ }
6297
+ if (token === "-f" || token === "--file" || token.startsWith("--file=")) break;
6298
+ if (token.startsWith("-") && token !== "-") {
6299
+ i += SEARCH_OPTION_WITH_ARG.has(token) ? 2 : 1;
6300
+ continue;
6301
+ }
6302
+ patternIdx = i;
6303
+ break;
6304
+ }
6305
+ if (patternIdx === null || patternIdx >= tokens.length) return seg;
6306
+ tokens.splice(patternIdx, 1);
6307
+ return tokens.map((t) => /\s/.test(t) ? `'${t.replaceAll("'", "'\\''")}'` : t).join(" ");
6308
+ }
5744
6309
  function stripSearchPatternLiterals(actionDetail) {
5745
6310
  const parts = [];
5746
6311
  for (const seg of splitCommandSegments2(actionDetail)) {
6312
+ if (/^(?:&&|\|\||[;|&\n])$/.test(seg.trim())) {
6313
+ parts.push(seg);
6314
+ continue;
6315
+ }
5747
6316
  const low = seg.trim().toLowerCase();
5748
6317
  const words = low.length ? low.split(/\s+/) : [];
5749
6318
  let idx = 0;
5750
6319
  while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
5751
6320
  const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
5752
6321
  if (isSearch && !low.includes("--pre")) {
5753
- parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
6322
+ parts.push(stripSearchPatternArgument(seg));
5754
6323
  } else {
5755
6324
  parts.push(seg);
5756
6325
  }
@@ -5798,7 +6367,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5798
6367
  riskType: "file_access",
5799
6368
  confidence: 90,
5800
6369
  source: "heuristic",
5801
- violatedLayers: ["L1.1"]
6370
+ violatedLayers: ["L1.1"],
6371
+ deniedReadPath: sp.path
5802
6372
  };
5803
6373
  }
5804
6374
  const denyMode = sp.denyMode || (sp.credential ? "deny_both" : sp.readOnly ? "deny_read" : "deny_write");
@@ -5812,7 +6382,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5812
6382
  confidence: 90,
5813
6383
  source: "heuristic",
5814
6384
  violatedLayers: ["L1.1"],
5815
- isCredential: !!sp.credential
6385
+ isCredential: !!sp.credential,
6386
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5816
6387
  };
5817
6388
  }
5818
6389
  }
@@ -5869,7 +6440,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5869
6440
  confidence: 90,
5870
6441
  source: "heuristic",
5871
6442
  violatedLayers: ["L1.1"],
5872
- isCredential: !!sp.credential
6443
+ isCredential: !!sp.credential,
6444
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5873
6445
  };
5874
6446
  }
5875
6447
  }
@@ -5892,7 +6464,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5892
6464
  confidence: 90,
5893
6465
  source: "heuristic",
5894
6466
  violatedLayers: ["L1.1"],
5895
- isCredential: !!sp.credential
6467
+ isCredential: !!sp.credential,
6468
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5896
6469
  };
5897
6470
  }
5898
6471
  }
@@ -5909,7 +6482,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5909
6482
  confidence: 90,
5910
6483
  source: "heuristic",
5911
6484
  violatedLayers: ["L1.1"],
5912
- isCredential: true
6485
+ isCredential: true,
6486
+ deniedReadPath: cp.path
5913
6487
  };
5914
6488
  }
5915
6489
  }
@@ -6070,7 +6644,7 @@ function checkDangerousPatterns(actionType, actionDetail) {
6070
6644
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
6071
6645
  const wildcardDeleteRe = /(?:\brm\b|\b(r?mdir|del|delete|remove|rmdir|unlink)\b|\b删除\b|\b移除\b)[\s\S]{0,40}?[*?]|[*?][\s\S]{0,40}?\b(?:rm|del|delete|remove|rmdir|unlink)\b|rm\s+-[a-zA-Z]*[rf][a-zA-Z]*\s+\S*[*?]/i;
6072
6646
  const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
6073
- if (!isTempPath && wildcardDeleteRe.test(scanNoSpecials)) {
6647
+ if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
6074
6648
  return {
6075
6649
  allowed: false,
6076
6650
  reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
@@ -6212,7 +6786,7 @@ function checkLateralMovement(actionDetail) {
6212
6786
  }
6213
6787
  return null;
6214
6788
  }
6215
- 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;
6789
+ var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SEARCH_OPTION_WITH_ARG, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
6216
6790
  var init_heuristic = __esm({
6217
6791
  "src/engine/heuristic.ts"() {
6218
6792
  "use strict";
@@ -6238,6 +6812,10 @@ var init_heuristic = __esm({
6238
6812
  DANGEROUS_PATTERNS_WINDOWS = _loadDangerousPatterns("windows");
6239
6813
  DANGEROUS_PATTERNS_MACOS = _loadDangerousPatterns("macos");
6240
6814
  DANGEROUS_PATTERNS_HARMONY = _loadDangerousPatterns("harmony");
6815
+ RM_ASSIGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|]+)\s*/;
6816
+ RM_VAR_RE = /\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;
6817
+ RM_COMMAND_PREFIXES = /* @__PURE__ */ new Set(["sudo", "env", "command", "builtin", "exec", "nohup", "time"]);
6818
+ RM_SENSITIVE_FIRST = /* @__PURE__ */ new Set(["etc", "usr", "boot", "root", "opt", "srv", "sys", "proc", "home"]);
6241
6819
  LOOPBACK_URL_RE = /https?:\/\/([^\/\s;'"|&)]+)/i;
6242
6820
  HEURISTIC_RULES = loadHeuristicRules();
6243
6821
  LOOPBACK_HOSTS = new Set(HEURISTIC_RULES.loopback_hosts ?? []);
@@ -6257,6 +6835,28 @@ var init_heuristic = __esm({
6257
6835
  COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
6258
6836
  TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
6259
6837
  COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
6838
+ SEARCH_OPTION_WITH_ARG = /* @__PURE__ */ new Set([
6839
+ "-m",
6840
+ "--max-count",
6841
+ "-A",
6842
+ "--after-context",
6843
+ "-B",
6844
+ "--before-context",
6845
+ "-C",
6846
+ "--context",
6847
+ "-d",
6848
+ "--directories",
6849
+ "-D",
6850
+ "--devices",
6851
+ "--include",
6852
+ "--exclude",
6853
+ "--exclude-dir",
6854
+ "--glob",
6855
+ "--iglob",
6856
+ "--type",
6857
+ "--type-add",
6858
+ "--type-not"
6859
+ ]);
6260
6860
  SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
6261
6861
  SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
6262
6862
  SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
@@ -9158,6 +9758,9 @@ async function runLLMAnalysis(input, previous) {
9158
9758
  scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
9159
9759
  }
9160
9760
  const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
9761
+ const budgetMode = getAgentMossSetting("AGENT_MOSS_LLM_BUDGET_MODE", "hard").trim().toLowerCase() === "soft" ? "soft" : "hard";
9762
+ const budgetActive = maxPromptTokens > 0;
9763
+ const tokenLimit = budgetActive && budgetMode === "hard" ? Math.floor(maxPromptTokens * 100 / 115) : maxPromptTokens;
9161
9764
  let historyMaxItems = getNumSetting("AGENT_MOSS_LLM_HISTORY_MAX_ITEMS", 20);
9162
9765
  let historyMaxChars = getNumSetting("AGENT_MOSS_LLM_ACTION_DETAIL_MAX_CHARS", 500);
9163
9766
  let prompt = "";
@@ -9174,13 +9777,14 @@ async function runLLMAnalysis(input, previous) {
9174
9777
  historyMaxItems,
9175
9778
  historyMaxChars
9176
9779
  );
9177
- if (maxPromptTokens <= 0 || estimateTokens(prompt) <= maxPromptTokens) break;
9780
+ if (!budgetActive || estimateTokens(prompt) <= tokenLimit) break;
9178
9781
  historyMaxItems = historyMaxItems > 0 ? Math.max(2, Math.floor(historyMaxItems / 2)) : 2;
9179
9782
  historyMaxChars = historyMaxChars > 0 ? Math.max(100, Math.floor(historyMaxChars / 2)) : 100;
9180
9783
  }
9181
- if (maxPromptTokens > 0 && estimateTokens(prompt) > maxPromptTokens) {
9784
+ let budgetCode = "";
9785
+ if (budgetActive && estimateTokens(prompt) > tokenLimit) {
9182
9786
  const estimated = estimateTokens(prompt);
9183
- const ratio = estimated / maxPromptTokens;
9787
+ const ratio = tokenLimit > 0 ? estimated / tokenLimit : Number.POSITIVE_INFINITY;
9184
9788
  const allowed = Math.max(200, Math.floor(input.aNext.actionDetail.length / ratio));
9185
9789
  const truncated = truncateDetail(input.aNext.actionDetail, allowed);
9186
9790
  prompt = buildPrompt(
@@ -9196,8 +9800,14 @@ async function runLLMAnalysis(input, previous) {
9196
9800
  historyMaxChars
9197
9801
  );
9198
9802
  console.warn(
9199
- `[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${maxPromptTokens}\uFF09\uFF0C\u5F53\u524D\u52A8\u4F5C\u8BE6\u60C5\u622A\u65AD\u81F3 ${truncated.length} \u5B57\u7B26`
9803
+ `[AgentMoss] L3 prompt \u8D85 token \u9884\u7B97\uFF08\u4F30 ${estimated} > ${tokenLimit}\uFF09\uFF0C\u5F53\u524D\u52A8\u4F5C\u8BE6\u60C5\u622A\u65AD\u81F3 ${truncated.length} \u5B57\u7B26`
9200
9804
  );
9805
+ if (estimateTokens(prompt) > tokenLimit) {
9806
+ if (budgetMode === "hard") {
9807
+ throw new LLMPromptBudgetExceeded("l3_budget_unreachable");
9808
+ }
9809
+ budgetCode = "l3_budget_unreachable";
9810
+ }
9201
9811
  }
9202
9812
  logPrompt(prompt, input.aNext, previous.llmLogPath);
9203
9813
  traceFull("l3.prompt", {
@@ -9210,6 +9820,7 @@ async function runLLMAnalysis(input, previous) {
9210
9820
  prompt_chars: prompt.length
9211
9821
  });
9212
9822
  const result = await analyzeWithLLM(prompt, config);
9823
+ if (budgetCode) result.degraded = [...result.degraded || [], budgetCode];
9213
9824
  traceSummary("l3.verdict", {
9214
9825
  allowed: result.allowed,
9215
9826
  risk_level: result.riskLevel,
@@ -9283,11 +9894,14 @@ function buildPrompt(input, previous, matchedSkills, templates, scriptAnalysis,
9283
9894
  const skillsText = formatSkillsForPrompt(matchedSkills);
9284
9895
  const historyStr = formatActionHistory(input.actionHistory, historyMaxItems, historyMaxChars);
9285
9896
  const promptHistoryText = formatPromptHistory(input.promptHistory);
9897
+ const historyAuthorization = /(因历史窗口上限省略|本段因长度上限已截断)/.test(promptHistoryText) ? `
9898
+
9899
+ ${HISTORY_AUTHORIZATION}` : "";
9286
9900
  const scriptAnalysisText = scriptChainText ? scriptChainText : scriptAnalysis ? formatScriptAnalysisForPrompt(scriptAnalysis) : "";
9287
9901
  const hintsText = formatHints(previous);
9288
9902
  const securityJudgeTemplate = templates["security_judge"];
9289
9903
  if (securityJudgeTemplate) {
9290
- return securityJudgeTemplate.replaceAll("{prompt_session}", input.promptSession || "\uFF08\u672A\u63D0\u4F9B\uFF09").replaceAll("{prompt_history_text}", promptHistoryText).replaceAll("{action_history}", historyStr).replaceAll("{action_type}", input.aNext.actionType).replaceAll("{action_detail}", input.aNext.actionDetail).replaceAll("{reason}", input.reason || "\u672A\u8BF4\u660E").replaceAll("{skills_text}", skillsText).replaceAll("{hints_text}", hintsText).replaceAll("{script_analysis_text}", scriptAnalysisText).replaceAll("{skip_l3_hints}", skipL3Hints).replaceAll("{path_context}", pathContext || "\uFF08\u672C\u547D\u4EE4\u65E0\u4E3B\u76EE\u5F55\u76F8\u5173\u8DEF\u5F84\u6BB5\uFF0C\u4E0D\u9002\u7528\uFF09").replaceAll("{{", "{").replaceAll("}}", "}");
9904
+ return securityJudgeTemplate.replaceAll("{prompt_session}", input.promptSession || "\uFF08\u672A\u63D0\u4F9B\uFF09").replaceAll("{prompt_history_text}", promptHistoryText).replaceAll("{history_authorization}", historyAuthorization).replaceAll("{action_history}", historyStr).replaceAll("{action_type}", input.aNext.actionType).replaceAll("{action_detail}", input.aNext.actionDetail).replaceAll("{reason}", input.reason || "\u672A\u8BF4\u660E").replaceAll("{skills_text}", skillsText).replaceAll("{hints_text}", hintsText).replaceAll("{script_analysis_text}", scriptAnalysisText).replaceAll("{skip_l3_hints}", skipL3Hints).replaceAll("{path_context}", pathContext || "\uFF08\u672C\u547D\u4EE4\u65E0\u4E3B\u76EE\u5F55\u76F8\u5173\u8DEF\u5F84\u6BB5\uFF0C\u4E0D\u9002\u7528\uFF09").replaceAll("{{", "{").replaceAll("}}", "}");
9291
9905
  }
9292
9906
  console.warn("[AgentMoss] security_judge template missing, using sparse fallback prompt");
9293
9907
  return `## \u5F53\u524D\u64CD\u4F5C\u4E0A\u4E0B\u6587
@@ -9317,25 +9931,34 @@ ${scriptAnalysisText}` : ""}
9317
9931
  \u8F93\u51FA\u683C\u5F0F:
9318
9932
  {"allowed": true/false, "reason": "\u5224\u65AD\u7406\u7531", "riskLevel": "low|medium|high|critical", "riskType": "\u98CE\u9669\u7C7B\u578B", "confidence": 0-100}`;
9319
9933
  }
9320
- function formatPromptHistory(promptHistory, maxTextChars = 500) {
9934
+ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNumSetting("AGENT_MOSS_LLM_PROMPT_HISTORY_MAX_TURNS", 20)) {
9321
9935
  if (!promptHistory || promptHistory.length === 0) {
9322
9936
  return "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
9323
9937
  }
9938
+ const limit = Math.max(0, Math.floor(maxTurns));
9939
+ const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
9940
+ let omitted = 0;
9324
9941
  const lines = [];
9325
9942
  for (let i = 0; i < promptHistory.length; i++) {
9326
9943
  const turn = promptHistory[i];
9327
9944
  const text = (typeof turn === "string" ? turn : turn?.text || "").trim();
9328
- if (!text) continue;
9329
- let line = ` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${text.slice(0, maxTextChars)}`;
9330
9945
  const actions = typeof turn === "string" ? void 0 : turn?.actions;
9331
- if (actions && actions.length > 0) {
9332
- const types = actions.map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
9333
- if (types.length > 0) {
9334
- line += ` \u2192 \u52A8\u4F5C: ${types.join(", ")}`;
9335
- }
9946
+ const types = (actions || []).map((a) => a?.actionType).filter((t) => typeof t === "string" && t.length > 0);
9947
+ if (!text && types.length === 0) continue;
9948
+ if (i < firstTurnIndex) {
9949
+ omitted += 1;
9950
+ continue;
9336
9951
  }
9337
- lines.push(line);
9952
+ if (!text) {
9953
+ lines.push(` \u7B2C${i + 1}\u8F6E\u52A8\u4F5C: ${types.join(", ")}`);
9954
+ continue;
9955
+ }
9956
+ let shown = text.slice(0, maxTextChars);
9957
+ if (shown.length < text.length) shown += "\uFF08\u672C\u6BB5\u56E0\u957F\u5EA6\u4E0A\u9650\u5DF2\u622A\u65AD\uFF09";
9958
+ const suffix = types.length > 0 ? ` \u2192 \u52A8\u4F5C: ${types.join(", ")}` : "";
9959
+ lines.push(` \u7B2C${i + 1}\u8F6E\u7528\u6237\u610F\u56FE: ${shown}${suffix}`);
9338
9960
  }
9961
+ if (omitted) lines.unshift(`\uFF08\u56E0\u5386\u53F2\u7A97\u53E3\u4E0A\u9650\u7701\u7565 ${omitted} \u8F6E\u66F4\u65E9\u5386\u53F2\u610F\u56FE\uFF09`);
9339
9962
  return lines.length > 0 ? lines.join("\n") : "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
9340
9963
  }
9341
9964
  function formatHints(previous) {
@@ -9348,11 +9971,15 @@ function formatHints(previous) {
9348
9971
  );
9349
9972
  }
9350
9973
  if (previous.logic) {
9351
- hints.push(
9352
- `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
9974
+ if (previous.logic.l3Hint) {
9975
+ hints.push(`\u2139\uFE0F ${previous.logic.l3Hint}`);
9976
+ } else {
9977
+ hints.push(
9978
+ `\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u53D1\u73B0\u98CE\u9669 [\u98CE\u9669\u7B49\u7EA7: ${previous.logic.riskLevel}]:
9353
9979
  \u7C7B\u578B: ${previous.logic.riskType}
9354
9980
  \u539F\u56E0: ${previous.logic.reason}`
9355
- );
9981
+ );
9982
+ }
9356
9983
  }
9357
9984
  return hints.length > 0 ? hints.join("\n\n") : "\u7279\u5F81\u5339\u914D\u68C0\u6D4B\u548C\u903B\u8F91\u89C4\u5219\u68C0\u6D4B\u5747\u672A\u53D1\u73B0\u98CE\u9669\u3002";
9358
9985
  }
@@ -9564,7 +10191,7 @@ async function analyzeWithLLM(prompt, config) {
9564
10191
  clearTimeout(totalTimeoutTimer);
9565
10192
  throw new Error(`LLM \u5206\u6790\u8D85\u65F6\uFF08totalTimeout ${timeoutCfg.totalTimeout}s\uFF09`);
9566
10193
  }
9567
- var LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
10194
+ var LLMPromptBudgetExceeded, HISTORY_AUTHORIZATION, LLMCircuitOpenError, llmCache, LLM_CACHE_MAX;
9568
10195
  var init_llm_analyzer = __esm({
9569
10196
  "src/engine/llm-analyzer.ts"() {
9570
10197
  "use strict";
@@ -9578,6 +10205,15 @@ var init_llm_analyzer = __esm({
9578
10205
  init_trace_log();
9579
10206
  init_metrics();
9580
10207
  init_circuit_breaker();
10208
+ LLMPromptBudgetExceeded = class extends Error {
10209
+ code;
10210
+ constructor(code) {
10211
+ super(code);
10212
+ this.name = "LLMPromptBudgetExceeded";
10213
+ this.code = code;
10214
+ }
10215
+ };
10216
+ HISTORY_AUTHORIZATION = "\u88AB\u7701\u7565\u6216\u88AB\u622A\u65AD\u7684\u5386\u53F2\u4E0D\u80FD\u4F5C\u4E3A\u6388\u6743\u4F9D\u636E\u3002\n\u201C\u7EE7\u7EED\u201D\u53EA\u6307\u4EE3\u53EF\u89C1\u7684\u524D\u6587\uFF1B\u5982\u679C\u53EF\u89C1\u524D\u6587\u4E0D\u8DB3\u4EE5\u786E\u8BA4\u6307\u4EE3\u76EE\u6807\u6216\u6388\u6743\u8303\u56F4\uFF0C\u5E94\u5728 reason \u4E2D\u8BF4\u660E\u4F9D\u636E\u4E0D\u8DB3\uFF0C\u5E76\u6309\u6700\u5C0F\u6743\u9650\u539F\u5219\u5224\u65AD\u9700\u8981\u8BE5\u6388\u6743\u7684\u52A8\u4F5C\u3002\n\u5F53\u524D\u7528\u6237\u8BF7\u6C42\u4E2D\u660E\u786E\u5199\u51FA\u7684\u6388\u6743\u4ECD\u7136\u6709\u6548\uFF0C\u6309\u5176\u53EF\u89C1\u7684\u76EE\u6807\u548C\u9650\u5236\u5224\u65AD\u3002";
9581
10217
  LLMCircuitOpenError = class extends Error {
9582
10218
  constructor(message) {
9583
10219
  super(message);
@@ -11020,11 +11656,35 @@ function checkMCRules(graph) {
11020
11656
  for (const rule of rules) {
11021
11657
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
11022
11658
  if (ruleViolates(rule, trace2, witnessMode)) {
11659
+ const pathNodes = nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3);
11660
+ const path9 = pathNodes.map((n) => ({
11661
+ sessionId: n.sessionId,
11662
+ seq: n.seq,
11663
+ detail: n.actionDetail.slice(0, 60)
11664
+ }));
11023
11665
  violations.push({
11024
11666
  propertyId: String(rule.id || "mc-ltl"),
11025
11667
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
11026
11668
  riskLevel: String(rule.risk_level || "high"),
11027
- path: nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3).map((n) => ({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }))
11669
+ path: path9,
11670
+ graph: {
11671
+ property_id: String(rule.id || "mc-ltl"),
11672
+ property_short: "P6",
11673
+ property_name: "LTL \u6A21\u578B\u68C0\u6D4B",
11674
+ nodes: pathNodes.map((n) => ({
11675
+ session_id: n.sessionId,
11676
+ seq: n.seq,
11677
+ stage: n.stage,
11678
+ action_detail: n.actionDetail,
11679
+ resources: [...n.resources].sort(),
11680
+ instance_id: n.instanceId || ""
11681
+ })),
11682
+ edges: pathNodes.slice(1).map((_, i) => ({
11683
+ from: i,
11684
+ to: i + 1,
11685
+ type: "next"
11686
+ }))
11687
+ }
11028
11688
  });
11029
11689
  if (witnessMode) return violations;
11030
11690
  }
@@ -11724,11 +12384,17 @@ function checkLowIntegrityCommandExec(graph) {
11724
12384
  for (const i of candidates) {
11725
12385
  const n = nodes[i];
11726
12386
  if (lowAt.has(i) && isComputeNode(n)) {
12387
+ const path9 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11727
12388
  violations.push({
11728
12389
  propertyId: "low-integrity-command-exec",
11729
12390
  reason: `\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u63A7\u5236\u547D\u4EE4\u6267\u884C\uFF1A${lowAt.get(i)} \u2192 ${n.sessionId}#${n.seq} \u6267\u884C\u4E0D\u53EF\u4FE1\u5185\u5BB9`,
11730
12391
  riskLevel: "critical",
11731
- path: [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }]
12392
+ path: path9,
12393
+ graph: graphFromPath(nodes, path9, "next", {
12394
+ property_id: "low-integrity-command-exec",
12395
+ property_short: "P7",
12396
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u547D\u4EE4\u6267\u884C"
12397
+ }, ["sink"])
11732
12398
  });
11733
12399
  if (witness !== void 0) return violations;
11734
12400
  }
@@ -11770,11 +12436,21 @@ function checkCrossSessionReachability(graph) {
11770
12436
  if (reached.has(i)) {
11771
12437
  const srcIdx = Math.min(...sources);
11772
12438
  const srcDesc = nodes[srcIdx].actionDetail.slice(0, 40);
12439
+ const path9 = nodes.slice(-3).map((m) => ({
12440
+ sessionId: m.sessionId,
12441
+ seq: m.seq,
12442
+ detail: m.actionDetail.slice(0, 60)
12443
+ }));
11773
12444
  violations.push({
11774
12445
  propertyId: "low-integrity-reachability",
11775
12446
  reason: `\u4F4E\u5B8C\u6574\u6027\u6E90\u7ECF\u8DE8 session \u6570\u636E\u94FE\u591A\u8DF3\u5230\u8FBE\u5F53\u524D\u6267\u884C\uFF08\u6E90: ${srcDesc} \u2192 ${n.sessionId}#${n.seq}\uFF09`,
11776
12447
  riskLevel: "high",
11777
- path: nodes.slice(-3).map((m) => ({ sessionId: m.sessionId, seq: m.seq, detail: m.actionDetail.slice(0, 60) }))
12448
+ path: path9,
12449
+ graph: graphFromPath(nodes, path9, "data", {
12450
+ property_id: "low-integrity-reachability",
12451
+ property_short: "P3",
12452
+ property_name: "\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u6D41\u53EF\u8FBE"
12453
+ })
11778
12454
  });
11779
12455
  if (witness !== void 0) return violations;
11780
12456
  }
@@ -11944,6 +12620,7 @@ var init_engine = __esm({
11944
12620
  });
11945
12621
 
11946
12622
  // src/engine/formal-engine/stateful.ts
12623
+ import { createHash as createHash4 } from "crypto";
11947
12624
  import * as fs5 from "fs";
11948
12625
  import * as os3 from "os";
11949
12626
  import * as path6 from "path";
@@ -12084,7 +12761,53 @@ function cleanupChainArchives(dir, maxBytes = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_
12084
12761
  }
12085
12762
  return { deleted: removed, files: remainFiles, bytes: remainBytes };
12086
12763
  }
12087
- 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;
12764
+ function canonicalActionType(actionType) {
12765
+ const low = String(actionType || "").trim().toLowerCase();
12766
+ return SHELL_ACTION_ALIASES[low] || low;
12767
+ }
12768
+ function canonicalDetail(actionDetail) {
12769
+ const detail = String(actionDetail || "");
12770
+ const m = TRUNCATED_DETAIL_RE.exec(detail);
12771
+ const digest = m ? m[1] : createHash4("sha256").update(detail).digest("hex").slice(0, 16);
12772
+ return `sha256:${digest}`;
12773
+ }
12774
+ function canonicalCalledAt(calledAt) {
12775
+ const value = String(calledAt || "").trim();
12776
+ if (!value) return "";
12777
+ let normalized = value;
12778
+ if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?$/.test(normalized)) {
12779
+ normalized = normalized.replace(" ", "T") + "Z";
12780
+ }
12781
+ const ms = Date.parse(normalized);
12782
+ return Number.isFinite(ms) ? String(Math.floor(ms / 1e3)) : value;
12783
+ }
12784
+ function fingerprint(sessionId, actionType, actionDetail, calledAt) {
12785
+ const raw = [
12786
+ String(sessionId),
12787
+ canonicalActionType(actionType),
12788
+ canonicalDetail(actionDetail),
12789
+ canonicalCalledAt(calledAt)
12790
+ ].join("\0");
12791
+ return createHash4("blake2b512").update(raw).digest("hex").slice(0, 16);
12792
+ }
12793
+ function gateOrder(action) {
12794
+ const callId = String(action?.gateCallId ?? "");
12795
+ const callTimeUs = Number(action?.gateCallTimeUs ?? 0);
12796
+ return callId && Number.isFinite(callTimeUs) && callTimeUs > 0 ? { callId, callTimeUs } : null;
12797
+ }
12798
+ function gateFingerprint(action, isError, agentId, instanceId, order) {
12799
+ const values = [
12800
+ String(action?.actionType ?? ""),
12801
+ String(action?.actionDetail ?? ""),
12802
+ String(action?.calledAt ?? ""),
12803
+ String(action?.agentId ?? agentId ?? ""),
12804
+ String(action?.instanceId ?? instanceId ?? ""),
12805
+ Boolean(isError),
12806
+ order.callTimeUs
12807
+ ];
12808
+ return createHash4("sha256").update(JSON.stringify(values)).digest("hex");
12809
+ }
12810
+ var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, StatefulAnalysisUnavailable, UnconfirmedGateRetry, GateCallConflict, STAGES_PATTERNS, CHAINS, COMMON_DIR_RESOURCES2, MAX_NODES, TRUNCATED_DETAIL_RE, SHELL_ACTION_ALIASES, StatefulChainTracker;
12088
12811
  var init_stateful = __esm({
12089
12812
  "src/engine/formal-engine/stateful.ts"() {
12090
12813
  "use strict";
@@ -12100,6 +12823,12 @@ var init_stateful = __esm({
12100
12823
  SOCK_RE = /([\w./-]*(?:\/tmp\/|\/var\/run\/|\.sock\b)[\w./-]*)/;
12101
12824
  UNIT_RE = /systemctl\s+(?:start|enable|restart)\s+([\w.-]+)/i;
12102
12825
  PORT_STAGE_RE = /LISTEN|PERSIST|SCAN/;
12826
+ StatefulAnalysisUnavailable = class extends Error {
12827
+ };
12828
+ UnconfirmedGateRetry = class extends StatefulAnalysisUnavailable {
12829
+ };
12830
+ GateCallConflict = class extends UnconfirmedGateRetry {
12831
+ };
12103
12832
  STAGES_PATTERNS = null;
12104
12833
  CHAINS = null;
12105
12834
  COMMON_DIR_RESOURCES2 = /* @__PURE__ */ new Set([
@@ -12116,6 +12845,13 @@ var init_stateful = __esm({
12116
12845
  "/storage"
12117
12846
  ]);
12118
12847
  MAX_NODES = resolveMaxNodes();
12848
+ TRUNCATED_DETAIL_RE = /…\[truncated \d+B sha256:([0-9a-f]{16})\]$/;
12849
+ SHELL_ACTION_ALIASES = {
12850
+ executebash: "bash",
12851
+ "terminal-executebash": "bash",
12852
+ execute_bash: "bash",
12853
+ terminal_execute_bash: "bash"
12854
+ };
12119
12855
  StatefulChainTracker = class _StatefulChainTracker {
12120
12856
  /** 本地接收时刻(实时路径无 called_at 时的兜底时间戳,ISO)。 */
12121
12857
  static now() {
@@ -12135,6 +12871,9 @@ var init_stateful = __esm({
12135
12871
  taintedResources = /* @__PURE__ */ new Set();
12136
12872
  aliveResources = {};
12137
12873
  seqNext = 0;
12874
+ seededKeys = /* @__PURE__ */ new Set();
12875
+ /** (sessionId, gateCallId) → 节点,用于 Gate 精确一次关联。 */
12876
+ gateNodes = /* @__PURE__ */ new Map();
12138
12877
  constructor(agentId = "") {
12139
12878
  this.agentId = agentId;
12140
12879
  loadRules();
@@ -12193,28 +12932,73 @@ var init_stateful = __esm({
12193
12932
  }
12194
12933
  return added;
12195
12934
  }
12935
+ resultOf(node, matched, exfil) {
12936
+ return {
12937
+ seq: this.seqNext,
12938
+ node,
12939
+ matched,
12940
+ pendingPrefixes: this.pendingPrefixes,
12941
+ exfil,
12942
+ get shouldBlock() {
12943
+ return this.matched !== null || this.exfil.length > 0;
12944
+ }
12945
+ };
12946
+ }
12196
12947
  /** 增量推进:把当前动作追加到时间线 → 链指针推进 → 判定。 */
12197
12948
  advance(args) {
12198
12949
  const { aNext, sessionId = "current", isError = false, agentId = "", instanceId = "" } = args;
12199
- const node = this.appendNode(aNext, sessionId, isError, agentId, instanceId);
12950
+ const order = gateOrder(aNext);
12951
+ const gateFingerprintValue = order ? gateFingerprint(aNext, isError, agentId, instanceId, order) : "";
12952
+ if (order) {
12953
+ const existing = this.gateNodes.get(this.gateKey(sessionId, order.callId));
12954
+ if (existing) {
12955
+ if (existing.confirmed) {
12956
+ if (existing.inputFingerprint === gateFingerprintValue && existing.gateCallTimeUs === order.callTimeUs) {
12957
+ return this.resultOf(existing, existing.confirmed.matched, existing.confirmed.exfil);
12958
+ }
12959
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u5185\u5BB9\u6216\u65F6\u95F4\u4E0D\u4E00\u81F4");
12960
+ }
12961
+ if (aNext.gateDeliveryUncertain === true) {
12962
+ throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
12963
+ }
12964
+ if (existing.gateCallTimeUs !== order.callTimeUs) {
12965
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u65F6\u95F4\u4E0D\u4E00\u81F4");
12966
+ }
12967
+ if (existing.inputFingerprint) {
12968
+ throw new GateCallConflict("\u540C\u4E00 Gate call_id \u7684\u91CD\u590D\u8C03\u7528\u7F3A\u5C11\u9001\u8FBE\u4E0D\u786E\u5B9A\u6807\u8BB0");
12969
+ }
12970
+ return this.resultOf(existing, null, []);
12971
+ }
12972
+ if (aNext.gateDeliveryUncertain === true) {
12973
+ throw new UnconfirmedGateRetry("\u4E0D\u786E\u5B9A\u9001\u8FBE\u7684\u8C03\u7528\u7F3A\u5C11\u5DF2\u786E\u8BA4\u7684\u72B6\u6001\u5316\u5224\u5B9A");
12974
+ }
12975
+ }
12976
+ const node = this.appendNode(
12977
+ order ? {
12978
+ ...aNext,
12979
+ gateCallId: order.callId,
12980
+ gateCallTimeUs: order.callTimeUs,
12981
+ gateInputFingerprint: gateFingerprintValue
12982
+ } : aNext,
12983
+ sessionId,
12984
+ isError,
12985
+ agentId,
12986
+ instanceId
12987
+ );
12200
12988
  if (!node) {
12201
- return { seq: this.seqNext, node: null, matched: null, pendingPrefixes: this.pendingPrefixes, exfil: [], shouldBlock: false };
12989
+ return this.resultOf(null, null, []);
12202
12990
  }
12203
12991
  const seq = this.seqNext;
12204
12992
  this.recordLifecycle(node);
12205
12993
  const matched = this.advanceChains(node);
12206
12994
  this.advanceTaint(node);
12207
12995
  const exfil = this.checkExfilAfterTaint(node);
12208
- return {
12209
- seq,
12210
- node,
12211
- matched,
12212
- pendingPrefixes: this.pendingPrefixes,
12213
- exfil,
12214
- get shouldBlock() {
12215
- return this.matched !== null || this.exfil.length > 0;
12216
- }
12217
- };
12996
+ if (order) {
12997
+ node.confirmed = { matched, exfil };
12998
+ this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
12999
+ }
13000
+ void seq;
13001
+ return this.resultOf(node, matched, exfil);
12218
13002
  }
12219
13003
  /**
12220
13004
  * 自动轮转:归档旧节点,只保留最近 `retain` 条,并重建链指针/taint。
@@ -12251,6 +13035,7 @@ var init_stateful = __esm({
12251
13035
  this.taintOrigin.clear();
12252
13036
  this.aliveResources = {};
12253
13037
  this.seqNext = 0;
13038
+ this.gateNodes.clear();
12254
13039
  for (const n of kept) {
12255
13040
  const node = this.appendNode(
12256
13041
  {
@@ -12258,7 +13043,12 @@ var init_stateful = __esm({
12258
13043
  actionDetail: n.actionDetail,
12259
13044
  agentId: n.agentId,
12260
13045
  instanceId: n.instanceId,
12261
- ...n.timestamp ? { calledAt: n.timestamp } : {}
13046
+ ...n.timestamp ? { calledAt: n.timestamp } : {},
13047
+ ...n.gateCallId ? {
13048
+ gateCallId: n.gateCallId,
13049
+ gateCallTimeUs: n.gateCallTimeUs,
13050
+ gateInputFingerprint: n.inputFingerprint
13051
+ } : {}
12262
13052
  },
12263
13053
  n.sessionId,
12264
13054
  n.isError,
@@ -12266,6 +13056,7 @@ var init_stateful = __esm({
12266
13056
  n.instanceId
12267
13057
  );
12268
13058
  if (node) {
13059
+ if (n.confirmed) node.confirmed = n.confirmed;
12269
13060
  this.recordLifecycle(node);
12270
13061
  this.advanceTaint(node);
12271
13062
  this.advanceChains(node);
@@ -12273,10 +13064,16 @@ var init_stateful = __esm({
12273
13064
  }
12274
13065
  return { archived: old.length, file };
12275
13066
  }
13067
+ gateKey(sessionId, callId) {
13068
+ return `${sessionId}\0${callId}`;
13069
+ }
12276
13070
  appendNode(action, sessionId, isError = false, agentId = "", instanceId = "") {
12277
13071
  const ad = String(action.actionDetail || "");
12278
13072
  const at = String(action.actionType || "");
12279
13073
  if (!ad) return null;
13074
+ const suppliedCalledAt = typeof action.calledAt === "string" ? action.calledAt : "";
13075
+ const dedupeKey = suppliedCalledAt ? fingerprint(sessionId, at, ad, suppliedCalledAt) : "";
13076
+ if (dedupeKey && this.seededKeys.has(dedupeKey)) return null;
12280
13077
  if (this.nodes_.length >= MAX_NODES) {
12281
13078
  try {
12282
13079
  const r = this.rotate();
@@ -12299,10 +13096,18 @@ var init_stateful = __esm({
12299
13096
  agentId: String(action.agentId || agentId || ""),
12300
13097
  instanceId: String(action.instanceId || instanceId || ""),
12301
13098
  lifecycle: lifecycleFor(ad, stage, isError),
12302
- timestamp: typeof action.calledAt === "string" ? action.calledAt : _StatefulChainTracker.now()
13099
+ timestamp: suppliedCalledAt || _StatefulChainTracker.now()
12303
13100
  };
13101
+ const order = gateOrder(action);
13102
+ if (order) {
13103
+ node.gateCallId = order.callId;
13104
+ node.gateCallTimeUs = order.callTimeUs;
13105
+ node.inputFingerprint = String(action.gateInputFingerprint || "");
13106
+ this.gateNodes.set(this.gateKey(sessionId, order.callId), node);
13107
+ }
12304
13108
  this.nodes_.push(node);
12305
13109
  this.seqNext += 1;
13110
+ if (dedupeKey) this.seededKeys.add(dedupeKey);
12306
13111
  return node;
12307
13112
  }
12308
13113
  recordLifecycle(node) {
@@ -12628,12 +13433,14 @@ var init_stateful = __esm({
12628
13433
  taint_parent: Object.fromEntries([...this.taintParent.entries()].map(([k, v]) => [String(k), v])),
12629
13434
  taint_origin: Object.fromEntries([...this.taintOrigin.entries()]),
12630
13435
  alive: { ...this.aliveResources },
12631
- seq_next: this.seqNext
13436
+ seq_next: this.seqNext,
13437
+ seeded_keys: [...this.seededKeys].sort()
12632
13438
  };
12633
13439
  }
12634
13440
  restore(snapshot) {
12635
13441
  if (!snapshot) return;
12636
13442
  this.agentId = String(snapshot.agent_id || this.agentId);
13443
+ this.seededKeys = new Set((snapshot.seeded_keys || []).map(String));
12637
13444
  for (const raw of snapshot.nodes || []) {
12638
13445
  this.nodes_.push({
12639
13446
  seq: Number(raw.seq || 0),
@@ -12649,11 +13456,24 @@ var init_stateful = __esm({
12649
13456
  // 旧快照无此字段 → 空
12650
13457
  isError: Boolean(raw.isError),
12651
13458
  lifecycle: String(raw.lifecycle || ""),
12652
- timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null
13459
+ timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null,
12653
13460
  // 旧快照无此字段 → null
13461
+ ...raw.gateCallId ? { gateCallId: String(raw.gateCallId) } : {},
13462
+ ...raw.gateCallTimeUs ? { gateCallTimeUs: Number(raw.gateCallTimeUs) } : {},
13463
+ ...raw.inputFingerprint ? { inputFingerprint: String(raw.inputFingerprint) } : {},
13464
+ ...raw.confirmed ? { confirmed: raw.confirmed } : {}
12654
13465
  });
12655
13466
  }
12656
13467
  this.seqNext = Number(snapshot.seq_next || this.nodes_.length);
13468
+ this.gateNodes = /* @__PURE__ */ new Map();
13469
+ for (const n of this.nodes_) {
13470
+ if (n.gateCallId) this.gateNodes.set(this.gateKey(n.sessionId, n.gateCallId), n);
13471
+ }
13472
+ for (const n of this.nodes_) {
13473
+ if (n.timestamp) {
13474
+ this.seededKeys.add(fingerprint(n.sessionId, n.actionType, n.actionDetail, n.timestamp));
13475
+ }
13476
+ }
12657
13477
  this.ptr = Object.fromEntries(Object.entries(snapshot.ptrs || {}).map(([k, v]) => [k, Number(v)]));
12658
13478
  this.tainted = new Set((snapshot.tainted || []).map(Number));
12659
13479
  this.taintParent = new Map(
@@ -12711,12 +13531,12 @@ var init_stateful = __esm({
12711
13531
  import * as fs6 from "fs";
12712
13532
  import * as os4 from "os";
12713
13533
  import * as path7 from "path";
12714
- import { createHash as createHash4 } from "crypto";
13534
+ import { createHash as createHash5 } from "crypto";
12715
13535
  function defaultStateDbPath() {
12716
13536
  const base = process.env.AGENT_MOSS_STATE_DIR || path7.join(os4.homedir(), ".agentmoss");
12717
13537
  const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
12718
13538
  const dir = instance ? path7.join(base, instance) : base;
12719
- const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
13539
+ const tag = createHash5("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
12720
13540
  const target = path7.join(dir, `stateful_chains_${tag}.json`);
12721
13541
  if (instance) {
12722
13542
  const legacy = path7.join(base, `stateful_chains_${tag}.json`);
@@ -12970,6 +13790,7 @@ __export(coordinator_exports, {
12970
13790
  TRUSTED_SKILLS_BASE: () => TRUSTED_SKILLS_BASE,
12971
13791
  _resetBrainForTest: () => _resetBrainForTest,
12972
13792
  extractFirstCommand: () => extractFirstCommand,
13793
+ independentFileCommand: () => independentFileCommand,
12973
13794
  matchesAny: () => matchesAny,
12974
13795
  runAnalysis: () => runAnalysis,
12975
13796
  splitCommandSegments: () => splitCommandSegments,
@@ -12989,6 +13810,25 @@ function extractRawCommand(detail) {
12989
13810
  const m = detail.match(/command=([^,]+)/);
12990
13811
  return m ? m[1].trim() : detail;
12991
13812
  }
13813
+ function independentFileCommand(command, osType) {
13814
+ if (String(osType).toLowerCase() === "windows") return "";
13815
+ if (["\\", "#", "<<", "<(", ">(", "`", "$"].some((mark) => command.includes(mark))) return "";
13816
+ const parts = splitCommandSegments(command);
13817
+ if (parts.length !== 2) return "";
13818
+ const ordinary = parts.filter((part2) => !isInlineScriptCommand(part2.toLowerCase()));
13819
+ if (ordinary.length !== 1) return "";
13820
+ const part = ordinary[0];
13821
+ const name = part.trim().split(/\s+/)[0] || "";
13822
+ const { writeCommandRes } = getPlatformTraits(osType);
13823
+ const isWriteCommandName = writeCommandRes.some((rx) => {
13824
+ const flags = rx.flags.replace("g", "");
13825
+ return new RegExp(`^(?:${rx.source})$`, flags).test(name);
13826
+ });
13827
+ if (SHELL_FULL_READ_CMDS.includes(name) || isWriteCommandName) {
13828
+ return part;
13829
+ }
13830
+ return "";
13831
+ }
12992
13832
  function matchesAny(cmd, patterns) {
12993
13833
  return patterns.some((p) => p.test(cmd));
12994
13834
  }
@@ -13066,21 +13906,42 @@ async function runAnalysis(input) {
13066
13906
  const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
13067
13907
  const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
13068
13908
  if (heuristicResult && !heuristicResult.allowed) {
13069
- const skipInlineFileAccess = (isInlineScriptCmd || isLiteralTextCmd) && heuristicResult.riskType === "file_access";
13070
- if (!skipInlineFileAccess) {
13071
- const shouldDenyL1 = heuristicResult.riskLevel === "high" || heuristicResult.riskLevel === "critical" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "file_access" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "resource_exhaustion";
13072
- if (shouldDenyL1) {
13073
- return heuristicResult;
13909
+ let skipInlineFileAccess = (isInlineScriptCmd || isLiteralTextCmd) && heuristicResult.riskType === "file_access";
13910
+ const shouldDenyL1 = heuristicResult.riskLevel === "high" || heuristicResult.riskLevel === "critical" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "file_access" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "resource_exhaustion";
13911
+ const bashLike = ["bash", "executebash", "terminal-executebash"].includes(input.aNext.actionType.toLowerCase());
13912
+ if (skipInlineFileAccess && shouldDenyL1 && isInlineScriptCmd && bashLike) {
13913
+ const detail = input.aNext.actionDetail;
13914
+ const command = independentFileCommand(detail, input.osType);
13915
+ if (command) {
13916
+ const hit = runHeuristicCheck({ ...input, aNext: { ...input.aNext, actionDetail: command } });
13917
+ if (hit && !hit.allowed && hit.riskType === "file_access" && ["medium", "high", "critical"].includes(hit.riskLevel)) {
13918
+ return hit;
13919
+ }
13920
+ } else if (String(input.osType || "").toLowerCase() !== "windows" && heuristicResult.deniedReadPath) {
13921
+ skipInlineFileAccess = !confirmsInlineRead(detail, heuristicResult.deniedReadPath);
13074
13922
  }
13075
13923
  }
13924
+ if (!skipInlineFileAccess && shouldDenyL1) {
13925
+ return heuristicResult;
13926
+ }
13076
13927
  }
13077
13928
  const agentExt = mergeAgentExtensions(
13078
13929
  isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
13079
13930
  isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
13080
13931
  );
13932
+ const degradedNotes = [];
13081
13933
  let scriptChain = null;
13082
- if (input.aNext.actionType.toLowerCase() === "bash") {
13934
+ if (input.aNext.actionType.toLowerCase() === "bash" && getDeployRole() === "host") {
13935
+ degradedNotes.push("script_content_deferred_to_sandbox: AGENT_MOSS_DEPLOY_ROLE=host");
13936
+ } else if (input.aNext.actionType.toLowerCase() === "bash") {
13083
13937
  scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
13938
+ if (scriptChain.nodes.length > 0) {
13939
+ for (const node of scriptChain.nodes) {
13940
+ if (node.error && !node.unanalyzable) {
13941
+ degradedNotes.push(`script_content_unavailable: ${node.scriptPath} (${node.error})`);
13942
+ }
13943
+ }
13944
+ }
13084
13945
  if (heuristicEnabled && scriptChain.nodes.length > 0) {
13085
13946
  for (const node of scriptChain.nodes) {
13086
13947
  if (node.unanalyzable) {
@@ -13351,7 +14212,8 @@ async function runAnalysis(input) {
13351
14212
  riskType: "",
13352
14213
  confidence: 85,
13353
14214
  source: "heuristic_and_logic_only",
13354
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
14215
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
14216
+ degraded: degradedNotes
13355
14217
  };
13356
14218
  }
13357
14219
  let skipL3Hints = "\u65E0\uFF08\u5F53\u524D\u65E0\u7981\u7528\u89C4\u5219\u547D\u4E2D\uFF09";
@@ -13388,8 +14250,22 @@ async function runAnalysis(input) {
13388
14250
  pathContext
13389
14251
  });
13390
14252
  } catch (e) {
13391
- const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
13392
14253
  const { getLLMFailMode: getLLMFailMode2 } = await Promise.resolve().then(() => (init_config(), config_exports));
14254
+ if (e instanceof LLMPromptBudgetExceeded) {
14255
+ const failMode = getLLMFailMode2();
14256
+ const allowed = failMode === "fail_open";
14257
+ return {
14258
+ allowed,
14259
+ reason: `L3 prompt \u8D85\u51FA\u786C\u9884\u7B97\uFF0C\u5DF2\u8DF3\u8FC7\u8BED\u4E49\u5206\u6790\uFF0C\u6309 ${failMode} ${allowed ? "\u653E\u884C" : "\u62D2\u7EDD"}`,
14260
+ riskLevel: allowed ? "low" : "medium",
14261
+ riskType: "",
14262
+ confidence: allowed ? 50 : 60,
14263
+ source: "llm_budget_skipped",
14264
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
14265
+ degraded: [...degradedNotes, e.code]
14266
+ };
14267
+ }
14268
+ const failSource = e instanceof LLMCircuitOpenError ? "llm_circuit_open" : "llm_failure_fallback";
13393
14269
  if (getLLMFailMode2() === "fail_open") {
13394
14270
  console.warn(`[AgentMoss] LLM \u5206\u6790\u5931\u8D25\uFF0Cfail_open \u6A21\u5F0F\uFF1A\u5141\u8BB8\u6267\u884C\uFF08\u524D\u4E24\u5C42\u672A\u62E6\u622A\uFF09: ${e.message}`);
13395
14271
  return {
@@ -13399,7 +14275,8 @@ async function runAnalysis(input) {
13399
14275
  riskType: "",
13400
14276
  confidence: 50,
13401
14277
  source: failSource,
13402
- violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : []
14278
+ violatedLayers: observedFormalLayers.length > 0 ? [...observedFormalLayers] : [],
14279
+ degraded: degradedNotes
13403
14280
  };
13404
14281
  }
13405
14282
  return {
@@ -13409,7 +14286,10 @@ async function runAnalysis(input) {
13409
14286
  riskType: "",
13410
14287
  confidence: 60,
13411
14288
  source: failSource,
13412
- violatedLayers: ["L3.1"]
14289
+ violatedLayers: ["L3.1"],
14290
+ degraded: degradedNotes,
14291
+ ask_recommended: true,
14292
+ ask_reason: "L3 \u8BED\u4E49\u5206\u6790\u4E0D\u53EF\u7528\uFF0C\u6309 fail_closed \u62D2\u7EDD\uFF1B\u8FD9\u662F\u201C\u6CA1\u67E5\u5B8C\u201D\u800C\u975E\u201C\u786E\u8BA4\u6709\u98CE\u9669\u201D\uFF0C\u5EFA\u8BAE\u5411\u7528\u6237\u786E\u8BA4\u662F\u5426\u7EE7\u7EED\u3002"
13413
14293
  };
13414
14294
  }
13415
14295
  if (!llmResult.allowed && llmResult.confidence && llmResult.confidence >= 90 && _brainExtractor) {
@@ -13429,6 +14309,9 @@ async function runAnalysis(input) {
13429
14309
  if (observedFormalLayers.length > 0 && llmResult.allowed) {
13430
14310
  llmResult.violatedLayers = Array.from(/* @__PURE__ */ new Set([...observedFormalLayers, ...llmResult.violatedLayers || []]));
13431
14311
  }
14312
+ if (degradedNotes.length > 0) {
14313
+ llmResult.degraded = Array.from(/* @__PURE__ */ new Set([...llmResult.degraded || [], ...degradedNotes]));
14314
+ }
13432
14315
  return llmResult;
13433
14316
  }
13434
14317
  var TRUSTED_SKILLS_BASE, _brainStore, _brainExtractor, _brainSkillManager, _brainCurator, _brainInitialized, _brainLastMaintenance, BRAIN_MAINT_INTERVAL_MS, formalEngine;
@@ -13475,7 +14358,7 @@ function deriveL3Outcome(j) {
13475
14358
  if (src === "llm_failure_fallback") return j.allowed ? "fail_open" : "fail_closed";
13476
14359
  if (src === "llm_circuit_open") return "circuit_open";
13477
14360
  if (src === "llm_failure_with_violation") return "failed_but_blocked";
13478
- if (src === "heuristic_and_logic_only" || src === "disabled") return "skipped";
14361
+ if (src === "heuristic_and_logic_only" || src === "disabled" || src === "llm_budget_skipped") return "skipped";
13479
14362
  return "not_reached";
13480
14363
  }
13481
14364
  var init_types = __esm({
@@ -13486,7 +14369,7 @@ var init_types = __esm({
13486
14369
  });
13487
14370
 
13488
14371
  // src/infra/policy-cache.ts
13489
- import { createHash as createHash5 } from "crypto";
14372
+ import { createHash as createHash6 } from "crypto";
13490
14373
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
13491
14374
  import { tmpdir as tmpdir3 } from "os";
13492
14375
  import { join as join18 } from "path";
@@ -13531,7 +14414,7 @@ var init_policy_cache = __esm({
13531
14414
  return `${sessionId}::${promptSession}`;
13532
14415
  }
13533
14416
  cacheFilePath(sessionId, promptSession) {
13534
- const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
14417
+ const promptHash = createHash6("md5").update(promptSession).digest("hex").slice(0, 12);
13535
14418
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13536
14419
  return join18(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13537
14420
  }
@@ -14190,12 +15073,24 @@ import * as fs8 from "fs";
14190
15073
  import * as os5 from "os";
14191
15074
  import * as path8 from "path";
14192
15075
  function normalizeAction(row) {
14193
- return {
15076
+ const act = {
14194
15077
  actionType: String(row.action_type || row.tool_name || row.name || ""),
14195
15078
  actionDetail: String(row.action_detail || row.command || row.input || "")
14196
15079
  };
15080
+ if (row.called_at) act.calledAt = String(row.called_at);
15081
+ try {
15082
+ const audit = JSON.parse(String(row.moss_response || "{}"));
15083
+ if (audit && audit._gate_protocol_rejected === true) {
15084
+ act.gateProtocolRejected = true;
15085
+ } else if (audit && typeof audit._gate_call_id === "string" && /^[0-9a-f]{32}$/.test(audit._gate_call_id) && Number.isInteger(audit._gate_call_time_us) && audit._gate_call_time_us > 0) {
15086
+ act.gateCallId = audit._gate_call_id;
15087
+ act.gateCallTimeUs = audit._gate_call_time_us;
15088
+ }
15089
+ } catch {
15090
+ }
15091
+ return act;
14197
15092
  }
14198
- function readJsonDir(dirPath, limit = 1e5) {
15093
+ function readJsonDir(dirPath, limit = 1e5, strict = false) {
14199
15094
  const sessions = /* @__PURE__ */ new Map();
14200
15095
  try {
14201
15096
  const files = fs8.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
@@ -14217,24 +15112,34 @@ function readJsonDir(dirPath, limit = 1e5) {
14217
15112
  for (const v of sessions.values()) total += v.length;
14218
15113
  if (total > limit) break;
14219
15114
  }
14220
- } catch {
15115
+ } catch (err) {
15116
+ if (strict) throw err;
14221
15117
  }
14222
15118
  return [...sessions.entries()].map(([sessionId, actionHistory]) => ({ sessionId, actionHistory }));
14223
15119
  }
14224
- function readSqlite(dbPath, limit = 1e5) {
15120
+ function readSqlite(dbPath, limit = 1e5, strict = false) {
14225
15121
  let Database;
14226
15122
  try {
14227
15123
  Database = esmRequire("better-sqlite3");
14228
- } catch {
15124
+ } catch (err) {
15125
+ if (strict) throw err;
14229
15126
  return [];
14230
15127
  }
14231
15128
  let db;
14232
15129
  try {
14233
15130
  db = new Database(dbPath, { readonly: true });
14234
- const rows = db.prepare(
14235
- `SELECT session_id, action_type, tool_name, action_detail, command, called_at
14236
- FROM tool_calls ORDER BY called_at, id LIMIT ?`
14237
- ).all(limit);
15131
+ let rows;
15132
+ try {
15133
+ rows = db.prepare(
15134
+ `SELECT session_id, action_type, tool_name, action_detail, command, called_at, moss_response
15135
+ FROM tool_calls ORDER BY called_at, id LIMIT ?`
15136
+ ).all(limit);
15137
+ } catch {
15138
+ rows = db.prepare(
15139
+ `SELECT session_id, action_type, tool_name, action_detail, command, called_at
15140
+ FROM tool_calls ORDER BY called_at, id LIMIT ?`
15141
+ ).all(limit);
15142
+ }
14238
15143
  const sessions = /* @__PURE__ */ new Map();
14239
15144
  for (const r of rows) {
14240
15145
  const sid = String(r.session_id || "");
@@ -14246,7 +15151,8 @@ function readSqlite(dbPath, limit = 1e5) {
14246
15151
  sessions.set(sid, list);
14247
15152
  }
14248
15153
  return [...sessions.entries()].map(([sessionId, actionHistory]) => ({ sessionId, actionHistory }));
14249
- } catch {
15154
+ } catch (err) {
15155
+ if (strict) throw err;
14250
15156
  return [];
14251
15157
  } finally {
14252
15158
  try {
@@ -14257,15 +15163,10 @@ function readSqlite(dbPath, limit = 1e5) {
14257
15163
  }
14258
15164
  function loadAgentGateSessions(dbPath = "") {
14259
15165
  if (dbPath) {
14260
- try {
14261
- if (fs8.statSync(dbPath).isDirectory()) {
14262
- return readJsonDir(dbPath);
14263
- }
14264
- } catch {
14265
- }
14266
- const sql2 = readSqlite(dbPath);
14267
- if (sql2.length > 0) return sql2;
14268
- return readJsonDir(dbPath);
15166
+ const target = dbPath.replace(/^~(?=$|\/)/, os5.homedir());
15167
+ const stat = fs8.statSync(target);
15168
+ if (stat.isDirectory()) return readJsonDir(target, 1e5, true);
15169
+ return readSqlite(target, 1e5, true);
14269
15170
  }
14270
15171
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
14271
15172
  if (sql.length > 0) return sql;
@@ -14473,6 +15374,10 @@ async function analyzeRoute(c) {
14473
15374
  try {
14474
15375
  const body = await c.req.json();
14475
15376
  const req = AnalyzeRequestSchema.parse(normalizeObservablePayload(body));
15377
+ const gateCallId = String(c.get("gateCallId") || "");
15378
+ if (gateCallId && (req.gate_call_id !== gateCallId || !validGateCallTime(req.gate_call_time_us) || typeof req.gate_delivery_uncertain !== "boolean")) {
15379
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5143\u6570\u636E\u65E0\u6548" }, 422);
15380
+ }
14476
15381
  const unmappedTool = String(
14477
15382
  req.metadata?.unmapped_tool || ""
14478
15383
  );
@@ -14519,7 +15424,7 @@ async function analyzeRoute(c) {
14519
15424
  session_history: req.session_history,
14520
15425
  metadata: req.metadata
14521
15426
  });
14522
- const result = await analyze({
15427
+ let result = await analyze({
14523
15428
  sessionId: req.session_id,
14524
15429
  promptSession: req.prompt_session,
14525
15430
  // output 必须透传:L2 的「授权(consent)」判定看的是**用户对提问的回答**,
@@ -14577,7 +15482,86 @@ async function analyzeRoute(c) {
14577
15482
  llmConfig: perRequestLlmEnabled() ? req.metadata?.llm_config : void 0,
14578
15483
  llmLogPath: req.metadata?.llm_log_path
14579
15484
  });
15485
+ const meta = req.metadata || {};
15486
+ const incEnabled = String(meta.stateful_incremental || "").toLowerCase();
15487
+ let finding = null;
15488
+ if (incEnabled === "1" || incEnabled === "true" || incEnabled === "yes" || incEnabled === "on") {
15489
+ try {
15490
+ const store = getChainStateStoreFor(agentId);
15491
+ const inc = store.applyAction(
15492
+ chainBucket(agentId),
15493
+ {
15494
+ actionType: req.a_next.action_type,
15495
+ actionDetail: req.a_next.action_detail,
15496
+ ...req.a_next.called_at ? { calledAt: req.a_next.called_at } : {},
15497
+ ...gateCallId ? {
15498
+ gateCallId,
15499
+ gateCallTimeUs: req.gate_call_time_us,
15500
+ gateDeliveryUncertain: req.gate_delivery_uncertain === true
15501
+ } : {}
15502
+ },
15503
+ req.session_id,
15504
+ Boolean(meta.is_error),
15505
+ agentId,
15506
+ // 来源:真实 agent(桶 key 可能是 __system__)
15507
+ instanceId
15508
+ );
15509
+ try {
15510
+ const total = store.stats().nodes;
15511
+ const pct = Math.round(total / MAX_NODES * 1e3) / 10;
15512
+ if (total >= MAX_NODES) {
15513
+ degradedNotes.push(
15514
+ `\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`
15515
+ );
15516
+ } else if (pct >= 90) {
15517
+ degradedNotes.push(
15518
+ `\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`
15519
+ );
15520
+ }
15521
+ } catch {
15522
+ }
15523
+ finding = incMatchedToDeny(inc);
15524
+ } catch (err) {
15525
+ if (err instanceof UnconfirmedGateRetry) {
15526
+ const reason = "AgentMoss \u65E0\u6CD5\u786E\u8BA4\u672C\u6B21 Gate \u8C03\u7528\u662F\u5426\u5DF2\u5165\u94FE";
15527
+ degradedNotes.push(`\u3010\u5DF2\u964D\u7EA7\u3011${reason}\uFF1B\u672C\u6B21\u6309\u62D2\u7EDD\u5904\u7406\uFF0C\u907F\u514D\u91CD\u590D\u5165\u94FE\u3002`);
15528
+ if (result.decision !== "Deny") {
15529
+ result = {
15530
+ ...result,
15531
+ decision: "Deny",
15532
+ reason,
15533
+ risk_type: "service_unavailable",
15534
+ risk_level: "high",
15535
+ policy: "",
15536
+ ask_recommended: true,
15537
+ ask_reason: "\u65E0\u6CD5\u786E\u8BA4\u672C\u6B21 Gate \u8C03\u7528\u662F\u5426\u5DF2\u5165\u94FE\uFF1B\u8FD9\u662F\u201C\u6CA1\u67E5\u5B8C\u201D\u800C\u975E\u201C\u786E\u8BA4\u6709\u98CE\u9669\u201D\uFF0C\u5EFA\u8BAE\u5411\u7528\u6237\u786E\u8BA4\u662F\u5426\u7EE7\u7EED\u3002"
15538
+ };
15539
+ }
15540
+ } else if (err instanceof StatefulAnalysisUnavailable) {
15541
+ degradedNotes.push(
15542
+ "\u3010\u5DF2\u964D\u7EA7\u3011\u6709\u72B6\u6001\u5206\u6790\u4E0D\u53EF\u7528\uFF08\u94FE\u72B6\u6001\u5B58\u50A8\u4E0D\u53EF\u7528\u6216\u672C\u6B21\u52A8\u4F5C\u8D85\u51FA\u4FDD\u7559\u7A97\u53E3\uFF09\uFF1A\u672C\u6B21\u52A8\u4F5C\u672A\u53C2\u4E0E L2.2 \u7EC4\u5408\u94FE\u68C0\u6D4B\uFF1BL1/L2.1/L3 \u5224\u5B9A\u4E0D\u53D7\u5F71\u54CD\u3002"
15543
+ );
15544
+ } else {
15545
+ console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
15546
+ degradedNotes.push(
15547
+ "\u3010\u5DF2\u964D\u7EA7\u3011\u6709\u72B6\u6001\u5206\u6790\u4E0D\u53EF\u7528\uFF08\u5185\u90E8\u5F02\u5E38\uFF09\uFF1A\u672C\u6B21\u52A8\u4F5C\u672A\u53C2\u4E0E L2.2 \u7EC4\u5408\u94FE\u68C0\u6D4B\uFF1BL1/L2.1/L3 \u5224\u5B9A\u4E0D\u53D7\u5F71\u54CD\u3002"
15548
+ );
15549
+ }
15550
+ }
15551
+ }
15552
+ result = publicFormalResult(
15553
+ result,
15554
+ finding,
15555
+ instanceId,
15556
+ req.session_id,
15557
+ req.session_history || []
15558
+ );
14580
15559
  const durationMs = performance.now() - t0;
15560
+ if (Array.isArray(result.degraded)) {
15561
+ for (const note of result.degraded) {
15562
+ if (note && !degradedNotes.includes(note)) degradedNotes.push(note);
15563
+ }
15564
+ }
14581
15565
  const _l3FailMsg = String(result.reason || "").slice(0, 160);
14582
15566
  if (result.l3_outcome === "reasoning_fallback") {
14583
15567
  degradedNotes.push(
@@ -14611,8 +15595,10 @@ async function analyzeRoute(c) {
14611
15595
  l3_outcome: result.l3_outcome || ""
14612
15596
  });
14613
15597
  ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
14614
- for (const layer of result.violated_layers || []) {
14615
- LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
15598
+ for (const layer of new Set(
15599
+ (result.violated_layers || []).map((layer2) => String(layer2).split("-")[0])
15600
+ )) {
15601
+ LAYER_HIT_TOTAL.inc(1, { layer });
14616
15602
  }
14617
15603
  } catch {
14618
15604
  }
@@ -14644,62 +15630,6 @@ async function analyzeRoute(c) {
14644
15630
  });
14645
15631
  } catch {
14646
15632
  }
14647
- const meta = req.metadata || {};
14648
- const incEnabled = String(meta.stateful_incremental || "").toLowerCase();
14649
- if (incEnabled === "1" || incEnabled === "true" || incEnabled === "yes" || incEnabled === "on") {
14650
- try {
14651
- const store = getChainStateStoreFor(agentId);
14652
- const inc = store.applyAction(
14653
- chainBucket(agentId),
14654
- { actionType: req.a_next.action_type, actionDetail: req.a_next.action_detail },
14655
- req.session_id,
14656
- Boolean(meta.is_error),
14657
- agentId,
14658
- // 来源:真实 agent(桶 key 可能是 __system__)
14659
- instanceId
14660
- );
14661
- try {
14662
- const total = store.stats().nodes;
14663
- const pct = Math.round(total / MAX_NODES * 1e3) / 10;
14664
- if (total >= MAX_NODES) {
14665
- degradedNotes.push(
14666
- `\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`
14667
- );
14668
- } else if (pct >= 90) {
14669
- degradedNotes.push(
14670
- `\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`
14671
- );
14672
- }
14673
- } catch {
14674
- }
14675
- const judgment = incMatchedToDeny(inc);
14676
- if (judgment) {
14677
- const layers = [...result.violated_layers];
14678
- if (!layers.includes("L2.2-stateful")) layers.push("L2.2-stateful");
14679
- console.error(
14680
- `[AgentMoss] stateful \u589E\u91CF\u62E6\u622A: agent=${agentId || "-"} property=${judgment.property_id} risk=${judgment.risk_level}`
14681
- );
14682
- return c.json(
14683
- AnalyzeResponseSchema.parse({
14684
- decision: "Deny",
14685
- reason: judgment.reason,
14686
- risk_level: judgment.risk_level,
14687
- risk_type: "formal_verification",
14688
- violated_layers: layers,
14689
- policy: "",
14690
- violated_policy: "",
14691
- confidence: 90,
14692
- analysis_duration_ms: Math.round((performance.now() - t0) * 10) / 10,
14693
- // 跨会话节点脱敏(时间线按 agent_id 共享,原样返回等于泄露别人的命令原文)
14694
- violation_chain: redactChain(judgment.violation_chain, instanceId, req.session_id),
14695
- violation_graph: redactGraph(judgment.violation_graph, instanceId, req.session_id)
14696
- })
14697
- );
14698
- }
14699
- } catch (err) {
14700
- console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
14701
- }
14702
- }
14703
15633
  return c.json(
14704
15634
  AnalyzeResponseSchema.parse({
14705
15635
  decision: result.decision,
@@ -14713,13 +15643,18 @@ async function analyzeRoute(c) {
14713
15643
  violated_policy: result.violated_policy,
14714
15644
  confidence: result.confidence,
14715
15645
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
15646
+ // 已在 publicFormalResult 中按静态/增量来源选定并脱敏;这里不能再按
15647
+ // 真实 session 二次脱敏,否则会把静态引擎的 `current` 别名节点误隐藏。
14716
15648
  violation_chain: result.violation_chain ?? [],
14717
- violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
15649
+ violation_graph: result.violation_graph ?? null,
14718
15650
  // 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
14719
15651
  degraded: degradedNotes,
14720
15652
  // L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
14721
15653
  // 「L3 判过的 Allow」与「L3 挂了 fail_open 放的」。
14722
- l3_outcome: result.l3_outcome || ""
15654
+ l3_outcome: result.l3_outcome || "",
15655
+ ask_recommended: result.ask_recommended === true,
15656
+ ask_reason: String(result.ask_reason || ""),
15657
+ ...gateCallId ? { gate_call_id: gateCallId } : {}
14723
15658
  })
14724
15659
  );
14725
15660
  } catch (err) {
@@ -14741,6 +15676,83 @@ async function analyzeRoute(c) {
14741
15676
  function getChainStateStoreFor(_agentId) {
14742
15677
  return getChainStateStore();
14743
15678
  }
15679
+ function mergeStatefulDenial(result, finding) {
15680
+ const level = String(finding.risk_level || "high");
15681
+ const outcome = result.l3_outcome;
15682
+ 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);
15683
+ const merged = { ...result };
15684
+ if (statefulWins) {
15685
+ const reason = finding.reason || "\u6709\u72B6\u6001\u589E\u91CF\u94FE\u5224\u5B9A\uFF1A\u7EC4\u5408\u653B\u51FB\u94FE\u547D\u4E2D";
15686
+ Object.assign(merged, {
15687
+ decision: "Deny",
15688
+ reason,
15689
+ risk_level: level,
15690
+ risk_type: "formal_verification",
15691
+ source: "formal_engine",
15692
+ confidence: 90,
15693
+ policy: "",
15694
+ violated_policy: `[formal_verification] ${reason}`
15695
+ });
15696
+ }
15697
+ const layers = Array.isArray(result.violated_layers) ? result.violated_layers : [];
15698
+ merged.violated_layers = [.../* @__PURE__ */ new Set([...layers, "L2.2-stateful"])];
15699
+ if (outcome === "fail_open" || outcome === "fail_closed") {
15700
+ merged.l3_outcome = "failed_but_blocked";
15701
+ }
15702
+ console.error(
15703
+ `[AgentMoss] stateful \u589E\u91CF\u62E6\u622A: property=${finding.property_id || "?"} risk=${level} final_risk=${merged.risk_level}`
15704
+ );
15705
+ return { result: merged, wins: statefulWins };
15706
+ }
15707
+ function publicFormalResult(result, finding, instanceId, sessionId, sessionHistory) {
15708
+ let graph = result.violation_graph;
15709
+ let chain = result.violation_chain;
15710
+ let propertyId = graph?.property_id;
15711
+ let staticEvidence = Boolean(chain && chain.length || graph);
15712
+ if (!finding && !staticEvidence) return result;
15713
+ if (finding) {
15714
+ const merged = mergeStatefulDenial(result, finding);
15715
+ result = merged.result;
15716
+ if (merged.wins) propertyId = finding.property_id;
15717
+ const incrementalGraph = finding.violation_graph || {};
15718
+ const fillsMissingGraph = !graph && (finding.risk_level || "high") === result.risk_level && finding.violation_chain && incrementalGraph.nodes;
15719
+ if (merged.wins || !staticEvidence || fillsMissingGraph) {
15720
+ chain = finding.violation_chain;
15721
+ graph = incrementalGraph;
15722
+ staticEvidence = false;
15723
+ }
15724
+ }
15725
+ let publicSessionId = sessionId;
15726
+ let alias = "";
15727
+ if (staticEvidence) {
15728
+ if (!sessionHistory.some((s) => s.session_id === "current")) {
15729
+ alias = "current";
15730
+ } else if (publicSessionId === "current") {
15731
+ publicSessionId = "";
15732
+ }
15733
+ }
15734
+ const publicGraph = redactGraph(graph, instanceId, publicSessionId, { sessionAlias: alias });
15735
+ const out = {
15736
+ ...result,
15737
+ violation_chain: redactChain(chain || [], instanceId, publicSessionId, {
15738
+ graph,
15739
+ sessionAlias: alias
15740
+ }),
15741
+ violation_graph: publicGraph
15742
+ };
15743
+ if (propertyId === "sensitive-data-flow" && chainDetailMode() !== "full") {
15744
+ const nodes = publicGraph?.nodes || [];
15745
+ let reason = "\u654F\u611F\u6570\u636E\u4F20\u64AD\u5916\u4F20\uFF1A\u68C0\u6D4B\u5230\u7ECF\u5171\u4EAB\u8F7D\u4F53\u5916\u53D1";
15746
+ if (nodes.length >= 2) {
15747
+ const src = nodes[0];
15748
+ const dst = nodes[nodes.length - 1];
15749
+ 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`;
15750
+ }
15751
+ out.reason = reason;
15752
+ out.violated_policy = `[formal_verification] ${reason}`;
15753
+ }
15754
+ return out;
15755
+ }
14744
15756
  function incMatchedToDeny(inc) {
14745
15757
  if (inc.matched) {
14746
15758
  const chain = (inc.matched.path || []).map((p) => [p.sessionId, p.seq, p.stage, p.timestamp, p.agentId ?? null]);
@@ -14770,12 +15782,6 @@ async function reviewRoute(c) {
14770
15782
  const body = await c.req.json();
14771
15783
  const req = ReviewRequestSchema.parse(body);
14772
15784
  const agentId = req.agent_id || "default";
14773
- const store = getChainStateStoreFor(agentId);
14774
- const bucket = chainBucket(agentId);
14775
- let tracker = store.load(bucket);
14776
- if (!tracker) {
14777
- tracker = new StatefulChainTracker(bucket);
14778
- }
14779
15785
  if (req.db_path && !pathWithin(req.db_path, reviewRoots())) {
14780
15786
  return c.json({
14781
15787
  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"
@@ -14783,24 +15789,39 @@ async function reviewRoute(c) {
14783
15789
  }
14784
15790
  let sessions = [];
14785
15791
  if (req.db_path) {
14786
- sessions = loadAgentGateSessions(req.db_path);
14787
- if (sessions.length === 0) sessions = (req.sessions || []).map((s) => ({
14788
- sessionId: s.session_id,
14789
- actionHistory: s.action_history.map((a) => ({ actionType: a.action_type, actionDetail: a.action_detail }))
14790
- }));
15792
+ try {
15793
+ sessions = loadAgentGateSessions(req.db_path);
15794
+ } catch (err) {
15795
+ if (err?.code === "ENOENT") {
15796
+ return c.json({ detail: "\u6307\u5B9A\u7684\u56DE\u987E\u8DEF\u5F84\u4E0D\u5B58\u5728" }, 404);
15797
+ }
15798
+ throw err;
15799
+ }
14791
15800
  } else {
14792
15801
  sessions = (req.sessions || []).map((s) => ({
14793
15802
  sessionId: s.session_id,
14794
- actionHistory: s.action_history.map((a) => ({ actionType: a.action_type, actionDetail: a.action_detail }))
15803
+ actionHistory: s.action_history.map((a) => ({ actionType: a.action_type, actionDetail: a.action_detail, calledAt: a.called_at }))
14795
15804
  }));
14796
15805
  }
14797
- const added = sessions.length > 0 ? tracker.seed(sessions) : 0;
15806
+ const explicitEmpty = !!req.db_path && sessions.length === 0;
15807
+ const store = getChainStateStoreFor(agentId);
15808
+ const bucket = chainBucket(agentId);
15809
+ let tracker = store.load(bucket);
15810
+ if (!tracker) {
15811
+ tracker = new StatefulChainTracker(bucket);
15812
+ }
15813
+ const seedSessions = sessions.map((s) => ({
15814
+ ...s,
15815
+ actionHistory: (s.actionHistory || []).filter((a) => !a.gateProtocolRejected)
15816
+ }));
15817
+ const added = seedSessions.length > 0 ? tracker.seed(seedSessions) : 0;
14798
15818
  store.save(tracker);
14799
15819
  let verified = true;
14800
15820
  const violations = [];
14801
- if (sessions.length > 0 || tracker.nodes.length > 0) {
15821
+ const shouldVerify = explicitEmpty ? Boolean(req.a_next) : sessions.length > 0 || tracker.nodes.length > 0;
15822
+ if (shouldVerify) {
14802
15823
  const eng = new FormalEngine();
14803
- const verifySessions = sessions.length > 0 ? sessions.map((s) => ({ sessionId: s.sessionId, actionHistory: s.actionHistory })) : tracker.nodes.length > 0 ? [{
15824
+ const verifySessions = explicitEmpty ? [] : sessions.length > 0 ? sessions.map((s) => ({ sessionId: s.sessionId, actionHistory: s.actionHistory })) : tracker.nodes.length > 0 ? [{
14804
15825
  sessionId: tracker.agentId,
14805
15826
  actionHistory: tracker.nodes.map((n) => ({
14806
15827
  actionType: n.actionType,
@@ -14948,7 +15969,7 @@ async function brainImportRoute(c) {
14948
15969
  })));
14949
15970
  return c.json({ imported: rules.length });
14950
15971
  }
14951
- var __dirname9;
15972
+ var __dirname9, RISK_PRIORITY;
14952
15973
  var init_routes = __esm({
14953
15974
  "src/routes.ts"() {
14954
15975
  "use strict";
@@ -14958,6 +15979,7 @@ var init_routes = __esm({
14958
15979
  init_analyzer();
14959
15980
  init_actrail();
14960
15981
  init_formal_engine();
15982
+ init_stateful();
14961
15983
  init_circuit_breaker();
14962
15984
  init_pattern_miner();
14963
15985
  init_agent_gate_reader();
@@ -14970,6 +15992,7 @@ var init_routes = __esm({
14970
15992
  init_runtime_stats();
14971
15993
  init_metrics();
14972
15994
  __dirname9 = dirname13(fileURLToPath10(import.meta.url));
15995
+ RISK_PRIORITY = { low: 0, medium: 1, high: 2, critical: 3 };
14973
15996
  }
14974
15997
  });
14975
15998
 
@@ -15506,9 +16529,29 @@ function createApp() {
15506
16529
  if (!okAuth && !isPublicPage) {
15507
16530
  return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
15508
16531
  }
16532
+ let gateCallId = null;
16533
+ const gateRequired = c.req.header(GATE_IDENTITY_HEADER);
16534
+ const gatePath = path9.replace(/\/+$/, "");
16535
+ if (method === "POST" && gateRequired !== void 0 && (gatePath === "/api/v1/analyze" || gatePath === "/api/v1/review")) {
16536
+ if (principal !== GATE_PRINCIPAL) {
16537
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8EAB\u4EFD\u6821\u9A8C\u5931\u8D25" }, 403);
16538
+ }
16539
+ if (gateRequired !== "1") {
16540
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
16541
+ }
16542
+ }
16543
+ if (method === "POST" && gatePath === "/api/v1/analyze" && principal === GATE_PRINCIPAL) {
16544
+ const id = c.req.header(GATE_CALL_ID_HEADER) || "";
16545
+ if (gateRequired !== "1" || !validGateCallId(id)) {
16546
+ return c.json({ detail: "AgentGate \u4E13\u7528\u8BF7\u6C42\u5934\u65E0\u6548" }, 422);
16547
+ }
16548
+ gateCallId = id;
16549
+ c.set("gateCallId", id);
16550
+ }
15509
16551
  if (limiter.enabled && path9.startsWith("/api/")) {
15510
16552
  const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
15511
16553
  if (!limiter.allow(key)) {
16554
+ if (gateCallId) c.header(GATE_RATE_LIMIT_HEADER, gateCallId);
15512
16555
  return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
15513
16556
  }
15514
16557
  }
@@ -15524,6 +16567,7 @@ function createApp() {
15524
16567
  const busy = (detail, status = 503) => {
15525
16568
  c.header("Retry-After", "1");
15526
16569
  c.header("Connection", "close");
16570
+ if (gateCallId) c.header(GATE_BUSY_HEADER, gateCallId);
15527
16571
  return c.json({ detail }, status);
15528
16572
  };
15529
16573
  try {
@@ -16276,7 +17320,7 @@ async function main() {
16276
17320
  const expectInstance = process.env.AGENT_MOSS_INSTANCE || "";
16277
17321
  let foundPort = 0;
16278
17322
  let version2 = "";
16279
- const otherInstances = [];
17323
+ const seen = [];
16280
17324
  for (let port = 9090; port <= 9095; port++) {
16281
17325
  try {
16282
17326
  const data = await new Promise((resolve12, reject) => {
@@ -16291,22 +17335,30 @@ async function main() {
16291
17335
  }
16292
17336
  });
16293
17337
  });
17338
+ req.on("timeout", () => req.destroy(new Error("probe timeout")));
16294
17339
  req.on("error", reject);
16295
17340
  });
16296
- if (data.status === "healthy") {
17341
+ if (data.status === "healthy" || data.status === "degraded") {
16297
17342
  const inst = data.instance || "";
16298
- if (inst === expectInstance) {
17343
+ const ver = data.version || "";
17344
+ seen.push({ port, instance: inst, version: ver });
17345
+ if (!foundPort && inst === expectInstance) {
16299
17346
  foundPort = port;
16300
- version2 = data.version || "";
16301
- break;
17347
+ version2 = ver;
16302
17348
  }
16303
- otherInstances.push({ port, instance: inst });
16304
17349
  }
16305
17350
  } catch {
16306
17351
  }
16307
17352
  }
17353
+ const otherInstances = seen.filter((s) => s.port !== foundPort);
16308
17354
  if (foundPort) {
16309
17355
  console.log(`\u2705 AgentMoss \u670D\u52A1\u8FD0\u884C\u4E2D`);
17356
+ console.log(` Instance: ${expectInstance || "(\u672A\u6307\u5B9A)"}`);
17357
+ if (!expectInstance && seen.length > 1) {
17358
+ console.log(
17359
+ " \u26A0\uFE0F \u672A\u8BBE\u7F6E AGENT_MOSS_INSTANCE\uFF0C\u4E0A\u9762\u663E\u793A\u7684\u662F\u7B2C\u4E00\u4E2A instance \u4E3A\u7A7A\u7684\u5B9E\u4F8B\uFF1B\u540C\u673A\u7684\u5176\u5B83\u5B9E\u4F8B\u89C1\u4E0B\u65B9\u6E05\u5355"
17360
+ );
17361
+ }
16310
17362
  console.log(` \u7248\u672C: ${version2 || "?"}`);
16311
17363
  console.log(` \u7AEF\u53E3: ${foundPort}`);
16312
17364
  console.log(` Console: http://127.0.0.1:${foundPort}/console`);
@@ -16329,6 +17381,7 @@ async function main() {
16329
17381
  }
16330
17382
  });
16331
17383
  });
17384
+ req.on("timeout", () => req.destroy(new Error("probe timeout")));
16332
17385
  req.on("error", reject);
16333
17386
  });
16334
17387
  const layers = data.layers || {};
@@ -16340,6 +17393,15 @@ async function main() {
16340
17393
  console.log(` L3 LLM \u5206\u6790: ${l3}`);
16341
17394
  } catch {
16342
17395
  }
17396
+ if (otherInstances.length > 0) {
17397
+ console.log();
17398
+ console.log(` \u26A0\uFE0F \u540C\u673A\u53E6\u6709 ${otherInstances.length} \u4E2A\u5B9E\u4F8B\uFF08\u672A\u8BA1\u5165\u4E0A\u9762\u7684\u72B6\u6001\uFF09\uFF1A`);
17399
+ for (const o of otherInstances) {
17400
+ const tag = o.instance === expectInstance ? " \u2190 \u4E0E\u672C\u5B9E\u4F8B\u540C\u540D\uFF08\u53EF\u80FD\u662F\u5347\u7EA7\u540E\u672A\u9000\u51FA\u7684\u65E7/\u65B0\u8FDB\u7A0B\uFF09" : "";
17401
+ console.log(` \u7AEF\u53E3 ${o.port} instance=${o.instance || "(\u7A7A)"} v${o.version || "?"}${tag}`);
17402
+ }
17403
+ console.log(" \u67E5\u770B\u6307\u5B9A\u5B9E\u4F8B\uFF1AAGENT_MOSS_INSTANCE=<\u540D\u5B57> agent-moss status");
17404
+ }
16343
17405
  console.log();
16344
17406
  console.log(" \u542F\u505C\u547D\u4EE4\uFF1A");
16345
17407
  console.log(" systemctl start agent-moss \u542F\u52A8");
@@ -16348,15 +17410,15 @@ async function main() {
16348
17410
  console.log(" systemctl status agent-moss \u72B6\u6001");
16349
17411
  console.log(" journalctl -u agent_moss -f \u65E5\u5FD7");
16350
17412
  } else if (otherInstances.length > 0) {
16351
- console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C\uFF08instance=${expectInstance || "(\u7A7A)"}\uFF09`);
17413
+ console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C\uFF08instance=${expectInstance || "(\u672A\u6307\u5B9A)"}\uFF09`);
16352
17414
  console.log(` Systemd: ${systemdInfo ? "active" : "inactive"}`);
16353
- const detail = otherInstances.map((o) => `\u7AEF\u53E3 ${o.port} (instance=${o.instance || "(\u7A7A)"})`).join("; ");
17415
+ const detail = otherInstances.map((o) => `\u7AEF\u53E3 ${o.port} (instance=${o.instance || "(\u7A7A)"}, v${o.version || "?"})`).join("; ");
16354
17416
  console.log(` \u26A0\uFE0F \u68C0\u6D4B\u5230\u5176\u4ED6 agent \u7684 agentmoss \u5B9E\u4F8B: ${detail}`);
16355
- console.log(` \u8FD9\u4E9B\u4E0D\u5C5E\u4E8E\u672C\u5B9E\u4F8B\uFF08instance=${expectInstance || "(\u7A7A)"}\uFF09\uFF0C\u672A\u8BA1\u5165\u8FD0\u884C\u72B6\u6001\u3002`);
17417
+ console.log(` \u8FD9\u4E9B\u4E0D\u5C5E\u4E8E\u672C\u5B9E\u4F8B\uFF08instance=${expectInstance || "(\u672A\u6307\u5B9A)"}\uFF09\uFF0C\u672A\u8BA1\u5165\u8FD0\u884C\u72B6\u6001\u3002`);
16356
17418
  console.log(` \u542F\u52A8\u672C\u5B9E\u4F8B: AGENT_MOSS_INSTANCE=${expectInstance || "xiaoo"} agent-moss server`);
16357
17419
  process.exit(1);
16358
17420
  } else {
16359
- console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C`);
17421
+ console.log(`\u274C AgentMoss \u670D\u52A1\u672A\u8FD0\u884C\uFF08instance=${expectInstance || "(\u672A\u6307\u5B9A)"}\uFF09`);
16360
17422
  if (systemdInfo) {
16361
17423
  console.log(` Systemd: active \u4F46\u7AEF\u53E3\u63A2\u6D4B\u4E0D\u5230`);
16362
17424
  console.log(` \u68C0\u67E5\u65E5\u5FD7\uFF1Ajournalctl -u agent_moss -n 20 --no-pager`);