Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions agent-network/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion agent-network/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@sleep2agi/agent-network",
"version": "2.3.0-preview.255",
"version": "2.3.0-preview.256",
"description": "AI Agent Network CLI — Local-first multi-agent orchestration across 6 runtimes (Claude Code CLI / Claude Agent SDK / Codex SDK / Codex app-server / Grok Build ACP / OpenCode CLI) and 8+ LLM providers. Apache 2.0.",
"type": "module",
"main": "dist/src/client.js",
Expand Down
4 changes: 2 additions & 2 deletions agent-network/src/opencode-agent-node-pair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } fro
import { opencodeOwnedPathModeIsSafe } from "./opencode-owner-mode";
import { describeUnsafeDirectory, describeUnsafePath } from "./unsafe-package-path-reason";

export const PAIRED_AGENT_NETWORK_VERSION = "2.3.0-preview.255";
export const PAIRED_AGENT_NODE_VERSION = "2.5.0-preview.221";
export const PAIRED_AGENT_NETWORK_VERSION = "2.3.0-preview.256";
export const PAIRED_AGENT_NODE_VERSION = "2.5.0-preview.222";
export const PAIRED_AGENT_NODE_SPEC = `@sleep2agi/agent-node@${PAIRED_AGENT_NODE_VERSION}`;
// Backward-compatible names for the first consumer of the shared pair.
export const OPENCODE_AGENT_NETWORK_VERSION = PAIRED_AGENT_NETWORK_VERSION;
Expand Down
4 changes: 2 additions & 2 deletions agent-node/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion agent-node/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@sleep2agi/agent-node",
"version": "2.5.0-preview.221",
"version": "2.5.0-preview.222",
"description": "AI Agent runtime for CommHub networks. Supports Claude Code CLI, Claude Agent SDK, Codex SDK, Codex app-server, Grok Build ACP, and OpenCode CLI.",
"bin": {
"agent-node": "dist/cli.js"
Expand Down
4 changes: 2 additions & 2 deletions docs-site/docs/en/guide/getting-started.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions docs-site/docs/guide/getting-started.md

Large diffs are not rendered by default.

20 changes: 20 additions & 0 deletions docs/tests/release-v2.3.0-preview.256.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# agent-network (CLI) 2.3.0-preview.256

与 `@sleep2agi/agent-node` **2.5.0-preview.222** 精确配对。

## Why

只改配对常量:指向 agent-node `2.5.0-preview.222`(claude / codex-app-server / ACP 三类运行时的「停止」与能力位)。CLI 本体与 `.255` 一致。

## Install

```bash
npm install -g @sleep2agi/agent-network@2.3.0-preview.256 @sleep2agi/agent-node@2.5.0-preview.222
```

## Upgrade

```bash
anet pair # 打印与当前 CLI 精确配对的那一行
anet upgrade # 按配对升级节点与 CLI
```
35 changes: 35 additions & 0 deletions docs/tests/release-v2.5.0-preview.222.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# agent-node 2.5.0-preview.222

与 `@sleep2agi/agent-network` (CLI) **2.3.0-preview.256** 精确配对。

## Why

**回合控制能力位与「停止」实现**(`#5332` ③ 三步全部落地):

```text
claude(默认 runtime) #3786 复用已有 AbortController ⇒ 停止可用;插话仍不支持(SDK query() 无同轮注入)
codex-app-server #3788 bridge 增加 turn/interrupt ⇒ 停止可用
ACP(antigravity / grok)#3789 session/cancel 通知 ⇒ 停止可用(同时覆盖 grok ACP)
能力位:turn_interrupt_capable = opencode V2 共存 ∥ claude ∥ codex-app-server ∥ ACP
turn_steer_capable 仍只有 opencode V2 共存
```

## Install

```bash
npm install -g @sleep2agi/agent-node@2.5.0-preview.222 @sleep2agi/agent-network@2.3.0-preview.256
```

## Upgrade

```bash
anet pair # 打印与当前 CLI 精确配对的那一行
anet upgrade # 按配对升级节点与 CLI
```

## 未验

```text
· 真机:agy 节点 working 时点「停止」是否真的 cancelled(老版本 agy 可能不认 session/cancel;
若不认,按版本降级能力位或固定 false)
```
74 changes: 74 additions & 0 deletions server/src/event-loop-lag.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@
import { describe, expect, test } from "bun:test";
import {
eventLoopStats,
formatTopRoutes,
noteRequestServed,
rankTopRoutes,
recordGap,
resetEventLoopLagForTests,
startEventLoopLagMonitor,
STALL_TOP_ROUTES,
} from "./event-loop-lag.js";
import { formatSlowSql, slowSqlThresholdMs } from "./db-adapter.js";

Expand Down Expand Up @@ -71,6 +74,77 @@ describe("event-loop-lag: recordGap", () => {
});
});

