lemonpie-cli 0.3.2__tar.gz → 0.3.3__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.
Files changed (59) hide show
  1. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/architecture/project-structure.md +4 -4
  2. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/backend/client.md +6 -2
  3. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/cli/cli-commands.md +7 -3
  4. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/config/config-format.md +6 -4
  5. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/config/config-paths.md +2 -2
  6. lemonpie_cli-0.3.3/.release-please/manifest.json +3 -0
  7. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/CHANGELOG.md +11 -0
  8. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/PKG-INFO +10 -2
  9. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/README.md +9 -1
  10. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/docs/usage/command-index.md +5 -2
  11. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/_version.py +2 -2
  12. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/cli/config_cmd.py +132 -25
  13. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/config.py +9 -1
  14. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/main.py +3 -1
  15. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/tests/conftest.py +6 -0
  16. lemonpie_cli-0.3.3/tests/test_api_key.py +310 -0
  17. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/tests/test_config_cmd.py +10 -10
  18. lemonpie_cli-0.3.2/.release-please/manifest.json +0 -3
  19. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/INDEX.md +0 -0
  20. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/architecture/_topic.md +0 -0
  21. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/backend/_topic.md +0 -0
  22. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/cicd/_topic.md +0 -0
  23. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/cicd/ci-workflow.md +0 -0
  24. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/cicd/release-workflow.md +0 -0
  25. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/cli/_topic.md +0 -0
  26. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/config/_topic.md +0 -0
  27. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/sessions/_topic.md +0 -0
  28. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.agents/kb/topics/sessions/session-storage.md +0 -0
  29. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.github/release.yml +0 -0
  30. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.github/workflows/ci.yml +0 -0
  31. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.github/workflows/pr-labler.yml +0 -0
  32. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.github/workflows/release.yml +0 -0
  33. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.gitignore +0 -0
  34. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/.release-please/config.json +0 -0
  35. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/AGENTS.md +0 -0
  36. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/LICENSE +0 -0
  37. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/SECURITY.md +0 -0
  38. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/docs/ROADMAP.md +0 -0
  39. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/docs/config.example.json +0 -0
  40. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/docs/design/code-completion.md +0 -0
  41. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/docs/design/feature-ideas.md +0 -0
  42. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/docs/design/model-verification.md +0 -0
  43. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/docs/design/packaging.md +0 -0
  44. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/pyproject.toml +0 -0
  45. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/__init__.py +0 -0
  46. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/cli/__init__.py +0 -0
  47. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/cli/parser.py +0 -0
  48. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/cli/ui.py +0 -0
  49. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/client.py +0 -0
  50. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/models.py +0 -0
  51. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/paths.py +0 -0
  52. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/sessions/__init__.py +0 -0
  53. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/sessions/storage.py +0 -0
  54. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/src/lemonpie/time_utils.py +0 -0
  55. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/tests/test_cli.py +0 -0
  56. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/tests/test_client.py +0 -0
  57. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/tests/test_dry_run.py +0 -0
  58. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/tests/test_sessions.py +0 -0
  59. {lemonpie_cli-0.3.2 → lemonpie_cli-0.3.3}/uv.lock +0 -0
@@ -3,7 +3,7 @@ id: 20261117-project-structure
3
3
  title: Project structure
4
4
  tags: [architecture]
5
5
  created: 2026-11-17
6
- updated: 2026-11-24
6
+ updated: 2026-11-26
7
7
  related: [20261117-http-client, 20261117-cli-commands, 20261117-session-storage]
8
8
  summary: Source layout of the lemonpie package — what each module does and how they relate.
9
9
  ---
@@ -23,7 +23,7 @@ and `lmConfig` (→ `cli.config_cmd:main`).
23
23
  ```
24
24
  src/lemonpie/
25
25
  main.py # CLI session manager — entry point for `lm` / `lemonpie`
26
- config.py # Config load, save, and schema
26
+ config.py # Config load, save, and runtime env overrides (LEMONPIE_HOST, LEMONPIE_API_KEY)
27
27
  paths.py # OS-appropriate config/data directory resolution (via platformdirs)
28
28
  time_utils.py # Timestamp helpers
29
29
  models.py # Model alias resolution
@@ -43,8 +43,8 @@ src/lemonpie/
43
43
  and `sessions/storage.py` to persist history.
44
44
  - `paths.py` is a pure utility — both `config.py` and `sessions/storage.py` import it
45
45
  to find the right OS directory without duplicating platform logic.
46
- - `cli/config_cmd.py` is an independent entry point; it imports `config.py` and `paths.py`
47
- but does not depend on `main.py`.
46
+ - `cli/config_cmd.py` is an independent entry point; it imports `config.py`, `models.py`,
47
+ `cli/ui.py`, and `client.py` (to probe the server in `--init`) but does not depend on `main.py`.
48
48
 
49
49
  ## Build system
50
50
 
@@ -3,7 +3,7 @@ id: 20261117-http-client
3
3
  title: HTTP backend client
4
4
  tags: [backend]
5
5
  created: 2026-11-17
6
- updated: 2026-11-24
6
+ updated: 2026-11-26
7
7
  related: [20261117-project-structure, 20261117-config-format]
8
8
  summary: How lemonpie talks to AI backends — a unified OpenAI-compatible HTTP client (client.py) supporting Ollama, llama.cpp, LM Studio, vLLM, and hosted APIs.
9
9
  ---
@@ -34,9 +34,13 @@ The `backend` field in `config.json` is recorded by `lmConfig --init` for identi
34
34
  | Config field | Used for |
35
35
  |---|---|
36
36
  | `server` | Base URL — the client appends `/v1/chat/completions` |
37
- | `api_key` | Bearer token; `null` for unauthenticated local servers |
37
+ | `api_key` | Bearer token; `null` for unauthenticated local servers. `LEMONPIE_API_KEY` overrides it at runtime |
38
38
  | `backend` | Backend name (identification only; set by `lmConfig --init`) |
39
39
 
40
+ ## Authentication
41
+
42
+ `build_client(server_host, timeout, api_key)` sends `Authorization: Bearer <api_key>` on every request when a key is set. `main.py` resolves the key with `config.resolve_api_key`, so `LEMONPIE_API_KEY` wins over the config value. `lmConfig --init` probes `GET /v1/models` through the same client; a 401/403 response triggers its API key prompt.
43
+
40
44
  ## Streaming
41
45
 
42
46
  LemonPie uses streaming responses for real-time terminal output. Each token is printed
@@ -3,7 +3,7 @@ id: 20261117-cli-commands
3
3
  title: CLI commands
4
4
  tags: [cli]
5
5
  created: 2026-11-17
6
- updated: 2026-11-24
6
+ updated: 2026-11-26
7
7
  related: [20261117-config-format, 20261117-session-storage]
8
8
  summary: Full flag reference for lm/lemonpie and lmConfig — every flag, its effect, and usage examples.
9
9
  ---
@@ -26,14 +26,16 @@ Manages `config.json`.
26
26
 
27
27
  | Flag | Description |
28
28
  |---|---|
29
- | `--init` | Interactive setup wizard: select backend, configure server URL, verify reachability, list and select installed models, optionally set a default |
29
+ | `--init` | Interactive setup wizard: select backend, configure server URL, verify reachability, list and select installed models, optionally set a default. If the server answers 401/403, prompts for an API key (hidden input) and retries; a key from `LEMONPIE_API_KEY` is tried first and never saved |
30
30
  | `--init --force` | Same as `--init` but skip server verification |
31
31
  | `--host <url>` | Set server host URL (`http(s)://host:port`) |
