Zero-Ceremony Local Fallback for Oh My Pi (OMP) with LM Studio on Linux

Anyone running terminal-based coding agents like Oh My Pi (OMP) knows two competing pain points:

  1. Free cloud routers (such as OpenRouter Free or Kilo) are convenient, but they frequently hit rate limits (429) or stall during peak traffic.
  2. Keeping a local LLM loaded in VRAM around the clock—especially on an 8 GB card like an RTX 3060 Ti—ties up 5–6 GB of video memory and leaves Electron/Node background processes running even when you never touch the local model.

The goal was a “zero-ceremony” setup:

  • Launch OMP with a single command (omp-proxy) or from a desktop launcher.
  • Use free cloud routers whenever they respond, keeping GPU and system RAM completely untouched.
  • Spin up LM Studio and load the local model strictly on demand, on the first fallback request.
  • Stream responses smoothly into OMP’s TUI with zero socket errors or stray tracebacks.
  • Unload the model and tear down all background processes (server, AppImage, and workers) as soon as OMP exits.

Why Pointing OMP Directly at LM Studio Falls Short

LM Studio exposes an OpenAI-compatible API at [http://127.0.0.1:1234/v1](http://127.0.0.1:1234/v1). Pointing OMP directly at that port has three practical drawbacks:

  • No lazy startup: If LM Studio isn’t already running, requests fail immediately with Connection refused.
  • Duplicated configuration: Switching local models means updating both LM Studio and OMP’s config files (models.yml and config.yml).
  • Lingering processes on Linux: The lms CLI delegates inference to the LM Studio AppImage. Running lms server stop shuts down the HTTP endpoint, but leaves the tray application and its internal Node workers alive in memory.

How omp-proxy Works

Everything lives inside a single executable (~/.local/bin/omp-proxy): a Bash wrapper paired with a zero-dependency Python HTTP micro-proxy listening on 127.0.0.1:1235.

OMP (TUI)
  ├── Primary      ──► Free cloud routers (OpenRouter / Kilo)
  └── Fallback     ──► omp-proxy (127.0.0.1:1235)
                         ├── Runs `lms server start` + `lms load` (only on first hit)
                         ├── Rewrites `"model": "local"` -> actual model ID
                         ├── Streams response chunks (`Transfer-Encoding: chunked`)
                         └── On exit (`trap EXIT`): unloads model and kills LM Studio

Key Design Decisions

  1. Lazy startup: When omp-proxy starts, the micro-proxy binds to port 1235 without touching LM Studio. As long as cloud routers succeed, your GPU stays completely idle.
  2. Single source of truth for the model ID: OMP’s models.yml and config.yml point to a static alias (lm-studio-proxy/local). The actual model to load (for example, Qwen 3.5 9B in Q4_K_M, which fits comfortably inside an RTX 3060 Ti’s 8 GB VRAM with room for a solid context window) is defined once inside omp-proxy. On every JSON POST request, the proxy rewrites "model": "local" to the real model identifier and updates Content-Length.
  3. Clean HTTP/1.1 chunked streaming: OMP’s TUI expects real-time token streaming. The proxy forwards response chunks using Transfer-Encoding: chunked and silently catches BrokenPipeError and ConnectionResetError when the client closes the socket at [DONE], keeping the terminal UI free of tracebacks.
  4. Deterministic cleanup on exit: Using trap cleanup EXIT INT TERM HUP and an atomic state file, the script tracks whether it started LM Studio during the session. When OMP exits, it runs lms unload --all, lms server stop, and terminates any remaining AppImage/worker processes owned by the current $UID.

Complete Script: ~/.local/bin/omp-proxy

#!/usr/bin/env bash
set -u

# Imposta qui il tuo modello di default
LM_MODEL="${LM_STUDIO_MODEL:-qwen3.5-9b-deepseek-v4-flash}"

# ---------------------------------------------------
export PATH="$HOME/.local/bin:$PATH"

LMS="${LMS_BIN:-$HOME/.lmstudio/bin/lms}"
command -v "$LMS" >/dev/null 2>&1 || LMS="lms"

PROXY_PORT="${LM_PROXY_PORT:-1235}"
LMS_PORT="${LM_STUDIO_PORT:-1234}"

state_file=$(mktemp -t ompls-state.XXXXXX)
printf 'started_server=0\nloaded_model=0\n' >"$state_file"
proxy_pid=""

cleanup() {
  if [ -n "$proxy_pid" ] && kill -0 "$proxy_pid" 2>/dev/null; then
    kill "$proxy_pid" 2>/dev/null || true
    wait "$proxy_pid" 2>/dev/null || true
  fi

  local started_server=0
  local loaded_model=0
  if [ -f "$state_file" ]; then
    # shellcheck disable=SC1090
    source "$state_file"
  fi

  if command -v "$LMS" >/dev/null 2>&1; then
    if [ "${loaded_model:-0}" -eq 1 ]; then
      "$LMS" unload --all >/dev/null 2>&1 || true
    fi
    if [ "${started_server:-0}" -eq 1 ]; then
      "$LMS" server stop >/dev/null 2>&1 || true
    fi
  fi

  if [ "${started_server:-0}" -eq 1 ]; then
    pkill -TERM -u "$UID" -f '\.lmstudio|mount_lm-stu' 2>/dev/null || true
    sleep 1
    pkill -KILL -u "$UID" -f '\.lmstudio|mount_lm-stu' 2>/dev/null || true
  fi

  rm -f "$state_file"
}

trap cleanup EXIT INT TERM HUP

python3 - "$PROXY_PORT" "$LMS_PORT" "$LMS" "$LM_MODEL" "$state_file" <<'PY' &
import http.client
import http.server
import os
import socketserver
import subprocess
import sys
import threading
import time
import json

proxy_port = int(sys.argv[1])
lms_port = int(sys.argv[2])
lms_bin = sys.argv[3]
lm_model = sys.argv[4]
state_file = sys.argv[5]

lock = threading.Lock()
ready = False
started_server = 0
loaded_model = 0

def write_state():
    tmp_path = f"{state_file}.tmp.{os.getpid()}"
    try:
        with open(tmp_path, "w", encoding="utf-8") as f:
            f.write(f"started_server={started_server}\nloaded_model={loaded_model}\n")
        os.replace(tmp_path, state_file)
    except Exception:
        try:
            if os.path.exists(tmp_path):
                os.remove(tmp_path)
        except Exception:
            pass

def lms_up() -> bool:
    conn = None
    try:
        conn = http.client.HTTPConnection("127.0.0.1", lms_port, timeout=1.0)
        conn.request("GET", "/v1/models")
        resp = conn.getresponse()
        resp.read()
        return resp.status == 200
    except Exception:
        return False
    finally:
        if conn:
            conn.close()

def ensure_started():
    global ready, started_server, loaded_model
    with lock:
        if ready and lms_up():
            return
        if not lms_up():
            res = subprocess.run(
                [lms_bin, "server", "start"],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
            )
            if res.returncode == 0:
                started_server = 1
                write_state()
            for _ in range(40):
                if lms_up():
                    break
                time.sleep(0.5)
        if lm_model and loaded_model == 0:
            res = subprocess.run(
                [lms_bin, "load", lm_model],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
            )
            if res.returncode == 0:
                loaded_model = 1
                write_state()
        ready = True

class Handler(http.server.BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, format, *args):
        pass

    def _write_chunk(self, data: bytes):
        if data:
            self.wfile.write(f"{len(data):x}\r\n".encode("ascii") + data + b"\r\n")
            self.wfile.flush()

    def _finish_chunks(self):
        self.wfile.write(b"0\r\n\r\n")
        self.wfile.flush()

    def _forward(self, method: str):
        ensure_started()

        length = int(self.headers.get("Content-Length", "0") or "0")
        body = self.rfile.read(length) if length > 0 else None

        if body and lm_model and "application/json" in (self.headers.get("Content-Type") or "").lower():
            try:
                parsed = json.loads(body.decode("utf-8"))
                if isinstance(parsed, dict) and "model" in parsed:
                    parsed["model"] = lm_model
                    body = json.dumps(parsed, ensure_ascii=False).encode("utf-8")
            except Exception:
                pass

        headers = {
            k: v
            for k, v in self.headers.items()
            if k.lower() not in ("host", "connection", "content-length", "transfer-encoding")
        }
        headers["Connection"] = "close"
        if body is not None:
            headers["Content-Length"] = str(len(body))

        conn = None
        headers_sent = False
        try:
            conn = http.client.HTTPConnection("127.0.0.1", lms_port, timeout=300)
            conn.request(method, self.path, body=body, headers=headers)
            resp = conn.getresponse()

            self.send_response(resp.status, resp.reason)
            for k, v in resp.getheaders():
                kl = k.lower()
                if kl not in ("transfer-encoding", "content-length", "connection"):
                    self.send_header(k, v)
            self.send_header("Transfer-Encoding", "chunked")
            self.end_headers()
            headers_sent = True

            while True:
                chunk = resp.read(4096)
                if not chunk:
                    break
                self._write_chunk(chunk)
            self._finish_chunks()
        except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
            pass
        except Exception as e:
            if not headers_sent:
                try:
                    err_bytes = str(e).encode("utf-8")
                    self.send_response(502, "Bad Gateway")
                    self.send_header("Content-Type", "text/plain; charset=utf-8")
                    self.send_header("Transfer-Encoding", "chunked")
                    self.end_headers()
                    self._write_chunk(err_bytes)
                    self._finish_chunks()
                except Exception:
                    pass
        finally:
            if conn:
                conn.close()

    def do_GET(self):
        self._forward("GET")

    def do_POST(self):
        self._forward("POST")

    def do_OPTIONS(self):
        self._forward("OPTIONS")

class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
    daemon_threads = True

    def handle_error(self, request, client_address):
        pass

with ThreadingHTTPServer(("127.0.0.1", proxy_port), Handler) as httpd:
    httpd.serve_forever()
PY
proxy_pid=$!

command omp "$@"
rc=$?
exit $rc

Oh My Pi Configuration

Make the wrapper executable (chmod +x ~/.local/bin/omp-proxy), then add two static blocks to OMP’s configuration files.

~/.omp/agent/models.yml

providers:
  lm-studio-proxy:
    baseUrl: http://127.0.0.1:1235/v1
    api: openai-completions
    auth: none
    models:
      - id: local
        name: Local (via omp-proxy+lmstudio)

~/.omp/agent/config.yml

modelRoles:
  plan: openrouter/openrouter/free
  slow: openrouter/openrouter/free
  smol: openrouter/openrouter/free
  task: openrouter/openrouter/free
  commit: openrouter/openrouter/free
  default: openrouter/openrouter/free
symbolPreset: unicode
composer:
  shape: band
theme:
  dark: titanium
update:
  auto: false
setupVersion: 3
defaultThinkingLevel: auto
edit:
  mode: hashline
retry:
  fallbackChains:
    default:
      - kilo/kilo-auto/free
      - lm-studio-proxy/local
    plan:
      - kilo/kilo-auto/free
      - lm-studio-proxy/local
    slow:
      - kilo/kilo-auto/free
      - lm-studio-proxy/local
    smol:
      - kilo/kilo-auto/free
      - lm-studio-proxy/local
    task:
      - kilo/kilo-auto/free
      - lm-studio-proxy/local

Wrapping Up

From here on, omp-proxy works as a drop-in replacement for omp. Cloud routers handle your prompts by default; the moment they hit a rate limit or go offline, LM Studio spins up automatically, streams the local response, and cleans itself out of VRAM and RAM as soon as you exit.

Leave a Reply