#!/usr/bin/env bash # snappy-os-inject.sh — Inject program.md + state/index.md into every session. # # Fetches from skills.snappy.ai (the gateway), caches locally for 5 minutes. # Falls back to local repo if network is down. # # Works for both: # - UserPromptSubmit → emits additionalContext # - PreToolUse (Task) → prepends to subagent prompt set -euo pipefail GATEWAY="https://skills.snappy.ai/.well-known/skills/snappy-os" CACHE_DIR="${HOME}/.cache/snappy-os" CACHE_TTL=300 # seconds LOCAL_FALLBACK="${HOME}/projects/snappy-os" # Load master key for personal-tier access ENV_CACHE="${HOME}/.claude/skills/snappy-settings/.env.cache" MASTER_KEY="" if [ -f "$ENV_CACHE" ]; then MASTER_KEY="$(grep '^SNAPPY_MASTER_KEY=' "$ENV_CACHE" | cut -d= -f2- | tr -d '"' | tr -d "'")" fi mkdir -p "$CACHE_DIR" fetch_or_cache() { local file="$1" local cache_file="${CACHE_DIR}/$(echo "$file" | tr '/' '_')" # Use cache if fresh if [ -f "$cache_file" ]; then local age=$(( $(date +%s) - $(stat -f %m "$cache_file") )) if [ "$age" -lt "$CACHE_TTL" ]; then cat "$cache_file" return 0 fi fi # Fetch from gateway local auth_header="" if [ -n "$MASTER_KEY" ]; then auth_header="Authorization: Bearer ${MASTER_KEY}" fi local content if content="$(curl -sS --max-time 3 ${auth_header:+-H "$auth_header"} "${GATEWAY}/${file}" 2>/dev/null)" && [ -n "$content" ]; then printf '%s' "$content" > "$cache_file" printf '%s' "$content" return 0 fi # Fall back to local local local_file="${LOCAL_FALLBACK}/${file}" if [ -f "$local_file" ]; then cat "$local_file" return 0 fi return 1 } # Bail if we can't get program.md from any source program_content="$(fetch_or_cache "program.md")" || exit 0 index_content="$(fetch_or_cache "state/index.md")" || exit 0 input="$(cat)" # Detect mode task_prompt="$(printf '%s' "$input" | jq -r '.tool_input.prompt // empty' 2>/dev/null || true)" user_prompt="$(printf '%s' "$input" | jq -r '.prompt // empty' 2>/dev/null || true)" if [ -n "$task_prompt" ]; then MODE="task" elif [ -n "$user_prompt" ]; then MODE="user" else exit 0 fi context_block=" You are operating snappy-os. The following two files are your operating system. Read them, then route or execute. --- program.md --- ${program_content} --- state/index.md --- ${index_content} " # Emit if [ "$MODE" = "task" ]; then new_prompt="${context_block}"$'\n\n'"${task_prompt}" printf '%s' "$input" | jq --arg p "$new_prompt" ' { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: (.tool_input | .prompt = $p) } } ' else jq -n --arg ctx "$context_block" '{ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: $ctx } }' fi