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
27 changes: 27 additions & 0 deletions .github/workflows/ci-e2e-native-opencode.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,30 @@ jobs:
name: e2e-native-opencode-artifacts
path: tmp/e2e-artifacts
if-no-files-found: ignore

e2e-opencode-responses-ws:
name: OpenCode V2 Responses WebSocket ACP (zero tokens)
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Install WebSocket-capable OpenCode V2
run: npm i -g @opencode/cli@2.0.20
- name: Install deps
run: npm ci
- name: Build
run: npm run build
- name: Run native Responses WebSocket ACP regression
env:
E2E_OC_BIN: opencode
run: ACP_TEST_E2E_OC_WS=1 node --import tsx --test tests/e2e/e2e-opencode-responses-ws.test.ts
- uses: actions/upload-artifact@v4
if: failure()
with:
name: e2e-opencode-responses-ws-artifacts
path: /tmp/bili-oc-ws-e2e-*
if-no-files-found: ignore
20 changes: 20 additions & 0 deletions CLIENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,26 @@ 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).

### OpenAI Responses WebSockets (V2)

The V2 plugin also intercepts OpenAI `experimental.ws.handshake` requests.
Both legs use WebSocket: OpenCode → bili → the Responses upstream. This
includes API-key OpenAI and ChatGPT Pro/Plus browser/headless OAuth; the login
method does not select the transport. No OpenCode configuration rewrite or
new bili setting is required. The socket must originate locally and carry
the cooperative plugin identity; generic or unclaimed upgrades retain 426.

ACP processing, native tools and usage accounting stay active. Client deltas
are expanded before compression. Upstream deltas are used only when the
processed history exactly extends the previous response; a fold starts a new
chain with full compressed input on the same socket. Ref tagging or other
history edits can also require full input, so connection reuse does not imply
every turn is incremental. Older hosts without the experimental hook must
use OpenCode's existing `providers.openai.settings.transport: "http"` setting.
Realtime, multiplexed concurrent responses, and remote WS clients are outside
this integration's scope. Verification: real OpenCode V2.0.20 with a local
Responses WS upstream, not live OpenAI/ChatGPT credentials.

### Pure proxy (no plugin)

