Skip to content

Commit 979949a

Browse files
author
PeterPirog
committed
fix(v1.8.1-P2+P3): OpenCode plugins use documented API; installer selects plugin per client
P2: V2 plugin rewritten off the undocumented ctx.tool.hook/ctx.event best-effort surface to the documented hooks-object API (return { 'tool.execute.after', event, 'experimental.session.compacting }) verified against opencode.ai/docs/plugins (2026-08-26). - Empty catch{} blocks removed: hook/subprocess failures are now logged to stderr (OpenCode log) instead of being silently swallowed. - Known beta gap documented: anomalyco/opencode#44788 (beta 18050) 'event.subscribe delivers no events' — noted in plugin header + docs. - V1 plugin also hardened: same stderr logging, no empty catches. P3: install.py now installs EXACTLY ONE resilience plugin matched to the client (V1 and V2 register identical hook names; co-install would double-fire): - --client opencode -> internal-rag-resilience.ts (V2 removed) - --client opencode2 -> internal-rag-resilience-v2.ts (V1 removed) - default (no --client) -> V1 plugin - self-install (repo into itself) must not delete the repo's own plugins - LOCAL_EXCLUDES + uninstall MANAGED_PATHS cover both plugin files. Tests: +7 (TestOpenCodePluginV1V2Select): documented API present in both plugins, no silent empty catch in V2, V1-install removes V2 and vice versa, default installs V1, self-install guard. 351 tests pass (5 skipped).
1 parent 7845a04 commit 979949a

6 files changed

Lines changed: 264 additions & 104 deletions

File tree

Lines changed: 70 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,54 @@
11
// OpenCode 2 (beta) plugin: MCP Light Memory resilience hooks.
22
//
3-
// WARNING: OpenCode 2 is still in beta. Its plugin API may change without
4-
// notice. This file is a best-effort compatibility layer using the
5-
// documented V2 plugin patterns. If the V2 plugin API breaks, MCP Light
6-
// Memory will still work via MCP tools (context/search/remember/guard) —
7-
// the plugin only adds auto-checkpoint/compact convenience hooks.
3+
// Uses the documented hooks-object plugin API (verified against
4+
// https://opencode.ai/docs/plugins/ 2026-08-26):
5+
// export const Plugin = async (ctx) => { return { "tool.execute.after", event, "experimental.session.compacting" } }
86
//
9-
// Key differences from V1:
10-
// - V2 uses ctx.tool.hook("execute.after", ...) instead of "tool.execute.after"
11-
// - V2 uses ctx.event(...) instead of event({...})
12-
// - V2 session compaction hook name may differ
7+
// Known beta limitations (documented, NOT silently swallowed):
8+
// - GitHub issue #44788 (beta 18050): "event.subscribe delivers no events;
9+
// context-hook and synthetic injections never reach the model prompt".
10+
// If you are on that beta build, the event/compacting hooks below may
11+
// not fire. MCP Light Memory core (MCP tools) is unaffected.
12+
// - All hook failures are logged to stderr (visible in OpenCode logs);
13+
// nothing is silently discarded.
1314
//
14-
// Installation for OpenCode 2:
15-
// Place in .opencode/plugins/ (auto-loaded by V2 as well).
16-
// The V1 plugin (internal-rag-resilience.ts) can coexist — V2 will ignore
17-
// V1-style return shapes and V1 will ignore V2-style hooks.
18-
//
19-
// Limitations:
20-
// - If V2 does not support the exact hook names used here, the hooks will
21-
// be silently ignored. MCP Light Memory core functionality (MCP tools)
22-
// is unaffected.
23-
// - No auto-compaction in V2 if the session.compacting hook is unavailable.
15+
// Installation:
16+
// install.py --client opencode2 copies ONLY this file (not the V1 plugin),
17+
// or place manually in .opencode/plugins/.
18+
import type { Plugin } from "@opencode-ai/plugin"
19+
import { readFile } from "node:fs/promises"
20+
import { join } from "node:path"
2421

2522
const py = process.platform === "win32" ? "python" : "python3"
2623

27-
export default async (ctx: any) => {
28-
// ctx is the V2 plugin context. We use optional chaining extensively
29-
// because the V2 API is still beta and may not expose all methods.
30-
31-
const worktree = ctx?.worktree || ctx?.cwd || process.cwd()
32-
const script = [worktree, ".agents", "skills", "internal-rag", "mlm.py"].join("/")
24+
export const McpLightMemoryResilienceV2: Plugin = async ({ worktree }) => {
25+
const script = join(worktree, ".agents", "skills", "internal-rag", "mlm.py")
3326

27+
// Debounce: at least 60s between auto-checkpoints, count skipped
3428
let lastAutoCheckpoint = 0
3529
let skippedCount = 0
3630

31+
const log = (msg: string) => {
32+
console.error(`[internal-rag-resilience-v2] ${msg}`)
33+
}
34+
3735
const cp = async (reason: string, phase?: string) => {
36+
const args = [py, script, "checkpoint", "--reason", reason]
37+
if (phase) args.push("--phase", phase)
3838
try {
39-
const c = [py, script, "checkpoint", "--reason", reason]
40-
if (phase) c.push("--phase", phase)
41-
const p = Bun.spawn(c, { cwd: worktree, stdout: "ignore", stderr: "ignore" })
42-
await p.exited
43-
} catch {}
39+
const p = Bun.spawn(args, { cwd: worktree, stdout: "ignore", stderr: "pipe" })
40+
const err = await p.stderr?.text().catch(() => "")
41+
const code = await p.exited
42+
if (code !== 0) log(`checkpoint failed (exit ${code}): ${err.trim().slice(0, 200)}`)
43+
} catch (e: any) {
44+
log(`checkpoint spawn failed: ${e?.message ?? e}`)
45+
}
4446
}
4547

4648
const debouncedCp = async (reason: string, phase?: string) => {
4749
const now = Date.now()
48-
if (now - lastAutoCheckpoint < 60_000) {
50+
const minInterval = 60_000
51+
if (now - lastAutoCheckpoint < minInterval) {
4952
skippedCount++
5053
return
5154
}
@@ -59,49 +62,52 @@ export default async (ctx: any) => {
5962

6063
const compact = async () => {
6164
try {
62-
const p = Bun.spawn([py, script, "compact"], { cwd: worktree, stdout: "ignore", stderr: "ignore" })
63-
await p.exited
64-
} catch {}
65+
const p = Bun.spawn([py, script, "compact"], { cwd: worktree, stdout: "ignore", stderr: "pipe" })
66+
const err = await p.stderr?.text().catch(() => "")
67+
const code = await p.exited
68+
if (code !== 0) log(`compact failed (exit ${code}): ${err.trim().slice(0, 200)}`)
69+
} catch (e: any) {
70+
log(`compact spawn failed: ${e?.message ?? e}`)
71+
}
6572
}
6673

67-
// V2 hook registration (best-effort)
68-
if (ctx?.tool?.hook) {
69-
try {
70-
ctx.tool.hook("execute.after", async (input: any, _output: any) => {
74+
return {
75+
"tool.execute.after": async (input: any) => {
76+
try {
7177
if (["edit", "write", "apply_patch"].includes(input?.tool)) {
7278
await debouncedCp(`opencode2-auto-after-${input.tool}`)
7379
}
74-
})
75-
} catch {}
76-
}
77-
78-
if (ctx?.event) {
79-
try {
80-
ctx.event(async (event: any) => {
80+
} catch (e: any) {
81+
log(`tool.execute.after hook failed: ${e?.message ?? e}`)
82+
}
83+
},
84+
event: async ({ event }: any) => {
85+
try {
8186
if (event?.type === "session.error") {
82-
await cp("opencode2-session-error")
87+
await cp("opencode2-session-error", "Session error; inspect prior output and Git state before continuing.")
8388
} else if (event?.type === "session.idle") {
8489
await cp("opencode2-session-idle")
8590
}
86-
})
87-
} catch {}
88-
}
89-
90-
// V2 compaction hook (best-effort — name may differ in V2)
91-
if (ctx?.session?.compacting) {
92-
try {
93-
ctx.session.compacting(async (_input: any, output: any) => {
91+
} catch (e: any) {
92+
log(`event hook failed: ${e?.message ?? e}`)
93+
}
94+
},
95+
"experimental.session.compacting": async (_input: any, output: any) => {
96+
try {
9497
await compact()
95-
await cp("opencode2-before-compaction")
96-
if (output?.context) {
97-
try {
98-
const state = await Bun.file([worktree, "INTERNAL_RAG", "WORKING_STATE.md"].join("/")).text()
99-
output.context.push(`\n## Persistent project memory\n${state}\n`)
100-
} catch {}
98+
await cp("opencode2-before-compaction", "Context compaction; resume from persistent state.")
99+
let state = "(unavailable)"
100+
try {
101+
state = await readFile(join(worktree, "INTERNAL_RAG", "WORKING_STATE.md"), "utf8")
102+
} catch (e: any) {
103+
log(`WORKING_STATE.md unavailable: ${e?.message ?? e}`)
101104
}
102-
})
103-
} catch {}
105+
output?.context?.push(`\n## Persistent project memory\n${state}\nContinue using checkpoint/guard discipline.\n`)
106+
} catch (e: any) {
107+
log(`session.compacting hook failed: ${e?.message ?? e}`)
108+
}
109+
},
104110
}
111+
}
105112

106-
return {}
107-
}
113+
export default McpLightMemoryResilienceV2
Lines changed: 61 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
// OpenCode 1 (stable) plugin: MCP Light Memory resilience hooks.
22
//
3-
// This plugin is compatible with OpenCode 1's plugin API:
4-
// - Plugin<{ worktree }> async function
5-
// - tool.execute.after / event / experimental.session.compacting hooks
3+
// Uses the documented hooks-object plugin API (verified against
4+
// https://opencode.ai/docs/plugins/ 2026-08-26):
5+
// export const Plugin = async (ctx) => { return { "tool.execute.after", event, "experimental.session.compacting" } }
66
//
7-
// For OpenCode 2 (beta), see internal-rag-resilience-v2.ts which uses the
8-
// V2 plugin API (ctx.tool.hook etc.). OpenCode 2 is still beta and its
9-
// plugin API may change; the V2 plugin is a best-effort compatibility layer.
7+
// For OpenCode 2 (beta), install.py copies internal-rag-resilience-v2.ts
8+
// instead — do NOT install both (identical hook names would double-fire).
109
//
1110
// Installation:
12-
// - OpenCode 1: place in .opencode/plugins/ (auto-loaded)
13-
// - OpenCode 2: use internal-rag-resilience-v2.ts instead
11+
// - OpenCode 1: install.py --client opencode (or place in .opencode/plugins/)
12+
// - OpenCode 2: install.py --client opencode2
1413
import type { Plugin } from "@opencode-ai/plugin"
1514
import { readFile } from "node:fs/promises"
1615
import { join } from "node:path"
@@ -24,18 +23,26 @@ export const McpLightMemoryResilience: Plugin = async ({ worktree }) => {
2423
let lastAutoCheckpoint = 0
2524
let skippedCount = 0
2625

26+
const log = (msg: string) => {
27+
console.error(`[internal-rag-resilience] ${msg}`)
28+
}
29+
2730
const cp = async (reason: string, phase?: string) => {
31+
const args = [py, script, "checkpoint", "--reason", reason]
32+
if (phase) args.push("--phase", phase)
2833
try {
29-
const c = [py, script, "checkpoint", "--reason", reason]
30-
if (phase) c.push("--phase", phase)
31-
const p = Bun.spawn(c, { cwd: worktree, stdout: "ignore", stderr: "ignore" })
32-
await p.exited
33-
} catch {}
34+
const p = Bun.spawn(args, { cwd: worktree, stdout: "ignore", stderr: "pipe" })
35+
const err = await p.stderr?.text().catch(() => "")
36+
const code = await p.exited
37+
if (code !== 0) log(`checkpoint failed (exit ${code}): ${err.trim().slice(0, 200)}`)
38+
} catch (e: any) {
39+
log(`checkpoint spawn failed: ${e?.message ?? e}`)
40+
}
3441
}
3542

3643
const debouncedCp = async (reason: string, phase?: string) => {
3744
const now = Date.now()
38-
const minInterval = 60_000 // 60 seconds
45+
const minInterval = 60_000
3946
if (now - lastAutoCheckpoint < minInterval) {
4047
skippedCount++
4148
return
@@ -50,32 +57,52 @@ export const McpLightMemoryResilience: Plugin = async ({ worktree }) => {
5057

5158
const compact = async () => {
5259
try {
53-
const p = Bun.spawn([py, script, "compact"], { cwd: worktree, stdout: "ignore", stderr: "ignore" })
54-
await p.exited
55-
} catch {}
60+
const p = Bun.spawn([py, script, "compact"], { cwd: worktree, stdout: "ignore", stderr: "pipe" })
61+
const err = await p.stderr?.text().catch(() => "")
62+
const code = await p.exited
63+
if (code !== 0) log(`compact failed (exit ${code}): ${err.trim().slice(0, 200)}`)
64+
} catch (e: any) {
65+
log(`compact spawn failed: ${e?.message ?? e}`)
66+
}
5667
}
5768

5869
return {
59-
"tool.execute.after": async (input, _output) => {
60-
if (["edit", "write", "apply_patch"].includes(input.tool)) {
61-
await debouncedCp(`opencode-auto-after-${input.tool}`)
70+
"tool.execute.after": async (input: any) => {
71+
try {
72+
if (["edit", "write", "apply_patch"].includes(input?.tool)) {
73+
await debouncedCp(`opencode-auto-after-${input.tool}`)
74+
}
75+
} catch (e: any) {
76+
log(`tool.execute.after hook failed: ${e?.message ?? e}`)
6277
}
6378
},
64-
event: async ({ event }) => {
65-
if (event.type === "session.error") {
66-
await cp("opencode-session-error", "Session error; inspect prior output and Git state before continuing.")
67-
} else if (event.type === "session.idle") {
68-
await cp("opencode-session-idle")
79+
event: async ({ event }: any) => {
80+
try {
81+
if (event?.type === "session.error") {
82+
await cp("opencode-session-error", "Session error; inspect prior output and Git state before continuing.")
83+
} else if (event?.type === "session.idle") {
84+
await cp("opencode-session-idle")
85+
}
86+
} catch (e: any) {
87+
log(`event hook failed: ${e?.message ?? e}`)
6988
}
7089
},
71-
"experimental.session.compacting": async (_input, output) => {
72-
await compact()
73-
await cp("opencode-before-compaction", "Context compaction; resume from persistent state.")
74-
let state = "(unavailable)"
90+
"experimental.session.compacting": async (_input: any, output: any) => {
7591
try {
76-
state = await readFile(join(worktree, "INTERNAL_RAG", "WORKING_STATE.md"), "utf8")
77-
} catch {}
78-
output.context.push(`\n## Persistent project memory\n${state}\nContinue using checkpoint/guard discipline.\n`)
79-
}
92+
await compact()
93+
await cp("opencode-before-compaction", "Context compaction; resume from persistent state.")
94+
let state = "(unavailable)"
95+
try {
96+
state = await readFile(join(worktree, "INTERNAL_RAG", "WORKING_STATE.md"), "utf8")
97+
} catch (e: any) {
98+
log(`WORKING_STATE.md unavailable: ${e?.message ?? e}`)
99+
}
100+
output?.context?.push(`\n## Persistent project memory\n${state}\nContinue using checkpoint/guard discipline.\n`)
101+
} catch (e: any) {
102+
log(`session.compacting hook failed: ${e?.message ?? e}`)
103+
}
104+
},
80105
}
81-
}
106+
}
107+
108+
export default McpLightMemoryResilience

‎docs/OPENCODE.md‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,24 @@ All tools support `--json` where relevant.
2626

2727
## Plugin (resilience)
2828

29-
`internal-rag-resilience.ts`:
30-
- `tool.execute.after` — auto-checkpoint after `edit`/`write`/`apply_patch`.
29+
The installer copies exactly ONE plugin, matched to the client (installing
30+
both would double-fire identical hooks):
31+
32+
- `--client opencode` → `internal-rag-resilience.ts` (V1)
33+
- `--client opencode2` → `internal-rag-resilience-v2.ts` (V2 beta)
34+
35+
Both use the documented hooks-object API (`return { "tool.execute.after", event, "experimental.session.compacting" }`):
36+
- `tool.execute.after` — auto-checkpoint after `edit`/`write`/`apply_patch` (debounced 60s).
3137
- `session.error` — checkpoint + suggest inspection.
3238
- `session.idle` — checkpoint.
3339
- `experimental.session.compacting` — `compact` + checkpoint + inject WORKING_STATE into context.
3440

41+
Hook failures are logged to stderr (visible in OpenCode logs); nothing is
42+
silently swallowed.
43+
44+
Known OpenCode 2 beta limitation: GitHub issue anomalyco/opencode#44788
45+
(beta 18050) reports that `event` delivery does not work — on affected
46+
builds the `session.error`/`session.idle`/compacting hooks may not fire.
47+
MCP tools are unaffected.
48+
3549
If a native tool fails, the agent can always call `irag.py` via the terminal.

‎install.py‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,6 @@
107107
Path('.opencode/tools/memory-guard.ts'),
108108
Path('.opencode/tools/memory-remember.ts'),
109109
Path('.opencode/tools/memory-status.ts'),
110-
Path('.opencode/plugins/internal-rag-resilience.ts'),
111110
Path('.opencode/commands/memory.md'),
112111
Path('.opencode/commands/memory-check.md'),
113112
Path('.opencode/commands/checkpoint.md'),
@@ -125,6 +124,7 @@
125124
'/.opencode/tools/memory-remember.ts',
126125
'/.opencode/tools/memory-status.ts',
127126
'/.opencode/plugins/internal-rag-resilience.ts',
127+
'/.opencode/plugins/internal-rag-resilience-v2.ts',
128128
'/.opencode/plugins/internal-rag-compaction.ts',
129129
'/.opencode/commands/memory.md',
130130
'/.opencode/commands/memory-check.md',
@@ -216,7 +216,7 @@ def backup_existing(target: Path, backup_root: Path, rel: Path):
216216
shutil.copy2(src, dst)
217217

218218

219-
def copy_update_files(target: Path, backup_root: Path):
219+
def copy_update_files(target: Path, backup_root: Path, client: str | None = None):
220220
for rel in UPDATE_PATHS:
221221
src = (HERE / rel).resolve()
222222
if not src.exists():
@@ -233,6 +233,28 @@ def copy_update_files(target: Path, backup_root: Path):
233233
shutil.copytree(src, dst, dirs_exist_ok=True)
234234
else:
235235
shutil.copy2(src, dst)
236+
# OpenCode plugin: install the version matching the requested client.
237+
# V1 and V2 register identical hook names, so co-installing both would
238+
# double-fire hooks. Default (no client) installs the V1 plugin.
239+
v1_plugin = Path('.opencode/plugins/internal-rag-resilience.ts')
240+
v2_plugin = Path('.opencode/plugins/internal-rag-resilience-v2.ts')
241+
for rel, want in ((v1_plugin, client != 'opencode2'),
242+
(v2_plugin, client == 'opencode2')):
243+
if want:
244+
src = (HERE / rel).resolve()
245+
if not src.exists():
246+
continue
247+
backup_existing(target, backup_root, rel)
248+
dst = (target / rel).resolve()
249+
dst.parent.mkdir(parents=True, exist_ok=True)
250+
if src != dst:
251+
shutil.copy2(src, dst)
252+
else:
253+
dst = target / rel
254+
if dst.exists() and (HERE / rel).resolve() != dst.resolve():
255+
backup_existing(target, backup_root, rel)
256+
dst.unlink()
257+
print(f'Removed non-matching plugin: {rel}')
236258
for rel in REMOVE_LEGACY_PATHS:
237259
dst = target / rel
238260
if dst.exists():
@@ -756,7 +778,7 @@ def main():
756778
print(f'MCP Light Memory v{VERSION} -> {target}')
757779
print(f'Install mode: {mode}')
758780
print(f'Backup: {backup_root}')
759-
copy_update_files(target, backup_root)
781+
copy_update_files(target, backup_root, client=args.client)
760782
memory_existed_before = (target / 'INTERNAL_RAG').exists()
761783
install_memory_skeleton(target)
762784
agent_info = merge_agents(target, backup_root)

0 commit comments

Comments
 (0)