32
32
  | `--default-model <name>` | Set default model using alias or full name (must exist in models list) |
33
33
  | `--add-model <alias> <model>` | Add a model mapping: alias → full model name |
34
34
  | `--remove-model <identifier>` | Remove a model mapping by alias or full name |
35
35
  | `--list-models` | List all configured model aliases and names |
36
- | `--show` | Print the full `config.json` |
36
+ | `--api-key [<key>]` | Set or update the API key. Omit `<key>` to be prompted without echo (keeps it out of shell history) |
37
+ | `--remove-api-key` | Remove the API key from the config |
38
+ | `--show` | Print `config.json` (the API key is masked) |
37
39
  | `--force` | Force overwrite on alias conflict; skip server verification when used with `--init` |
38
40
 
39
41
  ### Examples
@@ -45,6 +47,8 @@ lmConfig --list-models
45
47
  lmConfig --remove-model qwen
46
48
  lmConfig --host http://192.168.1.10:11434
47
49
  lmConfig --default-model qwen
50
+ lmConfig --api-key # prompts without echo
51
+ lmConfig --remove-api-key
48
52
  lmConfig --show
49
53
  ```
50
54
 
@@ -3,7 +3,7 @@ id: 20261117-config-format
3
3
  title: Config file format
4
4
  tags: [config]
5
5
  created: 2026-11-17
6
- updated: 2026-11-20
6
+ updated: 2026-11-26
7
7
  related: [20261117-config-paths, 20261117-cli-commands, 20261117-http-client]
8
8
  summary: JSON schema for lemonpie's config file — backend, server URL, API key, default model, and model alias list.
9
9
  ---
@@ -36,7 +36,7 @@ on first use. `docs/config.example.json` in the repo is a reference template.
36
36
  |---|---|---|
37
37
  | `backend` | string | Backend identifier (`"ollama"`, or any OpenAI-compatible server name) |
38
38
  | `server` | string | Server URL for the OpenAI-compatible `/v1/chat/completions` endpoint |
39
- | `api_key` | string \| null | Optional API key — `null` for local servers, required for hosted APIs |
39
+ | `api_key` | string \| null | Optional API key — `null` for local servers, required for hosted APIs. `LEMONPIE_API_KEY` overrides it at runtime |
40
40
  | `default` | string | Canonical model name used when no `-m` flag is given |
41
41
  | `models` | array | Registered models; each has `alias` (nullable string) and `name` (full identifier) |
42
42
 
@@ -45,8 +45,10 @@ on first use. `docs/config.example.json` in the repo is a reference template.
45
45
  - `default` must be the **full** model identifier (e.g. `qwen2.5-coder:3b`), not an alias.
46
46
  - `alias` is optional — set to `null` to register a model without a shorthand.
47
47
  - Aliases are resolved by `models.py` before any API call.
48
- - Writes use atomic tmp-then-replace for safety.
49
- - `lmConfig --init` guides through backend selection, server setup, and model listing interactively.
48
+ - Writes use atomic tmp-then-replace for safety. The temp file is created with mode `0600`, so the saved config is owner-only on POSIX (it may hold an API key).
49
+ - Environment overrides win at runtime and are never written to the file: `LEMONPIE_HOST` overrides `server`, `LEMONPIE_API_KEY` overrides `api_key`.
50
+ - `lmConfig --api-key` / `--remove-api-key` set or clear `api_key`; `lmConfig --show` masks it.
51
+ - `lmConfig --init` guides through backend selection, server setup, and model listing interactively. If the server answers 401/403 it prompts for an API key (hidden input) and saves the key only after it authenticates.
50
52
 
51
53
  ## Related
52
54
 
@@ -3,7 +3,7 @@ id: 20261117-config-paths
3
3
  title: Config and data paths
4
4
  tags: [config]
5
5
  created: 2026-11-17
6
- updated: 2026-11-17
6
+ updated: 2026-11-26
7
7
  related: [20261117-config-format, 20261117-session-storage]
8
8
  summary: Where lemonpie stores its config file and session data on Linux, macOS, and Windows, and how to override them.
9
9
  ---
@@ -32,7 +32,7 @@ Both directories can be overridden at runtime:
32
32
  | Variable | Overrides |
33
33
  |---|---|
34
34
  | `LEMONPIE_CONFIG_DIR` | Config directory |
35
- | `LEMONPIE_SESSIONS_DIR` | Sessions directory |
35
+ | `LEMONPIE_SESSION_DIR` | Sessions directory |
36
36
 
37
37
  Useful for testing, CI runs, or containerized environments where the default OS path
38
38
  isn't appropriate.
@@ -0,0 +1,3 @@
1
+ {
2
+ ".": "0.3.3"
3
+ }
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.3 (2026-11-26)
4
+
5
+ <!-- Release notes generated using configuration in .github/release.yml at main -->
6
+
7
+ ## What's Changed
8
+ ### New Features
9
+ * feat: add API key management and LEMONPIE_API_KEY override by @famousStratum in https://github.com/famousStratum/LemonPie/pull/65
10
+
11
+
12
+ **Full Changelog**: https://github.com/famousStratum/LemonPie/compare/v0.3.2...v0.3.3
13
+
3
14
  ## 0.3.2 (2026-11-25)
4
15
 
5
16
  <!-- Release notes generated using configuration in .github/release.yml at main -->
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lemonpie-cli
3
- Version: 0.3.2
3
+ Version: 0.3.3
4
4
  Summary: LemonPie — A lightweight CLI for LLM inference servers
5
5
  Project-URL: homepage, https://versicode.com/projects/lemon-pie
6
6
  Project-URL: repository, https://github.com/famousStratum/LemonPie
@@ -124,7 +124,7 @@ LemonPie keeps its config file and session history in your OS's standard user di
124
124
  | Windows | `%LOCALAPPDATA%\lemonpie\` | `%LOCALAPPDATA%\lemonpie\sessions\` |
125
125
 
126
126
 
127
- All three are overridable via environment variables — `LEMONPIE_HOST`, `LEMONPIE_CONFIG_DIR`, and `LEMONPIE_SESSION_DIR` — useful for testing or running in a container.
127
+ All of these are overridable via environment variables — `LEMONPIE_HOST`, `LEMONPIE_CONFIG_DIR`, and `LEMONPIE_SESSION_DIR` — useful for testing or running in a container. Set `LEMONPIE_API_KEY` to supply an API key without storing it in `config.json`; when set, it takes precedence over the config value.
128
128
 
129
129
  `docs/config.example.json` is a template. Run `lmConfig --init` to set up your config interactively — it verifies server reachability, lists installed models for selection, and writes the file for you. `lmConfig` also auto-creates a minimal config on first use if you prefer to configure manually.
130
130
 
@@ -179,6 +179,14 @@ models: list of objects with alias (nullable) and name
179
179
  `lmConfig --list-models`\
180
180
  <sup>Lists configured model aliases and names</sup>
181
181
 
182
+ - Manage the API key\
183
+ `lmConfig --api-key`\
184
+ <sup>Prompts for the key without echoing it (recommended; keeps it out of shell history)</sup>\
185
+ `lmConfig --api-key <key>`\
186
+ <sup>Sets the key directly (it will appear in shell history)</sup>\
187
+ `lmConfig --remove-api-key`\
188
+ <sup>Removes the stored key</sup>
189
+
182
190
 
183
191
  👉 For full command reference, please read [docs/usage/command-index.md](https://github.com/famousStratum/LemonPie/blob/main/docs/usage/command-index.md)
184
192
 
@@ -105,7 +105,7 @@ LemonPie keeps its config file and session history in your OS's standard user di
105
105
  | Windows | `%LOCALAPPDATA%\lemonpie\` | `%LOCALAPPDATA%\lemonpie\sessions\` |
106
106
 
107
107
 
108
- All three are overridable via environment variables — `LEMONPIE_HOST`, `LEMONPIE_CONFIG_DIR`, and `LEMONPIE_SESSION_DIR` — useful for testing or running in a container.
108
+ All of these are overridable via environment variables — `LEMONPIE_HOST`, `LEMONPIE_CONFIG_DIR`, and `LEMONPIE_SESSION_DIR` — useful for testing or running in a container. Set `LEMONPIE_API_KEY` to supply an API key without storing it in `config.json`; when set, it takes precedence over the config value.
109
109
 
110
110
  `docs/config.example.json` is a template. Run `lmConfig --init` to set up your config interactively — it verifies server reachability, lists installed models for selection, and writes the file for you. `lmConfig` also auto-creates a minimal config on first use if you prefer to configure manually.
111
111
 
@@ -160,6 +160,14 @@ models: list of objects with alias (nullable) and name
160
160
  `lmConfig --list-models`\
161
161
  <sup>Lists configured model aliases and names</sup>
162
162
 
163
+ - Manage the API key\
164
+ `lmConfig --api-key`\
165
+ <sup>Prompts for the key without echoing it (recommended; keeps it out of shell history)</sup>\
166
+ `lmConfig --api-key <key>`\
167
+ <sup>Sets the key directly (it will appear in shell history)</sup>\
168
+ `lmConfig --remove-api-key`\
169
+ <sup>Removes the stored key</sup>
170
+
163
171
 
164
172
  👉 For full command reference, please read [docs/usage/command-index.md](https://github.com/famousStratum/LemonPie/blob/main/docs/usage/command-index.md)
165
173
 
@@ -9,14 +9,16 @@ Useful for both **users** (cheat sheet) and **developers** (tracking CLI surface
9
9
 
10
10
  Manage LemonPie configuration (`config.json`).
11
11
 
12
- - `--init` — Interactive setup wizard: select backend, configure server URL (local default or custom), verify reachability, list and select installed models, optionally set a default
12
+ - `--init` — Interactive setup wizard: select backend, configure server URL (local default or custom), verify reachability, list and select installed models, optionally set a default. If the server answers 401/403, prompts for an API key (hidden input) and retries; a key from `LEMONPIE_API_KEY` is tried first and never saved
13
13
  - `--init --force` — Same as `--init` but skip server verification
14
14
  - `--host <url>` — Set server host URL (`http(s)://host:port`)
