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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Changelog

## Unreleased (master, since v0.1.38)
- **feat(nudge): nudge 注入持久化为只读 session entry + acp.log 单物理行(closes #326)** — 此前 nudge 提示仅经 `ctx.ui.notify()` 显示为瞬态 `Text` 子节点,进程重启后 `chatContainer.clear()` + 重建把注入历史从视图里全部抹掉;且 acp.log 中多行 nudge body 溢出到未打标签的物理行,`grep nudge-injected` 只能拿到标题行。现在注入时经 `pi.appendEntry("acp-nudge", ...)` 追加一条紧凑记录(如 `[ACP nudge] EMERGENCY 95% · T1 · top range m00120–m00168`):pi 的 custom entry 为 `type:"custom"`,不进入发送视图(只有 `custom_message` 会投影给模型),故零模型上下文污染;entry 落盘 session JSONL,重启可恢复,并注册 entry renderer(基于 pi-tui 的 dim box,内联 bundle 进 dist、零新增运行时依赖)使其在 TUI scrollback 与重建后均可见;按用户轮去重(每轮至多一条,emergency 逐次重注入不重复落盘)。同时 `log.ts` 对字符串字段(含 stack)转义 `\r`/`\n`,保证每条日志恰好占一个物理行、grep 自包含
- **fix(proxy): native 模式共存——退让检查增加 BILLION_CONTEXT_NATIVE 动作时检测,env 检查改为逐事件重读(closes #461)** — billion-context host-native 模式(pi-native,billion-context#706/#824)在进程内自拉起代理并在 **fetch 层**改写模型 API 流量:本扩展与 native 入口同进程加载时双压缩(违反单一压缩 owner 原则)。现有两条自禁用信号在 native 模式下均不可见:① `BILLION_CONTEXT_PROXY` 只在扩展加载(factory)时读一次,而 native 下该变量由 bootstrap 在代理起来之后**异步**写入(通常几十毫秒后),各扩展模块启动期同步连续求值 → 时序上几乎必然漏检;② lazy 守卫只认 `ctx.model.baseUrl` 的 `/bili/<scheme>://` 前缀,而 native 的改写发生在 fetch 层、配置里的 baseUrl 永远是原始上游地址。修复:lazy 守卫(session_start + context 两个检测点)补测 `process.env.BILLION_CONTEXT_NATIVE`(native 入口模块求值时在**任何 await 之前**同步写入、first-writer-wins,billion-context `markNativeHost()`),并把 `BILLION_CONTEXT_PROXY` 从一次性读取改为动作时重读(异步启动同样会漏检);命中走既有 refusal 路径(`runtime.refused=true`、四个工具返回原因),native 命中用专门文案注明 "native mode detected"(含宿主值,便于诊断宿主错位),结构化日志 `event=native-host-detected`。launcher 模式(`bili pi`,env 随子进程继承)与手动接线模式(baseUrl 带 `/bili/` 前缀)行为不变;上游 native 落地前零行为变化(标记未设即不命中)。测试 `tests/proxy-standdown.test.ts` +2(native 标记全链路退让 / factory 之后才设置的 PROXY env 被惰性重读捕获)
- **fix(size): 上下文规模记账校准锚定——内部估计不再与 provider 实测长期偏离 1.5-2x 且永不回锚;scale-flip 不再重新武装 first-sight-mass(closes #455)** — fork host(PI_ACP_FORK_HOST=1)上内部 tokenCount 全程高于 provider 实测 1.5-2x:floors 是 raise-only(#257/#258)只能抬高不能拉低,#289 view-recount 用同一估计器重测也治不了估计器内部的幻影质量(物理上限坐实:请求全部成功、provider 峰值 109392 < 128K 窗口、首轮估计 161790 > 128K ⇒ 必有 ≥34K 幻影从未上线)。三处修复:① **校准锚定**——接口实测新鲜(锚点晚于最近一次成功压缩)且稳定(近 4 轮样本 ≥3 个且 (max−min)/min ≤ 25%,拒绝 #452 式 ±15K 抖动成为移动上限)时,估计封顶 ⌈实测×1.2⌉(等价 density 缩放,保留发送前预估能力);陈旧/抖动回退裸估计。② **scale-flip 重锚定**——原 #267 清零式重置在每次 stale↔fresh flip 都重新武装内核的一次性 first-sight-mass 旁路(需 lastNudgeShownTokens===0 && baseline===0),而每个压缩周期发生两次 flip,锯齿会话因此永久 emergency nudge(#452 日志 20 分钟内 `[first-sight mass]` 触发 7 次、每次紧跟 flip)。现改为把既有引用重锚到当前 tokenCount(growth 增量归零、cadence 基线不失义、旁路保持已消费);真冷启动的一次性语义不变。③ **分歧告警**——新鲜锚点下 |est−real|/real > 0.5 连续 3 轮 → 每 episode 一条 warn(`event=size-divergence`,含 est/host/ratio/stable 字段);校准生效时自然停发,校准因陈旧/抖动无法生效时让状态可见而非静默。实现:`src/runtime.ts`(`noteHostUsage`/`dropHostUsageSamples`/`noteSizeDivergence`/`dropSizeDivergence`)、`src/index.ts`(calibrate + applyFloors、divergence watch、scale-flip-reanchor、session_start/session_shutdown 清理);测试 `tests/size-accounting.test.ts` 3 例(冷启动/stale-flip/fresh-flip-back 全程 mass 后缀恰好一次 / 稳定新鲜锚点封顶实测×1.2 且陈旧锚点脱钩 / 抖动拒绝校准且 >2x 持续只告警一次)
- **feat(delegate): 检测到项目级第三方 subagent(pi-subagents)时自动停用 acp_delegate + delegate.forceEnable 强制开启(closes #415)** — 两套子代理系统并存各有 fleet 检查器与 spawn 路径,功能重叠、易混淆(#412 的 ctrl+alt+f 快捷键冲突即其表象之一),且 pi-subagents 的子代理默认拿不到 ACP 上下文压缩却无任何提示。现在 session_start 用既有检测逻辑按作用域区分:**项目级**安装(`<cwd>/.pi/npm` 或项目内 extensions)命中且未强制开启时跳过 acp_delegate 的工具/快捷键/系统提示注册(与 proxy-detect 相同的 stand-down 模式),打结构化日志 `delegate-auto-disabled`(含命中的安装路径)并按进程一次打印醒目提醒(TUI notify / headless console.error):说明需运行 `/acp-subagents` 把 compress/decompress/search_context/acp_status 注入 pi-subagents 的 agent overrides;**仅用户级**(全局)安装时只记 `delegate-user-scope-detected` 警告日志、不停用——避免一次全局安装让所有项目都失去 acp_delegate。新增配置 `delegate.forceEnable`(boolean,默认 false,env `PI_ACP_DELEGATE_FORCE_ENABLE` 覆盖,坏值回退配置值并告警)强制保留 acp_delegate;优先级矩阵:显式 `enabled: false` 永远赢 > `forceEnable: true` 无视检测结果 > 否则按项目级检测结果决定。v1 只认 pi-subagents 包名(泛化到任意第三方 subagent 需要宿主 ExtensionAPI 暴露已加载扩展枚举能力,列为后续)。实现:`src/config.ts`(forceEnable + resolveForceEnable)、`src/setup-subagent-tools.ts`(`findPiSubagentsInstalls` 作用域拆分,原 `findPiSubagentsInstall` 优先级语义不变)、`src/runtime.ts`(delegateStoodDown)、`src/index.ts`(session_start 检测门控 + wireSystemPrompt 门控);测试 `tests/config.test.ts`(+5:默认值 / env 优先 / 坏值回退 / 显式关赢过 forceEnable)+ `tests/integration.test.ts`(+5:项目级 stand-down / 仅用户级保持启用 / forceEnable 保留 / 显式关赢过 forceEnable / 无检测回归);文档 README(+zh-CN) install 段 + CONFIGURATION(+zh-CN) `delegate.forceEnable` 节与 env 表
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,9 @@ billion-context-pi writes a structured, always-on log to `~/.pi/acp.log` (overri
- **Always written** (even with `debug: false`): `error`, `warn`, `info` levels — session start, every context turn (token usage / nudge decision), compress/decompress, delegate spawn/done, and **all errors and warnings** (config/state/tool failures, delegate errors, guardrail caps, update failures). Error lines include the message and stack trace.
- **Written only when `debug: true`**: verbose `debug`-level diagnostics (full field dumps, per-turn internals).

Each line: `<ISO timestamp> [<level>] [<scope>] key=value key=value`. The file rotates to `~/.pi/acp.log.old` at 10 MB.
- **Nudge audit trail**: whenever a context-limit nudge is injected, a compact one-line record (e.g. `[ACP nudge] EMERGENCY 95% · T1 · top range m00120–m00168`) is appended as a *display-only* session entry — it survives process restarts, shows up in TUI scrollback and the session file, and is never sent to the model.

Each line: `<ISO timestamp> [<level>] [<scope>] key=value key=value`. Multi-line values (e.g. the full nudge text in `nudge-injected`) are escaped (`\n` → literal `\\n`), so every entry occupies exactly **one physical line** and stays self-contained for `grep`. The file rotates to `~/.pi/acp.log.old` at 10 MB.

```sh
tail -f ~/.pi/acp.log # watch the session live
Expand Down
3 changes: 2 additions & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,9 @@ billion-context-pi 会向 `~/.pi/acp.log`(可用 `ACP_LOG_FILE` 覆盖)写入结
- `warn` — 值得注意的非致命情况:紧急 nudge 注入、配置加载失败、自动更新网络错误、工具输出被截断、委派结果注入被跳过。
- `info` — 生命周期事件:会话启动、每轮上下文变换摘要(消息数/token/压缩比/活跃块数)、压缩/解压、delegate 派发与完成、自动更新检查。
- `debug` —— 仅在 `debug: true` 时额外写入(细粒度的字段级事件)。
- **Nudge 审计轨迹** — 无论何时注入上下文限制 nudge,一条紧凑的单行记录(如 `[ACP nudge] EMERGENCY 95% · T1 · top range m00120–m00168`)会作为*仅供显示*的会话条目写入——它跨进程重启存活,在 TUI 回滚历史和会话文件中可见,且永远不会发给模型。

每行格式:`<ISO 时间戳> [<级别>] [<范围>] key=value key=value`。文件达到 10 MB 时轮转为 `~/.pi/acp.log.old`。
每行格式:`<ISO 时间戳> [<级别>] [<范围>] key=value key=value`。多行字段值(如 `nudge-injected` 中的完整 nudge 正文)会被转义(`\n` → 字面量 `\\n`),保证每条日志恰好占**一行物理行**,便于 `grep`。文件达到 10 MB 时轮转为 `~/.pi/acp.log.old`。

```bash
tail -f ~/.pi/acp.log # 实时观察会话
Expand Down
43 changes: 41 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
} from "@earendil-works/pi-coding-agent";
import { CONFIG_DIR_NAME } from "./config-dir.js";
import { parseAcpJson } from "./user-config.js";
import type { KeyId } from "@earendil-works/pi-tui";
import { Box, Text, type KeyId } from "@earendil-works/pi-tui";
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
Expand All @@ -23,7 +23,7 @@ import { makeDelegateTool, makeDelegateWaitTool, makeDelegateCancelTool, running
import { makeCommands } from "./commands.js";
import { mergeSurface, readToolSurfaceWithPacks, resolveActivePack, resolvePackName, surfaceMetaOf } from "./prompt-pack.js";
import type { NudgeSectionsConfig } from "./surface.js";
import { coreOutToAgentMessages, extractText } from "./messages.js";
import { coreOutToAgentMessages, extractText, ACP_NUDGE_CUSTOM_TYPE, type AcpNudgeRecord } from "./messages.js";
import { liveOnlyTail } from "./live-only-tail.js";
import { carryHostSystemMessages } from "./system-passthrough.js";
import { sanitizeToolPairing } from "./tool-pair-sanitizer.js";
Expand Down Expand Up @@ -135,6 +135,7 @@ export function createAcpExtension(adapter: AdapterConfig = {}): ExtensionFactor
for (const { name, options } of makeCommands(runtime, pi)) {
pi.registerCommand(name, options);
}
wireNudgeRecords(pi);
};
}

Expand Down Expand Up @@ -761,6 +762,19 @@ function wireContextTransform(pi: ExtensionAPI, runtime: AcpRuntime, standDownIf
}
if (!emergency) runtime.markNudgeShown(sid, turnKey, tokenCount);
debug.event("nudge-injected", { sid: ctx.sessionManager.getSessionId(), voice: rendered.voice, channels: ["context", debugOn ? "terminal" : null].filter(Boolean), emergency, turnKey, reInject: shownAt !== undefined, text: rendered.text + example });
// issue #326: persist a compact display-only record so the injection
// survives restarts (TUI scrollback + session file). One per user turn:
// emergency nudges re-inject on every LLM call and must not flood the
// session file; type:"custom" entries are never projected into the
// sent view, so model context stays clean.
if (typeof pi.appendEntry === "function" && !runtime.nudgeRecordedFor(sid, turnKey)) {
try {
pi.appendEntry(ACP_NUDGE_CUSTOM_TYPE, { text: formatNudgeRecord(turn.nudge, emergency) });
runtime.markNudgeRecorded(sid, turnKey);
} catch (e) {
logWarn("nudge", { sid: ctx.sessionManager.getSessionId(), event: "persist-failed", error: e instanceof Error ? e.message : String(e) });
}
}
} else {
debug.event("nudge-suppressed", { sid: ctx.sessionManager.getSessionId(), turnKey, reason: turn.nudge.reason, shownAt: shownAt ?? null, tokenCount, adaptiveGrowth, reInjectFloor });
}
Expand Down Expand Up @@ -1050,3 +1064,28 @@ function nudgeMessage(nudge: NudgeDecision, blocks: CompressionBlock[], prompts:
timestamp: Date.now(),
} as AgentMessage;
}

// issue #326: render persisted nudge records in the TUI. Without a registered
// renderer pi silently drops custom entries on both live append and session
// rebuild, so this is required for the records to be visible at all.
function wireNudgeRecords(pi: ExtensionAPI): void {
if (typeof pi.registerEntryRenderer !== "function") return;
pi.registerEntryRenderer<AcpNudgeRecord>(ACP_NUDGE_CUSTOM_TYPE, (entry, _options, theme) => {
const text = entry.data?.text;
if (!text) return undefined;
const box = new Box(1, 1, (t: string) => theme.bg("customMessageBg", t));
box.addChild(new Text(theme.fg("dim", text), 0, 0));
return box;
});
}

// Compact one-line twin of nudgeMessage() for the persisted session entry
// (issue #326): auditability only — the full multi-line nudge deliberately
// stays out of the session file.
export function formatNudgeRecord(nudge: NudgeDecision, emergency: boolean): string {
const pct = Math.round(nudge.contextUsage * 100);
const tier = `T${nudge.tier ?? 1}`;
const top = [...nudge.compressibleRanges].sort((a, b) => b.tokens - a.tokens)[0];
const range = top ? ` · top range ${top.startRef}–${top.endRef}` : "";
return `[ACP nudge]${emergency ? " EMERGENCY" : ""} ${pct}% · ${tier}${range}`;
}
13 changes: 10 additions & 3 deletions src/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,20 @@ function debugOn(): boolean {
return runtimeDebug ?? ENV_DEBUG;
}

// One physical line per entry (issue #326): multi-line field values (nudge
// text, error stacks) must not spill onto untagged lines or grep of an event
// name stops at the headline. JSON.stringify already escapes control chars.
function escapeLine(s: string): string {
return s.replace(/\r/g, "\\r").replace(/\n/g, "\\n");
}

function fmt(v: unknown): string {
if (typeof v === "string") return v;
if (v instanceof Error) return v.stack || String(v);
if (typeof v === "string") return escapeLine(v);
if (v instanceof Error) return escapeLine(v.stack || String(v));
try {
return JSON.stringify(v);
} catch {
return String(v);
return escapeLine(String(v));
}
}

Expand Down
8 changes: 8 additions & 0 deletions src/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ export const ACP_STATUS_CUSTOM_TYPE = "acp-status";
* persistent in the session but never projected into LLM context (#255). */
export const ACP_EXPORT_CUSTOM_TYPE = "acp-export";

/** Nudge persistence record (issue #326): written via pi.appendEntry as a
* type:"custom" entry — never projected into the sent view (see above), so
* the compact one-liner stays out of model context while surviving restarts. */
export const ACP_NUDGE_CUSTOM_TYPE = "acp-nudge";
export interface AcpNudgeRecord {
text: string;
}

/** Custom-message types excluded from LLM-context projection (#255, #380):
* UI-only panels/docs that persist in the session but must not reach the model.
* Shared by isCustomMessageEntry below and the turn-boundary predicate in
Expand Down
17 changes: 16 additions & 1 deletion src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ export interface AcpRuntime {
nudgeShownTokensFor(sid: string, turnKey: string): number | undefined;
/** Clears the token-count stamps recorded by markNudgeShown — used on a token-scale flip (issue #267) so the same-turn re-inject floor (#269 / PR #316) is not computed against an old-scale stamp. */
clearNudgeTokenStamps(sid: string): void;
/** Like the nudgeShown* pair but tracks the persisted display-only session
* entry (issue #326): at most one record per user turn even when the
* emergency nudge re-injects on every LLM call. */
markNudgeRecorded(sid: string, turnKey: string): void;
nudgeRecordedFor(sid: string, turnKey: string): boolean;
/** Process compress toolResults for the CURRENT user turn only (the caller
* scopes the list — see collectCompressOutcomes in src/index.ts); idempotent
* per toolCallId. turnKey MUST be the stable persisted-boundary key
Expand Down Expand Up @@ -376,10 +381,20 @@ export function createRuntime(adapter: AdapterConfig): AcpRuntime {
function clearNudgeTracking(sid: string): void {
nudgeShownTurns.delete(sid);
nudgeShownTokens.delete(sid);
nudgeRecordedTurns.delete(sid);
}
function clearNudgeTokenStamps(sid: string): void {
nudgeShownTokens.delete(sid);
}
const nudgeRecordedTurns = new Map<string, Set<string>>();
function markNudgeRecorded(sid: string, turnKey: string): void {
let turns = nudgeRecordedTurns.get(sid);
if (!turns) { turns = new Set(); nudgeRecordedTurns.set(sid, turns); }
turns.add(turnKey);
}
function nudgeRecordedFor(sid: string, turnKey: string): boolean {
return nudgeRecordedTurns.get(sid)?.has(turnKey) ?? false;
}
// Per-session overflow self-heal state (learned window + armed emergency).
const overflowEpisodes = new Map<string, OverflowEpisode>();
function overflowFor(sid: string): OverflowEpisode {
Expand Down Expand Up @@ -727,4 +742,4 @@ export function createRuntime(adapter: AdapterConfig): AcpRuntime {
let refused = false;
let refusalMessage: string | null = null;
let delegateStoodDown = false;
return { core, store, get refused() { return refused; }, set refused(v: boolean) { refused = v; }, get refusalMessage() { return refusalMessage; }, set refusalMessage(v: string | null) { refusalMessage = v; }, get delegateStoodDown() { return delegateStoodDown; }, set delegateStoodDown(v: boolean) { delegateStoodDown = v; }, get adapter() { return adapterRef; }, setAdapter: (a) => { adapterRef = a; }, get prompts() { return promptsRef; }, setPrompts: (p) => { promptsRef = p; }, markNudgeShown, nudgeShownFor, nudgeShownTokensFor, clearNudgeTracking, clearNudgeTokenStamps, noteCompressOutcomes, compressRetryCappedFor, clearCompressRetryTracking, liveContextLimit, configFor, reasoningDropFor, reloadConfig, stateFor, save, deriveChildState: deriveChild, acquireLock, overflowFor, overflowDrop, noteDeadCompress, clearDeadCompress, throttleFor, throttleDrop , noteTokenScale, dropTokenScale, noteHostUsage, dropHostUsageSamples, noteSizeDivergence, dropSizeDivergence, noteTerminalEscape, dropTerminalEscape, noteTruncationSkipped, dropTruncationSkipped, stripImagesFor };}
return { core, store, get refused() { return refused; }, set refused(v: boolean) { refused = v; }, get refusalMessage() { return refusalMessage; }, set refusalMessage(v: string | null) { refusalMessage = v; }, get delegateStoodDown() { return delegateStoodDown; }, set delegateStoodDown(v: boolean) { delegateStoodDown = v; }, get adapter() { return adapterRef; }, setAdapter: (a) => { adapterRef = a; }, get prompts() { return promptsRef; }, setPrompts: (p) => { promptsRef = p; }, markNudgeShown, nudgeShownFor, nudgeShownTokensFor, clearNudgeTracking, clearNudgeTokenStamps, markNudgeRecorded, nudgeRecordedFor, noteCompressOutcomes, compressRetryCappedFor, clearCompressRetryTracking, liveContextLimit, configFor, reasoningDropFor, reloadConfig, stateFor, save, deriveChildState: deriveChild, acquireLock, overflowFor, overflowDrop, noteDeadCompress, clearDeadCompress, throttleFor, throttleDrop , noteTokenScale, dropTokenScale, noteHostUsage, dropHostUsageSamples, noteSizeDivergence, dropSizeDivergence, noteTerminalEscape, dropTerminalEscape, noteTruncationSkipped, dropTruncationSkipped, stripImagesFor };}
Loading
Loading