#!/usr/bin/env bash
# -u intentionally omitted: the auto-detect block references optional env vars
# (LEOSIS_SKILLS_DIR, CLAUDE_SKILLS_DIR, HERMES_SKILLS_DIR, CURSOR_RULES_DIR,
# OPENCODE_DIR, CODEX_HOME) — failing on unset values breaks installer UX.
# -o pipefail kept: ensures the heredoc chain surfaces real failures.
set -eo pipefail

# ───────────────────────────────────────────────────────────────────────
# USB installer
# pack:    universal-skill-bridge-catalog v1.0.3
# target:  auto
# skills:  1
# verify:  https://usbplus.peepsicklabs.com/api/install-sha256?slug=intent-router&target=auto
# Inspect with: less install.sh   |   Run with: bash install.sh
# Dry-run:  bash install.sh --check   (lists actions, executes nothing)
# ───────────────────────────────────────────────────────────────────────

# --- output helpers (also used by the auto-detect block below) ---
RED=$'[0;31m'
GRN=$'[0;32m'
YEL=$'[0;33m'
CYA=$'[0;36m'
DIM=$'[2m'
RST=$'[0m'

# --- --check / --dry-run flag: show what would happen, run nothing ---
USB_CHECK=0
case "${1:-}" in
  --check|--dry-run)
    USB_CHECK=1
    shift
    printf '
%s[check]%s dry-run mode — listing actions, executing nothing.

' "$CYA" "$RST"
    ;;
esac

# Run a command, or print "[would] <cmd>" in check mode.
do_or_show() {
  if [ "$USB_CHECK" = "1" ]; then
    printf '  %s[would]%s %s
' "$DIM" "$RST" "$*"
  else
    "$@"
  fi
}

# Write stdin to a file, or just announce it in check mode.
# Redirections can't go through do_or_show: the shell would open/truncate
# the file before the function runs, so dry-run must consume stdin itself.
write_file() {
  if [ "$USB_CHECK" = "1" ]; then
    cat > /dev/null
    printf '  %s[would]%s write %s
' "$DIM" "$RST" "$1"
  else
    cat > "$1"
  fi
}

REQUESTED_TARGET="auto"
TARGET="$REQUESTED_TARGET"
PACK_SLUG="universal-skill-bridge-catalog"
PACK_VERSION="1.0.3"
SKILL_COUNT="1"
ROOT="${AI_SKILL_HOME:-$HOME/.ai-skills}"
PACK_DIR="$ROOT/$PACK_SLUG"

if [ "$TARGET" = "auto" ]; then
  # Detect every supported runtime. We collect ALL hits so the user can pick
  # when more than one is installed — silently picking the first is bad UX.
  __USB_DETECTED=()
  [ -n "$LEOSIS_SKILLS_DIR" ] || [ -d "$HOME/.leosis" ]    && __USB_DETECTED+=("leosis")
  [ -n "$CLAUDE_SKILLS_DIR" ] || [ -d "$HOME/.claude" ]    && __USB_DETECTED+=("claude")
  [ -n "$HERMES_SKILLS_DIR" ] || [ -d "$HOME/.hermes" ]    && __USB_DETECTED+=("hermes")
  [ -n "$CURSOR_RULES_DIR" ] || [ -d "$HOME/.cursor" ]    && __USB_DETECTED+=("cursor")
  [ -n "$OPENCODE_DIR" ]      || [ -d "$HOME/.opencode" ] && __USB_DETECTED+=("opencode")
  [ -n "$CODEX_HOME" ]        || [ -d "$HOME/.codex" ]    && __USB_DETECTED+=("openai")
  [ -d "$HOME/.continue" ]                                  && __USB_DETECTED+=("langchain")
  [ -d "$HOME/.aider" ]                                     && __USB_DETECTED+=("anthropic")
  [ -d "$HOME/.vllm" ]                                      && __USB_DETECTED+=("vllm")
  [ -d "$HOME/.ollama" ]                                    && __USB_DETECTED+=("ollama")
  [ -d "$HOME/.lmstudio" ]                                  && __USB_DETECTED+=("lm-studio")
  [ -d "$HOME/.openrouter" ]                                && __USB_DETECTED+=("openrouter")
  [ -d "$HOME/.groq" ]                                      && __USB_DETECTED+=("groq")
  [ -d "$HOME/.mistral" ]                                   && __USB_DETECTED+=("mistral")
  [ -d "$HOME/.mcp" ]                                       && __USB_DETECTED+=("mcp")

  __USB_DETECT_COUNT=${#__USB_DETECTED[@]}
  if [ "$__USB_DETECT_COUNT" -eq 0 ]; then
    TARGET="generic"
    printf '%s[!]%s No AI runtime detected — falling back to generic.
' "$YEL" "$RST"
  elif [ "$__USB_DETECT_COUNT" -eq 1 ]; then
    TARGET="${__USB_DETECTED[0]}"
    printf '%s[OK]%s Auto-detected runtime: %s%s%s
' "$GRN" "$RST" "$CYA" "$TARGET" "$RST"
  else
    printf '
%s  Multiple AI runtimes detected on this machine:%s
' "$CYA" "$RST"
    printf '  %s
' "${__USB_DETECTED[*]}"

    # Where the answer is read from matters. Under `curl ... | bash` — the
    # documented one-liner, and what the CLI itself used to do — stdin is the
    # pipe carrying this script's own remaining text, not the keyboard. A bare
    # `select` there eats those leftover script lines as answers, prints
    # "Invalid choice" once per line, and never waits for the user. The real
    # terminal is /dev/tty, so prefer that whenever stdin isn't already one.
    __USB_INPUT=""
    if [ -t 0 ]; then
      __USB_INPUT="/dev/stdin"
    elif [ -r /dev/tty ] && (exec < /dev/tty) 2>/dev/null; then
      __USB_INPUT="/dev/tty"
    fi

    if [ -z "$__USB_INPUT" ]; then
      # Truly non-interactive (CI, no tty). Never loop — pick and say so.
      TARGET="${__USB_DETECTED[0]}"
      printf '%s[!]%s No terminal attached — defaulting to %s%s%s.
' "$YEL" "$RST" "$CYA" "$TARGET" "$RST"
      printf '    Pass --target=<name> or set USB_TARGET=<name> to choose explicitly.
'
    else
      __USB_OPTIONS=("${__USB_DETECTED[@]}" "generic (custom path)" "Cancel")
      PS3=$'
  Which one should USB install into? (number): '
      select __USB_CHOICE in "${__USB_OPTIONS[@]}"; do
        # Windows terminals deliver Enter as CRLF, leaving a trailing \r in
        # REPLY. select resolves the option before we can strip it, so on a
        # miss re-resolve by index from the stripped REPLY.
        REPLY="${REPLY%$'\r'}"
        if [ -z "$__USB_CHOICE" ]; then
          case "$REPLY" in
            ''|*[!0-9]*) ;;
            *) __USB_CHOICE="${__USB_OPTIONS[$((REPLY-1))]:-}" ;;
          esac
        fi
        if [ -z "$__USB_CHOICE" ]; then
          printf '%s[!]%s Invalid choice.
