Skip to content
Open
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: 3 additions & 1 deletion src/claude-mcp-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ export function _setClaudeHostPidForTest(pid: number | undefined): void {
async function probeProxyHealth(origin: string): Promise<boolean> {
try {
const res = await fetch(healthUrl(origin), { signal: AbortSignal.timeout(2000) });
return res.ok;
if (!res.ok) return false;
const payload = await res.json() as { ok?: unknown } | null;
return payload?.ok === true;
} catch {
return false;
}
Expand Down
88 changes: 64 additions & 24 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2764,7 +2764,7 @@ export function warnResponsesReasoningPairs(
* block with recorded refs needs exact matching) and each call's args are
* parsed at most ONCE, whereas the old per-block scan reparsed them for
* every block. */
function buildCarrierIndex(messages: BiliMessage[]): { callIds: Set<string>; compressCalls: BiliMessage[]; ensureRangePairs: () => Map<string, Set<string>> } {
function buildCarrierIndex(messages: BiliMessage[]): { callIds: Set<string>; compressCalls: BiliMessage[]; ensureRangePairs: () => Map<string, Set<string>>; ensureRangeSummaries: () => Map<string, Map<string, Set<string>>> } {
const callIds = new Set<string>();
const compressCalls: BiliMessage[] = [];
for (const m of messages) {
Expand All @@ -2773,33 +2773,56 @@ function buildCarrierIndex(messages: BiliMessage[]): { callIds: Set<string>; com
if (m.toolName === COMPRESS_TOOL_NAME) compressCalls.push(m);
}
let rangePairs: Map<string, Set<string>> | null = null;
const ensureRangePairs = (): Map<string, Set<string>> => {
if (!rangePairs) {
rangePairs = new Map<string, Set<string>>();
for (const c of compressCalls) {
let parsed: unknown;
try {
parsed = JSON.parse(c.text ?? "");
} catch {
continue;
}
const obj = parsed as { startId?: string; endId?: string; content?: unknown };
const ranges: Array<{ startId?: string; endId?: string }> = Array.isArray(obj?.content) ? (obj.content as Array<{ startId?: string; endId?: string }>) : [obj];
for (const r of ranges) {
if (typeof r?.startId !== "string" || !r.startId || typeof r?.endId !== "string" || !r.endId) continue;
let ends = rangePairs.get(r.startId);
if (!ends) { ends = new Set<string>(); rangePairs.set(r.startId, ends); }
ends.add(r.endId);
}
let rangeSummaries: Map<string, Map<string, Set<string>>> | null = null;
const ensureRangeData = (): void => {
if (rangePairs && rangeSummaries) return;
rangePairs = new Map<string, Set<string>>();
rangeSummaries = new Map<string, Map<string, Set<string>>>();
for (const c of compressCalls) {
let parsed: unknown;
try {
parsed = JSON.parse(c.text ?? "");
} catch {
continue;
}
const obj = parsed as { startId?: string; endId?: string; summary?: unknown; content?: unknown };
const ranges: Array<{ startId?: string; endId?: string; summary?: unknown }> = Array.isArray(obj?.content) ? (obj.content as Array<{ startId?: string; endId?: string; summary?: unknown }>) : [obj];
for (const r of ranges) {
if (typeof r?.startId !== "string" || !r.startId || typeof r?.endId !== "string" || !r.endId) continue;
let ends = rangePairs.get(r.startId);
if (!ends) { ends = new Set<string>(); rangePairs.set(r.startId, ends); }
ends.add(r.endId);
const summary = typeof r.summary === "string" ? r.summary : "";
let sumEnds = rangeSummaries.get(r.startId);
if (!sumEnds) { sumEnds = new Map<string, Set<string>>(); rangeSummaries.set(r.startId, sumEnds); }
let summaries = sumEnds.get(r.endId);
if (!summaries) { summaries = new Set<string>(); sumEnds.set(r.endId, summaries); }
summaries.add(summary);
}
}
return rangePairs;
};
return { callIds, compressCalls, ensureRangePairs };
const ensureRangePairs = (): Map<string, Set<string>> => {
ensureRangeData();
return rangePairs!;
};
const ensureRangeSummaries = (): Map<string, Map<string, Set<string>>> => {
ensureRangeData();
return rangeSummaries!;
};
return { callIds, compressCalls, ensureRangePairs, ensureRangeSummaries };
}

// #5866: extract the body (everything after the first topic line) of a kernel
// summary anchor. The kernel renders anchors as `<topic-line>\n<body>` (or just
// the topic line when the body is empty); a simplified anchor with no newline
// yields its whole text as the body.
function extractAnchorBody(text: string): string {
const idx = text.indexOf("\n");
return idx === -1 ? text : text.slice(idx + 1);
}

export function stripKernelSummaries(messages: BiliMessage[], state: CompressionState): BiliMessage[] {
const { callIds, compressCalls, ensureRangePairs } = buildCarrierIndex(messages);
const { callIds, compressCalls, ensureRangePairs, ensureRangeSummaries } = buildCarrierIndex(messages);
const carried = new Set<string>();
for (const b of state.blocks) {
if (!b.active || !b.compressCallId) continue;
Expand All @@ -2815,9 +2838,26 @@ export function stripKernelSummaries(messages: BiliMessage[], state: Compression
const present = isPluginFoldCallId(b.compressCallId)
? (!b.startRef || !b.endRef ? compressCalls.length > 0 : ensureRangePairs().get(b.startRef)?.has(b.endRef) ?? false)
: callIds.has(b.compressCallId);
if (present) {
carried.add(`acp_summary_${b.blockId}`);
if (!present) continue;
// #5866 option A: integrity-aware anchor stripping for plugin folds.
// The re-sent compress call is only a full carrier while it still
// carries the FULL summary verbatim. After the first post-fold turn,
// hideConsumedCompressCalls stubs the call's summary to a 200-char
// prefix, so the call no longer carries the full text — the in-place
// anchor must then be the sole full carrier and MUST be kept. Strip
// only when some matching call's summary is verbatim-equal to the
// anchor's body; otherwise keep the anchor.
if (isPluginFoldCallId(b.compressCallId) && b.startRef && b.endRef) {
const anchorId = `acp_summary_${b.blockId}`;
const anchor = messages.find((m) => m.id === anchorId);
if (anchor) {
const anchorBody = extractAnchorBody(anchor.text ?? "");
const callSummaries = ensureRangeSummaries().get(b.startRef)?.get(b.endRef);
const fullCarrier = callSummaries ? Array.from(callSummaries).some((s) => s.trim() === anchorBody) : false;
if (!fullCarrier) continue;
}
}
carried.add(`acp_summary_${b.blockId}`);
}
return messages.filter((m) => !(m.id ?? "").startsWith("acp_summary_") || !carried.has(m.id));
}
Expand Down
173 changes: 173 additions & 0 deletions tests/claude-watchdog-health-payload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import assert from "node:assert/strict";
import { once } from "node:events";
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { test, type TestContext } from "node:test";
import { watchdogTick, type MutableWatchdogState, type WatchdogDeps } from "../src/claude-mcp-entry.ts";
import { forwardTool } from "../src/mcp.ts";
import { readClaudeManagedBaseUrl, repinClaudeManagedBaseUrl } from "../src/plugin-install.ts";
import { rmrf } from "./tmp-rm.ts";

type HealthReply = { status: number; body: string; contentType?: string; stall?: "headers" | "body" };
type Request = { listener: "old" | "replacement"; url: string; body?: Record<string, unknown> };

async function fixture(t: TestContext, initialReply: HealthReply) {
let reply = initialReply;
const requests: Request[] = [];
const servers: http.Server[] = [];
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-claude-health-payload-"));
const env = { CLAUDE_CONFIG_DIR: dir };
const previousPin = process.env.BILI_MCP_PROXY;
t.after(async () => {
if (previousPin === undefined) delete process.env.BILI_MCP_PROXY;
else process.env.BILI_MCP_PROXY = previousPin;
for (const server of servers) {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
rmrf(dir);
});

const listen = async (listener: "old" | "replacement"): Promise<string> => {
const server = http.createServer(async (req, res) => {
let raw = "";
for await (const chunk of req) raw += chunk;
const body = raw ? JSON.parse(raw) as Record<string, unknown> : undefined;
requests.push({ listener, url: req.url ?? "", body });
if (req.url === "/__bili/health" && listener === "old") {
if (reply.stall === "headers") return;
res.writeHead(reply.status, { "content-type": reply.contentType ?? "application/json" });
if (reply.stall === "body") {
res.write(reply.body);
return;
}
res.end(reply.body);
return;
}
res.setHeader("content-type", "application/json");
res.end(JSON.stringify(req.url === "/__bili/plugin/tool"
? { ok: true, result: `ACP receipt from ${listener}`, outcome: "success" }
: { ok: true, version: "0.1.216" }));
});
servers.push(server);
server.listen(0, "127.0.0.1");
await once(server, "listening");
const address = server.address();
assert.ok(address && typeof address === "object");
return `http://127.0.0.1:${address.port}`;
};

const origin = await listen("old");
const replacement = await listen("replacement");
const settingsPath = path.join(dir, "settings.json");
fs.writeFileSync(settingsPath, JSON.stringify({
env: { ANTHROPIC_BASE_URL: `${origin}/bili/https://api.anthropic.com`, KEEP_SETTING: "unchanged" },
permissions: { allow: ["Read"] },
}));
process.env.BILI_MCP_PROXY = origin;
const state: MutableWatchdogState = { origin, failures: 0 };
let ensureCalls = 0;
const deps: WatchdogDeps = {
ensure: async (opts) => {
ensureCalls += 1;
assert.equal(opts.port, 0);
assert.equal(opts.strictPort, false);
assert.equal(opts.lane, "claude");
return { origin: replacement, port: Number(new URL(replacement).port), attached: true };
},
repin: (next) => repinClaudeManagedBaseUrl(next, env),
};
const tick = () => watchdogTick(state, { port: 0, strict: false }, deps, () => {});
const assertRouting = async (listener: "old" | "replacement") => {
const expected = listener === "replacement" ? replacement : origin;
assert.equal(state.origin, expected);
assert.equal(process.env.BILI_MCP_PROXY, expected);
assert.equal(readClaudeManagedBaseUrl(env), expected);
const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
assert.equal(settings.env.KEEP_SETTING, "unchanged");
assert.deepEqual(settings.permissions, { allow: ["Read"] });
const receipt = await forwardTool("acp_status", { detail: "preserved" }, 2_000, "health-payload-session");
assert.equal(receipt.text, `ACP receipt from ${listener}`);
const posts = requests.filter((request) => request.url === "/__bili/plugin/tool");
assert.equal(posts.length, 1);
assert.equal(posts[0].listener, listener);
assert.equal(posts[0].body?.conversationId, "health-payload-session");
assert.deepEqual(posts[0].body?.args, { detail: "preserved" });
};
return { state, tick, assertRouting, ensureCalls: () => ensureCalls, setReply: (next: HealthReply) => { reply = next; } };
}

for (const [name, reply] of [
["HTML with status 200", { status: 200, body: "<!doctype html><html>Development app</html>", contentType: "text/html" }],
["an explicit not-ok reply", { status: 200, body: '{"ok":false}' }],
["a string ok flag", { status: 200, body: '{"ok":"true"}' }],
["a numeric ok flag", { status: 200, body: '{"ok":1}' }],
["a missing ok flag", { status: 200, body: '{"version":"other-service"}' }],
["JSON null", { status: 200, body: "null" }],
["a JSON primitive", { status: 200, body: "true" }],
["malformed JSON", { status: 200, body: '{"ok":true' }],
["an empty 204 reply", { status: 204, body: "" }],
] satisfies Array<[string, HealthReply]>) {
test(`Claude watchdog recovers after three health replies containing ${name}`, async (t) => {
const f = await fixture(t, reply);
await f.tick();
assert.equal(f.state.failures, 1);
await f.tick();
assert.equal(f.state.failures, 2);
assert.equal(f.ensureCalls(), 0);
await f.tick();
assert.equal(f.ensureCalls(), 1);
assert.equal(f.state.failures, 0);
await f.assertRouting("replacement");
await f.tick();
assert.equal(f.ensureCalls(), 1, "the replacement's valid health response prevents another recovery");
});
}

for (const contentType of ["application/json", "text/plain"]) {
test(`Claude watchdog accepts a valid health object served as ${contentType}`, async (t) => {
const f = await fixture(t, { status: 200, body: '{"ok":true,"version":"0.1.216"}', contentType });
f.state.failures = 2;
await f.tick();
assert.equal(f.state.failures, 0);
assert.equal(f.ensureCalls(), 0);
await f.assertRouting("old");
});
}

test("Claude watchdog still rejects an HTTP error even with an ok payload", async (t) => {
const f = await fixture(t, { status: 503, body: '{"ok":true}' });
for (let i = 0; i < 3; i++) await f.tick();
assert.equal(f.ensureCalls(), 1);
await f.assertRouting("replacement");
});

test("Claude watchdog requires consecutive invalid payloads after a healthy reset", async (t) => {
const f = await fixture(t, { status: 200, body: '{"ok":false}' });
await f.tick();
await f.tick();
assert.equal(f.state.failures, 2);
f.setReply({ status: 200, body: '{"ok":true}' });
await f.tick();
assert.equal(f.state.failures, 0);
f.setReply({ status: 200, body: '{"ok":false}' });
await f.tick();
await f.tick();
assert.equal(f.ensureCalls(), 0);
await f.tick();
assert.equal(f.ensureCalls(), 1);
await f.assertRouting("replacement");
});

for (const stall of ["headers", "body"] as const) {
test(`Claude watchdog bounds a stalled health ${stall} with its existing timeout`, { timeout: 10_000 }, async (t) => {
const f = await fixture(t, { status: 200, body: '{"ok":', stall });
f.state.failures = 2;
await f.tick();
assert.equal(f.ensureCalls(), 1, "an incomplete health reply cannot reset the failure counter");
assert.equal(f.state.failures, 0);
await f.assertRouting("replacement");
});
}
8 changes: 4 additions & 4 deletions tests/issue2042-carrier-index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ test("non-tool-call message carrying the same toolCallId does not count", () =>
});

test("plugin block: exact range match via flat args -> stripped", () => {
const messages = [summary("pb0"), toolCall("c1", "compress", '{"startId":"m1","endId":"m9"}'), tail(0)];
const messages = [summary("pb0"), toolCall("c1", "compress", '{"startId":"m1","endId":"m9","summary":"summary"}'), tail(0)];
const out = stripKernelSummaries(messages, stateWith([{ blockId: "pb0", active: true, compressCallId: "plugin_1", startRef: "m1", endRef: "m9" }]));
assert.deepEqual(ids(out), ["tc_c1", "u0"]);
});

test("plugin block: exact range match via content array -> stripped", () => {
const messages = [summary("pb0"), toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m9"}]}'), tail(0)];
const messages = [summary("pb0"), toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m9","summary":"summary"}]}'), tail(0)];
const out = stripKernelSummaries(messages, stateWith([{ blockId: "pb0", active: true, compressCallId: "plugin_1", startRef: "m1", endRef: "m9" }]));
assert.deepEqual(ids(out), ["tc_c1", "u0"]);
});
Expand Down Expand Up @@ -107,7 +107,7 @@ test("mixed branches: only blocks with carriers are stripped, order preserved",
const messages = [
summary("p_hit"), summary("p_miss"), summary("pl_hit"), summary("pl_bad"),
toolCall("proxy_call_p_hit", "bash"),
toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m2"},{"startId":"m3","endId":"m4"}]}'),
toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m2"},{"startId":"m3","endId":"m4","summary":"summary"}]}'),
toolCall("c2", "compress", "{bad json"),
tail(0),
];
Expand All @@ -124,7 +124,7 @@ test("mixed branches: only blocks with carriers are stripped, order preserved",
test("one content array serving two plugin blocks parses the args exactly once", () => {
const messages = [
summary("a0"), summary("a1"),
toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m2"},{"startId":"m3","endId":"m4"}]}'),
toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m2","summary":"summary"},{"startId":"m3","endId":"m4","summary":"summary"}]}'),
tail(0),
];
const state = stateWith([
Expand Down
Loading
Loading