feat: multi-platform adapter architecture (Claude Code, Gemini CLI, OpenCode) (#32)

* Fix istall/update scripts

* test: capture pre-refactor install snapshot for regression

Adds take-snapshot.sh script and the resulting snapshot/ directory,
capturing the exact vault state produced by launchme.sh before the
framework-agnosticity refactor begins.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Summary: Refactor agents/skills/hooks/mcp in agentic-platform-agnostic templates.

refactor: rename source CLAUDE.md → DISPATCHER.md (framework-neutral)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

refactor: convert agent frontmatter from tools: to neutral capabilities:

Replace Claude Code-specific `tools:` frontmatter with framework-agnostic
`mode: subagent` and `capabilities: [...]` in all 8 agent files.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

refactor: add neutral hook trigger manifests (.hook.yaml)

refactor: hooks read neutral JSON schema (args.* instead of tool_input.*)

refactor: convert .mcp.json to neutral mcp/servers.yaml

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Implement agentic-platform adapters skeleton.

build: add adapters/lib.sh skeleton with vocabulary constants

test: bash test runner for adapter helpers

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(adapters): parse_frontmatter helper with tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(adapters): parse_capabilities helper with tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(adapters): should_include helper with tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(adapters): parse_hook_yaml helper with tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(adapters): agent_body helper with tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(adapters): enumerate_agents and enumerate_hooks helpers

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Implement agentic-platform adapter for Claude Code.

build(adapters): claude-code adapter skeleton with capability/event tables

build(claude-code): adapter_translate_dispatcher with test

build(claude-code): adapter_translate_references with test

build(claude-code): adapter_translate_skills with tests

build(claude-code): adapter_translate_agents with capability→tools mapping

build(claude-code): hook wrapper template (CC native → neutral schema)

build(claude-code): adapter_translate_hooks with wrapper generation

build(claude-code): adapter_translate_mcp with hand-rolled YAML parser

build(claude-code): adapter_finalize and complete adapter_build wiring

build: scripts/build.sh dispatches to per-framework adapter

Also fix adapter_translate_hooks and adapter_translate_agents to use
while-read loops (avoiding word-splitting on paths with spaces) and
guard grep calls with || true to survive set -eo pipefail when hooks
have no match-tool field. Remove scripts/build.sh from .gitignore.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Refactor install/update scripts to support agentic-platform agnosticity.

refactor(lib.sh): generalize install_claude_md → install_dispatcher

New signature takes the full destination path instead of just the vault
dir, allowing callers to install CLAUDE.md, AGENTS.md, or any dispatcher
file to an explicit location.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

feat(launchme): support --framework flag, build dist/ before install

Add --framework and --target arg parsing. Run build.sh before installing
to populate dist/<framework>/. All install_* calls now read from
dist/<framework>/ instead of the raw source dirs. MCP is now handled
automatically by the adapter (no interactive prompt). Replaced
install_claude_md with install_dispatcher.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

feat(updateme): support --framework flag, build dist/ before update

Add --framework and --target arg parsing. Run build.sh before installing
to populate dist/<framework>/. All install_* calls now read from
dist/<framework>/ instead of raw source dirs. Replaced install_claude_md
with install_dispatcher.

Also fix set -e compatibility in lib.sh: add || true to all conditional
[[ ... ]] && info "..." logging lines so they don't abort the script
when VERBOSE_COPY=0.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: regression runner diffs dist/claude-code against pre-refactor snapshot

- Add tests/regression/run.sh that builds dist/claude-code and compares
  against snapshot, excluding runtime-only artifacts (.mbifc-manifest,
  .mcp.json, .claude-plugin/plugin.json)
- Fix adapters/lib.sh agent_body: preserve '---' section dividers in body
  (awk now only skips '---' while still inside frontmatter, fm < 2)
- Fix adapters/claude-code/adapter.sh: change 'read' capability to expand
  to only 'Read', appending 'Glob, Grep' at end of tools list to match
  snapshot ordering
- Update snapshot to reflect intentional refactor changes: hook JSON schema
  (.args.* instead of .tool_input.*), wrapper scripts, settings.json with
  wrapper paths, and consistent tool ordering for postman/sorter

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Implement opencode adapter.

Co-Authored-By: win0na <winnie@winneon.moe>

feat(lib.sh): add install_plugins helper for opencode JS plugins

build(adapters): opencode adapter skeleton with capability/event tables

build(opencode): adapter_translate_dispatcher (DISPATCHER.md → AGENTS.md)

build(opencode): adapter_translate_references and adapter_translate_skills

Implements Task 4 and Task 5:
- adapter_translate_references: Copies reference markdown files to .opencode/references/
- adapter_translate_skills: Copies skill SKILL.md files to .opencode/skills/<name>/ with exclude filtering

Both functions respect framework filtering via should_include().

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(opencode): adapter_translate_agents with capability→permission mapping

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(opencode): bash-executor template for spawning hook scripts

build(opencode): plugin-stub template for mbifc-hooks.js

build(opencode): adapter_translate_hooks with JS plugin generation

Implements _oc_hook_registry_json and adapter_translate_hooks in the
opencode adapter. Copies hook scripts to .opencode/hooks/, generates a
single .opencode/plugins/mbifc-hooks.js by inlining bash-executor.js and
synthesising a hook registry from *.hook.yaml files. Uses python3 for
template substitution to safely handle multi-line JS content. Adds 3
unit tests (copies scripts, registry entries, noop when no hooks dir).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(opencode): adapter_translate_mcp with local/remote handling

build(opencode): adapter_finalize and complete adapter_build wiring

Add adapter_finalize placeholder and wire adapter_translate_mcp into
adapter_build; add end-to-end integration test (14/14 pass).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

feat(launchme): branch on --framework for opencode install layout

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

feat(updateme): branch on --framework for opencode install layout

Mirror the same case "$FRAMEWORK" block from launchme.sh: framework-specific
DIST_COMPONENTS_DIR, VAULT_COMPONENTS_DIR, DISPATCHER_SRC/DST, MCP_SRC/DST,
HAS_PLUGINS; conditional install_plugins; conditional install_settings;
framework-aware vault-setup check; framework-neutral summary messages.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix adapters to follow the same template.

fix: restore adapter_build() contract, revert function renames

Both adapters now export adapter_build() and adapter_translate_*() as
the uniform public contract. scripts/build.sh sources one adapter and
calls adapter_build uniformly. Private helpers (_oc_*) and vocabulary
tables (cc_capability_to_tools, oc_capability_to_permission, etc.)
retain their prefixes. CC regression and OC unit tests all pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

fix(tests): restore test_oc_ prefix on adapter_build end-to-end test

* Fix agent format in opencode adapter

* refactor: rename --framework to --platform across all scripts and tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Modify generic name for model tiers

Co-Authored-By: win0na <winnie@winneon.moe>

refactor: neutral model vocabulary (low/mid/high) in source agents

feat(claude-code): cc_model_to_native() maps low/mid/high to haiku/sonnet/opus

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

feat(opencode): update oc_model_to_provider() for low/mid/high vocabulary

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add gemini-cli adapter

Co-Authored-By: win0na <winnie@winneon.moe>

build(gemini-cli): adapter skeleton with capability/event/model tables

build(gemini-cli): adapter_translate_dispatcher (DISPATCHER.md → GEMINI.md)

build(gemini-cli): adapter_translate_references and adapter_translate_skills

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(gemini-cli): adapter_translate_agents with capability→tools mapping

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(gemini-cli): adapter_translate_hooks with wrapper scripts

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

feat(install): add gemini-cli platform to launchme.sh and updateme.sh

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Implement preserving config merge for opencode.

Co-Authored-By: win0na <winnie@winneon.moe>

feat(opencode): config-merge.sh with formatting-preserving JSON merge

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(opencode): source config-merge.sh from adapter

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

feat(install): use oc_config_merge for opencode.json instead of overwrite

Source config-merge.sh from install scripts for opencode platform so
user keys in opencode.json are preserved on reinstall and update.
Fix in-place merge by writing to a temp file before moving to output.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add mcp files to gitignore.

* Fix claude-specific references in agents, skills and references

* Fix: remove claude-specific reference from hooks.

build: add platform_dir and dispatcher_name to all hook wrapper/plugin templates

feat(hooks): platform-aware path checks using platform_dir and dispatcher_name from JSON input

test: update regression snapshot for platform-aware hook wrappers and scripts

* Added interactive platform choice in launchme, and platform auto-detection in updateme.

* Fix: remove claude-specific references from documentation

* Update documentation to reflect the new platform-agnostic architecture

* fix: address Copilot review feedback on PR #32

- tests/run.sh: check source return code, report failures
- tests/regression/run.sh: use mktemp + trap cleanup instead of fixed /tmp paths
- tests/regression/run.sh: include .mcp.json in regression comparison
- tests/regression/take-snapshot.sh: use --platform flag instead of stale scripted input
- adapters/opencode/templates/plugin-stub.js.tmpl: include stdout in hook block error message

* fix: address Copilot review round 2

- config-merge.sh: reword comment to only promise indentation preservation (not full formatting)
- take-snapshot.sh: copy required artifacts explicitly, optional ones with existence check
- adapters/lib.sh: document parse_hook_yaml single-trigger limitation

* fix: address Copilot review round 3

- adapters/opencode/adapter.sh: replace python3 template substitution with
  pure bash (while-read loop with case matching), removing python3 dependency
- adapters/lib.sh: should_include now falls back to plain YAML key read for
  files without frontmatter delimiters (fixes hook .yaml exclude: support)

* fix: address Copilot review round 4

- scripts/launchme.sh: fix double-dot in FW_DIR_NAME display (basename
  already includes the dot, e.g. ".claude")
- scripts/launchme.sh: replace undefined MCP_ANSWER with check on MCP_DST
  existence for summary banner

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Giacomo Nunziati
2026-04-10 23:28:28 +02:00
committed by GitHub
parent e8452f0801
commit 53b605379e
99 changed files with 13868 additions and 692 deletions

353
adapters/opencode/adapter.sh Executable file
View File

@@ -0,0 +1,353 @@
#!/usr/bin/env bash
# =============================================================================
# adapters/opencode/adapter.sh — Opencode framework adapter
# =============================================================================
# Sourced by scripts/build.sh AFTER adapters/lib.sh.
# Translates source files into a dist/opencode/ tree that mirrors what
# opencode expects in the user's vault.
# =============================================================================
# shellcheck source=adapters/opencode/config-merge.sh
source "$(dirname "${BASH_SOURCE[0]}")/config-merge.sh"
OC_PLATFORM="opencode"
OC_FW_DIR="opencode"
OC_DISPATCHER="AGENTS.md"
# Capability → opencode permission key. Returns the permission key to set to
# "allow" for each capability, or empty string for capabilities that have no
# opencode equivalent (they are dropped).
#
# Reference (spec §"Capability vocabulary"):
# read → implicit, no permission needed
# write → edit: allow
# edit → edit: allow
# bash → bash: allow
# webfetch → webfetch: allow
# websearch → drop (no equivalent)
# notebook → drop
# task → drop (subagent invocation, not a permission)
# todo → drop
oc_capability_to_permission() {
local cap="$1"
case "$cap" in
read) echo "" ;; # implicit
write) echo "edit" ;;
edit) echo "edit" ;;
bash) echo "bash" ;;
webfetch) echo "webfetch" ;;
websearch) echo "" ;; # drop
notebook) echo "" ;; # drop
task) echo "" ;; # drop
todo) echo "" ;; # drop
*) echo "" ;;
esac
}
# Event vocabulary → opencode native event name.
oc_event_to_native() {
local event="$1"
case "$event" in
before-tool-use) echo "tool.execute.before" ;;
after-tool-use) echo "tool.execute.after" ;;
on-notification) echo "session.idle" ;;
on-session-start) echo "session.created" ;;
on-prompt-submit) echo "tui.prompt.append" ;;
*) echo "" ;;
esac
}
# Neutral model tier → opencode provider/model id. Conservative mapping:
# if the source model is already provider-prefixed (contains "/"), pass through
# unchanged. Otherwise look up in the table and fall back to the raw value.
oc_model_to_provider() {
local model="$1"
case "$model" in
*/*) echo "$model" ;; # already qualified
low) echo "anthropic/claude-haiku-4-5" ;;
mid) echo "anthropic/claude-sonnet-4-5" ;;
high) echo "anthropic/claude-opus-4-5" ;;
*) echo "$model" ;; # unknown — passthrough
esac
}
# adapter_translate_dispatcher <source_dispatcher_md> <dest_dir>
# Copies the source DISPATCHER.md to dest_dir/AGENTS.md (opencode's vault-root
# dispatcher filename). Rewrites .platform/ and DISPATCHER.md to opencode paths.
adapter_translate_dispatcher() {
local src="$1" dst="$2"
[[ -f "$src" ]] || return 0
mkdir -p "$dst"
cp "$src" "$dst/AGENTS.md"
rewrite_platform_paths "$dst/AGENTS.md" "$OC_FW_DIR" "$OC_DISPATCHER"
}
# adapter_translate_references <source_refs_dir> <dest_root>
# Copies *.md into dest_root/.opencode/references/, rewriting framework paths.
adapter_translate_references() {
local src="$1" dst="$2"
[[ -d "$src" ]] || return 0
local out="$dst/.opencode/references"
mkdir -p "$out"
for f in "$src"/*.md; do
[[ -f "$f" ]] || continue
should_include "$f" "$OC_PLATFORM" || continue
cp "$f" "$out/"
rewrite_platform_paths "$out/$(basename "$f")" "$OC_FW_DIR" "$OC_DISPATCHER"
done
}
# adapter_translate_skills <source_skills_dir> <dest_root>
# Copies each skill directory's SKILL.md into dest_root/.opencode/skills/<name>/,
# rewriting framework paths in the body.
adapter_translate_skills() {
local src="$1" dst="$2"
[[ -d "$src" ]] || return 0
for skill_dir in "$src"/*/; do
[[ -f "${skill_dir}SKILL.md" ]] || continue
should_include "${skill_dir}SKILL.md" "$OC_PLATFORM" || continue
local name; name="$(basename "$skill_dir")"
local out="$dst/.opencode/skills/$name"
mkdir -p "$out"
cp "${skill_dir}SKILL.md" "$out/SKILL.md"
rewrite_platform_paths "$out/SKILL.md" "$OC_FW_DIR" "$OC_DISPATCHER"
done
}
# adapter_translate_agents <source_agents_dir> <dest_root>
# For each *.md in source_agents_dir, translate the capabilities frontmatter
# into an opencode permission block, map the model, and write to
# dest_root/.opencode/agents/<name>.md.
adapter_translate_agents() {
local src="$1" dst="$2"
[[ -d "$src" ]] || return 0
local out_dir="$dst/.opencode/agents"
mkdir -p "$out_dir"
while IFS= read -r agent; do
[[ -f "$agent" ]] || continue
should_include "$agent" "$OC_PLATFORM" || continue
local model_raw; model_raw="$(parse_frontmatter "$agent" model)"
local mode_raw; mode_raw="$(parse_frontmatter "$agent" mode)"
local caps; caps="$(parse_capabilities "$agent")"
local model_out; model_out="$(oc_model_to_provider "$model_raw")"
local mode_out="${mode_raw:-subagent}"
# Build a unique permission list
local perms=""
for cap in $caps; do
local p; p="$(oc_capability_to_permission "$cap")"
[[ -z "$p" ]] && continue
# Dedupe: skip if already in $perms (space-delimited)
case " $perms " in
*" $p "*) ;;
*) perms="$perms $p" ;;
esac
done
perms="${perms# }"
local out_file="$out_dir/$(basename "$agent")"
{
echo "---"
# Copy description block verbatim (may be folded YAML with continuation lines)
awk '/^---$/{n++; next} n==1 && /^description:/{print; in_desc=1; next} n==1 && in_desc && /^[[:space:]]/{print; next} n==1 && in_desc && !/^[[:space:]]/{in_desc=0} n>=2{exit}' "$agent"
echo "mode: $mode_out"
echo "model: $model_out"
if [[ -z "$perms" ]]; then
echo "permission: {}"
else
echo "permission:"
for p in $perms; do
echo " $p: allow"
done
fi
echo "---"
echo ""
agent_body "$agent"
} > "$out_file"
rewrite_platform_paths "$out_file" "$OC_FW_DIR" "$OC_DISPATCHER"
done < <(enumerate_agents "$src")
}
# _oc_hook_registry_json <source_hooks_dir>
# Emits a JSON array literal representing the hook registry, suitable for
# substituting into the plugin template. Each entry: {name, script, triggers: [{event, matchTool}]}.
# Script paths are stored as "../hooks/<basename>" so the plugin (at .opencode/plugins/)
# can reach .opencode/hooks/ at runtime via __dirname + path join.
_oc_hook_registry_json() {
local src="$1"
local entries='[]'
while IFS= read -r yaml; do
[[ -f "$yaml" ]] || continue
should_include "$yaml" "$OC_PLATFORM" || continue
local meta; meta="$(parse_hook_yaml "$yaml")"
local name; name="$(echo "$meta" | grep '^name=' | head -1 | cut -d= -f2-)"
local script; script="$(echo "$meta" | grep '^script=' | head -1 | cut -d= -f2-)"
local event; event="$(echo "$meta" | grep '^event=' | head -1 | cut -d= -f2-)"
local match_tool; match_tool="$(echo "$meta" | grep '^match-tool=' | head -1 | cut -d= -f2- || true)"
local oc_event; oc_event="$(oc_event_to_native "$event")"
# Build the matchTool JSON array (empty array if no filter)
local match_json='[]'
if [[ -n "$match_tool" ]]; then
match_json="$(echo "$match_tool" | jq -R 'split(" ") | map(select(length > 0))')"
fi
# Use ../hooks/<script> so the plugin at .opencode/plugins/ can resolve
# its sibling .opencode/hooks/ directory at runtime.
local script_rel="../hooks/$script"
entries="$(echo "$entries" | jq \
--arg name "$name" \
--arg script "$script_rel" \
--arg event "$oc_event" \
--argjson match "$match_json" \
'. += [{name: $name, script: $script, triggers: [{event: $event, matchTool: $match}]}]')"
done < <(enumerate_hooks "$src")
echo "$entries"
}
# adapter_translate_hooks <source_hooks_dir> <dest_root>
# Copies each hook's .sh script to dst/.opencode/hooks/ and generates a single
# dst/.opencode/plugins/mbifc-hooks.js plugin containing the vendored bash
# executor plus a hook registry synthesised from the source .hook.yaml files.
adapter_translate_hooks() {
local src="$1" dst="$2"
[[ -d "$src" ]] || return 0
local hooks_out="$dst/.opencode/hooks"
local plugins_out="$dst/.opencode/plugins"
mkdir -p "$hooks_out" "$plugins_out"
# Copy every referenced .sh script
local have_any=0
while IFS= read -r yaml; do
[[ -f "$yaml" ]] || continue
should_include "$yaml" "$OC_PLATFORM" || continue
local meta; meta="$(parse_hook_yaml "$yaml")"
local script; script="$(echo "$meta" | grep '^script=' | head -1 | cut -d= -f2-)"
[[ -f "$src/$script" ]] || continue
cp "$src/$script" "$hooks_out/$script"
chmod +x "$hooks_out/$script"
rewrite_platform_paths "$hooks_out/$script" "$OC_FW_DIR" "$OC_DISPATCHER"
have_any=1
done < <(enumerate_hooks "$src")
# If there were no hooks, skip plugin generation and clean up the empty dirs
if [[ $have_any -eq 0 ]]; then
rmdir "$hooks_out" "$plugins_out" 2>/dev/null || true
return 0
fi
# Load templates
local tpl_dir; tpl_dir="$(dirname "${BASH_SOURCE[0]}")/templates"
# Build the registry JSON
local registry; registry="$(_oc_hook_registry_json "$src")"
# Pretty-print registry (2-space indent)
local registry_pretty; registry_pretty="$(echo "$registry" | jq '.')"
# Substitute placeholders by reading the template line-by-line.
# We avoid sed/awk gsub because the replacement strings (JS code, JSON)
# contain backslashes and ampersands that break regex replacement.
local out="$plugins_out/mbifc-hooks.js"
local executor_file="$tpl_dir/bash-executor.js"
local stub_file="$tpl_dir/plugin-stub.js.tmpl"
while IFS= read -r line; do
case "$line" in
*__BASH_EXECUTOR__*)
cat "$executor_file"
;;
*__HOOK_REGISTRY__*)
# Replace the placeholder within the line (preserves "const HOOKS = " prefix)
local prefix="${line%%__HOOK_REGISTRY__*}"
local suffix="${line##*__HOOK_REGISTRY__}"
printf '%s' "$prefix"
printf '%s' "$registry_pretty"
printf '%s\n' "$suffix"
;;
*)
printf '%s\n' "$line"
;;
esac
done < "$stub_file" > "$out"
}
# adapter_translate_mcp <source_mcp_dir> <dest_root>
# Reads mcp/servers.yaml and writes dst/opencode.json with a top-level "mcp" key.
# Local servers → {type: "local", command: "<joined>", environment: {}}
# HTTP servers → {type: "remote", url: "..."}
adapter_translate_mcp() {
local src="$1" dst="$2"
local yaml="$src/servers.yaml"
[[ -f "$yaml" ]] || return 0
mkdir -p "$dst"
local out="$dst/opencode.json"
local json='{}'
local current_name="" current_cmd="" current_url="" current_type=""
_oc_flush_current() {
[[ -z "$current_name" ]] && return 0
if [[ "$current_type" == "local" || -n "$current_cmd" ]]; then
local cmd_str="${current_cmd// / }"
json="$(echo "$json" | jq --arg n "$current_name" --arg c "$cmd_str" \
'.[$n] = {type: "local", command: $c, environment: {}}')"
else
json="$(echo "$json" | jq --arg n "$current_name" --arg u "$current_url" \
'.[$n] = {type: "remote", url: $u}')"
fi
}
while IFS= read -r line; do
case "$line" in
*"- name:"*)
_oc_flush_current
current_name="$(echo "$line" | sed 's/.*- name:[[:space:]]*//' | tr -d '"')"
current_cmd=""
current_url=""
current_type=""
;;
*"type:"*)
current_type="$(echo "$line" | sed 's/.*type:[[:space:]]*//' | tr -d '"')"
# Opencode uses "remote" for HTTP; normalise the source "http" → "remote"
[[ "$current_type" == "http" ]] && current_type="remote"
;;
*"command:"*"["*)
current_cmd="$(echo "$line" | sed 's/.*command:[[:space:]]*\[//' | sed 's/\][[:space:]]*$//' | tr -d '"' | sed 's/,[[:space:]]*/ /g')"
;;
*"url:"*)
current_url="$(echo "$line" | sed 's/.*url:[[:space:]]*//' | tr -d '"')"
;;
esac
done < "$yaml"
_oc_flush_current
echo "$json" | jq '{mcp: .}' > "$out"
}
# adapter_finalize <source_root> <dest_root>
# Opencode has no per-framework manifest file; placeholder for future additions.
adapter_finalize() {
local src="$1" dst="$2"
return 0
}
# adapter_build <source_dir> <dest_dir>
# The single entry point invoked by scripts/build.sh.
adapter_build() {
local src="$1" dst="$2"
rm -rf "$dst"
mkdir -p "$dst"
adapter_translate_dispatcher "$src/DISPATCHER.md" "$dst"
adapter_translate_references "$src/references" "$dst"
adapter_translate_skills "$src/skills" "$dst"
adapter_translate_agents "$src/agents" "$dst"
adapter_translate_hooks "$src/hooks" "$dst"
adapter_translate_mcp "$src/mcp" "$dst"
adapter_finalize "$src" "$dst"
}

