Skip to content
Merged
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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ The model decides <em>when</em> and <em>what</em> to compress — not a hard lim

---

> **Host support:** this plugin is for **Pi**. It does **not** support **OMP (oh-my-pi)** — on an OMP host it refuses to run. OMP users: use [billion-context](https://github.com/ranxianglei/billion-context) instead (`bili omp`). Details: [docs/omp.md](./docs/omp.md).

## Why?

When conversations get long, the model runs out of context. Most tools hard-truncate — silently dropping earlier messages. **billion-context** gives the model a `compress` tool: the LLM decides **when** and **what** to compress into high-fidelity summaries, preserving critical details (file paths, decisions, error strings) while reclaiming context space.
Expand Down Expand Up @@ -72,6 +74,22 @@ This has two practical implications:

2. **Even with a single compression plugin, interference is still possible in rare cases.** Load order under Pi is determined by filesystem discovery order (`fs.readdirSync` over `.pi/extensions/` → global → packages), which is not fully deterministic. If another (non-compression) extension also hooks the `context` event and happens to load *after* billion-context-pi, it could modify the compressed output. billion-context-pi rebuilds its working set from the session log rather than the chained input, which makes it robust to handlers that run *before* it — but it cannot defend against a handler that runs *after* it. This is a limitation of Pi's extension model; if you observe unexpected context behavior, check whether other installed extensions intercept the `context` event.

## Host support

billion-context-pi is built for the **Pi** coding agent (`@earendil-works/pi-coding-agent`) and detects the host at session start:

- **Pi** — fully supported.
- **OMP (`can1357/oh-my-pi`)** — **not supported.** OMP's in-process session API diverges from Pi's, so the compression refs the extension injects can drift out of sync with the session's real refs and `compress` calls fail with `does not exist in this session` (issue [#234](https://github.com/ranxianglei/billion-context-pi/issues/234)). On OMP the extension now **refuses service**: it prints a warning, disables the ACP tools, and leaves the host's own context handling untouched.

**Use [billion-context](https://github.com/ranxianglei/billion-context) instead** — it runs the same compression pipeline server-side in a proxy, so the refs never diverge:

```bash
npm install -g billion-context
bili omp # run OMP through the proxy
```

Full details: [docs/omp.md](./docs/omp.md).

## Model-facing tools

| Tool | What it does |
Expand Down
18 changes: 18 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

---

> **宿主支持:** 本插件面向 **Pi**。它**不支持 OMP(oh-my-pi)** —— 在 OMP 宿主上会拒绝运行。OMP 用户请改用 [billion-context](https://github.com/ranxianglei/billion-context)(`bili omp`)。详细说明:[docs/omp.zh-CN.md](./docs/omp.zh-CN.md)。

## 为什么选择 billion-context

当对话变长,模型的上下文会耗尽。多数工具采用硬截断 —— 静默丢弃早期消息。**billion-context** 把 `compress` 工具交给模型:由 LLM 决定**何时**压缩、压缩**什么**,将内容压缩成高保真摘要,在回收上下文空间的同时保留关键细节(文件路径、决策、错误字符串)。
Expand Down Expand Up @@ -71,6 +73,22 @@ billion-context 通过拦截 Pi 的 `context` 事件接管上下文管理。**Pi

2. **即使只有一个压缩插件,在少数情况下仍可能出现干扰。** Pi 下的加载顺序由文件系统发现顺序(`fs.readdirSync` 遍历 `.pi/extensions/` → 全局 → 包)决定,并不完全确定。如果另一个(非压缩类)扩展也 hook 了 `context` 事件、且恰好加载在 billion-context-pi *之后*,它可能修改压缩后的输出。billion-context-pi 从会话日志重建工作集(而非链式输入),这让它对*排在它之前*的 handler 鲁棒 —— 但无法防御*排在它之后*的 handler。这是 Pi 扩展模型的固有限制;若你观察到上下文行为异常,请检查是否有其他已安装扩展拦截了 `context` 事件。

## 宿主支持

billion-context-pi 面向 **Pi** 编码代理(`@earendil-works/pi-coding-agent`)构建,并在会话开始时检测宿主:

- **Pi** — 完全支持。
- **OMP(`can1357/oh-my-pi`)** — **不支持。** OMP 的进程内会话 API 与 Pi 不同,扩展注入的压缩引用可能与会话的真实引用漂移失步,导致 `compress` 调用失败,报错 `does not exist in this session`(issue [#234](https://github.com/ranxianglei/billion-context-pi/issues/234))。在 OMP 上,扩展现在会**拒绝服务**:打印警告、禁用 ACP 工具,并保持宿主自身的上下文处理不受影响。

**请改用 [billion-context](https://github.com/ranxianglei/billion-context)** — 它把同样的压缩流水线运行在服务端代理里,因此引用不会漂移:

```bash
npm install -g billion-context
bili omp # 让 OMP 通过代理运行
```

完整说明:[docs/omp.zh-CN.md](./docs/omp.zh-CN.md)。

## 模型工具

| 工具 | 作用 |
Expand Down
53 changes: 53 additions & 0 deletions docs/omp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
[English](./omp.md) | [中文](./omp.zh-CN.md)

# OMP (oh-my-pi) support

> **billion-context-pi does not support OMP.** If you run it on an OMP
> (`can1357/oh-my-pi`) host, the extension **refuses to run**: it prints a
> warning once, disables the ACP tools, and leaves the host's own context
> handling untouched. Use the [billion-context](https://github.com/ranxianglei/billion-context)
> proxy instead.

## Why OMP is not supported

billion-context-pi is an in-process adapter for the **Pi** coding agent
(`@earendil-works/pi-coding-agent`). It manages context by injecting invisible
message refs (`m00001`, `m00002`, …) into the live conversation and letting the
model drive `compress` / `decompress` / `search_context` against those refs.

OMP exposes a different in-process session API. The refs the extension injects
can drift out of sync with the session's real refs, so `compress` calls fail
with `does not exist in this session` and one-shot runs never succeed
([#234](https://github.com/ranxianglei/billion-context-pi/issues/234)). Keeping
that in-process integration reliable on OMP is not worth the maintenance cost,
so OMP is no longer an actively supported host for this plugin.

## What happens on an OMP host

At session start the extension feature-detects the host (Pi exposes
`sessionManager.buildContextEntries()`; OMP only exposes `getBranch()`). When it
detects OMP it stands down:

- warns **once per process** (UI notification in TUI/RPC; `console.error` to
stderr in headless one-shot mode) pointing at the supported alternative,
- the four ACP tools (`compress`, `decompress`, `search_context`, `acp_status`)
return the guidance message instead of acting,
- the ACP system-prompt injection is skipped,
- the `context` transform is a no-op (messages pass through untouched),
- the host's own auto-compaction is **not** cancelled.

Pi hosts are completely unaffected.

## The alternative: billion-context proxy

[billion-context](https://github.com/ranxianglei/billion-context) runs the same
compression pipeline **server-side in a proxy**. Because the proxy owns the ref
coordinate space, the refs never diverge — it works on OMP (and other hosts).

```bash
npm install -g billion-context
bili omp
```

`bili omp` starts a local proxy and launches OMP against it. See
[billion-context](https://github.com/ranxianglei/billion-context) for options.
50 changes: 50 additions & 0 deletions docs/omp.zh-CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
[English](./omp.md) | [中文](./omp.zh-CN.md)

# OMP(oh-my-pi)支持

> **billion-context-pi 不支持 OMP。** 在 OMP(`can1357/oh-my-pi`)宿主上运行时,
> 扩展会**拒绝服务**:打印一次警告、禁用 ACP 工具,并保持宿主自身的上下文处理
> 不受影响。请改用 [billion-context](https://github.com/ranxianglei/billion-context)
> 代理。

## 为什么不支持 OMP

billion-context-pi 是面向 **Pi** 编码代理(`@earendil-works/pi-coding-agent`)的
进程内适配器。它通过向实时对话注入不可见的消息引用(`m00001`、`m00002` …),
让模型基于这些引用驱动 `compress` / `decompress` / `search_context` 来管理上下文。

OMP 暴露的是另一套进程内会话 API。扩展注入的引用可能与会话的真实引用发生漂移,
导致 `compress` 调用失败,报错 `does not exist in this session`,一次性运行
(one-shot)永远无法成功
([#234](https://github.com/ranxianglei/billion-context-pi/issues/234))。在 OMP 上
维持这套进程内集成的可靠性并不划算,因此 OMP 不再是本插件主动支持的宿主。

## 在 OMP 宿主上会发生什么

会话开始时,扩展通过特性检测识别宿主(Pi 暴露
`sessionManager.buildContextEntries()`,OMP 只暴露 `getBranch()`)。检测到 OMP 时,
扩展会"让位":

- **每个进程只警告一次**(TUI/RPC 下用 UI 通知;headless 一次性模式下用
`console.error` 输出到 stderr),并指向受支持的替代方案;
- 四个 ACP 工具(`compress`、`decompress`、`search_context`、`acp_status`)
返回引导信息,而不执行实际操作;
- 跳过 ACP 系统提示注入;
- `context` 转换变为空操作(消息原样透传);
- **不**取消宿主自身的自动压缩。

Pi 宿主完全不受影响。

## 替代方案:billion-context 代理

[billion-context](https://github.com/ranxianglei/billion-context) 把同样的压缩
流水线**运行在服务端代理**里。由于代理持有引用坐标系,引用不会漂移 —— 因此它
在 OMP(以及其他宿主)上都能工作。

```bash
npm install -g billion-context
bili omp
```

`bili omp` 会启动一个本地代理,并让 OMP 通过它运行。更多选项见
[billion-context](https://github.com/ranxianglei/billion-context)。
2 changes: 2 additions & 0 deletions src/compress-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { debug, logError, logInfo, logThrow, logWarn } from "./log.js";
import { estimateTokens, collectCoveredMessageIds, collectImageTokens, modelSupportsImages } from "./tokens.js";
import { defaultCountTokens, parseCompressArgs, type CompressionBlock, type CompressParseDiagnostics } from "acp-kernel";
import { getSystemPromptText } from "./compat.js";
import { OMP_UNSUPPORTED_MESSAGE } from "./omp.js";

function formatK(n: number): string {
return n >= 1000 ? `${(n / 1000).toFixed(1)}K` : String(n);
Expand Down Expand Up @@ -53,6 +54,7 @@ export function makeCompressTool(runtime: AcpRuntime): ToolDefinition<typeof Com
],
parameters: CompressParams,
async execute(toolCallId, params, _signal, _onUpdate, ctx): Promise<AgentToolResult<unknown>> {
if (runtime.refused) return { details: undefined, content: [{ type: "text", text: OMP_UNSUPPORTED_MESSAGE }] };
let result: string;
try {
result = await handleCompress(params as CompressArgs, runtime, ctx, toolCallId);
Expand Down
2 changes: 2 additions & 0 deletions src/decompress-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { AcpRuntime } from "./runtime.js";
import { debug, logError, logInfo, logThrow } from "./log.js";
import { parseBlockIdArg, collectBlockContent, type CompressionBlock } from "acp-kernel";
import { entriesToCoreMessages } from "./messages.js";
import { OMP_UNSUPPORTED_MESSAGE } from "./omp.js";
import { writeFile, mkdir } from "node:fs/promises";
import { existsSync, lstatSync, readlinkSync, realpathSync } from "node:fs";
import { resolve, relative, isAbsolute, join, basename, dirname } from "node:path";
Expand Down Expand Up @@ -45,6 +46,7 @@ export function makeDecompressTool(runtime: AcpRuntime): ToolDefinition<typeof D
],
parameters: DecompressParams,
async execute(_toolCallId, params, _signal, _onUpdate, ctx): Promise<AgentToolResult<unknown>> {
if (runtime.refused) return { details: undefined, content: [{ type: "text", text: OMP_UNSUPPORTED_MESSAGE }] };
let result: string;
try {
result = await handleDecompress(params as DecompressArgs, runtime, ctx);
Expand Down
38 changes: 34 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
import { defaultCountTokens } from "acp-kernel";
import { formatSystemPromptForEvent, getSystemPromptText } from "./compat.js";
import { inspectOverflowMessage, reserveOutputHeadroom, shouldReserveOutputHeadroom } from "./overflow-selfheal.js";
import { isOmpHost, OMP_UNSUPPORTED_MESSAGE } from "./omp.js";

type AgentMessage = SessionMessageEntry["message"];

Expand All @@ -46,7 +47,7 @@ export function createAcpExtension(adapter: AdapterConfig = {}): ExtensionFactor
return;
}
const runtime = createRuntime(adapter);
wireCompactionDisable(pi);
wireCompactionDisable(pi, runtime);
wireSessionLifecycle(pi, runtime);
wireContextTransform(pi, runtime);
wireSystemPrompt(pi, runtime);
Expand All @@ -66,17 +67,39 @@ export function createAcpExtension(adapter: AdapterConfig = {}): ExtensionFactor
export default createAcpExtension();

// ACP owns compression; cancel Pi's built-in auto-compaction entirely (mirrors
// opencode-acp requiring opencode's compaction.auto = false).
function wireCompactionDisable(pi: ExtensionAPI): void {
pi.on("session_before_compact", () => ({ cancel: true }));
// opencode-acp requiring opencode's compaction.auto = false). On a refused host
// (OMP) we stand down and let the host compact normally instead.
function wireCompactionDisable(pi: ExtensionAPI, runtime: AcpRuntime): void {
pi.on("session_before_compact", () => {
if (runtime.refused) return;
return { cancel: true };
});
}

// (acp_delegate injection is best-effort: sendUserMessage is fire-and-forget
// in pi, and interactive/rpc sessions are long-lived so their main loop
// consumes the follow-up queue naturally — no shutdown drain needed.)

function wireSessionLifecycle(pi: ExtensionAPI, runtime: AcpRuntime): void {
let ompWarned = false;
pi.on("session_start", async (_event, ctx) => {
// OMP (oh-my-pi) is not supported: its in-process live-entries integration
// diverges the nudge's example refs from the session's real refs, so
// compress calls fail with "does not exist in this session". Stand down —
// refuse service and point the user at the billion-context proxy. session_start
// always precedes the first context/before_agent_start event, so setting
// `refused` here reliably gates every downstream handler for the session.
if (isOmpHost(ctx.sessionManager)) {
runtime.refused = true;
if (!ompWarned) {
ompWarned = true;
const sid = ctx.sessionManager.getSessionId();
logWarn("host", { event: "omp-unsupported", sid, action: "refused" });
if (ctx.hasUI) ctx.ui.notify(OMP_UNSUPPORTED_MESSAGE, "warning");
else console.error(OMP_UNSUPPORTED_MESSAGE);
}
return;
}
runtime.store.invalidate();
runtime.clearNudgeTracking();
runtime.throttleFor(ctx.sessionManager.getSessionId()).reset();
Expand Down Expand Up @@ -131,6 +154,10 @@ function wireSessionLifecycle(pi: ExtensionAPI, runtime: AcpRuntime): void {
// nudge decision) and return the transformed AgentMessage[].
function wireContextTransform(pi: ExtensionAPI, runtime: AcpRuntime): void {
pi.on("context", async (event, ctx) => {
// Refused host (OMP): leave the context completely untouched — no ref tags,
// no compression, no nudge. Returning undefined makes pi send the original
// messages verbatim.
if (runtime.refused) return;
const sid = ctx.sessionManager.getSessionId();
const release = await runtime.acquireLock(sid);
try {
Expand Down Expand Up @@ -348,6 +375,9 @@ function wireContextTransform(pi: ExtensionAPI, runtime: AcpRuntime): void {

function wireSystemPrompt(pi: ExtensionAPI, runtime: AcpRuntime): void {
pi.on("before_agent_start", (event) => {
// Refused host (OMP): don't inject the ACP system prompt — the model must
// not learn about compress/decompress on a host where they can't work.
if (runtime.refused) return;
const delegate = runtime.adapter.delegate !== false;
const acp = buildAcpSystemPrompt(runtime.prompts);
const prompt = delegate ? `${acp}\n${ACP_DELEGATE_PROMPT}` : acp;
Expand Down
31 changes: 31 additions & 0 deletions src/omp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
import { isPiHost } from "./runtime.js";

/**
* Positive OMP (oh-my-pi) host detection.
*
* pi exposes `sessionManager.buildContextEntries()`; omp only exposes
* `getBranch()`. `isPiHost` feature-detects the former, so its negation is the
* established "omp path" used throughout the adapter (see runtime.stateFor).
* We reuse that semantic so the refusal and the (now dormant) best-effort omp
* path can never disagree about which host we are on.
*/
export function isOmpHost(sm: ExtensionContext["sessionManager"]): boolean {
return !isPiHost(sm);
}

/**
* Shown (and logged) when the extension detects an OMP host and stands down.
* OMP's in-process live-entries integration is unreliable: the nudge's example
* refs diverge from the session's real refs, so compress calls fail with
* "does not exist in this session". The billion-context proxy runs compression
* server-side (it owns the ref coordinate space) and works on OMP.
*/
export const OMP_UNSUPPORTED_MESSAGE = [
"[billion-context-pi] This host is OMP (oh-my-pi), which is NOT supported — ACP has been disabled for this session.",
"The in-process compression path is unreliable on OMP: the nudge's example refs diverge from the session's real refs, so compress calls fail with \"does not exist in this session\".",
"Use the billion-context proxy instead — it runs compression server-side and works on OMP:",
" npm install -g billion-context",
" bili omp",
"Docs: https://github.com/ranxianglei/billion-context",
].join("\n");
8 changes: 7 additions & 1 deletion src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ export function isPiHost(sm: ExtensionContext["sessionManager"]): boolean {

export interface AcpRuntime {
core: CompressionCore;
/** Set when the host is unsupported (currently: OMP / oh-my-pi). Once true,
* the extension stands down: the context transform, system-prompt injection,
* compaction-cancel and ACP tools all no-op so the host runs untouched.
* Set at session_start (see wireOmpRefusal in src/index.ts). */
refused: boolean;
/** Per-session provider-throttle retry episode (attempt budget + kick
* pacing), keyed by session id so concurrent sessions in one extension
* instance cannot share an episode. Reset on session_start and on any
Expand Down Expand Up @@ -378,4 +383,5 @@ export function createRuntime(adapter: AdapterConfig): AcpRuntime {
await store.save(state, sm.getSessionFile() ?? undefined, sm.getSessionId());
}

return { core, store, get adapter() { return adapterRef; }, setAdapter: (a) => { adapterRef = a; }, get prompts() { return promptsRef; }, setPrompts: (p) => { promptsRef = p; }, markNudgeShown: (k) => { nudgeShownTurns.add(k); }, nudgeShownFor: (k) => nudgeShownTurns.has(k), clearNudgeTracking: () => { nudgeShownTurns.clear(); }, noteCompressOutcomes, compressRetryCappedFor, clearCompressRetryTracking, liveContextLimit, configFor, reloadConfig, stateFor, save, acquireLock, overflowFor, overflowDrop, throttleFor, throttleDrop };}
let refused = false;
return { core, store, get refused() { return refused; }, set refused(v: boolean) { refused = v; }, get adapter() { return adapterRef; }, setAdapter: (a) => { adapterRef = a; }, get prompts() { return promptsRef; }, setPrompts: (p) => { promptsRef = p; }, markNudgeShown: (k) => { nudgeShownTurns.add(k); }, nudgeShownFor: (k) => nudgeShownTurns.has(k), clearNudgeTracking: () => { nudgeShownTurns.clear(); }, noteCompressOutcomes, compressRetryCappedFor, clearCompressRetryTracking, liveContextLimit, configFor, reloadConfig, stateFor, save, acquireLock, overflowFor, overflowDrop, throttleFor, throttleDrop };}
Loading
Loading