' "$YEL" "$RST"
          continue
        fi
        if [ "$__USB_CHOICE" = "Cancel" ]; then
          printf '%s[x]%s Cancelled.
' "$RED" "$RST"
          exit 1
        fi
        if [ "$__USB_CHOICE" = "generic (custom path)" ]; then
          TARGET="generic"
        else
          TARGET="$__USB_CHOICE"
        fi
        printf '%s[OK]%s Selected: %s%s%s
' "$GRN" "$RST" "$CYA" "$TARGET" "$RST"
        break
      done < "$__USB_INPUT"

      # select leaves its loop on EOF (Ctrl-D) without ever assigning TARGET.
      if [ "$TARGET" = "auto" ]; then
        TARGET="${__USB_DETECTED[0]}"
        printf '
%s[!]%s No selection made — defaulting to %s%s%s.
' "$YEL" "$RST" "$CYA" "$TARGET" "$RST"
      fi
    fi
  fi
  unset __USB_DETECTED __USB_DETECT_COUNT __USB_CHOICE __USB_OPTIONS __USB_INPUT
fi

do_or_show mkdir -p "$PACK_DIR/skills" "$ROOT/adapters/$TARGET"

write_file "$PACK_DIR/skillpack.json" <<'__USB_SKILLPACK_JSON_79D4C9413CF4D485__'
{
  "schemaVersion": "skill-bridge/v1",
  "generatedAt": "2026-10-15T23:26:45.298Z",
  "source": "https://usbplus.peepsicklabs.com",
  "installCommand": "curl -fsSL \"https://usbplus.peepsicklabs.com/api/install?target=auto\" | bash",
  "target": "auto",
  "adapter": {
    "files": [
      {
        "kind": "manifest",
        "path": "skillpack.json",
        "description": "Portable manifest containing all skills and adapter metadata."
      },
      {
        "kind": "skill",
        "path": "skills/*.md",
        "description": "Markdown skill files readable by any agent runtime."
      }
    ],
    "label": "Auto-detect Bridge",
    "notes": "Auto-detects the active agent runtime on your machine. LeoSIS folders are checked first, then Claude, Hermes, Cursor, LangChain, and finally falls back to generic markdown + JSON manifest when no known runtime is found.",
    "target": "auto",
    "commandHint": "curl -fsSL <host>/api/install?target=auto | bash",
    "installPath": "$AI_SKILL_HOME or $HOME/.ai-skills",
    "capabilities": [
      "runtime detection",
      "manifest sync",
      "portable markdown skills",
      "LeoSIS-first preference"
    ]
  },
  "pack": {
    "slug": "universal-skill-bridge-catalog",
    "name": "Universal Systems Bridge Catalog",
    "description": "A fully original, from-scratch catalog across 16 provider targets: 65 hand-researched engineering domains systematically expanded across 8 workflows (Audit, Plan, Build, Script, Diagnose, Harden, Explain, Tune) into 529 skills, plus 9 hand-written core orchestration skills. Every skill has a distinct trigger phrase, protocol prompt, input/output contract and examples — zero external dependencies.",
    "version": "1.0.3",
    "author": "Universal Systems Bridge"
  },
  "adapters": [
    {
      "files": [
        {
          "kind": "manifest",
          "path": "leosis.skillpack.json",
          "description": "LeoSIS-native skill pack manifest with /v1/skills metadata."
        },
        {
          "kind": "skill",
          "path": "skills/<slug>.md",
          "description": "Markdown skill card consumable by LeoSIS skill router."
        },
        {
          "kind": "tool",
          "path": "adapter.bridge.json",
          "description": "OpenAI-compatible tool descriptor for /v1/chat/completions."
        }
      ],
      "label": "LeoSIS Native Bridge",
      "notes": "First-class integration with PeepSick Labs LeoSIS Ultra. Installs the catalog into the LeoSIS skill directory and exposes it through the LeoSIS Brain router. Works with LeoSis CoWorker, Brain, and AgentOS runtimes out of the box. Recommended default for LeoSIS Ultra deployments.",
      "target": "leosis",
      "commandHint": "curl -fsSL <host>/api/install?target=leosis | bash",
      "installPath": "$LEOSIS_SKILLS_DIR or $HOME/.leosis/skills/universal-skill-bridge-catalog",
      "capabilities": [
        "LeoSIS Ultra native integration",
        "OpenAI-compatible /v1 endpoint",
        "sk-leosis-... key authentication",
        "per-user memory isolation",
        "RAG-augmented tool routing"
      ]
    },
    {
      "files": [
        {
          "kind": "manifest",
          "path": "skillpack.json",
          "description": "Portable manifest containing all skills and adapter metadata."
        },
        {
          "kind": "skill",
          "path": "skills/*.md",
          "description": "Markdown skill files readable by any agent runtime."
        }
      ],
      "label": "Auto-detect Bridge",
      "notes": "Auto-detects the active agent runtime on your machine. LeoSIS folders are checked first, then Claude, Hermes, Cursor, LangChain, and finally falls back to generic markdown + JSON manifest when no known runtime is found.",
      "target": "auto",
      "commandHint": "curl -fsSL <host>/api/install?target=auto | bash",
      "installPath": "$AI_SKILL_HOME or $HOME/.ai-skills",
      "capabilities": [
        "runtime detection",
        "manifest sync",
        "portable markdown skills",
        "LeoSIS-first preference"
      ]
    },
    {
      "files": [
        {
          "kind": "skill",
          "path": "skills/<slug>.md",
          "description": "Claude Code-compatible skill card with trigger phrase and protocol."
        }
      ],
      "label": "Claude-compatible Skills",
      "notes": "Writes prompt, input and output contracts as markdown skill cards into Claude Code's expected folder structure.",
      "target": "claude",
      "commandHint": "curl -fsSL <host>/api/install?target=claude | bash",
      "installPath": "$CLAUDE_SKILLS_DIR or $HOME/.claude/skills/universal-skill-bridge-catalog",
      "capabilities": [
        "SKILL.md style docs",
        "tool contract prompts",
        "verification checklists"
      ]
    },
    {
      "files": [
        {
          "kind": "manifest",
          "path": "hermes.skillpack.json",
          "description": "Hermes adapter target, capabilities and file listing."
        }
      ],
      "label": "Hermes Agent Pack",
      "notes": "Generates Hermes-compatible manifest and markdown protocols for agent orchestration.",
      "target": "hermes",
      "commandHint": "curl -fsSL <host>/api/install?target=hermes | bash",
      "installPath": "$HERMES_SKILLS_DIR or $HOME/.hermes/skills/universal-skill-bridge-catalog",
      "capabilities": [
        "agent graph hints",
        "skill routing",
        "memory summaries"
      ]
    },
    {
      "files": [
        {
          "kind": "tool",
          "path": "openai.tools.json",
          "description": "Tool descriptor list derived from skill input/output contracts."
        }
      ],
      "label": "OpenAI Agents Tool Descriptor",
      "notes": "Converts skill information into OpenAI Agents SDK function/tool descriptor format via manifest generation.",
      "target": "openai",
      "commandHint": "curl -fsSL <host>/api/install?target=openai | bash",
      "installPath": "$AI_SKILL_HOME/adapters/openai",
      "capabilities": [
        "tool descriptors",
        "json inputs",
        "structured outputs"
      ]
    },
    {
      "files": [
        {
          "kind": "tool",
          "path": "anthropic.tools.json",
          "description": "Anthropic Messages API tool_use descriptors."
        },
        {
          "kind": "skill",
          "path": "skills/<slug>.md",
          "description": "Markdown skill cards with prompt-cache breakpoint hints."
        }
      ],
      "label": "Anthropic Messages API",
      "notes": "Targets Anthropic's first-party Messages API (api.anthropic.com) directly without going through Claude Code. Produces tool_use descriptors compatible with Claude 3.5 Sonnet, 3.7 Sonnet, and the 4 family. Honors prompt-cache TTL fields and cache breakpoint placement.",
      "target": "anthropic",
      "commandHint": "curl -fsSL <host>/api/install?target=anthropic | bash",
      "installPath": "$ANTHROPIC_SKILLS_DIR or $HOME/.anthropic/skills/universal-skill-bridge-catalog",
      "capabilities": [
        "direct Messages API tool_use blocks",
        "Claude 3.5/3.7/4 native compatibility",
        "prompt-cache TTL hints",
        "no Claude Code dependency"
      ]
    },
    {
      "files": [
        {
          "kind": "tool",
          "path": "langchain.registry.json",
          "description": "Tool registry and routing hints."
        }
      ],
      "label": "LangChain / LangGraph Adapter",
      "notes": "Drops a ready-made registry JSON for writing a skill router node in LangChain or LangGraph.",
      "target": "langchain",
      "commandHint": "curl -fsSL <host>/api/install?target=langchain | bash",
      "installPath": "$AI_SKILL_HOME/adapters/langchain",
      "capabilities": [
        "tool registry",
        "graph node notes",
        "router metadata"
      ]
    },
    {
      "files": [
        {
          "kind": "rule",
          "path": "universal-skill-bridge-catalog.mdc",
          "description": "Compact skill router rules for IDE agents."
        }
      ],
      "label": "Cursor / IDE Rules",
      "notes": "Summarizes the skill pack into a single IDE rule file, providing behavior to coding agents in a single document.",
      "target": "cursor",
      "commandHint": "curl -fsSL <host>/api/install?target=cursor | bash",
      "installPath": "$CURSOR_RULES_DIR or $HOME/.cursor/rules/universal-skill-bridge-catalog.mdc",
      "capabilities": [
        "project rules",
        "coding checklists",
        "review protocol"
      ]
    },
    {
      "files": [
        {
          "kind": "manifest",
          "path": "mcp.server.json",
          "description": "MCP prompt/resource descriptor draft."
        }
      ],
      "label": "MCP Server Descriptor",
      "notes": "Produces a descriptor for contextualizing MCP server implementation as prompts/resources.",
      "target": "mcp",
      "commandHint": "curl -fsSL <host>/api/install?target=mcp | bash",
      "installPath": "$AI_SKILL_HOME/adapters/mcp",
      "capabilities": [
        "server manifest",
        "resource hints",
        "prompt templates"
      ]
    },
    {
      "files": [
        {
          "kind": "manifest",
          "path": "skillpack.json",
          "description": "Runtime-independent master pack manifest."
        }
      ],
      "label": "Generic Portable Pack",
      "notes": "Creates importable manifest and markdown skill files for any model or agent system that does not match a specific adapter.",
      "target": "generic",
      "commandHint": "curl -fsSL <host>/api/install?target=generic | bash",
      "installPath": "$AI_SKILL_HOME or $HOME/.ai-skills/universal-skill-bridge-catalog",
      "capabilities": [
        "plain manifest",
        "markdown prompts",
        "runtime-agnostic"
      ]
    },
    {
      "files": [
        {
          "kind": "tool",
          "path": "openrouter.tools.json",
          "description": "OpenAI-format tool descriptors routed through OpenRouter."
        },
        {
          "kind": "manifest",
          "path": "skillpack.json",
          "description": "Portable manifest with model routing hints."
        }
      ],
      "label": "OpenRouter Multi-Model Bridge",
      "notes": "Targets OpenRouter (openrouter.ai) which exposes an OpenAI-compatible API for 100+ models. Adapter emits tool descriptors in OpenAI tool format so any OpenRouter-routed model can call the skills. Includes credit-cost hints per skill and free-model fallback annotations.",
      "target": "openrouter",
      "commandHint": "curl -fsSL <host>/api/install?target=openrouter | bash",
      "installPath": "$OPENROUTER_SKILLS_DIR or $HOME/.openrouter/skills/universal-skill-bridge-catalog",
      "capabilities": [
        "OpenAI-compatible /api/v1 endpoint",
        "fallback model routing",
        "credit-based billing passthrough",
        "100+ model manifest"
      ]
    },
    {
      "files": [
        {
          "kind": "tool",
          "path": "groq.tools.json",
          "description": "OpenAI function-call descriptors for Groq inference."
        },
        {
          "kind": "skill",
          "path": "skills/<slug>.md",
          "description": "Markdown skill cards with latency-budget annotations."
        }
      ],
      "label": "Groq Fast Inference Bridge",
      "notes": "Targets GroqCloud (groq.com) — sub-second token streaming via LPU hardware. Adapter emits function-call descriptors in OpenAI format. Best suited for high-throughput RAG and tool-routing scenarios where latency matters more than model size.",
      "target": "groq",
      "commandHint": "curl -fsSL <host>/api/install?target=groq | bash",
      "installPath": "$GROQ_SKILLS_DIR or $HOME/.groq/skills/universal-skill-bridge-catalog",
      "capabilities": [
        "ultra-low-latency LPU inference",
        "OpenAI-compatible endpoint",
        "Llama 3 / Mixtral / Gemma native",
        "batch routing aware"
      ]
    },
    {
      "files": [
        {
          "kind": "tool",
          "path": "mistral.tools.json",
          "description": "Mistral function-calling descriptors."
        },
        {
          "kind": "skill",
          "path": "skills/<slug>.md",
          "description": "Markdown skill cards with model-suitability tags."
        }
      ],
      "label": "Mistral AI API Bridge",
      "notes": "Targets Mistral AI's first-party API (api.mistral.ai). Adapter produces function-calling descriptors compatible with Mistral Large, Codestral, and Mixtral model families. Supports JSON-mode tool outputs and per-model capability hints.",
      "target": "mistral",
      "commandHint": "curl -fsSL <host>/api/install?target=mistral | bash",
      "installPath": "$MISTRAL_SKILLS_DIR or $HOME/.mistral/skills/universal-skill-bridge-catalog",
      "capabilities": [
        "Mistral function-calling",
        "Codestral code-completion aware",
        "OpenAI-compatible endpoint",
        "JSON-mode tool outputs"
      ]
    },
    {
      "files": [
        {
          "kind": "manifest",
          "path": "ollama.modelfile.patch",
          "description": "Patch instructions for Ollama Modelfile."
        },
        {
          "kind": "skill",
          "path": "skills/<slug>.md",
          "description": "Markdown skill cards consumable by Ollama tool-aware models."
        }
      ],
      "label": "Ollama Local Runtime",
      "notes": "Targets Ollama (ollama.com) running locally. Adapter emits Ollama Modelfile patches that teach the local model the skill catalog. Compatible with any Ollama model that supports function calling (llama3.1, qwen2.5, mistral, etc.).",
      "target": "ollama",
      "commandHint": "curl -fsSL <host>/api/install?target=ollama | bash",
      "installPath": "$OLLAMA_SKILLS_DIR or $HOME/.ollama/skills/universal-skill-bridge-catalog",
      "capabilities": [
        "local inference, zero API cost",
        "Modelfile-aware tool support",
        "GPU/CPU autodetect",
        "offline-first skill library"
      ]
    },
    {
      "files": [
        {
          "kind": "tool",
          "path": "lmstudio.tools.json",
          "description": "OpenAI-format tool descriptors for LM Studio's local server."
        },
        {
          "kind": "manifest",
          "path": "preset.json",
          "description": "LM Studio preset configuration patch."
        }
      ],
      "label": "LM Studio Local Desktop",
      "notes": "Targets LM Studio's built-in local server (lmstudio.ai). Emits OpenAI-compatible tool descriptors and patches LM Studio's preset configuration to include the skill catalog. Runs entirely offline; ideal for air-gapped development.",
      "target": "lm-studio",
      "commandHint": "curl -fsSL <host>/api/install?target=lm-studio | bash",
      "installPath": "$LM_STUDIO_SKILLS_DIR or $HOME/.lmstudio/skills/universal-skill-bridge-catalog",
      "capabilities": [
        "GGUF model support",
        "local OpenAI-compatible server",
        "GPU/CPU layer offload aware",
        "no network requirement"
      ]
    },
    {
      "files": [
        {
          "kind": "tool",
          "path": "vllm.tools.json",
          "description": "OpenAI-format tool descriptors for vLLM /v1 endpoint."
        },
        {
          "kind": "skill",
          "path": "skills/<slug>.md",
          "description": "Markdown skill cards with throughput hints."
        }
      ],
      "label": "vLLM Self-Hosted Inference",
      "notes": "Targets self-hosted vLLM inference servers. Adapter emits OpenAI-format tool descriptors compatible with vLLM's /v1/chat/completions endpoint. Suitable for on-prem deployments, large-scale batch processing, and cost-sensitive production workloads.",
      "target": "vllm",
      "commandHint": "curl -fsSL <host>/api/install?target=vllm | bash",
      "installPath": "$VLLM_SKILLS_DIR or $HOME/.vllm/skills/universal-skill-bridge-catalog",
      "capabilities": [
        "PagedAttention high-throughput",
        "OpenAI-compatible server",
        "multi-GPU tensor parallelism",
        "HuggingFace model loader"
      ]
    }
  ],
  "skills": [
    {
      "slug": "intent-router",
      "name": "Intent Router",
      "category": "Orchestration",
      "description": "Analyses a user request, determines the most appropriate skill to invoke, and produces a ranked execution plan. Prevents unnecessary agent context switching by grouping related sub-tasks under a single skill.",
      "triggerPhrase": "Call this when a user request is vague, multi-layered, or when you are unsure which specialised skill applies.",
      "promptTemplate": "Read the full request. Identify the primary intent (create, debug, refactor, document, secure, optimise). Determine the target layer (frontend, backend, data, infra, AI, docs). Choose the single best matching skill slug. Explain the choice in one sentence. If multiple skills could apply, rank them and output a sequence. Never default to asking clarifying questions if a safe fallback exists.",
      "inputs": [
        {
          "kind": "text",
          "name": "goal",
          "required": true,
          "description": "The precise outcome the user wants to achieve."
        },
        {
          "kind": "text",
          "name": "context",
          "required": false,
          "description": "Project, file, conversation or task context."
        },
        {
          "kind": "text",
          "name": "assets",
          "required": false,
          "description": "Relevant code, logs, URLs, documents or data samples."
        }
      ],
      "outputs": [
        {
          "kind": "json",
          "name": "manifest",
          "description": "Machine-readable plan, contract or registry output."
        },
        {
          "kind": "checklist",
          "name": "checklist",
          "description": "Executable steps with risk assessment and validation items."
        }
      ],
      "examples": [
        "User asks 'set up authentication for my app' → route to oauth-auth-guardian.",
        "User says 'the build is failing' → route to incident-debugger."
      ],
      "metadata": {
        "risk": "low",
        "tags": [
          "router",
          "orchestration",
          "classification"
        ],
        "agentAgnostic": true,
        "modelAgnostic": true
      }
    }
  ]
}
__USB_SKILLPACK_JSON_79D4C9413CF4D485__

