Skip to content

Commit 587f134

Browse files
authored
Merge pull request #2385 from HazielMagallanes/fix/opencode-v2-setup-hooks
fix(cli): register OpenCode 2 hooks via the setup context
2 parents 6926a65 + fb88365 commit 587f134

4 files changed

Lines changed: 267 additions & 72 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -722,7 +722,7 @@ overwrite user-modified agents.
722722
| Codex CLI | Detected | `$CODEX_HOME/config.toml` | Managed `AGENTS.md` activation pointer, `~/.agents/skills/codebase-memory/SKILL.md`, three read-only agents; `SessionStart` + `SubagentStart`, `PreToolUse` graph lookup for `Bash` searches |
723723
| Gemini CLI | Detected | `.gemini/settings.json` | `GEMINI.md`, three explicit read/graph-tool subagents; `BeforeTool`, `AfterTool` `read_file` coverage, and `SessionStart` |
724724
| Zed | Detected | platform `settings.json` (JSONC) | `AGENTS.md` + shared skill |
725-
| OpenCode | Detected | `$OPENCODE_CONFIG` or resolved global config | `AGENTS.md`, skill, three deny-by-default read-only agents; plugin adds grep/glob graph lookup, post-`read` coverage, first-tool-result session context, and post-compaction reinjection |
725+
| OpenCode | Detected | `$OPENCODE_CONFIG` or resolved global config | `AGENTS.md`, skill, three deny-by-default read-only agents; plugin adds grep/glob graph lookup, post-`read` coverage, first-tool-result session context, and post-compaction reinjection on OpenCode 1.18.x |
726726
| Antigravity | Detected | `.gemini/config/mcp_config.json` | `.gemini/GEMINI.md` |
727727
| Aider | Detected | none | `CONVENTIONS.md` via `.aider.conf.yml` |
728728
| KiloCode | Detected | `.config/kilo/kilo.jsonc` | Rule + three graph-tool subagents with deny-by-default permissions |

‎src/cli/client_adapter.c‎

Lines changed: 168 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -427,9 +427,16 @@ char *cbm_client_adapter_opencode(const char *binary_path) {
427427
sb_append(&sb, "// OpenCode already reaches every tool over MCP; this module adds the\n"
428428
"// context surfaces other clients get through hook configuration: graph\n"
429429
"// lookup after grep/glob, index-coverage notes after read, session-start\n"
430-
"// tier routing (carried on the first tool result of each session, since\n"
431-
"// OpenCode documents no context-output lifecycle hook), and reinjection\n"
432-
"// after compaction via the documented experimental surface.\n");
430+
"// tier routing (carried on the first tool result of each session), and\n"
431+
"// on OpenCode 1.18.x reinjection after compaction.\n"
432+
"//\n"
433+
"// Two runtimes load this module:\n"
434+
"// - OpenCode 1.18.x dispatches the hooks returned by server(ctx).\n"
435+
"// - OpenCode 2 ignores server and calls setup(ctx), which registers the\n"
436+
"// tool hook on the context's tool domain. The registration fails open,\n"
437+
"// and the server() tool hook yields once it has registered. OpenCode 2\n"
438+
"// gets no note after compaction: no compaction channel has been run on\n"
439+
"// a real 2.x host yet.\n");
433440
sb_append(&sb, "import { spawn } from 'node:child_process';\n\n");
434441
sb_append(&sb, "const BIN = '");
435442
sb_append(&sb, bin);
@@ -481,64 +488,165 @@ char *cbm_client_adapter_opencode(const char *binary_path) {
481488
" });\n"
482489
"}\n\n");
483490

