xithead 1.0.0 → 1.1.0

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 (3) hide show
  1. package/README.md +169 -91
  2. package/npm/bin/xithead.js +192 -43
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,161 +1,239 @@
1
1
  <div align="center">
2
- <img src="https://cdn.xtream-itsolutions.com/u/logo.png" alt="Xtream-ITSolutions UG" width="200" />
2
+ <img src="https://cdn.xtream-itsolutions.com/u/logo.png" alt="Xtream-ITSolutions UG" width="160" />
3
3
  <h1>xithead</h1>
4
- <p><strong>Aggressive Claude Context Optimizer</strong></p>
5
- <p>Cut your Claude API costs by 50–95% with zero accuracy loss.</p>
4
+ <p><strong>Aggressive Claude Context Optimizer — bis zu 95% Token-Einsparung</strong></p>
6
5
  <p>
7
- <a href="https://pypi.org/project/xithead/"><img src="https://img.shields.io/pypi/v/xithead?color=blue&label=PyPI" alt="PyPI" /></a>
8
- <a href="https://www.npmjs.com/package/xithead"><img src="https://img.shields.io/npm/v/xithead?color=red&label=npm" alt="npm" /></a>
9
- <a href="https://discord.gg/xtream-itsolutions"><img src="https://img.shields.io/discord/1234567890?color=7289da&label=Discord&logo=discord" alt="Discord" /></a>
10
- <a href="LICENSE"><img src="https://img.shields.io/badge/License-Apache%202.0-green" alt="License" /></a>
6
+ <a href="https://pypi.org/project/xithead/"><img src="https://img.shields.io/pypi/v/xithead?color=00d4ff&label=PyPI&style=flat-square" alt="PyPI" /></a>
7
+ <a href="https://www.npmjs.com/package/xithead"><img src="https://img.shields.io/npm/v/xithead?color=e879f9&label=npm&style=flat-square" alt="npm" /></a>
8
+ <a href="https://discord.gg/xtream-itsolutions"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat-square&logo=discord&logoColor=white" alt="Discord" /></a>
9
+ <a href="LICENSE"><img src="https://img.shields.io/badge/License-Apache%202.0-10b981?style=flat-square" alt="License" /></a>
11
10
  </p>
12
11
  <p>
13
- <a href="https://discord.gg/xtream-itsolutions">Join our Discord</a> ·
14
- <a href="https://github.com/xtream-itsolutions/headroom/issues">Report Bug</a> ·
15
- <a href="https://github.com/xtream-itsolutions/headroom/issues">Request Feature</a>
12
+ <a href="https://discord.gg/xtream-itsolutions">💬 Discord</a> ·
13
+ <a href="https://github.com/xtream-itsolutions/headroom/issues">🐛 Bug melden</a> ·
14
+ <a href="https://github.com/xtream-itsolutions/headroom/issues">✨ Feature anfragen</a>
16
15
  </p>
17
16
  </div>
18
17
 
19
18
  ---
20
19
 
21
- ## What is xithead?
20
+ ## Was ist xithead?
22
21
 
23
- **xithead** is an open-source context optimization layer built specifically for Claude.
24
- It sits between your application and the Claude API, aggressively compressing prompts and caching responses — so you send fewer tokens and pay less.
22
+ **xithead** ist ein Claude-spezifischer Context Optimizer von **Xtream-ITSolutions UG**.
23
+ Er sitzt zwischen deiner App und der Claude API, komprimiert Prompts aggressiv und cached Antworten — du sendest weniger Tokens und zahlst deutlich weniger.
25
24
 
26
- Built and maintained by **Xtream-ITSolutions UG**.
25
+ - **Drop-in Proxy** — keine Code-Änderungen nötig
26
+ - **Immer Sonnet 4.6** — das beste Modell, automatisch gepinnt
27
+ - **Ultra-Modus standardmäßig** — 50–95% Einsparung ab dem ersten Request
28
+ - **Live Dashboard** — Einsparungen in Echtzeit auf `localhost:8787/dashboard`
27
29
 
