From 1f7dc7f0f520a9029bb8afcb10eee1503d9a0981 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Thu, 3 Sep 2026 00:04:38 +0800 Subject: [PATCH] fix(#451): restore plugin-mode nudge injection + honest diagNudge log MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0.1.69 (225ceb4) gated all three nudge injection sites by !pluginMode on the premise that "in plugin mode the agent owns compression". The agent plugins (pi/omp) are pure protocol clients with NO nudge channel of their own, so the gate silently disabled proactive compression in plugin mode — leaving only preflight at the hard limit — while diagNudge kept logging "INJECT" (the log lied about delivery, same class as #413). - Drop !pluginMode from the anthropic/openai/responses nudge gates. The nudge is an ephemeral trailing user message (not persisted, never enters the agent's re-sent history, prefix-cache-anchor safe), so it belongs in BOTH modes. Tool injection stays gated by !pluginMode (the agent provides tools). - diagNudge now takes the actual willInject decision and prints INJECT only when the nudge truly reaches the upstream payload, else ARMED-SUPPRESSED. - README two-modes table: split the tools/nudge row (tools = none in plugin mode, nudge = yes in both modes). - tests/plugin-nudge-injection.test.ts: regression guard asserting the nudge is a trailing user message in BOTH proxy and plugin mode when armed (verified to fail 30!==31 against the old gate). typecheck / test(901) / build green. --- README.md | 3 +- src/server.ts | 46 ++++++---- tests/plugin-nudge-injection.test.ts | 131 +++++++++++++++++++++++++++ 3 files changed, 163 insertions(+), 17 deletions(-) create mode 100644 tests/plugin-nudge-injection.test.ts diff --git a/README.md b/README.md index 2ea186488d..fe47df7fcd 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,8 @@ The proxy runs in one of two modes, and **the mode decides who executes | **Summary carrier on the wire** | **the `compress` tool call** | **an `acp_summary` user message** | | System messages on the wire | always exactly 1 (client + prompt) | always exactly 1 (client + prompt) — summaries ride on user messages | | SGLang "single system" 400 (#377) | cannot happen | cannot happen (summaries are user messages, not system) | -| Proxy-injected tools + nudge | none (agent owns compression) | the 4 context tools + nudge (when enabled) | +| Proxy-injected `compress` tools | none — the agent registers the 4 ACP tools natively | the 4 context tools (when enabled) | +| Proxy-injected nudge | **yes** — the agent has no nudge channel of its own, so the proxy-side nudge is the proactive compression trigger (preflight alone only fires at the hard limit; #451) | yes (when enabled) | **Why the carriers differ.** In plugin mode the agent owns compression: the `compress` call + result live in the agent's own history and are re-sent every diff --git a/src/server.ts b/src/server.ts index 169e4ea8e9..26a3714257 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1364,7 +1364,7 @@ function diagTagSummary(messages: CoreMessage[], sessionId: string, strategy: st return `[${sessionId}] processTurn: ${messages.length} msgs, renderTags=${strategy}, ${textTagged} text tagged, ${toolTagged} tool tagged (should be 0 with text-only)`; } -function diagNudge(turn: { nudge?: { shouldInject: boolean; reason: string; contextUsage: number; tier: number | null; breakdown?: Record } | null }, sessionId: string, tokenCount: number, limit: number, model?: string): string { +function diagNudge(turn: { nudge?: { shouldInject: boolean; reason: string; contextUsage: number; tier: number | null; breakdown?: Record } | null }, sessionId: string, tokenCount: number, limit: number, model: string | undefined, willInject: boolean): string { const n = turn.nudge; if (!n) return `[${sessionId}] nudge: unavailable`; const b = n.breakdown ?? {}; @@ -1374,7 +1374,10 @@ function diagNudge(turn: { nudge?: { shouldInject: boolean; reason: string; cont const interval = b["nudgeGrowthTokens"] ?? 0; const pendingT1 = b["pendingT1"] ?? 0; const ref = b["growthReference"] ?? 0; - const inject = n.shouldInject ? `INJECT T${n.tier ?? "?"}` : "idle"; + // "INJECT" only when the nudge actually reaches the upstream payload. When + // armed but suppressed by config/mode, say so explicitly so the log never + // lies about delivery (#451, same class as #413). + const inject = !n.shouldInject ? "idle" : willInject ? `INJECT T${n.tier ?? "?"}` : `ARMED-SUPPRESSED T${n.tier ?? "?"}`; const modelTag = model ? ` model=${model}` : ""; return `[${sessionId}] nudge ${inject}: usage=${pct} (${tokenCount}/${limit}), growth=${growth}/${floor} (ref=${ref}, interval=${interval}), pendingT1=${pendingT1}/${interval}${modelTag}, reason="${n.reason.slice(0, 120)}"`; } @@ -1436,7 +1439,8 @@ function prepareAnthropic( if (t) session.meta.title = t; } log("info", diagTagSummary(turn.messages, sessionId, "text-only")); - log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model)); + const willInjectNudge = opts.compress.injectNudge && !!turn.nudge?.shouldInject; + log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model, willInjectNudge)); processedMessages = stripKernelSummaries(turn.messages, turn.state); reapOrphanBlocks(session, msgs, deactivateBlock); rebuiltMessages = coreToAnthropic(processedMessages as BiliMessage[], cacheControls); @@ -1447,9 +1451,12 @@ function prepareAnthropic( } // Nudge as a separate trailing user message (cache-friendly): the // system block stays byte-stable so the prefix cache survives. - // Gated by !pluginMode: in plugin mode the agent owns compression - // (its own overflow self-heal), so a proxy-injected nudge is redundant. - if (opts.compress.injectNudge && !pluginMode && turn.nudge?.shouldInject) { + // Injected in BOTH modes (#451): in plugin mode the agent supplies the + // ACP tools but has NO nudge channel of its own, so this proxy-side + // nudge IS the proactive trigger — preflight alone only fires at the + // hard limit. Ephemeral user message: not persisted, never enters the + // agent's re-sent history, safe for the prefix-cache anchor. + if (willInjectNudge && turn.nudge) { try { const rendered = renderNudgeText(turn.nudge, prompts); if (rendered.text) { @@ -1532,7 +1539,8 @@ function prepareOpenai( if (t) session.meta.title = t; } log("info", diagTagSummary(turn.messages, sessionId, "text-only")); - log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model)); + const willInjectNudge = opts.compress.injectNudge && !!turn.nudge?.shouldInject && shouldInject; + log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model, willInjectNudge)); processedMessages = stripKernelSummaries(turn.messages, turn.state); reapOrphanBlocks(session, msgs, deactivateBlock); rebuiltMessages = systemToUser(coreToOpenai(processedMessages as BiliMessage[])); @@ -1550,10 +1558,13 @@ function prepareOpenai( if (injectTools) { toolsOut = injectOpenaiTool(parsed.tools); } - // Nudge as a separate trailing user message (cache-friendly). - // Gated by !pluginMode: in plugin mode the agent owns compression - // (its own overflow self-heal), so a proxy-injected nudge is redundant. - if (opts.compress.injectNudge && !pluginMode && turn.nudge?.shouldInject && shouldInject) { + // Nudge as a separate trailing user message (cache-friendly). Injected + // in BOTH modes (#451): plugin agents supply the ACP tools but have no + // nudge channel of their own, so this proxy-side nudge is the proactive + // trigger (preflight alone fires only at the hard limit). Ephemeral user + // message — not persisted, never enters the agent's re-sent history, + // prefix-cache-anchor safe. + if (willInjectNudge && turn.nudge) { try { const rendered = renderNudgeText(turn.nudge, prompts); if (rendered.text) { @@ -1687,7 +1698,8 @@ function prepareResponses( if (t) session.meta.title = t; } log("info", diagTagSummary(turn.messages, sessionId, "text-only")); - log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model)); + const willInjectNudge = opts.compress.injectNudge && !!turn.nudge?.shouldInject && shouldInject && !isCompactionTrigger; + log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model, willInjectNudge)); processedMessages = stripKernelSummaries(turn.messages, turn.state); reapOrphanBlocks(session, msgs, deactivateBlock); rebuiltInput = patchResponsesInput(projection, processedMessages); @@ -1715,10 +1727,12 @@ function prepareResponses( } // A nudge appended after a trailing `compaction_trigger` would break // the upstream's "must be the final input item" requirement and is - // redundant — the native compact IS the compression. Gated by - // !pluginMode: in plugin mode the agent owns compression (its own - // overflow self-heal), so a proxy-injected nudge is redundant. - if (opts.compress.injectNudge && !pluginMode && turn.nudge?.shouldInject && shouldInject && !isCompactionTrigger) { + // redundant — the native compact IS the compression. Otherwise injected + // in BOTH modes (#451): plugin agents supply the ACP tools but have no + // nudge channel of their own, so this proxy-side nudge is the proactive + // trigger (preflight alone fires only at the hard limit). Ephemeral user + // message — not persisted, prefix-cache-anchor safe. + if (willInjectNudge && turn.nudge) { try { const rendered = renderNudgeText(turn.nudge, prompts); if (rendered.text) { diff --git a/tests/plugin-nudge-injection.test.ts b/tests/plugin-nudge-injection.test.ts new file mode 100644 index 0000000000..59b40533ee --- /dev/null +++ b/tests/plugin-nudge-injection.test.ts @@ -0,0 +1,131 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import { defaultConfig } from "acp-kernel"; +import { startServer, type ProxyOptions } from "../src/server.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; + +// #451 regression: 0.1.69 gated all three nudge injection sites by !pluginMode +// on the premise that "in plugin mode the agent owns compression". The agent +// plugins (pi/omp) are pure protocol clients with NO nudge channel of their +// own, so suppressing the proxy-side nudge left plugin-mode sessions with no +// proactive trigger — only preflight at the hard limit. The nudge is an +// ephemeral trailing USER message (not persisted, never enters the agent's +// re-sent history), so injecting it in plugin mode is safe. Observable: the +// forwarded payload carries the nudge as a final user message when armed. + +function okJson(promptTokens: number): string { + return JSON.stringify({ + id: "chatcmpl-1", + object: "chat.completion", + choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], + usage: { prompt_tokens: promptTokens, completion_tokens: 3, total_tokens: promptTokens + 3 }, + }); +} + +// 29-message history shaped so the OVER-LIMIT nudge is viable: a long text far +// outside the protected recent zone (so compressible ranges exist) plus filler +// that pushes the tail past preserveRecentMessages/preserveRecentTokens. +function turn2Messages(): Record[] { + const longText = "y".repeat(20_000); + const filler: { role: "user" | "assistant"; content: string }[] = []; + for (let i = 1; i <= 12; i++) { + filler.push({ role: "user", content: `q${i} ` + "f".repeat(997) }); + filler.push({ role: "assistant", content: `a${i} ` + "e".repeat(997) }); + } + return [ + { role: "user", content: "hello" }, + { role: "assistant", content: "ok" }, + { role: "user", content: "continue" }, + { role: "assistant", content: longText }, + ...filler, + { role: "user", content: "now summarize" }, + ]; +} + +async function forwardedTurn2Length(sessionId: string, extraHeaders: Record): Promise { + const received: unknown[][] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const body = JSON.parse(Buffer.concat(chunks).toString("utf8")); + received.push(body.messages ?? []); + res.writeHead(200, { "content-type": "application/json" }); + res.end(okJson(50_000)); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = upstream.address().port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + // Operator-declared window (never floored) so 50k/64k = 78% trips the + // OVER-LIMIT nudge deterministically. + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "deepseek-v4-flash": { context: 64_000 } } } }, + modelContextLimit: 200_000, + kernelConfig: defaultConfig(200_000), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + const proxyPort = proxy.address().port; + + try { + const url = `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1/chat/completions`; + const headers = { "content-type": "application/json", "x-acp-session": sessionId, ...extraHeaders }; + + // Turn 1 teaches the session its real context size (50k via usage report). + const r1 = await fetch(url, { + method: "POST", + headers, + body: JSON.stringify({ model: "deepseek-v4-flash", max_tokens: 64_000, messages: [{ role: "user", content: "hello" }] }), + }); + assert.equal(r1.status, 200); + await r1.text(); + + // Turn 2: 78% of the declared window arms the nudge. Forwarded payload = + // 29 client msgs + 1 leading compress system message [+ 1 nudge]. + const r2 = await fetch(url, { + method: "POST", + headers, + body: JSON.stringify({ model: "deepseek-v4-flash", max_tokens: 64_000, messages: turn2Messages() }), + }); + assert.equal(r2.status, 200); + await r2.text(); + + assert.equal(received.length, 2, "both turns reached the upstream"); + return (received[1] ?? []).length; + } finally { + proxy.close(); + await once(proxy, "close"); + upstream.close(); + await once(upstream, "close"); + } +} + +test("#451 control: nudge injected in PROXY mode when armed", async () => { + const len = await forwardedTurn2Length("nudge-ctrl", {}); + assert.equal(len, 31, "proxy mode appends the nudge as a trailing user message at 78% of 64k"); +}); + +test("#451: nudge ALSO injected in PLUGIN mode when armed (regression)", async () => { + const len = await forwardedTurn2Length("nudge-plugin", { "x-bili-plugin": "omp" }); + assert.equal(len, 31, "plugin mode must append the nudge too — before the fix the !pluginMode gate suppressed it and this would be 30"); +});