Skip to content

Commit 98a66b7

Browse files
fix(cli): emit OpenCode plugin hooks for the V2 setup context
- keep the `server(ctx)` entry that OpenCode 1.18.x dispatches hooks from - fill `setup(ctx)` with the V2 hook registrations (execute.after, compaction) and fail open per domain, so one unavailable registration neither breaks the host nor disables the other - prefer `content` over `output` in appendResult and return the result unchanged when no text surface exists, so a tool's own output is never hidden - persist the post-compaction note as a keyed session instruction (`codebase-memory-session-note`) that survives compaction instead of editing the system prompt; hosts without that channel skip reinjection - resolve each session's directory with ctx.session.get (cached), because ctx.location is the plugin instance's location, not the session's - update the DeusData#2089 emission test in place to state the 2.x contract Fixes DeusData#2204 Refs DeusData#2077 DeusData#2089 Signed-off-by: HazielMagallanes <contactame.haziel@gmail.com>
1 parent 812d075 commit 98a66b7

3 files changed

Lines changed: 253 additions & 71 deletions

File tree

‎src/cli/client_adapter.c‎

Lines changed: 195 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -427,9 +427,15 @@ 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+
"// reinjection after compaction through the session context channel.\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+
"// same behaviour on the context's tool and session hook domains. Each\n"
437+
"// registration fails open, and the matching server() hook yields once\n"
438+
"// its domain has registered.\n");
433439
sb_append(&sb, "import { spawn } from 'node:child_process';\n\n");
434440
sb_append(&sb, "const BIN = '");
435441
sb_append(&sb, bin);
@@ -481,64 +487,193 @@ char *cbm_client_adapter_opencode(const char *binary_path) {
481487
" });\n"
482488
"}\n\n");
483489

