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
10 changes: 9 additions & 1 deletion CLIENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,8 @@ on `@opencode/cli` 2.0.3 (V1 lane: 1.14.46 and 1.18.31).
| Native (no launcher) | `bili plugin install opencode` | self-spawning plugin in your real config; start `opencode` as usual |
| Pure proxy (fallback) | baseURL `/bili/` prefix | no plugin — wire-level tool injection |

These paths are **mutually exclusive** — each one owns routing of the same requests, so exactly one may be active per host instance. A hand-written `/bili/` provider baseURL is the pure-proxy path's marker; writing it while the native plugin is installed is a **conflicting configuration** (#1958): `bili plugin install opencode` refuses (exit code 1, listing every offending file/provider/baseURL plus the fix-it guide), and at runtime the native route warns once per session with the same guide. The supported exception is an explicit pin of the **same** origin — `BILLION_CONTEXT_PROXY` pointing at the proxy the URLs already ride — which stays silent.

### Launcher — `bili opencode`

HTTPS rides cert-MITM, HTTP a temp `opencode.json` clone with `/bili/`
Expand Down Expand Up @@ -465,7 +467,9 @@ same native bili tools as launcher mode — no fixed port, no env var, no
launcher. Opt-out: `BILI_NATIVE_OPENCODE=0`. If no proxy can be made
healthy, requests go direct (uncompressed) with a one-time warning and
recover automatically. Under a `bili opencode` launch this entry is skipped
entirely (the launcher owns the proxy).
entirely (the launcher owns the proxy). Installing over a config that already
carries pre-routed `/bili/` provider baseURLs is refused — that config belongs
to the pure-proxy path (see above).

### Pure proxy (no plugin)

Expand All @@ -488,6 +492,10 @@ Point the provider baseURL at the proxy like any other client:
Note: 2.0 AI-SDK providers require an `apiKey` field even for local
endpoints that never check it — set any non-empty value.

