mirror of
https://github.com/gnekt/My-Brain-Is-Full-Crew.git
synced 2026-09-04 14:35:36 +00:00
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>
This commit is contained in:
370
adapters/opencode/adapter.sh
Executable file
370
adapters/opencode/adapter.sh
Executable file
@@ -0,0 +1,370 @@
|
||||
#!/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.
|
||||
# =============================================================================
|
||||
|
||||
FRAMEWORK="opencode"
|
||||
|
||||
# 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
|
||||
}
|
||||
|
||||
# CC-style short model name → 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
|
||||
sonnet) echo "anthropic/claude-sonnet-4-5" ;;
|
||||
opus) echo "anthropic/claude-opus-4-5" ;;
|
||||
haiku) echo "anthropic/claude-haiku-4-5" ;;
|
||||
*) echo "$model" ;; # unknown — pass through
|
||||
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). No content translation.
|
||||
adapter_translate_dispatcher() {
|
||||
local src="$1" dst="$2"
|
||||
[[ -f "$src" ]] || return 0
|
||||
mkdir -p "$dst"
|
||||
cp "$src" "$dst/AGENTS.md"
|
||||
}
|
||||
|
||||
# adapter_translate_references <source_refs_dir> <dest_root>
|
||||
# Verbatim copy of *.md into dest_root/.opencode/references/.
|
||||
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" "$FRAMEWORK" || continue
|
||||
cp "$f" "$out/"
|
||||
done
|
||||
}
|
||||
|
||||
# adapter_translate_skills <source_skills_dir> <dest_root>
|
||||
# Copies each skill directory's SKILL.md into dest_root/.opencode/skills/<name>/.
|
||||
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" "$FRAMEWORK" || continue
|
||||
local name; name="$(basename "$skill_dir")"
|
||||
local out="$dst/.opencode/skills/$name"
|
||||
mkdir -p "$out"
|
||||
cp "${skill_dir}SKILL.md" "$out/SKILL.md"
|
||||
done
|
||||
}
|
||||
|
||||
# _oc_flatten_description <agent_file>
|
||||
# Reads the description field from the source agent, collapsing any YAML
|
||||
# folded continuation lines into a single line with whitespace normalised.
|
||||
# Echoes the bare description text with no leading/trailing quotes.
|
||||
_oc_flatten_description() {
|
||||
local file="$1"
|
||||
awk '
|
||||
/^---$/ { fm++; next }
|
||||
fm == 1 && /^description:/ {
|
||||
sub(/^description:[[:space:]]*/, "")
|
||||
desc = $0
|
||||
in_desc = 1
|
||||
next
|
||||
}
|
||||
fm == 1 && in_desc && /^[[:space:]]/ {
|
||||
sub(/^[[:space:]]+/, "")
|
||||
desc = desc " " $0
|
||||
next
|
||||
}
|
||||
fm == 1 && in_desc { in_desc = 0 }
|
||||
fm >= 2 { exit }
|
||||
END {
|
||||
# Collapse runs of whitespace
|
||||
gsub(/[[:space:]]+/, " ", desc)
|
||||
sub(/^[[:space:]]+/, "", desc)
|
||||
sub(/[[:space:]]+$/, "", desc)
|
||||
print desc
|
||||
}
|
||||
' "$file"
|
||||
}
|
||||
|
||||
# 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" "$FRAMEWORK" || 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 desc; desc="$(_oc_flatten_description "$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 "---"
|
||||
echo "description: \"$desc\""
|
||||
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"
|
||||
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" "$FRAMEWORK" || 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" "$FRAMEWORK" || 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"
|
||||
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 '.')"
|
||||
|
||||
# Use python3 to substitute placeholders — avoids awk/sed issues with
|
||||
# multi-line JS content containing backslashes and ampersands.
|
||||
local out="$plugins_out/mbifc-hooks.js"
|
||||
local executor_file="$tpl_dir/bash-executor.js"
|
||||
local stub_file="$tpl_dir/plugin-stub.js.tmpl"
|
||||
python3 - "$stub_file" "$executor_file" "$out" "$registry_pretty" <<'PYEOF'
|
||||
import sys
|
||||
|
||||
stub_path, executor_path, out_path, registry = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
|
||||
|
||||
with open(stub_path, 'r') as f:
|
||||
content = f.read()
|
||||
with open(executor_path, 'r') as f:
|
||||
executor = f.read()
|
||||
|
||||
content = content.replace('__BASH_EXECUTOR__', executor)
|
||||
content = content.replace('__HOOK_REGISTRY__', registry)
|
||||
|
||||
with open(out_path, 'w') as f:
|
||||
f.write(content)
|
||||
PYEOF
|
||||
}
|
||||
|
||||
# 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"
|
||||
}
|
||||
43
adapters/opencode/templates/bash-executor.js
Executable file
43
adapters/opencode/templates/bash-executor.js
Executable 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 };
|
||||
88
adapters/opencode/templates/plugin-stub.js.tmpl
Executable file
88
adapters/opencode/templates/plugin-stub.js.tmpl
Executable file
@@ -0,0 +1,88 @@
|
||||
// =============================================================================
|
||||
// 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",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, stderr } = await runBashHook(scriptAbs, payload);
|
||||
if (exitCode === 2) {
|
||||
// Documented opencode block mechanism for tool.execute.before
|
||||
throw new Error(`[${h.name}] blocked: ${stderr.trim() || "exit 2"}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
return handlers;
|
||||
};
|
||||
Reference in New Issue
Block a user