{"id":432,"date":"2026-11-25T07:54:29","date_gmt":"2026-11-25T06:54:29","guid":{"rendered":"https:\/\/www.netlabor.it\/?p=432"},"modified":"2026-11-25T07:54:29","modified_gmt":"2026-11-25T06:54:29","slug":"zero-ceremony-local-fallback-per-oh-my-pi-omp-con-lm-studio-su-linux","status":"publish","type":"post","link":"https:\/\/www.netlabor.it\/en\/zero-ceremony-local-fallback-per-oh-my-pi-omp-con-lm-studio-su-linux\/","title":{"rendered":"Zero-Ceremony Local Fallback for Oh My Pi (OMP) with LM Studio on Linux"},"content":{"rendered":"\n<div class=\"wp-block-bogo-language-switcher\"><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Anyone running terminal-based coding agents like <strong>Oh My Pi (OMP)<\/strong> knows two competing pain points:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li><strong>Free cloud routers<\/strong> (such as OpenRouter Free or Kilo) are convenient, but they frequently hit rate limits (<code>429<\/code>) or stall during peak traffic.<\/li>\n\n\n\n<li><strong>Keeping a local LLM loaded in VRAM around the clock<\/strong>\u2014especially on an 8 GB card like an <strong>RTX 3060 Ti<\/strong>\u2014ties up 5\u20136 GB of video memory and leaves Electron\/Node background processes running even when you never touch the local model.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The goal was a <strong>&#8220;zero-ceremony&#8221;<\/strong> setup:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Launch OMP with a single command (<code>omp-proxy<\/code>) or from a desktop launcher.<\/li>\n\n\n\n<li>Use free cloud routers whenever they respond, keeping GPU and system RAM completely untouched.<\/li>\n\n\n\n<li>Spin up LM Studio and load the local model <strong>strictly on demand<\/strong>, on the first fallback request.<\/li>\n\n\n\n<li>Stream responses smoothly into OMP&#8217;s TUI with zero socket errors or stray tracebacks.<\/li>\n\n\n\n<li>Unload the model and tear down all background processes (server, AppImage, and workers) as soon as OMP exits.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Why Pointing OMP Directly at LM Studio Falls Short<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">LM Studio exposes an OpenAI-compatible API at <code>[http:\/\/127.0.0.1:1234\/v1](http:\/\/127.0.0.1:1234\/v1)<\/code>. Pointing OMP directly at that port has three practical drawbacks:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>No lazy startup:<\/strong> If LM Studio isn&#8217;t already running, requests fail immediately with <code>Connection refused<\/code>.<\/li>\n\n\n\n<li><strong>Duplicated configuration:<\/strong> Switching local models means updating both LM Studio and OMP&#8217;s config files (<code>models.yml<\/code> and <code>config.yml<\/code>).<\/li>\n\n\n\n<li><strong>Lingering processes on Linux:<\/strong> The <code>lms<\/code> CLI delegates inference to the LM Studio AppImage. Running <code>lms server stop<\/code> shuts down the HTTP endpoint, but leaves the tray application and its internal Node workers alive in memory.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">How <code>omp-proxy<\/code> Works<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Everything lives inside a single executable (<code>~\/.local\/bin\/omp-proxy<\/code>): a Bash wrapper paired with a zero-dependency Python HTTP micro-proxy listening on <code>127.0.0.1:1235<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>OMP (TUI)\n  \u251c\u2500\u2500 Primary      \u2500\u2500\u25ba Free cloud routers (OpenRouter \/ Kilo)\n  \u2514\u2500\u2500 Fallback     \u2500\u2500\u25ba omp-proxy (127.0.0.1:1235)\n                         \u251c\u2500\u2500 Runs `lms server start` + `lms load` (only on first hit)\n                         \u251c\u2500\u2500 Rewrites `\"model\": \"local\"` -&gt; actual model ID\n                         \u251c\u2500\u2500 Streams response chunks (`Transfer-Encoding: chunked`)\n                         \u2514\u2500\u2500 On exit (`trap EXIT`): unloads model and kills LM Studio\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Key Design Decisions<\/h4>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li><strong>Lazy startup:<\/strong> When <code>omp-proxy<\/code> starts, the micro-proxy binds to port <code>1235<\/code> without touching LM Studio. As long as cloud routers succeed, your GPU stays completely idle.<\/li>\n\n\n\n<li><strong>Single source of truth for the model ID:<\/strong> OMP&#8217;s <code>models.yml<\/code> and <code>config.yml<\/code> point to a static alias (<code>lm-studio-proxy\/local<\/code>). The actual model to load (for example, <code>Qwen 3.5 9B<\/code> in <code>Q4_K_M<\/code>, which fits comfortably inside an RTX 3060 Ti&#8217;s 8 GB VRAM with room for a solid context window) is defined <strong>once<\/strong> inside <code>omp-proxy<\/code>. On every JSON <code>POST<\/code> request, the proxy rewrites <code>\"model\": \"local\"<\/code> to the real model identifier and updates <code>Content-Length<\/code>.<\/li>\n\n\n\n<li><strong>Clean HTTP\/1.1 chunked streaming:<\/strong> OMP&#8217;s TUI expects real-time token streaming. The proxy forwards response chunks using <code>Transfer-Encoding: chunked<\/code> and silently catches <code>BrokenPipeError<\/code> and <code>ConnectionResetError<\/code> when the client closes the socket at <code>[DONE]<\/code>, keeping the terminal UI free of tracebacks.<\/li>\n\n\n\n<li><strong>Deterministic cleanup on exit:<\/strong> Using <code>trap cleanup EXIT INT TERM HUP<\/code> and an atomic state file, the script tracks whether it started LM Studio during the session. When OMP exits, it runs <code>lms unload --all<\/code>, <code>lms server stop<\/code>, and terminates any remaining AppImage\/worker processes owned by the current <code class=\"\">$UID<\/code>.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Complete Script: <code>~\/.local\/bin\/omp-proxy<\/code><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/env bash\nset -u\n\n# Imposta qui il tuo modello di default\nLM_MODEL=\"${LM_STUDIO_MODEL:-qwen3.5-9b-deepseek-v4-flash}\"\n\n# ---------------------------------------------------\nexport PATH=\"$HOME\/.local\/bin:$PATH\"\n\nLMS=\"${LMS_BIN:-$HOME\/.lmstudio\/bin\/lms}\"\ncommand -v \"$LMS\" >\/dev\/null 2>&amp;1 || LMS=\"lms\"\n\nPROXY_PORT=\"${LM_PROXY_PORT:-1235}\"\nLMS_PORT=\"${LM_STUDIO_PORT:-1234}\"\n\nstate_file=$(mktemp -t ompls-state.XXXXXX)\nprintf 'started_server=0\\nloaded_model=0\\n' >\"$state_file\"\nproxy_pid=\"\"\n\ncleanup() {\n  if &#091; -n \"$proxy_pid\" ] &amp;&amp; kill -0 \"$proxy_pid\" 2>\/dev\/null; then\n    kill \"$proxy_pid\" 2>\/dev\/null || true\n    wait \"$proxy_pid\" 2>\/dev\/null || true\n  fi\n\n  local started_server=0\n  local loaded_model=0\n  if &#091; -f \"$state_file\" ]; then\n    # shellcheck disable=SC1090\n    source \"$state_file\"\n  fi\n\n  if command -v \"$LMS\" >\/dev\/null 2>&amp;1; then\n    if &#091; \"${loaded_model:-0}\" -eq 1 ]; then\n      \"$LMS\" unload --all >\/dev\/null 2>&amp;1 || true\n    fi\n    if &#091; \"${started_server:-0}\" -eq 1 ]; then\n      \"$LMS\" server stop >\/dev\/null 2>&amp;1 || true\n    fi\n  fi\n\n  if &#091; \"${started_server:-0}\" -eq 1 ]; then\n    pkill -TERM -u \"$UID\" -f '\\.lmstudio|mount_lm-stu' 2>\/dev\/null || true\n    sleep 1\n    pkill -KILL -u \"$UID\" -f '\\.lmstudio|mount_lm-stu' 2>\/dev\/null || true\n  fi\n\n  rm -f \"$state_file\"\n}\n\ntrap cleanup EXIT INT TERM HUP\n\npython3 - \"$PROXY_PORT\" \"$LMS_PORT\" \"$LMS\" \"$LM_MODEL\" \"$state_file\" &lt;&lt;'PY' &amp;\nimport http.client\nimport http.server\nimport os\nimport socketserver\nimport subprocess\nimport sys\nimport threading\nimport time\nimport json\n\nproxy_port = int(sys.argv&#091;1])\nlms_port = int(sys.argv&#091;2])\nlms_bin = sys.argv&#091;3]\nlm_model = sys.argv&#091;4]\nstate_file = sys.argv&#091;5]\n\nlock = threading.Lock()\nready = False\nstarted_server = 0\nloaded_model = 0\n\ndef write_state():\n    tmp_path = f\"{state_file}.tmp.{os.getpid()}\"\n    try:\n        with open(tmp_path, \"w\", encoding=\"utf-8\") as f:\n            f.write(f\"started_server={started_server}\\nloaded_model={loaded_model}\\n\")\n        os.replace(tmp_path, state_file)\n    except Exception:\n        try:\n            if os.path.exists(tmp_path):\n                os.remove(tmp_path)\n        except Exception:\n            pass\n\ndef lms_up() -> bool:\n    conn = None\n    try:\n        conn = http.client.HTTPConnection(\"127.0.0.1\", lms_port, timeout=1.0)\n        conn.request(\"GET\", \"\/v1\/models\")\n        resp = conn.getresponse()\n        resp.read()\n        return resp.status == 200\n    except Exception:\n        return False\n    finally:\n        if conn:\n            conn.close()\n\ndef ensure_started():\n    global ready, started_server, loaded_model\n    with lock:\n        if ready and lms_up():\n            return\n        if not lms_up():\n            res = subprocess.run(\n                &#091;lms_bin, \"server\", \"start\"],\n                stdout=subprocess.DEVNULL,\n                stderr=subprocess.DEVNULL,\n            )\n            if res.returncode == 0:\n                started_server = 1\n                write_state()\n            for _ in range(40):\n                if lms_up():\n                    break\n                time.sleep(0.5)\n        if lm_model and loaded_model == 0:\n            res = subprocess.run(\n                &#091;lms_bin, \"load\", lm_model],\n                stdout=subprocess.DEVNULL,\n                stderr=subprocess.DEVNULL,\n            )\n            if res.returncode == 0:\n                loaded_model = 1\n                write_state()\n        ready = True\n\nclass Handler(http.server.BaseHTTPRequestHandler):\n    protocol_version = \"HTTP\/1.1\"\n\n    def log_message(self, format, *args):\n        pass\n\n    def _write_chunk(self, data: bytes):\n        if data:\n            self.wfile.write(f\"{len(data):x}\\r\\n\".encode(\"ascii\") + data + b\"\\r\\n\")\n            self.wfile.flush()\n\n    def _finish_chunks(self):\n        self.wfile.write(b\"0\\r\\n\\r\\n\")\n        self.wfile.flush()\n\n    def _forward(self, method: str):\n        ensure_started()\n\n        length = int(self.headers.get(\"Content-Length\", \"0\") or \"0\")\n        body = self.rfile.read(length) if length > 0 else None\n\n        if body and lm_model and \"application\/json\" in (self.headers.get(\"Content-Type\") or \"\").lower():\n            try:\n                parsed = json.loads(body.decode(\"utf-8\"))\n                if isinstance(parsed, dict) and \"model\" in parsed:\n                    parsed&#091;\"model\"] = lm_model\n                    body = json.dumps(parsed, ensure_ascii=False).encode(\"utf-8\")\n            except Exception:\n                pass\n\n        headers = {\n            k: v\n            for k, v in self.headers.items()\n            if k.lower() not in (\"host\", \"connection\", \"content-length\", \"transfer-encoding\")\n        }\n        headers&#091;\"Connection\"] = \"close\"\n        if body is not None:\n            headers&#091;\"Content-Length\"] = str(len(body))\n\n        conn = None\n        headers_sent = False\n        try:\n            conn = http.client.HTTPConnection(\"127.0.0.1\", lms_port, timeout=300)\n            conn.request(method, self.path, body=body, headers=headers)\n            resp = conn.getresponse()\n\n            self.send_response(resp.status, resp.reason)\n            for k, v in resp.getheaders():\n                kl = k.lower()\n                if kl not in (\"transfer-encoding\", \"content-length\", \"connection\"):\n                    self.send_header(k, v)\n            self.send_header(\"Transfer-Encoding\", \"chunked\")\n            self.end_headers()\n            headers_sent = True\n\n            while True:\n                chunk = resp.read(4096)\n                if not chunk:\n                    break\n                self._write_chunk(chunk)\n            self._finish_chunks()\n        except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):\n            pass\n        except Exception as e:\n            if not headers_sent:\n                try:\n                    err_bytes = str(e).encode(\"utf-8\")\n                    self.send_response(502, \"Bad Gateway\")\n                    self.send_header(\"Content-Type\", \"text\/plain; charset=utf-8\")\n                    self.send_header(\"Transfer-Encoding\", \"chunked\")\n                    self.end_headers()\n                    self._write_chunk(err_bytes)\n                    self._finish_chunks()\n                except Exception:\n                    pass\n        finally:\n            if conn:\n                conn.close()\n\n    def do_GET(self):\n        self._forward(\"GET\")\n\n    def do_POST(self):\n        self._forward(\"POST\")\n\n    def do_OPTIONS(self):\n        self._forward(\"OPTIONS\")\n\nclass ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):\n    daemon_threads = True\n\n    def handle_error(self, request, client_address):\n        pass\n\nwith ThreadingHTTPServer((\"127.0.0.1\", proxy_port), Handler) as httpd:\n    httpd.serve_forever()\nPY\nproxy_pid=$!\n\ncommand omp \"$@\"\nrc=$?\nexit $rc<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Oh My Pi Configuration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Make the wrapper executable (<code>chmod +x ~\/.local\/bin\/omp-proxy<\/code>), then add two static blocks to OMP&#8217;s configuration files.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><code>~\/.omp\/agent\/models.yml<\/code><\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>providers:\n  lm-studio-proxy:\n    baseUrl: http:\/\/127.0.0.1:1235\/v1\n    api: openai-completions\n    auth: none\n    models:\n      - id: local\n        name: Local (via omp-proxy+lmstudio)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><code>~\/.omp\/agent\/config.yml<\/code><\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>modelRoles:\n  plan: openrouter\/openrouter\/free\n  slow: openrouter\/openrouter\/free\n  smol: openrouter\/openrouter\/free\n  task: openrouter\/openrouter\/free\n  commit: openrouter\/openrouter\/free\n  default: openrouter\/openrouter\/free\nsymbolPreset: unicode\ncomposer:\n  shape: band\ntheme:\n  dark: titanium\nupdate:\n  auto: false\nsetupVersion: 3\ndefaultThinkingLevel: auto\nedit:\n  mode: hashline\nretry:\n  fallbackChains:\n    default:\n      - kilo\/kilo-auto\/free\n      - lm-studio-proxy\/local\n    plan:\n      - kilo\/kilo-auto\/free\n      - lm-studio-proxy\/local\n    slow:\n      - kilo\/kilo-auto\/free\n      - lm-studio-proxy\/local\n    smol:\n      - kilo\/kilo-auto\/free\n      - lm-studio-proxy\/local\n    task:\n      - kilo\/kilo-auto\/free\n      - lm-studio-proxy\/local<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Wrapping Up<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">From here on, <code>omp-proxy<\/code> works as a drop-in replacement for <code>omp<\/code>. 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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Anyone running terminal-based coding agents like Oh My Pi (OMP) knows two competing pain points: The goal was a &#8220;zero-ceremony&#8221; setup: 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: How omp-proxy Works Everything lives inside a [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"full-width-page-template.php","format":"standard","meta":{"_locale":"en_US","_original_post":"https:\/\/www.netlabor.it\/?p=430","footnotes":""},"categories":[24,6,7],"tags":[25,8,9],"class_list":["post-432","post","type-post","status-publish","format-standard","hentry","category-ai","category-informatica","category-programmazione","tag-ai","tag-informatica","tag-programmazione","en-US","missing-thumbnail"],"_links":{"self":[{"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/posts\/432","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/comments?post=432"}],"version-history":[{"count":1,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/posts\/432\/revisions"}],"predecessor-version":[{"id":433,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/posts\/432\/revisions\/433"}],"wp:attachment":[{"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/media?parent=432"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/categories?post=432"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/tags?post=432"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}