490+
/* OpenCode 2 tool results are structured (Tool.Result: content is the
491+
* string/parts surface the model reads, output is the tool's schema-typed
492+
* value). Append to content first, then a string output; if neither text
493+
* surface exists, leave the result untouched so the tool's own output is
494+
* never hidden. The caller assigns the returned result onto event.result. */
495+
sb_append(&sb,
496+
"function appendResult(result, extra) {\n"
497+
" if (!result || typeof result !== 'object') return result;\n"
498+
" if (typeof result.content === 'string') {\n"
499+
" return { ...result, content: result.content + '\\n' + extra };\n"
500+
" }\n"
501+
" if (Array.isArray(result.content)) {\n"
502+
" const content = result.content.slice();\n"
503+
" for (let i = content.length - 1; i >= 0; i--) {\n"
504+
" if (content[i] && content[i].type === 'text') {\n"
505+
" content[i] = { ...content[i], text: content[i].text + '\\n' + extra };\n"
506+
" return { ...result, content };\n"
507+
" }\n"
508+
" }\n"
509+
" content.push({ type: 'text', text: extra });\n"
510+
" return { ...result, content };\n"
511+
" }\n"
512+
" if (typeof result.output === 'string') {\n"
513+
" return { ...result, output: result.output + '\\n' + extra };\n"
514+
" }\n"
515+
" return result;\n"
516+
"}\n\n");
517+
518+
/* Per-domain registration flags: a host that dispatches both server() and
519+
* setup() with domains must not append the note twice. The server() hook
520+
* for a domain yields once setup() registered that same domain. */
521+
sb_append(&sb, "let toolHooksRegistered = false;\n"
522+
"let sessionHooksRegistered = false;\n\n");
523+
484524
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");
525+
&sb,
526+
"export default {\n"
527+
" id: 'codebase-memory-augment',\n"
528+
" // OpenCode 1.18.x server runtime: reads default.server and dispatches\n"
529+
" // the hooks it returns.\n"
530+
" server: async (ctx) => {\n"
531+
" const dir = ctx?.directory;\n"
532+
" const seen = new Set();\n"
533+
" const lifecycle = () =>\n"
534+
" augment({ hook_event_name: 'SessionStart', cwd: dir });\n"
535+
" return {\n"
536+
" 'tool.execute.after': async (input, output) => {\n"
537+
" if (toolHooksRegistered) return;\n"
538+
" if (typeof output?.output !== 'string') return;\n"
539+
" const pieces = [];\n"
540+
" const sid = input?.sessionID;\n"
541+
" if (typeof sid === 'string' && !seen.has(sid)) {\n"
542+
" seen.add(sid);\n"
543+
" pieces.push(await lifecycle());\n"
544+
" }\n"
545+
" const args = input?.args ?? {};\n"
546+
" const search =\n"
547+
" input?.tool === 'grep' ? 'Grep' : input?.tool === 'glob' ? 'Glob' : null;\n"
548+
" if (search) {\n"
549+
" pieces.push(await augment({\n"
550+
" hook_event_name: 'PreToolUse',\n"
551+
" tool_name: search,\n"
552+
" tool_input: args,\n"
553+
" cwd: dir,\n"
554+
" }));\n"
555+
" } else if (input?.tool === 'read') {\n"
556+
" const filePath = args.filePath ?? args.file_path ?? args.path;\n"
557+
" if (typeof filePath === 'string' && filePath) {\n"
558+
" pieces.push(await augment({\n"
559+
" hook_event_name: 'PostToolUse',\n"
560+
" tool_name: 'Read',\n"
561+
" tool_input: { file_path: filePath },\n"
562+
" cwd: dir,\n"
563+
" }));\n"
564+
" }\n"
565+
" }\n"
566+
" const extra = pieces.filter(Boolean).join('\\n');\n"
567+
" if (extra) {\n"
568+
" output.output += '\\n' + extra;\n"
569+
" }\n"
570+
" },\n"
571+
" // Documented (experimental) compaction surface: output.context is the\n"
572+
" // mutable array of context strings for the rebuilt session.\n"
573+
" 'experimental.session.compacting': async (_input, output) => {\n"
574+
" if (sessionHooksRegistered) return;\n"
575+
" const note = await lifecycle();\n"
576+
" if (note && Array.isArray(output?.context)) {\n"
577+
" output.context.push(note);\n"
578+
" }\n"
579+
" },\n"
580+
" };\n"
581+
" },\n"
582+
" // OpenCode 2 runtime: default.server is ignored and setup(ctx) registers\n"
583+
" // the hooks on the context domains. Each registration fails open, so one\n"
584+
" // missing domain cannot break the host or the other domain.\n"
585+
" async setup(ctx) {\n"
586+
" const seen = new Set();\n"
587+
" const dirs = new Map();\n"
588+
" const dirFor = async (sessionID) => {\n"
589+
" if (typeof sessionID !== 'string' || sessionID === '') return undefined;\n"
590+
" if (dirs.has(sessionID)) return dirs.get(sessionID);\n"
591+
" try {\n"
592+
" const session = await ctx.session.get({ sessionID });\n"
593+
" const dir = session?.location?.directory;\n"
594+
" if (typeof dir === 'string' && dir !== '') {\n"
595+
" dirs.set(sessionID, dir);\n"
596+
" return dir;\n"
597+
" }\n"
598+
" } catch {}\n"
599+
" return undefined;\n"
600+
" };\n"
601+
" const lifecycle = (dir) =>\n"
602+
" augment({ hook_event_name: 'SessionStart', cwd: dir });\n"
603+
" if (ctx?.tool?.hook) {\n"
604+
" try {\n"
605+
" await ctx.tool.hook('execute.after', async (event) => {\n"
606+
" if (event?.status !== 'completed') return;\n"
607+
" const dir = await dirFor(event?.sessionID);\n"
608+
" if (!dir) return;\n"
609+
" const pieces = [];\n"
610+
" if (typeof event?.sessionID === 'string' && !seen.has(event.sessionID)) {\n"
611+
" seen.add(event.sessionID);\n"
612+
" pieces.push(await lifecycle(dir));\n"
613+
" }\n"
614+
" const args = event?.input ?? {};\n"
615+
" const search =\n"
616+
" event?.tool === 'grep' ? 'Grep' : event?.tool === 'glob' ? 'Glob' : null;\n"
617+
" if (search) {\n"
618+
" pieces.push(await augment({\n"
619+
" hook_event_name: 'PreToolUse',\n"
620+
" tool_name: search,\n"
621+
" tool_input: args,\n"
622+
" cwd: dir,\n"
623+
" }));\n"
624+
" } else if (event?.tool === 'read') {\n"
625+
" const filePath = args.filePath ?? args.file_path ?? args.path;\n"
626+
" if (typeof filePath === 'string' && filePath) {\n"
627+
" pieces.push(await augment({\n"
628+
" hook_event_name: 'PostToolUse',\n"
629+
" tool_name: 'Read',\n"
630+
" tool_input: { file_path: filePath },\n"
631+
" cwd: dir,\n"
632+
" }));\n"
633+
" }\n"
634+
" }\n"
635+
" const extra = pieces.filter(Boolean).join('\\n');\n"
636+
" if (extra) {\n"
637+
" event.result = appendResult(event.result, extra);\n"
638+
" }\n"
639+
" });\n"
640+
" toolHooksRegistered = true;\n"
641+
" } catch {\n"
642+
" // Fail open: the server() tool hook stays active.\n"
643+
" }\n"
644+
" }\n"
645+
" // OpenCode 2 compaction: persist the note as a keyed session\n"
646+
" // instruction (a <context> entry) instead of editing the system\n"
647+
" // prompt; entries survive compaction. Hosts without the channel\n"
648+
" // skip reinjection rather than failing the plugin.\n"
649+
" if (ctx?.session?.hook) {\n"
650+
" try {\n"
651+
" await ctx.session.hook('compaction', async (event) => {\n"
652+
" const sessionID = event?.sessionID;\n"
653+
" if (typeof sessionID !== 'string' || sessionID === '') return;\n"
654+
" const entry = ctx?.session?.instructions?.entry;\n"
655+
" if (typeof entry?.put !== 'function') return;\n"
656+
" const dir = await dirFor(sessionID);\n"
657+
" if (!dir) return;\n"
658+
" const note = await lifecycle(dir);\n"
659+
" if (!note) return;\n"
660+
" try {\n"
661+
" await entry.put({\n"
662+
" sessionID,\n"
663+
" key: 'codebase-memory-session-note',\n"
664+
" value: note,\n"
665+
" });\n"
666+
" } catch {\n"
667+
" // Fail open: reinjection is best-effort.\n"
668+
" }\n"
669+
" });\n"
670+
" sessionHooksRegistered = true;\n"
671+
" } catch {\n"
672+
" // Fail open: the server() compaction hook stays active.\n"
673+
" }\n"
674+
" }\n"
675+
" },\n"
676+
"};\n");
542677

