mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
feat(opencode): support the OpenCode 2.x plugin API (#3999)
## Description Takeover of #3719 by @laurence-diack-pk, who has been unavailable since Sep 23 and whose branch was left conflicted with `main`. The original commit is preserved and @laurence-diack-pk remains its author; this branch adds follow-up commits addressing @JerrettDavis's review and the findings from live OpenCode 2.x testing. It makes the OpenCode plugin and `headroom wrap opencode` work on both OpenCode 1.x and 2.x. On 2.x the 1.x function plugin was silently dropped (the loader requires a `{ id, setup }` default export loaded from a directory), and Effect's `FetchHttpClient` keeps its own `fetch` reference from before plugins load — so `wrap opencode` loaded no plugin and routed nothing. Closes #3669. Supersedes #3719. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) ## Changes Made Carried from #3719: - One plugin for both versions: default export `{ id: "headroom", server, setup }`; 1.x calls `server`, 2.x calls `setup`. - 2.x `setup`: registers `headroom_retrieve` via `ctx.tool.transform` (`codemode: false`), sets `HEADROOM_*` shell env through the `create.before` hook, and returns a cleanup that releases the refcounted transport so hot reloads do not stack interceptors. - 2.x model routing: `ctx.model.transform` points remote OpenAI-wire models at the proxy with `x-headroom-base-url` / `x-headroom-original-path` headers, since 2.x keeps its own `fetch` reference and the transport patch alone misses model traffic. - Wheel ships the bundle as `_dist/index.js`; `headroom_opencode_plugin_path()` returns the directory; `wrap opencode` adds `--standalone` on 2.x so the private server sees `OPENCODE_CONFIG_CONTENT`. Follow-up commits (review from #3719 + live testing): - Rebased on current `main` (0.40.0). Fixed the routing-contract conflict: replaced `routesThroughProxy` (TS2554 against `shouldRoute`'s 3-arg signature) with `modelBaseRoutesThroughProxy`, a deliberate model-base eligibility check that keeps the shared protocol / loopback / proxy-origin / excluded-host contract but drops the endpoint-suffix requirement, since 2.x hands us model base URLs (e.g. `/v1`), not inference endpoints. - `setup` now resolves the effective `excludeHosts` once (option over `HEADROOM_OPENCODE_EXCLUDE_HOSTS`) and applies it to both the transport install and the model rewrite, with new tests for both paths. - Fixed `test_build_launch_env_with_project` to decode `OPENCODE_CONFIG_CONTENT` instead of substring-matching the raw path, which JSON backslash escaping makes impossible on Windows. - `opencode_major_version` now reads the `v2` channel marker in dev builds (`opencode v0.0.0-v2-<stamp>`), which previously parsed as major 0, so `wrap` skips `--standalone` and the private server never loads Headroom's config. - Rebuilt `_dist/index.js` and `hook-shim/handler.js`; drift check clean. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .` — run on the changed paths) - [x] Type checking passes (`mypy headroom` — run on the changed paths) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text # plugins/opencode $ npm ci && npm run typecheck && npm run build:standalone && npm test tsc: clean (no TS2554) vitest: Test Files 3 passed (3) | Tests 45 passed (45) $ cmp dist-standalone/index.js ../../headroom/providers/opencode/_dist/index.js # identical $ cmp dist-standalone/hook-shim/handler.js ../../headroom/providers/opencode/hook-shim/handler.js # identical # focused Python suites (same set as #3719, plus the 2.x dev-build version case) $ pytest tests/test_providers_opencode_plugin_path.py tests/test_providers_opencode_config.py \ tests/test_providers_opencode_install.py tests/test_cli/test_wrap_opencode.py \ tests/test_mcp_registry_opencode.py tests/test_learn/test_opencode_scanner.py -q 193 passed in 1.10s $ ruff check / ruff format --check on changed paths: clean $ mypy headroom/providers/opencode headroom/cli/wrap.py: Success: no issues found ``` ## Real Behavior Proof - Environment: macOS arm64, Node v26.10.0, Python 3.13, headroom from this branch (0.41.0-dev). Tested against two real OpenCode 2.x clients, each in throwaway XDG dirs with its own proxy port: - `opencode 2.0.19` (official 2.x binary); - OpenCode 2.x head built from `anomalyco/opencode@v2` (`0.0.0-v2-202610061051`, Bun 1.4.2, `bun run script/build.ts --single` in `packages/cli`). - Exact command / steps: throwaway XDG dirs and a dedicated proxy port; fake key first (routing proof), then the real key (end-to-end proof): ```bash # fake key first (routing proof), then the real key (end-to-end proof) OPENCODE_API_KEY=<key> headroom wrap opencode --port 8799 --no-serena -- \ run -m opencode-go/deepseek-v4.1-flash "reply with the single word ok" # exclusion check HEADROOM_OPENCODE_EXCLUDE_HOSTS=opencode.ai OPENCODE_API_KEY=<key> headroom wrap opencode ... ``` (`opencode-go` declares `OPENCODE_API_KEY` as its env credential in the catalog, so no interactive login is needed.) - Observed result: routed 401 with the fake key and 200 with the real key through the proxy, `--standalone` added automatically, exclusion honored — details: - **Fake key** — proxy log: `proxy_inbound_request POST /v1/chat/completions` with `user-agent: opencode/latest/2.0.19/cli` (and `opencode/v2/0.0.0-v2-202610061051/cli` for the head), headers `x-headroom-base-url: https://opencode.ai` and `x-headroom-original-path: /zen/go/v1/chat/completions`; forwarded upstream, `401` from the fake key — routed through Headroom. - **Real key** — the model answered `ok`; proxy `status=200` with upstream `https://opencode.ai/inference/go/openai/v1/chat/completions`. - `wrap` added `--standalone` automatically on 2.0.19, and again on the v2 head after the dev-build version fix (explicit `--standalone` also works, per the kill-switch path). - **Exclusion** — with `HEADROOM_OPENCODE_EXCLUDE_HOSTS=opencode.ai` the model still answered while the proxy saw **zero** new chat requests: the 2.x model transform honors the exclusion list. - Not tested: Windows; OpenAI "responses"-wire against a live 2.x server; Anthropic-wire custom providers on 2.x; loading the plugin by npm name (`headroom-opencode`), which needs a published release; OpenCode 1.x older than 1.2.20. ## Runtime Rollout Safety - Rollout-managed feature(s): none - Minimum rollout channel: n/a - Stable/default behavior changed: on OpenCode 2.x, `wrap opencode` launches with `--standalone` (a private server per session); on 1.x behaviour is unchanged apart from the plugin path now being a directory. - Kill switch / disable path: pass `--server <url>` or `--standalone` explicitly; `HEADROOM_OPENCODE_PLUGIN_PATH` still overrides the plugin location. - Unsafe override required: no - Qualification impact: none - Rollback path: revert this PR; the wheel bundle and plugin path revert with it. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) ## Additional Notes @laurence-diack-pk — thank you for the original implementation; the commit is preserved verbatim at the base of this branch. @JerrettDavis — this addresses the routing-contract conflict you described in #3719 (the missing `excludeHosts` argument and the model-base vs endpoint mismatch), the Windows assertion, and a dev-build version-detection gap found while validating on macOS. Live 2.x validation is done on both 2.0.19 and today's `v2` head; details above. --------- Co-authored-by: laurence <laurence.diack@peekrobotics.co.nz> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
laurence
Claude Opus 5.5
JerrettDavis
parent
22d0905a73
commit
1d4b357ca7
@@ -44,15 +44,15 @@ jobs:
|
||||
- run: npm run build
|
||||
- run: npm test
|
||||
# The wheel ships a committed self-contained bundle at
|
||||
# headroom/providers/opencode/_dist/entry.opencode.js so pip installs
|
||||
# get the transport plugin too. Rebuild it and fail if the committed
|
||||
# artifact has drifted from the source.
|
||||
# headroom/providers/opencode/_dist/index.js so pip installs get the
|
||||
# transport plugin too. Rebuild it and fail if the committed artifact
|
||||
# has drifted from the source.
|
||||
- run: npm run build:standalone
|
||||
- name: verify committed wheel bundle matches source
|
||||
run: |
|
||||
cmp dist-standalone/entry.opencode.js \
|
||||
../../headroom/providers/opencode/_dist/entry.opencode.js \
|
||||
|| { echo "::error::headroom/providers/opencode/_dist/entry.opencode.js is stale - run 'npm run build:standalone' in plugins/opencode and commit the result"; exit 1; }
|
||||
cmp dist-standalone/index.js \
|
||||
../../headroom/providers/opencode/_dist/index.js \
|
||||
|| { echo "::error::headroom/providers/opencode/_dist/index.js is stale - run 'npm run build:standalone' in plugins/opencode and commit the result"; exit 1; }
|
||||
cmp dist-standalone/hook-shim/handler.js \
|
||||
../../headroom/providers/opencode/hook-shim/handler.js \
|
||||
|| { echo "::error::headroom/providers/opencode/hook-shim/handler.js is stale - run 'npm run build:standalone' in plugins/opencode and commit the result"; exit 1; }
|
||||
|
||||
@@ -123,20 +123,22 @@ The default user scope only writes shell environment configuration. For OpenCode
|
||||
|
||||
## Native OpenCode Plugin
|
||||
|
||||
The `headroom-opencode` package exports `HeadroomPlugin` for direct OpenCode plugin registration. The plugin installs Headroom transport interception inside OpenCode, exposes the `headroom_retrieve` tool, and publishes Headroom metadata through the OpenCode plugin output env.
|
||||
The `headroom-opencode` package's default export is a native OpenCode plugin that works with both OpenCode 1.x and 2.x. It installs Headroom transport interception inside OpenCode, exposes the `headroom_retrieve` tool, and adds Headroom metadata (`HEADROOM_ACTIVE`, `HEADROOM_PROXY_URL`, `HEADROOM_PROJECT`) to the environment of shell commands OpenCode runs.
|
||||
|
||||
Example:
|
||||
Register it in `opencode.json`:
|
||||
|
||||
```ts
|
||||
import { HeadroomPlugin } from "headroom-opencode";
|
||||
|
||||
export default async function plugin(input) {
|
||||
return HeadroomPlugin(input, {
|
||||
proxyUrl: process.env.HEADROOM_PROXY_URL ?? "http://127.0.0.1:8787",
|
||||
});
|
||||
```json
|
||||
{
|
||||
"plugin": [
|
||||
["headroom-opencode", { "proxyUrl": "http://127.0.0.1:8787" }]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
OpenCode 2.x migrates the 1.x `plugin` key automatically. To configure it the 2.x way, use `"plugins": [{ "package": "headroom-opencode", "options": { "proxyUrl": "http://127.0.0.1:8787" } }]`. Without `proxyUrl`, the plugin reads `HEADROOM_PROXY_URL` and falls back to `http://127.0.0.1:8787`.
|
||||
|
||||
The default export has `server` for OpenCode 1.x and `setup` for OpenCode 2.x. Each version ignores the other's field. `HeadroomPlugin` (1.x) and `headroomSetup` (2.x) are also exported by name for custom wrappers.
|
||||
|
||||
Use this plugin when OpenCode should intercept provider traffic in-process. Use `headroom wrap opencode` when you want the CLI to manage the proxy, config injection, MCP registration, backups, and unwrap behavior.
|
||||
|
||||
The plugin routes every external HTTP(S) request through the proxy. To keep a provider or gateway off the proxy while leaving the plugin loaded, pass `excludeHosts` in the plugin options or set `HEADROOM_OPENCODE_EXCLUDE_HOSTS` before launching OpenCode. An entry matches the host and all of its subdomains; excluded requests are sent as-is, with no compression or telemetry.
|
||||
@@ -174,7 +176,7 @@ const retrieve = createHeadroomRetrieveTool({
|
||||
1. **Config injection**. The wrapper writes a `provider.headroom` block into `opencode.json`. The provider uses `@ai-sdk/openai-compatible`, which OpenCode supports natively. Model mappings route requests through `http://127.0.0.1:<port>/v1`.
|
||||
2. **Runtime config**. `OPENCODE_CONFIG_CONTENT` is set as an env var containing provider, plugin, and optional local MCP JSON. OpenCode reads it at startup and merges it with on-disk config.
|
||||
3. **MCP tools**. Headroom registers `headroom_compress`, `headroom_retrieve`, and `headroom_stats` through `headroom mcp serve` unless `--no-mcp` is set.
|
||||
4. **Native plugin path**. `HeadroomPlugin` installs Headroom transport interception and uses `HEADROOM_PROXY_URL` or `http://127.0.0.1:8787` to reach the proxy.
|
||||
4. **Native plugin path**. `wrap` loads the transport plugin from a local directory (`plugins/opencode/dist/` in a checkout, `headroom/providers/opencode/_dist/` in the wheel), because OpenCode 2.x only accepts local plugins as directories. The plugin uses `HEADROOM_PROXY_URL` or `http://127.0.0.1:8787` to reach the proxy.
|
||||
5. **Unwrap**. `headroom unwrap opencode` restores `opencode.json` from the pre-wrap backup when present, strips Headroom marker blocks when no backup exists, and unregisters Headroom MCP servers.
|
||||
|
||||
## Troubleshooting
|
||||
@@ -183,6 +185,10 @@ const retrieve = createHeadroomRetrieveTool({
|
||||
|
||||
Check that `OPENCODE_CONFIG_CONTENT` is set and contains the `provider.headroom` block. The wrap command prints the env vars it sets.
|
||||
|
||||
**OpenCode 2.x traffic does not show up in Headroom.**
|
||||
|
||||
OpenCode 2.x connects to a shared background service by default. A service that was already running when you wrapped never sees Headroom's config. `headroom wrap opencode` adds `--standalone` on 2.x so OpenCode runs a private server with that config instead. If you pass `--server <url>`, that server must be started with Headroom's config too. Check what OpenCode actually loaded with `opencode api plugin.list --param directory="$PWD"`, which should list `headroom`.
|
||||
|
||||
**The native plugin cannot reach Headroom.**
|
||||
|
||||
Set `HEADROOM_PROXY_URL` to the running proxy URL, for example `http://127.0.0.1:8787`.
|
||||
|
||||
+13
-1
@@ -200,6 +200,10 @@ from headroom.providers.opencode.config import (
|
||||
snapshot_opencode_config_if_unwrapped,
|
||||
strip_opencode_headroom_blocks,
|
||||
)
|
||||
from headroom.providers.opencode.runtime import (
|
||||
opencode_major_version,
|
||||
with_opencode_standalone,
|
||||
)
|
||||
from headroom.providers.wrap_registry import WRAP_TARGETS, WrapTarget
|
||||
from headroom.providers.wrap_registry import build_launch_env as _build_registry_launch_env
|
||||
from headroom.providers.zcode import (
|
||||
@@ -8345,6 +8349,8 @@ def opencode(
|
||||
Sets OPENCODE_CONFIG_CONTENT to route all OpenCode API calls through
|
||||
Headroom. Configures a headroom provider via @ai-sdk/openai-compatible.
|
||||
Also sets OPENAI_BASE_URL and ANTHROPIC_BASE_URL as fallbacks.
|
||||
On OpenCode 2.x, adds --standalone (unless --server is given) so a private
|
||||
server loads that config instead of a running background service.
|
||||
|
||||
\b
|
||||
Examples:
|
||||
@@ -8513,13 +8519,19 @@ def opencode(
|
||||
os.environ.get("USER", os.environ.get("USERNAME", "default")),
|
||||
)
|
||||
|
||||
# OpenCode 2.x otherwise attaches to an already-running background
|
||||
# service that never sees this launch's OPENCODE_CONFIG_CONTENT.
|
||||
launch_args = with_opencode_standalone(opencode_args, opencode_major_version(opencode_bin))
|
||||
if verbose and launch_args != tuple(opencode_args):
|
||||
click.echo(" OpenCode 2.x: adding --standalone so it loads Headroom's config")
|
||||
|
||||
# Proxy already started by _ensure_proxy above; tell _launch_tool to
|
||||
# skip duplicate startup.
|
||||
launch_started = True
|
||||
try:
|
||||
_launch_tool(
|
||||
binary=opencode_bin,
|
||||
args=opencode_args,
|
||||
args=launch_args,
|
||||
env=env,
|
||||
port=actual_port,
|
||||
no_proxy=True,
|
||||
|
||||
+101
-9
@@ -12625,7 +12625,7 @@ function isExcludedHost(hostname3, excludeHosts) {
|
||||
function isLlmEndpointPath(pathname) {
|
||||
return pathname.endsWith("/chat/completions") || pathname.endsWith("/responses") || pathname.endsWith("/messages") || pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent");
|
||||
}
|
||||
function shouldRoute(url2, proxy, excludeHosts) {
|
||||
function isRoutableUpstream(url2, proxy, excludeHosts) {
|
||||
if (url2.protocol !== "http:" && url2.protocol !== "https:") {
|
||||
return false;
|
||||
}
|
||||
@@ -12638,7 +12638,17 @@ function shouldRoute(url2, proxy, excludeHosts) {
|
||||
if (isExcludedHost(url2.hostname, excludeHosts)) {
|
||||
return false;
|
||||
}
|
||||
return isLlmEndpointPath(url2.pathname);
|
||||
return true;
|
||||
}
|
||||
function shouldRoute(url2, proxy, excludeHosts) {
|
||||
return isRoutableUpstream(url2, proxy, excludeHosts) && isLlmEndpointPath(url2.pathname);
|
||||
}
|
||||
function modelBaseRoutesThroughProxy(baseUrl, proxyUrl, excludeHosts = []) {
|
||||
try {
|
||||
return isRoutableUpstream(new URL(baseUrl), normalizeProxyUrl(proxyUrl), excludeHosts);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function routedUrl(upstream, proxy) {
|
||||
return new URL(`${upstream.pathname}${upstream.search}`, proxy.origin);
|
||||
@@ -12900,6 +12910,7 @@ function uninstallHeadroomTransport() {
|
||||
}
|
||||
|
||||
// src/plugin.ts
|
||||
var HEADROOM_PLUGIN_ID = "headroom";
|
||||
function normalizeProxyUrl2(url2) {
|
||||
return trimTrailingSlashes(url2);
|
||||
}
|
||||
@@ -12908,6 +12919,46 @@ function resolveProxyUrl(options) {
|
||||
options?.proxyUrl ?? process.env.HEADROOM_PROXY_URL ?? process.env.HEADROOM_BASE_URL ?? getDefaultProxyUrl()
|
||||
);
|
||||
}
|
||||
function resolveExcludeHosts(options) {
|
||||
return normalizeExcludeHosts(options?.excludeHosts ?? process.env[EXCLUDE_HOSTS_ENV] ?? "");
|
||||
}
|
||||
function headroomShellEnv(proxyUrl, project, options) {
|
||||
return {
|
||||
HEADROOM_ACTIVE: "1",
|
||||
HEADROOM_PROXY_URL: proxyUrl,
|
||||
HEADROOM_PROJECT: project,
|
||||
...options.backend ? { HEADROOM_BACKEND: options.backend } : {}
|
||||
};
|
||||
}
|
||||
function openAiWireSuffix(pkg) {
|
||||
if (!pkg?.startsWith("@opencode/ai/providers/")) return void 0;
|
||||
if (pkg === "@opencode/ai/providers/openai-compatible" || pkg.endsWith("/chat")) {
|
||||
return "/chat/completions";
|
||||
}
|
||||
if (pkg.endsWith("-responses") || pkg.endsWith("/responses")) return "/responses";
|
||||
return void 0;
|
||||
}
|
||||
function routeModelsThroughProxy(models, proxyUrl, project, excludeHosts) {
|
||||
for (const model of models.list()) {
|
||||
const providerID = String(model.providerID);
|
||||
const modelID = String(model.id);
|
||||
const provider = models.provider.get(providerID)?.provider;
|
||||
const suffix = openAiWireSuffix(model.package ?? provider?.package);
|
||||
const baseURL = model.settings?.baseURL ?? provider?.settings?.baseURL;
|
||||
if (!suffix || typeof baseURL !== "string") continue;
|
||||
if (!modelBaseRoutesThroughProxy(baseURL, proxyUrl, excludeHosts)) continue;
|
||||
const upstream = new URL(baseURL);
|
||||
models.update(providerID, modelID, (draft) => {
|
||||
draft.settings = { ...draft.settings, baseURL: `${proxyUrl}/v1` };
|
||||
draft.headers = {
|
||||
...draft.headers,
|
||||
[BASE_URL_HEADER]: upstream.origin,
|
||||
[ORIGINAL_PATH_HEADER]: `${trimTrailingSlashes(upstream.pathname)}${suffix}`,
|
||||
[PROJECT_HEADER]: project
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
var HeadroomPlugin = async (input, options = {}) => {
|
||||
const pluginOptions = options;
|
||||
const proxyUrl = resolveProxyUrl(pluginOptions);
|
||||
@@ -12935,15 +12986,56 @@ var HeadroomPlugin = async (input, options = {}) => {
|
||||
})
|
||||
},
|
||||
"shell.env": async (_input, output) => {
|
||||
output.env.HEADROOM_ACTIVE = "1";
|
||||
output.env.HEADROOM_PROXY_URL = proxyUrl;
|
||||
output.env.HEADROOM_PROJECT = project;
|
||||
if (pluginOptions.backend) {
|
||||
output.env.HEADROOM_BACKEND = pluginOptions.backend;
|
||||
}
|
||||
Object.assign(output.env, headroomShellEnv(proxyUrl, project, pluginOptions));
|
||||
}
|
||||
};
|
||||
};
|
||||
var headroomSetup = async (ctx) => {
|
||||
const pluginOptions = ctx.options;
|
||||
const proxyUrl = resolveProxyUrl(pluginOptions);
|
||||
const project = pluginOptions.project ?? ctx.location.project.id ?? ctx.location.directory;
|
||||
const retrieveTool = createHeadroomRetrieveTool({ proxyBaseUrl: proxyUrl });
|
||||
const excludeHosts = resolveExcludeHosts(pluginOptions);
|
||||
const uninstallTransport = installHeadroomTransport({
|
||||
proxyUrl,
|
||||
project,
|
||||
excludeHosts,
|
||||
debug: pluginOptions.debug
|
||||
});
|
||||
try {
|
||||
await ctx.model.transform((models) => {
|
||||
routeModelsThroughProxy(models, proxyUrl, project, excludeHosts);
|
||||
});
|
||||
await ctx.tool.transform((editor) => {
|
||||
editor.add({
|
||||
name: retrieveTool.name,
|
||||
description: retrieveTool.description,
|
||||
input: retrieveTool.parameters,
|
||||
// Offer the tool directly, like OpenCode's built-ins, rather than only
|
||||
// through the code-mode `execute` tool.
|
||||
options: { codemode: false },
|
||||
async execute(args) {
|
||||
return { content: await retrieveTool.execute(args) };
|
||||
}
|
||||
});
|
||||
});
|
||||
await ctx.shell.hook("create.before", (shell) => {
|
||||
Object.assign(shell.env, headroomShellEnv(proxyUrl, project, pluginOptions));
|
||||
});
|
||||
} catch (error45) {
|
||||
uninstallTransport();
|
||||
throw error45;
|
||||
}
|
||||
return () => {
|
||||
uninstallTransport();
|
||||
};
|
||||
};
|
||||
var HeadroomOpenCodePlugin = {
|
||||
id: HEADROOM_PLUGIN_ID,
|
||||
server: HeadroomPlugin,
|
||||
setup: headroomSetup
|
||||
};
|
||||
var plugin_default = HeadroomOpenCodePlugin;
|
||||
export {
|
||||
HeadroomPlugin as default
|
||||
plugin_default as default
|
||||
};
|
||||
@@ -141,7 +141,7 @@ function isExcludedHost(hostname, excludeHosts) {
|
||||
function isLlmEndpointPath(pathname) {
|
||||
return pathname.endsWith("/chat/completions") || pathname.endsWith("/responses") || pathname.endsWith("/messages") || pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent");
|
||||
}
|
||||
function shouldRoute(url, proxy, excludeHosts) {
|
||||
function isRoutableUpstream(url, proxy, excludeHosts) {
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
return false;
|
||||
}
|
||||
@@ -154,7 +154,10 @@ function shouldRoute(url, proxy, excludeHosts) {
|
||||
if (isExcludedHost(url.hostname, excludeHosts)) {
|
||||
return false;
|
||||
}
|
||||
return isLlmEndpointPath(url.pathname);
|
||||
return true;
|
||||
}
|
||||
function shouldRoute(url, proxy, excludeHosts) {
|
||||
return isRoutableUpstream(url, proxy, excludeHosts) && isLlmEndpointPath(url.pathname);
|
||||
}
|
||||
function routedUrl(upstream, proxy) {
|
||||
return new URL(`${upstream.pathname}${upstream.search}`, proxy.origin);
|
||||
|
||||
@@ -4,9 +4,12 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from collections.abc import Mapping
|
||||
import re
|
||||
import subprocess
|
||||
from collections.abc import Mapping, Sequence
|
||||
from pathlib import Path
|
||||
|
||||
from headroom._subprocess import run
|
||||
from headroom.mcp_registry.install import DEFAULT_PROXY_URL
|
||||
|
||||
from .config import HEADROOM_OPENCODE_PLUGIN, headroom_provider_entry
|
||||
@@ -17,24 +20,122 @@ def proxy_base_url(port: int) -> str:
|
||||
return f"http://127.0.0.1:{port}/v1"
|
||||
|
||||
|
||||
def headroom_opencode_plugin_path() -> str | None:
|
||||
"""Return the absolute path to the built OpenCode transport plugin, or None.
|
||||
# OpenCode 2.x subcommands. Of these only the interactive ones (the root TUI,
|
||||
# ``run`` and ``mini``) get ``--standalone``; the rest are management commands.
|
||||
_OPENCODE_SUBCOMMANDS = frozenset(
|
||||
{
|
||||
"acp",
|
||||
"api",
|
||||
"auth",
|
||||
"debug",
|
||||
"mcp",
|
||||
"mini",
|
||||
"models",
|
||||
"plugin",
|
||||
"run",
|
||||
"serve",
|
||||
"service",
|
||||
"session",
|
||||
"stats",
|
||||
"uninstall",
|
||||
"update",
|
||||
"upgrade",
|
||||
}
|
||||
)
|
||||
_OPENCODE_STANDALONE_SUBCOMMANDS = frozenset({"run", "mini"})
|
||||
|
||||
OpenCode loads a plugin from an absolute file path (verified against
|
||||
opencode 1.17). The plugin's loader entry exports ONLY the plugin function
|
||||
(``plugins/opencode/dist/entry.opencode.js``) — the library barrel cannot
|
||||
be loaded directly ("Plugin export is not a function").
|
||||
# Root OpenCode 2.x options that consume the following argument. Their values
|
||||
# must not be mistaken for the command position when they happen to match a
|
||||
# subcommand name (e.g. `--session models`).
|
||||
_OPENCODE_ROOT_VALUE_FLAGS = frozenset({"--session", "-s", "--prompt"})
|
||||
|
||||
|
||||
def opencode_major_version(binary: str) -> int | None:
|
||||
"""Return the major version of the ``opencode`` binary, or ``None``.
|
||||
|
||||
Parses ``opencode --version`` (1.x prints ``1.18.32``, 2.x prints
|
||||
``opencode v2.0.12``). Returns ``None`` on any failure — missing binary,
|
||||
non-zero exit, timeout, unparseable output — so callers treat the version
|
||||
as unknown and change nothing. Never raises.
|
||||
"""
|
||||
try:
|
||||
proc = run([binary, "--version"], capture_output=True, text=True, timeout=10)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
if getattr(proc, "returncode", 0) != 0:
|
||||
return None
|
||||
output = f"{getattr(proc, 'stdout', '') or ''} {getattr(proc, 'stderr', '') or ''}"
|
||||
# Not `\b`: in "v2.0.12" the "v" and "2" are both word characters.
|
||||
match = re.search(r"(?<!\d)(\d+)\.\d+\.\d+", output)
|
||||
major = int(match.group(1)) if match else None
|
||||
if major == 0:
|
||||
# Dev builds report `0.0.0-v2-<stamp>`; the channel marker carries the
|
||||
# real major. Take the highest `vN` token, skipping the "v0" prefix.
|
||||
channels = re.findall(r"(?<![A-Za-z0-9])v(\d+)(?![0-9])", output)
|
||||
if channels:
|
||||
major = max(int(channel) for channel in channels)
|
||||
return major
|
||||
|
||||
|
||||
def with_opencode_standalone(args: Sequence[str], major_version: int | None) -> tuple[str, ...]:
|
||||
"""Add ``--standalone`` to an interactive OpenCode 2.x launch.
|
||||
|
||||
OpenCode 2.x attaches to a shared background service by default. When one
|
||||
is already running, it was started with its own environment, so the
|
||||
``OPENCODE_CONFIG_CONTENT`` wrap sets (Headroom provider routing and the
|
||||
transport plugin) never reaches it. ``--standalone`` runs a private server
|
||||
that reads this launch's environment.
|
||||
|
||||
Leaves ``args`` alone for OpenCode 1.x or an unknown version, when the user
|
||||
already chose ``--standalone`` or ``--server``, and for management
|
||||
subcommands (``models``, ``auth``, ...). The flag goes right after ``run``
|
||||
or ``mini``, and first for the root TUI.
|
||||
"""
|
||||
args = tuple(args)
|
||||
if major_version is None or major_version < 2:
|
||||
return args
|
||||
if any(arg in ("--standalone", "--server") or arg.startswith("--server=") for arg in args):
|
||||
return args
|
||||
skip_next = False
|
||||
for index, arg in enumerate(args):
|
||||
if skip_next:
|
||||
skip_next = False
|
||||
continue
|
||||
if arg in _OPENCODE_ROOT_VALUE_FLAGS:
|
||||
skip_next = True
|
||||
continue
|
||||
if arg.startswith("-"):
|
||||
continue
|
||||
# First positional token: the subcommand, or the root TUI's directory
|
||||
# argument. Only this position decides whether to add the flag.
|
||||
if arg in _OPENCODE_STANDALONE_SUBCOMMANDS:
|
||||
return (*args[: index + 1], "--standalone", *args[index + 1 :])
|
||||
if arg in _OPENCODE_SUBCOMMANDS:
|
||||
return args
|
||||
break
|
||||
return ("--standalone", *args)
|
||||
|
||||
|
||||
def headroom_opencode_plugin_path() -> str | None:
|
||||
"""Return the absolute path to the built OpenCode transport plugin directory, or None.
|
||||
|
||||
OpenCode 2.x only loads a configured local plugin from a directory — a file
|
||||
path is dropped with "configured plugin path must be a directory" — and
|
||||
resolves ``<dir>/server.*`` then ``<dir>/index.*``. OpenCode 1.x resolves a
|
||||
directory without ``package.json`` to its ``index.*`` as well. The
|
||||
``index.js`` in each candidate directory default-exports a plugin object
|
||||
carrying both the 1.x ``server`` and the 2.x ``setup`` entry points.
|
||||
|
||||
Resolution order:
|
||||
|
||||
1. ``HEADROOM_OPENCODE_PLUGIN_PATH`` env override.
|
||||
2. A repo-checkout build (``plugins/opencode/dist/entry.opencode.js``) —
|
||||
external-deps build, resolvable because the checkout has node_modules.
|
||||
1. ``HEADROOM_OPENCODE_PLUGIN_PATH`` env override (a directory for 2.x).
|
||||
2. A repo-checkout build (``plugins/opencode/dist/``) — external-deps
|
||||
build, resolvable because the checkout has node_modules.
|
||||
3. The self-contained bundle shipped inside the wheel
|
||||
(``headroom/providers/opencode/_dist/entry.opencode.js``, built by
|
||||
(``headroom/providers/opencode/_dist/``, built by
|
||||
``npm run build:standalone``) — every dependency inlined, so it loads
|
||||
from site-packages where no node_modules exists (verified against
|
||||
opencode 1.18.5).
|
||||
opencode 1.18.32 and 2.0.12).
|
||||
|
||||
Returns ``None`` only when none of the three exist, in which case wrap
|
||||
falls back to the native-provider baseURL override, which already covers
|
||||
@@ -42,15 +143,13 @@ def headroom_opencode_plugin_path() -> str | None:
|
||||
"""
|
||||
override = os.environ.get("HEADROOM_OPENCODE_PLUGIN_PATH", "").strip()
|
||||
if override:
|
||||
return override if Path(override).is_file() else None
|
||||
return override if Path(override).exists() else None
|
||||
# runtime.py → opencode → providers → headroom → <repo root>
|
||||
repo_candidate = (
|
||||
Path(__file__).resolve().parents[3] / "plugins" / "opencode" / "dist" / "entry.opencode.js"
|
||||
)
|
||||
if repo_candidate.is_file():
|
||||
repo_candidate = Path(__file__).resolve().parents[3] / "plugins" / "opencode" / "dist"
|
||||
if (repo_candidate / "index.js").is_file():
|
||||
return str(repo_candidate)
|
||||
packaged = Path(__file__).resolve().parent / "_dist" / "entry.opencode.js"
|
||||
return str(packaged) if packaged.is_file() else None
|
||||
packaged = Path(__file__).resolve().parent / "_dist"
|
||||
return str(packaged) if (packaged / "index.js").is_file() else None
|
||||
|
||||
|
||||
def build_opencode_config_content(
|
||||
|
||||
+19
-15
@@ -35,32 +35,36 @@ The generated provider uses `@ai-sdk/openai-compatible` and points model request
|
||||
|
||||
## Native OpenCode Plugin
|
||||
|
||||
Use `HeadroomPlugin` when OpenCode should intercept provider traffic in-process and expose Headroom tooling from a plugin.
|
||||
The package's default export is an OpenCode plugin that loads on both OpenCode 1.x and 2.x. Register it in `opencode.json`:
|
||||
|
||||
```ts
|
||||
import { HeadroomPlugin } from "headroom-opencode";
|
||||
|
||||
export default async function plugin(input) {
|
||||
return HeadroomPlugin(input, {
|
||||
proxyUrl: process.env.HEADROOM_PROXY_URL ?? "http://127.0.0.1:8787",
|
||||
});
|
||||
```json
|
||||
{
|
||||
"plugin": [
|
||||
["headroom-opencode", { "proxyUrl": "http://127.0.0.1:8787" }]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`HeadroomPlugin`:
|
||||
OpenCode 2.x migrates the 1.x `plugin` key automatically. To configure it the 2.x way, use `"plugins": [{ "package": "headroom-opencode", "options": { ... } }]`.
|
||||
|
||||
- installs Headroom transport interception for OpenCode provider traffic.
|
||||
- exposes the `headroom_retrieve` tool.
|
||||
- publishes `HEADROOM_PROXY_URL` in the plugin output env.
|
||||
- defaults to `http://127.0.0.1:8787` when no proxy URL is supplied.
|
||||
- skips routing for hosts listed in `excludeHosts` (or `HEADROOM_OPENCODE_EXCLUDE_HOSTS`); those requests go straight upstream with no compression or telemetry.
|
||||
The default export is `{ id: "headroom", server, setup }`. OpenCode 1.x calls `server` (`HeadroomPlugin`) and 2.x calls `setup` (`headroomSetup`); each ignores the other's field. Both entry points:
|
||||
|
||||
- install Headroom transport interception for OpenCode provider traffic.
|
||||
- expose the `headroom_retrieve` tool (a direct tool on 2.x, not only through code mode).
|
||||
- add `HEADROOM_ACTIVE`, `HEADROOM_PROXY_URL`, `HEADROOM_PROJECT` (and `HEADROOM_BACKEND` when set) to shell command environments.
|
||||
- default to `HEADROOM_PROXY_URL`, then `http://127.0.0.1:8787`, when no `proxyUrl` option is supplied.
|
||||
- skip routing for hosts listed in `excludeHosts` (or `HEADROOM_OPENCODE_EXCLUDE_HOSTS`); those requests go straight upstream with no compression or telemetry.
|
||||
|
||||
On 2.x, setup returns a cleanup that releases the transport, so hot reloads do not stack interceptors.
|
||||
|
||||
OpenCode 2.x keeps its own reference to `fetch` from before plugins load, so patching `fetch` alone does not catch its model traffic. On 2.x the plugin also rewrites each remote model that uses the OpenAI chat-completions or responses format so that it points at the proxy. Headers name the real upstream, as the transport does. Models on other formats (Anthropic messages, Google) are left alone. `headroom wrap opencode` routes native Anthropic and OpenAI through the proxy separately, via their `baseURL`.
|
||||
|
||||
To keep a provider off the proxy, list its host. An entry matches the host and all of its subdomains, and `.example.com` / `*.example.com` are accepted as spellings of `example.com`:
|
||||
|
||||
```jsonc
|
||||
// opencode.json
|
||||
{
|
||||
"plugin": [["/path/to/headroom/providers/opencode/_dist/entry.opencode.js", { "excludeHosts": ["opencode.ai"] }]]
|
||||
"plugin": [["/path/to/headroom/providers/opencode/_dist", { "excludeHosts": ["opencode.ai"] }]]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Generated
+3801
-8
File diff suppressed because it is too large
Load Diff
@@ -38,6 +38,7 @@
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@opencode/plugin": "^2.0.14",
|
||||
"@types/node": "^26.1.1",
|
||||
"@typescript/native": "npm:typescript@^7.0.2",
|
||||
"tsup": "^8.0.0",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Dedicated entry for OpenCode's plugin loader.
|
||||
//
|
||||
// OpenCode loads a plugin module and treats its exports as plugin factories —
|
||||
// it rejects the module if a non-function export is present ("Plugin export is
|
||||
// not a function"). The library barrel (index.ts) re-exports helpers/constants,
|
||||
// so it cannot be loaded directly. This entry exports ONLY the plugin function.
|
||||
export { HeadroomPlugin as default } from "./plugin.js";
|
||||
// Both OpenCode loaders only read the default export: 1.x takes `{ id, server }`
|
||||
// and 2.x takes `{ id, setup }`, so the dual-shape plugin object loads on
|
||||
// either. The library barrel (index.ts) re-exports helpers the plugin does not
|
||||
// need, so this entry keeps the standalone wheel bundle to the plugin alone.
|
||||
export { default } from "./plugin.js";
|
||||
|
||||
@@ -17,7 +17,13 @@ export {
|
||||
setDefaultProxyUrl,
|
||||
} from "./retrieve.js";
|
||||
export type { RetrieveToolConfig } from "./retrieve.js";
|
||||
export { HeadroomPlugin, default } from "./plugin.js";
|
||||
export {
|
||||
HEADROOM_PLUGIN_ID,
|
||||
HeadroomOpenCodePlugin,
|
||||
HeadroomPlugin,
|
||||
default,
|
||||
headroomSetup,
|
||||
} from "./plugin.js";
|
||||
export type { HeadroomOpenCodePluginOptions } from "./plugin.js";
|
||||
|
||||
export { installHeadroomTransport } from "./transport.js";
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { HeadroomPlugin } from "./plugin.js";
|
||||
import HeadroomOpenCodePlugin, { HeadroomPlugin, headroomSetup } from "./plugin.js";
|
||||
|
||||
const TRANSPORT_STATE = Symbol.for("headroom.opencode.transport");
|
||||
|
||||
function pluginInput() {
|
||||
return {
|
||||
@@ -15,8 +17,77 @@ function pluginInput() {
|
||||
} as never;
|
||||
}
|
||||
|
||||
interface FakeModel {
|
||||
id: string;
|
||||
providerID: string;
|
||||
package?: string;
|
||||
settings?: Record<string, unknown>;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface FakeProvider {
|
||||
id: string;
|
||||
package: string;
|
||||
settings?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// Minimal OpenCode 2.x plugin context: records what setup registers.
|
||||
function pluginContextV2(
|
||||
options: Record<string, unknown>,
|
||||
catalog: { providers?: FakeProvider[]; models?: FakeModel[] } = {},
|
||||
) {
|
||||
const tools: Array<Record<string, any>> = [];
|
||||
const shellHooks: Array<(input: { env: Record<string, string | undefined> }) => unknown> = [];
|
||||
const providers = catalog.providers ?? [];
|
||||
const models = catalog.models ?? [];
|
||||
const context = {
|
||||
options,
|
||||
location: {
|
||||
directory: "/repo",
|
||||
project: { id: "project-1", directory: "/repo", canonical: "/repo" },
|
||||
},
|
||||
model: {
|
||||
transform: vi.fn(async (callback: (editor: Record<string, any>) => void) => {
|
||||
callback({
|
||||
list: () => models,
|
||||
update: (providerID: string, modelID: string, update: (model: FakeModel) => void) => {
|
||||
const model = models.find((m) => m.providerID === providerID && m.id === modelID);
|
||||
if (model) update(model);
|
||||
},
|
||||
provider: {
|
||||
get: (providerID: string) => {
|
||||
const provider = providers.find((p) => p.id === providerID);
|
||||
return provider ? { provider, models: new Map() } : undefined;
|
||||
},
|
||||
},
|
||||
});
|
||||
return { dispose: async () => {} };
|
||||
}),
|
||||
},
|
||||
tool: {
|
||||
transform: vi.fn(async (callback: (editor: { add: (tool: Record<string, any>) => void }) => void) => {
|
||||
callback({ add: (tool) => tools.push(tool) });
|
||||
return { dispose: async () => {} };
|
||||
}),
|
||||
},
|
||||
shell: {
|
||||
hook: vi.fn(async (name: string, callback: (input: { env: Record<string, string | undefined> }) => unknown) => {
|
||||
expect(name).toBe("create.before");
|
||||
shellHooks.push(callback);
|
||||
return { dispose: async () => {} };
|
||||
}),
|
||||
},
|
||||
};
|
||||
return { context: context as never, tools, shellHooks };
|
||||
}
|
||||
|
||||
function transportState(): { refs: number } | undefined {
|
||||
return (globalThis as Record<symbol, { refs: number } | undefined>)[TRANSPORT_STATE];
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("HeadroomPlugin", () => {
|
||||
@@ -33,6 +104,7 @@ describe("HeadroomPlugin", () => {
|
||||
};
|
||||
|
||||
await plugin["shell.env"]?.({ cwd: "/repo" }, output);
|
||||
await plugin.dispose?.();
|
||||
|
||||
expect(output.env).toMatchObject({
|
||||
HEADROOM_ACTIVE: "1",
|
||||
@@ -58,6 +130,7 @@ describe("HeadroomPlugin", () => {
|
||||
{ hash: "0123456789abcdef01234567" },
|
||||
{} as never,
|
||||
);
|
||||
await plugin.dispose?.();
|
||||
|
||||
expect(result).toBe("original content");
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
@@ -66,3 +139,353 @@ describe("HeadroomPlugin", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("headroomSetup (OpenCode 2.x)", () => {
|
||||
it("registers headroom_retrieve as a direct tool backed by the proxy", async () => {
|
||||
const { context, tools } = pluginContextV2({ proxyUrl: "http://127.0.0.1:8787/" });
|
||||
const cleanup = await headroomSetup(context);
|
||||
|
||||
const fetchMock = vi.fn(async () => ({
|
||||
ok: true,
|
||||
json: async () => "original content",
|
||||
}));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
expect(tools).toHaveLength(1);
|
||||
const [retrieve] = tools;
|
||||
expect(retrieve).toMatchObject({
|
||||
name: "headroom_retrieve",
|
||||
options: { codemode: false },
|
||||
input: { type: "object", required: ["hash"] },
|
||||
});
|
||||
const result = await retrieve.execute(
|
||||
{ hash: "0123456789abcdef01234567" },
|
||||
{ signal: new AbortController().signal, progress: async () => {} },
|
||||
);
|
||||
await cleanup?.();
|
||||
|
||||
expect(result).toEqual({ content: "original content" });
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"http://127.0.0.1:8787/v1/retrieve/0123456789abcdef01234567",
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
|
||||
it("adds only Headroom metadata to shell env", async () => {
|
||||
const { context, shellHooks } = pluginContextV2({
|
||||
proxyUrl: "http://127.0.0.1:8787/",
|
||||
backend: "litellm",
|
||||
});
|
||||
const cleanup = await headroomSetup(context);
|
||||
const shell = {
|
||||
env: {
|
||||
OPENAI_BASE_URL: "https://deepseek.example/v1",
|
||||
ANTHROPIC_BASE_URL: "https://anthropic.example",
|
||||
} as Record<string, string | undefined>,
|
||||
};
|
||||
|
||||
expect(shellHooks).toHaveLength(1);
|
||||
await shellHooks[0](shell);
|
||||
await cleanup?.();
|
||||
|
||||
expect(shell.env).toMatchObject({
|
||||
HEADROOM_ACTIVE: "1",
|
||||
HEADROOM_PROXY_URL: "http://127.0.0.1:8787",
|
||||
HEADROOM_PROJECT: "project-1",
|
||||
HEADROOM_BACKEND: "litellm",
|
||||
OPENAI_BASE_URL: "https://deepseek.example/v1",
|
||||
ANTHROPIC_BASE_URL: "https://anthropic.example",
|
||||
});
|
||||
});
|
||||
|
||||
it("points remote OpenAI-wire models at the proxy and names the real upstream", async () => {
|
||||
const models: FakeModel[] = [
|
||||
{ id: "deepseek-v4.1-flash", providerID: "opencode-go" },
|
||||
{ id: "gpt-6-luna", providerID: "gateway", package: "@opencode/ai/providers/openai/responses" },
|
||||
];
|
||||
const { context } = pluginContextV2(
|
||||
{ proxyUrl: "http://127.0.0.1:8787/" },
|
||||
{
|
||||
providers: [
|
||||
{
|
||||
id: "opencode-go",
|
||||
package: "@opencode/ai/providers/openai-compatible",
|
||||
settings: { baseURL: "https://opencode.ai/zen/go/v1/" },
|
||||
},
|
||||
{
|
||||
id: "gateway",
|
||||
package: "@opencode/ai/providers/openai-compatible",
|
||||
settings: { baseURL: "https://gateway.example/api/v1" },
|
||||
},
|
||||
],
|
||||
models,
|
||||
},
|
||||
);
|
||||
|
||||
const cleanup = await headroomSetup(context);
|
||||
await cleanup?.();
|
||||
|
||||
expect(models[0]).toMatchObject({
|
||||
settings: { baseURL: "http://127.0.0.1:8787/v1" },
|
||||
headers: {
|
||||
"x-headroom-base-url": "https://opencode.ai",
|
||||
"x-headroom-original-path": "/zen/go/v1/chat/completions",
|
||||
"x-headroom-project": "project-1",
|
||||
},
|
||||
});
|
||||
expect(models[1]).toMatchObject({
|
||||
settings: { baseURL: "http://127.0.0.1:8787/v1" },
|
||||
headers: {
|
||||
"x-headroom-base-url": "https://gateway.example",
|
||||
"x-headroom-original-path": "/api/v1/responses",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers a model's own baseURL over its provider's", async () => {
|
||||
const models: FakeModel[] = [
|
||||
{
|
||||
id: "custom",
|
||||
providerID: "opencode-go",
|
||||
settings: { baseURL: "https://model.example/v1", temperature: 0 },
|
||||
headers: { "x-user": "kept" },
|
||||
},
|
||||
];
|
||||
const { context } = pluginContextV2(
|
||||
{ proxyUrl: "http://127.0.0.1:8787" },
|
||||
{
|
||||
providers: [
|
||||
{
|
||||
id: "opencode-go",
|
||||
package: "@opencode/ai/providers/openai-compatible",
|
||||
settings: { baseURL: "https://opencode.ai/zen/go/v1" },
|
||||
},
|
||||
],
|
||||
models,
|
||||
},
|
||||
);
|
||||
|
||||
const cleanup = await headroomSetup(context);
|
||||
await cleanup?.();
|
||||
|
||||
expect(models[0]).toEqual({
|
||||
id: "custom",
|
||||
providerID: "opencode-go",
|
||||
settings: { baseURL: "http://127.0.0.1:8787/v1", temperature: 0 },
|
||||
headers: {
|
||||
"x-user": "kept",
|
||||
"x-headroom-base-url": "https://model.example",
|
||||
"x-headroom-original-path": "/v1/chat/completions",
|
||||
"x-headroom-project": "project-1",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps hosts excluded by option off the model rewrite", async () => {
|
||||
const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
|
||||
const models: FakeModel[] = [
|
||||
{ id: "zen", providerID: "opencode-go" },
|
||||
{ id: "kept", providerID: "gateway" },
|
||||
];
|
||||
const { context } = pluginContextV2(
|
||||
{ proxyUrl: "http://127.0.0.1:8787", excludeHosts: [".opencode.ai"] },
|
||||
{
|
||||
providers: [
|
||||
{
|
||||
id: "opencode-go",
|
||||
package: "@opencode/ai/providers/openai-compatible",
|
||||
settings: { baseURL: "https://opencode.ai/zen/go/v1" },
|
||||
},
|
||||
{
|
||||
id: "gateway",
|
||||
package: "@opencode/ai/providers/openai-compatible",
|
||||
settings: { baseURL: "https://gateway.example/api/v1" },
|
||||
},
|
||||
],
|
||||
models,
|
||||
},
|
||||
);
|
||||
|
||||
try {
|
||||
const cleanup = await headroomSetup(context);
|
||||
await cleanup?.();
|
||||
} finally {
|
||||
if (originalExclude === undefined) {
|
||||
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
|
||||
} else {
|
||||
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
|
||||
}
|
||||
}
|
||||
|
||||
expect(models[0].settings).toBeUndefined();
|
||||
expect(models[0].headers).toBeUndefined();
|
||||
expect(models[1]).toMatchObject({
|
||||
settings: { baseURL: "http://127.0.0.1:8787/v1" },
|
||||
headers: { "x-headroom-base-url": "https://gateway.example" },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps hosts excluded by environment off the model rewrite", async () => {
|
||||
const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
|
||||
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = "opencode.ai";
|
||||
try {
|
||||
const models: FakeModel[] = [{ id: "zen", providerID: "opencode-go" }];
|
||||
const { context } = pluginContextV2(
|
||||
{ proxyUrl: "http://127.0.0.1:8787" },
|
||||
{
|
||||
providers: [
|
||||
{
|
||||
id: "opencode-go",
|
||||
package: "@opencode/ai/providers/openai-compatible",
|
||||
settings: { baseURL: "https://zen.opencode.ai/zen/go/v1" },
|
||||
},
|
||||
],
|
||||
models,
|
||||
},
|
||||
);
|
||||
|
||||
const cleanup = await headroomSetup(context);
|
||||
await cleanup?.();
|
||||
|
||||
expect(models[0].settings).toBeUndefined();
|
||||
expect(models[0].headers).toBeUndefined();
|
||||
} finally {
|
||||
if (originalExclude === undefined) {
|
||||
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
|
||||
} else {
|
||||
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("handles adversarial slash runs in model base URLs in bounded time", async () => {
|
||||
const trailing = "/".repeat(20000);
|
||||
const models: FakeModel[] = [
|
||||
{
|
||||
id: "non-slash-tail",
|
||||
providerID: "gateway",
|
||||
settings: { baseURL: `https://gateway.example/api/v1${trailing}x` },
|
||||
},
|
||||
{
|
||||
id: "slash-tail",
|
||||
providerID: "gateway",
|
||||
settings: { baseURL: `https://gateway.example/api/v1${trailing}` },
|
||||
},
|
||||
];
|
||||
const { context } = pluginContextV2(
|
||||
{ proxyUrl: "http://127.0.0.1:8787" },
|
||||
{
|
||||
providers: [
|
||||
{
|
||||
id: "gateway",
|
||||
package: "@opencode/ai/providers/openai-compatible",
|
||||
},
|
||||
],
|
||||
models,
|
||||
},
|
||||
);
|
||||
|
||||
const cleanup = await headroomSetup(context);
|
||||
await cleanup?.();
|
||||
|
||||
expect(models[0]).toMatchObject({
|
||||
settings: { baseURL: "http://127.0.0.1:8787/v1" },
|
||||
headers: {
|
||||
"x-headroom-base-url": "https://gateway.example",
|
||||
"x-headroom-original-path": `/api/v1${trailing}x/chat/completions`,
|
||||
},
|
||||
});
|
||||
expect(models[1]).toMatchObject({
|
||||
settings: { baseURL: "http://127.0.0.1:8787/v1" },
|
||||
headers: {
|
||||
"x-headroom-base-url": "https://gateway.example",
|
||||
"x-headroom-original-path": "/api/v1/chat/completions",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves local, already-proxied, non-OpenAI-wire and URL-less models alone", async () => {
|
||||
const models: FakeModel[] = [
|
||||
{ id: "llama", providerID: "ollama" },
|
||||
{ id: "gpt-4o", providerID: "openai" },
|
||||
{ id: "claude", providerID: "anthropic-gateway" },
|
||||
{ id: "glm", providerID: "zai-coding-plan", package: "@opencode/ai/providers/zai-coding-plan/messages" },
|
||||
{ id: "sonnet", providerID: "anthropic" },
|
||||
{ id: "gemini", providerID: "google" },
|
||||
];
|
||||
const snapshot = structuredClone(models);
|
||||
const { context } = pluginContextV2(
|
||||
{ proxyUrl: "http://127.0.0.1:8787" },
|
||||
{
|
||||
providers: [
|
||||
{
|
||||
id: "ollama",
|
||||
package: "@opencode/ai/providers/openai-compatible",
|
||||
settings: { baseURL: "http://127.0.0.1:11434/v1" },
|
||||
},
|
||||
{
|
||||
id: "openai",
|
||||
package: "@opencode/ai/providers/openai/responses",
|
||||
settings: { baseURL: "http://127.0.0.1:8787/v1" },
|
||||
},
|
||||
{
|
||||
id: "anthropic-gateway",
|
||||
package: "@opencode/ai/providers/anthropic",
|
||||
settings: { baseURL: "https://gateway.example/v1" },
|
||||
},
|
||||
{
|
||||
id: "zai-coding-plan",
|
||||
package: "@opencode/ai/providers/zai-coding-plan/chat",
|
||||
settings: { baseURL: "https://api.z.ai/api/coding/paas/v4" },
|
||||
},
|
||||
{ id: "anthropic", package: "@opencode/ai/providers/anthropic" },
|
||||
{
|
||||
id: "google",
|
||||
package: "@ai-sdk/google",
|
||||
settings: { baseURL: "https://generativelanguage.googleapis.com/v1beta" },
|
||||
},
|
||||
],
|
||||
models,
|
||||
},
|
||||
);
|
||||
|
||||
const cleanup = await headroomSetup(context);
|
||||
await cleanup?.();
|
||||
|
||||
expect(models).toEqual(snapshot);
|
||||
});
|
||||
|
||||
it("releases the transport on cleanup so reloads do not leak it", async () => {
|
||||
const { context } = pluginContextV2({ proxyUrl: "http://127.0.0.1:8787" });
|
||||
|
||||
const first = await headroomSetup(context);
|
||||
expect(transportState()?.refs).toBe(1);
|
||||
await first?.();
|
||||
expect(transportState()).toBeUndefined();
|
||||
|
||||
const second = await headroomSetup(context);
|
||||
expect(transportState()?.refs).toBe(1);
|
||||
await second?.();
|
||||
expect(transportState()).toBeUndefined();
|
||||
});
|
||||
|
||||
it("releases the transport when hook registration fails", async () => {
|
||||
const { context } = pluginContextV2({ proxyUrl: "http://127.0.0.1:8787" });
|
||||
(context as { shell: { hook: () => Promise<never> } }).shell.hook = async () => {
|
||||
throw new Error("registration failed");
|
||||
};
|
||||
|
||||
await expect(headroomSetup(context)).rejects.toThrow("registration failed");
|
||||
expect(transportState()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("default export", () => {
|
||||
it("carries both the OpenCode 1.x and 2.x entry points", () => {
|
||||
expect(HeadroomOpenCodePlugin).toEqual({
|
||||
id: "headroom",
|
||||
server: HeadroomPlugin,
|
||||
setup: headroomSetup,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Plugin } from "@opencode-ai/plugin";
|
||||
import { tool } from "@opencode-ai/plugin";
|
||||
import type { Plugin as PluginV2 } from "@opencode/plugin";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
@@ -7,7 +8,15 @@ import {
|
||||
getDefaultProxyUrl,
|
||||
trimTrailingSlashes,
|
||||
} from "./retrieve.js";
|
||||
import { installHeadroomTransport } from "./transport.js";
|
||||
import {
|
||||
BASE_URL_HEADER,
|
||||
EXCLUDE_HOSTS_ENV,
|
||||
ORIGINAL_PATH_HEADER,
|
||||
PROJECT_HEADER,
|
||||
installHeadroomTransport,
|
||||
modelBaseRoutesThroughProxy,
|
||||
normalizeExcludeHosts,
|
||||
} from "./transport.js";
|
||||
|
||||
export interface HeadroomOpenCodePluginOptions {
|
||||
proxyUrl?: string;
|
||||
@@ -17,6 +26,8 @@ export interface HeadroomOpenCodePluginOptions {
|
||||
debug?: boolean;
|
||||
}
|
||||
|
||||
export const HEADROOM_PLUGIN_ID = "headroom";
|
||||
|
||||
function normalizeProxyUrl(url: string): string {
|
||||
return trimTrailingSlashes(url);
|
||||
}
|
||||
@@ -30,6 +41,75 @@ function resolveProxyUrl(options?: HeadroomOpenCodePluginOptions): string {
|
||||
);
|
||||
}
|
||||
|
||||
// The exclusion list governs both the transport patch and the 2.x model
|
||||
// rewrite, so resolve it once: option over environment variable, normalized
|
||||
// the same way the transport does.
|
||||
function resolveExcludeHosts(options?: HeadroomOpenCodePluginOptions): string[] {
|
||||
return normalizeExcludeHosts(options?.excludeHosts ?? process.env[EXCLUDE_HOSTS_ENV] ?? "");
|
||||
}
|
||||
|
||||
function headroomShellEnv(
|
||||
proxyUrl: string,
|
||||
project: string,
|
||||
options: HeadroomOpenCodePluginOptions,
|
||||
): Record<string, string> {
|
||||
return {
|
||||
HEADROOM_ACTIVE: "1",
|
||||
HEADROOM_PROXY_URL: proxyUrl,
|
||||
HEADROOM_PROJECT: project,
|
||||
...(options.backend ? { HEADROOM_BACKEND: options.backend } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// The endpoint an OpenCode 2.x package calls under its baseURL, for packages
|
||||
// on the OpenAI chat-completions or responses wire format; undefined otherwise.
|
||||
// `.../messages` (Anthropic wire) and other protocols are left alone.
|
||||
function openAiWireSuffix(pkg: string | undefined): string | undefined {
|
||||
if (!pkg?.startsWith("@opencode/ai/providers/")) return undefined;
|
||||
if (pkg === "@opencode/ai/providers/openai-compatible" || pkg.endsWith("/chat")) {
|
||||
return "/chat/completions";
|
||||
}
|
||||
if (pkg.endsWith("-responses") || pkg.endsWith("/responses")) return "/responses";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// OpenCode 2.x sends model traffic through Effect's FetchHttpClient, which
|
||||
// captures `globalThis.fetch` on the process's first HTTP request, before any
|
||||
// plugin runs, so the transport's fetch patch never sees it. Point each
|
||||
// remote OpenAI-wire model at the proxy instead, with the same routing headers
|
||||
// the transport sends: the upstream origin, and the real path the proxy
|
||||
// appends to it.
|
||||
type ModelEditor = Parameters<Parameters<PluginV2.Context["model"]["transform"]>[0]>[0];
|
||||
|
||||
function routeModelsThroughProxy(
|
||||
models: ModelEditor,
|
||||
proxyUrl: string,
|
||||
project: string,
|
||||
excludeHosts: string[],
|
||||
): void {
|
||||
for (const model of models.list()) {
|
||||
// DeepMutable turns the branded ID strings into object types.
|
||||
const providerID = String(model.providerID);
|
||||
const modelID = String(model.id);
|
||||
const provider = models.provider.get(providerID)?.provider;
|
||||
const suffix = openAiWireSuffix(model.package ?? provider?.package);
|
||||
const baseURL = model.settings?.baseURL ?? provider?.settings?.baseURL;
|
||||
if (!suffix || typeof baseURL !== "string") continue;
|
||||
if (!modelBaseRoutesThroughProxy(baseURL, proxyUrl, excludeHosts)) continue;
|
||||
const upstream = new URL(baseURL);
|
||||
models.update(providerID, modelID, (draft) => {
|
||||
draft.settings = { ...draft.settings, baseURL: `${proxyUrl}/v1` };
|
||||
draft.headers = {
|
||||
...draft.headers,
|
||||
[BASE_URL_HEADER]: upstream.origin,
|
||||
[ORIGINAL_PATH_HEADER]: `${trimTrailingSlashes(upstream.pathname)}${suffix}`,
|
||||
[PROJECT_HEADER]: project,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// OpenCode 1.x: a factory returning a hooks object.
|
||||
export const HeadroomPlugin: Plugin = async (input, options = {}) => {
|
||||
const pluginOptions = options as HeadroomOpenCodePluginOptions;
|
||||
const proxyUrl = resolveProxyUrl(pluginOptions);
|
||||
@@ -63,14 +143,64 @@ export const HeadroomPlugin: Plugin = async (input, options = {}) => {
|
||||
}),
|
||||
},
|
||||
"shell.env": async (_input, output) => {
|
||||
output.env.HEADROOM_ACTIVE = "1";
|
||||
output.env.HEADROOM_PROXY_URL = proxyUrl;
|
||||
output.env.HEADROOM_PROJECT = project;
|
||||
if (pluginOptions.backend) {
|
||||
output.env.HEADROOM_BACKEND = pluginOptions.backend;
|
||||
}
|
||||
Object.assign(output.env, headroomShellEnv(proxyUrl, project, pluginOptions));
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default HeadroomPlugin;
|
||||
// OpenCode 2.x: setup registers hooks imperatively and returns its cleanup.
|
||||
// OpenCode reruns setup (after cleanup) whenever it hot-reloads the plugin;
|
||||
// the transport is refcounted, so reinstalling is safe.
|
||||
export const headroomSetup: PluginV2.Plugin["setup"] = async (ctx) => {
|
||||
const pluginOptions = ctx.options as HeadroomOpenCodePluginOptions;
|
||||
const proxyUrl = resolveProxyUrl(pluginOptions);
|
||||
const project =
|
||||
pluginOptions.project ?? ctx.location.project.id ?? ctx.location.directory;
|
||||
const retrieveTool = createHeadroomRetrieveTool({ proxyBaseUrl: proxyUrl });
|
||||
const excludeHosts = resolveExcludeHosts(pluginOptions);
|
||||
const uninstallTransport = installHeadroomTransport({
|
||||
proxyUrl,
|
||||
project,
|
||||
excludeHosts,
|
||||
debug: pluginOptions.debug,
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.model.transform((models) => {
|
||||
routeModelsThroughProxy(models, proxyUrl, project, excludeHosts);
|
||||
});
|
||||
await ctx.tool.transform((editor) => {
|
||||
editor.add({
|
||||
name: retrieveTool.name,
|
||||
description: retrieveTool.description,
|
||||
input: retrieveTool.parameters,
|
||||
// Offer the tool directly, like OpenCode's built-ins, rather than only
|
||||
// through the code-mode `execute` tool.
|
||||
options: { codemode: false },
|
||||
async execute(args) {
|
||||
return { content: await retrieveTool.execute(args as { hash: string }) };
|
||||
},
|
||||
});
|
||||
});
|
||||
await ctx.shell.hook("create.before", (shell) => {
|
||||
Object.assign(shell.env, headroomShellEnv(proxyUrl, project, pluginOptions));
|
||||
});
|
||||
} catch (error) {
|
||||
uninstallTransport();
|
||||
throw error;
|
||||
}
|
||||
|
||||
return () => {
|
||||
uninstallTransport();
|
||||
};
|
||||
};
|
||||
|
||||
// One default export for both loaders: OpenCode 1.x reads `server`, 2.x reads
|
||||
// `setup`, and each ignores the other's key.
|
||||
export const HeadroomOpenCodePlugin = {
|
||||
id: HEADROOM_PLUGIN_ID,
|
||||
server: HeadroomPlugin,
|
||||
setup: headroomSetup,
|
||||
};
|
||||
|
||||
export default HeadroomOpenCodePlugin;
|
||||
|
||||
@@ -7,11 +7,11 @@ const http2 = nodeRequire("node:http2") as typeof import("node:http2");
|
||||
const childProcess = nodeRequire("node:child_process") as typeof import("node:child_process");
|
||||
const fs = nodeRequire("node:fs") as typeof import("node:fs");
|
||||
|
||||
const BASE_URL_HEADER = "x-headroom-base-url";
|
||||
const ORIGINAL_PATH_HEADER = "x-headroom-original-path";
|
||||
const PROJECT_HEADER = "x-headroom-project";
|
||||
export const BASE_URL_HEADER = "x-headroom-base-url";
|
||||
export const ORIGINAL_PATH_HEADER = "x-headroom-original-path";
|
||||
export const PROJECT_HEADER = "x-headroom-project";
|
||||
const PROXY_ENV = "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL";
|
||||
const EXCLUDE_HOSTS_ENV = "HEADROOM_OPENCODE_EXCLUDE_HOSTS";
|
||||
export const EXCLUDE_HOSTS_ENV = "HEADROOM_OPENCODE_EXCLUDE_HOSTS";
|
||||
const STATE_KEY = Symbol.for("headroom.opencode.transport");
|
||||
|
||||
type FetchArgs = Parameters<typeof fetch>;
|
||||
@@ -69,7 +69,7 @@ function setState(state: TransportState | undefined): void {
|
||||
}
|
||||
|
||||
// ponytail: the shim only exists next to the checkout build
|
||||
// (plugins/opencode/dist/). The wheel ships entry.opencode.js alone, so
|
||||
// (plugins/opencode/dist/). The wheel shipped the entry bundle alone, so
|
||||
// `--import=<missing file>` killed every Node child at startup — including
|
||||
// OpenCode's stdio MCP servers (issue #2798). No shim on disk, no injection:
|
||||
// children go direct instead of dying. Upgrade path is bundling the shim into
|
||||
@@ -208,7 +208,7 @@ function isLoopback(hostname: string): boolean {
|
||||
// string is the comma-separated env form; plugin options arrive from untyped
|
||||
// JSON, so a lone string there is treated the same way instead of iterated
|
||||
// character by character.
|
||||
function normalizeExcludeHosts(entries: string | Iterable<unknown>): string[] {
|
||||
export function normalizeExcludeHosts(entries: string | Iterable<unknown>): string[] {
|
||||
const hosts = new Set<string>();
|
||||
for (const entry of typeof entries === "string" ? entries.split(",") : entries) {
|
||||
const host = String(entry).trim().toLowerCase().replace(/^(\*\.|\.)/, "");
|
||||
@@ -243,7 +243,7 @@ function isLlmEndpointPath(pathname: string): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function shouldRoute(url: URL, proxy: URL, excludeHosts: string[]): boolean {
|
||||
function isRoutableUpstream(url: URL, proxy: URL, excludeHosts: string[]): boolean {
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
return false;
|
||||
}
|
||||
@@ -256,7 +256,28 @@ function shouldRoute(url: URL, proxy: URL, excludeHosts: string[]): boolean {
|
||||
if (isExcludedHost(url.hostname, excludeHosts)) {
|
||||
return false;
|
||||
}
|
||||
return isLlmEndpointPath(url.pathname);
|
||||
return true;
|
||||
}
|
||||
|
||||
function shouldRoute(url: URL, proxy: URL, excludeHosts: string[]): boolean {
|
||||
return isRoutableUpstream(url, proxy, excludeHosts) && isLlmEndpointPath(url.pathname);
|
||||
}
|
||||
|
||||
// OpenCode 2.x hands the plugin model base URLs (e.g.
|
||||
// https://opencode.ai/zen/go/v1), not inference endpoints: setup appends the
|
||||
// wire path when it rewrites the model, so the endpoint-suffix check cannot
|
||||
// apply. Eligibility is the shared host/protocol contract only — http(s),
|
||||
// not loopback, not the proxy itself, not an excluded host.
|
||||
export function modelBaseRoutesThroughProxy(
|
||||
baseUrl: string,
|
||||
proxyUrl: string,
|
||||
excludeHosts: string[] = [],
|
||||
): boolean {
|
||||
try {
|
||||
return isRoutableUpstream(new URL(baseUrl), normalizeProxyUrl(proxyUrl), excludeHosts);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function routedUrl(upstream: URL, proxy: URL): URL {
|
||||
|
||||
@@ -6,10 +6,13 @@ import { defineConfig } from "tsup";
|
||||
// with node_modules present; pip installs have no node_modules, so this
|
||||
// variant bundles every dependency into a single loadable file.
|
||||
export default defineConfig({
|
||||
// The entry is emitted as `index.js` because OpenCode 2.x only loads a local
|
||||
// plugin from a directory, resolving `<dir>/server.*` then `<dir>/index.*`;
|
||||
// 1.x resolves a package-less directory to its `index.*` too.
|
||||
// `hook-shim/handler` is the self-contained Node `--import` loader shipped
|
||||
// alongside the entry so spawned Node children route their traffic too (#2850).
|
||||
entry: {
|
||||
"entry.opencode": "src/entry.opencode.ts",
|
||||
index: "src/entry.opencode.ts",
|
||||
"hook-shim/handler": "src/hook-shim.ts",
|
||||
},
|
||||
outDir: "dist-standalone",
|
||||
|
||||
@@ -31,6 +31,12 @@ def _mock_ensure_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(wrap_mod, "_ensure_proxy", fake_ensure_proxy)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _unknown_opencode_version(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Tests use a fake `opencode` binary; never run whatever is on PATH."""
|
||||
monkeypatch.setattr(wrap_mod, "opencode_major_version", lambda binary: None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def runner() -> CliRunner:
|
||||
return CliRunner()
|
||||
@@ -423,6 +429,43 @@ def test_wrap_opencode_sets_config_content_env(
|
||||
assert captured["args"] == ("--model", "gpt-4o")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("major", "args", "expected"),
|
||||
[
|
||||
(2, (), ("--standalone",)),
|
||||
(2, ("--model", "gpt-4o"), ("--standalone", "--model", "gpt-4o")),
|
||||
(2, ("run", "fix it"), ("run", "--standalone", "fix it")),
|
||||
(2, ("--server", "http://127.0.0.1:4096"), ("--server", "http://127.0.0.1:4096")),
|
||||
(1, ("--model", "gpt-4o"), ("--model", "gpt-4o")),
|
||||
(None, (), ()),
|
||||
],
|
||||
)
|
||||
def test_wrap_opencode_adds_standalone_on_v2(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
major: int | None,
|
||||
args: tuple[str, ...],
|
||||
expected: tuple[str, ...],
|
||||
) -> None:
|
||||
"""OpenCode 2.x must not attach to a background service that lacks Headroom's config."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
monkeypatch.setattr(wrap_mod, "opencode_major_version", lambda binary: major)
|
||||
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake_launch_tool(**kwargs): # noqa: ANN003
|
||||
captured.update(kwargs)
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
with patch.object(wrap_mod, "_launch_tool", side_effect=fake_launch_tool):
|
||||
result = runner.invoke(main, ["wrap", "opencode", "--no-mcp", "--", *args])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert captured["args"] == expected
|
||||
|
||||
|
||||
def test_wrap_opencode_does_not_add_base_url_env_vars(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
|
||||
@@ -521,8 +521,9 @@ def test_build_opencode_config_content_without_mcp(
|
||||
) -> None:
|
||||
from headroom.providers.opencode.runtime import build_opencode_config_content
|
||||
|
||||
plugin = tmp_path / "entry.opencode.js"
|
||||
plugin.write_text("export default () => {}", encoding="utf-8")
|
||||
plugin = tmp_path / "headroom-plugin"
|
||||
plugin.mkdir()
|
||||
(plugin / "index.js").write_text("export default {}", encoding="utf-8")
|
||||
monkeypatch.setenv("HEADROOM_OPENCODE_PLUGIN_PATH", str(plugin))
|
||||
|
||||
config = build_opencode_config_content(port=8787, include_mcp=False)
|
||||
@@ -539,7 +540,7 @@ def test_build_opencode_config_content_without_mcp(
|
||||
assert set(models) == {"gpt-4o", "gpt-4.1"}
|
||||
assert not any(model_id.startswith("claude-") for model_id in models)
|
||||
assert all(not model_id.startswith("headroom/") for model_id in models)
|
||||
# The transport plugin is injected by absolute path (opencode loads it directly).
|
||||
# The transport plugin directory is injected by absolute path (opencode loads it directly).
|
||||
assert config["plugin"] == [str(plugin)]
|
||||
|
||||
|
||||
@@ -574,8 +575,9 @@ def test_build_launch_env_with_project(monkeypatch: pytest.MonkeyPatch, tmp_path
|
||||
monkeypatch.delenv("HEADROOM_PROJECT", raising=False)
|
||||
monkeypatch.delenv("OPENAI_BASE_URL", raising=False)
|
||||
monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)
|
||||
plugin = tmp_path / "entry.opencode.js"
|
||||
plugin.write_text("export default () => {}", encoding="utf-8")
|
||||
plugin = tmp_path / "headroom-plugin"
|
||||
plugin.mkdir()
|
||||
(plugin / "index.js").write_text("export default {}", encoding="utf-8")
|
||||
monkeypatch.setenv("HEADROOM_OPENCODE_PLUGIN_PATH", str(plugin))
|
||||
|
||||
env, display = build_launch_env(
|
||||
@@ -586,7 +588,9 @@ def test_build_launch_env_with_project(monkeypatch: pytest.MonkeyPatch, tmp_path
|
||||
assert env["HEADROOM_PROJECT"] == "test-proj"
|
||||
# Plugin loaded → its proxy target is exported for self-configuration.
|
||||
assert env["HEADROOM_PROXY_URL"] == "http://127.0.0.1:8787"
|
||||
assert str(plugin) in env["OPENCODE_CONFIG_CONTENT"]
|
||||
# Compare the decoded entry: JSON escapes Windows backslashes, so the raw
|
||||
# path is not a substring of the serialized text there.
|
||||
assert json.loads(env["OPENCODE_CONFIG_CONTENT"])["plugin"] == [str(plugin)]
|
||||
assert f"plugin={HEADROOM_OPENCODE_PLUGIN}" in display
|
||||
assert "OPENAI_BASE_URL" not in env
|
||||
assert "ANTHROPIC_BASE_URL" not in env
|
||||
@@ -633,6 +637,76 @@ def test_inject_provider_config_strips_existing_markers(
|
||||
assert second.count("headroom") == first.count("headroom")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OpenCode 2.x --standalone launch flag
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("stdout", "returncode", "expected"),
|
||||
[
|
||||
("opencode v2.0.12\n", 0, 2),
|
||||
("1.18.32\n", 0, 1),
|
||||
("opencode v0.0.0-v2-202610061051\n", 0, 2),
|
||||
("0.0.0-dev-202610060234\n", 0, 0),
|
||||
("garbage\n", 0, None),
|
||||
("opencode v2.0.12\n", 1, None),
|
||||
],
|
||||
)
|
||||
def test_opencode_major_version_parses_both_cli_formats(
|
||||
monkeypatch: pytest.MonkeyPatch, stdout: str, returncode: int, expected: int | None
|
||||
) -> None:
|
||||
import subprocess
|
||||
|
||||
import headroom.providers.opencode.runtime as oc_runtime
|
||||
|
||||
def fake_run(*args, **kwargs): # noqa: ANN002, ANN003
|
||||
return subprocess.CompletedProcess(args[0], returncode, stdout=stdout, stderr="")
|
||||
|
||||
monkeypatch.setattr(oc_runtime, "run", fake_run)
|
||||
assert oc_runtime.opencode_major_version("opencode") == expected
|
||||
|
||||
|
||||
def test_opencode_major_version_missing_binary_is_unknown(tmp_path: Path) -> None:
|
||||
from headroom.providers.opencode.runtime import opencode_major_version
|
||||
|
||||
assert opencode_major_version(str(tmp_path / "no-such-opencode")) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("args", "expected"),
|
||||
[
|
||||
((), ("--standalone",)),
|
||||
(("--continue",), ("--standalone", "--continue")),
|
||||
(("run", "fix it"), ("run", "--standalone", "fix it")),
|
||||
(("--print-logs", "mini"), ("--print-logs", "mini", "--standalone")),
|
||||
(("models",), ("models",)),
|
||||
(("auth", "list"), ("auth", "list")),
|
||||
(("--session", "models"), ("--standalone", "--session", "models")),
|
||||
(("--prompt", "models", "extra"), ("--standalone", "--prompt", "models", "extra")),
|
||||
(("-s", "stats"), ("--standalone", "-s", "stats")),
|
||||
(("run", "--agent", "models"), ("run", "--standalone", "--agent", "models")),
|
||||
(("--standalone",), ("--standalone",)),
|
||||
(
|
||||
("run", "--server", "http://127.0.0.1:4096", "x"),
|
||||
("run", "--server", "http://127.0.0.1:4096", "x"),
|
||||
),
|
||||
(("--server=http://127.0.0.1:4096",), ("--server=http://127.0.0.1:4096",)),
|
||||
],
|
||||
)
|
||||
def test_with_opencode_standalone_on_v2(args: tuple[str, ...], expected: tuple[str, ...]) -> None:
|
||||
from headroom.providers.opencode.runtime import with_opencode_standalone
|
||||
|
||||
assert with_opencode_standalone(args, 2) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("major", [1, None])
|
||||
def test_with_opencode_standalone_leaves_v1_and_unknown_alone(major: int | None) -> None:
|
||||
from headroom.providers.opencode.runtime import with_opencode_standalone
|
||||
|
||||
assert with_opencode_standalone(("run", "fix it"), major) == ("run", "fix it")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("conflict", ["canonical", "sibling"])
|
||||
def test_jsonc_migration_treats_dangling_conflict_as_ambiguous(
|
||||
tmp_path: Path, conflict: str
|
||||
|
||||
@@ -9,26 +9,33 @@ import pytest
|
||||
import headroom.providers.opencode.runtime as oc_runtime
|
||||
from headroom.providers.opencode.runtime import headroom_opencode_plugin_path
|
||||
|
||||
_PACKAGED = Path(oc_runtime.__file__).resolve().parent / "_dist" / "entry.opencode.js"
|
||||
_REPO_BUILD = (
|
||||
Path(oc_runtime.__file__).resolve().parents[3]
|
||||
/ "plugins"
|
||||
/ "opencode"
|
||||
/ "dist"
|
||||
/ "entry.opencode.js"
|
||||
)
|
||||
# OpenCode 2.x only loads a configured local plugin from a directory, so the
|
||||
# resolver returns directories; each holds the loadable `index.js`.
|
||||
_PACKAGED = Path(oc_runtime.__file__).resolve().parent / "_dist"
|
||||
_REPO_BUILD = Path(oc_runtime.__file__).resolve().parents[3] / "plugins" / "opencode" / "dist"
|
||||
|
||||
|
||||
def test_packaged_bundle_is_committed_and_self_contained() -> None:
|
||||
# The wheel picks this file up via maturin's python-source packaging; if
|
||||
# it goes missing, pip installs silently lose all-provider routing again.
|
||||
assert _PACKAGED.is_file(), "committed wheel bundle missing - run npm run build:standalone"
|
||||
text = _PACKAGED.read_text(encoding="utf-8")
|
||||
bundle = _PACKAGED / "index.js"
|
||||
assert bundle.is_file(), "committed wheel bundle missing - run npm run build:standalone"
|
||||
text = bundle.read_text(encoding="utf-8")
|
||||
assert len(text) > 10_000, "bundle suspiciously small - not the standalone build?"
|
||||
# Self-contained: no bare npm imports; node builtins are the only imports
|
||||
# allowed (site-packages has no node_modules to resolve anything else).
|
||||
assert 'from "headroom-ai"' not in text
|
||||
assert 'from "@opencode-ai/plugin"' not in text
|
||||
assert 'from "@opencode/plugin"' not in text
|
||||
# One default export serves both loaders: 1.x calls `server`, 2.x `setup`.
|
||||
assert "server: HeadroomPlugin" in text
|
||||
assert "setup: headroomSetup" in text
|
||||
|
||||
|
||||
def test_packaged_bundle_is_the_only_file_in_its_directory() -> None:
|
||||
# OpenCode 2.x resolves `<dir>/server.*` before `<dir>/index.*`, and 1.x
|
||||
# prefers a `package.json` entry — a stray file here would shadow index.js.
|
||||
assert sorted(p.name for p in _PACKAGED.iterdir()) == ["index.js"]
|
||||
|
||||
|
||||
def test_hook_shim_is_committed_next_to_the_entry_bundle() -> None:
|
||||
@@ -37,7 +44,7 @@ def test_hook_shim_is_committed_next_to_the_entry_bundle() -> None:
|
||||
# spawned under `headroom wrap opencode` lose fetch/http routing (the
|
||||
# existsSync guard skips injection), and before that guard they crashed with
|
||||
# ERR_MODULE_NOT_FOUND on every Node MCP (#2850, #2806).
|
||||
shim = _PACKAGED.resolve().parent.parent / "hook-shim" / "handler.js"
|
||||
shim = _PACKAGED.parent / "hook-shim" / "handler.js"
|
||||
assert shim.is_file(), "committed wheel hook-shim missing - run npm run build:standalone"
|
||||
text = shim.read_text(encoding="utf-8")
|
||||
assert len(text) > 5_000, "hook-shim suspiciously small - not the standalone build?"
|
||||
@@ -49,19 +56,27 @@ def test_hook_shim_is_committed_next_to_the_entry_bundle() -> None:
|
||||
|
||||
|
||||
def test_plugin_path_env_override_wins(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
override = tmp_path / "custom.js"
|
||||
override.write_text("// plugin")
|
||||
override = tmp_path / "custom"
|
||||
override.mkdir()
|
||||
(override / "index.js").write_text("// plugin")
|
||||
monkeypatch.setenv("HEADROOM_OPENCODE_PLUGIN_PATH", str(override))
|
||||
assert headroom_opencode_plugin_path() == str(override)
|
||||
|
||||
|
||||
def test_plugin_path_env_override_missing_resolves_none(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setenv("HEADROOM_OPENCODE_PLUGIN_PATH", str(tmp_path / "missing"))
|
||||
assert headroom_opencode_plugin_path() is None
|
||||
|
||||
|
||||
def test_plugin_path_falls_back_to_packaged_bundle(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv("HEADROOM_OPENCODE_PLUGIN_PATH", raising=False)
|
||||
resolved = headroom_opencode_plugin_path()
|
||||
assert resolved is not None
|
||||
# In a repo checkout with a built plugins/opencode/dist the repo build wins
|
||||
# (fresher during development); otherwise the packaged bundle must resolve.
|
||||
if _REPO_BUILD.is_file():
|
||||
if (_REPO_BUILD / "index.js").is_file():
|
||||
assert resolved == str(_REPO_BUILD)
|
||||
else:
|
||||
assert resolved == str(_PACKAGED)
|
||||
|
||||
@@ -15,6 +15,7 @@ Contract pinned here:
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
@@ -30,6 +31,21 @@ MESSAGES = "/v1/messages"
|
||||
BODY = {"model": "glm-5.2", "max_tokens": 16, "messages": [{"role": "user", "content": "hi"}]}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _public_opencode_dns(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Keep header forwarding independent of live DNS; retain SSRF validation."""
|
||||
original = socket.getaddrinfo
|
||||
|
||||
def resolve(host, *args, **kwargs):
|
||||
if host == "opencode.ai":
|
||||
return [
|
||||
(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", 443))
|
||||
]
|
||||
return original(host, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(socket, "getaddrinfo", resolve)
|
||||
|
||||
|
||||
def _make_config(**overrides) -> ProxyConfig:
|
||||
base = {
|
||||
"optimize": False,
|
||||
|
||||
Reference in New Issue
Block a user