#!/usr/bin/env bash # basemind PreToolUse hook for the deferred agent tools (agent_post, agent_inbox, agent_threads). # # Pipes the hook event to `basemind agent hook pre-tool-use`, which names the caller's sub-identity # (the subagent, or else the session) and, when the call carries no `as`, answers with # {"hookSpecificOutput":{"hookEventName":"PreToolUse","updatedInput":{...,"as":""}}} # so two sessions or subagents in one checkout keep separate inboxes. The launcher sets # BASEMIND_HOST exactly as it does for `serve`, so the name resolves under the same principal. The # binary answers only on a host that applies a rewritten input (Claude Code; Codex, which needs # `permissionDecision: "allow"` beside it); elsewhere it prints nothing and the call is unchanged. # # Hard rule: this must NEVER block or fail the tool call. It is time-boxed (with or without a # `timeout` binary) and fail-open: any error (no binary, slow launcher, unreadable event) exits 0 # with no output, and the call proceeds unchanged. set -uo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" PLUGIN_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" # Run "$@" for at most $1 seconds. Uses `timeout` where installed; macOS has none by default, so a # watchdog stops the command there. The command runs in a process group of its own and the watchdog # signals that group: a helper it left holding stdout goes too, while the daemon its CLI may have # started, in a session of its own, is outside the group and keeps running. Standard input is passed # through. run_bounded() ( secs="$1" shift if command -v timeout >/dev/null 2>&1; then exec timeout "$secs" "$@" fi # Job control gives a background job its own process group. The shell's job reports would go to # its stderr, so that is discarded and the command gets the caller's stderr from fd 3. exec 3>&2 2>/dev/null set -m "$@" <&0 2>&3 3>&- & pid=$! ( nap="" trap '[ -z "$nap" ] || kill "$nap"; exit 0' TERM sleep "$secs" & nap=$! wait "$nap" || exit 0 kill -TERM -- "-$pid" ) >/dev/null 3>&- & watchdog=$! wait "$pid" rc=$? kill "$watchdog" wait "$watchdog" exit "$rc" ) # Cursor and Copilot, which the launcher names before Claude Code or Codex: the binary rewrites no # input for them, so there is no launcher to start. if [ -z "${BASEMIND_HOST:-}" ] && { [ -n "${CURSOR_PLUGIN_ROOT:-}" ] || [ -n "${COPILOT_CLI:-}" ]; }; then exit 0 fi STDIN_JSON="$(cat 2>/dev/null || true)" [ -n "$STDIN_JSON" ] || exit 0 OUT="$(printf '%s' "$STDIN_JSON" | run_bounded 6 "${PLUGIN_ROOT}/scripts/mcp-launch.sh" agent hook pre-tool-use 2>/dev/null)" || exit 0 [ -n "$OUT" ] || exit 0 printf '%s\n' "$OUT" exit 0