491+
/* OpenCode 2 tool results are structured (Tool.Result: content is the
492+
* string/parts surface the model reads, output is the tool's schema-typed
493+
* value). Append to content first, then a string output; if neither text
494+
* surface exists, leave the result untouched so the tool's own output is
495+
* never hidden. A parts array gets a new text part only when it already
496+
* holds a part: `content: []` is a valid result, and a part added there
497+
* would be the note alone, so an empty array falls through to the string
498+
* output (or the unchanged result). The caller assigns the returned result
499+
* onto event.result. */
500+
sb_append(&sb,
501+
"function appendResult(result, extra) {\n"
502+
" if (!result || typeof result !== 'object') return result;\n"
503+
" if (typeof result.content === 'string') {\n"
504+
" return { ...result, content: result.content + '\\n' + extra };\n"
505+
" }\n"
506+
" if (Array.isArray(result.content) && result.content.length > 0) {\n"
507+
" const content = result.content.slice();\n"
508+
" for (let i = content.length - 1; i >= 0; i--) {\n"
509+
" if (content[i] && content[i].type === 'text') {\n"
510+
" content[i] = { ...content[i], text: content[i].text + '\\n' + extra };\n"
511+
" return { ...result, content };\n"
512+
" }\n"
513+
" }\n"
514+
" content.push({ type: 'text', text: extra });\n"
515+
" return { ...result, content };\n"
516+
" }\n"
517+
" if (typeof result.output === 'string') {\n"
518+
" return { ...result, output: result.output + '\\n' + extra };\n"
519+
" }\n"
520+
" return result;\n"
521+
"}\n\n");
522+
523+
/* A host that dispatches both server() and setup() with a tool domain must
524+
* not append the note twice: the server() tool hook yields once setup()
525+
* registered the tool domain. */
526+
sb_append(&sb, "let toolHooksRegistered = false;\n\n");
527+
484528
sb_append(
485-
&sb, "export default {\n"
486-
" id: 'codebase-memory-augment',\n"
487-
" // V2 config loader: requires id + setup|effect; no tool domain yet\n"
488-
" // at this point, so there is nothing to register here.\n"
489-
" setup() {},\n"
490-
" // Server runtime: reads default.server and dispatches the hooks it returns.\n"
491-
" server: async (ctx) => {\n"
492-
" const dir = ctx?.directory;\n"
493-
" const seen = new Set();\n"
494-
" const lifecycle = () =>\n"
495-
" augment({ hook_event_name: 'SessionStart', cwd: dir });\n"
496-
" return {\n"
497-
" 'tool.execute.after': async (input, output) => {\n"
498-
" if (typeof output?.output !== 'string') return;\n"
499-
" const pieces = [];\n"
500-
" const sid = input?.sessionID;\n"
501-
" if (typeof sid === 'string' && !seen.has(sid)) {\n"
502-
" seen.add(sid);\n"
503-
" pieces.push(await lifecycle());\n"
504-
" }\n"
505-
" const args = input?.args ?? {};\n"
506-
" const search =\n"
507-
" input?.tool === 'grep' ? 'Grep' : input?.tool === 'glob' ? 'Glob' : null;\n"
508-
" if (search) {\n"
509-
" pieces.push(await augment({\n"
510-
" hook_event_name: 'PreToolUse',\n"
511-
" tool_name: search,\n"
512-
" tool_input: args,\n"
513-
" cwd: dir,\n"
514-
" }));\n"
515-
" } else if (input?.tool === 'read') {\n"
516-
" const filePath = args.filePath ?? args.file_path ?? args.path;\n"
517-
" if (typeof filePath === 'string' && filePath) {\n"
518-
" pieces.push(await augment({\n"
519-
" hook_event_name: 'PostToolUse',\n"
520-
" tool_name: 'Read',\n"
521-
" tool_input: { file_path: filePath },\n"
522-
" cwd: dir,\n"
523-
" }));\n"
524-
" }\n"
525-
" }\n"
526-
" const extra = pieces.filter(Boolean).join('\\n');\n"
527-
" if (extra) {\n"
528-
" output.output += '\\n' + extra;\n"
529-
" }\n"
530-
" },\n"
531-
" // Documented (experimental) compaction surface: output.context is the\n"
532-
" // mutable array of context strings for the rebuilt session.\n"
533-
" 'experimental.session.compacting': async (_input, output) => {\n"
534-
" const note = await lifecycle();\n"
535-
" if (note && Array.isArray(output?.context)) {\n"
536-
" output.context.push(note);\n"
537-
" }\n"
538-
" },\n"
539-
" };\n"
540-
" },\n"
541-
"};\n");
529+
&sb,
530+
"export default {\n"
531+
" id: 'codebase-memory-augment',\n"
532+
" // OpenCode 1.18.x server runtime: reads default.server and dispatches\n"
533+
" // the hooks it returns.\n"
534+
" server: async (ctx) => {\n"
535+
" const dir = ctx?.directory;\n"
536+
" const seen = new Set();\n"
537+
" const lifecycle = () =>\n"
538+
" augment({ hook_event_name: 'SessionStart', cwd: dir });\n"
539+
" return {\n"
540+
" 'tool.execute.after': async (input, output) => {\n"
541+
" if (toolHooksRegistered) return;\n"
542+
" if (typeof output?.output !== 'string') return;\n"
543+
" const pieces = [];\n"
544+
" const sid = input?.sessionID;\n"
545+
" if (typeof sid === 'string' && !seen.has(sid)) {\n"
546+
" seen.add(sid);\n"
547+
" pieces.push(await lifecycle());\n"
548+
" }\n"
549+
" const args = input?.args ?? {};\n"
550+
" const search =\n"
551+
" input?.tool === 'grep' ? 'Grep' : input?.tool === 'glob' ? 'Glob' : null;\n"
552+
" if (search) {\n"
553+
" pieces.push(await augment({\n"
554+
" hook_event_name: 'PreToolUse',\n"
555+
" tool_name: search,\n"
556+
" tool_input: args,\n"
557+
" cwd: dir,\n"
558+
" }));\n"
559+
" } else if (input?.tool === 'read') {\n"
560+
" const filePath = args.filePath ?? args.file_path ?? args.path;\n"
561+
" if (typeof filePath === 'string' && filePath) {\n"
562+
" pieces.push(await augment({\n"
563+
" hook_event_name: 'PostToolUse',\n"
564+
" tool_name: 'Read',\n"
565+
" tool_input: { file_path: filePath },\n"
566+
" cwd: dir,\n"
567+
" }));\n"
568+
" }\n"
569+
" }\n"
570+
" const extra = pieces.filter(Boolean).join('\\n');\n"
571+
" if (extra) {\n"
572+
" output.output += '\\n' + extra;\n"
573+
" }\n"
574+
" },\n"
575+
" // Documented (experimental) compaction surface: output.context is the\n"
576+
" // mutable array of context strings for the rebuilt session.\n"
577+
" 'experimental.session.compacting': async (_input, output) => {\n"
578+
" const note = await lifecycle();\n"
579+
" if (note && Array.isArray(output?.context)) {\n"
580+
" output.context.push(note);\n"
581+
" }\n"
582+
" },\n"
583+
" };\n"
584+
" },\n"
585+
" // OpenCode 2 runtime: default.server is ignored and setup(ctx) registers\n"
586+
" // the tool hook on the context's tool domain. The registration fails\n"
587+
" // open, so a missing domain cannot break the host.\n"
588+
" async setup(ctx) {\n"
589+
" const seen = new Set();\n"
590+
" const dirs = new Map();\n"
591+
" const dirFor = async (sessionID) => {\n"
592+
" if (typeof sessionID !== 'string' || sessionID === '') return undefined;\n"
593+
" if (dirs.has(sessionID)) return dirs.get(sessionID);\n"
594+
" try {\n"
595+
" const session = await ctx.session.get({ sessionID });\n"
596+
" const dir = session?.location?.directory;\n"
597+
" if (typeof dir === 'string' && dir !== '') {\n"
598+
" dirs.set(sessionID, dir);\n"
599+
" return dir;\n"
600+
" }\n"
601+
" } catch {}\n"
602+
" return undefined;\n"
603+
" };\n"
604+
" const lifecycle = (dir) =>\n"
605+
" augment({ hook_event_name: 'SessionStart', cwd: dir });\n"
606+
" if (ctx?.tool?.hook) {\n"
607+
" try {\n"
608+
" await ctx.tool.hook('execute.after', async (event) => {\n"
609+
" if (event?.status !== 'completed') return;\n"
610+
" const dir = await dirFor(event?.sessionID);\n"
611+
" if (!dir) return;\n"
612+
" const pieces = [];\n"
613+
" if (typeof event?.sessionID === 'string' && !seen.has(event.sessionID)) {\n"
614+
" seen.add(event.sessionID);\n"
615+
" pieces.push(await lifecycle(dir));\n"
616+
" }\n"
617+
" const args = event?.input ?? {};\n"
618+
" const search =\n"
619+
" event?.tool === 'grep' ? 'Grep' : event?.tool === 'glob' ? 'Glob' : null;\n"
620+
" if (search) {\n"
621+
" pieces.push(await augment({\n"
622+
" hook_event_name: 'PreToolUse',\n"
623+
" tool_name: search,\n"
624+
" tool_input: args,\n"
625+
" cwd: dir,\n"
626+
" }));\n"
627+
" } else if (event?.tool === 'read') {\n"
628+
" const filePath = args.filePath ?? args.file_path ?? args.path;\n"
629+
" if (typeof filePath === 'string' && filePath) {\n"
630+
" pieces.push(await augment({\n"
631+
" hook_event_name: 'PostToolUse',\n"
632+
" tool_name: 'Read',\n"
633+
" tool_input: { file_path: filePath },\n"
634+
" cwd: dir,\n"
635+
" }));\n"
636+
" }\n"
637+
" }\n"
638+
" const extra = pieces.filter(Boolean).join('\\n');\n"
639+
" if (extra) {\n"
640+
" event.result = appendResult(event.result, extra);\n"
641+
" }\n"
642+
" });\n"
643+
" toolHooksRegistered = true;\n"
644+
" } catch {\n"
645+
" // Fail open: the server() tool hook stays active.\n"
646+
" }\n"
647+
" }\n"
648+
" },\n"
649+
"};\n");
542650