Point the provider baseURL at the proxy like any other client:
Expand Down
17 changes: 17 additions & 0 deletions CLIENTS.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,23 @@ HTTPS 走证书 MITM,HTTP 走临时 `opencode.json` 副本(`/bili/` 改写;JSONC

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

### OpenAI Responses WebSocket(V2)

V2 插件也接管 OpenAI 的 `experimental.ws.handshake` 请求,两端均使用
WebSocket:OpenCode → bili → Responses 上游。支持 OpenAI API Key 及
ChatGPT Pro/Plus browser/headless OAuth;登录方式不决定传输方式。
无需改写 OpenCode 配置或增加 bili 设置。首版只接受本机发起、携带原生
插件身份的连接;普通或未接管的 WebSocket 升级仍立即返回 426。

ACP 处理、原生工具和用量统计保持生效。客户端增量先还原再压缩;只有
处理后的历史确实延续上次响应时,上游才使用增量。压缩后在同一连接上
发送完整压缩上下文,开始新的响应链。引用标签或其它历史变化也可能要求
完整输入,因此复用连接不代表每轮都只发增量。不支持实验钩子的旧宿主
需要使用 OpenCode 已有的 `providers.openai.settings.transport: "http"`。
Realtime、同一连接的并发多路响应及远程 WS 客户端不在本次范围。
验证使用真实 OpenCode V2.0.20 与本地 Responses WS 上游,未使用真实
OpenAI/ChatGPT 凭据。

### 纯代理(无插件)

与其它客户端一样,把 provider baseURL 指向代理:
Expand Down
110 changes: 110 additions & 0 deletions docs/opencode-responses-websocket.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# OpenCode V2 Responses WebSocket integration (#1844)

## Approved scope

The user authorized implementing the previously discussed two-ended WebSocket
ACP integration on 2026-10-01. OpenCode V2 connects to bili over WebSocket;
bili connects to the selected Responses upstream over WebSocket. This includes
the OpenAI API and ChatGPT OAuth/Codex endpoint. It does not implement Realtime,
generic opaque WebSocket passthrough, or change the user's OpenCode configuration.

## Decision points

- The V2 handshake hook routes supported Responses sockets through the existing
explicit-protocol tunnel, with plugin identity and model metadata. Other
protocols, disabled plugins, and older hosts retain their existing behavior.
- Only loopback, cooperative OpenCode Responses upgrades are admitted initially.
Destination admission reuses the existing tunnel guard. Unclaimed upgrades
still receive the existing immediate 426, independently of PR #1472.
- Responses frames enter the existing request pipeline through an in-process
HTTP-shaped envelope, not a network HTTP hop. An async-scoped fetch transport
executes model requests, retries, and preflight requests over upstream
WebSocket. Existing ACP policy, tool execution, usage accounting, and prose
filtering remain the single authority. Tool argument strings are never cleaned.
- Client and upstream continuation checkpoints are separate: the client sees
its original history and visible output; the upstream sees the ACP-processed
history. Incoming deltas are expanded before ACP. Outgoing deltas are used only
when the processed input extends the upstream checkpoint exactly. A fold or
other history change sends full processed input without previous_response_id.
This starts a new response chain without requiring a new socket.
Request-size logs marked `view=ws-expanded` describe reconstructed pipeline
envelopes, not incremental WebSocket wire bytes.
- Only completed responses establish continuation checkpoints. Disconnect,
cancellation, failed/incomplete responses, and unknown response IDs do not
fabricate successful history. Checkpoints and queued payloads are bounded.
- Both checkpoints accumulate `response.output_item.done` items by output index.
Empty, missing, or partial terminal `response.output` must not erase completed
tool calls and leave orphaned results on the next delta. Terminal items merge
by item ID; streaming frames remain unchanged. Debug logs report restored
checkpoint item counts without recording their contents.
- WS diagnostics identify the local socket and session, failure phase
(`handshake`, `await-first-event`, `stream`, or `dispatch`), numeric close code,
full/delta request mode, and checkpoint reset/recovery reason. They omit
authorization headers, URLs, close-reason text, payloads, and upstream error
messages. Normal lifecycle/recovery details use debug; failures use warn.
- No configuration field, environment variable, package version, persistence
format, or acp-kernel version is added or changed. Socket checkpoints are
connection-local; ACP persistence remains unchanged. The ws implementation is
a bundled build-time dependency, not an external runtime requirement.

## Architecture: generic WebSocket bridge (#1467 phase-2 shell)

The WebSocket interception is split into a protocol-independent shell and a
per-protocol codec:

- `src/ws-bridge.ts` (shell) owns admission (loopback source, `x-bili-plugin`
lane marker, `x-bili-plugin-conversation` session header, tunnel-destination
guard), the upgrade handshake, per-connection bookkeeping, and shutdown
teardown. It knows nothing about any wire protocol.
- `src/responses-ws.ts` (codec) owns everything Responses-specific: frame
validation, the `previous_response_id` client history contract, the upstream
WebSocket transport with its continuation checkpoints, and the SSE response
sink. It is registered as `responsesCodec` in a codec table at the single
wiring site (`installWebSocketBridge(server, dispatch, log, [responsesCodec,
codexResponsesCodec])` in `src/server.ts`).

A second wire protocol is a new codec file plus one table entry — no shell
changes. The shell contract is `WsBridgeCodec` (name, plugin marker, URL claim,
session factory) and `WsBridgeSession` (message/close/shutdown); sessions
receive the labeled logger, the upgraded peer, the upgrade request, the claimed
upstream URL, and the ACP pipeline entry (`dispatch`), and are expected to
rebuild protocol-shaped envelopes in-process. `tests/ws-bridge.test.ts` drives
the shell with a synthetic second codec to keep the codec table honest.

The second real codec is already here: **`codexResponsesCodec`** claims codex
CLI's Responses-over-WebSocket dial (`/bili/<upstream>/responses`, conversation
header `session-id`, `stream:true` frames, per-connection prewarm probe with
`generate:false` relayed verbatim around the pipeline). It is prefix-lane:
no plugin marker on the wire, admission resting on loopback + conversation
header + tunnel guard — the same trust level as prefix-mode HTTP. Codex
replays the full history every turn (`previous_response_id` is never sent),
so the fold simply shrinks the next replay; see `tests/codex-responses-ws.test.ts`.

