@@ -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 );
0 commit comments