rtk-rewrite.sh

 1#!/usr/bin/env bash
 2
 3# RTK hook for Crush
 4# This hook rewrites bash commands to use rtk for token savings.
 5#
 6# https://github.com/rtk-ai/rtk
 7#
 8# Requires: rtk >= 0.23.0, jq
 9#
10# All rewrite logic lives in `rtk rewrite`, which is the single source of
11# truth. To add or change rewrite rules, edit the Rust registry, not this
12# file.
13#
14# Exit code protocol for `rtk rewrite`:
15#   0 + stdout  Rewrite found → allow with updated input
16#   1           No RTK equivalent → pass through unchanged
17#   2           Deny rule matched → pass through
18
19set -euo pipefail
20
21if ! command -v jq &>/dev/null; then
22    echo "[rtk] WARNING: jq is not installed. Install: https://jqlang.github.io/jq/download/" >&2
23    exit 0
24fi
25
26if ! command -v rtk &>/dev/null; then
27    echo "[rtk] WARNING: rtk is not installed. Install: https://github.com/rtk-ai/rtk#installation" >&2
28    exit 0
29fi
30
31# Version guard: rtk rewrite requires >= 0.23.0.
32RTK_VERSION=$(rtk --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
33if [ -n "$RTK_VERSION" ]; then
34    MAJOR=$(echo "$RTK_VERSION" | cut -d. -f1)
35    MINOR=$(echo "$RTK_VERSION" | cut -d. -f2)
36    if [ "$MAJOR" -eq 0 ] && [ "$MINOR" -lt 23 ]; then
37        echo "[rtk] WARNING: rtk $RTK_VERSION is too old (need >= 0.23.0). Upgrade: cargo install rtk" >&2
38        exit 0
39    fi
40fi
41
42CMD="${CRUSH_TOOL_INPUT_COMMAND:-}"
43if [ -z "$CMD" ]; then
44    exit 0
45fi
46
47REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null) && EXIT_CODE=0 || EXIT_CODE=$?
48
49case $EXIT_CODE in
500 | 3)
51    # Rewrite found. If identical, the command already uses rtk.
52    [ "$CMD" = "$REWRITTEN" ] && exit 0
53    jq -n --arg cmd "$REWRITTEN" \
54        '{decision: "allow", updated_input: ({command: $cmd} | tostring)}'
55    ;;
56*)
57    # No rewrite (1), deny (2), or unexpected — pass through.
58    exit 0
59    ;;
60esac