28
- ## Key Features
30
+ ---
31
+
32
+ ## Schnellstart — Windows (empfohlen)
33
+
34
+ ```powershell
35
+ # PowerShell als Administrator, einmalig:
36
+ Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
37
+ iex (irm https://raw.githubusercontent.com/xtream-itsolutions/headroom/main/headroom.ps1)
38
+ ```
29
39
 
30
- | Feature | Description | Savings |
31
- |---------|-------------|---------|
32
- | 🔥 **Prompt Caching** | Auto-injects Anthropic `cache_control` markers | Up to 90% on cached tokens |
33
- | 🗜️ **Context Compression** | Removes redundancy, deduplicates messages | 30–60% fewer tokens |
34
- | 💾 **Smart Caching** | Multi-layer cache (memory + SQLite) | Skip repeat API calls |
35
- | 🎯 **System Prompt Optimizer** | Compresses verbose system prompts | 10–40% savings |
36
- | 📊 **Real-time Dashboard** | Live token & cost tracking via proxy | Full visibility |
37
- | 🔌 **Drop-in Proxy** | Zero code changes needed | Works with any client |
40
+ Danach neues Terminal öffnen und loslegen:
38
41
 
39
- ## Quick Start
42
+ ```powershell
43
+ xithead # Claude starten — ultra-aggressiv, 50-95% Einsparung
44
+ xithead-proxy # Proxy + Dashboard auf http://localhost:8787/dashboard
45
+ xithead-stats # Einsparungen anzeigen
46
+ xithead-update # xithead aktualisieren
47
+ xithead-help # Alle Befehle
48
+ ```
49
+
50
+ > **VS Code:** Terminal mit `Strg+\`` öffnen, PowerShell wählen, `xithead` eingeben — fertig.
51
+
52
+ ---
53
+
54
+ ## Installation
40
55
 
41
56
  ### Python
42
57
 
43
58
  ```bash
44
- pip install xithead
59
+ pip install xithead # nur CLI + Optimizer
60
+ pip install "xithead[proxy]" # + Proxy + Dashboard (empfohlen)
61
+ ```
62
+
63
+ ### npm / Node.js
64
+
65
+ ```bash
66
+ npm install -g xithead
67
+ ```
68
+
69
+ ---
70
+
71
+ ## CLI Befehle
72
+
73
+ ```bash
74
+ xithead proxy # Proxy starten (Port 8787) + Dashboard
75
+ xithead optimize "prompt" # Prompt optimieren und Einsparung zeigen
76
+ xithead stats # Session-Statistiken
77
+ xithead cache stats # Cache-Statistiken
78
+ xithead cache clear # Cache leeren
79
+ xithead model set claude-sonnet-4-6 # Modell setzen
80
+ xithead model show # Aktuelles Modell anzeigen
45
81
  ```
46
82
 
