Skip to content

Experience-Driven Black-Box Cost Control for Coding Agents

opencode 2.2.5 console fixed

Aaron9009312f992f
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 5c1fd65..76fc48f 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -85,3 +85,47 @@ jobs:
env:
TE_CODEX_E2E: "1"
COLUMNS: "200"
+
+ opencode:
+ # The opencode plugin under opencode's own runtime, its binary run as Bun
+ # (tests/test_opencode_plugin.py). opencode 2.x runs plugins in its background service, which
+ # on Windows has no console: there the hooks are started from a parent with none, and must not
+ # each get a console window. No model is called.
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest]
+ runs-on: ${{ matrix.os }}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - uses: actions/checkout@v5
+ - uses: actions/setup-python@v6
+ with:
+ python-version: "3.13"
+ - uses: actions/setup-node@v5
+ with:
+ node-version: "22"
+ # Pinned: a new opencode can change how it runs plugins; move it on purpose.
+ - run: npm install -g @opencode/[email protected]
+ - run: python -m pip install pytest
+ # What each hook process was given goes out as a notice, and on failure the summary lines
+ # as an error, all shown on the check run without signing in.
+ - run: |
+ set -o pipefail
+ export TE_OPENCODE_BIN="$(npm root -g)/@opencode/cli/bin/opencode.exe"
+ status=0
+ python -m pytest tests/test_opencode_plugin.py -rfEsP --tb=short 2>&1 | tee pytest.log \
+ || status=$?
+ grep -hE '^(plugin|control): ' pytest.log | sed 's/^/::notice title=hook consoles::/' \
+ || true
+ if [ "$status" -ne 0 ]; then
+ msg=$(grep -E '^(FAILED|ERROR) |\.py:[0-9]+: ' pytest.log | head -60 \
+ | sed 's/%/%25/g' | awk '{printf "%s%%0A", $0}')
+ echo "::error title=pytest::${msg}"
+ fi
+ exit $status
+ env:
+ TE_OPENCODE_E2E: "1"
+ COLUMNS: "200"
diff --git a/plugin/README.md b/plugin/README.md
index 56fd4dd..38b7494 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -311,6 +311,11 @@ repository. opencode has no plugin slash commands, so every command runs from a
pruning does not apply. Micro-skills is off by default: `te --host opencode config set
microskills=on` (or `envfacts`, without model calls).
+**Environment variables on 2.x.** opencode 2.x runs plugins in its background service, not in
+the terminal you start it from, so a `TE_` variable you set there (`TE_DISABLE=1`, `TE_PYTHON`,
+...) reaches the plugin only once the service restarts: `opencode service restart` from a shell
+where it is set. Settings made with `te config` need no restart.
+
**How it hands a session over.** On 1.x the plugin exports the session with `opencode export` at
the end of every turn and sends the path; on 2.x, which has no export command, it records the
session from its events and writes the same JSON. A headless `opencode run` is folded when its
diff --git a/plugin/opencode/tokeneconomizer.ts b/plugin/opencode/tokeneconomizer.ts
index 1415bd3..0795732 100644
--- a/plugin/opencode/tokeneconomizer.ts
+++ b/plugin/opencode/tokeneconomizer.ts
@@ -69,6 +69,12 @@ function launch(
const childEnv = () => ({ ...process.env, PYTHONUTF8: "1", TE_OPENCODE_MODE: mode() });
+/** Every child starts with `windowsHide`. opencode 2.x runs plugins in its background service,
+ * which on Windows has no console, so each `python` the hooks start (one per prompt, tool call
+ * and turn) was given a console window of its own: the terminal flickered while the agent
+ * worked. Elsewhere the option does nothing. */
+const HIDDEN = { windowsHide: true } as const;
+
/** One dispatcher call; `{}` (no change) on any failure. */
function hook(payload: Record<string, unknown>): Promise<any> {
if (disabled()) return Promise.resolve({});
@@ -77,7 +83,11 @@ function hook(payload: Record<string, unknown>): Promise<any> {
let child;
try {
const [program, argv] = launch("te-hook", ["--host", "opencode"]);
- child = spawn(program, argv, { env: childEnv(), stdio: ["pipe", "pipe", "ignore"] });
+ child = spawn(program, argv, {
+ ...HIDDEN,
+ env: childEnv(),
+ stdio: ["pipe", "pipe", "ignore"],
+ });
} catch {
done({});
return;
@@ -112,6 +122,7 @@ function hookSync(payload: Record<string, unknown>) {
try {
const [program, argv] = launch("te-hook", ["--host", "opencode"]);
spawnSync(program, argv, {
+ ...HIDDEN,
env: childEnv(),
input: JSON.stringify(payload),
timeout: HOOK_TIMEOUT_MS,
@@ -136,6 +147,7 @@ function exportSession(sessionID: string, cwd: string): string {
? "opencode"
: process.execPath;
const res = spawnSync(exe, ["export", sessionID], {
+ ...HIDDEN,
cwd,
encoding: "utf8",
timeout: HOOK_TIMEOUT_MS,
diff --git a/tests/test_opencode_plugin.py b/tests/test_opencode_plugin.py
new file mode 100644
index 0000000..7a89592
--- /dev/null
+++ b/tests/test_opencode_plugin.py
@@ -0,0 +1,104 @@
+"""The opencode plugin under opencode's own runtime: CI's `opencode` job (`TE_OPENCODE_E2E=1`).
+
+opencode 2.x runs plugins in its background service, which on Windows has no console of its own,
+so every hook the plugin starts (a `python` per prompt, per tool call, per turn) got a new console
+window: the terminal "flickered" while the agent worked. These load the plugin's 2.x entry in
+opencode's binary run as Bun (`BUN_BE_BUN=1`), from a parent started without a console as the
+service is, drive one prompt and one tool call through it, and read back from each hook process
+whether it was given a console window. A copy of the plugin without `windowsHide` is the control.
+"""
+import json
+import os
+import pathlib
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+OPENCODE = os.environ.get("TE_OPENCODE_BIN") or shutil.which("opencode")
+
+pytestmark = pytest.mark.skipif(
+ os.environ.get("TE_OPENCODE_E2E") != "1" or not OPENCODE,
+ reason="drives opencode's own runtime: set TE_OPENCODE_E2E=1 and TE_OPENCODE_BIN to the "
+ "opencode binary (CI's opencode job)")
+
+# Imported by every hook's Python (through PYTHONPATH): whether it has a console window.
+PROBE = '''import json, os
+log = os.environ.get("TE_CONSOLE_PROBE")
+if log:
+ rec = {"pid": os.getpid()}
+ if os.name == "nt":
+ import ctypes
+ hwnd = ctypes.windll.kernel32.GetConsoleWindow()
+ rec["console_window"] = bool(hwnd)
+ rec["visible"] = bool(hwnd and ctypes.windll.user32.IsWindowVisible(hwnd))
+ with open(log, "a", encoding="utf-8") as fh:
+ fh.write(json.dumps(rec) + "\\n")
+'''
+
+# opencode 2.x's plugin context, as far as the plugin reads it: one prompt, one tool call, then
+# the process exits (the plugin hands the open session over then, with a blocking call).
+HARNESS = '''import plugin from %s;
+const hooks: Record<string, any> = {};
+await plugin.setup({
+ location: { directory: process.env.TE_WORK },
+ session: { hook: async (name: string, fn: any) => { hooks["session." + name] = fn; } },
+ tool: { hook: async (name: string, fn: any) => { hooks["tool." + name] = fn; } },
+ event: { subscribe: async function* () {} },
+});
+await hooks["session.prompt"]({ sessionID: "ses_t", messageID: "m1", prompt: { text: "say hi" } });
+await hooks["tool.execute.after"]({ sessionID: "ses_t", status: "completed", tool: "bash",
+ id: "c1", input: { command: "echo hi" }, result: { content: "hi", metadata: { exit: 0 } } });
+console.log("harness done");
+process.exit(0);
+'''
+
+
+def _run(tmp_path, plugin_file, name):
+ """The harness against `plugin_file`, from a parent with no console; the probe's records."""
+ work, probe_dir = tmp_path / f"work-{name}", tmp_path / "probe"
+ work.mkdir()
+ subprocess.run(["git", "init", "-q", str(work)], check=True)
+ probe_dir.mkdir(exist_ok=True)
+ (probe_dir / "sitecustomize.py").write_text(PROBE, encoding="utf-8")
+ log = tmp_path / f"probe-{name}.jsonl"
+ harness = tmp_path / f"harness-{name}.ts"
+ harness.write_text(HARNESS % json.dumps(pathlib.Path(plugin_file).as_uri()), encoding="utf-8")
+ env = dict(os.environ, BUN_BE_BUN="1", TE_WORK=str(work), TE_PYTHON=sys.executable,
+ TOKENECONOMIZER_HOME=str(tmp_path / f"te-{name}"), TE_CORE_PATH=REPO,
+ PYTHONPATH=str(probe_dir), TE_CONSOLE_PROBE=str(log))
+ env.pop("TE_DISABLE", None)
+ flags = subprocess.DETACHED_PROCESS if os.name == "nt" else 0
+ out = subprocess.run([OPENCODE, "run", str(harness)], capture_output=True, text=True,
+ encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL,
+ cwd=str(work), env=env, timeout=240, creationflags=flags)
+ assert out.returncode == 0 and "harness done" in out.stdout, (out.stdout[-1500:],
+ out.stderr[-1500:])
+ recs = [json.loads(ln) for ln in log.read_text(encoding="utf-8").splitlines()] \
+ if log.exists() else []
+ print(f"{name}: {recs}")
+ # SessionStart, UserPromptSubmit, PostToolUse, and SessionEnd as the process exits
+ assert len(recs) >= 4, (name, recs, out.stderr[-1500:])
+ return recs
+
+
+def test_the_plugins_hooks_open_no_console_window(tmp_path):
+ recs = _run(tmp_path, os.path.join(REPO, "plugin", "opencode", "tokeneconomizer.ts"),
+ "plugin")
+ if os.name != "nt":
+ return # the round trip is what is checked here
+ assert not [r for r in recs if r["visible"]], recs
+ # The control: the same plugin without `windowsHide`, next to a copy of its launchers. Each
+ # hook gets a console of its own, so this test would see the windows the fix removes.
+ copy = tmp_path / "plugin"
+ shutil.copytree(os.path.join(REPO, "plugin", "scripts"), copy / "scripts")
+ (copy / "opencode").mkdir()
+ text = open(os.path.join(REPO, "plugin", "opencode", "tokeneconomizer.ts"),
+ encoding="utf-8").read()
+ assert "windowsHide: true" in text
+ (copy / "opencode" / "tokeneconomizer.ts").write_text(
+ text.replace("windowsHide: true", "windowsHide: false"), encoding="utf-8")
+ control = _run(tmp_path, copy / "opencode" / "tokeneconomizer.ts", "control")
+ assert all(r["console_window"] for r in control), control