Unknown protocols cannot be compressed (folding requires knowing where history
lives in the wire format); they stay on the #1472 transparent passthrough lane
and remain untouched by this bridge.

## Verification

Use random loopback ports and fake Responses WebSocket upstreams, with no real
credentials or model usage. Prove both directions stay on WebSocket, normal
continuation is incremental, a real ACP fold resets the upstream history,
tool argument payloads survive unchanged, usage reaches the existing session,
and successive tool calls/results still advance history after a fold even when
the terminal output is sparse,
and unknown upgrades retain 426. Verify upstream proxy routing, errors,
cancellation, reconnect, checkpoint misses, and session isolation. Exercise a
real OpenCode V2 binary with an isolated configuration and successful fake
WebSocket upstream; an unavailable socket that merely falls back to HTTP is
not acceptable evidence. Run typecheck, the full unit suite, build, and the
required Responses client E2E before submitting a human-reviewed PR.

Failure-combination coverage includes tool arguments delivered before disconnect,
failed/incomplete terminal events, cancellation followed immediately by a new
connection with rotated synthetic credentials, overlapping creates, repeated
continuation/connection-limit errors with bounded retries, and handshake refusal
followed by recovery. The sparse-output real-fold test also chains a missing
checkpoint, an idle disconnect, and connection-limit rotation, asserting that
summaries survive and each completed call/result appears exactly once upstream.
These are transport/history assertions, not proof of exactly-once execution of
arbitrary host tools or of the real OAuth refresh lifecycle.
56 changes: 56 additions & 0 deletions docs/opencode-responses-websocket.zh-CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# OpenCode V2 Responses WebSocket 接入(#1844)

## 已批准范围

用户于 2026-10-01 授权实现双端 WebSocket ACP 接入:OpenCode V2 到 bili、
bili 到 OpenAI Responses 上游均使用 WebSocket,包括 ChatGPT OAuth/Codex
端点。不实现 Realtime、通用透明帧转发,也不修改用户现用 OpenCode 配置。

## 关键设计

