meshapi-code 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.
meshapi/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
meshapi/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
meshapi/cli.py ADDED
@@ -0,0 +1,102 @@
1
+ """meshapi — terminal chat REPL for Mesh API."""
2
+ import argparse
3
+ import sys
4
+
5
+ import httpx
6
+ from prompt_toolkit import PromptSession
7
+ from prompt_toolkit.history import FileHistory
8
+ from prompt_toolkit.styles import Style
9
+ from rich.panel import Panel
10
+
11
+ from . import __version__
12
+ from .client import stream_chat
13
+ from .commands import handle_command
14
+ from .config import CONFIG_FILE, HISTORY_FILE, load_config
15
+ from .render import console, fmt_usd, render_stream
16
+
17
+
18
+ def parse_args(argv=None) -> argparse.Namespace:
19
+ p = argparse.ArgumentParser(prog="meshapi", description="Terminal chat for Mesh API")
20
+ p.add_argument("--version", action="version", version=f"meshapi {__version__}")
21
+ p.add_argument("--model", help="Override model for this session (e.g. openai/gpt-4o-mini)")
22
+ p.add_argument("--route", choices=["cheapest", "fastest", "balanced"], help="Routing mode")
23
+ return p.parse_args(argv)
24
+
25
+
26
+ def main() -> None:
27
+ args = parse_args()
28
+ cfg = load_config()
29
+ if args.model:
30
+ cfg["model"] = args.model
31
+ if args.route:
32
+ cfg["route"] = args.route
33
+
34
+ if not cfg["api_key"]:
35
+ console.print(
36
+ "[red]No API key found. Set MESHAPI_API_KEY env var or edit "
37
+ f"{CONFIG_FILE}[/red]"
38
+ )
39
+ sys.exit(1)
40
+
41
+ state = {
42
+ "cfg": cfg,
43
+ "messages": [{"role": "system", "content": cfg["system"]}],
44
+ "session_cost": 0.0,
45
+ }
46
+
47
+ session = PromptSession(history=FileHistory(str(HISTORY_FILE)))
48
+ console.print(Panel.fit(
49
+ f"meshapi {__version__}\n"
50
+ f"model: [bold cyan]{cfg['model']}[/bold cyan]\n"
51
+ f"route: [cyan]{cfg.get('route') or 'default'}[/cyan]\n"
52
+ "type /help for commands, /exit to quit",
53
+ border_style="cyan",
54
+ ))
55
+
56
+ while True:
57
+ try:
58
+ user_input = session.prompt(
59
+ "you > ",
60
+ style=Style.from_dict({"prompt": "ansicyan bold"}),
61
+ )
62
+ except (KeyboardInterrupt, EOFError):
63
+ console.print("\n[dim]bye[/dim]")
64
+ break
65
+
66
+ if not user_input.strip():
67
+ continue
68
+ if user_input.startswith("/"):
69
+ if not handle_command(user_input, state):
70
+ break
71
+ continue
72
+
73
+ state["messages"].append({"role": "user", "content": user_input})
74
+ console.print()
75
+ try:
76
+ reply, meta = render_stream(stream_chat(state["messages"], state["cfg"]))
77
+ state["messages"].append({"role": "assistant", "content": reply})
78
+
79
+ cost = meta.get("cost")
80
+ if cost is not None:
81
+ try:
82
+ state["session_cost"] += float(cost)
83
+ except (TypeError, ValueError):
84
+ pass
85
+ usage = meta.get("usage") or {}
86
+ tokens = (
87
+ f"{usage.get('prompt_tokens', '?')} → {usage.get('completion_tokens', '?')} tok"
88
+ if usage else ""
89
+ )
90
+ cost_line = f"[dim]{tokens} • {fmt_usd(cost)} • session {fmt_usd(state['session_cost'])}[/dim]"
91
+ console.print(cost_line)
92
+ except httpx.HTTPStatusError as e:
93
+ console.print(f"[red]API error {e.response.status_code}: {e.response.text}[/red]")
94
+ state["messages"].pop()
95
+ except Exception as e:
96
+ console.print(f"[red]Error: {e}[/red]")
97
+ state["messages"].pop()
98
+ console.print()
99
+
100
+
101
+ if __name__ == "__main__":
102
+ main()
meshapi/client.py ADDED
@@ -0,0 +1,52 @@
1
+ """Streaming OpenAI-compatible HTTP client for Mesh API."""
2
+ import json
3
+ from typing import Iterable
4
+
5
+ import httpx
6
+
7
+
8
+ def stream_chat(messages: list, cfg: dict) -> Iterable:
9
+ """Yield content deltas, then a final {'usage':..., 'cost':...} dict.
10
+
11
+ Mesh API is OpenAI-compatible but adds `cost` to the final SSE chunk.
12
+ """
13
+ url = f"{cfg['base_url']}/chat/completions"
14
+ headers = {
15
+ "Authorization": f"Bearer {cfg['api_key']}",
16
+ "Content-Type": "application/json",
17
+ }
18
+ payload: dict = {
19
+ "model": cfg["model"],
20
+ "messages": messages,
21
+ "stream": True,
22
+ }
23
+ if cfg.get("route"):
24
+ payload["route"] = cfg["route"]
25
+
26
+ last_meta: dict = {}
27
+ with httpx.stream("POST", url, json=payload, headers=headers, timeout=120) as r:
28
+ r.raise_for_status()
29
+ for line in r.iter_lines():
30
+ if not line or not line.startswith("data: "):
31
+ continue
32
+ data = line[6:]
33
+ if data.strip() == "[DONE]":
34
+ break
35
+ try:
36
+ obj = json.loads(data)
37
+ except json.JSONDecodeError:
38
+ continue
39
+
40
+ choices = obj.get("choices") or []
41
+ if choices:
42
+ delta = choices[0].get("delta", {}).get("content")
43
+ if delta:
44
+ yield delta
45
+
46
+ usage = obj.get("usage")
47
+ cost = obj.get("cost")
48
+ if usage or cost:
49
+ last_meta = {"usage": usage, "cost": cost}
50
+
51
+ if last_meta:
52
+ yield last_meta
meshapi/commands.py ADDED
@@ -0,0 +1,82 @@
1
+ """Slash command handlers."""
2
+ from pathlib import Path
3
+
4
+ from rich.panel import Panel
5
+
6
+ from .config import save_config
7
+ from .render import console, fmt_usd
8
+
9
+ ROUTES = {"cheapest", "fastest", "balanced"}
10
+
11
+
12
+ def handle_command(cmd: str, state: dict) -> bool:
13
+ """Handle slash commands. Returns True if app should continue."""
14
+ parts = cmd.strip().split(maxsplit=1)
15
+ name = parts[0].lower()
16
+ arg = parts[1] if len(parts) > 1 else ""
17
+
18
+ if name in ("/exit", "/quit", "/q"):
19
+ return False
20
+
21
+ if name == "/clear":
22
+ state["messages"] = [{"role": "system", "content": state["cfg"]["system"]}]
23
+ state["session_cost"] = 0.0
24
+ console.print("[dim]Conversation cleared.[/dim]")
25
+
26
+ elif name == "/model":
27
+ if arg:
28
+ state["cfg"]["model"] = arg
29
+ save_config(state["cfg"])
30
+ console.print(f"[dim]Model set to {arg}[/dim]")
31
+ else:
32
+ console.print(f"[dim]Current model: {state['cfg']['model']}[/dim]")
33
+
34
+ elif name == "/route":
35
+ if not arg:
36
+ console.print(f"[dim]Current route: {state['cfg'].get('route') or 'default'}[/dim]")
37
+ elif arg in ROUTES or arg == "default":
38
+ state["cfg"]["route"] = None if arg == "default" else arg
39
+ save_config(state["cfg"])
40
+ console.print(f"[dim]Routing set to {arg}[/dim]")
41
+ else:
42
+ console.print(f"[red]Unknown route. Try: {', '.join(sorted(ROUTES))}, default[/red]")
43
+
44
+ elif name == "/file":
45
+ path = Path(arg).expanduser()
46
+ if path.exists():
47
+ content = path.read_text()
48
+ state["messages"].append({
49
+ "role": "user",
50
+ "content": f"File: {path.name}\n\n```\n{content}\n```",
51
+ })
52
+ console.print(f"[dim]Added {path.name} ({len(content)} chars) to context[/dim]")
53
+ else:
54
+ console.print(f"[red]File not found: {path}[/red]")
55
+
56
+ elif name == "/system":
57
+ if arg:
58
+ state["cfg"]["system"] = arg
59
+ state["messages"] = [{"role": "system", "content": arg}]
60
+ console.print("[dim]System prompt updated and conversation reset.[/dim]")
61
+ else:
62
+ console.print(f"[dim]{state['cfg']['system']}[/dim]")
63
+
64
+ elif name == "/cost":
65
+ console.print(f"[dim]Session spend: {fmt_usd(state.get('session_cost', 0))}[/dim]")
66
+
67
+ elif name == "/help":
68
+ console.print(Panel.fit(
69
+ "/exit end session\n"
70
+ "/clear reset conversation\n"
71
+ "/model <name> switch model (e.g. anthropic/claude-sonnet-4.5)\n"
72
+ "/route <mode> cheapest|fastest|balanced|default\n"
73
+ "/file <path> add file to context\n"
74
+ "/system <txt> set system prompt\n"
75
+ "/cost show session spend\n"
76
+ "/help show this",
77
+ title="commands",
78
+ border_style="cyan",
79
+ ))
80
+ else:
81
+ console.print(f"[red]Unknown command: {name}. Type /help[/red]")
82
+ return True
meshapi/config.py ADDED
@@ -0,0 +1,37 @@
1
+ """Config storage at ~/.meshapi/config.json."""
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+
6
+ CONFIG_DIR = Path.home() / ".meshapi"
7
+ CONFIG_FILE = CONFIG_DIR / "config.json"
8
+ HISTORY_FILE = CONFIG_DIR / "history"
9
+
10
+ DEFAULT_CONFIG = {
11
+ "base_url": "https://api.meshapi.ai/v1",
12
+ "api_key": "",
13
+ "model": "anthropic/claude-sonnet-4.5",
14
+ "system": "You are a helpful coding assistant. Be concise.",
15
+ "route": None,
16
+ }
17
+
18
+
19
+ def load_config() -> dict:
20
+ CONFIG_DIR.mkdir(exist_ok=True)
21
+ if not CONFIG_FILE.exists():
22
+ CONFIG_FILE.write_text(json.dumps(DEFAULT_CONFIG, indent=2))
23
+ cfg = {**DEFAULT_CONFIG, **json.loads(CONFIG_FILE.read_text())}
24
+ # MESH_API_KEY kept as fallback for one release; prefer MESHAPI_API_KEY.
25
+ cfg["api_key"] = (
26
+ os.getenv("MESHAPI_API_KEY")
27
+ or os.getenv("MESH_API_KEY")
28
+ or cfg.get("api_key", "")
29
+ )
30
+ cfg["base_url"] = os.getenv("MESHAPI_BASE_URL", cfg["base_url"])
31
+ return cfg
32
+
33
+
34
+ def save_config(cfg: dict) -> None:
35
+ CONFIG_DIR.mkdir(exist_ok=True)
36
+ persisted = {k: v for k, v in cfg.items() if k != "api_key"}
37
+ CONFIG_FILE.write_text(json.dumps(persisted, indent=2))
meshapi/render.py ADDED
@@ -0,0 +1,43 @@
1
+ """Rich-based markdown live rendering and shared formatters."""
2
+ from typing import Iterable
3
+
4
+ from rich.console import Console
5
+ from rich.live import Live
6
+ from rich.markdown import Markdown
7
+
8
+ console = Console()
9
+
10
+
11
+ def fmt_usd(value) -> str:
12
+ """USD formatter matching dashboard `fmtUsd` (routersvc-client/src/lib/utils.ts).
13
+
14
+ Always 6 decimals; K/M abbreviations for large values. Never use raw f-string
15
+ rounding for money — `999.999833` would render `$1000.00`.
16
+ """
17
+ try:
18
+ n = float(value)
19
+ except (TypeError, ValueError):
20
+ return "$0.000000"
21
+ if abs(n) >= 1_000_000:
22
+ return f"${n / 1_000_000:.2f}M"
23
+ if abs(n) >= 1_000:
24
+ return f"${n / 1_000:.2f}K"
25
+ return f"${n:.6f}"
26
+
27
+
28
+ def render_stream(events: Iterable) -> tuple[str, dict]:
29
+ """Live-render markdown content; return (full_text, metadata).
30
+
31
+ Generator yields strings (content deltas) and an optional final dict
32
+ (usage + cost from Mesh API's last SSE chunk).
33
+ """
34
+ buf = ""
35
+ meta: dict = {}
36
+ with Live(console=console, refresh_per_second=20) as live:
37
+ for event in events:
38
+ if isinstance(event, str):
39
+ buf += event
40
+ live.update(Markdown(buf))
41
+ elif isinstance(event, dict):
42
+ meta.update(event)
43
+ return buf, meta
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.4
2
+ Name: meshapi-code
3
+ Version: 0.1.0
4
+ Summary: Terminal chat for Mesh API — OpenAI-compatible LLM gateway
5
+ Project-URL: Homepage, https://meshapi.ai
6
+ Project-URL: Documentation, https://docs.meshapi.ai
7
+ Project-URL: Repository, https://github.com/aifiesta/meshapi-code
8
+ Author: Mesh API
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: anthropic,chat,cli,gateway,llm,mesh,openai
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: httpx>=0.27
24
+ Requires-Dist: prompt-toolkit>=3.0
25
+ Requires-Dist: rich>=13.7
26
+ Description-Content-Type: text/markdown
27
+
28
+ # meshapi-code
29
+
30
+ Terminal chat for [Mesh API](https://meshapi.ai) — the OpenAI-compatible LLM gateway. Streaming responses, live markdown, slash commands, real-time cost.
31
+
32
+ ```
33
+ $ meshapi
34
+ ╭───────────────────────────────╮
35
+ │ meshapi 0.1.0 │
36
+ │ model: anthropic/claude-… │
37
+ │ route: default │
38
+ ╰───────────────────────────────╯
39
+ you > how do I parse SSE in python
40
+ … streamed markdown reply …
41
+ 142 → 318 tok • $0.001234 • session $0.001234
42
+ ```
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pipx install meshapi-code # recommended
48
+ uv tool install meshapi-code # if you use uv
49
+ pip install meshapi-code # plain pip
50
+ ```
51
+
52
+ The PyPI package is `meshapi-code`; the command on your `$PATH` is `meshapi`.
53
+
54
+ Then:
55
+
56
+ ```bash
57
+ export MESHAPI_API_KEY=rsk_your_key_here
58
+ meshapi
59
+ ```
60
+
61
+ Get a key at [meshapi.ai](https://meshapi.ai).
62
+
63
+ ## What it does
64
+
65
+ - **Streaming completions** with live markdown rendering (`rich`)
66
+ - **Real cost per turn** — Mesh API returns `cost` in the SSE tail; we show it
67
+ - **Slash commands** — `/model`, `/route`, `/file`, `/system`, `/cost`, `/clear`
68
+ - **Mid-session model switching** — `/model openai/gpt-4o-mini`
69
+ - **Smart routing** — `/route cheapest` lets the gateway pick (Mesh-specific)
70
+ - **Persistent input history** — up-arrow recalls past prompts
71
+ - **Config + env-var override** — `~/.meshapi/config.json`, `MESHAPI_API_KEY`
72
+
73
+ ## Slash commands
74
+
75
+ | Command | What it does |
76
+ |---|---|
77
+ | `/help` | List commands |
78
+ | `/model <name>` | Switch model (e.g. `anthropic/claude-sonnet-4.5`) |
79
+ | `/route <mode>` | `cheapest`, `fastest`, `balanced`, or `default` |
80
+ | `/file <path>` | Inject a file into the conversation |
81
+ | `/system <text>` | Replace system prompt and reset chat |
82
+ | `/cost` | Show cumulative session spend |
83
+ | `/clear` | Reset conversation |
84
+ | `/exit` | Quit |
85
+
86
+ ## Config
87
+
88
+ `~/.meshapi/config.json`:
89
+
90
+ ```json
91
+ {
92
+ "base_url": "https://api.meshapi.ai/v1",
93
+ "model": "anthropic/claude-sonnet-4.5",
94
+ "system": "You are a helpful coding assistant. Be concise.",
95
+ "route": null
96
+ }
97
+ ```
98
+
99
+ The API key is read from `MESHAPI_API_KEY` (preferred) or stored in the same file.
100
+
101
+ ## Why it exists
102
+
103
+ Mesh API is OpenAI-compatible, so any generic chat CLI works against it. `meshapi` adds two things a generic CLI can't: (1) the gateway-only `cost` field shown after every turn, and (2) routing controls (`/route cheapest`) that hit Mesh's gateway-side model selection.
104
+
105
+ ## Roadmap
106
+
107
+ - v0.2 — tool calling, repo-aware mode, diff apply, `npm i -g meshapi-code`
108
+ - v0.3 — Homebrew tap, curl|sh installer at `meshapi.ai/install.sh`
109
+
110
+ ## License
111
+
112
+ MIT
@@ -0,0 +1,12 @@
1
+ meshapi/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ meshapi/__main__.py,sha256=MSmt_5Xg84uHqzTN38JwgseJK8rsJn_11A8WD99VtEo,61
3
+ meshapi/cli.py,sha256=ySXoOIv1b4pcY1b92LmA1rgZFlPiucW1BIBbEAGxwiU,3451
4
+ meshapi/client.py,sha256=BKRxbMAtgGSj9Y4pf0yof157DLZ95VorX--2QXiIsFY,1548
5
+ meshapi/commands.py,sha256=0ZiIh9n94f6ix-hH3u4v3gW7N8sLSWsPv9sdDPEUbg0,3040
6
+ meshapi/config.py,sha256=DcqOjZtAufuSDg2vDs0lsBynRjThL_8znLOl_Y2_PN4,1159
7
+ meshapi/render.py,sha256=jEpqYxvlTXm5oNeZYJ8X7nfOiCjiTxMURGUSk__M-f0,1321
8
+ meshapi_code-0.1.0.dist-info/METADATA,sha256=5YQtmiQVoB-_CeYmhQm1_sshCWGiLaUnoPAsLZnDdmU,3765
9
+ meshapi_code-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
10
+ meshapi_code-0.1.0.dist-info/entry_points.txt,sha256=ZCXZ_SgrhWIQEHSjAXz0pUlyGbIQKZ68vp_Cg1Y0rME,45
11
+ meshapi_code-0.1.0.dist-info/licenses/LICENSE,sha256=oALrQSPnF5cbhoBcSv6uDDsPUGl7q5Y2AL-dJ--wzt8,1065
12
+ meshapi_code-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ meshapi = meshapi.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mesh API
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.