write_file "$PACK_DIR/adapter.bridge.json" <<'__USB_ADAPTER_JSON_C0D44CD68345066F__'
{
  "schemaVersion": "skill-bridge/v1",
  "generatedAt": "2026-10-15T23:26:45.298Z",
  "target": "auto",
  "adapter": {
    "files": [
      {
        "kind": "manifest",
        "path": "skillpack.json",
        "description": "Portable manifest containing all skills and adapter metadata."
      },
      {
        "kind": "skill",
        "path": "skills/*.md",
        "description": "Markdown skill files readable by any agent runtime."
      }
    ],
    "label": "Auto-detect Bridge",
    "notes": "Auto-detects the active agent runtime on your machine. LeoSIS folders are checked first, then Claude, Hermes, Cursor, LangChain, and finally falls back to generic markdown + JSON manifest when no known runtime is found.",
    "target": "auto",
    "commandHint": "curl -fsSL <host>/api/install?target=auto | bash",
    "installPath": "$AI_SKILL_HOME or $HOME/.ai-skills",
    "capabilities": [
      "runtime detection",
      "manifest sync",
      "portable markdown skills",
      "LeoSIS-first preference"
    ]
  },
  "pack": {
    "slug": "universal-skill-bridge-catalog",
    "name": "Universal Systems Bridge Catalog",
    "description": "A fully original, from-scratch catalog across 16 provider targets: 65 hand-researched engineering domains systematically expanded across 8 workflows (Audit, Plan, Build, Script, Diagnose, Harden, Explain, Tune) into 529 skills, plus 9 hand-written core orchestration skills. Every skill has a distinct trigger phrase, protocol prompt, input/output contract and examples — zero external dependencies.",
    "version": "1.0.3",
    "author": "Universal Systems Bridge"
  },
  "tools": [
    {
      "name": "intent_router",
      "title": "Intent Router",
      "description": "Analyses a user request, determines the most appropriate skill to invoke, and produces a ranked execution plan. Prevents unnecessary agent context switching by grouping related sub-tasks under a single skill.",
      "trigger": "Call this when a user request is vague, multi-layered, or when you are unsure which specialised skill applies.",
      "inputSchema": {
        "type": "object",
        "properties": {
          "goal": {
            "type": "string",
            "description": "The precise outcome the user wants to achieve."
          },
          "context": {
            "type": "string",
            "description": "Project, file, conversation or task context."
          },
          "assets": {
            "type": "string",
            "description": "Relevant code, logs, URLs, documents or data samples."
          }
        },
        "required": [
          "goal"
        ]
      },
      "outputContract": [
        {
          "kind": "json",
          "name": "manifest",
          "description": "Machine-readable plan, contract or registry output."
        },
        {
          "kind": "checklist",
          "name": "checklist",
          "description": "Executable steps with risk assessment and validation items."
        }
      ],
      "promptTemplate": "Read the full request. Identify the primary intent (create, debug, refactor, document, secure, optimise). Determine the target layer (frontend, backend, data, infra, AI, docs). Choose the single best matching skill slug. Explain the choice in one sentence. If multiple skills could apply, rank them and output a sequence. Never default to asking clarifying questions if a safe fallback exists.",
      "metadata": {
        "risk": "low",
        "tags": [
          "router",
          "orchestration",
          "classification"
        ],
        "agentAgnostic": true,
        "modelAgnostic": true
      }
    }
  ]
}
__USB_ADAPTER_JSON_C0D44CD68345066F__

