@kenhkl/agent-moss 0.17.28 → 0.17.29

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
@@ -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().describe("Action type, e.g. bash, file_read, file_write"),
1419
- action_detail: z.string().describe("Action detail / command content"),
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
- const injectionHits = checkInjectionKeywords(injectionText, agentExt?.extra_injection_keywords, input.osType);
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 checkInjectionKeywords(text, extraKeywords, osType) {
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
  }
@@ -7719,11 +7755,12 @@ var init_tracker = __esm({
7719
7755
  };
7720
7756
  DEFAULT_BACKEND = new ShellBackend();
7721
7757
  RecursiveTracker = class {
7722
- constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE) {
7758
+ constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
7723
7759
  this.maxDepth = maxDepth;
7724
7760
  this.maxNodes = maxNodes;
7725
7761
  this.maxFileSize = maxFileSize;
7726
7762
  this.maxTotalSize = maxTotalSize;
7763
+ this.stopOnCritical = stopOnCritical;
7727
7764
  this._scanner = commandScanner;
7728
7765
  this.result = {
7729
7766
  nodes: [],
@@ -7744,6 +7781,7 @@ var init_tracker = __esm({
7744
7781
  maxNodes;
7745
7782
  maxFileSize;
7746
7783
  maxTotalSize;
7784
+ stopOnCritical;
7747
7785
  result;
7748
7786
  visiting = /* @__PURE__ */ new Set();
7749
7787
  visitedPaths = /* @__PURE__ */ new Set();
@@ -7808,9 +7846,11 @@ var init_tracker = __esm({
7808
7846
  node.l1MatchedPatterns = l1.matchedPatterns || [];
7809
7847
  if (l1.riskLevel === "critical") {
7810
7848
  this.result.hasCritical = true;
7811
- this.result.firstHitNode = node;
7812
- this.visiting.delete(pathStr);
7813
- return;
7849
+ if (!this.result.firstHitNode) this.result.firstHitNode = node;
7850
+ if (this.stopOnCritical) {
7851
+ this.visiting.delete(pathStr);
7852
+ return;
7853
+ }
7814
7854
  }
7815
7855
  }
7816
7856
  }
@@ -7820,7 +7860,7 @@ var init_tracker = __esm({
7820
7860
  const child = resolvePath(call.path, parentDir);
7821
7861
  childPaths.push(child);
7822
7862
  this.visitScript(child, depth + 1, path4.dirname(child), call.args);
7823
- if (this.result.hasCritical) break;
7863
+ if (this.stopOnCritical && this.result.hasCritical) break;
7824
7864
  }
7825
7865
  node.childPaths = childPaths;
7826
7866
  this.visiting.delete(pathStr);
@@ -8125,7 +8165,7 @@ function scanScriptChainKeywords(chain) {
8125
8165
  }
8126
8166
  return chain;
8127
8167
  }
8128
- function analyzeScriptContent2(input, ext) {
8168
+ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
8129
8169
  const actionType = input.aNext.actionType.toLowerCase();
8130
8170
  if (actionType !== "bash") return emptyChain();
8131
8171
  const { path: scriptPath, args: scriptArgs } = extractScriptPathWithArgs(input.aNext.actionDetail);
@@ -8154,7 +8194,14 @@ function analyzeScriptContent2(input, ext) {
8154
8194
  }
8155
8195
  return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
8156
8196
  };
8157
- const tracker = new RecursiveTracker(l1Adapter);
8197
+ const tracker = new RecursiveTracker(
8198
+ l1Adapter,
8199
+ void 0,
8200
+ void 0,
8201
+ void 0,
8202
+ void 0,
8203
+ stopOnCritical
8204
+ );
8158
8205
  const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
8159
8206
  if (chain.nodes.length === 0) return chain;
8160
8207
  scanScriptChainWithL1(chain, input, ext);
@@ -8723,7 +8770,7 @@ __export(token_stats_exports, {
8723
8770
  resetTokenStats: () => resetTokenStats,
8724
8771
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
8725
8772
  });
8726
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
8773
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
8727
8774
  function getStatsPath() {
8728
8775
  const envPath = process.env[ENV_STATS_PATH];
8729
8776
  if (envPath) return envPath;
@@ -8757,7 +8804,16 @@ function saveRecords(statsPath, records) {
8757
8804
  try {
8758
8805
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
8759
8806
  if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
8760
- writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
8807
+ const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
8808
+ try {
8809
+ writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
8810
+ renameSync(tmp, statsPath);
8811
+ } finally {
8812
+ try {
8813
+ unlinkSync2(tmp);
8814
+ } catch {
8815
+ }
8816
+ }
8761
8817
  try {
8762
8818
  const st = statSync6(statsPath);
8763
8819
  _recordsCache = {
@@ -9991,7 +10047,7 @@ var init_reviewer = __esm({
9991
10047
  });
9992
10048
 
9993
10049
  // src/brain/skill-manager.ts
9994
- import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync, writeFileSync as writeFileSync4 } from "fs";
10050
+ import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
9995
10051
  import { homedir as homedir7 } from "os";
9996
10052
  import { join as join14 } from "path";
9997
10053
  import { randomUUID } from "crypto";
@@ -10033,7 +10089,7 @@ var init_skill_manager = __esm({
10033
10089
  const tmp = `${this.metaPath}.tmp`;
10034
10090
  try {
10035
10091
  writeFileSync4(tmp, JSON.stringify(out, null, 2), "utf-8");
10036
- renameSync(tmp, this.metaPath);
10092
+ renameSync2(tmp, this.metaPath);
10037
10093
  } catch {
10038
10094
  }
10039
10095
  }
@@ -12667,7 +12723,8 @@ function _resetBrainForTest() {
12667
12723
  }
12668
12724
  async function runAnalysis(input) {
12669
12725
  const observedFormalLayers = [];
12670
- const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
12726
+ const heuristicEnabled = isHeuristicEnabled();
12727
+ const heuristicResult = heuristicEnabled ? runHeuristicCheck(input) : null;
12671
12728
  if (heuristicResult) {
12672
12729
  traceSummary("l1.result", {
12673
12730
  hit: !heuristicResult.allowed,
@@ -12693,8 +12750,8 @@ async function runAnalysis(input) {
12693
12750
  );
12694
12751
  let scriptChain = null;
12695
12752
  if (input.aNext.actionType.toLowerCase() === "bash") {
12696
- scriptChain = analyzeScriptContent2(input, agentExt);
12697
- if (scriptChain.nodes.length > 0) {
12753
+ scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
12754
+ if (heuristicEnabled && scriptChain.nodes.length > 0) {
12698
12755
  for (const node of scriptChain.nodes) {
12699
12756
  if (node.unanalyzable) {
12700
12757
  return {
@@ -14049,6 +14106,8 @@ async function healthRoute(c) {
14049
14106
  status: degraded.length ? "degraded" : "healthy",
14050
14107
  degraded,
14051
14108
  instance: process.env.AGENT_MOSS_INSTANCE || "",
14109
+ // 实际监听端口(端口漂移后调用方靠它发现)
14110
+ port: parseInt(process.env.AGENT_MOSS_ACTUAL_PORT || "0", 10) || 0,
14052
14111
  metrics
14053
14112
  }));
14054
14113
  }
@@ -14934,7 +14993,8 @@ import { Hono as Hono2 } from "hono";
14934
14993
  import { cors } from "hono/cors";
14935
14994
  import { logger } from "hono/logger";
14936
14995
  import net from "net";
14937
- import { existsSync as existsSync21 } from "fs";
14996
+ import { existsSync as existsSync21, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync9 } from "fs";
14997
+ import { dirname as dirname14, join as join22 } from "path";
14938
14998
  function logDeploymentSelfCheck() {
14939
14999
  try {
14940
15000
  const mode = getRulesMode();
@@ -15175,9 +15235,28 @@ async function warmUpEngine() {
15175
15235
  else process.env.AGENT_MOSS_SAVE_POLICY = prevSavePolicy;
15176
15236
  }
15177
15237
  }
15238
+ function writePortFile(port) {
15239
+ try {
15240
+ const path8 = join22(getDataRoot(), "agent_moss_server.port.json");
15241
+ mkdirSync9(dirname14(path8), { recursive: true });
15242
+ const payload = JSON.stringify({
15243
+ port,
15244
+ pid: process.pid,
15245
+ started_at: (/* @__PURE__ */ new Date()).toISOString()
15246
+ });
15247
+ const tmp = `${path8}.tmp`;
15248
+ writeFileSync7(tmp, payload, "utf-8");
15249
+ renameSync3(tmp, path8);
15250
+ console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path8} (port=${port})`);
15251
+ } catch (err) {
15252
+ console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
15253
+ }
15254
+ }
15178
15255
  async function startServer(host = "127.0.0.1", port = 9090) {
15179
15256
  failFastOnAuthError();
15180
15257
  const actualPort = await findFreePort(port, host);
15258
+ process.env.AGENT_MOSS_ACTUAL_PORT = String(actualPort);
15259
+ writePortFile(actualPort);
15181
15260
  const app = createApp();
15182
15261
  return {
15183
15262
  port: actualPort,
@@ -15209,12 +15288,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
15209
15288
  },
15210
15289
  serve: async () => {
15211
15290
  failFastOnAuthError();
15212
- const { mkdirSync: mkdirSync10, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15213
- const { dirname: dirname15 } = await import("path");
15214
- const dir = dirname15(socketPath);
15291
+ const { mkdirSync: mkdirSync11, existsSync: existsSync23, unlinkSync: unlinkSync6 } = await import("fs");
15292
+ const { dirname: dirname16 } = await import("path");
15293
+ const dir = dirname16(socketPath);
15215
15294
  if (dir) {
15216
15295
  try {
15217
- mkdirSync10(dir, { recursive: true });
15296
+ mkdirSync11(dir, { recursive: true });
15218
15297
  } catch {
15219
15298
  }
15220
15299
  }
@@ -15274,6 +15353,7 @@ var init_server = __esm({
15274
15353
  init_esm_shims();
15275
15354
  init_rules_contract();
15276
15355
  init_security_policy();
15356
+ init_paths();
15277
15357
  init_routes();
15278
15358
  init_console();
15279
15359
  init_runtime_config();
@@ -15346,18 +15426,18 @@ __export(rules_tools_exports, {
15346
15426
  rulesStatusText: () => rulesStatusText,
15347
15427
  templateSourceDir: () => templateSourceDir
15348
15428
  });
15349
- import { existsSync as existsSync22, mkdirSync as mkdirSync9, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync7 } from "fs";
15350
- import { dirname as dirname14, join as join22 } from "path";
15429
+ import { existsSync as existsSync22, mkdirSync as mkdirSync10, readdirSync as readdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync8 } from "fs";
15430
+ import { dirname as dirname15, join as join23 } from "path";
15351
15431
  import { fileURLToPath as fileURLToPath12 } from "url";
15352
15432
  function initRulesDir(targetDir, opts = {}) {
15353
- mkdirSync9(targetDir, { recursive: true });
15433
+ mkdirSync10(targetDir, { recursive: true });
15354
15434
  const written = [];
15355
- const extraPath = join22(targetDir, EXTRA_FILENAME);
15435
+ const extraPath = join23(targetDir, EXTRA_FILENAME);
15356
15436
  if (opts.force || !existsSync22(extraPath)) {
15357
- writeFileSync7(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
15437
+ writeFileSync8(extraPath, JSON.stringify(EXTRA_TEMPLATE, null, 2), "utf-8");
15358
15438
  written.push(extraPath);
15359
15439
  }
15360
- const samplePath = join22(targetDir, OVERRIDE_FILENAME);
15440
+ const samplePath = join23(targetDir, OVERRIDE_FILENAME);
15361
15441
  if (opts.force || !existsSync22(samplePath)) {
15362
15442
  let payload = OVERRIDE_TEMPLATE;
15363
15443
  if (opts.withBuiltin) {
@@ -15373,19 +15453,19 @@ function initRulesDir(targetDir, opts = {}) {
15373
15453
  payload = { _\u8BF4\u660E: OVERRIDE_BUILTIN_NOTE };
15374
15454
  for (const k of L1_KEYS) payload[k] = data[k] || [];
15375
15455
  }
15376
- writeFileSync7(samplePath, JSON.stringify(payload, null, 2), "utf-8");
15456
+ writeFileSync8(samplePath, JSON.stringify(payload, null, 2), "utf-8");
15377
15457
  written.push(samplePath);
15378
15458
  }
15379
- const readmeSrc = join22(templateSourceDir(), "README.md");
15380
- const readmeDst = join22(targetDir, "README.md");
15459
+ const readmeSrc = join23(templateSourceDir(), "README.md");
15460
+ const readmeDst = join23(targetDir, "README.md");
15381
15461
  if (existsSync22(readmeSrc) && (opts.force || !existsSync22(readmeDst))) {
15382
- writeFileSync7(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
15462
+ writeFileSync8(readmeDst, readFileSync21(readmeSrc, "utf-8"), "utf-8");
15383
15463
  written.push(readmeDst);
15384
15464
  }
15385
15465
  return written;
15386
15466
  }
15387
15467
  function templateSourceDir() {
15388
- const cands = [join22(__dirname11, "data", "rules_template"), join22(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
15468
+ const cands = [join23(__dirname11, "data", "rules_template"), join23(__dirname11, "..", "..", "agent_moss", "data", "rules_template")];
15389
15469
  for (const c of cands) if (existsSync22(c)) return c;
15390
15470
  return cands[0];
15391
15471
  }
@@ -15394,7 +15474,7 @@ function templateFiles(dirs) {
15394
15474
  for (const d of dirs) {
15395
15475
  try {
15396
15476
  for (const name of readdirSync7(d)) {
15397
- if (name.endsWith(".json.\u793A\u4F8B")) out.push(join22(d, name));
15477
+ if (name.endsWith(".json.\u793A\u4F8B")) out.push(join23(d, name));
15398
15478
  }
15399
15479
  } catch {
15400
15480
  }
@@ -15450,7 +15530,7 @@ var init_rules_tools = __esm({
15450
15530
  "use strict";
15451
15531
  init_esm_shims();
15452
15532
  init_rules_loader();
15453
- __dirname11 = dirname14(fileURLToPath12(import.meta.url));
15533
+ __dirname11 = dirname15(fileURLToPath12(import.meta.url));
15454
15534
  EXTRA_TEMPLATE = {
15455
15535
  _\u8BF4\u660E: [
15456
15536
  "\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
- const injectionHits = checkInjectionKeywords(injectionText, agentExt?.extra_injection_keywords, input.osType);
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 checkInjectionKeywords(text, extraKeywords, osType) {
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
  }
@@ -5304,7 +5330,7 @@ __export(token_stats_exports, {
5304
5330
  resetTokenStats: () => resetTokenStats,
5305
5331
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
5306
5332
  });
5307
- import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
5333
+ import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
5308
5334
  function getStatsPath() {
5309
5335
  const envPath = process.env[ENV_STATS_PATH];
5310
5336
  if (envPath) return envPath;
@@ -5338,7 +5364,16 @@ function saveRecords(statsPath, records) {
5338
5364
  try {
5339
5365
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
5340
5366
  if (dir && !existsSync12(dir)) mkdirSync3(dir, { recursive: true });
5341
- writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
5367
+ const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
5368
+ try {
5369
+ writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
5370
+ renameSync(tmp, statsPath);
5371
+ } finally {
5372
+ try {
5373
+ unlinkSync2(tmp);
5374
+ } catch {
5375
+ }
5376
+ }
5342
5377
  try {
5343
5378
  const st = statSync6(statsPath);
5344
5379
  _recordsCache = {
@@ -7178,11 +7213,12 @@ function emptyNode(pathStr, depth) {
7178
7213
  };
7179
7214
  }
7180
7215
  var RecursiveTracker = class {
7181
- constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE) {
7216
+ constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
7182
7217
  this.maxDepth = maxDepth;
7183
7218
  this.maxNodes = maxNodes;
7184
7219
  this.maxFileSize = maxFileSize;
7185
7220
  this.maxTotalSize = maxTotalSize;
7221
+ this.stopOnCritical = stopOnCritical;
7186
7222
  this._scanner = commandScanner;
7187
7223
  this.result = {
7188
7224
  nodes: [],
@@ -7203,6 +7239,7 @@ var RecursiveTracker = class {
7203
7239
  maxNodes;
7204
7240
  maxFileSize;
7205
7241
  maxTotalSize;
7242
+ stopOnCritical;
7206
7243
  result;
7207
7244
  visiting = /* @__PURE__ */ new Set();
7208
7245
  visitedPaths = /* @__PURE__ */ new Set();
@@ -7267,9 +7304,11 @@ var RecursiveTracker = class {
7267
7304
  node.l1MatchedPatterns = l1.matchedPatterns || [];
7268
7305
  if (l1.riskLevel === "critical") {
7269
7306
  this.result.hasCritical = true;
7270
- this.result.firstHitNode = node;
7271
- this.visiting.delete(pathStr);
7272
- return;
7307
+ if (!this.result.firstHitNode) this.result.firstHitNode = node;
7308
+ if (this.stopOnCritical) {
7309
+ this.visiting.delete(pathStr);
7310
+ return;
7311
+ }
7273
7312
  }
7274
7313
  }
7275
7314
  }
@@ -7279,7 +7318,7 @@ var RecursiveTracker = class {
7279
7318
  const child = resolvePath(call.path, parentDir);
7280
7319
  childPaths.push(child);
7281
7320
  this.visitScript(child, depth + 1, path4.dirname(child), call.args);
7282
- if (this.result.hasCritical) break;
7321
+ if (this.stopOnCritical && this.result.hasCritical) break;
7283
7322
  }
7284
7323
  node.childPaths = childPaths;
7285
7324
  this.visiting.delete(pathStr);
@@ -7597,7 +7636,7 @@ function scanScriptChainKeywords(chain) {
7597
7636
  }
7598
7637
  return chain;
7599
7638
  }
7600
- function analyzeScriptContent2(input, ext) {
7639
+ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
7601
7640
  const actionType = input.aNext.actionType.toLowerCase();
7602
7641
  if (actionType !== "bash") return emptyChain();
7603
7642
  const { path: scriptPath, args: scriptArgs } = extractScriptPathWithArgs(input.aNext.actionDetail);
@@ -7626,7 +7665,14 @@ function analyzeScriptContent2(input, ext) {
7626
7665
  }
7627
7666
  return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
7628
7667
  };
7629
- const tracker = new RecursiveTracker(l1Adapter);
7668
+ const tracker = new RecursiveTracker(
7669
+ l1Adapter,
7670
+ void 0,
7671
+ void 0,
7672
+ void 0,
7673
+ void 0,
7674
+ stopOnCritical
7675
+ );
7630
7676
  const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
7631
7677
  if (chain.nodes.length === 0) return chain;
7632
7678
  scanScriptChainWithL1(chain, input, ext);
@@ -9143,7 +9189,7 @@ function parseReview(content) {
9143
9189
 
9144
9190
  // src/brain/skill-manager.ts
9145
9191
  init_esm_shims();
9146
- import { existsSync as existsSync14, mkdirSync as mkdirSync5, readFileSync as readFileSync14, renameSync, writeFileSync as writeFileSync4 } from "fs";
9192
+ import { existsSync as existsSync14, mkdirSync as mkdirSync5, readFileSync as readFileSync14, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
9147
9193
  import { homedir as homedir7 } from "os";
9148
9194
  import { join as join13 } from "path";
9149
9195
  import { randomUUID } from "crypto";
@@ -9180,7 +9226,7 @@ var BrainSkillManager = class {
9180
9226
  const tmp = `${this.metaPath}.tmp`;
9181
9227
  try {
9182
9228
  writeFileSync4(tmp, JSON.stringify(out, null, 2), "utf-8");
9183
- renameSync(tmp, this.metaPath);
9229
+ renameSync2(tmp, this.metaPath);
9184
9230
  } catch {
9185
9231
  }
9186
9232
  }
@@ -10630,7 +10676,8 @@ function _resetBrainForTest() {
10630
10676
  var formalEngine = new FormalEngine();
10631
10677
  async function runAnalysis(input) {
10632
10678
  const observedFormalLayers = [];
10633
- const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
10679
+ const heuristicEnabled = isHeuristicEnabled();
10680
+ const heuristicResult = heuristicEnabled ? runHeuristicCheck(input) : null;
10634
10681
  if (heuristicResult) {
10635
10682
  traceSummary("l1.result", {
10636
10683
  hit: !heuristicResult.allowed,
@@ -10656,8 +10703,8 @@ async function runAnalysis(input) {
10656
10703
  );
10657
10704
  let scriptChain = null;
10658
10705
  if (input.aNext.actionType.toLowerCase() === "bash") {
10659
- scriptChain = analyzeScriptContent2(input, agentExt);
10660
- if (scriptChain.nodes.length > 0) {
10706
+ scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
10707
+ if (heuristicEnabled && scriptChain.nodes.length > 0) {
10661
10708
  for (const node of scriptChain.nodes) {
10662
10709
  if (node.unanalyzable) {
10663
10710
  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
- const injectionHits = checkInjectionKeywords(injectionText, agentExt?.extra_injection_keywords, input.osType);
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 checkInjectionKeywords(text, extraKeywords, osType) {
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
  }
@@ -7419,11 +7445,12 @@ var init_tracker = __esm({
7419
7445
  };
7420
7446
  DEFAULT_BACKEND = new ShellBackend();
7421
7447
  RecursiveTracker = class {
7422
- constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE) {
7448
+ constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
7423
7449
  this.maxDepth = maxDepth;
7424
7450
  this.maxNodes = maxNodes;
7425
7451
  this.maxFileSize = maxFileSize;
7426
7452
  this.maxTotalSize = maxTotalSize;
7453
+ this.stopOnCritical = stopOnCritical;
7427
7454
  this._scanner = commandScanner;
7428
7455
  this.result = {
7429
7456
  nodes: [],
@@ -7444,6 +7471,7 @@ var init_tracker = __esm({
7444
7471
  maxNodes;
7445
7472
  maxFileSize;
7446
7473
  maxTotalSize;
7474
+ stopOnCritical;
7447
7475
  result;
7448
7476
  visiting = /* @__PURE__ */ new Set();
7449
7477
  visitedPaths = /* @__PURE__ */ new Set();
@@ -7508,9 +7536,11 @@ var init_tracker = __esm({
7508
7536
  node.l1MatchedPatterns = l1.matchedPatterns || [];
7509
7537
  if (l1.riskLevel === "critical") {
7510
7538
  this.result.hasCritical = true;
7511
- this.result.firstHitNode = node;
7512
- this.visiting.delete(pathStr);
7513
- return;
7539
+ if (!this.result.firstHitNode) this.result.firstHitNode = node;
7540
+ if (this.stopOnCritical) {
7541
+ this.visiting.delete(pathStr);
7542
+ return;
7543
+ }
7514
7544
  }
7515
7545
  }
7516
7546
  }
@@ -7520,7 +7550,7 @@ var init_tracker = __esm({
7520
7550
  const child = resolvePath(call.path, parentDir);
7521
7551
  childPaths.push(child);
7522
7552
  this.visitScript(child, depth + 1, path4.dirname(child), call.args);
7523
- if (this.result.hasCritical) break;
7553
+ if (this.stopOnCritical && this.result.hasCritical) break;
7524
7554
  }
7525
7555
  node.childPaths = childPaths;
7526
7556
  this.visiting.delete(pathStr);
@@ -7825,7 +7855,7 @@ function scanScriptChainKeywords(chain) {
7825
7855
  }
7826
7856
  return chain;
7827
7857
  }
7828
- function analyzeScriptContent2(input, ext) {
7858
+ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
7829
7859
  const actionType = input.aNext.actionType.toLowerCase();
7830
7860
  if (actionType !== "bash") return emptyChain();
7831
7861
  const { path: scriptPath, args: scriptArgs } = extractScriptPathWithArgs(input.aNext.actionDetail);
@@ -7854,7 +7884,14 @@ function analyzeScriptContent2(input, ext) {
7854
7884
  }
7855
7885
  return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
7856
7886
  };
7857
- const tracker = new RecursiveTracker(l1Adapter);
7887
+ const tracker = new RecursiveTracker(
7888
+ l1Adapter,
7889
+ void 0,
7890
+ void 0,
7891
+ void 0,
7892
+ void 0,
7893
+ stopOnCritical
7894
+ );
7858
7895
  const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
7859
7896
  if (chain.nodes.length === 0) return chain;
7860
7897
  scanScriptChainWithL1(chain, input, ext);
@@ -8423,7 +8460,7 @@ __export(token_stats_exports, {
8423
8460
  resetTokenStats: () => resetTokenStats,
8424
8461
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
8425
8462
  });
8426
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
8463
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync2, existsSync as existsSync13, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
8427
8464
  function getStatsPath() {
8428
8465
  const envPath = process.env[ENV_STATS_PATH];
8429
8466
  if (envPath) return envPath;
@@ -8457,7 +8494,16 @@ function saveRecords(statsPath, records) {
8457
8494
  try {
8458
8495
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
8459
8496
  if (dir && !existsSync13(dir)) mkdirSync3(dir, { recursive: true });
8460
- writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
8497
+ const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
8498
+ try {
8499
+ writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
8500
+ renameSync(tmp, statsPath);
8501
+ } finally {
8502
+ try {
8503
+ unlinkSync2(tmp);
8504
+ } catch {
8505
+ }
8506
+ }
8461
8507
  try {
8462
8508
  const st = statSync6(statsPath);
8463
8509
  _recordsCache = {
@@ -9691,7 +9737,7 @@ var init_reviewer = __esm({
9691
9737
  });
9692
9738
 
9693
9739
  // src/brain/skill-manager.ts
9694
- import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync, writeFileSync as writeFileSync4 } from "fs";
9740
+ import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
9695
9741
  import { homedir as homedir7 } from "os";
9696
9742
  import { join as join14 } from "path";
9697
9743
  import { randomUUID } from "crypto";
@@ -9733,7 +9779,7 @@ var init_skill_manager = __esm({
9733
9779
  const tmp = `${this.metaPath}.tmp`;
9734
9780
  try {
9735
9781
  writeFileSync4(tmp, JSON.stringify(out, null, 2), "utf-8");
9736
- renameSync(tmp, this.metaPath);
9782
+ renameSync2(tmp, this.metaPath);
9737
9783
  } catch {
9738
9784
  }
9739
9785
  }
@@ -12102,7 +12148,8 @@ function _resetBrainForTest() {
12102
12148
  }
12103
12149
  async function runAnalysis(input) {
12104
12150
  const observedFormalLayers = [];
12105
- const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
12151
+ const heuristicEnabled = isHeuristicEnabled();
12152
+ const heuristicResult = heuristicEnabled ? runHeuristicCheck(input) : null;
12106
12153
  if (heuristicResult) {
12107
12154
  traceSummary("l1.result", {
12108
12155
  hit: !heuristicResult.allowed,
@@ -12128,8 +12175,8 @@ async function runAnalysis(input) {
12128
12175
  );
12129
12176
  let scriptChain = null;
12130
12177
  if (input.aNext.actionType.toLowerCase() === "bash") {
12131
- scriptChain = analyzeScriptContent2(input, agentExt);
12132
- if (scriptChain.nodes.length > 0) {
12178
+ scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
12179
+ if (heuristicEnabled && scriptChain.nodes.length > 0) {
12133
12180
  for (const node of scriptChain.nodes) {
12134
12181
  if (node.unanalyzable) {
12135
12182
  return {
@@ -12658,10 +12705,12 @@ function enforceRulesContract() {
12658
12705
 
12659
12706
  // src/server.ts
12660
12707
  init_security_policy();
12708
+ init_paths();
12661
12709
  import { cors } from "hono/cors";
12662
12710
  import { logger } from "hono/logger";
12663
12711
  import net from "net";
12664
- import { existsSync as existsSync21 } from "fs";
12712
+ import { existsSync as existsSync21, writeFileSync as writeFileSync6, renameSync as renameSync3, mkdirSync as mkdirSync8 } from "fs";
12713
+ import { dirname as dirname14, join as join21 } from "path";
12665
12714
 
12666
12715
  // src/routes.ts
12667
12716
  init_esm_shims();
@@ -12680,9 +12729,17 @@ var pkg = require2("../package.json");
12680
12729
  var version = pkg.version;
12681
12730
 
12682
12731
  // src/models.ts
12732
+ var isNonEmptyNoControl = (v) => v.trim().length > 0 && ![...v].some((c) => {
12733
+ const n = c.codePointAt(0) ?? 0;
12734
+ return n < 32 || n >= 127 && n <= 159;
12735
+ });
12683
12736
  var ActionItemSchema = z.object({
12684
- action_type: z.string().describe("Action type, e.g. bash, file_read, file_write"),
12685
- action_detail: z.string().describe("Action detail / command content"),
12737
+ action_type: z.string().refine(isNonEmptyNoControl, {
12738
+ message: "action_type must be nonempty and contain no control characters"
12739
+ }).describe("Action type, e.g. bash, file_read, file_write"),
12740
+ action_detail: z.string().refine((v) => !v.includes("\0"), {
12741
+ message: "action_detail must not contain NUL characters"
12742
+ }).describe("Action detail / command content"),
12686
12743
  // 工具返回给 agent 的内容。仅 L2 的授权(consent)判定用:判断「用户是否已授权」
12687
12744
  // 看的是 ask_user_question 的**回答**,不是提问正文。历史 bug:模型里没有这个字段、
12688
12745
  // 路由也没透传,TS 的授权判定退化成「提问正文非空」,等于问过任何问题即已授权。
@@ -12775,6 +12832,8 @@ var HealthResponseSchema = z.object({
12775
12832
  // 降级原因(status=degraded 时非空)
12776
12833
  degraded: z.array(z.string()).default([]),
12777
12834
  version: z.string().default(version),
12835
+ // 实际监听端口(端口被占用自动漂移后,调用方从这里得知新端口)。
12836
+ port: z.number().default(0),
12778
12837
  // 归属实例标识:值来自 env AGENT_MOSS_INSTANCE(spawn/systemd 注入),默认空串。
12779
12838
  // 多个 agentmoss 同机并存时,调用方按 instance 过滤避免连到别人的进程。
12780
12839
  // 空=未配置(独立部署或旧版),调用方可选择兼容或严格过滤。
@@ -13713,6 +13772,8 @@ async function healthRoute(c) {
13713
13772
  status: degraded.length ? "degraded" : "healthy",
13714
13773
  degraded,
13715
13774
  instance: process.env.AGENT_MOSS_INSTANCE || "",
13775
+ // 实际监听端口(端口漂移后调用方靠它发现)
13776
+ port: parseInt(process.env.AGENT_MOSS_ACTUAL_PORT || "0", 10) || 0,
13716
13777
  metrics
13717
13778
  }));
13718
13779
  }
@@ -14845,9 +14906,28 @@ async function warmUpEngine() {
14845
14906
  else process.env.AGENT_MOSS_SAVE_POLICY = prevSavePolicy;
14846
14907
  }
14847
14908
  }
14909
+ function writePortFile(port) {
14910
+ try {
14911
+ const path8 = join21(getDataRoot(), "agent_moss_server.port.json");
14912
+ mkdirSync8(dirname14(path8), { recursive: true });
14913
+ const payload = JSON.stringify({
14914
+ port,
14915
+ pid: process.pid,
14916
+ started_at: (/* @__PURE__ */ new Date()).toISOString()
14917
+ });
14918
+ const tmp = `${path8}.tmp`;
14919
+ writeFileSync6(tmp, payload, "utf-8");
14920
+ renameSync3(tmp, path8);
14921
+ console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path8} (port=${port})`);
14922
+ } catch (err) {
14923
+ console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
14924
+ }
14925
+ }
14848
14926
  async function startServer(host = "127.0.0.1", port = 9090) {
14849
14927
  failFastOnAuthError();
14850
14928
  const actualPort = await findFreePort(port, host);
14929
+ process.env.AGENT_MOSS_ACTUAL_PORT = String(actualPort);
14930
+ writePortFile(actualPort);
14851
14931
  const app = createApp();
14852
14932
  return {
14853
14933
  port: actualPort,
@@ -14879,12 +14959,12 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
14879
14959
  },
14880
14960
  serve: async () => {
14881
14961
  failFastOnAuthError();
14882
- const { mkdirSync: mkdirSync8, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
14883
- const { dirname: dirname14 } = await import("path");
14884
- const dir = dirname14(socketPath);
14962
+ const { mkdirSync: mkdirSync9, existsSync: existsSync22, unlinkSync: unlinkSync6 } = await import("fs");
14963
+ const { dirname: dirname15 } = await import("path");
14964
+ const dir = dirname15(socketPath);
14885
14965
  if (dir) {
14886
14966
  try {
14887
- mkdirSync8(dir, { recursive: true });
14967
+ mkdirSync9(dir, { recursive: true });
14888
14968
  } catch {
14889
14969
  }
14890
14970
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kenhkl/agent-moss",
3
- "version": "0.17.28",
3
+ "version": "0.17.29",
4
4
  "description": "Multi-layer security analysis engine for AI agents (TypeScript)",
5
5
  "type": "module",
6
6
  "main": "dist/server.js",