Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,13 @@ ln -s /path/to/TokenEconomizer/plugin/opencode/tokeneconomizer.ts ~/.config/open

(Per repository: `.opencode/plugins/`.) Python 3.10+ must be on `PATH`, or named by `TE_PYTHON`.

**A copied plugin, not a link,** has no `scripts/` beside it, so it cannot find the dispatcher on
its own. Point it at the checkout: `TE_CORE_PATH=/path/to/TokenEconomizer`, or `TE_PLUGIN_ROOT`
at the directory that holds `scripts/`. Without one of them a copied plugin starts no hook at all.
The state launcher (`~/.tokeneconomizer/bin/te`) is written once a hook has reached the
dispatcher, so it cannot make the first one work. On 2.x the variable must reach the service —
`opencode service restart` from a shell where it is set (see below).

**2. Check it.** Run a session, then `~/.tokeneconomizer/bin/te --host opencode status` in the
repository. opencode has no plugin slash commands, so every command runs from a terminal. Tool
pruning does not apply. Micro-skills is off by default: `te --host opencode config set
Expand Down
50 changes: 48 additions & 2 deletions plugin/opencode/tokeneconomizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
*/
import type { Plugin } from "@opencode-ai/plugin";
import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
Expand All @@ -49,7 +49,53 @@ const HERE = (() => {
return __dirname;
}
})();
const SCRIPTS = join(HERE, "..", "scripts");
/**
* The directory holding the dispatcher (`te_bootstrap.py` / `te-hook`). Where it sits depends on
* how the plugin was put where opencode loads it from: the checkout keeps it at
* `<root>/plugin/scripts`, an installed plugin at `<dir>/scripts`. Resolve rather than assume, so
* a move of the install is not a move of the dispatcher -- and the hook fails open rather than
* pointing at a path that is not there.
*
* Only the shipped layouts and the launcher the plugin writes itself are anchors. Nothing walks
* up from the plugin's directory: on Windows that walk ends at `C:\`, where a standard user can
* create folders by default, so a planted `scripts/te_bootstrap.py` would run in every hook --
* and any unrelated ancestor would win over the dispatcher the plugin actually ships with.
*/
const findScripts = (): string => {
const wanted = (p: string) => existsSync(join(p, "te_bootstrap.py"));
// Named explicitly: `TE_PLUGIN_ROOT` is the package (`<root>/scripts`), `TE_CORE_PATH` the
// checkout the bootstrap already documents (`<root>/plugin/scripts`). A fresh install has no
// launcher yet, so these are what make the first hook work.
const explicit: string[] = [];
const pluginRoot = process.env.TE_PLUGIN_ROOT;
if (pluginRoot) explicit.push(join(pluginRoot, "scripts"));
const core = process.env.TE_CORE_PATH;
if (core) explicit.push(join(core, "plugin", "scripts"));
for (const c of explicit) {
if (wanted(c)) return c;
}
// The layout the plugin ships in: `<plugin>/opencode/<file>` next to `<plugin>/scripts`.
const shipped = join(HERE, "..", "scripts");
if (wanted(shipped)) return shipped;
const state = process.env.TOKENECONOMIZER_HOME || join(homedir(), ".tokeneconomizer");
const launcher = join(state, "bin", "te");
try {
if (existsSync(launcher)) {
// The launcher is `exec <plugin>/scripts/te "$@"`, so its own directory is the dispatcher's.
const body = readFileSync(launcher, "utf8");
const m = /exec\s+(.+?)\s+"\$@"/.exec(body);
if (m) {
const target = m[1].replace(/^['"]|['"]$/g, "");
const scripts = dirname(target);
if (wanted(scripts)) return scripts;
}
}
} catch {
/* an unreadable launcher is no anchor */
}
return shipped;
};
const SCRIPTS = findScripts();
const HOOK_TIMEOUT_MS = 60_000;

const truthy = (v: string | undefined) =>
Expand Down
100 changes: 95 additions & 5 deletions tests/test_opencode_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,10 @@
'''


def _run(tmp_path, plugin_file, name):
"""The harness against `plugin_file`, from a parent with no console; the probe's records."""
def _run(tmp_path, plugin_file, name, env_over=None, expect_hooks=True):
"""The harness against `plugin_file`, from a parent with no console; the probe's records.
`env_over` overrides the hook environment (e.g. no `TE_CORE_PATH`); with `expect_hooks`
False a run that starts no hook process at all is accepted, for the fail-open case."""
work, probe_dir = tmp_path / f"work-{name}", tmp_path / "probe"
work.mkdir()
subprocess.run(["git", "init", "-q", str(work)], check=True)
Expand All @@ -77,7 +79,9 @@ def _run(tmp_path, plugin_file, name):
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)
for var in ("TE_DISABLE", "TE_PLUGIN_ROOT"):
env.pop(var, None)
env.update(env_over or {})
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,
Expand All @@ -87,11 +91,97 @@ def _run(tmp_path, plugin_file, name):
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([r for r in recs if r["hook"]]) >= 4, (name, recs, out.stderr[-1500:])
hooks = [r for r in recs if r["hook"]]
if expect_hooks:
# SessionStart, UserPromptSubmit, PostToolUse, and SessionEnd as the process exits
assert len(hooks) >= 4, (name, recs, out.stderr[-1500:])
return recs


def _installed(tmp_path, name, bundle=False):
"""The layout opencode loads plugins from: `<dir>/plugins/<file>`. With `bundle`, also the
launchers beside it and the package under `lib/` — the self-contained bundle the old
`<here>/../scripts` assumption was written for."""
root = tmp_path / name
(root / "plugins").mkdir(parents=True)
dst = root / "plugins" / "tokeneconomizer.ts"
shutil.copyfile(os.path.join(REPO, "plugin", "opencode", "tokeneconomizer.ts"), dst)
if bundle:
shutil.copytree(os.path.join(REPO, "plugin", "scripts"), root / "scripts")
shutil.copytree(os.path.join(REPO, "tokeneconomizer"), root / "lib" / "tokeneconomizer",
ignore=shutil.ignore_patterns("__pycache__"))
return dst


def _te_sessions(tmp_path, name):
"""Session state the dispatcher wrote: proof the hook ran, not just that a Python started.
(A hook that cannot find `te_bootstrap.py` still spawns a Python, which records itself and
exits; only the dispatcher writes this.)"""
return list((tmp_path / f"te-{name}").glob("repos/*/opencode/sessions/*.json"))


def test_an_installed_copy_finds_the_dispatcher_through_te_core_path(tmp_path):
"""opencode loads a copy from its config directory, without the launchers beside it. Resolving
`join(here, '..', 'scripts')` there points at a directory that does not exist, and every hook
silently fails to spawn: TE looks loaded but folds, injects and guards nothing. The plugin
must find the checkout named by TE_CORE_PATH instead."""
plugin = _installed(tmp_path, "installed")
_run(tmp_path, plugin, "installed")
assert _te_sessions(tmp_path, "installed")


def test_an_installed_copy_with_a_sibling_scripts_copy_keeps_working(tmp_path):
"""The bundle the console-window tests use — launchers and package beside the plugin — must
keep resolving with no TE_CORE_PATH at all."""
plugin = _installed(tmp_path, "sibling", bundle=True)
_run(tmp_path, plugin, "sibling", env_over={"TE_CORE_PATH": ""})
assert _te_sessions(tmp_path, "sibling")


def test_a_scripts_directory_above_the_copy_is_not_an_anchor(tmp_path):
"""Resolution must not walk up from the plugin's own directory. A `scripts/te_bootstrap.py`
planted above it — on Windows the walk reaches `C:\\`, where a standard user can create
folders by default — would otherwise win over the dispatcher the plugin ships with, and every
hook would run it. Only the shipped layout and the state launcher are anchors."""
plugin = _installed(tmp_path, "planted")
planted = tmp_path / "scripts"
planted.mkdir()
marker = tmp_path / "planted-ran"
(planted / "te_bootstrap.py").write_text(
f"import pathlib\npathlib.Path({str(marker)!r}).write_text('ran')\n", encoding="utf-8")
_run(tmp_path, plugin, "planted", env_over={"TE_CORE_PATH": ""}, expect_hooks=False)
assert not marker.exists(), "the plugin ran a dispatcher from an ancestor directory"
assert not _te_sessions(tmp_path, "planted")


def test_the_state_launcher_is_read_when_its_target_has_a_space(tmp_path):
"""A fresh install's only anchor is the launcher `paths.ensure_launcher` writes under the state
root: `exec <plugin>/scripts/te "$@"`, with `shlex.quote` around the path, so a checkout under
a path with a space arrives quoted. The plugin must read that form, not only an unquoted path."""
core = tmp_path / "core copy" / "plugin"
shutil.copytree(os.path.join(REPO, "plugin", "scripts"), core / "scripts")
shutil.copytree(os.path.join(REPO, "tokeneconomizer"), core / "lib" / "tokeneconomizer",
ignore=shutil.ignore_patterns("__pycache__"))
launcher = tmp_path / "te-space" / "bin" / "te"
launcher.parent.mkdir(parents=True)
target = core / "scripts" / "te"
launcher.write_text(f'#!/bin/sh\nexec \'{target}\' "$@"\n', encoding="utf-8")
plugin = _installed(tmp_path, "space")
_run(tmp_path, plugin, "space", env_over={"TE_CORE_PATH": ""})
assert _te_sessions(tmp_path, "space")


def test_with_no_anchor_the_hooks_fail_open(tmp_path):
"""No TE_CORE_PATH, no launchers beside the copy, no state launcher: the dispatcher cannot be
found. The session must still run, and the dispatcher must start nothing — the silent failure
the resolver removes. This is the near-miss: with the old assumption the same session writes
no state at all."""
plugin = _installed(tmp_path, "bare")
_run(tmp_path, plugin, "bare", env_over={"TE_CORE_PATH": ""}, expect_hooks=False)
assert not _te_sessions(tmp_path, "bare"), list(
(tmp_path / "te-bare").rglob("sessions/*.json"))


def test_the_plugins_hooks_open_no_console_window(tmp_path):
recs = _run(tmp_path, os.path.join(REPO, "plugin", "opencode", "tokeneconomizer.ts"),
"plugin")
Expand Down