Compare commits

..

11 Commits

Author SHA1 Message Date
Ahmed Allam
882d739d12 docs: keep the existing recommended model rows in the README 2026-09-02 14:56:58 +00:00
Ahmed Allam
89f534c8d6 docs: note viewer steering, history, and report prerequisites 2026-09-02 14:34:33 +00:00
Ahmed Allam
b18bc89f80 docs: trim crammed README sections and add cloud CLI and viewer docs pages 2026-09-02 14:29:36 +00:00
devin-ai-integration[bot]
a8642de76c docs(readme): trim the strix cloud section to the essentials (#1237) 2026-09-02 07:19:56 -07:00
Ahmed Allam
75b89018d3 docs: use openrouter/z-ai/glm-5.3 as the default model in setup examples 2026-09-02 16:52:53 +03:00
Ahmed Allam
129f938094 fix(models): keep aggregator routes out of RECOMMENDED_MODEL_NAMES, family matching already accepts them 2026-09-02 16:52:53 +03:00
Ahmed Allam
b438632e12 fix(models): keep list additions-only, restore gpt-5.4 examples, make openrouter/z-ai/glm-5.3 the top pick 2026-09-02 16:52:53 +03:00
Ahmed Allam
0ab7244807 feat(models): refresh the recommended model list and docs examples
Add Claude Fable 5.1, Gemini 3.7 Flash, and Z.ai GLM-5.3 / GLM-5.3-Flash
to RECOMMENDED_MODEL_NAMES, add a Z.ai GLM frontier family so GLM-5.x is
accepted through OpenRouter and Novita routes, and drop the superseded
GPT-5.4, GPT-5.3-codex, Opus 4.8, Sonnet 4.6, Gemini 3.6 Flash, and
Qwen3.7 entries. Update the README, docs provider pages, quickstart, and
CLI hint strings to the same current models, including DeepSeek V4,
Kimi K3, and GLM-5.3.
2026-09-02 16:52:53 +03:00
Ahmed Allam
c514f712f4 fix(config): persist only the alias the runtime settings read
pydantic-settings takes the first alias present in the environment, even
when it is empty. persist_current() must save that same alias, so an empty
LLM_API_KEY does not let a non-empty OPENAI_API_KEY sibling land in the
file and restore a credential the run did not use.
2026-09-02 16:10:52 +03:00
Ahmed Allam
3e88e498b9 fix(config): drop the stored LLM connection when a linked env var changes
A new STRIX_LLM, LLM_API_KEY, or LLM_API_BASE exported in the shell must not
be combined with the key, base, or model still stored in cli-config.json.
Restore the pre-refactor rule: when any linked LLM connection var differs
from the stored value, discard the whole stored connection before loading
and before persisting. Unrelated stored settings are kept.
2026-09-02 16:10:52 +03:00
Ahmed Allam
ce0db30252 fix(config): merge env into cli-config.json instead of overwriting it
persist_current rewrote the config file with only the env vars set in the
shell, so a run whose STRIX_LLM or LLM_API_KEY came from the file erased
them and the next launch failed with MISSING REQUIRED ENVIRONMENT
VARIABLES. Start from the stored env block, let a set env var override or
replace the aliases of its field, and let an empty env var clear it.
2026-09-02 16:10:52 +03:00
7 changed files with 430 additions and 166 deletions

163
README.md
View File

@@ -172,18 +172,9 @@ strix view my-run-name
strix view --host 0.0.0.0 --port 8080 --no-open
```
`strix view` starts a lightweight local server (bound to `127.0.0.1` on a random port) and opens your browser to a private, tokened link. Nothing leaves your machine: the dashboard reads the run's files straight off disk, with no cloud account or upload required. The UI ships prebuilt with Strix, so there is no extra install and no JS build step.
The dashboard shows the findings, a live map of the agent team, and past runs. Nothing leaves your machine, and the UI ships prebuilt. `strix view` binds to `127.0.0.1` and prints a tokened link that grants access to the run, so share it carefully.
Use `--host 0.0.0.0` to make the viewer reachable from other machines. Replace `0.0.0.0` in the printed URL with the server's reachable IP or hostname. The token in that URL grants access to the selected run's scan data, history, and steering, so only share it with trusted users and restrict the port with your firewall. Requests without the token-derived session cannot read run data.
### What's in the dashboard
- **Overview**: run status, target, and a severity breakdown of everything found so far.
- **Vulnerabilities**: each validated finding with its severity, details, and reproduction steps.
- **Agent graph**: a live map of the multi-agent team, showing which agent is doing what.
- **Steering**: send instructions to a live scan from the browser to redirect the agents mid-run.
- **History**: browse past runs on this machine and jump between them.
- **Reports**: generate a shareable report and email it to yourself or your team.
See the [viewer documentation](https://docs.strix.ai/usage/viewer) for the options and for reaching the viewer from another machine.
---
@@ -209,18 +200,9 @@ having to discover them by crawling. Pair the spec with the live base URL so the
agent knows where to send traffic:
```bash
# OpenAPI / Swagger file (.json / .yaml)
# OpenAPI / Swagger file, Postman export, or a live collection by id
strix --target ./openapi.yaml --target https://api.your-app.com
# Postman collection export
strix --target ./collection.postman_collection.json --target https://api.your-app.com
# Postman collection pulled live by id (no manual export)
export POSTMAN_API_KEY="PMAK-..."
strix --target postman://<collection-uuid>
# ...with a Postman environment to resolve {{baseUrl}} / token variables
strix --target "postman://<collection-uuid>?env=<environment-uuid>"
strix --target postman://<collection-uuid> --target https://api.your-app.com
```
@@ -235,20 +217,10 @@ strix -t https://github.com/org/app -t https://your-app.com
# Targets from a file, one target per non-empty, non-comment line
strix --target-list ./targets.txt
# White-box source-aware scan (local repository)
strix --target ./app-directory --scan-mode standard
# Focused testing with custom instructions
strix --target api.your-app.com --instruction "Focus on business logic flaws and IDOR vulnerabilities"
# Provide detailed instructions through file (e.g., rules of engagement, scope, exclusions)
strix --target api.your-app.com --instruction-file ./instruction.md
# Force PR diff-scope against a specific base branch
strix -n --target ./ --scan-mode quick --scope-mode diff --diff-base origin/main
```
See the [CLI reference](https://docs.strix.ai/usage/cli) for every option, including scan modes, diff scope, instruction files, and budgets.
### Headless Mode
Run Strix programmatically without interactive UI using the `-n/--non-interactive` flag - perfect for servers and automated jobs. The CLI prints real-time vulnerability findings and the final report before exiting. Exits with non-zero code when vulnerabilities are found.
@@ -287,9 +259,9 @@ jobs:
```
> [!TIP]
> In CI pull request runs, Strix automatically scopes quick reviews to changed files.
> If diff-scope cannot resolve, ensure checkout uses full history (`fetch-depth: 0`) or pass
> `--diff-base` explicitly.
> In CI pull request runs, Strix automatically scopes quick reviews to changed files, which is why the
> checkout above fetches full history. See the
> [CI/CD documentation](https://docs.strix.ai/integrations/github-actions) for the details.
### Configuration
@@ -300,140 +272,43 @@ export LLM_API_KEY="your-api-key"
# Optional
export LLM_API_BASE="your-api-base-url" # if using a local model, e.g. Ollama, LMStudio
export PERPLEXITY_API_KEY="your-api-key" # for search capabilities
export STRIX_REASONING_EFFORT="high" # control thinking effort (default: high, quick scan: medium)
```
> [!NOTE]
> Strix automatically saves your configuration to `~/.strix/cli-config.json`, so you don't have to re-enter it on every run.
> See the [configuration reference](https://docs.strix.ai/advanced/configuration) for every environment variable.
#### Sign in with a ChatGPT subscription
Instead of a metered API key, you can run Strix on your ChatGPT Plus/Pro subscription:
```bash
strix auth login chatgpt # sign in with your ChatGPT account
strix auth login chatgpt # sign in with your ChatGPT account
export STRIX_LLM="chatgpt/gpt-5.4" # chatgpt/<model> runs on the subscription
strix --target ./app-directory
strix auth status # show the active sign-in
strix auth logout # forget the sign-in
strix auth status # show the active sign-in, or logout to forget it
```
#### Use the managed platform: `strix cloud`
The `strix cloud` commands drive the managed platform ([app.strix.ai](https://app.strix.ai)) from the terminal. Sign in once with the device flow. The sign-in creates your account and workspace on first use and stores a personal API token in `~/.strix/platform-auth.json`:
Run scans on [app.strix.ai](https://app.strix.ai) from the terminal, without Docker or an LLM key:
```bash
strix cloud login # browser approval, then workspace + scope profile
strix cloud login --workspace "My Team" # select a workspace by name or ID
strix cloud whoami # fast local account/workspace status
strix cloud session # verify remote session + consent ceiling
strix cloud logout # revoke remotely, then remove locally
```
The default **Recommended** scope preset supports normal scan work, local source uploads,
workspace switching, and user-approved credit top-ups. It excludes credential creation;
request `tokens:write` explicitly (or choose Full) when needed. For strict least privilege, pass an explicit list such as
`--scopes scans:read scans:write uploads:write billing:read`. Named automation
profiles are also available with `--scope-profile minimal|recommended|full`.
Every operation of the [REST API](https://docs.app.strix.ai) has a matching command in the form `strix cloud <resource> <verb>`:
```bash
strix cloud # list all resources
strix cloud scans # run the safe default (`scans list`)
strix cloud scans help # list the verbs of a resource
strix cloud domains add --domain example.com --asset-type web_app
strix cloud login # browser sign-in, one credential per install
strix cloud scans start --source . --yes --wait # scan local code, approving the upload
strix cloud scans start --engagement-type live_test --domain-ids <uuid> --wait
strix cloud scans start --source . --dry-run --show-files --json # review + capture source.archive_sha256
SOURCE_SHA256="<reviewed source.archive_sha256>"
strix cloud scans start --source . --approve-sha256 "$SOURCE_SHA256" --wait
strix cloud vulns list --severity critical
strix cloud credits # credit balance
strix cloud billing topup --credits 20 --yes # explicitly approve agent payment after HTTP 402
```
Workspaces and account setup also work from the terminal:
Every [REST API](https://docs.app.strix.ai) operation has a matching `strix cloud <resource> <verb>` command. Run `strix cloud` to list the resources, and add `help` to a resource to list its verbs. Output is JSON when stdout is not a terminal or when you pass `--json`. Binary downloads are the exception: redirect the raw bytes, or combine `--output FILE --json` for download metadata.
```bash
strix cloud workspaces list # numbered list; `workspace` is also accepted
strix cloud workspaces create --name "My Team" # admin + organizations:write
strix cloud workspaces use 2 # switch by list number, exact name, or ID
strix cloud session scopes # granted scopes + login ceiling
strix cloud session scopes set minimal # narrow without another browser sign-in
strix cloud billing subscribe --plan strix_cloud # opens the hosted checkout page
strix cloud billing portal # opens the billing portal
strix cloud integrations install github # opens the app installation page
strix cloud domains verify <domain-id> # prints the DNS record to add
```
The last four commands end at a person. Strix creates the link, opens the browser for an interactive terminal, and always prints the URL. The user enters the card, approves the installation, or adds the DNS record. Pass `--no-browser` to print the URL only.
The commands work for humans and agents: terminal output favors names, branches, lifecycle states, and numbered selectors, while redirected output (or `--json`) preserves complete machine-readable records and IDs. Human lists retain the selectors needed by follow-up commands but omit internal organization/user IDs; a selector too long for the compact table is repeated losslessly in a copyable block. Paginated lists print the next `--page` or `--offset`, and detail views preserve useful prose within a safe terminal bound; use `--json` for the complete record. Token lists distinguish API keys from named CLI device sessions. Binary downloads are the exception: intentionally redirect their raw bytes, or use `--output FILE --json` to write the file and receive structured download metadata. There are no prompts when stdin is not a terminal. Exit codes: `0` success, `1` error, `2` invalid usage, `4` authentication or plan limit, `5` payment required. `--token` and `STRIX_API_TOKEN` are stateless per-command overrides and never replace the stored sign-in; pair a CLI-session override with `--workspace-id` or `STRIX_WORKSPACE_ID`.
A browser sign-in creates one reusable credential per CLI installation. Logging in again on the
same installation replaces its secret instead of accumulating keys. Workspace switches keep that
credential and expiry, preserve the server-side scope preference, cap access by the target role,
and can never exceed the login consent ceiling. Each process pins its starting workspace, so a
concurrent switch fails safely instead of sending a stale command to another organization.
`strix cloud logout` revokes the server session before deleting the local token; use
`--local-only` only when you deliberately cannot reach the server.
Write commands take request fields as flags, and every write command also accepts one JSON object with `--data`:
```bash
strix cloud scans start --data '{"engagement_type":"code_review"}' # literal JSON
strix cloud scans start --data @request.json # read a file
cat request.json | strix cloud scans start --data - # read standard input
```
For an agent or CI local-source scan, run `--dry-run --show-files --json`, review the manifest,
and capture `source.archive_sha256`. Rerun with the same `--source`, every `--exclude`, and any
`--include-*` selection flags, replacing `--dry-run` with `--approve-sha256 HASH`; Strix
rebuilds the archive and refuses to upload it if the digest changed. `--yes` instead approves
only the snapshot built in that one invocation. It is suitable for a deliberate human or
one-shot approval, not as a digest-bound two-step agent/CI handoff.
The safe default honors `.gitignore` and `.strixignore` and excludes hidden paths, secret-like
files, VCS metadata, dependencies/build output, symlinks, and nested archives. Opt in
separately with `--include-hidden`, `--include-sensitive`, or `--include-archives`. The client
caps a bundle at 20,000 files, 25 MiB per file, 250 MiB expanded, and 50 MiB compressed, and
the service independently validates the archive. Source alone infers a code review; adding a
domain infers a live test. You can always pass `--engagement-type` explicitly.
Strix removes the temporary local archive after every invocation. It deletes a staged remote
upload after a definitive scan rejection. If a network error, `5xx` response, malformed
success response, or interruption makes the launch outcome ambiguous, it retains the upload and reports its `upload_id` with
`launch_outcome_unknown: true`; if automatic deletion cannot be confirmed, it reports the ID
with `cleanup_unknown: true`. Check `strix cloud scans list` before retrying. If no scan is
linked to the retained upload, delete it with `strix cloud uploads delete UPLOAD_ID`.
Non-Enterprise scans consume the deterministic estimate shown for their scope (a source-only
code review at the default `ultra` tier currently starts at 60 credits). Enterprise scans are
plan-included and do not consume the credit wallet. Report downloads need Enterprise,
schedules need Pro, and billing writes need an admin token. Plan blocks exit `4`; an
insufficient credit wallet exits `5` without creating or charging a scan.
Enable native tab completion once per shell session:
```bash
source <(strix completions zsh) # use bash instead of zsh when appropriate
strix completions fish | source
```
See the [cloud CLI documentation](https://docs.strix.ai/cloud/cli) for scopes, workspaces, billing, and source-upload options.
#### Connect your own MCP servers
Strix can connect to Model Context Protocol (MCP) servers you list and expose their tools to the agent during a run. Create `~/.strix/mcp-servers.json` with a JSON list of servers. Each entry is either a local `stdio` server that Strix launches as a subprocess, or a remote `http` server:
Strix can connect to Model Context Protocol (MCP) servers you list and expose their tools to the agent during a run. Create `~/.strix/mcp-servers.json` with a JSON list of local `stdio` servers or remote `http` servers:
```json
[
{
"name": "local_fs",
"transport": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
},
{
"name": "github",
"transport": "http",
@@ -444,7 +319,7 @@ Strix can connect to Model Context Protocol (MCP) servers you list and expose th
]
```
Each server's tools are namespaced by `name` (for example `local_fs_read_file`). Omit `allowed_tools` to expose every tool the server offers, or set it to a list to restrict which tools the agent can call. The file is optional, and a server that fails to connect is skipped without failing the run. You can point Strix at a different file with `STRIX_MCP_CONFIG`.
Each server's tools are namespaced by `name`, for example `github_list_issues`. See the [MCP documentation](https://docs.strix.ai/integrations/mcp) for the full schema, tool filtering, and `stdio` servers.
**Recommended models for best results:**

103
docs/cloud/cli.mdx Normal file
View File

@@ -0,0 +1,103 @@
---
title: "Cloud CLI"
description: "Drive app.strix.ai from the terminal with strix cloud"
---
The `strix cloud` commands drive the managed platform ([app.strix.ai](https://app.strix.ai)) from the terminal. You do not need Docker or an LLM key.
## Sign In
Sign in once with the browser device flow. The sign-in creates your account and workspace on first use, and it stores a personal API token in `~/.strix/platform-auth.json`.
```bash
strix cloud login # browser approval, then workspace and scope profile
strix cloud login --workspace "My Team" # select a workspace by name or ID
strix cloud whoami # local account and workspace status
strix cloud session # verify the remote session and consent ceiling
strix cloud logout # revoke remotely, then remove the local token
```
A browser sign-in creates one reusable credential for each CLI installation. A second sign-in on the same installation replaces the secret instead of adding another key. `strix cloud logout` revokes the server session before it deletes the local token. Use `--local-only` when you cannot reach the server.
## Scopes
The default **Recommended** preset covers normal scan work, local source uploads, workspace switching, and user-approved credit top-ups. It excludes credential creation, so request `tokens:write` when you need it.
```bash
strix cloud login --scopes scans:read scans:write uploads:write billing:read
strix cloud login --scope-profile minimal # also accepts recommended or full
strix cloud session scopes # granted scopes and the login ceiling
strix cloud session scopes set minimal # narrow without another browser sign-in
```
A workspace switch keeps the credential and its expiry, preserves the server-side scope preference, and caps access by the target role. A switch can never exceed the login consent ceiling. Each process pins the workspace it started with, so a concurrent switch fails safely instead of sending a stale command to another organization.
## Commands
Every operation of the [REST API](https://docs.app.strix.ai) has a matching command in the form `strix cloud <resource> <verb>`.
```bash
strix cloud # list all resources
strix cloud scans # run the safe default (scans list)
strix cloud scans help # list the verbs of a resource
strix cloud domains add --domain example.com --asset-type web_app
strix cloud scans start --engagement-type live_test --domain-ids <uuid> --wait
strix cloud vulns list --severity critical
strix cloud credits # credit balance
```
Write commands take request fields as flags. Every write command also accepts one JSON object with `--data`:
```bash
strix cloud scans start --data '{"engagement_type":"code_review"}' # literal JSON
strix cloud scans start --data @request.json # read a file
cat request.json | strix cloud scans start --data - # read standard input
```
`--token` and `STRIX_API_TOKEN` are stateless overrides for a single command, and they never replace the stored sign-in. Pair a CLI-session override with `--workspace-id` or `STRIX_WORKSPACE_ID`.
## Workspaces And Account Setup
```bash
strix cloud workspaces list # numbered list; workspace is also accepted
strix cloud workspaces create --name "My Team" # needs admin and organizations:write
strix cloud workspaces use 2 # switch by list number, exact name, or ID
strix cloud billing topup --credits 20 --yes # approve an agent payment after HTTP 402
strix cloud billing subscribe --plan strix_cloud # opens the hosted checkout page
strix cloud billing portal # opens the billing portal
strix cloud integrations install github # opens the app installation page
strix cloud domains verify <domain-id> # prints the DNS record to add
```
The last four commands end at a person. Strix creates the link, opens the browser for an interactive terminal, and always prints the URL. The user enters the card, approves the installation, or adds the DNS record. Pass `--no-browser` to print the URL only.
## Output And Exit Codes
The commands work for people and for agents. Terminal output favors names, branches, lifecycle states, and numbered selectors. Redirected output, and `--json`, preserve the complete machine-readable record.
- Human lists keep the selectors that follow-up commands need, and they omit internal organization and user IDs. A selector that is too long for the compact table is repeated losslessly in a copyable block.
- Paginated lists print the next `--page` or `--offset`. Detail views keep useful prose within a safe terminal bound, so use `--json` for the complete record.
- Token lists separate API keys from named CLI device sessions.
- Binary downloads are the exception to JSON output. Redirect the raw bytes on purpose, or use `--output FILE --json` to write the file and receive structured download metadata.
- There are no prompts when stdin is not a terminal.
Exit codes: `0` success, `1` error, `2` invalid usage, `4` authentication or plan limit, `5` payment required.
## Credits And Plan Limits
Non-Enterprise scans consume the deterministic estimate shown for their scope. A source-only code review at the default `ultra` tier currently starts at 60 credits. Enterprise scans are plan-included and do not consume the credit wallet.
Report downloads need Enterprise, schedules need Pro, and billing writes need an admin token. A plan block exits `4`. An insufficient credit wallet exits `5` without the creation of a scan and without a charge.
## Local Source Scans
See [Scan Local Source](/cloud/overview#scan-local-source) for the upload approval flow, the exclusion rules, and the size limits.
## Tab Completion
Enable native tab completion once for each shell session:
```bash
source <(strix completions zsh) # use bash instead of zsh when appropriate
strix completions fish | source
```

View File

@@ -25,7 +25,8 @@
"pages": [
"usage/cli",
"usage/scan-modes",
"usage/instructions"
"usage/instructions",
"usage/viewer"
]
},
{
@@ -77,7 +78,8 @@
{
"group": "Strix Cloud",
"pages": [
"cloud/overview"
"cloud/overview",
"cloud/cli"
]
}
]

49
docs/usage/viewer.mdx Normal file
View File

@@ -0,0 +1,49 @@
---
title: "Local Web Viewer"
description: "Browse a run in a local dashboard with strix view"
---
Every scan writes its results to disk as it runs. `strix view` serves those files in a local dashboard, for a live run or a finished one.
```bash
strix view # the most recent run
strix view my-run-name # a specific run under ./strix_runs
strix view --host 0.0.0.0 --port 8080 --no-open
```
The UI ships prebuilt with Strix, so there is no extra install and no JavaScript build step. The dashboard reads the run files straight off disk. Nothing leaves your machine, and you do not need a cloud account.
## Options
<ParamField path="run" type="string">
Run name under `./strix_runs`. Defaults to the most recent run.
</ParamField>
<ParamField path="--host" type="string" default="127.0.0.1">
Host to bind to. Use `0.0.0.0` to reach the viewer from other machines.
</ParamField>
<ParamField path="--port" type="number" default="0">
Port to serve on. The default selects an available ephemeral port.
</ParamField>
<ParamField path="--no-open" type="boolean">
Do not open the browser automatically.
</ParamField>
## What Is In The Dashboard
- **Overview** — run status, target, and a severity breakdown of everything found so far.
- **Vulnerabilities** — each validated finding with its severity, details, and reproduction steps.
- **Agent graph** — a live map of the multi-agent team, and what each agent is doing.
- **Steering** — send instructions to a live scan to redirect the agents during the run. Steering works only in the dashboard the running scan opens. A standalone `strix view` has no live scan to steer.
- **History** — browse past runs on this machine and move between them. Verify your email address in the dashboard to unlock the other runs.
- **Reports** — generate a shareable report and send it by email. Verify your email address first.
## Sharing The Link
<Warning>
The token in the printed URL grants access to the run data, and to the steering of a live scan. Share it only with trusted users.
</Warning>
To reach the viewer from another machine, start it with `--host 0.0.0.0` and replace `0.0.0.0` in the printed URL with a reachable IP address or hostname. Restrict the port with your firewall. A request without the token-derived session cannot read run data.

View File

@@ -10,11 +10,13 @@ from typing import TYPE_CHECKING, Any
from pydantic import AliasChoices, BaseModel
from strix.config.settings import Settings
from strix.config.settings import LlmSettings, Settings
from strix.utils.secret_files import write_secret_text
if TYPE_CHECKING:
from collections.abc import Mapping
from pydantic.fields import FieldInfo
@@ -25,6 +27,11 @@ _DEFAULT_PATH: Path = Path.home() / ".strix" / "cli-config.json"
_override: Path | None = None
_cached: Settings | None = None
# Model, API key, and API base describe one provider connection. When the shell
# changes any of them, the stored values of the others no longer belong together
# and are dropped rather than mixed with the new value.
_LINKED_LLM_FIELDS = ("model", "api_key", "api_base")
def load_settings() -> Settings:
"""Resolve settings from env + JSON file + defaults. Memoized.
@@ -54,22 +61,31 @@ def apply_config_override(path: Path) -> None:
def persist_current() -> None:
"""Write currently-set env vars to the active config file (0o600)."""
"""Merge currently-set env vars into the active config file (0o600).
Values already in the file survive when their env var is unset, so a
run that gets its settings from the file does not erase them. An env
var set to the empty string clears the field from the file. A change to
any linked LLM connection var drops the whole stored connection first.
"""
s = load_settings()
target = _override or _DEFAULT_PATH
target.parent.mkdir(parents=True, exist_ok=True)
env_block: dict[str, str] = {}
for sub_name in s.model_fields:
env_block = _drop_stale_llm_connection(_read_env_block(target))
for sub_name in type(s).model_fields:
sub_model = getattr(s, sub_name)
if not isinstance(sub_model, BaseModel):
continue
for finfo in type(sub_model).model_fields.values():
for alias in _aliases_for(finfo):
value = os.environ.get(alias.upper())
if value:
env_block[alias.upper()] = value
break
aliases = [alias.upper() for alias in _aliases_for(finfo)]
active = next((alias for alias in aliases if alias in os.environ), None)
if active is None:
continue
for alias in aliases:
env_block.pop(alias, None)
if os.environ[active]:
env_block[active] = os.environ[active]
write_secret_text(target, json.dumps({"env": env_block}, indent=2))
@@ -93,17 +109,9 @@ def _read_json_overrides(path: Path) -> dict[str, dict[str, Any]]:
Only includes keys whose env var is NOT already set, so env always
wins over the persisted file.
"""
if not path.exists():
env_block_upper = _drop_stale_llm_connection(_read_env_block(path))
if not env_block_upper:
return {}
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return {}
env_block = data.get("env", {}) if isinstance(data, dict) else {}
if not isinstance(env_block, dict):
return {}
env_block_upper = {str(k).upper(): v for k, v in env_block.items()}
env_present = {k.upper() for k in os.environ}
nested: dict[str, dict[str, Any]] = {}
@@ -123,3 +131,38 @@ def _read_json_overrides(path: Path) -> dict[str, dict[str, Any]]:
if sub_data:
nested[sub_name] = sub_data
return nested
def _first_alias_value(aliases: list[str], source: Mapping[str, Any]) -> Any | None:
return next((source[alias] for alias in aliases if alias in source), None)
def _drop_stale_llm_connection(env_block: dict[str, Any]) -> dict[str, Any]:
"""Remove every linked LLM var from ``env_block`` if the shell changed any of them."""
linked_aliases = [
[alias.upper() for alias in _aliases_for(LlmSettings.model_fields[name])]
for name in _LINKED_LLM_FIELDS
]
changed = any(
(env_value := _first_alias_value(aliases, os.environ)) is not None
and env_value != _first_alias_value(aliases, env_block)
for aliases in linked_aliases
)
if not changed:
return env_block
stale = {alias for aliases in linked_aliases for alias in aliases}
return {k: v for k, v in env_block.items() if k not in stale}
def _read_env_block(path: Path) -> dict[str, Any]:
"""Return the ``env`` block stored in ``path`` with upper-cased keys, or ``{}``."""
if not path.exists():
return {}
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return {}
env_block = data.get("env", {}) if isinstance(data, dict) else {}
if not isinstance(env_block, dict):
return {}
return {str(k).upper(): v for k, v in env_block.items()}

View File

@@ -208,6 +208,191 @@ def test_persist_current_writes_env_block(tmp_path: Path, monkeypatch: pytest.Mo
}
def test_persist_current_keeps_file_values_when_env_is_unset(tmp_path: Path) -> None:
target = tmp_path / "cli-config.json"
target.write_text(
json.dumps({"env": {"STRIX_LLM": "file-model", "LLM_API_KEY": "file-key"}}),
encoding="utf-8",
)
loader.apply_config_override(target)
assert loader.load_settings().llm.model == "file-model"
loader.persist_current()
assert json.loads(target.read_text(encoding="utf-8")) == {
"env": {"STRIX_LLM": "file-model", "LLM_API_KEY": "file-key"}
}
def test_persist_current_env_overrides_file_value(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
target = tmp_path / "cli-config.json"
target.write_text(
json.dumps({"env": {"STRIX_LLM": "file-model", "PERPLEXITY_API_KEY": "file-pplx"}}),
encoding="utf-8",
)
loader.apply_config_override(target)
monkeypatch.setenv("PERPLEXITY_API_KEY", "env-pplx")
loader.persist_current()
assert json.loads(target.read_text(encoding="utf-8")) == {
"env": {"STRIX_LLM": "file-model", "PERPLEXITY_API_KEY": "env-pplx"}
}
def test_linked_llm_model_change_drops_stored_key_and_base(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
target = tmp_path / "cli-config.json"
target.write_text(
json.dumps(
{
"env": {
"STRIX_LLM": "file-model",
"LLM_API_KEY": "file-key",
"LLM_API_BASE": "http://file-base",
"PERPLEXITY_API_KEY": "pplx",
}
}
),
encoding="utf-8",
)
loader.apply_config_override(target)
monkeypatch.setenv("STRIX_LLM", "env-model")
llm = loader.load_settings().llm
assert llm.model == "env-model"
assert llm.api_key is None
assert llm.api_base is None
loader.persist_current()
assert json.loads(target.read_text(encoding="utf-8")) == {
"env": {"STRIX_LLM": "env-model", "PERPLEXITY_API_KEY": "pplx"}
}
def test_linked_llm_key_change_drops_stored_model(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
target = tmp_path / "cli-config.json"
target.write_text(
json.dumps({"env": {"STRIX_LLM": "file-model", "LLM_API_KEY": "file-key"}}),
encoding="utf-8",
)
loader.apply_config_override(target)
monkeypatch.setenv("LLM_API_KEY", "new-key")
assert loader.load_settings().llm.model is None
loader.persist_current()
assert json.loads(target.read_text(encoding="utf-8")) == {"env": {"LLM_API_KEY": "new-key"}}
def test_linked_llm_secondary_alias_in_env_is_not_a_change(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
target = tmp_path / "cli-config.json"
target.write_text(
json.dumps({"env": {"STRIX_LLM": "file-model", "LLM_API_KEY": "file-key"}}),
encoding="utf-8",
)
loader.apply_config_override(target)
monkeypatch.setenv("LLM_API_KEY", "file-key")
monkeypatch.setenv("OPENAI_API_KEY", "unrelated-global-key")
llm = loader.load_settings().llm
assert llm.model == "file-model"
assert llm.api_key == "file-key"
loader.persist_current()
assert json.loads(target.read_text(encoding="utf-8")) == {
"env": {"STRIX_LLM": "file-model", "LLM_API_KEY": "file-key"}
}
def test_linked_llm_unchanged_env_keeps_stored_key(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
target = tmp_path / "cli-config.json"
target.write_text(
json.dumps({"env": {"STRIX_LLM": "file-model", "LLM_API_KEY": "file-key"}}),
encoding="utf-8",
)
loader.apply_config_override(target)
monkeypatch.setenv("STRIX_LLM", "file-model")
assert loader.load_settings().llm.api_key == "file-key"
loader.persist_current()
assert json.loads(target.read_text(encoding="utf-8")) == {
"env": {"STRIX_LLM": "file-model", "LLM_API_KEY": "file-key"}
}
def test_persist_current_env_alias_replaces_other_alias_in_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
target = tmp_path / "cli-config.json"
target.write_text(json.dumps({"env": {"OPENAI_API_KEY": "old-key"}}), encoding="utf-8")
loader.apply_config_override(target)
monkeypatch.setenv("LLM_API_KEY", "new-key")
loader.persist_current()
assert json.loads(target.read_text(encoding="utf-8")) == {"env": {"LLM_API_KEY": "new-key"}}
def test_persist_current_empty_env_clears_file_value(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
target = tmp_path / "cli-config.json"
target.write_text(
json.dumps({"env": {"STRIX_LLM": "file-model", "PERPLEXITY_API_KEY": "pplx"}}),
encoding="utf-8",
)
loader.apply_config_override(target)
monkeypatch.setenv("PERPLEXITY_API_KEY", "")
loader.persist_current()
assert json.loads(target.read_text(encoding="utf-8")) == {"env": {"STRIX_LLM": "file-model"}}
def test_persist_current_empty_primary_alias_does_not_save_sibling(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
target = tmp_path / "cli-config.json"
target.write_text(json.dumps({"env": {"PERPLEXITY_API_KEY": "pplx"}}), encoding="utf-8")
loader.apply_config_override(target)
monkeypatch.setenv("LLM_API_KEY", "")
monkeypatch.setenv("OPENAI_API_KEY", "sibling-key")
assert loader.load_settings().llm.api_key == ""
loader.persist_current()
assert json.loads(target.read_text(encoding="utf-8")) == {"env": {"PERPLEXITY_API_KEY": "pplx"}}
def test_persist_current_replaces_corrupt_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
target = tmp_path / "cli-config.json"
target.write_text("{not json", encoding="utf-8")
loader.apply_config_override(target)
monkeypatch.setenv("STRIX_LLM", "env-model")
loader.persist_current()
assert json.loads(target.read_text(encoding="utf-8")) == {"env": {"STRIX_LLM": "env-model"}}
def test_persist_current_sets_0600_mode(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("STRIX_LLM", "persisted-model")
target = tmp_path / "cli-config.json"

View File

@@ -114,7 +114,14 @@ def test_config_file_loads_dedupe_model(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
for key in ("STRIX_LLM", "STRIX_DEDUPE_MODEL", "STRIX_DEDUPE_REASONING_EFFORT"):
for key in (
"STRIX_LLM",
"LLM_API_KEY",
"OPENAI_API_KEY",
"LLM_API_BASE",
"STRIX_DEDUPE_MODEL",
"STRIX_DEDUPE_REASONING_EFFORT",
):
monkeypatch.delenv(key, raising=False)
path = tmp_path / "config.json"
path.write_text(