83
+ ---
84
+
85
+ ## Features
86
+
87
+ | Feature | Beschreibung | Einsparung |
88
+ |---------|-------------|------------|
89
+ | 🔥 **Prompt Caching** | `cache_control`-Marker automatisch injizieren | Bis 90% auf Cache-Hits |
90
+ | 🗜️ **Context Compression** | Redundanz entfernen, Nachrichten deduplizieren | 30–60% weniger Tokens |
91
+ | 💾 **Multi-Layer Cache** | RAM + SQLite, SHA-256 Keys, TTL | Wiederholte Calls gratis |
92
+ | ✂️ **Context Trim** | Alten Context trimmen (verhindert 400-Fehler) | Spart Input-Tokens |
93
+ | 📉 **Verbosity Reduction** | System-Prompts komprimieren | 10–40% Einsparung |
94
+ | 📊 **Live Dashboard** | Token- & Kosten-Tracking in Echtzeit | Volle Transparenz |
95
+ | 🔌 **Drop-in Proxy** | Keine Code-Änderungen | Funktioniert mit jedem Client |
96
+
97
+ ---
98
+
99
+ ## Einsparungs-Beispiele
100
+
101
+ | Anwendungsfall | Original | Nach xithead | Gespart |
102
+ |----------------|----------|--------------|---------|
103
+ | Code-Review (wiederholter Kontext) | 50.000 Tokens | 4.000 Tokens | **92%** |
104
+ | Chat mit langem System-Prompt | 10.000 Tokens | 2.000 Tokens | **80%** |
105
+ | Agentischer Loop (Tool-Ergebnisse) | 100.000 Tokens | 25.000 Tokens | **75%** |
106
+ | Einfaches Q&A | 500 Tokens | 400 Tokens | ~20% |
107
+
108
+ ---
109
+
110
+ ## Python API
111
+
47
112
  ```python
48
113
  from xithead import optimize_for_claude
49
114
 
50
- messages = [{"role": "user", "content": "Your long prompt here..."}]
115
+ messages = [{"role": "user", "content": "Sehr langer Prompt hier..."}]
51
116
  result = optimize_for_claude(messages, model="claude-sonnet-4-6")
52
117
 
53
- # Use result.messages in your Anthropic API call
54
- print(f"Saved {result.tokens_saved} tokens (${result.cost_saved_usd:.4f})")
118
+ print(f"Tokens gespart: {result.tokens_saved}")
119
+ print(f"Kosten gespart: ${result.cost_saved_usd:.4f}")
120
+ print(f"Kompression: {result.compression_ratio:.1%}")
121
+ print(f"Cache-Hit: {result.cache_hit}")
122
+
123
+ # Optimierte messages an Anthropic API übergeben:
124
+ # client.messages.create(messages=result.messages, ...)
55
125
  ```
56
126
 
57
- ### Node.js / npm
127
+ ### Konfiguration
58
128
 
59
- ```bash
60
- npm install xithead
129
+ ```python
130
+ from xithead.claude_optimizer import ClaudeOptimizer, ClaudeOptimizerConfig
131
+
132
+ config = ClaudeOptimizerConfig(
133
+ enable_prompt_caching=True,
134
+ enable_dedup=True,
135
+ enable_verbosity_reduction=True,
136
+ enable_context_trim=True,
137
+ max_context_tokens=180_000,
138
+ cache_ttl_seconds=86400,
139
+ )
140
+ optimizer = ClaudeOptimizer(config)
141
+ result = optimizer.optimize(messages, system="Du bist ein hilfreicher Assistent.", model="claude-sonnet-4-6")
61
142
  ```
62
143
 
144
+ ---
145
+
146
+ ## Node.js / JavaScript API
147
+
63
148
  ```javascript
64
- const { optimize, createOptimizedClient } = require('xithead');
149
+ const { optimize, createOptimizedClient, injectCacheControl } = require('xithead');
65
150
  const Anthropic = require('@anthropic-ai/sdk');
66
151
 
67
- // Option 1: Manual optimization
152
+ // Option 1: Manuell optimieren
68
153
  const result = optimize({ messages, system, model: 'claude-sonnet-4-6' });
154
+ console.log(result.tokensSaved, result.costSavedUsd);
69
155
 
70
- // Option 2: Wrapped client (auto-optimizes every call)
156
+ // Option 2: Wrapped Client (optimiert automatisch jeden Call)
71
157
  const client = new Anthropic();
72
158
  const xitClient = createOptimizedClient(client);
73
159
  const response = await xitClient.messages.create({
74
160
  model: 'claude-sonnet-4-6',
75
161
  max_tokens: 1024,
76
- messages: [{ role: 'user', content: 'Hello!' }],
162
+ messages: [{ role: 'user', content: 'Hallo!' }],
77
163
  });