- V2 握手钩子通过已有显式协议隧道路由连接,并附带原生插件身份与模型信息。
其它协议、退出插件的情形及旧宿主保留原行为。
- 首版只接受本机、原生 OpenCode Responses 连接,复用既有隧道目的地安全
检查。未接管升级仍立即返回 426,与 #1472 的透明转发方案相互独立。
- Responses 帧经进程内 HTTP 形状适配进入既有 ACP 请求流程,不产生网络
HTTP 中间跳。异步作用域中的传输适配器把模型请求、预检和重试发送至上游
WebSocket;既有 ACP 策略、工具执行、统计和正文过滤仍是唯一权威。
工具参数字符串不经过清理。
- 客户端与上游分别保存连接级检查点。客户端增量先还原为完整历史;上游只有
在处理后输入确实延续其检查点时才发送增量。压缩或其它历史编辑后发送完整
处理后输入,不继续旧 previous_response_id,无需因此重开连接。
- 引用标签也可能改变上一轮助手消息,因此复用连接不保证每轮都只发送增量。
- 标记 `view=ws-expanded` 的请求大小日志描述还原后的处理视图,不代表增量
WebSocket 实际传输字节数。
- 只有成功完成的响应建立检查点。断线、取消、失败、未完成响应或未知响应 ID
不伪造成功历史;检查点和缓冲均有大小限制。
- 两侧检查点按输出索引累计 `response.output_item.done`,结束事件的
`response.output` 为空、缺省或不完整时仍保留已完成工具调用,避免下轮增量的
工具结果失去对应调用。结束事件按 item ID 合并,流式帧保持原样。
调试日志仅记录检查点补齐的项目数量,不记录内容。
- WS 诊断标明本地连接与会话、失败阶段(握手、等待首事件、流中或分派)、数值
关闭码、全量/增量请求模式,以及检查点重置和恢复原因。不记录认证头、URL、
关闭原因原文、请求内容或上游错误正文。正常生命周期与恢复使用 debug,失败
使用 warn。
- 不增加或改变运行时配置字段、环境变量、包版本、持久化格式或 acp-kernel
版本。ws 是构建时内联依赖,不增加外置运行时依赖。

## 验证

使用随机回环端口与假 Responses WebSocket 上游,不使用真实凭据或模型额度。
证明双端 WebSocket、增量续接、实际 ACP 折叠后重建响应链、工具参数保真、
用量统计以及未接管升级保留 426;覆盖代理出口、TLS、错误、取消、重连、
检查点丢失与会话隔离。
同时验证结束事件输出不完整时,压缩后的连续工具调用及结果仍能进入后续历史。

真实 OpenCode V2 二进制使用隔离配置,假上游必须成功建立 WebSocket,不能
把连接失败后回退 HTTP 当作证据。交付运行类型检查、完整单测、构建及客户端
端到端测试,并提交人工审查 PR;若真实 Responses 上游不可达,明确记录该
验收缺口,不声称完成线上 OpenAI/ChatGPT 验证。

异常组合覆盖:工具参数交付后断线、失败/未完成终态、取消后立即以轮换的模拟
凭据新建连接、重叠请求、续接/连接寿命错误连续发生时的重试上限,以及握手被拒
后恢复。稀疏终态的真实压缩测试还连续注入检查点丢失、空闲断线和连接轮换,
确认摘要保留且每对已完成调用/结果在上游历史中仅出现一次。
这些验证的是传输和历史,不代表任意宿主工具副作用的严格仅执行一次保证,也
不代替真实 OAuth 刷新生命周期验证。
36 changes: 35 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"@types/node": "^22.0.0",
"@types/node-forge": "^1.3.14",
"@types/semver": "^7.7.1",
"@types/ws": "8.18.2",
"acp-kernel": "0.0.101",
"fzstd": "0.1.1",
"jsonc-parser": "^3.3.1",
Expand All @@ -68,7 +69,8 @@
"tsx": "^4.0.0",
"typescript": "^5.5.0",
"undici": "^7.29.0",
"verdaccio": "^6.10.4"
"verdaccio": "^6.10.4",
"ws": "8.22.0"
},
"engines": {
"node": ">=20"
Expand Down
2 changes: 1 addition & 1 deletion src/agent/native-intercept.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ function isBiliControlUrl(url: string): boolean {
* done) but DOES stamp plugin headers on them. */
export function routedBiliModelUrl(url: string): string | undefined {
if (!/^https?:\/\//i.test(url) || url.includes("/__bili/") || url.includes("/__acp/")) return undefined;
const m = /^https?:\/\/[^/]+\/bili\/(https?:\/.+)$/i.exec(url);
const m = /^https?:\/\/[^/]+\/bili\/(?:responses\/)?(https?:\/.+)$/i.exec(url);
if (m === null) return undefined;
return isModelApiUrl(m[1]) ? m[1] : undefined;
}
Expand Down
Loading
Loading