This path means **no plugin**: if you also install the native plugin on top
of these URLs, the install refuses and the runtime warns once per session —
pick one path per provider (#1958).

### Status: `/acp` and `acp_status`

The `/acp` panel is session-bound in all modes, and the `acp_status` tool is
Expand Down
6 changes: 5 additions & 1 deletion CLIENTS.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ bili 只压缩路径匹配已知 wire 协议(`/chat/completions`、`/llm_raw_cha
| 原生(免启动器) | `bili plugin install opencode` | 自拉起插件写进真实配置;照常启动 `opencode` |
| 纯代理(兜底) | baseURL 加 `/bili/` 前缀 | 无插件 —— wire 级工具注入 |

这三条路径**互斥**——每条都拥有同一批请求的路由权,每个宿主实例只能激活其中一条。手写的 `/bili/` provider baseURL 是纯代理路径的标记;在原生插件已装的情况下写它就是**矛盾配置**(#1958):`bili plugin install opencode` 会拒绝(exit code 1,逐条列出命中的文件/provider/baseURL 与修复指引),运行时 native route 每会话警告一次,指引相同。受支持的例外是对**同一** origin 的显式钉住——`BILLION_CONTEXT_PROXY` 指向 URL 已经在走的那个代理——保持静默。

### 启动器 —— `bili opencode`

HTTPS 走证书 MITM,HTTP 走临时 `opencode.json` 副本(`/bili/` 改写;JSONC 注释照单接受,合并方式与 opencode 自身一致;相对本地插件路径在副本里重新锚定为绝对路径 —— opencode 按声明所在配置文件目录解析,#826)。宿主代次用 `--version` 探测(探测失败默认按 1.x):**2.x** 宿主注入内置 V2 插件(`dist/agent/opencode.js`),以临时包装目录形式给出(目录入口 `index.js` 再 re-export 插件文件 —— 2.x 拒绝配置 `plugin` 数组里的裸文件路径);**1.x** 宿主直接给裸文件路径。
Expand All @@ -137,7 +139,7 @@ HTTPS 走证书 MITM,HTTP 走临时 `opencode.json` 副本(`/bili/` 改写;JSONC

在真实 opencode 配置里注册一个自拉起插件并设 `compaction.auto: false`,之后直接跑 `opencode` 即可。默认不加 MCP 面(原生插件已提供会话绑定的 bili 工具);需要就传 `--with-mcp` —— 该条目不带 origin 钉扎,能扛过插件临时端口的代理重启(#926)。条目形态取决于**本 bili 自身的安装来源**:**npm 安装**写裸包名(`"plugin": ["billion-context"]`)—— 包经 `exports["./server"]` → `dist/agent/opencode-native.js` 暴露插件入口,opencode 用自己的 Npm.add 机制加载、自行管理安装与升级;零绝对路径、可跨机。(这个裸包名条目也可以不经 bili 直接手写进配置 —— 见 README 快速上手 方式 1。)**git checkout / 开发构建**回退到本机 shim 目录(`<configDir>/plugins/billion-context/index.js` → 该 checkout 的 `dist/agent/opencode-native.js`)—— 按构造即机器本地;之后改用 npm 安装再跑一次 install 会把条目迁回裸包名。

加载时插件自拉起自己的代理(健康的已有实例直接复用不重复起;父进程 pid 看门狗在 opencode 退出时收掉它),把模型流量路由到 `<proxy>/bili/<upstream-url>`,暴露与启动器模式相同的原生 bili 工具 —— 无固定端口、无环境变量、免启动器。退出:`BILI_NATIVE_OPENCODE=0`。若没有任何代理能拉到健康状态,请求直连(不压缩)并给一次性告警,之后自动恢复。在 `bili opencode` 启动下该条目整体跳过(代理归启动器管)。
加载时插件自拉起自己的代理(健康的已有实例直接复用不重复起;父进程 pid 看门狗在 opencode 退出时收掉它),把模型流量路由到 `<proxy>/bili/<upstream-url>`,暴露与启动器模式相同的原生 bili 工具 —— 无固定端口、无环境变量、免启动器。退出:`BILI_NATIVE_OPENCODE=0`。若没有任何代理能拉到健康状态,请求直连(不压缩)并给一次性告警,之后自动恢复。在 `bili opencode` 启动下该条目整体跳过(代理归启动器管)。在已带预烤 `/bili/` provider baseURL 的配置上安装会被拒绝——那属于纯代理路径(见上)。

### 纯代理(无插件)

Expand All @@ -159,6 +161,8 @@ HTTPS 走证书 MITM,HTTP 走临时 `opencode.json` 副本(`/bili/` 改写;JSONC

注意:2.0 AI-SDK provider 即使本地端点从不校验也要求 `apiKey` 字段 —— 随便填个非空值。

这条路径意味着**无插件**:在这些 URL 之上再装原生插件,安装会被拒绝、运行时每会话警告一次——每个 provider 只选一条路径(#1958)。

### 状态:`/acp` 与 `acp_status`

`/acp` 面板在所有模式下都绑定当前会话,`acp_status` 工具是其宿主内等价手段。在命令编辑器支持新增条目的宿主(2.0.x 稳定版,`editor.add`)上,V2 插件额外注册 `/acp` 斜杠命令 —— 以合成非模型消息渲染,面板优先(与 `acp_status` 工具一致);旧形状上该注册保持惰性。注意 `opencode run` 模式完全不派发斜杠命令(它们会透传给模型)—— 请用 TUI。
Expand Down
2 changes: 2 additions & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,8 @@ Clients you configure with an **API key** (not a login) let you change the upstr
"baseURL": "http://localhost:8787/bili/https://open.bigmodel.cn/api/coding/paas/v4"
```

**OpenCode note.** This is the **no-plugin** path for OpenCode. Installing the native plugin over such a config is refused (`bili plugin install opencode` exits 1, listing every offending file/provider/baseURL); if the combo already exists, the runtime warns once per session with the same fix-it guide. The three mutually exclusive OpenCode access paths are documented in [CLIENTS.md](CLIENTS.md#opencode).

**Codex (API key)** — edit `~/.codex/config.toml`, change the provider's `base_url`:

```toml
Expand Down
2 changes: 2 additions & 0 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,8 @@ launcher 命令里 `--` 之后的参数原样透传给客户端(`bili pi -- pr
"baseURL": "http://localhost:8787/bili/https://open.bigmodel.cn/api/coding/paas/v4"
```

**OpenCode 注意。**这是 OpenCode 的**无插件**路径。在如此配置上安装原生插件会被拒绝(`bili plugin install opencode` 以 exit code 1 退出,逐条列出命中的文件/provider/baseURL);若该组合已存在,运行时每会话警告一次并附同样的修复指引。三条互斥的 OpenCode 接入路径见 [CLIENTS.zh-CN.md](CLIENTS.zh-CN.md#opencode)。

**Codex(API key 模式)** —— 编辑 `~/.codex/config.toml`,改 provider 的 `base_url`:

```toml
Expand Down
27 changes: 26 additions & 1 deletion src/agent/opencode-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,20 +108,45 @@ export type OpencodeNativeRouteDeps = LiveOriginResolverDeps;
export function createNativeRoute(state: NativeInterceptState, deps: OpencodeNativeRouteDeps = {}): (e: V2HttpRequestEvent, s: V2State) => Promise<void> {
const resolveLive = createLiveOriginResolver(state, deps);
let warned = false;
// #1958: conflicting pre-routed config exposed once per (session, origin).
const conflictWarned = new Set<string>();
return async (e, s) => {
const url = typeof e.request?.url === "string" ? e.request.url : undefined;
if (url === undefined) return;
// #1365: routed URLs are skipped by isModelApiUrl by design — record
// the pinned model channel before that gate so attach recovery can see it.
if (routedBiliModelUrl(url) !== undefined) {
noteRoutedOrigin(state, url);
const baked = new URL(url).origin;
// #1958: an explicit pin of THIS origin (BILLION_CONTEXT_PROXY set
// to the same proxy) is the supported attach posture — silent.
// Anything else means the user hand-wrote the /bili/ prefix while
// the native plugin is active: two access paths claiming one
// request. Expose it with a fix-it guide, once per session+origin.
// Compared against the env, NOT state.origin: attach arming does
// not freeze state.origin synchronously, so early requests would
// false-warn against a benign pin.
const declaredRaw = process.env.BILLION_CONTEXT_PROXY;
let declared: string | undefined;
try {
declared = declaredRaw !== undefined && declaredRaw !== "" ? new URL(declaredRaw).origin : undefined;
} catch {
declared = undefined;
}
if (declared !== baked) {
const key = `${String(e.sessionID ?? "_")}\u0000${baked}`;
if (!conflictWarned.has(key)) {
conflictWarned.add(key);
console.error(`bili-native-opencode: conflicting configuration — model requests already carry a /bili/ prefix (origin ${baked}) while the native plugin is active. The plugin routes model requests itself; hand-written /bili/ prefixes belong to the no-plugin plain-proxy path. Pick ONE: (1) remove the /bili/ prefix from your opencode provider baseURL(s) so the plugin routes them, or (2) run \`bili plugin remove opencode\` and keep the pre-routed URLs. Until resolved, this session continues bound to ${baked}.`);
}
}
// #1958: the request ALREADY rides a bili proxy — its origin is
// baked into the URL. Bind the hook's stamping base there (NOT the
// lifecycle state.origin, which may point elsewhere) so the
// generic V2 stamping below carries the plugin identity. No
// rewrite and no resolveLive: a pinned channel cannot follow a
// replacement instance (#1365/#1370).
s.proxyBase = new URL(url).origin;
s.proxyBase = baked;
return;
}
if (!isModelApiUrl(url)) return;
Expand Down
56 changes: 56 additions & 0 deletions src/client-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1420,6 +1420,62 @@ export function readOpencodeProjectLayer(cwd: string): OpencodeProjectLayer {
return { providers };
}

// #1958: provider baseURLs already carrying a /bili/ route prefix — the
// plain-proxy posture conflicting with the native plugin (which routes model
// requests itself). Install refuses on them; the runtime hook warns.
export interface BiliPrefixedBaseURLEntry {
file: string;
provider: string;
baseURL: string;
}

export function isBiliRoutedBaseUrl(value: string): boolean {
try {
return new URL(value).pathname.startsWith("/bili/");
} catch {
return false;
}
}

/** #1958: every EFFECTIVE provider baseURL carrying a /bili/ route prefix
* across opencode's real config surface. Globals merge in opencode's own
* precedence order (config.json → opencode.json → opencode.jsonc, later
* wins; an explicit OPENCODE_CONFIG layers on top), so a stale entry an
* overriding file replaced never false-positives; the project layer (cwd up
* to the git root) outranks globals per provider id exactly like opencode's
* discovery. Each hit carries the declaring file for the actionable refusal
* message. */
export function findBiliPrefixedOpencodeBaseURLs(env: NodeJS.ProcessEnv, cwd: string): BiliPrefixedBaseURLEntry[] {
const hits: BiliPrefixedBaseURLEntry[] = [];
const xdg = nonEmpty(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path.join(os.homedir(), ".config");
const dir = path.join(xdg, "opencode");
// Same load order as readOpencodeConfigRoot — under the deep merge the
// last declarer of a provider's options.baseURL owns the effective value.
const ordered = ["config.json", "opencode.json", "opencode.jsonc"].map((f) => path.join(dir, f));
if (nonEmpty(env.OPENCODE_CONFIG)) ordered.push(env.OPENCODE_CONFIG);
const effective: Record<string, { baseURL: string; file: string }> = {};
for (const file of ordered) {
const parsed = readConfigFileRoot(file);
if (parsed === undefined) continue;
const provRoot = parsed.provider;
if (!provRoot || typeof provRoot !== "object" || Array.isArray(provRoot)) continue;
for (const [name, value] of Object.entries(provRoot as Record<string, unknown>)) {
if (!value || typeof value !== "object" || Array.isArray(value)) continue;
const opts = (value as Record<string, unknown>).options;
const rawBase = opts && typeof opts === "object" && !Array.isArray(opts) ? (opts as Record<string, unknown>).baseURL : undefined;
if (typeof rawBase === "string" && rawBase !== "") effective[name] = { baseURL: rawBase, file };
}
}
// Project layer outranks globals per provider id (nearest level wins).
for (const [name, view] of Object.entries(readOpencodeProjectLayer(cwd).providers)) {
if (view.baseURL !== undefined) effective[name] = { baseURL: view.baseURL, file: view.file };
}
for (const [provider, v] of Object.entries(effective)) {
if (isBiliRoutedBaseUrl(v.baseURL)) hits.push({ file: v.file, provider, baseURL: v.baseURL });
}
return hits.sort((a, b) => a.file.localeCompare(b.file) || a.provider.localeCompare(b.provider));
}

export function parseZcodeConfig(obj: unknown): ZcodeConfig {
const result: ZcodeConfig = { providers: {} };
if (!obj || typeof obj !== "object" || Array.isArray(obj)) return result;
Expand Down
20 changes: 19 additions & 1 deletion src/plugin-install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import crypto from "node:crypto";
import { execFileSync, spawnSync } from "node:child_process";
import { fileURLToPath, pathToFileURL } from "node:url";
import { applyEdits, modify as jsoncModify, parse as jsoncParse, type ParseError } from "jsonc-parser";
import { resolveDshHome, resolveHermesHome, resolveKimiHome, resolvePiHome } from "./client-config.js";
import { findBiliPrefixedOpencodeBaseURLs, resolveDshHome, resolveHermesHome, resolveKimiHome, resolvePiHome } from "./client-config.js";
import { resolveClaudeNativePort } from "./config.js";
import { lanePreferredPort } from "./instance.js";
import { DSH_PACKAGE, dshBundleInstalled, dshHasLegacyManagedBlock, dshProfileDependsOnBili, dshProfileDepSpec, dshProfileDirs, isRegistryDepSpec, planDshSpawn, refreshDshProfileBundles, runDshPlugin, stripLegacyManagedBlock } from "./dsh-channel.js";
Expand Down Expand Up @@ -1196,6 +1196,24 @@ export function applyOpencodePluginEntry(args: { data: Record<string, unknown>;

function opencodeInstall(withMcp = false): string {
const file = opencodeTargetFile();
// #1958: refuse to CREATE the conflicting configuration — pre-routed /bili/
// provider baseURLs are the no-plugin plain-proxy path; under the native
// plugin they split routing ownership. Scan the real effective config
// surface (globals + OPENCODE_CONFIG + cwd project layer), not just the
// target file. Nothing is written before this point, so it fails clean.
const prefixed = findBiliPrefixedOpencodeBaseURLs(process.env, process.cwd());
if (prefixed.length > 0) {
throw new Error(
[
"conflicting configuration — opencode config already carries pre-routed /bili/ provider baseURL(s):",
...prefixed.map((h) => ` - ${h.file} -> provider "${h.provider}" baseURL ${JSON.stringify(h.baseURL)}`),
"The native plugin routes model requests itself; hand-written /bili/ prefixes belong to the no-plugin plain-proxy path and the two are mutually exclusive. Pick ONE, then re-run:",
" 1) remove the /bili/ prefix from those baseURLs so the plugin routes requests itself (recommended), or",
" 2) keep the pre-routed URLs and do not install the native plugin (plain proxy mode).",
"Nothing was written.",
].join("\n"),
);
}
const { original, data } = loadOpencodeConfig(file);
const notes: string[] = [];
const touched = new Set<string>();
Expand Down
Loading
Loading