#compdef every-other-token

autoload -U is-at-least

_every-other-token() {
    typeset -A opt_args
    typeset -a _arguments_options
    local ret=1

    if is-at-least 5.2; then
        _arguments_options=(-s -S -C)
    else
        _arguments_options=(-s -C)
    fi

    local context curcontext="$curcontext" state line
    _arguments "${_arguments_options[@]}" : \
'--provider=[LLM provider\: openai, anthropic, ollama (local server), openrouter, gemini, mock (no API key needed), or local (a model running inside this program, exact probabilities; needs the \`local\` feature)]:PROVIDER:((openai\:"OpenAI Chat Completions API (GPT-3.5, GPT-4, etc.)"
anthropic\:"Anthropic Messages API (Claude family)"
ollama\:"Local Ollama server through its OpenAI-compatible endpoint (no API key)"
openrouter\:"OpenRouter\: hundreds of hosted models behind one OpenAI-compatible API"
gemini\:"Google Gemini through its OpenAI-compatible endpoint"
mock\:"In-process mock provider for tests and dry-run mode"
local\:"A small model running in-process (feature \`local\`)\: exact per-token log-probabilities with no API key or server, and \`--attribute\`"))' \
'--base-url=[Send requests to this API base URL instead of the provider'\''s default. Use it with --provider openai for any OpenAI-compatible server (llama.cpp, vLLM, LM Studio, a proxy), e.g. http\://localhost\:8080/v1. The API key is optional when this is set]:URL:_default' \
'--port=[Port for the web UI server]:PORT:_default' \
'--runs=[Number of runs in research mode]:RUNS:_default' \
'--output=[Output file path for research JSON (defaults to stdout)]:OUTPUT:_default' \
'--system-a=[System prompt A for A/B experiment mode]:SYSTEM_A:_default' \
'--top-logprobs=[Number of top alternative tokens to return per position (OpenAI only, 0–20)]:TOP_LOGPROBS:_default' \
'--system-b=[System prompt B for A/B experiment mode]:SYSTEM_B:_default' \
'--db=[Path to SQLite database for persisting experiment results (optional)]:DB:_default' \
'--heatmap-export=[Export per-position token confidence heatmap to CSV at this path]:HEATMAP_EXPORT:_default' \
'--heatmap-min-confidence=[Minimum average confidence to include a position in heatmap CSV export (0.0–1.0)]:HEATMAP_MIN_CONFIDENCE:_default' \
'--heatmap-sort-by=[Sort heatmap CSV rows by "position" (default) or "confidence"]:HEATMAP_SORT_BY:_default' \
'--record=[Record token events to a JSON replay file at this path]:RECORD:_default' \
'--replay=[Replay token events from a JSON file (bypasses live LLM call)]:REPLAY:_default' \
'--rate=[Fraction of tokens to intercept and transform (0.0–1.0, default 0.5). At 0.5 every other token is transformed; at 0.3 roughly one in three. Uses a deterministic Bresenham spread so results are reproducible when combined with --seed]:RATE:_default' \
'--seed=[Fixed RNG seed for reproducible Noise/Chaos transforms. Omit to use entropy-seeded randomness (default behaviour)]:SEED:_default' \
'--log-db=[Path to SQLite experiment log database (requires sqlite-log feature)]:LOG_DB:_default' \
'--prompt-file=[Path to a file with one prompt per line for batch research]:PROMPT_FILE:_default' \
'--completions=[Generate shell completions for the given shell and exit]:SHELL:(bash elvish fish powershell zsh)' \
'--rate-range=[Rate range for stochastic experiments, e.g. "0.3-0.7". When set, the interceptor randomly picks a rate in \[min, max\] for each run. Overrides --rate when provided. Format\: "MIN-MAX" (e.g. "0.2-0.8")]:RATE_RANGE:_default' \
'--template=[Prompt template with {input} placeholder. When set, the positional prompt is substituted into the template. Example\: "Answer this\: {input}"]:TEMPLATE:_default' \
'--min-confidence=[Only transform tokens whose API confidence is below this threshold. Tokens with confidence >= threshold are passed through unchanged. When no confidence data is available (Anthropic), falls back to rate-based selection. Range\: 0.0–1.0. Example\: --min-confidence 0.8]:MIN_CONFIDENCE:_default' \
'--format=[Output format for research mode\: "json" (default), "jsonl" (one JSON object per line)]:FORMAT:_default' \
'--collapse-window=[Number of consecutive low-confidence tokens to consider a "collapse" in research mode. Default\: 5]:COLLAPSE_WINDOW:_default' \
'--orchestrator-url=[Base URL for the MCP orchestrator pipeline (default\: http\://localhost\:3000)]:ORCHESTRATOR_URL:_default' \
'--max-retries=[Maximum API retry attempts on 429/5xx errors (default\: 3)]:MAX_RETRIES:_default' \
'--anthropic-max-tokens=[Maximum tokens in the Anthropic response (default\: 4096). Ignored when using the OpenAI provider]:ANTHROPIC_MAX_TOKENS:_default' \
'--synonym-file=[Path to a TSV or key=value file of additional synonym pairs to merge with the built-in map. Format\: one \`word\\treplacement\` or \`word = replacement\` pair per line]:SYNONYM_FILE:_default' \
'--api-key=[Optional API key required for /api/ endpoints in web UI mode. When set, requests to /api/* must include \`Authorization\: Bearer <key>\`]:API_KEY:_default' \
'--replay-speed=[Replay speed multiplier for --replay mode. 1.0 = real-time, 2.0 = double speed, 0.0 = instant]:REPLAY_SPEED:_default' \
'--timeout=[Stream hang timeout in seconds. The stream is forcibly dropped if no token arrives within this duration. Default\: 120 (2 minutes). Set to 0 to disable]:TIMEOUT:_default' \
'--export-timeseries=[Export per-run timeseries data to a CSV file at this path. Columns\: run,token_index,confidence,perplexity]:EXPORT_TIMESERIES:_default' \
'--local-max-tokens=[Longest reply --provider local generates, in tokens]:LOCAL_MAX_TOKENS:_default' \
'--list-models=[List known models for a provider\: "openai", "anthropic", or "all"]:LIST_MODELS:_default' \
'--sse-buffer-size=[Maximum number of tokens to buffer in the SSE stream before dropping oldest (default\: 1000). When the buffer is full, the oldest token is dropped and a BUFFER_OVERFLOW sentinel event is emitted to the client]:SSE_BUFFER_SIZE:_default' \
'--batch=[Path to a JSONL file for batch research mode. Each line must be JSON\: {"prompt"\: "...", "model"\: "gpt-4o", "transforms"\: \["drop_every_other"\]} Results are saved to batch_results_<timestamp>.jsonl]:BATCH:_default' \
'--export-logprobs=[Export per-token logprob data during a session. A path ending in .jsonl or .ndjson writes JSON lines with every token field (including top alternatives); anything else writes CSV with columns token,logprob,rank,model,timestamp,original,transformed,confidence,perplexity]:EXPORT_LOGPROBS:_default' \
'--compare=[Comma-separated list of models to compare with the same prompt. Runs the prompt through each model and shows a divergence heatmap. Example\: --compare gpt-4o,gpt-4o-mini]:COMPARE:_default' \
'--batch-tokens=[Path to a JSONL file of token arrays for batch compression processing. Each line must be a JSON array of strings\: \["tok1", "tok2", ...\] Results are printed as JSONL to stdout with job_id, ratio, and elapsed_ms]:FILE:_default' \
'*--similarity=[Compute and print cosine similarity between two texts. Provide exactly two space-separated strings. Example\: --similarity "hello world" "hello rust"]:TEXT:_default:TEXT:_default' \
'--importance=[Score each token in the prompt by importance and print results. Scoring method\: positional (default), frequency, syntactic, or composite. Example\: --importance positional]:METHOD:_default' \
'--chunk=[Chunk the prompt tokens with a strategy and print resulting chunks. Strategies\: fixed\:<n>, sentence, paragraph, semantic\:<threshold>. Example\: --chunk fixed\:50  or  --chunk sentence]:STRATEGY:_default' \
'--context-budget=[Token budget for the context window manager (max tokens for LLM context). Example\: --context-budget 4096]:CONTEXT_BUDGET:_default' \
'-v[Enable visual mode with color-coded tokens]' \
'--visual[Enable visual mode with color-coded tokens]' \
'--heatmap[Enable token importance heatmap]' \
'--orchestrator[Route through tokio-prompt-orchestrator MCP pipeline at localhost\:3000]' \
'--web[Launch web UI on localhost instead of terminal output]' \
'--no-open[With --web, do not open a browser tab automatically]' \
'--research[Enable headless research mode\: runs N times and outputs JSON stats]' \
'--significance[Compute statistical significance (two-sample t-test) when ≥2 A/B runs available]' \
'--baseline[Enable per-position confidence baseline comparison (research mode)]' \
'--diff-terminal[Run two parallel streams (OpenAI + Anthropic) and print side-by-side diff in terminal]' \
'--json-stream[Print one JSON line per token to stdout instead of colored text]' \
'(--web --json-stream --research)--tui[Full-screen terminal view\: the reply colored by confidence, live stats, a confidence sparkline and the top alternatives for the latest token. Press q to quit; the reply stays printed afterwards]' \
'--dry-run[Dry-run mode\: show what transforms would be applied without calling any API. Applies the configured transform to a sample token list and prints results]' \
'--json-schema[Print the embedded research JSON schema and exit]' \
'--attribute[With --provider local\: after the reply, show how much it depended on each prompt word, measured by removing the word and re-scoring the same reply with the model (occlusion attribution)]' \
'--validate-config[Validate configuration (print resolved values and exit)]' \
'--quality[Print quality metrics for the token compression applied to the prompt. Shows semantic_preservation, syntax_validity, ratio, and overall_score]' \
'--diversity-filter[Deduplicate the prompt tokens using the diversity filter. Splits the prompt on whitespace into token sequences, removes near-duplicate sequences (cosine similarity > 0.85), and prints the filtered result]' \
'--stats[Print sequence statistics (length, entropy, top tokens, hapax count, …) for the prompt tokens]' \
'--benchmark[Run the built-in compression benchmarks and print a ranked ASCII table]' \
'--vocab-stats[Print vocabulary statistics for the prompt tokens against a built-in reference corpus. Outputs\: vocab size, coverage %, OOV rate, avg/median frequency, and Zipf score]' \
'-h[Print help (see more with '\''--help'\'')]' \
'--help[Print help (see more with '\''--help'\'')]' \
'-V[Print version]' \
'--version[Print version]' \
'::prompt -- Input prompt to send to the LLM (optional when using --web):_default' \
'::transform -- Transform applied to the chosen tokens\: reverse, uppercase, mock, noise, chaos, scramble, delete, synonym, delay\:N, or a chain like reverse,uppercase:_default' \
'::model -- Model name (e.g. gpt-4, claude-sonnet-4-20250514):_default' \
&& ret=0
}

(( $+functions[_every-other-token_commands] )) ||
_every-other-token_commands() {
    local commands; commands=()
    _describe -t commands 'every-other-token commands' commands "$@"
}

if [ "$funcstack[1]" = "_every-other-token" ]; then
    _every-other-token "$@"
else
    compdef _every-other-token every-other-token
fi
