llm-switcher 1.2.0 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +1 -0
  3. package/blindfold/make-certs.sh +3 -1
  4. package/catalog.mjs +132 -42
  5. package/classifier.mjs +238 -0
  6. package/docs/TOKEN-OPTIMIZER-INTEROP.md +110 -110
  7. package/docs/response-matrix.json +1130 -1130
  8. package/formats.mjs +30 -1
  9. package/icons/antigravity.png +0 -0
  10. package/icons/claude.png +0 -0
  11. package/icons/codex.png +0 -0
  12. package/icons/deepseek.png +0 -0
  13. package/icons/gemini.png +0 -0
  14. package/icons/github.png +0 -0
  15. package/icons/groq.png +0 -0
  16. package/icons/intact.svg +1 -0
  17. package/icons/ollama.png +0 -0
  18. package/icons/openai.png +0 -0
  19. package/icons/openrouter.png +0 -0
  20. package/icons/qwen.png +0 -0
  21. package/icons/vertex.png +0 -0
  22. package/mcp.mjs +2 -2
  23. package/package.json +1 -1
  24. package/proxy.mjs +34 -20
  25. package/scripts/run-tests.mjs +3 -1
  26. package/skills/llm-switcher/SKILL.md +93 -93
  27. package/state.mjs +58 -4
  28. package/switch +0 -0
  29. package/switch.mjs +28 -4
  30. package/tests/blindfold-e2e.test.mjs +2 -2
  31. package/tests/blindfold-task5.test.mjs +1 -1
  32. package/tests/blindfold.task3.test.mjs +2 -2
  33. package/tests/blindfold.wire.test.mjs +3 -1
  34. package/tests/catalog.test.mjs +117 -19
  35. package/tests/classifier.test.mjs +210 -0
  36. package/tests/codex-daemon.test.mjs +92 -0
  37. package/tests/formats.test.mjs +30 -0
  38. package/tests/helpers.mjs +24 -24
  39. package/tests/lifecycle.test.mjs +49 -37
  40. package/tests/live-optimizer-interop.mjs +205 -205
  41. package/tests/make-certs.test.mjs +22 -0
  42. package/tests/real-user-sim.test.mjs +3 -0
  43. package/tests/shim.test.mjs +8 -3
  44. package/tests/switch.test.mjs +30 -24
  45. package/tests/ui.test.mjs +90 -0
  46. package/tests/version.test.mjs +78 -0
  47. package/ui.html +1895 -1616
  48. package/version.mjs +53 -0