write_file "$PACK_DIR/cursor-rule.mdc" <<'__USB_CURSOR_RULE_615841536A89B4A4__'
---
description: Universal Systems Bridge Catalog router rules
globs: ["**/*"]
alwaysApply: false
---

# Universal Systems Bridge Catalog

This rule file introduces the modular skill pack to the IDE agent as a compact router.

## Router rule
Classify the user's request first by intent, risk, context, and required output type. Pick the best-fitting skill slug below, write a brief rationale, and apply that skill's protocol.

- intent-router: Call this when a user request is vague, multi-layered, or when you are unsure which specialised skill applies. Output: json, checklist.

## General safety
- Never write secret values into the client bundle.
- Never consider a code change done without running its verification commands.
- Fall back to generic markdown + JSON manifest behavior if the target runtime is unknown.
__USB_CURSOR_RULE_615841536A89B4A4__

write_file "$PACK_DIR/skills/intent-router.md" <<'__USB_SKILL_45BCA16379F69095__'
---
description: "Analyses a user request, determines the most appropriate skill to invoke, and produces a ranked execution plan. Prevents unnecessary agent context switching by grouping related sub-tasks under a single skill. Call this when a user request is vague, multi-layered, or when you are unsure which specialised skill applies."
slug: intent-router
name: Intent Router
category: Orchestration
risk: low
model_agnostic: true
agent_agnostic: true
tags: router, orchestration, classification
---

