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
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,14 @@ Pick by your client:
| **omp** | [`billion-context`](https://github.com/ranxianglei/billion-context) via `bili omp` (built-in plugin) |
| **everything else** (no context hook) | [`billion-context`](https://github.com/ranxianglei/billion-context) — `bili <client>` (launcher, preferred) or `/bili/` prefix |

**Native mode vs standalone extensions.** The host-native plugins (`bili plugin install pi` / `opencode` — they spawn the proxy inside the host process) and the standalone in-process extensions (`billion-context-pi`, `opencode-acp`) are **mutually exclusive**: both active means double compression. The installer makes the switch (`bili plugin install pi` replaces the legacy `npm:billion-context-pi` entry). As a runtime safety net for manual installs, the native entries set `BILLION_CONTEXT_NATIVE=<host>` synchronously at load so a standalone extension can stand down at action time — its own load-time `BILLION_CONTEXT_PROXY` check cannot see a proxy that native mode spawns asynchronously, and its `/bili/` baseUrl check never sees the fetch-layer rewrite.
**Native mode vs standalone extensions.** The host-native plugins (`bili plugin install pi` / `opencode` — they spawn the proxy inside the host process) and the standalone in-process extensions (`billion-context-pi`, `opencode-acp`) are **mutually exclusive**: both active means double compression. The installer makes the switch: `bili plugin install pi` replaces the legacy `npm:billion-context-pi` entry, and `bili plugin install opencode` strips legacy `opencode-acp` entries from the global opencode.json — bare name, `npm:` alias, versioned (`opencode-acp@stable`), or path form, array or object shape; the original config is snapshotted to `opencode.json.bili-bak`. A **project-local** install (`opencode plugin opencode-acp` writes `<project>/.opencode/opencode.json`, not the global config) is not touched — remove it by hand; the installer note reminds you. As a runtime safety net for manual installs, the native entries set `BILLION_CONTEXT_NATIVE=<host>` synchronously at load so a standalone extension can stand down at action time — its own load-time `BILLION_CONTEXT_PROXY` check cannot see a proxy that native mode spawns asynchronously, and its `/bili/` baseUrl check never sees the fetch-layer rewrite.

**Legacy sessions from opencode-acp (v1 lane routing).** On OpenCode 1.x, `bili plugin install opencode` keeps pre-migration sessions WORKING: the native entry absorbs the installed `opencode-acp` package (imported directly from `node_modules` — `.opencode/node_modules`, project `node_modules`, global npm root, or opencode's config-scope modules, first hit wins) and routes per session. A session is legacy iff opencode-acp's persisted state file exists (`<XDG_DATA_HOME>/opencode/storage/plugin/acp/<sessionID>.json`):

- **Legacy session** — compression runs through the absorbed opencode-acp (its own `<dcp-message-id>` refs and block store keep working: `compress` / `decompress` / `search_context` / `acp_status` / `acp_context_recap` all execute in it). Its model requests carry `x-bili-plugin-bypass: 1`, and the proxy forwards them VERBATIM — no wire injection, no nudge, no session binding.
- **New session** — bili owns it: tool calls forward to the proxy's plugin endpoints (plugin mode). The tool slots the model sees carry the DCP schemas (one def per name process-wide on v1), but the executor routes by session lane, so a new session's `compress` reaches the proxy while a legacy session's reaches opencode-acp. `acp_context_recap` has no proxy counterpart — on new sessions the proxy answers it with its unknown-tool message.

`/acp` and `/dcp` route the same way. Adoption of new sessions into opencode-acp's registry is prevented by gating its transforms (system / messages / text.complete) on the legacy predicate. Degradation: when the opencode-acp package is absent or fails to import, bili runs alone and legacy sessions behave as read-only archives (old `<acp>` tags render, `decompress` returns `[Block … not found]`, new refs restart from m00001).

## Install

Expand Down
9 changes: 8 additions & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,14 @@ AI 编程助手的<strong>通用上下文压缩代理</strong>
| **omp** | [`billion-context`](https://github.com/ranxianglei/billion-context),`bili omp`(内置插件) |
| **其余所有**(没有上下文 hook) | [`billion-context`](https://github.com/ranxianglei/billion-context) —— `bili <client>`(启动器,优先)或 `/bili/` 前缀 |

**原生模式 vs 独立扩展。** 宿主原生插件(`bili plugin install pi` / `opencode` —— 代理在宿主进程内拉起)与独立进程内扩展(`billion-context-pi`、`opencode-acp`)**互斥**:两者同时生效意味着双重压缩。安装器负责切换(`bili plugin install pi` 会替换旧的 `npm:billion-context-pi` 条目);作为手动安装的运行期安全网,原生入口在加载时同步设置 `BILLION_CONTEXT_NATIVE=<host>`,让独立扩展在动作时自动退出 —— 它自己的加载期 `BILLION_CONTEXT_PROXY` 检查看不见原生模式异步拉起的代理,`/bili/` baseURL 检查也看不见 fetch 层改写。
**原生模式 vs 独立扩展。** 宿主原生插件(`bili plugin install pi` / `opencode` —— 代理在宿主进程内拉起)与独立进程内扩展(`billion-context-pi`、`opencode-acp`)**互斥**:两者同时生效意味着双重压缩。安装器负责切换:`bili plugin install pi` 会替换旧的 `npm:billion-context-pi` 条目;`bili plugin install opencode` 会从全局 opencode.json 里剔除旧的 `opencode-acp` 条目 —— 裸名、`npm:` 别名、带版本号(`opencode-acp@stable`)、路径形式都认,数组/对象两种形态都处理;原配置会快照到 `opencode.json.bili-bak`。**项目级**安装(`opencode plugin opencode-acp` 写的是 `<project>/.opencode/opencode.json`,不是全局配置)不会被碰 —— 需手动移除,安装器输出里会提醒。作为手动安装的运行期安全网,原生入口在加载时同步设置 `BILLION_CONTEXT_NATIVE=<host>`,让独立扩展在动作时自动退出 —— 它自己的加载期 `BILLION_CONTEXT_PROXY` 检查看不见原生模式异步拉起的代理,`/bili/` baseURL 检查也看不见 fetch 层改写。

**从 opencode-acp 迁移旧会话(v1 泳道路由)。** 在 OpenCode 1.x 上,`bili plugin install opencode` 让迁移前的旧会话继续可用:原生入口会吸收已安装的 `opencode-acp` 包(直接从 `node_modules` 导入 —— `.opencode/node_modules`、项目 `node_modules`、全局 npm root、opencode 配置级 modules,先到先得),并按会话路由。会话属于 legacy ⟺ opencode-acp 的持久化状态文件存在(`<XDG_DATA_HOME>/opencode/storage/plugin/acp/<sessionID>.json`):

- **旧会话** —— 压缩由被吸收的 opencode-acp 执行(它自己的 `<dcp-message-id>` 引用号与块存储照常工作:`compress` / `decompress` / `search_context` / `acp_status` / `acp_context_recap` 全部在它里面执行)。其模型请求带 `x-bili-plugin-bypass: 1`,代理原样转发 —— 不注入 wire 工具、不注 nudge、不绑定会话。
- **新会话** —— bili 接管:工具调用转发到代理的 plugin 端点(plugin 模式)。模型看到的工具槽位带 DCP schema(v1 进程级每个名字仅一份定义),但执行器按会话分泳道:新会话的 `compress` 发到代理,旧会话的发给 opencode-acp。`acp_context_recap` 没有代理端对应 —— 新会话调用会收到代理的 unknown-tool 消息。

`/acp` 与 `/dcp` 同样路由。新会话被 opencode-acp 注册表收编的可能被其 transform 门控(system / messages / text.complete 都过 legacy 谓词)阻断。退化路径:opencode-acp 包缺失或导入失败时 bili 单独运行,旧会话退化为只读存档(旧 `<acp>` 标签照常渲染、`decompress` 返回 `[Block … not found]`、新引用号从 m00001 重新开始)。

## 安装

Expand Down
176 changes: 176 additions & 0 deletions src/agent/opencode-legacy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
// opencode-acp absorption for LEGACY V1 sessions (#920).
//
// Users migrating from the standalone `opencode-acp` extension (DCP protocol,
// its own ref space + block store) to `bili plugin install opencode` still
// need their OLD sessions to work: those sessions' history is annotated with
// `<dcp-message-id>` tags and their refs live in acp's store — bili's kernel
// cannot serve them. Routing requirement: legacy sessions keep running
// through opencode-acp, new sessions go through bili.
//
// Probed facts (opencode-acp 1.18.x, ~/projects/opencode-acp):
// - package exports ONLY `default server` (index.ts); `server(ctx)` returns
// `{}` immediately when BILLION_CONTEXT_PROXY is set — the env is checked
// ONLY there (index.ts:38); executors never re-check it, so calling
// `server(ctx)` with the env temporarily unset yields the armed hooks.
// - its `config` hook self-disables the whole plugin when any provider
// baseURL contains `/bili/` (findBiliProxyProviders) AND denies the tools
// via permission.deny — so we call it with `provider` hidden and merge
// back only the keys it legitimately owns (permission / command /
// experimental.primary_tools / agent snapshot side effects).
// - adoption of NEW sessions happens in messages.transform via
// registry.getOrCreate(lastUserMessage.info.sessionID) — gating that hook
// (and system.transform / text.complete) on legacy state keeps new
// sessions out of acp's registry entirely.
// - legacy session marker: acp's persisted state file at
// `<XDG_DATA_HOME|~/.local/share>/opencode/storage/plugin/acp/<sid>.json`
// (getDefaultStorageDir, lib/state/persistence.ts:67). config storagePath
// overrides are NOT probed (documented limitation).
// - tool args are kernel-compatible: compress `content:
// [{topic,startId,endId,summary}]` is the kernel's accepted object form
// (verified: parseCompressArgs maps startId/endId → ranges[].startRef/
// endRef), decompress/search_context/acp_status args match the kernel
// shapes — so NEW-session calls can be forwarded to the proxy verbatim
// with zero translation. `acp_context_recap` has no proxy counterpart
// (rejected by /__bili/plugin/tool) — legacy-only, documented.
// - the v1 host loads tool defs from the hooks table statically; ONE def
// per name process-wide. The slots therefore carry acp's DCP schemas for
// everyone, and the WRAPPED executors route per session: legacy → acp
// executor, new → forwardTool to the proxy (plugin-mode carrier).
//
// Degradation: package not found / import fails / unexpected shape → the
// caller falls back to bili's own V1 tools (current behavior); legacy
// sessions then degrade as documented (read-only archives).

import { existsSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";

export interface LegacyAcpToolDef {
description?: unknown;
args?: unknown;
execute?: (args: Record<string, unknown>, ctx: { sessionID: string; messageID?: string }) => Promise<unknown>;
}

export interface LegacyAcpModule {
/** acp's full hooks table (config/tool/hooks keys as returned by server()). */
hooks: Record<string, unknown>;
/** hooks.tool — the DCP tool slots (compress/decompress/search_context/acp_status/acp_context_recap). */
tools: Record<string, LegacyAcpToolDef>;
/** hooks.config — must be called with `provider` hidden (self-disable neutered). */
configHook: ((cfg: Record<string, unknown>) => Promise<void>) | undefined;
/** hooks["command.execute.before"] — /acp + /dcp handler for legacy sessions. */
commandHook: ((input: { command: string; sessionID: string; arguments?: string }, output?: { parts?: unknown[] }) => Promise<void>) | undefined;
/** resolved dist/index.js path (for logs). */
source: string;
}

/** Candidate `opencode-acp/dist/index.js` paths, most specific first:
* project plugin scope, plain project node_modules, opencode's v1 package
* cache (`opencode plugin opencode-acp` — global AND project installs land
* in `~/.cache/opencode/packages/opencode-acp@<ver>/node_modules`; every
* version present is offered, newest first), global user npm root, and
* opencode's config-scope node_modules. */
export function legacyAcpCandidates(cwd: string | undefined): string[] {
const dirs: string[] = [];
if (cwd !== undefined && cwd.length > 0) {
dirs.push(path.join(cwd, ".opencode", "node_modules"));
dirs.push(path.join(cwd, "node_modules"));
}
const out: string[] = [];
const pushDir = (d: string): void => {
out.push(path.join(d, "opencode-acp", "dist", "index.js"));
};
for (const d of dirs) pushDir(d);
const cacheHome = process.env.XDG_CACHE_HOME ?? path.join(homedir(), ".cache");
const packages = path.join(cacheHome, "opencode", "packages");
try {
const versions = readdirSync(packages)
.filter((e) => e.startsWith("opencode-acp@"))
.sort()
.reverse();
for (const v of versions) {
pushDir(path.join(packages, v, "node_modules"));
}
} catch {
// no package cache
}
pushDir(path.join(homedir(), ".local", "lib", "node_modules"));
pushDir(path.join(process.env.XDG_CONFIG_HOME ?? path.join(homedir(), ".config"), "opencode", "node_modules"));
return out;
}

/** acp's default persisted-state location for a session id. */
export function legacyAcpStatePath(sessionId: string): string {
const dataHome = process.env.XDG_DATA_HOME ?? path.join(homedir(), ".local", "share");
return path.join(dataHome, "opencode", "storage", "plugin", "acp", `${sessionId}.json`);
}

/** A session is legacy iff acp has a state file for it. Ids are sanitized
* (no separators, bounded length) before touching the filesystem. */
export function isLegacyAcpSession(sessionId: string | undefined): boolean {
if (sessionId === undefined || sessionId.length === 0 || sessionId.length > 200) return false;
if (/[/\\\s]/.test(sessionId)) return false;
try {
return existsSync(legacyAcpStatePath(sessionId));
} catch {
return false;
}
}

export async function loadLegacyAcp(ctx: { directory?: string; client?: unknown }, log: (msg: string) => void = () => {}): Promise<LegacyAcpModule | undefined> {
let found: string | undefined;
for (const p of legacyAcpCandidates(ctx.directory)) {
if (existsSync(p)) {
found = p;
break;
}
}
if (found === undefined) return undefined;
// acp's server() refuses to arm when BILLION_CONTEXT_PROXY is set; the
// check runs only at entry, so it is unset strictly around the call and
// restored in finally. Concurrent readers on this event loop see either
// value only across our own awaits here.
const prev = process.env.BILLION_CONTEXT_PROXY;
try {
if (prev !== undefined) delete process.env.BILLION_CONTEXT_PROXY;
const mod = (await import(pathToFileURL(found).href)) as { default?: unknown };
const server = mod.default;
if (typeof server !== "function") {
log(`[bili-opencode-native] legacy: ${found} exports no server function — ignored`);
return undefined;
}
const hooks = (await (server as (c: unknown) => Promise<Record<string, unknown>>)(ctx)) ?? {};
if (typeof hooks !== "object") return undefined;
const toolsRaw = hooks.tool;
const tools = toolsRaw !== null && typeof toolsRaw === "object" && !Array.isArray(toolsRaw) ? (toolsRaw as Record<string, LegacyAcpToolDef>) : {};
if (Object.keys(tools).length === 0) {
log(`[bili-opencode-native] legacy: ${found} armed but registered no tools (acp disabled by its own config?) — ignored`);
return undefined;
}
const configHook = typeof hooks.config === "function" ? (hooks.config as LegacyAcpModule["configHook"]) : undefined;
const commandHook = typeof hooks["command.execute.before"] === "function" ? (hooks["command.execute.before"] as LegacyAcpModule["commandHook"]) : undefined;
log(`[bili-opencode-native] legacy opencode-acp absorbed from ${found} (tools: ${Object.keys(tools).join(", ")})`);
return { hooks, tools, configHook, commandHook, source: found };
} catch (err) {
log(`[bili-opencode-native] legacy: failed to load ${found}: ${String(err)} — legacy sessions degrade to read-only`);
return undefined;
} finally {
if (prev === undefined) delete process.env.BILLION_CONTEXT_PROXY;
else process.env.BILLION_CONTEXT_PROXY = prev;
}
}

/** Call acp's config hook without letting it see (and self-disable on) the
* /bili/-wrapped provider URLs, then merge back the top-level keys it may
* have replaced on the shadow copy (it writes via `??=`/spread-replace, so a
* reference change marks an owned write; in-place mutations already hit the
* real object). */
export async function callLegacyAcpConfig(configHook: NonNullable<LegacyAcpModule["configHook"]>, cfg: Record<string, unknown>): Promise<void> {
const shadow: Record<string, unknown> = { ...cfg };
delete shadow.provider;
await configHook(shadow);
for (const key of ["permission", "command", "experimental"] as const) {
if (shadow[key] !== cfg[key]) cfg[key] = shadow[key];
}
}
Loading
Loading