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
3 changes: 2 additions & 1 deletion docs/PLUGIN.md
Original file line number Diff line number Diff line change
Expand Up @@ -829,7 +829,8 @@ open-vocabulary. On a repository you do not trust, leave micro-skills off (the d
* **opencode (experimental)** — verified on 1.19.5, 2.2.0 and 2.2.5 (CI), not in the 2.x
terminal UI. On 2.x the loop guard's notices go to the server's stderr because plugins cannot
toast there; opencode has no deny-list settings file, so tool pruning does not apply (as on
Pi), and a TUI quit is only noticed by the next session's start.
Pi), and a TUI quit is noticed by the plugin itself: a session quiet for `fold.STALE_S`
(600 s; `TE_OPENCODE_QUIET_MS` overrides it) is handed over without waiting for a next start.
* **Grok Build (experimental)** — micro-skills and the loop guard, on 1.0.70. No tool pruning. The
start context reaches the model only with the session's first tool call (a session with none
never gets it), and the ledger counts it as injected from `SessionStart`. A turn interrupted
Expand Down
5 changes: 3 additions & 2 deletions plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -429,8 +429,9 @@ session from its events and writes the same JSON (where that copy holds no promp
2.x's `opencode session export` instead). A turn ends at 2.x's `session.execution.*` events or
the documented `session.idle`, whichever the release emits; a headless `opencode run` is folded
when its turn ends and a deleted session when it is deleted. Quitting the TUI gives a plugin no
chance to say so: that session is folded by the next session's start, once its export has been
quiet for 10 minutes.
chance to say so, so the plugin hands a session over itself once it has been quiet for 10
minutes — the window TE's own recovery uses (`fold.STALE_S`; `TE_OPENCODE_QUIET_MS` overrides it,
floor 10 s) — whether or not a later session start ever arrives.

**Model calls.** The proposer and the loop guard's judge run through `opencode run` on your
default opencode model (`paid_model` names another): tools that change anything are denied,
Expand Down
49 changes: 43 additions & 6 deletions plugin/opencode/tokeneconomizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@
* still-stuck notice is shown as a toast
* event session.idle -> Stop closes the turn; the session is exported as
* JSON and its path sent along
* event session.deleted, a headless run's end, or the process exiting
* -> SessionEnd hands the session to a detached fold; a
* TUI quit sends nothing, so the plugin's
* session-recovery folds it at the next
* start once its export has been quiet for
* 10 minutes
* event session.deleted, a headless run's end, a session quiet for 10 minutes, or the
* process exiting -> SessionEnd hands the session to a detached fold. On
* 2.x `opencode run` and the TUI are the
* same background process, so the plugin
* does not guess which one it is: any
* session quiet as long as TE's own
* recovery treats it as over (fold.STALE_S)
* is handed over, whether or not a later
* session start ever arrives.
*
* The module's one export is the default object below: opencode 1.x reads its `server`, 2.x its
* `setup`, and 1.x would call a second export as another plugin. The two entries map the same
Expand Down Expand Up @@ -381,7 +384,36 @@ const setupV2 = async (ctx: any) => {
manuals.set(id, out?.hookSpecificOutput?.additionalContext ?? "");
notify(out?.systemMessage);
};
/**
* A session that has been quiet this long is over, however it was started. opencode 2.x runs
* plugins in its background service, where `opencode run` and the TUI are the same process, so
* `mode()` cannot tell them apart -- and a release may move which one holds the plugin again.
* TE's own recovery already calls a session quiet for `fold.STALE_S` (600 s) over; this
* enforces the same rule here, so the hand-over does not wait for a later session start and
* does not depend on guessing the mode. Any activity resets the timer.
*/
const QUIET_MS = (() => {
const raw = Number(process.env.TE_OPENCODE_QUIET_MS);
return Number.isFinite(raw) && raw >= 10_000 ? raw : 600_000;
})();
const quiet = new Map<string, ReturnType<typeof setTimeout>>();
const settled = (id: string) => {
const timer = quiet.get(id);
if (timer) clearTimeout(timer);
quiet.delete(id);
};
const bumpQuiet = (id: string) => {
if (!open.has(id)) return;
settled(id);
const timer = setTimeout(() => {
quiet.delete(id);
if (open.has(id)) void end(id, "idle");
}, QUIET_MS);
(timer as unknown as { unref?: () => void }).unref?.();
quiet.set(id, timer);
};
const end = async (id: string, reason: string) => {
settled(id);
if (!open.delete(id)) return;
await hook({ ...base(id, writeExport(id)), hook_event_name: "SessionEnd", reason });
};
Expand All @@ -397,7 +429,10 @@ const setupV2 = async (ctx: any) => {
prompt_id: turns.get(id) ?? "",
stop_hook_active: false,
});
// Where the process really is a one-shot run, hand the session over now; everywhere else the
// quiet timer does it, so the fold no longer depends on how the plugin was launched.
if (mode() === "run") await end(id, "run");
else bumpQuiet(id);
};
process.once("exit", () => {
for (const id of open)
Expand Down Expand Up @@ -426,6 +461,7 @@ const setupV2 = async (ctx: any) => {
const turn = `${id}:${n}`;
turns.set(id, turn);
unsettled.add(id);
bumpQuiet(id);
const text: string = e.prompt?.text ?? "";
records.get(id)?.push({
info: { id: String(e.messageID ?? turn), role: "user" },
Expand Down Expand Up @@ -453,6 +489,7 @@ const setupV2 = async (ctx: any) => {
try {
await ctx.tool.hook("execute.after", async (e: any) => {
const id: string = e.sessionID;
bumpQuiet(id);
const ok = e.status === "completed";
const result = ok ? e.result : undefined;
const text = ok
Expand Down
17 changes: 17 additions & 0 deletions tests/test_opencode_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
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 } } });
if (process.env.TE_WAIT_MS) await new Promise((r) => setTimeout(r, Number(process.env.TE_WAIT_MS)));
console.log("harness done");
process.exit(0);
'''
Expand Down Expand Up @@ -113,6 +114,22 @@ def test_the_plugins_hooks_open_no_console_window(tmp_path):
assert all(r["visible"] for r in control if r["hook"]), control


def test_a_quiet_session_is_handed_over_without_a_mode_guess(tmp_path, monkeypatch):
"""On 2.x `opencode run` and the TUI are the same background process, so the plugin cannot
tell them apart. A session quiet for the window it is told (TE_OPENCODE_QUIET_MS) is handed
over with SessionEnd while the process is still up, instead of waiting for the next start."""
monkeypatch.setenv("TE_OPENCODE_QUIET_MS", "12000")
monkeypatch.setenv("TE_WAIT_MS", "15000")
_run(
tmp_path,
os.path.join(REPO, "plugin", "opencode", "tokeneconomizer.ts"),
"quiet",
)
(state,) = (tmp_path / "te-quiet").glob("repos/*/opencode/sessions/ses_t.json")
doc = json.loads(state.read_text(encoding="utf-8"))
assert doc.get("end_reason") == "idle" and doc.get("ended"), doc


class _Chat(BaseHTTPRequestHandler):
"""An OpenAI-compatible chat endpoint that answers every request with "done"."""

Expand Down