# Intent Router

Analyses a user request, determines the most appropriate skill to invoke, and produces a ranked execution plan. Prevents unnecessary agent context switching by grouping related sub-tasks under a single skill.

## When to use it
Call this when a user request is vague, multi-layered, or when you are unsure which specialised skill applies.

## Protocol
Read the full request. Identify the primary intent (create, debug, refactor, document, secure, optimise). Determine the target layer (frontend, backend, data, infra, AI, docs). Choose the single best matching skill slug. Explain the choice in one sentence. If multiple skills could apply, rank them and output a sequence. Never default to asking clarifying questions if a safe fallback exists.

## Input contract
- **goal** (text, required): The precise outcome the user wants to achieve.
- **context** (text, optional): Project, file, conversation or task context.
- **assets** (text, optional): Relevant code, logs, URLs, documents or data samples.

## Output contract
- **manifest** (json): Machine-readable plan, contract or registry output.
- **checklist** (checklist): Executable steps with risk assessment and validation items.

## Examples
- User asks 'set up authentication for my app' → route to oauth-auth-guardian.
- User says 'the build is failing' → route to incident-debugger.
__USB_SKILL_45BCA16379F69095__

case "$TARGET" in
  leosis)
    DEST="${LEOSIS_SKILLS_DIR:-$HOME/.leosis/skills/$PACK_SLUG}"
    do_or_show mkdir -p "$DEST"
    do_or_show cp "$PACK_DIR/skills/"*.md "$DEST/"
    do_or_show cp "$PACK_DIR/skillpack.json" "$DEST/skillpack.json"
    do_or_show cp "$PACK_DIR/adapter.bridge.json" "$DEST/adapter.bridge.json"
    do_or_show cp "$PACK_DIR/cursor-rule.mdc" "$DEST/$PACK_SLUG.mdc"
    ;;
  claude)
    # Claude Code discovers skills as <skill-name>/SKILL.md directories, not
    # as loose .md files — dropping the pack in as flat markdown wrote real
    # files that Claude then silently ignored.
    DEST="${CLAUDE_SKILLS_DIR:-$HOME/.claude/skills}"
    do_or_show mkdir -p "$DEST"
    if [ "$SKILL_COUNT" -le 10 ]; then
      # A handful: each becomes its own directly-invocable /<slug> skill.
      for __usb_src in "$PACK_DIR/skills/"*.md; do
        __usb_slug=$(basename "$__usb_src" .md)
        do_or_show mkdir -p "$DEST/$__usb_slug"
        do_or_show cp "$__usb_src" "$DEST/$__usb_slug/SKILL.md"
      done
      unset __usb_src __usb_slug
    else
      # A catalog: one /usb router skill, with the skills beside it as
      # reference files. Claude loads every skill's description up front to
      # choose between them, so N directories would mean N descriptions in
      # context on every request; a skill's body costs nothing until used.
      do_or_show mkdir -p "$DEST/usb/skills"
      do_or_show cp "$PACK_DIR/skills/"*.md "$DEST/usb/skills/"
      do_or_show cp "$PACK_DIR/skillpack.json" "$DEST/usb/skillpack.json"