78
- console.log(xitClient.getStats()); // { tokensSaved: 42, costSavedUsd: 0.000126, ... }
164
+ console.log(xitClient.getStats());
79
165
  ```
80
166
 
81
- ### Proxy (Zero Code Changes)
167
+ ---
168
+
169
+ ## Proxy-Modus (Zero Code Changes)
82
170
 
83
171
  ```bash
172
+ # Proxy starten
84
173
  xithead proxy --port 8787
85
- # Now point your Claude client to http://localhost:8787
86
- # All requests are automatically optimized
87
- ```
88
174
 
89
- ## How it Works
175
+ # Dashboard öffnen
176
+ # → http://localhost:8787/dashboard
90
177
 
91
- ```
92
- Your App → xithead (local) → Optimized Request → Claude API
93
- │
94
- ├─ Cache lookup (skip API call if cached)
95
- ├─ Message deduplication
96
- ├─ System prompt compression
97
- ├─ cache_control marker injection
98
- ├─ Context window trim (prevent 400 errors)
99
- └─ Token/cost tracking
178
+ # Deinen Claude Client auf den Proxy zeigen lassen:
179
+ export ANTHROPIC_BASE_URL=http://localhost:8787
180
+ claude # oder jede andere App
100
181
  ```
101
182
 
102
- ## CLI Commands
103
-
104
- ```bash
105
- xithead proxy [--port 8787] [--host 127.0.0.1] # Start proxy
106
- xithead optimize "your prompt" # Optimize a prompt
107
- xithead stats # Show session stats
108
- xithead cache clear # Clear local cache
109
- xithead cache stats # Cache statistics
110
- xithead memory list # List stored memories
183
+ In PowerShell:
184
+ ```powershell
185
+ $env:ANTHROPIC_BASE_URL = "http://localhost:8787"
186
+ claude
111
187
  ```
112
188
 
113
- ## Savings Examples
189
+ ---
114
190
 
115
- | Use Case | Original Tokens | After xithead | Saved |
116
- |----------|----------------|----------------|-------|
117
- | Code review (repeated context) | 50,000 | 8,000 | **84%** |
118
- | Chat with long system prompt | 10,000 | 2,500 | **75%** |
119
- | Agentic loop (tool results) | 100,000 | 35,000 | **65%** |
120
- | Simple Q&A | 500 | 450 | ~10% |
191
+ ## Wie es funktioniert
121
192
 
122
- ## Configuration
193
+ ```
194
+ Deine App → xithead Proxy → Optimierter Request → Claude API
195
+ │
196
+ ├─ Cache-Lookup (API-Call überspringen wenn gecacht)
197
+ ├─ Nachrichten-Deduplizierung
198
+ ├─ System-Prompt Kompression
199
+ ├─ cache_control Marker injizieren
200
+ ├─ Context-Window Trim (verhindert 400-Fehler)
201
+ └─ Token/Kosten-Tracking
202
+ ```
123
203
 
124
- ```python
125
- from xithead.claude_optimizer import ClaudeOptimizer, ClaudeOptimizerConfig
204
+ ---
126
205
 
127
- config = ClaudeOptimizerConfig(
128
- enable_prompt_caching=True, # Inject cache_control markers
129
- enable_dedup=True, # Remove duplicate messages
130
- enable_verbosity_reduction=True, # Compress system prompts
131
- enable_context_trim=True, # Trim old context
132
- max_context_tokens=180_000, # Claude max context
133
- cache_ttl_seconds=86400, # 24h cache TTL
134
- )
135
- optimizer = ClaudeOptimizer(config)
136
- result = optimizer.optimize(messages, system="You are a helpful assistant.", model="claude-sonnet-4-6")
137
- ```
206
+ ## Umgebungsvariablen
138
207
 