@@ -1,110 +1,110 @@
1
- # Token Optimizer Interoperability & Failure Mode Report
2
-
3
- **How LLM Switcher acts as the protective outermost edge gateway for aggressive prompt/token optimizers (Headroom, RTK, Ponytail).**
4
-
5
- ---
6
-
7
- ## Executive Summary
8
-
9
- Third-party prompt optimizers and token compressors — such as **Headroom**, **RTK (Rust Token Killer)**, and **Ponytail** — attempt to reduce LLM input tokens by aggressively pruning message history, truncating command stdout, or forcing extreme prompt brevity.
10
-
11
- While these tools can reduce raw token counts in simple scenarios, **they frequently break complex agentic coding workflows** by corrupting message graphs, orphaning tool calls, and stripping reasoning parameters. When these pruned payloads hit upstream APIs directly (such as Anthropic, OpenAI, or 9Router), the provider immediately throws fatal `HTTP 400 Bad Request` errors or severely degrades reasoning depth.
12
-
13
- **LLM Switcher solves this by acting as the outermost edge gatekeeper (`127.0.0.1:3456`).** It intercepts the pruned payload before it leaves your machine, runs its built-in **Healer Engine** to repair message graphs and restore reasoning parameters, unlocks 1M context windows, and safely converts the protocol to your upstream provider.
14
-
15
- ---
16
-
17
- ## Tool Breakdown: What They Do & How They Break Payloads
18
-
19
- ### 1. Headroom (`headroomlabs-ai/headroom`)
20
- - **Mechanism:** Runs as a local proxy on `:8787` (or wraps CLI agents). Compresses conversation history, RAG chunks, and tool outputs using SmartCrusher (JSON), CodeCompressor (AST), and Kompress-v2-base. Also attempts "effort routing" to dial down thinking budgets.
21
- - **Critical Failure Points:**
22
- - **Orphaned `tool_result` blocks:** When pruning historical turns, Headroom often discards the `assistant` turn containing a `tool_use`, while retaining the subsequent `user` turn containing the `tool_result`. Anthropic's API strictly validates tool use IDs and crashes with:
23
- ```
24
- HTTP 400 invalid_request_error: "tool_use_id 'xxx' does not correspond to any tool_use"
25
- ```
26
- - **Consecutive `user` turns:** Dropping intermediary assistant turns causes multiple user messages to sit adjacent to each other. Anthropic strictly throws:
27
- ```
28
- HTTP 400 invalid_request_error: "roles must alternate between 'user' and 'assistant'"
29
- ```
30
- - **Reasoning Suppression:** Its "effort routing" dials down `thinking.budget_tokens` on routine tool turns. On complex models (Claude Opus, Gemini Flash), this prevents the model from formulating multi-step reasoning before acting.
31
-
32
- ### 2. RTK (`rtk-ai/rtk` - Rust Token Killer)
33
- - **Mechanism:** A single Rust binary that hooks into shell tool execution (e.g. `PreToolUse` in Claude Code / Cursor) and rewrites CLI commands (`git`, `ls`, `cat`, `grep`, `pytest`) to filter out noise, truncate lines, and inject recall tokens (`[full output: rtk recall xxx]`).
34
- - **Critical Failure Points:**
35
- - **Corrupted Structural Data:** When an agent invokes a tool expecting machine-readable JSON or exact AST formatting, RTK's heuristic summaries can alter structural delimiters, causing downstream tool call parsing errors.
36
- - **Custom Tracking Headers:** RTK and associated tracing proxies inject headers (`x-rtk-*`, `traceparent`, `x-optimizer-id`) that some strict upstream endpoints reject if not cleanly forwarded.
37
-
38
- ### 3. Ponytail (`DietrichGebert/ponytail`)
39
- - **Mechanism:** A behavioral prompt engineering plugin/ruleset that injects extreme conciseness instructions ("write one line, it works, YAGNI") into agent system prompts across 20+ coding tools.
40
- - **Critical Failure Points:**
41
- - **Premature Execution without Reasoning:** By commanding the model to be maximally brief and avoid planning, reasoning models are discouraged from spending thinking tokens. The model outputs untested single-liners that often fail type checks and test suites.
42
- - **System Prompt Prefix Invalidation:** Injected rules alter the leading system prompt bytes, busting provider prompt caches unless carefully aligned.
43
-
44
- ---
45
-
46
- ## The Healer Engine: How LLM Switcher Protects the Workflow
47
-
48
- LLM Switcher sits between the optimizer tool and the upstream LLM:
49
-
50
- ```
51
- [CLI Agent] ──> [Optimizer: Headroom / RTK] ──> [LLM Switcher :3456] ──> [Upstream / 9Router]
52
- │
53
- ├── 1. Heal Orphaned tool_results
54
- ├── 2. Merge Consecutive Turns
55
- ├── 3. Restore Stripped Thinking
56
- └── 4. Enforce 1M Context
57
- ```
58
-
59
- ### Protection Matrix: Before vs. After
60
-
61
- | Scenario | Direct to Upstream (Without Switcher) | Through LLM Switcher (Healer Engine) |
62
- |---|---|---|
63
- | **Orphaned `tool_result` turn** | ❌ **HTTP 400 Crash**: `tool_use_id does not correspond to any tool_use` | ✅ **HTTP 200 OK**: Heals orphaned result into contextual text block `[Tool Result (id)]: ...` |
64
- | **Consecutive `user` turns** | ❌ **HTTP 400 Crash**: `roles must alternate` | ✅ **HTTP 200 OK**: Merges consecutive turns into a single valid turn seamlessly |
65
- | **Stripped `thinking` parameters** | ⚠️ **Degraded AI**: Reasoning disabled, model outputs shallow single-liners | ✅ **HTTP 200 OK**: Detects reasoning models and automatically restores safe thinking budget |
66
- | **Orphaned `tool` role in Chat API** | ❌ **HTTP 400 Crash**: `tool role must respond to tool_calls` | ✅ **HTTP 200 OK**: Converts orphaned tool message into user context |
67
- | **Custom tracking headers** | ⚠️ Connection dropped / unrecognized header warnings | ✅ **HTTP 200 OK**: Cleanly passes through `traceparent`, `x-request-id`, `x-rtk-*` |
68
-
69
- ---
70
-
71
- ## Test Methodology & Verification Suite
72
-
73
- We created an automated verification suite in [`tests/live-optimizer-interop.mjs`](../tests/live-optimizer-interop.mjs) that systematically replicates the failure modes of each tool:
74
-
75
- ### Running the Test Suite
76
- ```bash
77
- node tests/live-optimizer-interop.mjs
78
- ```
79
-
80
- ### Live Test Results
81
- ```text
82
- ================================================================
83
- LLM SWITCHER — TOKEN OPTIMIZER INTEROPERABILITY TEST SUITE
84
- Simulating failure modes from Headroom, RTK, and Ponytail
85
- ================================================================
86
-
87
- [TEST] Headroom Simulation: Orphaned tool_result turn... PASS (8840ms)
88
- ↳ Healed orphaned tool_result. Response HTTP 200: "It looks like you've shared a fragment of context ..."
89
- [TEST] Headroom Simulation: Consecutive User turns (Role alternation violation)... PASS (2683ms)
90
- ↳ Merged consecutive turns seamlessly. Stop reason: end_turn
91
- [TEST] Thinking Guard: Restoring stripped thinking parameter on reasoning models... PASS (5372ms)
92
- ↳ Automatically restored thinking: thinking_delta=true, signature_delta=true, text_delta=true
93
- [TEST] RTK Intermediary: Custom headers and traceparent passthrough... PASS (2453ms)
94
- ↳ Headers accepted cleanly with HTTP 200 OK
95
- [TEST] OpenAI Chat Healer: Orphaned role tool without preceding assistant tool_calls... PASS (1561ms)
96
- ↳ Chat Healer rescued orphaned tool role. Stop reason: length
97
-
98
- ================================================================
99
- TEST RESULTS: 5 PASSED / 0 FAILED
100
- ================================================================
101
- ```
102
-
103
- ---
104
-
105
- ## Recommended User Setup
106
-
107
- For developers using prompt optimization tools:
108
- 1. Keep the optimizer installed in your CLI tool as usual.
109
- 2. In the optimizer's configuration (e.g. `headroom.yaml` or RTK upstream settings), set the upstream target URL to **LLM Switcher** (`http://127.0.0.1:3456`).
110
- 3. Enjoy prompt compression savings without worrying about broken conversation graphs, HTTP 400 crashes, or lost reasoning depth.
1
+ # Token Optimizer Interoperability & Failure Mode Report
2
+
3
+ **How LLM Switcher acts as the protective outermost edge gateway for aggressive prompt/token optimizers (Headroom, RTK, Ponytail).**
4
+
5
+ ---
6
+
7
+ ## Executive Summary
8
+
9
+ Third-party prompt optimizers and token compressors — such as **Headroom**, **RTK (Rust Token Killer)**, and **Ponytail** — attempt to reduce LLM input tokens by aggressively pruning message history, truncating command stdout, or forcing extreme prompt brevity.
10
+
11
+ While these tools can reduce raw token counts in simple scenarios, **they frequently break complex agentic coding workflows** by corrupting message graphs, orphaning tool calls, and stripping reasoning parameters. When these pruned payloads hit upstream APIs directly (such as Anthropic, OpenAI, or 9Router), the provider immediately throws fatal `HTTP 400 Bad Request` errors or severely degrades reasoning depth.
12
+
13
+ **LLM Switcher solves this by acting as the outermost edge gatekeeper (`127.0.0.1:3456`).** It intercepts the pruned payload before it leaves your machine, runs its built-in **Healer Engine** to repair message graphs and restore reasoning parameters, unlocks 1M context windows, and safely converts the protocol to your upstream provider.
14
+
15
+ ---
16
+
17
+ ## Tool Breakdown: What They Do & How They Break Payloads
18
+
19
+ ### 1. Headroom (`headroomlabs-ai/headroom`)
20
+ - **Mechanism:** Runs as a local proxy on `:8787` (or wraps CLI agents). Compresses conversation history, RAG chunks, and tool outputs using SmartCrusher (JSON), CodeCompressor (AST), and Kompress-v2-base. Also attempts "effort routing" to dial down thinking budgets.
21
+ - **Critical Failure Points:**
22
+ - **Orphaned `tool_result` blocks:** When pruning historical turns, Headroom often discards the `assistant` turn containing a `tool_use`, while retaining the subsequent `user` turn containing the `tool_result`. Anthropic's API strictly validates tool use IDs and crashes with:
23
+ ```
24
+ HTTP 400 invalid_request_error: "tool_use_id 'xxx' does not correspond to any tool_use"
25
+ ```
26
+ - **Consecutive `user` turns:** Dropping intermediary assistant turns causes multiple user messages to sit adjacent to each other. Anthropic strictly throws:
27
+ ```
28
+ HTTP 400 invalid_request_error: "roles must alternate between 'user' and 'assistant'"
29
+ ```
30
+ - **Reasoning Suppression:** Its "effort routing" dials down `thinking.budget_tokens` on routine tool turns. On complex models (Claude Opus, Gemini Flash), this prevents the model from formulating multi-step reasoning before acting.
31
+
32
+ ### 2. RTK (`rtk-ai/rtk` - Rust Token Killer)
33
+ - **Mechanism:** A single Rust binary that hooks into shell tool execution (e.g. `PreToolUse` in Claude Code / Cursor) and rewrites CLI commands (`git`, `ls`, `cat`, `grep`, `pytest`) to filter out noise, truncate lines, and inject recall tokens (`[full output: rtk recall xxx]`).
34
+ - **Critical Failure Points:**
35
+ - **Corrupted Structural Data:** When an agent invokes a tool expecting machine-readable JSON or exact AST formatting, RTK's heuristic summaries can alter structural delimiters, causing downstream tool call parsing errors.
36
+ - **Custom Tracking Headers:** RTK and associated tracing proxies inject headers (`x-rtk-*`, `traceparent`, `x-optimizer-id`) that some strict upstream endpoints reject if not cleanly forwarded.
37
+
38
+ ### 3. Ponytail (`DietrichGebert/ponytail`)
39
+ - **Mechanism:** A behavioral prompt engineering plugin/ruleset that injects extreme conciseness instructions ("write one line, it works, YAGNI") into agent system prompts across 20+ coding tools.
40
+ - **Critical Failure Points:**
41
+ - **Premature Execution without Reasoning:** By commanding the model to be maximally brief and avoid planning, reasoning models are discouraged from spending thinking tokens. The model outputs untested single-liners that often fail type checks and test suites.
42
+ - **System Prompt Prefix Invalidation:** Injected rules alter the leading system prompt bytes, busting provider prompt caches unless carefully aligned.
43
+
44
+ ---
45
+
46
+ ## The Healer Engine: How LLM Switcher Protects the Workflow
47
+
48
+ LLM Switcher sits between the optimizer tool and the upstream LLM:
49
+
50
+ ```
51
+ [CLI Agent] ──> [Optimizer: Headroom / RTK] ──> [LLM Switcher :3456] ──> [Upstream / 9Router]
52
+ │
53
+ ├── 1. Heal Orphaned tool_results
54
+ ├── 2. Merge Consecutive Turns
55
+ ├── 3. Restore Stripped Thinking
56
+ └── 4. Enforce 1M Context
57
+ ```
58
+
59
+ ### Protection Matrix: Before vs. After
60
+
61
+ | Scenario | Direct to Upstream (Without Switcher) | Through LLM Switcher (Healer Engine) |
62
+ |---|---|---|
63
+ | **Orphaned `tool_result` turn** | ❌ **HTTP 400 Crash**: `tool_use_id does not correspond to any tool_use` | ✅ **HTTP 200 OK**: Heals orphaned result into contextual text block `[Tool Result (id)]: ...` |
64
+ | **Consecutive `user` turns** | ❌ **HTTP 400 Crash**: `roles must alternate` | ✅ **HTTP 200 OK**: Merges consecutive turns into a single valid turn seamlessly |
65
+ | **Stripped `thinking` parameters** | ⚠️ **Degraded AI**: Reasoning disabled, model outputs shallow single-liners | ✅ **HTTP 200 OK**: Detects reasoning models and automatically restores safe thinking budget |
66
+ | **Orphaned `tool` role in Chat API** | ❌ **HTTP 400 Crash**: `tool role must respond to tool_calls` | ✅ **HTTP 200 OK**: Converts orphaned tool message into user context |
67
+ | **Custom tracking headers** | ⚠️ Connection dropped / unrecognized header warnings | ✅ **HTTP 200 OK**: Cleanly passes through `traceparent`, `x-request-id`, `x-rtk-*` |
68
+
69
+ ---
70
+
71
+ ## Test Methodology & Verification Suite
72
+
73
+ We created an automated verification suite in [`tests/live-optimizer-interop.mjs`](../tests/live-optimizer-interop.mjs) that systematically replicates the failure modes of each tool:
74
+
75
+ ### Running the Test Suite
76
+ ```bash
77
+ node tests/live-optimizer-interop.mjs
78
+ ```
79
+
80
+ ### Live Test Results
81
+ ```text
82
+ ================================================================
83
+ LLM SWITCHER — TOKEN OPTIMIZER INTEROPERABILITY TEST SUITE
84
+ Simulating failure modes from Headroom, RTK, and Ponytail
85
+ ================================================================
86
+
87
+ [TEST] Headroom Simulation: Orphaned tool_result turn... PASS (8840ms)
88
+ ↳ Healed orphaned tool_result. Response HTTP 200: "It looks like you've shared a fragment of context ..."
89
+ [TEST] Headroom Simulation: Consecutive User turns (Role alternation violation)... PASS (2683ms)
90
+ ↳ Merged consecutive turns seamlessly. Stop reason: end_turn
91
+ [TEST] Thinking Guard: Restoring stripped thinking parameter on reasoning models... PASS (5372ms)
92
+ ↳ Automatically restored thinking: thinking_delta=true, signature_delta=true, text_delta=true
93
+ [TEST] RTK Intermediary: Custom headers and traceparent passthrough... PASS (2453ms)
94
+ ↳ Headers accepted cleanly with HTTP 200 OK
95
+ [TEST] OpenAI Chat Healer: Orphaned role tool without preceding assistant tool_calls... PASS (1561ms)
96
+ ↳ Chat Healer rescued orphaned tool role. Stop reason: length
97
+
98
+ ================================================================
99
+ TEST RESULTS: 5 PASSED / 0 FAILED
100
+ ================================================================
101
+ ```
102
+
103
+ ---
104
+
105
+ ## Recommended User Setup
106
+
107
+ For developers using prompt optimization tools:
108
+ 1. Keep the optimizer installed in your CLI tool as usual.
109
+ 2. In the optimizer's configuration (e.g. `headroom.yaml` or RTK upstream settings), set the upstream target URL to **LLM Switcher** (`http://127.0.0.1:3456`).
110
+ 3. Enjoy prompt compression savings without worrying about broken conversation graphs, HTTP 400 crashes, or lost reasoning depth.