Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
revert: remove optimization and Go migration plan docs
Cursor Agentc05b696c6ec0
diff --git a/docs/PHASE1_GOLANG_PLAN.md b/docs/PHASE1_GOLANG_PLAN.mddeleted file mode 100644index c3483c9d..00000000--- a/docs/PHASE1_GOLANG_PLAN.md+++ /dev/null@@ -1,315 +0,0 @@-# Phase 1: Go Proxy Implementation Plan--Port the HTTP proxy (API, optimization handlers, rate limiting, NIM provider, session store, CLI manager) to Go. **Telegram bot stays in Python** and will call this Go proxy.-------## 1. Scope--### In Scope-| Component | Python Source | Go Target |-|-----------|---------------|-----------|-| HTTP server + routes | `api/app.py`, `api/routes.py` | `cmd/proxy/main.go`, `internal/http/` |-| Request/response models | `api/models/` | `internal/models/` |-| Optimization handlers | `api/optimization_handlers.py`, `api/detection.py` | `internal/optimization/` |-| Command utils | `api/command_utils.py` | `internal/optimization/command.go` |-| Token counting | `api/request_utils.py` | `internal/token/` (approx or tiktoken-go) |-| Rate limiter | `providers/rate_limit.py` | `internal/ratelimit/` |-| NIM request builder | `providers/nvidia_nim/request.py`, `utils/message_converter.py` | `internal/nim/request.go` |-| NIM client + streaming | `providers/nvidia_nim/client.py` | `internal/nim/client.go` |-| SSE builder | `providers/nvidia_nim/utils/sse_builder.py` | `internal/nim/sse.go` |-| Think parser | `providers/nvidia_nim/utils/think_parser.py` | `internal/nim/think_parser.go` |-| Heuristic tool parser | `providers/nvidia_nim/utils/heuristic_tool_parser.py` | `internal/nim/heuristic_tool.go` |-| Error mapping | `providers/nvidia_nim/errors.py` | `internal/nim/errors.go` |-| Session store | `messaging/session.py` | `internal/session/store.go` |-| CLI manager | `cli/manager.py`, `cli/session.py` | `internal/cli/manager.go` |-| Process registry | `cli/process_registry.py` | `internal/cli/registry.go` |-| Config | `config/settings.py`, `config/nim.py` | `internal/config/` |--### Out of Scope (Phase 1)-- Telegram bot (stays in Python)-- Message handler, tree queue, transcript (Telegram-specific)-- Messaging rate limiter (Telegram-specific)-------## 2. Project Structure--```-free-claude-code/-├── cmd/-│ └── proxy/-│ └── main.go # Entry point, load config, start server-├── internal/-│ ├── config/-│ │ ├── config.go # Settings from env-│ │ └── nim.go # NIM-specific settings-│ ├── http/-│ │ ├── server.go # HTTP server setup-│ │ ├── routes.go # Route registration-│ │ └── handlers.go # Route handlers-│ ├── models/-│ │ ├── anthropic.go # Request/response structs-│ │ └── openai.go # OpenAI/NIM structs-│ ├── optimization/-│ │ ├── detection.go # is_quota_check, is_title, etc.-│ │ ├── handlers.go # try_optimizations, individual handlers-│ │ └── command.go # extract_command_prefix, extract_filepaths-│ ├── token/-│ │ └── count.go # Token estimation (approx or tiktoken-go)-│ ├── ratelimit/-│ │ └── limiter.go # GlobalRateLimiter (sliding window)-│ ├── nim/-│ │ ├── client.go # HTTP client, stream_response-│ │ ├── request.go # build_request_body-│ │ ├── converter.go # Anthropic -> OpenAI message format-│ │ ├── sse.go # SSE event builder-│ │ ├── think_parser.go # <think> tag parser-│ │ ├── heuristic_tool.go # Heuristic tool call parser-│ │ └── errors.go # Map OpenAI errors -> Anthropic-│ ├── session/-│ │ └── store.go # JSON file store, trees, sessions-│ └── cli/-│ ├── manager.go # CLISessionManager-│ ├── session.go # CLISession (subprocess)-│ └── registry.go # Process cleanup-├── go.mod-├── go.sum-└── Makefile-```-------## 3. Implementation Order--### Milestone 1: Skeleton + Config + Optimization Fast-Path-**Goal:** Go server that returns optimized responses for quota, prefix, title, suggestion, filepath. No NIM yet.--| Step | Task | Files |-|------|------|-------|-| 1.1 | `go mod init`, project layout | `go.mod`, `cmd/proxy/main.go` |-| 1.2 | Config from env (viper or envconfig) | `internal/config/config.go`, `nim.go` |-| 1.3 | Request/response models (JSON tags) | `internal/models/anthropic.go` |-| 1.4 | Detection logic | `internal/optimization/detection.go` |-| 1.5 | Command utils (shlex equivalent) | `internal/optimization/command.go` |-| 1.6 | Optimization handlers | `internal/optimization/handlers.go` |-| 1.7 | HTTP routes: POST /v1/messages (optimization path only) | `internal/http/` |-| 1.8 | GET /, GET /health | `internal/http/handlers.go` |--**Verify:** `curl -X POST http://localhost:8082/v1/messages -d '{"model":"claude","messages":[{"role":"user","content":"quota check"}]}'` returns mock quota response.-------### Milestone 2: Token Counting + Count Tokens Endpoint-**Goal:** Add POST /v1/messages/count_tokens.--| Step | Task | Files |-|------|------|-------|-| 2.1 | Token estimation: `len(text)/4` approximation or `tiktoken-go` | `internal/token/count.go` |-| 2.2 | Count tokens handler | `internal/http/handlers.go` |--**Verify:** `curl -X POST http://localhost:8082/v1/messages/count_tokens -d '{"model":"claude","messages":[{"role":"user","content":"hello"}]}'` returns `input_tokens`.-------### Milestone 3: Rate Limiter-**Goal:** Add provider rate limiter before NIM calls.--| Step | Task | Files |-|------|------|-------|-| 3.1 | Sliding window rate limiter | `internal/ratelimit/limiter.go` |-| 3.2 | Reactive block on 429 | `internal/ratelimit/limiter.go` |-| 3.3 | Retry with backoff on 429 | `internal/ratelimit/limiter.go` |--**Verify:** Unit tests for limiter; integration test with mock NIM.-------### Milestone 4: NIM Request Builder + Message Converter-**Goal:** Build OpenAI-format request body from Anthropic request.--| Step | Task | Files |-|------|------|-------|-| 4.1 | Anthropic -> OpenAI message converter | `internal/nim/converter.go` |-| 4.2 | Request body builder (max_tokens, temperature, tools, etc.) | `internal/nim/request.go` |-| 4.3 | NIM settings (from config) | `internal/config/nim.go` |--**Verify:** Unit tests for converter and request builder.-------### Milestone 5: NIM Client + SSE Streaming-**Goal:** Stream NIM responses and convert to Anthropic SSE format.--| Step | Task | Files |-|------|------|-------|-| 5.1 | SSE event builder | `internal/nim/sse.go` |-| 5.2 | Think tag parser | `internal/nim/think_parser.go` |-| 5.3 | Heuristic tool parser | `internal/nim/heuristic_tool.go` |-| 5.4 | Error mapping | `internal/nim/errors.go` |-| 5.5 | NIM HTTP client (streaming) | `internal/nim/client.go` |-| 5.6 | Wire NIM into POST /v1/messages (non-optimized path) | `internal/http/handlers.go` |--**Verify:** Full flow: `claude` CLI connects to Go proxy, sends real request, receives streamed response.-------### Milestone 6: Session Store-**Goal:** JSON file store for sessions and trees (for future Telegram integration).--| Step | Task | Files |-|------|------|-------|-| 6.1 | Session store (sessions, trees, node_to_tree) | `internal/session/store.go` |-| 6.2 | Debounced save | `internal/session/store.go` |-| 6.3 | Message log (optional, for /clear) | `internal/session/store.go` |--**Verify:** Unit tests; store survives restart.-------### Milestone 7: CLI Manager + Process Registry-**Goal:** Spawn and manage Claude CLI subprocesses.--| Step | Task | Files |-|------|------|-------|-| 7.1 | Process registry (register, unregister, kill_all) | `internal/cli/registry.go` |-| 7.2 | CLISession (start_task, stop, env setup) | `internal/cli/session.go` |-| 7.3 | CLISessionManager (get_or_create, register_real_session_id) | `internal/cli/manager.go` |-| 7.4 | POST /stop handler | `internal/http/handlers.go` |-| 7.5 | Lifespan: init CLI manager, cleanup on shutdown | `cmd/proxy/main.go` |--**Verify:** Telegram bot (Python) can start CLI via Go proxy; POST /stop cancels tasks.-------### Milestone 8: Polish-**Goal:** Production readiness.--| Step | Task |-|------|------|-| 8.1 | Graceful shutdown (timeout) |-| 8.2 | Logging (structured, e.g. slog) |-| 8.3 | Health check includes provider status |-| 8.4 | README for Go proxy |-------## 4. API Contracts (JSON)--### Request: POST /v1/messages-```json-{- "model": "claude-3-sonnet",- "max_tokens": 4096,- "messages": [{"role": "user", "content": "Hello"}],- "system": "You are helpful.",- "tools": [...],- "tool_choice": "auto",- "temperature": 1.0,- "stop_sequences": null-}-```--### Response: Optimized (non-streaming JSON)-```json-{- "id": "msg_xxx",- "model": "claude-3-sonnet",- "role": "assistant",- "content": [{"type": "text", "text": "..."}],- "stop_reason": "end_turn",- "usage": {"input_tokens": 100, "output_tokens": 5}-}-```--### Response: Streaming (SSE)-- `event: message_start` → `data: {"type":"message_start",...}`-- `event: content_block_start` → `data: {"type":"content_block_start",...}`-- `event: content_block_delta` → ...-- `event: content_block_stop` → ...-- `event: message_delta` → ...-- `event: message_stop` → ...-- `[DONE]`-------## 5. Go Dependencies--| Package | Purpose |-|---------|---------|-| `github.com/joho/godotenv` | Load .env |-| `github.com/kelseyhightower/envconfig` or `github.com/caarlos0/env` | Config from env |-| `github.com/sashabaranov/go-openai` | OpenAI client (NIM is OpenAI-compatible) |-| `github.com/google/uuid` | UUID generation |-| `github.com/pelletier/go-toml` or stdlib | Optional: config file |-------## 6. Config Mapping (Env Vars)--| Python | Go |-|--------|-----|-| `NVIDIA_NIM_API_KEY` | `NVIDIA_NIM_API_KEY` |-| `MODEL` | `MODEL` |-| `NVIDIA_NIM_RATE_LIMIT` | `NVIDIA_NIM_RATE_LIMIT` |-| `NVIDIA_NIM_RATE_WINDOW` | `NVIDIA_NIM_RATE_WINDOW` |-| `FAST_PREFIX_DETECTION` | `FAST_PREFIX_DETECTION` |-| `ENABLE_NETWORK_PROBE_MOCK` | `ENABLE_NETWORK_PROBE_MOCK` |-| `ENABLE_TITLE_GENERATION_SKIP` | `ENABLE_TITLE_GENERATION_SKIP` |-| `ENABLE_SUGGESTION_MODE_SKIP` | `ENABLE_SUGGESTION_MODE_SKIP` |-| `ENABLE_FILEPATH_EXTRACTION_MOCK` | `ENABLE_FILEPATH_EXTRACTION_MOCK` |-| `CLAUDE_WORKSPACE` | `CLAUDE_WORKSPACE` |-| `ALLOWED_DIR` | `ALLOWED_DIR` |-| `MAX_CLI_SESSIONS` | `MAX_CLI_SESSIONS` |-| `HOST`, `PORT` | `HOST`, `PORT` |-| All `NVIDIA_NIM_*` | `NVIDIA_NIM_*` |-------## 7. Token Counting Strategy--**Option A (recommended):** Use `len(text)/4` approximation. Fast, no deps. Claude uses cl100k; approximation is ~10–20% off for typical text.--**Option B:** Use `github.com/pkoukk/tiktoken-go` (community port). More accurate but adds dependency and binary size.--**Option C:** Call Python microservice for token count. Avoid for Phase 1 (adds complexity).-------## 8. Testing Strategy--| Type | Approach |-|------|----------|-| Unit | `*_test.go` next to each package |-| Integration | Test server with mock NIM (httptest) |-| E2E | Run `claude` CLI against Go proxy; verify streaming |-| Parity | Compare Go proxy responses with Python proxy for same requests |-------## 9. Acceptance Criteria--- [ ] Go proxy returns same optimized responses as Python for quota, prefix, title, suggestion, filepath-- [ ] Go proxy streams NIM responses correctly (thinking, text, tool_use)-- [ ] Claude CLI works with Go proxy (ANTHROPIC_BASE_URL=http://localhost:8082)-- [ ] POST /stop cancels running tasks-- [ ] Rate limiting: 40 req/60s enforced; 429 triggers backoff-- [ ] Session store persists and restores-- [ ] Graceful shutdown: CLI processes killed, no orphaned subprocesses-- [ ] Python Telegram bot can use Go proxy (no code changes to bot beyond base URL)-------## 10. Estimated Effort--| Milestone | Effort |-|-----------|--------|-| M1: Skeleton + Config + Optimization | 2–3 days |-| M2: Token counting | 0.5 day |-| M3: Rate limiter | 1 day |-| M4: NIM request builder | 1–2 days |-| M5: NIM client + SSE | 2–3 days |-| M6: Session store | 1 day |-| M7: CLI manager | 1–2 days |-| M8: Polish | 1 day |-| **Total** | **~10–14 days** |diff --git a/docs/RESOURCE_OPTIMIZATION_PLAN.md b/docs/RESOURCE_OPTIMIZATION_PLAN.mddeleted file mode 100644index f9983ed3..00000000--- a/docs/RESOURCE_OPTIMIZATION_PLAN.md+++ /dev/null@@ -1,298 +0,0 @@-# Resource Usage & Efficiency Optimization Plan--This document outlines opportunities to improve efficiency and resource usage across the Free Claude Code proxy. Each section identifies the current behavior, optimization opportunity, and suggested approach.-------## 1. API Request Path Optimizations--### 1.1 Skip Token Counting for Optimized Responses-**Location:** `api/routes.py` (create_message)--**Current:** `get_token_count()` is only called when the request proceeds to streaming (after `try_optimizations` returns `None`). ✅ Already optimized.--**Status:** No change needed.-------### 1.2 Detection Short-Circuit & Shared Text Extraction-**Location:** `api/detection.py`, `api/optimization_handlers.py`--**Current:** Each optimization handler may call `extract_text_from_content()` independently. For a single request, detection functions can extract text from the same content multiple times (e.g., `is_quota_check_request`, `is_prefix_detection_request` both inspect the first user message).--**Opportunity:**-- Add a **single-pass detection** that extracts text once and runs all cheap checks (quota, title, suggestion, prefix, filepath) against it.-- Reorder handlers by **cheapest-first** (already done: quota → prefix → title → suggestion → filepath).-- Consider a **unified detection** function that returns a `(optimization_type, extracted_data)` tuple to avoid redundant parsing.--**Effort:** Low–Medium | **Impact:** Medium (reduces CPU per request on hot path)-------### 1.3 Lazy Tiktoken Encoder-**Location:** `api/request_utils.py` (line 14)--**Current:** `ENCODER = tiktoken.get_encoding("cl100k_base")` is loaded at module import time. Tiktoken loading involves reading/parsing encoding files.--**Opportunity:** Use lazy initialization—only load the encoder on first `get_token_count()` call. For optimization-heavy workloads (quota, prefix, title, etc.), many requests never need token counting.--**Effort:** Low | **Impact:** Low–Medium (faster startup, less memory if optimizations dominate)-------### 1.4 Fix Syntax Error in request_utils.py ✅ DONE-**Location:** `api/request_utils.py` line 89--**Current:** `except TypeError, ValueError:` — invalid Python 3 syntax.--**Fix:** `except (TypeError, ValueError):` — applied.--**Effort:** Trivial | **Impact:** Bug fix (code may not run correctly in edge cases)-------## 2. Session Store & Persistence--### 2.1 Async-Friendly Session Store-**Location:** `messaging/session.py`--**Current:** Uses `threading.Lock` and synchronous file I/O (`open`, `json.load`, `json.dump`). All tree/session updates trigger debounced saves that block a thread.--**Opportunity:**-- Use `asyncio.Lock` and `aiofiles` (or `run_in_executor`) for non-blocking I/O.-- Keeps the event loop responsive during heavy save operations.-- Consider batching multiple dirty writes into a single flush.--**Effort:** Medium | **Impact:** Medium (better responsiveness under load)-------### 2.2 Reduce Session Store Write Frequency-**Location:** `messaging/session.py` — `_schedule_save`, `record_message_id`, `save_tree`--**Current:** Debounce is 0.5s. Every `record_message_id` and `save_tree` can schedule a save. Under high message volume, this can still mean frequent disk writes.--**Opportunity:**-- Increase debounce to 1–2 seconds for tree/session updates.-- Add a max write interval (e.g., cap at 1 write per 2s even if dirty).-- For `record_message_id`, consider batching or skipping persistence for high-frequency status updates (if acceptable for `/clear` semantics).--**Effort:** Low | **Impact:** Low–Medium (fewer disk I/O operations)-------## 3. Rate Limiters--### 3.1 Provider Rate Limiter — Sleep Outside Lock-**Location:** `providers/rate_limit.py` — `_acquire_proactive_slot`--**Current:** Already sleeps outside the lock. ✅ Good.--**Status:** No change needed.-------### 3.2 Messaging Rate Limiter — Config from Settings-**Location:** `messaging/limiter.py` (lines 99–100)--**Current:** Reads `MESSAGING_RATE_LIMIT` and `MESSAGING_RATE_WINDOW` directly from `os.getenv()`, bypassing `config.settings`.--**Opportunity:** Inject these from `Settings` for consistency and testability. Reduces env reads and aligns with the rest of the app.--**Effort:** Low | **Impact:** Low (consistency, testability)-------## 4. Messaging & Handler--### 4.1 Defer Message ID Recording-**Location:** `messaging/handler.py` — `handle_message`--**Current:** `record_message_id` is called for every incoming message, including commands and status echoes, before early returns.--**Opportunity:** Move `record_message_id` to after command/status filtering, or use a fire-and-forget pattern so the main path isn’t blocked by session store updates. The store already uses debounced saves, but the lock is still acquired synchronously.--**Effort:** Low | **Impact:** Low (slightly faster handler path)-------### 4.2 Transcript Event Type Lookup-**Location:** `messaging/handler.py` — `TRANSCRIPT_EVENT_TYPES`--**Current:** Uses `frozenset` for O(1) membership. ✅ Good.--**Status:** No change needed.-------## 5. Provider & Streaming--### 5.1 NIM Client — Reuse Parsers-**Location:** `providers/nvidia_nim/client.py` — `stream_response`--**Current:** Creates `ThinkTagParser()` and `HeuristicToolParser()` per request. These are lightweight.--**Opportunity:** If profiling shows allocation overhead, consider object pooling. Likely not necessary unless under extreme request rates.--**Effort:** Low | **Impact:** Low-------### 5.2 SSE Builder Token Counting-**Location:** `providers/nvidia_nim/utils/sse_builder.py`--**Current:** Uses `ENCODER.encode()` for usage reporting. Shares tiktoken with `request_utils`.--**Opportunity:** Same lazy encoder as in 1.3. Ensure a single shared encoder instance.--**Effort:** Low | **Impact:** Low-------## 6. CLI & Process Management--### 6.1 Idle Session Cleanup-**Location:** `cli/manager.py` — `_cleanup_idle_sessions_unlocked`--**Current:** Cleanup runs when hitting `max_sessions`. Sessions are removed when CLI exits.--**Opportunity:** Add a background task that periodically prunes idle sessions (e.g., no activity for N minutes) to free subprocesses and file descriptors earlier.--**Effort:** Medium | **Impact:** Medium (better resource reclaim under bursty usage)-------### 6.2 Process Registry — Best-Effort Cleanup-**Location:** `cli/process_registry.py`, `server.py`--**Current:** `kill_all_best_effort()` runs in `finally` on shutdown. Good safety net.--**Status:** No change needed.-------## 7. Application Lifespan--### 7.1 Lazy Messaging Initialization-**Location:** `api/app.py` — `lifespan`--**Current:** Messaging platform, session store, CLI manager, and tree queue are all initialized at startup, even when no Telegram messages are expected (e.g., CLI-only usage).--**Opportunity:** Defer messaging initialization until the first request that needs it (e.g., first `/stop` or first webhook hit). Reduces startup time and memory when running in CLI-only mode.--**Effort:** Medium | **Impact:** Medium (faster startup for CLI-only)-------### 7.2 Tree Restoration-**Location:** `api/app.py` — `lifespan` (lines 101–121)--**Current:** Loads all trees and node mappings at startup, then runs `cleanup_stale_nodes()` and syncs back.--**Opportunity:** Run restoration in a background task so the server can accept requests sooner. Ensure handlers tolerate `tree_queue` not being fully restored for a short window.--**Effort:** Medium | **Impact:** Low–Medium (faster startup)-------## 8. Configuration & Imports--### 8.1 Settings Loaded Twice at Startup-**Location:** `api/app.py` (lines 19–20, 46)--**Current:** `get_settings()` is called at module level and again in `lifespan`. `get_settings` is `@lru_cache()` so it’s cheap, but the pattern is redundant.--**Opportunity:** Use a single `settings = get_settings()` at module level and pass it where needed, or rely solely on `Depends(get_settings)` in lifespan.--**Effort:** Low | **Impact:** Low (cleaner code)-------### 8.2 PTB Environment Variable-**Location:** `api/app.py` (line 7)--**Current:** `os.environ["PTB_TIMEDELTA"] = "1"` is set at import time. Required for python-telegram-bot.--**Status:** No change needed.-------## 9. Summary: Recommended Priorities--| Priority | Item | Effort | Impact |-|----------|------|--------|--------|-| P0 | Fix `except TypeError, ValueError` syntax | Trivial | Bug fix |-| P1 | Lazy tiktoken encoder | Low | Startup/memory |-| P1 | Single-pass detection / shared text extraction | Low–Med | CPU per request |-| P2 | Messaging limiter config from Settings | Low | Consistency |-| P2 | Session store debounce tuning | Low | Disk I/O |-| P3 | Async session store I/O | Medium | Responsiveness |-| P3 | Lazy messaging initialization | Medium | Startup (CLI-only) |-| P3 | Idle session cleanup background task | Medium | Resource reclaim |-| P4 | Tree restoration in background | Medium | Startup |-| P4 | Defer message ID recording | Low | Handler latency |-------## 10. Implementation Order Suggestion--1. **Immediate:** Fix syntax error in `request_utils.py`.-2. **Quick wins:** Lazy tiktoken, single-pass detection, messaging limiter from Settings.-3. **Next:** Session store debounce, defer message ID recording.-4. **Larger refactors:** Async session store, lazy messaging init, idle session cleanup, background tree restoration.-------## 11. What to Move to Golang--Components that would benefit from being rewritten in Go for better efficiency, lower memory, and faster execution. Go excels at: HTTP/streaming, concurrency, subprocess management, and single-binary deployment.--### 11.1 Best Candidates (High ROI, Lower Friction)--| Component | Location | Why Go Helps | Go Alternatives |-|-----------|----------|--------------|-----------------|-| **HTTP API + SSE streaming** | `api/routes.py`, `api/app.py` | `net/http` is very efficient; SSE is straightforward; no GIL; lower memory per connection | `net/http`, `encoding/json`, or `chi`/`gin` |-| **Optimization handlers** | `api/optimization_handlers.py`, `api/detection.py` | Pure logic, string matching, JSON; Go is fast and allocation-friendly | stdlib `strings`, `encoding/json` |-| **Rate limiters** | `providers/rate_limit.py`, `messaging/limiter.py` | Goroutines + channels; strict sliding window is trivial; no asyncio overhead | `sync.Mutex`, `time.Ticker`, or `golang.org/x/time/rate` |-| **Session store** | `messaging/session.py` | File I/O, JSON, locking; Go's sync is efficient; no threading.Lock + debounce complexity | `sync.RWMutex`, `encoding/json`, `os.WriteFile` |-| **CLI subprocess management** | `cli/manager.py`, `cli/session.py`, `cli/process_registry.py` | `exec.Command`, `os.Process`; native process lifecycle; no asyncio.subprocess | `os/exec`, `syscall` |--### 11.2 Medium Candidates (Good ROI, Some Reinvention)--| Component | Location | Why Go Helps | Friction |-|-----------|----------|--------------|----------|-| **NVIDIA NIM provider** | `providers/nvidia_nim/` | HTTP streaming, JSON, SSE; Go HTTP client is efficient | Need OpenAI-compatible client; `sashabaranov/go-openai` or custom |-| **SSE builder / event conversion** | `providers/nvidia_nim/utils/sse_builder.py` | String building, streaming; Go `strings.Builder` is fast | Logic must be ported; think/tool parsing |-| **Tree queue / processor** | `messaging/tree_queue.py`, `tree_processor.py` | Concurrency, state machines; goroutines fit well | Data structures and callbacks need redesign |--### 11.3 Poor Candidates (Keep in Python)--| Component | Location | Why Keep in Python |-|-----------|----------|--------------------|-| **Telegram bot** | `messaging/telegram.py` | `python-telegram-bot` is mature; Go has `go-telegram-bot-api/telegram-bot-api` but different API and less ecosystem |-| **Token counting (tiktoken)** | `api/request_utils.py`, `sse_builder.py` | OpenAI tiktoken is Python/Rust; Go has `tiktoken-go` (community) or approximations (GPT-2 BPE) — accuracy may differ |-| **Handler / transcript logic** | `messaging/handler.py`, `transcript.py` | Tightly coupled to Telegram, markdown, event parsing; high porting cost for marginal gain |--### 11.4 Hybrid Architecture Options--1. **Go proxy + Python sidecar**- - Go: HTTP API, optimization handlers, rate limiting, session store, CLI process manager.- - Python: Telegram bot, NIM streaming (or call Go for NIM if ported), token counting (or approximate in Go).- - Communication: HTTP between Go and Python, or shared Redis/DB for session state.--2. **Full Go rewrite**- - Port everything except Telegram; run Telegram bot as a separate Python service that forwards to the Go proxy.- - Token counting: use `tiktoken-go` or accept approximation (e.g., chars/4).--3. **Go for hot path only**- - Go microservice: `/v1/messages` optimization fast-path (quota, prefix, title, suggestion, filepath) + rate limiting.- - Python: Full proxy for non-optimized requests, Telegram, CLI management.- - Reduces Python load for the majority of requests (optimizations handle many).--### 11.5 Suggested Migration Order (if pursuing Go)--1. **Phase 1:** Go service for optimization handlers + rate limiting (standalone or sidecar). Python proxy forwards to it for fast-path decisions.-2. **Phase 2:** Port session store to Go (or Redis); Python reads/writes via HTTP or shared store.-3. **Phase 3:** Port NIM provider + SSE streaming to Go; Python handles only Telegram + CLI.-4. **Phase 4:** Port CLI manager to Go; Python only for Telegram bot.-5. **Phase 5 (optional):** Port Telegram to Go if `go-telegram-bot-api` meets needs; then full Go stack.