139
- ## Architecture
208
+ | Variable | Standardwert | Beschreibung |
209
+ |----------|-------------|--------------|
210
+ | `XITHEAD_MODEL` | `claude-sonnet-4-6` | Claude-Modell |
211
+ | `XITHEAD_ENABLE_CACHE_CONTROL` | `1` | Prompt-Caching aktivieren |
212
+ | `XITHEAD_ENABLE_DEDUP` | `1` | Nachrichten-Dedup aktivieren |
213
+ | `XITHEAD_ENABLE_CONTEXT_TRIM` | `1` | Context-Trim aktivieren |
214
+ | `HEADROOM_COMPRESSION_RATIO_TARGET` | `0.3` | Kompressions-Ziel (0.3 = 70%) |
215
+ | `HEADROOM_STRENGTH` | `aggressive` | Kompressions-Stärke |
216
+ | `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | `2048` | Max. Output-Tokens |
140
217
 
141
- xithead is built on top of the headroom context optimization engine, with additional Claude-specific optimizations:
218
+ ---
142
219
 
143
- - **xithead layer**: Claude-specific cache_control injection, SQLite caching, CLI
144
- - **headroom engine**: SmartCrusher (JSON), CodeCompressor (AST), Kompress (ML), semantic caching
145
- - **Rust crates**: Native proxy (Axum), fast tokenization, embeddings
220
+ ## Beitragen
146
221
 
147
- ## Contributing
222
+ Wir freuen uns über Beiträge! Öffne ein Issue oder Pull Request.
148
223
 
149
- We welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md).
224
+ Tritt unserer Community bei: [discord.gg/xtream-itsolutions](https://discord.gg/xtream-itsolutions)
150
225
 
151
- Join the community: [discord.gg/xtream-itsolutions](https://discord.gg/xtream-itsolutions)
226
+ ---
152
227
 
153
- ## License
228
+ ## Lizenz
154
229
 
155
- Apache 2.0 — see [LICENSE](LICENSE).
230
+ Apache 2.0 — siehe [LICENSE](LICENSE).
156
231
 
157
232
  ---
158
233
 
159
234
  <div align="center">
160
- <sub>Built with ❤️ by <a href="https://xtream-itsolutions.com">Xtream-ITSolutions UG</a></sub>
235
+ <p>Made with ❤️ by <a href="https://xtream-itsolutions.com"><strong>Xtream-ITSolutions UG</strong></a></p>
236
+ <a href="https://discord.gg/xtream-itsolutions">
237
+ <img src="https://img.shields.io/badge/Discord-Community_beitreten-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Discord" />
238
+ </a>
161
239
  </div>
@@ -1,58 +1,207 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * xithead CLI (Node.js wrapper)
4
- * by Xtream-ITSolutions UG
3
+ * xithead CLI — Claude Context Optimizer
4
+ * by Xtream-ITSolutions UG | discord.gg/xtream-itsolutions
5
5
  */
6
6
  'use strict';
7
7
 
8
- const { execSync, spawnSync } = require('child_process');
9
- const path = require('path');
8
+ const { spawnSync, spawn } = require('child_process');
9
+ const http = require('http');
10
10
 
11
11
  const args = process.argv.slice(2);
12
+ const PROXY_PORT = 8787;
13
+ const PROXY_URL = `http://localhost:${PROXY_PORT}`;
12
14
 