write_file "$DEST/usb/SKILL.md" <<'__USB_CLAUDE_ROUTER_C8BC876981372834__'
---
description: "Universal Systems Bridge Catalog: 1 engineering skills across 1 categories. Use when the user wants to audit, plan, build, script, diagnose, harden, explain, or tune a specific technology — databases, infrastructure, frontend, security, AI agents, and more."
---

# Universal Systems Bridge Catalog

1 skills are installed as reference files in `skills/` next to this file.
Each one carries a full protocol, input and output contracts, and worked examples.

## How to use this

1. Work out what the user is asking for: the technology involved, and the kind
   of work — audit, plan, build, script, diagnose, harden, explain, or tune.
2. Find the matching slug in the index below. Generated skills are named
   `<domain>-<workflow>`, for example `redis-caching-harden`.
3. Read `skills/<slug>.md` and follow its Protocol section.
4. If nothing matches closely, say so and proceed normally rather than forcing
   an unrelated skill.

## Index

### Orchestration
intent-router
__USB_CLAUDE_ROUTER_C8BC876981372834__
    fi
    ;;
  hermes)
    DEST="${HERMES_SKILLS_DIR:-$HOME/.hermes/skills/$PACK_SLUG}"
    do_or_show mkdir -p "$DEST"
    do_or_show cp "$PACK_DIR/skills/"*.md "$DEST/"
    do_or_show cp "$PACK_DIR/skillpack.json" "$DEST/hermes.skillpack.json"
    do_or_show cp "$PACK_DIR/adapter.bridge.json" "$DEST/adapter.bridge.json"
    ;;
  cursor)
    # Cursor reads project rules from .cursor/rules INSIDE the project;
    # user-level rules are Settings-UI only, so a file written to
    # ~/.cursor/rules is never read. Default to the current project and say
    # where it went, since that only helps if you run this from the repo.
    DEST="${CURSOR_RULES_DIR:-$PWD/.cursor/rules}"
    do_or_show mkdir -p "$DEST"
    do_or_show cp "$PACK_DIR/cursor-rule.mdc" "$DEST/$PACK_SLUG.mdc"
    if [ "$USB_CHECK" != "1" ] && [ "${CURSOR_RULES_DIR:-}" = "" ]; then
      printf '%s[i]%s Cursor rules are per-project. Installed into %s%s%s — run USB from another
