localmend 0.1.0__py3-none-any.whl

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.
localmend/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
localmend/banner.py ADDED
@@ -0,0 +1,66 @@
1
+ """The startup banner: the name in block letters, shown only to a person at a terminal.
2
+
3
+ Shown by `localmend` (no command) and `localmend serve`. Never on doctor/report/check
4
+ output (people paste that into issues), and skipped when the output isn't a terminal,
5
+ with NO_COLOR, with --quiet, or in a window too narrow to draw it.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import shutil
11
+ import sys
12
+
13
+ ART = (
14
+ "██╗ ██████╗ ██████╗ █████╗ ██╗ ███╗ ███╗███████╗███╗ ██╗██████╗ ",
15
+ "██║ ██╔═══██╗██╔════╝██╔══██╗██║ ████╗ ████║██╔════╝████╗ ██║██╔══██╗",
16
+ "██║ ██║ ██║██║ ███████║██║ ██╔████╔██║█████╗ ██╔██╗ ██║██║ ██║",
17
+ "██║ ██║ ██║██║ ██╔══██║██║ ██║╚██╔╝██║██╔══╝ ██║╚██╗██║██║ ██║",
18
+ "███████╗╚██████╔╝╚██████╗██║ ██║███████╗██║ ╚═╝ ██║███████╗██║ ╚████║██████╔╝",
19
+ "╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝╚═════╝ ",
20
+ )
21
+ COLOR = "\x1b[38;2;74;21;32m" # very dark maroon #4a1520
22
+ DIM = "\x1b[2m"
23
+ RESET = "\x1b[0m"
24
+ TAGLINE = "fixes and diagnoses local AI for coding agents"
25
+
26
+
27
+ def _enable_vt(stream) -> bool:
28
+ """Windows consoles need virtual-terminal mode for colors; True if it's on."""
29
+ if sys.platform != "win32":
30
+ return True
31
+ try:
32
+ import ctypes
33
+ k = ctypes.windll.kernel32
34
+ h = k.GetStdHandle(-11 if stream is sys.stdout else -12) # stdout / stderr
35
+ mode = ctypes.c_uint32()
36
+ if not k.GetConsoleMode(h, ctypes.byref(mode)):
37
+ return False
38
+ return bool(k.SetConsoleMode(h, mode.value | 0x0004)) # ENABLE_VIRTUAL_TERMINAL_PROCESSING
39
+ except Exception:
40
+ return False
41
+
42
+
43
+ def text(version: str, stream=None) -> str | None:
44
+ """The banner for this stream, or None when it shouldn't be shown."""
45
+ stream = stream or sys.stderr
46
+ if os.environ.get("NO_COLOR") or os.environ.get("TERM") == "dumb":
47
+ return None
48
+ if not getattr(stream, "isatty", lambda: False)():
49
+ return None
50
+ if shutil.get_terminal_size((0, 0)).columns < len(ART[0]):
51
+ return None
52
+ try:
53
+ ("".join(ART) + TAGLINE + "·").encode(getattr(stream, "encoding", None) or "utf-8")
54
+ except (UnicodeEncodeError, LookupError):
55
+ return None
56
+ if not _enable_vt(stream):
57
+ return None
58
+ art = "\n".join(COLOR + line.rstrip() + RESET for line in ART)
59
+ return f"\n{art}\n{DIM}v{version} · {TAGLINE}{RESET}\n"
60
+
61
+
62
+ def show(version: str, stream=None) -> None:
63
+ stream = stream or sys.stderr
64
+ t = text(version, stream)
65
+ if t:
66
+ print(t, file=stream, flush=True)
localmend/check.py ADDED
@@ -0,0 +1,220 @@
1
+ """`localmend check`: test the model server the way a coding agent will use it.
2
+
3
+ About a minute, no agent needed. Each finding says what it costs and what to do,
4
+ cheapest cure first (a server or app setting), a localmend fix second.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import random
9
+ import time
10
+
11
+ import httpx
12
+
13
+ from . import checks, upstream
14
+ from .fixes import sysmerge
15
+ from .sse import summarize
16
+
17
+ AGENT_PROMPT = 14_000 # tokens an agent sends per request (Claude Code ~13-22k, OpenCode ~10-14k)
18
+ MIN_CTX = 32_768
19
+ SHARED = 160 # lines of shared prompt start in the reuse test (~2k tokens: fits a 4k context)
20
+
21
+
22
+ def _shared_text(seed: int) -> str:
23
+ rnd = random.Random(seed)
24
+ words = ("server model prompt cache token agent file test python value check list"
25
+ " write read error session system tool answer result time line").split()
26
+ return "\n".join(f"Note {i}: " + " ".join(rnd.choice(words) for _ in range(5)) for i in range(SHARED))
27
+
28
+
29
+ class Server:
30
+ def __init__(self, url: str, model: str | None, client: httpx.Client | None = None):
31
+ self.c = client or httpx.Client(base_url=upstream.base_url(url), timeout=600)
32
+ self.model = model
33
+ self.kind = upstream.OTHER
34
+
35
+ def get(self, path: str, timeout: float = 5):
36
+ try:
37
+ r = self.c.get(path, timeout=timeout)
38
+ return r.json() if r.status_code == 200 else None
39
+ except (httpx.HTTPError, ValueError):
40
+ return None
41
+
42
+ def chat(self, messages: list, max_tokens: int = 1, **extra) -> tuple[int, str, float]:
43
+ """(status, raw body, seconds). Streamed, like an agent does."""
44
+ body = {"model": self.model or "local", "messages": messages, "max_tokens": max_tokens,
45
+ "stream": True, "stream_options": {"include_usage": True}, "temperature": 0, **extra}
46
+ t0 = time.time()
47
+ with self.c.stream("POST", "/v1/chat/completions", json=body) as r:
48
+ raw = r.read().decode("utf-8", "replace")
49
+ return r.status_code, raw, time.time() - t0
50
+
51
+
52
+ def _detect(s: Server) -> str:
53
+ v = s.get("/api/version")
54
+ if isinstance(v, dict) and "version" in v: # LM Studio answers this path with an error object
55
+ return upstream.OLLAMA
56
+ props = s.get("/props")
57
+ if isinstance(props, dict) and "default_generation_settings" in props:
58
+ return upstream.LLAMACPP
59
+ models = s.get("/api/v0/models")
60
+ if isinstance(models, dict) and isinstance(models.get("data"), list):
61
+ return upstream.LMSTUDIO
62
+ return upstream.OTHER
63
+
64
+
65
+ def _ollama_model(s: Server) -> str | None:
66
+ for path in ("/api/ps", "/api/tags"):
67
+ j = s.get(path)
68
+ models = j.get("models") or [] if isinstance(j, dict) else []
69
+ if models:
70
+ return models[0].get("name") or models[0].get("model")
71
+ return None
72
+
73
+
74
+ def _context(s: Server) -> int | None:
75
+ if s.kind == upstream.LLAMACPP:
76
+ p = s.get("/props", timeout=30) or {} # can be slow while the server finishes a request
77
+ n = (p.get("default_generation_settings") or {}).get("n_ctx")
78
+ return int(n) if n else None
79
+ if s.kind == upstream.OLLAMA:
80
+ for m in (s.get("/api/ps") or {}).get("models") or []:
81
+ if m.get("context_length"):
82
+ return int(m["context_length"])
83
+ if s.kind == upstream.LMSTUDIO:
84
+ loaded = [m for m in (s.get("/api/v0/models") or {}).get("data") or []
85
+ if isinstance(m, dict) and m.get("state") == "loaded" and m.get("loaded_context_length")]
86
+ m = next((m for m in loaded if m.get("id") == s.model), None if s.model else (loaded[0] if loaded else None))
87
+ return int(m["loaded_context_length"]) if m else None
88
+ return None
89
+
90
+
91
+ def _read(raw: str, wall: float) -> tuple[float, int | None, int | None]:
92
+ """(seconds spent reading the prompt, prompt tokens in all, tokens reused from the cache)
93
+ from the server's own numbers. llama.cpp's prompt_n counts only what it read and cache_n
94
+ the rest; Ollama's prompt_n is the whole prompt and the reused part is in usage."""
95
+ s = summarize(raw)
96
+ t, u = s.timings or {}, s.usage or {}
97
+ secs = float(t["prompt_ms"]) / 1000 if "prompt_ms" in t else wall
98
+ cached = (u.get("prompt_tokens_details") or {}).get("cached_tokens")
99
+ if "cache_n" in t:
100
+ n, reused = int(t.get("prompt_n") or 0), int(t["cache_n"])
101
+ return secs, n + reused, reused
102
+ total = t.get("prompt_n") or u.get("prompt_tokens")
103
+ return secs, int(total) if total else None, int(cached) if cached is not None else None
104
+
105
+
106
+ def run(url: str, model: str | None = None, client: httpx.Client | None = None, say=print) -> list[str]:
107
+ """Run every check, printing as it goes. Returns the PROBLEM lines (empty = all ok)."""
108
+ s = Server(url, model, client)
109
+ problems: list[str] = []
110
+
111
+ def problem(text: str, do: str) -> None:
112
+ problems.append(text)
113
+ say("PROBLEM " + text)
114
+ say(" do: " + do)
115
+
116
+ # 1. reachable, which server, which model
117
+ try:
118
+ s.c.get("/", timeout=5)
119
+ except httpx.HTTPError:
120
+ say(f"PROBLEM server: nothing answers at {url}. Start llama-server or Ollama first, "
121
+ "or pass its address with --upstream.")
122
+ return ["server"]
123
+ s.kind = _detect(s)
124
+ if s.kind == upstream.OLLAMA and not s.model:
125
+ s.model = _ollama_model(s)
126
+ if not s.model:
127
+ say("PROBLEM model: Ollama has no models. Pull one first, e.g. `ollama pull qwen3.5:4b`.")
128
+ return ["model"]
129
+ say(f"ok server: {s.kind} at {url}" + (f", model {s.model}" if s.model else ""))
130
+
131
+ st, raw, _ = s.chat([{"role": "user", "content": "Say ok."}]) # loads the model, so timings below are fair
132
+ if st != 200:
133
+ say(f"PROBLEM server: a plain chat request failed with HTTP {st}: {raw[:200]}")
134
+ return problems + ["chat"]
135
+
136
+ # 2. context size (now that Ollama has the model loaded)
137
+ ctx = _context(s)
138
+ if ctx and ctx < MIN_CTX:
139
+ fix = ("set OLLAMA_CONTEXT_LENGTH=32768 and restart Ollama (or raise it in the app's Settings)"
140
+ if s.kind == upstream.OLLAMA else
141
+ "load the model with a bigger context: in LM Studio's load settings, or `lms load <model> -c 32768`"
142
+ if s.kind == upstream.LMSTUDIO else "start the server with a bigger context, e.g. llama-server -c 32768")
143
+ problem(f"context: {ctx:,} tokens. Coding agents send 10-22k tokens per request before any work, so "
144
+ "the prompt gets cut or the agent runs out of room.", fix)
145
+ elif ctx:
146
+ say(f"ok context: {ctx:,} tokens.")
147
+ else:
148
+ say("? context: the server doesn't say. Agents need 32k or more.")
149
+
150
+ # 3. prompt reading speed + reuse of a shared prompt start (what a new session needs)
151
+ shared = _shared_text(random.randrange(1 << 30)) # fresh text, so nothing is cached from before
152
+ first = [{"role": "system", "content": "You are a coding agent.\n" + shared},
153
+ {"role": "user", "content": "Task A: say ok."}]
154
+ second = [first[0], {"role": "user", "content": "Task B: say yes."}]
155
+ st1, raw, wall = s.chat(first)
156
+ st2, raw2, wall2 = s.chat(second)
157
+ if st1 != 200 or st2 != 200:
158
+ say(f"? speed and cache: a ~2k-token prompt failed with HTTP {st1 if st1 != 200 else st2}, so these "
159
+ f"weren't tested: {(raw if st1 != 200 else raw2)[:160]}")
160
+ else:
161
+ t1, total1, reused1 = _read(raw, wall)
162
+ t2, _, reused2 = _read(raw2, wall2)
163
+ if total1 and t1:
164
+ rate = (total1 - (reused1 or 0)) / t1
165
+ say(f"ok speed: reads {rate:,.0f} prompt tokens/s, so an agent's ~{AGENT_PROMPT // 1000}k-token "
166
+ f"prompt takes ~{AGENT_PROMPT / rate:.0f} s to read whenever the cache misses.")
167
+ # the server's own count if it gives one, else the time tells
168
+ full = reused2 < 0.5 * total1 if reused2 is not None and total1 else t2 > 0.5 * t1
169
+ how = (f"reused {reused2:,} of {total1:,} tokens, " if reused2 is not None and total1 else "") + \
170
+ f"{t1:.1f} s, then {t2:.1f} s"
171
+ if full:
172
+ problem(f"cache: a second prompt with the same start was read again almost in full ({how}). "
173
+ "Every new session pays the full read, and moving changing parts out of the system prompt "
174
+ "(localmend's prefix fix) can't help here.",
175
+ "nothing a proxy can fix. Models with hybrid or sliding-window layers (Qwen3.5, Gemma 4) "
176
+ "can only go back to a few saved points in a prompt; a newer server version or llama.cpp "
177
+ "may place them better.")
178
+ else:
179
+ say(f"ok cache: a second prompt with the same start skipped the shared part ({how}). This was a "
180
+ "short prompt: models with hybrid or sliding-window layers (Qwen3.5, Gemma 4) can still miss "
181
+ "on a long agent prompt, which the recorded session (below) shows.")
182
+
183
+ if s.kind == upstream.OLLAMA:
184
+ j = s.get("/api/ps")
185
+ models = j.get("models") or [] if isinstance(j, dict) else []
186
+ if models and all(not m.get("size_vram") for m in models):
187
+ problem("gpu: Ollama runs this model on the CPU only, which is several times slower.",
188
+ checks.gpu_advice())
189
+
190
+ # 4. a system message after the start (Claude Code and others send one)
191
+ st, raw, _ = s.chat([{"role": "system", "content": "You are a coding agent."},
192
+ {"role": "user", "content": "Say ok."},
193
+ {"role": "assistant", "content": "ok"},
194
+ {"role": "system", "content": "Note: the working directory changed."},
195
+ {"role": "user", "content": "Say ok again."}])
196
+ if st >= 400 and sysmerge.REJECTED.search(raw):
197
+ problem("chat template: the model only accepts a system message at the start, and apps such as "
198
+ "Claude Code and Codex CLI send more later on. Every such request fails (HTTP %d)." % st,
199
+ "run your app through `localmend serve` (it moves later system messages into the "
200
+ "conversation), or use a patched chat template. Claude Code alone: a Claude model name, "
201
+ "e.g. ANTHROPIC_MODEL=claude-sonnet-4-5, also avoids it.")
202
+ elif st >= 400:
203
+ say(f"? chat template: a later system message got HTTP {st}: {raw[:150]}")
204
+ else:
205
+ say("ok chat template: accepts a system message after the start.")
206
+
207
+ # 5. `think: false` (Odysseus and others send it to turn thinking off)
208
+ st, raw, wall = s.chat([{"role": "user", "content": "What is 2+2? Answer with one number."}],
209
+ max_tokens=200, think=False)
210
+ if st == 200 and summarize(raw).reasoning:
211
+ problem("thinking: the app's `think: false` is ignored, so the model thinks anyway "
212
+ f"({wall:.0f} s for a one-number answer). Thinking eats minutes on short side requests.",
213
+ "run your app through `localmend serve`, which sends the server's own no-thinking switch.")
214
+ elif st == 200:
215
+ say("ok thinking: `think: false` is honoured (or this model doesn't think).")
216
+
217
+ say("")
218
+ say("Next: see what your agent actually does with this server. Run `localmend serve --observe`, point "
219
+ "your agent at it, do a task or two, then stop it with Ctrl+C for a report.")
220
+ return problems
localmend/checks.py ADDED
@@ -0,0 +1,69 @@
1
+ """Setup problems we can see from the traffic, with the exact fix.
2
+
3
+ These are not fixed by the proxy (they live in the server's configuration),
4
+ so they are reported: once on the console while serving, and by `doctor`.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+
10
+ from .sse import Summary
11
+
12
+ CHARS_PER_TOKEN = 4 # rough; real text/code is 3-5, and we only flag a 2x gap
13
+
14
+
15
+ def estimate_tokens(req: dict) -> int:
16
+ chars = len(json.dumps(req.get("messages") or [], ensure_ascii=False))
17
+ chars += len(json.dumps(req.get("tools") or [], ensure_ascii=False))
18
+ return chars // CHARS_PER_TOKEN
19
+
20
+
21
+ def tokens_seen(s: Summary) -> int | None:
22
+ def num(v) -> int: # the server's numbers; a buggy or hostile one may send anything
23
+ return int(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else 0
24
+ t = s.timings if isinstance(s.timings, dict) else {}
25
+ u = s.usage if isinstance(s.usage, dict) else {}
26
+ if "prompt_n" in t:
27
+ return num(t.get("prompt_n")) + num(t.get("cache_n"))
28
+ if num(u.get("prompt_tokens")):
29
+ return num(u["prompt_tokens"])
30
+ return None
31
+
32
+
33
+ def truncation(req: dict, s: Summary) -> tuple[int, int] | None:
34
+ """(estimated, seen) if the server evidently dropped most of the prompt."""
35
+ seen = tokens_seen(s)
36
+ est = estimate_tokens(req)
37
+ if seen is None or est < 2000 or seen >= est / 2:
38
+ return None
39
+ return est, seen
40
+
41
+
42
+ def truncation_message(est: int, seen: int, server: str) -> str:
43
+ fix = ("Ollama's default context is 4096 tokens. Set OLLAMA_CONTEXT_LENGTH=32768 (or more) "
44
+ "in the environment and restart Ollama." if server == "ollama" else
45
+ "Raise the server's context size (e.g. llama-server -c 32768).")
46
+ return (f"PROBLEM context: the agent sent ~{est:,} tokens but the model saw only {seen:,}. "
47
+ f"The server is cutting the prompt, so the model loses the agent's instructions and tools. {fix}")
48
+
49
+
50
+ IGPU_ADVICE = ("On Intel/AMD integrated GPUs Ollama skips the GPU unless you set OLLAMA_IGPU_ENABLE=1 and "
51
+ "restart it (check with `ollama ps`: PROCESSOR should not say 100% CPU).")
52
+ MAC_ADVICE = ("On Apple Silicon Ollama uses the GPU by itself, so this usually means the model plus its context "
53
+ "doesn't fit in the memory macOS gives the GPU: try a smaller model, quantization or context. On "
54
+ "Intel Macs Ollama runs on the CPU only.")
55
+ IGPU_MESSAGE = "PROBLEM gpu: Ollama is running this model on the CPU only. " + IGPU_ADVICE
56
+ MAC_GPU_MESSAGE = "PROBLEM gpu: Ollama is running this model on the CPU only (check with `ollama ps`). " + MAC_ADVICE
57
+
58
+
59
+ def gpu_advice(platform: str | None = None) -> str:
60
+ """What to do about Ollama running on the CPU only, for the machine localmend runs on."""
61
+ import sys
62
+ return MAC_ADVICE if (platform or sys.platform) == "darwin" else IGPU_ADVICE
63
+
64
+
65
+ def gpu_message(platform: str | None = None) -> str:
66
+ """The CPU-only warning, with advice for the machine localmend runs on
67
+ (normally the same machine as Ollama)."""
68
+ import sys
69
+ return MAC_GPU_MESSAGE if (platform or sys.platform) == "darwin" else IGPU_MESSAGE
localmend/cli.py ADDED
@@ -0,0 +1,250 @@
1
+ """Command line: `localmend check`, `serve`, `doctor` and `report`."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+
8
+ from .sse import summarize
9
+
10
+
11
+ def _version() -> str:
12
+ from importlib.metadata import PackageNotFoundError, version
13
+ try:
14
+ return version("localmend")
15
+ except PackageNotFoundError:
16
+ return "dev"
17
+
18
+
19
+ def port_in_use(host: str, port: int) -> bool:
20
+ """On Windows a second server can bind a busy port without error and never
21
+ receive traffic, so check by connecting first."""
22
+ import socket
23
+
24
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
25
+ s.settimeout(0.5)
26
+ return s.connect_ex((host, port)) == 0
27
+
28
+
29
+ def trace_dir() -> str:
30
+ """Where --observe keeps its traces: a per-user folder, never the project folder.
31
+ A trace holds full prompts, code and answers; in the current folder it could end
32
+ up in a git commit or a shared folder by accident."""
33
+ import os
34
+ if sys.platform == "win32":
35
+ base = os.environ.get("LOCALAPPDATA") or os.path.join(os.path.expanduser("~"), "AppData", "Local")
36
+ elif sys.platform == "darwin":
37
+ base = os.path.expanduser("~/Library/Application Support")
38
+ else:
39
+ base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
40
+ return os.path.join(base, "localmend", "traces")
41
+
42
+
43
+ def new_trace_path() -> str:
44
+ """A fresh file per run, in a folder only this user can read (Linux/Mac)."""
45
+ import os
46
+ import time
47
+ d = trace_dir()
48
+ os.makedirs(d, mode=0o700, exist_ok=True)
49
+ return os.path.join(d, time.strftime("trace-%Y%m%d-%H%M%S.jsonl"))
50
+
51
+
52
+ def latest_trace() -> str | None:
53
+ import os
54
+ d = trace_dir()
55
+ try:
56
+ names = [n for n in os.listdir(d) if n.startswith("trace-") and n.endswith(".jsonl")]
57
+ except OSError:
58
+ return None
59
+ return os.path.join(d, max(names)) if names else None
60
+
61
+
62
+ def _trace_arg(a, cmd: str) -> None:
63
+ """`doctor`/`report` with no file: the newest --observe trace."""
64
+ if a.trace:
65
+ return
66
+ a.trace = latest_trace()
67
+ if a.trace is None:
68
+ sys.exit(f"localmend {cmd}: no traces yet in {trace_dir()}. Record one with `localmend serve --observe`, "
69
+ "use your agent for a few tasks, then stop it with Ctrl+C.")
70
+
71
+
72
+ def serve(a) -> None:
73
+ import uvicorn
74
+
75
+ from .server import Settings, build_app
76
+
77
+ if port_in_use(a.host, a.port):
78
+ sys.exit(f"localmend: something is already listening on {a.host}:{a.port}; pick another --port")
79
+
80
+ if a.observe:
81
+ a.no_prefix = a.no_verify = a.no_sidecalls = a.no_think_flag = True
82
+ a.trace = a.trace or new_trace_path()
83
+ from .upstream import base_url
84
+ s = Settings(upstream=base_url(a.upstream), prefix=not a.no_prefix, learn=not a.no_learn,
85
+ verify=not a.no_verify, sidecalls=not a.no_sidecalls, think_flag=not a.no_think_flag,
86
+ sysmerge=not a.no_sysmerge,
87
+ trace_path=a.trace, log=not a.quiet)
88
+ on = [n for n, v in (("prefix", s.prefix), ("verify", s.verify), ("sidecalls", s.sidecalls),
89
+ ("think-flag", s.think_flag), ("sysmerge", s.sysmerge)) if v]
90
+ if not a.quiet:
91
+ from . import banner
92
+ banner.show(_version())
93
+ print(f"localmend: http://{a.host}:{a.port}/v1 -> {s.upstream} fixes: {', '.join(on) or 'none'}"
94
+ + (f" trace: {s.trace_path}" if s.trace_path else ""), file=sys.stderr)
95
+ print(f"localmend: OpenAI-style apps: base URL http://{a.host}:{a.port}/v1 "
96
+ f"Claude Code: ANTHROPIC_BASE_URL=http://{a.host}:{a.port}", file=sys.stderr)
97
+ from .server import LOOPBACK_HOSTS
98
+ # On localhost, only accept requests addressed to localhost (blocks DNS rebinding
99
+ # from web pages). With --host 0.0.0.0 the user chose to be reachable by any name.
100
+ hosts = LOOPBACK_HOSTS if a.host in ("127.0.0.1", "localhost", "::1") else None
101
+ try:
102
+ uvicorn.run(build_app(s, allowed_hosts=hosts), host=a.host, port=a.port, log_level="warning")
103
+ except KeyboardInterrupt: # normally uvicorn handles Ctrl+C itself and returns
104
+ pass
105
+ _report_on_exit(s.trace_path)
106
+
107
+
108
+ def _report_on_exit(trace_path: str | None) -> None:
109
+ """After Ctrl+C: what the recorded session shows, so nobody has to know about `doctor`."""
110
+ import os
111
+ if not trace_path or not os.path.exists(trace_path):
112
+ return
113
+ from .doctor import diagnose, load
114
+ reqs = load(trace_path)
115
+ if not reqs:
116
+ return
117
+ if hasattr(sys.stdout, "reconfigure"):
118
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
119
+ print(f"\nlocalmend doctor {trace_path}\n")
120
+ for line in diagnose(reqs):
121
+ print(line)
122
+
123
+
124
+ def check(a) -> None:
125
+ from .check import run
126
+ from .upstream import base_url
127
+
128
+ if hasattr(sys.stdout, "reconfigure"):
129
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
130
+ print(f"localmend check: testing {base_url(a.upstream)} the way a coding agent uses it (about a minute)\n")
131
+ problems = run(a.upstream, a.model, say=lambda t: print(t, flush=True))
132
+ sys.exit(1 if problems else 0)
133
+
134
+
135
+ def report(a) -> None:
136
+ from .doctor import _safe
137
+ from .fixes import anthropic
138
+
139
+ if hasattr(sys.stdout, "reconfigure"):
140
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
141
+ _trace_arg(a, "report")
142
+ import os
143
+ if not os.path.exists(a.trace):
144
+ sys.exit(f"localmend report: no trace at {a.trace}. Record one with `localmend serve --trace FILE` "
145
+ "(or --observe).")
146
+ n = 0
147
+ for line in open(a.trace, encoding="utf-8"):
148
+ try:
149
+ r = json.loads(line)
150
+ except ValueError: # e.g. the last line of a trace cut off mid-write
151
+ continue
152
+ path = r.get("path", "") if isinstance(r, dict) else ""
153
+ path = path if isinstance(path, str) else ""
154
+ try:
155
+ row = _report_row(r, path, anthropic)
156
+ except (AttributeError, TypeError, ValueError, KeyError):
157
+ continue # a malformed record
158
+ if row is None:
159
+ continue
160
+ read, cached, calls, text = row
161
+ n += 1
162
+ fixes = ",".join(_safe(f) for f in (r.get("fixes") or []) if isinstance(r.get("fixes"), list))
163
+ print(f"#{n:>3} {float(r.get('total_s') or 0):>7.1f}s read={_safe(read):>6} cached={_safe(cached):>6} "
164
+ f"fixes={fixes or '-':<14} calls={calls or '-'} {text[:70]!r}")
165
+ if not n:
166
+ print("No chat requests in this trace.")
167
+
168
+
169
+ def _report_row(r: dict, path: str, anthropic):
170
+ """(prompt tokens read, reused, tool calls, answer) of one traced request, or None."""
171
+ if "chat/completions" in path:
172
+ s = summarize(r.get("response", ""))
173
+ t = s.timings or {}
174
+ read, cached = t.get("prompt_n", "?"), t.get("cache_n", "?")
175
+ calls, text = [c["name"] for c in s.tool_calls.values()], s.content
176
+ elif "/responses" in path: # OpenAI Responses API (Codex CLI)
177
+ from . import responses
178
+ s = responses.summarize(r.get("response", ""))
179
+ t = s.timings or {}
180
+ read, cached = t.get("prompt_n", "?"), t.get("cache_n", "?")
181
+ calls, text = [c["name"] for c in s.tool_calls.values()], s.content
182
+ elif "/messages" in path: # Anthropic Messages API (Claude Code)
183
+ u = anthropic.usage(r.get("response", ""))
184
+ read, cached = u.get("input_tokens", "?"), u.get("cache_read_input_tokens", "?")
185
+ text, calls, _ = anthropic.text_of(r.get("response", ""))
186
+ else:
187
+ return None
188
+ return read, cached, calls, text
189
+
190
+
191
+ def doctor(a) -> None:
192
+ from .doctor import diagnose, load
193
+
194
+ if hasattr(sys.stdout, "reconfigure"):
195
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
196
+ _trace_arg(a, "doctor")
197
+ import os
198
+ if not os.path.exists(a.trace):
199
+ sys.exit(f"localmend doctor: no trace at {a.trace}. Record one with `localmend serve --observe`, "
200
+ "use your agent for a few tasks, then run doctor on the file it prints.")
201
+ for line in diagnose(load(a.trace)):
202
+ print(line)
203
+
204
+
205
+ def main(argv=None) -> None:
206
+ p = argparse.ArgumentParser(prog="localmend")
207
+ p.add_argument("--version", action="version", version=f"%(prog)s {_version()}")
208
+ sub = p.add_subparsers(dest="cmd")
209
+ cp = sub.add_parser("check", help="test your model server the way a coding agent uses it (about a minute)")
210
+ cp.add_argument("--upstream", default="http://127.0.0.1:8080",
211
+ help="your model server, e.g. Ollama http://127.0.0.1:11434 (default %(default)s)")
212
+ cp.add_argument("--model", help="model to test (Ollama: default the loaded or first installed one)")
213
+ cp.set_defaults(fn=check)
214
+ sp = sub.add_parser("serve", help="run the proxy")
215
+ sp.add_argument("--upstream", default="http://127.0.0.1:8080",
216
+ help="your model server: llama.cpp, Ollama (:11434), vLLM, LM Studio... (default %(default)s)")
217
+ sp.add_argument("--host", default="127.0.0.1",
218
+ help="address to listen on (default %(default)s; 0.0.0.0 opens it to your network without a password)")
219
+ sp.add_argument("--port", type=int, default=4747, help="port to listen on (default %(default)s)")
220
+ sp.add_argument("--trace", help="write a JSONL trace of every exchange to this file")
221
+ sp.add_argument("--quiet", action="store_true", help="don't print a line per request")
222
+ sp.add_argument("--observe", action="store_true",
223
+ help="all fixes off, just record a trace for `localmend doctor` (saved in your user data folder, "
224
+ "not the project; --trace FILE to choose)")
225
+ sp.add_argument("--no-prefix", action="store_true", help="disable the prefix stabilizer")
226
+ sp.add_argument("--no-learn", action="store_true", help="only use known patterns, don't learn volatile regions")
227
+ sp.add_argument("--no-verify", action="store_true", help="disable the verify guard")
228
+ sp.add_argument("--no-sidecalls", action="store_true", help="don't turn thinking off for title/side requests")
229
+ sp.add_argument("--no-think-flag", action="store_true",
230
+ help="don't translate an app's `think: false` into the server's own no-thinking switch")
231
+ sp.add_argument("--no-sysmerge", action="store_true",
232
+ help="don't fold later system messages into the conversation when the server rejects them")
233
+ sp.set_defaults(fn=serve)
234
+ rp = sub.add_parser("report", help="summarise a trace file")
235
+ rp.add_argument("trace", nargs="?", help="trace file (default: the newest --observe trace)")
236
+ rp.set_defaults(fn=report)
237
+ dp = sub.add_parser("doctor", help="explain where an agent's time went, from a trace")
238
+ dp.add_argument("trace", nargs="?", help="trace file (default: the newest --observe trace)")
239
+ dp.set_defaults(fn=doctor)
240
+ a = p.parse_args(argv)
241
+ if a.cmd is None: # plain `localmend`: who we are, then what to type
242
+ from . import banner
243
+ banner.show(_version(), sys.stdout)
244
+ p.print_help()
245
+ return
246
+ a.fn(a)
247
+
248
+
249
+ if __name__ == "__main__":
250
+ main()