13
- // Try Python xithead first
14
- function tryPython() {
15
- const result = spawnSync('xithead', args, { stdio: 'inherit', shell: false });
16
- if (result.status === 0) process.exit(0);
17
- if (result.error && result.error.code === 'ENOENT') return false;
18
- process.exit(result.status || 1);
15
+ // ── Helpers ──────────────────────────────────────────────────────────────────
16
+
17
+ function findPython() {
18
+ for (const cmd of ['python', 'python3', 'py']) {
19
+ const r = spawnSync(cmd, ['--version'], { stdio: 'pipe' });
20
+ if (r.status === 0) return cmd;
21
+ }
22
+ return null;
23
+ }
24
+
25
+ function proxyAlive() {
26
+ return new Promise(resolve => {
27
+ const req = http.get(`${PROXY_URL}/api/stats`, { timeout: 1500 }, res => {
28
+ resolve(res.statusCode === 200);
29
+ });
30
+ req.on('error', () => resolve(false));
31
+ req.on('timeout', () => { req.destroy(); resolve(false); });
32
+ });
33
+ }
34
+
35
+ function startProxy(py) {
36
+ // Start Python proxy in background (detached, no output)
37
+ const child = spawn(py, ['-m', 'xithead.cli.main', 'proxy', '--port', String(PROXY_PORT)], {
38
+ detached: true,
39
+ stdio: 'ignore',
40
+ });
41
+ child.unref();
42
+ }
43
+
44
+ function waitForProxy(timeoutMs = 8000) {
45
+ return new Promise(async resolve => {
46
+ const deadline = Date.now() + timeoutMs;
47
+ while (Date.now() < deadline) {
48
+ if (await proxyAlive()) return resolve(true);
49
+ await new Promise(r => setTimeout(r, 400));
50
+ }
51
+ resolve(false);
52
+ });
53
+ }
54
+
55
+ function hasPythonXithead(py) {
56
+ const r = spawnSync(py, ['-c', 'import xithead'], { stdio: 'pipe' });
57
+ return r.status === 0;
58
+ }
59
+
60
+ // ── Commands ──────────────────────────────────────────────────────────────────
61
+
62
+ function showBanner(proxyOk) {
63
+ const c = {
64
+ cyan: '\x1b[36m',
65
+ green: '\x1b[32m',
66
+ magenta: '\x1b[35m',
67
+ gray: '\x1b[90m',
68
+ yellow: '\x1b[33m',
69
+ reset: '\x1b[0m',
70
+ };
71
+ console.log('');
72
+ console.log(`${c.cyan} ╔═══════════════════════════════════════════╗${c.reset}`);
73
+ console.log(`${c.cyan} ║ Xtream-ITSolutions — xithead v1.0.0 ║${c.reset}`);
74
+ console.log(`${c.cyan} ║ discord.gg/xtream-itsolutions ║${c.reset}`);
75
+ console.log(`${c.cyan} ╠═══════════════════════════════════════════╣${c.reset}`);
76
+ console.log(`${c.green} ║ Modell: claude-sonnet-4-6 ║${c.reset}`);
77
+ console.log(`${c.magenta} ║ Modus: Ultra-Aggressiv (50-95%) ║${c.reset}`);
78
+ if (proxyOk) {
79
+ console.log(`${c.green} ║ Proxy: http://localhost:${PROXY_PORT}/v1 ✓ ║${c.reset}`);
80
+ } else {
81
+ console.log(`${c.yellow} ║ Proxy: nicht erreichbar — direkter API ║${c.reset}`);
82
+ }
83
+ console.log(`${c.cyan} ╚═══════════════════════════════════════════╝${c.reset}`);
84
+ console.log('');
19
85
  }
20
86
 
21
- // Fallback: show help
22
87
  function showHelp() {
23
- console.log(`
24
- ██╗ ██╗██╗████████╗██╗ ██╗███████╗ █████╗ ██████╗
25
- ╚██╗██╔╝██║╚══██╔══╝██║ ██║██╔════╝██╔══██╗██╔══██╗
26
- ╚███╔╝ ██║ ██║ ███████║█████╗ ███████║██║ ██║
27
- ██╔██╗ ██║ ██║ ██╔══██║██╔══╝ ██╔══██║██║ ██║
28
- ██╔╝ ██╗██║ ██║ ██║ ██║███████╗██║ ██║██████╔╝
29
- ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝
30
-
31
- xithead v1.0.0 - Claude Context Optimizer
32
- by Xtream-ITSolutions UG
33
- discord.gg/xtream-itsolutions
34
-
35
- Usage:
36
- xithead proxy [--port 8787] Start optimization proxy
37
- xithead stats Show savings statistics
38
- xithead cache clear Clear local cache
39
- xithead optimize <prompt> Optimize a single prompt
40
-
41
- JS API:
42
- const { optimize, createOptimizedClient } = require('xithead');
43
- const result = optimize({ messages, system, model: 'claude-sonnet-4-6' });
44
-
45
- Install Python CLI for full features:
46
- pip install xithead
47
- `);
48
- process.exit(0);
49
- }
50
-
51
- if (!tryPython()) {
52
- if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
88
+ const c = { cyan: '\x1b[36m', green: '\x1b[32m', gray: '\x1b[90m', reset: '\x1b[0m' };
89
+ console.log('');
90
+ console.log(`${c.cyan} xithead — Claude Context Optimizer${c.reset}`);
91
+ console.log(`${c.gray} by Xtream-ITSolutions UG${c.reset}`);
92
+ console.log('');
93
+ console.log(`${c.green} xithead${c.reset} Claude starten (Proxy auto, 50-95% Einsparung)`);
94
+ console.log(`${c.green} xithead proxy${c.reset} Proxy + Dashboard starten`);
95
+ console.log(`${c.green} xithead stats${c.reset} Token-Einsparungen anzeigen`);
96
+ console.log(`${c.green} xithead help${c.reset} Diese Hilfe`);
97
+ console.log('');
98
+ console.log(`${c.gray} Dashboard: http://localhost:${PROXY_PORT}/dashboard${c.reset}`);
99
+ console.log(`${c.gray} Discord: discord.gg/xtream-itsolutions${c.reset}`);
100
+ console.log('');
101
+ }
102
+
103
+ async function showStats() {
104
+ return new Promise(resolve => {
105
+ const req = http.get(`${PROXY_URL}/api/stats`, { timeout: 3000 }, res => {
106
+ let body = '';
107
+ res.on('data', d => body += d);
108
+ res.on('end', () => {
109
+ try {
110
+ const s = JSON.parse(body);
111
+ const c = { cyan: '\x1b[36m', green: '\x1b[32m', gray: '\x1b[90m', reset: '\x1b[0m' };
112
+ console.log('');
113
+ console.log(`${c.cyan} ┌─────────────────────────────────────┐${c.reset}`);
114
+ console.log(`${c.cyan} │ xithead Statistiken │${c.reset}`);
115
+ console.log(`${c.cyan} ├─────────────────────────────────────┤${c.reset}`);
116
+ console.log(`${c.reset} │ Requests: ${String(s.session.requests).padEnd(19)}│${c.reset}`);
117
+ console.log(`${c.green} │ Tokens gespart: ${String(s.session.tokens_saved).padEnd(19)}│${c.reset}`);
118
+ console.log(`${c.green} │ Kosten gespart: $${String((s.session.cost_saved_usd||0).toFixed(4)).padEnd(18)}│${c.reset}`);
119
+ console.log(`${c.cyan} │ Cache-Hit-Rate: ${String(((s.session.cache_hit_rate||0)*100).toFixed(1)+'%').padEnd(19)}│${c.reset}`);
120
+ console.log(`${c.gray} │ Modell: ${String(s.model||'').padEnd(19)}│${c.reset}`);
121
+ console.log(`${c.cyan} └─────────────────────────────────────┘${c.reset}`);
122
+ } catch { console.log(' [xithead] Konnte Stats nicht parsen.'); }
123
+ resolve();
124
+ });
125
+ });
126
+ req.on('error', () => {
127
+ console.log('\x1b[33m [xithead] Proxy nicht erreichbar — starte mit: xithead\x1b[0m');
128
+ resolve();
129
+ });
130
+ req.on('timeout', () => { req.destroy(); resolve(); });
131
+ });
132
+ }
133
+
134
+ // ── Main ──────────────────────────────────────────────────────────────────────
135
+
136
+ async function main() {
137
+ const cmd = args[0];
138
+
139
+ if (cmd === 'help' || cmd === '--help' || cmd === '-h') {
53
140
  showHelp();
54
- } else {
55
- console.error('[xithead] Python CLI not found. Install: pip install xithead');
141
+ return;
142
+ }
143
+
144
+ if (cmd === 'stats') {
145
+ await showStats();
146
+ return;
147
+ }
148
+
149
+ if (cmd === 'proxy') {
150
+ const py = findPython();
151
+ if (!py || !hasPythonXithead(py)) {
152
+ console.error('\x1b[31m [xithead] Python-Paket nicht installiert.\x1b[0m');
153
+ console.error(' Installieren: pip install "git+https://github.com/xtream-itsolutions/headroom.git#subdirectory=xithead_dist"');
154
+ process.exit(1);
155
+ }
156
+ console.log(`\x1b[36m [xithead] Proxy auf Port ${PROXY_PORT} | Ctrl+C zum Stoppen\x1b[0m`);
157
+ console.log(`\x1b[32m [xithead] Dashboard: ${PROXY_URL}/dashboard\x1b[0m`);
158
+ const child = spawnSync(py, ['-m', 'xithead.cli.main', 'proxy', '--port', String(PROXY_PORT), '--verbose'], { stdio: 'inherit' });
159
+ process.exit(child.status || 0);
160
+ return;
161
+ }
162
+
163
+ // Default: launch Claude with proxy
164
+ const py = findPython();
165
+ let proxyOk = await proxyAlive();
166
+
167
+ if (!proxyOk && py && hasPythonXithead(py)) {
168
+ process.stdout.write('\x1b[33m [xithead] Proxy startet...\x1b[0m');
169
+ startProxy(py);
170
+ proxyOk = await waitForProxy();
171
+ process.stdout.write(proxyOk ? ' \x1b[32mbereit!\x1b[0m\n' : ' \x1b[33mTimeout\x1b[0m\n');
172
+ }
173
+
174
+ showBanner(proxyOk);
175
+
176
+ // Set env vars for Claude process
177
+ const env = {
178
+ ...process.env,
179
+ ANTHROPIC_MODEL: 'claude-sonnet-4-6',
180
+ CLAUDE_MODEL: 'claude-sonnet-4-6',
181
+ CLAUDE_SMALL_FAST_MODEL: 'claude-haiku-4-5-20251001',
182
+ CLAUDE_CODE_MAX_OUTPUT_TOKENS: '2048',
183
+ CLAUDE_CODE_MAX_THINKING_TOKENS: '1000',
184
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
185
+ XITHEAD_MODEL: 'claude-sonnet-4-6',
186
+ XITHEAD_ENABLE_CACHE_CONTROL: '1',
187
+ XITHEAD_ENABLE_DEDUP: '1',
188
+ XITHEAD_ENABLE_CONTEXT_TRIM: '1',
189
+ HEADROOM_STRENGTH: 'aggressive',
190
+ HEADROOM_COMPRESSION_RATIO_TARGET: '0.3',
191
+ ANTHROPIC_BASE_URL: proxyOk ? `${PROXY_URL}/v1` : 'https://api.anthropic.com/v1',
192
+ };
193
+
194
+ // Find claude binary
195
+ const claudeResult = spawnSync(process.platform === 'win32' ? 'where' : 'which', ['claude'], { stdio: 'pipe' });
196
+ if (claudeResult.status !== 0) {
197
+ console.error('\x1b[31m [xithead] Claude Code nicht gefunden. Installieren:\x1b[0m');
198
+ console.error(' npm install -g @anthropic-ai/claude-code');
56
199
  process.exit(1);
57
200
  }
201
+
202
+ const claudeArgs = args.length > 0 ? args : [];
203
+ const claudeProc = spawnSync('claude', claudeArgs, { stdio: 'inherit', env });
204
+ process.exit(claudeProc.status || 0);
58
205
  }
206
+
207
+ main().catch(e => { console.error(e); process.exit(1); });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xithead",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Aggressive Claude context optimizer - Cut API costs by 50-95%. By Xtream-ITSolutions UG.",
5
5
  "keywords": [
6
6
  "claude",