describe("event-loop-lag: 停顿归因(2026-11-23)", () => {
test("rankTopRoutes:按总耗时降序取前 5,保留次数/最大值", () => {
const top = rankTopRoutes([
{ route: "a", count: 1, total_ms: 10, max_ms: 10 },
{ route: "b", count: 3, total_ms: 90, max_ms: 40 },
{ route: "c", count: 2, total_ms: 30, max_ms: 20 },
{ route: "d", count: 1, total_ms: 5, max_ms: 5 },
{ route: "e", count: 1, total_ms: 1, max_ms: 1 },
{ route: "f", count: 1, total_ms: 100, max_ms: 100 },
]);
expect(top.map(r => r.route)).toEqual(["f", "b", "c", "a", "d"]);
expect(top.length).toBe(STALL_TOP_ROUTES);
expect(top[1].count).toBe(3);
expect(top[1].max_ms).toBe(40);
});

test("recordGap:停顿记录里带上 top_routes(/health recent_stalls 读的就是它)", () => {
resetEventLoopLagForTests();
recordGap(30_000, {
intervalMs: 250, thresholdMs: 2_000, rssMb: 900, served: 120,
topRoutes: [
{ route: "POST /mcp tools/call report_status", count: 40, total_ms: 5_000, max_ms: 300 },
{ route: "GET /api/inbox", count: 60, total_ms: 2_000, max_ms: 120 },
],
});
const s = eventLoopStats().recent_stalls[0];
expect(s.requests_since_last_tick).toBe(120);
expect(s.top_routes?.map(r => r.route)).toEqual(["POST /mcp tools/call report_status", "GET /api/inbox"]);
expect(s.top_routes?.[0].total_ms).toBe(5000);
});

test("未接归因源时停顿记录不出现 top_routes(与旧行为一致)", () => {
resetEventLoopLagForTests();
recordGap(30_000, { intervalMs: 250, thresholdMs: 2_000 });
expect(eventLoopStats().recent_stalls[0].top_routes).toBeUndefined();
});

test("formatTopRoutes:空/未定义为空串,有数据时带次数与最大值", () => {
expect(formatTopRoutes(undefined)).toBe("");
expect(formatTopRoutes([])).toBe("");
const line = formatTopRoutes([{ route: "GET /api/inbox", count: 7, total_ms: 140.4, max_ms: 90.2 }]);
expect(line).toContain("GET /api/inbox ×7 140ms max 90ms");
});

test("monitor:每个 tick 都抽干归因窗口,停顿日志与记录里带前 5", async () => {
resetEventLoopLagForTests();
const logs: string[] = [];
let drains = 0;
const timer = startEventLoopLagMonitor({
intervalMs: 20,
thresholdMs: 40,
log: (m) => logs.push(m),
rssMb: () => 321,
bootGraceMs: 0,
tickRoutes: () => {
drains++;
// 每 tick 只给一条,证明窗口是「这次窗口」而不是累积好几轮
return [{ route: "GET /api/inbox", count: 1, total_ms: 5, max_ms: 5 }];
},
});
const until = performance.now() + 120;
while (performance.now() < until) { /* spin */ }
await Bun.sleep(60);
clearInterval(timer);
expect(drains).toBeGreaterThan(0);
expect(logs.length).toBeGreaterThan(0);
expect(logs[0]).toContain("top: GET /api/inbox ×1 5ms max 5ms");
expect(eventLoopStats().recent_stalls[0].top_routes?.[0].route).toBe("GET /api/inbox");
});
});