15
15
  - `--default-model <name>` — Set default model using alias or full name (must exist in models)
16
16
  - `--add-model <alias> <model>` — Add model mapping: alias → model_full_name
17
17
  - `--remove-model <identifier>` — Remove a model mapping by alias or full name
18
18
  - `--list-models` — List configured model aliases and names
19
- - `--show` — Print full `config.json`
19
+ - `--api-key [<key>]` — Set or update the API key. Omit `<key>` to be prompted without echo (keeps it out of shell history and the process list)
20
+ - `--remove-api-key` — Remove the API key from the config
21
+ - `--show` — Print `config.json` (the API key is masked)
20
22
  - `--force` — Force overwrite when adding a model; skip server verification when used with `--init`
21
23
 
22
24
  ---
@@ -50,4 +52,5 @@ Start and manage chat sessions.
50
52
  ```
51
53
 
52
54
  - `--force` applies to `lmConfig --add-model` (overwrite alias conflicts) and `lmConfig --init` (skip server verification).
55
+ - `LEMONPIE_API_KEY` overrides the `api_key` value in `config.json` at runtime, and is used (but never saved) by `lmConfig --init`.
53
56
  - Future flags will be added here as they are introduced.
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.3.2'
22
- __version_tuple__ = version_tuple = (0, 3, 2)
21
+ __version__ = version = '0.3.3'
22
+ __version_tuple__ = version_tuple = (0, 3, 3)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -10,9 +10,12 @@ Usage examples:
10
10
  lmConfig --default-model qwen # Set default by alias or name
11
11
  lmConfig --remove-model qwen # Clear alias or remove model
12
12
  lmConfig --list-models # View configured models
13
+ lmConfig --api-key # Set the API key (hidden prompt)
14
+ lmConfig --remove-api-key # Remove the stored API key
13
15
  """
14
16
 
15
17
  import argparse
18
+ import getpass
16
19
  import json
17
20
  import os
18
21
  import sys
@@ -20,11 +23,13 @@ import sys
20
23
  import httpx2
21
24
 
22
25
  from lemonpie.cli.ui import confirm
26
+ from lemonpie.client import build_client, resolve_error
23
27
  from lemonpie.config import (
24
28
  config_file_path,
25
29
  ensure_models_list,
26
30
  is_valid_url,
27
31
  load_config,
32
+ resolve_api_key,
28
33
  save_config,
29
34
  )
30
35
  from lemonpie.models import (
@@ -192,25 +197,43 @@ def _prompt_default(models):
192
197
  # ---------------------------------------------------------------------------
193
198
 
194
199
 
195
- def fetch_available_models(server):
196
- """GET /v1/models and return (list_of_name_strings, error_str_or_None).
200
+ def _fetch_with_key(server, api_key=None):
201
+ """GET /v1/models with an optional API key.
197
202
 
198
- Used by cmd_init to verify server reachability and discover installed
199
- models in a single round-trip.
203
+ Returns (models, err, auth_err) where ``err`` is a human-readable
204
+ error message (or ``None`` on success) and ``auth_err`` is ``True``
205
+ when the server returned 401/403 — letting the caller prompt for an
206
+ API key without relying on string parsing.
200
207
  """
201
208
  try:
202
- resp = httpx2.get(f"{server.rstrip('/')}/v1/models", timeout=5.0)
203
- resp.raise_for_status()
204
- data = resp.json()
205
- return [m["id"] for m in data.get("data", [])], None
206
- except httpx2.ConnectError:
207
- return [], "Connection refused"
208
- except httpx2.TimeoutException:
209
- return [], "Connection timed out"
210
- except httpx2.HTTPError as exc:
211
- return [], f"HTTP error: {exc}"
212
- except (json.JSONDecodeError, KeyError, TypeError) as exc:
213
- return [], f"Invalid response format from server, {exc}"
209
+ with build_client(server, timeout=5.0, api_key=api_key) as client:
210
+ resp = client.get("/v1/models")
211
+ resp.raise_for_status()
212
+ data = resp.json()
213
+ return [m["id"] for m in data.get("data", [])], None, False
214
+ except httpx2.HTTPStatusError as exc:
215
+ status = exc.response.status_code
216
+ if status in (401, 403):
217
+ return [], "Server requires authentication", True
218
+ return [], f"Server returned HTTP {status}", False
219
+ except (httpx2.HTTPError, httpx2.InvalidURL) as exc:
220
+ # Connection, timeout, DNS, TLS and protocol failures. HTTPStatusError
221
+ # is handled above because it is a subclass of HTTPError.
222
+ message, _hint = resolve_error(exc, server)
223
+ return [], message, False
224
+ except (ValueError, KeyError, TypeError, AttributeError) as exc:
225
+ # Bad JSON (JSONDecodeError is a ValueError) or an unexpected shape.
226
+ return [], f"Invalid response format from server ({exc!r})", False
227
+
228
+
229
+ def _print_probe_result(models, err):
230
+ """Finish the 'Connecting ...' status line that the caller started."""
231
+ if err:
232
+ print(f" failed.\n {err}")
233
+ return
234
+ count = len(models)
235
+ label = f"{count} model(s) available" if count else "no models installed"
236
+ print(f" OK ({label})")
214
237
 
215
238
 
216
239
  # ---------------------------------------------------------------------------
@@ -228,7 +251,10 @@ def cmd_init(force=False):
228
251
  3. Prompt for server URL — local (default or custom) or remote.
229
252
  4. Unless ``--force``, verify server reachability via ``GET /v1/models``.
230
253
  - If reachable: present the installed-model list for selection.
231
- - If unreachable: offer to continue without verification.
254
+ - If the server answers 401/403: prompt for an API key and retry
255
+ (a key from LEMONPIE_API_KEY is tried first and never saved).
256
+ - If unreachable or the key is rejected: offer to continue without
257
+ verification.
232
258
  5. If no server models are available, offer manual model entry.
233
259
  6. Optionally set a default model.
234
260
  7. Save and print a summary.
@@ -261,22 +287,41 @@ def cmd_init(force=False):
261
287
  # ------------------------------------------------------------------
262
288
  available_models: list[str] = []
263
289
  server_ok = False
290
+ api_key: str | None = None
264
291
 
265
292
  if force:
266
- print(" Skipping server verification (--force).")
293
+ print(
294
+ " Skipping server verification (--force).\n"
295
+ " Use `lmConfig --api-key` later if your server needs a key."
296
+ )
267
297
  else:
298
+ # A key from LEMONPIE_API_KEY is used for the probe only; it is never
299
+ # written to the config file.
268
300
  print(f" Connecting to {server} ...", end="", flush=True)
269
- available_models, err = fetch_available_models(server)
301
+ available_models, err, auth_err = _fetch_with_key(server, resolve_api_key({}))
302
+ if auth_err:
303
+ print(" authentication required.")
304
+ raw_key = getpass.getpass(
305
+ " Enter API key (or press Enter to skip): "
306
+ ).strip()
307
+ if raw_key:
308
+ print(" Retrying with API key ...", end="", flush=True)
309
+ available_models, err, auth_err = _fetch_with_key(server, raw_key)
310
+ if auth_err:
311
+ err = "Server rejected the API key"
312
+ if not err:
313
+ api_key = raw_key
314
+ _print_probe_result(available_models, err)
315
+ # Key skipped: err is still set, so the prompt below applies.
316
+ else:
317
+ _print_probe_result(available_models, err)
318
+
270
319
  if err:
271
- print(f" failed.\n {err}")
272
320
  if not confirm(" Continue without verification?"):
273
321
  print("Aborted.")
274
322
  return 1
275
323
  else:
276
324
  server_ok = True
277
- count = len(available_models)
278
- label = f"{count} model(s) available" if count else "no models installed"
279
- print(f" OK ({label})")
280
325
 
281
326
  # ------------------------------------------------------------------
282
327
  # Step 4: Select / add models
@@ -302,7 +347,7 @@ def cmd_init(force=False):
302
347
  cfg = {
303
348
  "backend": backend,
304
349
  "server": server,
305
- "api_key": None,
350
+ "api_key": api_key,
306
351
  "default": default,
307
352
  "models": models,
308
353
  }
@@ -508,8 +553,52 @@ def cmd_list_models(cfg):
508
553
  return 0
509
554
 
510
555
 
556
+ # Sentinel: ``--api-key`` was given without a value, so ask for it without echo.
557
+ _PROMPT_FOR_KEY = object()
558
+
559
+
560
+ def _warn_if_env_key():
561
+ if os.environ.get("LEMONPIE_API_KEY"):
562
+ print(
563
+ "Note: LEMONPIE_API_KEY is set and takes precedence over the "
564
+ "config value at runtime."
565
+ )
566
+
567
+
568
+ def cmd_set_api_key(cfg, api_key):
569
+ """Set or update the API key in the config.
570
+
571
+ Pass ``_PROMPT_FOR_KEY`` to read the key from a hidden prompt, which keeps
572
+ it out of shell history and the process list.
573
+ """
574
+ if api_key is _PROMPT_FOR_KEY:
575
+ api_key = getpass.getpass("Enter API key: ")
576
+ api_key = api_key.strip()
577
+ if not api_key:
578
+ print("No API key provided.")
579
+ return 2
580
+ cfg["api_key"] = api_key
581
+ save_config(cfg)
582
+ print("API key set.")
583
+ _warn_if_env_key()
584
+ return 0
585
+
586
+
587
+ def cmd_clear_api_key(cfg):
588
+ """Remove the API key from the config."""
589
+ cfg["api_key"] = None
590
+ save_config(cfg)
591
+ print("API key removed.")
592
+ _warn_if_env_key()
593
+ return 0
594
+
595
+
511
596
  def cmd_show(cfg):
512
- print(json.dumps(cfg, indent=2, ensure_ascii=False))
597
+ shown = dict(cfg)
598
+ key = shown.get("api_key")
599
+ if key:
600
+ shown["api_key"] = f"****{key[-4:]}" if len(key) >= 12 else "****"
601
+ print(json.dumps(shown, indent=2, ensure_ascii=False))
513
602
  return 0
514
603
 
515
604
 
@@ -549,6 +638,18 @@ def build_parser():
549
638
  action="store_true",
550
639
  help="List configured model aliases and names",
551
640
  )
641
+ parser.add_argument(
642
+ "--api-key",
643
+ nargs="?",
644
+ const=_PROMPT_FOR_KEY,
645
+ metavar="KEY",
646
+ help="Set or update the API key (omit KEY to be prompted without echo)",
647
+ )
648
+ parser.add_argument(
649
+ "--remove-api-key",
650
+ action="store_true",
651
+ help="Remove the API key from config",
652
+ )
552
653
  parser.add_argument("--show", action="store_true", help="Print full config.json")
553
654
  parser.add_argument(
554
655
  "--force",
@@ -583,6 +684,12 @@ def main():
583
684
  if args.remove_model:
584
685
  return cmd_remove_model(cfg, args.remove_model)
585
686
 
687
+ if args.api_key is not None:
688
+ return cmd_set_api_key(cfg, args.api_key)
689
+
690
+ if args.remove_api_key:
691
+ return cmd_clear_api_key(cfg)
692
+
586
693
  if args.list_models:
587
694
  return cmd_list_models(cfg)
588
695
 
@@ -9,7 +9,11 @@ from lemonpie.paths import CONFIG_FILE
9
9
 
10
10
  def save_config(cfg):
11
11
  tmp = CONFIG_FILE + ".tmp"
12
- with open(tmp, "w", encoding="utf-8") as f:
12
+ # The file can hold an API key, so create it owner-only (0o600). The mode
13
+ # is effectively ignored on Windows, where the profile directory is
14
+ # already per-user.
15
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
16
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
13
17
  json.dump(cfg, f, indent=2, ensure_ascii=False)
14
18
  os.replace(tmp, CONFIG_FILE)
15
19
 
@@ -43,6 +47,10 @@ def resolve_server_host(cfg):
43
47
  return os.environ.get("LEMONPIE_HOST") or cfg.get("server")
44
48
 
45
49
 
50
+ def resolve_api_key(cfg):
51
+ return os.environ.get("LEMONPIE_API_KEY") or cfg.get("api_key")
52
+
53
+
46
54
  def is_valid_url(url):
47
55
  try:
48
56
  p = urlparse(url)
@@ -38,6 +38,7 @@ from lemonpie.client import (
38
38
  from lemonpie.config import (
39
39
  build_timeout,
40
40
  load_config,
41
+ resolve_api_key,
41
42
  resolve_server_host,
42
43
  )
43
44
  from lemonpie.models import (
@@ -60,9 +61,10 @@ from lemonpie.time_utils import now_ts
60
61
 
61
62
  def main():
62
63
  cfg = load_config()
64
+ api_key = resolve_api_key(cfg)
63
65
  server_host = resolve_server_host(cfg)
64
66
  timeout = build_timeout()
65
- client = build_client(server_host, timeout, api_key=cfg.get("api_key"))
67
+ client = build_client(server_host, timeout, api_key)
66
68
  default_model_name = cfg.get("default") or None
67
69
  parser = build_parser()
68
70
  args = parser.parse_args()
@@ -83,3 +83,9 @@ def write_cfg(isolated_dirs, sample_cfg):
83
83
  """Write sample_cfg to the isolated config file and hand back the dict."""
84
84
  isolated_dirs["config_file"].write_text(json.dumps(sample_cfg), encoding="utf-8")
85
85
  return sample_cfg
86
+
87
+
88
+ @pytest.fixture(autouse=True)
89
+ def _no_env_api_key(monkeypatch):
90
+ """Keep a developer's real LEMONPIE_API_KEY from leaking into tests."""
91
+ monkeypatch.delenv("LEMONPIE_API_KEY", raising=False)
@@ -0,0 +1,310 @@
1
+ """Tests for API key handling.
2
+
3
+ Covers ``resolve_api_key`` precedence, ``lmConfig --api-key`` /
4
+ ``--remove-api-key`` / ``--show``, the authentication prompt in ``cmd_init``,
5
+ the error classification in ``_fetch_with_key``, and config file permissions.
6
+
7
+ ``cmd_init`` prompts via ``input()`` (and ``confirm()``) and, for the key,
8
+ via ``getpass.getpass()``; both are mocked so every interaction is
9
+ deterministic.
10
+ """
11
+
12
+ import json
13
+ import sys
14
+
15
+ import httpx2
16
+ import pytest
17
+
18
+ from lemonpie.cli import config_cmd
19
+ from lemonpie.cli.config_cmd import _fetch_with_key, cmd_init
20
+ from lemonpie.config import resolve_api_key, save_config
21
+
22
+ # ---------------------------------------------------------------------------
23
+ # Helpers
24
+ # ---------------------------------------------------------------------------
25
+
26
+
27
+ def _make_input(responses):
28
+ it = iter(responses)
29
+ return lambda _prompt="": next(it)
30
+
31
+
32
+ def _read_cfg(isolated_dirs):
33
+ return json.loads(isolated_dirs["config_file"].read_text(encoding="utf-8"))
34
+
35
+
36
+ def _set_getpass(monkeypatch, value):
37
+ monkeypatch.setattr("getpass.getpass", lambda _prompt="": value)
38
+
39
+
40
+ def _forbid_getpass(monkeypatch):
41
+ def _boom(_prompt=""):
42
+ raise AssertionError("getpass must not be called")
43
+
44
+ monkeypatch.setattr("getpass.getpass", _boom)
45
+
46
+
47
+ def _auth_server(monkeypatch, good_key, models):
48
+ """Server that answers 401 unless called with *good_key*. Returns call log."""
49
+ calls = []
50
+
51
+ def fake(_server, _key=None):
52
+ calls.append(_key)
53
+ if _key == good_key:
54
+ return models, None, False
55
+ return [], "Server requires authentication", True
56
+
57
+ monkeypatch.setattr("lemonpie.cli.config_cmd._fetch_with_key", fake)
58
+ return calls
59
+
60
+
61
+ # Input prefix for cmd_init: Ollama, local, default URL
62
+ _WIZARD_START = ["2", "y", "1"]
63
+
64
+ # ---------------------------------------------------------------------------
65
+ # resolve_api_key
66
+ # ---------------------------------------------------------------------------
67
+
68
+
69
+ class TestResolveApiKey:
70
+ def test_env_overrides_config(self, monkeypatch):
71
+ monkeypatch.setenv("LEMONPIE_API_KEY", "sk-env")
72
+ assert resolve_api_key({"api_key": "sk-cfg"}) == "sk-env"
73
+
74
+ def test_falls_back_to_config(self):
75
+ assert resolve_api_key({"api_key": "sk-cfg"}) == "sk-cfg"
76
+
77
+ def test_empty_env_falls_back_to_config(self, monkeypatch):
78
+ monkeypatch.setenv("LEMONPIE_API_KEY", "")
79
+ assert resolve_api_key({"api_key": "sk-cfg"}) == "sk-cfg"
80
+
81
+ def test_nothing_set(self):
82
+ assert resolve_api_key({"api_key": None}) is None
83
+ assert resolve_api_key({}) is None
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # lmConfig --api-key / --remove-api-key / --show
88
+ # ---------------------------------------------------------------------------
89
+
90
+
91
+ class TestApiKeyCommands:
92
+ def _run(self, monkeypatch, *args):
93
+ monkeypatch.setattr(sys, "argv", ["lmConfig", *args])
94
+ return config_cmd.main()
95
+
96
+ def test_set_key_from_argument(self, isolated_dirs, monkeypatch):
97
+ assert self._run(monkeypatch, "--api-key", "sk-1") == 0
98
+ assert _read_cfg(isolated_dirs)["api_key"] == "sk-1"
99
+
100
+ def test_set_key_prompts_when_no_value(self, isolated_dirs, monkeypatch):
101
+ _set_getpass(monkeypatch, " sk-prompted ")
102
+ assert self._run(monkeypatch, "--api-key") == 0
103
+ assert _read_cfg(isolated_dirs)["api_key"] == "sk-prompted"
104
+
105
+ def test_empty_prompt_is_rejected_and_config_unchanged(
106
+ self, write_cfg, isolated_dirs, monkeypatch
107
+ ):
108
+ _set_getpass(monkeypatch, "")
109
+ assert self._run(monkeypatch, "--api-key") == 2
110
+ assert _read_cfg(isolated_dirs)["api_key"] is None
111
+
112
+ def test_empty_argument_is_rejected(self, write_cfg, isolated_dirs, monkeypatch):
113
+ assert self._run(monkeypatch, "--api-key", "") == 2
114
+ assert _read_cfg(isolated_dirs)["api_key"] is None
115
+
116
+ def test_remove_key(self, write_cfg, isolated_dirs, monkeypatch):
117
+ save_config({**write_cfg, "api_key": "sk-old"})
118
+ assert self._run(monkeypatch, "--remove-api-key") == 0
119
+ assert _read_cfg(isolated_dirs)["api_key"] is None
120
+
121
+ def test_env_override_warning(self, isolated_dirs, monkeypatch, capsys):
122
+ monkeypatch.setenv("LEMONPIE_API_KEY", "sk-env")
123
+ assert self._run(monkeypatch, "--api-key", "sk-1") == 0
124
+ assert "LEMONPIE_API_KEY" in capsys.readouterr().out
125
+
126
+ def test_show_masks_key(self, write_cfg, isolated_dirs, monkeypatch, capsys):
127
+ secret = "sk-secret-value-1234"
128
+ save_config({**write_cfg, "api_key": secret})
129
+ assert self._run(monkeypatch, "--show") == 0
130
+ out = capsys.readouterr().out
131
+ assert secret not in out
132
+ assert "****1234" in out
133
+
134
+
135
+ # ---------------------------------------------------------------------------
136
+ # Config file permissions
137
+ # ---------------------------------------------------------------------------
138
+
139
+
140
+ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX permission bits")
141
+ def test_config_file_is_owner_only(isolated_dirs):
142
+ save_config({"api_key": "sk-1"})
143
+ assert isolated_dirs["config_file"].stat().st_mode & 0o777 == 0o600
144
+
145
+
146
+ # ---------------------------------------------------------------------------
147
+ # cmd_init authentication prompt
148
+ # ---------------------------------------------------------------------------
149
+
150
+
151
+ class TestCmdInitAuth:
152
+ def test_key_accepted_is_saved(self, isolated_dirs, monkeypatch):
153
+ calls = _auth_server(monkeypatch, "sk-good", ["qwen2.5-coder:3b"])
154
+ _set_getpass(monkeypatch, "sk-good")
155
+ monkeypatch.setattr(
156
+ "builtins.input", _make_input([*_WIZARD_START, ""]) # skip selection
157
+ )
158
+ assert cmd_init() == 0
159
+
160
+ assert _read_cfg(isolated_dirs)["api_key"] == "sk-good"
161
+ assert calls == [None, "sk-good"]
162
+
163
+ def test_key_rejected_continue_does_not_save_key(self, isolated_dirs, monkeypatch):
164
+ _auth_server(monkeypatch, "sk-good", [])
165
+ _set_getpass(monkeypatch, "sk-bad")
166
+ monkeypatch.setattr(
167
+ "builtins.input",
168
+ _make_input([*_WIZARD_START, "y", "n"]), # continue; no manual model
169
+ )
170
+ assert cmd_init() == 0
171
+ assert _read_cfg(isolated_dirs)["api_key"] is None
172
+
173
+ def test_key_rejected_abort(self, isolated_dirs, monkeypatch):
174
+ _auth_server(monkeypatch, "sk-good", [])
175
+ _set_getpass(monkeypatch, "sk-bad")
176
+ monkeypatch.setattr("builtins.input", _make_input([*_WIZARD_START, "n"]))
177
+ assert cmd_init() == 1
178
+ assert not isolated_dirs["config_file"].exists()
179
+
180
+ def test_key_skipped_goes_to_continue_prompt_without_retry(
181
+ self, isolated_dirs, monkeypatch
182
+ ):
183
+ calls = _auth_server(monkeypatch, "sk-good", [])
184
+ _set_getpass(monkeypatch, "")
185
+ monkeypatch.setattr("builtins.input", _make_input([*_WIZARD_START, "n"]))
186
+ assert cmd_init() == 1
187
+ assert calls == [None]
188
+
189
+ def test_env_key_used_for_probe_but_not_saved(self, isolated_dirs, monkeypatch):
190
+ monkeypatch.setenv("LEMONPIE_API_KEY", "sk-env")
191
+ calls = _auth_server(monkeypatch, "sk-env", ["qwen2.5-coder:3b"])
192
+ _forbid_getpass(monkeypatch)
193
+ monkeypatch.setattr("builtins.input", _make_input([*_WIZARD_START, ""]))
194
+ assert cmd_init() == 0
195
+
196
+ assert calls == ["sk-env"]
197
+ assert _read_cfg(isolated_dirs)["api_key"] is None
198
+
199
+ def test_non_auth_failure_does_not_prompt_for_key(self, isolated_dirs, monkeypatch):
200
+ monkeypatch.setattr(
201
+ "lemonpie.cli.config_cmd._fetch_with_key",
202
+ lambda _server, _key=None: ([], "Connection refused", False),
203
+ )
204
+ _forbid_getpass(monkeypatch)
205
+ monkeypatch.setattr("builtins.input", _make_input([*_WIZARD_START, "n"]))
206
+ assert cmd_init() == 1
207
+
208
+ def test_force_never_prompts_for_key(self, isolated_dirs, monkeypatch):
209
+ _forbid_getpass(monkeypatch)
210
+ monkeypatch.setattr(
211
+ "builtins.input", _make_input([*_WIZARD_START, "n"]) # no manual model
212
+ )
213
+ assert cmd_init(force=True) == 0
214
+ assert _read_cfg(isolated_dirs)["api_key"] is None
215
+
216
+
217
+ # ---------------------------------------------------------------------------
218
+ # _fetch_with_key classification
219
+ # ---------------------------------------------------------------------------
220
+
221
+
222
+ class _FakeResponse:
223
+ def __init__(self, status=200, payload=None, json_error=None):
224
+ self.status_code = status
225
+ self._payload = payload
226
+ self._json_error = json_error
227
+
228
+ def raise_for_status(self):
229
+ if self.status_code >= 400:
230
+ request = httpx2.Request("GET", "http://test/v1/models")
231
+ response = httpx2.Response(self.status_code, request=request)
232
+ raise httpx2.HTTPStatusError(
233
+ "error", request=request, response=response
234
+ )
235
+
236
+ def json(self):
237
+ if self._json_error:
238
+ raise self._json_error
239
+ return self._payload
240
+
241
+
242
+ class _FakeClient:
243
+ def __init__(self, response=None, exc=None):
244
+ self._response = response
245
+ self._exc = exc
246
+ self.closed = False
247
+
248
+ def __enter__(self):
249
+ return self
250
+
251
+ def __exit__(self, *_exc_info):
252
+ self.closed = True
253
+
254
+ def get(self, _path):
255
+ if self._exc:
256
+ raise self._exc
257
+ return self._response
258
+
259
+
260
+ def _install(monkeypatch, client):
261
+ monkeypatch.setattr(config_cmd, "build_client", lambda *a, **k: client)
262
+
263
+
264
+ class TestFetchWithKey:
265
+ def test_success(self, monkeypatch):
266
+ client = _FakeClient(_FakeResponse(payload={"data": [{"id": "a"}, {"id": "b"}]}))
267
+ _install(monkeypatch, client)
268
+ assert _fetch_with_key("http://test") == (["a", "b"], None, False)
269
+ assert client.closed
270
+
271
+ @pytest.mark.parametrize("status", [401, 403])
272
+ def test_auth_statuses_flag_auth_err(self, monkeypatch, status):
273
+ client = _FakeClient(_FakeResponse(status=status))
274
+ _install(monkeypatch, client)
275
+ models, err, auth_err = _fetch_with_key("http://test")
276
+ assert models == [] and err and auth_err is True
277
+ assert client.closed
278
+
279
+ def test_other_status_is_not_auth_err(self, monkeypatch):
280
+ _install(monkeypatch, _FakeClient(_FakeResponse(status=500)))
281
+ _models, err, auth_err = _fetch_with_key("http://test")
282
+ assert "500" in err and auth_err is False
283
+
284
+ @pytest.mark.parametrize(
285
+ "exc",
286
+ [
287
+ httpx2.ConnectError("[Errno 111] Connection refused"),
288
+ httpx2.ConnectTimeout("timed out"),
289
+ httpx2.ReadError("connection reset"),
290
+ ],
291
+ )
292
+ def test_transport_errors_are_reported_not_raised(self, monkeypatch, exc):
293
+ client = _FakeClient(exc=exc)
294
+ _install(monkeypatch, client)
295
+ models, err, auth_err = _fetch_with_key("http://test")
296
+ assert models == [] and err and auth_err is False
297
+ assert client.closed
298
+
299
+ @pytest.mark.parametrize(
300
+ "response",
301
+ [
302
+ _FakeResponse(payload=["not", "a", "dict"]),
303
+ _FakeResponse(payload={"data": [{"no_id": 1}]}),
304
+ _FakeResponse(json_error=json.JSONDecodeError("bad", "", 0)),
305
+ ],
306
+ )
307
+ def test_malformed_body_is_reported_not_raised(self, monkeypatch, response):
308
+ _install(monkeypatch, _FakeClient(response))
309
+ models, err, auth_err = _fetch_with_key("http://test")
310
+ assert models == [] and "Invalid response" in err and auth_err is False
@@ -10,7 +10,7 @@ Approach
10
10
  globally with an iterator so every prompt consumes the next queued response
11
11
  in order, making the full interaction deterministic.
12
12
 
13
- ``fetch_available_models`` makes a network request, so every test that reaches
13
+ ``_fetch_with_key`` makes a network request, so every test that reaches
14
14
  the server-verification step mocks it at the module level via monkeypatch.
15
15
 
16
16
  All tests that touch the filesystem use the ``isolated_dirs`` fixture from
@@ -177,10 +177,10 @@ class TestCmdInitForce:
177
177
 
178
178
  class TestCmdInitServerOk:
179
179
  def _mock_server(self, monkeypatch, models):
180
- """Patch fetch_available_models to return *models* with no error."""
180
+ """Patch _fetch_with_key to return *models* with no error."""
181
181
  monkeypatch.setattr(
182
- "lemonpie.cli.config_cmd.fetch_available_models",
183
- lambda _server: (models, None),
182
+ "lemonpie.cli.config_cmd._fetch_with_key",
183
+ lambda _server, _key=None: (models, None, False),
184
184
  )
185
185
 
186
186
  def test_server_ok_select_one_model_with_alias(self, isolated_dirs, monkeypatch):
@@ -328,8 +328,8 @@ class TestCmdInitServerOk:
328
328
  class TestCmdInitServerUnreachable:
329
329
  def _mock_error(self, monkeypatch, err="Connection refused"):
330
330
  monkeypatch.setattr(
331
- "lemonpie.cli.config_cmd.fetch_available_models",
332
- lambda _server: ([], err),
331
+ "lemonpie.cli.config_cmd._fetch_with_key",
332
+ lambda _server, _key=None: ([], err, False),
333
333
  )
334
334
 
335
335
  def test_unreachable_user_aborts(self, isolated_dirs, monkeypatch):
@@ -440,8 +440,8 @@ class TestCmdInitInputValidation:
440
440
  def test_invalid_url_loops_until_valid(self, isolated_dirs, monkeypatch):
441
441
  """Bad URL triggers a re-prompt; second attempt accepted."""
442
442
  monkeypatch.setattr(
443
- "lemonpie.cli.config_cmd.fetch_available_models",
444
- lambda _: ([], None),
443
+ "lemonpie.cli.config_cmd._fetch_with_key",
444
+ lambda _server, _key=None: ([], None, False),
445
445
  )
446
446
  monkeypatch.setattr(
447
447
  "builtins.input",
@@ -488,8 +488,8 @@ class TestCmdInitInputValidation:
488
488
  def test_invalid_default_number_loops_until_valid(self, isolated_dirs, monkeypatch):
489
489
  """Out-of-range and non-numeric entries in the default-pick loop are retried."""
490
490
  monkeypatch.setattr(
491
- "lemonpie.cli.config_cmd.fetch_available_models",
492
- lambda _: (["qwen2.5-coder:3b", "llama3.2:1b"], None),
491
+ "lemonpie.cli.config_cmd._fetch_with_key",
492
+ lambda _server, _key=None: (["qwen2.5-coder:3b", "llama3.2:1b"], None, False),
493
493
  )
494
494
  monkeypatch.setattr(
495
495
  "builtins.input",
@@ -1,3 +0,0 @@
1
- {
2
- ".": "0.3.2"
3
- }
File without changes
File without changes
File without changes
File without changes
File without changes