543651
if (sb.failed) {
544652
free(sb.buf);

‎src/cli/client_adapter.h‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,18 @@ char *cbm_client_adapter_pi(const char *binary_path);
4848
* other clients get through their own native hook configuration. OpenCode has
4949
* no such configuration; a plugin module is its only extension point.
5050
*
51-
* NOTE for maintainers: this hooks `tool.execute.after`, whose ability to
52-
* modify a tool's output is NOT part of OpenCode's documented plugin contract
53-
* (only `tool.execute.before`'s argument mutation is). If OpenCode changes it,
54-
* augmentation stops silently — no error, no signal. That risk is accepted
55-
* deliberately and recorded here so it is not rediscovered as a mystery.
51+
* NOTE for maintainers: the module serves two loader generations from one
52+
* default export. OpenCode 1.18.x dispatches the hooks returned by
53+
* `server(ctx)`; its `tool.execute.after` ability to modify a tool's output is
54+
* NOT part of the documented plugin contract (only `tool.execute.before`'s
55+
* argument mutation is), so if that runtime changes, augmentation stops
56+
* silently — no error, no signal. That risk is accepted deliberately for the
57+
* server() path and recorded here so it is not rediscovered as a mystery.
58+
* OpenCode 2 ignores `server` and calls `setup(ctx)`, which registers
59+
* `execute.after` on the context's tool domain and fails open. It registers no
60+
* `compaction` hook: pushing a plain object into `event.messages` would fail,
61+
* if at all, inside OpenCode's own compaction where the plugin cannot catch it,
62+
* so a note after compaction needs a real 2.x run first.
5663
*
5764
* Returns NULL on allocation failure or when binary_path is NULL/empty. */
5865
char *cbm_client_adapter_opencode(const char *binary_path);

0 commit comments

Comments
 (0)