tokensaver-cli 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) TokenSaver
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.
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: tokensaver-cli
3
+ Version: 0.1.0
4
+ Summary: TokenSaver CLI — route AI agents (Claude Code, Cursor, Codex) through the SaaS control plane
5
+ Author: TokenSaver
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://platform.tokensaver.fr
8
+ Project-URL: Documentation, https://tokensaver.fr/sdk-api
9
+ Project-URL: PyPI, https://pypi.org/project/tokensaver-cli/
10
+ Keywords: tokensaver,llm,cli,claude,cursor,mcp,agents
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Environment :: Console
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Provides-Extra: dev
22
+ Requires-Dist: build>=1.0.0; extra == "dev"
23
+ Requires-Dist: pytest>=7.4.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
25
+ Requires-Dist: twine>=5.0.0; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # TokenSaver CLI (`tokensaver-cli`)
29
+
30
+ Console command **`tokensaver`** to route AI agents through the **TokenSaver SaaS control plane** (`api.tokensaver.fr`) — cache, compression, PII, MCP gateway, observability.
31
+
32
+ Companion package to **[`tokensaver-sdk`](https://pypi.org/project/tokensaver-sdk/)** (Python API client). The CLI configures your **local machine**; the pipeline runs on TokenSaver servers.
33
+
34
+ **Get started:** sign up at [platform.tokensaver.fr](https://platform.tokensaver.fr), create a **`ts_…`** API key, then:
35
+
36
+ ```bash
37
+ pip install tokensaver-cli
38
+ export TOKENSAVER_API_KEY=ts_your_key
39
+ tokensaver route claude --launch
40
+ tokensaver doctor
41
+ ```
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ pip install tokensaver-cli
47
+ ```
48
+
49
+ Development inside the monorepo:
50
+
51
+ ```bash
52
+ cd packages/cli
53
+ python -m venv .venv && . .venv/bin/activate
54
+ pip install -e ".[dev]"
55
+ ```
56
+
57
+ **Requirements:** Python ≥ 3.10, no extra runtime dependencies (stdlib only).
58
+
59
+ ## Commands
60
+
61
+ | Command | Purpose |
62
+ |---------|---------|
63
+ | `tokensaver route claude` | Configure Claude Code (`~/.claude/settings.json` + `.mcp.json`) |
64
+ | `tokensaver route claude --launch` | Configure + start `claude` |
65
+ | `tokensaver route cursor` | Write `.cursor/mcp.json` + print Override URL steps |
66
+ | `tokensaver route codex` | Print OpenAI-compat env vars for Codex |
67
+ | `tokensaver route proxy` | Show base URLs for LangChain / OpenAI SDK / your code |
68
+ | `tokensaver unroute <target>` | Restore backed-up config |
69
+ | `tokensaver doctor` | Check API key and SaaS endpoint reachability |
70
+
71
+ ## SaaS defaults (no local server)
72
+
73
+ | Surface | URL |
74
+ |---------|-----|
75
+ | API | `https://api.tokensaver.fr` |
76
+ | OpenAI-compat | `https://api.tokensaver.fr/openai/v1` |
77
+ | Anthropic-compat | `https://api.tokensaver.fr/anthropic` |
78
+ | MCP tools | `https://mcp.tokensaver.fr/mcp` |
79
+ | MCP gateway | `https://gateway.tokensaver.fr/mcp` |
80
+
81
+ Override with `TOKENSAVER_API_URL`, `TOKENSAVER_MCP_URL`, etc. if you use a private deployment.
82
+
83
+ ## Environment
84
+
85
+ ```bash
86
+ export TOKENSAVER_API_KEY=ts_… # required
87
+ # optional scope for MCP gateway headers:
88
+ export X-Organisation-ID=…
89
+ export X-Workspace-ID=…
90
+ ```
91
+
92
+ ## Related packages
93
+
94
+ | PyPI package | Role |
95
+ |--------------|------|
96
+ | **`tokensaver-cli`** | This package — `tokensaver route` / `doctor` |
97
+ | **`tokensaver-sdk`** | Python API client — `TokenSaver(api_key=…).ask(…)` |
98
+
99
+ API reference (public): [tokensaver.fr/sdk-api](https://tokensaver.fr/sdk-api)
100
+
101
+ ## Tests
102
+
103
+ ```bash
104
+ cd packages/cli && pip install -e ".[dev]" && pytest -q
105
+ ```
106
+
107
+ ## Publishing to PyPI
108
+
109
+ Maintainers: see **[`docs/PYPI-CLI-RELEASE.md`](../../docs/PYPI-CLI-RELEASE.md)**.
110
+
111
+ Tag format: **`cli-vX.Y.Z`** (version in `src/tokensaver_cli/__init__.py`).
@@ -0,0 +1,84 @@
1
+ # TokenSaver CLI (`tokensaver-cli`)
2
+
3
+ Console command **`tokensaver`** to route AI agents through the **TokenSaver SaaS control plane** (`api.tokensaver.fr`) — cache, compression, PII, MCP gateway, observability.
4
+
5
+ Companion package to **[`tokensaver-sdk`](https://pypi.org/project/tokensaver-sdk/)** (Python API client). The CLI configures your **local machine**; the pipeline runs on TokenSaver servers.
6
+
7
+ **Get started:** sign up at [platform.tokensaver.fr](https://platform.tokensaver.fr), create a **`ts_…`** API key, then:
8
+
9
+ ```bash
10
+ pip install tokensaver-cli
11
+ export TOKENSAVER_API_KEY=ts_your_key
12
+ tokensaver route claude --launch
13
+ tokensaver doctor
14
+ ```
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pip install tokensaver-cli
20
+ ```
21
+
22
+ Development inside the monorepo:
23
+
24
+ ```bash
25
+ cd packages/cli
26
+ python -m venv .venv && . .venv/bin/activate
27
+ pip install -e ".[dev]"
28
+ ```
29
+
30
+ **Requirements:** Python ≥ 3.10, no extra runtime dependencies (stdlib only).
31
+
32
+ ## Commands
33
+
34
+ | Command | Purpose |
35
+ |---------|---------|
36
+ | `tokensaver route claude` | Configure Claude Code (`~/.claude/settings.json` + `.mcp.json`) |
37
+ | `tokensaver route claude --launch` | Configure + start `claude` |
38
+ | `tokensaver route cursor` | Write `.cursor/mcp.json` + print Override URL steps |
39
+ | `tokensaver route codex` | Print OpenAI-compat env vars for Codex |
40
+ | `tokensaver route proxy` | Show base URLs for LangChain / OpenAI SDK / your code |
41
+ | `tokensaver unroute <target>` | Restore backed-up config |
42
+ | `tokensaver doctor` | Check API key and SaaS endpoint reachability |
43
+
44
+ ## SaaS defaults (no local server)
45
+
46
+ | Surface | URL |
47
+ |---------|-----|
48
+ | API | `https://api.tokensaver.fr` |
49
+ | OpenAI-compat | `https://api.tokensaver.fr/openai/v1` |
50
+ | Anthropic-compat | `https://api.tokensaver.fr/anthropic` |
51
+ | MCP tools | `https://mcp.tokensaver.fr/mcp` |
52
+ | MCP gateway | `https://gateway.tokensaver.fr/mcp` |
53
+
54
+ Override with `TOKENSAVER_API_URL`, `TOKENSAVER_MCP_URL`, etc. if you use a private deployment.
55
+
56
+ ## Environment
57
+
58
+ ```bash
59
+ export TOKENSAVER_API_KEY=ts_… # required
60
+ # optional scope for MCP gateway headers:
61
+ export X-Organisation-ID=…
62
+ export X-Workspace-ID=…
63
+ ```
64
+
65
+ ## Related packages
66
+
67
+ | PyPI package | Role |
68
+ |--------------|------|
69
+ | **`tokensaver-cli`** | This package — `tokensaver route` / `doctor` |
70
+ | **`tokensaver-sdk`** | Python API client — `TokenSaver(api_key=…).ask(…)` |
71
+
72
+ API reference (public): [tokensaver.fr/sdk-api](https://tokensaver.fr/sdk-api)
73
+
74
+ ## Tests
75
+
76
+ ```bash
77
+ cd packages/cli && pip install -e ".[dev]" && pytest -q
78
+ ```
79
+
80
+ ## Publishing to PyPI
81
+
82
+ Maintainers: see **[`docs/PYPI-CLI-RELEASE.md`](../../docs/PYPI-CLI-RELEASE.md)**.
83
+
84
+ Tag format: **`cli-vX.Y.Z`** (version in `src/tokensaver_cli/__init__.py`).
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tokensaver-cli"
7
+ dynamic = ["version"]
8
+ description = "TokenSaver CLI — route AI agents (Claude Code, Cursor, Codex) through the SaaS control plane"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "TokenSaver" }]
14
+ keywords = ["tokensaver", "llm", "cli", "claude", "cursor", "mcp", "agents"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Environment :: Console",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ ]
24
+ dependencies = []
25
+
26
+ [project.scripts]
27
+ tokensaver = "tokensaver_cli.main:main"
28
+
29
+ [project.optional-dependencies]
30
+ dev = [
31
+ "build>=1.0.0",
32
+ "pytest>=7.4.0",
33
+ "ruff>=0.1.0",
34
+ "twine>=5.0.0",
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://platform.tokensaver.fr"
39
+ Documentation = "https://tokensaver.fr/sdk-api"
40
+ PyPI = "https://pypi.org/project/tokensaver-cli/"
41
+
42
+ [tool.setuptools.packages.find]
43
+ where = ["src"]
44
+
45
+ [tool.setuptools.dynamic]
46
+ version = { attr = "tokensaver_cli.__version__" }
47
+
48
+ [tool.pytest.ini_options]
49
+ testpaths = ["tests"]
50
+ pythonpath = ["src"]
51
+
52
+ [tool.ruff]
53
+ line-length = 100
54
+ target-version = "py310"
55
+
56
+ [tool.ruff.lint]
57
+ select = ["E", "F", "I", "UP"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,8 @@
1
+ """
2
+ TokenSaver CLI — route agent traffic through the TokenSaver SaaS control plane.
3
+
4
+ Published on PyPI as ``tokensaver-cli``; installs the ``tokensaver`` console command.
5
+ No server-side pipeline code — configures local agents to call api.tokensaver.fr.
6
+ """
7
+
8
+ __version__ = "0.1.0"
@@ -0,0 +1,257 @@
1
+ """Route / unroute handlers per agent or integration mode."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from tokensaver_cli.config import MCP_GATEWAY_KEY, MCP_TOOLS_KEY, RouteConfig
11
+ from tokensaver_cli.json_merge import deep_merge, read_json, write_json
12
+ from tokensaver_cli.state import RoutedFile, backup_file, clear_route, load_state, record_route, restore_file
13
+
14
+
15
+ def _begin_route_files(target: str, paths: list[Path]) -> list[RoutedFile]:
16
+ """Backup config files once per target; preserve originals on re-route."""
17
+ existing = load_state().get(target)
18
+ if existing and existing.files:
19
+ return existing.files
20
+ routed: list[RoutedFile] = []
21
+ for path in paths:
22
+ backup = backup_file(path) if path.is_file() else None
23
+ routed.append(RoutedFile(path=str(path), backup=backup or ""))
24
+ return routed
25
+
26
+
27
+ def _mcp_tools_entry(cfg: RouteConfig) -> dict:
28
+ return {
29
+ "type": "http",
30
+ "url": cfg.mcp_tools_url,
31
+ "headers": {"Authorization": f"Bearer {cfg.api_key}"},
32
+ }
33
+
34
+
35
+ def _mcp_gateway_entry(cfg: RouteConfig, client: str) -> dict:
36
+ headers: dict[str, str] = {
37
+ "Authorization": f"Bearer {cfg.api_key}",
38
+ "X-Tokensaver-Client": client,
39
+ }
40
+ if cfg.organisation_id:
41
+ headers["X-Organisation-ID"] = cfg.organisation_id
42
+ if cfg.workspace_id:
43
+ headers["X-Workspace-ID"] = cfg.workspace_id
44
+ return {
45
+ "type": "http",
46
+ "url": cfg.gateway_url,
47
+ "headers": headers,
48
+ }
49
+
50
+
51
+ def _restore_routed_files(files: list[RoutedFile]) -> None:
52
+ for item in files:
53
+ path = Path(item.path)
54
+ if not item.backup:
55
+ path.unlink(missing_ok=True)
56
+ continue
57
+ restore_file(path, item.backup)
58
+
59
+
60
+ def route_claude(cfg: RouteConfig, *, launch: bool, extra_args: list[str]) -> int:
61
+ settings_path = Path.home() / ".claude" / "settings.json"
62
+ mcp_path = Path.cwd() / ".mcp.json"
63
+ routed = _begin_route_files("claude", [settings_path, mcp_path])
64
+
65
+ settings = read_json(settings_path)
66
+ env_patch = {
67
+ "ANTHROPIC_BASE_URL": cfg.anthropic_base_url,
68
+ "ANTHROPIC_AUTH_TOKEN": cfg.api_key,
69
+ "ANTHROPIC_API_KEY": "",
70
+ "TOKENSAVER_API_KEY": cfg.api_key,
71
+ }
72
+ settings = deep_merge(settings, {"env": env_patch})
73
+ write_json(settings_path, settings)
74
+
75
+ data = read_json(mcp_path)
76
+ patch = {
77
+ "mcpServers": {
78
+ MCP_TOOLS_KEY: _mcp_tools_entry(cfg),
79
+ MCP_GATEWAY_KEY: _mcp_gateway_entry(cfg, "claude-code/1.0"),
80
+ }
81
+ }
82
+ write_json(mcp_path, deep_merge(data, patch))
83
+
84
+ record_route("claude", routed)
85
+ _print_routed("Claude Code", cfg, client="claude-code/1.0")
86
+
87
+ if launch or extra_args:
88
+ env = os.environ.copy()
89
+ env.update(env_patch)
90
+ return subprocess.call(["claude", *extra_args], env=env)
91
+ return 0
92
+
93
+
94
+ def unroute_claude() -> int:
95
+ rec = clear_route("claude")
96
+ if not rec:
97
+ print("Claude Code is not routed through TokenSaver.", file=sys.stderr)
98
+ return 1
99
+ _restore_routed_files(rec.files)
100
+ print("Claude Code unrouted — original config restored.")
101
+ return 0
102
+
103
+
104
+ def route_cursor(cfg: RouteConfig) -> int:
105
+ mcp_path = Path.cwd() / ".cursor" / "mcp.json"
106
+ routed = _begin_route_files("cursor", [mcp_path])
107
+
108
+ data = read_json(mcp_path)
109
+ patch = {
110
+ "mcpServers": {
111
+ MCP_TOOLS_KEY: _mcp_tools_entry(cfg),
112
+ MCP_GATEWAY_KEY: _mcp_gateway_entry(cfg, "cursor/1.0"),
113
+ }
114
+ }
115
+ mcp_path.parent.mkdir(parents=True, exist_ok=True)
116
+ write_json(mcp_path, deep_merge(data, patch))
117
+ record_route("cursor", routed)
118
+
119
+ print("Cursor routed through TokenSaver.")
120
+ print()
121
+ print("MCP config written:", mcp_path)
122
+ print()
123
+ print("Manual step — Cursor Settings → Models → Override OpenAI Base URL:")
124
+ print(f" {cfg.openai_base_url}")
125
+ print()
126
+ print("Use a TokenSaver model id (e.g. openai/gpt-4o or anthropic/claude-sonnet-4-6).")
127
+ print("Restart Cursor → Settings → Tools & MCP → enable tokensaver-route-* servers.")
128
+ print()
129
+ print("Note: native Cursor Agent/Autocomplete may still bypass the override (~40% coverage).")
130
+ return 0
131
+
132
+
133
+ def unroute_cursor() -> int:
134
+ rec = clear_route("cursor")
135
+ if not rec:
136
+ print("Cursor is not routed through TokenSaver.", file=sys.stderr)
137
+ return 1
138
+ _restore_routed_files(rec.files)
139
+ print("Cursor unrouted — .cursor/mcp.json restored.")
140
+ print("Remove Override OpenAI Base URL in Cursor Settings if you set it manually.")
141
+ return 0
142
+
143
+
144
+ def route_codex(cfg: RouteConfig, *, launch: bool, extra_args: list[str]) -> int:
145
+ env_patch = {
146
+ "OPENAI_BASE_URL": cfg.openai_base_url,
147
+ "OPENAI_API_KEY": cfg.api_key,
148
+ "TOKENSAVER_API_KEY": cfg.api_key,
149
+ }
150
+ routed = [RoutedFile(path="__env__", backup="")]
151
+ record_route("codex", routed)
152
+ _print_routed("OpenAI Codex", cfg, client="codex/1.0", env_only=env_patch)
153
+
154
+ if launch or extra_args:
155
+ env = os.environ.copy()
156
+ env.update(env_patch)
157
+ return subprocess.call(["codex", *extra_args], env=env)
158
+ return 0
159
+
160
+
161
+ def unroute_codex() -> int:
162
+ rec = clear_route("codex")
163
+ if not rec:
164
+ print("Codex is not routed through TokenSaver.", file=sys.stderr)
165
+ return 1
166
+ print("Codex unrouted.")
167
+ print("Unset OPENAI_BASE_URL and OPENAI_API_KEY if you exported them in your shell profile.")
168
+ return 0
169
+
170
+
171
+ def route_proxy(cfg: RouteConfig) -> int:
172
+ record_route("proxy", [])
173
+ print("TokenSaver API proxy endpoints (OpenAI-compatible clients):")
174
+ print(f" OpenAI base URL : {cfg.openai_base_url}")
175
+ print(f" Anthropic base : {cfg.anthropic_base_url}")
176
+ print(f" API key : Bearer {cfg.api_key[:8]}…")
177
+ print()
178
+ print("Point any OpenAI-compatible SDK (LangChain, Agno, LiteLLM, your code) at the base URL above.")
179
+ print()
180
+ print("Optional — capture all outbound HTTPS (advanced, self-hosted egress proxy):")
181
+ print(" export HTTPS_PROXY=http://127.0.0.1:8888")
182
+ print(" export TOKENSAVER_API_KEY=ts_…")
183
+ return 0
184
+
185
+
186
+ def unroute_proxy() -> int:
187
+ if not clear_route("proxy"):
188
+ print("Proxy route state was not set.", file=sys.stderr)
189
+ return 1
190
+ print("Proxy route cleared. Unset HTTPS_PROXY if you configured egress capture.")
191
+ return 0
192
+
193
+
194
+ def route_mcp(cfg: RouteConfig, *, target: str | None) -> int:
195
+ if not target:
196
+ print("MCP gateway (SaaS): gateway URL is already injected in .mcp.json by route claude/cursor.")
197
+ print()
198
+ print("Local stdio wrapper (advanced) requires tokensaver-mcp-gateway on PATH:")
199
+ print()
200
+ print(" tokensaver-mcp-gateway \\")
201
+ print(' --target "npx -y @modelcontextprotocol/server-filesystem /path/to/project" \\')
202
+ print(' --workspace "dev-local"')
203
+ print()
204
+ print("Environment:")
205
+ print(f" TOKENSAVER_API_KEY={cfg.api_key[:8]}…")
206
+ print(f" TOKENSAVER_API_BASE_URL={cfg.api_v1_base}")
207
+ return 0
208
+
209
+ cmd = [
210
+ "tokensaver-mcp-gateway",
211
+ "--target",
212
+ target,
213
+ "--workspace",
214
+ cfg.workspace_id or "route-cli",
215
+ ]
216
+ env = os.environ.copy()
217
+ env.setdefault("TOKENSAVER_API_KEY", cfg.api_key)
218
+ env.setdefault("TOKENSAVER_API_BASE_URL", cfg.api_v1_base)
219
+ record_route("mcp", [])
220
+ print("Starting MCP Trust Gateway:", " ".join(cmd))
221
+ return subprocess.call(cmd, env=env)
222
+
223
+
224
+ def unroute_mcp() -> int:
225
+ if not clear_route("mcp"):
226
+ print("MCP route state was not set.", file=sys.stderr)
227
+ return 1
228
+ print("MCP route cleared. Stop any running tokensaver-mcp-gateway process manually.")
229
+ return 0
230
+
231
+
232
+ def _print_routed(
233
+ label: str,
234
+ cfg: RouteConfig,
235
+ *,
236
+ client: str,
237
+ env_only: dict[str, str] | None = None,
238
+ ) -> None:
239
+ print(f"{label} routed through TokenSaver.")
240
+ print()
241
+ print(" Control plane:")
242
+ print(f" LLM (Anthropic) : {cfg.anthropic_base_url}")
243
+ print(f" LLM (OpenAI) : {cfg.openai_base_url}")
244
+ print(f" MCP tools : {cfg.mcp_tools_url}")
245
+ print(f" MCP gateway : {cfg.gateway_url}")
246
+ print(f" Client tag : {client}")
247
+ if env_only:
248
+ print()
249
+ print(" Export in your shell (or use --launch):")
250
+ for key, value in env_only.items():
251
+ if key == "TOKENSAVER_API_KEY":
252
+ print(f" export {key}={value[:8]}…")
253
+ else:
254
+ print(f" export {key}={value}")
255
+ print()
256
+ print(" Undo: tokensaver unroute", label.split()[0].lower())
257
+ print(" Check: tokensaver doctor")
@@ -0,0 +1,36 @@
1
+ """Retro ASCII banner shown when the ``tokensaver`` command starts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+
8
+ from tokensaver_cli import __version__
9
+
10
+ _BANNER = r"""
11
+ ████████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗███████╗ █████╗ ██╗ ██╗███████╗██████╗
12
+ ╚══██╔══╝██╔═══██╗██║ ██║██╔════╝████╗ ██║██╔════╝██╔══██╗██║ ██║██╔════╝██╔══██╗
13
+ ██║ ██║ ██║███████║█████╗ ██╔██╗ ██║███████╗███████║██║ ██║█████╗ ██████╔╝
14
+ ██║ ██║ ██║██╔══██║██╔══╝ ██║╚██╗██║╚════██║██╔══██║╚██╗ ██╔╝██╔══╝ ██╔══██╗
15
+ ██║ ╚██████╔╝██║ ██║███████╗██║ ╚████║███████║██║ ██║ ╚████╔╝ ███████╗██║ ██║
16
+ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚══════╝╚═╝ ╚═╝
17
+
18
+ ┌─────────────────────────────────────────────────────────────┐
19
+ │ CONTROL PLANE · route · compress · govern · save │
20
+ │ Claude Code · Cursor · Codex · LangChain · your code │
21
+ └─────────────────────────────────────────────────────────────┘
22
+ """
23
+
24
+
25
+ def banner_enabled() -> bool:
26
+ flag = (os.environ.get("TOKENSAVER_NO_BANNER") or "").strip().lower()
27
+ return flag not in ("1", "true", "yes", "on")
28
+
29
+
30
+ def print_banner(*, file=None) -> None:
31
+ if not banner_enabled():
32
+ return
33
+ out = file if file is not None else sys.stdout
34
+ print(_BANNER, file=out)
35
+ print(f" TokenSaver CLI v{__version__} — https://platform.tokensaver.fr", file=out)
36
+ print(file=out)
@@ -0,0 +1,78 @@
1
+ """Resolved URLs and credentials for ``tokensaver route``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+
8
+ PROD_API_HOST = "https://api.tokensaver.fr"
9
+ PROD_MCP_URL = "https://mcp.tokensaver.fr/mcp"
10
+ PROD_GATEWAY_URL = "https://gateway.tokensaver.fr/mcp"
11
+
12
+ MCP_TOOLS_KEY = "tokensaver-route-tools"
13
+ MCP_GATEWAY_KEY = "tokensaver-route-gateway"
14
+
15
+
16
+ def _strip_trailing_slash(url: str) -> str:
17
+ return url.rstrip("/")
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class RouteConfig:
22
+ api_key: str
23
+ api_host: str
24
+ anthropic_base_url: str
25
+ openai_base_url: str
26
+ mcp_tools_url: str
27
+ gateway_url: str
28
+ organisation_id: str | None
29
+ workspace_id: str | None
30
+
31
+ @property
32
+ def api_v1_base(self) -> str:
33
+ host = _strip_trailing_slash(self.api_host)
34
+ if host.endswith("/api/v1"):
35
+ return host
36
+ return f"{host}/api/v1"
37
+
38
+
39
+ def resolve_route_config() -> RouteConfig:
40
+ api_key = (os.environ.get("TOKENSAVER_API_KEY") or "").strip()
41
+ if not api_key:
42
+ raise RouteConfigError(
43
+ "TOKENSAVER_API_KEY is required. "
44
+ "Create a key at https://platform.tokensaver.fr → Paramètres → TokenSaver API keys."
45
+ )
46
+
47
+ api_host = _strip_trailing_slash(
48
+ os.environ.get("TOKENSAVER_API_URL") or os.environ.get("TOKENSAVER_API_BASE_URL") or PROD_API_HOST
49
+ )
50
+ if api_host.endswith("/api/v1"):
51
+ api_host = api_host[: -len("/api/v1")]
52
+
53
+ anthropic_base = _strip_trailing_slash(
54
+ os.environ.get("TOKENSAVER_ANTHROPIC_BASE_URL") or f"{api_host}/anthropic"
55
+ )
56
+ openai_base = _strip_trailing_slash(
57
+ os.environ.get("TOKENSAVER_OPENAI_BASE_URL") or f"{api_host}/openai/v1"
58
+ )
59
+ mcp_url = os.environ.get("TOKENSAVER_MCP_URL") or PROD_MCP_URL
60
+ gateway_url = os.environ.get("TOKENSAVER_GATEWAY_URL") or PROD_GATEWAY_URL
61
+
62
+ org_id = (os.environ.get("X-Organisation-ID") or os.environ.get("X-Team-ID") or "").strip() or None
63
+ workspace_id = (os.environ.get("X-Workspace-ID") or "").strip() or None
64
+
65
+ return RouteConfig(
66
+ api_key=api_key,
67
+ api_host=api_host,
68
+ anthropic_base_url=anthropic_base,
69
+ openai_base_url=openai_base,
70
+ mcp_tools_url=mcp_url,
71
+ gateway_url=gateway_url,
72
+ organisation_id=org_id,
73
+ workspace_id=workspace_id,
74
+ )
75
+
76
+
77
+ class RouteConfigError(Exception):
78
+ """Missing or invalid route configuration."""
@@ -0,0 +1,61 @@
1
+ """Health checks for routed integrations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import urllib.error
7
+ import urllib.request
8
+
9
+ from tokensaver_cli.config import RouteConfigError, resolve_route_config
10
+ from tokensaver_cli.state import load_state
11
+
12
+
13
+ def _probe(url: str, headers: dict[str, str] | None = None) -> tuple[bool, str]:
14
+ req = urllib.request.Request(url, method="GET", headers=headers or {})
15
+ try:
16
+ with urllib.request.urlopen(req, timeout=10) as resp:
17
+ return True, f"HTTP {resp.status}"
18
+ except urllib.error.HTTPError as exc:
19
+ if exc.code in (401, 405):
20
+ return True, f"HTTP {exc.code} (reachable, auth required)"
21
+ return False, f"HTTP {exc.code}"
22
+ except Exception as exc: # noqa: BLE001 — doctor surfaces any transport error
23
+ return False, str(exc)
24
+
25
+
26
+ def run_doctor() -> int:
27
+ try:
28
+ cfg = resolve_route_config()
29
+ except RouteConfigError as exc:
30
+ print(f"FAIL config — {exc}", file=sys.stderr)
31
+ return 1
32
+
33
+ ok = True
34
+ print("TokenSaver route doctor")
35
+ print()
36
+
37
+ checks = [
38
+ ("API key", True, f"{cfg.api_key[:8]}… ({len(cfg.api_key)} chars)"),
39
+ ("OpenAI-compat", *_probe(f"{cfg.openai_base_url}/models", {"Authorization": f"Bearer {cfg.api_key}"})),
40
+ ("Anthropic-compat", *_probe(f"{cfg.anthropic_base_url}/v1/models", {"x-api-key": cfg.api_key})),
41
+ ("MCP tools", *_probe(cfg.mcp_tools_url, {"Authorization": f"Bearer {cfg.api_key}"})),
42
+ ("MCP gateway", *_probe(cfg.gateway_url, {"Authorization": f"Bearer {cfg.api_key}"})),
43
+ ]
44
+
45
+ for name, passed, detail in checks:
46
+ status = "OK" if passed else "FAIL"
47
+ print(f" {status:4} {name:16} {detail}")
48
+ if not passed:
49
+ ok = False
50
+
51
+ routes = load_state()
52
+ if routes:
53
+ print()
54
+ print(" Active routes:")
55
+ for target, rec in sorted(routes.items()):
56
+ print(f" - {target} (since {rec.routed_at})")
57
+ else:
58
+ print()
59
+ print(" No active routes. Run: tokensaver route claude")
60
+
61
+ return 0 if ok else 1
@@ -0,0 +1,28 @@
1
+ """Small JSON helpers for merging agent config files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+
10
+ def read_json(path: Path) -> dict[str, Any]:
11
+ if not path.is_file():
12
+ return {}
13
+ return json.loads(path.read_text(encoding="utf-8"))
14
+
15
+
16
+ def write_json(path: Path, data: dict[str, Any]) -> None:
17
+ path.parent.mkdir(parents=True, exist_ok=True)
18
+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
19
+
20
+
21
+ def deep_merge(base: dict[str, Any], patch: dict[str, Any]) -> dict[str, Any]:
22
+ out = dict(base)
23
+ for key, value in patch.items():
24
+ if key in out and isinstance(out[key], dict) and isinstance(value, dict):
25
+ out[key] = deep_merge(out[key], value)
26
+ else:
27
+ out[key] = value
28
+ return out
@@ -0,0 +1,150 @@
1
+ """CLI entrypoint: tokensaver route | unroute | doctor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from tokensaver_cli.agents import (
9
+ route_claude,
10
+ route_codex,
11
+ route_cursor,
12
+ route_mcp,
13
+ route_proxy,
14
+ unroute_claude,
15
+ unroute_codex,
16
+ unroute_cursor,
17
+ unroute_mcp,
18
+ unroute_proxy,
19
+ )
20
+ from tokensaver_cli.banner import print_banner
21
+ from tokensaver_cli.config import RouteConfigError, resolve_route_config
22
+ from tokensaver_cli.doctor import run_doctor
23
+
24
+ ROUTE_TARGETS = ("claude", "cursor", "codex", "proxy", "mcp")
25
+ UNROUTE_TARGETS = ("claude", "cursor", "codex", "proxy", "mcp")
26
+
27
+ DOCS_URL = "https://tokensaver.fr/sdk-api"
28
+
29
+
30
+ def print_usage() -> None:
31
+ print(
32
+ f"""TokenSaver CLI — route agent traffic through the control plane
33
+
34
+ Usage:
35
+ tokensaver route <target> [options] [-- extra-args...]
36
+ tokensaver unroute <target>
37
+ tokensaver doctor
38
+
39
+ Targets:
40
+ claude Claude Code — settings.json + .mcp.json (+ optional launch)
41
+ cursor Cursor — writes .cursor/mcp.json + prints Override URL steps
42
+ codex OpenAI Codex — prints env vars (+ optional launch)
43
+ proxy Print OpenAI/Anthropic base URLs for any compatible client
44
+ mcp MCP Trust Gateway — SaaS URL or local stdio wrapper
45
+
46
+ Options (route claude | codex):
47
+ --launch Start the agent after routing
48
+
49
+ Options (route mcp):
50
+ --target CMD Upstream MCP command (local tokensaver-mcp-gateway)
51
+
52
+ Environment:
53
+ TOKENSAVER_API_KEY Required — ts_… API key
54
+ TOKENSAVER_API_URL API host (default https://api.tokensaver.fr)
55
+ TOKENSAVER_OPENAI_BASE_URL Override OpenAI-compat base
56
+ TOKENSAVER_ANTHROPIC_BASE_URL Override Anthropic-compat base
57
+ TOKENSAVER_MCP_URL MCP tools URL (default mcp.tokensaver.fr)
58
+ TOKENSAVER_GATEWAY_URL MCP gateway URL (default gateway.tokensaver.fr)
59
+ X-Organisation-ID Optional scope header for gateway
60
+ X-Workspace-ID Optional scope header for gateway
61
+
62
+ Examples:
63
+ tokensaver route claude --launch
64
+ tokensaver route cursor
65
+ tokensaver route proxy
66
+ tokensaver unroute claude
67
+ tokensaver doctor
68
+
69
+ Install: pip install tokensaver-cli
70
+ Docs: {DOCS_URL}
71
+ """
72
+ )
73
+
74
+
75
+ def build_parser() -> argparse.ArgumentParser:
76
+ parser = argparse.ArgumentParser(
77
+ prog="tokensaver",
78
+ description="Route AI agents through TokenSaver (cache, compression, PII, governance).",
79
+ add_help=False,
80
+ )
81
+ parser.add_argument("command", nargs="?", choices=("route", "unroute", "doctor", "help"))
82
+ parser.add_argument("target", nargs="?", choices=ROUTE_TARGETS)
83
+ parser.add_argument("--launch", action="store_true", help="Launch agent after route (claude, codex)")
84
+ parser.add_argument("--target", dest="mcp_target", default=None, help="Upstream MCP for route mcp")
85
+ parser.add_argument("-h", "--help", action="store_true")
86
+ parser.add_argument("remainder", nargs=argparse.REMAINDER)
87
+ return parser
88
+
89
+
90
+ def _split_remainder(remainder: list[str]) -> list[str]:
91
+ if remainder and remainder[0] == "--":
92
+ return remainder[1:]
93
+ return [a for a in remainder if a != "--"]
94
+
95
+
96
+ def main(argv: list[str] | None = None) -> None:
97
+ parser = build_parser()
98
+ args = parser.parse_args(argv)
99
+
100
+ print_banner()
101
+
102
+ if args.help or args.command in (None, "help"):
103
+ print_usage()
104
+ raise SystemExit(0)
105
+
106
+ if args.command == "doctor":
107
+ raise SystemExit(run_doctor())
108
+
109
+ if args.command == "unroute":
110
+ if not args.target:
111
+ print("unroute requires a target:", ", ".join(UNROUTE_TARGETS), file=sys.stderr)
112
+ raise SystemExit(2)
113
+ handlers = {
114
+ "claude": unroute_claude,
115
+ "cursor": unroute_cursor,
116
+ "codex": unroute_codex,
117
+ "proxy": unroute_proxy,
118
+ "mcp": unroute_mcp,
119
+ }
120
+ raise SystemExit(handlers[args.target]())
121
+
122
+ if args.command != "route":
123
+ print_usage()
124
+ raise SystemExit(2)
125
+
126
+ if not args.target:
127
+ print("route requires a target:", ", ".join(ROUTE_TARGETS), file=sys.stderr)
128
+ raise SystemExit(2)
129
+
130
+ try:
131
+ cfg = resolve_route_config()
132
+ except RouteConfigError as exc:
133
+ print(str(exc), file=sys.stderr)
134
+ raise SystemExit(1) from exc
135
+
136
+ extra = _split_remainder(args.remainder)
137
+ launch = args.launch or bool(extra)
138
+
139
+ handlers = {
140
+ "claude": lambda: route_claude(cfg, launch=launch, extra_args=extra),
141
+ "cursor": lambda: route_cursor(cfg),
142
+ "codex": lambda: route_codex(cfg, launch=launch, extra_args=extra),
143
+ "proxy": lambda: route_proxy(cfg),
144
+ "mcp": lambda: route_mcp(cfg, target=args.mcp_target),
145
+ }
146
+ raise SystemExit(handlers[args.target]())
147
+
148
+
149
+ if __name__ == "__main__":
150
+ main()
@@ -0,0 +1,102 @@
1
+ """Persist route state and config backups for ``unroute``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shutil
7
+ from dataclasses import asdict, dataclass
8
+ from datetime import UTC, datetime
9
+ from pathlib import Path
10
+
11
+
12
+ @dataclass
13
+ class RoutedFile:
14
+ path: str
15
+ backup: str
16
+
17
+
18
+ @dataclass
19
+ class RouteRecord:
20
+ target: str
21
+ routed_at: str
22
+ files: list[RoutedFile]
23
+
24
+
25
+ def route_state_dir() -> Path:
26
+ base = Path.home() / ".config" / "tokensaver" / "route"
27
+ base.mkdir(parents=True, exist_ok=True)
28
+ return base
29
+
30
+
31
+ def backups_dir() -> Path:
32
+ path = route_state_dir() / "backups"
33
+ path.mkdir(parents=True, exist_ok=True)
34
+ return path
35
+
36
+
37
+ def state_file() -> Path:
38
+ return route_state_dir() / "state.json"
39
+
40
+
41
+ def load_state() -> dict[str, RouteRecord]:
42
+ path = state_file()
43
+ if not path.is_file():
44
+ return {}
45
+ raw = json.loads(path.read_text(encoding="utf-8"))
46
+ out: dict[str, RouteRecord] = {}
47
+ for target, rec in (raw.get("routes") or {}).items():
48
+ files = [RoutedFile(**f) for f in rec.get("files") or []]
49
+ out[target] = RouteRecord(
50
+ target=target,
51
+ routed_at=rec.get("routed_at", ""),
52
+ files=files,
53
+ )
54
+ return out
55
+
56
+
57
+ def save_state(routes: dict[str, RouteRecord]) -> None:
58
+ payload = {
59
+ "routes": {
60
+ target: {
61
+ "target": rec.target,
62
+ "routed_at": rec.routed_at,
63
+ "files": [asdict(f) for f in rec.files],
64
+ }
65
+ for target, rec in routes.items()
66
+ }
67
+ }
68
+ state_file().write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
69
+
70
+
71
+ def backup_file(source: Path) -> str | None:
72
+ if not source.is_file():
73
+ return None
74
+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
75
+ dest = backups_dir() / f"{source.name}.{stamp}.bak"
76
+ shutil.copy2(source, dest)
77
+ return str(dest)
78
+
79
+
80
+ def restore_file(source: Path, backup_path: str) -> None:
81
+ backup = Path(backup_path)
82
+ if not backup.is_file():
83
+ raise FileNotFoundError(f"Backup not found: {backup_path}")
84
+ source.parent.mkdir(parents=True, exist_ok=True)
85
+ shutil.copy2(backup, source)
86
+
87
+
88
+ def record_route(target: str, files: list[RoutedFile]) -> None:
89
+ routes = load_state()
90
+ routes[target] = RouteRecord(
91
+ target=target,
92
+ routed_at=datetime.now(UTC).isoformat(),
93
+ files=files,
94
+ )
95
+ save_state(routes)
96
+
97
+
98
+ def clear_route(target: str) -> RouteRecord | None:
99
+ routes = load_state()
100
+ rec = routes.pop(target, None)
101
+ save_state(routes)
102
+ return rec
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: tokensaver-cli
3
+ Version: 0.1.0
4
+ Summary: TokenSaver CLI — route AI agents (Claude Code, Cursor, Codex) through the SaaS control plane
5
+ Author: TokenSaver
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://platform.tokensaver.fr
8
+ Project-URL: Documentation, https://tokensaver.fr/sdk-api
9
+ Project-URL: PyPI, https://pypi.org/project/tokensaver-cli/
10
+ Keywords: tokensaver,llm,cli,claude,cursor,mcp,agents
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Environment :: Console
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Provides-Extra: dev
22
+ Requires-Dist: build>=1.0.0; extra == "dev"
23
+ Requires-Dist: pytest>=7.4.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
25
+ Requires-Dist: twine>=5.0.0; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # TokenSaver CLI (`tokensaver-cli`)
29
+
30
+ Console command **`tokensaver`** to route AI agents through the **TokenSaver SaaS control plane** (`api.tokensaver.fr`) — cache, compression, PII, MCP gateway, observability.
31
+
32
+ Companion package to **[`tokensaver-sdk`](https://pypi.org/project/tokensaver-sdk/)** (Python API client). The CLI configures your **local machine**; the pipeline runs on TokenSaver servers.
33
+
34
+ **Get started:** sign up at [platform.tokensaver.fr](https://platform.tokensaver.fr), create a **`ts_…`** API key, then:
35
+
36
+ ```bash
37
+ pip install tokensaver-cli
38
+ export TOKENSAVER_API_KEY=ts_your_key
39
+ tokensaver route claude --launch
40
+ tokensaver doctor
41
+ ```
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ pip install tokensaver-cli
47
+ ```
48
+
49
+ Development inside the monorepo:
50
+
51
+ ```bash
52
+ cd packages/cli
53
+ python -m venv .venv && . .venv/bin/activate
54
+ pip install -e ".[dev]"
55
+ ```
56
+
57
+ **Requirements:** Python ≥ 3.10, no extra runtime dependencies (stdlib only).
58
+
59
+ ## Commands
60
+
61
+ | Command | Purpose |
62
+ |---------|---------|
63
+ | `tokensaver route claude` | Configure Claude Code (`~/.claude/settings.json` + `.mcp.json`) |
64
+ | `tokensaver route claude --launch` | Configure + start `claude` |
65
+ | `tokensaver route cursor` | Write `.cursor/mcp.json` + print Override URL steps |
66
+ | `tokensaver route codex` | Print OpenAI-compat env vars for Codex |
67
+ | `tokensaver route proxy` | Show base URLs for LangChain / OpenAI SDK / your code |
68
+ | `tokensaver unroute <target>` | Restore backed-up config |
69
+ | `tokensaver doctor` | Check API key and SaaS endpoint reachability |
70
+
71
+ ## SaaS defaults (no local server)
72
+
73
+ | Surface | URL |
74
+ |---------|-----|
75
+ | API | `https://api.tokensaver.fr` |
76
+ | OpenAI-compat | `https://api.tokensaver.fr/openai/v1` |
77
+ | Anthropic-compat | `https://api.tokensaver.fr/anthropic` |
78
+ | MCP tools | `https://mcp.tokensaver.fr/mcp` |
79
+ | MCP gateway | `https://gateway.tokensaver.fr/mcp` |
80
+
81
+ Override with `TOKENSAVER_API_URL`, `TOKENSAVER_MCP_URL`, etc. if you use a private deployment.
82
+
83
+ ## Environment
84
+
85
+ ```bash
86
+ export TOKENSAVER_API_KEY=ts_… # required
87
+ # optional scope for MCP gateway headers:
88
+ export X-Organisation-ID=…
89
+ export X-Workspace-ID=…
90
+ ```
91
+
92
+ ## Related packages
93
+
94
+ | PyPI package | Role |
95
+ |--------------|------|
96
+ | **`tokensaver-cli`** | This package — `tokensaver route` / `doctor` |
97
+ | **`tokensaver-sdk`** | Python API client — `TokenSaver(api_key=…).ask(…)` |
98
+
99
+ API reference (public): [tokensaver.fr/sdk-api](https://tokensaver.fr/sdk-api)
100
+
101
+ ## Tests
102
+
103
+ ```bash
104
+ cd packages/cli && pip install -e ".[dev]" && pytest -q
105
+ ```
106
+
107
+ ## Publishing to PyPI
108
+
109
+ Maintainers: see **[`docs/PYPI-CLI-RELEASE.md`](../../docs/PYPI-CLI-RELEASE.md)**.
110
+
111
+ Tag format: **`cli-vX.Y.Z`** (version in `src/tokensaver_cli/__init__.py`).
@@ -0,0 +1,19 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/tokensaver_cli/__init__.py
5
+ src/tokensaver_cli/agents.py
6
+ src/tokensaver_cli/banner.py
7
+ src/tokensaver_cli/config.py
8
+ src/tokensaver_cli/doctor.py
9
+ src/tokensaver_cli/json_merge.py
10
+ src/tokensaver_cli/main.py
11
+ src/tokensaver_cli/state.py
12
+ src/tokensaver_cli.egg-info/PKG-INFO
13
+ src/tokensaver_cli.egg-info/SOURCES.txt
14
+ src/tokensaver_cli.egg-info/dependency_links.txt
15
+ src/tokensaver_cli.egg-info/entry_points.txt
16
+ src/tokensaver_cli.egg-info/requires.txt
17
+ src/tokensaver_cli.egg-info/top_level.txt
18
+ tests/test_banner.py
19
+ tests/test_route_cli.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tokensaver = tokensaver_cli.main:main
@@ -0,0 +1,6 @@
1
+
2
+ [dev]
3
+ build>=1.0.0
4
+ pytest>=7.4.0
5
+ ruff>=0.1.0
6
+ twine>=5.0.0
@@ -0,0 +1 @@
1
+ tokensaver_cli
@@ -0,0 +1,21 @@
1
+ """Banner tests."""
2
+
3
+ from tokensaver_cli.banner import banner_enabled, print_banner
4
+
5
+
6
+ def test_banner_enabled_default(monkeypatch) -> None:
7
+ monkeypatch.delenv("TOKENSAVER_NO_BANNER", raising=False)
8
+ assert banner_enabled() is True
9
+
10
+
11
+ def test_banner_disabled(monkeypatch) -> None:
12
+ monkeypatch.setenv("TOKENSAVER_NO_BANNER", "1")
13
+ assert banner_enabled() is False
14
+
15
+
16
+ def test_print_banner_runs(capsys, monkeypatch) -> None:
17
+ monkeypatch.delenv("TOKENSAVER_NO_BANNER", raising=False)
18
+ print_banner()
19
+ out = capsys.readouterr().out
20
+ assert "TokenSaver CLI" in out
21
+ assert "CONTROL PLANE" in out
@@ -0,0 +1,131 @@
1
+ """Tests for tokensaver route CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+
11
+ from tokensaver_cli.agents import route_claude, route_cursor, unroute_claude, unroute_cursor
12
+ from tokensaver_cli.config import RouteConfig, RouteConfigError, resolve_route_config
13
+ from tokensaver_cli.state import load_state, route_state_dir
14
+
15
+
16
+ @pytest.fixture
17
+ def route_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
18
+ config_home = tmp_path / "home"
19
+ monkeypatch.setenv("HOME", str(config_home))
20
+ monkeypatch.setenv("TOKENSAVER_API_KEY", "ts_test_key_12345678")
21
+ monkeypatch.setenv("TOKENSAVER_API_URL", "https://api.example.test")
22
+ return config_home
23
+
24
+
25
+ @pytest.fixture
26
+ def cfg() -> RouteConfig:
27
+ return RouteConfig(
28
+ api_key="ts_test_key_12345678",
29
+ api_host="https://api.example.test",
30
+ anthropic_base_url="https://api.example.test/anthropic",
31
+ openai_base_url="https://api.example.test/openai/v1",
32
+ mcp_tools_url="https://mcp.example.test/mcp",
33
+ gateway_url="https://gateway.example.test/mcp",
34
+ organisation_id="org-1",
35
+ workspace_id="ws-1",
36
+ )
37
+
38
+
39
+ def test_resolve_route_config_requires_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
40
+ monkeypatch.delenv("TOKENSAVER_API_KEY", raising=False)
41
+ with pytest.raises(RouteConfigError):
42
+ resolve_route_config()
43
+
44
+
45
+ def test_resolve_route_config_strips_api_v1_suffix(monkeypatch: pytest.MonkeyPatch) -> None:
46
+ monkeypatch.setenv("TOKENSAVER_API_KEY", "ts_x")
47
+ monkeypatch.setenv("TOKENSAVER_API_BASE_URL", "https://api.example.test/api/v1")
48
+ resolved = resolve_route_config()
49
+ assert resolved.api_host == "https://api.example.test"
50
+ assert resolved.api_v1_base == "https://api.example.test/api/v1"
51
+
52
+
53
+ def test_route_claude_writes_settings_and_mcp(route_home: Path, cfg: RouteConfig, tmp_path: Path) -> None:
54
+ project = tmp_path / "project"
55
+ project.mkdir()
56
+ old_cwd = os.getcwd()
57
+ try:
58
+ os.chdir(project)
59
+ assert route_claude(cfg, launch=False, extra_args=[]) == 0
60
+ finally:
61
+ os.chdir(old_cwd)
62
+
63
+ settings_path = route_home / ".claude" / "settings.json"
64
+ assert settings_path.is_file()
65
+ settings = json.loads(settings_path.read_text())
66
+ assert settings["env"]["ANTHROPIC_BASE_URL"] == cfg.anthropic_base_url
67
+ assert settings["env"]["ANTHROPIC_AUTH_TOKEN"] == cfg.api_key
68
+
69
+ mcp_path = project / ".mcp.json"
70
+ assert mcp_path.is_file()
71
+ mcp = json.loads(mcp_path.read_text())
72
+ assert "tokensaver-route-tools" in mcp["mcpServers"]
73
+ assert "tokensaver-route-gateway" in mcp["mcpServers"]
74
+
75
+ state = load_state()
76
+ assert "claude" in state
77
+ assert route_state_dir().is_dir()
78
+
79
+
80
+ def test_unroute_claude_restores_backup(route_home: Path, cfg: RouteConfig, tmp_path: Path) -> None:
81
+ project = tmp_path / "project"
82
+ project.mkdir()
83
+ settings_path = route_home / ".claude"
84
+ settings_path.mkdir(parents=True)
85
+ original = settings_path / "settings.json"
86
+ original.write_text('{"env": {"FOO": "bar"}}\n', encoding="utf-8")
87
+
88
+ old_cwd = os.getcwd()
89
+ try:
90
+ os.chdir(project)
91
+ route_claude(cfg, launch=False, extra_args=[])
92
+ assert "ANTHROPIC_BASE_URL" in original.read_text()
93
+ assert unroute_claude() == 0
94
+ restored = json.loads(original.read_text())
95
+ assert restored["env"]["FOO"] == "bar"
96
+ assert "ANTHROPIC_BASE_URL" not in restored.get("env", {})
97
+ finally:
98
+ os.chdir(old_cwd)
99
+
100
+
101
+ def test_route_cursor_writes_mcp_json(cfg: RouteConfig, tmp_path: Path) -> None:
102
+ project = tmp_path / "proj"
103
+ project.mkdir()
104
+ old_cwd = os.getcwd()
105
+ try:
106
+ os.chdir(project)
107
+ assert route_cursor(cfg) == 0
108
+ mcp = json.loads((project / ".cursor" / "mcp.json").read_text())
109
+ assert mcp["mcpServers"]["tokensaver-route-gateway"]["headers"]["X-Tokensaver-Client"] == "cursor/1.0"
110
+ finally:
111
+ os.chdir(old_cwd)
112
+
113
+
114
+ def test_unroute_cursor_restores(route_home: Path, cfg: RouteConfig, tmp_path: Path) -> None:
115
+ project = tmp_path / "proj"
116
+ cursor_dir = project / ".cursor"
117
+ cursor_dir.mkdir(parents=True)
118
+ mcp_path = cursor_dir / "mcp.json"
119
+ mcp_path.write_text('{"mcpServers": {"other": {"url": "http://x"}}}\n', encoding="utf-8")
120
+
121
+ old_cwd = os.getcwd()
122
+ try:
123
+ os.chdir(project)
124
+ route_cursor(cfg)
125
+ route_cursor(cfg)
126
+ assert unroute_cursor() == 0
127
+ restored = json.loads(mcp_path.read_text())
128
+ assert "tokensaver-route-tools" not in restored.get("mcpServers", {})
129
+ assert restored["mcpServers"]["other"]["url"] == "http://x"
130
+ finally:
131
+ os.chdir(old_cwd)