' "$CYA" "$RST" "$CYA" "$DEST" "$RST"
      printf '    project (or set CURSOR_RULES_DIR) to install them there too.
'
    fi
    ;;
  openai|anthropic|openrouter|groq|mistral)
    DEST="$ROOT/adapters/$TARGET"
    do_or_show mkdir -p "$DEST"
    do_or_show cp "$PACK_DIR/adapter.bridge.json" "$DEST/$PACK_SLUG.json"
    do_or_show cp "$PACK_DIR/skillpack.json" "$DEST/skillpack.json"
    ;;
  langchain|mcp)
    DEST="$ROOT/adapters/$TARGET"
    do_or_show mkdir -p "$DEST"
    do_or_show cp "$PACK_DIR/adapter.bridge.json" "$DEST/$PACK_SLUG.json"
    do_or_show cp "$PACK_DIR/skillpack.json" "$DEST/skillpack.json"
    ;;
  ollama|lm-studio|vllm)
    DEST="$ROOT/adapters/$TARGET"
    do_or_show mkdir -p "$DEST"
    do_or_show cp "$PACK_DIR/adapter.bridge.json" "$DEST/$PACK_SLUG.json"
    do_or_show cp "$PACK_DIR/skills/"*.md "$DEST/"
    ;;
  *)
    DEST="$PACK_DIR"
    ;;
