From 941a210c60a7845756f7e196f9e700387010e474 Mon Sep 17 00:00:00 2001 From: Have-Purple <17238093+Have-Purple@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:10:05 -0700 Subject: [PATCH] opencode: hand over a session that has gone quiet On 2.x 'opencode run' and the TUI are the same background service, so mode() cannot tell them apart: a headless run only folded at the next session start. A session quiet for TE's own recovery rule (fold.STALE_S, 600 s; TE_OPENCODE_QUIET_MS overrides it) is now handed over on a timer. Where mode()=='run' can still be detected, the immediate hand-over is unchanged, and any prompt or tool call resets the timer. plugin/README.md and docs/PLUGIN.md no longer say a TUI session waits for the next start. --- docs/PLUGIN.md | 3 +- plugin/README.md | 5 +-- plugin/opencode/tokeneconomizer.ts | 49 ++++++++++++++++++++++++++---- tests/test_opencode_plugin.py | 17 +++++++++++ 4 files changed, 65 insertions(+), 9 deletions(-) diff --git a/docs/PLUGIN.md b/docs/PLUGIN.md index 0ca122fc..b14d3eb9 100644 --- a/docs/PLUGIN.md +++ b/docs/PLUGIN.md @@ -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 diff --git a/plugin/README.md b/plugin/README.md index 0395d666..e9aad050 100644 --- a/plugin/README.md +++ b/plugin/README.md @@ -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, diff --git a/plugin/opencode/tokeneconomizer.ts b/plugin/opencode/tokeneconomizer.ts index ac9ffa69..24feec80 100644 --- a/plugin/opencode/tokeneconomizer.ts +++ b/plugin/opencode/tokeneconomizer.ts @@ -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 @@ -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>(); + 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 }); }; @@ -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) @@ -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" }, @@ -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 diff --git a/tests/test_opencode_plugin.py b/tests/test_opencode_plugin.py index 2064e5e6..6405cd05 100644 --- a/tests/test_opencode_plugin.py +++ b/tests/test_opencode_plugin.py @@ -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); ''' @@ -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"."""