diff --git a/CLIENTS.md b/CLIENTS.md index ac69b7c175..5e0b922f15 100644 --- a/CLIENTS.md +++ b/CLIENTS.md @@ -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/` @@ -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) @@ -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 diff --git a/CLIENTS.zh-CN.md b/CLIENTS.zh-CN.md index 028be6b704..b195d60e7f 100644 --- a/CLIENTS.zh-CN.md +++ b/CLIENTS.zh-CN.md @@ -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** 宿主直接给裸文件路径。 @@ -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 目录(`/plugins/billion-context/index.js` → 该 checkout 的 `dist/agent/opencode-native.js`)—— 按构造即机器本地;之后改用 npm 安装再跑一次 install 会把条目迁回裸包名。 -加载时插件自拉起自己的代理(健康的已有实例直接复用不重复起;父进程 pid 看门狗在 opencode 退出时收掉它),把模型流量路由到 `/bili/`,暴露与启动器模式相同的原生 bili 工具 —— 无固定端口、无环境变量、免启动器。退出:`BILI_NATIVE_OPENCODE=0`。若没有任何代理能拉到健康状态,请求直连(不压缩)并给一次性告警,之后自动恢复。在 `bili opencode` 启动下该条目整体跳过(代理归启动器管)。 +加载时插件自拉起自己的代理(健康的已有实例直接复用不重复起;父进程 pid 看门狗在 opencode 退出时收掉它),把模型流量路由到 `/bili/`,暴露与启动器模式相同的原生 bili 工具 —— 无固定端口、无环境变量、免启动器。退出:`BILI_NATIVE_OPENCODE=0`。若没有任何代理能拉到健康状态,请求直连(不压缩)并给一次性告警,之后自动恢复。在 `bili opencode` 启动下该条目整体跳过(代理归启动器管)。在已带预烤 `/bili/` provider baseURL 的配置上安装会被拒绝——那属于纯代理路径(见上)。 ### 纯代理(无插件) @@ -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。 diff --git a/CONFIGURATION.md b/CONFIGURATION.md index f64eb05267..9c12209209 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -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 diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index d916721e59..6643a23e9b 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -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 diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index 841db31a9c..93ce53a25a 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -108,6 +108,8 @@ export type OpencodeNativeRouteDeps = LiveOriginResolverDeps; export function createNativeRoute(state: NativeInterceptState, deps: OpencodeNativeRouteDeps = {}): (e: V2HttpRequestEvent, s: V2State) => Promise { const resolveLive = createLiveOriginResolver(state, deps); let warned = false; + // #1958: conflicting pre-routed config exposed once per (session, origin). + const conflictWarned = new Set(); return async (e, s) => { const url = typeof e.request?.url === "string" ? e.request.url : undefined; if (url === undefined) return; @@ -115,13 +117,36 @@ export function createNativeRoute(state: NativeInterceptState, deps: OpencodeNat // 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; diff --git a/src/client-config.ts b/src/client-config.ts index 4e060ef4ed..626125f1fb 100644 --- a/src/client-config.ts +++ b/src/client-config.ts @@ -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 = {}; + 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)) { + if (!value || typeof value !== "object" || Array.isArray(value)) continue; + const opts = (value as Record).options; + const rawBase = opts && typeof opts === "object" && !Array.isArray(opts) ? (opts as Record).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; diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 7d40373200..8f459be8a0 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -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"; @@ -1196,6 +1196,24 @@ export function applyOpencodePluginEntry(args: { data: Record; 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(); diff --git a/tests/issue1958-conflict-detection.test.ts b/tests/issue1958-conflict-detection.test.ts new file mode 100644 index 0000000000..5e82b58d34 --- /dev/null +++ b/tests/issue1958-conflict-detection.test.ts @@ -0,0 +1,264 @@ +// #1958 (direction change): "native plugin + hand-written /bili/ provider +// baseURL" is a CONFLICTING configuration — two mutually exclusive access +// paths claiming routing ownership of the same requests. It must be exposed, +// not silently absorbed: +// - install: `bili plugin install opencode` refuses (exit 1 upstream in the +// CLI) when the real effective config surface carries a /bili/ baseURL; +// - runtime: the V2 native route warns once per (session, origin) with a +// fix-it guide; an explicit pin of the SAME origin (BILLION_CONTEXT_PROXY +// pointing at the proxy the URLs already ride) stays silent. +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +// Module-level guards read env while opencode-native EVALUATES; static imports +// hoist above any assignment, so set the marker first and import dynamically. +process.env.NODE_TEST_CONTEXT = "1"; + +import type { NativeInterceptState } from "../src/agent/native-intercept.ts"; +import type { V2HttpRequestEvent, V2State } from "../src/agent/opencode-v2.ts"; +import { findBiliPrefixedOpencodeBaseURLs, isBiliRoutedBaseUrl } from "../src/client-config.ts"; +import { pluginInstall } from "../src/plugin-install.ts"; +import { rmrf } from "./tmp-rm.ts"; + +const { createNativeRoute } = await import("../src/agent/opencode-native.ts"); + +function tempDir(prefix: string): string { + return fs.mkdtempSync(path.join(os.tmpdir(), prefix)); +} + +function writeJson(file: string, obj: unknown): void { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify(obj, null, 2)); +} + +/** A cwd that is its own git root, so the project-layer scan stays inside it. */ +function gitCwd(prefix: string): string { + const dir = tempDir(prefix); + fs.mkdirSync(path.join(dir, ".git")); + return dir; +} + +// --------------------------------------------------------------------------- +// Install-time surface: the pure scanner +// --------------------------------------------------------------------------- + +test("#1958: isBiliRoutedBaseUrl flags only http(s) paths starting with /bili/", () => { + assert.equal(isBiliRoutedBaseUrl("http://127.0.0.1:8787/bili/https://api.openai.com/v1"), true); + assert.equal(isBiliRoutedBaseUrl("https://proxy.example/bili/http://upstream/v1/chat/completions"), true); + assert.equal(isBiliRoutedBaseUrl("https://api.openai.com/v1"), false); + assert.equal(isBiliRoutedBaseUrl("http://127.0.0.1:8787/bilibili/videos"), false); + assert.equal(isBiliRoutedBaseUrl("http://127.0.0.1:8787/bili"), false); + assert.equal(isBiliRoutedBaseUrl("not a url"), false); +}); + +test("#1958: scanner reports effective hits only — overridden stale entries never fire", () => { + const xdg = tempDir("bili-oc-scan-xdg-"); + const cwd = gitCwd("bili-oc-scan-cwd-"); + try { + const cfg = path.join(xdg, "opencode", "config.json"); + const jsonc = path.join(xdg, "opencode", "opencode.jsonc"); + writeJson(cfg, { + provider: { + stale: { options: { baseURL: "http://127.0.0.1:8787/bili/https://stale.invalid/v1" } }, + live: { options: { baseURL: "http://127.0.0.1:8787/bili/https://live.invalid/v1" } }, + }, + }); + // opencode.jsonc merges over config.json and replaces "stale"'s base. + writeJson(jsonc, { provider: { stale: { options: { baseURL: "https://stale.invalid/v1" } } } }); + const env = { XDG_CONFIG_HOME: xdg } as NodeJS.ProcessEnv; + assert.deepEqual(findBiliPrefixedOpencodeBaseURLs(env, cwd), [ + { file: cfg, provider: "live", baseURL: "http://127.0.0.1:8787/bili/https://live.invalid/v1" }, + ]); + } finally { + rmrf(xdg); + rmrf(cwd); + } +}); + +test("#1958: scanner honors OPENCODE_CONFIG and the project layer (nearest wins)", () => { + const xdg = tempDir("bili-oc-scan-xdg2-"); + const cwd = gitCwd("bili-oc-scan-cwd2-"); + try { + const overlay = path.join(xdg, "overlay.jsonc"); + writeJson(overlay, { provider: { ov: { options: { baseURL: "http://127.0.0.1:8787/bili/https://ov.invalid/v1" } } } }); + // Project file outranks globals per provider id. + writeJson(path.join(cwd, "opencode.json"), { provider: { proj: { options: { baseURL: "http://127.0.0.1:8787/bili/https://proj.invalid/v1" } } } }); + const env = { XDG_CONFIG_HOME: xdg, OPENCODE_CONFIG: overlay } as NodeJS.ProcessEnv; + const hits = findBiliPrefixedOpencodeBaseURLs(env, cwd); + const byProvider: Record = {}; + for (const h of hits) byProvider[h.provider] = h; + assert.deepEqual(byProvider.ov, { file: overlay, provider: "ov", baseURL: "http://127.0.0.1:8787/bili/https://ov.invalid/v1" }); + assert.deepEqual(byProvider.proj, { file: path.join(cwd, "opencode.json"), provider: "proj", baseURL: "http://127.0.0.1:8787/bili/https://proj.invalid/v1" }); + // A project-level RAW base overrides the global prefixed one. + writeJson(path.join(cwd, "opencode.json"), { provider: { proj: { options: { baseURL: "https://proj.invalid/v1" } } } }); + const hits2 = findBiliPrefixedOpencodeBaseURLs(env, cwd); + assert.equal(hits2.length, 1); + assert.equal(hits2[0].provider, "ov"); + } finally { + rmrf(xdg); + rmrf(cwd); + } +}); + +// --------------------------------------------------------------------------- +// Install-time behavior: refusal + clean failure + no false positive +// --------------------------------------------------------------------------- + +function withIsolatedHome(t: test.TestContext, opts: { configFile?: unknown }): { xdg: string; cwd: string; target: string } { + const xdg = tempDir("bili-oc-install-xdg-"); + const cwd = gitCwd("bili-oc-install-cwd-"); + const target = path.join(xdg, "opencode", "opencode.json"); + if (opts.configFile !== undefined) writeJson(target, opts.configFile); + const prev = { + xdg: process.env.XDG_CONFIG_HOME, + open: process.env.OPENCODE_CONFIG, + bin: process.env.BILI_CLIENT_BIN, + }; + delete process.env.OPENCODE_CONFIG; + // Hermetic probe pin: unresolvable bin fails soft to major 1. + process.env.BILI_CLIENT_BIN = "/nonexistent/bili-oc-probe-pin"; + process.env.XDG_CONFIG_HOME = xdg; + const prevCwd = process.cwd(); + process.chdir(cwd); + t.after(() => { + process.chdir(prevCwd); + if (prev.xdg === undefined) delete process.env.XDG_CONFIG_HOME; + else process.env.XDG_CONFIG_HOME = prev.xdg; + if (prev.open === undefined) delete process.env.OPENCODE_CONFIG; + else process.env.OPENCODE_CONFIG = prev.open; + if (prev.bin === undefined) delete process.env.BILI_CLIENT_BIN; + else process.env.BILI_CLIENT_BIN = prev.bin; + rmrf(xdg); + rmrf(cwd); + }); + return { xdg, cwd, target }; +} + +test("#1958: plugin install refuses over a pre-routed /bili/ baseURL and writes nothing", (t) => { + const { target } = withIsolatedHome(t, { + configFile: { provider: { openai: { options: { baseURL: "http://127.0.0.1:8787/bili/https://api.openai.com/v1" } } } }, + }); + const before = fs.readFileSync(target, "utf8"); + assert.throws(() => pluginInstall("opencode"), (err: unknown) => { + assert.ok(err instanceof Error); + assert.match(err.message, /conflicting configuration/); + assert.match(err.message, new RegExp(target)); + assert.match(err.message, /provider "openai"/); + assert.match(err.message, /Nothing was written\./); + return true; + }); + assert.equal(fs.readFileSync(target, "utf8"), before, "the config is untouched"); +}); + +test("#1958: plugin install proceeds when every baseURL is raw (no false positive)", (t) => { + withIsolatedHome(t, { + configFile: { provider: { openai: { options: { baseURL: "https://api.openai.com/v1" } } } }, + }); + const out = pluginInstall("opencode"); + assert.match(out, /installed ->/); +}); + +// --------------------------------------------------------------------------- +// Runtime exposure: warn once per (session, origin); benign pins stay silent +// --------------------------------------------------------------------------- + +const BAKED = "http://127.0.0.1:9999"; +const ROUTED_URL = `${BAKED}/bili/http://example.invalid/v1/chat/completions`; + +function routedEvent(sessionID: string | undefined, url = ROUTED_URL): V2HttpRequestEvent { + const e: V2HttpRequestEvent = { request: new Request(url, { method: "POST" }) }; + if (sessionID !== undefined) e.sessionID = sessionID; + return e; +} + +async function capturedErrors(fn: () => Promise): Promise { + const lines: string[] = []; + const orig = console.error; + console.error = (...args: unknown[]) => { lines.push(args.map(String).join(" ")); }; + try { + await fn(); + } finally { + console.error = orig; + } + return lines.filter((l) => l.includes("conflicting configuration")); +} + +function spawnState(): NativeInterceptState { + return { origin: "http://127.0.0.1:7777", ready: Promise.resolve("http://127.0.0.1:7777") }; +} + +test("#1958: conflicting pre-routed URL warns once per (session, origin), then stays quiet", async () => { + const prev = process.env.BILLION_CONTEXT_PROXY; + delete process.env.BILLION_CONTEXT_PROXY; + try { + const route = createNativeRoute(spawnState()); + const s: V2State = {}; + const otherUrl = `${BAKED.replace(":9999", ":9998")}/bili/http://other.invalid/v1/chat/completions`; + const run = async (): Promise => { + await route(routedEvent("ses_a"), s); + assert.equal(s.proxyBase, BAKED, "stamping binds to the baked origin (#1959 fallback)"); + await route(routedEvent("ses_a"), s); + await route(routedEvent("ses_b"), s); + await route(routedEvent("ses_a", otherUrl), s); + }; + const lines = await capturedErrors(run); + assert.equal(lines.length, 3, "one per distinct (session, origin) pair"); + assert.match(lines[0], new RegExp(BAKED)); + assert.match(lines[0], /pick one/i); + assert.equal(s.proxyBase, BAKED.replace(":9999", ":9998"), "the last request's origin is the current binding"); + } finally { + if (prev === undefined) delete process.env.BILLION_CONTEXT_PROXY; + else process.env.BILLION_CONTEXT_PROXY = prev; + } +}); + +test("#1958: an explicit pin of the SAME origin is the supported attach posture — silent", async () => { + const prev = process.env.BILLION_CONTEXT_PROXY; + process.env.BILLION_CONTEXT_PROXY = BAKED; + try { + const state: NativeInterceptState = { origin: BAKED, ready: Promise.resolve(BAKED), attach: true }; + const s: V2State = {}; + const lines = await capturedErrors(async () => { + await createNativeRoute(state)(routedEvent("ses_pin"), s); + await createNativeRoute(state)(routedEvent("ses_pin"), s); + }); + assert.equal(lines.length, 0, "benign explicit pin must not warn"); + assert.equal(s.proxyBase, BAKED); + // Trailing slash / default-port spelling differences normalize away. + process.env.BILLION_CONTEXT_PROXY = `${BAKED}/`; + const s2: V2State = {}; + const lines2 = await capturedErrors(async () => { + await createNativeRoute(state)(routedEvent("ses_pin"), s2); + }); + assert.equal(lines2.length, 0); + process.env.BILLION_CONTEXT_PROXY = "http://127.0.0.1:80"; + const s3: V2State = {}; + const lines3 = await capturedErrors(async () => { + await createNativeRoute({ origin: "http://127.0.0.1", ready: Promise.resolve("http://127.0.0.1") })(routedEvent("ses_pin", "http://127.0.0.1:80/bili/http://example.invalid/v1/chat/completions"), s3); + }); + assert.equal(lines3.length, 0, "default ports fold in URL.origin comparison"); + } finally { + if (prev === undefined) delete process.env.BILLION_CONTEXT_PROXY; + else process.env.BILLION_CONTEXT_PROXY = prev; + } +}); + +test("#1958: attach to a DIFFERENT origin than the baked URL warns (real conflict)", async () => { + const prev = process.env.BILLION_CONTEXT_PROXY; + process.env.BILLION_CONTEXT_PROXY = "http://127.0.0.1:7777"; + try { + const state: NativeInterceptState = { origin: "http://127.0.0.1:7777", ready: Promise.resolve("http://127.0.0.1:7777"), attach: true }; + const s: V2State = {}; + const lines = await capturedErrors(async () => { + await createNativeRoute(state)(routedEvent("ses_mismatch"), s); + }); + assert.equal(lines.length, 1); + assert.equal(s.proxyBase, BAKED, "the pinned channel still wins over the declared origin (#1365)"); + } finally { + if (prev === undefined) delete process.env.BILLION_CONTEXT_PROXY; + else process.env.BILLION_CONTEXT_PROXY = prev; + } +}); diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index 7bf3044496..f58693d58e 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -1456,6 +1456,10 @@ function hintEnv(home: string, piAgentDir: string): Record { return { PI_CODING_AGENT_DIR: piAgentDir, CODEX_HOME: home, + // #1958: the install-time /bili/ scan reads the real effective config + // surface — pin XDG so the ambient global opencode config (which on a + // dev machine may itself carry pre-routed baseURLs) never leaks in. + XDG_CONFIG_HOME: path.join(home, ".config"), OPENCODE_CONFIG: path.join(home, ".config/opencode/opencode.json"), CLAUDE_CONFIG_DIR: home, CLAUDE: "/nonexistent/bili-claude-stub", @@ -1681,7 +1685,8 @@ test("plugin install opencode without a live proxy: MCP shell skipped, native pl const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-oc-noproxy-")); const ocFile = path.join(home, ".config/opencode/opencode.json"); try { - await withEnv({ OPENCODE_CONFIG: ocFile, BILI_MCP_PROXY: undefined, XDG_STATE_HOME: path.join(home, "state") }, async () => { + // #1958: pin XDG too — the install-time /bili/ scan reads the ambient global config surface. + await withEnv({ OPENCODE_CONFIG: ocFile, BILI_MCP_PROXY: undefined, XDG_STATE_HOME: path.join(home, "state"), XDG_CONFIG_HOME: path.join(home, ".config") }, async () => { const ocKey = pickPluginKey(detectOpencodeMajor()); const msg = pluginInstall("opencode"); assert.match(msg, /installed/); @@ -1709,7 +1714,8 @@ test("plugin install opencode replaces legacy opencode-acp entries — array and const ocFile = path.join(home, ".config/opencode/opencode.json"); fs.mkdirSync(path.dirname(ocFile), { recursive: true }); try { - await withEnv({ OPENCODE_CONFIG: ocFile, BILI_MCP_PROXY: undefined, XDG_STATE_HOME: path.join(home, "state") }, async () => { + // #1958: pin XDG too — the install-time /bili/ scan reads the ambient global config surface. + await withEnv({ OPENCODE_CONFIG: ocFile, BILI_MCP_PROXY: undefined, XDG_STATE_HOME: path.join(home, "state"), XDG_CONFIG_HOME: path.join(home, ".config") }, async () => { const ocKey = pickPluginKey(detectOpencodeMajor()); const otherKey = ocKey === "plugin" ? "plugins" : "plugin"; const dir = path.join(home, ".config/opencode/plugins/billion-context"); @@ -1759,7 +1765,8 @@ test("plugin install/remove/status survive a non-object mcp in opencode.json (#8 const ocFile = path.join(home, ".config/opencode/opencode.json"); fs.mkdirSync(path.dirname(ocFile), { recursive: true }); try { - await withEnv({ OPENCODE_CONFIG: ocFile, BILI_MCP_PROXY: undefined, XDG_STATE_HOME: path.join(home, "state") }, async () => { + // #1958: pin XDG too — the install-time /bili/ scan reads the ambient global config surface. + await withEnv({ OPENCODE_CONFIG: ocFile, BILI_MCP_PROXY: undefined, XDG_STATE_HOME: path.join(home, "state"), XDG_CONFIG_HOME: path.join(home, ".config") }, async () => { const ocKey = pickPluginKey(detectOpencodeMajor()); fs.writeFileSync(ocFile, JSON.stringify({ mcp: "totally-broken-string" })); const msg = pluginInstall("opencode");