esac

# --- Local install registry (always-on, no network, no PII) ---
INSTALL_RECORD="$PACK_DIR/installed.json"
write_file "$INSTALL_RECORD" <<'__USB_INSTALL_RECORD__'
{
  "pack": "__PACK_SLUG__",
  "version": "__PACK_VERSION__",
  "target": "__TARGET__",
  "skill_count": __SKILL_COUNT__,
  "installed_at": "__TIMESTAMP__"
}
__USB_INSTALL_RECORD__
if [ "$USB_CHECK" != "1" ]; then
  sed -i.bak \
    -e "s|__PACK_SLUG__|$PACK_SLUG|g" \
    -e "s|__PACK_VERSION__|$PACK_VERSION|g" \
    -e "s|__TARGET__|$TARGET|g" \
    -e "s|__SKILL_COUNT__|$SKILL_COUNT|g" \
    -e "s|__TIMESTAMP__|$(date -u +%Y-%m-%dT%H:%M:%SZ)|g" \
    "$INSTALL_RECORD"
  rm -f "$INSTALL_RECORD.bak"
fi

# --- Optional anonymous install telemetry (opt-in via env var) ---
if [ "${USB_TELEMETRY:-off}" = "on" ]; then
  TELEMETRY_URL="${USB_TELEMETRY_URL:-https://api.universal-skill-bridge.dev/v1/telemetry}"
  do_or_show curl -fsS -X POST -H "Content-Type: application/json" \
    --max-time 3 \
    -d "{\"target\":\"$TARGET\",\"pack\":\"$PACK_SLUG\",\"version\":\"$PACK_VERSION\",\"skills\":$SKILL_COUNT,\"ts\":$(date +%s)}" \
    "$TELEMETRY_URL" >/dev/null 2>&1 || true
fi

if [ "$USB_CHECK" = "1" ]; then
  printf '
[check] Would write %s skills. Re-run without --check to actually install.
' "$SKILL_COUNT"
  printf '  [would] pack dir:    %s
' "$PACK_DIR"
  printf '  [would] registry:    %s
' "$INSTALL_RECORD"
  printf '  [would] target:      (resolved after auto-detect — see logs above)
'
  exit 0
fi

SKILL_UNIT="skills"; [ "$SKILL_COUNT" = "1" ] && SKILL_UNIT="skill"
echo "✅ $PACK_SLUG v$PACK_VERSION installed for target: $TARGET ($SKILL_COUNT $SKILL_UNIT)"
echo "📦 Portable pack: $PACK_DIR"
echo "🔌 Target files: ${DEST:-$PACK_DIR}"
echo "📝 Local registry: $INSTALL_RECORD"
echo "ℹ️  Tip: override the target folder with AI_SKILL_HOME, LEOSIS_SKILLS_DIR, CLAUDE_SKILLS_DIR, HERMES_SKILLS_DIR, or CURSOR_RULES_DIR."
echo "💡 Optional: export USB_TELEMETRY=on to send anonymous install stats (target + pack + version, no PII)."

# ─────────────────────────────────────────────────────────────────
# Filter applied: 1 / 529 skills (100% smaller)
# Query: ?slug=intent-router&target=auto
# Verify with:  curl -fsSL "https://usbplus.peepsicklabs.com/api/install-sha256?slug=intent-router&target=auto"
# ─────────────────────────────────────────────────────────────────