View File

@@ -0,0 +1,76 @@
#!/usr/bin/env bash
# =============================================================================
# adapters/opencode/config-merge.sh — JSON config merge for opencode.json
# =============================================================================
# Merges a built opencode.json with an existing one in the vault, preserving
# user keys and indentation style (2-space, 4-space, or tab). Only the "mcp"
# key is managed; everything else belongs to the user. Note: jq normalizes
# whitespace and may reorder keys within objects.
#
# Sourced by the opencode adapter. Requires jq.
# =============================================================================
# Provide a fallback warn() if scripts/lib.sh has not been sourced yet.
if ! declare -f warn >/dev/null 2>&1; then
warn() { echo " ! $*" >&2; }
fi
# oc_detect_indent <file>
# Detects the indentation unit used in a JSON file.
# Returns the number of spaces (2 or 4). Defaults to 2.
oc_detect_indent() {
local file="$1"
local indent_str; indent_str="$(awk '/^[[:space:]]+[^[:space:]]/ { match($0, /^[[:space:]]+/); print substr($0, 1, RLENGTH); exit }' "$file")"
if [[ -z "$indent_str" ]]; then
echo "2"
return
fi
case "$indent_str" in
$'\t'*) echo "tab" ;;
" "*) echo "4" ;;
*) echo "2" ;;
esac
}
# oc_config_merge <built_file> <existing_file> <output_file>
# Merges built opencode.json into an existing one:
# - If existing doesn't exist → copy built as-is
# - If existing is malformed → overwrite with built (with warning)
# - Otherwise → merge: our mcp entries overwrite same-name, user keys preserved
oc_config_merge() {
local built="$1" existing="$2" output="$3"
# Fresh install — no existing file
if [[ ! -f "$existing" ]]; then
cp "$built" "$output"
return 0
fi
# Validate existing file is JSON
if ! jq empty "$existing" 2>/dev/null; then
warn "Existing opencode.json is malformed — overwriting with built version"
cp "$built" "$output"
return 0
fi
# Detect indentation from existing file
local indent; indent="$(oc_detect_indent "$existing")"
local jq_indent
case "$indent" in
tab) jq_indent="--tab" ;;
4) jq_indent="--indent 4" ;;
*) jq_indent="--indent 2" ;;
esac
# Read our managed MCP entries
local our_mcp; our_mcp="$(jq '.mcp // {}' "$built")"
# Merge: start with existing, overlay our mcp entries.
# Always write to a temp file first to support in-place merges (output == existing).
local tmp; tmp="$(mktemp)"
# shellcheck disable=SC2086
jq $jq_indent --argjson our_mcp "$our_mcp" '
.mcp = ((.mcp // {}) + $our_mcp)
' "$existing" > "$tmp"
mv "$tmp" "$output"
}

View File

@@ -0,0 +1,43 @@
// =============================================================================
// bash-executor.js — Spawn a bash script and pipe neutral JSON context to stdin
// =============================================================================
// This file is vendored verbatim into the generated mbifc-hooks.js plugin at
// build time. It must not require any npm modules beyond Node.js builtins so
// that opencode's embedded runtime can execute it without installation.
// =============================================================================
const { spawn } = require("node:child_process");
/**
* Run a bash script with a JSON payload on stdin.
*
* @param {string} scriptPath Absolute path to the .sh file.
* @param {object} payload Neutral-schema object to pipe in as JSON.
* @param {object} [env] Extra environment variables (merged with process.env).
* @returns {Promise<{exitCode:number, stdout:string, stderr:string}>}
*/
function runBashHook(scriptPath, payload, env = {}) {
return new Promise((resolve, reject) => {
const child = spawn("bash", [scriptPath], {
env: { ...process.env, ...env },
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
child.stdout.on("data", (d) => { stdout += d.toString(); });
child.stderr.on("data", (d) => { stderr += d.toString(); });
child.on("error", reject);
child.on("close", (exitCode) => {
resolve({ exitCode: exitCode ?? 0, stdout, stderr });
});
try {
child.stdin.write(JSON.stringify(payload));
child.stdin.end();
} catch (err) {
reject(err);
}
});
}
module.exports = { runBashHook };

View File

@@ -0,0 +1,91 @@
// =============================================================================
// Generated by adapters/opencode/adapter.sh — do not edit.
// mbifc-hooks.js — opencode plugin that dispatches events to bash hook scripts
// =============================================================================
// This file is generated at build time. It contains a vendored bash executor
// (from adapters/opencode/templates/bash-executor.js) and a hook registry
// synthesised from the source hooks/*.hook.yaml files.
// =============================================================================
// ── bash-executor.js (vendored) ─────────────────────────────────────────────
__BASH_EXECUTOR__
// ── Hook registry (generated) ───────────────────────────────────────────────
const HOOKS = __HOOK_REGISTRY__;
// ── Helpers ─────────────────────────────────────────────────────────────────
/**
* Build the neutral JSON payload from an opencode event context.
* The opencode event shapes vary per event; we extract the common fields and
* leave everything else under `args`.
*/
function buildPayload(eventName, input) {
const tool = (input && (input.tool || input.toolName)) || "";
const args =
(input && (input.args || input.toolInput || input.input)) ||
(input && input.title !== undefined ? { title: input.title, message: input.message } : {}) ||
{};
const neutralEvent = (() => {
switch (eventName) {
case "tool.execute.before": return "before-tool-use";
case "tool.execute.after": return "after-tool-use";
case "session.idle": return "on-notification";
case "session.created": return "on-session-start";
case "tui.prompt.append": return "on-prompt-submit";
default: return eventName;
}
})();
return {
event: neutralEvent,
tool,
args,
session_id: (input && input.sessionId) || "",
cwd: (input && input.cwd) || process.cwd(),
framework: "opencode",
platform_dir: ".opencode",
dispatcher_name: "AGENTS.md",
};
}
/**
* Check whether a hook's match-tool filter (if any) matches the current tool.
*/
function matchesTool(hook, tool) {
const m = hook.matchTool;
if (!m || m.length === 0) return true;
return m.includes((tool || "").toLowerCase());
}
// ── Plugin entry point ──────────────────────────────────────────────────────
module.exports = async function mbifcHooksPlugin({ app, client }) {
// Group hooks by opencode event name
const byEvent = {};
for (const h of HOOKS) {
for (const trig of h.triggers) {
(byEvent[trig.event] ||= []).push({ ...h, matchTool: trig.matchTool });
}
}
// Register one handler per opencode event; dispatch to matching hooks.
const handlers = {};
for (const [event, hooks] of Object.entries(byEvent)) {
handlers[event] = async (input, output) => {
const payload = buildPayload(event, { ...input, ...output });
for (const h of hooks) {
if (!matchesTool(h, payload.tool)) continue;
const path = require("node:path");
const scriptAbs = path.isAbsolute(h.script)
? h.script
: path.join(__dirname, h.script);
const { exitCode, stdout, stderr } = await runBashHook(scriptAbs, payload);
if (exitCode === 2) {
// Documented opencode block mechanism for tool.execute.before
const reason = stdout.trim() || stderr.trim() || "exit 2";
throw new Error(`[${h.name}] blocked: ${reason}`);
}
}
};
}
return handlers;
};