From 141cfbcf97f32de69301d223cad3f5db0e011dcc Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 10 Nov 2026 23:55:59 +0800 Subject: [PATCH 1/5] pi lane: show the injected nudge text verbatim in the transcript when debug is on MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With the existing debug switch on (ACP_DEBUG=1 / config debug), every compression nudge the proxy injects is mirrored into the pi transcript as a transcript-only CustomEntry: [bili-nudge] / tier=… reason=… label + the final wire text the model actually read that turn. Human-only: pi's session-context build ignores type:"custom", so the view never enters LLM context or re-sent history. Mechanism: the prepare stage (anthropic + openai lanes — the two pi reaches) emits the post-wrapper text into a tiny in-process pub/sub (src/nudge-debug.ts); in the default INLINE pi mode the extension is the same bundle/process and mirrors each event via pi.appendEntry("bili-nudge") + registerEntryRenderer. Emitters are listener-less no-ops, so the prepare sites stay config-plumbing-free; the consumer gate is a new debugEnabled() knob (src/knobs.ts) mirroring Options.debug exactly (env ACP_DEBUG > file debug > false). No new config fields / env vars / CLI flags — rides the existing debug switch (owner decision; a draft nudgeDebug field from the first draft was removed before the PR). kernel/ and pi-subagents/ untouched. --- docs/clients.md | 13 ++ docs/clients.zh-CN.md | 2 + reference/architecture.md | 1 + src/agent/pi.ts | 47 ++++- src/knobs.ts | 11 ++ src/nudge-debug.ts | 73 ++++++++ src/server/prepare-anthropic.ts | 13 +- src/server/prepare-openai.ts | 13 +- tests/nudge-debug.test.ts | 314 ++++++++++++++++++++++++++++++++ 9 files changed, 479 insertions(+), 8 deletions(-) create mode 100644 src/nudge-debug.ts create mode 100644 tests/nudge-debug.test.ts diff --git a/docs/clients.md b/docs/clients.md index e0819f6151..5d51b43db1 100644 --- a/docs/clients.md +++ b/docs/clients.md @@ -699,6 +699,19 @@ fallback — read only while the section is absent, ignored once it exists. Full field table and the `PI_ACP_DELEGATE_*` env overrides: configuration.md → [`pi`](configuration.md#pi). +**Nudge debug (see the injected text verbatim).** With the global debug +switch on (`ACP_DEBUG=1`, or `"debug": true` in the config file), every nudge +the proxy injects mid-compression is mirrored into the pi transcript as a +transcript-only entry: a `[bili-nudge] / tier=… reason=…` +label above the verbatim wire text — exactly the ephemeral trailing user +message the model reads that turn. The entry is a pi `CustomEntry`, which +never enters the LLM context (pi's session-context build ignores +`type:"custom"`), so only the human sees it; nothing is added to any re-sent +history. Pi inline mode only — in spawn/attach the proxy is a separate +process and the view is unavailable. Covers the Anthropic and OpenAI wire +lanes (the two pi reaches over HTTP); on hosts without +`registerEntryRenderer`/`appendEntry` the feature degrades to absent. + **How routing works.** The pi extension bootstraps (or attaches to) its own proxy and patches `globalThis.fetch` in-process: every model-API HTTP request is rewritten to `/bili/`, and the extension stamps the diff --git a/docs/clients.zh-CN.md b/docs/clients.zh-CN.md index 24d9a97b65..0741d0628a 100644 --- a/docs/clients.zh-CN.md +++ b/docs/clients.zh-CN.md @@ -164,6 +164,8 @@ Pi 有完整原生模式(`bili plugin install pi`,README 快速上手方案 1); **子代理配置(#2230)。** 内置 `acp_delegate` 面(三个 delegate 工具、角色、fleet 检查器——由 `bili pi` 经内嵌扩展接线)配置在 bili 自己的配置文件:`~/.config/billion-context/billion-context.json` 的 `pi.subagents` 段(布尔简写 `"pi": {"subagents": false}` 可整体关闭)。`~/.pi/acp.json` 的四键(`delegate` / `delegatePrompt` / `displayUsage` / `debug`)是已废弃的回退源——仅当段缺失时读取,段存在后完全忽略。完整字段表与 `PI_ACP_DELEGATE_*` 环境变量见 configuration.zh-CN.md 的 [`pi`](configuration.zh-CN.md#pi) 段。 +**nudge 调试(逐字查看注入原文)。** 打开全局 debug 开关(`ACP_DEBUG=1`,或配置文件 `"debug": true`)后,压缩过程中代理每次注入 nudge 都会以「仅转录条目」的形式镜像进 pi 会话记录:`[bili-nudge] <协议>/<类型> tier=… reason=…` 标签 + 逐字 wire 原文——即模型当轮实际读到的那条临时尾随 user 消息,一字不差。该条目是 pi 的 `CustomEntry`,从不进入模型上下文(pi 的会话上下文构建会忽略 `type:"custom"`),所以只有人能看到,也不会被加进任何重发历史。仅 pi inline 模式有效——spawn/attach 下代理是独立进程,看不到;覆盖 Anthropic 与 OpenAI 两条 wire 车道(pi 走 HTTP 仅有的两条);宿主缺少 `registerEntryRenderer`/`appendEntry` 时此功能静默缺席。 + **路由机制。** pi 扩展自行拉起(或附着)代理并进程内 patch `globalThis.fetch`:所有模型 API 的 HTTP 请求被改写到 `/bili/`,扩展经 pi 的 `before_provider_headers` 事件盖 `x-bili-plugin*` 头。所有 HTTP 系 provider(Anthropic、OpenAI chat/completions/responses、Gemini、Mistral、OpenRouter、Azure、自定义中转……)走这条路,得到具名 plugin-mode 会话。 **搭配 pi-claude-bridge:压缩状态不跨 reopen/resume(#3429)。** pi-claude-bridge 每次 pi 会话启动都会拉起一个**全新的 Claude Code 子进程**,该子进程在每个模型请求上盖自己的 `x-claude-code-session-id`——pi 的稳定会话 id 根本不上这条 HTTP。bili 按它看到的 id verbatim 键控会话(此处即 `x-claude-code-session-id`),所以 reopen/resume/fork 之后桥的新 CC id 映射到空会话:已折叠历史与压缩账本不延续,launcher/native `compress` 对 pi id 返回 404(未知 plugin 会话)——同一根机制,不是两个 bug。这是桥侧的身份缺口,不是 bili 缺陷:内容从不丢失或损坏,只是压缩的*状态*重置。根治属于 pi-claude-bridge(让 CC session id 从 pi 会话 id 稳定派生);在那之前,把 pi+claude-bridge 当纯代理模式看待上下文管理。 diff --git a/reference/architecture.md b/reference/architecture.md index cf232d6f07..1581550b10 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -287,6 +287,7 @@ billion-context/ │ ├── notice-store.ts # Notice dismissal receipts in unified kv_store, legacy file fallback (#5548) │ ├── notices.ts # Built-in notice registry: activity predicates + i18n key table (#5548) │ ├── nudge-decide.ts # Model-decided nudge timing over the already-cached prefix (#2228) +│ ├── nudge-debug.ts # Nudge-injection debug bus: verbatim wire text → pi TUI CustomEntry (never in LLM context; gated on the debug switch) │ ├── order-persist.ts # Persists session-order skeletons across restarts (#3397) │ ├── pack-install.ts # bili pack install|remove|list: npm-distributable prompt packs (#5319) │ ├── pck-notice.ts # One-time notice for the prompt_cache.routing default flip (#5079) diff --git a/src/agent/pi.ts b/src/agent/pi.ts index 83792937a7..5e503b5d06 100644 --- a/src/agent/pi.ts +++ b/src/agent/pi.ts @@ -5,12 +5,13 @@ // minimal structural declarations — the bundled artifact imports NOTHING // from the host at runtime (the host duck-types us in). -import type { MessageRenderer } from "@earendil-works/pi-coding-agent"; +import type { EntryRenderer, MessageRenderer } from "@earendil-works/pi-coding-agent"; import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui"; import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { wrapCacheReport, wrapRuleReport } from "../acp-panel.js"; +import { onNudgeInjected, type NudgeDebugEvent } from "../nudge-debug.js"; import { awaitNativeProxyOrigin } from "./native-bootstrap.js"; import { disposeSubagentSelfReg, selfRegisterForSession, type SubagentSelfRegState } from "./pi-subagent-registry.js"; import { isModelApiUrl, nativeInterceptInstalled } from "./native-intercept.js"; @@ -25,7 +26,7 @@ import { asciiHeaderValue, detectProxyBase, destinationRoutedThroughProxy, fetch import { createForkAdopter } from "./fork-adopt.js"; import { logHostEvent } from "./host-log.js"; import { plainHttpTrusted } from "../private-host.js"; -import { allowPrivateHttpProviders, guardrailBashTimeout, guardrailMaxOutputBytes, guardrailRepetition } from "../knobs.js"; +import { allowPrivateHttpProviders, debugEnabled, guardrailBashTimeout, guardrailMaxOutputBytes, guardrailRepetition } from "../knobs.js"; import { hostProfileFor } from "../host-profiles.js"; export type Ctx = { @@ -82,6 +83,13 @@ type ExtensionAPI = { registerTool: (tool: ToolDefinition) => void; registerCommand?: (name: string, options: { description?: string; handler: (args: string, ctx: CommandCtx) => void | Promise }) => void; registerMessageRenderer?: (customType: string, renderer: MessageRenderer) => void; + // Nudge debug surface (debug switch, ACP_DEBUG/debug): mirror the exact + // injected nudge wire text into the transcript as a CustomEntry — + // human-visible, never in LLM context (the host's session-context build + // ignores type:"custom"). Optional because older hosts lack it; without + // it the debug view is simply unavailable. + registerEntryRenderer?: (customType: string, renderer: EntryRenderer) => void; + appendEntry?: (customType: string, data?: unknown) => void; // #2186: acp_delegate (inlined from billion-context-pi-subagents) injects // completion notifications through the host's persistent transcript // channel; optional because older hosts and non-pi hosts lack it. @@ -891,6 +899,11 @@ export function createPiDirectSendGuard(): (url: string, input: string | URL | R }; } +// Nudge-debug wiring guard: the bus subscription is process-global (the +// emitters live in this same bundle in inline mode), so wire it at most once +// even if a host ever re-invokes the factory. +let nudgeDebugWired = false; + export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalMs?: number }): (pi: ExtensionAPI) => void { return function biliPlugin(pi: ExtensionAPI): void { const agent = agentName(agentOverride); @@ -1102,6 +1115,36 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM return box; }); } + // Nudge debug surface: with the debug switch on (ACP_DEBUG / config + // debug — rides the familiar global debug knob), each nudge the + // prepare stage injects (the ephemeral trailing user message — final + // wrapped wire text) is mirrored into the transcript as a + // CustomEntry so the operator sees the verbatim text inline. + // CustomEntry never reaches the model: pi's session-context build + // ignores type:"custom", and the engine-side emitter is this same + // bundle/process in the default INLINE pi mode (spawn/attach proxies + // are separate processes — no bus listener, feature inert there). + if (agent === "pi" && typeof pi.registerEntryRenderer === "function" && typeof pi.appendEntry === "function" && debugEnabled()) { + pi.registerEntryRenderer("bili-nudge", (entry, _options, theme) => { + const data = entry.data as NudgeDebugEvent | undefined; + if (data === undefined || typeof data !== "object" || typeof data.text !== "string" || data.text.length === 0) return undefined; + const box = new Box(1, 1, (line) => theme.bg("customMessageBg", line)); + box.addChild(new Text(theme.fg("customMessageLabel", `\x1b[1m[bili-nudge] ${data.protocol}/${data.kind} tier=${data.tier ?? "-"} reason=${data.reason}\x1b[22m`), 0, 0)); + box.addChild(new Spacer(1)); + box.addChild(new Text(data.text, 0, 0)); + return box; + }); + if (!nudgeDebugWired) { + nudgeDebugWired = true; + onNudgeInjected((event) => { + try { + pi.appendEntry?.("bili-nudge", event); + } catch { + // debug surface only — a failed append must never break the request pipeline + } + }); + } + } const piCommands = piCommandsEnabled(); if (typeof pi.registerCommand === "function") { if (piCommands.has("acp")) { diff --git a/src/knobs.ts b/src/knobs.ts index 8590c94762..987319aa2d 100644 --- a/src/knobs.ts +++ b/src/knobs.ts @@ -775,6 +775,17 @@ export function dump4xxEnabled(): boolean { return fileDiag().dump4xx === true; } +/** ACP_DEBUG > debug > false — the existing global verbose-debug switch, + * resolved exactly like Options.debug (src/config.ts). Reused by the + * pi-lane nudge debug surface (src/nudge-debug.ts / src/agent/pi.ts) so the + * feature rides the familiar debug switch instead of adding a knob of its + * own. */ +export function debugEnabled(): boolean { + const envRaw = process.env.ACP_DEBUG; + if (envRaw !== undefined) return envRaw === "1"; + return loadConfigFile().debug === true; +} + /** BILI_DUMP_4XX_MAX_BYTES > diagnostics.dump4xxMaxBytes > 2 MiB (floor 1 KiB). */ export function dump4xxMaxBytes(): number { const envRaw = process.env.BILI_DUMP_4XX_MAX_BYTES; diff --git a/src/nudge-debug.ts b/src/nudge-debug.ts new file mode 100644 index 0000000000..3da7f8eaec --- /dev/null +++ b/src/nudge-debug.ts @@ -0,0 +1,73 @@ +// Nudge-injection debug surface: a tiny in-process pub/sub carrying the EXACT +// wire text a prepare stage just injected as the ephemeral trailing user +// message (post renderNudgeText + withFirstSightDrain/withSummaryBudgetNote/ +// withMarkerIntegrityNote — the final string that goes on the wire, not the +// pre-wrapper template). +// +// Why a bus and not a log line: the nudge text IS the thing under debugging — +// "what did the model actually read this round" — and grepping a log file +// after the fact hides the placement (which turn, which arm). The pi lane +// subscribes (src/agent/pi.ts wireNudgeDebug) and mirrors each event into the +// host transcript as a CustomEntry via pi.appendEntry("bili-nudge", ...) — +// CustomEntry does NOT participate in LLM context (pi's buildSessionContext +// ignores type:"custom"), so the debug view is HUMAN-ONLY: the operator sees +// the verbatim nudge inline in pi, the model never does, and nothing is added +// to any re-sent history. Gated by the existing debug switch +// (debugEnabled(), src/knobs.ts — ACP_DEBUG > config `debug` > false) on the +// consumer side; emitters always fire — a listener-less emit is a no-op, so +// the prepare sites stay config-plumbing-free. +// +// Process scope: the bus is a module-level singleton. It reaches the pi +// extension because BOTH live inside the same dist bundle + process in the pi +// lane's default INLINE mode (dist/agent/pi-native.js bundles pi.ts AND +// inline-engine.ts AND these prepare modules — tsup splitting:false). In +// spawn/attach mode the proxy is a separate process holding its own bundle +// copy: no listener ever fires there and the feature is inert (documented in +// docs/configuration.md). + +export type NudgeDebugKind = "advisory" | "directive" | "fallback"; + +export type NudgeDebugEvent = { + /** bili session id the nudge armed under (not the host session id). */ + sessionId: string; + /** Wire family that carried the nudge ("anthropic" | "openai"). */ + protocol: string; + /** Which injection arm fired: legacy/over-limit advisory, model-decided + * directive (#2228), or decide-ladder fallback advisory. */ + kind: NudgeDebugKind; + /** Nudge tier (1 = gentle, 2+ = distillation pressure); null when the + * nudge is not tier-based (legacy over-limit/emergency). */ + tier: number | null; + /** Why the nudge armed (turn.nudge.reason). */ + reason: string; + /** The FINAL wrapped wire text, verbatim. */ + text: string; + ts: number; +}; + +type NudgeDebugListener = (event: NudgeDebugEvent) => void; + +const listeners = new Set(); + +/** Subscribe; returns an unsubscribe function. */ +export function onNudgeInjected(listener: NudgeDebugListener): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** Fire-and-forget emit. A throwing listener must never break the request + * pipeline — injection already happened on the wire when this fires. */ +export function emitNudgeInjected(event: NudgeDebugEvent): void { + for (const listener of [...listeners]) { + try { + listener(event); + } catch { + // debug surface only — swallow + } + } +} + +/** Test seam: drop all listeners between cases. */ +export function _resetNudgeDebugForTest(): void { + listeners.clear(); +} diff --git a/src/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index a76a48b3b5..3ec11cde4f 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -10,6 +10,7 @@ import { pluginAgentHeader } from "../plugin.js"; import { applyReasoningDrop, dedupeAdjacentOutputConfig, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, makeFoldPointReasoningDroppable, planReasoningDrop, reapOrphansLogged, runNudgeDecision, stripKernelSummaries, warnAnthropicThinkingPairs, type Prepared } from "../server.js"; import { recordNudgeObservation } from "../context-analysis.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; +import { emitNudgeInjected } from "../nudge-debug.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; import { maybeSnapshotView } from "./snapshot-render.js"; @@ -523,8 +524,10 @@ export async function prepareAnthropic( const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections, "anthropic"); const renderedWithPayload = rendered.text; if (rendered.text) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; + const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); + rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; + emitNudgeInjected({ sessionId, protocol: "anthropic", kind: "fallback", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); } else { nudgeOutcome = "skipped"; } @@ -544,8 +547,10 @@ export async function prepareAnthropic( if (outcome.kind === "yes") { const span = resolveDecisionRange(outcome, ranges); if (span) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(buildDirectiveText(span.startRef, span.endRef, outcome.topic), turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; + const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(buildDirectiveText(span.startRef, span.endRef, outcome.topic), turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); + rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; + emitNudgeInjected({ sessionId, protocol: "anthropic", kind: "directive", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); } else { nudgeOutcome = "skipped"; log("info", `[${sessionId}] [acp-decide] yes but no live range left to target — skipping injection`); @@ -560,8 +565,10 @@ export async function prepareAnthropic( const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections, "anthropic"); const renderedWithPayload = rendered.text; if (rendered.text) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; + const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); + rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; + emitNudgeInjected({ sessionId, protocol: "anthropic", kind: "advisory", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); } else { nudgeOutcome = "skipped"; } diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index 98cae44892..efaa2dcc3f 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -13,6 +13,7 @@ import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTo import { recordNudgeObservation } from "../context-analysis.js"; import { yieldToEventLoop } from "../yield-loop.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; +import { emitNudgeInjected } from "../nudge-debug.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; import { maybeSnapshotView } from "./snapshot-render.js"; @@ -491,8 +492,10 @@ export async function prepareOpenai( const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections, "openai"); const renderedWithPayload = rendered.text; if (rendered.text) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; + const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); + rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; + emitNudgeInjected({ sessionId, protocol: "openai", kind: "fallback", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); } else { nudgeOutcome = "skipped"; } @@ -512,8 +515,10 @@ export async function prepareOpenai( if (outcome.kind === "yes") { const span = resolveDecisionRange(outcome, ranges); if (span) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(buildDirectiveText(span.startRef, span.endRef, outcome.topic), turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; + const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(buildDirectiveText(span.startRef, span.endRef, outcome.topic), turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); + rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; + emitNudgeInjected({ sessionId, protocol: "openai", kind: "directive", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); } else { nudgeOutcome = "skipped"; log("info", `[${sessionId}] [acp-decide] yes but no live range left to target — skipping injection`); @@ -530,8 +535,10 @@ export async function prepareOpenai( const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections, "openai"); const renderedWithPayload = rendered.text; if (rendered.text) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; + const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); + rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; + emitNudgeInjected({ sessionId, protocol: "openai", kind: "advisory", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); } else { nudgeOutcome = "skipped"; } diff --git a/tests/nudge-debug.test.ts b/tests/nudge-debug.test.ts new file mode 100644 index 0000000000..8800af4e52 --- /dev/null +++ b/tests/nudge-debug.test.ts @@ -0,0 +1,314 @@ +// Nudge debug surface (gated by the existing debug switch — ACP_DEBUG / config +// debug): the prepare stage must mirror the EXACT nudge wire text it injects +// into the in-process bus (src/nudge-debug.ts); the pi lane turns each event +// into a transcript-only CustomEntry (src/agent/pi.ts — CustomEntry never +// enters LLM context). Gold assertion: the bus event text is BYTE-IDENTICAL +// to the trailing user message content the proxy actually sent upstream — the +// human in pi sees exactly what the model read, and nothing more. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; +import { once } from "node:events"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { emitNudgeInjected, onNudgeInjected, _resetNudgeDebugForTest, type NudgeDebugEvent } from "../src/nudge-debug.ts"; +import { debugEnabled } from "../src/knobs.ts"; +import { createBiliPlugin } from "../src/agent/pi.ts"; + +// ---------- bus unit ---------- + +test("nudge-debug bus: emit reaches subscribers; unsubscribe works; a throwing listener is isolated", () => { + _resetNudgeDebugForTest(); + const seen: NudgeDebugEvent[] = []; + const off = onNudgeInjected((e) => seen.push(e)); + let afterThrow = false; + const bad = onNudgeInjected(() => { + throw new Error("boom"); + }); + const later = onNudgeInjected(() => { + afterThrow = true; + }); + const ev: NudgeDebugEvent = { sessionId: "s1", protocol: "anthropic", kind: "advisory", tier: null, reason: "r", text: "T", ts: 1 }; + emitNudgeInjected(ev); + assert.deepEqual(seen, [ev]); + assert.ok(afterThrow, "a throwing listener must not break later subscribers"); + off(); + emitNudgeInjected(ev); + assert.equal(seen.length, 1, "unsubscribed listener must not fire"); + bad(); + later(); + _resetNudgeDebugForTest(); +}); + +// ---------- knob (debugEnabled reuses the global debug switch) ---------- + +test("debugEnabled: ACP_DEBUG env wins; file `debug` tier; default off; only the literal 1 enables", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "bili-nudge-debug-cfg-")); + const cfg = path.join(root, "config.jsonc"); + const savedEnv = process.env.ACP_DEBUG; + const savedCfg = process.env.BILI_CONFIG_FILE; + try { + process.env.BILI_CONFIG_FILE = cfg; + fs.writeFileSync(cfg, "{}"); + if (savedEnv !== undefined) process.env.ACP_DEBUG = savedEnv; + else delete process.env.ACP_DEBUG; + assert.equal(debugEnabled(), false, "default off"); + fs.writeFileSync(cfg, '{ "debug": true }'); + assert.equal(debugEnabled(), true, "file tier"); + process.env.ACP_DEBUG = "0"; + assert.equal(debugEnabled(), false, "env '0' beats file true"); + process.env.ACP_DEBUG = "true"; + assert.equal(debugEnabled(), false, "only literal '1' enables (matches Options.debug)"); + fs.writeFileSync(cfg, "{}"); + process.env.ACP_DEBUG = "1"; + assert.equal(debugEnabled(), true, "env '1' wins over file false"); + } finally { + if (savedEnv === undefined) delete process.env.ACP_DEBUG; + else process.env.ACP_DEBUG = savedEnv; + if (savedCfg === undefined) delete process.env.BILI_CONFIG_FILE; + else process.env.BILI_CONFIG_FILE = savedCfg; + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +// ---------- pi wiring gate (both directions, #3617 discipline) ---------- + +test("pi wiring: the bili-nudge entry renderer registers iff the debug switch is on", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "bili-nudge-gate-")); + const cfg = path.join(root, "config.jsonc"); + const savedEnv = process.env.ACP_DEBUG; + const savedCfg = process.env.BILI_CONFIG_FILE; + try { + fs.writeFileSync(cfg, "{}"); + process.env.BILI_CONFIG_FILE = cfg; + if (savedEnv !== undefined) process.env.ACP_DEBUG = savedEnv; + else delete process.env.ACP_DEBUG; + const makeStub = () => { + const entryTypes: string[] = []; + return { + entryTypes, + on: () => {}, + fire: () => undefined, + fireAsync: async () => undefined, + registerTool: () => {}, + registerCommand: () => {}, + registerProvider: () => {}, + registerMessageRenderer: () => {}, + registerEntryRenderer: (t: string) => { entryTypes.push(t); }, + appendEntry: () => {}, + getSessionName: () => "test", + }; + }; + const off = makeStub(); + createBiliPlugin("pi")(off as never); + assert.ok(!off.entryTypes.includes("bili-nudge"), "off by default"); + process.env.ACP_DEBUG = "0"; + const offExplicit = makeStub(); + createBiliPlugin("pi")(offExplicit as never); + assert.ok(!offExplicit.entryTypes.includes("bili-nudge"), "env '0' keeps it off"); + process.env.ACP_DEBUG = "1"; + const on = makeStub(); + createBiliPlugin("pi")(on as never); + assert.ok(on.entryTypes.includes("bili-nudge"), "registers when ACP_DEBUG=1"); + } finally { + if (savedEnv === undefined) delete process.env.ACP_DEBUG; + else process.env.ACP_DEBUG = savedEnv; + if (savedCfg === undefined) delete process.env.BILI_CONFIG_FILE; + else process.env.BILI_CONFIG_FILE = savedCfg; + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +// ---------- e2e: emitted text === the wire text actually sent upstream ---------- + +const WINDOW = 15_000; +const MODEL = "claude-test"; +const SYSTEM = "You are a coding agent."; +const ARMED_INPUT_TOKENS = 13_500; + +// 7 messages × ~4400 distinct chars → local estimate ≈51% of WINDOW (below the +// band) so turn 1 stays clean; the upstream-reported usage crosses the +// over-limit band (90%) so turn 2 injects the nudge. +function filler(seed: number, targetChars: number): string { + const para = `Paragraph ${seed}: the ledger module under review passed its integration suite across all four regions without any reported regressions. `; + const unit = Math.max(1, Math.ceil(targetChars / para.length)); + return Array.from({ length: unit }, (_, i) => para.replace(String(seed), `${seed}-${i}`)).join(""); +} + +const ANTHROPIC_MESSAGES = (): Array<{ role: string; content: Array<{ type: string; text: string }> }> => { + const out: Array<{ role: string; content: Array<{ type: string; text: string }> }> = []; + for (let i = 1; i <= 7; i++) { + out.push({ role: i % 2 === 1 ? "user" : "assistant", content: [{ type: "text", text: `Turn ${i}: working session entry. ` + filler(i, 4400) }] }); + } + return out; +}; + +const OPENAI_MESSAGES = (): Array<{ role: string; content: string }> => + ANTHROPIC_MESSAGES().map((m) => ({ role: m.role, content: m.content.map((b) => b.text).join("") })); + +const anthropicSse = (event: string, data: unknown): string => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; + +const anthropicReply = (): string => + [ + anthropicSse("message_start", { type: "message_start", message: { id: "msg_r", role: "assistant", usage: { input_tokens: ARMED_INPUT_TOKENS } } }), + anthropicSse("content_block_start", { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }), + anthropicSse("content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ack" } }), + anthropicSse("content_block_stop", { type: "content_block_stop", index: 0 }), + anthropicSse("message_delta", { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 3 } }), + anthropicSse("message_stop", { type: "message_stop" }), + ].join(""); + +interface Harness { + origin: string; + upstreamUrl: string; + captured: string[]; + close(): Promise; +} + +async function startHarness(wire: "anthropic" | "openai"): Promise { + const captured: string[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + captured.push(Buffer.concat(chunks).toString("utf8")); + if (wire === "anthropic") { + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + res.end(anthropicReply()); + } else { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ id: "chat_r", object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: "ack" }, finish_reason: "stop" }], usage: { prompt_tokens: ARMED_INPUT_TOKENS, completion_tokens: 3, total_tokens: ARMED_INPUT_TOKENS + 3 } })); + } + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamUrl = `http://127.0.0.1:${(upstream.address() as { port: number }).port}`; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: upstreamUrl, + routes: { [upstreamUrl]: { models: { [MODEL]: { context: WINDOW } } } }, + modelContextLimit: WINDOW, + kernelConfig: { ...defaultConfig(WINDOW), nudge: { ...defaultConfig(WINDOW).nudge, minPressureBenefitTokens: 0 } }, + 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 origin = `http://127.0.0.1:${(proxy.address() as { port: number }).port}`; + + return { + origin, + upstreamUrl, + captured, + close: async () => { + proxy.close(); + proxy.closeIdleConnections?.(); + await once(proxy, "close"); + upstream.close(); + upstream.closeIdleConnections?.(); + await once(upstream, "close"); + }, + }; +} + +function textOf(content: string | Array<{ type?: string; text?: string }>): string { + return typeof content === "string" ? content : content.map((b) => b.text ?? "").join(""); +} + +test("nudge-debug e2e (anthropic wire): bus event text is byte-identical to the injected trailing user message", async () => { + const h = await startHarness("anthropic"); + const events: NudgeDebugEvent[] = []; + const off = onNudgeInjected((e) => events.push(e)); + try { + const url = `${h.origin}/bili/${h.upstreamUrl}/v1/messages`; + const post = (session: string) => fetch(url, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": session }, + body: JSON.stringify({ model: MODEL, max_tokens: 1024, stream: true, system: SYSTEM, messages: ANTHROPIC_MESSAGES() }), + }); + + const r1 = await post("nudgedbg-anth-a"); + assert.equal(r1.status, 200); + await r1.text(); + assert.equal(events.length, 0, "turn 1 (under the band) injects no nudge"); + + const r2 = await post("nudgedbg-anth-a"); + assert.equal(r2.status, 200); + await r2.text(); + + assert.equal(events.length, 1, "turn 2 (over limit) fires exactly one nudge event"); + const ev = events[0]!; + assert.equal(ev.protocol, "anthropic"); + assert.equal(ev.kind, "advisory", "no decide config in this harness → legacy advisory arm"); + assert.equal(ev.text.length > 0, true, "event carries the verbatim wire text"); + + const body = JSON.parse(h.captured[1]!) as { messages: Array<{ role: string; content: string | Array<{ type?: string; text?: string }> }> }; + const sent = ANTHROPIC_MESSAGES().length; + assert.equal(body.messages.length, sent + 1, "exactly one nudge message appended"); + const last = body.messages[body.messages.length - 1]!; + assert.equal(last.role, "user"); + assert.equal(ev.text, textOf(last.content), "bus event text === the exact bytes sent upstream"); + } finally { + off(); + await h.close(); + } +}); + +test("nudge-debug e2e (openai wire): bus event text is byte-identical to the injected trailing user message", async () => { + const h = await startHarness("openai"); + const events: NudgeDebugEvent[] = []; + const off = onNudgeInjected((e) => events.push(e)); + try { + const url = `${h.origin}/bili/${h.upstreamUrl}/v1/chat/completions`; + const post = (session: string) => fetch(url, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": session }, + body: JSON.stringify({ model: MODEL, max_tokens: 1024, messages: OPENAI_MESSAGES() }), + }); + + const r1 = await post("nudgedbg-openai-a"); + assert.equal(r1.status, 200); + await r1.text(); + const r2 = await post("nudgedbg-openai-a"); + assert.equal(r2.status, 200); + await r2.text(); + + assert.equal(events.length, 1, "turn 2 fires exactly one nudge event"); + const ev = events[0]!; + assert.equal(ev.protocol, "openai"); + assert.equal(ev.kind, "advisory"); + + type OMsg = { role: string; content: string | Array<{ type?: string; text?: string }> }; + const t1 = JSON.parse(h.captured[0]!) as { messages: OMsg[] }; + const t2 = JSON.parse(h.captured[1]!) as { messages: OMsg[] }; + // The openai lane injects its own lane message into `messages` on the + // armed turn (see issue3910's non-vacuity guard), so compare against + // the turn-1 count instead of an absolute +1. + assert.equal(t2.messages.length, t1.messages.length + 1, "exactly one nudge message appended vs turn 1"); + const last = t2.messages[t2.messages.length - 1]!; + assert.equal(last.role, "user"); + assert.equal(ev.text, textOf(last.content), "bus event text === the exact bytes sent upstream"); + } finally { + off(); + await h.close(); + } +}); From a5a3a757a668ea3a4c291038c54e6786a988f19d Mon Sep 17 00:00:00 2001 From: ci-check Date: Wed, 11 Nov 2026 03:40:18 +0800 Subject: [PATCH 2/5] fix(nudge-debug): unused-exports gate red + point header comment at real docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NudgeDebugKind is referenced only inside this file (by NudgeDebugEvent.kind), so the gate classifies the export INTERNAL_ONLY — drop the leading export per the gate's own remedy. Fixes the failed static gate on head 141cfbcf. Also correct the header comment: the spawn/attach inertness limit is documented in docs/clients.md en+zh (Pi section), not docs/configuration.md. --- src/nudge-debug.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/nudge-debug.ts b/src/nudge-debug.ts index 3da7f8eaec..0ea50ca3f8 100644 --- a/src/nudge-debug.ts +++ b/src/nudge-debug.ts @@ -23,9 +23,9 @@ // inline-engine.ts AND these prepare modules — tsup splitting:false). In // spawn/attach mode the proxy is a separate process holding its own bundle // copy: no listener ever fires there and the feature is inert (documented in -// docs/configuration.md). +// docs/clients.md en+zh, Pi section). -export type NudgeDebugKind = "advisory" | "directive" | "fallback"; +type NudgeDebugKind = "advisory" | "directive" | "fallback"; export type NudgeDebugEvent = { /** bili session id the nudge armed under (not the host session id). */ From ace5b0cfa40ebe2ed61812373cae24e1ff68785a Mon Sep 17 00:00:00 2001 From: ci-check Date: Wed, 11 Nov 2026 03:44:08 +0800 Subject: [PATCH 3/5] fix(knobs): debugEnabled mirrors Options.debug verbatim Options.debug (src/config.ts) resolves as (env.ACP_DEBUG ?? (fileConfig.debug ? "1" : "0")) === "1". The first pass used .debug === true on the file tier, which diverges from the main debug surface for a non-boolean truthy file value. Use the literal same expression so the two surfaces cannot disagree on any input. --- src/knobs.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/knobs.ts b/src/knobs.ts index 987319aa2d..4f5cc2832b 100644 --- a/src/knobs.ts +++ b/src/knobs.ts @@ -776,14 +776,13 @@ export function dump4xxEnabled(): boolean { } /** ACP_DEBUG > debug > false — the existing global verbose-debug switch, - * resolved exactly like Options.debug (src/config.ts). Reused by the + * resolved EXACTLY like Options.debug (src/config.ts): same expression, so + * the two surfaces can never disagree on any input. Reused by the * pi-lane nudge debug surface (src/nudge-debug.ts / src/agent/pi.ts) so the * feature rides the familiar debug switch instead of adding a knob of its * own. */ export function debugEnabled(): boolean { - const envRaw = process.env.ACP_DEBUG; - if (envRaw !== undefined) return envRaw === "1"; - return loadConfigFile().debug === true; + return (process.env.ACP_DEBUG ?? (loadConfigFile().debug ? "1" : "0")) === "1"; } /** BILI_DUMP_4XX_MAX_BYTES > diagnostics.dump4xxMaxBytes > 2 MiB (floor 1 KiB). */ From 56bb58302e839ee424e9ca1506bac03c0ff139e5 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Wed, 11 Nov 2026 09:03:44 +0800 Subject: [PATCH 4/5] pi lane: align the nudge view with billion-context-pi #326 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - custom type acp-nudge (was bili-nudge); compact one-liner [ACP nudge] % · T[ EMERGENCY][ · top range a–b] - the compact record line is ALWAYS on (no debug config needed): one per user turn, persistent in the session file, pi-visible / model-invisible (type:custom never enters LLM context) - the verbatim wire text becomes a transient terminal notification (debug switch on: ACP_DEBUG / config debug), shown once per turn after the model answered — never persisted - dedup per (session, turn) via a stable key of the last text user message (anthropic tool_result user messages skipped) - bus events carry the record metadata (pct/tier/emergency/topRange/ turnKey); emitters compute it from the PRE-nudge array --- docs/clients.md | 29 +++++--- docs/clients.zh-CN.md | 2 +- reference/architecture.md | 2 +- src/agent/pi.ts | 79 ++++++++++++++------ src/nudge-debug.ts | 125 +++++++++++++++++++++++++++----- src/server/prepare-anthropic.ts | 12 ++- src/server/prepare-openai.ts | 12 ++- tests/nudge-debug.test.ts | 90 ++++++++++++++++------- 8 files changed, 264 insertions(+), 87 deletions(-) diff --git a/docs/clients.md b/docs/clients.md index 5d51b43db1..1fd5eb8e82 100644 --- a/docs/clients.md +++ b/docs/clients.md @@ -699,18 +699,23 @@ fallback — read only while the section is absent, ignored once it exists. Full field table and the `PI_ACP_DELEGATE_*` env overrides: configuration.md → [`pi`](configuration.md#pi). -**Nudge debug (see the injected text verbatim).** With the global debug -switch on (`ACP_DEBUG=1`, or `"debug": true` in the config file), every nudge -the proxy injects mid-compression is mirrored into the pi transcript as a -transcript-only entry: a `[bili-nudge] / tier=… reason=…` -label above the verbatim wire text — exactly the ephemeral trailing user -message the model reads that turn. The entry is a pi `CustomEntry`, which -never enters the LLM context (pi's session-context build ignores -`type:"custom"`), so only the human sees it; nothing is added to any re-sent -history. Pi inline mode only — in spawn/attach the proxy is a separate -process and the view is unavailable. Covers the Anthropic and OpenAI wire -lanes (the two pi reaches over HTTP); on hosts without -`registerEntryRenderer`/`appendEntry` the feature degrades to absent. +**Nudge visibility (what the proxy injected, without model-context cost).** +Every nudge the proxy injects mid-compression leaves a COMPACT RECORD LINE in +the pi transcript — `[ACP nudge] 92% · T2 · top range m0120–m0145` (percent of +context used, tier, optional top compressible range; `EMERGENCY` flag when the +emergency arm fired) — one per user turn, always on, no config needed. The +line is a pi `CustomEntry` of type `acp-nudge`, which never enters the LLM +context (pi's session-context build ignores `type:"custom"`) and persists in +the session file across restarts: pi-visible, model-invisible. With the +global debug switch on (`ACP_DEBUG=1`, or `"debug": true` in the config +file) the VERBATIM wire text — exactly the ephemeral trailing user message +the model reads that turn — is additionally shown once per turn as a transient +terminal notification; it is never written to the session file. Pi inline +mode only — in spawn/attach the proxy is a separate process and the view is +unavailable. Covers the Anthropic and OpenAI wire lanes (the two pi reaches +over HTTP); on hosts without `registerEntryRenderer`/`appendEntry` the feature +degrades to absent. (Custom type and line format aligned with the official +pi client, billion-context-pi issue #326.) **How routing works.** The pi extension bootstraps (or attaches to) its own proxy and patches `globalThis.fetch` in-process: every model-API HTTP request diff --git a/docs/clients.zh-CN.md b/docs/clients.zh-CN.md index 0741d0628a..7bc23f481d 100644 --- a/docs/clients.zh-CN.md +++ b/docs/clients.zh-CN.md @@ -164,7 +164,7 @@ Pi 有完整原生模式(`bili plugin install pi`,README 快速上手方案 1); **子代理配置(#2230)。** 内置 `acp_delegate` 面(三个 delegate 工具、角色、fleet 检查器——由 `bili pi` 经内嵌扩展接线)配置在 bili 自己的配置文件:`~/.config/billion-context/billion-context.json` 的 `pi.subagents` 段(布尔简写 `"pi": {"subagents": false}` 可整体关闭)。`~/.pi/acp.json` 的四键(`delegate` / `delegatePrompt` / `displayUsage` / `debug`)是已废弃的回退源——仅当段缺失时读取,段存在后完全忽略。完整字段表与 `PI_ACP_DELEGATE_*` 环境变量见 configuration.zh-CN.md 的 [`pi`](configuration.zh-CN.md#pi) 段。 -**nudge 调试(逐字查看注入原文)。** 打开全局 debug 开关(`ACP_DEBUG=1`,或配置文件 `"debug": true`)后,压缩过程中代理每次注入 nudge 都会以「仅转录条目」的形式镜像进 pi 会话记录:`[bili-nudge] <协议>/<类型> tier=… reason=…` 标签 + 逐字 wire 原文——即模型当轮实际读到的那条临时尾随 user 消息,一字不差。该条目是 pi 的 `CustomEntry`,从不进入模型上下文(pi 的会话上下文构建会忽略 `type:"custom"`),所以只有人能看到,也不会被加进任何重发历史。仅 pi inline 模式有效——spawn/attach 下代理是独立进程,看不到;覆盖 Anthropic 与 OpenAI 两条 wire 车道(pi 走 HTTP 仅有的两条);宿主缺少 `registerEntryRenderer`/`appendEntry` 时此功能静默缺席。 +**nudge 可见性(模型零上下文成本,看代理注入了什么)。** 代理在压缩过程中每次注入 nudge,都会在 pi 会话记录里留下一条**紧凑记录行**——`[ACP nudge] 92% · T2 · top range m0120–m0145`(上下文占用百分比、tier、可选的最大可压缩区间;紧急臂触发时带 `EMERGENCY` 标志)——每个用户 turn 一行,**始终开启,无需任何配置**。该行是 `acp-nudge` 类型的 pi `CustomEntry`,从不进入模型上下文(pi 的会话上下文构建会忽略 `type:"custom"`),且持久化在 session 文件里、重启后仍在:pi 可见、模型不可见。打开全局 debug 开关(`ACP_DEBUG=1` 或配置文件 `"debug": true`)后,还会在终端以**一次性临时通知**的形式显示**逐字 wire 原文**——即模型当轮实际读到的那条临时尾随 user 消息,一字不差;原文从不写入 session 文件。仅 pi inline 模式有效——spawn/attach 下代理是独立进程,看不到;覆盖 Anthropic 与 OpenAI 两条 wire 车道(pi 走 HTTP 仅有的两条);宿主缺少 `registerEntryRenderer`/`appendEntry` 时此功能静默缺席。(custom type 与行格式与官方 pi 客户端 billion-context-pi issue #326 对齐。) **路由机制。** pi 扩展自行拉起(或附着)代理并进程内 patch `globalThis.fetch`:所有模型 API 的 HTTP 请求被改写到 `/bili/`,扩展经 pi 的 `before_provider_headers` 事件盖 `x-bili-plugin*` 头。所有 HTTP 系 provider(Anthropic、OpenAI chat/completions/responses、Gemini、Mistral、OpenRouter、Azure、自定义中转……)走这条路,得到具名 plugin-mode 会话。 diff --git a/reference/architecture.md b/reference/architecture.md index 1581550b10..9429e2ee66 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -287,7 +287,7 @@ billion-context/ │ ├── notice-store.ts # Notice dismissal receipts in unified kv_store, legacy file fallback (#5548) │ ├── notices.ts # Built-in notice registry: activity predicates + i18n key table (#5548) │ ├── nudge-decide.ts # Model-decided nudge timing over the already-cached prefix (#2228) -│ ├── nudge-debug.ts # Nudge-injection debug bus: verbatim wire text → pi TUI CustomEntry (never in LLM context; gated on the debug switch) +│ ├── nudge-debug.ts # Nudge-injection bus: compact `[ACP nudge]` record line (CustomEntry, always on) + verbatim wire text for the debug terminal notify (billion-context-pi #326 parity; never in LLM context) │ ├── order-persist.ts # Persists session-order skeletons across restarts (#3397) │ ├── pack-install.ts # bili pack install|remove|list: npm-distributable prompt packs (#5319) │ ├── pck-notice.ts # One-time notice for the prompt_cache.routing default flip (#5079) diff --git a/src/agent/pi.ts b/src/agent/pi.ts index 5e503b5d06..5be61bfe52 100644 --- a/src/agent/pi.ts +++ b/src/agent/pi.ts @@ -11,7 +11,7 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { wrapCacheReport, wrapRuleReport } from "../acp-panel.js"; -import { onNudgeInjected, type NudgeDebugEvent } from "../nudge-debug.js"; +import { ACP_NUDGE_CUSTOM_TYPE, formatNudgeRecord, onNudgeInjected, type NudgeDebugEvent } from "../nudge-debug.js"; import { awaitNativeProxyOrigin } from "./native-bootstrap.js"; import { disposeSubagentSelfReg, selfRegisterForSession, type SubagentSelfRegState } from "./pi-subagent-registry.js"; import { isModelApiUrl, nativeInterceptInstalled } from "./native-intercept.js"; @@ -902,7 +902,18 @@ export function createPiDirectSendGuard(): (url: string, input: string | URL | R // Nudge-debug wiring guard: the bus subscription is process-global (the // emitters live in this same bundle in inline mode), so wire it at most once // even if a host ever re-invokes the factory. +// Nudge debug surface (billion-context-pi issue #326 parity) — module-level +// because the bus subscription is process-singleton: +// nudgeDebugWired: the onNudgeInjected listener registered exactly once. +// nudgeRecordedTurns: (sessionId → turnKey) one compact record line per user +// turn — emergency nudges re-inject on every LLM call and must not +// flood the session file. +// nudgeFullPending / nudgeNotifiedTurns: the verbatim wire text is shown as +// a transient terminal notification (debug switch on), deduped per turn. let nudgeDebugWired = false; +const nudgeRecordedTurns = new Map(); +const nudgeNotifiedTurns = new Map(); +let nudgeFullPending: NudgeDebugEvent | null = null; export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalMs?: number }): (pi: ExtensionAPI) => void { return function biliPlugin(pi: ExtensionAPI): void { @@ -1115,35 +1126,61 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM return box; }); } - // Nudge debug surface: with the debug switch on (ACP_DEBUG / config - // debug — rides the familiar global debug knob), each nudge the - // prepare stage injects (the ephemeral trailing user message — final - // wrapped wire text) is mirrored into the transcript as a - // CustomEntry so the operator sees the verbatim text inline. - // CustomEntry never reaches the model: pi's session-context build - // ignores type:"custom", and the engine-side emitter is this same - // bundle/process in the default INLINE pi mode (spawn/attach proxies - // are separate processes — no bus listener, feature inert there). - if (agent === "pi" && typeof pi.registerEntryRenderer === "function" && typeof pi.appendEntry === "function" && debugEnabled()) { - pi.registerEntryRenderer("bili-nudge", (entry, _options, theme) => { - const data = entry.data as NudgeDebugEvent | undefined; - if (data === undefined || typeof data !== "object" || typeof data.text !== "string" || data.text.length === 0) return undefined; - const box = new Box(1, 1, (line) => theme.bg("customMessageBg", line)); - box.addChild(new Text(theme.fg("customMessageLabel", `\x1b[1m[bili-nudge] ${data.protocol}/${data.kind} tier=${data.tier ?? "-"} reason=${data.reason}\x1b[22m`), 0, 0)); - box.addChild(new Spacer(1)); - box.addChild(new Text(data.text, 0, 0)); - return box; - }); + // Nudge display (aligned with billion-context-pi issue #326, custom + // type `acp-nudge`): the nudge ITSELF goes to the model — that is the + // pre-existing mechanism's job, this surface adds nothing to model + // context. What lands in the transcript: ONE compact record line per + // user turn (`[ACP nudge] …`), always, as a CustomEntry — pi-visible, + // model-invisible (pi's buildSessionContext ignores type:"custom"), + // persistent in the session file. With the debug switch on + // (ACP_DEBUG / config `debug`) the VERBATIM wire text is additionally + // shown as a transient terminal notification (see the + // after_provider_response hook) and is never persisted. + // Engine-side emitter: same bundle/process in the default INLINE pi + // mode (spawn/attach proxies are separate processes — no bus + // listener, feature inert there; docs/clients.md). + if (agent === "pi" && typeof pi.registerEntryRenderer === "function" && typeof pi.appendEntry === "function") { if (!nudgeDebugWired) { nudgeDebugWired = true; onNudgeInjected((event) => { try { - pi.appendEntry?.("bili-nudge", event); + if (nudgeRecordedTurns.get(event.sessionId) !== event.turnKey) { + nudgeRecordedTurns.set(event.sessionId, event.turnKey); + pi.appendEntry?.(ACP_NUDGE_CUSTOM_TYPE, { text: formatNudgeRecord(event) }); + } } catch { // debug surface only — a failed append must never break the request pipeline } + nudgeFullPending = event; }); } + pi.registerEntryRenderer(ACP_NUDGE_CUSTOM_TYPE, (entry, _options, theme) => { + const data = entry.data as { text?: unknown } | undefined; + const text = data !== undefined && typeof data === "object" ? data.text : undefined; + if (typeof text !== "string" || text.length === 0) return undefined; + const box = new Box(1, 1, (line) => theme.bg("customMessageBg", line)); + box.addChild(new Text(theme.fg("dim", text), 0, 0)); + return box; + }); + } + // Nudge debug FULL text: once the model has answered a request that + // carried a nudge, show the verbatim wire text once per user turn — + // a transient terminal notification only, never written to the + // session file (billion-context-pi #326 parity: the file keeps the + // compact `[ACP nudge] …` line). Gated on the debug switch. + if (agent === "pi") { + pi.on("after_provider_response", ((_event: unknown, ctx: Ctx) => { + const pending = nudgeFullPending; + if (pending === null || !debugEnabled()) return; + if (nudgeNotifiedTurns.get(pending.sessionId) === pending.turnKey) return; + nudgeNotifiedTurns.set(pending.sessionId, pending.turnKey); + try { + const example = pending.topRange !== null ? `\n\nExample: compress({ content: [{ startId: "${pending.topRange.startRef}", endId: "${pending.topRange.endRef}", summary: "..." }] })` : ""; + ctx.ui?.notify?.(`[ACP nudge → context]${pending.emergency ? " [EMERGENCY]" : ""}\n${pending.text}${example}`); + } catch { + // host UI unavailable — best-effort display + } + }) as unknown as (...args: unknown[]) => void); } const piCommands = piCommandsEnabled(); if (typeof pi.registerCommand === "function") { diff --git a/src/nudge-debug.ts b/src/nudge-debug.ts index 0ea50ca3f8..823d71c5f4 100644 --- a/src/nudge-debug.ts +++ b/src/nudge-debug.ts @@ -1,32 +1,45 @@ -// Nudge-injection debug surface: a tiny in-process pub/sub carrying the EXACT -// wire text a prepare stage just injected as the ephemeral trailing user -// message (post renderNudgeText + withFirstSightDrain/withSummaryBudgetNote/ -// withMarkerIntegrityNote — the final string that goes on the wire, not the -// pre-wrapper template). +// Nudge-injection debug surface: a tiny in-process pub/sub carrying the nudge +// a prepare stage just injected as the ephemeral trailing user message (final +// wrapped wire text, post renderNudgeText + withFirstSightDrain/ +// withSummaryBudgetNote/withMarkerIntegrityNote — the exact string on the +// wire, not the pre-wrapper template). +// +// Display contract (aligned with billion-context-pi issue #326, custom type +// `acp-nudge`): +// 1. The nudge itself goes to the MODEL — that is the pre-existing nudge +// mechanism's job (the model must read it to call compress); this module +// adds nothing to model context. +// 2. ALWAYS: the pi lane mirrors ONE compact record line per user turn +// (`formatNudgeRecord`) into the host transcript as a CustomEntry via +// pi.appendEntry(ACP_NUDGE_CUSTOM_TYPE, { text }). CustomEntries do NOT +// participate in LLM context (pi's buildSessionContext ignores +// type:"custom"), so the record is HUMAN-ONLY: pi-visible, model- +// invisible, and persistent in the session file across restarts. +// 3. DEBUG ONLY (debugEnabled() — ACP_DEBUG > config `debug` > false): the +// verbatim wire text is shown as a transient terminal notification by +// the pi lane; it is never written to the session file. +// Per-turn dedup (turnKey) lives on the consumer side: emergency nudges +// re-inject on every LLM call of a turn and must not flood the session file +// with one record per call — one record per user turn. // // Why a bus and not a log line: the nudge text IS the thing under debugging — // "what did the model actually read this round" — and grepping a log file -// after the fact hides the placement (which turn, which arm). The pi lane -// subscribes (src/agent/pi.ts wireNudgeDebug) and mirrors each event into the -// host transcript as a CustomEntry via pi.appendEntry("bili-nudge", ...) — -// CustomEntry does NOT participate in LLM context (pi's buildSessionContext -// ignores type:"custom"), so the debug view is HUMAN-ONLY: the operator sees -// the verbatim nudge inline in pi, the model never does, and nothing is added -// to any re-sent history. Gated by the existing debug switch -// (debugEnabled(), src/knobs.ts — ACP_DEBUG > config `debug` > false) on the -// consumer side; emitters always fire — a listener-less emit is a no-op, so -// the prepare sites stay config-plumbing-free. +// after the fact hides the placement (which turn, which arm). // // Process scope: the bus is a module-level singleton. It reaches the pi // extension because BOTH live inside the same dist bundle + process in the pi // lane's default INLINE mode (dist/agent/pi-native.js bundles pi.ts AND -// inline-engine.ts AND these prepare modules — tsup splitting:false). In +// inline-engine.ts AND the prepare modules — tsup splitting:false). In // spawn/attach mode the proxy is a separate process holding its own bundle // copy: no listener ever fires there and the feature is inert (documented in // docs/clients.md en+zh, Pi section). type NudgeDebugKind = "advisory" | "directive" | "fallback"; +/** Same custom entry type the pi lane (billion-context-pi) persists for + * nudge records — one name across both pi clients. */ +export const ACP_NUDGE_CUSTOM_TYPE = "acp-nudge"; + export type NudgeDebugEvent = { /** bili session id the nudge armed under (not the host session id). */ sessionId: string; @@ -40,11 +53,89 @@ export type NudgeDebugEvent = { tier: number | null; /** Why the nudge armed (turn.nudge.reason). */ reason: string; - /** The FINAL wrapped wire text, verbatim. */ + /** Context usage at decision time, whole percent. */ + pct: number; + /** Emergency arm (breakdown.emergencyOverride) — record line marks it. */ + emergency: boolean; + /** Largest compressible range by tokens (the record line's suggestion), + * or null when the nudge carried no ranges. */ + topRange: { startRef: string; endRef: string } | null; + /** Identity of the user message this nudge belongs to (the LAST user + * message of the pre-nudge conversation). One record line per + * (session, turnKey) — emergency re-injections within a turn collapse. */ + turnKey: string; + /** The FINAL wrapped wire text, verbatim (debug display only — the pi + * lane shows it transiently and never persists it). */ text: string; ts: number; }; +/** Minimal structural view of the kernel NudgeDecision the emit sites have + * in scope — keeps this module free of a kernel import. */ +type NudgeDecisionView = { + tier: number | null; + reason: string; + contextUsage: number; + breakdown?: { emergencyOverride?: number } | null; + compressibleRanges?: Array<{ startRef: string; endRef: string; tokens: number }> | null; +}; + +/** Fields shared by every emit site of a turn — computed once at the top of + * the injection block (see prepare-anthropic.ts / prepare-openai.ts). */ +type NudgeDebugMeta = Pick; + +export function nudgeDebugMeta(nudge: NudgeDecisionView, preNudgeMessages: Array<{ role?: string; content?: unknown }>): NudgeDebugMeta { + const top = [...(nudge.compressibleRanges ?? [])].sort((a, b) => b.tokens - a.tokens)[0] ?? null; + return { + tier: nudge.tier, + reason: nudge.reason, + pct: Math.round(nudge.contextUsage * 100), + emergency: nudge.breakdown?.emergencyOverride === 1, + topRange: top !== null ? { startRef: top.startRef, endRef: top.endRef } : null, + turnKey: nudgeTurnKey(preNudgeMessages), + }; +} + +/** Cheap identity key for the LAST user message with TEXT content (before + * the nudge append): length + djb2 of the first 512 chars. On the anthropic + * wire, tool results come back as role:"user" with tool_result blocks (no + * text) — they are skipped, so the key stays stable across a turn's tool + * loop and the per-turn record dedup collapses re-injections. A collision + * only ever costs one record line. */ +export function nudgeTurnKey(messages: Array<{ role?: string; content?: unknown }>): string { + for (let i = messages.length - 1; i >= 0; i--) { + const m = messages[i]; + if (m === undefined || m.role !== "user") continue; + const c = m.content; + const text = + typeof c === "string" + ? c + : Array.isArray(c) + ? c.map((p) => (typeof p === "string" ? p : (p as { text?: string } | null)?.text ?? "")).join("") + : ""; + if (text.length === 0) continue; + return `${text.length}:${djb2(text.slice(0, 512))}`; + } + return "0:0"; +} + +function djb2(s: string): number { + let h = 5381; + for (let i = 0; i < s.length; i++) { + h = ((h << 5) + h + s.charCodeAt(i)) >>> 0; + } + return h; +} + +/** Compact one-line twin of the wire nudge (billion-context-pi issue #326 + * formatNudgeRecord): auditability only — the full multi-line nudge + * deliberately stays out of the session file. */ +export function formatNudgeRecord(ev: Pick): string { + const tier = `T${ev.tier ?? 1}`; + const range = ev.topRange !== null ? ` · top range ${ev.topRange.startRef}–${ev.topRange.endRef}` : ""; + return `[ACP nudge]${ev.emergency ? " EMERGENCY" : ""} ${ev.pct}% · ${tier}${range}`; +} + type NudgeDebugListener = (event: NudgeDebugEvent) => void; const listeners = new Set(); diff --git a/src/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index 3ec11cde4f..10bd90b755 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -10,7 +10,7 @@ import { pluginAgentHeader } from "../plugin.js"; import { applyReasoningDrop, dedupeAdjacentOutputConfig, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, makeFoldPointReasoningDroppable, planReasoningDrop, reapOrphansLogged, runNudgeDecision, stripKernelSummaries, warnAnthropicThinkingPairs, type Prepared } from "../server.js"; import { recordNudgeObservation } from "../context-analysis.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; -import { emitNudgeInjected } from "../nudge-debug.js"; +import { emitNudgeInjected, nudgeDebugMeta } from "../nudge-debug.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; import { maybeSnapshotView } from "./snapshot-render.js"; @@ -518,6 +518,10 @@ export async function prepareAnthropic( // anything else injects nothing this round. EMERGENCY arms and // tier>=2 distillation keep the legacy advisory below. const useDecide = decide !== undefined && turn.nudge.tier === 1 && turn.nudge.breakdown.emergencyOverride !== 1; + // Nudge debug record fields (billion-context-pi #326 parity) — + // computed from the PRE-nudge array so the turnKey is the user + // message, stable across the turn's re-injections. + const nudgeMeta = nudgeDebugMeta(turn.nudge, rebuiltMessages); if (useDecide && ladderMode(session.metadata) === "fallback") { consumeFallback(session.metadata); try { @@ -527,7 +531,7 @@ export async function prepareAnthropic( const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; - emitNudgeInjected({ sessionId, protocol: "anthropic", kind: "fallback", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); + emitNudgeInjected({ sessionId, protocol: "anthropic", kind: "fallback", text: wireText, ts: Date.now(), ...nudgeMeta }); } else { nudgeOutcome = "skipped"; } @@ -550,7 +554,7 @@ export async function prepareAnthropic( const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(buildDirectiveText(span.startRef, span.endRef, outcome.topic), turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; - emitNudgeInjected({ sessionId, protocol: "anthropic", kind: "directive", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); + emitNudgeInjected({ sessionId, protocol: "anthropic", kind: "directive", text: wireText, ts: Date.now(), ...nudgeMeta }); } else { nudgeOutcome = "skipped"; log("info", `[${sessionId}] [acp-decide] yes but no live range left to target — skipping injection`); @@ -568,7 +572,7 @@ export async function prepareAnthropic( const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; - emitNudgeInjected({ sessionId, protocol: "anthropic", kind: "advisory", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); + emitNudgeInjected({ sessionId, protocol: "anthropic", kind: "advisory", text: wireText, ts: Date.now(), ...nudgeMeta }); } else { nudgeOutcome = "skipped"; } diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index efaa2dcc3f..ffe690bee0 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -13,7 +13,7 @@ import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTo import { recordNudgeObservation } from "../context-analysis.js"; import { yieldToEventLoop } from "../yield-loop.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; -import { emitNudgeInjected } from "../nudge-debug.js"; +import { emitNudgeInjected, nudgeDebugMeta } from "../nudge-debug.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; import { maybeSnapshotView } from "./snapshot-render.js"; @@ -486,6 +486,10 @@ export async function prepareOpenai( // gentle/over-limit T1 arms ask the model first; EMERGENCY and // tier>=2 keep the legacy advisory. const useDecide = decide !== undefined && turn.nudge.tier === 1 && turn.nudge.breakdown.emergencyOverride !== 1; + // Nudge debug record fields (billion-context-pi #326 parity) — + // computed from the PRE-nudge array so the turnKey is the user + // message, stable across the turn's re-injections. + const nudgeMeta = nudgeDebugMeta(turn.nudge, rebuiltMessages); if (useDecide && ladderMode(session.metadata) === "fallback") { consumeFallback(session.metadata); try { @@ -495,7 +499,7 @@ export async function prepareOpenai( const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; - emitNudgeInjected({ sessionId, protocol: "openai", kind: "fallback", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); + emitNudgeInjected({ sessionId, protocol: "openai", kind: "fallback", text: wireText, ts: Date.now(), ...nudgeMeta }); } else { nudgeOutcome = "skipped"; } @@ -518,7 +522,7 @@ export async function prepareOpenai( const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(buildDirectiveText(span.startRef, span.endRef, outcome.topic), turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; - emitNudgeInjected({ sessionId, protocol: "openai", kind: "directive", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); + emitNudgeInjected({ sessionId, protocol: "openai", kind: "directive", text: wireText, ts: Date.now(), ...nudgeMeta }); } else { nudgeOutcome = "skipped"; log("info", `[${sessionId}] [acp-decide] yes but no live range left to target — skipping injection`); @@ -538,7 +542,7 @@ export async function prepareOpenai( const wireText = withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers); rebuiltMessages = [...rebuiltMessages, { role: "user", content: wireText }]; nudgeOutcome = "injected"; - emitNudgeInjected({ sessionId, protocol: "openai", kind: "advisory", tier: turn.nudge.tier, reason: turn.nudge.reason, text: wireText, ts: Date.now() }); + emitNudgeInjected({ sessionId, protocol: "openai", kind: "advisory", text: wireText, ts: Date.now(), ...nudgeMeta }); } else { nudgeOutcome = "skipped"; } diff --git a/tests/nudge-debug.test.ts b/tests/nudge-debug.test.ts index 8800af4e52..63e777f217 100644 --- a/tests/nudge-debug.test.ts +++ b/tests/nudge-debug.test.ts @@ -1,10 +1,13 @@ -// Nudge debug surface (gated by the existing debug switch — ACP_DEBUG / config -// debug): the prepare stage must mirror the EXACT nudge wire text it injects -// into the in-process bus (src/nudge-debug.ts); the pi lane turns each event -// into a transcript-only CustomEntry (src/agent/pi.ts — CustomEntry never -// enters LLM context). Gold assertion: the bus event text is BYTE-IDENTICAL -// to the trailing user message content the proxy actually sent upstream — the -// human in pi sees exactly what the model read, and nothing more. +// Nudge debug surface (billion-context-pi issue #326 parity): the prepare +// stage must mirror the EXACT nudge wire text it injects into the in-process +// bus (src/nudge-debug.ts); the pi lane turns each event into ONE compact +// `[ACP nudge] …` CustomEntry record line per user turn (ALWAYS on — +// CustomEntry never enters LLM context, pi-visible / model-invisible, +// persistent in the session file) and, with the debug switch on +// (ACP_DEBUG / config `debug`), a transient verbatim terminal notification. +// Gold assertion: the bus event text is BYTE-IDENTICAL to the trailing user +// message content the proxy actually sent upstream — the human in pi sees +// exactly what the model read, and nothing more. import assert from "node:assert/strict"; import fs from "node:fs"; import http from "node:http"; @@ -20,7 +23,7 @@ import { startServer } from "../src/server.ts"; import type { ProxyOptions } from "../src/config.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; -import { emitNudgeInjected, onNudgeInjected, _resetNudgeDebugForTest, type NudgeDebugEvent } from "../src/nudge-debug.ts"; +import { emitNudgeInjected, onNudgeInjected, _resetNudgeDebugForTest, formatNudgeRecord, nudgeDebugMeta, nudgeTurnKey, type NudgeDebugEvent } from "../src/nudge-debug.ts"; import { debugEnabled } from "../src/knobs.ts"; import { createBiliPlugin } from "../src/agent/pi.ts"; @@ -37,7 +40,7 @@ test("nudge-debug bus: emit reaches subscribers; unsubscribe works; a throwing l const later = onNudgeInjected(() => { afterThrow = true; }); - const ev: NudgeDebugEvent = { sessionId: "s1", protocol: "anthropic", kind: "advisory", tier: null, reason: "r", text: "T", ts: 1 }; + const ev: NudgeDebugEvent = { sessionId: "s1", protocol: "anthropic", kind: "advisory", tier: null, reason: "r", pct: 92, emergency: false, topRange: null, turnKey: "42:123456", text: "T", ts: 1 }; emitNudgeInjected(ev); assert.deepEqual(seen, [ev]); assert.ok(afterThrow, "a throwing listener must not break later subscribers"); @@ -80,16 +83,47 @@ test("debugEnabled: ACP_DEBUG env wins; file `debug` tier; default off; only the } }); +// ---------- record line + turn key (billion-context-pi #326 parity) ---------- + +test("formatNudgeRecord: matches the pi-lane one-liner format", () => { + const base = { tier: 2, pct: 92, emergency: false, topRange: { startRef: "m00010", endRef: "m00030" } }; + assert.equal(formatNudgeRecord(base), "[ACP nudge] 92% · T2 · top range m00010–m00030"); + assert.equal(formatNudgeRecord({ ...base, emergency: true }), "[ACP nudge] EMERGENCY 92% · T2 · top range m00010–m00030"); + assert.equal(formatNudgeRecord({ ...base, tier: null, topRange: null }), "[ACP nudge] 92% · T1"); +}); + +test("nudgeTurnKey: identity of the last TEXT user message; tool-only tails do not move it", () => { + const u = { role: "user", content: "please fix the ledger bug" }; + const a = { role: "assistant", content: "on it" }; + const t1 = nudgeTurnKey([u, a]); + // anthropic wire: tool results come back as role:"user" with tool_result + // blocks (no text) — they must NOT change the key, or the per-turn record + // dedup could not collapse a turn's re-injections. + const toolResult = { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "ok" }] }; + assert.equal(nudgeTurnKey([u, a, toolResult]), t1, "tool_result tail keeps the key"); + assert.notEqual(nudgeTurnKey([{ role: "user", content: "a different ask" }]), t1, "different user message → different key"); + assert.equal(nudgeTurnKey([a]), "0:0", "no user message at all"); +}); + +test("nudgeDebugMeta: pct rounds, emergency flags, top range by tokens", () => { + const meta = nudgeDebugMeta( + { tier: 2, reason: "over-limit", contextUsage: 0.924, breakdown: { emergencyOverride: 0 }, compressibleRanges: [{ startRef: "m1", endRef: "m2", tokens: 400 }, { startRef: "m3", endRef: "m4", tokens: 900 }] }, + [{ role: "user", content: "go" }], + ); + assert.equal(meta.pct, 92); + assert.equal(meta.emergency, false); + assert.deepEqual(meta.topRange, { startRef: "m3", endRef: "m4" }, "largest range by tokens"); + assert.equal(typeof meta.turnKey, "string"); + const emergency = nudgeDebugMeta({ tier: 1, reason: "x", contextUsage: 0.98, breakdown: { emergencyOverride: 1 }, compressibleRanges: [] }, [{ role: "user", content: "go" }]); + assert.equal(emergency.emergency, true); + assert.equal(emergency.topRange, null, "no ranges → null"); +}); + // ---------- pi wiring gate (both directions, #3617 discipline) ---------- -test("pi wiring: the bili-nudge entry renderer registers iff the debug switch is on", () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "bili-nudge-gate-")); - const cfg = path.join(root, "config.jsonc"); +test("pi wiring: the acp-nudge entry renderer registers on every pi host (record lines are always on)", () => { const savedEnv = process.env.ACP_DEBUG; - const savedCfg = process.env.BILI_CONFIG_FILE; try { - fs.writeFileSync(cfg, "{}"); - process.env.BILI_CONFIG_FILE = cfg; if (savedEnv !== undefined) process.env.ACP_DEBUG = savedEnv; else delete process.env.ACP_DEBUG; const makeStub = () => { @@ -108,23 +142,22 @@ test("pi wiring: the bili-nudge entry renderer registers iff the debug switch is getSessionName: () => "test", }; }; - const off = makeStub(); - createBiliPlugin("pi")(off as never); - assert.ok(!off.entryTypes.includes("bili-nudge"), "off by default"); - process.env.ACP_DEBUG = "0"; - const offExplicit = makeStub(); - createBiliPlugin("pi")(offExplicit as never); - assert.ok(!offExplicit.entryTypes.includes("bili-nudge"), "env '0' keeps it off"); - process.env.ACP_DEBUG = "1"; + // Always on now — the compact record line no longer rides the debug + // switch (billion-context-pi #326: one line per turn, persistent); + // the switch gates only the transient full-text terminal notify. const on = makeStub(); createBiliPlugin("pi")(on as never); - assert.ok(on.entryTypes.includes("bili-nudge"), "registers when ACP_DEBUG=1"); + assert.ok(on.entryTypes.includes("acp-nudge"), "registers on the pi host without any debug config"); + process.env.ACP_DEBUG = "0"; + const off = makeStub(); + createBiliPlugin("pi")(off as never); + assert.ok(off.entryTypes.includes("acp-nudge"), "stays registered with the debug switch explicitly off"); + const other = makeStub(); + createBiliPlugin("omp")(other as never); + assert.ok(!other.entryTypes.includes("acp-nudge"), "pi lane only"); } finally { if (savedEnv === undefined) delete process.env.ACP_DEBUG; else process.env.ACP_DEBUG = savedEnv; - if (savedCfg === undefined) delete process.env.BILI_CONFIG_FILE; - else process.env.BILI_CONFIG_FILE = savedCfg; - fs.rmSync(root, { recursive: true, force: true }); } }); @@ -260,6 +293,9 @@ test("nudge-debug e2e (anthropic wire): bus event text is byte-identical to the assert.equal(ev.protocol, "anthropic"); assert.equal(ev.kind, "advisory", "no decide config in this harness → legacy advisory arm"); assert.equal(ev.text.length > 0, true, "event carries the verbatim wire text"); + assert.ok(ev.pct >= 0 && ev.pct <= 100, "record metadata: usage percent"); + assert.equal(ev.emergency, false, "the over-limit band here is not the emergency arm"); + assert.ok(typeof ev.turnKey === "string" && ev.turnKey.length > 0, "record metadata: turn key"); const body = JSON.parse(h.captured[1]!) as { messages: Array<{ role: string; content: string | Array<{ type?: string; text?: string }> }> }; const sent = ANTHROPIC_MESSAGES().length; From 1090cd876459cb553af3dc2af210b36cda38fb99 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Wed, 11 Nov 2026 09:38:10 +0800 Subject: [PATCH 5/5] =?UTF-8?q?pi=20lane:=20drop=20the=20persistent=20nudg?= =?UTF-8?q?e=20record=20line=20=E2=80=94=20transient=20verbatim=20notify?= =?UTF-8?q?=20only?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per owner review: the always-on compact record line (acp-nudge CustomEntry, billion-context-pi #326 parity) is unnecessary — the transient verbatim terminal notification (debug switch on) is the whole point of this feature. - src/agent/pi.ts: no more registerEntryRenderer/appendEntry wiring; one after_provider_response hook shows the verbatim wire text once per user turn via ctx.ui.notify (consumes+clears the pending event, turnKey dedup) - src/nudge-debug.ts: drop ACP_NUDGE_CUSTOM_TYPE + formatNudgeRecord - tests: wiring test asserts the pi host carries exactly one extra after_provider_response subscription vs omp (the #3248 ack channel subscribes both lanes); formatNudgeRecord test removed - docs en+zh, architecture.md: transient notify only, never persisted --- docs/clients.md | 27 ++++++--------- docs/clients.zh-CN.md | 2 +- reference/architecture.md | 2 +- src/agent/pi.ts | 72 ++++++++++----------------------------- src/nudge-debug.ts | 43 ++++++----------------- tests/nudge-debug.test.ts | 52 +++++++++++----------------- 6 files changed, 62 insertions(+), 136 deletions(-) diff --git a/docs/clients.md b/docs/clients.md index 1fd5eb8e82..6f177f15e2 100644 --- a/docs/clients.md +++ b/docs/clients.md @@ -700,22 +700,17 @@ Full field table and the `PI_ACP_DELEGATE_*` env overrides: configuration.md → [`pi`](configuration.md#pi). **Nudge visibility (what the proxy injected, without model-context cost).** -Every nudge the proxy injects mid-compression leaves a COMPACT RECORD LINE in -the pi transcript — `[ACP nudge] 92% · T2 · top range m0120–m0145` (percent of -context used, tier, optional top compressible range; `EMERGENCY` flag when the -emergency arm fired) — one per user turn, always on, no config needed. The -line is a pi `CustomEntry` of type `acp-nudge`, which never enters the LLM -context (pi's session-context build ignores `type:"custom"`) and persists in -the session file across restarts: pi-visible, model-invisible. With the -global debug switch on (`ACP_DEBUG=1`, or `"debug": true` in the config -file) the VERBATIM wire text — exactly the ephemeral trailing user message -the model reads that turn — is additionally shown once per turn as a transient -terminal notification; it is never written to the session file. Pi inline -mode only — in spawn/attach the proxy is a separate process and the view is -unavailable. Covers the Anthropic and OpenAI wire lanes (the two pi reaches -over HTTP); on hosts without `registerEntryRenderer`/`appendEntry` the feature -degrades to absent. (Custom type and line format aligned with the official -pi client, billion-context-pi issue #326.) +With the global debug switch on (`ACP_DEBUG=1`, or `"debug": true` in the +config file), every nudge the proxy injects mid-compression is shown in the +terminal — once per user turn, as a transient notification after the model +has answered — with the VERBATIM wire text: exactly the ephemeral trailing +user message the model reads that turn, byte for byte. The notification is +terminal-only: it is never written to the session file and adds nothing to +model context (the nudge reaching the model is the pre-existing mechanism's +job; this view just lets a human see it happen). Pi inline mode only — in +spawn/attach the proxy is a separate process and the view is unavailable. +Covers the Anthropic and OpenAI wire lanes (the two pi reaches over HTTP); on +hosts without `ui.notify` the feature degrades to absent. **How routing works.** The pi extension bootstraps (or attaches to) its own proxy and patches `globalThis.fetch` in-process: every model-API HTTP request diff --git a/docs/clients.zh-CN.md b/docs/clients.zh-CN.md index 7bc23f481d..d942693270 100644 --- a/docs/clients.zh-CN.md +++ b/docs/clients.zh-CN.md @@ -164,7 +164,7 @@ Pi 有完整原生模式(`bili plugin install pi`,README 快速上手方案 1); **子代理配置(#2230)。** 内置 `acp_delegate` 面(三个 delegate 工具、角色、fleet 检查器——由 `bili pi` 经内嵌扩展接线)配置在 bili 自己的配置文件:`~/.config/billion-context/billion-context.json` 的 `pi.subagents` 段(布尔简写 `"pi": {"subagents": false}` 可整体关闭)。`~/.pi/acp.json` 的四键(`delegate` / `delegatePrompt` / `displayUsage` / `debug`)是已废弃的回退源——仅当段缺失时读取,段存在后完全忽略。完整字段表与 `PI_ACP_DELEGATE_*` 环境变量见 configuration.zh-CN.md 的 [`pi`](configuration.zh-CN.md#pi) 段。 -**nudge 可见性(模型零上下文成本,看代理注入了什么)。** 代理在压缩过程中每次注入 nudge,都会在 pi 会话记录里留下一条**紧凑记录行**——`[ACP nudge] 92% · T2 · top range m0120–m0145`(上下文占用百分比、tier、可选的最大可压缩区间;紧急臂触发时带 `EMERGENCY` 标志)——每个用户 turn 一行,**始终开启,无需任何配置**。该行是 `acp-nudge` 类型的 pi `CustomEntry`,从不进入模型上下文(pi 的会话上下文构建会忽略 `type:"custom"`),且持久化在 session 文件里、重启后仍在:pi 可见、模型不可见。打开全局 debug 开关(`ACP_DEBUG=1` 或配置文件 `"debug": true`)后,还会在终端以**一次性临时通知**的形式显示**逐字 wire 原文**——即模型当轮实际读到的那条临时尾随 user 消息,一字不差;原文从不写入 session 文件。仅 pi inline 模式有效——spawn/attach 下代理是独立进程,看不到;覆盖 Anthropic 与 OpenAI 两条 wire 车道(pi 走 HTTP 仅有的两条);宿主缺少 `registerEntryRenderer`/`appendEntry` 时此功能静默缺席。(custom type 与行格式与官方 pi 客户端 billion-context-pi issue #326 对齐。) +**nudge 可见性(模型零上下文成本,看代理注入了什么)。** 打开全局 debug 开关(`ACP_DEBUG=1` 或配置文件 `"debug": true`)后,代理每次在压缩中注入 nudge,都会在终端以**一次性临时通知**显示——每个用户 turn 一次,且在该轮模型回答之后——显示的是**逐字 wire 原文**,即模型当轮实际读到的那条临时尾随 user 消息,一字不差。通知只进终端:从不写入 session 文件,也不给模型上下文增加任何东西(nudge 进模型是既有机制的职责,这个视图只是让人看到它发生)。仅 pi inline 模式有效——spawn/attach 下代理是独立进程,看不到;覆盖 Anthropic 与 OpenAI 两条 wire 车道(pi 走 HTTP 仅有的两条);宿主没有 `ui.notify` 时此功能静默缺席。 **路由机制。** pi 扩展自行拉起(或附着)代理并进程内 patch `globalThis.fetch`:所有模型 API 的 HTTP 请求被改写到 `/bili/`,扩展经 pi 的 `before_provider_headers` 事件盖 `x-bili-plugin*` 头。所有 HTTP 系 provider(Anthropic、OpenAI chat/completions/responses、Gemini、Mistral、OpenRouter、Azure、自定义中转……)走这条路,得到具名 plugin-mode 会话。 diff --git a/reference/architecture.md b/reference/architecture.md index 9429e2ee66..f2a24cc267 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -287,7 +287,7 @@ billion-context/ │ ├── notice-store.ts # Notice dismissal receipts in unified kv_store, legacy file fallback (#5548) │ ├── notices.ts # Built-in notice registry: activity predicates + i18n key table (#5548) │ ├── nudge-decide.ts # Model-decided nudge timing over the already-cached prefix (#2228) -│ ├── nudge-debug.ts # Nudge-injection bus: compact `[ACP nudge]` record line (CustomEntry, always on) + verbatim wire text for the debug terminal notify (billion-context-pi #326 parity; never in LLM context) +│ ├── nudge-debug.ts # Nudge-injection bus: mirrors the exact wire nudge text to the pi lane's debug terminal notify (transient, never in LLM context, never persisted) │ ├── order-persist.ts # Persists session-order skeletons across restarts (#3397) │ ├── pack-install.ts # bili pack install|remove|list: npm-distributable prompt packs (#5319) │ ├── pck-notice.ts # One-time notice for the prompt_cache.routing default flip (#5079) diff --git a/src/agent/pi.ts b/src/agent/pi.ts index 5be61bfe52..b858f3eed8 100644 --- a/src/agent/pi.ts +++ b/src/agent/pi.ts @@ -5,13 +5,13 @@ // minimal structural declarations — the bundled artifact imports NOTHING // from the host at runtime (the host duck-types us in). -import type { EntryRenderer, MessageRenderer } from "@earendil-works/pi-coding-agent"; +import type { MessageRenderer } from "@earendil-works/pi-coding-agent"; import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui"; import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { wrapCacheReport, wrapRuleReport } from "../acp-panel.js"; -import { ACP_NUDGE_CUSTOM_TYPE, formatNudgeRecord, onNudgeInjected, type NudgeDebugEvent } from "../nudge-debug.js"; +import { onNudgeInjected, type NudgeDebugEvent } from "../nudge-debug.js"; import { awaitNativeProxyOrigin } from "./native-bootstrap.js"; import { disposeSubagentSelfReg, selfRegisterForSession, type SubagentSelfRegState } from "./pi-subagent-registry.js"; import { isModelApiUrl, nativeInterceptInstalled } from "./native-intercept.js"; @@ -83,13 +83,6 @@ type ExtensionAPI = { registerTool: (tool: ToolDefinition) => void; registerCommand?: (name: string, options: { description?: string; handler: (args: string, ctx: CommandCtx) => void | Promise }) => void; registerMessageRenderer?: (customType: string, renderer: MessageRenderer) => void; - // Nudge debug surface (debug switch, ACP_DEBUG/debug): mirror the exact - // injected nudge wire text into the transcript as a CustomEntry — - // human-visible, never in LLM context (the host's session-context build - // ignores type:"custom"). Optional because older hosts lack it; without - // it the debug view is simply unavailable. - registerEntryRenderer?: (customType: string, renderer: EntryRenderer) => void; - appendEntry?: (customType: string, data?: unknown) => void; // #2186: acp_delegate (inlined from billion-context-pi-subagents) injects // completion notifications through the host's persistent transcript // channel; optional because older hosts and non-pi hosts lack it. @@ -902,16 +895,14 @@ export function createPiDirectSendGuard(): (url: string, input: string | URL | R // Nudge-debug wiring guard: the bus subscription is process-global (the // emitters live in this same bundle in inline mode), so wire it at most once // even if a host ever re-invokes the factory. -// Nudge debug surface (billion-context-pi issue #326 parity) — module-level -// because the bus subscription is process-singleton: +// Nudge debug surface (transient terminal view only) — module-level because +// the bus subscription is process-singleton: // nudgeDebugWired: the onNudgeInjected listener registered exactly once. -// nudgeRecordedTurns: (sessionId → turnKey) one compact record line per user -// turn — emergency nudges re-inject on every LLM call and must not -// flood the session file. -// nudgeFullPending / nudgeNotifiedTurns: the verbatim wire text is shown as -// a transient terminal notification (debug switch on), deduped per turn. +// nudgeFullPending: the latest injected nudge, consumed (and cleared) by the +// after_provider_response hook once the model has answered. +// nudgeNotifiedTurns: (sessionId → turnKey) dedup — emergency nudges +// re-inject on every LLM call of a turn; notify at most once per turn. let nudgeDebugWired = false; -const nudgeRecordedTurns = new Map(); const nudgeNotifiedTurns = new Map(); let nudgeFullPending: NudgeDebugEvent | null = null; @@ -1126,51 +1117,24 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM return box; }); } - // Nudge display (aligned with billion-context-pi issue #326, custom - // type `acp-nudge`): the nudge ITSELF goes to the model — that is the - // pre-existing mechanism's job, this surface adds nothing to model - // context. What lands in the transcript: ONE compact record line per - // user turn (`[ACP nudge] …`), always, as a CustomEntry — pi-visible, - // model-invisible (pi's buildSessionContext ignores type:"custom"), - // persistent in the session file. With the debug switch on - // (ACP_DEBUG / config `debug`) the VERBATIM wire text is additionally - // shown as a transient terminal notification (see the - // after_provider_response hook) and is never persisted. - // Engine-side emitter: same bundle/process in the default INLINE pi - // mode (spawn/attach proxies are separate processes — no bus - // listener, feature inert there; docs/clients.md). - if (agent === "pi" && typeof pi.registerEntryRenderer === "function" && typeof pi.appendEntry === "function") { + // Nudge debug view (transient only, gated on the debug switch — + // ACP_DEBUG / config `debug`): when the proxy injects a nudge (the + // ephemeral trailing user message the model reads), the VERBATIM wire + // text is shown once per user turn as a terminal notification after + // the model has answered. Nothing is persisted and nothing is added + // to model context. Engine-side emitter: same bundle/process in the + // default INLINE pi mode (spawn/attach proxies are separate processes + // — no bus listener, feature inert there; docs/clients.md). + if (agent === "pi") { if (!nudgeDebugWired) { nudgeDebugWired = true; onNudgeInjected((event) => { - try { - if (nudgeRecordedTurns.get(event.sessionId) !== event.turnKey) { - nudgeRecordedTurns.set(event.sessionId, event.turnKey); - pi.appendEntry?.(ACP_NUDGE_CUSTOM_TYPE, { text: formatNudgeRecord(event) }); - } - } catch { - // debug surface only — a failed append must never break the request pipeline - } nudgeFullPending = event; }); } - pi.registerEntryRenderer(ACP_NUDGE_CUSTOM_TYPE, (entry, _options, theme) => { - const data = entry.data as { text?: unknown } | undefined; - const text = data !== undefined && typeof data === "object" ? data.text : undefined; - if (typeof text !== "string" || text.length === 0) return undefined; - const box = new Box(1, 1, (line) => theme.bg("customMessageBg", line)); - box.addChild(new Text(theme.fg("dim", text), 0, 0)); - return box; - }); - } - // Nudge debug FULL text: once the model has answered a request that - // carried a nudge, show the verbatim wire text once per user turn — - // a transient terminal notification only, never written to the - // session file (billion-context-pi #326 parity: the file keeps the - // compact `[ACP nudge] …` line). Gated on the debug switch. - if (agent === "pi") { pi.on("after_provider_response", ((_event: unknown, ctx: Ctx) => { const pending = nudgeFullPending; + nudgeFullPending = null; if (pending === null || !debugEnabled()) return; if (nudgeNotifiedTurns.get(pending.sessionId) === pending.turnKey) return; nudgeNotifiedTurns.set(pending.sessionId, pending.turnKey); diff --git a/src/nudge-debug.ts b/src/nudge-debug.ts index 823d71c5f4..a65a41bc2c 100644 --- a/src/nudge-debug.ts +++ b/src/nudge-debug.ts @@ -4,23 +4,15 @@ // withSummaryBudgetNote/withMarkerIntegrityNote — the exact string on the // wire, not the pre-wrapper template). // -// Display contract (aligned with billion-context-pi issue #326, custom type -// `acp-nudge`): -// 1. The nudge itself goes to the MODEL — that is the pre-existing nudge -// mechanism's job (the model must read it to call compress); this module -// adds nothing to model context. -// 2. ALWAYS: the pi lane mirrors ONE compact record line per user turn -// (`formatNudgeRecord`) into the host transcript as a CustomEntry via -// pi.appendEntry(ACP_NUDGE_CUSTOM_TYPE, { text }). CustomEntries do NOT -// participate in LLM context (pi's buildSessionContext ignores -// type:"custom"), so the record is HUMAN-ONLY: pi-visible, model- -// invisible, and persistent in the session file across restarts. -// 3. DEBUG ONLY (debugEnabled() — ACP_DEBUG > config `debug` > false): the -// verbatim wire text is shown as a transient terminal notification by -// the pi lane; it is never written to the session file. -// Per-turn dedup (turnKey) lives on the consumer side: emergency nudges -// re-inject on every LLM call of a turn and must not flood the session file -// with one record per call — one record per user turn. +// Display contract: the nudge ITSELF goes to the model — that is the +// pre-existing nudge mechanism's job (the model must read it to call +// compress); this module adds nothing to model context. The pi lane mirrors +// the injection to the TERMINAL ONLY, gated on the debug switch +// (debugEnabled() — ACP_DEBUG > config `debug` > false): once the model has +// answered a request that carried a nudge, the verbatim wire text is shown +// as a transient terminal notification (pi.ui.notify), at most once per user +// turn (per-turn dedup, turnKey: emergency nudges re-inject on every LLM +// call of a turn). Nothing is written to the session file. // // Why a bus and not a log line: the nudge text IS the thing under debugging — // "what did the model actually read this round" — and grepping a log file @@ -36,10 +28,6 @@ type NudgeDebugKind = "advisory" | "directive" | "fallback"; -/** Same custom entry type the pi lane (billion-context-pi) persists for - * nudge records — one name across both pi clients. */ -export const ACP_NUDGE_CUSTOM_TYPE = "acp-nudge"; - export type NudgeDebugEvent = { /** bili session id the nudge armed under (not the host session id). */ sessionId: string; @@ -64,8 +52,8 @@ export type NudgeDebugEvent = { * message of the pre-nudge conversation). One record line per * (session, turnKey) — emergency re-injections within a turn collapse. */ turnKey: string; - /** The FINAL wrapped wire text, verbatim (debug display only — the pi - * lane shows it transiently and never persists it). */ + /** The FINAL wrapped wire text, verbatim (debug display only — shown + * transiently in the terminal, never persisted). */ text: string; ts: number; }; @@ -127,15 +115,6 @@ function djb2(s: string): number { return h; } -/** Compact one-line twin of the wire nudge (billion-context-pi issue #326 - * formatNudgeRecord): auditability only — the full multi-line nudge - * deliberately stays out of the session file. */ -export function formatNudgeRecord(ev: Pick): string { - const tier = `T${ev.tier ?? 1}`; - const range = ev.topRange !== null ? ` · top range ${ev.topRange.startRef}–${ev.topRange.endRef}` : ""; - return `[ACP nudge]${ev.emergency ? " EMERGENCY" : ""} ${ev.pct}% · ${tier}${range}`; -} - type NudgeDebugListener = (event: NudgeDebugEvent) => void; const listeners = new Set(); diff --git a/tests/nudge-debug.test.ts b/tests/nudge-debug.test.ts index 63e777f217..2e413d8f66 100644 --- a/tests/nudge-debug.test.ts +++ b/tests/nudge-debug.test.ts @@ -1,10 +1,9 @@ -// Nudge debug surface (billion-context-pi issue #326 parity): the prepare -// stage must mirror the EXACT nudge wire text it injects into the in-process -// bus (src/nudge-debug.ts); the pi lane turns each event into ONE compact -// `[ACP nudge] …` CustomEntry record line per user turn (ALWAYS on — -// CustomEntry never enters LLM context, pi-visible / model-invisible, -// persistent in the session file) and, with the debug switch on -// (ACP_DEBUG / config `debug`), a transient verbatim terminal notification. +// Nudge debug surface: the prepare stage must mirror the EXACT nudge wire +// text it injects into the in-process bus (src/nudge-debug.ts); the pi lane +// shows it as a TRANSIENT terminal notification (debug switch on — +// ACP_DEBUG / config `debug`), once per user turn, never persisted. The nudge +// itself going to the model is the pre-existing mechanism's job; this module +// adds nothing to model context. // Gold assertion: the bus event text is BYTE-IDENTICAL to the trailing user // message content the proxy actually sent upstream — the human in pi sees // exactly what the model read, and nothing more. @@ -23,7 +22,7 @@ import { startServer } from "../src/server.ts"; import type { ProxyOptions } from "../src/config.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; -import { emitNudgeInjected, onNudgeInjected, _resetNudgeDebugForTest, formatNudgeRecord, nudgeDebugMeta, nudgeTurnKey, type NudgeDebugEvent } from "../src/nudge-debug.ts"; +import { emitNudgeInjected, onNudgeInjected, _resetNudgeDebugForTest, nudgeDebugMeta, nudgeTurnKey, type NudgeDebugEvent } from "../src/nudge-debug.ts"; import { debugEnabled } from "../src/knobs.ts"; import { createBiliPlugin } from "../src/agent/pi.ts"; @@ -83,14 +82,7 @@ test("debugEnabled: ACP_DEBUG env wins; file `debug` tier; default off; only the } }); -// ---------- record line + turn key (billion-context-pi #326 parity) ---------- - -test("formatNudgeRecord: matches the pi-lane one-liner format", () => { - const base = { tier: 2, pct: 92, emergency: false, topRange: { startRef: "m00010", endRef: "m00030" } }; - assert.equal(formatNudgeRecord(base), "[ACP nudge] 92% · T2 · top range m00010–m00030"); - assert.equal(formatNudgeRecord({ ...base, emergency: true }), "[ACP nudge] EMERGENCY 92% · T2 · top range m00010–m00030"); - assert.equal(formatNudgeRecord({ ...base, tier: null, topRange: null }), "[ACP nudge] 92% · T1"); -}); +// ---------- turn key (per-turn dedup for the terminal notify) ---------- test("nudgeTurnKey: identity of the last TEXT user message; tool-only tails do not move it", () => { const u = { role: "user", content: "please fix the ledger bug" }; @@ -119,42 +111,38 @@ test("nudgeDebugMeta: pct rounds, emergency flags, top range by tokens", () => { assert.equal(emergency.topRange, null, "no ranges → null"); }); -// ---------- pi wiring gate (both directions, #3617 discipline) ---------- +// ---------- pi wiring (both directions, #3617 discipline) ---------- -test("pi wiring: the acp-nudge entry renderer registers on every pi host (record lines are always on)", () => { +test("pi wiring: the nudge terminal-notify hook subscribes on the pi host only", () => { const savedEnv = process.env.ACP_DEBUG; try { if (savedEnv !== undefined) process.env.ACP_DEBUG = savedEnv; else delete process.env.ACP_DEBUG; const makeStub = () => { - const entryTypes: string[] = []; + const events: string[] = []; return { - entryTypes, - on: () => {}, + events, + on: (name: string) => { events.push(name); }, fire: () => undefined, fireAsync: async () => undefined, registerTool: () => {}, registerCommand: () => {}, registerProvider: () => {}, registerMessageRenderer: () => {}, - registerEntryRenderer: (t: string) => { entryTypes.push(t); }, - appendEntry: () => {}, getSessionName: () => "test", }; }; - // Always on now — the compact record line no longer rides the debug - // switch (billion-context-pi #326: one line per turn, persistent); - // the switch gates only the transient full-text terminal notify. const on = makeStub(); createBiliPlugin("pi")(on as never); - assert.ok(on.entryTypes.includes("acp-nudge"), "registers on the pi host without any debug config"); - process.env.ACP_DEBUG = "0"; - const off = makeStub(); - createBiliPlugin("pi")(off as never); - assert.ok(off.entryTypes.includes("acp-nudge"), "stays registered with the debug switch explicitly off"); const other = makeStub(); createBiliPlugin("omp")(other as never); - assert.ok(!other.entryTypes.includes("acp-nudge"), "pi lane only"); + // The #3248 incremental-ack channel subscribes after_provider_response + // for BOTH lanes unconditionally, so assert the DIFFERENCE: the pi + // host carries exactly one extra subscription — the nudge notify hook + // (the debug switch gates the display, not the wiring). + const count = (s: { events: string[] }) => s.events.filter((e) => e === "after_provider_response").length; + assert.ok(count(on) >= 1, "pi host has the after_provider_response hook"); + assert.equal(count(on), count(other) + 1, "pi lane only: exactly one extra after_provider_response subscription vs omp"); } finally { if (savedEnv === undefined) delete process.env.ACP_DEBUG; else process.env.ACP_DEBUG = savedEnv;