Skip to content

Commit ddb6dbd

Browse files
committed
fix(hook): migrate opencode hook to session.status; ship .opencode/package.json baseline
opencode v1.15.x silently broke sessions for users with our installed plugin and tool-override files. Two upstream changes are at play: - session.idle was deprecated (anomalyco/opencode bdfa213c, 2025-11-17) in favor of session.status with status.type === "idle". The deprecated event still fires today, but listening only for it is a walking time bomb. - When .opencode/tools/*.ts imports from @opencode-ai/plugin, opencode runs bun install against .opencode/ at startup. Without a baseline package.json, arborist can write "@opencode-ai/plugin": "local" (the dev-build sentinel), which then fails to resolve and the entire session goes unresponsive — every prompt silently dies with ERR_MODULE_NOT_FOUND. See anomalyco/opencode#28286. This commit: - Switches the generated plugin to listen for session.status + idle and default-export a PluginModule { id, server } shape (the v1 loader requires path plugins to carry an explicit id). - Ships .opencode/package.json pinning @opencode-ai/plugin to "latest"; opencode's arborist will overwrite that on first install with a real published version, pre-empting the @Local resolution failure. - Extends HookTarget with support_files so the package.json lands transparently alongside the plugin, including for users upgrading from a trie release where their plugin file is already up to date. Tests updated; new tests for the package.json baseline + idempotency. Full suite: 526 passed, 1 skipped. Ruff clean.
1 parent 8af7fde commit ddb6dbd

2 files changed

Lines changed: 212 additions & 23 deletions

File tree

‎tests/test_setup.py‎

Lines changed: 66 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,67 @@ def test_opencode_hook_creates_plugin_file(project: Path):
6565
assert result.path == expected_path
6666
assert expected_path.exists()
6767
contents = expected_path.read_text()
68-
# Key wiring: the plugin listens for session.idle and runs trie refresh.
69-
assert "session.idle" in contents
68+
# Key wiring: the plugin listens for `session.status` with idle status
69+
# (the new non-deprecated event) and runs trie refresh.
70+
assert "session.status" in contents
71+
assert '"idle"' in contents
7072
assert "trie refresh --after-turn" in contents
73+
# The plugin MUST default-export a PluginModule shape with `id`. opencode's
74+
# v1 loader (`readV1Plugin`) requires path plugins to carry an `id`, and
75+
# the legacy named-export path is being phased out.
76+
assert "export default" in contents
77+
assert '"trie-refresh"' in contents
78+
# The package.json baseline must land alongside the plugin to pre-empt
79+
# opencode's `@opencode-ai/plugin@local` resolution failure.
80+
pkg_json = project / ".opencode" / "package.json"
81+
assert pkg_json.exists()
82+
data = json.loads(pkg_json.read_text())
83+
assert data["dependencies"]["@opencode-ai/plugin"]
84+
85+
86+
def test_opencode_hook_writes_package_json_to_unblock_bun_install(project: Path):
87+
"""opencode runs `bun install` against `.opencode/` at startup; without a
88+
baseline `package.json`, an older opencode build could leave the directory
89+
pinned to `@opencode-ai/plugin@local` which then fails to resolve and
90+
silently breaks every prompt (anomalyco/opencode#28286). We ship a known-
91+
good baseline pointing at the `"latest"` tag — opencode's arborist will
92+
overwrite the version with the running opencode version on first install,
93+
which is a real published version and resolves cleanly.
94+
"""
95+
install(
96+
target_names=["opencode"],
97+
install_all=False,
98+
print_only=False,
99+
dry_run=False,
100+
project_root=project,
101+
)
102+
pkg_json = project / ".opencode" / "package.json"
103+
assert pkg_json.exists()
104+
data = json.loads(pkg_json.read_text())
105+
assert data["dependencies"]["@opencode-ai/plugin"] == "latest"
106+
107+
108+
def test_opencode_hook_package_json_is_idempotent(project: Path):
109+
"""A second run with the same support file content reports nothing
110+
surprising — the package.json contents are stable and we don't keep
111+
rewriting them."""
112+
install(
113+
target_names=["opencode"],
114+
install_all=False,
115+
print_only=False,
116+
dry_run=False,
117+
project_root=project,
118+
)
119+
pkg_path = project / ".opencode" / "package.json"
120+
before = pkg_path.read_text()
121+
install(
122+
target_names=["opencode"],
123+
install_all=False,
124+
print_only=False,
125+
dry_run=False,
126+
project_root=project,
127+
)
128+
assert pkg_path.read_text() == before
71129

72130

73131
def test_opencode_hook_is_idempotent(project: Path):
@@ -105,7 +163,7 @@ def test_opencode_hook_updates_when_contents_changed(project: Path):
105163
project_root=project,
106164
)
107165
assert plan.results[0].action == "updated"
108-
assert "session.idle" in plugin_path.read_text()
166+
assert "session.status" in plugin_path.read_text()
109167

110168

111169
def test_print_only_writes_no_files(project: Path):
@@ -118,7 +176,7 @@ def test_print_only_writes_no_files(project: Path):
118176
)
119177
assert plan.results[0].action == "preview"
120178
# Contents are still returned so the caller can render them.
121-
assert "session.idle" in plan.results[0].contents
179+
assert "session.status" in plan.results[0].contents
122180
# But nothing landed on disk.
123181
assert not (project / ".opencode").exists()
124182

@@ -211,7 +269,9 @@ def test_cli_setup_opencode_writes_both_files(project: Path, monkeypatch: pytest
211269
# Hook plugin written.
212270
hook_path = project / ".opencode" / "plugins" / "trie-refresh.ts"
213271
assert hook_path.exists()
214-
assert "session.idle" in hook_path.read_text()
272+
assert "session.status" in hook_path.read_text()
273+
# And the package.json baseline that lets `@opencode-ai/plugin` resolve.
274+
assert (project / ".opencode" / "package.json").exists()
215275

216276

217277
def test_cli_setup_claude_code_does_mcp_and_warns_about_hook(
@@ -236,7 +296,7 @@ def test_cli_setup_print_only_writes_nothing(project: Path, monkeypatch: pytest.
236296
assert not (project / "opencode.json").exists()
237297
assert not (project / ".opencode").exists()
238298
# But the preview text should reach the user.
239-
assert "session.idle" in result.output
299+
assert "session.status" in result.output
240300

241301

242302
def test_cli_setup_target_and_all_mutex(project: Path, monkeypatch: pytest.MonkeyPatch):

‎trie/hook_install.py‎

Lines changed: 146 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@
77
remember.
88
99
Coverage today is intentionally narrow: opencode is the only agent with a
10-
documented event API we can wire into (`session.idle`). For every other
11-
agent we know about, this module returns a `needs_manual_setup` result
12-
that surfaces the instructions a human has to follow.
10+
documented event API we can wire into (`session.status` with idle status;
11+
the older `session.idle` event was deprecated upstream on 2025-11-17). For
12+
every other agent we know about, this module returns a `needs_manual_setup`
13+
result that surfaces the instructions a human has to follow.
1314
1415
The shape mirrors `mcp_install` so `trie setup` can present one unified
1516
report. Each `HookTarget` describes:
@@ -55,6 +56,21 @@ class HookApplyResult:
5556
detail: str = ""
5657

5758

59+
@dataclass(frozen=True)
60+
class HookSupportFile:
61+
"""A secondary file written alongside the primary plugin file.
62+
63+
Used for runtime scaffolding the hook depends on but doesn't itself
64+
contain — e.g. the `.opencode/package.json` that lets opencode's bun
65+
install pin `@opencode-ai/plugin` cleanly. Reported in the apply result
66+
via `detail` but doesn't appear as a separate `HookApplyResult`; this is
67+
intentionally a quiet, hook-internal concern.
68+
"""
69+
70+
relative_path: tuple[str, ...]
71+
render_contents: Callable[[Path], str]
72+
73+
5874
@dataclass(frozen=True)
5975
class HookTarget:
6076
"""Static description of an agent's turn-boundary hook surface.
@@ -63,6 +79,11 @@ class HookTarget:
6379
`relative_path`. When `None`, the target is known but doesn't have an
6480
automatable hook story — `apply_one` returns `needs_manual_setup` so the
6581
user knows to wire it themselves.
82+
83+
`support_files` is for ancillary files the hook's runtime depends on
84+
(e.g. `.opencode/package.json`). They're written transparently as part
85+
of `apply_one` and are subject to the same idempotency rules as the
86+
primary file.
6687
"""
6788

6889
name: str
@@ -73,10 +94,11 @@ class HookTarget:
7394
relative_path: tuple[str, ...] | None = None
7495
render_contents: Callable[[Path], str] | None = None
7596
manual_instructions: str = ""
97+
support_files: tuple[HookSupportFile, ...] = ()
7698

7799

78100
# ---------------------------------------------------------------------------
79-
# opencode: plugin-based turn hook via the `session.idle` event.
101+
# opencode: plugin-based turn hook via the `session.status` event (idle status).
80102
# ---------------------------------------------------------------------------
81103

82104

@@ -87,9 +109,14 @@ def _render_opencode_plugin(_project_root: Path) -> str:
87109
"""Render the opencode plugin file that fires `trie refresh --after-turn`
88110
every time an agent session goes idle.
89111
90-
The plugin listens for the `session.idle` event (documented in opencode's
91-
plugin reference) and shells out to the global `trie` binary. The hook
92-
runs in fire-and-await fashion: opencode pauses for the duration before
112+
The plugin listens for `session.status` with `status.type === "idle"`
113+
(documented in opencode's plugin reference) and shells out to the global
114+
`trie` binary. opencode also still emits a deprecated `session.idle` event;
115+
we ignore it to avoid double-firing — `session.status` is the future-proof
116+
surface (the legacy event was marked deprecated in upstream commit
117+
bdfa213c on 2025-11-17).
118+
119+
The hook runs fire-and-await: opencode pauses for the duration before
93120
moving on, which is the right tradeoff during eval runs where we'd rather
94121
the next turn see a fresh graph than start fast and look stale.
95122
@@ -102,25 +129,70 @@ def _render_opencode_plugin(_project_root: Path) -> str:
102129
// when an opencode session goes idle, keeping the graph + triefact tree in
103130
// sync with edits the agent made during the turn.
104131
//
132+
// We listen for `session.status` with status.type === "idle" — the
133+
// `session.idle` event was deprecated upstream (commit bdfa213c, 2025-11-17)
134+
// and listening for both would double-fire the refresh.
135+
//
105136
// See https://opencode.ai/docs/plugins for the plugin API.
106137
107138
import type { Plugin } from "@opencode-ai/plugin"
108139
109-
export const TrieRefresh: Plugin = async ({ $, directory }) => {
140+
const TrieRefreshPlugin: Plugin = async ({ $, directory }) => {
110141
return {
111142
event: async ({ event }) => {
112-
if (event.type === "session.idle") {
113-
try {
114-
await $`trie refresh --after-turn`.cwd(directory).quiet()
115-
} catch {
116-
// Swallow errors. trie refresh logs to debug.jsonl on failure; the
117-
// plugin throwing would noisy-up the opencode TUI for problems the
118-
// user can diagnose via `trie audit` later.
119-
}
143+
if (event.type !== "session.status") return
144+
if ((event as any).properties?.status?.type !== "idle") return
145+
try {
146+
await $`trie refresh --after-turn`.cwd(directory).quiet()
147+
} catch {
148+
// Swallow errors. trie refresh logs to debug.jsonl on failure; the
149+
// plugin throwing would noisy-up the opencode TUI for problems the
150+
// user can diagnose via `trie audit` later.
120151
}
121152
},
122153
}
123154
}
155+
156+
// opencode v1.x prefers a default-exported PluginModule object ({ id, server }).
157+
// Named exports (the v0 shape) still work via the legacy loader, but the v1
158+
// shape is what the loader looks for first and is required for path plugins
159+
// since `resolvePluginId` mandates an explicit id.
160+
export default {
161+
id: "trie-refresh",
162+
server: TrieRefreshPlugin,
163+
}
164+
"""
165+
166+
167+
def _render_opencode_package_json(_project_root: Path) -> str:
168+
"""Render `.opencode/package.json` pinning `@opencode-ai/plugin`.
169+
170+
Without this file, opencode runs `bun install` against the `.opencode/`
171+
directory at startup and tries to add `@opencode-ai/plugin` with a version
172+
derived from the running opencode build. For dev/source builds (or any
173+
stale state where the version resolves to `"local"`), bun writes
174+
`"@opencode-ai/plugin": "local"` into the generated package.json, the next
175+
install fails ("No matching version found for @opencode-ai/plugin@local"),
176+
and every `.opencode/tools/*.ts` import that pulls from `@opencode-ai/plugin`
177+
dies with ERR_MODULE_NOT_FOUND. The user-visible symptom is that opencode
178+
sessions become silently unresponsive (see anomalyco/opencode#28286 and
179+
#27676).
180+
181+
Shipping a known-good baseline pinned to `"latest"` pre-empts opencode's
182+
broken auto-pin: arborist will overwrite our `"latest"` with the running
183+
opencode version, which is a real published version and resolves cleanly.
184+
185+
We declare it as a `dependencies` entry (not `peerDependencies`) so bun's
186+
arborist treats it as the canonical install target.
187+
"""
188+
return """{
189+
"//": "Auto-generated by `trie setup`. Do not hand-edit — opencode rewrites this on every startup. The pin pre-empts the @opencode-ai/plugin@local resolution failure that silently kills tool overrides; see https://github.com/anomalyco/opencode/issues/28286.",
190+
"name": "trie-opencode-overrides",
191+
"private": true,
192+
"dependencies": {
193+
"@opencode-ai/plugin": "latest"
194+
}
195+
}
124196
"""
125197

126198

@@ -136,6 +208,18 @@ def _render_opencode_plugin(_project_root: Path) -> str:
136208
display_name="opencode",
137209
relative_path=(".opencode", "plugins", _OPENCODE_PLUGIN_FILENAME),
138210
render_contents=_render_opencode_plugin,
211+
support_files=(
212+
# opencode runs `bun install` against `.opencode/` at startup and
213+
# tries to add `@opencode-ai/plugin`. If a stale `package.json`
214+
# pins it to `"local"` (the dev-build sentinel), every subsequent
215+
# install fails and tool-override `.ts` files die with
216+
# ERR_MODULE_NOT_FOUND, silently breaking the session. Shipping
217+
# our own baseline pre-empts that.
218+
HookSupportFile(
219+
relative_path=(".opencode", "package.json"),
220+
render_contents=_render_opencode_package_json,
221+
),
222+
),
139223
),
140224
"claude-code": HookTarget(
141225
name="claude-code",
@@ -312,12 +396,21 @@ def apply_one(
312396
detail=f"could not read existing hook file: {exc}",
313397
)
314398
if current == contents:
399+
# Still pass through the support-file writer: a user upgrading
400+
# trie from a release that predates `support_files` (or one that
401+
# had a manually-deleted `.opencode/package.json`) needs the
402+
# baseline package.json to land even when the plugin itself is
403+
# already up to date.
404+
support_notes = _apply_support_files(target.support_files, project_root)
405+
detail = "hook already installed with the same contents"
406+
if support_notes:
407+
detail = f"{detail}; {'; '.join(support_notes)}"
315408
return HookApplyResult(
316409
target=target.name,
317410
action="skipped",
318411
path=target_path,
319412
contents=contents,
320-
detail="hook already installed with the same contents",
413+
detail=detail,
321414
)
322415

323416
if dry_run:
@@ -330,9 +423,45 @@ def apply_one(
330423

331424
target_path.parent.mkdir(parents=True, exist_ok=True)
332425
target_path.write_text(contents)
426+
427+
support_notes = _apply_support_files(target.support_files, project_root)
428+
detail = "; ".join(support_notes) if support_notes else ""
429+
333430
return HookApplyResult(
334431
target=target.name,
335432
action="updated" if existed_before else "created",
336433
path=target_path,
337434
contents=contents,
435+
detail=detail,
338436
)
437+
438+
439+
def _apply_support_files(
440+
files: tuple[HookSupportFile, ...],
441+
project_root: Path,
442+
) -> list[str]:
443+
"""Write each support file with the same created/updated/skipped semantics
444+
as the primary hook file, returning short human-readable notes.
445+
446+
Failures to write a single support file are noted but don't propagate;
447+
the primary hook is the gating contract and we don't want a missing
448+
`.opencode/package.json` write permission to mask a successful plugin
449+
install. Issues become visible through trie's own telemetry and the
450+
notes returned here.
451+
"""
452+
notes: list[str] = []
453+
for support in files:
454+
path = project_root.joinpath(*support.relative_path)
455+
rel = "/".join(support.relative_path)
456+
contents = support.render_contents(project_root)
457+
try:
458+
if path.exists() and path.read_text() == contents:
459+
notes.append(f"{rel}: up to date")
460+
continue
461+
path.parent.mkdir(parents=True, exist_ok=True)
462+
existed = path.exists()
463+
path.write_text(contents)
464+
notes.append(f"{rel}: {'updated' if existed else 'created'}")
465+
except OSError as exc:
466+
notes.append(f"{rel}: write failed ({exc})")
467+
return notes

0 commit comments

Comments
 (0)