@kenhkl/agent-moss 0.17.28 → 0.17.30
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 +137 -39
- package/dist/engine/coordinator.js +83 -18
- package/dist/server.js +123 -25
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1408,15 +1408,23 @@ var init_package_json = __esm({
|
|
|
1408
1408
|
|
|
1409
1409
|
// src/models.ts
|
|
1410
1410
|
import { z } from "zod";
|
|
1411
|
-
var ActionItemSchema, PromptTurnSchema, AnalyzeRequestSchema, AnalyzeResponseSchema, HealthResponseSchema, ReviewRequestSchema, ReviewResponseSchema;
|
|
1411
|
+
var isNonEmptyNoControl, ActionItemSchema, PromptTurnSchema, AnalyzeRequestSchema, AnalyzeResponseSchema, HealthResponseSchema, ReviewRequestSchema, ReviewResponseSchema;
|
|
1412
1412
|
var init_models = __esm({
|
|
1413
1413
|
"src/models.ts"() {
|
|
1414
1414
|
"use strict";
|
|
1415
1415
|
init_esm_shims();
|
|
1416
1416
|
init_package_json();
|
|
1417
|
+
isNonEmptyNoControl = (v) => v.trim().length > 0 && ![...v].some((c) => {
|
|
1418
|
+
const n = c.codePointAt(0) ?? 0;
|
|
1419
|
+
return n < 32 || n >= 127 && n <= 159;
|
|
1420
|
+
});
|
|
1417
1421
|
ActionItemSchema = z.object({
|
|
1418
|
-
action_type: z.string().
|
|
1419
|
-
|
|
1422
|
+
action_type: z.string().refine(isNonEmptyNoControl, {
|
|
1423
|
+
message: "action_type must be nonempty and contain no control characters"
|
|
1424
|
+
}).describe("Action type, e.g. bash, file_read, file_write"),
|
|
1425
|
+
action_detail: z.string().refine((v) => !v.includes("\0"), {
|
|
1426
|
+
message: "action_detail must not contain NUL characters"
|
|
1427
|
+
}).describe("Action detail / command content"),
|
|
1420
1428
|
// 工具返回给 agent 的内容。仅 L2 的授权(consent)判定用:判断「用户是否已授权」
|
|
1421
1429
|
// 看的是 ask_user_question 的**回答**,不是提问正文。历史 bug:模型里没有这个字段、
|
|
1422
1430
|
// 路由也没透传,TS 的授权判定退化成「提问正文非空」,等于问过任何问题即已授权。
|
|
@@ -1509,6 +1517,8 @@ var init_models = __esm({
|
|
|
1509
1517
|
// 降级原因(status=degraded 时非空)
|
|
1510
1518
|
degraded: z.array(z.string()).default([]),
|
|
1511
1519
|
version: z.string().default(version),
|
|
1520
|
+
// 实际监听端口(端口被占用自动漂移后,调用方从这里得知新端口)。
|
|
1521
|
+
port: z.number().default(0),
|
|
1512
1522
|
// 归属实例标识:值来自 env AGENT_MOSS_INSTANCE(spawn/systemd 注入),默认空串。
|
|
1513
1523
|
// 多个 agentmoss 同机并存时,调用方按 instance 过滤避免连到别人的进程。
|
|
1514
1524
|
// 空=未配置(独立部署或旧版),调用方可选择兼容或严格过滤。
|
|
@@ -5414,7 +5424,16 @@ function runHeuristicCheck(input) {
|
|
|
5414
5424
|
}
|
|
5415
5425
|
}
|
|
5416
5426
|
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();
|
|
5417
|
-
|
|
5427
|
+
let pythonWalkOnerrorOnly = false;
|
|
5428
|
+
if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
|
|
5429
|
+
pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
|
|
5430
|
+
}
|
|
5431
|
+
const injectionHits = checkInjectionKeywords(
|
|
5432
|
+
injectionText,
|
|
5433
|
+
agentExt?.extra_injection_keywords,
|
|
5434
|
+
input.osType,
|
|
5435
|
+
pythonWalkOnerrorOnly
|
|
5436
|
+
);
|
|
5418
5437
|
if (injectionHits.length > 0) {
|
|
5419
5438
|
const topHit = injectionHits.reduce((a, b) => severityRank(a.riskLevel) >= severityRank(b.riskLevel) ? a : b);
|
|
5420
5439
|
matched.push(...injectionHits.map((h) => `\u6CE8\u5165\u5173\u952E\u8BCD [${h.lang}]: ${h.keyword}`));
|
|
@@ -5463,10 +5482,27 @@ function runHeuristicCheck(input) {
|
|
|
5463
5482
|
if (lateralResult) return lateralResult;
|
|
5464
5483
|
return null;
|
|
5465
5484
|
}
|
|
5466
|
-
function
|
|
5485
|
+
function onlyPythonWalkOnerrorKeywords(command) {
|
|
5486
|
+
const lower = command.toLowerCase();
|
|
5487
|
+
const occurrences = (lower.match(/onerror=/g) || []).length;
|
|
5488
|
+
if (!occurrences || command.length > 128 * 1024) return false;
|
|
5489
|
+
if (command.includes("$") || command.includes("`")) return false;
|
|
5490
|
+
const m = command.match(/^\s*python(?:3(?:\.\d+)?)?\s+-c\s+(['"])([\s\S]*)\1\s*(?:2>&1\s*)?$/i);
|
|
5491
|
+
if (!m) return false;
|
|
5492
|
+
const code = m[2];
|
|
5493
|
+
if ((code.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
|
|
5494
|
+
const noStr = code.replace(/(['"])(?:\\.|(?!\1)[^\\])*\1/g, "");
|
|
5495
|
+
if ((noStr.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
|
|
5496
|
+
const named = noStr.match(/onerror=\s*[A-Za-z_][\w.]*/g) || [];
|
|
5497
|
+
if (named.length !== occurrences) return false;
|
|
5498
|
+
const walkKws = noStr.match(/os\.walk\s*\([^)]*\bonerror\s*=/g) || [];
|
|
5499
|
+
return walkKws.length > 0;
|
|
5500
|
+
}
|
|
5501
|
+
function checkInjectionKeywords(text, extraKeywords, osType, pythonWalkOnerrorOnly = false) {
|
|
5467
5502
|
const hits = [];
|
|
5468
5503
|
const baseKeywords = runtimeConfigBridge.current?.effectiveInjectionKeywords(osType) ?? INJECTION_KEYWORDS;
|
|
5469
5504
|
for (const entry of baseKeywords) {
|
|
5505
|
+
if (pythonWalkOnerrorOnly && entry.keyword.toLowerCase() === "onerror=") continue;
|
|
5470
5506
|
if (text.includes(entry.keyword.toLowerCase())) {
|
|
5471
5507
|
hits.push(entry);
|
|
5472
5508
|
}
|
|
@@ -5631,6 +5667,22 @@ function splitCommandSegments2(actionDetail) {
|
|
|
5631
5667
|
if (start < actionDetail.length) segments.push(actionDetail.slice(start));
|
|
5632
5668
|
return segments;
|
|
5633
5669
|
}
|
|
5670
|
+
function stripSearchPatternLiterals(actionDetail) {
|
|
5671
|
+
const parts = [];
|
|
5672
|
+
for (const seg of splitCommandSegments2(actionDetail)) {
|
|
5673
|
+
const low = seg.trim().toLowerCase();
|
|
5674
|
+
const words = low.length ? low.split(/\s+/) : [];
|
|
5675
|
+
let idx = 0;
|
|
5676
|
+
while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
|
|
5677
|
+
const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
|
|
5678
|
+
if (isSearch && !low.includes("--pre")) {
|
|
5679
|
+
parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
|
|
5680
|
+
} else {
|
|
5681
|
+
parts.push(seg);
|
|
5682
|
+
}
|
|
5683
|
+
}
|
|
5684
|
+
return parts.join("");
|
|
5685
|
+
}
|
|
5634
5686
|
function severityRank(s) {
|
|
5635
5687
|
const ranks = { low: 1, medium: 2, high: 3, critical: 4 };
|
|
5636
5688
|
return ranks[s] || 0;
|
|
@@ -5926,7 +5978,7 @@ function isSshKeygenGenerate(command) {
|
|
|
5926
5978
|
}
|
|
5927
5979
|
function checkDangerousPatterns(actionType, actionDetail) {
|
|
5928
5980
|
if (actionType === "file_write" || actionType === "file_edit") return null;
|
|
5929
|
-
const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
|
|
5981
|
+
const scan = stripSearchPatternLiterals(stripHeredocContent(stripShellDocsOnly(actionDetail)));
|
|
5930
5982
|
const isTempPath = TEMP_DIRS2.some(
|
|
5931
5983
|
(td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
|
|
5932
5984
|
) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
|
|
@@ -6073,7 +6125,7 @@ function checkLateralMovement(actionDetail) {
|
|
|
6073
6125
|
}
|
|
6074
6126
|
return null;
|
|
6075
6127
|
}
|
|
6076
|
-
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, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
6128
|
+
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;
|
|
6077
6129
|
var init_heuristic = __esm({
|
|
6078
6130
|
"src/engine/heuristic.ts"() {
|
|
6079
6131
|
"use strict";
|
|
@@ -6116,6 +6168,8 @@ var init_heuristic = __esm({
|
|
|
6116
6168
|
"\\bchpasswd\\b"
|
|
6117
6169
|
]);
|
|
6118
6170
|
COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
|
|
6171
|
+
TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
|
|
6172
|
+
COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
|
|
6119
6173
|
SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
|
|
6120
6174
|
SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
|
|
6121
6175
|
SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
|
|
@@ -7719,11 +7773,12 @@ var init_tracker = __esm({
|
|
|
7719
7773
|
};
|
|
7720
7774
|
DEFAULT_BACKEND = new ShellBackend();
|
|
7721
7775
|
RecursiveTracker = class {
|
|
7722
|
-
constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE) {
|
|
7776
|
+
constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
|
|
7723
7777
|
this.maxDepth = maxDepth;
|
|
7724
7778
|
this.maxNodes = maxNodes;
|
|
7725
7779
|
this.maxFileSize = maxFileSize;
|
|
7726
7780
|
this.maxTotalSize = maxTotalSize;
|
|
7781
|
+
this.stopOnCritical = stopOnCritical;
|
|
7727
7782
|
this._scanner = commandScanner;
|
|
7728
7783
|
this.result = {
|
|
7729
7784
|
nodes: [],
|
|
@@ -7744,6 +7799,7 @@ var init_tracker = __esm({
|
|
|
7744
7799
|
maxNodes;
|
|
7745
7800
|
maxFileSize;
|
|
7746
7801
|
maxTotalSize;
|
|
7802
|
+
stopOnCritical;
|
|
7747
7803
|
result;
|
|
7748
7804
|
visiting = /* @__PURE__ */ new Set();
|
|
7749
7805
|
visitedPaths = /* @__PURE__ */ new Set();
|
|
@@ -7808,9 +7864,11 @@ var init_tracker = __esm({
|
|
|
7808
7864
|
node.l1MatchedPatterns = l1.matchedPatterns || [];
|
|
7809
7865
|
if (l1.riskLevel === "critical") {
|
|
7810
7866
|
this.result.hasCritical = true;
|
|
7811
|
-
this.result.firstHitNode = node;
|
|
7812
|
-
this.
|
|
7813
|
-
|
|
7867
|
+
if (!this.result.firstHitNode) this.result.firstHitNode = node;
|
|
7868
|
+
if (this.stopOnCritical) {
|
|
7869
|
+
this.visiting.delete(pathStr);
|
|
7870
|
+
return;
|
|
7871
|
+
}
|
|
7814
7872
|
}
|
|
7815
7873
|
}
|
|
7816
7874
|
}
|
|
@@ -7820,7 +7878,7 @@ var init_tracker = __esm({
|
|
|
7820
7878
|
const child = resolvePath(call.path, parentDir);
|
|
7821
7879
|
childPaths.push(child);
|
|
7822
7880
|
this.visitScript(child, depth + 1, path4.dirname(child), call.args);
|
|
7823
|
-
if (this.result.hasCritical) break;
|
|
7881
|
+
if (this.stopOnCritical && this.result.hasCritical) break;
|
|
7824
7882
|
}
|
|
7825
7883
|
node.childPaths = childPaths;
|
|
7826
7884
|
this.visiting.delete(pathStr);
|
|
@@ -8125,7 +8183,7 @@ function scanScriptChainKeywords(chain) {
|
|
|
8125
8183
|
}
|
|
8126
8184
|
return chain;
|
|
8127
8185
|
}
|
|
8128
|
-
function analyzeScriptContent2(input, ext) {
|
|
8186
|
+
function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
8129
8187
|
const actionType = input.aNext.actionType.toLowerCase();
|
|
8130
8188
|
if (actionType !== "bash") return emptyChain();
|
|
8131
8189
|
const { path: scriptPath, args: scriptArgs } = extractScriptPathWithArgs(input.aNext.actionDetail);
|
|
@@ -8154,7 +8212,14 @@ function analyzeScriptContent2(input, ext) {
|
|
|
8154
8212
|
}
|
|
8155
8213
|
return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
|
|
8156
8214
|
};
|
|
8157
|
-
const tracker = new RecursiveTracker(
|
|
8215
|
+
const tracker = new RecursiveTracker(
|
|
8216
|
+
l1Adapter,
|
|
8217
|
+
void 0,
|
|
8218
|
+
void 0,
|
|
8219
|
+
void 0,
|
|
8220
|
+
void 0,
|
|
8221
|
+
stopOnCritical
|
|
8222
|
+
);
|
|
8158
8223
|
const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
|
|
8159
8224
|
if (chain.nodes.length === 0) return chain;
|
|
8160
8225
|
scanScriptChainWithL1(chain, input, ext);
|
|
@@ -8723,7 +8788,7 @@ __export(token_stats_exports, {
|
|
|
8723
8788
|
resetTokenStats: () => resetTokenStats,
|
|
8724
8789
|
resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
|
|
8725
8790
|
});
|
|
8726
|
-
import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
|
|
8791
|
+
import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
|
|
8727
8792
|
function getStatsPath() {
|
|
8728
8793
|
const envPath = process.env[ENV_STATS_PATH];
|
|
8729
8794
|
if (envPath) return envPath;
|
|
@@ -8757,7 +8822,16 @@ function saveRecords(statsPath, records) {
|
|
|
8757
8822
|
try {
|
|
8758
8823
|
const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
|
|
8759
8824
|
if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
|
|
8760
|
-
|
|
8825
|
+
const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
|
|
8826
|
+
try {
|
|
8827
|
+
writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
|
|
8828
|
+
renameSync(tmp, statsPath);
|
|
8829
|
+
} finally {
|
|
8830
|
+
try {
|
|
8831
|
+
unlinkSync2(tmp);
|
|
8832
|
+
} catch {
|
|
8833
|
+
}
|
|
8834
|
+
}
|
|
8761
8835
|
try {
|
|
8762
8836
|
const st = statSync6(statsPath);
|
|
8763
8837
|
_recordsCache = {
|
|
@@ -9991,7 +10065,7 @@ var init_reviewer = __esm({
|
|
|
9991
10065
|
});
|
|
9992
10066
|
|
|
9993
10067
|
// src/brain/skill-manager.ts
|
|
9994
|
-
import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync, writeFileSync as writeFileSync4 } from "fs";
|
|
10068
|
+
import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
9995
10069
|
import { homedir as homedir7 } from "os";
|
|
9996
10070
|
import { join as join14 } from "path";
|
|
9997
10071
|
import { randomUUID } from "crypto";
|
|
@@ -10033,7 +10107,7 @@ var init_skill_manager = __esm({
|
|
|
10033
10107
|
const tmp = `${this.metaPath}.tmp`;
|
|
10034
10108
|
try {
|
|
10035
10109
|
writeFileSync4(tmp, JSON.stringify(out, null, 2), "utf-8");
|
|
10036
|
-
|
|
10110
|
+
renameSync2(tmp, this.metaPath);
|
|
10037
10111
|
} catch {
|
|
10038
10112
|
}
|
|
10039
10113
|
}
|
|
@@ -12667,7 +12741,8 @@ function _resetBrainForTest() {
|
|
|
12667
12741
|
}
|
|
12668
12742
|
async function runAnalysis(input) {
|
|
12669
12743
|
const observedFormalLayers = [];
|
|
12670
|
-
const
|
|
12744
|
+
const heuristicEnabled = isHeuristicEnabled();
|
|
12745
|
+
const heuristicResult = heuristicEnabled ? runHeuristicCheck(input) : null;
|
|
12671
12746
|
if (heuristicResult) {
|
|
12672
12747
|
traceSummary("l1.result", {
|
|
12673
12748
|
hit: !heuristicResult.allowed,
|
|
@@ -12693,8 +12768,8 @@ async function runAnalysis(input) {
|
|
|
12693
12768
|
);
|
|
12694
12769
|
let scriptChain = null;
|
|
12695
12770
|
if (input.aNext.actionType.toLowerCase() === "bash") {
|
|
12696
|
-
scriptChain = analyzeScriptContent2(input, agentExt);
|
|
12697
|
-
if (scriptChain.nodes.length > 0) {
|
|
12771
|
+
scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
|
|
12772
|
+
if (heuristicEnabled && scriptChain.nodes.length > 0) {
|
|
12698
12773
|
for (const node of scriptChain.nodes) {
|
|
12699
12774
|
if (node.unanalyzable) {
|
|
12700
12775
|
return {
|
|
@@ -14049,6 +14124,8 @@ async function healthRoute(c) {
|
|
|
14049
14124
|
status: degraded.length ? "degraded" : "healthy",
|
|
14050
14125
|
degraded,
|
|
14051
14126
|
instance: process.env.AGENT_MOSS_INSTANCE || "",
|
|
14127
|
+
// 实际监听端口(端口漂移后调用方靠它发现)
|
|
14128
|
+
port: parseInt(process.env.AGENT_MOSS_ACTUAL_PORT || "0", 10) || 0,
|
|
14052
14129
|
metrics
|
|
14053
14130
|
}));
|
|
14054
14131
|
}
|
|
@@ -14934,7 +15011,8 @@ import { Hono as Hono2 } from "hono";
|
|
|
14934
15011
|
import { cors } from "hono/cors";
|
|
14935
15012
|
import { logger } from "hono/logger";
|
|
14936
15013
|
import net from "net";
|
|
14937
|
-
import { existsSync as existsSync21 } from "fs";
|
|
15014
|
+
import { existsSync as existsSync21, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync9 } from "fs";
|
|
15015
|
+
import { dirname as dirname14, join as join22 } from "path";
|
|
14938
15016
|
function logDeploymentSelfCheck() {
|
|
14939
15017
|
try {
|
|
14940
15018
|
const mode = getRulesMode();
|
|
@@ -15175,9 +15253,28 @@ async function warmUpEngine() {
|
|
|
15175
15253
|
else process.env.AGENT_MOSS_SAVE_POLICY = prevSavePolicy;
|
|
15176
15254
|
}
|
|
15177
15255
|
}
|
|
15256
|
+
function writePortFile(port) {
|
|
15257
|
+
try {
|
|
15258
|
+
const path8 = join22(getDataRoot(), "agent_moss_server.port.json");
|
|
15259
|
+
mkdirSync9(dirname14(path8), { recursive: true });
|
|
15260
|
+
const payload = JSON.stringify({
|
|
15261
|
+
port,
|
|
15262
|
+
pid: process.pid,
|
|
15263
|
+
started_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
15264
|
+
});
|
|
15265
|
+
const tmp = `${path8}.tmp`;
|
|
15266
|
+
writeFileSync7(tmp, payload, "utf-8");
|
|
15267
|
+
renameSync3(tmp, path8);
|
|
15268
|
+
console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path8} (port=${port})`);
|
|
15269
|
+
} catch (err) {
|
|
15270
|
+
console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
|
|
15271
|
+
}
|
|
15272
|
+
}
|
|
15178
15273
|
async function startServer(host = "127.0.0.1", port = 9090) {
|
|
15179
15274
|
failFastOnAuthError();
|
|
15180
15275
|
const actualPort = await findFreePort(port, host);
|
|
15276
|
+
process.env.AGENT_MOSS_ACTUAL_PORT = String(actualPort);
|
|
15277
|
+
writePortFile(actualPort);
|
|
15181
15278
|
const app = createApp();
|
|
15182
15279
|
return {
|
|
15183
15280
|
port: actualPort,
|
|
@@ -15209,12 +15306,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
|
|
|
15209
15306
|
},
|
|
15210
15307
|
serve: async () => {
|
|
15211
15308
|
failFastOnAuthError();
|
|
15212
|
-
const { mkdirSync:
|
|
15213
|
-
const { dirname:
|
|
15214
|
-
const dir =
|
|
15309
|
+
const { mkdirSync: mkdirSync11, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
|
|
15310
|
+
const { dirname: dirname16 } = await import("path");
|
|
15311
|
+
const dir = dirname16(socketPath);
|
|
15215
15312
|
if (dir) {
|
|
15216
15313
|
try {
|
|
15217
|
-
|
|
15314
|
+
mkdirSync11(dir, { recursive: true });
|
|
15218
15315
|
} catch {
|
|
15219
15316
|
}
|
|
15220
15317
|
}
|
|
@@ -15274,6 +15371,7 @@ var init_server = __esm({
|
|
|
15274
15371
|
init_esm_shims();
|
|
15275
15372
|
init_rules_contract();
|
|
15276
15373
|
init_security_policy();
|
|
15374
|
+
init_paths();
|
|
15277
15375
|
init_routes();
|
|
15278
15376
|
init_console();
|
|
15279
15377
|
init_runtime_config();
|
|
@@ -15346,18 +15444,18 @@ __export(rules_tools_exports, {
|
|
|
15346
15444
|
rulesStatusText: () => rulesStatusText,
|
|
15347
15445
|
templateSourceDir: () => templateSourceDir
|
|
15348
15446
|
});
|
|
15349
|
-
import { existsSync as existsSync22, mkdirSync as
|
|
15350
|
-
import { dirname as
|
|
15447
|
+
import { existsSync as existsSync22, mkdirSync as mkdirSync10, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync8 } from "fs";
|
|
15448
|
+
import { dirname as dirname15, join as join23 } from "path";
|
|
15351
15449
|
import { fileURLToPath as fileURLToPath12 } from "url";
|
|
15352
15450
|
function initRulesDir(targetDir, opts = {}) {
|
|
15353
|
-
|
|
15451
|
+
mkdirSync10(targetDir, { recursive: true });
|
|
15354
15452
|
const written = [];
|
|
15355
|
-
const extraPath =
|
|
15453
|
+
const extraPath = join23(targetDir, EXTRA_FILENAME);
|
|
15356
15454
|
if (opts.force || !existsSync22(extraPath)) {
|
|
15357
|
-
|
|
15455
|
+
writeFileSync8(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
|
|
15358
15456
|
written.push(extraPath);
|
|
15359
15457
|
}
|
|
15360
|
-
const samplePath =
|
|
15458
|
+
const samplePath = join23(targetDir, OVERRIDE_FILENAME);
|
|
15361
15459
|
if (opts.force || !existsSync22(samplePath)) {
|
|
15362
15460
|
let payload = OVERRIDE_TEMPLATE;
|
|
15363
15461
|
if (opts.withBuiltin) {
|
|
@@ -15373,19 +15471,19 @@ function initRulesDir(targetDir, opts = {}) {
|
|
|
15373
15471
|
payload = { _\u8BF4\u660E: OVERRIDE_BUILTIN_NOTE };
|
|
15374
15472
|
for (const k of L1_KEYS) payload[k] = data[k] || [];
|
|
15375
15473
|
}
|
|
15376
|
-
|
|
15474
|
+
writeFileSync8(samplePath, JSON.stringify(payload, null, 2), "utf-8");
|
|
15377
15475
|
written.push(samplePath);
|
|
15378
15476
|
}
|
|
15379
|
-
const readmeSrc =
|
|
15380
|
-
const readmeDst =
|
|
15477
|
+
const readmeSrc = join23(templateSourceDir(), "README.md");
|
|
15478
|
+
const readmeDst = join23(targetDir, "README.md");
|
|
15381
15479
|
if (existsSync22(readmeSrc) && (opts.force || !existsSync22(readmeDst))) {
|
|
15382
|
-
|
|
15480
|
+
writeFileSync8(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
|
|
15383
15481
|
written.push(readmeDst);
|
|
15384
15482
|
}
|
|
15385
15483
|
return written;
|
|
15386
15484
|
}
|
|
15387
15485
|
function templateSourceDir() {
|
|
15388
|
-
const cands = [
|
|
15486
|
+
const cands = [join23(__dirname11, "data", "rules_template"), join23(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
|
|
15389
15487
|
for (const c of cands) if (existsSync22(c)) return c;
|
|
15390
15488
|
return cands[0];
|
|
15391
15489
|
}
|
|
@@ -15394,7 +15492,7 @@ function templateFiles(dirs) {
|
|
|
15394
15492
|
for (const d of dirs) {
|
|
15395
15493
|
try {
|
|
15396
15494
|
for (const name of readdirSync7(d)) {
|
|
15397
|
-
if (name.endsWith(".json.\u793A\u4F8B")) out.push(
|
|
15495
|
+
if (name.endsWith(".json.\u793A\u4F8B")) out.push(join23(d, name));
|
|
15398
15496
|
}
|
|
15399
15497
|
} catch {
|
|
15400
15498
|
}
|
|
@@ -15450,7 +15548,7 @@ var init_rules_tools = __esm({
|
|
|
15450
15548
|
"use strict";
|
|
15451
15549
|
init_esm_shims();
|
|
15452
15550
|
init_rules_loader();
|
|
15453
|
-
__dirname11 =
|
|
15551
|
+
__dirname11 = dirname15(fileURLToPath12(import.meta.url));
|
|
15454
15552
|
EXTRA_TEMPLATE = {
|
|
15455
15553
|
_\u8BF4\u660E: [
|
|
15456
15554
|
"\u8FFD\u52A0\u89C4\u5219\uFF1A\u5185\u7F6E\u89C4\u5219\u5168\u90E8\u4FDD\u7559\uFF0C\u4F60\u5199\u5728\u8FD9\u91CC\u7684\u89C4\u5219\u52A0\u5728\u5185\u7F6E\u4E4B\u540E\u4E00\u8D77\u5224\u5B9A\u3002",
|
|
@@ -4583,7 +4583,16 @@ function runHeuristicCheck(input) {
|
|
|
4583
4583
|
}
|
|
4584
4584
|
}
|
|
4585
4585
|
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();
|
|
4586
|
-
|
|
4586
|
+
let pythonWalkOnerrorOnly = false;
|
|
4587
|
+
if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
|
|
4588
|
+
pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
|
|
4589
|
+
}
|
|
4590
|
+
const injectionHits = checkInjectionKeywords(
|
|
4591
|
+
injectionText,
|
|
4592
|
+
agentExt?.extra_injection_keywords,
|
|
4593
|
+
input.osType,
|
|
4594
|
+
pythonWalkOnerrorOnly
|
|
4595
|
+
);
|
|
4587
4596
|
if (injectionHits.length > 0) {
|
|
4588
4597
|
const topHit = injectionHits.reduce((a, b) => severityRank(a.riskLevel) >= severityRank(b.riskLevel) ? a : b);
|
|
4589
4598
|
matched.push(...injectionHits.map((h) => `\u6CE8\u5165\u5173\u952E\u8BCD [${h.lang}]: ${h.keyword}`));
|
|
@@ -4632,10 +4641,27 @@ function runHeuristicCheck(input) {
|
|
|
4632
4641
|
if (lateralResult) return lateralResult;
|
|
4633
4642
|
return null;
|
|
4634
4643
|
}
|
|
4635
|
-
function
|
|
4644
|
+
function onlyPythonWalkOnerrorKeywords(command) {
|
|
4645
|
+
const lower = command.toLowerCase();
|
|
4646
|
+
const occurrences = (lower.match(/onerror=/g) || []).length;
|
|
4647
|
+
if (!occurrences || command.length > 128 * 1024) return false;
|
|
4648
|
+
if (command.includes("$") || command.includes("`")) return false;
|
|
4649
|
+
const m = command.match(/^\s*python(?:3(?:\.\d+)?)?\s+-c\s+(['"])([\s\S]*)\1\s*(?:2>&1\s*)?$/i);
|
|
4650
|
+
if (!m) return false;
|
|
4651
|
+
const code = m[2];
|
|
4652
|
+
if ((code.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
|
|
4653
|
+
const noStr = code.replace(/(['"])(?:\\.|(?!\1)[^\\])*\1/g, "");
|
|
4654
|
+
if ((noStr.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
|
|
4655
|
+
const named = noStr.match(/onerror=\s*[A-Za-z_][\w.]*/g) || [];
|
|
4656
|
+
if (named.length !== occurrences) return false;
|
|
4657
|
+
const walkKws = noStr.match(/os\.walk\s*\([^)]*\bonerror\s*=/g) || [];
|
|
4658
|
+
return walkKws.length > 0;
|
|
4659
|
+
}
|
|
4660
|
+
function checkInjectionKeywords(text, extraKeywords, osType, pythonWalkOnerrorOnly = false) {
|
|
4636
4661
|
const hits = [];
|
|
4637
4662
|
const baseKeywords = runtimeConfigBridge.current?.effectiveInjectionKeywords(osType) ?? INJECTION_KEYWORDS;
|
|
4638
4663
|
for (const entry of baseKeywords) {
|
|
4664
|
+
if (pythonWalkOnerrorOnly && entry.keyword.toLowerCase() === "onerror=") continue;
|
|
4639
4665
|
if (text.includes(entry.keyword.toLowerCase())) {
|
|
4640
4666
|
hits.push(entry);
|
|
4641
4667
|
}
|
|
@@ -4800,6 +4826,22 @@ function splitCommandSegments2(actionDetail) {
|
|
|
4800
4826
|
if (start < actionDetail.length) segments.push(actionDetail.slice(start));
|
|
4801
4827
|
return segments;
|
|
4802
4828
|
}
|
|
4829
|
+
function stripSearchPatternLiterals(actionDetail) {
|
|
4830
|
+
const parts = [];
|
|
4831
|
+
for (const seg of splitCommandSegments2(actionDetail)) {
|
|
4832
|
+
const low = seg.trim().toLowerCase();
|
|
4833
|
+
const words = low.length ? low.split(/\s+/) : [];
|
|
4834
|
+
let idx = 0;
|
|
4835
|
+
while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
|
|
4836
|
+
const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
|
|
4837
|
+
if (isSearch && !low.includes("--pre")) {
|
|
4838
|
+
parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
|
|
4839
|
+
} else {
|
|
4840
|
+
parts.push(seg);
|
|
4841
|
+
}
|
|
4842
|
+
}
|
|
4843
|
+
return parts.join("");
|
|
4844
|
+
}
|
|
4803
4845
|
function severityRank(s) {
|
|
4804
4846
|
const ranks = { low: 1, medium: 2, high: 3, critical: 4 };
|
|
4805
4847
|
return ranks[s] || 0;
|
|
@@ -5095,7 +5137,7 @@ function isSshKeygenGenerate(command) {
|
|
|
5095
5137
|
}
|
|
5096
5138
|
function checkDangerousPatterns(actionType, actionDetail) {
|
|
5097
5139
|
if (actionType === "file_write" || actionType === "file_edit") return null;
|
|
5098
|
-
const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
|
|
5140
|
+
const scan = stripSearchPatternLiterals(stripHeredocContent(stripShellDocsOnly(actionDetail)));
|
|
5099
5141
|
const isTempPath = TEMP_DIRS2.some(
|
|
5100
5142
|
(td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
|
|
5101
5143
|
) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
|
|
@@ -5242,7 +5284,7 @@ function checkLateralMovement(actionDetail) {
|
|
|
5242
5284
|
}
|
|
5243
5285
|
return null;
|
|
5244
5286
|
}
|
|
5245
|
-
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, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
5287
|
+
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;
|
|
5246
5288
|
var init_heuristic = __esm({
|
|
5247
5289
|
"src/engine/heuristic.ts"() {
|
|
5248
5290
|
"use strict";
|
|
@@ -5285,6 +5327,8 @@ var init_heuristic = __esm({
|
|
|
5285
5327
|
"\\bchpasswd\\b"
|
|
5286
5328
|
]);
|
|
5287
5329
|
COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
|
|
5330
|
+
TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
|
|
5331
|
+
COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
|
|
5288
5332
|
SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
|
|
5289
5333
|
SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
|
|
5290
5334
|
SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
|
|
@@ -5304,7 +5348,7 @@ __export(token_stats_exports, {
|
|
|
5304
5348
|
resetTokenStats: () => resetTokenStats,
|
|
5305
5349
|
resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
|
|
5306
5350
|
});
|
|
5307
|
-
import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
|
|
5351
|
+
import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
|
|
5308
5352
|
function getStatsPath() {
|
|
5309
5353
|
const envPath = process.env[ENV_STATS_PATH];
|
|
5310
5354
|
if (envPath) return envPath;
|
|
@@ -5338,7 +5382,16 @@ function saveRecords(statsPath, records) {
|
|
|
5338
5382
|
try {
|
|
5339
5383
|
const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
|
|
5340
5384
|
if (dir && !existsSync12(dir)) mkdirSync3(dir, { recursive: true });
|
|
5341
|
-
|
|
5385
|
+
const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
|
|
5386
|
+
try {
|
|
5387
|
+
writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
|
|
5388
|
+
renameSync(tmp, statsPath);
|
|
5389
|
+
} finally {
|
|
5390
|
+
try {
|
|
5391
|
+
unlinkSync2(tmp);
|
|
5392
|
+
} catch {
|
|
5393
|
+
}
|
|
5394
|
+
}
|
|
5342
5395
|
try {
|
|
5343
5396
|
const st = statSync6(statsPath);
|
|
5344
5397
|
_recordsCache = {
|
|
@@ -7178,11 +7231,12 @@ function emptyNode(pathStr, depth) {
|
|
|
7178
7231
|
};
|
|
7179
7232
|
}
|
|
7180
7233
|
var RecursiveTracker = class {
|
|
7181
|
-
constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE) {
|
|
7234
|
+
constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
|
|
7182
7235
|
this.maxDepth = maxDepth;
|
|
7183
7236
|
this.maxNodes = maxNodes;
|
|
7184
7237
|
this.maxFileSize = maxFileSize;
|
|
7185
7238
|
this.maxTotalSize = maxTotalSize;
|
|
7239
|
+
this.stopOnCritical = stopOnCritical;
|
|
7186
7240
|
this._scanner = commandScanner;
|
|
7187
7241
|
this.result = {
|
|
7188
7242
|
nodes: [],
|
|
@@ -7203,6 +7257,7 @@ var RecursiveTracker = class {
|
|
|
7203
7257
|
maxNodes;
|
|
7204
7258
|
maxFileSize;
|
|
7205
7259
|
maxTotalSize;
|
|
7260
|
+
stopOnCritical;
|
|
7206
7261
|
result;
|
|
7207
7262
|
visiting = /* @__PURE__ */ new Set();
|
|
7208
7263
|
visitedPaths = /* @__PURE__ */ new Set();
|
|
@@ -7267,9 +7322,11 @@ var RecursiveTracker = class {
|
|
|
7267
7322
|
node.l1MatchedPatterns = l1.matchedPatterns || [];
|
|
7268
7323
|
if (l1.riskLevel === "critical") {
|
|
7269
7324
|
this.result.hasCritical = true;
|
|
7270
|
-
this.result.firstHitNode = node;
|
|
7271
|
-
this.
|
|
7272
|
-
|
|
7325
|
+
if (!this.result.firstHitNode) this.result.firstHitNode = node;
|
|
7326
|
+
if (this.stopOnCritical) {
|
|
7327
|
+
this.visiting.delete(pathStr);
|
|
7328
|
+
return;
|
|
7329
|
+
}
|
|
7273
7330
|
}
|
|
7274
7331
|
}
|
|
7275
7332
|
}
|
|
@@ -7279,7 +7336,7 @@ var RecursiveTracker = class {
|
|
|
7279
7336
|
const child = resolvePath(call.path, parentDir);
|
|
7280
7337
|
childPaths.push(child);
|
|
7281
7338
|
this.visitScript(child, depth + 1, path4.dirname(child), call.args);
|
|
7282
|
-
if (this.result.hasCritical) break;
|
|
7339
|
+
if (this.stopOnCritical && this.result.hasCritical) break;
|
|
7283
7340
|
}
|
|
7284
7341
|
node.childPaths = childPaths;
|
|
7285
7342
|
this.visiting.delete(pathStr);
|
|
@@ -7597,7 +7654,7 @@ function scanScriptChainKeywords(chain) {
|
|
|
7597
7654
|
}
|
|
7598
7655
|
return chain;
|
|
7599
7656
|
}
|
|
7600
|
-
function analyzeScriptContent2(input, ext) {
|
|
7657
|
+
function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
7601
7658
|
const actionType = input.aNext.actionType.toLowerCase();
|
|
7602
7659
|
if (actionType !== "bash") return emptyChain();
|
|
7603
7660
|
const { path: scriptPath, args: scriptArgs } = extractScriptPathWithArgs(input.aNext.actionDetail);
|
|
@@ -7626,7 +7683,14 @@ function analyzeScriptContent2(input, ext) {
|
|
|
7626
7683
|
}
|
|
7627
7684
|
return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
|
|
7628
7685
|
};
|
|
7629
|
-
const tracker = new RecursiveTracker(
|
|
7686
|
+
const tracker = new RecursiveTracker(
|
|
7687
|
+
l1Adapter,
|
|
7688
|
+
void 0,
|
|
7689
|
+
void 0,
|
|
7690
|
+
void 0,
|
|
7691
|
+
void 0,
|
|
7692
|
+
stopOnCritical
|
|
7693
|
+
);
|
|
7630
7694
|
const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
|
|
7631
7695
|
if (chain.nodes.length === 0) return chain;
|
|
7632
7696
|
scanScriptChainWithL1(chain, input, ext);
|
|
@@ -9143,7 +9207,7 @@ function parseReview(content) {
|
|
|
9143
9207
|
|
|
9144
9208
|
// src/brain/skill-manager.ts
|
|
9145
9209
|
init_esm_shims();
|
|
9146
|
-
import { existsSync as existsSync14, mkdirSync as mkdirSync5, readFileSync as readFileSync14, renameSync, writeFileSync as writeFileSync4 } from "fs";
|
|
9210
|
+
import { existsSync as existsSync14, mkdirSync as mkdirSync5, readFileSync as readFileSync14, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
9147
9211
|
import { homedir as homedir7 } from "os";
|
|
9148
9212
|
import { join as join13 } from "path";
|
|
9149
9213
|
import { randomUUID } from "crypto";
|
|
@@ -9180,7 +9244,7 @@ var BrainSkillManager = class {
|
|
|
9180
9244
|
const tmp = `${this.metaPath}.tmp`;
|
|
9181
9245
|
try {
|
|
9182
9246
|
writeFileSync4(tmp, JSON.stringify(out, null, 2), "utf-8");
|
|
9183
|
-
|
|
9247
|
+
renameSync2(tmp, this.metaPath);
|
|
9184
9248
|
} catch {
|
|
9185
9249
|
}
|
|
9186
9250
|
}
|
|
@@ -10630,7 +10694,8 @@ function _resetBrainForTest() {
|
|
|
10630
10694
|
var formalEngine = new FormalEngine();
|
|
10631
10695
|
async function runAnalysis(input) {
|
|
10632
10696
|
const observedFormalLayers = [];
|
|
10633
|
-
const
|
|
10697
|
+
const heuristicEnabled = isHeuristicEnabled();
|
|
10698
|
+
const heuristicResult = heuristicEnabled ? runHeuristicCheck(input) : null;
|
|
10634
10699
|
if (heuristicResult) {
|
|
10635
10700
|
traceSummary("l1.result", {
|
|
10636
10701
|
hit: !heuristicResult.allowed,
|
|
@@ -10656,8 +10721,8 @@ async function runAnalysis(input) {
|
|
|
10656
10721
|
);
|
|
10657
10722
|
let scriptChain = null;
|
|
10658
10723
|
if (input.aNext.actionType.toLowerCase() === "bash") {
|
|
10659
|
-
scriptChain = analyzeScriptContent2(input, agentExt);
|
|
10660
|
-
if (scriptChain.nodes.length > 0) {
|
|
10724
|
+
scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
|
|
10725
|
+
if (heuristicEnabled && scriptChain.nodes.length > 0) {
|
|
10661
10726
|
for (const node of scriptChain.nodes) {
|
|
10662
10727
|
if (node.unanalyzable) {
|
|
10663
10728
|
return {
|
package/dist/server.js
CHANGED
|
@@ -5114,7 +5114,16 @@ function runHeuristicCheck(input) {
|
|
|
5114
5114
|
}
|
|
5115
5115
|
}
|
|
5116
5116
|
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();
|
|
5117
|
-
|
|
5117
|
+
let pythonWalkOnerrorOnly = false;
|
|
5118
|
+
if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
|
|
5119
|
+
pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
|
|
5120
|
+
}
|
|
5121
|
+
const injectionHits = checkInjectionKeywords(
|
|
5122
|
+
injectionText,
|
|
5123
|
+
agentExt?.extra_injection_keywords,
|
|
5124
|
+
input.osType,
|
|
5125
|
+
pythonWalkOnerrorOnly
|
|
5126
|
+
);
|
|
5118
5127
|
if (injectionHits.length > 0) {
|
|
5119
5128
|
const topHit = injectionHits.reduce((a, b) => severityRank(a.riskLevel) >= severityRank(b.riskLevel) ? a : b);
|
|
5120
5129
|
matched.push(...injectionHits.map((h) => `\u6CE8\u5165\u5173\u952E\u8BCD [${h.lang}]: ${h.keyword}`));
|
|
@@ -5163,10 +5172,27 @@ function runHeuristicCheck(input) {
|
|
|
5163
5172
|
if (lateralResult) return lateralResult;
|
|
5164
5173
|
return null;
|
|
5165
5174
|
}
|
|
5166
|
-
function
|
|
5175
|
+
function onlyPythonWalkOnerrorKeywords(command) {
|
|
5176
|
+
const lower = command.toLowerCase();
|
|
5177
|
+
const occurrences = (lower.match(/onerror=/g) || []).length;
|
|
5178
|
+
if (!occurrences || command.length > 128 * 1024) return false;
|
|
5179
|
+
if (command.includes("$") || command.includes("`")) return false;
|
|
5180
|
+
const m = command.match(/^\s*python(?:3(?:\.\d+)?)?\s+-c\s+(['"])([\s\S]*)\1\s*(?:2>&1\s*)?$/i);
|
|
5181
|
+
if (!m) return false;
|
|
5182
|
+
const code = m[2];
|
|
5183
|
+
if ((code.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
|
|
5184
|
+
const noStr = code.replace(/(['"])(?:\\.|(?!\1)[^\\])*\1/g, "");
|
|
5185
|
+
if ((noStr.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
|
|
5186
|
+
const named = noStr.match(/onerror=\s*[A-Za-z_][\w.]*/g) || [];
|
|
5187
|
+
if (named.length !== occurrences) return false;
|
|
5188
|
+
const walkKws = noStr.match(/os\.walk\s*\([^)]*\bonerror\s*=/g) || [];
|
|
5189
|
+
return walkKws.length > 0;
|
|
5190
|
+
}
|
|
5191
|
+
function checkInjectionKeywords(text, extraKeywords, osType, pythonWalkOnerrorOnly = false) {
|
|
5167
5192
|
const hits = [];
|
|
5168
5193
|
const baseKeywords = runtimeConfigBridge.current?.effectiveInjectionKeywords(osType) ?? INJECTION_KEYWORDS;
|
|
5169
5194
|
for (const entry of baseKeywords) {
|
|
5195
|
+
if (pythonWalkOnerrorOnly && entry.keyword.toLowerCase() === "onerror=") continue;
|
|
5170
5196
|
if (text.includes(entry.keyword.toLowerCase())) {
|
|
5171
5197
|
hits.push(entry);
|
|
5172
5198
|
}
|
|
@@ -5331,6 +5357,22 @@ function splitCommandSegments2(actionDetail) {
|
|
|
5331
5357
|
if (start < actionDetail.length) segments.push(actionDetail.slice(start));
|
|
5332
5358
|
return segments;
|
|
5333
5359
|
}
|
|
5360
|
+
function stripSearchPatternLiterals(actionDetail) {
|
|
5361
|
+
const parts = [];
|
|
5362
|
+
for (const seg of splitCommandSegments2(actionDetail)) {
|
|
5363
|
+
const low = seg.trim().toLowerCase();
|
|
5364
|
+
const words = low.length ? low.split(/\s+/) : [];
|
|
5365
|
+
let idx = 0;
|
|
5366
|
+
while (idx < words.length && COMMAND_PREFIX_WORDS.has(words[idx])) idx++;
|
|
5367
|
+
const isSearch = idx < words.length && TEXT_SEARCH_COMMANDS.has(words[idx]);
|
|
5368
|
+
if (isSearch && !low.includes("--pre")) {
|
|
5369
|
+
parts.push(seg.replace(/'[^']*'|"[^"]*"/g, " "));
|
|
5370
|
+
} else {
|
|
5371
|
+
parts.push(seg);
|
|
5372
|
+
}
|
|
5373
|
+
}
|
|
5374
|
+
return parts.join("");
|
|
5375
|
+
}
|
|
5334
5376
|
function severityRank(s) {
|
|
5335
5377
|
const ranks = { low: 1, medium: 2, high: 3, critical: 4 };
|
|
5336
5378
|
return ranks[s] || 0;
|
|
@@ -5626,7 +5668,7 @@ function isSshKeygenGenerate(command) {
|
|
|
5626
5668
|
}
|
|
5627
5669
|
function checkDangerousPatterns(actionType, actionDetail) {
|
|
5628
5670
|
if (actionType === "file_write" || actionType === "file_edit") return null;
|
|
5629
|
-
const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
|
|
5671
|
+
const scan = stripSearchPatternLiterals(stripHeredocContent(stripShellDocsOnly(actionDetail)));
|
|
5630
5672
|
const isTempPath = TEMP_DIRS2.some(
|
|
5631
5673
|
(td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
|
|
5632
5674
|
) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
|
|
@@ -5773,7 +5815,7 @@ function checkLateralMovement(actionDetail) {
|
|
|
5773
5815
|
}
|
|
5774
5816
|
return null;
|
|
5775
5817
|
}
|
|
5776
|
-
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, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
5818
|
+
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;
|
|
5777
5819
|
var init_heuristic = __esm({
|
|
5778
5820
|
"src/engine/heuristic.ts"() {
|
|
5779
5821
|
"use strict";
|
|
@@ -5816,6 +5858,8 @@ var init_heuristic = __esm({
|
|
|
5816
5858
|
"\\bchpasswd\\b"
|
|
5817
5859
|
]);
|
|
5818
5860
|
COMMAND_SEGMENT_TOKEN_RE = /['";\n]|&&|\|\|/g;
|
|
5861
|
+
TEXT_SEARCH_COMMANDS = /* @__PURE__ */ new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "ack-grep"]);
|
|
5862
|
+
COMMAND_PREFIX_WORDS = /* @__PURE__ */ new Set(["sudo", "command", "nohup", "time"]);
|
|
5819
5863
|
SENSITIVE_EXCLUDED_PREFIXES = HEURISTIC_RULES.sensitive_excluded_prefixes ?? [];
|
|
5820
5864
|
SEARCH_ACTION_PREFIXES = HEURISTIC_RULES.search_action_prefixes ?? [];
|
|
5821
5865
|
SEARCH_ACTION_EXACT = HEURISTIC_RULES.search_action_exact ?? [];
|
|
@@ -7419,11 +7463,12 @@ var init_tracker = __esm({
|
|
|
7419
7463
|
};
|
|
7420
7464
|
DEFAULT_BACKEND = new ShellBackend();
|
|
7421
7465
|
RecursiveTracker = class {
|
|
7422
|
-
constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE) {
|
|
7466
|
+
constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
|
|
7423
7467
|
this.maxDepth = maxDepth;
|
|
7424
7468
|
this.maxNodes = maxNodes;
|
|
7425
7469
|
this.maxFileSize = maxFileSize;
|
|
7426
7470
|
this.maxTotalSize = maxTotalSize;
|
|
7471
|
+
this.stopOnCritical = stopOnCritical;
|
|
7427
7472
|
this._scanner = commandScanner;
|
|
7428
7473
|
this.result = {
|
|
7429
7474
|
nodes: [],
|
|
@@ -7444,6 +7489,7 @@ var init_tracker = __esm({
|
|
|
7444
7489
|
maxNodes;
|
|
7445
7490
|
maxFileSize;
|
|
7446
7491
|
maxTotalSize;
|
|
7492
|
+
stopOnCritical;
|
|
7447
7493
|
result;
|
|
7448
7494
|
visiting = /* @__PURE__ */ new Set();
|
|
7449
7495
|
visitedPaths = /* @__PURE__ */ new Set();
|
|
@@ -7508,9 +7554,11 @@ var init_tracker = __esm({
|
|
|
7508
7554
|
node.l1MatchedPatterns = l1.matchedPatterns || [];
|
|
7509
7555
|
if (l1.riskLevel === "critical") {
|
|
7510
7556
|
this.result.hasCritical = true;
|
|
7511
|
-
this.result.firstHitNode = node;
|
|
7512
|
-
this.
|
|
7513
|
-
|
|
7557
|
+
if (!this.result.firstHitNode) this.result.firstHitNode = node;
|
|
7558
|
+
if (this.stopOnCritical) {
|
|
7559
|
+
this.visiting.delete(pathStr);
|
|
7560
|
+
return;
|
|
7561
|
+
}
|
|
7514
7562
|
}
|
|
7515
7563
|
}
|
|
7516
7564
|
}
|
|
@@ -7520,7 +7568,7 @@ var init_tracker = __esm({
|
|
|
7520
7568
|
const child = resolvePath(call.path, parentDir);
|
|
7521
7569
|
childPaths.push(child);
|
|
7522
7570
|
this.visitScript(child, depth + 1, path4.dirname(child), call.args);
|
|
7523
|
-
if (this.result.hasCritical) break;
|
|
7571
|
+
if (this.stopOnCritical && this.result.hasCritical) break;
|
|
7524
7572
|
}
|
|
7525
7573
|
node.childPaths = childPaths;
|
|
7526
7574
|
this.visiting.delete(pathStr);
|
|
@@ -7825,7 +7873,7 @@ function scanScriptChainKeywords(chain) {
|
|
|
7825
7873
|
}
|
|
7826
7874
|
return chain;
|
|
7827
7875
|
}
|
|
7828
|
-
function analyzeScriptContent2(input, ext) {
|
|
7876
|
+
function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
7829
7877
|
const actionType = input.aNext.actionType.toLowerCase();
|
|
7830
7878
|
if (actionType !== "bash") return emptyChain();
|
|
7831
7879
|
const { path: scriptPath, args: scriptArgs } = extractScriptPathWithArgs(input.aNext.actionDetail);
|
|
@@ -7854,7 +7902,14 @@ function analyzeScriptContent2(input, ext) {
|
|
|
7854
7902
|
}
|
|
7855
7903
|
return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
|
|
7856
7904
|
};
|
|
7857
|
-
const tracker = new RecursiveTracker(
|
|
7905
|
+
const tracker = new RecursiveTracker(
|
|
7906
|
+
l1Adapter,
|
|
7907
|
+
void 0,
|
|
7908
|
+
void 0,
|
|
7909
|
+
void 0,
|
|
7910
|
+
void 0,
|
|
7911
|
+
stopOnCritical
|
|
7912
|
+
);
|
|
7858
7913
|
const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
|
|
7859
7914
|
if (chain.nodes.length === 0) return chain;
|
|
7860
7915
|
scanScriptChainWithL1(chain, input, ext);
|
|
@@ -8423,7 +8478,7 @@ __export(token_stats_exports, {
|
|
|
8423
8478
|
resetTokenStats: () => resetTokenStats,
|
|
8424
8479
|
resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
|
|
8425
8480
|
});
|
|
8426
|
-
import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
|
|
8481
|
+
import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
|
|
8427
8482
|
function getStatsPath() {
|
|
8428
8483
|
const envPath = process.env[ENV_STATS_PATH];
|
|
8429
8484
|
if (envPath) return envPath;
|
|
@@ -8457,7 +8512,16 @@ function saveRecords(statsPath, records) {
|
|
|
8457
8512
|
try {
|
|
8458
8513
|
const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
|
|
8459
8514
|
if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
|
|
8460
|
-
|
|
8515
|
+
const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
|
|
8516
|
+
try {
|
|
8517
|
+
writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
|
|
8518
|
+
renameSync(tmp, statsPath);
|
|
8519
|
+
} finally {
|
|
8520
|
+
try {
|
|
8521
|
+
unlinkSync2(tmp);
|
|
8522
|
+
} catch {
|
|
8523
|
+
}
|
|
8524
|
+
}
|
|
8461
8525
|
try {
|
|
8462
8526
|
const st = statSync6(statsPath);
|
|
8463
8527
|
_recordsCache = {
|
|
@@ -9691,7 +9755,7 @@ var init_reviewer = __esm({
|
|
|
9691
9755
|
});
|
|
9692
9756
|
|
|
9693
9757
|
// src/brain/skill-manager.ts
|
|
9694
|
-
import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync, writeFileSync as writeFileSync4 } from "fs";
|
|
9758
|
+
import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
9695
9759
|
import { homedir as homedir7 } from "os";
|
|
9696
9760
|
import { join as join14 } from "path";
|
|
9697
9761
|
import { randomUUID } from "crypto";
|
|
@@ -9733,7 +9797,7 @@ var init_skill_manager = __esm({
|
|
|
9733
9797
|
const tmp = `${this.metaPath}.tmp`;
|
|
9734
9798
|
try {
|
|
9735
9799
|
writeFileSync4(tmp, JSON.stringify(out, null, 2), "utf-8");
|
|
9736
|
-
|
|
9800
|
+
renameSync2(tmp, this.metaPath);
|
|
9737
9801
|
} catch {
|
|
9738
9802
|
}
|
|
9739
9803
|
}
|
|
@@ -12102,7 +12166,8 @@ function _resetBrainForTest() {
|
|
|
12102
12166
|
}
|
|
12103
12167
|
async function runAnalysis(input) {
|
|
12104
12168
|
const observedFormalLayers = [];
|
|
12105
|
-
const
|
|
12169
|
+
const heuristicEnabled = isHeuristicEnabled();
|
|
12170
|
+
const heuristicResult = heuristicEnabled ? runHeuristicCheck(input) : null;
|
|
12106
12171
|
if (heuristicResult) {
|
|
12107
12172
|
traceSummary("l1.result", {
|
|
12108
12173
|
hit: !heuristicResult.allowed,
|
|
@@ -12128,8 +12193,8 @@ async function runAnalysis(input) {
|
|
|
12128
12193
|
);
|
|
12129
12194
|
let scriptChain = null;
|
|
12130
12195
|
if (input.aNext.actionType.toLowerCase() === "bash") {
|
|
12131
|
-
scriptChain = analyzeScriptContent2(input, agentExt);
|
|
12132
|
-
if (scriptChain.nodes.length > 0) {
|
|
12196
|
+
scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
|
|
12197
|
+
if (heuristicEnabled && scriptChain.nodes.length > 0) {
|
|
12133
12198
|
for (const node of scriptChain.nodes) {
|
|
12134
12199
|
if (node.unanalyzable) {
|
|
12135
12200
|
return {
|
|
@@ -12658,10 +12723,12 @@ function enforceRulesContract() {
|
|
|
12658
12723
|
|
|
12659
12724
|
// src/server.ts
|
|
12660
12725
|
init_security_policy();
|
|
12726
|
+
init_paths();
|
|
12661
12727
|
import { cors } from "hono/cors";
|
|
12662
12728
|
import { logger } from "hono/logger";
|
|
12663
12729
|
import net from "net";
|
|
12664
|
-
import { existsSync as existsSync21 } from "fs";
|
|
12730
|
+
import { existsSync as existsSync21, writeFileSync as writeFileSync6, renameSync as renameSync3, mkdirSync as mkdirSync8 } from "fs";
|
|
12731
|
+
import { dirname as dirname14, join as join21 } from "path";
|
|
12665
12732
|
|
|
12666
12733
|
// src/routes.ts
|
|
12667
12734
|
init_esm_shims();
|
|
@@ -12680,9 +12747,17 @@ var pkg = require2("../package.json");
|
|
|
12680
12747
|
var version = pkg.version;
|
|
12681
12748
|
|
|
12682
12749
|
// src/models.ts
|
|
12750
|
+
var isNonEmptyNoControl = (v) => v.trim().length > 0 && ![...v].some((c) => {
|
|
12751
|
+
const n = c.codePointAt(0) ?? 0;
|
|
12752
|
+
return n < 32 || n >= 127 && n <= 159;
|
|
12753
|
+
});
|
|
12683
12754
|
var ActionItemSchema = z.object({
|
|
12684
|
-
action_type: z.string().
|
|
12685
|
-
|
|
12755
|
+
action_type: z.string().refine(isNonEmptyNoControl, {
|
|
12756
|
+
message: "action_type must be nonempty and contain no control characters"
|
|
12757
|
+
}).describe("Action type, e.g. bash, file_read, file_write"),
|
|
12758
|
+
action_detail: z.string().refine((v) => !v.includes("\0"), {
|
|
12759
|
+
message: "action_detail must not contain NUL characters"
|
|
12760
|
+
}).describe("Action detail / command content"),
|
|
12686
12761
|
// 工具返回给 agent 的内容。仅 L2 的授权(consent)判定用:判断「用户是否已授权」
|
|
12687
12762
|
// 看的是 ask_user_question 的**回答**,不是提问正文。历史 bug:模型里没有这个字段、
|
|
12688
12763
|
// 路由也没透传,TS 的授权判定退化成「提问正文非空」,等于问过任何问题即已授权。
|
|
@@ -12775,6 +12850,8 @@ var HealthResponseSchema = z.object({
|
|
|
12775
12850
|
// 降级原因(status=degraded 时非空)
|
|
12776
12851
|
degraded: z.array(z.string()).default([]),
|
|
12777
12852
|
version: z.string().default(version),
|
|
12853
|
+
// 实际监听端口(端口被占用自动漂移后,调用方从这里得知新端口)。
|
|
12854
|
+
port: z.number().default(0),
|
|
12778
12855
|
// 归属实例标识:值来自 env AGENT_MOSS_INSTANCE(spawn/systemd 注入),默认空串。
|
|
12779
12856
|
// 多个 agentmoss 同机并存时,调用方按 instance 过滤避免连到别人的进程。
|
|
12780
12857
|
// 空=未配置(独立部署或旧版),调用方可选择兼容或严格过滤。
|
|
@@ -13713,6 +13790,8 @@ async function healthRoute(c) {
|
|
|
13713
13790
|
status: degraded.length ? "degraded" : "healthy",
|
|
13714
13791
|
degraded,
|
|
13715
13792
|
instance: process.env.AGENT_MOSS_INSTANCE || "",
|
|
13793
|
+
// 实际监听端口(端口漂移后调用方靠它发现)
|
|
13794
|
+
port: parseInt(process.env.AGENT_MOSS_ACTUAL_PORT || "0", 10) || 0,
|
|
13716
13795
|
metrics
|
|
13717
13796
|
}));
|
|
13718
13797
|
}
|
|
@@ -14845,9 +14924,28 @@ async function warmUpEngine() {
|
|
|
14845
14924
|
else process.env.AGENT_MOSS_SAVE_POLICY = prevSavePolicy;
|
|
14846
14925
|
}
|
|
14847
14926
|
}
|
|
14927
|
+
function writePortFile(port) {
|
|
14928
|
+
try {
|
|
14929
|
+
const path8 = join21(getDataRoot(), "agent_moss_server.port.json");
|
|
14930
|
+
mkdirSync8(dirname14(path8), { recursive: true });
|
|
14931
|
+
const payload = JSON.stringify({
|
|
14932
|
+
port,
|
|
14933
|
+
pid: process.pid,
|
|
14934
|
+
started_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
14935
|
+
});
|
|
14936
|
+
const tmp = `${path8}.tmp`;
|
|
14937
|
+
writeFileSync6(tmp, payload, "utf-8");
|
|
14938
|
+
renameSync3(tmp, path8);
|
|
14939
|
+
console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path8} (port=${port})`);
|
|
14940
|
+
} catch (err) {
|
|
14941
|
+
console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
|
|
14942
|
+
}
|
|
14943
|
+
}
|
|
14848
14944
|
async function startServer(host = "127.0.0.1", port = 9090) {
|
|
14849
14945
|
failFastOnAuthError();
|
|
14850
14946
|
const actualPort = await findFreePort(port, host);
|
|
14947
|
+
process.env.AGENT_MOSS_ACTUAL_PORT = String(actualPort);
|
|
14948
|
+
writePortFile(actualPort);
|
|
14851
14949
|
const app = createApp();
|
|
14852
14950
|
return {
|
|
14853
14951
|
port: actualPort,
|
|
@@ -14879,12 +14977,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
|
|
|
14879
14977
|
},
|
|
14880
14978
|
serve: async () => {
|
|
14881
14979
|
failFastOnAuthError();
|
|
14882
|
-
const { mkdirSync:
|
|
14883
|
-
const { dirname:
|
|
14884
|
-
const dir =
|
|
14980
|
+
const { mkdirSync: mkdirSync9, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
|
|
14981
|
+
const { dirname: dirname15 } = await import("path");
|
|
14982
|
+
const dir = dirname15(socketPath);
|
|
14885
14983
|
if (dir) {
|
|
14886
14984
|
try {
|
|
14887
|
-
|
|
14985
|
+
mkdirSync9(dir, { recursive: true });
|
|
14888
14986
|
} catch {
|
|
14889
14987
|
}
|
|
14890
14988
|
}
|