describe("event-loop-lag: startEventLoopLagMonitor", () => {
test("阈值 0 时不打日志,但仍然计数", async () => {
resetEventLoopLagForTests();
Expand Down
65 changes: 62 additions & 3 deletions server/src/event-loop-lag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,18 @@
// 注意:`setInterval` 自己也会被阻塞 —— 这正是我们要测量的东西。
// 停顿结束后第一次 tick 的 gap 就是停顿长度,不需要外部进程配合。

/**
* 一个 tick 窗口里某个路由(或 MCP 工具)的耗时累计。
* 只记「次数 / 总耗时 / 单次最大」,不记 query、不记请求体、不记别名。
*/
export type TickRouteCost = {
/** 路由形状,MCP 会带工具名,如 "POST /mcp tools/call report_status"。 */
route: string;
count: number;
total_ms: number;
max_ms: number;
};

export type EventLoopStall = {
/** 这个间隔里处理完的请求数:0 = 真的没推进;>0 = 循环在干活,只是 timer 被饿住。 */
/** ISO 时间(停顿**结束**的时刻,即这次 tick 的时间)。 */
Expand All @@ -26,8 +38,19 @@ export type EventLoopStall = {
/** 停顿结束时的进程 RSS(MB),用于和内存尖峰对齐。 */
rss_mb: number;
requests_since_last_tick?: number;
/**
* 这个停顿窗口里总耗时最高的前几条路由(最多 5 条,按 total_ms 降序)。
* 归因用:requests_since_last_tick 说明循环在干活,这里说明**活是谁干的**。
* 未接计时源(测试 / 早期调用)时缺省。
*/
top_routes?: TickRouteCost[];
};

/** 一次停顿里最多留几条路由归因。 */
export const STALL_TOP_ROUTES = 5;
/** 日志里每个路由名的最大长度(MCP 标签已经限长,这里再兜一层,避免一行被撑爆)。 */
const STALL_ROUTE_CLIP = 48;

const KEEP_STALLS = 20;

/**
Expand Down Expand Up @@ -57,7 +80,7 @@ const stalls: EventLoopStall[] = [];
/** 记录一次 tick 间隔。返回这次 tick 的停顿量(毫秒,可为负→归零)。 */
export function recordGap(
gapMs: number,
opts: { intervalMs?: number; thresholdMs?: number; rssMb?: number; now?: number; served?: number } = {},
opts: { intervalMs?: number; thresholdMs?: number; rssMb?: number; now?: number; served?: number; topRoutes?: readonly TickRouteCost[] } = {},
): number {
const interval = opts.intervalMs ?? 250;
const threshold = opts.thresholdMs ?? 2000;
Expand All @@ -69,17 +92,39 @@ export function recordGap(
stallCount++;
lastStallAt = at;
lastStallMs = stallMs;
const top = opts.topRoutes && opts.topRoutes.length ? rankTopRoutes(opts.topRoutes) : undefined;
stalls.push({
at,
gap_ms: Math.round(gapMs),
stall_ms: Math.round(stallMs),
rss_mb: opts.rssMb ?? 0,
requests_since_last_tick: opts.served ?? 0,
...(top ? { top_routes: top } : {}),
});
while (stalls.length > KEEP_STALLS) stalls.shift();
return stallMs;
}

/** 取总耗时最高的前 N 条(只在 stall 时调用,不是每 tick)。 */
export function rankTopRoutes(routes: readonly TickRouteCost[], limit = STALL_TOP_ROUTES): TickRouteCost[] {
const out = routes
.filter(r => r && r.count > 0)
.map(r => ({ route: r.route, count: r.count, total_ms: Math.round(r.total_ms * 10) / 10, max_ms: Math.round(r.max_ms * 10) / 10 }))
.sort((a, b) => b.total_ms - a.total_ms || b.max_ms - a.max_ms)
.slice(0, limit);
return out;
}

/** 把 top_routes 拼成日志后缀;空数组/未接计时源时返回空串。 */
export function formatTopRoutes(routes: readonly TickRouteCost[] | undefined): string {
if (!routes || !routes.length) return "";
const parts = routes.map(r => {
const route = r.route.length > STALL_ROUTE_CLIP ? `${r.route.slice(0, STALL_ROUTE_CLIP - 1)}…` : r.route;
return `${route} ×${r.count} ${Math.round(r.total_ms)}ms max ${Math.round(r.max_ms)}ms`;
});
return ` | top: ${parts.join("; ")}`;
}

/**
* 2026-10-31 —— 窗口两端必须跟着读数一起走(#3174)。
*
Expand Down Expand Up @@ -160,6 +205,11 @@ export function startEventLoopLagMonitor(opts: {
bootGraceMs?: number;
/** 测试注入:返回进程已运行的毫秒数(默认 process.uptime())。 */
uptimeMs?: () => number;
/**
* 归因来源:取走**本 tick 窗口**内按路由累计的耗时(route-timing.ts 的 takeTickRouteCosts),
* 每个 tick 都会被调用一次且会清空窗口。不接就没有 top_routes(行为与旧版一致)。
*/
tickRoutes?: () => TickRouteCost[];
} = {}): ReturnType<typeof setInterval> {
const intervalMs = opts.intervalMs ?? Math.max(50, envMs("COMMHUB_STALL_TICK_MS", 250));
const thresholdMs = opts.thresholdMs ?? envMs("COMMHUB_STALL_LOG_MS", 2000);
Expand All @@ -181,17 +231,26 @@ export function startEventLoopLagMonitor(opts: {
const rss = rssMb();
const served = servedSinceTick;
servedSinceTick = 0;
// 归因窗口必须每个 tick 都抽干:否则非停顿的 tick 会一直往同一次累计里堆,
// 停顿时看到的就成了「过去好几个 tick 的总和」。抽干是清空,不排序。
let tickRoutes: TickRouteCost[] = [];
if (opts.tickRoutes) {
try { tickRoutes = opts.tickRoutes() ?? []; } catch { tickRoutes = []; }
}
// 启动尖峰:只可能是**第一个** tick,且到来时进程才刚起来。
// 两个条件缺一不可 —— 只看「第一个 tick」会吞掉运行中立刻发生的真实停顿。
if (firstTick) {
firstTick = false;
if (uptimeMs() < bootGraceMs) return;
}
const stall = recordGap(gap, { intervalMs, thresholdMs, rssMb: rss, served });
// 排序/取前 N 只在真停顿的时候做。
const top = tickRoutes.length ? rankTopRoutes(tickRoutes) : undefined;
const stall = recordGap(gap, { intervalMs, thresholdMs, rssMb: rss, served, ...(top ? { topRoutes: top } : {}) });
if (thresholdMs > 0 && stall >= thresholdMs) {
// 和 retention/slow-sql 的日志同一前缀,方便 grep。
// `served` 是判据的关键:它非零就说明循环在干活,这段“gap”是 timer 被饿住,不是阻塞。
log(`[commhub stall] loop idle ~${Math.round(stall)}ms (tick gap ${Math.round(gap)}ms, rss ${rss} MB, served ${served} req)`);
// `top` 是归因:这个窗口里总耗时最高的几条路由(见 route-timing.ts 的 tick 归因)。
log(`[commhub stall] loop idle ~${Math.round(stall)}ms (tick gap ${Math.round(gap)}ms, rss ${rss} MB, served ${served} req)${formatTopRoutes(top)}`);
}
}, intervalMs);
// 监测不该拖住进程退出。
Expand Down
3 changes: 2 additions & 1 deletion server/src/mcp-inflight.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ describe("#2363 server wiring (source assertions)", () => {
// 抛异常路径
expect(src).toContain("settleMcpInflight();\n throw e;");
// 正常路径(setImmediate 里 close 完成后结算,且重复调用安全)
expect(src).toContain("mcpServer.close().catch(() => {}).finally(settleMcpInflight)");
// 2026-11-23 复用池:结算挂在 close().finally 上,close 成功才回池(.then),失败丢弃(.catch)。
expect(src).toContain("mcpServer.close().then(() => releaseServer(mcpServerKey, mcpServer)).catch(() => {}).finally(settleMcpInflight)");
// 幂等闸门:只允许真正减一次
expect(src).toContain("if (mcpInflightSettled) return;");
});
Expand Down
Loading
Loading