billion-context 0.1.50 → 0.1.51-pr.235.77
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -226
- package/README.zh-CN.md +1 -5
- package/dist/agent/omp.js +20 -1
- package/dist/agent/omp.js.map +1 -1
- package/dist/agent/opencode.js +43 -1
- package/dist/agent/opencode.js.map +1 -1
- package/dist/agent/pi.js +20 -1
- package/dist/agent/pi.js.map +1 -1
- package/dist/index.js +506 -87
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -44,78 +44,12 @@ This installs the `bili` command (`bili-proxy` is kept as an alias).
|
|
|
44
44
|
|
|
45
45
|
Two ways to use it — pick one:
|
|
46
46
|
|
|
47
|
-
- **Launcher (
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
(whitelisted for TLS interception), HTTP upstreams via a `/bili/` baseURL
|
|
52
|
-
rewrite (cert MITM can't intercept plaintext). See **Option 0** below.
|
|
53
|
-
- **Zero-config (simplest):** prefix your client's baseURL with the proxy
|
|
54
|
-
origin + `/bili/`. No config file needed — context windows are auto-detected
|
|
55
|
-
from the [models.dev](https://models.dev) registry. The `/bili/` prefix also
|
|
56
|
-
doubles as a self-detection signal: billion-context client extensions
|
|
57
|
-
(billion-context-pi / opencode-acp) can recognize it in their own baseUrl
|
|
58
|
-
and self-disable, so you never get double compression.
|
|
59
|
-
|
|
60
|
-
### Agent plugin mode (inside-out)
|
|
61
|
-
|
|
62
|
-
For a native-plugin experience, an agent can run a small cooperative plugin
|
|
63
|
-
alongside the proxy: the plugin registers the four ACP tools
|
|
64
|
-
(`compress` / `decompress` / `search_context` / `acp_status`) natively with
|
|
65
|
-
the agent and drives the agent's own tool loop, while the proxy stays the
|
|
66
|
-
compression authority (state, history folding, philosophy prompt, nudges).
|
|
67
|
-
Tool schemas are served by the proxy itself (`GET /__bili/plugin/manifest`),
|
|
68
|
-
so plugin and proxy can never drift. See [PLUGIN.md](PLUGIN.md) for the
|
|
69
|
-
protocol spec. Plugin-equipped sessions are detected automatically via
|
|
70
|
-
request headers — wire-level tool injection is then suppressed for them
|
|
71
|
-
(no double compression, native tool UX). Works in both proxy modes: the
|
|
72
|
-
`/bili/` prefix baseURL **and MITM transparent mode** — the launcher
|
|
73
|
-
(`bili pi` / `bili codex` / `bili claude`) exports `BILLION_CONTEXT_PROXY`
|
|
74
|
-
for plugins to detect; the plugin can also report the agent's own model
|
|
75
|
-
context window (`x-bili-plugin-context-window`) and read live context
|
|
76
|
-
usage via `GET /__bili/plugin/status`.
|
|
77
|
-
|
|
78
|
-
Compression is injected automatically — you only configure routing, never
|
|
79
|
-
compression itself.
|
|
80
|
-
|
|
81
|
-
Installing a plugin is **optional** — without one, every client (hermes
|
|
82
|
-
included) still gets the four tools wire-injected by the proxy; installing
|
|
83
|
-
only upgrades them to native agent tools. The plugins ship **inside
|
|
84
|
-
billion-context itself** — no separate package: pi and omp get native agent
|
|
85
|
-
plugins (`dist/agent/*.js`), claude, codex and opencode get the MCP bridge
|
|
86
|
-
(`dist/mcp.js`, same protocol underneath). hermes has no plugin API — it
|
|
87
|
-
always rides the wire-injected tools.
|
|
88
|
-
|
|
89
|
-
What each host gets from a plugin: **pi / omp / opencode** register the four
|
|
90
|
-
tools natively **and** add an `/acp` status command; **claude / codex** (MCP
|
|
91
|
-
bridge) get the four tools as native MCP tools but no `/acp` slash command
|
|
92
|
-
(the MCP protocol has none). Without a plugin the compression is identical —
|
|
93
|
-
the client UI just never lists the tools; ask the model to run `acp_status`
|
|
94
|
-
if you want the status panel rendered in chat.
|
|
47
|
+
- **Launcher (easiest):** one `bili <client>` command brings up the proxy and
|
|
48
|
+
the client together — no real config file is ever touched.
|
|
49
|
+
- **URL change (persistent):** prefix your client's baseURL with the proxy
|
|
50
|
+
origin + `/bili/`.
|
|
95
51
|
|
|
96
|
-
|
|
97
|
-
bili plugin install pi # needed: pi's native tools + /acp come ONLY from install (the launcher never injects MCP for pi)
|
|
98
|
-
bili plugin list # install status for every supported host
|
|
99
|
-
bili plugin remove pi # undo (original files backed up to *.bili-bak once)
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
Every other host skips install: omp ships with the plugin built in, opencode
|
|
103
|
-
is injected automatically by `bili opencode`, claude/codex can set
|
|
104
|
-
`BILI_LAUNCHER_PLUGIN=1` with the launcher (or `plugin install` for a
|
|
105
|
-
persistent MCP registration), and hermes has no plugin API at all.
|
|
106
|
-
|
|
107
|
-
The installed plugin is a **thin** one (~5 KB, zero runtime deps): it just
|
|
108
|
-
detects the proxy (from the `/bili/` baseURL or `BILLION_CONTEXT_PROXY`),
|
|
109
|
-
fetches tool schemas from the proxy, registers native tools, and forwards
|
|
110
|
-
executions — the proxy remains the single compression authority, so plugin
|
|
111
|
-
and proxy always match versions. Killing it entirely: `BILLION_CONTEXT_PLUGIN=0`.
|
|
112
|
-
|
|
113
|
-
Via the launcher you never need `plugin install`: `bili opencode` injects
|
|
114
|
-
its plugin automatically (temp `OPENCODE_CONFIG`), claude/codex get the
|
|
115
|
-
MCP shell with `BILI_LAUNCHER_PLUGIN=1`, and pi/omp/hermes ride the
|
|
116
|
-
wire-injected tools.
|
|
117
|
-
|
|
118
|
-
### Option 0 — Launcher (`bili pi` / `bili codex` / `bili claude` / `bili omp` / `bili opencode` / `bili hermes`)
|
|
52
|
+
### Option 1 — Launcher (`bili pi` / `bili codex` / `bili claude` / `bili omp` / `bili opencode` / `bili hermes`)
|
|
119
53
|
|
|
120
54
|
The launcher wraps a client in one command: it starts a proxy on an
|
|
121
55
|
independent port (a fresh instance is always spawned — a port is never
|
|
@@ -128,123 +62,15 @@ and blind-tunnel everything else.
|
|
|
128
62
|
|
|
129
63
|
```bash
|
|
130
64
|
bili pi # launch pi through the proxy
|
|
131
|
-
bili pi -- print "hi" # args after the client are passed through
|
|
132
|
-
bili pi-test # clean pi (extensions off) — proxy owns compression, no double-compress
|
|
133
65
|
bili codex # launch codex through the proxy
|
|
134
66
|
bili claude # launch claude through the proxy
|
|
135
|
-
bili omp # pi-style: MITM env +
|
|
67
|
+
bili omp # pi-style: MITM env + persistent overlay home (~/.omp/agent-bili, real config untouched)
|
|
136
68
|
bili opencode # MITM for HTTPS + temp opencode.json (/bili/ for HTTP) + thin /acp plugin
|
|
137
|
-
bili hermes # no MITM possible (certifi CA) —
|
|
138
|
-
bili test pi # quick end-to-end smoke test of the pi path
|
|
69
|
+
bili hermes # no MITM possible (certifi CA) — persistent overlay home (~/.hermes-bili), all traffic /bili/
|
|
139
70
|
bili pi --mitm-domain api.foo.com # add a domain to the MITM whitelist
|
|
140
71
|
```
|
|
141
72
|
|
|
142
|
-
|
|
143
|
-
additionally injects a single `bili` MCP server (`--mcp-config` for claude,
|
|
144
|
-
`-c mcp_servers.bili.*` for codex — both ephemeral, nothing written to host
|
|
145
|
-
config). The traffic route is **unchanged by default** — the transparent-
|
|
146
|
-
MITM proxy as before — so existing setups keep working exactly as they did
|
|
147
|
-
(OAuth-subscription traffic, custom relay endpoints). Opt in to **direct URL
|
|
148
|
-
routing** (`BILI_LAUNCHER_DIRECT=1`) to drop MITM/CA trust entirely (claude's
|
|
149
|
-
`ANTHROPIC_BASE_URL` / codex's provider `base_url` pointing at the `/bili/`
|
|
150
|
-
prefix); the launcher prints a warning when direct mode changes your traffic
|
|
151
|
-
route. The result is the native-plugin experience of [PLUGIN.md](PLUGIN.md)
|
|
152
|
-
with zero setup: the four ACP tools appear as native MCP tools, executed on
|
|
153
|
-
the proxy under the session lock, while the proxy keeps state, folding,
|
|
154
|
-
philosophy prompt and nudges. Session binding is automatic — claude passes
|
|
155
|
-
its session id to MCP children and on every request; codex spawns bind on
|
|
156
|
-
first sight. Plugin mode is opt-in while host-flag compatibility soaks: set
|
|
157
|
-
`BILI_LAUNCHER_PLUGIN=1` to enable the native MCP tools (verified with
|
|
158
|
-
claude 2.1.227 / codex 0.147.0; `BILI_LAUNCHER_PLUGIN=0` forces the plain
|
|
159
|
-
wire-injected launcher once the default flips on).
|
|
160
|
-
`BILI_LAUNCHER_DIRECT=1` is an opt-in, not an opt-out.
|
|
161
|
-
|
|
162
|
-
Mode matrix:
|
|
163
|
-
|
|
164
|
-
| Mode | Tools surface | Setup | When |
|
|
165
|
-
|------|--------------|-------|------|
|
|
166
|
-
| Launcher + MCP (`BILI_LAUNCHER_PLUGIN=1`) | native MCP tools | one env var | best UX; opt-in while soaking |
|
|
167
|
-
| Launcher wire mode (default for claude/codex) | proxy-injected wire tools | none — just `bili claude` / `bili codex` | default until plugin mode soaks |
|
|
168
|
-
| Manual plugin (pi etc.) | agent-side plugin | install plugin | hosts with plugin APIs |
|
|
169
|
-
| Manual baseURL | proxy-injected wire tools | edit client config | exotic hosts |
|
|
170
|
-
|
|
171
|
-
How the client is pointed at the proxy (set automatically in the child env):
|
|
172
|
-
|
|
173
|
-
| Client | Proxy redirect | CA trust env var |
|
|
174
|
-
|-------------|---------------------|-------------------------|
|
|
175
|
-
| pi | `HTTPS_PROXY` | `NODE_EXTRA_CA_CERTS` |
|
|
176
|
-
| claude | `HTTPS_PROXY` (undici ignores it → `ANTHROPIC_BASE_URL` `/bili/` ride-along) | `NODE_EXTRA_CA_CERTS` |
|
|
177
|
-
| codex | `HTTPS_PROXY` | `SSL_CERT_FILE` |
|
|
178
|
-
| omp | `HTTPS_PROXY` | `NODE_EXTRA_CA_CERTS` |
|
|
179
|
-
| opencode | `HTTPS_PROXY` | `NODE_EXTRA_CA_CERTS` |
|
|
180
|
-
| hermes | `HERMES_HOME` (temp `config.yaml`, every upstream `/bili/`) | — (no MITM: httpx builds its own CA bundle) |
|
|
181
|
-
|
|
182
|
-
`NODE_EXTRA_CA_CERTS` *appends* to the built-in trust store, so it points at
|
|
183
|
-
the MITM root alone (`root-ca.pem`). `SSL_CERT_FILE` *replaces* the default
|
|
184
|
-
CA bundle, so for codex it points at `combined-ca.pem` — a bundle containing
|
|
185
|
-
the MITM root **plus** the system/Node public roots — keeping pip/git/curl
|
|
186
|
-
style TLS (blind-tunnelled, real certificates) working inside the child env
|
|
187
|
-
(#152).
|
|
188
|
-
|
|
189
|
-
The real upstream HTTPS hosts are **discovered by reading** (never editing)
|
|
190
|
-
the client's own config, so whatever you already have set up keeps working:
|
|
191
|
-
|
|
192
|
-
| Client | Read from |
|
|
193
|
-
|-------------|----------------------------------------------|
|
|
194
|
-
| Pi | `~/.pi/agent/models.json` — each provider's `baseUrl` |
|
|
195
|
-
| Codex | `~/.codex/config.toml` — each `[model_providers.<name>]` `base_url` (+ top-level `openai_base_url`) |
|
|
196
|
-
| Claude Code | hardcoded `api.anthropic.com` (no per-config upstream) |
|
|
197
|
-
| omp | `~/.omp/agent/models.yml` — each provider's `baseUrl` |
|
|
198
|
-
| opencode | `~/.config/opencode/opencode.json` — each provider's `options.baseURL` |
|
|
199
|
-
| hermes | `~/.hermes/config.yaml` — each provider's `api:`/`base_url:` endpoint |
|
|
200
|
-
|
|
201
|
-
Only **HTTPS** hosts are MITM'd (a self-signed CA can't intercept plaintext
|
|
202
|
-
anyway); HTTP / `localhost` / `127.0.0.1` providers used to go direct, but are
|
|
203
|
-
now auto-proxied too. Both schemes are covered with no config edits:
|
|
204
|
-
|
|
205
|
-
- **HTTPS upstreams → cert MITM.** The MITM CA cert is the proxy's own root
|
|
206
|
-
(`~/.local/share/billion-context/ca/root-ca.pem`, generated lazily); the
|
|
207
|
-
client must trust it — pi/claude honor `NODE_EXTRA_CA_CERTS`, codex honors
|
|
208
|
-
`SSL_CERT_FILE` (which points at `combined-ca.pem`, see above). Compression
|
|
209
|
-
is injected on the intercepted TLS stream.
|
|
210
|
-
- **HTTP upstreams → `/bili/` baseURL rewrite** (since plaintext can't be
|
|
211
|
-
MITM'd). The launcher rewrites the client's base URL through the client's own
|
|
212
|
-
mechanism, leaving its config files untouched: codex via `-c key=value` flags,
|
|
213
|
-
claude via the `ANTHROPIC_BASE_URL` env var, pi via an isolated
|
|
214
|
-
`PI_CODING_AGENT_DIR` pointing at a temp copy of the pi home with a rewritten
|
|
215
|
-
`models.json` (`auth.json` and the rest are symlinked through unchanged; the
|
|
216
|
-
temp dir is removed when the client exits).
|
|
217
|
-
|
|
218
|
-
`--mitm-domain <domain>` (repeatable) adds extra domains to the whitelist
|
|
219
|
-
beyond what auto-discovery finds — useful for hosts the client fetches at
|
|
220
|
-
runtime rather than from its config file. The proxy port defaults to `8787`;
|
|
221
|
-
if it's taken, a free port is chosen automatically. Use `--passthrough` /
|
|
222
|
-
`--debug` / `--no-auto-update` just like plain `bili`.
|
|
223
|
-
|
|
224
|
-
For clients whose config can't be pointed at the proxy through env vars, the
|
|
225
|
-
launcher writes an **isolated temp copy** of the client config with the
|
|
226
|
-
discovered upstreams rewritten and points the client at it — the real config
|
|
227
|
-
is never touched, and the temp dir is removed when the client exits:
|
|
228
|
-
|
|
229
|
-
- **pi / omp** — an isolated `PI_CODING_AGENT_DIR` whose `models.json` /
|
|
230
|
-
`models.yml` rewrites HTTP upstreams to the `/bili/` form (HTTPS upstreams
|
|
231
|
-
ride cert-MITM; everything else in the real home is symlinked through).
|
|
232
|
-
- **opencode** — `OPENCODE_CONFIG` pointing at a full copy of `opencode.json`
|
|
233
|
-
with HTTP upstreams `/bili/`-rewritten **and** the thin `bili` `/acp`
|
|
234
|
-
status plugin appended to `plugin` (`BILLION_CONTEXT_PROXY` makes a host
|
|
235
|
-
opencode-acp plugin self-disable so the proxy owns the ACP tools).
|
|
236
|
-
- **hermes** — cert MITM is impossible (httpx builds its own CA bundle from
|
|
237
|
-
certifi and ignores `SSL_CERT_FILE`), so **every** upstream is rewritten to
|
|
238
|
-
the `/bili/` form in an isolated `HERMES_HOME` (`config.yaml` copy;
|
|
239
|
-
skills/memories/sessions stay shared via symlinks). No plugin — hermes has
|
|
240
|
-
no plugin API; wire-injected tools ride the proxied stream.
|
|
241
|
-
|
|
242
|
-
> **Note:** the launcher ties the proxy's lifetime to the client — when the
|
|
243
|
-
> client exits, the proxy it started is stopped. Each `bili <client>` spawns
|
|
244
|
-
> its own fresh proxy instance; an independently started `bili` on the same
|
|
245
|
-
> port is never reused.
|
|
246
|
-
|
|
247
|
-
### Option A — Zero-config (`/bili/` prefix)
|
|
73
|
+
### Option 2 — URL change (`/bili/` prefix)
|
|
248
74
|
|
|
249
75
|
Start the proxy:
|
|
250
76
|
|
|
@@ -445,52 +271,9 @@ recommended** for many concurrent conversations because of the collision
|
|
|
445
271
|
risk — until pi grows its own session-id signal. For pi multi-agent use,
|
|
446
272
|
pass an explicit `x-acp-session` header per conversation to avoid collisions.
|
|
447
273
|
|
|
448
|
-
### Codex subagents get their own compression namespace (#150)
|
|
449
|
-
|
|
450
|
-
Codex subagents (e.g. the `guardian_subagent` approval reviewer) reuse the
|
|
451
|
-
main conversation's `session_id`, so on the wire they look like the same
|
|
452
|
-
session. Without care their requests inherit the main conversation's
|
|
453
|
-
compression state — a subagent turn can get its context folded (losing the
|
|
454
|
-
verbatim user authorization it must read back) and the two roles' usage
|
|
455
|
-
estimates pollute each other.
|
|
456
|
-
|
|
457
|
-
billion-context detects this via the `instructions` field: subagent requests
|
|
458
|
-
carry their own role prompt. The **first** instructions seen for a
|
|
459
|
-
conversation anchor the main namespace (stable even if the main prompt
|
|
460
|
-
drifts); any other instructions value maps to a separate `|sub:` namespace
|
|
461
|
-
with its own empty compression state. Subagent requests are self-contained
|
|
462
|
-
replays, so the fresh namespace is lossless — and the web UI's session list
|
|
463
|
-
shows the two namespaces as separate sessions sharing the same client label.
|
|
464
|
-
|
|
465
|
-
### Sessions depend on the proxy (#151)
|
|
466
|
-
|
|
467
|
-
Compression state (blocks, summaries, original message cache) lives **in the
|
|
468
|
-
proxy**, not in the client. The client's own local history is the full
|
|
469
|
-
uncompressed view. Two consequences:
|
|
470
|
-
|
|
471
|
-
- If you point the client back at the real upstream (or stop the proxy), the
|
|
472
|
-
client replays its **full local history** every turn. After a long
|
|
473
|
-
compressed session this can exceed the model's context window
|
|
474
|
-
(`context_window_exceeded`).
|
|
475
|
-
- There is no way to "unpack" a compression block into the client's local
|
|
476
|
-
history — the client never saw the compressed form.
|
|
477
|
-
|
|
478
|
-
**Migrating off the proxy:** export the session and paste it into a fresh
|
|
479
|
-
conversation as a handoff:
|
|
480
|
-
|
|
481
|
-
```bash
|
|
482
|
-
bili export # list persisted sessions (id, label, blocks)
|
|
483
|
-
bili export <id|label> # print a Markdown handoff (block summaries)
|
|
484
|
-
bili export <id> --full # include the original messages per block
|
|
485
|
-
bili export <id> --full --output handoff.md
|
|
486
|
-
```
|
|
487
|
-
|
|
488
|
-
Then start a new conversation in the client (direct to upstream) and paste
|
|
489
|
-
the handoff doc as the opening context.
|
|
490
|
-
|
|
491
274
|
## Status
|
|
492
275
|
|
|
493
|
-
Early. Protocol handling and compression work against mock tests (
|
|
276
|
+
Early. Protocol handling and compression work against mock tests (500+ passing). Real-model integration testing is the next milestone. Expect rough edges.
|
|
494
277
|
|
|
495
278
|
See [billion-context-pi](https://github.com/ranxianglei/billion-context-pi) for the pi-extension mode (in-process, tighter integration, the reference implementation).
|
|
496
279
|
|
package/README.zh-CN.md
CHANGED
|
@@ -62,10 +62,6 @@ bili opencode # HTTPS 走 MITM + 临时 opencode.json(HT
|
|
|
62
62
|
bili hermes # 无法 MITM(certifi CA)—— 隔离 HERMES_HOME,全部流量 /bili/
|
|
63
63
|
bili pi --mitm-domain api.foo.com # 向 MITM 白名单追加域名
|
|
64
64
|
```
|
|
65
|
-
注意,以下客户端需要执行`bili plugin install`以获得原生体验
|
|
66
|
-
```bash
|
|
67
|
-
bili plugin install pi # 必需: launcher 对 pi/omp 不注入 MCP,install 是原生工具 + /acp 的唯一途径
|
|
68
|
-
```
|
|
69
65
|
|
|
70
66
|
|
|
71
67
|
### 方式 2 —— 改url(`/bili/` 前缀)
|
|
@@ -226,7 +222,7 @@ Windows 下会自动发现常见 Clash/Mihomo 静态系统代理;Web UI 会显
|
|
|
226
222
|
|
|
227
223
|
## 状态
|
|
228
224
|
|
|
229
|
-
早期。协议处理和压缩已通过 mock 测试(
|
|
225
|
+
早期。协议处理和压缩已通过 mock 测试(500+ 项通过)。真实模型集成测试是下一里程碑。预期会有粗糙的地方。
|
|
230
226
|
|
|
231
227
|
pi 扩展模式(进程内、更紧密集成、参考实现)见 [billion-context-pi](https://github.com/ranxianglei/billion-context-pi)。
|
|
232
228
|
|
package/dist/agent/omp.js
CHANGED
|
@@ -85,6 +85,12 @@ async function fetchStatus(proxyBase, conversationId) {
|
|
|
85
85
|
if (!ok || !json || typeof json !== "object") return void 0;
|
|
86
86
|
return json;
|
|
87
87
|
}
|
|
88
|
+
async function fetchProxyVersion(proxyBase) {
|
|
89
|
+
const { ok, json } = await fetchJson(`${proxyBase}/__bili/plugin/manifest`, void 0, STATUS_TIMEOUT_MS);
|
|
90
|
+
if (!ok || !json || typeof json !== "object") return void 0;
|
|
91
|
+
const version = json.version;
|
|
92
|
+
return typeof version === "string" && version.length > 0 ? version : void 0;
|
|
93
|
+
}
|
|
88
94
|
|
|
89
95
|
// src/agent/pi.ts
|
|
90
96
|
function agentName(override) {
|
|
@@ -207,7 +213,20 @@ function createBiliPlugin(agentOverride) {
|
|
|
207
213
|
return;
|
|
208
214
|
}
|
|
209
215
|
if (status === void 0) {
|
|
210
|
-
|
|
216
|
+
let version;
|
|
217
|
+
try {
|
|
218
|
+
version = await fetchProxyVersion(proxyBase);
|
|
219
|
+
} catch {
|
|
220
|
+
version = void 0;
|
|
221
|
+
}
|
|
222
|
+
if (version !== void 0) {
|
|
223
|
+
notify(
|
|
224
|
+
`billion-context@${version} \u2014 proxy connected, compression armed. No model request in this conversation yet; send one, then run /acp again.`,
|
|
225
|
+
"info"
|
|
226
|
+
);
|
|
227
|
+
} else {
|
|
228
|
+
notify("bili: no ACP session yet (send a model request first, then run /acp)", "warning");
|
|
229
|
+
}
|
|
211
230
|
return;
|
|
212
231
|
}
|
|
213
232
|
const panel = typeof status.panel === "string" ? status.panel : void 0;
|
package/dist/agent/omp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/agent/shared.ts","../../src/agent/pi.ts","../../src/agent/omp.ts"],"sourcesContent":["// Shared thin-plugin core for agent-side extensions (\"内外呼应\", issue #1).\n// The agent plugin is a PURE PROTOCOL CLIENT: no acp-kernel import, no\n// compression logic. The proxy stays the single compression authority; the\n// plugin only (1) detects the proxy, (2) fetches the tool manifest (single\n// source of truth), (3) forwards tool executes, (4) reads status. Same\n// package as the proxy ⇒ same version ⇒ no kernel-skew bug class.\n\nexport type ManifestTool = {\n name: string;\n description?: string;\n inputSchema: unknown;\n};\n\nconst MANIFEST_TIMEOUT_MS = 5000;\nconst TOOL_TIMEOUT_MS = 60000;\nconst STATUS_TIMEOUT_MS = 5000;\n\n/** Detect the proxy from a provider baseUrl's `/bili/` zero-config prefix.\n * The real prefix embeds the full upstream URL (`/bili/https://…`), so the\n * check requires `bili` as the first path segment followed by an http(s)\n * URL — a plain `/foo/bili/` path segment is NOT a bili proxy.\n * Returns the proxy origin (scheme//host) the request will actually hit. */\nexport function proxyBaseFromUrl(baseUrl: string | undefined): string | undefined {\n if (!baseUrl) return undefined;\n try {\n const url = new URL(baseUrl);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return undefined;\n const segments = url.pathname.split(\"/\").filter((s) => s.length > 0);\n if (segments[0] !== \"bili\") return undefined;\n const rest = url.pathname.slice(url.pathname.indexOf(\"bili\") + \"bili\".length);\n if (!/^\\/https?:\\/\\//.test(rest)) return undefined;\n return `${url.protocol}//${url.host}`;\n } catch {\n return undefined;\n }\n}\n\n/** MITM transparent mode has no `/bili/` prefix; the proxy's launcher exports\n * BILLION_CONTEXT_PROXY. A stale value surfaces as a tool-forward error. */\nexport function proxyBaseFromEnv(): string | undefined {\n const raw = process.env.BILLION_CONTEXT_PROXY?.trim();\n if (!raw) return undefined;\n try {\n const url = new URL(raw);\n return url.protocol === \"http:\" || url.protocol === \"https:\" ? `${url.protocol}//${url.host}` : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function detectProxyBase(baseUrl: string | undefined): string | undefined {\n if (process.env.BILLION_CONTEXT_PLUGIN === \"0\") return undefined;\n return proxyBaseFromUrl(baseUrl) ?? proxyBaseFromEnv();\n}\n\nasync function fetchJson(url: string, init: RequestInit | undefined, timeoutMs: number, externalSignal?: AbortSignal): Promise<{ ok: boolean; status: number; json: unknown }> {\n const ac = new AbortController();\n // An already-aborted external signal never fires its \"abort\" event, so\n // forward the state directly — otherwise only the timeout could stop\n // the request, turning an instant cancel into a timeout wait.\n if (externalSignal?.aborted) ac.abort();\n const timer = setTimeout(() => ac.abort(), timeoutMs);\n const onExternalAbort = () => ac.abort();\n externalSignal?.addEventListener(\"abort\", onExternalAbort, { once: true });\n try {\n let res: Response;\n try {\n res = await fetch(url, { ...init, signal: ac.signal });\n } catch (err) {\n if (ac.signal.aborted && !externalSignal?.aborted) throw new Error(`timeout after ${timeoutMs}ms: ${url}`);\n throw err;\n }\n const text = await res.text();\n let json: unknown = undefined;\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n return { ok: res.ok, status: res.status, json };\n } finally {\n clearTimeout(timer);\n externalSignal?.removeEventListener(\"abort\", onExternalAbort);\n }\n}\n\nexport async function fetchManifest(proxyBase: string): Promise<ManifestTool[]> {\n const { ok, status, json } = await fetchJson(`${proxyBase}/__bili/plugin/manifest`, undefined, MANIFEST_TIMEOUT_MS);\n if (!ok || !json || typeof json !== \"object\") throw new Error(`manifest fetch failed: ${status}`);\n const data = json as { tools?: { anthropic?: { name?: string; description?: string; input_schema?: unknown }[] } };\n const tools = (data.tools?.anthropic ?? []).filter((t): t is { name: string; description?: string; input_schema?: unknown } => typeof t.name === \"string\");\n if (tools.length === 0) throw new Error(\"manifest served no anthropic tools\");\n return tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.input_schema ?? { type: \"object\", properties: {} } }));\n}\n\nexport async function forwardTool(proxyBase: string, conversationId: string, tool: string, args: unknown, signal?: AbortSignal): Promise<string> {\n const { ok, status, json } = await fetchJson(`${proxyBase}/__bili/plugin/tool`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ conversationId, tool, args: args ?? {} }),\n }, TOOL_TIMEOUT_MS, signal);\n const data = json as { ok?: boolean; result?: string; error?: string } | undefined;\n if (!ok || !data?.ok) {\n throw new Error(`bili proxy tool ${tool} failed (${status}): ${data?.error ?? \"unknown error\"}`);\n }\n return data.result ?? \"\";\n}\n\n/** Soft-fail by design: the status read is best-effort UI data; undefined\n * means \"no data\" whether the proxy is down or the session is unknown. */\nexport async function fetchStatus(proxyBase: string, conversationId: string): Promise<Record<string, unknown> | undefined> {\n const { ok, json } = await fetchJson(`${proxyBase}/__bili/plugin/status?conversationId=${encodeURIComponent(conversationId)}`, undefined, STATUS_TIMEOUT_MS);\n if (!ok || !json || typeof json !== \"object\") return undefined;\n return json as Record<string, unknown>;\n}\n","// Thin agent extension for pi and omp (\"内外呼应\", issue #1). Loaded by pi\n// via the package.json `pi` manifest (dist/agent/pi.js) or by omp via the\n// config.yml `extensions:` list (dist/agent/omp.js). pi and omp share the\n// ExtensionFactory API shape, so one factory serves both; types below are\n// minimal structural declarations — the bundled artifact imports NOTHING\n// from the host at runtime (the host duck-types us in).\n\nimport { detectProxyBase, fetchManifest, forwardTool, fetchStatus, type ManifestTool } from \"./shared.js\";\n\ntype Ctx = {\n sessionManager?: { getSessionId?: () => string } | undefined;\n model?: { contextWindow?: number; baseUrl?: string } | undefined;\n cwd?: string;\n};\n\ntype TextBlock = { type: \"text\"; text: string };\ntype ToolResult = { content: TextBlock[]; isError?: boolean };\n\ntype ToolDefinition = {\n name: string;\n description?: string;\n parameters: unknown;\n execute: (toolCallId: string, params: Record<string, unknown>, signal: AbortSignal | undefined, onUpdate: ((u: unknown) => void) | undefined, ctx: Ctx) => Promise<ToolResult>;\n};\n\ntype CommandCtx = {\n sessionManager?: { getSessionId?: () => string } | undefined;\n model?: { contextWindow?: number; baseUrl?: string } | undefined;\n ui?: { notify?: (message: string, type?: string) => void } | undefined;\n};\n\ntype ExtensionAPI = {\n on: (event: string, handler: (event: never, ctx: Ctx) => unknown) => void;\n registerTool: (tool: ToolDefinition) => void;\n registerCommand?: (name: string, options: { description?: string; handler: (args: string, ctx: CommandCtx) => void | Promise<void> }) => void;\n};\n\nfunction agentName(override: string | undefined): string {\n if (override) return override;\n return process.env.BILLION_CONTEXT_PLUGIN_AGENT === \"omp\" ? \"omp\" : \"pi\";\n}\n\nfunction proxyBaseForCtx(ctx: Ctx): string | undefined {\n return detectProxyBase(ctx.model?.baseUrl);\n}\n\nfunction sessionIdOf(ctx: Ctx): string | undefined {\n try {\n const sid = ctx.sessionManager?.getSessionId?.();\n return typeof sid === \"string\" ? sid : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction fmtTok(n: number): string {\n if (n < 1000) return String(n);\n if (n < 1_000_000) return `${(n / 1000).toFixed(1)}K`;\n return `${(n / 1_000_000).toFixed(2)}M`;\n}\n\nfunction renderAcpStatus(s: Record<string, unknown>): string {\n const num = (v: unknown): number | null => (typeof v === \"number\" && Number.isFinite(v) ? v : null);\n const contextTokens = num(s.contextTokens);\n const contextLimit = num(s.contextLimit);\n const inputTokens = num(s.inputTokens);\n const outputTokens = num(s.outputTokens);\n const cachedTokens = num(s.cachedTokens);\n const requests = num(s.requests);\n const blocks = Array.isArray(s.blocks) ? (s.blocks as Array<{ tier?: number; active?: boolean }>) : [];\n const activeBlocks = blocks.filter((b) => b.active === true).length;\n const lines: string[] = [\"📊 ACP status\"];\n if (contextTokens !== null) {\n const pct = contextLimit !== null && contextLimit > 0 ? ` (${((contextTokens / contextLimit) * 100).toFixed(1)}%)` : \"\";\n lines.push(` context: ${fmtTok(contextTokens)}${contextLimit !== null ? ` / ${fmtTok(contextLimit)}` : \"\"}${pct}`);\n }\n if (inputTokens !== null || outputTokens !== null || cachedTokens !== null) {\n lines.push(` in/out/cached: ${fmtTok(inputTokens ?? 0)} / ${fmtTok(outputTokens ?? 0)} / ${fmtTok(cachedTokens ?? 0)}`);\n }\n if (requests !== null) lines.push(` requests: ${requests}`);\n if (blocks.length > 0) lines.push(` blocks: ${blocks.length} (${activeBlocks} active)`);\n return lines.join(\"\\n\");\n}\n\nfunction manifestToTool(proxyBase: string, tool: ManifestTool, agent: string): ToolDefinition {\n return {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {\n const conversationId = sessionIdOf(ctx) ?? \"unknown\";\n try {\n const output = await forwardTool(proxyBase, conversationId, tool.name, params, signal);\n return { content: [{ type: \"text\", text: output }] };\n } catch (err) {\n return { content: [{ type: \"text\", text: `bili tool error: ${err instanceof Error ? err.message : String(err)}` }], isError: true };\n }\n },\n };\n}\n\nconst RETRY_INTERVAL_MS = 10000;\n\ntype RegisterState = { sid?: string; toolsReady?: boolean; pending?: Promise<void>; retryAt?: number };\n\nasync function registerTools(pi: ExtensionAPI, ctx: Ctx, state: RegisterState, agent: string): Promise<void> {\n const proxyBase = proxyBaseForCtx(ctx);\n if (proxyBase === undefined) return;\n // Cache on the session id; \"\" (host has no sessionManager) still caches,\n // so a successful registration is not re-fetched on every provider\n // request — the manifest is session-independent anyway.\n const sid = sessionIdOf(ctx) ?? \"\";\n if (sid === state.sid) return;\n if (state.pending !== undefined) return state.pending;\n if (state.retryAt !== undefined && Date.now() < state.retryAt) return;\n state.pending = (async () => {\n let tools: ManifestTool[];\n try {\n tools = await fetchManifest(proxyBase);\n } catch (err) {\n state.retryAt = Date.now() + RETRY_INTERVAL_MS;\n console.error(`bili-plugin(${agent}): manifest fetch failed: ${err instanceof Error ? err.message : String(err)} — retrying in ${RETRY_INTERVAL_MS / 1000}s`);\n return;\n }\n try {\n for (const t of tools) pi.registerTool(manifestToTool(proxyBase, t, agent));\n state.sid = sid;\n state.toolsReady = true;\n state.retryAt = undefined;\n } catch (err) {\n state.sid = undefined;\n state.retryAt = Date.now() + RETRY_INTERVAL_MS;\n console.error(`bili-plugin(${agent}): tool registration deferred (${err instanceof Error ? err.message : String(err)}) — retrying in ${RETRY_INTERVAL_MS / 1000}s`);\n }\n })();\n try {\n await state.pending;\n } finally {\n state.pending = undefined;\n }\n}\n\nexport function createBiliPlugin(agentOverride?: string): (pi: ExtensionAPI) => void {\n return function biliPlugin(pi: ExtensionAPI): void {\n const agent = agentName(agentOverride);\n const state: RegisterState = {};\n if (typeof pi.registerCommand === \"function\") {\n pi.registerCommand(\"acp\", {\n description: \"Show ACP context-compression status for this session\",\n handler: async (_args, ctx) => {\n const notify = (message: string, type?: string): void => {\n try {\n ctx.ui?.notify?.(message, type);\n } catch {\n // host UI unavailable — the command is best-effort\n }\n };\n const proxyBase = detectProxyBase(ctx.model?.baseUrl);\n if (proxyBase === undefined) {\n notify(\"bili: no proxy detected (run via `bili <client>` or set a /bili/ baseURL)\", \"warning\");\n return;\n }\n const conversationId = sessionIdOf(ctx) ?? \"unknown\";\n let status: Record<string, unknown> | undefined;\n try {\n status = await fetchStatus(proxyBase, conversationId);\n } catch (err) {\n notify(`bili: status fetch failed: ${err instanceof Error ? err.message : String(err)}`, \"error\");\n return;\n }\n if (status === undefined) {\n notify(\"bili: no ACP session yet (send a model request first, then run /acp)\", \"warning\");\n return;\n }\n const panel = typeof status.panel === \"string\" ? status.panel : undefined;\n notify(panel ?? renderAcpStatus(status), \"info\");\n },\n });\n }\n pi.on(\"before_provider_headers\", (event, ctx) => {\n try {\n if (proxyBaseForCtx(ctx) === undefined) return;\n const headers = (event as unknown as { headers?: Record<string, string> }).headers;\n if (headers === undefined || typeof headers !== \"object\" || Array.isArray(headers)) return;\n // The x-bili-plugin marker tells the proxy \"the client owns the\n // ACP tools natively — skip wire-level injection\". Stamping it\n // before registerTools() finishes would send round 1 out with\n // NO ACP tools (the first provider request races the manifest\n // fetch). Claim ownership only once tools are registered;\n // until then the request rides the proxy's wire mode. A\n // permanently failing manifest fetch keeps us in wire mode —\n // a graceful fallback rather than a tool-less session.\n if (state.toolsReady === true) {\n const sid = sessionIdOf(ctx);\n if (sid !== undefined) headers[\"x-bili-plugin-conversation\"] = sid;\n headers[\"x-bili-plugin\"] = agent;\n const window = ctx.model?.contextWindow;\n if (typeof window === \"number\" && Number.isFinite(window) && window > 0) {\n headers[\"x-bili-plugin-context-window\"] = String(Math.floor(window));\n }\n }\n } catch (err) {\n console.error(`bili-plugin(${agent}): header stamp skipped (${err instanceof Error ? err.message : String(err)})`);\n }\n void registerTools(pi, ctx, state, agent).catch((err: unknown) => console.error(`bili-plugin(${agent}): ${err instanceof Error ? err.message : String(err)}`));\n });\n pi.on(\"session_start\", (_event, ctx) => {\n state.sid = undefined;\n void registerTools(pi, ctx, state, agent).catch((err: unknown) => console.error(`bili-plugin(${agent}): ${err instanceof Error ? err.message : String(err)}`));\n });\n };\n}\n\nexport default createBiliPlugin();\n\nexport { fetchStatus };\n","import { createBiliPlugin } from \"./pi.js\";\n\nexport default createBiliPlugin(\"omp\");\n"],"mappings":";;;;AAaA,IAAM,sBAAsB;AAC5B,IAAM,kBAAkB;AACxB,IAAM,oBAAoB;AAOnB,SAAS,iBAAiB,SAAiD;AAC9E,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI;AACA,UAAM,MAAM,IAAI,IAAI,OAAO;AAC3B,QAAI,IAAI,aAAa,WAAW,IAAI,aAAa,SAAU,QAAO;AAClE,UAAM,WAAW,IAAI,SAAS,MAAM,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AACnE,QAAI,SAAS,CAAC,MAAM,OAAQ,QAAO;AACnC,UAAM,OAAO,IAAI,SAAS,MAAM,IAAI,SAAS,QAAQ,MAAM,IAAI,OAAO,MAAM;AAC5E,QAAI,CAAC,iBAAiB,KAAK,IAAI,EAAG,QAAO;AACzC,WAAO,GAAG,IAAI,QAAQ,KAAK,IAAI,IAAI;AAAA,EACvC,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAIO,SAAS,mBAAuC;AACnD,QAAM,MAAM,QAAQ,IAAI,uBAAuB,KAAK;AACpD,MAAI,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C,YAAM,MAAM;AACZ,WAAK,cAAc,IAAI,KAAK,OAAO,KAAK,EAAE,MAAM,CAAC,QAAiB,QAAQ,MAAM,eAAe,KAAK,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE,CAAC;AAAA,IACjK,CAAC;AAAA,EACL;AACJ;AAEA,IAAO,aAAQ,iBAAiB;;;ACnNhC,IAAO,cAAQ,iBAAiB,KAAK;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/agent/shared.ts","../../src/agent/pi.ts","../../src/agent/omp.ts"],"sourcesContent":["// Shared thin-plugin core for agent-side extensions (\"内外呼应\", issue #1).\n// The agent plugin is a PURE PROTOCOL CLIENT: no acp-kernel import, no\n// compression logic. The proxy stays the single compression authority; the\n// plugin only (1) detects the proxy, (2) fetches the tool manifest (single\n// source of truth), (3) forwards tool executes, (4) reads status. Same\n// package as the proxy ⇒ same version ⇒ no kernel-skew bug class.\n\nexport type ManifestTool = {\n name: string;\n description?: string;\n inputSchema: unknown;\n};\n\nconst MANIFEST_TIMEOUT_MS = 5000;\nconst TOOL_TIMEOUT_MS = 60000;\nconst STATUS_TIMEOUT_MS = 5000;\n\n/** Detect the proxy from a provider baseUrl's `/bili/` zero-config prefix.\n * The real prefix embeds the full upstream URL (`/bili/https://…`), so the\n * check requires `bili` as the first path segment followed by an http(s)\n * URL — a plain `/foo/bili/` path segment is NOT a bili proxy.\n * Returns the proxy origin (scheme//host) the request will actually hit. */\nexport function proxyBaseFromUrl(baseUrl: string | undefined): string | undefined {\n if (!baseUrl) return undefined;\n try {\n const url = new URL(baseUrl);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return undefined;\n const segments = url.pathname.split(\"/\").filter((s) => s.length > 0);\n if (segments[0] !== \"bili\") return undefined;\n const rest = url.pathname.slice(url.pathname.indexOf(\"bili\") + \"bili\".length);\n if (!/^\\/https?:\\/\\//.test(rest)) return undefined;\n return `${url.protocol}//${url.host}`;\n } catch {\n return undefined;\n }\n}\n\n/** MITM transparent mode has no `/bili/` prefix; the proxy's launcher exports\n * BILLION_CONTEXT_PROXY. A stale value surfaces as a tool-forward error. */\nexport function proxyBaseFromEnv(): string | undefined {\n const raw = process.env.BILLION_CONTEXT_PROXY?.trim();\n if (!raw) return undefined;\n try {\n const url = new URL(raw);\n return url.protocol === \"http:\" || url.protocol === \"https:\" ? `${url.protocol}//${url.host}` : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function detectProxyBase(baseUrl: string | undefined): string | undefined {\n if (process.env.BILLION_CONTEXT_PLUGIN === \"0\") return undefined;\n return proxyBaseFromUrl(baseUrl) ?? proxyBaseFromEnv();\n}\n\nasync function fetchJson(url: string, init: RequestInit | undefined, timeoutMs: number, externalSignal?: AbortSignal): Promise<{ ok: boolean; status: number; json: unknown }> {\n const ac = new AbortController();\n // An already-aborted external signal never fires its \"abort\" event, so\n // forward the state directly — otherwise only the timeout could stop\n // the request, turning an instant cancel into a timeout wait.\n if (externalSignal?.aborted) ac.abort();\n const timer = setTimeout(() => ac.abort(), timeoutMs);\n const onExternalAbort = () => ac.abort();\n externalSignal?.addEventListener(\"abort\", onExternalAbort, { once: true });\n try {\n let res: Response;\n try {\n res = await fetch(url, { ...init, signal: ac.signal });\n } catch (err) {\n if (ac.signal.aborted && !externalSignal?.aborted) throw new Error(`timeout after ${timeoutMs}ms: ${url}`);\n throw err;\n }\n const text = await res.text();\n let json: unknown = undefined;\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n return { ok: res.ok, status: res.status, json };\n } finally {\n clearTimeout(timer);\n externalSignal?.removeEventListener(\"abort\", onExternalAbort);\n }\n}\n\nexport async function fetchManifest(proxyBase: string): Promise<ManifestTool[]> {\n const { ok, status, json } = await fetchJson(`${proxyBase}/__bili/plugin/manifest`, undefined, MANIFEST_TIMEOUT_MS);\n if (!ok || !json || typeof json !== \"object\") throw new Error(`manifest fetch failed: ${status}`);\n const data = json as { tools?: { anthropic?: { name?: string; description?: string; input_schema?: unknown }[] } };\n const tools = (data.tools?.anthropic ?? []).filter((t): t is { name: string; description?: string; input_schema?: unknown } => typeof t.name === \"string\");\n if (tools.length === 0) throw new Error(\"manifest served no anthropic tools\");\n return tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.input_schema ?? { type: \"object\", properties: {} } }));\n}\n\nexport async function forwardTool(proxyBase: string, conversationId: string, tool: string, args: unknown, signal?: AbortSignal): Promise<string> {\n const { ok, status, json } = await fetchJson(`${proxyBase}/__bili/plugin/tool`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ conversationId, tool, args: args ?? {} }),\n }, TOOL_TIMEOUT_MS, signal);\n const data = json as { ok?: boolean; result?: string; error?: string } | undefined;\n if (!ok || !data?.ok) {\n throw new Error(`bili proxy tool ${tool} failed (${status}): ${data?.error ?? \"unknown error\"}`);\n }\n return data.result ?? \"\";\n}\n\n/** Soft-fail by design: the status read is best-effort UI data; undefined\n * means \"no data\" whether the proxy is down or the session is unknown. */\nexport async function fetchStatus(proxyBase: string, conversationId: string): Promise<Record<string, unknown> | undefined> {\n const { ok, json } = await fetchJson(`${proxyBase}/__bili/plugin/status?conversationId=${encodeURIComponent(conversationId)}`, undefined, STATUS_TIMEOUT_MS);\n if (!ok || !json || typeof json !== \"object\") return undefined;\n return json as Record<string, unknown>;\n}\n\n/** Liveness + version probe for status UIs: same loopback origin as the\n * status endpoint, so a 404 status + a live manifest means \"proxy up,\n * conversation not seen yet\" — an armed-but-idle state, not an error. */\nexport async function fetchProxyVersion(proxyBase: string): Promise<string | undefined> {\n const { ok, json } = await fetchJson(`${proxyBase}/__bili/plugin/manifest`, undefined, STATUS_TIMEOUT_MS);\n if (!ok || !json || typeof json !== \"object\") return undefined;\n const version = (json as { version?: unknown }).version;\n return typeof version === \"string\" && version.length > 0 ? version : undefined;\n}\n","// Thin agent extension for pi and omp (\"内外呼应\", issue #1). Loaded by pi\n// via the package.json `pi` manifest (dist/agent/pi.js) or by omp via the\n// config.yml `extensions:` list (dist/agent/omp.js). pi and omp share the\n// ExtensionFactory API shape, so one factory serves both; types below are\n// minimal structural declarations — the bundled artifact imports NOTHING\n// from the host at runtime (the host duck-types us in).\n\nimport { detectProxyBase, fetchManifest, forwardTool, fetchStatus, fetchProxyVersion, type ManifestTool } from \"./shared.js\";\n\ntype Ctx = {\n sessionManager?: { getSessionId?: () => string } | undefined;\n model?: { contextWindow?: number; baseUrl?: string } | undefined;\n cwd?: string;\n};\n\ntype TextBlock = { type: \"text\"; text: string };\ntype ToolResult = { content: TextBlock[]; isError?: boolean };\n\ntype ToolDefinition = {\n name: string;\n description?: string;\n parameters: unknown;\n execute: (toolCallId: string, params: Record<string, unknown>, signal: AbortSignal | undefined, onUpdate: ((u: unknown) => void) | undefined, ctx: Ctx) => Promise<ToolResult>;\n};\n\ntype CommandCtx = {\n sessionManager?: { getSessionId?: () => string } | undefined;\n model?: { contextWindow?: number; baseUrl?: string } | undefined;\n ui?: { notify?: (message: string, type?: string) => void } | undefined;\n};\n\ntype ExtensionAPI = {\n on: (event: string, handler: (event: never, ctx: Ctx) => unknown) => void;\n registerTool: (tool: ToolDefinition) => void;\n registerCommand?: (name: string, options: { description?: string; handler: (args: string, ctx: CommandCtx) => void | Promise<void> }) => void;\n};\n\nfunction agentName(override: string | undefined): string {\n if (override) return override;\n return process.env.BILLION_CONTEXT_PLUGIN_AGENT === \"omp\" ? \"omp\" : \"pi\";\n}\n\nfunction proxyBaseForCtx(ctx: Ctx): string | undefined {\n return detectProxyBase(ctx.model?.baseUrl);\n}\n\nfunction sessionIdOf(ctx: Ctx): string | undefined {\n try {\n const sid = ctx.sessionManager?.getSessionId?.();\n return typeof sid === \"string\" ? sid : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction fmtTok(n: number): string {\n if (n < 1000) return String(n);\n if (n < 1_000_000) return `${(n / 1000).toFixed(1)}K`;\n return `${(n / 1_000_000).toFixed(2)}M`;\n}\n\nfunction renderAcpStatus(s: Record<string, unknown>): string {\n const num = (v: unknown): number | null => (typeof v === \"number\" && Number.isFinite(v) ? v : null);\n const contextTokens = num(s.contextTokens);\n const contextLimit = num(s.contextLimit);\n const inputTokens = num(s.inputTokens);\n const outputTokens = num(s.outputTokens);\n const cachedTokens = num(s.cachedTokens);\n const requests = num(s.requests);\n const blocks = Array.isArray(s.blocks) ? (s.blocks as Array<{ tier?: number; active?: boolean }>) : [];\n const activeBlocks = blocks.filter((b) => b.active === true).length;\n const lines: string[] = [\"📊 ACP status\"];\n if (contextTokens !== null) {\n const pct = contextLimit !== null && contextLimit > 0 ? ` (${((contextTokens / contextLimit) * 100).toFixed(1)}%)` : \"\";\n lines.push(` context: ${fmtTok(contextTokens)}${contextLimit !== null ? ` / ${fmtTok(contextLimit)}` : \"\"}${pct}`);\n }\n if (inputTokens !== null || outputTokens !== null || cachedTokens !== null) {\n lines.push(` in/out/cached: ${fmtTok(inputTokens ?? 0)} / ${fmtTok(outputTokens ?? 0)} / ${fmtTok(cachedTokens ?? 0)}`);\n }\n if (requests !== null) lines.push(` requests: ${requests}`);\n if (blocks.length > 0) lines.push(` blocks: ${blocks.length} (${activeBlocks} active)`);\n return lines.join(\"\\n\");\n}\n\nfunction manifestToTool(proxyBase: string, tool: ManifestTool, agent: string): ToolDefinition {\n return {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {\n const conversationId = sessionIdOf(ctx) ?? \"unknown\";\n try {\n const output = await forwardTool(proxyBase, conversationId, tool.name, params, signal);\n return { content: [{ type: \"text\", text: output }] };\n } catch (err) {\n return { content: [{ type: \"text\", text: `bili tool error: ${err instanceof Error ? err.message : String(err)}` }], isError: true };\n }\n },\n };\n}\n\nconst RETRY_INTERVAL_MS = 10000;\n\ntype RegisterState = { sid?: string; toolsReady?: boolean; pending?: Promise<void>; retryAt?: number };\n\nasync function registerTools(pi: ExtensionAPI, ctx: Ctx, state: RegisterState, agent: string): Promise<void> {\n const proxyBase = proxyBaseForCtx(ctx);\n if (proxyBase === undefined) return;\n // Cache on the session id; \"\" (host has no sessionManager) still caches,\n // so a successful registration is not re-fetched on every provider\n // request — the manifest is session-independent anyway.\n const sid = sessionIdOf(ctx) ?? \"\";\n if (sid === state.sid) return;\n if (state.pending !== undefined) return state.pending;\n if (state.retryAt !== undefined && Date.now() < state.retryAt) return;\n state.pending = (async () => {\n let tools: ManifestTool[];\n try {\n tools = await fetchManifest(proxyBase);\n } catch (err) {\n state.retryAt = Date.now() + RETRY_INTERVAL_MS;\n console.error(`bili-plugin(${agent}): manifest fetch failed: ${err instanceof Error ? err.message : String(err)} — retrying in ${RETRY_INTERVAL_MS / 1000}s`);\n return;\n }\n try {\n for (const t of tools) pi.registerTool(manifestToTool(proxyBase, t, agent));\n state.sid = sid;\n state.toolsReady = true;\n state.retryAt = undefined;\n } catch (err) {\n state.sid = undefined;\n state.retryAt = Date.now() + RETRY_INTERVAL_MS;\n console.error(`bili-plugin(${agent}): tool registration deferred (${err instanceof Error ? err.message : String(err)}) — retrying in ${RETRY_INTERVAL_MS / 1000}s`);\n }\n })();\n try {\n await state.pending;\n } finally {\n state.pending = undefined;\n }\n}\n\nexport function createBiliPlugin(agentOverride?: string): (pi: ExtensionAPI) => void {\n return function biliPlugin(pi: ExtensionAPI): void {\n const agent = agentName(agentOverride);\n const state: RegisterState = {};\n if (typeof pi.registerCommand === \"function\") {\n pi.registerCommand(\"acp\", {\n description: \"Show ACP context-compression status for this session\",\n handler: async (_args, ctx) => {\n const notify = (message: string, type?: string): void => {\n try {\n ctx.ui?.notify?.(message, type);\n } catch {\n // host UI unavailable — the command is best-effort\n }\n };\n const proxyBase = detectProxyBase(ctx.model?.baseUrl);\n if (proxyBase === undefined) {\n notify(\"bili: no proxy detected (run via `bili <client>` or set a /bili/ baseURL)\", \"warning\");\n return;\n }\n const conversationId = sessionIdOf(ctx) ?? \"unknown\";\n let status: Record<string, unknown> | undefined;\n try {\n status = await fetchStatus(proxyBase, conversationId);\n } catch (err) {\n notify(`bili: status fetch failed: ${err instanceof Error ? err.message : String(err)}`, \"error\");\n return;\n }\n if (status === undefined) {\n // 404 from a live proxy = this conversation has sent no\n // model request yet (e.g. /acp right after startup).\n // Probe the manifest to confirm liveness + version and\n // show an armed/idle notice instead of a scary warning.\n let version: string | undefined;\n try {\n version = await fetchProxyVersion(proxyBase);\n } catch {\n version = undefined;\n }\n if (version !== undefined) {\n notify(\n `billion-context@${version} — proxy connected, compression armed. No model request in this conversation yet; send one, then run /acp again.`,\n \"info\",\n );\n } else {\n notify(\"bili: no ACP session yet (send a model request first, then run /acp)\", \"warning\");\n }\n return;\n }\n const panel = typeof status.panel === \"string\" ? status.panel : undefined;\n notify(panel ?? renderAcpStatus(status), \"info\");\n },\n });\n }\n pi.on(\"before_provider_headers\", (event, ctx) => {\n try {\n if (proxyBaseForCtx(ctx) === undefined) return;\n const headers = (event as unknown as { headers?: Record<string, string> }).headers;\n if (headers === undefined || typeof headers !== \"object\" || Array.isArray(headers)) return;\n // The x-bili-plugin marker tells the proxy \"the client owns the\n // ACP tools natively — skip wire-level injection\". Stamping it\n // before registerTools() finishes would send round 1 out with\n // NO ACP tools (the first provider request races the manifest\n // fetch). Claim ownership only once tools are registered;\n // until then the request rides the proxy's wire mode. A\n // permanently failing manifest fetch keeps us in wire mode —\n // a graceful fallback rather than a tool-less session.\n if (state.toolsReady === true) {\n const sid = sessionIdOf(ctx);\n if (sid !== undefined) headers[\"x-bili-plugin-conversation\"] = sid;\n headers[\"x-bili-plugin\"] = agent;\n const window = ctx.model?.contextWindow;\n if (typeof window === \"number\" && Number.isFinite(window) && window > 0) {\n headers[\"x-bili-plugin-context-window\"] = String(Math.floor(window));\n }\n }\n } catch (err) {\n console.error(`bili-plugin(${agent}): header stamp skipped (${err instanceof Error ? err.message : String(err)})`);\n }\n void registerTools(pi, ctx, state, agent).catch((err: unknown) => console.error(`bili-plugin(${agent}): ${err instanceof Error ? err.message : String(err)}`));\n });\n pi.on(\"session_start\", (_event, ctx) => {\n state.sid = undefined;\n void registerTools(pi, ctx, state, agent).catch((err: unknown) => console.error(`bili-plugin(${agent}): ${err instanceof Error ? err.message : String(err)}`));\n });\n };\n}\n\nexport default createBiliPlugin();\n\nexport { fetchStatus };\n","import { createBiliPlugin } from \"./pi.js\";\n\nexport default createBiliPlugin(\"omp\");\n"],"mappings":";;;;AAaA,IAAM,sBAAsB;AAC5B,IAAM,kBAAkB;AACxB,IAAM,oBAAoB;AAOnB,SAAS,iBAAiB,SAAiD;AAC9E,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI;AACA,UAAM,MAAM,IAAI,IAAI,OAAO;AAC3B,QAAI,IAAI,aAAa,WAAW,IAAI,aAAa,SAAU,QAAO;AAClE,UAAM,WAAW,IAAI,SAAS,MAAM,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AACnE,QAAI,SAAS,CAAC,MAAM,OAAQ,QAAO;AACnC,UAAM,OAAO,IAAI,SAAS,MAAM,IAAI,SAAS,QAAQ,MAAM,IAAI,OAAO,MAAM;AAC5E,QAAI,CAAC,iBAAiB,KAAK,IAAI,EAAG,QAAO;AACzC,WAAO,GAAG,IAAI,QAAQ,KAAK,IAAI,IAAI;AAAA,EACvC,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAIO,SAAS,mBAAuC;AACnD,QAAM,MAAM,QAAQ,IAAI,uBAAuB,KAAK;AACpD,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACA,UAAM,MAAM,IAAI,IAAI,GAAG;AACvB,WAAO,IAAI,aAAa,WAAW,IAAI,aAAa,WAAW,GAAG,IAAI,QAAQ,KAAK,IAAI,IAAI,KAAK;AAAA,EACpG,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAEO,SAAS,gBAAgB,SAAiD;AAC7E,MAAI,QAAQ,IAAI,2BAA2B,IAAK,QAAO;AACvD,SAAO,iBAAiB,OAAO,KAAK,iBAAiB;AACzD;AAEA,eAAe,UAAU,KAAa,MA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,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE,CAAC;AAAA,IACjK,CAAC;AACD,OAAG,GAAG,iBAAiB,CAAC,QAAQ,QAAQ;AACpC,YAAM,MAAM;AACZ,WAAK,cAAc,IAAI,KAAK,OAAO,KAAK,EAAE,MAAM,CAAC,QAAiB,QAAQ,MAAM,eAAe,KAAK,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE,CAAC;AAAA,IACjK,CAAC;AAAA,EACL;AACJ;AAEA,IAAO,aAAQ,iBAAiB;;;ACpOhC,IAAO,cAAQ,iBAAiB,KAAK;","names":[]}
|
package/dist/agent/opencode.js
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
import { createRequire as __biliCreateRequire } from 'node:module';
|
|
2
2
|
const require = __biliCreateRequire(import.meta.url);
|
|
3
3
|
|
|
4
|
+
// src/agent/shared.ts
|
|
5
|
+
var STATUS_TIMEOUT_MS = 5e3;
|
|
6
|
+
async function fetchJson(url, init, timeoutMs, externalSignal) {
|
|
7
|
+
const ac = new AbortController();
|
|
8
|
+
if (externalSignal?.aborted) ac.abort();
|
|
9
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
10
|
+
const onExternalAbort = () => ac.abort();
|
|
11
|
+
externalSignal?.addEventListener("abort", onExternalAbort, { once: true });
|
|
12
|
+
try {
|
|
13
|
+
let res;
|
|
14
|
+
try {
|
|
15
|
+
res = await fetch(url, { ...init, signal: ac.signal });
|
|
16
|
+
} catch (err) {
|
|
17
|
+
if (ac.signal.aborted && !externalSignal?.aborted) throw new Error(`timeout after ${timeoutMs}ms: ${url}`);
|
|
18
|
+
throw err;
|
|
19
|
+
}
|
|
20
|
+
const text = await res.text();
|
|
21
|
+
let json = void 0;
|
|
22
|
+
try {
|
|
23
|
+
json = JSON.parse(text);
|
|
24
|
+
} catch {
|
|
25
|
+
json = void 0;
|
|
26
|
+
}
|
|
27
|
+
return { ok: res.ok, status: res.status, json };
|
|
28
|
+
} finally {
|
|
29
|
+
clearTimeout(timer);
|
|
30
|
+
externalSignal?.removeEventListener("abort", onExternalAbort);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async function fetchProxyVersion(proxyBase2) {
|
|
34
|
+
const { ok, json } = await fetchJson(`${proxyBase2}/__bili/plugin/manifest`, void 0, STATUS_TIMEOUT_MS);
|
|
35
|
+
if (!ok || !json || typeof json !== "object") return void 0;
|
|
36
|
+
const version = json.version;
|
|
37
|
+
return typeof version === "string" && version.length > 0 ? version : void 0;
|
|
38
|
+
}
|
|
39
|
+
|
|
4
40
|
// src/agent/opencode.ts
|
|
5
41
|
var proxyBase = process.env.BILLION_CONTEXT_PROXY ?? "";
|
|
6
42
|
async function showText(ctx, sid, text) {
|
|
@@ -39,7 +75,13 @@ var server = async (ctx) => {
|
|
|
39
75
|
if (typeof status.panel === "string" && status.panel.length > 0) {
|
|
40
76
|
text = status.panel;
|
|
41
77
|
} else if (status.ok === false) {
|
|
42
|
-
|
|
78
|
+
let version;
|
|
79
|
+
try {
|
|
80
|
+
version = await fetchProxyVersion(proxyBase);
|
|
81
|
+
} catch {
|
|
82
|
+
version = void 0;
|
|
83
|
+
}
|
|
84
|
+
text = version !== void 0 ? `billion-context@${version} \u2014 proxy connected, no ACP session yet. Send a model request, then run /acp again.` : "bili: no ACP session yet (send a model request first, then run /acp)";
|
|
43
85
|
} else {
|
|
44
86
|
text = "bili: proxy returned no status panel";
|
|
45
87
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/agent/opencode.ts"],"sourcesContent":["// Thin opencode plugin for the billion-context proxy (`bili opencode`).\n//\n// Activates ONLY when BILLION_CONTEXT_PROXY is set (the launcher sets it);\n// otherwise it is a no-op so shipping it inside the package is harmless.\n// Mirrors the pi/omp plugin (src/agent/pi.ts):\n// - registers the /acp command (config hook + command.execute.before)\n// - binds the opencode session id to the proxy session via the\n// pending-register queue (POST /__bili/plugin/register on session.created)\n// - renders the proxy's buildStatusPanel via an ignored chat message\n\ninterface OpencodeCommandConfig {\n template: string;\n description?: string;\n}\n\ninterface OpencodeConfig {\n command?: Record<string, OpencodeCommandConfig>;\n [key: string]: unknown;\n}\n\ninterface OpencodeSessionInfo {\n id?: unknown;\n}\n\ninterface OpencodeEvent {\n type?: string;\n properties?: { info?: OpencodeSessionInfo; [key: string]: unknown };\n}\n\ninterface OpencodeEventInput {\n event?: OpencodeEvent;\n}\n\ninterface OpencodeCommandInput {\n command: string;\n sessionID: string;\n arguments?: string;\n}\n\ninterface OpencodePromptPart {\n type: string;\n text: string;\n ignored?: boolean;\n}\n\ninterface OpencodeClient {\n session?: {\n prompt?: (args: {\n path: { id: string };\n body: { noReply: boolean; parts: OpencodePromptPart[] };\n }) => Promise<unknown>;\n };\n}\n\ninterface OpencodePluginContext {\n client?: OpencodeClient;\n}\n\ninterface OpencodeHooks {\n config?: (input: OpencodeConfig) => Promise<void>;\n event?: (input: OpencodeEventInput) => Promise<void>;\n \"command.execute.before\"?: (input: OpencodeCommandInput, output: { parts: unknown[] }) => Promise<void>;\n}\n\nconst proxyBase = process.env.BILLION_CONTEXT_PROXY ?? \"\";\n\nasync function showText(ctx: OpencodePluginContext, sid: string, text: string): Promise<void> {\n // Direct method call — `const p = ctx.client.session.prompt; p(...)` loses `this` (this._client) and throws.\n const session = ctx.client?.session;\n if (!session || typeof session.prompt !== \"function\") {\n console.error(\"[bili-opencode] /acp render failed: session.prompt unavailable\");\n return;\n }\n try {\n await session.prompt({\n path: { id: sid },\n body: { noReply: true, parts: [{ type: \"text\", text, ignored: true }] },\n });\n } catch (err) {\n console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nconst server = async (ctx: OpencodePluginContext): Promise<OpencodeHooks> => {\n if (!proxyBase) return {};\n console.log(\"[bili-opencode] plugin active (proxy \" + proxyBase + \")\");\n return {\n config: async (opencodeConfig) => {\n opencodeConfig.command ??= {};\n opencodeConfig.command[\"acp\"] = {\n template: \"\",\n description: \"Show ACP status (billion-context proxy)\",\n };\n },\n \"command.execute.before\": async (input) => {\n if (input.command !== \"acp\") return;\n const sid = input.sessionID;\n let text: string;\n try {\n const res = await fetch(`${proxyBase}/__bili/plugin/status?conversationId=${encodeURIComponent(sid)}&fallback=latest`);\n const status = (await res.json()) as { ok?: boolean; panel?: string; error?: string };\n if (typeof status.panel === \"string\" && status.panel.length > 0) {\n text = status.panel;\n } else if (status.ok === false) {\n text = \"bili: no ACP session yet (send a model request first, then run /acp)\";\n } else {\n text = \"bili: proxy returned no status panel\";\n }\n } catch (err) {\n text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`;\n }\n await showText(ctx, sid, text);\n throw new Error(\"__BILI_ACP_HANDLED__\");\n },\n };\n};\n\nexport default server;\n"],"mappings":";;;;AAgEA,IAAM,YAAY,QAAQ,IAAI,yBAAyB;AAEvD,eAAe,SAAS,KAA4B,KAAa,MAA6B;AAEtF,QAAM,UAAU,IAAI,QAAQ;AAC5B,MAAI,CAAC,WAAW,OAAO,QAAQ,WAAW,YAAY;AAClD,YAAQ,MAAM,gEAAgE;AAC9E;AAAA,EACJ;AACA,MAAI;AACA,UAAM,QAAQ,OAAO;AAAA,MACjB,MAAM,EAAE,IAAI,IAAI;AAAA,MAChB,MAAM,EAAE,SAAS,MAAM,OAAO,CAAC,EAAE,MAAM,QAAQ,MAAM,SAAS,KAAK,CAAC,EAAE;AAAA,IAC1E,CAAC;AAAA,EACL,SAAS,KAAK;AACV,YAAQ,MAAM,uCAAuC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE;AAAA,EAC3G;AACR;AAEA,IAAM,SAAS,OAAO,QAAuD;AACzE,MAAI,CAAC,UAAW,QAAO,CAAC;AACxB,UAAQ,IAAI,0CAA0C,YAAY,GAAG;AACrE,SAAO;AAAA,IACH,QAAQ,OAAO,mBAAmB;AAC9B,qBAAe,YAAY,CAAC;AAC5B,qBAAe,QAAQ,KAAK,IAAI;AAAA,QAC5B,UAAU;AAAA,QACV,aAAa;AAAA,MACjB;AAAA,IACJ;AAAA,IACA,0BAA0B,OAAO,UAAU;AACvC,UAAI,MAAM,YAAY,MAAO;AAC7B,YAAM,MAAM,MAAM;AAClB,UAAI;AACJ,UAAI;AACA,cAAM,MAAM,MAAM,MAAM,GAAG,SAAS,wCAAwC,mBAAmB,GAAG,CAAC,kBAAkB;AACrH,cAAM,SAAU,MAAM,IAAI,KAAK;AAC/B,YAAI,OAAO,OAAO,UAAU,YAAY,OAAO,MAAM,SAAS,GAAG;AAC7D,iBAAO,OAAO;AAAA,QAClB,WAAW,OAAO,OAAO,OAAO;AAC5B,iBAAO;AAAA,QACX,OAAO;AACH,iBAAO;AAAA,QACX;AAAA,MACJ,SAAS,KAAK;AACV,eAAO,sBAAsB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,MACjF;AACA,YAAM,SAAS,KAAK,KAAK,IAAI;AAC7B,YAAM,IAAI,MAAM,sBAAsB;AAAA,IAC1C;AAAA,EACJ;AACJ;AAEA,IAAO,mBAAQ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/agent/shared.ts","../../src/agent/opencode.ts"],"sourcesContent":["// Shared thin-plugin core for agent-side extensions (\"内外呼应\", issue #1).\n// The agent plugin is a PURE PROTOCOL CLIENT: no acp-kernel import, no\n// compression logic. The proxy stays the single compression authority; the\n// plugin only (1) detects the proxy, (2) fetches the tool manifest (single\n// source of truth), (3) forwards tool executes, (4) reads status. Same\n// package as the proxy ⇒ same version ⇒ no kernel-skew bug class.\n\nexport type ManifestTool = {\n name: string;\n description?: string;\n inputSchema: unknown;\n};\n\nconst MANIFEST_TIMEOUT_MS = 5000;\nconst TOOL_TIMEOUT_MS = 60000;\nconst STATUS_TIMEOUT_MS = 5000;\n\n/** Detect the proxy from a provider baseUrl's `/bili/` zero-config prefix.\n * The real prefix embeds the full upstream URL (`/bili/https://…`), so the\n * check requires `bili` as the first path segment followed by an http(s)\n * URL — a plain `/foo/bili/` path segment is NOT a bili proxy.\n * Returns the proxy origin (scheme//host) the request will actually hit. */\nexport function proxyBaseFromUrl(baseUrl: string | undefined): string | undefined {\n if (!baseUrl) return undefined;\n try {\n const url = new URL(baseUrl);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return undefined;\n const segments = url.pathname.split(\"/\").filter((s) => s.length > 0);\n if (segments[0] !== \"bili\") return undefined;\n const rest = url.pathname.slice(url.pathname.indexOf(\"bili\") + \"bili\".length);\n if (!/^\\/https?:\\/\\//.test(rest)) return undefined;\n return `${url.protocol}//${url.host}`;\n } catch {\n return undefined;\n }\n}\n\n/** MITM transparent mode has no `/bili/` prefix; the proxy's launcher exports\n * BILLION_CONTEXT_PROXY. A stale value surfaces as a tool-forward error. */\nexport function proxyBaseFromEnv(): string | undefined {\n const raw = process.env.BILLION_CONTEXT_PROXY?.trim();\n if (!raw) return undefined;\n try {\n const url = new URL(raw);\n return url.protocol === \"http:\" || url.protocol === \"https:\" ? `${url.protocol}//${url.host}` : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function detectProxyBase(baseUrl: string | undefined): string | undefined {\n if (process.env.BILLION_CONTEXT_PLUGIN === \"0\") return undefined;\n return proxyBaseFromUrl(baseUrl) ?? proxyBaseFromEnv();\n}\n\nasync function fetchJson(url: string, init: RequestInit | undefined, timeoutMs: number, externalSignal?: AbortSignal): Promise<{ ok: boolean; status: number; json: unknown }> {\n const ac = new AbortController();\n // An already-aborted external signal never fires its \"abort\" event, so\n // forward the state directly — otherwise only the timeout could stop\n // the request, turning an instant cancel into a timeout wait.\n if (externalSignal?.aborted) ac.abort();\n const timer = setTimeout(() => ac.abort(), timeoutMs);\n const onExternalAbort = () => ac.abort();\n externalSignal?.addEventListener(\"abort\", onExternalAbort, { once: true });\n try {\n let res: Response;\n try {\n res = await fetch(url, { ...init, signal: ac.signal });\n } catch (err) {\n if (ac.signal.aborted && !externalSignal?.aborted) throw new Error(`timeout after ${timeoutMs}ms: ${url}`);\n throw err;\n }\n const text = await res.text();\n let json: unknown = undefined;\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n return { ok: res.ok, status: res.status, json };\n } finally {\n clearTimeout(timer);\n externalSignal?.removeEventListener(\"abort\", onExternalAbort);\n }\n}\n\nexport async function fetchManifest(proxyBase: string): Promise<ManifestTool[]> {\n const { ok, status, json } = await fetchJson(`${proxyBase}/__bili/plugin/manifest`, undefined, MANIFEST_TIMEOUT_MS);\n if (!ok || !json || typeof json !== \"object\") throw new Error(`manifest fetch failed: ${status}`);\n const data = json as { tools?: { anthropic?: { name?: string; description?: string; input_schema?: unknown }[] } };\n const tools = (data.tools?.anthropic ?? []).filter((t): t is { name: string; description?: string; input_schema?: unknown } => typeof t.name === \"string\");\n if (tools.length === 0) throw new Error(\"manifest served no anthropic tools\");\n return tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.input_schema ?? { type: \"object\", properties: {} } }));\n}\n\nexport async function forwardTool(proxyBase: string, conversationId: string, tool: string, args: unknown, signal?: AbortSignal): Promise<string> {\n const { ok, status, json } = await fetchJson(`${proxyBase}/__bili/plugin/tool`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ conversationId, tool, args: args ?? {} }),\n }, TOOL_TIMEOUT_MS, signal);\n const data = json as { ok?: boolean; result?: string; error?: string } | undefined;\n if (!ok || !data?.ok) {\n throw new Error(`bili proxy tool ${tool} failed (${status}): ${data?.error ?? \"unknown error\"}`);\n }\n return data.result ?? \"\";\n}\n\n/** Soft-fail by design: the status read is best-effort UI data; undefined\n * means \"no data\" whether the proxy is down or the session is unknown. */\nexport async function fetchStatus(proxyBase: string, conversationId: string): Promise<Record<string, unknown> | undefined> {\n const { ok, json } = await fetchJson(`${proxyBase}/__bili/plugin/status?conversationId=${encodeURIComponent(conversationId)}`, undefined, STATUS_TIMEOUT_MS);\n if (!ok || !json || typeof json !== \"object\") return undefined;\n return json as Record<string, unknown>;\n}\n\n/** Liveness + version probe for status UIs: same loopback origin as the\n * status endpoint, so a 404 status + a live manifest means \"proxy up,\n * conversation not seen yet\" — an armed-but-idle state, not an error. */\nexport async function fetchProxyVersion(proxyBase: string): Promise<string | undefined> {\n const { ok, json } = await fetchJson(`${proxyBase}/__bili/plugin/manifest`, undefined, STATUS_TIMEOUT_MS);\n if (!ok || !json || typeof json !== \"object\") return undefined;\n const version = (json as { version?: unknown }).version;\n return typeof version === \"string\" && version.length > 0 ? version : undefined;\n}\n","// Thin opencode plugin for the billion-context proxy (`bili opencode`).\n//\n// Activates ONLY when BILLION_CONTEXT_PROXY is set (the launcher sets it);\n// otherwise it is a no-op so shipping it inside the package is harmless.\n// Mirrors the pi/omp plugin (src/agent/pi.ts):\n// - registers the /acp command (config hook + command.execute.before)\n// - binds the opencode session id to the proxy session via the\n// pending-register queue (POST /__bili/plugin/register on session.created)\n// - renders the proxy's buildStatusPanel via an ignored chat message\n\nimport { fetchProxyVersion } from \"./shared.js\";\n\ninterface OpencodeCommandConfig {\n template: string;\n description?: string;\n}\n\ninterface OpencodeConfig {\n command?: Record<string, OpencodeCommandConfig>;\n [key: string]: unknown;\n}\n\ninterface OpencodeSessionInfo {\n id?: unknown;\n}\n\ninterface OpencodeEvent {\n type?: string;\n properties?: { info?: OpencodeSessionInfo; [key: string]: unknown };\n}\n\ninterface OpencodeEventInput {\n event?: OpencodeEvent;\n}\n\ninterface OpencodeCommandInput {\n command: string;\n sessionID: string;\n arguments?: string;\n}\n\ninterface OpencodePromptPart {\n type: string;\n text: string;\n ignored?: boolean;\n}\n\ninterface OpencodeClient {\n session?: {\n prompt?: (args: {\n path: { id: string };\n body: { noReply: boolean; parts: OpencodePromptPart[] };\n }) => Promise<unknown>;\n };\n}\n\ninterface OpencodePluginContext {\n client?: OpencodeClient;\n}\n\ninterface OpencodeHooks {\n config?: (input: OpencodeConfig) => Promise<void>;\n event?: (input: OpencodeEventInput) => Promise<void>;\n \"command.execute.before\"?: (input: OpencodeCommandInput, output: { parts: unknown[] }) => Promise<void>;\n}\n\nconst proxyBase = process.env.BILLION_CONTEXT_PROXY ?? \"\";\n\nasync function showText(ctx: OpencodePluginContext, sid: string, text: string): Promise<void> {\n // Direct method call — `const p = ctx.client.session.prompt; p(...)` loses `this` (this._client) and throws.\n const session = ctx.client?.session;\n if (!session || typeof session.prompt !== \"function\") {\n console.error(\"[bili-opencode] /acp render failed: session.prompt unavailable\");\n return;\n }\n try {\n await session.prompt({\n path: { id: sid },\n body: { noReply: true, parts: [{ type: \"text\", text, ignored: true }] },\n });\n } catch (err) {\n console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nconst server = async (ctx: OpencodePluginContext): Promise<OpencodeHooks> => {\n if (!proxyBase) return {};\n console.log(\"[bili-opencode] plugin active (proxy \" + proxyBase + \")\");\n return {\n config: async (opencodeConfig) => {\n opencodeConfig.command ??= {};\n opencodeConfig.command[\"acp\"] = {\n template: \"\",\n description: \"Show ACP status (billion-context proxy)\",\n };\n },\n \"command.execute.before\": async (input) => {\n if (input.command !== \"acp\") return;\n const sid = input.sessionID;\n let text: string;\n try {\n const res = await fetch(`${proxyBase}/__bili/plugin/status?conversationId=${encodeURIComponent(sid)}&fallback=latest`);\n const status = (await res.json()) as { ok?: boolean; panel?: string; error?: string };\n if (typeof status.panel === \"string\" && status.panel.length > 0) {\n text = status.panel;\n } else if (status.ok === false) {\n // zero sessions on the proxy (fresh launch) — friendly idle notice\n let version: string | undefined;\n try {\n version = await fetchProxyVersion(proxyBase);\n } catch {\n version = undefined;\n }\n text = version !== undefined\n ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.`\n : \"bili: no ACP session yet (send a model request first, then run /acp)\";\n } else {\n text = \"bili: proxy returned no status panel\";\n }\n } catch (err) {\n text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`;\n }\n await showText(ctx, sid, text);\n throw new Error(\"__BILI_ACP_HANDLED__\");\n },\n };\n};\n\n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,KAAK;AACV,eAAO,sBAAsB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,MACjF;AACA,YAAM,SAAS,KAAK,KAAK,IAAI;AAC7B,YAAM,IAAI,MAAM,sBAAsB;AAAA,IAC1C;AAAA,EACJ;AACJ;AAEA,IAAO,mBAAQ;","names":["proxyBase"]}
|
package/dist/agent/pi.js
CHANGED
|
@@ -85,6 +85,12 @@ async function fetchStatus(proxyBase, conversationId) {
|
|
|
85
85
|
if (!ok || !json || typeof json !== "object") return void 0;
|
|
86
86
|
return json;
|
|
87
87
|
}
|
|
88
|
+
async function fetchProxyVersion(proxyBase) {
|
|
89
|
+
const { ok, json } = await fetchJson(`${proxyBase}/__bili/plugin/manifest`, void 0, STATUS_TIMEOUT_MS);
|
|
90
|
+
if (!ok || !json || typeof json !== "object") return void 0;
|
|
91
|
+
const version = json.version;
|
|
92
|
+
return typeof version === "string" && version.length > 0 ? version : void 0;
|
|
93
|
+
}
|
|
88
94
|
|
|
89
95
|
// src/agent/pi.ts
|
|
90
96
|
function agentName(override) {
|
|
@@ -207,7 +213,20 @@ function createBiliPlugin(agentOverride) {
|
|
|
207
213
|
return;
|
|
208
214
|
}
|
|
209
215
|
if (status === void 0) {
|
|
210
|
-
|
|
216
|
+
let version;
|
|
217
|
+
try {
|
|
218
|
+
version = await fetchProxyVersion(proxyBase);
|
|
219
|
+
} catch {
|
|
220
|
+
version = void 0;
|
|
221
|
+
}
|
|
222
|
+
if (version !== void 0) {
|
|
223
|
+
notify(
|
|
224
|
+
`billion-context@${version} \u2014 proxy connected, compression armed. No model request in this conversation yet; send one, then run /acp again.`,
|
|
225
|
+
"info"
|
|
226
|
+
);
|
|
227
|
+
} else {
|
|
228
|
+
notify("bili: no ACP session yet (send a model request first, then run /acp)", "warning");
|
|
229
|
+
}
|
|
211
230
|
return;
|
|
212
231
|
}
|
|
213
232
|
const panel = typeof status.panel === "string" ? status.panel : void 0;
|