543678
if (sb.failed) {
544679
free(sb.buf);

‎src/cli/client_adapter.h‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,17 @@ 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` and `compaction` on the context domains. Each registration
60+
* fails open, and the post-compaction note is stored as a keyed session
61+
* instruction (`<context>` entry) instead of the system prompt.
5662
*
5763
* Returns NULL on allocation failure or when binary_path is NULL/empty. */
5864
char *cbm_client_adapter_opencode(const char *binary_path);

‎tests/test_agent_clients.c‎

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1342,18 +1342,59 @@ TEST(client_adapter_opencode_covers_lifecycle_read_and_compaction) {
13421342
PASS();
13431343
}
13441344

1345-
/* #2077: OpenCode's V2 loader only reads the default export and needs an
1346-
* id plus a setup()/effect() function; the old named export had neither. */
1345+
/* #2077/#2089/#2204: the two OpenCode runtimes read different entries of the
1346+
* default export. 1.18.x dispatches the hooks returned by `server(ctx)`; 2.x
1347+
* ignores `server` and calls `setup(ctx)`, whose context provides the tool and
1348+
* session hook domains. Registrations fail open per domain, so the matching
1349+
* server() hook yields once its domain is registered. The post-compaction note
1350+
* goes through a keyed session instruction (a <context> entry that survives
1351+
* compaction), never the system prompt. */
13471352
TEST(client_adapter_opencode_exports_the_v2_default_definition_issue2077) {
13481353
char *js = cbm_client_adapter_opencode("/usr/local/bin/codebase-memory-mcp");
13491354
ASSERT_NOT_NULL(js);
13501355
ASSERT_NOT_NULL(strstr(js, "export default {"));
13511356
ASSERT_NOT_NULL(strstr(js, "id: 'codebase-memory-augment'"));
1352-
/* Hooks live under server(), which the server runtime reads; setup()
1353-
* stays empty since the V2 config loader has no tool domain yet. */
1354-
ASSERT_NOT_NULL(strstr(js, "setup() {}"));
1357+
/* OpenCode 1.18.x server runtime. */
13551358
ASSERT_NOT_NULL(strstr(js, "server: async (ctx) => {"));
1356-
ASSERT_NULL(strstr(js, "async setup(ctx) {"));
1359+
/* OpenCode 2 registers through the setup context; the domains exist on
1360+
* 2.x, so setup is no longer the empty placeholder #2089 pinned. */
1361+
ASSERT_NOT_NULL(strstr(js, "async setup(ctx) {"));
1362+
ASSERT_NOT_NULL(strstr(js, "ctx.tool.hook('execute.after'"));
1363+
ASSERT_NOT_NULL(strstr(js, "ctx.session.hook('compaction'"));
1364+
ASSERT_NULL(strstr(js, "ctx.session.hook('context'"));
1365+
/* content is the surface the model reads; prefer it over output, and never
1366+
* synthesize content that would hide the tool's own result. */
1367+
const char *content_first = strstr(js, "if (typeof result.content === 'string') {");
1368+
const char *output_fallback = strstr(js, "if (typeof result.output === 'string') {");
1369+
ASSERT_NOT_NULL(content_first);
1370+
ASSERT_NOT_NULL(output_fallback);
1371+
ASSERT_TRUE(content_first < output_fallback);
1372+
ASSERT_NULL(strstr(js, "if (result.content === undefined)"));
1373+
/* Compaction uses the durable session context channel, not the system
1374+
* prompt; older hosts without it skip reinjection. */
1375+
ASSERT_NOT_NULL(strstr(js, "event?.sessionID"));
1376+
ASSERT_NOT_NULL(strstr(js, "ctx?.session?.instructions?.entry"));
1377+
/* The plugin instance's location is not the session's location in a
1378+
* multi-project server: resolve each session's directory. */
1379+
ASSERT_NOT_NULL(strstr(js, "const dir = await dirFor("));
1380+
ASSERT_NOT_NULL(strstr(js, "ctx.session.get({ sessionID })"));
1381+
ASSERT_NOT_NULL(strstr(js, "dirs.has(sessionID)"));
1382+
ASSERT_NOT_NULL(strstr(js, "if (!dir) return;"));
1383+
/* No fallback to the plugin instance's location: that is not the session's
1384+
* location in a multi-project server. */
1385+
ASSERT_NULL(strstr(js, "ctx?.location?.directory"));
1386+
ASSERT_NOT_NULL(strstr(js, "key: 'codebase-memory-session-note'"));
1387+
ASSERT_NULL(strstr(js, "event.system.push"));
1388+
ASSERT_NULL(strstr(js, "pendingReinject"));
1389+
/* Registrations fail open per domain; the server() hooks yield per domain. */
1390+
ASSERT_NOT_NULL(strstr(js, "toolHooksRegistered = true;"));
1391+
ASSERT_NOT_NULL(strstr(js, "sessionHooksRegistered = true;"));
1392+
ASSERT_NOT_NULL(strstr(js, "if (toolHooksRegistered) return;"));
1393+
ASSERT_NOT_NULL(strstr(js, "if (sessionHooksRegistered) return;"));
1394+
ASSERT_NOT_NULL(strstr(js, "catch {"));
1395+
ASSERT_NOT_NULL(strstr(js, "event.result = appendResult(event.result, extra);"));
1396+
/* The empty setup placeholder and the old named export must both be gone. */
1397+
ASSERT_NULL(strstr(js, "setup() {}"));
13571398
ASSERT_NULL(strstr(js, "export const CodebaseMemory"));
13581399
free(js);
13591400
PASS();

0 commit comments

Comments
 (0)